@restatedev/restate-sdk-cloudflare-workers 1.10.2 → 1.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"common_api.d.cts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;cAwCa;6GAmGmlrB,IAAA,QAAA,EAAA;;EAnGnlrB,GAAA,CAAA,gBAAA,uBAAmC,CAAA,OAAA,CAAA,EAAA,CAAA,CAAA,MAAA,GAAA,CAAA,gBAAA,QAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA;oHAmGowvB,IAAA,qBAAA,QAAA,EAAA;;;;;AAAptE,KA9FplrB,kBA8FolrB,CAAA,CAAA,CAAA,GA9F5jrB,cA8F4jrB,CA9F7irB,CA8F6irB,CAAA;AAAotE,cALvyvB,oBAKuyvB,EAAA,OALnxvB,QAAA,CAAA,OAKmxvB;AAAA,cAJvyvB,mBAIuyvB,EAAA,OAJpxvB,QAAA,CAAA,MAAA,CAAA,SAIoxvB;AAAA,cAHvyvB,yBAGuyvB,EAAA,OAH9wvB,QAAA,CAAA,MAAA,CAAA,MAG8wvB;cAFvyvB,8BAAqB,QAAA,CAAA,QAAA,CAAA;cACrB,oCAA2B,QAAA,CAAA,QAAA,CAAA"}
1
+ {"version":3,"file":"common_api.d.cts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;cAwCa;6GAmGiwrB,IAAA,QAAA,EAAA;;EAnGjwrB,GAAA,CAAA,gBAAA,uBAAmC,CAAA,OAAA,CAAA,EAAA,CAAA,CAAA,MAAA,GAAA,CAAA,gBAAA,QAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA;oHAmGk7vB,IAAA,qBAAA,QAAA,EAAA;;;;;AAAptE,KA9FlwrB,kBA8FkwrB,CAAA,CAAA,CAAA,GA9F1urB,cA8F0urB,CA9F3trB,CA8F2trB,CAAA;AAAotE,cALr9vB,oBAKq9vB,EAAA,OALj8vB,QAAA,CAAA,OAKi8vB;AAAA,cAJr9vB,mBAIq9vB,EAAA,OAJl8vB,QAAA,CAAA,MAAA,CAAA,SAIk8vB;AAAA,cAHr9vB,yBAGq9vB,EAAA,OAH57vB,QAAA,CAAA,MAAA,CAAA,MAG47vB;cAFr9vB,8BAAqB,QAAA,CAAA,QAAA,CAAA;cACrB,oCAA2B,QAAA,CAAA,QAAA,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"common_api.d.ts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;cAwCa;6GAmGmlrB,IAAA,QAAA,EAAA;;EAnGnlrB,GAAA,CAAA,gBAAA,uBAAmC,CAAA,OAAA,CAAA,EAAA,CAAA,CAAA,MAAA,GAAA,CAAA,gBAAA,QAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA;oHAmGowvB,IAAA,qBAAA,QAAA,EAAA;;;;;AAAptE,KA9FplrB,kBA8FolrB,CAAA,CAAA,CAAA,GA9F5jrB,cA8F4jrB,CA9F7irB,CA8F6irB,CAAA;AAAotE,cALvyvB,oBAKuyvB,EAAA,OALnxvB,QAAA,CAAA,OAKmxvB;AAAA,cAJvyvB,mBAIuyvB,EAAA,OAJpxvB,QAAA,CAAA,MAAA,CAAA,SAIoxvB;AAAA,cAHvyvB,yBAGuyvB,EAAA,OAH9wvB,QAAA,CAAA,MAAA,CAAA,MAG8wvB;cAFvyvB,8BAAqB,QAAA,CAAA,QAAA,CAAA;cACrB,oCAA2B,QAAA,CAAA,QAAA,CAAA"}
1
+ {"version":3,"file":"common_api.d.ts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;cAwCa;6GAmGiwrB,IAAA,QAAA,EAAA;;EAnGjwrB,GAAA,CAAA,gBAAA,uBAAmC,CAAA,OAAA,CAAA,EAAA,CAAA,CAAA,MAAA,GAAA,CAAA,gBAAA,QAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA;oHAmGk7vB,IAAA,qBAAA,QAAA,EAAA;;;;;AAAptE,KA9FlwrB,kBA8FkwrB,CAAA,CAAA,CAAA,GA9F1urB,cA8F0urB,CA9F3trB,CA8F2trB,CAAA;AAAotE,cALr9vB,oBAKq9vB,EAAA,OALj8vB,QAAA,CAAA,OAKi8vB;AAAA,cAJr9vB,mBAIq9vB,EAAA,OAJl8vB,QAAA,CAAA,MAAA,CAAA,SAIk8vB;AAAA,cAHr9vB,yBAGq9vB,EAAA,OAH57vB,QAAA,CAAA,MAAA,CAAA,MAG47vB;cAFr9vB,8BAAqB,QAAA,CAAA,QAAA,CAAA;cACrB,oCAA2B,QAAA,CAAA,QAAA,CAAA"}
@@ -187,6 +187,10 @@ type GenericCall<REQ, RES> = {
187
187
  inputSerde?: Serde<REQ>;
188
188
  outputSerde?: Serde<RES>;
189
189
  idempotencyKey?: string;
190
+ /**
191
+ * Observability name, recorded in the Restate journal.
192
+ */
193
+ name?: string;
190
194
  };
191
195
  /**
192
196
  * Send a message to an handler directly avoiding restate's type safety checks.
@@ -202,6 +206,10 @@ type GenericSend<REQ> = {
202
206
  inputSerde?: Serde<REQ>;
203
207
  delay?: Duration | number;
204
208
  idempotencyKey?: string;
209
+ /**
210
+ * Observability name, recorded in the Restate journal.
211
+ */
212
+ name?: string;
205
213
  };
206
214
  /**
207
215
  * The context that gives access to all Restate-backed operations, for example
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.cts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAoCA;;;;AAyCmC,UAzClB,OAAA,CAyCkB;EAAW;AAI9C;AACA;AAKA;EAA8C,SAAA,EAAA,EAAA,MAAA;EAYb;;;;EAEf,SAAA,OAAA,EAtDE,WAsDF,CAAA,MAAA,EAAA,MAAA,CAAA;EAAe;;;;;EACnB,SAAA,cAAA,EAhDa,WAgDb,CAAA,MAAA,EAAA,MAAA,GAAA,MAAA,EA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,eAAe,eAAe,SAAS,OAAO;;;;eAK7C,QAAQ;;UAGN,IAAA;;;;;;;;;;;;;;;KAiBL,oBAAoB,QAAQ;;;;;;;;oBAQpB,oBAAoB,eAAe;;;;;;;;;;;;;;;0BAgB7B,aAAa,kBAAkB,IAAI,eAAe;;;;;;KAOhE,YAAA;;;cAEC;;;;;0BAKa;;KAUd,gBAAA;yBAEa,QAAQ;;KAGrB,uBAAuB,eAAe,KAAK;cAE1C;;;;;;;;;;+BAUkB,mCACnB,IACP,uCAAuC,IAAI,QAAQ,EAAE;;;;;;;;;;gCAuB1B,mCACpB,IACP,eAAe,QAAQ;;;;;;;;;;;+BAsBG,mCACnB,IACP,eAAe,QAAQ;;;;;;;;;;sCAqBU,mCAC1B,IACP,uCACqB,IAAI,qBAAqB,QAAQ,EAAE;;;;;;;KAqBjD,oBAAoB,QAAQ;;;;UAI9B,QAAQ;;;;;kBAMA,IAAI;;;;;4BAMM;;;;SAKnB,eAAe;;UAGP,qCAAqC,aAAa,sBACzD,oBAAoB,SAAS;;;;;;;;;;;;;;;;;;;;;;;;mCAwBJ,MAAM,KAAK,eAAe;;UAG5C,+BAA+B,aAAa,sBAEzD,sBAAsB,SACtB,cAAc,SACd"}
package/dist/context.d.ts CHANGED
@@ -187,6 +187,10 @@ type GenericCall<REQ, RES> = {
187
187
  inputSerde?: Serde<REQ>;
188
188
  outputSerde?: Serde<RES>;
189
189
  idempotencyKey?: string;
190
+ /**
191
+ * Observability name, recorded in the Restate journal.
192
+ */
193
+ name?: string;
190
194
  };
191
195
  /**
192
196
  * Send a message to an handler directly avoiding restate's type safety checks.
@@ -202,6 +206,10 @@ type GenericSend<REQ> = {
202
206
  inputSerde?: Serde<REQ>;
203
207
  delay?: Duration | number;
204
208
  idempotencyKey?: string;
209
+ /**
210
+ * Observability name, recorded in the Restate journal.
211
+ */
212
+ name?: string;
205
213
  };
