grpc-dc 0.32.10 → 0.32.12

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.10",
3
+ "version": "0.32.12",
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",
@@ -1637,8 +1637,26 @@ const PY_STREAM_HELPERS = `class _RecvStream:
1637
1637
  self._resp_cls = resp_cls
1638
1638
 
1639
1639
  def recv(self):
1640
+ if self._stream is None:
1641
+ raise EOFError("stream closed")
1640
1642
  return self._stream.recv(self._resp_cls())
1641
1643
 
1644
+ def close(self):
1645
+ """Abandon the call early: RST so the server stops."""
1646
+ stream, self._stream = self._stream, None
1647
+ if stream is not None:
1648
+ stream.cancel()
1649
+
1650
+ def __del__(self):
1651
+ self.close()
1652
+
1653
+ def __enter__(self):
1654
+ return self
1655
+
1656
+ def __exit__(self, *exc):
1657
+ self.close()
1658
+ return False
1659
+
1642
1660
  def __iter__(self):
1643
1661
  return self
1644
1662
 
@@ -1705,6 +1723,9 @@ class _AsyncRecvStream:
1705
1723
  def cancel(self):
1706
1724
  self._stream.cancel()
1707
1725
 
1726
+ async def aclose(self):
1727
+ self.cancel()
1728
+
1708
1729
  def __aiter__(self):
1709
1730
  return self
1710
1731
 
@@ -3102,8 +3123,11 @@ function rpCamel(s) {
3102
3123
  return s.split('_').map((p) => (p ? p[0].toUpperCase() + p.slice(1).toLowerCase() : '')).join('');
3103
3124
  }
3104
3125
 
3126
+ const RP_RUST_KEYWORDS = new Set(['type', 'ref', 'box', 'self', 'Self', 'crate', 'super', 'move', 'static', 'mut', 'fn', 'struct', 'enum', 'impl', 'trait', 'loop', 'match', 'mod', 'pub', 'use', 'where', 'async', 'await', 'dyn', 'abstract', 'become', 'do', 'final', 'macro', 'override', 'priv', 'typeof', 'unsized', 'virtual', 'yield', 'try', 'gen']);
3127
+
3105
3128
  function rpFieldName(f) {
3106
- return rpSnake(f.name);
3129
+ const name = rpSnake(f.name);
3130
+ return RP_RUST_KEYWORDS.has(name) ? 'r#' + name : name;
3107
3131
  }
3108
3132
 
3109
3133
  function rpFlat(pkg, full) {
@@ -3596,14 +3620,21 @@ function javaClientTimeoutMethod(m, svc) {
3596
3620
 
3597
3621
  function javaClientStreamClass(m, svc) {
3598
3622
  if (m.kind !== 'server-streaming' && m.kind !== 'bidi') return '';
3599
- return ' /** Receiving stream for ' + svc + '.' + m.name + ': recv() throws EOFException at end. */\n'
3600
- + ' public static final class ' + svc + m.name + 'Stream {\n'
3623
+ return ' /** Receiving stream for ' + svc + '.' + m.name + ': recv() throws EOFException at end. Close to abandon early (RST). */\n'
3624
+ + ' public static final class ' + svc + m.name + 'Stream implements AutoCloseable {\n'
3601
3625
  + ' private final Channel.ClientStream stream;\n\n'
3602
3626
  + ' ' + svc + m.name + 'Stream(Channel.ClientStream stream) {\n'
3603
3627
  + ' this.stream = stream;\n }\n\n'
3604
3628
  + ' public ' + m.output + ' recv() throws Exception {\n'
3605
3629
  + ' ' + m.output + ' resp = new ' + m.output + '();\n'
3606
- + ' stream.recv(resp);\n return resp;\n }\n }\n\n';
3630
+ + ' stream.recv(resp);\n return resp;\n }\n\n'
3631
+ + ' /** Abort this stream (sends RST, wakes a pending recv). */\n'
3632
+ + ' public void cancel() {\n'
3633
+ + ' stream.cancel();\n }\n\n'
3634
+ + ' /** Abandon the call if still live (RST); no-op once terminated. */\n'
3635
+ + ' @Override\n'
3636
+ + ' public void close() {\n'
3637
+ + ' stream.close();\n }\n }\n\n';
3607
3638
  }
3608
3639
 
3609
3640
  function javaServerIfaceMethodRaw(m, svc) {
@@ -3928,6 +3959,12 @@ function jpExplicitLiteral(model, f) {
3928
3959
  }
3929
3960
  }
3930
3961
 
3962
+ function jpBoxedDefault(model, f) {
3963
+ if (f.type === 1) return '0.0';
3964
+ if (f.type === 2) return '0.0f';
3965
+ return jpDefault(model, f);
3966
+ }
3967
+
3931
3968
  function jpDefault(model, f) {
3932
3969
  const lit = jpExplicitLiteral(model, f);
3933
3970
  if (lit !== null) return lit;
@@ -4163,8 +4200,8 @@ function jpMapHelpers(model, entry, support) {
4163
4200
  + jpEncodeSingular(model, { ...valF, label: 1 }, 'value', ' ', support)
4164
4201
  + ' return w.toBytes();\n }\n\n'
4165
4202
  + ' static Object[] ' + base + 'Decode(byte[] bytes) {\n'
4166
- + ' ' + kt + ' key = ' + jpDefault(model, { ...keyF, label: 1 }) + ';\n'
4167
- + ' ' + vt + ' value = ' + jpDefault(model, { ...valF, label: 1 }) + ';\n'
4203
+ + ' ' + kt + ' key = ' + jpBoxedDefault(model, { ...keyF, label: 1 }) + ';\n'
4204
+ + ' ' + vt + ' value = ' + jpBoxedDefault(model, { ...valF, label: 1 }) + ';\n'
4168
4205
  + ' Reader r = new Reader(bytes);\n Field field;\n while ((field = r.next()) != null) {\n switch (field.number) {\n'
4169
4206
  + ' case ' + keyF.number + ': ' + jpDecodeSingularStmt(model, { ...keyF, label: 1 }, 'key') + ' break;\n'
4170
4207
  + ' case ' + valF.number + ': ' + jpDecodeSingularStmt(model, { ...valF, label: 1 }, 'value') + ' break;\n'
@@ -4346,6 +4383,22 @@ function emitJavaPbFiles(model) {
4346
4383
  return files;
4347
4384
  }
4348
4385
 
4386
+ function javaQualifyType(pkg, simple, full) {
4387
+ if (!full || !pkg || full.startsWith(pkg + '.')) return simple;
4388
+ return full.split('.').slice(0, -1).join('.') + '.' + simple;
4389
+ }
4390
+
4391
+ function javaQualifyServices(pkg, services) {
4392
+ return services.map((svc) => ({
4393
+ ...svc,
4394
+ methods: svc.methods.map((m) => ({
4395
+ ...m,
4396
+ input: javaQualifyType(pkg, m.input, m.inputFull),
4397
+ output: javaQualifyType(pkg, m.output, m.outputFull),
4398
+ })),
4399
+ }));
4400
+ }
4401
+
4349
4402
  function emitJavaFile(model, params) {
4350
4403
  const base = baseName(model.name);
4351
4404
  const className = pascalName(base) + 'GrpcDc';
@@ -4360,7 +4413,7 @@ function emitJavaFile(model, params) {
4360
4413
  + 'import java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CompletionException;\n\n'
4361
4414
  + '/** Generated gRPC-over-DataChannels stubs for ' + model.name + '. */\n'
4362
4415
  + 'public final class ' + className + ' {\n private ' + className + '() {}\n\n'
4363
- + model.services.map(javaService).join('')
4416
+ + javaQualifyServices(pkg, model.services).map(javaService).join('')
4364
4417
  + '}\n',
4365
4418
  };
4366
4419
  const pbFiles = emitJavaPbFiles(model);
@@ -4403,13 +4456,17 @@ function csClientMethodRaw(m, svc) {
4403
4456
 
4404
4457
  function csClientStreamClass(m, svc) {
4405
4458
  if (m.kind !== 'server-streaming' && m.kind !== 'bidi') return '';
4406
- return ' /// <summary>Receiving stream for ' + svc + '.' + m.name + ': Recv() throws EndOfStreamException at end.</summary>\n'
4407
- + ' public sealed class ' + svc + m.name + 'Stream\n {\n'
4459
+ return ' /// <summary>Receiving stream for ' + svc + '.' + m.name + ': Recv() throws EndOfStreamException at end. Dispose to abandon early (RST).</summary>\n'
4460
+ + ' public sealed class ' + svc + m.name + 'Stream : IDisposable\n {\n'
4408
4461
  + ' private readonly Channel.ClientStream _stream;\n\n'
4409
4462
  + ' internal ' + svc + m.name + 'Stream(Channel.ClientStream stream)\n {\n _stream = stream;\n }\n\n'
4410
4463
  + ' public ' + m.output + ' Recv()\n {\n'
4411
4464
  + ' var resp = new ' + m.output + '();\n'
4412
- + ' _stream.Recv(resp);\n return resp;\n }\n }\n\n';
4465
+ + ' _stream.Recv(resp);\n return resp;\n }\n\n'
4466
+ + ' /// <summary>Abort this stream (sends RST, wakes a pending Recv).</summary>\n'
4467
+ + ' public void Cancel() => _stream.Cancel();\n\n'
4468
+ + ' /// <summary>Abandon the call if still live (RST); no-op once terminated.</summary>\n'
4469
+ + ' public void Dispose() => _stream.Dispose();\n }\n\n';
4413
4470
  }
4414
4471
 
4415
4472
  function csServerIfaceMethodRaw(m, svc) {
@@ -4530,7 +4587,7 @@ function csClientAsyncMethod(m, svc) {
4530
4587
  return ' public async IAsyncEnumerable<' + m.output + '> ' + m.name + 'Async(' + m.input + ' req, IDictionary<string, string> metadata = null, TimeSpan? timeout = null,\n'
4531
4588
  + ' [EnumeratorCancellation] CancellationToken cancellationToken = default)\n'
4532
4589
  + ' {\n var stream = ' + m.name + '(req, metadata, timeout);\n'
4533
- + ' await foreach (var item in AsyncPump.Stream(stream.Recv, cancellationToken))\n'
4590
+ + ' await foreach (var item in AsyncPump.Stream(stream.Recv, stream.Cancel, cancellationToken))\n'
4534
4591
  + ' {\n yield return item;\n }\n }\n\n';
4535
4592
  case 'client-streaming':
4536
4593
  return ' public Task<' + m.output + '> ' + m.name + 'Async(IEnumerable<' + m.input + '> reqs, IDictionary<string, string> metadata = null, TimeSpan? timeout = null,\n'
@@ -4540,7 +4597,7 @@ function csClientAsyncMethod(m, svc) {
4540
4597
  return ' public async IAsyncEnumerable<' + m.output + '> ' + m.name + 'Async(IEnumerable<' + m.input + '> reqs, IDictionary<string, string> metadata = null, TimeSpan? timeout = null,\n'
4541
4598
  + ' [EnumeratorCancellation] CancellationToken cancellationToken = default)\n'
4542
4599
  + ' {\n var stream = ' + m.name + '(reqs, metadata, timeout);\n'
4543
- + ' await foreach (var item in AsyncPump.Stream(stream.Recv, cancellationToken))\n'
4600
+ + ' await foreach (var item in AsyncPump.Stream(stream.Recv, stream.Cancel, cancellationToken))\n'
4544
4601
  + ' {\n yield return item;\n }\n }\n\n';
4545
4602
  }
4546
4603
  }
@@ -6012,7 +6069,7 @@ function swiftClientStreamClass(m, svc) {
6012
6069
  + ' init(_ stream: Channel.ClientStream) { self.stream = stream }\n'
6013
6070
  + ' func Recv() throws -> ' + m.output + ' {\n'
6014
6071
  + ' let resp = ' + m.output + '()\n'
6015
- + ' try stream.Recv(resp)\n return resp\n }\n }\n\n';
6072
+ + ' try stream.Recv(resp)\n return resp\n }\n func Cancel() { stream.Cancel() }\n func Close() { stream.Close() }\n }\n\n';
6016
6073
  }
6017
6074
 
6018
6075
  function swiftClientAsyncMethod(m, svc) {
@@ -6024,10 +6081,17 @@ function swiftClientAsyncMethod(m, svc) {
6024
6081
  case 'bidi': {
6025
6082
  const reqsType = m.kind === 'bidi' ? '[' + m.input + ']' : m.input;
6026
6083
  return ' func ' + m.name + 'Async(_ reqs: ' + reqsType + ', _ metadata: [String: String]? = nil, _ timeout: Double? = nil) -> AsyncThrowingStream<' + m.output + ', Error> {\n'
6027
- + ' AsyncThrowingStream { continuation in\n'
6084
+ + ' let stream: ' + svc + m.name + 'Stream\n'
6085
+ + ' do {\n'
6086
+ + ' stream = try ' + m.name + '(reqs, metadata, timeout)\n'
6087
+ + ' } catch {\n'
6088
+ + ' return AsyncThrowingStream { continuation in\n'
6089
+ + ' continuation.finish(throwing: error)\n'
6090
+ + ' }\n'
6091
+ + ' }\n'
6092
+ + ' return AsyncThrowingStream { continuation in\n'
6028
6093
  + ' let task = Task.detached {\n'
6029
6094
  + ' do {\n'
6030
- + ' let stream = try self.' + m.name + '(reqs, metadata, timeout)\n'
6031
6095
  + ' while true {\n'
6032
6096
  + ' continuation.yield(try stream.Recv())\n }\n'
6033
6097
  + ' } catch is EndOfStreamError {\n'
@@ -6035,7 +6099,10 @@ function swiftClientAsyncMethod(m, svc) {
6035
6099
  + ' } catch {\n'
6036
6100
  + ' continuation.finish(throwing: error)\n }\n'
6037
6101
  + ' }\n'
6038
- + ' continuation.onTermination = { _ in task.cancel() }\n }\n }\n\n';
6102
+ + ' continuation.onTermination = { _ in\n'
6103
+ + ' stream.Cancel()\n'
6104
+ + ' task.cancel()\n'
6105
+ + ' }\n }\n }\n\n';
6039
6106
  }
6040
6107
  default:
6041
6108
  return ' func ' + m.name + 'Async(_ reqs: [' + m.input + '], _ metadata: [String: String]? = nil, _ timeout: Double? = nil) async throws -> ' + m.output + ' {\n'
@@ -6750,10 +6817,14 @@ function kotlinClientMethodRaw(m, svc) {
6750
6817
 
6751
6818
  function kotlinClientStreamClass(m, svc) {
6752
6819
  if (m.kind !== 'server-streaming' && m.kind !== 'bidi') return '';
6753
- return ' class ' + svc + m.name + 'Stream(private val stream: Channel.ClientStream) {\n'
6820
+ return ' class ' + svc + m.name + 'Stream(private val stream: Channel.ClientStream) : AutoCloseable {\n'
6754
6821
  + ' fun recv(): ' + m.output + ' {\n'
6755
6822
  + ' val resp = ' + m.output + '()\n'
6756
- + ' stream.recv(resp)\n return resp\n }\n }\n\n';
6823
+ + ' stream.recv(resp)\n return resp\n }\n\n'
6824
+ + ' /** Abort this stream (sends RST, wakes a pending recv). */\n'
6825
+ + ' fun cancel() = stream.cancel()\n\n'
6826
+ + ' /** Abandon the call if still live (RST); no-op once terminated. */\n'
6827
+ + ' override fun close() = stream.close()\n }\n\n';
6757
6828
  }
6758
6829
 
6759
6830
  function kotlinClientAsyncMethod(m, svc) {
@@ -6770,8 +6841,8 @@ function kotlinClientAsyncMethod(m, svc) {
6770
6841
  return ' suspend fun ' + m.name + 'Async(' + reqsSig + ', metadata: Map<String, String>? = null, timeout: java.time.Duration? = null): List<' + m.output + '> {\n'
6771
6842
  + ' return AsyncPump.await(' + m.name + 'Future(' + callArgs + ', metadata, timeout))\n }\n\n'
6772
6843
  + ' fun ' + m.name + 'Future(' + reqsSig + ', metadata: Map<String, String>? = null, timeout: java.time.Duration? = null): CompletableFuture<List<' + m.output + '>> {\n'
6773
- + ' return AsyncPump.future {\n'
6774
- + ' val stream = ' + m.name + '(' + callArgs + ', metadata, timeout)\n'
6844
+ + ' val stream = ' + m.name + '(' + callArgs + ', metadata, timeout)\n'
6845
+ + ' return AsyncPump.future(onCancel = { stream.cancel() }) {\n'
6775
6846
  + ' val out = ArrayList<' + m.output + '>()\n'
6776
6847
  + ' while (true) {\n'
6777
6848
  + ' try {\n out.add(stream.recv())\n'
@@ -7538,10 +7609,34 @@ function dartClientStreamClass(m, svc) {
7538
7609
  + ' final resp = ' + m.output + '();\n'
7539
7610
  + ' await _stream.recv(resp);\n return resp;\n }\n\n'
7540
7611
  + ' /// Responses as a Dart Stream (native async surface).\n'
7541
- + ' Stream<' + m.output + '> get responses async* {\n'
7542
- + ' while (true) {\n'
7543
- + ' try {\n yield await recv();\n'
7544
- + ' } on EndOfStreamError {\n return;\n }\n }\n }\n}\n\n';
7612
+ + ' /// Cancelling the subscription abandons the call:\n'
7613
+ + ' /// RST CANCELLED is sent so the server stops.\n'
7614
+ + ' Stream<' + m.output + '> get responses {\n'
7615
+ + ' var cancelled = false;\n'
7616
+ + ' late StreamController<' + m.output + '> controller;\n'
7617
+ + ' controller = StreamController<' + m.output + '>(\n'
7618
+ + ' onListen: () {\n'
7619
+ + ' () async {\n'
7620
+ + ' try {\n'
7621
+ + ' while (!cancelled) {\n'
7622
+ + ' controller.add(await recv());\n'
7623
+ + ' }\n'
7624
+ + ' } on EndOfStreamError {\n'
7625
+ + ' if (!cancelled) await controller.close();\n'
7626
+ + ' } catch (e, st) {\n'
7627
+ + ' if (!cancelled) {\n'
7628
+ + ' controller.addError(e, st);\n'
7629
+ + ' await controller.close();\n'
7630
+ + ' }\n'
7631
+ + ' }\n'
7632
+ + ' }();\n'
7633
+ + ' },\n'
7634
+ + ' onCancel: () {\n'
7635
+ + ' cancelled = true;\n'
7636
+ + ' _stream.cancel();\n'
7637
+ + ' },\n'
7638
+ + ' );\n'
7639
+ + ' return controller.stream;\n }\n}\n\n';
7545
7640
  }
7546
7641
 
7547
7642
  function dartServerStreamIface(m, svc) {
@@ -8235,8 +8330,7 @@ function zigServerStreamStruct(m, svc) {
8235
8330
  + ' pub fn send(self: *' + svc + m.name + 'Server, resp: *const ' + m.output + ') Status {\n'
8236
8331
  + ' const payload = resp.marshalDc(self.alloc);\n'
8237
8332
  + ' defer self.alloc.free(payload);\n'
8238
- + ' self.sink.send(payload);\n'
8239
- + ' return Status.ok();\n }\n};\n\n';
8333
+ + ' return self.sink.send(payload);\n }\n};\n\n';
8240
8334
  case 'client-streaming':
8241
8335
  return '/// Receives requests of a ' + m.name + ' call.\n'
8242
8336
  + 'pub const ' + svc + m.name + 'Server = struct {\n'
@@ -8263,8 +8357,7 @@ function zigServerStreamStruct(m, svc) {
8263
8357
  + ' pub fn send(self: *' + svc + m.name + 'Server, resp: *const ' + m.output + ') Status {\n'
8264
8358
  + ' const payload = resp.marshalDc(self.alloc);\n'
8265
8359
  + ' defer self.alloc.free(payload);\n'
8266
- + ' self.sink.send(payload);\n'
8267
- + ' return Status.ok();\n }\n};\n\n';
8360
+ + ' return self.sink.send(payload);\n }\n};\n\n';
8268
8361
  }
8269
8362
  }
8270
8363
 
@@ -8300,8 +8393,7 @@ function zigAdapter(m, svc) {
8300
8393
  + ' if (!st.isOk()) return st;\n'
8301
8394
  + ' const payload = resp.marshalDc(reqs.alloc);\n'
8302
8395
  + ' defer reqs.alloc.free(payload);\n'
8303
- + ' sink.send(payload);\n'
8304
- + ' return Status.ok();\n}\n\n';
8396
+ + ' return sink.send(payload);\n}\n\n';
8305
8397
  case 'server-streaming':
8306
8398
  return head
8307
8399
  + ' var req = ' + m.input + '{};\n'
@@ -8322,8 +8414,7 @@ function zigAdapter(m, svc) {
8322
8414
  + ' return Status.init(wire.codeInternal, "client-streaming handler never called sendAndClose");\n'
8323
8415
  + ' const payload = resp.marshalDc(reqs.alloc);\n'
8324
8416
  + ' defer reqs.alloc.free(payload);\n'
8325
- + ' sink.send(payload);\n'
8326
- + ' return Status.ok();\n}\n\n';
8417
+ + ' return sink.send(payload);\n}\n\n';
8327
8418
  default:
8328
8419
  return head
8329
8420
  + ' var stream = ' + svc + m.name + 'Server{ .reqs = reqs, .sink = sink, .alloc = reqs.alloc };\n'
@@ -8934,8 +9025,15 @@ function luaCoroClientStreamClass(m, svc) {
8934
9025
  + ' error(value, 0)\n end\n'
8935
9026
  + ' return value\nend\n\n'
8936
9027
  + 'function ' + t + ':cancel()\n self.stream:cancel()\nend\n\n'
9028
+ + '--- Abandon the call early: RST so the server stops producing.\n'
9029
+ + 'function ' + t + ':close()\n self.stream:close()\nend\n\n'
9030
+ + '--- To-be-closed (<close>) and GC abandon the call the same way.\n'
9031
+ + 'function ' + t + ':__close()\n self:close()\nend\n\n'
9032
+ + 'function ' + t + ':__gc()\n self:close()\nend\n\n'
8937
9033
  + '--- Generic-for iterator: for resp in stream:iter() do ... end\n'
8938
- + 'function ' + t + ':iter()\n return function() return self:next() end\nend\n\n';
9034
+ + '--- Breaking the loop closes the closable stream, RST-ing\n'
9035
+ + '--- the call unless it already terminated.\n'
9036
+ + 'function ' + t + ':iter()\n return function() return self:next() end, nil, nil, self\nend\n\n';
8939
9037
  }
8940
9038
 
8941
9039
  function luaCoroClientMethod(m, svc) {
@@ -8973,7 +9071,13 @@ function luaClientStreamClass(m, svc) {
8973
9071
  + '--- Next response; raises EndOfStream at the end of the call.\n'
8974
9072
  + 'function ' + t + ':recv()\n'
8975
9073
  + ' local resp = ' + m.output + '.new()\n'
8976
- + ' self.stream:recv(resp)\n return resp\nend\n\n';
9074
+ + ' self.stream:recv(resp)\n return resp\nend\n\n'
9075
+ + '--- Abandon the call early: RST so the server stops producing.\n'
9076
+ + 'function ' + t + ':close()\n self.stream:close()\nend\n\n'
9077
+ + 'function ' + t + ':cancel()\n self.stream:cancel()\nend\n\n'
9078
+ + '--- To-be-closed (<close>) and GC abandon the call the same way.\n'
9079
+ + 'function ' + t + ':__close()\n self:close()\nend\n\n'
9080
+ + 'function ' + t + ':__gc()\n self:close()\nend\n\n';
8977
9081
  }
8978
9082
 
8979
9083
  function luaServerStreamClass(m, svc) {
@@ -9548,15 +9652,30 @@ const RB_STREAM_HELPERS = ` # Client receiving stream: recv raises EOFError at
9548
9652
  @stream.recv(@resp_cls.new)
