@restatedev/sessions 0.11.2 → 0.12.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.
Files changed (96) hide show
  1. package/README.md +330 -178
  2. package/dist/addon.d.ts +1 -0
  3. package/dist/addon.d.ts.map +1 -1
  4. package/dist/addon.js.map +1 -1
  5. package/dist/calls.d.ts +28 -28
  6. package/dist/calls.d.ts.map +1 -1
  7. package/dist/calls.js +25 -25
  8. package/dist/calls.js.map +1 -1
  9. package/dist/database.d.ts +90 -166
  10. package/dist/database.d.ts.map +1 -1
  11. package/dist/database.js +137 -249
  12. package/dist/database.js.map +1 -1
  13. package/dist/driver.d.ts +129 -126
  14. package/dist/driver.d.ts.map +1 -1
  15. package/dist/driver.js +337 -276
  16. package/dist/driver.js.map +1 -1
  17. package/dist/endpoint.d.ts +47 -5
  18. package/dist/endpoint.d.ts.map +1 -1
  19. package/dist/endpoint.js +175 -60
  20. package/dist/endpoint.js.map +1 -1
  21. package/dist/handler.d.ts +20 -17
  22. package/dist/handler.d.ts.map +1 -1
  23. package/dist/handler.js +161 -127
  24. package/dist/handler.js.map +1 -1
  25. package/dist/host.d.ts +29 -0
  26. package/dist/host.d.ts.map +1 -0
  27. package/dist/host.js +2 -0
  28. package/dist/host.js.map +1 -0
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +5 -26
  32. package/dist/index.js.map +1 -1
  33. package/dist/internal.d.ts +11 -11
  34. package/dist/internal.d.ts.map +1 -1
  35. package/dist/internal.js +20 -16
  36. package/dist/internal.js.map +1 -1
  37. package/dist/link.d.ts +1 -2
  38. package/dist/link.d.ts.map +1 -1
  39. package/dist/link.js +4 -5
  40. package/dist/link.js.map +1 -1
  41. package/dist/log.d.ts +14 -0
  42. package/dist/log.d.ts.map +1 -0
  43. package/dist/log.js +21 -0
  44. package/dist/log.js.map +1 -0
  45. package/dist/object.d.ts +217 -142
  46. package/dist/object.d.ts.map +1 -1
  47. package/dist/object.js +195 -241
  48. package/dist/object.js.map +1 -1
  49. package/dist/platform.d.ts +0 -1
  50. package/dist/platform.d.ts.map +1 -1
  51. package/dist/platform.js +4 -6
  52. package/dist/platform.js.map +1 -1
  53. package/dist/schema.d.ts +14 -22
  54. package/dist/schema.d.ts.map +1 -1
  55. package/dist/schema.js +31 -69
  56. package/dist/schema.js.map +1 -1
  57. package/dist/serve.d.ts +11 -17
  58. package/dist/serve.d.ts.map +1 -1
  59. package/dist/serve.js +21 -39
  60. package/dist/serve.js.map +1 -1
  61. package/dist/session.d.ts +58 -240
  62. package/dist/session.d.ts.map +1 -1
  63. package/dist/session.js +206 -532
  64. package/dist/session.js.map +1 -1
  65. package/dist/stop.d.ts +59 -0
  66. package/dist/stop.d.ts.map +1 -0
  67. package/dist/stop.js +220 -0
  68. package/dist/stop.js.map +1 -0
  69. package/dist/vm.d.ts +108 -29
  70. package/dist/vm.d.ts.map +1 -1
  71. package/dist/vm.js +43 -10
  72. package/dist/vm.js.map +1 -1
  73. package/package.json +4 -4
  74. package/src/addon.ts +1 -0
  75. package/src/calls.ts +51 -47
  76. package/src/database.ts +195 -339
  77. package/src/driver.ts +379 -315
  78. package/src/endpoint.ts +217 -62
  79. package/src/handler.ts +183 -164
  80. package/src/host.ts +28 -0
  81. package/src/index.ts +6 -26
  82. package/src/internal.ts +28 -39
  83. package/src/link.ts +4 -5
  84. package/src/log.ts +42 -0
  85. package/src/object.ts +379 -335
  86. package/src/platform.ts +4 -6
  87. package/src/schema.ts +37 -103
  88. package/src/serve.ts +20 -41
  89. package/src/session.ts +236 -629
  90. package/src/stop.ts +225 -0
  91. package/src/vm.ts +151 -55
  92. package/dist/scope.d.ts +0 -38
  93. package/dist/scope.d.ts.map +0 -1
  94. package/dist/scope.js +0 -55
  95. package/dist/scope.js.map +0 -1
  96. package/src/scope.ts +0 -78