206
214
  /**
207
215
  * The context that gives access to all Restate-backed operations, for example
@@ -1 +1 @@
1
- {"version":3,"file":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ACtB,kBAAkB;oBAEH,kBAAkB,YAAY,OAAO;;;;;aAM5C;;;;;;uBAOU;;;;;;;0BAQG,sBAAsB,MAAM,KAAK,eAAe;;;;;;;;;;;;;;UAezD,6BAA6B,aAAa,sBACjD,SAAS,cAAc,SAAS;;;;;;;;;;;;;;UAezB,mCAAmC,aAAa,sBACvD,SAAS;;;;;;;;;;;;;iCAcc,uBACvB,eAAe,wBAAwB,cACrC,MAAM,eAAe,eAAe,SAAS,OAAO,SAC3D,SAAS,eAAe,eAAe,SAAS,OAAO;;;;eAK7C,QAAQ;;UAGN,IAAA;;;;;;;;;;;;;;;KAiBL,oBAAoB,QAAQ;;;;;;;;oBAQpB,oBAAoB,eAAe;;;;;;;;;;;;;;;0BAgB7B,aAAa,kBAAkB,IAAI,eAAe;;;;;;KAOhE,YAAA;;;cAEC;;;;;0BAKa;;KAUd,gBAAA;yBAEa,QAAQ;;KAGrB,uBAAuB,eAAe,KAAK;cAE1C;;;;;;;;;;+BAUkB,mCACnB,IACP,uCAAuC,IAAI,QAAQ,EAAE;;;;;;;;;;gCAuB1B,mCACpB,IACP,eAAe,QAAQ;;;;;;;;;;;+BAsBG,mCACnB,IACP,eAAe,QAAQ;;;;;;;;;;sCAqBU,mCAC1B,IACP,uCACqB,IAAI,qBAAqB,QAAQ,EAAE;;;;;;;KAqBjD,oBAAoB,QAAQ;;;;UAI9B,QAAQ;;;;;kBAMA,IAAI;;;;;4BAMM;;;;SAKnB,eAAe;;UAGP,qCAAqC,aAAa,sBACzD,oBAAoB,SAAS;;;;;;;;;;;;;;;;;;;;;;;;mCAwBJ,MAAM,KAAK,eAAe;;UAG5C,+BAA+B,aAAa,sBAEzD,sBAAsB,SACtB,cAAc,SACd"}
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport type { Client, SendClient } from \"./types/rpc.js\";\nimport type {\n RestateContext,\n RestateObjectContext,\n RestateObjectSharedContext,\n RestateWorkflowContext,\n RestateWorkflowSharedContext,\n Service,\n ServiceDefinitionFrom,\n VirtualObject,\n VirtualObjectDefinitionFrom,\n Workflow,\n WorkflowDefinitionFrom,\n Serde,\n Duration,\n} from \"@restatedev/restate-sdk-core\";\nimport { ContextImpl } from \"./context_impl.js\";\nimport type { TerminalError } from \"./types/errors.js\";\n\n/**\n * Represents the original request as sent to this handler.\n *\n * A request object includes the request headers, and the raw unparsed\n * request body.\n */\nexport interface Request {\n /**\n * The unique id that identifies the current function invocation. This id is guaranteed to be\n * unique across invocations, but constant across reties and suspensions.\n */\n readonly id: string;\n\n /**\n * Request headers - the following headers capture the original invocation headers, as provided to\n * the ingress.\n */\n readonly headers: ReadonlyMap<string, string>;\n\n /**\n * Attempt headers - the following headers are sent by the restate runtime.\n * These headers are attempt specific, generated by the restate runtime uniquely for each attempt.\n * These headers might contain information such as the W3C trace context, and attempt specific information.\n */\n readonly attemptHeaders: ReadonlyMap<string, string | string[] | undefined>;\n\n /**\n * Raw unparsed request body\n */\n readonly body: Uint8Array;\n\n /**\n * Extra arguments provided to the request handler:\n * Lambda: [Context]\n * Cloudflare workers: [Env, ExecutionContext]\n * Deno: [ConnInfo]\n * Bun: [Server]\n * These arguments can contain request-specific values that could change after a suspension.\n * Care should be taken to use them deterministically.\n */\n readonly extraArgs: unknown[];\n\n /**\n * This is a signal that is aborted when the current attempt has been completed either successful or unsuccessfully.\n * When the signal is aborted, the current attempt has been completed and the handler should not perform any more work, other\n * than cleanup any external resources that might be shared across attempts (e.g. database connections).\n */\n readonly attemptCompletedSignal: AbortSignal;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type TypedState = Record<string, any>;\nexport type UntypedState = { _: never };\n\n/**\n * Key value store operations. Only keyed services have an attached key-value store.\n */\nexport interface KeyValueStore<TState extends TypedState> {\n /**\n * Get/retrieve state from the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to retrieve\n * @returns a Promise that is resolved with the value of the state key\n *\n * @example\n * const state = await ctx.get<string>(\"STATE\");\n */\n get<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;\n\n stateKeys(): Promise<Array<string>>;\n\n /**\n * Set/store state in the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to set\n * @param value value to set\n *\n * @example\n * ctx.set(\"STATE\", \"Hello\");\n */\n set<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n value: TState extends UntypedState ? TValue : TState[TKey],\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): void;\n\n /**\n * Clear/delete state in the Restate runtime.\n * @param name key of the state to delete\n *\n * @example\n * ctx.clear(\"STATE\");\n */\n clear<TKey extends keyof TState>(\n name: TState extends UntypedState ? string : TKey\n ): void;\n\n /**\n * Clear/delete all the state entries in the Restate runtime.\n *\n * @example\n * ctx.clearAll();\n */\n clearAll(): void;\n}\n\n/**\n * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead\n */\nexport interface SendOptions {\n /**\n * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead\n */\n delay?: number;\n}\n\nexport interface ContextDate {\n /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).\n * This is equivalent to Date.now()\n */\n now(): Promise<number>;\n /** Returns the JSON representation of the current date.\n * This is equivalent to new Date().toJSON()\n **/\n toJSON(): Promise<string>;\n}\n\n/**\n * A function that can be run and its result durably persisted by Restate.\n */\nexport type RunAction<T> = (() => Promise<T>) | (() => T);\n\nexport type RunOptions<T> = {\n serde?: Serde<T>;\n\n /**\n * Max number of attempts (including the initial), before giving up.\n *\n * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.\n */\n maxRetryAttempts?: number;\n\n /**\n * @deprecated Use `maxRetryDuration` instead.\n */\n maxRetryDurationMillis?: number;\n\n /**\n * Max duration of retries, before giving up.\n *\n * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxRetryDuration?: Duration | number;\n\n /**\n * @deprecated Use `initialRetryInterval` instead.\n */\n initialRetryIntervalMillis?: number;\n\n /**\n * Initial interval for the first retry attempt.\n * Retry interval will grow by a factor specified in `retryIntervalFactor`.\n *\n * The default is 50 milliseconds.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n initialRetryInterval?: Duration | number;\n\n /**\n * @deprecated Use `maxRetryInterval` instead.\n */\n maxRetryIntervalMillis?: number;\n\n /**\n * Max interval between retries.\n * Retry interval will grow by a factor specified in `retryIntervalFactor`.\n *\n * The default is 10 seconds.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxRetryInterval?: Duration | number;\n\n /**\n * Exponentiation factor to use when computing the next retry delay.\n *\n * The default value is `2`, meaning retry interval will double at each attempt.\n */\n retryIntervalFactor?: number;\n};\n\n/**\n * Call a handler directly avoiding restate's type safety checks.\n * This is a generic mechanism to invoke handlers directly by only knowing\n * the service and handler name, (or key in the case of objects or workflows)\n */\nexport type GenericCall<REQ, RES> = {\n service: string;\n method: string;\n parameter: REQ;\n key?: string;\n headers?: Record<string, string>;\n inputSerde?: Serde<REQ>;\n outputSerde?: Serde<RES>;\n idempotencyKey?: string;\n};\n\n/**\n * Send a message to an handler directly avoiding restate's type safety checks.\n * This is a generic mechanism to invoke handlers directly by only knowing\n * the service and handler name, (or key in the case of objects or workflows)\n */\nexport type GenericSend<REQ> = {\n service: string;\n method: string;\n parameter: REQ;\n key?: string;\n headers?: Record<string, string>;\n inputSerde?: Serde<REQ>;\n delay?: Duration | number;\n idempotencyKey?: string;\n};\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * Virtual objects can also access their key-value store using the {@link ObjectContext}.\n *\n */\nexport interface Context extends RestateContext {\n /**\n * Deterministic random methods; these are inherently predictable (seeded on the invocation ID, which is not secret)\n * and so should not be used for any cryptographic purposes. They are useful for identifiers, idempotency keys,\n * and for uniform sampling from a set of options. If a cryptographically secure value is needed, please generate that\n * externally and capture the result with a side effect.\n *\n * Calls to these methods from inside `ctx.run` are disallowed and will fail - side effects must be idempotent, and\n * these calls are not.\n */\n rand: Rand;\n\n /**\n * Console to use for logging. It attaches to each log message some contextual information,\n * such as invoked service method and invocation id, and automatically excludes logs during replay.\n */\n console: Console;\n\n /**\n * Deterministic date.\n */\n date: ContextDate;\n\n /**\n * Run an operation and store the result in Restate. The operation will thus not\n * be re-run during a later replay, but take the durable result from Restate.\n *\n * This let you capture potentially non-deterministic computation and interaction\n * with external systems in a safe way.\n *\n * Failure semantics are:\n * - If an operation has run and persisted before, the result (value or Error) will be\n * taken from the Restate journal.\n * - There is a small window where an action may be re-run, if a failure\n * occurred between a successful run and persisting the result.\n * - No second action will be run while a previous run's result is not\n * yet durable. That way, effects that build on top of each other can assume\n * deterministic results from previous runs, and at most one run will be\n * re-executed on replay (the latest, if the failure happened in the small windows\n * described above).\n *\n * You can customize retry options by either:\n *\n * - Providing retry policy options in {@link RunOptions}\n * - Throwing {@link RetryableError}, providing `retryAfter` option. This can be especially useful when interacting with HTTP requests returning the `Retry-After` header. You can combine the usage of throwing {@link RetryableError} with the `maxRetryAttempts`/`maxRetryDuration` from {@link RunOptions}.\n *\n * @example Run some external action and persist its result\n * ```ts\n * const result = await ctx.run(someExternalAction)\n *```\n * @example Add some retry options\n * ```ts\n * const result = await ctx.run(\"my action\", someExternalAction, { maxRetryAttempts: 10 })\n * ```\n * @example Terminal errors and retryable errors\n * ```ts\n * await ctx.run(\"payment action\", async () => {\n * const result = await paymentProvider.charge(txId, paymentInfo);\n * if (result.paymentRejected) {\n * // this action will not be retried anymore\n * throw new TerminalError(\"Payment failed\");\n * } else if (result.paymentGatewayBusy) {\n * // restate will retry automatically\n * // to bound retries, use RunOptions\n * throw new Error(\"Payment gateway busy\");\n * } else {\n * // success!\n * }\n * });\n * ```\n * @example Retryable error with custom retry delay\n * ```ts\n * await ctx.run(\"payment action\", async () => {\n * const res = fetch(...);\n * if (!res.ok) {\n * // Read Retry-After header\n * const retryAfterHeader = res.headers['Retry-After']\n *\n * // Use RetryableError to customize in how long to retry\n * throw RetryableError.from(cause, { retryAfter: { seconds: retryAfterHeader } })\n * }\n * }, {\n * // Retry at most ten times\n * maxRetryAttempts: 10\n * });\n * ```\n *\n * @param action The function to run.\n */\n run<T>(action: RunAction<T>): RestatePromise<T>;\n\n /**\n * Same as {@link run}, but providing a name, used for observability purposes.\n */\n run<T>(name: string, action: RunAction<T>): RestatePromise<T>;\n\n /**\n * See {@link run}\n */\n run<T>(\n name: string,\n action: RunAction<T>,\n options: RunOptions<T>\n ): RestatePromise<T>;\n\n /**\n * Register an awakeable and pause the processing until the awakeable ID (and optional payload) have been returned to the service\n * (via ctx.completeAwakeable(...)). The SDK deserializes the payload with `JSON.parse(result.toString()) as T`.\n * @returns\n * - id: the string ID that has to be used to complete the awakaeble by some external service\n * - promise: the Promise that needs to be awaited and that is resolved with the payload that was supplied by the service which completed the awakeable\n * @example Retryable errors and terminal errors\n * const awakeable = ctx.awakeable<string>();\n *\n * // send the awakeable ID to some external service that will wake this one back up\n * // The ID can be retrieved by:\n * const id = awakeable.id;\n *\n * // ... send to external service ...\n *\n * // Wait for the external service to wake this service back up\n * const result = await awakeable.promise;\n */\n awakeable<T>(serde?: Serde<T>): {\n id: string;\n promise: RestatePromise<T>;\n };\n\n /**\n * Resolve an awakeable.\n * @param id the string ID of the awakeable.\n * This is supplied by the service that needs to be woken up.\n * @param payload the payload to pass to the service that is woken up.\n * The SDK serializes the payload with `Buffer.from(JSON.stringify(payload))`\n * and deserializes it in the receiving service with `JSON.parse(result.toString()) as T`.\n * @example Retryable error with custom retry delay\n * // The sleeping service should have sent the awakeableIdentifier string to this service.\n * ctx.resolveAwakeable(awakeableIdentifier, \"hello\");\n */\n resolveAwakeable<T>(id: string, payload?: T, serde?: Serde<T>): void;\n\n /**\n * Reject an awakeable. When rejecting, the service waiting on this awakeable will be woken up with a terminal error with the provided reason.\n * @param id the string ID of the awakeable.\n * This is supplied by the service that needs to be woken up.\n * @param reason the reason of the rejection.\n *\n * @example\n * // The sleeping service should have sent the awakeableIdentifier string to this service.\n * ctx.rejectAwakeable(awakeableIdentifier, \"super bad error\");\n */\n rejectAwakeable(id: string, reason: string): void;\n\n /**\n * Sleep until a timeout has passed.\n * @param duration either Duration type or milliseconds.\n * @param name Observability name. This will be shown in the UI.\n * This is a lower-bound.\n *\n * @example\n * await ctx.sleep(1000);\n */\n sleep(duration: Duration | number, name?: string): RestatePromise<void>;\n\n /**\n * Makes a type-safe request/response RPC to the specified target service.\n *\n * The RPC goes through Restate and is guaranteed to be reliably delivered. The RPC is also\n * journaled for durable execution and will thus not be duplicated when the handler is re-invoked\n * for retries or after suspending.\n *\n * This call will return the result produced by the target handler, or the Error, if the target\n * handler finishes with a Terminal Error.\n *\n * This call is a suspension point: The handler might suspend while awaiting the response and\n * resume once the response is available.\n *\n * @example\n * *Service Side:*\n * ```ts\n * const service = restate.service(\n * name: \"myservice\",\n * handlers: {\n * someAction: async(ctx: restate.Context, req: string) => { ... },\n * anotherAction: async(ctx: restate.Context, count: number) => { ... }\n * });\n *\n * // option 1: export only the type signature\n * export type Service = typeof service;\n *\n *\n * restate.serve({ services: [service], port: 9080 });\n * ```\n * *Client side:*\n * ```ts\n * // option 1: use only types and supply service name separately\n * const result1 = await ctx.serviceClient<Service>({name: \"myservice\"}).someAction(\"hello!\");\n *\n * // option 2: use full API spec\n * type MyService: Service = { name: \"myservice\" };\n * const result2 = await ctx.serviceClient(Service).anotherAction(1337);\n * ```\n */\n serviceClient<D>(opts: ServiceDefinitionFrom<D>): Client<Service<D>>;\n\n /**\n * Same as {@link serviceClient} but for virtual objects.\n *\n * @param opts\n * @param key the virtual object key\n */\n objectClient<D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ): Client<VirtualObject<D>>;\n\n /**\n * Same as {@link serviceClient} but for workflows.\n *\n * @param opts\n * @param key the workflow key\n */\n workflowClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): Client<Workflow<D>>;\n\n /**\n * Same as {@link objectSendClient} but for workflows.\n *\n * @param opts\n * @param key the workflow key\n */\n workflowSendClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): SendClient<Workflow<D>>;\n\n /**\n * Makes a type-safe one-way RPC to the specified target service. This method effectively behaves\n * like enqueuing the message in a message queue.\n *\n * The message goes through Restate and is guaranteed to be reliably delivered. The RPC is also\n * journaled for durable execution and will thus not be duplicated when the handler is re-invoked\n * for retries or after suspending.\n *\n * This call will return immediately; the message sending happens asynchronously in the background.\n * Despite that, the message is guaranteed to be sent, because the completion of the invocation that\n * triggers the send (calls this function) happens logically after the sending. That means that any\n * failure where the message does not reach Restate also cannot complete this invocation, and will\n * hence recover this handler and (through the durable execution) recover the message to be sent.\n *\n * @example\n * *Service Side:*\n * ```ts\n * const service = restate.service(\n * name: \"myservice\",\n * handlers: {\n * someAction: async(ctx: restate.Context, req: string) => { ... },\n * anotherAction: async(ctx: restate.Context, count: number) => { ... }\n * });\n *\n * // option 1: export only the type signature of the router\n * export type MyApi = typeof service;\n *\n * // option 2: export the API definition with type and name (name)\n * const MyService: MyApi = { name: \"myservice\" };\n *\n * restate.serve({ services: [service], port: 9080 });\n * ```\n * *Client side:*\n * ```ts\n * // option 1: use only types and supply service name separately\n * ctx.serviceSendClient<MyApi>({name: \"myservice\"}).someAction(\"hello!\");\n *\n * // option 2: use full API spec\n * ctx.serviceSendClient(MyService).anotherAction(1337);\n * ```\n */\n serviceSendClient<D>(\n service: ServiceDefinitionFrom<D>,\n opts?: SendOptions\n ): SendClient<Service<D>>;\n\n /**\n * Same as {@link serviceSendClient} but for virtual objects.\n *\n * @param obj\n * @param key the virtual object key\n * @param opts Send options\n */\n objectSendClient<D>(\n obj: VirtualObjectDefinitionFrom<D>,\n key: string,\n opts?: SendOptions\n ): SendClient<VirtualObject<D>>;\n\n genericCall<REQ = Uint8Array, RES = Uint8Array>(\n call: GenericCall<REQ, RES>\n ): InvocationPromise<RES>;\n\n genericSend<REQ = Uint8Array>(call: GenericSend<REQ>): InvocationHandle;\n\n /**\n * Returns the raw request that triggered that handler.\n * Use that object to inspect the original request headers\n */\n request(): Request;\n\n /**\n * Cancel an invocation\n *\n * @param invocationId the invocation id to cancel\n */\n cancel(invocationId: InvocationId): void;\n\n /**\n * Attach to an invocation\n *\n * @param invocationId the invocation id to attach to\n * @param serde the serde to use for the result, default to JSON serde.\n */\n attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T>;\n}\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - access/update state\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * This context can be used only within virtual objects.\n *\n */\nexport interface ObjectContext<TState extends TypedState = UntypedState>\n extends Context, KeyValueStore<TState>, RestateObjectContext {\n key: string;\n}\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * This context can be used only within a shared virtual objects.\n *\n */\nexport interface ObjectSharedContext<TState extends TypedState = UntypedState>\n extends Context, RestateObjectSharedContext {\n key: string;\n\n /**\n * Get/retrieve state from the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to retrieve\n * @returns a Promise that is resolved with the value of the state key\n *\n * @example\n * const state = await ctx.get<string>(\"STATE\");\n */\n get<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;\n\n /**\n * Retrieve all the state keys for this object.\n */\n stateKeys(): Promise<Array<string>>;\n}\n\nexport interface Rand {\n /**\n * Equivalent of JS `Math.random()` but deterministic; seeded by the invocation ID of the current invocation,\n * each call will return a new pseudorandom float within the range [0,1)\n */\n random(): number;\n\n /**\n * Using the same random source and seed as random(), produce a UUID version 4 string. This is inherently predictable\n * based on the invocation ID and should not be used in cryptographic contexts\n */\n uuidv4(): string;\n}\n\n/**\n * A promise that can be combined using Promise combinators in RestateContext.\n */\nexport type RestatePromise<T> = Promise<T> & {\n /**\n * Creates a promise that awaits for the current promise up to the specified timeout duration.\n * If the timeout is fired, this Promise will be rejected with a {@link TimeoutError}.\n *\n * @param millis duration of the sleep in millis.\n * This is a lower-bound.\n */\n orTimeout(millis: Duration | number): RestatePromise<T>;\n\n /**\n * Creates a new {@link RestatePromise} that maps the result of this promise with\n * the provided `mapper`, once this promise is fulfilled.\n *\n * **NOTE**: You **MUST** use this API when you need to map the result of a\n * {@link RestatePromise} without `await`ing it, rather than using {@link Promise.then}.\n * {@link Promise.then} is used by Restate to distinguish when awaiting an asynchronous operation,\n * thus calling `.then` on several Restate promises can lead to concurrency issues.\n *\n * @param mapper the function to execute when this promise is fulfilled.\n * If the promise completed successfully, `value` is provided as input, otherwise `failure` is provided as input.\n * If this mapper returns a value, this value will be used to resolve the returned {@link RestatePromise}.\n * If the mapper throws a {@link TerminalError}, this error will be used to reject the returned {@link RestatePromise}.\n */\n map<U>(mapper: (value?: T, failure?: TerminalError) => U): RestatePromise<U>;\n};\n\n/**\n * Represents an invocation id.\n * @see {@link InvocationIdParser}\n */\nexport type InvocationId = string & { __brand: \"InvocationId\" };\n\nexport const InvocationIdParser = {\n /**\n * Creates an invocation id from a string.\n * @param id the string to use as invocation id.\n */\n fromString(id: string): InvocationId {\n if (!id.startsWith(\"inv\")) {\n throw new Error(\n `Expected invocation id to start with 'inv' but got ${id}`\n );\n }\n return id as InvocationId;\n },\n};\n\nexport type InvocationHandle = {\n // The invocation id of the call\n readonly invocationId: Promise<InvocationId>;\n};\n\nexport type InvocationPromise<T> = RestatePromise<T> & InvocationHandle;\n\nexport const RestatePromise = {\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n *\n * See {@link Promise.all} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n all<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<{ -readonly [P in keyof T]: Awaited<T[P]> }> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.all(p),\n values\n ) as RestatePromise<{\n -readonly [P in keyof T]: Awaited<T[P]>;\n }>;\n },\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n *\n * See {@link Promise.race} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n race<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<Awaited<T[number]>> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.race(p),\n values\n ) as RestatePromise<Awaited<T[number]>>;\n },\n\n /**\n * Creates a promise that fulfills when any of the input's promises fulfills, with this first fulfillment value.\n * It rejects when all the input's promises reject (including when an empty iterable is passed),\n * with an AggregateError containing an array of rejection reasons.\n *\n * See {@link Promise.any} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n any<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<Awaited<T[number]>> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.any(p),\n values\n ) as RestatePromise<Awaited<T[number]>>;\n },\n\n /**\n * Creates a promise that fulfills when all the input's promises settle (including when an empty iterable is passed),\n * with an array of objects that describe the outcome of each promise.\n *\n * See {@link Promise.allSettled} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n allSettled<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<{\n -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;\n }> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.allSettled(p),\n values\n ) as RestatePromise<{\n -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;\n }>;\n },\n};\n\n/**\n * Workflow bound durable promise\n *\n * See {@link WorkflowSharedContext} promise..\n */\nexport type DurablePromise<T> = Promise<T> & {\n /**\n * Returns the value of the promise, if it has been resolved.\n */\n peek(): Promise<T | undefined>;\n\n /**\n * Resolve the promise with the given value.\n * @param value the value to resolve the promise with\n */\n resolve(value?: T): Promise<void>;\n\n /**\n * Reject the promise with the given error message.\n * @param errorMsg the error message to use for rejection.\n */\n reject(errorMsg: string): Promise<void>;\n\n /**\n * Obtain a {@link RestatePromise} variant of this promise.\n */\n get(): RestatePromise<T>;\n};\n\nexport interface WorkflowSharedContext<TState extends TypedState = UntypedState>\n extends ObjectSharedContext<TState>, RestateWorkflowSharedContext {\n /**\n * Create a durable promise that can be resolved or rejected during the workflow execution.\n * The promise is bound to the workflow and will be persisted across suspensions and retries.\n * @example Add some retry options\n * ```ts\n * const wf = restate.workflow({\n * name: \"myWorkflow\",\n * handlers: {\n * run: async (ctx: restate.WorkflowContext) => {\n * // ... do some work ...\n * const payment = await ctx.promise<Payment>(\"payment.succeeded\");\n * // ... do some more work ...\n * },\n *\n * onPaymentSucceeded: async (ctx: restate.WorkflowContext, payment) => {\n * // ... handle payment succeeded ...\n * await ctx.promise(\"payment.succeeded\").resolve(payment);\n * }\n * });\n * ```\n *\n * @param name the name of the durable promise\n */\n promise<T>(name: string, serde?: Serde<T>): DurablePromise<T>;\n}\n\nexport interface WorkflowContext<TState extends TypedState = UntypedState>\n extends\n WorkflowSharedContext<TState>,\n ObjectContext<TState>,\n RestateWorkflowContext {}\n"],"mappings":";;;AA+rBA,MAAa,qBAAqB,EAKhC,WAAW,IAA0B;AACnC,KAAI,CAAC,GAAG,WAAW,MAAM,CACvB,OAAM,IAAI,MACR,sDAAsD,KACvD;AAEH,QAAO;GAEV;AASD,MAAa,iBAAiB;CAU5B,IACE,QAC6D;AAC7D,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAcH,KACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,KAAK,EAAE,EACtB,OACD;;CAaH,IACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAYH,WACE,QAGC;AACD,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,WAAW,EAAE,EAC5B,OACD;;CAIJ"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport type { Client, SendClient } from \"./types/rpc.js\";\nimport type {\n RestateContext,\n RestateObjectContext,\n RestateObjectSharedContext,\n RestateWorkflowContext,\n RestateWorkflowSharedContext,\n Service,\n ServiceDefinitionFrom,\n VirtualObject,\n VirtualObjectDefinitionFrom,\n Workflow,\n WorkflowDefinitionFrom,\n Serde,\n Duration,\n} from \"@restatedev/restate-sdk-core\";\nimport { ContextImpl } from \"./context_impl.js\";\nimport type { TerminalError } from \"./types/errors.js\";\n\n/**\n * Represents the original request as sent to this handler.\n *\n * A request object includes the request headers, and the raw unparsed\n * request body.\n */\nexport interface Request {\n /**\n * The unique id that identifies the current function invocation. This id is guaranteed to be\n * unique across invocations, but constant across reties and suspensions.\n */\n readonly id: string;\n\n /**\n * Request headers - the following headers capture the original invocation headers, as provided to\n * the ingress.\n */\n readonly headers: ReadonlyMap<string, string>;\n\n /**\n * Attempt headers - the following headers are sent by the restate runtime.\n * These headers are attempt specific, generated by the restate runtime uniquely for each attempt.\n * These headers might contain information such as the W3C trace context, and attempt specific information.\n */\n readonly attemptHeaders: ReadonlyMap<string, string | string[] | undefined>;\n\n /**\n * Raw unparsed request body\n */\n readonly body: Uint8Array;\n\n /**\n * Extra arguments provided to the request handler:\n * Lambda: [Context]\n * Cloudflare workers: [Env, ExecutionContext]\n * Deno: [ConnInfo]\n * Bun: [Server]\n * These arguments can contain request-specific values that could change after a suspension.\n * Care should be taken to use them deterministically.\n */\n readonly extraArgs: unknown[];\n\n /**\n * This is a signal that is aborted when the current attempt has been completed either successful or unsuccessfully.\n * When the signal is aborted, the current attempt has been completed and the handler should not perform any more work, other\n * than cleanup any external resources that might be shared across attempts (e.g. database connections).\n */\n readonly attemptCompletedSignal: AbortSignal;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type TypedState = Record<string, any>;\nexport type UntypedState = { _: never };\n\n/**\n * Key value store operations. Only keyed services have an attached key-value store.\n */\nexport interface KeyValueStore<TState extends TypedState> {\n /**\n * Get/retrieve state from the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to retrieve\n * @returns a Promise that is resolved with the value of the state key\n *\n * @example\n * const state = await ctx.get<string>(\"STATE\");\n */\n get<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;\n\n stateKeys(): Promise<Array<string>>;\n\n /**\n * Set/store state in the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to set\n * @param value value to set\n *\n * @example\n * ctx.set(\"STATE\", \"Hello\");\n */\n set<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n value: TState extends UntypedState ? TValue : TState[TKey],\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): void;\n\n /**\n * Clear/delete state in the Restate runtime.\n * @param name key of the state to delete\n *\n * @example\n * ctx.clear(\"STATE\");\n */\n clear<TKey extends keyof TState>(\n name: TState extends UntypedState ? string : TKey\n ): void;\n\n /**\n * Clear/delete all the state entries in the Restate runtime.\n *\n * @example\n * ctx.clearAll();\n */\n clearAll(): void;\n}\n\n/**\n * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead\n */\nexport interface SendOptions {\n /**\n * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead\n */\n delay?: number;\n}\n\nexport interface ContextDate {\n /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).\n * This is equivalent to Date.now()\n */\n now(): Promise<number>;\n /** Returns the JSON representation of the current date.\n * This is equivalent to new Date().toJSON()\n **/\n toJSON(): Promise<string>;\n}\n\n/**\n * A function that can be run and its result durably persisted by Restate.\n */\nexport type RunAction<T> = (() => Promise<T>) | (() => T);\n\nexport type RunOptions<T> = {\n serde?: Serde<T>;\n\n /**\n * Max number of attempts (including the initial), before giving up.\n *\n * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.\n */\n maxRetryAttempts?: number;\n\n /**\n * @deprecated Use `maxRetryDuration` instead.\n */\n maxRetryDurationMillis?: number;\n\n /**\n * Max duration of retries, before giving up.\n *\n * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxRetryDuration?: Duration | number;\n\n /**\n * @deprecated Use `initialRetryInterval` instead.\n */\n initialRetryIntervalMillis?: number;\n\n /**\n * Initial interval for the first retry attempt.\n * Retry interval will grow by a factor specified in `retryIntervalFactor`.\n *\n * The default is 50 milliseconds.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n initialRetryInterval?: Duration | number;\n\n /**\n * @deprecated Use `maxRetryInterval` instead.\n */\n maxRetryIntervalMillis?: number;\n\n /**\n * Max interval between retries.\n * Retry interval will grow by a factor specified in `retryIntervalFactor`.\n *\n * The default is 10 seconds.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxRetryInterval?: Duration | number;\n\n /**\n * Exponentiation factor to use when computing the next retry delay.\n *\n * The default value is `2`, meaning retry interval will double at each attempt.\n */\n retryIntervalFactor?: number;\n};\n\n/**\n * Call a handler directly avoiding restate's type safety checks.\n * This is a generic mechanism to invoke handlers directly by only knowing\n * the service and handler name, (or key in the case of objects or workflows)\n */\nexport type GenericCall<REQ, RES> = {\n service: string;\n method: string;\n parameter: REQ;\n key?: string;\n headers?: Record<string, string>;\n inputSerde?: Serde<REQ>;\n outputSerde?: Serde<RES>;\n idempotencyKey?: string;\n /**\n * Observability name, recorded in the Restate journal.\n */\n name?: string;\n};\n\n/**\n * Send a message to an handler directly avoiding restate's type safety checks.\n * This is a generic mechanism to invoke handlers directly by only knowing\n * the service and handler name, (or key in the case of objects or workflows)\n */\nexport type GenericSend<REQ> = {\n service: string;\n method: string;\n parameter: REQ;\n key?: string;\n headers?: Record<string, string>;\n inputSerde?: Serde<REQ>;\n delay?: Duration | number;\n idempotencyKey?: string;\n /**\n * Observability name, recorded in the Restate journal.\n */\n name?: string;\n};\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * Virtual objects can also access their key-value store using the {@link ObjectContext}.\n *\n */\nexport interface Context extends RestateContext {\n /**\n * Deterministic random methods; these are inherently predictable (seeded on the invocation ID, which is not secret)\n * and so should not be used for any cryptographic purposes. They are useful for identifiers, idempotency keys,\n * and for uniform sampling from a set of options. If a cryptographically secure value is needed, please generate that\n * externally and capture the result with a side effect.\n *\n * Calls to these methods from inside `ctx.run` are disallowed and will fail - side effects must be idempotent, and\n * these calls are not.\n */\n rand: Rand;\n\n /**\n * Console to use for logging. It attaches to each log message some contextual information,\n * such as invoked service method and invocation id, and automatically excludes logs during replay.\n */\n console: Console;\n\n /**\n * Deterministic date.\n */\n date: ContextDate;\n\n /**\n * Run an operation and store the result in Restate. The operation will thus not\n * be re-run during a later replay, but take the durable result from Restate.\n *\n * This let you capture potentially non-deterministic computation and interaction\n * with external systems in a safe way.\n *\n * Failure semantics are:\n * - If an operation has run and persisted before, the result (value or Error) will be\n * taken from the Restate journal.\n * - There is a small window where an action may be re-run, if a failure\n * occurred between a successful run and persisting the result.\n * - No second action will be run while a previous run's result is not\n * yet durable. That way, effects that build on top of each other can assume\n * deterministic results from previous runs, and at most one run will be\n * re-executed on replay (the latest, if the failure happened in the small windows\n * described above).\n *\n * You can customize retry options by either:\n *\n * - Providing retry policy options in {@link RunOptions}\n * - Throwing {@link RetryableError}, providing `retryAfter` option. This can be especially useful when interacting with HTTP requests returning the `Retry-After` header. You can combine the usage of throwing {@link RetryableError} with the `maxRetryAttempts`/`maxRetryDuration` from {@link RunOptions}.\n *\n * @example Run some external action and persist its result\n * ```ts\n * const result = await ctx.run(someExternalAction)\n *```\n * @example Add some retry options\n * ```ts\n * const result = await ctx.run(\"my action\", someExternalAction, { maxRetryAttempts: 10 })\n * ```\n * @example Terminal errors and retryable errors\n * ```ts\n * await ctx.run(\"payment action\", async () => {\n * const result = await paymentProvider.charge(txId, paymentInfo);\n * if (result.paymentRejected) {\n * // this action will not be retried anymore\n * throw new TerminalError(\"Payment failed\");\n * } else if (result.paymentGatewayBusy) {\n * // restate will retry automatically\n * // to bound retries, use RunOptions\n * throw new Error(\"Payment gateway busy\");\n * } else {\n * // success!\n * }\n * });\n * ```\n * @example Retryable error with custom retry delay\n * ```ts\n * await ctx.run(\"payment action\", async () => {\n * const res = fetch(...);\n * if (!res.ok) {\n * // Read Retry-After header\n * const retryAfterHeader = res.headers['Retry-After']\n *\n * // Use RetryableError to customize in how long to retry\n * throw RetryableError.from(cause, { retryAfter: { seconds: retryAfterHeader } })\n * }\n * }, {\n * // Retry at most ten times\n * maxRetryAttempts: 10\n * });\n * ```\n *\n * @param action The function to run.\n */\n run<T>(action: RunAction<T>): RestatePromise<T>;\n\n /**\n * Same as {@link run}, but providing a name, used for observability purposes.\n */\n run<T>(name: string, action: RunAction<T>): RestatePromise<T>;\n\n /**\n * See {@link run}\n */\n run<T>(\n name: string,\n action: RunAction<T>,\n options: RunOptions<T>\n ): RestatePromise<T>;\n\n /**\n * Register an awakeable and pause the processing until the awakeable ID (and optional payload) have been returned to the service\n * (via ctx.completeAwakeable(...)). The SDK deserializes the payload with `JSON.parse(result.toString()) as T`.\n * @returns\n * - id: the string ID that has to be used to complete the awakaeble by some external service\n * - promise: the Promise that needs to be awaited and that is resolved with the payload that was supplied by the service which completed the awakeable\n * @example Retryable errors and terminal errors\n * const awakeable = ctx.awakeable<string>();\n *\n * // send the awakeable ID to some external service that will wake this one back up\n * // The ID can be retrieved by:\n * const id = awakeable.id;\n *\n * // ... send to external service ...\n *\n * // Wait for the external service to wake this service back up\n * const result = await awakeable.promise;\n */\n awakeable<T>(serde?: Serde<T>): {\n id: string;\n promise: RestatePromise<T>;\n };\n\n /**\n * Resolve an awakeable.\n * @param id the string ID of the awakeable.\n * This is supplied by the service that needs to be woken up.\n * @param payload the payload to pass to the service that is woken up.\n * The SDK serializes the payload with `Buffer.from(JSON.stringify(payload))`\n * and deserializes it in the receiving service with `JSON.parse(result.toString()) as T`.\n * @example Retryable error with custom retry delay\n * // The sleeping service should have sent the awakeableIdentifier string to this service.\n * ctx.resolveAwakeable(awakeableIdentifier, \"hello\");\n */\n resolveAwakeable<T>(id: string, payload?: T, serde?: Serde<T>): void;\n\n /**\n * Reject an awakeable. When rejecting, the service waiting on this awakeable will be woken up with a terminal error with the provided reason.\n * @param id the string ID of the awakeable.\n * This is supplied by the service that needs to be woken up.\n * @param reason the reason of the rejection.\n *\n * @example\n * // The sleeping service should have sent the awakeableIdentifier string to this service.\n * ctx.rejectAwakeable(awakeableIdentifier, \"super bad error\");\n */\n rejectAwakeable(id: string, reason: string): void;\n\n /**\n * Sleep until a timeout has passed.\n * @param duration either Duration type or milliseconds.\n * @param name Observability name. This will be shown in the UI.\n * This is a lower-bound.\n *\n * @example\n * await ctx.sleep(1000);\n */\n sleep(duration: Duration | number, name?: string): RestatePromise<void>;\n\n /**\n * Makes a type-safe request/response RPC to the specified target service.\n *\n * The RPC goes through Restate and is guaranteed to be reliably delivered. The RPC is also\n * journaled for durable execution and will thus not be duplicated when the handler is re-invoked\n * for retries or after suspending.\n *\n * This call will return the result produced by the target handler, or the Error, if the target\n * handler finishes with a Terminal Error.\n *\n * This call is a suspension point: The handler might suspend while awaiting the response and\n * resume once the response is available.\n *\n * @example\n * *Service Side:*\n * ```ts\n * const service = restate.service(\n * name: \"myservice\",\n * handlers: {\n * someAction: async(ctx: restate.Context, req: string) => { ... },\n * anotherAction: async(ctx: restate.Context, count: number) => { ... }\n * });\n *\n * // option 1: export only the type signature\n * export type Service = typeof service;\n *\n *\n * restate.serve({ services: [service], port: 9080 });\n * ```\n * *Client side:*\n * ```ts\n * // option 1: use only types and supply service name separately\n * const result1 = await ctx.serviceClient<Service>({name: \"myservice\"}).someAction(\"hello!\");\n *\n * // option 2: use full API spec\n * type MyService: Service = { name: \"myservice\" };\n * const result2 = await ctx.serviceClient(Service).anotherAction(1337);\n * ```\n */\n serviceClient<D>(opts: ServiceDefinitionFrom<D>): Client<Service<D>>;\n\n /**\n * Same as {@link serviceClient} but for virtual objects.\n *\n * @param opts\n * @param key the virtual object key\n */\n objectClient<D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ): Client<VirtualObject<D>>;\n\n /**\n * Same as {@link serviceClient} but for workflows.\n *\n * @param opts\n * @param key the workflow key\n */\n workflowClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): Client<Workflow<D>>;\n\n /**\n * Same as {@link objectSendClient} but for workflows.\n *\n * @param opts\n * @param key the workflow key\n */\n workflowSendClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): SendClient<Workflow<D>>;\n\n /**\n * Makes a type-safe one-way RPC to the specified target service. This method effectively behaves\n * like enqueuing the message in a message queue.\n *\n * The message goes through Restate and is guaranteed to be reliably delivered. The RPC is also\n * journaled for durable execution and will thus not be duplicated when the handler is re-invoked\n * for retries or after suspending.\n *\n * This call will return immediately; the message sending happens asynchronously in the background.\n * Despite that, the message is guaranteed to be sent, because the completion of the invocation that\n * triggers the send (calls this function) happens logically after the sending. That means that any\n * failure where the message does not reach Restate also cannot complete this invocation, and will\n * hence recover this handler and (through the durable execution) recover the message to be sent.\n *\n * @example\n * *Service Side:*\n * ```ts\n * const service = restate.service(\n * name: \"myservice\",\n * handlers: {\n * someAction: async(ctx: restate.Context, req: string) => { ... },\n * anotherAction: async(ctx: restate.Context, count: number) => { ... }\n * });\n *\n * // option 1: export only the type signature of the router\n * export type MyApi = typeof service;\n *\n * // option 2: export the API definition with type and name (name)\n * const MyService: MyApi = { name: \"myservice\" };\n *\n * restate.serve({ services: [service], port: 9080 });\n * ```\n * *Client side:*\n * ```ts\n * // option 1: use only types and supply service name separately\n * ctx.serviceSendClient<MyApi>({name: \"myservice\"}).someAction(\"hello!\");\n *\n * // option 2: use full API spec\n * ctx.serviceSendClient(MyService).anotherAction(1337);\n * ```\n */\n serviceSendClient<D>(\n service: ServiceDefinitionFrom<D>,\n opts?: SendOptions\n ): SendClient<Service<D>>;\n\n /**\n * Same as {@link serviceSendClient} but for virtual objects.\n *\n * @param obj\n * @param key the virtual object key\n * @param opts Send options\n */\n objectSendClient<D>(\n obj: VirtualObjectDefinitionFrom<D>,\n key: string,\n opts?: SendOptions\n ): SendClient<VirtualObject<D>>;\n\n genericCall<REQ = Uint8Array, RES = Uint8Array>(\n call: GenericCall<REQ, RES>\n ): InvocationPromise<RES>;\n\n genericSend<REQ = Uint8Array>(call: GenericSend<REQ>): InvocationHandle;\n\n /**\n * Returns the raw request that triggered that handler.\n * Use that object to inspect the original request headers\n */\n request(): Request;\n\n /**\n * Cancel an invocation\n *\n * @param invocationId the invocation id to cancel\n */\n cancel(invocationId: InvocationId): void;\n\n /**\n * Attach to an invocation\n *\n * @param invocationId the invocation id to attach to\n * @param serde the serde to use for the result, default to JSON serde.\n */\n attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T>;\n}\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - access/update state\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * This context can be used only within virtual objects.\n *\n */\nexport interface ObjectContext<TState extends TypedState = UntypedState>\n extends Context, KeyValueStore<TState>, RestateObjectContext {\n key: string;\n}\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * This context can be used only within a shared virtual objects.\n *\n */\nexport interface ObjectSharedContext<TState extends TypedState = UntypedState>\n extends Context, RestateObjectSharedContext {\n key: string;\n\n /**\n * Get/retrieve state from the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to retrieve\n * @returns a Promise that is resolved with the value of the state key\n *\n * @example\n * const state = await ctx.get<string>(\"STATE\");\n */\n get<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;\n\n /**\n * Retrieve all the state keys for this object.\n */\n stateKeys(): Promise<Array<string>>;\n}\n\nexport interface Rand {\n /**\n * Equivalent of JS `Math.random()` but deterministic; seeded by the invocation ID of the current invocation,\n * each call will return a new pseudorandom float within the range [0,1)\n */\n random(): number;\n\n /**\n * Using the same random source and seed as random(), produce a UUID version 4 string. This is inherently predictable\n * based on the invocation ID and should not be used in cryptographic contexts\n */\n uuidv4(): string;\n}\n\n/**\n * A promise that can be combined using Promise combinators in RestateContext.\n */\nexport type RestatePromise<T> = Promise<T> & {\n /**\n * Creates a promise that awaits for the current promise up to the specified timeout duration.\n * If the timeout is fired, this Promise will be rejected with a {@link TimeoutError}.\n *\n * @param millis duration of the sleep in millis.\n * This is a lower-bound.\n */\n orTimeout(millis: Duration | number): RestatePromise<T>;\n\n /**\n * Creates a new {@link RestatePromise} that maps the result of this promise with\n * the provided `mapper`, once this promise is fulfilled.\n *\n * **NOTE**: You **MUST** use this API when you need to map the result of a\n * {@link RestatePromise} without `await`ing it, rather than using {@link Promise.then}.\n * {@link Promise.then} is used by Restate to distinguish when awaiting an asynchronous operation,\n * thus calling `.then` on several Restate promises can lead to concurrency issues.\n *\n * @param mapper the function to execute when this promise is fulfilled.\n * If the promise completed successfully, `value` is provided as input, otherwise `failure` is provided as input.\n * If this mapper returns a value, this value will be used to resolve the returned {@link RestatePromise}.\n * If the mapper throws a {@link TerminalError}, this error will be used to reject the returned {@link RestatePromise}.\n */\n map<U>(mapper: (value?: T, failure?: TerminalError) => U): RestatePromise<U>;\n};\n\n/**\n * Represents an invocation id.\n * @see {@link InvocationIdParser}\n */\nexport type InvocationId = string & { __brand: \"InvocationId\" };\n\nexport const InvocationIdParser = {\n /**\n * Creates an invocation id from a string.\n * @param id the string to use as invocation id.\n */\n fromString(id: string): InvocationId {\n if (!id.startsWith(\"inv\")) {\n throw new Error(\n `Expected invocation id to start with 'inv' but got ${id}`\n );\n }\n return id as InvocationId;\n },\n};\n\nexport type InvocationHandle = {\n // The invocation id of the call\n readonly invocationId: Promise<InvocationId>;\n};\n\nexport type InvocationPromise<T> = RestatePromise<T> & InvocationHandle;\n\nexport const RestatePromise = {\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n *\n * See {@link Promise.all} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n all<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<{ -readonly [P in keyof T]: Awaited<T[P]> }> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.all(p),\n values\n ) as RestatePromise<{\n -readonly [P in keyof T]: Awaited<T[P]>;\n }>;\n },\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n *\n * See {@link Promise.race} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n race<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<Awaited<T[number]>> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.race(p),\n values\n ) as RestatePromise<Awaited<T[number]>>;\n },\n\n /**\n * Creates a promise that fulfills when any of the input's promises fulfills, with this first fulfillment value.\n * It rejects when all the input's promises reject (including when an empty iterable is passed),\n * with an AggregateError containing an array of rejection reasons.\n *\n * See {@link Promise.any} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n any<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<Awaited<T[number]>> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.any(p),\n values\n ) as RestatePromise<Awaited<T[number]>>;\n },\n\n /**\n * Creates a promise that fulfills when all the input's promises settle (including when an empty iterable is passed),\n * with an array of objects that describe the outcome of each promise.\n *\n * See {@link Promise.allSettled} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n allSettled<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<{\n -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;\n }> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.allSettled(p),\n values\n ) as RestatePromise<{\n -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;\n }>;\n },\n};\n\n/**\n * Workflow bound durable promise\n *\n * See {@link WorkflowSharedContext} promise..\n */\nexport type DurablePromise<T> = Promise<T> & {\n /**\n * Returns the value of the promise, if it has been resolved.\n */\n peek(): Promise<T | undefined>;\n\n /**\n * Resolve the promise with the given value.\n * @param value the value to resolve the promise with\n */\n resolve(value?: T): Promise<void>;\n\n /**\n * Reject the promise with the given error message.\n * @param errorMsg the error message to use for rejection.\n */\n reject(errorMsg: string): Promise<void>;\n\n /**\n * Obtain a {@link RestatePromise} variant of this promise.\n */\n get(): RestatePromise<T>;\n};\n\nexport interface WorkflowSharedContext<TState extends TypedState = UntypedState>\n extends ObjectSharedContext<TState>, RestateWorkflowSharedContext {\n /**\n * Create a durable promise that can be resolved or rejected during the workflow execution.\n * The promise is bound to the workflow and will be persisted across suspensions and retries.\n * @example Add some retry options\n * ```ts\n * const wf = restate.workflow({\n * name: \"myWorkflow\",\n * handlers: {\n * run: async (ctx: restate.WorkflowContext) => {\n * // ... do some work ...\n * const payment = await ctx.promise<Payment>(\"payment.succeeded\");\n * // ... do some more work ...\n * },\n *\n * onPaymentSucceeded: async (ctx: restate.WorkflowContext, payment) => {\n * // ... handle payment succeeded ...\n * await ctx.promise(\"payment.succeeded\").resolve(payment);\n * }\n * });\n * ```\n *\n * @param name the name of the durable promise\n */\n promise<T>(name: string, serde?: Serde<T>): DurablePromise<T>;\n}\n\nexport interface WorkflowContext<TState extends TypedState = UntypedState>\n extends\n WorkflowSharedContext<TState>,\n ObjectContext<TState>,\n RestateWorkflowContext {}\n"],"mappings":";;;AAusBA,MAAa,qBAAqB,EAKhC,WAAW,IAA0B;AACnC,KAAI,CAAC,GAAG,WAAW,MAAM,CACvB,OAAM,IAAI,MACR,sDAAsD,KACvD;AAEH,QAAO;GAEV;AASD,MAAa,iBAAiB;CAU5B,IACE,QAC6D;AAC7D,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAcH,KACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,KAAK,EAAE,EACtB,OACD;;CAaH,IACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAYH,WACE,QAGC;AACD,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,WAAW,EAAE,EAC5B,OACD;;CAIJ"}
@@ -83,7 +83,7 @@ var ContextImpl = class {
83
83
  return new require_promises.InvocationPendingPromise(this);
84
84
  }
