@restatedev/sessions 0.0.0 → 0.2.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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +480 -2
  3. package/dist/calls.d.ts +72 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +86 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/database.d.ts +169 -0
  8. package/dist/database.d.ts.map +1 -0
  9. package/dist/database.js +264 -0
  10. package/dist/database.js.map +1 -0
  11. package/dist/index.d.ts +7 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +28 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/internal.d.ts +10 -0
  16. package/dist/internal.d.ts.map +1 -0
  17. package/dist/internal.js +13 -0
  18. package/dist/internal.js.map +1 -0
  19. package/dist/object.d.ts +162 -0
  20. package/dist/object.d.ts.map +1 -0
  21. package/dist/object.js +235 -0
  22. package/dist/object.js.map +1 -0
  23. package/dist/platform.d.ts +5 -0
  24. package/dist/platform.d.ts.map +1 -0
  25. package/dist/platform.js +15 -0
  26. package/dist/platform.js.map +1 -0
  27. package/dist/schema.d.ts +35 -0
  28. package/dist/schema.d.ts.map +1 -0
  29. package/dist/schema.js +118 -0
  30. package/dist/schema.js.map +1 -0
  31. package/dist/selector.d.ts +86 -0
  32. package/dist/selector.d.ts.map +1 -0
  33. package/dist/selector.js +196 -0
  34. package/dist/selector.js.map +1 -0
  35. package/dist/serve.d.ts +21 -0
  36. package/dist/serve.d.ts.map +1 -0
  37. package/dist/serve.js +49 -0
  38. package/dist/serve.js.map +1 -0
  39. package/dist/session.d.ts +167 -0
  40. package/dist/session.d.ts.map +1 -0
  41. package/dist/session.js +547 -0
  42. package/dist/session.js.map +1 -0
  43. package/package.json +40 -5
  44. package/src/calls.ts +197 -0
  45. package/src/database.ts +392 -0
  46. package/src/index.ts +38 -0
  47. package/src/internal.ts +14 -0
  48. package/src/object.ts +368 -0
  49. package/src/platform.ts +15 -0
  50. package/src/schema.ts +162 -0
  51. package/src/selector.ts +253 -0
  52. package/src/serve.ts +54 -0
  53. package/src/session.ts +663 -0
