@quantumbpm/sdk 0.0.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +6 -0
  2. package/dist/bpmn.d.ts +35 -2
  3. package/dist/bpmn.js +10 -5
  4. package/dist/dmn.d.ts +5 -0
  5. package/dist/dmn.js +3 -1
  6. package/dist/generated/index.d.ts +5 -3
  7. package/dist/generated/index.js +4 -4
  8. package/dist/generated/models/BatchEvaluateDesignRequest.d.ts +3 -2
  9. package/dist/generated/models/BatchEvaluateDesignRequest.js +1 -1
  10. package/dist/generated/models/BpmnIncidentRecord.d.ts +88 -0
  11. package/dist/generated/models/BpmnIncidentRecord.js +23 -0
  12. package/dist/generated/models/BpmnIncidentRecordPaginatedResponse.d.ts +9 -0
  13. package/dist/generated/models/BpmnIncidentRecordPaginatedResponse.js +3 -0
  14. package/dist/generated/models/BpmnInstance.d.ts +24 -0
  15. package/dist/generated/models/BpmnInstance.js +1 -1
  16. package/dist/generated/models/BpmnInstanceState.d.ts +28 -5
  17. package/dist/generated/models/BpmnInstanceState.js +1 -1
  18. package/dist/generated/models/BpmnProcessVersion.d.ts +16 -0
  19. package/dist/generated/models/BpmnProcessVersion.js +1 -1
  20. package/dist/generated/models/EvaluateStoredRequest.d.ts +4 -0
  21. package/dist/generated/models/EvaluateStoredRequest.js +1 -1
  22. package/dist/generated/models/Execution.d.ts +4 -0
  23. package/dist/generated/models/Execution.js +1 -1
  24. package/dist/generated/models/ExternalJob.d.ts +8 -0
  25. package/dist/generated/models/ExternalJob.js +1 -1
  26. package/dist/generated/models/FeelNumber.d.ts +1 -1
  27. package/dist/generated/models/FeelNumber.js +1 -1
  28. package/dist/generated/models/StartBpmnInstanceRequest.d.ts +4 -0
  29. package/dist/generated/models/StartBpmnInstanceRequest.js +1 -1
  30. package/dist/generated/models/StartBpmnTestInstanceRequest.d.ts +4 -0
  31. package/dist/generated/models/StartBpmnTestInstanceRequest.js +1 -1
  32. package/dist/generated/models/SuspendBpmnDefinitionRequest.d.ts +6 -0
  33. package/dist/generated/models/SuspendBpmnDefinitionRequest.js +3 -0
  34. package/dist/generated/models/SuspendBpmnInstanceRequest.d.ts +9 -0
  35. package/dist/generated/models/SuspendBpmnInstanceRequest.js +3 -0
  36. package/dist/generated/models/SuspensionEntry.d.ts +22 -0
  37. package/dist/generated/models/SuspensionEntry.js +3 -0
  38. package/dist/generated/models/UserTask.d.ts +4 -0
  39. package/dist/generated/models/UserTask.js +1 -1
  40. package/dist/generated/services/BpmnService.d.ts +177 -22
  41. package/dist/generated/services/BpmnService.js +189 -28
  42. package/dist/generated/services/DefaultService.d.ts +33 -12
  43. package/dist/generated/services/DefaultService.js +37 -16
  44. package/dist/tracing.d.ts +17 -0
  45. package/dist/tracing.js +38 -0
  46. package/dist/workers.d.ts +25 -2
  47. package/dist/workers.js +53 -6
  48. package/package.json +2 -1
  49. package/src/bpmn.ts +46 -2
  50. package/src/dmn.ts +7 -0
  51. package/src/generated/index.ts +5 -3
  52. package/src/generated/models/BatchEvaluateDesignRequest.ts +3 -2
  53. package/src/generated/models/BpmnIncidentRecord.ts +93 -0
  54. package/src/generated/models/BpmnIncidentRecordPaginatedResponse.ts +14 -0
  55. package/src/generated/models/BpmnInstance.ts +24 -0
  56. package/src/generated/models/BpmnInstanceState.ts +28 -5
  57. package/src/generated/models/BpmnProcessVersion.ts +16 -0
  58. package/src/generated/models/EvaluateStoredRequest.ts +4 -0
  59. package/src/generated/models/Execution.ts +4 -0
  60. package/src/generated/models/ExternalJob.ts +8 -0
  61. package/src/generated/models/FeelNumber.ts +1 -1
  62. package/src/generated/models/StartBpmnInstanceRequest.ts +4 -0
  63. package/src/generated/models/StartBpmnTestInstanceRequest.ts +4 -0
  64. package/src/generated/models/SuspendBpmnDefinitionRequest.ts +11 -0
  65. package/src/generated/models/SuspendBpmnInstanceRequest.ts +14 -0
  66. package/src/generated/models/SuspensionEntry.ts +27 -0
  67. package/src/generated/models/UserTask.ts +4 -0
  68. package/src/generated/services/BpmnService.ts +265 -30
  69. package/src/generated/services/DefaultService.ts +48 -13
  70. package/src/index.test.ts +180 -0
  71. package/src/tracing.ts +49 -0
  72. package/src/workers.test.ts +117 -0
  73. package/src/workers.ts +75 -7
  74. package/dist/generated/models/BpmnActivityState.d.ts +0 -52
  75. package/dist/generated/models/BpmnActivityState.js +0 -17
  76. package/dist/generated/models/ExternalJobActiveWorkersItem.d.ts +0 -7
  77. package/dist/generated/models/ExternalJobActiveWorkersItem.js +0 -3
  78. package/dist/generated/models/ExternalJobActiveWorkersResponse.d.ts +0 -7
  79. package/dist/generated/models/ExternalJobActiveWorkersResponse.js +0 -3
  80. package/src/generated/models/BpmnActivityState.ts +0 -57
  81. package/src/generated/models/ExternalJobActiveWorkersItem.ts +0 -12
  82. package/src/generated/models/ExternalJobActiveWorkersResponse.ts +0 -12
