inngest 3.52.2 → 3.52.3

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # inngest
2
2
 
3
+ ## 3.52.3
4
+
5
+ ### Patch Changes
6
+
7
+ - [#1329](https://github.com/inngest/inngest-js/pull/1329) [`d079c0be`](https://github.com/inngest/inngest-js/commit/d079c0be84ab43995d84ee8681dda6462d281b58) Thanks [@Linell](https://github.com/Linell)! - fix: flush checkpoint buffer
8
+
3
9
  ## 3.52.2
4
10
 
5
11
  ### Patch Changes
package/api/schema.d.cts CHANGED
@@ -7,11 +7,11 @@ declare const errorSchema: z.ZodObject<{
7
7
  error: z.ZodString;
8
8
  status: z.ZodNumber;
9
9
  }, "strip", z.ZodTypeAny, {
10
- status: number;
11
10
  error: string;
12
- }, {
13
11
  status: number;
12
+ }, {
14
13
  error: string;
14
+ status: number;
15
15
  }>;
16
16
  type ErrorResponse = z.infer<typeof errorSchema>;
17
17
  declare const stepsSchemas: {
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.cts","names":[],"sources":["../../src/api/schema.ts"],"sourcesContent":[],"mappings":";;;;;cAIa,aAAW,CAAA,CAAA;;EAAX,MAAA,aAGX;CAAA,EAAA,OAAA,cAAA,EAAA;;;;QAHsB,EAAA,MAAA;EAAA,KAAA,EAAA,MAAA;AAIxB,CAAA,CAAA;AAAyB,KAAb,aAAA,GAAgB,CAAA,CAAE,KAAL,CAAA,OAAkB,WAAlB,CAAA;AAAkB,cAsD9B,YAtD8B,EAAA;kBAAb,cAAA,YAAA,YAAA,cAAA,SAAA,EAAA,GAAA,EAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAK,CAAA,cAAA,YAAA,YAAA,YAAA,CAAA,WAAA,CAAA,WAAA,CAAA,YAAA,CAAA;IAsDtB,IAAA,cAIoC,cAAA,aAAA,CAAA,MAAA,CAAA,CAAA,CAAA;IAAA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A;EAAK,CAAA,CAAA,CAAA,CAAA,cAAA,SAAA,EAAA;;;;;KAPvB,aAAA,WACJ,mBAAmB,CAAA,CAAE,cAAc,cAAc,MACvD;cAEW,aAAW,CAAA,CAAA,SAAA,CAAA,CAAA,WAAA,CAAA,CAAA,UAAA,CAAA,CAAA,WAAA,CAAA,CAAA,SAAA,mBAAA;KAGZ,aAAA,GAAgB,CAAA,CAAE,aAAa"}
package/api/schema.d.ts CHANGED
@@ -7,11 +7,11 @@ declare const errorSchema: z.ZodObject<{
7
7
  error: z.ZodString;
8
8
  status: z.ZodNumber;
9
9
  }, "strip", z.ZodTypeAny, {
10
- status: number;
11
10
  error: string;
12
- }, {
13
11
  status: number;
12
+ }, {
14
13
  error: string;
14
+ status: number;
15
15
  }>;
16
16
  type ErrorResponse = z.infer<typeof errorSchema>;
17
17
  declare const stepsSchemas: {
@@ -1 +1 @@
1
- {"version":3,"file":"schema.d.ts","names":[],"sources":["../../src/api/schema.ts"],"sourcesContent":[],"mappings":";;;;;cAIa,aAAW,CAAA,CAAA;;EAAX,MAAA,aAGX;CAAA,EAAA,OAAA,cAAA,EAAA;;;;QAHsB,EAAA,MAAA;EAAA,KAAA,EAAA,MAAA;AAIxB,CAAA,CAAA;AAAyB,KAAb,aAAA,GAAgB,CAAA,CAAE,KAAL,CAAA,OAAkB,WAAlB,CAAA;AAAkB,cAsD9B,YAtD8B,EAAA;kBAAb,cAAA,YAAA,YAAA,cAAA,SAAA,EAAA,GAAA,EAAA,GAAA,CAAA,CAAA,CAAA,CAAA;EAAK,CAAA,cAAA,YAAA,YAAA,YAAA,CAAA,WAAA,CAAA,WAAA,CAAA,YAAA,CAAA;IAsDtB,IAAA,cAIoC,cAAA,aAAA,CAAA,MAAA,CAAA,CAAA,CAAA;IAAA,IAAA,cAAA,SAAA,EAAA,GAAA,EAAA,GAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAA,SAAA,CAAA,CAAA,WAAA,CAAA,CAAA,UAAA,CAAA,CAAA,WAAA,CAAA,CAAA,SAAA,mBAAA;KAGZ,aAAA,GAAgB,CAAA,CAAE,aAAa"}
@@ -425,9 +425,13 @@ var V2InngestExecution = class extends require_InngestExecution.InngestExecution
425
425
  const stepResult = await this.tryExecuteStep(newSteps);
426
426
  if (stepResult) {
427
427
  this.debug(`executed step "${stepResult.id}" successfully`);
428
- if (stepResult.error) return stepRanHandler(stepResult);
428
+ if (stepResult.error) {
429
+ if (this.state.checkpointingStepBuffer.length) await attemptCheckpointAndResume(void 0, false, true);
430
+ return stepRanHandler(stepResult);
431
+ }
429
432
  return await attemptCheckpointAndResume(stepResult);
430
433
  }
434
+ if (this.state.checkpointingStepBuffer.length) await attemptCheckpointAndResume(void 0, false, true);
431
435
  return maybeReturnNewSteps(steps);
432
436
  }
433
437
  if (stepsToResume.length) {
@@ -1 +1 @@
1
- {"version":3,"file":"v2.cjs","names":["hashjs","createV2InngestExecution: InngestExecutionFactory","InngestExecution","ExecutionVersion","options: InngestExecutionOptions","StepMode","trace","version","getAsyncLocalStorage","headerKeys","retryWithBackoff","defaultMaxRetries","commonCheckpointHandler: CheckpointHandlers[StepMode][\"\"]","StepOpCode","serializeError","syncHandlers: CheckpointHandlers[StepMode.Sync]","asyncHandlers: CheckpointHandlers[StepMode.Async]","asyncCheckpointingHandlers: CheckpointHandlers[StepMode.AsyncCheckpointing]","step","getHookStack","internalEvents","invokePayloadSchema","outgoingOp: OutgoingOp","getAsyncCtx","interval: GoInterval | undefined","goIntervalTiming","runAsPromise","NonRetriableError","retriable: boolean | string","StepError","RetryAfterError","minifyPrettyError","undefinedToNull","createDeferredPromiseWithStack","loop: V2ExecutionState[\"loop\"]","z","jsonErrorSchema","deserializeError","foundStepsToReport: Map<string, FoundStep>","unhandledFoundStepsToReport: Map<string, FoundStep>","expectedNextStepIndexes: Map<string, number>","foundStepsReportPromise: Promise<void> | undefined","beforeExecHooksPromise: Promise<void> | undefined","resolveAfterPending","stepHandler: StepHandler","getStepOptions","ErrCode","prettyError","STEP_INDEXING_SUFFIX","createDeferredPromise","extraOpts: Record<string, unknown> | undefined","step: FoundStep","createStepTools","createTimeoutPromise"],"sources":["../../../src/components/execution/v2.ts"],"sourcesContent":["import { trace } from \"@opentelemetry/api\";\nimport hashjs from \"hash.js\";\nimport ms, { type StringValue } from \"ms\";\nimport { z } from \"zod/v3\";\nimport {\n defaultMaxRetries,\n ExecutionVersion,\n headerKeys,\n internalEvents,\n} from \"../../helpers/consts.ts\";\nimport {\n deserializeError,\n ErrCode,\n minifyPrettyError,\n prettyError,\n serializeError,\n} from \"../../helpers/errors.js\";\nimport { undefinedToNull } from \"../../helpers/functions.js\";\nimport {\n createDeferredPromise,\n createDeferredPromiseWithStack,\n createTimeoutPromise,\n type GoInterval,\n goIntervalTiming,\n resolveAfterPending,\n retryWithBackoff,\n runAsPromise,\n} from \"../../helpers/promises.ts\";\nimport * as Temporal from \"../../helpers/temporal.ts\";\nimport type { MaybePromise, Simplify } from \"../../helpers/types.ts\";\nimport {\n type APIStepPayload,\n type BaseContext,\n type Context,\n type EventPayload,\n type FailureEventArgs,\n type Handler,\n jsonErrorSchema,\n type OutgoingOp,\n StepMode,\n StepOpCode,\n} from \"../../types.ts\";\nimport { version } from \"../../version.ts\";\nimport type { Inngest } from \"../Inngest.ts\";\nimport type {\n MetadataKind,\n MetadataOpcode,\n MetadataScope,\n MetadataUpdate,\n} from \"../InngestMetadata.ts\";\nimport { getHookStack, type RunHookStack } from \"../InngestMiddleware.ts\";\nimport {\n createStepTools,\n type FoundStep,\n getStepOptions,\n invokePayloadSchema,\n STEP_INDEXING_SUFFIX,\n type StepHandler,\n} from \"../InngestStepTools.ts\";\nimport { NonRetriableError } from \"../NonRetriableError.ts\";\nimport { RetryAfterError } from \"../RetryAfterError.ts\";\nimport { StepError } from \"../StepError.ts\";\nimport { getAsyncCtx, getAsyncLocalStorage } from \"./als.ts\";\nimport {\n type BasicFoundStep,\n type ExecutionResult,\n type IInngestExecution,\n InngestExecution,\n type InngestExecutionFactory,\n type InngestExecutionOptions,\n type MemoizedOp,\n} from \"./InngestExecution.ts\";\nimport { clientProcessorMap } from \"./otel/access.ts\";\n\nconst { sha1 } = hashjs;\n\n/**\n * Retry configuration for checkpoint operations.\n *\n * Checkpoint calls use exponential backoff with jitter to handle transient\n * network failures (e.g., dev server temporarily down, cloud hiccup). If\n * retries exhaust, the error propagates up - for Sync mode this results in a\n * 500 error, for AsyncCheckpointing the caller handles fallback.\n */\nconst CHECKPOINT_RETRY_OPTIONS = { maxAttempts: 5, baseDelay: 100 };\nconst STEP_NOT_FOUND_MAX_FOUND_STEPS = 25;\n\nexport const createV2InngestExecution: InngestExecutionFactory = (options) => {\n return new V2InngestExecution(options);\n};\n\nclass V2InngestExecution extends InngestExecution implements IInngestExecution {\n public version = ExecutionVersion.V2;\n\n private state: V2ExecutionState;\n private fnArg: Context.Any;\n private checkpointHandlers: CheckpointHandlers;\n private timeoutDuration = 1000 * 10;\n private execution: Promise<ExecutionResult> | undefined;\n private userFnToRun: Handler.Any;\n\n /**\n * If we're supposed to run a particular step via `requestedRunStep`, this\n * will be a `Promise` that resolves after no steps have been found for\n * `timeoutDuration` milliseconds.\n *\n * If we're not supposed to run a particular step, this will be `undefined`.\n */\n private timeout?: ReturnType<typeof createTimeoutPromise>;\n\n /**\n * If we're checkpointing and have been given a maximum runtime, this will be\n * a `Promise` that resolves after that duration has elapsed, allowing us to\n * ensure that we end the execution in good time, especially in serverless\n * environments.\n */\n private checkpointingMaxRuntimeTimer?: ReturnType<\n typeof createTimeoutPromise\n >;\n\n /**\n * If we're checkpointing and have been given a maximum buffer interval, this\n * will be a `Promise` that resolves after that duration has elapsed, allowing\n * us to periodically checkpoint even if the step buffer hasn't filled.\n */\n private checkpointingMaxBufferIntervalTimer?: ReturnType<\n typeof createTimeoutPromise\n >;\n\n constructor(rawOptions: InngestExecutionOptions) {\n const options: InngestExecutionOptions = {\n ...rawOptions,\n stepMode: rawOptions.stepMode ?? StepMode.Async,\n };\n\n super(options);\n\n /**\n * Check we have everything we need for checkpointing\n */\n if (this.options.stepMode === StepMode.Sync) {\n if (!this.options.createResponse) {\n throw new Error(\"createResponse is required for sync step mode\");\n }\n }\n\n this.userFnToRun = this.getUserFnToRun();\n this.state = this.createExecutionState();\n this.fnArg = this.createFnArg();\n this.checkpointHandlers = this.createCheckpointHandlers();\n this.initializeTimer(this.state);\n this.initializeCheckpointRuntimeTimer(this.state);\n\n this.debug(\n \"created new V2 execution for run;\",\n this.options.requestedRunStep\n ? `wanting to run step \"${this.options.requestedRunStep}\"`\n : \"discovering steps\",\n );\n\n this.debug(\"existing state keys:\", Object.keys(this.state.stepState));\n }\n\n /**\n * Idempotently start the execution of the user's function.\n */\n public start() {\n if (!this.execution) {\n this.debug(\"starting V2 execution\");\n\n const tracer = trace.getTracer(\"inngest\", version);\n\n this.execution = getAsyncLocalStorage().then((als) => {\n return als.run(\n {\n app: this.options.client,\n execution: {\n ctx: this.fnArg,\n instance: this,\n },\n },\n async () => {\n return tracer.startActiveSpan(\"inngest.execution\", (span) => {\n clientProcessorMap.get(this.options.client)?.declareStartingSpan({\n span,\n runId: this.options.runId,\n traceparent: this.options.headers[headerKeys.TraceParent],\n tracestate: this.options.headers[headerKeys.TraceState],\n });\n\n return this._start()\n .then((result) => {\n this.debug(\"result:\", result);\n return result;\n })\n .finally(() => {\n span.end();\n });\n });\n },\n );\n });\n }\n\n return this.execution;\n }\n\n public addMetadata(\n stepId: string,\n kind: MetadataKind,\n scope: MetadataScope,\n op: MetadataOpcode,\n values: Record<string, unknown>,\n ) {\n if (!this.state.metadata) {\n this.state.metadata = new Map();\n }\n\n const updates = this.state.metadata.get(stepId) ?? [];\n updates.push({ kind, scope, op, values });\n this.state.metadata.set(stepId, updates);\n\n return true;\n }\n\n /**\n * Starts execution of the user's function and the core loop.\n */\n private async _start(): Promise<ExecutionResult> {\n try {\n const allCheckpointHandler = this.getCheckpointHandler(\"\");\n this.state.hooks = await this.initializeMiddleware();\n await this.startExecution();\n\n let i = 0;\n\n for await (const checkpoint of this.state.loop) {\n await allCheckpointHandler(checkpoint, i);\n\n const handler = this.getCheckpointHandler(checkpoint.type);\n const result = await handler(checkpoint, i++);\n\n if (result) {\n return result;\n }\n }\n } catch (error) {\n return await this.transformOutput({ error });\n } finally {\n void this.state.loop.return();\n await this.state.hooks?.beforeResponse?.();\n }\n\n /**\n * If we're here, the generator somehow finished without returning a value.\n * This should never happen.\n */\n throw new Error(\"Core loop finished without returning a value\");\n }\n\n private async checkpoint(steps: OutgoingOp[]): Promise<void> {\n if (this.options.stepMode === StepMode.Sync) {\n if (!this.state.checkpointedRun) {\n // We have to start the run\n const res = await retryWithBackoff(\n () =>\n this.options.client[\"inngestApi\"].checkpointNewRun({\n runId: this.fnArg.runId,\n event: this.fnArg.event as APIStepPayload,\n steps,\n executionVersion: this.version,\n retries: this.fnArg.maxAttempts ?? defaultMaxRetries,\n }),\n CHECKPOINT_RETRY_OPTIONS,\n );\n\n this.state.checkpointedRun = {\n appId: res.data.app_id,\n fnId: res.data.fn_id,\n token: res.data.token,\n };\n } else {\n await retryWithBackoff(\n () =>\n this.options.client[\"inngestApi\"].checkpointSteps({\n appId: this.state.checkpointedRun!.appId,\n fnId: this.state.checkpointedRun!.fnId,\n runId: this.fnArg.runId,\n steps,\n }),\n CHECKPOINT_RETRY_OPTIONS,\n );\n }\n } else if (this.options.stepMode === StepMode.AsyncCheckpointing) {\n if (!this.options.queueItemId) {\n throw new Error(\n \"Missing queueItemId for async checkpointing. This is a bug in the Inngest SDK.\",\n );\n }\n\n if (!this.options.internalFnId) {\n throw new Error(\n \"Missing internalFnId for async checkpointing. This is a bug in the Inngest SDK.\",\n );\n }\n\n await retryWithBackoff(\n () =>\n this.options.client[\"inngestApi\"].checkpointStepsAsync({\n runId: this.fnArg.runId,\n fnId: this.options.internalFnId!,\n queueItemId: this.options.queueItemId!,\n steps,\n }),\n CHECKPOINT_RETRY_OPTIONS,\n );\n } else {\n throw new Error(\n \"Checkpointing is only supported in Sync and AsyncCheckpointing step modes. This is a bug in the Inngest SDK.\",\n );\n }\n }\n\n private async checkpointAndSwitchToAsync(\n steps: OutgoingOp[],\n ): Promise<ExecutionResult> {\n await this.checkpoint(steps);\n\n if (!this.state.checkpointedRun?.token) {\n throw new Error(\"Failed to checkpoint and switch to async mode\");\n }\n\n return {\n type: \"change-mode\",\n ctx: this.fnArg,\n ops: this.ops,\n to: StepMode.Async,\n token: this.state.checkpointedRun?.token!,\n };\n }\n\n /**\n * Returns whether we're in the final attempt of execution, or `null` if we\n * can't determine this in the SDK.\n */\n private inFinalAttempt(): boolean | null {\n if (typeof this.fnArg.maxAttempts !== \"number\") {\n return null;\n }\n\n return this.fnArg.attempt + 1 >= this.fnArg.maxAttempts;\n }\n\n /**\n * Creates a handler for every checkpoint type, defining what to do when we\n * reach that checkpoint in the core loop.\n */\n private createCheckpointHandlers(): CheckpointHandlers {\n const commonCheckpointHandler: CheckpointHandlers[StepMode][\"\"] = (\n checkpoint,\n ) => {\n this.debug(`${this.options.stepMode} checkpoint:`, checkpoint);\n };\n\n const stepRanHandler = async (\n stepResult: OutgoingOp,\n ): Promise<ExecutionResult> => {\n const transformResult = await this.transformOutput(stepResult);\n\n /**\n * Transforming output will always return either function rejection or\n * resolution. In most cases, this can be immediately returned, but in\n * this particular case we want to handle it differently.\n */\n if (transformResult.type === \"function-resolved\") {\n return {\n type: \"step-ran\",\n ctx: transformResult.ctx,\n ops: transformResult.ops,\n step: {\n ...stepResult,\n data: transformResult.data,\n },\n };\n } else if (transformResult.type === \"function-rejected\") {\n const stepForResponse = {\n ...stepResult,\n error: transformResult.error,\n };\n\n if (stepResult.op === StepOpCode.StepFailed) {\n const ser = serializeError(transformResult.error);\n stepForResponse.data = {\n __serialized: true,\n name: ser.name,\n message: ser.message,\n stack: \"\",\n };\n }\n\n return {\n type: \"step-ran\",\n ctx: transformResult.ctx,\n ops: transformResult.ops,\n retriable: transformResult.retriable,\n step: stepForResponse,\n };\n }\n\n return transformResult;\n };\n\n const maybeReturnNewSteps = async (\n steps: FoundStep[],\n ): Promise<ExecutionResult | undefined> => {\n const newSteps = await this.filterNewSteps(Array.from(steps.values()));\n\n if (newSteps) {\n return {\n type: \"steps-found\",\n ctx: this.fnArg,\n ops: this.ops,\n steps: newSteps,\n };\n }\n\n return;\n };\n\n const attemptCheckpointAndResume = async (\n stepResult?: OutgoingOp,\n resume = true,\n force = false,\n ) => {\n // If we're here, we successfully ran a step, so we may now need\n // to checkpoint it depending on the step buffer configured.\n if (stepResult) {\n const stepToResume = this.resumeStepWithResult(stepResult, resume);\n\n // Transform data for checkpoint (middleware)\n // Only call the transformOutput hook directly, not the full transformOutput method\n // which has side effects like calling the finished hook\n const transformedOutput = await this.state.hooks?.transformOutput?.({\n result: { data: stepResult.data },\n step: stepResult,\n });\n const transformedData =\n transformedOutput?.result?.data ?? stepResult.data;\n\n // Buffer a copy with transformed data for checkpointing\n this.state.checkpointingStepBuffer.push({\n ...stepToResume,\n data: transformedData,\n });\n }\n\n if (\n force ||\n !this.options.checkpointingConfig?.bufferedSteps ||\n this.state.checkpointingStepBuffer.length >=\n this.options.checkpointingConfig.bufferedSteps\n ) {\n this.debug(\"checkpointing and resuming execution after step run\");\n\n try {\n this.debug(\n `checkpointing all buffered steps:`,\n this.state.checkpointingStepBuffer\n .map((op) => op.displayName || op.id)\n .join(\", \"),\n );\n\n return void (await this.checkpoint(\n this.state.checkpointingStepBuffer,\n ));\n } catch (err) {\n // If checkpointing fails for any reason, fall back to the async\n // flow\n this.debug(\n \"error checkpointing after step run, so falling back to async\",\n err,\n );\n\n if (stepResult) {\n return stepRanHandler(stepResult);\n }\n } finally {\n // Clear the checkpointing buffer\n this.state.checkpointingStepBuffer = [];\n }\n } else {\n this.debug(\n `not checkpointing yet, continuing execution as we haven't reached buffered step limit of ${this.options.checkpointingConfig?.bufferedSteps}`,\n );\n }\n\n return;\n };\n\n const syncHandlers: CheckpointHandlers[StepMode.Sync] = {\n /**\n * Run for all checkpoints. Best used for logging or common actions.\n * Use other handlers to return values and interrupt the core loop.\n */\n \"\": commonCheckpointHandler,\n\n \"function-resolved\": async (checkpoint, i) => {\n // Transform data for checkpoint (middleware)\n // Only call the transformOutput hook directly, not the full transformOutput method\n // which has side effects like calling the finished hook\n const transformedOutput = await this.state.hooks?.transformOutput?.({\n result: { data: checkpoint.data },\n step: this.state.executingStep,\n });\n const transformedData =\n transformedOutput?.result?.data ?? checkpoint.data;\n\n await this.checkpoint([\n {\n op: StepOpCode.RunComplete,\n id: _internals.hashId(\"complete\"), // ID is not important here\n data: await this.options.createResponse!(transformedData),\n },\n ]);\n\n // Apply middleware transformation before returning\n return await this.transformOutput({ data: checkpoint.data });\n },\n\n \"function-rejected\": async (checkpoint) => {\n // If the function throws during sync execution, we want to switch to\n // async mode so that we can retry. The exception is that we're already\n // at max attempts, in which case we do actually want to reject.\n if (this.inFinalAttempt()) {\n // Apply middleware transformation before returning\n return await this.transformOutput({ error: checkpoint.error });\n }\n\n // Otherwise, checkpoint the error and switch to async mode\n return this.checkpointAndSwitchToAsync([\n {\n id: _internals.hashId(\"complete\"), // ID is not important here\n op: StepOpCode.StepError,\n error: checkpoint.error,\n },\n ]);\n },\n\n \"step-not-found\": () => {\n return {\n type: \"function-rejected\",\n ctx: this.fnArg,\n error: new Error(\n \"Step not found when checkpointing; this should never happen\",\n ),\n ops: this.ops,\n retriable: false,\n };\n },\n\n \"steps-found\": async ({ steps }) => {\n // If we're entering parallelism or async mode, checkpoint and switch\n // to async.\n if (steps.length !== 1 || steps[0].mode !== StepMode.Sync) {\n return this.checkpointAndSwitchToAsync(\n steps.map((step) => ({ ...step, id: step.hashedId })),\n );\n }\n\n // Otherwise we're good to start executing things right now.\n const result = await this.executeStep(steps[0]);\n\n const transformed = await stepRanHandler(result);\n if (transformed.type !== \"step-ran\") {\n throw new Error(\n \"Unexpected checkpoint handler result type after running step in sync mode\",\n );\n }\n\n if (result.error) {\n return this.checkpointAndSwitchToAsync([transformed.step]);\n }\n\n // Resume the step with original data for user code\n //\n // Note: We should likely also pass this through `transformOutput` and\n // then `transformInput` to mimic the entire middleware cycle, to ensure\n // that any transformations that purposefully skew the resulting type\n // are supported.\n const stepToResume = this.resumeStepWithResult(result);\n\n // Checkpoint with transformed data from middleware\n const stepForCheckpoint = {\n ...stepToResume,\n data: transformed.step.data,\n };\n\n return void (await this.checkpoint([stepForCheckpoint]));\n },\n\n \"checkpointing-runtime-reached\": () => {\n return this.checkpointAndSwitchToAsync([\n {\n op: StepOpCode.DiscoveryRequest,\n id: _internals.hashId(\"discovery-request\"), // ID doesn't matter\n },\n ]);\n },\n\n \"checkpointing-buffer-interval-reached\": () => {\n return attemptCheckpointAndResume(undefined, false, true);\n },\n };\n\n const asyncHandlers: CheckpointHandlers[StepMode.Async] = {\n /**\n * Run for all checkpoints. Best used for logging or common actions.\n * Use other handlers to return values and interrupt the core loop.\n */\n \"\": commonCheckpointHandler,\n\n /**\n * The user's function has completed and returned a value.\n */\n \"function-resolved\": async ({ data }) => {\n // We need to do this even here for async, as we could be returning\n // data from an API endpoint, even if we were triggered async.\n if (this.options.createResponse) {\n data = await this.options.createResponse(data);\n }\n\n return await this.transformOutput({ data });\n },\n\n /**\n * The user's function has thrown an error.\n */\n \"function-rejected\": async (checkpoint) => {\n return await this.transformOutput({ error: checkpoint.error });\n },\n\n /**\n * We've found one or more steps. Here we may want to run a step or report\n * them back to Inngest.\n */\n \"steps-found\": async ({ steps }) => {\n const stepResult = await this.tryExecuteStep(steps);\n if (stepResult) {\n return stepRanHandler(stepResult);\n }\n\n return maybeReturnNewSteps(steps);\n },\n\n /**\n * While trying to find a step that Inngest has told us to run, we've\n * timed out or have otherwise decided that it doesn't exist.\n */\n \"step-not-found\": ({ step, foundSteps, totalFoundSteps }) => {\n return {\n type: \"step-not-found\",\n ctx: this.fnArg,\n ops: this.ops,\n step,\n foundSteps,\n totalFoundSteps,\n };\n },\n\n \"checkpointing-runtime-reached\": () => {\n throw new Error(\n \"Checkpointing maximum runtime reached, but this is not in a checkpointing step mode. This is a bug in the Inngest SDK.\",\n );\n },\n\n \"checkpointing-buffer-interval-reached\": () => {\n throw new Error(\n \"Checkpointing maximum buffer interval reached, but this is not in a checkpointing step mode. This is a bug in the Inngest SDK.\",\n );\n },\n };\n\n const asyncCheckpointingHandlers: CheckpointHandlers[StepMode.AsyncCheckpointing] =\n {\n \"\": commonCheckpointHandler,\n \"function-resolved\": async (checkpoint, i) => {\n const output = await asyncHandlers[\"function-resolved\"](\n checkpoint,\n i,\n );\n if (output?.type === \"function-resolved\") {\n const steps = this.state.checkpointingStepBuffer.concat({\n op: StepOpCode.RunComplete,\n id: _internals.hashId(\"complete\"), // ID is not important here\n data: output.data,\n }) as [OutgoingOp, ...OutgoingOp[]];\n\n return {\n type: \"steps-found\",\n ctx: output.ctx,\n ops: output.ops,\n steps,\n };\n }\n // NOTE - Do we need to handle this case?\n return;\n },\n \"function-rejected\": async (checkpoint) => {\n // If we have buffered steps, attempt checkpointing them first\n if (this.state.checkpointingStepBuffer.length) {\n await attemptCheckpointAndResume(undefined, false);\n }\n\n return await this.transformOutput({ error: checkpoint.error });\n },\n \"step-not-found\": asyncHandlers[\"step-not-found\"],\n \"steps-found\": async ({ steps }) => {\n // Note that if we have a requested run step, we'll never be\n // checkpointing, as that's an async parallel execution mode.\n\n // Break found steps in to { stepsToResume, newSteps }\n const { stepsToResume, newSteps } = steps.reduce(\n (acc, step) => {\n if (!step.hasStepState) {\n acc.newSteps.push(step);\n } else if (!step.fulfilled) {\n acc.stepsToResume.push(step);\n }\n\n return acc;\n },\n { stepsToResume: [], newSteps: [] } as {\n stepsToResume: FoundStep[];\n newSteps: FoundStep[];\n },\n );\n\n this.debug(\"split found steps in to:\", {\n stepsToResume: stepsToResume.length,\n newSteps: newSteps.length,\n });\n\n // Got new steps? Exit early.\n if (!this.options.requestedRunStep && newSteps.length) {\n const stepResult = await this.tryExecuteStep(newSteps);\n if (stepResult) {\n this.debug(`executed step \"${stepResult.id}\" successfully`);\n\n // We executed a step!\n //\n // We know that because we're in this mode, we're always free to\n // checkpoint and continue if we ran a step and it was successful.\n if (stepResult.error) {\n // If we failed, go back to the regular async flow.\n return stepRanHandler(stepResult);\n }\n\n // If we're here, we successfully ran a step, so we may now need\n // to checkpoint it depending on the step buffer configured.\n return await attemptCheckpointAndResume(stepResult);\n }\n\n return maybeReturnNewSteps(steps);\n }\n\n // If we have stepsToResume, resume as many as possible and resume execution\n if (stepsToResume.length) {\n this.debug(`resuming ${stepsToResume.length} steps`);\n\n for (const st of stepsToResume) {\n this.resumeStepWithResult({\n ...st,\n id: st.hashedId,\n });\n }\n }\n\n return;\n },\n \"checkpointing-runtime-reached\": async () => {\n return {\n type: \"steps-found\",\n ctx: this.fnArg,\n ops: this.ops,\n steps: [\n {\n op: StepOpCode.DiscoveryRequest,\n id: _internals.hashId(\"discovery-request\"), // ID doesn't matter\n },\n ],\n };\n },\n\n \"checkpointing-buffer-interval-reached\": () => {\n return attemptCheckpointAndResume(undefined, false, true);\n },\n };\n\n return {\n [StepMode.Async]: asyncHandlers,\n [StepMode.Sync]: syncHandlers,\n [StepMode.AsyncCheckpointing]: asyncCheckpointingHandlers,\n };\n }\n\n private getCheckpointHandler(type: keyof CheckpointHandlers[StepMode]) {\n return this.checkpointHandlers[this.options.stepMode][type] as (\n checkpoint: Checkpoint,\n iteration: number,\n ) => MaybePromise<ExecutionResult | undefined>;\n }\n\n private async tryExecuteStep(\n steps: FoundStep[],\n ): Promise<OutgoingOp | undefined> {\n const hashedStepIdToRun =\n this.options.requestedRunStep || this.getEarlyExecRunStep(steps);\n if (!hashedStepIdToRun) {\n return;\n }\n\n const step = steps.find(\n (step) => step.hashedId === hashedStepIdToRun && step.fn,\n );\n\n if (step) {\n return await this.executeStep(step);\n }\n\n /**\n * Ensure we reset the timeout if we have a requested run step but couldn't\n * find it, but also that we don't reset if we found and executed it.\n */\n return void this.timeout?.reset();\n }\n\n /**\n * Given a list of outgoing ops, decide if we can execute an op early and\n * return the ID of the step to execute if we can.\n */\n private getEarlyExecRunStep(steps: FoundStep[]): string | undefined {\n /**\n * We may have been disabled due to parallelism, in which case we can't\n * immediately execute unless explicitly requested.\n */\n if (this.options.disableImmediateExecution) return;\n\n const unfulfilledSteps = steps.filter((step) => !step.fulfilled);\n if (unfulfilledSteps.length !== 1) return;\n\n const op = unfulfilledSteps[0];\n\n if (\n op &&\n op.op === StepOpCode.StepPlanned\n // TODO We must individually check properties here that we do not want to\n // execute on, such as retry counts. Nothing exists here that falls in to\n // this case, but should be accounted for when we add them.\n // && typeof op.opts === \"undefined\"\n ) {\n return op.hashedId;\n }\n\n return;\n }\n\n private async filterNewSteps(\n foundSteps: FoundStep[],\n ): Promise<[OutgoingOp, ...OutgoingOp[]] | undefined> {\n if (this.options.requestedRunStep) {\n return;\n }\n\n /**\n * Gather any steps that aren't memoized and report them.\n */\n const newSteps = foundSteps.reduce((acc, step) => {\n if (!step.hasStepState) {\n acc.push(step);\n }\n\n return acc;\n }, [] as FoundStep[]);\n\n if (!newSteps.length) {\n return;\n }\n\n /**\n * We're finishing up; let's trigger the last of the hooks.\n */\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n\n const stepList = newSteps.map<OutgoingOp>((step) => ({\n displayName: step.displayName,\n op: step.op,\n id: step.hashedId,\n name: step.name,\n opts: step.opts,\n userland: step.userland,\n })) as [OutgoingOp, ...OutgoingOp[]];\n\n /**\n * We also run `onSendEvent` middleware hooks against `step.invoke()` steps\n * to ensure that their `data` is transformed correctly.\n */\n return await this.transformNewSteps(stepList);\n }\n\n /**\n * Using middleware, transform any newly-found steps before returning them to\n * an Inngest Server.\n */\n private async transformNewSteps<T extends [OutgoingOp, ...OutgoingOp[]]>(\n steps: T,\n ): Promise<T> {\n return Promise.all(\n steps.map(async (step) => {\n if (step.op !== StepOpCode.InvokeFunction) {\n return step;\n }\n\n const onSendEventHooks = await getHookStack(\n this.options.fn[\"middleware\"],\n \"onSendEvent\",\n undefined,\n {\n transformInput: (prev, output) => {\n return { ...prev, ...output };\n },\n transformOutput: (prev, output) => {\n return {\n result: { ...prev.result, ...output?.result },\n };\n },\n },\n );\n\n /**\n * For each event being sent, create a new `onSendEvent` hook stack to\n * process it. We do this as middleware hooks are intended to run once\n * during each lifecycle (onFunctionRun or onSendEvent) and here, a hook\n * is run for every single event.\n *\n * This is done because a developer can use this hook to filter out\n * events entirely; if we batch all of the events together, we can't\n * tell which ones were filtered out if we're processing >1 invocation\n * here.\n */\n const transformedPayload = await onSendEventHooks.transformInput?.({\n payloads: [\n {\n ...(step.opts?.payload ?? {}),\n name: internalEvents.FunctionInvoked,\n },\n ],\n });\n\n const newPayload = invokePayloadSchema.parse(\n transformedPayload?.payloads?.[0] ?? {},\n );\n\n return {\n ...step,\n opts: {\n ...step.opts,\n payload: {\n ...(step.opts?.payload ?? {}),\n ...newPayload,\n },\n },\n };\n }),\n ) as Promise<T>;\n }\n\n private async executeStep({\n id,\n name,\n opts,\n fn,\n displayName,\n userland,\n hashedId,\n }: FoundStep): Promise<OutgoingOp> {\n this.debug(`preparing to execute step \"${id}\"`);\n\n this.timeout?.clear();\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n\n const outgoingOp: OutgoingOp = {\n id: hashedId,\n op: StepOpCode.StepRun,\n name,\n opts,\n displayName,\n userland,\n };\n this.state.executingStep = outgoingOp;\n\n const store = await getAsyncCtx();\n\n if (store?.execution) {\n store.execution.executingStep = {\n id,\n name: displayName,\n };\n }\n\n this.debug(`executing step \"${id}\"`);\n\n let interval: GoInterval | undefined;\n\n return goIntervalTiming(() => runAsPromise(fn))\n .finally(async () => {\n this.debug(`finished executing step \"${id}\"`);\n\n if (store?.execution) {\n delete store.execution.executingStep;\n }\n\n await this.state.hooks?.afterExecution?.();\n })\n .then<OutgoingOp>(async ({ resultPromise, interval: _interval }) => {\n interval = _interval;\n const metadata = this.state.metadata?.get(id);\n\n return {\n ...outgoingOp,\n data: await resultPromise,\n ...(metadata && metadata.length > 0 ? { metadata } : {}),\n };\n })\n .catch<OutgoingOp>((error) => {\n let errorIsRetriable = true;\n\n if (\n error instanceof NonRetriableError ||\n // biome-ignore lint/suspicious/noExplicitAny: instanceof fails across module boundaries\n (error as any)?.name === \"NonRetriableError\"\n ) {\n errorIsRetriable = false;\n } else if (\n this.fnArg.maxAttempts &&\n this.fnArg?.maxAttempts - 1 === this.fnArg.attempt\n ) {\n errorIsRetriable = false;\n }\n\n const metadata = this.state.metadata?.get(id);\n\n // Serialize the error so it survives JSON.stringify (raw Error\n // objects have non-enumerable properties that get dropped).\n // This is critical for checkpoint requests where the error is\n // sent as JSON in the request body.\n const serialized = serializeError(error);\n\n if (errorIsRetriable) {\n return {\n ...outgoingOp,\n op: StepOpCode.StepError,\n error: serialized,\n ...(metadata && metadata.length > 0 ? { metadata } : {}),\n };\n } else {\n return {\n ...outgoingOp,\n op: StepOpCode.StepFailed,\n error: serialized,\n ...(metadata && metadata.length > 0 ? { metadata } : {}),\n };\n }\n })\n .then((op) => ({\n ...op,\n timing: interval,\n }));\n }\n\n /**\n * Starts execution of the user's function, including triggering checkpoints\n * and middleware hooks where appropriate.\n */\n private async startExecution(): Promise<void> {\n /**\n * Mutate input as neccessary based on middleware.\n */\n await this.transformInput();\n\n /**\n * Start the timer to time out the run if needed.\n */\n void this.timeout?.start();\n void this.checkpointingMaxRuntimeTimer?.start();\n void this.checkpointingMaxBufferIntervalTimer?.start();\n\n await this.state.hooks?.beforeMemoization?.();\n\n /**\n * If we had no state to begin with, immediately end the memoization phase.\n */\n if (this.state.allStateUsed()) {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n }\n\n /**\n * Trigger the user's function.\n */\n runAsPromise(() => this.userFnToRun(this.fnArg))\n .finally(async () => {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n })\n .then((data) => {\n this.state.setCheckpoint({ type: \"function-resolved\", data });\n })\n .catch((error) => {\n this.state.setCheckpoint({ type: \"function-rejected\", error });\n });\n }\n\n /**\n * Using middleware, transform input before running.\n */\n private async transformInput() {\n const inputMutations = await this.state.hooks?.transformInput?.({\n ctx: { ...this.fnArg },\n steps: Object.values(this.state.stepState),\n fn: this.options.fn,\n reqArgs: this.options.reqArgs,\n });\n\n if (inputMutations?.ctx) {\n this.fnArg = inputMutations.ctx;\n }\n\n if (inputMutations?.steps) {\n this.state.stepState = Object.fromEntries(\n inputMutations.steps.map((step) => [step.id, step]),\n );\n }\n }\n\n /**\n * Using middleware, transform output before returning.\n */\n private async transformOutput(\n dataOrError: Parameters<\n NonNullable<RunHookStack[\"transformOutput\"]>\n >[0][\"result\"],\n ): Promise<ExecutionResult> {\n const output = { ...dataOrError } as Partial<OutgoingOp>;\n\n const step = this.state.executingStep;\n delete this.state.executingStep;\n\n const isStepExecution = Boolean(step);\n\n const transformedOutput = await this.state.hooks?.transformOutput?.({\n result: { ...output },\n step,\n });\n\n const { data, error } = { ...output, ...transformedOutput?.result };\n\n if (!isStepExecution) {\n await this.state.hooks?.finished?.({\n result: { ...(typeof error !== \"undefined\" ? { error } : { data }) },\n });\n }\n\n if (typeof error !== \"undefined\") {\n /**\n * Ensure we give middleware the chance to decide on retriable behaviour\n * by looking at the error returned from output transformation.\n */\n let retriable: boolean | string = !(\n error instanceof NonRetriableError ||\n // biome-ignore lint/suspicious/noExplicitAny: instanceof fails across module boundaries\n (error as any)?.name === \"NonRetriableError\" ||\n (error instanceof StepError &&\n error === this.state.recentlyRejectedStepError)\n );\n if (\n retriable &&\n (error instanceof RetryAfterError ||\n // biome-ignore lint/suspicious/noExplicitAny: instanceof fails across module boundaries\n (error as any)?.name === \"RetryAfterError\")\n ) {\n retriable = (error as RetryAfterError).retryAfter;\n }\n\n const serializedError = minifyPrettyError(serializeError(error));\n\n return {\n type: \"function-rejected\",\n ctx: this.fnArg,\n ops: this.ops,\n error: serializedError,\n retriable,\n };\n }\n\n return {\n type: \"function-resolved\",\n ctx: this.fnArg,\n ops: this.ops,\n data: undefinedToNull(data),\n };\n }\n\n private createExecutionState(): V2ExecutionState {\n const d = createDeferredPromiseWithStack<Checkpoint>();\n let checkpointResolve = d.deferred.resolve;\n const checkpointResults = d.results;\n\n const loop: V2ExecutionState[\"loop\"] = (async function* (\n cleanUp?: () => void,\n ) {\n try {\n while (true) {\n const res = (await checkpointResults.next()).value;\n if (res) {\n yield res;\n }\n }\n } finally {\n cleanUp?.();\n }\n })(() => {\n this.timeout?.clear();\n this.checkpointingMaxRuntimeTimer?.clear();\n this.checkpointingMaxBufferIntervalTimer?.clear();\n void checkpointResults.return();\n });\n\n const stepsToFulfill = Object.keys(this.options.stepState).length;\n\n const state: V2ExecutionState = {\n stepState: this.options.stepState,\n stepsToFulfill,\n steps: new Map(),\n loop,\n hasSteps: Boolean(stepsToFulfill),\n stepCompletionOrder: [...this.options.stepCompletionOrder],\n remainingStepsToBeSeen: new Set(this.options.stepCompletionOrder),\n setCheckpoint: (checkpoint: Checkpoint) => {\n this.debug(\"setting checkpoint:\", checkpoint.type);\n\n ({ resolve: checkpointResolve } = checkpointResolve(checkpoint));\n },\n allStateUsed: () => {\n return this.state.remainingStepsToBeSeen.size === 0;\n },\n checkpointingStepBuffer: [],\n metadata: new Map(),\n };\n\n return state;\n }\n\n get ops(): Record<string, MemoizedOp> {\n return Object.fromEntries(this.state.steps);\n }\n\n private createFnArg(): Context.Any {\n const step = this.createStepTools();\n\n let fnArg = {\n ...(this.options.data as { event: EventPayload }),\n step,\n } as Context.Any;\n\n /**\n * Handle use of the `onFailure` option by deserializing the error.\n */\n if (this.options.isFailureHandler) {\n const eventData = z\n .object({ error: jsonErrorSchema })\n .parse(fnArg.event?.data);\n\n (fnArg as Partial<Pick<FailureEventArgs, \"error\">>) = {\n ...fnArg,\n error: deserializeError(eventData.error),\n };\n }\n\n return this.options.transformCtx?.(fnArg) ?? fnArg;\n }\n\n private createStepTools(): ReturnType<typeof createStepTools> {\n /**\n * A list of steps that have been found and are being rolled up before being\n * reported to the core loop.\n */\n const foundStepsToReport: Map<string, FoundStep> = new Map();\n\n /**\n * A map of the subset of found steps to report that have not yet been\n * handled. Used for fast access to steps that need to be handled in order.\n */\n const unhandledFoundStepsToReport: Map<string, FoundStep> = new Map();\n\n /**\n * A map of the latest sequential step indexes found for each step ID. Used\n * to ensure that we don't index steps in parallel.\n *\n * Note that these must be sequential; if we've seen or assigned `a:1`,\n * `a:2` and `a:4`, the latest sequential step index is `2`.\n *\n */\n const expectedNextStepIndexes: Map<string, number> = new Map();\n\n /**\n * A promise that's used to ensure that step reporting cannot be run more than\n * once in a given asynchronous time span.\n */\n let foundStepsReportPromise: Promise<void> | undefined;\n\n /**\n * A promise that's used to represent middleware hooks running before\n * execution.\n */\n let beforeExecHooksPromise: Promise<void> | undefined;\n\n /**\n * A helper used to report steps to the core loop. Used after adding an item\n * to `foundStepsToReport`.\n */\n const reportNextTick = () => {\n // Being explicit instead of using `??=` to appease TypeScript.\n if (foundStepsReportPromise) {\n return;\n }\n\n foundStepsReportPromise = resolveAfterPending()\n /**\n * Ensure that we wait for this promise to resolve before continuing.\n *\n * The groups in which steps are reported can affect how we detect some\n * more complex determinism issues like parallel indexing. This promise\n * can represent middleware hooks being run early, in the middle of\n * ingesting steps to report.\n *\n * Because of this, it's important we wait for this middleware to resolve\n * before continuing to report steps to ensure that all steps have a\n * chance to be reported throughout this asynchronous action.\n */\n .then(() => beforeExecHooksPromise)\n .then(() => {\n foundStepsReportPromise = undefined;\n\n for (const [hashedId, step] of unhandledFoundStepsToReport) {\n // Note that we only run `step.handle()` if `step.hasStepState` is\n // `true`. This gives us a chance to handle checkpointing in another\n // part of the loop.\n if (\n (this.options.stepMode === StepMode.Async || step.hasStepState) &&\n step.handle()\n ) {\n unhandledFoundStepsToReport.delete(hashedId);\n\n if (step.fulfilled) {\n foundStepsToReport.delete(step.id);\n }\n }\n }\n\n if (foundStepsToReport.size) {\n const steps = [...foundStepsToReport.values()] as [\n FoundStep,\n ...FoundStep[],\n ];\n\n foundStepsToReport.clear();\n unhandledFoundStepsToReport.clear();\n\n return void this.state.setCheckpoint({\n type: \"steps-found\",\n steps: steps,\n });\n }\n });\n };\n\n /**\n * A helper used to push a step to the list of steps to report.\n */\n const pushStepToReport = (step: FoundStep) => {\n foundStepsToReport.set(step.hashedId, step);\n unhandledFoundStepsToReport.set(step.hashedId, step);\n reportNextTick();\n };\n\n const stepHandler: StepHandler = async ({\n args,\n matchOp,\n opts,\n }): Promise<unknown> => {\n await beforeExecHooksPromise;\n\n const stepOptions = getStepOptions(args[0]);\n const opId = matchOp(stepOptions, ...args.slice(1));\n\n if (this.state.executingStep) {\n /**\n * If a step is found after asynchronous actions during another step's\n * execution, everything is fine. The problem here is if we've found\n * that a step nested inside another a step, which is something we don't\n * support at the time of writing.\n *\n * In this case, we could use something like Async Hooks to understand\n * how the step is being triggered, though this isn't available in all\n * environments.\n *\n * Therefore, we'll only show a warning here to indicate that this is\n * potentially an issue.\n */\n this.options.client[\"warnMetadata\"](\n { run_id: this.fnArg.runId },\n ErrCode.NESTING_STEPS,\n prettyError({\n whatHappened: `We detected that you have nested \\`step.*\\` tooling in \\`${\n opId.displayName ?? opId.id\n }\\``,\n consequences: \"Nesting `step.*` tooling is not supported.\",\n type: \"warn\",\n reassurance:\n \"It's possible to see this warning if steps are separated by regular asynchronous calls, which is fine.\",\n stack: true,\n toFixNow:\n \"Make sure you're not using `step.*` tooling inside of other `step.*` tooling. If you need to compose steps together, you can create a new async function and call it from within your step function, or use promise chaining.\",\n code: ErrCode.NESTING_STEPS,\n }),\n );\n }\n\n if (this.state.steps.has(_internals.hashId(opId.id))) {\n const originalId = opId.id;\n\n const expectedNextIndex = expectedNextStepIndexes.get(originalId) ?? 1;\n for (let i = expectedNextIndex; ; i++) {\n const newId = originalId + STEP_INDEXING_SUFFIX + i;\n\n if (!this.state.steps.has(_internals.hashId(newId))) {\n expectedNextStepIndexes.set(originalId, i + 1);\n opId.id = newId;\n opId.userland.index = i;\n break;\n }\n }\n }\n\n const { promise, resolve, reject } = createDeferredPromise();\n const hashedId = _internals.hashId(opId.id);\n const stepState = this.state.stepState[hashedId];\n let isFulfilled = false;\n if (stepState) {\n stepState.seen = true;\n this.state.remainingStepsToBeSeen.delete(hashedId);\n\n if (typeof stepState.input === \"undefined\") {\n isFulfilled = true;\n }\n }\n\n let extraOpts: Record<string, unknown> | undefined;\n let fnArgs = [...args];\n\n if (\n typeof stepState?.input !== \"undefined\" &&\n Array.isArray(stepState.input)\n ) {\n switch (opId.op) {\n // `step.run()` has its function input affected\n case StepOpCode.StepPlanned: {\n fnArgs = [...args.slice(0, 2), ...stepState.input];\n\n extraOpts = { input: [...stepState.input] };\n break;\n }\n\n // `step.ai.infer()` has its body affected\n case StepOpCode.AiGateway: {\n extraOpts = {\n body: {\n ...(typeof opId.opts?.body === \"object\"\n ? { ...opId.opts.body }\n : {}),\n ...stepState.input[0],\n },\n };\n break;\n }\n }\n }\n\n const step: FoundStep = {\n ...opId,\n opts: { ...opId.opts, ...extraOpts },\n rawArgs: fnArgs, // TODO What is the right value here? Should this be raw args without affected input?\n hashedId,\n input: stepState?.input,\n\n fn: opts?.fn ? () => opts.fn?.(this.fnArg, ...fnArgs) : undefined,\n promise,\n fulfilled: isFulfilled,\n hasStepState: Boolean(stepState),\n displayName: opId.displayName ?? opId.id,\n handled: false,\n handle: () => {\n if (step.handled) {\n return false;\n }\n\n this.debug(`handling step \"${hashedId}\"`);\n\n step.handled = true;\n\n // Refetch step state because it may have been changed since we found\n // the step. This could be due to checkpointing, where we run this\n // live and then return to the function.\n const result = this.state.stepState[hashedId];\n\n if (step.fulfilled && result) {\n result.fulfilled = true;\n\n // For some execution scenarios such as testing, `data`, `error`,\n // and `input` may be `Promises`. This could also be the case for\n // future middleware applications. For this reason, we'll make sure\n // the values are fully resolved before continuing.\n void Promise.all([result.data, result.error, result.input]).then(\n () => {\n if (typeof result.data !== \"undefined\") {\n resolve(result.data);\n } else {\n this.state.recentlyRejectedStepError = new StepError(\n opId.id,\n result.error,\n );\n reject(this.state.recentlyRejectedStepError);\n }\n },\n );\n }\n\n return true;\n },\n };\n\n this.state.steps.set(hashedId, step);\n this.state.hasSteps = true;\n pushStepToReport(step);\n\n /**\n * If this is the last piece of state we had, we've now finished\n * memoizing.\n */\n if (!beforeExecHooksPromise && this.state.allStateUsed()) {\n // biome-ignore lint/suspicious/noAssignInExpressions: intentional\n await (beforeExecHooksPromise = (async () => {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n })());\n }\n\n return promise;\n };\n\n return createStepTools(this.options.client, this, stepHandler);\n }\n\n private resumeStepWithResult(resultOp: OutgoingOp, resume = true): FoundStep {\n const userlandStep = this.state.steps.get(resultOp.id);\n if (!userlandStep) {\n throw new Error(\n \"Step not found in memoization state during async checkpointing; this should never happen and is a bug in the Inngest SDK\",\n );\n }\n\n const data = undefinedToNull(resultOp.data);\n\n userlandStep.data = data;\n userlandStep.timing = resultOp.timing;\n userlandStep.op = resultOp.op;\n userlandStep.id = resultOp.id;\n userlandStep.hasStepState = true;\n\n if (resume) {\n userlandStep.fulfilled = true;\n this.state.stepState[resultOp.id] = userlandStep;\n\n userlandStep.handle();\n }\n\n return userlandStep;\n }\n\n private getUserFnToRun(): Handler.Any {\n if (!this.options.isFailureHandler) {\n return this.options.fn[\"fn\"];\n }\n\n if (!this.options.fn[\"onFailureFn\"]) {\n /**\n * Somehow, we've ended up detecting that this is a failure handler but\n * doesn't have an `onFailure` function. This should never happen.\n */\n throw new Error(\"Cannot find function `onFailure` handler\");\n }\n\n return this.options.fn[\"onFailureFn\"];\n }\n\n private initializeTimer(state: V2ExecutionState): void {\n if (!this.options.requestedRunStep) {\n return;\n }\n\n this.timeout = createTimeoutPromise(this.timeoutDuration);\n\n void this.timeout.then(async () => {\n const { foundSteps, totalFoundSteps } = this.getStepNotFoundDetails();\n\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n\n state.setCheckpoint({\n type: \"step-not-found\",\n step: {\n id: this.options.requestedRunStep as string,\n op: StepOpCode.StepNotFound,\n },\n foundSteps,\n totalFoundSteps,\n });\n });\n }\n\n private getStepNotFoundDetails(): {\n foundSteps: BasicFoundStep[];\n totalFoundSteps: number;\n } {\n const foundSteps = [...this.state.steps.values()]\n .filter((step) => !step.hasStepState)\n .map<BasicFoundStep>((step) => ({\n id: step.hashedId,\n name: step.name,\n displayName: step.displayName,\n }))\n .sort((a, b) => a.id.localeCompare(b.id));\n\n return {\n foundSteps: foundSteps.slice(0, STEP_NOT_FOUND_MAX_FOUND_STEPS),\n totalFoundSteps: foundSteps.length,\n };\n }\n\n private initializeCheckpointRuntimeTimer(state: V2ExecutionState): void {\n this.debug(\n \"initializing checkpointing runtime timers\",\n this.options.checkpointingConfig,\n );\n\n if (this.options.checkpointingConfig?.maxRuntime) {\n const maxRuntimeMs = Temporal.isTemporalDuration(\n this.options.checkpointingConfig.maxRuntime,\n )\n ? this.options.checkpointingConfig.maxRuntime.total({\n unit: \"milliseconds\",\n })\n : typeof this.options.checkpointingConfig.maxRuntime === \"string\"\n ? ms(this.options.checkpointingConfig.maxRuntime as StringValue) // type assertion to satisfy ms package\n : (this.options.checkpointingConfig.maxRuntime as number);\n\n // 0 or negative max runtime? Skip.\n if (Number.isFinite(maxRuntimeMs) && maxRuntimeMs > 0) {\n this.checkpointingMaxRuntimeTimer = createTimeoutPromise(maxRuntimeMs);\n\n void this.checkpointingMaxRuntimeTimer.then(async () => {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n\n state.setCheckpoint({\n type: \"checkpointing-runtime-reached\",\n });\n });\n }\n }\n\n if (this.options.checkpointingConfig?.maxInterval) {\n const maxIntervalMs = Temporal.isTemporalDuration(\n this.options.checkpointingConfig.maxInterval,\n )\n ? this.options.checkpointingConfig.maxInterval.total({\n unit: \"milliseconds\",\n })\n : typeof this.options.checkpointingConfig.maxInterval === \"string\"\n ? ms(this.options.checkpointingConfig.maxInterval as StringValue) // type assertion to satisfy ms package\n : (this.options.checkpointingConfig.maxInterval as number);\n\n // 0 or negative max interval? Skip.\n if (Number.isFinite(maxIntervalMs) && maxIntervalMs > 0) {\n this.checkpointingMaxBufferIntervalTimer =\n createTimeoutPromise(maxIntervalMs);\n\n void this.checkpointingMaxBufferIntervalTimer.then(async () => {\n // Note that this will not immediately run; it will be queued like all\n // other checkpoints so that we're never running multiple checkpoints\n // at the same time and it's easier to reason about those decision\n // points.\n //\n // A change in the future may be to make this particular checkpointing\n // action immediate and have the checkpoint action itself be\n // idempotent.\n state.setCheckpoint({\n type: \"checkpointing-buffer-interval-reached\",\n });\n\n this.checkpointingMaxBufferIntervalTimer?.reset();\n });\n }\n }\n }\n\n private async initializeMiddleware(): Promise<RunHookStack> {\n const ctx = this.options.data as Pick<\n Readonly<BaseContext<Inngest.Any>>,\n \"event\" | \"events\" | \"runId\"\n >;\n\n const hooks = await getHookStack(\n this.options.fn[\"middleware\"],\n \"onFunctionRun\",\n {\n ctx,\n fn: this.options.fn,\n steps: Object.values(this.options.stepState),\n reqArgs: this.options.reqArgs,\n },\n {\n transformInput: (prev, output) => {\n return {\n ctx: { ...prev.ctx, ...output?.ctx },\n fn: this.options.fn,\n steps: prev.steps.map((step, i) => ({\n ...step,\n ...output?.steps?.[i],\n })),\n reqArgs: prev.reqArgs,\n };\n },\n transformOutput: (prev, output) => {\n return {\n result: { ...prev.result, ...output?.result },\n step: prev.step,\n };\n },\n },\n );\n\n return hooks;\n }\n}\n\n/**\n * Types of checkpoints that can be reached during execution.\n */\nexport interface Checkpoints {\n \"steps-found\": { steps: [FoundStep, ...FoundStep[]] };\n \"function-rejected\": { error: unknown };\n \"function-resolved\": { data: unknown };\n \"step-not-found\": {\n step: OutgoingOp;\n foundSteps: BasicFoundStep[];\n totalFoundSteps: number;\n };\n \"checkpointing-runtime-reached\": {};\n \"checkpointing-buffer-interval-reached\": {};\n}\n\ntype Checkpoint = {\n [K in keyof Checkpoints]: Simplify<{ type: K } & Checkpoints[K]>;\n}[keyof Checkpoints];\n\ntype CheckpointHandlers = Record<\n StepMode,\n {\n [C in Checkpoint as C[\"type\"]]: (\n checkpoint: C,\n\n /**\n * This is the number of checkpoints that have been seen before this one was\n * triggered.\n *\n * The catch-all `\"\"` checkpoint does not increment this count.\n */\n i: number,\n ) => MaybePromise<ExecutionResult | undefined>;\n } & {\n \"\": (\n checkpoint: Checkpoint,\n\n /**\n * This is the number of checkpoints that have been seen before this one was\n * triggered.\n *\n * The catch-all `\"\"` checkpoint does not increment this count.\n */\n i: number,\n ) => MaybePromise<void>;\n }\n>;\n\nexport interface V2ExecutionState {\n /**\n * A value that indicates that we're executing this step. Can be used to\n * ensure steps are not accidentally nested until we support this across all\n * platforms.\n */\n executingStep?: Readonly<Omit<OutgoingOp, \"id\">>;\n\n /**\n * A map of step IDs to their data, used to fill previously-completed steps\n * with state from the executor.\n */\n stepState: Record<string, MemoizedOp>;\n\n /**\n * The number of steps we expect to fulfil based on the state passed from the\n * Executor.\n */\n stepsToFulfill: number;\n\n /**\n * A map of step IDs to their functions to run. The executor can request a\n * specific step to run, so we need to store the function to run here.\n */\n steps: Map<string, FoundStep>;\n\n /**\n * A flag which represents whether or not steps are understood to be used in\n * this function. This is used to determine whether or not we should run\n * some steps (such as `step.sendEvent`) inline as they are found.\n */\n hasSteps: boolean;\n\n /**\n * The core loop - a generator used to take an action upon finding the next\n * checkpoint. Manages the flow of execution and cleaning up after itself.\n */\n loop: AsyncGenerator<Checkpoint, void, void>;\n\n /**\n * A function that resolves the `Promise` returned by `waitForNextDecision`.\n */\n setCheckpoint: (data: Checkpoint) => void;\n\n /**\n * Initialized middleware hooks for this execution.\n *\n * Middleware hooks are cached to ensure they can only be run once, which\n * means that these hooks can be called in many different places to ensure we\n * handle all possible execution paths.\n */\n hooks?: RunHookStack;\n\n /**\n * Returns whether or not all state passed from the executor has been used to\n * fulfill found steps.\n */\n allStateUsed: () => boolean;\n\n /**\n * An ordered list of step IDs that represents the order in which their\n * execution was completed.\n */\n stepCompletionOrder: string[];\n\n /**\n * An set of step IDs that have yet to be seen in this execution. Used to\n * decide when to trigger middleware based on the current state.\n */\n remainingStepsToBeSeen: Set<string>;\n\n /**\n * If defined, this is the error that purposefully thrown when memoizing step\n * state in order to support per-step errors.\n *\n * We use this so that if the function itself rejects with the same error, we\n * know that it was entirely uncaught (or at the very least rethrown), so we\n * should send a `NonRetriableError` to stop needless execution of a function\n * that will continue to fail.\n *\n * TODO This is imperfect, as this state is currently kept around for longer\n * than it needs to be. It should disappear as soon as we've seen that the\n * error did not immediately throw. It may need to be refactored to work a\n * little more smoothly with the core loop.\n */\n recentlyRejectedStepError?: StepError;\n\n /**\n * If defined, this indicates that we're running a checkpointed function run,\n * and contains the data needed to report progress back to Inngest.\n */\n checkpointedRun?: {\n fnId: string;\n appId: string;\n token?: string;\n };\n\n /**\n * A buffer of steps that are currently queued to be checkpointed.\n */\n checkpointingStepBuffer: OutgoingOp[];\n\n /**\n * Metadata collected during execution to be sent with outgoing ops.\n */\n metadata?: Map<string, Array<MetadataUpdate>>;\n}\n\nconst hashId = (id: string): string => {\n return sha1().update(id).digest(\"hex\");\n};\n\nconst hashOp = (op: OutgoingOp): OutgoingOp => {\n return {\n ...op,\n id: hashId(op.id),\n };\n};\n\n/**\n * Exported for testing.\n */\nexport const _internals = { hashOp, hashId };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,EAAE,SAASA;;;;;;;;;AAUjB,MAAM,2BAA2B;CAAE,aAAa;CAAG,WAAW;CAAK;AACnE,MAAM,iCAAiC;AAEvC,MAAaC,4BAAqD,YAAY;AAC5E,QAAO,IAAI,mBAAmB,QAAQ;;AAGxC,IAAM,qBAAN,cAAiCC,0CAA8C;CAC7E,AAAO,UA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,oBAAoB,YAA2B,GAC9D,KAAK,QAAQ,oBAAoB;AAGxC,OAAI,OAAO,SAAS,cAAc,IAAI,gBAAgB,GAAG;AACvD,SAAK,sCACHA,sCAAqB,cAAc;AAErC,IAAK,KAAK,oCAAoC,KAAK,YAAY;AAS7D,WAAM,cAAc,EAClB,MAAM,yCACP,CAAC;AAEF,UAAK,qCAAqC,OAAO;MACjD;;;;CAKR,MAAc,uBAA8C;EAC1D,MAAM,MAAM,KAAK,QAAQ;AAmCzB,SA9Bc,MAAMlC,uCAClB,KAAK,QAAQ,GAAG,eAChB,iBACA;GACE;GACA,IAAI,KAAK,QAAQ;GACjB,OAAO,OAAO,OAAO,KAAK,QAAQ,UAAU;GAC5C,SAAS,KAAK,QAAQ;GACvB,EACD;GACE,iBAAiB,MAAM,WAAW;AAChC,WAAO;KACL,KAAK;MAAE,GAAG,KAAK;MAAK,GAAG,QAAQ;MAAK;KACpC,IAAI,KAAK,QAAQ;KACjB,OAAO,KAAK,MAAM,KAAK,MAAM,OAAO;MAClC,GAAG;MACH,GAAG,QAAQ,QAAQ;MACpB,EAAE;KACH,SAAS,KAAK;KACf;;GAEH,kBAAkB,MAAM,WAAW;AACjC,WAAO;KACL,QAAQ;MAAE,GAAG,KAAK;MAAQ,GAAG,QAAQ;MAAQ;KAC7C,MAAM,KAAK;KACZ;;GAEJ,CACF;;;AAmKL,MAAM,UAAU,OAAuB;AACrC,QAAO,MAAM,CAAC,OAAO,GAAG,CAAC,OAAO,MAAM;;AAGxC,MAAM,UAAU,OAA+B;AAC7C,QAAO;EACL,GAAG;EACH,IAAI,OAAO,GAAG,GAAG;EAClB;;;;;AAMH,MAAa,aAAa;CAAE;CAAQ;CAAQ"}
1
+ {"version":3,"file":"v2.cjs","names":["hashjs","createV2InngestExecution: InngestExecutionFactory","InngestExecution","ExecutionVersion","options: InngestExecutionOptions","StepMode","trace","version","getAsyncLocalStorage","headerKeys","retryWithBackoff","defaultMaxRetries","commonCheckpointHandler: CheckpointHandlers[StepMode][\"\"]","StepOpCode","serializeError","syncHandlers: CheckpointHandlers[StepMode.Sync]","asyncHandlers: CheckpointHandlers[StepMode.Async]","asyncCheckpointingHandlers: CheckpointHandlers[StepMode.AsyncCheckpointing]","step","getHookStack","internalEvents","invokePayloadSchema","outgoingOp: OutgoingOp","getAsyncCtx","interval: GoInterval | undefined","goIntervalTiming","runAsPromise","NonRetriableError","retriable: boolean | string","StepError","RetryAfterError","minifyPrettyError","undefinedToNull","createDeferredPromiseWithStack","loop: V2ExecutionState[\"loop\"]","z","jsonErrorSchema","deserializeError","foundStepsToReport: Map<string, FoundStep>","unhandledFoundStepsToReport: Map<string, FoundStep>","expectedNextStepIndexes: Map<string, number>","foundStepsReportPromise: Promise<void> | undefined","beforeExecHooksPromise: Promise<void> | undefined","resolveAfterPending","stepHandler: StepHandler","getStepOptions","ErrCode","prettyError","STEP_INDEXING_SUFFIX","createDeferredPromise","extraOpts: Record<string, unknown> | undefined","step: FoundStep","createStepTools","createTimeoutPromise"],"sources":["../../../src/components/execution/v2.ts"],"sourcesContent":["import { trace } from \"@opentelemetry/api\";\nimport hashjs from \"hash.js\";\nimport ms, { type StringValue } from \"ms\";\nimport { z } from \"zod/v3\";\nimport {\n defaultMaxRetries,\n ExecutionVersion,\n headerKeys,\n internalEvents,\n} from \"../../helpers/consts.ts\";\nimport {\n deserializeError,\n ErrCode,\n minifyPrettyError,\n prettyError,\n serializeError,\n} from \"../../helpers/errors.js\";\nimport { undefinedToNull } from \"../../helpers/functions.js\";\nimport {\n createDeferredPromise,\n createDeferredPromiseWithStack,\n createTimeoutPromise,\n type GoInterval,\n goIntervalTiming,\n resolveAfterPending,\n retryWithBackoff,\n runAsPromise,\n} from \"../../helpers/promises.ts\";\nimport * as Temporal from \"../../helpers/temporal.ts\";\nimport type { MaybePromise, Simplify } from \"../../helpers/types.ts\";\nimport {\n type APIStepPayload,\n type BaseContext,\n type Context,\n type EventPayload,\n type FailureEventArgs,\n type Handler,\n jsonErrorSchema,\n type OutgoingOp,\n StepMode,\n StepOpCode,\n} from \"../../types.ts\";\nimport { version } from \"../../version.ts\";\nimport type { Inngest } from \"../Inngest.ts\";\nimport type {\n MetadataKind,\n MetadataOpcode,\n MetadataScope,\n MetadataUpdate,\n} from \"../InngestMetadata.ts\";\nimport { getHookStack, type RunHookStack } from \"../InngestMiddleware.ts\";\nimport {\n createStepTools,\n type FoundStep,\n getStepOptions,\n invokePayloadSchema,\n STEP_INDEXING_SUFFIX,\n type StepHandler,\n} from \"../InngestStepTools.ts\";\nimport { NonRetriableError } from \"../NonRetriableError.ts\";\nimport { RetryAfterError } from \"../RetryAfterError.ts\";\nimport { StepError } from \"../StepError.ts\";\nimport { getAsyncCtx, getAsyncLocalStorage } from \"./als.ts\";\nimport {\n type BasicFoundStep,\n type ExecutionResult,\n type IInngestExecution,\n InngestExecution,\n type InngestExecutionFactory,\n type InngestExecutionOptions,\n type MemoizedOp,\n} from \"./InngestExecution.ts\";\nimport { clientProcessorMap } from \"./otel/access.ts\";\n\nconst { sha1 } = hashjs;\n\n/**\n * Retry configuration for checkpoint operations.\n *\n * Checkpoint calls use exponential backoff with jitter to handle transient\n * network failures (e.g., dev server temporarily down, cloud hiccup). If\n * retries exhaust, the error propagates up - for Sync mode this results in a\n * 500 error, for AsyncCheckpointing the caller handles fallback.\n */\nconst CHECKPOINT_RETRY_OPTIONS = { maxAttempts: 5, baseDelay: 100 };\nconst STEP_NOT_FOUND_MAX_FOUND_STEPS = 25;\n\nexport const createV2InngestExecution: InngestExecutionFactory = (options) => {\n return new V2InngestExecution(options);\n};\n\nclass V2InngestExecution extends InngestExecution implements IInngestExecution {\n public version = ExecutionVersion.V2;\n\n private state: V2ExecutionState;\n private fnArg: Context.Any;\n private checkpointHandlers: CheckpointHandlers;\n private timeoutDuration = 1000 * 10;\n private execution: Promise<ExecutionResult> | undefined;\n private userFnToRun: Handler.Any;\n\n /**\n * If we're supposed to run a particular step via `requestedRunStep`, this\n * will be a `Promise` that resolves after no steps have been found for\n * `timeoutDuration` milliseconds.\n *\n * If we're not supposed to run a particular step, this will be `undefined`.\n */\n private timeout?: ReturnType<typeof createTimeoutPromise>;\n\n /**\n * If we're checkpointing and have been given a maximum runtime, this will be\n * a `Promise` that resolves after that duration has elapsed, allowing us to\n * ensure that we end the execution in good time, especially in serverless\n * environments.\n */\n private checkpointingMaxRuntimeTimer?: ReturnType<\n typeof createTimeoutPromise\n >;\n\n /**\n * If we're checkpointing and have been given a maximum buffer interval, this\n * will be a `Promise` that resolves after that duration has elapsed, allowing\n * us to periodically checkpoint even if the step buffer hasn't filled.\n */\n private checkpointingMaxBufferIntervalTimer?: ReturnType<\n typeof createTimeoutPromise\n >;\n\n constructor(rawOptions: InngestExecutionOptions) {\n const options: InngestExecutionOptions = {\n ...rawOptions,\n stepMode: rawOptions.stepMode ?? StepMode.Async,\n };\n\n super(options);\n\n /**\n * Check we have everything we need for checkpointing\n */\n if (this.options.stepMode === StepMode.Sync) {\n if (!this.options.createResponse) {\n throw new Error(\"createResponse is required for sync step mode\");\n }\n }\n\n this.userFnToRun = this.getUserFnToRun();\n this.state = this.createExecutionState();\n this.fnArg = this.createFnArg();\n this.checkpointHandlers = this.createCheckpointHandlers();\n this.initializeTimer(this.state);\n this.initializeCheckpointRuntimeTimer(this.state);\n\n this.debug(\n \"created new V2 execution for run;\",\n this.options.requestedRunStep\n ? `wanting to run step \"${this.options.requestedRunStep}\"`\n : \"discovering steps\",\n );\n\n this.debug(\"existing state keys:\", Object.keys(this.state.stepState));\n }\n\n /**\n * Idempotently start the execution of the user's function.\n */\n public start() {\n if (!this.execution) {\n this.debug(\"starting V2 execution\");\n\n const tracer = trace.getTracer(\"inngest\", version);\n\n this.execution = getAsyncLocalStorage().then((als) => {\n return als.run(\n {\n app: this.options.client,\n execution: {\n ctx: this.fnArg,\n instance: this,\n },\n },\n async () => {\n return tracer.startActiveSpan(\"inngest.execution\", (span) => {\n clientProcessorMap.get(this.options.client)?.declareStartingSpan({\n span,\n runId: this.options.runId,\n traceparent: this.options.headers[headerKeys.TraceParent],\n tracestate: this.options.headers[headerKeys.TraceState],\n });\n\n return this._start()\n .then((result) => {\n this.debug(\"result:\", result);\n return result;\n })\n .finally(() => {\n span.end();\n });\n });\n },\n );\n });\n }\n\n return this.execution;\n }\n\n public addMetadata(\n stepId: string,\n kind: MetadataKind,\n scope: MetadataScope,\n op: MetadataOpcode,\n values: Record<string, unknown>,\n ) {\n if (!this.state.metadata) {\n this.state.metadata = new Map();\n }\n\n const updates = this.state.metadata.get(stepId) ?? [];\n updates.push({ kind, scope, op, values });\n this.state.metadata.set(stepId, updates);\n\n return true;\n }\n\n /**\n * Starts execution of the user's function and the core loop.\n */\n private async _start(): Promise<ExecutionResult> {\n try {\n const allCheckpointHandler = this.getCheckpointHandler(\"\");\n this.state.hooks = await this.initializeMiddleware();\n await this.startExecution();\n\n let i = 0;\n\n for await (const checkpoint of this.state.loop) {\n await allCheckpointHandler(checkpoint, i);\n\n const handler = this.getCheckpointHandler(checkpoint.type);\n const result = await handler(checkpoint, i++);\n\n if (result) {\n return result;\n }\n }\n } catch (error) {\n return await this.transformOutput({ error });\n } finally {\n void this.state.loop.return();\n await this.state.hooks?.beforeResponse?.();\n }\n\n /**\n * If we're here, the generator somehow finished without returning a value.\n * This should never happen.\n */\n throw new Error(\"Core loop finished without returning a value\");\n }\n\n private async checkpoint(steps: OutgoingOp[]): Promise<void> {\n if (this.options.stepMode === StepMode.Sync) {\n if (!this.state.checkpointedRun) {\n // We have to start the run\n const res = await retryWithBackoff(\n () =>\n this.options.client[\"inngestApi\"].checkpointNewRun({\n runId: this.fnArg.runId,\n event: this.fnArg.event as APIStepPayload,\n steps,\n executionVersion: this.version,\n retries: this.fnArg.maxAttempts ?? defaultMaxRetries,\n }),\n CHECKPOINT_RETRY_OPTIONS,\n );\n\n this.state.checkpointedRun = {\n appId: res.data.app_id,\n fnId: res.data.fn_id,\n token: res.data.token,\n };\n } else {\n await retryWithBackoff(\n () =>\n this.options.client[\"inngestApi\"].checkpointSteps({\n appId: this.state.checkpointedRun!.appId,\n fnId: this.state.checkpointedRun!.fnId,\n runId: this.fnArg.runId,\n steps,\n }),\n CHECKPOINT_RETRY_OPTIONS,\n );\n }\n } else if (this.options.stepMode === StepMode.AsyncCheckpointing) {\n if (!this.options.queueItemId) {\n throw new Error(\n \"Missing queueItemId for async checkpointing. This is a bug in the Inngest SDK.\",\n );\n }\n\n if (!this.options.internalFnId) {\n throw new Error(\n \"Missing internalFnId for async checkpointing. This is a bug in the Inngest SDK.\",\n );\n }\n\n await retryWithBackoff(\n () =>\n this.options.client[\"inngestApi\"].checkpointStepsAsync({\n runId: this.fnArg.runId,\n fnId: this.options.internalFnId!,\n queueItemId: this.options.queueItemId!,\n steps,\n }),\n CHECKPOINT_RETRY_OPTIONS,\n );\n } else {\n throw new Error(\n \"Checkpointing is only supported in Sync and AsyncCheckpointing step modes. This is a bug in the Inngest SDK.\",\n );\n }\n }\n\n private async checkpointAndSwitchToAsync(\n steps: OutgoingOp[],\n ): Promise<ExecutionResult> {\n await this.checkpoint(steps);\n\n if (!this.state.checkpointedRun?.token) {\n throw new Error(\"Failed to checkpoint and switch to async mode\");\n }\n\n return {\n type: \"change-mode\",\n ctx: this.fnArg,\n ops: this.ops,\n to: StepMode.Async,\n token: this.state.checkpointedRun?.token!,\n };\n }\n\n /**\n * Returns whether we're in the final attempt of execution, or `null` if we\n * can't determine this in the SDK.\n */\n private inFinalAttempt(): boolean | null {\n if (typeof this.fnArg.maxAttempts !== \"number\") {\n return null;\n }\n\n return this.fnArg.attempt + 1 >= this.fnArg.maxAttempts;\n }\n\n /**\n * Creates a handler for every checkpoint type, defining what to do when we\n * reach that checkpoint in the core loop.\n */\n private createCheckpointHandlers(): CheckpointHandlers {\n const commonCheckpointHandler: CheckpointHandlers[StepMode][\"\"] = (\n checkpoint,\n ) => {\n this.debug(`${this.options.stepMode} checkpoint:`, checkpoint);\n };\n\n const stepRanHandler = async (\n stepResult: OutgoingOp,\n ): Promise<ExecutionResult> => {\n const transformResult = await this.transformOutput(stepResult);\n\n /**\n * Transforming output will always return either function rejection or\n * resolution. In most cases, this can be immediately returned, but in\n * this particular case we want to handle it differently.\n */\n if (transformResult.type === \"function-resolved\") {\n return {\n type: \"step-ran\",\n ctx: transformResult.ctx,\n ops: transformResult.ops,\n step: {\n ...stepResult,\n data: transformResult.data,\n },\n };\n } else if (transformResult.type === \"function-rejected\") {\n const stepForResponse = {\n ...stepResult,\n error: transformResult.error,\n };\n\n if (stepResult.op === StepOpCode.StepFailed) {\n const ser = serializeError(transformResult.error);\n stepForResponse.data = {\n __serialized: true,\n name: ser.name,\n message: ser.message,\n stack: \"\",\n };\n }\n\n return {\n type: \"step-ran\",\n ctx: transformResult.ctx,\n ops: transformResult.ops,\n retriable: transformResult.retriable,\n step: stepForResponse,\n };\n }\n\n return transformResult;\n };\n\n const maybeReturnNewSteps = async (\n steps: FoundStep[],\n ): Promise<ExecutionResult | undefined> => {\n const newSteps = await this.filterNewSteps(Array.from(steps.values()));\n\n if (newSteps) {\n return {\n type: \"steps-found\",\n ctx: this.fnArg,\n ops: this.ops,\n steps: newSteps,\n };\n }\n\n return;\n };\n\n const attemptCheckpointAndResume = async (\n stepResult?: OutgoingOp,\n resume = true,\n force = false,\n ) => {\n // If we're here, we successfully ran a step, so we may now need\n // to checkpoint it depending on the step buffer configured.\n if (stepResult) {\n const stepToResume = this.resumeStepWithResult(stepResult, resume);\n\n // Transform data for checkpoint (middleware)\n // Only call the transformOutput hook directly, not the full transformOutput method\n // which has side effects like calling the finished hook\n const transformedOutput = await this.state.hooks?.transformOutput?.({\n result: { data: stepResult.data },\n step: stepResult,\n });\n const transformedData =\n transformedOutput?.result?.data ?? stepResult.data;\n\n // Buffer a copy with transformed data for checkpointing\n this.state.checkpointingStepBuffer.push({\n ...stepToResume,\n data: transformedData,\n });\n }\n\n if (\n force ||\n !this.options.checkpointingConfig?.bufferedSteps ||\n this.state.checkpointingStepBuffer.length >=\n this.options.checkpointingConfig.bufferedSteps\n ) {\n this.debug(\"checkpointing and resuming execution after step run\");\n\n try {\n this.debug(\n `checkpointing all buffered steps:`,\n this.state.checkpointingStepBuffer\n .map((op) => op.displayName || op.id)\n .join(\", \"),\n );\n\n return void (await this.checkpoint(\n this.state.checkpointingStepBuffer,\n ));\n } catch (err) {\n // If checkpointing fails for any reason, fall back to the async\n // flow\n this.debug(\n \"error checkpointing after step run, so falling back to async\",\n err,\n );\n\n if (stepResult) {\n return stepRanHandler(stepResult);\n }\n } finally {\n // Clear the checkpointing buffer\n this.state.checkpointingStepBuffer = [];\n }\n } else {\n this.debug(\n `not checkpointing yet, continuing execution as we haven't reached buffered step limit of ${this.options.checkpointingConfig?.bufferedSteps}`,\n );\n }\n\n return;\n };\n\n const syncHandlers: CheckpointHandlers[StepMode.Sync] = {\n /**\n * Run for all checkpoints. Best used for logging or common actions.\n * Use other handlers to return values and interrupt the core loop.\n */\n \"\": commonCheckpointHandler,\n\n \"function-resolved\": async (checkpoint, i) => {\n // Transform data for checkpoint (middleware)\n // Only call the transformOutput hook directly, not the full transformOutput method\n // which has side effects like calling the finished hook\n const transformedOutput = await this.state.hooks?.transformOutput?.({\n result: { data: checkpoint.data },\n step: this.state.executingStep,\n });\n const transformedData =\n transformedOutput?.result?.data ?? checkpoint.data;\n\n await this.checkpoint([\n {\n op: StepOpCode.RunComplete,\n id: _internals.hashId(\"complete\"), // ID is not important here\n data: await this.options.createResponse!(transformedData),\n },\n ]);\n\n // Apply middleware transformation before returning\n return await this.transformOutput({ data: checkpoint.data });\n },\n\n \"function-rejected\": async (checkpoint) => {\n // If the function throws during sync execution, we want to switch to\n // async mode so that we can retry. The exception is that we're already\n // at max attempts, in which case we do actually want to reject.\n if (this.inFinalAttempt()) {\n // Apply middleware transformation before returning\n return await this.transformOutput({ error: checkpoint.error });\n }\n\n // Otherwise, checkpoint the error and switch to async mode\n return this.checkpointAndSwitchToAsync([\n {\n id: _internals.hashId(\"complete\"), // ID is not important here\n op: StepOpCode.StepError,\n error: checkpoint.error,\n },\n ]);\n },\n\n \"step-not-found\": () => {\n return {\n type: \"function-rejected\",\n ctx: this.fnArg,\n error: new Error(\n \"Step not found when checkpointing; this should never happen\",\n ),\n ops: this.ops,\n retriable: false,\n };\n },\n\n \"steps-found\": async ({ steps }) => {\n // If we're entering parallelism or async mode, checkpoint and switch\n // to async.\n if (steps.length !== 1 || steps[0].mode !== StepMode.Sync) {\n return this.checkpointAndSwitchToAsync(\n steps.map((step) => ({ ...step, id: step.hashedId })),\n );\n }\n\n // Otherwise we're good to start executing things right now.\n const result = await this.executeStep(steps[0]);\n\n const transformed = await stepRanHandler(result);\n if (transformed.type !== \"step-ran\") {\n throw new Error(\n \"Unexpected checkpoint handler result type after running step in sync mode\",\n );\n }\n\n if (result.error) {\n return this.checkpointAndSwitchToAsync([transformed.step]);\n }\n\n // Resume the step with original data for user code\n //\n // Note: We should likely also pass this through `transformOutput` and\n // then `transformInput` to mimic the entire middleware cycle, to ensure\n // that any transformations that purposefully skew the resulting type\n // are supported.\n const stepToResume = this.resumeStepWithResult(result);\n\n // Checkpoint with transformed data from middleware\n const stepForCheckpoint = {\n ...stepToResume,\n data: transformed.step.data,\n };\n\n return void (await this.checkpoint([stepForCheckpoint]));\n },\n\n \"checkpointing-runtime-reached\": () => {\n return this.checkpointAndSwitchToAsync([\n {\n op: StepOpCode.DiscoveryRequest,\n id: _internals.hashId(\"discovery-request\"), // ID doesn't matter\n },\n ]);\n },\n\n \"checkpointing-buffer-interval-reached\": () => {\n return attemptCheckpointAndResume(undefined, false, true);\n },\n };\n\n const asyncHandlers: CheckpointHandlers[StepMode.Async] = {\n /**\n * Run for all checkpoints. Best used for logging or common actions.\n * Use other handlers to return values and interrupt the core loop.\n */\n \"\": commonCheckpointHandler,\n\n /**\n * The user's function has completed and returned a value.\n */\n \"function-resolved\": async ({ data }) => {\n // We need to do this even here for async, as we could be returning\n // data from an API endpoint, even if we were triggered async.\n if (this.options.createResponse) {\n data = await this.options.createResponse(data);\n }\n\n return await this.transformOutput({ data });\n },\n\n /**\n * The user's function has thrown an error.\n */\n \"function-rejected\": async (checkpoint) => {\n return await this.transformOutput({ error: checkpoint.error });\n },\n\n /**\n * We've found one or more steps. Here we may want to run a step or report\n * them back to Inngest.\n */\n \"steps-found\": async ({ steps }) => {\n const stepResult = await this.tryExecuteStep(steps);\n if (stepResult) {\n return stepRanHandler(stepResult);\n }\n\n return maybeReturnNewSteps(steps);\n },\n\n /**\n * While trying to find a step that Inngest has told us to run, we've\n * timed out or have otherwise decided that it doesn't exist.\n */\n \"step-not-found\": ({ step, foundSteps, totalFoundSteps }) => {\n return {\n type: \"step-not-found\",\n ctx: this.fnArg,\n ops: this.ops,\n step,\n foundSteps,\n totalFoundSteps,\n };\n },\n\n \"checkpointing-runtime-reached\": () => {\n throw new Error(\n \"Checkpointing maximum runtime reached, but this is not in a checkpointing step mode. This is a bug in the Inngest SDK.\",\n );\n },\n\n \"checkpointing-buffer-interval-reached\": () => {\n throw new Error(\n \"Checkpointing maximum buffer interval reached, but this is not in a checkpointing step mode. This is a bug in the Inngest SDK.\",\n );\n },\n };\n\n const asyncCheckpointingHandlers: CheckpointHandlers[StepMode.AsyncCheckpointing] =\n {\n \"\": commonCheckpointHandler,\n \"function-resolved\": async (checkpoint, i) => {\n const output = await asyncHandlers[\"function-resolved\"](\n checkpoint,\n i,\n );\n if (output?.type === \"function-resolved\") {\n const steps = this.state.checkpointingStepBuffer.concat({\n op: StepOpCode.RunComplete,\n id: _internals.hashId(\"complete\"), // ID is not important here\n data: output.data,\n }) as [OutgoingOp, ...OutgoingOp[]];\n\n return {\n type: \"steps-found\",\n ctx: output.ctx,\n ops: output.ops,\n steps,\n };\n }\n // NOTE - Do we need to handle this case?\n return;\n },\n \"function-rejected\": async (checkpoint) => {\n // If we have buffered steps, attempt checkpointing them first\n if (this.state.checkpointingStepBuffer.length) {\n await attemptCheckpointAndResume(undefined, false);\n }\n\n return await this.transformOutput({ error: checkpoint.error });\n },\n \"step-not-found\": asyncHandlers[\"step-not-found\"],\n \"steps-found\": async ({ steps }) => {\n // Note that if we have a requested run step, we'll never be\n // checkpointing, as that's an async parallel execution mode.\n\n // Break found steps in to { stepsToResume, newSteps }\n const { stepsToResume, newSteps } = steps.reduce(\n (acc, step) => {\n if (!step.hasStepState) {\n acc.newSteps.push(step);\n } else if (!step.fulfilled) {\n acc.stepsToResume.push(step);\n }\n\n return acc;\n },\n { stepsToResume: [], newSteps: [] } as {\n stepsToResume: FoundStep[];\n newSteps: FoundStep[];\n },\n );\n\n this.debug(\"split found steps in to:\", {\n stepsToResume: stepsToResume.length,\n newSteps: newSteps.length,\n });\n\n // Got new steps? Exit early.\n if (!this.options.requestedRunStep && newSteps.length) {\n const stepResult = await this.tryExecuteStep(newSteps);\n if (stepResult) {\n this.debug(`executed step \"${stepResult.id}\" successfully`);\n\n // We executed a step!\n //\n // We know that because we're in this mode, we're always free to\n // checkpoint and continue if we ran a step and it was successful.\n if (stepResult.error) {\n // Flush buffered steps before falling back to async,\n // so previously-successful steps aren't lost.\n if (this.state.checkpointingStepBuffer.length) {\n await attemptCheckpointAndResume(undefined, false, true);\n }\n\n // If we failed, go back to the regular async flow.\n return stepRanHandler(stepResult);\n }\n\n // If we're here, we successfully ran a step, so we may now need\n // to checkpoint it depending on the step buffer configured.\n return await attemptCheckpointAndResume(stepResult);\n }\n\n // Flush any buffered checkpoint steps before returning\n // new steps to the executor. Without this, steps executed\n // in-process during AsyncCheckpointing but not yet\n // checkpointed would be lost. When the executor later calls\n // back with requestedRunStep, those steps would be missing\n // from stepState, causing \"step not found\" errors.\n if (this.state.checkpointingStepBuffer.length) {\n await attemptCheckpointAndResume(undefined, false, true);\n }\n\n return maybeReturnNewSteps(steps);\n }\n\n // If we have stepsToResume, resume as many as possible and resume execution\n if (stepsToResume.length) {\n this.debug(`resuming ${stepsToResume.length} steps`);\n\n for (const st of stepsToResume) {\n this.resumeStepWithResult({\n ...st,\n id: st.hashedId,\n });\n }\n }\n\n return;\n },\n \"checkpointing-runtime-reached\": async () => {\n return {\n type: \"steps-found\",\n ctx: this.fnArg,\n ops: this.ops,\n steps: [\n {\n op: StepOpCode.DiscoveryRequest,\n id: _internals.hashId(\"discovery-request\"), // ID doesn't matter\n },\n ],\n };\n },\n\n \"checkpointing-buffer-interval-reached\": () => {\n return attemptCheckpointAndResume(undefined, false, true);\n },\n };\n\n return {\n [StepMode.Async]: asyncHandlers,\n [StepMode.Sync]: syncHandlers,\n [StepMode.AsyncCheckpointing]: asyncCheckpointingHandlers,\n };\n }\n\n private getCheckpointHandler(type: keyof CheckpointHandlers[StepMode]) {\n return this.checkpointHandlers[this.options.stepMode][type] as (\n checkpoint: Checkpoint,\n iteration: number,\n ) => MaybePromise<ExecutionResult | undefined>;\n }\n\n private async tryExecuteStep(\n steps: FoundStep[],\n ): Promise<OutgoingOp | undefined> {\n const hashedStepIdToRun =\n this.options.requestedRunStep || this.getEarlyExecRunStep(steps);\n if (!hashedStepIdToRun) {\n return;\n }\n\n const step = steps.find(\n (step) => step.hashedId === hashedStepIdToRun && step.fn,\n );\n\n if (step) {\n return await this.executeStep(step);\n }\n\n /**\n * Ensure we reset the timeout if we have a requested run step but couldn't\n * find it, but also that we don't reset if we found and executed it.\n */\n return void this.timeout?.reset();\n }\n\n /**\n * Given a list of outgoing ops, decide if we can execute an op early and\n * return the ID of the step to execute if we can.\n */\n private getEarlyExecRunStep(steps: FoundStep[]): string | undefined {\n /**\n * We may have been disabled due to parallelism, in which case we can't\n * immediately execute unless explicitly requested.\n */\n if (this.options.disableImmediateExecution) return;\n\n const unfulfilledSteps = steps.filter((step) => !step.fulfilled);\n if (unfulfilledSteps.length !== 1) return;\n\n const op = unfulfilledSteps[0];\n\n if (\n op &&\n op.op === StepOpCode.StepPlanned\n // TODO We must individually check properties here that we do not want to\n // execute on, such as retry counts. Nothing exists here that falls in to\n // this case, but should be accounted for when we add them.\n // && typeof op.opts === \"undefined\"\n ) {\n return op.hashedId;\n }\n\n return;\n }\n\n private async filterNewSteps(\n foundSteps: FoundStep[],\n ): Promise<[OutgoingOp, ...OutgoingOp[]] | undefined> {\n if (this.options.requestedRunStep) {\n return;\n }\n\n /**\n * Gather any steps that aren't memoized and report them.\n */\n const newSteps = foundSteps.reduce((acc, step) => {\n if (!step.hasStepState) {\n acc.push(step);\n }\n\n return acc;\n }, [] as FoundStep[]);\n\n if (!newSteps.length) {\n return;\n }\n\n /**\n * We're finishing up; let's trigger the last of the hooks.\n */\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n\n const stepList = newSteps.map<OutgoingOp>((step) => ({\n displayName: step.displayName,\n op: step.op,\n id: step.hashedId,\n name: step.name,\n opts: step.opts,\n userland: step.userland,\n })) as [OutgoingOp, ...OutgoingOp[]];\n\n /**\n * We also run `onSendEvent` middleware hooks against `step.invoke()` steps\n * to ensure that their `data` is transformed correctly.\n */\n return await this.transformNewSteps(stepList);\n }\n\n /**\n * Using middleware, transform any newly-found steps before returning them to\n * an Inngest Server.\n */\n private async transformNewSteps<T extends [OutgoingOp, ...OutgoingOp[]]>(\n steps: T,\n ): Promise<T> {\n return Promise.all(\n steps.map(async (step) => {\n if (step.op !== StepOpCode.InvokeFunction) {\n return step;\n }\n\n const onSendEventHooks = await getHookStack(\n this.options.fn[\"middleware\"],\n \"onSendEvent\",\n undefined,\n {\n transformInput: (prev, output) => {\n return { ...prev, ...output };\n },\n transformOutput: (prev, output) => {\n return {\n result: { ...prev.result, ...output?.result },\n };\n },\n },\n );\n\n /**\n * For each event being sent, create a new `onSendEvent` hook stack to\n * process it. We do this as middleware hooks are intended to run once\n * during each lifecycle (onFunctionRun or onSendEvent) and here, a hook\n * is run for every single event.\n *\n * This is done because a developer can use this hook to filter out\n * events entirely; if we batch all of the events together, we can't\n * tell which ones were filtered out if we're processing >1 invocation\n * here.\n */\n const transformedPayload = await onSendEventHooks.transformInput?.({\n payloads: [\n {\n ...(step.opts?.payload ?? {}),\n name: internalEvents.FunctionInvoked,\n },\n ],\n });\n\n const newPayload = invokePayloadSchema.parse(\n transformedPayload?.payloads?.[0] ?? {},\n );\n\n return {\n ...step,\n opts: {\n ...step.opts,\n payload: {\n ...(step.opts?.payload ?? {}),\n ...newPayload,\n },\n },\n };\n }),\n ) as Promise<T>;\n }\n\n private async executeStep({\n id,\n name,\n opts,\n fn,\n displayName,\n userland,\n hashedId,\n }: FoundStep): Promise<OutgoingOp> {\n this.debug(`preparing to execute step \"${id}\"`);\n\n this.timeout?.clear();\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n\n const outgoingOp: OutgoingOp = {\n id: hashedId,\n op: StepOpCode.StepRun,\n name,\n opts,\n displayName,\n userland,\n };\n this.state.executingStep = outgoingOp;\n\n const store = await getAsyncCtx();\n\n if (store?.execution) {\n store.execution.executingStep = {\n id,\n name: displayName,\n };\n }\n\n this.debug(`executing step \"${id}\"`);\n\n let interval: GoInterval | undefined;\n\n return goIntervalTiming(() => runAsPromise(fn))\n .finally(async () => {\n this.debug(`finished executing step \"${id}\"`);\n\n if (store?.execution) {\n delete store.execution.executingStep;\n }\n\n await this.state.hooks?.afterExecution?.();\n })\n .then<OutgoingOp>(async ({ resultPromise, interval: _interval }) => {\n interval = _interval;\n const metadata = this.state.metadata?.get(id);\n\n return {\n ...outgoingOp,\n data: await resultPromise,\n ...(metadata && metadata.length > 0 ? { metadata } : {}),\n };\n })\n .catch<OutgoingOp>((error) => {\n let errorIsRetriable = true;\n\n if (\n error instanceof NonRetriableError ||\n // biome-ignore lint/suspicious/noExplicitAny: instanceof fails across module boundaries\n (error as any)?.name === \"NonRetriableError\"\n ) {\n errorIsRetriable = false;\n } else if (\n this.fnArg.maxAttempts &&\n this.fnArg?.maxAttempts - 1 === this.fnArg.attempt\n ) {\n errorIsRetriable = false;\n }\n\n const metadata = this.state.metadata?.get(id);\n\n // Serialize the error so it survives JSON.stringify (raw Error\n // objects have non-enumerable properties that get dropped).\n // This is critical for checkpoint requests where the error is\n // sent as JSON in the request body.\n const serialized = serializeError(error);\n\n if (errorIsRetriable) {\n return {\n ...outgoingOp,\n op: StepOpCode.StepError,\n error: serialized,\n ...(metadata && metadata.length > 0 ? { metadata } : {}),\n };\n } else {\n return {\n ...outgoingOp,\n op: StepOpCode.StepFailed,\n error: serialized,\n ...(metadata && metadata.length > 0 ? { metadata } : {}),\n };\n }\n })\n .then((op) => ({\n ...op,\n timing: interval,\n }));\n }\n\n /**\n * Starts execution of the user's function, including triggering checkpoints\n * and middleware hooks where appropriate.\n */\n private async startExecution(): Promise<void> {\n /**\n * Mutate input as neccessary based on middleware.\n */\n await this.transformInput();\n\n /**\n * Start the timer to time out the run if needed.\n */\n void this.timeout?.start();\n void this.checkpointingMaxRuntimeTimer?.start();\n void this.checkpointingMaxBufferIntervalTimer?.start();\n\n await this.state.hooks?.beforeMemoization?.();\n\n /**\n * If we had no state to begin with, immediately end the memoization phase.\n */\n if (this.state.allStateUsed()) {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n }\n\n /**\n * Trigger the user's function.\n */\n runAsPromise(() => this.userFnToRun(this.fnArg))\n .finally(async () => {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n })\n .then((data) => {\n this.state.setCheckpoint({ type: \"function-resolved\", data });\n })\n .catch((error) => {\n this.state.setCheckpoint({ type: \"function-rejected\", error });\n });\n }\n\n /**\n * Using middleware, transform input before running.\n */\n private async transformInput() {\n const inputMutations = await this.state.hooks?.transformInput?.({\n ctx: { ...this.fnArg },\n steps: Object.values(this.state.stepState),\n fn: this.options.fn,\n reqArgs: this.options.reqArgs,\n });\n\n if (inputMutations?.ctx) {\n this.fnArg = inputMutations.ctx;\n }\n\n if (inputMutations?.steps) {\n this.state.stepState = Object.fromEntries(\n inputMutations.steps.map((step) => [step.id, step]),\n );\n }\n }\n\n /**\n * Using middleware, transform output before returning.\n */\n private async transformOutput(\n dataOrError: Parameters<\n NonNullable<RunHookStack[\"transformOutput\"]>\n >[0][\"result\"],\n ): Promise<ExecutionResult> {\n const output = { ...dataOrError } as Partial<OutgoingOp>;\n\n const step = this.state.executingStep;\n delete this.state.executingStep;\n\n const isStepExecution = Boolean(step);\n\n const transformedOutput = await this.state.hooks?.transformOutput?.({\n result: { ...output },\n step,\n });\n\n const { data, error } = { ...output, ...transformedOutput?.result };\n\n if (!isStepExecution) {\n await this.state.hooks?.finished?.({\n result: { ...(typeof error !== \"undefined\" ? { error } : { data }) },\n });\n }\n\n if (typeof error !== \"undefined\") {\n /**\n * Ensure we give middleware the chance to decide on retriable behaviour\n * by looking at the error returned from output transformation.\n */\n let retriable: boolean | string = !(\n error instanceof NonRetriableError ||\n // biome-ignore lint/suspicious/noExplicitAny: instanceof fails across module boundaries\n (error as any)?.name === \"NonRetriableError\" ||\n (error instanceof StepError &&\n error === this.state.recentlyRejectedStepError)\n );\n if (\n retriable &&\n (error instanceof RetryAfterError ||\n // biome-ignore lint/suspicious/noExplicitAny: instanceof fails across module boundaries\n (error as any)?.name === \"RetryAfterError\")\n ) {\n retriable = (error as RetryAfterError).retryAfter;\n }\n\n const serializedError = minifyPrettyError(serializeError(error));\n\n return {\n type: \"function-rejected\",\n ctx: this.fnArg,\n ops: this.ops,\n error: serializedError,\n retriable,\n };\n }\n\n return {\n type: \"function-resolved\",\n ctx: this.fnArg,\n ops: this.ops,\n data: undefinedToNull(data),\n };\n }\n\n private createExecutionState(): V2ExecutionState {\n const d = createDeferredPromiseWithStack<Checkpoint>();\n let checkpointResolve = d.deferred.resolve;\n const checkpointResults = d.results;\n\n const loop: V2ExecutionState[\"loop\"] = (async function* (\n cleanUp?: () => void,\n ) {\n try {\n while (true) {\n const res = (await checkpointResults.next()).value;\n if (res) {\n yield res;\n }\n }\n } finally {\n cleanUp?.();\n }\n })(() => {\n this.timeout?.clear();\n this.checkpointingMaxRuntimeTimer?.clear();\n this.checkpointingMaxBufferIntervalTimer?.clear();\n void checkpointResults.return();\n });\n\n const stepsToFulfill = Object.keys(this.options.stepState).length;\n\n const state: V2ExecutionState = {\n stepState: this.options.stepState,\n stepsToFulfill,\n steps: new Map(),\n loop,\n hasSteps: Boolean(stepsToFulfill),\n stepCompletionOrder: [...this.options.stepCompletionOrder],\n remainingStepsToBeSeen: new Set(this.options.stepCompletionOrder),\n setCheckpoint: (checkpoint: Checkpoint) => {\n this.debug(\"setting checkpoint:\", checkpoint.type);\n\n ({ resolve: checkpointResolve } = checkpointResolve(checkpoint));\n },\n allStateUsed: () => {\n return this.state.remainingStepsToBeSeen.size === 0;\n },\n checkpointingStepBuffer: [],\n metadata: new Map(),\n };\n\n return state;\n }\n\n get ops(): Record<string, MemoizedOp> {\n return Object.fromEntries(this.state.steps);\n }\n\n private createFnArg(): Context.Any {\n const step = this.createStepTools();\n\n let fnArg = {\n ...(this.options.data as { event: EventPayload }),\n step,\n } as Context.Any;\n\n /**\n * Handle use of the `onFailure` option by deserializing the error.\n */\n if (this.options.isFailureHandler) {\n const eventData = z\n .object({ error: jsonErrorSchema })\n .parse(fnArg.event?.data);\n\n (fnArg as Partial<Pick<FailureEventArgs, \"error\">>) = {\n ...fnArg,\n error: deserializeError(eventData.error),\n };\n }\n\n return this.options.transformCtx?.(fnArg) ?? fnArg;\n }\n\n private createStepTools(): ReturnType<typeof createStepTools> {\n /**\n * A list of steps that have been found and are being rolled up before being\n * reported to the core loop.\n */\n const foundStepsToReport: Map<string, FoundStep> = new Map();\n\n /**\n * A map of the subset of found steps to report that have not yet been\n * handled. Used for fast access to steps that need to be handled in order.\n */\n const unhandledFoundStepsToReport: Map<string, FoundStep> = new Map();\n\n /**\n * A map of the latest sequential step indexes found for each step ID. Used\n * to ensure that we don't index steps in parallel.\n *\n * Note that these must be sequential; if we've seen or assigned `a:1`,\n * `a:2` and `a:4`, the latest sequential step index is `2`.\n *\n */\n const expectedNextStepIndexes: Map<string, number> = new Map();\n\n /**\n * A promise that's used to ensure that step reporting cannot be run more than\n * once in a given asynchronous time span.\n */\n let foundStepsReportPromise: Promise<void> | undefined;\n\n /**\n * A promise that's used to represent middleware hooks running before\n * execution.\n */\n let beforeExecHooksPromise: Promise<void> | undefined;\n\n /**\n * A helper used to report steps to the core loop. Used after adding an item\n * to `foundStepsToReport`.\n */\n const reportNextTick = () => {\n // Being explicit instead of using `??=` to appease TypeScript.\n if (foundStepsReportPromise) {\n return;\n }\n\n foundStepsReportPromise = resolveAfterPending()\n /**\n * Ensure that we wait for this promise to resolve before continuing.\n *\n * The groups in which steps are reported can affect how we detect some\n * more complex determinism issues like parallel indexing. This promise\n * can represent middleware hooks being run early, in the middle of\n * ingesting steps to report.\n *\n * Because of this, it's important we wait for this middleware to resolve\n * before continuing to report steps to ensure that all steps have a\n * chance to be reported throughout this asynchronous action.\n */\n .then(() => beforeExecHooksPromise)\n .then(() => {\n foundStepsReportPromise = undefined;\n\n for (const [hashedId, step] of unhandledFoundStepsToReport) {\n // Note that we only run `step.handle()` if `step.hasStepState` is\n // `true`. This gives us a chance to handle checkpointing in another\n // part of the loop.\n if (\n (this.options.stepMode === StepMode.Async || step.hasStepState) &&\n step.handle()\n ) {\n unhandledFoundStepsToReport.delete(hashedId);\n\n if (step.fulfilled) {\n foundStepsToReport.delete(step.id);\n }\n }\n }\n\n if (foundStepsToReport.size) {\n const steps = [...foundStepsToReport.values()] as [\n FoundStep,\n ...FoundStep[],\n ];\n\n foundStepsToReport.clear();\n unhandledFoundStepsToReport.clear();\n\n return void this.state.setCheckpoint({\n type: \"steps-found\",\n steps: steps,\n });\n }\n });\n };\n\n /**\n * A helper used to push a step to the list of steps to report.\n */\n const pushStepToReport = (step: FoundStep) => {\n foundStepsToReport.set(step.hashedId, step);\n unhandledFoundStepsToReport.set(step.hashedId, step);\n reportNextTick();\n };\n\n const stepHandler: StepHandler = async ({\n args,\n matchOp,\n opts,\n }): Promise<unknown> => {\n await beforeExecHooksPromise;\n\n const stepOptions = getStepOptions(args[0]);\n const opId = matchOp(stepOptions, ...args.slice(1));\n\n if (this.state.executingStep) {\n /**\n * If a step is found after asynchronous actions during another step's\n * execution, everything is fine. The problem here is if we've found\n * that a step nested inside another a step, which is something we don't\n * support at the time of writing.\n *\n * In this case, we could use something like Async Hooks to understand\n * how the step is being triggered, though this isn't available in all\n * environments.\n *\n * Therefore, we'll only show a warning here to indicate that this is\n * potentially an issue.\n */\n this.options.client[\"warnMetadata\"](\n { run_id: this.fnArg.runId },\n ErrCode.NESTING_STEPS,\n prettyError({\n whatHappened: `We detected that you have nested \\`step.*\\` tooling in \\`${\n opId.displayName ?? opId.id\n }\\``,\n consequences: \"Nesting `step.*` tooling is not supported.\",\n type: \"warn\",\n reassurance:\n \"It's possible to see this warning if steps are separated by regular asynchronous calls, which is fine.\",\n stack: true,\n toFixNow:\n \"Make sure you're not using `step.*` tooling inside of other `step.*` tooling. If you need to compose steps together, you can create a new async function and call it from within your step function, or use promise chaining.\",\n code: ErrCode.NESTING_STEPS,\n }),\n );\n }\n\n if (this.state.steps.has(_internals.hashId(opId.id))) {\n const originalId = opId.id;\n\n const expectedNextIndex = expectedNextStepIndexes.get(originalId) ?? 1;\n for (let i = expectedNextIndex; ; i++) {\n const newId = originalId + STEP_INDEXING_SUFFIX + i;\n\n if (!this.state.steps.has(_internals.hashId(newId))) {\n expectedNextStepIndexes.set(originalId, i + 1);\n opId.id = newId;\n opId.userland.index = i;\n break;\n }\n }\n }\n\n const { promise, resolve, reject } = createDeferredPromise();\n const hashedId = _internals.hashId(opId.id);\n const stepState = this.state.stepState[hashedId];\n let isFulfilled = false;\n if (stepState) {\n stepState.seen = true;\n this.state.remainingStepsToBeSeen.delete(hashedId);\n\n if (typeof stepState.input === \"undefined\") {\n isFulfilled = true;\n }\n }\n\n let extraOpts: Record<string, unknown> | undefined;\n let fnArgs = [...args];\n\n if (\n typeof stepState?.input !== \"undefined\" &&\n Array.isArray(stepState.input)\n ) {\n switch (opId.op) {\n // `step.run()` has its function input affected\n case StepOpCode.StepPlanned: {\n fnArgs = [...args.slice(0, 2), ...stepState.input];\n\n extraOpts = { input: [...stepState.input] };\n break;\n }\n\n // `step.ai.infer()` has its body affected\n case StepOpCode.AiGateway: {\n extraOpts = {\n body: {\n ...(typeof opId.opts?.body === \"object\"\n ? { ...opId.opts.body }\n : {}),\n ...stepState.input[0],\n },\n };\n break;\n }\n }\n }\n\n const step: FoundStep = {\n ...opId,\n opts: { ...opId.opts, ...extraOpts },\n rawArgs: fnArgs, // TODO What is the right value here? Should this be raw args without affected input?\n hashedId,\n input: stepState?.input,\n\n fn: opts?.fn ? () => opts.fn?.(this.fnArg, ...fnArgs) : undefined,\n promise,\n fulfilled: isFulfilled,\n hasStepState: Boolean(stepState),\n displayName: opId.displayName ?? opId.id,\n handled: false,\n handle: () => {\n if (step.handled) {\n return false;\n }\n\n this.debug(`handling step \"${hashedId}\"`);\n\n step.handled = true;\n\n // Refetch step state because it may have been changed since we found\n // the step. This could be due to checkpointing, where we run this\n // live and then return to the function.\n const result = this.state.stepState[hashedId];\n\n if (step.fulfilled && result) {\n result.fulfilled = true;\n\n // For some execution scenarios such as testing, `data`, `error`,\n // and `input` may be `Promises`. This could also be the case for\n // future middleware applications. For this reason, we'll make sure\n // the values are fully resolved before continuing.\n void Promise.all([result.data, result.error, result.input]).then(\n () => {\n if (typeof result.data !== \"undefined\") {\n resolve(result.data);\n } else {\n this.state.recentlyRejectedStepError = new StepError(\n opId.id,\n result.error,\n );\n reject(this.state.recentlyRejectedStepError);\n }\n },\n );\n }\n\n return true;\n },\n };\n\n this.state.steps.set(hashedId, step);\n this.state.hasSteps = true;\n pushStepToReport(step);\n\n /**\n * If this is the last piece of state we had, we've now finished\n * memoizing.\n */\n if (!beforeExecHooksPromise && this.state.allStateUsed()) {\n // biome-ignore lint/suspicious/noAssignInExpressions: intentional\n await (beforeExecHooksPromise = (async () => {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n })());\n }\n\n return promise;\n };\n\n return createStepTools(this.options.client, this, stepHandler);\n }\n\n private resumeStepWithResult(resultOp: OutgoingOp, resume = true): FoundStep {\n const userlandStep = this.state.steps.get(resultOp.id);\n if (!userlandStep) {\n throw new Error(\n \"Step not found in memoization state during async checkpointing; this should never happen and is a bug in the Inngest SDK\",\n );\n }\n\n const data = undefinedToNull(resultOp.data);\n\n userlandStep.data = data;\n userlandStep.timing = resultOp.timing;\n userlandStep.op = resultOp.op;\n userlandStep.id = resultOp.id;\n userlandStep.hasStepState = true;\n\n if (resume) {\n userlandStep.fulfilled = true;\n this.state.stepState[resultOp.id] = userlandStep;\n\n userlandStep.handle();\n }\n\n return userlandStep;\n }\n\n private getUserFnToRun(): Handler.Any {\n if (!this.options.isFailureHandler) {\n return this.options.fn[\"fn\"];\n }\n\n if (!this.options.fn[\"onFailureFn\"]) {\n /**\n * Somehow, we've ended up detecting that this is a failure handler but\n * doesn't have an `onFailure` function. This should never happen.\n */\n throw new Error(\"Cannot find function `onFailure` handler\");\n }\n\n return this.options.fn[\"onFailureFn\"];\n }\n\n private initializeTimer(state: V2ExecutionState): void {\n if (!this.options.requestedRunStep) {\n return;\n }\n\n this.timeout = createTimeoutPromise(this.timeoutDuration);\n\n void this.timeout.then(async () => {\n const { foundSteps, totalFoundSteps } = this.getStepNotFoundDetails();\n\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n\n state.setCheckpoint({\n type: \"step-not-found\",\n step: {\n id: this.options.requestedRunStep as string,\n op: StepOpCode.StepNotFound,\n },\n foundSteps,\n totalFoundSteps,\n });\n });\n }\n\n private getStepNotFoundDetails(): {\n foundSteps: BasicFoundStep[];\n totalFoundSteps: number;\n } {\n const foundSteps = [...this.state.steps.values()]\n .filter((step) => !step.hasStepState)\n .map<BasicFoundStep>((step) => ({\n id: step.hashedId,\n name: step.name,\n displayName: step.displayName,\n }))\n .sort((a, b) => a.id.localeCompare(b.id));\n\n return {\n foundSteps: foundSteps.slice(0, STEP_NOT_FOUND_MAX_FOUND_STEPS),\n totalFoundSteps: foundSteps.length,\n };\n }\n\n private initializeCheckpointRuntimeTimer(state: V2ExecutionState): void {\n this.debug(\n \"initializing checkpointing runtime timers\",\n this.options.checkpointingConfig,\n );\n\n if (this.options.checkpointingConfig?.maxRuntime) {\n const maxRuntimeMs = Temporal.isTemporalDuration(\n this.options.checkpointingConfig.maxRuntime,\n )\n ? this.options.checkpointingConfig.maxRuntime.total({\n unit: \"milliseconds\",\n })\n : typeof this.options.checkpointingConfig.maxRuntime === \"string\"\n ? ms(this.options.checkpointingConfig.maxRuntime as StringValue) // type assertion to satisfy ms package\n : (this.options.checkpointingConfig.maxRuntime as number);\n\n // 0 or negative max runtime? Skip.\n if (Number.isFinite(maxRuntimeMs) && maxRuntimeMs > 0) {\n this.checkpointingMaxRuntimeTimer = createTimeoutPromise(maxRuntimeMs);\n\n void this.checkpointingMaxRuntimeTimer.then(async () => {\n await this.state.hooks?.afterMemoization?.();\n await this.state.hooks?.beforeExecution?.();\n await this.state.hooks?.afterExecution?.();\n\n state.setCheckpoint({\n type: \"checkpointing-runtime-reached\",\n });\n });\n }\n }\n\n if (this.options.checkpointingConfig?.maxInterval) {\n const maxIntervalMs = Temporal.isTemporalDuration(\n this.options.checkpointingConfig.maxInterval,\n )\n ? this.options.checkpointingConfig.maxInterval.total({\n unit: \"milliseconds\",\n })\n : typeof this.options.checkpointingConfig.maxInterval === \"string\"\n ? ms(this.options.checkpointingConfig.maxInterval as StringValue) // type assertion to satisfy ms package\n : (this.options.checkpointingConfig.maxInterval as number);\n\n // 0 or negative max interval? Skip.\n if (Number.isFinite(maxIntervalMs) && maxIntervalMs > 0) {\n this.checkpointingMaxBufferIntervalTimer =\n createTimeoutPromise(maxIntervalMs);\n\n void this.checkpointingMaxBufferIntervalTimer.then(async () => {\n // Note that this will not immediately run; it will be queued like all\n // other checkpoints so that we're never running multiple checkpoints\n // at the same time and it's easier to reason about those decision\n // points.\n //\n // A change in the future may be to make this particular checkpointing\n // action immediate and have the checkpoint action itself be\n // idempotent.\n state.setCheckpoint({\n type: \"checkpointing-buffer-interval-reached\",\n });\n\n this.checkpointingMaxBufferIntervalTimer?.reset();\n });\n }\n }\n }\n\n private async initializeMiddleware(): Promise<RunHookStack> {\n const ctx = this.options.data as Pick<\n Readonly<BaseContext<Inngest.Any>>,\n \"event\" | \"events\" | \"runId\"\n >;\n\n const hooks = await getHookStack(\n this.options.fn[\"middleware\"],\n \"onFunctionRun\",\n {\n ctx,\n fn: this.options.fn,\n steps: Object.values(this.options.stepState),\n reqArgs: this.options.reqArgs,\n },\n {\n transformInput: (prev, output) => {\n return {\n ctx: { ...prev.ctx, ...output?.ctx },\n fn: this.options.fn,\n steps: prev.steps.map((step, i) => ({\n ...step,\n ...output?.steps?.[i],\n })),\n reqArgs: prev.reqArgs,\n };\n },\n transformOutput: (prev, output) => {\n return {\n result: { ...prev.result, ...output?.result },\n step: prev.step,\n };\n },\n },\n );\n\n return hooks;\n }\n}\n\n/**\n * Types of checkpoints that can be reached during execution.\n */\nexport interface Checkpoints {\n \"steps-found\": { steps: [FoundStep, ...FoundStep[]] };\n \"function-rejected\": { error: unknown };\n \"function-resolved\": { data: unknown };\n \"step-not-found\": {\n step: OutgoingOp;\n foundSteps: BasicFoundStep[];\n totalFoundSteps: number;\n };\n \"checkpointing-runtime-reached\": {};\n \"checkpointing-buffer-interval-reached\": {};\n}\n\ntype Checkpoint = {\n [K in keyof Checkpoints]: Simplify<{ type: K } & Checkpoints[K]>;\n}[keyof Checkpoints];\n\ntype CheckpointHandlers = Record<\n StepMode,\n {\n [C in Checkpoint as C[\"type\"]]: (\n checkpoint: C,\n\n /**\n * This is the number of checkpoints that have been seen before this one was\n * triggered.\n *\n * The catch-all `\"\"` checkpoint does not increment this count.\n */\n i: number,\n ) => MaybePromise<ExecutionResult | undefined>;\n } & {\n \"\": (\n checkpoint: Checkpoint,\n\n /**\n * This is the number of checkpoints that have been seen before this one was\n * triggered.\n *\n * The catch-all `\"\"` checkpoint does not increment this count.\n */\n i: number,\n ) => MaybePromise<void>;\n }\n>;\n\nexport interface V2ExecutionState {\n /**\n * A value that indicates that we're executing this step. Can be used to\n * ensure steps are not accidentally nested until we support this across all\n * platforms.\n */\n executingStep?: Readonly<Omit<OutgoingOp, \"id\">>;\n\n /**\n * A map of step IDs to their data, used to fill previously-completed steps\n * with state from the executor.\n */\n stepState: Record<string, MemoizedOp>;\n\n /**\n * The number of steps we expect to fulfil based on the state passed from the\n * Executor.\n */\n stepsToFulfill: number;\n\n /**\n * A map of step IDs to their functions to run. The executor can request a\n * specific step to run, so we need to store the function to run here.\n */\n steps: Map<string, FoundStep>;\n\n /**\n * A flag which represents whether or not steps are understood to be used in\n * this function. This is used to determine whether or not we should run\n * some steps (such as `step.sendEvent`) inline as they are found.\n */\n hasSteps: boolean;\n\n /**\n * The core loop - a generator used to take an action upon finding the next\n * checkpoint. Manages the flow of execution and cleaning up after itself.\n */\n loop: AsyncGenerator<Checkpoint, void, void>;\n\n /**\n * A function that resolves the `Promise` returned by `waitForNextDecision`.\n */\n setCheckpoint: (data: Checkpoint) => void;\n\n /**\n * Initialized middleware hooks for this execution.\n *\n * Middleware hooks are cached to ensure they can only be run once, which\n * means that these hooks can be called in many different places to ensure we\n * handle all possible execution paths.\n */\n hooks?: RunHookStack;\n\n /**\n * Returns whether or not all state passed from the executor has been used to\n * fulfill found steps.\n */\n allStateUsed: () => boolean;\n\n /**\n * An ordered list of step IDs that represents the order in which their\n * execution was completed.\n */\n stepCompletionOrder: string[];\n\n /**\n * An set of step IDs that have yet to be seen in this execution. Used to\n * decide when to trigger middleware based on the current state.\n */\n remainingStepsToBeSeen: Set<string>;\n\n /**\n * If defined, this is the error that purposefully thrown when memoizing step\n * state in order to support per-step errors.\n *\n * We use this so that if the function itself rejects with the same error, we\n * know that it was entirely uncaught (or at the very least rethrown), so we\n * should send a `NonRetriableError` to stop needless execution of a function\n * that will continue to fail.\n *\n * TODO This is imperfect, as this state is currently kept around for longer\n * than it needs to be. It should disappear as soon as we've seen that the\n * error did not immediately throw. It may need to be refactored to work a\n * little more smoothly with the core loop.\n */\n recentlyRejectedStepError?: StepError;\n\n /**\n * If defined, this indicates that we're running a checkpointed function run,\n * and contains the data needed to report progress back to Inngest.\n */\n checkpointedRun?: {\n fnId: string;\n appId: string;\n token?: string;\n };\n\n /**\n * A buffer of steps that are currently queued to be checkpointed.\n */\n checkpointingStepBuffer: OutgoingOp[];\n\n /**\n * Metadata collected during execution to be sent with outgoing ops.\n */\n metadata?: Map<string, Array<MetadataUpdate>>;\n}\n\nconst hashId = (id: string): string => {\n return sha1().update(id).digest(\"hex\");\n};\n\nconst hashOp = (op: OutgoingOp): OutgoingOp => {\n return {\n ...op,\n id: hashId(op.id),\n };\n};\n\n/**\n * Exported for testing.\n */\nexport const _internals = { hashOp, hashId };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,MAAM,EAAE,SAASA;;;;;;;;;AAUjB,MAAM,2BAA2B;CAAE,aAAa;CAAG,WAAW;CAAK;AACnE,MAAM,iCAAiC;AAEvC,MAAaC,4BAAqD,YAAY;AAC5E,QAAO,IAAI,mBAAmB,QAAQ;;AAGxC,IAAM,qBAAN,cAAiCC,0CAA8C;CAC7E,AAAO,UAAUC,gCAAiB;CAElC,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ,kBAAkB,MAAO;CACjC,AAAQ;CACR,AAAQ;;;;;;;;CASR,AAAQ;;;;;;;CAQR,AAAQ;;;;;;CASR,AAAQ;CAIR,YAAY,YAAqC;EAC/C,MAAMC,UAAmC;GACvC,GAAG;GACH,UAAU,WAAW,YAAYC,uBAAS;GAC3C;AAED,QAAM,QAAQ;;;;AAKd,MAAI,KAAK,QAAQ,aAAaA,uBAAS,MACrC;OAAI,CAAC,KAAK,QAAQ,eAChB,OAAM,IAAI,MAAM,gDAAgD;;AAIpE,OAAK,cAAc,KAAK,gBAAgB;AACxC,OAAK,QAAQ,KAAK,sB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;;;;2BAeH;;;;aAKd,YAAY,MAAM;;;;;cAiBlB;eAVO,eAAa"}
1
+ {"version":3,"file":"v2.d.ts","names":[],"sources":["../../../src/components/execution/v2.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;cAuFa,0BAA0B;;;;UAwqDtB,WAAA;;YACU,cAAc;;;IAzqD5B,KAAA,EAAA,OAAA;EAwqDI,CAAA;EAAW,mBAAA,EAAA;IACD,IAAA,EAAA,OAAA;;kBAIjB,EAAA;IACM,IAAA,EADN,UACM;IAAc,UAAA,EAAd,cAAc,EAAA;IAOzB,eAAU,EAAA,MAAA;EAAA,CAAA;iCACD,EAAA,CAAA,CAAA;yCAA+B,EAAA,CAAA,CAAA;;KADxC,UAAA,GAC0D,QAAnC,MAAd,WAAc,GAAA,QAAA,CAAA;EACpB,IAAA,EADqC,CACrC;AAAW,CAAA,GADgC,WAChC,CAD4C,CAC5C,CAAA,CAAA,EA+BnB,CAAA,MA/BQ,WA+BS,CAAA;AAAgB,UAAhB,gBAAA,CAAgB;;;;;;eAwBZ,CAAA,EAlBH,QAkBG,CAlBM,IAkBN,CAlBW,UAkBX,EAAA,IAAA,CAAA,CAAA;;;;;WA2BX,EAvCG,MAuCH,CAAA,MAAA,EAvCkB,UAuClB,CAAA;;;;;gBAsDe,EAAA,MAAA;;;AAiBzB;;OAVoB,EAxFX,GAwFW,CAAA,MAAA,EAxFC,SAwFD,CAAA;;;;;;;;;;;QA3EZ,eAAe;;;;wBAKC;;;;;;;;UASd;;;;;;;;;;;;;;;0BAkBgB;;;;;;;;;;;;;;;8BAgBI;;;;;;;;;;;;;2BAeH;;;;aAKd,YAAY,MAAM;;;;;cAiBlB;eAVO,eAAa"}
@@ -423,9 +423,13 @@ var V2InngestExecution = class extends InngestExecution {
423
423
  const stepResult = await this.tryExecuteStep(newSteps);
424
424
  if (stepResult) {
425
425
  this.debug(`executed step "${stepResult.id}" successfully`);
426
- if (stepResult.error) return stepRanHandler(stepResult);
426
+ if (stepResult.error) {
427
+ if (this.state.checkpointingStepBuffer.length) await attemptCheckpointAndResume(void 0, false, true);
428
+ return stepRanHandler(stepResult);
429
+ }
427
430
  return await attemptCheckpointAndResume(stepResult);
428
431
  }
432
+ if (this.state.checkpointingStepBuffer.length) await attemptCheckpointAndResume(void 0, false, true);
429
433
  return maybeReturnNewSteps(steps);
430
434
  }
431
435
  if (stepsToResume.length) {