|
| 1 | +using System.Collections.Concurrent; |
| 2 | +using System.Text.Json.Nodes; |
| 3 | +using MemNet.MemoryService.Core; |
| 4 | +using MemNet.MemoryService.Infrastructure; |
| 5 | +using Microsoft.Extensions.Logging.Abstractions; |
| 6 | + |
| 7 | +namespace MemNet.MemoryService.UnitTests; |
| 8 | + |
| 9 | +public class LifecycleAndReplayServiceTests |
| 10 | +{ |
| 11 | + [Fact] |
| 12 | + public async Task ApplyRetention_NegativeEventsDays_Returns400() |
| 13 | + { |
| 14 | + var service = new DataLifecycleService(new FakeMaintenanceStore()); |
| 15 | + |
| 16 | + var ex = await Assert.ThrowsAsync<ApiException>( |
| 17 | + () => service.ApplyRetentionAsync( |
| 18 | + "tenant", |
| 19 | + "user", |
| 20 | + new ApplyRetentionRequest( |
| 21 | + EventsDays: -1, |
| 22 | + AuditDays: 30, |
| 23 | + SnapshotsDays: 30, |
| 24 | + AsOfUtc: DateTimeOffset.UtcNow))); |
| 25 | + |
| 26 | + Assert.Equal(400, ex.StatusCode); |
| 27 | + Assert.Equal("INVALID_RETENTION_VALUE", ex.Code); |
| 28 | + } |
| 29 | + |
| 30 | + [Fact] |
| 31 | + public async Task ApplyRetention_UsesUtcAsOfAndForwardsRules() |
| 32 | + { |
| 33 | + var store = new FakeMaintenanceStore(); |
| 34 | + var service = new DataLifecycleService(store); |
| 35 | + var asOfWithOffset = new DateTimeOffset(2026, 1, 2, 8, 30, 0, TimeSpan.FromHours(5)); |
| 36 | + |
| 37 | + await service.ApplyRetentionAsync( |
| 38 | + "tenant-a", |
| 39 | + "user-a", |
| 40 | + new ApplyRetentionRequest( |
| 41 | + EventsDays: 365, |
| 42 | + AuditDays: 90, |
| 43 | + SnapshotsDays: 30, |
| 44 | + AsOfUtc: asOfWithOffset)); |
| 45 | + |
| 46 | + Assert.Equal("tenant-a", store.LastTenantId); |
| 47 | + Assert.Equal("user-a", store.LastUserId); |
| 48 | + Assert.Equal(new RetentionRules(30, 365, 90), store.LastRules); |
| 49 | + Assert.Equal(asOfWithOffset.ToUniversalTime(), store.LastAsOfUtc); |
| 50 | + } |
| 51 | + |
| 52 | + [Fact] |
| 53 | + public async Task ForgetUser_ForwardsIdentifiersToStore() |
| 54 | + { |
| 55 | + var store = new FakeMaintenanceStore(); |
| 56 | + var service = new DataLifecycleService(store); |
| 57 | + |
| 58 | + var result = await service.ForgetUserAsync("tenant-z", "user-z"); |
| 59 | + |
| 60 | + Assert.Equal("tenant-z", store.LastTenantId); |
| 61 | + Assert.Equal("user-z", store.LastUserId); |
| 62 | + Assert.Equal(3, result.DocumentsDeleted); |
| 63 | + } |
| 64 | + |
| 65 | + [Fact] |
| 66 | + public async Task ApplyReplayPatchAsync_UsesReplayPayloadAndReplayEtag() |
| 67 | + { |
| 68 | + var documentStore = new FakeDocumentStore(); |
| 69 | + var auditStore = new RecordingAuditStore(); |
| 70 | + var coordinator = new MemoryCoordinator( |
| 71 | + documentStore, |
| 72 | + new FakeEventStore(), |
| 73 | + auditStore, |
| 74 | + NullLogger<MemoryCoordinator>.Instance); |
| 75 | + |
| 76 | + var key = new DocumentKey("tenant", "user", "user/profile.json"); |
| 77 | + var seeded = await documentStore.UpsertAsync(key, CreateEnvelope("before"), "*"); |
| 78 | + |
| 79 | + var replay = new ReplayPatchRecord( |
| 80 | + ReplayId: "rpl_1", |
| 81 | + TargetBindingId: "binding_1", |
| 82 | + TargetPath: key.Path, |
| 83 | + BaseETag: seeded.ETag, |
| 84 | + Ops: |
| 85 | + [ |
| 86 | + new PatchOperation("replace", "/content/text", JsonValue.Create("after")) |
| 87 | + ], |
| 88 | + Evidence: new JsonObject { ["source"] = "replay" }); |
| 89 | + |
| 90 | + var replayService = new ReplayService(coordinator); |
| 91 | + var response = await replayService.ApplyReplayPatchAsync(key, replay, actor: "replay-agent"); |
| 92 | + |
| 93 | + Assert.Equal("after", response.Document.Content["text"]?.GetValue<string>()); |
| 94 | + Assert.Single(auditStore.Records); |
| 95 | + Assert.Equal("replay_update", auditStore.Records[0].Reason); |
| 96 | + Assert.Equal(seeded.ETag, auditStore.Records[0].PreviousETag); |
| 97 | + } |
| 98 | + |
| 99 | + private static DocumentEnvelope CreateEnvelope(string text) |
| 100 | + { |
| 101 | + var now = DateTimeOffset.UtcNow; |
| 102 | + return new DocumentEnvelope( |
| 103 | + DocId: $"doc-{Guid.NewGuid():N}", |
| 104 | + SchemaId: "memnet.file", |
| 105 | + SchemaVersion: "1.0.0", |
| 106 | + CreatedAt: now, |
| 107 | + UpdatedAt: now, |
| 108 | + UpdatedBy: "seed", |
| 109 | + Content: new JsonObject { ["text"] = text }); |
| 110 | + } |
| 111 | + |
| 112 | + private sealed class FakeMaintenanceStore : IUserDataMaintenanceStore |
| 113 | + { |
| 114 | + public string? LastTenantId { get; private set; } |
| 115 | + public string? LastUserId { get; private set; } |
| 116 | + public RetentionRules? LastRules { get; private set; } |
| 117 | + public DateTimeOffset? LastAsOfUtc { get; private set; } |
| 118 | + |
| 119 | + public Task<ForgetUserResult> ForgetUserAsync(string tenantId, string userId, CancellationToken cancellationToken = default) |
| 120 | + { |
| 121 | + LastTenantId = tenantId; |
| 122 | + LastUserId = userId; |
| 123 | + return Task.FromResult(new ForgetUserResult(3, 2, 1, 0, 0)); |
| 124 | + } |
| 125 | + |
| 126 | + public Task<RetentionSweepResult> ApplyRetentionAsync( |
| 127 | + string tenantId, |
| 128 | + string userId, |
| 129 | + RetentionRules rules, |
| 130 | + DateTimeOffset asOfUtc, |
| 131 | + CancellationToken cancellationToken = default) |
| 132 | + { |
| 133 | + LastTenantId = tenantId; |
| 134 | + LastUserId = userId; |
| 135 | + LastRules = rules; |
| 136 | + LastAsOfUtc = asOfUtc; |
| 137 | + |
| 138 | + return Task.FromResult(new RetentionSweepResult(1, 1, 1, 0, asOfUtc, asOfUtc, asOfUtc)); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + private sealed class FakeDocumentStore : IDocumentStore |
| 143 | + { |
| 144 | + private readonly ConcurrentDictionary<string, DocumentRecord> _records = new(StringComparer.Ordinal); |
| 145 | + private int _version; |
| 146 | + |
| 147 | + public Task<DocumentRecord?> GetAsync(DocumentKey key, CancellationToken cancellationToken = default) |
| 148 | + { |
| 149 | + _records.TryGetValue(Key(key), out var record); |
| 150 | + return Task.FromResult(record); |
| 151 | + } |
| 152 | + |
| 153 | + public Task<DocumentRecord> UpsertAsync(DocumentKey key, DocumentEnvelope envelope, string? ifMatch, CancellationToken cancellationToken = default) |
| 154 | + { |
| 155 | + var id = Key(key); |
| 156 | + if (_records.TryGetValue(id, out var existing)) |
| 157 | + { |
| 158 | + if (!string.Equals(existing.ETag, ifMatch, StringComparison.Ordinal)) |
| 159 | + { |
| 160 | + throw new ApiException(412, "ETAG_MISMATCH", "stale"); |
| 161 | + } |
| 162 | + } |
| 163 | + else if (!string.IsNullOrWhiteSpace(ifMatch) && ifMatch != "*") |
| 164 | + { |
| 165 | + throw new ApiException(412, "ETAG_MISMATCH", "missing"); |
| 166 | + } |
| 167 | + |
| 168 | + var etag = $"\"v{Interlocked.Increment(ref _version)}\""; |
| 169 | + var stored = new DocumentRecord(envelope, etag); |
| 170 | + _records[id] = stored; |
| 171 | + return Task.FromResult(stored); |
| 172 | + } |
| 173 | + |
| 174 | + public Task<IReadOnlyList<FileListItem>> ListAsync(string tenantId, string userId, string? prefix, int limit, CancellationToken cancellationToken = default) |
| 175 | + => Task.FromResult<IReadOnlyList<FileListItem>>(Array.Empty<FileListItem>()); |
| 176 | + |
| 177 | + public Task<bool> ExistsAsync(DocumentKey key, CancellationToken cancellationToken = default) |
| 178 | + => Task.FromResult(_records.ContainsKey(Key(key))); |
| 179 | + |
| 180 | + private static string Key(DocumentKey key) => $"{key.TenantId}/{key.UserId}/{key.Path}"; |
| 181 | + } |
| 182 | + |
| 183 | + private sealed class FakeEventStore : IEventStore |
| 184 | + { |
| 185 | + public Task WriteAsync(EventDigest digest, CancellationToken cancellationToken = default) => Task.CompletedTask; |
| 186 | + |
| 187 | + public Task<IReadOnlyList<EventDigest>> QueryAsync(string tenantId, string userId, EventSearchRequest request, CancellationToken cancellationToken = default) |
| 188 | + => Task.FromResult<IReadOnlyList<EventDigest>>(Array.Empty<EventDigest>()); |
| 189 | + } |
| 190 | + |
| 191 | + private sealed class RecordingAuditStore : IAuditStore |
| 192 | + { |
| 193 | + public List<AuditRecord> Records { get; } = []; |
| 194 | + |
| 195 | + public Task WriteAsync(AuditRecord record, CancellationToken cancellationToken = default) |
| 196 | + { |
| 197 | + Records.Add(record); |
| 198 | + return Task.CompletedTask; |
| 199 | + } |
| 200 | + } |
| 201 | +} |
0 commit comments