@@ -26,19 +26,6 @@ import type { CancelablePromise } from '../core/CancelablePromise';
26
26
  import type { BaseHttpRequest } from '../core/BaseHttpRequest';
27
27
  export class DefaultService {
28
28
  constructor(public readonly httpRequest: BaseHttpRequest) {}
29
- /**
30
- * Health Check
31
- * @returns any OK
32
- * @throws ApiError
33
- */
34
- public getHealth(): CancelablePromise<{
35
- status?: string;
36
- }> {
37
- return this.httpRequest.request({
38
- method: 'GET',
39
- url: '/health',
40
- });
41
- }
42
29
  /**
43
30
  * Version
44
31
  * @returns any OK
@@ -531,6 +518,7 @@ export class DefaultService {
531
518
  * @param definitionId
532
519
  * @param definitionsId Filter by DMN `<definitions id>` (XML id).
533
520
  * @param startDate Filter executions after this date (ISO 8601)
521
+ * @param businessId Exact-match filter on the caller-supplied correlation key.
534
522
  * @param page Page number (1-indexed)
535
523
  * @param pageSize Number of items per page (max 100)
536
524
  * @returns PaginatedExecutionsResponse OK
@@ -541,6 +529,7 @@ export class DefaultService {
541
529
  definitionId: string,
542
530
  definitionsId?: string,
543
531
  startDate?: string,
532
+ businessId?: string,
544
533
  page: number = 1,
545
534
  pageSize: number = 20,
546
535
  ): CancelablePromise<PaginatedExecutionsResponse> {
@@ -554,6 +543,7 @@ export class DefaultService {
554
543
  query: {
555
544
  'definitionsID': definitionsId,
556
545
  'startDate': startDate,
546
+ 'businessId': businessId,
557
547
  'page': page,
558
548
  'pageSize': pageSize,
559
549
  },
@@ -604,6 +594,7 @@ export class DefaultService {
604
594
  * Returns paginated execution history for the entire project, optionally filtered by DMN definition.
605
595
  * @param projectId
606
596
  * @param definitionsId Filter by DMN `<definitions id>` (XML id).
597
+ * @param businessId Exact-match filter on the caller-supplied correlation key.
607
598
  * @param page Page number (1-indexed)
608
599
  * @param pageSize Number of items per page (max 100)
609
600
  * @returns PaginatedExecutionsResponse OK
@@ -612,6 +603,7 @@ export class DefaultService {
612
603
  public listProjectExecutions(
613
604
  projectId: string,
614
605
  definitionsId?: string,
606
+ businessId?: string,
615
607
  page: number = 1,
616
608
  pageSize: number = 20,
617
609
  ): CancelablePromise<PaginatedExecutionsResponse> {
@@ -623,6 +615,7 @@ export class DefaultService {
623
615
  },
624
616
  query: {
625
617
  'definitionsID': definitionsId,
618
+ 'businessId': businessId,
626
619
  'page': page,
627
620
  'pageSize': pageSize,
628
621
  },
@@ -665,6 +658,23 @@ export class DefaultService {
665
658
  * @param projectId
666
659
  * @param definitionId
667
660
  * @param status
661
+ * @param hasIncident Filter by whether the instance has at least one unresolved incident.
662
+ * Omit to return all instances regardless of incident status; pass
663
+ * `true` to show only instances that need operator attention; pass
664
+ * `false` to exclude blocked instances.
665
+ *
666
+ * @param suspended Filter by instance-scope suspension. `true` → only instances with
667
+ * `suspendedAt` set; `false` → only running-and-not-paused. Omit for
668
+ * no filter. Does not consider definition-scope suspension; for a
669
+ * full "is this instance making progress?" view, callers should
670
+ * additionally join against the parent definition.
671
+ *
672
+ * @param createdAfter Only return instances created at or after this timestamp. Strongly
673
+ * recommended for monitoring views — terminal-state instance rows
674
+ * accumulate indefinitely, and unfiltered queries grow linearly with
675
+ * that history.
676
+ *
677
+ * @param businessId Exact-match filter on the caller-supplied correlation key set at start time.
668
678
  * @param page
669
679
  * @param pageSize
670
680
  * @returns BpmnInstancePaginatedResponse OK
@@ -674,6 +684,10 @@ export class DefaultService {
674
684
  projectId: string,
675
685
  definitionId?: string,
676
686
  status?: 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELED',
687
+ hasIncident?: boolean,
688
+ suspended?: boolean,
689
+ createdAfter?: string,
690
+ businessId?: string,
677
691
  page?: number,
678
692
  pageSize?: number,
679
693
  ): CancelablePromise<BpmnInstancePaginatedResponse> {
@@ -686,6 +700,10 @@ export class DefaultService {
686
700
  query: {
687
701
  'definitionID': definitionId,
688
702
  'status': status,
703
+ 'hasIncident': hasIncident,
704
+ 'suspended': suspended,
705
+ 'createdAfter': createdAfter,
706
+ 'businessId': businessId,
689
707
  'page': page,
690
708
  'pageSize': pageSize,
691
709
  },
@@ -719,6 +737,11 @@ export class DefaultService {
719
737
  },
720
738
  body: requestBody,
721
739
  mediaType: 'application/json',
740
+ errors: {
741
+ 400: `Bad Request`,
742
+ 401: `Unauthorized`,
743
+ 500: `Internal Server Error`,
744
+ },
722
745
  });
723
746
  }
724
747
  /**
@@ -782,6 +805,7 @@ export class DefaultService {
782
805
  * @param taskType Filter jobs by task type
783
806
  * @param status Filter jobs by status
784
807
  * @param workflowId Filter jobs by workflow ID
808
+ * @param businessId Exact-match filter on the caller-supplied correlation key.
785
809
  * @param createdAfter Only return jobs created at or after this timestamp. Strongly
786
810
  * recommended for monitoring views — completed-job records accumulate
787
811
  * indefinitely, and unfiltered queries grow linearly with that history.
@@ -796,6 +820,7 @@ export class DefaultService {
796
820
  taskType?: string,
797
821
  status?: 'PENDING' | 'COMPLETED' | 'FAILED' | 'CANCELED',
798
822
  workflowId?: string,
823
+ businessId?: string,
799
824
  createdAfter?: string,
800
825
  page?: number,
801
826
  pageSize?: number,
@@ -810,6 +835,7 @@ export class DefaultService {
810
835
  'taskType': taskType,
811
836
  'status': status,
812
837
  'workflowID': workflowId,
838
+ 'businessId': businessId,
813
839
  'createdAfter': createdAfter,
814
840
  'page': page,
815
841
  'pageSize': pageSize,
@@ -902,6 +928,15 @@ export class DefaultService {
902
928
  * Workflow ID returned by the poll response.
903
929
  */
904
930
  workflowID: string;
931
+ /**
932
+ * Optional worker identity (the same `clientID` used to poll).
933
+ * When supplied, the completion is applied only if this worker
934
+ * still holds the job's lock; a stale worker whose lease lapsed
935
+ * and whose job a peer re-acquired is rejected as a no-op.
936
+ * Omit for the legacy unchecked behavior.
937
+ *
938
+ */
939
+ clientID?: string;
905
940
  variables?: Record<string, any>;
906
941
  },
