| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using AsiBackbone.Core.Audit; |
| | | 4 | | using AsiBackbone.Core.HostIntegration; |
| | | 5 | | |
| | | 6 | | namespace AsiBackbone.Samples.NcatAuditCompletionAdapter; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Maps a minimized NCAT audit-completion handoff into AsiBackbone governed execution evidence. |
| | | 10 | | /// </summary> |
| | | 11 | | /// <remarks> |
| | | 12 | | /// This reference adapter intentionally depends only on AsiBackbone Core and the source-neutral |
| | | 13 | | /// <see cref="NcatAuditCompletionHandoff" /> contract. A consuming host may translate its NCAT |
| | | 14 | | /// completion receipt or completion-outbox entry into that contract without coupling either core product. |
| | | 15 | | /// </remarks> |
| | | 16 | | public sealed class NcatAuditCompletionAdapter |
| | | 17 | | { |
| | | 18 | | private const string SourceCompletionEntryIdMetadataKey = "ncatCompletionEntryId"; |
| | | 19 | | private const string SourceAdapterMetadataKey = "completionAdapter"; |
| | | 20 | | private const string SourceAdapterMetadataValue = "NCAT"; |
| | | 21 | | private const string LifecycleEventPrefix = "ncat-completion-"; |
| | | 22 | | |
| | | 23 | | private readonly IAsiBackboneAuditResidueLifecycleStore lifecycleStore; |
| | | 24 | | private readonly INcatDecisionResidueResolver decisionResidueResolver; |
| | | 25 | | private readonly NcatAuditCompletionAdapterOptions options; |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// Initializes a new optional NCAT audit-completion adapter. |
| | | 29 | | /// </summary> |
| | 28 | 30 | | public NcatAuditCompletionAdapter( |
| | 28 | 31 | | IAsiBackboneAuditResidueLifecycleStore lifecycleStore, |
| | 28 | 32 | | INcatDecisionResidueResolver decisionResidueResolver, |
| | 28 | 33 | | NcatAuditCompletionAdapterOptions? options = null) |
| | | 34 | | { |
| | 28 | 35 | | this.lifecycleStore = lifecycleStore ?? throw new ArgumentNullException(nameof(lifecycleStore)); |
| | 28 | 36 | | this.decisionResidueResolver = decisionResidueResolver ?? throw new ArgumentNullException(nameof(decisionResidue |
| | 28 | 37 | | this.options = options ?? new NcatAuditCompletionAdapterOptions(); |
| | 28 | 38 | | this.options.Validate(); |
| | 28 | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Attempts to append the governed completion lifecycle event before the source entry is acknowledged. |
| | | 43 | | /// </summary> |
| | | 44 | | public async ValueTask<NcatAuditCompletionDeliveryResult> DeliverAsync( |
| | | 45 | | NcatAuditCompletionHandoff handoff, |
| | | 46 | | CancellationToken cancellationToken = default) |
| | | 47 | | { |
| | 30 | 48 | | ArgumentNullException.ThrowIfNull(handoff); |
| | 30 | 49 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 50 | | |
| | 30 | 51 | | NcatAuditCompletionDeliveryResult? validationFailure = ValidateHandoff(handoff); |
| | 30 | 52 | | if (validationFailure is not null) |
| | | 53 | | { |
| | 6 | 54 | | return validationFailure; |
| | | 55 | | } |
| | | 56 | | |
| | 24 | 57 | | if (!TryMapOutcome(handoff.PersistenceOutcome, out GovernedOperationPersistenceOutcome persistenceOutcome)) |
| | | 58 | | { |
| | 0 | 59 | | return Terminal("unsupported-persistence-outcome"); |
| | | 60 | | } |
| | | 61 | | |
| | 24 | 62 | | IAsiBackboneAuditResidue? residue = await decisionResidueResolver.ResolveAsync( |
| | 24 | 63 | | handoff.DecisionAuditRecordId!.Trim(), |
| | 24 | 64 | | NormalizeOptional(handoff.CorrelationId), |
| | 24 | 65 | | cancellationToken).ConfigureAwait(false); |
| | | 66 | | |
| | 24 | 67 | | if (residue is null) |
| | | 68 | | { |
| | 2 | 69 | | return new NcatAuditCompletionDeliveryResult( |
| | 2 | 70 | | NcatAuditCompletionDeliveryDisposition.Deferred, |
| | 2 | 71 | | "decision-residue-not-available"); |
| | | 72 | | } |
| | | 73 | | |
| | 22 | 74 | | NcatAuditCompletionDeliveryResult? correlationFailure = ValidateDecisionCorrelation(handoff, residue); |
| | 22 | 75 | | if (correlationFailure is not null) |
| | | 76 | | { |
| | 2 | 77 | | return correlationFailure; |
| | | 78 | | } |
| | | 79 | | |
| | | 80 | | GovernedOperationExecutionReceipt receipt; |
| | | 81 | | try |
| | | 82 | | { |
| | 20 | 83 | | receipt = GovernedOperationExecutionReceipt.Create( |
| | 20 | 84 | | operationExecutionId: handoff.OperationExecutionId!, |
| | 20 | 85 | | persistenceOutcome: persistenceOutcome, |
| | 20 | 86 | | executionAttemptId: handoff.ExecutionAttemptId, |
| | 20 | 87 | | mutationBatchId: handoff.MutationBatchId, |
| | 20 | 88 | | mutationRecordCount: handoff.AuditRecordCount, |
| | 20 | 89 | | mutationManifestHash: handoff.MutationManifestHash, |
| | 20 | 90 | | mutationManifestAlgorithm: handoff.MutationManifestAlgorithm, |
| | 20 | 91 | | completedUtc: handoff.CompletedUtc, |
| | 20 | 92 | | persistenceProvider: options.PersistenceProvider, |
| | 20 | 93 | | decisionAuditRecordId: handoff.DecisionAuditRecordId); |
| | 18 | 94 | | } |
| | 2 | 95 | | catch (ArgumentException exception) |
| | | 96 | | { |
| | 2 | 97 | | return Terminal("invalid-execution-receipt", exception.GetType().Name); |
| | | 98 | | } |
| | | 99 | | |
| | 18 | 100 | | string lifecycleEventId = CreateLifecycleEventId(handoff.CompletionEntryId); |
| | 18 | 101 | | IReadOnlyDictionary<string, string> metadata = new Dictionary<string, string>(StringComparer.Ordinal) |
| | 18 | 102 | | { |
| | 18 | 103 | | [SourceCompletionEntryIdMetadataKey] = handoff.CompletionEntryId.Trim(), |
| | 18 | 104 | | [SourceAdapterMetadataKey] = SourceAdapterMetadataValue |
| | 18 | 105 | | }; |
| | | 106 | | |
| | 18 | 107 | | AuditResidueLifecycleEvent lifecycleEvent = HostAccountabilityLifecycleEvent.FromExecutionReceipt( |
| | 18 | 108 | | residue, |
| | 18 | 109 | | receipt, |
| | 18 | 110 | | eventId: lifecycleEventId, |
| | 18 | 111 | | metadata: metadata); |
| | | 112 | | |
| | 18 | 113 | | AuditResidueLifecycleEvent? existing = await lifecycleStore.FindByEventIdAsync( |
| | 18 | 114 | | lifecycleEventId, |
| | 18 | 115 | | cancellationToken).ConfigureAwait(false); |
| | | 116 | | |
| | 18 | 117 | | if (existing is not null) |
| | | 118 | | { |
| | 2 | 119 | | return Equivalent(existing, lifecycleEvent) |
| | 2 | 120 | | ? new NcatAuditCompletionDeliveryResult( |
| | 2 | 121 | | NcatAuditCompletionDeliveryDisposition.Duplicate, |
| | 2 | 122 | | "completion-already-delivered", |
| | 2 | 123 | | lifecycleEventId, |
| | 2 | 124 | | receipt, |
| | 2 | 125 | | existing) |
| | 2 | 126 | | : Terminal("idempotency-conflict", lifecycleEventId: lifecycleEventId); |
| | | 127 | | } |
| | | 128 | | |
| | | 129 | | try |
| | | 130 | | { |
| | 16 | 131 | | AuditResidueLifecycleEvent appended = await lifecycleStore.AppendAsync( |
| | 16 | 132 | | lifecycleEvent, |
| | 16 | 133 | | cancellationToken).ConfigureAwait(false); |
| | | 134 | | |
| | 12 | 135 | | return new NcatAuditCompletionDeliveryResult( |
| | 12 | 136 | | NcatAuditCompletionDeliveryDisposition.Delivered, |
| | 12 | 137 | | "lifecycle-event-appended", |
| | 12 | 138 | | appended.EventId, |
| | 12 | 139 | | receipt, |
| | 12 | 140 | | appended); |
| | | 141 | | } |
| | 0 | 142 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 143 | | { |
| | 0 | 144 | | throw; |
| | | 145 | | } |
| | 4 | 146 | | catch (Exception exception) |
| | | 147 | | { |
| | 4 | 148 | | return PersistenceFailure(handoff, lifecycleEventId, receipt, lifecycleEvent, exception); |
| | | 149 | | } |
| | 30 | 150 | | } |
| | | 151 | | |
| | | 152 | | private static NcatAuditCompletionDeliveryResult? ValidateHandoff(NcatAuditCompletionHandoff handoff) |
| | | 153 | | { |
| | 30 | 154 | | return string.IsNullOrWhiteSpace(handoff.CompletionEntryId) |
| | 30 | 155 | | ? Terminal("completion-entry-id-required") |
| | 30 | 156 | | : string.IsNullOrWhiteSpace(handoff.OperationExecutionId) |
| | 30 | 157 | | ? Terminal("operation-execution-id-required") |
| | 30 | 158 | | : string.IsNullOrWhiteSpace(handoff.DecisionAuditRecordId) |
| | 30 | 159 | | ? Terminal("decision-audit-record-id-required") |
| | 30 | 160 | | : string.IsNullOrWhiteSpace(handoff.PersistenceOutcome) |
| | 30 | 161 | | ? Terminal("persistence-outcome-required") |
| | 30 | 162 | | : handoff.AuditRecordCount < 0 |
| | 30 | 163 | | ? Terminal("audit-record-count-invalid") |
| | 30 | 164 | | : handoff.DeliveryAttempt < 0 |
| | 30 | 165 | | ? Terminal("delivery-attempt-invalid") |
| | 30 | 166 | | : null; |
| | | 167 | | } |
| | | 168 | | |
| | | 169 | | private static NcatAuditCompletionDeliveryResult? ValidateDecisionCorrelation( |
| | | 170 | | NcatAuditCompletionHandoff handoff, |
| | | 171 | | IAsiBackboneAuditResidue residue) |
| | | 172 | | { |
| | 22 | 173 | | string? correlationId = NormalizeOptional(handoff.CorrelationId); |
| | 22 | 174 | | if (correlationId is not null && |
| | 22 | 175 | | !string.Equals(correlationId, residue.CorrelationId, StringComparison.Ordinal)) |
| | | 176 | | { |
| | 2 | 177 | | return Terminal("correlation-id-mismatch"); |
| | | 178 | | } |
| | | 179 | | |
| | 20 | 180 | | string? traceId = NormalizeOptional(handoff.TraceId); |
| | 20 | 181 | | return traceId is not null && |
| | 20 | 182 | | !string.Equals(traceId, residue.TraceId, StringComparison.Ordinal) |
| | 20 | 183 | | ? Terminal("trace-id-mismatch") |
| | 20 | 184 | | : null; |
| | | 185 | | } |
| | | 186 | | |
| | | 187 | | private NcatAuditCompletionDeliveryResult PersistenceFailure( |
| | | 188 | | NcatAuditCompletionHandoff handoff, |
| | | 189 | | string lifecycleEventId, |
| | | 190 | | GovernedOperationExecutionReceipt receipt, |
| | | 191 | | AuditResidueLifecycleEvent lifecycleEvent, |
| | | 192 | | Exception exception) |
| | | 193 | | { |
| | 4 | 194 | | bool deadLettered = options.DeadLetterAfterAttempts is int threshold && |
| | 4 | 195 | | handoff.DeliveryAttempt >= threshold; |
| | | 196 | | |
| | 4 | 197 | | return new NcatAuditCompletionDeliveryResult( |
| | 4 | 198 | | deadLettered |
| | 4 | 199 | | ? NcatAuditCompletionDeliveryDisposition.DeadLetter |
| | 4 | 200 | | : NcatAuditCompletionDeliveryDisposition.Retryable, |
| | 4 | 201 | | deadLettered |
| | 4 | 202 | | ? "lifecycle-persistence-dead-lettered" |
| | 4 | 203 | | : "lifecycle-persistence-failed", |
| | 4 | 204 | | lifecycleEventId, |
| | 4 | 205 | | receipt, |
| | 4 | 206 | | lifecycleEvent, |
| | 4 | 207 | | exception.GetType().Name); |
| | | 208 | | } |
| | | 209 | | |
| | | 210 | | private static bool TryMapOutcome( |
| | | 211 | | string sourceOutcome, |
| | | 212 | | out GovernedOperationPersistenceOutcome persistenceOutcome) |
| | | 213 | | { |
| | 24 | 214 | | string normalized = string.Concat(sourceOutcome |
| | 24 | 215 | | .Where(char.IsLetterOrDigit) |
| | 24 | 216 | | .Select(char.ToLowerInvariant)); |
| | | 217 | | |
| | 24 | 218 | | persistenceOutcome = normalized switch |
| | 24 | 219 | | { |
| | 16 | 220 | | "committed" => GovernedOperationPersistenceOutcome.Committed, |
| | 2 | 221 | | "failed" => GovernedOperationPersistenceOutcome.Failed, |
| | 2 | 222 | | "rolledback" => GovernedOperationPersistenceOutcome.RolledBack, |
| | 4 | 223 | | "completedwithoutmutation" or "nomutation" => GovernedOperationPersistenceOutcome.CompletedWithoutMutation, |
| | 0 | 224 | | _ => default |
| | 24 | 225 | | }; |
| | | 226 | | |
| | 24 | 227 | | return normalized is "committed" or "failed" or "rolledback" or "completedwithoutmutation" or "nomutation"; |
| | | 228 | | } |
| | | 229 | | |
| | | 230 | | private static string CreateLifecycleEventId(string completionEntryId) |
| | | 231 | | { |
| | 18 | 232 | | byte[] digest = SHA256.HashData(Encoding.UTF8.GetBytes(completionEntryId.Trim())); |
| | 18 | 233 | | return string.Concat(LifecycleEventPrefix, Convert.ToHexString(digest).ToLowerInvariant()); |
| | | 234 | | } |
| | | 235 | | |
| | | 236 | | private static bool Equivalent( |
| | | 237 | | AuditResidueLifecycleEvent existing, |
| | | 238 | | AuditResidueLifecycleEvent candidate) |
| | | 239 | | { |
| | 2 | 240 | | if (existing.Stage != candidate.Stage || |
| | 2 | 241 | | !string.Equals(existing.CorrelationId, candidate.CorrelationId, StringComparison.Ordinal) || |
| | 2 | 242 | | !string.Equals(existing.AuditResidueId, candidate.AuditResidueId, StringComparison.Ordinal) || |
| | 2 | 243 | | !string.Equals(existing.TraceId, candidate.TraceId, StringComparison.Ordinal) || |
| | 2 | 244 | | !string.Equals(existing.OperationName, candidate.OperationName, StringComparison.Ordinal) || |
| | 2 | 245 | | !string.Equals(existing.Outcome, candidate.Outcome, StringComparison.Ordinal)) |
| | | 246 | | { |
| | 0 | 247 | | return false; |
| | | 248 | | } |
| | | 249 | | |
| | 2 | 250 | | string[] keys = |
| | 2 | 251 | | [ |
| | 2 | 252 | | SourceCompletionEntryIdMetadataKey, |
| | 2 | 253 | | HostAccountabilityMetadataKeys.OperationExecutionId, |
| | 2 | 254 | | HostAccountabilityMetadataKeys.ExecutionAttemptId, |
| | 2 | 255 | | HostAccountabilityMetadataKeys.DecisionAuditRecordId, |
| | 2 | 256 | | HostAccountabilityMetadataKeys.PersistenceOutcome, |
| | 2 | 257 | | HostAccountabilityMetadataKeys.MutationBatchId, |
| | 2 | 258 | | HostAccountabilityMetadataKeys.MutationRecordCount, |
| | 2 | 259 | | HostAccountabilityMetadataKeys.MutationManifestHash, |
| | 2 | 260 | | HostAccountabilityMetadataKeys.MutationManifestAlgorithm |
| | 2 | 261 | | ]; |
| | | 262 | | |
| | 20 | 263 | | return keys.All(key => string.Equals( |
| | 20 | 264 | | GetMetadata(existing.Metadata, key), |
| | 20 | 265 | | GetMetadata(candidate.Metadata, key), |
| | 20 | 266 | | StringComparison.Ordinal)); |
| | | 267 | | } |
| | | 268 | | |
| | | 269 | | private static string? GetMetadata(IReadOnlyDictionary<string, string> metadata, string key) |
| | | 270 | | { |
| | 36 | 271 | | return metadata.TryGetValue(key, out string? value) ? value : null; |
| | | 272 | | } |
| | | 273 | | |
| | | 274 | | private static string? NormalizeOptional(string? value) |
| | | 275 | | { |
| | 66 | 276 | | return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); |
| | | 277 | | } |
| | | 278 | | |
| | | 279 | | private static NcatAuditCompletionDeliveryResult Terminal( |
| | | 280 | | string reasonCode, |
| | | 281 | | string? failureType = null, |
| | | 282 | | string? lifecycleEventId = null) |
| | | 283 | | { |
| | 10 | 284 | | return new NcatAuditCompletionDeliveryResult( |
| | 10 | 285 | | NcatAuditCompletionDeliveryDisposition.Terminal, |
| | 10 | 286 | | reasonCode, |
| | 10 | 287 | | lifecycleEventId, |
| | 10 | 288 | | FailureType: failureType); |
| | | 289 | | } |
| | | 290 | | } |