@entrinsik/vite-plugin-informer 2.12.0 → 2.14.0-beta.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 +10 -4
- package/bin/deploy.js +10 -7
- package/bin/init.js +12 -16
- package/bin/workspace.js +5 -2
- package/index.d.ts +7 -5
- package/package.json +9 -3
- package/src/agent-dev.js +10 -8
- package/src/assemble.js +3 -2
- package/src/client.js +29 -3
- package/src/compat.js +7 -3
- package/src/deploy.js +199 -46
- package/src/dev-bag.js +12 -8
- package/src/dev-channel-actors.js +352 -0
- package/src/dev-channel-handlers.js +76 -18
- package/src/dev-channel-shim.js +28 -0
- package/src/dev-dependencies.js +58 -16
- package/src/dev-platform.js +6 -1
- package/src/dev-streams.js +2 -0
- package/src/index.js +16 -4
- package/src/openapi-to-dts.js +4 -0
- package/src/server-routes.js +24 -13
- package/src/signed-in.js +104 -0
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Channel actors in the dev mirror, the counterpart of the server's
|
|
5
|
+
* app-channel-actors.js. A `channels/` file whose `config.actor` is an object
|
|
6
|
+
* gets one live module instance per concrete channel (`match/42`), kept while
|
|
7
|
+
* pages are subscribed:
|
|
8
|
+
*
|
|
9
|
+
* - start({ channel, restored }) runs first, then join / joined / leave and
|
|
10
|
+
* every event export run inside that instance, one call at a time
|
|
11
|
+
* - tick({ dt, frame }) runs `config.actor.tick` times a second; a tick that
|
|
12
|
+
* comes due while a call is still running is skipped, not queued
|
|
13
|
+
* - the actor stops `idleMs` after its last page leaves, with its
|
|
14
|
+
* stop({ reason }), and the next join or send starts a fresh one
|
|
15
|
+
* - snapshot() is called every `snapshotMs` and kept in memory; when a file
|
|
16
|
+
* the actors load changes, each actor keeps a snapshot, stops with reason
|
|
17
|
+
* 'redeploy', and restarts at once on the new code from it, with the same
|
|
18
|
+
* pages: a game survives an edit, as it survives a deploy on the server
|
|
19
|
+
*
|
|
20
|
+
* A page is one member here (a dev page is one client, with no reconnects),
|
|
21
|
+
* so leave runs when it unsubscribes. The server's cluster, leases, billing
|
|
22
|
+
* and rate limits have no dev counterpart.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
export const ACTOR_LIFECYCLE = Object.freeze(['start', 'stop', 'tick', 'snapshot']);
|
|
26
|
+
// The server's actors.callTimeoutMs: a call that runs longer stops the actor.
|
|
27
|
+
export const ACTOR_CALL_TIMEOUT_MS = 1000;
|
|
28
|
+
export const ACTOR_STOP_TIMEOUT_MS = 5000;
|
|
29
|
+
const DEFAULTS = Object.freeze({ tick: 0, idleMs: 30000, snapshotMs: 5000 });
|
|
30
|
+
const MAX_TICK_HZ = 60;
|
|
31
|
+
|
|
32
|
+
export function isActorModule(mod) {
|
|
33
|
+
const actor = mod && mod.config && mod.config.actor;
|
|
34
|
+
return Boolean(actor && typeof actor === 'object' && !Array.isArray(actor));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `request.member` for a dev page: a hash of its client id, shaped like the server's. */
|
|
38
|
+
export function memberIdFor(clientId) {
|
|
39
|
+
return `m_${createHash('sha256').update(`dev:${clientId}`).digest('base64url').slice(0, 16)}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function optionsOf(mod) {
|
|
43
|
+
const asked = mod.config.actor;
|
|
44
|
+
return {
|
|
45
|
+
tickHz: Math.min(Math.max(Number(asked.tick) || 0, 0), MAX_TICK_HZ),
|
|
46
|
+
idleMs: asked.idleMs === undefined ? DEFAULTS.idleMs : Math.max(0, Number(asked.idleMs) || 0),
|
|
47
|
+
snapshotMs: Math.min(Math.max(Number(asked.snapshotMs) || DEFAULTS.snapshotMs, 1000), 60000)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// What `config.actor` may say, and the wording the deploy uses to refuse it
|
|
52
|
+
// (channel-scanner.js assertActorConfig on the server). Without this, a file
|
|
53
|
+
// that sets `actor: { tickRate: 30 }` or exports tick() with no rate runs
|
|
54
|
+
// quietly tick-less in dev and 400s at deploy time.
|
|
55
|
+
const ACTOR_KEYS = ['tick', 'idleMs', 'memoryMb', 'snapshotMs'];
|
|
56
|
+
|
|
57
|
+
function assertActorConfig(mod, filePath) {
|
|
58
|
+
const actor = mod.config.actor;
|
|
59
|
+
const exports = Object.keys(mod);
|
|
60
|
+
const fail = message => {
|
|
61
|
+
throw new Error(`channel handler "${filePath}" ${message} Fix config.actor.`);
|
|
62
|
+
};
|
|
63
|
+
const unknown = Object.keys(actor).filter(key => !ACTOR_KEYS.includes(key));
|
|
64
|
+
if (unknown.length) fail(`sets config.actor.${unknown.join(', config.actor.')}, which is not an actor setting (${ACTOR_KEYS.join(', ')} are).`);
|
|
65
|
+
const number = (key, min) => {
|
|
66
|
+
if (actor[key] === undefined) return;
|
|
67
|
+
if (typeof actor[key] !== 'number' || !Number.isFinite(actor[key]) || actor[key] < min) {
|
|
68
|
+
fail(`sets config.actor.${key} to ${JSON.stringify(actor[key])}; it must be a number of at least ${min}.`);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
number('tick', 0);
|
|
72
|
+
number('idleMs', 0);
|
|
73
|
+
number('memoryMb', 8);
|
|
74
|
+
number('snapshotMs', 1000);
|
|
75
|
+
if (actor.tick > 0 && !exports.includes('tick')) fail(`sets config.actor.tick to ${actor.tick} but exports no tick() to call.`);
|
|
76
|
+
if (exports.includes('tick') && !(actor.tick > 0)) fail('exports tick() but config.actor.tick does not say how often to call it.');
|
|
77
|
+
if (actor.snapshotMs !== undefined && !exports.includes('snapshot')) fail(`sets config.actor.snapshotMs to ${actor.snapshotMs} but exports no snapshot() to call.`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const unavailable = name => () => {
|
|
81
|
+
throw new Error(`${name}() is not available in a channel actor: it would run with one subscriber's credentials on behalf of all of them. Call a server/ route from the page instead.`);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @param {Object} opts
|
|
86
|
+
* @param {Object} opts.viteServer - loads a fresh module instance per actor run (ssrLoadModule with a query)
|
|
87
|
+
* @param {Function} opts.bagFor - async (channel, params) => the handler bag (broadcast, query, log, …)
|
|
88
|
+
* @param {string} [opts.logPrefix]
|
|
89
|
+
* @param {number} [opts.callTimeoutMs]
|
|
90
|
+
*/
|
|
91
|
+
export function createDevActors({ viteServer, bagFor, logPrefix = '[app-channel]', callTimeoutMs = ACTOR_CALL_TIMEOUT_MS }) {
|
|
92
|
+
const actors = new Map(); // channel name → actor
|
|
93
|
+
const starting = new Map(); // channel name → its start in flight
|
|
94
|
+
const snapshots = new Map(); // channel name → the last snapshot() kept
|
|
95
|
+
let runs = 0;
|
|
96
|
+
|
|
97
|
+
async function load(filePath, channel) {
|
|
98
|
+
// a query per run: a separate instance per channel, and a fresh one per start
|
|
99
|
+
return await viteServer.ssrLoadModule(`${filePath}?actor=${encodeURIComponent(channel)}&run=${++runs}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function queue(actor, exportName, extras, timeoutMs = callTimeoutMs) {
|
|
103
|
+
const run = async () => {
|
|
104
|
+
if (actor.state === 'stopped') throw Object.assign(new Error('app_channel_actor_stopped'), { statusCode: 503, code: 'app_channel_actor_stopped' });
|
|
105
|
+
actor.busy = true;
|
|
106
|
+
let timer;
|
|
107
|
+
try {
|
|
108
|
+
const call = Promise.resolve().then(() => actor.mod[exportName]({ ...actor.bag, ...extras }));
|
|
109
|
+
const overrun = new Promise((_, reject) => {
|
|
110
|
+
timer = setTimeout(() => reject(Object.assign(new Error(`${exportName} ran past ${timeoutMs} ms`), { overrun: true })), timeoutMs);
|
|
111
|
+
});
|
|
112
|
+
return await Promise.race([call, overrun]);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
if (err && err.overrun) {
|
|
115
|
+
console.error(`${logPrefix} actor "${actor.channel}" stopped: ${err.message}; the next join or send starts a new one`);
|
|
116
|
+
stop(actor, 'timeout');
|
|
117
|
+
throw Object.assign(new Error('app_channel_actor_timeout'), { statusCode: 504, code: 'app_channel_actor_timeout' });
|
|
118
|
+
}
|
|
119
|
+
if (err && typeof err.statusCode === 'number') throw err;
|
|
120
|
+
console.error(`${logPrefix} ${exportName}("${actor.channel}") failed:`, err);
|
|
121
|
+
throw Object.assign(new Error(`app_channel_${exportName}_failed`), { statusCode: 500, code: 'app_channel_send_failed' });
|
|
122
|
+
} finally {
|
|
123
|
+
clearTimeout(timer);
|
|
124
|
+
actor.busy = false;
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const result = actor.queue.then(run, run);
|
|
128
|
+
actor.queue = result.catch(() => {});
|
|
129
|
+
return result;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const has = (actor, name) => typeof actor.mod[name] === 'function';
|
|
133
|
+
|
|
134
|
+
// Another actor took this channel while this one was stopping: the
|
|
135
|
+
// channel's shared state (its kept snapshot, its registry slot) is that
|
|
136
|
+
// one's now, and this one must not write over it.
|
|
137
|
+
const isReplaced = actor => actors.has(actor.channel) && actors.get(actor.channel) !== actor;
|
|
138
|
+
|
|
139
|
+
function scheduleTick(actor) {
|
|
140
|
+
const period = 1000 / actor.options.tickHz;
|
|
141
|
+
const next = actor.tickOrigin + (actor.frame + 1) * period;
|
|
142
|
+
actor.timers.tick = setTimeout(() => {
|
|
143
|
+
if (actor.state !== 'running') return;
|
|
144
|
+
actor.frame++;
|
|
145
|
+
if (!actor.busy) {
|
|
146
|
+
const now = Date.now();
|
|
147
|
+
const dt = (now - actor.lastTickAt) / 1000;
|
|
148
|
+
actor.lastTickAt = now;
|
|
149
|
+
queue(actor, 'tick', { dt, frame: actor.frame, request: null }).catch(() => {});
|
|
150
|
+
}
|
|
151
|
+
scheduleTick(actor);
|
|
152
|
+
}, Math.max(0, next - Date.now()));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function armIdle(actor) {
|
|
156
|
+
clearTimeout(actor.timers.idle);
|
|
157
|
+
if (actor.members.size > 0 || actor.state !== 'running') return;
|
|
158
|
+
actor.timers.idle = setTimeout(() => stop(actor, 'idle'), actor.options.idleMs);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function saveSnapshot(actor) {
|
|
162
|
+
if (!has(actor, 'snapshot')) return;
|
|
163
|
+
try {
|
|
164
|
+
const state = await queue(actor, 'snapshot', { request: null });
|
|
165
|
+
// taken between messages, so a replacement may have started meanwhile
|
|
166
|
+
if (state !== undefined && state !== null && !isReplaced(actor)) snapshots.set(actor.channel, JSON.parse(JSON.stringify(state)));
|
|
167
|
+
} catch {
|
|
168
|
+
// reported by queue()
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function start(channel, params, filePath) {
|
|
173
|
+
const mod = await load(filePath, channel);
|
|
174
|
+
assertActorConfig(mod, filePath);
|
|
175
|
+
const bag = await bagFor(channel, params);
|
|
176
|
+
// An actor's broadcast to its own channel answers the production shape:
|
|
177
|
+
// there it is queued on the actor's ordered chain and has no seq yet,
|
|
178
|
+
// and `const { seq } = await channel.broadcast(...)` must not read as a
|
|
179
|
+
// usable number locally and null once deployed. Any other channel goes
|
|
180
|
+
// the way every handler's broadcast does.
|
|
181
|
+
const broadcastOwn = async (event, body, options) => {
|
|
182
|
+
await bag.broadcast(channel, event, body, options);
|
|
183
|
+
return { ok: true, queued: true, seq: null };
|
|
184
|
+
};
|
|
185
|
+
const actor = {
|
|
186
|
+
channel, params, filePath, mod,
|
|
187
|
+
options: optionsOf(mod),
|
|
188
|
+
bag: {
|
|
189
|
+
...bag,
|
|
190
|
+
broadcast: (name, event, body, options) => (name === channel
|
|
191
|
+
? broadcastOwn(event, body, options)
|
|
192
|
+
: bag.broadcast(name, event, body, options)),
|
|
193
|
+
fetch: unavailable('fetch'),
|
|
194
|
+
context: undefined,
|
|
195
|
+
channel: { name: channel, params, broadcast: broadcastOwn }
|
|
196
|
+
},
|
|
197
|
+
members: new Map(), // clientId → the request it joined with
|
|
198
|
+
queue: Promise.resolve(),
|
|
199
|
+
busy: false,
|
|
200
|
+
timers: {},
|
|
201
|
+
frame: 0,
|
|
202
|
+
state: 'running'
|
|
203
|
+
};
|
|
204
|
+
actors.set(channel, actor);
|
|
205
|
+
const restored = has(actor, 'snapshot') ? snapshots.get(channel) : undefined;
|
|
206
|
+
if (has(actor, 'start')) {
|
|
207
|
+
try {
|
|
208
|
+
await queue(actor, 'start', { restored, request: null });
|
|
209
|
+
} catch (err) {
|
|
210
|
+
// a state the new start cannot take would fail every start after it too
|
|
211
|
+
snapshots.delete(channel);
|
|
212
|
+
actors.delete(channel);
|
|
213
|
+
actor.state = 'stopped';
|
|
214
|
+
throw err;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (actor.options.tickHz > 0 && has(actor, 'tick')) {
|
|
218
|
+
actor.tickOrigin = Date.now();
|
|
219
|
+
actor.lastTickAt = actor.tickOrigin;
|
|
220
|
+
scheduleTick(actor);
|
|
221
|
+
}
|
|
222
|
+
if (has(actor, 'snapshot')) actor.timers.snapshot = setInterval(() => saveSnapshot(actor), actor.options.snapshotMs);
|
|
223
|
+
armIdle(actor);
|
|
224
|
+
console.log(`${logPrefix} actor "${channel}" started${restored !== undefined ? ' from its snapshot' : ''}`);
|
|
225
|
+
return actor;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Stop an actor: for a redeploy (an edited file) keep a snapshot first;
|
|
230
|
+
* after idle or a timeout drop it; stop() runs unless the actor hung.
|
|
231
|
+
*/
|
|
232
|
+
function stop(actor, reason) {
|
|
233
|
+
if (actor.stopping) return actor.stopping;
|
|
234
|
+
// Synchronously, as the server does: a stop that only marks the actor
|
|
235
|
+
// dead after its awaits hands it out of ensure() for the whole
|
|
236
|
+
// graceful stop, and the page joins an actor that is on its way out.
|
|
237
|
+
actor.state = 'stopping';
|
|
238
|
+
actor.stopping = (async () => {
|
|
239
|
+
clearTimeout(actor.timers.tick);
|
|
240
|
+
clearTimeout(actor.timers.idle);
|
|
241
|
+
clearInterval(actor.timers.snapshot);
|
|
242
|
+
if (reason === 'redeploy' || reason === 'shutdown') await saveSnapshot(actor);
|
|
243
|
+
if (reason !== 'timeout' && has(actor, 'stop')) {
|
|
244
|
+
await queue(actor, 'stop', { reason, request: null }, ACTOR_STOP_TIMEOUT_MS).catch(() => {});
|
|
245
|
+
}
|
|
246
|
+
actor.state = 'stopped';
|
|
247
|
+
const replaced = isReplaced(actor);
|
|
248
|
+
// a replacement started while this one was stopping owns the
|
|
249
|
+
// channel's snapshot now
|
|
250
|
+
if ((reason === 'idle' || reason === 'timeout') && !replaced) snapshots.delete(actor.channel);
|
|
251
|
+
if (!replaced) actors.delete(actor.channel);
|
|
252
|
+
console.log(`${logPrefix} actor "${actor.channel}" stopped (${reason})`);
|
|
253
|
+
})();
|
|
254
|
+
return actor.stopping;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Admit a page: the actor's join decides (exactly true admits), and an
|
|
259
|
+
* actor never holds a member its join did not admit. Every admission goes
|
|
260
|
+
* through here, as on the server, so a join that seeds per-member state or
|
|
261
|
+
* caps seats is exercised in dev too -- not just on the subscribe path.
|
|
262
|
+
*/
|
|
263
|
+
async function admit(actor, clientId, request) {
|
|
264
|
+
if (has(actor, 'join') && await queue(actor, 'join', { payload: null, request }) !== true) {
|
|
265
|
+
armIdle(actor);
|
|
266
|
+
throw Object.assign(new Error('app_channel_join_refused'), { statusCode: 403, code: 'app_channel_join_refused' });
|
|
267
|
+
}
|
|
268
|
+
actor.members.set(clientId, request);
|
|
269
|
+
clearTimeout(actor.timers.idle);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// The running actor for a channel, starting one if there is none; two
|
|
273
|
+
// callers at once share one start.
|
|
274
|
+
async function ensure(channel, params, filePath) {
|
|
275
|
+
const running = actors.get(channel);
|
|
276
|
+
if (running && running.state === 'running' && !starting.has(channel)) return running;
|
|
277
|
+
if (!starting.has(channel)) {
|
|
278
|
+
starting.set(channel, start(channel, params, filePath).finally(() => starting.delete(channel)));
|
|
279
|
+
}
|
|
280
|
+
return await starting.get(channel);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
/** A page subscribes: the actor's join decides (exactly true admits). */
|
|
285
|
+
async join({ channel, params, filePath, clientId, request }) {
|
|
286
|
+
const actor = await ensure(channel, params, filePath);
|
|
287
|
+
await admit(actor, clientId, request);
|
|
288
|
+
},
|
|
289
|
+
async joined({ channel, clientId, request }) {
|
|
290
|
+
const actor = actors.get(channel);
|
|
291
|
+
if (!actor || !actor.members.has(clientId) || !has(actor, 'joined')) return;
|
|
292
|
+
await queue(actor, 'joined', { payload: null, request });
|
|
293
|
+
},
|
|
294
|
+
async leave({ channel, clientId }) {
|
|
295
|
+
const actor = actors.get(channel);
|
|
296
|
+
if (!actor || !actor.members.has(clientId)) return;
|
|
297
|
+
const request = actor.members.get(clientId);
|
|
298
|
+
actor.members.delete(clientId);
|
|
299
|
+
armIdle(actor);
|
|
300
|
+
if (has(actor, 'leave')) await queue(actor, 'leave', { payload: null, request });
|
|
301
|
+
},
|
|
302
|
+
/** A page's send(): a call into the running actor, started afresh if it stopped. */
|
|
303
|
+
async send({ channel, params, filePath, clientId, request, event, payload }) {
|
|
304
|
+
const actor = await ensure(channel, params, filePath);
|
|
305
|
+
if (ACTOR_LIFECYCLE.includes(event) || typeof actor.mod[event] !== 'function') {
|
|
306
|
+
throw Object.assign(new Error('app_channel_no_handler'), { statusCode: 404, code: 'app_channel_no_handler' });
|
|
307
|
+
}
|
|
308
|
+
// a sender this actor has not admitted (it restarted, or its code
|
|
309
|
+
// changed since the page joined) goes through join like anyone else
|
|
310
|
+
if (!actor.members.has(clientId)) await admit(actor, clientId, request);
|
|
311
|
+
return await queue(actor, event, { payload: payload === undefined ? null : payload, request });
|
|
312
|
+
},
|
|
313
|
+
/**
|
|
314
|
+
* A file an actor loads changed: an actor that keeps snapshots and has
|
|
315
|
+
* pages stops with one and restarts at once on the new code, carrying
|
|
316
|
+
* its pages in through the new code's own join. Any other actor just
|
|
317
|
+
* stops, and the next join or send starts it fresh -- the same two
|
|
318
|
+
* rules the server follows across a deploy, so a join that refuses the
|
|
319
|
+
* carried page (or a file that keeps no snapshot) behaves here as it
|
|
320
|
+
* will there.
|
|
321
|
+
*/
|
|
322
|
+
async restartAll() {
|
|
323
|
+
const running = [...actors.values()].filter(a => a.state === 'running');
|
|
324
|
+
await Promise.all(running.map(async actor => {
|
|
325
|
+
const carry = has(actor, 'snapshot') && actor.members.size > 0;
|
|
326
|
+
const members = new Map(actor.members);
|
|
327
|
+
await stop(actor, 'redeploy');
|
|
328
|
+
if (!carry) return;
|
|
329
|
+
try {
|
|
330
|
+
const next = await ensure(actor.channel, actor.params, actor.filePath);
|
|
331
|
+
for (const [clientId, request] of members) {
|
|
332
|
+
try {
|
|
333
|
+
await admit(next, clientId, request);
|
|
334
|
+
} catch (err) {
|
|
335
|
+
console.log(`${logPrefix} a page was not carried into actor "${actor.channel}" on the edited code: ${err.message}`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
} catch (err) {
|
|
339
|
+
console.error(`${logPrefix} actor "${actor.channel}" did not restart on the edited code:`, err);
|
|
340
|
+
}
|
|
341
|
+
}));
|
|
342
|
+
},
|
|
343
|
+
async stopAll(reason = 'shutdown') {
|
|
344
|
+
await Promise.all([...actors.values()].map(actor => stop(actor, reason)));
|
|
345
|
+
},
|
|
346
|
+
/** What is running, for the terminal and tests. */
|
|
347
|
+
list() {
|
|
348
|
+
return [...actors.values()].map(a => ({ channel: a.channel, members: a.members.size, frame: a.frame, state: a.state }));
|
|
349
|
+
},
|
|
350
|
+
snapshots
|
|
351
|
+
};
|
|
352
|
+
}
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
|
-
import { join } from 'node:path';
|
|
2
|
+
import { join, relative, sep } from 'node:path';
|
|
3
3
|
import { parse as parseUrl } from 'node:url';
|
|
4
4
|
import { createDevBagBuilder, buildDevUser } from './dev-bag.js';
|
|
5
5
|
import { devPlatform } from './dev-platform.js';
|
|
6
6
|
import { filePathToRoute, matchRoute, walkJsFiles } from './server-routes.js';
|
|
7
7
|
import { createDevChannels, isChannelName, isWildcardName, isEventName, isReservedEvent, channelError, USER_CHANNEL_PREFIX } from './dev-channels.js';
|
|
8
|
+
import { createDevActors, isActorModule, memberIdFor, ACTOR_LIFECYCLE } from './dev-channel-actors.js';
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
11
|
* The dev counterpart of app-channel-handlers.js: a page's `channel()` mock
|
|
@@ -12,8 +13,9 @@ import { createDevChannels, isChannelName, isWildcardName, isEventName, isReserv
|
|
|
12
13
|
* the matching `channels/` file runs in-process the way a deployed handler
|
|
13
14
|
* runs in the sandbox — `join` decides admission, `joined` runs after it,
|
|
14
15
|
* `leave` runs on unsubscribe, and an event-named export answers `send()`.
|
|
15
|
-
*
|
|
16
|
-
*
|
|
16
|
+
* A file with `config.actor` runs as a channel actor instead (see
|
|
17
|
+
* dev-channel-actors.js). Frames still ride Vite's websocket to every page;
|
|
18
|
+
* admission is what tells the page which frames it may dispatch.
|
|
17
19
|
*/
|
|
18
20
|
|
|
19
21
|
export const CHANNELS_DIR = 'channels';
|
|
@@ -23,6 +25,10 @@ export const CHANNEL_METHOD = 'CHANNEL';
|
|
|
23
25
|
export const HANDLER_TIMEOUT_MS = 5000;
|
|
24
26
|
// Per-user inbound budget (token bucket): send() and the replay reads a reconnect makes.
|
|
25
27
|
export const SEND_RATE = Object.freeze({ perSecond: 10, burst: 30 });
|
|
28
|
+
// The server's separate, larger send() budget for actor channels (a game's inputs).
|
|
29
|
+
export const ACTOR_SEND_RATE = Object.freeze({ perSecond: 30, burst: 60 });
|
|
30
|
+
// Edits under these directories can change what an actor runs: its file, or what it imports.
|
|
31
|
+
const ACTOR_SOURCE_DIRS = ['channels', 'shared', 'lib', 'server'];
|
|
26
32
|
// Exports with a fixed meaning; every other export must be an event name.
|
|
27
33
|
export const LIFECYCLE_EXPORTS = Object.freeze(['config', 'join', 'joined', 'leave']);
|
|
28
34
|
|
|
@@ -156,10 +162,39 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
156
162
|
// handler reading platform.capabilities.embeddings must not disagree with
|
|
157
163
|
// the route beside it, and its embed() must be bound when they agree.
|
|
158
164
|
const bagBuilder = createDevBagBuilder({ serverOrigin, authHeader, devWorkspaceId, projectRoot, devBindings, appToken, channels, logPrefix: '[app]', platform, appId });
|
|
159
|
-
// clientId → channel name → { clientId, channel, params, file }
|
|
165
|
+
// clientId → channel name → { clientId, channel, params, file, actor }
|
|
160
166
|
const subscriptions = new Map();
|
|
161
|
-
// username → { tokens, ts }
|
|
167
|
+
// username (or `actor:` + username) → { tokens, ts }
|
|
162
168
|
const buckets = new Map();
|
|
169
|
+
const actors = createDevActors({
|
|
170
|
+
viteServer,
|
|
171
|
+
bagFor: async () => (await bagBuilder.build()).bag,
|
|
172
|
+
logPrefix,
|
|
173
|
+
callTimeoutMs: Math.min(timeoutMs, 1000)
|
|
174
|
+
});
|
|
175
|
+
// A Vite restart (a config edit) closes this server and builds another:
|
|
176
|
+
// without this the old server's actors keep their tick loops and module
|
|
177
|
+
// instances running forever, so two config edits leave three copies of the
|
|
178
|
+
// same game ticking.
|
|
179
|
+
if (viteServer.httpServer && typeof viteServer.httpServer.once === 'function') {
|
|
180
|
+
viteServer.httpServer.once('close', () => {
|
|
181
|
+
actors.stopAll().catch(err => console.error(`${logPrefix} stopping actors on shutdown failed:`, err));
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
// An edit to a file actors load restarts them on the new code, from their snapshots.
|
|
185
|
+
if (viteServer.watcher && typeof viteServer.watcher.on === 'function') {
|
|
186
|
+
viteServer.watcher.on('change', file => {
|
|
187
|
+
const rel = relative(projectRoot, file);
|
|
188
|
+
if (rel.startsWith('..') || !ACTOR_SOURCE_DIRS.includes(rel.split(sep)[0])) return;
|
|
189
|
+
for (const mod of (viteServer.moduleGraph && viteServer.moduleGraph.getModulesByFile(file)) || []) {
|
|
190
|
+
viteServer.moduleGraph.invalidateModule(mod);
|
|
191
|
+
}
|
|
192
|
+
actors.restartAll().catch(err => console.error(`${logPrefix} restarting actors after an edit failed:`, err));
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// The `request` a handler sees: the page's member id, and the mocked viewer.
|
|
197
|
+
const requestFor = clientId => ({ member: memberIdFor(clientId), user: { ...devUser }, roles });
|
|
163
198
|
|
|
164
199
|
function recordsFor(clientId) {
|
|
165
200
|
let records = subscriptions.get(clientId);
|
|
@@ -170,14 +205,15 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
170
205
|
return records;
|
|
171
206
|
}
|
|
172
207
|
|
|
173
|
-
function takeSendToken(username) {
|
|
208
|
+
function takeSendToken(username, budget = rate) {
|
|
174
209
|
const at = now();
|
|
175
|
-
|
|
210
|
+
const key = budget === rate ? username : `actor:${username}`;
|
|
211
|
+
let bucket = buckets.get(key);
|
|
176
212
|
if (!bucket) {
|
|
177
|
-
bucket = { tokens:
|
|
178
|
-
buckets.set(
|
|
213
|
+
bucket = { tokens: budget.burst, ts: at };
|
|
214
|
+
buckets.set(key, bucket);
|
|
179
215
|
}
|
|
180
|
-
bucket.tokens = Math.min(
|
|
216
|
+
bucket.tokens = Math.min(budget.burst, bucket.tokens + (Math.max(0, at - bucket.ts) / 1000) * budget.perSecond);
|
|
181
217
|
bucket.ts = at;
|
|
182
218
|
if (bucket.tokens < 1) return false;
|
|
183
219
|
bucket.tokens -= 1;
|
|
@@ -209,13 +245,13 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
209
245
|
|
|
210
246
|
// Run one export with the channel bag under the handler's timeout. A thrown
|
|
211
247
|
// channel error keeps its status; anything else is 500 app_channel_<export>_failed.
|
|
212
|
-
async function runExport(mod, exportName, { channel, params, payload }) {
|
|
248
|
+
async function runExport(mod, exportName, { channel, params, payload, clientId }) {
|
|
213
249
|
const { bag } = await bagBuilder.build();
|
|
214
250
|
const invocation = {
|
|
215
251
|
...bag,
|
|
216
252
|
channel: { name: channel, params, broadcast: async (event, body, options) => await bag.broadcast(channel, event, body, options) },
|
|
217
253
|
payload: payload === undefined ? null : payload,
|
|
218
|
-
request:
|
|
254
|
+
request: requestFor(clientId)
|
|
219
255
|
};
|
|
220
256
|
const cap = Math.min(Number(mod.config && mod.config.timeout) || timeoutMs, timeoutMs);
|
|
221
257
|
let timer;
|
|
@@ -252,12 +288,17 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
252
288
|
if (Array.isArray(required) && required.length > 0 && !required.some(r => roles.includes(r))) {
|
|
253
289
|
throw channelError('app_channel_role_required', 403);
|
|
254
290
|
}
|
|
255
|
-
if (
|
|
291
|
+
if (isActorModule(mod)) {
|
|
292
|
+
// the channel's actor runs join itself (and starts on the first one)
|
|
293
|
+
if (isWildcardName(channel)) throw channelError('app_channel_actor_wildcard', 403);
|
|
294
|
+
await actors.join({ channel, params: record.params, filePath: resolved.file.filePath, clientId, request: requestFor(clientId) });
|
|
295
|
+
record.actor = true;
|
|
296
|
+
} else if (typeof mod.join === 'function') {
|
|
256
297
|
// admitted only when the handler returned exactly true
|
|
257
298
|
if (await runExport(mod, 'join', record) !== true) throw channelError('app_channel_join_refused', 403);
|
|
258
299
|
}
|
|
259
300
|
recordsFor(clientId).set(channel, record);
|
|
260
|
-
console.log(`${logPrefix} join("${channel}") admitted${typeof mod.join === 'function' ? '' : ' (no join export)'}`);
|
|
301
|
+
console.log(`${logPrefix} join("${channel}") admitted${record.actor ? ' (actor)' : typeof mod.join === 'function' ? '' : ' (no join export)'}`);
|
|
261
302
|
return mod;
|
|
262
303
|
}
|
|
263
304
|
|
|
@@ -267,6 +308,10 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
267
308
|
if (!record) return;
|
|
268
309
|
records.delete(channel);
|
|
269
310
|
if (!record.file) return;
|
|
311
|
+
if (record.actor) {
|
|
312
|
+
await actors.leave({ channel, clientId }).catch(err => console.warn(`${logPrefix} leave("${channel}") failed: ${err.message}`));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
270
315
|
try {
|
|
271
316
|
const mod = await viteServer.ssrLoadModule(record.file.filePath);
|
|
272
317
|
if (typeof mod.leave === 'function') await runExport(mod, 'leave', record);
|
|
@@ -282,6 +327,12 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
282
327
|
if (!isEventName(event)) throw channelError('app_channel_invalid_event', 400);
|
|
283
328
|
if (isReservedEvent(event)) throw channelError('app_channel_reserved_event', 400);
|
|
284
329
|
if (!record.file) throw channelError('app_channel_no_handler', 404);
|
|
330
|
+
if (record.actor) {
|
|
331
|
+
if (LIFECYCLE_EXPORTS.includes(event) || ACTOR_LIFECYCLE.includes(event)) throw channelError('app_channel_no_handler', 404);
|
|
332
|
+
if (!takeSendToken(devUser.username, ACTOR_SEND_RATE)) throw channelError('app_channel_rate_limited', 429);
|
|
333
|
+
const result = await actors.send({ channel, params: record.params, filePath: record.file.filePath, clientId, request: requestFor(clientId), event, payload });
|
|
334
|
+
return result === undefined ? null : result;
|
|
335
|
+
}
|
|
285
336
|
const mod = await viteServer.ssrLoadModule(record.file.filePath);
|
|
286
337
|
if (LIFECYCLE_EXPORTS.includes(event) || typeof mod[event] !== 'function') throw channelError('app_channel_no_handler', 404);
|
|
287
338
|
if (!takeSendToken(devUser.username)) throw channelError('app_channel_rate_limited', 429);
|
|
@@ -290,7 +341,7 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
290
341
|
return result === undefined ? null : result;
|
|
291
342
|
}
|
|
292
343
|
|
|
293
|
-
|
|
344
|
+
async function devChannelHandlersMiddleware(req, res, next) {
|
|
294
345
|
const parsed = parseUrl(req.url, true);
|
|
295
346
|
const route = `${req.method} ${parsed.pathname}`;
|
|
296
347
|
let body = {};
|
|
@@ -315,7 +366,10 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
315
366
|
if (mod && typeof mod.joined === 'function') {
|
|
316
367
|
const record = recordsFor(body.clientId).get(body.channel);
|
|
317
368
|
setImmediate(() => {
|
|
318
|
-
|
|
369
|
+
const run = record.actor
|
|
370
|
+
? actors.joined({ channel: body.channel, clientId: body.clientId, request: requestFor(body.clientId) })
|
|
371
|
+
: runExport(mod, 'joined', record);
|
|
372
|
+
run.catch(err => console.warn(`${logPrefix} joined("${body.channel}") failed: ${err.message}`));
|
|
319
373
|
});
|
|
320
374
|
}
|
|
321
375
|
return;
|
|
@@ -324,12 +378,16 @@ export function createDevChannelHandlers(viteServer, { serverOrigin, authHeader,
|
|
|
324
378
|
await unsubscribe(body);
|
|
325
379
|
return sendJson(res, 200, { ok: true });
|
|
326
380
|
}
|
|
327
|
-
|
|
381
|
+
// `now`, as the server stamps it: the page's serverNow() reads it
|
|
382
|
+
return sendJson(res, 200, { result: await send(body), now: Date.now() });
|
|
328
383
|
} catch (err) {
|
|
329
384
|
const status = typeof err.statusCode === 'number' ? err.statusCode : 500;
|
|
330
385
|
if (status === 500) console.error(logPrefix, err);
|
|
331
386
|
else if (route === 'POST /subscribe') console.log(`${logPrefix} join("${body.channel}") refused (${err.code || err.message})`);
|
|
332
387
|
sendJson(res, status, { error: err.code || err.message });
|
|
333
388
|
}
|
|
334
|
-
}
|
|
389
|
+
}
|
|
390
|
+
// the running actors, for tests and the terminal
|
|
391
|
+
devChannelHandlersMiddleware.actors = actors;
|
|
392
|
+
return devChannelHandlersMiddleware;
|
|
335
393
|
}
|
package/src/dev-channel-shim.js
CHANGED
|
@@ -134,6 +134,30 @@ export function generateDevChannelShim() {
|
|
|
134
134
|
hot.on('vite:ws:connect', subscribeAll);
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
// A page that goes away (closed, reloaded, navigated off) leaves its
|
|
138
|
+
// channels, as its socket closing does on the server, or an actor
|
|
139
|
+
// would keep it as a member and never go idle. One the browser keeps
|
|
140
|
+
// and brings back (the back/forward cache) joins them again.
|
|
141
|
+
if (hot && typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
|
|
142
|
+
window.addEventListener('pagehide', function () {
|
|
143
|
+
open.forEach(function (ch) {
|
|
144
|
+
if (!ch._admitted) return;
|
|
145
|
+
ch._admitted = false;
|
|
146
|
+
ch._resume = true;
|
|
147
|
+
try {
|
|
148
|
+
fetch(API + '/unsubscribe', {
|
|
149
|
+
method: 'POST', keepalive: true, credentials: 'same-origin',
|
|
150
|
+
headers: { 'Content-Type': 'application/json' },
|
|
151
|
+
body: JSON.stringify({ clientId: clientId, channel: ch.name })
|
|
152
|
+
}).catch(function () {});
|
|
153
|
+
} catch (e) { /* the page is going regardless */ }
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
window.addEventListener('pageshow', function (e) {
|
|
157
|
+
if (e.persisted) subscribeAll();
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
137
161
|
function Channel(name, opts) {
|
|
138
162
|
this.name = name;
|
|
139
163
|
// null-prototype: an event name admits 'constructor' and 'toString',
|
|
@@ -355,6 +379,10 @@ export function generateDevChannelShim() {
|
|
|
355
379
|
}).catch(function () {});
|
|
356
380
|
};
|
|
357
381
|
|
|
382
|
+
// the page and the dev server share this machine's clock
|
|
383
|
+
informer.serverNow = function () { return Date.now(); };
|
|
384
|
+
Channel.prototype.serverNow = function () { return Date.now(); };
|
|
385
|
+
|
|
358
386
|
informer.channel = function (name, opts) {
|
|
359
387
|
if (typeof name !== 'string' || name.length > CHANNEL_NAME_MAX_LENGTH || !CHANNEL_NAME.test(name)) {
|
|
360
388
|
throw channelError('join_refused', 'Invalid channel name: ' + name);
|