@restatedev/restate-sdk-cloudflare-workers 1.9.1 → 1.10.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/LICENSE +21 -0
- package/dist/_virtual/rolldown_runtime.cjs +25 -0
- package/dist/common_api.cjs +25 -0
- package/dist/common_api.d.cts +30 -0
- package/dist/common_api.d.cts.map +1 -0
- package/dist/common_api.d.ts +30 -0
- package/dist/common_api.d.ts.map +1 -0
- package/dist/common_api.js +19 -0
- package/dist/common_api.js.map +1 -0
- package/dist/context.cjs +29 -0
- package/dist/context.d.cts +699 -0
- package/dist/context.d.cts.map +1 -0
- package/dist/context.d.ts +699 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +29 -0
- package/dist/context.js.map +1 -0
- package/dist/context_impl.cjs +441 -0
- package/dist/context_impl.js +440 -0
- package/dist/context_impl.js.map +1 -0
- package/dist/endpoint/components.cjs +257 -0
- package/dist/endpoint/components.js +253 -0
- package/dist/endpoint/components.js.map +1 -0
- package/dist/endpoint/endpoint.cjs +117 -0
- package/dist/endpoint/endpoint.js +118 -0
- package/dist/endpoint/endpoint.js.map +1 -0
- package/dist/endpoint/fetch_endpoint.cjs +41 -0
- package/dist/endpoint/fetch_endpoint.d.cts +39 -0
- package/dist/endpoint/fetch_endpoint.d.cts.map +1 -0
- package/dist/endpoint/fetch_endpoint.d.ts +39 -0
- package/dist/endpoint/fetch_endpoint.d.ts.map +1 -0
- package/dist/endpoint/fetch_endpoint.js +42 -0
- package/dist/endpoint/fetch_endpoint.js.map +1 -0
- package/dist/endpoint/handlers/fetch.cjs +21 -0
- package/dist/endpoint/handlers/fetch.js +21 -0
- package/dist/endpoint/handlers/fetch.js.map +1 -0
- package/dist/endpoint/handlers/generic.cjs +328 -0
- package/dist/endpoint/handlers/generic.js +324 -0
- package/dist/endpoint/handlers/generic.js.map +1 -0
- package/dist/endpoint/handlers/lambda.cjs +93 -0
- package/dist/endpoint/handlers/lambda.js +89 -0
- package/dist/endpoint/handlers/lambda.js.map +1 -0
- package/dist/endpoint/lambda_endpoint.cjs +36 -0
- package/dist/endpoint/lambda_endpoint.d.cts +26 -0
- package/dist/endpoint/lambda_endpoint.d.cts.map +1 -0
- package/dist/endpoint/lambda_endpoint.d.ts +26 -0
- package/dist/endpoint/lambda_endpoint.d.ts.map +1 -0
- package/dist/endpoint/lambda_endpoint.js +37 -0
- package/dist/endpoint/lambda_endpoint.js.map +1 -0
- package/dist/endpoint/node_endpoint.cjs +101 -0
- package/dist/endpoint/node_endpoint.js +99 -0
- package/dist/endpoint/node_endpoint.js.map +1 -0
- package/dist/endpoint/types.d.cts +61 -0
- package/dist/endpoint/types.d.cts.map +1 -0
- package/dist/endpoint/types.d.ts +61 -0
- package/dist/endpoint/types.d.ts.map +1 -0
- package/dist/endpoint/withOptions.cjs +15 -0
- package/dist/endpoint/withOptions.js +15 -0
- package/dist/endpoint/withOptions.js.map +1 -0
- package/dist/endpoint.d.cts +112 -0
- package/dist/endpoint.d.cts.map +1 -0
- package/dist/endpoint.d.ts +112 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/fetch.cjs +83 -0
- package/dist/fetch.d.cts +52 -0
- package/dist/fetch.d.cts.map +1 -0
- package/dist/fetch.d.ts +52 -0
- package/dist/fetch.d.ts.map +1 -0
- package/dist/{esm/src/fetch.js → fetch.js} +15 -18
- package/dist/fetch.js.map +1 -0
- package/dist/index.cjs +48 -0
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +7 -0
- package/dist/io.cjs +48 -0
- package/dist/io.js +48 -0
- package/dist/io.js.map +1 -0
- package/dist/lambda.cjs +74 -0
- package/dist/lambda.d.cts +32 -0
- package/dist/lambda.d.cts.map +1 -0
- package/dist/lambda.d.ts +32 -0
- package/dist/lambda.d.ts.map +1 -0
- package/dist/lambda.js +35 -0
- package/dist/lambda.js.map +1 -0
- package/dist/logging/console_logger_transport.cjs +54 -0
- package/dist/logging/console_logger_transport.js +54 -0
- package/dist/logging/console_logger_transport.js.map +1 -0
- package/dist/logging/logger.cjs +43 -0
- package/dist/logging/logger.js +44 -0
- package/dist/logging/logger.js.map +1 -0
- package/dist/logging/logger_transport.cjs +42 -0
- package/dist/logging/logger_transport.d.cts +57 -0
- package/dist/logging/logger_transport.d.cts.map +1 -0
- package/dist/logging/logger_transport.d.ts +57 -0
- package/dist/logging/logger_transport.d.ts.map +1 -0
- package/dist/logging/logger_transport.js +40 -0
- package/dist/logging/logger_transport.js.map +1 -0
- package/dist/node.cjs +90 -0
- package/dist/node.d.cts +51 -0
- package/dist/node.d.cts.map +1 -0
- package/dist/node.d.ts +51 -0
- package/dist/node.d.ts.map +1 -0
- package/dist/node.js +50 -0
- package/dist/node.js.map +1 -0
- package/dist/package.cjs +11 -0
- package/dist/package.js +6 -0
- package/dist/package.js.map +1 -0
- package/dist/promises.cjs +234 -0
- package/dist/promises.js +226 -0
- package/dist/promises.js.map +1 -0
- package/dist/types/errors.cjs +110 -0
- package/dist/types/errors.d.cts +71 -0
- package/dist/types/errors.d.cts.map +1 -0
- package/dist/types/errors.d.ts +71 -0
- package/dist/types/errors.d.ts.map +1 -0
- package/dist/types/errors.js +102 -0
- package/dist/types/errors.js.map +1 -0
- package/dist/types/rpc.cjs +425 -0
- package/dist/types/rpc.d.cts +580 -0
- package/dist/types/rpc.d.cts.map +1 -0
- package/dist/types/rpc.d.ts +580 -0
- package/dist/types/rpc.d.ts.map +1 -0
- package/dist/types/rpc.js +406 -0
- package/dist/types/rpc.js.map +1 -0
- package/dist/user_agent.cjs +7 -0
- package/dist/user_agent.js +8 -0
- package/dist/user_agent.js.map +1 -0
- package/dist/utils/completable_promise.cjs +22 -0
- package/dist/utils/completable_promise.js +22 -0
- package/dist/utils/completable_promise.js.map +1 -0
- package/dist/utils/rand.cjs +72 -0
- package/dist/utils/rand.js +71 -0
- package/dist/utils/rand.js.map +1 -0
- package/dist/utils/streams.cjs +14 -0
- package/dist/utils/streams.js +13 -0
- package/dist/utils/streams.js.map +1 -0
- package/package.json +30 -52
- package/dist/esm/src/common_api.d.ts +0 -37
- package/dist/esm/src/common_api.d.ts.map +0 -1
- package/dist/esm/src/common_api.js +0 -32
- package/dist/esm/src/common_api.js.map +0 -1
- package/dist/esm/src/context.d.ts +0 -695
- package/dist/esm/src/context.d.ts.map +0 -1
- package/dist/esm/src/context.js +0 -87
- package/dist/esm/src/context.js.map +0 -1
- package/dist/esm/src/context_impl.d.ts +0 -69
- package/dist/esm/src/context_impl.d.ts.map +0 -1
- package/dist/esm/src/context_impl.js +0 -592
- package/dist/esm/src/context_impl.js.map +0 -1
- package/dist/esm/src/endpoint/components.d.ts +0 -97
- package/dist/esm/src/endpoint/components.d.ts.map +0 -1
- package/dist/esm/src/endpoint/components.js +0 -343
- package/dist/esm/src/endpoint/components.js.map +0 -1
- package/dist/esm/src/endpoint/discovery.d.ts +0 -184
- package/dist/esm/src/endpoint/discovery.d.ts.map +0 -1
- package/dist/esm/src/endpoint/discovery.js +0 -8
- package/dist/esm/src/endpoint/discovery.js.map +0 -1
- package/dist/esm/src/endpoint/endpoint.d.ts +0 -39
- package/dist/esm/src/endpoint/endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/endpoint.js +0 -155
- package/dist/esm/src/endpoint/endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/fetch_endpoint.d.ts +0 -49
- package/dist/esm/src/endpoint/fetch_endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/fetch_endpoint.js +0 -49
- package/dist/esm/src/endpoint/fetch_endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/handlers/fetch.d.ts +0 -5
- package/dist/esm/src/endpoint/handlers/fetch.d.ts.map +0 -1
- package/dist/esm/src/endpoint/handlers/fetch.js +0 -31
- package/dist/esm/src/endpoint/handlers/fetch.js.map +0 -1
- package/dist/esm/src/endpoint/handlers/generic.d.ts +0 -61
- package/dist/esm/src/endpoint/handlers/generic.d.ts.map +0 -1
- package/dist/esm/src/endpoint/handlers/generic.js +0 -470
- package/dist/esm/src/endpoint/handlers/generic.js.map +0 -1
- package/dist/esm/src/endpoint/handlers/lambda.d.ts +0 -10
- package/dist/esm/src/endpoint/handlers/lambda.d.ts.map +0 -1
- package/dist/esm/src/endpoint/handlers/lambda.js +0 -143
- package/dist/esm/src/endpoint/handlers/lambda.js.map +0 -1
- package/dist/esm/src/endpoint/lambda_endpoint.d.ts +0 -30
- package/dist/esm/src/endpoint/lambda_endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/lambda_endpoint.js +0 -48
- package/dist/esm/src/endpoint/lambda_endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/node_endpoint.d.ts +0 -16
- package/dist/esm/src/endpoint/node_endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint/node_endpoint.js +0 -124
- package/dist/esm/src/endpoint/node_endpoint.js.map +0 -1
- package/dist/esm/src/endpoint/types.d.ts +0 -55
- package/dist/esm/src/endpoint/types.d.ts.map +0 -1
- package/dist/esm/src/endpoint/types.js +0 -2
- package/dist/esm/src/endpoint/types.js.map +0 -1
- package/dist/esm/src/endpoint/withOptions.d.ts +0 -4
- package/dist/esm/src/endpoint/withOptions.d.ts.map +0 -1
- package/dist/esm/src/endpoint/withOptions.js +0 -19
- package/dist/esm/src/endpoint/withOptions.js.map +0 -1
- package/dist/esm/src/endpoint.d.ts +0 -108
- package/dist/esm/src/endpoint.d.ts.map +0 -1
- package/dist/esm/src/endpoint.js +0 -12
- package/dist/esm/src/endpoint.js.map +0 -1
- package/dist/esm/src/fetch.d.ts +0 -43
- package/dist/esm/src/fetch.d.ts.map +0 -1
- package/dist/esm/src/fetch.js.map +0 -1
- package/dist/esm/src/generated/version.d.ts +0 -2
- package/dist/esm/src/generated/version.d.ts.map +0 -1
- package/dist/esm/src/generated/version.js +0 -2
- package/dist/esm/src/generated/version.js.map +0 -1
- package/dist/esm/src/io.d.ts +0 -24
- package/dist/esm/src/io.d.ts.map +0 -1
- package/dist/esm/src/io.js +0 -73
- package/dist/esm/src/io.js.map +0 -1
- package/dist/esm/src/lambda.d.ts +0 -23
- package/dist/esm/src/lambda.d.ts.map +0 -1
- package/dist/esm/src/lambda.js +0 -37
- package/dist/esm/src/lambda.js.map +0 -1
- package/dist/esm/src/logging/console_logger_transport.d.ts +0 -5
- package/dist/esm/src/logging/console_logger_transport.d.ts.map +0 -1
- package/dist/esm/src/logging/console_logger_transport.js +0 -94
- package/dist/esm/src/logging/console_logger_transport.js.map +0 -1
- package/dist/esm/src/logging/logger.d.ts +0 -10
- package/dist/esm/src/logging/logger.d.ts.map +0 -1
- package/dist/esm/src/logging/logger.js +0 -57
- package/dist/esm/src/logging/logger.js.map +0 -1
- package/dist/esm/src/logging/logger_transport.d.ts +0 -52
- package/dist/esm/src/logging/logger_transport.d.ts.map +0 -1
- package/dist/esm/src/logging/logger_transport.js +0 -55
- package/dist/esm/src/logging/logger_transport.js.map +0 -1
- package/dist/esm/src/node.d.ts +0 -39
- package/dist/esm/src/node.d.ts.map +0 -1
- package/dist/esm/src/node.js +0 -52
- package/dist/esm/src/node.js.map +0 -1
- package/dist/esm/src/promises.d.ts +0 -111
- package/dist/esm/src/promises.d.ts.map +0 -1
- package/dist/esm/src/promises.js +0 -314
- package/dist/esm/src/promises.js.map +0 -1
- package/dist/esm/src/public_api.d.ts +0 -2
- package/dist/esm/src/public_api.d.ts.map +0 -1
- package/dist/esm/src/public_api.js +0 -12
- package/dist/esm/src/public_api.js.map +0 -1
- package/dist/esm/src/types/errors.d.ts +0 -74
- package/dist/esm/src/types/errors.d.ts.map +0 -1
- package/dist/esm/src/types/errors.js +0 -128
- package/dist/esm/src/types/errors.js.map +0 -1
- package/dist/esm/src/types/rpc.d.ts +0 -620
- package/dist/esm/src/types/rpc.d.ts.map +0 -1
- package/dist/esm/src/types/rpc.js +0 -577
- package/dist/esm/src/types/rpc.js.map +0 -1
- package/dist/esm/src/user_agent.d.ts +0 -2
- package/dist/esm/src/user_agent.d.ts.map +0 -1
- package/dist/esm/src/user_agent.js +0 -13
- package/dist/esm/src/user_agent.js.map +0 -1
- package/dist/esm/src/utils/completable_promise.d.ts +0 -9
- package/dist/esm/src/utils/completable_promise.d.ts.map +0 -1
- package/dist/esm/src/utils/completable_promise.js +0 -30
- package/dist/esm/src/utils/completable_promise.js.map +0 -1
- package/dist/esm/src/utils/rand.d.ts +0 -13
- package/dist/esm/src/utils/rand.d.ts.map +0 -1
- package/dist/esm/src/utils/rand.js +0 -109
- package/dist/esm/src/utils/rand.js.map +0 -1
- package/dist/esm/src/utils/streams.d.ts +0 -3
- package/dist/esm/src/utils/streams.d.ts.map +0 -1
- package/dist/esm/src/utils/streams.js +0 -20
- package/dist/esm/src/utils/streams.js.map +0 -1
- package/dist/esm/tsconfig.tsbuildinfo +0 -1
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings.d.ts +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings.js +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.js +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm +0 -0
- /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm.d.ts +0 -0
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
import { TerminalError, ensureError } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
//#region src/types/rpc.ts
|
|
4
|
+
var Opts = class Opts {
|
|
5
|
+
/**
|
|
6
|
+
* Create a call configuration from the provided options.
|
|
7
|
+
*
|
|
8
|
+
* @param opts the call configuration
|
|
9
|
+
*/
|
|
10
|
+
static from(opts) {
|
|
11
|
+
return new Opts(opts);
|
|
12
|
+
}
|
|
13
|
+
constructor(opts) {
|
|
14
|
+
this.opts = opts;
|
|
15
|
+
}
|
|
16
|
+
getOpts() {
|
|
17
|
+
return this.opts;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
var SendOpts = class SendOpts {
|
|
21
|
+
static from(opts) {
|
|
22
|
+
return new SendOpts(opts);
|
|
23
|
+
}
|
|
24
|
+
getOpts() {
|
|
25
|
+
return this.opts;
|
|
26
|
+
}
|
|
27
|
+
constructor(opts) {
|
|
28
|
+
this.opts = opts;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
let rpc;
|
|
32
|
+
(function(_rpc) {
|
|
33
|
+
_rpc.opts = (opts) => Opts.from(opts);
|
|
34
|
+
_rpc.sendOpts = (opts) => SendOpts.from(opts);
|
|
35
|
+
})(rpc || (rpc = {}));
|
|
36
|
+
function optsFromArgs(args) {
|
|
37
|
+
let parameter;
|
|
38
|
+
let opts;
|
|
39
|
+
switch (args.length) {
|
|
40
|
+
case 0: break;
|
|
41
|
+
case 1:
|
|
42
|
+
if (args[0] instanceof Opts) opts = args[0].getOpts();
|
|
43
|
+
else if (args[0] instanceof SendOpts) opts = args[0].getOpts();
|
|
44
|
+
else parameter = args[0];
|
|
45
|
+
break;
|
|
46
|
+
case 2:
|
|
47
|
+
parameter = args[0];
|
|
48
|
+
if (args[1] instanceof Opts) opts = args[1].getOpts();
|
|
49
|
+
else if (args[1] instanceof SendOpts) opts = args[1].getOpts();
|
|
50
|
+
else throw new TypeError("The second argument must be either Opts or SendOpts");
|
|
51
|
+
break;
|
|
52
|
+
default: throw new TypeError("unexpected number of arguments");
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
parameter,
|
|
56
|
+
opts
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
const makeRpcCallProxy = (genericCall, defaultSerde, service$1, key) => {
|
|
60
|
+
return new Proxy({}, { get: (_target, prop) => {
|
|
61
|
+
const method = prop;
|
|
62
|
+
return (...args) => {
|
|
63
|
+
const { parameter, opts } = optsFromArgs(args);
|
|
64
|
+
const requestSerde = opts?.input ?? defaultSerde;
|
|
65
|
+
const responseSerde = opts?.output ?? defaultSerde;
|
|
66
|
+
return genericCall({
|
|
67
|
+
service: service$1,
|
|
68
|
+
method,
|
|
69
|
+
parameter,
|
|
70
|
+
key,
|
|
71
|
+
headers: opts?.headers,
|
|
72
|
+
inputSerde: requestSerde,
|
|
73
|
+
outputSerde: responseSerde,
|
|
74
|
+
idempotencyKey: opts?.idempotencyKey
|
|
75
|
+
});
|
|
76
|
+
};
|
|
77
|
+
} });
|
|
78
|
+
};
|
|
79
|
+
const makeRpcSendProxy = (genericSend, defaultSerde, service$1, key, legacyDelay) => {
|
|
80
|
+
return new Proxy({}, { get: (_target, prop) => {
|
|
81
|
+
const method = prop;
|
|
82
|
+
return (...args) => {
|
|
83
|
+
const { parameter, opts } = optsFromArgs(args);
|
|
84
|
+
const requestSerde = opts?.input ?? defaultSerde;
|
|
85
|
+
const delay = legacyDelay ?? opts?.delay;
|
|
86
|
+
return genericSend({
|
|
87
|
+
service: service$1,
|
|
88
|
+
method,
|
|
89
|
+
parameter,
|
|
90
|
+
key,
|
|
91
|
+
headers: opts?.headers,
|
|
92
|
+
delay,
|
|
93
|
+
inputSerde: requestSerde,
|
|
94
|
+
idempotencyKey: opts?.idempotencyKey
|
|
95
|
+
});
|
|
96
|
+
};
|
|
97
|
+
} });
|
|
98
|
+
};
|
|
99
|
+
let HandlerKind = /* @__PURE__ */ function(HandlerKind$1) {
|
|
100
|
+
HandlerKind$1[HandlerKind$1["SERVICE"] = 0] = "SERVICE";
|
|
101
|
+
HandlerKind$1[HandlerKind$1["EXCLUSIVE"] = 1] = "EXCLUSIVE";
|
|
102
|
+
HandlerKind$1[HandlerKind$1["SHARED"] = 2] = "SHARED";
|
|
103
|
+
HandlerKind$1[HandlerKind$1["WORKFLOW"] = 3] = "WORKFLOW";
|
|
104
|
+
return HandlerKind$1;
|
|
105
|
+
}({});
|
|
106
|
+
const HANDLER_SYMBOL = Symbol("Handler");
|
|
107
|
+
var HandlerWrapper = class HandlerWrapper {
|
|
108
|
+
static from(kind, handler, opts) {
|
|
109
|
+
const handlerCopy = function(...args) {
|
|
110
|
+
return handler.apply(this, args);
|
|
111
|
+
};
|
|
112
|
+
return new HandlerWrapper(kind, handlerCopy, opts?.input, opts?.output, opts?.accept, opts?.description, opts?.metadata, opts?.idempotencyRetention, opts?.journalRetention, opts?.inactivityTimeout, opts?.abortTimeout, opts?.ingressPrivate, opts !== void 0 && "enableLazyState" in opts ? opts?.enableLazyState : void 0, opts?.retryPolicy);
|
|
113
|
+
}
|
|
114
|
+
static fromHandler(handler) {
|
|
115
|
+
return handler[HANDLER_SYMBOL];
|
|
116
|
+
}
|
|
117
|
+
constructor(kind, handler, inputSerde, outputSerde, accept, description, metadata, idempotencyRetention, journalRetention, inactivityTimeout, abortTimeout, ingressPrivate, enableLazyState, retryPolicy, asTerminalError) {
|
|
118
|
+
this.kind = kind;
|
|
119
|
+
this.handler = handler;
|
|
120
|
+
this.inputSerde = inputSerde;
|
|
121
|
+
this.outputSerde = outputSerde;
|
|
122
|
+
this.accept = accept;
|
|
123
|
+
this.description = description;
|
|
124
|
+
this.metadata = metadata;
|
|
125
|
+
this.idempotencyRetention = idempotencyRetention;
|
|
126
|
+
this.journalRetention = journalRetention;
|
|
127
|
+
this.inactivityTimeout = inactivityTimeout;
|
|
128
|
+
this.abortTimeout = abortTimeout;
|
|
129
|
+
this.ingressPrivate = ingressPrivate;
|
|
130
|
+
this.enableLazyState = enableLazyState;
|
|
131
|
+
this.retryPolicy = retryPolicy;
|
|
132
|
+
this.asTerminalError = asTerminalError;
|
|
133
|
+
}
|
|
134
|
+
bindInstance(t) {
|
|
135
|
+
this.handler = this.handler.bind(t);
|
|
136
|
+
}
|
|
137
|
+
async invoke(context, input) {
|
|
138
|
+
let req;
|
|
139
|
+
try {
|
|
140
|
+
req = (this.inputSerde ?? context.defaultSerde).deserialize(input);
|
|
141
|
+
} catch (e) {
|
|
142
|
+
throw new TerminalError(`Failed to deserialize input: ${ensureError(e).message}`, { errorCode: 400 });
|
|
143
|
+
}
|
|
144
|
+
const res = await this.handler(context, req);
|
|
145
|
+
return (this.outputSerde ?? context.defaultSerde).serialize(res);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Instead of a HandlerWrapper with a handler property,
|
|
149
|
+
* return the original handler with a HandlerWrapper property.
|
|
150
|
+
* This is needed to keep the appearance of regular functions
|
|
151
|
+
* bound to an object, so that for example, `this.foo(ctx, arg)` would
|
|
152
|
+
* work.
|
|
153
|
+
*/
|
|
154
|
+
transpose() {
|
|
155
|
+
const handler = this.handler;
|
|
156
|
+
if (HandlerWrapper.fromHandler(handler) !== void 0) return handler;
|
|
157
|
+
Object.defineProperty(handler, HANDLER_SYMBOL, { value: this });
|
|
158
|
+
return handler;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
let handlers;
|
|
162
|
+
(function(_handlers) {
|
|
163
|
+
function handler(opts, fn) {
|
|
164
|
+
return HandlerWrapper.from(HandlerKind.SERVICE, fn, opts).transpose();
|
|
165
|
+
}
|
|
166
|
+
_handlers.handler = handler;
|
|
167
|
+
let workflow$1;
|
|
168
|
+
(function(_workflow) {
|
|
169
|
+
function workflow$2(optsOrFn, fn) {
|
|
170
|
+
if (typeof optsOrFn === "function") return HandlerWrapper.from(HandlerKind.WORKFLOW, optsOrFn).transpose();
|
|
171
|
+
const opts = optsOrFn;
|
|
172
|
+
if (typeof fn !== "function") throw new TypeError("The second argument must be a function");
|
|
173
|
+
return HandlerWrapper.from(HandlerKind.WORKFLOW, fn, opts).transpose();
|
|
174
|
+
}
|
|
175
|
+
_workflow.workflow = workflow$2;
|
|
176
|
+
function shared(optsOrFn, fn) {
|
|
177
|
+
if (typeof optsOrFn === "function") return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();
|
|
178
|
+
const opts = optsOrFn;
|
|
179
|
+
if (typeof fn !== "function") throw new TypeError("The second argument must be a function");
|
|
180
|
+
return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();
|
|
181
|
+
}
|
|
182
|
+
_workflow.shared = shared;
|
|
183
|
+
})(workflow$1 || (workflow$1 = _handlers.workflow || (_handlers.workflow = {})));
|
|
184
|
+
let object$1;
|
|
185
|
+
(function(_object) {
|
|
186
|
+
function exclusive(optsOrFn, fn) {
|
|
187
|
+
if (typeof optsOrFn === "function") return HandlerWrapper.from(HandlerKind.EXCLUSIVE, optsOrFn).transpose();
|
|
188
|
+
const opts = optsOrFn;
|
|
189
|
+
if (typeof fn !== "function") throw new TypeError("The second argument must be a function");
|
|
190
|
+
return HandlerWrapper.from(HandlerKind.EXCLUSIVE, fn, opts).transpose();
|
|
191
|
+
}
|
|
192
|
+
_object.exclusive = exclusive;
|
|
193
|
+
function shared(optsOrFn, fn) {
|
|
194
|
+
if (typeof optsOrFn === "function") return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();
|
|
195
|
+
const opts = optsOrFn;
|
|
196
|
+
if (typeof fn !== "function") throw new TypeError("The second argument must be a function");
|
|
197
|
+
return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();
|
|
198
|
+
}
|
|
199
|
+
_object.shared = shared;
|
|
200
|
+
})(object$1 || (object$1 = _handlers.object || (_handlers.object = {})));
|
|
201
|
+
})(handlers || (handlers = {}));
|
|
202
|
+
/**
|
|
203
|
+
* Define a Restate service.
|
|
204
|
+
*
|
|
205
|
+
* @example Here is an example of how to define a service:
|
|
206
|
+
*
|
|
207
|
+
* ```ts
|
|
208
|
+
* const greeter = service({
|
|
209
|
+
* name: "greeter",
|
|
210
|
+
* handlers: {
|
|
211
|
+
* greet: async (ctx: Context, name: string) => {
|
|
212
|
+
* return `Hello ${name}`;
|
|
213
|
+
* }
|
|
214
|
+
* }
|
|
215
|
+
* });
|
|
216
|
+
* ```
|
|
217
|
+
*
|
|
218
|
+
* To use the service, you can bind it to an endpoint:
|
|
219
|
+
* ```
|
|
220
|
+
* ...
|
|
221
|
+
* endpoint.bind(greeter)
|
|
222
|
+
* ```
|
|
223
|
+
* @example To use a service, you can export its type to be used in a client:
|
|
224
|
+
* ```
|
|
225
|
+
* export type Greeter = typeof greeter;
|
|
226
|
+
* ...
|
|
227
|
+
* ...
|
|
228
|
+
* import type { Greeter } from "./greeter";
|
|
229
|
+
* const client = ctx.serviceClient<Greeter>({ name : "greeter"});
|
|
230
|
+
* client.greet("World").then(console.log);
|
|
231
|
+
* ```
|
|
232
|
+
*
|
|
233
|
+
* @example Alternatively to avoid repeating the service name, you can:
|
|
234
|
+
* ```
|
|
235
|
+
* import type {Greeter} from "./greeter";
|
|
236
|
+
* const Greeter: Greeter = { name : "greeter"};
|
|
237
|
+
*
|
|
238
|
+
* // now you can reference the service like this:
|
|
239
|
+
* const client = ctx.serviceClient(Greeter);
|
|
240
|
+
* ```
|
|
241
|
+
*
|
|
242
|
+
* @param name the service name
|
|
243
|
+
* @param handlers the handlers for the service
|
|
244
|
+
* @param description an optional description for the service
|
|
245
|
+
* @param metadata an optional metadata for the service
|
|
246
|
+
* @type P the name of the service
|
|
247
|
+
* @type M the handlers for the service
|
|
248
|
+
*/
|
|
249
|
+
const service = (service$1) => {
|
|
250
|
+
if (!service$1.handlers) throw new Error("service must be defined");
|
|
251
|
+
const handlers$1 = Object.entries(service$1.handlers).map(([name, handler]) => {
|
|
252
|
+
if (handler instanceof Function) {
|
|
253
|
+
if (HandlerWrapper.fromHandler(handler) !== void 0) return [name, handler];
|
|
254
|
+
return [name, HandlerWrapper.from(HandlerKind.SERVICE, handler).transpose()];
|
|
255
|
+
}
|
|
256
|
+
throw new TypeError(`Unexpected handler type ${name}`);
|
|
257
|
+
});
|
|
258
|
+
return {
|
|
259
|
+
name: service$1.name,
|
|
260
|
+
service: Object.fromEntries(handlers$1),
|
|
261
|
+
metadata: service$1.metadata,
|
|
262
|
+
description: service$1.description,
|
|
263
|
+
options: service$1.options
|
|
264
|
+
};
|
|
265
|
+
};
|
|
266
|
+
/**
|
|
267
|
+
* Define a Restate virtual object.
|
|
268
|
+
*
|
|
269
|
+
* @example Here is an example of how to define a virtual object:
|
|
270
|
+
* ```ts
|
|
271
|
+
* const counter = object({
|
|
272
|
+
* name: "counter",
|
|
273
|
+
* handlers: {
|
|
274
|
+
* add: async (ctx: ObjectContext, amount: number) => {},
|
|
275
|
+
* get: async (ctx: ObjectContext) => {}
|
|
276
|
+
* }
|
|
277
|
+
* })
|
|
278
|
+
* ```
|
|
279
|
+
*
|
|
280
|
+
* @example To use the object, you can bind it to an endpoint:
|
|
281
|
+
* ```ts
|
|
282
|
+
* ...
|
|
283
|
+
* endpoint.bind(counter)
|
|
284
|
+
* ```
|
|
285
|
+
*
|
|
286
|
+
* @see to interact with the object, you can use the object client:
|
|
287
|
+
* ```ts
|
|
288
|
+
* ...
|
|
289
|
+
* const client = ctx.objectClient<typeof counter>({ name: "counter"});
|
|
290
|
+
* const res = await client.add(1)
|
|
291
|
+
* ```
|
|
292
|
+
*
|
|
293
|
+
* ### Shared handlers
|
|
294
|
+
*
|
|
295
|
+
* Shared handlers are used to allow concurrent read-only access to the object.
|
|
296
|
+
* This is useful when you want to allow multiple clients to read the object's state at the same time.
|
|
297
|
+
* To define a shared handler, you can use the `shared` decorator as shown below:
|
|
298
|
+
*
|
|
299
|
+
* ```ts
|
|
300
|
+
* const counter = object({
|
|
301
|
+
* name: "counter",
|
|
302
|
+
* handlers: {
|
|
303
|
+
*
|
|
304
|
+
* add: async (ctx: ObjectContext, amount: number) => { .. },
|
|
305
|
+
*
|
|
306
|
+
* get: handlers.object.shared(async (ctx: ObjectSharedContext) => {
|
|
307
|
+
* return ctx.get<number>("count");
|
|
308
|
+
* })
|
|
309
|
+
* }
|
|
310
|
+
* });
|
|
311
|
+
* ```
|
|
312
|
+
*
|
|
313
|
+
* @param name the name of the object
|
|
314
|
+
* @param handlers the handlers for the object
|
|
315
|
+
* @param description an optional description for the object
|
|
316
|
+
* @param metadata an optional metadata for the object
|
|
317
|
+
* @type P the name of the object
|
|
318
|
+
* @type M the handlers for the object
|
|
319
|
+
*/
|
|
320
|
+
const object = (object$1) => {
|
|
321
|
+
if (!object$1.handlers) throw new Error("object options must be defined");
|
|
322
|
+
const handlers$1 = Object.entries(object$1.handlers).map(([name, handler]) => {
|
|
323
|
+
if (handler instanceof Function) {
|
|
324
|
+
if (HandlerWrapper.fromHandler(handler) !== void 0) return [name, handler];
|
|
325
|
+
return [name, HandlerWrapper.from(HandlerKind.EXCLUSIVE, handler).transpose()];
|
|
326
|
+
}
|
|
327
|
+
throw new TypeError(`Unexpected handler type ${name}`);
|
|
328
|
+
});
|
|
329
|
+
return {
|
|
330
|
+
name: object$1.name,
|
|
331
|
+
object: Object.fromEntries(handlers$1),
|
|
332
|
+
metadata: object$1.metadata,
|
|
333
|
+
description: object$1.description,
|
|
334
|
+
options: object$1.options
|
|
335
|
+
};
|
|
336
|
+
};
|
|
337
|
+
/**
|
|
338
|
+
* Define a Restate workflow.
|
|
339
|
+
*
|
|
340
|
+
*
|
|
341
|
+
* @example Here is an example of how to define a workflow:
|
|
342
|
+
* ```ts
|
|
343
|
+
* const mywf = workflow({
|
|
344
|
+
* name: "mywf",
|
|
345
|
+
* handlers: {
|
|
346
|
+
* run: async (ctx: WorkflowContext, argument: any) => {
|
|
347
|
+
* return "Hello World";
|
|
348
|
+
* }
|
|
349
|
+
* }
|
|
350
|
+
* });
|
|
351
|
+
* ```
|
|
352
|
+
*
|
|
353
|
+
* ### Note:
|
|
354
|
+
* * That a workflow must contain exactly one handler named 'run', and this handler must accept as a first argument a WorkflowContext.
|
|
355
|
+
* * The workflow handlers other than 'run' must accept as a first argument a WorkflowSharedContext.
|
|
356
|
+
* * The workflow handlers can not be named 'workflowSubmit', 'workflowAttach', 'workflowOutput' - as these are reserved keywords.
|
|
357
|
+
*
|
|
358
|
+
* @example To use the workflow, you can bind it to an endpoint:
|
|
359
|
+
* ```ts
|
|
360
|
+
* endpoint.bind(mywf)
|
|
361
|
+
* ```
|
|
362
|
+
*
|
|
363
|
+
* @example To interact with the workflow, you can use the workflow client:
|
|
364
|
+
* ```ts
|
|
365
|
+
* const client = ctx.workflowClient<typeof mywf>({ name: "mywf"});
|
|
366
|
+
* const res = await client.run("Hello");
|
|
367
|
+
* ```
|
|
368
|
+
*
|
|
369
|
+
* To use the workflow client from any other environment (like a browser), please refer to the documentation.
|
|
370
|
+
* https://docs.restate.dev
|
|
371
|
+
*
|
|
372
|
+
*
|
|
373
|
+
*
|
|
374
|
+
* @param name the workflow name
|
|
375
|
+
* @param handlers the handlers for the workflow.
|
|
376
|
+
*/
|
|
377
|
+
const workflow = (workflow$1) => {
|
|
378
|
+
if (!workflow$1.handlers) throw new Error("workflow must contain handlers");
|
|
379
|
+
const runHandler = workflow$1.handlers["run"];
|
|
380
|
+
let runWrapper;
|
|
381
|
+
if (runHandler instanceof HandlerWrapper) runWrapper = runHandler;
|
|
382
|
+
else if (runHandler instanceof Function) runWrapper = HandlerWrapper.fromHandler(runHandler) ?? HandlerWrapper.from(HandlerKind.WORKFLOW, runHandler);
|
|
383
|
+
else throw new TypeError(`Missing main workflow handler, named 'run'`);
|
|
384
|
+
if (runWrapper.kind !== HandlerKind.WORKFLOW) throw new TypeError(`Workflow's main handler handler run, must be of type workflow'`);
|
|
385
|
+
const handlers$1 = [["run", runWrapper.transpose()]];
|
|
386
|
+
for (const [name, handler] of Object.entries(workflow$1.handlers)) {
|
|
387
|
+
if (name === "run") continue;
|
|
388
|
+
let wrapper;
|
|
389
|
+
if (handler instanceof HandlerWrapper) wrapper = handler;
|
|
390
|
+
else if (handler instanceof Function) wrapper = HandlerWrapper.fromHandler(handler) ?? HandlerWrapper.from(HandlerKind.SHARED, handler);
|
|
391
|
+
else throw new TypeError(`Unexpected handler type ${name}`);
|
|
392
|
+
if (wrapper.kind === HandlerKind.WORKFLOW) throw new TypeError(`A workflow must contain exactly one handler annotated as workflow, named 'run'. Please use a shared handler for any additional handlers`);
|
|
393
|
+
handlers$1.push([name, wrapper.transpose()]);
|
|
394
|
+
}
|
|
395
|
+
return {
|
|
396
|
+
name: workflow$1.name,
|
|
397
|
+
workflow: Object.fromEntries(handlers$1),
|
|
398
|
+
metadata: workflow$1.metadata,
|
|
399
|
+
description: workflow$1.description,
|
|
400
|
+
options: workflow$1.options
|
|
401
|
+
};
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
//#endregion
|
|
405
|
+
export { HandlerKind, HandlerWrapper, Opts, SendOpts, handlers, makeRpcCallProxy, makeRpcSendProxy, object, rpc, service, workflow };
|
|
406
|
+
//# sourceMappingURL=rpc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpc.js","names":["opts: ClientCallOptions<I, O>","opts: ClientSendOptions<I>","parameter: unknown","opts:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined","kind: HandlerKind","handler: Function","inputSerde?: Serde<unknown>","outputSerde?: Serde<unknown>","accept?: string","description?: string","metadata?: Record<string, string>","idempotencyRetention?: Duration | number","journalRetention?: Duration | number","inactivityTimeout?: Duration | number","abortTimeout?: Duration | number","ingressPrivate?: boolean","enableLazyState?: boolean","retryPolicy?: RetryPolicy","asTerminalError?: (error: any) => TerminalError | undefined","req: unknown","res: unknown","workflow","service","handlers","object","runWrapper: HandlerWrapper","wrapper: HandlerWrapper"],"sources":["../../src/types/rpc.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-function-type */\n/* eslint-disable @typescript-eslint/no-unsafe-call */\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport type {\n Context,\n GenericCall,\n GenericSend,\n InvocationHandle,\n InvocationPromise,\n ObjectContext,\n ObjectSharedContext,\n TypedState,\n UntypedState,\n WorkflowContext,\n WorkflowSharedContext,\n} from \"../context.js\";\n\nimport {\n type ServiceHandler,\n type ServiceDefinition,\n type ObjectHandler,\n type VirtualObjectDefinition,\n type WorkflowHandler,\n type WorkflowDefinition,\n type WorkflowSharedHandler,\n type Serde,\n type Duration,\n} from \"@restatedev/restate-sdk-core\";\nimport { ensureError, TerminalError } from \"./errors.js\";\n\n// ----------- rpc clients -------------------------------------------------------\n\nexport type ClientCallOptions<I, O> = {\n input?: Serde<I>;\n output?: Serde<O>;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n};\n\nexport class Opts<I, O> {\n /**\n * Create a call configuration from the provided options.\n *\n * @param opts the call configuration\n */\n public static from<I, O>(opts: ClientCallOptions<I, O>): Opts<I, O> {\n return new Opts<I, O>(opts);\n }\n\n private constructor(private readonly opts: ClientCallOptions<I, O>) {}\n\n public getOpts(): ClientCallOptions<I, O> {\n return this.opts;\n }\n}\n\nexport type ClientSendOptions<I> = {\n input?: Serde<I>;\n /**\n * Makes a type-safe one-way RPC to the specified target service, after a delay specified by the\n * milliseconds' argument.\n * This method is like setting up a fault-tolerant cron job that enqueues the message in a\n * message queue.\n * The handler calling this function does not have to stay active for the delay time.\n *\n * Both the delay timer and the message are durably stored in Restate and guaranteed to be reliably\n * delivered. The delivery happens no earlier than specified through the delay, but may happen\n * later, if the target service is down, or backpressuring the system.\n *\n * The delay message is journaled for durable execution and will thus not be duplicated when the\n * handler is re-invoked for retries or after suspending.\n *\n * This call will return immediately; the message sending happens asynchronously in the background.\n * Despite that, the message is guaranteed to be sent, because the completion of the invocation that\n * triggers the send (calls this function) happens logically after the sending. That means that any\n * failure where the message does not reach Restate also cannot complete this invocation, and will\n * hence recover this handler and (through the durable execution) recover the message to be sent.\n *\n * @example\n * ```ts\n * ctx.serviceSendClient(Service).anotherAction(1337, { delay: { seconds: 60 } });\n * ```\n */\n delay?: Duration | number;\n headers?: Record<string, string>;\n idempotencyKey?: string;\n};\n\nexport class SendOpts<I> {\n public static from<I>(opts: ClientSendOptions<I>): SendOpts<I> {\n return new SendOpts<I>(opts);\n }\n\n public getOpts(): ClientSendOptions<I> {\n return this.opts;\n }\n\n private constructor(private readonly opts: ClientSendOptions<I>) {}\n}\n\nexport namespace rpc {\n export const opts = <I, O>(opts: ClientCallOptions<I, O>) => Opts.from(opts);\n\n export const sendOpts = <I>(opts: ClientSendOptions<I>) =>\n SendOpts.from(opts);\n}\n\nfunction optsFromArgs(args: unknown[]): {\n parameter?: unknown;\n opts?:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined;\n} {\n let parameter: unknown;\n let opts:\n | ClientCallOptions<unknown, unknown>\n | ClientSendOptions<unknown>\n | undefined;\n switch (args.length) {\n case 0: {\n break;\n }\n case 1: {\n if (args[0] instanceof Opts) {\n opts = args[0].getOpts();\n } else if (args[0] instanceof SendOpts) {\n opts = args[0].getOpts();\n } else {\n parameter = args[0];\n }\n break;\n }\n case 2: {\n parameter = args[0];\n if (args[1] instanceof Opts) {\n opts = args[1].getOpts();\n } else if (args[1] instanceof SendOpts) {\n opts = args[1].getOpts();\n } else {\n throw new TypeError(\n \"The second argument must be either Opts or SendOpts\"\n );\n }\n break;\n }\n default: {\n throw new TypeError(\"unexpected number of arguments\");\n }\n }\n return {\n parameter,\n opts,\n };\n}\n\nexport const makeRpcCallProxy = <T>(\n genericCall: (call: GenericCall<unknown, unknown>) => Promise<unknown>,\n defaultSerde: Serde<any>,\n service: string,\n key?: string\n): T => {\n const clientProxy = new Proxy(\n {},\n {\n get: (_target, prop) => {\n const method = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n const requestSerde = opts?.input ?? defaultSerde;\n const responseSerde =\n (opts as ClientCallOptions<unknown, unknown> | undefined)?.output ??\n defaultSerde;\n return genericCall({\n service,\n method,\n parameter,\n key,\n headers: opts?.headers,\n inputSerde: requestSerde,\n outputSerde: responseSerde,\n idempotencyKey: opts?.idempotencyKey,\n });\n };\n },\n }\n );\n\n return clientProxy as T;\n};\n\nexport const makeRpcSendProxy = <T>(\n genericSend: (send: GenericSend<unknown>) => void,\n defaultSerde: Serde<any>,\n service: string,\n key?: string,\n legacyDelay?: number\n): T => {\n const clientProxy = new Proxy(\n {},\n {\n get: (_target, prop) => {\n const method = prop as string;\n return (...args: unknown[]) => {\n const { parameter, opts } = optsFromArgs(args);\n const requestSerde = opts?.input ?? defaultSerde;\n const delay =\n legacyDelay ??\n (opts as ClientSendOptions<unknown> | undefined)?.delay;\n return genericSend({\n service,\n method,\n parameter,\n key,\n headers: opts?.headers,\n delay,\n inputSerde: requestSerde,\n idempotencyKey: opts?.idempotencyKey,\n });\n };\n },\n }\n );\n\n return clientProxy as T;\n};\n\nexport type InferArg<P> = P extends [infer A, ...any[]] ? A : unknown;\n\nexport type Client<M> = {\n [K in keyof M as M[K] extends never ? never : K]: M[K] extends (\n arg: any,\n ...args: infer P\n ) => PromiseLike<infer O>\n ? (\n ...args: [...P, ...[opts?: Opts<InferArg<P>, O>]]\n ) => InvocationPromise<O>\n : never;\n};\n\nexport type SendClient<M> = {\n [K in keyof M as M[K] extends never ? never : K]: M[K] extends (\n arg: any,\n ...args: infer P\n ) => void\n ? (...args: [...P, ...[opts?: SendOpts<InferArg<P>>]]) => InvocationHandle\n : never;\n};\n\n// ----------- handlers ----------------------------------------------\n\nexport enum HandlerKind {\n SERVICE,\n EXCLUSIVE,\n SHARED,\n WORKFLOW,\n}\n\nexport type ServiceHandlerOpts<I, O> = {\n /**\n * Defines which Content-Type values are accepted when this handler is invoked via the ingress.\n * Wildcards are supported, for example `application/*` or `* / *`.\n *\n * If unset, `input.contentType` will be used as the default.\n *\n * This setting does not affect deserialization. To customize how the input is deserialized,\n * provide an `input` Serde.\n */\n accept?: string;\n\n /**\n * Serde used to deserialize the input parameter.\n * Defaults to `restate.serde.json`.\n *\n * Provide a custom Serde if the input is not JSON, or use\n * `restate.serde.binary` to skip serialization/deserialization altogether;\n * in that case the input parameter is a `Uint8Array`.\n */\n input?: Serde<I>;\n\n /**\n * Serde used to serialize the output value.\n * Defaults to `restate.serde.json`.\n *\n * Provide a custom Serde if the output is not JSON, or use\n * `restate.serde.binary` to skip serialization/deserialization altogether;\n * in that case the output value is a `Uint8Array`.\n */\n output?: Serde<O>;\n\n /**\n * Human-readable description of the handler, shown in documentation/admin tools.\n */\n description?: string;\n\n /**\n * Arbitrary key/value metadata for the handler. Exposed via the Admin API.\n */\n metadata?: Record<string, string>;\n\n /**\n * The retention duration of idempotent requests to this handler.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n idempotencyRetention?: Duration | number;\n\n /**\n * The journal retention for invocations to this handler.\n *\n * When a request has an idempotency key, `idempotencyRetention` caps the journal retention time.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n journalRetention?: Duration | number;\n\n /**\n * Guards against stalled invocations. Once this timeout expires, Restate requests a graceful\n * suspension of the invocation (preserving intermediate progress).\n *\n * If the invocation does not react to the suspension request, `abortTimeout` is used to abort it.\n *\n * Overrides the inactivity timeout set at the service level and the default configured in the Restate server.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n inactivityTimeout?: Duration | number;\n\n /**\n * Guards against invocations that fail to terminate after inactivity.\n * The abort timeout starts after `inactivityTimeout` expires and a graceful termination was requested.\n * When this timer expires, the invocation is aborted.\n *\n * This timer may interrupt user code. If more time is needed for graceful termination, increase this value.\n *\n * Overrides the abort timeout set at the service level and the default configured in the Restate server.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n abortTimeout?: Duration | number;\n\n /**\n * When set to `true`, this handler cannot be invoked via the Restate server HTTP or Kafka ingress;\n * it can only be called from other services.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n ingressPrivate?: boolean;\n\n /**\n * Retry policy to apply to all requests to this handler. For each unspecified field, the default value configured in the service or, if absent, in the restate-server configuration file, will be applied instead.\n */\n retryPolicy?: RetryPolicy;\n};\n\nexport type ObjectHandlerOpts<I, O> = ServiceHandlerOpts<I, O> & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this handler.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\nexport type WorkflowHandlerOpts<I, O> = ServiceHandlerOpts<I, O> & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this handler.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\nconst HANDLER_SYMBOL = Symbol(\"Handler\");\n\nexport class HandlerWrapper {\n public static from(\n kind: HandlerKind,\n handler: Function,\n opts?:\n | ServiceHandlerOpts<unknown, unknown>\n | ObjectHandlerOpts<unknown, unknown>\n | WorkflowHandlerOpts<unknown, unknown>\n ): HandlerWrapper {\n // we must create here a copy of the handler\n // to be able to reuse the original handler in other places.\n // like for example the same logic but under different routes.\n const handlerCopy = function (this: any, ...args: any[]): any {\n return handler.apply(this, args);\n };\n\n return new HandlerWrapper(\n kind,\n handlerCopy,\n opts?.input,\n opts?.output,\n opts?.accept,\n opts?.description,\n opts?.metadata,\n opts?.idempotencyRetention,\n opts?.journalRetention,\n opts?.inactivityTimeout,\n opts?.abortTimeout,\n opts?.ingressPrivate,\n opts !== undefined && \"enableLazyState\" in opts\n ? opts?.enableLazyState\n : undefined,\n opts?.retryPolicy\n );\n }\n\n public static fromHandler(handler: any): HandlerWrapper | undefined {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return handler[HANDLER_SYMBOL] as HandlerWrapper | undefined;\n }\n\n private constructor(\n public readonly kind: HandlerKind,\n private handler: Function,\n public readonly inputSerde?: Serde<unknown>,\n public readonly outputSerde?: Serde<unknown>,\n public readonly accept?: string,\n public readonly description?: string,\n public readonly metadata?: Record<string, string>,\n public readonly idempotencyRetention?: Duration | number,\n public readonly journalRetention?: Duration | number,\n public readonly inactivityTimeout?: Duration | number,\n public readonly abortTimeout?: Duration | number,\n public readonly ingressPrivate?: boolean,\n public readonly enableLazyState?: boolean,\n public readonly retryPolicy?: RetryPolicy,\n public readonly asTerminalError?: (error: any) => TerminalError | undefined\n ) {}\n\n bindInstance(t: unknown) {\n this.handler = this.handler.bind(t) as Function;\n }\n\n async invoke(context: { defaultSerde: Serde<any> }, input: Uint8Array) {\n let req: unknown;\n try {\n req = (this.inputSerde ?? context.defaultSerde).deserialize(input);\n } catch (e) {\n const error = ensureError(e);\n throw new TerminalError(`Failed to deserialize input: ${error.message}`, {\n errorCode: 400,\n });\n }\n\n const res: unknown = await this.handler(context, req);\n return (this.outputSerde ?? context.defaultSerde).serialize(res);\n }\n\n /**\n * Instead of a HandlerWrapper with a handler property,\n * return the original handler with a HandlerWrapper property.\n * This is needed to keep the appearance of regular functions\n * bound to an object, so that for example, `this.foo(ctx, arg)` would\n * work.\n */\n transpose<F>(): F {\n const handler = this.handler;\n const existing = HandlerWrapper.fromHandler(handler);\n if (existing !== undefined) {\n return handler as F;\n }\n Object.defineProperty(handler, HANDLER_SYMBOL, { value: this });\n return handler as F;\n }\n}\n\n// ----------- handler decorators ----------------------------------------------\nexport type RemoveVoidArgument<F> = F extends (\n ctx: infer C,\n arg: infer A\n) => infer R\n ? A extends void\n ? (ctx: C) => R\n : F\n : F;\n\nexport namespace handlers {\n /**\n * Create a service handler.\n *\n * @param opts additional configuration\n * @param fn the actual handler code to execute\n */\n export function handler<O, I = void>(\n opts: ServiceHandlerOpts<I, O>,\n fn: (ctx: Context, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn> {\n return HandlerWrapper.from(HandlerKind.SERVICE, fn, opts).transpose();\n }\n\n export namespace workflow {\n export function workflow<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: WorkflowHandlerOpts<I, O>,\n fn: (ctx: WorkflowContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n export function workflow<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: WorkflowContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n export function workflow<O, I = void>(\n optsOrFn:\n | WorkflowHandlerOpts<I, O>\n | ((ctx: WorkflowContext, input: I) => Promise<O>),\n fn?: (ctx: WorkflowContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.WORKFLOW, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies WorkflowHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.WORKFLOW, fn, opts).transpose();\n }\n\n /**\n * Creates a shared handler for a workflow.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: WorkflowHandlerOpts<I, O>,\n fn: (ctx: WorkflowSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a workflow.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: WorkflowSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a workflow\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<O, I = void>(\n optsOrFn:\n | WorkflowHandlerOpts<I, O>\n | ((ctx: WorkflowSharedContext, input: I) => Promise<O>),\n fn?: (ctx: WorkflowSharedContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();\n }\n }\n\n export namespace object {\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n * note : This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function exclusive<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: ObjectHandlerOpts<I, O>,\n fn: (ctx: ObjectContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n *\n * note 1: This applies only to a virtual object.\n * note 2: This is the default for virtual objects, so if no\n * additional reconfiguration is needed, you can simply\n * use the handler directly (no need to use exclusive).\n * This variant here is only for symmetry/convenance.\n *\n * @param fn the handler to execute\n */\n export function exclusive<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: ObjectContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates an exclusive handler for a virtual Object.\n *\n *\n * note 1: This applies only to a virtual object.\n * note 2: This is the default for virtual objects, so if no\n * additional reconfiguration is needed, you can simply\n * use the handler directly (no need to use exclusive).\n * This variant here is only for symmetry/convenance.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function exclusive<O, I = void>(\n optsOrFn:\n | ObjectHandlerOpts<I, O>\n | ((ctx: ObjectContext, input: I) => Promise<O>),\n fn?: (ctx: ObjectContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.EXCLUSIVE, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.EXCLUSIVE, fn, opts).transpose();\n }\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n opts: ObjectHandlerOpts<I, O>,\n fn: (ctx: ObjectSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<\n O,\n I = void,\n TState extends TypedState = UntypedState,\n >(\n fn: (ctx: ObjectSharedContext<TState>, input: I) => Promise<O>\n ): RemoveVoidArgument<typeof fn>;\n\n /**\n * Creates a shared handler for a virtual Object.\n *\n * A shared handler allows a read-only concurrent execution\n * for a given key.\n *\n * note: This applies only to a virtual object.\n *\n * @param opts additional configurations\n * @param fn the handler to execute\n */\n export function shared<I, O>(\n optsOrFn:\n | ObjectHandlerOpts<I, O>\n | ((ctx: ObjectSharedContext, input: I) => Promise<O>),\n fn?: (ctx: ObjectSharedContext, input: I) => Promise<O>\n ) {\n if (typeof optsOrFn === \"function\") {\n return HandlerWrapper.from(HandlerKind.SHARED, optsOrFn).transpose();\n }\n const opts = optsOrFn satisfies ObjectHandlerOpts<I, O>;\n if (typeof fn !== \"function\") {\n throw new TypeError(\"The second argument must be a function\");\n }\n return HandlerWrapper.from(HandlerKind.SHARED, fn, opts).transpose();\n }\n }\n}\n\n// ----------- services ----------------------------------------------\n\nexport type ServiceOpts<U> = {\n [K in keyof U]: U[K] extends ServiceHandler<U[K], Context>\n ? U[K]\n : ServiceHandler<U[K], Context>;\n};\n\nexport type RetryPolicy = {\n /**\n * Max number of retry attempts (including the initial).\n * When reached, the behavior specified in {@link onMaxAttempts} will be applied.\n */\n maxAttempts?: number;\n\n /**\n * What to do when max attempts are reached.\n *\n * If `pause`, the invocation will enter the paused state and can be manually resumed from the CLI/UI.\n *\n * If `kill`, the invocation will get automatically killed.\n */\n onMaxAttempts?: \"pause\" | \"kill\";\n\n /**\n * Initial interval for the first retry attempt.\n * Retry interval will grow by a factor specified in `exponentiationFactor`.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n initialInterval?: Duration | number;\n\n /**\n * Max interval between retries.\n * Retry interval will grow by a factor specified in `exponentiationFactor`.\n *\n * If a number is provided, it will be interpreted as milliseconds.\n */\n maxInterval?: Duration | number;\n\n /**\n * Exponentiation factor to use when computing the next retry delay.\n */\n exponentiationFactor?: number;\n};\n\nexport type ServiceOptions = {\n /**\n * The retention duration of idempotent requests to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n idempotencyRetention?: Duration | number;\n\n /**\n * Journal retention applied to all requests to all handlers of this service.\n *\n * When a request includes an idempotency key, `idempotencyRetention` caps the journal retention time.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n journalRetention?: Duration | number;\n\n /**\n * Guards against stalled invocations. Once this timeout expires, Restate requests a graceful\n * suspension of the invocation (preserving intermediate progress).\n *\n * If the invocation does not react to the suspension request, `abortTimeout` is used to abort it.\n *\n * Overrides the default inactivity timeout configured in the Restate server for all invocations to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n inactivityTimeout?: Duration | number;\n\n /**\n * Guards against invocations that fail to terminate after inactivity.\n * The abort timeout starts after `inactivityTimeout` expires and a graceful termination was requested.\n * When this timer expires, the invocation is aborted.\n *\n * This timer may interrupt user code. If more time is needed for graceful termination, increase this value.\n *\n * Overrides the default abort timeout configured in the Restate server for invocations to this service.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n abortTimeout?: Duration | number;\n\n /**\n * When set to `true`, this service (and all its handlers) cannot be invoked via the Restate server\n * HTTP or Kafka ingress; it can only be called from other services.\n *\n * Note: Available only when registering this endpoint with restate-server v1.4 or newer; otherwise service discovery will fail.\n */\n ingressPrivate?: boolean;\n\n /**\n * Retry policy to apply to all requests to this service. For each unspecified field, the default value configured in the restate-server configuration file will be applied instead.\n */\n retryPolicy?: RetryPolicy;\n\n /**\n * By default, Restate treats errors as terminal (non-retryable) only when they are instances of `TerminalError`.\n *\n * Use this hook to map domain-specific errors to `TerminalError` (or return `undefined` to keep them retryable).\n * When mapped to `TerminalError`, the error will not be retried.\n *\n * Note: This applies to errors thrown inside `ctx.run` closures as well as errors thrown by Restate handlers.\n *\n * Example:\n *\n * ```ts\n * class MyValidationError extends Error {}\n *\n * const greeter = restate.service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: restate.Context, name: string) => {\n * if (name.length === 0) {\n * throw new MyValidationError(\"Length too short\");\n * }\n * return `Hello ${name}`;\n * }\n * },\n * options: {\n * asTerminalError: (err) => {\n * if (err instanceof MyValidationError) {\n * // My validation error is terminal\n * return new restate.TerminalError(err.message, { errorCode: 400 });\n * }\n *\n * // Any other error is retryable\n * }\n * }\n * });\n * ```\n */\n asTerminalError?: (error: any) => TerminalError | undefined;\n\n /**\n * Default serde to use for requests, responses, state, side effects, awakeables, promises. Used when no other serde is specified.\n *\n * If not provided, defaults to `serde.json`.\n */\n serde?: Serde<any>;\n};\n\n/**\n * Define a Restate service.\n *\n * @example Here is an example of how to define a service:\n *\n * ```ts\n * const greeter = service({\n * name: \"greeter\",\n * handlers: {\n * greet: async (ctx: Context, name: string) => {\n * return `Hello ${name}`;\n * }\n * }\n * });\n * ```\n *\n * To use the service, you can bind it to an endpoint:\n * ```\n * ...\n * endpoint.bind(greeter)\n * ```\n * @example To use a service, you can export its type to be used in a client:\n * ```\n * export type Greeter = typeof greeter;\n * ...\n * ...\n * import type { Greeter } from \"./greeter\";\n * const client = ctx.serviceClient<Greeter>({ name : \"greeter\"});\n * client.greet(\"World\").then(console.log);\n * ```\n *\n * @example Alternatively to avoid repeating the service name, you can:\n * ```\n * import type {Greeter} from \"./greeter\";\n * const Greeter: Greeter = { name : \"greeter\"};\n *\n * // now you can reference the service like this:\n * const client = ctx.serviceClient(Greeter);\n * ```\n *\n * @param name the service name\n * @param handlers the handlers for the service\n * @param description an optional description for the service\n * @param metadata an optional metadata for the service\n * @type P the name of the service\n * @type M the handlers for the service\n */\nexport const service = <P extends string, M>(service: {\n name: P;\n handlers: ServiceOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: ServiceOptions;\n}): ServiceDefinition<P, M> => {\n if (!service.handlers) {\n throw new Error(\"service must be defined\");\n }\n const handlers = Object.entries(service.handlers).map(([name, handler]) => {\n if (handler instanceof Function) {\n if (HandlerWrapper.fromHandler(handler) !== undefined) {\n return [name, handler];\n }\n return [\n name,\n HandlerWrapper.from(HandlerKind.SERVICE, handler).transpose(),\n ];\n }\n throw new TypeError(`Unexpected handler type ${name}`);\n });\n\n return {\n name: service.name,\n service: Object.fromEntries(handlers) as object,\n metadata: service.metadata,\n description: service.description,\n options: service.options,\n } as ServiceDefinition<P, M>;\n};\n\n// ----------- objects ----------------------------------------------\n\nexport type ObjectOpts<U> = {\n [K in keyof U]: U[K] extends ObjectHandler<U[K], ObjectContext<any>>\n ? U[K]\n : U[K] extends ObjectHandler<U[K], ObjectSharedContext<any>>\n ? U[K]\n :\n | ObjectHandler<U[K], ObjectContext<any>>\n | ObjectHandler<U[K], ObjectSharedContext<any>>;\n};\n\nexport type ObjectOptions = ServiceOptions & {\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this service.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\n/**\n * Define a Restate virtual object.\n *\n * @example Here is an example of how to define a virtual object:\n * ```ts\n * const counter = object({\n * name: \"counter\",\n * handlers: {\n * add: async (ctx: ObjectContext, amount: number) => {},\n * get: async (ctx: ObjectContext) => {}\n * }\n * })\n * ```\n *\n * @example To use the object, you can bind it to an endpoint:\n * ```ts\n * ...\n * endpoint.bind(counter)\n * ```\n *\n * @see to interact with the object, you can use the object client:\n * ```ts\n * ...\n * const client = ctx.objectClient<typeof counter>({ name: \"counter\"});\n * const res = await client.add(1)\n * ```\n *\n * ### Shared handlers\n *\n * Shared handlers are used to allow concurrent read-only access to the object.\n * This is useful when you want to allow multiple clients to read the object's state at the same time.\n * To define a shared handler, you can use the `shared` decorator as shown below:\n *\n * ```ts\n * const counter = object({\n * name: \"counter\",\n * handlers: {\n *\n * add: async (ctx: ObjectContext, amount: number) => { .. },\n *\n * get: handlers.object.shared(async (ctx: ObjectSharedContext) => {\n * return ctx.get<number>(\"count\");\n * })\n * }\n * });\n * ```\n *\n * @param name the name of the object\n * @param handlers the handlers for the object\n * @param description an optional description for the object\n * @param metadata an optional metadata for the object\n * @type P the name of the object\n * @type M the handlers for the object\n */\nexport const object = <P extends string, M>(object: {\n name: P;\n handlers: ObjectOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: ObjectOptions;\n}): VirtualObjectDefinition<P, M> => {\n if (!object.handlers) {\n throw new Error(\"object options must be defined\");\n }\n\n const handlers = Object.entries(object.handlers).map(([name, handler]) => {\n if (handler instanceof Function) {\n if (HandlerWrapper.fromHandler(handler) !== undefined) {\n return [name, handler];\n }\n\n return [\n name,\n HandlerWrapper.from(HandlerKind.EXCLUSIVE, handler).transpose(),\n ];\n }\n throw new TypeError(`Unexpected handler type ${name}`);\n });\n\n return {\n name: object.name,\n object: Object.fromEntries(handlers) as object,\n metadata: object.metadata,\n description: object.description,\n options: object.options,\n } as VirtualObjectDefinition<P, M>;\n};\n\n// ----------- workflows ----------------------------------------------\n\n/**\n * A workflow handlers is a type that describes the handlers for a workflow.\n * The handlers must contain exactly one handler named 'run', and this handler must accept as a first argument a WorkflowContext.\n * It can contain any number of additional handlers, which must accept as a first argument a WorkflowSharedContext.\n * The handlers can not be named 'workflowSubmit', 'workflowAttach', 'workflowOutput' - as these are reserved.\n * @see {@link workflow} for an example.\n */\nexport type WorkflowOpts<U> = {\n run: (ctx: WorkflowContext<any>, argument: any) => Promise<any>;\n} & {\n [K in keyof U]: K extends\n | \"workflowSubmit\"\n | \"workflowAttach\"\n | \"workflowOutput\"\n ? `${K} is a reserved keyword`\n : K extends \"run\"\n ? U[K] extends WorkflowHandler<U[K], WorkflowContext<any>>\n ? U[K]\n : \"An handler named 'run' must take as a first argument a WorkflowContext, and must return a Promise\"\n : U[K] extends WorkflowSharedHandler<U[K], WorkflowSharedContext<any>>\n ? U[K]\n : \"An handler other then 'run' must accept as a first argument a WorkflowSharedContext\";\n};\n\nexport type WorkflowOptions = ServiceOptions & {\n /**\n * The retention duration for this workflow.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n workflowRetention?: Duration | number;\n /**\n * When set to `true`, lazy state will be enabled for all invocations to this service.\n *\n * *NOTE:* You can set this field only if you register this endpoint against restate-server >= 1.4,\n * otherwise the service discovery will fail.\n */\n enableLazyState?: boolean;\n};\n\n/**\n * Define a Restate workflow.\n *\n *\n * @example Here is an example of how to define a workflow:\n * ```ts\n * const mywf = workflow({\n * name: \"mywf\",\n * handlers: {\n * run: async (ctx: WorkflowContext, argument: any) => {\n * return \"Hello World\";\n * }\n * }\n * });\n * ```\n *\n * ### Note:\n * * That a workflow must contain exactly one handler named 'run', and this handler must accept as a first argument a WorkflowContext.\n * * The workflow handlers other than 'run' must accept as a first argument a WorkflowSharedContext.\n * * The workflow handlers can not be named 'workflowSubmit', 'workflowAttach', 'workflowOutput' - as these are reserved keywords.\n *\n * @example To use the workflow, you can bind it to an endpoint:\n * ```ts\n * endpoint.bind(mywf)\n * ```\n *\n * @example To interact with the workflow, you can use the workflow client:\n * ```ts\n * const client = ctx.workflowClient<typeof mywf>({ name: \"mywf\"});\n * const res = await client.run(\"Hello\");\n * ```\n *\n * To use the workflow client from any other environment (like a browser), please refer to the documentation.\n * https://docs.restate.dev\n *\n *\n *\n * @param name the workflow name\n * @param handlers the handlers for the workflow.\n */\nexport const workflow = <P extends string, M>(workflow: {\n name: P;\n handlers: WorkflowOpts<M> & ThisType<M>;\n description?: string;\n metadata?: Record<string, string>;\n options?: WorkflowOptions;\n}): WorkflowDefinition<P, M> => {\n if (!workflow.handlers) {\n throw new Error(\"workflow must contain handlers\");\n }\n\n //\n // Add the main 'run' handler\n //\n const runHandler = workflow.handlers[\"run\"];\n let runWrapper: HandlerWrapper;\n\n if (runHandler instanceof HandlerWrapper) {\n runWrapper = runHandler;\n } else if (runHandler instanceof Function) {\n runWrapper =\n HandlerWrapper.fromHandler(runHandler) ??\n HandlerWrapper.from(HandlerKind.WORKFLOW, runHandler);\n } else {\n throw new TypeError(`Missing main workflow handler, named 'run'`);\n }\n if (runWrapper.kind !== HandlerKind.WORKFLOW) {\n throw new TypeError(\n `Workflow's main handler handler run, must be of type workflow'`\n );\n }\n\n const handlers = [[\"run\", runWrapper.transpose()]];\n\n //\n // Add all the shared handlers now\n //\n\n for (const [name, handler] of Object.entries(workflow.handlers)) {\n if (name === \"run\") {\n continue;\n }\n let wrapper: HandlerWrapper;\n\n if (handler instanceof HandlerWrapper) {\n wrapper = handler;\n } else if (handler instanceof Function) {\n wrapper =\n HandlerWrapper.fromHandler(handler) ??\n HandlerWrapper.from(HandlerKind.SHARED, handler);\n } else {\n throw new TypeError(`Unexpected handler type ${name}`);\n }\n if (wrapper.kind === HandlerKind.WORKFLOW) {\n throw new TypeError(\n `A workflow must contain exactly one handler annotated as workflow, named 'run'. Please use a shared handler for any additional handlers`\n );\n }\n handlers.push([name, wrapper.transpose()]);\n }\n\n return {\n name: workflow.name,\n workflow: Object.fromEntries(handlers) as object,\n metadata: workflow.metadata,\n description: workflow.description,\n options: workflow.options,\n } as WorkflowDefinition<P, M>;\n};\n"],"mappings":";;;AAoDA,IAAa,OAAb,MAAa,KAAW;;;;;;CAMtB,O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_agent.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 pkg from \"../package.json\" with { type: \"json\" };\n\nexport const X_RESTATE_SERVER = `restate-sdk-typescript/${pkg.version}`;\n"],"mappings":";;;AAaA,MAAa,mBAAmB,0BAA0BA"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
//#region src/utils/completable_promise.ts
|
|
3
|
+
var CompletablePromise = class {
|
|
4
|
+
success;
|
|
5
|
+
failure;
|
|
6
|
+
promise;
|
|
7
|
+
constructor() {
|
|
8
|
+
this.promise = new Promise((resolve, reject) => {
|
|
9
|
+
this.success = resolve;
|
|
10
|
+
this.failure = reject;
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
resolve(value) {
|
|
14
|
+
this.success(value);
|
|
15
|
+
}
|
|
16
|
+
reject(reason) {
|
|
17
|
+
this.failure(reason);
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
//#endregion
|
|
22
|
+
exports.CompletablePromise = CompletablePromise;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/utils/completable_promise.ts
|
|
2
|
+
var CompletablePromise = class {
|
|
3
|
+
success;
|
|
4
|
+
failure;
|
|
5
|
+
promise;
|
|
6
|
+
constructor() {
|
|
7
|
+
this.promise = new Promise((resolve, reject) => {
|
|
8
|
+
this.success = resolve;
|
|
9
|
+
this.failure = reject;
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
resolve(value) {
|
|
13
|
+
this.success(value);
|
|
14
|
+
}
|
|
15
|
+
reject(reason) {
|
|
16
|
+
this.failure(reason);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
//#endregion
|
|
21
|
+
export { CompletablePromise };
|
|
22
|
+
//# sourceMappingURL=completable_promise.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"completable_promise.js","names":[],"sources":["../../src/utils/completable_promise.ts"],"sourcesContent":["/*\n * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH\n *\n * This file is part of the Restate SDK for Node.js/TypeScript,\n * which is released under the MIT license.\n *\n * You can find a copy of the license in file LICENSE in the root\n * directory of this repository or package, or at\n * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE\n */\n\n// Like https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\n// (not yet available in node)\nexport class CompletablePromise<T> {\n private success!: (value: T | PromiseLike<T>) => void;\n private failure!: (reason?: unknown) => void;\n\n public readonly promise: Promise<T>;\n\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.success = resolve;\n this.failure = reject;\n });\n }\n\n public resolve(value: T) {\n this.success(value);\n }\n\n public reject(reason?: unknown) {\n this.failure(reason);\n }\n}\n"],"mappings":";AAaA,IAAa,qBAAb,MAAmC;CACjC,AAAQ;CACR,AAAQ;CAER,AAAgB;CAEhB,cAAc;AACZ,OAAK,UAAU,IAAI,SAAS,SAAS,WAAW;AAC9C,QAAK,UAAU;AACf,QAAK,UAAU;IACf;;CAGJ,AAAO,QAAQ,OAAU;AACvB,OAAK,QAAQ,MAAM;;CAGrB,AAAO,OAAO,QAAkB;AAC9B,OAAK,QAAQ,OAAO"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
let node_buffer = require("node:buffer");
|
|
3
|
+
node_buffer = require_rolldown_runtime.__toESM(node_buffer);
|
|
4
|
+
|
|
5
|
+
//#region src/utils/rand.ts
|
|
6
|
+
var RandImpl = class RandImpl {
|
|
7
|
+
randstate256;
|
|
8
|
+
constructor(id, checkState = () => void 0) {
|
|
9
|
+
this.checkState = checkState;
|
|
10
|
+
if (typeof id === "bigint") {
|
|
11
|
+
let x = id & RandImpl.U64_MASK;
|
|
12
|
+
const next = () => {
|
|
13
|
+
x = x + 11400714819323198485n & RandImpl.U64_MASK;
|
|
14
|
+
let z = x;
|
|
15
|
+
z ^= z >> 30n;
|
|
16
|
+
z = z * 13787848793156543929n & RandImpl.U64_MASK;
|
|
17
|
+
z ^= z >> 27n;
|
|
18
|
+
z = z * 10723151780598845931n & RandImpl.U64_MASK;
|
|
19
|
+
z ^= z >> 31n;
|
|
20
|
+
return z & RandImpl.U64_MASK;
|
|
21
|
+
};
|
|
22
|
+
this.randstate256 = [
|
|
23
|
+
next(),
|
|
24
|
+
next(),
|
|
25
|
+
next(),
|
|
26
|
+
next()
|
|
27
|
+
];
|
|
28
|
+
} else this.randstate256 = id;
|
|
29
|
+
}
|
|
30
|
+
static U64_MASK = (1n << 64n) - 1n;
|
|
31
|
+
u64() {
|
|
32
|
+
const result = RandImpl.rotl(this.randstate256[0] + this.randstate256[3] & RandImpl.U64_MASK, 23n) + this.randstate256[0] & RandImpl.U64_MASK;
|
|
33
|
+
const t = this.randstate256[1] << 17n & RandImpl.U64_MASK;
|
|
34
|
+
this.randstate256[2] ^= this.randstate256[0];
|
|
35
|
+
this.randstate256[3] ^= this.randstate256[1];
|
|
36
|
+
this.randstate256[1] ^= this.randstate256[2];
|
|
37
|
+
this.randstate256[0] ^= this.randstate256[3];
|
|
38
|
+
this.randstate256[2] ^= t;
|
|
39
|
+
this.randstate256[3] = RandImpl.rotl(this.randstate256[3], 45n);
|
|
40
|
+
return result;
|
|
41
|
+
}
|
|
42
|
+
static rotl(x, k) {
|
|
43
|
+
return x << k & RandImpl.U64_MASK | x >> 64n - k;
|
|
44
|
+
}
|
|
45
|
+
static U53_MASK = (1n << 53n) - 1n;
|
|
46
|
+
random() {
|
|
47
|
+
this.checkState("rand.random");
|
|
48
|
+
const u53 = this.u64() & RandImpl.U53_MASK;
|
|
49
|
+
return Number(u53) / 2 ** 53;
|
|
50
|
+
}
|
|
51
|
+
uuidv4() {
|
|
52
|
+
this.checkState("rand.uuidv4");
|
|
53
|
+
const buf = node_buffer.Buffer.alloc(16);
|
|
54
|
+
buf.writeBigUInt64LE(this.u64(), 0);
|
|
55
|
+
buf.writeBigUInt64LE(this.u64(), 8);
|
|
56
|
+
buf[6] = buf[6] & 15 | 64;
|
|
57
|
+
buf[8] = buf[8] & 63 | 128;
|
|
58
|
+
return uuidStringify(buf);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const byteToHex = [];
|
|
62
|
+
for (let i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).slice(1));
|
|
63
|
+
/**
|
|
64
|
+
* Convert array of 16 byte values to UUID string format of the form:
|
|
65
|
+
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
|
|
66
|
+
*/
|
|
67
|
+
function uuidStringify(arr, offset = 0) {
|
|
68
|
+
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
exports.RandImpl = RandImpl;
|