@restatedev/sessions 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/selector.js CHANGED
@@ -15,30 +15,57 @@
15
15
  // TODO: drop the selector, and the pin, once an SDK release lets a handler
16
16
  // with explicit recovery await concurrently.
17
17
  import { setImmediate } from 'node:timers/promises';
18
+ /** The handle of the invocation's cancel signal: the VM's, and what `ctx.cancellation()` awaits. */
19
+ const CANCELLATION = 1;
20
+ /** Whether `future` waits for the invocation's cancellation, and nothing else. */
21
+ const cancellationAlone = (future) => 'Single' in future ? future.Single === CANCELLATION : Object.values(future)[0].every(cancellationAlone);
22
+ /**
23
+ * For tests: what every selector's loop awaits at each of its failpoints, to
24
+ * hold it there while something else happens (the input closes, a signal
25
+ * comes). At `wait`, it gets what the check asked for, and whether that was
26
+ * the invocation's cancellation alone (with the working run). Empty
27
+ * otherwise, and the loop then awaits nothing there.
28
+ */
29
+ export const failpoints = new Map();
18
30
  /**
19
31
  * One loop that drives every pending promise of an invocation, so that the
20
32
  * invocation has a single await point however many promises user code awaits
21
33
  * at once, with its own combinators or none.
22
34
  *
23
- * A promise is registered once and stays until it settles. The loop settles
24
- * whatever is ready, then asks the VM for progress on the first of all the
25
- * pending promises to complete: so a suspension waits for any of them, a
26
- * pending run starts whichever promise is awaited first, and a cancellation
27
- * reaches all of them. Registering wakes the loop, so a promise registered
28
- * while it waits is part of the next await point. An ephemeral command (a
29
- * state get left out of the journal) is registered by its completion id: the
30
- * VM reports its notification ahead of any future, and the loop goes on while
31
- * one is in flight, even with no promise pending. The loop runs while
32
- * something is pending, and is the only one waiting for external progress.
35
+ * A promise is registered once and stays until it settles. Each pass of the
36
+ * loop settles what is ready, then asks the VM for progress on the first of
37
+ * all the pending promises to complete: so a suspension waits for any of
38
+ * them, a pending run starts whichever promise is awaited first, and a
39
+ * cancellation reaches all of them. Registering wakes the loop, so a promise
40
+ * registered while it waits is part of the next pass. The loop runs while
41
+ * there is something to ask the VM for, and is the only one waiting for
42
+ * external progress.
43
+ *
44
+ * To ask is to say that the handler waits: the VM tells Restate what for,
45
+ * and suspends the invocation on it once the input closed (Restate's
46
+ * inactivity timeout). That holds for every promise but one. A handler with
47
+ * explicit cancellation awaits its cancellation (`cancelled(ctx)`) to stop
48
+ * work it does outside Restate, a model's request, say: it watches for it,
49
+ * and does not wait for it. Reported as awaited, the cancel signal would be
50
+ * all Restate believes the handler waits for; and suspended on it, the
51
+ * invocation would end its attempt in the middle of that work, with a
52
+ * cancellation as the only thing to resume it.
53
+ *
54
+ * So with only the cancellation pending, the loop asks for it together with
55
+ * the attempt's working run (`SelectorDriver.work`), which says what is true:
56
+ * the handler is at work on something of its own, as inside `ctx.run`. While
57
+ * a run executes, the VM reports no await, and does not suspend on a future
58
+ * the run is part of, whether the input is open or closed; and it still
59
+ * finds the cancel signal when it comes. See `awaited`.
33
60
  */
