-
Notifications
You must be signed in to change notification settings - Fork 370
feat(otel): add useLinksInsteadOfParent option to HatchetInstrumentor #3804
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
purva-8
wants to merge
3
commits into
hatchet-dev:main
Choose a base branch
from
purva-8:feat/otel-span-links-fire-and-forget
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+323
−21
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,270 @@ | ||
| /** | ||
| * Tests for HatchetInstrumentor.useLinksInsteadOfParent option. | ||
| * | ||
| * Verifies that fire-and-forget child runs use OTel span links instead of | ||
| * parent-child relationships when the predicate returns true, while | ||
| * preserving the default parent-child behaviour when it returns false. | ||
| */ | ||
|
|
||
| // Minimal OTel span mock | ||
| const makeMockSpan = () => ({ | ||
| end: jest.fn(), | ||
| recordException: jest.fn(), | ||
| setStatus: jest.fn(), | ||
| spanContext: jest.fn(() => ({ | ||
| traceId: 'a'.repeat(32), | ||
| spanId: 'b'.repeat(16), | ||
| traceFlags: 1, | ||
| })), | ||
| }); | ||
|
|
||
| // Build a mock tracer whose startActiveSpan captures its arguments. | ||
| const makeTracerMock = (span = makeMockSpan()) => { | ||
| const calls: IArguments[] = []; | ||
| const tracer = { | ||
| _calls: calls, | ||
| _span: span, | ||
| startActiveSpan: jest.fn(function (...args: unknown[]) { | ||
| // The last argument is always the callback (fn). | ||
| const fn = args[args.length - 1] as (span: unknown) => unknown; | ||
| return fn(span); | ||
| }), | ||
| }; | ||
| return tracer; | ||
| }; | ||
|
|
||
| // Dummy action used in all tests. | ||
| const makeAction = (actionId = 'my-worker:my-task') => ({ | ||
| actionId, | ||
| tenantId: 'tenant-1', | ||
| workflowRunId: 'run-1', | ||
| taskId: 'task-1', | ||
| taskRunExternalId: 'ext-1', | ||
| retryCount: 0, | ||
| parentWorkflowRunId: undefined, | ||
| childWorkflowIndex: undefined, | ||
| childWorkflowKey: undefined, | ||
| actionPayload: '{}', | ||
| jobName: 'my-task', | ||
| taskName: 'my-task', | ||
| workflowId: 'wf-1', | ||
| workflowVersionId: 'wfv-1', | ||
| // Encode a fake traceparent in the metadata so extractContext finds a valid context. | ||
| additionalMetadata: JSON.stringify({ | ||
| traceparent: '00-' + 'a'.repeat(32) + '-' + 'b'.repeat(16) + '-01', | ||
| }), | ||
| }); | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Shared setup: mock @opentelemetry/api and @opentelemetry/instrumentation so | ||
| // HatchetInstrumentor can be imported without a real OTel SDK being present. | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| jest.mock('@opentelemetry/api', () => { | ||
| const validSpanCtx = { | ||
| traceId: 'a'.repeat(32), | ||
| spanId: 'b'.repeat(16), | ||
| traceFlags: 1, | ||
| }; | ||
|
|
||
| // SpanKind.CONSUMER = 4, SpanStatusCode.OK = 1, SpanStatusCode.ERROR = 2 | ||
| return { | ||
| SpanKind: { INTERNAL: 0, SERVER: 1, CLIENT: 2, PRODUCER: 3, CONSUMER: 4 }, | ||
| SpanStatusCode: { UNSET: 0, OK: 1, ERROR: 2 }, | ||
| context: { | ||
| active: jest.fn(() => ({})), | ||
| with: jest.fn((_ctx: unknown, fn: () => unknown) => fn()), | ||
| }, | ||
| propagation: { | ||
| extract: jest.fn(() => ({ _extracted: true })), | ||
| inject: jest.fn(), | ||
| }, | ||
| trace: { | ||
| getSpanContext: jest.fn(() => validSpanCtx), | ||
| isSpanContextValid: jest.fn(() => true), | ||
| }, | ||
| diag: { | ||
| debug: jest.fn(), | ||
| info: jest.fn(), | ||
| warn: jest.fn(), | ||
| error: jest.fn(), | ||
| }, | ||
| }; | ||
| }); | ||
|
|
||
| jest.mock('@opentelemetry/instrumentation', () => { | ||
| class InstrumentationBase { | ||
| protected tracer: ReturnType<typeof makeTracerMock>; | ||
| protected config: Record<string, unknown>; | ||
| constructor(_name: string, _version: string, config: Record<string, unknown>) { | ||
| this.config = config; | ||
| this.tracer = makeTracerMock(); | ||
| } | ||
| getConfig() { | ||
| return this.config; | ||
| } | ||
| setConfig(cfg: Record<string, unknown>) { | ||
| this.config = cfg; | ||
| } | ||
| protected _wrap( | ||
| proto: Record<string, unknown>, | ||
| method: string, | ||
| wrapper: (orig: unknown) => unknown | ||
| ) { | ||
| proto[method] = wrapper(proto[method]); | ||
| } | ||
| protected _unwrap(proto: Record<string, unknown>, method: string) { | ||
| // no-op in tests | ||
| } | ||
| } | ||
|
|
||
| return { | ||
| InstrumentationBase, | ||
| InstrumentationNodeModuleDefinition: jest.fn(() => ({})), | ||
| InstrumentationNodeModuleFile: jest.fn(() => ({})), | ||
| isWrapped: jest.fn(() => false), | ||
| }; | ||
| }); | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Import the instrumentor AFTER mocks are set up. | ||
| // --------------------------------------------------------------------------- | ||
| import { HatchetInstrumentor } from './instrumentor'; | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Helpers | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| function buildWorkerProto(action = makeAction()) { | ||
| const proto = { | ||
| workerId: 'worker-1', | ||
| handleStartStepRun: jest.fn().mockResolvedValue(undefined), | ||
| }; | ||
| return proto; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the `startActiveSpan` call arguments for the `hatchet.start_step_run` span. | ||
| * startActiveSpan is overloaded: | ||
| * (name, opts, context, fn) → parent-child mode (fn is 4th arg, index 3) | ||
| * (name, opts, fn) → link mode (fn is 3rd arg, index 2) | ||
| */ | ||
| function getStartStepRunArgs(tracer: ReturnType<typeof makeTracerMock>) { | ||
| const call = (tracer.startActiveSpan as jest.Mock).mock.calls.find( | ||
| ([name]: [string]) => typeof name === 'string' && name.startsWith('hatchet.start_step_run') | ||
| ); | ||
| expect(call).toBeDefined(); | ||
| return call as unknown[]; | ||
| } | ||
|
|
||
| // --------------------------------------------------------------------------- | ||
| // Tests | ||
| // --------------------------------------------------------------------------- | ||
|
|
||
| describe('HatchetInstrumentor.useLinksInsteadOfParent', () => { | ||
| it('uses parent-child semantics by default (no option provided)', async () => { | ||
| const instrumentor = new HatchetInstrumentor({}); | ||
| const tracer = (instrumentor as unknown as { tracer: ReturnType<typeof makeTracerMock> }).tracer; | ||
| tracer.startActiveSpan = makeTracerMock()._span | ||
| ? jest.fn((...args: unknown[]) => { | ||
| const fn = args[args.length - 1] as (span: unknown) => unknown; | ||
| return fn(makeMockSpan()); | ||
| }) | ||
| : tracer.startActiveSpan; | ||
|
purva-8 marked this conversation as resolved.
|
||
|
|
||
| const proto = buildWorkerProto(); | ||
| (instrumentor as unknown as { patchWorker: (e: unknown) => void }).patchWorker({ | ||
| InternalWorker: { prototype: proto }, | ||
| }); | ||
|
|
||
| await proto.handleStartStepRun(makeAction()); | ||
|
|
||
| const args = getStartStepRunArgs(tracer); | ||
| // 4 args → (name, opts, parentContext, fn) | ||
| expect(args).toHaveLength(4); | ||
| // opts should NOT include links | ||
| const opts = args[1] as Record<string, unknown>; | ||
| expect(opts.links).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('uses parent-child semantics when predicate returns false', async () => { | ||
| const instrumentor = new HatchetInstrumentor({ | ||
| useLinksInsteadOfParent: () => false, | ||
| }); | ||
| const tracer = (instrumentor as unknown as { tracer: ReturnType<typeof makeTracerMock> }).tracer; | ||
|
|
||
| const proto = buildWorkerProto(); | ||
| (instrumentor as unknown as { patchWorker: (e: unknown) => void }).patchWorker({ | ||
| InternalWorker: { prototype: proto }, | ||
| }); | ||
|
|
||
| await proto.handleStartStepRun(makeAction()); | ||
|
|
||
| const args = getStartStepRunArgs(tracer); | ||
| expect(args).toHaveLength(4); | ||
| const opts = args[1] as Record<string, unknown>; | ||
| expect(opts.links).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('uses span links and no parent context when predicate returns true', async () => { | ||
| const instrumentor = new HatchetInstrumentor({ | ||
| useLinksInsteadOfParent: () => true, | ||
| }); | ||
| const tracer = (instrumentor as unknown as { tracer: ReturnType<typeof makeTracerMock> }).tracer; | ||
|
|
||
| const proto = buildWorkerProto(); | ||
| (instrumentor as unknown as { patchWorker: (e: unknown) => void }).patchWorker({ | ||
| InternalWorker: { prototype: proto }, | ||
| }); | ||
|
|
||
| await proto.handleStartStepRun(makeAction()); | ||
|
|
||
| const args = getStartStepRunArgs(tracer); | ||
| // 3 args → (name, opts, fn) — no parent context | ||
| expect(args).toHaveLength(3); | ||
| const opts = args[1] as Record<string, unknown>; | ||
| expect(Array.isArray(opts.links)).toBe(true); | ||
| expect((opts.links as unknown[]).length).toBe(1); | ||
| }); | ||
|
|
||
| it('passes the actionId to the predicate', async () => { | ||
| const predicate = jest.fn(() => false); | ||
| const action = makeAction('custom-worker:custom-task'); | ||
|
|
||
| const instrumentor = new HatchetInstrumentor({ | ||
| useLinksInsteadOfParent: predicate, | ||
| }); | ||
|
|
||
| const proto = buildWorkerProto(action); | ||
| (instrumentor as unknown as { patchWorker: (e: unknown) => void }).patchWorker({ | ||
| InternalWorker: { prototype: proto }, | ||
| }); | ||
|
|
||
| await proto.handleStartStepRun(action); | ||
|
|
||
| expect(predicate).toHaveBeenCalledWith('custom-worker:custom-task'); | ||
| }); | ||
|
|
||
| it('falls back to no links when parent span context is invalid', async () => { | ||
| const otelApi = require('@opentelemetry/api'); | ||
| jest.spyOn(otelApi.trace, 'isSpanContextValid').mockReturnValueOnce(false); | ||
|
|
||
| const instrumentor = new HatchetInstrumentor({ | ||
| useLinksInsteadOfParent: () => true, | ||
| }); | ||
| const tracer = (instrumentor as unknown as { tracer: ReturnType<typeof makeTracerMock> }).tracer; | ||
|
|
||
| const proto = buildWorkerProto(); | ||
| (instrumentor as unknown as { patchWorker: (e: unknown) => void }).patchWorker({ | ||
| InternalWorker: { prototype: proto }, | ||
| }); | ||
|
|
||
| await proto.handleStartStepRun(makeAction()); | ||
|
|
||
| const args = getStartStepRunArgs(tracer); | ||
| // Still 3 args (link mode path), but links array is empty | ||
| expect(args).toHaveLength(3); | ||
| const opts = args[1] as Record<string, unknown>; | ||
| expect((opts.links as unknown[]).length).toBe(0); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.