@restatedev/sessions 0.0.0-stage → 0.1.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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +474 -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 +6 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +25 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/internal.d.ts +9 -0
  16. package/dist/internal.d.ts.map +1 -0
  17. package/dist/internal.js +12 -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/session.d.ts +167 -0
  36. package/dist/session.d.ts.map +1 -0
  37. package/dist/session.js +547 -0
  38. package/dist/session.js.map +1 -0
  39. package/package.json +46 -3
  40. package/src/calls.ts +197 -0
  41. package/src/database.ts +392 -0
  42. package/src/index.ts +35 -0
  43. package/src/internal.ts +13 -0
  44. package/src/object.ts +368 -0
  45. package/src/platform.ts +15 -0
  46. package/src/schema.ts +162 -0
  47. package/src/selector.ts +253 -0
  48. package/src/session.ts +663 -0
@@ -0,0 +1,547 @@
1
+ // An attempt's database: the session's database, kept in the object's state
2
+ // (database.ts), opened as an exclusive attempt starts (a view's on its first
3
+ // read) and saved when the handler ends; and its transactions, with the sends
4
+ // each commits with (`tx.send`).
5
+ import { Buffer } from 'node:buffer';
6
+ import { randomUUID } from 'node:crypto';
7
+ import { CancelledError, serde, TerminalError } from '@restatedev/restate-sdk';
8
+ import { millisOrDurationToMillis } from '@restatedev/restate-sdk-core';
9
+ import { open, sqlOver, SqlError, } from './database.js';
10
+ import { apply, dropAll, ofObject, sessions } from './schema.js';
11
+ import { sendOf } from './calls.js';
12
+ let wrapStore;
13
+ /** Wrap each object's store, such as for fault injection in tests. */
14
+ export function setStoreWrapper(wrap) {
15
+ wrapStore = wrap;
16
+ }
17
+ /** The end of an attempt, as `invocationEndPromise` rejects with it, for the requests that would otherwise wait for it. */
18
+ class AttemptEnd {
19
+ ended;
20
+ /** The rejections of the requests waiting. */
21
+ waiting = new Set();
22
+ listeners = new Set();
23
+ constructor(end) {
24
+ end.catch((error) => {
25
+ const ended = error instanceof Error ? error : new Error(String(error));
26
+ this.ended = ended;
27
+ for (const reject of this.waiting)
28
+ reject(ended);
29
+ this.waiting.clear();
30
+ for (const listener of this.listeners)
31
+ listener();
32
+ this.listeners.clear();
33
+ });
34
+ }
35
+ /**
36
+ * `promise`, or a rejection once the attempt ends: an attempt that is
37
+ * suspended or aborted never settles what it was waiting for.
38
+ */
39
+ race(promise) {
40
+ if (this.ended)
41
+ return Promise.reject(this.ended);
42
+ return new Promise((resolve, reject) => {
43
+ this.waiting.add(reject);
44
+ void Promise.resolve(promise)
45
+ .finally(() => this.waiting.delete(reject))
46
+ .then(resolve, reject);
47
+ });
48
+ }
49
+ /** Call `listener` when the attempt ends; the returned function cancels it. */
50
+ onEnd(listener) {
51
+ if (this.ended) {
52
+ listener();
53
+ return () => { };
54
+ }
55
+ this.listeners.add(listener);
56
+ return () => this.listeners.delete(listener);
57
+ }
58
+ }
59
+ // A state command is named after its key, so that tooling can hide the
60
+ // database's head, tail and packs by name (`dev.restate.tooling.journal.hidden.name.prefix`).
61
+ const named = (key) => ({ name: key });
62
+ // A shared handler's reader writes nothing.
63
+ const refusedWrite = () => {
64
+ throw new Error('a shared handler writes no state');
65
+ };
66
+ /**
67
+ * The keys of the database `name`, apart from the object's own: each of the
68
+ * format's keys (`v22/head`, `v22/tail/...`, `v22/manifest/...`,
69
+ * `v22/pack/...`) as `v22/db/<name>/head`, under the format's prefix still,
70
+ * which tooling hides, and under none of the object's database's.
71
+ */
72
+ const beside = (name) => (key) => {
73
+ const at = key.indexOf('/') + 1;
74
+ return `${key.slice(0, at)}db/${name}/${key.slice(at)}`;
75
+ };
76
+ /**
77
+ * The format's key of a key of the database `name` (undoes {@link beside});
78
+ * `undefined` for any other key of the object.
79
+ */
80
+ const unbeside = (name) => (key) => {
81
+ const at = key.indexOf('/') + 1;
82
+ const prefix = `db/${name}/`;
83
+ return at > 0 && key.startsWith(prefix, at) ? key.slice(0, at) + key.slice(at + prefix.length) : undefined;
84
+ };
85
+ /**
86
+ * The object's state as an ordered store: `get` is a state get, `set` and
87
+ * `clear` are state writes, which return at once and which the runtime
88
+ * stores in order; `sync` is an empty `ctx.run`, acknowledged after the
89
+ * commands before it. A `get` or `sync` the attempt's end leaves waiting
90
+ * rejects, so the session that made it ends instead of holding its lock for
91
+ * the life of the process.
92
+ */
93
+ function objectStore(ctx, end, dbName, cancelled) {
94
+ const keyOf = dbName === undefined ? (key) => key : beside(dbName);
95
+ // The addon gets a request's failure as text: a cancellation is kept here,
96
+ // for the call that failed of it to fail with it (see `Attempt.call`).
97
+ const request = (promise) => end.race(promise).catch((error) => {
98
+ if (error instanceof CancelledError)
99
+ cancelled(error);
100
+ throw error;
101
+ });
102
+ // TODO: read with protocol v8's ephemeral get, left out of the journal, once
103
+ // a Restate release ships v8 and the SDK lets a library make one. Restate 1.8
104
+ // negotiates v7 at most: a journaled get.
105
+ const get = async (key) => (await request(ctx.get(keyOf(key), serde.binary, named(keyOf(key))))) ?? undefined;
106
+ if (ctx.shared)
107
+ return { get, set: refusedWrite, clear: refusedWrite, sync: async () => { } };
108
+ return {
109
+ get,
110
+ set: (key, value) => ctx.set(keyOf(key), value, serde.binary, named(keyOf(key))),
111
+ clear: (key) => ctx.clear(keyOf(key), named(keyOf(key))),
112
+ // The database's keys, for a garbage collection.
113
+ keys: async () => {
114
+ const keys = await request(ctx.stateKeys());
115
+ if (dbName === undefined)
116
+ return keys;
117
+ const own = unbeside(dbName);
118
+ return keys.flatMap((key) => own(key) ?? []);
119
+ },
120
+ sync: async () => {
121
+ await request(ctx.run('sync', () => { }));
122
+ },
123
+ };
124
+ }
125
+ /**
126
+ * What a failed call to the session fails the handler with: an
127
+ * {@link SqlError}, which a retry would repeat, becomes a
128
+ * {@link TerminalError}, its `cause` the SQL error. Anything else is as for
129
+ * any handler: a storage error, which ends the session, or the handler's own
130
+ * (a failed request to another service, say) is retried, unless it is a
131
+ * TerminalError itself.
132
+ */
133
+ function handlerError(error) {
134
+ if (!(error instanceof SqlError))
135
+ return error;
136
+ const terminal = new TerminalError(error.message);
137
+ terminal.cause = error;
138
+ return terminal;
139
+ }
140
+ /** `call`'s result, or the error the handler fails with (see {@link handlerError}). */
141
+ async function forHandler(call) {
142
+ try {
143
+ return await call;
144
+ }
145
+ catch (error) {
146
+ throw handlerError(error);
147
+ }
148
+ }
149
+ /** The SQL of a transaction's body: `tx`'s, failing as {@link forHandler} does. */
150
+ function forBody(tx) {
151
+ return sqlOver((sql, params) => forHandler(tx.queryColumns(sql, params)), handlerError);
152
+ }
153
+ /**
154
+ * `connection`, opened without the SDK (`open`), as a handler's `ctx.db`:
155
+ * for a library's tests, and tools. Its transactions send nothing, and a
156
+ * library's schema applies to it (`Schema.ensure`).
157
+ */
158
+ export function asDatabase(connection) {
159
+ const db = {
160
+ ...sqlOver((sql, params) => connection.queryColumns(sql, params)),
161
+ transaction: (body) => connection.transaction((tx) => body({ ...forBody(tx), send: refusedSend })),
162
+ };
163
+ sessions.set(db, (schemas) => apply(connection, schemas));
164
+ return db;
165
+ }
166
+ // The transactions of `ctx.db`, each with how it empties the database (`reset`).
167
+ const resets = new WeakMap();
168
+ /**
169
+ * Empty the key's database in `tx`, a transaction of an exclusive handler's
170
+ * `ctx.db`: every table, view, index and trigger is dropped, the schemas are
171
+ * applied again (the object's, and the libraries' the attempt applied), and
172
+ * the outbox stays. It commits with `tx`: what `tx` writes after it are the
173
+ * new database's first rows, in the same commit.
174
+ */
175
+ export function reset(tx) {
176
+ const of = resets.get(tx);
177
+ if (of === undefined)
178
+ throw new TerminalError("reset takes a transaction of an exclusive handler's ctx.db");
179
+ return forHandler(of());
180
+ }
181
+ /**
182
+ * A database that `opener` opens on its first call, as a handler's `ctx.db`
183
+ * opens: for tests, which give each attempt one over the same state.
184
+ */
185
+ export function lazyDatabase(opener) {
186
+ let opened;
187
+ const db = () => (opened ??= opener());
188
+ const lazy = {
189
+ query: async (sql, params) => (await db()).query(sql, params),
190
+ get: async (sql, params) => (await db()).get(sql, params),
191
+ values: async (sql, params) => (await db()).values(sql, params),
192
+ execute: async (sql, params) => (await db()).execute(sql, params),
193
+ transaction: async (body) => (await db()).transaction(body),
194
+ };
195
+ sessions.set(lazy, async (schemas) => {
196
+ const inner = await db();
197
+ const ensure = sessions.get(inner);
198
+ if (ensure === undefined)
199
+ throw new TerminalError("lazyDatabase opens a handler's ctx.db, or a database of asDatabase");
200
+ await ensure(schemas);
201
+ });
202
+ return lazy;
203
+ }
204
+ /** The sends of a transaction that has no outbox: a shared handler's, or another database's. */
205
+ const refusedSend = () => {
206
+ throw new TerminalError("a send of a transaction is an exclusive handler's, in the object's own database");
207
+ };
208
+ /** The database's record of the outbox. */
209
+ const OUTBOX = 'outbox';
210
+ /** The outbox as its record: none is empty, as a record never set reads. */
211
+ function encodeOutbox(outbox) {
212
+ return outbox.length === 0 ? new Uint8Array() : new TextEncoder().encode(JSON.stringify(outbox));
213
+ }
214
+ function decodeOutbox(record) {
215
+ return record.length === 0 ? [] : JSON.parse(new TextDecoder().decode(record));
216
+ }
217
+ function storedSend(send) {
218
+ const { parameter, inputSerde, delay, ...rest } = send;
219
+ return {
220
+ ...rest,
221
+ ...(delay !== undefined ? { delay: millisOrDurationToMillis(delay) } : {}),
222
+ parameter: Buffer.from((inputSerde ?? serde.binary).serialize(parameter)).toString('base64'),
223
+ };
224
+ }
225
+ function settle(outcome) {
226
+ if ('error' in outcome)
227
+ throw outcome.error;
228
+ return outcome.value;
229
+ }
230
+ // The attempts, by their `ctx.db`: for `database`.
231
+ const attempts = new WeakMap();
232
+ // A database's name (`database`).
233
+ const DATABASE_NAME = /^[\w.-]{1,64}$/;
234
+ /**
235
+ * The database `name` of the key, apart from the object's own (`ctx.db`, of
236
+ * the attempt whose session `db` is): for a library whose tables must be
237
+ * alone in their database, such as OpenCode's. It opens on its first use,
238
+ * and ends with the attempt, as `ctx.db` does. A name is 1 to 64 letters,
239
+ * digits, `_`, `-` or `.`.
240
+ */
241
+ export function database(db, name) {
242
+ if (!DATABASE_NAME.test(name))
243
+ throw new TerminalError(`database: ${JSON.stringify(name)} is not a database name`);
244
+ const attempt = attempts.get(db);
245
+ if (attempt === undefined)
246
+ throw new TerminalError("database takes a handler's ctx.db");
247
+ return attempt.database(name);
248
+ }
249
+ /**
250
+ * An attempt's SQL session: opened on its first use, or as an exclusive
251
+ * attempt starts ({@link openNow}), shared by everything the handler does,
252
+ * and saved when the handler ends ({@link end}). With `name`, of the key's database `name`
253
+ * ({@link database}), which has neither the object's schema nor an outbox.
254
+ */
255
+ export class Attempt {
256
+ /** `ctx.db`. */
257
+ db;
258
+ ctx;
259
+ name;
260
+ /** The key's other databases this attempt opened, by name. */
261
+ databases = new Map();
262
+ /** The session, from its first use on. */
263
+ session;
264
+ /** The ids of the outbox's transactions this attempt made the sends of. */
265
+ made = new Set();
266
+ /** The schemas this attempt's database has all the steps of. */
267
+ ensured = new Map();
268
+ ended = false;
269
+ /** Opened when the attempt started ({@link openNow}), and no call has seen how it went yet. */
270
+ unseenOpen = false;
271
+ /** Stops closing the session when the attempt ends. */
272
+ keepOpen = () => { };
273
+ /** The invocation's cancellation, once a request of the session failed of it. */
274
+ cancelled;
275
+ constructor(ctx, name) {
276
+ this.ctx = ctx;
277
+ this.name = name;
278
+ this.db = {
279
+ ...sqlOver((sql, params) => this.call((db) => db.queryColumns(sql, params)), handlerError),
280
+ // A shared handler's writes stay in its session: it has no outbox.
281
+ transaction: (body) => this.ctx.shared
282
+ ? this.call((db) => db.transaction((tx) => body({ ...forBody(tx), send: refusedSend })))
283
+ : this.name !== undefined
284
+ ? this.call((db) => db.transaction((handle) => {
285
+ const transaction = { ...forBody(handle), send: refusedSend };
286
+ resets.set(transaction, () => this.reset(handle));
287
+ return body(transaction);
288
+ }))
289
+ : this.withSends((tx, record, handle) => {
290
+ const transaction = { ...tx, send: sendOf(record) };
291
+ resets.set(transaction, () => this.reset(handle));
292
+ return body(transaction);
293
+ }),
294
+ };
295
+ sessions.set(this.db, (schemas) => {
296
+ this.unseenOpen = false;
297
+ return this.opened().then((db) => this.ensureSchemas(db, schemas));
298
+ });
299
+ attempts.set(this.db, this);
300
+ }
301
+ /** The key's database `name`, in this attempt: see {@link database}. */
302
+ database(name) {
303
+ if (this.ended)
304
+ throw new Error('the handler has ended: its SQL session is closed');
305
+ let other = this.databases.get(name);
306
+ if (other === undefined)
307
+ this.databases.set(name, (other = new Attempt(this.ctx, name)));
308
+ return other.db;
309
+ }
310
+ /**
311
+ * One transaction of the session, whose sends are made once it commits,
312
+ * and kept in the outbox until they are stored: `body` gets its SQL, and
313
+ * `record`, which records a send.
314
+ */
315
+ async withSends(body) {
316
+ const sends = [];
317
+ let recording = true;
318
+ const record = (send) => {
319
+ if (!recording)
320
+ throw new TerminalError('the transaction has ended: send from inside its body');
321
+ sends.push(storedSend(send));
322
+ };
323
+ let outgoing;
324
+ const value = await this.call((db) => db.transaction(async (handle) => {
325
+ let result;
326
+ try {
327
+ result = await body(forBody(handle), record, handle);
328
+ }
329
+ finally {
330
+ recording = false;
331
+ }
332
+ // The outbox as committed, but the sends stored since, and this
333
+ // transaction's: unchanged, it is not written again.
334
+ const outbox = await this.unstored(handle);
335
+ if (sends.length > 0) {
336
+ // A delay counts from the commit: one made again waits what remains.
337
+ const now = Date.now();
338
+ for (const send of sends)
339
+ if (send.delay !== undefined)
340
+ send.due = now + send.delay;
341
+ outgoing = { id: randomUUID(), sends };
342
+ outbox.push(outgoing);
343
+ }
344
+ handle.setRecord(OUTBOX, encodeOutbox(outbox));
345
+ return result;
346
+ }));
347
+ if (outgoing !== undefined) {
348
+ this.make(outgoing);
349
+ // Emptied at once, by a commit after the sends, which Restate stores
350
+ // before it: left in the outbox until the handler's end, they would be
351
+ // made again by an attempt that resumes a long wait (an approval), past
352
+ // the idempotency retention that drops a repeat.
353
+ await this.call((db) => this.flush(db));
354
+ }
355
+ return value;
356
+ }
357
+ /**
358
+ * The handler ended with `outcome`: an SQL error that escaped it becomes
359
+ * terminal, then the outbox is emptied, and the session is saved. One that
360
+ * a storage error ended closes now, rather than when it is collected.
361
+ */
362
+ async end(outcome) {
363
+ // The key's other databases end first, as the handler left them.
364
+ const databases = await Promise.allSettled([...this.databases.values()].map((d) => d.end({ value: undefined })));
365
+ const value = await this.endSession(outcome);
366
+ const failed = databases.find((d) => d.status === 'rejected');
367
+ if (failed)
368
+ throw failed.reason;
369
+ return value;
370
+ }
371
+ /**
372
+ * Open the session now, as the attempt starts, rather than on its first
373
+ * call: the open makes the sends a crashed attempt committed and left
374
+ * unmade, which must not wait for a handler that uses the database.
375
+ */
376
+ openNow() {
377
+ if (this.ctx.shared || this.name !== undefined || this.session !== undefined)
378
+ return;
379
+ this.unseenOpen = true;
380
+ this.opened().catch(() => { });
381
+ }
382
+ /** Empty the database in the transaction `handle` ({@link reset}), and apply the schemas this attempt applied again. */
383
+ async reset(handle) {
384
+ // Another database of the key has none of the object's schema.
385
+ const own = this.name === undefined ? ofObject(this.ctx.request().target.service) : undefined;
386
+ const schemas = [...(own ? [own] : []), ...[...this.ensured.values()].filter((s) => s !== own)];
387
+ await dropAll(handle, schemas);
388
+ }
389
+ /**
390
+ * `call` on the session, opening it on the first; its failure as the
391
+ * handler fails with it, or the invocation's cancellation, if a request of
392
+ * the session failed of it: a call it ended fails with a CancelledError,
393
+ * as any of the handler's awaits does.
394
+ */
395
+ async call(call) {
396
+ this.unseenOpen = false;
397
+ try {
398
+ const db = await this.opened();
399
+ return await forHandler(call(db));
400
+ }
401
+ catch (error) {
402
+ throw this.cancelled ?? error;
403
+ }
404
+ }
405
+ /** Apply the steps of `schemas` that the database lacks, each schema once per attempt. */
406
+ async ensureSchemas(db, schemas) {
407
+ const lacking = schemas.filter((s) => !this.ensured.has(s.name));
408
+ if (lacking.length === 0)
409
+ return;
410
+ await forHandler(apply(db, lacking, { reader: this.ctx.shared }));
411
+ for (const s of lacking)
412
+ this.ensured.set(s.name, s);
413
+ }
414
+ /** Make the sends of a committed transaction: each with an idempotency key of the transaction (or its own), so that making them again is dropped. */
415
+ make({ id, sends }, again = false) {
416
+ sends.forEach(({ parameter, due, delay, ...send }, index) => {
417
+ this.ctx.genericSend({
418
+ ...send,
419
+ // Made again, a delayed send waits only what remains of its delay.
420
+ ...(delay !== undefined ? { delay: again && due !== undefined ? Math.max(0, due - Date.now()) : delay } : {}),
421
+ parameter: new Uint8Array(Buffer.from(parameter, 'base64')),
422
+ inputSerde: serde.binary,
423
+ idempotencyKey: send.idempotencyKey ?? `transaction/${id}/${index}`,
424
+ });
425
+ });
426
+ this.made.add(id);
427
+ }
428
+ /** The outbox as committed, but the transactions this attempt made the sends of: a commit made after them stores them first. */
429
+ async unstored(db) {
430
+ return decodeOutbox(await db.record(OUTBOX)).filter(({ id }) => !this.made.has(id));
431
+ }
432
+ /**
433
+ * Empty the outbox, so that a later open does not make its sends again: a
434
+ * commit after them, which stores them first.
435
+ */
436
+ async flush(db) {
437
+ if ((await db.record(OUTBOX)).length === 0)
438
+ return;
439
+ // Read in the transaction that writes it: one that committed sends since
440
+ // the read above keeps them.
441
+ await db.transaction(async (tx) => tx.setRecord(OUTBOX, encodeOutbox(await this.unstored(tx))));
442
+ }
443
+ /** The session, opening it on the first call. */
444
+ opened() {
445
+ if (this.ended)
446
+ return Promise.reject(new Error('the handler has ended: its SQL session is closed'));
447
+ this.session ??= this.start();
448
+ return this.session;
449
+ }
450
+ async start() {
451
+ const ctx = this.ctx;
452
+ // The page cache's: the key escaped, so that no key reads as another's
453
+ // database (a name has no `/`).
454
+ const key = `${ctx.request().target.service}/${encodeURIComponent(ctx.key)}`;
455
+ const namespace = this.name === undefined ? key : `${key}/${this.name}`;
456
+ const end = new AttemptEnd(ctx.invocationEndPromise.promise);
457
+ const object = objectStore(ctx, end, this.name, (error) => (this.cancelled ??= error));
458
+ const db = await open(namespace, wrapStore ? wrapStore(object) : object, { reader: ctx.shared });
459
+ // A handler still waiting for something else when the attempt ends (a
460
+ // model request, say) keeps the session no longer: it closes once no
461
+ // statement runs, and the handler's later calls fail.
462
+ this.keepOpen = end.onEnd(() => void db.close().catch(() => { }));
463
+ // The object's schema: in a shared handler's session too, whose writes are never stored, so a
464
+ // key never written reads as empty tables.
465
+ const own = this.name === undefined ? ofObject(ctx.request().target.service) : undefined;
466
+ try {
467
+ // A view writes nothing: a write fails, rather than vanish with the attempt.
468
+ if (ctx.shared)
469
+ await db.execute('PRAGMA query_only = 1');
470
+ // What a crash may have left unmade.
471
+ if (!ctx.shared && this.name === undefined) {
472
+ const left = decodeOutbox(await db.record(OUTBOX));
473
+ left.forEach((outgoing) => this.make(outgoing, true));
474
+ // Emptied at once, as a transaction's own sends are (see `withSends`):
475
+ // kept until the handler's end, an attempt that resumes a long wait
476
+ // would make them again, past the idempotency retention.
477
+ if (left.length > 0)
478
+ await this.flush(db);
479
+ }
480
+ if (own)
481
+ await this.ensureSchemas(db, [own]);
482
+ }
483
+ catch (error) {
484
+ const failed = handlerError(error);
485
+ await db.close();
486
+ throw failed;
487
+ }
488
+ return db;
489
+ }
490
+ async endSession(outcome) {
491
+ this.ended = true;
492
+ const session = this.session;
493
+ if (session === undefined)
494
+ return settle(outcome);
495
+ let db;
496
+ try {
497
+ db = await session;
498
+ }
499
+ catch (error) {
500
+ // The open failed, and its error went to the call that made it; one
501
+ // made as the attempt started that no call saw fails the attempt, as
502
+ // its outbox is still to be made.
503
+ if (this.unseenOpen)
504
+ throw error;
505
+ return settle(outcome);
506
+ }
507
+ this.keepOpen();
508
+ if (this.ctx.shared) {
509
+ // It read the snapshot it opened on, whatever committed since; one that
510
+ // outlived 16 commits failed its read ("is gone"), and is retried.
511
+ const failed = 'error' in outcome ? handlerError(outcome.error) : undefined;
512
+ await db.close();
513
+ if ('error' in outcome)
514
+ throw failed;
515
+ return outcome.value;
516
+ }
517
+ if ('error' in outcome) {
518
+ const error = handlerError(outcome.error);
519
+ // The handler's error stands: what it committed is stored, and an
520
+ // outbox left full is made again by the next open.
521
+ await this.save(db).catch(() => db.close().catch(() => { }));
522
+ throw error;
523
+ }
524
+ // A transaction left open, say, which a retry would leave open again.
525
+ await forHandler(this.save(db));
526
+ return outcome.value;
527
+ }
528
+ /** Empty the outbox and save the session; one a storage error ended only closes. */
529
+ async save(db) {
530
+ if (!db.isUsable())
531
+ return db.close();
532
+ await this.flush(db);
533
+ await db.save();
534
+ }
535
+ }
536
+ /** Run `handler`, then end `attempt`'s SQL session, if it opened one (see {@link Attempt.end}). */
537
+ export async function withAttempt(handler, attempt) {
538
+ let outcome;
539
+ try {
540
+ outcome = { value: await handler() };
541
+ }
542
+ catch (error) {
543
+ outcome = { error };
544
+ }
545
+ return attempt.end(outcome);
546
+ }
547
+ //# sourceMappingURL=session.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../src/session.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,8EAA8E;AAC9E,8EAA8E;AAC9E,iCAAiC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CA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1
1
  {
2
2
  "name": "@restatedev/sessions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Session objects on Restate: virtual objects with a SQL database per key, kept in the object's state (ctx.db)",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/restatedev/sdk-sessions.git",
9
+ "directory": "packages/sessions"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "src"
14
+ ],
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./internal": {
23
+ "types": "./dist/internal.d.ts",
24
+ "default": "./dist/internal.js"
25
+ }
26
+ },
27
+ "dependencies": {
28
+ "@restatedev/restate-sdk": "1.18.2",
29
+ "@restatedev/restate-sdk-core": "1.18.2"
30
+ },
31
+ "optionalDependencies": {
32
+ "@restatedev/sessions-darwin-arm64": "0.1.0",
33
+ "@restatedev/sessions-linux-arm64-gnu": "0.1.0",
34
+ "@restatedev/sessions-linux-x64-gnu": "0.1.0"
35
+ },
36
+ "engines": {
37
+ "node": ">=24"
38
+ },
39
+ "scripts": {
40
+ "build": "cargo build --release --manifest-path native/Cargo.toml && node native/copy-addon.ts release",
41
+ "build:debug": "cargo build --manifest-path native/Cargo.toml && node native/copy-addon.ts debug",
42
+ "test": "vitest run",
43
+ "test:rust": "cd native && cargo test --locked --release",
44
+ "lint:rust": "cd native && cargo fmt --check && cargo clippy --locked --all-targets -- -D warnings && cargo clippy --locked --all-targets --features bench,object-store -- -D warnings",
45
+ "format:rust": "cd native && cargo fmt",
46
+ "build:dist": "cargo build --locked --profile dist --manifest-path native/Cargo.toml && node native/copy-addon.ts dist",
47
+ "build:ts": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.build.json"
48
+ }
6
49
  }