|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +using System; |
| 19 | +using System.Net; |
| 20 | +using System.Net.Http; |
| 21 | +using System.Threading; |
| 22 | +using System.Threading.Tasks; |
| 23 | +using System.IO; |
| 24 | + |
| 25 | +namespace Apache.Arrow.Adbc.Drivers.Databricks |
| 26 | +{ |
| 27 | + /// <summary> |
| 28 | + /// HTTP handler that implements retry behavior for 503 responses with Retry-After headers. |
| 29 | + /// </summary> |
| 30 | + internal class RetryHttpHandler : DelegatingHandler |
| 31 | + { |
| 32 | + private readonly int _retryTimeoutSeconds; |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Initializes a new instance of the <see cref="RetryHttpHandler"/> class. |
| 36 | + /// </summary> |
| 37 | + /// <param name="innerHandler">The inner handler to delegate to.</param> |
| 38 | + /// <param name="retryEnabled">Whether retry behavior is enabled.</param> |
| 39 | + /// <param name="retryTimeoutSeconds">Maximum total time in seconds to retry before failing.</param> |
| 40 | + public RetryHttpHandler(HttpMessageHandler innerHandler, int retryTimeoutSeconds) |
| 41 | + : base(innerHandler) |
| 42 | + { |
| 43 | + _retryTimeoutSeconds = retryTimeoutSeconds; |
| 44 | + } |
| 45 | + |
| 46 | + /// <summary> |
| 47 | + /// Sends an HTTP request to the inner handler with retry logic for 503 responses. |
| 48 | + /// </summary> |
| 49 | + protected override async Task<HttpResponseMessage> SendAsync( |
| 50 | + HttpRequestMessage request, |
| 51 | + CancellationToken cancellationToken) |
| 52 | + { |
| 53 | + // Clone the request content if it's not null so we can reuse it for retries |
| 54 | + var requestContentClone = request.Content != null |
| 55 | + ? await CloneHttpContentAsync(request.Content) |
| 56 | + : null; |
| 57 | + |
| 58 | + HttpResponseMessage response; |
| 59 | + string? lastErrorMessage = null; |
| 60 | + DateTime startTime = DateTime.UtcNow; |
| 61 | + int totalRetrySeconds = 0; |
| 62 | + |
| 63 | + do |
| 64 | + { |
| 65 | + // Set the content for each attempt (if needed) |
| 66 | + if (requestContentClone != null && request.Content == null) |
| 67 | + { |
| 68 | + request.Content = await CloneHttpContentAsync(requestContentClone); |
| 69 | + } |
| 70 | + |
| 71 | + response = await base.SendAsync(request, cancellationToken); |
| 72 | + |
| 73 | + // If it's not a 503 response, return immediately |
| 74 | + if (response.StatusCode != HttpStatusCode.ServiceUnavailable) |
| 75 | + { |
| 76 | + return response; |
| 77 | + } |
| 78 | + |
| 79 | + // Check for Retry-After header |
| 80 | + if (!response.Headers.TryGetValues("Retry-After", out var retryAfterValues)) |
| 81 | + { |
| 82 | + // No Retry-After header, so return the response as is |
| 83 | + return response; |
| 84 | + } |
| 85 | + |
| 86 | + // Parse the Retry-After value |
| 87 | + string retryAfterValue = string.Join(",", retryAfterValues); |
| 88 | + if (!int.TryParse(retryAfterValue, out int retryAfterSeconds) || retryAfterSeconds <= 0) |
| 89 | + { |
| 90 | + // Invalid Retry-After value, return the response as is |
| 91 | + return response; |
| 92 | + } |
| 93 | + |
| 94 | + lastErrorMessage = $"Service temporarily unavailable (HTTP 503). Retry after {retryAfterSeconds} seconds."; |
| 95 | + |
| 96 | + // Dispose the response before retrying |
| 97 | + response.Dispose(); |
| 98 | + |
| 99 | + // Reset the request content for the next attempt |
| 100 | + request.Content = null; |
| 101 | + |
| 102 | + // Check if we've exceeded the timeout |
| 103 | + totalRetrySeconds += retryAfterSeconds; |
| 104 | + if (_retryTimeoutSeconds > 0 && totalRetrySeconds > _retryTimeoutSeconds) |
| 105 | + { |
| 106 | + // We've exceeded the timeout, so break out of the loop |
| 107 | + break; |
| 108 | + } |
| 109 | + |
| 110 | + // Wait for the specified retry time |
| 111 | + await Task.Delay(TimeSpan.FromSeconds(retryAfterSeconds), cancellationToken); |
| 112 | + } while (!cancellationToken.IsCancellationRequested); |
| 113 | + |
| 114 | + // If we get here, we've either exceeded the timeout or been cancelled |
| 115 | + if (cancellationToken.IsCancellationRequested) |
| 116 | + { |
| 117 | + throw new OperationCanceledException("Request cancelled during retry wait", cancellationToken); |
| 118 | + } |
| 119 | + |
| 120 | + throw new DatabricksException( |
| 121 | + lastErrorMessage ?? "Service temporarily unavailable and retry timeout exceeded", |
| 122 | + AdbcStatusCode.IOError); |
| 123 | + } |
| 124 | + |
| 125 | + /// <summary> |
| 126 | + /// Clones an HttpContent object so it can be reused for retries. |
| 127 | + /// per .net guidance, we should not reuse the http content across multiple |
| 128 | + /// request, as it maybe disposed. |
| 129 | + /// </summary> |
| 130 | + private static async Task<HttpContent> CloneHttpContentAsync(HttpContent content) |
| 131 | + { |
| 132 | + var ms = new MemoryStream(); |
| 133 | + await content.CopyToAsync(ms); |
| 134 | + ms.Position = 0; |
| 135 | + |
| 136 | + var clone = new StreamContent(ms); |
| 137 | + if (content.Headers != null) |
| 138 | + { |
| 139 | + foreach (var header in content.Headers) |
| 140 | + { |
| 141 | + clone.Headers.Add(header.Key, header.Value); |
| 142 | + } |
| 143 | + } |
| 144 | + return clone; |
| 145 | + } |
| 146 | + } |
| 147 | +} |
0 commit comments