@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/database.ts CHANGED
@@ -57,26 +57,88 @@ export interface DatabaseWriter extends DatabaseReader {
57
57
  execute(sql: string, params?: SqlParam[]): Promise<void>;
58
58
  }
59
59
 
60
+ /**
61
+ * What the addon refuses as a parameter before it runs a call (its conversion
62
+ * of an SQL value): a failure here is the call's own, and nothing ran.
63
+ */
64
+ function checkParams(params: SqlParam[] | undefined): void {
65
+ for (const param of params ?? []) {
66
+ const type = typeof param;
67
+ if (type === 'bigint' && ((param as bigint) > 2n ** 63n - 1n || (param as bigint) < -(2n ** 63n))) {
68
+ throw new Error('a bigint parameter exceeds 64 bits');
69
+ }
70
+ if (type === 'symbol' || type === 'function') {
71
+ throw new Error(`unsupported SQL value: ${type === 'symbol' ? 'Symbol' : 'Function'}`);
72
+ }
73
+ if (type === 'object' && param !== null && !(param instanceof Uint8Array)) {
74
+ throw new Error('unsupported SQL value: Object');
75
+ }
76
+ }
77
+ }
78
+
79
+ /** Nothing: what settles a queue's last call, and what `execute` resolves with. */
80
+ const nothing = (): void => {};
81
+
60
82
  /** The rows of `result` as objects by column name; a column name twice is an {@link SqlError}. */
61
83
  function objects({ columns, rows }: SqlQueryResult): Row[] {
62
- if (new Set(columns).size !== columns.length) {
63
- const twice = columns.find((name, i) => columns.indexOf(name) !== i);
84
+ const names = columns.length;
85
+ let twice: string | undefined;
86
+ for (let i = 1; i < names && twice === undefined; i++) {
87
+ // A statement has a handful of columns: comparing them pairwise costs less than a Set.
88
+ for (let j = 0; j < i; j++) {
89
+ if (columns[j] === columns[i]) {
90
+ twice = columns[i];
91
+ break;
92
+ }
93
+ }
94
+ }
95
+ if (twice !== undefined) {
64
96
  throw new SqlError(`the column ${twice} is named twice: alias one (AS), or read the rows with values()`);
65
97
  }
66
- return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]!])));
98
+ // A column named `__proto__` is an own property of the row, as `Object.fromEntries` makes it;
99
+ // assignment would set the row's prototype instead.
100
+ if (columns.includes('__proto__')) {
101
+ return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]!])));
102
+ }
103
+ const result: Row[] = [];
104
+ for (const row of rows) {
105
+ const object: Row = {};
106
+ for (let i = 0; i < names; i++) object[columns[i]!] = row[i]!;
107
+ result.push(object);
108
+ }
109
+ return result;
67
110
  }
68
111
 
112
+ // `result` mapped, as a promise: a result that is ready is mapped now, and a failure of the mapping is a rejection.
113
+ const mapped = <T>(result: Answer<SqlQueryResult>, map: (result: SqlQueryResult) => T): Promise<T> => {
114
+ if (result instanceof Promise) return result.then(map);
115
+ try {
116
+ return Promise.resolve(map(result));
117
+ } catch (error) {
118
+ return Promise.reject(error);
119
+ }
120
+ };
121
+
69
122
  /**
70
123
  * {@link DatabaseWriter} over `run`, which runs one call's SQL and returns
71
124
  * its rows with their columns, failing as `failure` makes its errors (as
72
- * `run` makes the engine's).
125
+ * `run` makes the engine's). `run` answers with the value itself when the
126
+ * call was ready at once, which only this package sees: each call returns a
127
+ * promise.
73
128
  */
