@narumitw/pi-chat 0.0.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/src/network.ts ADDED
@@ -0,0 +1,201 @@
1
+ import type { Duplex } from "node:stream";
2
+ import Hyperswarm, { type PeerDiscovery, type PeerInfo } from "hyperswarm";
3
+ import type { ChatTransport, ChatTransportListener, TransportPeer } from "./chat-session.js";
4
+ import type { ChatIdentity } from "./identity.js";
5
+ import {
6
+ encodeFrame,
7
+ FrameDecoder,
8
+ type ProtocolMessage,
9
+ type RoomDescriptor,
10
+ } from "./protocol.js";
11
+
12
+ export interface HyperswarmTransportOptions {
13
+ room: RoomDescriptor;
14
+ identity: ChatIdentity;
15
+ maxPeers?: number;
16
+ dht?: unknown;
17
+ bootstrap?: unknown[];
18
+ }
19
+
20
+ interface ActiveConnection {
21
+ socket: Duplex;
22
+ peer: TransportPeer;
23
+ }
24
+
25
+ export class HyperswarmTransport implements ChatTransport {
26
+ private readonly options: HyperswarmTransportOptions;
27
+ private swarm: Hyperswarm | undefined;
28
+ private discovery: PeerDiscovery | undefined;
29
+ private listener: ChatTransportListener | undefined;
30
+ private readonly connections = new Map<Duplex, ActiveConnection>();
31
+ private readonly directPeers = new Map<string, Buffer>();
32
+ private readonly refreshTimers = new Set<NodeJS.Timeout>();
33
+ private stopPromise: Promise<void> | undefined;
34
+
35
+ constructor(options: HyperswarmTransportOptions) {
36
+ this.options = options;
37
+ }
38
+
39
+ get connectionCount(): number {
40
+ return this.connections.size;
41
+ }
42
+
43
+ async start(listener: ChatTransportListener, signal?: AbortSignal): Promise<void> {
44
+ if (this.swarm) throw new Error("Hyperswarm transport has already started.");
45
+ const startupSignal = signal
46
+ ? AbortSignal.any([signal, AbortSignal.timeout(15_000)])
47
+ : AbortSignal.timeout(15_000);
48
+ startupSignal.throwIfAborted();
49
+ this.listener = listener;
50
+ const swarm = new Hyperswarm({
51
+ keyPair: {
52
+ publicKey: this.options.identity.publicKey,
53
+ secretKey: this.options.identity.secretKey,
54
+ },
55
+ maxPeers: this.options.maxPeers ?? 16,
56
+ ...(this.options.dht ? { dht: this.options.dht } : {}),
57
+ ...(this.options.bootstrap ? { bootstrap: this.options.bootstrap } : {}),
58
+ });
59
+ this.swarm = swarm;
60
+ swarm.on("connection", (socket, info) => this.accept(socket, info));
61
+ swarm.on("error", (error) => this.listener?.onError(safeNetworkError(error)));
62
+ try {
63
+ const discovery = swarm.join(this.options.room.topic, {
64
+ server: true,
65
+ client: true,
66
+ limit: this.options.maxPeers ?? 16,
67
+ });
68
+ this.discovery = discovery;
69
+ await raceAbort(discovery.flushed(), startupSignal);
70
+ startupSignal.throwIfAborted();
71
+ this.scheduleEarlyRefreshes(discovery);
72
+ } catch (error) {
73
+ await this.stop();
74
+ throw error;
75
+ }
76
+ }
77
+
78
+ connectPeer(publicKey: Buffer): void {
79
+ if (!this.swarm || publicKey.length !== 32 || this.directPeers.size >= 16) return;
80
+ const id = publicKey.toString("hex");
81
+ if (id === this.options.identity.publicKey.toString("hex") || this.directPeers.has(id)) return;
82
+ this.directPeers.set(id, Buffer.from(publicKey));
83
+ this.swarm.joinPeer(publicKey);
84
+ }
85
+
86
+ stop(): Promise<void> {
87
+ if (this.stopPromise) return this.stopPromise;
88
+ this.stopPromise = this.stopOwned();
89
+ return this.stopPromise;
90
+ }
91
+
92
+ private scheduleEarlyRefreshes(discovery: PeerDiscovery): void {
93
+ const delays = [250, 750, 1_500, 3_000, 6_000, 12_000];
94
+ const schedule = (index: number): void => {
95
+ const delayMs = delays[index];
96
+ if (delayMs === undefined || this.discovery !== discovery) return;
97
+ const timer = setTimeout(() => {
98
+ this.refreshTimers.delete(timer);
99
+ if (this.discovery !== discovery) return;
100
+ void discovery
101
+ .refresh()
102
+ .catch(() => undefined)
103
+ .finally(() => {
104
+ if (this.discovery === discovery) schedule(index + 1);
105
+ });
106
+ }, delayMs);
107
+ this.refreshTimers.add(timer);
108
+ };
109
+ schedule(0);
110
+ }
111
+
112
+ private accept(socket: Duplex, info: PeerInfo): void {
113
+ if (!this.swarm || !this.listener) {
114
+ socket.destroy();
115
+ return;
116
+ }
117
+ const decoder = new FrameDecoder();
118
+ let closed = false;
119
+ const peer: TransportPeer = {
120
+ publicKey: Buffer.from(info.publicKey),
121
+ send(message: ProtocolMessage) {
122
+ if (closed || socket.destroyed) throw new Error("Peer connection is closed.");
123
+ const accepted = socket.write(encodeFrame(message));
124
+ if (!accepted && socket.destroyed) throw new Error("Peer connection rejected the message.");
125
+ },
126
+ close() {
127
+ if (closed) return;
128
+ closed = true;
129
+ socket.destroy();
130
+ },
131
+ };
132
+ this.connections.set(socket, { socket, peer });
133
+ this.listener.onPeer(peer);
134
+ socket.on("data", (chunk: unknown) => {
135
+ if (closed || !this.listener) return;
136
+ try {
137
+ const bytes =
138
+ typeof chunk === "string"
139
+ ? Buffer.from(chunk)
140
+ : Buffer.isBuffer(chunk)
141
+ ? chunk
142
+ : Buffer.from(chunk as Uint8Array);
143
+ for (const message of decoder.push(bytes)) this.listener.onMessage(peer, message);
144
+ } catch {
145
+ closed = true;
146
+ socket.destroy();
147
+ this.listener?.onError(new Error("Pi Chat rejected invalid peer protocol data."));
148
+ }
149
+ });
150
+ const disconnected = () => {
151
+ if (!this.connections.delete(socket)) return;
152
+ closed = true;
153
+ this.listener?.onDisconnect(peer);
154
+ };
155
+ socket.once("close", disconnected);
156
+ socket.once("error", (error) => {
157
+ this.listener?.onError(safeNetworkError(error));
158
+ disconnected();
159
+ });
160
+ }
161
+
162
+ private async stopOwned(): Promise<void> {
163
+ for (const timer of this.refreshTimers) clearTimeout(timer);
164
+ this.refreshTimers.clear();
165
+ const discovery = this.discovery;
166
+ this.discovery = undefined;
167
+ if (discovery) await discovery.destroy().catch(() => undefined);
168
+ for (const { socket } of this.connections.values()) socket.destroy();
169
+ this.connections.clear();
170
+ const swarm = this.swarm;
171
+ if (swarm) {
172
+ for (const publicKey of this.directPeers.values()) swarm.leavePeer(publicKey);
173
+ }
174
+ this.directPeers.clear();
175
+ this.swarm = undefined;
176
+ this.listener = undefined;
177
+ if (swarm) await swarm.destroy().catch(() => undefined);
178
+ }
179
+ }
180
+
181
+ async function raceAbort<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T> {
182
+ if (!signal) return operation;
183
+ signal.throwIfAborted();
184
+ let remove = () => {};
185
+ const aborted = new Promise<never>((_resolve, reject) => {
186
+ const onAbort = () => reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
187
+ signal.addEventListener("abort", onAbort, { once: true });
188
+ remove = () => signal.removeEventListener("abort", onAbort);
189
+ });
190
+ try {
191
+ return await Promise.race([operation, aborted]);
192
+ } finally {
193
+ remove();
194
+ }
195
+ }
196
+
197
+ function safeNetworkError(error: unknown): Error {
198
+ const code =
199
+ error instanceof Error && "code" in error ? String(Reflect.get(error, "code")) : "error";
200
+ return new Error(`Pi Chat network ${code}.`);
201
+ }