@@ -0,0 +1,253 @@
1
+ // Concurrent awaits in a handler with SQL: one loop, the selector, drives
2
+ // every promise the handler awaits.
3
+ //
4
+ // The published SDK drives each awaited RestatePromise with a loop of its own,
5
+ // and only one of them may wait for progress from the server at a time
6
+ // (`ExternalProgressChannel.awaitNext`): two promises awaited at once that
7
+ // both need the server, such as two state reads with lazy state, fail the
8
+ // attempt with "awaitNext already pending". With journal replay, that order of
9
+ // awaits is part of what a replay must match; with explicit recovery nothing
10
+ // is replayed, so a handler with SQL hands every awaited promise to one loop,
11
+ // which asks the VM about all of them at once (`hookSelector`). The hook
12
+ // replaces the invocation's `promisesExecutor.doProgress`: it relies on the
13
+ // SDK's internals, as of the version this package pins (1.18.2).
14
+ //
15
+ // TODO: drop the selector, and the pin, once an SDK release lets a handler
16
+ // with explicit recovery await concurrently.
17
+ import { setImmediate } from 'node:timers/promises';
18
+
19
+ /** A future of the VM, as `do_progress` takes it. */
20
+ export type UnresolvedFuture =
21
+ | { Single: number }
22
+ | { FirstCompleted: UnresolvedFuture[] }
23
+ | { AllCompleted: UnresolvedFuture[] }
24
+ | { FirstSucceededOrAllFailed: UnresolvedFuture[] }
25
+ | { AllSucceededOrFirstFailed: UnresolvedFuture[] }
26
+ | { Unknown: UnresolvedFuture[] };
27
+
28
+ /** What `do_progress` returns. */
29
+ export type DoProgressResult =
30
+ | 'AnyCompleted'
31
+ | 'WaitExternalProgress'
32
+ | { ExecuteRun: number }
33
+ | 'CancelSignalReceived'
34
+ | { EphemeralNotificationReady: number };
35
+
36
+ /** What the selector needs of a promise: the shape of InternalRestatePromise. */
37
+ export interface Selectable {
38
+ /** Takes the result if it is ready, and settles the promise with it. */
39
+ tryComplete(): Promise<void>;
40
+ /** What it still waits for, or null once settled. */
41
+ unresolvedFuture(): UnresolvedFuture | null;
42
+ /** Rejects it with a CancelledError. */
43
+ tryCancel(): void;
44
+ }
45
+
46
+ /** What the selector needs of the invocation. */
47
+ export interface SelectorDriver {
48
+ doProgress(future: UnresolvedFuture): DoProgressResult;
49
+ /** Writes out what the VM has buffered. */
50
+ flushOutput(): Promise<void>;
51
+ /** Resolves on the next signal of external progress (input, a finished run, a registration). */
52
+ awaitExternalProgress(): Promise<void>;
53
+ /** Signals external progress. */
54
+ wake(): void;
55
+ executeRun(handle: number): void;
56
+ completeEphemeral(completionId: number): Promise<void>;
57
+ /** The attempt cannot go on: suspension, or an error. */
58
+ onError(e: unknown): void;
59
+ }
60
+
61
+ /**
62
+ * One loop that drives every pending promise of an invocation, so that the
63
+ * invocation has a single await point however many promises user code awaits
64
+ * at once, with its own combinators or none.
65
+ *
66
+ * A promise is registered once and stays until it settles. The loop settles
67
+ * whatever is ready, then asks the VM for progress on the first of all the
68
+ * pending promises to complete: so a suspension waits for any of them, a
69
+ * pending run starts whichever promise is awaited first, and a cancellation
70
+ * reaches all of them. Registering wakes the loop, so a promise registered
71
+ * while it waits is part of the next await point. An ephemeral command (a
72
+ * state get left out of the journal) is registered by its completion id: the
73
+ * VM reports its notification ahead of any future, and the loop goes on while
74
+ * one is in flight, even with no promise pending. The loop runs while
75
+ * something is pending, and is the only one waiting for external progress.
76
+ */
77
+ export class PromiseSelector {
78
+ private readonly pending = new Set<Selectable>();
79
+ // The completion ids of the ephemeral commands in flight.
80
+ private readonly ephemeral = new Set<number>();
81
+ private running = false;
82
+ private closed = false;
83
+ // Between the VM's WaitExternalProgress and the next external progress.
84
+ private waiting = false;
85
+
86
+ private readonly driver: SelectorDriver;
87
+
88
+ constructor(driver: SelectorDriver) {
89
+ this.driver = driver;
90
+ }
91
+
92
+ register(promise: Selectable): void {
93
+ if (this.closed || this.pending.has(promise)) return;
94
+ this.pending.add(promise);
95
+ this.start();
96
+ }
97
+
98
+ /** An ephemeral command's completion id, until its notification is ready. */
99
+ registerEphemeral(completionId: number): void {
100
+ if (this.closed) return;
101
+ this.ephemeral.add(completionId);
102
+ this.start();
103
+ }
104
+
105
+ private start(): void {
106
+ if (this.running) {
107
+ this.wake();
108
+ } else {
109
+ this.running = true;
110
+ void this.loop();
111
+ }
112
+ }
113
+
114
+ /** Stops the loop (it finds nothing pending), at the end of the attempt. */
115
+ close(): void {
116
+ if (this.closed) return;
117
+ this.closed = true;
118
+ this.pending.clear();
119
+ this.ephemeral.clear();
120
+ if (this.running) this.wake();
121
+ }
122
+
123
+ // Only a waiting loop needs waking, once: any other picks up the change on
124
+ // its next pass. (Waking it otherwise would buffer a signal per promise, and
125
+ // as many needless passes.)
126
+ private wake(): void {
127
+ if (!this.waiting) return;
128
+ this.waiting = false;
129
+ this.driver.wake();
130
+ }
131
+
132
+ /** The promises still pending, for tests. */
133
+ get size(): number {
134
+ return this.pending.size + this.ephemeral.size;
135
+ }
136
+
137
+ private async loop(): Promise<void> {
138
+ try {
139
+ await this.driver.flushOutput();
140
+ for (;;) {
141
+ // Settle what is ready.
142
+ for (const promise of this.pending) {
143
+ await promise.tryComplete();
144
+ }
145
+ // Let what that settled run, and register what it awaits next, so
146
+ // that one check covers them (a combinator also flags itself
147
+ // completed in a .finally, a tick late). An optimization: what is
148
+ // registered later wakes the loop anyway.
149
+ await setImmediate();
150
+
151
+ const futures: UnresolvedFuture[] = [];
152
+ for (const promise of this.pending) {
153
+ const future = promise.unresolvedFuture();
154
+ if (future === null) {
155
+ this.pending.delete(promise);
156
+ } else {
157
+ futures.push(future);
158
+ }
159
+ }
160
+ if (futures.length === 0 && this.ephemeral.size === 0) return;
161
+
162
+ // With only ephemeral commands in flight, no future: the VM reports
163
+ // their notifications, or waits for input.
164
+ const result = this.driver.doProgress(futures.length === 1 ? futures[0]! : { FirstCompleted: futures });
165
+ if (result === 'AnyCompleted') {
166
+ continue;
167
+ } else if (result === 'WaitExternalProgress') {
168
+ // From here, in the same turn as the check: what is registered
169
+ // after it is not part of it.
170
+ this.waiting = true;
171
+ await this.driver.flushOutput();
172
+ await this.driver.awaitExternalProgress();
173
+ this.waiting = false;
174
+ } else if (result === 'CancelSignalReceived') {
175
+ // Reaches every pending promise; what is awaited after it is not cancelled.
176
+ for (const promise of this.pending) promise.tryCancel();
177
+ this.pending.clear();
178
+ } else if ('EphemeralNotificationReady' in result) {
179
+ this.ephemeral.delete(result.EphemeralNotificationReady);
180
+ await this.driver.completeEphemeral(result.EphemeralNotificationReady);
181
+ } else {
182
+ this.driver.executeRun(result.ExecuteRun);
183
+ // Let the run start, then come back.
184
+ await setImmediate();
185
+ }
186
+ }
187
+ } catch (e) {
188
+ this.close();
189
+ this.driver.onError(e);
190
+ } finally {
191
+ // Decided with nothing pending, in the same turn: a registration from
192
+ // here on starts a new loop.
193
+ this.running = false;
194
+ }
195
+ }
196
+ }
197
+
198
+ /** The SDK's promises executor, as far as the hook needs it: its fields are private in its types. */
199
+ interface Executor {
200
+ doProgress(promise: Selectable): Promise<void>;
201
+ coreVm: {
202
+ do_progress(future: UnresolvedFuture): DoProgressResult;
203
+ take_ephemeral_notification(completionId: number): unknown;
204
+ };
205
+ outputPump: { awaitNextProgress(): Promise<void> };
206
+ externalProgressChannel: { awaitNext(): Promise<void>; signal(): void };
207
+ runClosuresTracker: { executeRun(handle: number): void };
208
+ ephemeralRequestTracker: { complete(completionId: number, value: unknown): Promise<void> };
209
+ errorCallback: (e: unknown) => void;
210
+ }
211
+
212
+ const FIELDS = [
213
+ 'coreVm',
214
+ 'outputPump',
215
+ 'externalProgressChannel',
216
+ 'runClosuresTracker',
217
+ 'ephemeralRequestTracker',
218
+ 'errorCallback',
219
+ ] as const;
220
+
221
+ /**
222
+ * Drive every promise that the invocation of `ctx` (the SDK's context, not a
223
+ * proxy of it) awaits from here on with one selector. The returned function
224
+ * stops it, at the end of the attempt, and gives the invocation back its
225
+ * own loops.
226
+ */
227
+ export function hookSelector(ctx: object): () => void {
228
+ const executor = (ctx as { promisesExecutor?: Executor }).promisesExecutor;
229
+ const missing = executor ? FIELDS.filter((field) => executor[field] === undefined) : ['promisesExecutor'];
230
+ if (missing.length > 0 || typeof executor?.coreVm.do_progress !== 'function') {
231
+ throw new Error(
232
+ `@restatedev/sessions drives a handler's promises through the SDK's internals, which this SDK version does not have ` +
233
+ `(${missing.join(', ') || 'coreVm.do_progress'}): use the @restatedev/restate-sdk that @restatedev/sessions pins`,
234
+ );
235
+ }
236
+ const { coreVm, outputPump, externalProgressChannel, runClosuresTracker, ephemeralRequestTracker } = executor;
237
+ const selector = new PromiseSelector({
238
+ doProgress: (future) => coreVm.do_progress(future),
239
+ flushOutput: () => outputPump.awaitNextProgress(),
240
+ awaitExternalProgress: () => externalProgressChannel.awaitNext(),
241
+ wake: () => externalProgressChannel.signal(),
242
+ executeRun: (handle) => runClosuresTracker.executeRun(handle),
243
+ completeEphemeral: (completionId) =>
244
+ ephemeralRequestTracker.complete(completionId, coreVm.take_ephemeral_notification(completionId)),
245
+ onError: (e) => executor.errorCallback(e),
246
+ });
247
+ // An own property, over the class's method: removing it gives the method back.
248
+ executor.doProgress = async (promise) => selector.register(promise);
249
+ return () => {
250
+ selector.close();
251
+ delete (executor as Partial<Executor>).doProgress;
252
+ };
253
+ }
package/src/serve.ts ADDED
@@ -0,0 +1,54 @@
1
+ // `serve`: the services of a program, on PORT, with what they need beside
2
+ // them (a library's objects, such as @restatedev/agents' `signals`).
3
+ import * as restate from '@restatedev/restate-sdk';
4
+
5
+ type Service = restate.ServeOptions['services'][number];
6
+
7
+ /** Where a definition keeps the services it needs served beside it: see {@link needing}. */
8
+ const NEEDS = Symbol.for('restate-sessions.needs');
9
+
10
+ /**
11
+ * `definition`, which needs `services` served beside it: {@link serve}
12
+ * serves them too. For a library whose objects call one of its own (an
13
+ * agent's `signals`, say).
14
+ */
15
+ export const needing = <D extends object>(definition: D, services: () => Service[]): D =>
16
+ Object.defineProperty(definition, NEEDS, { value: services });
17
+
18
+ /**
19
+ * Serve `services` on PORT (default 9080), with the services they need
20
+ * beside them, each once. RESTATE_SERVE_ONLY, names separated by commas
21
+ * (`triage,planner,signals`), serves only those of them: one program (or
22
+ * image), deployed in parts.
23
+ *
24
+ * await restate.serve(notes, orders);
25
+ */
26
+ export const serve = (...services: Service[]) =>
27
+ restate.serve({ services: served(services, process.env.RESTATE_SERVE_ONLY), port: Number(process.env.PORT ?? 9080) });
28
+
29
+ /** What {@link serve} serves of `services`: each with what it needs beside it, once, of those `names` names. */
30
+ export function served(services: Service[], names?: string): Service[] {
31
+ const all = new Map<string, Service>();
32
+ const add = (service: Service) => {
33
+ if (all.has(service.name)) return;
34
+ all.set(service.name, service);
35
+ for (const needed of (service as { [NEEDS]?: () => Service[] })[NEEDS]?.() ?? []) add(needed);
36
+ };
37
+ services.forEach(add);
38
+ return only([...all.values()], names);
39
+ }
40
+
41
+ /** The `services` that `names` (comma separated) names, or all of them without names; a name of none is an error. */
42
+ function only(services: Service[], names: string | undefined) {
43
+ const wanted = (names ?? '')
44
+ .split(',')
45
+ .map((name) => name.trim())
46
+ .filter(Boolean);
47
+ if (wanted.length === 0) return services;
48
+ const known = services.map((s) => s.name);
49
+ const unknown = wanted.filter((name) => !known.includes(name));
50
+ if (unknown.length > 0) {
51
+ throw new Error(`RESTATE_SERVE_ONLY names ${unknown.join(', ')}: the services are ${known.join(', ')}`);
52
+ }
53
+ return services.filter((s) => wanted.includes(s.name));
54
+ }