| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Buffers; |
| | 6 | | using System.Globalization; |
| | 7 | | using System.IO; |
| | 8 | | using System.Threading; |
| | 9 | | using System.Threading.Tasks; |
| | 10 | | using Azure.Core; |
| | 11 | | using Azure.Core.Pipeline; |
| | 12 | | using Azure.Storage.Shared; |
| | 13 | |
|
| | 14 | | namespace Azure.Storage |
| | 15 | | { |
| | 16 | | /// <summary> |
| | 17 | | /// Used for Open Read APIs. |
| | 18 | | /// </summary> |
| | 19 | | internal class LazyLoadingReadOnlyStream<TRequestConditions, TProperties> : Stream |
| | 20 | | { |
| | 21 | | /// <summary> |
| | 22 | | /// The current position within the blob or file. |
| | 23 | | /// </summary> |
| | 24 | | private long _position; |
| | 25 | |
|
| | 26 | | /// <summary> |
| | 27 | | /// Last known length of underlying blob or file. |
| | 28 | | /// </summary> |
| | 29 | | private long _length; |
| | 30 | |
|
| | 31 | | /// <summary> |
| | 32 | | /// The number of bytes to download per call. |
| | 33 | | /// </summary> |
| | 34 | | private readonly int _bufferSize; |
| | 35 | |
|
| | 36 | | /// <summary> |
| | 37 | | /// The backing buffer. |
| | 38 | | /// </summary> |
| | 39 | | private byte[] _buffer; |
| | 40 | |
|
| | 41 | | /// <summary> |
| | 42 | | /// The current position within the buffer. |
| | 43 | | /// </summary> |
| | 44 | | private int _bufferPosition; |
| | 45 | |
|
| | 46 | | /// <summary> |
| | 47 | | /// The current length of the buffer that is populated. |
| | 48 | | /// </summary> |
| | 49 | | private int _bufferLength; |
| | 50 | |
|
| | 51 | | /// <summary> |
| | 52 | | /// If we are allowing the blob to be modifed while we read it. |
| | 53 | | /// </summary> |
| | 54 | | private bool _allowBlobModifications; |
| | 55 | |
|
| | 56 | | /// <summary> |
| | 57 | | /// Request conditions to send on the download requests. |
| | 58 | | /// </summary> |
| | 59 | | private TRequestConditions _requestConditions; |
| | 60 | |
|
| | 61 | | /// <summary> |
| | 62 | | /// Download() function. |
| | 63 | | /// </summary> |
| | 64 | | private readonly Func<HttpRange, TRequestConditions, bool, bool, CancellationToken, Task<Response<IDownloadedCon |
| | 65 | |
|
| | 66 | | /// <summary> |
| | 67 | | /// Function to create RequestConditions. |
| | 68 | | /// </summary> |
| | 69 | | private readonly Func<ETag?, TRequestConditions> _createRequestConditionsFunc; |
| | 70 | |
|
| | 71 | | /// <summary> |
| | 72 | | /// Function to get properties. |
| | 73 | | /// </summary> |
| | 74 | | private readonly Func<bool, CancellationToken, Task<Response<TProperties>>> _getPropertiesInternalFunc; |
| | 75 | |
|
| 14 | 76 | | public LazyLoadingReadOnlyStream( |
| 14 | 77 | | Func<HttpRange, TRequestConditions, bool, bool, CancellationToken, Task<Response<IDownloadedContent>>> downl |
| 14 | 78 | | Func<ETag?, TRequestConditions> createRequestConditionsFunc, |
| 14 | 79 | | Func<bool, CancellationToken, Task<Response<TProperties>>> getPropertiesFunc, |
| 14 | 80 | | long position = 0, |
| 14 | 81 | | int? bufferSize = default, |
| 14 | 82 | | TRequestConditions requestConditions = default) |
| | 83 | | { |
| 14 | 84 | | _downloadInternalFunc = downloadInternalFunc; |
| 14 | 85 | | _createRequestConditionsFunc = createRequestConditionsFunc; |
| 14 | 86 | | _getPropertiesInternalFunc = getPropertiesFunc; |
| 14 | 87 | | _position = position; |
| 14 | 88 | | _bufferSize = bufferSize ?? Constants.DefaultStreamingDownloadSize; |
| 14 | 89 | | _buffer = ArrayPool<byte>.Shared.Rent(_bufferSize); |
| 14 | 90 | | _bufferPosition = 0; |
| 14 | 91 | | _bufferLength = 0; |
| 14 | 92 | | _requestConditions = requestConditions; |
| 14 | 93 | | _length = -1; |
| 14 | 94 | | _allowBlobModifications = !(_requestConditions == null && _createRequestConditionsFunc != null); |
| 14 | 95 | | } |
| | 96 | |
|
| | 97 | | public override int Read(byte[] buffer, int offset, int count) |
| 0 | 98 | | => ReadInternal( |
| 0 | 99 | | buffer, |
| 0 | 100 | | offset, |
| 0 | 101 | | count, |
| 0 | 102 | | async: false, |
| 0 | 103 | | default) |
| 0 | 104 | | .EnsureCompleted(); |
| | 105 | |
|
| | 106 | | public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationTo |
| 40 | 107 | | => await ReadInternal( |
| 40 | 108 | | buffer, |
| 40 | 109 | | offset, |
| 40 | 110 | | count, |
| 40 | 111 | | async: true, |
| 40 | 112 | | cancellationToken) |
| 40 | 113 | | .ConfigureAwait(false); |
| | 114 | |
|
| | 115 | | public async Task<int> ReadInternal(byte[] buffer, int offset, int count, bool async, CancellationToken cancella |
| | 116 | | { |
| 40 | 117 | | ValidateReadParameters(buffer, offset, count); |
| | 118 | |
|
| 32 | 119 | | if (_position == _length) |
| | 120 | | { |
| 0 | 121 | | if (_allowBlobModifications) |
| | 122 | | { |
| | 123 | | // In case the blob grow since our last download call. |
| 0 | 124 | | _length = await GetBlobLengthInternal(async, cancellationToken).ConfigureAwait(false); |
| | 125 | |
|
| 0 | 126 | | if (_position == _length) |
| | 127 | | { |
| 0 | 128 | | return 0; |
| | 129 | | } |
| | 130 | | } |
| | 131 | | else |
| | 132 | | { |
| 0 | 133 | | return 0; |
| | 134 | | } |
| | 135 | |
|
| | 136 | | } |
| | 137 | |
|
| 32 | 138 | | if (_bufferPosition == 0 || _bufferPosition == _buffer.Length) |
| | 139 | | { |
| 32 | 140 | | int lastDownloadedBytes = await DownloadInternal(async, cancellationToken).ConfigureAwait(false); |
| 28 | 141 | | if (lastDownloadedBytes == 0) |
| | 142 | | { |
| 0 | 143 | | return 0; |
| | 144 | | } |
| | 145 | | } |
| | 146 | |
|
| 28 | 147 | | int remainingBytesInBuffer = _bufferLength - _bufferPosition; |
| | 148 | |
|
| | 149 | | // We will return the minimum of remainingBytesInBuffer and the count provided by the user |
| 28 | 150 | | int bytesToWrite = Math.Min(remainingBytesInBuffer, count); |
| | 151 | |
|
| 28 | 152 | | Array.Copy(_buffer, _bufferPosition, buffer, offset, bytesToWrite); |
| | 153 | |
|
| 28 | 154 | | _position += bytesToWrite; |
| | 155 | |
|
| 28 | 156 | | return bytesToWrite; |
| 28 | 157 | | } |
| | 158 | |
|
| | 159 | | private async Task<int> DownloadInternal(bool async, CancellationToken cancellationToken) |
| | 160 | | { |
| | 161 | | Response<IDownloadedContent> response; |
| | 162 | |
|
| 32 | 163 | | HttpRange range = new HttpRange(_position, _bufferSize); |
| | 164 | |
|
| | 165 | | #pragma warning disable AZC0110 // DO NOT use await keyword in possibly synchronous scope. |
| 32 | 166 | | response = await _downloadInternalFunc(range, _requestConditions, default, async, cancellationToken).Configu |
| | 167 | | #pragma warning restore AZC0110 // DO NOT use await keyword in possibly synchronous scope. |
| | 168 | |
|
| 28 | 169 | | using Stream networkStream = response.Value.Content; |
| | 170 | |
|
| | 171 | | int copiedBytes; |
| | 172 | |
|
| 28 | 173 | | if (async) |
| | 174 | | { |
| 28 | 175 | | copiedBytes = await networkStream.ReadAsync( |
| 28 | 176 | | buffer: _buffer, |
| 28 | 177 | | offset: 0, |
| 28 | 178 | | count: _buffer.Length, |
| 28 | 179 | | cancellationToken: cancellationToken).ConfigureAwait(false); |
| | 180 | | } |
| | 181 | | else |
| | 182 | | { |
| 0 | 183 | | copiedBytes = networkStream.Read( |
| 0 | 184 | | buffer: _buffer, |
| 0 | 185 | | offset: 0, |
| 0 | 186 | | count: _buffer.Length); |
| | 187 | | } |
| | 188 | |
|
| 28 | 189 | | _bufferPosition = 0; |
| 28 | 190 | | _bufferLength = copiedBytes; |
| 28 | 191 | | _length = GetBlobLengthFromResponse(response.GetRawResponse()); |
| | 192 | |
|
| | 193 | | // Set _requestConditions If-Match if we are not allowing the blob to be modified. |
| 28 | 194 | | if (!_allowBlobModifications) |
| | 195 | | { |
| 0 | 196 | | _requestConditions = _createRequestConditionsFunc(response.GetRawResponse().Headers.ETag); |
| | 197 | | } |
| | 198 | |
|
| 28 | 199 | | return response.GetRawResponse().Headers.ContentLength.GetValueOrDefault(); |
| 28 | 200 | | } |
| | 201 | |
|
| | 202 | | private static void ValidateReadParameters(byte[] buffer, int offset, int count) |
| | 203 | | { |
| 40 | 204 | | if (buffer == null) |
| | 205 | | { |
| 2 | 206 | | throw new ArgumentNullException($"{nameof(buffer)}", $"{nameof(buffer)} cannot be null."); |
| | 207 | | } |
| | 208 | |
|
| 38 | 209 | | if (offset < 0) |
| | 210 | | { |
| 2 | 211 | | throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot be less than 0."); |
| | 212 | | } |
| | 213 | |
|
| 36 | 214 | | if (offset > buffer.Length) |
| | 215 | | { |
| 2 | 216 | | throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot exceed {nameof(buffer)} length."); |
| | 217 | | } |
| | 218 | |
|
| 34 | 219 | | if (count < 0) |
| | 220 | | { |
| 2 | 221 | | throw new ArgumentOutOfRangeException($"{nameof(count)} cannot be less than 0."); |
| | 222 | | } |
| 32 | 223 | | } |
| | 224 | |
|
| | 225 | | protected override void Dispose(bool disposing) |
| | 226 | | { |
| | 227 | | // Return the buffer to the pool if we're called from Dispose or a finalizer |
| 0 | 228 | | if (_buffer != null) |
| | 229 | | { |
| 0 | 230 | | ArrayPool<byte>.Shared.Return(_buffer, clearArray: true); |
| 0 | 231 | | _buffer = null; |
| | 232 | | } |
| 0 | 233 | | } |
| | 234 | |
|
| | 235 | | private async Task<long> GetBlobLengthInternal(bool async, CancellationToken cancellationToken) |
| | 236 | | { |
| | 237 | | #pragma warning disable AZC0110 // DO NOT use await keyword in possibly synchronous scope. |
| 0 | 238 | | Response<TProperties> response = await _getPropertiesInternalFunc(async, cancellationToken).ConfigureAwait(f |
| | 239 | | #pragma warning restore AZC0110 // DO NOT use await keyword in possibly synchronous scope. |
| | 240 | |
|
| 0 | 241 | | response.GetRawResponse().Headers.TryGetValue("Content-Length", out string lengthString); |
| | 242 | |
|
| 0 | 243 | | if (lengthString == null) |
| | 244 | | { |
| 0 | 245 | | throw new ArgumentException($"{HttpHeader.Names.ContentLength} header is mssing on get properties respon |
| | 246 | | } |
| | 247 | |
|
| 0 | 248 | | return Convert.ToInt64(lengthString, CultureInfo.InvariantCulture); |
| 0 | 249 | | } |
| | 250 | |
|
| | 251 | | private static long GetBlobLengthFromResponse(Response response) |
| | 252 | | { |
| 28 | 253 | | response.Headers.TryGetValue("Content-Range", out string lengthString); |
| | 254 | |
|
| 28 | 255 | | if (lengthString == null) |
| | 256 | | { |
| 0 | 257 | | throw new ArgumentException("Content-Range header is mssing on download response."); |
| | 258 | | } |
| | 259 | |
|
| 28 | 260 | | string[] split = lengthString.Split('/'); |
| 28 | 261 | | return Convert.ToInt64(split[1], CultureInfo.InvariantCulture); |
| | 262 | | } |
| | 263 | |
|
| 0 | 264 | | public override bool CanRead => true; |
| | 265 | |
|
| 0 | 266 | | public override bool CanSeek => false; |
| | 267 | |
|
| 0 | 268 | | public override bool CanWrite => false; |
| | 269 | |
|
| 8 | 270 | | public override long Length => _length; |
| | 271 | |
|
| | 272 | | public override long Position |
| | 273 | | { |
| 0 | 274 | | get => _position; |
| 0 | 275 | | set => throw new NotSupportedException(); |
| | 276 | | } |
| | 277 | |
|
| | 278 | | public override long Seek(long offset, SeekOrigin origin) |
| | 279 | | { |
| 0 | 280 | | throw new NotSupportedException(); |
| | 281 | | } |
| | 282 | |
|
| | 283 | | public override void SetLength(long value) |
| | 284 | | { |
| 0 | 285 | | throw new NotSupportedException(); |
| | 286 | | } |
| | 287 | |
|
| | 288 | | public override void Write(byte[] buffer, int offset, int count) |
| | 289 | | { |
| 0 | 290 | | throw new NotSupportedException(); |
| | 291 | | } |
| | 292 | |
|
| 0 | 293 | | public override void Flush() { } |
| | 294 | |
|
| | 295 | | public override Task FlushAsync(CancellationToken cancellationToken) |
| 0 | 296 | | => Task.CompletedTask; |
| | 297 | | } |
| | 298 | | } |