package/src/endpoint.ts CHANGED
@@ -1,5 +1,18 @@
1
- // Every invocation of a session object runs on the explicit recovery VM
2
- // (`handler.ts`), whichever way its deployment is served.
1
+ // A session object's handlers are on the explicit recovery protocol (version
2
+ // 1), which the published SDK does not speak: this package serves them, and
3
+ // the discovery that declares them, ahead of the SDK's request handler. Every
4
+ // other request — a library's journaled objects, the health check — is the
5
+ // SDK's, unchanged.
6
+ //
7
+ // - `/discover`: manifest v6, the SDK's manifest with `protocolFamily:
8
+ // EXPLICIT_RECOVERY` on every session object's handler, the range of the
9
+ // protocol the addon's VM speaks (`explicitRecoveryProtocol`), and the
10
+ // durable execution range only if a handler is on that protocol.
11
+ // - `/invoke/<object>/<handler>` of a session object: an attempt on the VM
12
+ // (`handler.ts`); a request of another protocol is answered 415.
13
+ // - A SIGTERM ends the attempts under way with an unasked
14
+ // `ShutdownMessage`, and refuses new ones with 503 while the process goes
15
+ // away.
3
16
  //
4
17
  // The SDK builds its own VM per invocation, and the dispatch that does it is
5
18
  // module-private: there is no supported seam. What every transport does share
@@ -10,15 +23,15 @@
10
23
  // It is a patch on another package's prototype, which is worth naming plainly.
11
24
  // It touches four methods whose contract is "give me a request handler", and
12
25
  // the handler it returns is the SDK's own for everything but a session
13
- // object. The alternative it replaced was larger: reaching into five private
14
- // fields of the SDK's promise executor to drive its VM by hand.
26
+ // object's invocations and the discovery that names them.
15
27
  import * as http2 from 'node:http2';
16
28
  import type { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
17
29
  import type { IncomingMessage, ServerResponse } from 'node:http';
18
30
  import * as restate from '@restatedev/restate-sdk';
19
- import { MIN_PROTOCOL, servedHere, serveSession, type Stream } from './handler.ts';
20
- import { isSessionObject } from './object.ts';
21
- import { Identity, type VmHeader } from './vm.ts';
31
+ import { goAway, serveSession, type Stream } from './handler.ts';
32
+ import { type Log, logOf } from './log.ts';
33
+ import { isSessionObject, PROTOCOL_FAMILY, refuseOptions } from './object.ts';
34
+ import { explicitRecoveryProtocolRange, Identity, type VmHeader } from './vm.ts';
22
35
 
23
36
  /** Marks the prototype this package has already wrapped. */
24
37
  const PATCHED = Symbol.for('restate-sessions.endpoint-patched') as unknown as string;
@@ -28,7 +41,10 @@ interface Endpoint {
28
41
  builder: {
29
42
  serviceDefinitions: Map<string, object>;
30
43
  keySet: string[];
44
+ defaultServiceOptions: restate.DefaultServiceOptions;
45
+ loggerTransport: restate.LoggerTransport;
31
46
  journalValueCodecProvider?: unknown;
47
+ build(): { discoveryMetadata: Manifest };
32
48
  };
33
49
  handler(options?: { bidirectional?: boolean }): (request: never, response: never) => void;
34
50
  http2Handler(options?: { bidirectional?: boolean }): (request: never, response: never) => void;
@@ -57,6 +73,8 @@ function refuseWhatTheVmCannotServe(endpoint: Endpoint, sessions: Map<string, un
57
73
  'their attempts are never replayed, and nothing of theirs is journaled to encode',
58
74
  );
59
75
  }
76
+ // Every service's options start from these, a session object's too.
77
+ refuseOptions("@restatedev/sessions: the endpoint's default service options", endpoint.builder.defaultServiceOptions);
60
78
  }
