grpc-dc 0.32.7 → 0.32.8
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 +1 -1
- package/src/channel.js +38 -27
- package/src/codec.js +13 -5
- package/src/endpoint.js +22 -7
- package/src/http2.js +15 -5
- package/src/server.js +30 -1
package/package.json
CHANGED
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
|
-
|
|
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 === "
|
|
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 === "
|
|
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
|
-
|
|
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
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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
|
-
|
|
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
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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
|
@@ -45,6 +45,18 @@ export class Http2DataChannel {
|
|
|
45
45
|
send(frameBytes) {
|
|
46
46
|
const frame = decodeFrame(frameBytes);
|
|
47
47
|
const id = frame.streamId;
|
|
48
|
+
// HTTP/2 header block -> grpc-dc metadata: transport keys
|
|
49
|
+
// drop out. -bin values are base64 in both domains (the
|
|
50
|
+
// gRPC HTTP/2 spec base64s them; so does the JSON wire).
|
|
51
|
+
const toDcMetadata = (headers) => {
|
|
52
|
+
const meta = {};
|
|
53
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
54
|
+
if (k.startsWith(":") || typeof v !== "string") continue;
|
|
55
|
+
if (["content-type", "grpc-status", "grpc-message", "grpc-encoding", "grpc-accept-encoding"].includes(k)) continue;
|
|
56
|
+
meta[k] = v;
|
|
57
|
+
}
|
|
58
|
+
return meta;
|
|
59
|
+
};
|
|
48
60
|
if (frame.type === FrameType.HEADERS) {
|
|
49
61
|
const head = parseHeaders(frame.payload);
|
|
50
62
|
const metadata = {};
|
|
@@ -59,25 +71,23 @@ export class Http2DataChannel {
|
|
|
59
71
|
this.#streams.set(id, stream);
|
|
60
72
|
this.#buffers.set(id, Buffer.alloc(0));
|
|
61
73
|
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
|
-
}
|
|
66
74
|
const trailersOnly =
|
|
67
75
|
(flags & http2.constants.NGHTTP2_FLAG_END_STREAM) !== 0 && headers["grpc-status"] !== undefined;
|
|
68
76
|
if (trailersOnly) {
|
|
69
77
|
this.#emitFrame(FrameType.TRAILERS, id, JSON.stringify({
|
|
70
78
|
code: Number(headers["grpc-status"]),
|
|
71
79
|
message: decodeURIComponent(headers["grpc-message"] ?? ""),
|
|
80
|
+
metadata: toDcMetadata(headers),
|
|
72
81
|
}));
|
|
73
82
|
} else {
|
|
74
|
-
this.#emitFrame(FrameType.HEADERS, id, JSON.stringify({ metadata:
|
|
83
|
+
this.#emitFrame(FrameType.HEADERS, id, JSON.stringify({ metadata: toDcMetadata(headers) }));
|
|
75
84
|
}
|
|
76
85
|
});
|
|
77
86
|
stream.on("trailers", (headers) => {
|
|
78
87
|
this.#emitFrame(FrameType.TRAILERS, id, JSON.stringify({
|
|
79
88
|
code: Number(headers["grpc-status"] ?? 2),
|
|
80
89
|
message: decodeURIComponent(headers["grpc-message"] ?? ""),
|
|
90
|
+
metadata: toDcMetadata(headers),
|
|
81
91
|
}));
|
|
82
92
|
});
|
|
83
93
|
stream.on("data", (chunk) => {
|
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,
|
|
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);
|