@restatedev/sessions 0.11.1 → 0.12.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 +330 -178
- package/dist/addon.d.ts +1 -0
- package/dist/addon.d.ts.map +1 -1
- package/dist/addon.js.map +1 -1
- package/dist/calls.d.ts +28 -28
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +25 -25
- package/dist/calls.js.map +1 -1
- package/dist/database.d.ts +90 -166
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +137 -249
- package/dist/database.js.map +1 -1
- package/dist/driver.d.ts +129 -126
- package/dist/driver.d.ts.map +1 -1
- package/dist/driver.js +337 -276
- package/dist/driver.js.map +1 -1
- package/dist/endpoint.d.ts +47 -5
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +175 -60
- package/dist/endpoint.js.map +1 -1
- package/dist/handler.d.ts +20 -17
- package/dist/handler.d.ts.map +1 -1
- package/dist/handler.js +161 -127
- package/dist/handler.js.map +1 -1
- package/dist/host.d.ts +29 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +2 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -26
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +11 -11
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +20 -16
- package/dist/internal.js.map +1 -1
- package/dist/link.d.ts +1 -2
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +4 -5
- package/dist/link.js.map +1 -1
- package/dist/log.d.ts +14 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +21 -0
- package/dist/log.js.map +1 -0
- package/dist/object.d.ts +217 -142
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +195 -241
- package/dist/object.js.map +1 -1
- package/dist/platform.d.ts +0 -1
- package/dist/platform.d.ts.map +1 -1
- package/dist/platform.js +4 -6
- package/dist/platform.js.map +1 -1
- package/dist/schema.d.ts +14 -22
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +31 -69
- package/dist/schema.js.map +1 -1
- package/dist/serve.d.ts +11 -17
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +21 -39
- package/dist/serve.js.map +1 -1
- package/dist/session.d.ts +58 -236
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +206 -513
- package/dist/session.js.map +1 -1
- package/dist/stop.d.ts +59 -0
- package/dist/stop.d.ts.map +1 -0
- package/dist/stop.js +220 -0
- package/dist/stop.js.map +1 -0
- package/dist/vm.d.ts +108 -29
- package/dist/vm.d.ts.map +1 -1
- package/dist/vm.js +43 -10
- package/dist/vm.js.map +1 -1
- package/package.json +4 -4
- package/src/addon.ts +1 -0
- package/src/calls.ts +51 -47
- package/src/database.ts +195 -339
- package/src/driver.ts +379 -315
- package/src/endpoint.ts +217 -62
- package/src/handler.ts +183 -164
- package/src/host.ts +28 -0
- package/src/index.ts +6 -26
- package/src/internal.ts +28 -39
- package/src/link.ts +4 -5
- package/src/log.ts +42 -0
- package/src/object.ts +379 -335
- package/src/platform.ts +4 -6
- package/src/schema.ts +37 -103
- package/src/serve.ts +20 -41
- package/src/session.ts +236 -613
- package/src/stop.ts +225 -0
- package/src/vm.ts +151 -55
- package/dist/scope.d.ts +0 -38
- package/dist/scope.d.ts.map +0 -1
- package/dist/scope.js +0 -55
- package/dist/scope.js.map +0 -1
- package/src/scope.ts +0 -78
package/src/object.ts
CHANGED
|
@@ -1,244 +1,260 @@
|
|
|
1
1
|
// Session objects: Restate virtual objects whose state is a SQL database per
|
|
2
|
-
// key.
|
|
3
|
-
//
|
|
4
|
-
// calls, and nothing else of the SDK's context:
|
|
5
|
-
//
|
|
6
|
-
// const notes = restate.sessionObject({
|
|
7
|
-
// name: 'notes',
|
|
8
|
-
// schema: ['CREATE TABLE notes (text TEXT NOT NULL)'],
|
|
9
|
-
// handlers: {
|
|
10
|
-
// add: async (ctx, text: string) => {
|
|
11
|
-
// await ctx.db.execute('INSERT INTO notes (text) VALUES (?)', [text]);
|
|
12
|
-
// },
|
|
13
|
-
// },
|
|
14
|
-
// views: {
|
|
15
|
-
// list: async (ctx) => ctx.db.query<{ text: string }>('SELECT text FROM notes'),
|
|
16
|
-
// },
|
|
17
|
-
// });
|
|
2
|
+
// key. Handlers run one at a time per key, and views run beside them. Each gets
|
|
3
|
+
// a context with the key, the request, the database and calls.
|
|
18
4
|
import * as restate from '@restatedev/restate-sdk';
|
|
19
|
-
import
|
|
20
|
-
|
|
21
|
-
|
|
5
|
+
import {
|
|
6
|
+
type Duration,
|
|
7
|
+
millisOrDurationToMillis,
|
|
8
|
+
type Serde,
|
|
9
|
+
type VirtualObjectDefinition,
|
|
10
|
+
} from '@restatedev/restate-sdk-core';
|
|
11
|
+
import { type Rpc, rpcOf, type Send, sendOf } from './calls.ts';
|
|
12
|
+
import type { DatabaseReader, Stoppable, Suspendable, Working } from './database.ts';
|
|
22
13
|
import { ensureOf, ensuring, Schema, type Step } from './schema.ts';
|
|
23
14
|
import { patchEndpoint } from './endpoint.ts';
|
|
15
|
+
import type { AttemptDriver } from './driver.ts';
|
|
16
|
+
import type { AttemptHost } from './host.ts';
|
|
24
17
|
import { Link } from './link.ts';
|
|
25
|
-
import {
|
|
26
|
-
import
|
|
18
|
+
import { type Database, Attempt, type ObjectConfig } from './session.ts';
|
|
19
|
+
import type { Scope } from './stop.ts';
|
|
20
|
+
|
|
21
|
+
/** A session object's request: the SDK's, with the number of the attempt, from 1. */
|
|
22
|
+
export type SessionRequest = restate.Request & { readonly attempt: number };
|
|
27
23
|
|
|
28
24
|
/**
|
|
29
|
-
* The context of a session object's handler. A handler runs in attempts
|
|
30
|
-
* Restate starts a new
|
|
31
|
-
*
|
|
32
|
-
*
|
|
25
|
+
* The context of a session object's handler. A handler runs in attempts.
|
|
26
|
+
* Restate starts a new attempt after a crash, a retryable error or a
|
|
27
|
+
* shutdown of the attempt. Each attempt runs the handler from its first
|
|
28
|
+
* line and finds what earlier attempts committed. Operations can be awaited together
|
|
33
29
|
* (`Promise.all`, `Promise.race`).
|
|
34
30
|
*/
|
|
35
31
|
export interface SessionContext {
|
|
36
|
-
/** The session
|
|
32
|
+
/** The key of this session object. */
|
|
37
33
|
readonly key: string;
|
|
38
|
-
/** The request:
|
|
39
|
-
readonly request:
|
|
34
|
+
/** The request: id (the same on every attempt), headers, target, the attempt's number and `attemptCompletedSignal`. */
|
|
35
|
+
readonly request: SessionRequest;
|
|
40
36
|
/**
|
|
41
37
|
* The key's database. Each statement outside a transaction is its own
|
|
42
|
-
* commit, and `db.transaction` groups several
|
|
38
|
+
* commit, and `db.transaction` groups several. A commit is durable when
|
|
43
39
|
* its promise resolves. Calls run one at a time, in call order.
|
|
44
40
|
*/
|
|
45
41
|
readonly db: Database;
|
|
46
42
|
/** Calls, typed (`ctx.rpc(object, key).handler(input)`) or literal. */
|
|
47
43
|
readonly rpc: Rpc;
|
|
48
|
-
/** Sends, made
|
|
44
|
+
/** Sends, made immediately. A transaction's sends (`tx.send`) are made when it commits. */
|
|
49
45
|
readonly send: Send;
|
|
50
|
-
/** Cancel an invocation
|
|
46
|
+
/** Cancel an invocation by its id: see {@link Cancel}. */
|
|
51
47
|
readonly cancel: Cancel;
|
|
52
48
|
/**
|
|
53
|
-
* Run `fn
|
|
54
|
-
* Restate that may outlast Restate's inactivity timeout (a minute
|
|
55
|
-
* default), such as a model
|
|
49
|
+
* Run `fn` and keep the attempt alive while it runs: for work outside
|
|
50
|
+
* Restate that may outlast Restate's inactivity timeout (a minute by
|
|
51
|
+
* default), such as a model request.
|
|
56
52
|
*
|
|
57
53
|
* const reply = await ctx.working(() => model.generate(prompt));
|
|
58
54
|
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
55
|
+
* The work runs to its end. A cancellation reaches the handler as a
|
|
56
|
+
* `CancelledError`: pending `ctx.rpc` results reject with it, or else the
|
|
57
|
+
* next database call or `ctx.rpc` fails with it, before anything is
|
|
58
|
+
* written or sent. `ctx.send` never fails with it. To stop the work
|
|
59
|
+
* itself, use {@link stoppable}.
|
|
60
|
+
*
|
|
61
|
+
* Outside `working`, Restate shuts down an attempt it hears nothing from
|
|
62
|
+
* for that timeout. The attempt suspends on the calls it waits for, and a
|
|
63
|
+
* new attempt runs the handler from the start when one answers (or
|
|
64
|
+
* immediately, if it waits for none). So a wait of days holds no process,
|
|
65
|
+
* and work cut off this way is done again.
|
|
66
|
+
*
|
|
67
|
+
* Inside `working`, the attempt sends a heartbeat whenever it has been
|
|
68
|
+
* silent for a third of the handler's inactivity timeout (20 seconds for
|
|
69
|
+
* the default minute; `RESTATE_SESSIONS_HEARTBEAT`, in milliseconds,
|
|
70
|
+
* overrides it), whatever it waits for.
|
|
71
|
+
* Keep a long wait on Restate (a call, a signal) out of it, or wrap it in
|
|
72
|
+
* {@link suspendable}. Database calls keep the attempt alive by themselves.
|
|
67
73
|
*/
|
|
68
74
|
readonly working: Working;
|
|
75
|
+
/**
|
|
76
|
+
* {@link working}, with a signal that stops the work:
|
|
77
|
+
*
|
|
78
|
+
* const reply = await ctx.stoppable((signal) => model.generate(prompt, { signal }));
|
|
79
|
+
*
|
|
80
|
+
* The signal aborts with the `CancelledError` when Restate cancels the
|
|
81
|
+
* invocation, or with the error that ended the attempt if that comes
|
|
82
|
+
* first. It aborts only once: after a cancellation,
|
|
83
|
+
* `request.attemptCompletedSignal` tells when the attempt ends. A scope
|
|
84
|
+
* opened after either event gets an aborted signal.
|
|
85
|
+
*
|
|
86
|
+
* A cancellation that arrives while a scope is open, or is still owed when
|
|
87
|
+
* one opens, goes to the work through the signal, and not to the next
|
|
88
|
+
* database call or `ctx.rpc`. So the database calls the work makes as it
|
|
89
|
+
* stops are stored.
|
|
90
|
+
*
|
|
91
|
+
* Once a cancellation reaches the handler (through this signal or a failed
|
|
92
|
+
* call), a handler that then fails ends the invocation as cancelled,
|
|
93
|
+
* whatever it threw. One that returns answers it. With
|
|
94
|
+
* `explicitCancellation`, the signal aborts and nothing else happens: the
|
|
95
|
+
* handler decides how it ends.
|
|
96
|
+
*/
|
|
97
|
+
readonly stoppable: Stoppable;
|
|
98
|
+
/**
|
|
99
|
+
* Run `fn` while the {@link working} and {@link stoppable} scopes around
|
|
100
|
+
* the call (at any depth) do not keep the attempt alive, until `fn`
|
|
101
|
+
* settles: for a wait on Restate inside kept-alive work, such as a
|
|
102
|
+
* framework tool that calls another service.
|
|
103
|
+
*
|
|
104
|
+
* await ctx.working(async () => {
|
|
105
|
+
* const order = await model.generate(prompt);
|
|
106
|
+
* return ctx.suspendable(() => ctx.rpc(shop, 'main', { idempotencyKey: ctx.request.id }).place(order));
|
|
107
|
+
* });
|
|
108
|
+
*
|
|
109
|
+
* If no other scope keeps the attempt alive, Restate may suspend it on
|
|
110
|
+
* what it waits for, and run the handler again from its first line when
|
|
111
|
+
* that answers. The work before the `suspendable` is done again, and a
|
|
112
|
+
* call inside it needs an idempotency key to reach the same invocation.
|
|
113
|
+
* Other work in the same scope, running meanwhile, is not kept alive
|
|
114
|
+
* either. A scope opened inside `fn` (a `ctx.working`, a database call)
|
|
115
|
+
* still keeps the attempt alive. Outside any scope, `fn` just runs.
|
|
116
|
+
* Cancellation is unchanged: a call result inside it rejects with the
|
|
117
|
+
* cancellation, and a `stoppable` scope around it gets its signal.
|
|
118
|
+
*/
|
|
119
|
+
readonly suspendable: Suspendable;
|
|
120
|
+
/**
|
|
121
|
+
* Run `fn` inside a span `name`, shown in Restate's UI: the calls, sends and
|
|
122
|
+
* commits it makes are nested under it. It ends with `fn`, with its failure
|
|
123
|
+
* if it throws. On an attempt not served by Restate (a test's), just `fn`.
|
|
124
|
+
* A `db.transaction` opens no span of its own: its commit is inside the
|
|
125
|
+
* span it runs in, if any. To show a transaction as a span, wrap it:
|
|
126
|
+
*
|
|
127
|
+
* await ctx.span('save', () => ctx.db.transaction(async (tx) => { … }));
|
|
128
|
+
*/
|
|
129
|
+
span<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
|
69
130
|
}
|
|
70
131
|
|
|
71
132
|
/**
|
|
72
|
-
* The context of a session object's view
|
|
73
|
-
* reads the database as committed when its invocation started, whatever
|
|
74
|
-
* commit meanwhile. It writes
|
|
75
|
-
* invocation
|
|
133
|
+
* The context of a session object's view. A view runs beside the handlers
|
|
134
|
+
* and reads the database as committed when its invocation started, whatever
|
|
135
|
+
* the handlers commit meanwhile. It writes and sends nothing, but it can
|
|
136
|
+
* cancel an invocation, such as a handler of the same object (a Stop button).
|
|
76
137
|
*/
|
|
77
138
|
export interface ViewContext {
|
|
78
139
|
readonly key: string;
|
|
79
|
-
readonly request:
|
|
140
|
+
readonly request: SessionRequest;
|
|
80
141
|
readonly db: DatabaseReader;
|
|
81
142
|
readonly rpc: Rpc;
|
|
82
143
|
readonly cancel: Cancel;
|
|
83
144
|
}
|
|
84
145
|
|
|
85
146
|
/**
|
|
86
|
-
* Cancel invocation `invocationId` (such as `inv_1f…`), as Restate
|
|
87
|
-
* API does
|
|
88
|
-
* already ended does nothing, so a
|
|
89
|
-
* harmless.
|
|
147
|
+
* Cancel the invocation `invocationId` (such as `inv_1f…`), as the Restate
|
|
148
|
+
* admin API does. The cancel is sent immediately and is not awaited.
|
|
149
|
+
* Cancelling an invocation that already ended does nothing, so a retry that
|
|
150
|
+
* cancels it again is harmless. An `invocationId` that is not an invocation
|
|
151
|
+
* id throws a `TerminalError` (400): nothing is sent, and the handler may
|
|
152
|
+
* catch it and go on.
|
|
90
153
|
*
|
|
91
154
|
* ctx.cancel(turn.invocationId);
|
|
92
155
|
*/
|
|
93
156
|
export type Cancel = (invocationId: string) => void;
|
|
94
157
|
|
|
95
|
-
/** A handler of `C`: its input, if any, annotated. */
|
|
96
158
|
// oxlint-disable-next-line typescript/no-explicit-any
|
|
97
159
|
type Fn<C> = (ctx: C, input: any) => Promise<unknown>;
|
|
98
160
|
|
|
99
|
-
/** The SDK
|
|
161
|
+
/** The SDK handler options (`input`, `output`, `description`, `ingressPrivate`, ...). */
|
|
100
162
|
// oxlint-disable-next-line typescript/no-explicit-any
|
|
101
163
|
export type HandlerOptions = restate.ObjectHandlerOpts<any, any>;
|
|
102
164
|
|
|
103
|
-
/** A handler or a view: a function, or
|
|
165
|
+
/** A handler or a view: a function, or `{ handler, ...options }`. */
|
|
104
166
|
export type Entry<C> = Fn<C> | ({ handler: Fn<C> } & HandlerOptions);
|
|
105
167
|
|
|
106
|
-
/** Each entry's function, as clients see it
|
|
168
|
+
/** Each entry's function, as clients see it. Unknown when the entries are not inferred. */
|
|
107
169
|
type Functions<H> = string extends keyof H ? unknown : { [K in keyof H]: H[K] extends { handler: infer F } ? F : H[K] };
|
|
108
170
|
|
|
109
|
-
/**
|
|
110
|
-
* The key of the object database's head, its first read as it opens:
|
|
111
|
-
* `HEAD_KEY` in the addon's state format
|
|
112
|
-
* (`packages/sessions/native/src/state/format.rs`).
|
|
113
|
-
*/
|
|
171
|
+
/** The state key of the database head, the first read of an open (`HEAD_KEY` in shared-core `src/state/format.rs`). */
|
|
114
172
|
export const HEAD_KEY = 'v22/head';
|
|
115
173
|
|
|
116
|
-
/**
|
|
117
|
-
* The options every session object has: an invocation starts with the
|
|
118
|
-
* database's head only, not with every page. The rest of the database it
|
|
119
|
-
* reads as it needs it: its tail entries and packs change keys with each
|
|
120
|
-
* flush, so only the head can be named.
|
|
121
|
-
*/
|
|
174
|
+
/** Preload only the database head: tail and pack keys change with each flush. */
|
|
122
175
|
export const sqlOptions = { state: { preload: [HEAD_KEY] } } satisfies restate.ObjectOptions;
|
|
123
176
|
|
|
124
177
|
/**
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
178
|
+
* Marks a session object's handlers for discovery: they are on the explicit
|
|
179
|
+
* recovery protocol (`protocolFamily` in manifest v6, endpoint.ts). The
|
|
180
|
+
* database's actions are recorded as nothing, so Restate's UI shows none of
|
|
181
|
+
* its pages.
|
|
128
182
|
*/
|
|
129
|
-
export const
|
|
130
|
-
'dev.restate.tooling.journal.hidden.names': 'sync',
|
|
131
|
-
'dev.restate.tooling.journal.hidden.name.prefix': 'v22/',
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
// The handler options of every handler: explicit recovery, which runs a
|
|
135
|
-
// retried attempt from the start, since a later attempt makes different
|
|
136
|
-
// reads than a replayed journal would have.
|
|
137
|
-
export const recovery = () => restate.internal.explicitRecovery();
|
|
138
|
-
|
|
139
|
-
/** The SDK's runtime context, as far as the session needs it beyond its public type. */
|
|
140
|
-
type Runtime = { invocationEndPromise: SqlHost['invocationEndPromise']; defaultSerde: SqlHost['defaultSerde'] };
|
|
141
|
-
|
|
142
|
-
/** What an attempt needs of the SDK's context: a test's fake has these. */
|
|
143
|
-
export type AttemptContext = Pick<
|
|
144
|
-
restate.ObjectContext,
|
|
145
|
-
'key' | 'request' | 'get' | 'set' | 'clear' | 'stateKeys' | 'run' | 'genericSend' | 'genericCall' | 'invocation'
|
|
146
|
-
> &
|
|
147
|
-
Runtime;
|
|
148
|
-
|
|
149
|
-
/** What an attempt's session needs of the SDK's context `ctx`. */
|
|
150
|
-
export function host(
|
|
151
|
-
ctx: restate.ObjectContext | restate.ObjectSharedContext | AttemptContext,
|
|
152
|
-
shared: boolean,
|
|
153
|
-
): SqlHost {
|
|
154
|
-
const runtime = ctx as unknown as Runtime;
|
|
155
|
-
const exclusive = ctx as restate.ObjectContext;
|
|
156
|
-
return {
|
|
157
|
-
shared,
|
|
158
|
-
key: ctx.key,
|
|
159
|
-
invocationEndPromise: runtime.invocationEndPromise,
|
|
160
|
-
defaultSerde: runtime.defaultSerde,
|
|
161
|
-
request: () => ctx.request(),
|
|
162
|
-
get: (name, serde, entry) => ctx.get(name, serde, entry),
|
|
163
|
-
set: (name, value, serde, entry) => exclusive.set(name, value, serde, entry),
|
|
164
|
-
clear: (name, entry) => exclusive.clear(name, entry),
|
|
165
|
-
stateKeys: () => ctx.stateKeys(),
|
|
166
|
-
run: (name, action) => exclusive.run(name, action),
|
|
167
|
-
vm: (ctx as { vm?: SqlHost['vm'] }).vm,
|
|
168
|
-
takeCancellation: (ctx as { takeCancellation?: SqlHost['takeCancellation'] }).takeCancellation,
|
|
169
|
-
working: workingOf(ctx),
|
|
170
|
-
genericSend: (send) => ctx.genericSend(send),
|
|
171
|
-
};
|
|
172
|
-
}
|
|
183
|
+
export const PROTOCOL_FAMILY = 'EXPLICIT_RECOVERY';
|
|
173
184
|
|
|
174
|
-
/** A session object's: its config, which its attempts get, and its definition, once made. */
|
|
175
185
|
interface ObjectState {
|
|
176
186
|
readonly config: ObjectConfig;
|
|
177
|
-
definition?: object;
|
|
178
187
|
}
|
|
179
188
|
|
|
180
|
-
/** A handler or view of a session object: its function, kind, serdes, and object. */
|
|
181
189
|
interface HandlerEntry {
|
|
182
190
|
fn: Fn<never>;
|
|
183
191
|
view: boolean;
|
|
192
|
+
/** The entry's own SDK options (`{ handler, ...options }`), and its object's. */
|
|
193
|
+
options: HandlerOptions;
|
|
194
|
+
objectOptions: restate.ObjectOptions | undefined;
|
|
195
|
+
object: ObjectState;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* What an attempt of an entry runs with: its options resolved as the SDK
|
|
200
|
+
* resolves a handler's (`createExecutionOptions`, `registerHandlerIO` and
|
|
201
|
+
* discovery in the SDK's `endpoint/components.js`), the handler's own first,
|
|
202
|
+
* then its object's, then the endpoint's default service options.
|
|
203
|
+
*/
|
|
204
|
+
export interface ResolvedEntry {
|
|
205
|
+
view: boolean;
|
|
206
|
+
/** `explicitCancellation`. */
|
|
184
207
|
explicit: boolean;
|
|
185
|
-
/**
|
|
208
|
+
/** `serde`: what `input` and `output` default to, and the typed clients' calls and sends. */
|
|
209
|
+
defaultSerde: Serde<unknown>;
|
|
186
210
|
inputSerde: Serde<unknown>;
|
|
187
211
|
outputSerde: Serde<unknown>;
|
|
188
|
-
/**
|
|
189
|
-
asTerminalError?: (error: unknown) =>
|
|
190
|
-
object
|
|
212
|
+
/** Which errors end the invocation instead of being retried. */
|
|
213
|
+
asTerminalError?: (error: unknown) => restate.TerminalError | undefined;
|
|
214
|
+
/** The object's hooks (else the endpoint's default), then the handler's. */
|
|
215
|
+
hooks: readonly restate.HooksProvider[];
|
|
216
|
+
/** Restate's inactivity timeout, in milliseconds, as the handler, else its object, else the endpoint's defaults set it. */
|
|
217
|
+
inactivityTimeoutMs?: number;
|
|
191
218
|
}
|
|
192
219
|
|
|
193
220
|
/**
|
|
194
|
-
*
|
|
195
|
-
*
|
|
221
|
+
* What {@link serveSession} needs to run entry `name`, if `definition` is a
|
|
222
|
+
* session object, on an endpoint whose default service options are
|
|
223
|
+
* `defaults`.
|
|
196
224
|
*/
|
|
197
225
|
export function handlerEntry(
|
|
198
226
|
definition: object,
|
|
199
227
|
name: string,
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
view: boolean;
|
|
203
|
-
explicit: boolean;
|
|
204
|
-
inputSerde: Serde<unknown>;
|
|
205
|
-
outputSerde: Serde<unknown>;
|
|
206
|
-
asTerminalError?: (error: unknown) => Error | undefined;
|
|
207
|
-
}
|
|
208
|
-
| undefined {
|
|
228
|
+
defaults: restate.DefaultServiceOptions = {},
|
|
229
|
+
): ResolvedEntry | undefined {
|
|
209
230
|
const entry = OBJECT.of(definition)?.entries.get(name);
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
231
|
+
return entry === undefined ? undefined : resolved(entry, defaults);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function resolved({ view, options: h, objectOptions }: HandlerEntry, defaults: restate.DefaultServiceOptions) {
|
|
235
|
+
const o: restate.ObjectOptions = { ...defaults, ...objectOptions };
|
|
236
|
+
const defaultSerde = (h.serde ?? o.serde ?? restate.serde.json) as Serde<unknown>;
|
|
237
|
+
const asTerminalError = h.asTerminalError ?? o.asTerminalError;
|
|
238
|
+
return {
|
|
239
|
+
view,
|
|
240
|
+
explicit: (h.explicitCancellation ?? o.explicitCancellation) === true,
|
|
241
|
+
defaultSerde,
|
|
242
|
+
inputSerde: (h.input as Serde<unknown> | undefined) ?? defaultSerde,
|
|
243
|
+
outputSerde: (h.output as Serde<unknown> | undefined) ?? defaultSerde,
|
|
244
|
+
...(asTerminalError !== undefined ? { asTerminalError } : {}),
|
|
245
|
+
hooks: [...(o.hooks ?? []), ...(h.hooks ?? [])],
|
|
246
|
+
inactivityTimeoutMs: timeoutMs(h.inactivityTimeout ?? o.inactivityTimeout),
|
|
247
|
+
} satisfies ResolvedEntry;
|
|
213
248
|
}
|
|
214
249
|
|
|
215
|
-
/** Whether `definition` is a session object: it has handlers this package runs. */
|
|
216
250
|
export const isSessionObject = (definition: object): boolean => OBJECT.of(definition) !== undefined;
|
|
217
251
|
|
|
218
|
-
/** A session object's own, on its definition: for {@link invoke} and {@link withStoreWrapper}. */
|
|
219
252
|
const OBJECT = new Link<{ object: ObjectState; entries: Map<string, HandlerEntry> }>('a session object');
|
|
220
253
|
|
|
221
|
-
/**
|
|
222
|
-
* The definition (`sessionObject`'s) of the object whose handler or view
|
|
223
|
-
* `ctx` is the context of: what a library keeps per object lives on it.
|
|
224
|
-
*/
|
|
225
|
-
export const definitionOf = (ctx: SessionContext | ViewContext): object | undefined => scopeOf(ctx)?.definition;
|
|
226
|
-
|
|
227
|
-
/** What `definition`'s attempts get, if it is a session object: for a test's attempts of its own. */
|
|
254
|
+
/** For tests that run attempts without Restate. */
|
|
228
255
|
export const configOf = (definition: object): ObjectConfig | undefined => OBJECT.of(definition)?.object.config;
|
|
229
256
|
|
|
230
|
-
/**
|
|
231
|
-
* Wrap the stores of `definition`'s attempts with `wrap`: fault injection, in
|
|
232
|
-
* tests. A definition that is no session object has no store: it is left as
|
|
233
|
-
* it is.
|
|
234
|
-
*/
|
|
235
|
-
export function withStoreWrapper<D extends object>(definition: D, wrapper: (store: Store) => Store): D {
|
|
236
|
-
const object = OBJECT.of(definition);
|
|
237
|
-
if (object !== undefined) object.object.config.wrapStore = wrapper;
|
|
238
|
-
return definition;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
/** The reads of `db`, which apply a library's schema as `db` does (`Schema.ensure`). */
|
|
257
|
+
/** The reads of `db`, keeping its `Schema.ensure` support. */
|
|
242
258
|
function readerOf(db: Database): DatabaseReader {
|
|
243
259
|
const reader: DatabaseReader = {
|
|
244
260
|
query: (sql, params) => db.query(sql, params),
|
|
@@ -249,83 +265,86 @@ function readerOf(db: Database): DatabaseReader {
|
|
|
249
265
|
return Object.freeze(ensure ? ensuring(reader, ensure) : reader);
|
|
250
266
|
}
|
|
251
267
|
|
|
252
|
-
/**
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
export function contextOf(
|
|
260
|
-
|
|
261
|
-
db: Database,
|
|
262
|
-
options?: { view?: false; explicitCancellation?: boolean; definition?: object },
|
|
263
|
-
): SessionContext;
|
|
268
|
+
/** What {@link contextOf} takes beside its host and database. */
|
|
269
|
+
interface ContextOptions {
|
|
270
|
+
/** The serde of a typed client's calls and sends to a handler that declares none: the `serde` option, JSON by default. */
|
|
271
|
+
serde?: Serde<unknown>;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The context of a handler (or, with `view`, of a view) over `host`. Tests use it too. */
|
|
275
|
+
export function contextOf(host: AttemptHost, db: Database, options: { view: true } & ContextOptions): ViewContext;
|
|
276
|
+
export function contextOf(host: AttemptHost, db: Database, options?: { view?: false } & ContextOptions): SessionContext;
|
|
264
277
|
export function contextOf(
|
|
265
|
-
|
|
278
|
+
host: AttemptHost,
|
|
266
279
|
db: Database,
|
|
267
|
-
{
|
|
268
|
-
view = false,
|
|
269
|
-
explicitCancellation = false,
|
|
270
|
-
definition,
|
|
271
|
-
}: { view?: boolean; explicitCancellation?: boolean; definition?: object } = {},
|
|
280
|
+
{ view = false, serde }: { view?: boolean } & ContextOptions = {},
|
|
272
281
|
): SessionContext | ViewContext {
|
|
273
|
-
const
|
|
274
|
-
const
|
|
275
|
-
//
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
);
|
|
292
|
-
return Object.freeze(context);
|
|
282
|
+
const { key, request, stop } = host;
|
|
283
|
+
const rpc = rpcOf((call) => host.call(call), serde);
|
|
284
|
+
// An id that is not one throws a TerminalError (400): the VM checks it as Restate parses it.
|
|
285
|
+
const cancel: Cancel = (invocationId) => host.cancel(invocationId);
|
|
286
|
+
if (view) return Object.freeze(HOST.on({ key, request, db: readerOf(db), rpc, cancel }, host));
|
|
287
|
+
const context: SessionContext = {
|
|
288
|
+
key,
|
|
289
|
+
request,
|
|
290
|
+
db,
|
|
291
|
+
rpc,
|
|
292
|
+
send: sendOf((send) => host.send(send), serde),
|
|
293
|
+
cancel,
|
|
294
|
+
working: (fn) => stop.working(fn),
|
|
295
|
+
stoppable: (fn) => stop.stoppable(fn),
|
|
296
|
+
suspendable: (fn) => stop.suspendable(fn),
|
|
297
|
+
span: (name, fn) => (host.driver === undefined ? fn() : host.driver.inSpan(name, fn)),
|
|
298
|
+
};
|
|
299
|
+
return Object.freeze(HOST.on(context, host));
|
|
293
300
|
}
|
|
294
301
|
|
|
295
|
-
/** The
|
|
296
|
-
const
|
|
302
|
+
/** The attempt behind a handler's or a view's context: for {@link openScope} and the protocol's additions below. */
|
|
303
|
+
const HOST = new Link<AttemptHost>('a session object’s context');
|
|
297
304
|
|
|
298
|
-
/**
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
305
|
+
/**
|
|
306
|
+
* Open a `ctx.stoppable` scope until `scope.release()`, for framework hooks. A
|
|
307
|
+
* `pinned` scope is not paused by `ctx.suspendable`: for a framework whose next
|
|
308
|
+
* attempt would lose the result of work suspended inside it.
|
|
309
|
+
*/
|
|
310
|
+
export function openScope(ctx: SessionContext, { pinned = false }: { pinned?: boolean } = {}): Scope {
|
|
311
|
+
const host = HOST.of(ctx);
|
|
312
|
+
if (host === undefined || !('working' in ctx)) throw new TypeError("openScope takes a handler's context");
|
|
313
|
+
return host.stop.open({ stoppable: true, pinned });
|
|
314
|
+
}
|
|
306
315
|
|
|
307
|
-
/**
|
|
308
|
-
|
|
309
|
-
|
|
316
|
+
/**
|
|
317
|
+
* Run `handler`, then end `session`. A handler that fails after the
|
|
318
|
+
* cancellation was delivered fails with `CancelledError`, decided when the
|
|
319
|
+
* handler settles, not after the session is saved.
|
|
320
|
+
*/
|
|
321
|
+
export async function withAttempt<T>(
|
|
322
|
+
handler: () => Promise<T>,
|
|
323
|
+
session: Attempt,
|
|
324
|
+
stop: AttemptHost['stop'],
|
|
325
|
+
): Promise<T> {
|
|
326
|
+
let value: T;
|
|
327
|
+
try {
|
|
328
|
+
value = await handler();
|
|
329
|
+
} catch (error) {
|
|
330
|
+
return session.end({ error: stop.cancelled ? new restate.CancelledError() : error });
|
|
331
|
+
}
|
|
332
|
+
return session.end({ value });
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function attempt(entry: HandlerEntry, host: AttemptHost, input: unknown, run: ResolvedEntry): Promise<unknown> {
|
|
336
|
+
const { fn, view, object } = entry;
|
|
337
|
+
const { defaultSerde: serde } = run;
|
|
338
|
+
const session = new Attempt(host, view, { ...object.config, serde });
|
|
310
339
|
session.openNow();
|
|
311
|
-
const {
|
|
312
|
-
|
|
313
|
-
? contextOf(ctx, session.db, { view: true, definition })
|
|
314
|
-
: contextOf(ctx, session.db, { explicitCancellation: explicit, definition });
|
|
315
|
-
return withAttempt(() => fn(context as never, input as never), session);
|
|
340
|
+
const context = view ? contextOf(host, session.db, { view: true, serde }) : contextOf(host, session.db, { serde });
|
|
341
|
+
return withAttempt(async () => fn(context as never, input), session, host.stop);
|
|
316
342
|
}
|
|
317
343
|
|
|
318
344
|
/**
|
|
319
|
-
*
|
|
320
|
-
*
|
|
321
|
-
*
|
|
322
|
-
* `restate.endpoint()`, `restate.serve` and `connect`'s tunnel alike.
|
|
323
|
-
*
|
|
324
|
-
* Reaching here means the endpoint is one the patch does not cover, a fetch
|
|
325
|
-
* endpoint being the one that exists. A session object cannot run on the
|
|
326
|
-
* SDK's journaled VM: it is never replayed, and awaiting two things at once
|
|
327
|
-
* fails the attempt with `awaitNext already pending`. So it is refused, rather
|
|
328
|
-
* than half-served.
|
|
345
|
+
* The SDK handler of an entry, reached only on an endpoint the patch in
|
|
346
|
+
* endpoint.ts does not cover (a fetch endpoint). It refuses: a session object
|
|
347
|
+
* cannot run on the journaled SDK VM.
|
|
329
348
|
*/
|
|
330
349
|
function wrap(objectName: string, name: string) {
|
|
331
350
|
return () => {
|
|
@@ -339,20 +358,55 @@ function wrap(objectName: string, name: string) {
|
|
|
339
358
|
}
|
|
340
359
|
|
|
341
360
|
/**
|
|
342
|
-
* Run
|
|
343
|
-
*
|
|
361
|
+
* Run entry `name` of `definition` for one attempt over `host`: from
|
|
362
|
+
* handler.ts, with its options as {@link handlerEntry} resolved them on the
|
|
363
|
+
* endpoint, or from a test.
|
|
344
364
|
*/
|
|
345
|
-
export function invoke(
|
|
365
|
+
export function invoke(
|
|
366
|
+
definition: { name: string },
|
|
367
|
+
name: string,
|
|
368
|
+
host: AttemptHost,
|
|
369
|
+
input?: unknown,
|
|
370
|
+
run?: ResolvedEntry,
|
|
371
|
+
) {
|
|
346
372
|
const entry = OBJECT.of(definition)?.entries.get(name);
|
|
347
373
|
if (entry === undefined) throw new Error(`${definition.name}.${name} is no handler or view of a session object`);
|
|
348
|
-
return attempt(entry,
|
|
374
|
+
return attempt(entry, host, input, run ?? resolved(entry, {}));
|
|
349
375
|
}
|
|
350
376
|
|
|
351
|
-
/** Whether `value` is a handler of the SDK's already. */
|
|
352
377
|
const isSdkHandler = (value: object) => Object.getOwnPropertySymbols(value).some((s) => s.description === 'Handler');
|
|
353
378
|
|
|
354
|
-
/**
|
|
355
|
-
|
|
379
|
+
/** An inactivity timeout of the SDK's options, in milliseconds. */
|
|
380
|
+
const timeoutMs = (timeout: Duration | number | undefined) =>
|
|
381
|
+
timeout === undefined ? undefined : millisOrDurationToMillis(timeout);
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* The SDK options a session object refuses, where `options` sets them: the
|
|
385
|
+
* state options, which it sets itself (the database owns the state), and
|
|
386
|
+
* `onJournalMismatchErrors`, which has nothing to act on (an attempt is never
|
|
387
|
+
* replayed, so no journal mismatches).
|
|
388
|
+
*/
|
|
389
|
+
export function refuseOptions(where: string, options: object | undefined): void {
|
|
390
|
+
if (options === undefined) return;
|
|
391
|
+
if ('state' in options || 'enableLazyState' in options) {
|
|
392
|
+
throw new Error(`${where}: a session object sets its state options itself: leave out state and enableLazyState`);
|
|
393
|
+
}
|
|
394
|
+
if ('onJournalMismatchErrors' in options) {
|
|
395
|
+
throw new Error(
|
|
396
|
+
`${where}: onJournalMismatchErrors is not supported for session objects: their attempts are never replayed, ` +
|
|
397
|
+
'so there is no journal to mismatch',
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function handlerOf(
|
|
403
|
+
objectName: string,
|
|
404
|
+
name: string,
|
|
405
|
+
entry: unknown,
|
|
406
|
+
view: boolean,
|
|
407
|
+
object: ObjectState,
|
|
408
|
+
objectOptions: restate.ObjectOptions | undefined,
|
|
409
|
+
) {
|
|
356
410
|
const [fn, options] =
|
|
357
411
|
typeof entry === 'function'
|
|
358
412
|
? [entry, {}]
|
|
@@ -370,22 +424,9 @@ function handlerOf(objectName: string, name: string, entry: unknown, view: boole
|
|
|
370
424
|
'Put journaled work in a restate.object, service or workflow, and call it with ctx.rpc',
|
|
371
425
|
);
|
|
372
426
|
}
|
|
373
|
-
|
|
374
|
-
const
|
|
375
|
-
const
|
|
376
|
-
input?: Serde<unknown>;
|
|
377
|
-
output?: Serde<unknown>;
|
|
378
|
-
asTerminalError?: (error: unknown) => Error | undefined;
|
|
379
|
-
};
|
|
380
|
-
const made: HandlerEntry = {
|
|
381
|
-
fn: fn as Fn<never>,
|
|
382
|
-
view,
|
|
383
|
-
explicit,
|
|
384
|
-
inputSerde: serdes.input ?? (restate.serde.json as Serde<unknown>),
|
|
385
|
-
outputSerde: serdes.output ?? (restate.serde.json as Serde<unknown>),
|
|
386
|
-
asTerminalError: serdes.asTerminalError,
|
|
387
|
-
object,
|
|
388
|
-
};
|
|
427
|
+
refuseOptions(`${objectName}.${name}`, options);
|
|
428
|
+
const opts = { ...options } as HandlerOptions;
|
|
429
|
+
const made: HandlerEntry = { fn: fn as Fn<never>, view, options: opts, objectOptions, object };
|
|
389
430
|
const sdk = wrap(objectName, name) as never;
|
|
390
431
|
const handler = view ? restate.handlers.object.shared(opts, sdk) : restate.handlers.object.exclusive(opts, sdk);
|
|
391
432
|
return { handler, entry: made };
|
|
@@ -395,16 +436,27 @@ function handlerOf(objectName: string, name: string, entry: unknown, view: boole
|
|
|
395
436
|
* A virtual object whose state is a SQL database per key.
|
|
396
437
|
*
|
|
397
438
|
* - `schema`: the steps that make each key's database, in order, applied
|
|
398
|
-
* once per key
|
|
399
|
-
*
|
|
400
|
-
* - `
|
|
401
|
-
*
|
|
402
|
-
* - `views`: they run beside the handlers, each with a {@link ViewContext}:
|
|
403
|
-
* they read, and write nothing.
|
|
439
|
+
* once per key. A step that ran never changes: a change is a new step.
|
|
440
|
+
* - `handlers`: run one at a time per key, each with a {@link SessionContext}.
|
|
441
|
+
* - `views`: run beside the handlers, each with a {@link ViewContext}. They
|
|
442
|
+
* only read.
|
|
404
443
|
*
|
|
405
|
-
* Each is a function, or `{ handler, ...options }` with
|
|
444
|
+
* Each entry is a function, or `{ handler, ...options }` with SDK handler
|
|
406
445
|
* options. A name is a handler or a view, not both. `description`,
|
|
407
|
-
* `metadata` and `options` are the SDK
|
|
446
|
+
* `metadata` and `options` are the SDK object fields.
|
|
447
|
+
*
|
|
448
|
+
* const notes = restate.sessionObject({
|
|
449
|
+
* name: 'notes',
|
|
450
|
+
* schema: ['CREATE TABLE notes (text TEXT NOT NULL)'],
|
|
451
|
+
* handlers: {
|
|
452
|
+
* add: async (ctx, text: string) => {
|
|
453
|
+
* await ctx.db.execute('INSERT INTO notes (text) VALUES (?)', [text]);
|
|
454
|
+
* },
|
|
455
|
+
* },
|
|
456
|
+
* views: {
|
|
457
|
+
* list: async (ctx) => ctx.db.query<{ text: string }>('SELECT text FROM notes'),
|
|
458
|
+
* },
|
|
459
|
+
* });
|
|
408
460
|
*/
|
|
409
461
|
export function sessionObject<
|
|
410
462
|
P extends string,
|
|
@@ -420,17 +472,12 @@ export function sessionObject<
|
|
|
420
472
|
metadata?: Record<string, string>;
|
|
421
473
|
options?: restate.ObjectOptions;
|
|
422
474
|
}): VirtualObjectDefinition<P, Functions<H> & Functions<V>> {
|
|
423
|
-
//
|
|
424
|
-
// invocations to the explicit recovery VM (`endpoint.ts`). Installed here
|
|
425
|
-
// rather than on import: the package declares `sideEffects: false`.
|
|
475
|
+
// Here rather than on import, because the package declares `sideEffects: false` (see endpoint.ts).
|
|
426
476
|
patchEndpoint();
|
|
427
477
|
const { name, schema, handlers = {}, views = {}, description, metadata, options } = definition;
|
|
428
478
|
const both = Object.keys(handlers).filter((key) => key in views);
|
|
429
479
|
if (both.length > 0) throw new Error(`${name}: ${both.join(', ')} is a handler and a view: name one otherwise`);
|
|
430
|
-
|
|
431
|
-
if (options && ('state' in options || 'enableLazyState' in options)) {
|
|
432
|
-
throw new Error(`${name}: a session object sets its state options itself: leave out state and enableLazyState`);
|
|
433
|
-
}
|
|
480
|
+
refuseOptions(name, options);
|
|
434
481
|
const object: ObjectState = { config: { schema: schema ? new Schema(name, schema) : undefined } };
|
|
435
482
|
const sdkHandlers: Record<string, (ctx: restate.ObjectContext, input?: unknown) => Promise<unknown>> = {};
|
|
436
483
|
const entries = new Map<string, HandlerEntry>();
|
|
@@ -439,7 +486,7 @@ export function sessionObject<
|
|
|
439
486
|
[true, views],
|
|
440
487
|
] as const) {
|
|
441
488
|
for (const [key, value] of Object.entries(map)) {
|
|
442
|
-
const { handler, entry } = handlerOf(name, key, value, view, object);
|
|
489
|
+
const { handler, entry } = handlerOf(name, key, value, view, object, options);
|
|
443
490
|
sdkHandlers[key] = handler;
|
|
444
491
|
entries.set(key, entry);
|
|
445
492
|
}
|
|
@@ -448,99 +495,96 @@ export function sessionObject<
|
|
|
448
495
|
name,
|
|
449
496
|
description,
|
|
450
497
|
handlers: sdkHandlers,
|
|
451
|
-
metadata
|
|
498
|
+
...(metadata !== undefined ? { metadata } : {}),
|
|
452
499
|
options: { ...sqlOptions, ...options },
|
|
453
500
|
});
|
|
454
|
-
object.definition = made;
|
|
455
501
|
OBJECT.on(made, { object, entries });
|
|
456
502
|
return made;
|
|
457
503
|
}
|
|
458
504
|
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
505
|
+
// --- What the explicit recovery protocol adds, for libraries (provisional:
|
|
506
|
+
// the user-facing shape is still to design). Each works from a handler's or a
|
|
507
|
+
// view's context of an attempt on the VM, and throws a TerminalError from any
|
|
508
|
+
// other. `readSignal` is a wait on Restate as a `ctx.rpc` is: an owed
|
|
509
|
+
// cancellation fails it before it is made, and one that arrives while it waits
|
|
510
|
+
// rejects it (see stop.ts). The invocation state's reads (`get`, `keys`) and
|
|
511
|
+
// `flush` are the session's own waits: a cancellation neither refuses nor
|
|
512
|
+
// rejects them.
|
|
513
|
+
|
|
514
|
+
/** The VM's driver of the attempt whose context `ctx` is. */
|
|
515
|
+
function driverOf(ctx: SessionContext | ViewContext, of: string): AttemptDriver {
|
|
516
|
+
const driver = HOST.of(ctx)?.driver;
|
|
517
|
+
if (driver === undefined) throw new restate.TerminalError(`${of} takes the context of an attempt served by Restate`);
|
|
518
|
+
return driver;
|
|
464
519
|
}
|
|
465
520
|
|
|
466
521
|
/**
|
|
467
|
-
*
|
|
468
|
-
*
|
|
469
|
-
*
|
|
470
|
-
*
|
|
471
|
-
* attempt cancels this one too, as a send's would not be.
|
|
472
|
-
*
|
|
473
|
-
* Its result is left as it comes. A call of a workflow's `run` whose run of
|
|
474
|
-
* that id started already fails ("the workflow method was already
|
|
475
|
-
* invoked"), whatever its idempotency key, but its invocation id is that
|
|
476
|
-
* run's: so a new attempt that calls again gets the id of the run an
|
|
477
|
-
* earlier one started, and its `cancelCalls` cancels that run.
|
|
522
|
+
* The invocation's own state: every attempt of the invocation finds it, no
|
|
523
|
+
* other invocation does, and it ends with the invocation. Bytes only. For
|
|
524
|
+
* progress a handler must find again on its next attempt (what it already
|
|
525
|
+
* did), apart from the object's database.
|
|
478
526
|
*/
|
|
479
|
-
export
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
parameter: input,
|
|
486
|
-
inputSerde: inputSerde ?? restate.serde.json,
|
|
487
|
-
outputSerde: restate.serde.binary,
|
|
488
|
-
idempotencyKey,
|
|
489
|
-
headers,
|
|
490
|
-
});
|
|
491
|
-
return String(await called.invocationId);
|
|
527
|
+
export interface InvocationState {
|
|
528
|
+
get(key: string): Promise<Uint8Array | null>;
|
|
529
|
+
set(key: string, value: Uint8Array): void;
|
|
530
|
+
clear(key: string): void;
|
|
531
|
+
clearAll(): void;
|
|
532
|
+
keys(): Promise<string[]>;
|
|
492
533
|
}
|
|
493
534
|
|
|
494
|
-
/**
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
*/
|
|
499
|
-
export function attach<O = unknown>(
|
|
500
|
-
ctx: SessionContext,
|
|
501
|
-
invocationId: string,
|
|
502
|
-
outputSerde: Serde<O> = restate.serde.json as Serde<O>,
|
|
503
|
-
): Promise<O> {
|
|
504
|
-
const { sdk } = scopeOfHandler(ctx, 'attach');
|
|
505
|
-
return sdk.invocation(restate.InvocationIdParser.fromString(invocationId)).attach(outputSerde);
|
|
535
|
+
/** Throws a TerminalError if `ctx` is a view's: a view writes and sends nothing. */
|
|
536
|
+
function refusedInView(ctx: SessionContext | ViewContext, of: string): void {
|
|
537
|
+
if (!('working' in ctx))
|
|
538
|
+
throw new restate.TerminalError(`${of} takes a handler's context: a view writes and sends nothing`);
|
|
506
539
|
}
|
|
507
540
|
|
|
508
|
-
/**
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
541
|
+
/**
|
|
542
|
+
* The invocation state of the invocation whose context `ctx` is: see
|
|
543
|
+
* {@link InvocationState}. A view's reads it; its writes throw a TerminalError.
|
|
544
|
+
*/
|
|
545
|
+
export function invocationState(ctx: SessionContext | ViewContext): InvocationState {
|
|
546
|
+
const view = !('working' in ctx);
|
|
547
|
+
const writes = (of: string) => {
|
|
548
|
+
if (view) refusedInView(ctx, `invocationState(ctx).${of}`);
|
|
549
|
+
};
|
|
550
|
+
const driver = driverOf(ctx, 'invocationState');
|
|
551
|
+
return {
|
|
552
|
+
get: (key) => driver.stateGet('invocation', key),
|
|
553
|
+
set: (key, value) => (writes('set'), driver.stateSet('invocation', key, value)),
|
|
554
|
+
clear: (key) => (writes('clear'), driver.stateClear('invocation', key)),
|
|
555
|
+
clearAll: () => (writes('clearAll'), driver.stateClearAll('invocation')),
|
|
556
|
+
keys: () => driver.stateKeys('invocation'),
|
|
557
|
+
};
|
|
515
558
|
}
|
|
516
559
|
|
|
517
560
|
/**
|
|
518
|
-
*
|
|
519
|
-
*
|
|
520
|
-
*
|
|
521
|
-
*
|
|
522
|
-
*
|
|
523
|
-
*
|
|
524
|
-
* (a heartbeat, in `ctx.working`, tells Restate the attempt makes progress
|
|
525
|
-
* instead). The cancel signal comes while Restate keeps
|
|
526
|
-
* the invocation's input open. Once Restate closed it (the handler sent and
|
|
527
|
-
* got nothing for the inactivity timeout), a cancellation resolves this at
|
|
528
|
-
* the handler's next await of Restate's, which suspends the invocation and
|
|
529
|
-
* resumes it at once, or not at all if it awaits nothing more.
|
|
530
|
-
*
|
|
531
|
-
* So it is not a way to park a handler until it is cancelled. One that
|
|
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.
|
|
561
|
+
* The `index`-th signal named `name` (from 0) the invocation of `ctx`
|
|
562
|
+
* received: its payload, `null` if it carries nothing, or a TerminalError if
|
|
563
|
+
* it carries a failure. It waits for it: an attempt shut down meanwhile
|
|
564
|
+
* suspends, and the signal's arrival wakes the invocation. The caller keeps
|
|
565
|
+
* the index. A signal is sent through Restate's admin API
|
|
566
|
+
* (`POST /invocations/<id>/signals/<name>`) or {@link sendSignal}.
|
|
535
567
|
*/
|
|
536
|
-
export
|
|
537
|
-
|
|
538
|
-
}
|
|
568
|
+
export function readSignal(ctx: SessionContext | ViewContext, name: string, index = 0): Promise<Uint8Array | null> {
|
|
569
|
+
return driverOf(ctx, 'readSignal').signalRead(name, index);
|
|
570
|
+
}
|
|
539
571
|
|
|
540
572
|
/**
|
|
541
|
-
*
|
|
542
|
-
*
|
|
573
|
+
* Send the signal `name` to invocation `invocationId`, with `value`, a
|
|
574
|
+
* failure, or nothing. An `invocationId` that is not an invocation id throws a
|
|
575
|
+
* `TerminalError` (400): nothing is sent, and the handler may catch it.
|
|
543
576
|
*/
|
|
544
|
-
export
|
|
545
|
-
|
|
546
|
-
|
|
577
|
+
export function sendSignal(
|
|
578
|
+
ctx: SessionContext | ViewContext,
|
|
579
|
+
invocationId: string,
|
|
580
|
+
name: string,
|
|
581
|
+
value?: Uint8Array | restate.TerminalError,
|
|
582
|
+
): void {
|
|
583
|
+
refusedInView(ctx, 'sendSignal');
|
|
584
|
+
driverOf(ctx, 'sendSignal').signalSend(invocationId, name, value);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** Resolves once every action the attempt of `ctx` made before it is applied by Restate. */
|
|
588
|
+
export function flush(ctx: SessionContext | ViewContext): Promise<void> {
|
|
589
|
+
return driverOf(ctx, 'flush').flushActions();
|
|
590
|
+
}
|