grpc-dc 0.32.9 → 0.32.11

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.9",
3
+ "version": "0.32.11",
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) {
@@ -4403,13 +4434,17 @@ function csClientMethodRaw(m, svc) {
4403
4434
 
4404
4435
  function csClientStreamClass(m, svc) {
4405
4436
  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'
4437
+ return ' /// <summary>Receiving stream for ' + svc + '.' + m.name + ': Recv() throws EndOfStreamException at end. Dispose to abandon early (RST).</summary>\n'
4438
+ + ' public sealed class ' + svc + m.name + 'Stream : IDisposable\n {\n'
4408
4439
  + ' private readonly Channel.ClientStream _stream;\n\n'
4409
4440
  + ' internal ' + svc + m.name + 'Stream(Channel.ClientStream stream)\n {\n _stream = stream;\n }\n\n'
4410
4441
  + ' public ' + m.output + ' Recv()\n {\n'
4411
4442
  + ' var resp = new ' + m.output + '();\n'
4412
- + ' _stream.Recv(resp);\n return resp;\n }\n }\n\n';
4443
+ + ' _stream.Recv(resp);\n return resp;\n }\n\n'
4444
+ + ' /// <summary>Abort this stream (sends RST, wakes a pending Recv).</summary>\n'
4445
+ + ' public void Cancel() => _stream.Cancel();\n\n'
4446
+ + ' /// <summary>Abandon the call if still live (RST); no-op once terminated.</summary>\n'
4447
+ + ' public void Dispose() => _stream.Dispose();\n }\n\n';
4413
4448
  }
4414
4449
 
4415
4450
  function csServerIfaceMethodRaw(m, svc) {
@@ -4530,7 +4565,7 @@ function csClientAsyncMethod(m, svc) {
4530
4565
  return ' public async IAsyncEnumerable<' + m.output + '> ' + m.name + 'Async(' + m.input + ' req, IDictionary<string, string> metadata = null, TimeSpan? timeout = null,\n'
4531
4566
  + ' [EnumeratorCancellation] CancellationToken cancellationToken = default)\n'
4532
4567
  + ' {\n var stream = ' + m.name + '(req, metadata, timeout);\n'
4533
- + ' await foreach (var item in AsyncPump.Stream(stream.Recv, cancellationToken))\n'
4568
+ + ' await foreach (var item in AsyncPump.Stream(stream.Recv, stream.Cancel, cancellationToken))\n'
4534
4569
  + ' {\n yield return item;\n }\n }\n\n';
4535
4570
  case 'client-streaming':
4536
4571
  return ' public Task<' + m.output + '> ' + m.name + 'Async(IEnumerable<' + m.input + '> reqs, IDictionary<string, string> metadata = null, TimeSpan? timeout = null,\n'
@@ -4540,7 +4575,7 @@ function csClientAsyncMethod(m, svc) {
4540
4575
  return ' public async IAsyncEnumerable<' + m.output + '> ' + m.name + 'Async(IEnumerable<' + m.input + '> reqs, IDictionary<string, string> metadata = null, TimeSpan? timeout = null,\n'
4541
4576
  + ' [EnumeratorCancellation] CancellationToken cancellationToken = default)\n'
4542
4577
  + ' {\n var stream = ' + m.name + '(reqs, metadata, timeout);\n'
4543
- + ' await foreach (var item in AsyncPump.Stream(stream.Recv, cancellationToken))\n'
4578
+ + ' await foreach (var item in AsyncPump.Stream(stream.Recv, stream.Cancel, cancellationToken))\n'
4544
4579
  + ' {\n yield return item;\n }\n }\n\n';
4545
4580
  }
4546
4581
  }
@@ -6012,7 +6047,7 @@ function swiftClientStreamClass(m, svc) {
6012
6047
  + ' init(_ stream: Channel.ClientStream) { self.stream = stream }\n'
6013
6048
  + ' func Recv() throws -> ' + m.output + ' {\n'
6014
6049
  + ' let resp = ' + m.output + '()\n'
6015
- + ' try stream.Recv(resp)\n return resp\n }\n }\n\n';
6050
+ + ' try stream.Recv(resp)\n return resp\n }\n func Cancel() { stream.Cancel() }\n func Close() { stream.Close() }\n }\n\n';
6016
6051
  }
6017
6052
 
6018
6053
  function swiftClientAsyncMethod(m, svc) {
@@ -6024,10 +6059,17 @@ function swiftClientAsyncMethod(m, svc) {
6024
6059
  case 'bidi': {
6025
6060
  const reqsType = m.kind === 'bidi' ? '[' + m.input + ']' : m.input;
6026
6061
  return ' func ' + m.name + 'Async(_ reqs: ' + reqsType + ', _ metadata: [String: String]? = nil, _ timeout: Double? = nil) -> AsyncThrowingStream<' + m.output + ', Error> {\n'
6027
- + ' AsyncThrowingStream { continuation in\n'
6062
+ + ' let stream: ' + svc + m.name + 'Stream\n'
6063
+ + ' do {\n'
6064
+ + ' stream = try ' + m.name + '(reqs, metadata, timeout)\n'
6065
+ + ' } catch {\n'
6066
+ + ' return AsyncThrowingStream { continuation in\n'
6067
+ + ' continuation.finish(throwing: error)\n'
6068
+ + ' }\n'
6069
+ + ' }\n'
6070
+ + ' return AsyncThrowingStream { continuation in\n'
6028
6071
  + ' let task = Task.detached {\n'
6029
6072
  + ' do {\n'
6030
- + ' let stream = try self.' + m.name + '(reqs, metadata, timeout)\n'
6031
6073
  + ' while true {\n'
6032
6074
  + ' continuation.yield(try stream.Recv())\n }\n'
6033
6075
  + ' } catch is EndOfStreamError {\n'
@@ -6035,7 +6077,10 @@ function swiftClientAsyncMethod(m, svc) {
6035
6077
  + ' } catch {\n'
6036
6078
  + ' continuation.finish(throwing: error)\n }\n'
6037
6079
  + ' }\n'
6038
- + ' continuation.onTermination = { _ in task.cancel() }\n }\n }\n\n';
6080
+ + ' continuation.onTermination = { _ in\n'
6081
+ + ' stream.Cancel()\n'
6082
+ + ' task.cancel()\n'
6083
+ + ' }\n }\n }\n\n';
6039
6084
  }
6040
6085
  default:
6041
6086
  return ' func ' + m.name + 'Async(_ reqs: [' + m.input + '], _ metadata: [String: String]? = nil, _ timeout: Double? = nil) async throws -> ' + m.output + ' {\n'
@@ -6750,10 +6795,14 @@ function kotlinClientMethodRaw(m, svc) {
6750
6795
 
6751
6796
  function kotlinClientStreamClass(m, svc) {
6752
6797
  if (m.kind !== 'server-streaming' && m.kind !== 'bidi') return '';
6753
- return ' class ' + svc + m.name + 'Stream(private val stream: Channel.ClientStream) {\n'
6798
+ return ' class ' + svc + m.name + 'Stream(private val stream: Channel.ClientStream) : AutoCloseable {\n'
6754
6799
  + ' fun recv(): ' + m.output + ' {\n'
6755
6800
  + ' val resp = ' + m.output + '()\n'
6756
- + ' stream.recv(resp)\n return resp\n }\n }\n\n';
6801
+ + ' stream.recv(resp)\n return resp\n }\n\n'
6802
+ + ' /** Abort this stream (sends RST, wakes a pending recv). */\n'
6803
+ + ' fun cancel() = stream.cancel()\n\n'
6804
+ + ' /** Abandon the call if still live (RST); no-op once terminated. */\n'
6805
+ + ' override fun close() = stream.close()\n }\n\n';
6757
6806
  }
6758
6807
 
6759
6808
  function kotlinClientAsyncMethod(m, svc) {
@@ -6770,8 +6819,8 @@ function kotlinClientAsyncMethod(m, svc) {
6770
6819
  return ' suspend fun ' + m.name + 'Async(' + reqsSig + ', metadata: Map<String, String>? = null, timeout: java.time.Duration? = null): List<' + m.output + '> {\n'
6771
6820
  + ' return AsyncPump.await(' + m.name + 'Future(' + callArgs + ', metadata, timeout))\n }\n\n'
6772
6821
  + ' 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'
6822
+ + ' val stream = ' + m.name + '(' + callArgs + ', metadata, timeout)\n'
6823
+ + ' return AsyncPump.future(onCancel = { stream.cancel() }) {\n'
6775
6824
  + ' val out = ArrayList<' + m.output + '>()\n'
6776
6825
  + ' while (true) {\n'
6777
6826
  + ' try {\n out.add(stream.recv())\n'
@@ -7538,10 +7587,34 @@ function dartClientStreamClass(m, svc) {
7538
7587
  + ' final resp = ' + m.output + '();\n'
7539
7588
  + ' await _stream.recv(resp);\n return resp;\n }\n\n'
7540
7589
  + ' /// 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';
7590
+ + ' /// Cancelling the subscription abandons the call:\n'
7591
+ + ' /// RST CANCELLED is sent so the server stops.\n'
7592
+ + ' Stream<' + m.output + '> get responses {\n'
7593
+ + ' var cancelled = false;\n'
7594
+ + ' late StreamController<' + m.output + '> controller;\n'
7595
+ + ' controller = StreamController<' + m.output + '>(\n'
7596
+ + ' onListen: () {\n'
7597
+ + ' () async {\n'
7598
+ + ' try {\n'
7599
+ + ' while (!cancelled) {\n'
7600
+ + ' controller.add(await recv());\n'
7601
+ + ' }\n'
7602
+ + ' } on EndOfStreamError {\n'
7603
+ + ' if (!cancelled) await controller.close();\n'
7604
+ + ' } catch (e, st) {\n'
7605
+ + ' if (!cancelled) {\n'
7606
+ + ' controller.addError(e, st);\n'
7607
+ + ' await controller.close();\n'
7608
+ + ' }\n'
7609
+ + ' }\n'
7610
+ + ' }();\n'
7611
+ + ' },\n'
7612
+ + ' onCancel: () {\n'
7613
+ + ' cancelled = true;\n'
7614
+ + ' _stream.cancel();\n'
7615
+ + ' },\n'
7616
+ + ' );\n'
7617
+ + ' return controller.stream;\n }\n}\n\n';
7545
7618
  }
7546
7619
 
7547
7620
  function dartServerStreamIface(m, svc) {
@@ -8235,8 +8308,7 @@ function zigServerStreamStruct(m, svc) {
8235
8308
  + ' pub fn send(self: *' + svc + m.name + 'Server, resp: *const ' + m.output + ') Status {\n'
8236
8309
  + ' const payload = resp.marshalDc(self.alloc);\n'
8237
8310
  + ' defer self.alloc.free(payload);\n'
8238
- + ' self.sink.send(payload);\n'
8239
- + ' return Status.ok();\n }\n};\n\n';
8311
+ + ' return self.sink.send(payload);\n }\n};\n\n';
8240
8312
  case 'client-streaming':
8241
8313
  return '/// Receives requests of a ' + m.name + ' call.\n'
8242
8314
  + 'pub const ' + svc + m.name + 'Server = struct {\n'
@@ -8263,8 +8335,7 @@ function zigServerStreamStruct(m, svc) {
8263
8335
  + ' pub fn send(self: *' + svc + m.name + 'Server, resp: *const ' + m.output + ') Status {\n'
8264
8336
  + ' const payload = resp.marshalDc(self.alloc);\n'
8265
8337
  + ' defer self.alloc.free(payload);\n'
8266
- + ' self.sink.send(payload);\n'
8267
- + ' return Status.ok();\n }\n};\n\n';
8338
+ + ' return self.sink.send(payload);\n }\n};\n\n';
8268
8339
  }
8269
8340
  }
8270
8341
 
@@ -8300,8 +8371,7 @@ function zigAdapter(m, svc) {
8300
8371
  + ' if (!st.isOk()) return st;\n'
8301
8372
  + ' const payload = resp.marshalDc(reqs.alloc);\n'
8302
8373
  + ' defer reqs.alloc.free(payload);\n'
8303
- + ' sink.send(payload);\n'
8304
- + ' return Status.ok();\n}\n\n';
8374
+ + ' return sink.send(payload);\n}\n\n';
8305
8375
  case 'server-streaming':
8306
8376
  return head
8307
8377
  + ' var req = ' + m.input + '{};\n'
@@ -8322,8 +8392,7 @@ function zigAdapter(m, svc) {
8322
8392
  + ' return Status.init(wire.codeInternal, "client-streaming handler never called sendAndClose");\n'
8323
8393
  + ' const payload = resp.marshalDc(reqs.alloc);\n'
8324
8394
  + ' defer reqs.alloc.free(payload);\n'
8325
- + ' sink.send(payload);\n'
8326
- + ' return Status.ok();\n}\n\n';
8395
+ + ' return sink.send(payload);\n}\n\n';
8327
8396
  default:
8328
8397
  return head
8329
8398
  + ' var stream = ' + svc + m.name + 'Server{ .reqs = reqs, .sink = sink, .alloc = reqs.alloc };\n'
@@ -8934,8 +9003,15 @@ function luaCoroClientStreamClass(m, svc) {
8934
9003
  + ' error(value, 0)\n end\n'
8935
9004
  + ' return value\nend\n\n'
8936
9005
  + 'function ' + t + ':cancel()\n self.stream:cancel()\nend\n\n'
9006
+ + '--- Abandon the call early: RST so the server stops producing.\n'
9007
+ + 'function ' + t + ':close()\n self.stream:close()\nend\n\n'
9008
+ + '--- To-be-closed (<close>) and GC abandon the call the same way.\n'
9009
+ + 'function ' + t + ':__close()\n self:close()\nend\n\n'
9010
+ + 'function ' + t + ':__gc()\n self:close()\nend\n\n'
8937
9011
  + '--- 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';
9012
+ + '--- Breaking the loop closes the closable stream, RST-ing\n'
9013
+ + '--- the call unless it already terminated.\n'
9014
+ + 'function ' + t + ':iter()\n return function() return self:next() end, nil, nil, self\nend\n\n';
8939
9015
  }
8940
9016
 
8941
9017
  function luaCoroClientMethod(m, svc) {
@@ -8973,7 +9049,13 @@ function luaClientStreamClass(m, svc) {
8973
9049
  + '--- Next response; raises EndOfStream at the end of the call.\n'
8974
9050
  + 'function ' + t + ':recv()\n'
8975
9051
  + ' local resp = ' + m.output + '.new()\n'
8976
- + ' self.stream:recv(resp)\n return resp\nend\n\n';
9052
+ + ' self.stream:recv(resp)\n return resp\nend\n\n'
9053
+ + '--- Abandon the call early: RST so the server stops producing.\n'
9054
+ + 'function ' + t + ':close()\n self.stream:close()\nend\n\n'
9055
+ + 'function ' + t + ':cancel()\n self.stream:cancel()\nend\n\n'
9056
+ + '--- To-be-closed (<close>) and GC abandon the call the same way.\n'
9057
+ + 'function ' + t + ':__close()\n self:close()\nend\n\n'
9058
+ + 'function ' + t + ':__gc()\n self:close()\nend\n\n';
8977
9059
  }
8978
9060
 
8979
9061
  function luaServerStreamClass(m, svc) {
@@ -9548,15 +9630,30 @@ const RB_STREAM_HELPERS = ` # Client receiving stream: recv raises EOFError at
9548
9630
  @stream.recv(@resp_cls.new)
9549
9631
  end
9550
9632
 
9633
+ # Abandon the call early: RST so the server stops producing.
9634
+ def cancel
9635
+ @stream.cancel
9636
+ end
9637
+
9638
+ def close
9639
+ @stream.cancel
9640
+ end
9641
+
9551
9642
  def each
9552
9643
  return enum_for(:each) unless block_given?
9553
9644
 
9554
- loop do
9555
- begin
9556
- yield recv
9557
- rescue EOFError
9558
- return
9645
+ begin
9646
+ loop do
9647
+ begin
9648
+ yield recv
9649
+ rescue EOFError
9650
+ return
9651
+ end
9559
9652
  end
9653
+ ensure
9654
+ # Breaking out of the block abandons the call: RST so
9655
+ # the server stops producing (no-op once terminated).
9656
+ close
9560
9657
  end
9561
9658
  end
9562
9659
  end
@@ -9647,15 +9744,25 @@ const RB_STREAM_HELPERS = ` # Client receiving stream: recv raises EOFError at
9647
9744
  @stream.cancel
9648
9745
  end
9649
9746
 
9747
+ def close
9748
+ @stream.cancel
9749
+ end
9750
+
9650
9751
  def each
9651
9752
  return enum_for(:each) unless block_given?
9652
9753
 
9653
- loop do
9654
- begin
9655
- yield next_msg
9656
- rescue StopIteration
9657
- return
9754
+ begin
9755
+ loop do
9756
+ begin
9757
+ yield next_msg
9758
+ rescue StopIteration
9759
+ return
9760
+ end
9658
9761
  end
9762
+ ensure
9763
+ # Breaking out of the block abandons the call: RST so
9764
+ # the server stops producing (no-op once terminated).
9765
+ close
9659
9766
  end
9660
9767
  end
9661
9768
  end
@@ -10132,15 +10239,37 @@ class RecvStream
10132
10239
  return $this->stream->recv(new $cls());
10133
10240
  }
10134
10241
 
10242
+ /** Abandon the call early: RST so the server stops producing. */
10243
+ public function cancel(): void
10244
+ {
10245
+ $this->stream->cancel();
10246
+ }
10247
+
10248
+ public function close(): void
10249
+ {
10250
+ $this->stream->cancel();
10251
+ }
10252
+
10253
+ public function __destruct()
10254
+ {
10255
+ $this->close();
10256
+ }
10257
+
10135
10258
  /** @return \\Generator<int, object> */
10136
10259
  public function iterate(): \\Generator
10137
10260
  {
10261
+ $completed = false;
10138
10262
  try {
10139
10263
  while (true) {
10140
10264
  yield $this->recv();
10141
10265
  }
10142
10266
  } catch (\\Grpcdc\\CallClosed $e) {
10267
+ $completed = true;
10143
10268
  return;
10269
+ } finally {
10270
+ if (!$completed) {
10271
+ $this->close();
10272
+ }
10144
10273
  }
10145
10274
  }
10146
10275
  }
@@ -10268,12 +10397,18 @@ class FiberRecvStream
10268
10397
  /** @return \\Generator<int, object> */
10269
10398
  public function iterate(): \\Generator
10270
10399
  {
10400
+ $completed = false;
10271
10401
  try {
10272
10402
  while (true) {
10273
10403
  yield $this->next();
10274
10404
  }
10275
10405
  } catch (\\Grpcdc\\CallClosed $e) {
10406
+ $completed = true;
10276
10407
  return;
10408
+ } finally {
10409
+ if (!$completed) {
10410
+ $this->close();
10411
+ }
10277
10412
  }
10278
10413
  }
10279
10414
 
@@ -10281,6 +10416,16 @@ class FiberRecvStream
10281
10416
  {
10282
10417
  $this->stream->cancel();
10283
10418
  }
10419
+
10420
+ public function close(): void
10421
+ {
10422
+ $this->stream->cancel();
10423
+ }
10424
+
10425
+ public function __destruct()
10426
+ {
10427
+ $this->close();
10428
+ }
10284
10429
  }
10285
10430
 
10286
10431
  `;
@@ -10761,6 +10906,7 @@ function scalaFutureMethod(m) {
10761
10906
  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
10907
  + ' grpcdc.Futures {\n'
10763
10908
  + ' val stream = ' + m.name + '(req' + arg + ', metadata, timeout)\n'
10909
+ + ' try {\n'
10764
10910
  + ' val out = scala.collection.mutable.ListBuffer[' + m.output + ']()\n'
10765
10911
  + ' var done = false\n'
10766
10912
  + ' while (!done) {\n'
@@ -10769,7 +10915,7 @@ function scalaFutureMethod(m) {
10769
10915
  + ' } catch {\n'
10770
10916
  + ' case e: java.io.EOFException => done = true\n'
10771
10917
  + ' }\n }\n'
10772
- + ' out.toList\n }\n }\n\n';
10918
+ + ' out.toList\n } finally {\n stream.close()\n }\n }\n }\n\n';
10773
10919
  }
10774
10920
  }
10775
10921
  }
@@ -10885,10 +11031,30 @@ function scalaService(svc) {
10885
11031
  return ps.length ? ps : [[req0, resp0]];
10886
11032
  };
10887
11033
  const streamClass = (kind, out) =>
10888
- ' class ' + scalaClientStreamName(svc, kind, out) + '(private val stream: grpcdc.Channel#ClientStream) {\n'
11034
+ ' class ' + scalaClientStreamName(svc, kind, out) + '(private val stream: grpcdc.Channel#ClientStream) extends scala.collection.Iterator[' + out + '] with AutoCloseable {\n'
10889
11035
  + ' def recv(): ' + out + ' = {\n'
10890
11036
  + ' val resp = new ' + out + '()\n'
10891
- + ' stream.recv(resp)\n resp\n }\n }\n\n';
11037
+ + ' stream.recv(resp)\n resp\n }\n'
11038
+ + ' private var pending: ' + out + ' = null\n'
11039
+ + ' private var finished: Boolean = false\n'
11040
+ + ' def hasNext: Boolean = {\n'
11041
+ + ' if (pending == null && !finished) {\n'
11042
+ + ' try {\n'
11043
+ + ' pending = recv()\n'
11044
+ + ' } catch {\n'
11045
+ + ' case e: java.io.EOFException => finished = true\n'
11046
+ + ' }\n'
11047
+ + ' }\n'
11048
+ + ' pending != null\n'
11049
+ + ' }\n'
11050
+ + ' def next(): ' + out + ' = {\n'
11051
+ + ' if (!hasNext) throw new NoSuchElementException("next on empty stream")\n'
11052
+ + ' val out = pending\n'
11053
+ + ' pending = null\n'
11054
+ + ' out\n'
11055
+ + ' }\n'
11056
+ + ' def cancel(): Unit = stream.cancel()\n'
11057
+ + ' def close(): Unit = stream.close()\n }\n\n';
10892
11058
  return ' /** Client for ' + svc.fullName + '. */\n'
10893
11059
  + ' class ' + sname + 'Client(private val channel: grpcdc.Channel) {\n'
10894
11060
  + classOutputs('server-streaming').map((out) => streamClass('server-streaming', out)).join('')
package/src/channel.js CHANGED
@@ -152,6 +152,7 @@ export class Channel {
152
152
 
153
153
  async *#responses(id, input, RespType, deadline = null, hooks = {}) {
154
154
  const iterator = input[Symbol.asyncIterator]();
155
+ let completed = false;
155
156
  try {
156
157
  for (;;) {
157
158
  const step = await this.#next(id, iterator, deadline);
@@ -162,11 +163,13 @@ export class Channel {
162
163
  } else if (event.kind === "data") {
163
164
  yield RespType.decode(event.payload);
164
165
  } else if (event.kind === "trailers") {
166
+ completed = true;
165
167
  hooks.onTrailers?.(event.trailers ?? {});
166
168
  this.#endTrace(id, StatusName[event.status.code] ?? `CODE_${event.status.code}`);
167
169
  if (event.status.code !== 0) throw event.status;
168
170
  return;
169
171
  } else if (event.kind === "rst") {
172
+ completed = true;
170
173
  this.#endTrace(id, StatusName[event.status.code] ?? `CODE_${event.status.code}`);
171
174
  throw event.status;
172
175
  }
@@ -174,7 +177,11 @@ export class Channel {
174
177
  throw StatusError.unavailable("data channel closed");
175
178
  } finally {
176
179
  this.#endTrace(id, "UNAVAILABLE");
177
- this.#endpoint.closeStream(id);
180
+ // Consumer stopped early (broke out of iteration): cancel
181
+ // so the server stops producing instead of streaming into
182
+ // the void. A completed call just closes locally.
183
+ if (completed) this.#endpoint.closeStream(id);
184
+ else this.#endpoint.cancelStream(id);
178
185
  }
179
186
  }
180
187
 
package/src/endpoint.js CHANGED
@@ -251,8 +251,21 @@ export class Endpoint {
251
251
  const input = new StreamInput();
252
252
  this.#streams.set(streamId, input);
253
253
  const sink = {
254
- sendData: (payload) => this.sendFrame(encodeFrame(FrameType.DATA, streamId, payload)),
255
- sendHeaders: (metadata = {}) => this.sendFrame(headersFrame(streamId, null, metadata)),
254
+ // A stream dropped from the map was RST by the peer (or
255
+ // the channel went away): fail the send so a producing
256
+ // handler stops instead of streaming into the void.
257
+ sendData: (payload) => {
258
+ if (!this.#streams.has(streamId)) {
259
+ throw new StatusError(StatusCode.CANCELLED, "call cancelled");
260
+ }
261
+ return this.sendFrame(encodeFrame(FrameType.DATA, streamId, payload));
262
+ },
263
+ sendHeaders: (metadata = {}) => {
264
+ if (!this.#streams.has(streamId)) {
265
+ throw new StatusError(StatusCode.CANCELLED, "call cancelled");
266
+ }
267
+ return this.sendFrame(headersFrame(streamId, null, metadata));
268
+ },
256
269
  sendTrailers: (status, trailers) =>
257
270
  this.sendFrame(statusFrame(FrameType.TRAILERS, streamId, status, trailers)),
258
271
  };