@dbos-inc/dbos-sdk 5.4.10-preview → 5.5.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 (96) hide show
  1. package/dist/schemas/system_db_schema.d.ts +7 -0
  2. package/dist/schemas/system_db_schema.d.ts.map +1 -1
  3. package/dist/schemas/system_db_schema.js.map +1 -1
  4. package/dist/src/cli/cli.js +56 -13
  5. package/dist/src/cli/cli.js.map +1 -1
  6. package/dist/src/client.d.ts +44 -10
  7. package/dist/src/client.d.ts.map +1 -1
  8. package/dist/src/client.js +140 -44
  9. package/dist/src/client.js.map +1 -1
  10. package/dist/src/config.d.ts +1 -0
  11. package/dist/src/config.d.ts.map +1 -1
  12. package/dist/src/config.js +4 -0
  13. package/dist/src/config.js.map +1 -1
  14. package/dist/src/context.d.ts +6 -0
  15. package/dist/src/context.d.ts.map +1 -1
  16. package/dist/src/context.js +15 -1
  17. package/dist/src/context.js.map +1 -1
  18. package/dist/src/datasource.d.ts +2 -0
  19. package/dist/src/datasource.d.ts.map +1 -1
  20. package/dist/src/datasource.js +7 -1
  21. package/dist/src/datasource.js.map +1 -1
  22. package/dist/src/dbos-executor.d.ts +32 -4
  23. package/dist/src/dbos-executor.d.ts.map +1 -1
  24. package/dist/src/dbos-executor.js +102 -33
  25. package/dist/src/dbos-executor.js.map +1 -1
  26. package/dist/src/dbos.d.ts +104 -15
  27. package/dist/src/dbos.d.ts.map +1 -1
  28. package/dist/src/dbos.js +275 -86
  29. package/dist/src/dbos.js.map +1 -1
  30. package/dist/src/debugpoint.d.ts +1 -0
  31. package/dist/src/debugpoint.d.ts.map +1 -1
  32. package/dist/src/debugpoint.js +4 -2
  33. package/dist/src/debugpoint.js.map +1 -1
  34. package/dist/src/enqueue_options.d.ts +2 -0
  35. package/dist/src/enqueue_options.d.ts.map +1 -1
  36. package/dist/src/enqueue_options.js +3 -0
  37. package/dist/src/enqueue_options.js.map +1 -1
  38. package/dist/src/enqueue_workflow.d.ts.map +1 -1
  39. package/dist/src/enqueue_workflow.js +11 -5
  40. package/dist/src/enqueue_workflow.js.map +1 -1
  41. package/dist/src/enterprise.d.ts +78 -3
  42. package/dist/src/enterprise.d.ts.map +1 -1
  43. package/dist/src/enterprise.js +104 -45
  44. package/dist/src/enterprise.js.map +1 -1
  45. package/dist/src/error.d.ts +42 -0
  46. package/dist/src/error.d.ts.map +1 -1
  47. package/dist/src/error.js +85 -1
  48. package/dist/src/error.js.map +1 -1
  49. package/dist/src/eventreceiver.d.ts +2 -0
  50. package/dist/src/eventreceiver.d.ts.map +1 -1
  51. package/dist/src/eventreceiver.js +7 -1
  52. package/dist/src/eventreceiver.js.map +1 -1
  53. package/dist/src/external_storage.d.ts +27 -0
  54. package/dist/src/external_storage.d.ts.map +1 -0
  55. package/dist/src/external_storage.js +28 -0
  56. package/dist/src/external_storage.js.map +1 -0
  57. package/dist/src/index.d.ts +4 -3
  58. package/dist/src/index.d.ts.map +1 -1
  59. package/dist/src/index.js +2 -1
  60. package/dist/src/index.js.map +1 -1
  61. package/dist/src/scheduler/scheduler.d.ts +83 -3
  62. package/dist/src/scheduler/scheduler.d.ts.map +1 -1
  63. package/dist/src/scheduler/scheduler.js +422 -171
  64. package/dist/src/scheduler/scheduler.js.map +1 -1
  65. package/dist/src/shard_keys.d.ts +13 -0
  66. package/dist/src/shard_keys.d.ts.map +1 -0
  67. package/dist/src/shard_keys.js +55 -0
  68. package/dist/src/shard_keys.js.map +1 -0
  69. package/dist/src/streams.d.ts +2 -0
  70. package/dist/src/streams.d.ts.map +1 -1
  71. package/dist/src/streams.js +5 -2
  72. package/dist/src/streams.js.map +1 -1
  73. package/dist/src/sysdb_migrations/internal/migrations.js +82 -0
  74. package/dist/src/sysdb_migrations/internal/migrations.js.map +1 -1
  75. package/dist/src/system_database.d.ts +185 -10
  76. package/dist/src/system_database.d.ts.map +1 -1
  77. package/dist/src/system_database.js +1429 -626
  78. package/dist/src/system_database.js.map +1 -1
  79. package/dist/src/utils.d.ts +2 -0
  80. package/dist/src/utils.d.ts.map +1 -1
  81. package/dist/src/utils.js +9 -1
  82. package/dist/src/utils.js.map +1 -1
  83. package/dist/src/wfqueue.d.ts +1 -2
  84. package/dist/src/wfqueue.d.ts.map +1 -1
  85. package/dist/src/wfqueue.js +83 -63
  86. package/dist/src/wfqueue.js.map +1 -1
  87. package/dist/src/workflow.d.ts +15 -3
  88. package/dist/src/workflow.d.ts.map +1 -1
  89. package/dist/src/workflow.js +30 -12
  90. package/dist/src/workflow.js.map +1 -1
  91. package/dist/src/workflow_management.d.ts +17 -3
  92. package/dist/src/workflow_management.d.ts.map +1 -1
  93. package/dist/src/workflow_management.js +93 -20
  94. package/dist/src/workflow_management.js.map +1 -1
  95. package/dist/tsconfig.tsbuildinfo +1 -1
  96. package/package.json +2 -2
package/dist/src/dbos.js CHANGED
@@ -26,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.DBOS = exports.StepReservation = exports.runTransactionalInternalStep = exports.getResultInternal = exports.runInternalStep = exports.getExecutor = exports.resolveDelayEpochMS = exports.resolveStreamTimeoutMS = exports.resolveStreamPollingIntervalMs = exports.resolveStreamOffset = exports.resolvePollingIntervalMs = exports.resolveTimeoutSeconds = void 0;
29
+ exports.DBOS = exports.StepReservation = exports.runTransactionalInternalStep = exports.awaitRecordedResult = exports.getResultInternal = exports.runInternalStep = exports.getExecutor = exports.resolveDelayEpochMS = exports.resolveStreamTimeoutMS = exports.resolveStreamPollingIntervalMs = exports.resolveStreamOffset = exports.resolvePollingIntervalMs = exports.resolveTimeoutSeconds = void 0;
30
30
  const context_1 = require("./context");
