@restatedev/restate-sdk-cloudflare-workers 1.9.1 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (265) hide show
  1. package/LICENSE +21 -0
  2. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  3. package/dist/common_api.cjs +25 -0
  4. package/dist/common_api.d.cts +30 -0
  5. package/dist/common_api.d.cts.map +1 -0
  6. package/dist/common_api.d.ts +30 -0
  7. package/dist/common_api.d.ts.map +1 -0
  8. package/dist/common_api.js +19 -0
  9. package/dist/common_api.js.map +1 -0
  10. package/dist/context.cjs +29 -0
  11. package/dist/context.d.cts +699 -0
  12. package/dist/context.d.cts.map +1 -0
  13. package/dist/context.d.ts +699 -0
  14. package/dist/context.d.ts.map +1 -0
  15. package/dist/context.js +29 -0
  16. package/dist/context.js.map +1 -0
  17. package/dist/context_impl.cjs +441 -0
  18. package/dist/context_impl.js +440 -0
  19. package/dist/context_impl.js.map +1 -0
  20. package/dist/endpoint/components.cjs +257 -0
  21. package/dist/endpoint/components.js +253 -0
  22. package/dist/endpoint/components.js.map +1 -0
  23. package/dist/endpoint/endpoint.cjs +117 -0
  24. package/dist/endpoint/endpoint.js +118 -0
  25. package/dist/endpoint/endpoint.js.map +1 -0
  26. package/dist/endpoint/fetch_endpoint.cjs +41 -0
  27. package/dist/endpoint/fetch_endpoint.d.cts +39 -0
  28. package/dist/endpoint/fetch_endpoint.d.cts.map +1 -0
  29. package/dist/endpoint/fetch_endpoint.d.ts +39 -0
  30. package/dist/endpoint/fetch_endpoint.d.ts.map +1 -0
  31. package/dist/endpoint/fetch_endpoint.js +42 -0
  32. package/dist/endpoint/fetch_endpoint.js.map +1 -0
  33. package/dist/endpoint/handlers/fetch.cjs +21 -0
  34. package/dist/endpoint/handlers/fetch.js +21 -0
  35. package/dist/endpoint/handlers/fetch.js.map +1 -0
  36. package/dist/endpoint/handlers/generic.cjs +328 -0
  37. package/dist/endpoint/handlers/generic.js +324 -0
  38. package/dist/endpoint/handlers/generic.js.map +1 -0
  39. package/dist/endpoint/handlers/lambda.cjs +93 -0
  40. package/dist/endpoint/handlers/lambda.js +89 -0
  41. package/dist/endpoint/handlers/lambda.js.map +1 -0
  42. package/dist/endpoint/lambda_endpoint.cjs +36 -0
  43. package/dist/endpoint/lambda_endpoint.d.cts +26 -0
  44. package/dist/endpoint/lambda_endpoint.d.cts.map +1 -0
  45. package/dist/endpoint/lambda_endpoint.d.ts +26 -0
  46. package/dist/endpoint/lambda_endpoint.d.ts.map +1 -0
  47. package/dist/endpoint/lambda_endpoint.js +37 -0
  48. package/dist/endpoint/lambda_endpoint.js.map +1 -0
  49. package/dist/endpoint/node_endpoint.cjs +101 -0
  50. package/dist/endpoint/node_endpoint.js +99 -0
  51. package/dist/endpoint/node_endpoint.js.map +1 -0
  52. package/dist/endpoint/types.d.cts +61 -0
  53. package/dist/endpoint/types.d.cts.map +1 -0
  54. package/dist/endpoint/types.d.ts +61 -0
  55. package/dist/endpoint/types.d.ts.map +1 -0
  56. package/dist/endpoint/withOptions.cjs +15 -0
  57. package/dist/endpoint/withOptions.js +15 -0
  58. package/dist/endpoint/withOptions.js.map +1 -0
  59. package/dist/endpoint.d.cts +112 -0
  60. package/dist/endpoint.d.cts.map +1 -0
  61. package/dist/endpoint.d.ts +112 -0
  62. package/dist/endpoint.d.ts.map +1 -0
  63. package/dist/fetch.cjs +83 -0
  64. package/dist/fetch.d.cts +52 -0
  65. package/dist/fetch.d.cts.map +1 -0
  66. package/dist/fetch.d.ts +52 -0
  67. package/dist/fetch.d.ts.map +1 -0
  68. package/dist/{esm/src/fetch.js → fetch.js} +15 -18
  69. package/dist/fetch.js.map +1 -0
  70. package/dist/index.cjs +48 -0
  71. package/dist/index.d.cts +9 -0
  72. package/dist/index.d.ts +9 -0
  73. package/dist/index.js +7 -0
  74. package/dist/io.cjs +48 -0
  75. package/dist/io.js +48 -0
  76. package/dist/io.js.map +1 -0
  77. package/dist/lambda.cjs +74 -0
  78. package/dist/lambda.d.cts +32 -0
  79. package/dist/lambda.d.cts.map +1 -0
  80. package/dist/lambda.d.ts +32 -0
  81. package/dist/lambda.d.ts.map +1 -0
  82. package/dist/lambda.js +35 -0
  83. package/dist/lambda.js.map +1 -0
  84. package/dist/logging/console_logger_transport.cjs +54 -0
  85. package/dist/logging/console_logger_transport.js +54 -0
  86. package/dist/logging/console_logger_transport.js.map +1 -0
  87. package/dist/logging/logger.cjs +43 -0
  88. package/dist/logging/logger.js +44 -0
  89. package/dist/logging/logger.js.map +1 -0
  90. package/dist/logging/logger_transport.cjs +42 -0
  91. package/dist/logging/logger_transport.d.cts +57 -0
  92. package/dist/logging/logger_transport.d.cts.map +1 -0
  93. package/dist/logging/logger_transport.d.ts +57 -0
  94. package/dist/logging/logger_transport.d.ts.map +1 -0
  95. package/dist/logging/logger_transport.js +40 -0
  96. package/dist/logging/logger_transport.js.map +1 -0
  97. package/dist/node.cjs +90 -0
  98. package/dist/node.d.cts +51 -0
  99. package/dist/node.d.cts.map +1 -0
  100. package/dist/node.d.ts +51 -0
  101. package/dist/node.d.ts.map +1 -0
  102. package/dist/node.js +50 -0
  103. package/dist/node.js.map +1 -0
  104. package/dist/package.cjs +11 -0
  105. package/dist/package.js +6 -0
  106. package/dist/package.js.map +1 -0
  107. package/dist/promises.cjs +234 -0
  108. package/dist/promises.js +226 -0
  109. package/dist/promises.js.map +1 -0
  110. package/dist/types/errors.cjs +110 -0
  111. package/dist/types/errors.d.cts +71 -0
  112. package/dist/types/errors.d.cts.map +1 -0
  113. package/dist/types/errors.d.ts +71 -0
  114. package/dist/types/errors.d.ts.map +1 -0
  115. package/dist/types/errors.js +102 -0
  116. package/dist/types/errors.js.map +1 -0
  117. package/dist/types/rpc.cjs +425 -0
  118. package/dist/types/rpc.d.cts +580 -0
  119. package/dist/types/rpc.d.cts.map +1 -0
  120. package/dist/types/rpc.d.ts +580 -0
  121. package/dist/types/rpc.d.ts.map +1 -0
  122. package/dist/types/rpc.js +406 -0
  123. package/dist/types/rpc.js.map +1 -0
  124. package/dist/user_agent.cjs +7 -0
  125. package/dist/user_agent.js +8 -0
  126. package/dist/user_agent.js.map +1 -0
  127. package/dist/utils/completable_promise.cjs +22 -0
  128. package/dist/utils/completable_promise.js +22 -0
  129. package/dist/utils/completable_promise.js.map +1 -0
  130. package/dist/utils/rand.cjs +72 -0
  131. package/dist/utils/rand.js +71 -0
  132. package/dist/utils/rand.js.map +1 -0
  133. package/dist/utils/streams.cjs +14 -0
  134. package/dist/utils/streams.js +13 -0
  135. package/dist/utils/streams.js.map +1 -0
  136. package/package.json +30 -52
  137. package/dist/esm/src/common_api.d.ts +0 -37
  138. package/dist/esm/src/common_api.d.ts.map +0 -1
  139. package/dist/esm/src/common_api.js +0 -32
  140. package/dist/esm/src/common_api.js.map +0 -1
  141. package/dist/esm/src/context.d.ts +0 -695
  142. package/dist/esm/src/context.d.ts.map +0 -1
  143. package/dist/esm/src/context.js +0 -87
  144. package/dist/esm/src/context.js.map +0 -1
  145. package/dist/esm/src/context_impl.d.ts +0 -69
  146. package/dist/esm/src/context_impl.d.ts.map +0 -1
  147. package/dist/esm/src/context_impl.js +0 -592
  148. package/dist/esm/src/context_impl.js.map +0 -1
  149. package/dist/esm/src/endpoint/components.d.ts +0 -97
  150. package/dist/esm/src/endpoint/components.d.ts.map +0 -1
  151. package/dist/esm/src/endpoint/components.js +0 -343
  152. package/dist/esm/src/endpoint/components.js.map +0 -1
  153. package/dist/esm/src/endpoint/discovery.d.ts +0 -184
  154. package/dist/esm/src/endpoint/discovery.d.ts.map +0 -1
  155. package/dist/esm/src/endpoint/discovery.js +0 -8
  156. package/dist/esm/src/endpoint/discovery.js.map +0 -1
  157. package/dist/esm/src/endpoint/endpoint.d.ts +0 -39
  158. package/dist/esm/src/endpoint/endpoint.d.ts.map +0 -1
  159. package/dist/esm/src/endpoint/endpoint.js +0 -155
  160. package/dist/esm/src/endpoint/endpoint.js.map +0 -1
  161. package/dist/esm/src/endpoint/fetch_endpoint.d.ts +0 -49
  162. package/dist/esm/src/endpoint/fetch_endpoint.d.ts.map +0 -1
  163. package/dist/esm/src/endpoint/fetch_endpoint.js +0 -49
  164. package/dist/esm/src/endpoint/fetch_endpoint.js.map +0 -1
  165. package/dist/esm/src/endpoint/handlers/fetch.d.ts +0 -5
  166. package/dist/esm/src/endpoint/handlers/fetch.d.ts.map +0 -1
  167. package/dist/esm/src/endpoint/handlers/fetch.js +0 -31
  168. package/dist/esm/src/endpoint/handlers/fetch.js.map +0 -1
  169. package/dist/esm/src/endpoint/handlers/generic.d.ts +0 -61
  170. package/dist/esm/src/endpoint/handlers/generic.d.ts.map +0 -1
  171. package/dist/esm/src/endpoint/handlers/generic.js +0 -470
  172. package/dist/esm/src/endpoint/handlers/generic.js.map +0 -1
  173. package/dist/esm/src/endpoint/handlers/lambda.d.ts +0 -10
  174. package/dist/esm/src/endpoint/handlers/lambda.d.ts.map +0 -1
  175. package/dist/esm/src/endpoint/handlers/lambda.js +0 -143
  176. package/dist/esm/src/endpoint/handlers/lambda.js.map +0 -1
  177. package/dist/esm/src/endpoint/lambda_endpoint.d.ts +0 -30
  178. package/dist/esm/src/endpoint/lambda_endpoint.d.ts.map +0 -1
  179. package/dist/esm/src/endpoint/lambda_endpoint.js +0 -48
  180. package/dist/esm/src/endpoint/lambda_endpoint.js.map +0 -1
  181. package/dist/esm/src/endpoint/node_endpoint.d.ts +0 -16
  182. package/dist/esm/src/endpoint/node_endpoint.d.ts.map +0 -1
  183. package/dist/esm/src/endpoint/node_endpoint.js +0 -124
  184. package/dist/esm/src/endpoint/node_endpoint.js.map +0 -1
  185. package/dist/esm/src/endpoint/types.d.ts +0 -55
  186. package/dist/esm/src/endpoint/types.d.ts.map +0 -1
  187. package/dist/esm/src/endpoint/types.js +0 -2
  188. package/dist/esm/src/endpoint/types.js.map +0 -1
  189. package/dist/esm/src/endpoint/withOptions.d.ts +0 -4
  190. package/dist/esm/src/endpoint/withOptions.d.ts.map +0 -1
  191. package/dist/esm/src/endpoint/withOptions.js +0 -19
  192. package/dist/esm/src/endpoint/withOptions.js.map +0 -1
  193. package/dist/esm/src/endpoint.d.ts +0 -108
  194. package/dist/esm/src/endpoint.d.ts.map +0 -1
  195. package/dist/esm/src/endpoint.js +0 -12
  196. package/dist/esm/src/endpoint.js.map +0 -1
  197. package/dist/esm/src/fetch.d.ts +0 -43
  198. package/dist/esm/src/fetch.d.ts.map +0 -1
  199. package/dist/esm/src/fetch.js.map +0 -1
  200. package/dist/esm/src/generated/version.d.ts +0 -2
  201. package/dist/esm/src/generated/version.d.ts.map +0 -1
  202. package/dist/esm/src/generated/version.js +0 -2
  203. package/dist/esm/src/generated/version.js.map +0 -1
  204. package/dist/esm/src/io.d.ts +0 -24
  205. package/dist/esm/src/io.d.ts.map +0 -1
  206. package/dist/esm/src/io.js +0 -73
  207. package/dist/esm/src/io.js.map +0 -1
  208. package/dist/esm/src/lambda.d.ts +0 -23
  209. package/dist/esm/src/lambda.d.ts.map +0 -1
  210. package/dist/esm/src/lambda.js +0 -37
  211. package/dist/esm/src/lambda.js.map +0 -1
  212. package/dist/esm/src/logging/console_logger_transport.d.ts +0 -5
  213. package/dist/esm/src/logging/console_logger_transport.d.ts.map +0 -1
  214. package/dist/esm/src/logging/console_logger_transport.js +0 -94
  215. package/dist/esm/src/logging/console_logger_transport.js.map +0 -1
  216. package/dist/esm/src/logging/logger.d.ts +0 -10
  217. package/dist/esm/src/logging/logger.d.ts.map +0 -1
  218. package/dist/esm/src/logging/logger.js +0 -57
  219. package/dist/esm/src/logging/logger.js.map +0 -1
  220. package/dist/esm/src/logging/logger_transport.d.ts +0 -52
  221. package/dist/esm/src/logging/logger_transport.d.ts.map +0 -1
  222. package/dist/esm/src/logging/logger_transport.js +0 -55
  223. package/dist/esm/src/logging/logger_transport.js.map +0 -1
  224. package/dist/esm/src/node.d.ts +0 -39
  225. package/dist/esm/src/node.d.ts.map +0 -1
  226. package/dist/esm/src/node.js +0 -52
  227. package/dist/esm/src/node.js.map +0 -1
  228. package/dist/esm/src/promises.d.ts +0 -111
  229. package/dist/esm/src/promises.d.ts.map +0 -1
  230. package/dist/esm/src/promises.js +0 -314
  231. package/dist/esm/src/promises.js.map +0 -1
  232. package/dist/esm/src/public_api.d.ts +0 -2
  233. package/dist/esm/src/public_api.d.ts.map +0 -1
  234. package/dist/esm/src/public_api.js +0 -12
  235. package/dist/esm/src/public_api.js.map +0 -1
  236. package/dist/esm/src/types/errors.d.ts +0 -74
  237. package/dist/esm/src/types/errors.d.ts.map +0 -1
  238. package/dist/esm/src/types/errors.js +0 -128
  239. package/dist/esm/src/types/errors.js.map +0 -1
  240. package/dist/esm/src/types/rpc.d.ts +0 -620
  241. package/dist/esm/src/types/rpc.d.ts.map +0 -1
  242. package/dist/esm/src/types/rpc.js +0 -577
  243. package/dist/esm/src/types/rpc.js.map +0 -1
  244. package/dist/esm/src/user_agent.d.ts +0 -2
  245. package/dist/esm/src/user_agent.d.ts.map +0 -1
  246. package/dist/esm/src/user_agent.js +0 -13
  247. package/dist/esm/src/user_agent.js.map +0 -1
  248. package/dist/esm/src/utils/completable_promise.d.ts +0 -9
  249. package/dist/esm/src/utils/completable_promise.d.ts.map +0 -1
  250. package/dist/esm/src/utils/completable_promise.js +0 -30
  251. package/dist/esm/src/utils/completable_promise.js.map +0 -1
  252. package/dist/esm/src/utils/rand.d.ts +0 -13
  253. package/dist/esm/src/utils/rand.d.ts.map +0 -1
  254. package/dist/esm/src/utils/rand.js +0 -109
  255. package/dist/esm/src/utils/rand.js.map +0 -1
  256. package/dist/esm/src/utils/streams.d.ts +0 -3
  257. package/dist/esm/src/utils/streams.d.ts.map +0 -1
  258. package/dist/esm/src/utils/streams.js +0 -20
  259. package/dist/esm/src/utils/streams.js.map +0 -1
  260. package/dist/esm/tsconfig.tsbuildinfo +0 -1
  261. /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings.d.ts +0 -0
  262. /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings.js +0 -0
  263. /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.js +0 -0
  264. /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm +0 -0
  265. /package/dist/{esm/src/endpoint → endpoint}/handlers/vm/sdk_shared_core_wasm_bindings_bg.wasm.d.ts +0 -0
