@restatedev/restate-sdk 1.15.1 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -16
- package/dist/common_api.d.cts.map +1 -1
- package/dist/common_api.d.ts.map +1 -1
- package/dist/context.d.cts +4 -1
- package/dist/context.d.cts.map +1 -1
- package/dist/context.d.ts +4 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js.map +1 -1
- package/dist/context_impl.cjs +2 -0
- package/dist/context_impl.d.ts.map +1 -1
- package/dist/context_impl.js +2 -0
- package/dist/context_impl.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -54,21 +54,14 @@ This library follows [Semantic Versioning](https://semver.org/).
|
|
|
54
54
|
|
|
55
55
|
The compatibility with Restate is described in the following table:
|
|
56
56
|
|
|
57
|
-
| Restate Server\sdk-typescript |
|
|
58
|
-
|
|
59
|
-
|
|
|
60
|
-
| 1.
|
|
61
|
-
| 1.
|
|
62
|
-
| 1.5 | ⚠ <sup>(4)</sup> | ✅ | ✅ | ✅ | ✅ <sup>(3)</sup> | ✅ <sup>(3)</sup> |
|
|
63
|
-
| 1.6 | ⚠ <sup>(4)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ |
|
|
64
|
-
| 1.7 | ⚠ <sup>(4)</sup> | ✅ | ✅ | ✅ | ✅ | ✅ <sup>(5)</sup> |
|
|
57
|
+
| Restate Server\sdk-typescript | 1.11 - 1.14 | 1.15 - 1.16 |
|
|
58
|
+
|-------------------------------|-------------|-------------|
|
|
59
|
+
| 1.5 | ✅ | ✅ |
|
|
60
|
+
| 1.6 | ✅ | ✅ |
|
|
61
|
+
| 1.7 | ✅ | ✅ |
|
|
65
62
|
|
|
66
|
-
|
|
63
|
+
Some features require a minimum version of both Restate and the SDK:
|
|
67
64
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
<sup>(4)</sup> **Warning** SDK versions <= 1.4 are deprecated, and cannot be registered anymore. Check the [Restate 1.5 release notes](https://github.com/restatedev/restate/releases/tag/v1.5.0) for more info.
|
|
73
|
-
|
|
74
|
-
<sup>(5)</sup> **Note** `ctx.run`'s `retryPolicy` pause and `PauseError` work on Restate 1.7 setting `RESTATE_EXPERIMENTAL_ENABLE_PROTOCOL_V7=true` on the Restate Server. Check the in-code documentation for more details.
|
|
65
|
+
- **`TerminalError.metadata`**: requires Restate >= 1.6 with sdk-typescript >= 1.11. Check the in-code documentation for more details.
|
|
66
|
+
- **`ctx.run`'s `retryPolicy` pause and `PauseError`**: requires Restate >= 1.7 with sdk-typescript >= 1.15, setting `RESTATE_EXPERIMENTAL_ENABLE_PROTOCOL_V7=true` on the Restate Server. Check the in-code documentation for more details.
|
|
67
|
+
- **Scope and limit key**: requires Restate >= 1.7 with sdk-typescript >= 1.15
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common_api.d.cts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;cA4Ca;;;
|
|
1
|
+
{"version":3,"file":"common_api.d.cts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;cA4Ca;;;6GAwG264B,IAAA,QAAA,EAAA;;EAxG364B,GAAA,CAAA,gBAAA,uBAAmC,CAAA,OAAA,CAAA,EAAA,CAAA,CAAA,MAAA,GAAA,CAAA,gBAAA,QAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA;oHAwG248B,IAAA,qBAAA,QAAA,EAAA;;;;;KAnG/68B,wBAAwB,eAAe;cA2FtC,6BAAoB,QAAA,CAAA;cACpB,4BAAmB,QAAA,CAAA,MAAA,CAAA;cACnB,kCAAyB,QAAA,CAAA,MAAA,CAAA;cACzB,8BAAqB,QAAA,CAAA,QAAA,CAAA;AAKy58B,cAJ968B,2BAI868B,EAAA,OAJn58B,QAAA,CAAA,QAAA,CAAA,MAIm58B"}
|
package/dist/common_api.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common_api.d.ts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;cA4Ca;;;
|
|
1
|
+
{"version":3,"file":"common_api.d.ts","names":[],"sources":["../src/common_api.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;cA4Ca;;;6GAwG264B,IAAA,QAAA,EAAA;;EAxG364B,GAAA,CAAA,gBAAA,uBAAmC,CAAA,OAAA,CAAA,EAAA,CAAA,CAAA,MAAA,GAAA,CAAA,gBAAA,QAAA,EAAA,CAAA,MAAA,CAAA,CAAA,CAAA;oHAwG248B,IAAA,qBAAA,QAAA,EAAA;;;;;KAnG/68B,wBAAwB,eAAe;cA2FtC,6BAAoB,QAAA,CAAA;cACpB,4BAAmB,QAAA,CAAA,MAAA,CAAA;cACnB,kCAAyB,QAAA,CAAA,MAAA,CAAA;cACzB,8BAAqB,QAAA,CAAA,QAAA,CAAA;AAKy58B,cAJ968B,2BAI868B,EAAA,OAJn58B,QAAA,CAAA,QAAA,CAAA,MAIm58B"}
|
package/dist/context.d.cts
CHANGED
|
@@ -247,7 +247,7 @@ type GenericSend<REQ> = {
|
|
|
247
247
|
* @experimental
|
|
248
248
|
* @interface
|
|
249
249
|
*/
|
|
250
|
-
type ScopedContext = Pick<Context, "serviceClient" | "serviceSendClient" | "workflowClient" | "workflowSendClient">;
|
|
250
|
+
type ScopedContext = Pick<Context, "serviceClient" | "serviceSendClient" | "objectClient" | "objectSendClient" | "workflowClient" | "workflowSendClient">;
|
|
251
251
|
/**
|
|
252
252
|
* The context that gives access to all Restate-backed operations, for example
|
|
253
253
|
* - sending reliable messages / RPC through Restate
|
|
@@ -548,6 +548,9 @@ interface Context extends RestateContext {
|
|
|
548
548
|
* // Route a call into a named scope
|
|
549
549
|
* await ctx.scope("tenant-123").serviceClient(MyService).process(payload);
|
|
550
550
|
*
|
|
551
|
+
* // Virtual objects can be scoped too — the object key is part of the scoped identity
|
|
552
|
+
* await ctx.scope("tenant-123").objectClient(MyObject, "obj-key").update(payload);
|
|
553
|
+
*
|
|
551
554
|
* // Idempotency keys are scoped — "req-1" in "tenant-123" is distinct from "req-1" in "tenant-456"
|
|
552
555
|
* await ctx.scope("tenant-123").serviceClient(MyService)
|
|
553
556
|
* .process(payload, rpc.opts({ idempotencyKey: "req-1" }));
|
package/dist/context.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.cts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;UAuCiB,MAAA;;EAAA,OAAA,EAAM,MAAA;EAaN,GAAA,CAAA,EAAA,MAAO;EACL,QAAA,EAAA,EAAA,MAAA;;;;;;;AAmEnB;AACY,UArEK,OAAA,CAqEO;EAKP,SAAA,MAAA,EAzEE,MAyEW;EAAgB;;;;EAaG,SAAA,EAAA,EAhFlC,YAgFkC;EAC/B;;;;EAA8C,SAAA,OAAA,EA3E5C,WA2E4C,CAAA,MAAA,EAAA,MAAA,CAAA;EAApD;;;;;EACgD,SAAA,cAAA,EArEjC,WAqEiC,CAAA,MAAA,EAAA,MAAA,GAAA,MAAA,EAAA,GAAA,SAAA,CAAA;EAAvD;;;EAe4B,SAAA,IAAA,EA/EhB,UA+EgB;EACvB;;;;;;;;;EAEuB,SAAA,SAAA,EAAA,OAAA,EAAA;EAAe;;;EAApC,SAAA,cAAA,CAAA,EAAA,MAAA;EAUe;;;;;AAa3B;EAcY,SAAA,KAAS,CAAA,EAAA,MAAA;EAAqB;;;;AAE1C;;EACU,SAAA,QAAA,CAAA,EAAA,MAAA;EAgBW;;;;AAmCrB;EAGa,SAAA,sBAAA,EAzIsB,WAyItB;;AAGQ,KAxIT,UAAA,GAAa,MAwIJ,CAAA,MAAA,EAAA,GAAA,CAAA;AAAN,KAvIH,YAAA,GAuIG;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9B,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
|
@@ -247,7 +247,7 @@ type GenericSend<REQ> = {
|
|
|
247
247
|
* @experimental
|
|
248
248
|
* @interface
|
|
249
249
|
*/
|
|
250
|
-
type ScopedContext = Pick<Context, "serviceClient" | "serviceSendClient" | "workflowClient" | "workflowSendClient">;
|
|
250
|
+
type ScopedContext = Pick<Context, "serviceClient" | "serviceSendClient" | "objectClient" | "objectSendClient" | "workflowClient" | "workflowSendClient">;
|
|
251
251
|
/**
|
|
252
252
|
* The context that gives access to all Restate-backed operations, for example
|
|
253
253
|
* - sending reliable messages / RPC through Restate
|
|
@@ -548,6 +548,9 @@ interface Context extends RestateContext {
|
|
|
548
548
|
* // Route a call into a named scope
|
|
549
549
|
* await ctx.scope("tenant-123").serviceClient(MyService).process(payload);
|
|
550
550
|
*
|
|
551
|
+
* // Virtual objects can be scoped too — the object key is part of the scoped identity
|
|
552
|
+
* await ctx.scope("tenant-123").objectClient(MyObject, "obj-key").update(payload);
|
|
553
|
+
*
|
|
551
554
|
* // Idempotency keys are scoped — "req-1" in "tenant-123" is distinct from "req-1" in "tenant-456"
|
|
552
555
|
* await ctx.scope("tenant-123").serviceClient(MyService)
|
|
553
556
|
* .process(payload, rpc.opts({ idempotencyKey: "req-1" }));
|
package/dist/context.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;UAuCiB,MAAA;;EAAA,OAAA,EAAM,MAAA;EAaN,GAAA,CAAA,EAAA,MAAO;EACL,QAAA,EAAA,EAAA,MAAA;;;;;;;AAmE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c,uBACvB,eAAe,wBAAwB,cACrC,MAAM,eAAe,eAAe,SAAS,OAAO,SAC3D,SAAS,eAAe,eAAe,SAAS,OAAO;;;;eAK7C,QAAQ;;UAGN,IAAA;;;;;;;;;;;;;;;;;KAmBL,oBAAoB,QAAQ;;;;;;;;oBAQpB,oBAAoB,eAAe;;;;;;;;;;;;;;;;;;0BAmB7B,aAAa,kBAAkB,IAAI,eAAe;;;;;;KAOhE,YAAA;;;cAEC;;;;;0BAKa;;KAUd,gBAAA;yBAEa,QAAQ;;KAGrB,uBAAuB,eAAe,KAAK;cAE1C;;;;;;;;;;oBAUO,IAAI,eAAe,QAAQ;;;;;;;4BAanB,gBAAgB,eAAe;;;;;;;;;;+BAa5B,mCACnB,IACP,uCAAuC,IAAI,QAAQ,EAAE;;;;;;;;;;gCAmB1B,mCACpB,IACP,eAAe,QAAQ;;;;;;;;;;;+BAqBG,mCACnB,IACP,eAAe,QAAQ;;;;;;;;;;sCAiBU,mCAC1B,IACP,uCACqB,IAAI,qBAAqB,QAAQ,EAAE;;;;;;;KAiBjD,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.js.map
CHANGED
|
@@ -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 {\n Client,\n SendClient,\n //eslint-disable-next-line @typescript-eslint/no-unused-vars\n ClientCallOptions,\n} 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 type { TerminalError } from \"./types/errors.js\";\nimport {\n InternalRestatePromise,\n CombinatorRestatePromise,\n ConstRestatePromise,\n} from \"./promises.js\";\n\nexport interface Target {\n service: string;\n handler: string;\n key?: string;\n toString(): string;\n}\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 readonly target: Target;\n\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: InvocationId;\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 * The idempotency key with which this invocation was submitted, if any.\n */\n readonly idempotencyKey?: string;\n\n /**\n * The scope key with which this invocation was submitted, if any.\n *\n * @see {@link Context.scope}\n * @experimental\n */\n readonly scope?: string;\n\n /**\n * The limit key with which this invocation was submitted, if any.\n *\n * @see {@link ClientCallOptions.limitKey}\n * @experimental\n */\n readonly limitKey?: string;\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\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 * 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 * 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 * 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 * Scope of the request target.\n *\n * @see {@link Context.scope}.\n */\n scope?: string;\n /**\n * Limit key to use within the scope. Requires `scope` to be set.\n *\n * @see {@link ClientCallOptions.limitKey}.\n * @experimental\n */\n limitKey?: 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 * Scope of the request target.\n *\n * @see {@link Context.scope}.\n */\n scope?: string;\n /**\n * Limit key to use within the scope. Requires `scope` to be set.\n *\n * @see {@link ClientCallOptions.limitKey}.\n * @experimental\n */\n limitKey?: string;\n /**\n * Observability name, recorded in the Restate journal.\n */\n name?: string;\n};\n\n/**\n * A context for making RPC calls within a specific scope.\n *\n * @see {@link Context.scope}\n * @experimental\n * @interface\n */\nexport type ScopedContext = Pick<\n Context,\n | \"serviceClient\"\n | \"serviceSendClient\"\n | \"workflowClient\"\n | \"workflowSendClient\"\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, either a string message or a {@link TerminalError}.\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 | TerminalError): 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 ): 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 ): SendClient<VirtualObject<D>>;\n\n /**\n * Returns a {@link ScopedContext} that routes all outgoing calls within the given scope.\n *\n * **NOTE:** This API is in preview and is not enabled by default.\n * To use it in restate-server 1.7, enable the flow control and protocol v7 experimental features,\n * via `RESTATE_EXPERIMENTAL_ENABLE_PROTOCOL_V7=true` and `RESTATE_EXPERIMENTAL_ENABLE_VQUEUES=true`.\n * These can be enabled only on **new clusters**, for more info check out https://docs.restate.dev/services/flow-control#enabling-flow-control.\n * If these experimental features aren't enabled, the call fails with a retryable error and keeps retrying until they are.\n *\n * A scope is a sub-grouping of resources (invocations, virtual object instances, workflow\n * instances, concurrency limits) within the Restate cluster.\n * It becomes part of the target identity tuple:\n * - `scope, service, handler, idempotencyKey?`\n * - `scope, virtualObject, objectKey, handler, idempotencyKey?`\n * - `scope, workflow, workflowKey, handler`\n *\n * Under the hood, the scope contributes to the partition key, so all resources in a scope get co-located by the restate-server.\n *\n * Omitting the scope (i.e. using the regular `serviceClient` / `workflowClient` methods)\n * is equivalent to calling with no scope, which is the existing behavior.\n *\n * The scope key must consist only of `[a-zA-Z0-9_.-]` characters, with 1 <= length <= 36 chars.\n *\n * @example\n * ```ts\n * // Route a call into a named scope\n * await ctx.scope(\"tenant-123\").serviceClient(MyService).process(payload);\n *\n * // Idempotency keys are scoped — \"req-1\" in \"tenant-123\" is distinct from \"req-1\" in \"tenant-456\"\n * await ctx.scope(\"tenant-123\").serviceClient(MyService)\n * .process(payload, rpc.opts({ idempotencyKey: \"req-1\" }));\n *\n * // Combine with a limit key to enforce per-scope concurrency limits\n * await ctx.scope(\"tenant-123\").workflowClient(MyWorkflow, \"wf-key\")\n * .run(input, rpc.opts({ limitKey: \"api-key/user42\" }));\n * ```\n *\n * @param scopeKey the scope identifier\n * @see https://docs.restate.dev/services/flow-control\n * @experimental\n */\n scope(scopeKey: string): ScopedContext;\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 * @deprecated use `ctx.invocation().attach()`\n */\n cancel(invocationId: InvocationId): void;\n\n /**\n * @deprecated use `ctx.invocation().cancel()`\n */\n attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T>;\n\n /**\n * Wait for a named signal to arrive on the current invocation.\n *\n * Signals are identified by name and are scoped to the current invocation.\n * Another handler can send a signal to this invocation using\n * {@link InvocationReference.signal}, specifying this invocation's\n * ID (available via `ctx.request().id`) and the same signal name.\n *\n * @param name the name of the signal to wait for.\n * @param serde optional custom serializer/deserializer for the payload.\n * @returns a {@link RestatePromise} that resolves when the signal arrives.\n *\n * @example\n * const approved = await ctx.signal<boolean>(\"approved\");\n */\n signal<T>(name: string, serde?: Serde<T>): RestatePromise<T>;\n\n /**\n * Get a reference to a target invocation, to send signals to it.\n *\n * @param invocationId the invocation ID of the target invocation.\n * @returns an {@link InvocationReference} for the target invocation.\n *\n * @example\n * const target = ctx.invocation(targetInvocationId);\n * target.signal(\"approved\").resolve(true);\n * target.signal(\"approved\").reject(\"Request denied\");\n */\n invocation(invocationId: InvocationId): InvocationReference;\n}\n\n/**\n * A reference to a target invocation, used to send signals.\n */\nexport interface InvocationReference {\n /**\n * Get a handle to a named signal on the target invocation.\n *\n * @param name the name of the signal.\n * @param serde optional custom serializer/deserializer for the payload.\n * @returns a {@link SignalReference} to resolve or reject the signal.\n */\n signal<T>(name: string, serde?: Serde<T>): SignalReference<T>;\n\n /**\n * Cancel the target invocation.\n */\n cancel(): void;\n\n /**\n * Attach to the target invocation and wait for its result.\n *\n * @param serde optional custom serializer/deserializer for the result.\n * @returns a {@link RestatePromise} that resolves with the invocation result.\n */\n attach<T>(serde?: Serde<T>): RestatePromise<T>;\n}\n\n/**\n * A handle to send a signal value to a target invocation.\n */\nexport interface SignalReference<T> {\n /**\n * Resolve the signal with a value.\n *\n * @param payload the payload to send.\n */\n resolve(payload?: T): void;\n\n /**\n * Reject the signal. The target invocation waiting on this signal will be\n * woken up with a terminal error containing the provided reason.\n *\n * @param reason the reason for rejection, either a string message or a {@link TerminalError}.\n */\n reject(reason: string | TerminalError): void;\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 *\n * To check at runtime whether a value is a {@link RestatePromise}, use {@link isRestatePromise}.\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 * **NOTE**: Contrary to `.then`, the closure is executed ONLY when the promise is awaited,\n * and not eagerly as soon as the promise completes.\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 {@link RestatePromise} that is resolved with the given value.\n *\n * If the value is already a {@link RestatePromise}, it is returned as-is (mirroring\n * the behavior of {@link Promise.resolve} when given a native {@link Promise}).\n *\n * @param value The value to resolve, or an existing {@link RestatePromise} to return.\n * @returns A resolved {@link RestatePromise}, or the input promise unchanged.\n */\n resolve<T>(value: T): RestatePromise<Awaited<T>> {\n if (value instanceof InternalRestatePromise) {\n return value as unknown as RestatePromise<Awaited<T>>;\n }\n return ConstRestatePromise.resolve(value);\n },\n\n /**\n * Creates a {@link RestatePromise} that is rejected with the given {@link TerminalError}.\n *\n * @param reason The {@link TerminalError} to reject with.\n * @returns A rejected {@link RestatePromise}.\n */\n reject<T = never>(reason: TerminalError): RestatePromise<T> {\n return ConstRestatePromise.reject(reason);\n },\n\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 return CombinatorRestatePromise.fromPromises(\n \"AllSucceededOrFirstFailed\",\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 return ConstRestatePromise.pending();\n }\n return CombinatorRestatePromise.fromPromises(\n \"FirstCompleted\",\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 return CombinatorRestatePromise.fromPromises(\n \"FirstSucceededOrAllFailed\",\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 return CombinatorRestatePromise.fromPromises(\n \"AllCompleted\",\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}.\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":";;;AAo3BA,MAAa,qBAAqB,EAKhC,WAAW,IAA0B;AACnC,KAAI,CAAC,GAAG,WAAW,MAAM,CACvB,OAAM,IAAI,MACR,sDAAsD,KACvD;AAEH,QAAO;GAEV;AASD,MAAa,iBAAiB;CAU5B,QAAW,OAAsC;AAC/C,MAAI,iBAAiB,uBACnB,QAAO;AAET,SAAO,oBAAoB,QAAQ,MAAM;;CAS3C,OAAkB,QAA0C;AAC1D,SAAO,oBAAoB,OAAO,OAAO;;CAY3C,IACE,QAC6D;AAC7D,SAAO,yBAAyB,aAC9B,8BACC,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAcH,KACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,QAAO,oBAAoB,SAAS;AAEtC,SAAO,yBAAyB,aAC9B,mBACC,MAAM,QAAQ,KAAK,EAAE,EACtB,OACD;;CAaH,IACE,QACoC;AACpC,SAAO,yBAAyB,aAC9B,8BACC,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAYH,WACE,QAGC;AACD,SAAO,yBAAyB,aAC9B,iBACC,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 {\n Client,\n SendClient,\n //eslint-disable-next-line @typescript-eslint/no-unused-vars\n ClientCallOptions,\n} 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 type { TerminalError } from \"./types/errors.js\";\nimport {\n InternalRestatePromise,\n CombinatorRestatePromise,\n ConstRestatePromise,\n} from \"./promises.js\";\n\nexport interface Target {\n service: string;\n handler: string;\n key?: string;\n toString(): string;\n}\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 readonly target: Target;\n\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: InvocationId;\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 * The idempotency key with which this invocation was submitted, if any.\n */\n readonly idempotencyKey?: string;\n\n /**\n * The scope key with which this invocation was submitted, if any.\n *\n * @see {@link Context.scope}\n * @experimental\n */\n readonly scope?: string;\n\n /**\n * The limit key with which this invocation was submitted, if any.\n *\n * @see {@link ClientCallOptions.limitKey}\n * @experimental\n */\n readonly limitKey?: string;\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\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 * 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 * 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 * 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 * Scope of the request target.\n *\n * @see {@link Context.scope}.\n */\n scope?: string;\n /**\n * Limit key to use within the scope. Requires `scope` to be set.\n *\n * @see {@link ClientCallOptions.limitKey}.\n * @experimental\n */\n limitKey?: 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 * Scope of the request target.\n *\n * @see {@link Context.scope}.\n */\n scope?: string;\n /**\n * Limit key to use within the scope. Requires `scope` to be set.\n *\n * @see {@link ClientCallOptions.limitKey}.\n * @experimental\n */\n limitKey?: string;\n /**\n * Observability name, recorded in the Restate journal.\n */\n name?: string;\n};\n\n/**\n * A context for making RPC calls within a specific scope.\n *\n * @see {@link Context.scope}\n * @experimental\n * @interface\n */\nexport type ScopedContext = Pick<\n Context,\n | \"serviceClient\"\n | \"serviceSendClient\"\n | \"objectClient\"\n | \"objectSendClient\"\n | \"workflowClient\"\n | \"workflowSendClient\"\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, either a string message or a {@link TerminalError}.\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 | TerminalError): 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 ): 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 ): SendClient<VirtualObject<D>>;\n\n /**\n * Returns a {@link ScopedContext} that routes all outgoing calls within the given scope.\n *\n * **NOTE:** This API is in preview and is not enabled by default.\n * To use it in restate-server 1.7, enable the flow control and protocol v7 experimental features,\n * via `RESTATE_EXPERIMENTAL_ENABLE_PROTOCOL_V7=true` and `RESTATE_EXPERIMENTAL_ENABLE_VQUEUES=true`.\n * These can be enabled only on **new clusters**, for more info check out https://docs.restate.dev/services/flow-control#enabling-flow-control.\n * If these experimental features aren't enabled, the call fails with a retryable error and keeps retrying until they are.\n *\n * A scope is a sub-grouping of resources (invocations, virtual object instances, workflow\n * instances, concurrency limits) within the Restate cluster.\n * It becomes part of the target identity tuple:\n * - `scope, service, handler, idempotencyKey?`\n * - `scope, virtualObject, objectKey, handler, idempotencyKey?`\n * - `scope, workflow, workflowKey, handler`\n *\n * Under the hood, the scope contributes to the partition key, so all resources in a scope get co-located by the restate-server.\n *\n * Omitting the scope (i.e. using the regular `serviceClient` / `workflowClient` methods)\n * is equivalent to calling with no scope, which is the existing behavior.\n *\n * The scope key must consist only of `[a-zA-Z0-9_.-]` characters, with 1 <= length <= 36 chars.\n *\n * @example\n * ```ts\n * // Route a call into a named scope\n * await ctx.scope(\"tenant-123\").serviceClient(MyService).process(payload);\n *\n * // Virtual objects can be scoped too — the object key is part of the scoped identity\n * await ctx.scope(\"tenant-123\").objectClient(MyObject, \"obj-key\").update(payload);\n *\n * // Idempotency keys are scoped — \"req-1\" in \"tenant-123\" is distinct from \"req-1\" in \"tenant-456\"\n * await ctx.scope(\"tenant-123\").serviceClient(MyService)\n * .process(payload, rpc.opts({ idempotencyKey: \"req-1\" }));\n *\n * // Combine with a limit key to enforce per-scope concurrency limits\n * await ctx.scope(\"tenant-123\").workflowClient(MyWorkflow, \"wf-key\")\n * .run(input, rpc.opts({ limitKey: \"api-key/user42\" }));\n * ```\n *\n * @param scopeKey the scope identifier\n * @see https://docs.restate.dev/services/flow-control\n * @experimental\n */\n scope(scopeKey: string): ScopedContext;\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 * @deprecated use `ctx.invocation().attach()`\n */\n cancel(invocationId: InvocationId): void;\n\n /**\n * @deprecated use `ctx.invocation().cancel()`\n */\n attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T>;\n\n /**\n * Wait for a named signal to arrive on the current invocation.\n *\n * Signals are identified by name and are scoped to the current invocation.\n * Another handler can send a signal to this invocation using\n * {@link InvocationReference.signal}, specifying this invocation's\n * ID (available via `ctx.request().id`) and the same signal name.\n *\n * @param name the name of the signal to wait for.\n * @param serde optional custom serializer/deserializer for the payload.\n * @returns a {@link RestatePromise} that resolves when the signal arrives.\n *\n * @example\n * const approved = await ctx.signal<boolean>(\"approved\");\n */\n signal<T>(name: string, serde?: Serde<T>): RestatePromise<T>;\n\n /**\n * Get a reference to a target invocation, to send signals to it.\n *\n * @param invocationId the invocation ID of the target invocation.\n * @returns an {@link InvocationReference} for the target invocation.\n *\n * @example\n * const target = ctx.invocation(targetInvocationId);\n * target.signal(\"approved\").resolve(true);\n * target.signal(\"approved\").reject(\"Request denied\");\n */\n invocation(invocationId: InvocationId): InvocationReference;\n}\n\n/**\n * A reference to a target invocation, used to send signals.\n */\nexport interface InvocationReference {\n /**\n * Get a handle to a named signal on the target invocation.\n *\n * @param name the name of the signal.\n * @param serde optional custom serializer/deserializer for the payload.\n * @returns a {@link SignalReference} to resolve or reject the signal.\n */\n signal<T>(name: string, serde?: Serde<T>): SignalReference<T>;\n\n /**\n * Cancel the target invocation.\n */\n cancel(): void;\n\n /**\n * Attach to the target invocation and wait for its result.\n *\n * @param serde optional custom serializer/deserializer for the result.\n * @returns a {@link RestatePromise} that resolves with the invocation result.\n */\n attach<T>(serde?: Serde<T>): RestatePromise<T>;\n}\n\n/**\n * A handle to send a signal value to a target invocation.\n */\nexport interface SignalReference<T> {\n /**\n * Resolve the signal with a value.\n *\n * @param payload the payload to send.\n */\n resolve(payload?: T): void;\n\n /**\n * Reject the signal. The target invocation waiting on this signal will be\n * woken up with a terminal error containing the provided reason.\n *\n * @param reason the reason for rejection, either a string message or a {@link TerminalError}.\n */\n reject(reason: string | TerminalError): void;\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 *\n * To check at runtime whether a value is a {@link RestatePromise}, use {@link isRestatePromise}.\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 * **NOTE**: Contrary to `.then`, the closure is executed ONLY when the promise is awaited,\n * and not eagerly as soon as the promise completes.\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 {@link RestatePromise} that is resolved with the given value.\n *\n * If the value is already a {@link RestatePromise}, it is returned as-is (mirroring\n * the behavior of {@link Promise.resolve} when given a native {@link Promise}).\n *\n * @param value The value to resolve, or an existing {@link RestatePromise} to return.\n * @returns A resolved {@link RestatePromise}, or the input promise unchanged.\n */\n resolve<T>(value: T): RestatePromise<Awaited<T>> {\n if (value instanceof InternalRestatePromise) {\n return value as unknown as RestatePromise<Awaited<T>>;\n }\n return ConstRestatePromise.resolve(value);\n },\n\n /**\n * Creates a {@link RestatePromise} that is rejected with the given {@link TerminalError}.\n *\n * @param reason The {@link TerminalError} to reject with.\n * @returns A rejected {@link RestatePromise}.\n */\n reject<T = never>(reason: TerminalError): RestatePromise<T> {\n return ConstRestatePromise.reject(reason);\n },\n\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 return CombinatorRestatePromise.fromPromises(\n \"AllSucceededOrFirstFailed\",\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 return ConstRestatePromise.pending();\n }\n return CombinatorRestatePromise.fromPromises(\n \"FirstCompleted\",\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 return CombinatorRestatePromise.fromPromises(\n \"FirstSucceededOrAllFailed\",\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 return CombinatorRestatePromise.fromPromises(\n \"AllCompleted\",\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}.\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":";;;AAy3BA,MAAa,qBAAqB,EAKhC,WAAW,IAA0B;AACnC,KAAI,CAAC,GAAG,WAAW,MAAM,CACvB,OAAM,IAAI,MACR,sDAAsD,KACvD;AAEH,QAAO;GAEV;AASD,MAAa,iBAAiB;CAU5B,QAAW,OAAsC;AAC/C,MAAI,iBAAiB,uBACnB,QAAO;AAET,SAAO,oBAAoB,QAAQ,MAAM;;CAS3C,OAAkB,QAA0C;AAC1D,SAAO,oBAAoB,OAAO,OAAO;;CAY3C,IACE,QAC6D;AAC7D,SAAO,yBAAyB,aAC9B,8BACC,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAcH,KACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,QAAO,oBAAoB,SAAS;AAEtC,SAAO,yBAAyB,aAC9B,mBACC,MAAM,QAAQ,KAAK,EAAE,EACtB,OACD;;CAaH,IACE,QACoC;AACpC,SAAO,yBAAyB,aAC9B,8BACC,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAYH,WACE,QAGC;AACD,SAAO,yBAAyB,aAC9B,iBACC,MAAM,QAAQ,WAAW,EAAE,EAC5B,OACD;;CAIJ"}
|
package/dist/context_impl.cjs
CHANGED
|
@@ -153,6 +153,8 @@ var ContextImpl = class {
|
|
|
153
153
|
return {
|
|
154
154
|
serviceClient: ({ name }) => require_rpc.makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, void 0, scopeKey),
|
|
155
155
|
serviceSendClient: ({ name }) => require_rpc.makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, void 0, scopeKey),
|
|
156
|
+
objectClient: ({ name }, key) => require_rpc.makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, key, scopeKey),
|
|
157
|
+
objectSendClient: ({ name }, key) => require_rpc.makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, key, scopeKey),
|
|
156
158
|
workflowClient: ({ name }, key) => require_rpc.makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, key, scopeKey),
|
|
157
159
|
workflowSendClient: ({ name }, key) => require_rpc.makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, key, scopeKey)
|
|
158
160
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context_impl.d.ts","sourceRoot":"","sources":["../src/context_impl.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EACd,WAAW,EACX,WAAW,EACX,gBAAgB,EACh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AE,CAAC,eAAe,EAC/B,OAAO,EAAE,MAAM,CAAC,EAChB,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,KAAK,MAAM,EACvC,GAAG,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,GAC9B,cAAc,CAAC,CAAC,CAAC;IAwBpB,YAAY,CAAC,CAAC,EAAE,OAAO,EAAE,WAAW,CAAC,EAAE,eAAe;CASvD;AA6KD,qBAAa,kBAAkB;IAMjB,OAAO,CAAC,QAAQ,CAAC,OAAO;IALpC,OAAO,CAAC,aAAa,CAGjB;gBAEyB,OAAO,EAAE,uBAAuB;IAE7D,UAAU,CAAC,MAAM,EAAE,MAAM;IAWzB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC,GAAG,CAAC;CAGlE;AAID,KAAK,SAAS,GAAG,CACf,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,oBAAoB,CAAC,GAAG,CAAC,KAC5B,OAAO,CAAC,OAAO,CAAC,CAAC;AAStB,qBAAa,YAAa,SAAQ,KAAK;aAQjB,KAAK,EAAE,OAAO;IAChC,QAAQ,CAAC,WAAW,EAAE,eAAe;IACrC,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM;gBATpB,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,eAAe;gBAEtD,KAAK,EAAE,OAAO,EACd,WAAW,EAAE,eAAe,EAC5B,YAAY,EAAE,MAAM;IAWtB,gFAAgF;IAChF,IAAI,eAAe,IAAI,OAAO,CAE7B;CACF"}
|
package/dist/context_impl.js
CHANGED
|
@@ -151,6 +151,8 @@ var ContextImpl = class {
|
|
|
151
151
|
return {
|
|
152
152
|
serviceClient: ({ name }) => makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, void 0, scopeKey),
|
|
153
153
|
serviceSendClient: ({ name }) => makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, void 0, scopeKey),
|
|
154
|
+
objectClient: ({ name }, key) => makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, key, scopeKey),
|
|
155
|
+
objectSendClient: ({ name }, key) => makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, key, scopeKey),
|
|
154
156
|
workflowClient: ({ name }, key) => makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, key, scopeKey),
|
|
155
157
|
workflowSendClient: ({ name }, key) => makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, key, scopeKey)
|
|
156
158
|
};
|
package/dist/context_impl.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context_impl.js","names":["coreVm: WasmVM","console: Console","handlerKind: HandlerKind","vmLogger: Console","invocationRequest: Request","invocationEndPromise: PromiseWithResolvers<void>","journalValueCodec: JournalValueCodec","serde","requestSerde: Serde<REQ>","responseSerde: Serde<RES>","parameter: Uint8Array","wasmRun: vm.WasmRun","doRun: () => Promise<any>","res: T","awakeable: vm.WasmAwakeable","value: Uint8Array","handle: number","cancelled: InvocationId[]","ctx: ContextImpl","invocationId: InvocationId","name: string","channel: ExternalProgressChannel","cause: unknown","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 InvocationReference,\n ObjectContext,\n Rand,\n Request,\n RestatePromise,\n RunAction,\n RunOptions,\n SignalReference,\n ScopedContext,\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 WasmInput,\n WasmVM,\n} from \"./endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js\";\nimport {\n ensureError,\n INTERNAL_ERROR_CODE,\n PauseError,\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 { AsyncResultValue, CombinatorRestatePromise } from \"./promises.js\";\nimport {\n ConstRestatePromise,\n pendingPromise,\n PromisesExecutor,\n InvocationRestatePromise,\n SingleRestatePromise,\n} from \"./promises.js\";\nimport { InputPump, OutputPump } from \"./io.js\";\nimport { ExternalProgressChannel } from \"./utils/external_progress_channel.js\";\nimport type { ContextInternal } from \"./internal.js\";\nimport { InputReader, OutputWriter } from \"./endpoint/handlers/types.js\";\nimport { ExecutionOptions } from \"./endpoint/components.js\";\n\nexport class ContextImpl\n implements ObjectContext, WorkflowContext, ContextInternal\n{\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 readonly inputPump: InputPump;\n private readonly runClosuresTracker: RunClosuresTracker;\n readonly promisesExecutor: PromisesExecutor;\n private readonly serviceKey: string;\n private runInterceptor: (\n name: string,\n runner: () => Promise<void>\n ) => Promise<void>;\n private cancellationPromise?: SingleRestatePromise<void>;\n readonly defaultSerde: Serde<any>;\n private readonly asTerminalError?: (error: any) => TerminalError | undefined;\n\n // If undefined, we're not tracking invocation id promises\n private readonly trackedInvocationIdPromises?: SingleRestatePromise<string>[];\n\n constructor(\n readonly coreVm: WasmVM,\n input: WasmInput,\n public readonly console: Console,\n public readonly handlerKind: HandlerKind,\n readonly vmLogger: Console,\n private readonly invocationRequest: Request,\n readonly invocationEndPromise: PromiseWithResolvers<void>,\n inputReader: InputReader,\n outputWriter: OutputWriter,\n readonly journalValueCodec: JournalValueCodec,\n executionOptions?: ExecutionOptions\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 const externalProgressChannel = new ExternalProgressChannel();\n this.runClosuresTracker = new RunClosuresTracker(externalProgressChannel);\n this.inputPump = new InputPump(\n coreVm,\n inputReader,\n externalProgressChannel,\n this.abortAttempt.bind(this)\n );\n this.promisesExecutor = new PromisesExecutor(\n coreVm,\n this.outputPump,\n this.runClosuresTracker,\n externalProgressChannel,\n this.abortAttempt.bind(this)\n );\n this.serviceKey = input.key;\n // Identity interceptor by default; replaced by startUserHandler after hooks are instantiated\n this.runInterceptor = (_name, runner) => runner();\n this.defaultSerde = executionOptions?.defaultSerde ?? serde.json;\n this.asTerminalError = executionOptions?.asTerminalError;\n this.trackedInvocationIdPromises = executionOptions?.explicitCancellation\n ? []\n : undefined;\n }\n\n setRunInterceptor(\n interceptor: (name: string, runner: () => Promise<void>) => Promise<void>\n ) {\n this.runInterceptor = interceptor;\n }\n\n isProcessing(): boolean {\n return this.coreVm.is_processing();\n }\n\n cancel(invocationId: InvocationId): void {\n this._cancel(invocationId);\n }\n\n private _cancel(invocationId: string): 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.serviceKey;\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.abortAttempt(e, WasmCommandType.Call);\n return Object.assign(ConstRestatePromise.pending<RES>(), {\n invocationId: pendingPromise<InvocationId>(),\n });\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.scope,\n call.limitKey,\n call.name\n );\n const commandIndex = this.coreVm.last_command_index();\n\n const invocationIdPromise = new SingleRestatePromise(\n this,\n call_handles.invocation_id_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.Call,\n commandIndex,\n InvocationIdCompleter\n )\n );\n\n this.trackedInvocationIdPromises?.push(\n invocationIdPromise as SingleRestatePromise<string>\n );\n\n return new InvocationRestatePromise(\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.abortAttempt(e);\n // We return a pending promise to avoid the caller to see the error.\n return Object.assign(ConstRestatePromise.pending<RES>(), {\n invocationId: pendingPromise<InvocationId>(),\n });\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.abortAttempt(e, WasmCommandType.OneWayCall);\n return Object.assign(ConstRestatePromise.pending<void>(), {\n invocationId: pendingPromise<InvocationId>(),\n });\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.scope,\n send.limitKey,\n send.name\n );\n const commandIndex = this.coreVm.last_command_index();\n\n return {\n invocationId: new SingleRestatePromise(\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.abortAttempt(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,\n }: ServiceDefinitionFrom<D>): SendClient<Service<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n undefined\n );\n }\n\n public objectSendClient<D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string\n ): SendClient<VirtualObject<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key\n );\n }\n\n workflowSendClient<D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string\n ): SendClient<Workflow<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key\n );\n }\n\n scope(scopeKey: string): ScopedContext {\n return {\n serviceClient: <D>({ name }: ServiceDefinitionFrom<D>) =>\n makeRpcCallProxy<Client<Service<D>>>(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n undefined,\n scopeKey\n ),\n serviceSendClient: <D>({ name }: ServiceDefinitionFrom<D>) =>\n makeRpcSendProxy<SendClient<Service<D>>>(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n undefined,\n scopeKey\n ),\n workflowClient: <D>({ name }: WorkflowDefinitionFrom<D>, key: string) =>\n makeRpcCallProxy<Client<Workflow<D>>>(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n key,\n scopeKey\n ),\n workflowSendClient: <D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string\n ) =>\n makeRpcSendProxy<SendClient<Workflow<D>>>(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key,\n scopeKey\n ),\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 wasmRun: vm.WasmRun;\n try {\n wasmRun = this.coreVm.sys_run(name ?? \"\");\n } catch (e) {\n this.abortAttempt(e);\n return ConstRestatePromise.pending();\n }\n const handle = wasmRun.handle;\n const commandIndex = this.coreVm.last_command_index();\n\n if (!wasmRun.replayed) {\n // Let's prepare the run task only if the run wasnt replayed.\n const doRun: () => Promise<any> = async () => {\n // Execute the user code, wrapping with run interceptor hooks\n const startTime = Date.now();\n let res: T;\n let err;\n try {\n await this.runInterceptor(name ?? \"\", async () => {\n res = await action();\n });\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: Object.entries(err.metadata ?? {}).map(\n ([key, value]) => ({ key, value })\n ),\n });\n } else if (err instanceof RetryableError) {\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 options?.maxRetryDuration !== undefined\n ? BigInt(millisOrDurationToMillis(options?.maxRetryDuration))\n : undefined\n );\n } else if (err instanceof PauseError) {\n this.coreVm.propose_run_completion_failure_transient_with_pause(\n handle,\n err.message,\n err.stack,\n BigInt(attemptDuration)\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?.maxRetryDuration !== undefined ||\n options?.maxRetryInterval !== undefined\n ) {\n retryPolicy = {\n factor: options?.retryIntervalFactor ?? 2.0,\n initial_interval: millisOrDurationToMillis(\n options?.initialRetryInterval ?? 50\n ),\n max_attempts: options?.maxRetryAttempts,\n max_duration:\n options?.maxRetryDuration === undefined\n ? undefined\n : millisOrDurationToMillis(options?.maxRetryDuration),\n max_interval: millisOrDurationToMillis(\n options?.maxRetryInterval ?? { 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.abortAttempt(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\n // TODO: here as well\n // Return the promise\n return new SingleRestatePromise(\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.abortAttempt(e);\n return {\n id: \"invalid\",\n promise: ConstRestatePromise.pending(),\n };\n }\n\n return {\n id: awakeable.id,\n promise: new SingleRestatePromise(\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 | TerminalError): void {\n this.processNonCompletableEntry(\n WasmCommandType.CompleteAwakeable,\n () => {},\n (vm) => {\n vm.sys_complete_awakeable_failure(id, toWasmFailure(reason));\n }\n );\n }\n\n // -- Signals\n\n public signal<T>(name: string, serde?: Serde<T>): RestatePromise<T> {\n let handle: number;\n try {\n handle = this.coreVm.sys_signal(name);\n } catch (e) {\n this.abortAttempt(e);\n return ConstRestatePromise.pending();\n }\n\n return new SingleRestatePromise(\n this,\n handle,\n completeSignalPromiseUsing(\n VoidAsUndefined,\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec),\n Failure\n )\n );\n }\n\n public invocation(invocationId: InvocationId): InvocationReference {\n return new InvocationReferenceImpl(this, invocationId);\n }\n\n public promise<T>(name: string, serde?: Serde<T>): DurablePromise<T> {\n return new DurablePromiseImpl(this, name, serde);\n }\n\n cancellation(): RestatePromise<void> {\n if (!this.cancellationPromise || this.cancellationPromise.isCompleted()) {\n this.cancellationPromise = new SingleRestatePromise(\n this,\n 1 /* HANDLE 1 is a hardcoded cancellation signal! */,\n completeSignalPromiseUsing(VoidAsUndefined)\n );\n }\n\n return this.cancellationPromise;\n }\n\n cancelPreviousCalls(): RestatePromise<InvocationId[]> {\n if (!this.trackedInvocationIdPromises) {\n return ConstRestatePromise.resolve([]);\n }\n\n return CombinatorRestatePromise.fromPromises(\n \"AllCompleted\",\n (p: Promise<any>[]) => Promise.allSettled(p),\n this.trackedInvocationIdPromises.splice(0)\n ).map((results, failure) => {\n if (failure) {\n throw failure;\n }\n const cancelled: InvocationId[] = [];\n for (const result of results as PromiseSettledResult<string>[]) {\n if (result.status === \"fulfilled\") {\n this._cancel(result.value);\n cancelled.push(result.value as InvocationId);\n } else {\n this.console.warn(\n `Error when trying to get invocation id: ${result.reason}`\n );\n }\n }\n return cancelled;\n });\n }\n\n // -- Various private methods\n\n 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.abortAttempt(e, commandType);\n return;\n }\n\n try {\n vmCall(this.coreVm, input);\n } catch (e) {\n this.abortAttempt(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.abortAttempt(e, commandType);\n return ConstRestatePromise.pending();\n }\n\n let handle: number;\n try {\n handle = vmCall(this.coreVm, input);\n } catch (e) {\n this.abortAttempt(e);\n return ConstRestatePromise.pending();\n }\n const commandIndex = this.coreVm.last_command_index();\n return new SingleRestatePromise(\n this,\n handle,\n completeCommandPromiseUsing(commandType, commandIndex, ...completers)\n );\n }\n\n abortAttempt(e: unknown, commandType?: WasmCommandType) {\n // ensureError so interceptors always receive a proper Error,\n // not a raw VM object like { code, message }.\n this.invocationEndPromise.reject(\n commandType !== undefined\n ? new CommandError(e, commandType)\n : ensureError(e)\n );\n }\n}\n\nfunction toWasmFailure(reason: string | TerminalError): vm.WasmFailure {\n if (typeof reason === \"string\") {\n return {\n code: UNKNOWN_ERROR_CODE,\n message: reason,\n metadata: [],\n };\n }\n return {\n code: reason.code,\n message: reason.message,\n metadata: Object.entries(reason.metadata ?? {}).map(([key, value]) => ({\n key,\n value,\n })),\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 InvocationReferenceImpl implements InvocationReference {\n constructor(\n private readonly ctx: ContextImpl,\n private readonly invocationId: InvocationId\n ) {}\n\n signal<T>(name: string, serde?: Serde<T>): SignalReference<T> {\n return new SignalReferenceImpl(this.ctx, this.invocationId, name, serde);\n }\n\n cancel(): void {\n this.ctx.cancel(this.invocationId);\n }\n\n attach<T>(serde?: Serde<T>): RestatePromise<T> {\n return this.ctx.attach(this.invocationId, serde);\n }\n}\n\nclass SignalReferenceImpl<T> implements SignalReference<T> {\n private readonly serde: Serde<T>;\n\n constructor(\n private readonly ctx: ContextImpl,\n private readonly invocationId: InvocationId,\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 resolve(payload?: T): void {\n this.ctx.processNonCompletableEntry(\n WasmCommandType.SendSignal,\n () =>\n this.ctx.journalValueCodec.encode(this.serde.serialize(payload as T)),\n (vm, bytes) =>\n vm.sys_complete_signal_success(this.invocationId, this.name, bytes)\n );\n }\n\n reject(reason: string | TerminalError): void {\n this.ctx.processNonCompletableEntry(\n WasmCommandType.SendSignal,\n () => {},\n (vm) => {\n vm.sys_complete_signal_failure(\n this.invocationId,\n this.name,\n toWasmFailure(reason)\n );\n }\n );\n }\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 runsToExecute: Map<number, () => Promise<any>> = new Map<\n number,\n () => Promise<any>\n >();\n\n constructor(private readonly channel: ExternalProgressChannel) {}\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 this.runsToExecute.delete(handle);\n runClosure()\n .finally(() => this.channel.signal())\n .catch(() => {});\n }\n\n registerRunClosure(handle: number, runClosure: () => Promise<any>) {\n this.runsToExecute.set(handle, runClosure);\n }\n}\n\n// ---- Functions used to parse async results\n\ntype Completer = (\n value: AsyncResultValue,\n prom: PromiseWithResolvers<any>\n) => Promise<boolean>;\n\n// Wraps an error with command metadata so the centralized catch in\n// process() can call the right VM notification method.\n//\n// - Preparation failure (command not yet in journal): new CommandError(e, type)\n// → notify_error_for_next_command\n// - Completion failure (command exists): new CommandError(e, type, index)\n// → notify_error_for_specific_command\nexport class CommandError extends Error {\n constructor(cause: unknown, commandType: WasmCommandType);\n constructor(\n cause: unknown,\n commandType: WasmCommandType,\n commandIndex: number\n );\n constructor(\n override readonly cause: unknown,\n readonly commandType: WasmCommandType,\n readonly commandIndex?: number\n ) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n super(msg, { cause });\n }\n\n /** True when the error is for a specific command that exists in the journal. */\n get hasCommandIndex(): boolean {\n return this.commandIndex !== undefined;\n }\n}\n\nfunction completeCommandPromiseUsing<T>(\n commandType: WasmCommandType,\n commandIndex: number,\n ...completers: Array<Completer>\n): (value: AsyncResultValue, prom: PromiseWithResolvers<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: PromiseWithResolvers<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 CommandError(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: PromiseWithResolvers<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: PromiseWithResolvers<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 const metadata = (value.Failure.metadata ?? []).reduce(\n (\n acc: Record<string, string>,\n { key, value: v }: { key: string; value: string }\n ) => {\n acc[key] = v;\n return acc;\n },\n {} as Record<string, string>\n );\n prom.reject(\n new TerminalError(value.Failure.message, {\n errorCode: value.Failure.code,\n metadata,\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":";;;;;;;;;;AAgFA,IAAa,cAAb,MAEA;CACE,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,AAAS;CACT,AAAiB;CACjB,AAAS;CACT,AAAiB;CACjB,AAAQ;CAIR,AAAQ;CACR,AAAS;CACT,AAAiB;CAGjB,AAAiB;CAEjB,YACE,AAASA,QACT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,OAAO,SAAS;AAC1C,KAAI,OAAO,UAAU,YAAY,aAAa,OAAO;EACnD,MAAM,YAAY,MAAM,QAAQ,YAAY,EAAE,EAAE,QAE5C,KACA,EAAE,KAAK,OAAO,QACX;AACH,OAAI,OAAO;AACX,UAAO;KAET,EAAE,CACH;AACD,OAAK,OACH,IAAI,cAAc,MAAM,QAAQ,SAAS;GACvC,WAAW,MAAM,QAAQ;GACzB;GACD,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: WasmVM","console: Console","handlerKind: HandlerKind","vmLogger: Console","invocationRequest: Request","invocationEndPromise: PromiseWithResolvers<void>","journalValueCodec: JournalValueCodec","serde","requestSerde: Serde<REQ>","responseSerde: Serde<RES>","parameter: Uint8Array","wasmRun: vm.WasmRun","doRun: () => Promise<any>","res: T","awakeable: vm.WasmAwakeable","value: Uint8Array","handle: number","cancelled: InvocationId[]","ctx: ContextImpl","invocationId: InvocationId","name: string","channel: ExternalProgressChannel","cause: unknown","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 InvocationReference,\n ObjectContext,\n Rand,\n Request,\n RestatePromise,\n RunAction,\n RunOptions,\n SignalReference,\n ScopedContext,\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 WasmInput,\n WasmVM,\n} from \"./endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js\";\nimport {\n ensureError,\n INTERNAL_ERROR_CODE,\n PauseError,\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 { AsyncResultValue, CombinatorRestatePromise } from \"./promises.js\";\nimport {\n ConstRestatePromise,\n pendingPromise,\n PromisesExecutor,\n InvocationRestatePromise,\n SingleRestatePromise,\n} from \"./promises.js\";\nimport { InputPump, OutputPump } from \"./io.js\";\nimport { ExternalProgressChannel } from \"./utils/external_progress_channel.js\";\nimport type { ContextInternal } from \"./internal.js\";\nimport { InputReader, OutputWriter } from \"./endpoint/handlers/types.js\";\nimport { ExecutionOptions } from \"./endpoint/components.js\";\n\nexport class ContextImpl\n implements ObjectContext, WorkflowContext, ContextInternal\n{\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 readonly inputPump: InputPump;\n private readonly runClosuresTracker: RunClosuresTracker;\n readonly promisesExecutor: PromisesExecutor;\n private readonly serviceKey: string;\n private runInterceptor: (\n name: string,\n runner: () => Promise<void>\n ) => Promise<void>;\n private cancellationPromise?: SingleRestatePromise<void>;\n readonly defaultSerde: Serde<any>;\n private readonly asTerminalError?: (error: any) => TerminalError | undefined;\n\n // If undefined, we're not tracking invocation id promises\n private readonly trackedInvocationIdPromises?: SingleRestatePromise<string>[];\n\n constructor(\n readonly coreVm: WasmVM,\n input: WasmInput,\n public readonly console: Console,\n public readonly handlerKind: HandlerKind,\n readonly vmLogger: Console,\n private readonly invocationRequest: Request,\n readonly invocationEndPromise: PromiseWithResolvers<void>,\n inputReader: InputReader,\n outputWriter: OutputWriter,\n readonly journalValueCodec: JournalValueCodec,\n executionOptions?: ExecutionOptions\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 const externalProgressChannel = new ExternalProgressChannel();\n this.runClosuresTracker = new RunClosuresTracker(externalProgressChannel);\n this.inputPump = new InputPump(\n coreVm,\n inputReader,\n externalProgressChannel,\n this.abortAttempt.bind(this)\n );\n this.promisesExecutor = new PromisesExecutor(\n coreVm,\n this.outputPump,\n this.runClosuresTracker,\n externalProgressChannel,\n this.abortAttempt.bind(this)\n );\n this.serviceKey = input.key;\n // Identity interceptor by default; replaced by startUserHandler after hooks are instantiated\n this.runInterceptor = (_name, runner) => runner();\n this.defaultSerde = executionOptions?.defaultSerde ?? serde.json;\n this.asTerminalError = executionOptions?.asTerminalError;\n this.trackedInvocationIdPromises = executionOptions?.explicitCancellation\n ? []\n : undefined;\n }\n\n setRunInterceptor(\n interceptor: (name: string, runner: () => Promise<void>) => Promise<void>\n ) {\n this.runInterceptor = interceptor;\n }\n\n isProcessing(): boolean {\n return this.coreVm.is_processing();\n }\n\n cancel(invocationId: InvocationId): void {\n this._cancel(invocationId);\n }\n\n private _cancel(invocationId: string): 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.serviceKey;\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.abortAttempt(e, WasmCommandType.Call);\n return Object.assign(ConstRestatePromise.pending<RES>(), {\n invocationId: pendingPromise<InvocationId>(),\n });\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.scope,\n call.limitKey,\n call.name\n );\n const commandIndex = this.coreVm.last_command_index();\n\n const invocationIdPromise = new SingleRestatePromise(\n this,\n call_handles.invocation_id_completion_id,\n completeCommandPromiseUsing(\n WasmCommandType.Call,\n commandIndex,\n InvocationIdCompleter\n )\n );\n\n this.trackedInvocationIdPromises?.push(\n invocationIdPromise as SingleRestatePromise<string>\n );\n\n return new InvocationRestatePromise(\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.abortAttempt(e);\n // We return a pending promise to avoid the caller to see the error.\n return Object.assign(ConstRestatePromise.pending<RES>(), {\n invocationId: pendingPromise<InvocationId>(),\n });\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.abortAttempt(e, WasmCommandType.OneWayCall);\n return Object.assign(ConstRestatePromise.pending<void>(), {\n invocationId: pendingPromise<InvocationId>(),\n });\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.scope,\n send.limitKey,\n send.name\n );\n const commandIndex = this.coreVm.last_command_index();\n\n return {\n invocationId: new SingleRestatePromise(\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.abortAttempt(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,\n }: ServiceDefinitionFrom<D>): SendClient<Service<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n undefined\n );\n }\n\n public objectSendClient<D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string\n ): SendClient<VirtualObject<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key\n );\n }\n\n workflowSendClient<D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string\n ): SendClient<Workflow<D>> {\n return makeRpcSendProxy(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key\n );\n }\n\n scope(scopeKey: string): ScopedContext {\n return {\n serviceClient: <D>({ name }: ServiceDefinitionFrom<D>) =>\n makeRpcCallProxy<Client<Service<D>>>(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n undefined,\n scopeKey\n ),\n serviceSendClient: <D>({ name }: ServiceDefinitionFrom<D>) =>\n makeRpcSendProxy<SendClient<Service<D>>>(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n undefined,\n scopeKey\n ),\n objectClient: <D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string\n ) =>\n makeRpcCallProxy<Client<VirtualObject<D>>>(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n key,\n scopeKey\n ),\n objectSendClient: <D>(\n { name }: VirtualObjectDefinitionFrom<D>,\n key: string\n ) =>\n makeRpcSendProxy<SendClient<VirtualObject<D>>>(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key,\n scopeKey\n ),\n workflowClient: <D>({ name }: WorkflowDefinitionFrom<D>, key: string) =>\n makeRpcCallProxy<Client<Workflow<D>>>(\n (call) => this.genericCall(call),\n this.defaultSerde,\n name,\n key,\n scopeKey\n ),\n workflowSendClient: <D>(\n { name }: WorkflowDefinitionFrom<D>,\n key: string\n ) =>\n makeRpcSendProxy<SendClient<Workflow<D>>>(\n (send) => this.genericSend(send),\n this.defaultSerde,\n name,\n key,\n scopeKey\n ),\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 wasmRun: vm.WasmRun;\n try {\n wasmRun = this.coreVm.sys_run(name ?? \"\");\n } catch (e) {\n this.abortAttempt(e);\n return ConstRestatePromise.pending();\n }\n const handle = wasmRun.handle;\n const commandIndex = this.coreVm.last_command_index();\n\n if (!wasmRun.replayed) {\n // Let's prepare the run task only if the run wasnt replayed.\n const doRun: () => Promise<any> = async () => {\n // Execute the user code, wrapping with run interceptor hooks\n const startTime = Date.now();\n let res: T;\n let err;\n try {\n await this.runInterceptor(name ?? \"\", async () => {\n res = await action();\n });\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: Object.entries(err.metadata ?? {}).map(\n ([key, value]) => ({ key, value })\n ),\n });\n } else if (err instanceof RetryableError) {\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 options?.maxRetryDuration !== undefined\n ? BigInt(millisOrDurationToMillis(options?.maxRetryDuration))\n : undefined\n );\n } else if (err instanceof PauseError) {\n this.coreVm.propose_run_completion_failure_transient_with_pause(\n handle,\n err.message,\n err.stack,\n BigInt(attemptDuration)\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?.maxRetryDuration !== undefined ||\n options?.maxRetryInterval !== undefined\n ) {\n retryPolicy = {\n factor: options?.retryIntervalFactor ?? 2.0,\n initial_interval: millisOrDurationToMillis(\n options?.initialRetryInterval ?? 50\n ),\n max_attempts: options?.maxRetryAttempts,\n max_duration:\n options?.maxRetryDuration === undefined\n ? undefined\n : millisOrDurationToMillis(options?.maxRetryDuration),\n max_interval: millisOrDurationToMillis(\n options?.maxRetryInterval ?? { 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.abortAttempt(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\n // TODO: here as well\n // Return the promise\n return new SingleRestatePromise(\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.abortAttempt(e);\n return {\n id: \"invalid\",\n promise: ConstRestatePromise.pending(),\n };\n }\n\n return {\n id: awakeable.id,\n promise: new SingleRestatePromise(\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 | TerminalError): void {\n this.processNonCompletableEntry(\n WasmCommandType.CompleteAwakeable,\n () => {},\n (vm) => {\n vm.sys_complete_awakeable_failure(id, toWasmFailure(reason));\n }\n );\n }\n\n // -- Signals\n\n public signal<T>(name: string, serde?: Serde<T>): RestatePromise<T> {\n let handle: number;\n try {\n handle = this.coreVm.sys_signal(name);\n } catch (e) {\n this.abortAttempt(e);\n return ConstRestatePromise.pending();\n }\n\n return new SingleRestatePromise(\n this,\n handle,\n completeSignalPromiseUsing(\n VoidAsUndefined,\n SuccessWithSerde(serde ?? this.defaultSerde, this.journalValueCodec),\n Failure\n )\n );\n }\n\n public invocation(invocationId: InvocationId): InvocationReference {\n return new InvocationReferenceImpl(this, invocationId);\n }\n\n public promise<T>(name: string, serde?: Serde<T>): DurablePromise<T> {\n return new DurablePromiseImpl(this, name, serde);\n }\n\n cancellation(): RestatePromise<void> {\n if (!this.cancellationPromise || this.cancellationPromise.isCompleted()) {\n this.cancellationPromise = new SingleRestatePromise(\n this,\n 1 /* HANDLE 1 is a hardcoded cancellation signal! */,\n completeSignalPromiseUsing(VoidAsUndefined)\n );\n }\n\n return this.cancellationPromise;\n }\n\n cancelPreviousCalls(): RestatePromise<InvocationId[]> {\n if (!this.trackedInvocationIdPromises) {\n return ConstRestatePromise.resolve([]);\n }\n\n return CombinatorRestatePromise.fromPromises(\n \"AllCompleted\",\n (p: Promise<any>[]) => Promise.allSettled(p),\n this.trackedInvocationIdPromises.splice(0)\n ).map((results, failure) => {\n if (failure) {\n throw failure;\n }\n const cancelled: InvocationId[] = [];\n for (const result of results as PromiseSettledResult<string>[]) {\n if (result.status === \"fulfilled\") {\n this._cancel(result.value);\n cancelled.push(result.value as InvocationId);\n } else {\n this.console.warn(\n `Error when trying to get invocation id: ${result.reason}`\n );\n }\n }\n return cancelled;\n });\n }\n\n // -- Various private methods\n\n 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.abortAttempt(e, commandType);\n return;\n }\n\n try {\n vmCall(this.coreVm, input);\n } catch (e) {\n this.abortAttempt(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.abortAttempt(e, commandType);\n return ConstRestatePromise.pending();\n }\n\n let handle: number;\n try {\n handle = vmCall(this.coreVm, input);\n } catch (e) {\n this.abortAttempt(e);\n return ConstRestatePromise.pending();\n }\n const commandIndex = this.coreVm.last_command_index();\n return new SingleRestatePromise(\n this,\n handle,\n completeCommandPromiseUsing(commandType, commandIndex, ...completers)\n );\n }\n\n abortAttempt(e: unknown, commandType?: WasmCommandType) {\n // ensureError so interceptors always receive a proper Error,\n // not a raw VM object like { code, message }.\n this.invocationEndPromise.reject(\n commandType !== undefined\n ? new CommandError(e, commandType)\n : ensureError(e)\n );\n }\n}\n\nfunction toWasmFailure(reason: string | TerminalError): vm.WasmFailure {\n if (typeof reason === \"string\") {\n return {\n code: UNKNOWN_ERROR_CODE,\n message: reason,\n metadata: [],\n };\n }\n return {\n code: reason.code,\n message: reason.message,\n metadata: Object.entries(reason.metadata ?? {}).map(([key, value]) => ({\n key,\n value,\n })),\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 InvocationReferenceImpl implements InvocationReference {\n constructor(\n private readonly ctx: ContextImpl,\n private readonly invocationId: InvocationId\n ) {}\n\n signal<T>(name: string, serde?: Serde<T>): SignalReference<T> {\n return new SignalReferenceImpl(this.ctx, this.invocationId, name, serde);\n }\n\n cancel(): void {\n this.ctx.cancel(this.invocationId);\n }\n\n attach<T>(serde?: Serde<T>): RestatePromise<T> {\n return this.ctx.attach(this.invocationId, serde);\n }\n}\n\nclass SignalReferenceImpl<T> implements SignalReference<T> {\n private readonly serde: Serde<T>;\n\n constructor(\n private readonly ctx: ContextImpl,\n private readonly invocationId: InvocationId,\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 resolve(payload?: T): void {\n this.ctx.processNonCompletableEntry(\n WasmCommandType.SendSignal,\n () =>\n this.ctx.journalValueCodec.encode(this.serde.serialize(payload as T)),\n (vm, bytes) =>\n vm.sys_complete_signal_success(this.invocationId, this.name, bytes)\n );\n }\n\n reject(reason: string | TerminalError): void {\n this.ctx.processNonCompletableEntry(\n WasmCommandType.SendSignal,\n () => {},\n (vm) => {\n vm.sys_complete_signal_failure(\n this.invocationId,\n this.name,\n toWasmFailure(reason)\n );\n }\n );\n }\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 runsToExecute: Map<number, () => Promise<any>> = new Map<\n number,\n () => Promise<any>\n >();\n\n constructor(private readonly channel: ExternalProgressChannel) {}\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 this.runsToExecute.delete(handle);\n runClosure()\n .finally(() => this.channel.signal())\n .catch(() => {});\n }\n\n registerRunClosure(handle: number, runClosure: () => Promise<any>) {\n this.runsToExecute.set(handle, runClosure);\n }\n}\n\n// ---- Functions used to parse async results\n\ntype Completer = (\n value: AsyncResultValue,\n prom: PromiseWithResolvers<any>\n) => Promise<boolean>;\n\n// Wraps an error with command metadata so the centralized catch in\n// process() can call the right VM notification method.\n//\n// - Preparation failure (command not yet in journal): new CommandError(e, type)\n// → notify_error_for_next_command\n// - Completion failure (command exists): new CommandError(e, type, index)\n// → notify_error_for_specific_command\nexport class CommandError extends Error {\n constructor(cause: unknown, commandType: WasmCommandType);\n constructor(\n cause: unknown,\n commandType: WasmCommandType,\n commandIndex: number\n );\n constructor(\n override readonly cause: unknown,\n readonly commandType: WasmCommandType,\n readonly commandIndex?: number\n ) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n super(msg, { cause });\n }\n\n /** True when the error is for a specific command that exists in the journal. */\n get hasCommandIndex(): boolean {\n return this.commandIndex !== undefined;\n }\n}\n\nfunction completeCommandPromiseUsing<T>(\n commandType: WasmCommandType,\n commandIndex: number,\n ...completers: Array<Completer>\n): (value: AsyncResultValue, prom: PromiseWithResolvers<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: PromiseWithResolvers<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 CommandError(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: PromiseWithResolvers<T>) => Promise<void> {\n return async (value: AsyncResultValue, prom: PromiseWithResolvers<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 const metadata = (value.Failure.metadata ?? []).reduce(\n (\n acc: Record<string, string>,\n { key, value: v }: { key: string; value: string }\n ) => {\n acc[key] = v;\n return acc;\n },\n {} as Record<string, string>\n );\n prom.reject(\n new TerminalError(value.Failure.message, {\n errorCode: value.Failure.code,\n metadata,\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":";;;;;;;;;;AAgFA,IAAa,cAAb,MAEA;CACE,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,AAAS;CACT,AAAiB;CACjB,AAAS;CACT,AAAiB;CACjB,AAAQ;CAIR,AAAQ;CACR,AAAS;CACT,AAAiB;CAGjB,AAAiB;CAEjB,YACE,AAASA,QACT,OACA,AAAgBC,SAChB,AAAgBC,aAChB,AAASC,UACT,AAAiBC,mBACjB,AAASC,sBACT,aACA,cACA,AAASC,mBACT,kBACA;EAXS;EAEO;EACA;EACP;EACQ;EACR;EAGA;AAGT,OAAK,OAAO,IAAI,SAAS,MAAM,mBAAmB,GAOhD;AACF,OAAK,aAAa,IAAI,WAAW,QAAQ,aAAa;EACtD,MAAM,0BAA0B,IAAI,yBAAyB;AAC7D,OAAK,qBAAqB,IAAI,mBAAmB,wBAAwB;AACzE,OAAK,YAAY,IAAI,UACnB,QACA,aACA,yBACA,KAAK,aAAa,KAAK,KAAK,CAC7B;AACD,OAAK,mBAAmB,IAAI,iBAC1B,QACA,KAAK,YACL,KAAK,oBACL,yBACA,KAAK,aAAa,KAAK,KAAK,CAC7B;AACD,OAAK,aAAa,MAAM;AAExB,OAAK,kBAAkB,OAAO,WAAW,QAAQ;AACjD,OAAK,eAAe,kBAAkB,gBAAgB,MAAM;AAC5D,OAAK,kBAAkB,kBAAkB;AACzC,OAAK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C7B,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"}
|
package/dist/package.cjs
CHANGED
package/dist/package.js
CHANGED
package/dist/package.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"@restatedev/restate-sdk\",\n \"version\": \"1.
|
|
1
|
+
{"version":3,"file":"package.js","names":[],"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"@restatedev/restate-sdk\",\n \"version\": \"1.16.0\",\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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@restatedev/restate-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.16.0",
|
|
4
4
|
"description": "Typescript SDK for Restate",
|
|
5
5
|
"author": "Restate Developers",
|
|
6
6
|
"email": "code@restate.dev",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"access": "public"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@restatedev/restate-sdk-core": "1.
|
|
47
|
+
"@restatedev/restate-sdk-core": "1.16.0"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
50
50
|
"@types/aws-lambda": "^8.10.115"
|