@aws/durable-execution-sdk-js 1.0.0 → 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 (74) hide show
  1. package/README.md +3 -50
  2. package/dist/index.mjs +1874 -2017
  3. package/dist/index.mjs.map +1 -1
  4. package/dist-cjs/index.js +1873 -2016
  5. package/dist-cjs/index.js.map +1 -1
  6. package/dist-types/context/durable-context/durable-context.d.ts +0 -6
  7. package/dist-types/context/durable-context/durable-context.d.ts.map +1 -1
  8. package/dist-types/errors/durable-error/durable-error.d.ts +6 -0
  9. package/dist-types/errors/durable-error/durable-error.d.ts.map +1 -1
  10. package/dist-types/errors/step-errors/step-errors.d.ts +1 -0
  11. package/dist-types/errors/step-errors/step-errors.d.ts.map +1 -1
  12. package/dist-types/handlers/callback-handler/callback-promise.d.ts +2 -2
  13. package/dist-types/handlers/callback-handler/callback-promise.d.ts.map +1 -1
  14. package/dist-types/handlers/callback-handler/callback.d.ts +1 -2
  15. package/dist-types/handlers/callback-handler/callback.d.ts.map +1 -1
  16. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.d.ts +1 -0
  17. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.d.ts.map +1 -1
  18. package/dist-types/handlers/invoke-handler/invoke-handler.d.ts +1 -2
  19. package/dist-types/handlers/invoke-handler/invoke-handler.d.ts.map +1 -1
  20. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-handler.d.ts.map +1 -1
  21. package/dist-types/handlers/step-handler/step-handler.d.ts +1 -9
  22. package/dist-types/handlers/step-handler/step-handler.d.ts.map +1 -1
  23. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.d.ts +1 -6
  24. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.d.ts.map +1 -1
  25. package/dist-types/handlers/wait-handler/wait-handler-comparison.test.d.ts +2 -0
  26. package/dist-types/handlers/wait-handler/wait-handler-comparison.test.d.ts.map +1 -0
  27. package/dist-types/handlers/wait-handler/wait-handler.d.ts +1 -2
  28. package/dist-types/handlers/wait-handler/wait-handler.d.ts.map +1 -1
  29. package/dist-types/testing/create-test-checkpoint-manager.d.ts.map +1 -1
  30. package/dist-types/testing/create-test-durable-context.d.ts.map +1 -1
  31. package/dist-types/testing/mock-checkpoint-manager.d.ts +0 -1
  32. package/dist-types/testing/mock-checkpoint-manager.d.ts.map +1 -1
  33. package/dist-types/testing/mock-checkpoint.d.ts +1 -0
  34. package/dist-types/testing/mock-checkpoint.d.ts.map +1 -1
  35. package/dist-types/types/batch.d.ts +8 -0
  36. package/dist-types/types/batch.d.ts.map +1 -1
  37. package/dist-types/types/core.d.ts +1 -3
  38. package/dist-types/types/core.d.ts.map +1 -1
  39. package/dist-types/types/durable-context.d.ts +8 -6
  40. package/dist-types/types/durable-context.d.ts.map +1 -1
  41. package/dist-types/types/index.d.ts +2 -0
  42. package/dist-types/types/index.d.ts.map +1 -1
  43. package/dist-types/types/operation-lifecycle-state.d.ts +27 -0
  44. package/dist-types/types/operation-lifecycle-state.d.ts.map +1 -0
  45. package/dist-types/types/operation-lifecycle.d.ts +27 -0
  46. package/dist-types/types/operation-lifecycle.d.ts.map +1 -0
  47. package/dist-types/utils/checkpoint/checkpoint-ancestor.test.d.ts +2 -0
  48. package/dist-types/utils/checkpoint/checkpoint-ancestor.test.d.ts.map +1 -0
  49. package/dist-types/utils/checkpoint/checkpoint-central-termination.test.d.ts +2 -0
  50. package/dist-types/utils/checkpoint/checkpoint-central-termination.test.d.ts.map +1 -0
  51. package/dist-types/utils/checkpoint/checkpoint-helper.d.ts +37 -0
  52. package/dist-types/utils/checkpoint/checkpoint-helper.d.ts.map +1 -1
  53. package/dist-types/utils/checkpoint/checkpoint-manager.d.ts +37 -12
  54. package/dist-types/utils/checkpoint/checkpoint-manager.d.ts.map +1 -1
  55. package/dist-types/utils/constants/constants.d.ts +0 -1
  56. package/dist-types/utils/constants/constants.d.ts.map +1 -1
  57. package/dist-types/utils/durable-execution-invocation-input/durable-execution-invocation-input.d.ts +3 -1
  58. package/dist-types/utils/durable-execution-invocation-input/durable-execution-invocation-input.d.ts.map +1 -1
  59. package/dist-types/utils/durable-execution-invocation-input/durable-execution-invocation-input.test.d.ts +2 -0
  60. package/dist-types/utils/durable-execution-invocation-input/durable-execution-invocation-input.test.d.ts.map +1 -0
  61. package/dist-types/utils/termination-helper/termination-helper.d.ts +0 -9
  62. package/dist-types/utils/termination-helper/termination-helper.d.ts.map +1 -1
  63. package/dist-types/with-durable-execution.d.ts.map +1 -1
  64. package/package.json +8 -3
  65. package/dist-types/utils/checkpoint/checkpoint-ancestor-checking.test.d.ts +0 -2
  66. package/dist-types/utils/checkpoint/checkpoint-ancestor-checking.test.d.ts.map +0 -1
  67. package/dist-types/utils/termination-helper/active-operations-tracker.d.ts +0 -31
  68. package/dist-types/utils/termination-helper/active-operations-tracker.d.ts.map +0 -1
  69. package/dist-types/utils/termination-helper/active-operations-tracker.test.d.ts +0 -2
  70. package/dist-types/utils/termination-helper/active-operations-tracker.test.d.ts.map +0 -1
  71. package/dist-types/utils/wait-before-continue/wait-before-continue.d.ts +0 -35
  72. package/dist-types/utils/wait-before-continue/wait-before-continue.d.ts.map +0 -1
  73. package/dist-types/utils/wait-before-continue/wait-before-continue.test.d.ts +0 -2
  74. package/dist-types/utils/wait-before-continue/wait-before-continue.test.d.ts.map +0 -1
package/dist-cjs/index.js CHANGED
@@ -300,6 +300,34 @@ class DurablePromise {
300
300
  }
301
301
  }
302
302
 