@@ -0,0 +1,699 @@
1
+ import { TerminalError } from "./types/errors.cjs";
2
+ import { Client, SendClient } from "./types/rpc.cjs";
3
+ import { Duration, RestateContext, RestateObjectContext, RestateObjectSharedContext, RestateWorkflowContext, RestateWorkflowSharedContext, Serde, Service, ServiceDefinitionFrom, VirtualObject, VirtualObjectDefinitionFrom, Workflow, WorkflowDefinitionFrom } from "@restatedev/restate-sdk-core";
4
+
5
+ //#region src/context.d.ts
6
+
7
+ /**
8
+ * Represents the original request as sent to this handler.
9
+ *
10
+ * A request object includes the request headers, and the raw unparsed
11
+ * request body.
12
+ */
13
+ interface Request {
14
+ /**
15
+ * The unique id that identifies the current function invocation. This id is guaranteed to be
16
+ * unique across invocations, but constant across reties and suspensions.
17
+ */
18
+ readonly id: string;
19
+ /**
20
+ * Request headers - the following headers capture the original invocation headers, as provided to
21
+ * the ingress.
22
+ */
23
+ readonly headers: ReadonlyMap<string, string>;
24
+ /**
25
+ * Attempt headers - the following headers are sent by the restate runtime.
26
+ * These headers are attempt specific, generated by the restate runtime uniquely for each attempt.
27
+ * These headers might contain information such as the W3C trace context, and attempt specific information.
28
+ */
29
+ readonly attemptHeaders: ReadonlyMap<string, string | string[] | undefined>;
30
+ /**
31
+ * Raw unparsed request body
32
+ */
33
+ readonly body: Uint8Array;
34
+ /**
35
+ * Extra arguments provided to the request handler:
36
+ * Lambda: [Context]
37
+ * Cloudflare workers: [Env, ExecutionContext]
38
+ * Deno: [ConnInfo]
39
+ * Bun: [Server]
40
+ * These arguments can contain request-specific values that could change after a suspension.
41
+ * Care should be taken to use them deterministically.
42
+ */
43
+ readonly extraArgs: unknown[];
44
+ /**
45
+ * This is a signal that is aborted when the current attempt has been completed either successful or unsuccessfully.
46
+ * When the signal is aborted, the current attempt has been completed and the handler should not perform any more work, other
47
+ * than cleanup any external resources that might be shared across attempts (e.g. database connections).
48
+ */
49
+ readonly attemptCompletedSignal: AbortSignal;
50
+ }
51
+ type TypedState = Record<string, any>;
52
+ type UntypedState = {
53
+ _: never;
54
+ };
55
+ /**
56
+ * Key value store operations. Only keyed services have an attached key-value store.
57
+ */
58
+ interface KeyValueStore<TState extends TypedState> {
59
+ /**
60
+ * Get/retrieve state from the Restate runtime.
61
+ * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`
62
+ * and deserialized with `JSON.parse(value.toString()) as T`.
63
+ *
64
+ * @param name key of the state to retrieve
65
+ * @returns a Promise that is resolved with the value of the state key
66
+ *
67
+ * @example
68
+ * const state = await ctx.get<string>("STATE");
69
+ */
70
+ get<TValue, TKey extends keyof TState = string>(name: TState extends UntypedState ? string : TKey, serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;
71
+ stateKeys(): Promise<Array<string>>;
72
+ /**
73
+ * Set/store state in the Restate runtime.
74
+ * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`
75
+ * and deserialized with `JSON.parse(value.toString()) as T`.
76
+ *
77
+ * @param name key of the state to set
78
+ * @param value value to set
79
+ *
80
+ * @example
81
+ * ctx.set("STATE", "Hello");
82
+ */
83
+ set<TValue, TKey extends keyof TState = string>(name: TState extends UntypedState ? string : TKey, value: TState extends UntypedState ? TValue : TState[TKey], serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>): void;
84
+ /**
85
+ * Clear/delete state in the Restate runtime.
86
+ * @param name key of the state to delete
87
+ *
88
+ * @example
89
+ * ctx.clear("STATE");
90
+ */
91
+ clear<TKey extends keyof TState>(name: TState extends UntypedState ? string : TKey): void;
92
+ /**
93
+ * Clear/delete all the state entries in the Restate runtime.
94
+ *
95
+ * @example
96
+ * ctx.clearAll();
97
+ */
98
+ clearAll(): void;
99
+ }
100
+ /**
101
+ * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead
102
+ */
103
+ interface SendOptions {
104
+ /**
105
+ * @deprecated SendOptions on the client factory are deprecated, please use `restate.rpc.sendOpts` instead
106
+ */
107
+ delay?: number;
108
+ }
109
+ interface ContextDate {
110
+ /** Returns the number of milliseconds elapsed since midnight, January 1, 1970 Universal Coordinated Time (UTC).
111
+ * This is equivalent to Date.now()
112
+ */
113
+ now(): Promise<number>;
114
+ /** Returns the JSON representation of the current date.
115
+ * This is equivalent to new Date().toJSON()
116
+ **/
117
+ toJSON(): Promise<string>;
118
+ }
119
+ /**
120
+ * A function that can be run and its result durably persisted by Restate.
121
+ */
122
+ type RunAction<T> = (() => Promise<T>) | (() => T);
123
+ type RunOptions<T> = {
124
+ serde?: Serde<T>;
125
+ /**
126
+ * Max number of attempts (including the initial), before giving up.
127
+ *
128
+ * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.
129
+ */
130
+ maxRetryAttempts?: number;
131
+ /**
132
+ * @deprecated Use `maxRetryDuration` instead.
133
+ */
134
+ maxRetryDurationMillis?: number;
135
+ /**
136
+ * Max duration of retries, before giving up.
137
+ *
138
+ * When giving up, `ctx.run` will throw a `TerminalError` wrapping the original error message.
139
+ *
140
+ * If a number is provided, it will be interpreted as milliseconds.
141
+ */
142
+ maxRetryDuration?: Duration | number;
143
+ /**
144
+ * @deprecated Use `initialRetryInterval` instead.
145
+ */
146
+ initialRetryIntervalMillis?: number;
147
+ /**
148
+ * Initial interval for the first retry attempt.
149
+ * Retry interval will grow by a factor specified in `retryIntervalFactor`.
150
+ *
151
+ * The default is 50 milliseconds.
152
+ *
153
+ * If a number is provided, it will be interpreted as milliseconds.
154
+ */
155
+ initialRetryInterval?: Duration | number;
156
+ /**
157
+ * @deprecated Use `maxRetryInterval` instead.
158
+ */
159
+ maxRetryIntervalMillis?: number;
160
+ /**
161
+ * Max interval between retries.
162
+ * Retry interval will grow by a factor specified in `retryIntervalFactor`.
163
+ *
164
+ * The default is 10 seconds.
165
+ *
166
+ * If a number is provided, it will be interpreted as milliseconds.
167
+ */
168
+ maxRetryInterval?: Duration | number;
169
+ /**
170
+ * Exponentiation factor to use when computing the next retry delay.
171
+ *
172
+ * The default value is `2`, meaning retry interval will double at each attempt.
173
+ */
174
+ retryIntervalFactor?: number;
175
+ };
176
+ /**
177
+ * Call a handler directly avoiding restate's type safety checks.
178
+ * This is a generic mechanism to invoke handlers directly by only knowing
179
+ * the service and handler name, (or key in the case of objects or workflows)
180
+ */
181
+ type GenericCall<REQ, RES> = {
182
+ service: string;
183
+ method: string;
184
+ parameter: REQ;
185
+ key?: string;
186
+ headers?: Record<string, string>;
187
+ inputSerde?: Serde<REQ>;
188
+ outputSerde?: Serde<RES>;
189
+ idempotencyKey?: string;
190
+ };
191
+ /**
192
+ * Send a message to an handler directly avoiding restate's type safety checks.
193
+ * This is a generic mechanism to invoke handlers directly by only knowing
194
+ * the service and handler name, (or key in the case of objects or workflows)
195
+ */
196
+ type GenericSend<REQ> = {
197
+ service: string;
198
+ method: string;
199
+ parameter: REQ;
200
+ key?: string;
201
+ headers?: Record<string, string>;
202
+ inputSerde?: Serde<REQ>;
203
+ delay?: Duration | number;
204
+ idempotencyKey?: string;
205
+ };
206
+ /**
207
+ * The context that gives access to all Restate-backed operations, for example
208
+ * - sending reliable messages / RPC through Restate
209
+ * - execute non-deterministic closures and memoize their result
210
+ * - sleeps and delayed calls
211
+ * - awakeables
212
+ * - ...
213
+ *
214
+ * Virtual objects can also access their key-value store using the {@link ObjectContext}.
215
+ *
216
+ */
217
+ interface Context extends RestateContext {
218
+ /**
219
+ * Deterministic random methods; these are inherently predictable (seeded on the invocation ID, which is not secret)
220
+ * and so should not be used for any cryptographic purposes. They are useful for identifiers, idempotency keys,
221
+ * and for uniform sampling from a set of options. If a cryptographically secure value is needed, please generate that
222
+ * externally and capture the result with a side effect.
223
+ *
224
+ * Calls to these methods from inside `ctx.run` are disallowed and will fail - side effects must be idempotent, and
225
+ * these calls are not.
226
+ */
227
+ rand: Rand;
228
+ /**
229
+ * Console to use for logging. It attaches to each log message some contextual information,
230
+ * such as invoked service method and invocation id, and automatically excludes logs during replay.
231
+ */
232
+ console: Console;
233
+ /**
234
+ * Deterministic date.
235
+ */
236
+ date: ContextDate;
237
+ /**
238
+ * Run an operation and store the result in Restate. The operation will thus not
239
+ * be re-run during a later replay, but take the durable result from Restate.
240
+ *
241
+ * This let you capture potentially non-deterministic computation and interaction
242
+ * with external systems in a safe way.
243
+ *
244
+ * Failure semantics are:
245
+ * - If an operation has run and persisted before, the result (value or Error) will be
246
+ * taken from the Restate journal.
247
+ * - There is a small window where an action may be re-run, if a failure
248
+ * occurred between a successful run and persisting the result.
249
+ * - No second action will be run while a previous run's result is not
250
+ * yet durable. That way, effects that build on top of each other can assume
251
+ * deterministic results from previous runs, and at most one run will be
252
+ * re-executed on replay (the latest, if the failure happened in the small windows
253
+ * described above).
254
+ *
255
+ * You can customize retry options by either:
256
+ *
257
+ * - Providing retry policy options in {@link RunOptions}
258
+ * - Throwing {@link RetryableError}, providing `retryAfter` option. This can be especially useful when interacting with HTTP requests returning the `Retry-After` header. You can combine the usage of throwing {@link RetryableError} with the `maxRetryAttempts`/`maxRetryDuration` from {@link RunOptions}.
259
+ *
260
+ * @example Run some external action and persist its result
261
+ * ```ts
262
+ * const result = await ctx.run(someExternalAction)
263
+ *```
264
+ * @example Add some retry options
265
+ * ```ts
266
+ * const result = await ctx.run("my action", someExternalAction, { maxRetryAttempts: 10 })
267
+ * ```
268
+ * @example Terminal errors and retryable errors
269
+ * ```ts
270
+ * await ctx.run("payment action", async () => {
271
+ * const result = await paymentProvider.charge(txId, paymentInfo);
272
+ * if (result.paymentRejected) {
273
+ * // this action will not be retried anymore
274
+ * throw new TerminalError("Payment failed");
275
+ * } else if (result.paymentGatewayBusy) {
276
+ * // restate will retry automatically
277
+ * // to bound retries, use RunOptions
278
+ * throw new Error("Payment gateway busy");
279
+ * } else {
280
+ * // success!
281
+ * }
282
+ * });
283
+ * ```
284
+ * @example Retryable error with custom retry delay
285
+ * ```ts
286
+ * await ctx.run("payment action", async () => {
287
+ * const res = fetch(...);
288
+ * if (!res.ok) {
289
+ * // Read Retry-After header
290
+ * const retryAfterHeader = res.headers['Retry-After']
291
+ *
292
+ * // Use RetryableError to customize in how long to retry
293
+ * throw RetryableError.from(cause, { retryAfter: { seconds: retryAfterHeader } })
294
+ * }
295
+ * }, {
296
+ * // Retry at most ten times
297
+ * maxRetryAttempts: 10
298
+ * });
299
+ * ```
300
+ *
301
+ * @param action The function to run.
302
+ */
303
+ run<T>(action: RunAction<T>): RestatePromise<T>;
304
+ /**
305
+ * Same as {@link run}, but providing a name, used for observability purposes.
306
+ */
307
+ run<T>(name: string, action: RunAction<T>): RestatePromise<T>;
308
+ /**
309
+ * See {@link run}
310
+ */
311
+ run<T>(name: string, action: RunAction<T>, options: RunOptions<T>): RestatePromise<T>;
312
+ /**
313
+ * Register an awakeable and pause the processing until the awakeable ID (and optional payload) have been returned to the service
314
+ * (via ctx.completeAwakeable(...)). The SDK deserializes the payload with `JSON.parse(result.toString()) as T`.
315
+ * @returns
316
+ * - id: the string ID that has to be used to complete the awakaeble by some external service
317
+ * - promise: the Promise that needs to be awaited and that is resolved with the payload that was supplied by the service which completed the awakeable
318
+ * @example Retryable errors and terminal errors
319
+ * const awakeable = ctx.awakeable<string>();
320
+ *
321
+ * // send the awakeable ID to some external service that will wake this one back up
322
+ * // The ID can be retrieved by:
323
+ * const id = awakeable.id;
324
+ *
325
+ * // ... send to external service ...
326
+ *
327
+ * // Wait for the external service to wake this service back up
328
+ * const result = await awakeable.promise;
329
+ */
330
+ awakeable<T>(serde?: Serde<T>): {
331
+ id: string;
332
+ promise: RestatePromise<T>;
333
+ };
334
+ /**
335
+ * Resolve an awakeable.
336
+ * @param id the string ID of the awakeable.
337
+ * This is supplied by the service that needs to be woken up.
338
+ * @param payload the payload to pass to the service that is woken up.
339
+ * The SDK serializes the payload with `Buffer.from(JSON.stringify(payload))`
340
+ * and deserializes it in the receiving service with `JSON.parse(result.toString()) as T`.
341
+ * @example Retryable error with custom retry delay
342
+ * // The sleeping service should have sent the awakeableIdentifier string to this service.
343
+ * ctx.resolveAwakeable(awakeableIdentifier, "hello");
344
+ */
345
+ resolveAwakeable<T>(id: string, payload?: T, serde?: Serde<T>): void;
346
+ /**
347
+ * Reject an awakeable. When rejecting, the service waiting on this awakeable will be woken up with a terminal error with the provided reason.
348
+ * @param id the string ID of the awakeable.
349
+ * This is supplied by the service that needs to be woken up.
350
+ * @param reason the reason of the rejection.
351
+ *
352
+ * @example
353
+ * // The sleeping service should have sent the awakeableIdentifier string to this service.
354
+ * ctx.rejectAwakeable(awakeableIdentifier, "super bad error");
355
+ */
356
+ rejectAwakeable(id: string, reason: string): void;
357
+ /**
358
+ * Sleep until a timeout has passed.
359
+ * @param duration either Duration type or milliseconds.
360
+ * @param name Observability name. This will be shown in the UI.
361
+ * This is a lower-bound.
362
+ *
363
+ * @example
364
+ * await ctx.sleep(1000);
365
+ */
366
+ sleep(duration: Duration | number, name?: string): RestatePromise<void>;
367
+ /**
368
+ * Makes a type-safe request/response RPC to the specified target service.
369
+ *
370
+ * The RPC goes through Restate and is guaranteed to be reliably delivered. The RPC is also
371
+ * journaled for durable execution and will thus not be duplicated when the handler is re-invoked
372
+ * for retries or after suspending.
373
+ *
374
+ * This call will return the result produced by the target handler, or the Error, if the target
375
+ * handler finishes with a Terminal Error.
376
+ *
377
+ * This call is a suspension point: The handler might suspend while awaiting the response and
378
+ * resume once the response is available.
379
+ *
380
+ * @example
381
+ * *Service Side:*
382
+ * ```ts
383
+ * const service = restate.service(
384
+ * name: "myservice",
385
+ * handlers: {
386
+ * someAction: async(ctx: restate.Context, req: string) => { ... },
387
+ * anotherAction: async(ctx: restate.Context, count: number) => { ... }
388
+ * });
389
+ *
390
+ * // option 1: export only the type signature
391
+ * export type Service = typeof service;
392
+ *
393
+ *
394
+ * restate.serve({ services: [service], port: 9080 });
395
+ * ```
396
+ * *Client side:*
397
+ * ```ts
398
+ * // option 1: use only types and supply service name separately
399
+ * const result1 = await ctx.serviceClient<Service>({name: "myservice"}).someAction("hello!");
400
+ *
401
+ * // option 2: use full API spec
402
+ * type MyService: Service = { name: "myservice" };
403
+ * const result2 = await ctx.serviceClient(Service).anotherAction(1337);
404
+ * ```
405
+ */
406
+ serviceClient<D>(opts: ServiceDefinitionFrom<D>): Client<Service<D>>;
407
+ /**
408
+ * Same as {@link serviceClient} but for virtual objects.
409
+ *
410
+ * @param opts
411
+ * @param key the virtual object key
412
+ */
413
+ objectClient<D>(opts: VirtualObjectDefinitionFrom<D>, key: string): Client<VirtualObject<D>>;
414
+ /**
415
+ * Same as {@link serviceClient} but for workflows.
416
+ *
417
+ * @param opts
418
+ * @param key the workflow key
419
+ */
420
+ workflowClient<D>(opts: WorkflowDefinitionFrom<D>, key: string): Client<Workflow<D>>;
421
+ /**
422
+ * Same as {@link objectSendClient} but for workflows.
423
+ *
424
+ * @param opts
425
+ * @param key the workflow key
426
+ */
427
+ workflowSendClient<D>(opts: WorkflowDefinitionFrom<D>, key: string): SendClient<Workflow<D>>;
428
+ /**
429
+ * Makes a type-safe one-way RPC to the specified target service. This method effectively behaves
430
+ * like enqueuing the message in a message queue.
431
+ *
432
+ * The message goes through Restate and is guaranteed to be reliably delivered. The RPC is also
433
+ * journaled for durable execution and will thus not be duplicated when the handler is re-invoked
434
+ * for retries or after suspending.
435
+ *
436
+ * This call will return immediately; the message sending happens asynchronously in the background.
437
+ * Despite that, the message is guaranteed to be sent, because the completion of the invocation that
438
+ * triggers the send (calls this function) happens logically after the sending. That means that any
439
+ * failure where the message does not reach Restate also cannot complete this invocation, and will
440
+ * hence recover this handler and (through the durable execution) recover the message to be sent.
441
+ *
442
+ * @example
443
+ * *Service Side:*
444
+ * ```ts
445
+ * const service = restate.service(
446
+ * name: "myservice",
447
+ * handlers: {
448
+ * someAction: async(ctx: restate.Context, req: string) => { ... },
449
+ * anotherAction: async(ctx: restate.Context, count: number) => { ... }
450
+ * });
451
+ *
452
+ * // option 1: export only the type signature of the router
453
+ * export type MyApi = typeof service;
454
+ *
455
+ * // option 2: export the API definition with type and name (name)
456
+ * const MyService: MyApi = { name: "myservice" };
457
+ *
458
+ * restate.serve({ services: [service], port: 9080 });
459
+ * ```
460
+ * *Client side:*
461
+ * ```ts
462
+ * // option 1: use only types and supply service name separately
463
+ * ctx.serviceSendClient<MyApi>({name: "myservice"}).someAction("hello!");
464
+ *
465
+ * // option 2: use full API spec
466
+ * ctx.serviceSendClient(MyService).anotherAction(1337);
467
+ * ```
468
+ */
469
+ serviceSendClient<D>(service: ServiceDefinitionFrom<D>, opts?: SendOptions): SendClient<Service<D>>;
470
+ /**
471
+ * Same as {@link serviceSendClient} but for virtual objects.
472
+ *
473
+ * @param obj
474
+ * @param key the virtual object key
475
+ * @param opts Send options
476
+ */
477
+ objectSendClient<D>(obj: VirtualObjectDefinitionFrom<D>, key: string, opts?: SendOptions): SendClient<VirtualObject<D>>;
478
+ genericCall<REQ = Uint8Array, RES = Uint8Array>(call: GenericCall<REQ, RES>): InvocationPromise<RES>;
479
+ genericSend<REQ = Uint8Array>(call: GenericSend<REQ>): InvocationHandle;
480
+ /**
481
+ * Returns the raw request that triggered that handler.
482
+ * Use that object to inspect the original request headers
483
+ */
484
+ request(): Request;
485
+ /**
486
+ * Cancel an invocation
487
+ *
488
+ * @param invocationId the invocation id to cancel
489
+ */
490
+ cancel(invocationId: InvocationId): void;
491
+ /**
492
+ * Attach to an invocation
493
+ *
494
+ * @param invocationId the invocation id to attach to
495
+ * @param serde the serde to use for the result, default to JSON serde.
496
+ */
497
+ attach<T>(invocationId: InvocationId, serde?: Serde<T>): RestatePromise<T>;
498
+ }
499
+ /**
500
+ * The context that gives access to all Restate-backed operations, for example
501
+ * - sending reliable messages / RPC through Restate
502
+ * - access/update state
503
+ * - execute non-deterministic closures and memoize their result
504
+ * - sleeps and delayed calls
505
+ * - awakeables
506
+ * - ...
507
+ *
508
+ * This context can be used only within virtual objects.
509
+ *
510
+ */
511
+ interface ObjectContext<TState extends TypedState = UntypedState> extends Context, KeyValueStore<TState>, RestateObjectContext {
512
+ key: string;
513
+ }
514
+ /**
515
+ * The context that gives access to all Restate-backed operations, for example
516
+ * - sending reliable messages / RPC through Restate
517
+ * - execute non-deterministic closures and memoize their result
518
+ * - sleeps and delayed calls
519
+ * - awakeables
520
+ * - ...
521
+ *
522
+ * This context can be used only within a shared virtual objects.
523
+ *
524
+ */
525
+ interface ObjectSharedContext<TState extends TypedState = UntypedState> extends Context, RestateObjectSharedContext {
526
+ key: string;
527
+ /**
528
+ * Get/retrieve state from the Restate runtime.
529
+ * Note that state objects are serialized with `Buffer.from(JSON.stringify(theObject))`
530
+ * and deserialized with `JSON.parse(value.toString()) as T`.
531
+ *
532
+ * @param name key of the state to retrieve
533
+ * @returns a Promise that is resolved with the value of the state key
534
+ *
535
+ * @example
536
+ * const state = await ctx.get<string>("STATE");
537
+ */
538
+ get<TValue, TKey extends keyof TState = string>(name: TState extends UntypedState ? string : TKey, serde?: Serde<TState extends UntypedState ? TValue : TState[TKey]>): Promise<(TState extends UntypedState ? TValue : TState[TKey]) | null>;
539
+ /**
540
+ * Retrieve all the state keys for this object.
541
+ */
542
+ stateKeys(): Promise<Array<string>>;
543
+ }
544
+ interface Rand {
545
+ /**
546
+ * Equivalent of JS `Math.random()` but deterministic; seeded by the invocation ID of the current invocation,
547
+ * each call will return a new pseudorandom float within the range [0,1)
548
+ */
549
+ random(): number;
550
+ /**
551
+ * Using the same random source and seed as random(), produce a UUID version 4 string. This is inherently predictable
552
+ * based on the invocation ID and should not be used in cryptographic contexts
553
+ */
554
+ uuidv4(): string;
555
+ }
556
+ /**
557
+ * A promise that can be combined using Promise combinators in RestateContext.
558
+ */
559
+ type RestatePromise<T> = Promise<T> & {
560
+ /**
561
+ * Creates a promise that awaits for the current promise up to the specified timeout duration.
562
+ * If the timeout is fired, this Promise will be rejected with a {@link TimeoutError}.
563
+ *
564
+ * @param millis duration of the sleep in millis.
565
+ * This is a lower-bound.
566
+ */
567
+ orTimeout(millis: Duration | number): RestatePromise<T>;
568
+ /**
569
+ * Creates a new {@link RestatePromise} that maps the result of this promise with
570
+ * the provided `mapper`, once this promise is fulfilled.
571
+ *
572
+ * **NOTE**: You **MUST** use this API when you need to map the result of a
573
+ * {@link RestatePromise} without `await`ing it, rather than using {@link Promise.then}.
574
+ * {@link Promise.then} is used by Restate to distinguish when awaiting an asynchronous operation,
575
+ * thus calling `.then` on several Restate promises can lead to concurrency issues.
576
+ *
577
+ * @param mapper the function to execute when this promise is fulfilled.
578
+ * If the promise completed successfully, `value` is provided as input, otherwise `failure` is provided as input.
579
+ * If this mapper returns a value, this value will be used to resolve the returned {@link RestatePromise}.
580
+ * If the mapper throws a {@link TerminalError}, this error will be used to reject the returned {@link RestatePromise}.
581
+ */
582
+ map<U>(mapper: (value?: T, failure?: TerminalError) => U): RestatePromise<U>;
583
+ };
584
+ /**
585
+ * Represents an invocation id.
586
+ * @see {@link InvocationIdParser}
587
+ */
588
+ type InvocationId = string & {
589
+ __brand: "InvocationId";
590
+ };
591
+ declare const InvocationIdParser: {
592
+ /**
593
+ * Creates an invocation id from a string.
594
+ * @param id the string to use as invocation id.
595
+ */
596
+ fromString(id: string): InvocationId;
597
+ };
598
+ type InvocationHandle = {
599
+ readonly invocationId: Promise<InvocationId>;
600
+ };
601
+ type InvocationPromise<T> = RestatePromise<T> & InvocationHandle;
602
+ declare const RestatePromise: {
603
+ /**
604
+ * Creates a Promise that is resolved with an array of results when all of the provided Promises
605
+ * resolve, or rejected when any Promise is rejected.
606
+ *
607
+ * See {@link Promise.all} for more details.
608
+ *
609
+ * @param values An iterable of Promises.
610
+ * @returns A new Promise.
611
+ */
612
+ all<const T extends readonly RestatePromise<unknown>[]>(values: T): RestatePromise<{ -readonly [P in keyof T]: Awaited<T[P]> }>;
613
+ /**
614
+ * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
615
+ * or rejected.
616
+ *
617
+ * See {@link Promise.race} for more details.
618
+ *
619
+ * @param values An iterable of Promises.
620
+ * @returns A new Promise.
621
+ */
622
+ race<const T extends readonly RestatePromise<unknown>[]>(values: T): RestatePromise<Awaited<T[number]>>;
623
+ /**
624
+ * Creates a promise that fulfills when any of the input's promises fulfills, with this first fulfillment value.
625
+ * It rejects when all the input's promises reject (including when an empty iterable is passed),
626
+ * with an AggregateError containing an array of rejection reasons.
627
+ *
628
+ * See {@link Promise.any} for more details.
629
+ *
630
+ * @param values An iterable of Promises.
631
+ * @returns A new Promise.
632
+ */
633
+ any<const T extends readonly RestatePromise<unknown>[]>(values: T): RestatePromise<Awaited<T[number]>>;
634
+ /**
635
+ * Creates a promise that fulfills when all the input's promises settle (including when an empty iterable is passed),
636
+ * with an array of objects that describe the outcome of each promise.
637
+ *
638
+ * See {@link Promise.allSettled} for more details.
639
+ *
640
+ * @param values An iterable of Promises.
641
+ * @returns A new Promise.
642
+ */
643
+ allSettled<const T extends readonly RestatePromise<unknown>[]>(values: T): RestatePromise<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>> }>;
644
+ };
645
+ /**
646
+ * Workflow bound durable promise
647
+ *
648
+ * See {@link WorkflowSharedContext} promise..
649
+ */
650
+ type DurablePromise<T> = Promise<T> & {
651
+ /**
652
+ * Returns the value of the promise, if it has been resolved.
653
+ */
654
+ peek(): Promise<T | undefined>;
655
+ /**
656
+ * Resolve the promise with the given value.
657
+ * @param value the value to resolve the promise with
658
+ */
659
+ resolve(value?: T): Promise<void>;
660
+ /**
661
+ * Reject the promise with the given error message.
662
+ * @param errorMsg the error message to use for rejection.
663
+ */
664
+ reject(errorMsg: string): Promise<void>;
665
+ /**
666
+ * Obtain a {@link RestatePromise} variant of this promise.
667
+ */
668
+ get(): RestatePromise<T>;
669
+ };
670
+ interface WorkflowSharedContext<TState extends TypedState = UntypedState> extends ObjectSharedContext<TState>, RestateWorkflowSharedContext {
671
+ /**
672
+ * Create a durable promise that can be resolved or rejected during the workflow execution.
673
+ * The promise is bound to the workflow and will be persisted across suspensions and retries.
674
+ * @example Add some retry options
675
+ * ```ts
676
+ * const wf = restate.workflow({
677
+ * name: "myWorkflow",
678
+ * handlers: {
679
+ * run: async (ctx: restate.WorkflowContext) => {
680
+ * // ... do some work ...
681
+ * const payment = await ctx.promise<Payment>("payment.succeeded");
682
+ * // ... do some more work ...
683
+ * },
684
+ *
685
+ * onPaymentSucceeded: async (ctx: restate.WorkflowContext, payment) => {
686
+ * // ... handle payment succeeded ...
687
+ * await ctx.promise("payment.succeeded").resolve(payment);
688
+ * }
689
+ * });
690
+ * ```
691
+ *
692
+ * @param name the name of the durable promise
693
+ */
694
+ promise<T>(name: string, serde?: Serde<T>): DurablePromise<T>;
695
+ }
696
+ interface WorkflowContext<TState extends TypedState = UntypedState> extends WorkflowSharedContext<TState>, ObjectContext<TState>, RestateWorkflowContext {}
697
+ //#endregion
698
+ export { Context, ContextDate, DurablePromise, GenericCall, GenericSend, InvocationHandle, InvocationId, InvocationIdParser, InvocationPromise, KeyValueStore, ObjectContext, ObjectSharedContext, Rand, Request, RestatePromise, RunAction, RunOptions, SendOptions, TypedState, UntypedState, WorkflowContext, WorkflowSharedContext };
699
+ //# sourceMappingURL=context.d.cts.map