| | | 1 | | using Amazon.DynamoDBv2.DataModel; |
| | | 2 | | using Amazon.Runtime; |
| | | 3 | | using Amazon.DynamoDBv2.DocumentModel; |
| | | 4 | | using Amazon.DynamoDBv2.Model; |
| | | 5 | | using System.Runtime.CompilerServices; |
| | | 6 | | using ArturRios.Data.DynamoDb.Interfaces; |
| | | 7 | | using ArturRios.Output; |
| | | 8 | | using Microsoft.Extensions.Logging; |
| | | 9 | | |
| | | 10 | | namespace ArturRios.Data.DynamoDb.Repositories; |
| | | 11 | | |
| | | 12 | | /// <summary> |
| | | 13 | | /// DynamoDB implementation of <see cref="IAsyncDynamoRepository{T}" /> over the AWS object-persistence |
| | | 14 | | /// model (<see cref="IDynamoDBContext" />). Failures are returned as <see cref="DataOutput{T}" /> / |
| | | 15 | | /// <see cref="ProcessOutput" />; a <see cref="ConditionalCheckFailedException" /> (from |
| | | 16 | | /// <c>[DynamoDBVersion]</c> optimistic locking) becomes a concurrency error. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <typeparam name="T">The item type.</typeparam> |
| | | 19 | | /// <param name="context">The DynamoDB object-persistence context.</param> |
| | | 20 | | /// <param name="logger"> |
| | | 21 | | /// Optional logger. Envelopes never carry service text, so a failure is otherwise |
| | | 22 | | /// undiagnosable: supply a logger and the full exception, plus the item type and the |
| | | 23 | | /// repository method that failed, is written at <see cref="LogLevel.Error" />. Item contents |
| | | 24 | | /// and key values are never logged. Resolved from DI when logging is registered. |
| | | 25 | | /// </param> |
| | 22 | 26 | | public class DynamoRepository<T>(IDynamoDBContext context, ILogger<DynamoRepository<T>>? logger = null) |
| | | 27 | | : IAsyncDynamoRepository<T> where T : class |
| | | 28 | | { |
| | | 29 | | /// <summary>Message returned when an operation fails with no finer classification.</summary> |
| | | 30 | | protected const string OperationFailedMessage = "A data-access error occurred."; |
| | | 31 | | |
| | | 32 | | /// <summary>Message returned on an optimistic-concurrency conflict.</summary> |
| | | 33 | | protected const string ConcurrencyMessage = "Concurrency conflict: the item was modified by another process."; |
| | | 34 | | |
| | | 35 | | /// <summary>Message returned when the failure is transient and the operation may be retried.</summary> |
| | | 36 | | protected const string TransientMessage = "The data store is temporarily unavailable. Please retry."; |
| | | 37 | | |
| | | 38 | | /// <summary> |
| | | 39 | | /// The DynamoDB batch-write API rejects types with a <c>[DynamoDBVersion]</c> property unless |
| | | 40 | | /// version checking is explicitly skipped (batch writes have no per-item conditional-check |
| | | 41 | | /// support). Optimistic concurrency remains enforced on the single-item <see cref="SaveAsync" />/ |
| | | 42 | | /// <see cref="DeleteAsync" /> paths. |
| | | 43 | | /// </summary> |
| | 2 | 44 | | private static readonly BatchWriteConfig BatchSkipVersionCheckConfig = new() { SkipVersionCheck = true }; |
| | | 45 | | |
| | | 46 | | /// <inheritdoc /> |
| | | 47 | | public Task<DataOutput<T>> SaveAsync(T item, CancellationToken ct = default) => |
| | 28 | 48 | | GuardedAsync(async () => |
| | 28 | 49 | | { |
| | 28 | 50 | | await context.SaveAsync(item, ct).ConfigureAwait(false); |
| | 28 | 51 | | |
| | 22 | 52 | | return item; |
| | 50 | 53 | | }); |
| | | 54 | | |
| | | 55 | | /// <inheritdoc /> |
| | | 56 | | public Task<DataOutput<T?>> LoadAsync(object hashKey, CancellationToken ct = default) => |
| | 4 | 57 | | GuardedAsync<T?>(async () => await context.LoadAsync<T>(hashKey, ct).ConfigureAwait(false)); |
| | | 58 | | |
| | | 59 | | /// <inheritdoc /> |
| | | 60 | | public Task<DataOutput<T?>> LoadAsync(object hashKey, object rangeKey, CancellationToken ct = default) => |
| | 12 | 61 | | GuardedAsync<T?>(async () => await context.LoadAsync<T>(hashKey, rangeKey, ct).ConfigureAwait(false)); |
| | | 62 | | |
| | | 63 | | /// <inheritdoc /> |
| | | 64 | | public Task<ProcessOutput> DeleteAsync(T item, CancellationToken ct = default) => |
| | 8 | 65 | | GuardedProcessAsync(async () => await context.DeleteAsync(item, ct).ConfigureAwait(false)); |
| | | 66 | | |
| | | 67 | | /// <inheritdoc /> |
| | | 68 | | public Task<DataOutput<IEnumerable<T>>> QueryAsync(object hashKey, CancellationToken ct = default) => |
| | 4 | 69 | | GuardedAsync<IEnumerable<T>>(async () => await context.QueryAsync<T>(hashKey).GetRemainingAsync(ct).ConfigureAwa |
| | | 70 | | |
| | | 71 | | /// <inheritdoc /> |
| | | 72 | | public Task<DataOutput<IEnumerable<T>>> QueryAsync(object hashKey, QueryOperator op, |
| | | 73 | | IEnumerable<object> sortKeyValues, CancellationToken ct = default) => |
| | 2 | 74 | | GuardedAsync<IEnumerable<T>>(async () => |
| | 4 | 75 | | await context.QueryAsync<T>(hashKey, op, sortKeyValues).GetRemainingAsync(ct).ConfigureAwait(false)); |
| | | 76 | | |
| | | 77 | | /// <inheritdoc /> |
| | | 78 | | public Task<DataOutput<IEnumerable<T>>> ScanAsync(IEnumerable<ScanCondition> conditions, |
| | | 79 | | CancellationToken ct = default) => |
| | 4 | 80 | | GuardedAsync<IEnumerable<T>>(async () => await context.ScanAsync<T>(conditions).GetRemainingAsync(ct).ConfigureA |
| | | 81 | | |
| | | 82 | | /// <inheritdoc /> |
| | | 83 | | public Task<DataOutput<IEnumerable<T>>> SaveManyAsync(IEnumerable<T> items, CancellationToken ct = default) => |
| | 2 | 84 | | GuardedAsync<IEnumerable<T>>(async () => |
| | 2 | 85 | | { |
| | 2 | 86 | | var list = items.ToList(); |
| | 2 | 87 | | var batch = context.CreateBatchWrite<T>(BatchSkipVersionCheckConfig); |
| | 2 | 88 | | batch.AddPutItems(list); |
| | 2 | 89 | | await batch.ExecuteAsync(ct).ConfigureAwait(false); |
| | 2 | 90 | | return list; |
| | 4 | 91 | | }); |
| | | 92 | | |
| | | 93 | | /// <inheritdoc /> |
| | | 94 | | public Task<ProcessOutput> DeleteManyAsync(IEnumerable<T> items, CancellationToken ct = default) => |
| | 2 | 95 | | GuardedProcessAsync(async () => |
| | 2 | 96 | | { |
| | 2 | 97 | | var batch = context.CreateBatchWrite<T>(BatchSkipVersionCheckConfig); |
| | 2 | 98 | | batch.AddDeleteItems(items.ToList()); |
| | 2 | 99 | | await batch.ExecuteAsync(ct).ConfigureAwait(false); |
| | 4 | 100 | | }); |
| | | 101 | | |
| | | 102 | | /// <inheritdoc /> |
| | | 103 | | public Task<DataOutput<IEnumerable<T>>> |
| | | 104 | | LoadManyAsync(IEnumerable<object> hashKeys, CancellationToken ct = default) => |
| | 4 | 105 | | GuardedAsync<IEnumerable<T>>(async () => |
| | 4 | 106 | | { |
| | 4 | 107 | | var batch = context.CreateBatchGet<T>(); |
| | 24 | 108 | | foreach (var key in hashKeys) |
| | 4 | 109 | | { |
| | 8 | 110 | | batch.AddKey(key); |
| | 4 | 111 | | } |
| | 4 | 112 | | |
| | 4 | 113 | | await batch.ExecuteAsync(ct).ConfigureAwait(false); |
| | 4 | 114 | | |
| | 4 | 115 | | return batch.Results; |
| | 8 | 116 | | }); |
| | | 117 | | |
| | | 118 | | /// <summary>Runs an operation returning data, converting failures to envelope errors.</summary> |
| | | 119 | | /// <param name="operation">The operation to run.</param> |
| | | 120 | | /// <param name="operationName">The calling repository method, used as log context.</param> |
| | | 121 | | protected async Task<DataOutput<TResult>> GuardedAsync<TResult>(Func<Task<TResult>> operation, |
| | | 122 | | [CallerMemberName] string operationName = "") |
| | | 123 | | { |
| | | 124 | | try |
| | | 125 | | { |
| | 48 | 126 | | return DataOutput<TResult>.New.WithData(await operation().ConfigureAwait(false)); |
| | | 127 | | } |
| | 0 | 128 | | catch (OperationCanceledException) |
| | | 129 | | { |
| | 0 | 130 | | throw; |
| | | 131 | | } |
| | 6 | 132 | | catch (Exception ex) |
| | | 133 | | { |
| | 6 | 134 | | return Fail<TResult>(ex, operationName); |
| | | 135 | | } |
| | 48 | 136 | | } |
| | | 137 | | |
| | | 138 | | /// <summary>Runs an operation with no payload, converting failures to envelope errors.</summary> |
| | | 139 | | /// <param name="operation">The operation to run.</param> |
| | | 140 | | /// <param name="operationName">The calling repository method, used as log context.</param> |
| | | 141 | | protected async Task<ProcessOutput> GuardedProcessAsync(Func<Task> operation, |
| | | 142 | | [CallerMemberName] string operationName = "") |
| | | 143 | | { |
| | | 144 | | try |
| | | 145 | | { |
| | 6 | 146 | | await operation().ConfigureAwait(false); |
| | 6 | 147 | | return ProcessOutput.New; |
| | | 148 | | } |
| | 0 | 149 | | catch (OperationCanceledException) |
| | | 150 | | { |
| | 0 | 151 | | throw; |
| | | 152 | | } |
| | 0 | 153 | | catch (Exception ex) |
| | | 154 | | { |
| | 0 | 155 | | Log(ex, operationName); |
| | | 156 | | |
| | 0 | 157 | | return ex is ConditionalCheckFailedException |
| | 0 | 158 | | ? ProcessOutput.New.WithError(ConcurrencyMessage) |
| | 0 | 159 | | : ProcessOutput.New.WithError(Describe(ex)); |
| | | 160 | | } |
| | 6 | 161 | | } |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Logs the failure in full when a logger is configured, and maps it to a data-output error |
| | | 165 | | /// envelope. Service text names tables, indexes, keys and request ids, so it goes to the |
| | | 166 | | /// log and never to the caller. |
| | | 167 | | /// </summary> |
| | | 168 | | /// <param name="ex">The exception caught by a guard.</param> |
| | | 169 | | /// <param name="operationName">The repository method that failed, used as log context.</param> |
| | | 170 | | protected DataOutput<TResult> Fail<TResult>(Exception ex, string operationName = "") |
| | | 171 | | { |
| | 6 | 172 | | Log(ex, operationName); |
| | | 173 | | |
| | 6 | 174 | | return ex switch |
| | 6 | 175 | | { |
| | 2 | 176 | | ConditionalCheckFailedException => DataOutput<TResult>.New.WithError(ConcurrencyMessage), |
| | 4 | 177 | | _ => DataOutput<TResult>.New.WithError(Describe(ex)) |
| | 6 | 178 | | }; |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | private void Log(Exception ex, string operationName) |
| | | 182 | | { |
| | | 183 | | // A conditional-check failure is the expected outcome of optimistic locking, not an |
| | | 184 | | // operational fault: logging it at Error would fill the log with routine contention. |
| | 6 | 185 | | var level = ex is ConditionalCheckFailedException ? LogLevel.Debug : LogLevel.Error; |
| | | 186 | | |
| | 6 | 187 | | logger?.Log(level, ex, "DynamoDB operation failed. Item: {Item}, operation: {Operation}", |
| | 6 | 188 | | typeof(T).Name, operationName); |
| | 2 | 189 | | } |
| | | 190 | | |
| | | 191 | | /// <summary>Classifies a non-concurrency failure into a caller-safe message.</summary> |
| | | 192 | | protected static string Describe(Exception ex) |
| | | 193 | | { |
| | 24 | 194 | | for (var current = ex; current is not null; current = current.InnerException) |
| | | 195 | | { |
| | 8 | 196 | | if (current is TimeoutException || IsRetryableServiceFault(current)) |
| | | 197 | | { |
| | 0 | 198 | | return TransientMessage; |
| | | 199 | | } |
| | | 200 | | } |
| | | 201 | | |
| | 4 | 202 | | return OperationFailedMessage; |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | // Throttling and server faults reach the caller under several exception types (and as a plain |
| | | 206 | | // AmazonDynamoDBException with a throttling error code), so classify on what the SDK reports |
| | | 207 | | // about the response rather than on the exception type alone. |
| | | 208 | | private static bool IsRetryableServiceFault(Exception ex) |
| | | 209 | | { |
| | 8 | 210 | | if (ex is ProvisionedThroughputExceededException or RequestLimitExceededException |
| | 8 | 211 | | or InternalServerErrorException) |
| | | 212 | | { |
| | 0 | 213 | | return true; |
| | | 214 | | } |
| | | 215 | | |
| | 8 | 216 | | return ex is AmazonServiceException service && |
| | 8 | 217 | | (service.Retryable is not null || |
| | 8 | 218 | | (int)service.StatusCode == 429 || |
| | 8 | 219 | | (int)service.StatusCode >= 500); |
| | | 220 | | } |
| | | 221 | | } |