9549
9653
  end
9550
9654
 
9655
+ # Abandon the call early: RST so the server stops producing.
9656
+ def cancel
9657
+ @stream.cancel
9658
+ end
9659
+
9660
+ def close
9661
+ @stream.cancel
9662
+ end
9663
+
9551
9664
  def each
9552
9665
  return enum_for(:each) unless block_given?
9553
9666
 
9554
- loop do
9555
- begin
9556
- yield recv
9557
- rescue EOFError
9558
- return
9667
+ begin
9668
+ loop do
9669
+ begin
9670
+ yield recv
9671
+ rescue EOFError
9672
+ return
9673
+ end
9559
9674
  end
9675
+ ensure
9676
+ # Breaking out of the block abandons the call: RST so
9677
+ # the server stops producing (no-op once terminated).
9678
+ close
9560
9679
  end
9561
9680
  end
9562
9681
  end
@@ -9647,15 +9766,25 @@ const RB_STREAM_HELPERS = ` # Client receiving stream: recv raises EOFError at
9647
9766
  @stream.cancel
9648
9767
  end
9649
9768
 
9769
+ def close
9770
+ @stream.cancel
9771
+ end
9772
+
9650
9773
  def each
9651
9774
  return enum_for(:each) unless block_given?
9652
9775
 
9653
- loop do
9654
- begin
9655
- yield next_msg
9656
- rescue StopIteration
9657
- return
9776
+ begin
9777
+ loop do
9778
+ begin
9779
+ yield next_msg
9780
+ rescue StopIteration
9781
+ return
9782
+ end
9658
9783
  end
9784
+ ensure
9785
+ # Breaking out of the block abandons the call: RST so
9786
+ # the server stops producing (no-op once terminated).
9787
+ close
9659
9788
  end
9660
9789
  end
9661
9790
  end
@@ -10132,15 +10261,37 @@ class RecvStream
10132
10261
  return $this->stream->recv(new $cls());
10133
10262
  }
10134
10263
 
10264
+ /** Abandon the call early: RST so the server stops producing. */
10265
+ public function cancel(): void
10266
+ {
10267
+ $this->stream->cancel();
10268
+ }
10269
+
10270
+ public function close(): void
10271
+ {
10272
+ $this->stream->cancel();
10273
+ }
10274
+
10275
+ public function __destruct()
10276
+ {
10277
+ $this->close();
10278
+ }
10279
+
10135
10280
  /** @return \\Generator<int, object> */
10136
10281
  public function iterate(): \\Generator
10137
10282
  {
10283
+ $completed = false;
10138
10284
  try {
10139
10285
  while (true) {
10140
10286
  yield $this->recv();
10141
10287
  }
10142
10288
  } catch (\\Grpcdc\\CallClosed $e) {
10289
+ $completed = true;
10143
10290
  return;
10291
+ } finally {
10292
+ if (!$completed) {
10293
+ $this->close();
10294
+ }
10144
10295
  }
10145
10296
  }
10146
10297
  }
@@ -10268,12 +10419,18 @@ class FiberRecvStream
10268
10419
  /** @return \\Generator<int, object> */
10269
10420
  public function iterate(): \\Generator
10270
10421
  {
10422
+ $completed = false;
10271
10423
  try {
10272
10424
  while (true) {
10273
10425
  yield $this->next();
10274
10426
  }
10275
10427
  } catch (\\Grpcdc\\CallClosed $e) {
10428
+ $completed = true;
10276
10429
  return;
10430
+ } finally {
10431
+ if (!$completed) {
10432
+ $this->close();
10433
+ }
10277
10434
  }
10278
10435
  }
10279
10436
 
@@ -10281,6 +10438,16 @@ class FiberRecvStream
10281
10438
  {
10282
10439
  $this->stream->cancel();
10283
10440
  }
10441
+
10442
+ public function close(): void
10443
+ {
10444
+ $this->stream->cancel();
10445
+ }
10446
+
10447
+ public function __destruct()
10448
+ {
10449
+ $this->close();
10450
+ }
10284
10451
  }
10285
10452
 
10286
10453
  `;