34
61
  export class PromiseSelector {
35
62
  pending = new Set();
36
- // The completion ids of the ephemeral commands in flight.
37
- ephemeral = new Set();
38
63
  running = false;
39
64
  closed = false;
40
- // Between the VM's WaitExternalProgress and the next external progress.
65
+ // Between a check that found nothing and the next external progress.
41
66
  waiting = false;
67
+ // Whether the last check asked for the cancellation alone, with the working run.
68
+ watching = false;
42
69
  driver;
43
70
  constructor(driver) {
44
71
  this.driver = driver;
@@ -47,16 +74,6 @@ export class PromiseSelector {
47
74
  if (this.closed || this.pending.has(promise))
48
75
  return;
49
76
  this.pending.add(promise);
50
- this.start();
51
- }
52
- /** An ephemeral command's completion id, until its notification is ready. */
53
- registerEphemeral(completionId) {
54
- if (this.closed)
55
- return;
56
- this.ephemeral.add(completionId);
57
- this.start();
58
- }
59
- start() {
60
77
  if (this.running) {
61
78
  this.wake();
62
79
  }
@@ -71,13 +88,12 @@ export class PromiseSelector {
71
88
  return;
72
89
  this.closed = true;
73
90
  this.pending.clear();
74
- this.ephemeral.clear();
75
91
  if (this.running)
76
92
  this.wake();
77
93
  }
78
94
  // Only a waiting loop needs waking, once: any other picks up the change on
79
95
  // its next pass. (Waking it otherwise would buffer a signal per promise, and
80
- // as many needless passes.)
96
+ // as many needless passes, each of which tells Restate what is awaited.)
81
97
  wake() {
82
98
  if (!this.waiting)
83
99
  return;
@@ -86,43 +102,63 @@ export class PromiseSelector {
86
102
  }
87
103
  /** The promises still pending, for tests. */
88
104
  get size() {
89
- return this.pending.size + this.ephemeral.size;
105
+ return this.pending.size;
106
+ }
107
+ /**
108
+ * What to ask the VM for: the first of the pending promises to complete,
109
+ * or undefined with nothing pending. With only the invocation's
110
+ * cancellation pending, the handler watches and waits for nothing: the
111
+ * working run goes with it (see the class).
112
+ */
113
+ awaited() {
114
+ const futures = [];
115
+ let watching = true; // for the cancellation, and waiting for nothing
116
+ for (const promise of this.pending) {
117
+ const future = promise.unresolvedFuture();
118
+ if (future === null) {
119
+ this.pending.delete(promise);
120
+ }
121
+ else {
122
+ futures.push(future);
123
+ watching &&= cancellationAlone(future);
124
+ }
125
+ }
126
+ this.watching = watching && futures.length > 0;
127
+ if (futures.length === 0)
128
+ return undefined;
129
+ if (watching)
130
+ futures.push({ Single: this.driver.work() });
131
+ return futures.length === 1 ? futures[0] : { FirstCompleted: futures };
90
132
  }
91
133
  async loop() {
92
134
  try {
93
135
  await this.driver.flushOutput();
94
136
  for (;;) {
137
+ if (failpoints.size > 0)
138
+ await failpoints.get('pass')?.();
95
139
  // Settle what is ready.
96
140
  for (const promise of this.pending) {
97
141
  await promise.tryComplete();
98
142
  }
99
- // Let what that settled run, and register what it awaits next, so
100
- // that one check covers them (a combinator also flags itself
101
- // completed in a .finally, a tick late). An optimization: what is
102
- // registered later wakes the loop anyway.
143
+ // A turn of the event loop: what was settled runs, and registers
144
+ // what it awaits next, so that one check covers that too (a
145
+ // combinator also flags itself completed in a .finally, a tick late).
146
+ // An optimization: what is registered later wakes the loop anyway.
103
147
  await setImmediate();
104
- const futures = [];
105
- for (const promise of this.pending) {
106
- const future = promise.unresolvedFuture();
107
- if (future === null) {
108
- this.pending.delete(promise);
109
- }
110
- else {
111
- futures.push(future);
112
- }
113
- }
114
- if (futures.length === 0 && this.ephemeral.size === 0)
148
+ // From here to the end of the pass, or to `waiting`, in one turn:
149
+ // what is registered after the check finds the loop gone, and starts
150
+ // another, or finds it waiting, and wakes it.
151
+ const future = this.awaited();
152
+ if (future === undefined)
115
153
  return;
116
- // With only ephemeral commands in flight, no future: the VM reports
117
- // their notifications, or waits for input.
118
- const result = this.driver.doProgress(futures.length === 1 ? futures[0] : { FirstCompleted: futures });
154
+ const result = this.driver.doProgress(future);
119
155
  if (result === 'AnyCompleted') {
120
156
  continue;
121
157
  }
122
158
  else if (result === 'WaitExternalProgress') {
123
- // From here, in the same turn as the check: what is registered
124
- // after it is not part of it.
125
159
  this.waiting = true;
160
+ if (failpoints.size > 0)
161
+ await failpoints.get('wait')?.(future, this.watching);
126
162
  await this.driver.flushOutput();
127
163
  await this.driver.awaitExternalProgress();
128
164
  this.waiting = false;
@@ -133,14 +169,13 @@ export class PromiseSelector {
133
169
  promise.tryCancel();
134
170
  this.pending.clear();
135
171
  }
136
- else if ('EphemeralNotificationReady' in result) {
137
- this.ephemeral.delete(result.EphemeralNotificationReady);
138
- await this.driver.completeEphemeral(result.EphemeralNotificationReady);
172
+ else if ('ExecuteRun' in result) {
173
+ // It starts in the turn the next pass takes before its check.
174
+ this.driver.executeRun(result.ExecuteRun);
139
175
  }
140
176
  else {
141
- this.driver.executeRun(result.ExecuteRun);
142
- // Let the run start, then come back.
143
- await setImmediate();
177
+ // An ephemeral command's notification: a handler with SQL makes none.
178
+ throw new Error(`@restatedev/sessions: unexpected progress from the VM: ${JSON.stringify(result)}`);
144
179
  }
145
180
  }
146
181
  }
@@ -149,20 +184,11 @@ export class PromiseSelector {
149
184
  this.driver.onError(e);
150
185
  }
151
186
  finally {
152
- // Decided with nothing pending, in the same turn: a registration from
153
- // here on starts a new loop.
154
187
  this.running = false;
155
188
  }
156
189
  }
157
190
  }
158
- const FIELDS = [
159
- 'coreVm',
160
- 'outputPump',
161
- 'externalProgressChannel',
162
- 'runClosuresTracker',
163
- 'ephemeralRequestTracker',
164
- 'errorCallback',
165
- ];
191
+ const FIELDS = ['coreVm', 'outputPump', 'externalProgressChannel', 'runClosuresTracker', 'errorCallback'];
166
192
  /**
167
193
  * Drive every promise that the invocation of `ctx` (the SDK's context, not a
168
194
  * proxy of it) awaits from here on with one selector. The returned function
@@ -172,18 +198,36 @@ const FIELDS = [
172
198
  export function hookSelector(ctx) {
173
199
  const executor = ctx.promisesExecutor;
174
200
  const missing = executor ? FIELDS.filter((field) => executor[field] === undefined) : ['promisesExecutor'];
175
- if (missing.length > 0 || typeof executor?.coreVm.do_progress !== 'function') {
201
+ if (missing.length === 0) {
202
+ const { coreVm, runClosuresTracker } = executor;
203
+ for (const method of ['do_progress', 'sys_run', 'propose_run_completion_success']) {
204
+ if (typeof coreVm[method] !== 'function')
205
+ missing.push(`coreVm.${method}`);
206
+ }
207
+ if (typeof runClosuresTracker.registerRunClosure !== 'function')
208
+ missing.push('runClosuresTracker.registerRunClosure');
209
+ }
210
+ if (missing.length > 0 || executor === undefined) {
176
211
  throw new Error(`@restatedev/sessions drives a handler's promises through the SDK's internals, which this SDK version does not have ` +
177
- `(${missing.join(', ') || 'coreVm.do_progress'}): use the @restatedev/restate-sdk that @restatedev/sessions pins`);
212
+ `(${missing.join(', ')}): use the @restatedev/restate-sdk that @restatedev/sessions pins`);
178
213
  }
179
- const { coreVm, outputPump, externalProgressChannel, runClosuresTracker, ephemeralRequestTracker } = executor;
214
+ const { coreVm, outputPump, externalProgressChannel, runClosuresTracker } = executor;
215
+ // The working run: journaled as a run named `work`, with no closure of its
216
+ // own to end it. It ends with the attempt.
217
+ let work;
180
218
  const selector = new PromiseSelector({
181
219
  doProgress: (future) => coreVm.do_progress(future),
182
220
  flushOutput: () => outputPump.awaitNextProgress(),
183
221
  awaitExternalProgress: () => externalProgressChannel.awaitNext(),
184
222
  wake: () => externalProgressChannel.signal(),
223
+ work: () => {
224
+ if (work === undefined) {
225
+ work = coreVm.sys_run('work').handle;
226
+ runClosuresTracker.registerRunClosure(work, () => new Promise(() => { }));
227
+ }
228
+ return work;
229
+ },
185
230
  executeRun: (handle) => runClosuresTracker.executeRun(handle),
186
- completeEphemeral: (completionId) => ephemeralRequestTracker.complete(completionId, coreVm.take_ephemeral_notification(completionId)),
187
231
  onError: (e) => executor.errorCallback(e),
188
232
  });
189
233
  // An own property, over the class's method: removing it gives the method back.
@@ -191,6 +235,17 @@ export function hookSelector(ctx) {
191
235
  return () => {
192
236
  selector.close();
193
237
  delete executor.doProgress;
238
+ // The work is over: so is its run, in the journal of an invocation that
239
+ // goes on to answer. (A VM that an error or a suspension closed refuses.)
240
+ if (work !== undefined) {
241
+ try {
242
+ coreVm.propose_run_completion_success(work, new Uint8Array());
243
+ }
244
+ catch {
245
+ // The attempt ended: the next one, or nothing, ends the run.
246
+ }
247
+ work = undefined;
248
+ }
194
249
  };
195
250
  }
196
251
  //# sourceMappingURL=selector.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"selector.js","sourceRoot":"","sources":["../src/selector.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,oCAAoC;AACpC,EAAE;AACF,+EAA+E;AAC/E,uEAAuE;AACvE,2EAA2E;AAC3E,0EAA0E;AAC1E,+EAA+E;AAC/E,6EAA6E;AAC7E,8EAA8E;AAC9E,yEAAyE;AACzE,4EAA4E;AAC5E,iEAAiE;AACjE,EAAE;AACF,2EAA2E;AAC3E,6CAA6C;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AA4CpD;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,eAAe;IACT,OAAO,GAAG,IAAI,GAAG,EAAc,CAAC;IACjD,0DAA0D;IACzC,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACvC,OAAO,GAAG,KAAK,CAAC;IAChB,MAAM,GAAG,KAAK,CAAC;IACvB,wEAA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EAAE,CAAC;QACjB,OAAQ,QAA8B,CAAC,UAAU,CAAC;QAClD,wEAAwE;QACxE,0EAA0E;QAC1E,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,IAAI,CAAC;gBACH,MAAM,CAAC,8BAA8B,CAAC,IAAI,EAAE,IAAI,UAAU,EAAE,CAAC,CAAC;YAChE,CAAC;YAAC,MAAM,CAAC;gBACP,6DAA6D;YAC/D,CAAC;YACD,IAAI,GAAG,SAAS,CAAC;QACnB,CAAC;IACH,CAAC,CAAC;AACJ,CAAC"}
package/dist/serve.d.ts CHANGED
@@ -2,20 +2,27 @@ import * as restate from '@restatedev/restate-sdk';
2
2
  type Service = restate.ServeOptions['services'][number];
3
3
  /**
4
4
  * `definition`, which needs `services` served beside it: {@link serve}
5
- * serves them too. For a library whose objects call one of its own (an
6
- * agent's `signals`, say).
5
+ * serves them too. For a library whose objects call one of their own (an
6
+ * agent's companion, say).
7
7
  */
8
8
  export declare const needing: <D extends object>(definition: D, services: () => Service[]) => D;
9
9
  /**
10
10
  * Serve `services` on PORT (default 9080), with the services they need
11
11
  * beside them, each once. RESTATE_SERVE_ONLY, names separated by commas
12
- * (`triage,planner,signals`), serves only those of them: one program (or
13
- * image), deployed in parts.
12
+ * (`triage,planner`), serves only those of them, each with what it needs
13
+ * beside it: one program (or image), deployed in parts.
14
14
  *
15
15
  * await restate.serve(notes, orders);
16
16
  */
17
17
  export declare const serve: (...services: Service[]) => Promise<number>;
18
- /** What {@link serve} serves of `services`: each with what it needs beside it, once, of those `names` names. */
18
+ /**
19
+ * What {@link serve} serves of `services`: each with what it needs beside
20
+ * it, once; with `names` (separated by commas), only the services it names,
21
+ * each with what it needs beside it. For an endpoint of your own:
22
+ *
23
+ * const endpoint = restate.endpoint();
24
+ * for (const service of restate.served([notes, orders])) endpoint.bind(service);
25
+ */
19
26
  export declare function served(services: Service[], names?: string): Service[];
20
27
  export {};
21
28
  //# sourceMappingURL=serve.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,yBAAyB,CAAC;AAEnD,KAAK,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC;AAKxD;;;;GAIG;AACH,eAAO,MAAM,OAAO,GAAI,CAAC,SAAS,MAAM,cAAc,CAAC,YAAY,MAAM,OAAO,EAAE,KAAG,CACtB,CAAC;AAEhE;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK,gBAAiB,OAAO,EAAE,oBAC2E,CAAC;AAExH,gHAAgH;AAChH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,EAAE,CASrE"}
1
+ {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,OAAO,MAAM,yBAAyB,CAAC;AAEnD,KAAK,OAAO,GAAG,OAAO,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,CAAC;AAKxD;;;;GAIG;AACH,eAAO,MAAM,OAAO,GAAI,CAAC,SAAS,MAAM,cAAc,CAAC,YAAY,MAAM,OAAO,EAAE,KAAG,CACtB,CAAC;AAEhE;;;;;;;GAOG;AACH,eAAO,MAAM,KAAK,gBAAiB,OAAO,EAAE,oBAC2E,CAAC;AAExH;;;;;;;GAOG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,OAAO,EAAE,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,EAAE,CAarE"}
package/dist/serve.js CHANGED
@@ -1,49 +1,57 @@
1
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`).
2
+ // them (a library's objects, such as each @restatedev/agents agent's companion).
3
3
  import * as restate from '@restatedev/restate-sdk';
4
4
  /** Where a definition keeps the services it needs served beside it: see {@link needing}. */
5
5
  const NEEDS = Symbol.for('restate-sessions.needs');
6
6
  /**
7
7
  * `definition`, which needs `services` served beside it: {@link serve}
8
- * serves them too. For a library whose objects call one of its own (an
9
- * agent's `signals`, say).
8
+ * serves them too. For a library whose objects call one of their own (an
9
+ * agent's companion, say).
10
10
  */
11
11
  export const needing = (definition, services) => Object.defineProperty(definition, NEEDS, { value: services });
12
12
  /**
13
13
  * Serve `services` on PORT (default 9080), with the services they need
14
14
  * beside them, each once. RESTATE_SERVE_ONLY, names separated by commas
15
- * (`triage,planner,signals`), serves only those of them: one program (or
16
- * image), deployed in parts.
15
+ * (`triage,planner`), serves only those of them, each with what it needs
16
+ * beside it: one program (or image), deployed in parts.
17
17
  *
18
18
  * await restate.serve(notes, orders);
19
19
  */
20
20
  export const serve = (...services) => restate.serve({ services: served(services, process.env.RESTATE_SERVE_ONLY), port: Number(process.env.PORT ?? 9080) });
21
- /** What {@link serve} serves of `services`: each with what it needs beside it, once, of those `names` names. */
21
+ /**
22
+ * What {@link serve} serves of `services`: each with what it needs beside
23
+ * it, once; with `names` (separated by commas), only the services it names,
24
+ * each with what it needs beside it. For an endpoint of your own:
25
+ *
26
+ * const endpoint = restate.endpoint();
27
+ * for (const service of restate.served([notes, orders])) endpoint.bind(service);
28
+ */
22
29
  export function served(services, names) {
23
- const all = new Map();
24
- const add = (service) => {
25
- if (all.has(service.name))
26
- return;
27
- all.set(service.name, service);
28
- for (const needed of service[NEEDS]?.() ?? [])
29
- add(needed);
30
- };
31
- services.forEach(add);
32
- return only([...all.values()], names);
33
- }
34
- /** The `services` that `names` (comma separated) names, or all of them without names; a name of none is an error. */
35
- function only(services, names) {
30
+ const all = withNeeds(services);
36
31
  const wanted = (names ?? '')
37
32
  .split(',')
38
33
  .map((name) => name.trim())
39
34
  .filter(Boolean);
40
35
  if (wanted.length === 0)
41
- return services;
42
- const known = services.map((s) => s.name);
36
+ return all;
37
+ const known = all.map((s) => s.name);
43
38
  const unknown = wanted.filter((name) => !known.includes(name));
44
39
  if (unknown.length > 0) {
45
40
  throw new Error(`RESTATE_SERVE_ONLY names ${unknown.join(', ')}: the services are ${known.join(', ')}`);
46
41
  }
47
- return services.filter((s) => wanted.includes(s.name));
42
+ return withNeeds(all.filter((s) => wanted.includes(s.name)));
43
+ }
44
+ /** `services`, each with what it needs beside it, once. */
45
+ function withNeeds(services) {
46
+ const all = new Map();
47
+ const add = (service) => {
48
+ if (all.has(service.name))
49
+ return;
50
+ all.set(service.name, service);
51
+ for (const needed of service[NEEDS]?.() ?? [])
52
+ add(needed);
53
+ };
54
+ services.forEach(add);
55
+ return [...all.values()];
48
56
  }
49
57
  //# sourceMappingURL=serve.js.map
package/dist/serve.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"serve.js","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,qEAAqE;AACrE,OAAO,KAAK,OAAO,MAAM,yBAAyB,CAAC;AAInD,4FAA4F;AAC5F,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AAEnD;;;;GAIG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAmB,UAAa,EAAE,QAAyB,EAAK,EAAE,CACvF,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC;AAEhE;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,GAAG,QAAmB,EAAE,EAAE,CAC9C,OAAO,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;AAExH,gHAAgH;AAChH,MAAM,UAAU,MAAM,CAAC,QAAmB,EAAE,KA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}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restatedev/sessions",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Session objects on Restate: virtual objects with a SQL database per key, kept in the object's state (ctx.db)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,9 +29,9 @@
29
29
  "@restatedev/restate-sdk-core": "1.18.2"
30
30
  },
31
31
  "optionalDependencies": {
32
- "@restatedev/sessions-darwin-arm64": "0.5.0",
33
- "@restatedev/sessions-linux-arm64-gnu": "0.5.0",
34
- "@restatedev/sessions-linux-x64-gnu": "0.5.0"
32
+ "@restatedev/sessions-darwin-arm64": "0.7.0",
33
+ "@restatedev/sessions-linux-arm64-gnu": "0.7.0",
34
+ "@restatedev/sessions-linux-x64-gnu": "0.7.0"
35
35
  },
36
36
  "engines": {
37
37
  "node": ">=24"
package/src/index.ts CHANGED
@@ -34,5 +34,6 @@ export {
34
34
  type ViewContext,
35
35
  } from './object.ts';
36
36
  export type { CallOptions, Client, Rpc, Send, SendClient, SendOptions, Target } from './calls.ts';
37
- // In place of the SDK's: the services, on PORT, with what they need beside them.
38
- export { serve } from './serve.ts';
37
+ // In place of the SDK's: the services, on PORT, with what they need beside
38
+ // them; and `served`, the services with what they need, for an endpoint of your own.
39
+ export { serve, served } from './serve.ts';
package/src/internal.ts CHANGED
@@ -4,15 +4,16 @@
4
4
  // databases of their own, and the Restate SDK as @restatedev/sessions runs it (its
5
5
  // own copy, so that a library's journaled handlers serve beside its objects).
6
6
  export * as sdk from '@restatedev/restate-sdk';
7
- export { Schema } from './schema.ts';
7
+ export { ensureSchemas, Schema } from './schema.ts';
8
8
  export { asDatabase, lazyDatabase, database, reset, Attempt, withAttempt } from './session.ts';
9
9
  export type { ObjectConfig, SqlHost } from './session.ts';
10
10
  export { Link } from './link.ts';
11
11
  export { ScopeKey } from './scope.ts';
12
12
  export { open, type Connection, type Store, type ConnectionTransaction } from './database.ts';
13
- export { PromiseSelector } from './selector.ts';
13
+ export { failpoints, PromiseSelector, type Failpoint } from './selector.ts';
14
14
  export { needing, served } from './serve.ts';
15
15
  export {
16
+ attach,
16
17
  cancelCalls,
17
18
  cancelled,
18
19
  configOf,
@@ -20,6 +21,7 @@ export {
20
21
  definitionOf,
21
22
  HEAD_KEY,
22
23
  invoke,
24
+ start,
23
25
  withStoreWrapper,
24
26
  type AttemptContext,
25
27
  } from './object.ts';
package/src/object.ts CHANGED
@@ -16,8 +16,8 @@
16
16
  // },
17
17
  // });
18
18
  import * as restate from '@restatedev/restate-sdk';
19
- import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
20
- import { type Rpc, rpcOf, type Send, sendOf } from './calls.ts';
19
+ import type { Serde, VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
20
+ import { type CallOptions, type Rpc, rpcOf, type Send, sendOf, type Target } from './calls.ts';
21
21
  import type { DatabaseReader, Store } from './database.ts';
22
22
  import { ensureOf, ensuring, Schema, type Step } from './schema.ts';
23
23
  import { Link } from './link.ts';
@@ -371,10 +371,58 @@ export function sessionObject<
371
371
  return made;
372
372
  }
373
373
 
374
- /** The SDK's context behind `ctx`, a handler's with `explicitCancellation: true`. */
375
- function explicitOf(ctx: SessionContext, of: string) {
374
+ /** The scope of `ctx`, a session object's handler's context. */
375
+ function scopeOfHandler(ctx: SessionContext, of: string) {
376
376
  const scope = scopeOf(ctx);
377
377
  if (scope === undefined) throw new restate.TerminalError(`${of} takes a session object's ctx`);
378
+ return scope;
379
+ }
380
+
381
+ /**
382
+ * Call `target`, and resolve to the id of the call's invocation (`inv_1f…`),
383
+ * not waiting for its result: for a library that waits for it by
384
+ * {@link attach}. It is a call, not a send: a handler with
385
+ * `explicitCancellation` whose `cancelCalls` cancels the calls of its
386
+ * attempt cancels this one too, as a send's would not be.
387
+ *
388
+ * Its result is left as it comes. A call of a workflow's `run` whose run of
389
+ * that id started already fails ("the workflow method was already
390
+ * invoked"), whatever its idempotency key, but its invocation id is that
391
+ * run's: so a new attempt that calls again gets the id of the run an
392
+ * earlier one started, and its `cancelCalls` cancels that run.
393
+ */
394
+ export async function start(ctx: SessionContext, target: Target & CallOptions): Promise<string> {
395
+ const { service, key, handler, input, inputSerde, idempotencyKey, headers } = target;
396
+ const called = scopeOfHandler(ctx, 'start').sdk.genericCall({
397
+ service,
398
+ method: handler,
399
+ key,
400
+ parameter: input,
401
+ inputSerde: inputSerde ?? restate.serde.json,
402
+ outputSerde: restate.serde.binary,
403
+ idempotencyKey,
404
+ headers,
405
+ });
406
+ return String(await called.invocationId);
407
+ }
408
+
409
+ /**
410
+ * The result of invocation `invocationId` (such as {@link start}'s), once it
411
+ * ends: its output, or its terminal error. Waiting for it cancels nothing
412
+ * when the attempt ends: the invocation is its own.
413
+ */
414
+ export function attach<O = unknown>(
415
+ ctx: SessionContext,
416
+ invocationId: string,
417
+ outputSerde: Serde<O> = restate.serde.json as Serde<O>,
418
+ ): Promise<O> {
419
+ const { sdk } = scopeOfHandler(ctx, 'attach');
420
+ return sdk.invocation(restate.InvocationIdParser.fromString(invocationId)).attach(outputSerde);
421
+ }
422
+
423
+ /** The SDK's context behind `ctx`, a handler's with `explicitCancellation: true`. */
424
+ function explicitOf(ctx: SessionContext, of: string) {
425
+ const scope = scopeOfHandler(ctx, of);
378
426
  if (!scope.explicitCancellation) {
379
427
  throw new restate.TerminalError(`${of} takes the ctx of a handler with explicitCancellation: true`);
380
428
  }
@@ -385,6 +433,20 @@ function explicitOf(ctx: SessionContext, of: string) {
385
433
  * Resolves when Restate cancels the invocation of `ctx`, a handler's with
386
434
  * `explicitCancellation: true`, whose awaits are left as they are: for a
387
435
  * library that stops its own work then (a model's request, say).
436
+ *
437
+ * It watches for the cancellation, and holds nothing: awaited alone, it does
438
+ * not suspend the invocation, and Restate is not told that the handler waits
439
+ * (see selector.ts: the attempt's journal has a run named `work` instead,
440
+ * for the handler's own work). The cancel signal comes while Restate keeps
441
+ * the invocation's input open. Once Restate closed it (the handler sent and
442
+ * got nothing for the inactivity timeout), a cancellation resolves this at
443
+ * the handler's next await of Restate's, which suspends the invocation and
444
+ * resumes it at once, or not at all if it awaits nothing more.
445
+ *
446
+ * So it is not a way to park a handler until it is cancelled. One that
447
+ * awaits this and nothing else is not suspended: its attempt stays open past
448
+ * the inactivity timeout, Restate aborts it at the abort timeout and retries
449
+ * it from the start, and so on until the cancellation comes.
388
450
  */
389
451
  export const cancelled = async (ctx: SessionContext): Promise<void> => {
390
452
  await explicitOf(ctx, 'cancelled').cancellation();
package/src/schema.ts CHANGED
@@ -19,7 +19,8 @@
19
19
  // which stores nothing, then reads: a key never written reads as
20
20
  // empty tables. This repository's libraries (@restatedev/agents) keep their tables
21
21
  // in a schema of their own name, which `schema.ensure(ctx.db)` applies where
22
- // they use them, in any object: internal, from @restatedev/sessions/internal.
22
+ // they use them, in any object (`ensureSchemas(ctx.db, [...])` for several at
23
+ // once, in one commit): internal, from @restatedev/sessions/internal.
23
24
  import type { Connection, DatabaseReader, DatabaseWriter, ConnectionTransaction } from './database.ts';
24
25
  import { Link } from './link.ts';
25
26
 
@@ -57,11 +58,20 @@ export class Schema {
57
58
  * handler's are its own, vanishing with its session.
58
59
  */
59
60
  ensure(db: DatabaseReader | Connection): Promise<void> {
60
- const ensure = ensureOf(db);
61
- return ensure ? ensure([this]) : apply(db as Connection, [this]);
61
+ return ensureSchemas(db, [this]);
62
62
  }
63
63
  }
64
64
 
65
+ /**
66
+ * Apply the steps of `schemas` that `db` lacks, as {@link Schema.ensure}
67
+ * does each, in one transaction: a database that lacks several (a key's
68
+ * first handler, say) gets them in one commit rather than one each.
69
+ */
70
+ export function ensureSchemas(db: DatabaseReader | Connection, schemas: readonly Schema[]): Promise<void> {
71
+ const ensure = ensureOf(db);
72
+ return ensure ? ensure(schemas) : apply(db as Connection, schemas);
73
+ }
74
+
65
75
  /** How a database applies schemas: a handler's (`ctx.db`, its reader), or one of `asDatabase`. */
66
76
  type Ensure = (schemas: readonly Schema[]) => Promise<void>;
67
77