@aws/durable-execution-sdk-js 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/README.md +412 -0
  2. package/dist/index.mjs +4771 -0
  3. package/dist/index.mjs.map +1 -0
  4. package/dist-cjs/index.js +4789 -0
  5. package/dist-cjs/index.js.map +1 -0
  6. package/dist-types/context/durable-context/durable-context.d.ts +76 -0
  7. package/dist-types/context/durable-context/durable-context.d.ts.map +1 -0
  8. package/dist-types/context/durable-context/durable-context.integration.test.d.ts +2 -0
  9. package/dist-types/context/durable-context/durable-context.integration.test.d.ts.map +1 -0
  10. package/dist-types/context/durable-context/durable-context.unit.test.d.ts +2 -0
  11. package/dist-types/context/durable-context/durable-context.unit.test.d.ts.map +1 -0
  12. package/dist-types/context/durable-context/logger-mode-aware.test.d.ts +2 -0
  13. package/dist-types/context/durable-context/logger-mode-aware.test.d.ts.map +1 -0
  14. package/dist-types/context/durable-context/logger-property.test.d.ts +2 -0
  15. package/dist-types/context/durable-context/logger-property.test.d.ts.map +1 -0
  16. package/dist-types/context/durable-context/mode-management/mode-management.d.ts +13 -0
  17. package/dist-types/context/durable-context/mode-management/mode-management.d.ts.map +1 -0
  18. package/dist-types/context/durable-context/mode-management/mode-management.test.d.ts +2 -0
  19. package/dist-types/context/durable-context/mode-management/mode-management.test.d.ts.map +1 -0
  20. package/dist-types/context/execution-context/execution-context.d.ts +9 -0
  21. package/dist-types/context/execution-context/execution-context.d.ts.map +1 -0
  22. package/dist-types/context/execution-context/execution-context.test.d.ts +2 -0
  23. package/dist-types/context/execution-context/execution-context.test.d.ts.map +1 -0
  24. package/dist-types/durable-execution-api-client/durable-execution-api-client-caching.test.d.ts +2 -0
  25. package/dist-types/durable-execution-api-client/durable-execution-api-client-caching.test.d.ts.map +1 -0
  26. package/dist-types/durable-execution-api-client/durable-execution-api-client.d.ts +29 -0
  27. package/dist-types/durable-execution-api-client/durable-execution-api-client.d.ts.map +1 -0
  28. package/dist-types/durable-execution-api-client/durable-execution-api-client.test.d.ts +2 -0
  29. package/dist-types/durable-execution-api-client/durable-execution-api-client.test.d.ts.map +1 -0
  30. package/dist-types/errors/callback-error/callback-error.test.d.ts +2 -0
  31. package/dist-types/errors/callback-error/callback-error.test.d.ts.map +1 -0
  32. package/dist-types/errors/checkpoint-errors/checkpoint-errors.d.ts +21 -0
  33. package/dist-types/errors/checkpoint-errors/checkpoint-errors.d.ts.map +1 -0
  34. package/dist-types/errors/checkpoint-errors/checkpoint-errors.test.d.ts +2 -0
  35. package/dist-types/errors/checkpoint-errors/checkpoint-errors.test.d.ts.map +1 -0
  36. package/dist-types/errors/durable-error/durable-error-coverage.test.d.ts +2 -0
  37. package/dist-types/errors/durable-error/durable-error-coverage.test.d.ts.map +1 -0
  38. package/dist-types/errors/durable-error/durable-error.d.ts +55 -0
  39. package/dist-types/errors/durable-error/durable-error.d.ts.map +1 -0
  40. package/dist-types/errors/durable-error/durable-error.test.d.ts +2 -0
  41. package/dist-types/errors/durable-error/durable-error.test.d.ts.map +1 -0
  42. package/dist-types/errors/durable-error/error-determinism.integration.test.d.ts +2 -0
  43. package/dist-types/errors/durable-error/error-determinism.integration.test.d.ts.map +1 -0
  44. package/dist-types/errors/non-deterministic-error/non-deterministic-error.d.ts +10 -0
  45. package/dist-types/errors/non-deterministic-error/non-deterministic-error.d.ts.map +1 -0
  46. package/dist-types/errors/serdes-errors/serdes-errors.d.ts +27 -0
  47. package/dist-types/errors/serdes-errors/serdes-errors.d.ts.map +1 -0
  48. package/dist-types/errors/serdes-errors/serdes-errors.test.d.ts +2 -0
  49. package/dist-types/errors/serdes-errors/serdes-errors.test.d.ts.map +1 -0
  50. package/dist-types/errors/step-errors/step-errors.d.ts +8 -0
  51. package/dist-types/errors/step-errors/step-errors.d.ts.map +1 -0
  52. package/dist-types/errors/unrecoverable-error/unrecoverable-error.d.ts +41 -0
  53. package/dist-types/errors/unrecoverable-error/unrecoverable-error.d.ts.map +1 -0
  54. package/dist-types/errors/unrecoverable-error/unrecoverable-error.test.d.ts +2 -0
  55. package/dist-types/errors/unrecoverable-error/unrecoverable-error.test.d.ts.map +1 -0
  56. package/dist-types/handlers/callback-handler/callback-promise.d.ts +5 -0
  57. package/dist-types/handlers/callback-handler/callback-promise.d.ts.map +1 -0
  58. package/dist-types/handlers/callback-handler/callback-promise.test.d.ts +2 -0
  59. package/dist-types/handlers/callback-handler/callback-promise.test.d.ts.map +1 -0
  60. package/dist-types/handlers/callback-handler/callback.d.ts +7 -0
  61. package/dist-types/handlers/callback-handler/callback.d.ts.map +1 -0
  62. package/dist-types/handlers/callback-handler/callback.test.d.ts +2 -0
  63. package/dist-types/handlers/callback-handler/callback.test.d.ts.map +1 -0
  64. package/dist-types/handlers/concurrent-execution-handler/batch-result.d.ts +35 -0
  65. package/dist-types/handlers/concurrent-execution-handler/batch-result.d.ts.map +1 -0
  66. package/dist-types/handlers/concurrent-execution-handler/batch-result.test.d.ts +2 -0
  67. package/dist-types/handlers/concurrent-execution-handler/batch-result.test.d.ts.map +1 -0
  68. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler-two-phase.test.d.ts +2 -0
  69. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler-two-phase.test.d.ts.map +1 -0
  70. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.d.ts +12 -0
  71. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.d.ts.map +1 -0
  72. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.integration.test.d.ts +2 -0
  73. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.integration.test.d.ts.map +1 -0
  74. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.replay.test.d.ts +2 -0
  75. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.replay.test.d.ts.map +1 -0
  76. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.test.d.ts +2 -0
  77. package/dist-types/handlers/concurrent-execution-handler/concurrent-execution-handler.test.d.ts.map +1 -0
  78. package/dist-types/handlers/invoke-handler/invoke-handler-two-phase.test.d.ts +2 -0
  79. package/dist-types/handlers/invoke-handler/invoke-handler-two-phase.test.d.ts.map +1 -0
  80. package/dist-types/handlers/invoke-handler/invoke-handler.d.ts +8 -0
  81. package/dist-types/handlers/invoke-handler/invoke-handler.d.ts.map +1 -0
  82. package/dist-types/handlers/invoke-handler/invoke-handler.test.d.ts +2 -0
  83. package/dist-types/handlers/invoke-handler/invoke-handler.test.d.ts.map +1 -0
  84. package/dist-types/handlers/map-handler/map-handler-two-phase.test.d.ts +2 -0
  85. package/dist-types/handlers/map-handler/map-handler-two-phase.test.d.ts.map +1 -0
  86. package/dist-types/handlers/map-handler/map-handler.d.ts +3 -0
  87. package/dist-types/handlers/map-handler/map-handler.d.ts.map +1 -0
  88. package/dist-types/handlers/map-handler/map-handler.test.d.ts +2 -0
  89. package/dist-types/handlers/map-handler/map-handler.test.d.ts.map +1 -0
  90. package/dist-types/handlers/parallel-handler/parallel-handler-two-phase.test.d.ts +2 -0
  91. package/dist-types/handlers/parallel-handler/parallel-handler-two-phase.test.d.ts.map +1 -0
  92. package/dist-types/handlers/parallel-handler/parallel-handler.d.ts +3 -0
  93. package/dist-types/handlers/parallel-handler/parallel-handler.d.ts.map +1 -0
  94. package/dist-types/handlers/parallel-handler/parallel-handler.test.d.ts +2 -0
  95. package/dist-types/handlers/parallel-handler/parallel-handler.test.d.ts.map +1 -0
  96. package/dist-types/handlers/promise-handler/promise-handler.d.ts +8 -0
  97. package/dist-types/handlers/promise-handler/promise-handler.d.ts.map +1 -0
  98. package/dist-types/handlers/promise-handler/promise-handler.test.d.ts +2 -0
  99. package/dist-types/handlers/promise-handler/promise-handler.test.d.ts.map +1 -0
  100. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-handler-two-phase.test.d.ts +2 -0
  101. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-handler-two-phase.test.d.ts.map +1 -0
  102. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-handler.d.ts +10 -0
  103. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-handler.d.ts.map +1 -0
  104. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-handler.test.d.ts +2 -0
  105. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-handler.test.d.ts.map +1 -0
  106. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-integration.test.d.ts +2 -0
  107. package/dist-types/handlers/run-in-child-context-handler/run-in-child-context-integration.test.d.ts.map +1 -0
  108. package/dist-types/handlers/step-handler/step-handler-two-phase.test.d.ts +2 -0
  109. package/dist-types/handlers/step-handler/step-handler-two-phase.test.d.ts.map +1 -0
  110. package/dist-types/handlers/step-handler/step-handler.d.ts +14 -0
  111. package/dist-types/handlers/step-handler/step-handler.d.ts.map +1 -0
  112. package/dist-types/handlers/step-handler/step-handler.test.d.ts +2 -0
  113. package/dist-types/handlers/step-handler/step-handler.test.d.ts.map +1 -0
  114. package/dist-types/handlers/step-handler/step-handler.timing.test.d.ts +2 -0
  115. package/dist-types/handlers/step-handler/step-handler.timing.test.d.ts.map +1 -0
  116. package/dist-types/handlers/wait-for-callback-handler/wait-for-callback-handler.d.ts +3 -0
  117. package/dist-types/handlers/wait-for-callback-handler/wait-for-callback-handler.d.ts.map +1 -0
  118. package/dist-types/handlers/wait-for-callback-handler/wait-for-callback-handler.test.d.ts +2 -0
  119. package/dist-types/handlers/wait-for-callback-handler/wait-for-callback-handler.test.d.ts.map +1 -0
  120. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler-two-phase.test.d.ts +2 -0
  121. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler-two-phase.test.d.ts.map +1 -0
  122. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.d.ts +10 -0
  123. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.d.ts.map +1 -0
  124. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.test.d.ts +2 -0
  125. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.test.d.ts.map +1 -0
  126. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.timing.test.d.ts +2 -0
  127. package/dist-types/handlers/wait-for-condition-handler/wait-for-condition-handler.timing.test.d.ts.map +1 -0
  128. package/dist-types/handlers/wait-handler/wait-handler-two-phase.test.d.ts +2 -0
  129. package/dist-types/handlers/wait-handler/wait-handler-two-phase.test.d.ts.map +1 -0
  130. package/dist-types/handlers/wait-handler/wait-handler.d.ts +9 -0
  131. package/dist-types/handlers/wait-handler/wait-handler.d.ts.map +1 -0
  132. package/dist-types/handlers/wait-handler/wait-handler.test.d.ts +2 -0
  133. package/dist-types/handlers/wait-handler/wait-handler.test.d.ts.map +1 -0
  134. package/dist-types/index.d.ts +12 -0
  135. package/dist-types/index.d.ts.map +1 -0
  136. package/dist-types/run-durable.d.ts +2 -0
  137. package/dist-types/run-durable.d.ts.map +1 -0
  138. package/dist-types/termination-manager/termination-manager-checkpoint.test.d.ts +2 -0
  139. package/dist-types/termination-manager/termination-manager-checkpoint.test.d.ts.map +1 -0
  140. package/dist-types/termination-manager/termination-manager.d.ts +15 -0
  141. package/dist-types/termination-manager/termination-manager.d.ts.map +1 -0
  142. package/dist-types/termination-manager/termination-manager.test.d.ts +2 -0
  143. package/dist-types/termination-manager/termination-manager.test.d.ts.map +1 -0
  144. package/dist-types/termination-manager/types.d.ts +26 -0
  145. package/dist-types/termination-manager/types.d.ts.map +1 -0
  146. package/dist-types/testing/create-test-checkpoint-manager.d.ts +5 -0
  147. package/dist-types/testing/create-test-checkpoint-manager.d.ts.map +1 -0
  148. package/dist-types/testing/create-test-durable-context.d.ts +32 -0
  149. package/dist-types/testing/create-test-durable-context.d.ts.map +1 -0
  150. package/dist-types/testing/mock-batch-result.d.ts +26 -0
  151. package/dist-types/testing/mock-batch-result.d.ts.map +1 -0
  152. package/dist-types/testing/mock-checkpoint-manager.d.ts +21 -0
  153. package/dist-types/testing/mock-checkpoint-manager.d.ts.map +1 -0
  154. package/dist-types/testing/mock-checkpoint.d.ts +12 -0
  155. package/dist-types/testing/mock-checkpoint.d.ts.map +1 -0
  156. package/dist-types/testing/mock-context.d.ts +10 -0
  157. package/dist-types/testing/mock-context.d.ts.map +1 -0
  158. package/dist-types/testing/test-constants.d.ts +59 -0
  159. package/dist-types/testing/test-constants.d.ts.map +1 -0
  160. package/dist-types/types/batch.d.ts +177 -0
  161. package/dist-types/types/batch.d.ts.map +1 -0
  162. package/dist-types/types/callback.d.ts +48 -0
  163. package/dist-types/types/callback.d.ts.map +1 -0
  164. package/dist-types/types/child-context.d.ts +24 -0
  165. package/dist-types/types/child-context.d.ts.map +1 -0
  166. package/dist-types/types/core.d.ts +315 -0
  167. package/dist-types/types/core.d.ts.map +1 -0
  168. package/dist-types/types/durable-context.d.ts +667 -0
  169. package/dist-types/types/durable-context.d.ts.map +1 -0
  170. package/dist-types/types/durable-execution.d.ts +192 -0
  171. package/dist-types/types/durable-execution.d.ts.map +1 -0
  172. package/dist-types/types/durable-logger.d.ts +69 -0
  173. package/dist-types/types/durable-logger.d.ts.map +1 -0
  174. package/dist-types/types/durable-promise.d.ts +80 -0
  175. package/dist-types/types/durable-promise.d.ts.map +1 -0
  176. package/dist-types/types/index.d.ts +13 -0
  177. package/dist-types/types/index.d.ts.map +1 -0
  178. package/dist-types/types/invoke.d.ts +12 -0
  179. package/dist-types/types/invoke.d.ts.map +1 -0
  180. package/dist-types/types/logger.d.ts +63 -0
  181. package/dist-types/types/logger.d.ts.map +1 -0
  182. package/dist-types/types/step.d.ts +76 -0
  183. package/dist-types/types/step.d.ts.map +1 -0
  184. package/dist-types/types/wait-condition.d.ts +46 -0
  185. package/dist-types/types/wait-condition.d.ts.map +1 -0
  186. package/dist-types/utils/checkpoint/checkpoint-ancestor-checking.test.d.ts +2 -0
  187. package/dist-types/utils/checkpoint/checkpoint-ancestor-checking.test.d.ts.map +1 -0
  188. package/dist-types/utils/checkpoint/checkpoint-error-classification.test.d.ts +2 -0
  189. package/dist-types/utils/checkpoint/checkpoint-error-classification.test.d.ts.map +1 -0
  190. package/dist-types/utils/checkpoint/checkpoint-helper.d.ts +10 -0
  191. package/dist-types/utils/checkpoint/checkpoint-helper.d.ts.map +1 -0
  192. package/dist-types/utils/checkpoint/checkpoint-integration.test.d.ts +2 -0
  193. package/dist-types/utils/checkpoint/checkpoint-integration.test.d.ts.map +1 -0
  194. package/dist-types/utils/checkpoint/checkpoint-manager.d.ts +53 -0
  195. package/dist-types/utils/checkpoint/checkpoint-manager.d.ts.map +1 -0
  196. package/dist-types/utils/checkpoint/checkpoint-queue-completion.test.d.ts +2 -0
  197. package/dist-types/utils/checkpoint/checkpoint-queue-completion.test.d.ts.map +1 -0
  198. package/dist-types/utils/checkpoint/checkpoint-stepdata-update.test.d.ts +2 -0
  199. package/dist-types/utils/checkpoint/checkpoint-stepdata-update.test.d.ts.map +1 -0
  200. package/dist-types/utils/checkpoint/checkpoint-termination.test.d.ts +2 -0
  201. package/dist-types/utils/checkpoint/checkpoint-termination.test.d.ts.map +1 -0
  202. package/dist-types/utils/checkpoint/checkpoint.test.d.ts +2 -0
  203. package/dist-types/utils/checkpoint/checkpoint.test.d.ts.map +1 -0
  204. package/dist-types/utils/constants/constants.d.ts +10 -0
  205. package/dist-types/utils/constants/constants.d.ts.map +1 -0
  206. package/dist-types/utils/context-tracker/context-tracker.d.ts +13 -0
  207. package/dist-types/utils/context-tracker/context-tracker.d.ts.map +1 -0
  208. package/dist-types/utils/context-tracker/context-tracker.test.d.ts +2 -0
  209. package/dist-types/utils/context-tracker/context-tracker.test.d.ts.map +1 -0
  210. package/dist-types/utils/durable-execution-invocation-input/durable-execution-invocation-input.d.ts +20 -0
  211. package/dist-types/utils/durable-execution-invocation-input/durable-execution-invocation-input.d.ts.map +1 -0
  212. package/dist-types/utils/duration/duration.d.ts +8 -0
  213. package/dist-types/utils/duration/duration.d.ts.map +1 -0
  214. package/dist-types/utils/duration/duration.test.d.ts +2 -0
  215. package/dist-types/utils/duration/duration.test.d.ts.map +1 -0
  216. package/dist-types/utils/error-object/error-object-coverage.test.d.ts +2 -0
  217. package/dist-types/utils/error-object/error-object-coverage.test.d.ts.map +1 -0
  218. package/dist-types/utils/error-object/error-object.d.ts +3 -0
  219. package/dist-types/utils/error-object/error-object.d.ts.map +1 -0
  220. package/dist-types/utils/error-object/error-object.test.d.ts +2 -0
  221. package/dist-types/utils/error-object/error-object.test.d.ts.map +1 -0
  222. package/dist-types/utils/logger/default-logger.d.ts +51 -0
  223. package/dist-types/utils/logger/default-logger.d.ts.map +1 -0
  224. package/dist-types/utils/logger/default-logger.test.d.ts +2 -0
  225. package/dist-types/utils/logger/default-logger.test.d.ts.map +1 -0
  226. package/dist-types/utils/logger/logger.d.ts +2 -0
  227. package/dist-types/utils/logger/logger.d.ts.map +1 -0
  228. package/dist-types/utils/logger/logger.test.d.ts +2 -0
  229. package/dist-types/utils/logger/logger.test.d.ts.map +1 -0
  230. package/dist-types/utils/logger/structured-logger-integration.test.d.ts +2 -0
  231. package/dist-types/utils/logger/structured-logger-integration.test.d.ts.map +1 -0
  232. package/dist-types/utils/replay-validation/replay-validation.d.ts +8 -0
  233. package/dist-types/utils/replay-validation/replay-validation.d.ts.map +1 -0
  234. package/dist-types/utils/replay-validation/replay-validation.test.d.ts +2 -0
  235. package/dist-types/utils/replay-validation/replay-validation.test.d.ts.map +1 -0
  236. package/dist-types/utils/retry/retry-config/index.d.ts +167 -0
  237. package/dist-types/utils/retry/retry-config/index.d.ts.map +1 -0
  238. package/dist-types/utils/retry/retry-config/index.test.d.ts +2 -0
  239. package/dist-types/utils/retry/retry-config/index.test.d.ts.map +1 -0
  240. package/dist-types/utils/retry/retry-presets/retry-presets.d.ts +35 -0
  241. package/dist-types/utils/retry/retry-presets/retry-presets.d.ts.map +1 -0
  242. package/dist-types/utils/safe-stringify/safe-stringify.d.ts +2 -0
  243. package/dist-types/utils/safe-stringify/safe-stringify.d.ts.map +1 -0
  244. package/dist-types/utils/safe-stringify/safe-stringify.test.d.ts +2 -0
  245. package/dist-types/utils/safe-stringify/safe-stringify.test.d.ts.map +1 -0
  246. package/dist-types/utils/serdes/serdes.d.ts +152 -0
  247. package/dist-types/utils/serdes/serdes.d.ts.map +1 -0
  248. package/dist-types/utils/serdes/serdes.test.d.ts +2 -0
  249. package/dist-types/utils/serdes/serdes.test.d.ts.map +1 -0
  250. package/dist-types/utils/step-id-utils/step-id-utils.d.ts +16 -0
  251. package/dist-types/utils/step-id-utils/step-id-utils.d.ts.map +1 -0
  252. package/dist-types/utils/step-id-utils/step-id-utils.test.d.ts +2 -0
  253. package/dist-types/utils/step-id-utils/step-id-utils.test.d.ts.map +1 -0
  254. package/dist-types/utils/summary-generators/summary-generators.d.ts +10 -0
  255. package/dist-types/utils/summary-generators/summary-generators.d.ts.map +1 -0
  256. package/dist-types/utils/summary-generators/summary-generators.test.d.ts +2 -0
  257. package/dist-types/utils/summary-generators/summary-generators.test.d.ts.map +1 -0
  258. package/dist-types/utils/termination-helper/active-operations-tracker.d.ts +31 -0
  259. package/dist-types/utils/termination-helper/active-operations-tracker.d.ts.map +1 -0
  260. package/dist-types/utils/termination-helper/active-operations-tracker.test.d.ts +2 -0
  261. package/dist-types/utils/termination-helper/active-operations-tracker.test.d.ts.map +1 -0
  262. package/dist-types/utils/termination-helper/termination-deferral.test.d.ts +2 -0
  263. package/dist-types/utils/termination-helper/termination-deferral.test.d.ts.map +1 -0
  264. package/dist-types/utils/termination-helper/termination-helper.d.ts +20 -0
  265. package/dist-types/utils/termination-helper/termination-helper.d.ts.map +1 -0
  266. package/dist-types/utils/termination-helper/termination-helper.test.d.ts +2 -0
  267. package/dist-types/utils/termination-helper/termination-helper.test.d.ts.map +1 -0
  268. package/dist-types/utils/wait-before-continue/wait-before-continue.d.ts +35 -0
  269. package/dist-types/utils/wait-before-continue/wait-before-continue.d.ts.map +1 -0
  270. package/dist-types/utils/wait-before-continue/wait-before-continue.test.d.ts +2 -0
  271. package/dist-types/utils/wait-before-continue/wait-before-continue.test.d.ts.map +1 -0
  272. package/dist-types/utils/wait-strategy/wait-strategy-config.d.ts +19 -0
  273. package/dist-types/utils/wait-strategy/wait-strategy-config.d.ts.map +1 -0
  274. package/dist-types/utils/wait-strategy/wait-strategy-config.test.d.ts +2 -0
  275. package/dist-types/utils/wait-strategy/wait-strategy-config.test.d.ts.map +1 -0
  276. package/dist-types/with-durable-execution-queue-completion.test.d.ts +2 -0
  277. package/dist-types/with-durable-execution-queue-completion.test.d.ts.map +1 -0
  278. package/dist-types/with-durable-execution.d.ts +75 -0
  279. package/dist-types/with-durable-execution.d.ts.map +1 -0
  280. package/dist-types/with-durable-execution.test.d.ts +2 -0
  281. package/dist-types/with-durable-execution.test.d.ts.map +1 -0
  282. package/package.json +64 -3