61
79
 
62
80
  /** The request's headers, as the verifier takes them. */
@@ -66,6 +84,123 @@ function headersOf(headers: Readonly<Record<string, string | string[] | undefine
66
84
  );
67
85
  }
68
86
 
87
+ /** The SDK's manifest, as far as this module reads and changes it. */
88
+ interface Manifest {
89
+ minProtocolVersion?: number;
90
+ maxProtocolVersion?: number;
91
+ services: { name: string; handlers: { name: string; protocolFamily?: string }[] }[];
92
+ [field: string]: unknown;
93
+ }
94
+
95
+ /** The content type of manifest v6, the first with protocol families. */
96
+ const MANIFEST_V6 = 'application/vnd.restate.endpointmanifest.v6+json';
97
+
98
+ /**
99
+ * Manifest v6 of `endpoint`, served in `protocolMode`: its SDK manifest, with
100
+ * every session object's handler on the explicit recovery protocol. Throws
101
+ * if the endpoint cannot serve them: a session object needs a bidirectional
102
+ * stream (HTTP/2).
103
+ */
104
+ export function manifestV6(
105
+ endpoint: { builder: Endpoint['builder'] },
106
+ protocolMode: 'BIDI_STREAM' | 'REQUEST_RESPONSE',
107
+ ): Record<string, unknown> {
108
+ const sessions = sessionsOf(endpoint as Endpoint);
109
+ const sdk = endpoint.builder.build().discoveryMetadata;
110
+ const services = sdk.services.map((service) =>
111
+ sessions.has(service.name)
112
+ ? { ...service, handlers: service.handlers.map((h) => ({ ...h, protocolFamily: PROTOCOL_FAMILY })) }
113
+ : service,
114
+ );
115
+ const handlers = services.flatMap((service) => service.handlers);
116
+ const explicit = handlers.filter((handler) => handler.protocolFamily === PROTOCOL_FAMILY);
117
+ if (explicit.length > 0 && protocolMode !== 'BIDI_STREAM') {
118
+ throw new Error(
119
+ `@restatedev/sessions: session objects need a bidirectional stream (HTTP/2): the explicit recovery ` +
120
+ `protocol is not served over request/response (${[...sessions.keys()].join(', ')})`,
121
+ );
122
+ }
123
+ const { minProtocolVersion, maxProtocolVersion, services: _, ...rest } = sdk;
124
+ // The durable execution range only if a handler speaks that protocol.
125
+ const durable = explicit.length < handlers.length || handlers.length === 0;
126
+ return {
127
+ ...rest,
128
+ protocolMode,
129
+ ...(durable ? { minProtocolVersion, maxProtocolVersion } : {}),
130
+ ...(explicit.length > 0 ? { explicitRecoveryProtocol: explicitRecoveryProtocolRange() } : {}),
131
+ services,
132
+ };
133
+ }
134
+
135
+ /** Answer `/discover` with manifest v6, if Restate takes it (`accept`). */
136
+ function discover(
137
+ endpoint: Endpoint,
138
+ protocolMode: 'BIDI_STREAM' | 'REQUEST_RESPONSE',
139
+ accept: string | string[] | undefined,
140
+ response: Http2ServerResponse | ServerResponse,
141
+ ): void {
142
+ const fail = (status: number, message: string) => {
143
+ (response as Http2ServerResponse).writeHead(status, { 'content-type': 'text/plain' });
144
+ response.end(message);
145
+ };
146
+ const accepted = Array.isArray(accept) ? accept.join(',') : (accept ?? '');
147
+ if (!accepted.includes(MANIFEST_V6)) {
148
+ fail(
149
+ 500,
150
+ '@restatedev/sessions: the Restate server is too old: session objects use the explicit recovery protocol, ' +
151
+ `which needs discovery protocol version 6 (it accepts ${accepted || 'nothing'})`,
152
+ );
153
+ return;
154
+ }
155
+ let manifest: Record<string, unknown>;
156
+ try {
157
+ manifest = manifestV6(endpoint, protocolMode);
158
+ } catch (error) {
159
+ fail(500, (error as Error).message);
160
+ return;
161
+ }
162
+ (response as Http2ServerResponse).writeHead(200, {
163
+ 'content-type': MANIFEST_V6,
164
+ 'x-restate-server': 'restate-sdk-typescript (@restatedev/sessions)',
165
+ });
166
+ response.end(JSON.stringify(manifest));
167
+ }
168
+
169
+ /** Whether the process is going away (a SIGTERM): new attempts are refused. */
170
+ let draining = false;
171
+ /** The log of the first endpoint that watches for a SIGTERM, which says what one does. */
172
+ let watching: Log | undefined;
173
+
174
+ /**
175
+ * On a SIGTERM, end the attempts under way with an unasked `ShutdownMessage`
176
+ * (Restate starts each again, elsewhere, with no retry counted) and refuse
177
+ * new ones with 503, which Restate retries with a backoff: by then this port
178
+ * is gone. With no other SIGTERM listener the process then goes, as it
179
+ * would have without this one.
180
+ */
181
+ function watchSigterm(log: Log): void {
182
+ if (watching !== undefined) return;
183
+ watching = log;
184
+ process.on('SIGTERM', onSigterm);
185
+ }
186
+
187
+ /** What {@link watchSigterm} does on a SIGTERM. */
188
+ function onSigterm(): void {
189
+ draining = true;
190
+ const ended = goAway();
191
+ watching?.('info', `SIGTERM: ended ${ended} attempts with a shutdown, and refuses new ones (503)`);
192
+ if (process.listenerCount('SIGTERM') > 1) return;
193
+ process.removeListener('SIGTERM', onSigterm);
194
+ // A moment for the shutdowns to reach the socket, then the signal's own end.
195
+ setTimeout(() => process.kill(process.pid, 'SIGTERM'), ended > 0 ? 200 : 0);
196
+ }
197
+
198
+ /** What the SDK answers a request whose signature does not verify: nothing runs. */
199
+ function unauthorized(response: Http2ServerResponse | ServerResponse): void {
200
+ (response as Http2ServerResponse).writeHead(401, { 'content-type': 'text/plain' });
201
+ response.end('Unauthorized');
202
+ }
203
+
69
204
  /** One invocation over HTTP/2, as {@link Stream}. */