303
+ /**
304
+ * Represents the lifecycle state of an operation in the durable execution system.
305
+ * This is distinct from AWS SDK's OperationStatus (PENDING, SUCCEEDED, FAILED).
306
+ */
307
+ var OperationLifecycleState;
308
+ (function (OperationLifecycleState) {
309
+ /**
310
+ * Operation is currently executing user code (step function, waitForCondition check)
311
+ */
312
+ OperationLifecycleState["EXECUTING"] = "EXECUTING";
313
+ /**
314
+ * Operation is waiting for retry timer to expire before re-executing user code
315
+ */
316
+ OperationLifecycleState["RETRY_WAITING"] = "RETRY_WAITING";
317
+ /**
318
+ * Operation is waiting for external event (timer, callback, invoke) but not awaited yet (phase 1)
319
+ */
320
+ OperationLifecycleState["IDLE_NOT_AWAITED"] = "IDLE_NOT_AWAITED";
321
+ /**
322
+ * Operation is waiting for external event and has been awaited (phase 2)
323
+ */
324
+ OperationLifecycleState["IDLE_AWAITED"] = "IDLE_AWAITED";
325
+ /**
326
+ * Operation has completed (success or permanent failure)
327
+ */
328
+ OperationLifecycleState["COMPLETED"] = "COMPLETED";
329
+ })(OperationLifecycleState || (OperationLifecycleState = {}));
330
+
303
331
  /**
304
332
  * Converts a Duration object to total seconds
305
333
  * @param duration - Duration object with at least one time unit specified
@@ -313,6 +341,21 @@ function durationToSeconds(duration) {
313
341
  return days * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60 + seconds;
314
342
  }
315
343
 
344
+ /**
345
+ * Terminates execution for unrecoverable errors and returns a never-resolving promise
346
+ * @param context - The execution context containing the termination manager
347
+ * @param error - The unrecoverable error that caused termination
348
+ * @param stepIdentifier - The step name or ID for error messaging
349
+ * @returns A never-resolving promise
350
+ */
351
+ function terminateForUnrecoverableError(context, error, stepIdentifier) {
352
+ context.terminationManager.terminate({
353
+ reason: error.terminationReason,
354
+ message: `Unrecoverable error in step ${stepIdentifier}: ${error.message}`,
355
+ });
356
+ return new Promise(() => { }); // Never-resolving promise
357
+ }
358
+
316
359
  const safeStringify = (data) => {
317
360
  try {
318
361
  const seen = new WeakSet();
@@ -346,238 +389,6 @@ const log = (emoji, message, data) => {
346
389
  }
347
390
  };
348
391
 
349
- var TerminationReason;
350
- (function (TerminationReason) {
351
- // Default termination reason
352
- TerminationReason["OPERATION_TERMINATED"] = "OPERATION_TERMINATED";
353
- // Retry-related reasons
354
- TerminationReason["RETRY_SCHEDULED"] = "RETRY_SCHEDULED";
355
- TerminationReason["RETRY_INTERRUPTED_STEP"] = "RETRY_INTERRUPTED_STEP";
356
- // Wait-related reasons
357
- TerminationReason["WAIT_SCHEDULED"] = "WAIT_SCHEDULED";
358
- // Callback-related reasons
359
- TerminationReason["CALLBACK_PENDING"] = "CALLBACK_PENDING";
360
- // Error-related reasons
361
- TerminationReason["CHECKPOINT_FAILED"] = "CHECKPOINT_FAILED";
362
- TerminationReason["SERDES_FAILED"] = "SERDES_FAILED";
363
- TerminationReason["CONTEXT_VALIDATION_ERROR"] = "CONTEXT_VALIDATION_ERROR";
364
- // Custom reason
365
- TerminationReason["CUSTOM"] = "CUSTOM";
366
- })(TerminationReason || (TerminationReason = {}));
367
-
368
- const asyncLocalStorage = new async_hooks.AsyncLocalStorage();
369
- const getActiveContext = () => {
370
- return asyncLocalStorage.getStore();
371
- };
372
- const runWithContext = (contextId, parentId, fn, attempt, durableExecutionMode) => {
373
- return asyncLocalStorage.run({ contextId, parentId, attempt, durableExecutionMode }, fn);
374
- };
375
- const validateContextUsage = (operationContextId, operationName, terminationManager) => {
376
- const contextId = operationContextId || "root";
377
- const activeContext = getActiveContext();
378
- if (!activeContext) {
379
- return;
380
- }
381
- if (activeContext.contextId !== contextId) {
382
- const errorMessage = `Context usage error in "${operationName}": You are using a parent or sibling context instead of the current child context. Expected context ID: "${activeContext.contextId}", but got: "${operationContextId}". When inside runInChildContext(), you must use the child context parameter, not the parent context.`;
383
- terminationManager.terminate({
384
- reason: TerminationReason.CONTEXT_VALIDATION_ERROR,
385
- message: errorMessage,
386
- error: new Error(errorMessage),
387
- });
388
- // Only call termination manager, don't throw or return promise
389
- }
390
- };
391
-
392
- const HASH_LENGTH = 16;
393
- /**
394
- * Creates an MD5 hash of the input string for better performance than SHA-256
395
- * @param input - The string to hash
396
- * @returns The truncated hexadecimal hash string
397
- */
398
- const hashId = (input) => {
399
- return crypto.createHash("md5")
400
- .update(input)
401
- .digest("hex")
402
- .substring(0, HASH_LENGTH);
403
- };
404
- /**
405
- * Helper function to get step data using the original stepId
406
- * This function handles the hashing internally so callers don't need to worry about it
407
- * @param stepData - The stepData record from context
408
- * @param stepId - The original stepId (will be hashed internally)
409
- * @returns The operation data or undefined if not found
410
- */
411
- const getStepData = (stepData, stepId) => {
412
- const hashedId = hashId(stepId);
413
- return stepData[hashedId];
414
- };
415
-
416
- /**
417
- * Checks if any ancestor operation in the parent chain has finished (SUCCEEDED or FAILED)
418
- * or has a pending completion checkpoint
419
- */
420
- function hasFinishedAncestor(context, parentId) {
421
- if (!parentId) {
422
- log("🔍", "hasFinishedAncestor: No parentId provided");
423
- return false;
424
- }
425
- // First check if any ancestor has a pending completion checkpoint
426
- if (hasPendingAncestorCompletion(context, parentId)) {
427
- log("🔍", "hasFinishedAncestor: Found ancestor with pending completion!", {
428
- parentId,
429
- });
430
- return true;
431
- }
432
- let currentHashedId = hashId(parentId);
433
- log("🔍", "hasFinishedAncestor: Starting check", {
434
- parentId,
435
- initialHashedId: currentHashedId,
436
- });
437
- while (currentHashedId) {
438
- const parentOperation = context._stepData[currentHashedId];
439
- log("🔍", "hasFinishedAncestor: Checking operation", {
440
- hashedId: currentHashedId,
441
- hasOperation: !!parentOperation,
442
- status: parentOperation?.Status,
443
- type: parentOperation?.Type,
444
- });
445
- if (parentOperation?.Status === clientLambda.OperationStatus.SUCCEEDED ||
446
- parentOperation?.Status === clientLambda.OperationStatus.FAILED) {
447
- log("🔍", "hasFinishedAncestor: Found finished ancestor!", {
448
- hashedId: currentHashedId,
449
- status: parentOperation.Status,
450
- });
451
- return true;
452
- }
453
- currentHashedId = parentOperation?.ParentId;
454
- }
455
- log("🔍", "hasFinishedAncestor: No finished ancestor found");
456
- return false;
457
- }
458
- /**
459
- * Checks if any ancestor has a pending completion checkpoint
460
- */
461
- function hasPendingAncestorCompletion(context, stepId) {
462
- let currentHashedId = hashId(stepId);
463
- while (currentHashedId) {
464
- if (context.pendingCompletions.has(currentHashedId)) {
465
- return true;
466
- }
467
- const operation = context._stepData[currentHashedId];
468
- currentHashedId = operation?.ParentId;
469
- }
470
- return false;
471
- }
472
- /**
473
- * Terminates execution and returns a never-resolving promise to prevent code progression
474
- * @param context - The execution context containing the termination manager
475
- * @param reason - The termination reason
476
- * @param message - The termination message
477
- * @returns A never-resolving promise
478
- */
479
- function terminate(context, reason, message) {
480
- const activeContext = getActiveContext();
481
- // If we have a parent context, add delay to let checkpoints process
482
- if (activeContext?.parentId) {
483
- return new Promise(async (_resolve, _reject) => {
484
- // Wait a tick to let any pending checkpoints start processing
485
- await new Promise((resolve) => setImmediate(resolve));
486
- log("🔍", "Terminate called - checking context:", {
487
- hasActiveContext: !!activeContext,
488
- contextId: activeContext?.contextId,
489
- parentId: activeContext?.parentId,
490
- reason,
491
- message,
492
- });
493
- const ancestorFinished = hasFinishedAncestor(context, activeContext.parentId);
494
- log("🔍", "Ancestor check result:", {
495
- parentId: activeContext.parentId,
496
- ancestorFinished,
497
- });
498
- if (ancestorFinished) {
499
- log("🛑", "Skipping termination - ancestor already finished:", {
500
- contextId: activeContext.contextId,
501
- parentId: activeContext.parentId,
502
- reason,
503
- message,
504
- });
505
- // Return never-resolving promise without terminating
506
- return;
507
- }
508
- // Check if there are active operations before terminating
509
- const tracker = context.activeOperationsTracker;
510
- if (tracker && tracker.hasActive()) {
511
- log("⏳", "Deferring termination - active operations in progress:", {
512
- activeCount: tracker.getCount(),
513
- reason,
514
- message,
515
- });
516
- // Wait for operations to complete, then terminate
517
- const checkInterval = setInterval(() => {
518
- if (!tracker.hasActive()) {
519
- clearInterval(checkInterval);
520
- log("✅", "Active operations completed, proceeding with termination:", {
521
- reason,
522
- message,
523
- });
524
- context.terminationManager.terminate({
525
- reason,
526
- message,
527
- });
528
- }
529
- }, 10);
530
- return;
531
- }
532
- // No active operations, terminate immediately
533
- context.terminationManager.terminate({
534
- reason,
535
- message,
536
- });
537
- });
538
- }
539
- // No parent context - check active operations and terminate
540
- const tracker = context.activeOperationsTracker;
541
- if (tracker && tracker.hasActive()) {
542
- log("⏳", "Deferring termination - active operations in progress:", {
543
- activeCount: tracker.getCount(),
544
- reason,
545
- message,
546
- });
547
- return new Promise((_resolve, _reject) => {
548
- const checkInterval = setInterval(() => {
549
- if (!tracker.hasActive()) {
550
- clearInterval(checkInterval);
551
- log("✅", "Active operations completed, proceeding with termination:", {
552
- reason,
553
- message,
554
- });
555
- context.terminationManager.terminate({
556
- reason,
557
- message,
558
- });
559
- }
560
- }, 10);
561
- });
562
- }
563
- // No parent, no active operations - terminate immediately
564
- context.terminationManager.terminate({
565
- reason,
566
- message,
567
- });
568
- return new Promise(() => { });
569
- }
570
- /**
571
- * Terminates execution for unrecoverable errors and returns a never-resolving promise
572
- * @param context - The execution context containing the termination manager
573
- * @param error - The unrecoverable error that caused termination
574
- * @param stepIdentifier - The step name or ID for error messaging
575
- * @returns A never-resolving promise
576
- */
577
- function terminateForUnrecoverableError(context, error, stepIdentifier) {
578
- return terminate(context, error.terminationReason, `Unrecoverable error in step ${stepIdentifier}: ${error.message}`);
579
- }
580
-
581
392
  const DEFAULT_CONFIG$1 = {
582
393
  maxAttempts: 3,
583
394
  initialDelay: { seconds: 5 },
@@ -749,6 +560,7 @@ const retryPresets = {
749
560
  /**
750
561
  * Error thrown when a step with AT_MOST_ONCE_PER_RETRY semantics was started but interrupted
751
562
  * before completion.
563
+ * @public
752
564
  */
753
565
  class StepInterruptedError extends Error {
754
566
  constructor(_stepId, _stepName) {
@@ -757,13 +569,9 @@ class StepInterruptedError extends Error {
757
569
  }
758
570
  }
759
571
 
760
- /**
761
- * Shared constants to avoid circular dependencies
762
- */
763
- const OPERATIONS_COMPLETE_EVENT = "allOperationsComplete";
764
-
765
572
  /**
766
573
  * Base class for all durable operation errors
574
+ * @public
767
575
  */
768
576
  class DurableOperationError extends Error {
769
577
  cause;
@@ -812,6 +620,7 @@ class DurableOperationError extends Error {
812
620
  }
813
621
  /**
814
622
  * Error thrown when a step operation fails
623
+ * @public
815
624
  */
816
625
  class StepError extends DurableOperationError {
817
626
  errorType = "StepError";
@@ -821,6 +630,7 @@ class StepError extends DurableOperationError {
821
630
  }
822
631
  /**
823
632
  * Error thrown when a callback operation fails
633
+ * @public
824
634
  */
825
635
  class CallbackError extends DurableOperationError {
826
636
  errorType = "CallbackError";
@@ -830,6 +640,7 @@ class CallbackError extends DurableOperationError {
830
640
  }
831
641
  /**
832
642
  * Error thrown when an invoke operation fails
643
+ * @public
833
644
  */
834
645
  class InvokeError extends DurableOperationError {
835
646
  errorType = "InvokeError";
@@ -839,6 +650,7 @@ class InvokeError extends DurableOperationError {
839
650
  }
840
651
  /**
841
652
  * Error thrown when a child context operation fails
653
+ * @public
842
654
  */
843
655
  class ChildContextError extends DurableOperationError {
844
656
  errorType = "ChildContextError";
@@ -848,6 +660,7 @@ class ChildContextError extends DurableOperationError {
848
660
  }
849
661
  /**
850
662
  * Error thrown when a wait for condition operation fails
663
+ * @public
851
664
  */
852
665
  class WaitForConditionError extends DurableOperationError {
853
666
  errorType = "WaitForConditionError";
@@ -1015,6 +828,25 @@ function createClassSerdesWithDates(cls, dateProps) {
1015
828
  };
1016
829
  }
1017
830
 
831
+ var TerminationReason;
832
+ (function (TerminationReason) {
833
+ // Default termination reason
834
+ TerminationReason["OPERATION_TERMINATED"] = "OPERATION_TERMINATED";
835
+ // Retry-related reasons
836
+ TerminationReason["RETRY_SCHEDULED"] = "RETRY_SCHEDULED";
837
+ TerminationReason["RETRY_INTERRUPTED_STEP"] = "RETRY_INTERRUPTED_STEP";
838
+ // Wait-related reasons
839
+ TerminationReason["WAIT_SCHEDULED"] = "WAIT_SCHEDULED";
840
+ // Callback-related reasons
841
+ TerminationReason["CALLBACK_PENDING"] = "CALLBACK_PENDING";
842
+ // Error-related reasons
843
+ TerminationReason["CHECKPOINT_FAILED"] = "CHECKPOINT_FAILED";
844
+ TerminationReason["SERDES_FAILED"] = "SERDES_FAILED";
845
+ TerminationReason["CONTEXT_VALIDATION_ERROR"] = "CONTEXT_VALIDATION_ERROR";
846
+ // Custom reason
847
+ TerminationReason["CUSTOM"] = "CUSTOM";
848
+ })(TerminationReason || (TerminationReason = {}));
849
+
1018
850
  /**
1019
851
  * Base class for all unrecoverable errors
1020
852
  * Any error that inherits from this class indicates a fatal condition
@@ -1135,6 +967,30 @@ async function safeDeserialize(serdes, data, stepId, stepName, terminationManage
1135
967
  }
1136
968
  }
1137
969
 
970
+ const asyncLocalStorage = new async_hooks.AsyncLocalStorage();
971
+ const getActiveContext = () => {
972
+ return asyncLocalStorage.getStore();
973
+ };
974
+ const runWithContext = (contextId, parentId, fn, attempt, durableExecutionMode) => {
975
+ return asyncLocalStorage.run({ contextId, parentId, attempt, durableExecutionMode }, fn);
976
+ };
977
+ const validateContextUsage = (operationContextId, operationName, terminationManager) => {
978
+ const contextId = operationContextId || "root";
979
+ const activeContext = getActiveContext();
980
+ if (!activeContext) {
981
+ return;
982
+ }
983
+ if (activeContext.contextId !== contextId) {
984
+ const errorMessage = `Context usage error in "${operationName}": You are using a parent or sibling context instead of the current child context. Expected context ID: "${activeContext.contextId}", but got: "${operationContextId}". When inside runInChildContext(), you must use the child context parameter, not the parent context.`;
985
+ terminationManager.terminate({
986
+ reason: TerminationReason.CONTEXT_VALIDATION_ERROR,
987
+ message: errorMessage,
988
+ error: new Error(errorMessage),
989
+ });
990
+ // Only call termination manager, don't throw or return promise
991
+ }
992
+ };
993
+
1138
994
  function isErrorLike(obj) {
1139
995
  return (obj instanceof Error ||
1140
996
  (obj != null &&
@@ -1163,525 +1019,426 @@ function createErrorObjectFromError(error, data) {
1163
1019
  }
1164
1020
 
1165
1021
  /**
1166
- * Error thrown when a checkpoint operation fails due to invocation-level issues
1167
- * (e.g., 5xx errors, invalid checkpoint token)
1168
- * This will terminate the current Lambda invocation, but the execution can continue with a new invocation
1169
- */
1170
- class CheckpointUnrecoverableInvocationError extends UnrecoverableInvocationError {
1171
- terminationReason = TerminationReason.CHECKPOINT_FAILED;
1172
- constructor(message, originalError) {
1173
- super(message || "Checkpoint operation failed", originalError);
1174
- }
1175
- }
1176
- /**
1177
- * Error thrown when a checkpoint operation fails due to execution-level issues
1178
- * (e.g., 4xx errors other than invalid checkpoint token)
1179
- * This will terminate the entire execution and cannot be recovered
1022
+ * Error thrown when non-deterministic code is detected during replay
1180
1023
  */
1181
- class CheckpointUnrecoverableExecutionError extends UnrecoverableExecutionError {
1182
- terminationReason = TerminationReason.CHECKPOINT_FAILED;
1183
- constructor(message, originalError) {
1184
- super(message || "Checkpoint operation failed", originalError);
1024
+ class NonDeterministicExecutionError extends UnrecoverableExecutionError {
1025
+ terminationReason = TerminationReason.CUSTOM;
1026
+ constructor(message) {
1027
+ super(message);
1028
+ this.name = "NonDeterministicExecutionError";
1185
1029
  }
1186
1030
  }
1187
1031
 
1188
- const STEP_DATA_UPDATED_EVENT = "stepDataUpdated";
1189
- class CheckpointManager {
1190
- durableExecutionArn;
1191
- stepData;
1192
- storage;
1193
- terminationManager;
1194
- activeOperationsTracker;
1195
- stepDataEmitter;
1196
- logger;
1197
- pendingCompletions;
1198
- queue = [];
1199
- isProcessing = false;
1200
- currentTaskToken;
1201
- forceCheckpointPromises = [];
1202
- queueCompletionResolver = null;
1203
- queueCompletionTimeout = null;
1204
- MAX_PAYLOAD_SIZE = 750 * 1024; // 750KB in bytes
1205
- isTerminating = false;
1206
- static textEncoder = new TextEncoder();
1207
- constructor(durableExecutionArn, stepData, storage, terminationManager, activeOperationsTracker, initialTaskToken, stepDataEmitter, logger, pendingCompletions) {
1208
- this.durableExecutionArn = durableExecutionArn;
1209
- this.stepData = stepData;
1210
- this.storage = storage;
1211
- this.terminationManager = terminationManager;
1212
- this.activeOperationsTracker = activeOperationsTracker;
1213
- this.stepDataEmitter = stepDataEmitter;
1214
- this.logger = logger;
1215
- this.pendingCompletions = pendingCompletions;
1216
- this.currentTaskToken = initialTaskToken;
1032
+ const validateReplayConsistency = (stepId, currentOperation, checkpointData, context) => {
1033
+ // Skip validation if no checkpoint data exists or if Type is undefined (first execution)
1034
+ if (!checkpointData || !checkpointData.Type) {
1035
+ return;
1217
1036
  }
1218
- setTerminating() {
1219
- this.isTerminating = true;
1220
- log("🛑", "Checkpoint manager marked as terminating");
1221
- }
1222
- /**
1223
- * Checks if a step ID or any of its ancestors has a pending completion
1224
- */
1225
- hasPendingAncestorCompletion(stepId) {
1226
- let currentHashedId = hashId(stepId);
1227
- while (currentHashedId) {
1228
- if (this.pendingCompletions.has(currentHashedId)) {
1229
- return true;
1230
- }
1231
- const operation = this.stepData[currentHashedId];
1232
- currentHashedId = operation?.ParentId;
1233
- }
1234
- return false;
1235
- }
1236
- async forceCheckpoint() {
1237
- if (this.isTerminating) {
1238
- log("⚠️", "Force checkpoint skipped - termination in progress");
1239
- return new Promise(() => { }); // Never resolves during termination
1240
- }
1241
- return new Promise((resolve, reject) => {
1242
- this.forceCheckpointPromises.push({ resolve, reject });
1243
- if (!this.isProcessing) {
1244
- setImmediate(() => {
1245
- this.processQueue();
1246
- });
1247
- }
1248
- });
1249
- }
1250
- async waitForQueueCompletion() {
1251
- if (this.queue.length === 0 && !this.isProcessing) {
1252
- return;
1253
- }
1254
- return new Promise((resolve, reject) => {
1255
- this.queueCompletionResolver = resolve;
1256
- // Set a timeout to prevent infinite waiting
1257
- this.queueCompletionTimeout = setTimeout(() => {
1258
- this.queueCompletionResolver = null;
1259
- this.queueCompletionTimeout = null;
1260
- // Clear the queue since it's taking too long
1261
- this.clearQueue();
1262
- reject(new Error("Timeout waiting for checkpoint queue completion"));
1263
- }, 3000); // 3 second timeout
1264
- });
1037
+ // Validate operation type
1038
+ if (checkpointData.Type !== currentOperation.type) {
1039
+ const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation type mismatch for step "${stepId}". ` +
1040
+ `Expected type "${checkpointData.Type}", but got "${currentOperation.type}". ` +
1041
+ `This indicates non-deterministic control flow in your workflow code.`);
1042
+ terminateForUnrecoverableError(context, error, stepId);
1265
1043
  }
1266
- clearQueue() {
1267
- // Silently clear queue - we're terminating so no need to reject promises
1268
- this.queue = [];
1269
- this.forceCheckpointPromises = [];
1270
- // Resolve any waiting queue completion promises since we're clearing
1271
- this.notifyQueueCompletion();
1044
+ // Validate operation name (including undefined)
1045
+ if (checkpointData.Name !== currentOperation.name) {
1046
+ const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation name mismatch for step "${stepId}". ` +
1047
+ `Expected name "${checkpointData.Name ?? "undefined"}", but got "${currentOperation.name ?? "undefined"}". ` +
1048
+ `This indicates non-deterministic control flow in your workflow code.`);
1049
+ terminateForUnrecoverableError(context, error, stepId);
1272
1050
  }
1273
- // Alias for backward compatibility with Checkpoint interface
1274
- async force() {
1275
- return this.forceCheckpoint();
1051
+ // Validate operation subtype
1052
+ if (checkpointData.SubType !== currentOperation.subType) {
1053
+ const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation subtype mismatch for step "${stepId}". ` +
1054
+ `Expected subtype "${checkpointData.SubType}", but got "${currentOperation.subType}". ` +
1055
+ `This indicates non-deterministic control flow in your workflow code.`);
1056
+ terminateForUnrecoverableError(context, error, stepId);
1276
1057
  }
1277
- async checkpoint(stepId, data) {
1278
- if (this.isTerminating) {
1279
- log("⚠️", "Checkpoint skipped - termination in progress:", { stepId });
1280
- return new Promise(() => { }); // Never resolves during termination
1058
+ };
1059
+
1060
+ const createStepHandler = (context, checkpoint, parentContext, createStepId, logger, parentId) => {
1061
+ return (nameOrFn, fnOrOptions, maybeOptions) => {
1062
+ let name;
1063
+ let fn;
1064
+ let options;
1065
+ if (typeof nameOrFn === "string" || nameOrFn === undefined) {
1066
+ name = nameOrFn;
1067
+ fn = fnOrOptions;
1068
+ options = maybeOptions;
1281
1069
  }
1282
- if (this.activeOperationsTracker) {
1283
- this.activeOperationsTracker.increment();
1070
+ else {
1071
+ fn = nameOrFn;
1072
+ options = fnOrOptions;
1284
1073
  }
1285
- return new Promise((resolve, reject) => {
1286
- if (data.Action === clientLambda.OperationAction.SUCCEED ||
1287
- data.Action === clientLambda.OperationAction.FAIL) {
1288
- this.pendingCompletions.add(stepId);
1074
+ const stepId = createStepId();
1075
+ const semantics = options?.semantics || exports.StepSemantics.AtLeastOncePerRetry;
1076
+ const serdes = options?.serdes || defaultSerdes;
1077
+ // Phase 1: Execute step
1078
+ const phase1Promise = (async () => {
1079
+ let stepData = context.getStepData(stepId);
1080
+ validateReplayConsistency(stepId, { type: clientLambda.OperationType.STEP, name, subType: exports.OperationSubType.STEP }, stepData, context);
1081
+ // Check if already completed
1082
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1083
+ log("⏭️", "Step already completed:", { stepId });
1084
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1085
+ metadata: {
1086
+ stepId,
1087
+ name,
1088
+ type: clientLambda.OperationType.STEP,
1089
+ subType: exports.OperationSubType.STEP,
1090
+ parentId,
1091
+ },
1092
+ });
1093
+ return await safeDeserialize(serdes, stepData.StepDetails?.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
1289
1094
  }
1290
- const queuedItem = {
1291
- stepId,
1292
- data,
1293
- resolve: () => {
1294
- if (this.activeOperationsTracker) {
1295
- this.activeOperationsTracker.decrement();
1095
+ // Check if already failed
1096
+ if (stepData?.Status === clientLambda.OperationStatus.FAILED) {
1097
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1098
+ metadata: {
1099
+ stepId,
1100
+ name,
1101
+ type: clientLambda.OperationType.STEP,
1102
+ subType: exports.OperationSubType.STEP,
1103
+ parentId,
1104
+ },
1105
+ });
1106
+ if (stepData.StepDetails?.Error) {
1107
+ throw DurableOperationError.fromErrorObject(stepData.StepDetails.Error);
1108
+ }
1109
+ throw new StepError("Unknown error");
1110
+ }
1111
+ // Check if pending retry
1112
+ if (stepData?.Status === clientLambda.OperationStatus.PENDING) {
1113
+ checkpoint.markOperationState(stepId, OperationLifecycleState.RETRY_WAITING, {
1114
+ metadata: {
1115
+ stepId,
1116
+ name,
1117
+ type: clientLambda.OperationType.STEP,
1118
+ subType: exports.OperationSubType.STEP,
1119
+ parentId,
1120
+ },
1121
+ endTimestamp: stepData.StepDetails?.NextAttemptTimestamp,
1122
+ });
1123
+ return (async () => {
1124
+ await checkpoint.waitForRetryTimer(stepId);
1125
+ stepData = context.getStepData(stepId);
1126
+ return await executeStepLogic();
1127
+ })();
1128
+ }
1129
+ // Check for interrupted step with AT_MOST_ONCE_PER_RETRY
1130
+ if (stepData?.Status === clientLambda.OperationStatus.STARTED &&
1131
+ semantics === exports.StepSemantics.AtMostOncePerRetry) {
1132
+ const error = new StepInterruptedError(stepId, name);
1133
+ const currentAttempt = (stepData.StepDetails?.Attempt || 0) + 1;
1134
+ const retryDecision = options?.retryStrategy?.(error, currentAttempt) ??
1135
+ retryPresets.default(error, currentAttempt);
1136
+ if (!retryDecision.shouldRetry) {
1137
+ await checkpoint.checkpoint(stepId, {
1138
+ Id: stepId,
1139
+ ParentId: parentId,
1140
+ Action: clientLambda.OperationAction.FAIL,
1141
+ SubType: exports.OperationSubType.STEP,
1142
+ Type: clientLambda.OperationType.STEP,
1143
+ Error: createErrorObjectFromError(error),
1144
+ Name: name,
1145
+ });
1146
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1147
+ throw DurableOperationError.fromErrorObject(createErrorObjectFromError(error));
1148
+ }
1149
+ await checkpoint.checkpoint(stepId, {
1150
+ Id: stepId,
1151
+ ParentId: parentId,
1152
+ Action: clientLambda.OperationAction.RETRY,
1153
+ SubType: exports.OperationSubType.STEP,
1154
+ Type: clientLambda.OperationType.STEP,
1155
+ Error: createErrorObjectFromError(error),
1156
+ Name: name,
1157
+ StepOptions: {
1158
+ NextAttemptDelaySeconds: retryDecision.delay
1159
+ ? durationToSeconds(retryDecision.delay)
1160
+ : 1,
1161
+ },
1162
+ });
1163
+ checkpoint.markOperationState(stepId, OperationLifecycleState.RETRY_WAITING, {
1164
+ metadata: {
1165
+ stepId,
1166
+ name,
1167
+ type: clientLambda.OperationType.STEP,
1168
+ subType: exports.OperationSubType.STEP,
1169
+ parentId,
1170
+ },
1171
+ endTimestamp: context.getStepData(stepId)?.StepDetails?.NextAttemptTimestamp,
1172
+ });
1173
+ return (async () => {
1174
+ await checkpoint.waitForRetryTimer(stepId);
1175
+ stepData = context.getStepData(stepId);
1176
+ return await executeStepLogic();
1177
+ })();
1178
+ }
1179
+ return await executeStepLogic();
1180
+ async function executeStepLogic() {
1181
+ stepData = context.getStepData(stepId);
1182
+ if (stepData?.Status !== clientLambda.OperationStatus.STARTED) {
1183
+ if (semantics === exports.StepSemantics.AtMostOncePerRetry) {
1184
+ await checkpoint.checkpoint(stepId, {
1185
+ Id: stepId,
1186
+ ParentId: parentId,
1187
+ Action: clientLambda.OperationAction.START,
1188
+ SubType: exports.OperationSubType.STEP,
1189
+ Type: clientLambda.OperationType.STEP,
1190
+ Name: name,
1191
+ });
1296
1192
  }
1297
- resolve();
1298
- },
1299
- reject: (error) => {
1300
- if (this.activeOperationsTracker) {
1301
- this.activeOperationsTracker.decrement();
1193
+ else {
1194
+ checkpoint.checkpoint(stepId, {
1195
+ Id: stepId,
1196
+ ParentId: parentId,
1197
+ Action: clientLambda.OperationAction.START,
1198
+ SubType: exports.OperationSubType.STEP,
1199
+ Type: clientLambda.OperationType.STEP,
1200
+ Name: name,
1201
+ });
1302
1202
  }
1303
- reject(error);
1304
- },
1305
- };
1306
- this.queue.push(queuedItem);
1307
- log("📥", "Checkpoint queued:", {
1308
- stepId,
1309
- queueLength: this.queue.length,
1310
- isProcessing: this.isProcessing,
1311
- });
1312
- if (!this.isProcessing) {
1313
- setImmediate(() => {
1314
- this.processQueue();
1315
- });
1203
+ }
1204
+ try {
1205
+ stepData = context.getStepData(stepId);
1206
+ const currentAttempt = stepData?.StepDetails?.Attempt || 0;
1207
+ const stepContext = { logger };
1208
+ // Mark operation as EXECUTING
1209
+ checkpoint.markOperationState(stepId, OperationLifecycleState.EXECUTING, {
1210
+ metadata: {
1211
+ stepId,
1212
+ name,
1213
+ type: clientLambda.OperationType.STEP,
1214
+ subType: exports.OperationSubType.STEP,
1215
+ parentId,
1216
+ },
1217
+ });
1218
+ let result;
1219
+ result = await runWithContext(stepId, parentId, () => fn(stepContext), currentAttempt + 1, DurableExecutionMode.ExecutionMode);
1220
+ const serializedResult = await safeSerialize(serdes, result, stepId, name, context.terminationManager, context.durableExecutionArn);
1221
+ await checkpoint.checkpoint(stepId, {
1222
+ Id: stepId,
1223
+ ParentId: parentId,
1224
+ Action: clientLambda.OperationAction.SUCCEED,
1225
+ SubType: exports.OperationSubType.STEP,
1226
+ Type: clientLambda.OperationType.STEP,
1227
+ Payload: serializedResult,
1228
+ Name: name,
1229
+ });
1230
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1231
+ return await safeDeserialize(serdes, serializedResult, stepId, name, context.terminationManager, context.durableExecutionArn);
1232
+ }
1233
+ catch (error) {
1234
+ if (isUnrecoverableError(error)) {
1235
+ return terminateForUnrecoverableError(context, error, name || stepId);
1236
+ }
1237
+ stepData = context.getStepData(stepId);
1238
+ const currentAttempt = (stepData?.StepDetails?.Attempt || 0) + 1;
1239
+ const retryDecision = options?.retryStrategy?.(error instanceof Error ? error : new Error("Unknown Error"), currentAttempt) ??
1240
+ retryPresets.default(error instanceof Error ? error : new Error("Unknown Error"), currentAttempt);
1241
+ if (!retryDecision.shouldRetry) {
1242
+ await checkpoint.checkpoint(stepId, {
1243
+ Id: stepId,
1244
+ ParentId: parentId,
1245
+ Action: clientLambda.OperationAction.FAIL,
1246
+ SubType: exports.OperationSubType.STEP,
1247
+ Type: clientLambda.OperationType.STEP,
1248
+ Error: createErrorObjectFromError(error),
1249
+ Name: name,
1250
+ });
1251
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1252
+ throw DurableOperationError.fromErrorObject(createErrorObjectFromError(error));
1253
+ }
1254
+ await checkpoint.checkpoint(stepId, {
1255
+ Id: stepId,
1256
+ ParentId: parentId,
1257
+ Action: clientLambda.OperationAction.RETRY,
1258
+ SubType: exports.OperationSubType.STEP,
1259
+ Type: clientLambda.OperationType.STEP,
1260
+ Error: createErrorObjectFromError(error),
1261
+ Name: name,
1262
+ StepOptions: {
1263
+ NextAttemptDelaySeconds: retryDecision.delay
1264
+ ? durationToSeconds(retryDecision.delay)
1265
+ : 1,
1266
+ },
1267
+ });
1268
+ checkpoint.markOperationState(stepId, OperationLifecycleState.RETRY_WAITING, {
1269
+ metadata: {
1270
+ stepId,
1271
+ name,
1272
+ type: clientLambda.OperationType.STEP,
1273
+ subType: exports.OperationSubType.STEP,
1274
+ parentId,
1275
+ },
1276
+ endTimestamp: context.getStepData(stepId)?.StepDetails?.NextAttemptTimestamp,
1277
+ });
1278
+ await checkpoint.waitForRetryTimer(stepId);
1279
+ return await executeStepLogic();
1280
+ }
1316
1281
  }
1282
+ })();
1283
+ phase1Promise.catch(() => { });
1284
+ return new DurablePromise(async () => {
1285
+ checkpoint.markOperationAwaited(stepId);
1286
+ return await phase1Promise;
1317
1287
  });
1318
- }
1319
- hasFinishedAncestor(parentId) {
1320
- if (!parentId) {
1321
- return false;
1322
- }
1323
- let currentHashedId = hashId(parentId);
1324
- while (currentHashedId) {
1325
- const parentOperation = this.stepData[currentHashedId];
1326
- if (parentOperation?.Status === clientLambda.OperationStatus.SUCCEEDED ||
1327
- parentOperation?.Status === clientLambda.OperationStatus.FAILED) {
1328
- return true;
1288
+ };
1289
+ };
1290
+
1291
+ const createInvokeHandler = (context, checkpoint, createStepId, parentId, checkAndUpdateReplayMode) => {
1292
+ function invokeHandler(nameOrFuncId, funcIdOrInput, inputOrConfig, maybeConfig) {
1293
+ const isNameFirst = typeof funcIdOrInput === "string";
1294
+ const name = isNameFirst ? nameOrFuncId : undefined;
1295
+ const funcId = isNameFirst ? funcIdOrInput : nameOrFuncId;
1296
+ const input = isNameFirst
1297
+ ? inputOrConfig
1298
+ : funcIdOrInput;
1299
+ const config = isNameFirst
1300
+ ? maybeConfig
1301
+ : inputOrConfig;
1302
+ const stepId = createStepId();
1303
+ // Phase 1: Start invoke operation
1304
+ let isCompleted = false;
1305
+ const phase1Promise = (async () => {
1306
+ log("🔗", "Invoke phase 1:", { stepId, name: name || funcId });
1307
+ let stepData = context.getStepData(stepId);
1308
+ // Validate replay consistency
1309
+ validateReplayConsistency(stepId, {
1310
+ type: clientLambda.OperationType.CHAINED_INVOKE,
1311
+ name,
1312
+ subType: exports.OperationSubType.CHAINED_INVOKE,
1313
+ }, stepData, context);
1314
+ // Check if already completed
1315
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1316
+ log("⏭️", "Invoke already completed:", { stepId });
1317
+ checkAndUpdateReplayMode?.();
1318
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1319
+ metadata: {
1320
+ stepId,
1321
+ name,
1322
+ type: clientLambda.OperationType.CHAINED_INVOKE,
1323
+ subType: exports.OperationSubType.CHAINED_INVOKE,
1324
+ parentId,
1325
+ },
1326
+ });
1327
+ isCompleted = true;
1328
+ return;
1329
1329
  }
1330
- currentHashedId = parentOperation?.ParentId;
1331
- }
1332
- return false;
1333
- }
1334
- classifyCheckpointError(error) {
1335
- const originalError = error instanceof Error ? error : new Error(String(error));
1336
- const awsError = error;
1337
- const statusCode = awsError.$metadata?.httpStatusCode;
1338
- const errorName = awsError.name;
1339
- const errorMessage = awsError.message || originalError.message;
1340
- log("🔍", "Classifying checkpoint error:", {
1341
- statusCode,
1342
- errorName,
1343
- errorMessage,
1344
- });
1345
- if (statusCode &&
1346
- statusCode >= 400 &&
1347
- statusCode < 500 &&
1348
- errorName === "InvalidParameterValueException" &&
1349
- errorMessage.startsWith("Invalid Checkpoint Token")) {
1350
- return new CheckpointUnrecoverableInvocationError(`Checkpoint failed: ${errorMessage}`, originalError);
1351
- }
1352
- if (statusCode &&
1353
- statusCode >= 400 &&
1354
- statusCode < 500 &&
1355
- statusCode !== 429) {
1356
- return new CheckpointUnrecoverableExecutionError(`Checkpoint failed: ${errorMessage}`, originalError);
1357
- }
1358
- return new CheckpointUnrecoverableInvocationError(`Checkpoint failed: ${errorMessage}`, originalError);
1359
- }
1360
- async processQueue() {
1361
- if (this.isProcessing) {
1362
- return;
1363
- }
1364
- const hasQueuedItems = this.queue.length > 0;
1365
- const hasForceRequests = this.forceCheckpointPromises.length > 0;
1366
- if (!hasQueuedItems && !hasForceRequests) {
1367
- return;
1368
- }
1369
- this.isProcessing = true;
1370
- const batch = [];
1371
- let skippedCount = 0;
1372
- const baseSize = this.currentTaskToken.length + 100;
1373
- let currentSize = baseSize;
1374
- while (this.queue.length > 0) {
1375
- const nextItem = this.queue[0];
1376
- const itemSize = CheckpointManager.textEncoder.encode(JSON.stringify(nextItem)).length;
1377
- if (currentSize + itemSize > this.MAX_PAYLOAD_SIZE && batch.length > 0) {
1378
- break;
1330
+ // Check if already failed
1331
+ if (stepData?.Status === clientLambda.OperationStatus.FAILED ||
1332
+ stepData?.Status === clientLambda.OperationStatus.TIMED_OUT ||
1333
+ stepData?.Status === clientLambda.OperationStatus.STOPPED) {
1334
+ log("❌", "Invoke already failed:", { stepId });
1335
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1336
+ metadata: {
1337
+ stepId,
1338
+ name,
1339
+ type: clientLambda.OperationType.CHAINED_INVOKE,
1340
+ subType: exports.OperationSubType.CHAINED_INVOKE,
1341
+ parentId,
1342
+ },
1343
+ });
1344
+ isCompleted = true;
1345
+ return;
1379
1346
  }
1380
- this.queue.shift();
1381
- if (this.hasFinishedAncestor(nextItem.data.ParentId)) {
1382
- log("⚠️", "Checkpoint skipped - ancestor finished:", {
1383
- stepId: nextItem.stepId,
1384
- parentId: nextItem.data.ParentId,
1347
+ // Start invoke if not already started
1348
+ if (!stepData) {
1349
+ const serializedPayload = await safeSerialize(config?.payloadSerdes || defaultSerdes, input, stepId, name, context.terminationManager, context.durableExecutionArn);
1350
+ await checkpoint.checkpoint(stepId, {
1351
+ Id: stepId,
1352
+ ParentId: parentId,
1353
+ Action: clientLambda.OperationAction.START,
1354
+ SubType: exports.OperationSubType.CHAINED_INVOKE,
1355
+ Type: clientLambda.OperationType.CHAINED_INVOKE,
1356
+ Name: name,
1357
+ Payload: serializedPayload,
1358
+ ChainedInvokeOptions: {
1359
+ FunctionName: funcId,
1360
+ },
1385
1361
  });
1386
- skippedCount++;
1387
- continue;
1388
1362
  }
1389
- batch.push(nextItem);
1390
- currentSize += itemSize;
1391
- }
1392
- log("🔄", "Processing checkpoint batch:", {
1393
- batchSize: batch.length,
1394
- remainingInQueue: this.queue.length,
1395
- estimatedSize: currentSize,
1396
- maxSize: this.MAX_PAYLOAD_SIZE,
1397
- });
1398
- try {
1399
- if (batch.length > 0 || this.forceCheckpointPromises.length > 0) {
1400
- await this.processBatch(batch);
1401
- }
1402
- batch.forEach((item) => {
1403
- if (item.data.Action === clientLambda.OperationAction.SUCCEED ||
1404
- item.data.Action === clientLambda.OperationAction.FAIL) {
1405
- this.pendingCompletions.delete(item.stepId);
1406
- }
1407
- item.resolve();
1408
- });
1409
- const forcePromises = this.forceCheckpointPromises.splice(0);
1410
- forcePromises.forEach((promise) => {
1411
- promise.resolve();
1412
- });
1413
- log("✅", "Checkpoint batch processed successfully:", {
1414
- batchSize: batch.length,
1415
- skippedCount,
1416
- forceRequests: forcePromises.length,
1417
- newTaskToken: this.currentTaskToken,
1418
- });
1419
- }
1420
- catch (error) {
1421
- log("❌", "Checkpoint batch failed:", {
1422
- batchSize: batch.length,
1423
- error,
1424
- });
1425
- const checkpointError = this.classifyCheckpointError(error);
1426
- // Clear remaining queue silently - we're terminating
1427
- this.clearQueue();
1428
- this.terminationManager.terminate({
1429
- reason: TerminationReason.CHECKPOINT_FAILED,
1430
- message: checkpointError.message,
1431
- error: checkpointError,
1363
+ // Mark as IDLE_NOT_AWAITED
1364
+ checkpoint.markOperationState(stepId, OperationLifecycleState.IDLE_NOT_AWAITED, {
1365
+ metadata: {
1366
+ stepId,
1367
+ name,
1368
+ type: clientLambda.OperationType.CHAINED_INVOKE,
1369
+ subType: exports.OperationSubType.CHAINED_INVOKE,
1370
+ parentId,
1371
+ },
1432
1372
  });
1433
- }
1434
- finally {
1435
- this.isProcessing = false;
1436
- if (this.queue.length > 0) {
1437
- setImmediate(() => {
1438
- this.processQueue();
1439
- });
1440
- }
1441
- else {
1442
- // Queue is empty and processing is done - notify all waiting promises
1443
- this.notifyQueueCompletion();
1444
- }
1445
- }
1446
- }
1447
- notifyQueueCompletion() {
1448
- if (this.queueCompletionResolver) {
1449
- if (this.queueCompletionTimeout) {
1450
- clearTimeout(this.queueCompletionTimeout);
1451
- this.queueCompletionTimeout = null;
1452
- }
1453
- this.queueCompletionResolver();
1454
- this.queueCompletionResolver = null;
1455
- }
1456
- }
1457
- async processBatch(batch) {
1458
- const updates = batch.map((item) => {
1459
- const hashedStepId = hashId(item.stepId);
1460
- const update = {
1461
- Type: item.data.Type || "STEP",
1462
- Action: item.data.Action || "START",
1463
- ...item.data,
1464
- Id: hashedStepId,
1465
- ...(item.data.ParentId && { ParentId: hashId(item.data.ParentId) }),
1466
- };
1467
- return update;
1468
- });
1469
- const checkpointData = {
1470
- DurableExecutionArn: this.durableExecutionArn,
1471
- CheckpointToken: this.currentTaskToken,
1472
- Updates: updates,
1473
- };
1474
- log("⏺️", "Creating checkpoint batch:", {
1475
- batchSize: updates.length,
1476
- checkpointToken: this.currentTaskToken,
1477
- updates: updates.map((u) => ({
1478
- Id: u.Id,
1479
- Action: u.Action,
1480
- Type: u.Type,
1481
- })),
1482
- });
1483
- const response = await this.storage.checkpoint(checkpointData, this.logger);
1484
- if (response.CheckpointToken) {
1485
- this.currentTaskToken = response.CheckpointToken;
1486
- }
1487
- if (response.NewExecutionState?.Operations) {
1488
- this.updateStepDataFromCheckpointResponse(response.NewExecutionState.Operations);
1489
- }
1490
- }
1491
- updateStepDataFromCheckpointResponse(operations) {
1492
- log("🔄", "Updating stepData from checkpoint response:", {
1493
- operationCount: operations.length,
1494
- operationIds: operations.map((op) => op.Id).filter(Boolean),
1495
- });
1496
- operations.forEach((operation) => {
1497
- if (operation.Id) {
1498
- this.stepData[operation.Id] = operation;
1499
- log("📝", "Updated stepData entry:", operation);
1500
- this.stepDataEmitter.emit(STEP_DATA_UPDATED_EVENT, operation.Id);
1501
- }
1502
- });
1503
- log("✅", "StepData update completed:", {
1504
- totalStepDataEntries: Object.keys(this.stepData).length,
1505
- });
1506
- }
1507
- getQueueStatus() {
1508
- return {
1509
- queueLength: this.queue.length,
1510
- isProcessing: this.isProcessing,
1511
- };
1512
- }
1513
- }
1514
-
1515
- /**
1516
- * High-level helper that waits for conditions before continuing execution.
1517
- * Uses event-driven approach for both operations completion and status changes.
1518
- */
1519
- async function waitBeforeContinue(options) {
1520
- const { checkHasRunningOperations, checkStepStatus, checkTimer, scheduledEndTimestamp, stepId, context, hasRunningOperations, operationsEmitter, checkpoint, onAwaitedChange, } = options;
1521
- const promises = [];
1522
- const timers = [];
1523
- const cleanupFns = [];
1524
- // Cleanup function to clear all timers and listeners
1525
- const cleanup = () => {
1526
- timers.forEach((timer) => clearTimeout(timer));
1527
- cleanupFns.forEach((fn) => fn());
1528
- };
1529
- // Timer promise - resolves when scheduled time is reached
1530
- if (checkTimer && scheduledEndTimestamp) {
1531
- const timerPromise = new Promise((resolve) => {
1532
- const timeLeft = Number(scheduledEndTimestamp) - Date.now();
1533
- if (timeLeft > 0) {
1534
- const timer = setTimeout(() => resolve({ reason: "timer", timerExpired: true }), timeLeft);
1535
- timers.push(timer);
1536
- }
1537
- else {
1538
- resolve({ reason: "timer", timerExpired: true });
1539
- }
1540
- });
1541
- promises.push(timerPromise);
1542
- }
1543
- // Operations promise - event-driven approach
1544
- if (checkHasRunningOperations) {
1545
- const operationsPromise = new Promise((resolve) => {
1546
- if (!hasRunningOperations()) {
1547
- resolve({ reason: "operations" });
1373
+ log("✅", "Invoke phase 1 complete:", { stepId });
1374
+ })();
1375
+ phase1Promise.catch(() => { });
1376
+ // Phase 2: Wait for completion
1377
+ return new DurablePromise(async () => {
1378
+ await phase1Promise;
1379
+ if (isCompleted) {
1380
+ const stepData = context.getStepData(stepId);
1381
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1382
+ const invokeDetails = stepData.ChainedInvokeDetails;
1383
+ return await safeDeserialize(config?.resultSerdes || defaultSerdes, invokeDetails?.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
1384
+ }
1385
+ // Handle failure
1386
+ const invokeDetails = stepData?.ChainedInvokeDetails;
1387
+ if (invokeDetails?.Error) {
1388
+ throw new InvokeError(invokeDetails.Error.ErrorMessage || "Invoke failed", invokeDetails.Error.ErrorMessage
1389
+ ? new Error(invokeDetails.Error.ErrorMessage)
1390
+ : undefined, invokeDetails.Error.ErrorData);
1391
+ }
1392
+ else {
1393
+ throw new InvokeError("Invoke failed");
1394
+ }
1548
1395
  }
1549
- else {
1550
- // Event-driven: listen for completion event
1551
- const handler = () => {
1552
- resolve({ reason: "operations" });
1553
- };
1554
- operationsEmitter.once(OPERATIONS_COMPLETE_EVENT, handler);
1555
- cleanupFns.push(() => operationsEmitter.off(OPERATIONS_COMPLETE_EVENT, handler));
1396
+ log("🔗", "Invoke phase 2:", { stepId });
1397
+ checkpoint.markOperationAwaited(stepId);
1398
+ await checkpoint.waitForStatusChange(stepId);
1399
+ const stepData = context.getStepData(stepId);
1400
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1401
+ log("✅", "Invoke completed:", { stepId });
1402
+ checkAndUpdateReplayMode?.();
1403
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1404
+ const invokeDetails = stepData.ChainedInvokeDetails;
1405
+ return await safeDeserialize(config?.resultSerdes || defaultSerdes, invokeDetails?.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
1556
1406
  }
1557
- });
1558
- promises.push(operationsPromise);
1559
- }
1560
- // Step status promise - event-driven approach
1561
- if (checkStepStatus) {
1562
- const originalStatus = context.getStepData(stepId)?.Status;
1563
- const hashedStepId = hashId(stepId);
1564
- const stepStatusPromise = new Promise((resolve) => {
1565
- // Check if status already changed
1566
- const currentStatus = context.getStepData(stepId)?.Status;
1567
- if (originalStatus !== currentStatus) {
1568
- resolve({ reason: "status" });
1407
+ // Handle failure
1408
+ log("❌", "Invoke failed:", { stepId, status: stepData?.Status });
1409
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1410
+ const invokeDetails = stepData?.ChainedInvokeDetails;
1411
+ if (invokeDetails?.Error) {
1412
+ throw new InvokeError(invokeDetails.Error.ErrorMessage || "Invoke failed", invokeDetails.Error.ErrorMessage
1413
+ ? new Error(invokeDetails.Error.ErrorMessage)
1414
+ : undefined, invokeDetails.Error.ErrorData);
1569
1415
  }
1570
1416
  else {
1571
- // Event-driven: listen for step data updates
1572
- const handler = (updatedStepId) => {
1573
- if (updatedStepId === hashedStepId) {
1574
- const newStatus = context.getStepData(stepId)?.Status;
1575
- if (originalStatus !== newStatus) {
1576
- resolve({ reason: "status" });
1577
- }
1578
- }
1579
- };
1580
- operationsEmitter.on(STEP_DATA_UPDATED_EVENT, handler);
1581
- cleanupFns.push(() => operationsEmitter.off(STEP_DATA_UPDATED_EVENT, handler));
1417
+ throw new InvokeError("Invoke failed");
1582
1418
  }
1583
1419
  });
1584
- promises.push(stepStatusPromise);
1585
- }
1586
- // Awaited change promise - resolves when the callback we set is invoked
1587
- // Note: This is safe from race conditions because waitBeforeContinue is called
1588
- // during Phase 1 execution (inside stepHandler), which happens BEFORE the user
1589
- // can await the DurablePromise. The callback is registered before it can be invoked.
1590
- if (onAwaitedChange) {
1591
- const awaitedChangePromise = new Promise((resolve) => {
1592
- // Register a callback that will be invoked when the promise is awaited
1593
- onAwaitedChange(() => {
1594
- resolve({ reason: "status" });
1595
- });
1596
- });
1597
- promises.push(awaitedChangePromise);
1598
- }
1599
- // If no conditions provided, return immediately
1600
- if (promises.length === 0) {
1601
- return { reason: "timeout" };
1602
- }
1603
- // Wait for any condition to be met, then cleanup timers and listeners
1604
- const result = await Promise.race(promises);
1605
- cleanup();
1606
- // If timer expired, force checkpoint to get fresh data from API
1607
- if (result.reason === "timer" && result.timerExpired && checkpoint) {
1608
- if (checkpoint.force) {
1609
- await checkpoint.force();
1610
- }
1611
- else if (checkpoint.forceCheckpoint) {
1612
- await checkpoint.forceCheckpoint();
1613
- }
1614
- }
1615
- return result;
1616
- }
1617
-
1618
- /**
1619
- * Error thrown when non-deterministic code is detected during replay
1620
- */
1621
- class NonDeterministicExecutionError extends UnrecoverableExecutionError {
1622
- terminationReason = TerminationReason.CUSTOM;
1623
- constructor(message) {
1624
- super(message);
1625
- this.name = "NonDeterministicExecutionError";
1626
1420
  }
1627
- }
1421
+ return invokeHandler;
1422
+ };
1628
1423
 
1629
- const validateReplayConsistency = (stepId, currentOperation, checkpointData, context) => {
1630
- // Skip validation if no checkpoint data exists or if Type is undefined (first execution)
1631
- if (!checkpointData || !checkpointData.Type) {
1632
- return;
1633
- }
1634
- // Validate operation type
1635
- if (checkpointData.Type !== currentOperation.type) {
1636
- const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation type mismatch for step "${stepId}". ` +
1637
- `Expected type "${checkpointData.Type}", but got "${currentOperation.type}". ` +
1638
- `This indicates non-deterministic control flow in your workflow code.`);
1639
- terminateForUnrecoverableError(context, error, stepId);
1424
+ // Checkpoint size limit in bytes (256KB)
1425
+ const CHECKPOINT_SIZE_LIMIT = 256 * 1024;
1426
+ const determineChildReplayMode = (context, stepId) => {
1427
+ const stepData = context.getStepData(stepId);
1428
+ if (!stepData) {
1429
+ return DurableExecutionMode.ExecutionMode;
1640
1430
  }
1641
- // Validate operation name (including undefined)
1642
- if (checkpointData.Name !== currentOperation.name) {
1643
- const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation name mismatch for step "${stepId}". ` +
1644
- `Expected name "${checkpointData.Name ?? "undefined"}", but got "${currentOperation.name ?? "undefined"}". ` +
1645
- `This indicates non-deterministic control flow in your workflow code.`);
1646
- terminateForUnrecoverableError(context, error, stepId);
1431
+ if (stepData.Status === clientLambda.OperationStatus.SUCCEEDED &&
1432
+ stepData.ContextDetails?.ReplayChildren) {
1433
+ return DurableExecutionMode.ReplaySucceededContext;
1647
1434
  }
1648
- // Validate operation subtype
1649
- if (checkpointData.SubType !== currentOperation.subType) {
1650
- const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation subtype mismatch for step "${stepId}". ` +
1651
- `Expected subtype "${checkpointData.SubType}", but got "${currentOperation.subType}". ` +
1652
- `This indicates non-deterministic control flow in your workflow code.`);
1653
- terminateForUnrecoverableError(context, error, stepId);
1435
+ if (stepData.Status === clientLambda.OperationStatus.SUCCEEDED ||
1436
+ stepData.Status === clientLambda.OperationStatus.FAILED) {
1437
+ return DurableExecutionMode.ReplayMode;
1654
1438
  }
1439
+ return DurableExecutionMode.ExecutionMode;
1655
1440
  };
1656
-
1657
- // Special symbol to indicate that the main loop should continue
1658
- const CONTINUE_MAIN_LOOP$1 = Symbol("CONTINUE_MAIN_LOOP");
1659
- const waitForContinuation$1 = async (context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, onAwaitedChange) => {
1660
- const stepData = context.getStepData(stepId);
1661
- // Check if there are any ongoing operations
1662
- if (!hasRunningOperations()) {
1663
- // No ongoing operations - safe to terminate
1664
- return terminate(context, TerminationReason.RETRY_SCHEDULED, `Retry scheduled for ${name || stepId}`);
1665
- }
1666
- // There are ongoing operations - wait before continuing
1667
- await waitBeforeContinue({
1668
- checkHasRunningOperations: true,
1669
- checkStepStatus: true,
1670
- checkTimer: true,
1671
- scheduledEndTimestamp: stepData?.StepDetails?.NextAttemptTimestamp,
1672
- stepId,
1673
- context,
1674
- hasRunningOperations,
1675
- operationsEmitter: getOperationsEmitter(),
1676
- checkpoint,
1677
- onAwaitedChange,
1678
- });
1679
- // Return to let the main loop re-evaluate step status
1680
- };
1681
- /**
1682
- * Creates a step handler for executing durable steps with two-phase execution.
1683
- */
1684
- const createStepHandler = (context, checkpoint, parentContext, createStepId, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId) => {
1441
+ const createRunInChildContextHandler = (context, checkpoint, parentContext, createStepId, getParentLogger, createChildContext, parentId) => {
1685
1442
  return (nameOrFn, fnOrOptions, maybeOptions) => {
1686
1443
  let name;
1687
1444
  let fn;
@@ -1695,480 +1452,31 @@ const createStepHandler = (context, checkpoint, parentContext, createStepId, log
1695
1452
  fn = nameOrFn;
1696
1453
  options = fnOrOptions;
1697
1454
  }
1698
- const stepId = createStepId();
1699
- log("▶️", "Running step:", { stepId, name, options });
1455
+ const entityId = createStepId();
1456
+ log("🔄", "Running child context:", {
1457
+ entityId,
1458
+ name,
1459
+ });
1460
+ const stepData = context.getStepData(entityId);
1461
+ // Validate replay consistency
1462
+ validateReplayConsistency(entityId, {
1463
+ type: clientLambda.OperationType.CONTEXT,
1464
+ name,
1465
+ subType: options?.subType ||
1466
+ exports.OperationSubType.RUN_IN_CHILD_CONTEXT,
1467
+ }, stepData, context);
1700
1468
  // Two-phase execution: Phase 1 starts immediately, Phase 2 returns result when awaited
1701
- let isAwaited = false;
1702
- let waitingCallback;
1703
- const setWaitingCallback = (cb) => {
1704
- waitingCallback = cb;
1705
- };
1469
+ let phase1Result;
1470
+ let phase1Error;
1706
1471
  // Phase 1: Start execution immediately and capture result/error
1707
1472
  const phase1Promise = (async () => {
1708
- // Main step logic - can be re-executed if step status changes
1709
- while (true) {
1710
- try {
1711
- const stepData = context.getStepData(stepId);
1712
- // Validate replay consistency
1713
- validateReplayConsistency(stepId, {
1714
- type: clientLambda.OperationType.STEP,
1715
- name,
1716
- subType: exports.OperationSubType.STEP,
1717
- }, stepData, context);
1718
- if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1719
- return await handleCompletedStep(context, stepId, name, options?.serdes);
1720
- }
1721
- if (stepData?.Status === clientLambda.OperationStatus.FAILED) {
1722
- // Return an async rejected promise to ensure it's handled asynchronously
1723
- return (async () => {
1724
- // Reconstruct the original error from stored ErrorObject
1725
- if (stepData.StepDetails?.Error) {
1726
- throw DurableOperationError.fromErrorObject(stepData.StepDetails.Error);
1727
- }
1728
- else {
1729
- // Fallback for legacy data without Error field
1730
- const errorMessage = stepData?.StepDetails?.Result;
1731
- throw new StepError(errorMessage || "Unknown error");
1732
- }
1733
- })();
1734
- }
1735
- // If PENDING, wait for timer to complete
1736
- if (stepData?.Status === clientLambda.OperationStatus.PENDING) {
1737
- await waitForContinuation$1(context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, isAwaited ? undefined : setWaitingCallback);
1738
- continue; // Re-evaluate step status after waiting
1739
- }
1740
- // Check for interrupted step with AT_MOST_ONCE_PER_RETRY semantics
1741
- if (stepData?.Status === clientLambda.OperationStatus.STARTED) {
1742
- const semantics = options?.semantics || exports.StepSemantics.AtLeastOncePerRetry;
1743
- if (semantics === exports.StepSemantics.AtMostOncePerRetry) {
1744
- log("⚠️", "Step was interrupted during execution:", {
1745
- stepId,
1746
- name,
1747
- });
1748
- const error = new StepInterruptedError(stepId, name);
1749
- // Handle the interrupted step as a failure
1750
- const currentAttempt = (stepData?.StepDetails?.Attempt || 0) + 1;
1751
- let retryDecision;
1752
- if (options?.retryStrategy !== undefined) {
1753
- retryDecision = options.retryStrategy(error, currentAttempt);
1754
- }
1755
- else {
1756
- retryDecision = retryPresets.default(error, currentAttempt);
1757
- }
1758
- log("⚠️", "Should Retry Interrupted Step:", {
1759
- stepId,
1760
- name,
1761
- currentAttempt,
1762
- shouldRetry: retryDecision.shouldRetry,
1763
- delayInSeconds: retryDecision.shouldRetry
1764
- ? retryDecision.delay
1765
- ? durationToSeconds(retryDecision.delay)
1766
- : undefined
1767
- : undefined,
1768
- });
1769
- if (!retryDecision.shouldRetry) {
1770
- // No retry, mark as failed
1771
- await checkpoint.checkpoint(stepId, {
1772
- Id: stepId,
1773
- ParentId: parentId,
1774
- Action: clientLambda.OperationAction.FAIL,
1775
- SubType: exports.OperationSubType.STEP,
1776
- Type: clientLambda.OperationType.STEP,
1777
- Error: createErrorObjectFromError(error),
1778
- Name: name,
1779
- });
1780
- // Reconstruct error from ErrorObject for deterministic behavior
1781
- const errorObject = createErrorObjectFromError(error);
1782
- throw DurableOperationError.fromErrorObject(errorObject);
1783
- }
1784
- else {
1785
- // Retry
1786
- await checkpoint.checkpoint(stepId, {
1787
- Id: stepId,
1788
- ParentId: parentId,
1789
- Action: clientLambda.OperationAction.RETRY,
1790
- SubType: exports.OperationSubType.STEP,
1791
- Type: clientLambda.OperationType.STEP,
1792
- Error: createErrorObjectFromError(error),
1793
- Name: name,
1794
- StepOptions: {
1795
- NextAttemptDelaySeconds: retryDecision.delay
1796
- ? durationToSeconds(retryDecision.delay)
1797
- : 1,
1798
- },
1799
- });
1800
- await waitForContinuation$1(context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, isAwaited ? undefined : setWaitingCallback);
1801
- continue; // Re-evaluate step status after waiting
1802
- }
1803
- }
1804
- }
1805
- // Execute step function for READY, STARTED (AtLeastOncePerRetry), or first time (undefined)
1806
- const result = await executeStep(context, checkpoint, stepId, name, fn, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, options, isAwaited ? undefined : setWaitingCallback);
1807
- // If executeStep signals to continue the main loop, do so
1808
- if (result === CONTINUE_MAIN_LOOP$1) {
1809
- continue;
1810
- }
1811
- return result;
1812
- }
1813
- catch (error) {
1814
- // Preserve DurableOperationError instances (StepInterruptedError is handled specifically where it's thrown)
1815
- if (error instanceof DurableOperationError) {
1816
- throw error;
1817
- }
1818
- // For any other error from executeStep, wrap it in StepError for consistency
1819
- throw new StepError(error instanceof Error ? error.message : "Step failed", error instanceof Error ? error : undefined);
1820
- }
1821
- }
1822
- })();
1823
- // Attach catch handler to prevent unhandled promise rejections
1824
- // The error will still be thrown when the DurablePromise is awaited
1825
- phase1Promise.catch(() => { });
1826
- // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
1827
- return new DurablePromise(async () => {
1828
- // When promise is awaited, mark as awaited and invoke waiting callback
1829
- isAwaited = true;
1830
- if (waitingCallback) {
1831
- waitingCallback();
1832
- }
1833
- return await phase1Promise;
1834
- });
1835
- };
1836
- };
1837
- const handleCompletedStep = async (context, stepId, stepName, serdes = defaultSerdes) => {
1838
- log("⏭️", "Step already finished, returning cached result:", { stepId });
1839
- const stepData = context.getStepData(stepId);
1840
- const result = stepData?.StepDetails?.Result;
1841
- return await safeDeserialize(serdes, result, stepId, stepName, context.terminationManager, context.durableExecutionArn);
1842
- };
1843
- const executeStep = async (context, checkpoint, stepId, name, fn, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, options, onAwaitedChange) => {
1844
- // Determine step semantics (default to AT_LEAST_ONCE_PER_RETRY if not specified)
1845
- const semantics = options?.semantics || exports.StepSemantics.AtLeastOncePerRetry;
1846
- const serdes = options?.serdes || defaultSerdes;
1847
- // Checkpoint at start for both semantics (only if not already started)
1848
- const stepData = context.getStepData(stepId);
1849
- if (stepData?.Status !== clientLambda.OperationStatus.STARTED) {
1850
- if (semantics === exports.StepSemantics.AtMostOncePerRetry) {
1851
- // Wait for checkpoint to complete
1852
- await checkpoint.checkpoint(stepId, {
1853
- Id: stepId,
1854
- ParentId: parentId,
1855
- Action: clientLambda.OperationAction.START,
1856
- SubType: exports.OperationSubType.STEP,
1857
- Type: clientLambda.OperationType.STEP,
1858
- Name: name,
1859
- });
1860
- }
1861
- else {
1862
- // Fire and forget for AtLeastOncePerRetry
1863
- checkpoint.checkpoint(stepId, {
1864
- Id: stepId,
1865
- ParentId: parentId,
1866
- Action: clientLambda.OperationAction.START,
1867
- SubType: exports.OperationSubType.STEP,
1868
- Type: clientLambda.OperationType.STEP,
1869
- Name: name,
1870
- });
1871
- }
1872
- }
1873
- try {
1874
- // Get current attempt number for logger enrichment
1875
- const stepData = context.getStepData(stepId);
1876
- const currentAttempt = stepData?.StepDetails?.Attempt || 0;
1877
- // Create step context with enriched logger
1878
- const stepContext = {
1879
- logger,
1880
- };
1881
- // Execute the step function with stepContext
1882
- addRunningOperation(stepId);
1883
- let result;
1884
- try {
1885
- result = await runWithContext(stepId, parentId, () => fn(stepContext),
1886
- // The attempt that is running is the attempt from the step data (previous step attempt) + 1
1887
- currentAttempt + 1,
1888
- // Alwasy in execution mode when running step operations
1889
- DurableExecutionMode.ExecutionMode);
1890
- }
1891
- finally {
1892
- removeRunningOperation(stepId);
1893
- }
1894
- // Serialize the result for consistency
1895
- const serializedResult = await safeSerialize(serdes, result, stepId, name, context.terminationManager, context.durableExecutionArn);
1896
- // Always checkpoint on completion
1897
- await checkpoint.checkpoint(stepId, {
1898
- Id: stepId,
1899
- ParentId: parentId,
1900
- Action: clientLambda.OperationAction.SUCCEED,
1901
- SubType: exports.OperationSubType.STEP,
1902
- Type: clientLambda.OperationType.STEP,
1903
- Payload: serializedResult,
1904
- Name: name,
1905
- });
1906
- log("✅", "Step completed successfully:", {
1907
- stepId,
1908
- name,
1909
- result,
1910
- semantics,
1911
- });
1912
- // Deserialize the result for consistency with replay behavior
1913
- return await safeDeserialize(serdes, serializedResult, stepId, name, context.terminationManager, context.durableExecutionArn);
1914
- }
1915
- catch (error) {
1916
- log("❌", "Step failed:", {
1917
- stepId,
1918
- name,
1919
- error,
1920
- semantics,
1921
- });
1922
- // Handle unrecoverable errors - these should not go through retry logic
1923
- if (isUnrecoverableError(error)) {
1924
- log("💥", "Unrecoverable error detected:", {
1925
- stepId,
1926
- name,
1927
- error: error.message,
1928
- });
1929
- return terminateForUnrecoverableError(context, error, name || stepId);
1930
- }
1931
- const stepData = context.getStepData(stepId);
1932
- const currentAttempt = (stepData?.StepDetails?.Attempt || 0) + 1;
1933
- let retryDecision;
1934
- if (options?.retryStrategy !== undefined) {
1935
- // Use provided retry configuration
1936
- retryDecision = options.retryStrategy(error instanceof Error ? error : new Error("Unknown Error"), currentAttempt);
1937
- }
1938
- else {
1939
- // Use default retry preset if no config provided
1940
- retryDecision = retryPresets.default(error instanceof Error ? error : new Error("Unknown Error"), currentAttempt);
1941
- }
1942
- log("⚠️", "Should Retry:", {
1943
- stepId,
1944
- name,
1945
- currentAttempt,
1946
- shouldRetry: retryDecision.shouldRetry,
1947
- delayInSeconds: retryDecision.shouldRetry
1948
- ? retryDecision.delay
1949
- ? durationToSeconds(retryDecision.delay)
1950
- : undefined
1951
- : undefined,
1952
- semantics,
1953
- });
1954
- if (!retryDecision.shouldRetry) {
1955
- // No retry
1956
- await checkpoint.checkpoint(stepId, {
1957
- Id: stepId,
1958
- ParentId: parentId,
1959
- Action: clientLambda.OperationAction.FAIL,
1960
- SubType: exports.OperationSubType.STEP,
1961
- Type: clientLambda.OperationType.STEP,
1962
- Error: createErrorObjectFromError(error),
1963
- Name: name,
1964
- });
1965
- // Reconstruct error from ErrorObject for deterministic behavior
1966
- const errorObject = createErrorObjectFromError(error);
1967
- throw DurableOperationError.fromErrorObject(errorObject);
1968
- }
1969
- else {
1970
- // Retry
1971
- await checkpoint.checkpoint(stepId, {
1972
- Id: stepId,
1973
- ParentId: parentId,
1974
- Action: clientLambda.OperationAction.RETRY,
1975
- SubType: exports.OperationSubType.STEP,
1976
- Type: clientLambda.OperationType.STEP,
1977
- Error: createErrorObjectFromError(error),
1978
- Name: name,
1979
- StepOptions: {
1980
- NextAttemptDelaySeconds: retryDecision.delay
1981
- ? durationToSeconds(retryDecision.delay)
1982
- : 1,
1983
- },
1984
- });
1985
- // Wait for continuation and signal main loop to continue
1986
- await waitForContinuation$1(context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, onAwaitedChange);
1987
- return CONTINUE_MAIN_LOOP$1;
1988
- }
1989
- }
1990
- };
1991
-
1992
- const createInvokeHandler = (context, checkpoint, createStepId, hasRunningOperations, getOperationsEmitter, parentId, checkAndUpdateReplayMode) => {
1993
- function invokeHandler(nameOrFuncId, funcIdOrInput, inputOrConfig, maybeConfig) {
1994
- const isNameFirst = typeof funcIdOrInput === "string";
1995
- const name = isNameFirst ? nameOrFuncId : undefined;
1996
- const funcId = isNameFirst ? funcIdOrInput : nameOrFuncId;
1997
- const input = isNameFirst
1998
- ? inputOrConfig
1999
- : funcIdOrInput;
2000
- const config = isNameFirst
2001
- ? maybeConfig
2002
- : inputOrConfig;
2003
- const stepId = createStepId();
2004
- // Phase 1: Only checkpoint if needed, don't execute full logic
2005
- const startInvokeOperation = async () => {
2006
- log("🔗", `Invoke ${name || funcId} (${stepId}) - phase 1`);
2007
- // Check initial step data for replay consistency validation
2008
- const initialStepData = context.getStepData(stepId);
2009
- // Validate replay consistency once before any execution
2010
- validateReplayConsistency(stepId, {
2011
- type: clientLambda.OperationType.CHAINED_INVOKE,
2012
- name,
2013
- subType: exports.OperationSubType.CHAINED_INVOKE,
2014
- }, initialStepData, context);
2015
- // If stepData already exists, phase 1 has nothing to do
2016
- if (initialStepData) {
2017
- log("⏸️", `Invoke ${name || funcId} already exists (phase 1)`);
2018
- return;
2019
- }
2020
- // No stepData exists - need to start the invoke operation
2021
- // Serialize the input payload
2022
- const serializedPayload = await safeSerialize(config?.payloadSerdes || defaultSerdes, input, stepId, name, context.terminationManager, context.durableExecutionArn);
2023
- // Create checkpoint for the invoke operation
2024
- await checkpoint.checkpoint(stepId, {
2025
- Id: stepId,
2026
- ParentId: parentId,
2027
- Action: clientLambda.OperationAction.START,
2028
- SubType: exports.OperationSubType.CHAINED_INVOKE,
2029
- Type: clientLambda.OperationType.CHAINED_INVOKE,
2030
- Name: name,
2031
- Payload: serializedPayload,
2032
- ChainedInvokeOptions: {
2033
- FunctionName: funcId,
2034
- },
2035
- });
2036
- log("🚀", `Invoke ${name || funcId} started (phase 1)`);
2037
- };
2038
- // Phase 2: Execute full logic including waiting and termination
2039
- const continueInvokeOperation = async () => {
2040
- log("🔗", `Invoke ${name || funcId} (${stepId}) - phase 2`);
2041
- // Main invoke logic - can be re-executed if step status changes
2042
- while (true) {
2043
- // Check if we have existing step data
2044
- const stepData = context.getStepData(stepId);
2045
- if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
2046
- // Return cached result - no need to check for errors in successful operations
2047
- const invokeDetails = stepData.ChainedInvokeDetails;
2048
- checkAndUpdateReplayMode?.();
2049
- return await safeDeserialize(config?.resultSerdes || defaultSerdes, invokeDetails?.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
2050
- }
2051
- if (stepData?.Status === clientLambda.OperationStatus.FAILED ||
2052
- stepData?.Status === clientLambda.OperationStatus.TIMED_OUT ||
2053
- stepData?.Status === clientLambda.OperationStatus.STOPPED) {
2054
- // Operation failed, return async rejected promise
2055
- const invokeDetails = stepData.ChainedInvokeDetails;
2056
- return (async () => {
2057
- if (invokeDetails?.Error) {
2058
- throw new InvokeError(invokeDetails.Error.ErrorMessage || "Invoke failed", invokeDetails.Error.ErrorMessage
2059
- ? new Error(invokeDetails.Error.ErrorMessage)
2060
- : undefined, invokeDetails.Error.ErrorData);
2061
- }
2062
- else {
2063
- throw new InvokeError("Invoke failed");
2064
- }
2065
- })();
2066
- }
2067
- if (stepData?.Status === clientLambda.OperationStatus.STARTED) {
2068
- // Operation is still running
2069
- if (hasRunningOperations()) {
2070
- // Phase 2: Wait for other operations
2071
- log("⏳", `Invoke ${name || funcId} still in progress, waiting for other operations`);
2072
- await waitBeforeContinue({
2073
- checkHasRunningOperations: true,
2074
- checkStepStatus: true,
2075
- checkTimer: false,
2076
- stepId,
2077
- context,
2078
- hasRunningOperations,
2079
- operationsEmitter: getOperationsEmitter(),
2080
- });
2081
- continue; // Re-evaluate status after waiting
2082
- }
2083
- // No other operations running - terminate
2084
- log("⏳", `Invoke ${name || funcId} still in progress, terminating`);
2085
- return terminate(context, TerminationReason.OPERATION_TERMINATED, stepId);
2086
- }
2087
- // If stepData exists but has an unexpected status, break to avoid infinite loop
2088
- if (stepData && stepData.Status !== undefined) {
2089
- throw new InvokeError(`Unexpected operation status: ${stepData.Status}`);
2090
- }
2091
- // This should not happen in phase 2 since phase 1 creates stepData
2092
- throw new InvokeError("No step data found in phase 2 - this should not happen");
2093
- }
2094
- };
2095
- // Create a promise that tracks phase 1 completion
2096
- const startInvokePromise = startInvokeOperation()
2097
- .then(() => {
2098
- log("✅", "Invoke phase 1 complete:", { stepId, name: name || funcId });
2099
- })
2100
- .catch((error) => {
2101
- log("❌", "Invoke phase 1 error:", { stepId, error: error.message });
2102
- throw error; // Re-throw to fail phase 1
2103
- });
2104
- // Attach catch handler to prevent unhandled promise rejections
2105
- // The error will still be thrown when the DurablePromise is awaited
2106
- startInvokePromise.catch(() => { });
2107
- // Return DurablePromise that will execute phase 2 when awaited
2108
- return new DurablePromise(async () => {
2109
- // Wait for phase 1 to complete first
2110
- await startInvokePromise;
2111
- // Then execute phase 2
2112
- return await continueInvokeOperation();
2113
- });
2114
- }
2115
- return invokeHandler;
2116
- };
2117
-
2118
- // Checkpoint size limit in bytes (256KB)
2119
- const CHECKPOINT_SIZE_LIMIT = 256 * 1024;
2120
- const determineChildReplayMode = (context, stepId) => {
2121
- const stepData = context.getStepData(stepId);
2122
- if (!stepData) {
2123
- return DurableExecutionMode.ExecutionMode;
2124
- }
2125
- if (stepData.Status === clientLambda.OperationStatus.SUCCEEDED &&
2126
- stepData.ContextDetails?.ReplayChildren) {
2127
- return DurableExecutionMode.ReplaySucceededContext;
2128
- }
2129
- if (stepData.Status === clientLambda.OperationStatus.SUCCEEDED ||
2130
- stepData.Status === clientLambda.OperationStatus.FAILED) {
2131
- return DurableExecutionMode.ReplayMode;
2132
- }
2133
- return DurableExecutionMode.ExecutionMode;
2134
- };
2135
- const createRunInChildContextHandler = (context, checkpoint, parentContext, createStepId, getParentLogger, createChildContext, parentId) => {
2136
- return (nameOrFn, fnOrOptions, maybeOptions) => {
2137
- let name;
2138
- let fn;
2139
- let options;
2140
- if (typeof nameOrFn === "string" || nameOrFn === undefined) {
2141
- name = nameOrFn;
2142
- fn = fnOrOptions;
2143
- options = maybeOptions;
2144
- }
2145
- else {
2146
- fn = nameOrFn;
2147
- options = fnOrOptions;
2148
- }
2149
- const entityId = createStepId();
2150
- log("🔄", "Running child context:", {
2151
- entityId,
2152
- name,
2153
- });
2154
- const stepData = context.getStepData(entityId);
2155
- // Validate replay consistency
2156
- validateReplayConsistency(entityId, {
2157
- type: clientLambda.OperationType.CONTEXT,
2158
- name,
2159
- subType: options?.subType ||
2160
- exports.OperationSubType.RUN_IN_CHILD_CONTEXT,
2161
- }, stepData, context);
2162
- // Two-phase execution: Phase 1 starts immediately, Phase 2 returns result when awaited
2163
- let phase1Result;
2164
- let phase1Error;
2165
- // Phase 1: Start execution immediately and capture result/error
2166
- const phase1Promise = (async () => {
2167
- const currentStepData = context.getStepData(entityId);
2168
- // If already completed, return cached result
2169
- if (currentStepData?.Status === clientLambda.OperationStatus.SUCCEEDED ||
2170
- currentStepData?.Status === clientLambda.OperationStatus.FAILED) {
2171
- return handleCompletedChildContext(context, parentContext, entityId, name, fn, options, getParentLogger, createChildContext);
1473
+ const currentStepData = context.getStepData(entityId);
1474
+ // If already completed, return cached result
1475
+ if (currentStepData?.Status === clientLambda.OperationStatus.SUCCEEDED ||
1476
+ currentStepData?.Status === clientLambda.OperationStatus.FAILED) {
1477
+ // Mark this run-in-child-context as finished to prevent descendant operations
1478
+ checkpoint.markAncestorFinished(entityId);
1479
+ return handleCompletedChildContext(context, parentContext, entityId, name, fn, options, getParentLogger, createChildContext);
2172
1480
  }
2173
1481
  // Execute if not completed
2174
1482
  return executeChildContext(context, checkpoint, parentContext, entityId, name, fn, options, getParentLogger, createChildContext, parentId);
@@ -2257,8 +1565,10 @@ const executeChildContext = async (context, checkpoint, parentContext, entityId,
2257
1565
  limit: CHECKPOINT_SIZE_LIMIT,
2258
1566
  });
2259
1567
  }
1568
+ // Mark this run-in-child-context as finished to prevent descendant operations
1569
+ checkpoint.markAncestorFinished(entityId);
2260
1570
  const subType = options?.subType || exports.OperationSubType.RUN_IN_CHILD_CONTEXT;
2261
- await checkpoint.checkpoint(entityId, {
1571
+ checkpoint.checkpoint(entityId, {
2262
1572
  Id: entityId,
2263
1573
  ParentId: parentId,
2264
1574
  Action: clientLambda.OperationAction.SUCCEED,
@@ -2280,9 +1590,11 @@ const executeChildContext = async (context, checkpoint, parentContext, entityId,
2280
1590
  name,
2281
1591
  error,
2282
1592
  });
1593
+ // Mark this run-in-child-context as finished to prevent descendant operations
1594
+ checkpoint.markAncestorFinished(entityId);
2283
1595
  // Always checkpoint failures
2284
1596
  const subType = options?.subType || exports.OperationSubType.RUN_IN_CHILD_CONTEXT;
2285
- await checkpoint.checkpoint(entityId, {
1597
+ checkpoint.checkpoint(entityId, {
2286
1598
  Id: entityId,
2287
1599
  ParentId: parentId,
2288
1600
  Action: clientLambda.OperationAction.FAIL,
@@ -2298,433 +1610,324 @@ const executeChildContext = async (context, checkpoint, parentContext, entityId,
2298
1610
  }
2299
1611
  };
2300
1612
 
2301
- const createWaitHandler = (context, checkpoint, createStepId, hasRunningOperations, getOperationsEmitter, parentId, checkAndUpdateReplayMode) => {
1613
+ const createWaitHandler = (context, checkpoint, createStepId, parentId, checkAndUpdateReplayMode) => {
2302
1614
  function waitHandler(nameOrDuration, duration) {
2303
1615
  const isNameFirst = typeof nameOrDuration === "string";
2304
1616
  const actualName = isNameFirst ? nameOrDuration : undefined;
2305
1617
  const actualDuration = isNameFirst ? duration : nameOrDuration;
2306
1618
  const actualSeconds = durationToSeconds(actualDuration);
2307
1619
  const stepId = createStepId();
2308
- // Shared wait logic for both phases
2309
- const executeWaitLogic = async (canTerminate) => {
2310
- log("⏲️", `Wait executing (${canTerminate ? "phase 2" : "phase 1"}):`, {
1620
+ // Phase 1: Start wait operation
1621
+ let isCompleted = false;
1622
+ const phase1Promise = (async () => {
1623
+ log("⏲️", "Wait phase 1:", {
2311
1624
  stepId,
2312
1625
  name: actualName,
2313
- duration: actualDuration,
2314
1626
  seconds: actualSeconds,
2315
1627
  });
2316
1628
  let stepData = context.getStepData(stepId);
2317
- // Validate replay consistency once before loop
1629
+ // Validate replay consistency
2318
1630
  validateReplayConsistency(stepId, {
2319
1631
  type: clientLambda.OperationType.WAIT,
2320
1632
  name: actualName,
2321
1633
  subType: exports.OperationSubType.WAIT,
2322
1634
  }, stepData, context);
2323
- // Main wait logic - can be re-executed if step data changes
2324
- while (true) {
2325
- stepData = context.getStepData(stepId);
2326
- if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
2327
- log("⏭️", "Wait already completed:", { stepId });
2328
- checkAndUpdateReplayMode?.();
2329
- return;
2330
- }
2331
- // Only checkpoint START if we haven't started this wait before
2332
- if (!stepData) {
2333
- await checkpoint.checkpoint(stepId, {
2334
- Id: stepId,
2335
- ParentId: parentId,
2336
- Action: clientLambda.OperationAction.START,
2337
- SubType: exports.OperationSubType.WAIT,
2338
- Type: clientLambda.OperationType.WAIT,
2339
- Name: actualName,
2340
- WaitOptions: {
2341
- WaitSeconds: actualSeconds,
2342
- },
2343
- });
2344
- }
2345
- // Always refresh stepData to ensure it's up-to-date before proceeding
2346
- stepData = context.getStepData(stepId);
2347
- // Check if there are any ongoing operations
2348
- if (!hasRunningOperations()) {
2349
- // Phase 1: Just return without terminating
2350
- // Phase 2: Terminate
2351
- if (canTerminate) {
2352
- return terminate(context, TerminationReason.WAIT_SCHEDULED, `Operation ${actualName || stepId} scheduled to wait`);
2353
- }
2354
- else {
2355
- log("⏸️", "Wait ready but not terminating (phase 1):", { stepId });
2356
- return;
2357
- }
2358
- }
2359
- // There are ongoing operations - wait before continuing
2360
- await waitBeforeContinue({
2361
- checkHasRunningOperations: true,
2362
- checkStepStatus: true,
2363
- checkTimer: true,
2364
- scheduledEndTimestamp: stepData?.WaitDetails?.ScheduledEndTimestamp,
2365
- stepId,
2366
- context,
2367
- hasRunningOperations,
2368
- operationsEmitter: getOperationsEmitter(),
2369
- checkpoint,
1635
+ // Check if already completed
1636
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1637
+ log("⏭️", "Wait already completed:", { stepId });
1638
+ checkAndUpdateReplayMode?.();
1639
+ // Mark as completed
1640
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1641
+ metadata: {
1642
+ stepId,
1643
+ name: actualName,
1644
+ type: clientLambda.OperationType.WAIT,
1645
+ subType: exports.OperationSubType.WAIT,
1646
+ parentId,
1647
+ },
2370
1648
  });
2371
- // Continue the loop to re-evaluate all conditions from the beginning
1649
+ isCompleted = true;
1650
+ return;
2372
1651
  }
2373
- };
2374
- // Create a promise that tracks phase 1 completion
2375
- const phase1Promise = executeWaitLogic(false).then(() => {
2376
- log("✅", "Wait phase 1 complete:", { stepId, name: actualName });
2377
- });
2378
- // Attach catch handler to prevent unhandled promise rejections
2379
- // The error will still be thrown when the DurablePromise is awaited
1652
+ // Start wait if not already started
1653
+ if (!stepData) {
1654
+ await checkpoint.checkpoint(stepId, {
1655
+ Id: stepId,
1656
+ ParentId: parentId,
1657
+ Action: clientLambda.OperationAction.START,
1658
+ SubType: exports.OperationSubType.WAIT,
1659
+ Type: clientLambda.OperationType.WAIT,
1660
+ Name: actualName,
1661
+ WaitOptions: {
1662
+ WaitSeconds: actualSeconds,
1663
+ },
1664
+ });
1665
+ }
1666
+ // Refresh stepData after checkpoint
1667
+ stepData = context.getStepData(stepId);
1668
+ // Mark as IDLE_NOT_AWAITED (phase 1 complete, not awaited yet)
1669
+ checkpoint.markOperationState(stepId, OperationLifecycleState.IDLE_NOT_AWAITED, {
1670
+ metadata: {
1671
+ stepId,
1672
+ name: actualName,
1673
+ type: clientLambda.OperationType.WAIT,
1674
+ subType: exports.OperationSubType.WAIT,
1675
+ parentId,
1676
+ },
1677
+ endTimestamp: stepData?.WaitDetails?.ScheduledEndTimestamp,
1678
+ });
1679
+ log("✅", "Wait phase 1 complete:", { stepId });
1680
+ })();
1681
+ // Prevent unhandled rejection
2380
1682
  phase1Promise.catch(() => { });
2381
- // Return DurablePromise that will execute phase 2 when awaited
1683
+ // Phase 2: Wait for completion
2382
1684
  return new DurablePromise(async () => {
2383
- // Wait for phase 1 to complete first
1685
+ // Wait for phase 1
2384
1686
  await phase1Promise;
2385
- // Then execute phase 2
2386
- await executeWaitLogic(true);
1687
+ // If already completed in phase 1, skip phase 2
1688
+ if (isCompleted) {
1689
+ return;
1690
+ }
1691
+ log("⏲️", "Wait phase 2:", { stepId });
1692
+ // Mark as awaited
1693
+ checkpoint.markOperationAwaited(stepId);
1694
+ // Wait for status change
1695
+ await checkpoint.waitForStatusChange(stepId);
1696
+ // Check final status
1697
+ const stepData = context.getStepData(stepId);
1698
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1699
+ log("✅", "Wait completed:", { stepId });
1700
+ checkAndUpdateReplayMode?.();
1701
+ // Mark as completed
1702
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1703
+ return;
1704
+ }
1705
+ // Should not reach here, but handle gracefully
1706
+ log("⚠️", "Wait ended with unexpected status:", {
1707
+ stepId,
1708
+ status: stepData?.Status,
1709
+ });
2387
1710
  });
2388
1711
  }
2389
1712
  return waitHandler;
2390
1713
  };
2391
1714
 
2392
- // Special symbol to indicate that the main loop should continue
2393
- const CONTINUE_MAIN_LOOP = Symbol("CONTINUE_MAIN_LOOP");
2394
- const waitForContinuation = async (context, stepId, name, hasRunningOperations, checkpoint, operationsEmitter, onAwaitedChange) => {
2395
- const stepData = context.getStepData(stepId);
2396
- // Check if there are any ongoing operations
2397
- if (!hasRunningOperations()) {
2398
- // No ongoing operations - safe to terminate
2399
- return terminate(context, TerminationReason.RETRY_SCHEDULED, `Retry scheduled for ${name || stepId}`);
2400
- }
2401
- // There are ongoing operations - wait before continuing
2402
- await waitBeforeContinue({
2403
- checkHasRunningOperations: true,
2404
- checkStepStatus: true,
2405
- checkTimer: true,
2406
- scheduledEndTimestamp: stepData?.StepDetails?.NextAttemptTimestamp,
2407
- stepId,
2408
- context,
2409
- hasRunningOperations,
2410
- operationsEmitter,
2411
- checkpoint,
2412
- onAwaitedChange,
2413
- });
2414
- // Return to let the main loop re-evaluate step status
2415
- };
2416
- const createWaitForConditionHandler = (context, checkpoint, createStepId, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId) => {
1715
+ const createWaitForConditionHandler = (context, checkpoint, createStepId, logger, parentId) => {
2417
1716
  return (nameOrCheck, checkOrConfig, maybeConfig) => {
2418
- // Two-phase execution: Phase 1 starts immediately, Phase 2 returns result when awaited
2419
- let isAwaited = false;
2420
- let waitingCallback;
2421
- const setWaitingCallback = (cb) => {
2422
- waitingCallback = cb;
2423
- };
2424
- // Phase 1: Start execution immediately and capture result/error
1717
+ let name;
1718
+ let check;
1719
+ let config;
1720
+ if (typeof nameOrCheck === "string" || nameOrCheck === undefined) {
1721
+ name = nameOrCheck;
1722
+ check = checkOrConfig;
1723
+ config = maybeConfig;
1724
+ }
1725
+ else {
1726
+ check = nameOrCheck;
1727
+ config = checkOrConfig;
1728
+ }
1729
+ if (!config?.waitStrategy || config.initialState === undefined) {
1730
+ throw new Error("waitForCondition requires config with waitStrategy and initialState");
1731
+ }
1732
+ const stepId = createStepId();
1733
+ const serdes = config.serdes || defaultSerdes;
2425
1734
  const phase1Promise = (async () => {
2426
- let name;
2427
- let check;
2428
- let config;
2429
- // Parse overloaded parameters - validation errors thrown here are async
2430
- if (typeof nameOrCheck === "string" || nameOrCheck === undefined) {
2431
- name = nameOrCheck;
2432
- check = checkOrConfig;
2433
- config = maybeConfig;
1735
+ let stepData = context.getStepData(stepId);
1736
+ // Check if already completed
1737
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1738
+ log("⏭️", "WaitForCondition already completed:", { stepId });
1739
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1740
+ metadata: {
1741
+ stepId,
1742
+ name,
1743
+ type: clientLambda.OperationType.STEP,
1744
+ subType: exports.OperationSubType.WAIT_FOR_CONDITION,
1745
+ parentId,
1746
+ },
1747
+ });
1748
+ return await safeDeserialize(serdes, stepData.StepDetails?.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
2434
1749
  }
2435
- else {
2436
- check = nameOrCheck;
2437
- config = checkOrConfig;
1750
+ // Check if already failed
1751
+ if (stepData?.Status === clientLambda.OperationStatus.FAILED) {
1752
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1753
+ metadata: {
1754
+ stepId,
1755
+ name,
1756
+ type: clientLambda.OperationType.STEP,
1757
+ subType: exports.OperationSubType.WAIT_FOR_CONDITION,
1758
+ parentId,
1759
+ },
1760
+ });
1761
+ if (stepData.StepDetails?.Error) {
1762
+ throw DurableOperationError.fromErrorObject(stepData.StepDetails.Error);
1763
+ }
1764
+ throw new WaitForConditionError("waitForCondition failed");
2438
1765
  }
2439
- if (!config ||
2440
- !config.waitStrategy ||
2441
- config.initialState === undefined) {
2442
- throw new Error("waitForCondition requires config with waitStrategy and initialState");
1766
+ // Check if pending retry
1767
+ if (stepData?.Status === clientLambda.OperationStatus.PENDING) {
1768
+ checkpoint.markOperationState(stepId, OperationLifecycleState.RETRY_WAITING, {
1769
+ metadata: {
1770
+ stepId,
1771
+ name,
1772
+ type: clientLambda.OperationType.STEP,
1773
+ subType: exports.OperationSubType.WAIT_FOR_CONDITION,
1774
+ parentId,
1775
+ },
1776
+ endTimestamp: stepData.StepDetails?.NextAttemptTimestamp,
1777
+ });
1778
+ return (async () => {
1779
+ await checkpoint.waitForRetryTimer(stepId);
1780
+ stepData = context.getStepData(stepId);
1781
+ return await executeCheckLogic();
1782
+ })();
2443
1783
  }
2444
- const stepId = createStepId();
2445
- log("🔄", "Running waitForCondition:", {
2446
- stepId,
2447
- name,
2448
- config,
2449
- });
2450
- // Main waitForCondition logic - can be re-executed if step status changes
2451
- while (true) {
2452
- try {
2453
- const stepData = context.getStepData(stepId);
2454
- // Check if already completed
2455
- if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
2456
- return await handleCompletedWaitForCondition(context, stepId, name, config.serdes);
2457
- }
2458
- if (stepData?.Status === clientLambda.OperationStatus.FAILED) {
2459
- // Return an async rejected promise to ensure it's handled asynchronously
2460
- return (async () => {
2461
- // Reconstruct the original error from stored ErrorObject
2462
- if (stepData.StepDetails?.Error) {
2463
- throw DurableOperationError.fromErrorObject(stepData.StepDetails.Error);
2464
- }
2465
- else {
2466
- // Fallback for legacy data without Error field
2467
- const errorMessage = stepData?.StepDetails?.Result;
2468
- throw new WaitForConditionError(errorMessage || "waitForCondition failed");
2469
- }
2470
- })();
2471
- }
2472
- // If PENDING, wait for timer to complete
2473
- if (stepData?.Status === clientLambda.OperationStatus.PENDING) {
2474
- await waitForContinuation(context, stepId, name, hasRunningOperations, checkpoint, getOperationsEmitter(), isAwaited ? undefined : setWaitingCallback);
2475
- continue; // Re-evaluate step status after waiting
1784
+ return await executeCheckLogic();
1785
+ async function executeCheckLogic() {
1786
+ stepData = context.getStepData(stepId);
1787
+ // Get current state
1788
+ let currentState;
1789
+ if (stepData?.Status === clientLambda.OperationStatus.STARTED ||
1790
+ stepData?.Status === clientLambda.OperationStatus.READY) {
1791
+ const checkpointData = stepData.StepDetails?.Result;
1792
+ if (checkpointData) {
1793
+ try {
1794
+ const serdesContext = {
1795
+ entityId: stepId,
1796
+ durableExecutionArn: context.durableExecutionArn,
1797
+ };
1798
+ currentState = await serdes.deserialize(checkpointData, serdesContext);
1799
+ }
1800
+ catch {
1801
+ currentState = config.initialState;
1802
+ }
2476
1803
  }
2477
- // Execute check function for READY, STARTED, or first time (undefined)
2478
- const result = await executeWaitForCondition(context, checkpoint, stepId, name, check, config, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, isAwaited ? undefined : setWaitingCallback);
2479
- // If executeWaitForCondition signals to continue the main loop, do so
2480
- if (result === CONTINUE_MAIN_LOOP) {
2481
- continue;
1804
+ else {
1805
+ currentState = config.initialState;
2482
1806
  }
2483
- return result;
2484
1807
  }
2485
- catch (error) {
2486
- // For any error from executeWaitForCondition, re-throw it
2487
- throw error;
1808
+ else {
1809
+ currentState = config.initialState;
2488
1810
  }
2489
- }
2490
- })();
2491
- // Attach catch handler to prevent unhandled promise rejections
2492
- // The error will still be thrown when the DurablePromise is awaited
2493
- phase1Promise.catch(() => { });
2494
- // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
2495
- return new DurablePromise(async () => {
2496
- // When promise is awaited, mark as awaited and invoke waiting callback
2497
- isAwaited = true;
2498
- if (waitingCallback) {
2499
- waitingCallback();
2500
- }
1811
+ const currentAttempt = (stepData?.StepDetails?.Attempt ?? 0) + 1;
1812
+ // Checkpoint START if not already started
1813
+ if (stepData?.Status !== clientLambda.OperationStatus.STARTED) {
1814
+ checkpoint.checkpoint(stepId, {
1815
+ Id: stepId,
1816
+ ParentId: parentId,
1817
+ Action: clientLambda.OperationAction.START,
1818
+ SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
1819
+ Type: clientLambda.OperationType.STEP,
1820
+ Name: name,
1821
+ });
1822
+ }
1823
+ try {
1824
+ const waitForConditionContext = {
1825
+ logger,
1826
+ };
1827
+ // Mark operation as EXECUTING
1828
+ checkpoint.markOperationState(stepId, OperationLifecycleState.EXECUTING, {
1829
+ metadata: {
1830
+ stepId,
1831
+ name,
1832
+ type: clientLambda.OperationType.STEP,
1833
+ subType: exports.OperationSubType.WAIT_FOR_CONDITION,
1834
+ parentId,
1835
+ },
1836
+ });
1837
+ const newState = await runWithContext(stepId, parentId, () => check(currentState, waitForConditionContext), currentAttempt, DurableExecutionMode.ExecutionMode);
1838
+ const serializedState = await safeSerialize(serdes, newState, stepId, name, context.terminationManager, context.durableExecutionArn);
1839
+ const deserializedState = await safeDeserialize(serdes, serializedState, stepId, name, context.terminationManager, context.durableExecutionArn);
1840
+ const decision = config.waitStrategy(deserializedState, currentAttempt);
1841
+ if (!decision.shouldContinue) {
1842
+ await checkpoint.checkpoint(stepId, {
1843
+ Id: stepId,
1844
+ ParentId: parentId,
1845
+ Action: clientLambda.OperationAction.SUCCEED,
1846
+ SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
1847
+ Type: clientLambda.OperationType.STEP,
1848
+ Payload: serializedState,
1849
+ Name: name,
1850
+ });
1851
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1852
+ return deserializedState;
1853
+ }
1854
+ await checkpoint.checkpoint(stepId, {
1855
+ Id: stepId,
1856
+ ParentId: parentId,
1857
+ Action: clientLambda.OperationAction.RETRY,
1858
+ SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
1859
+ Type: clientLambda.OperationType.STEP,
1860
+ Payload: serializedState,
1861
+ Name: name,
1862
+ StepOptions: {
1863
+ NextAttemptDelaySeconds: durationToSeconds(decision.delay),
1864
+ },
1865
+ });
1866
+ checkpoint.markOperationState(stepId, OperationLifecycleState.RETRY_WAITING, {
1867
+ metadata: {
1868
+ stepId,
1869
+ name,
1870
+ type: clientLambda.OperationType.STEP,
1871
+ subType: exports.OperationSubType.WAIT_FOR_CONDITION,
1872
+ parentId,
1873
+ },
1874
+ endTimestamp: context.getStepData(stepId)?.StepDetails?.NextAttemptTimestamp,
1875
+ });
1876
+ await checkpoint.waitForRetryTimer(stepId);
1877
+ return await executeCheckLogic();
1878
+ }
1879
+ catch (error) {
1880
+ await checkpoint.checkpoint(stepId, {
1881
+ Id: stepId,
1882
+ ParentId: parentId,
1883
+ Action: clientLambda.OperationAction.FAIL,
1884
+ SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
1885
+ Type: clientLambda.OperationType.STEP,
1886
+ Error: createErrorObjectFromError(error),
1887
+ Name: name,
1888
+ });
1889
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1890
+ throw DurableOperationError.fromErrorObject(createErrorObjectFromError(error));
1891
+ }
1892
+ }
1893
+ })();
1894
+ phase1Promise.catch(() => { });
1895
+ return new DurablePromise(async () => {
1896
+ checkpoint.markOperationAwaited(stepId);
2501
1897
  return await phase1Promise;
2502
1898
  });
2503
1899
  };
2504
1900
  };
2505
- const handleCompletedWaitForCondition = async (context, stepId, stepName, serdes = defaultSerdes) => {
2506
- log("⏭️", "waitForCondition already finished, returning cached result:", {
2507
- stepId,
2508
- });
2509
- const stepData = context.getStepData(stepId);
2510
- const result = stepData?.StepDetails?.Result;
2511
- return await safeDeserialize(serdes, result, stepId, stepName, context.terminationManager, context.durableExecutionArn);
2512
- };
2513
- const executeWaitForCondition = async (context, checkpoint, stepId, name, check, config, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, onAwaitedChange) => {
2514
- const serdes = config.serdes || defaultSerdes;
2515
- // Get current state from previous checkpoint or use initial state
2516
- let currentState;
2517
- const existingOperation = context.getStepData(stepId);
2518
- if (existingOperation?.Status === clientLambda.OperationStatus.STARTED ||
2519
- existingOperation?.Status === clientLambda.OperationStatus.READY) {
2520
- // This is a retry - get state from previous checkpoint
2521
- const checkpointData = existingOperation.StepDetails?.Result;
2522
- if (checkpointData) {
2523
- try {
2524
- // Try to deserialize the checkpoint data directly
2525
- const serdesContext = {
2526
- entityId: stepId,
2527
- durableExecutionArn: context.durableExecutionArn,
2528
- };
2529
- currentState = await serdes.deserialize(checkpointData, serdesContext);
2530
- }
2531
- catch (error) {
2532
- log("⚠️", "Failed to deserialize checkpoint data, using initial state:", {
2533
- stepId,
2534
- name,
2535
- error,
2536
- });
2537
- currentState = config.initialState;
2538
- }
2539
- }
2540
- else {
2541
- currentState = config.initialState;
2542
- }
2543
- }
2544
- else {
2545
- // First execution
2546
- currentState = config.initialState;
2547
- }
2548
- // Get the current attempt number (1-based for wait strategy consistency)
2549
- const currentAttempt = existingOperation?.StepDetails?.Attempt || 1;
2550
- // Checkpoint START for observability (fire and forget) - only if not already started
2551
- const stepData = context.getStepData(stepId);
2552
- if (stepData?.Status !== clientLambda.OperationStatus.STARTED) {
2553
- checkpoint.checkpoint(stepId, {
2554
- Id: stepId,
2555
- ParentId: parentId,
2556
- Action: clientLambda.OperationAction.START,
2557
- SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
2558
- Type: clientLambda.OperationType.STEP,
2559
- Name: name,
2560
- });
2561
- }
2562
- try {
2563
- // Create WaitForConditionContext with enriched logger for the check function
2564
- const waitForConditionContext = {
2565
- logger,
2566
- };
2567
- // Execute the check function
2568
- addRunningOperation(stepId);
2569
- let newState;
2570
- try {
2571
- newState = await runWithContext(stepId, parentId, () => check(currentState, waitForConditionContext), currentAttempt + 1, DurableExecutionMode.ExecutionMode);
2572
- }
2573
- finally {
2574
- removeRunningOperation(stepId);
2575
- }
2576
- // Serialize the new state for consistency
2577
- const serializedState = await safeSerialize(serdes, newState, stepId, name, context.terminationManager, context.durableExecutionArn);
2578
- // Deserialize for consistency with replay behavior
2579
- const deserializedState = await safeDeserialize(serdes, serializedState, stepId, name, context.terminationManager, context.durableExecutionArn);
2580
- // Check if condition is met using the wait strategy
2581
- const decision = config.waitStrategy(deserializedState, currentAttempt);
2582
- log("🔍", "waitForCondition check completed:", {
2583
- stepId,
2584
- name,
2585
- currentAttempt: currentAttempt,
2586
- shouldContinue: decision.shouldContinue,
2587
- delayInSeconds: decision.shouldContinue
2588
- ? durationToSeconds(decision.delay)
2589
- : undefined,
2590
- });
2591
- if (!decision.shouldContinue) {
2592
- // Condition is met - complete successfully
2593
- await checkpoint.checkpoint(stepId, {
2594
- Id: stepId,
2595
- ParentId: parentId,
2596
- Action: clientLambda.OperationAction.SUCCEED,
2597
- SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
2598
- Type: clientLambda.OperationType.STEP,
2599
- Payload: serializedState,
2600
- Name: name,
2601
- });
2602
- log("✅", "waitForCondition completed successfully:", {
2603
- stepId,
2604
- name,
2605
- result: deserializedState,
2606
- totalAttempts: currentAttempt,
2607
- });
2608
- return deserializedState;
2609
- }
2610
- else {
2611
- // Condition not met - schedule retry
2612
- // Only checkpoint the state, not the attempt number (system handles that)
2613
- await checkpoint.checkpoint(stepId, {
2614
- Id: stepId,
2615
- ParentId: parentId,
2616
- Action: clientLambda.OperationAction.RETRY,
2617
- SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
2618
- Type: clientLambda.OperationType.STEP,
2619
- Payload: serializedState, // Just the state, not wrapped in an object
2620
- Name: name,
2621
- StepOptions: {
2622
- NextAttemptDelaySeconds: durationToSeconds(decision.delay),
2623
- },
2624
- });
2625
- // Wait for continuation and signal main loop to continue
2626
- await waitForContinuation(context, stepId, name, hasRunningOperations, checkpoint, getOperationsEmitter(), onAwaitedChange);
2627
- return CONTINUE_MAIN_LOOP;
2628
- }
2629
- }
2630
- catch (error) {
2631
- log("❌", "waitForCondition check function failed:", {
2632
- stepId,
2633
- name,
2634
- error,
2635
- currentAttempt: currentAttempt,
2636
- });
2637
- // Mark as failed - waitForCondition doesn't have its own retry logic for errors
2638
- // If the check function throws, it's considered a failure
2639
- await checkpoint.checkpoint(stepId, {
2640
- Id: stepId,
2641
- ParentId: parentId,
2642
- Action: clientLambda.OperationAction.FAIL,
2643
- SubType: exports.OperationSubType.WAIT_FOR_CONDITION,
2644
- Type: clientLambda.OperationType.STEP,
2645
- Error: createErrorObjectFromError(error),
2646
- Name: name,
2647
- });
2648
- // Reconstruct error from ErrorObject for deterministic behavior
2649
- const errorObject = createErrorObjectFromError(error);
2650
- throw DurableOperationError.fromErrorObject(errorObject);
2651
- }
2652
- };
2653
1901
 
2654
- const createCallbackPromise = (context, stepId, stepName, serdes, hasRunningOperations, operationsEmitter, terminationMessage, checkAndUpdateReplayMode) => {
1902
+ const createCallbackPromise = (context, checkpoint, stepId, stepName, serdes, checkAndUpdateReplayMode) => {
2655
1903
  return new DurablePromise(async () => {
2656
- log("🔄", "Callback promise phase 2 executing:", { stepId, stepName });
2657
- // Main callback logic - can be re-executed if step status changes
2658
- while (true) {
2659
- const stepData = context.getStepData(stepId);
2660
- // Handle case where stepData doesn't exist yet
2661
- // While Phase 1 should create stepData via checkpoint before Phase 2 starts,
2662
- // this can be undefined in test scenarios
2663
- if (!stepData) {
2664
- log("⚠️", "Step data not found, waiting for callback creation:", {
2665
- stepId,
2666
- });
2667
- if (hasRunningOperations()) {
2668
- await waitBeforeContinue({
2669
- checkHasRunningOperations: true,
2670
- checkStepStatus: true,
2671
- checkTimer: false,
2672
- stepId,
2673
- context,
2674
- hasRunningOperations,
2675
- operationsEmitter,
2676
- });
2677
- continue; // Re-evaluate after waiting
2678
- }
2679
- // No other operations and no step data - terminate gracefully
2680
- log("⏳", "No step data found and no running operations, terminating");
2681
- return terminate(context, TerminationReason.CALLBACK_PENDING, terminationMessage);
2682
- }
2683
- if (stepData.Status === clientLambda.OperationStatus.SUCCEEDED) {
2684
- const callbackData = stepData.CallbackDetails;
2685
- if (!callbackData?.CallbackId) {
2686
- throw new CallbackError(`No callback ID found for completed callback: ${stepId}`);
2687
- }
2688
- const result = await safeDeserialize(serdes, callbackData.Result, stepId, stepName, context.terminationManager, context.durableExecutionArn);
2689
- // Check and update replay mode after callback completion
2690
- checkAndUpdateReplayMode();
2691
- return result;
2692
- }
2693
- if (stepData.Status === clientLambda.OperationStatus.FAILED ||
2694
- stepData.Status === clientLambda.OperationStatus.TIMED_OUT) {
2695
- const callbackData = stepData.CallbackDetails;
2696
- const error = callbackData?.Error;
2697
- if (error) {
2698
- const cause = new Error(error.ErrorMessage);
2699
- cause.name = error.ErrorType || "Error";
2700
- cause.stack = error.StackTrace?.join("\n");
2701
- throw new CallbackError(error.ErrorMessage || "Callback failed", cause, error.ErrorData);
2702
- }
2703
- throw new CallbackError("Callback failed");
2704
- }
2705
- if (stepData.Status === clientLambda.OperationStatus.STARTED) {
2706
- // Callback is still pending
2707
- if (hasRunningOperations()) {
2708
- // Wait for other operations or callback completion
2709
- log("⏳", "Callback still pending, waiting for other operations");
2710
- await waitBeforeContinue({
2711
- checkHasRunningOperations: true,
2712
- checkStepStatus: true,
2713
- checkTimer: false,
2714
- stepId,
2715
- context,
2716
- hasRunningOperations,
2717
- operationsEmitter,
2718
- });
2719
- continue; // Re-evaluate status after waiting
2720
- }
2721
- // No other operations running - terminate
2722
- log("⏳", "Callback still pending, terminating");
2723
- return terminate(context, TerminationReason.CALLBACK_PENDING, terminationMessage);
1904
+ log("🔄", "Callback promise phase 2:", { stepId, stepName });
1905
+ checkpoint.markOperationAwaited(stepId);
1906
+ await checkpoint.waitForStatusChange(stepId);
1907
+ const stepData = context.getStepData(stepId);
1908
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
1909
+ log("✅", "Callback completed:", { stepId });
1910
+ checkAndUpdateReplayMode();
1911
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1912
+ const callbackData = stepData.CallbackDetails;
1913
+ if (!callbackData) {
1914
+ throw new CallbackError(`No callback data found for completed callback: ${stepId}`);
2724
1915
  }
2725
- // Should not reach here, but handle unexpected status
2726
- throw new CallbackError(`Unexpected callback status: ${stepData.Status}`);
1916
+ const result = await safeDeserialize(serdes, callbackData.Result, stepId, stepName, context.terminationManager, context.durableExecutionArn);
1917
+ return result;
1918
+ }
1919
+ // Handle failure
1920
+ log("❌", "Callback failed:", { stepId, status: stepData?.Status });
1921
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED);
1922
+ const callbackData = stepData?.CallbackDetails;
1923
+ const error = callbackData?.Error;
1924
+ if (error) {
1925
+ const cause = new Error(error.ErrorMessage);
1926
+ cause.name = error.ErrorType || "Error";
1927
+ cause.stack = error.StackTrace?.join("\n");
1928
+ throw new CallbackError(error.ErrorMessage || "Callback failed", cause, error.ErrorData);
2727
1929
  }
1930
+ throw new CallbackError("Callback failed");
2728
1931
  });
2729
1932
  };
2730
1933
 
@@ -2732,7 +1935,7 @@ const createPassThroughSerdes = () => ({
2732
1935
  serialize: async (value) => value,
2733
1936
  deserialize: async (data) => data,
2734
1937
  });
2735
- const createCallback = (context, checkpoint, createStepId, hasRunningOperations, getOperationsEmitter, checkAndUpdateReplayMode, parentId) => {
1938
+ const createCallback = (context, checkpoint, createStepId, checkAndUpdateReplayMode, parentId) => {
2736
1939
  return (nameOrConfig, maybeConfig) => {
2737
1940
  let name;
2738
1941
  let config;
@@ -2745,82 +1948,99 @@ const createCallback = (context, checkpoint, createStepId, hasRunningOperations,
2745
1948
  }
2746
1949
  const stepId = createStepId();
2747
1950
  const serdes = config?.serdes || createPassThroughSerdes();
2748
- // Validate replay consistency first
2749
- const stepData = context.getStepData(stepId);
2750
- validateReplayConsistency(stepId, {
2751
- type: clientLambda.OperationType.CALLBACK,
2752
- name,
2753
- subType: exports.OperationSubType.CALLBACK,
2754
- }, stepData, context);
2755
- // Phase 1: Setup and checkpoint (immediate execution)
2756
- const setupPromise = (async () => {
2757
- log("📞", "Creating callback phase 1:", { stepId, name, config });
2758
- // Handle already completed callbacks
1951
+ // Phase 1: Setup and checkpoint
1952
+ let isCompleted = false;
1953
+ const phase1Promise = (async () => {
1954
+ log("📞", "Callback phase 1:", { stepId, name });
1955
+ let stepData = context.getStepData(stepId);
1956
+ // Validate replay consistency
1957
+ validateReplayConsistency(stepId, {
1958
+ type: clientLambda.OperationType.CALLBACK,
1959
+ name,
1960
+ subType: exports.OperationSubType.CALLBACK,
1961
+ }, stepData, context);
1962
+ // Check if already completed
2759
1963
  if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
2760
- log("⏭️", "Callback already completed in phase 1:", { stepId });
2761
- return { wasNewCallback: false };
1964
+ log("⏭️", "Callback already completed:", { stepId });
1965
+ checkAndUpdateReplayMode();
1966
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1967
+ metadata: {
1968
+ stepId,
1969
+ name,
1970
+ type: clientLambda.OperationType.CALLBACK,
1971
+ subType: exports.OperationSubType.CALLBACK,
1972
+ parentId,
1973
+ },
1974
+ });
1975
+ isCompleted = true;
1976
+ return;
2762
1977
  }
1978
+ // Check if already failed
2763
1979
  if (stepData?.Status === clientLambda.OperationStatus.FAILED ||
2764
1980
  stepData?.Status === clientLambda.OperationStatus.TIMED_OUT) {
2765
- log("❌", "Callback already failed in phase 1:", { stepId });
2766
- return { wasNewCallback: false };
1981
+ log("❌", "Callback already failed:", { stepId });
1982
+ checkpoint.markOperationState(stepId, OperationLifecycleState.COMPLETED, {
1983
+ metadata: {
1984
+ stepId,
1985
+ name,
1986
+ type: clientLambda.OperationType.CALLBACK,
1987
+ subType: exports.OperationSubType.CALLBACK,
1988
+ parentId,
1989
+ },
1990
+ });
1991
+ isCompleted = true;
1992
+ return;
2767
1993
  }
2768
- // Handle already started callbacks
2769
- if (stepData?.Status === clientLambda.OperationStatus.STARTED) {
2770
- log("⏳", "Callback already started in phase 1:", { stepId });
2771
- return { wasNewCallback: false };
1994
+ // Start callback if not already started
1995
+ if (!stepData) {
1996
+ await checkpoint.checkpoint(stepId, {
1997
+ Id: stepId,
1998
+ ParentId: parentId,
1999
+ Action: "START",
2000
+ SubType: exports.OperationSubType.CALLBACK,
2001
+ Type: clientLambda.OperationType.CALLBACK,
2002
+ Name: name,
2003
+ CallbackOptions: {
2004
+ TimeoutSeconds: config?.timeout
2005
+ ? durationToSeconds(config.timeout)
2006
+ : undefined,
2007
+ HeartbeatTimeoutSeconds: config?.heartbeatTimeout
2008
+ ? durationToSeconds(config.heartbeatTimeout)
2009
+ : undefined,
2010
+ },
2011
+ });
2012
+ // Refresh stepData after checkpoint
2013
+ stepData = context.getStepData(stepId);
2772
2014
  }
2773
- // Create new callback - checkpoint START operation
2774
- log("🆕", "Creating new callback in phase 1:", { stepId, name });
2775
- await checkpoint.checkpoint(stepId, {
2776
- Id: stepId,
2777
- ParentId: parentId,
2778
- Action: "START",
2779
- SubType: exports.OperationSubType.CALLBACK,
2780
- Type: clientLambda.OperationType.CALLBACK,
2781
- Name: name,
2782
- CallbackOptions: {
2783
- TimeoutSeconds: config?.timeout
2784
- ? durationToSeconds(config.timeout)
2785
- : undefined,
2786
- HeartbeatTimeoutSeconds: config?.heartbeatTimeout
2787
- ? durationToSeconds(config.heartbeatTimeout)
2788
- : undefined,
2015
+ // Mark as IDLE_NOT_AWAITED
2016
+ checkpoint.markOperationState(stepId, OperationLifecycleState.IDLE_NOT_AWAITED, {
2017
+ metadata: {
2018
+ stepId,
2019
+ name,
2020
+ type: clientLambda.OperationType.CALLBACK,
2021
+ subType: exports.OperationSubType.CALLBACK,
2022
+ parentId,
2789
2023
  },
2790
2024
  });
2791
- log("✅", "Callback checkpoint completed in phase 1:", { stepId });
2792
- return { wasNewCallback: true };
2793
- })().catch((error) => {
2794
- log("❌", "Callback phase 1 error:", { stepId, error: error.message });
2795
- throw error;
2796
- });
2797
- // Return DurablePromise that executes phase 2 when awaited
2025
+ log("✅", "Callback phase 1 complete:", { stepId });
2026
+ })();
2027
+ phase1Promise.catch(() => { });
2028
+ // Phase 2: Handle results and create callback promise
2798
2029
  return new DurablePromise(async () => {
2799
- // Wait for phase 1 to complete
2800
- const { wasNewCallback } = await setupPromise;
2801
- // Phase 2: Handle results and create callback promise
2802
- log("🔄", "Callback phase 2 executing:", { stepId, name });
2803
- const stepData = context.getStepData(stepId);
2804
- // Handle completed callbacks
2805
- if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
2806
- const callbackData = stepData.CallbackDetails;
2030
+ await phase1Promise;
2031
+ if (isCompleted) {
2032
+ const stepData = context.getStepData(stepId);
2033
+ const callbackData = stepData?.CallbackDetails;
2807
2034
  if (!callbackData?.CallbackId) {
2808
- throw new CallbackError(`No callback ID found for completed callback: ${stepId}`);
2035
+ throw new CallbackError(`No callback ID found for callback: ${stepId}`);
2809
2036
  }
2810
- const deserializedResult = await safeDeserialize(serdes, callbackData.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
2811
- const resolvedPromise = new DurablePromise(async () => deserializedResult);
2812
- // Check and update replay mode after callback completion
2813
- checkAndUpdateReplayMode();
2814
- return [resolvedPromise, callbackData.CallbackId];
2815
- }
2816
- // Handle failed callbacks
2817
- if (stepData?.Status === clientLambda.OperationStatus.FAILED ||
2818
- stepData?.Status === clientLambda.OperationStatus.TIMED_OUT) {
2819
- const callbackData = stepData.CallbackDetails;
2820
- if (!callbackData?.CallbackId) {
2821
- throw new CallbackError(`No callback ID found for failed callback: ${stepId}`);
2037
+ if (stepData?.Status === clientLambda.OperationStatus.SUCCEEDED) {
2038
+ const deserializedResult = await safeDeserialize(serdes, callbackData.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
2039
+ const resolvedPromise = new DurablePromise(async () => deserializedResult);
2040
+ return [resolvedPromise, callbackData.CallbackId];
2822
2041
  }
2823
- const error = stepData.CallbackDetails?.Error;
2042
+ // Handle failure
2043
+ const error = stepData?.CallbackDetails?.Error;
2824
2044
  const callbackError = error
2825
2045
  ? (() => {
2826
2046
  const cause = new Error(error.ErrorMessage);
@@ -2834,25 +2054,15 @@ const createCallback = (context, checkpoint, createStepId, hasRunningOperations,
2834
2054
  });
2835
2055
  return [rejectedPromise, callbackData.CallbackId];
2836
2056
  }
2837
- // Handle started or new callbacks
2057
+ log("📞", "Callback phase 2:", { stepId });
2058
+ const stepData = context.getStepData(stepId);
2838
2059
  const callbackData = stepData?.CallbackDetails;
2839
2060
  if (!callbackData?.CallbackId) {
2840
- const errorMessage = wasNewCallback
2841
- ? `Callback ID not found in stepData after checkpoint: ${stepId}`
2842
- : `No callback ID found for started callback: ${stepId}`;
2843
- throw new CallbackError(errorMessage);
2061
+ throw new CallbackError(`No callback ID found for started callback: ${stepId}`);
2844
2062
  }
2845
2063
  const callbackId = callbackData.CallbackId;
2846
- // Create callback promise that handles completion
2847
- const terminationMessage = wasNewCallback
2848
- ? `Callback ${name || stepId} created and pending external completion`
2849
- : `Callback ${name || stepId} is pending external completion`;
2850
- const callbackPromise = createCallbackPromise(context, stepId, name, serdes, hasRunningOperations, getOperationsEmitter(), terminationMessage, checkAndUpdateReplayMode);
2851
- log("✅", "Callback created successfully in phase 2:", {
2852
- stepId,
2853
- name,
2854
- callbackId,
2855
- });
2064
+ const callbackPromise = createCallbackPromise(context, checkpoint, stepId, name, serdes, checkAndUpdateReplayMode);
2065
+ log("✅", "Callback created:", { stepId, name, callbackId });
2856
2066
  return [callbackPromise, callbackId];
2857
2067
  });
2858
2068
  };
@@ -3309,6 +2519,42 @@ class ConcurrencyController {
3309
2519
  (childStepData.Status === clientLambda.OperationStatus.SUCCEEDED ||
3310
2520
  childStepData.Status === clientLambda.OperationStatus.FAILED));
3311
2521
  }
2522
+ getCompletionReason(failureCount, successCount, completedCount, items, config) {
2523
+ // Check tolerance first, before checking if all completed
2524
+ const completion = config.completionConfig;
2525
+ // Handle fail-fast behavior (no completion config or empty completion config)
2526
+ if (!completion) {
2527
+ if (failureCount > 0)
2528
+ return "FAILURE_TOLERANCE_EXCEEDED";
2529
+ }
2530
+ else {
2531
+ const hasAnyCompletionCriteria = Object.values(completion).some((value) => value !== undefined);
2532
+ if (!hasAnyCompletionCriteria) {
2533
+ if (failureCount > 0)
2534
+ return "FAILURE_TOLERANCE_EXCEEDED";
2535
+ }
2536
+ else {
2537
+ // Check specific tolerance thresholds
2538
+ if (completion.toleratedFailureCount !== undefined &&
2539
+ failureCount > completion.toleratedFailureCount) {
2540
+ return "FAILURE_TOLERANCE_EXCEEDED";
2541
+ }
2542
+ if (completion.toleratedFailurePercentage !== undefined) {
2543
+ const failurePercentage = (failureCount / items.length) * 100;
2544
+ if (failurePercentage > completion.toleratedFailurePercentage) {
2545
+ return "FAILURE_TOLERANCE_EXCEEDED";
2546
+ }
2547
+ }
2548
+ }
2549
+ }
2550
+ // Check other completion reasons
2551
+ if (completedCount === items.length)
2552
+ return "ALL_COMPLETED";
2553
+ if (config.completionConfig?.minSuccessful !== undefined &&
2554
+ successCount >= config.completionConfig.minSuccessful)
2555
+ return "MIN_SUCCESSFUL_REACHED";
2556
+ return "ALL_COMPLETED";
2557
+ }
3312
2558
  async executeItems(items, executor, parentContext, config, durableExecutionMode = DurableExecutionMode.ExecutionMode, entityId, executionContext) {
3313
2559
  // In replay mode, we're reconstructing the result from child contexts
3314
2560
  if (durableExecutionMode === DurableExecutionMode.ReplaySucceededContext) {
@@ -3422,17 +2668,9 @@ class ConcurrencyController {
3422
2668
  completedCount,
3423
2669
  totalCount: resultItems.length,
3424
2670
  });
3425
- // Reconstruct the completion reason based on replay results
3426
2671
  const successCount = resultItems.filter((item) => item.status === exports.BatchItemStatus.SUCCEEDED).length;
3427
- const getCompletionReason = () => {
3428
- if (completedCount === items.length)
3429
- return "ALL_COMPLETED";
3430
- if (config.completionConfig?.minSuccessful !== undefined &&
3431
- successCount >= config.completionConfig.minSuccessful)
3432
- return "MIN_SUCCESSFUL_REACHED";
3433
- return "FAILURE_TOLERANCE_EXCEEDED";
3434
- };
3435
- return new BatchResultImpl(resultItems, getCompletionReason());
2672
+ const failureCount = completedCount - successCount;
2673
+ return new BatchResultImpl(resultItems, this.getCompletionReason(failureCount, successCount, completedCount, items, config));
3436
2674
  }
3437
2675
  async executeItemsConcurrently(items, executor, parentContext, config) {
3438
2676
  const maxConcurrency = config.maxConcurrency || Infinity;
@@ -3479,13 +2717,8 @@ class ConcurrencyController {
3479
2717
  }
3480
2718
  return false;
3481
2719
  };
3482
- const getCompletionReason = () => {
3483
- if (completedCount === items.length)
3484
- return "ALL_COMPLETED";
3485
- if (config.completionConfig?.minSuccessful !== undefined &&
3486
- successCount >= config.completionConfig.minSuccessful)
3487
- return "MIN_SUCCESSFUL_REACHED";
3488
- return "FAILURE_TOLERANCE_EXCEEDED";
2720
+ const getCompletionReason = (failureCount) => {
2721
+ return this.getCompletionReason(failureCount, successCount, completedCount, items, config);
3489
2722
  };
3490
2723
  const tryStartNext = () => {
3491
2724
  while (activeCount < maxConcurrency &&
@@ -3556,7 +2789,7 @@ class ConcurrencyController {
3556
2789
  startedCount: finalBatchItems.filter((item) => item.status === exports.BatchItemStatus.STARTED).length,
3557
2790
  totalCount: finalBatchItems.length,
3558
2791
  });
3559
- const result = new BatchResultImpl(finalBatchItems, getCompletionReason());
2792
+ const result = new BatchResultImpl(finalBatchItems, getCompletionReason(failureCount));
3560
2793
  resolve(result);
3561
2794
  }
3562
2795
  else {
@@ -3628,347 +2861,971 @@ const createConcurrentExecutionHandler = (context, runInChildContext, skipNextOp
3628
2861
  Array.isArray(result.all)) {
3629
2862
  return restoreBatchResult(result);
3630
2863
  }
3631
- return result;
3632
- })();
3633
- // Attach catch handler to prevent unhandled promise rejections
3634
- // The error will still be thrown when the DurablePromise is awaited
3635
- phase1Promise.catch(() => { });
3636
- // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
3637
- return new DurablePromise(async () => {
3638
- return await phase1Promise;
2864
+ return result;
2865
+ })();
2866
+ // Attach catch handler to prevent unhandled promise rejections
2867
+ // The error will still be thrown when the DurablePromise is awaited
2868
+ phase1Promise.catch(() => { });
2869
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
2870
+ return new DurablePromise(async () => {
2871
+ return await phase1Promise;
2872
+ });
2873
+ };
2874
+ };
2875
+
2876
+ class ModeManagement {
2877
+ captureExecutionState;
2878
+ checkAndUpdateReplayMode;
2879
+ checkForNonResolvingPromise;
2880
+ getDurableExecutionMode;
2881
+ setDurableExecutionMode;
2882
+ constructor(captureExecutionState, checkAndUpdateReplayMode, checkForNonResolvingPromise, getDurableExecutionMode, setDurableExecutionMode) {
2883
+ this.captureExecutionState = captureExecutionState;
2884
+ this.checkAndUpdateReplayMode = checkAndUpdateReplayMode;
2885
+ this.checkForNonResolvingPromise = checkForNonResolvingPromise;
2886
+ this.getDurableExecutionMode = getDurableExecutionMode;
2887
+ this.setDurableExecutionMode = setDurableExecutionMode;
2888
+ }
2889
+ withModeManagement(operation) {
2890
+ const shouldSwitchToExecutionMode = this.captureExecutionState();
2891
+ this.checkAndUpdateReplayMode();
2892
+ const nonResolvingPromise = this.checkForNonResolvingPromise();
2893
+ if (nonResolvingPromise)
2894
+ return nonResolvingPromise;
2895
+ try {
2896
+ return operation();
2897
+ }
2898
+ finally {
2899
+ if (shouldSwitchToExecutionMode) {
2900
+ this.setDurableExecutionMode(DurableExecutionMode.ExecutionMode);
2901
+ }
2902
+ }
2903
+ }
2904
+ withDurableModeManagement(operation) {
2905
+ const shouldSwitchToExecutionMode = this.captureExecutionState();
2906
+ this.checkAndUpdateReplayMode();
2907
+ const nonResolvingPromise = this.checkForNonResolvingPromise();
2908
+ if (nonResolvingPromise) {
2909
+ return new DurablePromise(async () => {
2910
+ await nonResolvingPromise;
2911
+ // This will never be reached
2912
+ throw new Error("Unreachable code");
2913
+ });
2914
+ }
2915
+ try {
2916
+ return operation();
2917
+ }
2918
+ finally {
2919
+ if (shouldSwitchToExecutionMode) {
2920
+ this.setDurableExecutionMode(DurableExecutionMode.ExecutionMode);
2921
+ }
2922
+ }
2923
+ }
2924
+ }
2925
+
2926
+ const HASH_LENGTH = 16;
2927
+ /**
2928
+ * Creates an MD5 hash of the input string for better performance than SHA-256
2929
+ * @param input - The string to hash
2930
+ * @returns The truncated hexadecimal hash string
2931
+ */
2932
+ const hashId = (input) => {
2933
+ return crypto.createHash("md5")
2934
+ .update(input)
2935
+ .digest("hex")
2936
+ .substring(0, HASH_LENGTH);
2937
+ };
2938
+ /**
2939
+ * Helper function to get step data using the original stepId
2940
+ * This function handles the hashing internally so callers don't need to worry about it
2941
+ * @param stepData - The stepData record from context
2942
+ * @param stepId - The original stepId (will be hashed internally)
2943
+ * @returns The operation data or undefined if not found
2944
+ */
2945
+ const getStepData = (stepData, stepId) => {
2946
+ const hashedId = hashId(stepId);
2947
+ return stepData[hashedId];
2948
+ };
2949
+
2950
+ class DurableContextImpl {
2951
+ executionContext;
2952
+ lambdaContext;
2953
+ _stepPrefix;
2954
+ _stepCounter = 0;
2955
+ durableLogger;
2956
+ modeAwareLoggingEnabled = true;
2957
+ checkpoint;
2958
+ durableExecutionMode;
2959
+ _parentId;
2960
+ modeManagement;
2961
+ durableExecution;
2962
+ logger;
2963
+ constructor(executionContext, lambdaContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId) {
2964
+ this.executionContext = executionContext;
2965
+ this.lambdaContext = lambdaContext;
2966
+ this._stepPrefix = stepPrefix;
2967
+ this._parentId = parentId;
2968
+ this.durableExecution = durableExecution;
2969
+ this.durableLogger = inheritedLogger;
2970
+ this.durableLogger.configureDurableLoggingContext?.(this.getDurableLoggingContext());
2971
+ this.logger = this.createModeAwareLogger(inheritedLogger);
2972
+ this.durableExecutionMode = durableExecutionMode;
2973
+ this.checkpoint = durableExecution.checkpointManager;
2974
+ this.modeManagement = new ModeManagement(this.captureExecutionState.bind(this), this.checkAndUpdateReplayMode.bind(this), this.checkForNonResolvingPromise.bind(this), () => this.durableExecutionMode, (mode) => {
2975
+ this.durableExecutionMode = mode;
2976
+ });
2977
+ }
2978
+ getDurableLoggingContext() {
2979
+ return {
2980
+ getDurableLogData: () => {
2981
+ const activeContext = getActiveContext();
2982
+ const result = {
2983
+ executionArn: this.executionContext.durableExecutionArn,
2984
+ requestId: this.executionContext.requestId,
2985
+ tenantId: this.executionContext.tenantId,
2986
+ operationId: !activeContext || activeContext?.contextId === "root"
2987
+ ? undefined
2988
+ : hashId(activeContext.contextId),
2989
+ };
2990
+ if (activeContext?.attempt !== undefined) {
2991
+ result.attempt = activeContext.attempt;
2992
+ }
2993
+ return result;
2994
+ },
2995
+ };
2996
+ }
2997
+ shouldLog() {
2998
+ const activeContext = getActiveContext();
2999
+ if (!this.modeAwareLoggingEnabled || !activeContext) {
3000
+ return true;
3001
+ }
3002
+ if (activeContext.contextId === "root") {
3003
+ return this.durableExecutionMode === DurableExecutionMode.ExecutionMode;
3004
+ }
3005
+ return (activeContext.durableExecutionMode === DurableExecutionMode.ExecutionMode);
3006
+ }
3007
+ createModeAwareLogger(logger) {
3008
+ const durableContextLogger = {
3009
+ warn: (...args) => {
3010
+ if (this.shouldLog()) {
3011
+ return logger.warn(...args);
3012
+ }
3013
+ },
3014
+ debug: (...args) => {
3015
+ if (this.shouldLog()) {
3016
+ return logger.debug(...args);
3017
+ }
3018
+ },
3019
+ info: (...args) => {
3020
+ if (this.shouldLog()) {
3021
+ return logger.info(...args);
3022
+ }
3023
+ },
3024
+ error: (...args) => {
3025
+ if (this.shouldLog()) {
3026
+ return logger.error(...args);
3027
+ }
3028
+ },
3029
+ };
3030
+ if ("log" in logger) {
3031
+ durableContextLogger.log = (level, ...args) => {
3032
+ if (this.shouldLog()) {
3033
+ return logger.log?.(level, ...args);
3034
+ }
3035
+ };
3036
+ }
3037
+ return durableContextLogger;
3038
+ }
3039
+ createStepId() {
3040
+ this._stepCounter++;
3041
+ return this._stepPrefix
3042
+ ? `${this._stepPrefix}-${this._stepCounter}`
3043
+ : `${this._stepCounter}`;
3044
+ }
3045
+ getNextStepId() {
3046
+ const nextCounter = this._stepCounter + 1;
3047
+ return this._stepPrefix
3048
+ ? `${this._stepPrefix}-${nextCounter}`
3049
+ : `${nextCounter}`;
3050
+ }
3051
+ /**
3052
+ * Skips the next operation by incrementing the step counter.
3053
+ * Used internally by concurrent execution handler during replay to skip incomplete items.
3054
+ * @internal
3055
+ */
3056
+ skipNextOperation() {
3057
+ this._stepCounter++;
3058
+ }
3059
+ checkAndUpdateReplayMode() {
3060
+ if (this.durableExecutionMode === DurableExecutionMode.ReplayMode) {
3061
+ const nextStepId = this.getNextStepId();
3062
+ const nextStepData = this.executionContext.getStepData(nextStepId);
3063
+ if (!nextStepData) {
3064
+ this.durableExecutionMode = DurableExecutionMode.ExecutionMode;
3065
+ }
3066
+ }
3067
+ }
3068
+ captureExecutionState() {
3069
+ const wasInReplayMode = this.durableExecutionMode === DurableExecutionMode.ReplayMode;
3070
+ const nextStepId = this.getNextStepId();
3071
+ const stepData = this.executionContext.getStepData(nextStepId);
3072
+ const wasNotFinished = !!(stepData &&
3073
+ stepData.Status !== clientLambda.OperationStatus.SUCCEEDED &&
3074
+ stepData.Status !== clientLambda.OperationStatus.FAILED);
3075
+ return wasInReplayMode && wasNotFinished;
3076
+ }
3077
+ checkForNonResolvingPromise() {
3078
+ if (this.durableExecutionMode === DurableExecutionMode.ReplaySucceededContext) {
3079
+ const nextStepId = this.getNextStepId();
3080
+ const nextStepData = this.executionContext.getStepData(nextStepId);
3081
+ if (nextStepData &&
3082
+ nextStepData.Status !== clientLambda.OperationStatus.SUCCEEDED &&
3083
+ nextStepData.Status !== clientLambda.OperationStatus.FAILED) {
3084
+ return new Promise(() => { }); // Non-resolving promise
3085
+ }
3086
+ }
3087
+ return null;
3088
+ }
3089
+ withModeManagement(operation) {
3090
+ return this.modeManagement.withModeManagement(operation);
3091
+ }
3092
+ withDurableModeManagement(operation) {
3093
+ return this.modeManagement.withDurableModeManagement(operation);
3094
+ }
3095
+ step(nameOrFn, fnOrOptions, maybeOptions) {
3096
+ validateContextUsage(this._stepPrefix, "step", this.executionContext.terminationManager);
3097
+ return this.withDurableModeManagement(() => {
3098
+ const stepHandler = createStepHandler(this.executionContext, this.checkpoint, this.lambdaContext, this.createStepId.bind(this), this.durableLogger, this._parentId);
3099
+ return stepHandler(nameOrFn, fnOrOptions, maybeOptions);
3100
+ });
3101
+ }
3102
+ invoke(nameOrFuncId, funcIdOrInput, inputOrConfig, maybeConfig) {
3103
+ validateContextUsage(this._stepPrefix, "invoke", this.executionContext.terminationManager);
3104
+ return this.withDurableModeManagement(() => {
3105
+ const invokeHandler = createInvokeHandler(this.executionContext, this.checkpoint, this.createStepId.bind(this), this._parentId, this.checkAndUpdateReplayMode.bind(this));
3106
+ return invokeHandler(...[
3107
+ nameOrFuncId,
3108
+ funcIdOrInput,
3109
+ inputOrConfig,
3110
+ maybeConfig,
3111
+ ]);
3112
+ });
3113
+ }
3114
+ runInChildContext(nameOrFn, fnOrOptions, maybeOptions) {
3115
+ validateContextUsage(this._stepPrefix, "runInChildContext", this.executionContext.terminationManager);
3116
+ return this.withDurableModeManagement(() => {
3117
+ const blockHandler = createRunInChildContextHandler(this.executionContext, this.checkpoint, this.lambdaContext, this.createStepId.bind(this), () => this.durableLogger,
3118
+ // Adapter function to maintain compatibility
3119
+ (executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, _checkpointToken, parentId) => createDurableContext(executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, this.durableExecution, parentId), this._parentId);
3120
+ return blockHandler(nameOrFn, fnOrOptions, maybeOptions);
3121
+ });
3122
+ }
3123
+ wait(nameOrDuration, maybeDuration) {
3124
+ validateContextUsage(this._stepPrefix, "wait", this.executionContext.terminationManager);
3125
+ return this.withDurableModeManagement(() => {
3126
+ const waitHandler = createWaitHandler(this.executionContext, this.checkpoint, this.createStepId.bind(this), this._parentId, this.checkAndUpdateReplayMode.bind(this));
3127
+ return typeof nameOrDuration === "string"
3128
+ ? waitHandler(nameOrDuration, maybeDuration)
3129
+ : waitHandler(nameOrDuration);
3130
+ });
3131
+ }
3132
+ /**
3133
+ * Configure logger behavior for this context
3134
+ *
3135
+ * This method allows partial configuration - only the properties provided will be updated.
3136
+ * For example, calling configureLogger(\{ modeAware: false \}) will only change the modeAware
3137
+ * setting without affecting any previously configured custom logger.
3138
+ *
3139
+ * @param config - Logger configuration options including customLogger and modeAware settings (default: modeAware=true)
3140
+ * @example
3141
+ * // Set custom logger and enable mode-aware logging
3142
+ * context.configureLogger(\{ customLogger: myLogger, modeAware: true \});
3143
+ *
3144
+ * // Later, disable mode-aware logging without changing the custom logger
3145
+ * context.configureLogger(\{ modeAware: false \});
3146
+ */
3147
+ configureLogger(config) {
3148
+ if (config.customLogger !== undefined) {
3149
+ this.durableLogger = config.customLogger;
3150
+ this.durableLogger.configureDurableLoggingContext?.(this.getDurableLoggingContext());
3151
+ this.logger = this.createModeAwareLogger(this.durableLogger);
3152
+ }
3153
+ if (config.modeAware !== undefined) {
3154
+ this.modeAwareLoggingEnabled = config.modeAware;
3155
+ }
3156
+ }
3157
+ createCallback(nameOrConfig, maybeConfig) {
3158
+ validateContextUsage(this._stepPrefix, "createCallback", this.executionContext.terminationManager);
3159
+ return this.withDurableModeManagement(() => {
3160
+ const callbackFactory = createCallback(this.executionContext, this.checkpoint, this.createStepId.bind(this), this.checkAndUpdateReplayMode.bind(this), this._parentId);
3161
+ return callbackFactory(nameOrConfig, maybeConfig);
3162
+ });
3163
+ }
3164
+ waitForCallback(nameOrSubmitter, submitterOrConfig, maybeConfig) {
3165
+ validateContextUsage(this._stepPrefix, "waitForCallback", this.executionContext.terminationManager);
3166
+ return this.withDurableModeManagement(() => {
3167
+ const waitForCallbackHandler = createWaitForCallbackHandler(this.executionContext, this.getNextStepId.bind(this), this.runInChildContext.bind(this));
3168
+ return waitForCallbackHandler(nameOrSubmitter, submitterOrConfig, maybeConfig);
3169
+ });
3170
+ }
3171
+ waitForCondition(nameOrCheckFunc, checkFuncOrConfig, maybeConfig) {
3172
+ validateContextUsage(this._stepPrefix, "waitForCondition", this.executionContext.terminationManager);
3173
+ return this.withDurableModeManagement(() => {
3174
+ const waitForConditionHandler = createWaitForConditionHandler(this.executionContext, this.checkpoint, this.createStepId.bind(this), this.durableLogger, this._parentId);
3175
+ return typeof nameOrCheckFunc === "string" ||
3176
+ nameOrCheckFunc === undefined
3177
+ ? waitForConditionHandler(nameOrCheckFunc, checkFuncOrConfig, maybeConfig)
3178
+ : waitForConditionHandler(nameOrCheckFunc, checkFuncOrConfig);
3179
+ });
3180
+ }
3181
+ map(nameOrItems, itemsOrMapFunc, mapFuncOrConfig, maybeConfig) {
3182
+ validateContextUsage(this._stepPrefix, "map", this.executionContext.terminationManager);
3183
+ return this.withDurableModeManagement(() => {
3184
+ const mapHandler = createMapHandler(this.executionContext, this._executeConcurrently.bind(this));
3185
+ return mapHandler(nameOrItems, itemsOrMapFunc, mapFuncOrConfig, maybeConfig);
3186
+ });
3187
+ }
3188
+ parallel(nameOrBranches, branchesOrConfig, maybeConfig) {
3189
+ validateContextUsage(this._stepPrefix, "parallel", this.executionContext.terminationManager);
3190
+ return this.withDurableModeManagement(() => {
3191
+ const parallelHandler = createParallelHandler(this.executionContext, this._executeConcurrently.bind(this));
3192
+ return parallelHandler(nameOrBranches, branchesOrConfig, maybeConfig);
3193
+ });
3194
+ }
3195
+ _executeConcurrently(nameOrItems, itemsOrExecutor, executorOrConfig, maybeConfig) {
3196
+ validateContextUsage(this._stepPrefix, "_executeConcurrently", this.executionContext.terminationManager);
3197
+ return this.withDurableModeManagement(() => {
3198
+ const concurrentExecutionHandler = createConcurrentExecutionHandler(this.executionContext, this.runInChildContext.bind(this), this.skipNextOperation.bind(this));
3199
+ const promise = concurrentExecutionHandler(nameOrItems, itemsOrExecutor, executorOrConfig, maybeConfig);
3200
+ // Prevent unhandled promise rejections
3201
+ promise?.catch(() => { });
3202
+ return promise;
3203
+ });
3204
+ }
3205
+ get promise() {
3206
+ return createPromiseHandler(this.step.bind(this));
3207
+ }
3208
+ }
3209
+ const createDurableContext = (executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId) => {
3210
+ return new DurableContextImpl(executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId);
3211
+ };
3212
+
3213
+ /**
3214
+ * Error thrown when a checkpoint operation fails due to invocation-level issues
3215
+ * (e.g., 5xx errors, invalid checkpoint token)
3216
+ * This will terminate the current Lambda invocation, but the execution can continue with a new invocation
3217
+ */
3218
+ class CheckpointUnrecoverableInvocationError extends UnrecoverableInvocationError {
3219
+ terminationReason = TerminationReason.CHECKPOINT_FAILED;
3220
+ constructor(message, originalError) {
3221
+ super(message || "Checkpoint operation failed", originalError);
3222
+ }
3223
+ }
3224
+ /**
3225
+ * Error thrown when a checkpoint operation fails due to execution-level issues
3226
+ * (e.g., 4xx errors other than invalid checkpoint token)
3227
+ * This will terminate the entire execution and cannot be recovered
3228
+ */
3229
+ class CheckpointUnrecoverableExecutionError extends UnrecoverableExecutionError {
3230
+ terminationReason = TerminationReason.CHECKPOINT_FAILED;
3231
+ constructor(message, originalError) {
3232
+ super(message || "Checkpoint operation failed", originalError);
3233
+ }
3234
+ }
3235
+
3236
+ const STEP_DATA_UPDATED_EVENT = "stepDataUpdated";
3237
+ class CheckpointManager {
3238
+ durableExecutionArn;
3239
+ stepData;
3240
+ storage;
3241
+ terminationManager;
3242
+ stepDataEmitter;
3243
+ logger;
3244
+ finishedAncestors;
3245
+ queue = [];
3246
+ isProcessing = false;
3247
+ currentTaskToken;
3248
+ forceCheckpointPromises = [];
3249
+ queueCompletionResolver = null;
3250
+ MAX_PAYLOAD_SIZE = 750 * 1024; // 750KB in bytes
3251
+ isTerminating = false;
3252
+ static textEncoder = new TextEncoder();
3253
+ // Operation lifecycle tracking
3254
+ operations = new Map();
3255
+ // Termination cooldown
3256
+ terminationTimer = null;
3257
+ terminationReason = null;
3258
+ TERMINATION_COOLDOWN_MS = 50;
3259
+ constructor(durableExecutionArn, stepData, storage, terminationManager, initialTaskToken, stepDataEmitter, logger, finishedAncestors) {
3260
+ this.durableExecutionArn = durableExecutionArn;
3261
+ this.stepData = stepData;
3262
+ this.storage = storage;
3263
+ this.terminationManager = terminationManager;
3264
+ this.stepDataEmitter = stepDataEmitter;
3265
+ this.logger = logger;
3266
+ this.finishedAncestors = finishedAncestors;
3267
+ this.currentTaskToken = initialTaskToken;
3268
+ }
3269
+ setTerminating() {
3270
+ this.isTerminating = true;
3271
+ log("🛑", "Checkpoint manager marked as terminating");
3272
+ }
3273
+ /**
3274
+ * Mark an ancestor as finished (for run-in-child-context operations)
3275
+ */
3276
+ markAncestorFinished(stepId) {
3277
+ this.finishedAncestors.add(stepId);
3278
+ }
3279
+ /**
3280
+ * Extract parent ID from hierarchical stepId (e.g., "1-2-3" -\> "1-2")
3281
+ */
3282
+ getParentId(stepId) {
3283
+ const lastDashIndex = stepId.lastIndexOf("-");
3284
+ return lastDashIndex > 0 ? stepId.substring(0, lastDashIndex) : undefined;
3285
+ }
3286
+ /**
3287
+ * Checks if any ancestor of the given stepId is finished
3288
+ * Only applies to operations that are descendants of run-in-child-context operations
3289
+ */
3290
+ hasFinishedAncestor(stepId) {
3291
+ // Only use getParentId to avoid mixing hashed and original stepIds
3292
+ let currentParentId = this.getParentId(stepId);
3293
+ while (currentParentId) {
3294
+ // Check if this ancestor is finished
3295
+ if (this.finishedAncestors.has(currentParentId)) {
3296
+ return true;
3297
+ }
3298
+ // Move up to the next ancestor using hierarchical stepId
3299
+ currentParentId = this.getParentId(currentParentId);
3300
+ }
3301
+ return false;
3302
+ }
3303
+ async forceCheckpoint() {
3304
+ if (this.isTerminating) {
3305
+ log("⚠️", "Force checkpoint skipped - termination in progress");
3306
+ return new Promise(() => { }); // Never resolves during termination
3307
+ }
3308
+ return new Promise((resolve, reject) => {
3309
+ this.forceCheckpointPromises.push({ resolve, reject });
3310
+ if (!this.isProcessing) {
3311
+ setImmediate(() => {
3312
+ this.processQueue();
3313
+ });
3314
+ }
3315
+ });
3316
+ }
3317
+ async waitForQueueCompletion() {
3318
+ if (this.queue.length === 0 && !this.isProcessing) {
3319
+ return;
3320
+ }
3321
+ return new Promise((resolve) => {
3322
+ this.queueCompletionResolver = resolve;
3323
+ });
3324
+ }
3325
+ clearQueue() {
3326
+ // Silently clear queue - we're terminating so no need to reject promises
3327
+ this.queue = [];
3328
+ this.forceCheckpointPromises = [];
3329
+ // Resolve any waiting queue completion promises since we're clearing
3330
+ this.notifyQueueCompletion();
3331
+ }
3332
+ // Alias for backward compatibility with Checkpoint interface
3333
+ async force() {
3334
+ return this.forceCheckpoint();
3335
+ }
3336
+ async checkpoint(stepId, data) {
3337
+ if (this.isTerminating) {
3338
+ log("⚠️", "Checkpoint skipped - termination in progress:", { stepId });
3339
+ return new Promise(() => { }); // Never resolves during termination
3340
+ }
3341
+ // Check if any ancestor is finished - if so, don't queue and don't resolve
3342
+ if (this.hasFinishedAncestor(stepId)) {
3343
+ log("⚠️", "Checkpoint skipped - ancestor already finished:", { stepId });
3344
+ return new Promise(() => { }); // Never resolves when ancestor is finished
3345
+ }
3346
+ return new Promise((resolve, reject) => {
3347
+ const queuedItem = {
3348
+ stepId,
3349
+ data,
3350
+ resolve: () => {
3351
+ resolve();
3352
+ },
3353
+ reject: (error) => {
3354
+ reject(error);
3355
+ },
3356
+ };
3357
+ this.queue.push(queuedItem);
3358
+ log("📥", "Checkpoint queued:", {
3359
+ stepId,
3360
+ queueLength: this.queue.length,
3361
+ isProcessing: this.isProcessing,
3362
+ });
3363
+ if (!this.isProcessing) {
3364
+ setImmediate(() => {
3365
+ this.processQueue();
3366
+ });
3367
+ }
3639
3368
  });
3640
- };
3641
- };
3642
-
3643
- class ModeManagement {
3644
- captureExecutionState;
3645
- checkAndUpdateReplayMode;
3646
- checkForNonResolvingPromise;
3647
- getDurableExecutionMode;
3648
- setDurableExecutionMode;
3649
- constructor(captureExecutionState, checkAndUpdateReplayMode, checkForNonResolvingPromise, getDurableExecutionMode, setDurableExecutionMode) {
3650
- this.captureExecutionState = captureExecutionState;
3651
- this.checkAndUpdateReplayMode = checkAndUpdateReplayMode;
3652
- this.checkForNonResolvingPromise = checkForNonResolvingPromise;
3653
- this.getDurableExecutionMode = getDurableExecutionMode;
3654
- this.setDurableExecutionMode = setDurableExecutionMode;
3655
3369
  }
3656
- withModeManagement(operation) {
3657
- const shouldSwitchToExecutionMode = this.captureExecutionState();
3658
- this.checkAndUpdateReplayMode();
3659
- const nonResolvingPromise = this.checkForNonResolvingPromise();
3660
- if (nonResolvingPromise)
3661
- return nonResolvingPromise;
3662
- try {
3663
- return operation();
3370
+ classifyCheckpointError(error) {
3371
+ const originalError = error instanceof Error ? error : new Error(String(error));
3372
+ const awsError = error;
3373
+ const statusCode = awsError.$metadata?.httpStatusCode;
3374
+ const errorName = awsError.name;
3375
+ const errorMessage = awsError.message || originalError.message;
3376
+ log("🔍", "Classifying checkpoint error:", {
3377
+ statusCode,
3378
+ errorName,
3379
+ errorMessage,
3380
+ });
3381
+ if (statusCode &&
3382
+ statusCode >= 400 &&
3383
+ statusCode < 500 &&
3384
+ errorName === "InvalidParameterValueException" &&
3385
+ errorMessage.startsWith("Invalid Checkpoint Token")) {
3386
+ return new CheckpointUnrecoverableInvocationError(`Checkpoint failed: ${errorMessage}`, originalError);
3664
3387
  }
3665
- finally {
3666
- if (shouldSwitchToExecutionMode) {
3667
- this.setDurableExecutionMode(DurableExecutionMode.ExecutionMode);
3668
- }
3388
+ if (statusCode &&
3389
+ statusCode >= 400 &&
3390
+ statusCode < 500 &&
3391
+ statusCode !== 429) {
3392
+ return new CheckpointUnrecoverableExecutionError(`Checkpoint failed: ${errorMessage}`, originalError);
3669
3393
  }
3394
+ return new CheckpointUnrecoverableInvocationError(`Checkpoint failed: ${errorMessage}`, originalError);
3670
3395
  }
3671
- withDurableModeManagement(operation) {
3672
- const shouldSwitchToExecutionMode = this.captureExecutionState();
3673
- this.checkAndUpdateReplayMode();
3674
- const nonResolvingPromise = this.checkForNonResolvingPromise();
3675
- if (nonResolvingPromise) {
3676
- return new DurablePromise(async () => {
3677
- await nonResolvingPromise;
3678
- // This will never be reached
3679
- throw new Error("Unreachable code");
3680
- });
3396
+ async processQueue() {
3397
+ if (this.isProcessing) {
3398
+ return;
3399
+ }
3400
+ const hasQueuedItems = this.queue.length > 0;
3401
+ const hasForceRequests = this.forceCheckpointPromises.length > 0;
3402
+ if (!hasQueuedItems && !hasForceRequests) {
3403
+ return;
3404
+ }
3405
+ this.isProcessing = true;
3406
+ const batch = [];
3407
+ const baseSize = this.currentTaskToken.length + 100;
3408
+ let currentSize = baseSize;
3409
+ while (this.queue.length > 0) {
3410
+ const nextItem = this.queue[0];
3411
+ const itemSize = CheckpointManager.textEncoder.encode(JSON.stringify(nextItem)).length;
3412
+ if (currentSize + itemSize > this.MAX_PAYLOAD_SIZE && batch.length > 0) {
3413
+ break;
3414
+ }
3415
+ this.queue.shift();
3416
+ batch.push(nextItem);
3417
+ currentSize += itemSize;
3681
3418
  }
3419
+ log("🔄", "Processing checkpoint batch:", {
3420
+ batchSize: batch.length,
3421
+ remainingInQueue: this.queue.length,
3422
+ estimatedSize: currentSize,
3423
+ maxSize: this.MAX_PAYLOAD_SIZE,
3424
+ });
3682
3425
  try {
3683
- return operation();
3426
+ if (batch.length > 0 || this.forceCheckpointPromises.length > 0) {
3427
+ await this.processBatch(batch);
3428
+ }
3429
+ batch.forEach((item) => {
3430
+ item.resolve();
3431
+ });
3432
+ const forcePromises = this.forceCheckpointPromises.splice(0);
3433
+ forcePromises.forEach((promise) => {
3434
+ promise.resolve();
3435
+ });
3436
+ log("✅", "Checkpoint batch processed successfully:", {
3437
+ batchSize: batch.length,
3438
+ forceRequests: forcePromises.length,
3439
+ newTaskToken: this.currentTaskToken,
3440
+ });
3441
+ }
3442
+ catch (error) {
3443
+ log("❌", "Checkpoint batch failed:", {
3444
+ batchSize: batch.length,
3445
+ error,
3446
+ });
3447
+ const checkpointError = this.classifyCheckpointError(error);
3448
+ // Clear remaining queue silently - we're terminating
3449
+ this.clearQueue();
3450
+ this.terminationManager.terminate({
3451
+ reason: TerminationReason.CHECKPOINT_FAILED,
3452
+ message: checkpointError.message,
3453
+ error: checkpointError,
3454
+ });
3684
3455
  }
3685
3456
  finally {
3686
- if (shouldSwitchToExecutionMode) {
3687
- this.setDurableExecutionMode(DurableExecutionMode.ExecutionMode);
3457
+ this.isProcessing = false;
3458
+ if (this.queue.length > 0) {
3459
+ setImmediate(() => {
3460
+ this.processQueue();
3461
+ });
3462
+ }
3463
+ else {
3464
+ // Queue is empty and processing is done - notify all waiting promises
3465
+ this.notifyQueueCompletion();
3688
3466
  }
3689
3467
  }
3690
3468
  }
3691
- }
3692
-
3693
- class DurableContextImpl {
3694
- executionContext;
3695
- lambdaContext;
3696
- _stepPrefix;
3697
- _stepCounter = 0;
3698
- durableLogger;
3699
- modeAwareLoggingEnabled = true;
3700
- runningOperations = new Set();
3701
- operationsEmitter = new events.EventEmitter();
3702
- checkpoint;
3703
- durableExecutionMode;
3704
- _parentId;
3705
- modeManagement;
3706
- durableExecution;
3707
- logger;
3708
- constructor(executionContext, lambdaContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId) {
3709
- this.executionContext = executionContext;
3710
- this.lambdaContext = lambdaContext;
3711
- this._stepPrefix = stepPrefix;
3712
- this._parentId = parentId;
3713
- this.durableExecution = durableExecution;
3714
- this.durableLogger = inheritedLogger;
3715
- this.durableLogger.configureDurableLoggingContext?.(this.getDurableLoggingContext());
3716
- this.logger = this.createModeAwareLogger(inheritedLogger);
3717
- this.durableExecutionMode = durableExecutionMode;
3718
- this.checkpoint = durableExecution.checkpointManager;
3719
- this.modeManagement = new ModeManagement(this.captureExecutionState.bind(this), this.checkAndUpdateReplayMode.bind(this), this.checkForNonResolvingPromise.bind(this), () => this.durableExecutionMode, (mode) => {
3720
- this.durableExecutionMode = mode;
3721
- });
3469
+ notifyQueueCompletion() {
3470
+ if (this.queueCompletionResolver) {
3471
+ this.queueCompletionResolver();
3472
+ this.queueCompletionResolver = null;
3473
+ }
3722
3474
  }
3723
- getDurableLoggingContext() {
3724
- return {
3725
- getDurableLogData: () => {
3726
- const activeContext = getActiveContext();
3727
- const result = {
3728
- executionArn: this.executionContext.durableExecutionArn,
3729
- requestId: this.executionContext.requestId,
3730
- tenantId: this.executionContext.tenantId,
3731
- operationId: !activeContext || activeContext?.contextId === "root"
3732
- ? undefined
3733
- : hashId(activeContext.contextId),
3734
- };
3735
- if (activeContext?.attempt !== undefined) {
3736
- result.attempt = activeContext.attempt;
3737
- }
3738
- return result;
3739
- },
3475
+ async processBatch(batch) {
3476
+ const updates = batch.map((item) => {
3477
+ const hashedStepId = hashId(item.stepId);
3478
+ const update = {
3479
+ Type: item.data.Type || "STEP",
3480
+ Action: item.data.Action || "START",
3481
+ ...item.data,
3482
+ Id: hashedStepId,
3483
+ ...(item.data.ParentId && { ParentId: hashId(item.data.ParentId) }),
3484
+ };
3485
+ return update;
3486
+ });
3487
+ const checkpointData = {
3488
+ DurableExecutionArn: this.durableExecutionArn,
3489
+ CheckpointToken: this.currentTaskToken,
3490
+ Updates: updates,
3740
3491
  };
3741
- }
3742
- shouldLog() {
3743
- const activeContext = getActiveContext();
3744
- if (!this.modeAwareLoggingEnabled || !activeContext) {
3745
- return true;
3492
+ log("⏺️", "Creating checkpoint batch:", {
3493
+ batchSize: updates.length,
3494
+ checkpointToken: this.currentTaskToken,
3495
+ updates: updates.map((u) => ({
3496
+ Id: u.Id,
3497
+ Action: u.Action,
3498
+ Type: u.Type,
3499
+ })),
3500
+ });
3501
+ const response = await this.storage.checkpoint(checkpointData, this.logger);
3502
+ if (response.CheckpointToken) {
3503
+ this.currentTaskToken = response.CheckpointToken;
3746
3504
  }
3747
- if (activeContext.contextId === "root") {
3748
- return this.durableExecutionMode === DurableExecutionMode.ExecutionMode;
3505
+ if (response.NewExecutionState?.Operations) {
3506
+ this.updateStepDataFromCheckpointResponse(response.NewExecutionState.Operations);
3749
3507
  }
3750
- return (activeContext.durableExecutionMode === DurableExecutionMode.ExecutionMode);
3751
3508
  }
3752
- createModeAwareLogger(logger) {
3753
- const durableContextLogger = {
3754
- warn: (...args) => {
3755
- if (this.shouldLog()) {
3756
- return logger.warn(...args);
3757
- }
3758
- },
3759
- debug: (...args) => {
3760
- if (this.shouldLog()) {
3761
- return logger.debug(...args);
3762
- }
3763
- },
3764
- info: (...args) => {
3765
- if (this.shouldLog()) {
3766
- return logger.info(...args);
3767
- }
3768
- },
3769
- error: (...args) => {
3770
- if (this.shouldLog()) {
3771
- return logger.error(...args);
3509
+ updateStepDataFromCheckpointResponse(operations) {
3510
+ log("🔄", "Updating stepData from checkpoint response:", {
3511
+ operationCount: operations.length,
3512
+ operationIds: operations.map((op) => op.Id).filter(Boolean),
3513
+ });
3514
+ operations.forEach((operation) => {
3515
+ if (operation.Id) {
3516
+ // Check if status changed
3517
+ const oldStatus = this.stepData[operation.Id]?.Status;
3518
+ const newStatus = operation.Status;
3519
+ this.stepData[operation.Id] = operation;
3520
+ log("📝", "Updated stepData entry:", operation);
3521
+ this.stepDataEmitter.emit(STEP_DATA_UPDATED_EVENT, operation.Id);
3522
+ // If status changed and we have a waiting promise, resolve it
3523
+ if (oldStatus !== newStatus) {
3524
+ this.resolveWaitingOperation(operation.Id);
3772
3525
  }
3773
- },
3774
- };
3775
- if ("log" in logger) {
3776
- durableContextLogger.log = (level, ...args) => {
3777
- if (this.shouldLog()) {
3778
- return logger.log?.(level, ...args);
3526
+ }
3527
+ });
3528
+ log("", "StepData update completed:", {
3529
+ totalStepDataEntries: Object.keys(this.stepData).length,
3530
+ });
3531
+ }
3532
+ resolveWaitingOperation(hashedStepId) {
3533
+ // Find operation by hashed ID in our operations map
3534
+ for (const [stepId, op] of this.operations.entries()) {
3535
+ if (hashId(stepId) === hashedStepId && op.resolver) {
3536
+ log("✅", `Resolving waiting operation ${stepId} due to status change`);
3537
+ op.resolver();
3538
+ op.resolver = undefined;
3539
+ if (op.timer) {
3540
+ clearTimeout(op.timer);
3541
+ op.timer = undefined;
3779
3542
  }
3780
- };
3543
+ break;
3544
+ }
3781
3545
  }
3782
- return durableContextLogger;
3783
3546
  }
3784
- createStepId() {
3785
- this._stepCounter++;
3786
- return this._stepPrefix
3787
- ? `${this._stepPrefix}-${this._stepCounter}`
3788
- : `${this._stepCounter}`;
3789
- }
3790
- getNextStepId() {
3791
- const nextCounter = this._stepCounter + 1;
3792
- return this._stepPrefix
3793
- ? `${this._stepPrefix}-${nextCounter}`
3794
- : `${nextCounter}`;
3795
- }
3796
- /**
3797
- * Skips the next operation by incrementing the step counter.
3798
- * Used internally by concurrent execution handler during replay to skip incomplete items.
3799
- * @internal
3800
- */
3801
- skipNextOperation() {
3802
- this._stepCounter++;
3547
+ getQueueStatus() {
3548
+ return {
3549
+ queueLength: this.queue.length,
3550
+ isProcessing: this.isProcessing,
3551
+ };
3803
3552
  }
3804
- checkAndUpdateReplayMode() {
3805
- if (this.durableExecutionMode === DurableExecutionMode.ReplayMode) {
3806
- const nextStepId = this.getNextStepId();
3807
- const nextStepData = this.executionContext.getStepData(nextStepId);
3808
- if (!nextStepData) {
3809
- this.durableExecutionMode = DurableExecutionMode.ExecutionMode;
3553
+ // ===== New Lifecycle & Termination Methods =====
3554
+ markOperationState(stepId, state, options) {
3555
+ let op = this.operations.get(stepId);
3556
+ if (!op) {
3557
+ // First call - create operation
3558
+ if (!options?.metadata) {
3559
+ throw new Error(`metadata required on first call for ${stepId}`);
3810
3560
  }
3561
+ op = {
3562
+ stepId,
3563
+ state,
3564
+ metadata: options.metadata,
3565
+ endTimestamp: options.endTimestamp,
3566
+ };
3567
+ this.operations.set(stepId, op);
3811
3568
  }
3812
- }
3813
- captureExecutionState() {
3814
- const wasInReplayMode = this.durableExecutionMode === DurableExecutionMode.ReplayMode;
3815
- const nextStepId = this.getNextStepId();
3816
- const stepData = this.executionContext.getStepData(nextStepId);
3817
- const wasNotFinished = !!(stepData &&
3818
- stepData.Status !== clientLambda.OperationStatus.SUCCEEDED &&
3819
- stepData.Status !== clientLambda.OperationStatus.FAILED);
3820
- return wasInReplayMode && wasNotFinished;
3821
- }
3822
- checkForNonResolvingPromise() {
3823
- if (this.durableExecutionMode === DurableExecutionMode.ReplaySucceededContext) {
3824
- const nextStepId = this.getNextStepId();
3825
- const nextStepData = this.executionContext.getStepData(nextStepId);
3826
- if (nextStepData &&
3827
- nextStepData.Status !== clientLambda.OperationStatus.SUCCEEDED &&
3828
- nextStepData.Status !== clientLambda.OperationStatus.FAILED) {
3829
- return new Promise(() => { }); // Non-resolving promise
3569
+ else {
3570
+ // Update existing operation
3571
+ op.state = state;
3572
+ if (options?.endTimestamp !== undefined) {
3573
+ op.endTimestamp = options.endTimestamp;
3830
3574
  }
3831
3575
  }
3832
- return null;
3833
- }
3834
- addRunningOperation(stepId) {
3835
- this.runningOperations.add(stepId);
3836
- }
3837
- removeRunningOperation(stepId) {
3838
- this.runningOperations.delete(stepId);
3839
- if (this.runningOperations.size === 0) {
3840
- this.operationsEmitter.emit(OPERATIONS_COMPLETE_EVENT);
3576
+ // Cleanup if transitioning to COMPLETED
3577
+ if (state === OperationLifecycleState.COMPLETED) {
3578
+ this.cleanupOperation(stepId);
3579
+ }
3580
+ // Check if we should terminate
3581
+ // Don't check for IDLE_NOT_AWAITED - operation might be awaited later or intentionally not awaited
3582
+ if (state !== OperationLifecycleState.IDLE_NOT_AWAITED) {
3583
+ this.checkAndTerminate();
3841
3584
  }
3842
3585
  }
3843
- hasRunningOperations() {
3844
- return this.runningOperations.size > 0;
3845
- }
3846
- getOperationsEmitter() {
3847
- return this.operationsEmitter;
3848
- }
3849
- withModeManagement(operation) {
3850
- return this.modeManagement.withModeManagement(operation);
3851
- }
3852
- withDurableModeManagement(operation) {
3853
- return this.modeManagement.withDurableModeManagement(operation);
3854
- }
3855
- step(nameOrFn, fnOrOptions, maybeOptions) {
3856
- validateContextUsage(this._stepPrefix, "step", this.executionContext.terminationManager);
3857
- return this.withDurableModeManagement(() => {
3858
- const stepHandler = createStepHandler(this.executionContext, this.checkpoint, this.lambdaContext, this.createStepId.bind(this), this.durableLogger, this.addRunningOperation.bind(this), this.removeRunningOperation.bind(this), this.hasRunningOperations.bind(this), this.getOperationsEmitter.bind(this), this._parentId);
3859
- return stepHandler(nameOrFn, fnOrOptions, maybeOptions);
3860
- });
3861
- }
3862
- invoke(nameOrFuncId, funcIdOrInput, inputOrConfig, maybeConfig) {
3863
- validateContextUsage(this._stepPrefix, "invoke", this.executionContext.terminationManager);
3864
- return this.withDurableModeManagement(() => {
3865
- const invokeHandler = createInvokeHandler(this.executionContext, this.checkpoint, this.createStepId.bind(this), this.hasRunningOperations.bind(this), this.getOperationsEmitter.bind(this), this._parentId, this.checkAndUpdateReplayMode.bind(this));
3866
- return invokeHandler(...[
3867
- nameOrFuncId,
3868
- funcIdOrInput,
3869
- inputOrConfig,
3870
- maybeConfig,
3871
- ]);
3872
- });
3873
- }
3874
- runInChildContext(nameOrFn, fnOrOptions, maybeOptions) {
3875
- validateContextUsage(this._stepPrefix, "runInChildContext", this.executionContext.terminationManager);
3876
- return this.withDurableModeManagement(() => {
3877
- const blockHandler = createRunInChildContextHandler(this.executionContext, this.checkpoint, this.lambdaContext, this.createStepId.bind(this), () => this.durableLogger,
3878
- // Adapter function to maintain compatibility
3879
- (executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, _checkpointToken, parentId) => createDurableContext(executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, this.durableExecution, parentId), this._parentId);
3880
- return blockHandler(nameOrFn, fnOrOptions, maybeOptions);
3586
+ waitForRetryTimer(stepId) {
3587
+ const op = this.operations.get(stepId);
3588
+ if (!op) {
3589
+ throw new Error(`Operation ${stepId} not found`);
3590
+ }
3591
+ if (op.state !== OperationLifecycleState.RETRY_WAITING) {
3592
+ throw new Error(`Operation ${stepId} must be in RETRY_WAITING state, got ${op.state}`);
3593
+ }
3594
+ // Start timer with polling
3595
+ this.startTimerWithPolling(stepId, op.endTimestamp);
3596
+ // Return promise that resolves when status changes
3597
+ return new Promise((resolve) => {
3598
+ op.resolver = resolve;
3881
3599
  });
3882
3600
  }
3883
- wait(nameOrDuration, maybeDuration) {
3884
- validateContextUsage(this._stepPrefix, "wait", this.executionContext.terminationManager);
3885
- return this.withDurableModeManagement(() => {
3886
- const waitHandler = createWaitHandler(this.executionContext, this.checkpoint, this.createStepId.bind(this), this.hasRunningOperations.bind(this), this.getOperationsEmitter.bind(this), this._parentId, this.checkAndUpdateReplayMode.bind(this));
3887
- return typeof nameOrDuration === "string"
3888
- ? waitHandler(nameOrDuration, maybeDuration)
3889
- : waitHandler(nameOrDuration);
3601
+ waitForStatusChange(stepId) {
3602
+ const op = this.operations.get(stepId);
3603
+ if (!op) {
3604
+ throw new Error(`Operation ${stepId} not found`);
3605
+ }
3606
+ if (op.state !== OperationLifecycleState.IDLE_AWAITED) {
3607
+ throw new Error(`Operation ${stepId} must be in IDLE_AWAITED state, got ${op.state}`);
3608
+ }
3609
+ // Start timer with polling
3610
+ this.startTimerWithPolling(stepId, op.endTimestamp);
3611
+ // Return promise that resolves when status changes
3612
+ return new Promise((resolve) => {
3613
+ op.resolver = resolve;
3890
3614
  });
3891
3615
  }
3892
- /**
3893
- * Configure logger behavior for this context
3894
- *
3895
- * This method allows partial configuration - only the properties provided will be updated.
3896
- * For example, calling configureLogger(\{ modeAware: false \}) will only change the modeAware
3897
- * setting without affecting any previously configured custom logger.
3898
- *
3899
- * @param config - Logger configuration options including customLogger and modeAware settings (default: modeAware=true)
3900
- * @example
3901
- * // Set custom logger and enable mode-aware logging
3902
- * context.configureLogger(\{ customLogger: myLogger, modeAware: true \});
3903
- *
3904
- * // Later, disable mode-aware logging without changing the custom logger
3905
- * context.configureLogger(\{ modeAware: false \});
3906
- */
3907
- configureLogger(config) {
3908
- if (config.customLogger !== undefined) {
3909
- this.durableLogger = config.customLogger;
3910
- this.durableLogger.configureDurableLoggingContext?.(this.getDurableLoggingContext());
3911
- this.logger = this.createModeAwareLogger(this.durableLogger);
3616
+ markOperationAwaited(stepId) {
3617
+ const op = this.operations.get(stepId);
3618
+ if (!op) {
3619
+ log("⚠️", `Cannot mark operation as awaited: ${stepId} not found`);
3620
+ return;
3912
3621
  }
3913
- if (config.modeAware !== undefined) {
3914
- this.modeAwareLoggingEnabled = config.modeAware;
3622
+ // Transition IDLE_NOT_AWAITED IDLE_AWAITED
3623
+ if (op.state === OperationLifecycleState.IDLE_NOT_AWAITED) {
3624
+ op.state = OperationLifecycleState.IDLE_AWAITED;
3625
+ log("📍", `Operation marked as awaited: ${stepId}`);
3626
+ // Check if we should terminate now that operation is awaited
3627
+ this.checkAndTerminate();
3915
3628
  }
3916
3629
  }
3917
- createCallback(nameOrConfig, maybeConfig) {
3918
- validateContextUsage(this._stepPrefix, "createCallback", this.executionContext.terminationManager);
3919
- return this.withDurableModeManagement(() => {
3920
- const callbackFactory = createCallback(this.executionContext, this.checkpoint, this.createStepId.bind(this), this.hasRunningOperations.bind(this), this.getOperationsEmitter.bind(this), this.checkAndUpdateReplayMode.bind(this), this._parentId);
3921
- return callbackFactory(nameOrConfig, maybeConfig);
3922
- });
3630
+ getOperationState(stepId) {
3631
+ return this.operations.get(stepId)?.state;
3923
3632
  }
3924
- waitForCallback(nameOrSubmitter, submitterOrConfig, maybeConfig) {
3925
- validateContextUsage(this._stepPrefix, "waitForCallback", this.executionContext.terminationManager);
3926
- return this.withDurableModeManagement(() => {
3927
- const waitForCallbackHandler = createWaitForCallbackHandler(this.executionContext, this.getNextStepId.bind(this), this.runInChildContext.bind(this));
3928
- return waitForCallbackHandler(nameOrSubmitter, submitterOrConfig, maybeConfig);
3929
- });
3633
+ getAllOperations() {
3634
+ return new Map(this.operations);
3930
3635
  }
3931
- waitForCondition(nameOrCheckFunc, checkFuncOrConfig, maybeConfig) {
3932
- validateContextUsage(this._stepPrefix, "waitForCondition", this.executionContext.terminationManager);
3933
- return this.withDurableModeManagement(() => {
3934
- const waitForConditionHandler = createWaitForConditionHandler(this.executionContext, this.checkpoint, this.createStepId.bind(this), this.durableLogger, this.addRunningOperation.bind(this), this.removeRunningOperation.bind(this), this.hasRunningOperations.bind(this), this.getOperationsEmitter.bind(this), this._parentId);
3935
- return typeof nameOrCheckFunc === "string" ||
3936
- nameOrCheckFunc === undefined
3937
- ? waitForConditionHandler(nameOrCheckFunc, checkFuncOrConfig, maybeConfig)
3938
- : waitForConditionHandler(nameOrCheckFunc, checkFuncOrConfig);
3939
- });
3636
+ // ===== Private Helper Methods =====
3637
+ cleanupOperation(stepId) {
3638
+ const op = this.operations.get(stepId);
3639
+ if (!op)
3640
+ return;
3641
+ // Clear timer
3642
+ if (op.timer) {
3643
+ clearTimeout(op.timer);
3644
+ op.timer = undefined;
3645
+ }
3646
+ // Clear resolver
3647
+ op.resolver = undefined;
3648
+ }
3649
+ cleanupAllOperations() {
3650
+ for (const op of this.operations.values()) {
3651
+ if (op.timer) {
3652
+ clearTimeout(op.timer);
3653
+ op.timer = undefined;
3654
+ }
3655
+ op.resolver = undefined;
3656
+ }
3940
3657
  }
3941
- map(nameOrItems, itemsOrMapFunc, mapFuncOrConfig, maybeConfig) {
3942
- validateContextUsage(this._stepPrefix, "map", this.executionContext.terminationManager);
3943
- return this.withDurableModeManagement(() => {
3944
- const mapHandler = createMapHandler(this.executionContext, this._executeConcurrently.bind(this));
3945
- return mapHandler(nameOrItems, itemsOrMapFunc, mapFuncOrConfig, maybeConfig);
3946
- });
3658
+ checkAndTerminate() {
3659
+ // Rule 1: Can't terminate if checkpoint queue is not empty
3660
+ if (this.queue.length > 0) {
3661
+ this.abortTermination();
3662
+ return;
3663
+ }
3664
+ // Rule 2: Can't terminate if checkpoint is currently processing
3665
+ if (this.isProcessing) {
3666
+ this.abortTermination();
3667
+ return;
3668
+ }
3669
+ // Rule 3: Can't terminate if there are pending force checkpoint promises
3670
+ if (this.forceCheckpointPromises.length > 0) {
3671
+ this.abortTermination();
3672
+ return;
3673
+ }
3674
+ const allOps = Array.from(this.operations.values());
3675
+ // Rule 4: Can't terminate if any operation is EXECUTING
3676
+ const hasExecuting = allOps.some((op) => op.state === OperationLifecycleState.EXECUTING);
3677
+ if (hasExecuting) {
3678
+ this.abortTermination();
3679
+ return;
3680
+ }
3681
+ // Rule 5: Clean up operations whose ancestors are complete or pending completion
3682
+ for (const op of allOps) {
3683
+ if (op.state === OperationLifecycleState.RETRY_WAITING ||
3684
+ op.state === OperationLifecycleState.IDLE_NOT_AWAITED ||
3685
+ op.state === OperationLifecycleState.IDLE_AWAITED) {
3686
+ // Use the original stepId from metadata, not the potentially hashed op.stepId
3687
+ const originalStepId = op.metadata.stepId;
3688
+ if (this.hasFinishedAncestor(originalStepId)) {
3689
+ log("🧹", `Cleaning up operation with completed ancestor: ${originalStepId}`);
3690
+ this.cleanupOperation(op.stepId);
3691
+ this.operations.delete(op.stepId);
3692
+ }
3693
+ }
3694
+ }
3695
+ // Re-check operations after cleanup
3696
+ const remainingOps = Array.from(this.operations.values());
3697
+ // Determine if we should terminate
3698
+ const hasWaiting = remainingOps.some((op) => op.state === OperationLifecycleState.RETRY_WAITING ||
3699
+ op.state === OperationLifecycleState.IDLE_NOT_AWAITED ||
3700
+ op.state === OperationLifecycleState.IDLE_AWAITED);
3701
+ if (hasWaiting) {
3702
+ const reason = this.determineTerminationReason(remainingOps);
3703
+ this.scheduleTermination(reason);
3704
+ }
3705
+ else {
3706
+ this.abortTermination();
3707
+ }
3947
3708
  }
3948
- parallel(nameOrBranches, branchesOrConfig, maybeConfig) {
3949
- validateContextUsage(this._stepPrefix, "parallel", this.executionContext.terminationManager);
3950
- return this.withDurableModeManagement(() => {
3951
- const parallelHandler = createParallelHandler(this.executionContext, this._executeConcurrently.bind(this));
3952
- return parallelHandler(nameOrBranches, branchesOrConfig, maybeConfig);
3953
- });
3709
+ abortTermination() {
3710
+ if (this.terminationTimer) {
3711
+ clearTimeout(this.terminationTimer);
3712
+ this.terminationTimer = null;
3713
+ this.terminationReason = null;
3714
+ log("🔄", "Termination aborted - conditions changed");
3715
+ }
3954
3716
  }
3955
- _executeConcurrently(nameOrItems, itemsOrExecutor, executorOrConfig, maybeConfig) {
3956
- validateContextUsage(this._stepPrefix, "_executeConcurrently", this.executionContext.terminationManager);
3957
- return this.withDurableModeManagement(() => {
3958
- const concurrentExecutionHandler = createConcurrentExecutionHandler(this.executionContext, this.runInChildContext.bind(this), this.skipNextOperation.bind(this));
3959
- const promise = concurrentExecutionHandler(nameOrItems, itemsOrExecutor, executorOrConfig, maybeConfig);
3960
- // Prevent unhandled promise rejections
3961
- promise?.catch(() => { });
3962
- return promise;
3717
+ scheduleTermination(reason) {
3718
+ // If already scheduled with same reason, don't reschedule
3719
+ if (this.terminationTimer && this.terminationReason === reason) {
3720
+ return;
3721
+ }
3722
+ // Clear any existing timer
3723
+ this.abortTermination();
3724
+ // Schedule new termination
3725
+ this.terminationReason = reason;
3726
+ log("⏱️", "Scheduling termination", {
3727
+ reason,
3728
+ cooldownMs: this.TERMINATION_COOLDOWN_MS,
3963
3729
  });
3730
+ this.terminationTimer = setTimeout(() => {
3731
+ this.executeTermination(reason);
3732
+ }, this.TERMINATION_COOLDOWN_MS);
3733
+ }
3734
+ executeTermination(reason) {
3735
+ log("🛑", "Executing termination after cooldown", { reason });
3736
+ // Clear timer
3737
+ this.terminationTimer = null;
3738
+ this.terminationReason = null;
3739
+ // Cleanup all operations before terminating
3740
+ this.cleanupAllOperations();
3741
+ // Call termination manager directly
3742
+ this.terminationManager.terminate({ reason });
3743
+ }
3744
+ determineTerminationReason(ops) {
3745
+ // Priority: RETRY_SCHEDULED > WAIT_SCHEDULED > CALLBACK_PENDING
3746
+ if (ops.some((op) => op.state === OperationLifecycleState.RETRY_WAITING &&
3747
+ op.metadata.subType === "Step")) {
3748
+ return TerminationReason.RETRY_SCHEDULED;
3749
+ }
3750
+ if (ops.some((op) => (op.state === OperationLifecycleState.IDLE_NOT_AWAITED ||
3751
+ op.state === OperationLifecycleState.IDLE_AWAITED) &&
3752
+ op.metadata.subType === "Wait")) {
3753
+ return TerminationReason.WAIT_SCHEDULED;
3754
+ }
3755
+ return TerminationReason.CALLBACK_PENDING;
3964
3756
  }
3965
- get promise() {
3966
- return createPromiseHandler(this.step.bind(this));
3757
+ startTimerWithPolling(stepId, endTimestamp) {
3758
+ const op = this.operations.get(stepId);
3759
+ if (!op)
3760
+ return;
3761
+ let delay;
3762
+ if (endTimestamp) {
3763
+ // Ensure endTimestamp is a Date object
3764
+ const timestamp = endTimestamp instanceof Date ? endTimestamp : new Date(endTimestamp);
3765
+ // Wait until endTimestamp
3766
+ delay = Math.max(0, timestamp.getTime() - Date.now());
3767
+ }
3768
+ else {
3769
+ // No timestamp, start polling immediately (1 second delay)
3770
+ delay = 1000;
3771
+ }
3772
+ // Initialize poll count and start time for this operation
3773
+ if (!op.pollCount) {
3774
+ op.pollCount = 0;
3775
+ op.pollStartTime = Date.now();
3776
+ }
3777
+ op.timer = setTimeout(() => {
3778
+ this.forceRefreshAndCheckStatus(stepId);
3779
+ }, delay);
3780
+ }
3781
+ async forceRefreshAndCheckStatus(stepId) {
3782
+ const op = this.operations.get(stepId);
3783
+ if (!op)
3784
+ return;
3785
+ // Check if we've exceeded max polling duration (15 minutes)
3786
+ const MAX_POLL_DURATION_MS = 15 * 60 * 1000; // 15 minutes
3787
+ if (op.pollStartTime &&
3788
+ Date.now() - op.pollStartTime > MAX_POLL_DURATION_MS) {
3789
+ // Stop polling after 15 minutes to prevent indefinite resource consumption.
3790
+ // We don't resolve or reject the promise because the handler cannot continue
3791
+ // without a status change. The execution will remain suspended until the
3792
+ // operation completes or the Lambda times out.
3793
+ log("⏱️", `Max polling duration (15 min) exceeded for ${stepId}, stopping poll`);
3794
+ if (op.timer) {
3795
+ clearTimeout(op.timer);
3796
+ op.timer = undefined;
3797
+ }
3798
+ return;
3799
+ }
3800
+ // Get old status before refresh
3801
+ const oldStatus = this.stepData[hashId(stepId)]?.Status;
3802
+ // Force checkpoint to refresh state from backend
3803
+ await this.forceCheckpoint();
3804
+ // Get new status after refresh
3805
+ const newStatus = this.stepData[hashId(stepId)]?.Status;
3806
+ // Check if status changed
3807
+ if (newStatus !== oldStatus) {
3808
+ // Status changed, resolve the waiting promise
3809
+ log("✅", `Status changed for ${stepId}: ${oldStatus} → ${newStatus}`);
3810
+ op.resolver?.();
3811
+ op.resolver = undefined;
3812
+ // Clear timer
3813
+ if (op.timer) {
3814
+ clearTimeout(op.timer);
3815
+ op.timer = undefined;
3816
+ }
3817
+ }
3818
+ else {
3819
+ // Status not changed yet, poll again with incremental backoff
3820
+ // Start at 1s, increase by 1s each poll, max 10s
3821
+ op.pollCount = (op.pollCount || 0) + 1;
3822
+ const nextDelay = Math.min(op.pollCount * 1000, 10000);
3823
+ op.timer = setTimeout(() => {
3824
+ this.forceRefreshAndCheckStatus(stepId);
3825
+ }, nextDelay);
3826
+ }
3967
3827
  }
3968
3828
  }
3969
- const createDurableContext = (executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId) => {
3970
- return new DurableContextImpl(executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId);
3971
- };
3972
3829
 
3973
3830
  /*
3974
3831
  Second Approach (Promise-based):
@@ -4262,43 +4119,6 @@ const createDefaultLogger = (executionContext) => {
4262
4119
  return new DefaultLogger(executionContext);
4263
4120
  };
4264
4121
 
4265
- /**
4266
- * Tracks active async operations to prevent premature termination
4267
- */
4268
- class ActiveOperationsTracker {
4269
- activeCount = 0;
4270
- /**
4271
- * Increment the counter when starting an async operation
4272
- */
4273
- increment() {
4274
- this.activeCount++;
4275
- }
4276
- /**
4277
- * Decrement the counter when an async operation completes
4278
- */
4279
- decrement() {
4280
- this.activeCount = Math.max(0, this.activeCount - 1);
4281
- }
4282
- /**
4283
- * Check if there are any active operations
4284
- */
4285
- hasActive() {
4286
- return this.activeCount > 0;
4287
- }
4288
- /**
4289
- * Get the current count of active operations
4290
- */
4291
- getCount() {
4292
- return this.activeCount;
4293
- }
4294
- /**
4295
- * Reset the counter (useful for testing)
4296
- */
4297
- reset() {
4298
- this.activeCount = 0;
4299
- }
4300
- }
4301
-
4302
4122
  let defaultLambdaClient;
4303
4123
  /**
4304
4124
  * Durable execution client which uses an API-based LambdaClient
@@ -4418,6 +4238,20 @@ class DurableExecutionInvocationInputWithClient {
4418
4238
  this.DurableExecutionArn = params.DurableExecutionArn;
4419
4239
  this.CheckpointToken = params.CheckpointToken;
4420
4240
  }
4241
+ static isInstance(event) {
4242
+ if (event instanceof DurableExecutionInvocationInputWithClient) {
4243
+ return true;
4244
+ }
4245
+ return !!(typeof event === "object" &&
4246
+ event &&
4247
+ event.toString() ===
4248
+ "[object DurableExecutionInvocationInputWithClient]" &&
4249
+ "durableExecutionClient" in event &&
4250
+ event.constructor.name === "DurableExecutionInvocationInputWithClient");
4251
+ }
4252
+ get [Symbol.toStringTag]() {
4253
+ return "DurableExecutionInvocationInputWithClient";
4254
+ }
4421
4255
  }
4422
4256
 
4423
4257
  const initializeExecutionContext = async (event, context, lambdaClient) => {
@@ -4427,7 +4261,7 @@ const initializeExecutionContext = async (event, context, lambdaClient) => {
4427
4261
  const durableExecutionArn = event.DurableExecutionArn;
4428
4262
  const durableExecutionClient =
4429
4263
  // Allow passing arbitrary durable clients if the input is a custom class
4430
- event instanceof DurableExecutionInvocationInputWithClient
4264
+ DurableExecutionInvocationInputWithClient.isInstance(event)
4431
4265
  ? event.durableExecutionClient
4432
4266
  : new DurableExecutionApiClient(lambdaClient);
4433
4267
  // Create logger for initialization errors using existing logger factory
@@ -4466,7 +4300,6 @@ const initializeExecutionContext = async (event, context, lambdaClient) => {
4466
4300
  durableExecutionClient,
4467
4301
  _stepData: stepData,
4468
4302
  terminationManager: new TerminationManager(),
4469
- activeOperationsTracker: new ActiveOperationsTracker(),
4470
4303
  durableExecutionArn,
4471
4304
  pendingCompletions: new Set(),
4472
4305
  getStepData(stepId) {
@@ -4485,7 +4318,7 @@ const LAMBDA_RESPONSE_SIZE_LIMIT = 6 * 1024 * 1024 - 50; // 6MB in bytes, minus
4485
4318
  async function runHandler(event, context, executionContext, durableExecutionMode, checkpointToken, handler) {
4486
4319
  // Create checkpoint manager and step data emitter
4487
4320
  const stepDataEmitter = new events.EventEmitter();
4488
- const checkpointManager = new CheckpointManager(executionContext.durableExecutionArn, executionContext._stepData, executionContext.durableExecutionClient, executionContext.terminationManager, executionContext.activeOperationsTracker, checkpointToken, stepDataEmitter, createDefaultLogger(executionContext), executionContext.pendingCompletions);
4321
+ const checkpointManager = new CheckpointManager(executionContext.durableExecutionArn, executionContext._stepData, executionContext.durableExecutionClient, executionContext.terminationManager, checkpointToken, stepDataEmitter, createDefaultLogger(executionContext), new Set());
4489
4322
  // Set the checkpoint terminating callback on the termination manager
4490
4323
  executionContext.terminationManager.setCheckpointTerminatingCallback(() => {
4491
4324
  checkpointManager.setTerminating();
@@ -4587,6 +4420,14 @@ async function runHandler(event, context, executionContext, durableExecutionMode
4587
4420
  Payload: serializedResult, // Reuse the already serialized result
4588
4421
  });
4589
4422
  log("✅", "Large result successfully checkpointed");
4423
+ // Wait for any pending checkpoints to complete before returning
4424
+ try {
4425
+ await durableExecution.checkpointManager.waitForQueueCompletion();
4426
+ }
4427
+ catch (waitError) {
4428
+ log("⚠️", "Error waiting for checkpoint queue completion:", waitError);
4429
+ // Continue anyway - the checkpoint will be retried on next invocation
4430
+ }
4590
4431
  // Return a response indicating the result was checkpointed
4591
4432
  return {
4592
4433
  Status: exports.InvocationStatus.SUCCEEDED,
@@ -4600,6 +4441,14 @@ async function runHandler(event, context, executionContext, durableExecutionMode
4600
4441
  }
4601
4442
  }
4602
4443
  // If response size is acceptable, return the response
4444
+ // Wait for any pending checkpoints to complete before returning
4445
+ try {
4446
+ await durableExecution.checkpointManager.waitForQueueCompletion();
4447
+ }
4448
+ catch (waitError) {
4449
+ log("⚠️", "Error waiting for checkpoint queue completion:", waitError);
4450
+ // Continue anyway - the checkpoint will be retried on next invocation
4451
+ }
4603
4452
  return {
4604
4453
  Status: exports.InvocationStatus.SUCCEEDED,
4605
4454
  Result: serializedResult,
@@ -4612,6 +4461,14 @@ async function runHandler(event, context, executionContext, durableExecutionMode
4612
4461
  log("🛑", "Unrecoverable invocation error - terminating Lambda execution");
4613
4462
  throw error; // Re-throw the error to terminate Lambda execution
4614
4463
  }
4464
+ // Wait for any pending checkpoints to complete before returning error
4465
+ try {
4466
+ await durableExecution.checkpointManager.waitForQueueCompletion();
4467
+ }
4468
+ catch (waitError) {
4469
+ log("⚠️", "Error waiting for checkpoint queue completion:", waitError);
4470
+ // Continue anyway - the checkpoint will be retried on next invocation
4471
+ }
4615
4472
  return {
4616
4473
  Status: exports.InvocationStatus.FAILED,
4617
4474
  Error: createErrorObjectFromError(error),