grpc-dc 0.32.14 → 0.32.16
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 +41 -16
- 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.32.
|
|
4
|
-
"description": "gRPC in the browser over WebRTC DataChannels: dependency-free generated gRPC clients & servers for JavaScript
|
|
3
|
+
"version": "0.32.16",
|
|
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
|
@@ -2846,7 +2846,8 @@ function emitCFile(model, params) {
|
|
|
2846
2846
|
+ ' grpcdc_bytes out; int r = grpcdc_stream_recv(s->raw, &out, st);\n'
|
|
2847
2847
|
+ ' if (r == 1) { memset(resp, 0, sizeof(*resp)); ' + resp + '_unmarshal(resp, out.data, out.len); grpcdc_bytes_free(&out); }\n'
|
|
2848
2848
|
+ ' return r;\n}\n\n'
|
|
2849
|
-
+ 'static inline void ' + S + m.name + 'Client_close(' + S + m.name + 'Client *s) { grpcdc_stream_free(s->raw); }\n\n'
|
|
2849
|
+
+ 'static inline void ' + S + m.name + 'Client_close(' + S + m.name + 'Client *s) { grpcdc_stream_free(s->raw); }\n\n'
|
|
2850
|
+
+ 'static inline void ' + S + m.name + 'Client_cancel(' + S + m.name + 'Client *s) { grpcdc_stream_cancel(s->raw); }\n\n');
|
|
2850
2851
|
} else if (m.kind === 'client-streaming') {
|
|
2851
2852
|
parts.push('static inline grpcdc_status ' + S + 'Client_' + name + '(' + S + 'Client *c, const ' + req + ' *reqs, size_t req_count, ' + resp + ' *resp, const grpcdc_kv *md, size_t md_count, int64_t deadline_ms) {\n'
|
|
2852
2853
|
+ ' grpcdc_stream *raw; grpcdc_status st;\n'
|
|
@@ -2878,7 +2879,8 @@ function emitCFile(model, params) {
|
|
|
2878
2879
|
+ ' grpcdc_bytes out; int r = grpcdc_stream_recv(s->raw, &out, st);\n'
|
|
2879
2880
|
+ ' if (r == 1) { memset(resp, 0, sizeof(*resp)); ' + resp + '_unmarshal(resp, out.data, out.len); grpcdc_bytes_free(&out); }\n'
|
|
2880
2881
|
+ ' return r;\n}\n\n'
|
|
2881
|
-
+ 'static inline void ' + S + m.name + 'Client_close(' + S + m.name + 'Client *s) { grpcdc_stream_free(s->raw); }\n\n'
|
|
2882
|
+
+ 'static inline void ' + S + m.name + 'Client_close(' + S + m.name + 'Client *s) { grpcdc_stream_free(s->raw); }\n\n'
|
|
2883
|
+
+ 'static inline void ' + S + m.name + 'Client_cancel(' + S + m.name + 'Client *s) { grpcdc_stream_cancel(s->raw); }\n\n');
|
|
2882
2884
|
}
|
|
2883
2885
|
}
|
|
2884
2886
|
// server stream helper types
|
|
@@ -3211,7 +3213,7 @@ function rpVarintExpr(f, v) {
|
|
|
3211
3213
|
function rpVarintDecode(f, v) {
|
|
3212
3214
|
switch (f.type) {
|
|
3213
3215
|
case 5: case 15: return '(' + v + ' as u32 as i32)';
|
|
3214
|
-
case 14: return
|
|
3216
|
+
case 14: return v + '.to_i32()';
|
|
3215
3217
|
case 13: case 7: return '(' + v + ' as u32)';
|
|
3216
3218
|
case 8: return '(' + v + ' != 0)';
|
|
3217
3219
|
case 17: return '(((' + v + ' as u32 >> 1) as i32) ^ (-(((' + v + ' as u32) & 1) as i32)))';
|
|
@@ -3257,7 +3259,7 @@ function rpEncodeSingular(model, f, v, indent) {
|
|
|
3257
3259
|
const n = f.number;
|
|
3258
3260
|
const proto2 = model.syntax === 'proto2';
|
|
3259
3261
|
if (RP_VARINT.has(f.type)) {
|
|
3260
|
-
const expr = f.type === 14 ? '(' + v + ' as
|
|
3262
|
+
const expr = f.type === 14 ? '(' + v + '.to_i32() as u64)' : rpVarintExpr(f, v);
|
|
3261
3263
|
if (proto2) {
|
|
3262
3264
|
return indent + '{ pb_append_tag(&mut out, ' + n + ', 0); pb_append_varint(&mut out, ' + expr + '); }\n';
|
|
3263
3265
|
}
|
|
@@ -3288,7 +3290,7 @@ function rpSetExpr(sib) {
|
|
|
3288
3290
|
case 11: case 10: return v + '.is_some()';
|
|
3289
3291
|
case 9: case 12: return '!' + v + '.is_empty()';
|
|
3290
3292
|
case 8: return v;
|
|
3291
|
-
case 14: return
|
|
3293
|
+
case 14: return v + '.to_i32() != 0';
|
|
3292
3294
|
case 1: case 2: return v + ' != 0.0';
|
|
3293
3295
|
default: return v + ' != 0';
|
|
3294
3296
|
}
|
|
@@ -3324,7 +3326,7 @@ function rpEncodeField(model, f) {
|
|
|
3324
3326
|
if (f.label !== 3) return rpEncodeSingular(model, f, v, ' ');
|
|
3325
3327
|
if (RP_VARINT.has(f.type)) {
|
|
3326
3328
|
return ' if !' + v + '.is_empty() {\n let mut payload = Vec::new();\n'
|
|
3327
|
-
+ ' for x in &' + v + ' { pb_append_varint(&mut payload, ' + (f.type === 14 ? '(*x as
|
|
3329
|
+
+ ' for x in &' + v + ' { pb_append_varint(&mut payload, ' + (f.type === 14 ? '((*x).to_i32() as u64)' : rpVarintExpr(f, '(*x)')) + '); }\n'
|
|
3328
3330
|
+ ' pb_append_bytes_field(&mut out, ' + n + ', &payload);\n }\n';
|
|
3329
3331
|
}
|
|
3330
3332
|
if (rpFixedInfo(f)) {
|
|
@@ -3458,12 +3460,15 @@ function rpMapHelpers(model, entry) {
|
|
|
3458
3460
|
|
|
3459
3461
|
function rpEnumNamed(model, full, e) {
|
|
3460
3462
|
const name = rpFlat(model.package, full);
|
|
3461
|
-
return '#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]\npub enum ' + name + ' {\n'
|
|
3463
|
+
return '#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]\n#[repr(i32)]\npub enum ' + name + ' {\n'
|
|
3462
3464
|
+ e.values.map((v, i) => ' ' + (i === 0 ? '#[default]\n ' : '') + rpCamel(v.name) + ' = ' + v.number + ',\n').join('')
|
|
3463
|
-
+ '}\n\n'
|
|
3465
|
+
+ ' Unknown(i32),\n}\n\n'
|
|
3464
3466
|
+ 'impl ' + name + ' {\n pub fn from_i32(v: i32) -> Self {\n match v {\n'
|
|
3465
3467
|
+ e.values.map((v) => ' ' + v.number + ' => ' + name + '::' + rpCamel(v.name) + ',\n').join('')
|
|
3466
|
-
+ ' _ => ' + name + '::
|
|
3468
|
+
+ ' _ => ' + name + '::Unknown(v),\n }\n }\n'
|
|
3469
|
+
+ ' pub fn to_i32(self) -> i32 {\n match self {\n'
|
|
3470
|
+
+ e.values.map((v) => ' ' + name + '::' + rpCamel(v.name) + ' => ' + v.number + ',\n').join('')
|
|
3471
|
+
+ ' ' + name + '::Unknown(v) => v,\n }\n }\n}\n\n';
|
|
3467
3472
|
}
|
|
3468
3473
|
|
|
3469
3474
|
function rpMessageStruct(model, msg) {
|
|
@@ -5259,6 +5264,8 @@ function cppClientStreamClass(m, svc) {
|
|
|
5259
5264
|
+ ' const grpcdc::Metadata& Headers() const { return stream_.headers().metadata; }\n\n'
|
|
5260
5265
|
+ ' /// Trailing metadata of the terminal status.\n'
|
|
5261
5266
|
+ ' const grpcdc::Metadata& Trailers() const { return stream_.trailers(); }\n\n'
|
|
5267
|
+
+ ' /// Abort this stream (sends RST, wakes a pending Recv).\n'
|
|
5268
|
+
+ ' void Cancel() { stream_.Cancel(); }\n\n'
|
|
5262
5269
|
+ ' private:\n'
|
|
5263
5270
|
+ ' grpcdc::Channel::ClientStream stream_;\n };\n\n';
|
|
5264
5271
|
}
|
|
@@ -6106,6 +6113,20 @@ function emitCppFile(model, params) {
|
|
|
6106
6113
|
const base = baseName(model.name);
|
|
6107
6114
|
const structName = pascalName(base) + 'GrpcDc';
|
|
6108
6115
|
const ns = xppNs(model.package);
|
|
6116
|
+
// Qualify cross-package method types (::pkg::...::Type) so stub
|
|
6117
|
+
// code resolves message types from other proto files.
|
|
6118
|
+
const qual = (full, plain) =>
|
|
6119
|
+
(!model.package || !full.includes('.') || full.startsWith(model.package + '.'))
|
|
6120
|
+
? plain
|
|
6121
|
+
: '::' + full.split('.').join('::');
|
|
6122
|
+
const services = model.services.map((svc) => ({
|
|
6123
|
+
...svc,
|
|
6124
|
+
methods: svc.methods.map((m) => ({
|
|
6125
|
+
...m,
|
|
6126
|
+
input: qual(m.inputFull, m.input),
|
|
6127
|
+
output: qual(m.outputFull, m.output),
|
|
6128
|
+
})),
|
|
6129
|
+
}));
|
|
6109
6130
|
const stub = {
|
|
6110
6131
|
name: base + '_grpc_dc.hpp',
|
|
6111
6132
|
content: '// @generated by protoc-gen-grpc-dc-cpp. DO NOT EDIT.\n'
|
|
@@ -6118,7 +6139,7 @@ function emitCppFile(model, params) {
|
|
|
6118
6139
|
+ 'namespace ' + ns + ' {\n\n'
|
|
6119
6140
|
+ '/// Generated gRPC-over-DataChannels stubs for ' + model.name + '.\n'
|
|
6120
6141
|
+ 'struct ' + structName + ' {\n'
|
|
6121
|
-
+
|
|
6142
|
+
+ services.map(cppService).join('')
|
|
6122
6143
|
+ '};\n\n'
|
|
6123
6144
|
+ '} // namespace ' + ns + '\n',
|
|
6124
6145
|
};
|
|
@@ -8048,7 +8069,7 @@ function dtpEncodeSingular(model, f, v, indent, support) {
|
|
|
8048
8069
|
}
|
|
8049
8070
|
switch (f.type) {
|
|
8050
8071
|
case 9: return proto2
|
|
8051
|
-
? indent + 'w.bytesField(' + n + ',
|
|
8072
|
+
? indent + 'w.bytesField(' + n + ', utf8.encode(' + v + '));\n'
|
|
8052
8073
|
: indent + 'w.stringField(' + n + ', ' + v + ');\n';
|
|
8053
8074
|
case 12: return proto2
|
|
8054
8075
|
? indent + 'w.bytesField(' + n + ', ' + v + ');\n'
|
|
@@ -8096,7 +8117,7 @@ function dtpEncodeField(model, f, support) {
|
|
|
8096
8117
|
+ ' w.bytesField(' + n + ', payload.toBytes());\n }\n';
|
|
8097
8118
|
}
|
|
8098
8119
|
switch (f.type) {
|
|
8099
|
-
case 9: return ' for (final x in ' + v + ') { w.bytesField(' + n + ',
|
|
8120
|
+
case 9: return ' for (final x in ' + v + ') { w.bytesField(' + n + ', utf8.encode(x)); }\n';
|
|
8100
8121
|
case 12: return ' for (final x in ' + v + ') { w.bytesField(' + n + ', x); }\n';
|
|
8101
8122
|
case 11: return ' for (final x in ' + v + ') { w.bytesField(' + n + ', x.marshalDc()); }\n';
|
|
8102
8123
|
default: throw new Error('unsupported repeated field type ' + f.type);
|
|
@@ -8123,7 +8144,7 @@ function dtpDecodeSingular(model, f, target, src, indent, support) {
|
|
|
8123
8144
|
return indent + target + ' = ' + conv + ';\n';
|
|
8124
8145
|
}
|
|
8125
8146
|
switch (f.type) {
|
|
8126
|
-
case 9: return indent + target + ' =
|
|
8147
|
+
case 9: return indent + target + ' = utf8.decode(' + src + ');\n';
|
|
8127
8148
|
case 12: return indent + target + ' = ' + src + ';\n';
|
|
8128
8149
|
case 11: {
|
|
8129
8150
|
const ref = dtpTypeRef(model, dtpResolve(model, f.typeName));
|
|
@@ -8192,7 +8213,7 @@ function dtpDecodeCase(model, f, support) {
|
|
|
8192
8213
|
+ tail;
|
|
8193
8214
|
}
|
|
8194
8215
|
switch (f.type) {
|
|
8195
|
-
case 9: return head + ' ' + v + '.add(
|
|
8216
|
+
case 9: return head + ' ' + v + '.add(utf8.decode(field.bytesValue));\n' + tail;
|
|
8196
8217
|
case 12: return head + ' ' + v + '.add(field.bytesValue);\n' + tail;
|
|
8197
8218
|
case 11: return head
|
|
8198
8219
|
+ ' final item = ' + dtpTypeRef(model, dtpResolve(model, f.typeName)) + '();\n'
|
|
@@ -8239,6 +8260,7 @@ function dtpMapHelpers(model, entry, support) {
|
|
|
8239
8260
|
|
|
8240
8261
|
function dtpSupportHead(p) {
|
|
8241
8262
|
return '// @generated by protoc-gen-grpc-dc-dart. DO NOT EDIT.\n'
|
|
8263
|
+
+ "import 'dart:convert';\n"
|
|
8242
8264
|
+ "import 'dart:typed_data';\n\n"
|
|
8243
8265
|
+ "import '../grpcdc/transport.dart';\n\n"
|
|
8244
8266
|
+ 'class ' + p + 'Writer {\n'
|
|
@@ -8246,7 +8268,7 @@ function dtpSupportHead(p) {
|
|
|
8246
8268
|
+ ' void varint(int value) { var v = BigInt.from(value) & ((BigInt.one << 64) - BigInt.one); final continuation = BigInt.from(0x80); while (v >= continuation) { _out.addByte(((v & BigInt.from(0x7f)) | continuation).toInt()); v = v >> 7; } _out.addByte(v.toInt()); }\n'
|
|
8247
8269
|
+ ' void tag(int field, int wire) { varint((field << 3) | wire); }\n'
|
|
8248
8270
|
+ ' void bytesField(int field, List<int> payload) { tag(field, 2); varint(payload.length); _out.add(payload); }\n'
|
|
8249
|
-
+ ' void stringField(int field, String value) { if (value.isEmpty) return; bytesField(field,
|
|
8271
|
+
+ ' void stringField(int field, String value) { if (value.isEmpty) return; bytesField(field, utf8.encode(value)); }\n'
|
|
8250
8272
|
+ ' void fixedUint32(int value) { final b = ByteData(4); b.setUint32(0, value, Endian.little); _out.add(b.buffer.asUint8List()); }\n'
|
|
8251
8273
|
+ ' void fixedInt32(int value) { final b = ByteData(4); b.setInt32(0, value, Endian.little); _out.add(b.buffer.asUint8List()); }\n'
|
|
8252
8274
|
+ ' void fixedUint64(int value) { final b = ByteData(8); b.setUint64(0, value, Endian.little); _out.add(b.buffer.asUint8List()); }\n'
|
|
@@ -8458,6 +8480,9 @@ function zigClientStreamClass(m, svc) {
|
|
|
8458
8480
|
+ ' /// Trailing metadata of the terminal status.\n'
|
|
8459
8481
|
+ ' pub fn trailers(self: *' + svc + m.name + 'Client) []const status_mod.TrailerPair {\n'
|
|
8460
8482
|
+ ' return self.stream.trailers;\n }\n\n'
|
|
8483
|
+
+ ' /// Abandon the call: RST so the server stops producing.\n'
|
|
8484
|
+
+ ' pub fn cancel(self: *' + svc + m.name + 'Client) void {\n'
|
|
8485
|
+
+ ' self.stream.cancel();\n }\n\n'
|
|
8461
8486
|
+ ' pub fn deinit(self: *' + svc + m.name + 'Client) void {\n'
|
|
8462
8487
|
+ ' self.stream.deinit();\n }\n};\n\n';
|
|
8463
8488
|
}
|
|
@@ -9692,7 +9717,7 @@ function emitLuaPbFile(model) {
|
|
|
9692
9717
|
for (const m of model.messages) collect(m);
|
|
9693
9718
|
const allMsgNames = (msg) => msg.mapEntry ? [] : [lpFlat(model.package, msg.fullName), ...msg.nested.flatMap(allMsgNames)];
|
|
9694
9719
|
const deps = [...new Set((model.dependencies || []).map((d) => baseName(d)))];
|
|
9695
|
-
const depRequires = deps.map((d) => 'local ' + lpFlat('', d + '_messages') + 'Messages = require("' + d + '_messages")\n').join('');
|
|
9720
|
+
const depRequires = deps.map((d) => 'local ' + lpFlat('', d + '_messages') + 'Messages = require("examples.' + d + '_messages")\n').join('');
|
|
9696
9721
|
const content = LP_SUPPORT
|
|
9697
9722
|
+ depRequires
|
|
9698
9723
|
+ (depRequires ? '\n' : '')
|
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
|
+
|