grpc-dc 0.32.13 → 0.32.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grpc-dc",
3
- "version": "0.32.13",
3
+ "version": "0.32.15",
4
4
  "description": "gRPC in the browser over WebRTC DataChannels: dependency-free generated gRPC clients & servers for JavaScript — no grpc-web proxy, no external runtime",
5
5
  "keywords": [
6
6
  "grpc",
@@ -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
@@ -5255,6 +5257,12 @@ function cppClientStreamClass(m, svc) {
5255
5257
  + ' ' + m.output + ' Recv() {\n'
5256
5258
  + ' ' + m.output + ' resp;\n'
5257
5259
  + ' stream_.Recv(resp);\n return resp;\n }\n\n'
5260
+ + ' /// Initial metadata (response headers).\n'
5261
+ + ' const grpcdc::Metadata& Headers() const { return stream_.headers().metadata; }\n\n'
5262
+ + ' /// Trailing metadata of the terminal status.\n'
5263
+ + ' const grpcdc::Metadata& Trailers() const { return stream_.trailers(); }\n\n'
5264
+ + ' /// Abort this stream (sends RST, wakes a pending Recv).\n'
5265
+ + ' void Cancel() { stream_.Cancel(); }\n\n'
5258
5266
  + ' private:\n'
5259
5267
  + ' grpcdc::Channel::ClientStream stream_;\n };\n\n';
5260
5268
  }
@@ -5973,21 +5981,68 @@ function xppMessageClass(model, msg, support, indent) {
5973
5981
  + msg.fields.map((f) => pad + ' ' + xppType(model, f) + ' ' + f.name + ' = ' + xppDefault(model, f) + ';\n').join('')
5974
5982
  + pad + ' grpcdc::Bytes unknown_fields;\n'
5975
5983
  + pad + ' ' + name + '() = default;\n'
5976
- + pad + ' grpcdc::Bytes MarshalDc() const override {\n'
5977
- + pad + ' ' + support + '::Writer w;\n'
5984
+ + pad + ' grpcdc::Bytes MarshalDc() const override;\n'
5985
+ + pad + ' void UnmarshalDc(const grpcdc::Bytes& data) override;\n'
5986
+ + pad + '};\n';
5987
+ }
5988
+
5989
+ function xppMessageImpls(model, msg, support, qual) {
5990
+ const q = qual ? qual + '::' + msg.name : msg.name;
5991
+ return 'inline grpcdc::Bytes ' + q + '::MarshalDc() const {\n'
5992
+ + ' ' + support + '::Writer w;\n'
5978
5993
  + msg.fields.map((f) => xppEncodeGuard(model, f, xppEncodeField(model, f, support))).join('')
5979
- + pad + ' w.Raw(unknown_fields);\n'
5980
- + pad + ' return w.ToBytes();\n' + pad + ' }\n'
5981
- + pad + ' void UnmarshalDc(const grpcdc::Bytes& data) override {\n'
5982
- + pad + ' unknown_fields.clear();\n'
5983
- + msg.fields.map((f) => pad + ' ' + f.name + ' = ' + xppDefault(model, f) + ';\n').join('')
5984
- + pad + ' ' + support + '::Reader r(data);\n'
5985
- + pad + ' ' + support + '::Field field;\n'
5986
- + pad + ' while (r.Next(field)) {\n' + pad + ' switch (field.number) {\n'
5994
+ + ' w.Raw(unknown_fields);\n'
5995
+ + ' return w.ToBytes();\n}\n\n'
5996
+ + 'inline void ' + q + '::UnmarshalDc(const grpcdc::Bytes& data) {\n'
5997
+ + ' unknown_fields.clear();\n'
5998
+ + msg.fields.map((f) => ' ' + f.name + ' = ' + xppDefault(model, f) + ';\n').join('')
5999
+ + ' ' + support + '::Reader r(data);\n'
6000
+ + ' ' + support + '::Field field;\n'
6001
+ + ' while (r.Next(field)) {\n switch (field.number) {\n'
5987
6002
  + msg.fields.map((f) => xppDecodeCase(model, f, support)).join('')
5988
- + pad + ' default: unknown_fields.insert(unknown_fields.end(), field.raw.begin(), field.raw.end()); break;\n'
5989
- + pad + ' }\n' + pad + ' }\n' + pad + ' }\n'
5990
- + pad + '};\n';
6003
+ + ' default: unknown_fields.insert(unknown_fields.end(), field.raw.begin(), field.raw.end()); break;\n'
6004
+ + ' }\n }\n}\n\n'
6005
+ + msg.nested.filter((n) => !n.mapEntry).map((n) => xppMessageImpls(model, n, support, q)).join('');
6006
+ }
6007
+
6008
+ function xppOrderedMessages(model) {
6009
+ const tops = model.messages.filter((m) => !m.mapEntry);
6010
+ const topOf = (e) => {
6011
+ if (!e || e.file !== model.name) return null;
6012
+ return xppRel(model.package, e.full).split('::')[0];
6013
+ };
6014
+ const depsOf = (m) => {
6015
+ const out = [];
6016
+ const note = (f) => {
6017
+ if (f.type !== 11) return;
6018
+ const e = xppResolve(model, f.typeName);
6019
+ if (!e) return;
6020
+ if (e.kind === 'map') {
6021
+ const valF = e.msg.fields.find((x) => x.name === 'value');
6022
+ if (valF && valF.type === 11) {
6023
+ const ve = xppResolve(model, valF.typeName);
6024
+ if (ve && ve.kind === 'message') { const t = topOf(ve); if (t && !out.includes(t)) out.push(t); }
6025
+ }
6026
+ } else if (e.kind === 'message' && f.label !== 3) {
6027
+ const t = topOf(e); if (t && !out.includes(t)) out.push(t);
6028
+ }
6029
+ };
6030
+ const walk = (msg) => { msg.fields.forEach(note); msg.nested.forEach(walk); };
6031
+ walk(m);
6032
+ return out;
6033
+ };
6034
+ const depMap = new Map(tops.map((m) => [m.name, depsOf(m)]));
6035
+ const remaining = new Set(tops.map((m) => m.name));
6036
+ const out = [];
6037
+ let rest = tops.slice();
6038
+ while (rest.length) {
6039
+ const next = rest.find((m) => depMap.get(m.name).every((d) => d === m.name || !remaining.has(d)));
6040
+ if (!next) throw new Error('emitCppPbFile: message dependency cycle');
6041
+ out.push(next);
6042
+ remaining.delete(next.name);
6043
+ rest = rest.filter((m) => m !== next);
6044
+ }
6045
+ return out;
5991
6046
  }
5992
6047
 
5993
6048
  function emitCppPbFile(model) {
@@ -6010,6 +6065,7 @@ function emitCppPbFile(model) {
6010
6065
  for (const n of msg.nested) collect(n);
6011
6066
  };
6012
6067
  for (const m of model.messages) collect(m);
6068
+ const ordered = xppOrderedMessages(model);
6013
6069
  const deps = model.dependencies || [];
6014
6070
  const content = '// @generated by protoc-gen-grpc-dc-cpp. DO NOT EDIT.\n'
6015
6071
  + '#pragma once\n\n'
@@ -6025,9 +6081,12 @@ function emitCppPbFile(model) {
6025
6081
  + '\n};\n\n').join('')
6026
6082
  + 'namespace pb_' + base + ' {\n\n'
6027
6083
  + XPP_SUPPORT_BODY
6028
- + helpers.map((h) => h.decls).join('')
6029
6084
  + '} // namespace pb_' + base + '\n\n'
6030
- + model.messages.filter((m) => !m.mapEntry).map((m) => xppMessageClass(model, m, support, '')).join('')
6085
+ + ordered.map((m) => xppMessageClass(model, m, support, '')).join('')
6086
+ + (helpers.length
6087
+ ? 'namespace pb_' + base + ' {\n\n' + helpers.map((h) => h.decls).join('') + '} // namespace pb_' + base + '\n\n'
6088
+ : '')
6089
+ + ordered.map((m) => xppMessageImpls(model, m, support, '')).join('')
6031
6090
  + (helpers.length
6032
6091
  ? 'namespace pb_' + base + ' {\n\n' + helpers.map((h) => h.defs).join('') + '} // namespace pb_' + base + '\n\n'
6033
6092
  : '')
@@ -6035,10 +6094,36 @@ function emitCppPbFile(model) {
6035
6094
  return { name: base + '_messages.hpp', content };
6036
6095
  }
6037
6096
 
6097
+ function cppStubIncludes(model) {
6098
+ if (!model.types) return '#include "examples/' + baseName(model.name) + '_messages.hpp"\n';
6099
+ const files = new Set();
6100
+ for (const svc of model.services) {
6101
+ for (const m of svc.methods) {
6102
+ files.add(xppResolve(model, m.inputFull).file);
6103
+ files.add(xppResolve(model, m.outputFull).file);
6104
+ }
6105
+ }
6106
+ return [...files].map((f) => '#include "examples/' + baseName(f) + '_messages.hpp"\n').join('');
6107
+ }
6108
+
6038
6109
  function emitCppFile(model, params) {
6039
6110
  const base = baseName(model.name);
6040
6111
  const structName = pascalName(base) + 'GrpcDc';
6041
- const ns = model.package || 'proto';
6112
+ const ns = xppNs(model.package);
6113
+ // Qualify cross-package method types (::pkg::...::Type) so stub
6114
+ // code resolves message types from other proto files.
6115
+ const qual = (full, plain) =>
6116
+ (!model.package || !full.includes('.') || full.startsWith(model.package + '.'))
6117
+ ? plain
6118
+ : '::' + full.split('.').join('::');
6119
+ const services = model.services.map((svc) => ({
6120
+ ...svc,
6121
+ methods: svc.methods.map((m) => ({
6122
+ ...m,
6123
+ input: qual(m.inputFull, m.input),
6124
+ output: qual(m.outputFull, m.output),
6125
+ })),
6126
+ }));
6042
6127
  const stub = {
6043
6128
  name: base + '_grpc_dc.hpp',
6044
6129
  content: '// @generated by protoc-gen-grpc-dc-cpp. DO NOT EDIT.\n'
@@ -6046,12 +6131,12 @@ function emitCppFile(model, params) {
6046
6131
  + '#pragma once\n\n'
6047
6132
  + '#include <future>\n#include <optional>\n\n#if __cplusplus >= 202002L\n#include "grpcdc/async.hpp"\n#endif\n'
6048
6133
  + '#include <memory>\n#include <vector>\n\n'
6049
- + '#include "examples/' + base + '_messages.hpp"\n'
6134
+ + cppStubIncludes(model)
6050
6135
  + '#include "grpcdc/channel.hpp"\n#include "grpcdc/server.hpp"\n\n'
6051
6136
  + 'namespace ' + ns + ' {\n\n'
6052
6137
  + '/// Generated gRPC-over-DataChannels stubs for ' + model.name + '.\n'
6053
6138
  + 'struct ' + structName + ' {\n'
6054
- + model.services.map(cppService).join('')
6139
+ + services.map(cppService).join('')
6055
6140
  + '};\n\n'
6056
6141
  + '} // namespace ' + ns + '\n',
6057
6142
  };
@@ -6095,7 +6180,12 @@ function swiftClientStreamClass(m, svc) {
6095
6180
  + ' init(_ stream: Channel.ClientStream) { self.stream = stream }\n'
6096
6181
  + ' func Recv() throws -> ' + m.output + ' {\n'
6097
6182
  + ' let resp = ' + m.output + '()\n'
6098
- + ' try stream.Recv(resp)\n return resp\n }\n func Cancel() { stream.Cancel() }\n func Close() { stream.Close() }\n }\n\n';
6183
+ + ' try stream.Recv(resp)\n return resp\n }\n'
6184
+ + ' /// Initial metadata (response headers); nil until they arrive.\n'
6185
+ + ' var Headers: [String: String]? { stream.headers?.metadata }\n'
6186
+ + ' /// Trailing metadata of the terminal status; nil until it arrives.\n'
6187
+ + ' var Trailers: [String: String]? { stream.trailers }\n'
6188
+ + ' func Cancel() { stream.Cancel() }\n func Close() { stream.Close() }\n }\n\n';
6099
6189
  }
6100
6190
 
6101
6191
  function swiftClientAsyncMethod(m, svc) {
@@ -6315,16 +6405,16 @@ function swiftService(svc) {
6315
6405
  + ' static func Register' + sname + 'ServerAsync(_ server: Server, _ impl: ' + sname + 'ServerAsync) {\n'
6316
6406
  + ' // Adapters are retained for the process lifetime: registration is\n'
6317
6407
  + ' // once-per-process and bounded by service count.\n'
6318
- + ' adapters.append(' + sname + 'ServerAsyncAdapter(impl))\n'
6319
- + ' Register' + sname + 'Server(server, adapters.last!)\n }\n\n'
6320
- + ' private static var adapters: [' + sname + 'ServerAsyncAdapter] = []\n'
6408
+ + ' ' + sname + 'Adapters.append(' + sname + 'ServerAsyncAdapter(impl))\n'
6409
+ + ' Register' + sname + 'Server(server, ' + sname + 'Adapters.last!)\n }\n\n'
6410
+ + ' private static var ' + sname + 'Adapters: [' + sname + 'ServerAsyncAdapter] = []\n'
6321
6411
  + ' #endif\n';
6322
6412
  }
6323
6413
 
6324
6414
  const SWIFT_RUN_BLOCKING =
6325
6415
  '#if canImport(Foundation)\n'
6326
6416
  + '/// Run an async operation to completion on a blocking thread.\n'
6327
- + 'func RunBlocking<T>(_ body: @escaping () async throws -> T) throws -> T {\n'
6417
+ + 'fileprivate func RunBlocking<T>(_ body: @escaping () async throws -> T) throws -> T {\n'
6328
6418
  + ' let semaphore = DispatchSemaphore(value: 0)\n'
6329
6419
  + ' var result: Result<T, Error>!\n'
6330
6420
  + ' Task.detached {\n'
@@ -6601,7 +6691,7 @@ function swpDecodeCase(model, f, support) {
6601
6691
  }
6602
6692
  if (SWP_VARINT.has(f.type)) {
6603
6693
  const conv = (src) => f.type === 14
6604
- ? swpEntryRef(model, swpResolve(model, f.typeName)) + '(rawValue: ' + swpVarintDecode({ ...f, type: 5 }, src) + ') ?? ' + swpDefault(model, f)
6694
+ ? swpEntryRef(model, swpResolve(model, f.typeName)) + '(rawValue: ' + swpVarintDecode({ ...f, type: 5 }, src) + ') ?? ' + swpDefault(model, { ...f, label: 1 })
6605
6695
  : swpVarintDecode(f, src);
6606
6696
  return head
6607
6697
  + ' if field.wire == 2 {\n'
@@ -6800,8 +6890,7 @@ function emitSwiftFile(model, params) {
6800
6890
  + '/// Generated gRPC-over-DataChannels stubs for ' + model.name + '.\n'
6801
6891
  + 'enum ' + enumName + ' {\n'
6802
6892
  + model.services.map(swiftService).join('')
6803
- + '}\n\n'
6804
- + SWIFT_RUN_BLOCKING,
6893
+ + '}\n',
6805
6894
  };
6806
6895
  const pbFile = emitSwiftPbFile(model);
6807
6896
  return pbFile ? [stub, pbFile] : stub;
@@ -7654,6 +7743,14 @@ function dartClientStreamClass(m, svc) {
7654
7743
  + ' Future<' + m.output + '> recv() async {\n'
7655
7744
  + ' final resp = ' + m.output + '();\n'
7656
7745
  + ' await _stream.recv(resp);\n return resp;\n }\n\n'
7746
+ + ' /// Initial metadata (response headers); null until they arrive.\n'
7747
+ + ' Map<String, String>? get headers => _stream.headers?.metadata;\n\n'
7748
+ + ' /// Trailing metadata of the terminal status; null until it arrives.\n'
7749
+ + ' Map<String, String>? get trailers => _stream.trailers;\n\n'
7750
+ + ' /// Abort this stream (sends RST, wakes a pending recv).\n'
7751
+ + ' void cancel() => _stream.cancel();\n\n'
7752
+ + ' /// Abandon the call if still live (RST); no-op once terminated.\n'
7753
+ + ' void close() => _stream.close();\n\n'
7657
7754
  + ' /// Responses as a Dart Stream (native async surface).\n'
7658
7755
  + ' /// Cancelling the subscription abandons the call:\n'
7659
7756
  + ' /// RST CANCELLED is sent so the server stops.\n'
@@ -7969,7 +8066,7 @@ function dtpEncodeSingular(model, f, v, indent, support) {
7969
8066
  }
7970
8067
  switch (f.type) {
7971
8068
  case 9: return proto2
7972
- ? indent + 'w.bytesField(' + n + ', Uint8List.fromList(' + v + '.codeUnits));\n'
8069
+ ? indent + 'w.bytesField(' + n + ', utf8.encode(' + v + '));\n'
7973
8070
  : indent + 'w.stringField(' + n + ', ' + v + ');\n';
7974
8071
  case 12: return proto2
7975
8072
  ? indent + 'w.bytesField(' + n + ', ' + v + ');\n'
@@ -8017,7 +8114,7 @@ function dtpEncodeField(model, f, support) {
8017
8114
  + ' w.bytesField(' + n + ', payload.toBytes());\n }\n';
8018
8115
  }
8019
8116
  switch (f.type) {
8020
- case 9: return ' for (final x in ' + v + ') { w.bytesField(' + n + ', Uint8List.fromList(x.codeUnits)); }\n';
8117
+ case 9: return ' for (final x in ' + v + ') { w.bytesField(' + n + ', utf8.encode(x)); }\n';
8021
8118
  case 12: return ' for (final x in ' + v + ') { w.bytesField(' + n + ', x); }\n';
8022
8119
  case 11: return ' for (final x in ' + v + ') { w.bytesField(' + n + ', x.marshalDc()); }\n';
8023
8120
  default: throw new Error('unsupported repeated field type ' + f.type);
@@ -8044,7 +8141,7 @@ function dtpDecodeSingular(model, f, target, src, indent, support) {
8044
8141
  return indent + target + ' = ' + conv + ';\n';
8045
8142
  }
8046
8143
  switch (f.type) {
8047
- case 9: return indent + target + ' = String.fromCharCodes(' + src + ');\n';
8144
+ case 9: return indent + target + ' = utf8.decode(' + src + ');\n';
8048
8145
  case 12: return indent + target + ' = ' + src + ';\n';
8049
8146
  case 11: {
8050
8147
  const ref = dtpTypeRef(model, dtpResolve(model, f.typeName));
@@ -8113,7 +8210,7 @@ function dtpDecodeCase(model, f, support) {
8113
8210
  + tail;
8114
8211
  }
8115
8212
  switch (f.type) {
8116
- case 9: return head + ' ' + v + '.add(String.fromCharCodes(field.bytesValue));\n' + tail;
8213
+ case 9: return head + ' ' + v + '.add(utf8.decode(field.bytesValue));\n' + tail;
8117
8214
  case 12: return head + ' ' + v + '.add(field.bytesValue);\n' + tail;
8118
8215
  case 11: return head
8119
8216
  + ' final item = ' + dtpTypeRef(model, dtpResolve(model, f.typeName)) + '();\n'
@@ -8160,6 +8257,7 @@ function dtpMapHelpers(model, entry, support) {
8160
8257
 
8161
8258
  function dtpSupportHead(p) {
8162
8259
  return '// @generated by protoc-gen-grpc-dc-dart. DO NOT EDIT.\n'
8260
+ + "import 'dart:convert';\n"
8163
8261
  + "import 'dart:typed_data';\n\n"
8164
8262
  + "import '../grpcdc/transport.dart';\n\n"
8165
8263
  + 'class ' + p + 'Writer {\n'
@@ -8167,7 +8265,7 @@ function dtpSupportHead(p) {
8167
8265
  + ' 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'
8168
8266
  + ' void tag(int field, int wire) { varint((field << 3) | wire); }\n'
8169
8267
  + ' void bytesField(int field, List<int> payload) { tag(field, 2); varint(payload.length); _out.add(payload); }\n'
8170
- + ' void stringField(int field, String value) { if (value.isEmpty) return; bytesField(field, Uint8List.fromList(value.codeUnits)); }\n'
8268
+ + ' void stringField(int field, String value) { if (value.isEmpty) return; bytesField(field, utf8.encode(value)); }\n'
8171
8269
  + ' void fixedUint32(int value) { final b = ByteData(4); b.setUint32(0, value, Endian.little); _out.add(b.buffer.asUint8List()); }\n'
8172
8270
  + ' void fixedInt32(int value) { final b = ByteData(4); b.setInt32(0, value, Endian.little); _out.add(b.buffer.asUint8List()); }\n'
8173
8271
  + ' void fixedUint64(int value) { final b = ByteData(8); b.setUint64(0, value, Endian.little); _out.add(b.buffer.asUint8List()); }\n'
@@ -8284,6 +8382,18 @@ function emitDartPbFile(model) {
8284
8382
  return { name: base + '_messages.dart', content };
8285
8383
  }
8286
8384
 
8385
+ function dartStubImports(model) {
8386
+ if (!model.types) return "import '" + baseName(model.name) + "_messages.dart';\n\n";
8387
+ const files = new Set();
8388
+ for (const svc of model.services) {
8389
+ for (const m of svc.methods) {
8390
+ files.add(dtpResolve(model, m.inputFull).file);
8391
+ files.add(dtpResolve(model, m.outputFull).file);
8392
+ }
8393
+ }
8394
+ return [...files].map((f) => "import '" + baseName(f) + "_messages.dart';\n").join('') + '\n';
8395
+ }
8396
+
8287
8397
  function emitDartFile(model, params) {
8288
8398
  const base = baseName(model.name);
8289
8399
  const className = pascalName(base) + 'GrpcDc';
@@ -8293,7 +8403,7 @@ function emitDartFile(model, params) {
8293
8403
  + '// source: ' + model.name + '\n\n'
8294
8404
  + "import 'dart:async';\n\n"
8295
8405
  + "import '../grpcdc/channel.dart';\nimport '../grpcdc/endpoint.dart';\nimport '../grpcdc/server.dart';\nimport '../grpcdc/status.dart';\nimport '../grpcdc/wire.dart';\n"
8296
- + "import '" + base + "_messages.dart';\n\n"
8406
+ + dartStubImports(model)
8297
8407
  + model.services.map(dartService).join('')
8298
8408
  + '/// Generated gRPC-over-DataChannels stubs for ' + model.name + '.\n'
8299
8409
  + 'class ' + className + ' {\n'
@@ -8361,6 +8471,15 @@ function zigClientStreamClass(m, svc) {
8361
8471
  + ' .message => return .{ .message = resp },\n'
8362
8472
  + ' .end => return .end,\n'
8363
8473
  + ' .status => |st| return .{ .status = st },\n }\n }\n\n'
8474
+ + ' /// Initial metadata (response headers); null until they arrive.\n'
8475
+ + ' pub fn headers(self: *' + svc + m.name + 'Client) ?grpcdc.codec.Headers {\n'
8476
+ + ' return self.stream.headers;\n }\n\n'
8477
+ + ' /// Trailing metadata of the terminal status.\n'
8478
+ + ' pub fn trailers(self: *' + svc + m.name + 'Client) []const status_mod.TrailerPair {\n'
8479
+ + ' return self.stream.trailers;\n }\n\n'
8480
+ + ' /// Abandon the call: RST so the server stops producing.\n'
8481
+ + ' pub fn cancel(self: *' + svc + m.name + 'Client) void {\n'
8482
+ + ' self.stream.cancel();\n }\n\n'
8364
8483
  + ' pub fn deinit(self: *' + svc + m.name + 'Client) void {\n'
8365
8484
  + ' self.stream.deinit();\n }\n};\n\n';
8366
8485
  }
@@ -8422,7 +8541,7 @@ function zigServerVtableField(m, svc) {
8422
8541
  function zigAdapter(m, svc) {
8423
8542
  const name = lowerFirst(m.name);
8424
8543
  const impl = zigSnake(m.implName);
8425
- const head = 'fn ' + name + 'Adapter(ctx: *anyopaque, call_ctx: *CallContext, reqs: *server_mod.RequestStream, sink: server_mod.Sink) Status {\n'
8544
+ const head = 'fn ' + lowerFirst(svc) + m.name + 'Adapter(ctx: *anyopaque, call_ctx: *CallContext, reqs: *server_mod.RequestStream, sink: server_mod.Sink) Status {\n'
8426
8545
  + ' const impl: *' + svc + 'Server = @ptrCast(@alignCast(ctx));\n';
8427
8546
  switch (m.kind) {
8428
8547
  case 'unary':
@@ -8475,8 +8594,8 @@ const ZIG_KIND_CONSTS = {
8475
8594
  bidi: 'bidi',
8476
8595
  };
8477
8596
 
8478
- function zigRegisterMethod(m) {
8479
- return ' .{ .name = ' + q(m.name) + ', .path = ' + q(m.path) + ', .kind = .' + ZIG_KIND_CONSTS[m.kind] + ', .ctx = impl, .handler = ' + lowerFirst(m.name) + 'Adapter },\n';
8597
+ function zigRegisterMethod(m, svc) {
8598
+ return ' .{ .name = ' + q(m.name) + ', .path = ' + q(m.path) + ', .kind = .' + ZIG_KIND_CONSTS[m.kind] + ', .ctx = impl, .handler = ' + lowerFirst(svc) + m.name + 'Adapter },\n';
8480
8599
  }
8481
8600
 
8482
8601
  function zigService(svc) {
@@ -8499,6 +8618,26 @@ function zigService(svc) {
8499
8618
  + svc.methods.concat(aliasServerMethods(svc)).map((m) => zigAdapter(m, sname)).join('');
8500
8619
  }
8501
8620
 
8621
+ function zigTypeOrigins(model) {
8622
+ const seen = [];
8623
+ for (const svc of model.services) {
8624
+ for (const m of svc.methods) {
8625
+ for (const [simple, full] of [[m.input, m.inputFull], [m.output, m.outputFull]]) {
8626
+ if (!seen.some(([n]) => n === simple)) {
8627
+ seen.push([simple, baseName(zgpResolve(model, full).file)]);
8628
+ }
8629
+ }
8630
+ }
8631
+ }
8632
+ return seen;
8633
+ }
8634
+
8635
+ function zigStubImports(model) {
8636
+ if (!model.types) return 'const messages = @import("' + baseName(model.name) + '_messages.zig");\n\n';
8637
+ const bases = [...new Set(zigTypeOrigins(model).map(([, b]) => b))];
8638
+ return bases.map((b) => 'const ' + b + '_messages = @import("' + b + '_messages.zig");\n').join('') + '\n';
8639
+ }
8640
+
8502
8641
  function zigMessageNames(model) {
8503
8642
  const seen = [];
8504
8643
  for (const svc of model.services) {
@@ -8516,7 +8655,7 @@ function zigRegisterService(svc) {
8516
8655
  + ' server.registerService(.{\n'
8517
8656
  + ' .name = ' + q(svc.fullName) + ',\n'
8518
8657
  + ' .methods = &.{\n'
8519
- + svc.methods.concat(aliasServerMethods(svc)).map(zigRegisterMethod).join('')
8658
+ + svc.methods.concat(aliasServerMethods(svc)).map((m) => zigRegisterMethod(m, sname)).join('')
8520
8659
  + ' },\n });\n }\n';
8521
8660
  }
8522
8661
 
@@ -8840,6 +8979,7 @@ function zgpMapHelpers(model, entry) {
8840
8979
  : zgpEncodeSingular(model, { ...valF, label: 1 }, 'value', ' '))
8841
8980
  + ' return w.toBytes();\n}\n\n'
8842
8981
  + 'pub fn decode' + sname + '(alloc: std.mem.Allocator, data: []const u8) ' + sname + ' {\n'
8982
+ + ([9, 12, 11].includes(keyF.type) || [9, 12, 11].includes(valF.type) ? '' : ' _ = alloc;\n')
8843
8983
  + ' var result: ' + sname + ' = .{ .key = ' + zgpDefault(model, { ...keyF, label: 1 }) + ', .value = ' + (valF.type === FT.MESSAGE ? '.{}' : zgpDefault(model, { ...valF, label: 1 })) + ' };\n'
8844
8984
  + ' var r = PbReader.init(data);\n while (r.next()) |field| {\n switch (field.number) {\n'
8845
8985
  + ' ' + keyF.number + ' => { ' + zgpDecodeSingular(model, { ...keyF, label: 1 }, 'result.key', zgpSrc(keyF), '').replace(/\s+$/, '') + ' },\n'
@@ -8941,7 +9081,7 @@ function zgpMessageStruct(model, msg, indent) {
8941
9081
  + indent + ' self.unknown_fields = unknown_fields_list.toOwnedSlice(alloc) catch &.{};\n'
8942
9082
  + msg.fields.filter((f) => zgpIsListField(model, f)).map((f) => indent + ' self.' + f.name + ' = ' + f.name + '_list.toOwnedSlice(alloc) catch &.{};\n').join('')
8943
9083
  + indent + ' }\n'
8944
- + msg.nested.map((n) => zgpMessageStruct(model, n, indent + ' ')).join('')
9084
+ + msg.nested.filter((n) => !n.mapEntry).map((n) => zgpMessageStruct(model, n, indent + ' ')).join('')
8945
9085
  + msg.enums.map((e) => zgpNestedEnum(e, indent + ' ')).join('')
8946
9086
  + indent + '};\n';
8947
9087
  }
@@ -8997,14 +9137,16 @@ function emitZigFile(model, params) {
8997
9137
  + 'const std = @import("std");\n'
8998
9138
  + 'const grpcdc = @import("grpcdc");\n'
8999
9139
  + 'const channel_mod = grpcdc.channel;\nconst endpoint_mod = grpcdc.endpoint;\nconst server_mod = grpcdc.server;\nconst status_mod = grpcdc.status;\nconst wire = grpcdc.wire;\n'
9000
- + 'const messages = @import("' + base + '_messages.zig");\n\n'
9140
+ + zigStubImports(model)
9001
9141
  + 'pub const Channel = channel_mod.Channel;\n'
9002
9142
  + 'pub const ClientStream = channel_mod.ClientStream;\n'
9003
9143
  + 'pub const CallContext = endpoint_mod.CallContext;\n'
9004
9144
  + 'pub const Server = server_mod.Server;\n'
9005
9145
  + 'pub const Status = status_mod.Status;\n'
9006
9146
  + 'pub const Metadata = channel_mod.Metadata;\n'
9007
- + zigMessageNames(model).map((msg) => 'pub const ' + msg + ' = messages.' + msg + ';\n').join('')
9147
+ + (model.types
9148
+ ? zigTypeOrigins(model).map(([n, b]) => 'pub const ' + n + ' = ' + b + '_messages.' + n + ';\n').join('')
9149
+ : zigMessageNames(model).map((msg) => 'pub const ' + msg + ' = messages.' + msg + ';\n').join(''))
9008
9150
  + '\n'
9009
9151
  + model.services.map(zigService).join('')
9010
9152
  + '/// Generated gRPC-over-DataChannels stubs for ' + model.name + '.\n'
@@ -9118,6 +9260,10 @@ function luaClientStreamClass(m, svc) {
9118
9260
  + 'function ' + t + ':recv()\n'
9119
9261
  + ' local resp = ' + m.output + '.new()\n'
9120
9262
  + ' self.stream:recv(resp)\n return resp\nend\n\n'
9263
+ + '--- Response initial metadata (after the first recv).\n'
9264
+ + 'function ' + t + ':headers()\n return self.stream.headers and self.stream.headers.metadata\nend\n\n'
9265
+ + '--- Response trailing metadata (after the call ends).\n'
9266
+ + 'function ' + t + ':trailers()\n return self.stream.trailers\nend\n\n'
9121
9267
  + '--- Abandon the call early: RST so the server stops producing.\n'
9122
9268
  + 'function ' + t + ':close()\n self.stream:close()\nend\n\n'
9123
9269
  + 'function ' + t + ':cancel()\n self.stream:cancel()\nend\n\n'
@@ -9568,7 +9714,7 @@ function emitLuaPbFile(model) {
9568
9714
  for (const m of model.messages) collect(m);
9569
9715
  const allMsgNames = (msg) => msg.mapEntry ? [] : [lpFlat(model.package, msg.fullName), ...msg.nested.flatMap(allMsgNames)];
9570
9716
  const deps = [...new Set((model.dependencies || []).map((d) => baseName(d)))];
9571
- const depRequires = deps.map((d) => 'local ' + lpFlat('', d + '_messages') + 'Messages = require("' + d + '_messages")\n').join('');
9717
+ const depRequires = deps.map((d) => 'local ' + lpFlat('', d + '_messages') + 'Messages = require("examples.' + d + '_messages")\n').join('');
9572
9718
  const content = LP_SUPPORT
9573
9719
  + depRequires
9574
9720
  + (depRequires ? '\n' : '')
@@ -9584,6 +9730,33 @@ function emitLuaPbFile(model) {
9584
9730
  return { name: base + '_messages.lua', content };
9585
9731
  }
9586
9732
 
9733
+ function luaStubRequires(model) {
9734
+ if (!model.types) {
9735
+ return 'local messages = require("examples.' + baseName(model.name) + '_messages")\n\n'
9736
+ + zigMessageNames(model).map((msg) => 'local ' + msg + ' = messages.' + msg + '\n').join('')
9737
+ + '\n';
9738
+ }
9739
+ const origins = [];
9740
+ const seenNames = new Set();
9741
+ for (const svc of model.services) {
9742
+ for (const m of svc.methods) {
9743
+ for (const pair of [[m.input, m.inputFull], [m.output, m.outputFull]]) {
9744
+ if (seenNames.has(pair[0])) continue;
9745
+ seenNames.add(pair[0]);
9746
+ origins.push({ name: pair[0], file: lpResolve(model, pair[1]).file });
9747
+ }
9748
+ }
9749
+ }
9750
+ const files = [...new Set(origins.map((o) => o.file))];
9751
+ return files.map((fn) => {
9752
+ const b = baseName(fn);
9753
+ return 'local ' + lpFlat('', b) + 'Messages = require("examples.' + b + '_messages")\n';
9754
+ }).join('')
9755
+ + '\n'
9756
+ + origins.map((o) => 'local ' + o.name + ' = ' + lpFlat('', baseName(o.file)) + 'Messages.' + o.name + '\n').join('')
9757
+ + '\n';
9758
+ }
9759
+
9587
9760
  function emitLuaFile(model, params) {
9588
9761
  const base = baseName(model.name);
9589
9762
  const stub = {
@@ -9594,13 +9767,11 @@ function emitLuaFile(model, params) {
9594
9767
  + 'local serverModule = require("grpcdc.server")\n'
9595
9768
  + 'local statusModule = require("grpcdc.status")\n'
9596
9769
  + 'local wire = require("grpcdc.wire")\n'
9597
- + 'local messages = require("examples.' + base + '_messages")\n\n'
9770
+ + luaStubRequires(model)
9598
9771
  + 'local Channel = channelModule.Channel\n'
9599
9772
  + 'local Server = serverModule.Server\n'
9600
9773
  + 'local Status = statusModule.Status\n'
9601
9774
  + 'local EndOfStream = statusModule.EndOfStream\n\n'
9602
- + zigMessageNames(model).map((msg) => 'local ' + msg + ' = messages.' + msg + '\n').join('')
9603
- + '\n'
9604
9775
  + model.services.map(luaService).join('')
9605
9776
  + model.services.map(luaRegisterService).join('')
9606
9777
  + 'return {\n'
@@ -9622,47 +9793,66 @@ function rbDeprecated(m) {
9622
9793
  return m.deprecated ? ' warn "deprecated"\n' : '';
9623
9794
  }
9624
9795
 
9625
- function rbClientMethodKind(pb, m, fiber) {
9796
+ function rbStubRef(model, full) {
9797
+ const e = rbpResolve(model, full);
9798
+ return rbpModuleName(e) + '::' + rbpFlat(e.pkg, e.msg.fullName);
9799
+ }
9800
+
9801
+ function rbStubRequires(model) {
9802
+ if (!model.types) return 'require_relative "' + baseName(model.name) + '_pb"\n';
9803
+ const files = new Set();
9804
+ for (const svc of model.services) {
9805
+ for (const m of svc.methods) {
9806
+ files.add(rbpResolve(model, m.inputFull).file);
9807
+ files.add(rbpResolve(model, m.outputFull).file);
9808
+ }
9809
+ }
9810
+ return [...files].map((fn) => 'require_relative "' + baseName(fn) + '_pb"\n').join('');
9811
+ }
9812
+
9813
+ function rbClientMethodKind(model, m, fiber) {
9626
9814
  const path = q(m.path);
9627
9815
  const recvCls = fiber ? 'FiberRecvStream' : 'RecvStream';
9816
+ const resp = rbStubRef(model, m.outputFull);
9628
9817
  switch (m.kind) {
9629
9818
  case 'unary':
9630
9819
  return ' def ' + m.name + '(req, metadata = nil, timeout: nil)\n'
9631
9820
  + rbDeprecated(m)
9632
- + ' @channel.unary(' + path + ', req, ' + pb + '::' + m.output + '.new, metadata, timeout: timeout)\n end\n\n';
9821
+ + ' @channel.unary(' + path + ', req, ' + resp + '.new, metadata, timeout: timeout)\n end\n\n';
9633
9822
  case 'server-streaming':
9634
9823
  return ' def ' + m.name + '(req, metadata = nil, timeout: nil)\n'
9635
9824
  + rbDeprecated(m)
9636
9825
  + ' stream = @channel.server_stream(' + path + ', req, metadata, timeout: timeout)\n'
9637
- + ' ' + recvCls + '.new(stream, ' + pb + '::' + m.output + ')\n end\n\n';
9826
+ + ' ' + recvCls + '.new(stream, ' + resp + ')\n end\n\n';
9638
9827
  case 'client-streaming':
9639
9828
  return ' def ' + m.name + '(reqs, metadata = nil, timeout: nil)\n'
9640
9829
  + rbDeprecated(m)
9641
- + ' @channel.client_stream(' + path + ', reqs, ' + pb + '::' + m.output + '.new, metadata, timeout: timeout)\n end\n\n';
9830
+ + ' @channel.client_stream(' + path + ', reqs, ' + resp + '.new, metadata, timeout: timeout)\n end\n\n';
9642
9831
  default:
9643
9832
  return ' def ' + m.name + '(reqs, metadata = nil, timeout: nil)\n'
9644
9833
  + rbDeprecated(m)
9645
9834
  + ' stream = @channel.bidi(' + path + ', reqs, metadata, timeout: timeout)\n'
9646
- + ' ' + recvCls + '.new(stream, ' + pb + '::' + m.output + ')\n end\n\n';
9835
+ + ' ' + recvCls + '.new(stream, ' + resp + ')\n end\n\n';
9647
9836
  }
9648
9837
  }
9649
9838
 
9650
- function rbServerHandler(pb, m) {
9839
+ function rbServerHandler(model, m) {
9651
9840
  const handlerVar = snake(m.name) + '_handler';
9652
9841
  const impl = m.implName;
9842
+ const req = rbStubRef(model, m.inputFull);
9653
9843
  switch (m.kind) {
9654
9844
  case 'unary':
9655
9845
  return ' ' + handlerVar + ' = lambda do |ctx, reqs, sink|\n'
9656
- + ' req = reqs.recv_into(' + pb + '::' + m.input + '.new)\n'
9846
+ + ' req = reqs.recv_into(' + req + '.new)\n'
9657
9847
  + ' resp = impl.' + impl + '(ctx, req)\n'
9658
9848
  + ' sink.send(resp.marshal_dc)\n end\n\n';
9659
9849
  case 'server-streaming':
9660
9850
  return ' ' + handlerVar + ' = lambda do |ctx, reqs, sink|\n'
9661
- + ' req = reqs.recv_into(' + pb + '::' + m.input + '.new)\n'
9851
+ + ' req = reqs.recv_into(' + req + '.new)\n'
9662
9852
  + ' impl.' + impl + '(req, SendStream.new(ctx, sink))\n end\n\n';
9663
9853
  case 'client-streaming':
9664
9854
  return ' ' + handlerVar + ' = lambda do |ctx, reqs, sink|\n'
9665
- + ' stream = ClientStreamImpl.new(ctx, reqs, ' + pb + '::' + m.input + ')\n'
9855
+ + ' stream = ClientStreamImpl.new(ctx, reqs, ' + req + ')\n'
9666
9856
  + ' impl.' + impl + '(stream)\n'
9667
9857
  + ' if stream.resp.nil?\n'
9668
9858
  + ' raise Grpcdc::StatusError.new(Grpcdc::CODE_INTERNAL, "client-streaming handler never called SendAndClose")\n'
@@ -9670,7 +9860,7 @@ function rbServerHandler(pb, m) {
9670
9860
  + ' sink.send(stream.resp.marshal_dc)\n end\n\n';
9671
9861
  default:
9672
9862
  return ' ' + handlerVar + ' = lambda do |ctx, reqs, sink|\n'
9673
- + ' impl.' + impl + '(BidiStream.new(ctx, reqs, sink, ' + pb + '::' + m.input + '))\n end\n\n';
9863
+ + ' impl.' + impl + '(BidiStream.new(ctx, reqs, sink, ' + req + '))\n end\n\n';
9674
9864
  }
9675
9865
  }
9676
9866
 
@@ -9698,6 +9888,16 @@ const RB_STREAM_HELPERS = ` # Client receiving stream: recv raises EOFError at
9698
9888
  @stream.recv(@resp_cls.new)
9699
9889
  end
9700
9890
 
9891
+ # Response initial metadata (after the first recv).
9892
+ def headers
9893
+ @stream.headers&.metadata
9894
+ end
9895
+
9896
+ # Response trailing metadata (after the call ends).
9897
+ def trailers
9898
+ @stream.trailers
9899
+ end
9900
+
9701
9901
  # Abandon the call early: RST so the server stops producing.
9702
9902
  def cancel
9703
9903
  @stream.cancel
@@ -9808,6 +10008,16 @@ const RB_STREAM_HELPERS = ` # Client receiving stream: recv raises EOFError at
9808
10008
  value
9809
10009
  end
9810
10010
 
10011
+ # Response initial metadata (after the first recv).
10012
+ def headers
10013
+ @stream.headers&.metadata
10014
+ end
10015
+
10016
+ # Response trailing metadata (after the call ends).
10017
+ def trailers
10018
+ @stream.trailers
10019
+ end
10020
+
9811
10021
  def cancel
9812
10022
  @stream.cancel
9813
10023
  end
@@ -9837,19 +10047,19 @@ const RB_STREAM_HELPERS = ` # Client receiving stream: recv raises EOFError at
9837
10047
 
9838
10048
  `;
9839
10049
 
9840
- function rbService(pb, svc) {
10050
+ function rbService(model, svc) {
9841
10051
  const sname = svc.name;
9842
10052
  const all = svc.methods.concat(aliasClientMethods(svc));
9843
10053
  const allServer = svc.methods.concat(aliasServerMethods(svc));
9844
10054
  return ' class ' + sname + 'Client\n def initialize(channel)\n @channel = channel\n end\n\n'
9845
- + all.map((m) => rbClientMethodKind(pb, m, false)).join('')
10055
+ + all.map((m) => rbClientMethodKind(model, m, false)).join('')
9846
10056
  + ' end\n\n'
9847
10057
  + ' # Fiber client: wraps a Grpcdc::FiberChannel (a sync Channel is wrapped).\n'
9848
10058
  + ' class ' + sname + 'ClientFiber\n def initialize(channel)\n @channel = channel.is_a?(Grpcdc::FiberChannel) ? channel : Grpcdc::FiberChannel.new(channel)\n end\n\n'
9849
- + all.map((m) => rbClientMethodKind(pb, m, true)).join('')
10059
+ + all.map((m) => rbClientMethodKind(model, m, true)).join('')
9850
10060
  + ' end\n\n'
9851
10061
  + ' def self.register_' + snake(sname) + '_server(server, impl)\n'
9852
- + allServer.map((m) => rbServerHandler(pb, m)).join('')
10062
+ + allServer.map((m) => rbServerHandler(model, m)).join('')
9853
10063
  + ' server.register_service(Grpcdc::ServiceDesc.new(\n ' + q(svc.fullName) + ',\n [\n'
9854
10064
  + allServer.map(rbMethodEntry).join('')
9855
10065
  + ' ]\n ))\n end\n';
@@ -10148,9 +10358,11 @@ function rbpMessageClass(model, pb, msg) {
10148
10358
  + ' def unmarshal_dc(data)\n'
10149
10359
  + ' @unknown_fields = "".b\n'
10150
10360
  + msg.fields.map((f) => ' @' + f.name + ' = ' + rbpDefault(model, f) + '\n').join('')
10151
- + ' r = Reader.new(data)\n loop do\n item = r.field\n break if item.nil?\n\n num, wire, varint_value, bytes_value, fixed_value, raw_value = item\n case num\n'
10152
- + msg.fields.map((f) => rbpDecodeCase(model, f)).join('')
10153
- + ' else\n @unknown_fields = @unknown_fields + raw_value\n end\n end\n self\n end\n\n'
10361
+ + ' r = Reader.new(data)\n loop do\n item = r.field\n break if item.nil?\n\n num, wire, varint_value, bytes_value, fixed_value, raw_value = item\n'
10362
+ + (msg.fields.length
10363
+ ? ' case num\n' + msg.fields.map((f) => rbpDecodeCase(model, f)).join('') + ' else\n @unknown_fields = @unknown_fields + raw_value\n end\n'
10364
+ : ' @unknown_fields = @unknown_fields + raw_value\n')
10365
+ + ' end\n self\n end\n\n'
10154
10366
  + ' def ==(other)\n other.is_a?(' + name + ') && '
10155
10367
  + (msg.fields.length ? msg.fields.map((f) => '@' + f.name + ' == other.' + f.name).join(' && ') : 'true')
10156
10368
  + '\n end\n'
@@ -10209,10 +10421,11 @@ function emitRubyFile(model, params) {
10209
10421
  name: base + '_grpc_dc.rb',
10210
10422
  content: '# @generated by protoc-gen-grpc-dc-ruby. DO NOT EDIT.\n'
10211
10423
  + '# source: ' + model.name + '\n\n'
10212
- + 'require_relative "' + base + '_pb"\nrequire "grpcdc"\n\n'
10424
+ + rbStubRequires(model)
10425
+ + 'require "grpcdc"\n\n'
10213
10426
  + 'module ' + mod + '\n'
10214
10427
  + RB_STREAM_HELPERS
10215
- + model.services.map((svc) => rbService(pb, svc)).join('')
10428
+ + model.services.map((svc) => rbService(model, svc)).join('')
10216
10429
  + 'end\n',
10217
10430
  };
10218
10431
  const pbFile = emitRubyPbFile(model);
@@ -10226,33 +10439,51 @@ function phpDeprecated(m) {
10226
10439
  return m.deprecated ? ' trigger_error("deprecated", E_USER_DEPRECATED);\n' : '';
10227
10440
  }
10228
10441
 
10229
- function phpClientMethodKind(pb, m, fiber) {
10442
+ function phpStubRef(model, full) {
10443
+ const e = phpbResolve(model, full);
10444
+ return '\\' + phpbNamespace(e) + '\\' + phpbFlat(e.pkg, e.msg.fullName);
10445
+ }
10446
+
10447
+ function phpStubRequires(model) {
10448
+ if (!model.types) return 'require_once __DIR__ . "/' + baseName(model.name) + '_pb.php";\n';
10449
+ const files = new Set();
10450
+ for (const svc of model.services) {
10451
+ for (const m of svc.methods) {
10452
+ files.add(phpbResolve(model, m.inputFull).file);
10453
+ files.add(phpbResolve(model, m.outputFull).file);
10454
+ }
10455
+ }
10456
+ return [...files].map((fn) => 'require_once __DIR__ . "/' + baseName(fn) + '_pb.php";\n').join('');
10457
+ }
10458
+
10459
+ function phpClientMethodKind(model, m, fiber) {
10230
10460
  const path = q(m.path);
10231
10461
  const depr = phpDeprecated(m);
10232
10462
  const recvCls = fiber ? 'FiberRecvStream' : 'RecvStream';
10233
- const type = (t) => '\\' + pb + '\\' + t;
10463
+ const reqT = phpStubRef(model, m.inputFull);
10464
+ const respT = phpStubRef(model, m.outputFull);
10234
10465
  switch (m.kind) {
10235
10466
  case 'unary':
10236
- return ' public function ' + m.name + '(' + type(m.input) + ' $req, ?array $metadata = null, ?float $timeout = null): ' + type(m.output) + '\n'
10237
- + ' {\n' + depr + ' return $this->channel->unary(' + path + ', $req, new ' + type(m.output) + '(), $metadata, $timeout);\n }\n\n';
10467
+ return ' public function ' + m.name + '(' + reqT + ' $req, ?array $metadata = null, ?float $timeout = null): ' + respT + '\n'
10468
+ + ' {\n' + depr + ' return $this->channel->unary(' + path + ', $req, new ' + respT + '(), $metadata, $timeout);\n }\n\n';
10238
10469
  case 'server-streaming':
10239
- return ' public function ' + m.name + '(' + type(m.input) + ' $req, ?array $metadata = null, ?float $timeout = null): ' + recvCls + '\n'
10470
+ return ' public function ' + m.name + '(' + reqT + ' $req, ?array $metadata = null, ?float $timeout = null): ' + recvCls + '\n'
10240
10471
  + ' {\n' + depr + ' $stream = $this->channel->serverStream(' + path + ', $req, $metadata, $timeout);\n'
10241
- + ' return new ' + recvCls + '($stream, ' + type(m.output) + '::class);\n }\n\n';
10472
+ + ' return new ' + recvCls + '($stream, ' + respT + '::class);\n }\n\n';
10242
10473
  case 'client-streaming':
10243
- return ' public function ' + m.name + '(array $reqs, ?array $metadata = null, ?float $timeout = null): ' + type(m.output) + '\n'
10244
- + ' {\n' + depr + ' return $this->channel->clientStream(' + path + ', $reqs, new ' + type(m.output) + '(), $metadata, $timeout);\n }\n\n';
10474
+ return ' public function ' + m.name + '(array $reqs, ?array $metadata = null, ?float $timeout = null): ' + respT + '\n'
10475
+ + ' {\n' + depr + ' return $this->channel->clientStream(' + path + ', $reqs, new ' + respT + '(), $metadata, $timeout);\n }\n\n';
10245
10476
  default:
10246
10477
  return ' public function ' + m.name + '(array $reqs, ?array $metadata = null, ?float $timeout = null): ' + recvCls + '\n'
10247
10478
  + ' {\n' + depr + ' $stream = $this->channel->bidi(' + path + ', $reqs, $metadata, $timeout);\n'
10248
- + ' return new ' + recvCls + '($stream, ' + type(m.output) + '::class);\n }\n\n';
10479
+ + ' return new ' + recvCls + '($stream, ' + respT + '::class);\n }\n\n';
10249
10480
  }
10250
10481
  }
10251
10482
 
10252
- function phpServerHandler(pb, m) {
10483
+ function phpServerHandler(model, m) {
10253
10484
  const handlerVar = '$' + snake(m.name) + 'Handler';
10254
10485
  const impl = m.implName;
10255
- const type = (t) => '\\' + pb + '\\' + t;
10486
+ const type = (t) => phpStubRef(model, m.inputFull);
10256
10487
  const head = ' ' + handlerVar + ' = function (\\Grpcdc\\CallContext $ctx, \\Grpcdc\\RequestStream $reqs, \\Grpcdc\\ResponseSink $sink) use ($impl) {\n';
10257
10488
  switch (m.kind) {
10258
10489
  case 'unary':
@@ -10307,6 +10538,18 @@ class RecvStream
10307
10538
  return $this->stream->recv(new $cls());
10308
10539
  }
10309
10540
 
10541
+ /** Response initial metadata (after the first recv). */
10542
+ public function headers(): ?array
10543
+ {
10544
+ return $this->stream->headers?->metadata;
10545
+ }
10546
+
10547
+ /** Response trailing metadata (after the call ends). */
10548
+ public function trailers(): ?array
10549
+ {
10550
+ return $this->stream->trailers;
10551
+ }
10552
+
10310
10553
  /** Abandon the call early: RST so the server stops producing. */
10311
10554
  public function cancel(): void
10312
10555
  {
@@ -10480,6 +10723,18 @@ class FiberRecvStream
10480
10723
  }
10481
10724
  }
10482
10725
 
10726
+ /** Response initial metadata (after the first recv). */
10727
+ public function headers(): ?array
10728
+ {
10729
+ return $this->stream->headers?->metadata;
10730
+ }
10731
+
10732
+ /** Response trailing metadata (after the call ends). */
10733
+ public function trailers(): ?array
10734
+ {
10735
+ return $this->stream->trailers;
10736
+ }
10737
+
10483
10738
  public function cancel(): void
10484
10739
  {
10485
10740
  $this->stream->cancel();
@@ -10498,19 +10753,19 @@ class FiberRecvStream
10498
10753
 
10499
10754
  `;
10500
10755
 
10501
- function phpService(pb, svc) {
10756
+ function phpService(model, svc) {
10502
10757
  const sname = svc.name;
10503
10758
  const all = svc.methods.concat(aliasClientMethods(svc));
10504
10759
  const allServer = svc.methods.concat(aliasServerMethods(svc));
10505
10760
  return 'class ' + sname + 'Client\n{\n private \\Grpcdc\\Channel $channel;\n\n public function __construct(\\Grpcdc\\Channel $channel)\n {\n $this->channel = $channel;\n }\n\n'
10506
- + all.map((m) => phpClientMethodKind(pb, m, false)).join('')
10761
+ + all.map((m) => phpClientMethodKind(model, m, false)).join('')
10507
10762
  + '}\n\n'
10508
10763
  + '// Fiber client: wraps a Grpcdc\\FiberChannel (a sync Channel is wrapped).\n'
10509
10764
  + 'class ' + sname + 'ClientFiber\n{\n private \\Grpcdc\\FiberChannel $channel;\n\n public function __construct($channel)\n {\n $this->channel = $channel instanceof \\Grpcdc\\FiberChannel ? $channel : new \\Grpcdc\\FiberChannel($channel);\n }\n\n'
10510
- + all.map((m) => phpClientMethodKind(pb, m, true)).join('')
10765
+ + all.map((m) => phpClientMethodKind(model, m, true)).join('')
10511
10766
  + '}\n\n'
10512
10767
  + 'function register' + sname + 'Server(\\Grpcdc\\Server $server, object $impl): void\n{\n'
10513
- + allServer.map((m) => phpServerHandler(pb, m)).join('')
10768
+ + allServer.map((m) => phpServerHandler(model, m)).join('')
10514
10769
  + ' $server->registerService(new \\Grpcdc\\ServiceDesc(\n ' + q(svc.fullName) + ',\n [\n'
10515
10770
  + allServer.map(phpMethodEntry).join('')
10516
10771
  + ' ]\n ));\n}\n';
@@ -10538,9 +10793,12 @@ function phpbFieldName(f) {
10538
10793
  return f.jsonName ? f.jsonName : phpbCamel(f.name);
10539
10794
  }
10540
10795
 
10796
+ const PHPB_RESERVED = new Set(('abstract and array as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum eval exit extends final finally fn for foreach function global goto if implements include include_once instanceof insteadof interface isset list match namespace new or parent print private protected public readonly require require_once return self static switch throw trait try unset use var while xor yield int float bool string true false null void iterable object mixed never resource numeric').split(' '));
10797
+
10541
10798
  function phpbFlat(pkg, full) {
10542
10799
  const rel = pkg && full.startsWith(pkg + '.') ? full.slice(pkg.length + 1) : full;
10543
- return rel.split('.').join('_');
10800
+ const flat = rel.split('.').join('_');
10801
+ return PHPB_RESERVED.has(flat.toLowerCase()) ? flat + '_' : flat;
10544
10802
  }
10545
10803
 
10546
10804
  function phpbResolve(model, typeName) {
@@ -10896,10 +11154,10 @@ function emitPhpFile(model, params) {
10896
11154
  content: '<?php\n// @generated by protoc-gen-grpc-dc-php. DO NOT EDIT.\n'
10897
11155
  + '// source: ' + model.name + '\n\n'
10898
11156
  + 'namespace ' + ns + ';\n\n'
10899
- + 'require_once __DIR__ . "/' + base + '_pb.php";\n'
11157
+ + phpStubRequires(model)
10900
11158
  + 'require_once __DIR__ . "/../grpcdc.php";\n\n'
10901
11159
  + PHP_STREAM_HELPERS
10902
- + model.services.map((svc) => phpService(pb, svc)).join(''),
11160
+ + model.services.map((svc) => phpService(model, svc)).join(''),
10903
11161
  };
10904
11162
  const pbFile = emitPhpPbFile(model);
10905
11163
  return pbFile ? [stub, pbFile] : stub;