| | 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 | |
|
| 0 | 27 | | private static readonly string[] s_failureStates = {"failed", "canceled"}; |
| 0 | 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 | |
|
| 0 | 48 | | public ArmOperationHelpers( |
| 0 | 49 | | IOperationSource<T> source, |
| 0 | 50 | | ClientDiagnostics clientDiagnostics, |
| 0 | 51 | | HttpPipeline pipeline, |
| 0 | 52 | | Request originalRequest, |
| 0 | 53 | | Response originalResponse, |
| 0 | 54 | | OperationFinalStateVia finalStateVia, |
| 0 | 55 | | string scopeName) |
| | 56 | | { |
| 0 | 57 | | _source = source; |
| 0 | 58 | | _rawResponse = originalResponse; |
| 0 | 59 | | _requestMethod = originalRequest.Method; |
| 0 | 60 | | _originalUri = originalRequest.Uri.ToString(); |
| 0 | 61 | | _finalStateVia = finalStateVia; |
| 0 | 62 | | InitializeScenarioInfo(); |
| | 63 | |
|
| 0 | 64 | | _pipeline = pipeline; |
| 0 | 65 | | _clientDiagnostics = clientDiagnostics; |
| 0 | 66 | | _scopeName = scopeName; |
| | 67 | | // When the original response has no headers, we do not start polling immediately. |
| 0 | 68 | | _shouldPoll = _headerFrom != HeaderFrom.None; |
| 0 | 69 | | } |
| | 70 | |
|
| 0 | 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 | | { |
| 0 | 80 | | while (true) |
| | 81 | | { |
| 0 | 82 | | await UpdateStatusAsync(cancellationToken).ConfigureAwait(false); |
| 0 | 83 | | if (HasCompleted) |
| | 84 | | { |
| 0 | 85 | | return Response.FromValue(Value, GetRawResponse()); |
| | 86 | | } |
| | 87 | |
|
| 0 | 88 | | await Task.Delay(pollingInterval, cancellationToken).ConfigureAwait(false); |
| | 89 | | } |
| 0 | 90 | | } |
| | 91 | |
|
| | 92 | | private async ValueTask<Response> UpdateStatusAsync(bool async, CancellationToken cancellationToken) |
| | 93 | | { |
| 0 | 94 | | if (_hasCompleted) |
| | 95 | | { |
| 0 | 96 | | return GetRawResponse(); |
| | 97 | | } |
| | 98 | |
|
| 0 | 99 | | if (_shouldPoll) |
| | 100 | | { |
| 0 | 101 | | UpdatePollUri(); |
| 0 | 102 | | _rawResponse = async |
| 0 | 103 | | ? await GetResponseAsync(_pollUri, cancellationToken).ConfigureAwait(false) |
| 0 | 104 | | : GetResponse(_pollUri, cancellationToken); |
| | 105 | | } |
| | 106 | |
|
| 0 | 107 | | _shouldPoll = true; |
| 0 | 108 | | _hasCompleted = IsTerminalState(out string state); |
| 0 | 109 | | if (_hasCompleted) |
| | 110 | | { |
| 0 | 111 | | Response finalResponse = GetRawResponse(); |
| 0 | 112 | | if (s_failureStates.Contains(state)) |
| | 113 | | { |
| 0 | 114 | | throw _clientDiagnostics.CreateRequestFailedException(finalResponse); |
| | 115 | | } |
| | 116 | |
|
| 0 | 117 | | string? finalUri = GetFinalUri(); |
| 0 | 118 | | if (finalUri != null) |
| | 119 | | { |
| 0 | 120 | | finalResponse = async |
| 0 | 121 | | ? await GetResponseAsync(finalUri, cancellationToken).ConfigureAwait(false) |
| 0 | 122 | | : GetResponse(finalUri, cancellationToken); |
| | 123 | | } |
| | 124 | |
|
| 0 | 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 | | { |
| 0 | 131 | | _value = async |
| 0 | 132 | | ? await _source.CreateResultAsync(finalResponse, cancellationToken).ConfigureAwait(false) |
| 0 | 133 | | : _source.CreateResult(finalResponse, cancellationToken); |
| 0 | 134 | | _rawResponse = finalResponse; |
| 0 | 135 | | _hasValue = true; |
| 0 | 136 | | break; |
| | 137 | | } |
| | 138 | | default: |
| 0 | 139 | | throw _clientDiagnostics.CreateRequestFailedException(finalResponse); |
| | 140 | | } |
| 0 | 141 | | } |
| | 142 | |
|
| 0 | 143 | | return GetRawResponse(); |
| 0 | 144 | | } |
| | 145 | |
|
| 0 | 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 | | { |
| 0 | 159 | | if (!HasValue) |
| | 160 | | { |
| 0 | 161 | | throw new InvalidOperationException("The operation has not completed yet."); |
| | 162 | | } |
| | 163 | |
|
| 0 | 164 | | return _value; |
| | 165 | | } |
| | 166 | | } |
| | 167 | |
|
| 0 | 168 | | public bool HasCompleted => _hasCompleted; |
| 0 | 169 | | public bool HasValue => _hasValue; |
| | 170 | |
|
| | 171 | | private HttpMessage CreateRequest(string link) |
| | 172 | | { |
| 0 | 173 | | HttpMessage message = _pipeline.CreateMessage(); |
| 0 | 174 | | Request request = message.Request; |
| 0 | 175 | | request.Method = RequestMethod.Get; |
| 0 | 176 | | request.Uri.Reset(new Uri(link)); |
| 0 | 177 | | return message; |
| | 178 | | } |
| | 179 | |
|
| | 180 | | private async ValueTask<Response> GetResponseAsync(string link, CancellationToken cancellationToken = default) |
| | 181 | | { |
| 0 | 182 | | if (link == null) |
| | 183 | | { |
| 0 | 184 | | throw new ArgumentNullException(nameof(link)); |
| | 185 | | } |
| | 186 | |
|
| 0 | 187 | | using DiagnosticScope scope = _clientDiagnostics.CreateScope(_scopeName); |
| 0 | 188 | | scope.Start(); |
| | 189 | | try |
| | 190 | | { |
| 0 | 191 | | using HttpMessage message = CreateRequest(link); |
| 0 | 192 | | await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); |
| 0 | 193 | | return message.Response; |
| | 194 | | } |
| 0 | 195 | | catch (Exception e) |
| | 196 | | { |
| 0 | 197 | | scope.Failed(e); |
| 0 | 198 | | throw; |
| | 199 | | } |
| 0 | 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 | | { |
| 0 | 226 | | Response response = GetRawResponse(); |
| 0 | 227 | | state = string.Empty; |
| 0 | 228 | | if (_headerFrom == HeaderFrom.Location) |
| | 229 | | { |
| 0 | 230 | | return response.Status != 202; |
| | 231 | | } |
| | 232 | |
|
| 0 | 233 | | if (response.Status >= 200 && response.Status <= 204) |
| | 234 | | { |
| 0 | 235 | | if (response.ContentStream?.Length > 0) |
| | 236 | | { |
| | 237 | | try |
| | 238 | | { |
| 0 | 239 | | using JsonDocument document = JsonDocument.Parse(response.ContentStream); |
| 0 | 240 | | foreach (JsonProperty property in document.RootElement.EnumerateObject()) |
| | 241 | | { |
| 0 | 242 | | if ((_headerFrom == HeaderFrom.OperationLocation || |
| 0 | 243 | | _headerFrom == HeaderFrom.AzureAsyncOperation) && |
| 0 | 244 | | property.NameEquals("status")) |
| | 245 | | { |
| 0 | 246 | | state = property.Value.GetString().ToLowerInvariant(); |
| 0 | 247 | | return s_terminalStates.Contains(state); |
| | 248 | | } |
| | 249 | |
|
| 0 | 250 | | if (_headerFrom == HeaderFrom.None && property.NameEquals("properties")) |
| | 251 | | { |
| 0 | 252 | | foreach (JsonProperty innerProperty in property.Value.EnumerateObject()) |
| | 253 | | { |
| 0 | 254 | | if (innerProperty.NameEquals("provisioningState")) |
| | 255 | | { |
| 0 | 256 | | state = innerProperty.Value.GetString().ToLowerInvariant(); |
| 0 | 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 |
| 0 | 266 | | response.ContentStream.Position = 0; |
| 0 | 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); |
| 0 | 278 | | } |
| | 279 | |
|
| | 280 | | private enum HeaderFrom |
| | 281 | | { |
| | 282 | | None, |
| | 283 | | OperationLocation, |
| | 284 | | AzureAsyncOperation, |
| | 285 | | Location |
| | 286 | | } |
| | 287 | |
|
| | 288 | | private void InitializeScenarioInfo() |
| | 289 | | { |
| 0 | 290 | | _originalHasLocation = _rawResponse.Headers.Contains("Location"); |
| | 291 | |
|
| 0 | 292 | | if (_rawResponse.Headers.Contains("Operation-Location")) |
| | 293 | | { |
| 0 | 294 | | _headerFrom = HeaderFrom.OperationLocation; |
| 0 | 295 | | return; |
| | 296 | | } |
| | 297 | |
|
| 0 | 298 | | if (_rawResponse.Headers.Contains("Azure-AsyncOperation")) |
| | 299 | | { |
| 0 | 300 | | _headerFrom = HeaderFrom.AzureAsyncOperation; |
| 0 | 301 | | return; |
| | 302 | | } |
| | 303 | |
|
| 0 | 304 | | if (_originalHasLocation) |
| | 305 | | { |
| 0 | 306 | | _headerFrom = HeaderFrom.Location; |
| 0 | 307 | | return; |
| | 308 | | } |
| | 309 | |
|
| 0 | 310 | | _pollUri = _originalUri; |
| 0 | 311 | | _headerFrom = HeaderFrom.None; |
| 0 | 312 | | } |
| | 313 | |
|
| | 314 | | private void UpdatePollUri() |
| | 315 | | { |
| 0 | 316 | | var hasLocation = _rawResponse.Headers.TryGetValue("Location", out string? location); |
| 0 | 317 | | if (hasLocation) |
| | 318 | | { |
| 0 | 319 | | _lastKnownLocation = location; |
| | 320 | | } |
| | 321 | |
|
| 0 | 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; |
| 0 | 330 | | case HeaderFrom.Location when hasLocation: |
| 0 | 331 | | _pollUri = location!; |
| 0 | 332 | | return; |
| | 333 | | } |
| 0 | 334 | | } |
| | 335 | |
|
| | 336 | | private string? GetFinalUri() |
| | 337 | | { |
| 0 | 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 | |
|
| 0 | 356 | | return null; |
| | 357 | | } |
| | 358 | | } |
| | 359 | | } |