74
129
  export function sqlOver(
75
- run: (sql: string, params?: SqlParam[]) => Promise<SqlQueryResult>,
130
+ run: (sql: string, params?: SqlParam[]) => Answer<SqlQueryResult>,
76
131
  failure: (error: unknown) => unknown = (error) => error,
77
132
  ): DatabaseWriter {
78
- const rowsOf = async (sql: string, params?: SqlParam[]) => {
79
- const result = await run(sql, params);
133
+ // A `run` that throws is a rejection, as it was when each of these was an async function.
134
+ const start = (sql: string, params?: SqlParam[]): Answer<SqlQueryResult> => {
135
+ try {
136
+ return run(sql, params);
137
+ } catch (error) {
138
+ return Promise.reject(error);
139
+ }
140
+ };
141
+ const rowsOf = (result: SqlQueryResult): Row[] => {
80
142
  try {
81
143
  return objects(result);
82
144
  } catch (error) {
@@ -84,10 +146,11 @@ export function sqlOver(
84
146
  }
85
147
  };
86
148
  return {
87
- query: async <T>(sql: string, params?: SqlParam[]) => (await rowsOf(sql, params)) as T[],
88
- get: async <T>(sql: string, params?: SqlParam[]) => (await rowsOf(sql, params))[0] as T | undefined,
89
- values: async (sql, params) => (await run(sql, params)).rows,
90
- execute: async (sql, params) => void (await run(sql, params)),
149
+ query: <T>(sql: string, params?: SqlParam[]) => mapped(start(sql, params), rowsOf) as Promise<T[]>,
150
+ get: <T>(sql: string, params?: SqlParam[]) =>
151
+ mapped(start(sql, params), (result) => rowsOf(result)[0] as T | undefined),
152
+ values: (sql, params) => mapped(start(sql, params), (result) => result.rows),
153
+ execute: (sql, params) => mapped(start(sql, params), nothing),
91
154
  };
92
155
  }
93
156
 
@@ -124,8 +187,11 @@ interface Addon {
124
187
  */
125
188
  interface NativeSession {
126
189
  queryColumns(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
190
+ /** `queryColumns`, after `before`'s statements in the same call; absent in an addon without it. */
191
+ queryColumnsAfter?(before: string[], sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
127
192
  begin(): Answer<void>;
128
- commit(records: Record<string, Buffer>): Answer<void>;
193
+ /** `withCommit`: whether the transaction has work to run at the commit's sync (see `Boundary.sync`). */
194
+ commit(records: Record<string, Buffer>, withCommit?: boolean): Answer<void>;
129
195
  rollback(): Answer<void>;
130
196
  record(name: string): Answer<Buffer>;
131
197
  isUsable(): boolean;
@@ -136,6 +202,13 @@ interface NativeSession {
136
202
  /** A value, or a promise of it: `await` takes either. */
137
203
  type Answer<T> = T | Promise<T>;
138
204
 
205
+ /**
206
+ * Run `fn`, keeping the attempt alive meanwhile: the attempt's `working`
207
+ * (see `driver.ts`). The database's calls run in it, being local work that
208
+ * never waits on Restate for long.
209
+ */
210
+ export type Working = <T>(fn: () => T | Promise<T>) => Promise<T>;
211
+
139
212
  const addon = loaded as unknown as Addon;
140
213
 
141
214
  /**
@@ -164,11 +237,11 @@ export async function openOnVm(
164
237
  namespace: string,
165
238
  store: Store,
166
239
  vm: Vm,
167
- { name, reader = false }: { name?: string; reader?: boolean } = {},
240
+ { name, reader = false, working }: { name?: string; reader?: boolean; working?: Working } = {},
168
241
  ): Promise<Connection> {
169
- const boundary = new Boundary(store);
242
+ const boundary = new Boundary(store, working);
170
243
  try {
171
- return new Connection(await addon.openOnVm(namespace, boundary, vm, name, reader), boundary);
244
+ return new Connection(await boundary.alive(() => addon.openOnVm(namespace, boundary, vm, name, reader)), boundary);
172
245
  } catch (error) {
173
246
  // The open reads the database's head. On this path that read waits in the
174
247
  // addon, so its failure arrives as text and `boundary.failed` is never
@@ -192,9 +265,11 @@ class Boundary implements Store {
192
265
  withSync: (() => void) | undefined;
193
266
  readonly keys?: () => Promise<string[]>;
194
267
  private readonly store: Store;
268
+ private readonly working: Working | undefined;
195
269
 
196
- constructor(store: Store) {
270
+ constructor(store: Store, working?: Working) {
197
271
  this.store = store;
272
+ this.working = working;
198
273
  // A store without keys keeps its garbage (see `Store.keys`).
199
274
  const keys = store.keys?.bind(store);
200
275
  if (keys) this.keys = () => this.kept(keys);
@@ -221,6 +296,22 @@ class Boundary implements Store {
221
296
  });
222
297
  }
223
298
 
299
+ /**
300
+ * `call`'s value if it is ready (the addon answers at once): then no scope
301
+ * is opened, as nothing waited; a promise runs on in the attempt's `working`
302
+ * scope, which opens as the call returns it.
303
+ */
304
+ aliveNow<T>(call: () => Answer<T>): Answer<T> {
305
+ const result = call();
306
+ if (!(result instanceof Promise)) return result;
307
+ return this.working === undefined ? result : this.working(() => result);
308
+ }
309
+
310
+ /** `call`, in the attempt's `working` scope if the database has one. */
311
+ alive<T>(call: () => T | Promise<T>): Promise<T> {
312
+ return this.working === undefined ? (async () => call())() : this.working(call);
313
+ }
314
+
224
315
  /** `request`'s result, keeping its error, thrown at once or rejected. */
225
316
  private kept<T>(request: () => T): T {
226
317
  const keep = (error: unknown): never => {
@@ -238,33 +329,59 @@ class Boundary implements Store {
238
329
 
239
330
  /**
240
331
  * SQL on a session of the addon: {@link DatabaseWriter}'s `query` and `execute`
241
- * by way of its `queryColumns`.
332
+ * by way of its `queryColumnsNow`.
242
333
  */
243
334
  abstract class Sql implements DatabaseWriter {
244
335
  protected readonly native: NativeSession;
245
336
  protected readonly boundary: Boundary;
337
+ private readonly over: DatabaseWriter;
246
338
 
247
339
  constructor(native: NativeSession, boundary: Boundary) {
248
340
  this.native = native;
249
341
  this.boundary = boundary;
342
+ this.over = sqlOver((s, p) => this.queryColumnsNow(s, p));
250
343
  }
251
344
 
252
- abstract queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult>;
345
+ /**
346
+ * The rows of one statement with their column names: the value itself if
347
+ * the addon answered at once (only the package's own code takes it so), else
348
+ * a promise of it. A failure is a rejection.
349
+ */
350
+ abstract queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
351
+
352
+ queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult> {
353
+ const result = this.queryColumnsNow(sql, params);
354
+ return result instanceof Promise ? result : Promise.resolve(result);
355
+ }
253
356
 
254
357
  query<T = Row>(sql: string, params?: SqlParam[]): Promise<T[]> {
255
- return sqlOver((s, p) => this.queryColumns(s, p)).query<T>(sql, params);
358
+ return this.over.query<T>(sql, params);
256
359
  }
257
360
 
258
361
  get<T = Row>(sql: string, params?: SqlParam[]): Promise<T | undefined> {
259
- return sqlOver((s, p) => this.queryColumns(s, p)).get<T>(sql, params);
362
+ return this.over.get<T>(sql, params);
260
363
  }
261
364
 
262
365
  values(sql: string, params?: SqlParam[]): Promise<SqlValue[][]> {
263
- return sqlOver((s, p) => this.queryColumns(s, p)).values(sql, params);
366
+ return this.over.values(sql, params);
264
367
  }
265
368
 
266
- async execute(sql: string, params?: SqlParam[]): Promise<void> {
267
- await this.queryColumns(sql, params);
369
+ execute(sql: string, params?: SqlParam[]): Promise<void> {
370
+ return this.over.execute(sql, params);
371
+ }
372
+
373
+ /** {@link request}, but the value itself if it is ready, and then without a scope or a promise. */
374
+ protected requestNow<T>(call: () => Answer<T>): Answer<T> {
375
+ let result: Answer<T>;
376
+ try {
377
+ result = this.boundary.aliveNow(call);
378
+ } catch (error) {
379
+ return Promise.reject(this.failure(error));
380
+ }
381
+ if (!(result instanceof Promise)) return result;
382
+ return result.catch((error: unknown) => {
383
+ throw this.failure(error);
384
+ });
268
385
  }
269
386
 
270
387
  /**
@@ -272,12 +389,16 @@ abstract class Sql implements DatabaseWriter {
272
389
  * addon throws as it is called (arguments it cannot convert, and the error
273
390
  * of a call that answers at once).
274
391
  */
275
- protected async request<T>(call: () => Answer<T>): Promise<T> {
392
+ protected request<T>(call: () => Answer<T>): Promise<T> {
393
+ let alive: Promise<T>;
276
394
  try {
277
- return await call();
395
+ alive = this.boundary.alive(call);
278
396
  } catch (error) {
279
- throw this.failure(error);
397
+ return Promise.reject(this.failure(error));
280
398
  }
399
+ return alive.catch((error: unknown) => {
400
+ throw this.failure(error);
401
+ });
281
402
  }
282
403
 
283
404
  /**
@@ -326,8 +447,23 @@ export class Connection extends Sql {
326
447
  private readonly running = new AsyncLocalStorage<OpenTransaction>();
327
448
  /** Settles once the last call queued so far has: the next call runs after it. */
328
449
  private queue: Promise<unknown> = Promise.resolve();
450
+ /** The last transaction queued, until it has committed or rolled back: a call queued behind it fires it. */
451
+ private tail: Gate | undefined;
452
+ /** Calls queued and not settled: with none, a call that is ready runs at once, in order. */
453
+ private inflight = 0;
454
+ private readonly release = (): void => {
455
+ this.inflight--;
456
+ };
329
457
 
330
- queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult> {
458
+ queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult> {
459
+ if (this.inflight === 0 && this.running.getStore()?.open !== true) {
460
+ const result = this.requestNow(() => this.native.queryColumns(sql, params));
461
+ if (!(result instanceof Promise)) return result;
462
+ // Not ready: the calls after it queue behind it.
463
+ this.inflight++;
464
+ this.queue = result.then(this.release, this.release);
465
+ return result;
466
+ }
331
467
  return this.serial(() => this.request(() => this.native.queryColumns(sql, params)));
332
468
  }
333
469
 
@@ -339,36 +475,49 @@ export class Connection extends Sql {
339
475
  * COMMIT rolls back.
340
476
  */
341
477
  transaction<T>(body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
478
+ const gate = new Gate();
342
479
  return this.serial(async () => {
343
- await this.request(() => this.native.begin());
344
- const tx = new OpenTransaction(this.native, this.boundary);
345
- let result: T;
346
480
  try {
347
- result = await this.running.run(tx, () => body(tx));
348
- } catch (error) {
349
- await tx.end();
350
- await this.rollback();
351
- throw error;
352
- }
353
- const records = await tx.end();
354
- // Its commit's sync runs what the body gave `withCommit`; one that
355
- // wrote nothing synced nothing, and it runs after.
356
- this.boundary.withSync = tx.commitRuns();
357
- let unsynced: (() => void) | undefined;
358
- try {
359
- await this.native.commit(records);
360
- } catch (error) {
361
- // A COMMIT that fails (a deferred constraint) leaves the transaction
362
- // open: without the rollback, the calls after it would run inside it.
363
- await this.rollback();
364
- throw this.failure(error);
481
+ return await this.run(gate, body);
365
482
  } finally {
366
- unsynced = this.boundary.withSync;
367
- this.boundary.withSync = undefined;
483
+ if (this.tail === gate) this.tail = undefined;
368
484
  }
369
- unsynced?.();
370
- return result;
371
- });
485
+ }, gate);
486
+ }
487
+
488
+ private async run<T>(gate: Gate, body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
489
+ await this.request(() => this.native.begin());
490
+ const tx = new OpenTransaction(this.native, this.boundary, gate.promise);
491
+ let result: T;
492
+ try {
493
+ result = await this.running.run(tx, () => body(tx));
494
+ await tx.drain();
495
+ } catch (error) {
496
+ await tx.end();
497
+ await this.rollback();
498
+ throw error;
499
+ }
500
+ const records = await tx.end();
501
+ // Its commit's sync runs what the body gave `withCommit`; one that
502
+ // wrote nothing synced nothing, and it runs after.
503
+ const runs = tx.commitRuns();
504
+ this.boundary.withSync = runs;
505
+ let unsynced: (() => void) | undefined;
506
+ try {
507
+ // Told whether there is work, the addon on the VM skips the call back
508
+ // that would only run it.
509
+ await this.boundary.alive(() => this.native.commit(records, runs !== undefined));
510
+ } catch (error) {
511
+ // A COMMIT that fails (a deferred constraint) leaves the transaction
512
+ // open: without the rollback, the calls after it would run inside it.
513
+ await this.rollback();
514
+ throw this.failure(error);
515
+ } finally {
516
+ unsynced = this.boundary.withSync;
517
+ this.boundary.withSync = undefined;
518
+ }
519
+ unsynced?.();
520
+ return result;
372
521
  }
373
522
 
374
523
  /**
@@ -399,12 +548,17 @@ export class Connection extends Sql {
399
548
  }
400
549
 
401
550
  /** Run `call` once the calls before it have, unless it comes from the body of a transaction it would wait for. */
402
- private serial<T>(call: () => Promise<T>): Promise<T> {
551
+ private serial<T>(call: () => Promise<T>, transaction?: Gate): Promise<T> {
403
552
  if (this.running.getStore()?.open) {
404
553
  return Promise.reject(new SqlError('inside a transaction, use the transaction handle its body gets'));
405
554
  }
555
+ // A call queued behind the last transaction tells it so; a transaction
556
+ // that is itself the last one queued from now on is told by the next.
557
+ this.tail?.fire();
558
+ if (transaction !== undefined) this.tail = transaction;
559
+ this.inflight++;
406
560
  const result = this.queue.then(call);
407
- this.queue = result.catch(() => {});
561
+ this.queue = result.then(this.release, this.release);
408
562
  return result;
409
563
  }
410
564
 
@@ -420,6 +574,8 @@ export class Connection extends Sql {
420
574
  export interface ConnectionTransaction extends DatabaseWriter {
421
575
  /** The rows of one statement, with their column names. */
422
576
  queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult>;
577
+ /** {@link queryColumns} for the package's own code: the value itself if the addon answered at once. */
578
+ queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
423
579
  /**
424
580
  * Set the record `name` to `value` with this transaction, in the same
425
581
  * write: a whole value kept beside the SQL, in no table, stored exactly
@@ -438,6 +594,43 @@ export interface ConnectionTransaction extends DatabaseWriter {
438
594
  * transaction rolls back.
439
595
  */
440
596
  withCommit(run: () => void): void;
597
+ /**
598
+ * Have `sql` (one statement, no parameters) run just before the next call
599
+ * of this transaction, in the same call to the addon: the statements are
600
+ * the ones a call of their own would run, in the order the calls are made,
601
+ * and the call fails with the error of the first that fails. It spares
602
+ * the crossing of a call. Returns false, and queues nothing, where the
603
+ * addon cannot (an addon without `queryColumnsAfter`): run the statement
604
+ * with {@link queryColumns}. One still queued as the body settles runs
605
+ * then, before the commit, and its failure fails the transaction.
606
+ */
607
+ defer(sql: string): boolean;
608
+ /**
609
+ * Take back the last `sql` that {@link defer} queued if no call has taken
610
+ * it yet: it never runs. Whether it did.
611
+ */
612
+ undefer(sql: string): boolean;
613
+ /**
614
+ * Settles, and never rejects, once another call to the connection has
615
+ * queued behind this transaction: it is waiting for the body to settle.
616
+ * A body that holds the transaction open for more work can return on it,
617
+ * so that the call costs one commit rather than a stall. A call made
618
+ * before the transaction began does not settle it, and neither does one
619
+ * made from the body, which is refused.
620
+ */
621
+ readonly queued: Promise<void>;
622
+ }
623
+
624
+ /** A promise that settles once {@link fire}d. */
625
+ class Gate {
626
+ readonly promise: Promise<void>;
627
+ private resolve!: () => void;
628
+ constructor() {
629
+ this.promise = new Promise<void>((resolve) => (this.resolve = resolve));
630
+ }
631
+ fire(): void {
632
+ this.resolve();
633
+ }
441
634
  }
442
635
 
443
636
  /**
@@ -453,7 +646,19 @@ class OpenTransaction extends Sql implements ConnectionTransaction {
453
646
  private readonly withCommits: (() => void)[] = [];
454
647
  /** Settles once the last call queued so far has: the next call runs after it. */
455
648
  private queue: Promise<unknown> = Promise.resolve();
649
+ private inflight = 0;
650
+ private readonly release = (): void => {
651
+ this.inflight--;
652
+ };
653
+ /** SQL that runs with the next call made (`defer`). */
654
+ private deferred: string[] = [];
456
655
  private ended = false;
656
+ readonly queued: Promise<void>;
657
+
658
+ constructor(native: NativeSession, boundary: Boundary, queued: Promise<void>) {
659
+ super(native, boundary);
660
+ this.queued = queued;
661
+ }
457
662
 
458
663
  /** Whether it is open: its body runs, and holds its session. */
459
664
  get open(): boolean {
@@ -470,8 +675,55 @@ class OpenTransaction extends Sql implements ConnectionTransaction {
470
675
  return Object.fromEntries(this.records);
471
676
  }
472
677
 
473
- queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult> {
474
- return this.serial(() => this.request(() => this.native.queryColumns(sql, params)));
678
+ queryColumnsNow(sql: string, params?: SqlParam[]): Answer<SqlQueryResult> {
679
+ if (this.ended) return Promise.reject(new SqlError('the transaction has ended'));
680
+ // The call fails before it runs anything if the addon cannot take its parameters: it must not have taken
681
+ // the deferred statements, which no call would then run (the addon's conversion is checked here, as it
682
+ // comes first there, and cannot be told from a failure of the SQL once it has run).
683
+ if (this.deferred.length > 0) {
684
+ try {
685
+ checkParams(params);
686
+ } catch (error) {
687
+ return Promise.reject(this.failure(error));
688
+ }
689
+ }
690
+ // Taken as the call is made, not as it runs: a call made before the deferral runs before it.
691
+ const before = this.deferred.splice(0);
692
+ const call = () =>
693
+ before.length === 0 ? this.native.queryColumns(sql, params) : this.native.queryColumnsAfter!(before, sql, params);
694
+ if (this.inflight === 0 && !this.ended) {
695
+ const result = this.requestNow(call);
696
+ if (!(result instanceof Promise)) return result;
697
+ this.inflight++;
698
+ this.queue = result.then(this.release, this.release);
699
+ return result;
700
+ }
701
+ return this.serial(() => this.request(call));
702
+ }
703
+
704
+ defer(sql: string): boolean {
705
+ if (this.ended || this.native.queryColumnsAfter === undefined) return false;
706
+ this.deferred.push(sql);
707
+ return true;
708
+ }
709
+
710
+ undefer(sql: string): boolean {
711
+ const at = this.deferred.lastIndexOf(sql);
712
+ if (at < 0) return false;
713
+ this.deferred.splice(at, 1);
714
+ return true;
715
+ }
716
+
717
+ /**
718
+ * Refuse calls from now on, and once those made have settled, run the SQL
719
+ * that no call took (`defer`): the body has settled, and the commit
720
+ * follows. Its failure fails the transaction, as the call that would have
721
+ * run it would have.
722
+ */
723
+ async drain(): Promise<void> {
724
+ this.ended = true;
725
+ await this.queue;
726
+ for (const sql of this.deferred.splice(0)) await this.request(() => this.native.queryColumns(sql));
475
727
  }
476
728
 
477
729
  setRecord(name: string, value: Uint8Array): void {
@@ -499,8 +751,9 @@ class OpenTransaction extends Sql implements ConnectionTransaction {
499
751
  /** Run `call`, made while the transaction is open, once the calls before it have. */
500
752
  private serial<T>(call: () => Promise<T>): Promise<T> {
501
753
  if (this.ended) return Promise.reject(new SqlError('the transaction has ended'));
754
+ this.inflight++;
502
755
  const result = this.queue.then(call);
503
- this.queue = result.catch(() => {});
756
+ this.queue = result.then(this.release, this.release);
504
757
  return result;
505
758
  }
506
759
 
package/src/driver.ts CHANGED
@@ -19,12 +19,12 @@
19
19
  // Restate shuts an attempt down by closing the request body, after its
20
20
  // inactivity timeout. From then on the attempt is over: every action throws,
21
21
  // the promises still pending reject, and a new attempt runs the handler from
22
- // the start. See the heartbeats on what keeps an attempt at work alive.
22
+ // the start, unless work in `working` keeps the attempt alive.
23
23
  import * as restate from '@restatedev/restate-sdk';
24
24
  import { isShutDown, type Vm, type VmFailure, type VmInput, type VmNotification } from './vm.ts';
25
25
 
26
26
  /**
27
- * How often an attempt at work of its own tells Restate it makes progress, in
27
+ * How often an attempt in `working` tells Restate it makes progress, in
28
28
  * milliseconds: RESTATE_SESSIONS_HEARTBEAT, or 20 seconds.
29
29
  *
30
30
  * Restate shuts down an attempt it has heard nothing from for its inactivity
@@ -171,7 +171,23 @@ export class AttemptDriver {
171
171
  */
172
172
  private carriedCancellation = false;
173
173
  private readonly cancelledPromise: Promise<void>;
174
- private heartbeats: ReturnType<typeof setInterval> | undefined;
174
+ /**
175
+ * The one timer of the heartbeats, armed for `beatDue`. It outlives a run of
176
+ * scopes, so the database's scopes (one a statement) do not start and clear
177
+ * a timer each: it fires, finds no scope open, and is not armed again.
178
+ */
179
+ private heartbeats: ReturnType<typeof setTimeout> | undefined;
180
+ private beatDue = 0;
181
+ /** The `working` scopes open: the attempt heartbeats while there is one. */
182
+ private scopes = 0;
183
+ /** The run of scopes now open: when the first opened, and its interval. */
184
+ private runEvery = 0;
185
+ /** When the run's next heartbeat is due. */
186
+ private nextBeat = 0;
187
+ /** The heartbeat interval, read from the environment on first use. */
188
+ private beatEvery: number | undefined;
189
+ /** When the attempt last wrote to Restate, which restarts Restate's inactivity timer. */
190
+ private wroteAt = Date.now();
175
191
  private readonly aborter = new AbortController();
176
192
  /**
177
193
  * The invocation's input. Taking it from the VM copies the body across the
@@ -226,7 +242,9 @@ export class AttemptDriver {
226
242
  private flush(): void {
227
243
  this.queued = false;
228
244
  const output = this.vm.takeOutput();
229
- if (output.length > 0) this.write(output);
245
+ if (output.length === 0) return;
246
+ this.write(output);
247
+ this.wroteAt = Date.now();
230
248
  }
231
249
 
232
250
  /**
@@ -550,29 +568,78 @@ export class AttemptDriver {
550
568
  // --- Keeping an attempt at work alive
551
569
  //
552
570
  // Restate shuts an attempt down once its inactivity timeout passes with
553
- // nothing heard. A heartbeat stops that while the handler works outside
554
- // Restate, on this rule: only while nothing of this attempt waits on
555
- // Restate. With something
556
- // waiting, a shutdown is what should happen — Restate starts a new attempt
557
- // when the answer comes, instead of holding a connection open meanwhile.
558
-
559
- /** Start the heartbeats of a running handler. */
560
- startHeartbeats(everyMs = heartbeatMs()): void {
561
- if (this.heartbeats !== undefined || this.ended !== undefined) return;
562
- this.heartbeats = setInterval(() => {
563
- if (this.ended !== undefined || this.waiting.size > 0) return;
564
- try {
565
- this.act((vm) => vm.heartbeat());
566
- } catch {
567
- // The attempt ended: the tick notices.
568
- }
569
- }, everyMs);
571
+ // nothing heard. That is the default: the attempt suspends on what it waits
572
+ // for (or, waiting for nothing, starts again at once), and a wait of days
573
+ // holds no process. Work that must not be cut off says so with `working`:
574
+ // while any of it runs, the attempt heartbeats, whatever else it waits for.
575
+
576
+ /**
577
+ * Run `fn`, keeping the attempt alive meanwhile: one heartbeat every
578
+ * `everyMs` from the first scope opening to the last closing. The first
579
+ * comes at once if the attempt has been silent for `everyMs` already (most
580
+ * of the timeout may be gone), so the silence never reaches twice that;
581
+ * otherwise the scopes the database opens for each of its calls would each
582
+ * send one.
583
+ */
584
+ async working<T>(fn: () => T | Promise<T>, everyMs = (this.beatEvery ??= heartbeatMs())): Promise<T> {
585
+ if (this.scopes++ === 0) this.startHeartbeats(everyMs);
586
+ try {
587
+ return await fn();
588
+ } finally {
589
+ this.scopes--;
590
+ }
591
+ }
592
+
593
+ /**
594
+ * A run of scopes opens. Its beats are `everyMs` after it opened, and every
595
+ * `everyMs` while a scope stays open: the timer is armed for the first, and
596
+ * on firing it beats if the run it finds is that old, waits out the rest if
597
+ * a run that opened later is younger, and is let go if no scope is open.
598
+ */
599
+ private startHeartbeats(everyMs: number): void {
600
+ if (this.ended !== undefined) return;
601
+ const now = Date.now();
602
+ if (now - this.wroteAt >= everyMs) this.heartbeat();
603
+ this.runEvery = everyMs;
604
+ this.nextBeat = now + everyMs;
605
+ this.arm(this.nextBeat);
606
+ }
607
+
608
+ /** Arm the timer for `due`, unless it is armed for that or earlier. */
609
+ private arm(due: number): void {
610
+ if (this.heartbeats !== undefined) {
611
+ if (this.beatDue <= due) return;
612
+ clearTimeout(this.heartbeats);
613
+ }
614
+ this.beatDue = due;
615
+ this.heartbeats = setTimeout(() => this.beat(), Math.max(0, due - Date.now()));
570
616
  this.heartbeats.unref?.();
571
617
  }
572
618
 
619
+ /** The timer fired. */
620
+ private beat(): void {
621
+ this.heartbeats = undefined;
622
+ if (this.ended !== undefined || this.scopes === 0) return;
623
+ const now = Date.now();
624
+ if (now >= this.nextBeat) {
625
+ this.heartbeat();
626
+ this.nextBeat = now + this.runEvery;
627
+ }
628
+ this.arm(this.nextBeat);
629
+ }
630
+
631
+ private heartbeat(): void {
632
+ if (this.ended !== undefined) return;
633
+ try {
634
+ this.act((vm) => vm.heartbeat());
635
+ } catch {
636
+ // The attempt ended: the tick notices.
637
+ }
638
+ }
639
+
573
640
  private stopHeartbeats(): void {
574
641
  if (this.heartbeats === undefined) return;
575
- clearInterval(this.heartbeats);
642
+ clearTimeout(this.heartbeats);
576
643
  this.heartbeats = undefined;
577
644
  }
578
645