@restatedev/restate-sdk 1.18.3 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context_impl.cjs +31 -11
- package/dist/context_impl.js +31 -11
- package/dist/context_impl.js.map +1 -1
- package/dist/endpoint/components.cjs +3 -11
- package/dist/endpoint/components.js +4 -11
- package/dist/endpoint/components.js.map +1 -1
- package/dist/endpoint/handlers/discovery.cjs +22 -2
- package/dist/endpoint/handlers/discovery.js +22 -2
- package/dist/endpoint/handlers/discovery.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.cjs +3 -4
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js +3 -4
- package/dist/endpoint/handlers/vm/sdk_shared_core_wasm_bindings.js.map +1 -1
- package/dist/endpoint/node_endpoint.cjs +2 -2
- package/dist/endpoint/node_endpoint.js +2 -2
- package/dist/endpoint/node_endpoint.js.map +1 -1
- package/dist/internal.cjs +2 -22
- package/dist/internal.d.cts +63 -29
- package/dist/internal.d.cts.map +1 -1
- package/dist/internal.d.ts +63 -29
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +2 -22
- package/dist/internal.js.map +1 -1
- package/dist/node.cjs +4 -2
- package/dist/node.d.cts +23 -2
- package/dist/node.d.cts.map +1 -1
- package/dist/node.d.ts +23 -2
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +4 -2
- package/dist/node.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/package.js.map +1 -1
- package/dist/types/interface.cjs +11 -1
- package/dist/types/interface.js +11 -1
- package/dist/types/interface.js.map +1 -1
- package/dist/types/rpc.d.cts +18 -0
- package/dist/types/rpc.d.cts.map +1 -1
- package/dist/types/rpc.d.ts +18 -0
- package/dist/types/rpc.d.ts.map +1 -1
- package/dist/types/rpc.js.map +1 -1
- package/package.json +2 -2
|
@@ -44,11 +44,11 @@ var NodeEndpoint = class {
|
|
|
44
44
|
else h1Handler(request, response);
|
|
45
45
|
});
|
|
46
46
|
}
|
|
47
|
-
listen(port) {
|
|
47
|
+
listen(port, options) {
|
|
48
48
|
const endpoint = this.builder.build();
|
|
49
49
|
const actualPort = port ?? parseInt(process.env.PORT ?? "9080");
|
|
50
50
|
endpoint.rlog.info(`Restate SDK started listening on ${actualPort}...`);
|
|
51
|
-
const server = node_http2.createServer(nodeHttp2Handler(endpoint, "BIDI_STREAM"));
|
|
51
|
+
const server = node_http2.createServer(options?.http2Settings ? { settings: options.http2Settings } : {}, nodeHttp2Handler(endpoint, "BIDI_STREAM"));
|
|
52
52
|
return new Promise((resolve, reject) => {
|
|
53
53
|
let failed = false;
|
|
54
54
|
server.once("error", (e) => {
|
|
@@ -42,11 +42,11 @@ var NodeEndpoint = class {
|
|
|
42
42
|
else h1Handler(request, response);
|
|
43
43
|
});
|
|
44
44
|
}
|
|
45
|
-
listen(port) {
|
|
45
|
+
listen(port, options) {
|
|
46
46
|
const endpoint = this.builder.build();
|
|
47
47
|
const actualPort = port ?? parseInt(process.env.PORT ?? "9080");
|
|
48
48
|
endpoint.rlog.info(`Restate SDK started listening on ${actualPort}...`);
|
|
49
|
-
const server = http2.createServer(nodeHttp2Handler(endpoint, "BIDI_STREAM"));
|
|
49
|
+
const server = http2.createServer(options?.http2Settings ? { settings: options.http2Settings } : {}, nodeHttp2Handler(endpoint, "BIDI_STREAM"));
|
|
50
50
|
return new Promise((resolve, reject) => {
|
|
51
51
|
let failed = false;
|
|
52
52
|
server.once("error", (e) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node_endpoint.js","names":[],"sources":["../../src/endpoint/node_endpoint.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport type { RestateEndpoint } from \"../index.js\";\nimport type {\n JournalValueCodec,\n ServiceDefinition,\n VirtualObjectDefinition,\n WorkflowDefinition,\n} from \"@restatedev/restate-sdk-core\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Http2ServerRequest, Http2ServerResponse } from \"node:http2\";\nimport * as http2 from \"node:http2\";\nimport type { Endpoint } from \"./endpoint.js\";\nimport { EndpointBuilder } from \"./endpoint.js\";\nimport { createRestateHandler } from \"./handlers/generic.js\";\nimport { ensureError } from \"../types/errors.js\";\nimport type { LoggerTransport } from \"../logging/logger_transport.js\";\nimport type { DefaultServiceOptions } from \"../endpoint.js\";\nimport { tryCreateContextualLogger } from \"./handlers/utils.js\";\nimport type { InputReader, OutputWriter } from \"./handlers/types.js\";\nimport type { ProtocolMode } from \"./discovery.js\";\n\nexport class NodeEndpoint implements RestateEndpoint {\n private builder: EndpointBuilder = new EndpointBuilder();\n\n public bind<P extends string, M>(\n definition:\n | ServiceDefinition<P, M>\n | VirtualObjectDefinition<P, M>\n | WorkflowDefinition<P, M>\n ): RestateEndpoint {\n this.builder.bind(definition);\n return this;\n }\n\n public withIdentityV1(...keys: string[]): RestateEndpoint {\n this.builder.addIdentityKeys(...keys);\n return this;\n }\n\n public defaultServiceOptions(\n options: DefaultServiceOptions\n ): RestateEndpoint {\n this.builder.setDefaultServiceOptions(options);\n return this;\n }\n\n public setLogger(logger: LoggerTransport): RestateEndpoint {\n this.builder.setLogger(logger);\n return this;\n }\n\n public journalValueCodecProvider(\n codecProvider: () => Promise<JournalValueCodec>\n ): RestateEndpoint {\n this.builder.setJournalValueCodecProvider(codecProvider);\n return this;\n }\n\n http2Handler(options?: {\n bidirectional?: boolean;\n }): (request: Http2ServerRequest, response: Http2ServerResponse) => void {\n return nodeHttp2Handler(\n this.builder.build(),\n options?.bidirectional === false ? \"REQUEST_RESPONSE\" : \"BIDI_STREAM\"\n );\n }\n\n http1Handler(options?: {\n bidirectional?: boolean;\n }): (request: IncomingMessage, response: ServerResponse) => void {\n return nodeHttp1Handler(\n this.builder.build(),\n options?.bidirectional ? \"BIDI_STREAM\" : \"REQUEST_RESPONSE\"\n );\n }\n\n handler(options?: { bidirectional?: boolean }): {\n (request: IncomingMessage, response: ServerResponse): void;\n (request: Http2ServerRequest, response: Http2ServerResponse): void;\n } {\n const endpoint = this.builder.build();\n const h2Handler = nodeHttp2Handler(\n endpoint,\n options?.bidirectional === false ? \"REQUEST_RESPONSE\" : \"BIDI_STREAM\"\n );\n const h1Handler = nodeHttp1Handler(\n endpoint,\n options?.bidirectional ? \"BIDI_STREAM\" : \"REQUEST_RESPONSE\"\n );\n\n return ((\n request: IncomingMessage | Http2ServerRequest,\n response: ServerResponse | Http2ServerResponse\n ) => {\n if (request.httpVersionMajor >= 2) {\n h2Handler(\n request as Http2ServerRequest,\n response as Http2ServerResponse\n );\n } else {\n h1Handler(request as IncomingMessage, response as ServerResponse);\n }\n }) as {\n (request: IncomingMessage, response: ServerResponse): void;\n (request: Http2ServerRequest, response: Http2ServerResponse): void;\n };\n }\n\n listen(port?: number): Promise<number> {\n const endpoint = this.builder.build();\n\n const actualPort = port ?? parseInt(process.env.PORT ?? \"9080\");\n endpoint.rlog.info(`Restate SDK started listening on ${actualPort}...`);\n\n const server = http2.createServer(\n nodeHttp2Handler(endpoint, \"BIDI_STREAM\")\n );\n\n return new Promise((resolve, reject) => {\n let failed = false;\n server.once(\"error\", (e: Error) => {\n failed = true;\n reject(e);\n });\n server.listen(actualPort, () => {\n if (failed) {\n return;\n }\n const address = server.address();\n if (address === null || typeof address === \"string\") {\n reject(\n new TypeError(\n \"endpoint.listen() currently supports only binding to a PORT\"\n )\n );\n } else {\n resolve(address.port);\n }\n });\n });\n }\n}\n\nfunction nodeHttp1Handler(\n endpoint: Endpoint,\n protocolMode: ProtocolMode\n): (request: IncomingMessage, response: ServerResponse) => void {\n return nodeHandlerImpl(endpoint, protocolMode);\n}\n\nfunction nodeHttp2Handler(\n endpoint: Endpoint,\n protocolMode: ProtocolMode\n): (request: Http2ServerRequest, response: Http2ServerResponse) => void {\n return nodeHandlerImpl(endpoint, protocolMode);\n}\n\nfunction nodeHandlerImpl(\n endpoint: Endpoint,\n protocolMode: ProtocolMode\n): (\n request: Http2ServerRequest | IncomingMessage,\n response: Http2ServerResponse | ServerResponse\n) => void {\n const handler = createRestateHandler(endpoint, protocolMode, {});\n\n return (httpRequest, httpResponse) => {\n const url = httpRequest.url!;\n const inputReader = inputReaderAdapter(httpRequest);\n const outputWriter = outputWriterAdapter(httpResponse);\n const res = httpResponse as NodeWritableResponse;\n\n // Abort controller used to clean up resources at the end of this attempt.\n const abortController = new AbortController();\n const abort = () => abortController.abort();\n\n // WARNING: DON'T TOUCH THIS UNLESS YOU REALLY KNOW WHAT YOU'RE DOING\n //\n // HTTP/1 has separate request and response lifecycles:\n // request body ends -> request closes -> handler finishes -> response closes.\n // The request can therefore close while the attempt is still running. The\n // response closes when the response completes or the connection is lost.\n //\n // In HTTP/2, the request and response share one stream:\n // request body ends -> handler finishes -> stream closes -> request closes.\n // Request close therefore covers both stream completion and reset.\n if (httpRequest.httpVersionMajor >= 2) {\n httpRequest.once(\"close\", abort);\n } else {\n httpResponse.once(\"close\", abort);\n }\n\n const writeHead = res.writeHead.bind(res);\n\n // handle should never throw\n const restateResponse = handler.handle({\n url,\n headers: httpRequest.headers,\n extraArgs: [],\n });\n\n restateResponse\n .process({\n inputReader,\n outputWriter,\n writeHead,\n abortSignal: abortController.signal,\n })\n .catch((e) => {\n // Responses handle their own errors before rejecting; anything\n // reaching here is an unexpected failure — just log.\n const error = ensureError(e);\n const logger =\n tryCreateContextualLogger(\n endpoint.loggerTransport,\n url,\n httpRequest.headers\n ) ?? endpoint.rlog;\n logger.error(\"Unexpected error: \" + (error.stack ?? error.message));\n });\n };\n}\n\n// Both ServerResponse and Http2ServerResponse satisfy this interface.\n// We use it to avoid TS union overload incompatibilities.\ninterface NodeWritableResponse {\n writeHead(statusCode: number, headers: Record<string, string>): void;\n write(chunk: Uint8Array, callback: (err?: Error | null) => void): boolean;\n end(callback: () => void): void;\n}\n\nfunction inputReaderAdapter(\n request: Http2ServerRequest | IncomingMessage\n): InputReader {\n return (request as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]();\n}\n\nfunction outputWriterAdapter(\n response: Http2ServerResponse | ServerResponse\n): OutputWriter {\n const res = response as NodeWritableResponse;\n return {\n write: function (value: Uint8Array): Promise<void> {\n return new Promise((resolve, reject) => {\n res.write(value, (err) => (err ? reject(err) : resolve()));\n });\n },\n close: function (): Promise<void> {\n return new Promise((resolve) => {\n res.end(() => resolve());\n });\n },\n };\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"node_endpoint.js","names":[],"sources":["../../src/endpoint/node_endpoint.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\nimport type { RestateEndpoint } from \"../index.js\";\nimport type {\n JournalValueCodec,\n ServiceDefinition,\n VirtualObjectDefinition,\n WorkflowDefinition,\n} from \"@restatedev/restate-sdk-core\";\nimport { IncomingMessage, ServerResponse } from \"node:http\";\nimport { Http2ServerRequest, Http2ServerResponse } from \"node:http2\";\nimport * as http2 from \"node:http2\";\nimport type { Endpoint } from \"./endpoint.js\";\nimport { EndpointBuilder } from \"./endpoint.js\";\nimport { createRestateHandler } from \"./handlers/generic.js\";\nimport { ensureError } from \"../types/errors.js\";\nimport type { LoggerTransport } from \"../logging/logger_transport.js\";\nimport type { DefaultServiceOptions } from \"../endpoint.js\";\nimport { tryCreateContextualLogger } from \"./handlers/utils.js\";\nimport type { InputReader, OutputWriter } from \"./handlers/types.js\";\nimport type { ProtocolMode } from \"./discovery.js\";\n\nexport interface NodeListenOptions {\n /** HTTP/2 settings of the server. Defaults to Node's defaults. */\n http2Settings?: http2.Settings;\n}\n\nexport class NodeEndpoint implements RestateEndpoint {\n private builder: EndpointBuilder = new EndpointBuilder();\n\n public bind<P extends string, M>(\n definition:\n | ServiceDefinition<P, M>\n | VirtualObjectDefinition<P, M>\n | WorkflowDefinition<P, M>\n ): RestateEndpoint {\n this.builder.bind(definition);\n return this;\n }\n\n public withIdentityV1(...keys: string[]): RestateEndpoint {\n this.builder.addIdentityKeys(...keys);\n return this;\n }\n\n public defaultServiceOptions(\n options: DefaultServiceOptions\n ): RestateEndpoint {\n this.builder.setDefaultServiceOptions(options);\n return this;\n }\n\n public setLogger(logger: LoggerTransport): RestateEndpoint {\n this.builder.setLogger(logger);\n return this;\n }\n\n public journalValueCodecProvider(\n codecProvider: () => Promise<JournalValueCodec>\n ): RestateEndpoint {\n this.builder.setJournalValueCodecProvider(codecProvider);\n return this;\n }\n\n http2Handler(options?: {\n bidirectional?: boolean;\n }): (request: Http2ServerRequest, response: Http2ServerResponse) => void {\n return nodeHttp2Handler(\n this.builder.build(),\n options?.bidirectional === false ? \"REQUEST_RESPONSE\" : \"BIDI_STREAM\"\n );\n }\n\n http1Handler(options?: {\n bidirectional?: boolean;\n }): (request: IncomingMessage, response: ServerResponse) => void {\n return nodeHttp1Handler(\n this.builder.build(),\n options?.bidirectional ? \"BIDI_STREAM\" : \"REQUEST_RESPONSE\"\n );\n }\n\n handler(options?: { bidirectional?: boolean }): {\n (request: IncomingMessage, response: ServerResponse): void;\n (request: Http2ServerRequest, response: Http2ServerResponse): void;\n } {\n const endpoint = this.builder.build();\n const h2Handler = nodeHttp2Handler(\n endpoint,\n options?.bidirectional === false ? \"REQUEST_RESPONSE\" : \"BIDI_STREAM\"\n );\n const h1Handler = nodeHttp1Handler(\n endpoint,\n options?.bidirectional ? \"BIDI_STREAM\" : \"REQUEST_RESPONSE\"\n );\n\n return ((\n request: IncomingMessage | Http2ServerRequest,\n response: ServerResponse | Http2ServerResponse\n ) => {\n if (request.httpVersionMajor >= 2) {\n h2Handler(\n request as Http2ServerRequest,\n response as Http2ServerResponse\n );\n } else {\n h1Handler(request as IncomingMessage, response as ServerResponse);\n }\n }) as {\n (request: IncomingMessage, response: ServerResponse): void;\n (request: Http2ServerRequest, response: Http2ServerResponse): void;\n };\n }\n\n listen(port?: number, options?: NodeListenOptions): Promise<number> {\n const endpoint = this.builder.build();\n\n const actualPort = port ?? parseInt(process.env.PORT ?? \"9080\");\n endpoint.rlog.info(`Restate SDK started listening on ${actualPort}...`);\n\n const server = http2.createServer(\n options?.http2Settings ? { settings: options.http2Settings } : {},\n nodeHttp2Handler(endpoint, \"BIDI_STREAM\")\n );\n\n return new Promise((resolve, reject) => {\n let failed = false;\n server.once(\"error\", (e: Error) => {\n failed = true;\n reject(e);\n });\n server.listen(actualPort, () => {\n if (failed) {\n return;\n }\n const address = server.address();\n if (address === null || typeof address === \"string\") {\n reject(\n new TypeError(\n \"endpoint.listen() currently supports only binding to a PORT\"\n )\n );\n } else {\n resolve(address.port);\n }\n });\n });\n }\n}\n\nfunction nodeHttp1Handler(\n endpoint: Endpoint,\n protocolMode: ProtocolMode\n): (request: IncomingMessage, response: ServerResponse) => void {\n return nodeHandlerImpl(endpoint, protocolMode);\n}\n\nfunction nodeHttp2Handler(\n endpoint: Endpoint,\n protocolMode: ProtocolMode\n): (request: Http2ServerRequest, response: Http2ServerResponse) => void {\n return nodeHandlerImpl(endpoint, protocolMode);\n}\n\nfunction nodeHandlerImpl(\n endpoint: Endpoint,\n protocolMode: ProtocolMode\n): (\n request: Http2ServerRequest | IncomingMessage,\n response: Http2ServerResponse | ServerResponse\n) => void {\n const handler = createRestateHandler(endpoint, protocolMode, {});\n\n return (httpRequest, httpResponse) => {\n const url = httpRequest.url!;\n const inputReader = inputReaderAdapter(httpRequest);\n const outputWriter = outputWriterAdapter(httpResponse);\n const res = httpResponse as NodeWritableResponse;\n\n // Abort controller used to clean up resources at the end of this attempt.\n const abortController = new AbortController();\n const abort = () => abortController.abort();\n\n // WARNING: DON'T TOUCH THIS UNLESS YOU REALLY KNOW WHAT YOU'RE DOING\n //\n // HTTP/1 has separate request and response lifecycles:\n // request body ends -> request closes -> handler finishes -> response closes.\n // The request can therefore close while the attempt is still running. The\n // response closes when the response completes or the connection is lost.\n //\n // In HTTP/2, the request and response share one stream:\n // request body ends -> handler finishes -> stream closes -> request closes.\n // Request close therefore covers both stream completion and reset.\n if (httpRequest.httpVersionMajor >= 2) {\n httpRequest.once(\"close\", abort);\n } else {\n httpResponse.once(\"close\", abort);\n }\n\n const writeHead = res.writeHead.bind(res);\n\n // handle should never throw\n const restateResponse = handler.handle({\n url,\n headers: httpRequest.headers,\n extraArgs: [],\n });\n\n restateResponse\n .process({\n inputReader,\n outputWriter,\n writeHead,\n abortSignal: abortController.signal,\n })\n .catch((e) => {\n // Responses handle their own errors before rejecting; anything\n // reaching here is an unexpected failure — just log.\n const error = ensureError(e);\n const logger =\n tryCreateContextualLogger(\n endpoint.loggerTransport,\n url,\n httpRequest.headers\n ) ?? endpoint.rlog;\n logger.error(\"Unexpected error: \" + (error.stack ?? error.message));\n });\n };\n}\n\n// Both ServerResponse and Http2ServerResponse satisfy this interface.\n// We use it to avoid TS union overload incompatibilities.\ninterface NodeWritableResponse {\n writeHead(statusCode: number, headers: Record<string, string>): void;\n write(chunk: Uint8Array, callback: (err?: Error | null) => void): boolean;\n end(callback: () => void): void;\n}\n\nfunction inputReaderAdapter(\n request: Http2ServerRequest | IncomingMessage\n): InputReader {\n return (request as AsyncIterable<Uint8Array>)[Symbol.asyncIterator]();\n}\n\nfunction outputWriterAdapter(\n response: Http2ServerResponse | ServerResponse\n): OutputWriter {\n const res = response as NodeWritableResponse;\n return {\n write: function (value: Uint8Array): Promise<void> {\n return new Promise((resolve, reject) => {\n res.write(value, (err) => (err ? reject(err) : resolve()));\n });\n },\n close: function (): Promise<void> {\n return new Promise((resolve) => {\n res.end(() => resolve());\n });\n },\n };\n}\n"],"mappings":"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"}
|
package/dist/internal.cjs
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
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');
|
|
4
3
|
|
|
5
4
|
//#region src/internal.ts
|
|
6
5
|
var internal_exports = /* @__PURE__ */ require_rolldown_runtime.__export({
|
|
@@ -9,29 +8,10 @@ var internal_exports = /* @__PURE__ */ require_rolldown_runtime.__export({
|
|
|
9
8
|
isSuspendedError: () => require_errors.isSuspendedError
|
|
10
9
|
});
|
|
11
10
|
/**
|
|
12
|
-
*
|
|
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
|
|
11
|
+
* @deprecated Use `@restatedev/sdk-sessions` npm package instead.
|
|
32
12
|
*/
|
|
33
13
|
function explicitRecovery() {
|
|
34
|
-
return {
|
|
14
|
+
return {};
|
|
35
15
|
}
|
|
36
16
|
/**
|
|
37
17
|
* Downcast the given context to {@link ContextInternal}, to access the internal APIs.
|
package/dist/internal.d.cts
CHANGED
|
@@ -1,40 +1,15 @@
|
|
|
1
|
-
import { isSuspendedError } from "./types/errors.cjs";
|
|
1
|
+
import { TerminalError, isSuspendedError } from "./types/errors.cjs";
|
|
2
2
|
import { Context, InvocationId, RestatePromise } from "./context.cjs";
|
|
3
3
|
import { Serde } from "@restatedev/restate-sdk-core";
|
|
4
4
|
|
|
5
5
|
//#region src/internal.d.ts
|
|
6
6
|
declare namespace internal_d_exports {
|
|
7
|
-
export { ContextInternal,
|
|
7
|
+
export { ContextInternal, GetProjectOptions, InvocationOutput, asInternal, explicitRecovery, isSuspendedError };
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* @experimental
|
|
13
|
-
*/
|
|
14
|
-
type ExplicitRecoveryOptions = Record<never, never>;
|
|
15
|
-
/**
|
|
16
|
-
* Run the handlers with explicit recovery: a retried or resumed invocation doesn't replay the journal of its earlier attempts,
|
|
17
|
-
* but runs the handler again from the start, executing every context operation anew, e.g. reading the current state.
|
|
18
|
-
*
|
|
19
|
-
* The handler takes care of recovering from the effects of the earlier attempts, which might repeat (at least once):
|
|
20
|
-
* * 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`.
|
|
21
|
-
* * `ctx.run` executes its action again on every attempt.
|
|
22
|
-
* * Awakeables are not supported.
|
|
23
|
-
*
|
|
24
|
-
* Spread the returned options into the service or handler options. Handler options take precedence over service options.
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```ts
|
|
28
|
-
* const counter = restate.object({
|
|
29
|
-
* name: "counter",
|
|
30
|
-
* handlers: { ... },
|
|
31
|
-
* options: { ...restate.internal.explicitRecovery() },
|
|
32
|
-
* });
|
|
33
|
-
* ```
|
|
34
|
-
*
|
|
35
|
-
* @experimental
|
|
10
|
+
* @deprecated Use `@restatedev/sdk-sessions` npm package instead.
|
|
36
11
|
*/
|
|
37
|
-
declare function explicitRecovery():
|
|
12
|
+
declare function explicitRecovery(): Record<never, never>;
|
|
38
13
|
/**
|
|
39
14
|
* Downcast the given context to {@link ContextInternal}, to access the internal APIs.
|
|
40
15
|
*
|
|
@@ -192,7 +167,66 @@ interface ContextInternal extends Context {
|
|
|
192
167
|
* @experimental
|
|
193
168
|
*/
|
|
194
169
|
getProject<TValue, TResult>(name: string, projection: (value: TValue | null) => TResult | Promise<TResult>, options?: GetProjectOptions<TValue, TResult>): RestatePromise<TResult>;
|
|
170
|
+
/**
|
|
171
|
+
* Get the output of the target invocation, **without waiting** for it to complete.
|
|
172
|
+
*
|
|
173
|
+
* Unlike `ctx.invocation(invocationId).attach()`, which waits until the target invocation completes,
|
|
174
|
+
* this returns immediately with an {@link InvocationOutput}:
|
|
175
|
+
* * `{ status: "running" }`: the target invocation has not completed yet.
|
|
176
|
+
* * `{ status: "success", value }`: the target invocation completed successfully, with the given output value.
|
|
177
|
+
* * `{ status: "failure", error }`: the target invocation completed with a failure.
|
|
178
|
+
* Note that the returned promise **does not** reject in this case.
|
|
179
|
+
*
|
|
180
|
+
* **Unknown invocations:** if the target invocation doesn't exist, or its result is no longer retained,
|
|
181
|
+
* the result is `{ status: "failure" }` with an `error` having code `404` and message `"not found"`.
|
|
182
|
+
*
|
|
183
|
+
* The result is recorded in the journal: on replay you get the same result as in the original execution,
|
|
184
|
+
* even if in the meantime the target invocation completed.
|
|
185
|
+
*
|
|
186
|
+
* @param invocationId the invocation ID of the target invocation.
|
|
187
|
+
* @param serde optional custom serializer/deserializer for the output value.
|
|
188
|
+
* @returns a {@link RestatePromise} resolved with the {@link InvocationOutput} of the target invocation.
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```ts
|
|
192
|
+
* const ctxInternal = restate.internal.asInternal(ctx);
|
|
193
|
+
* const output = await ctxInternal.getInvocationOutput<string>(invocationId);
|
|
194
|
+
* switch (output.status) {
|
|
195
|
+
* case "running":
|
|
196
|
+
* ctx.console.log("Still running");
|
|
197
|
+
* break;
|
|
198
|
+
* case "success":
|
|
199
|
+
* ctx.console.log("Completed with", output.value);
|
|
200
|
+
* break;
|
|
201
|
+
* case "failure":
|
|
202
|
+
* ctx.console.log("Failed with", output.error.message);
|
|
203
|
+
* break;
|
|
204
|
+
* }
|
|
205
|
+
* ```
|
|
206
|
+
*
|
|
207
|
+
* @experimental
|
|
208
|
+
*/
|
|
209
|
+
getInvocationOutput<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<InvocationOutput<T>>;
|
|
195
210
|
}
|
|
211
|
+
/**
|
|
212
|
+
* Output of a target invocation, returned by {@link ContextInternal.getInvocationOutput}.
|
|
213
|
+
*
|
|
214
|
+
* Use the `status` field to tell the cases apart:
|
|
215
|
+
* * `running`: the target invocation has not completed yet.
|
|
216
|
+
* * `success`: the target invocation completed successfully, `value` contains its output.
|
|
217
|
+
* * `failure`: the target invocation completed with a failure, `error` contains the failure.
|
|
218
|
+
*
|
|
219
|
+
* @experimental
|
|
220
|
+
*/
|
|
221
|
+
type InvocationOutput<T> = {
|
|
222
|
+
status: "running";
|
|
223
|
+
} | {
|
|
224
|
+
status: "success";
|
|
225
|
+
value: T;
|
|
226
|
+
} | {
|
|
227
|
+
status: "failure";
|
|
228
|
+
error: TerminalError;
|
|
229
|
+
};
|
|
196
230
|
/**
|
|
197
231
|
* Options for {@link ContextInternal.getProject}.
|
|
198
232
|
*
|
package/dist/internal.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.d.cts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"internal.d.cts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;iBASgB,gBAAA,CAAA,GAAoB;;;;;;;AAApC;AAgBA;AAWA;;;;AA6IwB,iBAxJR,UAAA,CAwJQ,GAAA,EAxJQ,OAwJR,CAAA,EAxJkB,eAwJlB;;;;;;;;AAEnB,UA/IY,eAAA,SAAwB,OA+IpC,CAAA;EA0Ca;;;;;;;;EAeN,YAAA,EAAA,EAAA,OAAgB;EAUhB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAlHM;;;;;;;;;;yBAWO,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gEAkChB,kBAAkB,UAAU,QAAQ,oBAC9C,kBAAkB,QAAQ,WACnC,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uCA0CF,sBACN,MAAM,KACb,eAAe,iBAAiB;;;;;;;;;;;;KAazB;;;;SAEoB;;;SACA;;;;;;;KAOpB;;;;UAIF,MAAM;;;;;;;gBAQA,MAAM"}
|
package/dist/internal.d.ts
CHANGED
|
@@ -1,40 +1,15 @@
|
|
|
1
|
-
import { isSuspendedError } from "./types/errors.js";
|
|
1
|
+
import { TerminalError, isSuspendedError } from "./types/errors.js";
|
|
2
2
|
import { Context, InvocationId, RestatePromise } from "./context.js";
|
|
3
3
|
import { Serde } from "@restatedev/restate-sdk-core";
|
|
4
4
|
|
|
5
5
|
//#region src/internal.d.ts
|
|
6
6
|
declare namespace internal_d_exports {
|
|
7
|
-
export { ContextInternal,
|
|
7
|
+
export { ContextInternal, GetProjectOptions, InvocationOutput, asInternal, explicitRecovery, isSuspendedError };
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* @experimental
|
|
13
|
-
*/
|
|
14
|
-
type ExplicitRecoveryOptions = Record<never, never>;
|
|
15
|
-
/**
|
|
16
|
-
* Run the handlers with explicit recovery: a retried or resumed invocation doesn't replay the journal of its earlier attempts,
|
|
17
|
-
* but runs the handler again from the start, executing every context operation anew, e.g. reading the current state.
|
|
18
|
-
*
|
|
19
|
-
* The handler takes care of recovering from the effects of the earlier attempts, which might repeat (at least once):
|
|
20
|
-
* * 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`.
|
|
21
|
-
* * `ctx.run` executes its action again on every attempt.
|
|
22
|
-
* * Awakeables are not supported.
|
|
23
|
-
*
|
|
24
|
-
* Spread the returned options into the service or handler options. Handler options take precedence over service options.
|
|
25
|
-
*
|
|
26
|
-
* @example
|
|
27
|
-
* ```ts
|
|
28
|
-
* const counter = restate.object({
|
|
29
|
-
* name: "counter",
|
|
30
|
-
* handlers: { ... },
|
|
31
|
-
* options: { ...restate.internal.explicitRecovery() },
|
|
32
|
-
* });
|
|
33
|
-
* ```
|
|
34
|
-
*
|
|
35
|
-
* @experimental
|
|
10
|
+
* @deprecated Use `@restatedev/sdk-sessions` npm package instead.
|
|
36
11
|
*/
|
|
37
|
-
declare function explicitRecovery():
|
|
12
|
+
declare function explicitRecovery(): Record<never, never>;
|
|
38
13
|
/**
|
|
39
14
|
* Downcast the given context to {@link ContextInternal}, to access the internal APIs.
|
|
40
15
|
*
|
|
@@ -192,7 +167,66 @@ interface ContextInternal extends Context {
|
|
|
192
167
|
* @experimental
|
|
193
168
|
*/
|
|
194
169
|
getProject<TValue, TResult>(name: string, projection: (value: TValue | null) => TResult | Promise<TResult>, options?: GetProjectOptions<TValue, TResult>): RestatePromise<TResult>;
|
|
170
|
+
/**
|
|
171
|
+
* Get the output of the target invocation, **without waiting** for it to complete.
|
|
172
|
+
*
|
|
173
|
+
* Unlike `ctx.invocation(invocationId).attach()`, which waits until the target invocation completes,
|
|
174
|
+
* this returns immediately with an {@link InvocationOutput}:
|
|
175
|
+
* * `{ status: "running" }`: the target invocation has not completed yet.
|
|
176
|
+
* * `{ status: "success", value }`: the target invocation completed successfully, with the given output value.
|
|
177
|
+
* * `{ status: "failure", error }`: the target invocation completed with a failure.
|
|
178
|
+
* Note that the returned promise **does not** reject in this case.
|
|
179
|
+
*
|
|
180
|
+
* **Unknown invocations:** if the target invocation doesn't exist, or its result is no longer retained,
|
|
181
|
+
* the result is `{ status: "failure" }` with an `error` having code `404` and message `"not found"`.
|
|
182
|
+
*
|
|
183
|
+
* The result is recorded in the journal: on replay you get the same result as in the original execution,
|
|
184
|
+
* even if in the meantime the target invocation completed.
|
|
185
|
+
*
|
|
186
|
+
* @param invocationId the invocation ID of the target invocation.
|
|
187
|
+
* @param serde optional custom serializer/deserializer for the output value.
|
|
188
|
+
* @returns a {@link RestatePromise} resolved with the {@link InvocationOutput} of the target invocation.
|
|
189
|
+
*
|
|
190
|
+
* @example
|
|
191
|
+
* ```ts
|
|
192
|
+
* const ctxInternal = restate.internal.asInternal(ctx);
|
|
193
|
+
* const output = await ctxInternal.getInvocationOutput<string>(invocationId);
|
|
194
|
+
* switch (output.status) {
|
|
195
|
+
* case "running":
|
|
196
|
+
* ctx.console.log("Still running");
|
|
197
|
+
* break;
|
|
198
|
+
* case "success":
|
|
199
|
+
* ctx.console.log("Completed with", output.value);
|
|
200
|
+
* break;
|
|
201
|
+
* case "failure":
|
|
202
|
+
* ctx.console.log("Failed with", output.error.message);
|
|
203
|
+
* break;
|
|
204
|
+
* }
|
|
205
|
+
* ```
|
|
206
|
+
*
|
|
207
|
+
* @experimental
|
|
208
|
+
*/
|
|
209
|
+
getInvocationOutput<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<InvocationOutput<T>>;
|
|
195
210
|
}
|
|
211
|
+
/**
|
|
212
|
+
* Output of a target invocation, returned by {@link ContextInternal.getInvocationOutput}.
|
|
213
|
+
*
|
|
214
|
+
* Use the `status` field to tell the cases apart:
|
|
215
|
+
* * `running`: the target invocation has not completed yet.
|
|
216
|
+
* * `success`: the target invocation completed successfully, `value` contains its output.
|
|
217
|
+
* * `failure`: the target invocation completed with a failure, `error` contains the failure.
|
|
218
|
+
*
|
|
219
|
+
* @experimental
|
|
220
|
+
*/
|
|
221
|
+
type InvocationOutput<T> = {
|
|
222
|
+
status: "running";
|
|
223
|
+
} | {
|
|
224
|
+
status: "success";
|
|
225
|
+
value: T;
|
|
226
|
+
} | {
|
|
227
|
+
status: "failure";
|
|
228
|
+
error: TerminalError;
|
|
229
|
+
};
|
|
196
230
|
/**
|
|
197
231
|
* Options for {@link ContextInternal.getProject}.
|
|
198
232
|
*
|
package/dist/internal.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.d.ts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"internal.d.ts","names":[],"sources":["../src/internal.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;iBASgB,gBAAA,CAAA,GAAoB;;;;;;;AAApC;AAgBA;AAWA;;;;AA6IwB,iBAxJR,UAAA,CAwJQ,GAAA,EAxJQ,OAwJR,CAAA,EAxJkB,eAwJlB;;;;;;;;AAEnB,UA/IY,eAAA,SAAwB,OA+IpC,CAAA;EA0Ca;;;;;;;;EAeN,YAAA,EAAA,EAAA,OAAgB;EAUhB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAlHM;;;;;;;;;;yBAWO,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gEAkChB,kBAAkB,UAAU,QAAQ,oBAC9C,kBAAkB,QAAQ,WACnC,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uCA0CF,sBACN,MAAM,KACb,eAAe,iBAAiB;;;;;;;;;;;;KAazB;;;;SAEoB;;;SACA;;;;;;;KAOpB;;;;UAIF,MAAM;;;;;;;gBAQA,MAAM"}
|
package/dist/internal.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { __export } from "./_virtual/rolldown_runtime.js";
|
|
2
2
|
import { isSuspendedError } from "./types/errors.js";
|
|
3
|
-
import { EXPLICIT_RECOVERY } from "./endpoint/components.js";
|
|
4
3
|
|
|
5
4
|
//#region src/internal.ts
|
|
6
5
|
var internal_exports = /* @__PURE__ */ __export({
|
|
@@ -9,29 +8,10 @@ var internal_exports = /* @__PURE__ */ __export({
|
|
|
9
8
|
isSuspendedError: () => isSuspendedError
|
|
10
9
|
});
|
|
11
10
|
/**
|
|
12
|
-
*
|
|
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
|
|
11
|
+
* @deprecated Use `@restatedev/sdk-sessions` npm package instead.
|
|
32
12
|
*/
|
|
33
13
|
function explicitRecovery() {
|
|
34
|
-
return {
|
|
14
|
+
return {};
|
|
35
15
|
}
|
|
36
16
|
/**
|
|
37
17
|
* Downcast the given context to {@link ContextInternal}, to access the internal APIs.
|
package/dist/internal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import { Context, InvocationId, RestatePromise } from \"./context.js\";\nimport type { Serde } from \"@restatedev/restate-sdk-core\";\nimport { EXPLICIT_RECOVERY } from \"./endpoint/components.js\";\n\nexport { isSuspendedError } from \"./types/errors.js\";\n\n/**\n * Options set by {@link explicitRecovery}, to spread into the options of a service, virtual object, workflow or handler.\n *\n * @experimental\n */\nexport type ExplicitRecoveryOptions = Record<never, never>;\n\n/**\n * Run the handlers with explicit recovery: a retried or resumed invocation doesn't replay the journal of its earlier attempts,\n * but runs the handler again from the start, executing every context operation anew, e.g. reading the current state.\n *\n * The handler takes care of recovering from the effects of the earlier attempts, which might repeat (at least once):\n * * 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`.\n * * `ctx.run` executes its action again on every attempt.\n * * Awakeables are not supported.\n *\n * Spread the returned options into the service or handler options. Handler options take precedence over service options.\n *\n * @example\n * ```ts\n * const counter = restate.object({\n * name: \"counter\",\n * handlers: { ... },\n * options: { ...restate.internal.explicitRecovery() },\n * });\n * ```\n *\n * @experimental\n */\nexport function explicitRecovery(): ExplicitRecoveryOptions {\n const options = { [EXPLICIT_RECOVERY]: true };\n return options;\n}\n\n/**\n * Downcast the given context to {@link ContextInternal}, to access the internal APIs.\n *\n * Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.\n *\n * @example\n * ```ts\n * const ctxInternal = restate.internal.asInternal(ctx);\n * ```\n *\n * @experimental\n */\nexport function asInternal(ctx: Context): ContextInternal {\n return ctx as ContextInternal;\n}\n\n/**\n * Internal {@link Context} interface exposing additional features.\n *\n * Please note that this API is to be considered experimental and might change without notice.\n *\n * @experimental\n */\nexport interface ContextInternal extends Context {\n /**\n * Returns true if the handler is in the processing phase.\n * This is the mechanism used by `ctx.console` to distinguish whether we should log or not in replaying/processing.\n *\n * **WARNING**: This method should not be used to influence control flow, as it will **surely** lead to non-determinism errors!\n *\n * @experimental\n */\n isProcessing(): boolean;\n\n /**\n * Returns a {@link RestatePromise} that resolves with `undefined` when Restate signals cancellation\n * of the current invocation.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, cancellations are propagated automatically,\n * and this promise will **NEVER** resolve.\n *\n * **Promise reuse:** calling this method multiple times returns the **same** promise instance as long as\n * the current cancellation signal has not yet arrived. Once the promise resolves (cancellation received),\n * later calls return a **new** promise that will resolve on the next cancellation signal.\n *\n * @example Race a long-running side effect against cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const result = await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * return result;\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Use the cancellation promise to create an AbortSignal for ctx.run\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const controller = new AbortController();\n * const cancellation = ctxInternal.cancellation()\n * .map(() => {\n * controller.abort();\n * throw new restate.TerminalError(\"Cancelled\");\n * });\n *\n * return RestatePromise.race([\n * ctx.run(() => fetch(`https://api.example.com/greet/${name}`, { signal: controller.signal })),\n * cancellation,\n * ]);\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Handle cancellation, perform cleanup, then listen for the next cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * try {\n * return await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * } catch (e) {\n * // Perform cleanup\n * await ctx.run(() => cleanupResources(name));\n *\n * // After cancellation is resolved, ctx.cancellation() returns a fresh promise.\n * // Race cleanup confirmation against the next cancellation signal.\n * await RestatePromise.race([\n * ctx.run(() => confirmCleanup(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Canceled during cleanup\") }),\n * ]);\n * }\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @experimental\n */\n cancellation(): RestatePromise<void>;\n\n /**\n * Cancel all previous calls made from this handler.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, this operation will always be a no-op.\n *\n * @return the invocation id of the canceled calls.\n * @experimental\n */\n cancelPreviousCalls(): RestatePromise<InvocationId[]>;\n\n /**\n * Get state from the Restate runtime, apply the given `projection` to it,\n * and record in the journal only the result of the projection.\n *\n * Use this to read big state values when you need only a small part of them:\n * unlike `ctx.get`, the complete state value is not recorded in the journal,\n * only its projection.\n *\n * It will appear in the UI as run(project:state_key).\n *\n * This method **MUST** only be used within Virtual Object and Workflow handlers.\n *\n * **NOTE:** Requires Restate >= 1.8 with service protocol V8 enabled, and **does not** work with request/response protocol mode (e.g. with AWS Lambda).\n *\n * @param name key of the state to retrieve\n * @param projection function receiving the state value, or `null` if the state is empty.\n * @param options serde for the state value, and serde for the projection result.\n * @returns a {@link RestatePromise} resolved with the result of the projection.\n *\n * @example\n * ```ts\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const itemsCount = await ctxInternal.getProject<Item[], number>(\n * \"items\",\n * (items) => items?.length ?? 0\n * );\n * ```\n *\n * @experimental\n */\n getProject<TValue, TResult>(\n name: string,\n projection: (value: TValue | null) => TResult | Promise<TResult>,\n options?: GetProjectOptions<TValue, TResult>\n ): RestatePromise<TResult>;\n}\n\n/**\n * Options for {@link ContextInternal.getProject}.\n *\n * @experimental\n */\nexport type GetProjectOptions<TValue, TResult> = {\n /**\n * Serde used to deserialize the state value.\n */\n serde?: Serde<TValue>;\n\n /**\n * Serde used to serialize the projection result, recorded in the journal.\n *\n * If not set, defaults to {@link GetProjectOptions.serde} when that is set,\n * otherwise to the default serde.\n */\n resultSerde?: Serde<TResult>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,mBAA4C;AAE1D,QADgB,GAAG,oBAAoB,MAAM;;;;;;;;;;;;;;AAgB/C,SAAgB,WAAW,KAA+B;AACxD,QAAO"}
|
|
1
|
+
{"version":3,"file":"internal.js","names":[],"sources":["../src/internal.ts"],"sourcesContent":["import { Context, InvocationId, RestatePromise } from \"./context.js\";\nimport type { Serde } from \"@restatedev/restate-sdk-core\";\nimport type { TerminalError } from \"./types/errors.js\";\n\nexport { isSuspendedError } from \"./types/errors.js\";\n\n/**\n * @deprecated Use `@restatedev/sdk-sessions` npm package instead.\n */\nexport function explicitRecovery(): Record<never, never> {\n return {};\n}\n\n/**\n * Downcast the given context to {@link ContextInternal}, to access the internal APIs.\n *\n * Works with every context type passed to handlers, e.g. `Context`, `ObjectContext`, `ObjectSharedContext`, `WorkflowContext`.\n *\n * @example\n * ```ts\n * const ctxInternal = restate.internal.asInternal(ctx);\n * ```\n *\n * @experimental\n */\nexport function asInternal(ctx: Context): ContextInternal {\n return ctx as ContextInternal;\n}\n\n/**\n * Internal {@link Context} interface exposing additional features.\n *\n * Please note that this API is to be considered experimental and might change without notice.\n *\n * @experimental\n */\nexport interface ContextInternal extends Context {\n /**\n * Returns true if the handler is in the processing phase.\n * This is the mechanism used by `ctx.console` to distinguish whether we should log or not in replaying/processing.\n *\n * **WARNING**: This method should not be used to influence control flow, as it will **surely** lead to non-determinism errors!\n *\n * @experimental\n */\n isProcessing(): boolean;\n\n /**\n * Returns a {@link RestatePromise} that resolves with `undefined` when Restate signals cancellation\n * of the current invocation.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, cancellations are propagated automatically,\n * and this promise will **NEVER** resolve.\n *\n * **Promise reuse:** calling this method multiple times returns the **same** promise instance as long as\n * the current cancellation signal has not yet arrived. Once the promise resolves (cancellation received),\n * later calls return a **new** promise that will resolve on the next cancellation signal.\n *\n * @example Race a long-running side effect against cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const result = await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * return result;\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Use the cancellation promise to create an AbortSignal for ctx.run\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const controller = new AbortController();\n * const cancellation = ctxInternal.cancellation()\n * .map(() => {\n * controller.abort();\n * throw new restate.TerminalError(\"Cancelled\");\n * });\n *\n * return RestatePromise.race([\n * ctx.run(() => fetch(`https://api.example.com/greet/${name}`, { signal: controller.signal })),\n * cancellation,\n * ]);\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @example Handle cancellation, perform cleanup, then listen for the next cancellation\n * ```ts\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * const ctxInternal = restate.internal.asInternal(ctx);\n * try {\n * return await RestatePromise.race([\n * ctx.run(() => longRunningTask(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Cancelled\") }),\n * ]);\n * } catch (e) {\n * // Perform cleanup\n * await ctx.run(() => cleanupResources(name));\n *\n * // After cancellation is resolved, ctx.cancellation() returns a fresh promise.\n * // Race cleanup confirmation against the next cancellation signal.\n * await RestatePromise.race([\n * ctx.run(() => confirmCleanup(name)),\n * ctxInternal.cancellation().map(() => { throw new restate.TerminalError(\"Canceled during cleanup\") }),\n * ]);\n * }\n * },\n * },\n * options: { explicitCancellation: true },\n * });\n * ```\n *\n * @experimental\n */\n cancellation(): RestatePromise<void>;\n\n /**\n * Cancel all previous calls made from this handler.\n *\n * This method **MUST** only be used when the handler (or its parent service/endpoint) is configured\n * with `explicitCancellation: true`. Without configuring this option, this operation will always be a no-op.\n *\n * @return the invocation id of the canceled calls.\n * @experimental\n */\n cancelPreviousCalls(): RestatePromise<InvocationId[]>;\n\n /**\n * Get state from the Restate runtime, apply the given `projection` to it,\n * and record in the journal only the result of the projection.\n *\n * Use this to read big state values when you need only a small part of them:\n * unlike `ctx.get`, the complete state value is not recorded in the journal,\n * only its projection.\n *\n * It will appear in the UI as run(project:state_key).\n *\n * This method **MUST** only be used within Virtual Object and Workflow handlers.\n *\n * **NOTE:** Requires Restate >= 1.8 with service protocol V8 enabled, and **does not** work with request/response protocol mode (e.g. with AWS Lambda).\n *\n * @param name key of the state to retrieve\n * @param projection function receiving the state value, or `null` if the state is empty.\n * @param options serde for the state value, and serde for the projection result.\n * @returns a {@link RestatePromise} resolved with the result of the projection.\n *\n * @example\n * ```ts\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const itemsCount = await ctxInternal.getProject<Item[], number>(\n * \"items\",\n * (items) => items?.length ?? 0\n * );\n * ```\n *\n * @experimental\n */\n getProject<TValue, TResult>(\n name: string,\n projection: (value: TValue | null) => TResult | Promise<TResult>,\n options?: GetProjectOptions<TValue, TResult>\n ): RestatePromise<TResult>;\n\n /**\n * Get the output of the target invocation, **without waiting** for it to complete.\n *\n * Unlike `ctx.invocation(invocationId).attach()`, which waits until the target invocation completes,\n * this returns immediately with an {@link InvocationOutput}:\n * * `{ status: \"running\" }`: the target invocation has not completed yet.\n * * `{ status: \"success\", value }`: the target invocation completed successfully, with the given output value.\n * * `{ status: \"failure\", error }`: the target invocation completed with a failure.\n * Note that the returned promise **does not** reject in this case.\n *\n * **Unknown invocations:** if the target invocation doesn't exist, or its result is no longer retained,\n * the result is `{ status: \"failure\" }` with an `error` having code `404` and message `\"not found\"`.\n *\n * The result is recorded in the journal: on replay you get the same result as in the original execution,\n * even if in the meantime the target invocation completed.\n *\n * @param invocationId the invocation ID of the target invocation.\n * @param serde optional custom serializer/deserializer for the output value.\n * @returns a {@link RestatePromise} resolved with the {@link InvocationOutput} of the target invocation.\n *\n * @example\n * ```ts\n * const ctxInternal = restate.internal.asInternal(ctx);\n * const output = await ctxInternal.getInvocationOutput<string>(invocationId);\n * switch (output.status) {\n * case \"running\":\n * ctx.console.log(\"Still running\");\n * break;\n * case \"success\":\n * ctx.console.log(\"Completed with\", output.value);\n * break;\n * case \"failure\":\n * ctx.console.log(\"Failed with\", output.error.message);\n * break;\n * }\n * ```\n *\n * @experimental\n */\n getInvocationOutput<T>(\n invocationId: InvocationId,\n serde?: Serde<T>\n ): RestatePromise<InvocationOutput<T>>;\n}\n\n/**\n * Output of a target invocation, returned by {@link ContextInternal.getInvocationOutput}.\n *\n * Use the `status` field to tell the cases apart:\n * * `running`: the target invocation has not completed yet.\n * * `success`: the target invocation completed successfully, `value` contains its output.\n * * `failure`: the target invocation completed with a failure, `error` contains the failure.\n *\n * @experimental\n */\nexport type InvocationOutput<T> =\n | { status: \"running\" }\n | { status: \"success\"; value: T }\n | { status: \"failure\"; error: TerminalError };\n\n/**\n * Options for {@link ContextInternal.getProject}.\n *\n * @experimental\n */\nexport type GetProjectOptions<TValue, TResult> = {\n /**\n * Serde used to deserialize the state value.\n */\n serde?: Serde<TValue>;\n\n /**\n * Serde used to serialize the projection result, recorded in the journal.\n *\n * If not set, defaults to {@link GetProjectOptions.serde} when that is set,\n * otherwise to the default serde.\n */\n resultSerde?: Serde<TResult>;\n};\n"],"mappings":";;;;;;;;;;;;AASA,SAAgB,mBAAyC;AACvD,QAAO,EAAE;;;;;;;;;;;;;;AAeX,SAAgB,WAAW,KAA+B;AACxD,QAAO"}
|
package/dist/node.cjs
CHANGED
|
@@ -63,8 +63,10 @@ function createEndpointHandler(options) {
|
|
|
63
63
|
* @param {ServeOptions} options - Configuration options for the endpoint handler.
|
|
64
64
|
* @returns a Promise that resolves with the bound port, or rejects with a failure otherwise.
|
|
65
65
|
*/
|
|
66
|
-
function serve({ port,...options }) {
|
|
67
|
-
|
|
66
|
+
function serve({ port, http2Settings,...options }) {
|
|
67
|
+
const endpoint$1 = new require_node_endpoint.NodeEndpoint();
|
|
68
|
+
require_withOptions.withOptions(endpoint$1, options);
|
|
69
|
+
return endpoint$1.listen(port, { http2Settings });
|
|
68
70
|
}
|
|
69
71
|
|
|
70
72
|
//#endregion
|
package/dist/node.d.cts
CHANGED
|
@@ -12,8 +12,8 @@ import { CombineablePromise, Descriptor, DescriptorOpts, Duration, HandlerDescri
|
|
|
12
12
|
import { ConnectOptions, ConnectTlsOptions, Connection, ConnectionOptions, ReconnectRetryPolicy } from "./endpoint/tunnel/types.cjs";
|
|
13
13
|
import { connect } from "./endpoint/connect/index.cjs";
|
|
14
14
|
import "./endpoint/tunnel/index.cjs";
|
|
15
|
+
import * as http2 from "node:http2";
|
|
15
16
|
import * as http0 from "http";
|
|
16
|
-
import * as http20 from "http2";
|
|
17
17
|
|
|
18
18
|
//#region src/node.d.ts
|
|
19
19
|
/**
|
|
@@ -66,10 +66,30 @@ interface NodeEndpointOptions extends EndpointOptions {
|
|
|
66
66
|
*/
|
|
67
67
|
declare function createEndpointHandler(options: NodeEndpointOptions): {
|
|
68
68
|
(request: http0.IncomingMessage, response: http0.ServerResponse): void;
|
|
69
|
-
(request:
|
|
69
|
+
(request: http2.Http2ServerRequest, response: http2.Http2ServerResponse): void;
|
|
70
70
|
};
|
|
71
71
|
interface ServeOptions extends EndpointOptions {
|
|
72
|
+
/**
|
|
73
|
+
* Port to listen on. Defaults to the `PORT` environment variable, or 9080.
|
|
74
|
+
*/
|
|
72
75
|
port?: number;
|
|
76
|
+
/**
|
|
77
|
+
* HTTP/2 settings of the server.
|
|
78
|
+
*
|
|
79
|
+
* Restate sends invocations as HTTP/2 streams over a few long-lived
|
|
80
|
+
* connections, and opens another connection only when the existing ones
|
|
81
|
+
* are close to their `maxConcurrentStreams`. A low `maxConcurrentStreams`
|
|
82
|
+
* makes Restate open more connections, which lets connection-level load
|
|
83
|
+
* balancing (for example an L4 load balancer in front of several replicas)
|
|
84
|
+
* spread invocations evenly.
|
|
85
|
+
*
|
|
86
|
+
* Restate Server versions before 1.7 don't open additional connections:
|
|
87
|
+
* they use one connection per partition, so a low `maxConcurrentStreams`
|
|
88
|
+
* also limits how many invocations of this endpoint run concurrently per
|
|
89
|
+
* partition. Avoid lowering it if you run many concurrent invocations
|
|
90
|
+
* against such a server.
|
|
91
|
+
*/
|
|
92
|
+
http2Settings?: http2.Settings;
|
|
73
93
|
}
|
|
74
94
|
/**
|
|
75
95
|
* Serves this Restate services as HTTP2 server, listening to the given port.
|
|
@@ -87,6 +107,7 @@ interface ServeOptions extends EndpointOptions {
|
|
|
87
107
|
*/
|
|
88
108
|
declare function serve({
|
|
89
109
|
port,
|
|
110
|
+
http2Settings,
|
|
90
111
|
...options
|
|
91
112
|
}: ServeOptions): Promise<number>;
|
|
92
113
|
//#endregion
|
package/dist/node.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.cts","names":[],"sources":["../src/node.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"node.d.cts","names":[],"sources":["../src/node.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAgCgB,QAAA,CAAA,GAAY;;;;;;;UAUX,mBAAA,SAA4B;EAV7B;AAUhB;AAsCA;;;;;;;EAQiB,aAAA,CAAA,EAAa,OAAA;AAuC9B;;;;;;;;;;;;;;;;;;;;;;;;;;iBA/CgB,qBAAA,UAA+B;YAAmB,KAAA,CAAA;;;UAQjD,YAAA,SAAqB;;;;;;;;;;;;;;;;;;;;;kBAsBpB,KAAA,CAAM;;;;;;;;;;;;;;;;iBAiBR,KAAA;;;;GAIb,eAAe"}
|
package/dist/node.d.ts
CHANGED
|
@@ -12,8 +12,8 @@ import { CombineablePromise, Descriptor, DescriptorOpts, Duration, HandlerDescri
|
|
|
12
12
|
import { ConnectOptions, ConnectTlsOptions, Connection, ConnectionOptions, ReconnectRetryPolicy } from "./endpoint/tunnel/types.js";
|
|
13
13
|
import { connect } from "./endpoint/connect/index.js";
|
|
14
14
|
import "./endpoint/tunnel/index.js";
|
|
15
|
+
import * as http2 from "node:http2";
|
|
15
16
|
import * as http0 from "http";
|
|
16
|
-
import * as http20 from "http2";
|
|
17
17
|
|
|
18
18
|
//#region src/node.d.ts
|
|
19
19
|
/**
|
|
@@ -66,10 +66,30 @@ interface NodeEndpointOptions extends EndpointOptions {
|
|
|
66
66
|
*/
|
|
67
67
|
declare function createEndpointHandler(options: NodeEndpointOptions): {
|
|
68
68
|
(request: http0.IncomingMessage, response: http0.ServerResponse): void;
|
|
69
|
-
(request:
|
|
69
|
+
(request: http2.Http2ServerRequest, response: http2.Http2ServerResponse): void;
|
|
70
70
|
};
|
|
71
71
|
interface ServeOptions extends EndpointOptions {
|
|
72
|
+
/**
|
|
73
|
+
* Port to listen on. Defaults to the `PORT` environment variable, or 9080.
|
|
74
|
+
*/
|
|
72
75
|
port?: number;
|
|
76
|
+
/**
|
|
77
|
+
* HTTP/2 settings of the server.
|
|
78
|
+
*
|
|
79
|
+
* Restate sends invocations as HTTP/2 streams over a few long-lived
|
|
80
|
+
* connections, and opens another connection only when the existing ones
|
|
81
|
+
* are close to their `maxConcurrentStreams`. A low `maxConcurrentStreams`
|
|
82
|
+
* makes Restate open more connections, which lets connection-level load
|
|
83
|
+
* balancing (for example an L4 load balancer in front of several replicas)
|
|
84
|
+
* spread invocations evenly.
|
|
85
|
+
*
|
|
86
|
+
* Restate Server versions before 1.7 don't open additional connections:
|
|
87
|
+
* they use one connection per partition, so a low `maxConcurrentStreams`
|
|
88
|
+
* also limits how many invocations of this endpoint run concurrently per
|
|
89
|
+
* partition. Avoid lowering it if you run many concurrent invocations
|
|
90
|
+
* against such a server.
|
|
91
|
+
*/
|
|
92
|
+
http2Settings?: http2.Settings;
|
|
73
93
|
}
|
|
74
94
|
/**
|
|
75
95
|
* Serves this Restate services as HTTP2 server, listening to the given port.
|
|
@@ -87,6 +107,7 @@ interface ServeOptions extends EndpointOptions {
|
|
|
87
107
|
*/
|
|
88
108
|
declare function serve({
|
|
89
109
|
port,
|
|
110
|
+
http2Settings,
|
|
90
111
|
...options
|
|
91
112
|
}: ServeOptions): Promise<number>;
|
|
92
113
|
//#endregion
|
package/dist/node.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.d.ts","names":[],"sources":["../src/node.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"node.d.ts","names":[],"sources":["../src/node.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;iBAgCgB,QAAA,CAAA,GAAY;;;;;;;UAUX,mBAAA,SAA4B;EAV7B;AAUhB;AAsCA;;;;;;;EAQiB,aAAA,CAAA,EAAa,OAAA;AAuC9B;;;;;;;;;;;;;;;;;;;;;;;;;;iBA/CgB,qBAAA,UAA+B;YAAmB,KAAA,CAAA;;;UAQjD,YAAA,SAAqB;;;;;;;;;;;;;;;;;;;;;kBAsBpB,KAAA,CAAM;;;;;;;;;;;;;;;;iBAiBR,KAAA;;;;GAIb,eAAe"}
|
package/dist/node.js
CHANGED
|
@@ -60,8 +60,10 @@ function createEndpointHandler(options) {
|
|
|
60
60
|
* @param {ServeOptions} options - Configuration options for the endpoint handler.
|
|
61
61
|
* @returns a Promise that resolves with the bound port, or rejects with a failure otherwise.
|
|
62
62
|
*/
|
|
63
|
-
function serve({ port,...options }) {
|
|
64
|
-
|
|
63
|
+
function serve({ port, http2Settings,...options }) {
|
|
64
|
+
const endpoint$1 = new NodeEndpoint();
|
|
65
|
+
withOptions(endpoint$1, options);
|
|
66
|
+
return endpoint$1.listen(port, { http2Settings });
|
|
65
67
|
}
|
|
66
68
|
|
|
67
69
|
//#endregion
|
package/dist/node.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node.js","names":[],"sources":["../src/node.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\nexport * from \"./common_api.js\";\nimport type { RestateEndpoint } from \"./endpoint.js\";\nimport { NodeEndpoint } from \"./endpoint/node_endpoint.js\";\nimport type { EndpointOptions } from \"./endpoint/types.js\";\nimport { withOptions } from \"./endpoint/withOptions.js\";\n\nexport { connect } from \"./endpoint/connect/index.js\";\nexport type {\n Connection,\n ConnectionOptions,\n ConnectOptions,\n ConnectTlsOptions,\n ReconnectRetryPolicy,\n} from \"./endpoint/tunnel/index.js\";\n\n/**\n * Create a new {@link RestateEndpoint}.\n * @deprecated Please use {@link createEndpointHandler}\n */\nexport function endpoint(): RestateEndpoint {\n return new NodeEndpoint();\n}\n\n/**\n * Options for creating a Node.js endpoint handler.\n *\n * Extends {@link EndpointOptions} with Node.js-specific options for controlling\n * the protocol mode.\n */\nexport interface NodeEndpointOptions extends EndpointOptions {\n /**\n * Controls the protocol mode used by the handler.\n *\n * - `undefined` (default): auto-detect based on HTTP version.\n * HTTP/2+ uses bidirectional streaming (`BIDI_STREAM`),\n * HTTP/1.1 uses request-response mode (`REQUEST_RESPONSE`).\n * - `true`: force `BIDI_STREAM` for all requests.\n * - `false`: force `REQUEST_RESPONSE` for all requests.\n */\n bidirectional?: boolean;\n}\n\n/**\n * Creates a request handler for the provided services.\n *\n * The returned handler auto-detects the HTTP protocol version per request:\n * - HTTP/2+ requests use bidirectional streaming (`BIDI_STREAM`)\n * - HTTP/1.1 requests use request-response mode (`REQUEST_RESPONSE`) by default\n *\n * Set `bidirectional: true` to force `BIDI_STREAM` for all requests, or\n * `bidirectional: false` to force `REQUEST_RESPONSE` for all requests.\n *\n * @example HTTP/2 server\n * ```\n * const httpServer = http2.createServer(createEndpointHandler({ services: [myService] }));\n * httpServer.listen(port);\n * ```\n *\n * @example HTTP/1.1 server\n * ```\n * const httpServer = http.createServer(createEndpointHandler({ services: [myService] }));\n * httpServer.listen(port);\n * ```\n *\n * @param {NodeEndpointOptions} options - Configuration options for the endpoint handler.\n * @returns A request handler function compatible with both HTTP/1.1 and HTTP/2 servers.\n */\nexport function createEndpointHandler(options: NodeEndpointOptions) {\n const { bidirectional, ...endpointOptions } = options;\n return withOptions<RestateEndpoint>(\n new NodeEndpoint(),\n endpointOptions\n ).handler({ bidirectional });\n}\n\nexport interface ServeOptions extends EndpointOptions {\n port?: number;\n}\n\n/**\n * Serves this Restate services as HTTP2 server, listening to the given port.\n *\n * If the port is undefined, this method will use the port set in the `PORT`\n * environment variable. If that variable is undefined as well, the method will\n * default to port 9080.\n *\n * The returned promise resolves with the bound port when the server starts listening, or rejects with a failure otherwise.\n *\n * If you need to manually control the server lifecycle, we suggest to manually instantiate the http2 server and use {@link createEndpointHandler}.\n *\n * @param {ServeOptions} options - Configuration options for the endpoint handler.\n * @returns a Promise that resolves with the bound port, or rejects with a failure otherwise.\n */\nexport function serve({
|
|
1
|
+
{"version":3,"file":"node.js","names":["endpoint"],"sources":["../src/node.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\nexport * from \"./common_api.js\";\n\nimport type * as http2 from \"node:http2\";\nimport type { RestateEndpoint } from \"./endpoint.js\";\nimport { NodeEndpoint } from \"./endpoint/node_endpoint.js\";\nimport type { EndpointOptions } from \"./endpoint/types.js\";\nimport { withOptions } from \"./endpoint/withOptions.js\";\n\nexport { connect } from \"./endpoint/connect/index.js\";\nexport type {\n Connection,\n ConnectionOptions,\n ConnectOptions,\n ConnectTlsOptions,\n ReconnectRetryPolicy,\n} from \"./endpoint/tunnel/index.js\";\n\n/**\n * Create a new {@link RestateEndpoint}.\n * @deprecated Please use {@link createEndpointHandler}\n */\nexport function endpoint(): RestateEndpoint {\n return new NodeEndpoint();\n}\n\n/**\n * Options for creating a Node.js endpoint handler.\n *\n * Extends {@link EndpointOptions} with Node.js-specific options for controlling\n * the protocol mode.\n */\nexport interface NodeEndpointOptions extends EndpointOptions {\n /**\n * Controls the protocol mode used by the handler.\n *\n * - `undefined` (default): auto-detect based on HTTP version.\n * HTTP/2+ uses bidirectional streaming (`BIDI_STREAM`),\n * HTTP/1.1 uses request-response mode (`REQUEST_RESPONSE`).\n * - `true`: force `BIDI_STREAM` for all requests.\n * - `false`: force `REQUEST_RESPONSE` for all requests.\n */\n bidirectional?: boolean;\n}\n\n/**\n * Creates a request handler for the provided services.\n *\n * The returned handler auto-detects the HTTP protocol version per request:\n * - HTTP/2+ requests use bidirectional streaming (`BIDI_STREAM`)\n * - HTTP/1.1 requests use request-response mode (`REQUEST_RESPONSE`) by default\n *\n * Set `bidirectional: true` to force `BIDI_STREAM` for all requests, or\n * `bidirectional: false` to force `REQUEST_RESPONSE` for all requests.\n *\n * @example HTTP/2 server\n * ```\n * const httpServer = http2.createServer(createEndpointHandler({ services: [myService] }));\n * httpServer.listen(port);\n * ```\n *\n * @example HTTP/1.1 server\n * ```\n * const httpServer = http.createServer(createEndpointHandler({ services: [myService] }));\n * httpServer.listen(port);\n * ```\n *\n * @param {NodeEndpointOptions} options - Configuration options for the endpoint handler.\n * @returns A request handler function compatible with both HTTP/1.1 and HTTP/2 servers.\n */\nexport function createEndpointHandler(options: NodeEndpointOptions) {\n const { bidirectional, ...endpointOptions } = options;\n return withOptions<RestateEndpoint>(\n new NodeEndpoint(),\n endpointOptions\n ).handler({ bidirectional });\n}\n\nexport interface ServeOptions extends EndpointOptions {\n /**\n * Port to listen on. Defaults to the `PORT` environment variable, or 9080.\n */\n port?: number;\n\n /**\n * HTTP/2 settings of the server.\n *\n * Restate sends invocations as HTTP/2 streams over a few long-lived\n * connections, and opens another connection only when the existing ones\n * are close to their `maxConcurrentStreams`. A low `maxConcurrentStreams`\n * makes Restate open more connections, which lets connection-level load\n * balancing (for example an L4 load balancer in front of several replicas)\n * spread invocations evenly.\n *\n * Restate Server versions before 1.7 don't open additional connections:\n * they use one connection per partition, so a low `maxConcurrentStreams`\n * also limits how many invocations of this endpoint run concurrently per\n * partition. Avoid lowering it if you run many concurrent invocations\n * against such a server.\n */\n http2Settings?: http2.Settings;\n}\n\n/**\n * Serves this Restate services as HTTP2 server, listening to the given port.\n *\n * If the port is undefined, this method will use the port set in the `PORT`\n * environment variable. If that variable is undefined as well, the method will\n * default to port 9080.\n *\n * The returned promise resolves with the bound port when the server starts listening, or rejects with a failure otherwise.\n *\n * If you need to manually control the server lifecycle, we suggest to manually instantiate the http2 server and use {@link createEndpointHandler}.\n *\n * @param {ServeOptions} options - Configuration options for the endpoint handler.\n * @returns a Promise that resolves with the bound port, or rejects with a failure otherwise.\n */\nexport function serve({\n port,\n http2Settings,\n ...options\n}: ServeOptions): Promise<number> {\n const endpoint = new NodeEndpoint();\n withOptions<RestateEndpoint>(endpoint, options);\n return endpoint.listen(port, {\n http2Settings,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,SAAgB,WAA4B;AAC1C,QAAO,IAAI,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+C3B,SAAgB,sBAAsB,SAA8B;CAClE,MAAM,EAAE,cAAe,GAAG,oBAAoB;AAC9C,QAAO,YACL,IAAI,cAAc,EAClB,gBACD,CAAC,QAAQ,EAAE,eAAe,CAAC;;;;;;;;;;;;;;;;AA0C9B,SAAgB,MAAM,EACpB,MACA,cACA,GAAG,WAC6B;CAChC,MAAMA,aAAW,IAAI,cAAc;AACnC,aAA6BA,YAAU,QAAQ;AAC/C,QAAOA,WAAS,OAAO,MAAM,EAC3B,eACD,CAAC"}
|
package/dist/package.cjs
CHANGED
package/dist/package.js
CHANGED