@kylewillett/troupe 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/CHANGELOG.md +36 -0
- package/LICENSE +21 -0
- package/README.md +376 -2
- package/dist/actor.d.ts +13 -0
- package/dist/actor.js +14 -0
- package/dist/ask.d.ts +39 -0
- package/dist/ask.js +135 -0
- package/dist/backstage/encode.d.ts +36 -0
- package/dist/backstage/encode.js +183 -0
- package/dist/backstage/index.d.ts +4 -0
- package/dist/backstage/index.js +4 -0
- package/dist/backstage/requests.d.ts +8 -0
- package/dist/backstage/requests.js +137 -0
- package/dist/backstage/source.d.ts +10 -0
- package/dist/backstage/source.js +143 -0
- package/dist/backstage/types.d.ts +135 -0
- package/dist/backstage/types.js +3 -0
- package/dist/backstage-ui/assets/index-Bg0MCiqs.css +1 -0
- package/dist/backstage-ui/assets/index-CeefBsDh.js +9 -0
- package/dist/backstage-ui/index.html +13 -0
- package/dist/cell.d.ts +129 -0
- package/dist/cell.js +763 -0
- package/dist/checks.d.ts +9 -0
- package/dist/checks.js +25 -0
- package/dist/dispatcher.d.ts +36 -0
- package/dist/dispatcher.js +65 -0
- package/dist/errors.d.ts +37 -0
- package/dist/errors.js +41 -0
- package/dist/events.d.ts +37 -0
- package/dist/events.js +88 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/internal.d.ts +81 -0
- package/dist/internal.js +36 -0
- package/dist/logger.d.ts +31 -0
- package/dist/logger.js +56 -0
- package/dist/names.d.ts +20 -0
- package/dist/names.js +50 -0
- package/dist/node/backstage/index.d.ts +1 -0
- package/dist/node/backstage/index.js +2 -0
- package/dist/node/backstage/server.d.ts +60 -0
- package/dist/node/backstage/server.js +342 -0
- package/dist/node/sqlite/index.d.ts +1 -0
- package/dist/node/sqlite/index.js +2 -0
- package/dist/node/sqlite/schema.d.ts +2 -0
- package/dist/node/sqlite/schema.js +36 -0
- package/dist/node/sqlite/schema.sql +32 -0
- package/dist/node/sqlite/sqlite.d.ts +24 -0
- package/dist/node/sqlite/sqlite.js +183 -0
- package/dist/persistence/actor.d.ts +158 -0
- package/dist/persistence/actor.js +454 -0
- package/dist/persistence/backend.d.ts +32 -0
- package/dist/persistence/backend.js +96 -0
- package/dist/persistence/errors.d.ts +60 -0
- package/dist/persistence/errors.js +82 -0
- package/dist/persistence/index.d.ts +6 -0
- package/dist/persistence/index.js +5 -0
- package/dist/persistence/json.d.ts +7 -0
- package/dist/persistence/json.js +75 -0
- package/dist/persistence/memory.d.ts +18 -0
- package/dist/persistence/memory.js +143 -0
- package/dist/persistence/postgres/index.d.ts +1 -0
- package/dist/persistence/postgres/index.js +3 -0
- package/dist/persistence/postgres/postgres.d.ts +66 -0
- package/dist/persistence/postgres/postgres.js +236 -0
- package/dist/persistence/postgres/schema.d.ts +12 -0
- package/dist/persistence/postgres/schema.js +57 -0
- package/dist/persistence/postgres/schema.sql +35 -0
- package/dist/persistence/projection.d.ts +48 -0
- package/dist/persistence/projection.js +102 -0
- package/dist/persistence/standard-schema.d.ts +63 -0
- package/dist/persistence/standard-schema.js +7 -0
- package/dist/persistence/types.d.ts +73 -0
- package/dist/persistence/types.js +3 -0
- package/dist/queue.d.ts +11 -0
- package/dist/queue.js +31 -0
- package/dist/scheduler.d.ts +24 -0
- package/dist/scheduler.js +23 -0
- package/dist/supervision.d.ts +91 -0
- package/dist/supervision.js +120 -0
- package/dist/system.d.ts +28 -0
- package/dist/system.js +216 -0
- package/dist/testkit/index.d.ts +4 -0
- package/dist/testkit/index.js +4 -0
- package/dist/testkit/kit.d.ts +63 -0
- package/dist/testkit/kit.js +93 -0
- package/dist/testkit/manual-scheduler.d.ts +58 -0
- package/dist/testkit/manual-scheduler.js +187 -0
- package/dist/testkit/probe.d.ts +50 -0
- package/dist/testkit/probe.js +124 -0
- package/dist/testkit/random.d.ts +11 -0
- package/dist/testkit/random.js +23 -0
- package/dist/timers.d.ts +37 -0
- package/dist/timers.js +110 -0
- package/dist/types.d.ts +364 -0
- package/dist/types.js +1 -0
- package/package.json +110 -4
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { BackstageSource } from '../../backstage/types.js';
|
|
2
|
+
import type { Logger } from '../../logger.js';
|
|
3
|
+
import type { Scheduler } from '../../scheduler.js';
|
|
4
|
+
import type { ActorSystem } from '../../types.js';
|
|
5
|
+
/** Options for {@link serveBackstage}. */
|
|
6
|
+
export interface BackstageServerOptions {
|
|
7
|
+
/** The port to listen on. Default 7070. `0` picks a free one, which `url` reports. */
|
|
8
|
+
port?: number;
|
|
9
|
+
/**
|
|
10
|
+
* The address to listen on. Default `127.0.0.1`. Backstage shows every message and every
|
|
11
|
+
* state, so any address but a loopback one shows them to whoever can reach it.
|
|
12
|
+
*/
|
|
13
|
+
host?: string;
|
|
14
|
+
}
|
|
15
|
+
/** A running Backstage server. */
|
|
16
|
+
export interface BackstageServer {
|
|
17
|
+
/** Where to open it, such as `http://127.0.0.1:7070/`. */
|
|
18
|
+
readonly url: string;
|
|
19
|
+
/** Stops serving, ends every connection and closes the source. Calling it again waits for the first. */
|
|
20
|
+
close(): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
/** How often a connection gets the events that have happened since, in ms. */
|
|
23
|
+
export declare const BATCH_MS = 50;
|
|
24
|
+
/** How much a connection may leave unsent before it's dropped, in bytes. */
|
|
25
|
+
export declare const MAX_BUFFERED: number;
|
|
26
|
+
/** The largest request body, in bytes. */
|
|
27
|
+
export declare const MAX_BODY: number;
|
|
28
|
+
/** How long an `EventSource` waits before it reconnects, in ms. */
|
|
29
|
+
export declare const RETRY_MS = 1000;
|
|
30
|
+
/**
|
|
31
|
+
* Serves Backstage for `system`: the UI at `/`, its frames as server-sent events at `/events`,
|
|
32
|
+
* batched every 50 ms on the system's scheduler, and read-only requests posted as JSON to
|
|
33
|
+
* `/request`. Node only. It listens on `127.0.0.1:7070` unless told otherwise, and refuses
|
|
34
|
+
* requests whose `Host` header isn't a name for that address.
|
|
35
|
+
* @throws TypeError, at once, unless `system` was made by `createActorSystem`, `opts.port` is an
|
|
36
|
+
* integer from 0 to 65535, and `opts.host` is a non-empty string.
|
|
37
|
+
* @returns A promise of the server once it's listening, which rejects if it can't listen.
|
|
38
|
+
*/
|
|
39
|
+
export declare function serveBackstage(system: ActorSystem, opts?: BackstageServerOptions): Promise<BackstageServer>;
|
|
40
|
+
/** What {@link serve} needs. Tests give their own source and UI folder. */
|
|
41
|
+
export interface ServeOptions {
|
|
42
|
+
readonly source: BackstageSource;
|
|
43
|
+
readonly scheduler: Scheduler;
|
|
44
|
+
readonly log: Logger;
|
|
45
|
+
readonly port: number;
|
|
46
|
+
readonly host: string;
|
|
47
|
+
/** The folder the UI is served from. */
|
|
48
|
+
readonly uiDir: string;
|
|
49
|
+
/** Default {@link MAX_BUFFERED}. */
|
|
50
|
+
readonly maxBuffered?: number;
|
|
51
|
+
}
|
|
52
|
+
/** Serves `opts.source`. It owns the source from now on, and closes it on close or on failure. */
|
|
53
|
+
export declare function serve(opts: ServeOptions): Promise<BackstageServer>;
|
|
54
|
+
/**
|
|
55
|
+
* Which `Host` headers a server on `host` and `port` answers. The port must match. A loopback
|
|
56
|
+
* server answers any loopback name. A server on every address answers any IP address and
|
|
57
|
+
* `localhost`, but never another name, which is what DNS rebinding needs. Otherwise only the
|
|
58
|
+
* address it was given.
|
|
59
|
+
*/
|
|
60
|
+
export declare function hostCheck(host: string, port: number): (header: string | undefined) => boolean;
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
// The Backstage server: the built UI, the protocol's frames as server-sent events, and requests
|
|
2
|
+
// as JSON posts, on node:http with no dependency (decision 0023). Localhost only by default, and
|
|
3
|
+
// it refuses any Host header that isn't a name for the address it serves, so a page on another
|
|
4
|
+
// site can't reach it through DNS rebinding.
|
|
5
|
+
import { readFile } from 'node:fs/promises';
|
|
6
|
+
import { createServer } from 'node:http';
|
|
7
|
+
import { isIP } from 'node:net';
|
|
8
|
+
import { extname, resolve, sep } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { backstage } from '../../backstage/source.js';
|
|
11
|
+
import { checkInt, checkKeys, describe } from '../../checks.js';
|
|
12
|
+
import { inspectSystem } from '../../internal.js';
|
|
13
|
+
const OPTIONS = new Set(['port', 'host']);
|
|
14
|
+
const DEFAULT_PORT = 7070;
|
|
15
|
+
const DEFAULT_HOST = '127.0.0.1';
|
|
16
|
+
/** How often a connection gets the events that have happened since, in ms. */
|
|
17
|
+
export const BATCH_MS = 50;
|
|
18
|
+
/** How much a connection may leave unsent before it's dropped, in bytes. */
|
|
19
|
+
export const MAX_BUFFERED = 1024 * 1024;
|
|
20
|
+
/** The largest request body, in bytes. */
|
|
21
|
+
export const MAX_BODY = 64 * 1024;
|
|
22
|
+
/** How long an `EventSource` waits before it reconnects, in ms. */
|
|
23
|
+
export const RETRY_MS = 1_000;
|
|
24
|
+
// From dist/node/backstage/ to dist/backstage-ui/, where the build puts the UI.
|
|
25
|
+
const UI_DIR = fileURLToPath(new URL('../../backstage-ui/', import.meta.url));
|
|
26
|
+
const TYPES = {
|
|
27
|
+
'.html': 'text/html; charset=utf-8',
|
|
28
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
29
|
+
'.css': 'text/css; charset=utf-8',
|
|
30
|
+
'.json': 'application/json; charset=utf-8',
|
|
31
|
+
'.map': 'application/json; charset=utf-8',
|
|
32
|
+
'.svg': 'image/svg+xml',
|
|
33
|
+
'.png': 'image/png',
|
|
34
|
+
'.ico': 'image/x-icon',
|
|
35
|
+
'.woff2': 'font/woff2',
|
|
36
|
+
};
|
|
37
|
+
// Sent with every response. No Access-Control-* header ever: the UI is same-origin.
|
|
38
|
+
const COMMON_HEADERS = {
|
|
39
|
+
'X-Content-Type-Options': 'nosniff',
|
|
40
|
+
'Referrer-Policy': 'no-referrer',
|
|
41
|
+
'Cache-Control': 'no-store',
|
|
42
|
+
};
|
|
43
|
+
const CSP = "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'";
|
|
44
|
+
/**
|
|
45
|
+
* Serves Backstage for `system`: the UI at `/`, its frames as server-sent events at `/events`,
|
|
46
|
+
* batched every 50 ms on the system's scheduler, and read-only requests posted as JSON to
|
|
47
|
+
* `/request`. Node only. It listens on `127.0.0.1:7070` unless told otherwise, and refuses
|
|
48
|
+
* requests whose `Host` header isn't a name for that address.
|
|
49
|
+
* @throws TypeError, at once, unless `system` was made by `createActorSystem`, `opts.port` is an
|
|
50
|
+
* integer from 0 to 65535, and `opts.host` is a non-empty string.
|
|
51
|
+
* @returns A promise of the server once it's listening, which rejects if it can't listen.
|
|
52
|
+
*/
|
|
53
|
+
export function serveBackstage(system, opts) {
|
|
54
|
+
const { port, host } = checkOptions(opts);
|
|
55
|
+
const inspection = inspectSystem(system);
|
|
56
|
+
return serve({
|
|
57
|
+
source: backstage(system),
|
|
58
|
+
scheduler: inspection.scheduler,
|
|
59
|
+
log: inspection.log,
|
|
60
|
+
port,
|
|
61
|
+
host,
|
|
62
|
+
uiDir: UI_DIR,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** Serves `opts.source`. It owns the source from now on, and closes it on close or on failure. */
|
|
66
|
+
export async function serve(opts) {
|
|
67
|
+
const { source, scheduler, log } = opts;
|
|
68
|
+
const maxBuffered = opts.maxBuffered ?? MAX_BUFFERED;
|
|
69
|
+
const uiDir = resolve(opts.uiDir);
|
|
70
|
+
const streams = new Set();
|
|
71
|
+
let cancelFlush;
|
|
72
|
+
let closing;
|
|
73
|
+
// Set once listening, since port 0 learns its port then.
|
|
74
|
+
let allowed = () => false;
|
|
75
|
+
const write = (stream, frames) => {
|
|
76
|
+
stream.res.write(`data: ${JSON.stringify(frames)}\n\n`);
|
|
77
|
+
// A tab that stopped reading. It reconnects when it can, with a fresh hello.
|
|
78
|
+
if (stream.res.writableLength > maxBuffered)
|
|
79
|
+
end(stream, true);
|
|
80
|
+
};
|
|
81
|
+
const end = (stream, destroy = false) => {
|
|
82
|
+
if (!streams.delete(stream))
|
|
83
|
+
return;
|
|
84
|
+
stream.disconnect();
|
|
85
|
+
if (destroy)
|
|
86
|
+
stream.res.destroy();
|
|
87
|
+
else
|
|
88
|
+
stream.res.end();
|
|
89
|
+
};
|
|
90
|
+
const flush = () => {
|
|
91
|
+
cancelFlush = undefined;
|
|
92
|
+
for (const stream of streams) {
|
|
93
|
+
if (stream.pending.length === 0)
|
|
94
|
+
continue;
|
|
95
|
+
const frames = stream.pending;
|
|
96
|
+
stream.pending = [];
|
|
97
|
+
write(stream, frames);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const openStream = (res) => {
|
|
101
|
+
res.writeHead(200, {
|
|
102
|
+
...COMMON_HEADERS,
|
|
103
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
104
|
+
});
|
|
105
|
+
res.write(`retry: ${String(RETRY_MS)}\n\n`);
|
|
106
|
+
const stream = { res, pending: [], disconnect: () => undefined };
|
|
107
|
+
streams.add(stream);
|
|
108
|
+
// The hello comes at once, in connect, and goes out on its own. Events wait for the batch.
|
|
109
|
+
stream.disconnect = source.connect((frame) => {
|
|
110
|
+
if (frame.type === 'hello') {
|
|
111
|
+
write(stream, [frame]);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
stream.pending.push(frame);
|
|
115
|
+
cancelFlush ??= scheduler.setTimer(flush, BATCH_MS);
|
|
116
|
+
});
|
|
117
|
+
// The response's close, not the request's, which closes once its (empty) body is read.
|
|
118
|
+
res.on('close', () => {
|
|
119
|
+
end(stream);
|
|
120
|
+
});
|
|
121
|
+
};
|
|
122
|
+
const answerRequest = async (req, res) => {
|
|
123
|
+
const type = req.headers['content-type'] ?? '';
|
|
124
|
+
if (!/^application\/json\s*(;|$)/i.test(type)) {
|
|
125
|
+
sendJson(res, 415, refusal('TypeError', 'a request must be sent as application/json'));
|
|
126
|
+
req.resume();
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const body = await readBody(req, MAX_BODY);
|
|
130
|
+
if (body === undefined) {
|
|
131
|
+
sendJson(res, 413, refusal('RangeError', `a request must be at most ${String(MAX_BODY)} bytes`));
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
let parsed;
|
|
135
|
+
try {
|
|
136
|
+
parsed = JSON.parse(body);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
sendJson(res, 400, refusal('TypeError', 'a request must be JSON'));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
// The source checks the request itself, and answers a bad one with a TypeError response.
|
|
143
|
+
sendJson(res, 200, await source.request(parsed));
|
|
144
|
+
};
|
|
145
|
+
const handle = async (req, res) => {
|
|
146
|
+
if (!allowed(req.headers.host)) {
|
|
147
|
+
sendText(res, 403, 'Backstage refuses this Host header.\n');
|
|
148
|
+
req.resume();
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const path = pathOf(req.url);
|
|
152
|
+
const method = path === '/request' ? 'POST' : 'GET';
|
|
153
|
+
if (req.method !== method) {
|
|
154
|
+
notAllowed(req, res, method);
|
|
155
|
+
}
|
|
156
|
+
else if (path === '/events') {
|
|
157
|
+
openStream(res);
|
|
158
|
+
}
|
|
159
|
+
else if (path === '/request') {
|
|
160
|
+
await answerRequest(req, res);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
await serveFile(res, uiDir, path);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
const server = createServer((req, res) => {
|
|
167
|
+
handle(req, res).catch((error) => {
|
|
168
|
+
log.error('the Backstage server failed a request', { error });
|
|
169
|
+
if (!res.headersSent)
|
|
170
|
+
sendText(res, 500, 'Backstage failed this request.\n');
|
|
171
|
+
else
|
|
172
|
+
res.destroy();
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
try {
|
|
176
|
+
await new Promise((done, fail) => {
|
|
177
|
+
server.once('error', fail);
|
|
178
|
+
server.listen(opts.port, opts.host, () => {
|
|
179
|
+
server.off('error', fail);
|
|
180
|
+
done();
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
source.close();
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
const { port } = server.address();
|
|
189
|
+
allowed = hostCheck(opts.host, port);
|
|
190
|
+
return Object.freeze({
|
|
191
|
+
url: `http://${openableHost(opts.host)}:${String(port)}/`,
|
|
192
|
+
close() {
|
|
193
|
+
closing ??= new Promise((done) => {
|
|
194
|
+
server.close(() => {
|
|
195
|
+
done();
|
|
196
|
+
});
|
|
197
|
+
cancelFlush?.();
|
|
198
|
+
// What has happened goes out before the streams end.
|
|
199
|
+
flush();
|
|
200
|
+
for (const stream of streams)
|
|
201
|
+
end(stream);
|
|
202
|
+
source.close();
|
|
203
|
+
// Keep-alive sockets would otherwise hold close() open.
|
|
204
|
+
server.closeAllConnections();
|
|
205
|
+
});
|
|
206
|
+
return closing;
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
function checkOptions(opts) {
|
|
211
|
+
if (opts === undefined)
|
|
212
|
+
return { port: DEFAULT_PORT, host: DEFAULT_HOST };
|
|
213
|
+
checkKeys(opts, OPTIONS, 'serveBackstage');
|
|
214
|
+
const { port = DEFAULT_PORT, host = DEFAULT_HOST } = opts;
|
|
215
|
+
checkInt(port, 'serveBackstage: port', { min: 0 });
|
|
216
|
+
if (port > 65_535) {
|
|
217
|
+
throw new TypeError(`serveBackstage: port must be at most 65535, got ${describe(port)}`);
|
|
218
|
+
}
|
|
219
|
+
if (typeof host !== 'string' || host === '') {
|
|
220
|
+
throw new TypeError(`serveBackstage: host must be a non-empty string, got ${describe(host)}`);
|
|
221
|
+
}
|
|
222
|
+
return { port: port, host };
|
|
223
|
+
}
|
|
224
|
+
const bare = (host) => host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host.toLowerCase();
|
|
225
|
+
const WILDCARDS = new Set(['0.0.0.0', '::']);
|
|
226
|
+
const LOOPBACK_NAMES = new Set(['localhost', '127.0.0.1', '::1']);
|
|
227
|
+
const isLoopback = (host) => LOOPBACK_NAMES.has(host) || (isIP(host) === 4 && host.startsWith('127.'));
|
|
228
|
+
/**
|
|
229
|
+
* Which `Host` headers a server on `host` and `port` answers. The port must match. A loopback
|
|
230
|
+
* server answers any loopback name. A server on every address answers any IP address and
|
|
231
|
+
* `localhost`, but never another name, which is what DNS rebinding needs. Otherwise only the
|
|
232
|
+
* address it was given.
|
|
233
|
+
*/
|
|
234
|
+
export function hostCheck(host, port) {
|
|
235
|
+
const bound = bare(host);
|
|
236
|
+
return (header) => {
|
|
237
|
+
if (header === undefined || header === '')
|
|
238
|
+
return false;
|
|
239
|
+
let url;
|
|
240
|
+
try {
|
|
241
|
+
url = new URL(`http://${header}`);
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return false;
|
|
245
|
+
}
|
|
246
|
+
// Anything but host and port, such as user@host, isn't a Host header.
|
|
247
|
+
if (url.host !== header.toLowerCase() && `${url.host}:80` !== header.toLowerCase()) {
|
|
248
|
+
return false;
|
|
249
|
+
}
|
|
250
|
+
if ((url.port === '' ? '80' : url.port) !== String(port))
|
|
251
|
+
return false;
|
|
252
|
+
const name = bare(url.hostname);
|
|
253
|
+
if (WILDCARDS.has(bound))
|
|
254
|
+
return name === 'localhost' || isIP(name) !== 0;
|
|
255
|
+
if (isLoopback(bound))
|
|
256
|
+
return isLoopback(name);
|
|
257
|
+
return name === bound;
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/** A host a browser can open: a wildcard means this machine. */
|
|
261
|
+
function openableHost(host) {
|
|
262
|
+
const name = bare(host);
|
|
263
|
+
if (name === '0.0.0.0')
|
|
264
|
+
return '127.0.0.1';
|
|
265
|
+
if (name === '::')
|
|
266
|
+
return '[::1]';
|
|
267
|
+
return isIP(name) === 6 ? `[${name}]` : name;
|
|
268
|
+
}
|
|
269
|
+
function pathOf(url) {
|
|
270
|
+
try {
|
|
271
|
+
return decodeURIComponent(new URL(url ?? '/', 'http://backstage').pathname);
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
// A malformed escape: no file has that name.
|
|
275
|
+
return '/\0';
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
async function serveFile(res, uiDir, path) {
|
|
279
|
+
const name = path === '/' ? 'index.html' : path.slice(1);
|
|
280
|
+
const file = resolve(uiDir, name);
|
|
281
|
+
if (!file.startsWith(uiDir + sep) || name.includes('\0')) {
|
|
282
|
+
sendText(res, 404, 'Not found.\n');
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
let content;
|
|
286
|
+
try {
|
|
287
|
+
content = await readFile(file);
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
if (isMissing(error)) {
|
|
291
|
+
sendText(res, 404, path === '/' ? 'The Backstage UI is not built. Run npm run build.\n' : 'Not found.\n');
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
const type = TYPES[extname(file)] ?? 'application/octet-stream';
|
|
297
|
+
res.writeHead(200, {
|
|
298
|
+
...COMMON_HEADERS,
|
|
299
|
+
'Content-Type': type,
|
|
300
|
+
...(type.startsWith('text/html') ? { 'Content-Security-Policy': CSP } : {}),
|
|
301
|
+
});
|
|
302
|
+
res.end(content);
|
|
303
|
+
}
|
|
304
|
+
function isMissing(error) {
|
|
305
|
+
const code = error?.code;
|
|
306
|
+
return code === 'ENOENT' || code === 'EISDIR' || code === 'ENOTDIR';
|
|
307
|
+
}
|
|
308
|
+
/** The body as text, or `undefined` once it passes `limit` bytes. */
|
|
309
|
+
function readBody(req, limit) {
|
|
310
|
+
return new Promise((done, fail) => {
|
|
311
|
+
const chunks = [];
|
|
312
|
+
let size = 0;
|
|
313
|
+
let over = false;
|
|
314
|
+
req.on('data', (chunk) => {
|
|
315
|
+
size += chunk.length;
|
|
316
|
+
if (size > limit)
|
|
317
|
+
over = true;
|
|
318
|
+
if (!over)
|
|
319
|
+
chunks.push(chunk);
|
|
320
|
+
});
|
|
321
|
+
req.on('end', () => {
|
|
322
|
+
done(over ? undefined : Buffer.concat(chunks).toString('utf8'));
|
|
323
|
+
});
|
|
324
|
+
req.on('error', fail);
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
function refusal(name, message) {
|
|
328
|
+
return { ok: false, error: { name, message } };
|
|
329
|
+
}
|
|
330
|
+
function notAllowed(req, res, allow) {
|
|
331
|
+
req.resume();
|
|
332
|
+
res.writeHead(405, { ...COMMON_HEADERS, Allow: allow, 'Content-Type': 'text/plain' });
|
|
333
|
+
res.end('Method not allowed.\n');
|
|
334
|
+
}
|
|
335
|
+
function sendText(res, status, text) {
|
|
336
|
+
res.writeHead(status, { ...COMMON_HEADERS, 'Content-Type': 'text/plain; charset=utf-8' });
|
|
337
|
+
res.end(text);
|
|
338
|
+
}
|
|
339
|
+
function sendJson(res, status, body) {
|
|
340
|
+
res.writeHead(status, { ...COMMON_HEADERS, 'Content-Type': 'application/json; charset=utf-8' });
|
|
341
|
+
res.end(JSON.stringify(body));
|
|
342
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { sqlitePersistence, type SqlitePersistence } from './sqlite.js';
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/** The SQL that creates the SQLite backend's tables, if they're missing. */
|
|
2
|
+
export declare const SQLITE_SCHEMA = "CREATE TABLE IF NOT EXISTS troupe_events (\n -- AUTOINCREMENT never reuses a value, so offsets only increase. Appends hold the write lock,\n -- so they also commit in offset order.\n global_offset INTEGER PRIMARY KEY AUTOINCREMENT,\n persistence_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n version INTEGER NOT NULL,\n timestamp INTEGER NOT NULL,\n -- JSON text: the event, and its tags as an array in the order they were given\n event TEXT NOT NULL,\n tags TEXT NOT NULL,\n UNIQUE (persistence_id, seq)\n);\n\nCREATE TABLE IF NOT EXISTS troupe_event_tags (\n tag TEXT NOT NULL,\n global_offset INTEGER NOT NULL,\n PRIMARY KEY (tag, global_offset)\n) WITHOUT ROWID;\n\nCREATE TABLE IF NOT EXISTS troupe_snapshots (\n persistence_id TEXT PRIMARY KEY,\n seq INTEGER NOT NULL,\n version INTEGER NOT NULL,\n timestamp INTEGER NOT NULL,\n state TEXT NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS troupe_offsets (\n name TEXT PRIMARY KEY,\n global_offset INTEGER NOT NULL\n);\n";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// The SQLite backend's tables. The build also writes this to dist/node/sqlite/schema.sql, for
|
|
2
|
+
// people who manage migrations themselves. Every statement is safe to run again.
|
|
3
|
+
/** The SQL that creates the SQLite backend's tables, if they're missing. */
|
|
4
|
+
export const SQLITE_SCHEMA = `CREATE TABLE IF NOT EXISTS troupe_events (
|
|
5
|
+
-- AUTOINCREMENT never reuses a value, so offsets only increase. Appends hold the write lock,
|
|
6
|
+
-- so they also commit in offset order.
|
|
7
|
+
global_offset INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
8
|
+
persistence_id TEXT NOT NULL,
|
|
9
|
+
seq INTEGER NOT NULL,
|
|
10
|
+
version INTEGER NOT NULL,
|
|
11
|
+
timestamp INTEGER NOT NULL,
|
|
12
|
+
-- JSON text: the event, and its tags as an array in the order they were given
|
|
13
|
+
event TEXT NOT NULL,
|
|
14
|
+
tags TEXT NOT NULL,
|
|
15
|
+
UNIQUE (persistence_id, seq)
|
|
16
|
+
);
|
|
17
|
+
|
|
18
|
+
CREATE TABLE IF NOT EXISTS troupe_event_tags (
|
|
19
|
+
tag TEXT NOT NULL,
|
|
20
|
+
global_offset INTEGER NOT NULL,
|
|
21
|
+
PRIMARY KEY (tag, global_offset)
|
|
22
|
+
) WITHOUT ROWID;
|
|
23
|
+
|
|
24
|
+
CREATE TABLE IF NOT EXISTS troupe_snapshots (
|
|
25
|
+
persistence_id TEXT PRIMARY KEY,
|
|
26
|
+
seq INTEGER NOT NULL,
|
|
27
|
+
version INTEGER NOT NULL,
|
|
28
|
+
timestamp INTEGER NOT NULL,
|
|
29
|
+
state TEXT NOT NULL
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
CREATE TABLE IF NOT EXISTS troupe_offsets (
|
|
33
|
+
name TEXT PRIMARY KEY,
|
|
34
|
+
global_offset INTEGER NOT NULL
|
|
35
|
+
);
|
|
36
|
+
`;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
CREATE TABLE IF NOT EXISTS troupe_events (
|
|
2
|
+
-- AUTOINCREMENT never reuses a value, so offsets only increase. Appends hold the write lock,
|
|
3
|
+
-- so they also commit in offset order.
|
|
4
|
+
global_offset INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
|
+
persistence_id TEXT NOT NULL,
|
|
6
|
+
seq INTEGER NOT NULL,
|
|
7
|
+
version INTEGER NOT NULL,
|
|
8
|
+
timestamp INTEGER NOT NULL,
|
|
9
|
+
-- JSON text: the event, and its tags as an array in the order they were given
|
|
10
|
+
event TEXT NOT NULL,
|
|
11
|
+
tags TEXT NOT NULL,
|
|
12
|
+
UNIQUE (persistence_id, seq)
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
CREATE TABLE IF NOT EXISTS troupe_event_tags (
|
|
16
|
+
tag TEXT NOT NULL,
|
|
17
|
+
global_offset INTEGER NOT NULL,
|
|
18
|
+
PRIMARY KEY (tag, global_offset)
|
|
19
|
+
) WITHOUT ROWID;
|
|
20
|
+
|
|
21
|
+
CREATE TABLE IF NOT EXISTS troupe_snapshots (
|
|
22
|
+
persistence_id TEXT PRIMARY KEY,
|
|
23
|
+
seq INTEGER NOT NULL,
|
|
24
|
+
version INTEGER NOT NULL,
|
|
25
|
+
timestamp INTEGER NOT NULL,
|
|
26
|
+
state TEXT NOT NULL
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
CREATE TABLE IF NOT EXISTS troupe_offsets (
|
|
30
|
+
name TEXT PRIMARY KEY,
|
|
31
|
+
global_offset INTEGER NOT NULL
|
|
32
|
+
);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Persistence } from '../../persistence/types.js';
|
|
2
|
+
/** The SQLite backend's stores, which share one connection. */
|
|
3
|
+
export interface SqlitePersistence extends Required<Persistence> {
|
|
4
|
+
/** Closes the connection. Calls made after it reject. Closing twice does nothing. */
|
|
5
|
+
close(): void;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* A backend on SQLite, through Node's built-in `node:sqlite`, so it adds no dependency. Node only.
|
|
9
|
+
*
|
|
10
|
+
* File databases use WAL mode. An append runs in a `BEGIN IMMEDIATE` transaction, which takes the
|
|
11
|
+
* database's write lock before it checks the stream's last sequence number, so two connections,
|
|
12
|
+
* in one process or several, can't both win. The loser rejects with `JournalConflictError`.
|
|
13
|
+
*
|
|
14
|
+
* `node:sqlite` is synchronous: each call does its work before it returns its promise, and an
|
|
15
|
+
* append waits up to 5 s, blocking the thread, for another connection's write lock. On Node 22,
|
|
16
|
+
* the first load prints an experimental warning. Node 24 and later don't.
|
|
17
|
+
*
|
|
18
|
+
* @param opts.path A database file, created if it's missing, or `":memory:"`.
|
|
19
|
+
* @param opts.clock The wall clock for timestamps, in integer ms. Defaults to `Date.now`.
|
|
20
|
+
*/
|
|
21
|
+
export declare function sqlitePersistence(opts: {
|
|
22
|
+
path: string;
|
|
23
|
+
clock?: () => number;
|
|
24
|
+
}): SqlitePersistence;
|