package/dist/index.mjs ADDED
@@ -0,0 +1,4771 @@
1
+ import { OperationStatus, OperationAction, OperationType, LambdaClient, GetDurableExecutionStateCommand, CheckpointDurableExecutionCommand } from '@aws-sdk/client-lambda';
2
+ import { EventEmitter } from 'events';
3
+ import { AsyncLocalStorage } from 'async_hooks';
4
+ import { createHash } from 'crypto';
5
+ import { Console } from 'node:console';
6
+ import util from 'node:util';
7
+
8
+ /**
9
+ * @internal
10
+ */
11
+ var DurableExecutionMode;
12
+ (function (DurableExecutionMode) {
13
+ DurableExecutionMode["ExecutionMode"] = "ExecutionMode";
14
+ DurableExecutionMode["ReplayMode"] = "ReplayMode";
15
+ DurableExecutionMode["ReplaySucceededContext"] = "ReplaySucceededContext";
16
+ })(DurableExecutionMode || (DurableExecutionMode = {}));
17
+ /**
18
+ * Status enumeration for durable execution invocation results.
19
+ *
20
+ * This enum defines the possible outcomes of a durable execution invocation,
21
+ * indicating whether the execution completed successfully, failed, or is
22
+ * continuing asynchronously.
23
+ *
24
+ * The status determines how the AWS durable execution service will handle
25
+ * the execution:
26
+ * - SUCCEEDED: Execution completed successfully with a final result
27
+ * - FAILED: Execution failed with an error that cannot be retried
28
+ * - PENDING: Execution is continuing and will be resumed later (checkpointed)
29
+ *
30
+ * @public
31
+ */
32
+ var InvocationStatus;
33
+ (function (InvocationStatus) {
34
+ /**
35
+ * The durable execution completed successfully.
36
+ *
37
+ * This status indicates:
38
+ * - A final result is available (if any)
39
+ * - No further invocations are needed
40
+ * - The execution has reached its natural completion
41
+ */
42
+ InvocationStatus["SUCCEEDED"] = "SUCCEEDED";
43
+ /**
44
+ * The durable execution failed with an unrecoverable error.
45
+ *
46
+ * This status indicates:
47
+ * - An error occurred that cannot be automatically retried
48
+ * - Error details are provided in the response
49
+ * - No further invocations will occur
50
+ */
51
+ InvocationStatus["FAILED"] = "FAILED";
52
+ /**
53
+ * The durable execution is continuing asynchronously.
54
+ *
55
+ * This status indicates:
56
+ * - Execution was checkpointed and will resume later
57
+ * - Common scenarios: waiting for callbacks, retries, wait operations
58
+ * - The function may terminate while execution continues
59
+ * - Future invocations will resume from the checkpoint
60
+ */
61
+ InvocationStatus["PENDING"] = "PENDING";
62
+ })(InvocationStatus || (InvocationStatus = {}));
63
+ /**
64
+ * Operation subtype enumeration for categorizing different types of durable operations.
65
+ *
66
+ * This enum provides fine-grained classification of durable operations beyond the
67
+ * basic operation types. Subtypes enable improved observability for specific
68
+ * operation patterns.
69
+ *
70
+ * Each subtype corresponds to a specific durable context method or execution pattern.
71
+ *
72
+ * @public
73
+ */
74
+ var OperationSubType;
75
+ (function (OperationSubType) {
76
+ /**
77
+ * A durable step operation (`context.step`).
78
+ *
79
+ * Represents atomic operations with automatic retry and checkpointing.
80
+ * Steps are the fundamental building blocks of durable executions.
81
+ */
82
+ OperationSubType["STEP"] = "Step";
83
+ /**
84
+ * A wait operation (`context.wait`).
85
+ *
86
+ * Represents time-based delays that pause execution for a specified duration.
87
+ * Waits allow long-running workflows without keeping invocations active.
88
+ */
89
+ OperationSubType["WAIT"] = "Wait";
90
+ /**
91
+ * A callback creation operation (`context.createCallback`).
92
+ *
93
+ * Represents the creation of a callback that external systems can complete.
94
+ * Used for human-in-the-loop workflows and external system integration.
95
+ */
96
+ OperationSubType["CALLBACK"] = "Callback";
97
+ /**
98
+ * A child context operation (`context.runInChildContext`).
99
+ *
100
+ * Represents execution within an isolated child context with its own
101
+ * step counter and state tracking. Used for grouping related operations.
102
+ */
103
+ OperationSubType["RUN_IN_CHILD_CONTEXT"] = "RunInChildContext";
104
+ /**
105
+ * A map operation (`context.map`).
106
+ *
107
+ * Represents parallel processing of an array of items with concurrency control
108
+ * and completion policies. Each map operation coordinates multiple iterations.
109
+ */
110
+ OperationSubType["MAP"] = "Map";
111
+ /**
112
+ * An individual iteration within a map operation.
113
+ *
114
+ * Represents the processing of a single item within a `context.map` call.
115
+ * Each iteration runs in its own child context with isolated state.
116
+ */
117
+ OperationSubType["MAP_ITERATION"] = "MapIteration";
118
+ /**
119
+ * A parallel execution operation (`context.parallel`).
120
+ *
121
+ * Represents concurrent execution of multiple branches with optional
122
+ * concurrency control and completion policies.
123
+ */
124
+ OperationSubType["PARALLEL"] = "Parallel";
125
+ /**
126
+ * An individual branch within a parallel operation.
127
+ *
128
+ * Represents a single branch of execution within a `context.parallel` call.
129
+ * Each branch runs in its own child context with isolated state.
130
+ */
131
+ OperationSubType["PARALLEL_BRANCH"] = "ParallelBranch";
132
+ /**
133
+ * A wait for callback operation (`context.waitForCallback`).
134
+ *
135
+ * Represents waiting for an external system to complete a callback,
136
+ * combining callback creation with submission logic.
137
+ */
138
+ OperationSubType["WAIT_FOR_CALLBACK"] = "WaitForCallback";
139
+ /**
140
+ * A wait for condition operation (`context.waitForCondition`).
141
+ *
142
+ * Represents periodic checking of a condition until it's met,
143
+ * with configurable polling intervals and wait strategies.
144
+ */
145
+ OperationSubType["WAIT_FOR_CONDITION"] = "WaitForCondition";
146
+ /**
147
+ * A chained invocation operation (`context.invoke`).
148
+ *
149
+ * Represents calling another durable function with input parameters
150
+ * and waiting for its completion. Used for function composition and workflows.
151
+ */
152
+ OperationSubType["CHAINED_INVOKE"] = "ChainedInvoke";
153
+ })(OperationSubType || (OperationSubType = {}));
154
+
155
+ /**
156
+ * Log level supported by the durable logger
157
+ * @public
158
+ */
159
+ var DurableLogLevel;
160
+ (function (DurableLogLevel) {
161
+ DurableLogLevel["INFO"] = "INFO";
162
+ DurableLogLevel["WARN"] = "WARN";
163
+ DurableLogLevel["ERROR"] = "ERROR";
164
+ DurableLogLevel["DEBUG"] = "DEBUG";
165
+ })(DurableLogLevel || (DurableLogLevel = {}));
166
+
167
+ /**
168
+ * @public
169
+ */
170
+ var StepSemantics;
171
+ (function (StepSemantics) {
172
+ StepSemantics["AtMostOncePerRetry"] = "AT_MOST_ONCE_PER_RETRY";
173
+ StepSemantics["AtLeastOncePerRetry"] = "AT_LEAST_ONCE_PER_RETRY";
174
+ })(StepSemantics || (StepSemantics = {}));
175
+ /**
176
+ * Jitter strategy for retry delays to prevent thundering herd. Jitter reduces simultaneous retry attempts
177
+ * by spreading retries out over a randomized delay interval.
178
+ *
179
+ * @public
180
+ */
181
+ var JitterStrategy;
182
+ (function (JitterStrategy) {
183
+ /** No jitter - use exact calculated delay */
184
+ JitterStrategy["NONE"] = "NONE";
185
+ /** Full jitter - random delay between 0 and calculated delay */
186
+ JitterStrategy["FULL"] = "FULL";
187
+ /** Half jitter - random delay between 50% and 100% of calculated delay */
188
+ JitterStrategy["HALF"] = "HALF";
189
+ })(JitterStrategy || (JitterStrategy = {}));
190
+
191
+ /**
192
+ * The status of a batch item
193
+ * @public
194
+ */
195
+ var BatchItemStatus;
196
+ (function (BatchItemStatus) {
197
+ BatchItemStatus["SUCCEEDED"] = "SUCCEEDED";
198
+ BatchItemStatus["FAILED"] = "FAILED";
199
+ BatchItemStatus["STARTED"] = "STARTED";
200
+ })(BatchItemStatus || (BatchItemStatus = {}));
201
+
202
+ /**
203
+ * A promise that defers execution until it's awaited or .then/.catch/.finally is called
204
+ *
205
+ * @public
206
+ */
207
+ class DurablePromise {
208
+ /**
209
+ * The actual promise instance, created only when execution begins.
210
+ * Starts as null and remains null until the DurablePromise is first awaited
211
+ * or chained (.then/.catch/.finally). Once created, it holds the running
212
+ * promise returned by the _executor function.
213
+ *
214
+ * Example lifecycle:
215
+ * ```typescript
216
+ * const dp = new DurablePromise(() => fetch('/api')); // _promise = null
217
+ * console.log(dp.isExecuted); // false
218
+ *
219
+ * const result = await dp; // NOW _promise = fetch('/api') promise
220
+ * console.log(dp.isExecuted); // true
221
+ * ```
222
+ *
223
+ * This lazy initialization prevents the executor from running until needed.
224
+ */
225
+ _promise = null;
226
+ /**
227
+ * Function that contains the deferred execution logic.
228
+ * This function is NOT called when the DurablePromise is created - it's only
229
+ * executed when the promise is first awaited or chained (.then/.catch/.finally).
230
+ *
231
+ * Example:
232
+ * ```typescript
233
+ * const durablePromise = new DurablePromise(async () => {
234
+ * console.log("This runs ONLY when awaited, not when created");
235
+ * return await someAsyncOperation();
236
+ * });
237
+ *
238
+ * // At this point, nothing has executed yet
239
+ * console.log("Promise created but not executed");
240
+ *
241
+ * // NOW the executor function runs
242
+ * const result = await durablePromise;
243
+ * ```
244
+ */
245
+ _executor;
246
+ /** Flag indicating whether the promise has been executed (awaited or chained) */
247
+ _isExecuted = false;
248
+ /**
249
+ * Creates a new DurablePromise
250
+ * @param executor - Function containing the deferred execution logic
251
+ */
252
+ constructor(executor) {
253
+ this._executor = executor;
254
+ }
255
+ /**
256
+ * Ensures the promise is executed, creating the actual promise if needed
257
+ * @returns The underlying promise instance
258
+ */
259
+ ensureExecution() {
260
+ if (!this._promise) {
261
+ this._isExecuted = true;
262
+ // Execute the promise
263
+ this._promise = this._executor();
264
+ }
265
+ return this._promise;
266
+ }
267
+ /**
268
+ * Attaches callbacks for the resolution and/or rejection of the Promise
269
+ * Triggers execution if not already started
270
+ */
271
+ then(onfulfilled, onrejected) {
272
+ return this.ensureExecution().then(onfulfilled, onrejected);
273
+ }
274
+ /**
275
+ * Attaches a callback for only the rejection of the Promise
276
+ * Triggers execution if not already started
277
+ */
278
+ catch(onrejected) {
279
+ return this.ensureExecution().catch(onrejected);
280
+ }
281
+ /**
282
+ * Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected)
283
+ * Triggers execution if not already started
284
+ */
285
+ finally(onfinally) {
286
+ return this.ensureExecution().finally(onfinally);
287
+ }
288
+ /** Returns the string tag for the promise type */
289
+ get [Symbol.toStringTag]() {
290
+ return "DurablePromise";
291
+ }
292
+ /**
293
+ * Check if the promise has been executed (awaited or had .then/.catch/.finally called)
294
+ * @returns true if execution has started, false otherwise
295
+ */
296
+ get isExecuted() {
297
+ return this._isExecuted;
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Converts a Duration object to total seconds
303
+ * @param duration - Duration object with at least one time unit specified
304
+ * @returns Total duration in seconds
305
+ */
306
+ function durationToSeconds(duration) {
307
+ const days = "days" in duration ? (duration.days ?? 0) : 0;
308
+ const hours = "hours" in duration ? (duration.hours ?? 0) : 0;
309
+ const minutes = "minutes" in duration ? (duration.minutes ?? 0) : 0;
310
+ const seconds = "seconds" in duration ? (duration.seconds ?? 0) : 0;
311
+ return days * 24 * 60 * 60 + hours * 60 * 60 + minutes * 60 + seconds;
312
+ }
313
+
314
+ const safeStringify = (data) => {
315
+ try {
316
+ const seen = new WeakSet();
317
+ return JSON.stringify(data, (key, value) => {
318
+ if (typeof value === "object" && value !== null) {
319
+ if (seen.has(value))
320
+ return "[Circular]";
321
+ seen.add(value);
322
+ // Handle Error objects by extracting their properties
323
+ if (value instanceof Error) {
324
+ return {
325
+ ...value,
326
+ name: value.name,
327
+ message: value.message,
328
+ stack: value.stack,
329
+ };
330
+ }
331
+ }
332
+ return value;
333
+ }, 2);
334
+ }
335
+ catch {
336
+ return "[Unable to stringify]";
337
+ }
338
+ };
339
+
340
+ /* eslint-disable no-console */
341
+ const log = (emoji, message, data) => {
342
+ if (process.env.DURABLE_VERBOSE_MODE === "true") {
343
+ console.debug(`${emoji} ${message}`, data ? safeStringify(data) : "");
344
+ }
345
+ };
346
+
347
+ var TerminationReason;
348
+ (function (TerminationReason) {
349
+ // Default termination reason
350
+ TerminationReason["OPERATION_TERMINATED"] = "OPERATION_TERMINATED";
351
+ // Retry-related reasons
352
+ TerminationReason["RETRY_SCHEDULED"] = "RETRY_SCHEDULED";
353
+ TerminationReason["RETRY_INTERRUPTED_STEP"] = "RETRY_INTERRUPTED_STEP";
354
+ // Wait-related reasons
355
+ TerminationReason["WAIT_SCHEDULED"] = "WAIT_SCHEDULED";
356
+ // Callback-related reasons
357
+ TerminationReason["CALLBACK_PENDING"] = "CALLBACK_PENDING";
358
+ // Error-related reasons
359
+ TerminationReason["CHECKPOINT_FAILED"] = "CHECKPOINT_FAILED";
360
+ TerminationReason["SERDES_FAILED"] = "SERDES_FAILED";
361
+ TerminationReason["CONTEXT_VALIDATION_ERROR"] = "CONTEXT_VALIDATION_ERROR";
362
+ // Custom reason
363
+ TerminationReason["CUSTOM"] = "CUSTOM";
364
+ })(TerminationReason || (TerminationReason = {}));
365
+
366
+ const asyncLocalStorage = new AsyncLocalStorage();
367
+ const getActiveContext = () => {
368
+ return asyncLocalStorage.getStore();
369
+ };
370
+ const runWithContext = (contextId, parentId, fn, attempt, durableExecutionMode) => {
371
+ return asyncLocalStorage.run({ contextId, parentId, attempt, durableExecutionMode }, fn);
372
+ };
373
+ const validateContextUsage = (operationContextId, operationName, terminationManager) => {
374
+ const contextId = operationContextId || "root";
375
+ const activeContext = getActiveContext();
376
+ if (!activeContext) {
377
+ return;
378
+ }
379
+ if (activeContext.contextId !== contextId) {
380
+ 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.`;
381
+ terminationManager.terminate({
382
+ reason: TerminationReason.CONTEXT_VALIDATION_ERROR,
383
+ message: errorMessage,
384
+ error: new Error(errorMessage),
385
+ });
386
+ // Only call termination manager, don't throw or return promise
387
+ }
388
+ };
389
+
390
+ const HASH_LENGTH = 16;
391
+ /**
392
+ * Creates an MD5 hash of the input string for better performance than SHA-256
393
+ * @param input - The string to hash
394
+ * @returns The truncated hexadecimal hash string
395
+ */
396
+ const hashId = (input) => {
397
+ return createHash("md5")
398
+ .update(input)
399
+ .digest("hex")
400
+ .substring(0, HASH_LENGTH);
401
+ };
402
+ /**
403
+ * Helper function to get step data using the original stepId
404
+ * This function handles the hashing internally so callers don't need to worry about it
405
+ * @param stepData - The stepData record from context
406
+ * @param stepId - The original stepId (will be hashed internally)
407
+ * @returns The operation data or undefined if not found
408
+ */
409
+ const getStepData = (stepData, stepId) => {
410
+ const hashedId = hashId(stepId);
411
+ return stepData[hashedId];
412
+ };
413
+
414
+ /**
415
+ * Checks if any ancestor operation in the parent chain has finished (SUCCEEDED or FAILED)
416
+ * or has a pending completion checkpoint
417
+ */
418
+ function hasFinishedAncestor(context, parentId) {
419
+ if (!parentId) {
420
+ log("🔍", "hasFinishedAncestor: No parentId provided");
421
+ return false;
422
+ }
423
+ // First check if any ancestor has a pending completion checkpoint
424
+ if (hasPendingAncestorCompletion(context, parentId)) {
425
+ log("🔍", "hasFinishedAncestor: Found ancestor with pending completion!", {
426
+ parentId,
427
+ });
428
+ return true;
429
+ }
430
+ let currentHashedId = hashId(parentId);
431
+ log("🔍", "hasFinishedAncestor: Starting check", {
432
+ parentId,
433
+ initialHashedId: currentHashedId,
434
+ });
435
+ while (currentHashedId) {
436
+ const parentOperation = context._stepData[currentHashedId];
437
+ log("🔍", "hasFinishedAncestor: Checking operation", {
438
+ hashedId: currentHashedId,
439
+ hasOperation: !!parentOperation,
440
+ status: parentOperation?.Status,
441
+ type: parentOperation?.Type,
442
+ });
443
+ if (parentOperation?.Status === OperationStatus.SUCCEEDED ||
444
+ parentOperation?.Status === OperationStatus.FAILED) {
445
+ log("🔍", "hasFinishedAncestor: Found finished ancestor!", {
446
+ hashedId: currentHashedId,
447
+ status: parentOperation.Status,
448
+ });
449
+ return true;
450
+ }
451
+ currentHashedId = parentOperation?.ParentId;
452
+ }
453
+ log("🔍", "hasFinishedAncestor: No finished ancestor found");
454
+ return false;
455
+ }
456
+ /**
457
+ * Checks if any ancestor has a pending completion checkpoint
458
+ */
459
+ function hasPendingAncestorCompletion(context, stepId) {
460
+ let currentHashedId = hashId(stepId);
461
+ while (currentHashedId) {
462
+ if (context.pendingCompletions.has(currentHashedId)) {
463
+ return true;
464
+ }
465
+ const operation = context._stepData[currentHashedId];
466
+ currentHashedId = operation?.ParentId;
467
+ }
468
+ return false;
469
+ }
470
+ /**
471
+ * Terminates execution and returns a never-resolving promise to prevent code progression
472
+ * @param context - The execution context containing the termination manager
473
+ * @param reason - The termination reason
474
+ * @param message - The termination message
475
+ * @returns A never-resolving promise
476
+ */
477
+ function terminate(context, reason, message) {
478
+ const activeContext = getActiveContext();
479
+ // If we have a parent context, add delay to let checkpoints process
480
+ if (activeContext?.parentId) {
481
+ return new Promise(async (_resolve, _reject) => {
482
+ // Wait a tick to let any pending checkpoints start processing
483
+ await new Promise((resolve) => setImmediate(resolve));
484
+ log("🔍", "Terminate called - checking context:", {
485
+ hasActiveContext: !!activeContext,
486
+ contextId: activeContext?.contextId,
487
+ parentId: activeContext?.parentId,
488
+ reason,
489
+ message,
490
+ });
491
+ const ancestorFinished = hasFinishedAncestor(context, activeContext.parentId);
492
+ log("🔍", "Ancestor check result:", {
493
+ parentId: activeContext.parentId,
494
+ ancestorFinished,
495
+ });
496
+ if (ancestorFinished) {
497
+ log("🛑", "Skipping termination - ancestor already finished:", {
498
+ contextId: activeContext.contextId,
499
+ parentId: activeContext.parentId,
500
+ reason,
501
+ message,
502
+ });
503
+ // Return never-resolving promise without terminating
504
+ return;
505
+ }
506
+ // Check if there are active operations before terminating
507
+ const tracker = context.activeOperationsTracker;
508
+ if (tracker && tracker.hasActive()) {
509
+ log("⏳", "Deferring termination - active operations in progress:", {
510
+ activeCount: tracker.getCount(),
511
+ reason,
512
+ message,
513
+ });
514
+ // Wait for operations to complete, then terminate
515
+ const checkInterval = setInterval(() => {
516
+ if (!tracker.hasActive()) {
517
+ clearInterval(checkInterval);
518
+ log("✅", "Active operations completed, proceeding with termination:", {
519
+ reason,
520
+ message,
521
+ });
522
+ context.terminationManager.terminate({
523
+ reason,
524
+ message,
525
+ });
526
+ }
527
+ }, 10);
528
+ return;
529
+ }
530
+ // No active operations, terminate immediately
531
+ context.terminationManager.terminate({
532
+ reason,
533
+ message,
534
+ });
535
+ });
536
+ }
537
+ // No parent context - check active operations and terminate
538
+ const tracker = context.activeOperationsTracker;
539
+ if (tracker && tracker.hasActive()) {
540
+ log("⏳", "Deferring termination - active operations in progress:", {
541
+ activeCount: tracker.getCount(),
542
+ reason,
543
+ message,
544
+ });
545
+ return new Promise((_resolve, _reject) => {
546
+ const checkInterval = setInterval(() => {
547
+ if (!tracker.hasActive()) {
548
+ clearInterval(checkInterval);
549
+ log("✅", "Active operations completed, proceeding with termination:", {
550
+ reason,
551
+ message,
552
+ });
553
+ context.terminationManager.terminate({
554
+ reason,
555
+ message,
556
+ });
557
+ }
558
+ }, 10);
559
+ });
560
+ }
561
+ // No parent, no active operations - terminate immediately
562
+ context.terminationManager.terminate({
563
+ reason,
564
+ message,
565
+ });
566
+ return new Promise(() => { });
567
+ }
568
+ /**
569
+ * Terminates execution for unrecoverable errors and returns a never-resolving promise
570
+ * @param context - The execution context containing the termination manager
571
+ * @param error - The unrecoverable error that caused termination
572
+ * @param stepIdentifier - The step name or ID for error messaging
573
+ * @returns A never-resolving promise
574
+ */
575
+ function terminateForUnrecoverableError(context, error, stepIdentifier) {
576
+ return terminate(context, error.terminationReason, `Unrecoverable error in step ${stepIdentifier}: ${error.message}`);
577
+ }
578
+
579
+ const DEFAULT_CONFIG$1 = {
580
+ maxAttempts: 3,
581
+ initialDelay: { seconds: 5 },
582
+ maxDelay: { minutes: 5 },
583
+ backoffRate: 2,
584
+ jitter: JitterStrategy.FULL,
585
+ retryableErrors: [/.*/], // By default, retry all errors
586
+ retryableErrorTypes: [],
587
+ };
588
+ const applyJitter$1 = (delay, strategy) => {
589
+ switch (strategy) {
590
+ case JitterStrategy.NONE:
591
+ return delay;
592
+ case JitterStrategy.FULL:
593
+ // Random between 0 and delay
594
+ return Math.random() * delay;
595
+ case JitterStrategy.HALF:
596
+ // Random between delay/2 and delay
597
+ return delay / 2 + Math.random() * (delay / 2);
598
+ default:
599
+ return delay;
600
+ }
601
+ };
602
+ /**
603
+ * Creates a retry strategy function with exponential backoff and configurable jitter
604
+ *
605
+ * @param config - Configuration options for the retry strategy
606
+ * @returns A function that determines whether to retry and calculates delay based on error and attempt count
607
+ *
608
+ * @remarks
609
+ * The returned function takes an error and attempt count, and returns a {@link RetryDecision} indicating
610
+ * whether to retry and the delay before the next attempt.
611
+ *
612
+ * **Delay Calculation:**
613
+ * - Base delay = `initialDelay × backoffRate^(attemptsMade - 1)`
614
+ * - Capped at `maxDelay`
615
+ * - Jitter applied based on `jitter` strategy
616
+ * - Final delay rounded to nearest second, minimum 1 second
617
+ *
618
+ * **Error Filtering:**
619
+ * - If neither `retryableErrors` nor `retryableErrorTypes` is specified: all errors are retried
620
+ * - If either is specified: only matching errors are retried
621
+ * - If both are specified: errors matching either criteria are retried (OR logic)
622
+ *
623
+ * @example
624
+ * ```typescript
625
+ * // Basic usage with defaults (retry all errors, 3 attempts, exponential backoff)
626
+ * const defaultRetry = createRetryStrategy();
627
+ *
628
+ * // Custom retry with more attempts and specific delays
629
+ * const customRetry = createRetryStrategy({
630
+ * maxAttempts: 5,
631
+ * initialDelay: { seconds: 10 },
632
+ * maxDelay: { seconds: 60 },
633
+ * backoffRate: 2,
634
+ * jitter: JitterStrategy.HALF
635
+ * });
636
+ *
637
+ * // Retry only specific error types
638
+ * class TimeoutError extends Error {}
639
+ * const typeBasedRetry = createRetryStrategy({
640
+ * retryableErrorTypes: [TimeoutError]
641
+ * });
642
+ *
643
+ * // Retry only errors matching message patterns
644
+ * const patternBasedRetry = createRetryStrategy({
645
+ * retryableErrors: [/timeout/i, /connection/i, "rate limit"]
646
+ * });
647
+ *
648
+ * // Combine error types and patterns
649
+ * const combinedRetry = createRetryStrategy({
650
+ * retryableErrorTypes: [TimeoutError],
651
+ * retryableErrors: [/network/i]
652
+ * });
653
+ *
654
+ * // Use in step configuration
655
+ * await context.step('api-call', async () => {
656
+ * return await callExternalAPI();
657
+ * }, { retryStrategy: customRetry });
658
+ * ```
659
+ *
660
+ * @see {@link RetryStrategyConfig} for configuration options
661
+ * @see {@link JitterStrategy} for jitter strategies
662
+ * @see {@link RetryDecision} for return type
663
+ *
664
+ * @public
665
+ */
666
+ const createRetryStrategy = (config = {}) => {
667
+ // Only apply default retryableErrors if user didn't specify either filter
668
+ const shouldUseDefaultErrors = config.retryableErrors === undefined &&
669
+ config.retryableErrorTypes === undefined;
670
+ const finalConfig = {
671
+ ...DEFAULT_CONFIG$1,
672
+ ...config,
673
+ retryableErrors: config.retryableErrors ?? (shouldUseDefaultErrors ? [/.*/] : []),
674
+ };
675
+ return (error, attemptsMade) => {
676
+ // Check if we've exceeded max attempts
677
+ if (attemptsMade >= finalConfig.maxAttempts) {
678
+ return { shouldRetry: false };
679
+ }
680
+ // Check if error is retryable based on error message
681
+ const isRetryableErrorMessage = finalConfig.retryableErrors.some((pattern) => {
682
+ if (pattern instanceof RegExp) {
683
+ return pattern.test(error.message);
684
+ }
685
+ return error.message.includes(pattern);
686
+ });
687
+ // Check if error is retryable based on error type
688
+ const isRetryableErrorType = finalConfig.retryableErrorTypes.some((ErrorType) => error instanceof ErrorType);
689
+ if (!isRetryableErrorMessage && !isRetryableErrorType) {
690
+ return { shouldRetry: false };
691
+ }
692
+ // Calculate delay with exponential backoff
693
+ const initialDelaySeconds = durationToSeconds(finalConfig.initialDelay);
694
+ const maxDelaySeconds = durationToSeconds(finalConfig.maxDelay);
695
+ const baseDelay = Math.min(initialDelaySeconds * Math.pow(finalConfig.backoffRate, attemptsMade - 1), maxDelaySeconds);
696
+ // Apply jitter
697
+ const delayWithJitter = applyJitter$1(baseDelay, finalConfig.jitter);
698
+ // Ensure delay is an integer >= 1
699
+ const finalDelay = Math.max(1, Math.round(delayWithJitter));
700
+ return { shouldRetry: true, delay: { seconds: finalDelay } };
701
+ };
702
+ };
703
+
704
+ /**
705
+ * Pre-configured retry strategies for common use cases
706
+ * @example
707
+ * ```typescript
708
+ * // Use default retry preset (3 attempts with exponential backoff)
709
+ * await context.step('my-step', async () => {
710
+ * return await someOperation();
711
+ * }, { retryStrategy: retryPresets.default });
712
+ *
713
+ * // Use no-retry preset (fail immediately on error)
714
+ * await context.step('critical-step', async () => {
715
+ * return await criticalOperation();
716
+ * }, { retryStrategy: retryPresets.noRetry });
717
+ * ```
718
+ *
719
+ * @public
720
+ */
721
+ const retryPresets = {
722
+ /**
723
+ * Default retry strategy with exponential backoff
724
+ * - 6 total attempts (1 initial + 5 retries)
725
+ * - Initial delay: 5 seconds
726
+ * - Max delay: 60 seconds
727
+ * - Backoff rate: 2x
728
+ * - Jitter: FULL (randomizes delay between 0 and calculated delay)
729
+ * - Total max wait time less than 150 seconds (2:30)
730
+ */
731
+ default: createRetryStrategy({
732
+ maxAttempts: 6,
733
+ initialDelay: { seconds: 5 },
734
+ maxDelay: { seconds: 60 },
735
+ backoffRate: 2,
736
+ jitter: JitterStrategy.FULL,
737
+ }),
738
+ /**
739
+ * No retry strategy - fails immediately on first error
740
+ * - 1 total attempt (no retries)
741
+ */
742
+ noRetry: createRetryStrategy({
743
+ maxAttempts: 1,
744
+ }),
745
+ };
746
+
747
+ /**
748
+ * Error thrown when a step with AT_MOST_ONCE_PER_RETRY semantics was started but interrupted
749
+ * before completion.
750
+ */
751
+ class StepInterruptedError extends Error {
752
+ constructor(_stepId, _stepName) {
753
+ super(`The step execution process was initiated but failed to reach completion due to an interruption.`);
754
+ this.name = "StepInterruptedError";
755
+ }
756
+ }
757
+
758
+ /**
759
+ * Shared constants to avoid circular dependencies
760
+ */
761
+ const OPERATIONS_COMPLETE_EVENT = "allOperationsComplete";
762
+
763
+ /**
764
+ * Base class for all durable operation errors
765
+ */
766
+ class DurableOperationError extends Error {
767
+ cause;
768
+ errorData;
769
+ stackTrace;
770
+ constructor(message, cause, errorData) {
771
+ super(message);
772
+ this.name = this.constructor.name;
773
+ this.cause = cause;
774
+ this.errorData = errorData;
775
+ }
776
+ /**
777
+ * Create DurableOperationError from ErrorObject (for reconstruction during replay)
778
+ */
779
+ static fromErrorObject(errorObject) {
780
+ const cause = new Error(errorObject.ErrorMessage);
781
+ cause.name = errorObject.ErrorType || "Error";
782
+ cause.stack = errorObject.StackTrace?.join("\n");
783
+ // Determine error type and create appropriate instance
784
+ switch (errorObject.ErrorType) {
785
+ case "StepError":
786
+ return new StepError(errorObject.ErrorMessage || "Step failed", cause, errorObject.ErrorData);
787
+ case "CallbackError":
788
+ return new CallbackError(errorObject.ErrorMessage || "Callback failed", cause, errorObject.ErrorData);
789
+ case "InvokeError":
790
+ return new InvokeError(errorObject.ErrorMessage || "Invoke failed", cause, errorObject.ErrorData);
791
+ case "ChildContextError":
792
+ return new ChildContextError(errorObject.ErrorMessage || "Child context failed", cause, errorObject.ErrorData);
793
+ case "WaitForConditionError":
794
+ return new WaitForConditionError(errorObject.ErrorMessage || "Wait for condition failed", cause, errorObject.ErrorData);
795
+ default:
796
+ return new StepError(errorObject.ErrorMessage || "Unknown error", cause, errorObject.ErrorData);
797
+ }
798
+ }
799
+ /**
800
+ * Convert to ErrorObject for serialization
801
+ */
802
+ toErrorObject() {
803
+ return {
804
+ ErrorType: this.errorType,
805
+ ErrorMessage: this.message,
806
+ ErrorData: this.errorData,
807
+ StackTrace: undefined,
808
+ };
809
+ }
810
+ }
811
+ /**
812
+ * Error thrown when a step operation fails
813
+ */
814
+ class StepError extends DurableOperationError {
815
+ errorType = "StepError";
816
+ constructor(message, cause, errorData) {
817
+ super(message || "Step failed", cause, errorData);
818
+ }
819
+ }
820
+ /**
821
+ * Error thrown when a callback operation fails
822
+ */
823
+ class CallbackError extends DurableOperationError {
824
+ errorType = "CallbackError";
825
+ constructor(message, cause, errorData) {
826
+ super(message || "Callback failed", cause, errorData);
827
+ }
828
+ }
829
+ /**
830
+ * Error thrown when an invoke operation fails
831
+ */
832
+ class InvokeError extends DurableOperationError {
833
+ errorType = "InvokeError";
834
+ constructor(message, cause, errorData) {
835
+ super(message || "Invoke failed", cause, errorData);
836
+ }
837
+ }
838
+ /**
839
+ * Error thrown when a child context operation fails
840
+ */
841
+ class ChildContextError extends DurableOperationError {
842
+ errorType = "ChildContextError";
843
+ constructor(message, cause, errorData) {
844
+ super(message || "Child context failed", cause, errorData);
845
+ }
846
+ }
847
+ /**
848
+ * Error thrown when a wait for condition operation fails
849
+ */
850
+ class WaitForConditionError extends DurableOperationError {
851
+ errorType = "WaitForConditionError";
852
+ constructor(message, cause, errorData) {
853
+ super(message || "Wait for condition failed", cause, errorData);
854
+ }
855
+ }
856
+
857
+ /**
858
+ * Default Serdes implementation using JSON.stringify and JSON.parse
859
+ * Wrapped in Promise.resolve() to maintain async interface compatibility
860
+ * Ignores context parameter since it uses inline JSON serialization
861
+ *
862
+ * Note: Uses 'any' type intentionally as this is a generic serializer that must
863
+ * handle arbitrary JavaScript values. JSON.stringify/parse work with any type,
864
+ * and using more restrictive types would break compatibility with the generic
865
+ * Serdes<T> interface when T can be any type.
866
+ *
867
+ * @public
868
+ */
869
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
870
+ const defaultSerdes = {
871
+ serialize: async (
872
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
873
+ value, _context) => value !== undefined ? JSON.stringify(value) : undefined,
874
+ deserialize: async (data, _context) => (data !== undefined ? JSON.parse(data) : undefined),
875
+ };
876
+ /**
877
+ * Creates a Serdes for a specific class that preserves the class type. This implementation
878
+ * is a basic class wrapper and does not support any complex class structures. If you need
879
+ * custom serialization, it is recommended to create your own custom serdes.
880
+ *
881
+ * @param cls - The class constructor (must have no required parameters)
882
+ * @returns A Serdes that maintains the class type during serialization/deserialization
883
+ *
884
+ * @example
885
+ * ```typescript
886
+ * class User {
887
+ * name: string = "";
888
+ * age: number = 0;
889
+ *
890
+ * greet() {
891
+ * return `Hello, ${this.name}`;
892
+ * }
893
+ * }
894
+ *
895
+ * const userSerdes = createClassSerdes(User);
896
+ *
897
+ * // In a durable function:
898
+ * const user = await context.step("create-user", async () => {
899
+ * const u = new User();
900
+ * u.name = "Alice";
901
+ * u.age = 30;
902
+ * return u;
903
+ * }, { serdes: userSerdes });
904
+ *
905
+ * console.log(user.greet()); // "Hello, Alice" - methods are preserved
906
+ * ```
907
+ *
908
+ * Limitations:
909
+ * - Class instances becomes plain objects and loses all class information
910
+ * - Constructor must have no parameters
911
+ * - Constructor side-effects will re-run during deserialization
912
+ * - Private fields (#field) cannot be serialized
913
+ * - Getters/setters are not preserved
914
+ * - Nested class instances lose their prototype
915
+ *
916
+ * For classes with Date properties, use createClassSerdesWithDates instead.
917
+ *
918
+ * @beta
919
+ */
920
+ function createClassSerdes(cls) {
921
+ return {
922
+ serialize: async (value, _context) => value !== undefined ? JSON.stringify(value) : undefined,
923
+ deserialize: async (data, _context) => data !== undefined
924
+ ? Object.assign(new cls(), JSON.parse(data))
925
+ : undefined,
926
+ };
927
+ }
928
+ /**
929
+ * Creates a custom Serdes for a class with special handling for Date properties. This implementation
930
+ * is a basic class wrapper and does not support any complex class structures. If you need
931
+ * custom serialization, it is recommended to create your own custom serdes.
932
+ *
933
+ * @param cls - The class constructor (must have no required parameters)
934
+ * @param dateProps - Array of property paths that should be converted to Date objects (supports nested paths like "metadata.createdAt")
935
+ * @returns A Serdes that maintains the class type and converts specified properties to Date objects
936
+ *
937
+ * @example
938
+ * ```typescript
939
+ * class Article {
940
+ * title: string = "";
941
+ * createdAt: Date = new Date();
942
+ * metadata: {
943
+ * publishedAt: Date;
944
+ * updatedAt: Date;
945
+ * } = {
946
+ * publishedAt: new Date(),
947
+ * updatedAt: new Date()
948
+ * };
949
+ *
950
+ * getAge() {
951
+ * return Date.now() - this.createdAt.getTime();
952
+ * }
953
+ * }
954
+ *
955
+ * const articleSerdes = createClassSerdesWithDates(Article, [
956
+ * "createdAt",
957
+ * "metadata.publishedAt",
958
+ * "metadata.updatedAt"
959
+ * ]);
960
+ *
961
+ * // In a durable function:
962
+ * const article = await context.step("create-article", async () => {
963
+ * const a = new Article();
964
+ * a.title = "My Article";
965
+ * return a;
966
+ * }, { serdes: articleSerdes });
967
+ *
968
+ * console.log(article.getAge()); // Works! Dates are properly restored
969
+ * ```
970
+ *
971
+ * Limitations:
972
+ * - Class instances becomes plain objects and loses all class information
973
+ * - Constructor must have no parameters
974
+ * - Constructor side-effects will re-run during deserialization
975
+ * - Private fields (#field) cannot be serialized
976
+ * - Getters/setters are not preserved
977
+ * - Nested class instances lose their prototype
978
+ *
979
+ * For classes with Date properties, use createClassSerdesWithDates instead.
980
+ *
981
+ * @beta
982
+ */
983
+ function createClassSerdesWithDates(cls, dateProps) {
984
+ return {
985
+ serialize: async (value, _context) => value !== undefined ? JSON.stringify(value) : undefined,
986
+ deserialize: async (data, _context) => {
987
+ if (data === undefined) {
988
+ return undefined;
989
+ }
990
+ const parsed = JSON.parse(data);
991
+ const instance = new cls();
992
+ // Copy all properties from parsed object to the new instance
993
+ Object.assign(instance, parsed);
994
+ // Convert date strings back to Date objects (supports nested paths)
995
+ for (const prop of dateProps) {
996
+ const parts = prop.split(".");
997
+ let obj = instance;
998
+ // Navigate to parent of target property
999
+ for (let i = 0; i < parts.length - 1; i++) {
1000
+ const next = obj[parts[i]];
1001
+ if (!next || typeof next !== "object")
1002
+ break;
1003
+ obj = next;
1004
+ }
1005
+ // Convert to Date if path exists
1006
+ const lastKey = parts[parts.length - 1];
1007
+ if (obj[lastKey]) {
1008
+ obj[lastKey] = new Date(obj[lastKey]);
1009
+ }
1010
+ }
1011
+ return instance;
1012
+ },
1013
+ };
1014
+ }
1015
+
1016
+ /**
1017
+ * Base class for all unrecoverable errors
1018
+ * Any error that inherits from this class indicates a fatal condition
1019
+ */
1020
+ class UnrecoverableError extends Error {
1021
+ originalError;
1022
+ isUnrecoverable = true;
1023
+ constructor(message, originalError) {
1024
+ super(message);
1025
+ this.originalError = originalError;
1026
+ this.name = this.constructor.name;
1027
+ // Preserve the original stack trace if available
1028
+ if (originalError?.stack) {
1029
+ this.stack = `${this.stack}\nCaused by: ${originalError.stack}`;
1030
+ }
1031
+ }
1032
+ }
1033
+ /**
1034
+ * Base class for errors that make the entire execution unrecoverable
1035
+ * These errors indicate that the execution cannot continue and should be terminated completely
1036
+ */
1037
+ class UnrecoverableExecutionError extends UnrecoverableError {
1038
+ isUnrecoverableExecution = true;
1039
+ constructor(message, originalError) {
1040
+ super(`[Unrecoverable Execution] ${message}`, originalError);
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Base class for errors that make the current invocation unrecoverable
1045
+ * These errors indicate that the current Lambda invocation should be terminated,
1046
+ * but the execution might be able to continue with a new invocation
1047
+ */
1048
+ class UnrecoverableInvocationError extends UnrecoverableError {
1049
+ isUnrecoverableInvocation = true;
1050
+ constructor(message, originalError) {
1051
+ super(`[Unrecoverable Invocation] ${message}`, originalError);
1052
+ }
1053
+ }
1054
+ /**
1055
+ * Type guard to check if an error is any kind of unrecoverable error
1056
+ */
1057
+ function isUnrecoverableError(error) {
1058
+ return (error instanceof Error &&
1059
+ "isUnrecoverable" in error &&
1060
+ error.isUnrecoverable === true);
1061
+ }
1062
+ /**
1063
+ * Type guard to check if an error is an unrecoverable invocation error
1064
+ */
1065
+ function isUnrecoverableInvocationError(error) {
1066
+ return (error instanceof Error &&
1067
+ "isUnrecoverableInvocation" in error &&
1068
+ error.isUnrecoverableInvocation === true);
1069
+ }
1070
+
1071
+ /**
1072
+ * Error thrown when serdes operation fails and terminates Lambda invocation
1073
+ * This is used by withDurableExecution to terminate the Lambda when serdes fails
1074
+ */
1075
+ class SerdesFailedError extends UnrecoverableInvocationError {
1076
+ terminationReason = TerminationReason.SERDES_FAILED;
1077
+ constructor(message, originalError) {
1078
+ super(message || "Serdes operation failed", originalError);
1079
+ }
1080
+ }
1081
+ /**
1082
+ * Utility function to safely execute serialization with proper error handling
1083
+ * Instead of throwing unrecoverable errors, this directly terminates execution
1084
+ */
1085
+ async function safeSerialize(serdes, value, stepId, stepName, terminationManager, durableExecutionArn) {
1086
+ try {
1087
+ const context = {
1088
+ entityId: stepId,
1089
+ durableExecutionArn,
1090
+ };
1091
+ return await serdes.serialize(value, context);
1092
+ }
1093
+ catch (error) {
1094
+ const message = `Serialization failed for step ${stepName ? `"${stepName}" ` : ""}(${stepId}): ${error instanceof Error ? error.message : "Unknown serialization error"}`;
1095
+ log("💥", "Serialization failed - terminating execution:", {
1096
+ stepId,
1097
+ stepName,
1098
+ error: error instanceof Error ? error.message : String(error),
1099
+ });
1100
+ terminationManager.terminate({
1101
+ reason: TerminationReason.SERDES_FAILED,
1102
+ message: message,
1103
+ });
1104
+ // Return a never-resolving promise to ensure the execution doesn't continue
1105
+ return new Promise(() => { });
1106
+ }
1107
+ }
1108
+ /**
1109
+ * Utility function to safely execute deserialization with proper error handling
1110
+ * Instead of throwing unrecoverable errors, this directly terminates execution
1111
+ */
1112
+ async function safeDeserialize(serdes, data, stepId, stepName, terminationManager, durableExecutionArn) {
1113
+ try {
1114
+ const context = {
1115
+ entityId: stepId,
1116
+ durableExecutionArn,
1117
+ };
1118
+ return await serdes.deserialize(data, context);
1119
+ }
1120
+ catch (error) {
1121
+ const message = `Deserialization failed for step ${stepName ? `"${stepName}" ` : ""}(${stepId}): ${error instanceof Error ? error.message : "Unknown deserialization error"}`;
1122
+ log("💥", "Deserialization failed - terminating execution:", {
1123
+ stepId,
1124
+ stepName,
1125
+ error: error instanceof Error ? error.message : String(error),
1126
+ });
1127
+ terminationManager.terminate({
1128
+ reason: TerminationReason.SERDES_FAILED,
1129
+ message: message,
1130
+ });
1131
+ // Return a never-resolving promise to ensure the execution doesn't continue
1132
+ return new Promise(() => { });
1133
+ }
1134
+ }
1135
+
1136
+ function isErrorLike(obj) {
1137
+ return (obj instanceof Error ||
1138
+ (obj != null &&
1139
+ typeof obj === "object" &&
1140
+ "message" in obj &&
1141
+ "name" in obj));
1142
+ }
1143
+ function createErrorObjectFromError(error, data) {
1144
+ if (error instanceof DurableOperationError) {
1145
+ // Use DurableOperationError's built-in serialization
1146
+ const errorObject = error.toErrorObject();
1147
+ return errorObject;
1148
+ }
1149
+ if (isErrorLike(error)) {
1150
+ return {
1151
+ ErrorData: data,
1152
+ ErrorMessage: error.message,
1153
+ ErrorType: error.name,
1154
+ StackTrace: undefined,
1155
+ };
1156
+ }
1157
+ return {
1158
+ ErrorData: data,
1159
+ ErrorMessage: "Unknown error",
1160
+ };
1161
+ }
1162
+
1163
+ /**
1164
+ * Error thrown when a checkpoint operation fails due to invocation-level issues
1165
+ * (e.g., 5xx errors, invalid checkpoint token)
1166
+ * This will terminate the current Lambda invocation, but the execution can continue with a new invocation
1167
+ */
1168
+ class CheckpointUnrecoverableInvocationError extends UnrecoverableInvocationError {
1169
+ terminationReason = TerminationReason.CHECKPOINT_FAILED;
1170
+ constructor(message, originalError) {
1171
+ super(message || "Checkpoint operation failed", originalError);
1172
+ }
1173
+ }
1174
+ /**
1175
+ * Error thrown when a checkpoint operation fails due to execution-level issues
1176
+ * (e.g., 4xx errors other than invalid checkpoint token)
1177
+ * This will terminate the entire execution and cannot be recovered
1178
+ */
1179
+ class CheckpointUnrecoverableExecutionError extends UnrecoverableExecutionError {
1180
+ terminationReason = TerminationReason.CHECKPOINT_FAILED;
1181
+ constructor(message, originalError) {
1182
+ super(message || "Checkpoint operation failed", originalError);
1183
+ }
1184
+ }
1185
+
1186
+ const STEP_DATA_UPDATED_EVENT = "stepDataUpdated";
1187
+ class CheckpointManager {
1188
+ durableExecutionArn;
1189
+ stepData;
1190
+ storage;
1191
+ terminationManager;
1192
+ activeOperationsTracker;
1193
+ stepDataEmitter;
1194
+ logger;
1195
+ pendingCompletions;
1196
+ queue = [];
1197
+ isProcessing = false;
1198
+ currentTaskToken;
1199
+ forceCheckpointPromises = [];
1200
+ queueCompletionResolver = null;
1201
+ queueCompletionTimeout = null;
1202
+ MAX_PAYLOAD_SIZE = 750 * 1024; // 750KB in bytes
1203
+ isTerminating = false;
1204
+ static textEncoder = new TextEncoder();
1205
+ constructor(durableExecutionArn, stepData, storage, terminationManager, activeOperationsTracker, initialTaskToken, stepDataEmitter, logger, pendingCompletions) {
1206
+ this.durableExecutionArn = durableExecutionArn;
1207
+ this.stepData = stepData;
1208
+ this.storage = storage;
1209
+ this.terminationManager = terminationManager;
1210
+ this.activeOperationsTracker = activeOperationsTracker;
1211
+ this.stepDataEmitter = stepDataEmitter;
1212
+ this.logger = logger;
1213
+ this.pendingCompletions = pendingCompletions;
1214
+ this.currentTaskToken = initialTaskToken;
1215
+ }
1216
+ setTerminating() {
1217
+ this.isTerminating = true;
1218
+ log("🛑", "Checkpoint manager marked as terminating");
1219
+ }
1220
+ /**
1221
+ * Checks if a step ID or any of its ancestors has a pending completion
1222
+ */
1223
+ hasPendingAncestorCompletion(stepId) {
1224
+ let currentHashedId = hashId(stepId);
1225
+ while (currentHashedId) {
1226
+ if (this.pendingCompletions.has(currentHashedId)) {
1227
+ return true;
1228
+ }
1229
+ const operation = this.stepData[currentHashedId];
1230
+ currentHashedId = operation?.ParentId;
1231
+ }
1232
+ return false;
1233
+ }
1234
+ async forceCheckpoint() {
1235
+ if (this.isTerminating) {
1236
+ log("⚠️", "Force checkpoint skipped - termination in progress");
1237
+ return new Promise(() => { }); // Never resolves during termination
1238
+ }
1239
+ return new Promise((resolve, reject) => {
1240
+ this.forceCheckpointPromises.push({ resolve, reject });
1241
+ if (!this.isProcessing) {
1242
+ setImmediate(() => {
1243
+ this.processQueue();
1244
+ });
1245
+ }
1246
+ });
1247
+ }
1248
+ async waitForQueueCompletion() {
1249
+ if (this.queue.length === 0 && !this.isProcessing) {
1250
+ return;
1251
+ }
1252
+ return new Promise((resolve, reject) => {
1253
+ this.queueCompletionResolver = resolve;
1254
+ // Set a timeout to prevent infinite waiting
1255
+ this.queueCompletionTimeout = setTimeout(() => {
1256
+ this.queueCompletionResolver = null;
1257
+ this.queueCompletionTimeout = null;
1258
+ // Clear the queue since it's taking too long
1259
+ this.clearQueue();
1260
+ reject(new Error("Timeout waiting for checkpoint queue completion"));
1261
+ }, 3000); // 3 second timeout
1262
+ });
1263
+ }
1264
+ clearQueue() {
1265
+ // Silently clear queue - we're terminating so no need to reject promises
1266
+ this.queue = [];
1267
+ this.forceCheckpointPromises = [];
1268
+ // Resolve any waiting queue completion promises since we're clearing
1269
+ this.notifyQueueCompletion();
1270
+ }
1271
+ // Alias for backward compatibility with Checkpoint interface
1272
+ async force() {
1273
+ return this.forceCheckpoint();
1274
+ }
1275
+ async checkpoint(stepId, data) {
1276
+ if (this.isTerminating) {
1277
+ log("⚠️", "Checkpoint skipped - termination in progress:", { stepId });
1278
+ return new Promise(() => { }); // Never resolves during termination
1279
+ }
1280
+ if (this.activeOperationsTracker) {
1281
+ this.activeOperationsTracker.increment();
1282
+ }
1283
+ return new Promise((resolve, reject) => {
1284
+ if (data.Action === OperationAction.SUCCEED ||
1285
+ data.Action === OperationAction.FAIL) {
1286
+ this.pendingCompletions.add(stepId);
1287
+ }
1288
+ const queuedItem = {
1289
+ stepId,
1290
+ data,
1291
+ resolve: () => {
1292
+ if (this.activeOperationsTracker) {
1293
+ this.activeOperationsTracker.decrement();
1294
+ }
1295
+ resolve();
1296
+ },
1297
+ reject: (error) => {
1298
+ if (this.activeOperationsTracker) {
1299
+ this.activeOperationsTracker.decrement();
1300
+ }
1301
+ reject(error);
1302
+ },
1303
+ };
1304
+ this.queue.push(queuedItem);
1305
+ log("📥", "Checkpoint queued:", {
1306
+ stepId,
1307
+ queueLength: this.queue.length,
1308
+ isProcessing: this.isProcessing,
1309
+ });
1310
+ if (!this.isProcessing) {
1311
+ setImmediate(() => {
1312
+ this.processQueue();
1313
+ });
1314
+ }
1315
+ });
1316
+ }
1317
+ hasFinishedAncestor(parentId) {
1318
+ if (!parentId) {
1319
+ return false;
1320
+ }
1321
+ let currentHashedId = hashId(parentId);
1322
+ while (currentHashedId) {
1323
+ const parentOperation = this.stepData[currentHashedId];
1324
+ if (parentOperation?.Status === OperationStatus.SUCCEEDED ||
1325
+ parentOperation?.Status === OperationStatus.FAILED) {
1326
+ return true;
1327
+ }
1328
+ currentHashedId = parentOperation?.ParentId;
1329
+ }
1330
+ return false;
1331
+ }
1332
+ classifyCheckpointError(error) {
1333
+ const originalError = error instanceof Error ? error : new Error(String(error));
1334
+ const awsError = error;
1335
+ const statusCode = awsError.$metadata?.httpStatusCode;
1336
+ const errorName = awsError.name;
1337
+ const errorMessage = awsError.message || originalError.message;
1338
+ log("🔍", "Classifying checkpoint error:", {
1339
+ statusCode,
1340
+ errorName,
1341
+ errorMessage,
1342
+ });
1343
+ if (statusCode &&
1344
+ statusCode >= 400 &&
1345
+ statusCode < 500 &&
1346
+ errorName === "InvalidParameterValueException" &&
1347
+ errorMessage.startsWith("Invalid Checkpoint Token")) {
1348
+ return new CheckpointUnrecoverableInvocationError(`Checkpoint failed: ${errorMessage}`, originalError);
1349
+ }
1350
+ if (statusCode &&
1351
+ statusCode >= 400 &&
1352
+ statusCode < 500 &&
1353
+ statusCode !== 429) {
1354
+ return new CheckpointUnrecoverableExecutionError(`Checkpoint failed: ${errorMessage}`, originalError);
1355
+ }
1356
+ return new CheckpointUnrecoverableInvocationError(`Checkpoint failed: ${errorMessage}`, originalError);
1357
+ }
1358
+ async processQueue() {
1359
+ if (this.isProcessing) {
1360
+ return;
1361
+ }
1362
+ const hasQueuedItems = this.queue.length > 0;
1363
+ const hasForceRequests = this.forceCheckpointPromises.length > 0;
1364
+ if (!hasQueuedItems && !hasForceRequests) {
1365
+ return;
1366
+ }
1367
+ this.isProcessing = true;
1368
+ const batch = [];
1369
+ let skippedCount = 0;
1370
+ const baseSize = this.currentTaskToken.length + 100;
1371
+ let currentSize = baseSize;
1372
+ while (this.queue.length > 0) {
1373
+ const nextItem = this.queue[0];
1374
+ const itemSize = CheckpointManager.textEncoder.encode(JSON.stringify(nextItem)).length;
1375
+ if (currentSize + itemSize > this.MAX_PAYLOAD_SIZE && batch.length > 0) {
1376
+ break;
1377
+ }
1378
+ this.queue.shift();
1379
+ if (this.hasFinishedAncestor(nextItem.data.ParentId)) {
1380
+ log("⚠️", "Checkpoint skipped - ancestor finished:", {
1381
+ stepId: nextItem.stepId,
1382
+ parentId: nextItem.data.ParentId,
1383
+ });
1384
+ skippedCount++;
1385
+ continue;
1386
+ }
1387
+ batch.push(nextItem);
1388
+ currentSize += itemSize;
1389
+ }
1390
+ log("🔄", "Processing checkpoint batch:", {
1391
+ batchSize: batch.length,
1392
+ remainingInQueue: this.queue.length,
1393
+ estimatedSize: currentSize,
1394
+ maxSize: this.MAX_PAYLOAD_SIZE,
1395
+ });
1396
+ try {
1397
+ if (batch.length > 0 || this.forceCheckpointPromises.length > 0) {
1398
+ await this.processBatch(batch);
1399
+ }
1400
+ batch.forEach((item) => {
1401
+ if (item.data.Action === OperationAction.SUCCEED ||
1402
+ item.data.Action === OperationAction.FAIL) {
1403
+ this.pendingCompletions.delete(item.stepId);
1404
+ }
1405
+ item.resolve();
1406
+ });
1407
+ const forcePromises = this.forceCheckpointPromises.splice(0);
1408
+ forcePromises.forEach((promise) => {
1409
+ promise.resolve();
1410
+ });
1411
+ log("✅", "Checkpoint batch processed successfully:", {
1412
+ batchSize: batch.length,
1413
+ skippedCount,
1414
+ forceRequests: forcePromises.length,
1415
+ newTaskToken: this.currentTaskToken,
1416
+ });
1417
+ }
1418
+ catch (error) {
1419
+ log("❌", "Checkpoint batch failed:", {
1420
+ batchSize: batch.length,
1421
+ error,
1422
+ });
1423
+ const checkpointError = this.classifyCheckpointError(error);
1424
+ // Clear remaining queue silently - we're terminating
1425
+ this.clearQueue();
1426
+ this.terminationManager.terminate({
1427
+ reason: TerminationReason.CHECKPOINT_FAILED,
1428
+ message: checkpointError.message,
1429
+ error: checkpointError,
1430
+ });
1431
+ }
1432
+ finally {
1433
+ this.isProcessing = false;
1434
+ if (this.queue.length > 0) {
1435
+ setImmediate(() => {
1436
+ this.processQueue();
1437
+ });
1438
+ }
1439
+ else {
1440
+ // Queue is empty and processing is done - notify all waiting promises
1441
+ this.notifyQueueCompletion();
1442
+ }
1443
+ }
1444
+ }
1445
+ notifyQueueCompletion() {
1446
+ if (this.queueCompletionResolver) {
1447
+ if (this.queueCompletionTimeout) {
1448
+ clearTimeout(this.queueCompletionTimeout);
1449
+ this.queueCompletionTimeout = null;
1450
+ }
1451
+ this.queueCompletionResolver();
1452
+ this.queueCompletionResolver = null;
1453
+ }
1454
+ }
1455
+ async processBatch(batch) {
1456
+ const updates = batch.map((item) => {
1457
+ const hashedStepId = hashId(item.stepId);
1458
+ const update = {
1459
+ Type: item.data.Type || "STEP",
1460
+ Action: item.data.Action || "START",
1461
+ ...item.data,
1462
+ Id: hashedStepId,
1463
+ ...(item.data.ParentId && { ParentId: hashId(item.data.ParentId) }),
1464
+ };
1465
+ return update;
1466
+ });
1467
+ const checkpointData = {
1468
+ DurableExecutionArn: this.durableExecutionArn,
1469
+ CheckpointToken: this.currentTaskToken,
1470
+ Updates: updates,
1471
+ };
1472
+ log("⏺️", "Creating checkpoint batch:", {
1473
+ batchSize: updates.length,
1474
+ checkpointToken: this.currentTaskToken,
1475
+ updates: updates.map((u) => ({
1476
+ Id: u.Id,
1477
+ Action: u.Action,
1478
+ Type: u.Type,
1479
+ })),
1480
+ });
1481
+ const response = await this.storage.checkpoint(checkpointData, this.logger);
1482
+ if (response.CheckpointToken) {
1483
+ this.currentTaskToken = response.CheckpointToken;
1484
+ }
1485
+ if (response.NewExecutionState?.Operations) {
1486
+ this.updateStepDataFromCheckpointResponse(response.NewExecutionState.Operations);
1487
+ }
1488
+ }
1489
+ updateStepDataFromCheckpointResponse(operations) {
1490
+ log("🔄", "Updating stepData from checkpoint response:", {
1491
+ operationCount: operations.length,
1492
+ operationIds: operations.map((op) => op.Id).filter(Boolean),
1493
+ });
1494
+ operations.forEach((operation) => {
1495
+ if (operation.Id) {
1496
+ this.stepData[operation.Id] = operation;
1497
+ log("📝", "Updated stepData entry:", operation);
1498
+ this.stepDataEmitter.emit(STEP_DATA_UPDATED_EVENT, operation.Id);
1499
+ }
1500
+ });
1501
+ log("✅", "StepData update completed:", {
1502
+ totalStepDataEntries: Object.keys(this.stepData).length,
1503
+ });
1504
+ }
1505
+ getQueueStatus() {
1506
+ return {
1507
+ queueLength: this.queue.length,
1508
+ isProcessing: this.isProcessing,
1509
+ };
1510
+ }
1511
+ }
1512
+
1513
+ /**
1514
+ * High-level helper that waits for conditions before continuing execution.
1515
+ * Uses event-driven approach for both operations completion and status changes.
1516
+ */
1517
+ async function waitBeforeContinue(options) {
1518
+ const { checkHasRunningOperations, checkStepStatus, checkTimer, scheduledEndTimestamp, stepId, context, hasRunningOperations, operationsEmitter, checkpoint, onAwaitedChange, } = options;
1519
+ const promises = [];
1520
+ const timers = [];
1521
+ const cleanupFns = [];
1522
+ // Cleanup function to clear all timers and listeners
1523
+ const cleanup = () => {
1524
+ timers.forEach((timer) => clearTimeout(timer));
1525
+ cleanupFns.forEach((fn) => fn());
1526
+ };
1527
+ // Timer promise - resolves when scheduled time is reached
1528
+ if (checkTimer && scheduledEndTimestamp) {
1529
+ const timerPromise = new Promise((resolve) => {
1530
+ const timeLeft = Number(scheduledEndTimestamp) - Date.now();
1531
+ if (timeLeft > 0) {
1532
+ const timer = setTimeout(() => resolve({ reason: "timer", timerExpired: true }), timeLeft);
1533
+ timers.push(timer);
1534
+ }
1535
+ else {
1536
+ resolve({ reason: "timer", timerExpired: true });
1537
+ }
1538
+ });
1539
+ promises.push(timerPromise);
1540
+ }
1541
+ // Operations promise - event-driven approach
1542
+ if (checkHasRunningOperations) {
1543
+ const operationsPromise = new Promise((resolve) => {
1544
+ if (!hasRunningOperations()) {
1545
+ resolve({ reason: "operations" });
1546
+ }
1547
+ else {
1548
+ // Event-driven: listen for completion event
1549
+ const handler = () => {
1550
+ resolve({ reason: "operations" });
1551
+ };
1552
+ operationsEmitter.once(OPERATIONS_COMPLETE_EVENT, handler);
1553
+ cleanupFns.push(() => operationsEmitter.off(OPERATIONS_COMPLETE_EVENT, handler));
1554
+ }
1555
+ });
1556
+ promises.push(operationsPromise);
1557
+ }
1558
+ // Step status promise - event-driven approach
1559
+ if (checkStepStatus) {
1560
+ const originalStatus = context.getStepData(stepId)?.Status;
1561
+ const hashedStepId = hashId(stepId);
1562
+ const stepStatusPromise = new Promise((resolve) => {
1563
+ // Check if status already changed
1564
+ const currentStatus = context.getStepData(stepId)?.Status;
1565
+ if (originalStatus !== currentStatus) {
1566
+ resolve({ reason: "status" });
1567
+ }
1568
+ else {
1569
+ // Event-driven: listen for step data updates
1570
+ const handler = (updatedStepId) => {
1571
+ if (updatedStepId === hashedStepId) {
1572
+ const newStatus = context.getStepData(stepId)?.Status;
1573
+ if (originalStatus !== newStatus) {
1574
+ resolve({ reason: "status" });
1575
+ }
1576
+ }
1577
+ };
1578
+ operationsEmitter.on(STEP_DATA_UPDATED_EVENT, handler);
1579
+ cleanupFns.push(() => operationsEmitter.off(STEP_DATA_UPDATED_EVENT, handler));
1580
+ }
1581
+ });
1582
+ promises.push(stepStatusPromise);
1583
+ }
1584
+ // Awaited change promise - resolves when the callback we set is invoked
1585
+ // Note: This is safe from race conditions because waitBeforeContinue is called
1586
+ // during Phase 1 execution (inside stepHandler), which happens BEFORE the user
1587
+ // can await the DurablePromise. The callback is registered before it can be invoked.
1588
+ if (onAwaitedChange) {
1589
+ const awaitedChangePromise = new Promise((resolve) => {
1590
+ // Register a callback that will be invoked when the promise is awaited
1591
+ onAwaitedChange(() => {
1592
+ resolve({ reason: "status" });
1593
+ });
1594
+ });
1595
+ promises.push(awaitedChangePromise);
1596
+ }
1597
+ // If no conditions provided, return immediately
1598
+ if (promises.length === 0) {
1599
+ return { reason: "timeout" };
1600
+ }
1601
+ // Wait for any condition to be met, then cleanup timers and listeners
1602
+ const result = await Promise.race(promises);
1603
+ cleanup();
1604
+ // If timer expired, force checkpoint to get fresh data from API
1605
+ if (result.reason === "timer" && result.timerExpired && checkpoint) {
1606
+ if (checkpoint.force) {
1607
+ await checkpoint.force();
1608
+ }
1609
+ else if (checkpoint.forceCheckpoint) {
1610
+ await checkpoint.forceCheckpoint();
1611
+ }
1612
+ }
1613
+ return result;
1614
+ }
1615
+
1616
+ /**
1617
+ * Error thrown when non-deterministic code is detected during replay
1618
+ */
1619
+ class NonDeterministicExecutionError extends UnrecoverableExecutionError {
1620
+ terminationReason = TerminationReason.CUSTOM;
1621
+ constructor(message) {
1622
+ super(message);
1623
+ this.name = "NonDeterministicExecutionError";
1624
+ }
1625
+ }
1626
+
1627
+ const validateReplayConsistency = (stepId, currentOperation, checkpointData, context) => {
1628
+ // Skip validation if no checkpoint data exists or if Type is undefined (first execution)
1629
+ if (!checkpointData || !checkpointData.Type) {
1630
+ return;
1631
+ }
1632
+ // Validate operation type
1633
+ if (checkpointData.Type !== currentOperation.type) {
1634
+ const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation type mismatch for step "${stepId}". ` +
1635
+ `Expected type "${checkpointData.Type}", but got "${currentOperation.type}". ` +
1636
+ `This indicates non-deterministic control flow in your workflow code.`);
1637
+ terminateForUnrecoverableError(context, error, stepId);
1638
+ }
1639
+ // Validate operation name (including undefined)
1640
+ if (checkpointData.Name !== currentOperation.name) {
1641
+ const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation name mismatch for step "${stepId}". ` +
1642
+ `Expected name "${checkpointData.Name ?? "undefined"}", but got "${currentOperation.name ?? "undefined"}". ` +
1643
+ `This indicates non-deterministic control flow in your workflow code.`);
1644
+ terminateForUnrecoverableError(context, error, stepId);
1645
+ }
1646
+ // Validate operation subtype
1647
+ if (checkpointData.SubType !== currentOperation.subType) {
1648
+ const error = new NonDeterministicExecutionError(`Non-deterministic execution detected: Operation subtype mismatch for step "${stepId}". ` +
1649
+ `Expected subtype "${checkpointData.SubType}", but got "${currentOperation.subType}". ` +
1650
+ `This indicates non-deterministic control flow in your workflow code.`);
1651
+ terminateForUnrecoverableError(context, error, stepId);
1652
+ }
1653
+ };
1654
+
1655
+ // Special symbol to indicate that the main loop should continue
1656
+ const CONTINUE_MAIN_LOOP$1 = Symbol("CONTINUE_MAIN_LOOP");
1657
+ const waitForContinuation$1 = async (context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, onAwaitedChange) => {
1658
+ const stepData = context.getStepData(stepId);
1659
+ // Check if there are any ongoing operations
1660
+ if (!hasRunningOperations()) {
1661
+ // No ongoing operations - safe to terminate
1662
+ return terminate(context, TerminationReason.RETRY_SCHEDULED, `Retry scheduled for ${name || stepId}`);
1663
+ }
1664
+ // There are ongoing operations - wait before continuing
1665
+ await waitBeforeContinue({
1666
+ checkHasRunningOperations: true,
1667
+ checkStepStatus: true,
1668
+ checkTimer: true,
1669
+ scheduledEndTimestamp: stepData?.StepDetails?.NextAttemptTimestamp,
1670
+ stepId,
1671
+ context,
1672
+ hasRunningOperations,
1673
+ operationsEmitter: getOperationsEmitter(),
1674
+ checkpoint,
1675
+ onAwaitedChange,
1676
+ });
1677
+ // Return to let the main loop re-evaluate step status
1678
+ };
1679
+ /**
1680
+ * Creates a step handler for executing durable steps with two-phase execution.
1681
+ */
1682
+ const createStepHandler = (context, checkpoint, parentContext, createStepId, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId) => {
1683
+ return (nameOrFn, fnOrOptions, maybeOptions) => {
1684
+ let name;
1685
+ let fn;
1686
+ let options;
1687
+ if (typeof nameOrFn === "string" || nameOrFn === undefined) {
1688
+ name = nameOrFn;
1689
+ fn = fnOrOptions;
1690
+ options = maybeOptions;
1691
+ }
1692
+ else {
1693
+ fn = nameOrFn;
1694
+ options = fnOrOptions;
1695
+ }
1696
+ const stepId = createStepId();
1697
+ log("▶️", "Running step:", { stepId, name, options });
1698
+ // Two-phase execution: Phase 1 starts immediately, Phase 2 returns result when awaited
1699
+ let isAwaited = false;
1700
+ let waitingCallback;
1701
+ const setWaitingCallback = (cb) => {
1702
+ waitingCallback = cb;
1703
+ };
1704
+ // Phase 1: Start execution immediately and capture result/error
1705
+ const phase1Promise = (async () => {
1706
+ // Main step logic - can be re-executed if step status changes
1707
+ while (true) {
1708
+ try {
1709
+ const stepData = context.getStepData(stepId);
1710
+ // Validate replay consistency
1711
+ validateReplayConsistency(stepId, {
1712
+ type: OperationType.STEP,
1713
+ name,
1714
+ subType: OperationSubType.STEP,
1715
+ }, stepData, context);
1716
+ if (stepData?.Status === OperationStatus.SUCCEEDED) {
1717
+ return await handleCompletedStep(context, stepId, name, options?.serdes);
1718
+ }
1719
+ if (stepData?.Status === OperationStatus.FAILED) {
1720
+ // Return an async rejected promise to ensure it's handled asynchronously
1721
+ return (async () => {
1722
+ // Reconstruct the original error from stored ErrorObject
1723
+ if (stepData.StepDetails?.Error) {
1724
+ throw DurableOperationError.fromErrorObject(stepData.StepDetails.Error);
1725
+ }
1726
+ else {
1727
+ // Fallback for legacy data without Error field
1728
+ const errorMessage = stepData?.StepDetails?.Result;
1729
+ throw new StepError(errorMessage || "Unknown error");
1730
+ }
1731
+ })();
1732
+ }
1733
+ // If PENDING, wait for timer to complete
1734
+ if (stepData?.Status === OperationStatus.PENDING) {
1735
+ await waitForContinuation$1(context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, isAwaited ? undefined : setWaitingCallback);
1736
+ continue; // Re-evaluate step status after waiting
1737
+ }
1738
+ // Check for interrupted step with AT_MOST_ONCE_PER_RETRY semantics
1739
+ if (stepData?.Status === OperationStatus.STARTED) {
1740
+ const semantics = options?.semantics || StepSemantics.AtLeastOncePerRetry;
1741
+ if (semantics === StepSemantics.AtMostOncePerRetry) {
1742
+ log("⚠️", "Step was interrupted during execution:", {
1743
+ stepId,
1744
+ name,
1745
+ });
1746
+ const error = new StepInterruptedError(stepId, name);
1747
+ // Handle the interrupted step as a failure
1748
+ const currentAttempt = (stepData?.StepDetails?.Attempt || 0) + 1;
1749
+ let retryDecision;
1750
+ if (options?.retryStrategy !== undefined) {
1751
+ retryDecision = options.retryStrategy(error, currentAttempt);
1752
+ }
1753
+ else {
1754
+ retryDecision = retryPresets.default(error, currentAttempt);
1755
+ }
1756
+ log("⚠️", "Should Retry Interrupted Step:", {
1757
+ stepId,
1758
+ name,
1759
+ currentAttempt,
1760
+ shouldRetry: retryDecision.shouldRetry,
1761
+ delayInSeconds: retryDecision.shouldRetry
1762
+ ? retryDecision.delay
1763
+ ? durationToSeconds(retryDecision.delay)
1764
+ : undefined
1765
+ : undefined,
1766
+ });
1767
+ if (!retryDecision.shouldRetry) {
1768
+ // No retry, mark as failed
1769
+ await checkpoint.checkpoint(stepId, {
1770
+ Id: stepId,
1771
+ ParentId: parentId,
1772
+ Action: OperationAction.FAIL,
1773
+ SubType: OperationSubType.STEP,
1774
+ Type: OperationType.STEP,
1775
+ Error: createErrorObjectFromError(error),
1776
+ Name: name,
1777
+ });
1778
+ // Reconstruct error from ErrorObject for deterministic behavior
1779
+ const errorObject = createErrorObjectFromError(error);
1780
+ throw DurableOperationError.fromErrorObject(errorObject);
1781
+ }
1782
+ else {
1783
+ // Retry
1784
+ await checkpoint.checkpoint(stepId, {
1785
+ Id: stepId,
1786
+ ParentId: parentId,
1787
+ Action: OperationAction.RETRY,
1788
+ SubType: OperationSubType.STEP,
1789
+ Type: OperationType.STEP,
1790
+ Error: createErrorObjectFromError(error),
1791
+ Name: name,
1792
+ StepOptions: {
1793
+ NextAttemptDelaySeconds: retryDecision.delay
1794
+ ? durationToSeconds(retryDecision.delay)
1795
+ : 1,
1796
+ },
1797
+ });
1798
+ await waitForContinuation$1(context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, isAwaited ? undefined : setWaitingCallback);
1799
+ continue; // Re-evaluate step status after waiting
1800
+ }
1801
+ }
1802
+ }
1803
+ // Execute step function for READY, STARTED (AtLeastOncePerRetry), or first time (undefined)
1804
+ const result = await executeStep(context, checkpoint, stepId, name, fn, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, options, isAwaited ? undefined : setWaitingCallback);
1805
+ // If executeStep signals to continue the main loop, do so
1806
+ if (result === CONTINUE_MAIN_LOOP$1) {
1807
+ continue;
1808
+ }
1809
+ return result;
1810
+ }
1811
+ catch (error) {
1812
+ // Preserve DurableOperationError instances (StepInterruptedError is handled specifically where it's thrown)
1813
+ if (error instanceof DurableOperationError) {
1814
+ throw error;
1815
+ }
1816
+ // For any other error from executeStep, wrap it in StepError for consistency
1817
+ throw new StepError(error instanceof Error ? error.message : "Step failed", error instanceof Error ? error : undefined);
1818
+ }
1819
+ }
1820
+ })();
1821
+ // Attach catch handler to prevent unhandled promise rejections
1822
+ // The error will still be thrown when the DurablePromise is awaited
1823
+ phase1Promise.catch(() => { });
1824
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
1825
+ return new DurablePromise(async () => {
1826
+ // When promise is awaited, mark as awaited and invoke waiting callback
1827
+ isAwaited = true;
1828
+ if (waitingCallback) {
1829
+ waitingCallback();
1830
+ }
1831
+ return await phase1Promise;
1832
+ });
1833
+ };
1834
+ };
1835
+ const handleCompletedStep = async (context, stepId, stepName, serdes = defaultSerdes) => {
1836
+ log("⏭️", "Step already finished, returning cached result:", { stepId });
1837
+ const stepData = context.getStepData(stepId);
1838
+ const result = stepData?.StepDetails?.Result;
1839
+ return await safeDeserialize(serdes, result, stepId, stepName, context.terminationManager, context.durableExecutionArn);
1840
+ };
1841
+ const executeStep = async (context, checkpoint, stepId, name, fn, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, options, onAwaitedChange) => {
1842
+ // Determine step semantics (default to AT_LEAST_ONCE_PER_RETRY if not specified)
1843
+ const semantics = options?.semantics || StepSemantics.AtLeastOncePerRetry;
1844
+ const serdes = options?.serdes || defaultSerdes;
1845
+ // Checkpoint at start for both semantics (only if not already started)
1846
+ const stepData = context.getStepData(stepId);
1847
+ if (stepData?.Status !== OperationStatus.STARTED) {
1848
+ if (semantics === StepSemantics.AtMostOncePerRetry) {
1849
+ // Wait for checkpoint to complete
1850
+ await checkpoint.checkpoint(stepId, {
1851
+ Id: stepId,
1852
+ ParentId: parentId,
1853
+ Action: OperationAction.START,
1854
+ SubType: OperationSubType.STEP,
1855
+ Type: OperationType.STEP,
1856
+ Name: name,
1857
+ });
1858
+ }
1859
+ else {
1860
+ // Fire and forget for AtLeastOncePerRetry
1861
+ checkpoint.checkpoint(stepId, {
1862
+ Id: stepId,
1863
+ ParentId: parentId,
1864
+ Action: OperationAction.START,
1865
+ SubType: OperationSubType.STEP,
1866
+ Type: OperationType.STEP,
1867
+ Name: name,
1868
+ });
1869
+ }
1870
+ }
1871
+ try {
1872
+ // Get current attempt number for logger enrichment
1873
+ const stepData = context.getStepData(stepId);
1874
+ const currentAttempt = stepData?.StepDetails?.Attempt || 0;
1875
+ // Create step context with enriched logger
1876
+ const stepContext = {
1877
+ logger,
1878
+ };
1879
+ // Execute the step function with stepContext
1880
+ addRunningOperation(stepId);
1881
+ let result;
1882
+ try {
1883
+ result = await runWithContext(stepId, parentId, () => fn(stepContext),
1884
+ // The attempt that is running is the attempt from the step data (previous step attempt) + 1
1885
+ currentAttempt + 1,
1886
+ // Alwasy in execution mode when running step operations
1887
+ DurableExecutionMode.ExecutionMode);
1888
+ }
1889
+ finally {
1890
+ removeRunningOperation(stepId);
1891
+ }
1892
+ // Serialize the result for consistency
1893
+ const serializedResult = await safeSerialize(serdes, result, stepId, name, context.terminationManager, context.durableExecutionArn);
1894
+ // Always checkpoint on completion
1895
+ await checkpoint.checkpoint(stepId, {
1896
+ Id: stepId,
1897
+ ParentId: parentId,
1898
+ Action: OperationAction.SUCCEED,
1899
+ SubType: OperationSubType.STEP,
1900
+ Type: OperationType.STEP,
1901
+ Payload: serializedResult,
1902
+ Name: name,
1903
+ });
1904
+ log("✅", "Step completed successfully:", {
1905
+ stepId,
1906
+ name,
1907
+ result,
1908
+ semantics,
1909
+ });
1910
+ // Deserialize the result for consistency with replay behavior
1911
+ return await safeDeserialize(serdes, serializedResult, stepId, name, context.terminationManager, context.durableExecutionArn);
1912
+ }
1913
+ catch (error) {
1914
+ log("❌", "Step failed:", {
1915
+ stepId,
1916
+ name,
1917
+ error,
1918
+ semantics,
1919
+ });
1920
+ // Handle unrecoverable errors - these should not go through retry logic
1921
+ if (isUnrecoverableError(error)) {
1922
+ log("💥", "Unrecoverable error detected:", {
1923
+ stepId,
1924
+ name,
1925
+ error: error.message,
1926
+ });
1927
+ return terminateForUnrecoverableError(context, error, name || stepId);
1928
+ }
1929
+ const stepData = context.getStepData(stepId);
1930
+ const currentAttempt = (stepData?.StepDetails?.Attempt || 0) + 1;
1931
+ let retryDecision;
1932
+ if (options?.retryStrategy !== undefined) {
1933
+ // Use provided retry configuration
1934
+ retryDecision = options.retryStrategy(error instanceof Error ? error : new Error("Unknown Error"), currentAttempt);
1935
+ }
1936
+ else {
1937
+ // Use default retry preset if no config provided
1938
+ retryDecision = retryPresets.default(error instanceof Error ? error : new Error("Unknown Error"), currentAttempt);
1939
+ }
1940
+ log("⚠️", "Should Retry:", {
1941
+ stepId,
1942
+ name,
1943
+ currentAttempt,
1944
+ shouldRetry: retryDecision.shouldRetry,
1945
+ delayInSeconds: retryDecision.shouldRetry
1946
+ ? retryDecision.delay
1947
+ ? durationToSeconds(retryDecision.delay)
1948
+ : undefined
1949
+ : undefined,
1950
+ semantics,
1951
+ });
1952
+ if (!retryDecision.shouldRetry) {
1953
+ // No retry
1954
+ await checkpoint.checkpoint(stepId, {
1955
+ Id: stepId,
1956
+ ParentId: parentId,
1957
+ Action: OperationAction.FAIL,
1958
+ SubType: OperationSubType.STEP,
1959
+ Type: OperationType.STEP,
1960
+ Error: createErrorObjectFromError(error),
1961
+ Name: name,
1962
+ });
1963
+ // Reconstruct error from ErrorObject for deterministic behavior
1964
+ const errorObject = createErrorObjectFromError(error);
1965
+ throw DurableOperationError.fromErrorObject(errorObject);
1966
+ }
1967
+ else {
1968
+ // Retry
1969
+ await checkpoint.checkpoint(stepId, {
1970
+ Id: stepId,
1971
+ ParentId: parentId,
1972
+ Action: OperationAction.RETRY,
1973
+ SubType: OperationSubType.STEP,
1974
+ Type: OperationType.STEP,
1975
+ Error: createErrorObjectFromError(error),
1976
+ Name: name,
1977
+ StepOptions: {
1978
+ NextAttemptDelaySeconds: retryDecision.delay
1979
+ ? durationToSeconds(retryDecision.delay)
1980
+ : 1,
1981
+ },
1982
+ });
1983
+ // Wait for continuation and signal main loop to continue
1984
+ await waitForContinuation$1(context, stepId, name, hasRunningOperations, getOperationsEmitter, checkpoint, onAwaitedChange);
1985
+ return CONTINUE_MAIN_LOOP$1;
1986
+ }
1987
+ }
1988
+ };
1989
+
1990
+ const createInvokeHandler = (context, checkpoint, createStepId, hasRunningOperations, getOperationsEmitter, parentId, checkAndUpdateReplayMode) => {
1991
+ function invokeHandler(nameOrFuncId, funcIdOrInput, inputOrConfig, maybeConfig) {
1992
+ const isNameFirst = typeof funcIdOrInput === "string";
1993
+ const name = isNameFirst ? nameOrFuncId : undefined;
1994
+ const funcId = isNameFirst ? funcIdOrInput : nameOrFuncId;
1995
+ const input = isNameFirst
1996
+ ? inputOrConfig
1997
+ : funcIdOrInput;
1998
+ const config = isNameFirst
1999
+ ? maybeConfig
2000
+ : inputOrConfig;
2001
+ const stepId = createStepId();
2002
+ // Phase 1: Only checkpoint if needed, don't execute full logic
2003
+ const startInvokeOperation = async () => {
2004
+ log("🔗", `Invoke ${name || funcId} (${stepId}) - phase 1`);
2005
+ // Check initial step data for replay consistency validation
2006
+ const initialStepData = context.getStepData(stepId);
2007
+ // Validate replay consistency once before any execution
2008
+ validateReplayConsistency(stepId, {
2009
+ type: OperationType.CHAINED_INVOKE,
2010
+ name,
2011
+ subType: OperationSubType.CHAINED_INVOKE,
2012
+ }, initialStepData, context);
2013
+ // If stepData already exists, phase 1 has nothing to do
2014
+ if (initialStepData) {
2015
+ log("⏸️", `Invoke ${name || funcId} already exists (phase 1)`);
2016
+ return;
2017
+ }
2018
+ // No stepData exists - need to start the invoke operation
2019
+ // Serialize the input payload
2020
+ const serializedPayload = await safeSerialize(config?.payloadSerdes || defaultSerdes, input, stepId, name, context.terminationManager, context.durableExecutionArn);
2021
+ // Create checkpoint for the invoke operation
2022
+ await checkpoint.checkpoint(stepId, {
2023
+ Id: stepId,
2024
+ ParentId: parentId,
2025
+ Action: OperationAction.START,
2026
+ SubType: OperationSubType.CHAINED_INVOKE,
2027
+ Type: OperationType.CHAINED_INVOKE,
2028
+ Name: name,
2029
+ Payload: serializedPayload,
2030
+ ChainedInvokeOptions: {
2031
+ FunctionName: funcId,
2032
+ },
2033
+ });
2034
+ log("🚀", `Invoke ${name || funcId} started (phase 1)`);
2035
+ };
2036
+ // Phase 2: Execute full logic including waiting and termination
2037
+ const continueInvokeOperation = async () => {
2038
+ log("🔗", `Invoke ${name || funcId} (${stepId}) - phase 2`);
2039
+ // Main invoke logic - can be re-executed if step status changes
2040
+ while (true) {
2041
+ // Check if we have existing step data
2042
+ const stepData = context.getStepData(stepId);
2043
+ if (stepData?.Status === OperationStatus.SUCCEEDED) {
2044
+ // Return cached result - no need to check for errors in successful operations
2045
+ const invokeDetails = stepData.ChainedInvokeDetails;
2046
+ checkAndUpdateReplayMode?.();
2047
+ return await safeDeserialize(config?.resultSerdes || defaultSerdes, invokeDetails?.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
2048
+ }
2049
+ if (stepData?.Status === OperationStatus.FAILED ||
2050
+ stepData?.Status === OperationStatus.TIMED_OUT ||
2051
+ stepData?.Status === OperationStatus.STOPPED) {
2052
+ // Operation failed, return async rejected promise
2053
+ const invokeDetails = stepData.ChainedInvokeDetails;
2054
+ return (async () => {
2055
+ if (invokeDetails?.Error) {
2056
+ throw new InvokeError(invokeDetails.Error.ErrorMessage || "Invoke failed", invokeDetails.Error.ErrorMessage
2057
+ ? new Error(invokeDetails.Error.ErrorMessage)
2058
+ : undefined, invokeDetails.Error.ErrorData);
2059
+ }
2060
+ else {
2061
+ throw new InvokeError("Invoke failed");
2062
+ }
2063
+ })();
2064
+ }
2065
+ if (stepData?.Status === OperationStatus.STARTED) {
2066
+ // Operation is still running
2067
+ if (hasRunningOperations()) {
2068
+ // Phase 2: Wait for other operations
2069
+ log("⏳", `Invoke ${name || funcId} still in progress, waiting for other operations`);
2070
+ await waitBeforeContinue({
2071
+ checkHasRunningOperations: true,
2072
+ checkStepStatus: true,
2073
+ checkTimer: false,
2074
+ stepId,
2075
+ context,
2076
+ hasRunningOperations,
2077
+ operationsEmitter: getOperationsEmitter(),
2078
+ });
2079
+ continue; // Re-evaluate status after waiting
2080
+ }
2081
+ // No other operations running - terminate
2082
+ log("⏳", `Invoke ${name || funcId} still in progress, terminating`);
2083
+ return terminate(context, TerminationReason.OPERATION_TERMINATED, stepId);
2084
+ }
2085
+ // If stepData exists but has an unexpected status, break to avoid infinite loop
2086
+ if (stepData && stepData.Status !== undefined) {
2087
+ throw new InvokeError(`Unexpected operation status: ${stepData.Status}`);
2088
+ }
2089
+ // This should not happen in phase 2 since phase 1 creates stepData
2090
+ throw new InvokeError("No step data found in phase 2 - this should not happen");
2091
+ }
2092
+ };
2093
+ // Create a promise that tracks phase 1 completion
2094
+ const startInvokePromise = startInvokeOperation()
2095
+ .then(() => {
2096
+ log("✅", "Invoke phase 1 complete:", { stepId, name: name || funcId });
2097
+ })
2098
+ .catch((error) => {
2099
+ log("❌", "Invoke phase 1 error:", { stepId, error: error.message });
2100
+ throw error; // Re-throw to fail phase 1
2101
+ });
2102
+ // Attach catch handler to prevent unhandled promise rejections
2103
+ // The error will still be thrown when the DurablePromise is awaited
2104
+ startInvokePromise.catch(() => { });
2105
+ // Return DurablePromise that will execute phase 2 when awaited
2106
+ return new DurablePromise(async () => {
2107
+ // Wait for phase 1 to complete first
2108
+ await startInvokePromise;
2109
+ // Then execute phase 2
2110
+ return await continueInvokeOperation();
2111
+ });
2112
+ }
2113
+ return invokeHandler;
2114
+ };
2115
+
2116
+ // Checkpoint size limit in bytes (256KB)
2117
+ const CHECKPOINT_SIZE_LIMIT = 256 * 1024;
2118
+ const determineChildReplayMode = (context, stepId) => {
2119
+ const stepData = context.getStepData(stepId);
2120
+ if (!stepData) {
2121
+ return DurableExecutionMode.ExecutionMode;
2122
+ }
2123
+ if (stepData.Status === OperationStatus.SUCCEEDED &&
2124
+ stepData.ContextDetails?.ReplayChildren) {
2125
+ return DurableExecutionMode.ReplaySucceededContext;
2126
+ }
2127
+ if (stepData.Status === OperationStatus.SUCCEEDED ||
2128
+ stepData.Status === OperationStatus.FAILED) {
2129
+ return DurableExecutionMode.ReplayMode;
2130
+ }
2131
+ return DurableExecutionMode.ExecutionMode;
2132
+ };
2133
+ const createRunInChildContextHandler = (context, checkpoint, parentContext, createStepId, getParentLogger, createChildContext, parentId) => {
2134
+ return (nameOrFn, fnOrOptions, maybeOptions) => {
2135
+ let name;
2136
+ let fn;
2137
+ let options;
2138
+ if (typeof nameOrFn === "string" || nameOrFn === undefined) {
2139
+ name = nameOrFn;
2140
+ fn = fnOrOptions;
2141
+ options = maybeOptions;
2142
+ }
2143
+ else {
2144
+ fn = nameOrFn;
2145
+ options = fnOrOptions;
2146
+ }
2147
+ const entityId = createStepId();
2148
+ log("🔄", "Running child context:", {
2149
+ entityId,
2150
+ name,
2151
+ });
2152
+ const stepData = context.getStepData(entityId);
2153
+ // Validate replay consistency
2154
+ validateReplayConsistency(entityId, {
2155
+ type: OperationType.CONTEXT,
2156
+ name,
2157
+ subType: options?.subType ||
2158
+ OperationSubType.RUN_IN_CHILD_CONTEXT,
2159
+ }, stepData, context);
2160
+ // Two-phase execution: Phase 1 starts immediately, Phase 2 returns result when awaited
2161
+ let phase1Result;
2162
+ let phase1Error;
2163
+ // Phase 1: Start execution immediately and capture result/error
2164
+ const phase1Promise = (async () => {
2165
+ const currentStepData = context.getStepData(entityId);
2166
+ // If already completed, return cached result
2167
+ if (currentStepData?.Status === OperationStatus.SUCCEEDED ||
2168
+ currentStepData?.Status === OperationStatus.FAILED) {
2169
+ return handleCompletedChildContext(context, parentContext, entityId, name, fn, options, getParentLogger, createChildContext);
2170
+ }
2171
+ // Execute if not completed
2172
+ return executeChildContext(context, checkpoint, parentContext, entityId, name, fn, options, getParentLogger, createChildContext, parentId);
2173
+ })()
2174
+ .then((result) => {
2175
+ phase1Result = result;
2176
+ })
2177
+ .catch((error) => {
2178
+ phase1Error = error;
2179
+ });
2180
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
2181
+ return new DurablePromise(async () => {
2182
+ await phase1Promise;
2183
+ if (phase1Error !== undefined) {
2184
+ throw phase1Error;
2185
+ }
2186
+ return phase1Result;
2187
+ });
2188
+ };
2189
+ };
2190
+ const handleCompletedChildContext = async (context, parentContext, entityId, stepName, fn, options, getParentLogger, createChildContext) => {
2191
+ const serdes = options?.serdes || defaultSerdes;
2192
+ const stepData = context.getStepData(entityId);
2193
+ const result = stepData?.ContextDetails?.Result;
2194
+ // Handle failed child context
2195
+ if (stepData?.Status === OperationStatus.FAILED) {
2196
+ if (stepData.ContextDetails?.Error) {
2197
+ const originalError = DurableOperationError.fromErrorObject(stepData.ContextDetails.Error);
2198
+ throw new ChildContextError(originalError.message, originalError);
2199
+ }
2200
+ else {
2201
+ throw new ChildContextError("Child context failed");
2202
+ }
2203
+ }
2204
+ // Check if we need to replay children due to large payload
2205
+ if (stepData?.ContextDetails?.ReplayChildren) {
2206
+ log("🔄", "ReplayChildren mode: Re-executing child context due to large payload:", { entityId, stepName });
2207
+ // Re-execute the child context to reconstruct the result
2208
+ const durableChildContext = createChildContext(context, parentContext, DurableExecutionMode.ReplaySucceededContext, getParentLogger(), entityId, undefined, entityId);
2209
+ return await runWithContext(entityId, entityId, () => fn(durableChildContext));
2210
+ }
2211
+ log("⏭️", "Child context already finished, returning cached result:", {
2212
+ entityId,
2213
+ });
2214
+ return await safeDeserialize(serdes, result, entityId, stepName, context.terminationManager, context.durableExecutionArn);
2215
+ };
2216
+ const executeChildContext = async (context, checkpoint, parentContext, entityId, name, fn, options, getParentLogger, createChildContext, parentId) => {
2217
+ const serdes = options?.serdes || defaultSerdes;
2218
+ // Checkpoint at start if not already started (fire-and-forget for performance)
2219
+ if (context.getStepData(entityId) === undefined) {
2220
+ const subType = options?.subType || OperationSubType.RUN_IN_CHILD_CONTEXT;
2221
+ checkpoint.checkpoint(entityId, {
2222
+ Id: entityId,
2223
+ ParentId: parentId,
2224
+ Action: OperationAction.START,
2225
+ SubType: subType,
2226
+ Type: OperationType.CONTEXT,
2227
+ Name: name,
2228
+ });
2229
+ }
2230
+ const childReplayMode = determineChildReplayMode(context, entityId);
2231
+ // Create a child context with the entity ID as prefix
2232
+ const durableChildContext = createChildContext(context, parentContext, childReplayMode, getParentLogger(), entityId, undefined, entityId);
2233
+ try {
2234
+ // Execute the child context function with context tracking
2235
+ const result = await runWithContext(entityId, parentId, () => fn(durableChildContext), undefined, childReplayMode);
2236
+ // Serialize the result for consistency
2237
+ const serializedResult = await safeSerialize(serdes, result, entityId, name, context.terminationManager, context.durableExecutionArn);
2238
+ // Check if payload is too large for adaptive mode
2239
+ let payloadToCheckpoint = serializedResult;
2240
+ let replayChildren = false;
2241
+ if (serializedResult &&
2242
+ Buffer.byteLength(serializedResult, "utf8") > CHECKPOINT_SIZE_LIMIT) {
2243
+ replayChildren = true;
2244
+ // Use summary generator if provided, otherwise use empty string
2245
+ if (options?.summaryGenerator) {
2246
+ payloadToCheckpoint = options.summaryGenerator(result);
2247
+ }
2248
+ else {
2249
+ payloadToCheckpoint = "";
2250
+ }
2251
+ log("📦", "Large payload detected, using ReplayChildren mode:", {
2252
+ entityId,
2253
+ name,
2254
+ payloadSize: Buffer.byteLength(serializedResult, "utf8"),
2255
+ limit: CHECKPOINT_SIZE_LIMIT,
2256
+ });
2257
+ }
2258
+ const subType = options?.subType || OperationSubType.RUN_IN_CHILD_CONTEXT;
2259
+ await checkpoint.checkpoint(entityId, {
2260
+ Id: entityId,
2261
+ ParentId: parentId,
2262
+ Action: OperationAction.SUCCEED,
2263
+ SubType: subType,
2264
+ Type: OperationType.CONTEXT,
2265
+ Payload: payloadToCheckpoint,
2266
+ ContextOptions: replayChildren ? { ReplayChildren: true } : undefined,
2267
+ Name: name,
2268
+ });
2269
+ log("✅", "Child context completed successfully:", {
2270
+ entityId,
2271
+ name,
2272
+ });
2273
+ return result;
2274
+ }
2275
+ catch (error) {
2276
+ log("❌", "Child context failed:", {
2277
+ entityId,
2278
+ name,
2279
+ error,
2280
+ });
2281
+ // Always checkpoint failures
2282
+ const subType = options?.subType || OperationSubType.RUN_IN_CHILD_CONTEXT;
2283
+ await checkpoint.checkpoint(entityId, {
2284
+ Id: entityId,
2285
+ ParentId: parentId,
2286
+ Action: OperationAction.FAIL,
2287
+ SubType: subType,
2288
+ Type: OperationType.CONTEXT,
2289
+ Error: createErrorObjectFromError(error),
2290
+ Name: name,
2291
+ });
2292
+ // Reconstruct error from ErrorObject for deterministic behavior
2293
+ const errorObject = createErrorObjectFromError(error);
2294
+ const reconstructedError = DurableOperationError.fromErrorObject(errorObject);
2295
+ throw new ChildContextError(reconstructedError.message, reconstructedError);
2296
+ }
2297
+ };
2298
+
2299
+ const createWaitHandler = (context, checkpoint, createStepId, hasRunningOperations, getOperationsEmitter, parentId, checkAndUpdateReplayMode) => {
2300
+ function waitHandler(nameOrDuration, duration) {
2301
+ const isNameFirst = typeof nameOrDuration === "string";
2302
+ const actualName = isNameFirst ? nameOrDuration : undefined;
2303
+ const actualDuration = isNameFirst ? duration : nameOrDuration;
2304
+ const actualSeconds = durationToSeconds(actualDuration);
2305
+ const stepId = createStepId();
2306
+ // Shared wait logic for both phases
2307
+ const executeWaitLogic = async (canTerminate) => {
2308
+ log("⏲️", `Wait executing (${canTerminate ? "phase 2" : "phase 1"}):`, {
2309
+ stepId,
2310
+ name: actualName,
2311
+ duration: actualDuration,
2312
+ seconds: actualSeconds,
2313
+ });
2314
+ let stepData = context.getStepData(stepId);
2315
+ // Validate replay consistency once before loop
2316
+ validateReplayConsistency(stepId, {
2317
+ type: OperationType.WAIT,
2318
+ name: actualName,
2319
+ subType: OperationSubType.WAIT,
2320
+ }, stepData, context);
2321
+ // Main wait logic - can be re-executed if step data changes
2322
+ while (true) {
2323
+ stepData = context.getStepData(stepId);
2324
+ if (stepData?.Status === OperationStatus.SUCCEEDED) {
2325
+ log("⏭️", "Wait already completed:", { stepId });
2326
+ checkAndUpdateReplayMode?.();
2327
+ return;
2328
+ }
2329
+ // Only checkpoint START if we haven't started this wait before
2330
+ if (!stepData) {
2331
+ await checkpoint.checkpoint(stepId, {
2332
+ Id: stepId,
2333
+ ParentId: parentId,
2334
+ Action: OperationAction.START,
2335
+ SubType: OperationSubType.WAIT,
2336
+ Type: OperationType.WAIT,
2337
+ Name: actualName,
2338
+ WaitOptions: {
2339
+ WaitSeconds: actualSeconds,
2340
+ },
2341
+ });
2342
+ }
2343
+ // Always refresh stepData to ensure it's up-to-date before proceeding
2344
+ stepData = context.getStepData(stepId);
2345
+ // Check if there are any ongoing operations
2346
+ if (!hasRunningOperations()) {
2347
+ // Phase 1: Just return without terminating
2348
+ // Phase 2: Terminate
2349
+ if (canTerminate) {
2350
+ return terminate(context, TerminationReason.WAIT_SCHEDULED, `Operation ${actualName || stepId} scheduled to wait`);
2351
+ }
2352
+ else {
2353
+ log("⏸️", "Wait ready but not terminating (phase 1):", { stepId });
2354
+ return;
2355
+ }
2356
+ }
2357
+ // There are ongoing operations - wait before continuing
2358
+ await waitBeforeContinue({
2359
+ checkHasRunningOperations: true,
2360
+ checkStepStatus: true,
2361
+ checkTimer: true,
2362
+ scheduledEndTimestamp: stepData?.WaitDetails?.ScheduledEndTimestamp,
2363
+ stepId,
2364
+ context,
2365
+ hasRunningOperations,
2366
+ operationsEmitter: getOperationsEmitter(),
2367
+ checkpoint,
2368
+ });
2369
+ // Continue the loop to re-evaluate all conditions from the beginning
2370
+ }
2371
+ };
2372
+ // Create a promise that tracks phase 1 completion
2373
+ const phase1Promise = executeWaitLogic(false).then(() => {
2374
+ log("✅", "Wait phase 1 complete:", { stepId, name: actualName });
2375
+ });
2376
+ // Attach catch handler to prevent unhandled promise rejections
2377
+ // The error will still be thrown when the DurablePromise is awaited
2378
+ phase1Promise.catch(() => { });
2379
+ // Return DurablePromise that will execute phase 2 when awaited
2380
+ return new DurablePromise(async () => {
2381
+ // Wait for phase 1 to complete first
2382
+ await phase1Promise;
2383
+ // Then execute phase 2
2384
+ await executeWaitLogic(true);
2385
+ });
2386
+ }
2387
+ return waitHandler;
2388
+ };
2389
+
2390
+ // Special symbol to indicate that the main loop should continue
2391
+ const CONTINUE_MAIN_LOOP = Symbol("CONTINUE_MAIN_LOOP");
2392
+ const waitForContinuation = async (context, stepId, name, hasRunningOperations, checkpoint, operationsEmitter, onAwaitedChange) => {
2393
+ const stepData = context.getStepData(stepId);
2394
+ // Check if there are any ongoing operations
2395
+ if (!hasRunningOperations()) {
2396
+ // No ongoing operations - safe to terminate
2397
+ return terminate(context, TerminationReason.RETRY_SCHEDULED, `Retry scheduled for ${name || stepId}`);
2398
+ }
2399
+ // There are ongoing operations - wait before continuing
2400
+ await waitBeforeContinue({
2401
+ checkHasRunningOperations: true,
2402
+ checkStepStatus: true,
2403
+ checkTimer: true,
2404
+ scheduledEndTimestamp: stepData?.StepDetails?.NextAttemptTimestamp,
2405
+ stepId,
2406
+ context,
2407
+ hasRunningOperations,
2408
+ operationsEmitter,
2409
+ checkpoint,
2410
+ onAwaitedChange,
2411
+ });
2412
+ // Return to let the main loop re-evaluate step status
2413
+ };
2414
+ const createWaitForConditionHandler = (context, checkpoint, createStepId, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId) => {
2415
+ return (nameOrCheck, checkOrConfig, maybeConfig) => {
2416
+ // Two-phase execution: Phase 1 starts immediately, Phase 2 returns result when awaited
2417
+ let isAwaited = false;
2418
+ let waitingCallback;
2419
+ const setWaitingCallback = (cb) => {
2420
+ waitingCallback = cb;
2421
+ };
2422
+ // Phase 1: Start execution immediately and capture result/error
2423
+ const phase1Promise = (async () => {
2424
+ let name;
2425
+ let check;
2426
+ let config;
2427
+ // Parse overloaded parameters - validation errors thrown here are async
2428
+ if (typeof nameOrCheck === "string" || nameOrCheck === undefined) {
2429
+ name = nameOrCheck;
2430
+ check = checkOrConfig;
2431
+ config = maybeConfig;
2432
+ }
2433
+ else {
2434
+ check = nameOrCheck;
2435
+ config = checkOrConfig;
2436
+ }
2437
+ if (!config ||
2438
+ !config.waitStrategy ||
2439
+ config.initialState === undefined) {
2440
+ throw new Error("waitForCondition requires config with waitStrategy and initialState");
2441
+ }
2442
+ const stepId = createStepId();
2443
+ log("🔄", "Running waitForCondition:", {
2444
+ stepId,
2445
+ name,
2446
+ config,
2447
+ });
2448
+ // Main waitForCondition logic - can be re-executed if step status changes
2449
+ while (true) {
2450
+ try {
2451
+ const stepData = context.getStepData(stepId);
2452
+ // Check if already completed
2453
+ if (stepData?.Status === OperationStatus.SUCCEEDED) {
2454
+ return await handleCompletedWaitForCondition(context, stepId, name, config.serdes);
2455
+ }
2456
+ if (stepData?.Status === OperationStatus.FAILED) {
2457
+ // Return an async rejected promise to ensure it's handled asynchronously
2458
+ return (async () => {
2459
+ // Reconstruct the original error from stored ErrorObject
2460
+ if (stepData.StepDetails?.Error) {
2461
+ throw DurableOperationError.fromErrorObject(stepData.StepDetails.Error);
2462
+ }
2463
+ else {
2464
+ // Fallback for legacy data without Error field
2465
+ const errorMessage = stepData?.StepDetails?.Result;
2466
+ throw new WaitForConditionError(errorMessage || "waitForCondition failed");
2467
+ }
2468
+ })();
2469
+ }
2470
+ // If PENDING, wait for timer to complete
2471
+ if (stepData?.Status === OperationStatus.PENDING) {
2472
+ await waitForContinuation(context, stepId, name, hasRunningOperations, checkpoint, getOperationsEmitter(), isAwaited ? undefined : setWaitingCallback);
2473
+ continue; // Re-evaluate step status after waiting
2474
+ }
2475
+ // Execute check function for READY, STARTED, or first time (undefined)
2476
+ const result = await executeWaitForCondition(context, checkpoint, stepId, name, check, config, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, isAwaited ? undefined : setWaitingCallback);
2477
+ // If executeWaitForCondition signals to continue the main loop, do so
2478
+ if (result === CONTINUE_MAIN_LOOP) {
2479
+ continue;
2480
+ }
2481
+ return result;
2482
+ }
2483
+ catch (error) {
2484
+ // For any error from executeWaitForCondition, re-throw it
2485
+ throw error;
2486
+ }
2487
+ }
2488
+ })();
2489
+ // Attach catch handler to prevent unhandled promise rejections
2490
+ // The error will still be thrown when the DurablePromise is awaited
2491
+ phase1Promise.catch(() => { });
2492
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
2493
+ return new DurablePromise(async () => {
2494
+ // When promise is awaited, mark as awaited and invoke waiting callback
2495
+ isAwaited = true;
2496
+ if (waitingCallback) {
2497
+ waitingCallback();
2498
+ }
2499
+ return await phase1Promise;
2500
+ });
2501
+ };
2502
+ };
2503
+ const handleCompletedWaitForCondition = async (context, stepId, stepName, serdes = defaultSerdes) => {
2504
+ log("⏭️", "waitForCondition already finished, returning cached result:", {
2505
+ stepId,
2506
+ });
2507
+ const stepData = context.getStepData(stepId);
2508
+ const result = stepData?.StepDetails?.Result;
2509
+ return await safeDeserialize(serdes, result, stepId, stepName, context.terminationManager, context.durableExecutionArn);
2510
+ };
2511
+ const executeWaitForCondition = async (context, checkpoint, stepId, name, check, config, logger, addRunningOperation, removeRunningOperation, hasRunningOperations, getOperationsEmitter, parentId, onAwaitedChange) => {
2512
+ const serdes = config.serdes || defaultSerdes;
2513
+ // Get current state from previous checkpoint or use initial state
2514
+ let currentState;
2515
+ const existingOperation = context.getStepData(stepId);
2516
+ if (existingOperation?.Status === OperationStatus.STARTED ||
2517
+ existingOperation?.Status === OperationStatus.READY) {
2518
+ // This is a retry - get state from previous checkpoint
2519
+ const checkpointData = existingOperation.StepDetails?.Result;
2520
+ if (checkpointData) {
2521
+ try {
2522
+ // Try to deserialize the checkpoint data directly
2523
+ const serdesContext = {
2524
+ entityId: stepId,
2525
+ durableExecutionArn: context.durableExecutionArn,
2526
+ };
2527
+ currentState = await serdes.deserialize(checkpointData, serdesContext);
2528
+ }
2529
+ catch (error) {
2530
+ log("⚠️", "Failed to deserialize checkpoint data, using initial state:", {
2531
+ stepId,
2532
+ name,
2533
+ error,
2534
+ });
2535
+ currentState = config.initialState;
2536
+ }
2537
+ }
2538
+ else {
2539
+ currentState = config.initialState;
2540
+ }
2541
+ }
2542
+ else {
2543
+ // First execution
2544
+ currentState = config.initialState;
2545
+ }
2546
+ // Get the current attempt number (1-based for wait strategy consistency)
2547
+ const currentAttempt = existingOperation?.StepDetails?.Attempt || 1;
2548
+ // Checkpoint START for observability (fire and forget) - only if not already started
2549
+ const stepData = context.getStepData(stepId);
2550
+ if (stepData?.Status !== OperationStatus.STARTED) {
2551
+ checkpoint.checkpoint(stepId, {
2552
+ Id: stepId,
2553
+ ParentId: parentId,
2554
+ Action: OperationAction.START,
2555
+ SubType: OperationSubType.WAIT_FOR_CONDITION,
2556
+ Type: OperationType.STEP,
2557
+ Name: name,
2558
+ });
2559
+ }
2560
+ try {
2561
+ // Create WaitForConditionContext with enriched logger for the check function
2562
+ const waitForConditionContext = {
2563
+ logger,
2564
+ };
2565
+ // Execute the check function
2566
+ addRunningOperation(stepId);
2567
+ let newState;
2568
+ try {
2569
+ newState = await runWithContext(stepId, parentId, () => check(currentState, waitForConditionContext), currentAttempt + 1, DurableExecutionMode.ExecutionMode);
2570
+ }
2571
+ finally {
2572
+ removeRunningOperation(stepId);
2573
+ }
2574
+ // Serialize the new state for consistency
2575
+ const serializedState = await safeSerialize(serdes, newState, stepId, name, context.terminationManager, context.durableExecutionArn);
2576
+ // Deserialize for consistency with replay behavior
2577
+ const deserializedState = await safeDeserialize(serdes, serializedState, stepId, name, context.terminationManager, context.durableExecutionArn);
2578
+ // Check if condition is met using the wait strategy
2579
+ const decision = config.waitStrategy(deserializedState, currentAttempt);
2580
+ log("🔍", "waitForCondition check completed:", {
2581
+ stepId,
2582
+ name,
2583
+ currentAttempt: currentAttempt,
2584
+ shouldContinue: decision.shouldContinue,
2585
+ delayInSeconds: decision.shouldContinue
2586
+ ? durationToSeconds(decision.delay)
2587
+ : undefined,
2588
+ });
2589
+ if (!decision.shouldContinue) {
2590
+ // Condition is met - complete successfully
2591
+ await checkpoint.checkpoint(stepId, {
2592
+ Id: stepId,
2593
+ ParentId: parentId,
2594
+ Action: OperationAction.SUCCEED,
2595
+ SubType: OperationSubType.WAIT_FOR_CONDITION,
2596
+ Type: OperationType.STEP,
2597
+ Payload: serializedState,
2598
+ Name: name,
2599
+ });
2600
+ log("✅", "waitForCondition completed successfully:", {
2601
+ stepId,
2602
+ name,
2603
+ result: deserializedState,
2604
+ totalAttempts: currentAttempt,
2605
+ });
2606
+ return deserializedState;
2607
+ }
2608
+ else {
2609
+ // Condition not met - schedule retry
2610
+ // Only checkpoint the state, not the attempt number (system handles that)
2611
+ await checkpoint.checkpoint(stepId, {
2612
+ Id: stepId,
2613
+ ParentId: parentId,
2614
+ Action: OperationAction.RETRY,
2615
+ SubType: OperationSubType.WAIT_FOR_CONDITION,
2616
+ Type: OperationType.STEP,
2617
+ Payload: serializedState, // Just the state, not wrapped in an object
2618
+ Name: name,
2619
+ StepOptions: {
2620
+ NextAttemptDelaySeconds: durationToSeconds(decision.delay),
2621
+ },
2622
+ });
2623
+ // Wait for continuation and signal main loop to continue
2624
+ await waitForContinuation(context, stepId, name, hasRunningOperations, checkpoint, getOperationsEmitter(), onAwaitedChange);
2625
+ return CONTINUE_MAIN_LOOP;
2626
+ }
2627
+ }
2628
+ catch (error) {
2629
+ log("❌", "waitForCondition check function failed:", {
2630
+ stepId,
2631
+ name,
2632
+ error,
2633
+ currentAttempt: currentAttempt,
2634
+ });
2635
+ // Mark as failed - waitForCondition doesn't have its own retry logic for errors
2636
+ // If the check function throws, it's considered a failure
2637
+ await checkpoint.checkpoint(stepId, {
2638
+ Id: stepId,
2639
+ ParentId: parentId,
2640
+ Action: OperationAction.FAIL,
2641
+ SubType: OperationSubType.WAIT_FOR_CONDITION,
2642
+ Type: OperationType.STEP,
2643
+ Error: createErrorObjectFromError(error),
2644
+ Name: name,
2645
+ });
2646
+ // Reconstruct error from ErrorObject for deterministic behavior
2647
+ const errorObject = createErrorObjectFromError(error);
2648
+ throw DurableOperationError.fromErrorObject(errorObject);
2649
+ }
2650
+ };
2651
+
2652
+ const createCallbackPromise = (context, stepId, stepName, serdes, hasRunningOperations, operationsEmitter, terminationMessage, checkAndUpdateReplayMode) => {
2653
+ return new DurablePromise(async () => {
2654
+ log("🔄", "Callback promise phase 2 executing:", { stepId, stepName });
2655
+ // Main callback logic - can be re-executed if step status changes
2656
+ while (true) {
2657
+ const stepData = context.getStepData(stepId);
2658
+ // Handle case where stepData doesn't exist yet
2659
+ // While Phase 1 should create stepData via checkpoint before Phase 2 starts,
2660
+ // this can be undefined in test scenarios
2661
+ if (!stepData) {
2662
+ log("⚠️", "Step data not found, waiting for callback creation:", {
2663
+ stepId,
2664
+ });
2665
+ if (hasRunningOperations()) {
2666
+ await waitBeforeContinue({
2667
+ checkHasRunningOperations: true,
2668
+ checkStepStatus: true,
2669
+ checkTimer: false,
2670
+ stepId,
2671
+ context,
2672
+ hasRunningOperations,
2673
+ operationsEmitter,
2674
+ });
2675
+ continue; // Re-evaluate after waiting
2676
+ }
2677
+ // No other operations and no step data - terminate gracefully
2678
+ log("⏳", "No step data found and no running operations, terminating");
2679
+ return terminate(context, TerminationReason.CALLBACK_PENDING, terminationMessage);
2680
+ }
2681
+ if (stepData.Status === OperationStatus.SUCCEEDED) {
2682
+ const callbackData = stepData.CallbackDetails;
2683
+ if (!callbackData?.CallbackId) {
2684
+ throw new CallbackError(`No callback ID found for completed callback: ${stepId}`);
2685
+ }
2686
+ const result = await safeDeserialize(serdes, callbackData.Result, stepId, stepName, context.terminationManager, context.durableExecutionArn);
2687
+ // Check and update replay mode after callback completion
2688
+ checkAndUpdateReplayMode();
2689
+ return result;
2690
+ }
2691
+ if (stepData.Status === OperationStatus.FAILED ||
2692
+ stepData.Status === OperationStatus.TIMED_OUT) {
2693
+ const callbackData = stepData.CallbackDetails;
2694
+ const error = callbackData?.Error;
2695
+ if (error) {
2696
+ const cause = new Error(error.ErrorMessage);
2697
+ cause.name = error.ErrorType || "Error";
2698
+ cause.stack = error.StackTrace?.join("\n");
2699
+ throw new CallbackError(error.ErrorMessage || "Callback failed", cause, error.ErrorData);
2700
+ }
2701
+ throw new CallbackError("Callback failed");
2702
+ }
2703
+ if (stepData.Status === OperationStatus.STARTED) {
2704
+ // Callback is still pending
2705
+ if (hasRunningOperations()) {
2706
+ // Wait for other operations or callback completion
2707
+ log("⏳", "Callback still pending, waiting for other operations");
2708
+ await waitBeforeContinue({
2709
+ checkHasRunningOperations: true,
2710
+ checkStepStatus: true,
2711
+ checkTimer: false,
2712
+ stepId,
2713
+ context,
2714
+ hasRunningOperations,
2715
+ operationsEmitter,
2716
+ });
2717
+ continue; // Re-evaluate status after waiting
2718
+ }
2719
+ // No other operations running - terminate
2720
+ log("⏳", "Callback still pending, terminating");
2721
+ return terminate(context, TerminationReason.CALLBACK_PENDING, terminationMessage);
2722
+ }
2723
+ // Should not reach here, but handle unexpected status
2724
+ throw new CallbackError(`Unexpected callback status: ${stepData.Status}`);
2725
+ }
2726
+ });
2727
+ };
2728
+
2729
+ const createPassThroughSerdes = () => ({
2730
+ serialize: async (value) => value,
2731
+ deserialize: async (data) => data,
2732
+ });
2733
+ const createCallback = (context, checkpoint, createStepId, hasRunningOperations, getOperationsEmitter, checkAndUpdateReplayMode, parentId) => {
2734
+ return (nameOrConfig, maybeConfig) => {
2735
+ let name;
2736
+ let config;
2737
+ if (typeof nameOrConfig === "string" || nameOrConfig === undefined) {
2738
+ name = nameOrConfig;
2739
+ config = maybeConfig;
2740
+ }
2741
+ else {
2742
+ config = nameOrConfig;
2743
+ }
2744
+ const stepId = createStepId();
2745
+ const serdes = config?.serdes || createPassThroughSerdes();
2746
+ // Validate replay consistency first
2747
+ const stepData = context.getStepData(stepId);
2748
+ validateReplayConsistency(stepId, {
2749
+ type: OperationType.CALLBACK,
2750
+ name,
2751
+ subType: OperationSubType.CALLBACK,
2752
+ }, stepData, context);
2753
+ // Phase 1: Setup and checkpoint (immediate execution)
2754
+ const setupPromise = (async () => {
2755
+ log("📞", "Creating callback phase 1:", { stepId, name, config });
2756
+ // Handle already completed callbacks
2757
+ if (stepData?.Status === OperationStatus.SUCCEEDED) {
2758
+ log("⏭️", "Callback already completed in phase 1:", { stepId });
2759
+ return { wasNewCallback: false };
2760
+ }
2761
+ if (stepData?.Status === OperationStatus.FAILED ||
2762
+ stepData?.Status === OperationStatus.TIMED_OUT) {
2763
+ log("❌", "Callback already failed in phase 1:", { stepId });
2764
+ return { wasNewCallback: false };
2765
+ }
2766
+ // Handle already started callbacks
2767
+ if (stepData?.Status === OperationStatus.STARTED) {
2768
+ log("⏳", "Callback already started in phase 1:", { stepId });
2769
+ return { wasNewCallback: false };
2770
+ }
2771
+ // Create new callback - checkpoint START operation
2772
+ log("🆕", "Creating new callback in phase 1:", { stepId, name });
2773
+ await checkpoint.checkpoint(stepId, {
2774
+ Id: stepId,
2775
+ ParentId: parentId,
2776
+ Action: "START",
2777
+ SubType: OperationSubType.CALLBACK,
2778
+ Type: OperationType.CALLBACK,
2779
+ Name: name,
2780
+ CallbackOptions: {
2781
+ TimeoutSeconds: config?.timeout
2782
+ ? durationToSeconds(config.timeout)
2783
+ : undefined,
2784
+ HeartbeatTimeoutSeconds: config?.heartbeatTimeout
2785
+ ? durationToSeconds(config.heartbeatTimeout)
2786
+ : undefined,
2787
+ },
2788
+ });
2789
+ log("✅", "Callback checkpoint completed in phase 1:", { stepId });
2790
+ return { wasNewCallback: true };
2791
+ })().catch((error) => {
2792
+ log("❌", "Callback phase 1 error:", { stepId, error: error.message });
2793
+ throw error;
2794
+ });
2795
+ // Return DurablePromise that executes phase 2 when awaited
2796
+ return new DurablePromise(async () => {
2797
+ // Wait for phase 1 to complete
2798
+ const { wasNewCallback } = await setupPromise;
2799
+ // Phase 2: Handle results and create callback promise
2800
+ log("🔄", "Callback phase 2 executing:", { stepId, name });
2801
+ const stepData = context.getStepData(stepId);
2802
+ // Handle completed callbacks
2803
+ if (stepData?.Status === OperationStatus.SUCCEEDED) {
2804
+ const callbackData = stepData.CallbackDetails;
2805
+ if (!callbackData?.CallbackId) {
2806
+ throw new CallbackError(`No callback ID found for completed callback: ${stepId}`);
2807
+ }
2808
+ const deserializedResult = await safeDeserialize(serdes, callbackData.Result, stepId, name, context.terminationManager, context.durableExecutionArn);
2809
+ const resolvedPromise = new DurablePromise(async () => deserializedResult);
2810
+ // Check and update replay mode after callback completion
2811
+ checkAndUpdateReplayMode();
2812
+ return [resolvedPromise, callbackData.CallbackId];
2813
+ }
2814
+ // Handle failed callbacks
2815
+ if (stepData?.Status === OperationStatus.FAILED ||
2816
+ stepData?.Status === OperationStatus.TIMED_OUT) {
2817
+ const callbackData = stepData.CallbackDetails;
2818
+ if (!callbackData?.CallbackId) {
2819
+ throw new CallbackError(`No callback ID found for failed callback: ${stepId}`);
2820
+ }
2821
+ const error = stepData.CallbackDetails?.Error;
2822
+ const callbackError = error
2823
+ ? (() => {
2824
+ const cause = new Error(error.ErrorMessage);
2825
+ cause.name = error.ErrorType || "Error";
2826
+ cause.stack = error.StackTrace?.join("\n");
2827
+ return new CallbackError(error.ErrorMessage || "Callback failed", cause, error.ErrorData);
2828
+ })()
2829
+ : new CallbackError("Callback failed");
2830
+ const rejectedPromise = new DurablePromise(async () => {
2831
+ throw callbackError;
2832
+ });
2833
+ return [rejectedPromise, callbackData.CallbackId];
2834
+ }
2835
+ // Handle started or new callbacks
2836
+ const callbackData = stepData?.CallbackDetails;
2837
+ if (!callbackData?.CallbackId) {
2838
+ const errorMessage = wasNewCallback
2839
+ ? `Callback ID not found in stepData after checkpoint: ${stepId}`
2840
+ : `No callback ID found for started callback: ${stepId}`;
2841
+ throw new CallbackError(errorMessage);
2842
+ }
2843
+ const callbackId = callbackData.CallbackId;
2844
+ // Create callback promise that handles completion
2845
+ const terminationMessage = wasNewCallback
2846
+ ? `Callback ${name || stepId} created and pending external completion`
2847
+ : `Callback ${name || stepId} is pending external completion`;
2848
+ const callbackPromise = createCallbackPromise(context, stepId, name, serdes, hasRunningOperations, getOperationsEmitter(), terminationMessage, checkAndUpdateReplayMode);
2849
+ log("✅", "Callback created successfully in phase 2:", {
2850
+ stepId,
2851
+ name,
2852
+ callbackId,
2853
+ });
2854
+ return [callbackPromise, callbackId];
2855
+ });
2856
+ };
2857
+ };
2858
+
2859
+ const createWaitForCallbackHandler = (context, getNextStepId, runInChildContext) => {
2860
+ return (nameOrSubmitter, submitterOrConfig, maybeConfig) => {
2861
+ let name;
2862
+ let submitter;
2863
+ let config;
2864
+ // Parse the overloaded parameters - validation errors thrown here are async
2865
+ if (typeof nameOrSubmitter === "string" || nameOrSubmitter === undefined) {
2866
+ // Case: waitForCallback("name", submitterFunc, config?) or waitForCallback(undefined, submitterFunc, config?)
2867
+ name = nameOrSubmitter;
2868
+ if (typeof submitterOrConfig === "function") {
2869
+ submitter = submitterOrConfig;
2870
+ config = maybeConfig;
2871
+ }
2872
+ else {
2873
+ return new DurablePromise(() => Promise.reject(new Error("waitForCallback requires a submitter function when name is provided")));
2874
+ }
2875
+ }
2876
+ else if (typeof nameOrSubmitter === "function") {
2877
+ // Case: waitForCallback(submitterFunc, config?)
2878
+ submitter = nameOrSubmitter;
2879
+ config = submitterOrConfig;
2880
+ }
2881
+ else {
2882
+ return new DurablePromise(() => Promise.reject(new Error("waitForCallback requires a submitter function")));
2883
+ }
2884
+ // Two-phase execution: Phase 1 starts immediately, Phase 2 returns result when awaited
2885
+ // Phase 1: Start execution immediately and capture result/error
2886
+ const phase1Promise = (async () => {
2887
+ log("📞", "WaitForCallback requested:", {
2888
+ name,
2889
+ hasSubmitter: !!submitter,
2890
+ config,
2891
+ });
2892
+ // Use runInChildContext to ensure proper ID generation and isolation
2893
+ const childFunction = async (childCtx) => {
2894
+ // Convert WaitForCallbackConfig to CreateCallbackConfig
2895
+ const createCallbackConfig = config
2896
+ ? {
2897
+ timeout: config.timeout,
2898
+ heartbeatTimeout: config.heartbeatTimeout,
2899
+ }
2900
+ : undefined;
2901
+ // Create callback and get the promise + callbackId
2902
+ const [callbackPromise, callbackId] = await childCtx.createCallback(createCallbackConfig);
2903
+ log("🆔", "Callback created:", {
2904
+ callbackId,
2905
+ name,
2906
+ });
2907
+ // Execute the submitter step (submitter is now mandatory)
2908
+ await childCtx.step(async (stepContext) => {
2909
+ // Use the step's built-in logger instead of creating a new one
2910
+ const callbackContext = {
2911
+ logger: stepContext.logger,
2912
+ };
2913
+ log("📤", "Executing submitter:", {
2914
+ callbackId,
2915
+ name,
2916
+ });
2917
+ await submitter(callbackId, callbackContext);
2918
+ log("✅", "Submitter completed:", {
2919
+ callbackId,
2920
+ name,
2921
+ });
2922
+ }, config?.retryStrategy
2923
+ ? { retryStrategy: config.retryStrategy }
2924
+ : undefined);
2925
+ log("⏳", "Waiting for callback completion:", {
2926
+ callbackId,
2927
+ name,
2928
+ });
2929
+ // Return just the callback promise result
2930
+ return await callbackPromise;
2931
+ };
2932
+ const stepId = getNextStepId();
2933
+ return {
2934
+ result: await runInChildContext(name, childFunction, {
2935
+ subType: OperationSubType.WAIT_FOR_CALLBACK,
2936
+ }),
2937
+ stepId,
2938
+ };
2939
+ })();
2940
+ // Attach catch handler to prevent unhandled promise rejections
2941
+ // The error will still be thrown when the DurablePromise is awaited
2942
+ phase1Promise.catch(() => { });
2943
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
2944
+ return new DurablePromise(async () => {
2945
+ const { result, stepId } = await phase1Promise;
2946
+ // Always deserialize the result since it's a string
2947
+ return (await safeDeserialize(config?.serdes ?? createPassThroughSerdes(), result, stepId, name, context.terminationManager, context.durableExecutionArn));
2948
+ });
2949
+ };
2950
+ };
2951
+
2952
+ /**
2953
+ * Creates a predefined summary generator for parallel operations
2954
+ */
2955
+ const createParallelSummaryGenerator = () => (result) => {
2956
+ return JSON.stringify({
2957
+ type: "ParallelResult",
2958
+ totalCount: result.totalCount,
2959
+ successCount: result.successCount,
2960
+ failureCount: result.failureCount,
2961
+ startedCount: result.startedCount,
2962
+ completionReason: result.completionReason,
2963
+ status: result.status,
2964
+ });
2965
+ };
2966
+ /**
2967
+ * Creates a predefined summary generator for map operations
2968
+ */
2969
+ const createMapSummaryGenerator = () => (result) => {
2970
+ return JSON.stringify({
2971
+ type: "MapResult",
2972
+ totalCount: result.totalCount,
2973
+ successCount: result.successCount,
2974
+ failureCount: result.failureCount,
2975
+ completionReason: result.completionReason,
2976
+ status: result.status,
2977
+ });
2978
+ };
2979
+
2980
+ const createMapHandler = (context, executeConcurrently) => {
2981
+ return (nameOrItems, itemsOrMapFunc, mapFuncOrConfig, maybeConfig) => {
2982
+ // Phase 1: Parse parameters and start execution immediately
2983
+ const phase1Promise = (async () => {
2984
+ let name;
2985
+ let items;
2986
+ let mapFunc;
2987
+ let config;
2988
+ // Parse overloaded parameters
2989
+ if (typeof nameOrItems === "string" || nameOrItems === undefined) {
2990
+ // Case: map(name, items, mapFunc, config?)
2991
+ name = nameOrItems;
2992
+ items = itemsOrMapFunc;
2993
+ mapFunc = mapFuncOrConfig;
2994
+ config = maybeConfig;
2995
+ }
2996
+ else {
2997
+ // Case: map(items, mapFunc, config?)
2998
+ items = nameOrItems;
2999
+ mapFunc = itemsOrMapFunc;
3000
+ config = mapFuncOrConfig;
3001
+ }
3002
+ log("🗺️", "Starting map operation:", {
3003
+ name,
3004
+ itemCount: items.length,
3005
+ maxConcurrency: config?.maxConcurrency,
3006
+ });
3007
+ // Validate inputs
3008
+ if (!Array.isArray(items)) {
3009
+ throw new Error("Map operation requires an array of items");
3010
+ }
3011
+ if (typeof mapFunc !== "function") {
3012
+ throw new Error("Map operation requires a function to process items");
3013
+ }
3014
+ // Convert to concurrent execution items
3015
+ const executionItems = items.map((item, index) => ({
3016
+ id: `map-item-${index}`,
3017
+ data: item,
3018
+ index,
3019
+ name: config?.itemNamer ? config.itemNamer(item, index) : undefined,
3020
+ }));
3021
+ // Create executor that calls mapFunc
3022
+ const executor = async (executionItem, childContext) => mapFunc(childContext, executionItem.data, executionItem.index, items);
3023
+ const result = await executeConcurrently(name, executionItems, executor, {
3024
+ maxConcurrency: config?.maxConcurrency,
3025
+ topLevelSubType: OperationSubType.MAP,
3026
+ iterationSubType: OperationSubType.MAP_ITERATION,
3027
+ summaryGenerator: createMapSummaryGenerator(),
3028
+ completionConfig: config?.completionConfig,
3029
+ serdes: config?.serdes,
3030
+ itemSerdes: config?.itemSerdes,
3031
+ });
3032
+ log("🗺️", "Map operation completed successfully:", {
3033
+ resultCount: result.totalCount,
3034
+ });
3035
+ return result;
3036
+ })();
3037
+ // Attach catch handler to prevent unhandled promise rejections
3038
+ // The error will still be thrown when the DurablePromise is awaited
3039
+ phase1Promise.catch(() => { });
3040
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
3041
+ return new DurablePromise(async () => {
3042
+ return await phase1Promise;
3043
+ });
3044
+ };
3045
+ };
3046
+
3047
+ const createParallelHandler = (context, executeConcurrently) => {
3048
+ return (nameOrBranches, branchesOrConfig, maybeConfig) => {
3049
+ // Phase 1: Parse parameters and start execution immediately
3050
+ const phase1Promise = (async () => {
3051
+ let name;
3052
+ let branches;
3053
+ let config;
3054
+ // Parse overloaded parameters
3055
+ if (typeof nameOrBranches === "string" || nameOrBranches === undefined) {
3056
+ // Case: parallel(name, branches, config?)
3057
+ name = nameOrBranches;
3058
+ branches = branchesOrConfig;
3059
+ config = maybeConfig;
3060
+ }
3061
+ else {
3062
+ // Case: parallel(branches, config?)
3063
+ branches = nameOrBranches;
3064
+ config = branchesOrConfig;
3065
+ }
3066
+ // Validate inputs
3067
+ if (!Array.isArray(branches)) {
3068
+ throw new Error("Parallel operation requires an array of branch functions");
3069
+ }
3070
+ log("🔀", "Starting parallel operation:", {
3071
+ name,
3072
+ branchCount: branches.length,
3073
+ maxConcurrency: config?.maxConcurrency,
3074
+ });
3075
+ if (branches.some((branch) => typeof branch !== "function" &&
3076
+ (typeof branch !== "object" || typeof branch.func !== "function"))) {
3077
+ throw new Error("All branches must be functions or NamedParallelBranch objects");
3078
+ }
3079
+ // Convert to concurrent execution items
3080
+ const executionItems = branches.map((branch, index) => {
3081
+ const isNamedBranch = typeof branch === "object" && "func" in branch;
3082
+ const func = isNamedBranch ? branch.func : branch;
3083
+ const branchName = isNamedBranch ? branch.name : undefined;
3084
+ return {
3085
+ id: `parallel-branch-${index}`,
3086
+ data: func,
3087
+ index,
3088
+ name: branchName,
3089
+ };
3090
+ });
3091
+ // Create executor that calls the branch function
3092
+ const executor = async (executionItem, childContext) => {
3093
+ log("🔀", "Processing parallel branch:", {
3094
+ index: executionItem.index,
3095
+ });
3096
+ const result = await executionItem.data(childContext);
3097
+ log("✅", "Parallel branch completed:", {
3098
+ index: executionItem.index,
3099
+ result,
3100
+ });
3101
+ return result;
3102
+ };
3103
+ const result = await executeConcurrently(name, executionItems, executor, {
3104
+ maxConcurrency: config?.maxConcurrency,
3105
+ topLevelSubType: OperationSubType.PARALLEL,
3106
+ iterationSubType: OperationSubType.PARALLEL_BRANCH,
3107
+ summaryGenerator: createParallelSummaryGenerator(),
3108
+ completionConfig: config?.completionConfig,
3109
+ serdes: config?.serdes,
3110
+ itemSerdes: config?.itemSerdes,
3111
+ });
3112
+ log("🔀", "Parallel operation completed successfully:", {
3113
+ resultCount: result.totalCount,
3114
+ });
3115
+ return result;
3116
+ })();
3117
+ // Attach catch handler to prevent unhandled promise rejections
3118
+ // The error will still be thrown when the DurablePromise is awaited
3119
+ phase1Promise.catch(() => { });
3120
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
3121
+ return new DurablePromise(async () => {
3122
+ return await phase1Promise;
3123
+ });
3124
+ };
3125
+ };
3126
+
3127
+ // Minimal error decoration for Promise.allSettled results
3128
+ function decorateErrors(value) {
3129
+ return value.map((item) => {
3130
+ if (item && item.status === "rejected" && item.reason instanceof Error) {
3131
+ return {
3132
+ ...item,
3133
+ reason: {
3134
+ message: item.reason.message,
3135
+ name: item.reason.name,
3136
+ stack: item.reason.stack,
3137
+ },
3138
+ };
3139
+ }
3140
+ return item;
3141
+ });
3142
+ }
3143
+ // Error restoration for Promise.allSettled results
3144
+ function restoreErrors(value) {
3145
+ return value.map((item) => {
3146
+ if (item &&
3147
+ item.status === "rejected" &&
3148
+ item.reason &&
3149
+ typeof item.reason === "object" &&
3150
+ item.reason.message) {
3151
+ const error = new Error(item.reason.message);
3152
+ error.name = item.reason.name || "Error";
3153
+ if (item.reason.stack)
3154
+ error.stack = item.reason.stack;
3155
+ return {
3156
+ ...item,
3157
+ reason: error,
3158
+ };
3159
+ }
3160
+ return item;
3161
+ });
3162
+ }
3163
+ // Custom serdes for promise results with error handling
3164
+ function createErrorAwareSerdes() {
3165
+ return {
3166
+ serialize: async (value, _context) => value !== undefined ? JSON.stringify(decorateErrors(value)) : undefined,
3167
+ deserialize: async (data, _context) => data !== undefined
3168
+ ? restoreErrors(JSON.parse(data))
3169
+ : undefined,
3170
+ };
3171
+ }
3172
+ // No-retry strategy for promise combinators
3173
+ const stepConfig = {
3174
+ retryStrategy: () => ({
3175
+ shouldRetry: false,
3176
+ }),
3177
+ };
3178
+ const createPromiseHandler = (step) => {
3179
+ const parseParams = (nameOrPromises, maybePromises) => {
3180
+ if (typeof nameOrPromises === "string" || nameOrPromises === undefined) {
3181
+ return { name: nameOrPromises, promises: maybePromises };
3182
+ }
3183
+ return { name: undefined, promises: nameOrPromises };
3184
+ };
3185
+ const all = (nameOrPromises, maybePromises) => {
3186
+ return new DurablePromise(async () => {
3187
+ const { name, promises } = parseParams(nameOrPromises, maybePromises);
3188
+ // Wrap Promise.all execution in a step for persistence
3189
+ return await step(name, () => Promise.all(promises), stepConfig);
3190
+ });
3191
+ };
3192
+ const allSettled = (nameOrPromises, maybePromises) => {
3193
+ return new DurablePromise(async () => {
3194
+ const { name, promises } = parseParams(nameOrPromises, maybePromises);
3195
+ // Wrap Promise.allSettled execution in a step for persistence
3196
+ return await step(name, () => Promise.allSettled(promises), {
3197
+ ...stepConfig,
3198
+ serdes: createErrorAwareSerdes(),
3199
+ });
3200
+ });
3201
+ };
3202
+ const any = (nameOrPromises, maybePromises) => {
3203
+ return new DurablePromise(async () => {
3204
+ const { name, promises } = parseParams(nameOrPromises, maybePromises);
3205
+ // Wrap Promise.any execution in a step for persistence
3206
+ return await step(name, () => Promise.any(promises), stepConfig);
3207
+ });
3208
+ };
3209
+ const race = (nameOrPromises, maybePromises) => {
3210
+ return new DurablePromise(async () => {
3211
+ const { name, promises } = parseParams(nameOrPromises, maybePromises);
3212
+ // Wrap Promise.race execution in a step for persistence
3213
+ return await step(name, () => Promise.race(promises), stepConfig);
3214
+ });
3215
+ };
3216
+ return {
3217
+ all,
3218
+ allSettled,
3219
+ any,
3220
+ race,
3221
+ };
3222
+ };
3223
+
3224
+ class BatchResultImpl {
3225
+ all;
3226
+ completionReason;
3227
+ constructor(all, completionReason) {
3228
+ this.all = all;
3229
+ this.completionReason = completionReason;
3230
+ }
3231
+ succeeded() {
3232
+ return this.all.filter((item) => item.status === BatchItemStatus.SUCCEEDED && item.result !== undefined);
3233
+ }
3234
+ failed() {
3235
+ return this.all.filter((item) => item.status === BatchItemStatus.FAILED && item.error !== undefined);
3236
+ }
3237
+ started() {
3238
+ return this.all.filter((item) => item.status === BatchItemStatus.STARTED);
3239
+ }
3240
+ get status() {
3241
+ return this.hasFailure ? BatchItemStatus.FAILED : BatchItemStatus.SUCCEEDED;
3242
+ }
3243
+ get hasFailure() {
3244
+ return this.all.some((item) => item.status === BatchItemStatus.FAILED);
3245
+ }
3246
+ throwIfError() {
3247
+ const firstError = this.all.find((item) => item.status === BatchItemStatus.FAILED)?.error;
3248
+ if (firstError) {
3249
+ throw firstError;
3250
+ }
3251
+ }
3252
+ getResults() {
3253
+ return this.succeeded().map((item) => item.result);
3254
+ }
3255
+ getErrors() {
3256
+ return this.failed().map((item) => item.error);
3257
+ }
3258
+ get successCount() {
3259
+ return this.all.filter((item) => item.status === BatchItemStatus.SUCCEEDED)
3260
+ .length;
3261
+ }
3262
+ get failureCount() {
3263
+ return this.all.filter((item) => item.status === BatchItemStatus.FAILED)
3264
+ .length;
3265
+ }
3266
+ get startedCount() {
3267
+ return this.all.filter((item) => item.status === BatchItemStatus.STARTED)
3268
+ .length;
3269
+ }
3270
+ get totalCount() {
3271
+ return this.all.length;
3272
+ }
3273
+ }
3274
+ /**
3275
+ * Restores methods to deserialized BatchResult data
3276
+ */
3277
+ function restoreBatchResult(data) {
3278
+ if (data &&
3279
+ typeof data === "object" &&
3280
+ "all" in data &&
3281
+ Array.isArray(data.all)) {
3282
+ const serializedData = data;
3283
+ // Restore Error objects
3284
+ const restoredItems = serializedData.all.map((item) => ({
3285
+ ...item,
3286
+ result: item.result,
3287
+ error: item.error
3288
+ ? DurableOperationError.fromErrorObject(item.error)
3289
+ : undefined,
3290
+ }));
3291
+ return new BatchResultImpl(restoredItems, serializedData.completionReason);
3292
+ }
3293
+ return new BatchResultImpl([], "ALL_COMPLETED");
3294
+ }
3295
+
3296
+ class ConcurrencyController {
3297
+ operationName;
3298
+ skipNextOperation;
3299
+ constructor(operationName, skipNextOperation) {
3300
+ this.operationName = operationName;
3301
+ this.skipNextOperation = skipNextOperation;
3302
+ }
3303
+ isChildEntityCompleted(executionContext, parentEntityId, completedCount) {
3304
+ const childEntityId = `${parentEntityId}-${completedCount + 1}`;
3305
+ const childStepData = executionContext.getStepData(childEntityId);
3306
+ return !!(childStepData &&
3307
+ (childStepData.Status === OperationStatus.SUCCEEDED ||
3308
+ childStepData.Status === OperationStatus.FAILED));
3309
+ }
3310
+ async executeItems(items, executor, parentContext, config, durableExecutionMode = DurableExecutionMode.ExecutionMode, entityId, executionContext) {
3311
+ // In replay mode, we're reconstructing the result from child contexts
3312
+ if (durableExecutionMode === DurableExecutionMode.ReplaySucceededContext) {
3313
+ log("🔄", `Replay mode: Reconstructing ${this.operationName} result:`, {
3314
+ itemCount: items.length,
3315
+ });
3316
+ // Try to get the target count from step data
3317
+ let targetTotalCount;
3318
+ if (entityId && executionContext) {
3319
+ const stepData = executionContext.getStepData(entityId);
3320
+ const summaryPayload = stepData?.ContextDetails?.Result;
3321
+ if (summaryPayload) {
3322
+ try {
3323
+ const serdes = config.serdes || defaultSerdes;
3324
+ const parsedSummary = await serdes.deserialize(summaryPayload, {
3325
+ entityId: entityId,
3326
+ durableExecutionArn: executionContext.durableExecutionArn,
3327
+ });
3328
+ if (parsedSummary &&
3329
+ typeof parsedSummary === "object" &&
3330
+ "totalCount" in parsedSummary) {
3331
+ // Read totalCount directly from summary metadata
3332
+ targetTotalCount = parsedSummary.totalCount;
3333
+ log("📊", "Found initial execution count:", {
3334
+ targetTotalCount,
3335
+ });
3336
+ }
3337
+ }
3338
+ catch (error) {
3339
+ log("⚠️", "Could not parse initial result summary:", error);
3340
+ }
3341
+ }
3342
+ }
3343
+ // If we have target count and required context, use optimized replay; otherwise fallback to concurrent execution
3344
+ if (targetTotalCount !== undefined && entityId && executionContext) {
3345
+ return await this.replayItems(items, executor, parentContext, config, targetTotalCount, executionContext, entityId);
3346
+ }
3347
+ else {
3348
+ log("⚠️", "No valid target count or context found, falling back to concurrent execution");
3349
+ }
3350
+ }
3351
+ // First-time execution or fallback: use normal concurrent execution logic
3352
+ return await this.executeItemsConcurrently(items, executor, parentContext, config);
3353
+ }
3354
+ async replayItems(items, executor, parentContext, config, targetTotalCount, executionContext, parentEntityId) {
3355
+ const resultItems = [];
3356
+ log("🔄", `Replaying ${items.length} items sequentially`, {
3357
+ targetTotalCount,
3358
+ });
3359
+ let completedCount = 0;
3360
+ let stepCounter = 0;
3361
+ // Replay items sequentially until we reach the target count
3362
+ for (const item of items) {
3363
+ // Stop if we've replayed all items that completed in initial execution
3364
+ if (completedCount >= targetTotalCount) {
3365
+ log("✅", "Reached target count, stopping replay", {
3366
+ completedCount,
3367
+ targetTotalCount,
3368
+ });
3369
+ break;
3370
+ }
3371
+ // Calculate the child entity ID that runInChildContext will create
3372
+ // It uses the parent's next step ID, which is parentEntityId-{counter}
3373
+ const childEntityId = `${parentEntityId}-${stepCounter + 1}`;
3374
+ if (!this.isChildEntityCompleted(executionContext, parentEntityId, stepCounter)) {
3375
+ log("⏭️", `Skipping incomplete item:`, {
3376
+ index: item.index,
3377
+ itemId: item.id,
3378
+ childEntityId,
3379
+ });
3380
+ // Increment step counter to maintain consistency
3381
+ this.skipNextOperation();
3382
+ stepCounter++;
3383
+ continue;
3384
+ }
3385
+ try {
3386
+ const result = await parentContext.runInChildContext(item.name || item.id, (childContext) => executor(item, childContext), { subType: config.iterationSubType, serdes: config.itemSerdes });
3387
+ resultItems.push({
3388
+ result,
3389
+ index: item.index,
3390
+ status: BatchItemStatus.SUCCEEDED,
3391
+ });
3392
+ completedCount++;
3393
+ stepCounter++;
3394
+ log("✅", `Replayed ${this.operationName} item:`, {
3395
+ index: item.index,
3396
+ itemId: item.id,
3397
+ completedCount,
3398
+ });
3399
+ }
3400
+ catch (error) {
3401
+ const err = error instanceof ChildContextError
3402
+ ? error
3403
+ : new ChildContextError(error instanceof Error ? error.message : String(error), error instanceof Error ? error : undefined);
3404
+ resultItems.push({
3405
+ error: err,
3406
+ index: item.index,
3407
+ status: BatchItemStatus.FAILED,
3408
+ });
3409
+ completedCount++;
3410
+ stepCounter++;
3411
+ log("❌", `Replay failed for ${this.operationName} item:`, {
3412
+ index: item.index,
3413
+ itemId: item.id,
3414
+ error: err.message,
3415
+ completedCount,
3416
+ });
3417
+ }
3418
+ }
3419
+ log("🎉", `${this.operationName} replay completed:`, {
3420
+ completedCount,
3421
+ totalCount: resultItems.length,
3422
+ });
3423
+ // Reconstruct the completion reason based on replay results
3424
+ const successCount = resultItems.filter((item) => item.status === BatchItemStatus.SUCCEEDED).length;
3425
+ const getCompletionReason = () => {
3426
+ if (completedCount === items.length)
3427
+ return "ALL_COMPLETED";
3428
+ if (config.completionConfig?.minSuccessful !== undefined &&
3429
+ successCount >= config.completionConfig.minSuccessful)
3430
+ return "MIN_SUCCESSFUL_REACHED";
3431
+ return "FAILURE_TOLERANCE_EXCEEDED";
3432
+ };
3433
+ return new BatchResultImpl(resultItems, getCompletionReason());
3434
+ }
3435
+ async executeItemsConcurrently(items, executor, parentContext, config) {
3436
+ const maxConcurrency = config.maxConcurrency || Infinity;
3437
+ const resultItems = new Array(items.length);
3438
+ const startedItems = new Set();
3439
+ let activeCount = 0;
3440
+ let currentIndex = 0;
3441
+ let completedCount = 0;
3442
+ let successCount = 0;
3443
+ let failureCount = 0;
3444
+ log("🚀", `Starting ${this.operationName} with concurrency control:`, {
3445
+ itemCount: items.length,
3446
+ maxConcurrency,
3447
+ });
3448
+ return new Promise((resolve) => {
3449
+ const shouldContinue = () => {
3450
+ const completion = config.completionConfig;
3451
+ if (!completion)
3452
+ return failureCount === 0;
3453
+ // Default to fail-fast when no completion criteria are defined
3454
+ const hasAnyCompletionCriteria = Object.values(completion).some((value) => value !== undefined);
3455
+ if (!hasAnyCompletionCriteria) {
3456
+ return failureCount === 0;
3457
+ }
3458
+ if (completion.toleratedFailureCount !== undefined &&
3459
+ failureCount > completion.toleratedFailureCount)
3460
+ return false;
3461
+ if (completion.toleratedFailurePercentage !== undefined) {
3462
+ const failurePercentage = (failureCount / items.length) * 100;
3463
+ if (failurePercentage > completion.toleratedFailurePercentage)
3464
+ return false;
3465
+ }
3466
+ return true;
3467
+ };
3468
+ const isComplete = () => {
3469
+ // Always complete when all items are done (matches BatchResult inference)
3470
+ if (completedCount === items.length) {
3471
+ return true;
3472
+ }
3473
+ const completion = config.completionConfig;
3474
+ if (completion?.minSuccessful !== undefined &&
3475
+ successCount >= completion.minSuccessful) {
3476
+ return true;
3477
+ }
3478
+ return false;
3479
+ };
3480
+ const getCompletionReason = () => {
3481
+ if (completedCount === items.length)
3482
+ return "ALL_COMPLETED";
3483
+ if (config.completionConfig?.minSuccessful !== undefined &&
3484
+ successCount >= config.completionConfig.minSuccessful)
3485
+ return "MIN_SUCCESSFUL_REACHED";
3486
+ return "FAILURE_TOLERANCE_EXCEEDED";
3487
+ };
3488
+ const tryStartNext = () => {
3489
+ while (activeCount < maxConcurrency &&
3490
+ currentIndex < items.length &&
3491
+ shouldContinue()) {
3492
+ const index = currentIndex++;
3493
+ const item = items[index];
3494
+ startedItems.add(index);
3495
+ activeCount++;
3496
+ // Set STARTED status immediately in result array
3497
+ resultItems[index] = { index, status: BatchItemStatus.STARTED };
3498
+ log("▶️", `Starting ${this.operationName} item:`, {
3499
+ index,
3500
+ itemId: item.id,
3501
+ itemName: item.name,
3502
+ });
3503
+ parentContext
3504
+ .runInChildContext(item.name || item.id, (childContext) => executor(item, childContext), { subType: config.iterationSubType, serdes: config.itemSerdes })
3505
+ .then((result) => {
3506
+ resultItems[index] = {
3507
+ result,
3508
+ index,
3509
+ status: BatchItemStatus.SUCCEEDED,
3510
+ };
3511
+ successCount++;
3512
+ log("✅", `${this.operationName} item completed:`, {
3513
+ index,
3514
+ itemId: item.id,
3515
+ itemName: item.name,
3516
+ });
3517
+ onComplete();
3518
+ }, (error) => {
3519
+ const err = error instanceof ChildContextError
3520
+ ? error
3521
+ : new ChildContextError(error instanceof Error ? error.message : String(error), error instanceof Error ? error : undefined);
3522
+ resultItems[index] = {
3523
+ error: err,
3524
+ index,
3525
+ status: BatchItemStatus.FAILED,
3526
+ };
3527
+ failureCount++;
3528
+ log("❌", `${this.operationName} item failed:`, {
3529
+ index,
3530
+ itemId: item.id,
3531
+ itemName: item.name,
3532
+ error: err.message,
3533
+ });
3534
+ onComplete();
3535
+ });
3536
+ }
3537
+ };
3538
+ const onComplete = () => {
3539
+ activeCount--;
3540
+ completedCount++;
3541
+ if (isComplete() || !shouldContinue()) {
3542
+ // Convert sparse array to dense array - items are already in correct order by index
3543
+ // Include all items that were started (have a value in resultItems)
3544
+ // Create shallow copy to prevent mutations from affecting the returned result
3545
+ const finalBatchItems = [];
3546
+ for (let i = 0; i < resultItems.length; i++) {
3547
+ if (resultItems[i] !== undefined) {
3548
+ finalBatchItems.push({ ...resultItems[i] });
3549
+ }
3550
+ }
3551
+ log("🎉", `${this.operationName} completed:`, {
3552
+ successCount,
3553
+ failureCount,
3554
+ startedCount: finalBatchItems.filter((item) => item.status === BatchItemStatus.STARTED).length,
3555
+ totalCount: finalBatchItems.length,
3556
+ });
3557
+ const result = new BatchResultImpl(finalBatchItems, getCompletionReason());
3558
+ resolve(result);
3559
+ }
3560
+ else {
3561
+ tryStartNext();
3562
+ }
3563
+ };
3564
+ tryStartNext();
3565
+ });
3566
+ }
3567
+ }
3568
+ const createConcurrentExecutionHandler = (context, runInChildContext, skipNextOperation) => {
3569
+ return (nameOrItems, itemsOrExecutor, executorOrConfig, maybeConfig) => {
3570
+ // Phase 1: Start execution immediately
3571
+ const phase1Promise = (async () => {
3572
+ let name;
3573
+ let items;
3574
+ let executor;
3575
+ let config;
3576
+ if (typeof nameOrItems === "string" || nameOrItems === undefined) {
3577
+ name = nameOrItems;
3578
+ items = itemsOrExecutor;
3579
+ executor = executorOrConfig;
3580
+ config = maybeConfig;
3581
+ }
3582
+ else {
3583
+ items = nameOrItems;
3584
+ executor = itemsOrExecutor;
3585
+ config = executorOrConfig;
3586
+ }
3587
+ log("🔄", "Starting concurrent execution:", {
3588
+ name,
3589
+ itemCount: items.length,
3590
+ maxConcurrency: config?.maxConcurrency,
3591
+ });
3592
+ if (!Array.isArray(items)) {
3593
+ throw new Error("Concurrent execution requires an array of items");
3594
+ }
3595
+ if (typeof executor !== "function") {
3596
+ throw new Error("Concurrent execution requires an executor function");
3597
+ }
3598
+ if (config?.maxConcurrency !== undefined &&
3599
+ config.maxConcurrency !== null &&
3600
+ config.maxConcurrency <= 0) {
3601
+ throw new Error(`Invalid maxConcurrency: ${config.maxConcurrency}. Must be a positive number or undefined for unlimited concurrency.`);
3602
+ }
3603
+ const executeOperation = async (executionContext) => {
3604
+ const concurrencyController = new ConcurrencyController("concurrent-execution", skipNextOperation);
3605
+ // Access durableExecutionMode from the context - it's set by runInChildContext
3606
+ // based on determineChildReplayMode logic
3607
+ const durableExecutionMode = executionContext.durableExecutionMode;
3608
+ // Get the entity ID (step prefix) from the child context
3609
+ const entityId = executionContext._stepPrefix;
3610
+ log("🔄", "Concurrent execution mode:", {
3611
+ mode: durableExecutionMode,
3612
+ itemCount: items.length,
3613
+ entityId,
3614
+ });
3615
+ return await concurrencyController.executeItems(items, executor, executionContext, config || {}, durableExecutionMode, entityId, context);
3616
+ };
3617
+ const result = await runInChildContext(name, executeOperation, {
3618
+ subType: config?.topLevelSubType,
3619
+ summaryGenerator: config?.summaryGenerator,
3620
+ serdes: config?.serdes,
3621
+ });
3622
+ // Restore BatchResult methods if the result came from deserialized data
3623
+ if (result &&
3624
+ typeof result === "object" &&
3625
+ "all" in result &&
3626
+ Array.isArray(result.all)) {
3627
+ return restoreBatchResult(result);
3628
+ }
3629
+ return result;
3630
+ })();
3631
+ // Attach catch handler to prevent unhandled promise rejections
3632
+ // The error will still be thrown when the DurablePromise is awaited
3633
+ phase1Promise.catch(() => { });
3634
+ // Phase 2: Return DurablePromise that returns Phase 1 result when awaited
3635
+ return new DurablePromise(async () => {
3636
+ return await phase1Promise;
3637
+ });
3638
+ };
3639
+ };
3640
+
3641
+ class ModeManagement {
3642
+ captureExecutionState;
3643
+ checkAndUpdateReplayMode;
3644
+ checkForNonResolvingPromise;
3645
+ getDurableExecutionMode;
3646
+ setDurableExecutionMode;
3647
+ constructor(captureExecutionState, checkAndUpdateReplayMode, checkForNonResolvingPromise, getDurableExecutionMode, setDurableExecutionMode) {
3648
+ this.captureExecutionState = captureExecutionState;
3649
+ this.checkAndUpdateReplayMode = checkAndUpdateReplayMode;
3650
+ this.checkForNonResolvingPromise = checkForNonResolvingPromise;
3651
+ this.getDurableExecutionMode = getDurableExecutionMode;
3652
+ this.setDurableExecutionMode = setDurableExecutionMode;
3653
+ }
3654
+ withModeManagement(operation) {
3655
+ const shouldSwitchToExecutionMode = this.captureExecutionState();
3656
+ this.checkAndUpdateReplayMode();
3657
+ const nonResolvingPromise = this.checkForNonResolvingPromise();
3658
+ if (nonResolvingPromise)
3659
+ return nonResolvingPromise;
3660
+ try {
3661
+ return operation();
3662
+ }
3663
+ finally {
3664
+ if (shouldSwitchToExecutionMode) {
3665
+ this.setDurableExecutionMode(DurableExecutionMode.ExecutionMode);
3666
+ }
3667
+ }
3668
+ }
3669
+ withDurableModeManagement(operation) {
3670
+ const shouldSwitchToExecutionMode = this.captureExecutionState();
3671
+ this.checkAndUpdateReplayMode();
3672
+ const nonResolvingPromise = this.checkForNonResolvingPromise();
3673
+ if (nonResolvingPromise) {
3674
+ return new DurablePromise(async () => {
3675
+ await nonResolvingPromise;
3676
+ // This will never be reached
3677
+ throw new Error("Unreachable code");
3678
+ });
3679
+ }
3680
+ try {
3681
+ return operation();
3682
+ }
3683
+ finally {
3684
+ if (shouldSwitchToExecutionMode) {
3685
+ this.setDurableExecutionMode(DurableExecutionMode.ExecutionMode);
3686
+ }
3687
+ }
3688
+ }
3689
+ }
3690
+
3691
+ class DurableContextImpl {
3692
+ executionContext;
3693
+ lambdaContext;
3694
+ _stepPrefix;
3695
+ _stepCounter = 0;
3696
+ durableLogger;
3697
+ modeAwareLoggingEnabled = true;
3698
+ runningOperations = new Set();
3699
+ operationsEmitter = new EventEmitter();
3700
+ checkpoint;
3701
+ durableExecutionMode;
3702
+ _parentId;
3703
+ modeManagement;
3704
+ durableExecution;
3705
+ logger;
3706
+ constructor(executionContext, lambdaContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId) {
3707
+ this.executionContext = executionContext;
3708
+ this.lambdaContext = lambdaContext;
3709
+ this._stepPrefix = stepPrefix;
3710
+ this._parentId = parentId;
3711
+ this.durableExecution = durableExecution;
3712
+ this.durableLogger = inheritedLogger;
3713
+ this.durableLogger.configureDurableLoggingContext?.(this.getDurableLoggingContext());
3714
+ this.logger = this.createModeAwareLogger(inheritedLogger);
3715
+ this.durableExecutionMode = durableExecutionMode;
3716
+ this.checkpoint = durableExecution.checkpointManager;
3717
+ this.modeManagement = new ModeManagement(this.captureExecutionState.bind(this), this.checkAndUpdateReplayMode.bind(this), this.checkForNonResolvingPromise.bind(this), () => this.durableExecutionMode, (mode) => {
3718
+ this.durableExecutionMode = mode;
3719
+ });
3720
+ }
3721
+ getDurableLoggingContext() {
3722
+ return {
3723
+ getDurableLogData: () => {
3724
+ const activeContext = getActiveContext();
3725
+ const result = {
3726
+ executionArn: this.executionContext.durableExecutionArn,
3727
+ requestId: this.executionContext.requestId,
3728
+ tenantId: this.executionContext.tenantId,
3729
+ operationId: !activeContext || activeContext?.contextId === "root"
3730
+ ? undefined
3731
+ : hashId(activeContext.contextId),
3732
+ };
3733
+ if (activeContext?.attempt !== undefined) {
3734
+ result.attempt = activeContext.attempt;
3735
+ }
3736
+ return result;
3737
+ },
3738
+ };
3739
+ }
3740
+ shouldLog() {
3741
+ const activeContext = getActiveContext();
3742
+ if (!this.modeAwareLoggingEnabled || !activeContext) {
3743
+ return true;
3744
+ }
3745
+ if (activeContext.contextId === "root") {
3746
+ return this.durableExecutionMode === DurableExecutionMode.ExecutionMode;
3747
+ }
3748
+ return (activeContext.durableExecutionMode === DurableExecutionMode.ExecutionMode);
3749
+ }
3750
+ createModeAwareLogger(logger) {
3751
+ const durableContextLogger = {
3752
+ warn: (...args) => {
3753
+ if (this.shouldLog()) {
3754
+ return logger.warn(...args);
3755
+ }
3756
+ },
3757
+ debug: (...args) => {
3758
+ if (this.shouldLog()) {
3759
+ return logger.debug(...args);
3760
+ }
3761
+ },
3762
+ info: (...args) => {
3763
+ if (this.shouldLog()) {
3764
+ return logger.info(...args);
3765
+ }
3766
+ },
3767
+ error: (...args) => {
3768
+ if (this.shouldLog()) {
3769
+ return logger.error(...args);
3770
+ }
3771
+ },
3772
+ };
3773
+ if ("log" in logger) {
3774
+ durableContextLogger.log = (level, ...args) => {
3775
+ if (this.shouldLog()) {
3776
+ return logger.log?.(level, ...args);
3777
+ }
3778
+ };
3779
+ }
3780
+ return durableContextLogger;
3781
+ }
3782
+ createStepId() {
3783
+ this._stepCounter++;
3784
+ return this._stepPrefix
3785
+ ? `${this._stepPrefix}-${this._stepCounter}`
3786
+ : `${this._stepCounter}`;
3787
+ }
3788
+ getNextStepId() {
3789
+ const nextCounter = this._stepCounter + 1;
3790
+ return this._stepPrefix
3791
+ ? `${this._stepPrefix}-${nextCounter}`
3792
+ : `${nextCounter}`;
3793
+ }
3794
+ /**
3795
+ * Skips the next operation by incrementing the step counter.
3796
+ * Used internally by concurrent execution handler during replay to skip incomplete items.
3797
+ * @internal
3798
+ */
3799
+ skipNextOperation() {
3800
+ this._stepCounter++;
3801
+ }
3802
+ checkAndUpdateReplayMode() {
3803
+ if (this.durableExecutionMode === DurableExecutionMode.ReplayMode) {
3804
+ const nextStepId = this.getNextStepId();
3805
+ const nextStepData = this.executionContext.getStepData(nextStepId);
3806
+ if (!nextStepData) {
3807
+ this.durableExecutionMode = DurableExecutionMode.ExecutionMode;
3808
+ }
3809
+ }
3810
+ }
3811
+ captureExecutionState() {
3812
+ const wasInReplayMode = this.durableExecutionMode === DurableExecutionMode.ReplayMode;
3813
+ const nextStepId = this.getNextStepId();
3814
+ const stepData = this.executionContext.getStepData(nextStepId);
3815
+ const wasNotFinished = !!(stepData &&
3816
+ stepData.Status !== OperationStatus.SUCCEEDED &&
3817
+ stepData.Status !== OperationStatus.FAILED);
3818
+ return wasInReplayMode && wasNotFinished;
3819
+ }
3820
+ checkForNonResolvingPromise() {
3821
+ if (this.durableExecutionMode === DurableExecutionMode.ReplaySucceededContext) {
3822
+ const nextStepId = this.getNextStepId();
3823
+ const nextStepData = this.executionContext.getStepData(nextStepId);
3824
+ if (nextStepData &&
3825
+ nextStepData.Status !== OperationStatus.SUCCEEDED &&
3826
+ nextStepData.Status !== OperationStatus.FAILED) {
3827
+ return new Promise(() => { }); // Non-resolving promise
3828
+ }
3829
+ }
3830
+ return null;
3831
+ }
3832
+ addRunningOperation(stepId) {
3833
+ this.runningOperations.add(stepId);
3834
+ }
3835
+ removeRunningOperation(stepId) {
3836
+ this.runningOperations.delete(stepId);
3837
+ if (this.runningOperations.size === 0) {
3838
+ this.operationsEmitter.emit(OPERATIONS_COMPLETE_EVENT);
3839
+ }
3840
+ }
3841
+ hasRunningOperations() {
3842
+ return this.runningOperations.size > 0;
3843
+ }
3844
+ getOperationsEmitter() {
3845
+ return this.operationsEmitter;
3846
+ }
3847
+ withModeManagement(operation) {
3848
+ return this.modeManagement.withModeManagement(operation);
3849
+ }
3850
+ withDurableModeManagement(operation) {
3851
+ return this.modeManagement.withDurableModeManagement(operation);
3852
+ }
3853
+ step(nameOrFn, fnOrOptions, maybeOptions) {
3854
+ validateContextUsage(this._stepPrefix, "step", this.executionContext.terminationManager);
3855
+ return this.withDurableModeManagement(() => {
3856
+ 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);
3857
+ return stepHandler(nameOrFn, fnOrOptions, maybeOptions);
3858
+ });
3859
+ }
3860
+ invoke(nameOrFuncId, funcIdOrInput, inputOrConfig, maybeConfig) {
3861
+ validateContextUsage(this._stepPrefix, "invoke", this.executionContext.terminationManager);
3862
+ return this.withDurableModeManagement(() => {
3863
+ 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));
3864
+ return invokeHandler(...[
3865
+ nameOrFuncId,
3866
+ funcIdOrInput,
3867
+ inputOrConfig,
3868
+ maybeConfig,
3869
+ ]);
3870
+ });
3871
+ }
3872
+ runInChildContext(nameOrFn, fnOrOptions, maybeOptions) {
3873
+ validateContextUsage(this._stepPrefix, "runInChildContext", this.executionContext.terminationManager);
3874
+ return this.withDurableModeManagement(() => {
3875
+ const blockHandler = createRunInChildContextHandler(this.executionContext, this.checkpoint, this.lambdaContext, this.createStepId.bind(this), () => this.durableLogger,
3876
+ // Adapter function to maintain compatibility
3877
+ (executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, _checkpointToken, parentId) => createDurableContext(executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, this.durableExecution, parentId), this._parentId);
3878
+ return blockHandler(nameOrFn, fnOrOptions, maybeOptions);
3879
+ });
3880
+ }
3881
+ wait(nameOrDuration, maybeDuration) {
3882
+ validateContextUsage(this._stepPrefix, "wait", this.executionContext.terminationManager);
3883
+ return this.withDurableModeManagement(() => {
3884
+ 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));
3885
+ return typeof nameOrDuration === "string"
3886
+ ? waitHandler(nameOrDuration, maybeDuration)
3887
+ : waitHandler(nameOrDuration);
3888
+ });
3889
+ }
3890
+ /**
3891
+ * Configure logger behavior for this context
3892
+ *
3893
+ * This method allows partial configuration - only the properties provided will be updated.
3894
+ * For example, calling configureLogger(\{ modeAware: false \}) will only change the modeAware
3895
+ * setting without affecting any previously configured custom logger.
3896
+ *
3897
+ * @param config - Logger configuration options including customLogger and modeAware settings (default: modeAware=true)
3898
+ * @example
3899
+ * // Set custom logger and enable mode-aware logging
3900
+ * context.configureLogger(\{ customLogger: myLogger, modeAware: true \});
3901
+ *
3902
+ * // Later, disable mode-aware logging without changing the custom logger
3903
+ * context.configureLogger(\{ modeAware: false \});
3904
+ */
3905
+ configureLogger(config) {
3906
+ if (config.customLogger !== undefined) {
3907
+ this.durableLogger = config.customLogger;
3908
+ this.durableLogger.configureDurableLoggingContext?.(this.getDurableLoggingContext());
3909
+ this.logger = this.createModeAwareLogger(this.durableLogger);
3910
+ }
3911
+ if (config.modeAware !== undefined) {
3912
+ this.modeAwareLoggingEnabled = config.modeAware;
3913
+ }
3914
+ }
3915
+ createCallback(nameOrConfig, maybeConfig) {
3916
+ validateContextUsage(this._stepPrefix, "createCallback", this.executionContext.terminationManager);
3917
+ return this.withDurableModeManagement(() => {
3918
+ 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);
3919
+ return callbackFactory(nameOrConfig, maybeConfig);
3920
+ });
3921
+ }
3922
+ waitForCallback(nameOrSubmitter, submitterOrConfig, maybeConfig) {
3923
+ validateContextUsage(this._stepPrefix, "waitForCallback", this.executionContext.terminationManager);
3924
+ return this.withDurableModeManagement(() => {
3925
+ const waitForCallbackHandler = createWaitForCallbackHandler(this.executionContext, this.getNextStepId.bind(this), this.runInChildContext.bind(this));
3926
+ return waitForCallbackHandler(nameOrSubmitter, submitterOrConfig, maybeConfig);
3927
+ });
3928
+ }
3929
+ waitForCondition(nameOrCheckFunc, checkFuncOrConfig, maybeConfig) {
3930
+ validateContextUsage(this._stepPrefix, "waitForCondition", this.executionContext.terminationManager);
3931
+ return this.withDurableModeManagement(() => {
3932
+ 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);
3933
+ return typeof nameOrCheckFunc === "string" ||
3934
+ nameOrCheckFunc === undefined
3935
+ ? waitForConditionHandler(nameOrCheckFunc, checkFuncOrConfig, maybeConfig)
3936
+ : waitForConditionHandler(nameOrCheckFunc, checkFuncOrConfig);
3937
+ });
3938
+ }
3939
+ map(nameOrItems, itemsOrMapFunc, mapFuncOrConfig, maybeConfig) {
3940
+ validateContextUsage(this._stepPrefix, "map", this.executionContext.terminationManager);
3941
+ return this.withDurableModeManagement(() => {
3942
+ const mapHandler = createMapHandler(this.executionContext, this._executeConcurrently.bind(this));
3943
+ return mapHandler(nameOrItems, itemsOrMapFunc, mapFuncOrConfig, maybeConfig);
3944
+ });
3945
+ }
3946
+ parallel(nameOrBranches, branchesOrConfig, maybeConfig) {
3947
+ validateContextUsage(this._stepPrefix, "parallel", this.executionContext.terminationManager);
3948
+ return this.withDurableModeManagement(() => {
3949
+ const parallelHandler = createParallelHandler(this.executionContext, this._executeConcurrently.bind(this));
3950
+ return parallelHandler(nameOrBranches, branchesOrConfig, maybeConfig);
3951
+ });
3952
+ }
3953
+ _executeConcurrently(nameOrItems, itemsOrExecutor, executorOrConfig, maybeConfig) {
3954
+ validateContextUsage(this._stepPrefix, "_executeConcurrently", this.executionContext.terminationManager);
3955
+ return this.withDurableModeManagement(() => {
3956
+ const concurrentExecutionHandler = createConcurrentExecutionHandler(this.executionContext, this.runInChildContext.bind(this), this.skipNextOperation.bind(this));
3957
+ const promise = concurrentExecutionHandler(nameOrItems, itemsOrExecutor, executorOrConfig, maybeConfig);
3958
+ // Prevent unhandled promise rejections
3959
+ promise?.catch(() => { });
3960
+ return promise;
3961
+ });
3962
+ }
3963
+ get promise() {
3964
+ return createPromiseHandler(this.step.bind(this));
3965
+ }
3966
+ }
3967
+ const createDurableContext = (executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId) => {
3968
+ return new DurableContextImpl(executionContext, parentContext, durableExecutionMode, inheritedLogger, stepPrefix, durableExecution, parentId);
3969
+ };
3970
+
3971
+ /*
3972
+ Second Approach (Promise-based):
3973
+ Pros:
3974
+ - Simpler implementation
3975
+ - Single promise instance for the entire lifecycle
3976
+ - More memory efficient as it doesn't create new promises on each getTerminationPromise() call
3977
+ - More predictable behavior since there's only one resolution path
3978
+ Cons:
3979
+ - Less flexible as it doesn't support multiple listeners
3980
+ - Once the promise is resolved, it stays resolved (can't be reset)
3981
+ - Doesn't leverage Node.js's event system
3982
+ */
3983
+ class TerminationManager extends EventEmitter {
3984
+ isTerminated = false;
3985
+ terminationDetails;
3986
+ resolveTermination;
3987
+ terminationPromise;
3988
+ setCheckpointTerminating;
3989
+ constructor(setCheckpointTerminating) {
3990
+ super();
3991
+ this.setCheckpointTerminating = setCheckpointTerminating;
3992
+ // Create the promise immediately during construction
3993
+ this.terminationPromise = new Promise((resolve) => {
3994
+ this.resolveTermination = resolve;
3995
+ });
3996
+ }
3997
+ setCheckpointTerminatingCallback(callback) {
3998
+ this.setCheckpointTerminating = callback;
3999
+ }
4000
+ terminate(options = {}) {
4001
+ if (this.isTerminated)
4002
+ return;
4003
+ // Set checkpoint termination flag before any other termination logic
4004
+ this.setCheckpointTerminating?.();
4005
+ this.isTerminated = true;
4006
+ this.terminationDetails = {
4007
+ reason: options.reason ?? TerminationReason.OPERATION_TERMINATED,
4008
+ message: options.message ?? "Operation terminated",
4009
+ error: options.error,
4010
+ cleanup: options.cleanup,
4011
+ };
4012
+ // Instead of emitting an event, resolve the promise
4013
+ if (this.resolveTermination) {
4014
+ this.handleTermination(this.terminationDetails).then(this.resolveTermination);
4015
+ }
4016
+ }
4017
+ getTerminationPromise() {
4018
+ return this.terminationPromise;
4019
+ }
4020
+ async handleTermination(details) {
4021
+ if (details.cleanup) {
4022
+ try {
4023
+ await details.cleanup();
4024
+ }
4025
+ catch { }
4026
+ }
4027
+ return {
4028
+ reason: details.reason,
4029
+ message: details.message,
4030
+ error: details.error,
4031
+ };
4032
+ }
4033
+ }
4034
+
4035
+ // The logic from this file is based on the NodeJS RIC LogPatch functionality for parity with standard Lambda functions. We should always
4036
+ // align the default behaviour of how logs are emitted to match the RIC logging behaviour for consistency.
4037
+ // For custom logic, users can implement their own logger to log data differently.
4038
+ // See: https://github.com/aws/aws-lambda-nodejs-runtime-interface-client/blob/962ed28eefbc052389c4de4366b1c0c49ee08a13/src/LogPatch.js
4039
+ /**
4040
+ * JSON.stringify replacer function for Error objects.
4041
+ * Based on AWS Lambda Runtime Interface Client LogPatch functionality.
4042
+ * Transforms Error instances into serializable objects with structured error information,
4043
+ * emulating the default Node.js console behavior in Lambda environments.
4044
+ *
4045
+ * @param _key - The property key (unused in this replacer)
4046
+ * @param value - The value being stringified
4047
+ * @returns The original value, or a structured error object for Error instances
4048
+ */
4049
+ function jsonErrorReplacer(_key, value) {
4050
+ if (value instanceof Error) {
4051
+ return Object.assign({
4052
+ errorType: value?.constructor?.name ?? "UnknownError",
4053
+ errorMessage: value.message,
4054
+ stackTrace: typeof value.stack === "string"
4055
+ ? value.stack.split("\n")
4056
+ : value.stack,
4057
+ }, value);
4058
+ }
4059
+ return value;
4060
+ }
4061
+ /**
4062
+ * Formats durable log data into structured JSON string output.
4063
+ * Emulates AWS Lambda Runtime Interface Client's formatJsonMessage functionality
4064
+ * to provide consistent logging format with standard Lambda functions.
4065
+ *
4066
+ * The function handles two main scenarios:
4067
+ * 1. Single parameter: Attempts to stringify directly, falls back to util.format on error
4068
+ * 2. Multiple parameters: Uses util.format to create message, extracts error details if present
4069
+ *
4070
+ * This approach mirrors the RIC's behavior of:
4071
+ * - Using util.format for message formatting (same as console.log)
4072
+ * - Handling circular references gracefully with fallback formatting
4073
+ * - Extracting structured error information when Error objects are present
4074
+ * - Including optional tenantId when available
4075
+ *
4076
+ * @param level - The log level for this message
4077
+ * @param logData - Durable execution context data (requestId, executionArn, etc.)
4078
+ * @param messageParams - Variable number of message parameters to log
4079
+ * @returns JSON string representation of the structured log entry
4080
+ */
4081
+ function formatDurableLogData(level, logData, ...messageParams) {
4082
+ const result = {
4083
+ requestId: logData.requestId,
4084
+ timestamp: new Date().toISOString(),
4085
+ level: level.toUpperCase(),
4086
+ executionArn: logData.executionArn,
4087
+ };
4088
+ const tenantId = logData.tenantId;
4089
+ if (tenantId != undefined && tenantId != null) {
4090
+ result.tenantId = tenantId;
4091
+ }
4092
+ if (logData.operationId !== undefined) {
4093
+ result.operationId = logData.operationId;
4094
+ }
4095
+ if (logData.attempt !== undefined) {
4096
+ result.attempt = logData.attempt;
4097
+ }
4098
+ if (messageParams.length === 1) {
4099
+ result.message = messageParams[0];
4100
+ try {
4101
+ return JSON.stringify(result, jsonErrorReplacer);
4102
+ }
4103
+ catch (_) {
4104
+ result.message = util.format(result.message);
4105
+ return JSON.stringify(result);
4106
+ }
4107
+ }
4108
+ result.message = util.format(...messageParams);
4109
+ for (const param of messageParams) {
4110
+ if (param instanceof Error) {
4111
+ result.errorType = param?.constructor?.name ?? "UnknownError";
4112
+ result.errorMessage = param.message;
4113
+ result.stackTrace =
4114
+ typeof param.stack === "string" ? param.stack.split("\n") : [];
4115
+ break;
4116
+ }
4117
+ }
4118
+ return JSON.stringify(result);
4119
+ }
4120
+ /**
4121
+ * Default logger class that outputs structured logs to console.
4122
+ *
4123
+ * This logger emulates the AWS Lambda Runtime Interface Client (RIC) console patching
4124
+ * behavior to maintain parity with standard Lambda function logging while providing
4125
+ * structured output suitable for durable execution contexts.
4126
+ *
4127
+ * Key RIC behavior emulation:
4128
+ * - Respects AWS_LAMBDA_LOG_LEVEL environment variable for log filtering
4129
+ * - Uses priority-based level filtering (DEBUG=2, INFO=3, WARN=4, ERROR=5)
4130
+ * - Outputs structured JSON with timestamp, requestId, executionArn, and other metadata
4131
+ * - Handles Error objects with structured error information extraction
4132
+ * - Uses Node.js Console instance for proper stdout/stderr routing
4133
+ * - Applies util.format for message formatting (same as console.log behavior)
4134
+ *
4135
+ * Individual logger methods (info, error, warn, debug) are dynamically enabled/disabled
4136
+ * based on the configured log level, defaulting to no-op functions when disabled.
4137
+ * This mirrors how RIC patches console methods conditionally.
4138
+ */
4139
+ class DefaultLogger {
4140
+ consoleLogger;
4141
+ durableLoggingContext = undefined;
4142
+ executionContext;
4143
+ noOpLog = () => { };
4144
+ constructor(executionContext) {
4145
+ this.executionContext = executionContext;
4146
+ // Override the RIC logger to provide custom attributes on the structured log output
4147
+ this.consoleLogger = new Console({
4148
+ stdout: process.stdout,
4149
+ stderr: process.stderr,
4150
+ });
4151
+ // Initialize methods with no-op and then configure based on log level
4152
+ this.info = this.noOpLog;
4153
+ this.error = this.noOpLog;
4154
+ this.warn = this.noOpLog;
4155
+ this.debug = this.noOpLog;
4156
+ this.configureLogLevel();
4157
+ }
4158
+ configureLogLevel() {
4159
+ const levels = {
4160
+ DEBUG: { name: "DEBUG", priority: 2 },
4161
+ INFO: { name: "INFO", priority: 3 },
4162
+ WARN: { name: "WARN", priority: 4 },
4163
+ ERROR: { name: "ERROR", priority: 5 },
4164
+ // Not implemented yet. Can be implemented later
4165
+ // TRACE: { name: "TRACE", priority: 1 },
4166
+ // FATAL: { name: "FATAL", priority: 6 },
4167
+ };
4168
+ const logLevelEnvVariable = process.env["AWS_LAMBDA_LOG_LEVEL"]?.toUpperCase();
4169
+ // Default to DEBUG level when env var is invalid/missing
4170
+ const lambdaLogLevel = logLevelEnvVariable && logLevelEnvVariable in levels
4171
+ ? levels[logLevelEnvVariable]
4172
+ : levels.DEBUG;
4173
+ // Enable methods based on priority: higher priority = more restrictive
4174
+ // e.g., if WARN is set (priority 4), only WARN and ERROR methods are enabled
4175
+ if (levels.DEBUG.priority >= lambdaLogLevel.priority) {
4176
+ this.debug = (message, ...optionalParams) => {
4177
+ const loggingContext = this.ensureDurableLoggingContext();
4178
+ const params = message !== undefined ? [message, ...optionalParams] : optionalParams;
4179
+ this.consoleLogger.debug(formatDurableLogData(DurableLogLevel.DEBUG, loggingContext.getDurableLogData(), ...params));
4180
+ };
4181
+ }
4182
+ if (levels.INFO.priority >= lambdaLogLevel.priority) {
4183
+ this.info = (message, ...optionalParams) => {
4184
+ const loggingContext = this.ensureDurableLoggingContext();
4185
+ const params = message !== undefined ? [message, ...optionalParams] : optionalParams;
4186
+ this.consoleLogger.info(formatDurableLogData(DurableLogLevel.INFO, loggingContext.getDurableLogData(), ...params));
4187
+ };
4188
+ }
4189
+ if (levels.WARN.priority >= lambdaLogLevel.priority) {
4190
+ this.warn = (message, ...optionalParams) => {
4191
+ const loggingContext = this.ensureDurableLoggingContext();
4192
+ const params = message !== undefined ? [message, ...optionalParams] : optionalParams;
4193
+ this.consoleLogger.warn(formatDurableLogData(DurableLogLevel.WARN, loggingContext.getDurableLogData(), ...params));
4194
+ };
4195
+ }
4196
+ if (levels.ERROR.priority >= lambdaLogLevel.priority) {
4197
+ this.error = (message, ...optionalParams) => {
4198
+ const loggingContext = this.ensureDurableLoggingContext();
4199
+ const params = message !== undefined ? [message, ...optionalParams] : optionalParams;
4200
+ this.consoleLogger.error(formatDurableLogData(DurableLogLevel.ERROR, loggingContext.getDurableLogData(), ...params));
4201
+ };
4202
+ }
4203
+ }
4204
+ ensureDurableLoggingContext() {
4205
+ const context = this.executionContext;
4206
+ if (!this.durableLoggingContext && !context) {
4207
+ throw new Error("DurableLoggingContext is not configured. Please call configureDurableLoggingContext before logging.");
4208
+ }
4209
+ if (this.durableLoggingContext) {
4210
+ return this.durableLoggingContext;
4211
+ }
4212
+ if (!context) {
4213
+ throw new Error("Execution context is not provided.");
4214
+ }
4215
+ return {
4216
+ getDurableLogData: () => {
4217
+ return {
4218
+ requestId: context.requestId,
4219
+ executionArn: context.durableExecutionArn,
4220
+ tenantId: context.tenantId,
4221
+ };
4222
+ },
4223
+ };
4224
+ }
4225
+ log(level, message, ...optionalParams) {
4226
+ switch (level) {
4227
+ case DurableLogLevel.DEBUG:
4228
+ this.debug(message, ...optionalParams);
4229
+ break;
4230
+ case DurableLogLevel.INFO:
4231
+ this.info(message, ...optionalParams);
4232
+ break;
4233
+ case DurableLogLevel.WARN:
4234
+ this.warn(message, ...optionalParams);
4235
+ break;
4236
+ case DurableLogLevel.ERROR:
4237
+ this.error(message, ...optionalParams);
4238
+ break;
4239
+ default:
4240
+ this.info(message, ...optionalParams);
4241
+ break;
4242
+ }
4243
+ }
4244
+ // These method signatures will be set dynamically in configureLogLevel()
4245
+ info;
4246
+ error;
4247
+ warn;
4248
+ debug;
4249
+ configureDurableLoggingContext(durableLoggingContext) {
4250
+ this.durableLoggingContext = durableLoggingContext;
4251
+ }
4252
+ }
4253
+ /**
4254
+ * Creates a default logger that outputs structured logs to console.
4255
+ *
4256
+ * @param executionContext - Optional execution context for logging
4257
+ * @returns DefaultLogger instance
4258
+ */
4259
+ const createDefaultLogger = (executionContext) => {
4260
+ return new DefaultLogger(executionContext);
4261
+ };
4262
+
4263
+ /**
4264
+ * Tracks active async operations to prevent premature termination
4265
+ */
4266
+ class ActiveOperationsTracker {
4267
+ activeCount = 0;
4268
+ /**
4269
+ * Increment the counter when starting an async operation
4270
+ */
4271
+ increment() {
4272
+ this.activeCount++;
4273
+ }
4274
+ /**
4275
+ * Decrement the counter when an async operation completes
4276
+ */
4277
+ decrement() {
4278
+ this.activeCount = Math.max(0, this.activeCount - 1);
4279
+ }
4280
+ /**
4281
+ * Check if there are any active operations
4282
+ */
4283
+ hasActive() {
4284
+ return this.activeCount > 0;
4285
+ }
4286
+ /**
4287
+ * Get the current count of active operations
4288
+ */
4289
+ getCount() {
4290
+ return this.activeCount;
4291
+ }
4292
+ /**
4293
+ * Reset the counter (useful for testing)
4294
+ */
4295
+ reset() {
4296
+ this.activeCount = 0;
4297
+ }
4298
+ }
4299
+
4300
+ let defaultLambdaClient;
4301
+ /**
4302
+ * Durable execution client which uses an API-based LambdaClient
4303
+ * with built-in error logging. By default, the Lambda client will
4304
+ * have custom timeouts set.
4305
+ *
4306
+ * @public
4307
+ */
4308
+ class DurableExecutionApiClient {
4309
+ client;
4310
+ constructor(client) {
4311
+ if (!client) {
4312
+ if (!defaultLambdaClient) {
4313
+ defaultLambdaClient = new LambdaClient({
4314
+ requestHandler: {
4315
+ connectionTimeout: 5000,
4316
+ socketTimeout: 50000,
4317
+ requestTimeout: 55000,
4318
+ throwOnRequestTimeout: true,
4319
+ },
4320
+ });
4321
+ }
4322
+ this.client = defaultLambdaClient;
4323
+ }
4324
+ else {
4325
+ this.client = client;
4326
+ }
4327
+ }
4328
+ /**
4329
+ * Gets operation state data from the durable execution
4330
+ * @param params - The GetDurableExecutionState request
4331
+ * @param logger - Optional developer logger for error reporting
4332
+ * @returns Response with operations data
4333
+ */
4334
+ async getExecutionState(params, logger) {
4335
+ try {
4336
+ const response = await this.client.send(new GetDurableExecutionStateCommand({
4337
+ DurableExecutionArn: params.DurableExecutionArn,
4338
+ CheckpointToken: params.CheckpointToken,
4339
+ Marker: params.Marker,
4340
+ MaxItems: params.MaxItems,
4341
+ }));
4342
+ return response;
4343
+ }
4344
+ catch (error) {
4345
+ // Internal debug logging
4346
+ log("❌", "GetDurableExecutionState failed", {
4347
+ error,
4348
+ requestId: error?.$metadata
4349
+ ?.requestId,
4350
+ DurableExecutionArn: params.DurableExecutionArn,
4351
+ CheckpointToken: params.CheckpointToken,
4352
+ Marker: params.Marker,
4353
+ });
4354
+ // Developer logging if logger provided
4355
+ if (logger) {
4356
+ logger.error("Failed to get durable execution state", error, {
4357
+ requestId: error
4358
+ ?.$metadata?.requestId,
4359
+ });
4360
+ }
4361
+ throw error;
4362
+ }
4363
+ }
4364
+ /**
4365
+ * Checkpoints the durable execution with operation updates
4366
+ * @param params - The checkpoint request
4367
+ * @param logger - Optional developer logger for error reporting
4368
+ * @returns Checkpoint response
4369
+ */
4370
+ async checkpoint(params, logger) {
4371
+ try {
4372
+ const response = await this.client.send(new CheckpointDurableExecutionCommand({
4373
+ DurableExecutionArn: params.DurableExecutionArn,
4374
+ CheckpointToken: params.CheckpointToken,
4375
+ ClientToken: params.ClientToken,
4376
+ Updates: params.Updates,
4377
+ }));
4378
+ return response;
4379
+ }
4380
+ catch (error) {
4381
+ // Internal debug logging
4382
+ log("❌", "CheckpointDurableExecution failed", {
4383
+ error,
4384
+ requestId: error?.$metadata
4385
+ ?.requestId,
4386
+ DurableExecutionArn: params.DurableExecutionArn,
4387
+ CheckpointToken: params.CheckpointToken,
4388
+ ClientToken: params.ClientToken,
4389
+ });
4390
+ // Developer logging if logger provided
4391
+ if (logger) {
4392
+ logger.error("Failed to checkpoint durable execution", error, {
4393
+ requestId: error
4394
+ ?.$metadata?.requestId,
4395
+ });
4396
+ }
4397
+ throw error;
4398
+ }
4399
+ }
4400
+ }
4401
+
4402
+ /**
4403
+ * Custom DurableExecutionInvocationInput which uses a custom durable
4404
+ * execution client instead of the API-based LambdaClient.
4405
+ *
4406
+ * @internal
4407
+ */
4408
+ class DurableExecutionInvocationInputWithClient {
4409
+ durableExecutionClient;
4410
+ InitialExecutionState;
4411
+ DurableExecutionArn;
4412
+ CheckpointToken;
4413
+ constructor(params, durableExecutionClient) {
4414
+ this.durableExecutionClient = durableExecutionClient;
4415
+ this.InitialExecutionState = params.InitialExecutionState;
4416
+ this.DurableExecutionArn = params.DurableExecutionArn;
4417
+ this.CheckpointToken = params.CheckpointToken;
4418
+ }
4419
+ }
4420
+
4421
+ const initializeExecutionContext = async (event, context, lambdaClient) => {
4422
+ log("🔵", "Initializing durable function with event:", event);
4423
+ log("📍", "Function Input:", event);
4424
+ const checkpointToken = event.CheckpointToken;
4425
+ const durableExecutionArn = event.DurableExecutionArn;
4426
+ const durableExecutionClient =
4427
+ // Allow passing arbitrary durable clients if the input is a custom class
4428
+ event instanceof DurableExecutionInvocationInputWithClient
4429
+ ? event.durableExecutionClient
4430
+ : new DurableExecutionApiClient(lambdaClient);
4431
+ // Create logger for initialization errors using existing logger factory
4432
+ const initLogger = createDefaultLogger({
4433
+ durableExecutionArn,
4434
+ requestId: context.awsRequestId,
4435
+ tenantId: context.tenantId,
4436
+ });
4437
+ const operationsArray = [...(event.InitialExecutionState.Operations || [])];
4438
+ let nextMarker = event.InitialExecutionState.NextMarker;
4439
+ while (nextMarker) {
4440
+ const response = await durableExecutionClient.getExecutionState({
4441
+ CheckpointToken: checkpointToken,
4442
+ Marker: nextMarker,
4443
+ DurableExecutionArn: durableExecutionArn,
4444
+ MaxItems: 1000,
4445
+ }, initLogger);
4446
+ operationsArray.push(...(response.Operations || []));
4447
+ nextMarker = response.NextMarker || "";
4448
+ }
4449
+ // Determine replay mode based on operations array length
4450
+ const durableExecutionMode = operationsArray.length > 1
4451
+ ? DurableExecutionMode.ReplayMode
4452
+ : DurableExecutionMode.ExecutionMode;
4453
+ log("📝", "Operations:", operationsArray);
4454
+ const stepData = operationsArray.reduce((acc, operation) => {
4455
+ if (operation.Id) {
4456
+ // The stepData received from backend has Id and ParentId as hash, so no need to hash it again
4457
+ acc[operation.Id] = operation;
4458
+ }
4459
+ return acc;
4460
+ }, {});
4461
+ log("📝", "Loaded step data:", stepData);
4462
+ return {
4463
+ executionContext: {
4464
+ durableExecutionClient,
4465
+ _stepData: stepData,
4466
+ terminationManager: new TerminationManager(),
4467
+ activeOperationsTracker: new ActiveOperationsTracker(),
4468
+ durableExecutionArn,
4469
+ pendingCompletions: new Set(),
4470
+ getStepData(stepId) {
4471
+ return getStepData(stepData, stepId);
4472
+ },
4473
+ tenantId: context.tenantId,
4474
+ requestId: context.awsRequestId,
4475
+ },
4476
+ durableExecutionMode,
4477
+ checkpointToken,
4478
+ };
4479
+ };
4480
+
4481
+ // Lambda response size limit is 6MB
4482
+ const LAMBDA_RESPONSE_SIZE_LIMIT = 6 * 1024 * 1024 - 50; // 6MB in bytes, minus 50 bytes for envelope
4483
+ async function runHandler(event, context, executionContext, durableExecutionMode, checkpointToken, handler) {
4484
+ // Create checkpoint manager and step data emitter
4485
+ const stepDataEmitter = new EventEmitter();
4486
+ const checkpointManager = new CheckpointManager(executionContext.durableExecutionArn, executionContext._stepData, executionContext.durableExecutionClient, executionContext.terminationManager, executionContext.activeOperationsTracker, checkpointToken, stepDataEmitter, createDefaultLogger(executionContext), executionContext.pendingCompletions);
4487
+ // Set the checkpoint terminating callback on the termination manager
4488
+ executionContext.terminationManager.setCheckpointTerminatingCallback(() => {
4489
+ checkpointManager.setTerminating();
4490
+ });
4491
+ const durableExecution = {
4492
+ checkpointManager,
4493
+ stepDataEmitter,
4494
+ setTerminating: () => checkpointManager.setTerminating(),
4495
+ };
4496
+ const durableContext = createDurableContext(executionContext, context, durableExecutionMode,
4497
+ // Default logger may not have the same type as Logger, but we should always provide a default logger even if the user overrides it
4498
+ createDefaultLogger(), undefined, durableExecution);
4499
+ // Extract customerHandlerEvent from the original event
4500
+ const initialExecutionEvent = event.InitialExecutionState.Operations?.[0];
4501
+ const customerHandlerEvent = JSON.parse(initialExecutionEvent?.ExecutionDetails?.InputPayload ?? "{}");
4502
+ try {
4503
+ log("🎯", `Starting handler execution, handler event: ${customerHandlerEvent}`);
4504
+ let handlerPromiseResolved = false;
4505
+ let terminationPromiseResolved = false;
4506
+ const handlerPromise = runWithContext("root", undefined, () => handler(customerHandlerEvent, durableContext)).then((result) => {
4507
+ handlerPromiseResolved = true;
4508
+ log("🏆", "Handler promise resolved first!");
4509
+ return ["handler", result];
4510
+ });
4511
+ const terminationPromise = executionContext.terminationManager
4512
+ .getTerminationPromise()
4513
+ .then((result) => {
4514
+ terminationPromiseResolved = true;
4515
+ log("💥", "Termination promise resolved first!");
4516
+ // Set checkpoint manager as terminating when termination starts
4517
+ durableExecution.setTerminating();
4518
+ return ["termination", result];
4519
+ });
4520
+ // Set up a timeout to log the state of promises after a short delay
4521
+ setTimeout(() => {
4522
+ log("⏱️", "Promise race status check:", {
4523
+ handlerResolved: handlerPromiseResolved,
4524
+ terminationResolved: terminationPromiseResolved,
4525
+ });
4526
+ }, 500);
4527
+ const [resultType, result] = await Promise.race([
4528
+ handlerPromise,
4529
+ terminationPromise,
4530
+ ]);
4531
+ log("🏁", "Promise race completed with:", {
4532
+ resultType,
4533
+ });
4534
+ // Wait for all pending checkpoints to complete
4535
+ try {
4536
+ await durableExecution.checkpointManager.waitForQueueCompletion();
4537
+ log("✅", "All pending checkpoints completed");
4538
+ }
4539
+ catch (error) {
4540
+ log("⚠️", "Error waiting for checkpoint completion:", error);
4541
+ }
4542
+ // If termination was due to checkpoint failure, throw the appropriate error
4543
+ if (resultType === "termination" &&
4544
+ result.reason === TerminationReason.CHECKPOINT_FAILED) {
4545
+ log("🛑", "Checkpoint failed - handling termination");
4546
+ // checkpoint.ts always provides classified error
4547
+ throw result.error;
4548
+ }
4549
+ // If termination was due to serdes failure, throw an error to terminate the Lambda
4550
+ if (resultType === "termination" &&
4551
+ result.reason === TerminationReason.SERDES_FAILED) {
4552
+ log("🛑", "Serdes failed - terminating Lambda execution");
4553
+ throw new SerdesFailedError(result.message);
4554
+ }
4555
+ // If termination was due to context validation error, return FAILED
4556
+ if (resultType === "termination" &&
4557
+ result.reason === TerminationReason.CONTEXT_VALIDATION_ERROR) {
4558
+ log("🛑", "Context validation error - returning FAILED status");
4559
+ return {
4560
+ Status: InvocationStatus.FAILED,
4561
+ Error: createErrorObjectFromError(result.error || new Error(result.message)),
4562
+ };
4563
+ }
4564
+ if (resultType === "termination") {
4565
+ log("🛑", "Returning termination response");
4566
+ return {
4567
+ Status: InvocationStatus.PENDING,
4568
+ };
4569
+ }
4570
+ log("✅", "Returning normal completion response");
4571
+ // Stringify the result once to avoid multiple JSON.stringify calls
4572
+ const serializedResult = JSON.stringify(result);
4573
+ const serializedSize = new TextEncoder().encode(serializedResult).length;
4574
+ // Check if the response size exceeds the Lambda limit
4575
+ // Note: JSON.stringify(undefined) returns undefined, so we need to handle that case
4576
+ if (serializedResult && serializedSize > LAMBDA_RESPONSE_SIZE_LIMIT) {
4577
+ log("📦", `Response size (${serializedSize} bytes) exceeds Lambda limit (${LAMBDA_RESPONSE_SIZE_LIMIT} bytes). Checkpointing result.`);
4578
+ // Create a checkpoint to save the large result
4579
+ const stepId = `execution-result-${Date.now()}`;
4580
+ try {
4581
+ await durableExecution.checkpointManager.checkpoint(stepId, {
4582
+ Id: stepId,
4583
+ Action: "SUCCEED",
4584
+ Type: OperationType.EXECUTION,
4585
+ Payload: serializedResult, // Reuse the already serialized result
4586
+ });
4587
+ log("✅", "Large result successfully checkpointed");
4588
+ // Return a response indicating the result was checkpointed
4589
+ return {
4590
+ Status: InvocationStatus.SUCCEEDED,
4591
+ Result: "",
4592
+ };
4593
+ }
4594
+ catch (checkpointError) {
4595
+ log("❌", "Failed to checkpoint large result:", checkpointError);
4596
+ // Re-throw - checkpoint.ts always classifies errors before terminating
4597
+ throw checkpointError;
4598
+ }
4599
+ }
4600
+ // If response size is acceptable, return the response
4601
+ return {
4602
+ Status: InvocationStatus.SUCCEEDED,
4603
+ Result: serializedResult,
4604
+ };
4605
+ }
4606
+ catch (error) {
4607
+ log("❌", "Handler threw an error:", error);
4608
+ // Check if this is an unrecoverable invocation error (includes checkpoint invocation failures)
4609
+ if (isUnrecoverableInvocationError(error)) {
4610
+ log("🛑", "Unrecoverable invocation error - terminating Lambda execution");
4611
+ throw error; // Re-throw the error to terminate Lambda execution
4612
+ }
4613
+ return {
4614
+ Status: InvocationStatus.FAILED,
4615
+ Error: createErrorObjectFromError(error),
4616
+ };
4617
+ }
4618
+ }
4619
+ /**
4620
+ * Validates that the event is a proper durable execution input
4621
+ */
4622
+ function validateDurableExecutionEvent(event) {
4623
+ try {
4624
+ const eventObj = event;
4625
+ if (!eventObj?.DurableExecutionArn || !eventObj?.CheckpointToken) {
4626
+ throw new Error("Missing required durable execution fields");
4627
+ }
4628
+ }
4629
+ catch {
4630
+ const msg = `Unexpected payload provided to start the durable execution.
4631
+ Check your resource configurations to confirm the durability is set.`;
4632
+ throw new Error(msg);
4633
+ }
4634
+ }
4635
+ /**
4636
+ * Wraps a durable handler function to create a handler with automatic state persistence,
4637
+ * retry logic, and workflow orchestration capabilities.
4638
+ *
4639
+ * This function transforms your durable handler into a function that integrates
4640
+ * with the AWS Durable Execution service. The wrapped handler automatically manages execution state
4641
+ * and checkpointing.
4642
+ *
4643
+ * @typeParam TEvent - The type of the input event your handler expects (defaults to any)
4644
+ * @typeParam TResult - The type of the result your handler returns (defaults to any)
4645
+ * @typeParam TLogger - The type of custom logger implementation (defaults to DurableLogger)
4646
+ *
4647
+ * @param handler - Your durable handler function that uses the DurableContext for operations
4648
+ * @param config - Optional configuration for custom advanced settings
4649
+ *
4650
+ * @returns A handler function that automatically manages durability
4651
+ *
4652
+ * @example
4653
+ * **Basic Usage:**
4654
+ * ```typescript
4655
+ * import { withDurableExecution, DurableExecutionHandler } from '@aws/durable-execution-sdk-js';
4656
+ *
4657
+ * const durableHandler: DurableExecutionHandler<MyEvent, MyResult> = async (event, context) => {
4658
+ * // Execute durable operations with automatic retry and checkpointing
4659
+ * const userData = await context.step("fetch-user", async () =>
4660
+ * fetchUserFromDB(event.userId)
4661
+ * );
4662
+ *
4663
+ * // Wait for external approval
4664
+ * const approval = await context.waitForCallback("user-approval", async (callbackId) => {
4665
+ * await sendApprovalEmail(callbackId, userData);
4666
+ * });
4667
+ *
4668
+ * // Process in parallel
4669
+ * const results = await context.parallel("process-data", [
4670
+ * async (ctx) => ctx.step("validate", () => validateData(userData)),
4671
+ * async (ctx) => ctx.step("transform", () => transformData(userData))
4672
+ * ]);
4673
+ *
4674
+ * return { success: true, results };
4675
+ * };
4676
+ *
4677
+ * export const handler = withDurableExecution(durableHandler);
4678
+ * ```
4679
+ *
4680
+ * @example
4681
+ * **With Custom Configuration:**
4682
+ * ```typescript
4683
+ * import { LambdaClient } from '@aws-sdk/client-lambda';
4684
+ *
4685
+ * const customClient = new LambdaClient({
4686
+ * region: 'us-west-2',
4687
+ * maxAttempts: 5
4688
+ * });
4689
+ *
4690
+ * export const handler = withDurableExecution(durableHandler, {
4691
+ * client: customClient
4692
+ * });
4693
+ * ```
4694
+ *
4695
+ * @example
4696
+ * **Passed Directly to the Handler:**
4697
+ * ```typescript
4698
+ * export const handler = withDurableExecution(async (event, context) => {
4699
+ * const result = await context.step(async () => processEvent(event));
4700
+ * return result;
4701
+ * });
4702
+ * ```
4703
+ *
4704
+ * @public
4705
+ */
4706
+ const withDurableExecution = (handler, config) => {
4707
+ return async (event, context) => {
4708
+ validateDurableExecutionEvent(event);
4709
+ const { executionContext, durableExecutionMode, checkpointToken } = await initializeExecutionContext(event, context, config?.client);
4710
+ let response = null;
4711
+ try {
4712
+ response = await runHandler(event, context, executionContext, durableExecutionMode, checkpointToken, handler);
4713
+ return response;
4714
+ }
4715
+ catch (err) {
4716
+ throw err;
4717
+ }
4718
+ };
4719
+ };
4720
+
4721
+ const DEFAULT_CONFIG = {
4722
+ maxAttempts: 60,
4723
+ initialDelay: { seconds: 5 },
4724
+ maxDelay: { seconds: 300 }, // 5 minutes
4725
+ backoffRate: 1.5,
4726
+ jitter: JitterStrategy.FULL,
4727
+ timeoutSeconds: undefined, // No timeout by default
4728
+ };
4729
+ const applyJitter = (delay, strategy) => {
4730
+ switch (strategy) {
4731
+ case JitterStrategy.NONE:
4732
+ return delay;
4733
+ case JitterStrategy.FULL:
4734
+ // Random between 0 and delay
4735
+ return Math.random() * delay;
4736
+ case JitterStrategy.HALF:
4737
+ // Random between delay/2 and delay
4738
+ return delay / 2 + Math.random() * (delay / 2);
4739
+ }
4740
+ };
4741
+ /**
4742
+ * @public
4743
+ */
4744
+ const createWaitStrategy = (config) => {
4745
+ const finalConfig = {
4746
+ ...DEFAULT_CONFIG,
4747
+ ...config,
4748
+ };
4749
+ return (result, attemptsMade) => {
4750
+ // Check if condition is met
4751
+ if (!finalConfig.shouldContinuePolling(result)) {
4752
+ return { shouldContinue: false };
4753
+ }
4754
+ // Check if we've exceeded max attempts
4755
+ if (attemptsMade >= finalConfig.maxAttempts) {
4756
+ throw new Error(`waitForCondition exceeded maximum attempts (${finalConfig.maxAttempts})`);
4757
+ }
4758
+ // Calculate delay with exponential backoff
4759
+ const initialDelaySeconds = durationToSeconds(finalConfig.initialDelay);
4760
+ const maxDelaySeconds = durationToSeconds(finalConfig.maxDelay);
4761
+ const baseDelay = Math.min(initialDelaySeconds * Math.pow(finalConfig.backoffRate, attemptsMade - 1), maxDelaySeconds);
4762
+ // Apply jitter
4763
+ const delayWithJitter = applyJitter(baseDelay, finalConfig.jitter);
4764
+ // Ensure delay is an integer >= 1
4765
+ const finalDelay = Math.max(1, Math.round(delayWithJitter));
4766
+ return { shouldContinue: true, delay: { seconds: finalDelay } };
4767
+ };
4768
+ };
4769
+
4770
+ export { BatchItemStatus, CallbackError, ChildContextError, DurableExecutionApiClient, DurableExecutionInvocationInputWithClient, DurableOperationError, DurablePromise, InvocationStatus, InvokeError, JitterStrategy, OperationSubType, StepError, StepInterruptedError, StepSemantics, WaitForConditionError, createClassSerdes, createClassSerdesWithDates, createRetryStrategy, createWaitStrategy, defaultSerdes, retryPresets, withDurableExecution };
4771
+ //# sourceMappingURL=index.mjs.map