@@ -10761,6 +10928,7 @@ function scalaFutureMethod(m) {
10761
10928
  return ' def ' + m.name + 'Future(req' + sig + ', metadata: Map[String, String] = null, timeout: java.time.Duration = null): scala.concurrent.Future[List[' + m.output + ']] = {\n'
10762
10929
  + ' grpcdc.Futures {\n'
10763
10930
  + ' val stream = ' + m.name + '(req' + arg + ', metadata, timeout)\n'
10931
+ + ' try {\n'
10764
10932
  + ' val out = scala.collection.mutable.ListBuffer[' + m.output + ']()\n'
10765
10933
  + ' var done = false\n'
10766
10934
  + ' while (!done) {\n'
@@ -10769,7 +10937,7 @@ function scalaFutureMethod(m) {
10769
10937
  + ' } catch {\n'
10770
10938
  + ' case e: java.io.EOFException => done = true\n'
10771
10939
  + ' }\n }\n'
10772
- + ' out.toList\n }\n }\n\n';
10940
+ + ' out.toList\n } finally {\n stream.close()\n }\n }\n }\n\n';
10773
10941
  }
10774
10942
  }
10775
10943
  }
@@ -10885,10 +11053,30 @@ function scalaService(svc) {
10885
11053
  return ps.length ? ps : [[req0, resp0]];
10886
11054
  };
