@yaks/durable-object 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +554 -2
- package/_dist/alarm.d.ts +35 -0
- package/_dist/alarm.d.ts.map +1 -0
- package/_dist/ceiling.d.ts +167 -0
- package/_dist/ceiling.d.ts.map +1 -0
- package/_dist/compose.d.ts +79 -0
- package/_dist/compose.d.ts.map +1 -0
- package/_dist/copy.d.ts +67 -0
- package/_dist/copy.d.ts.map +1 -0
- package/_dist/door.d.ts +172 -0
- package/_dist/door.d.ts.map +1 -0
- package/_dist/job.d.ts +26 -0
- package/_dist/job.d.ts.map +1 -0
- package/_dist/keys.d.ts +14 -0
- package/_dist/keys.d.ts.map +1 -0
- package/_dist/mod.d.ts +65 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/object.d.ts +75 -0
- package/_dist/object.d.ts.map +1 -0
- package/_dist/profile.d.ts +32 -0
- package/_dist/profile.d.ts.map +1 -0
- package/_dist/query-memory.d.ts +27 -0
- package/_dist/query-memory.d.ts.map +1 -0
- package/_dist/resets.d.ts +208 -0
- package/_dist/resets.d.ts.map +1 -0
- package/_dist/rewind.d.ts +21 -0
- package/_dist/rewind.d.ts.map +1 -0
- package/_dist/sockets.d.ts +90 -0
- package/_dist/sockets.d.ts.map +1 -0
- package/_dist/sql.d.ts +72 -0
- package/_dist/sql.d.ts.map +1 -0
- package/_dist/store.d.ts +8 -0
- package/_dist/store.d.ts.map +1 -0
- package/alarm.js +126 -0
- package/alarm.js.map +1 -0
- package/alarm.ts +188 -0
- package/ceiling.js +536 -0
- package/ceiling.js.map +1 -0
- package/ceiling.ts +681 -0
- package/compose.js +201 -0
- package/compose.js.map +1 -0
- package/compose.ts +249 -0
- package/copy.js +394 -0
- package/copy.js.map +1 -0
- package/copy.ts +413 -0
- package/deno.json +1 -0
- package/door.js +364 -0
- package/door.js.map +1 -0
- package/door.ts +542 -0
- package/example.ts +108 -0
- package/holds.js +85 -0
- package/holds.js.map +1 -0
- package/holds.ts +72 -0
- package/job.js +151 -0
- package/job.js.map +1 -0
- package/job.ts +166 -0
- package/keys.js +59 -0
- package/keys.js.map +1 -0
- package/keys.ts +85 -0
- package/mod.js +65 -0
- package/mod.js.map +1 -0
- package/mod.ts +167 -0
- package/object.js +247 -0
- package/object.js.map +1 -0
- package/object.ts +385 -0
- package/package.json +68 -4
- package/profile.js +131 -0
- package/profile.js.map +1 -0
- package/profile.ts +150 -0
- package/query-memory.js +157 -0
- package/query-memory.js.map +1 -0
- package/query-memory.ts +240 -0
- package/resets.js +302 -0
- package/resets.js.map +1 -0
- package/resets.ts +353 -0
- package/rewind.js +68 -0
- package/rewind.js.map +1 -0
- package/rewind.ts +91 -0
- package/sockets.js +749 -0
- package/sockets.js.map +1 -0
- package/sockets.ts +991 -0
- package/sql.js +221 -0
- package/sql.js.map +1 -0
- package/sql.ts +330 -0
- package/store.js +58 -0
- package/store.js.map +1 -0
- package/store.ts +80 -0
- package/watches.js +8 -0
- package/watches.js.map +1 -0
- package/watches.ts +23 -0
package/sockets.js
ADDED
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
// The socket plumbing, and only the plumbing. What a subscription means — a
|
|
2
|
+
// saved query whose results are sent again when a committed write changes them
|
|
3
|
+
// — belongs to @yaks/api; this file carries frames between that registry and a
|
|
4
|
+
// Durable Object's WebSockets, which no standard covers.
|
|
5
|
+
//
|
|
6
|
+
// The whole difficulty is hibernation. A socket accepted with
|
|
7
|
+
// `ctx.acceptWebSocket` outlives the object: the runtime evicts the object
|
|
8
|
+
// between two frames and rebuilds it on the next one, so every subscription
|
|
9
|
+
// held in memory is gone while the client still believes it is watching. The
|
|
10
|
+
// socket's attachment preserves its subscriptions or their storage key. A
|
|
11
|
+
// woken object rebuilds the registry from it (`wake`) before doing anything
|
|
12
|
+
// else. It can resume from a snapshot already on the wire or send current
|
|
13
|
+
// results to resync the client.
|
|
14
|
+
//
|
|
15
|
+
// A hibernated socket fires no events either, so @yaks/api's `attach()`, which
|
|
16
|
+
// registers event listeners, cannot be used here: the object's own
|
|
17
|
+
// `webSocketMessage` and `webSocketClose` handlers take its place, calling
|
|
18
|
+
// {@link Sockets.message} and {@link Sockets.close}.
|
|
19
|
+
import { clockReply, decode, fault, json, queue, receive, refusal } from "@yaks/api";
|
|
20
|
+
import { sha256 } from "@yaks/graph/sha256";
|
|
21
|
+
import { after, isPromise, over } from "@yaks/fp";
|
|
22
|
+
import { stringify } from "@yaks/vocab/wire";
|
|
23
|
+
import { checkpoints, holds, MissingSubscriptions } from "./holds.js";
|
|
24
|
+
import { pack, unpack } from "./watches.js";
|
|
25
|
+
/** Schedule subscription reads on the object's existing alarm. On a cold
|
|
26
|
+
* alarm, the adapter restores the socket's watches and reads their current
|
|
27
|
+
* answers, which supply fresh deadlines. The runtime holds no timer between
|
|
28
|
+
* reads. */ export let socketRenewals = (arm, { now = Date.now, keep } = {})=>{
|
|
29
|
+
let held = new Map();
|
|
30
|
+
let running = false;
|
|
31
|
+
return {
|
|
32
|
+
at: (at, read)=>{
|
|
33
|
+
held.set(read, at);
|
|
34
|
+
if (!running) {
|
|
35
|
+
let armed = arm(at).catch((e)=>fault(e, 'socket renewal alarm'));
|
|
36
|
+
keep?.(armed);
|
|
37
|
+
}
|
|
38
|
+
return ()=>void held.delete(read);
|
|
39
|
+
},
|
|
40
|
+
run: async ()=>{
|
|
41
|
+
let at = now();
|
|
42
|
+
let due = [
|
|
43
|
+
...held
|
|
44
|
+
].filter(([, time])=>time <= at);
|
|
45
|
+
running = true;
|
|
46
|
+
try {
|
|
47
|
+
await Promise.all(due.map(([read])=>{
|
|
48
|
+
if (held.delete(read)) return read();
|
|
49
|
+
}));
|
|
50
|
+
let next = Infinity;
|
|
51
|
+
for (let time of held.values())next = Math.min(next, time);
|
|
52
|
+
return next == Infinity ? null : next;
|
|
53
|
+
} finally{
|
|
54
|
+
running = false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
let CAP = 2048;
|
|
60
|
+
let TOKEN = '0'.repeat(36);
|
|
61
|
+
/** How long a burst of watch changes may take before its map is stored, ms. */ export let SETTLE = 1000;
|
|
62
|
+
// A `sync: peers` value is held in memory, and this object's memory does not
|
|
63
|
+
// survive hibernation. The attachment keeps keys; saved components are
|
|
64
|
+
// hydrated from storage under those surviving holders. Unsaved components
|
|
65
|
+
// retain keys alone so their holder's close can still clear them. The 2KB
|
|
66
|
+
// attachment bounds how many keys survive alongside subscriptions.
|
|
67
|
+
let KEYS = 16;
|
|
68
|
+
let open = (ws)=>ws.readyState == 1;
|
|
69
|
+
let copy = (values = {})=>Object.assign(Object.create(null), values);
|
|
70
|
+
let bytes = new TextEncoder();
|
|
71
|
+
let size = (value)=>bytes.encode(JSON.stringify(value)).length;
|
|
72
|
+
let within = (value)=>size(value) <= CAP;
|
|
73
|
+
// A delivery can grow independently of its watches. Reserve just the space
|
|
74
|
+
// for its storage key, including on sockets that have yet to enable ACKs.
|
|
75
|
+
let fits = (held)=>within(held) && within({
|
|
76
|
+
...held,
|
|
77
|
+
owed: TOKEN,
|
|
78
|
+
kept: true,
|
|
79
|
+
seen: undefined,
|
|
80
|
+
snapshots: undefined
|
|
81
|
+
});
|
|
82
|
+
// Snapshot proofs only avoid redundant transfers. Keep the watches even
|
|
83
|
+
// when there is room for their queries and ACKs alone.
|
|
84
|
+
let fitted = (held)=>{
|
|
85
|
+
if (fits(held)) return held;
|
|
86
|
+
if (!held.snapshots) return;
|
|
87
|
+
let short = {
|
|
88
|
+
...held,
|
|
89
|
+
snapshots: undefined
|
|
90
|
+
};
|
|
91
|
+
if (fits(short)) return short;
|
|
92
|
+
};
|
|
93
|
+
let snapshot = (frame)=>!frame.refused && (frame.transientReset !== undefined || frame.reset);
|
|
94
|
+
// Compare the answer itself. A new registry's revision can differ without a
|
|
95
|
+
// change, and rows behind an outstanding ACK can change before it wakes.
|
|
96
|
+
let checkpoint = (frame)=>{
|
|
97
|
+
let { revision, since: _, reset: _reset, ...answer } = frame;
|
|
98
|
+
return {
|
|
99
|
+
print: sha256(stringify(answer)).slice(0, 32),
|
|
100
|
+
revision
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
let relayOf = (ws)=>{
|
|
104
|
+
let held = ws.deserializeAttachment();
|
|
105
|
+
let keys = held && typeof held == 'object' ? held.relay : undefined;
|
|
106
|
+
return Array.isArray(keys) ? keys : [];
|
|
107
|
+
};
|
|
108
|
+
// The relay keys, written back beside everything else. Over the cap they are
|
|
109
|
+
// simply not written: a relay must never cost somebody their subscriptions.
|
|
110
|
+
let remember = (ws, keys)=>{
|
|
111
|
+
let held = ws.deserializeAttachment();
|
|
112
|
+
let was = held && typeof held == 'object' ? held : {};
|
|
113
|
+
let relay = keys.slice(0, KEYS);
|
|
114
|
+
let next = relay.length ? {
|
|
115
|
+
...was,
|
|
116
|
+
relay
|
|
117
|
+
} : {
|
|
118
|
+
...was,
|
|
119
|
+
relay: undefined
|
|
120
|
+
};
|
|
121
|
+
if (fits(next)) ws.serializeAttachment(next);
|
|
122
|
+
};
|
|
123
|
+
// What a frame subscribed to, read alongside @yaks/api's own dispatch so that
|
|
124
|
+
// the attachment stays current. Anything malformed is not a subscription —
|
|
125
|
+
// `receive` rejects it.
|
|
126
|
+
let asked = (msg)=>{
|
|
127
|
+
if (!msg || typeof msg != 'object') return null;
|
|
128
|
+
if ('ack' in msg && typeof msg.ack == 'string') {
|
|
129
|
+
return {
|
|
130
|
+
id: '',
|
|
131
|
+
ack: msg.ack
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
let sub = 'subscribe' in msg ? msg.subscribe : undefined;
|
|
135
|
+
if (typeof sub == 'string' || sub === true) {
|
|
136
|
+
return {
|
|
137
|
+
id: 'id' in msg && msg.id != null ? String(msg.id) : '',
|
|
138
|
+
ask: sub,
|
|
139
|
+
acks: 'acks' in msg && msg.acks === true,
|
|
140
|
+
frames: 'acks' in msg && msg.acks === true && 'frames' in msg && msg.frames === true
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
if ('unsubscribe' in msg && msg.unsubscribe != null) {
|
|
144
|
+
return {
|
|
145
|
+
id: String(msg.unsubscribe)
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
return null;
|
|
149
|
+
};
|
|
150
|
+
let messageKind = (msg)=>{
|
|
151
|
+
if (msg && typeof msg == 'object') {
|
|
152
|
+
if ('ack' in msg && typeof msg.ack == 'string') return 'ack';
|
|
153
|
+
if ('subscribe' in msg && (typeof msg.subscribe == 'string' || msg.subscribe === true)) {
|
|
154
|
+
return 'subscribe';
|
|
155
|
+
}
|
|
156
|
+
if ('unsubscribe' in msg && msg.unsubscribe != null) return 'unsubscribe';
|
|
157
|
+
if ('relay' in msg && Array.isArray(msg.relay)) return 'relay';
|
|
158
|
+
}
|
|
159
|
+
return 'other';
|
|
160
|
+
};
|
|
161
|
+
/** Answer a client's clock probe, `received` at the object's door: true
|
|
162
|
+
* when the frame was one, on a socket still open. Nothing else is read or
|
|
163
|
+
* written, so an object answers one before it opens anything. */ export let probed = (ws, data, received = Date.now())=>open(ws) && answered(ws, decode(data), received);
|
|
164
|
+
let answered = (ws, input, received)=>clockReply(ws, 'value' in input ? input.value : null, received);
|
|
165
|
+
/**
|
|
166
|
+
* Wire a Durable Object's sockets to a subscription registry. The object keeps
|
|
167
|
+
* one of these and calls it from its three handlers:
|
|
168
|
+
*
|
|
169
|
+
* ```ts
|
|
170
|
+
* // fetch(request) → live.wake(); live.accept(request)
|
|
171
|
+
* // webSocketMessage(ws, data) → live.message(ws, data)
|
|
172
|
+
* // webSocketClose(ws) → live.close(ws)
|
|
173
|
+
* ```
|
|
174
|
+
*
|
|
175
|
+
* Frames go straight to the socket; no durable write crosses it (a batch is
|
|
176
|
+
* applied with `POST /apply`, and the socket is how everyone hears about it).
|
|
177
|
+
* The one exception is a `sync: peers` relay, which crosses here because its
|
|
178
|
+
* lifetime is this socket's — see @yaks/api's `receive`.
|
|
179
|
+
*/ export let sockets = (subs, ctx, report, opts = {})=>{
|
|
180
|
+
let sinks = new Map();
|
|
181
|
+
let closed = new WeakSet();
|
|
182
|
+
// Sockets this incarnation accepted, and those any check has let through:
|
|
183
|
+
// the handshake already asked who the caller is, so a check refusing one
|
|
184
|
+
// it admitted before letting anything through is two answers to one
|
|
185
|
+
// question, which is ours to hear about.
|
|
186
|
+
let accepted = new WeakSet();
|
|
187
|
+
let admitted = new WeakSet();
|
|
188
|
+
let recovered = new Map();
|
|
189
|
+
let waking;
|
|
190
|
+
let queries = new Map();
|
|
191
|
+
let baselines = new Map();
|
|
192
|
+
let repo;
|
|
193
|
+
let backing = ()=>repo ??= holds(ctx.storage);
|
|
194
|
+
let saved;
|
|
195
|
+
let proofs = ()=>saved ??= checkpoints(ctx.storage);
|
|
196
|
+
// A page changes its watches in bursts: one that walks into another tile
|
|
197
|
+
// opens the tiles it reaches and closes the ones it left, a message each.
|
|
198
|
+
// Its stored map is written once the burst settles, not once a message.
|
|
199
|
+
let owed = new Map();
|
|
200
|
+
let reading = (held)=>opts.read ? opts.read(held?.read, held?.writer) : held?.read;
|
|
201
|
+
// The registry's timers (@yaks/api `Subs`), unset the runtime's: read as a
|
|
202
|
+
// timer is set, so a clock probe never touches the registry.
|
|
203
|
+
let timer = (fn, ms)=>{
|
|
204
|
+
if (subs.timer) return subs.timer(fn, ms);
|
|
205
|
+
let t = setTimeout(fn, ms);
|
|
206
|
+
return ()=>clearTimeout(t);
|
|
207
|
+
};
|
|
208
|
+
let defer = opts.defer ?? ((write)=>void timer(write, SETTLE));
|
|
209
|
+
let pay = ()=>{
|
|
210
|
+
let due = [
|
|
211
|
+
...owed
|
|
212
|
+
];
|
|
213
|
+
owed.clear();
|
|
214
|
+
for (let [ref, map] of due)backing().write(ref, map);
|
|
215
|
+
};
|
|
216
|
+
let owe = (ref, map)=>{
|
|
217
|
+
let first = !owed.size;
|
|
218
|
+
owed.set(ref, map);
|
|
219
|
+
if (first) defer(pay);
|
|
220
|
+
};
|
|
221
|
+
let release = (ref)=>{
|
|
222
|
+
owed.delete(ref);
|
|
223
|
+
backing().delete(ref);
|
|
224
|
+
};
|
|
225
|
+
let asks = (ws)=>{
|
|
226
|
+
let cached = queries.get(ws);
|
|
227
|
+
if (cached) return cached;
|
|
228
|
+
let held = ws.deserializeAttachment();
|
|
229
|
+
let found = copy(held?.subref ? backing().read(held.subref) : held?.subs);
|
|
230
|
+
if (held?.subref) baselines.set(ws, copy(found));
|
|
231
|
+
for (let [id, ask] of Object.entries(unpack(held?.subdelta ?? {}))){
|
|
232
|
+
if (ask === null) delete found[id];
|
|
233
|
+
else found[id] = ask;
|
|
234
|
+
}
|
|
235
|
+
queries.set(ws, found);
|
|
236
|
+
return found;
|
|
237
|
+
};
|
|
238
|
+
// Keep the small map on the socket. Once it exceeds the attachment's
|
|
239
|
+
// allowance, keep only its key there and store the queries on this object.
|
|
240
|
+
let hold = (ws, nextSubs, held)=>{
|
|
241
|
+
let next = {
|
|
242
|
+
...held,
|
|
243
|
+
subs: nextSubs,
|
|
244
|
+
subref: undefined,
|
|
245
|
+
subdelta: undefined
|
|
246
|
+
};
|
|
247
|
+
let inline = fitted(next);
|
|
248
|
+
if (inline) {
|
|
249
|
+
ws.serializeAttachment(inline);
|
|
250
|
+
if (held.subref) release(held.subref);
|
|
251
|
+
baselines.delete(ws);
|
|
252
|
+
} else {
|
|
253
|
+
let ref = held.subref ?? crypto.randomUUID();
|
|
254
|
+
let short = {
|
|
255
|
+
...next,
|
|
256
|
+
subs: undefined,
|
|
257
|
+
subref: ref
|
|
258
|
+
};
|
|
259
|
+
// A watch burst changes only part of a large stored map. Keep that
|
|
260
|
+
// difference on the socket; compact only when it no longer fits.
|
|
261
|
+
let baseline = baselines.get(ws);
|
|
262
|
+
let delta = copy();
|
|
263
|
+
if (baseline) {
|
|
264
|
+
for (let [id, ask] of Object.entries(nextSubs)){
|
|
265
|
+
if (!Object.hasOwn(baseline, id) || baseline[id] !== ask) {
|
|
266
|
+
delta[id] = ask;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
for (let id of Object.keys(baseline)){
|
|
270
|
+
if (!Object.hasOwn(nextSubs, id)) delta[id] = null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
let overlay = baseline && (fitted({
|
|
274
|
+
...short,
|
|
275
|
+
subdelta: delta
|
|
276
|
+
}) ?? fitted({
|
|
277
|
+
...short,
|
|
278
|
+
subdelta: pack(delta)
|
|
279
|
+
}));
|
|
280
|
+
if (overlay) {
|
|
281
|
+
ws.serializeAttachment(overlay);
|
|
282
|
+
} else {
|
|
283
|
+
// Repeated query paths often compress the complete watch map below
|
|
284
|
+
// the attachment limit. Its existing delta format carries the map
|
|
285
|
+
// over an empty base, preserving ACK room before anything spills.
|
|
286
|
+
let packed = fitted({
|
|
287
|
+
...next,
|
|
288
|
+
subs: undefined,
|
|
289
|
+
subdelta: pack(nextSubs)
|
|
290
|
+
});
|
|
291
|
+
if (packed) {
|
|
292
|
+
ws.serializeAttachment(packed);
|
|
293
|
+
if (held.subref) release(held.subref);
|
|
294
|
+
baselines.delete(ws);
|
|
295
|
+
} else {
|
|
296
|
+
let attached = fitted(short);
|
|
297
|
+
if (!attached) return false;
|
|
298
|
+
baselines.set(ws, nextSubs);
|
|
299
|
+
owe(ref, nextSubs);
|
|
300
|
+
ws.serializeAttachment(attached);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
queries.set(ws, nextSubs);
|
|
305
|
+
return true;
|
|
306
|
+
};
|
|
307
|
+
let delivery = (ws, owed, seen = new Map())=>{
|
|
308
|
+
let was = ws.deserializeAttachment();
|
|
309
|
+
let next = {
|
|
310
|
+
...was,
|
|
311
|
+
owed,
|
|
312
|
+
kept: undefined,
|
|
313
|
+
seen: seen.size ? [
|
|
314
|
+
...seen.keys()
|
|
315
|
+
] : undefined,
|
|
316
|
+
snapshots: seen.size ? [
|
|
317
|
+
...seen.values()
|
|
318
|
+
].map((s)=>s ?? null) : undefined
|
|
319
|
+
};
|
|
320
|
+
let previous = was?.kept ? was.owed : undefined;
|
|
321
|
+
let inline = within(next);
|
|
322
|
+
let spill = owed && seen.size && !inline ? owed : undefined;
|
|
323
|
+
if (spill) {
|
|
324
|
+
proofs().write(spill, [
|
|
325
|
+
...seen
|
|
326
|
+
].map(([id, proof])=>[
|
|
327
|
+
id,
|
|
328
|
+
proof ?? null
|
|
329
|
+
]));
|
|
330
|
+
next = {
|
|
331
|
+
...next,
|
|
332
|
+
kept: true,
|
|
333
|
+
seen: undefined,
|
|
334
|
+
snapshots: undefined
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
if (inline || within(next)) ws.serializeAttachment(next);
|
|
339
|
+
else if (!hold(ws, asks(ws), next)) {
|
|
340
|
+
throw new RangeError('socket attachment has no room for an ACK key');
|
|
341
|
+
}
|
|
342
|
+
} catch (error) {
|
|
343
|
+
if (spill && spill !== previous) proofs().delete(spill);
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
if (previous && previous !== spill) proofs().delete(previous);
|
|
347
|
+
};
|
|
348
|
+
let drop = (ws)=>{
|
|
349
|
+
if (closed.has(ws)) return;
|
|
350
|
+
closed.add(ws);
|
|
351
|
+
let to = sinks.get(ws);
|
|
352
|
+
let dropped = undefined;
|
|
353
|
+
if (to) {
|
|
354
|
+
to.close();
|
|
355
|
+
dropped = subs.drop(to.send);
|
|
356
|
+
}
|
|
357
|
+
sinks.delete(ws);
|
|
358
|
+
queries.delete(ws);
|
|
359
|
+
baselines.delete(ws);
|
|
360
|
+
let held = ws.deserializeAttachment();
|
|
361
|
+
if (held?.subref || held?.kept) {
|
|
362
|
+
// The socket can outlive this incarnation. Clear its pointer before
|
|
363
|
+
// deleting the row, so a later wake cannot read a row we removed.
|
|
364
|
+
ws.serializeAttachment({
|
|
365
|
+
...held,
|
|
366
|
+
subref: undefined,
|
|
367
|
+
subdelta: undefined,
|
|
368
|
+
subs: undefined,
|
|
369
|
+
kept: undefined,
|
|
370
|
+
owed: undefined
|
|
371
|
+
});
|
|
372
|
+
if (held.subref) release(held.subref);
|
|
373
|
+
if (held.kept && held.owed) proofs().delete(held.owed);
|
|
374
|
+
}
|
|
375
|
+
return dropped;
|
|
376
|
+
};
|
|
377
|
+
let retire = (ws, error)=>{
|
|
378
|
+
if (!(error instanceof MissingSubscriptions)) throw error;
|
|
379
|
+
finish(ws);
|
|
380
|
+
try {
|
|
381
|
+
ws.close?.(1012, 'subscriptions lost');
|
|
382
|
+
} catch {}
|
|
383
|
+
report?.(error);
|
|
384
|
+
};
|
|
385
|
+
// A protocol retirement has no caller to await its final saved writes.
|
|
386
|
+
let finish = (ws)=>{
|
|
387
|
+
let out = drop(ws);
|
|
388
|
+
if (out) out.catch((error)=>fault(error, 'socket close'));
|
|
389
|
+
};
|
|
390
|
+
// The sink for a socket, created once. A socket this object has not seen
|
|
391
|
+
// before may still be one it inherited, so its stored subscriptions are
|
|
392
|
+
// re-opened here — the client is sent its current results, which is the
|
|
393
|
+
// resync.
|
|
394
|
+
let authorize = (ws)=>{
|
|
395
|
+
if (!opts.authorize) return true;
|
|
396
|
+
// A socket is closed once: two checks in flight together (a wake's and a
|
|
397
|
+
// message's) both refuse it, and only the first closes it.
|
|
398
|
+
let refused = (why)=>{
|
|
399
|
+
if (closed.has(ws)) return false;
|
|
400
|
+
if (why !== undefined) {
|
|
401
|
+
report?.(why instanceof Error ? why : new Error(String(why)));
|
|
402
|
+
}
|
|
403
|
+
finish(ws);
|
|
404
|
+
try {
|
|
405
|
+
ws.close?.(1012, 'authorization handshake required');
|
|
406
|
+
} catch {}
|
|
407
|
+
return false;
|
|
408
|
+
};
|
|
409
|
+
try {
|
|
410
|
+
let held = ws.deserializeAttachment();
|
|
411
|
+
let out = opts.authorize(reading(held), held?.writer, held?.read);
|
|
412
|
+
let admit = (ok)=>{
|
|
413
|
+
if (closed.has(ws)) return refused();
|
|
414
|
+
if (!ok) {
|
|
415
|
+
return refused(accepted.has(ws) && !admitted.has(ws) ? new Error('a socket its handshake admitted was refused') : undefined);
|
|
416
|
+
}
|
|
417
|
+
admitted.add(ws);
|
|
418
|
+
return true;
|
|
419
|
+
};
|
|
420
|
+
return isPromise(out) ? out.then(admit, refused) : admit(out);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
return refused(error);
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
let sink = (ws, openings, deferStatic = false)=>{
|
|
426
|
+
let to = sinks.get(ws)?.send;
|
|
427
|
+
if (to) return after(recovered.get(ws), ()=>to);
|
|
428
|
+
let held = ws.deserializeAttachment();
|
|
429
|
+
let saved;
|
|
430
|
+
if (held?.owed && held.kept) {
|
|
431
|
+
saved = proofs().read(held.owed);
|
|
432
|
+
if (!saved) {
|
|
433
|
+
let error = new Error('socket delivery checkpoint missing');
|
|
434
|
+
if (report) report(error);
|
|
435
|
+
else fault(error, 'socket wake');
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
let seen = new Map(saved ? saved.map(([id, proof])=>[
|
|
439
|
+
id,
|
|
440
|
+
proof ?? undefined
|
|
441
|
+
]) : (held?.owed ? held.seen ?? [] : []).map((id, i)=>[
|
|
442
|
+
id,
|
|
443
|
+
held?.snapshots?.[i] ?? undefined
|
|
444
|
+
]));
|
|
445
|
+
if (!held?.owed && held?.seen?.length) {
|
|
446
|
+
delivery(ws);
|
|
447
|
+
}
|
|
448
|
+
// Gate the transport, not just the registry sink: ACKs and timer flushes
|
|
449
|
+
// can release frames long after the subscription's last read.
|
|
450
|
+
let waiting = [];
|
|
451
|
+
let sending = 0;
|
|
452
|
+
let delivering = false;
|
|
453
|
+
let deliver = async ()=>{
|
|
454
|
+
try {
|
|
455
|
+
while(waiting.length && !closed.has(ws) && open(ws)){
|
|
456
|
+
// Frames already queued can leave together. Anything queued while
|
|
457
|
+
// this check is away belongs to the next authorization.
|
|
458
|
+
let batch = waiting.splice(0);
|
|
459
|
+
sending = batch.length;
|
|
460
|
+
if (!await authorize(ws) || closed.has(ws) || !open(ws)) return;
|
|
461
|
+
for (let data of batch)ws.send(data);
|
|
462
|
+
sending = 0;
|
|
463
|
+
}
|
|
464
|
+
} catch {
|
|
465
|
+
finish(ws);
|
|
466
|
+
try {
|
|
467
|
+
ws.close?.(1012, 'authorization handshake required');
|
|
468
|
+
} catch {}
|
|
469
|
+
} finally{
|
|
470
|
+
waiting.length = sending = 0;
|
|
471
|
+
delivering = false;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
let transport = !opts.authorize ? ws : {
|
|
475
|
+
get bufferedAmount () {
|
|
476
|
+
return ws.bufferedAmount;
|
|
477
|
+
},
|
|
478
|
+
send: (data)=>{
|
|
479
|
+
if (waiting.length + sending >= 64) {
|
|
480
|
+
finish(ws);
|
|
481
|
+
ws.close?.(1012, 'authorization delivery backlog');
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
waiting.push(data);
|
|
485
|
+
if (delivering) return;
|
|
486
|
+
delivering = true;
|
|
487
|
+
let pending = Promise.resolve().then(deliver);
|
|
488
|
+
ctx.waitUntil?.(pending);
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
let fresh = queue(transport, timer, ()=>open(ws), {
|
|
492
|
+
owed: held?.owed,
|
|
493
|
+
sent: (frames, token)=>{
|
|
494
|
+
if (ws.deserializeAttachment()?.frames) seen.clear();
|
|
495
|
+
for (let f of frames){
|
|
496
|
+
if (snapshot(f)) seen.set(f.id, checkpoint(f));
|
|
497
|
+
else if (f.revision !== undefined || f.refused) seen.delete(f.id);
|
|
498
|
+
}
|
|
499
|
+
delivery(ws, token, seen);
|
|
500
|
+
},
|
|
501
|
+
// An ACK that let the next frame out was recorded by `sent` already.
|
|
502
|
+
acked: (owed)=>{
|
|
503
|
+
if (owed) return;
|
|
504
|
+
seen.clear();
|
|
505
|
+
delivery(ws);
|
|
506
|
+
}
|
|
507
|
+
});
|
|
508
|
+
let skip = new Map(seen);
|
|
509
|
+
let previous = new Map();
|
|
510
|
+
let reopening = new Map(Object.entries(asks(ws)));
|
|
511
|
+
let send = (frame)=>{
|
|
512
|
+
if (frame.refused) opts.refused?.(frame.refused);
|
|
513
|
+
let id = frame.id;
|
|
514
|
+
if (reopening.has(id) && reopening.get(id) !== true) {
|
|
515
|
+
reopening.delete(id);
|
|
516
|
+
let sent = skip.get(id);
|
|
517
|
+
skip.delete(id);
|
|
518
|
+
// A proof from the old attachment lets an identical snapshot keep
|
|
519
|
+
// its predecessor on the wire. A changed answer needs a full reset.
|
|
520
|
+
if (sent && snapshot(frame) && !frame.reset && sent.print === checkpoint(frame).print) {
|
|
521
|
+
previous.set(id, sent.revision);
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
frame = {
|
|
525
|
+
...frame,
|
|
526
|
+
reset: true
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
if (frame.revision !== undefined && previous.has(id)) {
|
|
530
|
+
if (frame.since !== undefined) {
|
|
531
|
+
frame = {
|
|
532
|
+
...frame,
|
|
533
|
+
since: previous.get(id)
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
previous.delete(id);
|
|
537
|
+
}
|
|
538
|
+
fresh.send(frame);
|
|
539
|
+
};
|
|
540
|
+
sinks.set(ws, {
|
|
541
|
+
...fresh,
|
|
542
|
+
send,
|
|
543
|
+
forget: (id)=>{
|
|
544
|
+
skip.delete(id);
|
|
545
|
+
previous.delete(id);
|
|
546
|
+
if (!seen.delete(id)) return;
|
|
547
|
+
let held = ws.deserializeAttachment();
|
|
548
|
+
delivery(ws, held?.owed, seen);
|
|
549
|
+
}
|
|
550
|
+
});
|
|
551
|
+
if (held?.acks) fresh.enable(held.frames);
|
|
552
|
+
// The relay keys first: whatever else this socket did, the registry has to
|
|
553
|
+
// know what it is saying before a close can stop saying it.
|
|
554
|
+
let relay = relayOf(ws);
|
|
555
|
+
let out = after(subs.relayed(send, relay), ()=>{
|
|
556
|
+
if (closed.has(ws)) return;
|
|
557
|
+
if (relay.some((key)=>{
|
|
558
|
+
let comp = key.slice(key.indexOf(' ') + 1);
|
|
559
|
+
return subs.vocab?.comp(comp)?.durable == 'connection';
|
|
560
|
+
})) transport.send(JSON.stringify({
|
|
561
|
+
id: '',
|
|
562
|
+
resay: true
|
|
563
|
+
}));
|
|
564
|
+
return after(over(Object.entries(asks(ws)), ([id, ask])=>{
|
|
565
|
+
if (openings) {
|
|
566
|
+
openings.push({
|
|
567
|
+
sink: send,
|
|
568
|
+
id,
|
|
569
|
+
query: ask,
|
|
570
|
+
opts: reading(held),
|
|
571
|
+
writer: held?.writer
|
|
572
|
+
});
|
|
573
|
+
} else {
|
|
574
|
+
return subs.restore([
|
|
575
|
+
{
|
|
576
|
+
sink: send,
|
|
577
|
+
id,
|
|
578
|
+
query: ask,
|
|
579
|
+
opts: reading(held),
|
|
580
|
+
writer: held?.writer
|
|
581
|
+
}
|
|
582
|
+
], deferStatic);
|
|
583
|
+
}
|
|
584
|
+
}), ()=>{});
|
|
585
|
+
});
|
|
586
|
+
if (isPromise(out)) {
|
|
587
|
+
recovered.set(ws, out);
|
|
588
|
+
out.then(()=>recovered.delete(ws), ()=>recovered.delete(ws));
|
|
589
|
+
}
|
|
590
|
+
return after(out, ()=>send);
|
|
591
|
+
};
|
|
592
|
+
let adapter = {
|
|
593
|
+
accept: (request, read, writer, socket)=>{
|
|
594
|
+
if ((request.headers.get('upgrade') ?? '').toLowerCase() != 'websocket') {
|
|
595
|
+
return json({
|
|
596
|
+
error: 'NotAllowed',
|
|
597
|
+
message: 'this is a WebSocket endpoint'
|
|
598
|
+
}, 405);
|
|
599
|
+
}
|
|
600
|
+
let pair = new WebSocketPair();
|
|
601
|
+
// Accepted for hibernation: the runtime holds this socket while the
|
|
602
|
+
// object is evicted and wakes the object with the next frame, so an idle
|
|
603
|
+
// client costs nothing.
|
|
604
|
+
if (read || writer) {
|
|
605
|
+
pair[1].serializeAttachment({
|
|
606
|
+
read,
|
|
607
|
+
writer
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
ctx.acceptWebSocket(pair[1], socket?.tags);
|
|
611
|
+
accepted.add(pair[1]);
|
|
612
|
+
socket?.opened(pair[1]);
|
|
613
|
+
// The 101 carries the other end; `webSocket` is the runtime's own
|
|
614
|
+
// ResponseInit field, which no standard declares.
|
|
615
|
+
let protocol = opts.protocol?.(request);
|
|
616
|
+
return new Response(null, {
|
|
617
|
+
status: 101,
|
|
618
|
+
webSocket: pair[0],
|
|
619
|
+
...protocol ? {
|
|
620
|
+
headers: {
|
|
621
|
+
'sec-websocket-protocol': protocol
|
|
622
|
+
}
|
|
623
|
+
} : {}
|
|
624
|
+
});
|
|
625
|
+
},
|
|
626
|
+
message: (ws, data, scope)=>{
|
|
627
|
+
if (closed.has(ws)) return;
|
|
628
|
+
if (!open(ws)) return;
|
|
629
|
+
let received = Date.now();
|
|
630
|
+
let input = decode(data);
|
|
631
|
+
if (answered(ws, input, received)) return;
|
|
632
|
+
let run = ()=>{
|
|
633
|
+
let held = ws.deserializeAttachment();
|
|
634
|
+
let msg = 'value' in input ? input.value : undefined;
|
|
635
|
+
// A held identity is vouched at the handshake. A host may refresh its
|
|
636
|
+
// current standing on wake without making the page reopen its socket.
|
|
637
|
+
let relay = msg && typeof msg == 'object' && 'relay' in msg && Array.isArray(msg.relay);
|
|
638
|
+
let valid = relay ? held?.writer === undefined ? false : opts.writer?.(held.writer) ?? true : true;
|
|
639
|
+
return after(valid, (valid)=>{
|
|
640
|
+
if (!valid) {
|
|
641
|
+
finish(ws);
|
|
642
|
+
ws.close?.(1012, 'writer handshake required');
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
return after(after(authorize(ws), (ok)=>ok ? sink(ws, undefined, !!opts.deferStatic && !!relay) : undefined), (to)=>{
|
|
646
|
+
if (!to) return;
|
|
647
|
+
let ask = asked('value' in input ? input.value : null);
|
|
648
|
+
let sender = sinks.get(ws);
|
|
649
|
+
if (ask?.ack) return sender.ack(ask.ack);
|
|
650
|
+
if (ask) sender.forget(ask.id);
|
|
651
|
+
if (ask?.acks) sender.enable(ask.frames);
|
|
652
|
+
let was = subs.relaying(to).join('\n');
|
|
653
|
+
return after(receive(subs, to, data, undefined, input, reading(ws.deserializeAttachment()), ws.deserializeAttachment()?.writer), (verdict)=>{
|
|
654
|
+
if (verdict == 'close') {
|
|
655
|
+
finish(ws);
|
|
656
|
+
ws.close?.(1008, 'relay flood');
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
// Only when it moved: a frame that relays nothing should not rewrite
|
|
660
|
+
// an attachment, and most frames relay nothing.
|
|
661
|
+
let now = subs.relaying(to);
|
|
662
|
+
if (now.join('\n') != was) remember(ws, now);
|
|
663
|
+
if (!ask) return;
|
|
664
|
+
let subscriptions = copy(asks(ws));
|
|
665
|
+
if (ask.ask === undefined) delete subscriptions[ask.id];
|
|
666
|
+
else subscriptions[ask.id] = ask.ask;
|
|
667
|
+
let held = ws.deserializeAttachment();
|
|
668
|
+
if (hold(ws, subscriptions, {
|
|
669
|
+
...held,
|
|
670
|
+
...ask.acks ? {
|
|
671
|
+
acks: true
|
|
672
|
+
} : {},
|
|
673
|
+
...ask.frames ? {
|
|
674
|
+
frames: true
|
|
675
|
+
} : {}
|
|
676
|
+
})) return;
|
|
677
|
+
subs.close(to, ask.id);
|
|
678
|
+
to({
|
|
679
|
+
id: ask.id,
|
|
680
|
+
refused: refusal(new RangeError('too many subscriptions to survive hibernation'))
|
|
681
|
+
});
|
|
682
|
+
});
|
|
683
|
+
});
|
|
684
|
+
});
|
|
685
|
+
};
|
|
686
|
+
let kind = messageKind('value' in input ? input.value : null);
|
|
687
|
+
let recover = ()=>{
|
|
688
|
+
try {
|
|
689
|
+
let out = run();
|
|
690
|
+
if (isPromise(out)) return out.catch((error)=>retire(ws, error));
|
|
691
|
+
} catch (error) {
|
|
692
|
+
retire(ws, error);
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
return scope ? scope(kind, recover) : recover();
|
|
696
|
+
},
|
|
697
|
+
close: drop,
|
|
698
|
+
renew: async ()=>{
|
|
699
|
+
if (!opts.renewals) return null;
|
|
700
|
+
await adapter.wake();
|
|
701
|
+
return await opts.renewals.run();
|
|
702
|
+
},
|
|
703
|
+
restand: async (update)=>{
|
|
704
|
+
await Promise.all(ctx.getWebSockets().map((ws)=>{
|
|
705
|
+
if (closed.has(ws) || !open(ws)) return;
|
|
706
|
+
let held = ws.deserializeAttachment();
|
|
707
|
+
let read = update(held?.read);
|
|
708
|
+
if (read !== held?.read) ws.serializeAttachment({
|
|
709
|
+
...held,
|
|
710
|
+
read
|
|
711
|
+
});
|
|
712
|
+
return authorize(ws);
|
|
713
|
+
}));
|
|
714
|
+
},
|
|
715
|
+
wake: (deferStatic = false)=>{
|
|
716
|
+
if (waking) {
|
|
717
|
+
return deferStatic ? waking : waking.then(()=>subs.resume?.());
|
|
718
|
+
}
|
|
719
|
+
let openings = [];
|
|
720
|
+
// Start the inherited readers' checks together so the host can batch
|
|
721
|
+
// them. Register their sinks in order as their own checks answer.
|
|
722
|
+
let inherited = ctx.getWebSockets().filter((ws)=>!closed.has(ws) && open(ws)).map((ws)=>({
|
|
723
|
+
ws,
|
|
724
|
+
check: sinks.has(ws) || authorize(ws)
|
|
725
|
+
}));
|
|
726
|
+
let out = after(over(inherited, ({ ws, check })=>{
|
|
727
|
+
if (closed.has(ws) || !open(ws)) return;
|
|
728
|
+
// An open sink already has its watches. Messages and delivery
|
|
729
|
+
// check its standing when it next uses them.
|
|
730
|
+
if (sinks.has(ws)) return recovered.get(ws);
|
|
731
|
+
try {
|
|
732
|
+
let restored = after(check, (ok)=>ok && !closed.has(ws) && open(ws) ? sink(ws, openings) : undefined);
|
|
733
|
+
if (isPromise(restored)) {
|
|
734
|
+
return restored.then(()=>{}, (error)=>retire(ws, error));
|
|
735
|
+
}
|
|
736
|
+
} catch (error) {
|
|
737
|
+
retire(ws, error);
|
|
738
|
+
}
|
|
739
|
+
}), ()=>after(openings.length ? subs.restore(openings, deferStatic) : undefined, ()=>!deferStatic ? subs.resume?.() : undefined));
|
|
740
|
+
if (isPromise(out)) {
|
|
741
|
+
waking = out;
|
|
742
|
+
out.then(()=>waking = undefined, ()=>waking = undefined);
|
|
743
|
+
}
|
|
744
|
+
return out;
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
return adapter;
|
|
748
|
+
};
|
|
749
|
+
//# sourceMappingURL=sockets.js.map
|