@restatedev/sessions 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +474 -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 +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/internal.d.ts +9 -0
- package/dist/internal.d.ts.map +1 -0
- package/dist/internal.js +12 -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/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 +46 -3
- package/src/calls.ts +197 -0
- package/src/database.ts +392 -0
- package/src/index.ts +35 -0
- package/src/internal.ts +13 -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/session.ts +663 -0
package/src/calls.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// oxlint-disable eslint/no-underscore-dangle -- the SDK's names, in its definitions
|
|
2
|
+
|
|
3
|
+
// Calls and sends from a session object's handler: `ctx.rpc` and `ctx.send`,
|
|
4
|
+
// and a transaction's `tx.send`. A target is a definition (with its key for
|
|
5
|
+
// an object or a workflow), or a literal naming it, for one known only at run
|
|
6
|
+
// time. Options go with the target: a client's methods take only their input.
|
|
7
|
+
import type * as restate from '@restatedev/restate-sdk';
|
|
8
|
+
import { serde, TerminalError } from '@restatedev/restate-sdk';
|
|
9
|
+
import type {
|
|
10
|
+
Duration,
|
|
11
|
+
HandlerDescriptor,
|
|
12
|
+
Serde,
|
|
13
|
+
ServiceDefinition,
|
|
14
|
+
VirtualObjectDefinition,
|
|
15
|
+
WorkflowDefinition,
|
|
16
|
+
} from '@restatedev/restate-sdk-core';
|
|
17
|
+
|
|
18
|
+
/** The options of a call, which apply to every call its client makes. */
|
|
19
|
+
export interface CallOptions {
|
|
20
|
+
/**
|
|
21
|
+
* A key that is the same on every attempt, so that a new attempt gets the
|
|
22
|
+
* first call's result. Without one, every attempt makes the call again,
|
|
23
|
+
* including the one that resumes a suspension: a call that may wait long
|
|
24
|
+
* wants a key. Restate scopes it to the target handler: two calls of the
|
|
25
|
+
* same handler through one keyed client are one invocation, so make a
|
|
26
|
+
* client per call when that is not what you mean.
|
|
27
|
+
*/
|
|
28
|
+
idempotencyKey?: string;
|
|
29
|
+
/** Headers of the call. */
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The options of a send. */
|
|
34
|
+
export interface SendOptions extends CallOptions {
|
|
35
|
+
/** How long after the send (for `tx.send`, after the commit) the target runs. */
|
|
36
|
+
delay?: Duration | number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A target known only at run time: untyped, and JSON unless serdes are given. */
|
|
40
|
+
export interface Target {
|
|
41
|
+
service: string;
|
|
42
|
+
/** The key of an object or a workflow. */
|
|
43
|
+
key?: string;
|
|
44
|
+
handler: string;
|
|
45
|
+
input?: unknown;
|
|
46
|
+
inputSerde?: Serde<unknown>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A definition the clients take: a service, a virtual object or a workflow, as `restate` makes them. */
|
|
50
|
+
type Definition = { name: string };
|
|
51
|
+
|
|
52
|
+
// The handlers of a definition, of whichever kind: each kind's type only
|
|
53
|
+
// infers from its own definitions, and is `unknown` for the others.
|
|
54
|
+
type OfObject<D> = D extends VirtualObjectDefinition<string, infer M> ? M : unknown;
|
|
55
|
+
type OfService<D> = D extends ServiceDefinition<string, infer M> ? M : unknown;
|
|
56
|
+
type OfWorkflow<D> = D extends WorkflowDefinition<string, infer M> ? M : unknown;
|
|
57
|
+
type HandlersOf<D> =
|
|
58
|
+
unknown extends OfObject<D> ? (unknown extends OfService<D> ? OfWorkflow<D> : OfService<D>) : OfObject<D>;
|
|
59
|
+
|
|
60
|
+
/** A client of `D`: each handler takes its input, if any, and returns its output. */
|
|
61
|
+
export type Client<D> = {
|
|
62
|
+
[K in keyof HandlersOf<D>]: HandlersOf<D>[K] extends (ctx: never, ...input: infer I) => PromiseLike<infer O>
|
|
63
|
+
? (...input: I) => Promise<O>
|
|
64
|
+
: never;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** A send client of `D`: each handler takes its input, if any. */
|
|
68
|
+
export type SendClient<D> = {
|
|
69
|
+
[K in keyof HandlersOf<D>]: HandlersOf<D>[K] extends (ctx: never, ...input: infer I) => unknown
|
|
70
|
+
? (...input: I) => void
|
|
71
|
+
: never;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Calls: `ctx.rpc(service)` or `ctx.rpc(object, key)` for a typed client, with
|
|
76
|
+
* the options of its calls last; or `ctx.rpc({ service, key, handler, input })`
|
|
77
|
+
* for a target known only at run time. A typed client of an object or a
|
|
78
|
+
* workflow needs its key, and one of a service has none: it fails at once
|
|
79
|
+
* otherwise. A literal target names no kind: its `key` is the caller's to give.
|
|
80
|
+
*/
|
|
81
|
+
export interface Rpc {
|
|
82
|
+
<D extends Definition>(target: D, options?: CallOptions): Client<D>;
|
|
83
|
+
<D extends Definition>(target: D, key: string, options?: CallOptions): Client<D>;
|
|
84
|
+
<O = unknown>(call: Target & CallOptions & { outputSerde?: Serde<O> }): Promise<O>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Sends, as {@link Rpc}'s calls: each returns at once, with nothing. */
|
|
88
|
+
export interface Send {
|
|
89
|
+
<D extends Definition>(target: D, options?: SendOptions): SendClient<D>;
|
|
90
|
+
<D extends Definition>(target: D, key: string, options?: SendOptions): SendClient<D>;
|
|
91
|
+
(send: Target & SendOptions): void;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** What a definition holds at run time, beside its name. */
|
|
95
|
+
type Defined = {
|
|
96
|
+
name: string;
|
|
97
|
+
_kind?: 'service' | 'object' | 'workflow';
|
|
98
|
+
_handlers?: Record<string, HandlerDescriptor>;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/** The target, key and options of a typed client's arguments. */
|
|
102
|
+
function clientOf(args: unknown[]): { def: Defined; key: string | undefined; options: SendOptions } {
|
|
103
|
+
const [def, second, third] = args as [Defined, unknown, unknown];
|
|
104
|
+
const key = typeof second === 'string' ? second : undefined;
|
|
105
|
+
const options = ((typeof second === 'string' ? third : second) ?? {}) as SendOptions;
|
|
106
|
+
const keyed = def._kind !== 'service';
|
|
107
|
+
if (keyed && key === undefined) {
|
|
108
|
+
throw new TerminalError(
|
|
109
|
+
`${def.name} is ${def._kind === 'workflow' ? 'a workflow' : 'an object'}: call it with its key`,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
if (!keyed && key !== undefined) throw new TerminalError(`${def.name} is a service: call it without a key`);
|
|
113
|
+
return { def, key, options };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Whether `value` is a literal target rather than a definition. */
|
|
117
|
+
const isLiteral = (value: unknown): value is Target =>
|
|
118
|
+
typeof (value as Target).handler === 'string' && typeof (value as Target).service === 'string';
|
|
119
|
+
|
|
120
|
+
/** A client whose methods make `call` of each one, with its input. */
|
|
121
|
+
function proxy(call: (method: string, input: unknown) => unknown): never {
|
|
122
|
+
return new Proxy(
|
|
123
|
+
{},
|
|
124
|
+
{
|
|
125
|
+
// Not a thenable: `await ctx.rpc(def, key)` gives the client, not a call of `then`.
|
|
126
|
+
get: (_, method) =>
|
|
127
|
+
typeof method === 'string' && method !== 'then' ? (input?: unknown) => call(method, input) : undefined,
|
|
128
|
+
},
|
|
129
|
+
) as never;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** `ctx.rpc` over the SDK context `ctx`. */
|
|
133
|
+
export function rpcOf(ctx: Pick<restate.Context, 'genericCall'>): Rpc {
|
|
134
|
+
return (...args: unknown[]) => {
|
|
135
|
+
if (isLiteral(args[0])) {
|
|
136
|
+
const { service, key, handler, input, inputSerde, outputSerde, idempotencyKey, headers } = args[0] as Target &
|
|
137
|
+
CallOptions & { outputSerde?: Serde<unknown> };
|
|
138
|
+
return ctx.genericCall({
|
|
139
|
+
service,
|
|
140
|
+
method: handler,
|
|
141
|
+
key,
|
|
142
|
+
parameter: input,
|
|
143
|
+
inputSerde: inputSerde ?? serde.json,
|
|
144
|
+
outputSerde: outputSerde ?? serde.json,
|
|
145
|
+
idempotencyKey,
|
|
146
|
+
headers,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
const { def, key, options } = clientOf(args);
|
|
150
|
+
return proxy((method, input) =>
|
|
151
|
+
ctx.genericCall({
|
|
152
|
+
service: def.name,
|
|
153
|
+
method,
|
|
154
|
+
key,
|
|
155
|
+
parameter: input,
|
|
156
|
+
inputSerde: def._handlers?.[method]?._inputSerde ?? serde.json,
|
|
157
|
+
outputSerde: def._handlers?.[method]?._outputSerde ?? serde.json,
|
|
158
|
+
idempotencyKey: options.idempotencyKey,
|
|
159
|
+
headers: options.headers,
|
|
160
|
+
}),
|
|
161
|
+
);
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** A send over `send`: `ctx.send` makes each at once, `tx.send` records it for its commit. */
|
|
166
|
+
export function sendOf(send: (send: restate.GenericSend<unknown>) => void): Send {
|
|
167
|
+
return ((...args: unknown[]) => {
|
|
168
|
+
if (isLiteral(args[0])) {
|
|
169
|
+
const { service, key, handler, input, inputSerde, idempotencyKey, headers, delay } = args[0] as Target &
|
|
170
|
+
SendOptions;
|
|
171
|
+
send({
|
|
172
|
+
service,
|
|
173
|
+
method: handler,
|
|
174
|
+
key,
|
|
175
|
+
parameter: input,
|
|
176
|
+
inputSerde: inputSerde ?? serde.json,
|
|
177
|
+
idempotencyKey,
|
|
178
|
+
headers,
|
|
179
|
+
delay,
|
|
180
|
+
});
|
|
181
|
+
return undefined;
|
|
182
|
+
}
|
|
183
|
+
const { def, key, options } = clientOf(args);
|
|
184
|
+
return proxy((method, input) => {
|
|
185
|
+
send({
|
|
186
|
+
service: def.name,
|
|
187
|
+
method,
|
|
188
|
+
key,
|
|
189
|
+
parameter: input,
|
|
190
|
+
inputSerde: def._handlers?.[method]?._inputSerde ?? serde.json,
|
|
191
|
+
idempotencyKey: options.idempotencyKey,
|
|
192
|
+
headers: options.headers,
|
|
193
|
+
delay: options.delay,
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
}) as Send;
|
|
197
|
+
}
|
package/src/database.ts
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
// A session's database, through the addon (`native/`): SQLite-compatible
|
|
2
|
+
// SQL, kept in the object's state. The addon reads and writes the state through a
|
|
3
|
+
// store (`objectStore` in session.ts), in the order it makes its requests
|
|
4
|
+
// (`native/src/node.rs`); this module orders the calls and runs transactions.
|
|
5
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
6
|
+
import { Buffer } from 'node:buffer';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import { PLATFORMS, platform } from './platform.ts';
|
|
9
|
+
|
|
10
|
+
/** An SQL value. Integers come back as numbers, or as bigints beyond 2^53. */
|
|
11
|
+
export type SqlValue = null | number | bigint | string | Uint8Array;
|
|
12
|
+
|
|
13
|
+
/** An SQL parameter: an `SqlValue`, or a boolean, stored as 0 or 1. */
|
|
14
|
+
export type SqlParam = SqlValue | boolean;
|
|
15
|
+
|
|
16
|
+
/** The rows of a statement, with its column names. */
|
|
17
|
+
export interface SqlQueryResult {
|
|
18
|
+
columns: string[];
|
|
19
|
+
rows: SqlValue[][];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A failure a retry would repeat: SQL the engine rejected (a syntax error, a
|
|
24
|
+
* constraint, a missing table), which undid just that statement and leaves
|
|
25
|
+
* the session usable; a parameter it cannot bind; or a call the session
|
|
26
|
+
* refused, which may have ended it (a `COMMIT` in a transaction's body, a
|
|
27
|
+
* transaction left open). A storage error, which ends the session, rejects
|
|
28
|
+
* as it is.
|
|
29
|
+
*/
|
|
30
|
+
export class SqlError extends Error {
|
|
31
|
+
override name = 'SqlError';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A row as an object, by column name. */
|
|
35
|
+
export type Row = Record<string, SqlValue>;
|
|
36
|
+
|
|
37
|
+
/** Reads of a database, or of one transaction of it. */
|
|
38
|
+
export interface DatabaseReader {
|
|
39
|
+
/**
|
|
40
|
+
* The rows of one statement, each an object by column name; parameters
|
|
41
|
+
* bind to a single statement. `T` declares the row's shape, unchecked:
|
|
42
|
+
* integers past 2^53 come back as bigints, and booleans as 0 or 1. Columns
|
|
43
|
+
* are named as SQL names them (an expression needs `AS`), and two of the
|
|
44
|
+
* same name are an {@link SqlError}: alias them, or use {@link values}.
|
|
45
|
+
*/
|
|
46
|
+
query<T = Row>(sql: string, params?: SqlParam[]): Promise<T[]>;
|
|
47
|
+
/** The first row of {@link query}, or `undefined` when there is none. */
|
|
48
|
+
get<T = Row>(sql: string, params?: SqlParam[]): Promise<T | undefined>;
|
|
49
|
+
/** The rows of one statement as arrays, in column order: for adapters, and for columns that share a name. */
|
|
50
|
+
values(sql: string, params?: SqlParam[]): Promise<SqlValue[][]>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** SQL: a database, or one transaction of it. */
|
|
54
|
+
export interface DatabaseWriter extends DatabaseReader {
|
|
55
|
+
/** Run SQL (one or more statements), discarding rows; parameters only with a single statement. */
|
|
56
|
+
execute(sql: string, params?: SqlParam[]): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The rows of `result` as objects by column name; a column name twice is an {@link SqlError}. */
|
|
60
|
+
function objects({ columns, rows }: SqlQueryResult): Row[] {
|
|
61
|
+
if (new Set(columns).size !== columns.length) {
|
|
62
|
+
const twice = columns.find((name, i) => columns.indexOf(name) !== i);
|
|
63
|
+
throw new SqlError(`the column ${twice} is named twice: alias one (AS), or read the rows with values()`);
|
|
64
|
+
}
|
|
65
|
+
return rows.map((row) => Object.fromEntries(columns.map((name, i) => [name, row[i]!])));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* {@link DatabaseWriter} over `run`, which runs one call's SQL and returns
|
|
70
|
+
* its rows with their columns, failing as `failure` makes its errors (as
|
|
71
|
+
* `run` makes the engine's).
|
|
72
|
+
*/
|
|
73
|
+
export function sqlOver(
|
|
74
|
+
run: (sql: string, params?: SqlParam[]) => Promise<SqlQueryResult>,
|
|
75
|
+
failure: (error: unknown) => unknown = (error) => error,
|
|
76
|
+
): DatabaseWriter {
|
|
77
|
+
const rowsOf = async (sql: string, params?: SqlParam[]) => {
|
|
78
|
+
const result = await run(sql, params);
|
|
79
|
+
try {
|
|
80
|
+
return objects(result);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
throw failure(error);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
query: async <T>(sql: string, params?: SqlParam[]) => (await rowsOf(sql, params)) as T[],
|
|
87
|
+
get: async <T>(sql: string, params?: SqlParam[]) => (await rowsOf(sql, params))[0] as T | undefined,
|
|
88
|
+
values: async (sql, params) => (await run(sql, params)).rows,
|
|
89
|
+
execute: async (sql, params) => void (await run(sql, params)),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* A key/value store, the object's state: `set` and `clear` return at once,
|
|
95
|
+
* and `sync` resolves once every write before it is stored. Writes are
|
|
96
|
+
* stored in the order they were made: a crash keeps a prefix of the writes
|
|
97
|
+
* since the last sync and loses the rest. `get` returns the stored value, or
|
|
98
|
+
* this request's own latest write; `undefined` or `null` when absent.
|
|
99
|
+
*/
|
|
100
|
+
export interface Store {
|
|
101
|
+
get(key: string): Promise<Uint8Array | null | undefined>;
|
|
102
|
+
set(key: string, value: Uint8Array): void;
|
|
103
|
+
clear(key: string): void;
|
|
104
|
+
sync(): Promise<void>;
|
|
105
|
+
/**
|
|
106
|
+
* Every key, as `ctx.stateKeys()`: then a commit that checkpoints deletes
|
|
107
|
+
* the packs no checkpoint needs any more. A store without it keeps them.
|
|
108
|
+
*/
|
|
109
|
+
keys?(): Promise<string[]>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The addon (`native/src/node.rs`). */
|
|
113
|
+
interface Addon {
|
|
114
|
+
open(namespace: string, store: Store, reader: boolean): Promise<NativeSession>;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* A session of the addon: one call at a time holds it. A transaction's body
|
|
119
|
+
* runs between `begin` and `commit` (or `rollback`). A call answers at once
|
|
120
|
+
* with its value (or throws) when it needs nothing from the store, such as
|
|
121
|
+
* SQL on cached pages, and with a promise when it waits for the store.
|
|
122
|
+
*/
|
|
123
|
+
interface NativeSession {
|
|
124
|
+
queryColumns(sql: string, params?: SqlParam[]): Answer<SqlQueryResult>;
|
|
125
|
+
begin(): Answer<void>;
|
|
126
|
+
commit(records: Record<string, Buffer>): Answer<void>;
|
|
127
|
+
rollback(): Answer<void>;
|
|
128
|
+
record(name: string): Answer<Buffer>;
|
|
129
|
+
isUsable(): boolean;
|
|
130
|
+
save(): Answer<void>;
|
|
131
|
+
close(): Promise<void>;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A value, or a promise of it: `await` takes either. */
|
|
135
|
+
type Answer<T> = T | Promise<T>;
|
|
136
|
+
|
|
137
|
+
const addon = load();
|
|
138
|
+
|
|
139
|
+
/** The addon of this machine's platform, from its package (see platform.ts). */
|
|
140
|
+
function load(): Addon {
|
|
141
|
+
const machine = platform();
|
|
142
|
+
const name = `@restatedev/sessions-${machine}`;
|
|
143
|
+
try {
|
|
144
|
+
return createRequire(import.meta.url)(name) as Addon;
|
|
145
|
+
} catch (error) {
|
|
146
|
+
if ((error as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') throw error;
|
|
147
|
+
throw new Error(
|
|
148
|
+
`@restatedev/sessions found no addon for ${machine}, the package ${name}: it ships them for ` +
|
|
149
|
+
`${PLATFORMS.join(', ')}. In its repository, \`pnpm build\` builds this machine's.`,
|
|
150
|
+
{ cause: error },
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Open the database of `namespace` over `store`. One process-wide page cache
|
|
157
|
+
* serves every namespace. A `reader` reads beside the namespace's owner (a
|
|
158
|
+
* shared handler), the state as of open, and writes nothing.
|
|
159
|
+
*/
|
|
160
|
+
export async function open(namespace: string, store: Store, { reader = false } = {}): Promise<Connection> {
|
|
161
|
+
return new Connection(await addon.open(namespace, store, reader));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* SQL on a session of the addon: {@link DatabaseWriter}'s `query` and `execute`
|
|
166
|
+
* by way of its `queryColumns`.
|
|
167
|
+
*/
|
|
168
|
+
abstract class Sql implements DatabaseWriter {
|
|
169
|
+
protected readonly native: NativeSession;
|
|
170
|
+
|
|
171
|
+
constructor(native: NativeSession) {
|
|
172
|
+
this.native = native;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
abstract queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult>;
|
|
176
|
+
|
|
177
|
+
query<T = Row>(sql: string, params?: SqlParam[]): Promise<T[]> {
|
|
178
|
+
return sqlOver((s, p) => this.queryColumns(s, p)).query<T>(sql, params);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
get<T = Row>(sql: string, params?: SqlParam[]): Promise<T | undefined> {
|
|
182
|
+
return sqlOver((s, p) => this.queryColumns(s, p)).get<T>(sql, params);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
values(sql: string, params?: SqlParam[]): Promise<SqlValue[][]> {
|
|
186
|
+
return sqlOver((s, p) => this.queryColumns(s, p)).values(sql, params);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async execute(sql: string, params?: SqlParam[]): Promise<void> {
|
|
190
|
+
await this.queryColumns(sql, params);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* `call`'s result, or its {@link failure}: `call` makes the request, as the
|
|
195
|
+
* addon throws as it is called (arguments it cannot convert, and the error
|
|
196
|
+
* of a call that answers at once).
|
|
197
|
+
*/
|
|
198
|
+
protected async request<T>(call: () => Answer<T>): Promise<T> {
|
|
199
|
+
try {
|
|
200
|
+
return await call();
|
|
201
|
+
} catch (error) {
|
|
202
|
+
throw this.failure(error);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A request's `error`: an {@link SqlError} if a retry would repeat it. */
|
|
207
|
+
protected failure(error: unknown): unknown {
|
|
208
|
+
if (error instanceof SqlError) return error;
|
|
209
|
+
const repeats = (error as { code?: unknown }).code === REFUSED || this.native.isUsable();
|
|
210
|
+
return repeats ? new SqlError((error as Error).message, { cause: error }) : error;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// The code of the addon's errors that a retry would repeat even though they
|
|
215
|
+
// ended the session (its `Refused`), and of arguments it cannot convert.
|
|
216
|
+
const REFUSED = 'InvalidArg';
|
|
217
|
+
|
|
218
|
+
// The transaction whose body is running, in that body's asynchronous context:
|
|
219
|
+
// the innermost, which knows the ones it runs inside.
|
|
220
|
+
const running = new AsyncLocalStorage<OpenTransaction>();
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* A session of a database: calls run one at a time, in call order, and a
|
|
224
|
+
* transaction holds the session until it commits or rolls back. Calls made
|
|
225
|
+
* meanwhile wait, but a call from inside the transaction's body is refused,
|
|
226
|
+
* as it would wait for that body: the body uses its `tx`.
|
|
227
|
+
*/
|
|
228
|
+
export class Connection extends Sql {
|
|
229
|
+
/** Settles once the last call queued so far has: the next call runs after it. */
|
|
230
|
+
private queue: Promise<unknown> = Promise.resolve();
|
|
231
|
+
|
|
232
|
+
queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult> {
|
|
233
|
+
return this.serial(() => this.request(() => this.native.queryColumns(sql, params)));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Run `body` as one SQL transaction: it commits when `body` resolves, with
|
|
238
|
+
* the records it set, and rolls back when it rejects, with the body's own
|
|
239
|
+
* error, once the calls it made have settled. A statement in it that ends
|
|
240
|
+
* the transaction (`COMMIT`, `ROLLBACK`) ends the session. A failing
|
|
241
|
+
* COMMIT rolls back.
|
|
242
|
+
*/
|
|
243
|
+
transaction<T>(body: (tx: ConnectionTransaction) => Promise<T>): Promise<T> {
|
|
244
|
+
return this.serial(async () => {
|
|
245
|
+
await this.request(() => this.native.begin());
|
|
246
|
+
const tx = new OpenTransaction(this, this.native, running.getStore());
|
|
247
|
+
let result: T;
|
|
248
|
+
try {
|
|
249
|
+
result = await running.run(tx, () => body(tx));
|
|
250
|
+
} catch (error) {
|
|
251
|
+
await tx.end();
|
|
252
|
+
await this.rollback();
|
|
253
|
+
throw error;
|
|
254
|
+
}
|
|
255
|
+
const records = await tx.end();
|
|
256
|
+
try {
|
|
257
|
+
await this.native.commit(records);
|
|
258
|
+
} catch (error) {
|
|
259
|
+
// A COMMIT that fails (a deferred constraint) leaves the transaction
|
|
260
|
+
// open: without the rollback, the calls after it would run inside it.
|
|
261
|
+
await this.rollback();
|
|
262
|
+
throw this.failure(error);
|
|
263
|
+
}
|
|
264
|
+
return result;
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The record `name`, as the last commit that set it left it (see
|
|
270
|
+
* {@link ConnectionTransaction.setRecord}); empty if none did.
|
|
271
|
+
*/
|
|
272
|
+
record(name: string): Promise<Uint8Array> {
|
|
273
|
+
return this.serial(async () => new Uint8Array(await this.request(() => this.native.record(name))));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Whether SQL can still run: an SQL error leaves the session usable, a storage error ends it. */
|
|
277
|
+
isUsable(): boolean {
|
|
278
|
+
return this.native.isUsable();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* End the session after the calls before it, leaving its engine to the
|
|
283
|
+
* next one. It rejects if they left a transaction open, or a failure ended
|
|
284
|
+
* the session.
|
|
285
|
+
*/
|
|
286
|
+
save(): Promise<void> {
|
|
287
|
+
return this.serial(() => this.request(() => this.native.save()));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** End the session now, whatever its state: queued calls reject. */
|
|
291
|
+
close(): Promise<void> {
|
|
292
|
+
return this.native.close();
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Run `call` once the calls before it have, unless it comes from the body of a transaction it would wait for. */
|
|
296
|
+
private serial<T>(call: () => Promise<T>): Promise<T> {
|
|
297
|
+
if (running.getStore()?.holds(this)) {
|
|
298
|
+
return Promise.reject(new SqlError('inside a transaction, use the transaction handle its body gets'));
|
|
299
|
+
}
|
|
300
|
+
const result = this.queue.then(call);
|
|
301
|
+
this.queue = result.catch(() => {});
|
|
302
|
+
return result;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Roll back, unless a storage error ended the session: the caller rethrows its own error, which says why. */
|
|
306
|
+
private async rollback(): Promise<void> {
|
|
307
|
+
try {
|
|
308
|
+
await this.native.rollback();
|
|
309
|
+
} catch {}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** SQL in one transaction, while its body runs, and the records it commits with. */
|
|
314
|
+
export interface ConnectionTransaction extends DatabaseWriter {
|
|
315
|
+
/** The rows of one statement, with their column names. */
|
|
316
|
+
queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult>;
|
|
317
|
+
/**
|
|
318
|
+
* Set the record `name` to `value` with this transaction, in the same
|
|
319
|
+
* write: a whole value kept beside the SQL, in no table, stored exactly
|
|
320
|
+
* when the transaction is, even if it changes no row. It stays until a
|
|
321
|
+
* later transaction sets it again; an empty value reads as never set. A
|
|
322
|
+
* name is at most 255 bytes, and not `db`; a value at most 16 MiB.
|
|
323
|
+
*/
|
|
324
|
+
setRecord(name: string, value: Uint8Array): void;
|
|
325
|
+
/** The record `name` as this transaction would commit it: as it set it, or as committed. */
|
|
326
|
+
record(name: string): Promise<Uint8Array>;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* A {@link ConnectionTransaction} of {@link Connection.transaction}, open until its body
|
|
331
|
+
* settles. Its calls run one at a time, in call order, also when the body
|
|
332
|
+
* awaits several together, or none: each call made while it is open runs
|
|
333
|
+
* before its commit or rollback, so none outlives it.
|
|
334
|
+
*/
|
|
335
|
+
class OpenTransaction extends Sql implements ConnectionTransaction {
|
|
336
|
+
private readonly database: Connection;
|
|
337
|
+
/** The transaction whose body this one's runs in, if any: of another database, since a database's own are refused. */
|
|
338
|
+
private readonly outer: OpenTransaction | undefined;
|
|
339
|
+
/** The records it sets, by name. */
|
|
340
|
+
private readonly records = new Map<string, Buffer>();
|
|
341
|
+
/** Settles once the last call queued so far has: the next call runs after it. */
|
|
342
|
+
private queue: Promise<unknown> = Promise.resolve();
|
|
343
|
+
private ended = false;
|
|
344
|
+
|
|
345
|
+
constructor(database: Connection, native: NativeSession, outer: OpenTransaction | undefined) {
|
|
346
|
+
super(native);
|
|
347
|
+
this.database = database;
|
|
348
|
+
this.outer = outer;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** Whether this transaction, or one it runs inside, is open and holds `database`. */
|
|
352
|
+
holds(database: Connection): boolean {
|
|
353
|
+
return (!this.ended && this.database === database) || (this.outer?.holds(database) ?? false);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* End it, refusing calls from now on, once the calls made before have
|
|
358
|
+
* settled; then the records it set, as the addon's commit takes them.
|
|
359
|
+
*/
|
|
360
|
+
async end(): Promise<Record<string, Buffer>> {
|
|
361
|
+
this.ended = true;
|
|
362
|
+
await this.queue;
|
|
363
|
+
return Object.fromEntries(this.records);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
queryColumns(sql: string, params?: SqlParam[]): Promise<SqlQueryResult> {
|
|
367
|
+
return this.serial(() => this.request(() => this.native.queryColumns(sql, params)));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
setRecord(name: string, value: Uint8Array): void {
|
|
371
|
+
this.refuseEnded();
|
|
372
|
+
this.records.set(name, Buffer.from(value));
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
record(name: string): Promise<Uint8Array> {
|
|
376
|
+
// As set when it is called, in call order with `setRecord`.
|
|
377
|
+
const set = this.records.get(name);
|
|
378
|
+
return this.serial(async () => new Uint8Array(set ?? (await this.request(() => this.native.record(name)))));
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Run `call`, made while the transaction is open, once the calls before it have. */
|
|
382
|
+
private serial<T>(call: () => Promise<T>): Promise<T> {
|
|
383
|
+
if (this.ended) return Promise.reject(new SqlError('the transaction has ended'));
|
|
384
|
+
const result = this.queue.then(call);
|
|
385
|
+
this.queue = result.catch(() => {});
|
|
386
|
+
return result;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
private refuseEnded(): void {
|
|
390
|
+
if (this.ended) throw new SqlError('the transaction has ended');
|
|
391
|
+
}
|
|
392
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Session objects: Restate virtual objects whose state is a SQL database per
|
|
2
|
+
// key. It is the Restate SDK, with `restate.sessionObject` beside its own
|
|
3
|
+
// objects, services and workflows:
|
|
4
|
+
//
|
|
5
|
+
// import * as restate from '@restatedev/sessions';
|
|
6
|
+
//
|
|
7
|
+
// const notes = restate.sessionObject({
|
|
8
|
+
// name: 'notes',
|
|
9
|
+
// schema: ['CREATE TABLE notes (text TEXT NOT NULL)'],
|
|
10
|
+
// handlers: {
|
|
11
|
+
// add: async (ctx, text: string) => {
|
|
12
|
+
// await ctx.db.execute('INSERT INTO notes (text) VALUES (?)', [text]);
|
|
13
|
+
// },
|
|
14
|
+
// },
|
|
15
|
+
// views: {
|
|
16
|
+
// list: async (ctx) => ctx.db.query<{ text: string }>('SELECT text FROM notes'),
|
|
17
|
+
// },
|
|
18
|
+
// });
|
|
19
|
+
//
|
|
20
|
+
// See README.md.
|
|
21
|
+
|
|
22
|
+
// The SDK, and what this module adds to it (or declares in its place: its
|
|
23
|
+
// `Client`, `SendClient` and `Target` are a session object's).
|
|
24
|
+
export * from '@restatedev/restate-sdk';
|
|
25
|
+
export type { Database, DatabaseReader, DatabaseWriter, Row, SqlParam, SqlValue, Transaction } from './session.ts';
|
|
26
|
+
export type { Step } from './schema.ts';
|
|
27
|
+
export {
|
|
28
|
+
sessionObject,
|
|
29
|
+
type Cancel,
|
|
30
|
+
type Entry,
|
|
31
|
+
type HandlerOptions,
|
|
32
|
+
type SessionContext,
|
|
33
|
+
type ViewContext,
|
|
34
|
+
} from './object.ts';
|
|
35
|
+
export type { CallOptions, Client, Rpc, Send, SendClient, SendOptions, Target } from './calls.ts';
|
package/src/internal.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// For tests: an attempt's session over a context of their own, the store's
|
|
2
|
+
// fault injection, a database over a store of their own, and the selector on
|
|
3
|
+
// its own. For this repository's libraries: the schemas their tables are in,
|
|
4
|
+
// databases of their own, and the Restate SDK as @restatedev/sessions runs it (its
|
|
5
|
+
// own copy, so that a library's journaled handlers serve beside its objects).
|
|
6
|
+
export * as sdk from '@restatedev/restate-sdk';
|
|
7
|
+
export { Schema } from './schema.ts';
|
|
8
|
+
export { asDatabase, lazyDatabase, database, reset, setStoreWrapper, Attempt, withAttempt } from './session.ts';
|
|
9
|
+
export type { SqlHost } from './session.ts';
|
|
10
|
+
export { open, type Connection, type Store, type ConnectionTransaction } from './database.ts';
|
|
11
|
+
export { PromiseSelector } from './selector.ts';
|
|
12
|
+
export { cancelCalls, cancelled, contextOf, HEAD_KEY, invoke, type AttemptContext } from './object.ts';
|
|
13
|
+
export type { DoProgressResult, Selectable, UnresolvedFuture } from './selector.ts';
|