@restatedev/restate-sdk-cloudflare-workers 1.9.1 → 1.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/_virtual/rolldown_runtime.cjs +25 -0
- package/dist/common_api.cjs +25 -0
- package/dist/common_api.d.cts +30 -0
- package/dist/common_api.d.cts.map +1 -0
- package/dist/common_api.d.ts +30 -0
- package/dist/common_api.d.ts.map +1 -0
- package/dist/common_api.js +19 -0
- package/dist/common_api.js.map +1 -0
- package/dist/context.cjs +29 -0
- package/dist/context.d.cts +699 -0
- package/dist/context.d.cts.map +1 -0
- package/dist/context.d.ts +699 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +29 -0
- package/dist/context.js.map +1 -0
- package/dist/context_impl.cjs +441 -0
- package/dist/context_impl.js +440 -0
- package/dist/context_impl.js.map +1 -0
- package/dist/endpoint/components.cjs +257 -0
- package/dist/endpoint/components.js +253 -0
- package/dist/endpoint/components.js.map +1 -0
- package/dist/endpoint/endpoint.cjs +117 -0
- package/dist/endpoint/endpoint.js +118 -0
- package/dist/endpoint/endpoint.js.map +1 -0
- package/dist/endpoint/fetch_endpoint.cjs +41 -0
- package/dist/endpoint/fetch_endpoint.d.cts +39 -0
- package/dist/endpoint/fetch_endpoint.d.cts.map +1 -0
- package/dist/endpoint/fetch_endpoint.d.ts +39 -0
- package/dist/endpoint/fetch_endpoint.d.ts.map +1 -0
- package/dist/endpoint/fetch_endpoint.js +42 -0
- package/dist/endpoint/fetch_endpoint.js.map +1 -0
- package/dist/endpoint/handlers/fetch.cjs +21 -0
- package/dist/endpoint/handlers/fetch.js +21 -0
- package/dist/endpoint/handlers/fetch.js.map +1 -0
- package/dist/endpoint/handlers/generic.cjs +328 -0
- package/dist/endpoint/handlers/generic.js +324 -0
- package/dist/endpoint/handlers/generic.js.map +1 -0
- package/dist/endpoint/handlers/lambda.cjs +93 -0
- package/dist/endpoint/handlers/lambda.js +89 -0
- package/dist/endpoint/handlers/lambda.js.map +1 -0
- package/dist/endpoint/lambda_endpoint.cjs +36 -0
- package/dist/endpoint/lambda_endpoint.d.cts +26 -0
- package/dist/endpoint/lambda_endpoint.d.cts.map +1 -0
- package/dist/endpoint/lambda_endpoint.d.ts +26 -0
- package/dist/endpoint/lambda_endpoint.d.ts.map +1 -0
- package/dist/endpoint/lambda_endpoint.js +37 -0
- package/dist/endpoint/lambda_endpoint.js.map +1 -0
- package/dist/endpoint/node_endpoint.cjs +101 -0
- package/dist/endpoint/node_endpoint.js +99 -0
- package/dist/endpoint/node_endpoint.js.map +1 -0
- package/dist/endpoint/types.d.cts +61 -0
- package/dist/endpoint/types.d.cts.map +1 -0
- package/dist/endpoint/types.d.ts +61 -0
- package/dist/endpoint/types.d.ts.map +1 -0
- package/dist/endpoint/withOptions.cjs +15 -0
- package/dist/endpoint/withOptions.js +15 -0
- package/dist/endpoint/withOptions.js.map +1 -0
- package/dist/endpoint.d.cts +112 -0
- package/dist/endpoint.d.cts.map +1 -0
- package/dist/endpoint.d.ts +112 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/fetch.cjs +83 -0
- package/dist/fetch.d.cts +52 -0
- package/dist/fetch.d.cts.map +1 -0
- package/dist/fetch.d.ts +52 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/{esm/src/fetch.js → fetch.js} +15 -18
- package/dist/fetch.js.map +1 -0
- package/dist/index.cjs +48 -0
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +7 -0
- package/dist/io.cjs +48 -0
- package/dist/io.js +48 -0
- package/dist/io.js.map +1 -0
- package/dist/lambda.cjs +74 -0
- package/dist/lambda.d.cts +32 -0
- package/dist/lambda.d.cts.map +1 -0
- package/dist/lambda.d.ts +32 -0
- package/dist/lambda.d.ts.map +1 -0
- package/dist/lambda.js +35 -0
- package/dist/lambda.js.map +1 -0
- package/dist/logging/console_logger_transport.cjs +54 -0
- package/dist/logging/console_logger_transport.js +54 -0
- package/dist/logging/console_logger_transport.js.map +1 -0
- package/dist/logging/logger.cjs +43 -0
- package/dist/logging/logger.js +44 -0
- package/dist/logging/logger.js.map +1 -0
- package/dist/logging/logger_transport.cjs +42 -0
- package/dist/logging/logger_transport.d.cts +57 -0
- package/dist/logging/logger_transport.d.cts.map +1 -0
- package/dist/logging/logger_transport.d.ts +57 -0
- package/dist/logging/logger_transport.d.ts.map +1 -0
- package/dist/logging/logger_transport.js +40 -0
- package/dist/logging/logger_transport.js.map +1 -0
- package/dist/node.cjs +90 -0
- package/dist/node.d.cts +51 -0
- package/dist/node.d.cts.map +1 -0
- package/dist/node.d.ts +51 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +50 -0
- package/dist/node.js.map +1 -0
- package/dist/package.cjs +11 -0
- package/dist/package.js +6 -0
- package/dist/package.js.map +1 -0
- package/dist/promises.cjs +234 -0
- package/dist/promises.js +226 -0
- package/dist/promises.js.map +1 -0
- package/dist/types/errors.cjs +110 -0
- package/dist/types/errors.d.cts +71 -0
- package/dist/types/errors.d.cts.map +1 -0
- package/dist/types/errors.d.ts +71 -0
- package/dist/types/errors.d.ts.map +1 -0
- package/dist/types/errors.js +102 -0
- package/dist/types/errors.js.map +1 -0
- package/dist/types/rpc.cjs +425 -0
- package/dist/types/rpc.d.cts +580 -0
- package/dist/types/rpc.d.cts.map +1 -0
- package/dist/types/rpc.d.ts +580 -0
- package/dist/types/rpc.d.ts.map +1 -0
- package/dist/types/rpc.js +406 -0
- package/dist/types/rpc.js.map +1 -0
- package/dist/user_agent.cjs +7 -0
- package/dist/user_agent.js +8 -0
- package/dist/user_agent.js.map +1 -0
- package/dist/utils/completable_promise.cjs +22 -0
- package/dist/utils/completable_promise.js +22 -0
- package/dist/utils/completable_promise.js.map +1 -0
- package/dist/utils/rand.cjs +72 -0
- package/dist/utils/rand.js +71 -0
- package/dist/utils/rand.js.map +1 -0
- package/dist/utils/streams.cjs +14 -0
- package/dist/utils/streams.js +13 -0
- package/dist/utils/streams.js.map +1 -0
- package/package.json +30 -52
- package/dist/esm/src/common_api.d.ts +0 -37
- package/dist/esm/src/common_api.d.ts.map +0 -1
- package/dist/esm/src/common_api.js +0 -32
- package/dist/esm/src/common_api.js.map +0 -1
- package/dist/esm/src/context.d.ts +0 -695
- package/dist/esm/src/context.d.ts.map +0 -1
- package/dist/esm/src/context.js +0 -87
- package/dist/esm/src/context.js.map +0 -1
- package/dist/esm/src/context_impl.d.ts +0 -69
- package/dist/esm/src/context_impl.d.ts.map +0 -1
- package/dist/esm/src/context_impl.js +0 -592
- package/dist/esm/src/context_impl.js.map +0 -1
- package/dist/esm/src/endpoint/components.d.ts +0 -97
- package/dist/esm/src/endpoint/components.d.ts.map +0 -1
- package/dist/esm/src/endpoint/components.js +0 -343
- package/dist/esm/src/endpoint/components.js.map +0 -1
- package/dist/esm/src/endpoint/discovery.d.ts +0 -184
- package/dist/esm/src/endpoint/discovery.d.ts.map +0 -1
- package/dist/esm/src/endpoint/discovery.js +0 -8
- package/dist/esm/src/endpoint/discovery.js.map +0 -1
- package/dist/esm/src/endpoint/endpoint.d.ts +0 -39
- package/dist/esm/src/endpoint/endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/endpoint.js +0 -155
- package/dist/esm/src/endpoint/endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/fetch_endpoint.d.ts +0 -49
- package/dist/esm/src/endpoint/fetch_endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/fetch_endpoint.js +0 -49
- package/dist/esm/src/endpoint/fetch_endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/handlers/fetch.d.ts +0 -5
- package/dist/esm/src/endpoint/handlers/fetch.d.ts.map +0 -1
- package/dist/esm/src/endpoint/handlers/fetch.js +0 -31
- package/dist/esm/src/endpoint/handlers/fetch.js.map +0 -1
- package/dist/esm/src/endpoint/handlers/generic.d.ts +0 -61
- package/dist/esm/src/endpoint/handlers/generic.d.ts.map +0 -1
- package/dist/esm/src/endpoint/handlers/generic.js +0 -470
- package/dist/esm/src/endpoint/handlers/generic.js.map +0 -1
- package/dist/esm/src/endpoint/handlers/lambda.d.ts +0 -10
- package/dist/esm/src/endpoint/handlers/lambda.d.ts.map +0 -1
- package/dist/esm/src/endpoint/handlers/lambda.js +0 -143
- package/dist/esm/src/endpoint/handlers/lambda.js.map +0 -1
- package/dist/esm/src/endpoint/lambda_endpoint.d.ts +0 -30
- package/dist/esm/src/endpoint/lambda_endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/lambda_endpoint.js +0 -48
- package/dist/esm/src/endpoint/lambda_endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/node_endpoint.d.ts +0 -16
- package/dist/esm/src/endpoint/node_endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/node_endpoint.js +0 -124
- package/dist/esm/src/endpoint/node_endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/types.d.ts +0 -55
- package/dist/esm/src/endpoint/types.d.ts.map +0 -1
- package/dist/esm/src/endpoint/types.js +0 -2
- package/dist/esm/src/endpoint/types.js.map +0 -1
- package/dist/esm/src/endpoint/withOptions.d.ts +0 -4
- package/dist/esm/src/endpoint/withOptions.d.ts.map +0 -1
- package/dist/esm/src/endpoint/withOptions.js +0 -19
- package/dist/esm/src/endpoint/withOptions.js.map +0 -1
- package/dist/esm/src/endpoint.d.ts +0 -108
- package/dist/esm/src/endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint.js +0 -12
- package/dist/esm/src/endpoint.js.map +0 -1
- package/dist/esm/src/fetch.d.ts +0 -43
- package/dist/esm/src/fetch.d.ts.map +0 -1
- package/dist/esm/src/fetch.js.map +0 -1
- package/dist/esm/src/generated/version.d.ts +0 -2
- package/dist/esm/src/generated/version.d.ts.map +0 -1
- package/dist/esm/src/generated/version.js +0 -2
- package/dist/esm/src/generated/version.js.map +0 -1
- package/dist/esm/src/io.d.ts +0 -24
- package/dist/esm/src/io.d.ts.map +0 -1
- package/dist/esm/src/io.js +0 -73
- package/dist/esm/src/io.js.map +0 -1
- package/dist/esm/src/lambda.d.ts +0 -23
- package/dist/esm/src/lambda.d.ts.map +0 -1
- package/dist/esm/src/lambda.js +0 -37
- package/dist/esm/src/lambda.js.map +0 -1
- package/dist/esm/src/logging/console_logger_transport.d.ts +0 -5
- package/dist/esm/src/logging/console_logger_transport.d.ts.map +0 -1
- package/dist/esm/src/logging/console_logger_transport.js +0 -94
- package/dist/esm/src/logging/console_logger_transport.js.map +0 -1
- package/dist/esm/src/logging/logger.d.ts +0 -10
- package/dist/esm/src/logging/logger.d.ts.map +0 -1
- package/dist/esm/src/logging/logger.js +0 -57
- package/dist/esm/src/logging/logger.js.map +0 -1
- package/dist/esm/src/logging/logger_transport.d.ts +0 -52
- package/dist/esm/src/logging/logger_transport.d.ts.map +0 -1
- package/dist/esm/src/logging/logger_transport.js +0 -55
- package/dist/esm/src/logging/logger_transport.js.map +0 -1
- package/dist/esm/src/node.d.ts +0 -39
- package/dist/esm/src/node.d.ts.map +0 -1
- package/dist/esm/src/node.js +0 -52
- package/dist/esm/src/node.js.map +0 -1
- package/dist/esm/src/promises.d.ts +0 -111
- package/dist/esm/src/promises.d.ts.map +0 -1
- package/dist/esm/src/promises.js +0 -314
- package/dist/esm/src/promises.js.map +0 -1
- package/dist/esm/src/public_api.d.ts +0 -2
- package/dist/esm/src/public_api.d.ts.map +0 -1
- package/dist/esm/src/public_api.js +0 -12
- package/dist/esm/src/public_api.js.map +0 -1
- package/dist/esm/src/types/errors.d.ts +0 -74
- package/dist/esm/src/types/errors.d.ts.map +0 -1
- package/dist/esm/src/types/errors.js +0 -128
- package/dist/esm/src/types/errors.js.map +0 -1
- package/dist/esm/src/types/rpc.d.ts +0 -620
- package/dist/esm/src/types/rpc.d.ts.map +0 -1
- package/dist/esm/src/types/rpc.js +0 -577
- package/dist/esm/src/types/rpc.js.map +0 -1
- package/dist/esm/src/user_agent.d.ts +0 -2
- package/dist/esm/src/user_agent.d.ts.map +0 -1
- package/dist/esm/src/user_agent.js +0 -13
- package/dist/esm/src/user_agent.js.map +0 -1
- package/dist/esm/src/utils/completable_promise.d.ts +0 -9
- package/dist/esm/src/utils/completable_promise.d.ts.map +0 -1
- package/dist/esm/src/utils/completable_promise.js +0 -30
- package/dist/esm/src/utils/completable_promise.js.map +0 -1
- package/dist/esm/src/utils/rand.d.ts +0 -13
- package/dist/esm/src/utils/rand.d.ts.map +0 -1
- package/dist/esm/src/utils/rand.js +0 -109
- package/dist/esm/src/utils/rand.js.map +0 -1
- package/dist/esm/src/utils/streams.d.ts +0 -3
- package/dist/esm/src/utils/streams.d.ts.map +0 -1
- package/dist/esm/src/utils/streams.js +0 -20
- package/dist/esm/src/utils/streams.js.map +0 -1
- package/dist/esm/tsconfig.tsbuildinfo +0 -1
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings.d.ts +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings.js +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.js +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","names":[],"sources":["../src/context.ts"],"sourcesContent":[],"mappings":";;;;;;;;AAoCA;;;;AAyCmC,UAzClB,OAAA,CAyCkB;EAAW;AAI9C;AACA;AAKA;EAA8C,SAAA,EAAA,EAAA,MAAA;EAYb;;;;EAEf,SAAA,OAAA,EAtDE,WAsDF,CAAA,MAAA,EAAA,MAAA,CAAA;EAAe;;;;;EACnB,SAAA,cAAA,EAhDa,WAgDb,CAAA,MAAA,EAAA,MAAA,GAAA,MAAA,EAAA,GAAA,SAAA,CAAA;EAAe;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ACzD,oBAAoB,SAAS;;;;;;;;;;;;;;;;;;;;;;;;mCAwBJ,MAAM,KAAK,eAAe;;UAG5C,+BAA+B,aAAa,sBAEzD,sBAAsB,SACtB,cAAc,SACd"}
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { ContextImpl } from "./context_impl.js";
|
|
2
|
+
|
|
3
|
+
//#region src/context.ts
|
|
4
|
+
const InvocationIdParser = { fromString(id) {
|
|
5
|
+
if (!id.startsWith("inv")) throw new Error(`Expected invocation id to start with 'inv' but got ${id}`);
|
|
6
|
+
return id;
|
|
7
|
+
} };
|
|
8
|
+
const RestatePromise = {
|
|
9
|
+
all(values) {
|
|
10
|
+
if (values.length === 0) throw new Error("Expected combineable promise to have at least one promise");
|
|
11
|
+
return ContextImpl.createCombinator((p) => Promise.all(p), values);
|
|
12
|
+
},
|
|
13
|
+
race(values) {
|
|
14
|
+
if (values.length === 0) throw new Error("Expected combineable promise to have at least one promise");
|
|
15
|
+
return ContextImpl.createCombinator((p) => Promise.race(p), values);
|
|
16
|
+
},
|
|
17
|
+
any(values) {
|
|
18
|
+
if (values.length === 0) throw new Error("Expected combineable promise to have at least one promise");
|
|
19
|
+
return ContextImpl.createCombinator((p) => Promise.any(p), values);
|
|
20
|
+
},
|
|
21
|
+
allSettled(values) {
|
|
22
|
+
if (values.length === 0) throw new Error("Expected combineable promise to have at least one promise");
|
|
23
|
+
return ContextImpl.createCombinator((p) => Promise.allSettled(p), values);
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { InvocationIdParser, RestatePromise };
|
|
29
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport type { Client, SendClient } from \"./types/rpc.js\";\nimport type {\n RestateContext,\n RestateObjectContext,\n RestateObjectSharedContext,\n RestateWorkflowContext,\n RestateWorkflowSharedContext,\n Service,\n ServiceDefinitionFrom,\n VirtualObject,\n VirtualObjectDefinitionFrom,\n Workflow,\n WorkflowDefinitionFrom,\n Serde,\n Duration,\n} from \"@restatedev/restate-sdk-core\";\nimport { ContextImpl } from \"./context_impl.js\";\nimport type { TerminalError } from \"./types/errors.js\";\n\n/**\n * Represents the original request as sent to this handler.\n *\n * A request object includes the request headers, and the raw unparsed\n * request body.\n */\nexport interface Request {\n /**\n * The unique id that identifies the current function invocation. This id is guaranteed to be\n * unique across invocations, but constant across reties and suspensions.\n */\n readonly id: string;\n\n /**\n * Request headers - the following headers capture the original invocation headers, as provided to\n * the ingress.\n */\n readonly headers: ReadonlyMap<string, string>;\n\n /**\n * Attempt headers - the following headers are sent by the restate runtime.\n * These headers are attempt specific, generated by the restate runtime uniquely for each attempt.\n * These headers might contain information such as the W3C trace context, and attempt specific information.\n */\n readonly attemptHeaders: ReadonlyMap<string, string | string[] | undefined>;\n\n /**\n * Raw unparsed request body\n */\n readonly body: Uint8Array;\n\n /**\n * Extra arguments provided to the request handler:\n * Lambda: [Context]\n * Cloudflare workers: [Env, ExecutionContext]\n * Deno: [ConnInfo]\n * Bun: [Server]\n * These arguments can contain request-specific values that could change after a suspension.\n * Care should be taken to use them deterministically.\n */\n readonly extraArgs: unknown[];\n\n /**\n * This is a signal that is aborted when the current attempt has been completed either successful or unsuccessfully.\n * When the signal is aborted, the current attempt has been completed and the handler should not perform any more work, other\n * than cleanup any external resources that might be shared across attempts (e.g. database connections).\n */\n readonly attemptCompletedSignal: AbortSignal;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nexport type TypedState = Record<string, any>;\nexport type UntypedState = { _: never };\n\n/**\n * Key value store operations. Only keyed services have an attached key-value store.\n */\nexport interface KeyValueStore<TState extends TypedState> {\n /**\n * Get/retrieve state from the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to retrieve\n * @returns a Promise that is resolved with the value of the state key\n *\n * @example\n * const state = await ctx.get<string>(\"STATE\");\n */\n get<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;\n\n stateKeys(): Promise<Array<string>>;\n\n /**\n * Set/store state in the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to set\n * @param value value to set\n *\n * @example\n * ctx.set(\"STATE\", \"Hello\");\n */\n set<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n value: TState extends UntypedState ? TValue : TState[TKey],\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): void;\n\n /**\n * Clear/delete state in the Restate runtime.\n * @param name key of the state to delete\n *\n * @example\n * ctx.clear(\"STATE\");\n */\n clear<TKey extends keyof TState>(\n name: TState extends UntypedState ? string : TKey\n ): void;\n\n /**\n * Clear/delete all the state entries in the Restate runtime.\n *\n * @example\n * ctx.clearAll();\n */\n clearAll(): void;\n}\n\n/**\n * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead\n */\nexport interface SendOptions {\n /**\n * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead\n */\n delay?: number;\n}\n\nexport interface ContextDate {\n /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).\n * This is equivalent to Date.now()\n */\n now(): Promise<number>;\n /** Returns the JSON representation of the current date.\n * This is equivalent to new Date().toJSON()\n **/\n toJSON(): Promise<string>;\n}\n\n/**\n * A function that can be run and its result durably persisted by Restate.\n */\nexport type RunAction<T> = (() => Promise<T>) | (() => T);\n\nexport type RunOptions<T> = {\n serde?: Serde<T>;\n\n /**\n * Max number of attempts (including the initial), before giving up.\n *\n * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.\n */\n maxRetryAttempts?: number;\n\n /**\n * @deprecated Use `maxRetryDuration` instead.\n */\n maxRetryDurationMillis?: number;\n\n /**\n * Max duration of retries, before giving up.\n *\n * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxRetryDuration?: Duration | number;\n\n /**\n * @deprecated Use `initialRetryInterval` instead.\n */\n initialRetryIntervalMillis?: number;\n\n /**\n * Initial interval for the first retry attempt.\n * Retry interval will grow by a factor specified in `retryIntervalFactor`.\n *\n * The default is 50 milliseconds.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n initialRetryInterval?: Duration | number;\n\n /**\n * @deprecated Use `maxRetryInterval` instead.\n */\n maxRetryIntervalMillis?: number;\n\n /**\n * Max interval between retries.\n * Retry interval will grow by a factor specified in `retryIntervalFactor`.\n *\n * The default is 10 seconds.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxRetryInterval?: Duration | number;\n\n /**\n * Exponentiation factor to use when computing the next retry delay.\n *\n * The default value is `2`, meaning retry interval will double at each attempt.\n */\n retryIntervalFactor?: number;\n};\n\n/**\n * Call a handler directly avoiding restate's type safety checks.\n * This is a generic mechanism to invoke handlers directly by only knowing\n * the service and handler name, (or key in the case of objects or workflows)\n */\nexport type GenericCall<REQ, RES> = {\n service: string;\n method: string;\n parameter: REQ;\n key?: string;\n headers?: Record<string, string>;\n inputSerde?: Serde<REQ>;\n outputSerde?: Serde<RES>;\n idempotencyKey?: string;\n};\n\n/**\n * Send a message to an handler directly avoiding restate's type safety checks.\n * This is a generic mechanism to invoke handlers directly by only knowing\n * the service and handler name, (or key in the case of objects or workflows)\n */\nexport type GenericSend<REQ> = {\n service: string;\n method: string;\n parameter: REQ;\n key?: string;\n headers?: Record<string, string>;\n inputSerde?: Serde<REQ>;\n delay?: Duration | number;\n idempotencyKey?: string;\n};\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * Virtual objects can also access their key-value store using the {@link ObjectContext}.\n *\n */\nexport interface Context extends RestateContext {\n /**\n * Deterministic random methods; these are inherently predictable (seeded on the invocation ID, which is not secret)\n * and so should not be used for any cryptographic purposes. They are useful for identifiers, idempotency keys,\n * and for uniform sampling from a set of options. If a cryptographically secure value is needed, please generate that\n * externally and capture the result with a side effect.\n *\n * Calls to these methods from inside `ctx.run` are disallowed and will fail - side effects must be idempotent, and\n * these calls are not.\n */\n rand: Rand;\n\n /**\n * Console to use for logging. It attaches to each log message some contextual information,\n * such as invoked service method and invocation id, and automatically excludes logs during replay.\n */\n console: Console;\n\n /**\n * Deterministic date.\n */\n date: ContextDate;\n\n /**\n * Run an operation and store the result in Restate. The operation will thus not\n * be re-run during a later replay, but take the durable result from Restate.\n *\n * This let you capture potentially non-deterministic computation and interaction\n * with external systems in a safe way.\n *\n * Failure semantics are:\n * - If an operation has run and persisted before, the result (value or Error) will be\n * taken from the Restate journal.\n * - There is a small window where an action may be re-run, if a failure\n * occurred between a successful run and persisting the result.\n * - No second action will be run while a previous run's result is not\n * yet durable. That way, effects that build on top of each other can assume\n * deterministic results from previous runs, and at most one run will be\n * re-executed on replay (the latest, if the failure happened in the small windows\n * described above).\n *\n * You can customize retry options by either:\n *\n * - Providing retry policy options in {@link RunOptions}\n * - Throwing {@link RetryableError}, providing `retryAfter` option. This can be especially useful when interacting with HTTP requests returning the `Retry-After` header. You can combine the usage of throwing {@link RetryableError} with the `maxRetryAttempts`/`maxRetryDuration` from {@link RunOptions}.\n *\n * @example Run some external action and persist its result\n * ```ts\n * const result = await ctx.run(someExternalAction)\n *```\n * @example Add some retry options\n * ```ts\n * const result = await ctx.run(\"my action\", someExternalAction, { maxRetryAttempts: 10 })\n * ```\n * @example Terminal errors and retryable errors\n * ```ts\n * await ctx.run(\"payment action\", async () => {\n * const result = await paymentProvider.charge(txId, paymentInfo);\n * if (result.paymentRejected) {\n * // this action will not be retried anymore\n * throw new TerminalError(\"Payment failed\");\n * } else if (result.paymentGatewayBusy) {\n * // restate will retry automatically\n * // to bound retries, use RunOptions\n * throw new Error(\"Payment gateway busy\");\n * } else {\n * // success!\n * }\n * });\n * ```\n * @example Retryable error with custom retry delay\n * ```ts\n * await ctx.run(\"payment action\", async () => {\n * const res = fetch(...);\n * if (!res.ok) {\n * // Read Retry-After header\n * const retryAfterHeader = res.headers['Retry-After']\n *\n * // Use RetryableError to customize in how long to retry\n * throw RetryableError.from(cause, { retryAfter: { seconds: retryAfterHeader } })\n * }\n * }, {\n * // Retry at most ten times\n * maxRetryAttempts: 10\n * });\n * ```\n *\n * @param action The function to run.\n */\n run<T>(action: RunAction<T>): RestatePromise<T>;\n\n /**\n * Same as {@link run}, but providing a name, used for observability purposes.\n */\n run<T>(name: string, action: RunAction<T>): RestatePromise<T>;\n\n /**\n * See {@link run}\n */\n run<T>(\n name: string,\n action: RunAction<T>,\n options: RunOptions<T>\n ): RestatePromise<T>;\n\n /**\n * Register an awakeable and pause the processing until the awakeable ID (and optional payload) have been returned to the service\n * (via ctx.completeAwakeable(...)). The SDK deserializes the payload with `JSON.parse(result.toString()) as T`.\n * @returns\n * - id: the string ID that has to be used to complete the awakaeble by some external service\n * - promise: the Promise that needs to be awaited and that is resolved with the payload that was supplied by the service which completed the awakeable\n * @example Retryable errors and terminal errors\n * const awakeable = ctx.awakeable<string>();\n *\n * // send the awakeable ID to some external service that will wake this one back up\n * // The ID can be retrieved by:\n * const id = awakeable.id;\n *\n * // ... send to external service ...\n *\n * // Wait for the external service to wake this service back up\n * const result = await awakeable.promise;\n */\n awakeable<T>(serde?: Serde<T>): {\n id: string;\n promise: RestatePromise<T>;\n };\n\n /**\n * Resolve an awakeable.\n * @param id the string ID of the awakeable.\n * This is supplied by the service that needs to be woken up.\n * @param payload the payload to pass to the service that is woken up.\n * The SDK serializes the payload with `Buffer.from(JSON.stringify(payload))`\n * and deserializes it in the receiving service with `JSON.parse(result.toString()) as T`.\n * @example Retryable error with custom retry delay\n * // The sleeping service should have sent the awakeableIdentifier string to this service.\n * ctx.resolveAwakeable(awakeableIdentifier, \"hello\");\n */\n resolveAwakeable<T>(id: string, payload?: T, serde?: Serde<T>): void;\n\n /**\n * Reject an awakeable. When rejecting, the service waiting on this awakeable will be woken up with a terminal error with the provided reason.\n * @param id the string ID of the awakeable.\n * This is supplied by the service that needs to be woken up.\n * @param reason the reason of the rejection.\n *\n * @example\n * // The sleeping service should have sent the awakeableIdentifier string to this service.\n * ctx.rejectAwakeable(awakeableIdentifier, \"super bad error\");\n */\n rejectAwakeable(id: string, reason: string): void;\n\n /**\n * Sleep until a timeout has passed.\n * @param duration either Duration type or milliseconds.\n * @param name Observability name. This will be shown in the UI.\n * This is a lower-bound.\n *\n * @example\n * await ctx.sleep(1000);\n */\n sleep(duration: Duration | number, name?: string): RestatePromise<void>;\n\n /**\n * Makes a type-safe request/response RPC to the specified target service.\n *\n * The RPC goes through Restate and is guaranteed to be reliably delivered. The RPC is also\n * journaled for durable execution and will thus not be duplicated when the handler is re-invoked\n * for retries or after suspending.\n *\n * This call will return the result produced by the target handler, or the Error, if the target\n * handler finishes with a Terminal Error.\n *\n * This call is a suspension point: The handler might suspend while awaiting the response and\n * resume once the response is available.\n *\n * @example\n * *Service Side:*\n * ```ts\n * const service = restate.service(\n * name: \"myservice\",\n * handlers: {\n * someAction: async(ctx: restate.Context, req: string) => { ... },\n * anotherAction: async(ctx: restate.Context, count: number) => { ... }\n * });\n *\n * // option 1: export only the type signature\n * export type Service = typeof service;\n *\n *\n * restate.serve({ services: [service], port: 9080 });\n * ```\n * *Client side:*\n * ```ts\n * // option 1: use only types and supply service name separately\n * const result1 = await ctx.serviceClient<Service>({name: \"myservice\"}).someAction(\"hello!\");\n *\n * // option 2: use full API spec\n * type MyService: Service = { name: \"myservice\" };\n * const result2 = await ctx.serviceClient(Service).anotherAction(1337);\n * ```\n */\n serviceClient<D>(opts: ServiceDefinitionFrom<D>): Client<Service<D>>;\n\n /**\n * Same as {@link serviceClient} but for virtual objects.\n *\n * @param opts\n * @param key the virtual object key\n */\n objectClient<D>(\n opts: VirtualObjectDefinitionFrom<D>,\n key: string\n ): Client<VirtualObject<D>>;\n\n /**\n * Same as {@link serviceClient} but for workflows.\n *\n * @param opts\n * @param key the workflow key\n */\n workflowClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): Client<Workflow<D>>;\n\n /**\n * Same as {@link objectSendClient} but for workflows.\n *\n * @param opts\n * @param key the workflow key\n */\n workflowSendClient<D>(\n opts: WorkflowDefinitionFrom<D>,\n key: string\n ): SendClient<Workflow<D>>;\n\n /**\n * Makes a type-safe one-way RPC to the specified target service. This method effectively behaves\n * like enqueuing the message in a message queue.\n *\n * The message goes through Restate and is guaranteed to be reliably delivered. The RPC is also\n * journaled for durable execution and will thus not be duplicated when the handler is re-invoked\n * for retries or after suspending.\n *\n * This call will return immediately; the message sending happens asynchronously in the background.\n * Despite that, the message is guaranteed to be sent, because the completion of the invocation that\n * triggers the send (calls this function) happens logically after the sending. That means that any\n * failure where the message does not reach Restate also cannot complete this invocation, and will\n * hence recover this handler and (through the durable execution) recover the message to be sent.\n *\n * @example\n * *Service Side:*\n * ```ts\n * const service = restate.service(\n * name: \"myservice\",\n * handlers: {\n * someAction: async(ctx: restate.Context, req: string) => { ... },\n * anotherAction: async(ctx: restate.Context, count: number) => { ... }\n * });\n *\n * // option 1: export only the type signature of the router\n * export type MyApi = typeof service;\n *\n * // option 2: export the API definition with type and name (name)\n * const MyService: MyApi = { name: \"myservice\" };\n *\n * restate.serve({ services: [service], port: 9080 });\n * ```\n * *Client side:*\n * ```ts\n * // option 1: use only types and supply service name separately\n * ctx.serviceSendClient<MyApi>({name: \"myservice\"}).someAction(\"hello!\");\n *\n * // option 2: use full API spec\n * ctx.serviceSendClient(MyService).anotherAction(1337);\n * ```\n */\n serviceSendClient<D>(\n service: ServiceDefinitionFrom<D>,\n opts?: SendOptions\n ): SendClient<Service<D>>;\n\n /**\n * Same as {@link serviceSendClient} but for virtual objects.\n *\n * @param obj\n * @param key the virtual object key\n * @param opts Send options\n */\n objectSendClient<D>(\n obj: VirtualObjectDefinitionFrom<D>,\n key: string,\n opts?: SendOptions\n ): SendClient<VirtualObject<D>>;\n\n genericCall<REQ = Uint8Array, RES = Uint8Array>(\n call: GenericCall<REQ, RES>\n ): InvocationPromise<RES>;\n\n genericSend<REQ = Uint8Array>(call: GenericSend<REQ>): InvocationHandle;\n\n /**\n * Returns the raw request that triggered that handler.\n * Use that object to inspect the original request headers\n */\n request(): Request;\n\n /**\n * Cancel an invocation\n *\n * @param invocationId the invocation id to cancel\n */\n cancel(invocationId: InvocationId): void;\n\n /**\n * Attach to an invocation\n *\n * @param invocationId the invocation id to attach to\n * @param serde the serde to use for the result, default to JSON serde.\n */\n attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T>;\n}\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - access/update state\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * This context can be used only within virtual objects.\n *\n */\nexport interface ObjectContext<TState extends TypedState = UntypedState>\n extends Context, KeyValueStore<TState>, RestateObjectContext {\n key: string;\n}\n\n/**\n * The context that gives access to all Restate-backed operations, for example\n * - sending reliable messages / RPC through Restate\n * - execute non-deterministic closures and memoize their result\n * - sleeps and delayed calls\n * - awakeables\n * - ...\n *\n * This context can be used only within a shared virtual objects.\n *\n */\nexport interface ObjectSharedContext<TState extends TypedState = UntypedState>\n extends Context, RestateObjectSharedContext {\n key: string;\n\n /**\n * Get/retrieve state from the Restate runtime.\n * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`\n * and deserialized with `JSON.parse(value.toString()) as T`.\n *\n * @param name key of the state to retrieve\n * @returns a Promise that is resolved with the value of the state key\n *\n * @example\n * const state = await ctx.get<string>(\"STATE\");\n */\n get<TValue, TKey extends keyof TState = string>(\n name: TState extends UntypedState ? string : TKey,\n serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>\n ): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;\n\n /**\n * Retrieve all the state keys for this object.\n */\n stateKeys(): Promise<Array<string>>;\n}\n\nexport interface Rand {\n /**\n * Equivalent of JS `Math.random()` but deterministic; seeded by the invocation ID of the current invocation,\n * each call will return a new pseudorandom float within the range [0,1)\n */\n random(): number;\n\n /**\n * Using the same random source and seed as random(), produce a UUID version 4 string. This is inherently predictable\n * based on the invocation ID and should not be used in cryptographic contexts\n */\n uuidv4(): string;\n}\n\n/**\n * A promise that can be combined using Promise combinators in RestateContext.\n */\nexport type RestatePromise<T> = Promise<T> & {\n /**\n * Creates a promise that awaits for the current promise up to the specified timeout duration.\n * If the timeout is fired, this Promise will be rejected with a {@link TimeoutError}.\n *\n * @param millis duration of the sleep in millis.\n * This is a lower-bound.\n */\n orTimeout(millis: Duration | number): RestatePromise<T>;\n\n /**\n * Creates a new {@link RestatePromise} that maps the result of this promise with\n * the provided `mapper`, once this promise is fulfilled.\n *\n * **NOTE**: You **MUST** use this API when you need to map the result of a\n * {@link RestatePromise} without `await`ing it, rather than using {@link Promise.then}.\n * {@link Promise.then} is used by Restate to distinguish when awaiting an asynchronous operation,\n * thus calling `.then` on several Restate promises can lead to concurrency issues.\n *\n * @param mapper the function to execute when this promise is fulfilled.\n * If the promise completed successfully, `value` is provided as input, otherwise `failure` is provided as input.\n * If this mapper returns a value, this value will be used to resolve the returned {@link RestatePromise}.\n * If the mapper throws a {@link TerminalError}, this error will be used to reject the returned {@link RestatePromise}.\n */\n map<U>(mapper: (value?: T, failure?: TerminalError) => U): RestatePromise<U>;\n};\n\n/**\n * Represents an invocation id.\n * @see {@link InvocationIdParser}\n */\nexport type InvocationId = string & { __brand: \"InvocationId\" };\n\nexport const InvocationIdParser = {\n /**\n * Creates an invocation id from a string.\n * @param id the string to use as invocation id.\n */\n fromString(id: string): InvocationId {\n if (!id.startsWith(\"inv\")) {\n throw new Error(\n `Expected invocation id to start with 'inv' but got ${id}`\n );\n }\n return id as InvocationId;\n },\n};\n\nexport type InvocationHandle = {\n // The invocation id of the call\n readonly invocationId: Promise<InvocationId>;\n};\n\nexport type InvocationPromise<T> = RestatePromise<T> & InvocationHandle;\n\nexport const RestatePromise = {\n /**\n * Creates a Promise that is resolved with an array of results when all of the provided Promises\n * resolve, or rejected when any Promise is rejected.\n *\n * See {@link Promise.all} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n all<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<{ -readonly [P in keyof T]: Awaited<T[P]> }> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.all(p),\n values\n ) as RestatePromise<{\n -readonly [P in keyof T]: Awaited<T[P]>;\n }>;\n },\n\n /**\n * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n * or rejected.\n *\n * See {@link Promise.race} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n race<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<Awaited<T[number]>> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.race(p),\n values\n ) as RestatePromise<Awaited<T[number]>>;\n },\n\n /**\n * Creates a promise that fulfills when any of the input's promises fulfills, with this first fulfillment value.\n * It rejects when all the input's promises reject (including when an empty iterable is passed),\n * with an AggregateError containing an array of rejection reasons.\n *\n * See {@link Promise.any} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n any<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<Awaited<T[number]>> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.any(p),\n values\n ) as RestatePromise<Awaited<T[number]>>;\n },\n\n /**\n * Creates a promise that fulfills when all the input's promises settle (including when an empty iterable is passed),\n * with an array of objects that describe the outcome of each promise.\n *\n * See {@link Promise.allSettled} for more details.\n *\n * @param values An iterable of Promises.\n * @returns A new Promise.\n */\n allSettled<const T extends readonly RestatePromise<unknown>[]>(\n values: T\n ): RestatePromise<{\n -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;\n }> {\n if (values.length === 0) {\n throw new Error(\n \"Expected combineable promise to have at least one promise\"\n );\n }\n return ContextImpl.createCombinator(\n (p) => Promise.allSettled(p),\n values\n ) as RestatePromise<{\n -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;\n }>;\n },\n};\n\n/**\n * Workflow bound durable promise\n *\n * See {@link WorkflowSharedContext} promise..\n */\nexport type DurablePromise<T> = Promise<T> & {\n /**\n * Returns the value of the promise, if it has been resolved.\n */\n peek(): Promise<T | undefined>;\n\n /**\n * Resolve the promise with the given value.\n * @param value the value to resolve the promise with\n */\n resolve(value?: T): Promise<void>;\n\n /**\n * Reject the promise with the given error message.\n * @param errorMsg the error message to use for rejection.\n */\n reject(errorMsg: string): Promise<void>;\n\n /**\n * Obtain a {@link RestatePromise} variant of this promise.\n */\n get(): RestatePromise<T>;\n};\n\nexport interface WorkflowSharedContext<TState extends TypedState = UntypedState>\n extends ObjectSharedContext<TState>, RestateWorkflowSharedContext {\n /**\n * Create a durable promise that can be resolved or rejected during the workflow execution.\n * The promise is bound to the workflow and will be persisted across suspensions and retries.\n * @example Add some retry options\n * ```ts\n * const wf = restate.workflow({\n * name: \"myWorkflow\",\n * handlers: {\n * run: async (ctx: restate.WorkflowContext) => {\n * // ... do some work ...\n * const payment = await ctx.promise<Payment>(\"payment.succeeded\");\n * // ... do some more work ...\n * },\n *\n * onPaymentSucceeded: async (ctx: restate.WorkflowContext, payment) => {\n * // ... handle payment succeeded ...\n * await ctx.promise(\"payment.succeeded\").resolve(payment);\n * }\n * });\n * ```\n *\n * @param name the name of the durable promise\n */\n promise<T>(name: string, serde?: Serde<T>): DurablePromise<T>;\n}\n\nexport interface WorkflowContext<TState extends TypedState = UntypedState>\n extends\n WorkflowSharedContext<TState>,\n ObjectContext<TState>,\n RestateWorkflowContext {}\n"],"mappings":";;;AA+rBA,MAAa,qBAAqB,EAKhC,WAAW,IAA0B;AACnC,KAAI,CAAC,GAAG,WAAW,MAAM,CACvB,OAAM,IAAI,MACR,sDAAsD,KACvD;AAEH,QAAO;GAEV;AASD,MAAa,iBAAiB;CAU5B,IACE,QAC6D;AAC7D,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAcH,KACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,KAAK,EAAE,EACtB,OACD;;CAaH,IACE,QACoC;AACpC,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,IAAI,EAAE,EACrB,OACD;;CAYH,WACE,QAGC;AACD,MAAI,OAAO,WAAW,EACpB,OAAM,IAAI,MACR,4DACD;AAEH,SAAO,YAAY,kBAChB,MAAM,QAAQ,WAAW,EAAE,EAC5B,OACD;;CAIJ"}
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_errors = require('./types/errors.cjs');
|
|
3
|
+
const require_rpc = require('./types/rpc.cjs');
|
|
4
|
+
const require_completable_promise = require('./utils/completable_promise.cjs');
|
|
5
|
+
const require_sdk_shared_core_wasm_bindings = require('./endpoint/handlers/vm/sdk_shared_core_wasm_bindings.cjs');
|
|
6
|
+
const require_rand = require('./utils/rand.cjs');
|
|
7
|
+
const require_promises = require('./promises.cjs');
|
|
8
|
+
const require_io = require('./io.cjs');
|
|
9
|
+
let __restatedev_restate_sdk_core = require("@restatedev/restate-sdk-core");
|
|
10
|
+
__restatedev_restate_sdk_core = require_rolldown_runtime.__toESM(__restatedev_restate_sdk_core);
|
|
11
|
+
|
|
12
|
+
//#region src/context_impl.ts
|
|
13
|
+
var ContextImpl = class {
|
|
14
|
+
rand;
|
|
15
|
+
date = {
|
|
16
|
+
now: () => {
|
|
17
|
+
return this.run(() => Date.now());
|
|
18
|
+
},
|
|
19
|
+
toJSON: () => {
|
|
20
|
+
return this.run(() => (/* @__PURE__ */ new Date()).toJSON());
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
outputPump;
|
|
24
|
+
runClosuresTracker;
|
|
25
|
+
promisesExecutor;
|
|
26
|
+
defaultSerde;
|
|
27
|
+
constructor(coreVm, input, console, handlerKind, vmLogger, invocationRequest, invocationEndPromise, inputReader, outputWriter, journalValueCodec, defaultSerde, asTerminalError) {
|
|
28
|
+
this.coreVm = coreVm;
|
|
29
|
+
this.input = input;
|
|
30
|
+
this.console = console;
|
|
31
|
+
this.handlerKind = handlerKind;
|
|
32
|
+
this.vmLogger = vmLogger;
|
|
33
|
+
this.invocationRequest = invocationRequest;
|
|
34
|
+
this.invocationEndPromise = invocationEndPromise;
|
|
35
|
+
this.journalValueCodec = journalValueCodec;
|
|
36
|
+
this.asTerminalError = asTerminalError;
|
|
37
|
+
this.rand = new require_rand.RandImpl(input.random_seed, () => {});
|
|
38
|
+
this.outputPump = new require_io.OutputPump(coreVm, outputWriter);
|
|
39
|
+
this.runClosuresTracker = new RunClosuresTracker();
|
|
40
|
+
this.promisesExecutor = new require_promises.PromisesExecutor(coreVm, new require_io.InputPump(coreVm, inputReader, this.handleInvocationEndError.bind(this)), this.outputPump, this.runClosuresTracker, this.promiseExecutorErrorCallback.bind(this));
|
|
41
|
+
this.defaultSerde = defaultSerde ?? __restatedev_restate_sdk_core.serde.json;
|
|
42
|
+
}
|
|
43
|
+
cancel(invocationId) {
|
|
44
|
+
this.processNonCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.CancelInvocation, () => {}, (vm) => vm.sys_cancel_invocation(invocationId));
|
|
45
|
+
}
|
|
46
|
+
attach(invocationId, serde$1) {
|
|
47
|
+
return this.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.AttachInvocation, () => {}, (vm) => vm.sys_attach_invocation(invocationId), SuccessWithSerde(serde$1 ?? this.defaultSerde, this.journalValueCodec), Failure);
|
|
48
|
+
}
|
|
49
|
+
get key() {
|
|
50
|
+
switch (this.handlerKind) {
|
|
51
|
+
case require_rpc.HandlerKind.EXCLUSIVE:
|
|
52
|
+
case require_rpc.HandlerKind.SHARED:
|
|
53
|
+
case require_rpc.HandlerKind.WORKFLOW: return this.input.key;
|
|
54
|
+
default: throw new require_errors.TerminalError("this handler type doesn't support key()");
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
request() {
|
|
58
|
+
return this.invocationRequest;
|
|
59
|
+
}
|
|
60
|
+
get(name, serde$1) {
|
|
61
|
+
return this.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.GetState, () => {}, (vm) => vm.sys_get_state(name), VoidAsNull, SuccessWithSerde(serde$1 ?? this.defaultSerde, this.journalValueCodec));
|
|
62
|
+
}
|
|
63
|
+
stateKeys() {
|
|
64
|
+
return this.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.GetStateKeys, () => {}, (vm) => vm.sys_get_state_keys(), StateKeys);
|
|
65
|
+
}
|
|
66
|
+
set(name, value, serde$1) {
|
|
67
|
+
this.processNonCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.SetState, () => this.journalValueCodec.encode((serde$1 ?? this.defaultSerde).serialize(value)), (vm, bytes) => vm.sys_set_state(name, bytes));
|
|
68
|
+
}
|
|
69
|
+
clear(name) {
|
|
70
|
+
this.processNonCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.ClearState, () => {}, (vm) => vm.sys_clear_state(name));
|
|
71
|
+
}
|
|
72
|
+
clearAll() {
|
|
73
|
+
this.processNonCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.ClearAllState, () => {}, (vm) => vm.sys_clear_all_state());
|
|
74
|
+
}
|
|
75
|
+
genericCall(call) {
|
|
76
|
+
const requestSerde = call.inputSerde ?? __restatedev_restate_sdk_core.serde.binary;
|
|
77
|
+
const responseSerde = call.outputSerde ?? __restatedev_restate_sdk_core.serde.binary;
|
|
78
|
+
let parameter;
|
|
79
|
+
try {
|
|
80
|
+
parameter = this.journalValueCodec.encode(requestSerde.serialize(call.parameter));
|
|
81
|
+
} catch (e) {
|
|
82
|
+
this.handleInvocationEndError(e, (vm, error) => vm.notify_error_for_next_command(error.message, error.stack, require_sdk_shared_core_wasm_bindings.WasmCommandType.Call));
|
|
83
|
+
return new require_promises.InvocationPendingPromise(this);
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const call_handles = this.coreVm.sys_call(call.service, call.method, parameter, call.key, call.headers ? Object.entries(call.headers).map(([key, value]) => new require_sdk_shared_core_wasm_bindings.WasmHeader(key, value)) : [], call.idempotencyKey);
|
|
87
|
+
const commandIndex = this.coreVm.last_command_index();
|
|
88
|
+
const invocationIdPromise = new require_promises.RestateSinglePromise(this, call_handles.invocation_id_completion_id, completeCommandPromiseUsing(require_sdk_shared_core_wasm_bindings.WasmCommandType.Call, commandIndex, InvocationIdCompleter));
|
|
89
|
+
return new require_promises.RestateInvocationPromise(this, call_handles.call_completion_id, completeCommandPromiseUsing(require_sdk_shared_core_wasm_bindings.WasmCommandType.Call, commandIndex, SuccessWithSerde(responseSerde, this.journalValueCodec), Failure), invocationIdPromise);
|
|
90
|
+
} catch (e) {
|
|
91
|
+
this.handleInvocationEndError(e);
|
|
92
|
+
return new require_promises.InvocationPendingPromise(this);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
genericSend(send) {
|
|
96
|
+
const requestSerde = send.inputSerde ?? __restatedev_restate_sdk_core.serde.binary;
|
|
97
|
+
let parameter;
|
|
98
|
+
try {
|
|
99
|
+
parameter = this.journalValueCodec.encode(requestSerde.serialize(send.parameter));
|
|
100
|
+
} catch (e) {
|
|
101
|
+
this.handleInvocationEndError(e, (vm, error) => vm.notify_error_for_next_command(error.message, error.stack, require_sdk_shared_core_wasm_bindings.WasmCommandType.OneWayCall));
|
|
102
|
+
return new require_promises.InvocationPendingPromise(this);
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
const delay = send.delay !== void 0 ? (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(send.delay) : void 0;
|
|
106
|
+
const handles = this.coreVm.sys_send(send.service, send.method, parameter, send.key, send.headers ? Object.entries(send.headers).map(([key, value]) => new require_sdk_shared_core_wasm_bindings.WasmHeader(key, value)) : [], delay !== void 0 && delay > 0 ? BigInt(delay) : void 0, send.idempotencyKey);
|
|
107
|
+
const commandIndex = this.coreVm.last_command_index();
|
|
108
|
+
return { invocationId: new require_promises.RestateSinglePromise(this, handles.invocation_id_completion_id, completeCommandPromiseUsing(require_sdk_shared_core_wasm_bindings.WasmCommandType.OneWayCall, commandIndex, InvocationIdCompleter)) };
|
|
109
|
+
} catch (e) {
|
|
110
|
+
this.handleInvocationEndError(e);
|
|
111
|
+
return { invocationId: require_promises.pendingPromise() };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
serviceClient({ name }) {
|
|
115
|
+
return require_rpc.makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name);
|
|
116
|
+
}
|
|
117
|
+
objectClient({ name }, key) {
|
|
118
|
+
return require_rpc.makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, key);
|
|
119
|
+
}
|
|
120
|
+
workflowClient({ name }, key) {
|
|
121
|
+
return require_rpc.makeRpcCallProxy((call) => this.genericCall(call), this.defaultSerde, name, key);
|
|
122
|
+
}
|
|
123
|
+
serviceSendClient({ name }, opts) {
|
|
124
|
+
return require_rpc.makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, void 0, opts?.delay);
|
|
125
|
+
}
|
|
126
|
+
objectSendClient({ name }, key, opts) {
|
|
127
|
+
return require_rpc.makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, key, opts?.delay);
|
|
128
|
+
}
|
|
129
|
+
workflowSendClient({ name }, key, opts) {
|
|
130
|
+
return require_rpc.makeRpcSendProxy((send) => this.genericSend(send), this.defaultSerde, name, key, opts?.delay);
|
|
131
|
+
}
|
|
132
|
+
run(nameOrAction, actionSecondParameter, options) {
|
|
133
|
+
const { name, action } = unpackRunParameters(nameOrAction, actionSecondParameter);
|
|
134
|
+
const serde$1 = options?.serde ?? this.defaultSerde;
|
|
135
|
+
let handle;
|
|
136
|
+
try {
|
|
137
|
+
handle = this.coreVm.sys_run(name ?? "");
|
|
138
|
+
} catch (e) {
|
|
139
|
+
this.handleInvocationEndError(e);
|
|
140
|
+
return new require_promises.RestatePendingPromise(this);
|
|
141
|
+
}
|
|
142
|
+
const commandIndex = this.coreVm.last_command_index();
|
|
143
|
+
const doRun = async () => {
|
|
144
|
+
const startTime = Date.now();
|
|
145
|
+
let res;
|
|
146
|
+
let err;
|
|
147
|
+
try {
|
|
148
|
+
res = await action();
|
|
149
|
+
} catch (e) {
|
|
150
|
+
err = require_errors.ensureError(e, this.asTerminalError);
|
|
151
|
+
}
|
|
152
|
+
const attemptDuration = Date.now() - startTime;
|
|
153
|
+
try {
|
|
154
|
+
if (err !== void 0) if (err instanceof require_errors.TerminalError) this.coreVm.propose_run_completion_failure(handle, {
|
|
155
|
+
code: err.code,
|
|
156
|
+
message: err.message
|
|
157
|
+
});
|
|
158
|
+
else if (err instanceof require_errors.RetryableError) {
|
|
159
|
+
const maxRetryDuration = options?.maxRetryDuration ?? options?.maxRetryDurationMillis;
|
|
160
|
+
this.coreVm.propose_run_completion_failure_transient_with_delay_override(handle, err.message, err.stack, BigInt(attemptDuration), err.retryAfter !== void 0 ? BigInt((0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(err.retryAfter)) : void 0, options?.maxRetryAttempts, maxRetryDuration !== void 0 ? BigInt((0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(maxRetryDuration)) : void 0);
|
|
161
|
+
} else {
|
|
162
|
+
this.vmLogger.warn(`Error when processing ctx.run '${name}'.\n`, err);
|
|
163
|
+
let retryPolicy;
|
|
164
|
+
if (options?.retryIntervalFactor !== void 0 || options?.maxRetryAttempts !== void 0 || options?.initialRetryInterval !== void 0 || options?.initialRetryIntervalMillis !== void 0 || options?.maxRetryDuration !== void 0 || options?.maxRetryDurationMillis !== void 0 || options?.maxRetryInterval !== void 0 || options?.maxRetryIntervalMillis !== void 0) {
|
|
165
|
+
const maxRetryDuration = options?.maxRetryDuration ?? options?.maxRetryDurationMillis;
|
|
166
|
+
retryPolicy = {
|
|
167
|
+
factor: options?.retryIntervalFactor ?? 2,
|
|
168
|
+
initial_interval: (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(options?.initialRetryInterval ?? options?.initialRetryIntervalMillis ?? 50),
|
|
169
|
+
max_attempts: options?.maxRetryAttempts,
|
|
170
|
+
max_duration: maxRetryDuration === void 0 ? void 0 : (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(maxRetryDuration),
|
|
171
|
+
max_interval: (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(options?.maxRetryInterval ?? options?.maxRetryIntervalMillis ?? { seconds: 10 })
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
this.coreVm.propose_run_completion_failure_transient(handle, err.message, err.stack, BigInt(attemptDuration), retryPolicy);
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
const serializedRes = serde$1.serialize(res);
|
|
178
|
+
const encodedRes = this.journalValueCodec.encode(serializedRes);
|
|
179
|
+
this.coreVm.propose_run_completion_success(handle, encodedRes);
|
|
180
|
+
}
|
|
181
|
+
} catch (e) {
|
|
182
|
+
this.handleInvocationEndError(e);
|
|
183
|
+
return require_promises.pendingPromise();
|
|
184
|
+
}
|
|
185
|
+
await this.outputPump.awaitNextProgress();
|
|
186
|
+
};
|
|
187
|
+
this.runClosuresTracker.registerRunClosure(handle, doRun);
|
|
188
|
+
return new require_promises.RestateSinglePromise(this, handle, completeCommandPromiseUsing(require_sdk_shared_core_wasm_bindings.WasmCommandType.Run, commandIndex, SuccessWithSerde(serde$1, this.journalValueCodec), Failure));
|
|
189
|
+
}
|
|
190
|
+
sleep(duration, name) {
|
|
191
|
+
return this.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.Sleep, () => {
|
|
192
|
+
if (duration === void 0) throw new Error(`Duration is undefined.`);
|
|
193
|
+
const millis = (0, __restatedev_restate_sdk_core.millisOrDurationToMillis)(duration);
|
|
194
|
+
if (millis < 0) throw new Error(`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()'.`);
|
|
195
|
+
return BigInt(millis);
|
|
196
|
+
}, (vm, millis) => vm.sys_sleep(millis, name), VoidAsUndefined);
|
|
197
|
+
}
|
|
198
|
+
awakeable(serde$1) {
|
|
199
|
+
let awakeable;
|
|
200
|
+
try {
|
|
201
|
+
awakeable = this.coreVm.sys_awakeable();
|
|
202
|
+
} catch (e) {
|
|
203
|
+
this.handleInvocationEndError(e);
|
|
204
|
+
return {
|
|
205
|
+
id: "invalid",
|
|
206
|
+
promise: new require_promises.RestatePendingPromise(this)
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
id: awakeable.id,
|
|
211
|
+
promise: new require_promises.RestateSinglePromise(this, awakeable.handle, completeSignalPromiseUsing(VoidAsUndefined, SuccessWithSerde(serde$1 ?? this.defaultSerde, this.journalValueCodec), Failure))
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
resolveAwakeable(id, payload, serde$1) {
|
|
215
|
+
this.processNonCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.CompleteAwakeable, () => {
|
|
216
|
+
let value;
|
|
217
|
+
if (serde$1) value = payload === void 0 ? new Uint8Array() : serde$1.serialize(payload);
|
|
218
|
+
else value = payload !== void 0 ? this.defaultSerde.serialize(payload) : this.defaultSerde.serialize(null);
|
|
219
|
+
return this.journalValueCodec.encode(value);
|
|
220
|
+
}, (vm, bytes) => vm.sys_complete_awakeable_success(id, bytes));
|
|
221
|
+
}
|
|
222
|
+
rejectAwakeable(id, reason) {
|
|
223
|
+
this.processNonCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.CompleteAwakeable, () => {}, (vm) => {
|
|
224
|
+
vm.sys_complete_awakeable_failure(id, {
|
|
225
|
+
code: require_errors.UNKNOWN_ERROR_CODE,
|
|
226
|
+
message: reason
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
promise(name, serde$1) {
|
|
231
|
+
return new DurablePromiseImpl(this, name, serde$1);
|
|
232
|
+
}
|
|
233
|
+
static createCombinator(combinatorConstructor, promises) {
|
|
234
|
+
const self = require_promises.extractContext(promises[0]);
|
|
235
|
+
if (!self) throw new Error("Not a combinable promise");
|
|
236
|
+
const castedPromises = [];
|
|
237
|
+
for (const promise of promises) {
|
|
238
|
+
if (require_promises.extractContext(promise) !== self) {
|
|
239
|
+
self.handleInvocationEndError(/* @__PURE__ */ new Error("You're mixing up RestatePromises from different RestateContext. This is not supported."));
|
|
240
|
+
return new require_promises.RestatePendingPromise(self);
|
|
241
|
+
}
|
|
242
|
+
castedPromises.push(promise);
|
|
243
|
+
}
|
|
244
|
+
return new require_promises.RestateCombinatorPromise(self, combinatorConstructor, castedPromises);
|
|
245
|
+
}
|
|
246
|
+
processNonCompletableEntry(commandType, prepare, vmCall) {
|
|
247
|
+
let input;
|
|
248
|
+
try {
|
|
249
|
+
input = prepare();
|
|
250
|
+
} catch (e) {
|
|
251
|
+
this.handleInvocationEndError(e, (vm, error) => vm.notify_error_for_next_command(error.message, error.stack, commandType));
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
try {
|
|
255
|
+
vmCall(this.coreVm, input);
|
|
256
|
+
} catch (e) {
|
|
257
|
+
this.handleInvocationEndError(e);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
processCompletableEntry(commandType, prepare, vmCall, ...completers) {
|
|
261
|
+
let input;
|
|
262
|
+
try {
|
|
263
|
+
input = prepare();
|
|
264
|
+
} catch (e) {
|
|
265
|
+
this.handleInvocationEndError(e, (vm, error) => vm.notify_error_for_next_command(error.message, error.stack, commandType));
|
|
266
|
+
return new require_promises.RestatePendingPromise(this);
|
|
267
|
+
}
|
|
268
|
+
let handle;
|
|
269
|
+
try {
|
|
270
|
+
handle = vmCall(this.coreVm, input);
|
|
271
|
+
} catch (e) {
|
|
272
|
+
this.handleInvocationEndError(e);
|
|
273
|
+
return new require_promises.RestatePendingPromise(this);
|
|
274
|
+
}
|
|
275
|
+
const commandIndex = this.coreVm.last_command_index();
|
|
276
|
+
return new require_promises.RestateSinglePromise(this, handle, completeCommandPromiseUsing(commandType, commandIndex, ...completers));
|
|
277
|
+
}
|
|
278
|
+
promiseExecutorErrorCallback(e) {
|
|
279
|
+
if (e instanceof AsyncCompleterError) {
|
|
280
|
+
const cause = require_errors.ensureError(e.cause);
|
|
281
|
+
require_errors.logError(this.vmLogger, e.cause);
|
|
282
|
+
this.coreVm.notify_error_for_specific_command(cause.message, cause.stack, e.commandType, e.commandIndex, null);
|
|
283
|
+
} else {
|
|
284
|
+
const error = require_errors.ensureError(e);
|
|
285
|
+
require_errors.logError(this.vmLogger, error);
|
|
286
|
+
if (!(error instanceof require_errors.RestateError)) this.coreVm.notify_error(error.message, error.stack);
|
|
287
|
+
}
|
|
288
|
+
this.invocationEndPromise.resolve();
|
|
289
|
+
}
|
|
290
|
+
handleInvocationEndError(e, notify_vm_error = (vm, error$1) => {
|
|
291
|
+
vm.notify_error(error$1.message, error$1.stack);
|
|
292
|
+
}) {
|
|
293
|
+
const error = require_errors.ensureError(e);
|
|
294
|
+
require_errors.logError(this.vmLogger, error);
|
|
295
|
+
notify_vm_error(this.coreVm, error);
|
|
296
|
+
this.invocationEndPromise.resolve();
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
function unpackRunParameters(a, b) {
|
|
300
|
+
if (typeof a === "string") {
|
|
301
|
+
if (typeof b !== "function") throw new TypeError("");
|
|
302
|
+
return {
|
|
303
|
+
name: a,
|
|
304
|
+
action: b
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
if (typeof a !== "function") throw new TypeError("unexpected type at the first parameter");
|
|
308
|
+
if (b) throw new TypeError("unexpected a function as a second parameter.");
|
|
309
|
+
return { action: a };
|
|
310
|
+
}
|
|
311
|
+
var DurablePromiseImpl = class {
|
|
312
|
+
serde;
|
|
313
|
+
constructor(ctx, name, serde$1) {
|
|
314
|
+
this.ctx = ctx;
|
|
315
|
+
this.name = name;
|
|
316
|
+
this.serde = serde$1 ?? this.ctx.defaultSerde;
|
|
317
|
+
}
|
|
318
|
+
then(onfulfilled, onrejected) {
|
|
319
|
+
return this.get().then(onfulfilled, onrejected);
|
|
320
|
+
}
|
|
321
|
+
catch(onrejected) {
|
|
322
|
+
return this.get().catch(onrejected);
|
|
323
|
+
}
|
|
324
|
+
finally(onfinally) {
|
|
325
|
+
return this.get().finally(onfinally);
|
|
326
|
+
}
|
|
327
|
+
[Symbol.toStringTag] = "DurablePromise";
|
|
328
|
+
get() {
|
|
329
|
+
return this.ctx.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.GetPromise, () => {}, (vm) => vm.sys_get_promise(this.name), SuccessWithSerde(this.serde, this.ctx.journalValueCodec), Failure);
|
|
330
|
+
}
|
|
331
|
+
peek() {
|
|
332
|
+
return this.ctx.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.PeekPromise, () => {}, (vm) => vm.sys_peek_promise(this.name), VoidAsUndefined, SuccessWithSerde(this.serde, this.ctx.journalValueCodec), Failure);
|
|
333
|
+
}
|
|
334
|
+
resolve(value) {
|
|
335
|
+
return this.ctx.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.CompletePromise, () => this.ctx.journalValueCodec.encode(this.serde.serialize(value)), (vm, bytes) => vm.sys_complete_promise_success(this.name, bytes), VoidAsUndefined, Failure);
|
|
336
|
+
}
|
|
337
|
+
reject(errorMsg) {
|
|
338
|
+
return this.ctx.processCompletableEntry(require_sdk_shared_core_wasm_bindings.WasmCommandType.CompletePromise, () => {}, (vm) => vm.sys_complete_promise_failure(this.name, {
|
|
339
|
+
code: require_errors.INTERNAL_ERROR_CODE,
|
|
340
|
+
message: errorMsg
|
|
341
|
+
}), VoidAsUndefined, Failure);
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
var RunClosuresTracker = class {
|
|
345
|
+
currentRunWaitPoint;
|
|
346
|
+
runsToExecute = /* @__PURE__ */ new Map();
|
|
347
|
+
executeRun(handle) {
|
|
348
|
+
const runClosure = this.runsToExecute.get(handle);
|
|
349
|
+
if (runClosure === void 0) throw new Error(`Handle ${handle} doesn't exist`);
|
|
350
|
+
runClosure().finally(() => {
|
|
351
|
+
this.unblockCurrentRunWaitPoint();
|
|
352
|
+
}).catch(() => {});
|
|
353
|
+
}
|
|
354
|
+
registerRunClosure(handle, runClosure) {
|
|
355
|
+
this.runsToExecute.set(handle, runClosure);
|
|
356
|
+
}
|
|
357
|
+
awaitNextCompletedRun() {
|
|
358
|
+
if (this.currentRunWaitPoint === void 0) this.currentRunWaitPoint = new require_completable_promise.CompletablePromise();
|
|
359
|
+
return this.currentRunWaitPoint.promise;
|
|
360
|
+
}
|
|
361
|
+
unblockCurrentRunWaitPoint() {
|
|
362
|
+
if (this.currentRunWaitPoint !== void 0) {
|
|
363
|
+
const p = this.currentRunWaitPoint;
|
|
364
|
+
this.currentRunWaitPoint = void 0;
|
|
365
|
+
p.resolve();
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
var AsyncCompleterError = class {
|
|
370
|
+
constructor(cause, commandType, commandIndex) {
|
|
371
|
+
this.cause = cause;
|
|
372
|
+
this.commandType = commandType;
|
|
373
|
+
this.commandIndex = commandIndex;
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
function completeCommandPromiseUsing(commandType, commandIndex, ...completers) {
|
|
377
|
+
return async (value, prom) => {
|
|
378
|
+
try {
|
|
379
|
+
for (const completer of completers) if (await completer(value, prom)) return;
|
|
380
|
+
} catch (e) {
|
|
381
|
+
throw new AsyncCompleterError(e, commandType, commandIndex);
|
|
382
|
+
}
|
|
383
|
+
throw new Error(`Unexpected variant in async result: ${JSON.stringify(value)}`);
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
function completeSignalPromiseUsing(...completers) {
|
|
387
|
+
return async (value, prom) => {
|
|
388
|
+
for (const completer of completers) if (await completer(value, prom)) return;
|
|
389
|
+
throw new Error(`Unexpected variant in async result: ${JSON.stringify(value)}`);
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
const VoidAsNull = (value, prom) => {
|
|
393
|
+
if (value === "Empty") {
|
|
394
|
+
prom.resolve(null);
|
|
395
|
+
return Promise.resolve(true);
|
|
396
|
+
}
|
|
397
|
+
return Promise.resolve(false);
|
|
398
|
+
};
|
|
399
|
+
const VoidAsUndefined = (value, prom) => {
|
|
400
|
+
if (value === "Empty") {
|
|
401
|
+
prom.resolve(void 0);
|
|
402
|
+
return Promise.resolve(true);
|
|
403
|
+
}
|
|
404
|
+
return Promise.resolve(false);
|
|
405
|
+
};
|
|
406
|
+
function SuccessWithSerde(serde$1, journalCodec, transform) {
|
|
407
|
+
return async (value, prom) => {
|
|
408
|
+
if (typeof value !== "object" || !("Success" in value)) return false;
|
|
409
|
+
let buffer;
|
|
410
|
+
if (journalCodec !== void 0) buffer = await journalCodec.decode(value.Success);
|
|
411
|
+
else buffer = value.Success;
|
|
412
|
+
let val = serde$1.deserialize(buffer);
|
|
413
|
+
if (transform) val = transform(val);
|
|
414
|
+
prom.resolve(val);
|
|
415
|
+
return true;
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
const Failure = (value, prom) => {
|
|
419
|
+
if (typeof value === "object" && "Failure" in value) {
|
|
420
|
+
prom.reject(new require_errors.TerminalError(value.Failure.message, { errorCode: value.Failure.code }));
|
|
421
|
+
return Promise.resolve(true);
|
|
422
|
+
}
|
|
423
|
+
return Promise.resolve(false);
|
|
424
|
+
};
|
|
425
|
+
const StateKeys = (value, prom) => {
|
|
426
|
+
if (typeof value === "object" && "StateKeys" in value) {
|
|
427
|
+
prom.resolve(value.StateKeys);
|
|
428
|
+
return Promise.resolve(true);
|
|
429
|
+
}
|
|
430
|
+
return Promise.resolve(false);
|
|
431
|
+
};
|
|
432
|
+
const InvocationIdCompleter = (value, prom) => {
|
|
433
|
+
if (typeof value === "object" && "InvocationId" in value) {
|
|
434
|
+
prom.resolve(value.InvocationId);
|
|
435
|
+
return Promise.resolve(true);
|
|
436
|
+
}
|
|
437
|
+
return Promise.resolve(false);
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
//#endregion
|
|
441
|
+
exports.ContextImpl = ContextImpl;
|