grpc-dc 0.32.7 → 0.32.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grpc-dc",
3
- "version": "0.32.7",
3
+ "version": "0.32.9",
4
4
  "description": "gRPC in the browser over WebRTC DataChannels: dependency-free generated gRPC clients & servers for JavaScript — no grpc-web proxy, no external runtime",
5
5
  "keywords": [
6
6
  "grpc",
package/src/channel.js CHANGED
@@ -33,7 +33,7 @@ export class Channel {
33
33
  return this.#endpoint;
34
34
  }
35
35
 
36
- async #open(path, metadata, timeout) {
36
+ async #open(path, metadata, timeout, signal = null) {
37
37
  let deadline = null;
38
38
  if (timeout !== undefined && timeout !== null) {
39
39
  deadline = Date.now() + timeout;
@@ -51,6 +51,15 @@ export class Channel {
51
51
  }
52
52
  const [id, input] = this.#endpoint.openStream();
53
53
  if (traceCtx !== null) this.#traces.set(id, { ctx: traceCtx, path });
54
+ if (signal) {
55
+ // Per-call cancellation: an aborted AbortSignal aborts
56
+ // the stream (RST CANCELLED; pending reads fail with
57
+ // CANCELLED). Stream ids are never reused, so a late
58
+ // abort after completion is a harmless no-op.
59
+ const onAbort = () => this.#endpoint.cancelStream(id);
60
+ if (signal.aborted) onAbort();
61
+ else signal.addEventListener("abort", onAbort, { once: true });
62
+ }
54
63
  try {
55
64
  await this.#endpoint.sendFrame(headersFrame(id, path, metadata));
56
65
  } catch (e) {
@@ -104,7 +113,11 @@ export class Channel {
104
113
  await this.#endpoint.sendFrame(encodeFrame(FrameType.DATA, id, ReqType.encode(request)));
105
114
  }
106
115
 
107
- async #collectOne(id, input, RespType, deadline = null) {
116
+ // hooks: optional {onHeaders, onTrailers} from call options,
117
+ // invoked with the response initial/trailing metadata ({} when
118
+ // the peer sent none). Trailers also ride the terminal
119
+ // StatusError as .trailers, success or failure.
120
+ async #collectOne(id, input, RespType, deadline = null, hooks = {}) {
108
121
  const iterator = input[Symbol.asyncIterator]();
109
122
  try {
110
123
  let response = null;
@@ -112,12 +125,15 @@ export class Channel {
112
125
  const step = await this.#next(id, iterator, deadline);
113
126
  if (step.done) break;
114
127
  const event = step.value;
115
- if (event.kind === "data") {
128
+ if (event.kind === "headers") {
129
+ hooks.onHeaders?.(event.headers?.metadata ?? {});
130
+ } else if (event.kind === "data") {
116
131
  if (response !== null) {
117
132
  throw StatusError.internal("unary call received more than one response");
118
133
  }
119
134
  response = RespType.decode(event.payload);
120
135
  } else if (event.kind === "trailers") {
136
+ hooks.onTrailers?.(event.trailers ?? {});
121
137
  this.#endTrace(id, StatusName[event.status.code] ?? `CODE_${event.status.code}`);
122
138
  if (event.status.code !== 0) throw event.status;
123
139
  if (response === null) throw StatusError.internal("call closed with no response");
@@ -134,16 +150,19 @@ export class Channel {
134
150
  }
135
151
  }
136
152
 
137
- async *#responses(id, input, RespType, deadline = null) {
153
+ async *#responses(id, input, RespType, deadline = null, hooks = {}) {
138
154
  const iterator = input[Symbol.asyncIterator]();
139
155
  try {
140
156
  for (;;) {
141
157
  const step = await this.#next(id, iterator, deadline);
142
158
  if (step.done) break;
143
159
  const event = step.value;
144
- if (event.kind === "data") {
160
+ if (event.kind === "headers") {
161
+ hooks.onHeaders?.(event.headers?.metadata ?? {});
162
+ } else if (event.kind === "data") {
145
163
  yield RespType.decode(event.payload);
146
164
  } else if (event.kind === "trailers") {
165
+ hooks.onTrailers?.(event.trailers ?? {});
147
166
  this.#endTrace(id, StatusName[event.status.code] ?? `CODE_${event.status.code}`);
148
167
  if (event.status.code !== 0) throw event.status;
149
168
  return;
@@ -174,55 +193,47 @@ export class Channel {
174
193
  }
175
194
 
176
195
  /** Unary: one request, one response. */
177
- async unary(path, request, ReqType, RespType, { metadata = {}, timeout } = {}) {
178
- const [id, input, deadline] = await this.#open(path, metadata, timeout);
196
+ async unary(path, request, ReqType, RespType, { metadata = {}, timeout, onHeaders, onTrailers, signal } = {}) {
197
+ const [id, input, deadline] = await this.#open(path, metadata, timeout, signal);
179
198
  await this.#sendMessage(id, ReqType, request);
180
199
  await this.#endpoint.sendFrame(encodeFrame(FrameType.HALF_CLOSE, id));
181
- return this.#collectOne(id, input, RespType, deadline);
200
+ return this.#collectOne(id, input, RespType, deadline, { onHeaders, onTrailers });
182
201
  }
183
202
 
184
203
  /** Server-streaming: one request, async iterable of responses. */
185
- serverStream(path, request, ReqType, RespType, { metadata = {}, timeout } = {}) {
204
+ serverStream(path, request, ReqType, RespType, { metadata = {}, timeout, onHeaders, onTrailers, signal } = {}) {
186
205
  return (async () => {
187
- const [id, input, deadline] = await this.#open(path, metadata, timeout);
206
+ const [id, input, deadline] = await this.#open(path, metadata, timeout, signal);
188
207
  await this.#sendMessage(id, ReqType, request);
189
208
  await this.#endpoint.sendFrame(encodeFrame(FrameType.HALF_CLOSE, id));
190
- return this.#responses(id, input, RespType, deadline);
209
+ return this.#responses(id, input, RespType, deadline, { onHeaders, onTrailers });
191
210
  })();
192
211
  }
193
212
 
194
213
  /** Client-streaming: async iterable of requests, one response. */
195
- async clientStream(path, requests, ReqType, RespType, { metadata = {}, timeout } = {}) {
196
- const [id, input, deadline] = await this.#open(path, metadata, timeout);
214
+ async clientStream(path, requests, ReqType, RespType, { metadata = {}, timeout, onHeaders, onTrailers, signal } = {}) {
215
+ const [id, input, deadline] = await this.#open(path, metadata, timeout, signal);
197
216
  const pump = this.#pump(id, requests, ReqType);
198
217
  try {
199
- return await this.#collectOne(id, input, RespType, deadline);
218
+ return await this.#collectOne(id, input, RespType, deadline, { onHeaders, onTrailers });
200
219
  } finally {
201
220
  pump.catch(() => {});
202
221
  }
203
222
  }
204
223
 
205
224
  /** Bidirectional: async iterable of requests and of responses. */
206
- bidi(path, requests, ReqType, RespType, { metadata = {}, timeout } = {}) {
225
+ bidi(path, requests, ReqType, RespType, { metadata = {}, timeout, onHeaders, onTrailers, signal } = {}) {
207
226
  return (async () => {
208
- const [id, input, deadline] = await this.#open(path, metadata, timeout);
227
+ const [id, input, deadline] = await this.#open(path, metadata, timeout, signal);
209
228
  const pump = this.#pump(id, requests, ReqType);
210
229
  pump.catch(() => {});
211
- return this.#responses(id, input, RespType, deadline);
230
+ return this.#responses(id, input, RespType, deadline, { onHeaders, onTrailers });
212
231
  })();
213
232
  }
214
233
 
215
234
  /** Abort a call: sends RST CANCELLED. */
235
+ /** Abort a call: RST CANCELLED to the peer, CANCELLED locally. */
216
236
  async cancel(streamId) {
217
- await this.#endpoint
218
- .sendFrame(
219
- statusFrame(
220
- FrameType.RST,
221
- streamId,
222
- new StatusError(1, "cancelled by caller"),
223
- ),
224
- )
225
- .catch(() => {});
226
- this.#endpoint.closeStream(streamId);
237
+ this.#endpoint.cancelStream(streamId);
227
238
  }
228
239
  }
package/src/codec.js CHANGED
@@ -85,7 +85,7 @@ export function asUint8Array(data) {
85
85
  }
86
86
 
87
87
  export function headersFrame(streamId, path, metadata = {}) {
88
- const body = path === null ? {} : { path, metadata };
88
+ const body = path === null ? { metadata } : { path, metadata };
89
89
  return encodeFrame(FrameType.HEADERS, streamId, textEncoder.encode(JSON.stringify(body)));
90
90
  }
91
91
 
@@ -109,9 +109,15 @@ export function parseTimeout(text) {
109
109
  return Number(digits) * unit;
110
110
  }
111
111
 
112
- export function statusFrame(frameType, streamId, status) {
113
- const body = JSON.stringify({ code: status.code, message: status.statusMessage ?? status.message ?? "" });
114
- return encodeFrame(frameType, streamId, textEncoder.encode(body));
112
+ // Status frames (TRAILERS/RST) carry {code, message} and, when
113
+ // the call produced trailing metadata, a metadata member with
114
+ // the same JSON shape as HEADERS metadata (SPEC.md). Peers that
115
+ // predate trailing metadata ignore the member.
116
+ export function statusFrame(frameType, streamId, status, trailers = undefined) {
117
+ const md = trailers ?? status.trailers;
118
+ const body = { code: status.code, message: status.statusMessage ?? status.message ?? "" };
119
+ if (md && Object.keys(md).length > 0) body.metadata = md;
120
+ return encodeFrame(frameType, streamId, textEncoder.encode(JSON.stringify(body)));
115
121
  }
116
122
 
117
123
  export function parseHeaders(payload) {
@@ -126,7 +132,9 @@ export function parseHeaders(payload) {
126
132
  export function parseStatus(payload) {
127
133
  try {
128
134
  const parsed = JSON.parse(textDecoder.decode(payload));
129
- return new StatusError(parsed.code ?? 2, parsed.message ?? "");
135
+ const status = new StatusError(parsed.code ?? 2, parsed.message ?? "");
136
+ status.trailers = parsed.metadata ?? {};
137
+ return status;
130
138
  } catch {
131
139
  return StatusError.internal("malformed status payload");
132
140
  }
package/src/endpoint.js CHANGED
@@ -125,6 +125,18 @@ export class Endpoint {
125
125
  }
126
126
  }
127
127
 
128
+ /** Abort one stream: RST (CANCELLED) to the peer, and any
129
+ * local reader wakes with that CANCELLED status. */
130
+ cancelStream(id) {
131
+ const status = new StatusError(StatusCode.CANCELLED, "call cancelled");
132
+ const input = this.#streams.get(id);
133
+ if (input) {
134
+ input.push({ kind: "rst", status, trailers: {} });
135
+ this.#streams.delete(id);
136
+ }
137
+ this.sendFrame(statusFrame(FrameType.RST, id, status)).catch(() => {});
138
+ }
139
+
128
140
  async sendFrame(frameBytes) {
129
141
  // Serialize sends so HEADERS never overtakes a previous frame on the
130
142
  // wire, and pause while the SCTP send buffer is above the threshold.
@@ -199,7 +211,7 @@ export class Endpoint {
199
211
 
200
212
  #terminal(streamId, payload, kind) {
201
213
  const status = parseStatus(payload);
202
- this.#streams.get(streamId)?.push({ kind, status });
214
+ this.#streams.get(streamId)?.push({ kind, status, trailers: status.trailers ?? {} });
203
215
  this.#streams.delete(streamId);
204
216
  }
205
217
 
@@ -240,14 +252,17 @@ export class Endpoint {
240
252
  this.#streams.set(streamId, input);
241
253
  const sink = {
242
254
  sendData: (payload) => this.sendFrame(encodeFrame(FrameType.DATA, streamId, payload)),
243
- sendHeaders: () => this.sendFrame(headersFrame(streamId, null)),
244
- sendTrailers: (status) =>
245
- this.sendFrame(statusFrame(FrameType.TRAILERS, streamId, status)),
255
+ sendHeaders: (metadata = {}) => this.sendFrame(headersFrame(streamId, null, metadata)),
256
+ sendTrailers: (status, trailers) =>
257
+ this.sendFrame(statusFrame(FrameType.TRAILERS, streamId, status, trailers)),
246
258
  };
247
259
  try {
248
- await sink.sendHeaders();
249
- await this.dispatcher(headers.path, headers, input, sink);
250
- await sink.sendTrailers(StatusError.ok());
260
+ // No eager HEADERS: the dispatcher sends initial metadata
261
+ // via sink.sendHeaders (Server does it lazily before the
262
+ // first DATA). A dispatcher may return {trailers} to have
263
+ // them ride the OK status frame.
264
+ const extra = await this.dispatcher(headers.path, headers, input, sink);
265
+ await sink.sendTrailers(StatusError.ok(), extra?.trailers);
251
266
  } catch (e) {
252
267
  const status =
253
268
  e instanceof StatusError ? e : StatusError.internal(e?.message ?? String(e));
package/src/http2.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // using WebRTC DataChannels.
12
12
 
13
13
  import http2 from "node:http2";
14
+ import zlib from "node:zlib";
14
15
  import { decodeFrame, encodeFrame, FrameType } from "./codec.js";
15
16
  import { parseHeaders } from "./codec.js";
16
17
  import { Channel } from "./channel.js";
@@ -19,6 +20,13 @@ export class Http2DataChannel {
19
20
  #listeners = new Map();
20
21
  #streams = new Map();
21
22
  #buffers = new Map();
23
+ // Per-stream gzip state: requests compress when the call
24
+ // metadata carries grpc-encoding: gzip; responses decompress
25
+ // when the response headers do. Every stream advertises
26
+ // gzip in grpc-accept-encoding, and per-message compression
27
+ // still follows the LPM compressed flag.
28
+ #compressOut = new Map();
29
+ #decompressIn = new Map();
22
30
 
23
31
  constructor(authority, { secure = false, ...connectOptions } = {}) {
24
32
  this.readyState = "open";
@@ -45,6 +53,18 @@ export class Http2DataChannel {
45
53
  send(frameBytes) {
46
54
  const frame = decodeFrame(frameBytes);
47
55
  const id = frame.streamId;
56
+ // HTTP/2 header block -> grpc-dc metadata: transport keys
57
+ // drop out. -bin values are base64 in both domains (the
58
+ // gRPC HTTP/2 spec base64s them; so does the JSON wire).
59
+ const toDcMetadata = (headers) => {
60
+ const meta = {};
61
+ for (const [k, v] of Object.entries(headers)) {
62
+ if (k.startsWith(":") || typeof v !== "string") continue;
63
+ if (["content-type", "grpc-status", "grpc-message", "grpc-encoding", "grpc-accept-encoding"].includes(k)) continue;
64
+ meta[k] = v;
65
+ }
66
+ return meta;
67
+ };
48
68
  if (frame.type === FrameType.HEADERS) {
49
69
  const head = parseHeaders(frame.payload);
50
70
  const metadata = {};
@@ -54,30 +74,31 @@ export class Http2DataChannel {
54
74
  ":method": "POST",
55
75
  "content-type": "application/grpc",
56
76
  te: "trailers",
77
+ "grpc-accept-encoding": "gzip,identity",
57
78
  ...metadata,
58
79
  });
59
80
  this.#streams.set(id, stream);
60
81
  this.#buffers.set(id, Buffer.alloc(0));
82
+ this.#compressOut.set(id, metadata["grpc-encoding"] === "gzip");
61
83
  stream.on("response", (headers, flags) => {
62
- const meta = {};
63
- for (const [k, v] of Object.entries(headers)) {
64
- if (!k.startsWith(":") && k !== "content-type") meta[k] = v;
65
- }
84
+ this.#decompressIn.set(id, headers["grpc-encoding"] === "gzip");
66
85
  const trailersOnly =
67
86
  (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) !== 0 && headers["grpc-status"] !== undefined;
68
87
  if (trailersOnly) {
69
88
  this.#emitFrame(FrameType.TRAILERS, id, JSON.stringify({
70
89
  code: Number(headers["grpc-status"]),
71
90
  message: decodeURIComponent(headers["grpc-message"] ?? ""),
91
+ metadata: toDcMetadata(headers),
72
92
  }));
73
93
  } else {
74
- this.#emitFrame(FrameType.HEADERS, id, JSON.stringify({ metadata: meta }));
94
+ this.#emitFrame(FrameType.HEADERS, id, JSON.stringify({ metadata: toDcMetadata(headers) }));
75
95
  }
76
96
  });
77
97
  stream.on("trailers", (headers) => {
78
98
  this.#emitFrame(FrameType.TRAILERS, id, JSON.stringify({
79
99
  code: Number(headers["grpc-status"] ?? 2),
80
100
  message: decodeURIComponent(headers["grpc-message"] ?? ""),
101
+ metadata: toDcMetadata(headers),
81
102
  }));
82
103
  });
83
104
  stream.on("data", (chunk) => {
@@ -85,7 +106,17 @@ export class Http2DataChannel {
85
106
  while (buf.length >= 5) {
86
107
  const len = buf.readUInt32BE(1);
87
108
  if (buf.length < 5 + len) break;
88
- this.#emit(encodeFrame(FrameType.DATA, id, new Uint8Array(buf.subarray(5, 5 + len))));
109
+ let payload = buf.subarray(5, 5 + len);
110
+ if (buf[0] === 1 && this.#decompressIn.get(id)) {
111
+ try {
112
+ payload = zlib.gunzipSync(payload);
113
+ } catch {
114
+ stream.close(http2.constants.NGHTTP2_CANCEL);
115
+ this.#emitFrame(FrameType.RST, id, JSON.stringify({ code: 3, message: "gzip decompression failed" }));
116
+ return;
117
+ }
118
+ }
119
+ this.#emit(encodeFrame(FrameType.DATA, id, new Uint8Array(payload)));
89
120
  buf = buf.subarray(5 + len);
90
121
  }
91
122
  this.#buffers.set(id, buf);
@@ -96,9 +127,16 @@ export class Http2DataChannel {
96
127
  } else if (frame.type === FrameType.DATA) {
97
128
  const stream = this.#streams.get(id);
98
129
  if (stream) {
99
- const lpm = Buffer.alloc(5 + frame.payload.length);
100
- lpm.writeUInt32BE(frame.payload.length, 1);
101
- Buffer.from(frame.payload).copy(lpm, 5);
130
+ let payload = frame.payload;
131
+ let flag = 0;
132
+ if (this.#compressOut.get(id)) {
133
+ payload = zlib.gzipSync(payload);
134
+ flag = 1;
135
+ }
136
+ const lpm = Buffer.alloc(5 + payload.length);
137
+ lpm[0] = flag;
138
+ lpm.writeUInt32BE(payload.length, 1);
139
+ Buffer.from(payload).copy(lpm, 5);
102
140
  stream.write(lpm);
103
141
  }
104
142
  } else if (frame.type === FrameType.HALF_CLOSE) {
package/src/server.js CHANGED
@@ -66,6 +66,28 @@ export class Server {
66
66
  const metadata = headers.metadata ?? {};
67
67
  const timeoutMs = parseTimeout(metadata["grpc-timeout"]);
68
68
  const deadline = timeoutMs === null ? null : Date.now() + timeoutMs;
69
+ // Initial/trailing metadata the handler accumulates via
70
+ // ctx.setHeaders/ctx.setTrailers. Initial metadata flushes
71
+ // lazily, right before the first response DATA (or at the
72
+ // end of a call that produced none); trailers ride the
73
+ // terminal status frame.
74
+ const responseHeaders = {};
75
+ const responseTrailers = {};
76
+ let headersSent = false;
77
+ const flushHeaders = async () => {
78
+ if (!headersSent) {
79
+ headersSent = true;
80
+ await sink.sendHeaders(responseHeaders);
81
+ }
82
+ };
83
+ const callSink = {
84
+ sendHeaders: flushHeaders,
85
+ sendData: async (payload) => {
86
+ await flushHeaders();
87
+ await sink.sendData(payload);
88
+ },
89
+ sendTrailers: sink.sendTrailers,
90
+ };
69
91
  const ctx = {
70
92
  path,
71
93
  metadata,
@@ -73,16 +95,23 @@ export class Server {
73
95
  method: method.method,
74
96
  deadline,
75
97
  timeRemaining: () => (deadline === null ? null : deadline - Date.now()),
98
+ setHeaders: (md) => Object.assign(responseHeaders, md),
99
+ setTrailers: (md) => Object.assign(responseTrailers, md),
76
100
  };
77
101
  const traceCtx = traceStart("server", path, parseTraceparent(metadata.traceparent));
78
102
  let traceStatus = "OK";
79
103
  try {
80
- await this.#dispatchTraced(path, method, ctx, input, sink);
104
+ await this.#dispatchTraced(path, method, ctx, input, callSink);
105
+ await flushHeaders();
106
+ return { trailers: responseTrailers };
81
107
  } catch (e) {
82
108
  traceStatus =
83
109
  e instanceof StatusError
84
110
  ? (StatusName[e.code] ?? `CODE_${e.code}`)
85
111
  : "INTERNAL";
112
+ // Trailers set before the failure still ride the status
113
+ // frame (statusFrame reads status.trailers).
114
+ if (e instanceof StatusError) e.trailers = { ...responseTrailers, ...(e.trailers ?? {}) };
86
115
  throw e;
87
116
  } finally {
88
117
  traceEnd("server", path, traceCtx, traceStatus);