@aws/durable-execution-sdk-js 0.0.1 → 1.0.1

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