freertc 0.1.32 → 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 +204 -12
- package/bin/freertc.mjs +38 -633
- package/migrations/0001_initial.sql +43 -0
- package/migrations/0002_kademlia_overlay.sql +32 -0
- package/migrations/0003_announcement_role.sql +4 -0
- package/package.json +44 -17
- package/public/app.js +746 -169
- package/public/icon-180.png +0 -0
- package/public/icon-192.png +0 -0
- package/public/index.html +200 -799
- package/public/pigeonlogo.svg +51 -0
- package/scripts/d1-schema.sql +36 -0
- package/scripts/deploy-cloudflare.mjs +190 -0
- package/scripts/dev-server.mjs +54 -7
- package/scripts/generate-relay-identity.mjs +14 -0
- package/scripts/name-setup.mjs +332 -0
- package/scripts/node-relay.mjs +1128 -0
- package/scripts/project-bootstrap.mjs +13 -6
- package/scripts/wrangler-install-wizard.mjs +21 -11
- package/src/client.js +3468 -0
- package/src/direct/cert.js +95 -0
- package/src/direct/common.js +187 -0
- package/src/direct/dial.js +47 -0
- package/src/direct/directory.js +230 -0
- package/src/direct/listener.js +201 -0
- package/src/direct/lookup.js +75 -0
- package/src/direct/names.js +150 -0
- package/src/direct/node-relay-direct.js +170 -0
- package/src/direct/portmap.js +214 -0
- package/src/direct/reachable.js +40 -0
- package/src/direct/record.js +188 -0
- package/src/index.js +1401 -199
- package/src/kademlia.js +133 -0
- package/src/node/account-sync.js +98 -0
- package/src/node/cost-meter.js +92 -0
- package/src/node/d1-sqlite.js +108 -0
- package/src/node/data-dir.js +66 -0
- package/src/node/durable-object.js +58 -0
- package/src/node/lan-beacon.js +55 -0
- package/src/node/link-crypto.js +99 -0
- package/src/node/relay-links.js +385 -0
- package/src/node/relay-name.js +193 -0
- package/src/node/relay-pq.js +68 -0
- package/src/node/relay-stats.js +276 -0
- package/src/node/stats-page.js +281 -0
- package/src/node/websocket-pair.js +117 -0
- package/src/punch/offer.js +143 -0
- package/src/punch/rendezvous.js +124 -0
- package/src/punch/transport.js +257 -0
- package/src/relay-fetch.js +131 -0
- package/src/relay-id.js +74 -0
- package/src/relay-identity.js +298 -0
- package/src/relay-overlay.js +857 -0
- package/src/tunnel/client.js +276 -0
- package/src/tunnel/frames.js +64 -0
- package/src/tunnel/home.js +271 -0
- package/wrangler.template.jsonc +34 -9
- package/wrangler.workers-dev.jsonc +20 -3
- package/scripts/non-cloudflare-server.mjs +0 -433
- package/scripts/postinstall-message.mjs +0 -133
package/src/index.js
CHANGED
|
@@ -1,5 +1,42 @@
|
|
|
1
|
+
import { lookupDirectRelays } from "./direct/lookup.js";
|
|
2
|
+
import { relayFetch } from "./relay-fetch.js";
|
|
3
|
+
import {
|
|
4
|
+
configuredBootstrapUrls,
|
|
5
|
+
handleKademliaRequest,
|
|
6
|
+
heartbeatKademlia,
|
|
7
|
+
isKademliaEnabled,
|
|
8
|
+
listBootstrapUrls,
|
|
9
|
+
listKnownRelays,
|
|
10
|
+
lookupRoomProviders,
|
|
11
|
+
lookupScopeProviders,
|
|
12
|
+
publishPeerProviderRecords,
|
|
13
|
+
refreshRoomProviders,
|
|
14
|
+
relayKindOf,
|
|
15
|
+
relayNodeIdOf,
|
|
16
|
+
} from "./relay-overlay.js";
|
|
17
|
+
import { relayPeerIdFor } from "./relay-id.js";
|
|
18
|
+
import { tunnelRoute } from "./tunnel/frames.js";
|
|
19
|
+
import { DIRECTORY_PATH, directoryEnabled, handleDirectoryRequest } from "./direct/directory.js";
|
|
20
|
+
import { NAMES_PATH, handleNameRequest } from "./direct/names.js";
|
|
21
|
+
import { REACHABLE_PATH, handleReachableRequest } from "./direct/reachable.js";
|
|
22
|
+
|
|
23
|
+
// Per-message log lines (one for every offer, answer and ICE candidate a relay
|
|
24
|
+
// passes on) only with FREERTC_VERBOSE; otherwise they are counted, and a
|
|
25
|
+
// Node relay prints the counts once a minute (relayLogCounts).
|
|
26
|
+
export const relayLogCounts = new Map();
|
|
27
|
+
let relayVerbose = false;
|
|
28
|
+
function relayLog(what, line) {
|
|
29
|
+
if (relayVerbose) {
|
|
30
|
+
console.log(line);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
relayLogCounts.set(what, (relayLogCounts.get(what) ?? 0) + 1);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export { RelayTunnel } from "./tunnel/home.js";
|
|
37
|
+
|
|
1
38
|
const PSP_VERSION = "1.0";
|
|
2
|
-
const WORKER_VERSION = "0.
|
|
39
|
+
const WORKER_VERSION = "0.5.0";
|
|
3
40
|
|
|
4
41
|
const DISCOVERY_TYPES = new Set(["announce", "withdraw", "discover", "peer_list", "redirect"]);
|
|
5
42
|
const NEGOTIATION_TYPES = new Set(["connect_request", "connect_accept", "connect_reject", "offer", "answer", "ice_candidate", "ice_end", "renegotiate"]);
|
|
@@ -17,46 +54,596 @@ const RELAY_TYPES = new Set([
|
|
|
17
54
|
]);
|
|
18
55
|
|
|
19
56
|
const DEFAULT_TTL_MS = 30_000;
|
|
57
|
+
const FEDERATED_PEER_QUERY_TIMEOUT_MS = 2_500;
|
|
58
|
+
// A discover is answered within this bound no matter what federation does;
|
|
59
|
+
// the local peers are sent alone if the federated lookup is still running.
|
|
60
|
+
const DISCOVER_REPLY_DEADLINE_MS = 4_000;
|
|
20
61
|
const MAX_TTL_MS = 120_000;
|
|
21
62
|
const MAX_MESSAGE_SIZE = 64 * 1024;
|
|
22
63
|
const MAX_BATCH = 50;
|
|
23
64
|
const RELAY_EXPIRY_MS = 5 * 60_000; // relay entry expires after 5 min without heartbeat
|
|
24
|
-
const FEDERATION_INTERVAL_MS = 2 * 60_000; // re-heartbeat every 2 min per
|
|
25
|
-
|
|
65
|
+
const FEDERATION_INTERVAL_MS = 2 * 60_000; // re-heartbeat every 2 min per relay (claimFederationHeartbeat)
|
|
66
|
+
// An isolate checks once per interval; this much early still claims, so a
|
|
67
|
+
// relay whose isolates all check a moment early still heartbeats each interval.
|
|
68
|
+
const FEDERATION_CLAIM_SLACK_MS = 5_000;
|
|
69
|
+
// Relays asked to deliver a message when none is known to hold its peer. They are the relays
|
|
70
|
+
// that serve the room, and each one that does not hold the peer says so, so asking all of
|
|
71
|
+
// them (up to the most a lookup returns) costs requests, not queued copies.
|
|
72
|
+
const KADEMLIA_FORWARD_LIMIT = 8;
|
|
73
|
+
const FEDERATED_FORWARD_DEADLINE_MS = 15_000;
|
|
74
|
+
const PEER_RELAY_HINT_TTL_MS = 60_000;
|
|
75
|
+
|
|
76
|
+
const livePeers = new Map(); // key: JSON [network, room, peerId]
|
|
77
|
+
const networkSubscribers = new Map(); // key: JSON [network, room] -> Set of sockets
|
|
78
|
+
const peerRelayHints = new Map(); // key: JSON [network, room, peerId] -> { url, expiresAt }
|
|
79
|
+
// Diagnostic trail of federation work done on behalf of live sockets. Read
|
|
80
|
+
// through GET /debug/state on the coordinator. Bounded; newest last.
|
|
81
|
+
const debugTrail = [];
|
|
82
|
+
const DEBUG_TRAIL_LIMIT = 300;
|
|
83
|
+
function debugNote(entry) {
|
|
84
|
+
debugTrail.push({ t: Date.now(), ...entry });
|
|
85
|
+
while (debugTrail.length > DEBUG_TRAIL_LIMIT) debugTrail.shift();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ===================== Deferred work =====================
|
|
89
|
+
//
|
|
90
|
+
// Nothing that leaves the runtime — a D1 query, a fetch to another relay, a
|
|
91
|
+
// Kademlia walk — may run on a WebSocket's own request context. The platform
|
|
92
|
+
// charges every such subrequest to the request that opened the socket, and a
|
|
93
|
+
// socket that lives for hours pays for all of them at once: after a handful of
|
|
94
|
+
// federated forwards each further call fails with "Subrequest depth limit
|
|
95
|
+
// exceeded", silently, and the peer looks reachable while nothing it sends
|
|
96
|
+
// gets out. So the socket handler only touches memory, and hands the rest to
|
|
97
|
+
// the coordinator's alarm, which runs each batch on a fresh context.
|
|
98
|
+
const DEFERRED_TASK_PREFIX = "task:";
|
|
99
|
+
const MAX_DEFERRED_TASKS_PER_ALARM = 16;
|
|
100
|
+
// How many queued entries one alarm inspects when deciding what is still
|
|
101
|
+
// worth running. Stale entries are dropped in bulk; only live ones run.
|
|
102
|
+
const DEFERRED_TASK_SCAN_LIMIT = 256;
|
|
103
|
+
// A queue drain or a heartbeat older than this is worthless: the peer has
|
|
104
|
+
// announced again since, or is gone. Running it anyway is what kept a relay
|
|
105
|
+
// with a deep backlog answering nothing for as long as the backlog lasted.
|
|
106
|
+
const DEFERRED_TASK_STALE_MS = 60_000;
|
|
107
|
+
// A negotiation frame waits ten seconds on the wire and its sender retries
|
|
108
|
+
// for sixteen; a forward that has sat in the queue longer than that would
|
|
109
|
+
// only deliver an offer the other side has already given up on.
|
|
110
|
+
const DEFERRED_FORWARD_STALE_MS = 20_000;
|
|
111
|
+
// A negotiation forward is the most time-critical thing in the queue: the
|
|
112
|
+
// offer behind it dies in ten seconds. Discovers and announces come next;
|
|
113
|
+
// a peer re-requests discovery before every dial, and letting those crowd
|
|
114
|
+
// out forwards left every cross-relay offer to expire unrun.
|
|
115
|
+
const DEFERRED_TASK_PRIORITY = { forward: 0, discover: 1, announce: 1, "peer-left": 1, "relay-list": 2, "deliver-queued": 3 };
|
|
116
|
+
const CLEANUP_INTERVAL_MS = 60_000;
|
|
117
|
+
const ALARM_REARM_SLACK_MS = 1_000;
|
|
118
|
+
// A due alarm normally runs within moments; one this far past due will not run by itself.
|
|
119
|
+
const ALARM_STUCK_AFTER_MS = 30_000;
|
|
120
|
+
// One queued task may not hold the queue: a lookup or a forward that never
|
|
121
|
+
// settles would otherwise keep every later announce and discover waiting.
|
|
122
|
+
const DEFERRED_TASK_TIMEOUT_MS = 25_000;
|
|
123
|
+
let deferredTaskSequence = 0;
|
|
124
|
+
let lastCleanupAt = 0;
|
|
125
|
+
|
|
126
|
+
function canDefer(ctx) {
|
|
127
|
+
return Boolean(ctx?.storage?.put && ctx?.storage?.setAlarm && ctx?.storage?.getAlarm);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Whether a ping has to drain the D1 relay queue for its sender. Under the
|
|
131
|
+
// coordinator every live socket is in this one object, so a frame for a
|
|
132
|
+
// live peer is delivered on arrival and only a frame for an absent peer is
|
|
133
|
+
// ever queued; that peer drains the queue when it announces again. Queuing
|
|
134
|
+
// a drain task on every ping from every peer fed the alarm queue faster
|
|
135
|
+
// than an alarm could empty it, and the discover replies waiting in the
|
|
136
|
+
// same queue starved: the busiest relays answered pings in a quarter of a
|
|
137
|
+
// second and discovers never. Without the coordinator, sockets can live in
|
|
138
|
+
// different isolates and the ping drain remains the delivery path.
|
|
139
|
+
export function pingDrainsQueuedMessages(ctx) {
|
|
140
|
+
return !canDefer(ctx);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function deferWork(ctx, env, task) {
|
|
144
|
+
if (!canDefer(ctx)) {
|
|
145
|
+
// No coordinator (legacy single-isolate mode): run it here as before.
|
|
146
|
+
const work = runDeferredTask(env, task).catch((error) => {
|
|
147
|
+
console.error(`[TASK] ${task.kind} failed: ${error?.message}`);
|
|
148
|
+
});
|
|
149
|
+
if (ctx?.waitUntil) ctx.waitUntil(work);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
deferredTaskSequence = (deferredTaskSequence + 1) % 1_000_000;
|
|
153
|
+
const key = deferredTaskKey(task, Date.now(), deferredTaskSequence);
|
|
154
|
+
await ctx.storage.put(key, task);
|
|
155
|
+
// Re-arm an alarm that is not due now, not only a missing one. An alarm
|
|
156
|
+
// that kept failing (as every one did while the account was over its daily
|
|
157
|
+
// Durable Object limit) sits in the platform's retry backoff, and a queue
|
|
158
|
+
// that waited for it answered no announce or discover at all.
|
|
159
|
+
// An alarm long overdue is stuck the same way: ooo's was 17 days past due
|
|
160
|
+
// with over a thousand tasks waiting behind it.
|
|
161
|
+
const alarm = await ctx.storage.getAlarm();
|
|
162
|
+
const now = Date.now();
|
|
163
|
+
if (alarm === null || alarm > now + ALARM_REARM_SLACK_MS || alarm < now - ALARM_STUCK_AFTER_MS) {
|
|
164
|
+
await ctx.storage.setAlarm(now);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// The queue key carries the enqueue time, so an alarm can tell a task's
|
|
169
|
+
// age without reading the task. A drain for a peer's queued frames and a
|
|
170
|
+
// heartbeat republish are only useful while fresh; a discover, a join, a
|
|
171
|
+
// leave, or a forward is always run because something is waiting on it.
|
|
172
|
+
// Storage lists keys in order, so the key decides what an alarm sees first.
|
|
173
|
+
// The priority digit comes before the enqueue time, and the "!" that leads
|
|
174
|
+
// it sorts before any digit, so every key written by this build sorts ahead
|
|
175
|
+
// of the timestamp-only keys an earlier build left behind. A discover is
|
|
176
|
+
// therefore always in the first window no matter how deep the backlog is.
|
|
177
|
+
const DEFERRED_TASK_PRIORITY_MARK = "!";
|
|
178
|
+
|
|
179
|
+
export function deferredTaskKey(task, now = Date.now(), sequence = 0) {
|
|
180
|
+
const priority = DEFERRED_TASK_PRIORITY[task?.kind] ?? 5;
|
|
181
|
+
return `${DEFERRED_TASK_PREFIX}${DEFERRED_TASK_PRIORITY_MARK}${priority}:${String(now).padStart(15, "0")}:${String(sequence).padStart(6, "0")}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function deferredTaskEnqueuedAt(key) {
|
|
185
|
+
const text = String(key ?? "");
|
|
186
|
+
if (!text.startsWith(DEFERRED_TASK_PREFIX)) return null;
|
|
187
|
+
let rest = text.slice(DEFERRED_TASK_PREFIX.length);
|
|
188
|
+
if (rest.startsWith(DEFERRED_TASK_PRIORITY_MARK)) rest = rest.slice(rest.indexOf(":") + 1);
|
|
189
|
+
const enqueuedAt = Number(rest.slice(0, 15));
|
|
190
|
+
return Number.isFinite(enqueuedAt) && enqueuedAt > 0 ? enqueuedAt : null;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function deferredTaskIsStale(key, task, now = Date.now()) {
|
|
194
|
+
const kind = task?.kind;
|
|
195
|
+
let budget;
|
|
196
|
+
if (kind === "deliver-queued" || (kind === "announce" && task?.isHeartbeat)) budget = DEFERRED_TASK_STALE_MS;
|
|
197
|
+
else if (kind === "forward" && NEGOTIATION_TYPES.has(task?.message?.type)) budget = DEFERRED_FORWARD_STALE_MS;
|
|
198
|
+
else return false;
|
|
199
|
+
const enqueuedAt = deferredTaskEnqueuedAt(key);
|
|
200
|
+
if (enqueuedAt === null) return false;
|
|
201
|
+
return now - enqueuedAt > budget;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function orderDeferredTasks(entries) {
|
|
205
|
+
const rank = (task) => DEFERRED_TASK_PRIORITY[task?.kind] ?? 5;
|
|
206
|
+
return [...entries].sort((left, right) => rank(left[1]) - rank(right[1]));
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Several discovers, heartbeats, or queue drains for the same peer answer
|
|
210
|
+
// the same question; only the newest is worth running. Returns the entries
|
|
211
|
+
// to run and the keys made redundant by a newer duplicate.
|
|
212
|
+
export function coalesceDeferredTasks(entries) {
|
|
213
|
+
const newestByPeer = new Map();
|
|
214
|
+
const redundant = [];
|
|
215
|
+
const keep = [];
|
|
216
|
+
for (const entry of entries) {
|
|
217
|
+
const [key, task] = entry;
|
|
218
|
+
const kind = task?.kind;
|
|
219
|
+
const coalescable = kind === "discover" || kind === "deliver-queued" || (kind === "announce" && task?.isHeartbeat);
|
|
220
|
+
if (!coalescable) { keep.push(entry); continue; }
|
|
221
|
+
const id = `${kind}:${task.network}:${task.room}:${task.peerId}`;
|
|
222
|
+
const previous = newestByPeer.get(id);
|
|
223
|
+
if (previous) redundant.push(previous[0]);
|
|
224
|
+
newestByPeer.set(id, entry);
|
|
225
|
+
}
|
|
226
|
+
for (const entry of newestByPeer.values()) keep.push(entry);
|
|
227
|
+
return { run: keep, redundant };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function drainDeferredTasks(state, env) {
|
|
231
|
+
const scanned = await state.storage.list({ prefix: DEFERRED_TASK_PREFIX, limit: DEFERRED_TASK_SCAN_LIMIT });
|
|
232
|
+
if (scanned.size === 0) return;
|
|
233
|
+
const now = Date.now();
|
|
234
|
+
const staleKeys = [];
|
|
235
|
+
const live = [];
|
|
236
|
+
for (const [key, task] of scanned) {
|
|
237
|
+
if (deferredTaskIsStale(key, task, now)) staleKeys.push(key);
|
|
238
|
+
else live.push([key, task]);
|
|
239
|
+
}
|
|
240
|
+
const coalesced = coalesceDeferredTasks(live);
|
|
241
|
+
staleKeys.push(...coalesced.redundant);
|
|
242
|
+
// Durable Object storage deletes at most 128 keys per call.
|
|
243
|
+
for (let index = 0; index < staleKeys.length; index += 128) {
|
|
244
|
+
await state.storage.delete(staleKeys.slice(index, index + 128));
|
|
245
|
+
}
|
|
246
|
+
if (staleKeys.length > 0) debugNote({ op: "task-stale-dropped", count: staleKeys.length });
|
|
247
|
+
const entries = orderDeferredTasks(coalesced.run).slice(0, MAX_DEFERRED_TASKS_PER_ALARM);
|
|
248
|
+
await Promise.all(entries.map(async ([key, task]) => {
|
|
249
|
+
const startedAt = Date.now();
|
|
250
|
+
try {
|
|
251
|
+
await Promise.race([
|
|
252
|
+
runDeferredTask(env, task),
|
|
253
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(`timed out after ${DEFERRED_TASK_TIMEOUT_MS} ms`)), DEFERRED_TASK_TIMEOUT_MS)),
|
|
254
|
+
]);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
debugNote({ op: "task-error", kind: task?.kind, error: String(error?.message || error).slice(0, 300), ms: Date.now() - startedAt });
|
|
257
|
+
console.error(`[TASK] ${task?.kind} failed: ${error?.message}`);
|
|
258
|
+
}
|
|
259
|
+
await state.storage.delete(key);
|
|
260
|
+
}));
|
|
261
|
+
const remaining = await state.storage.list({ prefix: DEFERRED_TASK_PREFIX, limit: 1 });
|
|
262
|
+
if (remaining.size > 0) await state.storage.setAlarm(Date.now());
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function runDeferredTask(env, task) {
|
|
266
|
+
const db = env.DB;
|
|
267
|
+
const { kind, network, room, peerId, selfRelayUrl } = task;
|
|
268
|
+
await primeRelayNodeId(env, selfRelayUrl);
|
|
269
|
+
const relayPeerId = resolveRelayPeerId(selfRelayUrl);
|
|
270
|
+
const liveSocket = () => livePeers.get(peerScopeKey(network, room, peerId))?.socket ?? null;
|
|
271
|
+
|
|
272
|
+
if (kind === "announce") {
|
|
273
|
+
let federatedPeers = null;
|
|
274
|
+
if (db) {
|
|
275
|
+
await upsertAnnouncement(db, task.message);
|
|
276
|
+
const socket = liveSocket();
|
|
277
|
+
if (socket) await deliverQueuedRelayMessages(db, socket, network, room, peerId);
|
|
278
|
+
}
|
|
279
|
+
if (selfRelayUrl && isKademliaEnabled(env)) {
|
|
280
|
+
if (task.isHeartbeat) {
|
|
281
|
+
await publishPeerProviderRecords(env, selfRelayUrl, network, room, peerId, { connections: livePeers.size });
|
|
282
|
+
} else {
|
|
283
|
+
// Query the established overlay immediately while publishing this
|
|
284
|
+
// peer's provider records in parallel. Discovery must not sit behind
|
|
285
|
+
// the publication round trip for a peer that is already isolated.
|
|
286
|
+
federatedPeers = await discoverJoiningPeer({
|
|
287
|
+
discover: (scopeProviders) => findFederatedPeers(env, selfRelayUrl, network, room, peerId, livePeers.size, scopeProviders),
|
|
288
|
+
publish: () => publishPeerProviderRecords(env, selfRelayUrl, network, room, peerId, { connections: livePeers.size, returnScopeProviders: true }),
|
|
289
|
+
send: (peers) => {
|
|
290
|
+
const socket = liveSocket();
|
|
291
|
+
if (!socket) return;
|
|
292
|
+
try { sendPeerList(socket, network, room, peers, peerId, relayPeerId); } catch {}
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// Only broadcast peer_list when the peer is newly joining, not on a
|
|
298
|
+
// heartbeat re-announce: no topology change occurred.
|
|
299
|
+
if (!task.isHeartbeat && db) {
|
|
300
|
+
relayLog('peer lists sent', `[NET] Broadcasting peer_list for network=${network} room=${room} after new announce from ${peerId}`);
|
|
301
|
+
await broadcastPeerList(env, selfRelayUrl, network, room, relayPeerId, { federatedPeers })
|
|
302
|
+
.catch((err) => console.error(`[Broadcast error]`, err?.message));
|
|
303
|
+
}
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (kind === "discover") {
|
|
308
|
+
// Never leave a discover unanswered. The reply is bounded: federated
|
|
309
|
+
// peers when they arrive in time, the local ones alone otherwise.
|
|
310
|
+
let answered = false;
|
|
311
|
+
const reply = (peers) => {
|
|
312
|
+
if (answered) return;
|
|
313
|
+
answered = true;
|
|
314
|
+
const socket = liveSocket();
|
|
315
|
+
if (!socket) return;
|
|
316
|
+
try { sendPeerList(socket, network, room, peers, peerId, relayPeerId); } catch {}
|
|
317
|
+
};
|
|
318
|
+
const localOnly = async () => {
|
|
319
|
+
try { return db ? await findPeers(db, network, room, peerId) : []; } catch { return []; }
|
|
320
|
+
};
|
|
321
|
+
const deadline = setTimeout(() => { localOnly().then(reply); }, DISCOVER_REPLY_DEADLINE_MS);
|
|
322
|
+
try {
|
|
323
|
+
const peers = await findFederatedPeers(env, selfRelayUrl, network, room, peerId, livePeers.size);
|
|
324
|
+
clearTimeout(deadline);
|
|
325
|
+
reply(peers);
|
|
326
|
+
} catch {
|
|
327
|
+
clearTimeout(deadline);
|
|
328
|
+
reply(await localOnly());
|
|
329
|
+
}
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (kind === "peer-left") {
|
|
334
|
+
if (!db) return;
|
|
335
|
+
await deleteAnnouncement(db, network, room, peerId);
|
|
336
|
+
await broadcastPeerList(env, selfRelayUrl, network, room, relayPeerId).catch(() => {});
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (kind === "deliver-queued") {
|
|
341
|
+
const socket = liveSocket();
|
|
342
|
+
if (db && socket) await deliverQueuedRelayMessages(db, socket, network, room, peerId);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (kind === "relay-list") {
|
|
347
|
+
if (!db) return;
|
|
348
|
+
await Promise.all((task.relays || [])
|
|
349
|
+
.filter((r) => r?.url)
|
|
350
|
+
.map((r) => upsertRelay(db, r.url, r.name || null).catch(() => {})));
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (kind === "forward") {
|
|
355
|
+
const message = task.message;
|
|
356
|
+
const type = message.type;
|
|
357
|
+
// The peer may have arrived here since the socket handler looked.
|
|
358
|
+
const live = livePeers.get(peerScopeKey(network, room, message.to));
|
|
359
|
+
if (live) {
|
|
360
|
+
try {
|
|
361
|
+
live.socket.send(JSON.stringify(message));
|
|
362
|
+
debugNote({ op: "forward", type, from: peerId.slice(0, 8), to: message.to.slice(0, 8), hint: "local", delivered: true, ms: 0 });
|
|
363
|
+
return;
|
|
364
|
+
} catch {}
|
|
365
|
+
}
|
|
366
|
+
if (!db) {
|
|
367
|
+
console.warn(`[RELAY] Could not deliver ${type} to ${message.to}; persistence unavailable`);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (!selfRelayUrl) {
|
|
371
|
+
await insertRelayMessage(db, message);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
// A peer that said goodbye here: drop what is still sent to it, and tell
|
|
375
|
+
// the sender once so it stops. Without this every offer and ICE candidate
|
|
376
|
+
// for a peer that had left went to every relay serving the room, twice,
|
|
377
|
+
// and was then stored for a peer that would never collect it.
|
|
378
|
+
const goneKey = peerScopeKey(network, room, message.to);
|
|
379
|
+
if ((relayIdlePeerUntilMs.get(goneKey) ?? 0) > Date.now()) {
|
|
380
|
+
await insertRelayMessage(db, message);
|
|
381
|
+
relayLog('messages held for peers resting off the relay', `[RELAY] ${message.to} is off the relay (mesh healthy): holding ${type}`);
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
const goneUntil = absentPeerUntilMs.get(goneKey) ?? 0;
|
|
385
|
+
if (goneUntil > Date.now()) {
|
|
386
|
+
relayLog('messages for peers no relay has, dropped', `[RELAY] ${message.type} for ${message.to} dropped: no relay has that peer`);
|
|
387
|
+
tellSenderPeerGone(peerId, network, room, message, relayPeerId);
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
const startedAt = Date.now();
|
|
391
|
+
const hint = getPeerRelayHint(network, room, message.to);
|
|
392
|
+
try {
|
|
393
|
+
// Bounded: a forward that cannot finish inside the deadline is queued
|
|
394
|
+
// like an unreachable peer instead of silently vanishing.
|
|
395
|
+
const deliveredRemote = await Promise.race([
|
|
396
|
+
forwardFederatedMessage(env, selfRelayUrl, network, room, message, livePeers.size),
|
|
397
|
+
new Promise((resolve) => setTimeout(() => resolve(false), FEDERATED_FORWARD_DEADLINE_MS)),
|
|
398
|
+
]);
|
|
399
|
+
debugNote({ op: "forward", type, from: peerId.slice(0, 8), to: message.to.slice(0, 8), hint, delivered: deliveredRemote, ms: Date.now() - startedAt });
|
|
400
|
+
if (deliveredRemote) {
|
|
401
|
+
relayLog('messages routed to other relays', `[FED] Routed ${type} to peer relay for ${message.to}`);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
} catch (error) {
|
|
405
|
+
debugNote({ op: "forward", type, from: peerId.slice(0, 8), to: message.to.slice(0, 8), hint, error: String(error?.stack || error?.message || error).slice(0, 400), ms: Date.now() - startedAt });
|
|
406
|
+
console.error(`[FED] forwarding ${type} to ${message.to} failed: ${error?.message}`);
|
|
407
|
+
}
|
|
408
|
+
// Not reachable right now (reconnecting, or not yet registered): hold it
|
|
409
|
+
// for the peer, as before. Only a peer that said goodbye is gone.
|
|
410
|
+
await insertRelayMessage(db, message);
|
|
411
|
+
relayLog('messages queued for absent peers', `[RELAY] Peer ${message.to} unavailable across federation, queued ${type} in DB`);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
if (kind === "cleanup") {
|
|
416
|
+
if (db) await cleanupExpired(db);
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
26
420
|
|
|
27
|
-
|
|
28
|
-
|
|
421
|
+
// Peers no relay had when last asked, so messages to them are dropped without
|
|
422
|
+
// asking again for a minute; and when each sender was last told, so it is
|
|
423
|
+
// told once a minute, not once per ICE candidate.
|
|
424
|
+
const ABSENT_PEER_MS = 60_000;
|
|
425
|
+
const MAX_ABSENT_PEERS = 5_000;
|
|
426
|
+
const absentPeerUntilMs = new Map();
|
|
427
|
+
// Peers that let go of this relay on purpose (relay on demand) and are still
|
|
428
|
+
// in their room's mesh, for as long as a membership lease lasts.
|
|
429
|
+
const RELAY_IDLE_PEER_MS = 10 * 60_000;
|
|
430
|
+
const relayIdlePeerUntilMs = new Map();
|
|
431
|
+
function noteRelayIdlePeer(key) {
|
|
432
|
+
if (relayIdlePeerUntilMs.size >= MAX_ABSENT_PEERS) relayIdlePeerUntilMs.delete(relayIdlePeerUntilMs.keys().next().value);
|
|
433
|
+
relayIdlePeerUntilMs.set(key, Date.now() + RELAY_IDLE_PEER_MS);
|
|
434
|
+
absentPeerUntilMs.delete(key);
|
|
435
|
+
}
|
|
436
|
+
const absentPeerToldAtMs = new Map();
|
|
437
|
+
function noteAbsentPeer(key) {
|
|
438
|
+
if (absentPeerUntilMs.size >= MAX_ABSENT_PEERS) absentPeerUntilMs.delete(absentPeerUntilMs.keys().next().value);
|
|
439
|
+
absentPeerUntilMs.set(key, Date.now() + ABSENT_PEER_MS);
|
|
440
|
+
}
|
|
441
|
+
export function clearAbsentPeer(network, room, peerId) {
|
|
442
|
+
absentPeerUntilMs.delete(peerScopeKey(network, room, peerId));
|
|
443
|
+
}
|
|
444
|
+
function tellSenderPeerGone(senderPeerId, network, room, message, relayPeerId) {
|
|
445
|
+
const socket = livePeers.get(peerScopeKey(network, room, senderPeerId))?.socket;
|
|
446
|
+
if (!socket) return;
|
|
447
|
+
const toldKey = `${peerScopeKey(network, room, senderPeerId)}>${message.to}`;
|
|
448
|
+
if (Date.now() - (absentPeerToldAtMs.get(toldKey) ?? 0) < ABSENT_PEER_MS) return;
|
|
449
|
+
if (absentPeerToldAtMs.size >= MAX_ABSENT_PEERS) absentPeerToldAtMs.delete(absentPeerToldAtMs.keys().next().value);
|
|
450
|
+
absentPeerToldAtMs.set(toldKey, Date.now());
|
|
451
|
+
try {
|
|
452
|
+
socket.send(JSON.stringify({
|
|
453
|
+
psp_version: PSP_VERSION, type: "error", network, session_id: room,
|
|
454
|
+
from: relayPeerId, to: senderPeerId,
|
|
455
|
+
message_id: crypto.randomUUID(), timestamp: Date.now(), ttl_ms: DEFAULT_TTL_MS,
|
|
456
|
+
body: { code: "target_not_connected", reason: "no relay has this peer", peer_id: message.to },
|
|
457
|
+
}));
|
|
458
|
+
} catch { /* the sender left too */ }
|
|
459
|
+
}
|
|
460
|
+
let nextSocketGeneration = 0;
|
|
461
|
+
|
|
462
|
+
export function claimLivePeer(livePeerMap, key, value) {
|
|
463
|
+
const current = livePeerMap.get(key);
|
|
464
|
+
if (
|
|
465
|
+
current?.socket !== value.socket
|
|
466
|
+
&& Number(current?.socketGeneration ?? 0) > Number(value.socketGeneration ?? 0)
|
|
467
|
+
) {
|
|
468
|
+
return false;
|
|
469
|
+
}
|
|
470
|
+
livePeerMap.set(key, value);
|
|
471
|
+
return true;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export function deleteLivePeerIfOwned(livePeerMap, key, socket) {
|
|
475
|
+
const current = livePeerMap.get(key);
|
|
476
|
+
if (!current || current.socket !== socket) return false;
|
|
477
|
+
livePeerMap.delete(key);
|
|
478
|
+
return true;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function relayCoordinatorStub(env) {
|
|
482
|
+
const namespace = env?.RELAY_COORDINATOR;
|
|
483
|
+
if (!namespace?.idFromName || !namespace?.get) return null;
|
|
484
|
+
return namespace.get(namespace.idFromName("relay"));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function normalizeRoom(value) {
|
|
488
|
+
return typeof value === "string" ? value.trim() : "";
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function scopeKey(network, room) {
|
|
492
|
+
return JSON.stringify([network, room]);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function peerScopeKey(network, room, peerId) {
|
|
496
|
+
return JSON.stringify([network, room, peerId]);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
export function rememberPeerRelayHint(network, room, peerId, relayUrl, now = Date.now()) {
|
|
500
|
+
const normalizedUrl = normalizeRelayUrl(relayUrl);
|
|
501
|
+
if (!network || !room || !peerId || !normalizedUrl || !/^wss?:\/\//.test(normalizedUrl)) return false;
|
|
502
|
+
peerRelayHints.set(peerScopeKey(network, room, peerId), {
|
|
503
|
+
url: normalizedUrl,
|
|
504
|
+
expiresAt: now + PEER_RELAY_HINT_TTL_MS,
|
|
505
|
+
});
|
|
506
|
+
// A relay lists the peer again: it is back.
|
|
507
|
+
absentPeerUntilMs.delete(peerScopeKey(network, room, peerId));
|
|
508
|
+
return true;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
export function forgetPeerRelayHint(network, room, peerId) {
|
|
512
|
+
peerRelayHints.delete(peerScopeKey(network, room, peerId));
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
export function getPeerRelayHint(network, room, peerId, now = Date.now()) {
|
|
516
|
+
const key = peerScopeKey(network, room, peerId);
|
|
517
|
+
const hint = peerRelayHints.get(key);
|
|
518
|
+
if (!hint) return null;
|
|
519
|
+
if (hint.expiresAt <= now) {
|
|
520
|
+
peerRelayHints.delete(key);
|
|
521
|
+
return null;
|
|
522
|
+
}
|
|
523
|
+
return hint.url;
|
|
524
|
+
}
|
|
29
525
|
|
|
30
526
|
let lastFederationMs = 0; // tracks last heartbeat time within this isolate
|
|
31
527
|
|
|
32
528
|
export default {
|
|
33
529
|
async fetch(request, env, ctx) {
|
|
530
|
+
relayVerbose = env?.FREERTC_VERBOSE === "1" || env?.FREERTC_VERBOSE === "true";
|
|
531
|
+
try {
|
|
532
|
+
return await handleFetch(request, env, ctx);
|
|
533
|
+
} catch (error) {
|
|
534
|
+
// An error that escapes a handler (a D1 call, a Durable Object hand-off) is logged
|
|
535
|
+
// with its path and answered with a 503, instead of failing the invocation.
|
|
536
|
+
console.error(`[FETCH] ${request.method} ${new URL(request.url).pathname}: ${error?.stack || error}`);
|
|
537
|
+
return jsonResponse({ ok: false, error: "Relay temporarily unavailable" }, 503);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
// The relay's own clock for jobs that must run once per relay, not once per
|
|
543
|
+
// isolate. Created on first use, so no migration is needed.
|
|
544
|
+
let relayClockReady = false;
|
|
545
|
+
|
|
546
|
+
/** True when this isolate claimed the federation heartbeat for this interval. */
|
|
547
|
+
export async function claimFederationHeartbeat(db, now) {
|
|
548
|
+
if (!relayClockReady) {
|
|
549
|
+
await db.prepare("CREATE TABLE IF NOT EXISTS psp_relay_clock (key TEXT PRIMARY KEY, at_ms INTEGER NOT NULL)").run();
|
|
550
|
+
await db.prepare("INSERT OR IGNORE INTO psp_relay_clock (key, at_ms) VALUES ('federation', 0)").run();
|
|
551
|
+
relayClockReady = true;
|
|
552
|
+
}
|
|
553
|
+
const result = await db.prepare(
|
|
554
|
+
"UPDATE psp_relay_clock SET at_ms = ?1 WHERE key = 'federation' AND at_ms <= ?2",
|
|
555
|
+
).bind(now, now - FEDERATION_INTERVAL_MS + FEDERATION_CLAIM_SLACK_MS).run();
|
|
556
|
+
return Number(result?.meta?.changes ?? 0) > 0;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
async function handleFetch(request, env, ctx) {
|
|
560
|
+
{
|
|
34
561
|
const url = new URL(request.url);
|
|
35
562
|
const upgrade = request.headers.get("Upgrade");
|
|
563
|
+
const selfRelayUrl = resolveSelfRelayUrl(request, env.RELAY_URL);
|
|
564
|
+
await primeRelayNodeId(env, selfRelayUrl);
|
|
36
565
|
|
|
37
|
-
// Heartbeat:
|
|
38
|
-
|
|
566
|
+
// Heartbeat: join the bounded Kademlia overlay when signing keys are
|
|
567
|
+
// configured. Older deployments retain the legacy registry fallback.
|
|
568
|
+
if (selfRelayUrl && env.DB) {
|
|
39
569
|
const now = Date.now();
|
|
40
570
|
if (now - lastFederationMs > FEDERATION_INTERVAL_MS) {
|
|
41
571
|
lastFederationMs = now;
|
|
42
572
|
ctx.waitUntil((async () => {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
//
|
|
48
|
-
|
|
49
|
-
|
|
573
|
+
// Every isolate keeps its own lastFederationMs, so each one the
|
|
574
|
+
// platform started heartbeat on its first request: a ping to up to
|
|
575
|
+
// 16 relays, which woke isolates there that pinged back. Each relay
|
|
576
|
+
// took ~1,300 pings an hour where a few dozen do. One heartbeat per
|
|
577
|
+
// relay per interval: the isolate that claims it in the relay's own
|
|
578
|
+
// database runs it.
|
|
579
|
+
// A database that cannot answer must not take the relay out of
|
|
580
|
+
// federation: then this isolate heartbeats, as every isolate used to.
|
|
581
|
+
if (!await claimFederationHeartbeat(env.DB, now).catch(() => true)) return;
|
|
582
|
+
const relayName = env.RELAY_NAME || relayHostname(selfRelayUrl);
|
|
583
|
+
if (isKademliaEnabled(env)) {
|
|
584
|
+
// A failed join is retried on the next heartbeat. Left uncaught, the rejection
|
|
585
|
+
// marked the request that happened to start it as a script exception.
|
|
586
|
+
await heartbeatKademlia(env, selfRelayUrl, { connections: livePeers.size })
|
|
587
|
+
.catch((error) => console.error(`[KAD] heartbeat failed: ${error?.stack || error}`));
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
await upsertRelay(env.DB, selfRelayUrl, relayName).catch(() => {});
|
|
592
|
+
// The legacy registry registers with a hub only when one is named. No relay is the
|
|
593
|
+
// default hub: a relay that names none just keeps its own registry.
|
|
594
|
+
const hubUrl = env.GLOBAL_RELAY_URL;
|
|
595
|
+
if (hubUrl && normalizeRelayUrl(hubUrl) !== selfRelayUrl) {
|
|
596
|
+
await registerWithHub(
|
|
597
|
+
{ ...env, GLOBAL_RELAY_URL: hubUrl, RELAY_NAME: relayName },
|
|
598
|
+
selfRelayUrl
|
|
599
|
+
).catch(() => {});
|
|
50
600
|
}
|
|
51
601
|
})());
|
|
52
602
|
}
|
|
53
603
|
}
|
|
54
604
|
|
|
605
|
+
// /t/<node id>/... is a relay behind NAT that tunnels through this one
|
|
606
|
+
// (src/tunnel): its federation calls and peer WebSockets go down the tunnel.
|
|
607
|
+
const tunnel = tunnelRoute(url.pathname);
|
|
608
|
+
if (tunnel) {
|
|
609
|
+
if (!env.RELAY_TUNNEL) return jsonResponse({ ok: false, error: "This relay is not a tunnel home" }, 404);
|
|
610
|
+
return env.RELAY_TUNNEL.get(env.RELAY_TUNNEL.idFromName(tunnel.nodeId)).fetch(request);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// The DNS relay directory (src/direct/directory.js): relays list and
|
|
614
|
+
// withdraw themselves here; only this Worker holds the DNS token.
|
|
615
|
+
if (url.pathname === DIRECTORY_PATH) {
|
|
616
|
+
if (!directoryEnabled(env)) return jsonResponse({ ok: false, error: "No relay directory here" }, 404);
|
|
617
|
+
return handleDirectoryRequest(request, env);
|
|
618
|
+
}
|
|
619
|
+
// Names for the owner's local relays on the owner's domain, and their
|
|
620
|
+
// Let's Encrypt challenges (src/direct/names.js).
|
|
621
|
+
if (url.pathname === NAMES_PATH) return handleNameRequest(request, env);
|
|
622
|
+
// A local relay checks that relays can call it on its public address
|
|
623
|
+
// before it federates there without a tunnel (src/direct/reachable.js).
|
|
624
|
+
if (url.pathname === REACHABLE_PATH) return handleReachableRequest(request);
|
|
625
|
+
|
|
626
|
+
if (request.method === "OPTIONS" && url.pathname.startsWith("/api/")) {
|
|
627
|
+
// Browsers preflight cross-origin API calls; a 405 here made Safari
|
|
628
|
+
// report the whole request as blocked by access control.
|
|
629
|
+
return new Response(null, {
|
|
630
|
+
status: 204,
|
|
631
|
+
headers: {
|
|
632
|
+
"Access-Control-Allow-Origin": "*",
|
|
633
|
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
|
634
|
+
"Access-Control-Allow-Headers": "Content-Type, Accept",
|
|
635
|
+
"Access-Control-Max-Age": "86400",
|
|
636
|
+
},
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
|
|
55
640
|
if (upgrade && upgrade.toLowerCase() === "websocket") {
|
|
56
641
|
if (url.pathname !== "/ws") {
|
|
57
642
|
return jsonResponse({ ok: false, error: "WebSocket endpoint is /ws" }, 404);
|
|
58
643
|
}
|
|
59
|
-
|
|
644
|
+
const coordinator = relayCoordinatorStub(env);
|
|
645
|
+
if (coordinator) return coordinator.fetch(request);
|
|
646
|
+
return handleWebSocket(request, env, ctx, selfRelayUrl);
|
|
60
647
|
}
|
|
61
648
|
|
|
62
649
|
if (url.pathname === "/ws") {
|
|
@@ -64,18 +651,33 @@ export default {
|
|
|
64
651
|
}
|
|
65
652
|
|
|
66
653
|
if (url.pathname === "/health") {
|
|
654
|
+
const coordinator = relayCoordinatorStub(env);
|
|
655
|
+
if (coordinator) return coordinator.fetch(request);
|
|
67
656
|
return jsonResponse({
|
|
68
657
|
ok: true,
|
|
69
658
|
version: WORKER_VERSION,
|
|
70
659
|
protocol_version: PSP_VERSION,
|
|
71
|
-
peers: livePeers.size
|
|
660
|
+
peers: livePeers.size,
|
|
661
|
+
relay_url: selfRelayUrl,
|
|
662
|
+
relay_peer_id: resolveRelayPeerId(selfRelayUrl),
|
|
663
|
+
node_id: relayNodeIdsByUrl.get(selfRelayUrl) ?? null,
|
|
664
|
+
relay_kind: relayKindOf(env),
|
|
665
|
+
kademlia_enabled: isKademliaEnabled(env),
|
|
666
|
+
bootstrap_urls: await listBootstrapUrls(env, selfRelayUrl).catch(() => configuredBootstrapUrls(env).filter((seed) => seed !== selfRelayUrl)),
|
|
72
667
|
}, 200);
|
|
73
668
|
}
|
|
74
669
|
|
|
670
|
+
if (url.pathname.startsWith("/api/v1/kad/")) {
|
|
671
|
+
return handleKademliaRequest(request, env, {
|
|
672
|
+
selfUrl: selfRelayUrl,
|
|
673
|
+
connections: livePeers.size,
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
|
|
75
677
|
// Federation: relay registry endpoints (any worker can serve these from its own D1)
|
|
76
678
|
if (url.pathname === "/api/v1/relays") {
|
|
77
679
|
if (request.method === "GET") {
|
|
78
|
-
return handleListRelays(env);
|
|
680
|
+
return handleListRelays(env, selfRelayUrl);
|
|
79
681
|
}
|
|
80
682
|
if (request.method === "POST") {
|
|
81
683
|
return handleRegisterRelay(request, env);
|
|
@@ -83,6 +685,25 @@ export default {
|
|
|
83
685
|
return jsonResponse({ ok: false, error: "Method not allowed" }, 405);
|
|
84
686
|
}
|
|
85
687
|
|
|
688
|
+
// Accounts shared between local relays (pigeonidp/relay): another relay
|
|
689
|
+
// asking this one's account store. Records are signed by their owners, so
|
|
690
|
+
// the store checks them itself; a relay without one says unsupported.
|
|
691
|
+
if (url.pathname === "/api/v1/idp") {
|
|
692
|
+
if (request.method !== "POST") return jsonResponse({ ok: false, error: "Method not allowed" }, 405);
|
|
693
|
+
if (typeof env.RELAY_REQUEST_HANDLER !== "function") return jsonResponse({ ok: false, error: "unsupported" }, 200);
|
|
694
|
+
const text = await request.text().catch(() => "");
|
|
695
|
+
if (text.length > 64 * 1024) return jsonResponse({ ok: false, error: "too large" }, 413);
|
|
696
|
+
let body = null;
|
|
697
|
+
try { body = JSON.parse(text); } catch { /* answered below */ }
|
|
698
|
+
if (!body || !["idp-get", "idp-put", "idp-sync"].includes(body.action)) return jsonResponse({ ok: false, error: "unsupported" }, 200);
|
|
699
|
+
try {
|
|
700
|
+
const result = await env.RELAY_REQUEST_HANDLER({ ...body, from_relay: true }, { fromRelay: true });
|
|
701
|
+
return jsonResponse(result ?? { ok: false, error: "unsupported" }, 200);
|
|
702
|
+
} catch (error) {
|
|
703
|
+
return jsonResponse({ ok: false, error: String(error?.message || error).slice(0, 200) }, 200);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
86
707
|
if (url.pathname === "/api/v1/peers") {
|
|
87
708
|
if (request.method === "GET") {
|
|
88
709
|
return handleListPeers(request, env);
|
|
@@ -90,8 +711,15 @@ export default {
|
|
|
90
711
|
return jsonResponse({ ok: false, error: "Method not allowed" }, 405);
|
|
91
712
|
}
|
|
92
713
|
|
|
714
|
+
if (url.pathname === "/debug/state") {
|
|
715
|
+
const coordinator = relayCoordinatorStub(env);
|
|
716
|
+
if (coordinator) return coordinator.fetch(request);
|
|
717
|
+
return jsonResponse({ ok: false, error: "No coordinator" }, 404);
|
|
718
|
+
}
|
|
93
719
|
if (url.pathname === "/api/v1/relay") {
|
|
94
720
|
if (request.method === "POST") {
|
|
721
|
+
const coordinator = relayCoordinatorStub(env);
|
|
722
|
+
if (coordinator) return coordinator.fetch(request);
|
|
95
723
|
return handleRelayForward(request, env);
|
|
96
724
|
}
|
|
97
725
|
return jsonResponse({ ok: false, error: "Method not allowed" }, 405);
|
|
@@ -99,7 +727,74 @@ export default {
|
|
|
99
727
|
|
|
100
728
|
return env.ASSETS?.fetch(request) ?? new Response("Not Found", { status: 404 });
|
|
101
729
|
}
|
|
102
|
-
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// Cloudflare may run an HTTP federation request in a different Worker isolate
|
|
733
|
+
// from the destination WebSocket. A single Durable Object per relay owns both
|
|
734
|
+
// entry points so a live peer can receive offers, answers, and ICE immediately
|
|
735
|
+
// instead of waiting for its next ping to drain D1.
|
|
736
|
+
export class RelayCoordinator {
|
|
737
|
+
constructor(state, env) {
|
|
738
|
+
this.state = state;
|
|
739
|
+
this.env = env;
|
|
740
|
+
// Work queued before a restart is still in storage; make sure an alarm
|
|
741
|
+
// exists to drain it.
|
|
742
|
+
state.blockConcurrencyWhile(async () => {
|
|
743
|
+
const pending = await state.storage.list({ prefix: DEFERRED_TASK_PREFIX, limit: 1 });
|
|
744
|
+
if (pending.size > 0 && (await state.storage.getAlarm()) === null) {
|
|
745
|
+
await state.storage.setAlarm(Date.now());
|
|
746
|
+
}
|
|
747
|
+
}).catch(() => {});
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
async alarm() {
|
|
751
|
+
await drainDeferredTasks(this.state, this.env);
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async fetch(request) {
|
|
755
|
+
const url = new URL(request.url);
|
|
756
|
+
const upgrade = request.headers.get("Upgrade");
|
|
757
|
+
const selfRelayUrl = resolveSelfRelayUrl(request, this.env.RELAY_URL);
|
|
758
|
+
await primeRelayNodeId(this.env, selfRelayUrl);
|
|
759
|
+
|
|
760
|
+
if (upgrade && upgrade.toLowerCase() === "websocket" && url.pathname === "/ws") {
|
|
761
|
+
return handleWebSocket(request, this.env, this.state, selfRelayUrl);
|
|
762
|
+
}
|
|
763
|
+
if (url.pathname === "/api/v1/relay" && request.method === "POST") {
|
|
764
|
+
return handleRelayForward(request, this.env);
|
|
765
|
+
}
|
|
766
|
+
if (url.pathname === "/debug/state") {
|
|
767
|
+
const now = Date.now();
|
|
768
|
+
const queued = await this.state.storage.list({ prefix: DEFERRED_TASK_PREFIX, limit: 1000 }).catch(() => null);
|
|
769
|
+
const alarm = await this.state.storage.getAlarm().catch(() => null);
|
|
770
|
+
return jsonResponse({
|
|
771
|
+
ok: true,
|
|
772
|
+
now,
|
|
773
|
+
queue: { tasks: queued ? queued.size : null, oldest: queued?.size ? [...queued.keys()][0] : null, alarm_in_ms: alarm === null ? null : alarm - now },
|
|
774
|
+
peers: livePeers.size,
|
|
775
|
+
peerKeys: [...livePeers.keys()].map((key) => key.slice(0, 80)),
|
|
776
|
+
hints: [...peerRelayHints.entries()].map(([key, hint]) => ({ key: key.slice(0, 80), url: hint.url, expiresIn: hint.expiresAt - now })),
|
|
777
|
+
trail: debugTrail.slice(-Number(url.searchParams.get("limit") || 60)),
|
|
778
|
+
}, 200);
|
|
779
|
+
}
|
|
780
|
+
if (url.pathname === "/health") {
|
|
781
|
+
return jsonResponse({
|
|
782
|
+
ok: true,
|
|
783
|
+
version: WORKER_VERSION,
|
|
784
|
+
protocol_version: PSP_VERSION,
|
|
785
|
+
peers: livePeers.size,
|
|
786
|
+
relay_url: selfRelayUrl,
|
|
787
|
+
relay_peer_id: resolveRelayPeerId(selfRelayUrl),
|
|
788
|
+
node_id: relayNodeIdsByUrl.get(selfRelayUrl) ?? null,
|
|
789
|
+
relay_kind: relayKindOf(this.env),
|
|
790
|
+
kademlia_enabled: isKademliaEnabled(this.env),
|
|
791
|
+
bootstrap_urls: await listBootstrapUrls(this.env, selfRelayUrl).catch(() => configuredBootstrapUrls(this.env).filter((seed) => seed !== selfRelayUrl)),
|
|
792
|
+
coordinated: true,
|
|
793
|
+
}, 200);
|
|
794
|
+
}
|
|
795
|
+
return jsonResponse({ ok: false, error: "Not Found" }, 404);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
103
798
|
|
|
104
799
|
function jsonResponse(body, status = 200) {
|
|
105
800
|
return new Response(JSON.stringify(body), {
|
|
@@ -110,12 +805,34 @@ function jsonResponse(body, status = 200) {
|
|
|
110
805
|
|
|
111
806
|
// ===================== Federation =====================
|
|
112
807
|
|
|
113
|
-
async function handleListRelays(env) {
|
|
808
|
+
async function handleListRelays(env, selfRelayUrl = null) {
|
|
114
809
|
if (!env.DB) return jsonResponse({ ok: false, error: "No database" }, 503);
|
|
115
|
-
const relays = await
|
|
810
|
+
const relays = await listFederatedRelays(env, selfRelayUrl);
|
|
116
811
|
return jsonResponse({ ok: true, relays });
|
|
117
812
|
}
|
|
118
813
|
|
|
814
|
+
// The registry a client bootstraps from is every relay this one knows: the
|
|
815
|
+
// legacy self-registrations in psp_relays plus every relay verified through
|
|
816
|
+
// the Kademlia overlay, with this relay itself first. Before this, a relay
|
|
817
|
+
// with signing keys skipped the legacy registration entirely and answered
|
|
818
|
+
// with an empty list, so clients ranking relays by distance only ever saw
|
|
819
|
+
// the static defaults and every newly deployed relay stayed invisible.
|
|
820
|
+
async function listFederatedRelays(env, selfRelayUrl = null) {
|
|
821
|
+
const merged = new Map();
|
|
822
|
+
const add = (relay) => {
|
|
823
|
+
const relayUrl = normalizeRelayUrl(relay?.url);
|
|
824
|
+
if (!relayUrl) return;
|
|
825
|
+
const previous = merged.get(relayUrl) || {};
|
|
826
|
+
merged.set(relayUrl, { ...previous, ...relay, url: relayUrl, name: relay.name ?? previous.name ?? null });
|
|
827
|
+
};
|
|
828
|
+
if (selfRelayUrl) add({ url: selfRelayUrl, name: env.RELAY_NAME || relayHostname(selfRelayUrl) });
|
|
829
|
+
if (isKademliaEnabled(env) && selfRelayUrl) {
|
|
830
|
+
for (const relay of await listKnownRelays(env, selfRelayUrl, { connections: livePeers.size }).catch(() => [])) add(relay);
|
|
831
|
+
}
|
|
832
|
+
for (const relay of await listRelays(env.DB).catch(() => [])) add(relay);
|
|
833
|
+
return Array.from(merged.values());
|
|
834
|
+
}
|
|
835
|
+
|
|
119
836
|
async function handleRegisterRelay(request, env) {
|
|
120
837
|
if (!env.DB) return jsonResponse({ ok: false, error: "No database" }, 503);
|
|
121
838
|
let body;
|
|
@@ -136,23 +853,18 @@ async function handleListPeers(request, env) {
|
|
|
136
853
|
if (!env.DB) return jsonResponse({ ok: false, error: "No database" }, 503);
|
|
137
854
|
const url = new URL(request.url);
|
|
138
855
|
const network = (url.searchParams.get("network") || "").trim();
|
|
856
|
+
const room = (url.searchParams.get("room") || url.searchParams.get("session_id") || "").trim();
|
|
139
857
|
const excludePeerId = (url.searchParams.get("exclude") || "").trim();
|
|
140
858
|
if (!network) return jsonResponse({ ok: false, error: "Missing network" }, 400);
|
|
141
|
-
|
|
142
|
-
const peers = await findPeers(env.DB, network, excludePeerId);
|
|
859
|
+
if (!room) return jsonResponse({ ok: false, error: "Missing room" }, 400);
|
|
860
|
+
const peers = await findPeers(env.DB, network, room, excludePeerId);
|
|
143
861
|
return jsonResponse({ ok: true, peers });
|
|
144
862
|
}
|
|
145
863
|
|
|
146
|
-
async function handleRelayForward(request, env) {
|
|
864
|
+
export async function handleRelayForward(request, env) {
|
|
147
865
|
if (!env.DB) return jsonResponse({ ok: false, error: "No database" }, 503);
|
|
148
|
-
|
|
149
866
|
let body;
|
|
150
|
-
try {
|
|
151
|
-
body = await request.json();
|
|
152
|
-
} catch {
|
|
153
|
-
return jsonResponse({ ok: false, error: "Invalid JSON" }, 400);
|
|
154
|
-
}
|
|
155
|
-
|
|
867
|
+
try { body = await request.json(); } catch { return jsonResponse({ ok: false, error: "Invalid JSON" }, 400); }
|
|
156
868
|
const message = body?.message || body;
|
|
157
869
|
if (!validEnvelope(message)) {
|
|
158
870
|
return jsonResponse({ ok: false, error: "Invalid PSP envelope" }, 400);
|
|
@@ -163,23 +875,50 @@ async function handleRelayForward(request, env) {
|
|
|
163
875
|
if (!message.to || typeof message.to !== "string") {
|
|
164
876
|
return jsonResponse({ ok: false, error: "Missing destination peer" }, 400);
|
|
165
877
|
}
|
|
166
|
-
|
|
167
|
-
const
|
|
878
|
+
const room = normalizeRoom(message.session_id);
|
|
879
|
+
const viaRelayUrl = typeof body?.via === "string" && /^wss?:\/\//.test(body.via)
|
|
880
|
+
? normalizeRelayUrl(body.via)
|
|
881
|
+
: null;
|
|
882
|
+
if (viaRelayUrl) {
|
|
883
|
+
rememberPeerRelayHint(message.network, room, message.from, viaRelayUrl);
|
|
884
|
+
}
|
|
885
|
+
const liveKey = peerScopeKey(message.network, room, message.to);
|
|
168
886
|
const live = livePeers.get(liveKey);
|
|
169
887
|
if (live) {
|
|
170
888
|
try {
|
|
171
889
|
live.socket.send(JSON.stringify(message));
|
|
890
|
+
relayLog('messages from other relays delivered', `[FED-IN] ${message.type} ${message.from?.slice(0, 8)} → ${message.to?.slice(0, 8)} from ${viaRelayUrl}: delivered to live socket`);
|
|
172
891
|
return jsonResponse({ ok: true, delivered: true }, 200);
|
|
173
|
-
} catch {
|
|
892
|
+
} catch (error) {
|
|
893
|
+
console.log(`[FED-IN] ${message.type} ${message.from?.slice(0, 8)} → ${message.to?.slice(0, 8)} from ${viaRelayUrl}: live socket send failed (${error?.message})`);
|
|
894
|
+
}
|
|
895
|
+
} else {
|
|
896
|
+
relayLog('messages from other relays for absent peers', `[FED-IN] ${message.type} ${message.from?.slice(0, 8)} → ${message.to?.slice(0, 8)} from ${viaRelayUrl}: not live here (${livePeers.size} live)`);
|
|
897
|
+
}
|
|
898
|
+
// A relay that has never heard of the peer keeps nothing for it. The sender asks every relay
|
|
899
|
+
// that serves the room, so a copy queued at each would be a write apiece and a false
|
|
900
|
+
// "queued" to the sender. A peer announced here but momentarily without a socket is still
|
|
901
|
+
// held for, as before.
|
|
902
|
+
const restingHere = (relayIdlePeerUntilMs.get(liveKey) ?? 0) > Date.now();
|
|
903
|
+
if (!live && !restingHere && !(await peerIsKnownHere(env.DB, message.network, room, message.to))) {
|
|
904
|
+
return jsonResponse({ ok: true, delivered: false, queued: false }, 200);
|
|
174
905
|
}
|
|
175
|
-
|
|
176
906
|
await insertRelayMessage(env.DB, message);
|
|
177
907
|
return jsonResponse({ ok: true, delivered: false, queued: true }, 202);
|
|
178
908
|
}
|
|
179
909
|
|
|
910
|
+
async function peerIsKnownHere(db, network, room, peerId) {
|
|
911
|
+
const result = await db.prepare(`
|
|
912
|
+
SELECT 1 AS known FROM psp_announcements
|
|
913
|
+
WHERE network = ?1 AND peer_id = ?2 AND expires_at_ms > ?3
|
|
914
|
+
LIMIT 1
|
|
915
|
+
`).bind(scopeKey(network, room), peerId, Date.now()).all();
|
|
916
|
+
return (result.results || []).length > 0;
|
|
917
|
+
}
|
|
918
|
+
|
|
180
919
|
// POST to the global hub; cache returned relay list into own D1 so both sides know each other
|
|
181
920
|
async function registerWithHub(env, selfUrl) {
|
|
182
|
-
const resp = await
|
|
921
|
+
const resp = await relayFetch(`${relayHttpBase(normalizeRelayUrl(env.GLOBAL_RELAY_URL))}/api/v1/relays`, {
|
|
183
922
|
method: "POST",
|
|
184
923
|
headers: { "Content-Type": "application/json" },
|
|
185
924
|
body: JSON.stringify({ url: selfUrl, name: env.RELAY_NAME || null })
|
|
@@ -216,37 +955,302 @@ function normalizeRelayUrl(url) {
|
|
|
216
955
|
return u;
|
|
217
956
|
}
|
|
218
957
|
|
|
958
|
+
// A Deploy to Cloudflare flow does not know the account's workers.dev
|
|
959
|
+
// subdomain in advance. Derive it from the first HTTPS request unless an
|
|
960
|
+
// explicit RELAY_URL was configured. Local HTTP development stays unfederated.
|
|
961
|
+
function resolveSelfRelayUrl(request, configuredUrl) {
|
|
962
|
+
const configured = normalizeRelayUrl(configuredUrl);
|
|
963
|
+
if (configured) return configured;
|
|
964
|
+
|
|
965
|
+
try {
|
|
966
|
+
const requestUrl = new URL(request.url);
|
|
967
|
+
if (requestUrl.protocol !== "https:") return null;
|
|
968
|
+
if (!requestUrl.hostname.toLowerCase().endsWith(".workers.dev")) return null;
|
|
969
|
+
return `wss://${requestUrl.host}/ws`;
|
|
970
|
+
} catch {
|
|
971
|
+
return null;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
function relayHostname(relayUrl) {
|
|
976
|
+
try {
|
|
977
|
+
return new URL(relayUrl).hostname;
|
|
978
|
+
} catch {
|
|
979
|
+
return null;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// A relay's peer ID is the SHA-256 of its deployed domain. There is no setting for it.
|
|
984
|
+
// A relay's PSP peer ID is its Kademlia node ID when it has a federation
|
|
985
|
+
// identity, so the relay is one ID everywhere (and a relay behind NAT no
|
|
986
|
+
// longer signs as its tunnel home's domain). A relay without one keeps the
|
|
987
|
+
// SHA-256 of its domain. Synchronous for every frame: primeRelayNodeId fills
|
|
988
|
+
// the cache, keyed by the relay's own URL, before a request is handled.
|
|
989
|
+
const relayNodeIdsByUrl = new Map();
|
|
990
|
+
|
|
991
|
+
async function primeRelayNodeId(env, selfRelayUrl) {
|
|
992
|
+
if (!selfRelayUrl || relayNodeIdsByUrl.has(selfRelayUrl)) return;
|
|
993
|
+
relayNodeIdsByUrl.set(selfRelayUrl, await relayNodeIdOf(env));
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
function resolveRelayPeerId(selfRelayUrl) {
|
|
997
|
+
return relayNodeIdsByUrl.get(selfRelayUrl) ?? relayPeerIdFor(selfRelayUrl);
|
|
998
|
+
}
|
|
999
|
+
|
|
219
1000
|
// Derive HTTP base URL from a wss:// relay URL (wss://peer.ooo/ws → https://peer.ooo)
|
|
220
1001
|
function relayHttpBase(wsUrl) {
|
|
221
1002
|
return wsUrl.replace(/^wss?:\/\//, (m) => m === "wss://" ? "https://" : "http://").replace(/\/ws$/, "");
|
|
222
1003
|
}
|
|
223
1004
|
|
|
224
|
-
// Query
|
|
225
|
-
async function queryRelayForPeers(relayUrl, network, requesterPeerId) {
|
|
1005
|
+
// Query a remote relay's HTTP peer-list endpoint.
|
|
1006
|
+
async function queryRelayForPeers(relayUrl, network, room, requesterPeerId, relayNodeId = null) {
|
|
226
1007
|
try {
|
|
227
1008
|
const base = relayHttpBase(relayUrl);
|
|
228
|
-
const params = new URLSearchParams({ network });
|
|
1009
|
+
const params = new URLSearchParams({ network, room });
|
|
229
1010
|
if (requesterPeerId) params.set("exclude", requesterPeerId);
|
|
230
|
-
|
|
1011
|
+
// A relay that hangs must not hang every discover that consults it: one
|
|
1012
|
+
// slow provider stalled the whole federated list past the clients' probe
|
|
1013
|
+
// window and they switched relays instead of getting an answer.
|
|
1014
|
+
const resp = await relayFetch(`${base}/api/v1/peers?${params.toString()}`, {
|
|
1015
|
+
signal: AbortSignal.timeout(FEDERATED_PEER_QUERY_TIMEOUT_MS),
|
|
1016
|
+
});
|
|
231
1017
|
if (!resp.ok) return [];
|
|
232
1018
|
const data = await resp.json();
|
|
233
1019
|
const peers = Array.isArray(data?.peers) ? data.peers : [];
|
|
234
|
-
return peers.map(p => ({ ...p, relay_url: relayUrl }));
|
|
1020
|
+
return peers.map(p => ({ ...p, relay_url: relayUrl, ...(relayNodeId ? { relay_node_id: relayNodeId } : {}) }));
|
|
235
1021
|
} catch {
|
|
236
1022
|
return [];
|
|
237
1023
|
}
|
|
238
1024
|
}
|
|
239
1025
|
|
|
240
|
-
|
|
241
|
-
|
|
1026
|
+
const FEDERATED_PEER_SHARE_MS = 5_000;
|
|
1027
|
+
const MAX_SHARED_FEDERATED_QUERIES = 2_000;
|
|
1028
|
+
const sharedFederatedQueries = new Map();
|
|
1029
|
+
|
|
1030
|
+
export async function sharedFederatedPeerQuery(selfRelayUrl, network, room, remoteUrls, nodeIdByUrl) {
|
|
1031
|
+
const key = JSON.stringify([selfRelayUrl, network, room, [...remoteUrls].sort()]);
|
|
1032
|
+
const now = Date.now();
|
|
1033
|
+
const shared = sharedFederatedQueries.get(key);
|
|
1034
|
+
if (shared && now - shared.startedAt < FEDERATED_PEER_SHARE_MS) return shared.promise;
|
|
1035
|
+
const promise = Promise.all(
|
|
1036
|
+
remoteUrls.map((relayUrl) => queryRelayForPeers(relayUrl, network, room, null, nodeIdByUrl.get(relayUrl) ?? null)),
|
|
1037
|
+
).then((lists) => lists.flat());
|
|
1038
|
+
sharedFederatedQueries.set(key, { promise, startedAt: now });
|
|
1039
|
+
if (sharedFederatedQueries.size > MAX_SHARED_FEDERATED_QUERIES) {
|
|
1040
|
+
const oldest = sharedFederatedQueries.keys().next().value;
|
|
1041
|
+
if (oldest !== undefined) sharedFederatedQueries.delete(oldest);
|
|
1042
|
+
}
|
|
1043
|
+
promise.catch(() => { if (sharedFederatedQueries.get(key)?.promise === promise) sharedFederatedQueries.delete(key); });
|
|
1044
|
+
return promise;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** The open-port (ws) URLs of the relays in the DNS relay directory; [] when DNS does not answer. */
|
|
1048
|
+
let directoryUrlsCache = { at: 0, urls: [], pending: null };
|
|
1049
|
+
async function directoryRelayUrls() {
|
|
1050
|
+
// Cached for a minute either way, and never waited on for more than 1.5 s:
|
|
1051
|
+
// a slow or unreachable resolver must not hold up a peer's discover.
|
|
1052
|
+
if (Date.now() - directoryUrlsCache.at < 60_000) return directoryUrlsCache.urls;
|
|
1053
|
+
directoryUrlsCache.pending ??= lookupDirectRelays()
|
|
1054
|
+
.then((records) => records.map((record) => record.ws).filter((url) => typeof url === 'string' && url.startsWith('ws://')))
|
|
1055
|
+
.catch(() => [])
|
|
1056
|
+
.then((urls) => { directoryUrlsCache = { at: Date.now(), urls, pending: null }; return urls; });
|
|
1057
|
+
return Promise.race([directoryUrlsCache.pending, new Promise((resolve) => setTimeout(() => resolve(directoryUrlsCache.urls), 1_500))]);
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
async function findFederatedPeers(
|
|
1061
|
+
env,
|
|
1062
|
+
selfRelayUrl,
|
|
1063
|
+
network,
|
|
1064
|
+
room,
|
|
1065
|
+
requesterPeerId,
|
|
1066
|
+
connections = 0,
|
|
1067
|
+
publishedScopeProviders = null,
|
|
1068
|
+
) {
|
|
1069
|
+
const localPeers = env.DB
|
|
1070
|
+
? await findPeers(env.DB, network, room, requesterPeerId)
|
|
1071
|
+
: [];
|
|
1072
|
+
|
|
1073
|
+
if (!selfRelayUrl || !env.DB) return localPeers;
|
|
1074
|
+
|
|
1075
|
+
let remoteUrls;
|
|
1076
|
+
// Which relay holds each remote peer, by node ID as well as URL (the URL of a
|
|
1077
|
+
// relay behind NAT is its tunnel home's; the node ID is its own).
|
|
1078
|
+
const nodeIdByUrl = new Map();
|
|
1079
|
+
if (isKademliaEnabled(env)) {
|
|
1080
|
+
const providers = Array.isArray(publishedScopeProviders)
|
|
1081
|
+
? publishedScopeProviders
|
|
1082
|
+
: await lookupScopeProviders(
|
|
1083
|
+
env,
|
|
1084
|
+
selfRelayUrl,
|
|
1085
|
+
network,
|
|
1086
|
+
room,
|
|
1087
|
+
{ connections },
|
|
1088
|
+
);
|
|
1089
|
+
for (const provider of providers) {
|
|
1090
|
+
if (provider?.url && provider?.node_id) nodeIdByUrl.set(provider.url, provider.node_id);
|
|
1091
|
+
}
|
|
1092
|
+
// Relays this one is linked to directly (node-relay: punched channels or
|
|
1093
|
+
// the LAN) are always asked too. The room's provider records live on the
|
|
1094
|
+
// relays closest to the room in the overlay, often cloud relays; when
|
|
1095
|
+
// those are out of requests, linked local relays still find each other's
|
|
1096
|
+
// peers.
|
|
1097
|
+
const linked = [
|
|
1098
|
+
...(typeof env.LINKED_RELAY_URLS === 'function' ? env.LINKED_RELAY_URLS() : []),
|
|
1099
|
+
// and the relays behind NAT reached through this one (node-relay)
|
|
1100
|
+
...(typeof env.HOSTED_RELAY_URLS === 'function' ? env.HOSTED_RELAY_URLS() : []),
|
|
1101
|
+
];
|
|
1102
|
+
// And every relay in the DNS relay directory (by its open port), read
|
|
1103
|
+
// through public DNS-over-HTTPS and cached: no cloud relay is involved.
|
|
1104
|
+
const listed = await directoryRelayUrls();
|
|
1105
|
+
remoteUrls = [...new Set([...providers.map((provider) => provider.url), ...linked, ...listed])]
|
|
1106
|
+
.filter((relayUrl) => relayUrl && relayUrl !== selfRelayUrl);
|
|
1107
|
+
} else {
|
|
1108
|
+
const allRelays = await listRelays(env.DB);
|
|
1109
|
+
remoteUrls = allRelays.map((relay) => relay.url).filter((relayUrl) => relayUrl !== selfRelayUrl);
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// Every discover asked every relay serving the room for its list: a GET to
|
|
1113
|
+
// each, a relay behind NAT through its tunnel. A room's discovers within
|
|
1114
|
+
// FEDERATED_PEER_SHARE_MS now share one round (the lists are fetched
|
|
1115
|
+
// without the requester excluded, and filtered for each caller below).
|
|
1116
|
+
const remotePeers = remoteUrls.length
|
|
1117
|
+
? await sharedFederatedPeerQuery(selfRelayUrl, network, room, remoteUrls, nodeIdByUrl)
|
|
1118
|
+
: [];
|
|
1119
|
+
|
|
1120
|
+
const peers = mergeDiscoveredPeers(localPeers, remotePeers)
|
|
1121
|
+
.filter((peer) => peer.peer_id !== requesterPeerId);
|
|
1122
|
+
for (const peer of peers) {
|
|
1123
|
+
if (peer?.relay_url) {
|
|
1124
|
+
rememberPeerRelayHint(network, room, peer.peer_id, peer.relay_url);
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
return peers;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
async function discoverJoiningPeer({ discover, publish, send }) {
|
|
1131
|
+
const eagerDiscovery = discover();
|
|
1132
|
+
const publication = publish();
|
|
1133
|
+
const eagerPeers = await eagerDiscovery;
|
|
1134
|
+
|
|
1135
|
+
if (eagerPeers.length > 0) {
|
|
1136
|
+
send(eagerPeers);
|
|
1137
|
+
await publication;
|
|
1138
|
+
return eagerPeers;
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
const publishedScopeProviders = await publication;
|
|
1142
|
+
const peers = await discover(publishedScopeProviders);
|
|
1143
|
+
if (peers.length > 0) send(peers);
|
|
1144
|
+
return peers;
|
|
1145
|
+
}
|
|
1146
|
+
|
|
1147
|
+
// Forward a PSP message through a remote relay's HTTP endpoint.
|
|
1148
|
+
async function forwardToRelayResult(relayUrl, message, selfRelayId) {
|
|
242
1149
|
try {
|
|
243
1150
|
const base = relayHttpBase(relayUrl);
|
|
244
|
-
await
|
|
1151
|
+
const response = await relayFetch(`${base}/api/v1/relay`, {
|
|
245
1152
|
method: "POST",
|
|
246
1153
|
headers: { "Content-Type": "application/json" },
|
|
247
1154
|
body: JSON.stringify({ message, via: selfRelayId || "relay-bridge" })
|
|
248
1155
|
});
|
|
249
|
-
|
|
1156
|
+
// Cloudflare counts unread response bodies as active outbound requests.
|
|
1157
|
+
// Offer/answer/ICE bursts can otherwise exhaust that limit and deadlock
|
|
1158
|
+
// the WebSocket request that is forwarding the negotiation.
|
|
1159
|
+
const bytes = await response.arrayBuffer();
|
|
1160
|
+
let outcome = "delivered";
|
|
1161
|
+
let why = null;
|
|
1162
|
+
if (!response.ok) {
|
|
1163
|
+
outcome = "failed";
|
|
1164
|
+
why = `answered ${response.status}`;
|
|
1165
|
+
} else {
|
|
1166
|
+
try {
|
|
1167
|
+
const result = JSON.parse(new TextDecoder().decode(bytes));
|
|
1168
|
+
if (result?.delivered === true) outcome = "delivered";
|
|
1169
|
+
else if (result?.queued === true) outcome = "queued";
|
|
1170
|
+
else if (result?.delivered === false) { outcome = "failed"; why = "the peer was no longer on that relay"; }
|
|
1171
|
+
} catch {
|
|
1172
|
+
// Legacy relay versions returned an empty success response.
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
relayLog(outcome === 'delivered' ? 'messages forwarded to other relays' : `forwards ${outcome}${why ? ` (${why})` : ''}`, `[FED] ${message.type} ${message.from?.slice(0, 8)} → ${message.to?.slice(0, 8)} via ${relayUrl}: ${outcome} (${response.status})`);
|
|
1176
|
+
if (outcome !== 'delivered') debugNote({ op: "forward-to-relay", type: message.type, to: message.to?.slice(0, 8), relay: relayUrl, outcome, why, status: response.status });
|
|
1177
|
+
return outcome;
|
|
1178
|
+
} catch (error) {
|
|
1179
|
+
debugNote({ op: "forward-to-relay", type: message.type, to: message.to?.slice(0, 8), relay: relayUrl, outcome: "failed", why: String(error?.message || error).slice(0, 160) });
|
|
1180
|
+
relayLog('forwards failed (the other relay did not answer)', `[FED] ${message.type} ${message.from?.slice(0, 8)} → ${message.to?.slice(0, 8)} via ${relayUrl}: fetch failed (${error?.message})`);
|
|
1181
|
+
return "failed";
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
export async function forwardToRelay(relayUrl, message, selfRelayId) {
|
|
1186
|
+
return (await forwardToRelayResult(relayUrl, message, selfRelayId)) === "delivered";
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
export async function forwardFederatedMessage(
|
|
1190
|
+
env,
|
|
1191
|
+
selfRelayUrl,
|
|
1192
|
+
network,
|
|
1193
|
+
room,
|
|
1194
|
+
message,
|
|
1195
|
+
connections = 0,
|
|
1196
|
+
options = {},
|
|
1197
|
+
) {
|
|
1198
|
+
const attempted = new Set(options.attempted || []);
|
|
1199
|
+
const queued = new Set();
|
|
1200
|
+
const hintedRelay = getPeerRelayHint(network, room, message.to);
|
|
1201
|
+
if (hintedRelay && hintedRelay !== selfRelayUrl && !attempted.has(hintedRelay)) {
|
|
1202
|
+
attempted.add(hintedRelay);
|
|
1203
|
+
const result = await forwardToRelayResult(hintedRelay, message, selfRelayUrl);
|
|
1204
|
+
if (result === "delivered") return true;
|
|
1205
|
+
if (result === "queued") queued.add(hintedRelay);
|
|
1206
|
+
}
|
|
1207
|
+
|
|
1208
|
+
const kademliaEnabled = isKademliaEnabled(env);
|
|
1209
|
+
let remoteUrls;
|
|
1210
|
+
let providerUrls = new Set();
|
|
1211
|
+
if (kademliaEnabled) {
|
|
1212
|
+
const providers = await lookupRoomProviders(
|
|
1213
|
+
env,
|
|
1214
|
+
selfRelayUrl,
|
|
1215
|
+
network,
|
|
1216
|
+
room,
|
|
1217
|
+
{ connections },
|
|
1218
|
+
);
|
|
1219
|
+
providerUrls = new Set(providers.map((provider) => provider.url));
|
|
1220
|
+
remoteUrls = [...providerUrls]
|
|
1221
|
+
.filter((relayUrl) => relayUrl !== selfRelayUrl && !attempted.has(relayUrl))
|
|
1222
|
+
.slice(0, KADEMLIA_FORWARD_LIMIT);
|
|
1223
|
+
} else {
|
|
1224
|
+
remoteUrls = (await getPeerRelayUrls(env.DB, selfRelayUrl))
|
|
1225
|
+
.filter((relayUrl) => !attempted.has(relayUrl));
|
|
1226
|
+
}
|
|
1227
|
+
// A queued result is authoritative only when Kademlia identifies that relay
|
|
1228
|
+
// as a provider for the destination peer. A stale discovery hint must not
|
|
1229
|
+
// prevent the provider lookup from finding a new live route.
|
|
1230
|
+
if (kademliaEnabled) {
|
|
1231
|
+
if ([...queued].some((relayUrl) => providerUrls.has(relayUrl))) return true;
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
if (!remoteUrls.length && !kademliaEnabled) return false;
|
|
1235
|
+
const results = await Promise.all(remoteUrls.map(async (relayUrl) => ({
|
|
1236
|
+
relayUrl,
|
|
1237
|
+
result: await forwardToRelayResult(relayUrl, message, selfRelayUrl),
|
|
1238
|
+
})));
|
|
1239
|
+
const delivered = results.find(({ result }) => result === "delivered");
|
|
1240
|
+
if (delivered) {
|
|
1241
|
+
rememberPeerRelayHint(network, room, message.to, delivered.relayUrl);
|
|
1242
|
+
return true;
|
|
1243
|
+
}
|
|
1244
|
+
if (kademliaEnabled && results.some(({ result }) => result === "queued")) {
|
|
1245
|
+
return true;
|
|
1246
|
+
}
|
|
1247
|
+
// The room's relays are cached for minutes, so a relay that started serving it since then
|
|
1248
|
+
// is missing from them. Ask the overlay again once and try only the relays that are new.
|
|
1249
|
+
if (kademliaEnabled && !options.refreshed && refreshRoomProviders(selfRelayUrl, network, room)) {
|
|
1250
|
+
for (const relayUrl of remoteUrls) attempted.add(relayUrl);
|
|
1251
|
+
return forwardFederatedMessage(env, selfRelayUrl, network, room, message, connections, { refreshed: true, attempted });
|
|
1252
|
+
}
|
|
1253
|
+
return false;
|
|
250
1254
|
}
|
|
251
1255
|
|
|
252
1256
|
// ===================== D1 Relay Registry =====================
|
|
@@ -291,11 +1295,68 @@ function mergeDiscoveredPeers(...peerGroups) {
|
|
|
291
1295
|
return Array.from(merged.values()).sort((left, right) => left.peer_id.localeCompare(right.peer_id));
|
|
292
1296
|
}
|
|
293
1297
|
|
|
294
|
-
|
|
1298
|
+
// Peers per list. A room can be bigger: each peer is sent the PEER_LIST_SIZE
|
|
1299
|
+
// nearest its own id (XOR, as the mesh measures), so every peer sees a
|
|
1300
|
+
// different slice and together they cover the whole room. The same lowest-id
|
|
1301
|
+
// slice for everyone left the rest of a 100-peer room undiscoverable.
|
|
1302
|
+
const PEER_LIST_SIZE = MAX_BATCH;
|
|
1303
|
+
// How many registrations are read to choose from.
|
|
1304
|
+
const PEER_SCAN_LIMIT = 1000;
|
|
1305
|
+
|
|
1306
|
+
// Each id's first 64 bits as a number, cached: comparing by XOR on these is
|
|
1307
|
+
// enough to order peers and costs a fraction of comparing hex digit by digit.
|
|
1308
|
+
const idKeys = new Map();
|
|
1309
|
+
function idKey(id) {
|
|
1310
|
+
let key = idKeys.get(id);
|
|
1311
|
+
if (key === undefined) {
|
|
1312
|
+
const hex = String(id).toLowerCase().slice(0, 16);
|
|
1313
|
+
key = /^[0-9a-f]{16}$/.test(hex) ? BigInt(`0x${hex}`) : null;
|
|
1314
|
+
if (idKeys.size > 20_000) idKeys.clear();
|
|
1315
|
+
idKeys.set(id, key);
|
|
1316
|
+
}
|
|
1317
|
+
return key;
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
export function peersNearest(peers, forPeerId, limit = PEER_LIST_SIZE) {
|
|
1321
|
+
if (!Array.isArray(peers)) return [];
|
|
1322
|
+
if (peers.length <= limit) return peers;
|
|
1323
|
+
// Peers with a role (a storage server, say) come first, nearest first: a
|
|
1324
|
+
// scope where many plain peers look for a few such peers must not cut them
|
|
1325
|
+
// from the list. Then the rest, nearest first, as before.
|
|
1326
|
+
if (peers.some((p) => p?.role)) {
|
|
1327
|
+
const withRole = peers.filter((p) => p?.role), rest = peers.filter((p) => !p?.role);
|
|
1328
|
+
const first = nearestOf(withRole, forPeerId, limit);
|
|
1329
|
+
return first.length >= limit ? first : [...first, ...nearestOf(rest, forPeerId, limit - first.length)];
|
|
1330
|
+
}
|
|
1331
|
+
return nearestOf(peers, forPeerId, limit);
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
function nearestOf(peers, forPeerId, limit) {
|
|
1335
|
+
if (peers.length <= limit) return peers;
|
|
1336
|
+
if (!forPeerId) return peers.slice(0, limit);
|
|
1337
|
+
const target = idKey(forPeerId);
|
|
1338
|
+
if (target === null) return peers.slice(0, limit);
|
|
1339
|
+
const scored = [];
|
|
1340
|
+
for (const peer of peers) {
|
|
1341
|
+
if (peer?.peer_id === forPeerId) continue;
|
|
1342
|
+
const key = idKey(peer?.peer_id);
|
|
1343
|
+
scored.push({ peer, distance: key === null ? (1n << 64n) : key ^ target });
|
|
1344
|
+
}
|
|
1345
|
+
scored.sort((a, b) => (a.distance < b.distance ? -1 : a.distance > b.distance ? 1 : 0));
|
|
1346
|
+
return scored.slice(0, limit).map((entry) => entry.peer);
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
// Which peer each subscribed socket belongs to, so a room-wide list can be
|
|
1350
|
+
// cut for each.
|
|
1351
|
+
const socketPeerIds = new WeakMap();
|
|
1352
|
+
|
|
1353
|
+
function sendPeerList(socket, network, room, peers, to = null, from = relayPeerIdFor(null)) {
|
|
1354
|
+
peers = peersNearest(peers, to ?? socketPeerIds.get(socket) ?? null);
|
|
295
1355
|
socket.send(JSON.stringify({
|
|
296
1356
|
psp_version: PSP_VERSION,
|
|
297
1357
|
type: "peer_list",
|
|
298
1358
|
network,
|
|
1359
|
+
session_id: room,
|
|
299
1360
|
from,
|
|
300
1361
|
to,
|
|
301
1362
|
message_id: crypto.randomUUID(),
|
|
@@ -305,28 +1366,56 @@ function sendPeerList(socket, network, peers, to = null, from = "bootstrap-relay
|
|
|
305
1366
|
}));
|
|
306
1367
|
}
|
|
307
1368
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
1369
|
+
function createRegistrationAck(message, relayPeerId = relayPeerIdFor(null)) {
|
|
1370
|
+
return {
|
|
1371
|
+
psp_version: PSP_VERSION,
|
|
1372
|
+
type: "ack",
|
|
1373
|
+
network: message.network,
|
|
1374
|
+
session_id: normalizeRoom(message.session_id),
|
|
1375
|
+
from: relayPeerId,
|
|
1376
|
+
to: message.from,
|
|
1377
|
+
message_id: crypto.randomUUID(),
|
|
1378
|
+
reply_to: message.message_id,
|
|
1379
|
+
timestamp: Date.now(),
|
|
1380
|
+
ttl_ms: DEFAULT_TTL_MS,
|
|
1381
|
+
body: { status: "ok", action: "announce" }
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
// Broadcast only to peers in the same Network + Room scope.
|
|
1386
|
+
// The list pushed to every subscriber after a join or a leave is the same
|
|
1387
|
+
// federated view a discover reply carries. It used to be this relay's own
|
|
1388
|
+
// rows alone, and a client that treats every peer_list as the whole room
|
|
1389
|
+
// dropped its dials to every peer registered elsewhere each time one landed.
|
|
1390
|
+
async function broadcastPeerList(env, selfRelayUrl, network, room, relayPeerId, {
|
|
1391
|
+
federatedPeers = null,
|
|
1392
|
+
subscribers = networkSubscribers,
|
|
1393
|
+
} = {}) {
|
|
1394
|
+
const db = env?.DB;
|
|
1395
|
+
if (!db) return;
|
|
1396
|
+
const storageScope = scopeKey(network, room);
|
|
1397
|
+
const sockets = subscribers.get(storageScope);
|
|
311
1398
|
if (!sockets || sockets.size === 0) return;
|
|
1399
|
+
await ensureRoleColumn(db);
|
|
312
1400
|
|
|
313
1401
|
const now = Date.now();
|
|
314
1402
|
const result = await db.prepare(`
|
|
315
|
-
SELECT peer_id, session_id, updated_at_ms
|
|
1403
|
+
SELECT peer_id, session_id, updated_at_ms, role
|
|
316
1404
|
FROM psp_announcements
|
|
317
1405
|
WHERE network = ?1 AND expires_at_ms > ?2
|
|
318
1406
|
ORDER BY peer_id ASC
|
|
319
1407
|
LIMIT ?3
|
|
320
|
-
`).bind(
|
|
1408
|
+
`).bind(storageScope, now, PEER_SCAN_LIMIT).all();
|
|
321
1409
|
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
}
|
|
1410
|
+
const localPeers = (result.results || []).map(peerRow);
|
|
1411
|
+
let remotePeers = Array.isArray(federatedPeers) ? federatedPeers : null;
|
|
1412
|
+
if (remotePeers === null && selfRelayUrl && isKademliaEnabled(env)) {
|
|
1413
|
+
remotePeers = await findFederatedPeers(env, selfRelayUrl, network, room, "", livePeers.size).catch(() => []);
|
|
1414
|
+
}
|
|
1415
|
+
const peers = mergeDiscoveredPeers(localPeers, remotePeers ?? []);
|
|
327
1416
|
for (const socket of sockets) {
|
|
328
1417
|
try {
|
|
329
|
-
sendPeerList(socket, network, peers);
|
|
1418
|
+
sendPeerList(socket, network, room, peers, null, relayPeerId);
|
|
330
1419
|
} catch (e) {
|
|
331
1420
|
sockets.delete(socket);
|
|
332
1421
|
}
|
|
@@ -335,41 +1424,93 @@ async function broadcastPeerList(db, network) {
|
|
|
335
1424
|
|
|
336
1425
|
// ===================== D1 Database Functions =====================
|
|
337
1426
|
|
|
338
|
-
|
|
1427
|
+
/**
|
|
1428
|
+
* Record that a peer is here. A client re-announces every 12 s to keep a 30 s lease, and each
|
|
1429
|
+
* unconditional rewrite is a row (and its index entries) for a lease that was nowhere near its
|
|
1430
|
+
* end. An existing announcement is rewritten only when its session changed or it has less than
|
|
1431
|
+
* half its lease left, so a live peer is renewed well before it lapses at a fraction of the
|
|
1432
|
+
* writes, and a peer that is gone still ages out on the lease it was given.
|
|
1433
|
+
*/
|
|
1434
|
+
// The role column (migration 0003) on a database that has not run that
|
|
1435
|
+
// migration yet: a relay deployed without applying migrations (a linked
|
|
1436
|
+
// GitHub build runs no D1 migration) adds the column itself, once, before it
|
|
1437
|
+
// first reads or writes a role. Another isolate adding it first is fine.
|
|
1438
|
+
const roleColumnReady = new WeakMap();
|
|
1439
|
+
export function ensureRoleColumn(db) {
|
|
1440
|
+
if (!db || typeof db !== "object") return Promise.resolve();
|
|
1441
|
+
let ready = roleColumnReady.get(db);
|
|
1442
|
+
if (!ready) {
|
|
1443
|
+
ready = (async () => {
|
|
1444
|
+
try {
|
|
1445
|
+
await db.prepare("SELECT role FROM psp_announcements LIMIT 0").bind().all();
|
|
1446
|
+
} catch {
|
|
1447
|
+
try {
|
|
1448
|
+
await db.prepare("ALTER TABLE psp_announcements ADD COLUMN role TEXT").bind().run();
|
|
1449
|
+
} catch (error) {
|
|
1450
|
+
if (!/duplicate column/i.test(String(error?.message || error))) { roleColumnReady.delete(db); throw error; }
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
})();
|
|
1454
|
+
roleColumnReady.set(db, ready);
|
|
1455
|
+
}
|
|
1456
|
+
return ready;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
// What the peer says it is (capabilities.role): a short lowercase word, or none.
|
|
1460
|
+
export function announcedRole(message) {
|
|
1461
|
+
const role = message?.body?.capabilities?.role;
|
|
1462
|
+
return typeof role === "string" && /^[a-z0-9][a-z0-9-]{0,31}$/.test(role) ? role : null;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
export async function upsertAnnouncement(db, message) {
|
|
1466
|
+
await ensureRoleColumn(db);
|
|
339
1467
|
const now = Date.now();
|
|
340
1468
|
const ttl = Math.min(message.ttl_ms || DEFAULT_TTL_MS, MAX_TTL_MS);
|
|
341
1469
|
const expiresAt = now + ttl;
|
|
342
1470
|
|
|
343
1471
|
await db.prepare(`
|
|
344
|
-
INSERT INTO psp_announcements (network, peer_id, session_id, expires_at_ms, updated_at_ms)
|
|
345
|
-
VALUES (?1, ?2, ?3, ?4, ?5)
|
|
1472
|
+
INSERT INTO psp_announcements (network, peer_id, session_id, expires_at_ms, updated_at_ms, role)
|
|
1473
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
|
346
1474
|
ON CONFLICT(network, peer_id) DO UPDATE SET
|
|
347
1475
|
session_id = excluded.session_id,
|
|
348
1476
|
expires_at_ms = excluded.expires_at_ms,
|
|
349
|
-
updated_at_ms = excluded.updated_at_ms
|
|
350
|
-
|
|
1477
|
+
updated_at_ms = excluded.updated_at_ms,
|
|
1478
|
+
role = excluded.role
|
|
1479
|
+
WHERE psp_announcements.session_id IS NOT excluded.session_id
|
|
1480
|
+
OR psp_announcements.role IS NOT excluded.role
|
|
1481
|
+
OR (psp_announcements.expires_at_ms - excluded.updated_at_ms) * 2
|
|
1482
|
+
<= (excluded.expires_at_ms - excluded.updated_at_ms)
|
|
1483
|
+
`).bind(scopeKey(message.network, normalizeRoom(message.session_id)), message.from, message.session_id, expiresAt, now, announcedRole(message)).run();
|
|
351
1484
|
}
|
|
352
1485
|
|
|
353
|
-
async function deleteAnnouncement(db, network, peerId) {
|
|
1486
|
+
async function deleteAnnouncement(db, network, room, peerId) {
|
|
354
1487
|
await db.prepare(`DELETE FROM psp_announcements WHERE network = ?1 AND peer_id = ?2`)
|
|
355
|
-
.bind(network, peerId).run();
|
|
1488
|
+
.bind(scopeKey(network, room), peerId).run();
|
|
356
1489
|
}
|
|
357
1490
|
|
|
358
|
-
async function findPeers(db, network, requesterPeerId) {
|
|
1491
|
+
async function findPeers(db, network, room, requesterPeerId) {
|
|
1492
|
+
await ensureRoleColumn(db);
|
|
359
1493
|
const now = Date.now();
|
|
1494
|
+
const storageScope = scopeKey(network, room);
|
|
360
1495
|
const result = await db.prepare(`
|
|
361
|
-
SELECT peer_id, session_id, updated_at_ms
|
|
1496
|
+
SELECT peer_id, session_id, updated_at_ms, role
|
|
362
1497
|
FROM psp_announcements
|
|
363
1498
|
WHERE network = ?1 AND peer_id != ?2 AND expires_at_ms > ?3
|
|
364
1499
|
ORDER BY peer_id ASC
|
|
365
1500
|
LIMIT ?4
|
|
366
|
-
`).bind(
|
|
1501
|
+
`).bind(storageScope, requesterPeerId, now, PEER_SCAN_LIMIT).all();
|
|
367
1502
|
|
|
368
|
-
return (result.results || []).map(
|
|
1503
|
+
return (result.results || []).map(peerRow);
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
// A listed peer: its id, room and when it last announced, and its role if it has one.
|
|
1507
|
+
function peerRow(row) {
|
|
1508
|
+
return {
|
|
369
1509
|
peer_id: row.peer_id,
|
|
370
1510
|
session_id: row.session_id,
|
|
371
|
-
timestamp: row.updated_at_ms
|
|
372
|
-
|
|
1511
|
+
timestamp: row.updated_at_ms,
|
|
1512
|
+
...(row.role ? { role: row.role } : {}),
|
|
1513
|
+
};
|
|
373
1514
|
}
|
|
374
1515
|
|
|
375
1516
|
async function insertRelayMessage(db, message) {
|
|
@@ -381,7 +1522,7 @@ async function insertRelayMessage(db, message) {
|
|
|
381
1522
|
INSERT INTO psp_relay (network, to_peer_id, type, session_id, message_json, expires_at_ms, created_at_ms)
|
|
382
1523
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
|
|
383
1524
|
`).bind(
|
|
384
|
-
message.network,
|
|
1525
|
+
scopeKey(message.network, normalizeRoom(message.session_id)),
|
|
385
1526
|
message.to,
|
|
386
1527
|
message.type,
|
|
387
1528
|
message.session_id || null,
|
|
@@ -391,7 +1532,7 @@ async function insertRelayMessage(db, message) {
|
|
|
391
1532
|
).run();
|
|
392
1533
|
}
|
|
393
1534
|
|
|
394
|
-
async function fetchRelayMessages(db, network, toPeerId) {
|
|
1535
|
+
async function fetchRelayMessages(db, network, room, toPeerId) {
|
|
395
1536
|
const now = Date.now();
|
|
396
1537
|
const result = await db.prepare(`
|
|
397
1538
|
SELECT id, message_json
|
|
@@ -399,7 +1540,7 @@ async function fetchRelayMessages(db, network, toPeerId) {
|
|
|
399
1540
|
WHERE network = ?1 AND to_peer_id = ?2 AND expires_at_ms > ?3
|
|
400
1541
|
ORDER BY created_at_ms ASC
|
|
401
1542
|
LIMIT ?4
|
|
402
|
-
`).bind(network, toPeerId, now, MAX_BATCH).all();
|
|
1543
|
+
`).bind(scopeKey(network, room), toPeerId, now, MAX_BATCH).all();
|
|
403
1544
|
|
|
404
1545
|
return (result.results || []).map(row => ({
|
|
405
1546
|
id: row.id,
|
|
@@ -407,13 +1548,13 @@ async function fetchRelayMessages(db, network, toPeerId) {
|
|
|
407
1548
|
}));
|
|
408
1549
|
}
|
|
409
1550
|
|
|
410
|
-
async function deliverQueuedRelayMessages(db, socket, network, peerId) {
|
|
1551
|
+
async function deliverQueuedRelayMessages(db, socket, network, room, peerId) {
|
|
411
1552
|
if (!db) return 0;
|
|
412
1553
|
|
|
413
|
-
const queued = await fetchRelayMessages(db, network, peerId);
|
|
1554
|
+
const queued = await fetchRelayMessages(db, network, room, peerId);
|
|
414
1555
|
if (queued.length === 0) return 0;
|
|
415
1556
|
|
|
416
|
-
|
|
1557
|
+
relayLog('held messages handed to reconnecting peers', `[OUT] Delivering ${queued.length} queued messages to ${peerId}`);
|
|
417
1558
|
const deliveredIds = [];
|
|
418
1559
|
for (const { id, message: queuedMsg } of queued) {
|
|
419
1560
|
try {
|
|
@@ -442,49 +1583,67 @@ async function cleanupExpired(db) {
|
|
|
442
1583
|
const now = Date.now();
|
|
443
1584
|
await db.prepare(`DELETE FROM psp_announcements WHERE expires_at_ms <= ?1`).bind(now).run();
|
|
444
1585
|
await db.prepare(`DELETE FROM psp_relay WHERE expires_at_ms <= ?1`).bind(now).run();
|
|
1586
|
+
await db.prepare(`DELETE FROM psp_kad_nodes WHERE expires_at_ms <= ?1`).bind(now).run();
|
|
1587
|
+
await db.prepare(`DELETE FROM psp_kad_records WHERE expires_at_ms <= ?1`).bind(now).run();
|
|
445
1588
|
}
|
|
446
1589
|
|
|
447
1590
|
// ===================== WebSocket Handler =====================
|
|
448
1591
|
|
|
449
|
-
function handleWebSocket(request, env, ctx) {
|
|
1592
|
+
function handleWebSocket(request, env, ctx, selfRelayUrl) {
|
|
450
1593
|
const { 0: client, 1: server } = new WebSocketPair();
|
|
1594
|
+
const relayPeerId = resolveRelayPeerId(selfRelayUrl);
|
|
1595
|
+
const socketGeneration = ++nextSocketGeneration;
|
|
451
1596
|
|
|
452
1597
|
let peerKey = null;
|
|
453
1598
|
let network = null;
|
|
1599
|
+
let room = null;
|
|
454
1600
|
let peerId = null;
|
|
455
1601
|
|
|
456
1602
|
function cleanupPeerState() {
|
|
457
1603
|
const currentNetwork = network;
|
|
1604
|
+
const currentRoom = room;
|
|
458
1605
|
|
|
459
|
-
if (!network || !peerId) {
|
|
460
|
-
return currentNetwork;
|
|
1606
|
+
if (!network || !room || !peerId) {
|
|
1607
|
+
return currentNetwork && currentRoom ? scopeKey(currentNetwork, currentRoom) : null;
|
|
461
1608
|
}
|
|
462
1609
|
|
|
463
1610
|
const currentPeerId = peerId;
|
|
464
|
-
const key =
|
|
1611
|
+
const key = peerScopeKey(currentNetwork, currentRoom, currentPeerId);
|
|
1612
|
+
const subscriberScope = scopeKey(currentNetwork, currentRoom);
|
|
465
1613
|
|
|
466
|
-
livePeers
|
|
1614
|
+
const releasedLivePeer = deleteLivePeerIfOwned(livePeers, key, server);
|
|
467
1615
|
peerKey = null;
|
|
468
1616
|
peerId = null;
|
|
469
1617
|
network = null;
|
|
1618
|
+
room = null;
|
|
470
1619
|
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
);
|
|
1620
|
+
// A replaced socket can close after its successor has already announced.
|
|
1621
|
+
// Only the socket that still owns this peer ID may delete the shared lease.
|
|
1622
|
+
if (env.DB && releasedLivePeer) {
|
|
1623
|
+
deferWork(ctx, env, { kind: "peer-left", network: currentNetwork, room: currentRoom, peerId: currentPeerId, selfRelayUrl })
|
|
1624
|
+
.catch(() => {});
|
|
477
1625
|
}
|
|
478
1626
|
|
|
479
|
-
return
|
|
1627
|
+
return subscriberScope;
|
|
480
1628
|
}
|
|
481
1629
|
|
|
482
1630
|
server.addEventListener("message", async (event) => {
|
|
483
1631
|
try {
|
|
484
|
-
const result = await handleClientMessage(
|
|
1632
|
+
const result = await handleClientMessage(
|
|
1633
|
+
server,
|
|
1634
|
+
event.data,
|
|
1635
|
+
env,
|
|
1636
|
+
ctx,
|
|
1637
|
+
selfRelayUrl,
|
|
1638
|
+
socketGeneration,
|
|
1639
|
+
peerKey,
|
|
1640
|
+
network,
|
|
1641
|
+
room
|
|
1642
|
+
);
|
|
485
1643
|
if (result) {
|
|
486
1644
|
peerKey = result.peerKey;
|
|
487
1645
|
network = result.network;
|
|
1646
|
+
room = result.room;
|
|
488
1647
|
peerId = result.peerId;
|
|
489
1648
|
}
|
|
490
1649
|
} catch (err) {
|
|
@@ -492,7 +1651,7 @@ function handleWebSocket(request, env, ctx) {
|
|
|
492
1651
|
try {
|
|
493
1652
|
server.send(JSON.stringify({
|
|
494
1653
|
psp_version: PSP_VERSION, type: "error",
|
|
495
|
-
from:
|
|
1654
|
+
from: relayPeerId, to: "client",
|
|
496
1655
|
body: { error: err?.message || "Unknown error" }
|
|
497
1656
|
}));
|
|
498
1657
|
} catch {}
|
|
@@ -500,9 +1659,9 @@ function handleWebSocket(request, env, ctx) {
|
|
|
500
1659
|
});
|
|
501
1660
|
|
|
502
1661
|
server.addEventListener("close", () => {
|
|
503
|
-
const
|
|
504
|
-
if (
|
|
505
|
-
const sockets = networkSubscribers.get(
|
|
1662
|
+
const subscriberScope = cleanupPeerState();
|
|
1663
|
+
if (subscriberScope) {
|
|
1664
|
+
const sockets = networkSubscribers.get(subscriberScope);
|
|
506
1665
|
if (sockets) {
|
|
507
1666
|
sockets.delete(server);
|
|
508
1667
|
}
|
|
@@ -510,9 +1669,9 @@ function handleWebSocket(request, env, ctx) {
|
|
|
510
1669
|
});
|
|
511
1670
|
|
|
512
1671
|
server.addEventListener("error", () => {
|
|
513
|
-
const
|
|
514
|
-
if (
|
|
515
|
-
const sockets = networkSubscribers.get(
|
|
1672
|
+
const subscriberScope = cleanupPeerState();
|
|
1673
|
+
if (subscriberScope) {
|
|
1674
|
+
const sockets = networkSubscribers.get(subscriberScope);
|
|
516
1675
|
if (sockets) {
|
|
517
1676
|
sockets.delete(server);
|
|
518
1677
|
}
|
|
@@ -524,8 +1683,19 @@ function handleWebSocket(request, env, ctx) {
|
|
|
524
1683
|
return new Response(null, { status: 101, webSocket: client });
|
|
525
1684
|
}
|
|
526
1685
|
|
|
527
|
-
async function handleClientMessage(
|
|
1686
|
+
async function handleClientMessage(
|
|
1687
|
+
socket,
|
|
1688
|
+
rawData,
|
|
1689
|
+
env,
|
|
1690
|
+
ctx,
|
|
1691
|
+
selfRelayUrl,
|
|
1692
|
+
socketGeneration,
|
|
1693
|
+
prevPeerKey = null,
|
|
1694
|
+
prevNetwork = null,
|
|
1695
|
+
prevRoom = null
|
|
1696
|
+
) {
|
|
528
1697
|
try {
|
|
1698
|
+
const relayPeerId = resolveRelayPeerId(selfRelayUrl);
|
|
529
1699
|
if (!rawData) return null;
|
|
530
1700
|
if (rawData.length > MAX_MESSAGE_SIZE) return null;
|
|
531
1701
|
|
|
@@ -535,7 +1705,7 @@ async function handleClientMessage(socket, rawData, env, ctx, prevPeerKey = null
|
|
|
535
1705
|
} catch (e) {
|
|
536
1706
|
socket.send(JSON.stringify({
|
|
537
1707
|
psp_version: PSP_VERSION, type: "error",
|
|
538
|
-
from:
|
|
1708
|
+
from: relayPeerId, to: "client",
|
|
539
1709
|
body: { error: "Invalid JSON" }
|
|
540
1710
|
}));
|
|
541
1711
|
return null;
|
|
@@ -544,183 +1714,215 @@ async function handleClientMessage(socket, rawData, env, ctx, prevPeerKey = null
|
|
|
544
1714
|
if (!validEnvelope(message)) {
|
|
545
1715
|
socket.send(JSON.stringify({
|
|
546
1716
|
psp_version: PSP_VERSION, type: "error",
|
|
547
|
-
from:
|
|
1717
|
+
from: relayPeerId, to: message?.from || "unknown",
|
|
548
1718
|
body: { error: "Invalid PSP envelope" }
|
|
549
1719
|
}));
|
|
550
1720
|
return null;
|
|
551
1721
|
}
|
|
552
1722
|
|
|
553
1723
|
const { network, from: peerId, type } = message;
|
|
1724
|
+
const room = normalizeRoom(message.session_id);
|
|
554
1725
|
const db = env.DB;
|
|
555
|
-
const peerKey =
|
|
1726
|
+
const peerKey = peerScopeKey(network, room, peerId);
|
|
1727
|
+
const subscriberScope = scopeKey(network, room);
|
|
1728
|
+
|
|
1729
|
+
if (type === "announce" && message.body?.instance_id !== network) {
|
|
1730
|
+
socket.send(JSON.stringify({
|
|
1731
|
+
psp_version: PSP_VERSION,
|
|
1732
|
+
type: "error",
|
|
1733
|
+
network,
|
|
1734
|
+
session_id: room,
|
|
1735
|
+
from: relayPeerId,
|
|
1736
|
+
to: peerId,
|
|
1737
|
+
message_id: crypto.randomUUID(),
|
|
1738
|
+
timestamp: Date.now(),
|
|
1739
|
+
ttl_ms: DEFAULT_TTL_MS,
|
|
1740
|
+
body: { error: "instance_id must match network" }
|
|
1741
|
+
}));
|
|
1742
|
+
return null;
|
|
1743
|
+
}
|
|
556
1744
|
|
|
557
|
-
// Never relay or process peer-to-peer negotiation from a peer to itself.
|
|
558
1745
|
if (message.to && message.to === peerId && RELAY_TYPES.has(type)) {
|
|
559
|
-
return { peerKey, network, peerId };
|
|
1746
|
+
return { peerKey, network, room, peerId };
|
|
560
1747
|
}
|
|
561
1748
|
|
|
562
|
-
// Subscribe to
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
1749
|
+
// Subscribe to the exact Network + Room scope. A domain is only a relay;
|
|
1750
|
+
// domain boundaries do not replace application scope boundaries.
|
|
1751
|
+
if (!prevPeerKey || prevNetwork !== network || prevRoom !== room) {
|
|
1752
|
+
if (prevNetwork && prevRoom && (prevNetwork !== network || prevRoom !== room)) {
|
|
1753
|
+
const oldSockets = networkSubscribers.get(scopeKey(prevNetwork, prevRoom));
|
|
566
1754
|
if (oldSockets) {
|
|
567
1755
|
oldSockets.delete(socket);
|
|
568
1756
|
}
|
|
569
1757
|
}
|
|
570
|
-
if (!networkSubscribers.has(
|
|
571
|
-
networkSubscribers.set(
|
|
1758
|
+
if (!networkSubscribers.has(subscriberScope)) {
|
|
1759
|
+
networkSubscribers.set(subscriberScope, new Set());
|
|
572
1760
|
}
|
|
573
|
-
networkSubscribers.get(
|
|
574
|
-
|
|
1761
|
+
networkSubscribers.get(subscriberScope).add(socket);
|
|
1762
|
+
socketPeerIds.set(socket, peerId);
|
|
1763
|
+
relayLog('peers subscribed', `[NET] Peer ${peerId} subscribed to network=${network} room=${room}`);
|
|
575
1764
|
}
|
|
576
1765
|
|
|
577
|
-
//
|
|
578
|
-
|
|
1766
|
+
// Reconnects reuse a peer ID. A late ping/close from the replaced socket
|
|
1767
|
+
// must never reclaim or remove the newer socket's live route.
|
|
1768
|
+
const ownsLivePeer = claimLivePeer(livePeers, peerKey, {
|
|
1769
|
+
peerId,
|
|
1770
|
+
network,
|
|
1771
|
+
room,
|
|
1772
|
+
socket,
|
|
1773
|
+
socketGeneration,
|
|
1774
|
+
lastSeen: Date.now(),
|
|
1775
|
+
});
|
|
1776
|
+
if (!ownsLivePeer) {
|
|
1777
|
+
try { socket.close(4001, "replaced_socket"); } catch {}
|
|
1778
|
+
return { peerKey, network, room, peerId };
|
|
1779
|
+
}
|
|
579
1780
|
|
|
580
1781
|
if (type === "announce") {
|
|
581
|
-
if (db) {
|
|
582
|
-
await upsertAnnouncement(db, message);
|
|
583
|
-
await deliverQueuedRelayMessages(db, socket, network, peerId);
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
// Only broadcast peer_list when the peer is newly joining, not on heartbeat re-announces.
|
|
587
|
-
// prevPeerKey === peerKey means same peer on the same socket sending a periodic keep-alive;
|
|
588
|
-
// no topology change occurred, so no need to push a new list to everyone.
|
|
589
1782
|
const isHeartbeat = prevPeerKey === peerKey;
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
1783
|
+
absentPeerUntilMs.delete(peerKey);
|
|
1784
|
+
relayIdlePeerUntilMs.delete(peerKey);
|
|
1785
|
+
|
|
1786
|
+
// Registration is complete only after the relay has accepted the
|
|
1787
|
+
// announcement. Clients use this ACK to begin discovery and signaling.
|
|
1788
|
+
socket.send(JSON.stringify(createRegistrationAck(
|
|
1789
|
+
message,
|
|
1790
|
+
relayPeerId
|
|
1791
|
+
)));
|
|
1792
|
+
|
|
1793
|
+
// The registry write, queued deliveries, provider publication and the
|
|
1794
|
+
// joining peer's discovery all leave the runtime; they run on the
|
|
1795
|
+
// coordinator's alarm, never on this socket's request.
|
|
1796
|
+
await deferWork(ctx, env, { kind: "announce", network, room, peerId, selfRelayUrl, message, isHeartbeat });
|
|
594
1797
|
|
|
595
1798
|
} else if (type === "withdraw") {
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
1799
|
+
// A peer that lets go of the relay because its mesh is healthy (relay on
|
|
1800
|
+
// demand) is still in the room: messages for it are held, not dropped.
|
|
1801
|
+
if (message.body?.reason === "relay_idle") noteRelayIdlePeer(peerKey);
|
|
1802
|
+
// Any other withdraw is a goodbye (closed tab, Ctrl-C, reload): the peer
|
|
1803
|
+
// has left, and what is still sent to it is dropped (see "forward").
|
|
1804
|
+
else noteAbsentPeer(peerKey);
|
|
1805
|
+
const releasedLivePeer = deleteLivePeerIfOwned(livePeers, peerKey, socket);
|
|
1806
|
+
if (db && releasedLivePeer) {
|
|
1807
|
+
await deferWork(ctx, env, { kind: "peer-left", network, room, peerId, selfRelayUrl });
|
|
602
1808
|
}
|
|
603
1809
|
|
|
604
1810
|
} else if (type === "discover") {
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
);
|
|
620
|
-
remotePeers = results.flat();
|
|
1811
|
+
await deferWork(ctx, env, { kind: "discover", network, room, peerId, selfRelayUrl });
|
|
1812
|
+
|
|
1813
|
+
} else if (type === "ext" && message.body?.relay_request === true) {
|
|
1814
|
+
// A request to this relay itself (not to a peer), answered on the same
|
|
1815
|
+
// socket. A node relay can serve such requests through
|
|
1816
|
+
// env.RELAY_REQUEST_HANDLER (body) -> result | null, such as the
|
|
1817
|
+
// PigeonIdP account store; a relay without one, or one the handler does
|
|
1818
|
+
// not know, answers unsupported so the client does not wait it out.
|
|
1819
|
+
let result = null;
|
|
1820
|
+
if (typeof env.RELAY_REQUEST_HANDLER === "function") {
|
|
1821
|
+
try {
|
|
1822
|
+
result = await env.RELAY_REQUEST_HANDLER({ ...message.body, from_relay: false }, { peerId, network, room });
|
|
1823
|
+
} catch (error) {
|
|
1824
|
+
result = { ok: false, error: String(error?.message || error).slice(0, 200) };
|
|
621
1825
|
}
|
|
622
1826
|
}
|
|
623
|
-
|
|
624
1827
|
try {
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
1828
|
+
socket.send(JSON.stringify({
|
|
1829
|
+
psp_version: PSP_VERSION, type: "ext", network,
|
|
1830
|
+
session_id: room,
|
|
1831
|
+
from: relayPeerId, to: peerId,
|
|
1832
|
+
message_id: crypto.randomUUID(), timestamp: Date.now(),
|
|
1833
|
+
ttl_ms: DEFAULT_TTL_MS, reply_to: message.message_id ?? null,
|
|
1834
|
+
body: { ...(result ?? { ok: false, error: "unsupported" }), relay_response: true, request_id: message.body.request_id ?? null },
|
|
1835
|
+
}));
|
|
1836
|
+
} catch { /* the socket went away */ }
|
|
633
1837
|
|
|
634
1838
|
} else if (type === "ext" && message.body?.action === "relay_list") {
|
|
635
1839
|
// Remote relay is sharing its known relay list — cache any new entries
|
|
636
1840
|
if (db) {
|
|
637
|
-
|
|
638
|
-
await Promise.all(
|
|
639
|
-
remoteRelays
|
|
640
|
-
.filter(r => r.url)
|
|
641
|
-
.map(r => upsertRelay(db, r.url, r.name || null).catch(() => {}))
|
|
642
|
-
);
|
|
1841
|
+
await deferWork(ctx, env, { kind: "relay-list", network, room, peerId, selfRelayUrl, relays: message.body.relays || [] });
|
|
643
1842
|
}
|
|
644
1843
|
|
|
645
1844
|
} else if (type === "ping") {
|
|
646
1845
|
socket.send(JSON.stringify({
|
|
647
1846
|
psp_version: PSP_VERSION, type: "pong", network,
|
|
648
|
-
|
|
1847
|
+
session_id: room,
|
|
1848
|
+
from: relayPeerId, to: peerId,
|
|
649
1849
|
message_id: crypto.randomUUID(), timestamp: Date.now(),
|
|
650
1850
|
ttl_ms: DEFAULT_TTL_MS, body: {}
|
|
651
1851
|
}));
|
|
652
|
-
if (db) {
|
|
653
|
-
await
|
|
1852
|
+
if (db && pingDrainsQueuedMessages(ctx)) {
|
|
1853
|
+
await deferWork(ctx, env, { kind: "deliver-queued", network, room, peerId, selfRelayUrl });
|
|
654
1854
|
}
|
|
655
1855
|
|
|
656
1856
|
} else if (type === "bye") {
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
livePeers.delete(peerKey);
|
|
661
|
-
if (db) {
|
|
662
|
-
broadcastPeerList(db, network).catch(() => {});
|
|
1857
|
+
const releasedLivePeer = deleteLivePeerIfOwned(livePeers, peerKey, socket);
|
|
1858
|
+
if (db && releasedLivePeer) {
|
|
1859
|
+
await deferWork(ctx, env, { kind: "peer-left", network, room, peerId, selfRelayUrl });
|
|
663
1860
|
}
|
|
664
1861
|
|
|
665
1862
|
} else if (RELAY_TYPES.has(type)) {
|
|
666
1863
|
// RTC negotiation messages - relay immediately if online, queue if offline
|
|
667
|
-
if (!message.to) return { peerKey, network, peerId };
|
|
668
|
-
if (message.to === peerId) return { peerKey, network, peerId };
|
|
1864
|
+
if (!message.to) return { peerKey, network, room, peerId };
|
|
1865
|
+
if (message.to === peerId) return { peerKey, network, room, peerId };
|
|
669
1866
|
|
|
670
1867
|
// Try immediate delivery to live peer
|
|
671
|
-
const liveKey =
|
|
1868
|
+
const liveKey = peerScopeKey(network, room, message.to);
|
|
672
1869
|
const live = livePeers.get(liveKey);
|
|
673
1870
|
let deliveredLive = false;
|
|
674
1871
|
if (live) {
|
|
675
1872
|
try {
|
|
676
1873
|
live.socket.send(rawData);
|
|
677
1874
|
deliveredLive = true;
|
|
678
|
-
|
|
1875
|
+
relayLog('messages delivered', `[RELAY] Delivered ${type} from ${peerId} to ${message.to} immediately`);
|
|
679
1876
|
} catch (err) {
|
|
680
|
-
|
|
1877
|
+
relayLog("deliveries to peers whose connection had just closed", `[RELAY] Failed to deliver to ${message.to}: ${err?.message}`);
|
|
681
1878
|
}
|
|
682
1879
|
}
|
|
683
1880
|
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
console.log(`[RELAY] Queued ${type} for ${message.to} after live delivery failure`);
|
|
690
|
-
}
|
|
691
|
-
} else if (!deliveredLive) {
|
|
692
|
-
console.warn(`[RELAY] Could not deliver ${type} to ${message.to}; persistence unavailable`);
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
// If still not delivered locally and federation is enabled, fan out to peer relays via WebSocket
|
|
696
|
-
if (!deliveredLive && env.RELAY_URL && env.DB) {
|
|
697
|
-
ctx.waitUntil((async () => {
|
|
698
|
-
const selfRelayId = env.RELAY_PEER_ID || "relay-bridge";
|
|
699
|
-
const selfUrl = normalizeRelayUrl(env.RELAY_URL);
|
|
700
|
-
const remoteUrls = await getPeerRelayUrls(env.DB, selfUrl);
|
|
701
|
-
if (!remoteUrls.length) return;
|
|
702
|
-
console.log(`[FED] Forwarding ${type} to ${remoteUrls.length} peer relay(s) for ${message.to}`);
|
|
703
|
-
await Promise.all(remoteUrls.map(u => forwardToRelay(u, message, selfRelayId)));
|
|
704
|
-
})());
|
|
1881
|
+
// Not here: route it through the peer's relay. A learned route is tried
|
|
1882
|
+
// first, Kademlia is the fallback, and an unreachable peer's message is
|
|
1883
|
+
// queued — all on the coordinator's alarm, off this socket's request.
|
|
1884
|
+
if (!deliveredLive) {
|
|
1885
|
+
await deferWork(ctx, env, { kind: "forward", network, room, peerId, selfRelayUrl, message });
|
|
705
1886
|
}
|
|
706
1887
|
}
|
|
707
1888
|
|
|
708
|
-
|
|
709
|
-
|
|
1889
|
+
if (db && Date.now() - lastCleanupAt > CLEANUP_INTERVAL_MS) {
|
|
1890
|
+
lastCleanupAt = Date.now();
|
|
1891
|
+
await deferWork(ctx, env, { kind: "cleanup", network, room, peerId, selfRelayUrl });
|
|
1892
|
+
}
|
|
1893
|
+
return { peerKey, network, room, peerId };
|
|
710
1894
|
} catch (err) {
|
|
711
|
-
|
|
1895
|
+
const text = err?.message || String(err);
|
|
1896
|
+
// A message for a peer whose connection closed a moment ago (a peer
|
|
1897
|
+
// leaving, a test ending): counted, not printed once per message.
|
|
1898
|
+
if (/not open/i.test(text)) relayLog('messages to peers whose connection had just closed', `[Handler] ${text}`);
|
|
1899
|
+
else console.error("[Handler] Error:", text);
|
|
712
1900
|
return null;
|
|
713
1901
|
}
|
|
714
1902
|
}
|
|
715
1903
|
|
|
716
1904
|
function validEnvelope(msg) {
|
|
717
|
-
return (
|
|
1905
|
+
return Boolean(
|
|
718
1906
|
typeof msg === "object" && msg !== null &&
|
|
719
1907
|
msg.psp_version === PSP_VERSION &&
|
|
720
1908
|
typeof msg.type === "string" && MESSAGE_TYPES.has(msg.type) &&
|
|
721
1909
|
typeof msg.from === "string" && msg.from.trim() &&
|
|
722
1910
|
typeof msg.network === "string" && msg.network.trim() &&
|
|
1911
|
+
typeof msg.session_id === "string" && msg.session_id.trim() &&
|
|
723
1912
|
typeof msg.message_id === "string" &&
|
|
724
1913
|
typeof msg.timestamp === "number"
|
|
725
1914
|
);
|
|
726
1915
|
}
|
|
1916
|
+
|
|
1917
|
+
export {
|
|
1918
|
+
broadcastPeerList,
|
|
1919
|
+
createRegistrationAck,
|
|
1920
|
+
discoverJoiningPeer,
|
|
1921
|
+
listFederatedRelays,
|
|
1922
|
+
normalizeRoom,
|
|
1923
|
+
peerScopeKey,
|
|
1924
|
+
resolveRelayPeerId,
|
|
1925
|
+
resolveSelfRelayUrl,
|
|
1926
|
+
scopeKey,
|
|
1927
|
+
validEnvelope
|
|
1928
|
+
};
|