@restatedev/sessions 0.9.0 → 0.10.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 +52 -26
- package/dist/addon.d.ts +9 -0
- package/dist/addon.d.ts.map +1 -0
- package/dist/addon.js +20 -0
- package/dist/addon.js.map +1 -0
- package/dist/database.d.ts +13 -0
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +44 -17
- package/dist/database.js.map +1 -1
- package/dist/driver.d.ts +186 -0
- package/dist/driver.d.ts.map +1 -0
- package/dist/driver.js +549 -0
- package/dist/driver.js.map +1 -0
- package/dist/endpoint.d.ts +13 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/endpoint.js +186 -0
- package/dist/endpoint.js.map +1 -0
- package/dist/handler.d.ts +35 -0
- package/dist/handler.d.ts.map +1 -0
- package/dist/handler.js +218 -0
- package/dist/handler.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +4 -2
- package/dist/internal.d.ts.map +1 -1
- package/dist/internal.js +7 -3
- package/dist/internal.js.map +1 -1
- package/dist/object.d.ts +15 -2
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +51 -12
- package/dist/object.js.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/serve.js +5 -0
- package/dist/serve.js.map +1 -1
- package/dist/session.d.ts +32 -2
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +59 -9
- package/dist/session.js.map +1 -1
- package/dist/vm.d.ts +151 -0
- package/dist/vm.d.ts.map +1 -0
- package/dist/vm.js +28 -0
- package/dist/vm.js.map +1 -0
- package/package.json +4 -4
- package/src/addon.ts +29 -0
- package/src/database.ts +48 -19
- package/src/driver.ts +653 -0
- package/src/endpoint.ts +220 -0
- package/src/handler.ts +272 -0
- package/src/index.ts +2 -1
- package/src/internal.ts +7 -4
- package/src/object.ts +75 -13
- package/src/serve.ts +5 -0
- package/src/session.ts +77 -8
- package/src/vm.ts +195 -0
- package/dist/selector.d.ts +0 -129
- package/dist/selector.d.ts.map +0 -1
- package/dist/selector.js +0 -251
- package/dist/selector.js.map +0 -1
- package/src/selector.ts +0 -323
package/src/endpoint.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Every invocation of a session object runs on the explicit recovery VM
|
|
2
|
+
// (`handler.ts`), whichever way its deployment is served.
|
|
3
|
+
//
|
|
4
|
+
// The SDK builds its own VM per invocation, and the dispatch that does it is
|
|
5
|
+
// module-private: there is no supported seam. What every transport does share
|
|
6
|
+
// is one class — `restate.endpoint()` returns a `NodeEndpoint`, and the tunnel
|
|
7
|
+
// behind `connect` builds `new NodeEndpoint()` of its own — and the request
|
|
8
|
+
// handler it hands out. So this wraps that class's four ways of producing one.
|
|
9
|
+
//
|
|
10
|
+
// It is a patch on another package's prototype, which is worth naming plainly.
|
|
11
|
+
// It touches four methods whose contract is "give me a request handler", and
|
|
12
|
+
// the handler it returns is the SDK's own for everything but a session
|
|
13
|
+
// object. The alternative it replaced was larger: reaching into five private
|
|
14
|
+
// fields of the SDK's promise executor to drive its VM by hand.
|
|
15
|
+
import * as http2 from 'node:http2';
|
|
16
|
+
import type { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
|
|
17
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
18
|
+
import * as restate from '@restatedev/restate-sdk';
|
|
19
|
+
import { MIN_PROTOCOL, servedHere, serveSession, type Stream } from './handler.ts';
|
|
20
|
+
import { isSessionObject } from './object.ts';
|
|
21
|
+
import { Identity, type VmHeader } from './vm.ts';
|
|
22
|
+
|
|
23
|
+
/** Marks the prototype this package has already wrapped. */
|
|
24
|
+
const PATCHED = Symbol.for('restate-sessions.endpoint-patched') as unknown as string;
|
|
25
|
+
|
|
26
|
+
/** What this package needs of the SDK's endpoint, which its types do not say. */
|
|
27
|
+
interface Endpoint {
|
|
28
|
+
builder: {
|
|
29
|
+
serviceDefinitions: Map<string, object>;
|
|
30
|
+
keySet: string[];
|
|
31
|
+
journalValueCodecProvider?: unknown;
|
|
32
|
+
};
|
|
33
|
+
handler(options?: { bidirectional?: boolean }): (request: never, response: never) => void;
|
|
34
|
+
http2Handler(options?: { bidirectional?: boolean }): (request: never, response: never) => void;
|
|
35
|
+
http1Handler(options?: { bidirectional?: boolean }): (request: never, response: never) => void;
|
|
36
|
+
listen(port?: number): Promise<number>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The session objects bound to `endpoint`, by name. */
|
|
40
|
+
function sessionsOf(endpoint: Endpoint): Map<string, { name: string }> {
|
|
41
|
+
const bound = new Map<string, { name: string }>();
|
|
42
|
+
for (const [name, definition] of endpoint.builder.serviceDefinitions) {
|
|
43
|
+
if (isSessionObject(definition)) bound.set(name, definition as { name: string });
|
|
44
|
+
}
|
|
45
|
+
return bound;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What an endpoint with session objects cannot also have. Each would need a
|
|
50
|
+
* second way of running an attempt, and there is none any more.
|
|
51
|
+
*/
|
|
52
|
+
function refuseWhatTheVmCannotServe(endpoint: Endpoint, sessions: Map<string, unknown>): void {
|
|
53
|
+
if (sessions.size === 0) return;
|
|
54
|
+
if (endpoint.builder.journalValueCodecProvider !== undefined) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
'@restatedev/sessions: a journal value codec is not supported for session objects: ' +
|
|
57
|
+
'their attempts are never replayed, and nothing of theirs is journaled to encode',
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The request's headers, as the verifier takes them. */
|
|
63
|
+
function headersOf(headers: Readonly<Record<string, string | string[] | undefined>>): VmHeader[] {
|
|
64
|
+
return Object.entries(headers).flatMap(([key, value]) =>
|
|
65
|
+
value === undefined ? [] : [{ key, value: Array.isArray(value) ? (value[0] ?? '') : value }],
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** One invocation over HTTP/2, as {@link Stream}. */
|
|
70
|
+
function streamOf(request: Http2ServerRequest, response: Http2ServerResponse): Stream {
|
|
71
|
+
return {
|
|
72
|
+
headers: request.headers,
|
|
73
|
+
body: request,
|
|
74
|
+
writeHead: (status, headers) => void response.writeHead(status, headers),
|
|
75
|
+
write: (chunk) => void response.write(chunk),
|
|
76
|
+
close: () => void response.end(),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* The path of `url` and the route it names, as the SDK reads it: the last
|
|
82
|
+
* three fragments. Nothing if it names no invocation, or is no path at all —
|
|
83
|
+
* `//` is a URL with an empty host, which `URL` refuses. Restate sends none
|
|
84
|
+
* of those, but anything that reaches the port can, and this runs in the
|
|
85
|
+
* request listener, where a throw is an `uncaughtException`.
|
|
86
|
+
*/
|
|
87
|
+
function parse(url: string): { path: string; service: string; handler: string } | undefined {
|
|
88
|
+
let path;
|
|
89
|
+
try {
|
|
90
|
+
path = new URL(url, 'http://invoke').pathname;
|
|
91
|
+
} catch {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
const parts = path.split('/');
|
|
95
|
+
if (parts.length < 3 || parts[parts.length - 3] !== 'invoke') return undefined;
|
|
96
|
+
const service = parts[parts.length - 2]!;
|
|
97
|
+
const handler = parts[parts.length - 1]!;
|
|
98
|
+
return service === '' || handler === '' ? undefined : { path, service, handler };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The route of an invocation's path, as the SDK reads it. */
|
|
102
|
+
export function invokeRoute(url: string): { service: string; handler: string } | undefined {
|
|
103
|
+
const route = parse(url);
|
|
104
|
+
return route === undefined ? undefined : { service: route.service, handler: route.handler };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* `sdk`, with a session object's invocations run on the VM instead. A request
|
|
109
|
+
* that is not one — discovery, the health check, a library's journaled objects
|
|
110
|
+
* — is the SDK's, unchanged.
|
|
111
|
+
*/
|
|
112
|
+
function routing(
|
|
113
|
+
endpoint: Endpoint,
|
|
114
|
+
sdk: (request: never, response: never) => void,
|
|
115
|
+
bidirectional: (request: { httpVersionMajor?: number }) => boolean,
|
|
116
|
+
): (request: Http2ServerRequest | IncomingMessage, response: Http2ServerResponse | ServerResponse) => void {
|
|
117
|
+
const sessions = sessionsOf(endpoint);
|
|
118
|
+
refuseWhatTheVmCannotServe(endpoint, sessions);
|
|
119
|
+
// The SDK verifies a request's signature in the handler this routes ahead
|
|
120
|
+
// of, so an invocation that goes to the VM is verified here instead. Every
|
|
121
|
+
// `connect` has keys: its key carries the signing key, and the SDK refuses
|
|
122
|
+
// one that does not.
|
|
123
|
+
const identity = endpoint.builder.keySet.length > 0 ? new Identity(endpoint.builder.keySet) : undefined;
|
|
124
|
+
return (request, response) => {
|
|
125
|
+
const route = sessions.size === 0 ? undefined : parse(request.url ?? '');
|
|
126
|
+
const definition = route === undefined ? undefined : sessions.get(route.service);
|
|
127
|
+
if (definition === undefined || route === undefined) {
|
|
128
|
+
sdk(request as never, response as never);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const { path } = route;
|
|
132
|
+
// `null` is a verified request, as the addon answers `None` with: a
|
|
133
|
+
// deployment without keys verifies nothing, and stands for the same.
|
|
134
|
+
const unsigned = identity === undefined ? null : identity.verify(path, headersOf(request.headers));
|
|
135
|
+
if (unsigned !== null) {
|
|
136
|
+
// What the SDK answers, and the handler never runs.
|
|
137
|
+
(response as Http2ServerResponse).writeHead(401, { 'content-type': 'text/plain' });
|
|
138
|
+
response.end('Unauthorized');
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
// After the signature check, so that an unsigned request learns nothing
|
|
142
|
+
// about what is bound here: the SDK answers one 401 for anything.
|
|
143
|
+
if (!servedHere(request.headers)) {
|
|
144
|
+
// A session object on a Restate too old for the VM. Handing it to the
|
|
145
|
+
// SDK would run it on a VM that replays, which such a handler cannot
|
|
146
|
+
// use; it would be refused there for the wrong reason, naming endpoint
|
|
147
|
+
// types to someone whose endpoint is fine. Say which it is.
|
|
148
|
+
const type = request.headers['content-type'];
|
|
149
|
+
const spoken = /\.invocation\.(v\d+)/.exec((Array.isArray(type) ? type[0] : type) ?? '')?.[1] ?? 'none';
|
|
150
|
+
(response as Http2ServerResponse).writeHead(415, { 'content-type': 'text/plain' });
|
|
151
|
+
response.end(
|
|
152
|
+
`@restatedev/sessions: ${route.service}/${route.handler} is a session object, which runs on the ` +
|
|
153
|
+
`explicit recovery VM and needs Restate's service protocol v${MIN_PROTOCOL} or later; this ` +
|
|
154
|
+
`invocation negotiated ${spoken}. Upgrade the Restate server.`,
|
|
155
|
+
);
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
serveSession(definition, route.handler, streamOf(request as Http2ServerRequest, response as Http2ServerResponse), {
|
|
159
|
+
bidirectional: bidirectional(request),
|
|
160
|
+
}).catch((error: unknown) => {
|
|
161
|
+
// The attempt could not be served at all: the VM wrote nothing.
|
|
162
|
+
if (!response.headersSent) (response as Http2ServerResponse).writeHead(500, { 'content-type': 'text/plain' });
|
|
163
|
+
response.end(error instanceof Error ? error.message : String(error));
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Wrap the SDK's endpoint class, once per process, so that every request
|
|
170
|
+
* handler it hands out routes a session object's invocations to the VM.
|
|
171
|
+
* Called by {@link sessionObject}: the package declares `sideEffects: false`,
|
|
172
|
+
* so this cannot be the work of an import.
|
|
173
|
+
*/
|
|
174
|
+
export function patchEndpoint(): void {
|
|
175
|
+
const prototype = Object.getPrototypeOf(restate.endpoint()) as Record<string, unknown>;
|
|
176
|
+
if (prototype[PATCHED] === true) return;
|
|
177
|
+
const missing = (['handler', 'http2Handler', 'http1Handler', 'listen'] as const).filter(
|
|
178
|
+
(method) => typeof prototype[method] !== 'function',
|
|
179
|
+
);
|
|
180
|
+
if (missing.length > 0) {
|
|
181
|
+
throw new Error(
|
|
182
|
+
`@restatedev/sessions runs a session object's invocations by wrapping the SDK's endpoint, which this SDK ` +
|
|
183
|
+
`version does not have (${missing.join(', ')}): use the @restatedev/restate-sdk that @restatedev/sessions pins`,
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// The SDK's own defaults: HTTP/2 is bidirectional unless told otherwise,
|
|
188
|
+
// HTTP/1.1 only when asked.
|
|
189
|
+
const wrap = (
|
|
190
|
+
method: 'handler' | 'http2Handler' | 'http1Handler',
|
|
191
|
+
mode: (set: boolean | undefined, request: { httpVersionMajor?: number }) => boolean,
|
|
192
|
+
) => {
|
|
193
|
+
const original = prototype[method] as Endpoint['handler'];
|
|
194
|
+
prototype[method] = function (this: Endpoint, options?: { bidirectional?: boolean }) {
|
|
195
|
+
const sdk = original.call(this, options);
|
|
196
|
+
return routing(this, sdk, (request) => mode(options?.bidirectional, request)) as never;
|
|
197
|
+
};
|
|
198
|
+
};
|
|
199
|
+
// `handler` dispatches per request, so the rule is the one for that
|
|
200
|
+
// request's protocol; a handler built for one protocol knows it already.
|
|
201
|
+
wrap('handler', (set, request) => ((request.httpVersionMajor ?? 2) >= 2 ? set !== false : set === true));
|
|
202
|
+
wrap('http2Handler', (set) => set !== false);
|
|
203
|
+
wrap('http1Handler', (set) => set === true);
|
|
204
|
+
|
|
205
|
+
// `listen` builds its server from the module's own handler, not from
|
|
206
|
+
// `http2Handler`, so wrapping it is building the server here.
|
|
207
|
+
prototype.listen = function (this: Endpoint, port?: number): Promise<number> {
|
|
208
|
+
const chosen = port ?? Number(process.env.PORT ?? 9080);
|
|
209
|
+
const server = http2.createServer(this.http2Handler() as never);
|
|
210
|
+
return new Promise<number>((resolve, reject) => {
|
|
211
|
+
server.once('error', reject);
|
|
212
|
+
server.listen(chosen, () => {
|
|
213
|
+
const address = server.address();
|
|
214
|
+
if (address === null || typeof address === 'string') reject(new TypeError('listen binds to a port'));
|
|
215
|
+
else resolve(address.port);
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
};
|
|
219
|
+
prototype[PATCHED] = true;
|
|
220
|
+
}
|
package/src/handler.ts
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// Serving one invocation of a session object's handler on the explicit
|
|
2
|
+
// recovery VM (`driver.ts`), rather than through the SDK's journaled context,
|
|
3
|
+
// which replays and would hold such a handler to one await at a time.
|
|
4
|
+
//
|
|
5
|
+
// The core takes a stream — the request's headers and body, and where to write
|
|
6
|
+
// the response — so that a test can drive it with wire bytes and `serve.ts`
|
|
7
|
+
// can hand it an HTTP/2 one. It is reached only for a session object's
|
|
8
|
+
// handler; everything else a deployment serves stays the SDK's.
|
|
9
|
+
import * as restate from '@restatedev/restate-sdk';
|
|
10
|
+
import { millisOrDurationToMillis, type Serde } from '@restatedev/restate-sdk-core';
|
|
11
|
+
import { AttemptDriver, AttemptFailed, AttemptShutDown } from './driver.ts';
|
|
12
|
+
import { handlerEntry, invoke, type AttemptContext } from './object.ts';
|
|
13
|
+
import { Vm, type VmHeader } from './vm.ts';
|
|
14
|
+
|
|
15
|
+
/** The lowest service protocol version the VM accepts; the SDK serves anything below. */
|
|
16
|
+
export const MIN_PROTOCOL = 7;
|
|
17
|
+
|
|
18
|
+
/** One invocation on the wire: what the core reads, and where it writes. */
|
|
19
|
+
export interface Stream {
|
|
20
|
+
readonly headers: Readonly<Record<string, string | string[] | undefined>>;
|
|
21
|
+
/** The request body, which only the input pump reads. */
|
|
22
|
+
readonly body: AsyncIterable<Uint8Array>;
|
|
23
|
+
writeHead(status: number, headers: Record<string, string>): void;
|
|
24
|
+
write(chunk: Uint8Array): void;
|
|
25
|
+
/** The response body ends. */
|
|
26
|
+
close(): void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Whether this package serves `headers`' invocation, or the SDK does. The VM
|
|
31
|
+
* accepts the service protocol V7 and V8 only.
|
|
32
|
+
*
|
|
33
|
+
* A Restate that speaks less once reached the SDK's VM through the selector.
|
|
34
|
+
* That is gone, and a session object cannot run on a VM that replays, so an
|
|
35
|
+
* older server cannot serve one at all: `endpoint.ts` answers such an
|
|
36
|
+
* invocation itself rather than handing it on. Everything that is not a
|
|
37
|
+
* session object is still the SDK's at any version it supports.
|
|
38
|
+
*/
|
|
39
|
+
export function servedHere(headers: Readonly<Record<string, string | string[] | undefined>>): boolean {
|
|
40
|
+
const type = headers['content-type'];
|
|
41
|
+
const match = /application\/vnd\.restate\.invocation\.v(\d+)/.exec((Array.isArray(type) ? type[0] : type) ?? '');
|
|
42
|
+
return match !== null && Number(match[1]) >= MIN_PROTOCOL;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** `headers` as the VM takes them. */
|
|
46
|
+
function vmHeaders(headers: Readonly<Record<string, string | string[] | undefined>>): VmHeader[] {
|
|
47
|
+
return Object.entries(headers).flatMap(([key, value]) =>
|
|
48
|
+
value === undefined ? [] : [{ key, value: Array.isArray(value) ? (value[0] ?? '') : value }],
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Run one attempt of `definition`'s handler `name` over `stream`, and end its
|
|
54
|
+
* response. `bidirectional` is false on a request/response transport, which
|
|
55
|
+
* cannot serve such a handler: the VM fails the invocation at once, pausing
|
|
56
|
+
* it, since no response could reach it.
|
|
57
|
+
*/
|
|
58
|
+
export async function serveSession(
|
|
59
|
+
definition: { name: string },
|
|
60
|
+
name: string,
|
|
61
|
+
stream: Stream,
|
|
62
|
+
{ bidirectional = true } = {},
|
|
63
|
+
): Promise<void> {
|
|
64
|
+
const entry = handlerEntry(definition, name);
|
|
65
|
+
if (entry === undefined) throw new Error(`${definition.name}/${name} is no handler or view of a session object`);
|
|
66
|
+
|
|
67
|
+
const vm = new Vm(vmHeaders(stream.headers), bidirectional);
|
|
68
|
+
const head = vm.getResponseHead();
|
|
69
|
+
stream.writeHead(head.statusCode, Object.fromEntries(head.headers.map(({ key, value }) => [key, value])));
|
|
70
|
+
|
|
71
|
+
const driver = new AttemptDriver(vm, (chunk) => stream.write(chunk), {
|
|
72
|
+
service: definition.name,
|
|
73
|
+
handler: name,
|
|
74
|
+
shared: entry.view,
|
|
75
|
+
explicitCancellation: entry.explicit,
|
|
76
|
+
});
|
|
77
|
+
// The database's store acts on the VM from the runtime's thread, in the
|
|
78
|
+
// addon; this is how it asks for the tick that writes what it sent.
|
|
79
|
+
vm.setScheduler(() => driver.scheduleTick());
|
|
80
|
+
|
|
81
|
+
// The input pump: the only reader of the request body. It runs until the
|
|
82
|
+
// body ends, beside the handler.
|
|
83
|
+
const ready = Promise.withResolvers<void>();
|
|
84
|
+
ready.promise.catch(() => {});
|
|
85
|
+
const pump = (async () => {
|
|
86
|
+
try {
|
|
87
|
+
for await (const chunk of stream.body) {
|
|
88
|
+
driver.notifyInput(chunk);
|
|
89
|
+
if (driver.isReadyToExecute()) ready.resolve();
|
|
90
|
+
}
|
|
91
|
+
} catch {
|
|
92
|
+
// The peer went away; the end of the body says the same.
|
|
93
|
+
} finally {
|
|
94
|
+
driver.notifyInputClosed();
|
|
95
|
+
// Ready or not, nothing more is coming.
|
|
96
|
+
ready.resolve();
|
|
97
|
+
}
|
|
98
|
+
})();
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
await ready.promise;
|
|
102
|
+
if (driver.over !== undefined || !driver.isReadyToExecute()) return;
|
|
103
|
+
driver.startHeartbeats();
|
|
104
|
+
// Input this handler cannot read will not read on the next attempt
|
|
105
|
+
// either: a terminal failure ends the invocation, where a retryable one
|
|
106
|
+
// would have Restate send the same bytes forever. The SDK's own handler
|
|
107
|
+
// does the same for input its journal codec cannot decode.
|
|
108
|
+
let input: unknown;
|
|
109
|
+
try {
|
|
110
|
+
input = entry.inputSerde.deserialize(driver.body);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
throw new restate.TerminalError(`failed to deserialize the input: ${(error as Error).message}`, {
|
|
113
|
+
errorCode: 400,
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
const output = await invoke(definition, name, contextOf(driver, stream.headers, vm), input);
|
|
117
|
+
// A cancellation that arrived while the handler ran is still cancelling
|
|
118
|
+
// its calls: they go out before the attempt ends, or not at all.
|
|
119
|
+
await driver.cancellingCalls;
|
|
120
|
+
driver.endSuccess(entry.outputSerde.serialize(output));
|
|
121
|
+
} catch (error) {
|
|
122
|
+
await driver.cancellingCalls;
|
|
123
|
+
endWith(driver, error, entry.asTerminalError);
|
|
124
|
+
} finally {
|
|
125
|
+
await pump;
|
|
126
|
+
// The attempt's last words are buffered: a turn lets the tick write them.
|
|
127
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
128
|
+
stream.close();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** End the attempt the way `error` says to. */
|
|
133
|
+
function endWith(driver: AttemptDriver, error: unknown, asTerminalError?: (error: unknown) => Error | undefined): void {
|
|
134
|
+
if (error instanceof AttemptShutDown) return; // the attempt is over; nothing more is sent
|
|
135
|
+
// The handler option of the same name: an error it names ends the
|
|
136
|
+
// invocation rather than being retried. The SDK applies it, so this does.
|
|
137
|
+
if (asTerminalError !== undefined && !(error instanceof restate.TerminalError)) {
|
|
138
|
+
const terminal = asTerminalError(error);
|
|
139
|
+
if (terminal !== undefined) {
|
|
140
|
+
driver.endFailure(
|
|
141
|
+
terminal instanceof restate.TerminalError ? terminal : new restate.TerminalError(terminal.message),
|
|
142
|
+
);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (error instanceof restate.TerminalError) {
|
|
147
|
+
driver.endFailure(error);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (error instanceof AttemptFailed) return; // the VM wrote why
|
|
151
|
+
const retryable = error as { retryAfter?: number };
|
|
152
|
+
const thrown = error instanceof Error ? error : new Error(String(error));
|
|
153
|
+
driver.fail(thrown.message, thrown.stack, retryable.retryAfter);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* What `invoke` needs of a handler's context, over `driver`: the members of
|
|
158
|
+
* the SDK's that a session object's attempt uses, and no others.
|
|
159
|
+
*/
|
|
160
|
+
function contextOf(
|
|
161
|
+
driver: AttemptDriver,
|
|
162
|
+
attemptHeaders: Readonly<Record<string, string | string[] | undefined>>,
|
|
163
|
+
vm: Vm,
|
|
164
|
+
): AttemptContext {
|
|
165
|
+
const headers = new Map(Object.entries(attemptHeaders));
|
|
166
|
+
const request = driver.request(headers);
|
|
167
|
+
|
|
168
|
+
/** The attempt's end, as `invocationEndPromise` gives it: a promise that rejects. */
|
|
169
|
+
const ending = Promise.withResolvers<never>();
|
|
170
|
+
ending.promise.catch(() => {});
|
|
171
|
+
driver.whenEnded(() => ending.reject(driver.over ?? new AttemptShutDown()));
|
|
172
|
+
|
|
173
|
+
const context = {
|
|
174
|
+
key: driver.key,
|
|
175
|
+
request: () => request,
|
|
176
|
+
// The object's state is the addon's: it reads and writes it as the VM's
|
|
177
|
+
// own commands, so nothing of it is implemented here. A session opened on
|
|
178
|
+
// a VM never asks (see `commitOnly` in `session.ts`); anything else that
|
|
179
|
+
// does is a mistake, and says so.
|
|
180
|
+
get: servedByVm('get'),
|
|
181
|
+
set: servedByVm('set'),
|
|
182
|
+
clear: servedByVm('clear'),
|
|
183
|
+
stateKeys: servedByVm('stateKeys'),
|
|
184
|
+
run: () => {
|
|
185
|
+
throw new restate.TerminalError(
|
|
186
|
+
'a session object has no ctx.run: put journaled work in a restate.object, service or workflow, and call it with ctx.rpc',
|
|
187
|
+
);
|
|
188
|
+
},
|
|
189
|
+
genericCall: (call: GenericCall) => {
|
|
190
|
+
const { result, invocationId } = driver.call({
|
|
191
|
+
service: call.service,
|
|
192
|
+
handler: call.method,
|
|
193
|
+
key: call.key,
|
|
194
|
+
input: (call.inputSerde ?? restate.serde.json).serialize(call.parameter),
|
|
195
|
+
idempotencyKey: call.idempotencyKey,
|
|
196
|
+
headers: Object.entries(call.headers ?? {}).map(([key, value]) => ({ key, value })),
|
|
197
|
+
});
|
|
198
|
+
// Marked handled: `start()` awaits only the invocation id, so nothing
|
|
199
|
+
// holds this, and it rejects when the callee fails, on a cancellation,
|
|
200
|
+
// and at the end of every attempt — including a successful one.
|
|
201
|
+
const answered = quiet(
|
|
202
|
+
result.then((value) => (call.outputSerde ?? restate.serde.json).deserialize(value ?? new Uint8Array())),
|
|
203
|
+
);
|
|
204
|
+
return Object.assign(answered, { invocationId });
|
|
205
|
+
},
|
|
206
|
+
genericSend: (send: GenericSend) =>
|
|
207
|
+
void driver.send({
|
|
208
|
+
service: send.service,
|
|
209
|
+
handler: send.method,
|
|
210
|
+
key: send.key,
|
|
211
|
+
input: (send.inputSerde ?? restate.serde.json).serialize(send.parameter),
|
|
212
|
+
// `SendOptions.delay` is milliseconds or a `Duration`; the VM takes
|
|
213
|
+
// milliseconds.
|
|
214
|
+
delay: send.delay === undefined ? undefined : millisOrDurationToMillis(send.delay),
|
|
215
|
+
idempotencyKey: send.idempotencyKey,
|
|
216
|
+
headers: Object.entries(send.headers ?? {}).map(([key, value]) => ({ key, value })),
|
|
217
|
+
}),
|
|
218
|
+
invocation: (invocationId: unknown) => ({
|
|
219
|
+
cancel: () => driver.cancel(String(invocationId)),
|
|
220
|
+
attach: (serde?: Serde<unknown>) =>
|
|
221
|
+
quiet(
|
|
222
|
+
driver
|
|
223
|
+
.attach(String(invocationId))
|
|
224
|
+
.then((value) => (serde ?? restate.serde.json).deserialize(value ?? new Uint8Array())),
|
|
225
|
+
),
|
|
226
|
+
}),
|
|
227
|
+
cancellation: () => driver.cancellation(),
|
|
228
|
+
// A cancellation owed to the handler's next await, which a call of its
|
|
229
|
+
// database takes before it issues anything (`session.ts`).
|
|
230
|
+
takeCancellation: () => driver.takeCarriedCancellation(),
|
|
231
|
+
cancelPreviousCalls: () => driver.cancelPreviousCalls(),
|
|
232
|
+
invocationEndPromise: { promise: ending.promise },
|
|
233
|
+
defaultSerde: restate.serde.json,
|
|
234
|
+
// The addon reads and writes the object's state on this, rather than
|
|
235
|
+
// calling back into JavaScript for every page (see `openOnVm`).
|
|
236
|
+
vm,
|
|
237
|
+
};
|
|
238
|
+
return context as unknown as AttemptContext;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Mark a promise handled, so that one the handler never awaits does not bring
|
|
243
|
+
* the process down when the attempt ends. The caller still sees the rejection.
|
|
244
|
+
*/
|
|
245
|
+
function quiet<T>(promise: Promise<T>): Promise<T> {
|
|
246
|
+
promise.catch(() => {});
|
|
247
|
+
return promise;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** What a state member of the context does if anything calls it. */
|
|
251
|
+
const servedByVm = (of: string) => () => {
|
|
252
|
+
throw new restate.TerminalError(
|
|
253
|
+
`@restatedev/sessions: the VM serves the object's state in the addon; ctx.${of} is not called`,
|
|
254
|
+
);
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
/** `ctx.genericCall`'s argument, as this package makes it (`calls.ts`). */
|
|
258
|
+
interface GenericCall {
|
|
259
|
+
service: string;
|
|
260
|
+
method: string;
|
|
261
|
+
key?: string;
|
|
262
|
+
parameter: unknown;
|
|
263
|
+
inputSerde?: Serde<unknown>;
|
|
264
|
+
outputSerde?: Serde<unknown>;
|
|
265
|
+
idempotencyKey?: string;
|
|
266
|
+
headers?: Record<string, string>;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** `ctx.genericSend`'s argument. */
|
|
270
|
+
interface GenericSend extends GenericCall {
|
|
271
|
+
delay?: number | Parameters<typeof millisOrDurationToMillis>[0];
|
|
272
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -38,5 +38,6 @@ export type { CallOptions, Client, Rpc, Send, SendClient, SendOptions, Target }
|
|
|
38
38
|
export { remote } from './calls.ts';
|
|
39
39
|
// In place of the SDK's: the services, on PORT, with what they need beside
|
|
40
40
|
// them; `connect`, the same for Restate Cloud (the SDK's own leaves them out);
|
|
41
|
-
// and `served`, the services with what they need, for an endpoint of your own
|
|
41
|
+
// and `served`, the services with what they need, for an endpoint of your own
|
|
42
|
+
// — which runs them on the VM too (`endpoint.ts`).
|
|
42
43
|
export { connect, serve, served } from './serve.ts';
|
package/src/internal.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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
|
|
3
|
-
//
|
|
2
|
+
// fault injection, and a database over a store of their own. For this
|
|
3
|
+
// repository's libraries: the schemas their tables are in,
|
|
4
4
|
// databases of their own, and the Restate SDK as @restatedev/sessions runs it (its
|
|
5
5
|
// own copy, so that a library's journaled handlers serve beside its objects).
|
|
6
6
|
export * as sdk from '@restatedev/restate-sdk';
|
|
@@ -10,8 +10,12 @@ export type { ObjectConfig, SqlHost } from './session.ts';
|
|
|
10
10
|
export { Link } from './link.ts';
|
|
11
11
|
export { ScopeKey } from './scope.ts';
|
|
12
12
|
export { open, type Connection, type Store, type ConnectionTransaction } from './database.ts';
|
|
13
|
-
|
|
13
|
+
// The attempt on the explicit recovery VM, for the tests that drive one.
|
|
14
|
+
export { AttemptDriver, AttemptFailed, AttemptShutDown } from './driver.ts';
|
|
15
|
+
export { Vm, isShutDown } from './vm.ts';
|
|
16
|
+
export { serveSession, servedHere, type Stream } from './handler.ts';
|
|
14
17
|
export { needing, served } from './serve.ts';
|
|
18
|
+
export { invokeRoute, patchEndpoint } from './endpoint.ts';
|
|
15
19
|
export {
|
|
16
20
|
attach,
|
|
17
21
|
cancelCalls,
|
|
@@ -25,4 +29,3 @@ export {
|
|
|
25
29
|
withStoreWrapper,
|
|
26
30
|
type AttemptContext,
|
|
27
31
|
} from './object.ts';
|
|
28
|
-
export type { DoProgressResult, Selectable, UnresolvedFuture } from './selector.ts';
|
package/src/object.ts
CHANGED
|
@@ -20,9 +20,9 @@ import type { Serde, VirtualObjectDefinition } from '@restatedev/restate-sdk-cor
|
|
|
20
20
|
import { type CallOptions, type Rpc, rpcOf, type Send, sendOf, type Target } from './calls.ts';
|
|
21
21
|
import type { DatabaseReader, Store } from './database.ts';
|
|
22
22
|
import { ensureOf, ensuring, Schema, type Step } from './schema.ts';
|
|
23
|
+
import { patchEndpoint } from './endpoint.ts';
|
|
23
24
|
import { Link } from './link.ts';
|
|
24
25
|
import { holding, Scope, scopeOf } from './scope.ts';
|
|
25
|
-
import { hookSelector } from './selector.ts';
|
|
26
26
|
import { type Database, Attempt, type ObjectConfig, type SqlHost, withAttempt } from './session.ts';
|
|
27
27
|
|
|
28
28
|
/**
|
|
@@ -147,6 +147,8 @@ export function host(
|
|
|
147
147
|
clear: (name, entry) => exclusive.clear(name, entry),
|
|
148
148
|
stateKeys: () => ctx.stateKeys(),
|
|
149
149
|
run: (name, action) => exclusive.run(name, action),
|
|
150
|
+
vm: (ctx as { vm?: SqlHost['vm'] }).vm,
|
|
151
|
+
takeCancellation: (ctx as { takeCancellation?: SqlHost['takeCancellation'] }).takeCancellation,
|
|
150
152
|
genericSend: (send) => ctx.genericSend(send),
|
|
151
153
|
};
|
|
152
154
|
}
|
|
@@ -157,14 +159,44 @@ interface ObjectState {
|
|
|
157
159
|
definition?: object;
|
|
158
160
|
}
|
|
159
161
|
|
|
160
|
-
/** A handler or view of a session object: its function, kind, and object. */
|
|
162
|
+
/** A handler or view of a session object: its function, kind, serdes, and object. */
|
|
161
163
|
interface HandlerEntry {
|
|
162
164
|
fn: Fn<never>;
|
|
163
165
|
view: boolean;
|
|
164
166
|
explicit: boolean;
|
|
167
|
+
/** How its input and output are encoded, as its options set them; JSON by default. */
|
|
168
|
+
inputSerde: Serde<unknown>;
|
|
169
|
+
outputSerde: Serde<unknown>;
|
|
170
|
+
/** The handler option of the same name: which errors end the invocation rather than retrying. */
|
|
171
|
+
asTerminalError?: (error: unknown) => Error | undefined;
|
|
165
172
|
object: ObjectState;
|
|
166
173
|
}
|
|
167
174
|
|
|
175
|
+
/**
|
|
176
|
+
* The handler or view `name` of `definition`, if it is a session object's:
|
|
177
|
+
* what {@link serveSession} needs to run an attempt of it on the VM.
|
|
178
|
+
*/
|
|
179
|
+
export function handlerEntry(
|
|
180
|
+
definition: object,
|
|
181
|
+
name: string,
|
|
182
|
+
):
|
|
183
|
+
| {
|
|
184
|
+
view: boolean;
|
|
185
|
+
explicit: boolean;
|
|
186
|
+
inputSerde: Serde<unknown>;
|
|
187
|
+
outputSerde: Serde<unknown>;
|
|
188
|
+
asTerminalError?: (error: unknown) => Error | undefined;
|
|
189
|
+
}
|
|
190
|
+
| undefined {
|
|
191
|
+
const entry = OBJECT.of(definition)?.entries.get(name);
|
|
192
|
+
if (entry === undefined) return undefined;
|
|
193
|
+
const { view, explicit, inputSerde, outputSerde, asTerminalError } = entry;
|
|
194
|
+
return { view, explicit, inputSerde, outputSerde, asTerminalError };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Whether `definition` is a session object: it has handlers this package runs. */
|
|
198
|
+
export const isSessionObject = (definition: object): boolean => OBJECT.of(definition) !== undefined;
|
|
199
|
+
|
|
168
200
|
/** A session object's own, on its definition: for {@link invoke} and {@link withStoreWrapper}. */
|
|
169
201
|
const OBJECT = new Link<{ object: ObjectState; entries: Map<string, HandlerEntry> }>('a session object');
|
|
170
202
|
|
|
@@ -260,13 +292,26 @@ function attempt({ fn, view, explicit, object }: HandlerEntry, ctx: AttemptConte
|
|
|
260
292
|
return withAttempt(() => fn(context as never, input as never), session);
|
|
261
293
|
}
|
|
262
294
|
|
|
263
|
-
/**
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
295
|
+
/**
|
|
296
|
+
* `entry` as the SDK's handler, which only a transport `endpoint.ts` does not
|
|
297
|
+
* reach can call: it routes a session object's invocation to the explicit
|
|
298
|
+
* recovery VM ahead of this, on every endpoint built from `NodeEndpoint` —
|
|
299
|
+
* `restate.endpoint()`, `restate.serve` and `connect`'s tunnel alike.
|
|
300
|
+
*
|
|
301
|
+
* Reaching here means the endpoint is one the patch does not cover, a fetch
|
|
302
|
+
* endpoint being the one that exists. A session object cannot run on the
|
|
303
|
+
* SDK's journaled VM: it is never replayed, and awaiting two things at once
|
|
304
|
+
* fails the attempt with `awaitNext already pending`. So it is refused, rather
|
|
305
|
+
* than half-served.
|
|
306
|
+
*/
|
|
307
|
+
function wrap(objectName: string, name: string) {
|
|
308
|
+
return () => {
|
|
309
|
+
throw new restate.TerminalError(
|
|
310
|
+
`@restatedev/sessions: ${objectName}.${name} is a session object's handler, which runs on the explicit ` +
|
|
311
|
+
'recovery VM. This endpoint does not route to it: serve the object from an endpoint built on the ' +
|
|
312
|
+
"SDK's node entry point (`restate.endpoint()`, `restate.serve` or `connect`). A fetch endpoint " +
|
|
313
|
+
'cannot run one.',
|
|
314
|
+
);
|
|
270
315
|
};
|
|
271
316
|
}
|
|
272
317
|
|
|
@@ -304,8 +349,21 @@ function handlerOf(objectName: string, name: string, entry: unknown, view: boole
|
|
|
304
349
|
}
|
|
305
350
|
const opts = { ...options, ...recovery() } as HandlerOptions;
|
|
306
351
|
const explicit = (options as HandlerOptions).explicitCancellation === true;
|
|
307
|
-
const
|
|
308
|
-
|
|
352
|
+
const serdes = options as {
|
|
353
|
+
input?: Serde<unknown>;
|
|
354
|
+
output?: Serde<unknown>;
|
|
355
|
+
asTerminalError?: (error: unknown) => Error | undefined;
|
|
356
|
+
};
|
|
357
|
+
const made: HandlerEntry = {
|
|
358
|
+
fn: fn as Fn<never>,
|
|
359
|
+
view,
|
|
360
|
+
explicit,
|
|
361
|
+
inputSerde: serdes.input ?? (restate.serde.json as Serde<unknown>),
|
|
362
|
+
outputSerde: serdes.output ?? (restate.serde.json as Serde<unknown>),
|
|
363
|
+
asTerminalError: serdes.asTerminalError,
|
|
364
|
+
object,
|
|
365
|
+
};
|
|
366
|
+
const sdk = wrap(objectName, name) as never;
|
|
309
367
|
const handler = view ? restate.handlers.object.shared(opts, sdk) : restate.handlers.object.exclusive(opts, sdk);
|
|
310
368
|
return { handler, entry: made };
|
|
311
369
|
}
|
|
@@ -339,6 +397,10 @@ export function sessionObject<
|
|
|
339
397
|
metadata?: Record<string, string>;
|
|
340
398
|
options?: restate.ObjectOptions;
|
|
341
399
|
}): VirtualObjectDefinition<P, Functions<H> & Functions<V>> {
|
|
400
|
+
// Every way the SDK hands out a request handler now routes this object's
|
|
401
|
+
// invocations to the explicit recovery VM (`endpoint.ts`). Installed here
|
|
402
|
+
// rather than on import: the package declares `sideEffects: false`.
|
|
403
|
+
patchEndpoint();
|
|
342
404
|
const { name, schema, handlers = {}, views = {}, description, metadata, options } = definition;
|
|
343
405
|
const both = Object.keys(handlers).filter((key) => key in views);
|
|
344
406
|
if (both.length > 0) throw new Error(`${name}: ${both.join(', ')} is a handler and a view: name one otherwise`);
|
|
@@ -436,8 +498,8 @@ function explicitOf(ctx: SessionContext, of: string) {
|
|
|
436
498
|
*
|
|
437
499
|
* It watches for the cancellation, and holds nothing: awaited alone, it does
|
|
438
500
|
* not suspend the invocation, and Restate is not told that the handler waits
|
|
439
|
-
* (
|
|
440
|
-
*
|
|
501
|
+
* (a heartbeat tells Restate the attempt makes progress instead, see
|
|
502
|
+
* `driver.ts`). The cancel signal comes while Restate keeps
|
|
441
503
|
* the invocation's input open. Once Restate closed it (the handler sent and
|
|
442
504
|
* got nothing for the inactivity timeout), a cancellation resolves this at
|
|
443
505
|
* the handler's next await of Restate's, which suspends the invocation and
|