@smthrs/flow 1.0.0-rc.4 → 1.0.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/README.md +4 -4
  3. package/dist/cjs/DurableDeferred.js +3 -3
  4. package/dist/cjs/DurableDeferred.js.map +2 -2
  5. package/dist/cjs/DurableQueue.d.ts +1 -1
  6. package/dist/cjs/DurableQueue.d.ts.map +1 -1
  7. package/dist/cjs/DurableQueue.js +2 -2
  8. package/dist/cjs/DurableQueue.js.map +2 -2
  9. package/dist/cjs/Flow/ExecutionIds.js +1 -1
  10. package/dist/cjs/Flow/ExecutionIds.js.map +2 -2
  11. package/dist/cjs/Flow/Result.d.ts +1 -1
  12. package/dist/cjs/Flow/Result.d.ts.map +1 -1
  13. package/dist/cjs/Flow/Result.js.map +2 -2
  14. package/dist/cjs/Flow/Runtime.js +1 -1
  15. package/dist/cjs/Flow/Runtime.js.map +2 -2
  16. package/dist/cjs/Flow/internal.js +1 -1
  17. package/dist/cjs/Flow/internal.js.map +2 -2
  18. package/dist/cjs/Graph.d.ts.map +1 -1
  19. package/dist/cjs/Graph.js +1 -2
  20. package/dist/cjs/Graph.js.map +2 -2
  21. package/dist/esm/DurableDeferred.js +3 -3
  22. package/dist/esm/DurableDeferred.js.map +1 -1
  23. package/dist/esm/DurableQueue.d.ts +1 -1
  24. package/dist/esm/DurableQueue.d.ts.map +1 -1
  25. package/dist/esm/DurableQueue.js +2 -2
  26. package/dist/esm/DurableQueue.js.map +1 -1
  27. package/dist/esm/Flow/ExecutionIds.js +1 -1
  28. package/dist/esm/Flow/ExecutionIds.js.map +1 -1
  29. package/dist/esm/Flow/Result.d.ts +1 -1
  30. package/dist/esm/Flow/Result.d.ts.map +1 -1
  31. package/dist/esm/Flow/Result.js.map +1 -1
  32. package/dist/esm/Flow/Runtime.js +1 -1
  33. package/dist/esm/Flow/Runtime.js.map +1 -1
  34. package/dist/esm/Flow/internal.js +1 -1
  35. package/dist/esm/Flow/internal.js.map +1 -1
  36. package/dist/esm/Graph.d.ts.map +1 -1
  37. package/dist/esm/Graph.js +4 -2
  38. package/dist/esm/Graph.js.map +1 -1
  39. package/docs/README.md +1 -1
  40. package/docs/installation.md +4 -4
  41. package/docs/reference/flow.md +1 -1
  42. package/package.json +10 -10
  43. package/src/DurableDeferred.ts +3 -3
  44. package/src/DurableQueue.ts +2 -2
  45. package/src/Flow/ExecutionIds.ts +1 -1
  46. package/src/Flow/Result.ts +1 -1
  47. package/src/Flow/Runtime.ts +1 -1
  48. package/src/Flow/internal.ts +1 -1
  49. package/src/Graph.ts +5 -2
