@quantumbpm/sdk 1.1.0 → 1.3.0

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 (80) hide show
  1. package/README.md +38 -2
  2. package/dist/bpmn.d.ts +4 -2
  3. package/dist/bpmn.js +4 -4
  4. package/dist/generated/RawClient.js +2 -2
  5. package/dist/generated/core/OpenAPI.js +2 -2
  6. package/dist/generated/index.d.ts +3 -0
  7. package/dist/generated/index.js +4 -2
  8. package/dist/generated/models/BatchEvaluateDesignRequest.d.ts +2 -0
  9. package/dist/generated/models/BatchEvaluateDesignRequest.js +1 -1
  10. package/dist/generated/models/BpmnIncident.d.ts +6 -0
  11. package/dist/generated/models/BpmnIncident.js +5 -1
  12. package/dist/generated/models/BpmnIncidentRecord.d.ts +8 -6
  13. package/dist/generated/models/BpmnIncidentRecord.js +3 -1
  14. package/dist/generated/models/BpmnInstance.d.ts +19 -0
  15. package/dist/generated/models/BpmnInstance.js +1 -1
  16. package/dist/generated/models/BpmnInstanceState.d.ts +18 -2
  17. package/dist/generated/models/BpmnInstanceState.js +1 -1
  18. package/dist/generated/models/CorrelationKeyNumber.d.ts +1 -1
  19. package/dist/generated/models/CorrelationKeyNumber.js +1 -1
  20. package/dist/generated/models/Error.d.ts +6 -0
  21. package/dist/generated/models/Error.js +5 -1
  22. package/dist/generated/models/ErrorMode.d.ts +15 -0
  23. package/dist/generated/models/ErrorMode.js +24 -0
  24. package/dist/generated/models/EvaluateStoredRequest.d.ts +6 -1
  25. package/dist/generated/models/EvaluateStoredRequest.js +1 -1
  26. package/dist/generated/models/EvaluationResult.d.ts +5 -0
  27. package/dist/generated/models/EvaluationResult.js +1 -1
  28. package/dist/generated/models/ExternalJob.d.ts +1 -1
  29. package/dist/generated/models/ExternalJob.js +1 -1
  30. package/dist/generated/models/ExternalJobBatchResponse.d.ts +2 -2
  31. package/dist/generated/models/ExternalJobBatchResponse.js +1 -1
  32. package/dist/generated/models/FeelWarning.d.ts +17 -0
  33. package/dist/generated/models/FeelWarning.js +3 -0
  34. package/dist/generated/models/JoinArrivals.d.ts +8 -0
  35. package/dist/generated/models/JoinArrivals.js +3 -0
  36. package/dist/generated/models/ModificationInstruction.d.ts +1 -1
  37. package/dist/generated/models/ModificationInstruction.js +1 -1
  38. package/dist/generated/models/PollBpmnJobRequest.d.ts +1 -1
  39. package/dist/generated/models/PollBpmnJobRequest.js +1 -1
  40. package/dist/generated/models/SuspensionEntry.d.ts +2 -2
  41. package/dist/generated/models/SuspensionEntry.js +1 -1
  42. package/dist/generated/models/UpdateDefinitionRequest.d.ts +3 -3
  43. package/dist/generated/models/UpdateDefinitionRequest.js +1 -1
  44. package/dist/generated/models/UpdateUserTaskAssignmentRequest.d.ts +11 -4
  45. package/dist/generated/models/UpdateUserTaskAssignmentRequest.js +1 -1
  46. package/dist/generated/services/BpmnService.d.ts +25 -17
  47. package/dist/generated/services/BpmnService.js +52 -6
  48. package/dist/generated/services/DefaultService.d.ts +25 -16
  49. package/dist/generated/services/DefaultService.js +47 -14
  50. package/dist/workers.d.ts +39 -5
  51. package/dist/workers.js +184 -52
  52. package/package.json +1 -1
  53. package/src/bpmn.ts +7 -4
  54. package/src/generated/RawClient.ts +1 -1
  55. package/src/generated/core/OpenAPI.ts +1 -1
  56. package/src/generated/index.ts +3 -0
  57. package/src/generated/models/BatchEvaluateDesignRequest.ts +2 -0
  58. package/src/generated/models/BpmnIncident.ts +6 -0
  59. package/src/generated/models/BpmnIncidentRecord.ts +8 -6
  60. package/src/generated/models/BpmnInstance.ts +19 -0
  61. package/src/generated/models/BpmnInstanceState.ts +18 -2
  62. package/src/generated/models/CorrelationKeyNumber.ts +1 -1
  63. package/src/generated/models/Error.ts +6 -0
  64. package/src/generated/models/ErrorMode.ts +19 -0
  65. package/src/generated/models/EvaluateStoredRequest.ts +6 -1
  66. package/src/generated/models/EvaluationResult.ts +5 -0
  67. package/src/generated/models/ExternalJob.ts +1 -1
  68. package/src/generated/models/ExternalJobBatchResponse.ts +2 -2
  69. package/src/generated/models/FeelWarning.ts +22 -0
  70. package/src/generated/models/JoinArrivals.ts +13 -0
  71. package/src/generated/models/ModificationInstruction.ts +1 -1
  72. package/src/generated/models/PollBpmnJobRequest.ts +1 -1
  73. package/src/generated/models/SuspensionEntry.ts +2 -2
  74. package/src/generated/models/UpdateDefinitionRequest.ts +3 -3
  75. package/src/generated/models/UpdateUserTaskAssignmentRequest.ts +11 -4
  76. package/src/generated/services/BpmnService.ts +62 -17
  77. package/src/generated/services/DefaultService.ts +53 -17
  78. package/src/index.test.ts +3 -0
  79. package/src/workers.test.ts +279 -1
  80. package/src/workers.ts +196 -57
