@restatedev/sessions 0.10.3 → 0.11.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/src/handler.ts CHANGED
@@ -78,6 +78,18 @@ export async function serveSession(
78
78
  // addon; this is how it asks for the tick that writes what it sent.
79
79
  vm.setScheduler(() => driver.scheduleTick());
80
80
 
81
+ // The response ends with the attempt, once the tick wrote its last words:
82
+ // not when the handler returns. Restate starts the next attempt only once
83
+ // it has, and a handler that Restate shut down at work of its own (outside
84
+ // `ctx.working`) runs on until that work is done, its actions throwing.
85
+ let closed = false;
86
+ const close = () => {
87
+ if (closed) return;
88
+ closed = true;
89
+ stream.close();
90
+ };
91
+ driver.whenEnded(() => setTimeout(close, 0));
92
+
81
93
  // The input pump: the only reader of the request body. It runs until the
82
94
  // body ends, beside the handler.
83
95
  const ready = Promise.withResolvers<void>();
@@ -100,7 +112,6 @@ export async function serveSession(
100
112
  try {
101
113
  await ready.promise;
102
114
  if (driver.over !== undefined || !driver.isReadyToExecute()) return;
103
- driver.startHeartbeats();
104
115
  // Input this handler cannot read will not read on the next attempt
105
116
  // either: a terminal failure ends the invocation, where a retryable one
106
117
  // would have Restate send the same bytes forever. The SDK's own handler
@@ -125,7 +136,7 @@ export async function serveSession(
125
136
  await pump;
126
137
  // The attempt's last words are buffered: a turn lets the tick write them.
127
138
  await new Promise((resolve) => setTimeout(resolve, 0));
128
- stream.close();
139
+ close();
129
140
  }
130
141
  }
131
142
 
@@ -229,6 +240,8 @@ function contextOf(
229
240
  // database takes before it issues anything (`session.ts`).
230
241
  takeCancellation: () => driver.takeCarriedCancellation(),
231
242
  cancelPreviousCalls: () => driver.cancelPreviousCalls(),
243
+ // What `ctx.working` keeps alive, and the database's own calls too (`session.ts`).
244
+ working: <T>(fn: () => T | Promise<T>) => driver.working(fn),
232
245
  invocationEndPromise: { promise: ending.promise },
233
246
  defaultSerde: restate.serde.json,
234
247
  // The addon reads and writes the object's state on this, rather than
package/src/internal.ts CHANGED
@@ -5,11 +5,11 @@
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
7
  export { ensureSchemas, Schema } from './schema.ts';
8
- export { asDatabase, lazyDatabase, database, reset, Attempt, withAttempt } from './session.ts';
8
+ export { asDatabase, lazyDatabase, database, reset, deferSql, undeferSql, 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
- export { open, type Connection, type Store, type ConnectionTransaction } from './database.ts';
12
+ export { open, type Connection, type Store, type ConnectionTransaction, type Working } from './database.ts';
13
13
  // The attempt on the explicit recovery VM, for the tests that drive one.
14
14
  export { AttemptDriver, AttemptFailed, AttemptShutDown } from './driver.ts';
15
15
  export { Vm, isShutDown } from './vm.ts';
package/src/object.ts CHANGED
@@ -18,7 +18,7 @@
18
18
  import * as restate from '@restatedev/restate-sdk';
19
19
  import type { Serde, VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
20
20
  import { type CallOptions, type Rpc, rpcOf, type Send, sendOf, type Target } from './calls.ts';
21
- import type { DatabaseReader, Store } from './database.ts';
21
+ import type { DatabaseReader, Store, Working } from './database.ts';
22
22
  import { ensureOf, ensuring, Schema, type Step } from './schema.ts';
23
23
  import { patchEndpoint } from './endpoint.ts';
24
24
  import { Link } from './link.ts';
@@ -49,6 +49,23 @@ export interface SessionContext {
49
49
  readonly send: Send;
50
50
  /** Cancel an invocation, by its id: see {@link Cancel}. */
51
51
  readonly cancel: Cancel;
52
+ /**
53
+ * Run `fn`, keeping the attempt alive while it runs: for work outside
54
+ * Restate that may outlast Restate's inactivity timeout (a minute, by
55
+ * default), such as a model's request.
56
+ *
57
+ * const reply = await ctx.working(() => model.generate(prompt));
58
+ *
59
+ * Outside it, an attempt Restate hears nothing from for that long is shut
60
+ * down: it suspends on the calls it waits for, and a new attempt runs the
61
+ * handler from the start when one answers (or at once, if it waits for
62
+ * none). So a wait of days holds no process, and work cut off that way is
63
+ * done again. Inside it, the attempt sends a heartbeat every 20 seconds
64
+ * (`RESTATE_SESSIONS_HEARTBEAT`, in milliseconds), whatever it waits for:
65
+ * keep a long wait on Restate (a call, a signal) out of it. The database's
66
+ * own calls keep the attempt alive by themselves.
67
+ */
68
+ readonly working: Working;
52
69
  }
53
70
 
54
71
  /**
@@ -149,6 +166,7 @@ export function host(
149
166
  run: (name, action) => exclusive.run(name, action),
150
167
  vm: (ctx as { vm?: SqlHost['vm'] }).vm,
151
168
  takeCancellation: (ctx as { takeCancellation?: SqlHost['takeCancellation'] }).takeCancellation,
169
+ working: workingOf(ctx),
152
170
  genericSend: (send) => ctx.genericSend(send),
153
171
  };
154
172
  }
@@ -266,12 +284,17 @@ export function contextOf(
266
284
  rpc,
267
285
  send: sendOf((send) => void ctx.genericSend(send)),
268
286
  cancel,
287
+ // An attempt the SDK serves (a test's) has nothing to keep alive.
288
+ working: workingOf(ctx) ?? ((fn) => (async () => fn())()),
269
289
  },
270
290
  scope,
271
291
  );
272
292
  return Object.freeze(context);
273
293
  }
274
294
 
295
+ /** The `working` of an attempt on the VM's context `ctx` (`handler.ts`); none on the SDK's. */
296
+ const workingOf = (ctx: object): Working | undefined => (ctx as { working?: Working }).working;
297
+
275
298
  /** {@link Cancel} over the SDK's context `ctx`. */
276
299
  const cancelOf =
277
300
  (ctx: Pick<restate.ObjectContext, 'invocation'>): Cancel =>
@@ -498,17 +521,17 @@ function explicitOf(ctx: SessionContext, of: string) {
498
521
  *
499
522
  * It watches for the cancellation, and holds nothing: awaited alone, it does
500
523
  * not suspend the invocation, and Restate is not told that the handler waits
501
- * (a heartbeat tells Restate the attempt makes progress instead, see
502
- * `driver.ts`). The cancel signal comes while Restate keeps
524
+ * (a heartbeat, in `ctx.working`, tells Restate the attempt makes progress
525
+ * instead). The cancel signal comes while Restate keeps
503
526
  * the invocation's input open. Once Restate closed it (the handler sent and
504
527
  * got nothing for the inactivity timeout), a cancellation resolves this at
505
528
  * the handler's next await of Restate's, which suspends the invocation and
506
529
  * resumes it at once, or not at all if it awaits nothing more.
507
530
  *
508
531
  * So it is not a way to park a handler until it is cancelled. One that
509
- * awaits this and nothing else is not suspended: its attempt stays open past
510
- * the inactivity timeout, Restate aborts it at the abort timeout and retries
511
- * it from the start, and so on until the cancellation comes.
532
+ * awaits this and nothing else is not suspended: its attempt is shut down at
533
+ * the inactivity timeout and started again at once, and so on until the
534
+ * cancellation comes.
512
535
  */
513
536
  export const cancelled = async (ctx: SessionContext): Promise<void> => {
514
537
  await explicitOf(ctx, 'cancelled').cancellation();
package/src/session.ts CHANGED
@@ -20,6 +20,7 @@ import {
20
20
  type SqlValue,
21
21
  type Store,
22
22
  type ConnectionTransaction,
23
+ type Working,
23
24
  } from './database.ts';
24
25
  import type { Vm } from './vm.ts';
25
26
  import { Link } from './link.ts';
@@ -53,6 +54,13 @@ export interface Transaction extends DatabaseWriter {
53
54
  * again is dropped.
54
55
  */
55
56
  readonly send: Send;
57
+ /**
58
+ * Settles, and never rejects, once another call to `ctx.db` waits for this
59
+ * transaction to end. A body that keeps the transaction open for more work
60
+ * can return when it settles, so that the other call waits for one commit
61
+ * and no more.
62
+ */
63
+ readonly queued: Promise<void>;
56
64
  }
57
65
 
58
66
  /** What the session needs of the handler's context. */
@@ -84,6 +92,11 @@ export interface SqlHost {
84
92
  * attempt, whose own awaits fail with it.
85
93
  */
86
94
  readonly takeCancellation?: () => boolean;
95
+ /**
96
+ * Keeps the attempt alive while a call of the database runs: the VM's
97
+ * attempt has it (`driver.ts`), the SDK's context does not.
98
+ */
99
+ readonly working?: Working;
87
100
  genericSend(send: restate.GenericSend<Uint8Array>): unknown;
88
101
  }
89
102
 
@@ -237,17 +250,43 @@ function handlerError(error: unknown): unknown {
237
250
  }
238
251
 
239
252
  /** `call`'s result, or the error the handler fails with (see {@link handlerError}). */
240
- async function forHandler<T>(call: Promise<T>): Promise<T> {
241
- try {
242
- return await call;
243
- } catch (error) {
253
+ function forHandler<T>(call: Promise<T>): Promise<T> {
254
+ return call.catch((error: unknown) => {
244
255
  throw handlerError(error);
245
- }
256
+ });
257
+ }
258
+
259
+ /** {@link forHandler} of a call that answers with its value when it is ready: then it is the value, which only this package takes so. */
260
+ function forHandlerNow<T>(call: T | Promise<T>): T | Promise<T> {
261
+ return call instanceof Promise ? forHandler(call) : call;
246
262
  }
247
263
 
248
264
  /** The SQL of a transaction's body: `tx`'s, failing as {@link forHandler} does. */
249
- function forBody(tx: ConnectionTransaction): DatabaseWriter {
250
- return sqlOver((sql, params) => forHandler(tx.queryColumns(sql, params)), handlerError);
265
+ function forBody(tx: ConnectionTransaction): DatabaseWriter & { readonly queued: Promise<void> } {
266
+ return {
267
+ ...sqlOver((sql, params) => forHandlerNow(tx.queryColumnsNow(sql, params)), handlerError),
268
+ queued: tx.queued,
269
+ };
270
+ }
271
+
272
+ /** The connection's transaction behind a `tx` of a body, for the SQL it defers ({@link deferSql}). */
273
+ const DEFERRED = new Link<ConnectionTransaction>('deferred sql');
274
+
275
+ /**
276
+ * Have `sql` (one statement, no parameters) run just before the next call of
277
+ * the transaction `tx`, in the same crossing of the addon: the statement and
278
+ * its order are those of a call made now, and what it spares is the call.
279
+ * Its failure is the next call's (or the commit's, if none comes). Returns
280
+ * false, queuing nothing, if the transaction cannot (a `tx` of another
281
+ * kind, or an addon without it): run the statement with `tx.execute`.
282
+ */
283
+ export function deferSql(tx: Transaction, sql: string): boolean {
284
+ return DEFERRED.of(tx)?.defer(sql) ?? false;
285
+ }
286
+
287
+ /** Take back the last `sql` that {@link deferSql} queued on `tx` and no call has taken: it never runs. Whether it was taken back. */
288
+ export function undeferSql(tx: Transaction, sql: string): boolean {
289
+ return DEFERRED.of(tx)?.undefer(sql) ?? false;
251
290
  }
252
291
 
253
292
  /**
@@ -257,8 +296,8 @@ function forBody(tx: ConnectionTransaction): DatabaseWriter {
257
296
  */
258
297
  export function asDatabase(connection: Connection): Database {
259
298
  const db: Database = {
260
- ...sqlOver((sql, params) => connection.queryColumns(sql, params)),
261
- transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
299
+ ...sqlOver((sql, params) => connection.queryColumnsNow(sql, params)),
300
+ transaction: (body) => connection.transaction((tx) => body(DEFERRED.on({ ...forBody(tx), send: refusedSend }, tx))),
262
301
  };
263
302
  return ensuring(db, (schemas) => apply(connection, schemas));
264
303
  }
@@ -406,6 +445,10 @@ class Session {
406
445
  /** A call failed on it once a failure ended it: the next call opens another. */
407
446
  retired = false;
408
447
  private connection: Connection | undefined;
448
+ /** Its connection, once its open settled. */
449
+ get opened(): Connection | undefined {
450
+ return this.connection;
451
+ }
409
452
  private failed = false;
410
453
  private release: () => void = () => {};
411
454
 
@@ -467,6 +510,8 @@ export class Attempt {
467
510
  private readonly databases = new Map<string, Attempt>();
468
511
  /** The session, from its first use on. */
469
512
  private session: Session | undefined;
513
+ /** The calls made on the session that have not reached its connection yet: see {@link call}. */
514
+ private unhanded = 0;
470
515
  /** The ids of the outbox's transactions this attempt made the sends of. */
471
516
  private readonly made = new Set<string>();
472
517
  /** The schemas this attempt's database has all the steps of. */
@@ -479,7 +524,10 @@ export class Attempt {
479
524
  this.name = name;
480
525
  this.hasOutbox = !ctx.shared && name === undefined;
481
526
  this.db = {
482
- ...sqlOver((sql, params) => this.asked(() => this.call((db) => db.queryColumns(sql, params))), handlerError),
527
+ ...sqlOver(
528
+ (sql, params) => this.askedNow(() => this.callNow((db) => db.queryColumnsNow(sql, params))),
529
+ handlerError,
530
+ ),
483
531
  transaction: (body) => this.asked(() => this.transaction(body)),
484
532
  };
485
533
  ensuring(this.db, (schemas) => this.asked(() => this.call((db) => this.ensureSchemas(db, schemas))));
@@ -514,6 +562,12 @@ export class Attempt {
514
562
  return call();
515
563
  }
516
564
 
565
+ /** {@link asked} for a call that answers with its value when it is ready ({@link callNow}). */
566
+ private askedNow<T>(call: () => T | Promise<T>): T | Promise<T> {
567
+ if (this.ctx.takeCancellation?.()) return Promise.reject(new CancelledError());
568
+ return call();
569
+ }
570
+
517
571
  /**
518
572
  * Open the session now, as the attempt starts, rather than on its first
519
573
  * call: the open makes the sends a crashed attempt committed and left
@@ -554,6 +608,7 @@ export class Attempt {
554
608
  const sends = this.hasOutbox ? new Sends() : undefined;
555
609
  const tx: Transaction = { ...forBody(handle), send: sends?.send ?? refusedSend };
556
610
  // A view's writes stay in its session: it has nothing to reset.
611
+ DEFERRED.on(tx, handle);
557
612
  if (!this.ctx.shared) RESET.on(tx, () => this.reset(handle));
558
613
  let result: T;
559
614
  try {
@@ -592,14 +647,55 @@ export class Attempt {
592
647
  */
593
648
  private async call<T>(call: (db: Connection) => Promise<T>): Promise<T> {
594
649
  const session = this.current();
650
+ // Counted until it reaches the connection, which orders it from there on.
651
+ this.unhanded++;
652
+ let counted = true;
653
+ const handed = () => {
654
+ if (counted) this.unhanded--;
655
+ counted = false;
656
+ };
595
657
  try {
596
- return await call(await session.ready);
658
+ const db = await session.ready;
659
+ handed();
660
+ return await call(db);
597
661
  } catch (error) {
662
+ handed();
598
663
  if (session.ended) session.retired = true;
599
664
  throw handlerError(error);
600
665
  }
601
666
  }
602
667
 
668
+ /**
669
+ * {@link call} for a call that answers with its value when it is ready: it
670
+ * is the value, without a promise, which only this package takes so. That
671
+ * is for a session that is open, and with no call before it still to reach
672
+ * the connection (a call made before it, which waits for the session, must
673
+ * run first): anything else is {@link call}.
674
+ */
675
+ private callNow<T>(call: (db: Connection) => T | Promise<T>): T | Promise<T> {
676
+ const session = this.session;
677
+ const db = session?.opened;
678
+ if (this.unhanded > 0 || session === undefined || db === undefined || session.retired || this.ended) {
679
+ return this.call(async (connection) => call(connection));
680
+ }
681
+ // As `call` fails: a session that a failure ended is retired by the call that fails on it.
682
+ const failure = (error: unknown): unknown => {
683
+ if (session.ended) session.retired = true;
684
+ return handlerError(error);
685
+ };
686
+ let result: T | Promise<T>;
687
+ try {
688
+ result = call(db);
689
+ } catch (error) {
690
+ return Promise.reject(failure(error));
691
+ }
692
+ return result instanceof Promise
693
+ ? result.catch((error: unknown) => {
694
+ throw failure(error);
695
+ })
696
+ : result;
697
+ }
698
+
603
699
  /** The session, opening one if there is none, or the one there is was retired. */
604
700
  private current(): Session {
605
701
  if (this.ended) throw new Error('the handler has ended: its SQL session is closed');
@@ -634,7 +730,7 @@ export class Attempt {
634
730
  const onVm = ctx.vm !== undefined;
635
731
  const object = onVm ? commitOnly() : objectStore(ctx, end, this.name);
636
732
  const db = onVm
637
- ? await openOnVm(namespace, object, ctx.vm, { name: this.name, reader: ctx.shared })
733
+ ? await openOnVm(namespace, object, ctx.vm, { name: this.name, reader: ctx.shared, working: ctx.working })
638
734
  : await open(namespace, wrap ? wrap(object) : object, { reader: ctx.shared });
639
735
  try {
640
736
  // A view writes nothing: a write fails, rather than vanish with the attempt.