@restatedev/sessions 0.0.0 → 0.2.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/LICENSE +21 -0
- package/README.md +480 -2
- package/dist/calls.d.ts +72 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/calls.js +86 -0
- package/dist/calls.js.map +1 -0
- package/dist/database.d.ts +169 -0
- package/dist/database.d.ts.map +1 -0
- package/dist/database.js +264 -0
- package/dist/database.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/internal.d.ts +10 -0
- package/dist/internal.d.ts.map +1 -0
- package/dist/internal.js +13 -0
- package/dist/internal.js.map +1 -0
- package/dist/object.d.ts +162 -0
- package/dist/object.d.ts.map +1 -0
- package/dist/object.js +235 -0
- package/dist/object.js.map +1 -0
- package/dist/platform.d.ts +5 -0
- package/dist/platform.d.ts.map +1 -0
- package/dist/platform.js +15 -0
- package/dist/platform.js.map +1 -0
- package/dist/schema.d.ts +35 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +118 -0
- package/dist/schema.js.map +1 -0
- package/dist/selector.d.ts +86 -0
- package/dist/selector.d.ts.map +1 -0
- package/dist/selector.js +196 -0
- package/dist/selector.js.map +1 -0
- package/dist/serve.d.ts +21 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/serve.js +49 -0
- package/dist/serve.js.map +1 -0
- package/dist/session.d.ts +167 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +547 -0
- package/dist/session.js.map +1 -0
- package/package.json +40 -5
- package/src/calls.ts +197 -0
- package/src/database.ts +392 -0
- package/src/index.ts +38 -0
- package/src/internal.ts +14 -0
- package/src/object.ts +368 -0
- package/src/platform.ts +15 -0
- package/src/schema.ts +162 -0
- package/src/selector.ts +253 -0
- package/src/serve.ts +54 -0
- package/src/session.ts +663 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 - Restate Software, Inc., Restate GmbH
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,4 +1,482 @@
|
|
|
1
1
|
# @restatedev/sessions
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
`@restatedev/sessions` is the Restate TypeScript SDK plus _session objects_:
|
|
4
|
+
virtual objects where each key has its own SQL database, `ctx.db`. We call
|
|
5
|
+
them _sessions_ for short. The database is stored in the object's Restate
|
|
6
|
+
state, so there is no database server to run, and you still get what
|
|
7
|
+
Restate gives any virtual object: one writer per key, retries, and durable
|
|
8
|
+
calls to other services.
|
|
9
|
+
|
|
10
|
+
Session handlers don't use Restate's journal replay. When an attempt fails,
|
|
11
|
+
Restate runs the handler again from the start (the SDK calls this _explicit
|
|
12
|
+
recovery_), and the handler continues from whatever it has committed to its
|
|
13
|
+
database. The storage that makes this safe is a Rust addon in
|
|
14
|
+
[`native/`](native/README.md), built on Turso's SQLite-compatible engine.
|
|
15
|
+
|
|
16
|
+
It runs on a released Restate server and the published SDK, version 1.18.2,
|
|
17
|
+
which it pins ([why](#concurrent-awaits)). See
|
|
18
|
+
[the requirements](../../README.md#requirements).
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import * as restate from '@restatedev/sessions';
|
|
22
|
+
|
|
23
|
+
const ledger = restate.sessionObject({
|
|
24
|
+
name: 'Ledger',
|
|
25
|
+
schema: ['CREATE TABLE accounts(id INTEGER PRIMARY KEY, balance INTEGER)'], // applied once per key
|
|
26
|
+
handlers: {
|
|
27
|
+
deposit: (ctx, { id, amount }: { id: number; amount: number }) =>
|
|
28
|
+
ctx.db.transaction(async (tx) => {
|
|
29
|
+
await tx.execute('UPDATE accounts SET balance = balance + ? WHERE id = ?', [amount, id]);
|
|
30
|
+
}), // one transaction: durable as a whole once it resolves
|
|
31
|
+
},
|
|
32
|
+
views: {
|
|
33
|
+
balance: async (ctx, id: number) =>
|
|
34
|
+
ctx.db.get<{ balance: number }>('SELECT balance FROM accounts WHERE id = ?', [id]),
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Defining a session object
|
|
40
|
+
|
|
41
|
+
`@restatedev/sessions` re-exports `@restatedev/restate-sdk`, so session objects
|
|
42
|
+
sit next to your regular services, virtual objects and workflows.
|
|
43
|
+
`restate.sessionObject({ name, schema, handlers, views })` takes:
|
|
44
|
+
|
|
45
|
+
- **`handlers`**, which run one at a time per key and are the only ones that
|
|
46
|
+
write. Each gets a `SessionContext`.
|
|
47
|
+
- **`views`**, which can run at any time, alongside the handlers, and only
|
|
48
|
+
read. Each gets a `ViewContext`. See [views](#views).
|
|
49
|
+
|
|
50
|
+
A name is either a handler or a view, not both. Each one is a function, or
|
|
51
|
+
`{ handler, ...options }` with the SDK's usual handler options (`input`,
|
|
52
|
+
`output`, `description`, `ingressPrivate`, …). You only annotate the input;
|
|
53
|
+
`ctx` is inferred. `description`, `options` and `metadata` work as on any
|
|
54
|
+
virtual object, but for the state options: a session object starts an
|
|
55
|
+
invocation with only its database's head preloaded, and hides the
|
|
56
|
+
database's state operations in Restate's UI.
|
|
57
|
+
|
|
58
|
+
SDK handlers (`restate.handlers.*`) aren't accepted. Journaled work belongs
|
|
59
|
+
in a regular `restate.object`, `restate.service` or `restate.workflow`, which
|
|
60
|
+
your session object can call.
|
|
61
|
+
|
|
62
|
+
`restate.serve(...services)` serves them, session objects and the SDK's
|
|
63
|
+
alike, on `PORT` (9080 by default), with what they need beside them (such
|
|
64
|
+
as @restatedev/agents' `signals`, which each agent brings with it).
|
|
65
|
+
`RESTATE_SERVE_ONLY=a,b` serves only the services it names: one program,
|
|
66
|
+
deployed in parts. For anything else (another port, HTTP/1.1, a
|
|
67
|
+
Lambda handler), the SDK's `restate.endpoint()` is there as ever.
|
|
68
|
+
|
|
69
|
+
### The contexts
|
|
70
|
+
|
|
71
|
+
The contexts are small and explicit, and a new one is built for each
|
|
72
|
+
attempt:
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
interface SessionContext {
|
|
76
|
+
readonly key: string;
|
|
77
|
+
readonly request: restate.Request; // id (the same on every attempt), headers, target...
|
|
78
|
+
readonly db: Database;
|
|
79
|
+
readonly rpc: Rpc;
|
|
80
|
+
readonly send: Send;
|
|
81
|
+
readonly cancel: Cancel; // cancel an invocation, by its id
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
interface ViewContext {
|
|
85
|
+
readonly key: string;
|
|
86
|
+
readonly request: restate.Request;
|
|
87
|
+
readonly db: DatabaseReader;
|
|
88
|
+
readonly rpc: Rpc;
|
|
89
|
+
readonly cancel: Cancel;
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Neither has key/value state, `run`, `sleep`, awakeables, promises or
|
|
94
|
+
signals: the database is a session's only state. You can await their
|
|
95
|
+
operations concurrently, with `Promise.all` or `Promise.race`.
|
|
96
|
+
|
|
97
|
+
### Views
|
|
98
|
+
|
|
99
|
+
A view reads the session's database as committed, while handlers may be
|
|
100
|
+
committing at the same time. A chat UI can read a conversation while the
|
|
101
|
+
agent is still working on it, for example. A view reads a snapshot of the
|
|
102
|
+
database as it was when the view's invocation started, whatever the
|
|
103
|
+
handlers commit afterwards. A view that is still running after 16 of their
|
|
104
|
+
commits fails, and Restate retries it ([how readers work](native/src/state/docs/DESIGN.md#readers)).
|
|
105
|
+
|
|
106
|
+
A view's `db` has no `execute` or `transaction`, and its context has no
|
|
107
|
+
`send`. A write through `query` fails too, because a view's database is
|
|
108
|
+
read-only. A view can cancel an invocation, though: see
|
|
109
|
+
[cancelling an invocation](#cancelling-an-invocation).
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
views: {
|
|
113
|
+
count: async (ctx) => ctx.db.get<{ accounts: number }>('SELECT count(*) AS accounts FROM accounts'),
|
|
114
|
+
},
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Retries
|
|
118
|
+
|
|
119
|
+
A handler runs in attempts. Restate starts a new attempt after a crash, a
|
|
120
|
+
retryable error or a suspension, and every attempt runs the handler from its
|
|
121
|
+
first line. A commit is durable once its promise resolves, and every later
|
|
122
|
+
attempt sees it. An error, terminal or not, doesn't undo what the handler
|
|
123
|
+
already committed.
|
|
124
|
+
|
|
125
|
+
So a handler's writes must be safe to run twice. The usual way is to record
|
|
126
|
+
an id that is the same on every attempt along with the writes, such as
|
|
127
|
+
`ctx.request.id` or an order id from the input, and check for it first.
|
|
128
|
+
Calls and sends are repeated on every attempt too, unless you give them an
|
|
129
|
+
idempotency key ([calls and sends](#calls-and-sends)).
|
|
130
|
+
|
|
131
|
+
What each operation does when a new attempt reaches it again:
|
|
132
|
+
|
|
133
|
+
| Operation | On a new attempt |
|
|
134
|
+
| ---------- | ----------------------------------------------------------------------------------------------------------------------- |
|
|
135
|
+
| `ctx.db` | Runs again against the database as committed. Record a stable id with your writes to recognize work already done. |
|
|
136
|
+
| `ctx.rpc` | Makes a new call, unless it has an idempotency key; then it reaches the invocation the earlier attempt started. |
|
|
137
|
+
| `ctx.send` | Sends again, unless it has an idempotency key; then Restate drops the repeat, and a delayed send keeps its first timer. |
|
|
138
|
+
| `tx.send` | Sent once its transaction commits, and only once ([sends in a transaction](#sends-in-a-transaction)). |
|
|
139
|
+
|
|
140
|
+
## The database
|
|
141
|
+
|
|
142
|
+
`ctx.db` is the key's database. Its namespace is `service/key`, it is
|
|
143
|
+
stored in the object's state, and the process keeps a page cache of it.
|
|
144
|
+
|
|
145
|
+
- `query<T>(sql, params)` returns the rows of a statement as objects keyed
|
|
146
|
+
by column name, and `get<T>` returns the first row or `undefined`. `T`
|
|
147
|
+
describes a row but isn't checked at runtime. Integers above 2^53 come
|
|
148
|
+
back as bigints, and booleans as 0 or 1. An expression needs `AS` to get a
|
|
149
|
+
column name, and two columns with the same name are an error.
|
|
150
|
+
- `values(sql, params)` returns rows as arrays in column order, for adapters
|
|
151
|
+
or for columns that share a name.
|
|
152
|
+
- `execute` runs one or more statements and returns no rows.
|
|
153
|
+
|
|
154
|
+
Outside a transaction, each statement is a commit of its own, and a
|
|
155
|
+
statement that changes nothing writes nothing. `ctx.db.transaction(tx => …)`
|
|
156
|
+
commits its body's statements together when the body resolves, and rolls
|
|
157
|
+
them back if it rejects. Every commit is one round trip to Restate, so a
|
|
158
|
+
transaction also makes a group of writes cheaper (one with sends costs one
|
|
159
|
+
more round trip, see [sends in a transaction](#sends-in-a-transaction)).
|
|
160
|
+
|
|
161
|
+
Calls to `ctx.db` run one at a time in the order you make them, even when
|
|
162
|
+
you await them together, and so do a transaction's statements. A
|
|
163
|
+
transaction holds `ctx.db` until it ends: inside its body, use `tx`, since a
|
|
164
|
+
call to `ctx.db` is refused.
|
|
165
|
+
|
|
166
|
+
If a crash happens between two commits, the first one stays. Statements that
|
|
167
|
+
must succeed or fail together belong in one transaction.
|
|
168
|
+
|
|
169
|
+
Libraries can keep their data in `ctx.db` too: the
|
|
170
|
+
[pi integration](../agents/src/pi/README.md) stores pi-durable's state there.
|
|
171
|
+
|
|
172
|
+
### Errors
|
|
173
|
+
|
|
174
|
+
An SQL error rejects with a `TerminalError` whose `cause` is the SQL error,
|
|
175
|
+
since a retry would fail the same way. That covers a statement the engine
|
|
176
|
+
rejects, a parameter it can't bind, and a call `ctx.db` refuses, including
|
|
177
|
+
the ones that close it: a `COMMIT` inside a transaction's body, or a
|
|
178
|
+
transaction still open when the handler returns. A storage error closes
|
|
179
|
+
`ctx.db` too, but it is retried. Errors thrown by your own code behave as in
|
|
180
|
+
any handler.
|
|
181
|
+
|
|
182
|
+
## The schema
|
|
183
|
+
|
|
184
|
+
`schema` lists the steps that create each key's database, in order. A step
|
|
185
|
+
is an SQL statement, or an async function that gets the transaction (to
|
|
186
|
+
move data, for example). The first attempt of a handler for a key applies
|
|
187
|
+
them in one transaction, when it opens the database.
|
|
188
|
+
|
|
189
|
+
The database records how far it got in a record next to its tables, which
|
|
190
|
+
commits together with the steps. So when you add a step later, such as a new
|
|
191
|
+
column or index, it runs once on each key's database. Never change a step
|
|
192
|
+
that has already run; add a new one instead. A view of a key that has never
|
|
193
|
+
been written sees empty tables.
|
|
194
|
+
|
|
195
|
+
Libraries that run in the database add their own tables. `@restatedev/agents`
|
|
196
|
+
names its tables `restate_…`, so give yours other names.
|
|
197
|
+
|
|
198
|
+
## Calls and sends
|
|
199
|
+
|
|
200
|
+
`ctx.rpc(target, key?, options?)` returns a client for a service, object or
|
|
201
|
+
workflow, typed by its definition. Objects and workflows need a key and
|
|
202
|
+
services don't; getting that wrong throws a `TerminalError`. For a target
|
|
203
|
+
known only at runtime, use `ctx.rpc({ service, key, handler, input })`,
|
|
204
|
+
which encodes JSON by default. `ctx.send` works the same way for one-way
|
|
205
|
+
messages, and also takes a `delay`. The options apply to every call made
|
|
206
|
+
through the client:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
const owner = await ctx.rpc(nickname, name, { idempotencyKey: `${ctx.request.id}:claim` }).claim(ctx.key);
|
|
210
|
+
ctx.send(audit).record(entry);
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The SDK never makes up idempotency keys: a call has one only if you pass it.
|
|
214
|
+
With a key, a new attempt, including one resuming from a suspension, reaches
|
|
215
|
+
the invocation the first attempt started and gets its result. Build the key
|
|
216
|
+
from the request id and what the call is for. Restate scopes keys to the
|
|
217
|
+
target handler and remembers them for the target's idempotency retention, a
|
|
218
|
+
day by default.
|
|
219
|
+
|
|
220
|
+
A key names one call. If an invocation makes the same call several times,
|
|
221
|
+
once per tool call for example, add something to the key that tells them
|
|
222
|
+
apart. Restate attaches a call with a key it has already seen to the earlier
|
|
223
|
+
invocation, whatever its input, so a key only fits a call whose input is the
|
|
224
|
+
same on every attempt. If the input depends on what the attempt read, put
|
|
225
|
+
that in the key, or use no key.
|
|
226
|
+
|
|
227
|
+
## Cancelling an invocation
|
|
228
|
+
|
|
229
|
+
`ctx.cancel(invocationId)` cancels an invocation, as Restate's admin API
|
|
230
|
+
does. It is made at once and not awaited. Handlers and views both have it.
|
|
231
|
+
A view that cancels its own object's running handler is a Stop button: the
|
|
232
|
+
handler is cancelled, and the next message waiting for the key runs.
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
views: {
|
|
236
|
+
stop: async (ctx, invocationId: string) => ctx.cancel(invocationId),
|
|
237
|
+
},
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Cancelling an invocation that already ended does nothing, so an attempt that
|
|
241
|
+
cancels the same id again is harmless. Be careful when the attempt itself
|
|
242
|
+
works out which invocation to cancel, such as by reading which one is
|
|
243
|
+
running. A second attempt may get a different answer: the message that
|
|
244
|
+
started once the first attempt's cancel took effect. Get the id from a call
|
|
245
|
+
with an idempotency key instead, which gives every attempt the same answer
|
|
246
|
+
([calls and sends](#calls-and-sends)).
|
|
247
|
+
|
|
248
|
+
A cancellation that comes while a `ctx.db` call waits on Restate fails that
|
|
249
|
+
call with a `CancelledError`, as any other await of the handler does. A
|
|
250
|
+
commit it interrupts may still be stored, so a `CancelledError` from
|
|
251
|
+
`transaction()` doesn't mean the transaction rolled back: if it committed,
|
|
252
|
+
the key's next invocation makes its sends.
|
|
253
|
+
|
|
254
|
+
## Sends in a transaction
|
|
255
|
+
|
|
256
|
+
A send made with `tx.send` goes out right after its transaction commits, and
|
|
257
|
+
never if it rolls back:
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
ctx.db.transaction(async (tx) => {
|
|
261
|
+
await tx.execute('UPDATE accounts SET balance = balance - ? WHERE id = ?', [amount, from]);
|
|
262
|
+
tx.send(store, 'a').reserve(item);
|
|
263
|
+
tx.send(store, 'b', { delay: { hours: 1 } }).expire();
|
|
264
|
+
});
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
The sends are stored in the transaction's commit, in a record called
|
|
268
|
+
`outbox` next to the tables. After the commit, the attempt makes them, each
|
|
269
|
+
with the idempotency key `transaction/<id>/<index>` (or the send's own key),
|
|
270
|
+
where `<id>` is a random id of the transaction. Then, before `transaction()`
|
|
271
|
+
resolves, a second commit empties the outbox. Restate stores an attempt's
|
|
272
|
+
commands in order, so the sends are stored by the time that commit is. An
|
|
273
|
+
attempt that suspends later, to wait days for an approval for example, has
|
|
274
|
+
nothing left to send again when it resumes, long after the keys expired.
|
|
275
|
+
|
|
276
|
+
If an attempt ends between the two commits, the sends stay in the outbox.
|
|
277
|
+
The next exclusive attempt opens the database when it starts, and sends them
|
|
278
|
+
again with the same keys and whatever remains of their delays, which count
|
|
279
|
+
from the commit. Restate drops a send whose key it has already seen. So
|
|
280
|
+
every send of a committed transaction is made once, even if no later attempt
|
|
281
|
+
uses the database, and the sends of a transaction that rolled back or was
|
|
282
|
+
lost are never made.
|
|
283
|
+
|
|
284
|
+
A transaction without sends costs nothing extra; one with sends costs one
|
|
285
|
+
more commit. If the sends fail after the commit because the attempt was
|
|
286
|
+
replaced, `transaction()` rejects even though it committed: that attempt is
|
|
287
|
+
over, and the next one makes them.
|
|
288
|
+
|
|
289
|
+
A send doesn't return an invocation id. When you need a call's result, make
|
|
290
|
+
the call before the transaction, with an idempotency key of its own, and
|
|
291
|
+
record its outcome in the transaction. The shop's `Orders` does this, and its
|
|
292
|
+
`expire` is a `tx.send`.
|
|
293
|
+
|
|
294
|
+
## How it works
|
|
295
|
+
|
|
296
|
+
**Where the data lives.** The database is stored in the object's state,
|
|
297
|
+
under the keys `v22/head`, `v22/tail/…`, `v22/manifest/…` and `v22/pack/…`.
|
|
298
|
+
Reads are `ctx.get`, writes are `ctx.set` and `ctx.clear`, and a sync is an
|
|
299
|
+
empty `ctx.run`. Handlers and views can't reach any other state key, since
|
|
300
|
+
a session has no key/value state of its own.
|
|
301
|
+
|
|
302
|
+
**Reads and writes.** A read is a state read. It is journaled for now (once
|
|
303
|
+
protocol v8 ships it won't be), and it goes
|
|
304
|
+
to the runtime unless this attempt wrote the key or the invocation started
|
|
305
|
+
with it. An invocation starts with only the database's head (`state:
|
|
306
|
+
{ preload: ['v22/head'] }`): its open's first read needs no round trip, and
|
|
307
|
+
it doesn't start by loading every page. A write or a clear is a state write, and returns at once.
|
|
308
|
+
Restate keeps an attempt's writes and sends in the order they were made, so
|
|
309
|
+
a crash can lose the last ones, but never a write without those before it.
|
|
310
|
+
|
|
311
|
+
**Commits.** A transaction writes the pages it changed, and its records, as
|
|
312
|
+
one tail entry under a key of its own. Then it writes the head, which points
|
|
313
|
+
to that entry; this is the commit point. One empty `ctx.run` then waits until
|
|
314
|
+
all of it is stored, so a commit is one round trip. Whatever a crash keeps,
|
|
315
|
+
the stored head only points to tail entries and checkpoints that are stored
|
|
316
|
+
too. Now and then, a commit first folds the tail into a checkpoint (see the
|
|
317
|
+
[state's architecture](native/src/state/docs/ARCHITECTURE.md)).
|
|
318
|
+
|
|
319
|
+
**The page cache.** The process caches the pages it read and wrote, and the
|
|
320
|
+
database's state as of its last head, for the key's next invocation.
|
|
321
|
+
Checkpoint packs never change, so the cache never invalidates them. An
|
|
322
|
+
attempt reads the stored head, and if another process wrote since, fetches
|
|
323
|
+
only the ranges the cache lacks. The head carries the database's random id,
|
|
324
|
+
which is part of the cache keys, so one process can serve several Restate
|
|
325
|
+
clusters, or a cluster that was wiped and recreated, without mixing up their
|
|
326
|
+
databases.
|
|
327
|
+
|
|
328
|
+
**No journal replay.** On a retry or a resume, the SDK normally replays the
|
|
329
|
+
journal: each operation returns its recorded result, and must match it.
|
|
330
|
+
That can't work here, because a later attempt makes different reads,
|
|
331
|
+
depending on what the page cache holds. With explicit recovery
|
|
332
|
+
(`restate.internal.explicitRecovery()`, which every session handler and view
|
|
333
|
+
has), the SDK skips the recorded journal, and the handler runs again from
|
|
334
|
+
the start against the state as it is. Recovery is then up to the storage:
|
|
335
|
+
opening the database reads the head, so a commit the crashed attempt didn't
|
|
336
|
+
finish is as if it never started.
|
|
337
|
+
|
|
338
|
+
**One writer.** The storage needs one writer per namespace. Restate runs one
|
|
339
|
+
exclusive invocation per key at a time, and one attempt of it at a time, so
|
|
340
|
+
the namespace is `service/key`, and only handlers write to it. Views read
|
|
341
|
+
alongside them.
|
|
342
|
+
|
|
343
|
+
## Concurrent awaits
|
|
344
|
+
|
|
345
|
+
You can await a context's calls (the SDK's `RestatePromise`s) and the
|
|
346
|
+
database's calls concurrently: with `Promise.all`, `Promise.race`, your own
|
|
347
|
+
combinators, several async functions at once, or a library's. The database's
|
|
348
|
+
own reads run concurrently too.
|
|
349
|
+
|
|
350
|
+
On its own, the published SDK drives each awaited promise with a loop of its
|
|
351
|
+
own, and lets only one of them wait for the server at a time
|
|
352
|
+
(`ExternalProgressChannel`). A second waiter fails the attempt with
|
|
353
|
+
`awaitNext already pending`, and it is retried forever. So session handlers
|
|
354
|
+
drive every promise they await with a single loop,
|
|
355
|
+
[the selector](src/selector.ts). Before the handler runs, it takes over the
|
|
356
|
+
invocation's `promisesExecutor.doProgress`, and gives it back when the
|
|
357
|
+
attempt ends. These are SDK internals as of 1.18.2, so the package pins that
|
|
358
|
+
version, and refuses to run a handler on an SDK without them.
|
|
359
|
+
[`test/selector.test.ts`](test/selector.test.ts) tests the selector against
|
|
360
|
+
a fake VM and the SDK's single-waiter channel.
|
|
361
|
+
|
|
362
|
+
What you get:
|
|
363
|
+
|
|
364
|
+
- **One await point.** The loop asks the server about all awaited promises
|
|
365
|
+
at once. After a suspension, the handler resumes on the first of them to
|
|
366
|
+
complete, and a promise awaited while the loop waits joins its next check,
|
|
367
|
+
so a call awaited late isn't held up by a slow call made earlier.
|
|
368
|
+
- **An operation starts when you make it.** A call goes out without an
|
|
369
|
+
`await`, and a failure nobody awaits is not an unhandled rejection.
|
|
370
|
+
- **Cancellation reaches every awaited promise**, and each one rejects with
|
|
371
|
+
`CancelledError`.
|
|
372
|
+
|
|
373
|
+
```ts
|
|
374
|
+
const quote = restate.sessionObject({
|
|
375
|
+
name: 'quote',
|
|
376
|
+
handlers: {
|
|
377
|
+
price: async (ctx, sku: string) => {
|
|
378
|
+
const [price, stock] = await Promise.all([
|
|
379
|
+
ctx.rpc(pricing).quote(sku),
|
|
380
|
+
ctx.db.get<{ count: number }>('SELECT count FROM stock WHERE sku = ?', [sku]),
|
|
381
|
+
]);
|
|
382
|
+
return { price, inStock: (stock?.count ?? 0) > 0 };
|
|
383
|
+
},
|
|
384
|
+
},
|
|
385
|
+
});
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
[`e2e/concurrency.ts`](../e2e/concurrency.ts) tests all of this against a
|
|
389
|
+
real server.
|
|
390
|
+
|
|
391
|
+
## Examples
|
|
392
|
+
|
|
393
|
+
The smallest is [`examples/basic/notes.ts`](../examples/basic/notes.ts): a
|
|
394
|
+
handler and a view with `ctx.db`. Two more live in [`test/`](test), where
|
|
395
|
+
the tests use them:
|
|
396
|
+
|
|
397
|
+
- [`ledger.ts`](test/ledger.ts): accounts and transfers between them,
|
|
398
|
+
deduplicated by transfer id.
|
|
399
|
+
- [`shop.ts`](test/shop.ts): two session objects that call each other, a
|
|
400
|
+
`Warehouse` per SKU and `Orders` per order. Placing an order reserves stock
|
|
401
|
+
(a call) and schedules the order's expiry (a delayed send). Paying commits
|
|
402
|
+
the stock, and an unpaid order releases it when it expires.
|
|
403
|
+
|
|
404
|
+
Each one runs on its own (`node test/shop.ts`, from here) or together with
|
|
405
|
+
the others (`pnpm --filter e2e serve`, or `node serve.ts ledger shop` in
|
|
406
|
+
[`packages/e2e/`](../e2e) for a few), on port 9080 or `PORT`:
|
|
407
|
+
|
|
408
|
+
```sh
|
|
409
|
+
pnpm install && pnpm build # from the repository root
|
|
410
|
+
pnpm --filter e2e serve # the ledger and the shop, on port 9080
|
|
411
|
+
npx @restatedev/restate-server # Restate, in another terminal
|
|
412
|
+
npx @restatedev/restate deployments register http://localhost:9080
|
|
413
|
+
curl localhost:8080/Ledger/bank/init --json '[8, 1000]'
|
|
414
|
+
curl localhost:8080/Warehouse/apple/restock --json '{"id": "first", "qty": 10}' # orders need stock
|
|
415
|
+
curl localhost:8080/Orders/o1/place --json '{"sku": "apple", "qty": 2}'
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
Both run through crashes against a real server in
|
|
419
|
+
[the crash test](../e2e/crash.ts) (`pnpm --filter e2e crash`). On one local
|
|
420
|
+
node, 200 ledger transfers in a row take 18.8 ms each.
|
|
421
|
+
|
|
422
|
+
For an agent that keeps its state in `ctx.db`, see
|
|
423
|
+
[`@restatedev/agents/pi`](../agents/src/pi/README.md), which runs pi-durable's
|
|
424
|
+
storage in the session's database.
|
|
425
|
+
|
|
426
|
+
## Caveats
|
|
427
|
+
|
|
428
|
+
- **Every read is journaled with its value.** A state read adds the value to
|
|
429
|
+
the invocation's journal, so reading pages costs log writes, and the page
|
|
430
|
+
cache matters more than usual. A completed invocation's journal, reads
|
|
431
|
+
included, is kept for Restate's default retention.
|
|
432
|
+
- **The journal grows across attempts.** Entries an attempt skips stay, and
|
|
433
|
+
each attempt adds its own.
|
|
434
|
+
- **A suspension is a restart.** Resuming means running from the start, so a
|
|
435
|
+
long handler that hits the inactivity timeout starts over.
|
|
436
|
+
- **One sync per commit.** Every commit waits for an empty `ctx.run` after
|
|
437
|
+
its head, a round trip to the runtime. Statements that commit one by one
|
|
438
|
+
pay it each time, so group them in a transaction.
|
|
439
|
+
- **10 GiB per database.** A statement that would grow a key's database past
|
|
440
|
+
that fails with SQLite's "database or disk is full", as an SQL error (a
|
|
441
|
+
`TerminalError`), and `ctx.db` keeps working.
|
|
442
|
+
- **Assumptions still to confirm with the runtime.** An empty `ctx.run` is
|
|
443
|
+
acknowledged only after the commands before it are stored (the sync). An
|
|
444
|
+
abandoned attempt's commands are never applied after a new attempt starts
|
|
445
|
+
(fencing). State that a lazy read returns is durable. The crash tests kill
|
|
446
|
+
processes, so they check recovery, not durability across a machine crash.
|
|
447
|
+
|
|
448
|
+
## Not supported
|
|
449
|
+
|
|
450
|
+
- Key/value state, durable steps, timers and awakeables in a session object.
|
|
451
|
+
Put them in a regular `restate.object`, `service` or `workflow`, and call
|
|
452
|
+
it.
|
|
453
|
+
- Request/response deployments, such as Lambda. They suspend at every
|
|
454
|
+
await, and for a session a suspension is a restart.
|
|
455
|
+
|
|
456
|
+
## Tests
|
|
457
|
+
|
|
458
|
+
- [`test/`](test): the library's own tests, without a server
|
|
459
|
+
(`pnpm --filter @restatedev/sessions test`): session objects, transactions and
|
|
460
|
+
their sends, views, SQL errors and lost writes.
|
|
461
|
+
- [`native/`](native/README.md#build-and-test): the addon's tests
|
|
462
|
+
(`pnpm --filter @restatedev/sessions test:rust`).
|
|
463
|
+
- [`e2e/concurrency.ts`](../e2e/concurrency.ts) and
|
|
464
|
+
[`e2e/crash.ts`](../e2e/crash.ts): against a real server.
|
|
465
|
+
|
|
466
|
+
[`test/support.ts`](test/support.ts) runs a handler's attempts over an
|
|
467
|
+
in-memory copy of the object's state, through crashes and fencing.
|
|
468
|
+
`@restatedev/agents` uses it in its tests too, as `@restatedev/sessions/test/support`.
|
|
469
|
+
|
|
470
|
+
`@restatedev/sessions/internal` exposes what the tests take apart:
|
|
471
|
+
|
|
472
|
+
- `invoke`: run a handler for one attempt, over a context of your own;
|
|
473
|
+
- `contextOf`: a handler's or view's context over such a context;
|
|
474
|
+
- `Attempt` and `withAttempt`: an attempt's database;
|
|
475
|
+
- `open` and `asDatabase`: a database over a store of your own;
|
|
476
|
+
- `setStoreWrapper`: fault injection in the store.
|
|
477
|
+
|
|
478
|
+
It also has what this repository's other libraries need: `Schema` (tables a
|
|
479
|
+
library owns, applied where it uses them), `database` (another database of
|
|
480
|
+
the same key), `reset` (empty the key's database in a transaction), and
|
|
481
|
+
`cancelled` and `cancelCalls` (explicit cancellation, for a handler with
|
|
482
|
+
`explicitCancellation: true`).
|
package/dist/calls.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type * as restate from '@restatedev/restate-sdk';
|
|
2
|
+
import type { Duration, Serde, ServiceDefinition, VirtualObjectDefinition, WorkflowDefinition } from '@restatedev/restate-sdk-core';
|
|
3
|
+
/** The options of a call, which apply to every call its client makes. */
|
|
4
|
+
export interface CallOptions {
|
|
5
|
+
/**
|
|
6
|
+
* A key that is the same on every attempt, so that a new attempt gets the
|
|
7
|
+
* first call's result. Without one, every attempt makes the call again,
|
|
8
|
+
* including the one that resumes a suspension: a call that may wait long
|
|
9
|
+
* wants a key. Restate scopes it to the target handler: two calls of the
|
|
10
|
+
* same handler through one keyed client are one invocation, so make a
|
|
11
|
+
* client per call when that is not what you mean.
|
|
12
|
+
*/
|
|
13
|
+
idempotencyKey?: string;
|
|
14
|
+
/** Headers of the call. */
|
|
15
|
+
headers?: Record<string, string>;
|
|
16
|
+
}
|
|
17
|
+
/** The options of a send. */
|
|
18
|
+
export interface SendOptions extends CallOptions {
|
|
19
|
+
/** How long after the send (for `tx.send`, after the commit) the target runs. */
|
|
20
|
+
delay?: Duration | number;
|
|
21
|
+
}
|
|
22
|
+
/** A target known only at run time: untyped, and JSON unless serdes are given. */
|
|
23
|
+
export interface Target {
|
|
24
|
+
service: string;
|
|
25
|
+
/** The key of an object or a workflow. */
|
|
26
|
+
key?: string;
|
|
27
|
+
handler: string;
|
|
28
|
+
input?: unknown;
|
|
29
|
+
inputSerde?: Serde<unknown>;
|
|
30
|
+
}
|
|
31
|
+
/** A definition the clients take: a service, a virtual object or a workflow, as `restate` makes them. */
|
|
32
|
+
type Definition = {
|
|
33
|
+
name: string;
|
|
34
|
+
};
|
|
35
|
+
type OfObject<D> = D extends VirtualObjectDefinition<string, infer M> ? M : unknown;
|
|
36
|
+
type OfService<D> = D extends ServiceDefinition<string, infer M> ? M : unknown;
|
|
37
|
+
type OfWorkflow<D> = D extends WorkflowDefinition<string, infer M> ? M : unknown;
|
|
38
|
+
type HandlersOf<D> = unknown extends OfObject<D> ? (unknown extends OfService<D> ? OfWorkflow<D> : OfService<D>) : OfObject<D>;
|
|
39
|
+
/** A client of `D`: each handler takes its input, if any, and returns its output. */
|
|
40
|
+
export type Client<D> = {
|
|
41
|
+
[K in keyof HandlersOf<D>]: HandlersOf<D>[K] extends (ctx: never, ...input: infer I) => PromiseLike<infer O> ? (...input: I) => Promise<O> : never;
|
|
42
|
+
};
|
|
43
|
+
/** A send client of `D`: each handler takes its input, if any. */
|
|
44
|
+
export type SendClient<D> = {
|
|
45
|
+
[K in keyof HandlersOf<D>]: HandlersOf<D>[K] extends (ctx: never, ...input: infer I) => unknown ? (...input: I) => void : never;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* Calls: `ctx.rpc(service)` or `ctx.rpc(object, key)` for a typed client, with
|
|
49
|
+
* the options of its calls last; or `ctx.rpc({ service, key, handler, input })`
|
|
50
|
+
* for a target known only at run time. A typed client of an object or a
|
|
51
|
+
* workflow needs its key, and one of a service has none: it fails at once
|
|
52
|
+
* otherwise. A literal target names no kind: its `key` is the caller's to give.
|
|
53
|
+
*/
|
|
54
|
+
export interface Rpc {
|
|
55
|
+
<D extends Definition>(target: D, options?: CallOptions): Client<D>;
|
|
56
|
+
<D extends Definition>(target: D, key: string, options?: CallOptions): Client<D>;
|
|
57
|
+
<O = unknown>(call: Target & CallOptions & {
|
|
58
|
+
outputSerde?: Serde<O>;
|
|
59
|
+
}): Promise<O>;
|
|
60
|
+
}
|
|
61
|
+
/** Sends, as {@link Rpc}'s calls: each returns at once, with nothing. */
|
|
62
|
+
export interface Send {
|
|
63
|
+
<D extends Definition>(target: D, options?: SendOptions): SendClient<D>;
|
|
64
|
+
<D extends Definition>(target: D, key: string, options?: SendOptions): SendClient<D>;
|
|
65
|
+
(send: Target & SendOptions): void;
|
|
66
|
+
}
|
|
67
|
+
/** `ctx.rpc` over the SDK context `ctx`. */
|
|
68
|
+
export declare function rpcOf(ctx: Pick<restate.Context, 'genericCall'>): Rpc;
|
|
69
|
+
/** A send over `send`: `ctx.send` makes each at once, `tx.send` records it for its commit. */
|
|
70
|
+
export declare function sendOf(send: (send: restate.GenericSend<unknown>) => void): Send;
|
|
71
|
+
export {};
|
|
72
|
+
//# sourceMappingURL=calls.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"calls.d.ts","sourceRoot":"","sources":["../src/calls.ts"],"names":[],"mappings":"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"}
|
package/dist/calls.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// oxlint-disable eslint/no-underscore-dangle -- the SDK's names, in its definitions
|
|
2
|
+
import { serde, TerminalError } from '@restatedev/restate-sdk';
|
|
3
|
+
/** The target, key and options of a typed client's arguments. */
|
|
4
|
+
function clientOf(args) {
|
|
5
|
+
const [def, second, third] = args;
|
|
6
|
+
const key = typeof second === 'string' ? second : undefined;
|
|
7
|
+
const options = ((typeof second === 'string' ? third : second) ?? {});
|
|
8
|
+
const keyed = def._kind !== 'service';
|
|
9
|
+
if (keyed && key === undefined) {
|
|
10
|
+
throw new TerminalError(`${def.name} is ${def._kind === 'workflow' ? 'a workflow' : 'an object'}: call it with its key`);
|
|
11
|
+
}
|
|
12
|
+
if (!keyed && key !== undefined)
|
|
13
|
+
throw new TerminalError(`${def.name} is a service: call it without a key`);
|
|
14
|
+
return { def, key, options };
|
|
15
|
+
}
|
|
16
|
+
/** Whether `value` is a literal target rather than a definition. */
|
|
17
|
+
const isLiteral = (value) => typeof value.handler === 'string' && typeof value.service === 'string';
|
|
18
|
+
/** A client whose methods make `call` of each one, with its input. */
|
|
19
|
+
function proxy(call) {
|
|
20
|
+
return new Proxy({}, {
|
|
21
|
+
// Not a thenable: `await ctx.rpc(def, key)` gives the client, not a call of `then`.
|
|
22
|
+
get: (_, method) => typeof method === 'string' && method !== 'then' ? (input) => call(method, input) : undefined,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
/** `ctx.rpc` over the SDK context `ctx`. */
|
|
26
|
+
export function rpcOf(ctx) {
|
|
27
|
+
return (...args) => {
|
|
28
|
+
if (isLiteral(args[0])) {
|
|
29
|
+
const { service, key, handler, input, inputSerde, outputSerde, idempotencyKey, headers } = args[0];
|
|
30
|
+
return ctx.genericCall({
|
|
31
|
+
service,
|
|
32
|
+
method: handler,
|
|
33
|
+
key,
|
|
34
|
+
parameter: input,
|
|
35
|
+
inputSerde: inputSerde ?? serde.json,
|
|
36
|
+
outputSerde: outputSerde ?? serde.json,
|
|
37
|
+
idempotencyKey,
|
|
38
|
+
headers,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const { def, key, options } = clientOf(args);
|
|
42
|
+
return proxy((method, input) => ctx.genericCall({
|
|
43
|
+
service: def.name,
|
|
44
|
+
method,
|
|
45
|
+
key,
|
|
46
|
+
parameter: input,
|
|
47
|
+
inputSerde: def._handlers?.[method]?._inputSerde ?? serde.json,
|
|
48
|
+
outputSerde: def._handlers?.[method]?._outputSerde ?? serde.json,
|
|
49
|
+
idempotencyKey: options.idempotencyKey,
|
|
50
|
+
headers: options.headers,
|
|
51
|
+
}));
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** A send over `send`: `ctx.send` makes each at once, `tx.send` records it for its commit. */
|
|
55
|
+
export function sendOf(send) {
|
|
56
|
+
return ((...args) => {
|
|
57
|
+
if (isLiteral(args[0])) {
|
|
58
|
+
const { service, key, handler, input, inputSerde, idempotencyKey, headers, delay } = args[0];
|
|
59
|
+
send({
|
|
60
|
+
service,
|
|
61
|
+
method: handler,
|
|
62
|
+
key,
|
|
63
|
+
parameter: input,
|
|
64
|
+
inputSerde: inputSerde ?? serde.json,
|
|
65
|
+
idempotencyKey,
|
|
66
|
+
headers,
|
|
67
|
+
delay,
|
|
68
|
+
});
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
const { def, key, options } = clientOf(args);
|
|
72
|
+
return proxy((method, input) => {
|
|
73
|
+
send({
|
|
74
|
+
service: def.name,
|
|
75
|
+
method,
|
|
76
|
+
key,
|
|
77
|
+
parameter: input,
|
|
78
|
+
inputSerde: def._handlers?.[method]?._inputSerde ?? serde.json,
|
|
79
|
+
idempotencyKey: options.idempotencyKey,
|
|
80
|
+
headers: options.headers,
|
|
81
|
+
delay: options.delay,
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=calls.js.map
|