@@ -10,6 +10,7 @@ import type { BpmnInstanceState } from '../models/BpmnInstanceState';
10
10
  import type { CreateDefinitionRequest } from '../models/CreateDefinitionRequest';
11
11
  import type { CreateProjectRequest } from '../models/CreateProjectRequest';
12
12
  import type { Definition } from '../models/Definition';
13
+ import type { ErrorMode } from '../models/ErrorMode';
13
14
  import type { EvaluateStoredRequest } from '../models/EvaluateStoredRequest';
14
15
  import type { EvaluationResult } from '../models/EvaluationResult';
15
16
  import type { Execution } from '../models/Execution';
@@ -71,6 +72,7 @@ export class DefaultService {
71
72
  * Names of decisions or decision services to evaluate. If empty, all decisions in the document are evaluated.
72
73
  */
73
74
  decisions?: Array<string>;
75
+ errorMode?: ErrorMode;
74
76
  },
75
77
  ): CancelablePromise<Record<string, EvaluationResult>> {
76
78
  return this.httpRequest.request({
@@ -423,8 +425,8 @@ export class DefaultService {
423
425
  });
424
426
  }
425
427
  /**
426
- * Update a DMN definition's metadata
427
- * Modifies metadata (name) of a stored definition. The DMN XML and version are immutable; post a new definition with the same XML `id` to publish a new version.
428
+ * Update a DMN definition version
429
+ * Replaces the name and XML of a stored definition version in place. Send `version` 0 to store the change as the next version of the same definition instead.
428
430
  * @param projectId
429
431
  * @param definitionId
430
432
  * @param requestBody
@@ -678,7 +680,8 @@ export class DefaultService {
678
680
  * accumulate indefinitely, and unfiltered queries grow linearly with
679
681
  * that history.
680
682
  *
681
- * @param businessId Exact-match filter on the caller-supplied correlation key set at start time.
683
+ * @param businessId Prefix match on the caller-supplied correlation key set at start time.
684
+ * @param processId Only instances of this process id, in any version. `definitionID` selects one version.
682
685
  * @param page
683
686
  * @param pageSize
684
687
  * @returns BpmnInstancePaginatedResponse OK
@@ -687,11 +690,12 @@ export class DefaultService {
687
690
  public listBpmnInstances(
688
691
  projectId: string,
689
692
  definitionId?: string,
690
- status?: 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELED',
693
+ status?: 'RUNNING' | 'COMPLETED' | 'FAILED' | 'CANCELED' | 'TERMINATED' | 'TIMED_OUT',
691
694
  hasIncident?: boolean,
692
695
  suspended?: boolean,
693
696
  createdAfter?: string,
694
697
  businessId?: string,
698
+ processId?: string,
695
699
  page?: number,
696
700
  pageSize?: number,
697
701
  ): CancelablePromise<BpmnInstancePaginatedResponse> {
@@ -708,6 +712,7 @@ export class DefaultService {
708
712
  'suspended': suspended,
709
713
  'createdAfter': createdAfter,
710
714
  'businessId': businessId,
715
+ 'processId': processId,
711
716
  'page': page,
712
717
  'pageSize': pageSize,
713
718
  },
@@ -719,6 +724,9 @@ export class DefaultService {
719
724
  * `workflowID` is the stable execution identifier - use it to fetch
720
725
  * state, send signals/messages, complete user tasks, etc.
721
726
  *
727
+ * A process from a resource that is not deployed yet is refused with a
728
+ * 400. Drafts only start test instances, see `StartBpmnTestInstance`.
729
+ *
722
730
  * @param projectId
723
731
  * @param requestBody
724
732
  * @returns any Created
@@ -744,6 +752,7 @@ export class DefaultService {
744
752
  errors: {
745
753
  400: `Bad Request`,
746
754
  401: `Unauthorized`,
755
+ 404: `Not Found`,
747
756
  500: `Internal Server Error`,
748
757
  },
749
758
  });
@@ -771,6 +780,11 @@ export class DefaultService {
771
780
  'projectID': projectId,
772
781
  'workflowID': workflowId,
773
782
  },
783
+ errors: {
784
+ 503: `The instance is running but did not answer the state query, typically
785
+ while Temporal retries a workflow task that timed out. Try again shortly.
786
+ `,
787
+ },
774
788
  });
775
789
  }
776
790
  /**
@@ -796,6 +810,10 @@ export class DefaultService {
796
810
  'projectID': projectId,
797
811
  'workflowID': workflowId,
798
812
  },
813
+ errors: {
814
+ 400: `The instance is a call-activity child of a running instance. Cancel the root instance instead.`,
815
+ 404: `No instance has this workflow ID.`,
816
+ },
799
817
  });
800
818
  }
801
819
  /**
@@ -809,7 +827,7 @@ export class DefaultService {
809
827
  * @param taskType Filter jobs by task type
810
828
  * @param status Filter jobs by status
811
829
  * @param workflowId Filter jobs by workflow ID
812
- * @param businessId Exact-match filter on the caller-supplied correlation key.
830
+ * @param businessId Prefix match on the caller-supplied correlation key.
813
831
  * @param createdAfter Only return jobs created at or after this timestamp. Strongly
814
832
  * recommended for monitoring views - completed-job records accumulate
815
833
  * indefinitely, and unfiltered queries grow linearly with that history.
@@ -850,9 +868,11 @@ export class DefaultService {
850
868
  * Poll for external jobs (long-poll)
851
869
  * Long-polls for PENDING jobs of a given `taskType`. Returns a batch of
852
870
  * jobs (up to `maxJobs`) as soon as any are available, or `204 No Content`
853
- * when the timeout elapses with no work. Each returned job is exclusively
854
- * leased to the caller for `lockDuration` - call `Heartbeat` to extend
855
- * the lock, then `Complete` or `ThrowError` to finalize.
871
+ * when the timeout elapses with no work. Each returned job is locked to
872
+ * the caller until `lockDuration` passes without a `Heartbeat`, and for at
873
+ * most the server's `BPMN_JOB_MAX_HOLD` (30m by default) in total. Finish
874
+ * with `Complete` or `ThrowError`. A lock that runs out costs the job a
875
+ * retry, and with no retries left it raises an incident.
856
876
  *
857
877
  * @param projectId
858
878
  * @param requestBody
@@ -871,14 +891,18 @@ export class DefaultService {
871
891
  },
872
892
  body: requestBody,
873
893
  mediaType: 'application/json',
894
+ errors: {
895
+ 400: `An empty \`clientID\`, or a \`lockDuration\` or \`timeout\` that is not a Go duration.`,
896
+ },
874
897
  });
875
898
  }
876
899
  /**
877
900
  * Extend the lock on an acquired job
878
- * Refreshes the exclusive lock on a job that the caller previously
879
- * acquired via `Poll`. Call this periodically when handling a job that
880
- * takes longer than the original `lockDuration`. Other workers cannot
881
- * claim the job until the lock expires or the job is completed.
901
+ * Keeps the caller's lock on a job it acquired via `Poll` for another
902
+ * `lockDuration`, up to `BPMN_JOB_MAX_HOLD` after the job was handed out.
903
+ * SDK workers send it at half of the lock the poll granted
904
+ * (`lockExpiresAt`) while a handler runs.
905
+ * Other workers cannot claim the job while the lock holds.
882
906
  *
883
907
  * @param projectId
884
908
  * @param executionKey
@@ -907,7 +931,12 @@ export class DefaultService {
907
931
  body: requestBody,
908
932
  mediaType: 'application/json',
909
933
  errors: {
910
- 404: `Job not found, not owned by this client, or already terminated`,
934
+ 400: `An empty \`clientID\`, or a \`lockDuration\` that is not a Go duration.`,
935
+ 404: `No job has this execution key.`,
936
+ 409: `This worker no longer holds the job. Its lock ran out, another
937
+ worker holds it, or the job has finished. Stop working on it. The
938
+ message says when the job was cancelled.
939
+ `,
911
940
  },
912
941
  });
913
942
  }
@@ -934,10 +963,10 @@ export class DefaultService {
934
963
  workflowID: string;
935
964
  /**
936
965
  * Optional worker identity (the same `clientID` used to poll).
937
- * When supplied, the completion is applied only if this worker
938
- * still holds the job's lock; a stale worker whose lease lapsed
939
- * and whose job a peer re-acquired is rejected as a no-op.
940
- * Omit for the legacy unchecked behavior.
966
+ * When supplied, a worker that no longer holds the job's lock
967
+ * gets 409 and its result is discarded. Completing a job this
968
+ * worker already completed answers 200 again. Omit for the
969
+ * legacy unchecked behavior.
941
970
  *
942
971
  */
943
972
  clientID?: string;
@@ -953,6 +982,13 @@ export class DefaultService {
953
982
  },
954
983
  body: requestBody,
955
984
  mediaType: 'application/json',
985
+ errors: {
986
+ 404: `No job has this execution key.`,
987
+ 409: `This worker no longer holds the job, so the result was discarded.
988
+ Its lock ran out, another worker holds or completed it, or the job
989
+ failed or was cancelled. The message says when it was cancelled.
990
+ `,
991
+ },
956
992
  });
