@restatedev/restate-sdk 0.7.3-worker → 0.8.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 (231) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +29 -51
  3. package/dist/clients/workflow_client.d.ts +77 -0
  4. package/dist/clients/workflow_client.d.ts.map +1 -0
  5. package/dist/clients/workflow_client.js +172 -0
  6. package/dist/clients/workflow_client.js.map +1 -0
  7. package/dist/connection/buffered_connection.js +44 -0
  8. package/dist/connection/buffered_connection.js.map +1 -0
  9. package/dist/connection/connection.js +13 -0
  10. package/dist/connection/connection.js.map +1 -0
  11. package/dist/connection/embedded_connection.js +59 -0
  12. package/dist/connection/embedded_connection.js.map +1 -0
  13. package/dist/connection/http_connection.js +203 -0
  14. package/dist/connection/http_connection.js.map +1 -0
  15. package/dist/connection/lambda_connection.js +58 -0
  16. package/dist/connection/lambda_connection.js.map +1 -0
  17. package/dist/{restate_context.d.ts → context.d.ts} +239 -170
  18. package/dist/context.d.ts.map +1 -0
  19. package/dist/context.js +113 -0
  20. package/dist/context.js.map +1 -0
  21. package/dist/{restate_context_impl.d.ts → context_impl.d.ts} +26 -30
  22. package/dist/context_impl.d.ts.map +1 -0
  23. package/dist/context_impl.js +439 -0
  24. package/dist/context_impl.js.map +1 -0
  25. package/dist/embedded/api.d.ts +2 -2
  26. package/dist/embedded/api.d.ts.map +1 -1
  27. package/dist/embedded/api.js +35 -0
  28. package/dist/embedded/api.js.map +1 -0
  29. package/dist/embedded/handler.d.ts +2 -2
  30. package/dist/embedded/handler.d.ts.map +1 -1
  31. package/dist/embedded/handler.js +26 -0
  32. package/dist/embedded/handler.js.map +1 -0
  33. package/dist/embedded/http2_remote.js +91 -0
  34. package/dist/embedded/http2_remote.js.map +1 -0
  35. package/dist/embedded/invocation.d.ts.map +1 -1
  36. package/dist/embedded/invocation.js +94 -0
  37. package/dist/embedded/invocation.js.map +1 -0
  38. package/dist/endpoint/endpoint_impl.d.ts +35 -0
  39. package/dist/endpoint/endpoint_impl.d.ts.map +1 -0
  40. package/dist/endpoint/endpoint_impl.js +405 -0
  41. package/dist/endpoint/endpoint_impl.js.map +1 -0
  42. package/dist/endpoint/http2_handler.d.ts +11 -0
  43. package/dist/endpoint/http2_handler.d.ts.map +1 -0
  44. package/dist/endpoint/http2_handler.js +119 -0
  45. package/dist/endpoint/http2_handler.js.map +1 -0
  46. package/dist/endpoint/lambda_handler.d.ts +15 -0
  47. package/dist/endpoint/lambda_handler.d.ts.map +1 -0
  48. package/dist/endpoint/lambda_handler.js +144 -0
  49. package/dist/endpoint/lambda_handler.js.map +1 -0
  50. package/dist/endpoint.d.ts +161 -0
  51. package/dist/endpoint.d.ts.map +1 -0
  52. package/dist/endpoint.js +22 -0
  53. package/dist/endpoint.js.map +1 -0
  54. package/dist/generated/dev/restate/events.js +371 -0
  55. package/dist/generated/dev/restate/events.js.map +1 -0
  56. package/dist/generated/dev/restate/ext.js +215 -0
  57. package/dist/generated/dev/restate/ext.js.map +1 -0
  58. package/dist/generated/google/protobuf/descriptor.js +6676 -0
  59. package/dist/generated/google/protobuf/descriptor.js.map +1 -0
  60. package/dist/generated/google/protobuf/empty.js +107 -0
  61. package/dist/generated/google/protobuf/empty.js.map +1 -0
  62. package/dist/generated/google/protobuf/struct.js +754 -0
  63. package/dist/generated/google/protobuf/struct.js.map +1 -0
  64. package/dist/generated/proto/discovery.js +364 -0
  65. package/dist/generated/proto/discovery.js.map +1 -0
  66. package/dist/generated/proto/dynrpc.js +668 -0
  67. package/dist/generated/proto/dynrpc.js.map +1 -0
  68. package/dist/generated/proto/javascript.d.ts +13 -0
  69. package/dist/generated/proto/javascript.d.ts.map +1 -1
  70. package/dist/generated/proto/javascript.js +416 -0
  71. package/dist/generated/proto/javascript.js.map +1 -0
  72. package/dist/generated/proto/protocol.d.ts +43 -0
  73. package/dist/generated/proto/protocol.d.ts.map +1 -1
  74. package/dist/generated/proto/protocol.js +2641 -0
  75. package/dist/generated/proto/protocol.js.map +1 -0
  76. package/dist/generated/proto/services.js +1535 -0
  77. package/dist/generated/proto/services.js.map +1 -0
  78. package/dist/generated/proto/test.js +321 -0
  79. package/dist/generated/proto/test.js.map +1 -0
  80. package/dist/invocation.d.ts +4 -1
  81. package/dist/invocation.d.ts.map +1 -1
  82. package/dist/invocation.js +157 -0
  83. package/dist/invocation.js.map +1 -0
  84. package/dist/io/decoder.d.ts +1 -0
  85. package/dist/io/decoder.d.ts.map +1 -1
  86. package/dist/io/decoder.js +140 -0
  87. package/dist/io/decoder.js.map +1 -0
  88. package/dist/io/encoder.d.ts +1 -2
  89. package/dist/io/encoder.d.ts.map +1 -1
  90. package/dist/io/encoder.js +68 -0
  91. package/dist/io/encoder.js.map +1 -0
  92. package/dist/journal.d.ts +13 -4
  93. package/dist/journal.d.ts.map +1 -1
  94. package/dist/journal.js +405 -0
  95. package/dist/journal.js.map +1 -0
  96. package/dist/local_state_store.d.ts +5 -3
  97. package/dist/local_state_store.d.ts.map +1 -1
  98. package/dist/local_state_store.js +82 -0
  99. package/dist/local_state_store.js.map +1 -0
  100. package/dist/logger.d.ts +19 -0
  101. package/dist/logger.d.ts.map +1 -0
  102. package/dist/logger.js +90 -0
  103. package/dist/logger.js.map +1 -0
  104. package/dist/promise_combinator_tracker.d.ts +29 -0
  105. package/dist/promise_combinator_tracker.d.ts.map +1 -0
  106. package/dist/promise_combinator_tracker.js +128 -0
  107. package/dist/promise_combinator_tracker.js.map +1 -0
  108. package/dist/public_api.d.ts +5 -5
  109. package/dist/public_api.d.ts.map +1 -1
  110. package/dist/public_api.js +60 -0
  111. package/dist/public_api.js.map +1 -0
  112. package/dist/state_machine.d.ts +19 -12
  113. package/dist/state_machine.d.ts.map +1 -1
  114. package/dist/state_machine.js +437 -0
  115. package/dist/state_machine.js.map +1 -0
  116. package/dist/types/errors.d.ts +12 -3
  117. package/dist/types/errors.d.ts.map +1 -1
  118. package/dist/types/errors.js +273 -0
  119. package/dist/types/errors.js.map +1 -0
  120. package/dist/types/grpc.d.ts +6 -4
  121. package/dist/types/grpc.d.ts.map +1 -1
  122. package/dist/types/grpc.js +81 -0
  123. package/dist/types/grpc.js.map +1 -0
  124. package/dist/types/protocol.d.ts +9 -5
  125. package/dist/types/protocol.d.ts.map +1 -1
  126. package/dist/types/protocol.js +147 -0
  127. package/dist/types/protocol.js.map +1 -0
  128. package/dist/types/router.d.ts +8 -8
  129. package/dist/types/router.d.ts.map +1 -1
  130. package/dist/types/router.js +36 -0
  131. package/dist/types/router.js.map +1 -0
  132. package/dist/types/types.d.ts +1 -0
  133. package/dist/types/types.d.ts.map +1 -1
  134. package/dist/types/types.js +138 -0
  135. package/dist/types/types.js.map +1 -0
  136. package/dist/utils/{assumpsions.d.ts → assumptions.d.ts} +1 -1
  137. package/dist/utils/{assumpsions.d.ts.map → assumptions.d.ts.map} +1 -1
  138. package/dist/utils/assumptions.js +101 -0
  139. package/dist/utils/assumptions.js.map +1 -0
  140. package/dist/utils/message_logger.d.ts +28 -0
  141. package/dist/utils/message_logger.d.ts.map +1 -0
  142. package/dist/utils/message_logger.js +88 -0
  143. package/dist/utils/message_logger.js.map +1 -0
  144. package/dist/utils/promises.d.ts +15 -0
  145. package/dist/utils/promises.d.ts.map +1 -0
  146. package/dist/utils/promises.js +67 -0
  147. package/dist/utils/promises.js.map +1 -0
  148. package/dist/utils/public_utils.js +49 -0
  149. package/dist/utils/public_utils.js.map +1 -0
  150. package/dist/utils/rand.d.ts +1 -1
  151. package/dist/utils/rand.d.ts.map +1 -1
  152. package/dist/utils/rand.js +114 -0
  153. package/dist/utils/rand.js.map +1 -0
  154. package/dist/utils/utils.d.ts +1 -10
  155. package/dist/utils/utils.d.ts.map +1 -1
  156. package/dist/utils/utils.js +122 -0
  157. package/dist/utils/utils.js.map +1 -0
  158. package/dist/workflows/workflow.d.ts +101 -0
  159. package/dist/workflows/workflow.d.ts.map +1 -0
  160. package/dist/workflows/workflow.js +80 -0
  161. package/dist/workflows/workflow.js.map +1 -0
  162. package/dist/workflows/workflow_state_service.d.ts +35 -0
  163. package/dist/workflows/workflow_state_service.d.ts.map +1 -0
  164. package/dist/workflows/workflow_state_service.js +201 -0
  165. package/dist/workflows/workflow_state_service.js.map +1 -0
  166. package/dist/workflows/workflow_wrapper_service.d.ts +10 -0
  167. package/dist/workflows/workflow_wrapper_service.d.ts.map +1 -0
  168. package/dist/workflows/workflow_wrapper_service.js +264 -0
  169. package/dist/workflows/workflow_wrapper_service.js.map +1 -0
  170. package/package.json +38 -39
  171. package/src/clients/workflow_client.ts +290 -0
  172. package/src/connection/buffered_connection.ts +47 -0
  173. package/src/connection/connection.ts +34 -0
  174. package/src/connection/embedded_connection.ts +62 -0
  175. package/src/connection/http_connection.ts +228 -0
  176. package/src/connection/lambda_connection.ts +69 -0
  177. package/src/context.ts +633 -0
  178. package/src/context_impl.ts +721 -0
  179. package/src/embedded/api.ts +57 -0
  180. package/src/embedded/handler.ts +36 -0
  181. package/src/embedded/http2_remote.ts +103 -0
  182. package/src/embedded/invocation.ts +126 -0
  183. package/src/endpoint/endpoint_impl.ts +623 -0
  184. package/src/endpoint/http2_handler.ts +151 -0
  185. package/src/endpoint/lambda_handler.ts +181 -0
  186. package/src/endpoint.ts +187 -0
  187. package/src/generated/dev/restate/events.ts +430 -0
  188. package/src/generated/dev/restate/ext.ts +238 -0
  189. package/src/generated/google/protobuf/descriptor.ts +7889 -0
  190. package/src/generated/google/protobuf/empty.ts +150 -0
  191. package/src/generated/google/protobuf/struct.ts +878 -0
  192. package/src/generated/proto/discovery.ts +423 -0
  193. package/src/generated/proto/dynrpc.ts +768 -0
  194. package/src/generated/proto/javascript.ts +488 -0
  195. package/src/generated/proto/protocol.ts +3091 -0
  196. package/src/generated/proto/services.ts +1834 -0
  197. package/src/generated/proto/test.ts +387 -0
  198. package/src/invocation.ts +212 -0
  199. package/src/io/decoder.ts +171 -0
  200. package/src/io/encoder.ts +72 -0
  201. package/src/journal.ts +537 -0
  202. package/src/local_state_store.ts +94 -0
  203. package/src/logger.ts +121 -0
  204. package/src/promise_combinator_tracker.ts +191 -0
  205. package/src/public_api.ts +53 -0
  206. package/src/state_machine.ts +635 -0
  207. package/src/types/errors.ts +297 -0
  208. package/src/types/grpc.ts +97 -0
  209. package/src/types/protocol.ts +201 -0
  210. package/src/types/router.ts +118 -0
  211. package/src/types/types.ts +160 -0
  212. package/src/utils/assumptions.ts +131 -0
  213. package/src/utils/message_logger.ts +112 -0
  214. package/src/utils/promises.ts +118 -0
  215. package/src/utils/public_utils.ts +91 -0
  216. package/src/utils/rand.ts +142 -0
  217. package/src/utils/utils.ts +178 -0
  218. package/src/workflows/workflow.ts +178 -0
  219. package/src/workflows/workflow_state_service.ts +299 -0
  220. package/src/workflows/workflow_wrapper_service.ts +314 -0
  221. package/dist/cloudflare_bundle.js +0 -27387
  222. package/dist/restate_context.d.ts.map +0 -1
  223. package/dist/restate_context_impl.d.ts.map +0 -1
  224. package/dist/server/base_restate_server.d.ts +0 -32
  225. package/dist/server/base_restate_server.d.ts.map +0 -1
  226. package/dist/server/restate_lambda_handler.d.ts +0 -104
  227. package/dist/server/restate_lambda_handler.d.ts.map +0 -1
  228. package/dist/server/restate_server.d.ts +0 -97
  229. package/dist/server/restate_server.d.ts.map +0 -1
  230. package/dist/utils/logger.d.ts +0 -60
  231. package/dist/utils/logger.d.ts.map +0 -1