10887
11055
  const streamClass = (kind, out) =>
10888
- ' class ' + scalaClientStreamName(svc, kind, out) + '(private val stream: grpcdc.Channel#ClientStream) {\n'
11056
+ ' class ' + scalaClientStreamName(svc, kind, out) + '(private val stream: grpcdc.Channel#ClientStream) extends scala.collection.Iterator[' + out + '] with AutoCloseable {\n'
10889
11057
  + ' def recv(): ' + out + ' = {\n'
10890
11058
  + ' val resp = new ' + out + '()\n'
10891
- + ' stream.recv(resp)\n resp\n }\n }\n\n';
11059
+ + ' stream.recv(resp)\n resp\n }\n'
11060
+ + ' private var pending: ' + out + ' = null\n'
11061
+ + ' private var finished: Boolean = false\n'
11062
+ + ' def hasNext: Boolean = {\n'
11063
+ + ' if (pending == null && !finished) {\n'
11064
+ + ' try {\n'
11065
+ + ' pending = recv()\n'
11066
+ + ' } catch {\n'
11067
+ + ' case e: java.io.EOFException => finished = true\n'
11068
+ + ' }\n'
11069
+ + ' }\n'
11070
+ + ' pending != null\n'
11071
+ + ' }\n'
11072
+ + ' def next(): ' + out + ' = {\n'
11073
+ + ' if (!hasNext) throw new NoSuchElementException("next on empty stream")\n'
11074
+ + ' val out = pending\n'
11075
+ + ' pending = null\n'
11076
+ + ' out\n'
11077
+ + ' }\n'
11078
+ + ' def cancel(): Unit = stream.cancel()\n'
11079
+ + ' def close(): Unit = stream.close()\n }\n\n';
10892
11080
  return ' /** Client for ' + svc.fullName + '. */\n'
10893
11081
  + ' class ' + sname + 'Client(private val channel: grpcdc.Channel) {\n'
10894
11082
  + classOutputs('server-streaming').map((out) => streamClass('server-streaming', out)).join('')