957
993
  }
958
994
  }
package/src/index.test.ts CHANGED
@@ -51,6 +51,7 @@ describe('BpmnClient.listInstances argument ordering', () => {
51
51
  suspended: false,
52
52
  createdAfter: '2026-01-01T00:00:00Z',
53
53
  businessId: 'ORDER-42',
54
+ processId: 'order_flow',
54
55
  page: 2,
55
56
  pageSize: 10,
56
57
  });
@@ -64,6 +65,7 @@ describe('BpmnClient.listInstances argument ordering', () => {
64
65
  false,
65
66
  '2026-01-01T00:00:00Z',
66
67
  'ORDER-42',
68
+ 'order_flow',
67
69
  2,
68
70
  10,
69
71
  ]);
@@ -93,6 +95,7 @@ describe('BpmnClient.listInstances argument ordering', () => {
93
95
  undefined,
94
96
  undefined,
95
97
  undefined,
98
+ undefined,
96
99
  3,
97
100
  undefined,
98
101
  ]);
@@ -1,5 +1,7 @@
1
- import { Worker, Job } from './workers';
1
+ import { Worker, Job, WorkerConfig, heartbeatIntervalMs, parseDurationMs } from './workers';
2
2
  import { RawClient } from './generated/RawClient';
3
+ import { ApiError } from './generated/core/ApiError';
4
+ import { CancelablePromise } from './generated/core/CancelablePromise';
3
5
  import { Vars } from './variables';