907
942
  ): CancelablePromise<any> {
package/src/index.test.ts CHANGED
@@ -28,3 +28,183 @@ describe('public API surface', () => {
28
28
  expect(vars.lookup('amount')).toBe(1000);
29
29
  });
30
30
  });
31
+
32
+ describe('BpmnClient.listInstances argument ordering', () => {
33
+ test('forwards each option to its matching generated parameter', async () => {
34
+ const calls: unknown[][] = [];
35
+ const fakeRaw = {
36
+ default: {
37
+ listBpmnInstances: (...args: unknown[]) => {
38
+ calls.push(args);
39
+ return Promise.resolve({ data: [], totalCount: 0 });
40
+ },
41
+ },
42
+ } as never;
43
+ const projectId = '00000000-0000-0000-0000-000000000001';
44
+ const { BpmnClient } = await import('./bpmn');
45
+ const client = new BpmnClient(fakeRaw, projectId);
46
+
47
+ await client.listInstances({
48
+ definitionId: 'def-1',
49
+ status: 'RUNNING',
50
+ hasIncident: true,
51
+ suspended: false,
52
+ createdAfter: '2026-01-01T00:00:00Z',
53
+ businessId: 'ORDER-42',
54
+ page: 2,
55
+ pageSize: 10,
56
+ });
57
+
58
+ expect(calls).toHaveLength(1);
59
+ expect(calls[0]).toEqual([
60
+ projectId,
61
+ 'def-1',
62
+ 'RUNNING',
63
+ true,
64
+ false,
65
+ '2026-01-01T00:00:00Z',
66
+ 'ORDER-42',
67
+ 2,
68
+ 10,
69
+ ]);
70
+ });
71
+
72
+ test('omits unset options without sliding values into wrong slots', async () => {
73
+ const calls: unknown[][] = [];
74
+ const fakeRaw = {
75
+ default: {
76
+ listBpmnInstances: (...args: unknown[]) => {
77
+ calls.push(args);
78
+ return Promise.resolve({ data: [], totalCount: 0 });
79
+ },
80
+ },
81
+ } as never;
82
+ const projectId = '00000000-0000-0000-0000-000000000001';
83
+ const { BpmnClient } = await import('./bpmn');
84
+ const client = new BpmnClient(fakeRaw, projectId);
85
+
86
+ await client.listInstances({ page: 3 });
87
+
88
+ expect(calls[0]).toEqual([
89
+ projectId,
90
+ undefined,
91
+ undefined,
92
+ undefined,
93
+ undefined,
94
+ undefined,
95
+ undefined,
96
+ 3,
97
+ undefined,
98
+ ]);
99
+ });
100
+ });
101
+
102
+ describe('BpmnClient businessId threading', () => {
103
+ const projectId = '00000000-0000-0000-0000-000000000001';
104
+
105
+ test('startInstance forwards businessId in the request body', async () => {
106
+ const bodies: Array<Record<string, unknown>> = [];
107
+ const fakeRaw = {
108
+ default: {
109
+ startBpmnInstance: (_projectId: string, body: Record<string, unknown>) => {
110
+ bodies.push(body);
111
+ return Promise.resolve({ workflowID: 'wf-1' });
112
+ },
113
+ },
114
+ } as never;
115
+ const { BpmnClient } = await import('./bpmn');
116
+ const client = new BpmnClient(fakeRaw, projectId);
117
+
118
+ await client.startInstance('def-1', new Vars().set('amount', 100), { businessId: 'ORDER-42' });
119
+
120
+ expect(bodies[0]?.businessId).toBe('ORDER-42');
121
+ });
122
+
123
+ test('startInstance omits businessId when no option is passed', async () => {
124
+ const bodies: Array<Record<string, unknown>> = [];
125
+ const fakeRaw = {
126
+ default: {
127
+ startBpmnInstance: (_projectId: string, body: Record<string, unknown>) => {
128
+ bodies.push(body);
129
+ return Promise.resolve({ workflowID: 'wf-1' });
130
+ },
131
+ },
132
+ } as never;
133
+ const { BpmnClient } = await import('./bpmn');
134
+ const client = new BpmnClient(fakeRaw, projectId);
135
+
136
+ await client.startInstance('def-1', new Vars());
137
+
138
+ expect(bodies[0]?.businessId).toBeUndefined();
139
+ });
140
+
141
+ test('listUserTasks forwards businessId in positional argument 7', async () => {
142
+ const calls: unknown[][] = [];
143
+ const fakeRaw = {
144
+ bpmn: {
145
+ listBpmnUserTasks: (...args: unknown[]) => {
146
+ calls.push(args);
147
+ return Promise.resolve({ data: [], pagination: {} });
148
+ },
149
+ },
150
+ } as never;
151
+ const { BpmnClient } = await import('./bpmn');
152
+ const client = new BpmnClient(fakeRaw, projectId);
153
+
154
+ await client.listUserTasks({ businessId: 'ORDER-42' });
155
+
156
+ expect(calls[0]).toEqual([
157
+ projectId,
158
+ undefined,
159
+ undefined,
160
+ undefined,
161
+ undefined,
162
+ undefined,
163
+ 'ORDER-42',
164
+ undefined,
165
+ undefined,
166
+ ]);
167
+ });
168
+ });
169
+
170
+ describe('DmnClient businessId threading', () => {
171
+ const projectId = '00000000-0000-0000-0000-000000000001';
172
+
173
+ test('evaluate forwards businessId in the request body', async () => {
174
+ const bodies: Array<Record<string, unknown>> = [];
175
+ const fakeRaw = {
176
+ default: {
177
+ evaluateByDefinitionsId: (_pid: string, _did: string, body: Record<string, unknown>) => {
178
+ bodies.push(body);
179
+ return Promise.resolve({});
180
+ },
181
+ },
182
+ } as never;
183
+ const { DmnClient } = await import('./dmn');
184
+ const client = new DmnClient(fakeRaw, projectId);
185
+
186
+ await client.evaluate('def-1', new Vars(), { businessId: 'ORDER-42' });
187
+
188
+ expect(bodies[0]?.businessId).toBe('ORDER-42');
189
+ });
190
+
191
+ test('evaluateById forwards businessId in the request body', async () => {
192
+ const bodies: Array<Record<string, unknown>> = [];
193
+ const fakeRaw = {
194
+ default: {
195
+ evaluateStored: (_pid: string, _did: string, body: Record<string, unknown>) => {
196
+ bodies.push(body);
197
+ return Promise.resolve({});
198
+ },
199
+ },
200
+ } as never;
201
+ const { DmnClient } = await import('./dmn');
202
+ const client = new DmnClient(fakeRaw, projectId);
203
+
204
+ await client.evaluateById('11111111-1111-1111-1111-111111111111', new Vars(), {
205
+ businessId: 'ORDER-42',
206
+ });
207
+
208
+ expect(bodies[0]?.businessId).toBe('ORDER-42');
209
+ });
210
+ });
package/src/tracing.ts ADDED
@@ -0,0 +1,49 @@
1
+ import {
2
+ trace,
3
+ context,
4
+ propagation,
5
+ SpanKind,
6
+ type Span,
7
+ type Context,
8
+ type Attributes,
9
+ } from '@opentelemetry/api';
10
+
11
+ import { ExternalJob } from './generated/models/ExternalJob';
12
+
13
+ /**
14
+ * Continues the originating process instance's trace (when the polled job
15
+ * carries trace context) and opens a worker span for the handler. Returns the
16
+ * span plus a Context with the span set, so running the handler under
17
+ * `context.with(ctx, ...)` makes any OpenTelemetry-aware work nest beneath it.
18
+ *
19
+ * No-op unless the worker process has registered an OpenTelemetry SDK: the
20
+ * `@opentelemetry/api` globals default to no-ops, so a worker that doesn't opt
21
+ * into tracing pays nothing and a missing traceContext degrades to a fresh
22
+ * (unrecorded) span.
23
+ */
24
+ export function startJobSpan(raw: ExternalJob, taskType: string): { ctx: Context; span: Span } {
25
+ let parent = context.active();
26
+ if (raw.traceContext) {
27
+ parent = propagation.extract(parent, raw.traceContext);
28
+ }
29
+ const attributes: Attributes = {
30
+ 'bpmn.task_type': taskType,
31
+ 'bpmn.node_id': raw.nodeID,
32
+ 'bpmn.process_instance_id': raw.workflowID,
33
+ 'bpmn.execution_key': raw.executionKey,
34
+ };
35
+ if (raw.businessId) {
36
+ attributes['bpmn.business_id'] = raw.businessId;
37
+ }
38
+ // Resolve the tracer lazily (not at module load): the worker module is
39
+ // imported before the application registers an OpenTelemetry SDK, and with
40
+ // a duplicate @opentelemetry/api copy a module-load-time tracer binds to a
41
+ // proxy that never receives the delegate. Resolving here reads the
42
+ // globally-registered provider at dispatch time.
43
+ const span = trace.getTracer('quantumbpm/js-sdk').startSpan(
44
+ 'bpmn.external-task.execute',
45
+ { kind: SpanKind.CONSUMER, attributes },
46
+ parent,
47
+ );
48
+ return { ctx: trace.setSpan(parent, span), span };
49
+ }
@@ -0,0 +1,117 @@
1
+ import { Worker, Job } from './workers';
2
+ import { RawClient } from './generated/RawClient';
3
+ import { Vars } from './variables';
4
+ import type { ExternalJob } from './generated';
5
+
6
+ function makeWorker(maxBytes?: number) {
7
+ const warnings: string[] = [];
8
+ const logger = {
9
+ error: () => {},
10
+ warn: (msg: string) => { warnings.push(msg); },
11
+ };
12
+ const fakeRaw = {} as unknown as RawClient;
13
+ const w = new Worker(fakeRaw, '00000000-0000-0000-0000-000000000001', {
14
+ logger,
15
+ ...(maxBytes !== undefined ? { maxErrorMessageBytes: maxBytes } : {}),
16
+ });
17
+ return { w, warnings };
18
+ }
19
+
20
+ describe('Worker.clampWorkerErrorMessage', () => {
21
+ test('passes short messages through unchanged and does not warn', () => {
22
+ const { w, warnings } = makeWorker();
23
+ const out = w.clampWorkerErrorMessage('payment', 'boom');
24
+ expect(out).toBe('boom');
25
+ expect(warnings).toHaveLength(0);
26
+ });
27
+
28
+ test('truncates at the default 2048-byte cap and warns once', () => {
29
+ const { w, warnings } = makeWorker();
30
+ const huge = 'x'.repeat(100_000);
31
+ const out = w.clampWorkerErrorMessage('payment', huge);
32
+ expect(Buffer.byteLength(out, 'utf8')).toBeLessThanOrEqual(2048);
33
+ expect(out).toMatch(/ bytes\]$/);
34
+ expect(warnings).toHaveLength(1);
35
+ expect(warnings[0]).toContain('WORKER_ERROR message truncated');
36
+ });
37
+
38
+ test('honors a smaller per-worker override', () => {
39
+ const { w } = makeWorker(256);
40
+ const out = w.clampWorkerErrorMessage('payment', 'x'.repeat(10_000));
41
+ expect(Buffer.byteLength(out, 'utf8')).toBeLessThanOrEqual(256);
42
+ });
43
+
44
+ test('cuts on a UTF-8 code-point boundary', () => {
45
+ const { w } = makeWorker(200);
46
+ // "é" is 2 bytes UTF-8 → boundary cuts could otherwise split a rune.
47
+ const msg = 'é'.repeat(1000);
48
+ const out = w.clampWorkerErrorMessage('t', msg);
49
+ // Round-trip through Buffer should be lossless if we cut on a boundary.
50
+ expect(Buffer.from(out, 'utf8').toString('utf8')).toBe(out);
51
+ expect(out).not.toContain('�');
52
+ });
53
+ });
54
+
55
+ describe('Worker job dispatch', () => {
56
+ function setupForDispatch() {
57
+ const raw = {
58
+ default: {
59
+ heartbeatBpmnExternalJob: async () => {},
60
+ completeBpmnExternalJob: async () => {},
61
+ },
62
+ bpmn: {
63
+ throwBpmnExternalJobError: async () => {},
64
+ },
65
+ } as unknown as RawClient;
66
+ const w = new Worker(raw, '00000000-0000-0000-0000-000000000001', {
67
+ logger: { error: () => {}, warn: () => {} },
68
+ });
69
+ return w;
70
+ }
71
+
72
+ function makeRaw(businessId?: string): ExternalJob {
73
+ return {
74
+ id: '11111111-1111-1111-1111-111111111111',
75
+ executionKey: 'wf-1:node-a:1',
76
+ workflowID: 'wf-1',
77
+ nodeID: 'node-a',
78
+ taskType: 'payment',
79
+ status: 'PENDING',
80
+ createdAt: new Date().toISOString(),
81
+ ...(businessId !== undefined ? { businessId } : {}),
82
+ } as unknown as ExternalJob;
83
+ }
84
+
85
+ test('Job exposes businessId from the poll response', async () => {
86
+ const w = setupForDispatch();
87
+ let received: Job | undefined;
88
+ w.handle('payment', async (job) => {
89
+ received = job;
90
+ return new Vars();
91
+ });
92
+
93
+ const registration = (w as any).registrations.get('payment');
94
+ const ac = new AbortController();
95
+ await (w as any).dispatch(registration, makeRaw('ORDER-42'), ac.signal);
96
+
97
+ expect(received).toBeDefined();
98
+ expect(received!.businessId).toBe('ORDER-42');
99
+ expect(received!.raw.businessId).toBe('ORDER-42');
100
+ });
101
+
102
+ test('businessId is undefined when the poll response omits it', async () => {
103
+ const w = setupForDispatch();
104
+ let received: Job | undefined;
105
+ w.handle('payment', async (job) => {
106
+ received = job;
107
+ return new Vars();
108
+ });
109
+
110
+ const registration = (w as any).registrations.get('payment');
111
+ const ac = new AbortController();
112
+ await (w as any).dispatch(registration, makeRaw(), ac.signal);
113
+
114
+ expect(received).toBeDefined();
115
+ expect(received!.businessId).toBeUndefined();
116
+ });
117
+ });
package/src/workers.ts CHANGED
@@ -6,8 +6,11 @@
6
6
  */