85
85
  try {
86
- const call_handles = this.coreVm.sys_call(call.service, call.method, parameter, call.key, call.headers ? Object.entries(call.headers).map(([key, value]) => new require_sdk_shared_core_wasm_bindings.WasmHeader(key, value)) : [], call.idempotencyKey);
86
+ const call_handles = this.coreVm.sys_call(call.service, call.method, parameter, call.key, call.headers ? Object.entries(call.headers).map(([key, value]) => new require_sdk_shared_core_wasm_bindings.WasmHeader(key, value)) : [], call.idempotencyKey, call.name);
87
87
  const commandIndex = this.coreVm.last_command_index();
88
88
  const invocationIdPromise = new require_promises.RestateSinglePromise(this, call_handles.invocation_id_completion_id, completeCommandPromiseUsing(require_sdk_shared_core_wasm_bindings.WasmCommandType.Call, commandIndex, InvocationIdCompleter));
89
89
  return new require_promises.RestateInvocationPromise(this, call_handles.call_completion_id, completeCommandPromiseUsing(require_sdk_shared_core_wasm_bindings.WasmCommandType.Call, commandIndex, SuccessWithSerde(responseSerde, this.journalValueCodec), Failure), invocationIdPromise);
@@ -103,7 +103,7 @@ var ContextImpl = class {
103
103
  }
104
104
  try {
105
105
  const delay = send.delay !== void 0 ? (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(send.delay) : void 0;
106
- const handles = this.coreVm.sys_send(send.service, send.method, parameter, send.key, send.headers ? Object.entries(send.headers).map(([key, value]) => new require_sdk_shared_core_wasm_bindings.WasmHeader(key, value)) : [], delay !== void 0 && delay > 0 ? BigInt(delay) : void 0, send.idempotencyKey);
106
+ const handles = this.coreVm.sys_send(send.service, send.method, parameter, send.key, send.headers ? Object.entries(send.headers).map(([key, value]) => new require_sdk_shared_core_wasm_bindings.WasmHeader(key, value)) : [], delay !== void 0 && delay > 0 ? BigInt(delay) : void 0, send.idempotencyKey, send.name);
107
107
  const commandIndex = this.coreVm.last_command_index();
108
108
  return { invocationId: new require_promises.RestateSinglePromise(this, handles.invocation_id_completion_id, completeCommandPromiseUsing(require_sdk_shared_core_wasm_bindings.WasmCommandType.OneWayCall, commandIndex, InvocationIdCompleter)) };
109
109
  } catch (e) {
@@ -81,7 +81,7 @@ var ContextImpl = class {
81
81
  return new InvocationPendingPromise(this);
82
82
  }
83
83
  try {
84
- const call_handles = this.coreVm.sys_call(call.service, call.method, parameter, call.key, call.headers ? Object.entries(call.headers).map(([key, value]) => new WasmHeader(key, value)) : [], call.idempotencyKey);
84
+ const call_handles = this.coreVm.sys_call(call.service, call.method, parameter, call.key, call.headers ? Object.entries(call.headers).map(([key, value]) => new WasmHeader(key, value)) : [], call.idempotencyKey, call.name);
85
85
  const commandIndex = this.coreVm.last_command_index();
86
86
  const invocationIdPromise = new RestateSinglePromise(this, call_handles.invocation_id_completion_id, completeCommandPromiseUsing(WasmCommandType.Call, commandIndex, InvocationIdCompleter));
87
87
  return new RestateInvocationPromise(this, call_handles.call_completion_id, completeCommandPromiseUsing(WasmCommandType.Call, commandIndex, SuccessWithSerde(responseSerde, this.journalValueCodec), Failure), invocationIdPromise);
@@ -101,7 +101,7 @@ var ContextImpl = class {
101
101
  }
102
102
  try {
103
103
  const delay = send.delay !== void 0 ? millisOrDurationToMillis(send.delay) : void 0;
104
- const handles = this.coreVm.sys_send(send.service, send.method, parameter, send.key, send.headers ? Object.entries(send.headers).map(([key, value]) => new WasmHeader(key, value)) : [], delay !== void 0 && delay > 0 ? BigInt(delay) : void 0, send.idempotencyKey);
104
+ const handles = this.coreVm.sys_send(send.service, send.method, parameter, send.key, send.headers ? Object.entries(send.headers).map(([key, value]) => new WasmHeader(key, value)) : [], delay !== void 0 && delay > 0 ? BigInt(delay) : void 0, send.idempotencyKey, send.name);
105
105
  const commandIndex = this.coreVm.last_command_index();
106
106
  return { invocationId: new RestateSinglePromise(this, handles.invocation_id_completion_id, completeCommandPromiseUsing(WasmCommandType.OneWayCall, commandIndex, InvocationIdCompleter)) };
107
107
  } catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"context_impl.js","names":["coreVm: vm.WasmVM","input: vm.WasmInput","console: Console","handlerKind: HandlerKind","vmLogger: Console","invocationRequest: Request","invocationEndPromise: CompletablePromise<void>","journalValueCodec: JournalValueCodec","asTerminalError?: (error: any) => TerminalError | undefined","serde","requestSerde: Serde<REQ>","responseSerde: Serde<RES>","parameter: Uint8Array","handle: number","doRun: () => Promise<any>","res: T","awakeable: vm.WasmAwakeable","value: Uint8Array","castedPromises: InternalRestatePromise<any>[]","error","ctx: ContextImpl","name: string","cause: any","commandType: WasmCommandType","commandIndex: number","VoidAsNull: Completer","VoidAsUndefined: Completer","buffer: Uint8Array","Failure: Completer","StateKeys: Completer","InvocationIdCompleter: Completer"],"sources":["../src/context_impl.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type {\n ContextDate,\n DurablePromise,\n GenericCall,\n GenericSend,\n InvocationHandle,\n InvocationId,\n InvocationPromise,\n ObjectContext,\n Rand,\n Request,\n RestatePromise,\n RunAction,\n RunOptions,\n SendOptions,\n WorkflowContext,\n} from \"./context.js\";\nimport type * as vm from \"./endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js\";\nimport {\n WasmCommandType,\n WasmHeader,\n} from \"./endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js\";\nimport {\n ensureError,\n INTERNAL_ERROR_CODE,\n logError,\n RestateError,\n RetryableError,\n TerminalError,\n UNKNOWN_ERROR_CODE,\n} from \"./types/errors.js\";\nimport type { Client, SendClient } from \"./types/rpc.js\";\nimport {\n HandlerKind,\n makeRpcCallProxy,\n makeRpcSendProxy,\n} from \"./types/rpc.js\";\nimport type {\n Duration,\n JournalValueCodec,\n Serde,\n Service,\n ServiceDefinitionFrom,\n VirtualObject,\n VirtualObjectDefinitionFrom,\n Workflow,\n WorkflowDefinitionFrom,\n} from \"@restatedev/restate-sdk-core\";\nimport { millisOrDurationToMillis, serde } from \"@restatedev/restate-sdk-core\";\nimport { RandImpl } from \"./utils/rand.js\";\nimport type {\n ReadableStreamDefaultReader,\n WritableStreamDefaultWriter,\n} from \"node:stream/web\";\nimport { CompletablePromise } from \"./utils/completable_promise.js\";\nimport type { AsyncResultValue, InternalRestatePromise } from \"./promises.js\";\nimport {\n extractContext,\n InvocationPendingPromise,\n pendingPromise,\n PromisesExecutor,\n RestateCombinatorPromise,\n RestateInvocationPromise,\n RestatePendingPromise,\n RestateSinglePromise,\n} from \"./promises.js\";\nimport { InputPump, OutputPump } from \"./io.js\";\n\nexport class ContextImpl implements ObjectContext, WorkflowContext {\n public readonly rand: Rand;\n\n public readonly date: ContextDate = {\n now: (): Promise<number> => {\n return this.run(() => Date.now());\n },\n\n toJSON: (): Promise<string> => {\n return this.run(() => new Date().toJSON());\n },\n };\n\n private readonly outputPump: OutputPump;\n private readonly runClosuresTracker: RunClosuresTracker;\n readonly promisesExecutor: PromisesExecutor;\n readonly defaultSerde: Serde<any>;\n\n constructor(\n readonly coreVm: vm.WasmVM,\n readonly input: vm.WasmInput,\n public readonly console: Console,\n public readonly handlerKind: HandlerKind,\n private readonly vmLogger: Console,\n private readonly invocationRequest: Request,\n private readonly invocationEndPromise: CompletablePromise<void>,\n inputReader: ReadableStreamDefaultReader<Uint8Array>,\n outputWriter: WritableStreamDefaultWriter<Uint8Array>,\n readonly journalValueCodec: JournalValueCodec,\n defaultSerde?: Serde<any>,\n private readonly asTerminalError?: (error: any) => TerminalError | undefined\n ) {\n this.rand = new RandImpl(input.random_seed, () => {\n // TODO reimplement this check with async context\n // if (coreVm.is_inside_run()) {\n // throw new Error(\n // \"Cannot generate random numbers within a run closure. Use the random object outside the run closure.\"\n // );\n // }\n });\n this.outputPump = new OutputPump(coreVm, outputWriter);\n this.runClosuresTracker = new RunClosuresTracker();\n this.promisesExecutor = new PromisesExecutor(\n coreVm,\n new InputPump(\n coreVm,\n inputReader,\n this.handleInvocationEndError.bind(this)\n ),\n this.outputPump,\n this.runClosuresTracker,\n this.promiseExecutorErrorCallback.bind(this)\n );\n this.defaultSerde = defaultSerde ?? serde.json;\n }\n\n cancel(invocationId: InvocationId): void {\n this.processNonCompletableEntry(\n WasmCommandType.CancelInvocation,\n () => {},\n (vm) => vm.sys_cancel_invocation(invocationId)\n );\n }\n\n attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T> {\n return this.processCompletableEntry(\n WasmCommandType.AttachInvocation,\n () => {},\n (vm) => vm.sys_attach_invocation(invocationId),\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec),\n Failure\n );\n }\n\n public get key(): string {\n switch (this.handlerKind) {\n case HandlerKind.EXCLUSIVE:\n case HandlerKind.SHARED:\n case HandlerKind.WORKFLOW: {\n return this.input.key;\n }\n default:\n throw new TerminalError(\"this handler type doesn't support key()\");\n }\n }\n\n public request(): Request {\n return this.invocationRequest;\n }\n\n public get<T>(name: string, serde?: Serde<T>): RestatePromise<T | null> {\n return this.processCompletableEntry(\n WasmCommandType.GetState,\n () => {},\n (vm) => vm.sys_get_state(name),\n VoidAsNull,\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec)\n );\n }\n\n public stateKeys(): RestatePromise<Array<string>> {\n return this.processCompletableEntry(\n WasmCommandType.GetStateKeys,\n () => {},\n (vm) => vm.sys_get_state_keys(),\n StateKeys\n );\n }\n\n public set<T>(name: string, value: T, serde?: Serde<T>): void {\n this.processNonCompletableEntry(\n WasmCommandType.SetState,\n () =>\n this.journalValueCodec.encode(\n (serde ?? this.defaultSerde).serialize(value)\n ),\n (vm, bytes) => vm.sys_set_state(name, bytes)\n );\n }\n\n public clear(name: string): void {\n this.processNonCompletableEntry(\n WasmCommandType.ClearState,\n () => {},\n (vm) => vm.sys_clear_state(name)\n );\n }\n\n public clearAll(): void {\n this.processNonCompletableEntry(\n WasmCommandType.ClearAllState,\n () => {},\n (vm) => vm.sys_clear_all_state()\n );\n }\n\n // --- Calls, background calls, etc\n //\n public genericCall<REQ = Uint8Array, RES = Uint8Array>(\n call: GenericCall<REQ, RES>\n ): InvocationPromise<RES> {\n const requestSerde: Serde<REQ> =\n call.inputSerde ?? (serde.binary as Serde<REQ>);\n const responseSerde: Serde<RES> =\n call.outputSerde ?? (serde.binary as Serde<RES>);\n\n let parameter: Uint8Array;\n try {\n parameter = this.journalValueCodec.encode(\n requestSerde.serialize(call.parameter)\n );\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n WasmCommandType.Call\n )\n );\n return new InvocationPendingPromise(this);\n }\n\n try {\n const call_handles = this.coreVm.sys_call(\n call.service,\n call.method,\n parameter,\n call.key,\n call.headers\n ? Object.entries(call.headers).map(\n ([key, value]) => new WasmHeader(key, value)\n )\n : [],\n call.idempotencyKey\n );\n const commandIndex = this.coreVm.last_command_index();\n\n const invocationIdPromise = new RestateSinglePromise(\n this,\n call_handles.invocation_id_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.Call,\n commandIndex,\n InvocationIdCompleter\n )\n );\n\n return new RestateInvocationPromise(\n this,\n call_handles.call_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.Call,\n commandIndex,\n SuccessWithSerde(responseSerde, this.journalValueCodec),\n Failure\n ),\n invocationIdPromise as RestatePromise<InvocationId>\n );\n } catch (e) {\n this.handleInvocationEndError(e);\n // We return a pending promise to avoid the caller to see the error.\n return new InvocationPendingPromise(this);\n }\n }\n\n public genericSend<REQ = Uint8Array>(\n send: GenericSend<REQ>\n ): InvocationHandle {\n const requestSerde = send.inputSerde ?? (serde.binary as Serde<REQ>);\n\n let parameter: Uint8Array;\n try {\n parameter = this.journalValueCodec.encode(\n requestSerde.serialize(send.parameter)\n );\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n WasmCommandType.OneWayCall\n )\n );\n return new InvocationPendingPromise(this);\n }\n\n try {\n const delay =\n send.delay !== undefined\n ? millisOrDurationToMillis(send.delay)\n : undefined;\n\n const handles = this.coreVm.sys_send(\n send.service,\n send.method,\n parameter,\n send.key,\n send.headers\n ? Object.entries(send.headers).map(\n ([key, value]) => new WasmHeader(key, value)\n )\n : [],\n delay !== undefined && delay > 0 ? BigInt(delay) : undefined,\n send.idempotencyKey\n );\n const commandIndex = this.coreVm.last_command_index();\n\n return {\n invocationId: new RestateSinglePromise(\n this,\n handles.invocation_id_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.OneWayCall,\n commandIndex,\n InvocationIdCompleter\n )\n ),\n };\n } catch (e) {\n this.handleInvocationEndError(e);\n return {\n invocationId: pendingPromise(),\n };\n }\n }\n\n serviceClient<D>({ name }: ServiceDefinitionFrom<D>): Client<Service<D>> {\n return makeRpcCallProxy(\n (call) => this.genericCall(call),\n this.defaultSerde,\n\n name\n );\n }\n\n objectClient<D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string\n ): Client<VirtualObject<D>> {\n return makeRpcCallProxy(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n key\n );\n }\n\n workflowClient<D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string\n ): Client<Workflow<D>> {\n return makeRpcCallProxy(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n key\n );\n }\n\n public serviceSendClient<D>(\n { name }: ServiceDefinitionFrom<D>,\n opts?: SendOptions\n ): SendClient<Service<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n undefined,\n opts?.delay\n );\n }\n\n public objectSendClient<D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string,\n opts?: SendOptions\n ): SendClient<VirtualObject<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key,\n opts?.delay\n );\n }\n\n workflowSendClient<D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string,\n opts?: SendOptions\n ): SendClient<Workflow<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key,\n opts?.delay\n );\n }\n\n // DON'T make this function async!!!\n // The reason is that we want the errors thrown by the initial checks to be propagated in the caller context,\n // and not in the promise context. To understand the semantic difference, make this function async and run the\n // UnawaitedSideEffectShouldFailSubsequentContextCall test.\n public run<T>(\n nameOrAction: string | RunAction<T>,\n actionSecondParameter?: RunAction<T>,\n options?: RunOptions<T>\n ): RestatePromise<T> {\n const { name, action } = unpackRunParameters(\n nameOrAction,\n actionSecondParameter\n );\n const serde = options?.serde ?? this.defaultSerde;\n\n // Prepare the handle\n let handle: number;\n try {\n handle = this.coreVm.sys_run(name ?? \"\");\n } catch (e) {\n this.handleInvocationEndError(e);\n return new RestatePendingPromise(this);\n }\n const commandIndex = this.coreVm.last_command_index();\n\n // Now prepare the run task\n const doRun: () => Promise<any> = async () => {\n // Execute the user code\n const startTime = Date.now();\n let res: T;\n let err;\n try {\n res = await action();\n } catch (e) {\n err = ensureError(e, this.asTerminalError);\n }\n const attemptDuration = Date.now() - startTime;\n\n // Propose the completion to the VM\n try {\n if (err !== undefined) {\n if (err instanceof TerminalError) {\n // Record failure, go ahead\n this.coreVm.propose_run_completion_failure(handle, {\n code: err.code,\n message: err.message,\n metadata: [],\n });\n } else if (err instanceof RetryableError) {\n const maxRetryDuration =\n options?.maxRetryDuration ?? options?.maxRetryDurationMillis;\n this.coreVm.propose_run_completion_failure_transient_with_delay_override(\n handle,\n err.message,\n err.stack,\n BigInt(attemptDuration),\n err.retryAfter !== undefined\n ? BigInt(millisOrDurationToMillis(err.retryAfter))\n : undefined,\n options?.maxRetryAttempts,\n maxRetryDuration !== undefined\n ? BigInt(millisOrDurationToMillis(maxRetryDuration))\n : undefined\n );\n } else {\n this.vmLogger.warn(\n `Error when processing ctx.run '${name}'.\\n`,\n err\n );\n\n // Configure the retry policy if any of the parameters are set.\n let retryPolicy;\n if (\n options?.retryIntervalFactor !== undefined ||\n options?.maxRetryAttempts !== undefined ||\n options?.initialRetryInterval !== undefined ||\n options?.initialRetryIntervalMillis !== undefined ||\n options?.maxRetryDuration !== undefined ||\n options?.maxRetryDurationMillis !== undefined ||\n options?.maxRetryInterval !== undefined ||\n options?.maxRetryIntervalMillis !== undefined\n ) {\n const maxRetryDuration =\n options?.maxRetryDuration ?? options?.maxRetryDurationMillis;\n retryPolicy = {\n factor: options?.retryIntervalFactor ?? 2.0,\n initial_interval: millisOrDurationToMillis(\n options?.initialRetryInterval ??\n options?.initialRetryIntervalMillis ??\n 50\n ),\n max_attempts: options?.maxRetryAttempts,\n max_duration:\n maxRetryDuration === undefined\n ? undefined\n : millisOrDurationToMillis(maxRetryDuration),\n max_interval: millisOrDurationToMillis(\n options?.maxRetryInterval ??\n options?.maxRetryIntervalMillis ?? { seconds: 10 }\n ),\n };\n }\n this.coreVm.propose_run_completion_failure_transient(\n handle,\n err.message,\n err.stack,\n BigInt(attemptDuration),\n retryPolicy\n );\n }\n } else {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error\n const serializedRes = serde.serialize(res);\n const encodedRes = this.journalValueCodec.encode(serializedRes);\n this.coreVm.propose_run_completion_success(handle, encodedRes);\n }\n } catch (e) {\n this.handleInvocationEndError(e);\n return pendingPromise<T>();\n }\n await this.outputPump.awaitNextProgress();\n };\n\n // Register the run to execute\n this.runClosuresTracker.registerRunClosure(handle, doRun);\n\n // TODO: here as well\n // Return the promise\n return new RestateSinglePromise(\n this,\n handle,\n completeCommandPromiseUsing(\n WasmCommandType.Run,\n commandIndex,\n SuccessWithSerde(serde, this.journalValueCodec),\n Failure\n )\n );\n }\n\n public sleep(\n duration: number | Duration,\n name?: string\n ): RestatePromise<void> {\n return this.processCompletableEntry(\n WasmCommandType.Sleep,\n () => {\n if (duration === undefined) {\n throw new Error(`Duration is undefined.`);\n }\n const millis = millisOrDurationToMillis(duration);\n if (millis < 0) {\n throw new Error(\n `Invalid negative sleep duration: ${millis}ms.\\nIf this duration is computed from a desired wake up time, make sure to record 'now' using 'wakeUpTime - ctx.date.now()'.`\n );\n }\n return BigInt(millis);\n },\n (vm, millis) => vm.sys_sleep(millis, name),\n VoidAsUndefined\n );\n }\n\n // -- Awakeables\n\n public awakeable<T>(serde?: Serde<T>): {\n id: string;\n promise: RestatePromise<T>;\n } {\n let awakeable: vm.WasmAwakeable;\n try {\n awakeable = this.coreVm.sys_awakeable();\n } catch (e) {\n this.handleInvocationEndError(e);\n return {\n id: \"invalid\",\n promise: new RestatePendingPromise(this),\n };\n }\n\n return {\n id: awakeable.id,\n promise: new RestateSinglePromise(\n this,\n awakeable.handle,\n completeSignalPromiseUsing(\n VoidAsUndefined,\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec),\n Failure\n )\n ),\n };\n }\n\n public resolveAwakeable<T>(id: string, payload?: T, serde?: Serde<T>): void {\n this.processNonCompletableEntry(\n WasmCommandType.CompleteAwakeable,\n () => {\n // We coerce undefined to null as null can be stringified by JSON.stringify\n let value: Uint8Array;\n\n if (serde) {\n value =\n payload === undefined ? new Uint8Array() : serde.serialize(payload);\n } else {\n value =\n payload !== undefined\n ? this.defaultSerde.serialize(payload)\n : this.defaultSerde.serialize(null);\n }\n return this.journalValueCodec.encode(value);\n },\n (vm, bytes) => vm.sys_complete_awakeable_success(id, bytes)\n );\n }\n\n public rejectAwakeable(id: string, reason: string): void {\n this.processNonCompletableEntry(\n WasmCommandType.CompleteAwakeable,\n () => {},\n (vm) => {\n vm.sys_complete_awakeable_failure(id, {\n code: UNKNOWN_ERROR_CODE,\n message: reason,\n metadata: [],\n });\n }\n );\n }\n\n public promise<T>(name: string, serde?: Serde<T>): DurablePromise<T> {\n return new DurablePromiseImpl(this, name, serde);\n }\n\n // Used by static methods of RestatePromise\n public static createCombinator<T extends readonly RestatePromise<unknown>[]>(\n combinatorConstructor: (promises: Promise<any>[]) => Promise<any>,\n promises: T\n ): RestatePromise<unknown> {\n // Extract context from first promise\n const self = extractContext(promises[0]);\n if (!self) {\n throw new Error(\"Not a combinable promise\");\n }\n\n // Collect first the promises downcasted to the internal promise type\n const castedPromises: InternalRestatePromise<any>[] = [];\n for (const promise of promises) {\n if (extractContext(promise) !== self) {\n self.handleInvocationEndError(\n new Error(\n \"You're mixing up RestatePromises from different RestateContext. This is not supported.\"\n )\n );\n return new RestatePendingPromise(self);\n }\n castedPromises.push(promise as InternalRestatePromise<any>);\n }\n return new RestateCombinatorPromise(\n self,\n combinatorConstructor,\n castedPromises\n );\n }\n\n // -- Various private methods\n\n private processNonCompletableEntry<T>(\n commandType: vm.WasmCommandType,\n prepare: () => T,\n vmCall: (vm: vm.WasmVM, input: T) => void\n ) {\n let input;\n try {\n input = prepare();\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n commandType\n )\n );\n return;\n }\n\n try {\n vmCall(this.coreVm, input);\n } catch (e) {\n this.handleInvocationEndError(e);\n }\n }\n\n processCompletableEntry<T, U>(\n commandType: vm.WasmCommandType,\n prepare: () => T,\n vmCall: (vm: vm.WasmVM, t: T) => number,\n ...completers: Array<Completer>\n ): RestatePromise<U> {\n let input;\n try {\n input = prepare();\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n commandType\n )\n );\n return new RestatePendingPromise(this);\n }\n\n let handle: number;\n try {\n handle = vmCall(this.coreVm, input);\n } catch (e) {\n this.handleInvocationEndError(e);\n return new RestatePendingPromise(this);\n }\n const commandIndex = this.coreVm.last_command_index();\n return new RestateSinglePromise(\n this,\n handle,\n completeCommandPromiseUsing(commandType, commandIndex, ...completers)\n );\n }\n\n promiseExecutorErrorCallback(e: unknown) {\n if (e instanceof AsyncCompleterError) {\n const cause = ensureError(e.cause);\n logError(this.vmLogger, e.cause);\n // Special handling for this one!\n this.coreVm.notify_error_for_specific_command(\n cause.message,\n cause.stack,\n e.commandType,\n e.commandIndex,\n null\n );\n } else {\n const error = ensureError(e);\n logError(this.vmLogger, error);\n if (!(error instanceof RestateError)) {\n // Notify error\n this.coreVm.notify_error(error.message, error.stack);\n }\n }\n\n // From now on, no progress will be made.\n this.invocationEndPromise.resolve();\n }\n\n handleInvocationEndError(\n e: unknown,\n notify_vm_error: (vm: vm.WasmVM, error: Error) => void = (vm, error) => {\n vm.notify_error(error.message, error.stack);\n }\n ) {\n const error = ensureError(e);\n logError(this.vmLogger, error);\n notify_vm_error(this.coreVm, error);\n\n // From now on, no progress will be made.\n this.invocationEndPromise.resolve();\n }\n}\n\nfunction unpackRunParameters<T>(\n a: string | RunAction<T>,\n b?: RunAction<T>\n): { name?: string; action: RunAction<T> } {\n if (typeof a === \"string\") {\n if (typeof b !== \"function\") {\n throw new TypeError(\"\");\n }\n return { name: a, action: b };\n }\n if (typeof a !== \"function\") {\n throw new TypeError(\"unexpected type at the first parameter\");\n }\n if (b) {\n throw new TypeError(\"unexpected a function as a second parameter.\");\n }\n return { action: a };\n}\n\nclass DurablePromiseImpl<T> implements DurablePromise<T> {\n private readonly serde: Serde<T>;\n\n constructor(\n private readonly ctx: ContextImpl,\n private readonly name: string,\n serde?: Serde<T>\n ) {\n this.serde = serde ?? (this.ctx.defaultSerde as unknown as Serde<T>);\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null\n ): Promise<TResult1 | TResult2> {\n return this.get().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null\n ): Promise<T | TResult> {\n return this.get().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.get().finally(onfinally);\n }\n\n [Symbol.toStringTag] = \"DurablePromise\";\n\n get(): RestatePromise<T> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.GetPromise,\n () => {},\n (vm) => vm.sys_get_promise(this.name),\n SuccessWithSerde(this.serde, this.ctx.journalValueCodec),\n Failure\n );\n }\n\n peek(): Promise<T | undefined> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.PeekPromise,\n () => {},\n (vm) => vm.sys_peek_promise(this.name),\n VoidAsUndefined,\n SuccessWithSerde(this.serde, this.ctx.journalValueCodec),\n Failure\n );\n }\n\n resolve(value?: T): Promise<void> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.CompletePromise,\n () => this.ctx.journalValueCodec.encode(this.serde.serialize(value as T)),\n (vm, bytes) => vm.sys_complete_promise_success(this.name, bytes),\n VoidAsUndefined,\n Failure\n );\n }\n\n reject(errorMsg: string): Promise<void> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.CompletePromise,\n () => {},\n (vm) =>\n vm.sys_complete_promise_failure(this.name, {\n code: INTERNAL_ERROR_CODE,\n message: errorMsg,\n metadata: [],\n }),\n VoidAsUndefined,\n Failure\n );\n }\n}\n\n/// Tracker of run closures to run\nexport class RunClosuresTracker {\n private currentRunWaitPoint?: CompletablePromise<void>;\n private runsToExecute: Map<number, () => Promise<any>> = new Map<\n number,\n () => Promise<any>\n >();\n\n executeRun(handle: number) {\n const runClosure = this.runsToExecute.get(handle);\n if (runClosure === undefined) {\n throw new Error(`Handle ${handle} doesn't exist`);\n }\n runClosure()\n .finally(() => {\n this.unblockCurrentRunWaitPoint();\n })\n .catch(() => {});\n }\n\n registerRunClosure(handle: number, runClosure: () => Promise<any>) {\n this.runsToExecute.set(handle, runClosure);\n }\n\n awaitNextCompletedRun(): Promise<void> {\n if (this.currentRunWaitPoint === undefined) {\n this.currentRunWaitPoint = new CompletablePromise();\n }\n return this.currentRunWaitPoint.promise;\n }\n\n private unblockCurrentRunWaitPoint() {\n if (this.currentRunWaitPoint !== undefined) {\n const p = this.currentRunWaitPoint;\n this.currentRunWaitPoint = undefined;\n p.resolve();\n }\n }\n}\n\n// ---- Functions used to parse async results\n\ntype Completer = (\n value: AsyncResultValue,\n prom: CompletablePromise<any>\n) => Promise<boolean>;\n\n// This is just a special type we use to propagate completer errors between this function and handleInvocationEndError\nclass AsyncCompleterError {\n constructor(\n readonly cause: any,\n readonly commandType: WasmCommandType,\n readonly commandIndex: number\n ) {}\n}\n\nfunction completeCommandPromiseUsing<T>(\n commandType: WasmCommandType,\n commandIndex: number,\n ...completers: Array<Completer>\n): (value: AsyncResultValue, prom: CompletablePromise<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: CompletablePromise<any>) => {\n try {\n for (const completer of completers) {\n if (await completer(value, prom)) {\n return;\n }\n }\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw new AsyncCompleterError(e, commandType, commandIndex);\n }\n\n throw new Error(\n `Unexpected variant in async result: ${JSON.stringify(value)}`\n );\n };\n}\n\n// This is like the function above, but won't decorate the error with the command metadata\nfunction completeSignalPromiseUsing<T>(\n ...completers: Array<Completer>\n): (value: AsyncResultValue, prom: CompletablePromise<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: CompletablePromise<any>) => {\n for (const completer of completers) {\n if (await completer(value, prom)) {\n return;\n }\n }\n\n throw new Error(\n `Unexpected variant in async result: ${JSON.stringify(value)}`\n );\n };\n}\n\nconst VoidAsNull: Completer = (value, prom) => {\n if (value === \"Empty\") {\n prom.resolve(null);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\nconst VoidAsUndefined: Completer = (value, prom) => {\n if (value === \"Empty\") {\n prom.resolve(undefined);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n\nfunction SuccessWithSerde<T>(\n serde: Serde<T>,\n journalCodec?: JournalValueCodec,\n transform?: <U>(success: T) => U\n): Completer {\n return async (value, prom) => {\n if (typeof value !== \"object\" || !(\"Success\" in value)) {\n return false;\n }\n let buffer: Uint8Array;\n if (journalCodec !== undefined) {\n buffer = await journalCodec.decode(value.Success);\n } else {\n buffer = value.Success;\n }\n let val = serde.deserialize(buffer);\n if (transform) {\n val = transform(val);\n }\n prom.resolve(val);\n return true;\n };\n}\n\nconst Failure: Completer = (value, prom) => {\n if (typeof value === \"object\" && \"Failure\" in value) {\n prom.reject(\n new TerminalError(value.Failure.message, {\n errorCode: value.Failure.code,\n })\n );\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n\nconst StateKeys: Completer = (value, prom) => {\n if (typeof value === \"object\" && \"StateKeys\" in value) {\n prom.resolve(value.StateKeys);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n\nconst InvocationIdCompleter: Completer = (value, prom) => {\n if (typeof value === \"object\" && \"InvocationId\" in value) {\n prom.resolve(value.InvocationId);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n"],"mappings":";;;;;;;;;;AAiFA,IAAa,cAAb,MAAmE;CACjE,AAAgB;CAEhB,AAAgB,OAAoB;EAClC,WAA4B;AAC1B,UAAO,KAAK,UAAU,KAAK,KAAK,CAAC;;EAGnC,cAA+B;AAC7B,UAAO,KAAK,2BAAU,IAAI,MAAM,EAAC,QAAQ,CAAC;;EAE7C;CAED,AAAiB;CACjB,AAAiB;CACjB,AAAS;CACT,AAAS;CAET,YACE,AAASA,QACT,AAASC,OACT,AAAgBC,SAChB,AAAgBC,aAChB,AAAiBC,UACjB,AAAiBC,mBACjB,AAAiBC,sBACjB,aACA,cACA,AAASC,mBACT,cACA,AAAiBC,iBACjB;EAZS;EACA;EACO;EACA;EACC;EACA;EACA;EAGR;EAEQ;AAEjB,OAAK,OAAO,IAAI,SAAS,MAAM,mBAAmB,GAOhD;AACF,OAAK,aAAa,IAAI,WAAW,QAAQ,aAAa;AACtD,OAAK,qBAAqB,IAAI,oBAAoB;AAClD,OAAK,mBAAmB,IAAI,iBAC1B,QACA,IAAI,UACF,QACA,aACA,KAAK,yBAAyB,KAAK,KAAK,CACzC,EACD,KAAK,YACL,KAAK,oBACL,KAAK,6BAA6B,KAAK,KAAK,CAC7C;AACD,OAAK,eAAe,gBAAgB,MAAM;;CAG5C,OAAO,cAAkC;A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AAI,UACF,OAAM,UAAU,IAAI;AAEtB,OAAK,QAAQ,IAAI;AACjB,SAAO;;;AAIX,MAAMmB,WAAsB,OAAO,SAAS;AAC1C,KAAI,OAAO,UAAU,YAAY,aAAa,OAAO;AACnD,OAAK,OACH,IAAI,cAAc,MAAM,QAAQ,SAAS,EACvC,WAAW,MAAM,QAAQ,MAC1B,CAAC,CACH;AACD,SAAO,QAAQ,QAAQ,KAAK;;AAE9B,QAAO,QAAQ,QAAQ,MAAM;;AAG/B,MAAMC,aAAwB,OAAO,SAAS;AAC5C,KAAI,OAAO,UAAU,YAAY,eAAe,OAAO;AACrD,OAAK,QAAQ,MAAM,UAAU;AAC7B,SAAO,QAAQ,QAAQ,KAAK;;AAE9B,QAAO,QAAQ,QAAQ,MAAM;;AAG/B,MAAMC,yBAAoC,OAAO,SAAS;AACxD,KAAI,OAAO,UAAU,YAAY,kBAAkB,OAAO;AACxD,OAAK,QAAQ,MAAM,aAAa;AAChC,SAAO,QAAQ,QAAQ,KAAK;;AAE9B,QAAO,QAAQ,QAAQ,MAAM"}
1
+ {"version":3,"file":"context_impl.js","names":["coreVm: vm.WasmVM","input: vm.WasmInput","console: Console","handlerKind: HandlerKind","vmLogger: Console","invocationRequest: Request","invocationEndPromise: CompletablePromise<void>","journalValueCodec: JournalValueCodec","asTerminalError?: (error: any) => TerminalError | undefined","serde","requestSerde: Serde<REQ>","responseSerde: Serde<RES>","parameter: Uint8Array","handle: number","doRun: () => Promise<any>","res: T","awakeable: vm.WasmAwakeable","value: Uint8Array","castedPromises: InternalRestatePromise<any>[]","error","ctx: ContextImpl","name: string","cause: any","commandType: WasmCommandType","commandIndex: number","VoidAsNull: Completer","VoidAsUndefined: Completer","buffer: Uint8Array","Failure: Completer","StateKeys: Completer","InvocationIdCompleter: Completer"],"sources":["../src/context_impl.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nimport type {\n ContextDate,\n DurablePromise,\n GenericCall,\n GenericSend,\n InvocationHandle,\n InvocationId,\n InvocationPromise,\n ObjectContext,\n Rand,\n Request,\n RestatePromise,\n RunAction,\n RunOptions,\n SendOptions,\n WorkflowContext,\n} from \"./context.js\";\nimport type * as vm from \"./endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js\";\nimport {\n WasmCommandType,\n WasmHeader,\n} from \"./endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js\";\nimport {\n ensureError,\n INTERNAL_ERROR_CODE,\n logError,\n RestateError,\n RetryableError,\n TerminalError,\n UNKNOWN_ERROR_CODE,\n} from \"./types/errors.js\";\nimport type { Client, SendClient } from \"./types/rpc.js\";\nimport {\n HandlerKind,\n makeRpcCallProxy,\n makeRpcSendProxy,\n} from \"./types/rpc.js\";\nimport type {\n Duration,\n JournalValueCodec,\n Serde,\n Service,\n ServiceDefinitionFrom,\n VirtualObject,\n VirtualObjectDefinitionFrom,\n Workflow,\n WorkflowDefinitionFrom,\n} from \"@restatedev/restate-sdk-core\";\nimport { millisOrDurationToMillis, serde } from \"@restatedev/restate-sdk-core\";\nimport { RandImpl } from \"./utils/rand.js\";\nimport type {\n ReadableStreamDefaultReader,\n WritableStreamDefaultWriter,\n} from \"node:stream/web\";\nimport { CompletablePromise } from \"./utils/completable_promise.js\";\nimport type { AsyncResultValue, InternalRestatePromise } from \"./promises.js\";\nimport {\n extractContext,\n InvocationPendingPromise,\n pendingPromise,\n PromisesExecutor,\n RestateCombinatorPromise,\n RestateInvocationPromise,\n RestatePendingPromise,\n RestateSinglePromise,\n} from \"./promises.js\";\nimport { InputPump, OutputPump } from \"./io.js\";\n\nexport class ContextImpl implements ObjectContext, WorkflowContext {\n public readonly rand: Rand;\n\n public readonly date: ContextDate = {\n now: (): Promise<number> => {\n return this.run(() => Date.now());\n },\n\n toJSON: (): Promise<string> => {\n return this.run(() => new Date().toJSON());\n },\n };\n\n private readonly outputPump: OutputPump;\n private readonly runClosuresTracker: RunClosuresTracker;\n readonly promisesExecutor: PromisesExecutor;\n readonly defaultSerde: Serde<any>;\n\n constructor(\n readonly coreVm: vm.WasmVM,\n readonly input: vm.WasmInput,\n public readonly console: Console,\n public readonly handlerKind: HandlerKind,\n private readonly vmLogger: Console,\n private readonly invocationRequest: Request,\n private readonly invocationEndPromise: CompletablePromise<void>,\n inputReader: ReadableStreamDefaultReader<Uint8Array>,\n outputWriter: WritableStreamDefaultWriter<Uint8Array>,\n readonly journalValueCodec: JournalValueCodec,\n defaultSerde?: Serde<any>,\n private readonly asTerminalError?: (error: any) => TerminalError | undefined\n ) {\n this.rand = new RandImpl(input.random_seed, () => {\n // TODO reimplement this check with async context\n // if (coreVm.is_inside_run()) {\n // throw new Error(\n // \"Cannot generate random numbers within a run closure. Use the random object outside the run closure.\"\n // );\n // }\n });\n this.outputPump = new OutputPump(coreVm, outputWriter);\n this.runClosuresTracker = new RunClosuresTracker();\n this.promisesExecutor = new PromisesExecutor(\n coreVm,\n new InputPump(\n coreVm,\n inputReader,\n this.handleInvocationEndError.bind(this)\n ),\n this.outputPump,\n this.runClosuresTracker,\n this.promiseExecutorErrorCallback.bind(this)\n );\n this.defaultSerde = defaultSerde ?? serde.json;\n }\n\n cancel(invocationId: InvocationId): void {\n this.processNonCompletableEntry(\n WasmCommandType.CancelInvocation,\n () => {},\n (vm) => vm.sys_cancel_invocation(invocationId)\n );\n }\n\n attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T> {\n return this.processCompletableEntry(\n WasmCommandType.AttachInvocation,\n () => {},\n (vm) => vm.sys_attach_invocation(invocationId),\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec),\n Failure\n );\n }\n\n public get key(): string {\n switch (this.handlerKind) {\n case HandlerKind.EXCLUSIVE:\n case HandlerKind.SHARED:\n case HandlerKind.WORKFLOW: {\n return this.input.key;\n }\n default:\n throw new TerminalError(\"this handler type doesn't support key()\");\n }\n }\n\n public request(): Request {\n return this.invocationRequest;\n }\n\n public get<T>(name: string, serde?: Serde<T>): RestatePromise<T | null> {\n return this.processCompletableEntry(\n WasmCommandType.GetState,\n () => {},\n (vm) => vm.sys_get_state(name),\n VoidAsNull,\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec)\n );\n }\n\n public stateKeys(): RestatePromise<Array<string>> {\n return this.processCompletableEntry(\n WasmCommandType.GetStateKeys,\n () => {},\n (vm) => vm.sys_get_state_keys(),\n StateKeys\n );\n }\n\n public set<T>(name: string, value: T, serde?: Serde<T>): void {\n this.processNonCompletableEntry(\n WasmCommandType.SetState,\n () =>\n this.journalValueCodec.encode(\n (serde ?? this.defaultSerde).serialize(value)\n ),\n (vm, bytes) => vm.sys_set_state(name, bytes)\n );\n }\n\n public clear(name: string): void {\n this.processNonCompletableEntry(\n WasmCommandType.ClearState,\n () => {},\n (vm) => vm.sys_clear_state(name)\n );\n }\n\n public clearAll(): void {\n this.processNonCompletableEntry(\n WasmCommandType.ClearAllState,\n () => {},\n (vm) => vm.sys_clear_all_state()\n );\n }\n\n // --- Calls, background calls, etc\n //\n public genericCall<REQ = Uint8Array, RES = Uint8Array>(\n call: GenericCall<REQ, RES>\n ): InvocationPromise<RES> {\n const requestSerde: Serde<REQ> =\n call.inputSerde ?? (serde.binary as Serde<REQ>);\n const responseSerde: Serde<RES> =\n call.outputSerde ?? (serde.binary as Serde<RES>);\n\n let parameter: Uint8Array;\n try {\n parameter = this.journalValueCodec.encode(\n requestSerde.serialize(call.parameter)\n );\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n WasmCommandType.Call\n )\n );\n return new InvocationPendingPromise(this);\n }\n\n try {\n const call_handles = this.coreVm.sys_call(\n call.service,\n call.method,\n parameter,\n call.key,\n call.headers\n ? Object.entries(call.headers).map(\n ([key, value]) => new WasmHeader(key, value)\n )\n : [],\n call.idempotencyKey,\n call.name\n );\n const commandIndex = this.coreVm.last_command_index();\n\n const invocationIdPromise = new RestateSinglePromise(\n this,\n call_handles.invocation_id_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.Call,\n commandIndex,\n InvocationIdCompleter\n )\n );\n\n return new RestateInvocationPromise(\n this,\n call_handles.call_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.Call,\n commandIndex,\n SuccessWithSerde(responseSerde, this.journalValueCodec),\n Failure\n ),\n invocationIdPromise as RestatePromise<InvocationId>\n );\n } catch (e) {\n this.handleInvocationEndError(e);\n // We return a pending promise to avoid the caller to see the error.\n return new InvocationPendingPromise(this);\n }\n }\n\n public genericSend<REQ = Uint8Array>(\n send: GenericSend<REQ>\n ): InvocationHandle {\n const requestSerde = send.inputSerde ?? (serde.binary as Serde<REQ>);\n\n let parameter: Uint8Array;\n try {\n parameter = this.journalValueCodec.encode(\n requestSerde.serialize(send.parameter)\n );\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n WasmCommandType.OneWayCall\n )\n );\n return new InvocationPendingPromise(this);\n }\n\n try {\n const delay =\n send.delay !== undefined\n ? millisOrDurationToMillis(send.delay)\n : undefined;\n\n const handles = this.coreVm.sys_send(\n send.service,\n send.method,\n parameter,\n send.key,\n send.headers\n ? Object.entries(send.headers).map(\n ([key, value]) => new WasmHeader(key, value)\n )\n : [],\n delay !== undefined && delay > 0 ? BigInt(delay) : undefined,\n send.idempotencyKey,\n send.name\n );\n const commandIndex = this.coreVm.last_command_index();\n\n return {\n invocationId: new RestateSinglePromise(\n this,\n handles.invocation_id_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.OneWayCall,\n commandIndex,\n InvocationIdCompleter\n )\n ),\n };\n } catch (e) {\n this.handleInvocationEndError(e);\n return {\n invocationId: pendingPromise(),\n };\n }\n }\n\n serviceClient<D>({ name }: ServiceDefinitionFrom<D>): Client<Service<D>> {\n return makeRpcCallProxy(\n (call) => this.genericCall(call),\n this.defaultSerde,\n\n name\n );\n }\n\n objectClient<D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string\n ): Client<VirtualObject<D>> {\n return makeRpcCallProxy(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n key\n );\n }\n\n workflowClient<D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string\n ): Client<Workflow<D>> {\n return makeRpcCallProxy(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n key\n );\n }\n\n public serviceSendClient<D>(\n { name }: ServiceDefinitionFrom<D>,\n opts?: SendOptions\n ): SendClient<Service<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n undefined,\n opts?.delay\n );\n }\n\n public objectSendClient<D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string,\n opts?: SendOptions\n ): SendClient<VirtualObject<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key,\n opts?.delay\n );\n }\n\n workflowSendClient<D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string,\n opts?: SendOptions\n ): SendClient<Workflow<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key,\n opts?.delay\n );\n }\n\n // DON'T make this function async!!!\n // The reason is that we want the errors thrown by the initial checks to be propagated in the caller context,\n // and not in the promise context. To understand the semantic difference, make this function async and run the\n // UnawaitedSideEffectShouldFailSubsequentContextCall test.\n public run<T>(\n nameOrAction: string | RunAction<T>,\n actionSecondParameter?: RunAction<T>,\n options?: RunOptions<T>\n ): RestatePromise<T> {\n const { name, action } = unpackRunParameters(\n nameOrAction,\n actionSecondParameter\n );\n const serde = options?.serde ?? this.defaultSerde;\n\n // Prepare the handle\n let handle: number;\n try {\n handle = this.coreVm.sys_run(name ?? \"\");\n } catch (e) {\n this.handleInvocationEndError(e);\n return new RestatePendingPromise(this);\n }\n const commandIndex = this.coreVm.last_command_index();\n\n // Now prepare the run task\n const doRun: () => Promise<any> = async () => {\n // Execute the user code\n const startTime = Date.now();\n let res: T;\n let err;\n try {\n res = await action();\n } catch (e) {\n err = ensureError(e, this.asTerminalError);\n }\n const attemptDuration = Date.now() - startTime;\n\n // Propose the completion to the VM\n try {\n if (err !== undefined) {\n if (err instanceof TerminalError) {\n // Record failure, go ahead\n this.coreVm.propose_run_completion_failure(handle, {\n code: err.code,\n message: err.message,\n metadata: [],\n });\n } else if (err instanceof RetryableError) {\n const maxRetryDuration =\n options?.maxRetryDuration ?? options?.maxRetryDurationMillis;\n this.coreVm.propose_run_completion_failure_transient_with_delay_override(\n handle,\n err.message,\n err.stack,\n BigInt(attemptDuration),\n err.retryAfter !== undefined\n ? BigInt(millisOrDurationToMillis(err.retryAfter))\n : undefined,\n options?.maxRetryAttempts,\n maxRetryDuration !== undefined\n ? BigInt(millisOrDurationToMillis(maxRetryDuration))\n : undefined\n );\n } else {\n this.vmLogger.warn(\n `Error when processing ctx.run '${name}'.\\n`,\n err\n );\n\n // Configure the retry policy if any of the parameters are set.\n let retryPolicy;\n if (\n options?.retryIntervalFactor !== undefined ||\n options?.maxRetryAttempts !== undefined ||\n options?.initialRetryInterval !== undefined ||\n options?.initialRetryIntervalMillis !== undefined ||\n options?.maxRetryDuration !== undefined ||\n options?.maxRetryDurationMillis !== undefined ||\n options?.maxRetryInterval !== undefined ||\n options?.maxRetryIntervalMillis !== undefined\n ) {\n const maxRetryDuration =\n options?.maxRetryDuration ?? options?.maxRetryDurationMillis;\n retryPolicy = {\n factor: options?.retryIntervalFactor ?? 2.0,\n initial_interval: millisOrDurationToMillis(\n options?.initialRetryInterval ??\n options?.initialRetryIntervalMillis ??\n 50\n ),\n max_attempts: options?.maxRetryAttempts,\n max_duration:\n maxRetryDuration === undefined\n ? undefined\n : millisOrDurationToMillis(maxRetryDuration),\n max_interval: millisOrDurationToMillis(\n options?.maxRetryInterval ??\n options?.maxRetryIntervalMillis ?? { seconds: 10 }\n ),\n };\n }\n this.coreVm.propose_run_completion_failure_transient(\n handle,\n err.message,\n err.stack,\n BigInt(attemptDuration),\n retryPolicy\n );\n }\n } else {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error\n const serializedRes = serde.serialize(res);\n const encodedRes = this.journalValueCodec.encode(serializedRes);\n this.coreVm.propose_run_completion_success(handle, encodedRes);\n }\n } catch (e) {\n this.handleInvocationEndError(e);\n return pendingPromise<T>();\n }\n await this.outputPump.awaitNextProgress();\n };\n\n // Register the run to execute\n this.runClosuresTracker.registerRunClosure(handle, doRun);\n\n // TODO: here as well\n // Return the promise\n return new RestateSinglePromise(\n this,\n handle,\n completeCommandPromiseUsing(\n WasmCommandType.Run,\n commandIndex,\n SuccessWithSerde(serde, this.journalValueCodec),\n Failure\n )\n );\n }\n\n public sleep(\n duration: number | Duration,\n name?: string\n ): RestatePromise<void> {\n return this.processCompletableEntry(\n WasmCommandType.Sleep,\n () => {\n if (duration === undefined) {\n throw new Error(`Duration is undefined.`);\n }\n const millis = millisOrDurationToMillis(duration);\n if (millis < 0) {\n throw new Error(\n `Invalid negative sleep duration: ${millis}ms.\\nIf this duration is computed from a desired wake up time, make sure to record 'now' using 'wakeUpTime - ctx.date.now()'.`\n );\n }\n return BigInt(millis);\n },\n (vm, millis) => vm.sys_sleep(millis, name),\n VoidAsUndefined\n );\n }\n\n // -- Awakeables\n\n public awakeable<T>(serde?: Serde<T>): {\n id: string;\n promise: RestatePromise<T>;\n } {\n let awakeable: vm.WasmAwakeable;\n try {\n awakeable = this.coreVm.sys_awakeable();\n } catch (e) {\n this.handleInvocationEndError(e);\n return {\n id: \"invalid\",\n promise: new RestatePendingPromise(this),\n };\n }\n\n return {\n id: awakeable.id,\n promise: new RestateSinglePromise(\n this,\n awakeable.handle,\n completeSignalPromiseUsing(\n VoidAsUndefined,\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec),\n Failure\n )\n ),\n };\n }\n\n public resolveAwakeable<T>(id: string, payload?: T, serde?: Serde<T>): void {\n this.processNonCompletableEntry(\n WasmCommandType.CompleteAwakeable,\n () => {\n // We coerce undefined to null as null can be stringified by JSON.stringify\n let value: Uint8Array;\n\n if (serde) {\n value =\n payload === undefined ? new Uint8Array() : serde.serialize(payload);\n } else {\n value =\n payload !== undefined\n ? this.defaultSerde.serialize(payload)\n : this.defaultSerde.serialize(null);\n }\n return this.journalValueCodec.encode(value);\n },\n (vm, bytes) => vm.sys_complete_awakeable_success(id, bytes)\n );\n }\n\n public rejectAwakeable(id: string, reason: string): void {\n this.processNonCompletableEntry(\n WasmCommandType.CompleteAwakeable,\n () => {},\n (vm) => {\n vm.sys_complete_awakeable_failure(id, {\n code: UNKNOWN_ERROR_CODE,\n message: reason,\n metadata: [],\n });\n }\n );\n }\n\n public promise<T>(name: string, serde?: Serde<T>): DurablePromise<T> {\n return new DurablePromiseImpl(this, name, serde);\n }\n\n // Used by static methods of RestatePromise\n public static createCombinator<T extends readonly RestatePromise<unknown>[]>(\n combinatorConstructor: (promises: Promise<any>[]) => Promise<any>,\n promises: T\n ): RestatePromise<unknown> {\n // Extract context from first promise\n const self = extractContext(promises[0]);\n if (!self) {\n throw new Error(\"Not a combinable promise\");\n }\n\n // Collect first the promises downcasted to the internal promise type\n const castedPromises: InternalRestatePromise<any>[] = [];\n for (const promise of promises) {\n if (extractContext(promise) !== self) {\n self.handleInvocationEndError(\n new Error(\n \"You're mixing up RestatePromises from different RestateContext. This is not supported.\"\n )\n );\n return new RestatePendingPromise(self);\n }\n castedPromises.push(promise as InternalRestatePromise<any>);\n }\n return new RestateCombinatorPromise(\n self,\n combinatorConstructor,\n castedPromises\n );\n }\n\n // -- Various private methods\n\n private processNonCompletableEntry<T>(\n commandType: vm.WasmCommandType,\n prepare: () => T,\n vmCall: (vm: vm.WasmVM, input: T) => void\n ) {\n let input;\n try {\n input = prepare();\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n commandType\n )\n );\n return;\n }\n\n try {\n vmCall(this.coreVm, input);\n } catch (e) {\n this.handleInvocationEndError(e);\n }\n }\n\n processCompletableEntry<T, U>(\n commandType: vm.WasmCommandType,\n prepare: () => T,\n vmCall: (vm: vm.WasmVM, t: T) => number,\n ...completers: Array<Completer>\n ): RestatePromise<U> {\n let input;\n try {\n input = prepare();\n } catch (e) {\n this.handleInvocationEndError(e, (vm, error) =>\n vm.notify_error_for_next_command(\n error.message,\n error.stack,\n commandType\n )\n );\n return new RestatePendingPromise(this);\n }\n\n let handle: number;\n try {\n handle = vmCall(this.coreVm, input);\n } catch (e) {\n this.handleInvocationEndError(e);\n return new RestatePendingPromise(this);\n }\n const commandIndex = this.coreVm.last_command_index();\n return new RestateSinglePromise(\n this,\n handle,\n completeCommandPromiseUsing(commandType, commandIndex, ...completers)\n );\n }\n\n promiseExecutorErrorCallback(e: unknown) {\n if (e instanceof AsyncCompleterError) {\n const cause = ensureError(e.cause);\n logError(this.vmLogger, e.cause);\n // Special handling for this one!\n this.coreVm.notify_error_for_specific_command(\n cause.message,\n cause.stack,\n e.commandType,\n e.commandIndex,\n null\n );\n } else {\n const error = ensureError(e);\n logError(this.vmLogger, error);\n if (!(error instanceof RestateError)) {\n // Notify error\n this.coreVm.notify_error(error.message, error.stack);\n }\n }\n\n // From now on, no progress will be made.\n this.invocationEndPromise.resolve();\n }\n\n handleInvocationEndError(\n e: unknown,\n notify_vm_error: (vm: vm.WasmVM, error: Error) => void = (vm, error) => {\n vm.notify_error(error.message, error.stack);\n }\n ) {\n const error = ensureError(e);\n logError(this.vmLogger, error);\n notify_vm_error(this.coreVm, error);\n\n // From now on, no progress will be made.\n this.invocationEndPromise.resolve();\n }\n}\n\nfunction unpackRunParameters<T>(\n a: string | RunAction<T>,\n b?: RunAction<T>\n): { name?: string; action: RunAction<T> } {\n if (typeof a === \"string\") {\n if (typeof b !== \"function\") {\n throw new TypeError(\"\");\n }\n return { name: a, action: b };\n }\n if (typeof a !== \"function\") {\n throw new TypeError(\"unexpected type at the first parameter\");\n }\n if (b) {\n throw new TypeError(\"unexpected a function as a second parameter.\");\n }\n return { action: a };\n}\n\nclass DurablePromiseImpl<T> implements DurablePromise<T> {\n private readonly serde: Serde<T>;\n\n constructor(\n private readonly ctx: ContextImpl,\n private readonly name: string,\n serde?: Serde<T>\n ) {\n this.serde = serde ?? (this.ctx.defaultSerde as unknown as Serde<T>);\n }\n\n then<TResult1 = T, TResult2 = never>(\n onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | null,\n onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null\n ): Promise<TResult1 | TResult2> {\n return this.get().then(onfulfilled, onrejected);\n }\n\n catch<TResult = never>(\n onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null\n ): Promise<T | TResult> {\n return this.get().catch(onrejected);\n }\n\n finally(onfinally?: (() => void) | null): Promise<T> {\n return this.get().finally(onfinally);\n }\n\n [Symbol.toStringTag] = \"DurablePromise\";\n\n get(): RestatePromise<T> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.GetPromise,\n () => {},\n (vm) => vm.sys_get_promise(this.name),\n SuccessWithSerde(this.serde, this.ctx.journalValueCodec),\n Failure\n );\n }\n\n peek(): Promise<T | undefined> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.PeekPromise,\n () => {},\n (vm) => vm.sys_peek_promise(this.name),\n VoidAsUndefined,\n SuccessWithSerde(this.serde, this.ctx.journalValueCodec),\n Failure\n );\n }\n\n resolve(value?: T): Promise<void> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.CompletePromise,\n () => this.ctx.journalValueCodec.encode(this.serde.serialize(value as T)),\n (vm, bytes) => vm.sys_complete_promise_success(this.name, bytes),\n VoidAsUndefined,\n Failure\n );\n }\n\n reject(errorMsg: string): Promise<void> {\n return this.ctx.processCompletableEntry(\n WasmCommandType.CompletePromise,\n () => {},\n (vm) =>\n vm.sys_complete_promise_failure(this.name, {\n code: INTERNAL_ERROR_CODE,\n message: errorMsg,\n metadata: [],\n }),\n VoidAsUndefined,\n Failure\n );\n }\n}\n\n/// Tracker of run closures to run\nexport class RunClosuresTracker {\n private currentRunWaitPoint?: CompletablePromise<void>;\n private runsToExecute: Map<number, () => Promise<any>> = new Map<\n number,\n () => Promise<any>\n >();\n\n executeRun(handle: number) {\n const runClosure = this.runsToExecute.get(handle);\n if (runClosure === undefined) {\n throw new Error(`Handle ${handle} doesn't exist`);\n }\n runClosure()\n .finally(() => {\n this.unblockCurrentRunWaitPoint();\n })\n .catch(() => {});\n }\n\n registerRunClosure(handle: number, runClosure: () => Promise<any>) {\n this.runsToExecute.set(handle, runClosure);\n }\n\n awaitNextCompletedRun(): Promise<void> {\n if (this.currentRunWaitPoint === undefined) {\n this.currentRunWaitPoint = new CompletablePromise();\n }\n return this.currentRunWaitPoint.promise;\n }\n\n private unblockCurrentRunWaitPoint() {\n if (this.currentRunWaitPoint !== undefined) {\n const p = this.currentRunWaitPoint;\n this.currentRunWaitPoint = undefined;\n p.resolve();\n }\n }\n}\n\n// ---- Functions used to parse async results\n\ntype Completer = (\n value: AsyncResultValue,\n prom: CompletablePromise<any>\n) => Promise<boolean>;\n\n// This is just a special type we use to propagate completer errors between this function and handleInvocationEndError\nclass AsyncCompleterError {\n constructor(\n readonly cause: any,\n readonly commandType: WasmCommandType,\n readonly commandIndex: number\n ) {}\n}\n\nfunction completeCommandPromiseUsing<T>(\n commandType: WasmCommandType,\n commandIndex: number,\n ...completers: Array<Completer>\n): (value: AsyncResultValue, prom: CompletablePromise<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: CompletablePromise<any>) => {\n try {\n for (const completer of completers) {\n if (await completer(value, prom)) {\n return;\n }\n }\n } catch (e) {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw new AsyncCompleterError(e, commandType, commandIndex);\n }\n\n throw new Error(\n `Unexpected variant in async result: ${JSON.stringify(value)}`\n );\n };\n}\n\n// This is like the function above, but won't decorate the error with the command metadata\nfunction completeSignalPromiseUsing<T>(\n ...completers: Array<Completer>\n): (value: AsyncResultValue, prom: CompletablePromise<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: CompletablePromise<any>) => {\n for (const completer of completers) {\n if (await completer(value, prom)) {\n return;\n }\n }\n\n throw new Error(\n `Unexpected variant in async result: ${JSON.stringify(value)}`\n );\n };\n}\n\nconst VoidAsNull: Completer = (value, prom) => {\n if (value === \"Empty\") {\n prom.resolve(null);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\nconst VoidAsUndefined: Completer = (value, prom) => {\n if (value === \"Empty\") {\n prom.resolve(undefined);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n\nfunction SuccessWithSerde<T>(\n serde: Serde<T>,\n journalCodec?: JournalValueCodec,\n transform?: <U>(success: T) => U\n): Completer {\n return async (value, prom) => {\n if (typeof value !== \"object\" || !(\"Success\" in value)) {\n return false;\n }\n let buffer: Uint8Array;\n if (journalCodec !== undefined) {\n buffer = await journalCodec.decode(value.Success);\n } else {\n buffer = value.Success;\n }\n let val = serde.deserialize(buffer);\n if (transform) {\n val = transform(val);\n }\n prom.resolve(val);\n return true;\n };\n}\n\nconst Failure: Completer = (value, prom) => {\n if (typeof value === \"object\" && \"Failure\" in value) {\n prom.reject(\n new TerminalError(value.Failure.message, {\n errorCode: value.Failure.code,\n })\n );\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n\nconst StateKeys: Completer = (value, prom) => {\n if (typeof value === \"object\" && \"StateKeys\" in value) {\n prom.resolve(value.StateKeys);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n\nconst InvocationIdCompleter: Completer = (value, prom) => {\n if (typeof value === \"object\" && \"InvocationId\" in value) {\n prom.resolve(value.InvocationId);\n return Promise.resolve(true);\n }\n return Promise.resolve(false);\n};\n"],"mappings":";;;;;;;;;;AAiFA,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QAAQ,KAAK;;AAE9B,QAAO,QAAQ,QAAQ,MAAM;;AAG/B,MAAMC,yBAAoC,OAAO,SAAS;AACxD,KAAI,OAAO,UAAU,YAAY,kBAAkB,OAAO;AACxD,OAAK,QAAQ,MAAM,aAAa;AAChC,SAAO,QAAQ,QAAQ,KAAK;;AAE9B,QAAO,QAAQ,QAAQ,MAAM"}
@@ -124,8 +124,8 @@ export class WasmVM {
124
124
  sys_sleep(millis: bigint, name?: string | null): number;
125
125
  sys_attach_invocation(invocation_id: string): number;
126
126
  sys_get_invocation_output(invocation_id: string): number;
127
- sys_call(service: string, handler: string, buffer: Uint8Array, key: string | null | undefined, headers: WasmHeader[], idempotency_key?: string | null): WasmCallHandle;
128
- sys_send(service: string, handler: string, buffer: Uint8Array, key: string | null | undefined, headers: WasmHeader[], delay?: bigint | null, idempotency_key?: string | null): WasmSendHandle;
127
+ sys_call(service: string, handler: string, buffer: Uint8Array, key: string | null | undefined, headers: WasmHeader[], idempotency_key?: string | null, name?: string | null): WasmCallHandle;
128
+ sys_send(service: string, handler: string, buffer: Uint8Array, key: string | null | undefined, headers: WasmHeader[], delay?: bigint | null, idempotency_key?: string | null, name?: string | null): WasmSendHandle;
129
129
  sys_awakeable(): WasmAwakeable;
130
130
  sys_complete_awakeable_success(id: string, buffer: Uint8Array): void;
131
131
  sys_complete_awakeable_failure(id: string, value: WasmFailure): void;
@@ -799,9 +799,10 @@ export class WasmVM {
799
799
  * @param {string | null | undefined} key
800
800
  * @param {WasmHeader[]} headers
801
801
  * @param {string | null} [idempotency_key]
802
+ * @param {string | null} [name]
802
803
  * @returns {WasmCallHandle}
803
804
  */
804
- sys_call(service, handler, buffer, key, headers, idempotency_key) {
805
+ sys_call(service, handler, buffer, key, headers, idempotency_key, name) {
805
806
  const ptr0 = passStringToWasm0(service, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
806
807
  const len0 = WASM_VECTOR_LEN;
807
808
  const ptr1 = passStringToWasm0(handler, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
@@ -814,7 +815,9 @@ export class WasmVM {
814
815
  const len4 = WASM_VECTOR_LEN;
815
816
  var ptr5 = isLikeNone(idempotency_key) ? 0 : passStringToWasm0(idempotency_key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
816
817
  var len5 = WASM_VECTOR_LEN;
817
- const ret = wasm.wasmvm_sys_call(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3, ptr4, len4, ptr5, len5);
818
+ var ptr6 = isLikeNone(name) ? 0 : passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
819
+ var len6 = WASM_VECTOR_LEN;
820
+ const ret = wasm.wasmvm_sys_call(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3, ptr4, len4, ptr5, len5, ptr6, len6);
818
821
  if (ret[2]) {
819
822
  throw takeFromExternrefTable0(ret[1]);
820
823
  }
@@ -828,9 +831,10 @@ export class WasmVM {
828
831
  * @param {WasmHeader[]} headers
829
832
  * @param {bigint | null} [delay]
830
833
  * @param {string | null} [idempotency_key]
834
+ * @param {string | null} [name]
831
835
  * @returns {WasmSendHandle}
832
836
  */
833
- sys_send(service, handler, buffer, key, headers, delay, idempotency_key) {
837
+ sys_send(service, handler, buffer, key, headers, delay, idempotency_key, name) {
834
838
  const ptr0 = passStringToWasm0(service, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
835
839
  const len0 = WASM_VECTOR_LEN;
836
840
  const ptr1 = passStringToWasm0(handler, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
@@ -843,7 +847,9 @@ export class WasmVM {
843
847
  const len4 = WASM_VECTOR_LEN;
844
848
  var ptr5 = isLikeNone(idempotency_key) ? 0 : passStringToWasm0(idempotency_key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
845
849
  var len5 = WASM_VECTOR_LEN;
846
- const ret = wasm.wasmvm_sys_send(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3, ptr4, len4, !isLikeNone(delay), isLikeNone(delay) ? BigInt(0) : delay, ptr5, len5);
850
+ var ptr6 = isLikeNone(name) ? 0 : passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
851
+ var len6 = WASM_VECTOR_LEN;
852
+ const ret = wasm.wasmvm_sys_send(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3, ptr4, len4, !isLikeNone(delay), isLikeNone(delay) ? BigInt(0) : delay, ptr5, len5, ptr6, len6);
847
853
  if (ret[2]) {
848
854
  throw takeFromExternrefTable0(ret[1]);
849
855
  }
@@ -38,8 +38,8 @@ export const wasmvm_sys_clear_all_state: (a: number) => [number, number];
38
38
  export const wasmvm_sys_sleep: (a: number, b: bigint, c: number, d: number) => [number, number, number];
39
39
  export const wasmvm_sys_attach_invocation: (a: number, b: number, c: number) => [number, number, number];
40
40
  export const wasmvm_sys_get_invocation_output: (a: number, b: number, c: number) => [number, number, number];
41
- export const wasmvm_sys_call: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: number) => [number, number, number];
42
- export const wasmvm_sys_send: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: bigint, n: number, o: number) => [number, number, number];
41
+ export const wasmvm_sys_call: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: number, n: number, o: number) => [number, number, number];
42
+ export const wasmvm_sys_send: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: bigint, n: number, o: number, p: number, q: number) => [number, number, number];
43
43
  export const wasmvm_sys_awakeable: (a: number) => [number, number, number];
44
44
  export const wasmvm_sys_complete_awakeable_success: (a: number, b: number, c: number, d: number, e: number) => [number, number];
45
45
  export const wasmvm_sys_complete_awakeable_failure: (a: number, b: number, c: number, d: any) => [number, number];
package/dist/package.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
 
2
2
  //#region package.json
3
- var version = "1.10.2";
3
+ var version = "1.10.3";
4
4
 
5
5
  //#endregion
6
6
  Object.defineProperty(exports, 'version', {
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "1.10.2";
2
+ var version = "1.10.3";
3
3
 
4
4
  //#endregion
5
5
  export { version };
@@ -1 +1 @@
1
- {"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"@restatedev/restate-sdk\",\n \"version\": \"1.10.2\",\n \"description\": \"Typescript SDK for Restate\",\n \"author\": \"Restate Developers\",\n \"email\": \"code@restate.dev\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/restatedev/sdk-typescript#readme\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/restatedev/sdk-typescript.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/restatedev/sdk-typescript/issues\"\n },\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.cts\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./fetch\": {\n \"import\": \"./dist/fetch.js\",\n \"require\": \"./dist/fetch.cjs\"\n },\n \"./lambda\": {\n \"import\": \"./dist/lambda.js\",\n \"require\": \"./dist/lambda.cjs\"\n },\n \"./node\": {\n \"import\": \"./dist/node.js\",\n \"require\": \"./dist/node.cjs\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"test\": \"turbo run _test --filter={.}...\",\n \"_test\": \"vitest run\",\n \"build\": \"turbo run _build --filter={.}...\",\n \"_build\": \"tsc --noEmit && tsdown\",\n \"dev\": \"tsc --noEmit --watch\",\n \"clean\": \"rm -rf dist *.tsbuildinfo .turbo\",\n \"check:types\": \"turbo run _check:types --filter={.}...\",\n \"_check:types\": \"tsc --noEmit --project tsconfig.build.json\",\n \"lint\": \"eslint .\",\n \"check:exports\": \"turbo run _check:exports --filter={.}...\",\n \"_check:exports\": \"attw --pack .\",\n \"check:api\": \"turbo run _check:api --filter={.}...\",\n \"_check:api\": \"api-extractor run --local && api-extractor run --local --config api-extractor.fetch.json && api-extractor run --local --config api-extractor.lambda.json && api-extractor run --local --config api-extractor.node.json\",\n \"prepublishOnly\": \"pnpm -w verify\"\n },\n \"dependencies\": {\n \"@restatedev/restate-sdk-core\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.115\"\n },\n \"typesVersions\": {\n \"*\": {\n \"fetch\": [\n \"./dist/fetch.d.ts\"\n ],\n \"lambda\": [\n \"./dist/lambda.d.ts\"\n ],\n \"node\": [\n \"./dist/node.d.ts\"\n ]\n }\n }\n}\n"],"mappings":";cAEa"}
1
+ {"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"@restatedev/restate-sdk\",\n \"version\": \"1.10.3\",\n \"description\": \"Typescript SDK for Restate\",\n \"author\": \"Restate Developers\",\n \"email\": \"code@restate.dev\",\n \"license\": \"MIT\",\n \"homepage\": \"https://github.com/restatedev/sdk-typescript#readme\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/restatedev/sdk-typescript.git\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/restatedev/sdk-typescript/issues\"\n },\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.cts\",\n \"exports\": {\n \".\": {\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n },\n \"./fetch\": {\n \"import\": \"./dist/fetch.js\",\n \"require\": \"./dist/fetch.cjs\"\n },\n \"./lambda\": {\n \"import\": \"./dist/lambda.js\",\n \"require\": \"./dist/lambda.cjs\"\n },\n \"./node\": {\n \"import\": \"./dist/node.js\",\n \"require\": \"./dist/node.cjs\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"test\": \"turbo run _test --filter={.}...\",\n \"_test\": \"vitest run\",\n \"build\": \"turbo run _build --filter={.}...\",\n \"_build\": \"tsc --noEmit && tsdown\",\n \"dev\": \"tsc --noEmit --watch\",\n \"clean\": \"rm -rf dist *.tsbuildinfo .turbo\",\n \"check:types\": \"turbo run _check:types --filter={.}...\",\n \"_check:types\": \"tsc --noEmit --project tsconfig.build.json\",\n \"lint\": \"eslint .\",\n \"check:exports\": \"turbo run _check:exports --filter={.}...\",\n \"_check:exports\": \"attw --pack .\",\n \"check:api\": \"turbo run _check:api --filter={.}...\",\n \"_check:api\": \"api-extractor run --local && api-extractor run --local --config api-extractor.fetch.json && api-extractor run --local --config api-extractor.lambda.json && api-extractor run --local --config api-extractor.node.json\",\n \"prepublishOnly\": \"pnpm -w verify\"\n },\n \"dependencies\": {\n \"@restatedev/restate-sdk-core\": \"workspace:*\"\n },\n \"devDependencies\": {\n \"@types/aws-lambda\": \"^8.10.115\"\n },\n \"typesVersions\": {\n \"*\": {\n \"fetch\": [\n \"./dist/fetch.d.ts\"\n ],\n \"lambda\": [\n \"./dist/lambda.d.ts\"\n ],\n \"node\": [\n \"./dist/node.d.ts\"\n ]\n }\n }\n}\n"],"mappings":";cAEa"}
@@ -71,7 +71,8 @@ const makeRpcCallProxy = (genericCall, defaultSerde, service$1, key) => {
71
71
  headers: opts?.headers,
72
72
  inputSerde: requestSerde,
73
73
  outputSerde: responseSerde,
74
- idempotencyKey: opts?.idempotencyKey
74
+ idempotencyKey: opts?.idempotencyKey,
75
+ name: opts?.name
75
76
  });
76
77
  };
77
78
  } });
@@ -91,7 +92,8 @@ const makeRpcSendProxy = (genericSend, defaultSerde, service$1, key, legacyDelay
91
92
  headers: opts?.headers,
92
93
  delay,
93
94
  inputSerde: requestSerde,
94
- idempotencyKey: opts?.idempotencyKey
95
+ idempotencyKey: opts?.idempotencyKey,
96
+ name: opts?.name
95
97
  });
96
98
  };
97
99
  } });
@@ -8,6 +8,10 @@ type ClientCallOptions<I, O$1> = {
8
8
  output?: Serde<O$1>;
9
9
  headers?: Record<string, string>;
10
10
  idempotencyKey?: string;
11
+ /**
12
+ * Observability name, recorded in the Restate journal.
13
+ */
14
+ name?: string;
11
15
  };
12
16
  declare class Opts<I, O$1> {
13
17
  private readonly opts;
@@ -50,6 +54,10 @@ type ClientSendOptions<I> = {
50
54
  delay?: Duration | number;
51
55
  headers?: Record<string, string>;
52
56
  idempotencyKey?: string;
57
+ /**
58
+ * Observability name, recorded in the Restate journal.
59
+ */
60
+ name?: string;
53
61
  };
54
62
  declare class SendOpts<I> {
55
63
  private readonly opts;
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.d.cts","names":[],"sources":["../../src/types/rpc.ts"],"sourcesContent":[],"mappings":";;;;;KA6CY;UACF,MAAM;EADJ,MAAA,CAAA,EAED,KAFC,CAEK,GAFL,CAAA;EACI,OAAA,CAAA,EAEJ,MAFI,CAAA,MAAA,EAAA,MAAA,CAAA;EAAN,cAAA,CAAA,EAAA,MAAA;CACO;AAAN,cAKE,IALF,CAAA,CAAA,EAAA,GAAA,CAAA,CAAA;EACC,iBAAA,IAAA;EAAM;AAIlB;;;;EAMgE,OAAA,IAAA,CAAA,CAAA,EAAA,GAAA,CAAA,CAAA,IAAA,EAA/B,iBAA+B,CAAb,CAAa,EAAV,GAAU,CAAA,CAAA,EAAL,IAAK,CAAA,CAAA,EAAG,GAAH,CAAA;EAAG,QAAA,WAAA,CAAA;EAAR,OAAA,CAAA,CAAA,EAMvC,iBANuC,CAMrB,CANqB,EAMlB,GANkB,CAAA;;AAMlB,KAK7B,iBAL6B,CAAA,CAAA,CAAA,GAAA;EAArB,KAAA,CAAA,EAMV,KANU,CAMJ,CANI,CAAA;EAAiB;AAKr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KAAG"}
@@ -8,6 +8,10 @@ type ClientCallOptions<I, O$1> = {
8
8
  output?: Serde<O$1>;
9
9
  headers?: Record<string, string>;
10
10
  idempotencyKey?: string;
11
+ /**
12
+ * Observability name, recorded in the Restate journal.
13
+ */
14
+ name?: string;
11
15
  };
12
16
  declare class Opts<I, O$1> {
13
17
  private readonly opts;
@@ -50,6 +54,10 @@ type ClientSendOptions<I> = {
50
54
  delay?: Duration | number;
51
55
  headers?: Record<string, string>;
52
56
  idempotencyKey?: string;
57
+ /**
58
+ * Observability name, recorded in the Restate journal.
59
+ */
60
+ name?: string;
53
61
  };
54
62
  declare class SendOpts<I> {
55
63
  private readonly opts;
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.d.ts","names":[],"sources":["../../src/types/rpc.ts"],"sourcesContent":[],"mappings":";;;;;KA6CY;UACF,MAAM;EADJ,MAAA,CAAA,EAED,KAFC,CAEK,GAFL,CAAA;EACI,OAAA,CAAA,EAEJ,MAFI,CAAA,MAAA,EAAA,MAAA,CAAA;EAAN,cAAA,CAAA,EAAA,MAAA;CACO;AAAN,cAKE,IALF,CAAA,CAAA,EAAA,GAAA,CAAA,CAAA;EACC,iBAAA,IAAA;EAAM;AAIlB;;;;EAMgE,OAAA,IAAA,CAAA,CAAA,EAAA,GAAA,CAAA,CAAA,IAAA,EAA/B,iBAA+B,CAAb,CAAa,EAAV,GAAU,CAAA,CAAA,EAAL,IAAK,CAAA,CAAA,EAAG,GAAH,CAAA;EAAG,QAAA,WAAA,CAAA;EAAR,OAAA,CAAA,CAAA,EAMvC,iBANuC,CAMrB,CANqB,EAMlB,GANkB,CAAA;;AAMlB,KAK7B,iBAL6B,CAAA,CAAA,CAAA,GAAA;EAArB,KAAA,CAAA,EAMV,KANU,CAMJ,CANI,CAAA;EAAiB;AAKrC;;;;;;AAgCA;;;;;;;;AAYA;;;;;;;;;;EAGwD,KAAA,CAAA,EApB9C,QAoB8C,GAAA,MAAA;EAAA,OAAA,CAAA,EAnB5C,MAmB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erde: requestSerde,
73
73
  outputSerde: responseSerde,
74
- idempotencyKey: opts?.idempotencyKey
74
+ idempotencyKey: opts?.idempotencyKey,
75
+ name: opts?.name
75
76
  });
76
77
  };
77
78
  } });
@@ -91,7 +92,8 @@ const makeRpcSendProxy = (genericSend, defaultSerde, service$1, key, legacyDelay
91
92
  headers: opts?.headers,
92
93
  delay,
93
94
  inputSerde: requestSerde,
94
- idempotencyKey: opts?.idempotencyKey
95
+ idempotencyKey: opts?.idempotencyKey,
96
+ name: opts?.name
95
97
  });
96
98
  };
