@restatedev/sessions 0.2.0 → 0.4.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/README.md +47 -8
- package/dist/database.d.ts +41 -2
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +99 -20
- package/dist/database.js.map +1 -1
- package/dist/internal.d.ts +5 -3
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +4 -2
- package/dist/internal.js.map +1 -1
- package/dist/link.d.ts +10 -0
- package/dist/link.d.ts.map +1 -0
- package/dist/link.js +19 -0
- package/dist/link.js.map +1 -0
- package/dist/object.d.ts +17 -4
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +61 -46
- package/dist/object.js.map +1 -1
- package/dist/schema.d.ts +7 -6
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +9 -10
- package/dist/schema.js.map +1 -1
- package/dist/scope.d.ts +38 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +55 -0
- package/dist/scope.js.map +1 -0
- package/dist/session.d.ts +70 -34
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +273 -221
- package/dist/session.js.map +1 -1
- package/package.json +5 -5
- package/src/database.ts +111 -22
- package/src/internal.ts +15 -3
- package/src/link.ts +22 -0
- package/src/object.ts +94 -63
- package/src/schema.ts +11 -10
- package/src/scope.ts +78 -0
- package/src/session.ts +273 -230
package/src/object.ts
CHANGED
|
@@ -18,10 +18,12 @@
|
|
|
18
18
|
import * as restate from '@restatedev/restate-sdk';
|
|
19
19
|
import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
|
|
20
20
|
import { type Rpc, rpcOf, type Send, sendOf } from './calls.ts';
|
|
21
|
-
import type { DatabaseReader } from './database.ts';
|
|
22
|
-
import {
|
|
21
|
+
import type { DatabaseReader, Store } from './database.ts';
|
|
22
|
+
import { ensureOf, ensuring, Schema, type Step } from './schema.ts';
|
|
23
|
+
import { Link } from './link.ts';
|
|
24
|
+
import { holding, Scope, scopeOf } from './scope.ts';
|
|
23
25
|
import { hookSelector } from './selector.ts';
|
|
24
|
-
import { type Database, Attempt, type SqlHost, withAttempt } from './session.ts';
|
|
26
|
+
import { type Database, Attempt, type ObjectConfig, type SqlHost, withAttempt } from './session.ts';
|
|
25
27
|
|
|
26
28
|
/**
|
|
27
29
|
* The context of a session object's handler. A handler runs in attempts:
|
|
@@ -149,11 +151,42 @@ export function host(
|
|
|
149
151
|
};
|
|
150
152
|
}
|
|
151
153
|
|
|
152
|
-
/**
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
154
|
+
/** A session object's: its config, which its attempts get, and its definition, once made. */
|
|
155
|
+
interface ObjectState {
|
|
156
|
+
readonly config: ObjectConfig;
|
|
157
|
+
definition?: object;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** A handler or view of a session object: its function, kind, and object. */
|
|
161
|
+
interface HandlerEntry {
|
|
162
|
+
fn: Fn<never>;
|
|
163
|
+
view: boolean;
|
|
164
|
+
explicit: boolean;
|
|
165
|
+
object: ObjectState;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** A session object's own, on its definition: for {@link invoke} and {@link withStoreWrapper}. */
|
|
169
|
+
const OBJECT = new Link<{ object: ObjectState; entries: Map<string, HandlerEntry> }>('a session object');
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The definition (`sessionObject`'s) of the object whose handler or view
|
|
173
|
+
* `ctx` is the context of: what a library keeps per object lives on it.
|
|
174
|
+
*/
|
|
175
|
+
export const definitionOf = (ctx: SessionContext | ViewContext): object | undefined => scopeOf(ctx)?.definition;
|
|
176
|
+
|
|
177
|
+
/** What `definition`'s attempts get, if it is a session object: for a test's attempts of its own. */
|
|
178
|
+
export const configOf = (definition: object): ObjectConfig | undefined => OBJECT.of(definition)?.object.config;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Wrap the stores of `definition`'s attempts with `wrap`: fault injection, in
|
|
182
|
+
* tests. A definition that is no session object has no store: it is left as
|
|
183
|
+
* it is.
|
|
184
|
+
*/
|
|
185
|
+
export function withStoreWrapper<D extends object>(definition: D, wrapper: (store: Store) => Store): D {
|
|
186
|
+
const object = OBJECT.of(definition);
|
|
187
|
+
if (object !== undefined) object.object.config.wrapStore = wrapper;
|
|
188
|
+
return definition;
|
|
189
|
+
}
|
|
157
190
|
|
|
158
191
|
/** The reads of `db`, which apply a library's schema as `db` does (`Schema.ensure`). */
|
|
159
192
|
function readerOf(db: Database): DatabaseReader {
|
|
@@ -162,9 +195,8 @@ function readerOf(db: Database): DatabaseReader {
|
|
|
162
195
|
get: (sql, params) => db.get(sql, params),
|
|
163
196
|
values: (sql, params) => db.values(sql, params),
|
|
164
197
|
};
|
|
165
|
-
const ensure =
|
|
166
|
-
|
|
167
|
-
return Object.freeze(reader);
|
|
198
|
+
const ensure = ensureOf(db);
|
|
199
|
+
return Object.freeze(ensure ? ensuring(reader, ensure) : reader);
|
|
168
200
|
}
|
|
169
201
|
|
|
170
202
|
/**
|
|
@@ -173,32 +205,39 @@ function readerOf(db: Database): DatabaseReader {
|
|
|
173
205
|
* over a context of its own. With `explicitCancellation`, a handler's with
|
|
174
206
|
* that option, which {@link cancelled} and {@link cancelCalls} take.
|
|
175
207
|
*/
|
|
176
|
-
export function contextOf(ctx: AttemptContext, db: Database, options: { view: true }): ViewContext;
|
|
208
|
+
export function contextOf(ctx: AttemptContext, db: Database, options: { view: true; definition?: object }): ViewContext;
|
|
177
209
|
export function contextOf(
|
|
178
210
|
ctx: AttemptContext,
|
|
179
211
|
db: Database,
|
|
180
|
-
options?: { view?: false; explicitCancellation?: boolean },
|
|
212
|
+
options?: { view?: false; explicitCancellation?: boolean; definition?: object },
|
|
181
213
|
): SessionContext;
|
|
182
214
|
export function contextOf(
|
|
183
215
|
ctx: AttemptContext,
|
|
184
216
|
db: Database,
|
|
185
|
-
{
|
|
217
|
+
{
|
|
218
|
+
view = false,
|
|
219
|
+
explicitCancellation = false,
|
|
220
|
+
definition,
|
|
221
|
+
}: { view?: boolean; explicitCancellation?: boolean; definition?: object } = {},
|
|
186
222
|
): SessionContext | ViewContext {
|
|
187
|
-
if (explicitCancellation) explicitlyCancelled.add(ctx);
|
|
188
223
|
const rpc = rpcOf(ctx);
|
|
189
224
|
const cancel = cancelOf(ctx);
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
225
|
+
// It holds the attempt's scope (scope.ts), then is frozen.
|
|
226
|
+
const scope = new Scope(ctx as unknown as restate.ObjectContext, { explicitCancellation, definition });
|
|
227
|
+
const context: SessionContext | ViewContext = holding(
|
|
228
|
+
view
|
|
229
|
+
? { key: ctx.key, request: ctx.request(), db: readerOf(db), rpc, cancel }
|
|
230
|
+
: {
|
|
231
|
+
key: ctx.key,
|
|
232
|
+
request: ctx.request(),
|
|
233
|
+
db,
|
|
234
|
+
rpc,
|
|
235
|
+
send: sendOf((send) => void ctx.genericSend(send)),
|
|
236
|
+
cancel,
|
|
237
|
+
},
|
|
238
|
+
scope,
|
|
239
|
+
);
|
|
240
|
+
return Object.freeze(context);
|
|
202
241
|
}
|
|
203
242
|
|
|
204
243
|
/** {@link Cancel} over the SDK's context `ctx`. */
|
|
@@ -210,52 +249,42 @@ const cancelOf =
|
|
|
210
249
|
ctx.invocation(restate.InvocationIdParser.fromString(invocationId)).cancel();
|
|
211
250
|
};
|
|
212
251
|
|
|
213
|
-
/** One attempt of `
|
|
214
|
-
function attempt(
|
|
215
|
-
|
|
216
|
-
{ view, explicit }: { view: boolean; explicit: boolean },
|
|
217
|
-
ctx: AttemptContext,
|
|
218
|
-
input: unknown,
|
|
219
|
-
): Promise<unknown> {
|
|
220
|
-
const session = new Attempt(host(ctx, view));
|
|
252
|
+
/** One attempt of `entry` over `ctx`: its own context and session, which ends with it. */
|
|
253
|
+
function attempt({ fn, view, explicit, object }: HandlerEntry, ctx: AttemptContext, input: unknown): Promise<unknown> {
|
|
254
|
+
const session = new Attempt(host(ctx, view), object.config);
|
|
221
255
|
session.openNow();
|
|
256
|
+
const { definition } = object;
|
|
222
257
|
const context = view
|
|
223
|
-
? contextOf(ctx, session.db, { view: true })
|
|
224
|
-
: contextOf(ctx, session.db, { explicitCancellation: explicit });
|
|
258
|
+
? contextOf(ctx, session.db, { view: true, definition })
|
|
259
|
+
: contextOf(ctx, session.db, { explicitCancellation: explicit, definition });
|
|
225
260
|
return withAttempt(() => fn(context as never, input as never), session);
|
|
226
261
|
}
|
|
227
262
|
|
|
228
|
-
/** `
|
|
229
|
-
function wrap(
|
|
263
|
+
/** `entry` as the SDK's handler: one loop drives each attempt's awaits (see selector.ts), until it ends. */
|
|
264
|
+
function wrap(entry: HandlerEntry) {
|
|
230
265
|
return (ctx: restate.ObjectContext | restate.ObjectSharedContext, input: never) => {
|
|
231
266
|
const unhook = hookSelector(ctx);
|
|
232
267
|
const runtime = ctx as unknown as Runtime;
|
|
233
268
|
runtime.invocationEndPromise.promise.catch(unhook);
|
|
234
|
-
return attempt(
|
|
269
|
+
return attempt(entry, ctx as unknown as AttemptContext, input).finally(unhook);
|
|
235
270
|
};
|
|
236
271
|
}
|
|
237
272
|
|
|
238
|
-
/** Each session object's handlers and views, by name: for {@link invoke}. */
|
|
239
|
-
const entries = new WeakMap<object, Map<string, { fn: Fn<never>; view: boolean; explicit: boolean }>>();
|
|
240
|
-
|
|
241
|
-
/** The SDK's contexts of the handlers with `explicitCancellation: true`: for {@link cancelled}. */
|
|
242
|
-
const explicitlyCancelled = new WeakSet<object>();
|
|
243
|
-
|
|
244
273
|
/**
|
|
245
274
|
* Run handler or view `name` of `definition` for one attempt over `ctx`, a
|
|
246
275
|
* context of a test's own, without Restate: for tests.
|
|
247
276
|
*/
|
|
248
277
|
export function invoke(definition: { name: string }, name: string, ctx: AttemptContext, input?: unknown) {
|
|
249
|
-
const entry =
|
|
278
|
+
const entry = OBJECT.of(definition)?.entries.get(name);
|
|
250
279
|
if (entry === undefined) throw new Error(`${definition.name}.${name} is no handler or view of a session object`);
|
|
251
|
-
return attempt(entry
|
|
280
|
+
return attempt(entry, ctx, input);
|
|
252
281
|
}
|
|
253
282
|
|
|
254
283
|
/** Whether `value` is a handler of the SDK's already. */
|
|
255
284
|
const isSdkHandler = (value: object) => Object.getOwnPropertySymbols(value).some((s) => s.description === 'Handler');
|
|
256
285
|
|
|
257
286
|
/** The SDK's handler of entry `name` of `object`. */
|
|
258
|
-
function handlerOf(
|
|
287
|
+
function handlerOf(objectName: string, name: string, entry: unknown, view: boolean, object: ObjectState) {
|
|
259
288
|
const [fn, options] =
|
|
260
289
|
typeof entry === 'function'
|
|
261
290
|
? [entry, {}]
|
|
@@ -266,18 +295,19 @@ function handlerOf(object: string, name: string, entry: unknown, view: boolean)
|
|
|
266
295
|
})()
|
|
267
296
|
: [undefined, undefined];
|
|
268
297
|
if (fn === undefined)
|
|
269
|
-
throw new TypeError(`${
|
|
298
|
+
throw new TypeError(`${objectName}.${name} is not a handler: a function, or { handler, ...options }`);
|
|
270
299
|
if (isSdkHandler(fn)) {
|
|
271
300
|
throw new TypeError(
|
|
272
|
-
`${
|
|
301
|
+
`${objectName}.${name} is an SDK handler: a session object's handlers are functions of its context. ` +
|
|
273
302
|
'Put journaled work in a restate.object, service or workflow, and call it with ctx.rpc',
|
|
274
303
|
);
|
|
275
304
|
}
|
|
276
305
|
const opts = { ...options, ...recovery() } as HandlerOptions;
|
|
277
306
|
const explicit = (options as HandlerOptions).explicitCancellation === true;
|
|
278
|
-
const made =
|
|
279
|
-
const
|
|
280
|
-
|
|
307
|
+
const made: HandlerEntry = { fn: fn as Fn<never>, view, explicit, object };
|
|
308
|
+
const sdk = wrap(made) as never;
|
|
309
|
+
const handler = view ? restate.handlers.object.shared(opts, sdk) : restate.handlers.object.exclusive(opts, sdk);
|
|
310
|
+
return { handler, entry: made };
|
|
281
311
|
}
|
|
282
312
|
|
|
283
313
|
/**
|
|
@@ -316,17 +346,17 @@ export function sessionObject<
|
|
|
316
346
|
if (options && ('state' in options || 'enableLazyState' in options)) {
|
|
317
347
|
throw new Error(`${name}: a session object sets its state options itself: leave out state and enableLazyState`);
|
|
318
348
|
}
|
|
319
|
-
|
|
349
|
+
const object: ObjectState = { config: { schema: schema ? new Schema(name, schema) : undefined } };
|
|
320
350
|
const sdkHandlers: Record<string, (ctx: restate.ObjectContext, input?: unknown) => Promise<unknown>> = {};
|
|
321
|
-
const
|
|
351
|
+
const entries = new Map<string, HandlerEntry>();
|
|
322
352
|
for (const [view, map] of [
|
|
323
353
|
[false, handlers],
|
|
324
354
|
[true, views],
|
|
325
355
|
] as const) {
|
|
326
356
|
for (const [key, value] of Object.entries(map)) {
|
|
327
|
-
const { handler, entry } = handlerOf(name, key, value, view);
|
|
357
|
+
const { handler, entry } = handlerOf(name, key, value, view, object);
|
|
328
358
|
sdkHandlers[key] = handler;
|
|
329
|
-
|
|
359
|
+
entries.set(key, entry);
|
|
330
360
|
}
|
|
331
361
|
}
|
|
332
362
|
const made = restate.object({
|
|
@@ -336,18 +366,19 @@ export function sessionObject<
|
|
|
336
366
|
metadata: { ...sqlMetadata, ...metadata },
|
|
337
367
|
options: { ...sqlOptions, ...options },
|
|
338
368
|
});
|
|
339
|
-
|
|
369
|
+
object.definition = made;
|
|
370
|
+
OBJECT.on(made, { object, entries });
|
|
340
371
|
return made;
|
|
341
372
|
}
|
|
342
373
|
|
|
343
374
|
/** The SDK's context behind `ctx`, a handler's with `explicitCancellation: true`. */
|
|
344
375
|
function explicitOf(ctx: SessionContext, of: string) {
|
|
345
|
-
const
|
|
346
|
-
if (
|
|
347
|
-
if (!
|
|
376
|
+
const scope = scopeOf(ctx);
|
|
377
|
+
if (scope === undefined) throw new restate.TerminalError(`${of} takes a session object's ctx`);
|
|
378
|
+
if (!scope.explicitCancellation) {
|
|
348
379
|
throw new restate.TerminalError(`${of} takes the ctx of a handler with explicitCancellation: true`);
|
|
349
380
|
}
|
|
350
|
-
return restate.internal.asInternal(sdk);
|
|
381
|
+
return restate.internal.asInternal(scope.sdk);
|
|
351
382
|
}
|
|
352
383
|
|
|
353
384
|
/**
|
package/src/schema.ts
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
// in a schema of their own name, which `schema.ensure(ctx.db)` applies where
|
|
22
22
|
// they use them, in any object: internal, from @restatedev/sessions/internal.
|
|
23
23
|
import type { Connection, DatabaseReader, DatabaseWriter, ConnectionTransaction } from './database.ts';
|
|
24
|
+
import { Link } from './link.ts';
|
|
24
25
|
|
|
25
26
|
/**
|
|
26
27
|
* The database's record of its schemas: how many steps of each it has, by
|
|
@@ -56,22 +57,22 @@ export class Schema {
|
|
|
56
57
|
* handler's are its own, vanishing with its session.
|
|
57
58
|
*/
|
|
58
59
|
ensure(db: DatabaseReader | Connection): Promise<void> {
|
|
59
|
-
const
|
|
60
|
-
return
|
|
60
|
+
const ensure = ensureOf(db);
|
|
61
|
+
return ensure ? ensure([this]) : apply(db as Connection, [this]);
|
|
61
62
|
}
|
|
62
63
|
}
|
|
63
64
|
|
|
64
|
-
/**
|
|
65
|
-
|
|
65
|
+
/** How a database applies schemas: a handler's (`ctx.db`, its reader), or one of `asDatabase`. */
|
|
66
|
+
type Ensure = (schemas: readonly Schema[]) => Promise<void>;
|
|
66
67
|
|
|
67
|
-
|
|
68
|
-
const
|
|
68
|
+
/** A database's {@link Ensure}. */
|
|
69
|
+
const ENSURE = new Link<Ensure>('Schema.ensure');
|
|
69
70
|
|
|
70
|
-
/**
|
|
71
|
-
export const
|
|
71
|
+
/** `db`, which applies schemas with `ensure` (see {@link Schema.ensure}). */
|
|
72
|
+
export const ensuring = <D extends object>(db: D, ensure: Ensure): D => ENSURE.on(db, ensure);
|
|
72
73
|
|
|
73
|
-
/**
|
|
74
|
-
export const
|
|
74
|
+
/** How `db` applies schemas, if it is a database of this package's. */
|
|
75
|
+
export const ensureOf = (db: object): Ensure | undefined => ENSURE.of(db);
|
|
75
76
|
|
|
76
77
|
/** Apply the steps of `schemas` that `db` lacks, in one transaction, with how far each got. */
|
|
77
78
|
export async function apply(db: Connection, schemas: readonly Schema[], { reader = false } = {}) {
|
package/src/scope.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// An attempt's scope: what its code keeps for the attempt (an agent's turn,
|
|
2
|
+
// the calls of its tools...), which its context holds and which ends with it.
|
|
3
|
+
// A retry gets a context, and so a scope, of its own. A module holds only the
|
|
4
|
+
// key of what it keeps (`ScopeKey`), never the state.
|
|
5
|
+
import type * as restate from '@restatedev/restate-sdk';
|
|
6
|
+
import { Link } from './link.ts';
|
|
7
|
+
import type { SessionContext, ViewContext } from './object.ts';
|
|
8
|
+
|
|
9
|
+
/** A context of an attempt: a handler's or a view's. */
|
|
10
|
+
type Context = SessionContext | ViewContext;
|
|
11
|
+
|
|
12
|
+
/** The scope's values, which only {@link ScopeKey} reaches. */
|
|
13
|
+
const VALUES = Symbol('values');
|
|
14
|
+
|
|
15
|
+
/** An attempt's own, as @restatedev/sessions made it, and what its code keeps for it ({@link ScopeKey}). */
|
|
16
|
+
export class Scope {
|
|
17
|
+
/** The SDK's context of the attempt. */
|
|
18
|
+
readonly sdk: restate.ObjectContext | restate.ObjectSharedContext;
|
|
19
|
+
/** Whether its handler has `explicitCancellation: true`. */
|
|
20
|
+
readonly explicitCancellation: boolean;
|
|
21
|
+
/** The definition of the session object whose handler or view it runs, if any. */
|
|
22
|
+
readonly definition: object | undefined;
|
|
23
|
+
readonly [VALUES] = new Map<ScopeKey<unknown>, unknown>();
|
|
24
|
+
|
|
25
|
+
constructor(
|
|
26
|
+
sdk: restate.ObjectContext | restate.ObjectSharedContext,
|
|
27
|
+
{ explicitCancellation = false, definition = undefined as object | undefined } = {},
|
|
28
|
+
) {
|
|
29
|
+
this.sdk = sdk;
|
|
30
|
+
this.explicitCancellation = explicitCancellation;
|
|
31
|
+
this.definition = definition;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The attempt's scope, on its context. */
|
|
36
|
+
const SCOPE = new Link<Scope>('scope');
|
|
37
|
+
|
|
38
|
+
/** `context`, holding `scope`: as it is made, before it is frozen. */
|
|
39
|
+
export const holding = <C extends Context>(context: C, scope: Scope): C => SCOPE.on(context, scope);
|
|
40
|
+
|
|
41
|
+
/** The scope of the attempt whose context `ctx` is, if it is one of @restatedev/sessions. */
|
|
42
|
+
export const scopeOf = (ctx: Context): Scope | undefined => SCOPE.of(ctx);
|
|
43
|
+
|
|
44
|
+
/** A kind of state an attempt's code keeps, by its context: its key in the attempt's scope. */
|
|
45
|
+
export class ScopeKey<T> {
|
|
46
|
+
/** What it is, for an error. */
|
|
47
|
+
private readonly what: string;
|
|
48
|
+
|
|
49
|
+
constructor(what: string) {
|
|
50
|
+
this.what = what;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
get(ctx: Context): T | undefined {
|
|
54
|
+
return this.values(ctx).get(this) as T | undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
set(ctx: Context, value: T): void {
|
|
58
|
+
this.values(ctx).set(this, value);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
delete(ctx: Context): void {
|
|
62
|
+
this.values(ctx).delete(this);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The attempt's, made by `make` the first time. */
|
|
66
|
+
of(ctx: Context, make: () => T): T {
|
|
67
|
+
const values = this.values(ctx);
|
|
68
|
+
if (!values.has(this)) values.set(this, make());
|
|
69
|
+
return values.get(this) as T;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
private values(ctx: Context): Map<ScopeKey<unknown>, unknown> {
|
|
73
|
+
const scope = scopeOf(ctx);
|
|
74
|
+
if (scope === undefined)
|
|
75
|
+
throw new TypeError(`${this.what} takes the context of a session object's handler or view`);
|
|
76
|
+
return scope[VALUES];
|
|
77
|
+
}
|
|
78
|
+
}
|