| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | #nullable enable |
| | 5 | |
|
| | 6 | | using System; |
| | 7 | | using System.Linq; |
| | 8 | | using System.Text.Json; |
| | 9 | | using System.Threading; |
| | 10 | | using System.Threading.Tasks; |
| | 11 | | using Azure.Core.Pipeline; |
| | 12 | |
|
| | 13 | | namespace Azure.Core |
| | 14 | | { |
| | 15 | | /// <summary> |
| | 16 | | /// This implements the ARM scenarios for LROs. It is highly recommended to read the ARM spec prior to modifying thi |
| | 17 | | /// https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/Addendum.md#asynchronous-operations |
| | 18 | | /// Other reference documents include: |
| | 19 | | /// https://github.com/Azure/autorest/blob/master/docs/extensions/readme.md#x-ms-long-running-operation |
| | 20 | | /// https://github.com/Azure/adx-documentation-pr/blob/master/sdks/LRO/LRO_AzureSDK.md |
| | 21 | | /// </summary> |
| | 22 | | /// <typeparam name="T">The final result of the LRO.</typeparam> |
| | 23 | | internal class ArmOperationHelpers<T> |
| | 24 | | { |
| 0 | 25 | | public static TimeSpan DefaultPollingInterval { get; } = TimeSpan.FromSeconds(1); |
| | 26 | |
|
| 4 | 27 | | private static readonly string[] s_failureStates = {"failed", "canceled"}; |
| 4 | 28 | | private static readonly string[] s_terminalStates = {"succeeded", "failed", "canceled"}; |
| | 29 | |
|
| | 30 | | private readonly HttpPipeline _pipeline; |
| | 31 | | private readonly ClientDiagnostics _clientDiagnostics; |
| | 32 | | private readonly string _scopeName; |
| | 33 | | private readonly RequestMethod _requestMethod; |
| | 34 | | private readonly string _originalUri; |
| | 35 | | private readonly OperationFinalStateVia _finalStateVia; |
| | 36 | | private HeaderFrom _headerFrom; |
| | 37 | | private string _pollUri = default!; |
| | 38 | | private bool _originalHasLocation; |
| | 39 | | private string? _lastKnownLocation; |
| | 40 | |
|
| | 41 | | private readonly IOperationSource<T> _source; |
| | 42 | | private Response _rawResponse; |
| | 43 | | private T _value = default!; |
| | 44 | | private bool _hasValue; |
| | 45 | | private bool _hasCompleted; |
| | 46 | | private bool _shouldPoll; |
| | 47 | |
|
| 104 | 48 | | public ArmOperationHelpers( |
| 104 | 49 | | IOperationSource<T> source, |
| 104 | 50 | | ClientDiagnostics clientDiagnostics, |
| 104 | 51 | | HttpPipeline pipeline, |
| 104 | 52 | | Request originalRequest, |
| 104 | 53 | | Response originalResponse, |
| 104 | 54 | | OperationFinalStateVia finalStateVia, |
| 104 | 55 | | string scopeName) |
| | 56 | | { |
| 104 | 57 | | _source = source; |
| 104 | 58 | | _rawResponse = originalResponse; |
| 104 | 59 | | _requestMethod = originalRequest.Method; |
| 104 | 60 | | _originalUri = originalRequest.Uri.ToString(); |
| 104 | 61 | | _finalStateVia = finalStateVia; |
| 104 | 62 | | InitializeScenarioInfo(); |
| | 63 | |
|
| 104 | 64 | | _pipeline = pipeline; |
| 104 | 65 | | _clientDiagnostics = clientDiagnostics; |
| 104 | 66 | | _scopeName = scopeName; |
| | 67 | | // When the original response has no headers, we do not start polling immediately. |
| 104 | 68 | | _shouldPoll = _headerFrom != HeaderFrom.None; |
| 104 | 69 | | } |
| | 70 | |
|
| 5868 | 71 | | public Response GetRawResponse() => _rawResponse; |
| | 72 | |
|
| | 73 | | public ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken = default) |
| | 74 | | { |
| 0 | 75 | | return WaitForCompletionAsync(DefaultPollingInterval, cancellationToken); |
| | 76 | | } |
| | 77 | |
|
| | 78 | | public async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellat |
| | 79 | | { |
| 2726 | 80 | | while (true) |
| | 81 | | { |
| 2830 | 82 | | await UpdateStatusAsync(cancellationToken).ConfigureAwait(false); |
| 2830 | 83 | | if (HasCompleted) |
| | 84 | | { |
| 104 | 85 | | return Response.FromValue(Value, GetRawResponse()); |
| | 86 | | } |
| | 87 | |
|
| 2726 | 88 | | await Task.Delay(pollingInterval, cancellationToken).ConfigureAwait(false); |
| | 89 | | } |
| 104 | 90 | | } |
| | 91 | |
|
| | 92 | | private async ValueTask<Response> UpdateStatusAsync(bool async, CancellationToken cancellationToken) |
| | 93 | | { |
| 2830 | 94 | | if (_hasCompleted) |
| | 95 | | { |
| 0 | 96 | | return GetRawResponse(); |
| | 97 | | } |
| | 98 | |
|
| 2830 | 99 | | if (_shouldPoll) |
| | 100 | | { |
| 2774 | 101 | | UpdatePollUri(); |
| 2774 | 102 | | _rawResponse = async |
| 2774 | 103 | | ? await GetResponseAsync(_pollUri, cancellationToken).ConfigureAwait(false) |
| 2774 | 104 | | : GetResponse(_pollUri, cancellationToken); |
| | 105 | | } |
| | 106 | |
|
| 2830 | 107 | | _shouldPoll = true; |
| 2830 | 108 | | _hasCompleted = IsTerminalState(out string state); |
| 2830 | 109 | | if (_hasCompleted) |
| | 110 | | { |
| 104 | 111 | | Response finalResponse = GetRawResponse(); |
| 104 | 112 | | if (s_failureStates.Contains(state)) |
| | 113 | | { |
| 0 | 114 | | throw _clientDiagnostics.CreateRequestFailedException(finalResponse); |
| | 115 | | } |
| | 116 | |
|
| 104 | 117 | | string? finalUri = GetFinalUri(); |
| 104 | 118 | | if (finalUri != null) |
| | 119 | | { |
| 0 | 120 | | finalResponse = async |
| 0 | 121 | | ? await GetResponseAsync(finalUri, cancellationToken).ConfigureAwait(false) |
| 0 | 122 | | : GetResponse(finalUri, cancellationToken); |
| | 123 | | } |
| | 124 | |
|
| 104 | 125 | | switch (finalResponse.Status) |
| | 126 | | { |
| | 127 | | case 200: |
| 0 | 128 | | case 201 when _requestMethod == RequestMethod.Put: |
| 0 | 129 | | case 204 when !(_requestMethod == RequestMethod.Put || _requestMethod == RequestMethod.Patch): |
| | 130 | | { |
| 104 | 131 | | _value = async |
| 104 | 132 | | ? await _source.CreateResultAsync(finalResponse, cancellationToken).ConfigureAwait(false) |
| 104 | 133 | | : _source.CreateResult(finalResponse, cancellationToken); |
| 104 | 134 | | _rawResponse = finalResponse; |
| 104 | 135 | | _hasValue = true; |
| 104 | 136 | | break; |
| | 137 | | } |
| | 138 | | default: |
| 0 | 139 | | throw _clientDiagnostics.CreateRequestFailedException(finalResponse); |
| | 140 | | } |
| 104 | 141 | | } |
| | 142 | |
|
| 2830 | 143 | | return GetRawResponse(); |
| 2830 | 144 | | } |
| | 145 | |
|
| 2830 | 146 | | public async ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => await Updat |
| | 147 | |
|
| 0 | 148 | | public Response UpdateStatus(CancellationToken cancellationToken = default) => UpdateStatusAsync(async: false, c |
| | 149 | |
|
| | 150 | | #pragma warning disable CA1822 |
| | 151 | | //TODO: This is currently unused. |
| 0 | 152 | | public string Id => throw new NotImplementedException(); |
| | 153 | | #pragma warning restore CA1822 |
| | 154 | |
|
| | 155 | | public T Value |
| | 156 | | { |
| | 157 | | get |
| | 158 | | { |
| 104 | 159 | | if (!HasValue) |
| | 160 | | { |
| 0 | 161 | | throw new InvalidOperationException("The operation has not completed yet."); |
| | 162 | | } |
| | 163 | |
|
| 104 | 164 | | return _value; |
| | 165 | | } |
| | 166 | | } |
| | 167 | |
|
| 2830 | 168 | | public bool HasCompleted => _hasCompleted; |
| 104 | 169 | | public bool HasValue => _hasValue; |
| | 170 | |
|
| | 171 | | private HttpMessage CreateRequest(string link) |
| | 172 | | { |
| 2774 | 173 | | HttpMessage message = _pipeline.CreateMessage(); |
| 2774 | 174 | | Request request = message.Request; |
| 2774 | 175 | | request.Method = RequestMethod.Get; |
| 2774 | 176 | | request.Uri.Reset(new Uri(link)); |
| 2774 | 177 | | return message; |
| | 178 | | } |
| | 179 | |
|
| | 180 | | private async ValueTask<Response> GetResponseAsync(string link, CancellationToken cancellationToken = default) |
| | 181 | | { |
| 2774 | 182 | | if (link == null) |
| | 183 | | { |
| 0 | 184 | | throw new ArgumentNullException(nameof(link)); |
| | 185 | | } |
| | 186 | |
|
| 2774 | 187 | | using DiagnosticScope scope = _clientDiagnostics.CreateScope(_scopeName); |
| 2774 | 188 | | scope.Start(); |
| | 189 | | try |
| | 190 | | { |
| 2774 | 191 | | using HttpMessage message = CreateRequest(link); |
| 2774 | 192 | | await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); |
| 2774 | 193 | | return message.Response; |
| | 194 | | } |
| 0 | 195 | | catch (Exception e) |
| | 196 | | { |
| 0 | 197 | | scope.Failed(e); |
| 0 | 198 | | throw; |
| | 199 | | } |
| 2774 | 200 | | } |
| | 201 | |
|
| | 202 | | private Response GetResponse(string link, CancellationToken cancellationToken = default) |
| | 203 | | { |
| 0 | 204 | | if (link == null) |
| | 205 | | { |
| 0 | 206 | | throw new ArgumentNullException(nameof(link)); |
| | 207 | | } |
| | 208 | |
|
| 0 | 209 | | using DiagnosticScope scope = _clientDiagnostics.CreateScope(_scopeName); |
| 0 | 210 | | scope.Start(); |
| | 211 | | try |
| | 212 | | { |
| 0 | 213 | | using HttpMessage message = CreateRequest(link); |
| 0 | 214 | | _pipeline.Send(message, cancellationToken); |
| 0 | 215 | | return message.Response; |
| | 216 | | } |
| 0 | 217 | | catch (Exception e) |
| | 218 | | { |
| 0 | 219 | | scope.Failed(e); |
| 0 | 220 | | throw; |
| | 221 | | } |
| 0 | 222 | | } |
| | 223 | |
|
| | 224 | | private bool IsTerminalState(out string state) |
| | 225 | | { |
| 2830 | 226 | | Response response = GetRawResponse(); |
| 2830 | 227 | | state = string.Empty; |
| 2830 | 228 | | if (_headerFrom == HeaderFrom.Location) |
| | 229 | | { |
| 872 | 230 | | return response.Status != 202; |
| | 231 | | } |
| | 232 | |
|
| 1958 | 233 | | if (response.Status >= 200 && response.Status <= 204) |
| | 234 | | { |
| 1958 | 235 | | if (response.ContentStream?.Length > 0) |
| | 236 | | { |
| | 237 | | try |
| | 238 | | { |
| 1958 | 239 | | using JsonDocument document = JsonDocument.Parse(response.ContentStream); |
| 29370 | 240 | | foreach (JsonProperty property in document.RootElement.EnumerateObject()) |
| | 241 | | { |
| 13706 | 242 | | if ((_headerFrom == HeaderFrom.OperationLocation || |
| 13706 | 243 | | _headerFrom == HeaderFrom.AzureAsyncOperation) && |
| 13706 | 244 | | property.NameEquals("status")) |
| | 245 | | { |
| 0 | 246 | | state = property.Value.GetString().ToLowerInvariant(); |
| 0 | 247 | | return s_terminalStates.Contains(state); |
| | 248 | | } |
| | 249 | |
|
| 13706 | 250 | | if (_headerFrom == HeaderFrom.None && property.NameEquals("properties")) |
| | 251 | | { |
| 21538 | 252 | | foreach (JsonProperty innerProperty in property.Value.EnumerateObject()) |
| | 253 | | { |
| 9790 | 254 | | if (innerProperty.NameEquals("provisioningState")) |
| | 255 | | { |
| 1958 | 256 | | state = innerProperty.Value.GetString().ToLowerInvariant(); |
| 1958 | 257 | | return s_terminalStates.Contains(state); |
| | 258 | | } |
| | 259 | | } |
| | 260 | | } |
| | 261 | | } |
| | 262 | | } |
| | 263 | | finally |
| | 264 | | { |
| | 265 | | // It is required to reset the position of the content after reading as this response may be use |
| 1958 | 266 | | response.ContentStream.Position = 0; |
| 1958 | 267 | | } |
| | 268 | | } |
| | 269 | |
|
| | 270 | | // If provisioningState was not found, it defaults to Succeeded. |
| 0 | 271 | | if (_headerFrom == HeaderFrom.None) |
| | 272 | | { |
| 0 | 273 | | return true; |
| | 274 | | } |
| | 275 | | } |
| | 276 | |
|
| 0 | 277 | | throw _clientDiagnostics.CreateRequestFailedException(response); |
| 1958 | 278 | | } |
| | 279 | |
|
| | 280 | | private enum HeaderFrom |
| | 281 | | { |
| | 282 | | None, |
| | 283 | | OperationLocation, |
| | 284 | | AzureAsyncOperation, |
| | 285 | | Location |
| | 286 | | } |
| | 287 | |
|
| | 288 | | private void InitializeScenarioInfo() |
| | 289 | | { |
| 104 | 290 | | _originalHasLocation = _rawResponse.Headers.Contains("Location"); |
| | 291 | |
|
| 104 | 292 | | if (_rawResponse.Headers.Contains("Operation-Location")) |
| | 293 | | { |
| 0 | 294 | | _headerFrom = HeaderFrom.OperationLocation; |
| 0 | 295 | | return; |
| | 296 | | } |
| | 297 | |
|
| 104 | 298 | | if (_rawResponse.Headers.Contains("Azure-AsyncOperation")) |
| | 299 | | { |
| 0 | 300 | | _headerFrom = HeaderFrom.AzureAsyncOperation; |
| 0 | 301 | | return; |
| | 302 | | } |
| | 303 | |
|
| 104 | 304 | | if (_originalHasLocation) |
| | 305 | | { |
| 48 | 306 | | _headerFrom = HeaderFrom.Location; |
| 48 | 307 | | return; |
| | 308 | | } |
| | 309 | |
|
| 56 | 310 | | _pollUri = _originalUri; |
| 56 | 311 | | _headerFrom = HeaderFrom.None; |
| 56 | 312 | | } |
| | 313 | |
|
| | 314 | | private void UpdatePollUri() |
| | 315 | | { |
| 2774 | 316 | | var hasLocation = _rawResponse.Headers.TryGetValue("Location", out string? location); |
| 2774 | 317 | | if (hasLocation) |
| | 318 | | { |
| 872 | 319 | | _lastKnownLocation = location; |
| | 320 | | } |
| | 321 | |
|
| 2774 | 322 | | switch (_headerFrom) |
| | 323 | | { |
| 0 | 324 | | case HeaderFrom.OperationLocation when _rawResponse.Headers.TryGetValue("Operation-Location", out string |
| 0 | 325 | | _pollUri = operationLocation; |
| 0 | 326 | | return; |
| 0 | 327 | | case HeaderFrom.AzureAsyncOperation when _rawResponse.Headers.TryGetValue("Azure-AsyncOperation", out st |
| 0 | 328 | | _pollUri = azureAsyncOperation; |
| 0 | 329 | | return; |
| 872 | 330 | | case HeaderFrom.Location when hasLocation: |
| 872 | 331 | | _pollUri = location!; |
| 872 | 332 | | return; |
| | 333 | | } |
| 0 | 334 | | } |
| | 335 | |
|
| | 336 | | private string? GetFinalUri() |
| | 337 | | { |
| 104 | 338 | | if (_headerFrom == HeaderFrom.OperationLocation || _headerFrom == HeaderFrom.AzureAsyncOperation) |
| | 339 | | { |
| 0 | 340 | | if (_requestMethod == RequestMethod.Delete) |
| | 341 | | { |
| 0 | 342 | | return null; |
| | 343 | | } |
| | 344 | |
|
| 0 | 345 | | if (_requestMethod == RequestMethod.Put || (_originalHasLocation && _finalStateVia == OperationFinalStat |
| | 346 | | { |
| 0 | 347 | | return _originalUri; |
| | 348 | | } |
| | 349 | |
|
| 0 | 350 | | if (_originalHasLocation && _finalStateVia == OperationFinalStateVia.Location) |
| | 351 | | { |
| 0 | 352 | | return _lastKnownLocation; |
| | 353 | | } |
| | 354 | | } |
| | 355 | |
|
| 104 | 356 | | return null; |
| | 357 | | } |
| | 358 | | } |
| | 359 | | } |