@johnhenry/browsermesh-pod 0.0.2 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +382 -1
- package/package.json +3 -3
- package/src/browser-host-child.mjs +109 -0
- package/src/browser-host-driver.mjs +445 -0
- package/src/detect-kind.mjs +9 -0
- package/src/host-protocol.mjs +1221 -0
- package/src/index.d.ts +274 -1
- package/src/index.mjs +15 -0
- package/src/transport.mjs +3 -1
- package/src/ws-transport.mjs +358 -0
package/src/index.d.ts
CHANGED
|
@@ -177,6 +177,33 @@ export declare class NullTransport implements TransportAdapter {
|
|
|
177
177
|
close(): Promise<void>;
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
+
export interface WebSocketTransportReconnectOptions {
|
|
181
|
+
baseMs?: number;
|
|
182
|
+
maxMs?: number;
|
|
183
|
+
maxAttempts?: number;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export interface WebSocketTransportOptions {
|
|
187
|
+
url: string;
|
|
188
|
+
podId: string;
|
|
189
|
+
WebSocket?: new (url: string) => any;
|
|
190
|
+
protocol?: "relay" | "signaling";
|
|
191
|
+
signalingUrl?: string;
|
|
192
|
+
peersFromSignaling?: boolean;
|
|
193
|
+
reconnect?: WebSocketTransportReconnectOptions;
|
|
194
|
+
onLog?: (msg: string) => void;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export declare class WebSocketTransport implements TransportAdapter {
|
|
198
|
+
constructor(opts: WebSocketTransportOptions);
|
|
199
|
+
get ready(): boolean;
|
|
200
|
+
get knownPeers(): Set<string>;
|
|
201
|
+
onMessage(handler: (msg: any) => void): void;
|
|
202
|
+
open(): Promise<void>;
|
|
203
|
+
send(msg: any): void;
|
|
204
|
+
close(): Promise<void>;
|
|
205
|
+
}
|
|
206
|
+
|
|
180
207
|
// ── Discovery adapters ────────────────────────────────────────────────────────
|
|
181
208
|
|
|
182
209
|
export interface PeerFoundInfo {
|
|
@@ -265,7 +292,7 @@ export declare class Pod {
|
|
|
265
292
|
get role(): PodRole;
|
|
266
293
|
get state(): PodState;
|
|
267
294
|
get peers(): Map<string, PeerInfo>;
|
|
268
|
-
get transport(): BroadcastChannelTransport | EventEmitterTransport | NullTransport | null;
|
|
295
|
+
get transport(): BroadcastChannelTransport | EventEmitterTransport | WebSocketTransport | NullTransport | null;
|
|
269
296
|
|
|
270
297
|
boot(opts?: PodBootOptions): Promise<void>;
|
|
271
298
|
shutdown(opts?: PodShutdownOptions): Promise<void>;
|
|
@@ -324,3 +351,249 @@ export declare function installPodRuntime(opts?: RuntimeOptions): Promise<Pod>;
|
|
|
324
351
|
export declare const createRuntime: typeof installPodRuntime;
|
|
325
352
|
export declare function createClient(opts?: RuntimeOptions): Promise<Pod>;
|
|
326
353
|
export declare function createServer(opts?: RuntimeOptions): Promise<Pod>;
|
|
354
|
+
|
|
355
|
+
// ── Pod host protocol (issue #185 control surface) ───────────────────────────
|
|
356
|
+
|
|
357
|
+
export type PodHostVerb =
|
|
358
|
+
| "spawn" | "status" | "send" | "exec"
|
|
359
|
+
| "snapshot" | "restore" | "drain" | "list";
|
|
360
|
+
|
|
361
|
+
export declare const POD_HOST_VERB: Readonly<{
|
|
362
|
+
SPAWN: "spawn"; STATUS: "status"; SEND: "send"; EXEC: "exec";
|
|
363
|
+
SNAPSHOT: "snapshot"; RESTORE: "restore"; DRAIN: "drain"; LIST: "list";
|
|
364
|
+
}>;
|
|
365
|
+
export declare const POD_HOST_VERBS: readonly PodHostVerb[];
|
|
366
|
+
|
|
367
|
+
export type PodLane = "isolate" | "microvm" | "node" | "browser";
|
|
368
|
+
|
|
369
|
+
export declare const POD_LANE: Readonly<{
|
|
370
|
+
ISOLATE: "isolate"; MICROVM: "microvm"; NODE: "node"; BROWSER: "browser";
|
|
371
|
+
}>;
|
|
372
|
+
export declare const POD_LANES: readonly PodLane[];
|
|
373
|
+
export declare const POD_LANE_VERBS: Readonly<Record<PodLane, readonly PodHostVerb[]>>;
|
|
374
|
+
export declare function laneSupports(lane: string, verb: string): boolean;
|
|
375
|
+
|
|
376
|
+
export type PodLifecycleState =
|
|
377
|
+
| "cold" | "booting" | "registered" | "serving"
|
|
378
|
+
| "paused" | "snapshotted" | "restoring" | "draining" | "gone";
|
|
379
|
+
|
|
380
|
+
export declare const POD_LIFECYCLE: Readonly<{
|
|
381
|
+
COLD: "cold"; BOOTING: "booting"; REGISTERED: "registered"; SERVING: "serving";
|
|
382
|
+
PAUSED: "paused"; SNAPSHOTTED: "snapshotted"; RESTORING: "restoring";
|
|
383
|
+
DRAINING: "draining"; GONE: "gone";
|
|
384
|
+
}>;
|
|
385
|
+
export declare const POD_LIFECYCLE_STATES: readonly PodLifecycleState[];
|
|
386
|
+
export declare const POD_LIFECYCLE_TRANSITIONS: Readonly<
|
|
387
|
+
Record<PodLifecycleState, readonly PodLifecycleState[]>
|
|
388
|
+
>;
|
|
389
|
+
export declare function canTransition(from: string, to: string): boolean;
|
|
390
|
+
|
|
391
|
+
export type PodHostErrorCode =
|
|
392
|
+
| "EACCES" | "ENOENT" | "EEXIST" | "EINVAL"
|
|
393
|
+
| "ENOTSUP" | "ELANE" | "ETIMEDOUT" | "EBUSY";
|
|
394
|
+
|
|
395
|
+
export declare const POD_HOST_ERROR: Readonly<Record<PodHostErrorCode, PodHostErrorCode>>;
|
|
396
|
+
|
|
397
|
+
export declare class PodHostDriverError extends Error {
|
|
398
|
+
constructor(code: PodHostErrorCode | string, message: string, details?: object | null);
|
|
399
|
+
code: string;
|
|
400
|
+
details: object | null;
|
|
401
|
+
toJSON(): { code: string; message: string };
|
|
402
|
+
static from(err: unknown): PodHostDriverError;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
export declare function createUnsupportedDriverMethod(
|
|
406
|
+
verb: string,
|
|
407
|
+
lane?: string,
|
|
408
|
+
opts?: { code?: string; message?: string },
|
|
409
|
+
): () => Promise<never>;
|
|
410
|
+
|
|
411
|
+
export interface PodSpecRun {
|
|
412
|
+
kind: "skill" | "module" | "rootfs" | "command";
|
|
413
|
+
ref: string;
|
|
414
|
+
entry?: string;
|
|
415
|
+
input?: unknown;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
export interface PodSpecLimits {
|
|
419
|
+
vcpus?: number;
|
|
420
|
+
memMib?: number;
|
|
421
|
+
timeoutMs?: number;
|
|
422
|
+
netRateLimiter?: Record<string, unknown>;
|
|
423
|
+
blockRateLimiter?: Record<string, unknown>;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
export interface PodSpecRestart {
|
|
427
|
+
policy: "never" | "on-failure" | "always";
|
|
428
|
+
maxRestarts?: number;
|
|
429
|
+
backoffMs?: number;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
export interface PodSpecLinks {
|
|
433
|
+
parent?: string;
|
|
434
|
+
hostedBy?: string;
|
|
435
|
+
detachOnParentExit?: boolean;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export interface PodSpec {
|
|
439
|
+
name: string;
|
|
440
|
+
lane?: PodLane;
|
|
441
|
+
run: PodSpecRun;
|
|
442
|
+
limits?: PodSpecLimits;
|
|
443
|
+
caps?: string[];
|
|
444
|
+
env?: Record<string, string>;
|
|
445
|
+
budget?: { credits: number; currency?: string };
|
|
446
|
+
restart?: Partial<PodSpecRestart>;
|
|
447
|
+
labels?: Record<string, string>;
|
|
448
|
+
links?: PodSpecLinks;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export interface NormalizedPodSpec extends PodSpec {
|
|
452
|
+
lane: PodLane;
|
|
453
|
+
restart: PodSpecRestart;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
export type ValidationResult<T> =
|
|
457
|
+
| { ok: true; value: T }
|
|
458
|
+
| { ok: false; errors: string[] };
|
|
459
|
+
|
|
460
|
+
export declare function validatePodSpec(spec: unknown): ValidationResult<NormalizedPodSpec>;
|
|
461
|
+
export declare function validateVerbRequest(
|
|
462
|
+
verb: string,
|
|
463
|
+
payload?: unknown,
|
|
464
|
+
): ValidationResult<Record<string, unknown>>;
|
|
465
|
+
|
|
466
|
+
export declare const POD_HOST_REQUEST: "pod-host:request";
|
|
467
|
+
export declare const POD_HOST_RESPONSE: "pod-host:response";
|
|
468
|
+
export declare const POD_HOST_EVENT: "pod-host:event";
|
|
469
|
+
export declare const POD_HOST_EVENT_KIND: Readonly<{
|
|
470
|
+
LIFECYCLE: "lifecycle"; LOG: "log"; EXIT: "exit";
|
|
471
|
+
}>;
|
|
472
|
+
|
|
473
|
+
export interface PodHostExitEventData {
|
|
474
|
+
name: string;
|
|
475
|
+
code?: number;
|
|
476
|
+
reason?: "drained" | "crashed" | "host-lost" | "evicted";
|
|
477
|
+
restartable: boolean;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
export interface PodHostRequestEnvelope {
|
|
481
|
+
type: "pod-host:request";
|
|
482
|
+
requestId: string;
|
|
483
|
+
verb: string;
|
|
484
|
+
payload: Record<string, unknown>;
|
|
485
|
+
ts: number;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export interface PodHostResponseEnvelope {
|
|
489
|
+
type: "pod-host:response";
|
|
490
|
+
requestId: string;
|
|
491
|
+
ok: boolean;
|
|
492
|
+
result: unknown;
|
|
493
|
+
error: { code: string; message: string } | null;
|
|
494
|
+
ts: number;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
export interface PodHostEventEnvelope {
|
|
498
|
+
type: "pod-host:event";
|
|
499
|
+
kind: string;
|
|
500
|
+
data: Record<string, unknown>;
|
|
501
|
+
ts: number;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export declare function createHostRequest(
|
|
505
|
+
verb: string,
|
|
506
|
+
payload?: Record<string, unknown>,
|
|
507
|
+
opts?: { requestId?: string },
|
|
508
|
+
): PodHostRequestEnvelope;
|
|
509
|
+
|
|
510
|
+
export declare function createHostResponse(
|
|
511
|
+
requestId: string,
|
|
512
|
+
opts: { ok: boolean; result?: unknown; error?: { code: string; message: string } },
|
|
513
|
+
): PodHostResponseEnvelope;
|
|
514
|
+
|
|
515
|
+
export declare function createHostEvent(
|
|
516
|
+
kind: string,
|
|
517
|
+
data?: Record<string, unknown>,
|
|
518
|
+
): PodHostEventEnvelope;
|
|
519
|
+
|
|
520
|
+
export interface PodHostStatus {
|
|
521
|
+
name: string;
|
|
522
|
+
lane: string;
|
|
523
|
+
state: PodLifecycleState;
|
|
524
|
+
createdAt: number;
|
|
525
|
+
updatedAt: number;
|
|
526
|
+
spec?: NormalizedPodSpec;
|
|
527
|
+
podId?: string | null;
|
|
528
|
+
inbox?: number;
|
|
529
|
+
execs?: number;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
export interface PodExecResult {
|
|
533
|
+
stdout: string;
|
|
534
|
+
stderr: string;
|
|
535
|
+
code: number;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export interface PodHostDriver {
|
|
539
|
+
lane: string;
|
|
540
|
+
capabilities(): { verbs: string[] };
|
|
541
|
+
spawn(spec: PodSpec): Promise<PodHostStatus>;
|
|
542
|
+
status(name: string): Promise<PodHostStatus>;
|
|
543
|
+
send(name: string, msg: { to?: string; payload: unknown }): Promise<object>;
|
|
544
|
+
exec(name: string, argv: string[], opts?: { timeoutMs?: number }): Promise<PodExecResult>;
|
|
545
|
+
snapshot(name: string): Promise<PodHostStatus>;
|
|
546
|
+
restore(name: string): Promise<PodHostStatus>;
|
|
547
|
+
drain(name: string, opts?: { cascade?: boolean }): Promise<PodHostStatus>;
|
|
548
|
+
list(): Promise<PodHostStatus[]>;
|
|
549
|
+
onEvent?(fn: (event: PodHostEventEnvelope) => void): () => void;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
export declare class InMemoryPodHostDriver implements PodHostDriver {
|
|
553
|
+
constructor(opts?: {
|
|
554
|
+
lane?: PodLane;
|
|
555
|
+
verbs?: string[];
|
|
556
|
+
exec?: (argv: string[], ctx: { name: string; timeoutMs?: number }) => Promise<PodExecResult>;
|
|
557
|
+
});
|
|
558
|
+
get lane(): string;
|
|
559
|
+
capabilities(): { verbs: string[] };
|
|
560
|
+
onEvent(fn: (event: PodHostEventEnvelope) => void): () => void;
|
|
561
|
+
spawn(spec: PodSpec): Promise<PodHostStatus>;
|
|
562
|
+
status(name: string): Promise<PodHostStatus>;
|
|
563
|
+
send(name: string, msg: { to?: string; payload: unknown }): Promise<{ delivered: boolean; inbox: number }>;
|
|
564
|
+
exec(name: string, argv: string[], opts?: { timeoutMs?: number }): Promise<PodExecResult>;
|
|
565
|
+
snapshot(name: string): Promise<PodHostStatus>;
|
|
566
|
+
restore(name: string): Promise<PodHostStatus>;
|
|
567
|
+
drain(name: string, opts?: { cascade?: boolean }): Promise<PodHostStatus>;
|
|
568
|
+
/** TEST-ONLY: force a live pod straight to `gone` with `reason: 'crashed'`. */
|
|
569
|
+
crash(name: string, opts?: { code?: number }): Promise<PodHostStatus>;
|
|
570
|
+
list(): Promise<PodHostStatus[]>;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// ── Browser lane: in-page driver ─────────────────────────────────────────
|
|
574
|
+
|
|
575
|
+
export declare const DEFAULT_DISCOVERY_CHANNEL: string;
|
|
576
|
+
export declare const BROWSER_HOST_READY: "browser-host:ready";
|
|
577
|
+
|
|
578
|
+
export declare function readPodName(g: object): string | null;
|
|
579
|
+
|
|
580
|
+
export declare function bootHostedPod(opts?: {
|
|
581
|
+
globalThis?: object;
|
|
582
|
+
channel?: string;
|
|
583
|
+
name?: string;
|
|
584
|
+
handshakeTimeout?: number;
|
|
585
|
+
discoveryTimeout?: number;
|
|
586
|
+
PodClass?: typeof Pod;
|
|
587
|
+
}): Promise<{ pod: Pod; name: string | null }>;
|
|
588
|
+
|
|
589
|
+
export declare function createInPageDriver(opts: {
|
|
590
|
+
globalThis?: object;
|
|
591
|
+
podUrl: string;
|
|
592
|
+
channel?: string;
|
|
593
|
+
spawnKind?: "iframe" | "window" | "worker";
|
|
594
|
+
timeoutMs?: number;
|
|
595
|
+
childHandshakeTimeoutMs?: number;
|
|
596
|
+
childDiscoveryTimeoutMs?: number;
|
|
597
|
+
BCConstructor?: new (name: string) => unknown;
|
|
598
|
+
driverId?: string;
|
|
599
|
+
}): PodHostDriver & { close(): void };
|
package/src/index.mjs
CHANGED
|
@@ -13,4 +13,19 @@ export {
|
|
|
13
13
|
export { InjectedPod } from './injected-pod.mjs'
|
|
14
14
|
export { installPodRuntime, createRuntime, createClient, createServer } from './runtime.mjs'
|
|
15
15
|
export { BroadcastChannelTransport, EventEmitterTransport, NullTransport } from './transport.mjs'
|
|
16
|
+
export { WebSocketTransport } from './ws-transport.mjs'
|
|
16
17
|
export { TransportDiscovery, NullDiscovery } from './discovery.mjs'
|
|
18
|
+
export {
|
|
19
|
+
POD_HOST_VERB, POD_HOST_VERBS, POD_LANE, POD_LANES, POD_LANE_VERBS, laneSupports,
|
|
20
|
+
POD_LIFECYCLE, POD_LIFECYCLE_STATES, POD_LIFECYCLE_TRANSITIONS, canTransition,
|
|
21
|
+
POD_HOST_ERROR, PodHostDriverError, createUnsupportedDriverMethod,
|
|
22
|
+
validatePodSpec, validateVerbRequest,
|
|
23
|
+
POD_HOST_REQUEST, POD_HOST_RESPONSE, POD_HOST_EVENT, POD_HOST_EVENT_KIND,
|
|
24
|
+
createHostRequest, createHostResponse, createHostEvent,
|
|
25
|
+
InMemoryPodHostDriver,
|
|
26
|
+
} from './host-protocol.mjs'
|
|
27
|
+
export {
|
|
28
|
+
bootHostedPod, readPodName,
|
|
29
|
+
DEFAULT_DISCOVERY_CHANNEL, BROWSER_HOST_READY,
|
|
30
|
+
} from './browser-host-child.mjs'
|
|
31
|
+
export { createInPageDriver } from './browser-host-driver.mjs'
|
package/src/transport.mjs
CHANGED
|
@@ -51,7 +51,9 @@ export class BroadcastChannelTransport {
|
|
|
51
51
|
if (this.#channel) return
|
|
52
52
|
this.#channel = new this.#BCConstructor(this.#channelName)
|
|
53
53
|
this.#channel.onmessage = (event) => {
|
|
54
|
-
if (this.#handler)
|
|
54
|
+
if (this.#handler) {
|
|
55
|
+
try { this.#handler(event.data) } catch { /* listener errors don't crash the pod */ }
|
|
56
|
+
}
|
|
55
57
|
}
|
|
56
58
|
}
|
|
57
59
|
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ws-transport.mjs — WebSocket-backed TransportAdapter for hosted pods.
|
|
3
|
+
*
|
|
4
|
+
* Speaks the `browsermesh-servers` relay/signaling wire protocol so a Pod
|
|
5
|
+
* can run anywhere a WebSocket client is available (Node.js, a browser,
|
|
6
|
+
* or a V8 isolate / workerd) and still reach the same mesh a
|
|
7
|
+
* BroadcastChannel-based Pod reaches in a browser tab.
|
|
8
|
+
*
|
|
9
|
+
* Wire protocol (verified against `browsermesh-servers/relay/index.mjs`
|
|
10
|
+
* and `browsermesh-servers/signaling/index.mjs`):
|
|
11
|
+
* - register: { type: 'register', podId }
|
|
12
|
+
* - registered: { type: 'registered', podId }
|
|
13
|
+
* - relay (client -> relay server): { type: 'relay', target, envelope }
|
|
14
|
+
* - relayed (relay server -> client): { type: 'relayed', source, envelope }
|
|
15
|
+
* - signal (client -> signaling server): { type: 'signal', target, envelope }
|
|
16
|
+
* forwarded by the signaling server as: { type: 'signal', source, envelope }
|
|
17
|
+
* (the signaling server spreads the forwarded payload and injects `source`,
|
|
18
|
+
* so any extra keys like `envelope` survive the hop unchanged)
|
|
19
|
+
* - peers: { type: 'peers', peers: string[] } (signaling only, sent once on registration)
|
|
20
|
+
* - peer-joined / peer-left: { type: 'peer-joined'|'peer-left', podId } (signaling only)
|
|
21
|
+
* - ping / pong: { type: 'ping' } / { type: 'pong' }
|
|
22
|
+
* - error: { type: 'error', message }
|
|
23
|
+
*
|
|
24
|
+
* NOTE: the relay server's wire protocol uses `target`/`source`, not
|
|
25
|
+
* `to`/`from` as the WP1 design sketch in issue #185 describes — this
|
|
26
|
+
* adapter speaks the server's real field names and remaps to the Pod
|
|
27
|
+
* message shape (`from`) on the way in.
|
|
28
|
+
*
|
|
29
|
+
* The relay server only forwards point-to-point (`relay{target, envelope}`
|
|
30
|
+
* -> `relayed{source, envelope}`); it has no broadcast/room concept. So a
|
|
31
|
+
* broadcast send (`msg.to` absent or `'*'`, e.g. discovery `hello`/`goodbye`)
|
|
32
|
+
* is fanned out point-to-point to every peer id this transport currently
|
|
33
|
+
* knows about (see `knownPeers`).
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
const DEFAULT_RECONNECT = { baseMs: 250, maxMs: 10000, maxAttempts: Infinity }
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* TransportAdapter backed by a WebSocket connection to a browsermesh relay
|
|
40
|
+
* (or signaling) server. Implements the same `send/onMessage/open/close/ready`
|
|
41
|
+
* contract as BroadcastChannelTransport and EventEmitterTransport.
|
|
42
|
+
*/
|
|
43
|
+
export class WebSocketTransport {
|
|
44
|
+
#url
|
|
45
|
+
#podId
|
|
46
|
+
#WS
|
|
47
|
+
#protocol
|
|
48
|
+
#signalingUrl
|
|
49
|
+
#peersFromSignaling
|
|
50
|
+
#reconnect
|
|
51
|
+
#onLog
|
|
52
|
+
|
|
53
|
+
#ws = null
|
|
54
|
+
#sigWs = null
|
|
55
|
+
#handler = null
|
|
56
|
+
#ready = false
|
|
57
|
+
#closed = true
|
|
58
|
+
#knownPeers = new Set()
|
|
59
|
+
|
|
60
|
+
#primaryReconnect = { attempts: 0, timer: null }
|
|
61
|
+
#sigReconnect = { attempts: 0, timer: null }
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* @param {object} opts
|
|
65
|
+
* @param {string} opts.url - WebSocket URL of the relay (or signaling) server
|
|
66
|
+
* @param {string} opts.podId - this pod's id, sent on `register`
|
|
67
|
+
* @param {Function|null} [opts.WebSocket] - injectable WebSocket constructor (default: globalThis.WebSocket; pass `null` explicitly to force "unavailable" for testing)
|
|
68
|
+
* @param {'relay'|'signaling'} [opts.protocol='relay'] - wire dialect for `url`
|
|
69
|
+
* @param {string} [opts.signalingUrl] - signaling server URL, used when `peersFromSignaling` is true
|
|
70
|
+
* @param {boolean} [opts.peersFromSignaling=false] - open a second connection to `signalingUrl` to seed `knownPeers` from `peers`/`peer-joined`/`peer-left`
|
|
71
|
+
* @param {{baseMs?: number, maxMs?: number, maxAttempts?: number}} [opts.reconnect] - exponential backoff config
|
|
72
|
+
* @param {(msg: string) => void} [opts.onLog] - diagnostic log sink
|
|
73
|
+
*/
|
|
74
|
+
constructor({
|
|
75
|
+
url,
|
|
76
|
+
podId,
|
|
77
|
+
WebSocket: WS,
|
|
78
|
+
protocol = 'relay',
|
|
79
|
+
signalingUrl,
|
|
80
|
+
peersFromSignaling = false,
|
|
81
|
+
reconnect = {},
|
|
82
|
+
onLog,
|
|
83
|
+
} = {}) {
|
|
84
|
+
if (!url) throw new Error('WebSocketTransport requires { url }')
|
|
85
|
+
if (!podId) throw new Error('WebSocketTransport requires { podId }')
|
|
86
|
+
this.#url = url
|
|
87
|
+
this.#podId = podId
|
|
88
|
+
this.#WS = WS !== undefined ? WS : globalThis.WebSocket
|
|
89
|
+
this.#protocol = protocol === 'signaling' ? 'signaling' : 'relay'
|
|
90
|
+
this.#signalingUrl = signalingUrl || null
|
|
91
|
+
this.#peersFromSignaling = !!peersFromSignaling
|
|
92
|
+
this.#reconnect = { ...DEFAULT_RECONNECT, ...reconnect }
|
|
93
|
+
this.#onLog = onLog || (() => {})
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @returns {boolean} true once the primary connection is registered */
|
|
97
|
+
get ready() { return this.#ready }
|
|
98
|
+
|
|
99
|
+
/** @returns {Set<string>} podIds this transport has seen (via relay/signal senders or signaling peers) */
|
|
100
|
+
get knownPeers() { return new Set(this.#knownPeers) }
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* @param {(msg: object) => void} handler
|
|
104
|
+
*/
|
|
105
|
+
onMessage(handler) {
|
|
106
|
+
this.#handler = handler
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Connect to the relay server (and, if configured, the signaling server)
|
|
111
|
+
* and complete registration. Resolves once `registered` arrives on the
|
|
112
|
+
* primary connection; rejects if the connection errors or closes first.
|
|
113
|
+
*/
|
|
114
|
+
async open() {
|
|
115
|
+
if (!this.#WS) {
|
|
116
|
+
throw new Error(
|
|
117
|
+
'WebSocketTransport: no WebSocket constructor available — pass { WebSocket } ' +
|
|
118
|
+
'or run in an environment with a global WebSocket (browser, Node >=22, workerd)'
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
if (this.#ready) return
|
|
122
|
+
this.#closed = false
|
|
123
|
+
|
|
124
|
+
const tasks = [this.#connectAndRegister('primary')]
|
|
125
|
+
if (this.#peersFromSignaling && this.#signalingUrl) {
|
|
126
|
+
tasks.push(this.#connectAndRegister('signaling'))
|
|
127
|
+
}
|
|
128
|
+
await Promise.all(tasks)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Send a message. Point-to-point if `msg.to` names a specific peer;
|
|
133
|
+
* otherwise (no `to`, or `to === '*'` — discovery hello/goodbye) fan
|
|
134
|
+
* out point-to-point to every known peer, since the relay/signaling
|
|
135
|
+
* servers have no broadcast primitive.
|
|
136
|
+
* @param {object} msg
|
|
137
|
+
*/
|
|
138
|
+
send(msg) {
|
|
139
|
+
if (!this.#ws || !this.#ready || !msg) return
|
|
140
|
+
const to = msg.to
|
|
141
|
+
if (to && to !== '*') {
|
|
142
|
+
this.#sendEnvelope(to, msg)
|
|
143
|
+
return
|
|
144
|
+
}
|
|
145
|
+
for (const peerId of this.#knownPeers) {
|
|
146
|
+
this.#sendEnvelope(peerId, msg)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Close both connections and clear any pending reconnect timers. */
|
|
151
|
+
async close() {
|
|
152
|
+
this.#closed = true
|
|
153
|
+
this.#clearTimer(this.#primaryReconnect)
|
|
154
|
+
this.#clearTimer(this.#sigReconnect)
|
|
155
|
+
this.#ready = false
|
|
156
|
+
if (this.#ws) {
|
|
157
|
+
try { this.#ws.close() } catch { /* already closed */ }
|
|
158
|
+
this.#ws = null
|
|
159
|
+
}
|
|
160
|
+
if (this.#sigWs) {
|
|
161
|
+
try { this.#sigWs.close() } catch { /* already closed */ }
|
|
162
|
+
this.#sigWs = null
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ── Private: outbound ────────────────────────────────────────────
|
|
167
|
+
|
|
168
|
+
#sendEnvelope(target, envelope) {
|
|
169
|
+
const frame = this.#protocol === 'signaling'
|
|
170
|
+
? { type: 'signal', target, envelope }
|
|
171
|
+
: { type: 'relay', target, envelope }
|
|
172
|
+
this.#send(this.#ws, frame)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
#send(ws, data) {
|
|
176
|
+
if (!ws) return
|
|
177
|
+
try {
|
|
178
|
+
if (ws.readyState === undefined || ws.readyState === 1 /* OPEN */) {
|
|
179
|
+
ws.send(JSON.stringify(data))
|
|
180
|
+
}
|
|
181
|
+
} catch { /* socket may be mid-teardown; reconnect loop recovers */ }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// ── Private: connection lifecycle ────────────────────────────────
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Open one WebSocket connection (`kind` is 'primary' or 'signaling'),
|
|
188
|
+
* register, and wire message/close handling. Resolves on `registered`,
|
|
189
|
+
* rejects on `error` or on close-before-registered. Always schedules a
|
|
190
|
+
* reconnect on close (unless `close()` has been called).
|
|
191
|
+
* @param {'primary'|'signaling'} kind
|
|
192
|
+
*/
|
|
193
|
+
#connectAndRegister(kind) {
|
|
194
|
+
const isPrimary = kind === 'primary'
|
|
195
|
+
const url = isPrimary ? this.#url : this.#signalingUrl
|
|
196
|
+
|
|
197
|
+
return new Promise((resolve, reject) => {
|
|
198
|
+
let settled = false
|
|
199
|
+
let ws
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
ws = new this.#WS(url)
|
|
203
|
+
} catch (err) {
|
|
204
|
+
this.#scheduleReconnect(kind)
|
|
205
|
+
reject(err)
|
|
206
|
+
return
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (isPrimary) this.#ws = ws
|
|
210
|
+
else this.#sigWs = ws
|
|
211
|
+
|
|
212
|
+
const finishResolve = () => {
|
|
213
|
+
if (settled) return
|
|
214
|
+
settled = true
|
|
215
|
+
if (isPrimary) {
|
|
216
|
+
this.#ready = true
|
|
217
|
+
this.#primaryReconnect.attempts = 0
|
|
218
|
+
} else {
|
|
219
|
+
this.#sigReconnect.attempts = 0
|
|
220
|
+
}
|
|
221
|
+
resolve()
|
|
222
|
+
}
|
|
223
|
+
const finishReject = (err) => {
|
|
224
|
+
if (settled) return
|
|
225
|
+
settled = true
|
|
226
|
+
reject(err)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const onOpen = () => {
|
|
230
|
+
this.#send(ws, { type: 'register', podId: this.#podId })
|
|
231
|
+
}
|
|
232
|
+
const onMessage = (event) => {
|
|
233
|
+
const data = this.#parse(event)
|
|
234
|
+
if (!data) return
|
|
235
|
+
if (isPrimary) this.#handlePrimaryMessage(data)
|
|
236
|
+
else this.#handleSignalingMessage(data)
|
|
237
|
+
|
|
238
|
+
if (data.type === 'registered') {
|
|
239
|
+
finishResolve()
|
|
240
|
+
} else if (data.type === 'error') {
|
|
241
|
+
finishReject(new Error(data.message || `WebSocketTransport: ${kind} registration error`))
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const onClose = () => {
|
|
245
|
+
if (isPrimary) { this.#ready = false; this.#ws = null }
|
|
246
|
+
else { this.#sigWs = null }
|
|
247
|
+
finishReject(new Error(`WebSocketTransport: ${kind} connection closed`))
|
|
248
|
+
this.#scheduleReconnect(kind)
|
|
249
|
+
}
|
|
250
|
+
const onError = (err) => {
|
|
251
|
+
this.#onLog(`[ws-transport] ${kind} socket error: ${err?.message ?? err}`)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
ws.addEventListener('open', onOpen)
|
|
255
|
+
ws.addEventListener('message', onMessage)
|
|
256
|
+
ws.addEventListener('close', onClose)
|
|
257
|
+
ws.addEventListener('error', onError)
|
|
258
|
+
})
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
#parse(event) {
|
|
262
|
+
try {
|
|
263
|
+
// Wire contract (same rule as @johnhenry/browsermesh-transport's
|
|
264
|
+
// encodeWireData): strings pass through untouched, binary is read as
|
|
265
|
+
// UTF-8 text, and the only JSON step is this one parse of the frame.
|
|
266
|
+
// Outbound, #send stringifies each control frame exactly once; the
|
|
267
|
+
// pod message rides inside it as a nested object, never as a
|
|
268
|
+
// pre-encoded string, so nothing is double-encoded.
|
|
269
|
+
const d = event.data
|
|
270
|
+
let raw
|
|
271
|
+
if (typeof d === 'string') raw = d
|
|
272
|
+
else if (d instanceof ArrayBuffer) raw = new TextDecoder().decode(d)
|
|
273
|
+
else if (ArrayBuffer.isView(d)) raw = new TextDecoder().decode(d)
|
|
274
|
+
else return null // Blob (async read) or anything else: not a frame we can read
|
|
275
|
+
return JSON.parse(raw)
|
|
276
|
+
} catch {
|
|
277
|
+
return null
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
#scheduleReconnect(kind) {
|
|
282
|
+
if (this.#closed) return
|
|
283
|
+
const state = kind === 'primary' ? this.#primaryReconnect : this.#sigReconnect
|
|
284
|
+
if (state.attempts >= this.#reconnect.maxAttempts) {
|
|
285
|
+
this.#onLog(`[ws-transport] giving up reconnect for ${kind} after ${state.attempts} attempts`)
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
const delay = Math.min(this.#reconnect.baseMs * 2 ** state.attempts, this.#reconnect.maxMs)
|
|
289
|
+
state.attempts++
|
|
290
|
+
state.timer = setTimeout(() => {
|
|
291
|
+
state.timer = null
|
|
292
|
+
this.#connectAndRegister(kind).catch((err) => {
|
|
293
|
+
this.#onLog(`[ws-transport] reconnect attempt failed (${kind}): ${err.message}`)
|
|
294
|
+
})
|
|
295
|
+
}, delay)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
#clearTimer(state) {
|
|
299
|
+
if (state.timer) {
|
|
300
|
+
clearTimeout(state.timer)
|
|
301
|
+
state.timer = null
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// ── Private: inbound ──────────────────────────────────────────────
|
|
306
|
+
|
|
307
|
+
#handlePrimaryMessage(data) {
|
|
308
|
+
switch (data.type) {
|
|
309
|
+
case 'relayed':
|
|
310
|
+
case 'signal': {
|
|
311
|
+
if (data.source) this.#knownPeers.add(data.source)
|
|
312
|
+
this.#deliver(data.source, data.envelope)
|
|
313
|
+
return
|
|
314
|
+
}
|
|
315
|
+
case 'ping':
|
|
316
|
+
this.#send(this.#ws, { type: 'pong' })
|
|
317
|
+
return
|
|
318
|
+
case 'error':
|
|
319
|
+
this.#onLog(`[ws-transport] relay error: ${data.message}`)
|
|
320
|
+
return
|
|
321
|
+
default:
|
|
322
|
+
return
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
#handleSignalingMessage(data) {
|
|
327
|
+
switch (data.type) {
|
|
328
|
+
case 'peers': {
|
|
329
|
+
for (const id of data.peers || []) {
|
|
330
|
+
if (id !== this.#podId) this.#knownPeers.add(id)
|
|
331
|
+
}
|
|
332
|
+
return
|
|
333
|
+
}
|
|
334
|
+
case 'peer-joined': {
|
|
335
|
+
if (data.podId && data.podId !== this.#podId) this.#knownPeers.add(data.podId)
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
case 'peer-left': {
|
|
339
|
+
if (data.podId) this.#knownPeers.delete(data.podId)
|
|
340
|
+
return
|
|
341
|
+
}
|
|
342
|
+
case 'ping':
|
|
343
|
+
this.#send(this.#sigWs, { type: 'pong' })
|
|
344
|
+
return
|
|
345
|
+
case 'error':
|
|
346
|
+
this.#onLog(`[ws-transport] signaling error: ${data.message}`)
|
|
347
|
+
return
|
|
348
|
+
default:
|
|
349
|
+
return
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
#deliver(source, envelope) {
|
|
354
|
+
if (!this.#handler || !envelope || typeof envelope !== 'object') return
|
|
355
|
+
const msg = ('from' in envelope) ? envelope : { ...envelope, from: source }
|
|
356
|
+
this.#handler(msg)
|
|
357
|
+
}
|
|
358
|
+
}
|