|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.IO; |
| 6 | +using System.IO.Pipelines; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using Microsoft.JSInterop; |
| 10 | + |
| 11 | +namespace Microsoft.AspNetCore.Components.Server.Circuits |
| 12 | +{ |
| 13 | + internal sealed class RemoteJSDataStream : Stream |
| 14 | + { |
| 15 | + private readonly RemoteJSRuntime _runtime; |
| 16 | + private readonly long _streamId; |
| 17 | + private readonly long _totalLength; |
| 18 | + private readonly TimeSpan _jsInteropDefaultCallTimeout; |
| 19 | + private readonly CancellationToken _streamCancellationToken; |
| 20 | + private readonly Stream _pipeReaderStream; |
| 21 | + private readonly Pipe _pipe; |
| 22 | + private long _bytesRead; |
| 23 | + private long _expectedChunkId; |
| 24 | + private DateTimeOffset _lastDataReceivedTime; |
| 25 | + private bool _disposed; |
| 26 | + |
| 27 | + public static async Task<bool> ReceiveData(RemoteJSRuntime runtime, long streamId, long chunkId, byte[] chunk, string error) |
| 28 | + { |
| 29 | + if (!runtime.RemoteJSDataStreamInstances.TryGetValue(streamId, out var instance)) |
| 30 | + { |
| 31 | + // There is no data stream with the given identifier. It may have already been disposed. |
| 32 | + // We notify JS that the stream has been cancelled/disposed. |
| 33 | + return false; |
| 34 | + } |
| 35 | + |
| 36 | + return await instance.ReceiveData(chunkId, chunk, error); |
| 37 | + } |
| 38 | + |
| 39 | + public static async ValueTask<RemoteJSDataStream> CreateRemoteJSDataStreamAsync( |
| 40 | + RemoteJSRuntime runtime, |
| 41 | + IJSStreamReference jsStreamReference, |
| 42 | + long totalLength, |
| 43 | + long maxBufferSize, |
| 44 | + long maximumIncomingBytes, |
| 45 | + TimeSpan jsInteropDefaultCallTimeout, |
| 46 | + CancellationToken cancellationToken = default) |
| 47 | + { |
| 48 | + // Enforce minimum 1 kb, maximum 50 kb, SignalR message size. |
| 49 | + // We budget 512 bytes overhead for the transfer, thus leaving at least 512 bytes for data |
| 50 | + // transfer per chunk with a 1 kb message size. |
| 51 | + // Additionally, to maintain interactivity, we put an upper limit of 50 kb on the message size. |
| 52 | + var chunkSize = maximumIncomingBytes > 1024 ? |
| 53 | + Math.Min(maximumIncomingBytes, 50*1024) - 512 : |
| 54 | + throw new ArgumentException($"SignalR MaximumIncomingBytes must be at least 1 kb."); |
| 55 | + |
| 56 | + var streamId = runtime.RemoteJSDataStreamNextInstanceId++; |
| 57 | + var remoteJSDataStream = new RemoteJSDataStream(runtime, streamId, totalLength, maxBufferSize, jsInteropDefaultCallTimeout, cancellationToken); |
| 58 | + await runtime.InvokeVoidAsync("Blazor._internal.sendJSDataStream", jsStreamReference, streamId, chunkSize); |
| 59 | + return remoteJSDataStream; |
| 60 | + } |
| 61 | + |
| 62 | + private RemoteJSDataStream( |
| 63 | + RemoteJSRuntime runtime, |
| 64 | + long streamId, |
| 65 | + long totalLength, |
| 66 | + long maxBufferSize, |
| 67 | + TimeSpan jsInteropDefaultCallTimeout, |
| 68 | + CancellationToken cancellationToken) |
| 69 | + { |
| 70 | + _runtime = runtime; |
| 71 | + _streamId = streamId; |
| 72 | + _totalLength = totalLength; |
| 73 | + _jsInteropDefaultCallTimeout = jsInteropDefaultCallTimeout; |
| 74 | + _streamCancellationToken = cancellationToken; |
| 75 | + |
| 76 | + _lastDataReceivedTime = DateTimeOffset.UtcNow; |
| 77 | + _ = ThrowOnTimeout(); |
| 78 | + |
| 79 | + _runtime.RemoteJSDataStreamInstances.Add(_streamId, this); |
| 80 | + |
| 81 | + _pipe = new Pipe(new PipeOptions(pauseWriterThreshold: maxBufferSize, resumeWriterThreshold: maxBufferSize / 2)); |
| 82 | + _pipeReaderStream = _pipe.Reader.AsStream(); |
| 83 | + } |
| 84 | + |
| 85 | + private async Task<bool> ReceiveData(long chunkId, byte[] chunk, string error) |
| 86 | + { |
| 87 | + try |
| 88 | + { |
| 89 | + _lastDataReceivedTime = DateTimeOffset.UtcNow; |
| 90 | + _ = ThrowOnTimeout(); |
| 91 | + |
| 92 | + if (!string.IsNullOrEmpty(error)) |
| 93 | + { |
| 94 | + throw new InvalidOperationException($"An error occurred while reading the remote stream: {error}"); |
| 95 | + } |
| 96 | + |
| 97 | + if (chunkId != _expectedChunkId) |
| 98 | + { |
| 99 | + throw new EndOfStreamException($"Out of sequence chunk received, expected {_expectedChunkId}, but received {chunkId}."); |
| 100 | + } |
| 101 | + |
| 102 | + ++_expectedChunkId; |
| 103 | + |
| 104 | + if (chunk.Length == 0) |
| 105 | + { |
| 106 | + throw new EndOfStreamException($"The incoming data chunk cannot be empty."); |
| 107 | + } |
| 108 | + |
| 109 | + _bytesRead += chunk.Length; |
| 110 | + |
| 111 | + if (_bytesRead > _totalLength) |
| 112 | + { |
| 113 | + throw new EndOfStreamException($"The incoming data stream declared a length {_totalLength}, but {_bytesRead} bytes were sent."); |
| 114 | + } |
| 115 | + |
| 116 | + await _pipe.Writer.WriteAsync(chunk, _streamCancellationToken); |
| 117 | + |
| 118 | + if (_bytesRead == _totalLength) |
| 119 | + { |
| 120 | + await CompletePipeAndDisposeStream(); |
| 121 | + } |
| 122 | + |
| 123 | + return true; |
| 124 | + } |
| 125 | + catch (Exception e) |
| 126 | + { |
| 127 | + await CompletePipeAndDisposeStream(e); |
| 128 | + |
| 129 | + // Fatal exception, crush the circuit. A well behaved client |
| 130 | + // should not result in this type of exception. |
| 131 | + if (e is EndOfStreamException) |
| 132 | + { |
| 133 | + throw; |
| 134 | + } |
| 135 | + |
| 136 | + return false; |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + public override bool CanRead => true; |
| 141 | + |
| 142 | + public override bool CanSeek => false; |
| 143 | + |
| 144 | + public override bool CanWrite => false; |
| 145 | + |
| 146 | + public override long Length => _totalLength; |
| 147 | + |
| 148 | + public override long Position |
| 149 | + { |
| 150 | + get => _pipeReaderStream.Position; |
| 151 | + set => throw new NotSupportedException(); |
| 152 | + } |
| 153 | + |
| 154 | + public override void Flush() |
| 155 | + => throw new NotSupportedException(); |
| 156 | + |
| 157 | + public override int Read(byte[] buffer, int offset, int count) |
| 158 | + => throw new NotSupportedException("Synchronous reads are not supported."); |
| 159 | + |
| 160 | + public override long Seek(long offset, SeekOrigin origin) |
| 161 | + => throw new NotSupportedException(); |
| 162 | + |
| 163 | + public override void SetLength(long value) |
| 164 | + => throw new NotSupportedException(); |
| 165 | + |
| 166 | + public override void Write(byte[] buffer, int offset, int count) |
| 167 | + => throw new NotSupportedException(); |
| 168 | + |
| 169 | + public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| 170 | + { |
| 171 | + var linkedCancellationToken = GetLinkedCancellationToken(_streamCancellationToken, cancellationToken); |
| 172 | + return await _pipeReaderStream.ReadAsync(buffer.AsMemory(offset, count), linkedCancellationToken); |
| 173 | + } |
| 174 | + |
| 175 | + public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) |
| 176 | + { |
| 177 | + var linkedCancellationToken = GetLinkedCancellationToken(_streamCancellationToken, cancellationToken); |
| 178 | + return await _pipeReaderStream.ReadAsync(buffer, linkedCancellationToken); |
| 179 | + } |
| 180 | + |
| 181 | + private static CancellationToken GetLinkedCancellationToken(CancellationToken a, CancellationToken b) |
| 182 | + { |
| 183 | + if (a.CanBeCanceled && b.CanBeCanceled) |
| 184 | + { |
| 185 | + return CancellationTokenSource.CreateLinkedTokenSource(a, b).Token; |
| 186 | + } |
| 187 | + else if (a.CanBeCanceled) |
| 188 | + { |
| 189 | + return a; |
| 190 | + } |
| 191 | + |
| 192 | + return b; |
| 193 | + } |
| 194 | + |
| 195 | + private async Task ThrowOnTimeout() |
| 196 | + { |
| 197 | + await Task.Delay(_jsInteropDefaultCallTimeout); |
| 198 | + |
| 199 | + if (!_disposed && (DateTimeOffset.UtcNow >= _lastDataReceivedTime.Add(_jsInteropDefaultCallTimeout))) |
| 200 | + { |
| 201 | + // Dispose of the stream if a chunk isn't received within the jsInteropDefaultCallTimeout. |
| 202 | + var timeoutException = new TimeoutException("Did not receive any data in the alloted time."); |
| 203 | + await CompletePipeAndDisposeStream(timeoutException); |
| 204 | + _runtime.RaiseUnhandledException(timeoutException); |
| 205 | + } |
| 206 | + } |
| 207 | + |
| 208 | + internal async Task CompletePipeAndDisposeStream(Exception? ex = null) |
| 209 | + { |
| 210 | + await _pipe.Writer.CompleteAsync(ex); |
| 211 | + Dispose(true); |
| 212 | + } |
| 213 | + |
| 214 | + protected override void Dispose(bool disposing) |
| 215 | + { |
| 216 | + if (disposing) |
| 217 | + { |
| 218 | + _runtime.RemoteJSDataStreamInstances.Remove(_streamId); |
| 219 | + } |
| 220 | + |
| 221 | + _disposed = true; |
| 222 | + } |
| 223 | + } |
| 224 | +} |
0 commit comments