@@ -0,0 +1,635 @@
1
+ /*
2
+ * Copyright (c) 2023-2024 - Restate Software, Inc., Restate GmbH
3
+ *
4
+ * This file is part of the Restate SDK for Node.js/TypeScript,
5
+ * which is released under the MIT license.
6
+ *
7
+ * You can find a copy of the license in file LICENSE in the root
8
+ * directory of this repository or package, or at
9
+ * https://github.com/restatedev/sdk-typescript/blob/main/LICENSE
10
+ */
11
+
12
+ import * as p from "./types/protocol";
13
+ import { ContextImpl } from "./context_impl";
14
+ import { Connection, RestateStreamConsumer } from "./connection/connection";
15
+ import { ProtocolMode } from "./generated/proto/discovery";
16
+ import { Message } from "./types/types";
17
+ import {
18
+ createStateMachineConsole,
19
+ StateMachineConsole,
20
+ } from "./utils/message_logger";
21
+ import { clearTimeout } from "timers";
22
+ import {
23
+ COMBINATOR_ENTRY_MESSAGE,
24
+ COMPLETION_MESSAGE_TYPE,
25
+ END_MESSAGE_TYPE,
26
+ EndMessage,
27
+ ENTRY_ACK_MESSAGE_TYPE,
28
+ ERROR_MESSAGE_TYPE,
29
+ OUTPUT_STREAM_ENTRY_MESSAGE_TYPE,
30
+ OutputStreamEntryMessage,
31
+ SUSPENSION_MESSAGE_TYPE,
32
+ SuspensionMessage,
33
+ } from "./types/protocol";
34
+ import { Journal } from "./journal";
35
+ import { Invocation } from "./invocation";
36
+ import {
37
+ ensureError,
38
+ TerminalError,
39
+ RetryableError,
40
+ errorToErrorMessage,
41
+ failureToTerminalError,
42
+ } from "./types/errors";
43
+ import { LocalStateStore } from "./local_state_store";
44
+ import { createRestateConsole, LoggerContext } from "./logger";
45
+ import {
46
+ CompletablePromise,
47
+ wrapDeeply,
48
+ WRAPPED_PROMISE_PENDING,
49
+ WrappedPromise,
50
+ } from "./utils/promises";
51
+ import {
52
+ PromiseCombinatorTracker,
53
+ PromiseId,
54
+ PromiseType,
55
+ } from "./promise_combinator_tracker";
56
+ import { CombinatorEntryMessage } from "./generated/proto/javascript";
57
+
58
+ export class StateMachine<I, O> implements RestateStreamConsumer {
59
+ private journal: Journal<I, O>;
60
+ private restateContext: ContextImpl;
61
+
62
+ private readonly invocationComplete = new CompletablePromise<Buffer | void>();
63
+
64
+ // when this flag is true, no more work will (and may) happen
65
+ // this is set to true in case of
66
+ // - a completed invocation
67
+ // - a suspension
68
+ // - an error in the state machine
69
+ private stateMachineClosed = false;
70
+
71
+ public readonly localStateStore: LocalStateStore;
72
+
73
+ // Whether the input channel (runtime -> service) is closed
74
+ // If it is closed, then we suspend immediately upon the next suspension point
75
+ // If it is open, then we suspend later because we might still get completions
76
+ private inputChannelClosed = false;
77
+
78
+ // Suspension timeout that gets set and cleared based on completion messages;
79
+ private suspensionTimeout?: NodeJS.Timeout;
80
+
81
+ private promiseCombinatorTracker: PromiseCombinatorTracker;
82
+
83
+ console: StateMachineConsole;
84
+
85
+ constructor(
86
+ private readonly connection: Connection,
87
+ private readonly invocation: Invocation<I, O>,
88
+ private readonly protocolMode: ProtocolMode,
89
+ keyedContext: boolean,
90
+ loggerContext: LoggerContext,
91
+ private readonly suspensionMillis: number = 30_000
92
+ ) {
93
+ this.localStateStore = invocation.localStateStore;
94
+ this.console = createStateMachineConsole(loggerContext);
95
+
96
+ this.restateContext = new ContextImpl(
97
+ this.invocation.id,
98
+ this.invocation.method.service,
99
+ // The console exposed by RestateContext filters logs in replay, while the internal one is based on the ENV variables.
100
+ createRestateConsole(loggerContext, () => !this.journal.isReplaying()),
101
+ keyedContext,
102
+ this
103
+ );
104
+ this.journal = new Journal(this.invocation);
105
+ this.promiseCombinatorTracker = new PromiseCombinatorTracker(
106
+ this.readCombinatorOrderEntry.bind(this),
107
+ this.writeCombinatorOrderEntry.bind(this)
108
+ );
109
+ }
110
+
111
+ public handleMessage(m: Message): boolean {
112
+ if (this.stateMachineClosed) {
113
+ // ignore this message
114
+ return false;
115
+ }
116
+
117
+ if (m.messageType === COMPLETION_MESSAGE_TYPE) {
118
+ this.console.debugJournalMessage(
119
+ "Received completion message from Restate, adding to journal.",
120
+ m.messageType,
121
+ m.message
122
+ );
123
+ this.journal.handleRuntimeCompletionMessage(
124
+ m.message as p.CompletionMessage
125
+ );
126
+ } else if (m.messageType === ENTRY_ACK_MESSAGE_TYPE) {
127
+ this.console.debugJournalMessage(
128
+ "Received entry ack message from Restate, adding to journal.",
129
+ m.messageType,
130
+ m.message
131
+ );
132
+ this.journal.handleEntryAckMessage(m.message as p.EntryAckMessage);
133
+ } else {
134
+ throw RetryableError.protocolViolation(
135
+ `Received message of type ${m.messageType}. Can only accept completion or acks messages after replay has finished.`
136
+ );
137
+ }
138
+
139
+ // Remove lingering suspension timeouts, if we are not waiting for completions anymore
140
+ if (
141
+ this.suspensionTimeout !== undefined &&
142
+ this.journal.getCompletableIndices().length === 0
143
+ ) {
144
+ clearTimeout(this.suspensionTimeout);
145
+ this.suspensionTimeout = undefined;
146
+ }
147
+
148
+ return false; // we are never complete
149
+ }
150
+
151
+ public handleUserCodeMessage<T>(
152
+ messageType: bigint,
153
+ message: p.ProtocolMessage,
154
+ completedFlag?: boolean,
155
+ protocolVersion?: number,
156
+ requiresAckFlag?: boolean
157
+ ): WrappedPromise<T | void> {
158
+ // if the state machine is already closed, return a promise that never
159
+ // completes, so that the user code does not resume
160
+ if (this.stateMachineClosed) {
161
+ return WRAPPED_PROMISE_PENDING as WrappedPromise<T | void>;
162
+ }
163
+
164
+ const promise = this.journal.handleUserSideMessage(messageType, message);
165
+ const journalIndex = this.journal.getUserCodeJournalIndex();
166
+
167
+ // Only send the message to restate if we are not in replaying mode
168
+ if (this.journal.isProcessing()) {
169
+ this.console.debugJournalMessage(
170
+ "Adding message to journal and sending to Restate",
171
+ messageType,
172
+ message
173
+ );
174
+
175
+ this.send(
176
+ new Message(
177
+ messageType,
178
+ message,
179
+ completedFlag,
180
+ protocolVersion,
181
+ requiresAckFlag
182
+ )
183
+ );
184
+ } else {
185
+ this.console.debugJournalMessage(
186
+ "Matched and replayed message from journal",
187
+ messageType,
188
+ message
189
+ );
190
+ }
191
+
192
+ return wrapDeeply(promise, () => {
193
+ if (!p.SUSPENSION_TRIGGERS.includes(messageType)) {
194
+ return;
195
+ }
196
+ if (this.journal.isUnResolved(journalIndex)) {
197
+ this.hitSuspensionPoint();
198
+ }
199
+ });
200
+ }
201
+
202
+ // -- Methods related to combinators to wire up promise combinator API with PromiseCombinatorTracker
203
+
204
+ public createCombinator(
205
+ combinatorConstructor: (
206
+ promises: PromiseLike<unknown>[]
207
+ ) => Promise<unknown>,
208
+ promises: Array<{ id: PromiseId; promise: Promise<unknown> }>
209
+ ) {
210
+ if (this.stateMachineClosed) {
211
+ return WRAPPED_PROMISE_PENDING as WrappedPromise<unknown>;
212
+ }
213
+
214
+ // We don't need the promise wrapping here to schedule a suspension,
215
+ // because the combined promises will already have that, so once we call then() on them,
216
+ // if we have to suspend we will suspend.
217
+ return this.promiseCombinatorTracker.createCombinator(
218
+ combinatorConstructor,
219
+ promises
220
+ );
221
+ }
222
+
223
+ readCombinatorOrderEntry(combinatorId: number): PromiseId[] | undefined {
224
+ const wannabeCombinatorEntry = this.journal.readNextReplayEntry();
225
+ if (wannabeCombinatorEntry === undefined) {
226
+ // We're in processing mode
227
+ return undefined;
228
+ }
229
+ if (wannabeCombinatorEntry.messageType !== COMBINATOR_ENTRY_MESSAGE) {
230
+ throw RetryableError.journalMismatch(
231
+ this.journal.getUserCodeJournalIndex(),
232
+ wannabeCombinatorEntry,
233
+ {
234
+ messageType: COMBINATOR_ENTRY_MESSAGE,
235
+ message: {
236
+ combinatorId,
237
+ } as CombinatorEntryMessage,
238
+ }
239
+ );
240
+ }
241
+
242
+ const combinatorMessage =
243
+ wannabeCombinatorEntry.message as CombinatorEntryMessage;
244
+ if (combinatorMessage.combinatorId != combinatorId) {
245
+ throw RetryableError.journalMismatch(
246
+ this.journal.getUserCodeJournalIndex(),
247
+ wannabeCombinatorEntry,
248
+ {
249
+ messageType: COMBINATOR_ENTRY_MESSAGE,
250
+ message: {
251
+ combinatorId,
252
+ } as CombinatorEntryMessage,
253
+ }
254
+ );
255
+ }
256
+
257
+ this.console.debugJournalMessage(
258
+ "Matched and replayed message from journal",
259
+ COMBINATOR_ENTRY_MESSAGE,
260
+ combinatorMessage
261
+ );
262
+
263
+ return combinatorMessage.journalEntriesOrder.map((id) => ({
264
+ id,
265
+ type: PromiseType.JournalEntry,
266
+ }));
267
+ }
268
+
269
+ async writeCombinatorOrderEntry(combinatorId: number, order: PromiseId[]) {
270
+ if (this.journal.isProcessing()) {
271
+ const combinatorMessage: CombinatorEntryMessage = {
272
+ combinatorId,
273
+ journalEntriesOrder: order.map((pid) => pid.id),
274
+ };
275
+ this.console.debugJournalMessage(
276
+ "Adding message to journal and sending to Restate",
277
+ COMBINATOR_ENTRY_MESSAGE,
278
+ combinatorMessage
279
+ );
280
+
281
+ const ackPromise = this.journal.appendJournalEntry(
282
+ COMBINATOR_ENTRY_MESSAGE,
283
+ combinatorMessage
284
+ );
285
+ this.send(
286
+ new Message(
287
+ COMBINATOR_ENTRY_MESSAGE,
288
+ combinatorMessage,
289
+ undefined,
290
+ undefined,
291
+ true
292
+ )
293
+ );
294
+
295
+ this.hitSuspensionPoint();
296
+ await ackPromise;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Invokes the RPC function and returns a promise that completes when the state machine
302
+ * stops processing the invocation, meaning when:
303
+ * - The function completes with a result or an exception
304
+ * - The execution suspends
305
+ * - An error is raised in the state machine (network, API violation, ...)
306
+ *
307
+ * The returned promise resolves successfully for all the cases above, because the are (from
308
+ * the perspective of the state machine) expected outcomes in which it send out corresponding
309
+ * result messages and cleanly closed the connection.
310
+ *
311
+ * The returned promise is rejected when an unhandled error arises and the caller would be
312
+ * expected to ensure that resources are properly cleaned up.
313
+ */
314
+ public invoke(): Promise<Buffer | void> {
315
+ // --------------------------------------------------------------------------------------------
316
+ // Implementation note:
317
+ //
318
+ // This method is not async, because we don't want to actually await anything
319
+ // in there. We cannot await the completion of the actual invocation, because for long-running
320
+ // code (that suspends), the function invocation never completes. Instead, the state machine
321
+ // triggers a suspension.
322
+ // We need to do a bit of promise chaining for the rpc function promise, and return a different
323
+ // promise that completes in also in suspension and error cases.
324
+ // --------------------------------------------------------------------------------------------
325
+
326
+ // it is unexpected for the state machine to be closed here, so we raise an error in
327
+ // that case, unlike in other places, where we simply ignore things
328
+ if (this.stateMachineClosed) {
329
+ return Promise.reject(new Error("state machine is already closed"));
330
+ }
331
+
332
+ if (this.journal.nextEntryWillBeReplayed()) {
333
+ this.console.debugInvokeMessage("Resuming (replaying) function.");
334
+ } else {
335
+ this.console.debugInvokeMessage("Invoking function.");
336
+ }
337
+
338
+ let resultBytes: Promise<Uint8Array>;
339
+
340
+ switch (this.invocation.invocationValue.kind) {
341
+ case "value":
342
+ resultBytes = this.invocation.method.invoke(
343
+ this.restateContext,
344
+ this.invocation.invocationValue.value
345
+ );
346
+ break;
347
+ case "failure":
348
+ resultBytes = Promise.reject(
349
+ failureToTerminalError(this.invocation.invocationValue.failure)
350
+ );
351
+ break;
352
+ }
353
+
354
+ resultBytes
355
+ .then((bytes) => {
356
+ // invocation successfully returned with a result value
357
+ try {
358
+ // the state machine might be closed here in some cases like when there was an error (like
359
+ // API violation) or a suspension, but the function code still completed
360
+ if (this.stateMachineClosed) {
361
+ this.console.warn(
362
+ "Unexpected successful completion of the function after the state machine closed. " +
363
+ "This may indicate that: \n" +
364
+ "- the function code does not properly await some Restate calls " +
365
+ "and did not notice an error \n" +
366
+ "- the function code was delayed for longer than the suspension timeout \n" +
367
+ "- the function code contained a try-catch block around a side effect which throws retryable errors. " +
368
+ "This try-catch block should be placed inside the side effect."
369
+ );
370
+ return;
371
+ }
372
+
373
+ const value = Buffer.from(bytes);
374
+
375
+ // handle the result value
376
+ const msg = new Message(
377
+ OUTPUT_STREAM_ENTRY_MESSAGE_TYPE,
378
+ OutputStreamEntryMessage.create({
379
+ value,
380
+ })
381
+ );
382
+
383
+ this.journal.handleUserSideMessage(msg.messageType, msg.message);
384
+
385
+ if (!this.journal.outputMsgWasReplayed()) {
386
+ this.send(msg);
387
+
388
+ this.console.debugJournalMessage(
389
+ "Journaled and sent output message",
390
+ msg.messageType,
391
+ msg.message
392
+ );
393
+ } else {
394
+ this.console.debugJournalMessage(
395
+ "Replayed and matched output message from journal",
396
+ msg.messageType,
397
+ msg.message
398
+ );
399
+ }
400
+
401
+ this.console.debugInvokeMessage("Function completed successfully.");
402
+
403
+ // Mark the end of the invocation
404
+ this.send(new Message(END_MESSAGE_TYPE, EndMessage.create()));
405
+
406
+ this.finish(value);
407
+ } catch (e) {
408
+ this.unhandledError(ensureError(e));
409
+ }
410
+ })
411
+ .catch((e) => {
412
+ // because of how we try/catch in the promise handler above, this here exclusively handles
413
+ // errors coming from the rpc function
414
+ try {
415
+ // Sometimes the function code fails as a consequence of the state machine encountering
416
+ // an error before (possibly Restate closed the connection).
417
+ if (this.stateMachineClosed) {
418
+ return;
419
+ }
420
+
421
+ const error = ensureError(e);
422
+ this.console.trace(
423
+ "Function completed with an error: " + error.message,
424
+ e
425
+ );
426
+
427
+ this.sendErrorAndFinish(error);
428
+ } catch (ee) {
429
+ this.unhandledError(ensureError(ee));
430
+ }
431
+ });
432
+
433
+ // this promise here completes under any completion, including the cases where the
434
+ // rpc function does not end (error, suspension, ...)
435
+ return this.invocationComplete.promise;
436
+ }
437
+
438
+ private async sendErrorAndFinish(e: Error) {
439
+ if (e instanceof TerminalError) {
440
+ this.sendTerminalError(e);
441
+ } else {
442
+ this.sendRetryableError(e);
443
+ }
444
+
445
+ await this.finish();
446
+ }
447
+
448
+ private sendRetryableError(e: Error) {
449
+ const msg = new Message(ERROR_MESSAGE_TYPE, errorToErrorMessage(e));
450
+ this.console.debugJournalMessage(
451
+ "Invocation ended with retryable error.",
452
+ msg.messageType,
453
+ msg.message
454
+ );
455
+
456
+ this.send(msg);
457
+ }
458
+
459
+ private sendTerminalError(e: TerminalError) {
460
+ const msg = new Message(
461
+ OUTPUT_STREAM_ENTRY_MESSAGE_TYPE,
462
+ OutputStreamEntryMessage.create({
463
+ failure: e.toFailure(),
464
+ })
465
+ );
466
+ this.console.debugJournalMessage(
467
+ "Invocation ended with failure message.",
468
+ msg.messageType,
469
+ msg.message
470
+ );
471
+
472
+ this.journal.handleUserSideMessage(msg.messageType, msg.message);
473
+ if (!this.journal.outputMsgWasReplayed()) {
474
+ this.send(msg);
475
+ }
476
+
477
+ // Mark the end of the invocation
478
+ this.send(new Message(END_MESSAGE_TYPE, EndMessage.create()));
479
+ }
480
+
481
+ private send(message: Message) {
482
+ this.connection.send(message).catch((err) => {
483
+ this.handleStreamError(err);
484
+ });
485
+ }
486
+
487
+ /**
488
+ * Closes the state machine, flushes all output, and resolves the invocation promise.
489
+ */
490
+ private async finish(value?: Buffer) {
491
+ try {
492
+ this.stateMachineClosed = true;
493
+ this.journal.close();
494
+ this.clearSuspensionTimeout();
495
+
496
+ await this.connection.end();
497
+
498
+ this.invocationComplete.resolve(value);
499
+ } catch (e) {
500
+ this.invocationComplete.reject(ensureError(e));
501
+ }
502
+ }
503
+
504
+ /**
505
+ * This function propagates errors up to the completion promise, to be handled
506
+ * on the connection layer.
507
+ */
508
+ private unhandledError(e: Error) {
509
+ this.invocationComplete.reject(e);
510
+ this.stateMachineClosed = true;
511
+ this.journal.close();
512
+ this.clearSuspensionTimeout();
513
+ }
514
+
515
+ /**
516
+ * This method is invoked when we hit a suspension point. A suspension point is everytime the user "await"s a Promise returned by RestateContext that might be completed at a later point in time by a CompletionMessage/AckMessage.
517
+ *
518
+ * Depending on the state of the read channel, and on the protocol mode, it might either immediately suspend, or schedule a suspension to happen at a later point in time.
519
+ */
520
+ private hitSuspensionPoint() {
521
+ // If there was already a timeout set, we want to reset the time to postpone suspension as long as we make progress.
522
+ // So we first clear the old timeout, and then we set a new one.
523
+ this.clearSuspensionTimeout();
524
+
525
+ const delay = this.getSuspensionMillis();
526
+ this.console.debugJournalMessage(
527
+ "Scheduling suspension in " + delay + " ms"
528
+ );
529
+
530
+ if (delay >= 0) {
531
+ // Set a new suspension with a new timeout
532
+ // The suspension will only be sent if the timeout is not canceled due to a completion.
533
+ // In case the delay is 0 we still schedule a timeout in order to process the suspension on the next process tick,
534
+ // without interrupting the current work.
535
+ this.suspensionTimeout = setTimeout(() => {
536
+ this.suspend();
537
+ }, delay);
538
+ }
539
+ }
540
+
541
+ // Suspension timeouts:
542
+ // Lambda case: suspend immediately when control is back in the user code
543
+ // Bidi streaming case:
544
+ // - suspend after 1 seconds if input channel is still open (can still get completions)
545
+ // - suspend immediately if input channel is closed (cannot get completions)
546
+ private getSuspensionMillis(): number {
547
+ return this.protocolMode === ProtocolMode.REQUEST_RESPONSE ||
548
+ this.inputChannelClosed
549
+ ? 0
550
+ : this.suspensionMillis;
551
+ }
552
+
553
+ private async suspend() {
554
+ const indices = this.journal.getCompletableIndices();
555
+ // If the state is closed then we either already send a suspension
556
+ // or something else bad happened...
557
+ if (this.journal.isClosed() || indices.length === 0) {
558
+ return;
559
+ }
560
+
561
+ // There need to be journal entries to complete, otherwise this timeout should have been removed.
562
+ // A suspension message is the end of the invocation.
563
+ // Resolve the root call with the suspension message
564
+ // This will lead to a onCallSuccess call where this msg will be sent.
565
+ const msg = new Message(
566
+ SUSPENSION_MESSAGE_TYPE,
567
+ SuspensionMessage.create({
568
+ entryIndexes: indices,
569
+ })
570
+ );
571
+
572
+ this.console.debugJournalMessage(
573
+ "Writing suspension message to journal.",
574
+ msg.messageType,
575
+ msg.message
576
+ );
577
+
578
+ this.journal.handleUserSideMessage(msg.messageType, msg.message);
579
+ if (!this.journal.outputMsgWasReplayed()) {
580
+ this.send(msg);
581
+ }
582
+
583
+ this.console.debugInvokeMessage("Suspending function.");
584
+
585
+ await this.finish();
586
+ }
587
+
588
+ /**
589
+ * WARNING: make sure you use this at the right point in the code
590
+ * After the index has been incremented...
591
+ * This is error-prone... Would be good to have a better solution for this.
592
+ */
593
+ public getUserCodeJournalIndex(): number {
594
+ return this.journal.getUserCodeJournalIndex();
595
+ }
596
+
597
+ public handleInputClosed(): void {
598
+ if (
599
+ this.journal.isClosed() ||
600
+ this.stateMachineClosed ||
601
+ this.inputChannelClosed
602
+ ) {
603
+ return;
604
+ }
605
+
606
+ this.inputChannelClosed = true;
607
+
608
+ this.console.debug("Restate closed connection to trigger suspension.");
609
+
610
+ // If there is a timeout planned, reset the timout to execute immediately when the work is done.
611
+ if (this.suspensionTimeout !== undefined) {
612
+ this.hitSuspensionPoint();
613
+ }
614
+ }
615
+
616
+ public handleStreamError(e: Error): void {
617
+ this.console.info(
618
+ "Aborting function execution and closing state machine due to connection error: " +
619
+ e.message
620
+ );
621
+
622
+ this.unhandledError(e);
623
+ }
624
+
625
+ public nextEntryWillBeReplayed() {
626
+ return this.journal.nextEntryWillBeReplayed();
627
+ }
628
+
629
+ private clearSuspensionTimeout() {
630
+ if (this.suspensionTimeout !== undefined) {
631
+ clearTimeout(this.suspensionTimeout);
632
+ this.suspensionTimeout = undefined;
633
+ }
634
+ }
635
+ }