dynamodb-reactive 0.3.0 → 0.5.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 +121 -43
- package/dist/{client-Zb67giI5.d.ts → client-wZQ9XC9S.d.ts} +11 -0
- package/dist/client.cjs +53 -55
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +53 -55
- package/dist/client.js.map +1 -1
- package/dist/cloudflare.cjs +461 -0
- package/dist/cloudflare.cjs.map +1 -0
- package/dist/cloudflare.d.cts +129 -0
- package/dist/cloudflare.d.ts +129 -0
- package/dist/cloudflare.js +456 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/cluster.cjs +66 -66
- package/dist/cluster.cjs.map +1 -1
- package/dist/cluster.d.cts +2 -78
- package/dist/cluster.d.ts +2 -78
- package/dist/cluster.js +66 -66
- package/dist/cluster.js.map +1 -1
- package/dist/core.cjs +1 -3
- package/dist/core.cjs.map +1 -1
- package/dist/core.js +1 -3
- package/dist/core.js.map +1 -1
- package/dist/hub.cjs +164 -0
- package/dist/hub.cjs.map +1 -0
- package/dist/hub.d.cts +91 -0
- package/dist/hub.d.ts +91 -0
- package/dist/hub.js +157 -0
- package/dist/hub.js.map +1 -0
- package/dist/index.cjs +1 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -3
- package/dist/index.js.map +1 -1
- package/dist/infra.cjs +19 -33
- package/dist/infra.cjs.map +1 -1
- package/dist/infra.js +19 -33
- package/dist/infra.js.map +1 -1
- package/dist/protocol-C4Syt_Bl.d.ts +78 -0
- package/dist/react.cjs +56 -65
- package/dist/react.cjs.map +1 -1
- package/dist/react.js +56 -65
- package/dist/react.js.map +1 -1
- package/dist/server.cjs +46 -139
- package/dist/server.cjs.map +1 -1
- package/dist/server.js +46 -139
- package/dist/server.js.map +1 -1
- package/package.json +42 -24
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
// ../client/src/cluster.ts
|
|
2
|
+
var DEFAULT_TICKET_LIFETIME_SECONDS = 60;
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === "object" && value !== null;
|
|
5
|
+
}
|
|
6
|
+
function parseClusterTicket(value) {
|
|
7
|
+
if (!isRecord(value) || typeof value.token !== "string" || value.token.length === 0 || typeof value.expiresAt !== "number" || !Number.isFinite(value.expiresAt) || typeof value.url !== "string") {
|
|
8
|
+
throw new Error("Cluster ticket response is invalid");
|
|
9
|
+
}
|
|
10
|
+
const url = new URL(value.url);
|
|
11
|
+
if (url.protocol !== "wss:") throw new Error("Cluster ticket URL must use WSS");
|
|
12
|
+
return { token: value.token, expiresAt: value.expiresAt, url: url.toString() };
|
|
13
|
+
}
|
|
14
|
+
var encoder = new TextEncoder();
|
|
15
|
+
function base64UrlEncode(bytes) {
|
|
16
|
+
let binary = "";
|
|
17
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
18
|
+
return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
|
|
19
|
+
}
|
|
20
|
+
function base64UrlDecode(value) {
|
|
21
|
+
const padded = value.replaceAll("-", "+").replaceAll("_", "/");
|
|
22
|
+
const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
23
|
+
const bytes = new Uint8Array(new ArrayBuffer(binary.length));
|
|
24
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
25
|
+
return bytes;
|
|
26
|
+
}
|
|
27
|
+
function hmacKey(secret, usage) {
|
|
28
|
+
return crypto.subtle.importKey(
|
|
29
|
+
"raw",
|
|
30
|
+
encoder.encode(secret),
|
|
31
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
32
|
+
false,
|
|
33
|
+
[usage]
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
async function createSignedClusterTicket(options) {
|
|
37
|
+
const expiresAt = Math.floor((options.now ?? Date.now()) / 1e3) + (options.lifetimeSeconds ?? DEFAULT_TICKET_LIFETIME_SECONDS);
|
|
38
|
+
const payload = base64UrlEncode(
|
|
39
|
+
encoder.encode(JSON.stringify({ p: options.principal, exp: expiresAt }))
|
|
40
|
+
);
|
|
41
|
+
const signature = new Uint8Array(
|
|
42
|
+
await crypto.subtle.sign(
|
|
43
|
+
"HMAC",
|
|
44
|
+
await hmacKey(options.secret, "sign"),
|
|
45
|
+
encoder.encode(payload)
|
|
46
|
+
)
|
|
47
|
+
);
|
|
48
|
+
return parseClusterTicket({
|
|
49
|
+
token: `${payload}.${base64UrlEncode(signature)}`,
|
|
50
|
+
expiresAt,
|
|
51
|
+
url: options.url
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
async function verifySignedClusterTicket(token, secret, now = Date.now()) {
|
|
55
|
+
const parts = token.split(".");
|
|
56
|
+
if (parts.length !== 2) return void 0;
|
|
57
|
+
const [payload, signature] = parts;
|
|
58
|
+
if (!payload || !signature) return void 0;
|
|
59
|
+
try {
|
|
60
|
+
const valid = await crypto.subtle.verify(
|
|
61
|
+
"HMAC",
|
|
62
|
+
await hmacKey(secret, "verify"),
|
|
63
|
+
base64UrlDecode(signature),
|
|
64
|
+
encoder.encode(payload)
|
|
65
|
+
);
|
|
66
|
+
if (!valid) return void 0;
|
|
67
|
+
const claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(payload)));
|
|
68
|
+
if (!isRecord(claims) || typeof claims.p !== "string" || typeof claims.exp !== "number" || claims.exp <= Math.floor(now / 1e3)) {
|
|
69
|
+
return void 0;
|
|
70
|
+
}
|
|
71
|
+
return claims.p;
|
|
72
|
+
} catch {
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// ../client/src/hub.ts
|
|
78
|
+
var DEFAULT_MAX_ATTACHMENT_BYTES = 2048;
|
|
79
|
+
var ReactiveHubError = class extends Error {
|
|
80
|
+
constructor(message) {
|
|
81
|
+
super(message);
|
|
82
|
+
this.name = "ReactiveHubError";
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
function isRecord2(value) {
|
|
86
|
+
return typeof value === "object" && value !== null;
|
|
87
|
+
}
|
|
88
|
+
function isHubRequest(value) {
|
|
89
|
+
if (!isRecord2(value)) return false;
|
|
90
|
+
return (value.type === "subscribe" || value.type === "unsubscribe") && typeof value.connectionId === "string" && typeof value.subscriptionId === "string" && typeof value.generation === "number" && (value.type === "unsubscribe" || typeof value.path === "string");
|
|
91
|
+
}
|
|
92
|
+
function bearerToken(request) {
|
|
93
|
+
const match = /^Bearer ([^\s]+)$/u.exec(request.headers.get("authorization") ?? "");
|
|
94
|
+
return match?.[1] ?? "";
|
|
95
|
+
}
|
|
96
|
+
function createHubSocketState(connectionId, principal, connectedAt) {
|
|
97
|
+
return {
|
|
98
|
+
connectionId,
|
|
99
|
+
principal,
|
|
100
|
+
subscriptions: [],
|
|
101
|
+
...connectedAt === void 0 ? {} : { connectedAt }
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
function socketState(socket) {
|
|
105
|
+
const state = socket.deserializeAttachment();
|
|
106
|
+
return { ...state, subscriptions: state.subscriptions.filter((entry) => entry.path) };
|
|
107
|
+
}
|
|
108
|
+
function send(socket, event) {
|
|
109
|
+
try {
|
|
110
|
+
socket.send(JSON.stringify(event));
|
|
111
|
+
} catch {
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function createReactiveHub(options) {
|
|
115
|
+
const { sockets, versions } = options;
|
|
116
|
+
const maxAttachmentBytes = options.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES;
|
|
117
|
+
const resolve = (path) => typeof options.paths === "function" ? options.paths(path) : Object.hasOwn(options.paths, path) ? options.paths[path] : void 0;
|
|
118
|
+
const ownedSocket = (connectionId, principal) => {
|
|
119
|
+
const socket = sockets.byConnectionId(connectionId);
|
|
120
|
+
return socket && socketState(socket).principal === principal ? socket : void 0;
|
|
121
|
+
};
|
|
122
|
+
const subscribersOf = (path) => sockets.all().flatMap(
|
|
123
|
+
(socket) => socketState(socket).subscriptions.filter((subscription) => subscription.path === path).map((subscription) => ({ socket, subscription }))
|
|
124
|
+
);
|
|
125
|
+
const bump = async (path) => {
|
|
126
|
+
const fromVersion = await versions.get(path);
|
|
127
|
+
const toVersion = fromVersion + 1;
|
|
128
|
+
await versions.set(path, toVersion);
|
|
129
|
+
return { fromVersion, toVersion };
|
|
130
|
+
};
|
|
131
|
+
return {
|
|
132
|
+
/** Answers the client's `init` and `ping` frames. */
|
|
133
|
+
message(socket, raw) {
|
|
134
|
+
let frame;
|
|
135
|
+
try {
|
|
136
|
+
frame = JSON.parse(raw);
|
|
137
|
+
} catch {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const type = isRecord2(frame) ? frame.type : void 0;
|
|
141
|
+
if (type === "init") {
|
|
142
|
+
send(socket, { type: "connected", connectionId: socketState(socket).connectionId });
|
|
143
|
+
} else if (type === "ping") {
|
|
144
|
+
send(socket, { type: "pong" });
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
async subscribe(request, principal) {
|
|
148
|
+
const handler = resolve(request.path);
|
|
149
|
+
if (!handler) throw new ReactiveHubError("Unknown subscription path");
|
|
150
|
+
if (!ownedSocket(request.connectionId, principal)) {
|
|
151
|
+
throw new ReactiveHubError("Unknown connection");
|
|
152
|
+
}
|
|
153
|
+
const context = { path: request.path, principal, input: request.input };
|
|
154
|
+
if (handler.authorize && !await handler.authorize(context)) {
|
|
155
|
+
throw new ReactiveHubError("Subscription not allowed");
|
|
156
|
+
}
|
|
157
|
+
const socket = ownedSocket(request.connectionId, principal);
|
|
158
|
+
if (!socket) throw new ReactiveHubError("Unknown connection");
|
|
159
|
+
const state = socketState(socket);
|
|
160
|
+
const next = {
|
|
161
|
+
...state,
|
|
162
|
+
subscriptions: [
|
|
163
|
+
...state.subscriptions.filter((entry) => entry.subscriptionId !== request.subscriptionId),
|
|
164
|
+
{
|
|
165
|
+
subscriptionId: request.subscriptionId,
|
|
166
|
+
generation: request.generation,
|
|
167
|
+
path: request.path
|
|
168
|
+
}
|
|
169
|
+
]
|
|
170
|
+
};
|
|
171
|
+
if (new TextEncoder().encode(JSON.stringify(next)).length > maxAttachmentBytes) {
|
|
172
|
+
throw new ReactiveHubError("Too many subscriptions on this connection");
|
|
173
|
+
}
|
|
174
|
+
socket.serializeAttachment(next);
|
|
175
|
+
const version = await versions.get(request.path);
|
|
176
|
+
const data = await handler.snapshot(context);
|
|
177
|
+
return {
|
|
178
|
+
type: "snapshot",
|
|
179
|
+
subscriptionId: request.subscriptionId,
|
|
180
|
+
generation: request.generation,
|
|
181
|
+
version,
|
|
182
|
+
data
|
|
183
|
+
};
|
|
184
|
+
},
|
|
185
|
+
unsubscribe(request, principal) {
|
|
186
|
+
const socket = ownedSocket(request.connectionId, principal);
|
|
187
|
+
if (!socket) return;
|
|
188
|
+
const state = socketState(socket);
|
|
189
|
+
socket.serializeAttachment({
|
|
190
|
+
...state,
|
|
191
|
+
subscriptions: state.subscriptions.filter(
|
|
192
|
+
(entry) => entry.subscriptionId !== request.subscriptionId
|
|
193
|
+
)
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
/** Bumps the path's version and asks each of its subscribers to re-fetch. */
|
|
197
|
+
async notify(path) {
|
|
198
|
+
const { fromVersion, toVersion } = await bump(path);
|
|
199
|
+
for (const { socket, subscription } of subscribersOf(path)) {
|
|
200
|
+
send(socket, {
|
|
201
|
+
type: "resync",
|
|
202
|
+
subscriptionId: subscription.subscriptionId,
|
|
203
|
+
generation: subscription.generation,
|
|
204
|
+
fromVersion,
|
|
205
|
+
toVersion,
|
|
206
|
+
messageId: crypto.randomUUID()
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
/**
|
|
211
|
+
* Bumps the path's version and sends the same JSON patches to each subscriber.
|
|
212
|
+
* Use it only when every subscriber of the path sees the same data.
|
|
213
|
+
*/
|
|
214
|
+
async publish(path, patches) {
|
|
215
|
+
const { fromVersion, toVersion } = await bump(path);
|
|
216
|
+
for (const { socket, subscription } of subscribersOf(path)) {
|
|
217
|
+
send(socket, {
|
|
218
|
+
type: "patch",
|
|
219
|
+
subscriptionId: subscription.subscriptionId,
|
|
220
|
+
generation: subscription.generation,
|
|
221
|
+
fromVersion,
|
|
222
|
+
toVersion,
|
|
223
|
+
messageId: crypto.randomUUID(),
|
|
224
|
+
patches
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ../client/src/cloudflare.ts
|
|
232
|
+
var HUB_PRINCIPAL_HEADER = "x-reactive-principal";
|
|
233
|
+
var HUB_ACTION_URL = "https://reactive-hub/";
|
|
234
|
+
var PRESENCE_TAG_PREFIX = "presence:";
|
|
235
|
+
var PRESENCE_KEY_PREFIX = "presence:";
|
|
236
|
+
var DEFAULT_PRESENCE_TIMEOUT_MS = 9e4;
|
|
237
|
+
var HEARTBEAT_TIMEOUT_CLOSE_CODE = 4001;
|
|
238
|
+
function json(value, status = 200) {
|
|
239
|
+
return Response.json(value, { status, headers: { "cache-control": "no-store" } });
|
|
240
|
+
}
|
|
241
|
+
function error(message, status) {
|
|
242
|
+
return json({ type: "error", message }, status);
|
|
243
|
+
}
|
|
244
|
+
function workersGlobal(name) {
|
|
245
|
+
return globalThis[name];
|
|
246
|
+
}
|
|
247
|
+
function createDurableObjectHub(ctx, options) {
|
|
248
|
+
const versionKey = options.versionKey ?? ((path) => `version:${path}`);
|
|
249
|
+
const randomId = options.randomId ?? (() => crypto.randomUUID());
|
|
250
|
+
const hub = createReactiveHub({
|
|
251
|
+
sockets: {
|
|
252
|
+
all: () => ctx.getWebSockets(),
|
|
253
|
+
// Tagging by connection id lets HTTP subscribes find the socket after hibernation.
|
|
254
|
+
byConnectionId: (connectionId) => ctx.getWebSockets(connectionId)[0]
|
|
255
|
+
},
|
|
256
|
+
versions: {
|
|
257
|
+
get: async (path) => await ctx.storage.get(versionKey(path)) ?? 0,
|
|
258
|
+
set: (path, version) => ctx.storage.put(versionKey(path), version)
|
|
259
|
+
},
|
|
260
|
+
paths: options.paths,
|
|
261
|
+
...options.maxAttachmentBytes === void 0 ? {} : { maxAttachmentBytes: options.maxAttachmentBytes }
|
|
262
|
+
});
|
|
263
|
+
if (options.autoPong !== false) {
|
|
264
|
+
const Pair = workersGlobal("WebSocketRequestResponsePair");
|
|
265
|
+
if (Pair && ctx.setWebSocketAutoResponse) {
|
|
266
|
+
ctx.setWebSocketAutoResponse(
|
|
267
|
+
new Pair(JSON.stringify({ type: "ping" }), JSON.stringify({ type: "pong" }))
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const tracked = new Set(options.presence?.principals ?? []);
|
|
272
|
+
const timeoutMs = options.presence?.timeoutMs ?? DEFAULT_PRESENCE_TIMEOUT_MS;
|
|
273
|
+
const lastSeen = (socket) => Math.max(
|
|
274
|
+
ctx.getWebSocketAutoResponseTimestamp?.(socket)?.getTime() ?? 0,
|
|
275
|
+
socket.deserializeAttachment().connectedAt ?? 0
|
|
276
|
+
);
|
|
277
|
+
const liveSockets = (principal, closing) => {
|
|
278
|
+
const now = Date.now();
|
|
279
|
+
return ctx.getWebSockets(PRESENCE_TAG_PREFIX + principal).filter((socket) => socket !== closing && now - lastSeen(socket) <= timeoutMs);
|
|
280
|
+
};
|
|
281
|
+
const reconcile = async (principal, closing) => {
|
|
282
|
+
const present = liveSockets(principal, closing).length > 0;
|
|
283
|
+
const key = PRESENCE_KEY_PREFIX + principal;
|
|
284
|
+
if ((await ctx.storage.get(key) ?? false) === present) return;
|
|
285
|
+
await ctx.storage.put(key, present);
|
|
286
|
+
await options.presence?.onChange?.(principal, present);
|
|
287
|
+
};
|
|
288
|
+
const scheduleSweep = async () => {
|
|
289
|
+
const { storage } = ctx;
|
|
290
|
+
if (!storage.getAlarm || !storage.setAlarm) {
|
|
291
|
+
throw new Error("Hub presence needs Durable Object alarms");
|
|
292
|
+
}
|
|
293
|
+
const seen = [...tracked].flatMap(
|
|
294
|
+
(principal) => ctx.getWebSockets(PRESENCE_TAG_PREFIX + principal).map((socket) => lastSeen(socket))
|
|
295
|
+
);
|
|
296
|
+
if (seen.length === 0) return;
|
|
297
|
+
const due = Math.min(...seen) + timeoutMs + 1;
|
|
298
|
+
const current = await storage.getAlarm();
|
|
299
|
+
if (current === null || current > due) await storage.setAlarm(due);
|
|
300
|
+
};
|
|
301
|
+
const closed = async (socket) => {
|
|
302
|
+
if (tracked.size === 0) return;
|
|
303
|
+
const { principal } = socket.deserializeAttachment();
|
|
304
|
+
if (tracked.has(principal)) await reconcile(principal, socket);
|
|
305
|
+
};
|
|
306
|
+
const accept = async (request) => {
|
|
307
|
+
const principal = request.headers.get(HUB_PRINCIPAL_HEADER);
|
|
308
|
+
if (!principal) return error("Unauthorized", 401);
|
|
309
|
+
const Pair = options.WebSocketPair ?? workersGlobal("WebSocketPair");
|
|
310
|
+
if (!Pair) throw new Error("WebSocketPair is not available in this runtime");
|
|
311
|
+
const pair = new Pair();
|
|
312
|
+
const connectionId = randomId();
|
|
313
|
+
const isTracked = tracked.has(principal);
|
|
314
|
+
ctx.acceptWebSocket(
|
|
315
|
+
pair[1],
|
|
316
|
+
isTracked ? [connectionId, PRESENCE_TAG_PREFIX + principal] : [connectionId]
|
|
317
|
+
);
|
|
318
|
+
pair[1].serializeAttachment(
|
|
319
|
+
createHubSocketState(connectionId, principal, isTracked ? Date.now() : void 0)
|
|
320
|
+
);
|
|
321
|
+
if (isTracked) {
|
|
322
|
+
await reconcile(principal);
|
|
323
|
+
await scheduleSweep();
|
|
324
|
+
}
|
|
325
|
+
return new Response(null, { status: 101, webSocket: pair[0] });
|
|
326
|
+
};
|
|
327
|
+
const act = async (action) => {
|
|
328
|
+
try {
|
|
329
|
+
switch (action.action) {
|
|
330
|
+
case "subscribe":
|
|
331
|
+
return json(await hub.subscribe(action.body, action.principal));
|
|
332
|
+
case "unsubscribe":
|
|
333
|
+
hub.unsubscribe(action.body, action.principal);
|
|
334
|
+
return json({ type: "ok" });
|
|
335
|
+
case "notify":
|
|
336
|
+
await hub.notify(action.path);
|
|
337
|
+
return json({ type: "ok" });
|
|
338
|
+
case "publish":
|
|
339
|
+
await hub.publish(action.path, action.patches);
|
|
340
|
+
return json({ type: "ok" });
|
|
341
|
+
default:
|
|
342
|
+
return error("Unknown hub action", 400);
|
|
343
|
+
}
|
|
344
|
+
} catch (cause) {
|
|
345
|
+
if (cause instanceof ReactiveHubError) return error(cause.message, 400);
|
|
346
|
+
throw cause;
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
return {
|
|
350
|
+
hub,
|
|
351
|
+
/** The Durable Object's `fetch`: WebSocket upgrades and actions from `hubClient`. */
|
|
352
|
+
async fetch(request) {
|
|
353
|
+
if (request.headers.get("upgrade") === "websocket") return accept(request);
|
|
354
|
+
return act(await request.json());
|
|
355
|
+
},
|
|
356
|
+
webSocketMessage(socket, message) {
|
|
357
|
+
if (typeof message === "string") hub.message(socket, message);
|
|
358
|
+
},
|
|
359
|
+
async webSocketClose(socket, code) {
|
|
360
|
+
try {
|
|
361
|
+
socket.close(code === 1005 ? 1e3 : code, "closed");
|
|
362
|
+
} catch {
|
|
363
|
+
}
|
|
364
|
+
await closed(socket);
|
|
365
|
+
},
|
|
366
|
+
async webSocketError(socket) {
|
|
367
|
+
try {
|
|
368
|
+
socket.close(1011, "error");
|
|
369
|
+
} catch {
|
|
370
|
+
}
|
|
371
|
+
await closed(socket);
|
|
372
|
+
},
|
|
373
|
+
/** Whether `principal` holds a socket that has pinged within the presence timeout. */
|
|
374
|
+
present(principal) {
|
|
375
|
+
return liveSockets(principal).length > 0;
|
|
376
|
+
},
|
|
377
|
+
/**
|
|
378
|
+
* The Durable Object's `alarm` when presence is tracked: closes silent
|
|
379
|
+
* sockets, reports principals that lost their last one, and reschedules.
|
|
380
|
+
*/
|
|
381
|
+
async alarm() {
|
|
382
|
+
const now = Date.now();
|
|
383
|
+
for (const principal of tracked) {
|
|
384
|
+
for (const socket of ctx.getWebSockets(PRESENCE_TAG_PREFIX + principal)) {
|
|
385
|
+
if (now - lastSeen(socket) <= timeoutMs) continue;
|
|
386
|
+
try {
|
|
387
|
+
socket.close(HEARTBEAT_TIMEOUT_CLOSE_CODE, "Heartbeat timeout");
|
|
388
|
+
} catch {
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
await reconcile(principal);
|
|
392
|
+
}
|
|
393
|
+
await scheduleSweep();
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function hubClient(stub) {
|
|
398
|
+
const post = (action) => stub.fetch(new Request(HUB_ACTION_URL, { method: "POST", body: JSON.stringify(action) }));
|
|
399
|
+
const ok = async (response) => {
|
|
400
|
+
if (!response.ok) throw new Error(`Hub request failed: HTTP ${response.status}`);
|
|
401
|
+
};
|
|
402
|
+
return {
|
|
403
|
+
/** Forwards a reactive HTTP request and returns the hub's response unchanged. */
|
|
404
|
+
request: (body, principal) => post(
|
|
405
|
+
body.type === "subscribe" ? { action: "subscribe", principal, body } : { action: "unsubscribe", principal, body }
|
|
406
|
+
),
|
|
407
|
+
notify: async (path) => ok(await post({ action: "notify", path })),
|
|
408
|
+
publish: async (path, patches) => ok(await post({ action: "publish", path, patches }))
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
async function handleReactiveRoutes(request, options) {
|
|
412
|
+
const url = new URL(request.url);
|
|
413
|
+
const { routes, secret } = options;
|
|
414
|
+
if (![routes.ticket, routes.socket, routes.reactive].includes(url.pathname)) return void 0;
|
|
415
|
+
if (!secret) return error("Reactive hub is not configured", 503);
|
|
416
|
+
if (url.pathname === routes.ticket) {
|
|
417
|
+
if (request.method !== "POST") return error("Method not allowed", 405);
|
|
418
|
+
const principal2 = await options.authenticate(request);
|
|
419
|
+
if (!principal2) return error("Unauthorized", 401);
|
|
420
|
+
const socketUrl = new URL(routes.socket, url);
|
|
421
|
+
socketUrl.protocol = "wss:";
|
|
422
|
+
return json(
|
|
423
|
+
await createSignedClusterTicket({
|
|
424
|
+
secret,
|
|
425
|
+
principal: principal2,
|
|
426
|
+
url: socketUrl.toString(),
|
|
427
|
+
...options.ticketLifetimeSeconds === void 0 ? {} : { lifetimeSeconds: options.ticketLifetimeSeconds }
|
|
428
|
+
})
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
if (url.pathname === routes.socket) {
|
|
432
|
+
if (request.headers.get("upgrade") !== "websocket") {
|
|
433
|
+
return error("Expected a WebSocket upgrade", 426);
|
|
434
|
+
}
|
|
435
|
+
const principal2 = await verifySignedClusterTicket(url.searchParams.get("token") ?? "", secret);
|
|
436
|
+
if (!principal2) return new Response("Unauthorized", { status: 401 });
|
|
437
|
+
const forwarded = new Request(request);
|
|
438
|
+
forwarded.headers.set(HUB_PRINCIPAL_HEADER, principal2);
|
|
439
|
+
return options.hub().fetch(forwarded);
|
|
440
|
+
}
|
|
441
|
+
if (request.method !== "POST") return error("Method not allowed", 405);
|
|
442
|
+
const principal = await verifySignedClusterTicket(bearerToken(request), secret);
|
|
443
|
+
if (!principal) return error("Unauthorized", 401);
|
|
444
|
+
let body;
|
|
445
|
+
try {
|
|
446
|
+
body = await request.json();
|
|
447
|
+
} catch {
|
|
448
|
+
return error("Invalid JSON", 400);
|
|
449
|
+
}
|
|
450
|
+
if (!isHubRequest(body)) return error("Unsupported reactive request", 400);
|
|
451
|
+
return hubClient(options.hub()).request(body, principal);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export { HUB_PRINCIPAL_HEADER, createDurableObjectHub, handleReactiveRoutes, hubClient };
|
|
455
|
+
//# sourceMappingURL=cloudflare.js.map
|
|
456
|
+
//# sourceMappingURL=cloudflare.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../client/src/cluster.ts","../../client/src/hub.ts","../../client/src/cloudflare.ts"],"names":["isRecord","principal"],"mappings":";AAeA,IAAM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AA,CAAM,gBAAgB,GAAG,CAAA;AAChD,EAAA,IAAI,IAAA;AACJ,EAAA,IAAI;AACF,IAAA,IAAA,GAAO,MAAM,QAAQ,IAAA,EAAK;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA,CAAM,gBAAgB,GAAG,CAAA;AAAA,EAClC;AACA,EAAA,IAAI,CAAC,YAAA,CAAa,IAAI,GAAG,OAAO,KAAA,CAAM,gCAAgC,GAAG,CAAA;AACzE,EAAA,OAAO,UAAU,OAAA,CAAQ,GAAA,EAAK,CAAA,CAAE,OAAA,CAAQ,MAAM,SAAS,CAAA;AACzD","file":"cloudflare.js","sourcesContent":["import { ReactiveClient } from './client.js';\nimport type { ReactiveClientConfig } from './types.js';\n\n/**\n * Cluster workers run on machines with no inbound access. They authenticate\n * outbound with a long-lived runner token, exchange it for a short-lived ticket,\n * and hold a reactive WebSocket that pushes work to them. These helpers use only\n * Web standards (fetch, WebSocket, Web Crypto), so the same code runs in Node and\n * in Workers runtimes, whichever backend serves the reactive protocol.\n */\n\nexport const DEFAULT_CLUSTER_TICKET_PATH = '/api/cluster/token';\nexport const DEFAULT_CLUSTER_HTTP_PATH = '/api/reactive';\nconst DEFAULT_RETRY_DELAY_MS = 10_000;\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\nconst DEFAULT_TICKET_LIFETIME_SECONDS = 60;\n// Workers are few and long-lived, and the server needs their pings to know they are alive.\nconst DEFAULT_CLUSTER_HEARTBEAT_MS = 30_000;\n\n/** Short-lived credential returned by the ticket endpoint. */\nexport interface ClusterTicket {\n /** Sent as the WebSocket `token` query parameter and the HTTP bearer token. */\n token: string;\n /** Expiry in epoch seconds. */\n expiresAt: number;\n /** `wss:` URL of the reactive WebSocket. */\n url: string;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** Validates a ticket endpoint response; the socket URL must use `wss:`. */\nexport function parseClusterTicket(value: unknown): ClusterTicket {\n if (\n !isRecord(value) ||\n typeof value.token !== 'string' ||\n value.token.length === 0 ||\n typeof value.expiresAt !== 'number' ||\n !Number.isFinite(value.expiresAt) ||\n typeof value.url !== 'string'\n ) {\n throw new Error('Cluster ticket response is invalid');\n }\n const url = new URL(value.url);\n if (url.protocol !== 'wss:') throw new Error('Cluster ticket URL must use WSS');\n return { token: value.token, expiresAt: value.expiresAt, url: url.toString() };\n}\n\nexport interface ClusterWorkerConfig {\n /** Origin of the application that serves the ticket and reactive HTTP endpoints. */\n baseUrl: string;\n /** Long-lived runner credential exchanged for tickets. */\n runnerToken: string | (() => string | Promise<string>);\n /** Ticket endpoint path. Defaults to `/api/cluster/token`. */\n ticketPath?: string;\n /** Reactive HTTP endpoint path. Defaults to `/api/reactive`. */\n httpPath?: string;\n /** Delay between ticket, connect, and reconnect attempts. Defaults to 10 seconds. */\n retryDelay?: number;\n /** Ticket request timeout. Defaults to 10 seconds. */\n requestTimeout?: number;\n /** Stops retrying when aborted. */\n signal?: AbortSignal;\n /** Called with each failed ticket or connect attempt before the next retry. */\n onRetry?: (error: Error) => void;\n /** Extra client options; the URL, HTTP URL, and auth are managed here. */\n client?: Omit<ReactiveClientConfig, 'url' | 'httpUrl' | 'auth'>;\n /** Fetch implementation for ticket requests. Defaults to the global fetch. */\n fetch?: typeof fetch;\n}\n\nfunction toError(cause: unknown): Error {\n return cause instanceof Error ? cause : new Error(String(cause));\n}\n\nfunction abortError(signal: AbortSignal): Error {\n return toError(signal.reason ?? new Error('Cluster worker connection aborted'));\n}\n\nfunction wait(milliseconds: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortError(signal));\n return;\n }\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortError(signal!));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, milliseconds);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** Requests a ticket from the application using the runner token. */\nexport async function fetchClusterTicket(\n config: Pick<\n ClusterWorkerConfig,\n 'baseUrl' | 'runnerToken' | 'ticketPath' | 'requestTimeout' | 'fetch'\n >,\n): Promise<ClusterTicket> {\n const runnerToken =\n typeof config.runnerToken === 'function' ? await config.runnerToken() : config.runnerToken;\n const endpoint = new URL(config.ticketPath ?? DEFAULT_CLUSTER_TICKET_PATH, config.baseUrl);\n const response = await (config.fetch ?? fetch)(endpoint, {\n method: 'POST',\n headers: { authorization: `Bearer ${runnerToken}` },\n signal: AbortSignal.timeout(config.requestTimeout ?? DEFAULT_REQUEST_TIMEOUT_MS),\n });\n if (!response.ok) {\n throw new Error(`Cluster ticket request failed: HTTP ${response.status}`);\n }\n return parseClusterTicket(await response.json());\n}\n\n/**\n * Connects a cluster worker, retrying ticket and connect failures until it\n * succeeds or `signal` aborts. Each (re)connect fetches a fresh ticket. The\n * returned client keeps reconnecting on its own; subscribe to work with\n * `client.subscribe(...)` and stop with `client.disconnect()`.\n */\nexport async function connectClusterWorker(config: ClusterWorkerConfig): Promise<ReactiveClient> {\n const retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;\n const httpUrl = new URL(config.httpPath ?? DEFAULT_CLUSTER_HTTP_PATH, config.baseUrl).toString();\n for (;;) {\n if (config.signal?.aborted) throw abortError(config.signal);\n let client: ReactiveClient | undefined;\n try {\n // The first ticket only supplies the socket URL; the client fetches its own\n // ticket for every connection so reconnects never reuse an expired one.\n // oxlint-disable-next-line no-await-in-loop -- Attempts retry serially.\n const ticket = await fetchClusterTicket(config);\n client = new ReactiveClient({\n reconnectDelay: retryDelay,\n maxReconnectAttempts: Number.MAX_SAFE_INTEGER,\n heartbeatInterval: DEFAULT_CLUSTER_HEARTBEAT_MS,\n ...config.client,\n url: ticket.url,\n httpUrl,\n auth: async () => (await fetchClusterTicket(config)).token,\n });\n // oxlint-disable-next-line no-await-in-loop -- Attempts retry serially.\n await client.connect();\n return client;\n } catch (cause) {\n // connect() keeps reconnecting after it rejects; stop it before retrying.\n client?.disconnect();\n if (config.signal?.aborted) throw abortError(config.signal);\n config.onRetry?.(toError(cause));\n // oxlint-disable-next-line no-await-in-loop -- Backoff belongs to the retry loop.\n await wait(retryDelay, config.signal);\n }\n }\n}\n\nconst encoder = new TextEncoder();\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '');\n}\n\nfunction base64UrlDecode(value: string): Uint8Array<ArrayBuffer> {\n const padded = value.replaceAll('-', '+').replaceAll('_', '/');\n const binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4));\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nfunction hmacKey(secret: string, usage: 'sign' | 'verify'): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n [usage],\n );\n}\n\nexport interface SignedClusterTicketOptions {\n /** HMAC secret shared only by the servers that mint and verify tickets. */\n secret: string;\n /** Service principal the ticket authenticates as. */\n principal: string;\n /** `wss:` URL returned to the worker. */\n url: string;\n /** Ticket lifetime. Defaults to 60 seconds. */\n lifetimeSeconds?: number;\n /** Current time in milliseconds, for tests. */\n now?: number;\n}\n\n/**\n * Mints a stateless HMAC-signed ticket. Verifying it needs no storage read,\n * which keeps reconnect storms off the database.\n */\nexport async function createSignedClusterTicket(\n options: SignedClusterTicketOptions,\n): Promise<ClusterTicket> {\n const expiresAt =\n Math.floor((options.now ?? Date.now()) / 1000) +\n (options.lifetimeSeconds ?? DEFAULT_TICKET_LIFETIME_SECONDS);\n const payload = base64UrlEncode(\n encoder.encode(JSON.stringify({ p: options.principal, exp: expiresAt })),\n );\n const signature = new Uint8Array(\n await crypto.subtle.sign(\n 'HMAC',\n await hmacKey(options.secret, 'sign'),\n encoder.encode(payload),\n ),\n );\n return parseClusterTicket({\n token: `${payload}.${base64UrlEncode(signature)}`,\n expiresAt,\n url: options.url,\n });\n}\n\n/** Returns the ticket's principal, or `undefined` when it is forged, malformed, or expired. */\nexport async function verifySignedClusterTicket(\n token: string,\n secret: string,\n now = Date.now(),\n): Promise<string | undefined> {\n const parts = token.split('.');\n if (parts.length !== 2) return undefined;\n const [payload, signature] = parts as [string, string];\n if (!payload || !signature) return undefined;\n try {\n // crypto.subtle.verify compares in constant time.\n const valid = await crypto.subtle.verify(\n 'HMAC',\n await hmacKey(secret, 'verify'),\n base64UrlDecode(signature),\n encoder.encode(payload),\n );\n if (!valid) return undefined;\n const claims: unknown = JSON.parse(new TextDecoder().decode(base64UrlDecode(payload)));\n if (\n !isRecord(claims) ||\n typeof claims.p !== 'string' ||\n typeof claims.exp !== 'number' ||\n claims.exp <= Math.floor(now / 1000)\n ) {\n return undefined;\n }\n return claims.p;\n } catch {\n return undefined;\n }\n}\n","import type {\n JsonPatch,\n SnapshotResponse,\n SubscribeRequest,\n UnsubscribeRequest,\n WebSocketEvent,\n} from './protocol.js';\n\n/**\n * Protocol core for a reactive hub: the server half of the wire protocol for\n * backends that hold WebSockets themselves (for example a Cloudflare Durable\n * Object). It keeps every piece of per-socket state on the socket's attachment so\n * the state survives hibernation, and it has no runtime imports, so it runs and\n * tests in Node.\n */\n\n/** Hibernation limits a socket attachment to 2,048 bytes of serialized JSON. */\nexport const DEFAULT_MAX_ATTACHMENT_BYTES = 2_048;\n\n/** One subscription held by a socket. */\nexport interface HubSubscription {\n subscriptionId: string;\n generation: number;\n path: string;\n}\n\n/** State kept on each socket's attachment. */\nexport interface HubSocketState {\n connectionId: string;\n principal: string;\n subscriptions: HubSubscription[];\n /** Epoch ms the socket was accepted; the liveness baseline before its first ping. */\n connectedAt?: number;\n}\n\n/** The parts of a hibernatable WebSocket the hub uses; faked in tests. */\nexport interface HubSocket {\n send(message: string): void;\n deserializeAttachment(): unknown;\n serializeAttachment(value: unknown): void;\n}\n\nexport interface HubSockets {\n all(): HubSocket[];\n byConnectionId(connectionId: string): HubSocket | undefined;\n}\n\n/** Monotonic per-path versions. Versions only need to grow while sockets stay open. */\nexport interface HubVersions {\n get(path: string): Promise<number>;\n set(path: string, version: number): Promise<void>;\n}\n\nexport interface HubPathContext {\n path: string;\n principal: string;\n input: unknown;\n}\n\nexport interface HubPath {\n /**\n * Runs before the subscription is stored. Return false to reject it. Every\n * subscriber of a path receives its pushes, so authorise here, not in `snapshot`.\n */\n authorize?(context: HubPathContext): boolean | Promise<boolean>;\n /** Current data for the path, sent as the subscription snapshot. */\n snapshot(context: HubPathContext): unknown;\n}\n\n/** Fixed paths by name, or a resolver for parameterised paths such as `drafts.<id>`. */\nexport type HubPaths = Record<string, HubPath> | ((path: string) => HubPath | undefined);\n\nexport interface ReactiveHubOptions {\n sockets: HubSockets;\n versions: HubVersions;\n paths: HubPaths;\n /** Rejects subscribes that would grow an attachment past this size. */\n maxAttachmentBytes?: number;\n}\n\n/** Thrown for requests the caller is not allowed to make. */\nexport class ReactiveHubError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ReactiveHubError';\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\n/** Validates a reactive HTTP body for the subscribe and unsubscribe requests a hub serves. */\nexport function isHubRequest(value: unknown): value is SubscribeRequest | UnsubscribeRequest {\n if (!isRecord(value)) return false;\n return (\n (value.type === 'subscribe' || value.type === 'unsubscribe') &&\n typeof value.connectionId === 'string' &&\n typeof value.subscriptionId === 'string' &&\n typeof value.generation === 'number' &&\n (value.type === 'unsubscribe' || typeof value.path === 'string')\n );\n}\n\n/** Returns the bearer token from an `Authorization` header, or an empty string. */\nexport function bearerToken(request: Request): string {\n const match = /^Bearer ([^\\s]+)$/u.exec(request.headers.get('authorization') ?? '');\n return match?.[1] ?? '';\n}\n\n/** Initial attachment for a newly accepted socket. */\nexport function createHubSocketState(\n connectionId: string,\n principal: string,\n connectedAt?: number,\n): HubSocketState {\n return {\n connectionId,\n principal,\n subscriptions: [],\n ...(connectedAt === undefined ? {} : { connectedAt }),\n };\n}\n\nfunction socketState(socket: HubSocket): HubSocketState {\n const state = socket.deserializeAttachment() as HubSocketState;\n // Attachments written before subscriptions carried a path have no path; they\n // are dropped rather than fanned out to every notification.\n return { ...state, subscriptions: state.subscriptions.filter((entry) => entry.path) };\n}\n\nfunction send(socket: HubSocket, event: WebSocketEvent): void {\n try {\n socket.send(JSON.stringify(event));\n } catch {\n // A socket closing mid-broadcast is cleaned up by its close handler.\n }\n}\n\n/** Creates the protocol core for one hub instance. */\nexport function createReactiveHub(options: ReactiveHubOptions) {\n const { sockets, versions } = options;\n const maxAttachmentBytes = options.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES;\n const resolve = (path: string): HubPath | undefined =>\n typeof options.paths === 'function'\n ? options.paths(path)\n : Object.hasOwn(options.paths, path)\n ? options.paths[path]\n : undefined;\n\n const ownedSocket = (connectionId: string, principal: string): HubSocket | undefined => {\n const socket = sockets.byConnectionId(connectionId);\n // The HTTP caller must own the WebSocket it registers against.\n return socket && socketState(socket).principal === principal ? socket : undefined;\n };\n\n const subscribersOf = (path: string) =>\n sockets.all().flatMap((socket) =>\n socketState(socket)\n .subscriptions.filter((subscription) => subscription.path === path)\n .map((subscription) => ({ socket, subscription })),\n );\n\n const bump = async (path: string) => {\n const fromVersion = await versions.get(path);\n const toVersion = fromVersion + 1;\n await versions.set(path, toVersion);\n return { fromVersion, toVersion };\n };\n\n return {\n /** Answers the client's `init` and `ping` frames. */\n message(socket: HubSocket, raw: string): void {\n let frame: unknown;\n try {\n frame = JSON.parse(raw);\n } catch {\n return;\n }\n const type = isRecord(frame) ? frame.type : undefined;\n if (type === 'init') {\n send(socket, { type: 'connected', connectionId: socketState(socket).connectionId });\n } else if (type === 'ping') {\n send(socket, { type: 'pong' });\n }\n },\n\n async subscribe(request: SubscribeRequest, principal: string): Promise<SnapshotResponse> {\n const handler = resolve(request.path);\n if (!handler) throw new ReactiveHubError('Unknown subscription path');\n if (!ownedSocket(request.connectionId, principal)) {\n throw new ReactiveHubError('Unknown connection');\n }\n const context: HubPathContext = { path: request.path, principal, input: request.input };\n if (handler.authorize && !(await handler.authorize(context))) {\n throw new ReactiveHubError('Subscription not allowed');\n }\n // Re-read after the awaits so a concurrent subscribe on the same socket is kept.\n const socket = ownedSocket(request.connectionId, principal);\n if (!socket) throw new ReactiveHubError('Unknown connection');\n const state = socketState(socket);\n const next: HubSocketState = {\n ...state,\n subscriptions: [\n ...state.subscriptions.filter((entry) => entry.subscriptionId !== request.subscriptionId),\n {\n subscriptionId: request.subscriptionId,\n generation: request.generation,\n path: request.path,\n },\n ],\n };\n if (new TextEncoder().encode(JSON.stringify(next)).length > maxAttachmentBytes) {\n throw new ReactiveHubError('Too many subscriptions on this connection');\n }\n socket.serializeAttachment(next);\n // Read the version before the data so a concurrent notify can only make the\n // client re-fetch, never miss a change.\n const version = await versions.get(request.path);\n const data = await handler.snapshot(context);\n return {\n type: 'snapshot',\n subscriptionId: request.subscriptionId,\n generation: request.generation,\n version,\n data,\n };\n },\n\n unsubscribe(request: UnsubscribeRequest, principal: string): void {\n const socket = ownedSocket(request.connectionId, principal);\n if (!socket) return;\n const state = socketState(socket);\n socket.serializeAttachment({\n ...state,\n subscriptions: state.subscriptions.filter(\n (entry) => entry.subscriptionId !== request.subscriptionId,\n ),\n } satisfies HubSocketState);\n },\n\n /** Bumps the path's version and asks each of its subscribers to re-fetch. */\n async notify(path: string): Promise<void> {\n const { fromVersion, toVersion } = await bump(path);\n for (const { socket, subscription } of subscribersOf(path)) {\n send(socket, {\n type: 'resync',\n subscriptionId: subscription.subscriptionId,\n generation: subscription.generation,\n fromVersion,\n toVersion,\n messageId: crypto.randomUUID(),\n });\n }\n },\n\n /**\n * Bumps the path's version and sends the same JSON patches to each subscriber.\n * Use it only when every subscriber of the path sees the same data.\n */\n async publish(path: string, patches: JsonPatch[]): Promise<void> {\n const { fromVersion, toVersion } = await bump(path);\n for (const { socket, subscription } of subscribersOf(path)) {\n send(socket, {\n type: 'patch',\n subscriptionId: subscription.subscriptionId,\n generation: subscription.generation,\n fromVersion,\n toVersion,\n messageId: crypto.randomUUID(),\n patches,\n });\n }\n },\n };\n}\n\nexport type ReactiveHub = ReturnType<typeof createReactiveHub>;\n","import { createSignedClusterTicket, verifySignedClusterTicket } from './cluster.js';\nimport {\n bearerToken,\n createHubSocketState,\n createReactiveHub,\n type HubPaths,\n type HubSocket,\n type HubSocketState,\n isHubRequest,\n ReactiveHubError,\n} from './hub.js';\nimport type { JsonPatch, SubscribeRequest, UnsubscribeRequest } from './protocol.js';\n\n/**\n * Cloudflare Durable Object shell for the reactive hub. It is structural: it\n * takes the Durable Object's `ctx` instead of extending `DurableObject`, so this\n * entry imports nothing from `cloudflare:workers` and builds like every other\n * entry. Your Durable Object class owns its name and migrations and delegates\n * `fetch`, `webSocketMessage`, `webSocketClose` and `webSocketError` to it, plus\n * `alarm` when it tracks presence.\n */\n\n/** Set by the route handler on requests it forwards to the hub; never trusted from clients. */\nexport const HUB_PRINCIPAL_HEADER = 'x-reactive-principal';\nconst HUB_ACTION_URL = 'https://reactive-hub/';\nconst PRESENCE_TAG_PREFIX = 'presence:';\nconst PRESENCE_KEY_PREFIX = 'presence:';\nconst DEFAULT_PRESENCE_TIMEOUT_MS = 90_000;\n/** Close code for a socket the presence sweep found silent. */\nexport const HEARTBEAT_TIMEOUT_CLOSE_CODE = 4001;\n\n/** A hibernatable Workers WebSocket, as far as the hub needs it. */\nexport interface DurableObjectWebSocket extends HubSocket {\n close(code?: number, reason?: string): void;\n}\n\n/** The parts of `DurableObjectState` the hub uses. */\nexport interface DurableObjectStateLike {\n acceptWebSocket(socket: DurableObjectWebSocket, tags?: string[]): void;\n getWebSockets(tag?: string): DurableObjectWebSocket[];\n setWebSocketAutoResponse?(pair?: unknown): void;\n /** When the runtime last answered this socket's `ping` itself; needed for presence. */\n getWebSocketAutoResponseTimestamp?(socket: DurableObjectWebSocket): Date | null;\n storage: {\n get<T>(key: string): Promise<T | undefined>;\n put<T>(key: string, value: T): Promise<void>;\n /** Needed for presence. */\n getAlarm?(): Promise<number | null>;\n /** Needed for presence. */\n setAlarm?(scheduledTime: number): Promise<void>;\n };\n}\n\n/** Anything with a Durable Object stub's `fetch`. */\nexport interface HubStub {\n fetch(request: Request): Promise<Response>;\n}\n\ntype WebSocketPairConstructor = new () => {\n 0: DurableObjectWebSocket;\n 1: DurableObjectWebSocket;\n};\ntype RequestResponsePairConstructor = new (request: string, response: string) => unknown;\n\nexport interface DurableObjectHubOptions {\n paths: HubPaths;\n /** Storage key for a path's version. Defaults to `version:<path>`. */\n versionKey?: (path: string) => string;\n maxAttachmentBytes?: number;\n /**\n * Answers the client's `ping` with `pong` without waking the Durable Object.\n * Defaults to true.\n */\n autoPong?: boolean;\n /**\n * Tracks whether these principals hold a live socket, so the hub can report a\n * worker as online without the worker polling over HTTP. Requires `autoPong`.\n */\n presence?: HubPresenceOptions;\n /** Workers' `WebSocketPair`; injectable for tests. */\n WebSocketPair?: WebSocketPairConstructor;\n /** Creates a connection id; injectable for tests. */\n randomId?: () => string;\n}\n\nexport interface HubPresenceOptions {\n principals: readonly string[];\n /**\n * A socket whose last `ping` is older than this is closed as dead, which is how\n * a peer that vanished without a close frame is noticed. Clients must ping more\n * often than this. @default 90000\n */\n timeoutMs?: number;\n /**\n * Called when a principal gains its first live socket or loses its last one,\n * for example to `notify` a status path. The last reported state is kept in\n * storage under `presence:<principal>`, so each change is reported once.\n */\n onChange?: (principal: string, present: boolean) => void | Promise<void>;\n}\n\ntype HubAction =\n | { action: 'subscribe'; principal: string; body: SubscribeRequest }\n | { action: 'unsubscribe'; principal: string; body: UnsubscribeRequest }\n | { action: 'notify'; path: string }\n | { action: 'publish'; path: string; patches: JsonPatch[] };\n\nfunction json(value: unknown, status = 200): Response {\n return Response.json(value, { status, headers: { 'cache-control': 'no-store' } });\n}\n\nfunction error(message: string, status: number): Response {\n return json({ type: 'error', message }, status);\n}\n\nfunction workersGlobal<T>(name: string): T | undefined {\n return (globalThis as Record<string, unknown>)[name] as T | undefined;\n}\n\n/** Wires the hub core to a Durable Object's hibernatable WebSockets and storage. */\nexport function createDurableObjectHub(\n ctx: DurableObjectStateLike,\n options: DurableObjectHubOptions,\n) {\n const versionKey = options.versionKey ?? ((path: string) => `version:${path}`);\n const randomId = options.randomId ?? (() => crypto.randomUUID());\n const hub = createReactiveHub({\n sockets: {\n all: () => ctx.getWebSockets(),\n // Tagging by connection id lets HTTP subscribes find the socket after hibernation.\n byConnectionId: (connectionId) => ctx.getWebSockets(connectionId)[0],\n },\n versions: {\n get: async (path) => (await ctx.storage.get<number>(versionKey(path))) ?? 0,\n set: (path, version) => ctx.storage.put(versionKey(path), version),\n },\n paths: options.paths,\n ...(options.maxAttachmentBytes === undefined\n ? {}\n : { maxAttachmentBytes: options.maxAttachmentBytes }),\n });\n\n if (options.autoPong !== false) {\n const Pair = workersGlobal<RequestResponsePairConstructor>('WebSocketRequestResponsePair');\n if (Pair && ctx.setWebSocketAutoResponse) {\n ctx.setWebSocketAutoResponse(\n new Pair(JSON.stringify({ type: 'ping' }), JSON.stringify({ type: 'pong' })),\n );\n }\n }\n\n const tracked = new Set(options.presence?.principals ?? []);\n const timeoutMs = options.presence?.timeoutMs ?? DEFAULT_PRESENCE_TIMEOUT_MS;\n\n // The runtime records each auto-answered ping without waking the object;\n // before the first ping the accept time stands in.\n const lastSeen = (socket: DurableObjectWebSocket): number =>\n Math.max(\n ctx.getWebSocketAutoResponseTimestamp?.(socket)?.getTime() ?? 0,\n (socket.deserializeAttachment() as HubSocketState).connectedAt ?? 0,\n );\n\n const liveSockets = (principal: string, closing?: DurableObjectWebSocket) => {\n const now = Date.now();\n return ctx\n .getWebSockets(PRESENCE_TAG_PREFIX + principal)\n .filter((socket) => socket !== closing && now - lastSeen(socket) <= timeoutMs);\n };\n\n const reconcile = async (principal: string, closing?: DurableObjectWebSocket) => {\n const present = liveSockets(principal, closing).length > 0;\n const key = PRESENCE_KEY_PREFIX + principal;\n if (((await ctx.storage.get<boolean>(key)) ?? false) === present) return;\n await ctx.storage.put(key, present);\n await options.presence?.onChange?.(principal, present);\n };\n\n // Wakes when the stalest tracked socket would time out; no tracked sockets, no alarm.\n const scheduleSweep = async () => {\n const { storage } = ctx;\n if (!storage.getAlarm || !storage.setAlarm) {\n throw new Error('Hub presence needs Durable Object alarms');\n }\n const seen = [...tracked].flatMap((principal) =>\n ctx.getWebSockets(PRESENCE_TAG_PREFIX + principal).map((socket) => lastSeen(socket)),\n );\n if (seen.length === 0) return;\n const due = Math.min(...seen) + timeoutMs + 1;\n const current = await storage.getAlarm();\n if (current === null || current > due) await storage.setAlarm(due);\n };\n\n const closed = async (socket: DurableObjectWebSocket) => {\n if (tracked.size === 0) return;\n const { principal } = socket.deserializeAttachment() as HubSocketState;\n if (tracked.has(principal)) await reconcile(principal, socket);\n };\n\n const accept = async (request: Request): Promise<Response> => {\n const principal = request.headers.get(HUB_PRINCIPAL_HEADER);\n if (!principal) return error('Unauthorized', 401);\n const Pair = options.WebSocketPair ?? workersGlobal<WebSocketPairConstructor>('WebSocketPair');\n if (!Pair) throw new Error('WebSocketPair is not available in this runtime');\n const pair = new Pair();\n const connectionId = randomId();\n const isTracked = tracked.has(principal);\n ctx.acceptWebSocket(\n pair[1],\n isTracked ? [connectionId, PRESENCE_TAG_PREFIX + principal] : [connectionId],\n );\n pair[1].serializeAttachment(\n createHubSocketState(connectionId, principal, isTracked ? Date.now() : undefined),\n );\n if (isTracked) {\n await reconcile(principal);\n await scheduleSweep();\n }\n return new Response(null, { status: 101, webSocket: pair[0] } as ResponseInit);\n };\n\n const act = async (action: HubAction): Promise<Response> => {\n try {\n switch (action.action) {\n case 'subscribe':\n return json(await hub.subscribe(action.body, action.principal));\n case 'unsubscribe':\n hub.unsubscribe(action.body, action.principal);\n return json({ type: 'ok' });\n case 'notify':\n await hub.notify(action.path);\n return json({ type: 'ok' });\n case 'publish':\n await hub.publish(action.path, action.patches);\n return json({ type: 'ok' });\n default:\n return error('Unknown hub action', 400);\n }\n } catch (cause) {\n if (cause instanceof ReactiveHubError) return error(cause.message, 400);\n throw cause;\n }\n };\n\n return {\n hub,\n\n /** The Durable Object's `fetch`: WebSocket upgrades and actions from `hubClient`. */\n async fetch(request: Request): Promise<Response> {\n if (request.headers.get('upgrade') === 'websocket') return accept(request);\n return act((await request.json()) as HubAction);\n },\n\n webSocketMessage(socket: DurableObjectWebSocket, message: string | ArrayBuffer): void {\n if (typeof message === 'string') hub.message(socket, message);\n },\n\n async webSocketClose(socket: DurableObjectWebSocket, code: number): Promise<void> {\n try {\n socket.close(code === 1005 ? 1000 : code, 'closed');\n } catch {\n // Already closed, or the runtime replied to the close frame itself.\n }\n await closed(socket);\n },\n\n async webSocketError(socket: DurableObjectWebSocket): Promise<void> {\n try {\n socket.close(1011, 'error');\n } catch {\n // Already closed.\n }\n await closed(socket);\n },\n\n /** Whether `principal` holds a socket that has pinged within the presence timeout. */\n present(principal: string): boolean {\n return liveSockets(principal).length > 0;\n },\n\n /**\n * The Durable Object's `alarm` when presence is tracked: closes silent\n * sockets, reports principals that lost their last one, and reschedules.\n */\n async alarm(): Promise<void> {\n const now = Date.now();\n for (const principal of tracked) {\n for (const socket of ctx.getWebSockets(PRESENCE_TAG_PREFIX + principal)) {\n if (now - lastSeen(socket) <= timeoutMs) continue;\n try {\n socket.close(HEARTBEAT_TIMEOUT_CLOSE_CODE, 'Heartbeat timeout');\n } catch {\n // Already closed.\n }\n }\n // oxlint-disable-next-line no-await-in-loop -- Few principals; storage writes stay ordered.\n await reconcile(principal);\n }\n await scheduleSweep();\n },\n };\n}\n\nexport type DurableObjectHub = ReturnType<typeof createDurableObjectHub>;\n\n/** Calls a hub Durable Object from the Worker. */\nexport function hubClient(stub: HubStub) {\n const post = (action: HubAction) =>\n stub.fetch(new Request(HUB_ACTION_URL, { method: 'POST', body: JSON.stringify(action) }));\n const ok = async (response: Response) => {\n if (!response.ok) throw new Error(`Hub request failed: HTTP ${response.status}`);\n };\n return {\n /** Forwards a reactive HTTP request and returns the hub's response unchanged. */\n request: (body: SubscribeRequest | UnsubscribeRequest, principal: string) =>\n post(\n body.type === 'subscribe'\n ? { action: 'subscribe', principal, body }\n : { action: 'unsubscribe', principal, body },\n ),\n notify: async (path: string) => ok(await post({ action: 'notify', path })),\n publish: async (path: string, patches: JsonPatch[]) =>\n ok(await post({ action: 'publish', path, patches })),\n };\n}\n\nexport interface ReactiveRoutes {\n /** `POST` exchanges a credential for a signed ticket. */\n ticket: string;\n /** WebSocket upgrade, authenticated by the ticket in the `token` query parameter. */\n socket: string;\n /** Reactive HTTP subscribe and unsubscribe, authenticated by the ticket as a bearer token. */\n reactive: string;\n}\n\nexport interface ReactiveRoutesOptions {\n routes: ReactiveRoutes;\n /** Ticket signing secret. Requests get 503 when it is not configured. */\n secret: string | undefined;\n /** The hub Durable Object stub that serves these routes. */\n hub: () => HubStub;\n /** Returns the principal for a ticket request, or undefined to answer 401. */\n authenticate(request: Request): string | undefined | Promise<string | undefined>;\n ticketLifetimeSeconds?: number;\n}\n\n/** Serves the ticket, socket and reactive HTTP routes; `undefined` for any other path. */\nexport async function handleReactiveRoutes(\n request: Request,\n options: ReactiveRoutesOptions,\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const { routes, secret } = options;\n if (![routes.ticket, routes.socket, routes.reactive].includes(url.pathname)) return undefined;\n if (!secret) return error('Reactive hub is not configured', 503);\n\n if (url.pathname === routes.ticket) {\n if (request.method !== 'POST') return error('Method not allowed', 405);\n const principal = await options.authenticate(request);\n if (!principal) return error('Unauthorized', 401);\n const socketUrl = new URL(routes.socket, url);\n socketUrl.protocol = 'wss:';\n return json(\n await createSignedClusterTicket({\n secret,\n principal,\n url: socketUrl.toString(),\n ...(options.ticketLifetimeSeconds === undefined\n ? {}\n : { lifetimeSeconds: options.ticketLifetimeSeconds }),\n }),\n );\n }\n\n if (url.pathname === routes.socket) {\n if (request.headers.get('upgrade') !== 'websocket') {\n return error('Expected a WebSocket upgrade', 426);\n }\n const principal = await verifySignedClusterTicket(url.searchParams.get('token') ?? '', secret);\n if (!principal) return new Response('Unauthorized', { status: 401 });\n const forwarded = new Request(request);\n forwarded.headers.set(HUB_PRINCIPAL_HEADER, principal);\n return options.hub().fetch(forwarded);\n }\n\n if (request.method !== 'POST') return error('Method not allowed', 405);\n const principal = await verifySignedClusterTicket(bearerToken(request), secret);\n if (!principal) return error('Unauthorized', 401);\n let body: unknown;\n try {\n body = await request.json();\n } catch {\n return error('Invalid JSON', 400);\n }\n if (!isHubRequest(body)) return error('Unsupported reactive request', 400);\n return hubClient(options.hub()).request(body, principal);\n}\n"]}
|