@@ -1 +1 @@
1
- {"version":3,"file":"DurableDeferred.js","sourceRoot":"","sources":["../../src/DurableDeferred.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAGnC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AAEzC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,IAAI,MAAM,aAAa,CAAA;AACnC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAA;AACtC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,YAAY,MAAM,qBAAqB,CAAA;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,KAAK,IAAI,MAAM,iBAAiB,CAAA;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAA;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,8BAA8B,CA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KAAK,CAAC,QAAQ;QACxB,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,IAAI,EAAE,OAAO,CAAC,IAAI;KACnB,CAAC,CAAA;AACJ,CAAC,CAAC,CACH,CAAA;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,OAAO,GAchB,IAAI,CACN,CAAC,EACD,CACE,IAAqC,EACrC,OAGC,EAC6E,EAAE,CAChF,IAAI,CAAC,IAAI,EAAE;IACT,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC;CAClC,CAAC,CACL,CAAA;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,IAAI,GAcb,IAAI,CACN,CAAC,EACD,CACE,IAAqC,EACrC,OAGC,EAC2E,EAAE,CAC9E,IAAI,CAAC,IAAI,EAAE;IACT,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;CAC/B,CAAC,CACL,CAAA;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,SAAS,GAclB,IAAI,CACN,CAAC,EACD,CACE,IAAqC,EACrC,OAGC,EAC2E,EAAE,CAC9E,IAAI,CAAC,IAAI,EAAE;IACT,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC;CACpC,CAAC,CACL,CAAA","sourcesContent":["// Deep reviewed and polished by a human on 2026-08-10.\n\n/**\n * Defines named wait points for durable flow executions.\n *\n * A `DurableDeferred` has a stable name and schemas for the value that will be\n * recorded later. Flows can await it, suspend when no result exists yet, and\n * resume after its result is recorded. Tokens identify the flow name,\n * execution id, and deferred name so external code can complete the correct\n * wait point later.\n *\n * @since 0.1.0\n */\n\nimport * as Arr from \"effect/Array\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport type * as Brand from \"effect/Brand\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Encoding from \"effect/Encoding\"\nimport * as Exit from \"effect/Exit\"\nimport * as Filter from \"effect/Filter\"\nimport { dual } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaGetter from \"effect/SchemaGetter\"\nimport { CurrentAttempt } from \"./Action/Context.ts\"\nimport * as Flow from \"./Flow/index.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\n\nconst TypeId = \"@smthrs/flow/DurableDeferred\"\n\n/**\n * Named durable deferred value whose completion is persisted by the flow\n * engine and encoded with success and error schemas.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DurableDeferred<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint = Schema.Never\n> {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n readonly successSchema: Success\n readonly errorSchema: Error\n readonly exitSchema: Schema.Exit<Schema.Top, Schema.Top, Schema.Top>\n readonly withActionAttempt: Effect.Effect<DurableDeferred<Success, Error>>\n}\n\n/**\n * Type-erased durable deferred shape for APIs that only need the deferred\n * identity and name.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Any {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n}\n\n/**\n * Type-erased durable deferred shape that also exposes success, error, and\n * exit schemas.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AnyWithProps {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n readonly successSchema: Schema.Top\n readonly errorSchema: Schema.Top\n readonly exitSchema: Schema.Exit<any, any, any>\n}\n\n// Queues, human tasks and clocks mint a deferred per item, attempt or sleep.\n// Effect caches compiled parsers by AST identity, so the exit schema is shared\n// per (success, error) pair rather than rebuilt for every deferred.\nconst exitSchemaCache = new WeakMap<object, WeakMap<object, Schema.Exit<any, any, any>>>()\n\nconst exitSchemaFor = (success: Schema.Constraint, error: Schema.Constraint): Schema.Exit<any, any, any> => {\n let byError = exitSchemaCache.get(success)\n if (byError === undefined) {\n byError = new WeakMap()\n exitSchemaCache.set(success, byError)\n }\n let cached = byError.get(error)\n if (cached === undefined) {\n cached = Schema.Exit(\n Schema.toCodecJson(success),\n Schema.toCodecJson(error),\n Schema.toCodecJson(Schema.Defect())\n )\n byError.set(error, cached)\n }\n return cached\n}\n\n/**\n * Creates a named durable deferred with optional success and error schemas for\n * persisted completion.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <\n Success extends Schema.Constraint = Schema.Void,\n Error extends Schema.Constraint = Schema.Never\n>(\n name: string,\n options?: {\n readonly success?: Success | undefined\n readonly error?: Error | undefined\n }\n): DurableDeferred<Success, Error> => {\n const successSchema = options?.success ?? (Schema.Void as any as Success)\n const errorSchema = options?.error ?? (Schema.Never as any as Error)\n return {\n [TypeId]: TypeId as typeof TypeId,\n name,\n successSchema,\n errorSchema,\n exitSchema: exitSchemaFor(successSchema, errorSchema) as any,\n withActionAttempt: Effect.gen(function*() {\n const attempt = yield* CurrentAttempt\n return make(`${name}/${attempt}`, {\n success: successSchema,\n error: errorSchema\n })\n })\n }\n}\n\nconst await_: <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n) => Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Error[\"DecodingServices\"]\n> =\n // Untraced because deferred polling participates in the flow scheduler hot path.\n Effect.fnUntraced(function*<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n >(self: DurableDeferred<Success, Error>) {\n const engine = yield* FlowRuntime\n const instance = yield* FlowInstance\n const exit = yield* Flow.wrapActionResult(\n engine.deferredResult(self),\n Option.isNone\n )\n if (Option.isNone(exit)) {\n return yield* Flow.suspend(instance)\n }\n const value = exit.value as Exit.Exit<any, any>\n // A recorded interruption is a durable *outcome*, not a request to\n // suspend: mark the instance interrupted before re-raising so\n // `Flow.intoResult` classifies the interrupt-only cause as a `Complete`\n // failure. Without this the driver mistakes the cause for an external\n // suspension interrupt, aborts without a terminal transition, and the\n // run spins in the suspended-retry loop forever.\n if (Exit.isFailure(value) && Cause.hasInterruptsOnly(value.cause)) {\n instance.interrupted = true\n }\n return yield* value\n })\n\nexport {\n /**\n * Waits for the durable deferred, suspending the current flow when no\n * persisted completion is available.\n *\n * @category combinators\n * @since 0.1.0\n */\n await_ as await\n}\n\n/**\n * Runs an effect and records its exit into the durable deferred, resuming\n * flows that are waiting on that deferred.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const into: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ): <R>(\n effect: Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>\n ) => Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | R\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n >\n <Success extends Schema.Constraint, Error extends Schema.Constraint, R>(\n effect: Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n self: DurableDeferred<Success, Error>\n ): Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | R\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n >\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint, R>(\n effect: Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n self: DurableDeferred<Success, Error>\n ): Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | R\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n > =>\n Effect.contextWith(\n (context: Context.Context<FlowRuntime | FlowInstance>) => {\n const engine = Context.get(context, FlowRuntime)\n const instance = Context.get(context, FlowInstance)\n // Keep the original instance: action regions identify their ancestors\n // by reference, and suspension metadata belongs to the enclosing flow.\n return Effect.onExit(\n effect,\n // Untraced because completion encoding is called for each deferred result.\n Effect.fnUntraced(function*(exit) {\n if (Exit.isFailure(exit)) {\n const [reasons, interrupts] = Arr.partition(\n exit.cause.reasons,\n Filter.fromPredicate(Cause.isInterruptReason)\n )\n const hasInterruptsOnly = interrupts.length === exit.cause.reasons.length\n if (hasInterruptsOnly) {\n // An interrupt-only exit is never a result: the effect was\n // suspended, preempted, or interrupted, so record nothing.\n // Recording here would durably persist the empty non-interrupt\n // partition, and first-writer-wins would replay that empty\n // cause forever instead of the real completion.\n return\n } else if (interrupts.length > 0) {\n exit = Exit.failCause(Cause.fromReasons(reasons))\n }\n }\n yield* engine.deferredDone(self, {\n flowName: instance.flow._tag,\n executionId: instance.executionId,\n deferredName: self.name,\n exit\n })\n })\n )\n }\n )\n)\n\n/**\n * Runs effects as a durable race, returning a previously persisted result when\n * present or completing a named deferred with the first success. The race\n * fails only when every effect fails.\n *\n * @category racing\n * @since 0.1.0\n */\nexport const raceAll = <\n const Effects extends NonEmptyReadonlyArray<Effect.Effect<any, any, any>>,\n Success extends Schema.Schema<Effect.Success<Effects[number]>>,\n Error extends Schema.Schema<Effect.Error<Effects[number]>>\n>(options: {\n name: string\n success: Success\n error: Error\n effects: Effects\n}): Effect.Effect<\n Effect.Success<Effects[number]>,\n Effect.Error<Effects[number]>,\n | Effect.Services<Effects[number]>\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n | FlowRuntime\n | FlowInstance\n> => {\n const deferred = make<any, any>(`raceAll/${options.name}`, {\n success: options.success,\n error: options.error\n })\n return Effect.gen(function*() {\n const engine = yield* FlowRuntime\n const exit = yield* engine.deferredResult(deferred)\n if (Option.isSome(exit)) {\n return yield* exit.value\n }\n return yield* into(\n Effect.raceAll(options.effects),\n deferred\n )\n })\n}\n\n/**\n * Runtime brand identifier for durable deferred tokens.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport const TokenTypeId = \"@smthrs/flow/DurableDeferred/Token\"\n\n/**\n * Type-level brand identifier for `Token` values.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport type TokenTypeId = typeof TokenTypeId\n\n/**\n * Branded string token identifying a durable deferred for a flow\n * execution.\n *\n * A token is an address, not a credential. It is unsigned base64url JSON of\n * the flow name, execution id, and deferred name, and `tokenFromExecutionId`\n * and `tokenFromPayload` rebuild it from those values alone. Anyone who can\n * call `done`, `succeed`, `fail`, `failCause`, or `HumanTask.answer` against\n * the run's `FlowRuntime` can complete an open wait whose address they know or\n * derive. A host that exposes completion to other parties must authorize the\n * caller before it calls one of them.\n *\n * @category token\n * @since 0.1.0\n */\nexport type Token = Brand.Branded<string, TokenTypeId>\n\n/**\n * Schema for branded durable deferred tokens.\n *\n * @category token\n * @since 0.1.0\n */\nexport const Token: Schema.brand<Schema.String, TokenTypeId> = Schema.String.pipe(Schema.brand(TokenTypeId))\n\n/**\n * A completion token could not be decoded into its durable address.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class TokenInvalid extends Schema.TaggedError<TokenInvalid>()(\"@smthrs/flow/DurableDeferred/TokenInvalid\", {\n code: Schema.Literals([\"malformed_token\", \"deferred_mismatch\"]).pipe(\n Schema.withConstructorDefault(Effect.succeed(\"malformed_token\"))\n ),\n message: Schema.String\n}) {}\n\n/**\n * Schema for a decoded durable deferred token containing the flow\n * name, execution ID, and deferred name.\n *\n * @category token\n * @since 0.1.0\n */\nexport class TokenParsed extends Schema.Class<TokenParsed>(\n \"@smthrs/flow/DurableDeferred/TokenParsed\"\n)({\n flowName: Schema.String,\n executionId: Schema.String,\n deferredName: Schema.String\n}) {\n /**\n * Encodes the parsed flow, execution, and deferred names back into a token.\n *\n * @since 0.1.0\n */\n get asToken(): Token {\n return Encoding.encodeBase64Url(\n JSON.stringify([this.flowName, this.executionId, this.deferredName])\n ) as Token\n }\n\n /**\n * Schema for decoding and encoding durable deferred tokens as strings.\n *\n * @since 0.1.0\n */\n static readonly FromString = Schema.String.pipe(\n Schema.decodeTo(\n Schema.fromJsonString(\n Schema.Tuple([Schema.String, Schema.String, Schema.String])\n ),\n {\n decode: SchemaGetter.decodeBase64UrlString(),\n encode: SchemaGetter.encodeBase64Url()\n }\n ),\n Schema.decodeTo(TokenParsed, {\n decode: SchemaGetter.transform(\n ([flowName, executionId, deferredName]) =>\n new TokenParsed({\n flowName,\n executionId,\n deferredName\n })\n ),\n encode: SchemaGetter.transform(\n (parsed) =>\n [\n parsed.flowName,\n parsed.executionId,\n parsed.deferredName\n ] as const\n )\n })\n )\n\n /**\n * Decodes a durable deferred token string into its parsed components.\n *\n * @since 0.1.0\n */\n static readonly fromString = Schema.decodeSync(TokenParsed.FromString)\n\n /**\n * Encodes parsed durable deferred token components into a token string.\n *\n * @since 0.1.0\n */\n static readonly encode = Schema.encodeSync(TokenParsed.FromString)\n\n /**\n * Parses an untrusted token into its durable address with a typed,\n * bounded diagnostic on failure.\n *\n * @category token\n * @since 1.0.0\n */\n static readonly parse = (token: string): Effect.Effect<TokenParsed, TokenInvalid> =>\n Effect.mapError(\n Schema.decodeEffect(TokenParsed.FromString)(token),\n (issue) =>\n new TokenInvalid({\n message: `The supplied token \"${tokenExcerpt(token)}\" is not a durable deferred token: ${issue.message}`\n })\n )\n}\n\nconst maxTokenExcerptChars = 64\n\n/** Renders a bounded excerpt of untrusted token content for a diagnostic. */\nconst tokenExcerpt = (token: string): string =>\n token.length <= maxTokenExcerptChars\n ? token\n : `${token.slice(0, maxTokenExcerptChars)} [${token.length - maxTokenExcerptChars} characters dropped]`\n\n/**\n * Creates a token for a durable deferred using the current flow instance's\n * flow name and execution ID.\n *\n * @category token\n * @since 0.1.0\n */\nexport const token: <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n) => Effect.Effect<Token, never, FlowInstance> =\n // Untraced because token allocation is on the durable-deferred hot path.\n Effect.fnUntraced(\n function*<Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ) {\n const instance = yield* FlowInstance\n return tokenFromExecutionId(self, instance)\n }\n )\n\n/**\n * Creates a durable deferred token from an explicit flow, execution ID,\n * and deferred name.\n *\n * @category token\n * @since 0.1.0\n */\nexport const tokenFromExecutionId: {\n (options: {\n readonly flow: Flow.Any\n readonly executionId: string\n }): <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ) => Token\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: { readonly flow: Flow.Any; readonly executionId: string }\n ): Token\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly flow: Flow.Any\n readonly executionId: string\n }\n ): Token =>\n new TokenParsed({\n flowName: options.flow._tag,\n executionId: options.executionId,\n deferredName: self.name\n }).asToken\n)\n\n/**\n * Creates a durable deferred token by deriving the flow execution ID from\n * the supplied flow payload.\n *\n * The payload identifies a previously started execution only when the flow\n * declares `idempotencyKey` or the host installs the opt-in `derived`\n * execution-id source. Otherwise the default `fresh` source mints a new\n * execution ID on every call, so the token addresses no earlier run. To\n * complete an existing execution without stable identity, keep its execution\n * ID and use {@link tokenFromExecutionId}.\n *\n * @category token\n * @since 0.1.0\n */\nexport const tokenFromPayload: {\n <W extends Flow.Any>(options: {\n readonly flow: W\n readonly payload: Flow.PayloadSchema<W>[\"~type.make.in\"]\n }): <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<Token, never, Crypto.Crypto | Flow.PayloadSchema<W>[\"EncodingServices\"]>\n <\n Success extends Schema.Constraint,\n Error extends Schema.Constraint,\n W extends Flow.Any\n >(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly flow: W\n readonly payload: Flow.PayloadSchema<W>[\"~type.make.in\"]\n }\n ): Effect.Effect<Token, never, Crypto.Crypto | Flow.PayloadSchema<W>[\"EncodingServices\"]>\n} = dual(\n 2,\n <\n Success extends Schema.Constraint,\n Error extends Schema.Constraint,\n W extends Flow.Any\n >(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly flow: W\n readonly payload: Flow.PayloadSchema<W>[\"~type.make.in\"]\n }\n ): Effect.Effect<Token, never, Crypto.Crypto | Flow.PayloadSchema<W>[\"EncodingServices\"]> =>\n Effect.map(options.flow.executionId(options.payload), (executionId) =>\n tokenFromExecutionId(self, {\n flow: options.flow,\n executionId\n }))\n)\n\n/**\n * Completes the durable deferred identified by a token with the supplied exit,\n * encoding the result through the deferred schemas.\n *\n * The token is not a credential (see {@link Token}): authorize the caller\n * before completing a wait on its behalf.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const done: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly exit: Exit.Exit<Success[\"Type\"], Error[\"Type\"]>\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<\n void,\n TokenInvalid,\n FlowRuntime | Success[\"EncodingServices\"] | Error[\"EncodingServices\"]\n >\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly exit: Exit.Exit<Success[\"Type\"], Error[\"Type\"]>\n }\n ): Effect.Effect<\n void,\n TokenInvalid,\n FlowRuntime | Success[\"EncodingServices\"] | Error[\"EncodingServices\"]\n >\n} = dual(\n 2,\n // Untraced because awaiting a deferred re-enters the scheduler recursively.\n Effect.fnUntraced(function*<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n >(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly exit: Exit.Exit<Success[\"Type\"], Error[\"Type\"]>\n }\n ) {\n const token = yield* TokenParsed.parse(options.token)\n if (token.deferredName !== self.name) {\n return yield* Effect.fail(\n new TokenInvalid({\n code: \"deferred_mismatch\",\n message: `The token addresses deferred \"${tokenExcerpt(token.deferredName)}\", but it was submitted through ` +\n `deferred \"${self.name}\".`\n })\n )\n }\n const engine = yield* FlowRuntime\n yield* engine.deferredDone(self, {\n flowName: token.flowName,\n executionId: token.executionId,\n deferredName: token.deferredName,\n exit: options.exit\n })\n })\n)\n\n/**\n * Completes the durable deferred identified by a token with a successful\n * value.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const succeed: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly value: Success[\"Type\"]\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<void, TokenInvalid, FlowRuntime | Success[\"EncodingServices\"]>\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly value: Success[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Success[\"EncodingServices\"]>\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly value: Success[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Success[\"EncodingServices\"]> =>\n done(self, {\n token: options.token,\n exit: Exit.succeed(options.value)\n })\n)\n\n/**\n * Completes the durable deferred identified by a token with a typed failure.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const fail: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly error: Error[\"Type\"]\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly error: Error[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly error: Error[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]> =>\n done(self, {\n token: options.token,\n exit: Exit.fail(options.error)\n })\n)\n\n/**\n * Completes the durable deferred identified by a token with a failure cause.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const failCause: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly cause: Cause.Cause<Error[\"Type\"]>\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly cause: Cause.Cause<Error[\"Type\"]>\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly cause: Cause.Cause<Error[\"Type\"]>\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]> =>\n done(self, {\n token: options.token,\n exit: Exit.failCause(options.cause)\n })\n)\n"]}
1
+ {"version":3,"file":"DurableDeferred.js","sourceRoot":"","sources":["../../src/DurableDeferred.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAGnC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AAEzC,OAAO,KAAK,MAAM,MAAM,eAAe,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MAAM,CAAC,MAAM,SAAS,GAclB,IAAI,CACN,CAAC,EACD,CACE,IAAqC,EACrC,OAGC,EAC2E,EAAE,CAC9E,IAAI,CAAC,IAAI,EAAE;IACT,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,KAAK,CAAC;CACpC,CAAC,CACL,CAAA","sourcesContent":["// Deep reviewed and polished by a human on 2026-08-10.\n\n/**\n * Defines named wait points for durable flow executions.\n *\n * A `DurableDeferred` has a stable name and schemas for the value that will be\n * recorded later. Flows can await it, suspend when no result exists yet, and\n * resume after its result is recorded. Tokens identify the flow name,\n * execution id, and deferred name so external code can complete the correct\n * wait point later.\n *\n * @since 0.1.0\n */\n\nimport * as Arr from \"effect/Array\"\nimport type { NonEmptyReadonlyArray } from \"effect/Array\"\nimport type * as Brand from \"effect/Brand\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Base64Url from \"effect/encoding/Base64Url\"\nimport * as Exit from \"effect/Exit\"\nimport * as Filter from \"effect/Filter\"\nimport { dual } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaGetter from \"effect/SchemaGetter\"\nimport { CurrentAttempt } from \"./Action/Context.ts\"\nimport * as Flow from \"./Flow/index.ts\"\nimport { FlowInstance } from \"./FlowRuntime/FlowInstance.ts\"\nimport { FlowRuntime } from \"./FlowRuntime/FlowRuntime.ts\"\n\nconst TypeId = \"@smthrs/flow/DurableDeferred\"\n\n/**\n * Named durable deferred value whose completion is persisted by the flow\n * engine and encoded with success and error schemas.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DurableDeferred<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint = Schema.Never\n> {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n readonly successSchema: Success\n readonly errorSchema: Error\n readonly exitSchema: Schema.Exit<Schema.Top, Schema.Top, Schema.Top>\n readonly withActionAttempt: Effect.Effect<DurableDeferred<Success, Error>>\n}\n\n/**\n * Type-erased durable deferred shape for APIs that only need the deferred\n * identity and name.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Any {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n}\n\n/**\n * Type-erased durable deferred shape that also exposes success, error, and\n * exit schemas.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AnyWithProps {\n readonly [TypeId]: typeof TypeId\n readonly name: string\n readonly successSchema: Schema.Top\n readonly errorSchema: Schema.Top\n readonly exitSchema: Schema.Exit<any, any, any>\n}\n\n// Queues, human tasks and clocks mint a deferred per item, attempt or sleep.\n// Effect caches compiled parsers by AST identity, so the exit schema is shared\n// per (success, error) pair rather than rebuilt for every deferred.\nconst exitSchemaCache = new WeakMap<object, WeakMap<object, Schema.Exit<any, any, any>>>()\n\nconst exitSchemaFor = (success: Schema.Constraint, error: Schema.Constraint): Schema.Exit<any, any, any> => {\n let byError = exitSchemaCache.get(success)\n if (byError === undefined) {\n byError = new WeakMap()\n exitSchemaCache.set(success, byError)\n }\n let cached = byError.get(error)\n if (cached === undefined) {\n cached = Schema.Exit(\n Schema.toCodecJson(success),\n Schema.toCodecJson(error),\n Schema.toCodecJson(Schema.Defect())\n )\n byError.set(error, cached)\n }\n return cached\n}\n\n/**\n * Creates a named durable deferred with optional success and error schemas for\n * persisted completion.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <\n Success extends Schema.Constraint = Schema.Void,\n Error extends Schema.Constraint = Schema.Never\n>(\n name: string,\n options?: {\n readonly success?: Success | undefined\n readonly error?: Error | undefined\n }\n): DurableDeferred<Success, Error> => {\n const successSchema = options?.success ?? (Schema.Void as any as Success)\n const errorSchema = options?.error ?? (Schema.Never as any as Error)\n return {\n [TypeId]: TypeId as typeof TypeId,\n name,\n successSchema,\n errorSchema,\n exitSchema: exitSchemaFor(successSchema, errorSchema) as any,\n withActionAttempt: Effect.gen(function*() {\n const attempt = yield* CurrentAttempt\n return make(`${name}/${attempt}`, {\n success: successSchema,\n error: errorSchema\n })\n })\n }\n}\n\nconst await_: <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n) => Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Error[\"DecodingServices\"]\n> =\n // Untraced because deferred polling participates in the flow scheduler hot path.\n Effect.fnUntraced(function*<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n >(self: DurableDeferred<Success, Error>) {\n const engine = yield* FlowRuntime\n const instance = yield* FlowInstance\n const exit = yield* Flow.wrapActionResult(\n engine.deferredResult(self),\n Option.isNone\n )\n if (Option.isNone(exit)) {\n return yield* Flow.suspend(instance)\n }\n const value = exit.value as Exit.Exit<any, any>\n // A recorded interruption is a durable *outcome*, not a request to\n // suspend: mark the instance interrupted before re-raising so\n // `Flow.intoResult` classifies the interrupt-only cause as a `Complete`\n // failure. Without this the driver mistakes the cause for an external\n // suspension interrupt, aborts without a terminal transition, and the\n // run spins in the suspended-retry loop forever.\n if (Exit.isFailure(value) && Cause.hasInterruptsOnly(value.cause)) {\n instance.interrupted = true\n }\n return yield* value\n })\n\nexport {\n /**\n * Waits for the durable deferred, suspending the current flow when no\n * persisted completion is available.\n *\n * @category combinators\n * @since 0.1.0\n */\n await_ as await\n}\n\n/**\n * Runs an effect and records its exit into the durable deferred, resuming\n * flows that are waiting on that deferred.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const into: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ): <R>(\n effect: Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>\n ) => Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | R\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n >\n <Success extends Schema.Constraint, Error extends Schema.Constraint, R>(\n effect: Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n self: DurableDeferred<Success, Error>\n ): Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | R\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n >\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint, R>(\n effect: Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n self: DurableDeferred<Success, Error>\n ): Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | R\n | FlowRuntime\n | FlowInstance\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n > =>\n Effect.contextWith(\n (context: Context.Context<FlowRuntime | FlowInstance>) => {\n const engine = Context.get(context, FlowRuntime)\n const instance = Context.get(context, FlowInstance)\n // Keep the original instance: action regions identify their ancestors\n // by reference, and suspension metadata belongs to the enclosing flow.\n return Effect.onExit(\n effect,\n // Untraced because completion encoding is called for each deferred result.\n Effect.fnUntraced(function*(exit) {\n if (Exit.isFailure(exit)) {\n const [interrupts, reasons] = Arr.partition(\n exit.cause.reasons,\n Filter.fromPredicate(Cause.isInterruptReason)\n )\n const hasInterruptsOnly = interrupts.length === exit.cause.reasons.length\n if (hasInterruptsOnly) {\n // An interrupt-only exit is never a result: the effect was\n // suspended, preempted, or interrupted, so record nothing.\n // Recording here would durably persist the empty non-interrupt\n // partition, and first-writer-wins would replay that empty\n // cause forever instead of the real completion.\n return\n } else if (interrupts.length > 0) {\n exit = Exit.failCause(Cause.fromReasons(reasons))\n }\n }\n yield* engine.deferredDone(self, {\n flowName: instance.flow._tag,\n executionId: instance.executionId,\n deferredName: self.name,\n exit\n })\n })\n )\n }\n )\n)\n\n/**\n * Runs effects as a durable race, returning a previously persisted result when\n * present or completing a named deferred with the first success. The race\n * fails only when every effect fails.\n *\n * @category racing\n * @since 0.1.0\n */\nexport const raceAll = <\n const Effects extends NonEmptyReadonlyArray<Effect.Effect<any, any, any>>,\n Success extends Schema.Schema<Effect.Success<Effects[number]>>,\n Error extends Schema.Schema<Effect.Error<Effects[number]>>\n>(options: {\n name: string\n success: Success\n error: Error\n effects: Effects\n}): Effect.Effect<\n Effect.Success<Effects[number]>,\n Effect.Error<Effects[number]>,\n | Effect.Services<Effects[number]>\n | Success[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"DecodingServices\"]\n | Error[\"EncodingServices\"]\n | FlowRuntime\n | FlowInstance\n> => {\n const deferred = make<any, any>(`raceAll/${options.name}`, {\n success: options.success,\n error: options.error\n })\n return Effect.gen(function*() {\n const engine = yield* FlowRuntime\n const exit = yield* engine.deferredResult(deferred)\n if (Option.isSome(exit)) {\n return yield* exit.value\n }\n return yield* into(\n Effect.raceAll(options.effects),\n deferred\n )\n })\n}\n\n/**\n * Runtime brand identifier for durable deferred tokens.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport const TokenTypeId = \"@smthrs/flow/DurableDeferred/Token\"\n\n/**\n * Type-level brand identifier for `Token` values.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport type TokenTypeId = typeof TokenTypeId\n\n/**\n * Branded string token identifying a durable deferred for a flow\n * execution.\n *\n * A token is an address, not a credential. It is unsigned base64url JSON of\n * the flow name, execution id, and deferred name, and `tokenFromExecutionId`\n * and `tokenFromPayload` rebuild it from those values alone. Anyone who can\n * call `done`, `succeed`, `fail`, `failCause`, or `HumanTask.answer` against\n * the run's `FlowRuntime` can complete an open wait whose address they know or\n * derive. A host that exposes completion to other parties must authorize the\n * caller before it calls one of them.\n *\n * @category token\n * @since 0.1.0\n */\nexport type Token = Brand.Branded<string, TokenTypeId>\n\n/**\n * Schema for branded durable deferred tokens.\n *\n * @category token\n * @since 0.1.0\n */\nexport const Token: Schema.brand<Schema.String, TokenTypeId> = Schema.String.pipe(Schema.brand(TokenTypeId))\n\n/**\n * A completion token could not be decoded into its durable address.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class TokenInvalid extends Schema.TaggedError<TokenInvalid>()(\"@smthrs/flow/DurableDeferred/TokenInvalid\", {\n code: Schema.Literals([\"malformed_token\", \"deferred_mismatch\"]).pipe(\n Schema.withConstructorDefault(Effect.succeed(\"malformed_token\"))\n ),\n message: Schema.String\n}) {}\n\n/**\n * Schema for a decoded durable deferred token containing the flow\n * name, execution ID, and deferred name.\n *\n * @category token\n * @since 0.1.0\n */\nexport class TokenParsed extends Schema.Class<TokenParsed>(\n \"@smthrs/flow/DurableDeferred/TokenParsed\"\n)({\n flowName: Schema.String,\n executionId: Schema.String,\n deferredName: Schema.String\n}) {\n /**\n * Encodes the parsed flow, execution, and deferred names back into a token.\n *\n * @since 0.1.0\n */\n get asToken(): Token {\n return Base64Url.encode(\n JSON.stringify([this.flowName, this.executionId, this.deferredName])\n ) as Token\n }\n\n /**\n * Schema for decoding and encoding durable deferred tokens as strings.\n *\n * @since 0.1.0\n */\n static readonly FromString = Schema.String.pipe(\n Schema.decodeTo(\n Schema.fromJsonString(\n Schema.Tuple([Schema.String, Schema.String, Schema.String])\n ),\n {\n decode: SchemaGetter.decodeBase64UrlString(),\n encode: SchemaGetter.encodeBase64Url()\n }\n ),\n Schema.decodeTo(TokenParsed, {\n decode: SchemaGetter.transform(\n ([flowName, executionId, deferredName]) =>\n new TokenParsed({\n flowName,\n executionId,\n deferredName\n })\n ),\n encode: SchemaGetter.transform(\n (parsed) =>\n [\n parsed.flowName,\n parsed.executionId,\n parsed.deferredName\n ] as const\n )\n })\n )\n\n /**\n * Decodes a durable deferred token string into its parsed components.\n *\n * @since 0.1.0\n */\n static readonly fromString = Schema.decodeSync(TokenParsed.FromString)\n\n /**\n * Encodes parsed durable deferred token components into a token string.\n *\n * @since 0.1.0\n */\n static readonly encode = Schema.encodeSync(TokenParsed.FromString)\n\n /**\n * Parses an untrusted token into its durable address with a typed,\n * bounded diagnostic on failure.\n *\n * @category token\n * @since 1.0.0\n */\n static readonly parse = (token: string): Effect.Effect<TokenParsed, TokenInvalid> =>\n Effect.mapError(\n Schema.decodeEffect(TokenParsed.FromString)(token),\n (issue) =>\n new TokenInvalid({\n message: `The supplied token \"${tokenExcerpt(token)}\" is not a durable deferred token: ${issue.message}`\n })\n )\n}\n\nconst maxTokenExcerptChars = 64\n\n/** Renders a bounded excerpt of untrusted token content for a diagnostic. */\nconst tokenExcerpt = (token: string): string =>\n token.length <= maxTokenExcerptChars\n ? token\n : `${token.slice(0, maxTokenExcerptChars)} [${token.length - maxTokenExcerptChars} characters dropped]`\n\n/**\n * Creates a token for a durable deferred using the current flow instance's\n * flow name and execution ID.\n *\n * @category token\n * @since 0.1.0\n */\nexport const token: <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n) => Effect.Effect<Token, never, FlowInstance> =\n // Untraced because token allocation is on the durable-deferred hot path.\n Effect.fnUntraced(\n function*<Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ) {\n const instance = yield* FlowInstance\n return tokenFromExecutionId(self, instance)\n }\n )\n\n/**\n * Creates a durable deferred token from an explicit flow, execution ID,\n * and deferred name.\n *\n * @category token\n * @since 0.1.0\n */\nexport const tokenFromExecutionId: {\n (options: {\n readonly flow: Flow.Any\n readonly executionId: string\n }): <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ) => Token\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: { readonly flow: Flow.Any; readonly executionId: string }\n ): Token\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly flow: Flow.Any\n readonly executionId: string\n }\n ): Token =>\n new TokenParsed({\n flowName: options.flow._tag,\n executionId: options.executionId,\n deferredName: self.name\n }).asToken\n)\n\n/**\n * Creates a durable deferred token by deriving the flow execution ID from\n * the supplied flow payload.\n *\n * The payload identifies a previously started execution only when the flow\n * declares `idempotencyKey` or the host installs the opt-in `derived`\n * execution-id source. Otherwise the default `fresh` source mints a new\n * execution ID on every call, so the token addresses no earlier run. To\n * complete an existing execution without stable identity, keep its execution\n * ID and use {@link tokenFromExecutionId}.\n *\n * @category token\n * @since 0.1.0\n */\nexport const tokenFromPayload: {\n <W extends Flow.Any>(options: {\n readonly flow: W\n readonly payload: Flow.PayloadSchema<W>[\"~type.make.in\"]\n }): <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<Token, never, Crypto.Crypto | Flow.PayloadSchema<W>[\"EncodingServices\"]>\n <\n Success extends Schema.Constraint,\n Error extends Schema.Constraint,\n W extends Flow.Any\n >(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly flow: W\n readonly payload: Flow.PayloadSchema<W>[\"~type.make.in\"]\n }\n ): Effect.Effect<Token, never, Crypto.Crypto | Flow.PayloadSchema<W>[\"EncodingServices\"]>\n} = dual(\n 2,\n <\n Success extends Schema.Constraint,\n Error extends Schema.Constraint,\n W extends Flow.Any\n >(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly flow: W\n readonly payload: Flow.PayloadSchema<W>[\"~type.make.in\"]\n }\n ): Effect.Effect<Token, never, Crypto.Crypto | Flow.PayloadSchema<W>[\"EncodingServices\"]> =>\n Effect.map(options.flow.executionId(options.payload), (executionId) =>\n tokenFromExecutionId(self, {\n flow: options.flow,\n executionId\n }))\n)\n\n/**\n * Completes the durable deferred identified by a token with the supplied exit,\n * encoding the result through the deferred schemas.\n *\n * The token is not a credential (see {@link Token}): authorize the caller\n * before completing a wait on its behalf.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const done: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly exit: Exit.Exit<Success[\"Type\"], Error[\"Type\"]>\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<\n void,\n TokenInvalid,\n FlowRuntime | Success[\"EncodingServices\"] | Error[\"EncodingServices\"]\n >\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly exit: Exit.Exit<Success[\"Type\"], Error[\"Type\"]>\n }\n ): Effect.Effect<\n void,\n TokenInvalid,\n FlowRuntime | Success[\"EncodingServices\"] | Error[\"EncodingServices\"]\n >\n} = dual(\n 2,\n // Untraced because awaiting a deferred re-enters the scheduler recursively.\n Effect.fnUntraced(function*<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n >(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly exit: Exit.Exit<Success[\"Type\"], Error[\"Type\"]>\n }\n ) {\n const token = yield* TokenParsed.parse(options.token)\n if (token.deferredName !== self.name) {\n return yield* Effect.fail(\n new TokenInvalid({\n code: \"deferred_mismatch\",\n message: `The token addresses deferred \"${tokenExcerpt(token.deferredName)}\", but it was submitted through ` +\n `deferred \"${self.name}\".`\n })\n )\n }\n const engine = yield* FlowRuntime\n yield* engine.deferredDone(self, {\n flowName: token.flowName,\n executionId: token.executionId,\n deferredName: token.deferredName,\n exit: options.exit\n })\n })\n)\n\n/**\n * Completes the durable deferred identified by a token with a successful\n * value.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const succeed: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly value: Success[\"Type\"]\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<void, TokenInvalid, FlowRuntime | Success[\"EncodingServices\"]>\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly value: Success[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Success[\"EncodingServices\"]>\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly value: Success[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Success[\"EncodingServices\"]> =>\n done(self, {\n token: options.token,\n exit: Exit.succeed(options.value)\n })\n)\n\n/**\n * Completes the durable deferred identified by a token with a typed failure.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const fail: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly error: Error[\"Type\"]\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly error: Error[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly error: Error[\"Type\"]\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]> =>\n done(self, {\n token: options.token,\n exit: Exit.fail(options.error)\n })\n)\n\n/**\n * Completes the durable deferred identified by a token with a failure cause.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const failCause: {\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly token: Token\n readonly cause: Cause.Cause<Error[\"Type\"]>\n }): (\n self: DurableDeferred<Success, Error>\n ) => Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly cause: Cause.Cause<Error[\"Type\"]>\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]>\n} = dual(\n 2,\n <Success extends Schema.Constraint, Error extends Schema.Constraint>(\n self: DurableDeferred<Success, Error>,\n options: {\n readonly token: Token\n readonly cause: Cause.Cause<Error[\"Type\"]>\n }\n ): Effect.Effect<void, TokenInvalid, FlowRuntime | Error[\"EncodingServices\"]> =>\n done(self, {\n token: options.token,\n exit: Exit.failCause(options.cause)\n })\n)\n"]}
@@ -1,9 +1,9 @@
1
1
  import type * as Crypto from "effect/Crypto";
2
2
  import * as Effect from "effect/Effect";
3
3
  import * as Layer from "effect/Layer";
4
+ import * as PersistedQueue from "effect/persistence/PersistedQueue";
4
5
  import * as Schedule from "effect/Schedule";
5
6
  import * as Schema from "effect/Schema";
6
- import * as PersistedQueue from "effect/unstable/persistence/PersistedQueue";
7
7
  import * as DurableDeferred from "./DurableDeferred.ts";
8
8
  import { type FlowInstance, type FlowRuntime } from "./FlowRuntime/index.ts";
9
9
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"DurableQueue.d.ts","sourceRoot":"","sources":["../../src/DurableQueue.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,KAAK,MAAM,MAAM,eAAe,CAAA;AAC5C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAGvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAEvC,OAAO,KAAK,cAAc,MAAM,4CAA4C,CAAA;AAE5E,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAmB,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,wBAAwB,CAAA;AAE7F;;;;;GAKG;AACH,MAAM,MAAM,MAAM,GAAG,2BAA2B,CAAA;AAEhD;;;;;GAKG;AACH,eAAO,MAAM,MAAM,EAAE,MAAoC,CAAA;AAEzD;;;;;;GAMG;AACH,MAAM,WAAW,YAAY,CAC3B,OAAO,SAAS,MAAM,CAAC,GA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E,YAAY,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAC3C,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EACjF,OAAO,CAAC,EAAE;IACR,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;IACzC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAC1C,GAAG,SAAS,KACV,KAAK,CAAC,KAAK,CACd,KAAK,EACL,KAAK,EACH,WAAW,GACX,cAAc,CAAC,qBAAqB,GACpC,CAAC,GACD,OAAO,CAAC,kBAAkB,CAAC,GAC3B,OAAO,CAAC,kBAAkB,CAAC,GAC3B,OAAO,CAAC,kBAAkB,CAAC,GAC3B,KAAK,CAAC,kBAAkB,CAAC,CACiE,CAAA"}
@@ -17,10 +17,10 @@ import * as Effect from "effect/Effect";
17
17
  import * as Exit from "effect/Exit";
18
18
  import * as Filter from "effect/Filter";
19
19
  import * as Layer from "effect/Layer";
20
+ import * as PersistedQueue from "effect/persistence/PersistedQueue";
20
21
  import * as Schedule from "effect/Schedule";
21
22
  import * as Schema from "effect/Schema";
22
23
  import * as Tracer from "effect/Tracer";
23
- import * as PersistedQueue from "effect/unstable/persistence/PersistedQueue";
24
24
  import * as Action from "./Action/index.js";
25
25
  import * as DurableDeferred from "./DurableDeferred.js";
26
26
  import { annotateWaiting } from "./FlowRuntime/index.js";
@@ -233,7 +233,7 @@ const makeWorkerEffect = Effect.fnUntraced(function* (self, f, concurrency, maxA
233
233
  });
234
234
  let exit = yield* Effect.exit(f(item.payload));
235
235
  if (Exit.isFailure(exit)) {
236
- const [reasons, interrupts] = Arr.partition(exit.cause.reasons, Filter.fromPredicate(Cause.isInterruptReason));
236
+ const [interrupts, reasons] = Arr.partition(exit.cause.reasons, Filter.fromPredicate(Cause.isInterruptReason));
237
237
  // Match DurableDeferred.into: interruption alone is not a durable
238
238
  // outcome, and must leave the item available without an attempt.
239
239
  if (interrupts.length === exit.cause.reasons.length) {
@@ -1 +1 @@
1
- {"version":3,"file":"DurableQueue.js","sourceRoot":"","sources":["../../src/DurableQueue.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,IAAI,MAAM,aAAa,CAAA;AACnC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,cAAc,MAAM,4CAA4C,CAAA;AAC5E,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAA;AAC3C,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAE,eAAe,EAAuC,MAAM,wBAAwB,CAAA;AAU7F;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAAW,2BAA2B,CAAA;AAqBzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAIlB,OASD,EAIC,EAAE,CAAC,CAAC;IACJ,CAAC,MAAM,CAAC,EAAE,MAAM;IAChB,IAAI,EAAE,OAAO,CAAC,IAAI;IAClB,aAAa,EAAE,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,OAAO,CAAC;QAC7C,CAAC,CAAC,OAAO,CAAC,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OAAO,EACd,MAAM,CAAC,YAAY,CAAC;QAClB,OAAO,EAAE,cAAc;QACvB,MAAM,EAAE,cAAc;QACtB,KAAK,EAAE,QAAQ;QACf,SAAS,EAAE,IAAI,CAAC,IAAI;KACrB,CAAC,CACH,CAAA;IAED,OAAO,KAAK,CAAC,CAAC,MAAM,CAAC,eAAe,CAAC,MAAM,EAAE,WAAW,EAAE,EAAE,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAC5F,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAC7B,CAAA;AACH,CAAC,CAAC,CAAA;AAEF;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,UAAU,GAsBnB,CAMF,IAA2C,EAC3C,CAAiF,EACjF,OAGC,EACD,EAAE;IACF,MAAM,WAAW,GAAG,OAAO,EAAE,WAAW,IAAI,CAAC,CAAA;IAC7C,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,IAAI,WAAW,GAAG,CAAC,EAAE,CAAC;QAC1D,MAAM,IAAI,UAAU,CAClB,iFAAiF,WAAW,GAAG,CAChG,CAAA;IACH,CAAC;IACD,OAAO,gBAAgB,CAAC,IAAI,EAAE,CAAC,EAAE,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,EAAE,CAAC,CAAA;AAC3E,CAAC,CAAA;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAsBf,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAA","sourcesContent":["// Deep reviewed and polished by a human on 2026-08-10.\n\n/**\n * Durable flow queues delegate work to persisted background workers and\n * resume the waiting flow with the worker result.\n *\n * A flow calls `process` to encode a payload, offer it to a named\n * `PersistedQueue`, attach a `DurableDeferred` token, and suspend. A worker\n * created with `makeWorker` or `worker` takes the item, runs the handler, and\n * records the handler's `Exit` through that token so the original flow can\n * continue with the typed success or error.\n *\n * @since 0.1.0\n */\n\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Filter from \"effect/Filter\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport * as Tracer from \"effect/Tracer\"\nimport * as PersistedQueue from \"effect/unstable/persistence/PersistedQueue\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableDeferred from \"./DurableDeferred.ts\"\nimport { annotateWaiting, type FlowInstance, type FlowRuntime } from \"./FlowRuntime/index.ts\"\n\n/**\n * Type-level identifier used to recognize `DurableQueue` values.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport type TypeId = \"@smthrs/flow/DurableQueue\"\n\n/**\n * Runtime identifier attached to `DurableQueue` values.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport const TypeId: TypeId = \"@smthrs/flow/DurableQueue\"\n\n/**\n * Durable flow queue definition containing a payload schema, idempotency\n * key, and deferred used to await worker results.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DurableQueue<\n Payload extends Schema.Top,\n Success extends Schema.Top = Schema.Void,\n Error extends Schema.Top = Schema.Never\n> {\n readonly [TypeId]: TypeId\n readonly name: string\n readonly payloadSchema: Payload\n readonly idempotencyKey: (payload: Payload[\"Type\"]) => string\n readonly deferred: DurableDeferred.DurableDeferred<Success, Error>\n}\n\n/**\n * Creates a `DurableQueue` that waits for persisted items to finish processing\n * using a `DurableDeferred`.\n *\n * **Example** (Defining a durable queue with workers)\n *\n * ```ts\n * import { Action, DurableQueue, Flow, Interpreter } from \"@smthrs/flow\"\n * import { Effect, Layer, Schema } from \"effect\"\n *\n * // Define a DurableQueue that can be used to derive workers and offer items for\n * // processing.\n * const ApiQueue = DurableQueue.make({\n * name: \"ApiQueue\",\n * payload: {\n * id: Schema.String\n * },\n * success: Schema.Void,\n * error: Schema.Never,\n * idempotencyKey(payload) {\n * return payload.id\n * }\n * })\n *\n * // Offering an item is work, so it is a declared Action: the declaration is\n * // pure data, and the implementation attaches separately.\n * const Offer = Action.make(\"MyFlow/offer\", {\n * payload: {\n * id: Schema.String\n * }\n * })\n *\n * const OfferLive = Offer.toLayer(\n * Effect.fnUntraced(function*({ id }) {\n * // Add an item to the DurableQueue defined above.\n * //\n * // When the worker has finished processing the item, the flow will\n * // resume.\n * //\n * yield* DurableQueue.process(ApiQueue, { id })\n *\n * yield* Effect.log(\"Flow succeeded!\")\n * })\n * )\n *\n * // The flow is the composite, and its body names the step it is made of.\n * const MyFlow = Flow.make(\"MyFlow\", {\n * payload: {\n * id: Schema.String\n * },\n * idempotencyKey: ({ id }) => id,\n * body: (payload) => Offer.call(payload)\n * })\n *\n * const MyFlowLayer = Layer.mergeAll(OfferLive, Interpreter.layer(MyFlow)).pipe(\n * Layer.provideMerge(Action.layerImplementations)\n * )\n *\n * // Define a worker layer that can process items from the DurableQueue.\n * const ApiWorker = DurableQueue.worker(\n * ApiQueue,\n * Effect.fnUntraced(function*({ id }) {\n * yield* Effect.log(`Worker processing API call with id: ${id}`)\n * }),\n * { concurrency: 5 } // Process up to 5 items concurrently\n * )\n * ```\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <\n Payload extends Schema.Top | Schema.Struct.Fields,\n Success extends Schema.Top = Schema.Void,\n Error extends Schema.Top = Schema.Never\n>(options: {\n readonly name: string\n readonly payload: Payload\n readonly idempotencyKey: (\n payload: Payload extends Schema.Struct.Fields ? Schema.Struct.Type<Payload>\n : Payload[\"Type\"]\n ) => string\n readonly success?: Success | undefined\n readonly error?: Error | undefined\n}): DurableQueue<\n Payload extends Schema.Struct.Fields ? Schema.Struct<Payload> : Payload,\n Success,\n Error\n> => ({\n [TypeId]: TypeId,\n name: options.name,\n payloadSchema: Schema.isSchema(options.payload)\n ? options.payload\n : Schema.Struct(options.payload as any) as any,\n idempotencyKey: options.idempotencyKey as any,\n deferred: DurableDeferred.make(`DurableQueue/${options.name}`, {\n success: options.success,\n error: options.error\n })\n})\n\nconst queueSchemas = new WeakMap<Schema.Top, Schema.Top>()\n\nconst getQueueSchema = <Payload extends Schema.Top>(\n payload: Payload\n): Schema.Struct<{\n token: typeof DurableDeferred.Token\n payload: Payload\n traceId: typeof Schema.String\n spanId: typeof Schema.String\n sampled: typeof Schema.Boolean\n}> => {\n let schema = queueSchemas.get(payload)\n if (!schema) {\n schema = Schema.Struct({\n token: DurableDeferred.Token,\n traceId: Schema.String,\n spanId: Schema.String,\n sampled: Schema.Boolean,\n payload\n })\n queueSchemas.set(payload, schema)\n }\n return schema as any\n}\n\n/**\n * Adds an item to the queue and waits for a worker to process it.\n *\n * `retrySchedule` controls retries when the persisted offer fails. The default\n * is unbounded, with exponential delays capped at one minute, so a transient\n * store outage does not lose the item. A caller-supplied schedule may exhaust;\n * its final offer failure becomes a defect to keep the public error channel\n * reserved for the worker's declared error.\n *\n * Payload construction also becomes a defect when `fields` does not satisfy\n * the queue's payload schema. The public error channel is the worker result,\n * not malformed caller input.\n *\n * @category processing\n * @since 0.1.0\n */\nexport const process: <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top\n>(\n self: DurableQueue<Payload, Success, Error>,\n payload: Payload[\"~type.make.in\"],\n options?: {\n readonly retrySchedule?: Schedule.Schedule<any, PersistedQueue.PersistedQueueError> | undefined\n }\n) => Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | FlowRuntime\n | FlowInstance\n | Crypto.Crypto\n | PersistedQueue.PersistedQueueFactory\n | Payload[\"EncodingServices\"]\n | Payload[\"DecodingServices\"]\n | Success[\"DecodingServices\"]\n | Error[\"DecodingServices\"]\n> =\n // Untraced because queue offer is a worker hot path.\n Effect.fnUntraced(function*<\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top\n >(self: DurableQueue<Payload, Success, Error>, fields: Payload[\"~type.make.in\"], options?: {\n readonly retrySchedule?: Schedule.Schedule<any, PersistedQueue.PersistedQueueError> | undefined\n }) {\n const payload = yield* self.payloadSchema.makeEffect(fields).pipe(\n Effect.mapError((issue) => new Schema.SchemaError(issue)),\n Effect.orDie\n )\n const queueName = `DurableQueue/${self.name}`\n const queue = yield* PersistedQueue.make({\n name: queueName,\n schema: getQueueSchema(self.payloadSchema)\n })\n const key = yield* Action.idempotencyKey(queueName, {\n parentScope: self.idempotencyKey(payload)\n })\n\n const deferred = DurableDeferred.make(`${self.deferred.name}/${key}`, {\n success: self.deferred.successSchema,\n error: self.deferred.errorSchema\n })\n const token = yield* DurableDeferred.token(deferred)\n\n yield* Effect.useSpan(`DurableQueue/${self.name}/process`, {\n attributes: { key }\n }, (span) =>\n queue.offer({\n token,\n payload,\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled\n } as any, { id: key }).pipe(\n Effect.tapCause(Effect.logWarning),\n Effect.catchTag(\"SchemaError\", Effect.die),\n Effect.retry(options?.retrySchedule ?? defaultRetrySchedule),\n Effect.orDie,\n Effect.annotateLogs({\n package: \"@smthrs/flow\",\n module: \"DurableQueue\",\n fiber: \"process\",\n queueName: self.name\n })\n ))\n\n yield* annotateWaiting({ reason: \"event\", token })\n return yield* DurableDeferred.await(deferred)\n })\n\nconst maxDeferredNameExcerptChars = 128\n\n/** Renders a bounded excerpt of a stored deferred name for a diagnostic. */\nconst deferredNameExcerpt = (name: string): string =>\n name.length <= maxDeferredNameExcerptChars\n ? name\n : `${name.slice(0, maxDeferredNameExcerptChars)} [${name.length - maxDeferredNameExcerptChars} characters dropped]`\n\nconst traceIdPattern = /^[0-9a-f]{32}$/\nconst spanIdPattern = /^[0-9a-f]{16}$/\n\n/**\n * The offering span as the worker span's parent, when the stored ids have the\n * W3C trace-context shape every Effect and OpenTelemetry tracer writes. A\n * stored item is not trusted to splice arbitrary identifiers into a trace.\n */\nconst externalParent = (item: {\n readonly traceId: string\n readonly spanId: string\n readonly sampled: boolean\n}): Tracer.ExternalSpan | undefined =>\n traceIdPattern.test(item.traceId) && spanIdPattern.test(item.spanId)\n ? Tracer.externalSpan({ traceId: item.traceId, spanId: item.spanId, sampled: item.sampled })\n : undefined\n\nconst defaultRetrySchedule = Schedule.min([\n Schedule.exponential(500, 1.5),\n Schedule.spaced(\"1 minute\")\n])\n\nconst makeWorkerEffect = Effect.fnUntraced(function*<\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n concurrency: number,\n maxAttempts: number\n) {\n const queue = yield* PersistedQueue.make({\n name: `DurableQueue/${self.name}`,\n schema: getQueueSchema(self.payloadSchema),\n maxAttempts,\n // The worker owns the 500 ms retry pause below. Keep an upstream queue\n // default from introducing an additional backoff after an Effect upgrade.\n retrySchedule: Schedule.spaced(0)\n })\n\n const worker = Effect.suspend(() => {\n let completion:\n | { readonly token: DurableDeferred.Token; readonly id: string; readonly attempts: number }\n | undefined\n return queue.take((item_, metadata) => {\n const item = item_ as {\n readonly token: DurableDeferred.Token\n readonly payload: Payload[\"Type\"]\n readonly traceId: string\n readonly spanId: string\n readonly sampled: boolean\n }\n return Effect.withSpan(\n Effect.gen(function*() {\n // Parse before running the handler. A malformed completion address\n // cannot strand a handler result that was already produced.\n const parsed = yield* DurableDeferred.TokenParsed.parse(item.token)\n // `process` offers each item under its key and addresses the\n // deferred `<queue deferred>/<key>`. Anything else in this queue\n // names a wait point the queue does not own (another queue's item,\n // a WaitFor gate, a human task), so completing it here would settle\n // a foreign wait under this queue's success schema.\n const expected = `${self.deferred.name}/${metadata.id}`\n if (parsed.deferredName !== expected) {\n return yield* new DurableDeferred.TokenInvalid({\n code: \"deferred_mismatch\",\n message: `The item \"${metadata.id}\" addresses the deferred \"${\n deferredNameExcerpt(parsed.deferredName)\n }\", not \"${deferredNameExcerpt(expected)}\".`\n })\n }\n const deferred = DurableDeferred.make(parsed.deferredName, {\n success: self.deferred.successSchema,\n error: self.deferred.errorSchema\n })\n let exit = yield* Effect.exit(f(item.payload))\n if (Exit.isFailure(exit)) {\n const [reasons, interrupts] = Arr.partition(\n exit.cause.reasons,\n Filter.fromPredicate(Cause.isInterruptReason)\n )\n // Match DurableDeferred.into: interruption alone is not a durable\n // outcome, and must leave the item available without an attempt.\n if (interrupts.length === exit.cause.reasons.length) {\n return yield* Effect.failCause(Cause.fromReasons<never>(interrupts))\n } else if (interrupts.length > 0) {\n exit = Exit.failCause(Cause.fromReasons(reasons))\n }\n }\n completion = { token: item.token, ...metadata }\n yield* DurableDeferred.done(deferred, {\n token: item.token,\n exit\n })\n }).pipe(\n Effect.catchTag(\"@smthrs/flow/DurableDeferred/TokenInvalid\", (error) =>\n Effect.logError(\n `DurableQueue \"${self.name}\" could not complete an item because its token was invalid. ${error.message}`\n ))\n ),\n `DurableQueue/${self.name}/worker`,\n {\n captureStackTrace: false,\n parent: externalParent(item)\n }\n )\n }).pipe(\n Effect.tapCause((cause) => {\n if (!completion) return Effect.void\n return Effect.logError(\"DurableQueue failed to persist or acknowledge a handler result\", cause).pipe(\n Effect.annotateLogs({\n token: completion.token,\n itemId: completion.id,\n attempt: completion.attempts,\n maxAttempts,\n exhausted: !Cause.hasInterrupts(cause) && completion.attempts >= maxAttempts\n })\n )\n })\n )\n }).pipe(\n // A persistently failing take would otherwise consume a core in a tight\n // loop while the queue store is unavailable.\n Effect.catchCause((cause) =>\n Effect.logWarning(cause).pipe(\n Effect.andThen(Effect.sleep(500))\n )\n ),\n Effect.forever,\n Effect.annotateLogs({\n package: \"@smthrs/flow\",\n module: \"DurableQueue\",\n fiber: \"worker\",\n queueName: self.name\n })\n )\n\n return yield* Effect.replicateEffect(worker, concurrency, { concurrency, discard: true }).pipe(\n Effect.andThen(Effect.never)\n )\n})\n\n/**\n * Create a worker effect that processes items from the durable queue.\n *\n * `concurrency` defaults to one and must be a positive safe integer. It is\n * checked before the persisted queue is opened. `maxAttempts` defaults to ten\n * and is passed to the persisted queue. Completion-write failures can rerun the\n * handler; side effects must be idempotent. Exhaustion leaves the flow waiting.\n *\n * @throws A `RangeError` when `concurrency` is not a positive safe integer.\n * @category worker\n * @since 0.1.0\n */\nexport const makeWorker: <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n options?: {\n readonly concurrency?: number | undefined\n readonly maxAttempts?: number | undefined\n } | undefined\n) => Effect.Effect<\n never,\n never,\n | FlowRuntime\n | PersistedQueue.PersistedQueueFactory\n | R\n | Payload[\"EncodingServices\"]\n | Payload[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"EncodingServices\"]\n> = <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n options?: {\n readonly concurrency?: number | undefined\n readonly maxAttempts?: number | undefined\n }\n) => {\n const concurrency = options?.concurrency ?? 1\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new RangeError(\n `DurableQueue.makeWorker: concurrency must be a positive safe integer, and was ${concurrency}.`\n )\n }\n return makeWorkerEffect(self, f, concurrency, options?.maxAttempts ?? 10)\n}\n\n/**\n * Create a layer that runs workers for the durable queue.\n *\n * @category worker\n * @since 0.1.0\n */\nexport const worker: <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n options?: {\n readonly concurrency?: number | undefined\n readonly maxAttempts?: number | undefined\n } | undefined\n) => Layer.Layer<\n never,\n never,\n | FlowRuntime\n | PersistedQueue.PersistedQueueFactory\n | R\n | Payload[\"EncodingServices\"]\n | Payload[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"EncodingServices\"]\n> = (self, f, options) => Layer.effectDiscard(Effect.forkScoped(makeWorker(self, f, options)))\n"]}
1
+ {"version":3,"file":"DurableQueue.js","sourceRoot":"","sources":["../../src/DurableQueue.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AAErC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,IAAI,MAAM,aAAa,CAAA;AACnC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,cAAc,MAAM,mCAAmC,CAAA;AACnE,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAA;AAC3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,mBAAmB,CAAA;AAC3C,OAAO,KAAK,eAAe,MAAM,sBAAsB,CAAA;AACvD,OAAO,EAAE,eAAe,EAAuC,MAAM,wBAAwB,CAAA;AAU7F;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAAW,2BAA2B,CAAA;AAqBzD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,MAAM,CAAC,MAAM,IAAI,GAAG,CAIlB,OASD,EAIC,EAAE,CAAC,CAAC;IACJ,CAAC,MAAM,CAAC,EAAE,MAAM;IAChB,IAAI,EAAE,OAAO,C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Durable flow queues delegate work to persisted background workers and\n * resume the waiting flow with the worker result.\n *\n * A flow calls `process` to encode a payload, offer it to a named\n * `PersistedQueue`, attach a `DurableDeferred` token, and suspend. A worker\n * created with `makeWorker` or `worker` takes the item, runs the handler, and\n * records the handler's `Exit` through that token so the original flow can\n * continue with the typed success or error.\n *\n * @since 0.1.0\n */\n\nimport * as Arr from \"effect/Array\"\nimport * as Cause from \"effect/Cause\"\nimport type * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Filter from \"effect/Filter\"\nimport * as Layer from \"effect/Layer\"\nimport * as PersistedQueue from \"effect/persistence/PersistedQueue\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as Schema from \"effect/Schema\"\nimport * as Tracer from \"effect/Tracer\"\nimport * as Action from \"./Action/index.ts\"\nimport * as DurableDeferred from \"./DurableDeferred.ts\"\nimport { annotateWaiting, type FlowInstance, type FlowRuntime } from \"./FlowRuntime/index.ts\"\n\n/**\n * Type-level identifier used to recognize `DurableQueue` values.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport type TypeId = \"@smthrs/flow/DurableQueue\"\n\n/**\n * Runtime identifier attached to `DurableQueue` values.\n *\n * @category type IDs\n * @since 0.1.0\n */\nexport const TypeId: TypeId = \"@smthrs/flow/DurableQueue\"\n\n/**\n * Durable flow queue definition containing a payload schema, idempotency\n * key, and deferred used to await worker results.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface DurableQueue<\n Payload extends Schema.Top,\n Success extends Schema.Top = Schema.Void,\n Error extends Schema.Top = Schema.Never\n> {\n readonly [TypeId]: TypeId\n readonly name: string\n readonly payloadSchema: Payload\n readonly idempotencyKey: (payload: Payload[\"Type\"]) => string\n readonly deferred: DurableDeferred.DurableDeferred<Success, Error>\n}\n\n/**\n * Creates a `DurableQueue` that waits for persisted items to finish processing\n * using a `DurableDeferred`.\n *\n * **Example** (Defining a durable queue with workers)\n *\n * ```ts\n * import { Action, DurableQueue, Flow, Interpreter } from \"@smthrs/flow\"\n * import { Effect, Layer, Schema } from \"effect\"\n *\n * // Define a DurableQueue that can be used to derive workers and offer items for\n * // processing.\n * const ApiQueue = DurableQueue.make({\n * name: \"ApiQueue\",\n * payload: {\n * id: Schema.String\n * },\n * success: Schema.Void,\n * error: Schema.Never,\n * idempotencyKey(payload) {\n * return payload.id\n * }\n * })\n *\n * // Offering an item is work, so it is a declared Action: the declaration is\n * // pure data, and the implementation attaches separately.\n * const Offer = Action.make(\"MyFlow/offer\", {\n * payload: {\n * id: Schema.String\n * }\n * })\n *\n * const OfferLive = Offer.toLayer(\n * Effect.fnUntraced(function*({ id }) {\n * // Add an item to the DurableQueue defined above.\n * //\n * // When the worker has finished processing the item, the flow will\n * // resume.\n * //\n * yield* DurableQueue.process(ApiQueue, { id })\n *\n * yield* Effect.log(\"Flow succeeded!\")\n * })\n * )\n *\n * // The flow is the composite, and its body names the step it is made of.\n * const MyFlow = Flow.make(\"MyFlow\", {\n * payload: {\n * id: Schema.String\n * },\n * idempotencyKey: ({ id }) => id,\n * body: (payload) => Offer.call(payload)\n * })\n *\n * const MyFlowLayer = Layer.mergeAll(OfferLive, Interpreter.layer(MyFlow)).pipe(\n * Layer.provideMerge(Action.layerImplementations)\n * )\n *\n * // Define a worker layer that can process items from the DurableQueue.\n * const ApiWorker = DurableQueue.worker(\n * ApiQueue,\n * Effect.fnUntraced(function*({ id }) {\n * yield* Effect.log(`Worker processing API call with id: ${id}`)\n * }),\n * { concurrency: 5 } // Process up to 5 items concurrently\n * )\n * ```\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <\n Payload extends Schema.Top | Schema.Struct.Fields,\n Success extends Schema.Top = Schema.Void,\n Error extends Schema.Top = Schema.Never\n>(options: {\n readonly name: string\n readonly payload: Payload\n readonly idempotencyKey: (\n payload: Payload extends Schema.Struct.Fields ? Schema.Struct.Type<Payload>\n : Payload[\"Type\"]\n ) => string\n readonly success?: Success | undefined\n readonly error?: Error | undefined\n}): DurableQueue<\n Payload extends Schema.Struct.Fields ? Schema.Struct<Payload> : Payload,\n Success,\n Error\n> => ({\n [TypeId]: TypeId,\n name: options.name,\n payloadSchema: Schema.isSchema(options.payload)\n ? options.payload\n : Schema.Struct(options.payload as any) as any,\n idempotencyKey: options.idempotencyKey as any,\n deferred: DurableDeferred.make(`DurableQueue/${options.name}`, {\n success: options.success,\n error: options.error\n })\n})\n\nconst queueSchemas = new WeakMap<Schema.Top, Schema.Top>()\n\nconst getQueueSchema = <Payload extends Schema.Top>(\n payload: Payload\n): Schema.Struct<{\n token: typeof DurableDeferred.Token\n payload: Payload\n traceId: typeof Schema.String\n spanId: typeof Schema.String\n sampled: typeof Schema.Boolean\n}> => {\n let schema = queueSchemas.get(payload)\n if (!schema) {\n schema = Schema.Struct({\n token: DurableDeferred.Token,\n traceId: Schema.String,\n spanId: Schema.String,\n sampled: Schema.Boolean,\n payload\n })\n queueSchemas.set(payload, schema)\n }\n return schema as any\n}\n\n/**\n * Adds an item to the queue and waits for a worker to process it.\n *\n * `retrySchedule` controls retries when the persisted offer fails. The default\n * is unbounded, with exponential delays capped at one minute, so a transient\n * store outage does not lose the item. A caller-supplied schedule may exhaust;\n * its final offer failure becomes a defect to keep the public error channel\n * reserved for the worker's declared error.\n *\n * Payload construction also becomes a defect when `fields` does not satisfy\n * the queue's payload schema. The public error channel is the worker result,\n * not malformed caller input.\n *\n * @category processing\n * @since 0.1.0\n */\nexport const process: <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top\n>(\n self: DurableQueue<Payload, Success, Error>,\n payload: Payload[\"~type.make.in\"],\n options?: {\n readonly retrySchedule?: Schedule.Schedule<any, PersistedQueue.PersistedQueueError> | undefined\n }\n) => Effect.Effect<\n Success[\"Type\"],\n Error[\"Type\"],\n | FlowRuntime\n | FlowInstance\n | Crypto.Crypto\n | PersistedQueue.PersistedQueueFactory\n | Payload[\"EncodingServices\"]\n | Payload[\"DecodingServices\"]\n | Success[\"DecodingServices\"]\n | Error[\"DecodingServices\"]\n> =\n // Untraced because queue offer is a worker hot path.\n Effect.fnUntraced(function*<\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top\n >(self: DurableQueue<Payload, Success, Error>, fields: Payload[\"~type.make.in\"], options?: {\n readonly retrySchedule?: Schedule.Schedule<any, PersistedQueue.PersistedQueueError> | undefined\n }) {\n const payload = yield* self.payloadSchema.makeEffect(fields).pipe(\n Effect.mapError((issue) => new Schema.SchemaError(issue)),\n Effect.orDie\n )\n const queueName = `DurableQueue/${self.name}`\n const queue = yield* PersistedQueue.make({\n name: queueName,\n schema: getQueueSchema(self.payloadSchema)\n })\n const key = yield* Action.idempotencyKey(queueName, {\n parentScope: self.idempotencyKey(payload)\n })\n\n const deferred = DurableDeferred.make(`${self.deferred.name}/${key}`, {\n success: self.deferred.successSchema,\n error: self.deferred.errorSchema\n })\n const token = yield* DurableDeferred.token(deferred)\n\n yield* Effect.useSpan(`DurableQueue/${self.name}/process`, {\n attributes: { key }\n }, (span) =>\n queue.offer({\n token,\n payload,\n traceId: span.traceId,\n spanId: span.spanId,\n sampled: span.sampled\n } as any, { id: key }).pipe(\n Effect.tapCause(Effect.logWarning),\n Effect.catchTag(\"SchemaError\", Effect.die),\n Effect.retry(options?.retrySchedule ?? defaultRetrySchedule),\n Effect.orDie,\n Effect.annotateLogs({\n package: \"@smthrs/flow\",\n module: \"DurableQueue\",\n fiber: \"process\",\n queueName: self.name\n })\n ))\n\n yield* annotateWaiting({ reason: \"event\", token })\n return yield* DurableDeferred.await(deferred)\n })\n\nconst maxDeferredNameExcerptChars = 128\n\n/** Renders a bounded excerpt of a stored deferred name for a diagnostic. */\nconst deferredNameExcerpt = (name: string): string =>\n name.length <= maxDeferredNameExcerptChars\n ? name\n : `${name.slice(0, maxDeferredNameExcerptChars)} [${name.length - maxDeferredNameExcerptChars} characters dropped]`\n\nconst traceIdPattern = /^[0-9a-f]{32}$/\nconst spanIdPattern = /^[0-9a-f]{16}$/\n\n/**\n * The offering span as the worker span's parent, when the stored ids have the\n * W3C trace-context shape every Effect and OpenTelemetry tracer writes. A\n * stored item is not trusted to splice arbitrary identifiers into a trace.\n */\nconst externalParent = (item: {\n readonly traceId: string\n readonly spanId: string\n readonly sampled: boolean\n}): Tracer.ExternalSpan | undefined =>\n traceIdPattern.test(item.traceId) && spanIdPattern.test(item.spanId)\n ? Tracer.externalSpan({ traceId: item.traceId, spanId: item.spanId, sampled: item.sampled })\n : undefined\n\nconst defaultRetrySchedule = Schedule.min([\n Schedule.exponential(500, 1.5),\n Schedule.spaced(\"1 minute\")\n])\n\nconst makeWorkerEffect = Effect.fnUntraced(function*<\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n concurrency: number,\n maxAttempts: number\n) {\n const queue = yield* PersistedQueue.make({\n name: `DurableQueue/${self.name}`,\n schema: getQueueSchema(self.payloadSchema),\n maxAttempts,\n // The worker owns the 500 ms retry pause below. Keep an upstream queue\n // default from introducing an additional backoff after an Effect upgrade.\n retrySchedule: Schedule.spaced(0)\n })\n\n const worker = Effect.suspend(() => {\n let completion:\n | { readonly token: DurableDeferred.Token; readonly id: string; readonly attempts: number }\n | undefined\n return queue.take((item_, metadata) => {\n const item = item_ as {\n readonly token: DurableDeferred.Token\n readonly payload: Payload[\"Type\"]\n readonly traceId: string\n readonly spanId: string\n readonly sampled: boolean\n }\n return Effect.withSpan(\n Effect.gen(function*() {\n // Parse before running the handler. A malformed completion address\n // cannot strand a handler result that was already produced.\n const parsed = yield* DurableDeferred.TokenParsed.parse(item.token)\n // `process` offers each item under its key and addresses the\n // deferred `<queue deferred>/<key>`. Anything else in this queue\n // names a wait point the queue does not own (another queue's item,\n // a WaitFor gate, a human task), so completing it here would settle\n // a foreign wait under this queue's success schema.\n const expected = `${self.deferred.name}/${metadata.id}`\n if (parsed.deferredName !== expected) {\n return yield* new DurableDeferred.TokenInvalid({\n code: \"deferred_mismatch\",\n message: `The item \"${metadata.id}\" addresses the deferred \"${\n deferredNameExcerpt(parsed.deferredName)\n }\", not \"${deferredNameExcerpt(expected)}\".`\n })\n }\n const deferred = DurableDeferred.make(parsed.deferredName, {\n success: self.deferred.successSchema,\n error: self.deferred.errorSchema\n })\n let exit = yield* Effect.exit(f(item.payload))\n if (Exit.isFailure(exit)) {\n const [interrupts, reasons] = Arr.partition(\n exit.cause.reasons,\n Filter.fromPredicate(Cause.isInterruptReason)\n )\n // Match DurableDeferred.into: interruption alone is not a durable\n // outcome, and must leave the item available without an attempt.\n if (interrupts.length === exit.cause.reasons.length) {\n return yield* Effect.failCause(Cause.fromReasons<never>(interrupts))\n } else if (interrupts.length > 0) {\n exit = Exit.failCause(Cause.fromReasons(reasons))\n }\n }\n completion = { token: item.token, ...metadata }\n yield* DurableDeferred.done(deferred, {\n token: item.token,\n exit\n })\n }).pipe(\n Effect.catchTag(\"@smthrs/flow/DurableDeferred/TokenInvalid\", (error) =>\n Effect.logError(\n `DurableQueue \"${self.name}\" could not complete an item because its token was invalid. ${error.message}`\n ))\n ),\n `DurableQueue/${self.name}/worker`,\n {\n captureStackTrace: false,\n parent: externalParent(item)\n }\n )\n }).pipe(\n Effect.tapCause((cause) => {\n if (!completion) return Effect.void\n return Effect.logError(\"DurableQueue failed to persist or acknowledge a handler result\", cause).pipe(\n Effect.annotateLogs({\n token: completion.token,\n itemId: completion.id,\n attempt: completion.attempts,\n maxAttempts,\n exhausted: !Cause.hasInterrupts(cause) && completion.attempts >= maxAttempts\n })\n )\n })\n )\n }).pipe(\n // A persistently failing take would otherwise consume a core in a tight\n // loop while the queue store is unavailable.\n Effect.catchCause((cause) =>\n Effect.logWarning(cause).pipe(\n Effect.andThen(Effect.sleep(500))\n )\n ),\n Effect.forever,\n Effect.annotateLogs({\n package: \"@smthrs/flow\",\n module: \"DurableQueue\",\n fiber: \"worker\",\n queueName: self.name\n })\n )\n\n return yield* Effect.replicateEffect(worker, concurrency, { concurrency, discard: true }).pipe(\n Effect.andThen(Effect.never)\n )\n})\n\n/**\n * Create a worker effect that processes items from the durable queue.\n *\n * `concurrency` defaults to one and must be a positive safe integer. It is\n * checked before the persisted queue is opened. `maxAttempts` defaults to ten\n * and is passed to the persisted queue. Completion-write failures can rerun the\n * handler; side effects must be idempotent. Exhaustion leaves the flow waiting.\n *\n * @throws A `RangeError` when `concurrency` is not a positive safe integer.\n * @category worker\n * @since 0.1.0\n */\nexport const makeWorker: <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n options?: {\n readonly concurrency?: number | undefined\n readonly maxAttempts?: number | undefined\n } | undefined\n) => Effect.Effect<\n never,\n never,\n | FlowRuntime\n | PersistedQueue.PersistedQueueFactory\n | R\n | Payload[\"EncodingServices\"]\n | Payload[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"EncodingServices\"]\n> = <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n options?: {\n readonly concurrency?: number | undefined\n readonly maxAttempts?: number | undefined\n }\n) => {\n const concurrency = options?.concurrency ?? 1\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) {\n throw new RangeError(\n `DurableQueue.makeWorker: concurrency must be a positive safe integer, and was ${concurrency}.`\n )\n }\n return makeWorkerEffect(self, f, concurrency, options?.maxAttempts ?? 10)\n}\n\n/**\n * Create a layer that runs workers for the durable queue.\n *\n * @category worker\n * @since 0.1.0\n */\nexport const worker: <\n Payload extends Schema.Top,\n Success extends Schema.Top,\n Error extends Schema.Top,\n R\n>(\n self: DurableQueue<Payload, Success, Error>,\n f: (payload: Payload[\"Type\"]) => Effect.Effect<Success[\"Type\"], Error[\"Type\"], R>,\n options?: {\n readonly concurrency?: number | undefined\n readonly maxAttempts?: number | undefined\n } | undefined\n) => Layer.Layer<\n never,\n never,\n | FlowRuntime\n | PersistedQueue.PersistedQueueFactory\n | R\n | Payload[\"EncodingServices\"]\n | Payload[\"DecodingServices\"]\n | Success[\"EncodingServices\"]\n | Error[\"EncodingServices\"]\n> = (self, f, options) => Layer.effectDiscard(Effect.forkScoped(makeWorker(self, f, options)))\n"]}
@@ -63,7 +63,7 @@ export const derived = {
63
63
  * @since 0.1.0
64
64
  */
65
65
  export const fresh = {
66
- mint: () => Effect.flatMap(Crypto.Crypto, (crypto) => Effect.orDie(crypto.randomUUIDv4))
66
+ mint: () => Effect.flatMap(Crypto.Crypto, (crypto) => Effect.orDie(crypto.randomUUIDv4()))
67
67
  };
68
68
  /**
69
69
  * Context reference carrying the host's execution-id source, defaulting to
@@ -1 +1 @@
1
- {"version":3,"file":"ExecutionIds.js","sourceRoot":"","sources":["../../../src/Flow/ExecutionIds.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAoB9D;;;;;;;;;;;GAWG;AACH,MAAM,YAAY,GAAG,CACnB,IAAO,EACP,OAAgB,EACoF,EAAE,CACrG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,WA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AAyB,EACL,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAA","sourcesContent":["/**\n * The ambient source of execution identity, for a flow executed without one.\n *\n * Identity has three sources, in this order: the `executionId` the caller\n * named, the `idempotencyKey` the flow declared, and — when neither exists —\n * the source in this module. The first two are decisions an author made at the\n * call site or the declaration site; the third is a decision the *host* makes\n * once, for every flow it drives, which is why it is a context reference and\n * not another option on `execute`.\n *\n * The default mints a fresh cryptographic UUID for every unkeyed invocation.\n * Equal payloads are independent requests. To reattach after a crash, retain\n * the returned execution id, declare an idempotency key, or explicitly install\n * the `derived` source. Changing this default does not rewrite stored ids.\n *\n * @since 0.1.0\n */\n\nimport { Sha256 } from \"@smthrs/crypto\"\nimport { DerivedKey } from \"@smthrs/keys\"\nimport * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport { ExecutionIdRequired } from \"./ExecutionIdRequired.ts\"\nimport type { Any } from \"./Flow.ts\"\n\n/**\n * Mints the execution id of an invocation that named none.\n *\n * It is consulted only after the two explicit sources are absent, and it runs\n * before the runtime is read, so a source that cannot name the invocation\n * fails the execution rather than starting one under a guessed identity.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ExecutionIdSource {\n readonly mint: <W extends Any>(\n flow: W,\n payload: unknown\n ) => Effect.Effect<string, never, Crypto.Crypto | W[\"payloadSchema\"][\"EncodingServices\"]>\n}\n\n/**\n * The canonical key of an invocation: the flow's own payload codec, then RFC\n * 8785, then SHA-256.\n *\n * Encoding first is what makes the key agree with the durable driver, which\n * compares the ENCODED payload when it decides whether an existing run row is\n * the same invocation. A payload with no canonical form — a non-finite number,\n * a lone surrogate, a cycle — has no derivable identity at all, so it fails\n * here instead of hashing something approximate.\n *\n * @private\n */\nconst canonicalKey = <W extends Any>(\n flow: W,\n payload: unknown\n): Effect.Effect<string, ExecutionIdRequired, Crypto.Crypto | W[\"payloadSchema\"][\"EncodingServices\"]> =>\n (Schema.encodeEffect(Schema.toCodecJson(flow.payloadSchema))(payload) as Effect.Effect<\n unknown,\n unknown,\n W[\"payloadSchema\"][\"EncodingServices\"]\n >).pipe(\n Effect.flatMap((encoded) => Schema.decodeUnknownEffect(DerivedKey)(encoded)),\n Effect.mapError(() => new ExecutionIdRequired({ flowName: flow._tag }))\n )\n\n/**\n * An opt-in deterministic source over the flow tag and the payload's\n * canonical form.\n *\n * Same tag and same encoded payload derive the same id, which is exactly the\n * pair the durable driver already treats as one invocation, so a re-drive of a\n * crashed program re-attaches to the run it left behind instead of opening a\n * second one.\n *\n * The tag and canonical payload key are JSON-tuple framed before hashing.\n * Their strings are used exactly as given and encoded as UTF-8, with no Unicode\n * normalization. This preimage encoding freezes at rc.0.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const derived: ExecutionIdSource = {\n mint: (flow, payload) =>\n canonicalKey(flow, payload).pipe(\n // The JSON tuple prevents delimiter splicing. This exact framing freezes at rc.0.\n Effect.flatMap((key) => Effect.orDie(Schema.decodeUnknownEffect(Sha256)(JSON.stringify([flow._tag, key])))),\n Effect.orDie\n )\n}\n\n/**\n * Mints independent execution ids for unkeyed requests using host cryptography.\n * @category constructors\n * @since 0.1.0\n */\nexport const fresh: ExecutionIdSource = {\n mint: () => Effect.flatMap(Crypto.Crypto, (crypto) => Effect.orDie(crypto.randomUUIDv4))\n}\n\n/**\n * Context reference carrying the host's execution-id source, defaulting to\n * {@link fresh}.\n *\n * @category idempotency\n * @since 0.1.0\n */\nexport const CurrentExecutionIds = Context.Reference<ExecutionIdSource>(\n \"@smthrs/flow/Flow/CurrentExecutionIds\",\n {\n defaultValue: () => fresh\n }\n)\n\n/**\n * Declares the host's execution-id source as a layer.\n *\n * **When to use**\n *\n * Install `derived` when equal payloads deliberately identify the same work,\n * or provide a host-specific identity source. Explicit caller execution ids\n * and declared idempotency keys take precedence over this source.\n *\n * @category idempotency\n * @since 0.1.0\n */\nexport const layerExecutionIds = (\n source: ExecutionIdSource\n): Layer.Layer<never> => Layer.succeed(CurrentExecutionIds)(source)\n"]}
1
+ {"version":3,"file":"ExecutionIds.js","sourceRoot":"","sources":["../../../src/Flow/ExecutionIds.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,KAAK,OAAO,MAAM,gBAAgB,CAAA;AACzC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,KAAK,MAAM,cAAc,CAAA;AACrC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAA;AAoB9D;;;;;;;;;;;GAWG;AACH,MAAM,YAAY,GAAG,CACnB,IAAO,EACP,OAAgB,EACoF,EAAE,CACrG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,OAAO,CAIlE,CAAC,IAAI,CACL,MAAM,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,EAC5E,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,mBAAmB,CAAC,EAAE,QAAQ,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CACxE,CAAA;AAEH;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,OAAO,GAAsB;IACxC,IAAI,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,CACtB,YAAY,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,IAAI;IAC9B,kFAAkF;IAClF,MAAM,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAC3G,MAAM,CAAC,KAAK,CACb;CACJ,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,KAAK,GAAsB;IACtC,IAAI,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;CAC3F,CAAA;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAClD,uCAAuC,EACvC;IACE,YAAY,EAAE,GAAG,EAAE,CAAC,KAAK;CAC1B,CACF,CAAA;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,MAAyB,EACL,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAA","sourcesContent":["/**\n * The ambient source of execution identity, for a flow executed without one.\n *\n * Identity has three sources, in this order: the `executionId` the caller\n * named, the `idempotencyKey` the flow declared, and — when neither exists —\n * the source in this module. The first two are decisions an author made at the\n * call site or the declaration site; the third is a decision the *host* makes\n * once, for every flow it drives, which is why it is a context reference and\n * not another option on `execute`.\n *\n * The default mints a fresh cryptographic UUID for every unkeyed invocation.\n * Equal payloads are independent requests. To reattach after a crash, retain\n * the returned execution id, declare an idempotency key, or explicitly install\n * the `derived` source. Changing this default does not rewrite stored ids.\n *\n * @since 0.1.0\n */\n\nimport { Sha256 } from \"@smthrs/crypto\"\nimport { DerivedKey } from \"@smthrs/keys\"\nimport * as Context from \"effect/Context\"\nimport * as Crypto from \"effect/Crypto\"\nimport * as Effect from \"effect/Effect\"\nimport * as Layer from \"effect/Layer\"\nimport * as Schema from \"effect/Schema\"\nimport { ExecutionIdRequired } from \"./ExecutionIdRequired.ts\"\nimport type { Any } from \"./Flow.ts\"\n\n/**\n * Mints the execution id of an invocation that named none.\n *\n * It is consulted only after the two explicit sources are absent, and it runs\n * before the runtime is read, so a source that cannot name the invocation\n * fails the execution rather than starting one under a guessed identity.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ExecutionIdSource {\n readonly mint: <W extends Any>(\n flow: W,\n payload: unknown\n ) => Effect.Effect<string, never, Crypto.Crypto | W[\"payloadSchema\"][\"EncodingServices\"]>\n}\n\n/**\n * The canonical key of an invocation: the flow's own payload codec, then RFC\n * 8785, then SHA-256.\n *\n * Encoding first is what makes the key agree with the durable driver, which\n * compares the ENCODED payload when it decides whether an existing run row is\n * the same invocation. A payload with no canonical form — a non-finite number,\n * a lone surrogate, a cycle — has no derivable identity at all, so it fails\n * here instead of hashing something approximate.\n *\n * @private\n */\nconst canonicalKey = <W extends Any>(\n flow: W,\n payload: unknown\n): Effect.Effect<string, ExecutionIdRequired, Crypto.Crypto | W[\"payloadSchema\"][\"EncodingServices\"]> =>\n (Schema.encodeEffect(Schema.toCodecJson(flow.payloadSchema))(payload) as Effect.Effect<\n unknown,\n unknown,\n W[\"payloadSchema\"][\"EncodingServices\"]\n >).pipe(\n Effect.flatMap((encoded) => Schema.decodeUnknownEffect(DerivedKey)(encoded)),\n Effect.mapError(() => new ExecutionIdRequired({ flowName: flow._tag }))\n )\n\n/**\n * An opt-in deterministic source over the flow tag and the payload's\n * canonical form.\n *\n * Same tag and same encoded payload derive the same id, which is exactly the\n * pair the durable driver already treats as one invocation, so a re-drive of a\n * crashed program re-attaches to the run it left behind instead of opening a\n * second one.\n *\n * The tag and canonical payload key are JSON-tuple framed before hashing.\n * Their strings are used exactly as given and encoded as UTF-8, with no Unicode\n * normalization. This preimage encoding freezes at rc.0.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const derived: ExecutionIdSource = {\n mint: (flow, payload) =>\n canonicalKey(flow, payload).pipe(\n // The JSON tuple prevents delimiter splicing. This exact framing freezes at rc.0.\n Effect.flatMap((key) => Effect.orDie(Schema.decodeUnknownEffect(Sha256)(JSON.stringify([flow._tag, key])))),\n Effect.orDie\n )\n}\n\n/**\n * Mints independent execution ids for unkeyed requests using host cryptography.\n * @category constructors\n * @since 0.1.0\n */\nexport const fresh: ExecutionIdSource = {\n mint: () => Effect.flatMap(Crypto.Crypto, (crypto) => Effect.orDie(crypto.randomUUIDv4()))\n}\n\n/**\n * Context reference carrying the host's execution-id source, defaulting to\n * {@link fresh}.\n *\n * @category idempotency\n * @since 0.1.0\n */\nexport const CurrentExecutionIds = Context.Reference<ExecutionIdSource>(\n \"@smthrs/flow/Flow/CurrentExecutionIds\",\n {\n defaultValue: () => fresh\n }\n)\n\n/**\n * Declares the host's execution-id source as a layer.\n *\n * **When to use**\n *\n * Install `derived` when equal payloads deliberately identify the same work,\n * or provide a host-specific identity source. Explicit caller execution ids\n * and declared idempotency keys take precedence over this source.\n *\n * @category idempotency\n * @since 0.1.0\n */\nexport const layerExecutionIds = (\n source: ExecutionIdSource\n): Layer.Layer<never> => Layer.succeed(CurrentExecutionIds)(source)\n"]}
@@ -5,8 +5,8 @@
5
5
  */
6
6
  import { CapabilityPattern } from "@smthrs/capability/Capability";
7
7
  import type * as Exit from "effect/Exit";
8
+ import type { ExitEncoded } from "effect/rpc/RpcMessage";
8
9
  import * as Schema from "effect/Schema";
9
- import type { ExitEncoded } from "effect/unstable/rpc/RpcMessage";
10
10
  declare const ResultTypeId = "@smthrs/flow/Flow/Result";
11
11
  /**
12
12
  * Returns `true` when a value is a flow `Result`.
@@ -1 +1 @@
1
- {"version":3,"file":"Result.d.ts","sourceRoot":"","sources":["../../../src/Flow/Result.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AAEH,OAAO,EAA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B,MAAM,CAAC;IACL,OAAO,EAAE,SAAS;IAClB,KAAK,EAAE,SAAS;CACjB,CAAC,CACH,CACK,CAAA","sourcesContent":["// Deep reviewed and polished by a human on 2026-08-10.\n\n/**\n * Serializable completion and suspension states returned by flow executions.\n *\n * @since 0.1.0\n */\n\nimport { CapabilityPattern } from \"@smthrs/capability/Capability\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaIssue from \"effect/SchemaIssue\"\nimport * as SchemaParser from \"effect/SchemaParser\"\nimport * as Transformation from \"effect/SchemaTransformation\"\nimport type { ExitEncoded } from \"effect/unstable/rpc/RpcMessage\"\n\nconst ResultTypeId = \"@smthrs/flow/Flow/Result\"\n\n/**\n * Returns `true` when a value is a flow `Result`.\n *\n * @category results\n * @since 0.1.0\n */\nexport const isResult = <A = unknown, E = unknown>(\n u: unknown\n): u is Result<A, E> => {\n if (u !== Object(u)) return false\n const marker = Object.getOwnPropertyDescriptor(u, ResultTypeId)\n if (marker === undefined || !(\"value\" in marker) || marker.value !== ResultTypeId) return false\n const tag = Object.getOwnPropertyDescriptor(u, \"_tag\")\n return tag !== undefined && \"value\" in tag &&\n (tag.value === \"Complete\" || tag.value === \"Suspended\" || tag.value === \"Handoff\")\n}\n\n/**\n * Result of a flow execution: a completed exit, a suspended flow state, or a\n * handoff to the next round of a trampoline lineage.\n *\n * @category results\n * @since 0.1.0\n */\nexport type Result<A, E> = Complete<A, E> | Suspended | Handoff\n\n/**\n * Encoded representation of a flow `Result`.\n *\n * @category results\n * @since 0.1.0\n */\nexport type ResultEncoded<A, E> =\n | CompleteEncoded<A, E>\n | typeof Suspended.Encoded\n | typeof Handoff.Encoded\n\n/**\n * Encoded representation of a completed flow result containing an encoded\n * `Exit`.\n *\n * @category results\n * @since 0.1.0\n */\nexport interface CompleteEncoded<A, E> {\n readonly _tag: \"Complete\"\n readonly exit: ExitEncoded<A, E>\n}\n\n/**\n * Schema constructor for `Complete` flow results using the supplied\n * success and error schemas.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport interface CompleteSchema<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n> extends\n Schema.declareConstructor<\n Complete<Success[\"Type\"], Error[\"Type\"]>,\n Complete<Success[\"Encoded\"], Error[\"Encoded\"]>,\n readonly [Schema.Exit<Success, Error, Schema.Defect>]\n >\n{\n readonly success: Success\n readonly error: Error\n}\n\n/**\n * Represents a completed flow execution with its success or failure `Exit`.\n *\n * @category results\n * @since 0.1.0\n */\nexport class Complete<A, E> extends Data.TaggedClass(\"Complete\")<{\n readonly exit: Exit.Exit<A, E>\n}> {\n /**\n * Marks this value as a flow result for runtime guards.\n *\n * @since 0.1.0\n */\n readonly [ResultTypeId] = ResultTypeId\n\n /**\n * Builds the schema for completed flow results from success and error schemas.\n *\n * @since 0.1.0\n */\n static Schema<Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly success: Success\n readonly error: Error\n }): CompleteSchema<Success, Error> {\n // The declaration stays inline because it closes over this constructor's schemas.\n const schema = Schema.declareConstructor<\n Complete<Success[\"Type\"], Error[\"Type\"]>,\n Complete<Success[\"Encoded\"], Error[\"Encoded\"]>\n >()(\n [Schema.Exit(options.success, options.error, Schema.Defect())],\n ([exit]) => (input, ast, options) => {\n if (!(isResult(input) && input._tag === \"Complete\")) {\n return Effect.fail(new SchemaIssue.InvalidType(ast, input, options))\n }\n return Effect.mapBothEager(\n SchemaParser.decodeEffect(exit)(input.exit, options),\n {\n onSuccess: (exit) => new Complete({ exit }),\n onFailure: (issue) =>\n new SchemaIssue.Composite(\n ast,\n [\n new SchemaIssue.Pointer([\"exit\"], issue)\n ],\n input,\n options\n )\n }\n )\n },\n {\n expected: \"Flow.Complete\",\n toCodecJson: ([exit]) =>\n Schema.link<Complete<Success[\"Encoded\"], Error[\"Encoded\"]>>()(\n Schema.Struct({\n _tag: Schema.tag(\"Complete\"),\n exit\n }),\n Transformation.transform({\n decode: (encoded) => new Complete({ exit: encoded.exit }),\n encode: (result) => (({\n _tag: \"Complete\",\n exit: result.exit\n }) as const)\n })\n )\n }\n )\n return Schema.make(schema.ast, {\n success: options.success,\n error: options.error\n })\n }\n}\n\n/**\n * Represents a suspended flow execution, optionally carrying the cause that\n * triggered suspension.\n *\n * @category results\n * @since 0.1.0\n */\nexport class Suspended extends Schema.Class<Suspended>(\n \"@smthrs/flow/Flow/Suspended\"\n)({\n _tag: Schema.tag(\"Suspended\"),\n cause: Schema.optional(Schema.Cause(Schema.Never, Schema.Defect()))\n}) {\n /**\n * Marks this value as a flow result for runtime guards.\n *\n * @since 0.1.0\n */\n readonly [ResultTypeId] = ResultTypeId\n}\n\n/**\n * The deadline a trampoline lineage's rounds share: the journaled first start\n * of its originating round and the bound in milliseconds, so every round\n * expires at `startedAtMs + deadlineMs`.\n *\n * @category results\n * @since 1.0.0\n */\nexport const LineageDeadline = Schema.Struct({\n startedAtMs: Schema.Number,\n deadlineMs: Schema.Number\n})\n\n/**\n * The deadline a trampoline lineage's rounds share.\n *\n * @category results\n * @since 1.0.0\n */\nexport type LineageDeadline = typeof LineageDeadline.Type\n\n/**\n * Represents a flow round that ended by handing off to the next round of its\n * trampoline lineage.\n *\n * A round settles this way when its body's root value is a `to` invocation\n * (`docs/concepts/trampoline-rounds.md`): the round produced no answer of\n * its own, it produced the NEXT flow to run. `flow` is the target's tag, so the\n * value survives the journal and the run row unchanged.\n *\n * DECIDED: `payload` is the target's payload in\n * ENCODED form. The target's `to` method accepts its ordinary constructor\n * shape so authoring stays aligned with `call` and `execute`; the body\n * interpreter resolves planned references and encodes the invocation through\n * the target declaration before constructing `Handoff`. The receiving round\n * decodes those bytes through the same schema.\n *\n * It is a third settlement rather than a `Complete` carrying a magic value\n * because the engine has to tell \"this run answered\" from \"this run continues\n * elsewhere\" without decoding against a success schema the handoff never\n * satisfies.\n *\n * @category results\n * @since 0.1.0\n */\nexport class Handoff extends Schema.Class<Handoff>(\n \"@smthrs/flow/Flow/Handoff\"\n)({\n _tag: Schema.tag(\"Handoff\"),\n flow: Schema.NonEmptyString,\n capabilityCeilings: Schema.optionalKey(Schema.Array(Schema.Array(CapabilityPattern))),\n payload: Schema.Unknown,\n /**\n * The lineage deadline the next round runs under, stamped by the round\n * that handed off when its lineage is bounded (`Deadline.bound`).\n */\n deadline: Schema.optionalKey(LineageDeadline)\n}) {\n /**\n * Marks this value as a flow result for runtime guards.\n *\n * @since 0.1.0\n */\n readonly [ResultTypeId] = ResultTypeId\n}\n\n/**\n * Creates a schema for flow results using the supplied success and error\n * schemas.\n *\n * @category results\n * @since 0.1.0\n */\nexport const Result = <\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n>(options: {\n readonly success: Success\n readonly error: Error\n}) => Schema.Union([Complete.Schema(options), Suspended, Handoff])\n\nconst AnyOrVoid = Schema.Union([Schema.Any, Schema.Void])\n\n/**\n * Schema for encoded flow results with generic success and error payloads.\n *\n * @category results\n * @since 0.1.0\n */\nexport const ResultEncoded: Schema.Codec<ResultEncoded<any, any>> = Schema.toEncoded(\n Schema.toCodecJson(\n Result({\n success: AnyOrVoid,\n error: AnyOrVoid\n })\n )\n) as any\n"]}
1
+ {"version":3,"file":"Result.js","sourceRoot":"","sources":["../../../src/Flow/Result.ts"],"names":[],"mappings":"AAAA,uDAAuD;AAEvD;;;;GAIG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,+BAA+B,CAAA;AACjE,OAAO,KAAK,IAAI,MAAM,aAAa,CAAA;AACnC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AAGvC,OAAO,KAAK,MAAM,MAAM,eAAe,CAAA;AACvC,OAAO,KAAK,WAAW,MAAM,oBAAoB,CAAA;AACjD,OAAO,KAAK,YAAY,MAAM,qBAAqB,CAAA;AACnD,OAAO,KAAK,cAAc,MAAM,6BAA6B,CAAA;AAE7D,MAAM,YAAY,GAAG,0BAA0B,CAAA;AAE/C;;;;;GAKG;AACH,MA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AS,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;AAEzD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,aAAa,GAA0C,MAAM,CAAC,SAAS,CAClF,MAAM,CAAC,WAAW,CAChB,MAAM,CAAC;IACL,OAAO,EAAE,SAAS;IAClB,KAAK,EAAE,SAAS;CACjB,CAAC,CACH,CACK,CAAA","sourcesContent":["// Deep reviewed and polished by a human on 2026-08-10.\n\n/**\n * Serializable completion and suspension states returned by flow executions.\n *\n * @since 0.1.0\n */\n\nimport { CapabilityPattern } from \"@smthrs/capability/Capability\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport type * as Exit from \"effect/Exit\"\nimport type { ExitEncoded } from \"effect/rpc/RpcMessage\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaIssue from \"effect/SchemaIssue\"\nimport * as SchemaParser from \"effect/SchemaParser\"\nimport * as Transformation from \"effect/SchemaTransformation\"\n\nconst ResultTypeId = \"@smthrs/flow/Flow/Result\"\n\n/**\n * Returns `true` when a value is a flow `Result`.\n *\n * @category results\n * @since 0.1.0\n */\nexport const isResult = <A = unknown, E = unknown>(\n u: unknown\n): u is Result<A, E> => {\n if (u !== Object(u)) return false\n const marker = Object.getOwnPropertyDescriptor(u, ResultTypeId)\n if (marker === undefined || !(\"value\" in marker) || marker.value !== ResultTypeId) return false\n const tag = Object.getOwnPropertyDescriptor(u, \"_tag\")\n return tag !== undefined && \"value\" in tag &&\n (tag.value === \"Complete\" || tag.value === \"Suspended\" || tag.value === \"Handoff\")\n}\n\n/**\n * Result of a flow execution: a completed exit, a suspended flow state, or a\n * handoff to the next round of a trampoline lineage.\n *\n * @category results\n * @since 0.1.0\n */\nexport type Result<A, E> = Complete<A, E> | Suspended | Handoff\n\n/**\n * Encoded representation of a flow `Result`.\n *\n * @category results\n * @since 0.1.0\n */\nexport type ResultEncoded<A, E> =\n | CompleteEncoded<A, E>\n | typeof Suspended.Encoded\n | typeof Handoff.Encoded\n\n/**\n * Encoded representation of a completed flow result containing an encoded\n * `Exit`.\n *\n * @category results\n * @since 0.1.0\n */\nexport interface CompleteEncoded<A, E> {\n readonly _tag: \"Complete\"\n readonly exit: ExitEncoded<A, E>\n}\n\n/**\n * Schema constructor for `Complete` flow results using the supplied\n * success and error schemas.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport interface CompleteSchema<\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n> extends\n Schema.declareConstructor<\n Complete<Success[\"Type\"], Error[\"Type\"]>,\n Complete<Success[\"Encoded\"], Error[\"Encoded\"]>,\n readonly [Schema.Exit<Success, Error, Schema.Defect>]\n >\n{\n readonly success: Success\n readonly error: Error\n}\n\n/**\n * Represents a completed flow execution with its success or failure `Exit`.\n *\n * @category results\n * @since 0.1.0\n */\nexport class Complete<A, E> extends Data.TaggedClass(\"Complete\")<{\n readonly exit: Exit.Exit<A, E>\n}> {\n /**\n * Marks this value as a flow result for runtime guards.\n *\n * @since 0.1.0\n */\n readonly [ResultTypeId] = ResultTypeId\n\n /**\n * Builds the schema for completed flow results from success and error schemas.\n *\n * @since 0.1.0\n */\n static Schema<Success extends Schema.Constraint, Error extends Schema.Constraint>(options: {\n readonly success: Success\n readonly error: Error\n }): CompleteSchema<Success, Error> {\n // The declaration stays inline because it closes over this constructor's schemas.\n const schema = Schema.declareConstructor<\n Complete<Success[\"Type\"], Error[\"Type\"]>,\n Complete<Success[\"Encoded\"], Error[\"Encoded\"]>\n >()(\n [Schema.Exit(options.success, options.error, Schema.Defect())],\n ([exit]) => (input, ast, options) => {\n if (!(isResult(input) && input._tag === \"Complete\")) {\n return Effect.fail(new SchemaIssue.InvalidType(ast, input, options))\n }\n return Effect.mapBothEager(\n SchemaParser.decodeEffect(exit)(input.exit, options),\n {\n onSuccess: (exit) => new Complete({ exit }),\n onFailure: (issue) =>\n new SchemaIssue.Composite(\n ast,\n [\n new SchemaIssue.Pointer([\"exit\"], issue)\n ],\n input,\n options\n )\n }\n )\n },\n {\n expected: \"Flow.Complete\",\n toCodecJson: ([exit]) =>\n Schema.link<Complete<Success[\"Encoded\"], Error[\"Encoded\"]>>()(\n Schema.Struct({\n _tag: Schema.tag(\"Complete\"),\n exit\n }),\n Transformation.transform({\n decode: (encoded) => new Complete({ exit: encoded.exit }),\n encode: (result) => (({\n _tag: \"Complete\",\n exit: result.exit\n }) as const)\n })\n )\n }\n )\n return Schema.make(schema.ast, {\n success: options.success,\n error: options.error\n })\n }\n}\n\n/**\n * Represents a suspended flow execution, optionally carrying the cause that\n * triggered suspension.\n *\n * @category results\n * @since 0.1.0\n */\nexport class Suspended extends Schema.Class<Suspended>(\n \"@smthrs/flow/Flow/Suspended\"\n)({\n _tag: Schema.tag(\"Suspended\"),\n cause: Schema.optional(Schema.Cause(Schema.Never, Schema.Defect()))\n}) {\n /**\n * Marks this value as a flow result for runtime guards.\n *\n * @since 0.1.0\n */\n readonly [ResultTypeId] = ResultTypeId\n}\n\n/**\n * The deadline a trampoline lineage's rounds share: the journaled first start\n * of its originating round and the bound in milliseconds, so every round\n * expires at `startedAtMs + deadlineMs`.\n *\n * @category results\n * @since 1.0.0\n */\nexport const LineageDeadline = Schema.Struct({\n startedAtMs: Schema.Number,\n deadlineMs: Schema.Number\n})\n\n/**\n * The deadline a trampoline lineage's rounds share.\n *\n * @category results\n * @since 1.0.0\n */\nexport type LineageDeadline = typeof LineageDeadline.Type\n\n/**\n * Represents a flow round that ended by handing off to the next round of its\n * trampoline lineage.\n *\n * A round settles this way when its body's root value is a `to` invocation\n * (`docs/concepts/trampoline-rounds.md`): the round produced no answer of\n * its own, it produced the NEXT flow to run. `flow` is the target's tag, so the\n * value survives the journal and the run row unchanged.\n *\n * DECIDED: `payload` is the target's payload in\n * ENCODED form. The target's `to` method accepts its ordinary constructor\n * shape so authoring stays aligned with `call` and `execute`; the body\n * interpreter resolves planned references and encodes the invocation through\n * the target declaration before constructing `Handoff`. The receiving round\n * decodes those bytes through the same schema.\n *\n * It is a third settlement rather than a `Complete` carrying a magic value\n * because the engine has to tell \"this run answered\" from \"this run continues\n * elsewhere\" without decoding against a success schema the handoff never\n * satisfies.\n *\n * @category results\n * @since 0.1.0\n */\nexport class Handoff extends Schema.Class<Handoff>(\n \"@smthrs/flow/Flow/Handoff\"\n)({\n _tag: Schema.tag(\"Handoff\"),\n flow: Schema.NonEmptyString,\n capabilityCeilings: Schema.optionalKey(Schema.Array(Schema.Array(CapabilityPattern))),\n payload: Schema.Unknown,\n /**\n * The lineage deadline the next round runs under, stamped by the round\n * that handed off when its lineage is bounded (`Deadline.bound`).\n */\n deadline: Schema.optionalKey(LineageDeadline)\n}) {\n /**\n * Marks this value as a flow result for runtime guards.\n *\n * @since 0.1.0\n */\n readonly [ResultTypeId] = ResultTypeId\n}\n\n/**\n * Creates a schema for flow results using the supplied success and error\n * schemas.\n *\n * @category results\n * @since 0.1.0\n */\nexport const Result = <\n Success extends Schema.Constraint,\n Error extends Schema.Constraint\n>(options: {\n readonly success: Success\n readonly error: Error\n}) => Schema.Union([Complete.Schema(options), Suspended, Handoff])\n\nconst AnyOrVoid = Schema.Union([Schema.Any, Schema.Void])\n\n/**\n * Schema for encoded flow results with generic success and error payloads.\n *\n * @category results\n * @since 0.1.0\n */\nexport const ResultEncoded: Schema.Codec<ResultEncoded<any, any>> = Schema.toEncoded(\n Schema.toCodecJson(\n Result({\n success: AnyOrVoid,\n error: AnyOrVoid\n })\n )\n) as any\n"]}
@@ -44,7 +44,7 @@ export const intoResult = (effect) => Effect.contextWith((context) => {
44
44
  // (`docs/concepts/trampoline-rounds.md`).
45
45
  onSuccess: (value) => Effect.succeed(instance.handoff ?? new Complete({ exit: Exit.succeed(value) })),
46
46
  onFailure: (cause) => {
47
- const [reasons, interrupts] = Arr.partition(cause.reasons, Filter.fromPredicate(Cause.isInterruptReason));
47
+ const [interrupts, reasons] = Arr.partition(cause.reasons, Filter.fromPredicate(Cause.isInterruptReason));
48
48
  const hasInterruptsOnly = interrupts.length === cause.reasons.length;
49
49
  const filtered = reasons.length === 0 ? cause : Cause.fromReasons(reasons);
50
50
  return instance.suspended && hasInterruptsOnly