Chore: Refactor the packages/jaeger-ui-components/src/model folder to TS (#59233)

This commit is contained in:
Hamas Shafiq 2022-11-24 09:56:09 +00:00 committed by GitHub
parent 24ce1a8a0b
commit 2105e52138
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 56 additions and 42 deletions

View File

@ -14,12 +14,13 @@
import PathElem from './PathElem'; import PathElem from './PathElem';
import { simplePath } from './sample-paths.test.resources'; import { simplePath } from './sample-paths.test.resources';
import { TDdgOperation, TDdgPath, TDdgService } from './types';
describe('PathElem', () => { describe('PathElem', () => {
const getPath = () => { const getPath = () => {
const path = { const path = {
focalIdx: 2, focalIdx: 2,
}; } as TDdgPath;
const members = simplePath.map( const members = simplePath.map(
({ operation, service }, i) => ({ operation, service }, i) =>
new PathElem({ new PathElem({
@ -28,8 +29,8 @@ describe('PathElem', () => {
name: operation, name: operation,
service: { service: {
name: service, name: service,
}, } as TDdgService,
}, } as TDdgOperation,
path, path,
}) })
); );
@ -42,13 +43,13 @@ describe('PathElem', () => {
return path; return path;
}; };
const testMemberIdx = 3; const testMemberIdx = 3;
const testOperation = {}; const testOperation = {} as TDdgOperation;
const testPath = { const testPath = {
focalIdx: 4, focalIdx: 4,
members: ['member0', 'member1', 'member2', 'member3', 'member4', 'member5'], members: ['member0', 'member1', 'member2', 'member3', 'member4', 'member5'],
}; } as unknown as TDdgPath;
const testVisibilityIdx = 105; const testVisibilityIdx = 105;
let pathElem; let pathElem: PathElem;
beforeEach(() => { beforeEach(() => {
pathElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: testMemberIdx }); pathElem = new PathElem({ path: testPath, operation: testOperation, memberIdx: testMemberIdx });

View File

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
export const simplePayloadElemMaker = (label) => ({ export const simplePayloadElemMaker = (label: string) => ({
operation: `${label}Operation`, operation: `${label}Operation`,
service: `${label}Service`, service: `${label}Service`,
}); });
@ -24,9 +24,9 @@ const sameFocalServicePayloadElem = {
service: focalPayloadElem.service, service: focalPayloadElem.service,
}; };
const pathLengthener = (path) => { const pathLengthener = (path: Array<{ operation: string; service: string }>) => {
const prequels = []; const prequels: Array<{ operation: string; service: string }> = [];
const sequels = []; const sequels: Array<{ operation: string; service: string }> = [];
path.forEach(({ operation, service }) => { path.forEach(({ operation, service }) => {
if (operation !== focalPayloadElem.operation && service !== focalPayloadElem.service) { if (operation !== focalPayloadElem.operation && service !== focalPayloadElem.service) {
prequels.push({ prequels.push({
@ -115,7 +115,3 @@ export const generationPaths = [
], ],
[generationPayloadElems.target, generationPayloadElems.beforeFocalMid, focalPayloadElem], [generationPayloadElems.target, generationPayloadElems.beforeFocalMid, focalPayloadElem],
]; ];
export const wrap = (paths) => ({
dependencies: paths.map((path) => ({ path, attributes: [] })),
});

View File

@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
import { TraceSpan } from '../types/trace';
import { _getTraceNameImpl as getTraceName } from './trace-viewer'; import { _getTraceNameImpl as getTraceName } from './trace-viewer';
describe('getTraceName', () => { describe('getTraceName', () => {
@ -223,22 +225,22 @@ describe('getTraceName', () => {
const fullTraceName = `${serviceName}: ${operationName}`; const fullTraceName = `${serviceName}: ${operationName}`;
it('returns an empty string if given spans with no root among them', () => { it('returns an empty string if given spans with no root among them', () => {
expect(getTraceName(spansWithNoRoots)).toEqual(''); expect(getTraceName(spansWithNoRoots as TraceSpan[])).toEqual('');
}); });
it('returns an id of root span with the earliest startTime', () => { it('returns an id of root span with the earliest startTime', () => {
expect(getTraceName(spansWithMultipleRootsDifferentByStartTime)).toEqual(fullTraceName); expect(getTraceName(spansWithMultipleRootsDifferentByStartTime as TraceSpan[])).toEqual(fullTraceName);
}); });
it('returns an id of root span without any refs', () => { it('returns an id of root span without any refs', () => {
expect(getTraceName(spansWithMultipleRootsWithOneWithoutRefs)).toEqual(fullTraceName); expect(getTraceName(spansWithMultipleRootsWithOneWithoutRefs as unknown as TraceSpan[])).toEqual(fullTraceName);
}); });
it('returns an id of root span with remote ref', () => { it('returns an id of root span with remote ref', () => {
expect(getTraceName(spansWithOneRootWithRemoteRef)).toEqual(fullTraceName); expect(getTraceName(spansWithOneRootWithRemoteRef as TraceSpan[])).toEqual(fullTraceName);
}); });
it('returns an id of root span with no refs', () => { it('returns an id of root span with no refs', () => {
expect(getTraceName(spansWithOneRootWithNoRefs)).toEqual(fullTraceName); expect(getTraceName(spansWithOneRootWithNoRefs as unknown as TraceSpan[])).toEqual(fullTraceName);
}); });
}); });

View File

@ -12,12 +12,15 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
import { Trace, TraceLink, TraceSpan } from '../types/trace';
import { import {
processTemplate, processTemplate,
createTestFunction, createTestFunction,
getParameterInArray, getParameterInArray,
getParameterInAncestor, getParameterInAncestor,
processLinkPattern, processLinkPattern,
ProcessedLinkPattern,
computeLinks, computeLinks,
createGetLinks, createGetLinks,
computeTraceLink, computeTraceLink,
@ -64,7 +67,8 @@ describe('processTemplate()', () => {
expect(() => expect(() =>
processTemplate( processTemplate(
{ {
template: (data) => `a${data.b}c`, /* eslint-disable @typescript-eslint/no-explicit-any */
template: (data: { [key: string]: any }) => `a${data.b}c`,
}, },
(a) => a (a) => a
) )
@ -243,21 +247,28 @@ describe('getParameterInAncestor()', () => {
}, },
tags: [{ key: 'a', value: 'a0' }], tags: [{ key: 'a', value: 'a0' }],
}, },
]; ] as TraceSpan[];
spans[1].references = [ spans[1].references = [
{ {
spanID: 's1',
traceID: 't2',
refType: 'CHILD_OF', refType: 'CHILD_OF',
span: spans[0], span: spans[0],
}, },
]; ];
spans[2].references = [ spans[2].references = [
{ {
spanID: 's1',
traceID: 't2',
refType: 'CHILD_OF', refType: 'CHILD_OF',
span: spans[0], span: spans[0],
}, },
]; ];
spans[3].references = [ spans[3].references = [
{ {
spanID: 's1',
traceID: 't2',
refType: 'CHILD_OF', refType: 'CHILD_OF',
span: spans[2], span: spans[2],
}, },
@ -311,7 +322,7 @@ describe('getParameterInAncestor()', () => {
depth: 0, depth: 0,
process: {}, process: {},
}, },
]; ] as TraceSpan[];
expect(getParameterInAncestor('a', spansWithUndefinedTags[0])).toBeUndefined(); expect(getParameterInAncestor('a', spansWithUndefinedTags[0])).toBeUndefined();
}); });
}); });
@ -328,7 +339,7 @@ describe('computeTraceLink()', () => {
url: 'http://example.com/?myKey=#{traceID}&myKey=#{myKey}', url: 'http://example.com/?myKey=#{traceID}&myKey=#{myKey}',
text: 'second link (#{myKey})', text: 'second link (#{myKey})',
}, },
].map(processLinkPattern); ].map(processLinkPattern) as ProcessedLinkPattern[];
const trace = { const trace = {
processes: [], processes: [],
@ -338,7 +349,7 @@ describe('computeTraceLink()', () => {
endTime: 2000, endTime: 2000,
duration: 1000, duration: 1000,
services: [], services: [],
}; } as unknown as Trace;
it('correctly computes links', () => { it('correctly computes links', () => {
expect(computeTraceLink(linkPatterns, trace)).toEqual([ expect(computeTraceLink(linkPatterns, trace)).toEqual([
@ -363,14 +374,16 @@ describe('computeLinks()', () => {
url: 'http://example.com/?myKey=#{myOtherKey}&myKey=#{myKey}', url: 'http://example.com/?myKey=#{myOtherKey}&myKey=#{myKey}',
text: 'second link (#{myOtherKey})', text: 'second link (#{myOtherKey})',
}, },
].map(processLinkPattern); ].map(processLinkPattern) as ProcessedLinkPattern[];
const spans = [ const spans = [
{ depth: 0, process: {}, tags: [{ key: 'myKey', value: 'valueOfMyKey' }] }, { depth: 0, process: {}, tags: [{ key: 'myKey', value: 'valueOfMyKey' }] },
{ depth: 1, process: {}, logs: [{ fields: [{ key: 'myOtherKey', value: 'valueOfMy+Other+Key' }] }] }, { depth: 1, process: {}, logs: [{ fields: [{ key: 'myOtherKey', value: 'valueOfMy+Other+Key' }] }] },
]; ] as unknown as TraceSpan[];
spans[1].references = [ spans[1].references = [
{ {
spanID: 's1',
traceID: 't2',
refType: 'CHILD_OF', refType: 'CHILD_OF',
span: spans[0], span: spans[0],
}, },
@ -399,12 +412,13 @@ describe('getLinks()', () => {
url: 'http://example.com/?mySpecialKey=#{mySpecialKey}', url: 'http://example.com/?mySpecialKey=#{mySpecialKey}',
text: 'special key link (#{mySpecialKey})', text: 'special key link (#{mySpecialKey})',
}, },
].map(processLinkPattern); ].map(processLinkPattern) as ProcessedLinkPattern[];
const template = jest.spyOn(linkPatterns[0].url, 'template'); const template = jest.spyOn(linkPatterns[0]!.url, 'template');
const span = { depth: 0, process: {}, tags: [{ key: 'mySpecialKey', value: 'valueOfMyKey' }] }; const span = { depth: 0, process: {}, tags: [{ key: 'mySpecialKey', value: 'valueOfMyKey' }] } as TraceSpan;
let cache; /* eslint-disable @typescript-eslint/no-explicit-any */
let cache: WeakMap<object, any>;
beforeEach(() => { beforeEach(() => {
cache = new WeakMap(); cache = new WeakMap();
@ -419,7 +433,7 @@ describe('getLinks()', () => {
}); });
it('returns the result from the cache', () => { it('returns the result from the cache', () => {
const result = []; const result: TraceLink[] = [];
cache.set(span.tags[0], result); cache.set(span.tags[0], result);
const getLinks = createGetLinks(linkPatterns, cache); const getLinks = createGetLinks(linkPatterns, cache);
expect(getLinks(span, span.tags, 0)).toBe(result); expect(getLinks(span, span.tags, 0)).toBe(result);

View File

@ -28,7 +28,7 @@ type ProcessedTemplate = {
template: (template: { [key: string]: any }) => string; template: (template: { [key: string]: any }) => string;
}; };
type ProcessedLinkPattern = { export type ProcessedLinkPattern = {
object: any; object: any;
type: (link: string) => boolean; type: (link: string) => boolean;
key: (link: string) => boolean; key: (link: string) => boolean;
@ -74,7 +74,7 @@ export function processTemplate(template: unknown, encodeFn: (unencoded: any) =>
}; };
} }
export function createTestFunction(entry: any) { export function createTestFunction(entry?: any) {
if (typeof entry === 'string') { if (typeof entry === 'string') {
return (arg: unknown) => arg === entry; return (arg: unknown) => arg === entry;
} }
@ -100,7 +100,7 @@ export function createTestFunction(entry: any) {
const identity = (a: any): typeof a => a; const identity = (a: any): typeof a => a;
export function processLinkPattern(pattern: any): ProcessedLinkPattern | TNil { export function processLinkPattern(pattern: any): ProcessedLinkPattern | null {
try { try {
const url = processTemplate(pattern.url, encodeURIComponent); const url = processTemplate(pattern.url, encodeURIComponent);
const text = processTemplate(pattern.text, identity); const text = processTemplate(pattern.text, identity);
@ -120,7 +120,7 @@ export function processLinkPattern(pattern: any): ProcessedLinkPattern | TNil {
} }
} }
export function getParameterInArray(name: string, array: TraceKeyValuePair[]) { export function getParameterInArray(name: string, array?: TraceKeyValuePair[] | TNil) {
if (array) { if (array) {
return array.find((entry) => entry.key === name); return array.find((entry) => entry.key === name);
} }
@ -150,10 +150,10 @@ export function computeTraceLink(linkPatterns: ProcessedLinkPattern[], trace: Tr
); );
linkPatterns linkPatterns
.filter((pattern) => pattern.type('traces')) ?.filter((pattern) => pattern?.type('traces'))
.forEach((pattern) => { .forEach((pattern) => {
const parameterValues: Record<string, any> = {}; const parameterValues: Record<string, any> = {};
const allParameters = pattern.parameters.every((parameter) => { const allParameters = pattern?.parameters.every((parameter) => {
const key = parameter as keyof Trace; const key = parameter as keyof Trace;
if (validKeys.includes(key)) { if (validKeys.includes(key)) {
// At this point is safe to access to trace object using parameter variable because // At this point is safe to access to trace object using parameter variable because

View File

@ -11,6 +11,7 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
import { TraceResponse } from '../types/trace';
import transformTraceData, { orderTags, deduplicateTags } from './transform-trace-data'; import transformTraceData, { orderTags, deduplicateTags } from './transform-trace-data';
@ -136,7 +137,7 @@ describe('transformTraceData()', () => {
traceID: undefined, traceID: undefined,
processes, processes,
spans, spans,
}; } as unknown as TraceResponse;
expect(transformTraceData(traceData)).toEqual(null); expect(transformTraceData(traceData)).toEqual(null);
}); });
@ -146,9 +147,9 @@ describe('transformTraceData()', () => {
traceID, traceID,
processes, processes,
spans: [...spans, rootSpanWithMissingRef], spans: [...spans, rootSpanWithMissingRef],
}; } as unknown as TraceResponse;
expect(transformTraceData(traceData).traceName).toEqual(`${serviceName}: ${rootOperationName}`); expect(transformTraceData(traceData)!.traceName).toEqual(`${serviceName}: ${rootOperationName}`);
}); });
it('should return trace data with correct traceName based on root span without any refs', () => { it('should return trace data with correct traceName based on root span without any refs', () => {
@ -156,8 +157,8 @@ describe('transformTraceData()', () => {
traceID, traceID,
processes, processes,
spans: [...spans, rootSpanWithoutRefs], spans: [...spans, rootSpanWithoutRefs],
}; } as unknown as TraceResponse;
expect(transformTraceData(traceData).traceName).toEqual(`${serviceName}: ${rootOperationName}`); expect(transformTraceData(traceData)!.traceName).toEqual(`${serviceName}: ${rootOperationName}`);
}); });
}); });