You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestServerStreamWriter.cs 2.4 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma warning disable IDE0073
  2. // Copyright 2019 The gRPC Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. using System.Threading.Channels;
  16. using Grpc.Core;
  17. namespace Microsoft.AutoGen.RuntimeGateway.Grpc.Tests.Helpers.Grpc;
  18. public class TestServerStreamWriter<T> : IDisposable, IServerStreamWriter<T> where T : class
  19. {
  20. private readonly ServerCallContext _serverCallContext;
  21. private readonly Channel<T> _channel;
  22. public WriteOptions? WriteOptions { get; set; }
  23. public TestServerStreamWriter(ServerCallContext serverCallContext)
  24. {
  25. _channel = Channel.CreateUnbounded<T>();
  26. _serverCallContext = serverCallContext;
  27. }
  28. public void Complete()
  29. {
  30. _channel.Writer.Complete();
  31. }
  32. public IAsyncEnumerable<T> ReadAllAsync()
  33. {
  34. return _channel.Reader.ReadAllAsync();
  35. }
  36. public async Task<T?> ReadNextAsync()
  37. {
  38. if (await _channel.Reader.WaitToReadAsync())
  39. {
  40. _channel.Reader.TryRead(out var message);
  41. return message;
  42. }
  43. else
  44. {
  45. return null;
  46. }
  47. }
  48. public Task WriteAsync(T message, CancellationToken cancellationToken)
  49. {
  50. if (cancellationToken.IsCancellationRequested)
  51. {
  52. return Task.FromCanceled(cancellationToken);
  53. }
  54. if (_serverCallContext.CancellationToken.IsCancellationRequested)
  55. {
  56. return Task.FromCanceled(_serverCallContext.CancellationToken);
  57. }
  58. if (!_channel.Writer.TryWrite(message))
  59. {
  60. throw new InvalidOperationException("Unable to write message.");
  61. }
  62. return Task.CompletedTask;
  63. }
  64. public Task WriteAsync(T message)
  65. {
  66. return WriteAsync(message, CancellationToken.None);
  67. }
  68. public void Dispose()
  69. {
  70. Complete();
  71. }
  72. }