97
99
  } });
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.js","names":["opts: ClientCallOptions<I, O>","opts: ClientSendOptions<I>","parameter: unknown","opts:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined","kind: HandlerKind","handler: Function","inputSerde?: Serde<unknown>","outputSerde?: Serde<unknown>","accept?: string","description?: string","metadata?: Record<string, string>","idempotencyRetention?: Duration | number","journalRetention?: Duration | number","inactivityTimeout?: Duration | number","abortTimeout?: Duration | number","ingressPrivate?: boolean","enableLazyState?: boolean","retryPolicy?: RetryPolicy","asTerminalError?: (error: any) => TerminalError | undefined","req: unknown","res: unknown","workflow","service","handlers","object","runWrapper: HandlerWrapper","wrapper: HandlerWrapper"],"sources":["../../src/types/rpc.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-function-type */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport type {\n Context,\n GenericCall,\n GenericSend,\n InvocationHandle,\n InvocationPromise,\n ObjectContext,\n ObjectSharedContext,\n TypedState,\n UntypedState,\n WorkflowContext,\n WorkflowSharedContext,\n} from \"../context.js\";\n\nimport {\n type ServiceHandler,\n type ServiceDefinition,\n type ObjectHandler,\n type VirtualObjectDefinition,\n type WorkflowHandler,\n type WorkflowDefinition,\n type WorkflowSharedHandler,\n type Serde,\n type Duration,\n} from \"@restatedev/restate-sdk-core\";\nimport { ensureError, TerminalError } from \"./errors.js\";\n\n// ----------- rpc clients -------------------------------------------------------\n\nexport type ClientCallOptions<I, O> = {\n input?: Serde<I>;\n output?: Serde<O>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n};\n\nexport class Opts<I, O> {\n /**\n * Create a call configuration from the provided options.\n *\n * @param opts the call configuration\n */\n public static from<I, O>(opts: ClientCallOptions<I, O>): Opts<I, O> {\n return new Opts<I, O>(opts);\n }\n\n private constructor(private readonly opts: ClientCallOptions<I, O>) {}\n\n public getOpts(): ClientCallOptions<I, O> {\n return this.opts;\n }\n}\n\nexport type ClientSendOptions<I> = {\n input?: Serde<I>;\n /**\n * Makes a type-safe one-way RPC to the specified target service, after a delay specified by the\n * milliseconds' argument.\n * This method is like setting up a fault-tolerant cron job that enqueues the message in a\n * message queue.\n * The handler calling this function does not have to stay active for the delay time.\n *\n * Both the delay timer and the message are durably stored in Restate and guaranteed to be reliably\n * delivered. The delivery happens no earlier than specified through the delay, but may happen\n * later, if the target service is down, or backpressuring the system.\n *\n * The delay message is journaled for durable execution and will thus not be duplicated when the\n * handler is re-invoked for retries or after suspending.\n *\n * This call will return immediately; the message sending happens asynchronously in the background.\n * Despite that, the message is guaranteed to be sent, because the completion of the invocation that\n * triggers the send (calls this function) happens logically after the sending. That means that any\n * failure where the message does not reach Restate also cannot complete this invocation, and will\n * hence recover this handler and (through the durable execution) recover the message to be sent.\n *\n * @example\n * ```ts\n * ctx.serviceSendClient(Service).anotherAction(1337, { delay: { seconds: 60 } });\n * ```\n */\n delay?: Duration | number;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n};\n\nexport class SendOpts<I> {\n public static from<I>(opts: ClientSendOptions<I>): SendOpts<I> {\n return new SendOpts<I>(opts);\n }\n\n public getOpts(): ClientSendOptions<I> {\n return this.opts;\n }\n\n private constructor(private readonly opts: ClientSendOptions<I>) {}\n}\n\nexport namespace rpc {\n export const opts = <I, O>(opts: ClientCallOptions<I, O>) => Opts.from(opts);\n\n export const sendOpts = <I>(opts: ClientSendOptions<I>) =>\n SendOpts.from(opts);\n}\n\nfunction optsFromArgs(args: unknown[]): {\n parameter?: unknown;\n opts?:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined;\n} {\n let parameter: unknown;\n let opts:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined;\n switch (args.length) {\n case 0: {\n break;\n }\n case 1: {\n if (args[0] instanceof Opts) {\n opts = args[0].getOpts();\n } else if (args[0] instanceof SendOpts) {\n opts = args[0].getOpts();\n } else {\n parameter = args[0];\n }\n break;\n }\n case 2: {\n parameter = args[0];\n if (args[1] instanceof Opts) {\n opts = args[1].getOpts();\n } else if (args[1] instanceof SendOpts) {\n opts = args[1].getOpts();\n } else {\n throw new TypeError(\n \"The second argument must be either Opts or SendOpts\"\n );\n }\n break;\n }\n default: {\n throw new TypeError(\"unexpected number of arguments\");\n }\n }\n return {\n parameter,\n opts,\n };\n}\n\nexport const makeRpcCallProxy = <T>(\n genericCall: (call: GenericCall<unknown, unknown>) => Promise<unknown>,\n defaultSerde: Serde<any>,\n service: string,\n key?: string\n): T => {\n const clientProxy = new Proxy(\n {},\n {\n get: (_target, prop) => {\n const method = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n const requestSerde = opts?.input ?? defaultSerde;\n const responseSerde =\n (opts as ClientCallOptions<unknown, unknown> | undefined)?.output ??\n defaultSerde;\n return genericCall({\n service,\n method,\n parameter,\n key,\n headers: opts?.headers,\n inputSerde: requestSerde,\n outputSerde: responseSerde,\n idempotencyKey: opts?.idempotencyKey,\n });\n };\n },\n }\n );\n\n return clientProxy as T;\n};\n\nexport const makeRpcSendProxy = <T>(\n genericSend: (send: GenericSend<unknown>) => void,\n defaultSerde: Serde<any>,\n service: string,\n key?: string,\n legacyDelay?: number\n): T => {\n const clientProxy = new Proxy(\n {},\n {\n get: (_target, prop) => {\n const method = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n const requestSerde = opts?.input ?? defaultSerde;\n const delay =\n legacyDelay ??\n (opts as ClientSendOptions<unknown> | undefined)?.delay;\n return genericSend({\n service,\n method,\n parameter,\n key,\n headers: opts?.headers,\n delay,\n inputSerde: requestSerde,\n idempotencyKey: opts?.idempotencyKey,\n });\n };\n },\n }\n );\n\n return clientProxy as T;\n};\n\nexport type InferArg<P> = P extends [infer A, ...any[]] ? A : unknown;\n\nexport type Client<M> = {\n [K in keyof M as M[K] extends never ? never : K]: M[K] extends (\n arg: any,\n ...args: infer P\n ) => PromiseLike<infer O>\n ? (\n ...args: [...P, ...[opts?: Opts<InferArg<P>, O>]]\n ) => InvocationPromise<O>\n : never;\n};\n\nexport type SendClient<M> = {\n [K in keyof M as M[K] extends never ? never : K]: M[K] extends (\n arg: any,\n ...args: infer P\n ) => void\n ? (...args: [...P, ...[opts?: SendOpts<InferArg<P>>]]) => InvocationHandle\n : never;\n};\n\n// ----------- handlers ----------------------------------------------\n\nexport enum HandlerKind {\n SERVICE,\n EXCLUSIVE,\n SHARED,\n WORKFLOW,\n}\n\nexport type ServiceHandlerOpts<I, O> = {\n /**\n * Defines which Content-Type values are accepted when this handler is invoked via the ingress.\n * Wildcards are supported, for example `application/*` or `* / *`.\n *\n * If unset, `input.contentType` will be used as the default.\n *\n * This setting does not affect deserialization. To customize how the input is deserialized,\n * provide an `input` Serde.\n */\n accept?: string;\n\n /**\n * Serde used to deserialize the input parameter.\n * Defaults to `restate.serde.json`.\n *\n * Provide a custom Serde if the input is not JSON, or use\n * `restate.serde.binary` to skip serialization/deserialization altogether;\n * in that case the input parameter is a `Uint8Array`.\n */\n input?: Serde<I>;\n\n /**\n * Serde used to serialize the output value.\n * Defaults to `restate.serde.json`.\n *\n * Provide a custom Serde if the output is not JSON, or use\n * `restate.serde.binary` to skip serialization/deserialization altogether;\n * in that case the output value is a `Uint8Array`.\n */\n output?: Serde<O>;\n\n /**\n * Human-readable description of the handler, shown in documentation/admin tools.\n */\n description?: string;\n\n /**\n * Arbitrary key/value metadata for the handler. Exposed via the Admin API.\n */\n metadata?: Record<string, string>;\n\n /**\n * The retention duration of idempotent requests to this handler.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n idempotencyRetention?: Duration | number;\n\n /**\n * The journal retention for invocations to this handler.\n *\n * When a request has an idempotency key, `idempotencyRetention` caps the journal retention time.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n journalRetention?: Duration | number;\n\n /**\n * Guards against stalled invocations. Once this timeout expires, Restate requests a graceful\n * suspension of the invocation (preserving intermediate progress).\n *\n * If the invocation does not react to the suspension request, `abortTimeout` is used to abort it.\n *\n * Overrides the inactivity timeout set at the service level and the default configured in the Restate server.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n inactivityTimeout?: Duration | number;\n\n /**\n * Guards against invocations that fail to terminate after inactivity.\n * The abort timeout starts after `inactivityTimeout` expires and a graceful termination was requested.\n * When this timer expires, the invocation is aborted.\n *\n * This timer may interrupt user code. If more time is needed for graceful termination, increase this value.\n *\n * Overrides the abort timeout set at the service level and the default configured in the Restate server.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n abortTimeout?: Duration | number;\n\n /**\n * When set to `true`, this handler cannot be invoked via the Restate server HTTP or Kafka ingress;\n * it can only be called from other services.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n ingressPrivate?: boolean;\n\n /**\n * Retry policy to apply to all requests to this handler. For each unspecified field, the default value configured in the service or, if absent, in the restate-server configuration file, will be applied instead.\n */\n retryPolicy?: RetryPolicy;\n};\n\nexport type ObjectHandlerOpts<I, O> = ServiceHandlerOpts<I, O> & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this handler.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\nexport type WorkflowHandlerOpts<I, O> = ServiceHandlerOpts<I, O> & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this handler.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\nconst HANDLER_SYMBOL = Symbol(\"Handler\");\n\nexport class HandlerWrapper {\n public static from(\n kind: HandlerKind,\n handler: Function,\n opts?:\n | ServiceHandlerOpts<unknown, unknown>\n | ObjectHandlerOpts<unknown, unknown>\n | WorkflowHandlerOpts<unknown, unknown>\n ): HandlerWrapper {\n // we must create here a copy of the handler\n // to be able to reuse the original handler in other places.\n // like for example the same logic but under different routes.\n const handlerCopy = function (this: any, ...args: any[]): any {\n return handler.apply(this, args);\n };\n\n return new HandlerWrapper(\n kind,\n handlerCopy,\n opts?.input,\n opts?.output,\n opts?.accept,\n opts?.description,\n opts?.metadata,\n opts?.idempotencyRetention,\n opts?.journalRetention,\n opts?.inactivityTimeout,\n opts?.abortTimeout,\n opts?.ingressPrivate,\n opts !== undefined && \"enableLazyState\" in opts\n ? opts?.enableLazyState\n : undefined,\n opts?.retryPolicy\n );\n }\n\n public static fromHandler(handler: any): HandlerWrapper | undefined {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return handler[HANDLER_SYMBOL] as HandlerWrapper | undefined;\n }\n\n private constructor(\n public readonly kind: HandlerKind,\n private handler: Function,\n public readonly inputSerde?: Serde<unknown>,\n public readonly outputSerde?: Serde<unknown>,\n public readonly accept?: string,\n public readonly description?: string,\n public readonly metadata?: Record<string, string>,\n public readonly idempotencyRetention?: Duration | number,\n public readonly journalRetention?: Duration | number,\n public readonly inactivityTimeout?: Duration | number,\n public readonly abortTimeout?: Duration | number,\n public readonly ingressPrivate?: boolean,\n public readonly enableLazyState?: boolean,\n public readonly retryPolicy?: RetryPolicy,\n public readonly asTerminalError?: (error: any) => TerminalError | undefined\n ) {}\n\n bindInstance(t: unknown) {\n this.handler = this.handler.bind(t) as Function;\n }\n\n async invoke(context: { defaultSerde: Serde<any> }, input: Uint8Array) {\n let req: unknown;\n try {\n req = (this.inputSerde ?? context.defaultSerde).deserialize(input);\n } catch (e) {\n const error = ensureError(e);\n throw new TerminalError(`Failed to deserialize input: ${error.message}`, {\n errorCode: 400,\n });\n }\n\n const res: unknown = await this.handler(context, req);\n return (this.outputSerde ?? context.defaultSerde).serialize(res);\n }\n\n /**\n * Instead of a HandlerWrapper with a handler property,\n * return the original handler with a HandlerWrapper property.\n * This is needed to keep the appearance of regular functions\n * bound to an object, so that for example, `this.foo(ctx, arg)` would\n * work.\n */\n transpose<F>(): F {\n const handler = this.handler;\n const existing = HandlerWrapper.fromHandler(handler);\n if (existing !== undefined) {\n return handler as F;\n }\n Object.defineProperty(handler, HANDLER_SYMBOL, { value: this });\n return handler as F;\n }\n}\n\n// ----------- handler decorators ----------------------------------------------\nexport type RemoveVoidArgument<F> = F extends (\n ctx: infer C,\n arg: infer A\n) => infer R\n ? A extends void\n ? (ctx: C) => R\n : F\n : F;\n\nexport namespace handlers {\n /**\n * Create a service handler.\n *\n * @param opts additional configuration\n * @param fn the actual handler code to execute\n */\n export function handler<O, I = void>(\n opts: ServiceHandlerOpts<I, O>,\n fn: (ctx: Context, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn> {\n return HandlerWrapper.from(HandlerKind.SERVICE, fn, opts).transpose();\n }\n\n export namespace workflow {\n export function workflow<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: WorkflowHandlerOpts<I, O>,\n fn: (ctx: WorkflowContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n export function workflow<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: WorkflowContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n export function workflow<O, I = void>(\n optsOrFn:\n | WorkflowHandlerOpts<I, O>\n | ((ctx: WorkflowContext, input: I) => Promise<O>),\n fn?: (ctx: WorkflowContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.WORKFLOW, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies WorkflowHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.WORKFLOW, fn, opts).transpose();\n }\n\n /**\n * Creates a shared handler for a workflow.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: WorkflowHandlerOpts<I, O>,\n fn: (ctx: WorkflowSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a workflow.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: WorkflowSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a workflow\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<O, I = void>(\n optsOrFn:\n | WorkflowHandlerOpts<I, O>\n | ((ctx: WorkflowSharedContext, input: I) => Promise<O>),\n fn?: (ctx: WorkflowSharedContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();\n }\n }\n\n export namespace object {\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n * note : This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function exclusive<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: ObjectHandlerOpts<I, O>,\n fn: (ctx: ObjectContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n *\n * note 1: This applies only to a virtual object.\n * note 2: This is the default for virtual objects, so if no\n * additional reconfiguration is needed, you can simply\n * use the handler directly (no need to use exclusive).\n * This variant here is only for symmetry/convenance.\n *\n * @param fn the handler to execute\n */\n export function exclusive<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: ObjectContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n *\n * note 1: This applies only to a virtual object.\n * note 2: This is the default for virtual objects, so if no\n * additional reconfiguration is needed, you can simply\n * use the handler directly (no need to use exclusive).\n * This variant here is only for symmetry/convenance.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function exclusive<O, I = void>(\n optsOrFn:\n | ObjectHandlerOpts<I, O>\n | ((ctx: ObjectContext, input: I) => Promise<O>),\n fn?: (ctx: ObjectContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.EXCLUSIVE, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.EXCLUSIVE, fn, opts).transpose();\n }\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: ObjectHandlerOpts<I, O>,\n fn: (ctx: ObjectSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: ObjectSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<I, O>(\n optsOrFn:\n | ObjectHandlerOpts<I, O>\n | ((ctx: ObjectSharedContext, input: I) => Promise<O>),\n fn?: (ctx: ObjectSharedContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();\n }\n }\n}\n\n// ----------- services ----------------------------------------------\n\nexport type ServiceOpts<U> = {\n [K in keyof U]: U[K] extends ServiceHandler<U[K], Context>\n ? U[K]\n : ServiceHandler<U[K], Context>;\n};\n\nexport type RetryPolicy = {\n /**\n * Max number of retry attempts (including the initial).\n * When reached, the behavior specified in {@link onMaxAttempts} will be applied.\n */\n maxAttempts?: number;\n\n /**\n * What to do when max attempts are reached.\n *\n * If `pause`, the invocation will enter the paused state and can be manually resumed from the CLI/UI.\n *\n * If `kill`, the invocation will get automatically killed.\n */\n onMaxAttempts?: \"pause\" | \"kill\";\n\n /**\n * Initial interval for the first retry attempt.\n * Retry interval will grow by a factor specified in `exponentiationFactor`.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n initialInterval?: Duration | number;\n\n /**\n * Max interval between retries.\n * Retry interval will grow by a factor specified in `exponentiationFactor`.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxInterval?: Duration | number;\n\n /**\n * Exponentiation factor to use when computing the next retry delay.\n */\n exponentiationFactor?: number;\n};\n\nexport type ServiceOptions = {\n /**\n * The retention duration of idempotent requests to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n idempotencyRetention?: Duration | number;\n\n /**\n * Journal retention applied to all requests to all handlers of this service.\n *\n * When a request includes an idempotency key, `idempotencyRetention` caps the journal retention time.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n journalRetention?: Duration | number;\n\n /**\n * Guards against stalled invocations. Once this timeout expires, Restate requests a graceful\n * suspension of the invocation (preserving intermediate progress).\n *\n * If the invocation does not react to the suspension request, `abortTimeout` is used to abort it.\n *\n * Overrides the default inactivity timeout configured in the Restate server for all invocations to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n inactivityTimeout?: Duration | number;\n\n /**\n * Guards against invocations that fail to terminate after inactivity.\n * The abort timeout starts after `inactivityTimeout` expires and a graceful termination was requested.\n * When this timer expires, the invocation is aborted.\n *\n * This timer may interrupt user code. If more time is needed for graceful termination, increase this value.\n *\n * Overrides the default abort timeout configured in the Restate server for invocations to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n abortTimeout?: Duration | number;\n\n /**\n * When set to `true`, this service (and all its handlers) cannot be invoked via the Restate server\n * HTTP or Kafka ingress; it can only be called from other services.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n ingressPrivate?: boolean;\n\n /**\n * Retry policy to apply to all requests to this service. For each unspecified field, the default value configured in the restate-server configuration file will be applied instead.\n */\n retryPolicy?: RetryPolicy;\n\n /**\n * By default, Restate treats errors as terminal (non-retryable) only when they are instances of `TerminalError`.\n *\n * Use this hook to map domain-specific errors to `TerminalError` (or return `undefined` to keep them retryable).\n * When mapped to `TerminalError`, the error will not be retried.\n *\n * Note: This applies to errors thrown inside `ctx.run` closures as well as errors thrown by Restate handlers.\n *\n * Example:\n *\n * ```ts\n * class MyValidationError extends Error {}\n *\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * if (name.length === 0) {\n * throw new MyValidationError(\"Length too short\");\n * }\n * return `Hello ${name}`;\n * }\n * },\n * options: {\n * asTerminalError: (err) => {\n * if (err instanceof MyValidationError) {\n * // My validation error is terminal\n * return new restate.TerminalError(err.message, { errorCode: 400 });\n * }\n *\n * // Any other error is retryable\n * }\n * }\n * });\n * ```\n */\n asTerminalError?: (error: any) => TerminalError | undefined;\n\n /**\n * Default serde to use for requests, responses, state, side effects, awakeables, promises. Used when no other serde is specified.\n *\n * If not provided, defaults to `serde.json`.\n */\n serde?: Serde<any>;\n};\n\n/**\n * Define a Restate service.\n *\n * @example Here is an example of how to define a service:\n *\n * ```ts\n * const greeter = service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: Context, name: string) => {\n * return `Hello ${name}`;\n * }\n * }\n * });\n * ```\n *\n * To use the service, you can bind it to an endpoint:\n * ```\n * ...\n * endpoint.bind(greeter)\n * ```\n * @example To use a service, you can export its type to be used in a client:\n * ```\n * export type Greeter = typeof greeter;\n * ...\n * ...\n * import type { Greeter } from \"./greeter\";\n * const client = ctx.serviceClient<Greeter>({ name : \"greeter\"});\n * client.greet(\"World\").then(console.log);\n * ```\n *\n * @example Alternatively to avoid repeating the service name, you can:\n * ```\n * import type {Greeter} from \"./greeter\";\n * const Greeter: Greeter = { name : \"greeter\"};\n *\n * // now you can reference the service like this:\n * const client = ctx.serviceClient(Greeter);\n * ```\n *\n * @param name the service name\n * @param handlers the handlers for the service\n * @param description an optional description for the service\n * @param metadata an optional metadata for the service\n * @type P the name of the service\n * @type M the handlers for the service\n */\nexport const service = <P extends string, M>(service: {\n name: P;\n handlers: ServiceOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: ServiceOptions;\n}): ServiceDefinition<P, M> => {\n if (!service.handlers) {\n throw new Error(\"service must be defined\");\n }\n const handlers = Object.entries(service.handlers).map(([name, handler]) => {\n if (handler instanceof Function) {\n if (HandlerWrapper.fromHandler(handler) !== undefined) {\n return [name, handler];\n }\n return [\n name,\n HandlerWrapper.from(HandlerKind.SERVICE, handler).transpose(),\n ];\n }\n throw new TypeError(`Unexpected handler type ${name}`);\n });\n\n return {\n name: service.name,\n service: Object.fromEntries(handlers) as object,\n metadata: service.metadata,\n description: service.description,\n options: service.options,\n } as ServiceDefinition<P, M>;\n};\n\n// ----------- objects ----------------------------------------------\n\nexport type ObjectOpts<U> = {\n [K in keyof U]: U[K] extends ObjectHandler<U[K], ObjectContext<any>>\n ? U[K]\n : U[K] extends ObjectHandler<U[K], ObjectSharedContext<any>>\n ? U[K]\n :\n | ObjectHandler<U[K], ObjectContext<any>>\n | ObjectHandler<U[K], ObjectSharedContext<any>>;\n};\n\nexport type ObjectOptions = ServiceOptions & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this service.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\n/**\n * Define a Restate virtual object.\n *\n * @example Here is an example of how to define a virtual object:\n * ```ts\n * const counter = object({\n * name: \"counter\",\n * handlers: {\n * add: async (ctx: ObjectContext, amount: number) => {},\n * get: async (ctx: ObjectContext) => {}\n * }\n * })\n * ```\n *\n * @example To use the object, you can bind it to an endpoint:\n * ```ts\n * ...\n * endpoint.bind(counter)\n * ```\n *\n * @see to interact with the object, you can use the object client:\n * ```ts\n * ...\n * const client = ctx.objectClient<typeof counter>({ name: \"counter\"});\n * const res = await client.add(1)\n * ```\n *\n * ### Shared handlers\n *\n * Shared handlers are used to allow concurrent read-only access to the object.\n * This is useful when you want to allow multiple clients to read the object's state at the same time.\n * To define a shared handler, you can use the `shared` decorator as shown below:\n *\n * ```ts\n * const counter = object({\n * name: \"counter\",\n * handlers: {\n *\n * add: async (ctx: ObjectContext, amount: number) => { .. },\n *\n * get: handlers.object.shared(async (ctx: ObjectSharedContext) => {\n * return ctx.get<number>(\"count\");\n * })\n * }\n * });\n * ```\n *\n * @param name the name of the object\n * @param handlers the handlers for the object\n * @param description an optional description for the object\n * @param metadata an optional metadata for the object\n * @type P the name of the object\n * @type M the handlers for the object\n */\nexport const object = <P extends string, M>(object: {\n name: P;\n handlers: ObjectOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: ObjectOptions;\n}): VirtualObjectDefinition<P, M> => {\n if (!object.handlers) {\n throw new Error(\"object options must be defined\");\n }\n\n const handlers = Object.entries(object.handlers).map(([name, handler]) => {\n if (handler instanceof Function) {\n if (HandlerWrapper.fromHandler(handler) !== undefined) {\n return [name, handler];\n }\n\n return [\n name,\n HandlerWrapper.from(HandlerKind.EXCLUSIVE, handler).transpose(),\n ];\n }\n throw new TypeError(`Unexpected handler type ${name}`);\n });\n\n return {\n name: object.name,\n object: Object.fromEntries(handlers) as object,\n metadata: object.metadata,\n description: object.description,\n options: object.options,\n } as VirtualObjectDefinition<P, M>;\n};\n\n// ----------- workflows ----------------------------------------------\n\n/**\n * A workflow handlers is a type that describes the handlers for a workflow.\n * The handlers must contain exactly one handler named 'run', and this handler must accept as a first argument a WorkflowContext.\n * It can contain any number of additional handlers, which must accept as a first argument a WorkflowSharedContext.\n * The handlers can not be named 'workflowSubmit', 'workflowAttach', 'workflowOutput' - as these are reserved.\n * @see {@link workflow} for an example.\n */\nexport type WorkflowOpts<U> = {\n run: (ctx: WorkflowContext<any>, argument: any) => Promise<any>;\n} & {\n [K in keyof U]: K extends\n | \"workflowSubmit\"\n | \"workflowAttach\"\n | \"workflowOutput\"\n ? `${K} is a reserved keyword`\n : K extends \"run\"\n ? U[K] extends WorkflowHandler<U[K], WorkflowContext<any>>\n ? U[K]\n : \"An handler named 'run' must take as a first argument a WorkflowContext, and must return a Promise\"\n : U[K] extends WorkflowSharedHandler<U[K], WorkflowSharedContext<any>>\n ? U[K]\n : \"An handler other then 'run' must accept as a first argument a WorkflowSharedContext\";\n};\n\nexport type WorkflowOptions = ServiceOptions & {\n /**\n * The retention duration for this workflow.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n workflowRetention?: Duration | number;\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this service.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\n/**\n * Define a Restate workflow.\n *\n *\n * @example Here is an example of how to define a workflow:\n * ```ts\n * const mywf = workflow({\n * name: \"mywf\",\n * handlers: {\n * run: async (ctx: WorkflowContext, argument: any) => {\n * return \"Hello World\";\n * }\n * }\n * });\n * ```\n *\n * ### Note:\n * * That a workflow must contain exactly one handler named 'run', and this handler must accept as a first argument a WorkflowContext.\n * * The workflow handlers other than 'run' must accept as a first argument a WorkflowSharedContext.\n * * The workflow handlers can not be named 'workflowSubmit', 'workflowAttach', 'workflowOutput' - as these are reserved keywords.\n *\n * @example To use the workflow, you can bind it to an endpoint:\n * ```ts\n * endpoint.bind(mywf)\n * ```\n *\n * @example To interact with the workflow, you can use the workflow client:\n * ```ts\n * const client = ctx.workflowClient<typeof mywf>({ name: \"mywf\"});\n * const res = await client.run(\"Hello\");\n * ```\n *\n * To use the workflow client from any other environment (like a browser), please refer to the documentation.\n * https://docs.restate.dev\n *\n *\n *\n * @param name the workflow name\n * @param handlers the handlers for the workflow.\n */\nexport const workflow = <P extends string, M>(workflow: {\n name: P;\n handlers: WorkflowOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: WorkflowOptions;\n}): WorkflowDefinition<P, M> => {\n if (!workflow.handlers) {\n throw new Error(\"workflow must contain handlers\");\n }\n\n //\n // Add the main 'run' handler\n //\n const runHandler = workflow.handlers[\"run\"];\n let runWrapper: HandlerWrapper;\n\n if (runHandler instanceof HandlerWrapper) {\n runWrapper = runHandler;\n } else if (runHandler instanceof Function) {\n runWrapper =\n HandlerWrapper.fromHandler(runHandler) ??\n HandlerWrapper.from(HandlerKind.WORKFLOW, runHandler);\n } else {\n throw new TypeError(`Missing main workflow handler, named 'run'`);\n }\n if (runWrapper.kind !== HandlerKind.WORKFLOW) {\n throw new TypeError(\n `Workflow's main handler handler run, must be of type workflow'`\n );\n }\n\n const handlers = [[\"run\", runWrapper.transpose()]];\n\n //\n // Add all the shared handlers now\n //\n\n for (const [name, handler] of Object.entries(workflow.handlers)) {\n if (name === \"run\") {\n continue;\n }\n let wrapper: HandlerWrapper;\n\n if (handler instanceof HandlerWrapper) {\n wrapper = handler;\n } else if (handler instanceof Function) {\n wrapper =\n HandlerWrapper.fromHandler(handler) ??\n HandlerWrapper.from(HandlerKind.SHARED, handler);\n } else {\n throw new TypeError(`Unexpected handler type ${name}`);\n }\n if (wrapper.kind === HandlerKind.WORKFLOW) {\n throw new TypeError(\n `A workflow must contain exactly one handler annotated as workflow, named 'run'. Please use a shared handler for any additional handlers`\n );\n }\n handlers.push([name, wrapper.transpose()]);\n }\n\n return {\n name: workflow.name,\n workflow: Object.fromEntries(handlers) as object,\n metadata: workflow.metadata,\n description: workflow.description,\n options: workflow.options,\n } as WorkflowDefinition<P, M>;\n};\n"],"mappings":";;;AAoDA,IAAa,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","opts: ClientSendOptions<I>","parameter: unknown","opts:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined","kind: HandlerKind","handler: Function","inputSerde?: Serde<unknown>","outputSerde?: Serde<unknown>","accept?: string","description?: string","metadata?: Record<string, string>","idempotencyRetention?: Duration | number","journalRetention?: Duration | number","inactivityTimeout?: Duration | number","abortTimeout?: Duration | number","ingressPrivate?: boolean","enableLazyState?: boolean","retryPolicy?: RetryPolicy","asTerminalError?: (error: any) => TerminalError | undefined","req: unknown","res: unknown","workflow","service","handlers","object","runWrapper: HandlerWrapper","wrapper: HandlerWrapper"],"sources":["../../src/types/rpc.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-function-type */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport type {\n Context,\n GenericCall,\n GenericSend,\n InvocationHandle,\n InvocationPromise,\n ObjectContext,\n ObjectSharedContext,\n TypedState,\n UntypedState,\n WorkflowContext,\n WorkflowSharedContext,\n} from \"../context.js\";\n\nimport {\n type ServiceHandler,\n type ServiceDefinition,\n type ObjectHandler,\n type VirtualObjectDefinition,\n type WorkflowHandler,\n type WorkflowDefinition,\n type WorkflowSharedHandler,\n type Serde,\n type Duration,\n} from \"@restatedev/restate-sdk-core\";\nimport { ensureError, TerminalError } from \"./errors.js\";\n\n// ----------- rpc clients -------------------------------------------------------\n\nexport type ClientCallOptions<I, O> = {\n input?: Serde<I>;\n output?: Serde<O>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n\n /**\n * Observability name, recorded in the Restate journal.\n */\n name?: string;\n};\n\nexport class Opts<I, O> {\n /**\n * Create a call configuration from the provided options.\n *\n * @param opts the call configuration\n */\n public static from<I, O>(opts: ClientCallOptions<I, O>): Opts<I, O> {\n return new Opts<I, O>(opts);\n }\n\n private constructor(private readonly opts: ClientCallOptions<I, O>) {}\n\n public getOpts(): ClientCallOptions<I, O> {\n return this.opts;\n }\n}\n\nexport type ClientSendOptions<I> = {\n input?: Serde<I>;\n /**\n * Makes a type-safe one-way RPC to the specified target service, after a delay specified by the\n * milliseconds' argument.\n * This method is like setting up a fault-tolerant cron job that enqueues the message in a\n * message queue.\n * The handler calling this function does not have to stay active for the delay time.\n *\n * Both the delay timer and the message are durably stored in Restate and guaranteed to be reliably\n * delivered. The delivery happens no earlier than specified through the delay, but may happen\n * later, if the target service is down, or backpressuring the system.\n *\n * The delay message is journaled for durable execution and will thus not be duplicated when the\n * handler is re-invoked for retries or after suspending.\n *\n * This call will return immediately; the message sending happens asynchronously in the background.\n * Despite that, the message is guaranteed to be sent, because the completion of the invocation that\n * triggers the send (calls this function) happens logically after the sending. That means that any\n * failure where the message does not reach Restate also cannot complete this invocation, and will\n * hence recover this handler and (through the durable execution) recover the message to be sent.\n *\n * @example\n * ```ts\n * ctx.serviceSendClient(Service).anotherAction(1337, { delay: { seconds: 60 } });\n * ```\n */\n delay?: Duration | number;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n\n /**\n * Observability name, recorded in the Restate journal.\n */\n name?: string;\n};\n\nexport class SendOpts<I> {\n public static from<I>(opts: ClientSendOptions<I>): SendOpts<I> {\n return new SendOpts<I>(opts);\n }\n\n public getOpts(): ClientSendOptions<I> {\n return this.opts;\n }\n\n private constructor(private readonly opts: ClientSendOptions<I>) {}\n}\n\nexport namespace rpc {\n export const opts = <I, O>(opts: ClientCallOptions<I, O>) => Opts.from(opts);\n\n export const sendOpts = <I>(opts: ClientSendOptions<I>) =>\n SendOpts.from(opts);\n}\n\nfunction optsFromArgs(args: unknown[]): {\n parameter?: unknown;\n opts?:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined;\n} {\n let parameter: unknown;\n let opts:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined;\n switch (args.length) {\n case 0: {\n break;\n }\n case 1: {\n if (args[0] instanceof Opts) {\n opts = args[0].getOpts();\n } else if (args[0] instanceof SendOpts) {\n opts = args[0].getOpts();\n } else {\n parameter = args[0];\n }\n break;\n }\n case 2: {\n parameter = args[0];\n if (args[1] instanceof Opts) {\n opts = args[1].getOpts();\n } else if (args[1] instanceof SendOpts) {\n opts = args[1].getOpts();\n } else {\n throw new TypeError(\n \"The second argument must be either Opts or SendOpts\"\n );\n }\n break;\n }\n default: {\n throw new TypeError(\"unexpected number of arguments\");\n }\n }\n return {\n parameter,\n opts,\n };\n}\n\nexport const makeRpcCallProxy = <T>(\n genericCall: (call: GenericCall<unknown, unknown>) => Promise<unknown>,\n defaultSerde: Serde<any>,\n service: string,\n key?: string\n): T => {\n const clientProxy = new Proxy(\n {},\n {\n get: (_target, prop) => {\n const method = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n const requestSerde = opts?.input ?? defaultSerde;\n const responseSerde =\n (opts as ClientCallOptions<unknown, unknown> | undefined)?.output ??\n defaultSerde;\n return genericCall({\n service,\n method,\n parameter,\n key,\n headers: opts?.headers,\n inputSerde: requestSerde,\n outputSerde: responseSerde,\n idempotencyKey: opts?.idempotencyKey,\n name: opts?.name,\n });\n };\n },\n }\n );\n\n return clientProxy as T;\n};\n\nexport const makeRpcSendProxy = <T>(\n genericSend: (send: GenericSend<unknown>) => void,\n defaultSerde: Serde<any>,\n service: string,\n key?: string,\n legacyDelay?: number\n): T => {\n const clientProxy = new Proxy(\n {},\n {\n get: (_target, prop) => {\n const method = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n const requestSerde = opts?.input ?? defaultSerde;\n const delay =\n legacyDelay ??\n (opts as ClientSendOptions<unknown> | undefined)?.delay;\n return genericSend({\n service,\n method,\n parameter,\n key,\n headers: opts?.headers,\n delay,\n inputSerde: requestSerde,\n idempotencyKey: opts?.idempotencyKey,\n name: opts?.name,\n });\n };\n },\n }\n );\n\n return clientProxy as T;\n};\n\nexport type InferArg<P> = P extends [infer A, ...any[]] ? A : unknown;\n\nexport type Client<M> = {\n [K in keyof M as M[K] extends never ? never : K]: M[K] extends (\n arg: any,\n ...args: infer P\n ) => PromiseLike<infer O>\n ? (\n ...args: [...P, ...[opts?: Opts<InferArg<P>, O>]]\n ) => InvocationPromise<O>\n : never;\n};\n\nexport type SendClient<M> = {\n [K in keyof M as M[K] extends never ? never : K]: M[K] extends (\n arg: any,\n ...args: infer P\n ) => void\n ? (...args: [...P, ...[opts?: SendOpts<InferArg<P>>]]) => InvocationHandle\n : never;\n};\n\n// ----------- handlers ----------------------------------------------\n\nexport enum HandlerKind {\n SERVICE,\n EXCLUSIVE,\n SHARED,\n WORKFLOW,\n}\n\nexport type ServiceHandlerOpts<I, O> = {\n /**\n * Defines which Content-Type values are accepted when this handler is invoked via the ingress.\n * Wildcards are supported, for example `application/*` or `* / *`.\n *\n * If unset, `input.contentType` will be used as the default.\n *\n * This setting does not affect deserialization. To customize how the input is deserialized,\n * provide an `input` Serde.\n */\n accept?: string;\n\n /**\n * Serde used to deserialize the input parameter.\n * Defaults to `restate.serde.json`.\n *\n * Provide a custom Serde if the input is not JSON, or use\n * `restate.serde.binary` to skip serialization/deserialization altogether;\n * in that case the input parameter is a `Uint8Array`.\n */\n input?: Serde<I>;\n\n /**\n * Serde used to serialize the output value.\n * Defaults to `restate.serde.json`.\n *\n * Provide a custom Serde if the output is not JSON, or use\n * `restate.serde.binary` to skip serialization/deserialization altogether;\n * in that case the output value is a `Uint8Array`.\n */\n output?: Serde<O>;\n\n /**\n * Human-readable description of the handler, shown in documentation/admin tools.\n */\n description?: string;\n\n /**\n * Arbitrary key/value metadata for the handler. Exposed via the Admin API.\n */\n metadata?: Record<string, string>;\n\n /**\n * The retention duration of idempotent requests to this handler.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n idempotencyRetention?: Duration | number;\n\n /**\n * The journal retention for invocations to this handler.\n *\n * When a request has an idempotency key, `idempotencyRetention` caps the journal retention time.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n journalRetention?: Duration | number;\n\n /**\n * Guards against stalled invocations. Once this timeout expires, Restate requests a graceful\n * suspension of the invocation (preserving intermediate progress).\n *\n * If the invocation does not react to the suspension request, `abortTimeout` is used to abort it.\n *\n * Overrides the inactivity timeout set at the service level and the default configured in the Restate server.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n inactivityTimeout?: Duration | number;\n\n /**\n * Guards against invocations that fail to terminate after inactivity.\n * The abort timeout starts after `inactivityTimeout` expires and a graceful termination was requested.\n * When this timer expires, the invocation is aborted.\n *\n * This timer may interrupt user code. If more time is needed for graceful termination, increase this value.\n *\n * Overrides the abort timeout set at the service level and the default configured in the Restate server.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n abortTimeout?: Duration | number;\n\n /**\n * When set to `true`, this handler cannot be invoked via the Restate server HTTP or Kafka ingress;\n * it can only be called from other services.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n ingressPrivate?: boolean;\n\n /**\n * Retry policy to apply to all requests to this handler. For each unspecified field, the default value configured in the service or, if absent, in the restate-server configuration file, will be applied instead.\n */\n retryPolicy?: RetryPolicy;\n};\n\nexport type ObjectHandlerOpts<I, O> = ServiceHandlerOpts<I, O> & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this handler.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\nexport type WorkflowHandlerOpts<I, O> = ServiceHandlerOpts<I, O> & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this handler.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\nconst HANDLER_SYMBOL = Symbol(\"Handler\");\n\nexport class HandlerWrapper {\n public static from(\n kind: HandlerKind,\n handler: Function,\n opts?:\n | ServiceHandlerOpts<unknown, unknown>\n | ObjectHandlerOpts<unknown, unknown>\n | WorkflowHandlerOpts<unknown, unknown>\n ): HandlerWrapper {\n // we must create here a copy of the handler\n // to be able to reuse the original handler in other places.\n // like for example the same logic but under different routes.\n const handlerCopy = function (this: any, ...args: any[]): any {\n return handler.apply(this, args);\n };\n\n return new HandlerWrapper(\n kind,\n handlerCopy,\n opts?.input,\n opts?.output,\n opts?.accept,\n opts?.description,\n opts?.metadata,\n opts?.idempotencyRetention,\n opts?.journalRetention,\n opts?.inactivityTimeout,\n opts?.abortTimeout,\n opts?.ingressPrivate,\n opts !== undefined && \"enableLazyState\" in opts\n ? opts?.enableLazyState\n : undefined,\n opts?.retryPolicy\n );\n }\n\n public static fromHandler(handler: any): HandlerWrapper | undefined {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return handler[HANDLER_SYMBOL] as HandlerWrapper | undefined;\n }\n\n private constructor(\n public readonly kind: HandlerKind,\n private handler: Function,\n public readonly inputSerde?: Serde<unknown>,\n public readonly outputSerde?: Serde<unknown>,\n public readonly accept?: string,\n public readonly description?: string,\n public readonly metadata?: Record<string, string>,\n public readonly idempotencyRetention?: Duration | number,\n public readonly journalRetention?: Duration | number,\n public readonly inactivityTimeout?: Duration | number,\n public readonly abortTimeout?: Duration | number,\n public readonly ingressPrivate?: boolean,\n public readonly enableLazyState?: boolean,\n public readonly retryPolicy?: RetryPolicy,\n public readonly asTerminalError?: (error: any) => TerminalError | undefined\n ) {}\n\n bindInstance(t: unknown) {\n this.handler = this.handler.bind(t) as Function;\n }\n\n async invoke(context: { defaultSerde: Serde<any> }, input: Uint8Array) {\n let req: unknown;\n try {\n req = (this.inputSerde ?? context.defaultSerde).deserialize(input);\n } catch (e) {\n const error = ensureError(e);\n throw new TerminalError(`Failed to deserialize input: ${error.message}`, {\n errorCode: 400,\n });\n }\n\n const res: unknown = await this.handler(context, req);\n return (this.outputSerde ?? context.defaultSerde).serialize(res);\n }\n\n /**\n * Instead of a HandlerWrapper with a handler property,\n * return the original handler with a HandlerWrapper property.\n * This is needed to keep the appearance of regular functions\n * bound to an object, so that for example, `this.foo(ctx, arg)` would\n * work.\n */\n transpose<F>(): F {\n const handler = this.handler;\n const existing = HandlerWrapper.fromHandler(handler);\n if (existing !== undefined) {\n return handler as F;\n }\n Object.defineProperty(handler, HANDLER_SYMBOL, { value: this });\n return handler as F;\n }\n}\n\n// ----------- handler decorators ----------------------------------------------\nexport type RemoveVoidArgument<F> = F extends (\n ctx: infer C,\n arg: infer A\n) => infer R\n ? A extends void\n ? (ctx: C) => R\n : F\n : F;\n\nexport namespace handlers {\n /**\n * Create a service handler.\n *\n * @param opts additional configuration\n * @param fn the actual handler code to execute\n */\n export function handler<O, I = void>(\n opts: ServiceHandlerOpts<I, O>,\n fn: (ctx: Context, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn> {\n return HandlerWrapper.from(HandlerKind.SERVICE, fn, opts).transpose();\n }\n\n export namespace workflow {\n export function workflow<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: WorkflowHandlerOpts<I, O>,\n fn: (ctx: WorkflowContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n export function workflow<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: WorkflowContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n export function workflow<O, I = void>(\n optsOrFn:\n | WorkflowHandlerOpts<I, O>\n | ((ctx: WorkflowContext, input: I) => Promise<O>),\n fn?: (ctx: WorkflowContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.WORKFLOW, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies WorkflowHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.WORKFLOW, fn, opts).transpose();\n }\n\n /**\n * Creates a shared handler for a workflow.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: WorkflowHandlerOpts<I, O>,\n fn: (ctx: WorkflowSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a workflow.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: WorkflowSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a workflow\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<O, I = void>(\n optsOrFn:\n | WorkflowHandlerOpts<I, O>\n | ((ctx: WorkflowSharedContext, input: I) => Promise<O>),\n fn?: (ctx: WorkflowSharedContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();\n }\n }\n\n export namespace object {\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n * note : This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function exclusive<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: ObjectHandlerOpts<I, O>,\n fn: (ctx: ObjectContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n *\n * note 1: This applies only to a virtual object.\n * note 2: This is the default for virtual objects, so if no\n * additional reconfiguration is needed, you can simply\n * use the handler directly (no need to use exclusive).\n * This variant here is only for symmetry/convenance.\n *\n * @param fn the handler to execute\n */\n export function exclusive<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: ObjectContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n *\n * note 1: This applies only to a virtual object.\n * note 2: This is the default for virtual objects, so if no\n * additional reconfiguration is needed, you can simply\n * use the handler directly (no need to use exclusive).\n * This variant here is only for symmetry/convenance.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function exclusive<O, I = void>(\n optsOrFn:\n | ObjectHandlerOpts<I, O>\n | ((ctx: ObjectContext, input: I) => Promise<O>),\n fn?: (ctx: ObjectContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.EXCLUSIVE, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.EXCLUSIVE, fn, opts).transpose();\n }\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: ObjectHandlerOpts<I, O>,\n fn: (ctx: ObjectSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: ObjectSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<I, O>(\n optsOrFn:\n | ObjectHandlerOpts<I, O>\n | ((ctx: ObjectSharedContext, input: I) => Promise<O>),\n fn?: (ctx: ObjectSharedContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();\n }\n }\n}\n\n// ----------- services ----------------------------------------------\n\nexport type ServiceOpts<U> = {\n [K in keyof U]: U[K] extends ServiceHandler<U[K], Context>\n ? U[K]\n : ServiceHandler<U[K], Context>;\n};\n\nexport type RetryPolicy = {\n /**\n * Max number of retry attempts (including the initial).\n * When reached, the behavior specified in {@link onMaxAttempts} will be applied.\n */\n maxAttempts?: number;\n\n /**\n * What to do when max attempts are reached.\n *\n * If `pause`, the invocation will enter the paused state and can be manually resumed from the CLI/UI.\n *\n * If `kill`, the invocation will get automatically killed.\n */\n onMaxAttempts?: \"pause\" | \"kill\";\n\n /**\n * Initial interval for the first retry attempt.\n * Retry interval will grow by a factor specified in `exponentiationFactor`.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n initialInterval?: Duration | number;\n\n /**\n * Max interval between retries.\n * Retry interval will grow by a factor specified in `exponentiationFactor`.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxInterval?: Duration | number;\n\n /**\n * Exponentiation factor to use when computing the next retry delay.\n */\n exponentiationFactor?: number;\n};\n\nexport type ServiceOptions = {\n /**\n * The retention duration of idempotent requests to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n idempotencyRetention?: Duration | number;\n\n /**\n * Journal retention applied to all requests to all handlers of this service.\n *\n * When a request includes an idempotency key, `idempotencyRetention` caps the journal retention time.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n journalRetention?: Duration | number;\n\n /**\n * Guards against stalled invocations. Once this timeout expires, Restate requests a graceful\n * suspension of the invocation (preserving intermediate progress).\n *\n * If the invocation does not react to the suspension request, `abortTimeout` is used to abort it.\n *\n * Overrides the default inactivity timeout configured in the Restate server for all invocations to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n inactivityTimeout?: Duration | number;\n\n /**\n * Guards against invocations that fail to terminate after inactivity.\n * The abort timeout starts after `inactivityTimeout` expires and a graceful termination was requested.\n * When this timer expires, the invocation is aborted.\n *\n * This timer may interrupt user code. If more time is needed for graceful termination, increase this value.\n *\n * Overrides the default abort timeout configured in the Restate server for invocations to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n abortTimeout?: Duration | number;\n\n /**\n * When set to `true`, this service (and all its handlers) cannot be invoked via the Restate server\n * HTTP or Kafka ingress; it can only be called from other services.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n ingressPrivate?: boolean;\n\n /**\n * Retry policy to apply to all requests to this service. For each unspecified field, the default value configured in the restate-server configuration file will be applied instead.\n */\n retryPolicy?: RetryPolicy;\n\n /**\n * By default, Restate treats errors as terminal (non-retryable) only when they are instances of `TerminalError`.\n *\n * Use this hook to map domain-specific errors to `TerminalError` (or return `undefined` to keep them retryable).\n * When mapped to `TerminalError`, the error will not be retried.\n *\n * Note: This applies to errors thrown inside `ctx.run` closures as well as errors thrown by Restate handlers.\n *\n * Example:\n *\n * ```ts\n * class MyValidationError extends Error {}\n *\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * if (name.length === 0) {\n * throw new MyValidationError(\"Length too short\");\n * }\n * return `Hello ${name}`;\n * }\n * },\n * options: {\n * asTerminalError: (err) => {\n * if (err instanceof MyValidationError) {\n * // My validation error is terminal\n * return new restate.TerminalError(err.message, { errorCode: 400 });\n * }\n *\n * // Any other error is retryable\n * }\n * }\n * });\n * ```\n */\n asTerminalError?: (error: any) => TerminalError | undefined;\n\n /**\n * Default serde to use for requests, responses, state, side effects, awakeables, promises. Used when no other serde is specified.\n *\n * If not provided, defaults to `serde.json`.\n */\n serde?: Serde<any>;\n};\n\n/**\n * Define a Restate service.\n *\n * @example Here is an example of how to define a service:\n *\n * ```ts\n * const greeter = service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: Context, name: string) => {\n * return `Hello ${name}`;\n * }\n * }\n * });\n * ```\n *\n * To use the service, you can bind it to an endpoint:\n * ```\n * ...\n * endpoint.bind(greeter)\n * ```\n * @example To use a service, you can export its type to be used in a client:\n * ```\n * export type Greeter = typeof greeter;\n * ...\n * ...\n * import type { Greeter } from \"./greeter\";\n * const client = ctx.serviceClient<Greeter>({ name : \"greeter\"});\n * client.greet(\"World\").then(console.log);\n * ```\n *\n * @example Alternatively to avoid repeating the service name, you can:\n * ```\n * import type {Greeter} from \"./greeter\";\n * const Greeter: Greeter = { name : \"greeter\"};\n *\n * // now you can reference the service like this:\n * const client = ctx.serviceClient(Greeter);\n * ```\n *\n * @param name the service name\n * @param handlers the handlers for the service\n * @param description an optional description for the service\n * @param metadata an optional metadata for the service\n * @type P the name of the service\n * @type M the handlers for the service\n */\nexport const service = <P extends string, M>(service: {\n name: P;\n handlers: ServiceOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: ServiceOptions;\n}): ServiceDefinition<P, M> => {\n if (!service.handlers) {\n throw new Error(\"service must be defined\");\n }\n const handlers = Object.entries(service.handlers).map(([name, handler]) => {\n if (handler instanceof Function) {\n if (HandlerWrapper.fromHandler(handler) !== undefined) {\n return [name, handler];\n }\n return [\n name,\n HandlerWrapper.from(HandlerKind.SERVICE, handler).transpose(),\n ];\n }\n throw new TypeError(`Unexpected handler type ${name}`);\n });\n\n return {\n name: service.name,\n service: Object.fromEntries(handlers) as object,\n metadata: service.metadata,\n description: service.description,\n options: service.options,\n } as ServiceDefinition<P, M>;\n};\n\n// ----------- objects ----------------------------------------------\n\nexport type ObjectOpts<U> = {\n [K in keyof U]: U[K] extends ObjectHandler<U[K], ObjectContext<any>>\n ? U[K]\n : U[K] extends ObjectHandler<U[K], ObjectSharedContext<any>>\n ? U[K]\n :\n | ObjectHandler<U[K], ObjectContext<any>>\n | ObjectHandler<U[K], ObjectSharedContext<any>>;\n};\n\nexport type ObjectOptions = ServiceOptions & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this service.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\n/**\n * Define a Restate virtual object.\n *\n * @example Here is an example of how to define a virtual object:\n * ```ts\n * const counter = object({\n * name: \"counter\",\n * handlers: {\n * add: async (ctx: ObjectContext, amount: number) => {},\n * get: async (ctx: ObjectContext) => {}\n * }\n * })\n * ```\n *\n * @example To use the object, you can bind it to an endpoint:\n * ```ts\n * ...\n * endpoint.bind(counter)\n * ```\n *\n * @see to interact with the object, you can use the object client:\n * ```ts\n * ...\n * const client = ctx.objectClient<typeof counter>({ name: \"counter\"});\n * const res = await client.add(1)\n * ```\n *\n * ### Shared handlers\n *\n * Shared handlers are used to allow concurrent read-only access to the object.\n * This is useful when you want to allow multiple clients to read the object's state at the same time.\n * To define a shared handler, you can use the `shared` decorator as shown below:\n *\n * ```ts\n * const counter = object({\n * name: \"counter\",\n * handlers: {\n *\n * add: async (ctx: ObjectContext, amount: number) => { .. },\n *\n * get: handlers.object.shared(async (ctx: ObjectSharedContext) => {\n * return ctx.get<number>(\"count\");\n * })\n * }\n * });\n * ```\n *\n * @param name the name of the object\n * @param handlers the handlers for the object\n * @param description an optional description for the object\n * @param metadata an optional metadata for the object\n * @type P the name of the object\n * @type M the handlers for the object\n */\nexport const object = <P extends string, M>(object: {\n name: P;\n handlers: ObjectOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: ObjectOptions;\n}): VirtualObjectDefinition<P, M> => {\n if (!object.handlers) {\n throw new Error(\"object options must be defined\");\n }\n\n const handlers = Object.entries(object.handlers).map(([name, handler]) => {\n if (handler instanceof Function) {\n if (HandlerWrapper.fromHandler(handler) !== undefined) {\n return [name, handler];\n }\n\n return [\n name,\n HandlerWrapper.from(HandlerKind.EXCLUSIVE, handler).transpose(),\n ];\n }\n throw new TypeError(`Unexpected handler type ${name}`);\n });\n\n return {\n name: object.name,\n object: Object.fromEntries(handlers) as object,\n metadata: object.metadata,\n description: object.description,\n options: object.options,\n } as VirtualObjectDefinition<P, M>;\n};\n\n// ----------- workflows ----------------------------------------------\n\n/**\n * A workflow handlers is a type that describes the handlers for a workflow.\n * The handlers must contain exactly one handler named 'run', and this handler must accept as a first argument a WorkflowContext.\n * It can contain any number of additional handlers, which must accept as a first argument a WorkflowSharedContext.\n * The handlers can not be named 'workflowSubmit', 'workflowAttach', 'workflowOutput' - as these are reserved.\n * @see {@link workflow} for an example.\n */\nexport type WorkflowOpts<U> = {\n run: (ctx: WorkflowContext<any>, argument: any) => Promise<any>;\n} & {\n [K in keyof U]: K extends\n | \"workflowSubmit\"\n | \"workflowAttach\"\n | \"workflowOutput\"\n ? `${K} is a reserved keyword`\n : K extends \"run\"\n ? U[K] extends WorkflowHandler<U[K], WorkflowContext<any>>\n ? U[K]\n : \"An handler named 'run' must take as a first argument a WorkflowContext, and must return a Promise\"\n : U[K] extends WorkflowSharedHandler<U[K], WorkflowSharedContext<any>>\n ? U[K]\n : \"An handler other then 'run' must accept as a first argument a WorkflowSharedContext\";\n};\n\nexport type WorkflowOptions = ServiceOptions & {\n /**\n * The retention duration for this workflow.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n workflowRetention?: Duration | number;\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this service.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\n/**\n * Define a Restate workflow.\n *\n *\n * @example Here is an example of how to define a workflow:\n * ```ts\n * const mywf = workflow({\n * name: \"mywf\",\n * handlers: {\n * run: async (ctx: WorkflowContext, argument: any) => {\n * return \"Hello World\";\n * }\n * }\n * });\n * ```\n *\n * ### Note:\n * * That a workflow must contain exactly one handler named 'run', and this handler must accept as a first argument a WorkflowContext.\n * * The workflow handlers other than 'run' must accept as a first argument a WorkflowSharedContext.\n * * The workflow handlers can not be named 'workflowSubmit', 'workflowAttach', 'workflowOutput' - as these are reserved keywords.\n *\n * @example To use the workflow, you can bind it to an endpoint:\n * ```ts\n * endpoint.bind(mywf)\n * ```\n *\n * @example To interact with the workflow, you can use the workflow client:\n * ```ts\n * const client = ctx.workflowClient<typeof mywf>({ name: \"mywf\"});\n * const res = await client.run(\"Hello\");\n * ```\n *\n * To use the workflow client from any other environment (like a browser), please refer to the documentation.\n * https://docs.restate.dev\n *\n *\n *\n * @param name the workflow name\n * @param handlers the handlers for the workflow.\n */\nexport const workflow = <P extends string, M>(workflow: {\n name: P;\n handlers: WorkflowOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: WorkflowOptions;\n}): WorkflowDefinition<P, M> => {\n if (!workflow.handlers) {\n throw new Error(\"workflow must contain handlers\");\n }\n\n //\n // Add the main 'run' handler\n //\n const runHandler = workflow.handlers[\"run\"];\n let runWrapper: HandlerWrapper;\n\n if (runHandler instanceof HandlerWrapper) {\n runWrapper = runHandler;\n } else if (runHandler instanceof Function) {\n runWrapper =\n HandlerWrapper.fromHandler(runHandler) ??\n HandlerWrapper.from(HandlerKind.WORKFLOW, runHandler);\n } else {\n throw new TypeError(`Missing main workflow handler, named 'run'`);\n }\n if (runWrapper.kind !== HandlerKind.WORKFLOW) {\n throw new TypeError(\n `Workflow's main handler handler run, must be of type workflow'`\n );\n }\n\n const handlers = [[\"run\", runWrapper.transpose()]];\n\n //\n // Add all the shared handlers now\n //\n\n for (const [name, handler] of Object.entries(workflow.handlers)) {\n if (name === \"run\") {\n continue;\n }\n let wrapper: HandlerWrapper;\n\n if (handler instanceof HandlerWrapper) {\n wrapper = handler;\n } else if (handler instanceof Function) {\n wrapper =\n HandlerWrapper.fromHandler(handler) ??\n HandlerWrapper.from(HandlerKind.SHARED, handler);\n } else {\n throw new TypeError(`Unexpected handler type ${name}`);\n }\n if (wrapper.kind === HandlerKind.WORKFLOW) {\n throw new TypeError(\n `A workflow must contain exactly one handler annotated as workflow, named 'run'. Please use a shared handler for any additional handlers`\n );\n }\n handlers.push([name, wrapper.transpose()]);\n }\n\n return {\n name: workflow.name,\n workflow: Object.fromEntries(handlers) as object,\n metadata: workflow.metadata,\n description: workflow.description,\n options: workflow.options,\n } as WorkflowDefinition<P, M>;\n};\n"],"mappings":";;;AAyDA,IAAa,OAAb,MAAa,KAAW;;;;;;CAMtB,OAAc,KAAW,MAA2C;AAClE,SAAO,IAAI,KAAW,KAAK;;CAG7B,AAAQ,YAAY,AAAiBA,MAA+B;EAA/B;;CAErC,AAAO,UAAmC;AACxC,SAAO,KAAK;;;AAyChB,IAAa,WAAb,MAAa,SAAY;CACvB,OAAc,KAAQ,MAAyC;AAC7D,SAAO,IAAI,SAAY,KAAK;;CAG9B,AAAO,UAAgC;AACrC,SAAO,KAAK;;CAG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;;;;;;;;;;;;;;AAsFH,MAAa,YAAiC,eAMd;AAC9B,KAAI,CAACH,WAAS,SACZ,OAAM,IAAI,MAAM,iCAAiC;CAMnD,MAAM,aAAaA,WAAS,SAAS;CACrC,IAAII;AAEJ,KAAI,sBAAsB,eACxB,cAAa;UACJ,sBAAsB,SAC/B,cACE,eAAe,YAAY,WAAW,IACtC,eAAe,KAAK,YAAY,UAAU,WAAW;KAEvD,OAAM,IAAI,UAAU,6CAA6C;AAEnE,KAAI,WAAW,SAAS,YAAY,SAClC,OAAM,IAAI,UACR,iEACD;CAGH,MAAMF,aAAW,CAAC,CAAC,OAAO,WAAW,WAAW,CAAC,CAAC;AAMlD,MAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQF,WAAS,SAAS,EAAE;AAC/D,MAAI,SAAS,MACX;EAEF,IAAIK;AAEJ,MAAI,mBAAmB,eACrB,WAAU;WACD,mBAAmB,SAC5B,WACE,eAAe,YAAY,QAAQ,IACnC,eAAe,KAAK,YAAY,QAAQ,QAAQ;MAElD,OAAM,IAAI,UAAU,2BAA2B,OAAO;AAExD,MAAI,QAAQ,SAAS,YAAY,SAC/B,OAAM,IAAI,UACR,0IACD;AAEH,aAAS,KAAK,CAAC,MAAM,QAAQ,WAAW,CAAC,CAAC;;AAG5C,QAAO;EACL,MAAML,WAAS;EACf,UAAU,OAAO,YAAYE,WAAS;EACtC,UAAUF,WAAS;EACnB,aAAaA,WAAS;EACtB,SAASA,WAAS;EACnB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restatedev/restate-sdk-cloudflare-workers",
3
- "version": "1.10.2",
3
+ "version": "1.10.3",
4
4
  "description": "Typescript SDK for Restate",
5
5
  "author": "Restate Developers",
6
6
  "email": "code@restate.dev",
@@ -35,11 +35,11 @@
35
35
  "access": "public"
36
36
  },
37
37
  "dependencies": {
38
- "@restatedev/restate-sdk-core": "1.10.2"
38
+ "@restatedev/restate-sdk-core": "1.10.3"
39
39
  },
40
40
  "devDependencies": {
41
41
  "@types/aws-lambda": "^8.10.115",
42
- "@restatedev/restate-sdk": "1.10.2"
42
+ "@restatedev/restate-sdk": "1.10.3"
43
43
  },
44
44
  "typesVersions": {
45
45
  "*": {