grpc-dc 0.32.15 → 0.33.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/index.d.ts +55 -0
- package/index.js +11 -0
- package/package.json +4 -3
- package/plugin/gen/generators.js +27 -12
- package/src/channel.js +109 -4
- package/src/eventbus.js +249 -0
- package/src/eventbus_gitlog.js +126 -0
- package/src/events_grpc_dc.js +25 -0
- package/src/events_pb.js +298 -0
package/index.d.ts
CHANGED
|
@@ -115,6 +115,61 @@ export declare function createPeer(
|
|
|
115
115
|
options?: { parity?: "odd" | "even" },
|
|
116
116
|
): { endpoint: Endpoint; server: Server; channel: Channel };
|
|
117
117
|
|
|
118
|
+
// Event bus (grpcdc.events.v1): message/stub types live in
|
|
119
|
+
// grpc-dc's generated events_pb/events_grpc_dc modules; these
|
|
120
|
+
// are the broker and helpers over them. TagValue/Event are
|
|
121
|
+
// structural here so the plain-JS generated classes satisfy
|
|
122
|
+
// them without casts.
|
|
123
|
+
export interface TagValueLike {
|
|
124
|
+
tag: number;
|
|
125
|
+
stringValue?: string;
|
|
126
|
+
intValue?: bigint;
|
|
127
|
+
doubleValue?: number;
|
|
128
|
+
boolValue?: boolean;
|
|
129
|
+
enumValue?: number;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface BusEvent {
|
|
133
|
+
tags: TagValueLike[];
|
|
134
|
+
payload: Uint8Array;
|
|
135
|
+
seq: bigint;
|
|
136
|
+
publisherId: string;
|
|
137
|
+
timestampUnixMs: bigint;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export declare function tagString(tag: number, value: string): TagValueLike;
|
|
141
|
+
export declare function tagInt(tag: number, value: bigint | number): TagValueLike;
|
|
142
|
+
export declare function tagDouble(tag: number, value: number): TagValueLike;
|
|
143
|
+
export declare function tagBool(tag: number, value: boolean): TagValueLike;
|
|
144
|
+
export declare function tagEnum(tag: number, value: number): TagValueLike;
|
|
145
|
+
export declare function tagsMatch(
|
|
146
|
+
eventTags: TagValueLike[],
|
|
147
|
+
filter: TagValueLike[],
|
|
148
|
+
): boolean;
|
|
149
|
+
|
|
150
|
+
export declare class EventBusBroker {
|
|
151
|
+
constructor(options?: { queueCapacity?: number });
|
|
152
|
+
publishEvent(
|
|
153
|
+
tags: TagValueLike[],
|
|
154
|
+
payload: Uint8Array,
|
|
155
|
+
publisherId?: string,
|
|
156
|
+
): BusEvent;
|
|
157
|
+
stats(): { published: number; subscribers: number; dropped: number };
|
|
158
|
+
register(server: Server): EventBusBroker;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export declare function publishEvent(
|
|
162
|
+
client: unknown,
|
|
163
|
+
tags: TagValueLike[],
|
|
164
|
+
payload: Uint8Array,
|
|
165
|
+
publisherId?: string,
|
|
166
|
+
): Promise<bigint>;
|
|
167
|
+
|
|
168
|
+
export declare function subscribeEvents(
|
|
169
|
+
client: unknown,
|
|
170
|
+
filter: TagValueLike[],
|
|
171
|
+
): Promise<AsyncIterable<BusEvent>>;
|
|
172
|
+
|
|
118
173
|
export declare class GenericMessage {
|
|
119
174
|
constructor(model?: unknown);
|
|
120
175
|
set(number: number, value: unknown): void;
|
package/index.js
CHANGED
|
@@ -17,6 +17,17 @@ export {
|
|
|
17
17
|
fromHex,
|
|
18
18
|
} from "./src/codec.js";
|
|
19
19
|
export { Endpoint, StreamInput } from "./src/endpoint.js";
|
|
20
|
+
export {
|
|
21
|
+
EventBusBroker,
|
|
22
|
+
publishEvent,
|
|
23
|
+
subscribeEvents,
|
|
24
|
+
tagBool,
|
|
25
|
+
tagDouble,
|
|
26
|
+
tagEnum,
|
|
27
|
+
tagInt,
|
|
28
|
+
tagString,
|
|
29
|
+
tagsMatch,
|
|
30
|
+
} from "./src/eventbus.js";
|
|
20
31
|
export { Channel } from "./src/channel.js";
|
|
21
32
|
export { Server } from "./src/server.js";
|
|
22
33
|
export { memoryDataChannelPair } from "./src/loopback.js";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "grpc-dc",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "gRPC in the browser over WebRTC DataChannels: dependency-free generated gRPC clients & servers for JavaScript
|
|
3
|
+
"version": "0.33.0",
|
|
4
|
+
"description": "gRPC in the browser over WebRTC DataChannels: dependency-free generated gRPC clients & servers for JavaScript \u2014 no grpc-web proxy, no external runtime",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"grpc",
|
|
7
7
|
"grpc-web",
|
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
},
|
|
30
30
|
"./wire_gen.js": "./wire_gen.js",
|
|
31
31
|
"./webrtc_direct": "./src/webrtc_direct.js",
|
|
32
|
-
"./http2": "./src/http2.js"
|
|
32
|
+
"./http2": "./src/http2.js",
|
|
33
|
+
"./eventbus_gitlog": "./src/eventbus_gitlog.js"
|
|
33
34
|
},
|
|
34
35
|
"bin": {
|
|
35
36
|
"protoc-gen-grpc-dc-js": "plugin/protoc-gen-grpc-dc-js.mjs",
|
package/plugin/gen/generators.js
CHANGED
|
@@ -1525,7 +1525,7 @@ function emitGoFile(model, params) {
|
|
|
1525
1525
|
+ 'package ' + goPackage(model, params) + '\n\n'
|
|
1526
1526
|
+ (model.services.length === 0
|
|
1527
1527
|
? ''
|
|
1528
|
-
: 'import (\n\t"context"\n\n\tgrpcdc "
|
|
1528
|
+
: 'import (\n\t"context"\n\n\tgrpcdc "' + GO_MODULE_PATH + '"\n)\n\n')
|
|
1529
1529
|
+ model.services.map(goService).join(''),
|
|
1530
1530
|
};
|
|
1531
1531
|
const pb = emitGoPbFile(model, params);
|
|
@@ -2990,7 +2990,15 @@ export function generateFiles(lang, setBytes, entries, parameter) {
|
|
|
2990
2990
|
for (const f of Array.isArray(produced) ? produced : [produced]) if (f) files.push(f);
|
|
2991
2991
|
}
|
|
2992
2992
|
return files.map(stampGeneratedHeader);
|
|
2993
|
-
}
|
|
2993
|
+
}const RP_ENUM_SHAPE = {"defaultMark":"#[default]\n ","fromArm":" ~a => ~a::~a,\n","header":"#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]\n#[repr(i32)]\npub enum ~a {\n","implOpen":"impl ~a {\n pub fn from_i32(v: i32) -> Self {\n match v {\n","toArm":" ~a::~a => ~a,\n","toOpen":" pub fn to_i32(self) -> i32 {\n match self {\n","unknownFromArm":" _ => ~a::Unknown(v),\n }\n }\n","unknownToArm":" ~a::Unknown(v) => v,\n }\n }\n}\n\n","unknownVariant":" Unknown(i32),\n}\n\n","value":" ~a~a = ~a,\n"};
|
|
2994
|
+
const GO_MODULE_PATH = "github.com/browser-grpc/grpc-over-datachannels/go";
|
|
2995
|
+
|
|
2996
|
+
function rpFmt(template, ...args) {
|
|
2997
|
+
let i = 0;
|
|
2998
|
+
return template.replace(/~a/g, () => String(args[i++]));
|
|
2999
|
+
}
|
|
3000
|
+
|
|
3001
|
+
// ---------------------------------------------------------------------------
|
|
2994
3002
|
// Rust emitter (mirrors the native rust template).
|
|
2995
3003
|
// ---------------------------------------------------------------------------
|
|
2996
3004
|
|
|
@@ -3213,7 +3221,7 @@ function rpVarintExpr(f, v) {
|
|
|
3213
3221
|
function rpVarintDecode(f, v) {
|
|
3214
3222
|
switch (f.type) {
|
|
3215
3223
|
case 5: case 15: return '(' + v + ' as u32 as i32)';
|
|
3216
|
-
case 14: return
|
|
3224
|
+
case 14: return v + '.to_i32()';
|
|
3217
3225
|
case 13: case 7: return '(' + v + ' as u32)';
|
|
3218
3226
|
case 8: return '(' + v + ' != 0)';
|
|
3219
3227
|
case 17: return '(((' + v + ' as u32 >> 1) as i32) ^ (-(((' + v + ' as u32) & 1) as i32)))';
|
|
@@ -3259,7 +3267,7 @@ function rpEncodeSingular(model, f, v, indent) {
|
|
|
3259
3267
|
const n = f.number;
|
|
3260
3268
|
const proto2 = model.syntax === 'proto2';
|
|
3261
3269
|
if (RP_VARINT.has(f.type)) {
|
|
3262
|
-
const expr = f.type === 14 ? '(' + v + ' as
|
|
3270
|
+
const expr = f.type === 14 ? '(' + v + '.to_i32() as u64)' : rpVarintExpr(f, v);
|
|
3263
3271
|
if (proto2) {
|
|
3264
3272
|
return indent + '{ pb_append_tag(&mut out, ' + n + ', 0); pb_append_varint(&mut out, ' + expr + '); }\n';
|
|
3265
3273
|
}
|
|
@@ -3290,7 +3298,7 @@ function rpSetExpr(sib) {
|
|
|
3290
3298
|
case 11: case 10: return v + '.is_some()';
|
|
3291
3299
|
case 9: case 12: return '!' + v + '.is_empty()';
|
|
3292
3300
|
case 8: return v;
|
|
3293
|
-
case 14: return
|
|
3301
|
+
case 14: return v + '.to_i32() != 0';
|
|
3294
3302
|
case 1: case 2: return v + ' != 0.0';
|
|
3295
3303
|
default: return v + ' != 0';
|
|
3296
3304
|
}
|
|
@@ -3326,7 +3334,7 @@ function rpEncodeField(model, f) {
|
|
|
3326
3334
|
if (f.label !== 3) return rpEncodeSingular(model, f, v, ' ');
|
|
3327
3335
|
if (RP_VARINT.has(f.type)) {
|
|
3328
3336
|
return ' if !' + v + '.is_empty() {\n let mut payload = Vec::new();\n'
|
|
3329
|
-
+ ' for x in &' + v + ' { pb_append_varint(&mut payload, ' + (f.type === 14 ? '(*x as
|
|
3337
|
+
+ ' for x in &' + v + ' { pb_append_varint(&mut payload, ' + (f.type === 14 ? '((*x).to_i32() as u64)' : rpVarintExpr(f, '(*x)')) + '); }\n'
|
|
3330
3338
|
+ ' pb_append_bytes_field(&mut out, ' + n + ', &payload);\n }\n';
|
|
3331
3339
|
}
|
|
3332
3340
|
if (rpFixedInfo(f)) {
|
|
@@ -3460,12 +3468,19 @@ function rpMapHelpers(model, entry) {
|
|
|
3460
3468
|
|
|
3461
3469
|
function rpEnumNamed(model, full, e) {
|
|
3462
3470
|
const name = rpFlat(model.package, full);
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
+
|
|
3471
|
+
// Static text comes from RP_ENUM_SHAPE, serialized from the
|
|
3472
|
+
// shared rust-enum-shape table in spec.rkt (same source the
|
|
3473
|
+
// native template formats) — edit the table, not this code.
|
|
3474
|
+
const S = RP_ENUM_SHAPE;
|
|
3475
|
+
return rpFmt(S.header, name)
|
|
3476
|
+
+ e.values.map((v, i) => rpFmt(S.value, i === 0 ? S.defaultMark : '', rpCamel(v.name), v.number)).join('')
|
|
3477
|
+
+ S.unknownVariant
|
|
3478
|
+
+ rpFmt(S.implOpen, name)
|
|
3479
|
+
+ e.values.map((v) => rpFmt(S.fromArm, v.number, name, rpCamel(v.name))).join('')
|
|
3480
|
+
+ rpFmt(S.unknownFromArm, name)
|
|
3481
|
+
+ S.toOpen
|
|
3482
|
+
+ e.values.map((v) => rpFmt(S.toArm, name, rpCamel(v.name), v.number)).join('')
|
|
3483
|
+
+ rpFmt(S.unknownToArm, name);
|
|
3469
3484
|
}
|
|
3470
3485
|
|
|
3471
3486
|
function rpMessageStruct(model, msg) {
|
package/src/channel.js
CHANGED
|
@@ -19,6 +19,72 @@ import {
|
|
|
19
19
|
} from "./codec.js";
|
|
20
20
|
import { Endpoint } from "./endpoint.js";
|
|
21
21
|
|
|
22
|
+
// AsyncIterable wrapper whose iterator keeps ONE read in
|
|
23
|
+
// flight at a time (no read-ahead). for-await on an async
|
|
24
|
+
// generator runs next() with no pipelining, so by the time a
|
|
25
|
+
// consumer breaks, the generator may already be parked in a
|
|
26
|
+
// read for an event nobody will consume; unwinding then has
|
|
27
|
+
// to wait for that read to settle, which for a quiet
|
|
28
|
+
// server-streaming call may be never. This wrapper hands the
|
|
29
|
+
// consumer an iterator over a one-slot queue instead: the
|
|
30
|
+
// inner generator is pumped into the queue only as fast as
|
|
31
|
+
// events arrive, .return() releases the consumer immediately,
|
|
32
|
+
// and the abandoned pump is dropped (its pending read is
|
|
33
|
+
// released by the cancel: the RST makes the server end the
|
|
34
|
+
// call, which settles the read with trailers).
|
|
35
|
+
function responsesIterable(inner, cancel) {
|
|
36
|
+
return {
|
|
37
|
+
[Symbol.asyncIterator]() {
|
|
38
|
+
const iterator = inner[Symbol.asyncIterator]();
|
|
39
|
+
const queue = [];
|
|
40
|
+
let waiter = null;
|
|
41
|
+
let done = false;
|
|
42
|
+
let failure = null;
|
|
43
|
+
const notify = () => {
|
|
44
|
+
if (waiter) {
|
|
45
|
+
const wake = waiter;
|
|
46
|
+
waiter = null;
|
|
47
|
+
wake();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
(async () => {
|
|
51
|
+
try {
|
|
52
|
+
for (;;) {
|
|
53
|
+
const step = await iterator.next();
|
|
54
|
+
if (step.done) break;
|
|
55
|
+
queue.push(step.value);
|
|
56
|
+
notify();
|
|
57
|
+
}
|
|
58
|
+
} catch (e) {
|
|
59
|
+
failure = e;
|
|
60
|
+
} finally {
|
|
61
|
+
done = true;
|
|
62
|
+
notify();
|
|
63
|
+
}
|
|
64
|
+
})();
|
|
65
|
+
return {
|
|
66
|
+
[Symbol.asyncIterator]() {
|
|
67
|
+
return this;
|
|
68
|
+
},
|
|
69
|
+
async next() {
|
|
70
|
+
for (;;) {
|
|
71
|
+
if (queue.length) return { value: queue.shift(), done: false };
|
|
72
|
+
if (failure) throw failure;
|
|
73
|
+
if (done) return { value: undefined, done: true };
|
|
74
|
+
await new Promise((resolve) => { waiter = resolve; });
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
async return(value) {
|
|
78
|
+
done = true;
|
|
79
|
+
cancel();
|
|
80
|
+
notify();
|
|
81
|
+
return { value, done: true };
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
22
88
|
export class Channel {
|
|
23
89
|
#endpoint;
|
|
24
90
|
#traces = new Map();
|
|
@@ -153,9 +219,40 @@ export class Channel {
|
|
|
153
219
|
async *#responses(id, input, RespType, deadline = null, hooks = {}) {
|
|
154
220
|
const iterator = input[Symbol.asyncIterator]();
|
|
155
221
|
let completed = false;
|
|
222
|
+
// A caller-owned ReadHandle makes `.return()` asynchronous
|
|
223
|
+
// with an internal queue, so wrapping the iterator handed
|
|
224
|
+
// to the consumer in a pausable shim is what lets a break
|
|
225
|
+
// actually cancel the call. The shim carries no buffering:
|
|
226
|
+
// events are pulled one at a time straight from `iterator`.
|
|
227
|
+
const consumer = {
|
|
228
|
+
[Symbol.asyncIterator]() {
|
|
229
|
+
return this;
|
|
230
|
+
},
|
|
231
|
+
next: () => this.#next(id, iterator, deadline),
|
|
232
|
+
return: async () => {
|
|
233
|
+
completed = false;
|
|
234
|
+
this.#endpoint.cancelStream(id);
|
|
235
|
+
return { value: undefined, done: true };
|
|
236
|
+
},
|
|
237
|
+
};
|
|
238
|
+
// The in-flight read and its abort: StreamInput resolves a
|
|
239
|
+
// pending read only on stream events, and the endpoint
|
|
240
|
+
// deliberately never fails locally-initiated streams, so
|
|
241
|
+
// on early exit (.return()) nothing else would release a
|
|
242
|
+
// read the race below abandoned. The abort fails that read
|
|
243
|
+
// with CANCELLED, which propagates out of the abandoned
|
|
244
|
+
// read without disturbing the yielded-event flow.
|
|
245
|
+
let abortReading = null;
|
|
156
246
|
try {
|
|
157
247
|
for (;;) {
|
|
158
|
-
const step = await
|
|
248
|
+
const step = await new Promise((resolve, reject) => {
|
|
249
|
+
abortReading = () =>
|
|
250
|
+
reject(new StatusError(StatusCode.CANCELLED, "call cancelled"));
|
|
251
|
+
consumer.next().then(
|
|
252
|
+
(s) => { abortReading = null; resolve(s); },
|
|
253
|
+
(e) => { abortReading = null; reject(e); },
|
|
254
|
+
);
|
|
255
|
+
});
|
|
159
256
|
if (step.done) break;
|
|
160
257
|
const event = step.value;
|
|
161
258
|
if (event.kind === "headers") {
|
|
@@ -179,7 +276,15 @@ export class Channel {
|
|
|
179
276
|
this.#endTrace(id, "UNAVAILABLE");
|
|
180
277
|
// Consumer stopped early (broke out of iteration): cancel
|
|
181
278
|
// so the server stops producing instead of streaming into
|
|
182
|
-
// the void. A completed call just closes locally.
|
|
279
|
+
// the void. A completed call just closes locally. This
|
|
280
|
+
// finally runs while the abandoned read above is still
|
|
281
|
+
// pending; abort it so its rejection cannot surface as an
|
|
282
|
+
// unhandled rejection after this generator completes.
|
|
283
|
+
if (abortReading) {
|
|
284
|
+
const abort = abortReading;
|
|
285
|
+
abortReading = null;
|
|
286
|
+
abort();
|
|
287
|
+
}
|
|
183
288
|
if (completed) this.#endpoint.closeStream(id);
|
|
184
289
|
else this.#endpoint.cancelStream(id);
|
|
185
290
|
}
|
|
@@ -213,7 +318,7 @@ export class Channel {
|
|
|
213
318
|
const [id, input, deadline] = await this.#open(path, metadata, timeout, signal);
|
|
214
319
|
await this.#sendMessage(id, ReqType, request);
|
|
215
320
|
await this.#endpoint.sendFrame(encodeFrame(FrameType.HALF_CLOSE, id));
|
|
216
|
-
return this.#responses(id, input, RespType, deadline, { onHeaders, onTrailers });
|
|
321
|
+
return responsesIterable(this.#responses(id, input, RespType, deadline, { onHeaders, onTrailers }), () => this.#endpoint.cancelStream(id));
|
|
217
322
|
})();
|
|
218
323
|
}
|
|
219
324
|
|
|
@@ -234,7 +339,7 @@ export class Channel {
|
|
|
234
339
|
const [id, input, deadline] = await this.#open(path, metadata, timeout, signal);
|
|
235
340
|
const pump = this.#pump(id, requests, ReqType);
|
|
236
341
|
pump.catch(() => {});
|
|
237
|
-
return this.#responses(id, input, RespType, deadline, { onHeaders, onTrailers });
|
|
342
|
+
return responsesIterable(this.#responses(id, input, RespType, deadline, { onHeaders, onTrailers }), () => this.#endpoint.cancelStream(id));
|
|
238
343
|
})();
|
|
239
344
|
}
|
|
240
345
|
|
package/src/eventbus.js
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// @generated by grpc-dc codegen. DO NOT EDIT.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// Event bus (grpcdc.events.v1.EventBus): in-memory broker,
|
|
4
|
+
// client helpers, and tag matching. Wire messages and stubs
|
|
5
|
+
// are generated from proto/events.proto (events_pb.js,
|
|
6
|
+
// events_grpc_dc.js); the broker policy comes from the shared
|
|
7
|
+
// event-bus spec.
|
|
8
|
+
//
|
|
9
|
+
// Delivery is at-most-once: each subscriber has a bounded
|
|
10
|
+
// queue (SUBSCRIBER_QUEUE_CAPACITY) and drops its oldest
|
|
11
|
+
// events when it falls behind; stats() reports the drops.
|
|
12
|
+
|
|
13
|
+
import { createEventBusService, EventBusClient } from "./events_grpc_dc.js";
|
|
14
|
+
import { Event, PublishReply, PublishRequest, SubscribeRequest, TagValue } from "./events_pb.js";
|
|
15
|
+
|
|
16
|
+
export const SUBSCRIBER_QUEUE_CAPACITY = 128;
|
|
17
|
+
|
|
18
|
+
const _doubleView = new DataView(new ArrayBuffer(8));
|
|
19
|
+
|
|
20
|
+
function doubleBits(value) {
|
|
21
|
+
_doubleView.setFloat64(0, value);
|
|
22
|
+
return _doubleView.getBigUint64(0).toString(16).padStart(16, "0");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Canonical identity of one tag value. The oneof kind is part
|
|
26
|
+
// of the identity (int 5 != "5" != enum 5). Kinds are told
|
|
27
|
+
// apart by value, so an all-default TagValue reads as the
|
|
28
|
+
// empty string value; numbers compare bit-exact, never via
|
|
29
|
+
// decimal text.
|
|
30
|
+
function valueKey(tv) {
|
|
31
|
+
if (tv.stringValue !== "") return `s:${tv.stringValue}`;
|
|
32
|
+
if (tv.intValue !== 0n) return `i:${tv.intValue.toString()}`;
|
|
33
|
+
if (tv.doubleValue !== 0) return `d:${doubleBits(tv.doubleValue)}`;
|
|
34
|
+
if (tv.boolValue) return "b:true";
|
|
35
|
+
if (tv.enumValue !== 0) return `e:${tv.enumValue}`;
|
|
36
|
+
return "s:";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Stable key for one TagValue, e.g. "1|s:orders".
|
|
40
|
+
export function tagValueKey(tv) {
|
|
41
|
+
return `${tv.tag}|${valueKey(tv)}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Containment match: the event is delivered when its tag list
|
|
45
|
+
// contains every (tag, value) pair of the filter. An empty
|
|
46
|
+
// filter matches everything.
|
|
47
|
+
export function tagsMatch(eventTags, filter) {
|
|
48
|
+
if (!filter || filter.length === 0) return true;
|
|
49
|
+
const have = new Set();
|
|
50
|
+
for (const tv of eventTags ?? []) have.add(tagValueKey(tv));
|
|
51
|
+
return filter.every((f) => have.has(tagValueKey(f)));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function tagString(tag, value) {
|
|
55
|
+
return new TagValue({ tag, stringValue: String(value) });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function tagInt(tag, value) {
|
|
59
|
+
return new TagValue({ tag, intValue: BigInt(value) });
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function tagDouble(tag, value) {
|
|
63
|
+
return new TagValue({ tag, doubleValue: value });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function tagBool(tag, value) {
|
|
67
|
+
return new TagValue({ tag, boolValue: Boolean(value) });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function tagEnum(tag, value) {
|
|
71
|
+
return new TagValue({ tag, enumValue: value | 0 });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
class Subscriber {
|
|
75
|
+
constructor(filter, capacity) {
|
|
76
|
+
this.filter = filter;
|
|
77
|
+
this.capacity = capacity;
|
|
78
|
+
this.queue = [];
|
|
79
|
+
this.waiter = null;
|
|
80
|
+
this.dropped = 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
push(event) {
|
|
84
|
+
let dropped = false;
|
|
85
|
+
if (this.queue.length >= this.capacity) {
|
|
86
|
+
this.queue.shift();
|
|
87
|
+
this.dropped += 1;
|
|
88
|
+
dropped = true;
|
|
89
|
+
}
|
|
90
|
+
this.queue.push(event);
|
|
91
|
+
if (this.waiter) {
|
|
92
|
+
const waiter = this.waiter;
|
|
93
|
+
this.waiter = null;
|
|
94
|
+
waiter();
|
|
95
|
+
}
|
|
96
|
+
return dropped;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Next queued event, or null when the wait times out. The
|
|
100
|
+
// broker re-checks every tick; a cancelled call is reaped
|
|
101
|
+
// when its next matching send fails (the runtime surfaces
|
|
102
|
+
// cancellation only at send time).
|
|
103
|
+
async take(timeoutMs) {
|
|
104
|
+
if (this.queue.length > 0) return this.queue.shift();
|
|
105
|
+
await new Promise((resolve) => {
|
|
106
|
+
const wake = () => {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
if (this.waiter === wake) this.waiter = null;
|
|
109
|
+
resolve();
|
|
110
|
+
};
|
|
111
|
+
const timer = setTimeout(wake, timeoutMs);
|
|
112
|
+
this.waiter = wake;
|
|
113
|
+
});
|
|
114
|
+
return this.queue.length > 0 ? this.queue.shift() : null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// In-memory grpcdc.events.v1.EventBus broker. Any peer can
|
|
119
|
+
// host it: register() it on a Server next to your own
|
|
120
|
+
// services, or call publishEvent() directly in-process.
|
|
121
|
+
export class EventBusBroker {
|
|
122
|
+
#subscribers = new Set();
|
|
123
|
+
#seq = 0;
|
|
124
|
+
#published = 0;
|
|
125
|
+
#dropped = 0;
|
|
126
|
+
|
|
127
|
+
constructor({ queueCapacity = SUBSCRIBER_QUEUE_CAPACITY } = {}) {
|
|
128
|
+
this.queueCapacity = queueCapacity;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Accept an event: assign its sequence number and timestamp
|
|
132
|
+
// and fan it out to matching subscribers. Returns the
|
|
133
|
+
// stamped Event.
|
|
134
|
+
publishEvent(tags, payload, publisherId = "") {
|
|
135
|
+
const event = new Event({
|
|
136
|
+
tags: [...(tags ?? [])],
|
|
137
|
+
payload: payload ?? new Uint8Array(0),
|
|
138
|
+
seq: BigInt(++this.#seq),
|
|
139
|
+
publisherId: publisherId ?? "",
|
|
140
|
+
timestampUnixMs: BigInt(Date.now()),
|
|
141
|
+
});
|
|
142
|
+
this.#published += 1;
|
|
143
|
+
for (const sub of this.#subscribers) {
|
|
144
|
+
if (tagsMatch(event.tags, sub.filter) && sub.push(event)) {
|
|
145
|
+
this.#dropped += 1;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return event;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
stats() {
|
|
152
|
+
return {
|
|
153
|
+
published: this.#published,
|
|
154
|
+
subscribers: this.#subscribers.size,
|
|
155
|
+
dropped: this.#dropped,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// In-process subscription: events fan out to it exactly
|
|
160
|
+
// like an RPC subscriber, without a call. Useful embedded
|
|
161
|
+
// and for tests; close() unregisters.
|
|
162
|
+
subscribeLocal(filter) {
|
|
163
|
+
const sub = new Subscriber(filter ?? [], this.queueCapacity);
|
|
164
|
+
this.#subscribers.add(sub);
|
|
165
|
+
return new LocalSubscription(sub, () => this.#subscribers.delete(sub));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
serviceHandlers() {
|
|
169
|
+
const broker = this;
|
|
170
|
+
return {
|
|
171
|
+
async publish(req) {
|
|
172
|
+
const event = broker.publishEvent(req.tags, req.payload, req.publisherId);
|
|
173
|
+
return new PublishReply({ seq: event.seq });
|
|
174
|
+
},
|
|
175
|
+
async *subscribe(req) {
|
|
176
|
+
const sub = new Subscriber(req.filter ?? [], broker.queueCapacity);
|
|
177
|
+
broker.#subscribers.add(sub);
|
|
178
|
+
try {
|
|
179
|
+
for (;;) {
|
|
180
|
+
const event = await sub.take(100);
|
|
181
|
+
if (event !== null) yield event;
|
|
182
|
+
}
|
|
183
|
+
} finally {
|
|
184
|
+
broker.#subscribers.delete(sub);
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
service() {
|
|
191
|
+
return createEventBusService(this.serviceHandlers());
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
register(server) {
|
|
195
|
+
server.addService(this.service());
|
|
196
|
+
return this;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Handle for EventBusBroker.subscribeLocal: pull events
|
|
201
|
+
// in-process. take() resolves to the next event, or null on
|
|
202
|
+
// timeout; dropped counts this subscription's drop-oldest
|
|
203
|
+
// losses.
|
|
204
|
+
export class LocalSubscription {
|
|
205
|
+
#sub;
|
|
206
|
+
#unregister;
|
|
207
|
+
constructor(sub, unregister) {
|
|
208
|
+
this.#sub = sub;
|
|
209
|
+
this.#unregister = unregister;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
get dropped() {
|
|
213
|
+
return this.#sub.dropped;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async take(timeoutMs = 1000) {
|
|
217
|
+
const deadline = Date.now() + timeoutMs;
|
|
218
|
+
for (;;) {
|
|
219
|
+
const event = await this.#sub.take(Math.max(0, deadline - Date.now()));
|
|
220
|
+
if (event !== null || Date.now() >= deadline) return event;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
close() {
|
|
225
|
+
this.#unregister();
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Publish through a generated EventBusClient; resolves to the
|
|
230
|
+
// broker-assigned sequence number (a BigInt).
|
|
231
|
+
export async function publishEvent(client, tags, payload, publisherId = "") {
|
|
232
|
+
const reply = await client.publish(
|
|
233
|
+
new PublishRequest({
|
|
234
|
+
tags: tags ?? [],
|
|
235
|
+
payload: payload ?? new Uint8Array(0),
|
|
236
|
+
publisherId: publisherId ?? "",
|
|
237
|
+
}),
|
|
238
|
+
);
|
|
239
|
+
return reply.seq;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Subscribe through a generated EventBusClient; resolves to an
|
|
243
|
+
// async iterable of Event. Breaking out of the iteration
|
|
244
|
+
// cancels the call and unsubscribes.
|
|
245
|
+
export function subscribeEvents(client, filter) {
|
|
246
|
+
return client.subscribe(new SubscribeRequest({ filter: filter ?? [] }));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export { EventBusClient };
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// @generated by grpc-dc codegen. DO NOT EDIT.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// Git log serde for the event bus (Node only): exports an
|
|
4
|
+
// event log to a git branch (one commit per event) and
|
|
5
|
+
// imports it back. The live broker never touches git; this is
|
|
6
|
+
// the durable serde layer beside it.
|
|
7
|
+
//
|
|
8
|
+
// Deterministic: the same events always produce the same
|
|
9
|
+
// commits, so re-exporting a log the branch already has is a
|
|
10
|
+
// no-op (each event's sequence number is the dedup key). The
|
|
11
|
+
// commit blob (event.pb) is authoritative; the message subject and
|
|
12
|
+
// trailers are a human index for `git log`.
|
|
13
|
+
|
|
14
|
+
import { execFileSync } from "node:child_process";
|
|
15
|
+
|
|
16
|
+
import { Event } from "./events_pb.js";
|
|
17
|
+
import { tagValueKey, tagsMatch } from "./eventbus.js";
|
|
18
|
+
|
|
19
|
+
const AUTHOR_NAME = "grpc-dc eventbus";
|
|
20
|
+
const AUTHOR_EMAIL = "eventbus@grpc-dc.local";
|
|
21
|
+
const BLOB_PATH = "event.pb";
|
|
22
|
+
const COMMIT_SUBJECT = "grpc-dc event";
|
|
23
|
+
const ZERO_SHA = "0".repeat(40);
|
|
24
|
+
|
|
25
|
+
export const EVENT_LOG_BRANCH = "grpc-dc-events";
|
|
26
|
+
|
|
27
|
+
function gitText(repo, args, { input, env } = {}) {
|
|
28
|
+
return execFileSync("git", ["-C", repo, ...args], {
|
|
29
|
+
input,
|
|
30
|
+
env: env ? { ...process.env, ...env } : process.env,
|
|
31
|
+
encoding: "utf8",
|
|
32
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
33
|
+
}).trim();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function gitBytes(repo, args) {
|
|
37
|
+
return execFileSync("git", ["-C", repo, ...args], {
|
|
38
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Create the log repo if needed (a plain `git init`).
|
|
43
|
+
export function initEventLogRepo(repo) {
|
|
44
|
+
try {
|
|
45
|
+
gitText(repo, ["rev-parse", "--git-dir"]);
|
|
46
|
+
} catch {
|
|
47
|
+
execFileSync("git", ["init", "-q", repo], { encoding: "utf8" });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function branchHead(repo, branch) {
|
|
52
|
+
try {
|
|
53
|
+
return gitText(repo, ["rev-parse", "--verify", `refs/heads/${branch}`]);
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// "grpc-dc event 42" plus Seq/Publisher/Tag trailers, so
|
|
60
|
+
// `git log` alone can filter the log without decoding blobs.
|
|
61
|
+
export function commitMessage(event) {
|
|
62
|
+
const lines = [`${COMMIT_SUBJECT} ${event.seq}`, "", `Seq: ${event.seq}`];
|
|
63
|
+
if (event.publisherId) lines.push(`Publisher: ${event.publisherId}`);
|
|
64
|
+
for (const tv of event.tags) lines.push(`Tag: ${tagValueKey(tv)}`);
|
|
65
|
+
return lines.join("\n") + "\n";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function commitEnv(event) {
|
|
69
|
+
const seconds = Math.max(0, Math.floor(Number(event.timestampUnixMs) / 1000));
|
|
70
|
+
const date = `${seconds} +0000`;
|
|
71
|
+
return {
|
|
72
|
+
GIT_AUTHOR_NAME: AUTHOR_NAME,
|
|
73
|
+
GIT_AUTHOR_EMAIL: AUTHOR_EMAIL,
|
|
74
|
+
GIT_COMMITTER_NAME: AUTHOR_NAME,
|
|
75
|
+
GIT_COMMITTER_EMAIL: AUTHOR_EMAIL,
|
|
76
|
+
GIT_AUTHOR_DATE: date,
|
|
77
|
+
GIT_COMMITTER_DATE: date,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Import a branch: events in chain order (oldest first),
|
|
82
|
+
// optionally windowed by sequence number and narrowed by a
|
|
83
|
+
// tag filter (same containment semantics as Subscribe). A
|
|
84
|
+
// missing branch imports as an empty log.
|
|
85
|
+
export function importEvents(repo, branch = EVENT_LOG_BRANCH, { fromSeq = 0n, toSeq = null, filter = null } = {}) {
|
|
86
|
+
if (!branchHead(repo, branch)) return [];
|
|
87
|
+
const shas = gitText(repo, ["rev-list", "--reverse", branch]).split("\n").filter(Boolean);
|
|
88
|
+
const events = [];
|
|
89
|
+
for (const sha of shas) {
|
|
90
|
+
const event = Event.decode(gitBytes(repo, ["cat-file", "-p", `${sha}:${BLOB_PATH}`]));
|
|
91
|
+
if (event.seq <= BigInt(fromSeq)) continue;
|
|
92
|
+
if (toSeq !== null && event.seq > BigInt(toSeq)) continue;
|
|
93
|
+
if (filter && !tagsMatch(event.tags, filter)) continue;
|
|
94
|
+
events.push(event);
|
|
95
|
+
}
|
|
96
|
+
return events;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Export events onto the branch: one commit per event, in
|
|
100
|
+
// sequence order, skipping sequence numbers the branch
|
|
101
|
+
// already has. Returns the new head sha (or the existing one
|
|
102
|
+
// when nothing was appended). The ref update is a
|
|
103
|
+
// compare-and-swap: a concurrent exporter fails loudly
|
|
104
|
+
// instead of forking the log; retrying is safe.
|
|
105
|
+
export function exportEvents(repo, events, branch = EVENT_LOG_BRANCH) {
|
|
106
|
+
initEventLogRepo(repo);
|
|
107
|
+
const existing = new Set(importEvents(repo, branch).map((e) => e.seq.toString()));
|
|
108
|
+
const ordered = [...events].sort((a, b) => (a.seq < b.seq ? -1 : a.seq > b.seq ? 1 : 0));
|
|
109
|
+
let head = branchHead(repo, branch);
|
|
110
|
+
const before = head;
|
|
111
|
+
for (const event of ordered) {
|
|
112
|
+
if (existing.has(event.seq.toString())) continue;
|
|
113
|
+
const blob = gitText(repo, ["hash-object", "-w", "--stdin"], { input: Buffer.from(Event.encode(event)) });
|
|
114
|
+
const tree = gitText(repo, ["mktree"], { input: `100644 blob ${blob}\t${BLOB_PATH}\n` });
|
|
115
|
+
const commitArgs = ["commit-tree", tree, "-m", commitMessage(event)];
|
|
116
|
+
if (head) commitArgs.push("-p", head);
|
|
117
|
+
head = gitText(repo, commitArgs, { env: commitEnv(event) });
|
|
118
|
+
existing.add(event.seq.toString());
|
|
119
|
+
}
|
|
120
|
+
if (head && head !== before) {
|
|
121
|
+
gitText(repo, ["update-ref", `refs/heads/${branch}`, head, before ?? ZERO_SHA]);
|
|
122
|
+
} else if (head && !before) {
|
|
123
|
+
gitText(repo, ["update-ref", `refs/heads/${branch}`, head, ZERO_SHA]);
|
|
124
|
+
}
|
|
125
|
+
return head;
|
|
126
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Generated code: use without restriction (see GENERATED-CODE-LICENSE.md).
|
|
2
|
+
// @generated by protoc-gen-grpc-dc-js. DO NOT EDIT.
|
|
3
|
+
// source: events.proto
|
|
4
|
+
import { PublishRequest, PublishReply, SubscribeRequest, Event } from "./events_pb.js";
|
|
5
|
+
|
|
6
|
+
export class EventBusClient {
|
|
7
|
+
#channel;
|
|
8
|
+
constructor(channel) { this.#channel = channel; }
|
|
9
|
+
async publish(request, options) {
|
|
10
|
+
return this.#channel.unary("/grpcdc.events.v1.EventBus/Publish", request, PublishRequest, PublishReply, options);
|
|
11
|
+
}
|
|
12
|
+
subscribe(request, options) {
|
|
13
|
+
return this.#channel.serverStream("/grpcdc.events.v1.EventBus/Subscribe", request, SubscribeRequest, Event, options);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function createEventBusService(handlers) {
|
|
18
|
+
return {
|
|
19
|
+
name: "grpcdc.events.v1.EventBus",
|
|
20
|
+
methods: {
|
|
21
|
+
Publish: { path: "/grpcdc.events.v1.EventBus/Publish", kind: "unary", requestType: PublishRequest, responseType: PublishReply, handler: handlers.publish },
|
|
22
|
+
Subscribe: { path: "/grpcdc.events.v1.EventBus/Subscribe", kind: "server-streaming", requestType: SubscribeRequest, responseType: Event, handler: handlers.subscribe },
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
package/src/events_pb.js
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
// Generated code: use without restriction (see GENERATED-CODE-LICENSE.md).
|
|
2
|
+
// @generated by protoc-gen-grpc-dc-js. DO NOT EDIT.
|
|
3
|
+
// source: events.proto
|
|
4
|
+
|
|
5
|
+
function varintBytes(value) {
|
|
6
|
+
let n = BigInt.asUintN(64, BigInt(value));
|
|
7
|
+
const out = [];
|
|
8
|
+
while (n > 0x7fn) {
|
|
9
|
+
out.push(Number((n & 0x7fn) | 0x80n));
|
|
10
|
+
n >>= 7n;
|
|
11
|
+
}
|
|
12
|
+
out.push(Number(n));
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function zz64(v) {
|
|
17
|
+
const b = BigInt(v);
|
|
18
|
+
return (b << 1n) ^ (b >> 63n);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function unzz64(v) {
|
|
22
|
+
return (v >> 1n) ^ (-(v & 1n));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
class Reader {
|
|
26
|
+
constructor(bytes) {
|
|
27
|
+
this.bytes = bytes;
|
|
28
|
+
this.pos = 0;
|
|
29
|
+
}
|
|
30
|
+
get done() {
|
|
31
|
+
return this.pos >= this.bytes.length;
|
|
32
|
+
}
|
|
33
|
+
varint() {
|
|
34
|
+
let result = 0n;
|
|
35
|
+
let shift = 0n;
|
|
36
|
+
for (;;) {
|
|
37
|
+
if (this.pos >= this.bytes.length) throw new Error("truncated varint");
|
|
38
|
+
const byte = this.bytes[this.pos++];
|
|
39
|
+
result |= BigInt(byte & 0x7f) << shift;
|
|
40
|
+
if ((byte & 0x80) === 0) return result;
|
|
41
|
+
shift += 7n;
|
|
42
|
+
if (shift >= 64n) throw new Error("varint too long");
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
take(n) {
|
|
46
|
+
const value = this.bytes.slice(this.pos, this.pos + n);
|
|
47
|
+
if (value.length !== n) throw new Error("truncated field");
|
|
48
|
+
this.pos += n;
|
|
49
|
+
return value;
|
|
50
|
+
}
|
|
51
|
+
field() {
|
|
52
|
+
if (this.done) return null;
|
|
53
|
+
const start = this.pos;
|
|
54
|
+
const tag = this.varint();
|
|
55
|
+
const field = Number(tag >> 3n);
|
|
56
|
+
const wire = Number(tag & 7n);
|
|
57
|
+
switch (wire) {
|
|
58
|
+
case 0:
|
|
59
|
+
return [field, wire, this.varint(), this.bytes.slice(start, this.pos)];
|
|
60
|
+
case 2: {
|
|
61
|
+
const len = Number(this.varint());
|
|
62
|
+
const v = this.take(len);
|
|
63
|
+
return [field, wire, v, this.bytes.slice(start, this.pos)];
|
|
64
|
+
}
|
|
65
|
+
case 1: {
|
|
66
|
+
const v = this.take(8);
|
|
67
|
+
return [field, wire, v, this.bytes.slice(start, this.pos)];
|
|
68
|
+
}
|
|
69
|
+
case 5: {
|
|
70
|
+
const v = this.take(4);
|
|
71
|
+
return [field, wire, v, this.bytes.slice(start, this.pos)];
|
|
72
|
+
}
|
|
73
|
+
default:
|
|
74
|
+
throw new Error("bad wire type " + wire);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function concatBytes(a, b) {
|
|
80
|
+
const out = new Uint8Array(a.length + b.length);
|
|
81
|
+
out.set(a);
|
|
82
|
+
out.set(b, a.length);
|
|
83
|
+
return out;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function putRaw(out, bytes) {
|
|
87
|
+
for (let i = 0; i < bytes.length; i++) out.push(bytes[i]);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function putTag(out, num, wire) {
|
|
91
|
+
out.push(...varintBytes((BigInt(num) << 3n) | BigInt(wire)));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function putVarintField(out, num, value) {
|
|
95
|
+
if (value === 0n) return;
|
|
96
|
+
putTag(out, num, 0);
|
|
97
|
+
out.push(...varintBytes(value));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function putBytesField(out, num, payload) {
|
|
101
|
+
putTag(out, num, 2);
|
|
102
|
+
putRaw(out, varintBytes(payload.length));
|
|
103
|
+
putRaw(out, payload);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function putStringField(out, num, value) {
|
|
107
|
+
if (!value) return;
|
|
108
|
+
putBytesField(out, num, new TextEncoder().encode(value));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function putFixedField(out, num, payload) {
|
|
112
|
+
putTag(out, num, payload.length === 8 ? 1 : 5);
|
|
113
|
+
out.push(...payload);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function fixedBytes(value, size, write) {
|
|
117
|
+
const bytes = new Uint8Array(size);
|
|
118
|
+
write(new DataView(bytes.buffer), value);
|
|
119
|
+
return bytes;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function readFixed(bytes, read) {
|
|
123
|
+
return read(new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export const Tag = { TAG_UNSPECIFIED: 0, TOPIC: 1, SOURCE: 2, KIND: 3 };
|
|
127
|
+
|
|
128
|
+
export class TagValue {
|
|
129
|
+
constructor({ tag = 0, stringValue = "", intValue = 0n, doubleValue = 0, boolValue = false, enumValue = 0 } = {}) {
|
|
130
|
+
this.tag = tag;
|
|
131
|
+
this.stringValue = stringValue;
|
|
132
|
+
this.intValue = intValue;
|
|
133
|
+
this.doubleValue = doubleValue;
|
|
134
|
+
this.boolValue = boolValue;
|
|
135
|
+
this.enumValue = enumValue;
|
|
136
|
+
this.unknownFields = new Uint8Array(0);
|
|
137
|
+
}
|
|
138
|
+
static encode(msg) {
|
|
139
|
+
const out = [];
|
|
140
|
+
putVarintField(out, 1, BigInt(msg.tag));
|
|
141
|
+
if (!(msg.intValue !== 0n || msg.doubleValue !== 0 || msg.boolValue || msg.enumValue !== 0)) {
|
|
142
|
+
putStringField(out, 2, msg.stringValue);
|
|
143
|
+
}
|
|
144
|
+
if (!(msg.doubleValue !== 0 || msg.boolValue || msg.enumValue !== 0)) {
|
|
145
|
+
putVarintField(out, 3, BigInt(msg.intValue));
|
|
146
|
+
}
|
|
147
|
+
if (!(msg.boolValue || msg.enumValue !== 0)) {
|
|
148
|
+
if (msg.doubleValue) putFixedField(out, 4, fixedBytes(msg.doubleValue, 8, (dv, x) => dv.setFloat64(0, x, true)));
|
|
149
|
+
}
|
|
150
|
+
if (!(msg.enumValue !== 0)) {
|
|
151
|
+
putVarintField(out, 5, (msg.boolValue ? 1n : 0n));
|
|
152
|
+
}
|
|
153
|
+
putVarintField(out, 6, BigInt(msg.enumValue));
|
|
154
|
+
putRaw(out, msg.unknownFields);
|
|
155
|
+
return new Uint8Array(out);
|
|
156
|
+
}
|
|
157
|
+
static decode(bytes) {
|
|
158
|
+
const msg = new TagValue();
|
|
159
|
+
const reader = new Reader(bytes);
|
|
160
|
+
let f;
|
|
161
|
+
while ((f = reader.field()) !== null) {
|
|
162
|
+
const [num, wire, value, raw] = f;
|
|
163
|
+
switch (num) {
|
|
164
|
+
case 1: msg.tag = Number(BigInt.asIntN(32, value)); break;
|
|
165
|
+
case 2: msg.intValue = 0n; msg.doubleValue = 0; msg.boolValue = false; msg.enumValue = 0; msg.stringValue = new TextDecoder().decode(value); break;
|
|
166
|
+
case 3: msg.stringValue = ""; msg.doubleValue = 0; msg.boolValue = false; msg.enumValue = 0; msg.intValue = BigInt.asIntN(64, value); break;
|
|
167
|
+
case 4: msg.stringValue = ""; msg.intValue = 0n; msg.boolValue = false; msg.enumValue = 0; msg.doubleValue = readFixed(value, (dv) => dv.getFloat64(0, true)); break;
|
|
168
|
+
case 5: msg.stringValue = ""; msg.intValue = 0n; msg.doubleValue = 0; msg.enumValue = 0; msg.boolValue = value !== 0n; break;
|
|
169
|
+
case 6: msg.stringValue = ""; msg.intValue = 0n; msg.doubleValue = 0; msg.boolValue = false; msg.enumValue = Number(BigInt.asIntN(32, value)); break;
|
|
170
|
+
default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return msg;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export class PublishRequest {
|
|
178
|
+
constructor({ tags = [], payload = new Uint8Array(0), publisherId = "" } = {}) {
|
|
179
|
+
this.tags = tags;
|
|
180
|
+
this.payload = payload;
|
|
181
|
+
this.publisherId = publisherId;
|
|
182
|
+
this.unknownFields = new Uint8Array(0);
|
|
183
|
+
}
|
|
184
|
+
static encode(msg) {
|
|
185
|
+
const out = [];
|
|
186
|
+
if (msg.tags) for (const v of msg.tags) putBytesField(out, 1, TagValue.encode(v));
|
|
187
|
+
if (msg.payload && msg.payload.length) putBytesField(out, 2, msg.payload);
|
|
188
|
+
putStringField(out, 3, msg.publisherId);
|
|
189
|
+
putRaw(out, msg.unknownFields);
|
|
190
|
+
return new Uint8Array(out);
|
|
191
|
+
}
|
|
192
|
+
static decode(bytes) {
|
|
193
|
+
const msg = new PublishRequest();
|
|
194
|
+
const reader = new Reader(bytes);
|
|
195
|
+
let f;
|
|
196
|
+
while ((f = reader.field()) !== null) {
|
|
197
|
+
const [num, wire, value, raw] = f;
|
|
198
|
+
switch (num) {
|
|
199
|
+
case 1: msg.tags.push(TagValue.decode(value)); break;
|
|
200
|
+
case 2: msg.payload = value; break;
|
|
201
|
+
case 3: msg.publisherId = new TextDecoder().decode(value); break;
|
|
202
|
+
default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return msg;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export class PublishReply {
|
|
210
|
+
constructor({ seq = 0n } = {}) {
|
|
211
|
+
this.seq = seq;
|
|
212
|
+
this.unknownFields = new Uint8Array(0);
|
|
213
|
+
}
|
|
214
|
+
static encode(msg) {
|
|
215
|
+
const out = [];
|
|
216
|
+
putVarintField(out, 1, BigInt(msg.seq));
|
|
217
|
+
putRaw(out, msg.unknownFields);
|
|
218
|
+
return new Uint8Array(out);
|
|
219
|
+
}
|
|
220
|
+
static decode(bytes) {
|
|
221
|
+
const msg = new PublishReply();
|
|
222
|
+
const reader = new Reader(bytes);
|
|
223
|
+
let f;
|
|
224
|
+
while ((f = reader.field()) !== null) {
|
|
225
|
+
const [num, wire, value, raw] = f;
|
|
226
|
+
switch (num) {
|
|
227
|
+
case 1: msg.seq = BigInt.asUintN(64, value); break;
|
|
228
|
+
default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return msg;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export class SubscribeRequest {
|
|
236
|
+
constructor({ filter = [] } = {}) {
|
|
237
|
+
this.filter = filter;
|
|
238
|
+
this.unknownFields = new Uint8Array(0);
|
|
239
|
+
}
|
|
240
|
+
static encode(msg) {
|
|
241
|
+
const out = [];
|
|
242
|
+
if (msg.filter) for (const v of msg.filter) putBytesField(out, 1, TagValue.encode(v));
|
|
243
|
+
putRaw(out, msg.unknownFields);
|
|
244
|
+
return new Uint8Array(out);
|
|
245
|
+
}
|
|
246
|
+
static decode(bytes) {
|
|
247
|
+
const msg = new SubscribeRequest();
|
|
248
|
+
const reader = new Reader(bytes);
|
|
249
|
+
let f;
|
|
250
|
+
while ((f = reader.field()) !== null) {
|
|
251
|
+
const [num, wire, value, raw] = f;
|
|
252
|
+
switch (num) {
|
|
253
|
+
case 1: msg.filter.push(TagValue.decode(value)); break;
|
|
254
|
+
default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return msg;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export class Event {
|
|
262
|
+
constructor({ tags = [], payload = new Uint8Array(0), seq = 0n, publisherId = "", timestampUnixMs = 0n } = {}) {
|
|
263
|
+
this.tags = tags;
|
|
264
|
+
this.payload = payload;
|
|
265
|
+
this.seq = seq;
|
|
266
|
+
this.publisherId = publisherId;
|
|
267
|
+
this.timestampUnixMs = timestampUnixMs;
|
|
268
|
+
this.unknownFields = new Uint8Array(0);
|
|
269
|
+
}
|
|
270
|
+
static encode(msg) {
|
|
271
|
+
const out = [];
|
|
272
|
+
if (msg.tags) for (const v of msg.tags) putBytesField(out, 1, TagValue.encode(v));
|
|
273
|
+
if (msg.payload && msg.payload.length) putBytesField(out, 2, msg.payload);
|
|
274
|
+
putVarintField(out, 3, BigInt(msg.seq));
|
|
275
|
+
putStringField(out, 4, msg.publisherId);
|
|
276
|
+
putVarintField(out, 5, BigInt(msg.timestampUnixMs));
|
|
277
|
+
putRaw(out, msg.unknownFields);
|
|
278
|
+
return new Uint8Array(out);
|
|
279
|
+
}
|
|
280
|
+
static decode(bytes) {
|
|
281
|
+
const msg = new Event();
|
|
282
|
+
const reader = new Reader(bytes);
|
|
283
|
+
let f;
|
|
284
|
+
while ((f = reader.field()) !== null) {
|
|
285
|
+
const [num, wire, value, raw] = f;
|
|
286
|
+
switch (num) {
|
|
287
|
+
case 1: msg.tags.push(TagValue.decode(value)); break;
|
|
288
|
+
case 2: msg.payload = value; break;
|
|
289
|
+
case 3: msg.seq = BigInt.asUintN(64, value); break;
|
|
290
|
+
case 4: msg.publisherId = new TextDecoder().decode(value); break;
|
|
291
|
+
case 5: msg.timestampUnixMs = BigInt.asIntN(64, value); break;
|
|
292
|
+
default: msg.unknownFields = concatBytes(msg.unknownFields, raw); break;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return msg;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|