7
7
  import { hostname } from 'os';
8
8
 
9
+ import { context as otelContext, SpanStatusCode } from '@opentelemetry/api';
10
+
9
11
  import { RawClient } from './generated/RawClient';
10
12
  import { ExternalJob } from './generated/models/ExternalJob';
13
+ import { startJobSpan } from './tracing';
11
14
 
12
15
  import { Vars } from './variables';
13
16
 
@@ -38,6 +41,12 @@ export interface Job<TVars = Record<string, unknown>> {
38
41
  typed: TVars;
39
42
  /** Static metadata attached at design time on the service task. */
40
43
  headers: Record<string, string>;
44
+ /**
45
+ * Caller-supplied correlation key inherited from the originating BPMN
46
+ * process. Undefined when the instance was started without one. Use it
47
+ * for log correlation or downstream tracing.
48
+ */
49
+ businessId?: string;
41
50
  /** Underlying generated record for low-level access. */
42
51
  raw: ExternalJob;
43
52
  }
@@ -45,9 +54,13 @@ export interface Job<TVars = Record<string, unknown>> {
45
54
  /**
46
55
  * Handler return value semantics:
47
56
  * - resolves with Vars (or undefined) → SDK calls Complete
48
- * - rejects with a BpmnError → SDK calls ThrowError with that code
57
+ * - rejects with a BpmnError → SDK calls ThrowError with that code as
58
+ * a business error (retryable=false):
59
+ * routed to a matching boundary error
60
+ * event immediately, bypassing retries
49
61
  * - rejects with anything else → SDK calls ThrowError with WORKER_ERROR
50
- * and decrements the retry budget
62
+ * as a retryable technical failure; the
63
+ * retry budget is consumed first
51
64
  */
52
65
  export type Handler<TVars = Record<string, unknown>> = (
53
66
  job: Job<TVars>,
@@ -72,6 +85,12 @@ export interface WorkerConfig {
72
85
  clientId?: string;
73
86
  /** Optional logger. Defaults to console. */
74
87
  logger?: { error(msg: string, ...args: unknown[]): void; warn(msg: string, ...args: unknown[]): void };
88
+ /**
89
+ * Cap on the byte length of the auto-built WORKER_ERROR message attached
90
+ * when a handler rejects with something other than a BpmnError. Default
91
+ * 2048. User-thrown BpmnError variables are not clamped.
92
+ */
93
+ maxErrorMessageBytes?: number;
75
94
  }
76
95
 
77
96
  interface Registration {
@@ -87,6 +106,7 @@ const DEFAULT_OPTIONS: Required<HandleOptions> = {
87
106
  };
88
107
 
89
108
  const POLL_ERROR_BACKOFF_MS = 2_000;
109
+ const DEFAULT_MAX_ERROR_MESSAGE_BYTES = 2048;
90
110
 
91
111
  /**
92
112
  * Worker is a long-poll runtime owning a set of handlers, one per task type.
@@ -95,6 +115,7 @@ export class Worker {
95
115
  private readonly registrations = new Map<string, Registration>();
96
116
  private readonly clientId: string;
97
117
  private readonly logger: NonNullable<WorkerConfig['logger']>;
118
+ private readonly maxErrorMessageBytes: number;
98
119
 
99
120
  constructor(
100
121
  private readonly raw: RawClient,
@@ -103,6 +124,10 @@ export class Worker {
103
124
  ) {
104
125
  this.clientId = config.clientId ?? `worker-${hostname()}-${process.pid}`;
105
126
  this.logger = config.logger ?? console;
127
+ this.maxErrorMessageBytes =
128
+ config.maxErrorMessageBytes && config.maxErrorMessageBytes > 0
129
+ ? config.maxErrorMessageBytes
130
+ : DEFAULT_MAX_ERROR_MESSAGE_BYTES;
106
131
  }
107
132
 
108
133
  /**
@@ -190,21 +215,37 @@ export class Worker {
190
215
  vars,
191
216
  typed: vars.toRecord(),
192
217
  headers: raw.headers ?? {},
218
+ businessId: raw.businessId,
193
219
  raw,
194
220
  };
195
221
 
222
+ const { ctx: spanCtx, span } = startJobSpan(raw, r.taskType);
223
+
196
224
  try {
197
- const result = await r.handler(job, ac.signal);
198
- await this.complete(raw, result ?? new Vars());
225
+ // Run the handler (and the success-path complete) under the span so
226
+ // the user's own OpenTelemetry work nests beneath it.
227
+ await otelContext.with(spanCtx, async () => {
228
+ const result = await r.handler(job, ac.signal);
229
+ await this.complete(raw, result ?? new Vars());
230
+ });
199
231
  } catch (err) {
200
232
  if (err instanceof BpmnError) {
201
- await this.throwError(raw, err.code, err.variables ?? new Vars());
233
+ span.setAttribute('bpmn.error_code', err.code);
234
+ // Business outcome: route to the boundary immediately
235
+ // (retryable=false), bypassing the retry budget.
236
+ await this.throwError(raw, err.code, err.variables ?? new Vars(), false);
202
237
  } else {
203
238
  this.logger.error(`workers: handler ${r.taskType}`, err);
204
239
  const message = err instanceof Error ? err.message : String(err);
205
- await this.throwError(raw, 'WORKER_ERROR', new Vars().set('error', message));
240
+ if (err instanceof Error) span.recordException(err);
241
+ span.setStatus({ code: SpanStatusCode.ERROR, message });
242
+ const clamped = this.clampWorkerErrorMessage(r.taskType, message);
243
+ // Technical failure: retryable, so the server consumes the
244
+ // retry budget before surfacing it.
245
+ await this.throwError(raw, 'WORKER_ERROR', new Vars().set('error', clamped), true);
206
246
  }
207
247
  } finally {
248
+ span.end();
208
249
  clearInterval(heartbeatTimer);
209
250
  parentSignal.removeEventListener('abort', onAbort);
210
251
  ac.abort();
@@ -232,6 +273,7 @@ export class Worker {
232
273
  try {
233
274
  await this.raw.default.completeBpmnExternalJob(this.projectId, job.executionKey, {
234
275
  workflowID: job.workflowID,
276
+ clientID: this.clientId,
235
277
  variables: vars.toWireMap() as any,
236
278
  });
237
279
  } catch (err) {
@@ -239,16 +281,42 @@ export class Worker {
239
281
  }
240
282
  }
241
283
 
242
- private async throwError(job: ExternalJob, code: string, vars: Vars): Promise<void> {
284
+ private async throwError(job: ExternalJob, code: string, vars: Vars, retryable: boolean): Promise<void> {
243
285
  try {
244
286
  await this.raw.bpmn.throwBpmnExternalJobError(this.projectId, job.executionKey, {
245
287
  errorCode: code,
288
+ clientID: this.clientId,
289
+ retryable,
246
290
  variables: vars.toWireMap() as any,
247
291
  });
248
292
  } catch (err) {
249
293
  this.logger.error(`workers: throwError ${job.executionKey}`, err);
250
294
  }
251
295
  }
296
+
297
+ /**
298
+ * Shortens an unhandled handler exception's message to the configured
299
+ * byte budget. UTF-8 safe (cuts on code-point boundary). Logs a WARN
300
+ * and appends a truncation marker when it triggers. Visible to tests.
301
+ */
302
+ clampWorkerErrorMessage(taskType: string, msg: string): string {
303
+ const limit = this.maxErrorMessageBytes;
304
+ const encoder = new TextEncoder();
305
+ const bytes = encoder.encode(msg);
306
+ if (limit <= 0 || bytes.length <= limit) {
307
+ return msg;
308
+ }
309
+ const marker = `…[truncated, original ${bytes.length} bytes]`;
310
+ const markerBytes = encoder.encode(marker).length;
311
+ const budget = Math.max(0, limit - markerBytes);
312
+ // Cut on a code-point boundary so we never emit half a multi-byte rune.
313
+ const slice = bytes.subarray(0, budget);
314
+ const decoded = new TextDecoder('utf-8', { fatal: false }).decode(slice).replace(/�+$/, '');
315
+ this.logger.warn(
316
+ `workers: WORKER_ERROR message truncated for task=${taskType} from ${bytes.length} to ${limit} bytes`,
317
+ );
318
+ return decoded + marker;
319
+ }
252
320
  }
253
321
 
254
322
  function parseDurationMs(d: string): number | null {