4
6
  import type { ExternalJob } from './generated';
5
7
 
@@ -115,3 +117,279 @@ describe('Worker job dispatch', () => {
115
117
  expect(received!.businessId).toBeUndefined();
116
118
  });
117
119
  });
120
+
121
+ describe('Worker clientId', () => {
122
+ const fakeRaw = {} as unknown as RawClient;
123
+ const projectId = '00000000-0000-0000-0000-000000000001';
124
+
125
+ test('keeps a configured clientId', () => {
126
+ const w = new Worker(fakeRaw, projectId, { clientId: 'billing-1' });
127
+ expect((w as any).clientId).toBe('billing-1');
128
+ });
129
+
130
+ // The server refuses a poll with an empty clientID, so blank falls back.
131
+ test.each(['', ' '])('falls back to a generated id for %j', (blank) => {
132
+ const w = new Worker(fakeRaw, projectId, { clientId: blank });
133
+ expect((w as any).clientId).toMatch(/^worker-.+-\d+$/);
134
+ });
135
+ });
136
+
137
+ describe('parseDurationMs', () => {
138
+ test.each([
139
+ ['30s', 30_000],
140
+ ['12.5s', 12_500],
141
+ ['1m30s', 90_000],
142
+ ['1h2m3.5s', 3_723_500],
143
+ ['500ms', 500],
144
+ ['1.5h', 5_400_000],
145
+ ['.5s', 500],
146
+ ['5.s', 5_000],
147
+ ['1500us', 1.5],
148
+ ['1500µs', 1.5],
149
+ ['2000000ns', 2],
150
+ ['0', 0],
151
+ ['+1s', 1_000],
152
+ ['-1s', -1_000],
153
+ [' 30s', 30_000],
154
+ ['30s ', 30_000],
155
+ ])('parses %j', (input, ms) => {
156
+ expect(parseDurationMs(input)).toBeCloseTo(ms);
157
+ });
158
+
159
+ test.each(['', '30', '12.5', 's', '.s', '1.2.3s', '1m30', '30 s', '1d', '5sec', '1,5s', 'soon'])(
160
+ 'rejects %j',
161
+ (input) => {
162
+ expect(parseDurationMs(input)).toBeNull();
163
+ },
164
+ );
165
+ });
166
+
167
+ describe('heartbeatIntervalMs', () => {
168
+ const now = Date.parse('2026-10-21T10:00:00Z');
169
+ const at = (ms: number) => new Date(now + ms).toISOString();
170
+
171
+ test('uses the granted lock when the server clamped the request down', () => {
172
+ expect(heartbeatIntervalMs(660_000, at(300_000), now)).toBe(150_000);
173
+ });
174
+
175
+ test('uses the requested lock when it is shorter than the grant', () => {
176
+ expect(heartbeatIntervalMs(5_000, at(10_000), now)).toBe(2_500);
177
+ });
178
+
179
+ test('handles a fractional lock', () => {
180
+ expect(heartbeatIntervalMs(12_500, at(12_500), now)).toBe(6_250);
181
+ });
182
+
183
+ test.each([
184
+ ['missing', undefined],
185
+ ['in the past', '2026-10-21T09:59:00Z'],
186
+ ['unparseable', 'later'],
187
+ ])('falls back to the requested lock when lockExpiresAt is %s', (_name, expiresAt) => {
188
+ expect(heartbeatIntervalMs(30_000, expiresAt, now)).toBe(15_000);
189
+ });
190
+
191
+ test('never goes below one second', () => {
192
+ expect(heartbeatIntervalMs(500, at(10_000), now)).toBe(1_000);
193
+ });
194
+ });
195
+
196
+ describe('Worker duration validation', () => {
197
+ const fakeRaw = {} as unknown as RawClient;
198
+ const projectId = '00000000-0000-0000-0000-000000000001';
199
+ const handler = async () => new Vars();
200
+
201
+ test('handle accepts fractional and compound durations', () => {
202
+ const w = new Worker(fakeRaw, projectId);
203
+ w.handle('payment', handler, { lockDuration: '12.5s', pollTimeout: '1m30s' });
204
+ expect((w as any).registrations.get('payment').lockMs).toBe(12_500);
205
+ });
206
+
207
+ test('handle trims the durations it sends', () => {
208
+ const w = new Worker(fakeRaw, projectId);
209
+ w.handle('payment', handler, { lockDuration: ' 10s ', pollTimeout: '5s ' });
210
+ const reg = (w as any).registrations.get('payment');
211
+ expect([reg.options.lockDuration, reg.options.pollTimeout, reg.lockMs]).toEqual(['10s', '5s', 10_000]);
212
+ });
213
+
214
+ test('handle throws on an invalid lockDuration', () => {
215
+ const w = new Worker(fakeRaw, projectId);
216
+ expect(() => w.handle('payment', handler, { lockDuration: '12.5x' })).toThrow(/invalid lockDuration "12.5x"/);
217
+ expect((w as any).registrations.size).toBe(0);
218
+ });
219
+
220
+ test('handle throws on an invalid pollTimeout', () => {
221
+ const w = new Worker(fakeRaw, projectId);
222
+ expect(() => w.handle('payment', handler, { pollTimeout: 'soon' })).toThrow(/invalid pollTimeout "soon"/);
223
+ });
224
+
225
+ test('the constructor throws on an invalid shutdownTimeout', () => {
226
+ expect(() => new Worker(fakeRaw, projectId, { shutdownTimeout: '20 seconds' }))
227
+ .toThrow(/invalid shutdownTimeout "20 seconds"/);
228
+ });
229
+ });
230
+
231
+ describe('Worker locks and shutdown', () => {
232
+ beforeEach(() => jest.useFakeTimers());
233
+ afterEach(() => jest.useRealTimers());
234
+
235
+ const job = {
236
+ executionKey: 'wf-1:node-a:1',
237
+ workflowID: 'wf-1',
238
+ taskType: 'payment',
239
+ } as unknown as ExternalJob;
240
+
241
+ function apiError(status: number, body?: unknown): ApiError {
242
+ return new ApiError(
243
+ { method: 'POST', url: '' },
244
+ { url: '', ok: false, status, statusText: '', body },
245
+ `status ${status}`,
246
+ );
247
+ }
248
+
249
+ // The first poll hands out one job. Later polls hang until cancelled.
250
+ function setup(config: WorkerConfig = {}, polled: ExternalJob = job) {
251
+ let polls = 0;
252
+ const calls = {
253
+ poll: jest.fn(() => new CancelablePromise<ExternalJob[]>((resolve) => {
254
+ if (polls++ === 0) resolve([polled]);
255
+ })),
256
+ heartbeat: jest.fn(async (..._args: unknown[]) => {}),
257
+ complete: jest.fn(async (..._args: unknown[]) => {}),
258
+ throwError: jest.fn(async (..._args: unknown[]) => {}),
259
+ };
260
+ const raw = {
261
+ default: {
262
+ pollBpmnExternalJobs: calls.poll,
263
+ heartbeatBpmnExternalJob: calls.heartbeat,
264
+ completeBpmnExternalJob: calls.complete,
265
+ },
266
+ bpmn: { throwBpmnExternalJobError: calls.throwError },
267
+ } as unknown as RawClient;
268
+ const warnings: string[] = [];
269
+ const errors: string[] = [];
270
+ const w = new Worker(raw, '00000000-0000-0000-0000-000000000001', {
271
+ logger: {
272
+ error: (msg: string) => { errors.push(msg); },
273
+ warn: (msg: string) => { warnings.push(msg); },
274
+ },
275
+ ...config,
276
+ });
277
+ return { w, calls, warnings, errors };
278
+ }
279
+
280
+ test('a heartbeat 409 aborts the handler signal and sends no complete', async () => {
281
+ const { w, calls, warnings } = setup();
282
+ calls.heartbeat.mockRejectedValue(apiError(409));
283
+ let signal: AbortSignal | undefined;
284
+ w.handle('payment', (_job, s) => {
285
+ signal = s;
286
+ return new Promise((_resolve, reject) => {
287
+ s.addEventListener('abort', () => reject(new Error('aborted')));
288
+ });
289
+ });
290
+
291
+ const stop = new AbortController();
292
+ const running = w.run(stop.signal);
293
+ await jest.advanceTimersByTimeAsync(15_000);
294
+ expect(signal?.aborted).toBe(true);
295
+
296
+ await jest.advanceTimersByTimeAsync(60_000);
297
+ stop.abort();
298
+ await running;
299
+
300
+ expect(calls.heartbeat).toHaveBeenCalledTimes(1);
301
+ expect(calls.complete).not.toHaveBeenCalled();
302
+ expect(calls.throwError).not.toHaveBeenCalled();
303
+ expect(warnings.filter(m => m.includes('this worker no longer holds the job, aborting the handler'))).toHaveLength(1);
304
+ });
305
+
306
+ test('heartbeats at half of the lock the server granted', async () => {
307
+ const clamped = { ...job, lockExpiresAt: new Date(Date.now() + 300_000).toISOString() } as ExternalJob;
308
+ const { w, calls } = setup({}, clamped);
309
+ let finish: (v: Vars) => void = () => {};
310
+ w.handle('payment', () => new Promise<Vars>((resolve) => { finish = resolve; }), { lockDuration: '11m' });
311
+
312
+ const stop = new AbortController();
313
+ const running = w.run(stop.signal);
314
+ await jest.advanceTimersByTimeAsync(149_999);
315
+ expect(calls.heartbeat).not.toHaveBeenCalled();
316
+ await jest.advanceTimersByTimeAsync(1);
317
+ expect(calls.heartbeat).toHaveBeenCalledTimes(1);
318
+ expect(calls.heartbeat.mock.calls[0][2]).toMatchObject({ lockDuration: '11m' });
319
+
320
+ stop.abort();
321
+ finish(new Vars());
322
+ await running;
323
+ expect(calls.complete).toHaveBeenCalledTimes(1);
324
+ });
325
+
326
+ test('after shutdown starts, a running handler keeps heartbeating and completes', async () => {
327
+ const { w, calls } = setup();
328
+ let signal: AbortSignal | undefined;
329
+ let finish: (v: Vars) => void = () => {};
330
+ w.handle('payment', (_job, s) => {
331
+ signal = s;
332
+ return new Promise<Vars>((resolve) => { finish = resolve; });
333
+ }, { maxJobs: 2, lockDuration: '10s' });
334
+
335
+ const stop = new AbortController();
336
+ const running = w.run(stop.signal);
337
+ await jest.advanceTimersByTimeAsync(0);
338
+ expect(signal).toBeDefined();
339
+ // The second poll is the in-flight long-poll that the abort cancels.
340
+ expect(calls.poll).toHaveBeenCalledTimes(2);
341
+
342
+ stop.abort();
343
+ await jest.advanceTimersByTimeAsync(15_000);
344
+ expect(calls.heartbeat).toHaveBeenCalledTimes(3);
345
+ expect(signal!.aborted).toBe(false);
346
+
347
+ finish(new Vars().set('ok', true));
348
+ await running;
349
+
350
+ expect(calls.poll).toHaveBeenCalledTimes(2);
351
+ expect(calls.complete).toHaveBeenCalledTimes(1);
352
+ expect(calls.complete.mock.calls[0][1]).toBe('wf-1:node-a:1');
353
+ expect(calls.complete.mock.calls[0][2]).toMatchObject({ variables: { ok: true } });
354
+ });
355
+
356
+ test('the shutdown timeout aborts a handler that does not finish and run resolves', async () => {
357
+ const { w, calls, warnings } = setup({ shutdownTimeout: '5s' });
358
+ let signal: AbortSignal | undefined;
359
+ w.handle('payment', (_job, s) => {
360
+ signal = s;
361
+ return new Promise<Vars>(() => {});
362
+ });
363
+
364
+ const stop = new AbortController();
365
+ let resolved = false;
366
+ const running = w.run(stop.signal).then(() => { resolved = true; });
367
+ await jest.advanceTimersByTimeAsync(0);
368
+ stop.abort();
369
+
370
+ await jest.advanceTimersByTimeAsync(4_999);
371
+ expect(resolved).toBe(false);
372
+ expect(signal!.aborted).toBe(false);
373
+
374
+ await jest.advanceTimersByTimeAsync(1);
375
+ await running;
376
+ expect(signal!.aborted).toBe(true);
377
+ expect(calls.complete).not.toHaveBeenCalled();
378
+ expect(calls.throwError).not.toHaveBeenCalled();
379
+ expect(warnings.some(m => m.includes('shutdown timeout'))).toBe(true);
380
+ // Heartbeat and shutdown timers are all cleared.
381
+ expect(jest.getTimerCount()).toBe(0);
382
+ });
383
+
384
+ test('a complete 409 is logged as a discarded result', async () => {
385
+ const { w, calls, warnings, errors } = setup();
386
+ calls.complete.mockRejectedValue(apiError(409, { code: 'CONFLICT', message: 'the job was canceled' }));
387
+ w.handle('payment', async () => new Vars());
388
+
389
+ const registration = (w as any).registrations.get('payment');
390
+ await (w as any).dispatch(registration, job, new AbortController().signal);
391
+
392
+ expect(warnings).toContain('workers: complete wf-1:node-a:1: result discarded: the job was canceled');
393
+ expect(errors).toHaveLength(0);
394
+ });
395
+ });