31
31
  const dbos_executor_1 = require("./dbos-executor");
32
32
  const traces_1 = require("./telemetry/traces");
@@ -48,6 +48,7 @@ const crontab_1 = require("./scheduler/crontab");
48
48
  const wfqueue_1 = require("./wfqueue");
49
49
  const enqueue_workflow_1 = require("./enqueue_workflow");
50
50
  const node_assert_1 = __importDefault(require("node:assert"));
51
+ const shard_keys_1 = require("./shard_keys");
51
52
  function resolveTimeoutSeconds(options) {
52
53
  if (options === undefined)
53
54
  return undefined;
@@ -59,6 +60,15 @@ function resolveTimeoutSeconds(options) {
59
60
  return options.timeoutSeconds;
60
61
  }
61
62
  exports.resolveTimeoutSeconds = resolveTimeoutSeconds;
63
+ /** The suspend-mode operations, or a refusal naming `operation` when suspend mode is off. */
64
+ function requireSuspendMode(operation) {
65
+ const suspend = dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.suspend;
66
+ if (suspend === undefined) {
67
+ throw new error_1.DBOSError(`${operation} with suspend: true requires suspend mode, a Transact Enterprise feature: ` +
68
+ 'set suspendMode to true in the DBOS configuration.');
69
+ }
70
+ return suspend;
71
+ }
62
72
  function resolvePollingIntervalMs(options) {
63
73
  if (options === undefined || typeof options === 'number')
64
74
  return undefined;
@@ -142,20 +152,23 @@ function runInternalStep(callback, funcName, childWFID, assignedFuncID) {
142
152
  }
143
153
  exports.runInternalStep = runInternalStep;
144
154
  async function getResultInternal(workflowID, timeoutSeconds, timerFuncID, assignedFuncID, pollingIntervalMs) {
145
- return await runInternalStep(async () => {
146
- const rres = await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.awaitWorkflowResult(workflowID, timeoutSeconds, DBOS.workflowID, timerFuncID, pollingIntervalMs);
147
- if (!rres)
148
- return null;
149
- if (rres?.cancelled) {
150
- throw new error_1.DBOSAwaitedWorkflowCancelledError(workflowID);
151
- }
152
- if (rres?.maxRecoveryAttemptsExceeded) {
153
- throw new error_1.DBOSAwaitedWorkflowExceededMaxRecoveryAttempts(workflowID);
154
- }
155
- return await dbos_executor_1.DBOSExecutor.reviveResultOrError(rres, getExecutor().serializer);
156
- }, 'DBOS.getResult', workflowID, assignedFuncID);
155
+ return await runInternalStep(() => awaitRecordedResult(workflowID, timeoutSeconds, timerFuncID, pollingIntervalMs), 'DBOS.getResult', workflowID, assignedFuncID);
157
156
  }
158
157
  exports.getResultInternal = getResultInternal;
158
+ /** Poll for the outcome recorded for `workflowID`, or null on timeout; the body of a `DBOS.getResult` step. */
159
+ async function awaitRecordedResult(workflowID, timeoutSeconds, timerFuncID, pollingIntervalMs) {
160
+ const rres = await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.awaitWorkflowResult(workflowID, timeoutSeconds, DBOS.workflowID, timerFuncID, pollingIntervalMs);
161
+ if (!rres)
162
+ return null;
163
+ if (rres?.cancelled) {
164
+ throw new error_1.DBOSAwaitedWorkflowCancelledError(workflowID);
165
+ }
166
+ if (rres?.maxRecoveryAttemptsExceeded) {
167
+ throw new error_1.DBOSAwaitedWorkflowExceededMaxRecoveryAttempts(workflowID);
168
+ }
169
+ return await dbos_executor_1.DBOSExecutor.reviveResultOrError(rres, getExecutor().serializer);
170
+ }
171
+ exports.awaitRecordedResult = awaitRecordedResult;
159
172
  /**
160
173
  * Like runInternalStep, but when called from within a workflow, the callback and the step
161
174
  * result recording run in the same database transaction (via runTransactionalStep).
@@ -259,8 +272,29 @@ class DBOS {
259
272
  * @param systemDatabaseUrl - The system database to create or migrate
260
273
  * @param options.schemaName - The schema holding the DBOS system tables (default: `dbos`)
261
274
  * @param options.applicationRole - A role to grant access to the system schema once migrated
275
+ * @param options.sharding - Create or migrate a sharded system database (requires @dbos-inc/dbos-enterprise)
262
276
  */
263
277
  static async migrate(systemDatabaseUrl, options = {}) {
278
+ if (options.sharding) {
279
+ // Sharded migrations come from Transact Enterprise; the grant is the same.
280
+ const sysdb = (0, system_database_1.createSystemDatabase)({
281
+ systemDatabaseUrl,
282
+ logger: new logs_1.GlobalLogger(),
283
+ serializer: serialization_1.DBOSJSON,
284
+ schemaName: options.schemaName ?? 'dbos',
285
+ sharding: true,
286
+ });
287
+ try {
288
+ await sysdb.runMigrations();
289
+ }
290
+ finally {
291
+ await sysdb.destroy();
292
+ }
293
+ if (options.applicationRole) {
294
+ await (0, system_database_1.grantDbosSchemaPermissions)(systemDatabaseUrl, options.applicationRole, new logs_1.GlobalLogger(), options.schemaName ?? 'dbos');
295
+ }
296
+ return;
297
+ }
264
298
  await (0, system_database_1.migrateSystemDatabase)(systemDatabaseUrl, new logs_1.GlobalLogger(), options.schemaName ?? 'dbos', options.applicationRole);
265
299
  }
266
300
  /**
@@ -289,7 +323,11 @@ class DBOS {
289
323
  }
290
324
  (0, decorators_1.finalizeClassRegistrations)();
291
325
  // Every enterprise feature requires Conductor to report the org entitled to it, and the package.
292
- const features = enterprise.enabledFeatures(config);
326
+ let features = enterprise.enabledFeatures(config);
327
+ if (internalConfig.sharding) {
328
+ // Auto-upgrade is disabled on a sharded system database, so it needs no entitlement.
329
+ features = features.filter((f) => f !== enterprise.AUTO_UPGRADE);
330
+ }
293
331
  const entitlementOptions = {
294
332
  enterpriseKey: config.transactEnterpriseKey,
295
333
  conductorKey: options?.conductorKey,
@@ -304,7 +342,7 @@ class DBOS {
304
342
  : undefined;
305
343
  // Workflows can also enroll for auto-upgrade individually, which the config flag's check above does not cover.
306
344
  const autoUpgradableWorkflowNames = (0, auto_upgrade_1.autoUpgradableWorkflows)(internalConfig.autoUpgrade);
307
- if (autoUpgradableWorkflowNames.length > 0 && !internalConfig.autoUpgrade) {
345
+ if (autoUpgradableWorkflowNames.length > 0 && !internalConfig.autoUpgrade && !internalConfig.sharding) {
308
346
  await enterprise.requireEnterprise([enterprise.AUTO_UPGRADE], entitlementOptions);
309
347
  loadedEnterprise ??= enterprise.load(enterprise.AUTO_UPGRADE.description);
310
348
  }
@@ -395,7 +433,11 @@ class DBOS {
395
433
  executor.conductor.start();
396
434
  }
397
435
  // Start the auto-upgrade loop if any workflow takes part.
398
- if (autoUpgradableWorkflowNames.length > 0) {
436
+ if (autoUpgradableWorkflowNames.length > 0 && executor.systemDatabase.sharded) {
437
+ // Its queries aren't keyed by shard, so it doesn't run on a sharded database.
438
+ executor.logger.warn('Auto-upgrade is disabled: it is not supported on a sharded system database.');
439
+ }
440
+ else if (autoUpgradableWorkflowNames.length > 0) {
399
441
  (0, node_assert_1.default)(loadedEnterprise, 'the enterprise package is loaded whenever a workflow enrolls in auto-upgrade');
400
442
  const upgradePass = new loadedEnterprise.AutoUpgradePass(executor, {
401
443
  graceMs: internalConfig.autoUpgradeGraceMs ?? auto_upgrade_1.DEFAULT_AUTO_UPGRADE_GRACE_MS,
@@ -459,7 +501,7 @@ class DBOS {
459
501
  executor.autoUpgrader = undefined;
460
502
  }
461
503
  await executor.awaitRunningWorkflows(drainTimeoutMS);
462
- await executor.stopWorkflowTimeoutSweep();
504
+ await executor.stopBackgroundJobs();
463
505
  }
464
506
  // Stop the conductor
465
507
  if (executor?.conductor) {
@@ -498,6 +540,46 @@ class DBOS {
498
540
  (0, decorators_1.clearAllRegistrations)();
499
541
  wfqueue_1.wfQueueRunner.clearRegistrations();
500
542
  }
543
+ /**
544
+ * Stop background work that brings new work into this process: queue dispatch and registered event receivers.
545
+ * Schedules keep firing, so another process can run them. Workflows already running here keep running.
546
+ * Has no effect if receivers are already stopped. Throws if DBOS is not launched, or if called from within a workflow.
547
+ * Restart them with `DBOS.initEventReceivers`.
548
+ */
549
+ static async deactivateEventReceivers() {
550
+ if (!DBOS.isInitialized())
551
+ throw new error_1.DBOSExecutorNotInitializedError();
552
+ // Not a checkpointed step, so it would rerun on every replay of the calling workflow.
553
+ if (DBOS.isWithinWorkflow()) {
554
+ throw new error_1.DBOSInvalidWorkflowTransitionError('Invalid call to `DBOS.deactivateEventReceivers` inside a workflow');
555
+ }
556
+ await DBOS.#executor.deactivateEventReceivers();
557
+ }
558
+ /**
559
+ * Restart queue dispatch and registered event receivers after `DBOS.deactivateEventReceivers`.
560
+ * Has no effect if receivers are already running. Throws if DBOS is not launched, or if called from within a workflow.
561
+ * If a receiver fails to start, stops whatever did start and rethrows the error, so the call can be retried.
562
+ */
563
+ static async initEventReceivers() {
564
+ // A launch that failed before the system database was ready leaves an uninitialized executor behind; don't start receivers on it.
565
+ if (!DBOS.isInitialized())
566
+ throw new error_1.DBOSExecutorNotInitializedError();
567
+ // Receivers started here would run in the calling workflow's context and record steps against it.
568
+ if (DBOS.isWithinWorkflow()) {
569
+ throw new error_1.DBOSInvalidWorkflowTransitionError('Invalid call to `DBOS.initEventReceivers` inside a workflow');
570
+ }
571
+ const executor = DBOS.#executor;
572
+ await executor.receiversLock.runExclusive(async () => {
573
+ try {
574
+ await executor.initEventReceiversUnlocked(DBOS.#dbosConfig?.listenQueues || null);
575
+ }
576
+ catch (e) {
577
+ // Tear down whatever did start, under the same lock, so a retry starts clean and a call queued behind this one isn't undone.
578
+ await executor.deactivateEventReceiversUnlocked();
579
+ throw e;
580
+ }
581
+ });
582
+ }
501
583
  // Global DBOS executor instance
502
584
  static get #executor() {
503
585
  return getExecutor();
@@ -541,6 +623,11 @@ class DBOS {
541
623
  static get workflowID() {
542
624
  return (0, context_1.getCurrentContextStore)()?.workflowId;
543
625
  }
626
+ /** The shard key of the currently executing workflow; undefined outside a workflow or on an unsharded database. */
627
+ static get shardKey() {
628
+ const ctx = (0, context_1.getCurrentContextStore)();
629
+ return ctx?.workflowId !== undefined ? ctx.shardKey : undefined;
630
+ }
544
631
  /** Use portable serialization by default? */
545
632
  static get #defaultSerializationType() {
546
633
  return (0, context_1.getCurrentContextStore)()?.serializationType;
@@ -603,21 +690,23 @@ class DBOS {
603
690
  * @param workflowID - ID of the workflow
604
691
  * @returns status of the workflow as `WorkflowStatus`, or `null` if there is no workflow with `workflowID`
605
692
  */
606
- static getWorkflowStatus(workflowID) {
693
+ static async getWorkflowStatus(workflowID, options) {
607
694
  (0, decorators_1.ensureDBOSIsLaunched)('getWorkflowStatus');
608
- if (DBOS.isWithinWorkflow()) {
609
- if (DBOS.isInStep()) {
610
- // OK to use directly
611
- return DBOS.#executor.getWorkflowStatus(workflowID);
612
- }
613
- else if (DBOS.isInWorkflow()) {
614
- return DBOS.#executor.getWorkflowStatus(workflowID, DBOS.workflowID, (0, context_1.functionIDGetIncrement)());
615
- }
616
- else {
617
- throw new error_1.DBOSInvalidWorkflowTransitionError('Invalid call to `getWorkflowStatus` inside a `transaction`');
695
+ return await (0, shard_keys_1.bindShardKeys)([[workflowID, options?.shardKey]], () => {
696
+ if (DBOS.isWithinWorkflow()) {
697
+ if (DBOS.isInStep()) {
698
+ // OK to use directly
699
+ return DBOS.#executor.getWorkflowStatus(workflowID);
700
+ }
701
+ else if (DBOS.isInWorkflow()) {
702
+ return DBOS.#executor.getWorkflowStatus(workflowID, DBOS.workflowID, (0, context_1.functionIDGetIncrement)());
703
+ }
704
+ else {
705
+ throw new error_1.DBOSInvalidWorkflowTransitionError('Invalid call to `getWorkflowStatus` inside a `transaction`');
706
+ }
618
707
  }
619
- }
620
- return DBOS.#executor.getWorkflowStatus(workflowID);
708
+ return DBOS.#executor.getWorkflowStatus(workflowID);
709
+ });
621
710
  }
622
711
  /**
623
712
  * Get the workflow result, given a workflow ID
@@ -634,11 +723,12 @@ class DBOS {
634
723
  // Reserve the function ID synchronously, before any await.
635
724
  timerFuncID = (0, context_1.functionIDGetIncrement)();
636
725
  }
637
- return await getResultInternal(workflowID, timeoutSeconds, timerFuncID, undefined, pollingIntervalMs);
726
+ const shardKey = typeof options === 'object' ? options.shardKey : undefined;
727
+ return await (0, shard_keys_1.bindShardKeys)([[workflowID, shardKey]], () => getResultInternal(workflowID, timeoutSeconds, timerFuncID, undefined, pollingIntervalMs));
638
728
  }
639
729
  /**
640
730
  * Wait for any one of the given workflow handles to complete and return it.
641
- * Polls the database until at least one workflow's status is no longer PENDING, ENQUEUED, or DELAYED,
731
+ * Polls the database until at least one workflow's status is no longer PENDING, ENQUEUED, DELAYED, or SUSPENDED,
642
732
  * then returns the corresponding handle.
643
733
  * @param handles - Non-empty array of workflow handles to wait on
644
734
  * @returns The first handle whose workflow has completed
@@ -658,14 +748,14 @@ class DBOS {
658
748
  handleMap.set(handle.workflowID, handle);
659
749
  }
660
750
  const workflowIds = [...handleMap.keys()];
661
- const completedId = await runInternalStep(async () => {
751
+ const completedId = await (0, shard_keys_1.bindShardKeys)(handles.map((h) => [h.workflowID, h.shardKey]), () => runInternalStep(async () => {
662
752
  return await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.awaitFirstWorkflowId(workflowIds, DBOS.workflowID, pollingIntervalMs);
663
- }, 'DBOS.waitFirst');
753
+ }, 'DBOS.waitFirst'));
664
754
  return handleMap.get(completedId);
665
755
  }
666
756
  /**
667
757
  * Wait for all of the given workflow handles to complete and return them.
668
- * Polls the database until each workflow's status is no longer PENDING, ENQUEUED, or DELAYED.
758
+ * Polls the database until each workflow's status is no longer PENDING, ENQUEUED, DELAYED, or SUSPENDED.
669
759
  * @param handles - Array of workflow handles to wait on
670
760
  * @param options - Optional polling interval
671
761
  * @returns The input handles, in the same order
@@ -677,9 +767,9 @@ class DBOS {
677
767
  }
678
768
  const pollingIntervalMs = resolvePollingIntervalMs(options);
679
769
  const workflowIds = [...new Set(handles.map((handle) => handle.workflowID))];
680
- await runInternalStep(async () => {
770
+ await (0, shard_keys_1.bindShardKeys)(handles.map((h) => [h.workflowID, h.shardKey]), () => runInternalStep(async () => {
681
771
  await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.awaitWorkflowIds(workflowIds, DBOS.workflowID, pollingIntervalMs);
682
- }, 'DBOS.waitAll');
772
+ }, 'DBOS.waitAll'));
683
773
  return handles;
684
774
  }
685
775
  /**
@@ -689,15 +779,14 @@ class DBOS {
689
779
  * @param workflowID - ID of the workflow
690
780
  * @returns `WorkflowHandle` that can be used to poll for the status or result of any workflow with `workflowID`
691
781
  */
692
- static retrieveWorkflow(workflowID) {
782
+ static retrieveWorkflow(workflowID, options) {
693
783
  (0, decorators_1.ensureDBOSIsLaunched)('retrieveWorkflow');
694
- if (DBOS.isWithinWorkflow()) {
695
- if (!DBOS.isInWorkflow()) {
696
- throw new error_1.DBOSInvalidWorkflowTransitionError('Invalid call to `retrieveWorkflow` inside a `transaction` or `step`');
697
- }
698
- return new workflow_1.RetrievedHandle(workflowID);
784
+ if (DBOS.isWithinWorkflow() && !DBOS.isInWorkflow()) {
785
+ throw new error_1.DBOSInvalidWorkflowTransitionError('Invalid call to `retrieveWorkflow` inside a `transaction` or `step`');
699
786
  }
700
- return DBOS.#executor.retrieveWorkflow(workflowID);
787
+ // The resolved key, so the handle also works outside this binding.
788
+ const shardKey = (0, shard_keys_1.bindShardKeys)([[workflowID, options?.shardKey]], () => DBOS.#executor.systemDatabase.keyHint(workflowID));
789
+ return new workflow_1.RetrievedHandle(workflowID, shardKey);
701
790
  }
702
791
  /**
703
792
  * Query the system database for all workflows matching the provided predicate
@@ -727,14 +816,14 @@ class DBOS {
727
816
  * @param workflowID - ID of the workflow
728
817
  * @param priority - Priority value (0 to 2,147,483,647). Lower values are dequeued first.
729
818
  */
730
- static async setWorkflowPriority(workflowID, priority) {
819
+ static async setWorkflowPriority(workflowID, priority, options) {
731
820
  (0, decorators_1.ensureDBOSIsLaunched)('setWorkflowPriority');
732
821
  if (priority < dbos_executor_1.DBOS_QUEUE_MIN_PRIORITY || priority > dbos_executor_1.DBOS_QUEUE_MAX_PRIORITY) {
733
822
  throw new error_1.DBOSInvalidQueuePriorityError(priority, dbos_executor_1.DBOS_QUEUE_MIN_PRIORITY, dbos_executor_1.DBOS_QUEUE_MAX_PRIORITY);
734
823
  }
735
- return runInternalStep(async () => {
824
+ return (0, shard_keys_1.bindShardKeys)([[workflowID, options?.shardKey]], () => runInternalStep(async () => {
736
825
  return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.setWorkflowPriority(workflowID, priority);
737
- }, 'DBOS.setWorkflowPriority');
826
+ }, 'DBOS.setWorkflowPriority'));
738
827
  }
739
828
  /**
740
829
  * Update the delay on a DELAYED workflow.
@@ -746,9 +835,10 @@ class DBOS {
746
835
  static async setWorkflowDelay(workflowID, options) {
747
836
  (0, decorators_1.ensureDBOSIsLaunched)('setWorkflowDelay');
748
837
  const delayUntilEpochMS = resolveDelayEpochMS(options);
749
- return runInternalStep(async () => {
838
+ const shardKey = typeof options === 'object' ? options.shardKey : undefined;
839
+ return (0, shard_keys_1.bindShardKeys)([[workflowID, shardKey]], () => runInternalStep(async () => {
750
840
  return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.setWorkflowDelay(workflowID, delayUntilEpochMS);
751
- }, 'DBOS.setWorkflowDelay');
841
+ }, 'DBOS.setWorkflowDelay'));
752
842
  }
753
843
  /**
754
844
  * Retrieve the steps of a workflow
@@ -758,9 +848,9 @@ class DBOS {
758
848
  */
759
849
  static async listWorkflowSteps(workflowID, options) {
760
850
  (0, decorators_1.ensureDBOSIsLaunched)('listWorkflowSteps');
761
- return await runInternalStep(async () => {
851
+ return await (0, shard_keys_1.bindShardKeys)([[workflowID, options?.shardKey]], () => runInternalStep(async () => {
762
852
  return await DBOS.#executor.listWorkflowSteps(workflowID, true, options);
763
- }, 'DBOS.listWorkflowSteps');
853
+ }, 'DBOS.listWorkflowSteps'));
764
854
  }
765
855
  /**
766
856
  * Cancel a workflow given its ID.
@@ -779,9 +869,9 @@ class DBOS {
779
869
  */
780
870
  static async cancelWorkflows(workflowIDs, options) {
781
871
  (0, decorators_1.ensureDBOSIsLaunched)('cancelWorkflows');
782
- return runInternalStep(async () => {
872
+ return (0, shard_keys_1.bindShardKeys)(workflowIDs.map((wid) => [wid, options?.shardKey]), () => runInternalStep(async () => {
783
873
  return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.cancelWorkflows(workflowIDs, options?.cancelChildren);
784
- }, 'DBOS.cancelWorkflow');
874
+ }, 'DBOS.cancelWorkflow'));
785
875
  }
786
876
  /**
787
877
  * Resume a workflow given its ID.
@@ -789,8 +879,11 @@ class DBOS {
789
879
  * @throws DBOSNonExistentWorkflowError if the workflow does not exist
790
880
  */
791
881
  static async resumeWorkflow(workflowID, options) {
792
- const handles = await this.resumeWorkflows([workflowID], options);
793
- return handles[0];
882
+ return await (0, shard_keys_1.bindShardKeys)([[workflowID, options?.shardKey]], async () => {
883
+ await this.resumeWorkflows([workflowID], options);
884
+ // The resolved key, so the handle also works outside this binding.
885
+ return new workflow_1.RetrievedHandle(workflowID, DBOS.#executor.systemDatabase.keyHint(workflowID));
886
+ });
794
887
  }
795
888
  /**
796
889
  * Resume multiple workflows given their IDs.
@@ -800,10 +893,12 @@ class DBOS {
800
893
  */
801
894
  static async resumeWorkflows(workflowIDs, options) {
802
895
  (0, decorators_1.ensureDBOSIsLaunched)('resumeWorkflows');
803
- await runInternalStep(async () => {
804
- return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.resumeWorkflows(workflowIDs, options?.queueName);
805
- }, 'DBOS.resumeWorkflow');
806
- return workflowIDs.map((wfid) => this.retrieveWorkflow(wfid));
896
+ return await (0, shard_keys_1.bindShardKeys)(workflowIDs.map((wid) => [wid, options?.shardKey]), async () => {
897
+ await runInternalStep(async () => {
898
+ return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.resumeWorkflows(workflowIDs, options?.queueName);
899
+ }, 'DBOS.resumeWorkflow');
900
+ return workflowIDs.map((wfid) => new workflow_1.RetrievedHandle(wfid, options?.shardKey));
901
+ });
807
902
  }
808
903
  /**
809
904
  * Delete a workflow and optionally all its child workflows.
@@ -814,8 +909,8 @@ class DBOS {
814
909
  * @param workflowID - ID of the workflow to delete
815
910
  * @param deleteChildren - If true, also delete all child workflows recursively (default: false)
816
911
  */
817
- static async deleteWorkflow(workflowID, deleteChildren = false) {
818
- return this.deleteWorkflows([workflowID], deleteChildren);
912
+ static async deleteWorkflow(workflowID, deleteChildren = false, options) {
913
+ return this.deleteWorkflows([workflowID], deleteChildren, options);
819
914
  }
820
915
  /**
821
916
  * Delete multiple workflows and optionally all their child workflows.
@@ -825,11 +920,11 @@ class DBOS {
825
920
  * @param workflowIDs - IDs of the workflows to delete
826
921
  * @param deleteChildren - If true, also delete all child workflows recursively (default: false)
827
922
  */
828
- static async deleteWorkflows(workflowIDs, deleteChildren = false) {
923
+ static async deleteWorkflows(workflowIDs, deleteChildren = false, options) {
829
924
  (0, decorators_1.ensureDBOSIsLaunched)('deleteWorkflows');
830
- return runInternalStep(async () => {
925
+ return (0, shard_keys_1.bindShardKeys)(workflowIDs.map((wid) => [wid, options?.shardKey]), () => runInternalStep(async () => {
831
926
  return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.deleteWorkflows(workflowIDs, deleteChildren);
832
- }, 'DBOS.deleteWorkflow');
927
+ }, 'DBOS.deleteWorkflow'));
833
928
  }
834
929
  /**
835
930
  * Fork a workflow given its ID.
@@ -841,10 +936,14 @@ class DBOS {
841
936
  */
842
937
  static async forkWorkflow(workflowID, startStep, options) {
843
938
  (0, decorators_1.ensureDBOSIsLaunched)('forkWorkflow');
844
- const forkedID = await runInternalStep(async () => {
845
- return await DBOS.#executor.forkWorkflow(workflowID, startStep, options);
846
- }, 'DBOS.forkWorkflow');
847
- return this.retrieveWorkflow(forkedID);
939
+ return await (0, shard_keys_1.bindShardKeys)([[workflowID, options?.shardKey]], async () => {
940
+ const forkedID = await runInternalStep(async () => {
941
+ return await DBOS.#executor.forkWorkflow(workflowID, startStep, options);
942
+ }, 'DBOS.forkWorkflow');
943
+ // A fork lives under its original's shard key, however the caller supplied it.
944
+ const forkKey = DBOS.#executor.systemDatabase.keyHint(workflowID);
945
+ return new workflow_1.RetrievedHandle(forkedID, forkKey);
946
+ });
848
947
  }
849
948
  /**
850
949
  * Rewind a workflow given its ID: drop its recorded history from `startStep` onwards
@@ -868,10 +967,13 @@ class DBOS {
868
967
  static async rewindWorkflow(workflowID, options) {
869
968
  (0, decorators_1.ensureDBOSIsLaunched)('rewindWorkflow');
870
969
  const startStep = options?.startStep ?? 0;
871
- await runInternalStep(async () => {
872
- return await DBOS.#executor.rewindWorkflow(workflowID, startStep, options ?? {});
873
- }, 'DBOS.rewindWorkflow');
874
- return this.retrieveWorkflow(workflowID);
970
+ return await (0, shard_keys_1.bindShardKeys)([[workflowID, options?.shardKey]], async () => {
971
+ await runInternalStep(async () => {
972
+ return await DBOS.#executor.rewindWorkflow(workflowID, startStep, options ?? {});
973
+ }, 'DBOS.rewindWorkflow');
974
+ // The resolved key, so the handle also works outside this binding.
975
+ return new workflow_1.RetrievedHandle(workflowID, DBOS.#executor.systemDatabase.keyHint(workflowID));
976
+ });
875
977
  }
876
978
  /**
877
979
  * Sleep for the specified amount of time.
@@ -880,8 +982,9 @@ class DBOS {
880
982
  * (calculated by adding `durationMS` to the original invocation time),
881
983
  * regardless of workflow recovery.
882
984
  * @param durationMS - Length of sleep, in milliseconds.
985
+ * @param options - {@link SleepOptions}
883
986
  */
884
- static async sleepms(durationMS) {
987
+ static async sleepms(durationMS, options) {
885
988
  if (!Number.isFinite(durationMS)) {
886
989
  throw new error_1.DBOSError('sleep duration must be a finite number of milliseconds');
887
990
  }
@@ -894,7 +997,16 @@ class DBOS {
894
997
  if (durationMS <= 0) {
895
998
  return;
896
999
  }
897
- return await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.durableSleepms(DBOS.workflowID, functionID, durationMS);
1000
+ const sysdb = dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase;
1001
+ if (options?.suspend) {
1002
+ const remainingMS = await requireSuspendMode('sleep').sleepSuspend(DBOS.workflowID, functionID, durationMS);
1003
+ const endTime = Date.now() + remainingMS;
1004
+ while (Date.now() < endTime) {
1005
+ await (0, utils_1.sleepms)(Math.min(endTime - Date.now(), utils_1.sleepConfig.maxTimeoutMS));
1006
+ }
1007
+ return await sysdb.checkIfCanceled(DBOS.workflowID);
1008
+ }
1009
+ return await sysdb.durableSleepms(DBOS.workflowID, functionID, durationMS);
898
1010
  }
899
1011
  const endTime = Date.now() + durationMS;
900
1012
  while (Date.now() < endTime) {
@@ -902,12 +1014,12 @@ class DBOS {
902
1014
  }
903
1015
  }
904
1016
  /** @see sleepms */
905
- static async sleepSeconds(durationSec) {
906
- return DBOS.sleepms(durationSec * 1000);
1017
+ static async sleepSeconds(durationSec, options) {
1018
+ return DBOS.sleepms(durationSec * 1000, options);
907
1019
  }
908
1020
  /** @see sleepms */
909
- static async sleep(durationMS) {
910
- return DBOS.sleepms(durationMS);
1021
+ static async sleep(durationMS, options) {
1022
+ return DBOS.sleepms(durationMS, options);
911
1023
  }
912
1024
  /**
913
1025
  * Get the current time in milliseconds, similar to `Date.now()`.
@@ -986,6 +1098,13 @@ class DBOS {
986
1098
  (0, decorators_1.ensureDBOSIsLaunched)('workflows');
987
1099
  return DBOS.#withTopContext({ workflowTimeoutMS: timeoutMS }, callback);
988
1100
  }
1101
+ /** Set the shard key of each workflow started, enqueued, or called in `callback`; their children don't inherit it. */
1102
+ static async withShardKey(shardKey, callback) {
1103
+ if (typeof shardKey !== 'string' || shardKey === '') {
1104
+ throw new error_1.DBOSError('shardKey must be a non-empty string');
1105
+ }
1106
+ return DBOS.#withTopContext({ shardKeyForNextWorkflow: shardKey }, callback);
1107
+ }
989
1108
  static async #withTopContext(options, callback) {
990
1109
  const pctx = (0, context_1.getCurrentContextStore)();
991
1110
  if (pctx) {
@@ -1073,16 +1192,16 @@ class DBOS {
1073
1192
  // calls in the same workflow don't race for IDs.
1074
1193
  const functionID = (0, context_1.functionIDGetIncrement)();
1075
1194
  const sermsg = await (0, serialization_1.serializeValue)(message, DBOS.#executor.serializer, options?.serializationType ?? DBOS.#defaultSerializationType);
1076
- return await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.send(DBOS.workflowID, functionID, destinationID, sermsg.serializedValue, topic, sermsg.serialization, idempotencyKey);
1195
+ return await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.send(DBOS.workflowID, functionID, destinationID, sermsg.serializedValue, topic, sermsg.serialization, idempotencyKey, options?.shardKey);
1077
1196
  }
1078
1197
  else if (DBOS.isInStep()) {
1079
1198
  // Inside a step: not recorded, but fenced on the enclosing workflow's ownership.
1080
1199
  const sermsg = await (0, serialization_1.serializeValue)(message, DBOS.#executor.serializer, options?.serializationType ?? DBOS.#defaultSerializationType);
1081
- return await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.sendFromStep(DBOS.workflowID, destinationID, sermsg.serializedValue, topic, sermsg.serialization, idempotencyKey);
1200
+ return await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.sendFromStep(DBOS.workflowID, destinationID, sermsg.serializedValue, topic, sermsg.serialization, idempotencyKey, options?.shardKey);
1082
1201
  }
1083
1202
  else {
1084
1203
  const sermsg = await (0, serialization_1.serializeValue)(message, DBOS.#executor.serializer, options?.serializationType ?? DBOS.#defaultSerializationType);
1085
- return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.sendDirect(destinationID, sermsg.serializedValue, topic, sermsg.serialization, idempotencyKey);
1204
+ return dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.sendDirect(destinationID, sermsg.serializedValue, topic, sermsg.serialization, idempotencyKey, undefined, options?.shardKey);
1086
1205
  }
1087
1206
  }
1088
1207
  /**
@@ -1108,11 +1227,66 @@ class DBOS {
1108
1227
  const timeoutFunctionID = (0, context_1.functionIDGetIncrement)();
1109
1228
  const timeoutSeconds = resolveTimeoutSeconds(options);
1110
1229
  const pollingIntervalMs = resolvePollingIntervalMs(options);
1111
- const msg = await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.recv(DBOS.workflowID, functionID, timeoutFunctionID, topic, timeoutSeconds, pollingIntervalMs);
1230
+ const msg = typeof options === 'object' && options.suspend
1231
+ ? await requireSuspendMode('recv').recvSuspend(DBOS.workflowID, functionID, timeoutFunctionID, topic, timeoutSeconds)
1232
+ : await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.recv(DBOS.workflowID, functionID, timeoutFunctionID, topic, timeoutSeconds, pollingIntervalMs);
1112
1233
  return (await (0, serialization_1.deserializeValue)(msg.serializedValue, msg.serialization, DBOS.#executor.serializer));
1113
1234
  }
1114
1235
  throw new error_1.DBOSInvalidWorkflowTransitionError('Attempt to call `DBOS.recv` outside of a workflow'); // Only workflows can recv
1115
1236
  }
1237
+ static #externalStorage() {
1238
+ const storage = DBOS.#executor.externalStorage;
1239
+ if (storage === undefined) {
1240
+ throw new error_1.DBOSExternalStoreNotConfiguredError(undefined, []);
1241
+ }
1242
+ return storage;
1243
+ }
1244
+ /**
1245
+ * Upload a value to an external store (if there are multiple, specify one with `storeID`) and return a ref to it.
1246
+ * A `Uint8Array` value, such as a `Buffer`, is stored as is, without serialization, which is fastest for large
1247
+ * objects, and loads as a `Buffer`.
1248
+ * @param value - The value to store
1249
+ * @param options - {@link StoreExternalObjectOptions}; outside a workflow, `ownerWorkflowID` is required
1250
+ * @returns A ref to pass to `DBOS.loadExternalObject`
1251
+ */
1252
+ static async storeExternalObject(value, options = {}) {
1253
+ (0, decorators_1.ensureDBOSIsLaunched)('storeExternalObject');
1254
+ const storage = DBOS.#externalStorage();
1255
+ const ctx = (0, context_1.getCurrentContextStore)();
1256
+ const owner = options.ownerWorkflowID ?? ctx?.workflowId;
1257
+ if (owner === undefined) {
1258
+ throw new error_1.DBOSError('storeExternalObject called outside a workflow requires an ownerWorkflowID');
1259
+ }
1260
+ // Another key would hide the object from its owner, so retention would collect it while the owner lives.
1261
+ if (ctx?.workflowId === owner &&
1262
+ ctx.shardKey !== undefined &&
1263
+ options.shardKey !== undefined &&
1264
+ options.shardKey !== ctx.shardKey) {
1265
+ throw new error_1.DBOSError(`storeExternalObject's shardKey ${options.shardKey} differs from workflow ${owner}'s shard key ${ctx.shardKey}`);
1266
+ }
1267
+ const store = async () => (await storage.store(value, {
1268
+ ownerWorkflowID: owner,
1269
+ serializationType: options.serializationType ?? DBOS.#defaultSerializationType,
1270
+ key: options.key,
1271
+ storeID: options.storeID,
1272
+ }));
1273
+ return await (0, shard_keys_1.bindShardKeys)([[owner, options.shardKey]], () => DBOS.isInWorkflow() ? DBOS.runStep(store, { name: 'DBOS.storeExternalObject' }) : store());
1274
+ }
1275
+ /**
1276
+ * Load the value an external object ref points to. Call it from a step, not a workflow, and use the value
1277
+ * in that step: a step's return value is checkpointed, so return only a small result.
1278
+ * @param ref - A ref returned by `storeExternalObject`
1279
+ * @returns The stored value
1280
+ */
1281
+ static async loadExternalObject(ref) {
1282
+ (0, decorators_1.ensureDBOSIsLaunched)('loadExternalObject');
1283
+ // A load is I/O, so it belongs in a step's retries and checkpointed errors, not a workflow body.
1284
+ if (DBOS.isInWorkflow()) {
1285
+ throw new error_1.DBOSError('loadExternalObject may not be called from a workflow. Call it from a step and use the value there: ' +
1286
+ "a step's return value is checkpointed, so return only a small result.");
1287
+ }
1288
+ return (await DBOS.#externalStorage().get(ref));
1289
+ }
1116
1290
  /**
1117
1291
  * Set an event, from within a DBOS workflow. This value can be retrieved with `DBOS.getEvent`.
1118
1292
  * If the event `key` already exists, its `value` is updated.
@@ -1150,6 +1324,10 @@ class DBOS {
1150
1324
  */
1151
1325
  static async getEvent(workflowID, key, options) {
1152
1326
  (0, decorators_1.ensureDBOSIsLaunched)('getEvent');
1327
+ const shardKey = typeof options === 'object' ? options.shardKey : undefined;
1328
+ return await (0, shard_keys_1.bindShardKeys)([[workflowID, shardKey]], () => DBOS.#getEvent(workflowID, key, options));
1329
+ }
1330
+ static async #getEvent(workflowID, key, options) {
1153
1331
  const timeoutSeconds = resolveTimeoutSeconds(options);
1154
1332
  const pollingIntervalMs = resolvePollingIntervalMs(options);
1155
1333
  if (DBOS.isWithinWorkflow()) {
@@ -1227,6 +1405,7 @@ class DBOS {
1227
1405
  timeoutMS: resolveStreamTimeoutMS(options),
1228
1406
  functionName: system_database_1.DBOS_FUNCNAME_READSTREAM,
1229
1407
  checkpoint: true,
1408
+ shardKey: options.shardKey,
1230
1409
  });
1231
1410
  }
1232
1411
  /**
@@ -1250,6 +1429,7 @@ class DBOS {
1250
1429
  timeoutMS: resolveStreamTimeoutMS(options),
1251
1430
  functionName: system_database_1.DBOS_FUNCNAME_READSTREAMOFFSET,
1252
1431
  checkpoint: true,
1432
+ shardKey: options.shardKey,
1253
1433
  });
1254
1434
  }
1255
1435
  //////
@@ -1306,6 +1486,8 @@ class DBOS {
1306
1486
  const ppctx = (0, context_1.getCurrentContextStore)();
1307
1487
  const queueName = params.queueName ?? ppctx?.queueAssignedForWorkflows;
1308
1488
  const timeoutMS = params.timeoutMS ?? ppctx?.workflowTimeoutMS;
1489
+ // Set by DBOS.withShardKey; a workflow never inherits its caller's own key.
1490
+ const shardKey = (0, context_1.nextWorkflowShardKey)(ppctx);
1309
1491
  const instance = $this === undefined || typeof $this === 'function' ? undefined : $this;
1310
1492
  if (instance && !(instance instanceof decorators_1.ConfiguredInstance)) {
1311
1493
  throw new error_1.DBOSInvalidWorkflowTransitionError('Attempt to call a `workflow` function on an object that is not a `ConfiguredInstance`');
@@ -1343,7 +1525,7 @@ class DBOS {
1343
1525
  if (isChild) {
1344
1526
  const pwfid = ppctx.workflowId;
1345
1527
  const wfParams = {
1346
- workflowUUID: wfId || pwfid + '-' + funcId,
1528
+ workflowUUID: wfId || (0, context_1.childWorkflowID)(pwfid, funcId, ppctx?.shardKey, shardKey),
1347
1529
  configuredInstance: instance,
1348
1530
  queueName,
1349
1531
  timeoutMS,
@@ -1355,6 +1537,7 @@ class DBOS {
1355
1537
  workflowAttributes: params.workflowAttributes,
1356
1538
  authenticatedUser: params.authenticatedUser,
1357
1539
  authenticatedRoles: params.authenticatedRoles,
1540
+ shardKey,
1358
1541
  };
1359
1542
  return await invokeRegOp(wfParams, pwfid, funcId);
1360
1543
  }
@@ -1370,6 +1553,7 @@ class DBOS {
1370
1553
  workflowAttributes: params.workflowAttributes,
1371
1554
  authenticatedUser: params.authenticatedUser,
1372
1555
  authenticatedRoles: params.authenticatedRoles,
1556
+ shardKey,
1373
1557
  };
1374
1558
  return await invokeRegOp(wfParams, undefined, undefined);
1375
1559
  }
@@ -1396,6 +1580,8 @@ class DBOS {
1396
1580
  // Reserve the parent's child-funcID once, before any await. Each loop iteration passes it
1397
1581
  // through so the return-existing retry loop consumes a single funcID instead of one per try.
1398
1582
  const childFuncId = DBOS.isInWorkflow() ? (0, context_1.functionIDGetIncrement)() : undefined;
1583
+ // The key the attached-to workflow lives under, as the start would have used.
1584
+ const shardKey = (0, context_1.nextWorkflowShardKey)((0, context_1.getCurrentContextStore)());
1399
1585
  // Resolve the workflow ID once: if the caller supplied one explicitly or via
1400
1586
  // `withNextWorkflowID`, reuse it on every iteration.
1401
1587
  const resolvedWorkflowID = (0, context_1.getNextWFID)(params.workflowID);
@@ -1416,7 +1602,7 @@ class DBOS {
1416
1602
  const now = Date.now();
1417
1603
  await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.recordOperationResult(DBOS.workflowID, childFuncId, regOP.name, true, now, now, { childWorkflowID: existingID });
1418
1604
  }
1419
- return new workflow_1.RetrievedHandle(existingID);
1605
+ return new workflow_1.RetrievedHandle(existingID, shardKey);
1420
1606
  }
1421
1607
  // The prior workflow's deduplication_id was cleared between our INSERT and
1422
1608
  // the lookup (it completed or was cancelled). Loop and try to claim the slot.
@@ -1700,6 +1886,7 @@ class DBOS {
1700
1886
  cronTimezone: options.options?.cronTimezone ?? null,
1701
1887
  queueName: options.options?.queueName ?? null,
1702
1888
  applicationName: utils_1.globalParams.appName,
1889
+ shardKey: options.options?.shardKey,
1703
1890
  };
1704
1891
  await runTransactionalInternalStep((client) => dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.createSchedule(schedInternal, client), 'DBOS.createSchedule');
1705
1892
  }
@@ -1785,6 +1972,7 @@ class DBOS {
1785
1972
  automaticBackfill: sched.automaticBackfill ?? false,
1786
1973
  cronTimezone: sched.cronTimezone ?? null,
1787
1974
  queueName: sched.queueName ?? null,
1975
+ shardKey: sched.shardKey,
1788
1976
  });
1789
1977
  }
1790
1978
  await dbos_executor_1.DBOSExecutor.globalInstance.systemDatabase.applySchedules(internals);
@@ -1796,7 +1984,7 @@ class DBOS {
1796
1984
  }
1797
1985
  const executor = dbos_executor_1.DBOSExecutor.globalInstance;
1798
1986
  const workflowID = await (0, scheduler_1.triggerSchedule)(executor.systemDatabase, executor.serializer, name);
1799
- return new workflow_1.RetrievedHandle(workflowID);
1987
+ return new workflow_1.RetrievedHandle(workflowID, await (0, scheduler_1.scheduleShardKey)(executor.systemDatabase, name));
1800
1988
  }
1801
1989
  static async backfillSchedule(name, start, end) {
1802
1990
  (0, decorators_1.ensureDBOSIsLaunched)('backfillSchedule');
@@ -1805,7 +1993,8 @@ class DBOS {
1805
1993
  }
1806
1994
  const executor = dbos_executor_1.DBOSExecutor.globalInstance;
1807
1995
  const workflowIDs = await (0, scheduler_1.backfillSchedule)(executor.systemDatabase, executor.serializer, name, start, end);
1808
- return workflowIDs.map((id) => new workflow_1.RetrievedHandle(id));
1996
+ const shardKey = await (0, scheduler_1.scheduleShardKey)(executor.systemDatabase, name);
1997
+ return workflowIDs.map((id) => new workflow_1.RetrievedHandle(id, shardKey));
1809
1998
  }
1810
1999
  // ==================== Application Versions ====================
1811
2000
  /**