70
205
  function streamOf(request: Http2ServerRequest, response: Http2ServerResponse): Stream {
71
206
  return {
@@ -77,37 +212,45 @@ function streamOf(request: Http2ServerRequest, response: Http2ServerResponse): S
77
212
  };
78
213
  }
79
214
 
215
+ /** A path the SDK serves as a serde preview (its `PREVIEW_PATH_REGEX`). */
216
+ const PREVIEW = /(?:^|\/)serdes\/[^/]+\/(?:encode|decode)\/.+?\/?$/;
217
+
80
218
  /**
81
- * The path of `url` and the route it names, as the SDK reads it: the last
82
- * three fragments. Nothing if it names no invocation, or is no path at all —
83
- * `//` is a URL with an empty host, which `URL` refuses. Restate sends none
84
- * of those, but anything that reaches the port can, and this runs in the
85
- * request listener, where a throw is an `uncaughtException`.
219
+ * What `url` names, read as the SDK reads it (`parseUrlComponents`), in its
220
+ * order: a serde preview; an invocation, by the last three fragments of the
221
+ * path (`.../invoke/<service>/<handler>`); discovery, by the last one. So a
222
+ * handler named `discover` is invoked, not answered with the manifest.
223
+ * Anything else, and anything that is no path at all, is `other`: `//` is a
224
+ * URL with an empty host, which `URL` refuses. Restate sends none of those,
225
+ * but anything that reaches the port can, and this runs in the request
226
+ * listener, where a throw is an `uncaughtException`.
86
227
  */
