| | | 1 | | using Services.ApiServices.OzonApi.Filters; |
| | | 2 | | |
| | | 3 | | namespace Services.ApiServices.OzonApi; |
| | | 4 | | |
| | | 5 | | public sealed class PackageLabelPollResult |
| | | 6 | | { |
| | | 7 | | public bool IsSuccess { get; init; } |
| | | 8 | | public string? FileUrl { get; init; } |
| | | 9 | | public string? Error { get; init; } |
| | | 10 | | |
| | | 11 | | public static PackageLabelPollResult Completed(string fileUrl) => |
| | | 12 | | new() { IsSuccess = true, FileUrl = fileUrl }; |
| | | 13 | | |
| | | 14 | | public static PackageLabelPollResult Failed(string error) => |
| | | 15 | | new() { IsSuccess = false, Error = error }; |
| | | 16 | | } |
| | | 17 | | |
| | | 18 | | /// <summary> |
| | | 19 | | /// Общая логика опроса заданий на этикетки Ozon (package-label/get). |
| | | 20 | | /// </summary> |
| | | 21 | | public static class PackageLabelPollingHelper |
| | | 22 | | { |
| | | 23 | | public const int DefaultMaxAttempts = 20; |
| | | 24 | | |
| | 1 | 25 | | private static readonly int[] BackoffDelaysMs = [300, 500, 1000, 2000]; |
| | | 26 | | |
| | | 27 | | public static async Task<byte[]> PollSingleTaskForBytesAsync( |
| | | 28 | | Func<long, Task<PackageLabelGetResponse>> getFile, |
| | | 29 | | Func<string, Task<byte[]>> downloadFile, |
| | | 30 | | long taskId, |
| | | 31 | | IReadOnlyCollection<string> postingNumbers, |
| | | 32 | | int maxAttempts = DefaultMaxAttempts, |
| | | 33 | | CancellationToken cancellationToken = default) |
| | | 34 | | { |
| | 0 | 35 | | var poll = await PollSingleTaskForFileUrlAsync(getFile, taskId, postingNumbers, maxAttempts, cancellationToken) |
| | 0 | 36 | | .ConfigureAwait(false); |
| | 0 | 37 | | if (!poll.IsSuccess || string.IsNullOrEmpty(poll.FileUrl)) |
| | 0 | 38 | | throw new Exception(poll.Error ?? "Не удалось получить этикетку"); |
| | | 39 | | |
| | 0 | 40 | | var bytes = await downloadFile(poll.FileUrl).ConfigureAwait(false); |
| | 0 | 41 | | if (bytes is not { Length: > 0 }) |
| | 0 | 42 | | throw new Exception("Этикетка не была напечатана (пустой файл)"); |
| | | 43 | | |
| | 0 | 44 | | return bytes; |
| | 0 | 45 | | } |
| | | 46 | | |
| | | 47 | | public static async Task<PackageLabelPollResult> PollSingleTaskForFileUrlAsync( |
| | | 48 | | Func<long, Task<PackageLabelGetResponse>> getFile, |
| | | 49 | | long taskId, |
| | | 50 | | IReadOnlyCollection<string> postingNumbers, |
| | | 51 | | int maxAttempts = DefaultMaxAttempts, |
| | | 52 | | CancellationToken cancellationToken = default) |
| | | 53 | | { |
| | 1 | 54 | | var postingSet = new HashSet<string>(postingNumbers, StringComparer.Ordinal); |
| | 1 | 55 | | PackageLabelGetResponse? lastResponse = null; |
| | | 56 | | |
| | 2 | 57 | | for (var attempt = 0; attempt < maxAttempts; attempt++) |
| | | 58 | | { |
| | 1 | 59 | | if (attempt > 0) |
| | | 60 | | { |
| | 0 | 61 | | var delayMs = BackoffDelaysMs[Math.Min(attempt - 1, BackoffDelaysMs.Length - 1)]; |
| | 0 | 62 | | await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); |
| | | 63 | | } |
| | | 64 | | |
| | 1 | 65 | | lastResponse = await getFile(taskId).ConfigureAwait(false); |
| | 1 | 66 | | var outcome = EvaluateResponse(lastResponse, postingSet); |
| | 1 | 67 | | if (outcome != null) |
| | 1 | 68 | | return outcome; |
| | | 69 | | } |
| | | 70 | | |
| | 0 | 71 | | var status = lastResponse?.Status?.Code ?? "unknown"; |
| | 0 | 72 | | return PackageLabelPollResult.Failed($"Не удалось получить этикетку: время ожидания истекло. Статус: {status}"); |
| | 1 | 73 | | } |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Параллельно опрашивает все незавершённые taskId на каждой итерации (общий backoff). |
| | | 77 | | /// </summary> |
| | | 78 | | public static async Task<Dictionary<long, PackageLabelPollResult>> PollTasksParallelForFileUrlsAsync( |
| | | 79 | | Func<long, Task<PackageLabelGetResponse>> getFile, |
| | | 80 | | IReadOnlyDictionary<long, string[]> taskIdToPostings, |
| | | 81 | | int maxAttempts = DefaultMaxAttempts, |
| | | 82 | | CancellationToken cancellationToken = default) |
| | | 83 | | { |
| | 1 | 84 | | var results = new Dictionary<long, PackageLabelPollResult>(); |
| | 1 | 85 | | if (taskIdToPostings.Count == 0) |
| | 0 | 86 | | return results; |
| | | 87 | | |
| | 1 | 88 | | var pending = taskIdToPostings.Keys.ToHashSet(); |
| | | 89 | | |
| | 6 | 90 | | for (var attempt = 0; attempt < maxAttempts && pending.Count > 0; attempt++) |
| | | 91 | | { |
| | 2 | 92 | | if (attempt > 0) |
| | | 93 | | { |
| | 1 | 94 | | var delayMs = BackoffDelaysMs[Math.Min(attempt - 1, BackoffDelaysMs.Length - 1)]; |
| | 1 | 95 | | await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); |
| | | 96 | | } |
| | | 97 | | |
| | 2 | 98 | | var pollTasks = pending.Select(async taskId => |
| | 2 | 99 | | { |
| | 6 | 100 | | var response = await getFile(taskId).ConfigureAwait(false); |
| | 6 | 101 | | return (taskId, response); |
| | 8 | 102 | | }); |
| | | 103 | | |
| | 2 | 104 | | var pollResponses = await Task.WhenAll(pollTasks).ConfigureAwait(false); |
| | | 105 | | |
| | 16 | 106 | | foreach (var (taskId, response) in pollResponses) |
| | | 107 | | { |
| | 6 | 108 | | var postings = taskIdToPostings[taskId]; |
| | 6 | 109 | | var postingSet = new HashSet<string>(postings, StringComparer.Ordinal); |
| | 6 | 110 | | var outcome = EvaluateResponse(response, postingSet); |
| | 6 | 111 | | if (outcome == null) |
| | | 112 | | continue; |
| | | 113 | | |
| | 3 | 114 | | results[taskId] = outcome; |
| | 3 | 115 | | pending.Remove(taskId); |
| | | 116 | | } |
| | | 117 | | } |
| | | 118 | | |
| | 2 | 119 | | foreach (var taskId in pending) |
| | | 120 | | { |
| | 0 | 121 | | results[taskId] = PackageLabelPollResult.Failed("Не удалось получить этикетку: время ожидания истекло"); |
| | | 122 | | } |
| | | 123 | | |
| | 1 | 124 | | return results; |
| | 1 | 125 | | } |
| | | 126 | | |
| | | 127 | | private static PackageLabelPollResult? EvaluateResponse( |
| | | 128 | | PackageLabelGetResponse? response, |
| | | 129 | | HashSet<string> postingSet) |
| | | 130 | | { |
| | 7 | 131 | | if (response == null) |
| | 0 | 132 | | return null; |
| | | 133 | | |
| | 7 | 134 | | var status = response.Status; |
| | | 135 | | |
| | 7 | 136 | | if (status?.UnprintedPostings is { Count: > 0 }) |
| | | 137 | | { |
| | 1 | 138 | | var unprinted = status.UnprintedPostings |
| | 2 | 139 | | .FirstOrDefault(p => !string.IsNullOrEmpty(p.PostingNumber) && |
| | 2 | 140 | | postingSet.Contains(p.PostingNumber)); |
| | 1 | 141 | | if (unprinted != null) |
| | | 142 | | { |
| | 1 | 143 | | return PackageLabelPollResult.Failed( |
| | 1 | 144 | | $"Ошибка формирования этикетки для {unprinted.PostingNumber}: {unprinted.Message ?? "Неизвестная оши |
| | | 145 | | } |
| | | 146 | | } |
| | | 147 | | |
| | 6 | 148 | | if (status?.Code == "completed" && !string.IsNullOrEmpty(response.FileUrl)) |
| | | 149 | | { |
| | 3 | 150 | | if (status.PrintedPostingsCount > 0) |
| | 3 | 151 | | return PackageLabelPollResult.Completed(response.FileUrl); |
| | | 152 | | |
| | 0 | 153 | | return PackageLabelPollResult.Failed( |
| | 0 | 154 | | $"Ошибка формирования этикетки: {response.Error?.Message ?? "Этикетка не была напечатана"}"); |
| | | 155 | | } |
| | | 156 | | |
| | 3 | 157 | | if (status?.Code == "error" || !string.IsNullOrEmpty(response.Error?.Message)) |
| | | 158 | | { |
| | 0 | 159 | | return PackageLabelPollResult.Failed( |
| | 0 | 160 | | $"Ошибка формирования этикетки: {response.Error?.Message ?? "Неизвестная ошибка"}"); |
| | | 161 | | } |
| | | 162 | | |
| | 3 | 163 | | return null; |
| | | 164 | | } |
| | | 165 | | } |