| | 1 | | // Copyright (c) ZeroC, Inc. |
| | 2 | |
|
| | 3 | | using IceRpc.Internal; |
| | 4 | | using IceRpc.Transports.Internal; |
| | 5 | | using System.Buffers; |
| | 6 | | using System.Diagnostics; |
| | 7 | | using System.IO.Pipelines; |
| | 8 | |
|
| | 9 | | namespace IceRpc.Transports.Coloc.Internal; |
| | 10 | |
|
| | 11 | | /// <summary>The colocated connection class to exchange data within the same process. The implementation copies the send |
| | 12 | | /// buffer into the receive buffer.</summary> |
| | 13 | | internal abstract class ColocConnection : IDuplexConnection |
| | 14 | | { |
| | 15 | | private protected PipeReader? _reader; |
| | 16 | | // FlagEnumExtensions operations are used to update the state. These operations are atomic and don't require mutex |
| | 17 | | // locking. |
| | 18 | | private protected int _state; |
| | 19 | |
|
| | 20 | | private readonly ServerAddress _serverAddress; |
| | 21 | | private readonly PipeWriter _writer; |
| | 22 | |
|
| | 23 | | public abstract Task<TransportConnectionInformation> ConnectAsync(CancellationToken cancellationToken); |
| | 24 | |
|
| | 25 | | public void Dispose() |
| 2251 | 26 | | { |
| 2251 | 27 | | Dispose(true); |
| 2251 | 28 | | GC.SuppressFinalize(this); |
| 2251 | 29 | | } |
| | 30 | |
|
| | 31 | | public async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) |
| 134979 | 32 | | { |
| 134979 | 33 | | ObjectDisposedException.ThrowIf(_state.HasFlag(State.Disposed), this); |
| | 34 | |
|
| 134977 | 35 | | if (_reader is null) |
| 2 | 36 | | { |
| 2 | 37 | | throw new InvalidOperationException("Reading is not allowed before connection is connected."); |
| | 38 | | } |
| 134975 | 39 | | if (!_state.TrySetFlag(State.Reading)) |
| 2 | 40 | | { |
| 2 | 41 | | throw new InvalidOperationException("Reading is already in progress."); |
| | 42 | | } |
| | 43 | |
|
| | 44 | | try |
| 134973 | 45 | | { |
| 134973 | 46 | | ReadResult readResult = await _reader.ReadAsync(cancellationToken).ConfigureAwait(false); |
| 133758 | 47 | | if (readResult.IsCanceled) |
| 0 | 48 | | { |
| | 49 | | // Dispose canceled ReadAsync. |
| 0 | 50 | | throw new IceRpcException(IceRpcError.OperationAborted); |
| | 51 | | } |
| 133758 | 52 | | else if (readResult.IsCompleted && readResult.Buffer.IsEmpty) |
| 260 | 53 | | { |
| 260 | 54 | | return 0; |
| | 55 | | } |
| | 56 | |
|
| | 57 | | // We could eventually add a CopyTo(this ReadOnlySequence<byte> src, Memory<byte> dest) extension method |
| | 58 | | // if we need this in other places. |
| | 59 | | int read; |
| 133498 | 60 | | if (readResult.Buffer.IsSingleSegment) |
| 10310 | 61 | | { |
| 10310 | 62 | | read = CopySegmentToMemory(readResult.Buffer.First, buffer); |
| 10310 | 63 | | } |
| | 64 | | else |
| 123188 | 65 | | { |
| 123188 | 66 | | read = 0; |
| 663718 | 67 | | foreach (ReadOnlyMemory<byte> segment in readResult.Buffer) |
| 208671 | 68 | | { |
| 208671 | 69 | | read += CopySegmentToMemory(segment, buffer[read..]); |
| 208671 | 70 | | if (read == buffer.Length) |
| 123188 | 71 | | { |
| 123188 | 72 | | break; |
| | 73 | | } |
| 85483 | 74 | | } |
| 123188 | 75 | | } |
| 133498 | 76 | | _reader.AdvanceTo(readResult.Buffer.GetPosition(read)); |
| 133498 | 77 | | return read; |
| | 78 | | } |
| | 79 | | finally |
| 134973 | 80 | | { |
| 134973 | 81 | | if (_state.HasFlag(State.Disposed)) |
| 0 | 82 | | { |
| 0 | 83 | | _reader.Complete(new IceRpcException(IceRpcError.ConnectionAborted)); |
| 0 | 84 | | } |
| 134973 | 85 | | _state.ClearFlag(State.Reading); |
| 134973 | 86 | | } |
| | 87 | |
|
| | 88 | | static int CopySegmentToMemory(ReadOnlyMemory<byte> source, Memory<byte> destination) |
| 218981 | 89 | | { |
| 218981 | 90 | | if (source.Length > destination.Length) |
| 118650 | 91 | | { |
| 118650 | 92 | | source[0..destination.Length].CopyTo(destination); |
| 118650 | 93 | | return destination.Length; |
| | 94 | | } |
| | 95 | | else |
| 100331 | 96 | | { |
| 100331 | 97 | | source.CopyTo(destination); |
| 100331 | 98 | | return source.Length; |
| | 99 | | } |
| 218981 | 100 | | } |
| 133758 | 101 | | } |
| | 102 | |
|
| | 103 | | public Task ShutdownWriteAsync(CancellationToken cancellationToken) |
| 280 | 104 | | { |
| 280 | 105 | | ObjectDisposedException.ThrowIf(_state.HasFlag(State.Disposed), this); |
| | 106 | |
|
| 280 | 107 | | if (_reader is null) |
| 2 | 108 | | { |
| 2 | 109 | | throw new InvalidOperationException("Shutdown is not allowed before the connection is connected."); |
| | 110 | | } |
| 278 | 111 | | if (_state.HasFlag(State.Writing)) |
| 2 | 112 | | { |
| 2 | 113 | | throw new InvalidOperationException("Shutdown or writing is in progress"); |
| | 114 | | } |
| 276 | 115 | | if (!_state.TrySetFlag(State.ShuttingDown)) |
| 0 | 116 | | { |
| 0 | 117 | | throw new InvalidOperationException("Shutdown has already been called."); |
| | 118 | | } |
| | 119 | |
|
| 276 | 120 | | _writer.Complete(); |
| 276 | 121 | | return Task.CompletedTask; |
| 276 | 122 | | } |
| | 123 | |
|
| | 124 | | public async ValueTask WriteAsync(ReadOnlySequence<byte> buffer, CancellationToken cancellationToken) |
| 13297 | 125 | | { |
| 13297 | 126 | | ObjectDisposedException.ThrowIf(_state.HasFlag(State.Disposed), this); |
| | 127 | |
|
| 13295 | 128 | | if (buffer.IsEmpty) |
| 0 | 129 | | { |
| 0 | 130 | | throw new ArgumentException($"The {nameof(buffer)} cannot be empty.", nameof(buffer)); |
| | 131 | | } |
| | 132 | |
|
| 13295 | 133 | | if (_reader is null) |
| 2 | 134 | | { |
| 2 | 135 | | throw new InvalidOperationException("Writing is not allowed before the connection is connected."); |
| | 136 | | } |
| 13293 | 137 | | if (_state.HasFlag(State.ShuttingDown)) |
| 4 | 138 | | { |
| 4 | 139 | | throw new InvalidOperationException("Writing is not allowed after the connection is shutdown."); |
| | 140 | | } |
| 13289 | 141 | | if (!_state.TrySetFlag(State.Writing)) |
| 2 | 142 | | { |
| 2 | 143 | | throw new InvalidOperationException("Writing is already in progress."); |
| | 144 | | } |
| | 145 | |
|
| | 146 | | try |
| 13287 | 147 | | { |
| 13287 | 148 | | _writer.Write(buffer); |
| 13287 | 149 | | FlushResult flushResult = await _writer.FlushAsync(cancellationToken).ConfigureAwait(false); |
| 13266 | 150 | | if (flushResult.IsCanceled) |
| 0 | 151 | | { |
| | 152 | | // Dispose canceled ReadAsync. |
| 0 | 153 | | throw new IceRpcException(IceRpcError.OperationAborted); |
| | 154 | | } |
| 13266 | 155 | | } |
| | 156 | | finally |
| 13287 | 157 | | { |
| 13287 | 158 | | Debug.Assert(!_state.HasFlag(State.ShuttingDown)); |
| 13287 | 159 | | if (_state.HasFlag(State.Disposed)) |
| 0 | 160 | | { |
| 0 | 161 | | _writer.Complete(new IceRpcException(IceRpcError.ConnectionAborted)); |
| 0 | 162 | | } |
| 13287 | 163 | | _state.ClearFlag(State.Writing); |
| 13287 | 164 | | } |
| 13266 | 165 | | } |
| | 166 | |
|
| 1899 | 167 | | public ColocConnection(ServerAddress serverAddress, PipeWriter writer) |
| 1899 | 168 | | { |
| 1899 | 169 | | _serverAddress = serverAddress; |
| 1899 | 170 | | _writer = writer; |
| 1899 | 171 | | } |
| | 172 | |
|
| | 173 | | private protected virtual void Dispose(bool disposing) |
| 2251 | 174 | | { |
| 2251 | 175 | | if (_state.TrySetFlag(State.Disposed)) |
| 1897 | 176 | | { |
| | 177 | | // _reader can be null if connection establishment failed or didn't run. |
| 1897 | 178 | | if (_reader is not null) |
| 1784 | 179 | | { |
| 1784 | 180 | | if (_state.HasFlag(State.Reading)) |
| 0 | 181 | | { |
| 0 | 182 | | _reader.CancelPendingRead(); |
| 0 | 183 | | } |
| | 184 | | else |
| 1784 | 185 | | { |
| 1784 | 186 | | _reader.Complete(new IceRpcException(IceRpcError.ConnectionAborted)); |
| 1784 | 187 | | } |
| 1784 | 188 | | } |
| | 189 | |
|
| 1897 | 190 | | if (_state.HasFlag(State.Writing)) |
| 0 | 191 | | { |
| 0 | 192 | | _writer.CancelPendingFlush(); |
| 0 | 193 | | } |
| | 194 | | else |
| 1897 | 195 | | { |
| 1897 | 196 | | _writer.Complete(new IceRpcException(IceRpcError.ConnectionAborted)); |
| 1897 | 197 | | } |
| 1897 | 198 | | } |
| 2251 | 199 | | } |
| | 200 | |
|
| | 201 | | private protected TransportConnectionInformation FinishConnect() |
| 1733 | 202 | | { |
| 1733 | 203 | | Debug.Assert(_reader is not null); |
| | 204 | |
|
| 1733 | 205 | | if (_state.HasFlag(State.Disposed)) |
| 0 | 206 | | { |
| 0 | 207 | | _reader.Complete(); |
| 0 | 208 | | throw new ObjectDisposedException($"{typeof(ColocConnection)}"); |
| | 209 | | } |
| | 210 | |
|
| 1733 | 211 | | var colocEndPoint = new ColocEndPoint(_serverAddress); |
| 1733 | 212 | | return new TransportConnectionInformation(colocEndPoint, colocEndPoint, null); |
| 1733 | 213 | | } |
| | 214 | |
|
| | 215 | | private protected enum State : int |
| | 216 | | { |
| | 217 | | Disposed = 1, |
| | 218 | | Reading = 2, |
| | 219 | | ShuttingDown = 4, |
| | 220 | | Writing = 8, |
| | 221 | | } |
| | 222 | | } |
| | 223 | |
|
| | 224 | | /// <summary>The colocated client connection class.</summary> |
| | 225 | | internal class ClientColocConnection : ColocConnection |
| | 226 | | { |
| | 227 | | private readonly Func<PipeReader, CancellationToken, Task<PipeReader>> _connectAsync; |
| | 228 | | private PipeReader? _localPipeReader; |
| | 229 | |
|
| | 230 | | public override async Task<TransportConnectionInformation> ConnectAsync(CancellationToken cancellationToken) |
| | 231 | | { |
| | 232 | | ObjectDisposedException.ThrowIf(_state.HasFlag(State.Disposed), this); |
| | 233 | |
|
| | 234 | | if (_reader is not null) |
| | 235 | | { |
| | 236 | | throw new InvalidOperationException("Connection establishment cannot be called twice."); |
| | 237 | | } |
| | 238 | |
|
| | 239 | | Debug.Assert(!_state.HasFlag(State.ShuttingDown)); |
| | 240 | |
|
| | 241 | | if (_localPipeReader is not null) |
| | 242 | | { |
| | 243 | | _reader = await _connectAsync(_localPipeReader, cancellationToken).ConfigureAwait(false); |
| | 244 | | _localPipeReader = null; // The server-side connection is now responsible for completing the pipe reader. |
| | 245 | | } |
| | 246 | | return FinishConnect(); |
| | 247 | | } |
| | 248 | |
|
| | 249 | | internal ClientColocConnection( |
| | 250 | | ServerAddress serverAddress, |
| | 251 | | Pipe localPipe, |
| | 252 | | Func<PipeReader, CancellationToken, Task<PipeReader>> connectAsync) |
| | 253 | | : base(serverAddress, localPipe.Writer) |
| | 254 | | { |
| | 255 | | _connectAsync = connectAsync; |
| | 256 | | _localPipeReader = localPipe.Reader; |
| | 257 | | } |
| | 258 | |
|
| | 259 | | private protected override void Dispose(bool disposing) |
| | 260 | | { |
| | 261 | | base.Dispose(disposing); |
| | 262 | | _localPipeReader?.Complete(); |
| | 263 | | } |
| | 264 | | } |
| | 265 | |
|
| | 266 | | /// <summary>The colocated server connection class.</summary> |
| | 267 | | internal class ServerColocConnection : ColocConnection |
| | 268 | | { |
| | 269 | | public override Task<TransportConnectionInformation> ConnectAsync(CancellationToken cancellationToken) => |
| | 270 | | Task.FromResult(FinishConnect()); |
| | 271 | |
|
| | 272 | | public ServerColocConnection(ServerAddress serverAddress, PipeWriter writer, PipeReader reader) |
| | 273 | | : base(serverAddress, writer) => _reader = reader; |
| | 274 | | } |