87
- function parse(url: string): { path: string; service: string; handler: string } | undefined {
228
+ function routeOf(
229
+ url: string,
230
+ ):
231
+ | { kind: 'invoke'; path: string; service: string; handler: string }
232
+ | { kind: 'discover'; path: string }
233
+ | { kind: 'other' } {
88
234
  let path;
89
235
  try {
90
236
  path = new URL(url, 'http://invoke').pathname;
91
237
  } catch {
92
- return undefined;
238
+ return { kind: 'other' };
93
239
  }
240
+ if (PREVIEW.test(path)) return { kind: 'other' };
94
241
  const parts = path.split('/');
95
- if (parts.length < 3 || parts[parts.length - 3] !== 'invoke') return undefined;
96
- const service = parts[parts.length - 2]!;
97
- const handler = parts[parts.length - 1]!;
98
- return service === '' || handler === '' ? undefined : { path, service, handler };
99
- }
100
-
101
- /** The route of an invocation's path, as the SDK reads it. */
102
- export function invokeRoute(url: string): { service: string; handler: string } | undefined {
103
- const route = parse(url);
104
- return route === undefined ? undefined : { service: route.service, handler: route.handler };
242
+ if (parts.length >= 3 && parts[parts.length - 3] === 'invoke') {
243
+ const service = parts[parts.length - 2]!;
244
+ const handler = parts[parts.length - 1]!;
245
+ return service === '' || handler === '' ? { kind: 'other' } : { kind: 'invoke', path, service, handler };
246
+ }
247
+ return parts.at(-1) === 'discover' ? { kind: 'discover', path } : { kind: 'other' };
105
248
  }
106
249
 
107
250
  /**
108
- * `sdk`, with a session object's invocations run on the VM instead. A request
109
- * that is not one — discovery, the health check, a library's journaled objects
110
- * — is the SDK's, unchanged.
251
+ * `sdk`, with a session object's invocations run on the VM instead, and the
252
+ * discovery that declares them answered here. A request that is neither —
253
+ * the health check, a library's journaled objects — is the SDK's, unchanged.
111
254
  */
112
255
  function routing(
113
256
  endpoint: Endpoint,
@@ -115,52 +258,62 @@ function routing(
115
258
  bidirectional: (request: { httpVersionMajor?: number }) => boolean,
116
259
  ): (request: Http2ServerRequest | IncomingMessage, response: Http2ServerResponse | ServerResponse) => void {
117
260
  const sessions = sessionsOf(endpoint);
118
- refuseWhatTheVmCannotServe(endpoint, sessions);
261
+ const log = logOf(endpoint.builder.loggerTransport);
262
+ if (sessions.size > 0) watchSigterm(log);
119
263
  // The SDK verifies a request's signature in the handler this routes ahead
120
- // of, so an invocation that goes to the VM is verified here instead. Every
121
- // `connect` has keys: its key carries the signing key, and the SDK refuses
122
- // one that does not.
264
+ // of, so a request served here is verified here instead. Every `connect`
265
+ // has keys: its key carries the signing key, and the SDK refuses one that
266
+ // does not.
123
267
  const identity = endpoint.builder.keySet.length > 0 ? new Identity(endpoint.builder.keySet) : undefined;
268
+ // `null` is a verified request, as the addon answers `None` with: a
269
+ // deployment without keys verifies nothing, and stands for the same.
270
+ const unsigned = (path: string, request: { headers: IncomingMessage['headers'] }) =>
271
+ identity === undefined ? null : identity.verify(path, headersOf(request.headers));
272
+ // Why it does not verify is not logged: it can quote a header.
273
+ const refuse = (path: string, response: Http2ServerResponse | ServerResponse) => {
274
+ log('warn', `refused a request for ${path}: its signature does not verify (401)`);
275
+ unauthorized(response);
276
+ };
124
277
  return (request, response) => {
125
- const route = sessions.size === 0 ? undefined : parse(request.url ?? '');
126
- const definition = route === undefined ? undefined : sessions.get(route.service);
127
- if (definition === undefined || route === undefined) {
278
+ if (sessions.size === 0) {
128
279
  sdk(request as never, response as never);
129
280
  return;
130
281
  }
131
- const { path } = route;
132
- // `null` is a verified request, as the addon answers `None` with: a
133
- // deployment without keys verifies nothing, and stands for the same.
134
- const unsigned = identity === undefined ? null : identity.verify(path, headersOf(request.headers));
135
- if (unsigned !== null) {
136
- // What the SDK answers, and the handler never runs.
137
- (response as Http2ServerResponse).writeHead(401, { 'content-type': 'text/plain' });
138
- response.end('Unauthorized');
282
+ const route = routeOf(request.url ?? '');
283
+ if (route.kind === 'discover') {
284
+ if (unsigned(route.path, request) !== null) return refuse(route.path, response);
285
+ discover(endpoint, bidirectional(request) ? 'BIDI_STREAM' : 'REQUEST_RESPONSE', request.headers.accept, response);
139
286
  return;
140
287
  }
141
- // After the signature check, so that an unsigned request learns nothing
142
- // about what is bound here: the SDK answers one 401 for anything.
143
- if (!servedHere(request.headers)) {
144
- // A session object on a Restate too old for the VM. Handing it to the
145
- // SDK would run it on a VM that replays, which such a handler cannot
146
- // use; it would be refused there for the wrong reason, naming endpoint
147
- // types to someone whose endpoint is fine. Say which it is.
148
- const type = request.headers['content-type'];
149
- const spoken = /\.invocation\.(v\d+)/.exec((Array.isArray(type) ? type[0] : type) ?? '')?.[1] ?? 'none';
150
- (response as Http2ServerResponse).writeHead(415, { 'content-type': 'text/plain' });
151
- response.end(
152
- `@restatedev/sessions: ${route.service}/${route.handler} is a session object, which runs on the ` +
153
- `explicit recovery VM and needs Restate's service protocol v${MIN_PROTOCOL} or later; this ` +
154
- `invocation negotiated ${spoken}. Upgrade the Restate server.`,
155
- );
288
+ const definition = route.kind === 'invoke' ? sessions.get(route.service) : undefined;
289
+ if (definition === undefined || route.kind !== 'invoke') {
290
+ sdk(request as never, response as never);
156
291
  return;
157
292
  }
158
- serveSession(definition, route.handler, streamOf(request as Http2ServerRequest, response as Http2ServerResponse), {
159
- bidirectional: bidirectional(request),
160
- }).catch((error: unknown) => {
161
- // The attempt could not be served at all: the VM wrote nothing.
293
+ if (unsigned(route.path, request) !== null) return refuse(route.path, response);
294
+ if (draining) {
295
+ // Going away: before any VM or user code runs. Restate counts a retry
296
+ // and backs off, and the next attempt reaches the process that replaces
297
+ // this one. The body is not drained: it stays open on this protocol.
298
+ (response as Http2ServerResponse).writeHead(503, {});
299
+ response.end();
300
+ return;
301
+ }
302
+ serveSession(
303
+ definition,
304
+ route.handler,
305
+ streamOf(request as Http2ServerRequest, response as Http2ServerResponse),
306
+ endpoint.builder.defaultServiceOptions,
307
+ log,
308
+ ).catch((error: unknown) => {
309
+ // The attempt could not be served at all: the VM wrote nothing. The
310
+ // reason goes to the log, not to whoever sent the request.
311
+ log(
312
+ 'error',
313
+ `${route.service}/${route.handler}: could not be served: ${error instanceof Error ? error.message : String(error)}`,
314
+ );
162
315
  if (!response.headersSent) (response as Http2ServerResponse).writeHead(500, { 'content-type': 'text/plain' });
163
- response.end(error instanceof Error ? error.message : String(error));
316
+ response.end('@restatedev/sessions: the invocation could not be served');
164
317
  });
165
318
  };
166
319
  }
@@ -192,6 +345,8 @@ export function patchEndpoint(): void {
192
345
  ) => {
193
346
  const original = prototype[method] as Endpoint['handler'];
194
347
  prototype[method] = function (this: Endpoint, options?: { bidirectional?: boolean }) {
348
+ // Before the SDK builds the endpoint, which would refuse some of it in its own words.
349
+ refuseWhatTheVmCannotServe(this, sessionsOf(this));
195
350
  const sdk = original.call(this, options);
196
351
  return routing(this, sdk, (request) => mode(options?.bidirectional, request)) as never;
197
352
  };