@restatedev/restate-sdk-cloudflare-workers 1.17.2 → 1.17.4
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/dist/common_api.d.cts +1 -1
- package/dist/common_api.d.cts.map +1 -1
- package/dist/common_api.d.ts +1 -1
- package/dist/common_api.d.ts.map +1 -1
- package/dist/common_api.js.map +1 -1
- package/dist/context.d.cts +25 -8
- package/dist/context.d.cts.map +1 -1
- package/dist/context.d.ts +25 -8
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js.map +1 -1
- package/dist/context_impl.cjs +84 -27
- package/dist/context_impl.js +84 -27
- package/dist/context_impl.js.map +1 -1
- package/dist/endpoint/components.cjs +11 -1
- package/dist/endpoint/components.js +11 -2
- package/dist/endpoint/components.js.map +1 -1
- package/dist/endpoint/endpoint.cjs +1 -1
- package/dist/endpoint/endpoint.js +1 -1
- package/dist/endpoint/endpoint.js.map +1 -1
- package/dist/endpoint/handlers/generic.cjs +1 -1
- package/dist/endpoint/handlers/generic.js +1 -1
- package/dist/endpoint/handlers/generic.js.map +1 -1
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.d.ts +9 -7
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings_bg.js +54 -12
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm +0 -0
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm.d.ts +9 -7
- package/dist/fetch.d.cts +2 -2
- package/dist/fetch.d.ts +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/internal.cjs +46 -1
- package/dist/internal.d.cts +96 -4
- package/dist/internal.d.cts.map +1 -1
- package/dist/internal.d.ts +96 -4
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +46 -1
- package/dist/internal.js.map +1 -1
- package/dist/lambda.d.cts +2 -2
- package/dist/lambda.d.ts +2 -2
- package/dist/node.d.cts +2 -2
- package/dist/node.d.ts +2 -2
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/dist/promises.cjs +5 -1
- package/dist/promises.d.cts.map +1 -1
- package/dist/promises.d.ts.map +1 -1
- package/dist/promises.js +5 -1
- package/dist/promises.js.map +1 -1
- package/dist/types/errors.cjs +2 -2
- package/dist/types/errors.d.cts +1 -1
- package/dist/types/errors.d.cts.map +1 -1
- package/dist/types/errors.d.ts +1 -1
- package/dist/types/errors.d.ts.map +1 -1
- package/dist/types/errors.js +2 -2
- package/dist/types/errors.js.map +1 -1
- package/dist/types/rpc.d.cts +3 -11
- package/dist/types/rpc.d.cts.map +1 -1
- package/dist/types/rpc.d.ts +3 -11
- package/dist/types/rpc.d.ts.map +1 -1
- package/dist/types/rpc.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generic.js","names":["endpoint: Endpoint","protocolMode: ProtocolMode","additionalDiscoveryFields: Partial<EndpointManifest>","vm.WasmIdentityVerifier","vm.WasmHeader","service: Component","handler: ComponentHandler","attemptHeaders: Headers","extraArgs: unknown[]","additionalContext: AdditionalContext","journalValueCodecInit:\n | Promise<JournalValueCodec>\n | undefined","loggerTransport: LoggerTransport","vm.WasmVM","journalValueCodec: JournalValueCodec","ctx: ContextImpl","invocationRequest: Request","hooks: Hooks[]","hookContext: { request: Request }","encodedOutput: Uint8Array | undefined","originalError: unknown"],"sources":["../../../src/endpoint/handlers/generic.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 {\n ensureError,\n logError,\n PauseError,\n RestateError,\n RetryableError,\n TerminalError,\n} from \"../../types/errors.js\";\nimport type {\n Endpoint as EndpointManifest,\n ProtocolMode,\n} from \"../discovery.js\";\nimport {\n Component,\n ComponentHandler,\n InvokePathComponents,\n} from \"../components.js\";\nimport { parseUrlComponents } from \"../components.js\";\nimport { X_RESTATE_SERVER } from \"../../user_agent.js\";\nimport { CommandError, ContextImpl } from \"../../context_impl.js\";\nimport { restoreError, sanitizeError } from \"../../error_sanitization.js\";\nimport type { InvocationId, Request } from \"../../context.js\";\nimport * as vm from \"./vm/sdk_shared_core_wasm_bindings.js\";\nimport { HandlerKind } from \"../../types/rpc.js\";\nimport { createLogger, type Logger } from \"../../logging/logger.js\";\nimport { DEFAULT_CONSOLE_LOGGER_LOG_LEVEL } from \"../../logging/console_logger_transport.js\";\nimport {\n LoggerContext,\n LoggerTransport,\n LogSource,\n RestateLogLevel,\n} from \"../../logging/logger_transport.js\";\nimport {\n type JournalValueCodec,\n millisOrDurationToMillis,\n} from \"@restatedev/restate-sdk-core\";\nimport type { Endpoint } from \"../endpoint.js\";\nimport {\n type RestateHandler,\n type Headers,\n type RestateRequest,\n type AdditionalContext,\n type RestateResponse,\n ResponseHeaders,\n InputReader,\n OutputWriter,\n} from \"./types.js\";\nimport { handleDiscovery } from \"./discovery.js\";\nimport { handlePreview } from \"./preview.js\";\nimport {\n errorResponse,\n invocationIdFromHeaders,\n simpleResponse,\n tryCreateContextualLogger,\n} from \"./utils.js\";\nimport { destroyLogger, registerLogger } from \"./core_logging.js\";\nimport type { Hooks } from \"../../hooks.js\";\n\n// Hidden symbol key used by first-party hooks to read the live\n// replay/processing phase without widening the public HooksProvider API.\nconst HOOK_CONTEXT_IS_PROCESSING_SYMBOL = Symbol.for(\n \"@restatedev/restate-sdk/hooks.isProcessing\"\n);\n\nexport function createRestateHandler(\n endpoint: Endpoint,\n protocolMode: ProtocolMode,\n additionalDiscoveryFields: Partial<EndpointManifest>\n): RestateHandler {\n return new RestateHandlerImpl(\n endpoint,\n protocolMode,\n additionalDiscoveryFields\n );\n}\n\n/**\n * This is the RestateHandler implementation\n */\nclass RestateHandlerImpl implements RestateHandler {\n private readonly identityVerifier?: vm.WasmIdentityVerifier;\n\n constructor(\n readonly endpoint: Endpoint,\n private readonly protocolMode: ProtocolMode,\n private readonly additionalDiscoveryFields: Partial<EndpointManifest>\n ) {\n // Setup identity verifier\n if (\n this.endpoint.keySet === undefined ||\n this.endpoint.keySet.length === 0\n ) {\n this.endpoint.rlog.warn(\n `Accepting requests without validating request signatures; handler access must be restricted`\n );\n } else {\n this.endpoint.rlog.info(\n `Validating requests using signing keys [${this.endpoint.keySet}]`\n );\n this.identityVerifier = new vm.WasmIdentityVerifier(this.endpoint.keySet);\n }\n\n // Set the logging level in the shared core too!\n vm.set_log_level(\n restateLogLevelToWasmLogLevel(DEFAULT_CONSOLE_LOGGER_LOG_LEVEL)\n );\n }\n\n // handle does not throw.\n public handle(\n request: RestateRequest,\n context?: AdditionalContext\n ): RestateResponse {\n try {\n return this._handle(request, context);\n } catch (e) {\n const error = ensureError(e);\n (\n tryCreateContextualLogger(\n this.endpoint.loggerTransport,\n request.url,\n request.headers\n ) ?? this.endpoint.rlog\n ).error(\n \"Error while handling request: \" + (error.stack ?? error.message)\n );\n return errorResponse(\n error instanceof RestateError ? error.code : 500,\n error.message\n );\n }\n }\n\n private _handle(\n request: RestateRequest,\n context?: AdditionalContext\n ): RestateResponse {\n // this is the recommended way to get the relative path from a url that may be relative or absolute\n const path = new URL(request.url, \"https://example.com\").pathname;\n const parsed = parseUrlComponents(path);\n\n if (parsed.type === \"unknown\") {\n const msg =\n \"Invalid path. Allowed are /health, /discover, /invoke/SvcName/handlerName, \" +\n \"/serdes/SvcName/decode/<serdeName>, or \" +\n \"/serdes/SvcName/encode/<serdeName>, but was: \" +\n path;\n this.endpoint.rlog.trace(msg);\n return errorResponse(404, msg);\n }\n if (parsed.type === \"health\") {\n return simpleResponse(\n 200,\n {\n \"content-type\": \"application/text\",\n \"x-restate-server\": X_RESTATE_SERVER,\n },\n new TextEncoder().encode(\"OK\")\n );\n }\n\n // Discovery, preview, and handling invocations require identity verification\n const error = this.validateConnectionSignature(path, request.headers);\n if (error !== null) {\n return error;\n }\n if (parsed.type === \"discover\") {\n return handleDiscovery(\n this.endpoint,\n this.protocolMode,\n this.additionalDiscoveryFields,\n request.headers[\"accept\"]\n );\n }\n if (parsed.type === \"preview\") {\n return handlePreview(this.endpoint, parsed);\n }\n\n return this.handleInvoke(\n parsed,\n request.headers,\n request.extraArgs,\n context ?? {}\n );\n }\n\n private validateConnectionSignature(\n path: string,\n headers: Headers\n ): RestateResponse | null {\n if (!this.identityVerifier) {\n // not validating\n return null;\n }\n\n const vmHeaders = Object.entries(headers)\n .filter(([, v]) => v !== undefined)\n .map(\n ([k, v]) =>\n new vm.WasmHeader(k, v instanceof Array ? v[0]! : (v as string))\n );\n\n try {\n this.identityVerifier.verify_identity(path, vmHeaders);\n return null;\n } catch (e) {\n this.endpoint.rlog.error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Rejecting request as its JWT did not validate: ${e}`\n );\n return errorResponse(401, \"Unauthorized\");\n }\n }\n\n private handleInvoke(\n invokePathComponent: InvokePathComponents,\n headers: Headers,\n extraArgs: unknown[],\n additionalContext: AdditionalContext\n ): RestateResponse {\n // Check if we support this protocol version\n const serviceProtocolVersionString = headers[\"content-type\"];\n if (typeof serviceProtocolVersionString !== \"string\") {\n const errorMessage = \"Missing content-type header\";\n this.endpoint.rlog.warn(errorMessage);\n return errorResponse(415, errorMessage);\n }\n\n const service = this.endpoint.components.get(\n invokePathComponent.componentName\n );\n if (!service) {\n const msg = `No service found for URL: ${JSON.stringify(invokePathComponent)}`;\n this.endpoint.rlog.error(msg);\n return errorResponse(404, msg);\n }\n\n const handler = service.handlerMatching(invokePathComponent);\n if (!handler) {\n const msg = `No handler found for URL: ${JSON.stringify(invokePathComponent)}`;\n this.endpoint.rlog.error(msg);\n return errorResponse(404, msg);\n }\n\n return new RestateInvokeResponse(\n service,\n handler,\n headers,\n extraArgs,\n additionalContext,\n this.endpoint.journalValueCodec,\n this.endpoint.loggerTransport\n );\n }\n}\n\nclass RestateInvokeResponse implements RestateResponse {\n private readonly headers: ResponseHeaders;\n private readonly statusCode: number;\n\n private readonly loggerId: number;\n private vmLogger: Logger;\n private readonly coreVm: vm.WasmVM;\n\n constructor(\n private readonly service: Component,\n private readonly handler: ComponentHandler,\n private readonly attemptHeaders: Headers,\n private readonly extraArgs: unknown[],\n private readonly additionalContext: AdditionalContext,\n private readonly journalValueCodecInit:\n | Promise<JournalValueCodec>\n | undefined,\n private readonly loggerTransport: LoggerTransport\n ) {\n this.loggerId = Math.floor(Math.random() * 4_294_967_295 /* u32::MAX */);\n const isJournalCodecDefined = this.journalValueCodecInit !== undefined;\n\n // Instantiate core vm and prepare response headers\n const vmHeaders = Object.entries(this.attemptHeaders)\n .filter(([, v]) => v !== undefined)\n .map(\n ([k, v]) =>\n new vm.WasmHeader(k, v instanceof Array ? v[0]! : (v as string))\n );\n this.coreVm = new vm.WasmVM(\n vmHeaders,\n restateLogLevelToWasmLogLevel(DEFAULT_CONSOLE_LOGGER_LOG_LEVEL),\n this.loggerId,\n isJournalCodecDefined,\n handler.executionOptions.explicitCancellation ?? false,\n onJournalMismatchErrorsToWasm(\n handler.executionOptions.onJournalMismatchErrors\n )\n );\n const responseHead = this.coreVm.get_response_head();\n this.statusCode = responseHead.status_code;\n this.headers = responseHead.headers.reduce(\n (headers, { key, value }) => ({\n [key]: value,\n ...headers,\n }),\n {\n \"x-restate-server\": X_RESTATE_SERVER,\n }\n );\n this.vmLogger = createLogger(\n this.loggerTransport,\n LogSource.JOURNAL,\n new LoggerContext(\n invocationIdFromHeaders(this.attemptHeaders),\n this.service.name(),\n this.handler.name(),\n undefined,\n undefined,\n this.additionalContext\n )\n );\n }\n\n async process({\n inputReader,\n outputWriter,\n writeHead,\n abortSignal,\n }: {\n inputReader: InputReader;\n outputWriter: OutputWriter;\n writeHead: (statusCode: number, headers: ResponseHeaders) => void;\n abortSignal: AbortSignal;\n }): Promise<void> {\n // Commit the response head immediately — the VM-determined head is known\n // at construction time and never changes during processing.\n writeHead(this.statusCode, this.headers);\n\n abortSignal.addEventListener(\n \"abort\",\n () => {\n // In any case, on abort remove the invocation logger to avoid memory leaks\n destroyLogger(this.loggerId);\n\n // When the HTTP connection closes (e.g. abort timeout), poison the VM.\n // We only read new input from the server when a Restate command is\n // waiting for a response. If no command has been issued, the server's\n // abort signal is never read. Poisoning the VM ensures the handler\n // fails on the next VM call (e.g. ctx.run, ctx.sleep).\n setImmediate(() => {\n const msg = \"Connection closed\";\n this.coreVm.notify_error(msg, msg);\n });\n },\n { once: true }\n );\n // Use a default logger that still respects the endpoint custom logger\n // We will override this later with a logger that has a LoggerContext\n // See vm_log below for more details\n registerLogger(this.loggerId, this.vmLogger);\n\n const journalValueCodec: JournalValueCodec = this.journalValueCodecInit\n ? await this.journalValueCodecInit\n : {\n encode: (entry) => entry,\n decode: (entry) => Promise.resolve(entry),\n };\n\n // This promise is used to signal the end of the computation,\n // which can be either the user returns a value,\n // or an exception gets caught, or the state machine fails/suspends.\n //\n // The last case is handled internally within the ContextImpl.\n const invocationEndPromise = Promise.withResolvers<void>();\n let ctx: ContextImpl;\n\n // Initial phase before running user code\n // -> Buffer in shared core the journal entries\n // -> Initiate loggers\n // -> Initialize the ContextImpl\n try {\n // Buffer journal inside shared core\n await bufferJournalReplayInCoreVm(this.coreVm, inputReader);\n\n // Get input from coreVm to build the request object\n const input = this.coreVm.sys_input();\n const invocationRequest: Request = {\n target: {\n service: this.service.name(),\n handler: this.handler.name(),\n key: input.key || undefined,\n toString() {\n return this.key !== undefined\n ? `${this.service}/${this.key}/${this.handler}`\n : `${this.service}/${this.handler}`;\n },\n },\n id: input.invocation_id as InvocationId,\n headers: input.headers.reduce((headers, { key, value }) => {\n headers.set(key, value);\n return headers;\n }, new Map()),\n attemptHeaders: Object.entries(this.attemptHeaders).reduce(\n (headers, [key, value]) => {\n if (value !== undefined) {\n headers.set(key, value instanceof Array ? value[0] : value);\n }\n return headers;\n },\n new Map()\n ),\n body: input.input,\n extraArgs: this.extraArgs,\n idempotencyKey: input.idempotency_key || undefined,\n scope: input.scope || undefined,\n limitKey: input.limit_key || undefined,\n attemptCompletedSignal: abortSignal,\n };\n\n // Prepare logger\n const loggerContext = new LoggerContext(\n input.invocation_id,\n this.handler.component().name(),\n this.handler.name(),\n this.handler.kind() === HandlerKind.SERVICE ? undefined : input.key,\n invocationRequest,\n this.additionalContext\n );\n const ctxLogger = createLogger(\n this.loggerTransport,\n LogSource.USER,\n loggerContext,\n () => !this.coreVm.is_processing()\n );\n // Override the vmLogger created before with more info!\n this.vmLogger = createLogger(\n this.loggerTransport,\n LogSource.JOURNAL,\n loggerContext\n // Filtering is done within the shared core\n );\n\n // See vm_log below for more details\n registerLogger(this.loggerId, this.vmLogger);\n if (!this.coreVm.is_processing()) {\n this.vmLogger.info(\"Replaying invocation.\");\n } else {\n this.vmLogger.info(\"Starting invocation.\");\n }\n\n // Prepare context\n ctx = new ContextImpl(\n this.coreVm,\n input,\n ctxLogger,\n this.handler.kind(),\n this.vmLogger,\n invocationRequest,\n invocationEndPromise,\n inputReader,\n outputWriter,\n journalValueCodec,\n this.handler.executionOptions\n );\n } catch (e) {\n // That's \"preflight\" failure cases, where stuff fails before running user code\n // In this scenario, we close the coreVm, then flush and close\n const error = ensureError(e);\n this.coreVm.notify_error(error.message, error.message);\n try {\n await flushAndClose(\n this.coreVm,\n this.vmLogger,\n Promise.resolve(inputReader),\n outputWriter\n );\n } finally {\n // Safety net: the abort listener should clean this up when the attempt\n // ends, but process() owns the logger registration, so avoid leaking if\n // an adapter ever fails to abort the attempt-completed signal.\n destroyLogger(this.loggerId);\n }\n return;\n }\n\n // Run user code. Errors that reach the handler or interceptor code\n // (handler throws, interceptor throws, entry completes with terminal\n // failure) propagate naturally. Errors where the handler is stuck on\n // an await that will never settle (e.g. suspension, retryable run\n // error) are broken out by raceWithAttemptEnd, which races against\n // invocationEndPromise — rejected by ContextImpl when the attempt ends.\n try {\n await startUserHandler(\n ctx,\n this.service,\n this.handler,\n journalValueCodec\n );\n } catch (e) {\n notifyError(e, ctx, this.handler.executionOptions.asTerminalError);\n } finally {\n try {\n await flushAndClose(\n this.coreVm,\n this.vmLogger,\n ctx.inputPump.stop(),\n outputWriter\n );\n } finally {\n // Safety net: the abort listener should clean this up when the attempt\n // ends, but process() owns the logger registration, so avoid leaking if\n // an adapter ever fails to abort the attempt-completed signal.\n destroyLogger(this.loggerId);\n }\n }\n }\n}\n\nasync function bufferJournalReplayInCoreVm(\n coreVm: vm.WasmVM,\n inputReader: InputReader\n) {\n while (!coreVm.is_ready_to_execute()) {\n const nextValue = await inputReader.next();\n if (nextValue.done) {\n coreVm.notify_input_closed();\n break;\n }\n if (nextValue.value !== undefined) {\n coreVm.notify_input(nextValue.value);\n }\n }\n}\n\nasync function startUserHandler(\n ctx: ContextImpl,\n service: Component,\n handler: ComponentHandler,\n journalValueCodec: JournalValueCodec\n) {\n // Instantiate hooks from providers.\n // If a provider throws, the same rules as handler failures apply:\n // TerminalError → terminate invocation, other errors → retry.\n const hooks: Hooks[] = [];\n for (const provider of handler.executionOptions.hooks ?? []) {\n const hookContext: { request: Request } = {\n request: ctx.request(),\n };\n Object.defineProperty(hookContext, HOOK_CONTEXT_IS_PROCESSING_SYMBOL, {\n value: () => ctx.isProcessing(),\n enumerable: false,\n });\n hooks.push(provider(hookContext));\n }\n\n // Compose interceptor.handler into a single interceptor (first = outermost)\n const handlerInterceptor = composeInterceptors(\n hooks.map((h) => h.interceptor?.handler).filter(isDefined)\n );\n\n ctx.setRunInterceptor(\n composeInterceptors(hooks.map((h) => h.interceptor?.run).filter(isDefined))\n );\n\n let encodedOutput: Uint8Array | undefined;\n await raceWithAttemptEnd(\n ctx,\n handlerInterceptor\n )(async () => {\n const decodedInput = await journalValueCodec\n .decode(ctx.request().body)\n .catch((e) =>\n // Re-throw as terminal error, to fail on input errors\n Promise.reject(\n new TerminalError(\n `Failed to decode input using journal value codec: ${\n ensureError(e).message\n }`,\n {\n errorCode: 400,\n }\n )\n )\n );\n\n // Then run user code\n const output = await handler.invoke(ctx, decodedInput);\n\n // Encode user code output\n encodedOutput = journalValueCodec.encode(output);\n });\n\n // Interceptor chain completed without error — commit the result.\n // sys_end() is called here (after interceptors) so that interceptor\n // errors after next() correctly prevent the invocation from succeeding.\n ctx.coreVm.sys_write_output_success(encodedOutput!);\n ctx.coreVm.sys_end();\n ctx.vmLogger.info(\"Invocation completed successfully.\");\n}\n\n/**\n * Classifies the error and notifies the VM. Called from the process() catch\n * block — the single place that decides how to report errors to the VM.\n */\nfunction notifyError(\n e: unknown,\n ctx: ContextImpl,\n asTerminalError?: (error: unknown) => TerminalError | undefined\n) {\n // Command-specific errors from ContextImpl carry metadata the VM needs\n // for command correlation. Check before ensureError to preserve the type.\n if (e instanceof CommandError) {\n const cause = ensureError(e.cause);\n logError(ctx.vmLogger, cause);\n if (e.hasCommandIndex) {\n // Completion failure — command exists in the journal\n ctx.coreVm.notify_error_for_specific_command(\n cause.message,\n cause.stack,\n e.commandType,\n e.commandIndex!,\n null\n );\n } else {\n // Preparation failure — command not yet issued\n ctx.coreVm.notify_error_for_next_command(\n cause.message,\n cause.stack,\n e.commandType\n );\n }\n return;\n }\n\n // Handler/interceptor errors\n const error = ensureError(e, asTerminalError);\n logError(ctx.vmLogger, error);\n\n try {\n if (error instanceof TerminalError) {\n // Terminal: write the failure as the invocation output\n ctx.coreVm.sys_write_output_failure({\n code: error.code,\n message: error.message,\n metadata: Object.entries(error.metadata ?? {}).map(([key, value]) => ({\n key,\n value,\n })),\n });\n ctx.coreVm.sys_end();\n } else if (error instanceof RetryableError) {\n // Retryable with explicit delay\n ctx.coreVm.notify_error_with_delay_override(\n error.message,\n error.stack,\n error.retryAfter !== undefined\n ? BigInt(millisOrDurationToMillis(error.retryAfter))\n : undefined\n );\n } else {\n if (error instanceof PauseError) {\n ctx.vmLogger.warn(\n \"Throwing PauseError from the handler context will be ignored, \" +\n \"as it leads to pause loops. You should use PauseError only inside `ctx.run`\"\n );\n }\n\n // Transient error — VM decides retry policy\n ctx.coreVm.notify_error(error.message, error.stack);\n }\n } catch (vmError) {\n // Safety net: if sys_write_output_failure or other VM calls fail,\n // fall back to notify_error.\n const inner = ensureError(vmError);\n ctx.coreVm.notify_error(inner.message, inner.stack);\n }\n}\n\nasync function flushAndClose(\n coreVm: vm.WasmVM,\n vmLogger: Logger,\n inputReaderGetter: Promise<InputReader>,\n outputWriter: OutputWriter\n): Promise<void> {\n let inputClosed = false;\n try {\n // Consume vm output buffer, write it out, then close the stream\n const nextOutput = coreVm.take_output();\n if (nextOutput?.length > 0) {\n await outputWriter.write(nextOutput);\n }\n\n // --- After this point, we should have flushed the shared core internal buffer\n\n // Wait for the input reader.\n // In case we executed the user code, this is wired up to the InputPump.stop()\n // to make sure there is only one reader for inputReader.\n const inputReader = await inputReaderGetter;\n\n // Let's make sure we properly close the request stream before closing the response stream\n while (!inputClosed) {\n try {\n const res = await inputReader.next();\n inputClosed = res.done ?? false;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n inputClosed = true;\n }\n }\n\n // Close the response stream\n await outputWriter.close();\n } catch (e) {\n // In case of failure, we can do little here except just logging stuff out,\n // because outputWriter is not usable here.\n const error = ensureError(e);\n const abortErrorOnWrite = isAbortErrorOnWrite(error);\n\n if (inputClosed && abortErrorOnWrite) {\n // Because we closed the input already,\n // these errors are benign and are caused by\n // synchronization issues wrt closing the response stream in the runtime\n // This will be fixed in the runtime with https://github.com/restatedev/restate/issues/4456\n return;\n }\n\n if (abortErrorOnWrite) {\n vmLogger.error(\n \"Got abort error from connection: \" +\n error.message +\n \"\\n\" +\n \"This might indicate that:\\n\" +\n \"* The restate-server aborted the connection after hitting the 'abort-timeout'\\n\" +\n \"* The connection with the restate-server was lost\\n\" +\n \"\\n\" +\n \"Please check the invocation in the Restate UI for more details.\"\n );\n } else {\n vmLogger.error(\n \"Error while handling request: \" + (error.stack ?? error.message)\n );\n }\n }\n}\n\nfunction isAbortErrorOnWrite(error: Error) {\n return (\n error.name === \"AbortError\" ||\n error.message === \"Invalid state: WritableStream is closed\" ||\n /**\n * Node stream closed error thrown on writes\n */\n (error as { code?: string }).code === \"ERR_HTTP2_INVALID_STREAM\"\n );\n}\n\n// -- Hook composition utils --------------------------------------------------\n\ntype InterceptorFn<Args extends unknown[]> = (\n ...args: [...Args, () => Promise<void>]\n) => Promise<void>;\n\nfunction composeInterceptors<Args extends unknown[]>(\n interceptors: InterceptorFn<Args>[]\n): InterceptorFn<Args> {\n return interceptors.reduceRight<InterceptorFn<Args>>(\n (innerInterceptor, interceptor) =>\n (...args) => {\n const context = args.slice(0, -1) as unknown as Args;\n const callback = args.at(-1) as () => Promise<void>;\n return interceptor(...context, () =>\n innerInterceptor(...context, callback)\n );\n },\n (...args) => (args.at(-1) as () => Promise<void>)()\n );\n}\n\n/**\n * Wraps an interceptor so that both `next()` and the interceptor body race\n * against `invocationEndPromise`. When the attempt ends (suspension, retryable\n * error, etc.), the promise rejects and the interceptor chain unwinds through\n * catch/finally blocks — preventing interceptors from hanging on a `next()`\n * that will never settle.\n *\n * SDK-internal metadata (CommandError, retryAfter) is stripped before the\n * interceptor sees the error and restored after the chain exits.\n */\nfunction raceWithAttemptEnd<Args extends unknown[]>(\n ctx: ContextImpl,\n interceptor: InterceptorFn<Args>\n): InterceptorFn<Args> {\n return (...args) => {\n let originalError: unknown;\n\n // Strip SDK metadata before interceptors see the error.\n // Store the original in the closure for restoration after the chain.\n const signal = ctx.invocationEndPromise.promise.catch((e) => {\n originalError = e;\n throw sanitizeError(e);\n }) as Promise<never>;\n\n const originalNext = args.at(-1) as () => Promise<void>;\n const racingNext = () => Promise.race([originalNext(), signal]);\n const newArgs = [...args.slice(0, -1), racingNext] as unknown as [\n ...Args,\n () => Promise<void>,\n ];\n\n return Promise.race([interceptor(...newArgs), signal]).catch((e) => {\n // Restore SDK metadata after the interceptor chain exits.\n if (originalError !== undefined) {\n throw restoreError(e, originalError);\n }\n throw e;\n });\n };\n}\n\nfunction isDefined<T>(value: T | undefined | null): value is T {\n return value != null;\n}\n\n// -- Logging utils -----------------------------------------------------------\n\nfunction restateLogLevelToWasmLogLevel(level: RestateLogLevel): vm.LogLevel {\n switch (level) {\n case RestateLogLevel.TRACE:\n return vm.LogLevel.TRACE;\n case RestateLogLevel.DEBUG:\n return vm.LogLevel.DEBUG;\n case RestateLogLevel.INFO:\n return vm.LogLevel.INFO;\n case RestateLogLevel.WARN:\n return vm.LogLevel.WARN;\n case RestateLogLevel.ERROR:\n return vm.LogLevel.ERROR;\n }\n}\n\nfunction onJournalMismatchErrorsToWasm(\n behavior: \"retry\" | \"pause\" | \"fail\" | undefined\n): vm.WasmJournalMismatchBehavior {\n switch (behavior) {\n case \"pause\":\n return vm.WasmJournalMismatchBehavior.Pause;\n case \"fail\":\n return vm.WasmJournalMismatchBehavior.Fail;\n case \"retry\":\n case undefined:\n return vm.WasmJournalMismatchBehavior.Retry;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuEA,MAAM,oCAAoC,OAAO,IAC/C,6CACD;AAED,SAAgB,qBACd,UACA,cACA,2BACgB;AAChB,QAAO,IAAI,mBACT,UACA,cACA,0BACD;;;;;AAMH,IAAM,qBAAN,MAAmD;CACjD,AAAiB;CAEjB,YACE,AAASA,UACT,AAAiBC,cACjB,AAAiBC,2BACjB;EAHS;EACQ;EACA;AAGjB,MACE,KAAK,SAAS,WAAW,UACzB,KAAK,SAAS,OAAO,WAAW,EAEhC,MAAK,SAAS,KAAK,KACjB,8FACD;OACI;AACL,QAAK,SAAS,KAAK,KACjB,2CAA2C,KAAK,SAAS,OAAO,GACjE;AACD,QAAK,mBAAmB,IAAIC,qBAAwB,KAAK,SAAS,OAAO;;AAI3E,gBACE,8BAA8B,iCAAiC,CAChE;;CAIH,AAAO,OACL,SACA,SACiB;AACjB,MAAI;AACF,UAAO,KAAK,QAAQ,SAAS,QAAQ;WAC9B,GAAG;GACV,MAAM,QAAQ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,8BAA8B,OAAqC;AAC1E,SAAQ,OAAR;EACE,KAAK,gBAAgB,MACnB,iBAAmB;EACrB,KAAK,gBAAgB,MACnB,iBAAmB;EACrB,KAAK,gBAAgB,KACnB,iBAAmB;EACrB,KAAK,gBAAgB,KACnB,iBAAmB;EACrB,KAAK,gBAAgB,MACnB,iBAAmB;;;AAIzB,SAAS,8BACP,UACgC;AAChC,SAAQ,UAAR;EACE,KAAK,QACH,oCAAsC;EACxC,KAAK,OACH,oCAAsC;EACxC,KAAK;EACL,KAAK,OACH,oCAAsC"}
|
|
1
|
+
{"version":3,"file":"generic.js","names":["endpoint: Endpoint","protocolMode: ProtocolMode","additionalDiscoveryFields: Partial<EndpointManifest>","vm.WasmIdentityVerifier","vm.WasmHeader","service: Component","handler: ComponentHandler","attemptHeaders: Headers","extraArgs: unknown[]","additionalContext: AdditionalContext","journalValueCodecInit:\n | Promise<JournalValueCodec>\n | undefined","loggerTransport: LoggerTransport","vm.WasmVM","journalValueCodec: JournalValueCodec","ctx: ContextImpl","invocationRequest: Request","hooks: Hooks[]","hookContext: { request: Request }","encodedOutput: Uint8Array | undefined","originalError: unknown"],"sources":["../../../src/endpoint/handlers/generic.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 {\n ensureError,\n logError,\n PauseError,\n RestateError,\n RetryableError,\n TerminalError,\n} from \"../../types/errors.js\";\nimport type {\n Endpoint as EndpointManifest,\n ProtocolMode,\n} from \"../discovery.js\";\nimport {\n Component,\n ComponentHandler,\n InvokePathComponents,\n} from \"../components.js\";\nimport { parseUrlComponents } from \"../components.js\";\nimport { X_RESTATE_SERVER } from \"../../user_agent.js\";\nimport { CommandError, ContextImpl } from \"../../context_impl.js\";\nimport { restoreError, sanitizeError } from \"../../error_sanitization.js\";\nimport type { InvocationId, Request } from \"../../context.js\";\nimport * as vm from \"./vm/sdk_shared_core_wasm_bindings.js\";\nimport { HandlerKind } from \"../../types/rpc.js\";\nimport { createLogger, type Logger } from \"../../logging/logger.js\";\nimport { DEFAULT_CONSOLE_LOGGER_LOG_LEVEL } from \"../../logging/console_logger_transport.js\";\nimport {\n LoggerContext,\n LoggerTransport,\n LogSource,\n RestateLogLevel,\n} from \"../../logging/logger_transport.js\";\nimport {\n type JournalValueCodec,\n millisOrDurationToMillis,\n} from \"@restatedev/restate-sdk-core\";\nimport type { Endpoint } from \"../endpoint.js\";\nimport {\n type RestateHandler,\n type Headers,\n type RestateRequest,\n type AdditionalContext,\n type RestateResponse,\n ResponseHeaders,\n InputReader,\n OutputWriter,\n} from \"./types.js\";\nimport { handleDiscovery } from \"./discovery.js\";\nimport { handlePreview } from \"./preview.js\";\nimport {\n errorResponse,\n invocationIdFromHeaders,\n simpleResponse,\n tryCreateContextualLogger,\n} from \"./utils.js\";\nimport { destroyLogger, registerLogger } from \"./core_logging.js\";\nimport type { Hooks } from \"../../hooks.js\";\n\n// Hidden symbol key used by first-party hooks to read the live\n// replay/processing phase without widening the public HooksProvider API.\nconst HOOK_CONTEXT_IS_PROCESSING_SYMBOL = Symbol.for(\n \"@restatedev/restate-sdk/hooks.isProcessing\"\n);\n\nexport function createRestateHandler(\n endpoint: Endpoint,\n protocolMode: ProtocolMode,\n additionalDiscoveryFields: Partial<EndpointManifest>\n): RestateHandler {\n return new RestateHandlerImpl(\n endpoint,\n protocolMode,\n additionalDiscoveryFields\n );\n}\n\n/**\n * This is the RestateHandler implementation\n */\nclass RestateHandlerImpl implements RestateHandler {\n private readonly identityVerifier?: vm.WasmIdentityVerifier;\n\n constructor(\n readonly endpoint: Endpoint,\n private readonly protocolMode: ProtocolMode,\n private readonly additionalDiscoveryFields: Partial<EndpointManifest>\n ) {\n // Setup identity verifier\n if (\n this.endpoint.keySet === undefined ||\n this.endpoint.keySet.length === 0\n ) {\n this.endpoint.rlog.warn(\n `Accepting requests without validating request signatures; handler access must be restricted`\n );\n } else {\n this.endpoint.rlog.info(\n `Validating requests using signing keys [${this.endpoint.keySet}]`\n );\n this.identityVerifier = new vm.WasmIdentityVerifier(this.endpoint.keySet);\n }\n\n // Set the logging level in the shared core too!\n vm.set_log_level(\n restateLogLevelToWasmLogLevel(DEFAULT_CONSOLE_LOGGER_LOG_LEVEL)\n );\n }\n\n // handle does not throw.\n public handle(\n request: RestateRequest,\n context?: AdditionalContext\n ): RestateResponse {\n try {\n return this._handle(request, context);\n } catch (e) {\n const error = ensureError(e);\n (\n tryCreateContextualLogger(\n this.endpoint.loggerTransport,\n request.url,\n request.headers\n ) ?? this.endpoint.rlog\n ).error(\n \"Error while handling request: \" + (error.stack ?? error.message)\n );\n return errorResponse(\n error instanceof RestateError ? error.code : 500,\n error.message\n );\n }\n }\n\n private _handle(\n request: RestateRequest,\n context?: AdditionalContext\n ): RestateResponse {\n // this is the recommended way to get the relative path from a url that may be relative or absolute\n const path = new URL(request.url, \"https://example.com\").pathname;\n const parsed = parseUrlComponents(path);\n\n if (parsed.type === \"unknown\") {\n const msg =\n \"Invalid path. Allowed are /health, /discover, /invoke/SvcName/handlerName, \" +\n \"/serdes/SvcName/decode/<serdeName>, or \" +\n \"/serdes/SvcName/encode/<serdeName>, but was: \" +\n path;\n this.endpoint.rlog.trace(msg);\n return errorResponse(404, msg);\n }\n if (parsed.type === \"health\") {\n return simpleResponse(\n 200,\n {\n \"content-type\": \"application/text\",\n \"x-restate-server\": X_RESTATE_SERVER,\n },\n new TextEncoder().encode(\"OK\")\n );\n }\n\n // Discovery, preview, and handling invocations require identity verification\n const error = this.validateConnectionSignature(path, request.headers);\n if (error !== null) {\n return error;\n }\n if (parsed.type === \"discover\") {\n return handleDiscovery(\n this.endpoint,\n this.protocolMode,\n this.additionalDiscoveryFields,\n request.headers[\"accept\"]\n );\n }\n if (parsed.type === \"preview\") {\n return handlePreview(this.endpoint, parsed);\n }\n\n return this.handleInvoke(\n parsed,\n request.headers,\n request.extraArgs,\n context ?? {}\n );\n }\n\n private validateConnectionSignature(\n path: string,\n headers: Headers\n ): RestateResponse | null {\n if (!this.identityVerifier) {\n // not validating\n return null;\n }\n\n const vmHeaders = Object.entries(headers)\n .filter(([, v]) => v !== undefined)\n .map(\n ([k, v]) =>\n new vm.WasmHeader(k, v instanceof Array ? v[0]! : (v as string))\n );\n\n try {\n this.identityVerifier.verify_identity(path, vmHeaders);\n return null;\n } catch (e) {\n this.endpoint.rlog.error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Rejecting request as its JWT did not validate: ${e}`\n );\n return errorResponse(401, \"Unauthorized\");\n }\n }\n\n private handleInvoke(\n invokePathComponent: InvokePathComponents,\n headers: Headers,\n extraArgs: unknown[],\n additionalContext: AdditionalContext\n ): RestateResponse {\n // Check if we support this protocol version\n const serviceProtocolVersionString = headers[\"content-type\"];\n if (typeof serviceProtocolVersionString !== \"string\") {\n const errorMessage = \"Missing content-type header\";\n this.endpoint.rlog.warn(errorMessage);\n return errorResponse(415, errorMessage);\n }\n\n const service = this.endpoint.components.get(\n invokePathComponent.componentName\n );\n if (!service) {\n const msg = `No service found for URL: ${JSON.stringify(invokePathComponent)}`;\n this.endpoint.rlog.error(msg);\n return errorResponse(404, msg);\n }\n\n const handler = service.handlerMatching(invokePathComponent);\n if (!handler) {\n const msg = `No handler found for URL: ${JSON.stringify(invokePathComponent)}`;\n this.endpoint.rlog.error(msg);\n return errorResponse(404, msg);\n }\n\n return new RestateInvokeResponse(\n service,\n handler,\n headers,\n extraArgs,\n additionalContext,\n this.endpoint.journalValueCodec,\n this.endpoint.loggerTransport\n );\n }\n}\n\nclass RestateInvokeResponse implements RestateResponse {\n private readonly headers: ResponseHeaders;\n private readonly statusCode: number;\n\n private readonly loggerId: number;\n private vmLogger: Logger;\n private readonly coreVm: vm.WasmVM;\n\n constructor(\n private readonly service: Component,\n private readonly handler: ComponentHandler,\n private readonly attemptHeaders: Headers,\n private readonly extraArgs: unknown[],\n private readonly additionalContext: AdditionalContext,\n private readonly journalValueCodecInit:\n | Promise<JournalValueCodec>\n | undefined,\n private readonly loggerTransport: LoggerTransport\n ) {\n this.loggerId = Math.floor(Math.random() * 4_294_967_295 /* u32::MAX */);\n const isJournalCodecDefined = this.journalValueCodecInit !== undefined;\n\n // Instantiate core vm and prepare response headers\n const vmHeaders = Object.entries(this.attemptHeaders)\n .filter(([, v]) => v !== undefined)\n .map(\n ([k, v]) =>\n new vm.WasmHeader(k, v instanceof Array ? v[0]! : (v as string))\n );\n this.coreVm = new vm.WasmVM(\n vmHeaders,\n restateLogLevelToWasmLogLevel(DEFAULT_CONSOLE_LOGGER_LOG_LEVEL),\n this.loggerId,\n isJournalCodecDefined,\n handler.executionOptions.explicitCancellation ?? false,\n onJournalMismatchErrorsToWasm(\n handler.executionOptions.onJournalMismatchErrors\n ),\n handler.executionOptions.explicitRecovery ?? false\n );\n const responseHead = this.coreVm.get_response_head();\n this.statusCode = responseHead.status_code;\n this.headers = responseHead.headers.reduce(\n (headers, { key, value }) => ({\n [key]: value,\n ...headers,\n }),\n {\n \"x-restate-server\": X_RESTATE_SERVER,\n }\n );\n this.vmLogger = createLogger(\n this.loggerTransport,\n LogSource.JOURNAL,\n new LoggerContext(\n invocationIdFromHeaders(this.attemptHeaders),\n this.service.name(),\n this.handler.name(),\n undefined,\n undefined,\n this.additionalContext\n )\n );\n }\n\n async process({\n inputReader,\n outputWriter,\n writeHead,\n abortSignal,\n }: {\n inputReader: InputReader;\n outputWriter: OutputWriter;\n writeHead: (statusCode: number, headers: ResponseHeaders) => void;\n abortSignal: AbortSignal;\n }): Promise<void> {\n // Commit the response head immediately — the VM-determined head is known\n // at construction time and never changes during processing.\n writeHead(this.statusCode, this.headers);\n\n abortSignal.addEventListener(\n \"abort\",\n () => {\n // In any case, on abort remove the invocation logger to avoid memory leaks\n destroyLogger(this.loggerId);\n\n // When the HTTP connection closes (e.g. abort timeout), poison the VM.\n // We only read new input from the server when a Restate command is\n // waiting for a response. If no command has been issued, the server's\n // abort signal is never read. Poisoning the VM ensures the handler\n // fails on the next VM call (e.g. ctx.run, ctx.sleep).\n setImmediate(() => {\n const msg = \"Connection closed\";\n this.coreVm.notify_error(msg, msg);\n });\n },\n { once: true }\n );\n // Use a default logger that still respects the endpoint custom logger\n // We will override this later with a logger that has a LoggerContext\n // See vm_log below for more details\n registerLogger(this.loggerId, this.vmLogger);\n\n const journalValueCodec: JournalValueCodec = this.journalValueCodecInit\n ? await this.journalValueCodecInit\n : {\n encode: (entry) => entry,\n decode: (entry) => Promise.resolve(entry),\n };\n\n // This promise is used to signal the end of the computation,\n // which can be either the user returns a value,\n // or an exception gets caught, or the state machine fails/suspends.\n //\n // The last case is handled internally within the ContextImpl.\n const invocationEndPromise = Promise.withResolvers<void>();\n let ctx: ContextImpl;\n\n // Initial phase before running user code\n // -> Buffer in shared core the journal entries\n // -> Initiate loggers\n // -> Initialize the ContextImpl\n try {\n // Buffer journal inside shared core\n await bufferJournalReplayInCoreVm(this.coreVm, inputReader);\n\n // Get input from coreVm to build the request object\n const input = this.coreVm.sys_input();\n const invocationRequest: Request = {\n target: {\n service: this.service.name(),\n handler: this.handler.name(),\n key: input.key || undefined,\n toString() {\n return this.key !== undefined\n ? `${this.service}/${this.key}/${this.handler}`\n : `${this.service}/${this.handler}`;\n },\n },\n id: input.invocation_id as InvocationId,\n headers: input.headers.reduce((headers, { key, value }) => {\n headers.set(key, value);\n return headers;\n }, new Map()),\n attemptHeaders: Object.entries(this.attemptHeaders).reduce(\n (headers, [key, value]) => {\n if (value !== undefined) {\n headers.set(key, value instanceof Array ? value[0] : value);\n }\n return headers;\n },\n new Map()\n ),\n body: input.input,\n extraArgs: this.extraArgs,\n idempotencyKey: input.idempotency_key || undefined,\n scope: input.scope || undefined,\n limitKey: input.limit_key || undefined,\n attemptCompletedSignal: abortSignal,\n };\n\n // Prepare logger\n const loggerContext = new LoggerContext(\n input.invocation_id,\n this.handler.component().name(),\n this.handler.name(),\n this.handler.kind() === HandlerKind.SERVICE ? undefined : input.key,\n invocationRequest,\n this.additionalContext\n );\n const ctxLogger = createLogger(\n this.loggerTransport,\n LogSource.USER,\n loggerContext,\n () => !this.coreVm.is_processing()\n );\n // Override the vmLogger created before with more info!\n this.vmLogger = createLogger(\n this.loggerTransport,\n LogSource.JOURNAL,\n loggerContext\n // Filtering is done within the shared core\n );\n\n // See vm_log below for more details\n registerLogger(this.loggerId, this.vmLogger);\n if (!this.coreVm.is_processing()) {\n this.vmLogger.info(\"Replaying invocation.\");\n } else {\n this.vmLogger.info(\"Starting invocation.\");\n }\n\n // Prepare context\n ctx = new ContextImpl(\n this.coreVm,\n input,\n ctxLogger,\n this.handler.kind(),\n this.vmLogger,\n invocationRequest,\n invocationEndPromise,\n inputReader,\n outputWriter,\n journalValueCodec,\n this.handler.executionOptions\n );\n } catch (e) {\n // That's \"preflight\" failure cases, where stuff fails before running user code\n // In this scenario, we close the coreVm, then flush and close\n const error = ensureError(e);\n this.coreVm.notify_error(error.message, error.message);\n try {\n await flushAndClose(\n this.coreVm,\n this.vmLogger,\n Promise.resolve(inputReader),\n outputWriter\n );\n } finally {\n // Safety net: the abort listener should clean this up when the attempt\n // ends, but process() owns the logger registration, so avoid leaking if\n // an adapter ever fails to abort the attempt-completed signal.\n destroyLogger(this.loggerId);\n }\n return;\n }\n\n // Run user code. Errors that reach the handler or interceptor code\n // (handler throws, interceptor throws, entry completes with terminal\n // failure) propagate naturally. Errors where the handler is stuck on\n // an await that will never settle (e.g. suspension, retryable run\n // error) are broken out by raceWithAttemptEnd, which races against\n // invocationEndPromise — rejected by ContextImpl when the attempt ends.\n try {\n await startUserHandler(\n ctx,\n this.service,\n this.handler,\n journalValueCodec\n );\n } catch (e) {\n notifyError(e, ctx, this.handler.executionOptions.asTerminalError);\n } finally {\n try {\n await flushAndClose(\n this.coreVm,\n this.vmLogger,\n ctx.inputPump.stop(),\n outputWriter\n );\n } finally {\n // Safety net: the abort listener should clean this up when the attempt\n // ends, but process() owns the logger registration, so avoid leaking if\n // an adapter ever fails to abort the attempt-completed signal.\n destroyLogger(this.loggerId);\n }\n }\n }\n}\n\nasync function bufferJournalReplayInCoreVm(\n coreVm: vm.WasmVM,\n inputReader: InputReader\n) {\n while (!coreVm.is_ready_to_execute()) {\n const nextValue = await inputReader.next();\n if (nextValue.done) {\n coreVm.notify_input_closed();\n break;\n }\n if (nextValue.value !== undefined) {\n coreVm.notify_input(nextValue.value);\n }\n }\n}\n\nasync function startUserHandler(\n ctx: ContextImpl,\n service: Component,\n handler: ComponentHandler,\n journalValueCodec: JournalValueCodec\n) {\n // Instantiate hooks from providers.\n // If a provider throws, the same rules as handler failures apply:\n // TerminalError → terminate invocation, other errors → retry.\n const hooks: Hooks[] = [];\n for (const provider of handler.executionOptions.hooks ?? []) {\n const hookContext: { request: Request } = {\n request: ctx.request(),\n };\n Object.defineProperty(hookContext, HOOK_CONTEXT_IS_PROCESSING_SYMBOL, {\n value: () => ctx.isProcessing(),\n enumerable: false,\n });\n hooks.push(provider(hookContext));\n }\n\n // Compose interceptor.handler into a single interceptor (first = outermost)\n const handlerInterceptor = composeInterceptors(\n hooks.map((h) => h.interceptor?.handler).filter(isDefined)\n );\n\n ctx.setRunInterceptor(\n composeInterceptors(hooks.map((h) => h.interceptor?.run).filter(isDefined))\n );\n\n let encodedOutput: Uint8Array | undefined;\n await raceWithAttemptEnd(\n ctx,\n handlerInterceptor\n )(async () => {\n const decodedInput = await journalValueCodec\n .decode(ctx.request().body)\n .catch((e) =>\n // Re-throw as terminal error, to fail on input errors\n Promise.reject(\n new TerminalError(\n `Failed to decode input using journal value codec: ${\n ensureError(e).message\n }`,\n {\n errorCode: 400,\n }\n )\n )\n );\n\n // Then run user code\n const output = await handler.invoke(ctx, decodedInput);\n\n // Encode user code output\n encodedOutput = journalValueCodec.encode(output);\n });\n\n // Interceptor chain completed without error — commit the result.\n // sys_end() is called here (after interceptors) so that interceptor\n // errors after next() correctly prevent the invocation from succeeding.\n ctx.coreVm.sys_write_output_success(encodedOutput!);\n ctx.coreVm.sys_end();\n ctx.vmLogger.info(\"Invocation completed successfully.\");\n}\n\n/**\n * Classifies the error and notifies the VM. Called from the process() catch\n * block — the single place that decides how to report errors to the VM.\n */\nfunction notifyError(\n e: unknown,\n ctx: ContextImpl,\n asTerminalError?: (error: unknown) => TerminalError | undefined\n) {\n // Command-specific errors from ContextImpl carry metadata the VM needs\n // for command correlation. Check before ensureError to preserve the type.\n if (e instanceof CommandError) {\n const cause = ensureError(e.cause);\n logError(ctx.vmLogger, cause);\n if (e.hasCommandIndex) {\n // Completion failure — command exists in the journal\n ctx.coreVm.notify_error_for_specific_command(\n cause.message,\n cause.stack,\n e.commandType,\n e.commandIndex!,\n null\n );\n } else {\n // Preparation failure — command not yet issued\n ctx.coreVm.notify_error_for_next_command(\n cause.message,\n cause.stack,\n e.commandType\n );\n }\n return;\n }\n\n // Handler/interceptor errors\n const error = ensureError(e, asTerminalError);\n logError(ctx.vmLogger, error);\n\n try {\n if (error instanceof TerminalError) {\n // Terminal: write the failure as the invocation output\n ctx.coreVm.sys_write_output_failure({\n code: error.code,\n message: error.message,\n metadata: Object.entries(error.metadata ?? {}).map(([key, value]) => ({\n key,\n value,\n })),\n });\n ctx.coreVm.sys_end();\n } else if (error instanceof RetryableError) {\n // Retryable with explicit delay\n ctx.coreVm.notify_error_with_delay_override(\n error.message,\n error.stack,\n error.retryAfter !== undefined\n ? BigInt(millisOrDurationToMillis(error.retryAfter))\n : undefined\n );\n } else {\n if (error instanceof PauseError) {\n ctx.vmLogger.warn(\n \"Throwing PauseError from the handler context will be ignored, \" +\n \"as it leads to pause loops. You should use PauseError only inside `ctx.run`\"\n );\n }\n\n // Transient error — VM decides retry policy\n ctx.coreVm.notify_error(error.message, error.stack);\n }\n } catch (vmError) {\n // Safety net: if sys_write_output_failure or other VM calls fail,\n // fall back to notify_error.\n const inner = ensureError(vmError);\n ctx.coreVm.notify_error(inner.message, inner.stack);\n }\n}\n\nasync function flushAndClose(\n coreVm: vm.WasmVM,\n vmLogger: Logger,\n inputReaderGetter: Promise<InputReader>,\n outputWriter: OutputWriter\n): Promise<void> {\n let inputClosed = false;\n try {\n // Consume vm output buffer, write it out, then close the stream\n const nextOutput = coreVm.take_output();\n if (nextOutput?.length > 0) {\n await outputWriter.write(nextOutput);\n }\n\n // --- After this point, we should have flushed the shared core internal buffer\n\n // Wait for the input reader.\n // In case we executed the user code, this is wired up to the InputPump.stop()\n // to make sure there is only one reader for inputReader.\n const inputReader = await inputReaderGetter;\n\n // Let's make sure we properly close the request stream before closing the response stream\n while (!inputClosed) {\n try {\n const res = await inputReader.next();\n inputClosed = res.done ?? false;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n inputClosed = true;\n }\n }\n\n // Close the response stream\n await outputWriter.close();\n } catch (e) {\n // In case of failure, we can do little here except just logging stuff out,\n // because outputWriter is not usable here.\n const error = ensureError(e);\n const abortErrorOnWrite = isAbortErrorOnWrite(error);\n\n if (inputClosed && abortErrorOnWrite) {\n // Because we closed the input already,\n // these errors are benign and are caused by\n // synchronization issues wrt closing the response stream in the runtime\n // This will be fixed in the runtime with https://github.com/restatedev/restate/issues/4456\n return;\n }\n\n if (abortErrorOnWrite) {\n vmLogger.error(\n \"Got abort error from connection: \" +\n error.message +\n \"\\n\" +\n \"This might indicate that:\\n\" +\n \"* The restate-server aborted the connection after hitting the 'abort-timeout'\\n\" +\n \"* The connection with the restate-server was lost\\n\" +\n \"\\n\" +\n \"Please check the invocation in the Restate UI for more details.\"\n );\n } else {\n vmLogger.error(\n \"Error while handling request: \" + (error.stack ?? error.message)\n );\n }\n }\n}\n\nfunction isAbortErrorOnWrite(error: Error) {\n return (\n error.name === \"AbortError\" ||\n error.message === \"Invalid state: WritableStream is closed\" ||\n /**\n * Node stream closed error thrown on writes\n */\n (error as { code?: string }).code === \"ERR_HTTP2_INVALID_STREAM\"\n );\n}\n\n// -- Hook composition utils --------------------------------------------------\n\ntype InterceptorFn<Args extends unknown[]> = (\n ...args: [...Args, () => Promise<void>]\n) => Promise<void>;\n\nfunction composeInterceptors<Args extends unknown[]>(\n interceptors: InterceptorFn<Args>[]\n): InterceptorFn<Args> {\n return interceptors.reduceRight<InterceptorFn<Args>>(\n (innerInterceptor, interceptor) =>\n (...args) => {\n const context = args.slice(0, -1) as unknown as Args;\n const callback = args.at(-1) as () => Promise<void>;\n return interceptor(...context, () =>\n innerInterceptor(...context, callback)\n );\n },\n (...args) => (args.at(-1) as () => Promise<void>)()\n );\n}\n\n/**\n * Wraps an interceptor so that both `next()` and the interceptor body race\n * against `invocationEndPromise`. When the attempt ends (suspension, retryable\n * error, etc.), the promise rejects and the interceptor chain unwinds through\n * catch/finally blocks — preventing interceptors from hanging on a `next()`\n * that will never settle.\n *\n * SDK-internal metadata (CommandError, retryAfter) is stripped before the\n * interceptor sees the error and restored after the chain exits.\n */\nfunction raceWithAttemptEnd<Args extends unknown[]>(\n ctx: ContextImpl,\n interceptor: InterceptorFn<Args>\n): InterceptorFn<Args> {\n return (...args) => {\n let originalError: unknown;\n\n // Strip SDK metadata before interceptors see the error.\n // Store the original in the closure for restoration after the chain.\n const signal = ctx.invocationEndPromise.promise.catch((e) => {\n originalError = e;\n throw sanitizeError(e);\n }) as Promise<never>;\n\n const originalNext = args.at(-1) as () => Promise<void>;\n const racingNext = () => Promise.race([originalNext(), signal]);\n const newArgs = [...args.slice(0, -1), racingNext] as unknown as [\n ...Args,\n () => Promise<void>,\n ];\n\n return Promise.race([interceptor(...newArgs), signal]).catch((e) => {\n // Restore SDK metadata after the interceptor chain exits.\n if (originalError !== undefined) {\n throw restoreError(e, originalError);\n }\n throw e;\n });\n };\n}\n\nfunction isDefined<T>(value: T | undefined | null): value is T {\n return value != null;\n}\n\n// -- Logging utils -----------------------------------------------------------\n\nfunction restateLogLevelToWasmLogLevel(level: RestateLogLevel): vm.LogLevel {\n switch (level) {\n case RestateLogLevel.TRACE:\n return vm.LogLevel.TRACE;\n case RestateLogLevel.DEBUG:\n return vm.LogLevel.DEBUG;\n case RestateLogLevel.INFO:\n return vm.LogLevel.INFO;\n case RestateLogLevel.WARN:\n return vm.LogLevel.WARN;\n case RestateLogLevel.ERROR:\n return vm.LogLevel.ERROR;\n }\n}\n\nfunction onJournalMismatchErrorsToWasm(\n behavior: \"retry\" | \"pause\" | \"fail\" | undefined\n): vm.WasmJournalMismatchBehavior {\n switch (behavior) {\n case \"pause\":\n return vm.WasmJournalMismatchBehavior.Pause;\n case \"fail\":\n return vm.WasmJournalMismatchBehavior.Fail;\n case \"retry\":\n case undefined:\n return vm.WasmJournalMismatchBehavior.Retry;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuEA,MAAM,oCAAoC,OAAO,IAC/C,6CACD;AAED,SAAgB,qBACd,UACA,cACA,2BACgB;AAChB,QAAO,IAAI,mBACT,UACA,cACA,0BACD;;;;;AAMH,IAAM,qBAAN,MAAmD;CACjD,AAAiB;CAEjB,YACE,AAASA,UACT,AAAiBC,cACjB,AAAiBC,2BACjB;EAHS;EACQ;EACA;AAGjB,MACE,KAAK,SAAS,WAAW,UACzB,KAAK,SAAS,OAAO,WAAW,EAEhC,MAAK,SAAS,KAAK,KACjB,8FACD;OACI;AACL,QAAK,SAAS,KAAK,KACjB,2CAA2C,KAAK,SAAS,OAAO,GACjE;AACD,QAAK,mBAAmB,IAAIC,qBAAwB,KAAK,SAAS,OAAO;;AAI3E,gBACE,8BAA8B,iCAAiC,CAChE;;CAIH,AAAO,OACL,SACA,SACiB;AACjB,MAAI;AACF,UAAO,KAAK,QAAQ,SAAS,QAAQ;WAC9B,GAAG;GACV,MAAM,QAAQ,YAAY,EAAE;AAC5B,IACE,0BACE,KAAK,SAAS,iBACd,QAAQ,KACR,QAAQ,QACT,IAAI,KAAK,SAAS,MACnB,MACA,oCAAoC,MAAM,SAAS,MAAM,SAC1D;AACD,UAAO,cACL,iBAAiB,eAAe,MAAM,O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ACrB,KAAK,gBAAgB,KACnB,iBAAmB;EACrB,KAAK,gBAAgB,MACnB,iBAAmB;;;AAIzB,SAAS,8BACP,UACgC;AAChC,SAAQ,UAAR;EACE,KAAK,QACH,oCAAsC;EACxC,KAAK,OACH,oCAAsC;EACxC,KAAK;EACL,KAAK,OACH,oCAAsC"}
|
|
@@ -40,7 +40,7 @@ export interface WasmSendHandle {
|
|
|
40
40
|
|
|
41
41
|
export type WasmAsyncResultValue = "NotReady" | "Empty" | { Success: Uint8Array } | { Failure: WasmFailure } | { StateKeys: string[] } | { InvocationId: string };
|
|
42
42
|
|
|
43
|
-
export type WasmDoProgressResult = "AnyCompleted" | "WaitExternalProgress" | { ExecuteRun: number } | "CancelSignalReceived";
|
|
43
|
+
export type WasmDoProgressResult = "AnyCompleted" | "WaitExternalProgress" | { ExecuteRun: number } | "CancelSignalReceived" | { EphemeralNotificationReady: number };
|
|
44
44
|
|
|
45
45
|
export type WasmUnresolvedFuture = { Single: number } | { FirstCompleted: WasmUnresolvedFuture[] } | { AllCompleted: WasmUnresolvedFuture[] } | { FirstSucceededOrAllFailed: WasmUnresolvedFuture[] } | { AllSucceededOrFirstFailed: WasmUnresolvedFuture[] } | { Unknown: WasmUnresolvedFuture[] };
|
|
46
46
|
|
|
@@ -134,12 +134,13 @@ export class WasmVM {
|
|
|
134
134
|
free(): void;
|
|
135
135
|
[Symbol.dispose](): void;
|
|
136
136
|
do_progress(future: WasmUnresolvedFuture): WasmDoProgressResult;
|
|
137
|
+
ephemeral_state_get(key: string): number;
|
|
137
138
|
get_response_head(): WasmResponseHead;
|
|
138
139
|
is_completed(handle: number): boolean;
|
|
139
140
|
is_processing(): boolean;
|
|
140
141
|
is_ready_to_execute(): boolean;
|
|
141
142
|
last_command_index(): number;
|
|
142
|
-
constructor(headers: WasmHeader[], log_level: LogLevel, logger_id: number, disable_payload_checks: boolean, explicit_cancellation: boolean, on_journal_mismatch: WasmJournalMismatchBehavior);
|
|
143
|
+
constructor(headers: WasmHeader[], log_level: LogLevel, logger_id: number, disable_payload_checks: boolean, explicit_cancellation: boolean, on_journal_mismatch: WasmJournalMismatchBehavior, explicit_recovery: boolean);
|
|
143
144
|
notify_error(error_message: string, stacktrace?: string | null): void;
|
|
144
145
|
notify_error_for_next_command(error_message: string, stacktrace: string | null | undefined, wasm_command_type: WasmCommandType): void;
|
|
145
146
|
notify_error_for_specific_command(error_message: string, stacktrace: string | null | undefined, wasm_command_type: WasmCommandType, command_index: number, command_name?: string | null): void;
|
|
@@ -155,8 +156,8 @@ export class WasmVM {
|
|
|
155
156
|
sys_awakeable(): WasmAwakeable;
|
|
156
157
|
sys_call(service: string, handler: string, buffer: Uint8Array, key: string | null | undefined, headers: WasmHeader[], idempotency_key?: string | null, scope?: string | null, limit_key?: string | null, name?: string | null): WasmCallHandle;
|
|
157
158
|
sys_cancel_invocation(target_invocation_id: string): void;
|
|
158
|
-
sys_clear_all_state(): void;
|
|
159
|
-
sys_clear_state(key: string): void;
|
|
159
|
+
sys_clear_all_state(name?: string | null): void;
|
|
160
|
+
sys_clear_state(key: string, name?: string | null): void;
|
|
160
161
|
sys_complete_awakeable_failure(id: string, value: WasmFailure): void;
|
|
161
162
|
sys_complete_awakeable_success(id: string, buffer: Uint8Array): void;
|
|
162
163
|
sys_complete_promise_failure(key: string, value: WasmFailure): number;
|
|
@@ -166,17 +167,18 @@ export class WasmVM {
|
|
|
166
167
|
sys_end(): void;
|
|
167
168
|
sys_get_invocation_output(invocation_id: string): number;
|
|
168
169
|
sys_get_promise(key: string): number;
|
|
169
|
-
sys_get_state(key: string): number;
|
|
170
|
-
sys_get_state_keys(): number;
|
|
170
|
+
sys_get_state(key: string, name?: string | null): number;
|
|
171
|
+
sys_get_state_keys(name?: string | null): number;
|
|
171
172
|
sys_input(): WasmInput;
|
|
172
173
|
sys_peek_promise(key: string): number;
|
|
173
174
|
sys_run(name: string): WasmRun;
|
|
174
175
|
sys_send(service: string, handler: string, buffer: Uint8Array, key: string | null | undefined, headers: WasmHeader[], delay?: bigint | null, idempotency_key?: string | null, scope?: string | null, limit_key?: string | null, name?: string | null): WasmSendHandle;
|
|
175
|
-
sys_set_state(key: string, buffer: Uint8Array): void;
|
|
176
|
+
sys_set_state(key: string, buffer: Uint8Array, name?: string | null): void;
|
|
176
177
|
sys_signal(signal_name: string): number;
|
|
177
178
|
sys_sleep(millis: bigint, name?: string | null): number;
|
|
178
179
|
sys_write_output_failure(value: WasmFailure): void;
|
|
179
180
|
sys_write_output_success(buffer: Uint8Array): void;
|
|
181
|
+
take_ephemeral_notification(ephemeral_notification_handle: number): WasmAsyncResultValue;
|
|
180
182
|
take_notification(handle: number): WasmAsyncResultValue;
|
|
181
183
|
take_output(): Uint8Array;
|
|
182
184
|
}
|
|
@@ -335,6 +335,19 @@ export class WasmVM {
|
|
|
335
335
|
}
|
|
336
336
|
return takeFromExternrefTable0(ret[0]);
|
|
337
337
|
}
|
|
338
|
+
/**
|
|
339
|
+
* @param {string} key
|
|
340
|
+
* @returns {number}
|
|
341
|
+
*/
|
|
342
|
+
ephemeral_state_get(key) {
|
|
343
|
+
const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
344
|
+
const len0 = WASM_VECTOR_LEN;
|
|
345
|
+
const ret = wasm.wasmvm_ephemeral_state_get(this.__wbg_ptr, ptr0, len0);
|
|
346
|
+
if (ret[2]) {
|
|
347
|
+
throw takeFromExternrefTable0(ret[1]);
|
|
348
|
+
}
|
|
349
|
+
return ret[0] >>> 0;
|
|
350
|
+
}
|
|
338
351
|
/**
|
|
339
352
|
* @returns {WasmResponseHead}
|
|
340
353
|
*/
|
|
@@ -381,11 +394,12 @@ export class WasmVM {
|
|
|
381
394
|
* @param {boolean} disable_payload_checks
|
|
382
395
|
* @param {boolean} explicit_cancellation
|
|
383
396
|
* @param {WasmJournalMismatchBehavior} on_journal_mismatch
|
|
397
|
+
* @param {boolean} explicit_recovery
|
|
384
398
|
*/
|
|
385
|
-
constructor(headers, log_level, logger_id, disable_payload_checks, explicit_cancellation, on_journal_mismatch) {
|
|
399
|
+
constructor(headers, log_level, logger_id, disable_payload_checks, explicit_cancellation, on_journal_mismatch, explicit_recovery) {
|
|
386
400
|
const ptr0 = passArrayJsValueToWasm0(headers, wasm.__wbindgen_malloc);
|
|
387
401
|
const len0 = WASM_VECTOR_LEN;
|
|
388
|
-
const ret = wasm.wasmvm_new(ptr0, len0, log_level, logger_id, disable_payload_checks, explicit_cancellation, on_journal_mismatch);
|
|
402
|
+
const ret = wasm.wasmvm_new(ptr0, len0, log_level, logger_id, disable_payload_checks, explicit_cancellation, on_journal_mismatch, explicit_recovery);
|
|
389
403
|
if (ret[2]) {
|
|
390
404
|
throw takeFromExternrefTable0(ret[1]);
|
|
391
405
|
}
|
|
@@ -600,19 +614,27 @@ export class WasmVM {
|
|
|
600
614
|
throw takeFromExternrefTable0(ret[0]);
|
|
601
615
|
}
|
|
602
616
|
}
|
|
603
|
-
|
|
604
|
-
|
|
617
|
+
/**
|
|
618
|
+
* @param {string | null} [name]
|
|
619
|
+
*/
|
|
620
|
+
sys_clear_all_state(name) {
|
|
621
|
+
var ptr0 = isLikeNone(name) ? 0 : passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
622
|
+
var len0 = WASM_VECTOR_LEN;
|
|
623
|
+
const ret = wasm.wasmvm_sys_clear_all_state(this.__wbg_ptr, ptr0, len0);
|
|
605
624
|
if (ret[1]) {
|
|
606
625
|
throw takeFromExternrefTable0(ret[0]);
|
|
607
626
|
}
|
|
608
627
|
}
|
|
609
628
|
/**
|
|
610
629
|
* @param {string} key
|
|
630
|
+
* @param {string | null} [name]
|
|
611
631
|
*/
|
|
612
|
-
sys_clear_state(key) {
|
|
632
|
+
sys_clear_state(key, name) {
|
|
613
633
|
const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
614
634
|
const len0 = WASM_VECTOR_LEN;
|
|
615
|
-
|
|
635
|
+
var ptr1 = isLikeNone(name) ? 0 : passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
636
|
+
var len1 = WASM_VECTOR_LEN;
|
|
637
|
+
const ret = wasm.wasmvm_sys_clear_state(this.__wbg_ptr, ptr0, len0, ptr1, len1);
|
|
616
638
|
if (ret[1]) {
|
|
617
639
|
throw takeFromExternrefTable0(ret[0]);
|
|
618
640
|
}
|
|
@@ -739,22 +761,28 @@ export class WasmVM {
|
|
|
739
761
|
}
|
|
740
762
|
/**
|
|
741
763
|
* @param {string} key
|
|
764
|
+
* @param {string | null} [name]
|
|
742
765
|
* @returns {number}
|
|
743
766
|
*/
|
|
744
|
-
sys_get_state(key) {
|
|
767
|
+
sys_get_state(key, name) {
|
|
745
768
|
const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
746
769
|
const len0 = WASM_VECTOR_LEN;
|
|
747
|
-
|
|
770
|
+
var ptr1 = isLikeNone(name) ? 0 : passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
771
|
+
var len1 = WASM_VECTOR_LEN;
|
|
772
|
+
const ret = wasm.wasmvm_sys_get_state(this.__wbg_ptr, ptr0, len0, ptr1, len1);
|
|
748
773
|
if (ret[2]) {
|
|
749
774
|
throw takeFromExternrefTable0(ret[1]);
|
|
750
775
|
}
|
|
751
776
|
return ret[0] >>> 0;
|
|
752
777
|
}
|
|
753
778
|
/**
|
|
779
|
+
* @param {string | null} [name]
|
|
754
780
|
* @returns {number}
|
|
755
781
|
*/
|
|
756
|
-
sys_get_state_keys() {
|
|
757
|
-
|
|
782
|
+
sys_get_state_keys(name) {
|
|
783
|
+
var ptr0 = isLikeNone(name) ? 0 : passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
784
|
+
var len0 = WASM_VECTOR_LEN;
|
|
785
|
+
const ret = wasm.wasmvm_sys_get_state_keys(this.__wbg_ptr, ptr0, len0);
|
|
758
786
|
if (ret[2]) {
|
|
759
787
|
throw takeFromExternrefTable0(ret[1]);
|
|
760
788
|
}
|
|
@@ -837,13 +865,16 @@ export class WasmVM {
|
|
|
837
865
|
/**
|
|
838
866
|
* @param {string} key
|
|
839
867
|
* @param {Uint8Array} buffer
|
|
868
|
+
* @param {string | null} [name]
|
|
840
869
|
*/
|
|
841
|
-
sys_set_state(key, buffer) {
|
|
870
|
+
sys_set_state(key, buffer, name) {
|
|
842
871
|
const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
843
872
|
const len0 = WASM_VECTOR_LEN;
|
|
844
873
|
const ptr1 = passArray8ToWasm0(buffer, wasm.__wbindgen_malloc);
|
|
845
874
|
const len1 = WASM_VECTOR_LEN;
|
|
846
|
-
|
|
875
|
+
var ptr2 = isLikeNone(name) ? 0 : passStringToWasm0(name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
|
|
876
|
+
var len2 = WASM_VECTOR_LEN;
|
|
877
|
+
const ret = wasm.wasmvm_sys_set_state(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2);
|
|
847
878
|
if (ret[1]) {
|
|
848
879
|
throw takeFromExternrefTable0(ret[0]);
|
|
849
880
|
}
|
|
@@ -895,6 +926,17 @@ export class WasmVM {
|
|
|
895
926
|
throw takeFromExternrefTable0(ret[0]);
|
|
896
927
|
}
|
|
897
928
|
}
|
|
929
|
+
/**
|
|
930
|
+
* @param {number} ephemeral_notification_handle
|
|
931
|
+
* @returns {WasmAsyncResultValue}
|
|
932
|
+
*/
|
|
933
|
+
take_ephemeral_notification(ephemeral_notification_handle) {
|
|
934
|
+
const ret = wasm.wasmvm_take_ephemeral_notification(this.__wbg_ptr, ephemeral_notification_handle);
|
|
935
|
+
if (ret[2]) {
|
|
936
|
+
throw takeFromExternrefTable0(ret[1]);
|
|
937
|
+
}
|
|
938
|
+
return takeFromExternrefTable0(ret[0]);
|
|
939
|
+
}
|
|
898
940
|
/**
|
|
899
941
|
* @param {number} handle
|
|
900
942
|
* @returns {WasmAsyncResultValue}
|
|
Binary file
|
|
@@ -23,12 +23,13 @@ export const wasmheader_new: (a: number, b: number, c: number, d: number) => num
|
|
|
23
23
|
export const wasmidentityverifier_new: (a: number, b: number) => [number, number, number];
|
|
24
24
|
export const wasmidentityverifier_verify_identity: (a: number, b: number, c: number, d: number, e: number) => [number, number];
|
|
25
25
|
export const wasmvm_do_progress: (a: number, b: any) => [number, number, number];
|
|
26
|
+
export const wasmvm_ephemeral_state_get: (a: number, b: number, c: number) => [number, number, number];
|
|
26
27
|
export const wasmvm_get_response_head: (a: number) => number;
|
|
27
28
|
export const wasmvm_is_completed: (a: number, b: number) => number;
|
|
28
29
|
export const wasmvm_is_processing: (a: number) => number;
|
|
29
30
|
export const wasmvm_is_ready_to_execute: (a: number) => [number, number, number];
|
|
30
31
|
export const wasmvm_last_command_index: (a: number) => number;
|
|
31
|
-
export const wasmvm_new: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number, number];
|
|
32
|
+
export const wasmvm_new: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number) => [number, number, number];
|
|
32
33
|
export const wasmvm_notify_error: (a: number, b: number, c: number, d: number, e: number) => void;
|
|
33
34
|
export const wasmvm_notify_error_for_next_command: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
|
|
34
35
|
export const wasmvm_notify_error_for_specific_command: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number) => void;
|
|
@@ -44,8 +45,8 @@ export const wasmvm_sys_attach_invocation: (a: number, b: number, c: number) =>
|
|
|
44
45
|
export const wasmvm_sys_awakeable: (a: number) => [number, number, number];
|
|
45
46
|
export const wasmvm_sys_call: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: number, n: number, o: number, p: number, q: number, r: number, s: number) => [number, number, number];
|
|
46
47
|
export const wasmvm_sys_cancel_invocation: (a: number, b: number, c: number) => [number, number];
|
|
47
|
-
export const wasmvm_sys_clear_all_state: (a: number) => [number, number];
|
|
48
|
-
export const wasmvm_sys_clear_state: (a: number, b: number, c: number) => [number, number];
|
|
48
|
+
export const wasmvm_sys_clear_all_state: (a: number, b: number, c: number) => [number, number];
|
|
49
|
+
export const wasmvm_sys_clear_state: (a: number, b: number, c: number, d: number, e: number) => [number, number];
|
|
49
50
|
export const wasmvm_sys_complete_awakeable_failure: (a: number, b: number, c: number, d: any) => [number, number];
|
|
50
51
|
export const wasmvm_sys_complete_awakeable_success: (a: number, b: number, c: number, d: number, e: number) => [number, number];
|
|
51
52
|
export const wasmvm_sys_complete_promise_failure: (a: number, b: number, c: number, d: any) => [number, number, number];
|
|
@@ -55,21 +56,22 @@ export const wasmvm_sys_complete_signal_success: (a: number, b: number, c: numbe
|
|
|
55
56
|
export const wasmvm_sys_end: (a: number) => [number, number];
|
|
56
57
|
export const wasmvm_sys_get_invocation_output: (a: number, b: number, c: number) => [number, number, number];
|
|
57
58
|
export const wasmvm_sys_get_promise: (a: number, b: number, c: number) => [number, number, number];
|
|
58
|
-
export const wasmvm_sys_get_state: (a: number, b: number, c: number) => [number, number, number];
|
|
59
|
-
export const wasmvm_sys_get_state_keys: (a: number) => [number, number, number];
|
|
59
|
+
export const wasmvm_sys_get_state: (a: number, b: number, c: number, d: number, e: number) => [number, number, number];
|
|
60
|
+
export const wasmvm_sys_get_state_keys: (a: number, b: number, c: number) => [number, number, number];
|
|
60
61
|
export const wasmvm_sys_input: (a: number) => [number, number, number];
|
|
61
62
|
export const wasmvm_sys_peek_promise: (a: number, b: number, c: number) => [number, number, number];
|
|
62
63
|
export const wasmvm_sys_run: (a: number, b: number, c: number) => [number, number, number];
|
|
63
64
|
export const wasmvm_sys_send: (a: number, b: number, c: number, d: number, e: number, f: number, g: number, h: number, i: number, j: number, k: number, l: number, m: bigint, n: number, o: number, p: number, q: number, r: number, s: number, t: number, u: number) => [number, number, number];
|
|
64
|
-
export const wasmvm_sys_set_state: (a: number, b: number, c: number, d: number, e: number) => [number, number];
|
|
65
|
+
export const wasmvm_sys_set_state: (a: number, b: number, c: number, d: number, e: number, f: number, g: number) => [number, number];
|
|
65
66
|
export const wasmvm_sys_signal: (a: number, b: number, c: number) => [number, number, number];
|
|
66
67
|
export const wasmvm_sys_sleep: (a: number, b: bigint, c: number, d: number) => [number, number, number];
|
|
67
68
|
export const wasmvm_sys_write_output_failure: (a: number, b: any) => [number, number];
|
|
68
69
|
export const wasmvm_sys_write_output_success: (a: number, b: number, c: number) => [number, number];
|
|
70
|
+
export const wasmvm_take_ephemeral_notification: (a: number, b: number) => [number, number, number];
|
|
69
71
|
export const wasmvm_take_notification: (a: number, b: number) => [number, number, number];
|
|
70
72
|
export const wasmvm_take_output: (a: number) => any;
|
|
71
|
-
export const __wbg_get_wasminput_invocation_id: (a: number) => [number, number];
|
|
72
73
|
export const start: () => void;
|
|
74
|
+
export const __wbg_get_wasminput_invocation_id: (a: number) => [number, number];
|
|
73
75
|
export const __wbindgen_malloc: (a: number, b: number) => number;
|
|
74
76
|
export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
|
75
77
|
export const __wbindgen_exn_store: (a: number) => void;
|
package/dist/fetch.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CancelledError, PauseError, RestateError, RetryableError, RetryableErrorOptions, TerminalError, TimeoutError } from "./types/errors.cjs";
|
|
2
2
|
import { Hooks, HooksProvider, Interceptor } from "./hooks.cjs";
|
|
3
3
|
import { Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, InferArg, ObjectHandlerOpts, ObjectOptions, ObjectOpts, Opts, RemoveVoidArgument, RetryPolicy, SendClient, SendClientFromDescriptors, SendOpts, ServiceHandlerOpts, ServiceOptions, ServiceOpts, WorkflowHandlerOpts, WorkflowOptions, WorkflowOpts, handlers, object, rpc, service, workflow } from "./types/rpc.cjs";
|
|
4
|
-
import { Context, ContextDate, DurablePromise, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request as Request$1, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.cjs";
|
|
4
|
+
import { Context, ContextDate, DurablePromise, EntryOptions, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request as Request$1, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.cjs";
|
|
5
5
|
import { LogMetadata, LogSource, LoggerContext, LoggerTransport, RestateLogLevel } from "./logging/logger_transport.cjs";
|
|
6
6
|
import { DefaultServiceOptions, RestateEndpoint, RestateEndpointBase } from "./endpoint.cjs";
|
|
7
7
|
import { internal_d_exports } from "./internal.cjs";
|
|
@@ -52,5 +52,5 @@ interface FetchEndpointOptions extends EndpointOptions {
|
|
|
52
52
|
*/
|
|
53
53
|
declare function createEndpointHandler(options: FetchEndpointOptions): (request: Request, ...extraArgs: unknown[]) => Promise<Response>;
|
|
54
54
|
//#endregion
|
|
55
|
-
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, type FetchEndpoint, FetchEndpointOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request$1 as Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, service, workflow };
|
|
55
|
+
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, EntryOptions, type FetchEndpoint, FetchEndpointOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request$1 as Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, service, workflow };
|
|
56
56
|
//# sourceMappingURL=fetch.d.cts.map
|
package/dist/fetch.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CancelledError, PauseError, RestateError, RetryableError, RetryableErrorOptions, TerminalError, TimeoutError } from "./types/errors.js";
|
|
2
2
|
import { Hooks, HooksProvider, Interceptor } from "./hooks.js";
|
|
3
3
|
import { Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, InferArg, ObjectHandlerOpts, ObjectOptions, ObjectOpts, Opts, RemoveVoidArgument, RetryPolicy, SendClient, SendClientFromDescriptors, SendOpts, ServiceHandlerOpts, ServiceOptions, ServiceOpts, WorkflowHandlerOpts, WorkflowOptions, WorkflowOpts, handlers, object, rpc, service, workflow } from "./types/rpc.js";
|
|
4
|
-
import { Context, ContextDate, DurablePromise, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request as Request$1, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.js";
|
|
4
|
+
import { Context, ContextDate, DurablePromise, EntryOptions, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request as Request$1, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.js";
|
|
5
5
|
import { LogMetadata, LogSource, LoggerContext, LoggerTransport, RestateLogLevel } from "./logging/logger_transport.js";
|
|
6
6
|
import { DefaultServiceOptions, RestateEndpoint, RestateEndpointBase } from "./endpoint.js";
|
|
7
7
|
import { internal_d_exports } from "./internal.js";
|
|
@@ -52,5 +52,5 @@ interface FetchEndpointOptions extends EndpointOptions {
|
|
|
52
52
|
*/
|
|
53
53
|
declare function createEndpointHandler(options: FetchEndpointOptions): (request: Request, ...extraArgs: unknown[]) => Promise<Response>;
|
|
54
54
|
//#endregion
|
|
55
|
-
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, type FetchEndpoint, FetchEndpointOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request$1 as Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, service, workflow };
|
|
55
|
+
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, EntryOptions, type FetchEndpoint, FetchEndpointOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request$1 as Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, service, workflow };
|
|
56
56
|
//# sourceMappingURL=fetch.d.ts.map
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CancelledError, PauseError, RestateError, RetryableError, RetryableErrorOptions, TerminalError, TimeoutError } from "./types/errors.cjs";
|
|
2
2
|
import { Hooks, HooksProvider, Interceptor } from "./hooks.cjs";
|
|
3
3
|
import { Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, InferArg, ObjectHandlerOpts, ObjectOptions, ObjectOpts, Opts, RemoveVoidArgument, RetryPolicy, SendClient, SendClientFromDescriptors, SendOpts, ServiceHandlerOpts, ServiceOptions, ServiceOpts, WorkflowHandlerOpts, WorkflowOptions, WorkflowOpts, handlers, object, rpc, service, workflow } from "./types/rpc.cjs";
|
|
4
|
-
import { Context, ContextDate, DurablePromise, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.cjs";
|
|
4
|
+
import { Context, ContextDate, DurablePromise, EntryOptions, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.cjs";
|
|
5
5
|
import { LogMetadata, LogSource, LoggerContext, LoggerTransport, RestateLogLevel } from "./logging/logger_transport.cjs";
|
|
6
6
|
import { DefaultServiceOptions, RestateEndpoint, RestateEndpointBase } from "./endpoint.cjs";
|
|
7
7
|
import { internal_d_exports } from "./internal.cjs";
|
|
@@ -10,4 +10,4 @@ import { FnOf, ObjectImplHandlers, ObjectPerHandlerOpts, ServiceImplHandlers, Se
|
|
|
10
10
|
import { EndpointOptions } from "./endpoint/types.cjs";
|
|
11
11
|
import { CombineablePromise, Descriptor, DescriptorOpts, Duration, HandlerDescriptor, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferInput, InferOutput, JournalValueCodec, ObjectDescriptor, ObjectHandler, RestateContext, RestateObjectContext, RestateObjectSharedContext, RestateWorkflowContext, RestateWorkflowSharedContext, Serde, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceInterface, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowSharedHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, iface, serde } from "./common_api.cjs";
|
|
12
12
|
import { NodeEndpointOptions, ServeOptions, createEndpointHandler, endpoint, serve } from "./node.cjs";
|
|
13
|
-
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, NodeEndpointOptions, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, ServeOptions, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, serve, service, workflow };
|
|
13
|
+
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, EntryOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, NodeEndpointOptions, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, ServeOptions, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, serve, service, workflow };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { CancelledError, PauseError, RestateError, RetryableError, RetryableErrorOptions, TerminalError, TimeoutError } from "./types/errors.js";
|
|
2
2
|
import { Hooks, HooksProvider, Interceptor } from "./hooks.js";
|
|
3
3
|
import { Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, InferArg, ObjectHandlerOpts, ObjectOptions, ObjectOpts, Opts, RemoveVoidArgument, RetryPolicy, SendClient, SendClientFromDescriptors, SendOpts, ServiceHandlerOpts, ServiceOptions, ServiceOpts, WorkflowHandlerOpts, WorkflowOptions, WorkflowOpts, handlers, object, rpc, service, workflow } from "./types/rpc.js";
|
|
4
|
-
import { Context, ContextDate, DurablePromise, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.js";
|
|
4
|
+
import { Context, ContextDate, DurablePromise, EntryOptions, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request, RestatePromise, RunAction, RunOptions, ScopedContext, SignalReference, Target, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext } from "./context.js";
|
|
5
5
|
import { LogMetadata, LogSource, LoggerContext, LoggerTransport, RestateLogLevel } from "./logging/logger_transport.js";
|
|
6
6
|
import { DefaultServiceOptions, RestateEndpoint, RestateEndpointBase } from "./endpoint.js";
|
|
7
7
|
import { internal_d_exports } from "./internal.js";
|
|
@@ -10,4 +10,4 @@ import { FnOf, ObjectImplHandlers, ObjectPerHandlerOpts, ServiceImplHandlers, Se
|
|
|
10
10
|
import { EndpointOptions } from "./endpoint/types.js";
|
|
11
11
|
import { CombineablePromise, Descriptor, DescriptorOpts, Duration, HandlerDescriptor, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferInput, InferOutput, JournalValueCodec, ObjectDescriptor, ObjectHandler, RestateContext, RestateObjectContext, RestateObjectSharedContext, RestateWorkflowContext, RestateWorkflowSharedContext, Serde, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceInterface, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowSharedHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, iface, serde } from "./common_api.js";
|
|
12
12
|
import { NodeEndpointOptions, ServeOptions, createEndpointHandler, endpoint, serve } from "./node.js";
|
|
13
|
-
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, NodeEndpointOptions, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, ServeOptions, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, serve, service, workflow };
|
|
13
|
+
export { CancelledError, Client, ClientCallOptions, ClientFromDescriptors, ClientSendOptions, CombineablePromise, Context, ContextDate, DefaultServiceOptions, Descriptor, DescriptorOpts, DurablePromise, Duration, EndpointOptions, EntryOptions, FnOf, GenericCall, GenericSend, HandlerDescriptor, Hooks, HooksProvider, ImplementedDefinition, ImplementedObjectDefinition, ImplementedServiceDefinition, ImplementedWorkflowDefinition, InferArg, InferInput, InferOutput, Interceptor, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, InvocationReference, JournalValueCodec, KeyValueStore, LogMetadata, LogSource, LoggerContext, LoggerTransport, NodeEndpointOptions, ObjectContext, ObjectDescriptor, ObjectHandler, ObjectHandlerOpts, ObjectImplHandlers, ObjectOptions, ObjectOpts, ObjectPerHandlerOpts, ObjectSharedContext, Opts, PauseError, Rand, RemoveVoidArgument, Request, RestateContext, RestateEndpoint, RestateEndpointBase, RestateError, RestateLogLevel, RestateObjectContext, RestateObjectSharedContext, RestatePromise, RestateWorkflowContext, RestateWorkflowSharedContext, RetryPolicy, RetryableError, RetryableErrorOptions, RunAction, RunOptions, ScopedContext, SendClient, SendClientFromDescriptors, SendOpts, Serde, ServeOptions, Service, ServiceDefinition, ServiceDefinitionFrom, ServiceDescriptor, ServiceHandler, ServiceHandlerOpts, ServiceImplHandlers, ServiceInterface, ServiceOptions, ServiceOpts, ServicePerHandlerOpts, SignalReference, Target, TerminalError, TimeoutError, TypedState, UntypedState, VirtualObject, VirtualObjectDefinition, VirtualObjectDefinitionFrom, Workflow, WorkflowContext, WorkflowDefinition, WorkflowDefinitionFrom, WorkflowDescriptor, WorkflowHandler, WorkflowHandlerOpts, WorkflowImplHandlers, WorkflowOptions, WorkflowOpts, WorkflowPerHandlerOpts, WorkflowSharedContext, WorkflowSharedHandler, createEndpointHandler, createObjectHandler, createObjectSharedHandler, createServiceHandler, createWorkflowHandler, createWorkflowSharedHandler, endpoint, handlers, iface, implement, internal_d_exports as internal, isRestatePromise, object, rpc, serde, serve, service, workflow };
|
package/dist/internal.cjs
CHANGED
|
@@ -1,8 +1,53 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
const require_errors = require('./types/errors.cjs');
|
|
3
|
+
const require_components = require('./endpoint/components.cjs');
|
|
3
4
|
|
|
4
5
|
//#region src/internal.ts
|
|
5
|
-
var internal_exports = /* @__PURE__ */ require_rolldown_runtime.__export({
|
|
6
|
+
var internal_exports = /* @__PURE__ */ require_rolldown_runtime.__export({
|
|
7
|
+
asInternal: () => asInternal,
|
|
8
|
+
explicitRecovery: () => explicitRecovery,
|
|
9
|
+
isSuspendedError: () => require_errors.isSuspendedError
|
|
10
|
+
});
|
|
11
|
+
/**
|
|
12
|
+
* Run the handlers with explicit recovery: a retried or resumed invocation doesn't replay the journal of its earlier attempts,
|
|
13
|
+
* but runs the handler again from the start, executing every context operation anew, e.g. reading the current state.
|
|
14
|
+
*
|
|
15
|
+
* The handler takes care of recovering from the effects of the earlier attempts, which might repeat (at least once):
|
|
16
|
+
* * Each attempt's calls and sends are new requests. To reach the invocation an earlier attempt started, give it an idempotency key that is the same on every attempt, such as one made from `ctx.request().id`.
|
|
17
|
+
* * `ctx.run` executes its action again on every attempt.
|
|
18
|
+
* * Awakeables are not supported.
|
|
19
|
+
*
|
|
20
|
+
* Spread the returned options into the service or handler options. Handler options take precedence over service options.
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```ts
|
|
24
|
+
* const counter = restate.object({
|
|
25
|
+
* name: "counter",
|
|
26
|
+
* handlers: { ... },
|
|
27
|
+
* options: { ...restate.internal.explicitRecovery() },
|
|
28
|
+
* });
|
|
29
|
+
* ```
|
|
30
|
+
*
|
|
31
|
+
* @experimental
|
|
32
|
+
*/
|
|
33
|
+
function explicitRecovery() {
|
|
34
|
+
return { [require_components.EXPLICIT_RECOVERY]: true };
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Downcast the given context to {@link ContextInternal}, to access the internal APIs.
|
|
38
|
+
*
|
|
39
|
+
* Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* const ctxInternal = restate.internal.asInternal(ctx);
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @experimental
|
|
47
|
+
*/
|
|
48
|
+
function asInternal(ctx) {
|
|
49
|
+
return ctx;
|
|
50
|
+
}
|
|
6
51
|
|
|
7
52
|
//#endregion
|
|
8
53
|
Object.defineProperty(exports, 'internal_exports', {
|