grpc-dc 0.40.0 → 0.42.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.
@@ -0,0 +1,212 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Node HTTP/POST signaling server: the server half of the
4
+ // browser signaling contract in signaling.js. Each POST creates
5
+ // a fresh Peer on the handler's shared PeerMux (one UDP socket
6
+ // for every session; options.mux supplies a process-wide one),
7
+ // answers the offer, returns the answer JSON immediately, then
8
+ // connects in the background and serves the browser's "grpc"
9
+ // DataChannel with the given generated Server. Non-trickle: the answer
10
+ // carries the peer's host candidates as created; configure
11
+ // peerOptions (localIps / stunServers / turnServers) when the
12
+ // host candidates in the answer are not reachable as-is.
13
+ // Auth and CORS belong to the host application: mount
14
+ // signalingHandler on your own HTTP server behind them, or use
15
+ // serveHttpSignaling for the standalone no-auth shape.
16
+
17
+ import { createServer } from "node:http";
18
+
19
+ import { PeerMux } from "../../webrtc/js/mux.js";
20
+
21
+ export const SIGNAL_PATH = "/grpc-dc/signal";
22
+ const MAX_SIGNAL_BODY = 1 << 20;
23
+
24
+ function sendJson(res, status, value) {
25
+ const body = JSON.stringify(value);
26
+ res.writeHead(status, {
27
+ "content-type": "application/json",
28
+ "content-length": Buffer.byteLength(body),
29
+ });
30
+ res.end(body);
31
+ }
32
+
33
+ async function readBody(req) {
34
+ const chunks = [];
35
+ let size = 0;
36
+ for await (const chunk of req) {
37
+ size += chunk.length;
38
+ if (size > MAX_SIGNAL_BODY) throw new Error("signaling body too large");
39
+ chunks.push(chunk);
40
+ }
41
+ return Buffer.concat(chunks).toString("utf8");
42
+ }
43
+
44
+ /**
45
+ * HTTP handler for the signaling contract. Returns true when
46
+ * the request path matched (and was handled), false otherwise,
47
+ * so hosts can mount it alongside their own routes:
48
+ * const signal = signalingHandler(grpcServer);
49
+ * createServer((req, res) => signal(req, res).then(h => ...));
50
+ */
51
+ export function signalingHandler(grpcServer, options = {}) {
52
+ const path = options.path ?? SIGNAL_PATH;
53
+ const peerOptions = options.peerOptions ?? {};
54
+ const onError = options.onError ?? ((e) => console.error("http-signaling:", e));
55
+ const peers = new Set();
56
+ const sessions = new Map(); // session id -> peer (trickle/restart)
57
+ // All session peers share one PeerMux UDP socket for the
58
+ // life of this handler (created lazily on first POST, or
59
+ // supplied by the host via options.mux so several signaling
60
+ // servers in one process share one socket; a host-supplied
61
+ // mux stays host-owned and is never closed here).
62
+ let muxPromise = options.mux ? Promise.resolve(options.mux) : null;
63
+ let ownsMux = !options.mux;
64
+ const getMux = () => {
65
+ if (!muxPromise) {
66
+ muxPromise = PeerMux.bind(options.muxBind ?? {});
67
+ }
68
+ return muxPromise;
69
+ };
70
+ const handler = async (req, res) => {
71
+ let pathname;
72
+ try {
73
+ pathname = new URL(req.url, "http://localhost").pathname;
74
+ } catch {
75
+ return false;
76
+ }
77
+ const isSignal = pathname === path;
78
+ const isCandidate = pathname === `${path}/candidate`;
79
+ const isRestart = pathname === `${path}/restart`;
80
+ if (!isSignal && !isCandidate && !isRestart) return false;
81
+ if (req.method !== "POST") {
82
+ sendJson(res, 405, { error: "method not allowed" });
83
+ return true;
84
+ }
85
+ let peer = null;
86
+ try {
87
+ const parsed = JSON.parse(await readBody(req));
88
+ if (isCandidate || isRestart) {
89
+ const sessionPeer = sessions.get(parsed?.session);
90
+ if (!sessionPeer) {
91
+ sendJson(res, 404, { error: "unknown session" });
92
+ return true;
93
+ }
94
+ if (isCandidate) {
95
+ if (typeof parsed?.candidate !== "string") {
96
+ sendJson(res, 400, { error: "expected {\"session\",\"candidate\":...}" });
97
+ return true;
98
+ }
99
+ sessionPeer.addRemoteCandidate(parsed.candidate);
100
+ sendJson(res, 200, { ok: true });
101
+ return true;
102
+ }
103
+ if (parsed?.type !== "offer" || typeof parsed?.sdp !== "string" || !parsed.sdp) {
104
+ sendJson(res, 400, { error: "expected {\"session\",\"type\":\"offer\",\"sdp\":...}" });
105
+ return true;
106
+ }
107
+ try {
108
+ const answer = sessionPeer.handleRestartOffer(parsed.sdp);
109
+ sendJson(res, 200, { type: "answer", sdp: answer, session: parsed.session });
110
+ } catch {
111
+ sendJson(res, 400, { error: "invalid restart offer SDP" });
112
+ }
113
+ return true;
114
+ }
115
+ if (parsed?.type !== "offer" || typeof parsed?.sdp !== "string" || !parsed.sdp) {
116
+ sendJson(res, 400, { error: "expected {\"type\":\"offer\",\"sdp\":...}" });
117
+ return true;
118
+ }
119
+ peer = await (await getMux()).createPeer(peerOptions);
120
+ peers.add(peer);
121
+ let answer;
122
+ try {
123
+ answer = peer.handleOffer(parsed.sdp);
124
+ } catch {
125
+ await peer.close().catch(() => {});
126
+ peers.delete(peer);
127
+ peer = null;
128
+ sendJson(res, 400, { error: "invalid offer SDP" });
129
+ return true;
130
+ }
131
+ const session = globalThis.crypto?.randomUUID?.() ?? `s${Date.now()}-${sessions.size}`;
132
+ sessions.set(session, peer);
133
+ sendJson(res, 200, { type: "answer", sdp: answer, session });
134
+ // Background: run ICE/DTLS, then serve the grpc channel.
135
+ const serving = peer;
136
+ void (async () => {
137
+ try {
138
+ const endpoint = await serving.connect();
139
+ endpoint.onchannel = (channel) => {
140
+ if ((channel.label ?? "grpc") === "grpc") {
141
+ grpcServer.serve(channel);
142
+ // One signaling POST owns one peer: when its grpc
143
+ // channel closes, tear the peer (socket, timers)
144
+ // down with it instead of leaking it per request.
145
+ channel.addEventListener?.(
146
+ "close",
147
+ () => {
148
+ peers.delete(serving);
149
+ sessions.delete(session);
150
+ void serving.close().catch(() => {});
151
+ },
152
+ { once: true },
153
+ );
154
+ }
155
+ };
156
+ } catch (e) {
157
+ onError(e);
158
+ sessions.delete(session);
159
+ await serving.close().catch(() => {});
160
+ }
161
+ })();
162
+ return true;
163
+ } catch (e) {
164
+ if (peer) {
165
+ peers.delete(peer);
166
+ await peer.close().catch(() => {});
167
+ }
168
+ if (!res.headersSent) sendJson(res, 500, { error: "signaling failed" });
169
+ return true;
170
+ }
171
+ };
172
+ // Hosts/tests can tear down every peer created so far (each
173
+ // grpc channel close already closes its own peer; this is
174
+ // the bulk shutdown path). Also exposed as closeSignaling
175
+ // on serveHttpSignaling's returned server.
176
+ handler.closePeers = async () => {
177
+ const all = [...peers];
178
+ peers.clear();
179
+ sessions.clear();
180
+ await Promise.all(all.map((p) => p.close().catch(() => {})));
181
+ if (ownsMux && muxPromise) {
182
+ const mux = await muxPromise.catch(() => null);
183
+ muxPromise = null;
184
+ try { mux?.close(); } catch { /* already closed */ }
185
+ }
186
+ };
187
+ handler.peers = peers;
188
+ // The shared PeerMux every session peer was created on
189
+ // (host-supplied via options.mux, or bound lazily here).
190
+ handler.getMux = getMux;
191
+ return handler;
192
+ }
193
+
194
+ /**
195
+ * Standalone signaling HTTP server on host:port (defaults
196
+ * 127.0.0.1:8080). Requests outside the signaling path get a
197
+ * 404 JSON body. Returns the node:http Server (await its
198
+ * "listening" event; close() to stop). Host applications that
199
+ * need auth/CORS should mount signalingHandler instead.
200
+ */
201
+ export function serveHttpSignaling(grpcServer, options = {}) {
202
+ const handler = signalingHandler(grpcServer, options);
203
+ const server = createServer((req, res) => {
204
+ void handler(req, res).then((handled) => {
205
+ if (!handled && !res.headersSent) sendJson(res, 404, { error: "not found" });
206
+ });
207
+ });
208
+ server.closeSignaling = handler.closePeers;
209
+ server.getSignalingMux = handler.getMux;
210
+ server.listen(options.port ?? 8080, options.host ?? "127.0.0.1");
211
+ return server;
212
+ }