| | 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 | |
|
| 148 | 76 | | public LazyLoadingReadOnlyStream( |
| 148 | 77 | | Func<HttpRange, TRequestConditions, bool, bool, CancellationToken, Task<Response<IDownloadedContent>>> downl |
| 148 | 78 | | Func<ETag?, TRequestConditions> createRequestConditionsFunc, |
| 148 | 79 | | Func<bool, CancellationToken, Task<Response<TProperties>>> getPropertiesFunc, |
| 148 | 80 | | long position = 0, |
| 148 | 81 | | int? bufferSize = default, |
| 148 | 82 | | TRequestConditions requestConditions = default) |
| | 83 | | { |
| 148 | 84 | | _downloadInternalFunc = downloadInternalFunc; |
| 148 | 85 | | _createRequestConditionsFunc = createRequestConditionsFunc; |
| 148 | 86 | | _getPropertiesInternalFunc = getPropertiesFunc; |
| 148 | 87 | | _position = position; |
| 148 | 88 | | _bufferSize = bufferSize ?? Constants.DefaultStreamingDownloadSize; |
| 148 | 89 | | _buffer = ArrayPool<byte>.Shared.Rent(_bufferSize); |
| 148 | 90 | | _bufferPosition = 0; |
| 148 | 91 | | _bufferLength = 0; |
| 148 | 92 | | _requestConditions = requestConditions; |
| 148 | 93 | | _length = -1; |
| 148 | 94 | | _allowBlobModifications = !(_requestConditions == null && _createRequestConditionsFunc != null); |
| 148 | 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 |
| 612 | 107 | | => await ReadInternal( |
| 612 | 108 | | buffer, |
| 612 | 109 | | offset, |
| 612 | 110 | | count, |
| 612 | 111 | | async: true, |
| 612 | 112 | | cancellationToken) |
| 612 | 113 | | .ConfigureAwait(false); |
| | 114 | |
|
| | 115 | | public async Task<int> ReadInternal(byte[] buffer, int offset, int count, bool async, CancellationToken cancella |
| | 116 | | { |
| 612 | 117 | | ValidateReadParameters(buffer, offset, count); |
| | 118 | |
|
| 580 | 119 | | if (_position == _length) |
| | 120 | | { |
| 12 | 121 | | if (_allowBlobModifications) |
| | 122 | | { |
| | 123 | | // In case the blob grow since our last download call. |
| 8 | 124 | | _length = await GetBlobLengthInternal(async, cancellationToken).ConfigureAwait(false); |
| | 125 | |
|
| 8 | 126 | | if (_position == _length) |
| | 127 | | { |
| 0 | 128 | | return 0; |
| | 129 | | } |
| | 130 | | } |
| | 131 | | else |
| | 132 | | { |
| 4 | 133 | | return 0; |
| | 134 | | } |
| | 135 | |
|
| | 136 | | } |
| | 137 | |
|
| 576 | 138 | | if (_bufferPosition == 0 || _bufferPosition == _buffer.Length) |
| | 139 | | { |
| 576 | 140 | | int lastDownloadedBytes = await DownloadInternal(async, cancellationToken).ConfigureAwait(false); |
| 520 | 141 | | if (lastDownloadedBytes == 0) |
| | 142 | | { |
| 0 | 143 | | return 0; |
| | 144 | | } |
| | 145 | | } |
| | 146 | |
|
| 520 | 147 | | int remainingBytesInBuffer = _bufferLength - _bufferPosition; |
| | 148 | |
|
| | 149 | | // We will return the minimum of remainingBytesInBuffer and the count provided by the user |
| 520 | 150 | | int bytesToWrite = Math.Min(remainingBytesInBuffer, count); |
| | 151 | |
|
| 520 | 152 | | Array.Copy(_buffer, _bufferPosition, buffer, offset, bytesToWrite); |
| | 153 | |
|
| 520 | 154 | | _position += bytesToWrite; |
| | 155 | |
|
| 520 | 156 | | return bytesToWrite; |
| 524 | 157 | | } |
| | 158 | |
|
| | 159 | | private async Task<int> DownloadInternal(bool async, CancellationToken cancellationToken) |
| | 160 | | { |
| | 161 | | Response<IDownloadedContent> response; |
| | 162 | |
|
| 576 | 163 | | HttpRange range = new HttpRange(_position, _bufferSize); |
| | 164 | |
|
| | 165 | | #pragma warning disable AZC0110 // DO NOT use await keyword in possibly synchronous scope. |
| 576 | 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 | |
|
| 520 | 169 | | using Stream networkStream = response.Value.Content; |
| | 170 | |
|
| | 171 | | int copiedBytes; |
| | 172 | |
|
| 520 | 173 | | if (async) |
| | 174 | | { |
| 520 | 175 | | copiedBytes = await networkStream.ReadAsync( |
| 520 | 176 | | buffer: _buffer, |
| 520 | 177 | | offset: 0, |
| 520 | 178 | | count: _buffer.Length, |
| 520 | 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 | |
|
| 520 | 189 | | _bufferPosition = 0; |
| 520 | 190 | | _bufferLength = copiedBytes; |
| 520 | 191 | | _length = GetBlobLengthFromResponse(response.GetRawResponse()); |
| | 192 | |
|
| | 193 | | // Set _requestConditions If-Match if we are not allowing the blob to be modified. |
| 520 | 194 | | if (!_allowBlobModifications) |
| | 195 | | { |
| 312 | 196 | | _requestConditions = _createRequestConditionsFunc(response.GetRawResponse().Headers.ETag); |
| | 197 | | } |
| | 198 | |
|
| 520 | 199 | | return response.GetRawResponse().Headers.ContentLength.GetValueOrDefault(); |
| 520 | 200 | | } |
| | 201 | |
|
| | 202 | | private static void ValidateReadParameters(byte[] buffer, int offset, int count) |
| | 203 | | { |
| 612 | 204 | | if (buffer == null) |
| | 205 | | { |
| 8 | 206 | | throw new ArgumentNullException($"{nameof(buffer)}", $"{nameof(buffer)} cannot be null."); |
| | 207 | | } |
| | 208 | |
|
| 604 | 209 | | if (offset < 0) |
| | 210 | | { |
| 8 | 211 | | throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot be less than 0."); |
| | 212 | | } |
| | 213 | |
|
| 596 | 214 | | if (offset > buffer.Length) |
| | 215 | | { |
| 8 | 216 | | throw new ArgumentOutOfRangeException($"{nameof(offset)} cannot exceed {nameof(buffer)} length."); |
| | 217 | | } |
| | 218 | |
|
| 588 | 219 | | if (count < 0) |
| | 220 | | { |
| 8 | 221 | | throw new ArgumentOutOfRangeException($"{nameof(count)} cannot be less than 0."); |
| | 222 | | } |
| 580 | 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. |
| 8 | 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 | |
|
| 8 | 241 | | response.GetRawResponse().Headers.TryGetValue("Content-Length", out string lengthString); |
| | 242 | |
|
| 8 | 243 | | if (lengthString == null) |
| | 244 | | { |
| 0 | 245 | | throw new ArgumentException($"{HttpHeader.Names.ContentLength} header is mssing on get properties respon |
| | 246 | | } |
| | 247 | |
|
| 8 | 248 | | return Convert.ToInt64(lengthString, CultureInfo.InvariantCulture); |
| 8 | 249 | | } |
| | 250 | |
|
| | 251 | | private static long GetBlobLengthFromResponse(Response response) |
| | 252 | | { |
| 520 | 253 | | response.Headers.TryGetValue("Content-Range", out string lengthString); |
| | 254 | |
|
| 520 | 255 | | if (lengthString == null) |
| | 256 | | { |
| 0 | 257 | | throw new ArgumentException("Content-Range header is mssing on download response."); |
| | 258 | | } |
| | 259 | |
|
| 520 | 260 | | string[] split = lengthString.Split('/'); |
| 520 | 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 | |
|
| 72 | 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 | | } |