using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Server.Configuration; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using ClassNotify.Shared.Contracts; using ClassNotify.Shared.Enums; using ClassNotify.Shared.Models; using ClassNotify.Shared.Services; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Identity; using Npgsql; using ClassNotify.Server.Services; namespace ClassNotify.DeliveryTests; public class CustomWebApplicationFactory : WebApplicationFactory { public const string TestJwtKey = "THIS_IS_A_VERY_LONG_TEST_SIGNING_KEY_EXCEEDING_SIXTY_FOUR_BYTES_IN_LENGTH_FOR_DELIVERY_TESTS!"; public const string TestIssuer = "ClassNotify.Server"; public const string TestAudience = "ClassNotify.Clients"; private readonly string _testDbName; public CustomWebApplicationFactory(string? dbName = null) { _testDbName = dbName ?? ("classnotify_delivery_test_" + Guid.NewGuid().ToString("N")); } public string DbName => _testDbName; protected override void ConfigureWebHost(IWebHostBuilder builder) { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir != null && !File.Exists(Path.Combine(dir.FullName, "ClassNotify.sln"))) { dir = dir.Parent; } var rootDir = dir?.FullName ?? Directory.GetCurrentDirectory(); var serverPath = Path.Combine(rootDir, "src", "Server", "ClassNotify.Server"); builder.UseContentRoot(serverPath); builder.UseEnvironment("Development"); builder.ConfigureAppConfiguration((context, config) => { config.AddInMemoryCollection(new Dictionary { ["RateLimit:AuthPermitLimit"] = "100", ["RateLimit:ActivationPermitLimit"] = "100", ["RateLimit:SendPermitLimit"] = "100", ["Jwt:SigningKey"] = TestJwtKey, ["Jwt:Issuer"] = TestIssuer, ["Jwt:Audience"] = TestAudience, ["Jwt:LifetimeDays"] = "14", ["ConnectionStrings:DefaultConnection"] = "Host=127.0.0.1;Database=classnotify_test;Username=postgres;" }); }); builder.ConfigureServices(services => { var dbDescriptors = services.Where(d => d.ServiceType == typeof(DbContextOptions) || d.ServiceType == typeof(ClassNotifyDbContext)).ToList(); foreach (var d in dbDescriptors) { services.Remove(d); } services.AddDbContext(options => { options.UseInMemoryDatabase(_testDbName); }); }); } public static string CreateTeacherJwt(IServiceProvider services, string userId, string userName, string tenantId) { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(TestJwtKey); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, userId), new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Role, "Teacher"), new Claim("tenant_id", tenantId), new Claim("token_version", "1") }), Issuer = TestIssuer, Audience = TestAudience, Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } } public class Program { private static int _passedTests = 0; private static int _failedTests = 0; public static async Task Main(string[] args) { Console.WriteLine("=========================================================="); Console.WriteLine(" ClassNotify P1 Batch 9: Delivery & TTL Test Suite "); Console.WriteLine("=========================================================="); using var factory = new CustomWebApplicationFactory(); var client = factory.CreateClient(); await SeedBaselineDataAsync(factory); await RunTestAsync("TTL: Business Policy (Call=10m, Notice=60m, Urgent=24h, Custom, Boundary Guard)", () => Test_BusinessTTL_Policy(factory, client)); await RunTestAsync("Online: Immediate Delivery & End-to-End ACK Receipt Update", () => Test_Online_ImmediateDelivery_And_Ack(factory, client)); await RunTestAsync("Offline: Reconnect Catch-up for Pending Sent Notifications", () => Test_Offline_Device_Receives_Catchup_On_Reconnect(factory, client)); await RunTestAsync("Chronological: Multiple Offline Notifications Dispatched In CreatedAt Order", () => Test_Multiple_Offline_Notifications_Chronological_Order(factory, client)); await RunTestAsync("TTL Enforcement: Expired Notifications Strictly Suppressed & Marked Expired", () => Test_Expired_Notifications_Strictly_Suppressed(factory)); await RunTestAsync("Idempotency: Acknowledged Notifications Never Repeated On Reconnect", () => Test_Already_Acknowledged_Not_Repeated(factory, client)); RunTest("Client Deduplication: At-Least-Once Delivery With Atomic Client Idempotent Duplicate Suppression", Test_Client_Notification_Deduplicator_Actual_Class); await RunTestAsync("Isolation: Multi-Tenant & Multi-Classroom Scope Isolation On Catch-up", () => Test_MultiTenant_Classroom_Isolation_On_Catchup(factory, client)); await RunTestAsync("Legacy TTL Safety: Legacy NULL ExpiresAt Never Delivered and Automatically Marked Expired", () => Test_Legacy_Null_ExpiresAt_Never_Delivered_And_Marked_Expired(factory)); await RunTestAsync("Service Resilience: Transient WPF UI Latency Does Not Drop Message and Delivers On Connect", () => Test_Transient_Wpf_Unavailable_Does_Not_Drop_Message_And_Delivers_On_Connect(factory, client)); await RunTestAsync("Pipe Mid-Send Race: Broken Pipe On Send Fails-Back To Buffer and Recovers On Next Connect", Test_Pipe_Send_Returns_False_Mid_Send_Recovers_And_Delivers_On_Next_Connect); await RunTestAsync("History Aggregation: Notification History Correctly Identifies Expired and Timeout Receipts", () => Test_History_Aggregation_Recognizes_Expired_And_Timeout(factory, client)); RunTest("EF Migration Verification: Batch8 to Batch9 Schema Upgrade, Backfill Operations, and Model Snapshot", Test_EFCore_Migration_Batch8_To_Batch9_Upgrade); await RunTestAsync("Real PostgreSQL Migration: Batch8 to Batch9 Real DB Upgrade, Indexes, Backfill, and Catch-up", Test_PostgreSQL_Batch8_To_Batch9_Migration_Integration_With_Legacy_Data); await RunTestAsync("Persistence & Restart: Pending Catch-up Survives Server Shutdown and Resumes On Restart", () => Test_Server_Restart_Pending_Notification_Survives(factory)); Console.WriteLine("\n=========================================================="); Console.WriteLine($" Test Results: {_passedTests} Passed, {_failedTests} Failed"); Console.WriteLine("=========================================================="); return _failedTests == 0 ? 0 : 1; } private static async Task RunTestAsync(string name, Func testAction) { try { await testAction(); Console.WriteLine($"[PASS] {name}"); _passedTests++; } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"[FAIL] {name}"); Console.WriteLine($" Exception: {ex.Message}"); Console.WriteLine($" Stack: {ex.StackTrace}"); Console.ResetColor(); _failedTests++; } } private static void RunTest(string name, Action testAction) { try { testAction(); Console.WriteLine($"[PASS] {name}"); _passedTests++; } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"[FAIL] {name}"); Console.WriteLine($" Exception: {ex.Message}"); Console.ResetColor(); _failedTests++; } } private static async Task SeedBaselineDataAsync(CustomWebApplicationFactory factory) { using var scope = factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); await db.Database.EnsureCreatedAsync(); var rawToken = "dtoken_bj4_801_secret"; var tokenHash = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(rawToken))); // Ensure devices exist for t_beijing_no4 var d1 = await db.Devices.FirstOrDefaultAsync(d => d.Id == "dev_bj4_801"); if (d1 == null) { db.Devices.Add(new Device { Id = "dev_bj4_801", TenantId = "t_beijing_no4", ClassroomId = "cls_801", DeviceTokenHash = tokenHash, Hostname = "PC-801", IsActive = true, CreatedAt = DateTimeOffset.UtcNow }); } else { d1.DeviceTokenHash = tokenHash; d1.IsActive = true; } var d2 = await db.Devices.FirstOrDefaultAsync(d => d.Id == "dev_bj4_802"); if (d2 == null) { db.Devices.Add(new Device { Id = "dev_bj4_802", TenantId = "t_beijing_no4", ClassroomId = "cls_802", DeviceTokenHash = tokenHash, Hostname = "PC-802", IsActive = true, CreatedAt = DateTimeOffset.UtcNow }); } else { d2.DeviceTokenHash = tokenHash; d2.IsActive = true; } var d3 = await db.Devices.FirstOrDefaultAsync(d => d.Id == "dev_sh1_801"); if (d3 == null) { db.Devices.Add(new Device { Id = "dev_sh1_801", TenantId = "t_shanghai_high", ClassroomId = "cls_801", DeviceTokenHash = tokenHash, Hostname = "PC-SH801", IsActive = true, CreatedAt = DateTimeOffset.UtcNow }); } else { d3.DeviceTokenHash = tokenHash; d3.IsActive = true; } var teacher = await db.Users.FirstOrDefaultAsync(u => u.Id == "u_teacher_1"); if (teacher == null) { db.Users.Add(new User { Id = "u_teacher_1", Username = "teacher_1", PasswordHash = "dummy_hash", FullName = "张老师", Role = "Teacher", TenantId = "t_beijing_no4", IsLocked = false, TokenVersion = 1, CreatedAt = DateTimeOffset.UtcNow }); } else { teacher.IsLocked = false; teacher.TokenVersion = 1; } await db.SaveChangesAsync(); } private static HubConnection CreateDeviceHubConnection(CustomWebApplicationFactory factory, string deviceId, string rawToken) { var url = $"http://localhost/hubs/device?device_id={Uri.EscapeDataString(deviceId)}&device_token={Uri.EscapeDataString(rawToken)}"; return new HubConnectionBuilder() .WithUrl(url, options => { options.HttpMessageHandlerFactory = _ => factory.Server.CreateHandler(); options.Headers.Add("X-Device-Id", deviceId); options.Headers.Add("X-Device-Token", rawToken); options.Transports = HttpTransportType.LongPolling; }) .Build(); } #region Tests private static async Task Test_BusinessTTL_Policy(CustomWebApplicationFactory factory, HttpClient client) { var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "张老师", "t_beijing_no4"); // 1. Call notification -> ExpiresAt should be approx CreatedAt + 10 min var callDto = new NotificationDto { ClassId = "cls_801", Title = "🔔 办公室谈话", Message = "请小明下课后来办公室", Type = NotificationType.Call }; var reqCall = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); reqCall.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); reqCall.Content = JsonContent.Create(callDto); var resCall = await client.SendAsync(reqCall); if (resCall.StatusCode != HttpStatusCode.OK) throw new Exception($"Send Call returned {resCall.StatusCode}"); var callJson = await resCall.Content.ReadFromJsonAsync(); var callMsgId = callJson.GetProperty("messageId").GetString()!; // 2. Notice notification -> ExpiresAt should be approx CreatedAt + 60 min var noticeDto = new NotificationDto { ClassId = "cls_801", Title = "📢 卫生检查", Message = "大扫除公告", Type = NotificationType.Notice }; var reqNotice = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); reqNotice.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); reqNotice.Content = JsonContent.Create(noticeDto); var resNotice = await client.SendAsync(reqNotice); if (resNotice.StatusCode != HttpStatusCode.OK) throw new Exception($"Send Notice returned {resNotice.StatusCode}"); var noticeJson = await resNotice.Content.ReadFromJsonAsync(); var noticeMsgId = noticeJson.GetProperty("messageId").GetString()!; // 3. Urgent notification -> ExpiresAt should be approx CreatedAt + 24 hours var urgentDto = new NotificationDto { ClassId = "cls_801", Title = "⚠️ 紧急疏散", Message = "消防演习", Type = NotificationType.Urgent }; var reqUrgent = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); reqUrgent.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); reqUrgent.Content = JsonContent.Create(urgentDto); var resUrgent = await client.SendAsync(reqUrgent); if (resUrgent.StatusCode != HttpStatusCode.OK) throw new Exception($"Send Urgent returned {resUrgent.StatusCode}"); var urgentJson = await resUrgent.Content.ReadFromJsonAsync(); var urgentMsgId = urgentJson.GetProperty("messageId").GetString()!; // Verify DB values using var scope = factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var notifCall = await db.Notifications.FirstAsync(n => n.Id == callMsgId); var callTtlMinutes = (notifCall.ExpiresAt!.Value - notifCall.CreatedAt).TotalMinutes; if (callTtlMinutes < 9.9 || callTtlMinutes > 10.1) throw new Exception($"Call TTL expected 10 min, got {callTtlMinutes:F2} min"); var notifNotice = await db.Notifications.FirstAsync(n => n.Id == noticeMsgId); var noticeTtlMinutes = (notifNotice.ExpiresAt!.Value - notifNotice.CreatedAt).TotalMinutes; if (noticeTtlMinutes < 59.9 || noticeTtlMinutes > 60.1) throw new Exception($"Notice TTL expected 60 min, got {noticeTtlMinutes:F2} min"); var notifUrgent = await db.Notifications.FirstAsync(n => n.Id == urgentMsgId); var urgentTtlHours = (notifUrgent.ExpiresAt!.Value - notifUrgent.CreatedAt).TotalHours; if (urgentTtlHours < 23.9 || urgentTtlHours > 24.1) throw new Exception($"Urgent TTL expected 24 hours, got {urgentTtlHours:F2} hours"); // 4. Past ExpiresAt -> Should be rejected with 400 BadRequest var pastDto = new NotificationDto { ClassId = "cls_801", Title = "Test", Message = "Expired", ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-5) }; var reqPast = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); reqPast.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); reqPast.Content = JsonContent.Create(pastDto); var resPast = await client.SendAsync(reqPast); if (resPast.StatusCode != HttpStatusCode.BadRequest) throw new Exception($"Past ExpiresAt expected 400 BadRequest, got {resPast.StatusCode}"); // 5. Exceeding 7 days -> Capped at 7 days var farDto = new NotificationDto { ClassId = "cls_801", Title = "Test", Message = "Far future", ExpiresAt = DateTimeOffset.UtcNow.AddDays(30) }; var reqFar = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); reqFar.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); reqFar.Content = JsonContent.Create(farDto); var resFar = await client.SendAsync(reqFar); if (resFar.StatusCode != HttpStatusCode.OK) throw new Exception($"Far ExpiresAt expected 200 OK, got {resFar.StatusCode}"); var farJson = await resFar.Content.ReadFromJsonAsync(); var farMsgId = farJson.GetProperty("messageId").GetString()!; var notifFar = await db.Notifications.FirstAsync(n => n.Id == farMsgId); var farDays = (notifFar.ExpiresAt!.Value - notifFar.CreatedAt).TotalDays; if (farDays < 6.9 || farDays > 7.1) throw new Exception($"Far TTL expected to be capped at 7 days, got {farDays:F2} days"); } private static async Task Test_Online_ImmediateDelivery_And_Ack(CustomWebApplicationFactory factory, HttpClient client) { var deviceConn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); var receivedNotifs = new List(); deviceConn.On("ReceiveNotification", n => { receivedNotifs.Add(n); }); await deviceConn.StartAsync(); try { var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "李老师", "t_beijing_no4"); var notifDto = new NotificationDto { ClassId = "cls_801", Title = "实时测试", Message = "在线即时下发测试内容", Type = NotificationType.Call }; var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); req.Content = JsonContent.Create(notifDto); var res = await client.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"Send failed: {res.StatusCode}"); var resJson = await res.Content.ReadFromJsonAsync(); var msgId = resJson.GetProperty("messageId").GetString()!; // Wait up to 3s for SignalR delivery var timeout = DateTime.UtcNow.AddSeconds(3); while (!receivedNotifs.Any(n => n.Id == msgId) && DateTime.UtcNow < timeout) { await Task.Delay(50); } var received = receivedNotifs.FirstOrDefault(n => n.Id == msgId); if (received == null) throw new Exception($"Online device did not receive notification {msgId} via SignalR"); // Send Delivered ACK await deviceConn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = msgId, ClassId = "cls_801", Status = AckStatus.Delivered, Timestamp = DateTimeOffset.UtcNow }); // Send Acknowledged ACK await deviceConn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = msgId, ClassId = "cls_801", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); await Task.Delay(200); // Verify DB receipt state using var scope = factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var rcpt = await db.NotificationReceipts.FirstOrDefaultAsync(r => r.NotificationId == msgId && r.DeviceId == "dev_bj4_801"); if (rcpt == null) throw new Exception("Receipt was not created in DB"); if (rcpt.Status != "Acknowledged") throw new Exception($"Receipt status expected 'Acknowledged', got '{rcpt.Status}'"); if (!rcpt.AcknowledgedAt.HasValue) throw new Exception("AcknowledgedAt was not stamped on receipt"); } finally { await deviceConn.StopAsync(); } } private static async Task Test_Offline_Device_Receives_Catchup_On_Reconnect(CustomWebApplicationFactory factory, HttpClient client) { // 1. Device is OFFLINE. Teacher sends notification. var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "王老师", "t_beijing_no4"); var notifDto = new NotificationDto { ClassId = "cls_801", Title = "离线补发测试", Message = "这是一条在设备关机离线期间发送的通知", Type = NotificationType.Call }; var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); req.Content = JsonContent.Create(notifDto); var res = await client.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"Send failed: {res.StatusCode}"); var resJson = await res.Content.ReadFromJsonAsync(); var msgId = resJson.GetProperty("messageId").GetString()!; // Confirm DB receipt exists in "Sent" state using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var initialRcpt = await db.NotificationReceipts.FirstOrDefaultAsync(r => r.NotificationId == msgId && r.DeviceId == "dev_bj4_801"); if (initialRcpt == null || initialRcpt.Status != "Sent") throw new Exception($"Initial receipt state should be 'Sent', got '{initialRcpt?.Status}'"); } // 2. Device comes ONLINE (connects to DeviceHub) var deviceConn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); var caughtUpNotifs = new List(); deviceConn.On("ReceiveNotification", n => { caughtUpNotifs.Add(n); }); await deviceConn.StartAsync(); try { // Wait up to 3s for catch-up var timeout = DateTime.UtcNow.AddSeconds(3); while (caughtUpNotifs.All(n => n.Id != msgId) && DateTime.UtcNow < timeout) { await Task.Delay(50); } var matching = caughtUpNotifs.FirstOrDefault(n => n.Id == msgId); if (matching == null) throw new Exception("Offline device did not receive catch-up notification on reconnect"); if (matching.Message != notifDto.Message) throw new Exception($"Catch-up message content mismatch: expected '{notifDto.Message}', got '{matching.Message}'"); // 3. Device acks catch-up await deviceConn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = msgId, ClassId = "cls_801", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); await Task.Delay(200); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var updatedRcpt = await db.NotificationReceipts.FirstAsync(r => r.NotificationId == msgId && r.DeviceId == "dev_bj4_801"); if (updatedRcpt.Status != "Acknowledged") throw new Exception($"Receipt status should be 'Acknowledged', got '{updatedRcpt.Status}'"); } } finally { await deviceConn.StopAsync(); } } private static async Task Test_Multiple_Offline_Notifications_Chronological_Order(CustomWebApplicationFactory factory, HttpClient client) { var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "赵老师", "t_beijing_no4"); // Send 3 notifications sequentially var msgIds = new List(); for (int i = 1; i <= 3; i++) { var notif = new NotificationDto { ClassId = "cls_801", Title = $"时序测试 #{i}", Message = $"消息序号第 {i} 条", Type = NotificationType.Call }; var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); req.Content = JsonContent.Create(notif); var res = await client.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"Send failed: {res.StatusCode}"); var json = await res.Content.ReadFromJsonAsync(); msgIds.Add(json.GetProperty("messageId").GetString()!); await Task.Delay(50); // slight offset in CreatedAt } // Device connects var deviceConn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); var caughtUp = new List(); deviceConn.On("ReceiveNotification", n => { if (msgIds.Contains(n.Id)) { caughtUp.Add(n); } }); await deviceConn.StartAsync(); try { var timeout = DateTime.UtcNow.AddSeconds(4); while (caughtUp.Count < 3 && DateTime.UtcNow < timeout) { await Task.Delay(50); } if (caughtUp.Count < 3) throw new Exception($"Expected 3 caught-up notifications, got {caughtUp.Count}"); // Verify order matches msgIds order for (int i = 0; i < 3; i++) { if (caughtUp[i].Id != msgIds[i]) { throw new Exception($"Chronological order mismatch at index {i}: expected {msgIds[i]}, got {caughtUp[i].Id}"); } } // Acknowledge all to keep DB clean foreach (var id in msgIds) { await deviceConn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = id, ClassId = "cls_801", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); } } finally { await deviceConn.StopAsync(); } } private static async Task Test_Expired_Notifications_Strictly_Suppressed(CustomWebApplicationFactory factory) { string expiredMsgId = $"msg_expired_{Guid.NewGuid():N}"; string validMsgId = $"msg_valid_{Guid.NewGuid():N}"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var dev = await db.Devices.FirstOrDefaultAsync(d => d.Id == "dev_bj4_801"); if (dev != null) { dev.BindingStartedAtUtc = DateTimeOffset.UtcNow.AddHours(-2); } // Insert expired notification (ExpiresAt was 10 minutes ago) db.Notifications.Add(new Notification { Id = expiredMsgId, TenantId = "t_beijing_no4", ClassroomId = "cls_801", SenderName = "系统", Title = "已过期通知", Message = "此消息已经超期", Priority = "Call", CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-30), ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-10) }); db.NotificationReceipts.Add(new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = expiredMsgId, DeviceId = "dev_bj4_801", Status = "Sent", UpdatedAt = DateTimeOffset.UtcNow.AddMinutes(-30) }); // Insert valid active notification (ExpiresAt is 10 minutes from now) db.Notifications.Add(new Notification { Id = validMsgId, TenantId = "t_beijing_no4", ClassroomId = "cls_801", SenderName = "系统", Title = "有效待补发通知", Message = "此消息仍在有效期内", Priority = "Call", CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-2), ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(10) }); db.NotificationReceipts.Add(new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = validMsgId, DeviceId = "dev_bj4_801", Status = "Sent", UpdatedAt = DateTimeOffset.UtcNow.AddMinutes(-2) }); await db.SaveChangesAsync(); } // Connect device and collect catch-ups var deviceConn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); var received = new List(); deviceConn.On("ReceiveNotification", n => { received.Add(n); }); await deviceConn.StartAsync(); try { var timeout = DateTime.UtcNow.AddSeconds(3); while (!received.Any(n => n.Id == validMsgId) && DateTime.UtcNow < timeout) { await Task.Delay(50); } // Verify: valid notification WAS received if (!received.Any(n => n.Id == validMsgId)) throw new Exception("Valid notification was not received"); // Verify: expired notification was NEVER received if (received.Any(n => n.Id == expiredMsgId)) throw new Exception("SECURITY/CONTRACT VIOLATION: Expired notification was incorrectly delivered!"); // Check DB state for expired notification receipt using var scope = factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var expiredRcpt = await db.NotificationReceipts.FirstAsync(r => r.NotificationId == expiredMsgId && r.DeviceId == "dev_bj4_801"); if (expiredRcpt.Status != "Expired") throw new Exception($"Expired notification receipt status should be 'Expired', got '{expiredRcpt.Status}'"); // Acknowledge valid one await deviceConn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = validMsgId, ClassId = "cls_801", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); } finally { await deviceConn.StopAsync(); } } private static async Task Test_Already_Acknowledged_Not_Repeated(CustomWebApplicationFactory factory, HttpClient client) { // 1. Send and Acknowledge a notification var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "钱老师", "t_beijing_no4"); var notif = new NotificationDto { ClassId = "cls_801", Title = "防重测试", Message = "测试已确认消息不重复推送", Type = NotificationType.Call }; var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); req.Content = JsonContent.Create(notif); var res = await client.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"Send failed: {res.StatusCode}"); var json = await res.Content.ReadFromJsonAsync(); var msgId = json.GetProperty("messageId").GetString()!; // Directly mark receipt as Acknowledged in DB (simulating prior ack) using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var rcpt = await db.NotificationReceipts.FirstAsync(r => r.NotificationId == msgId && r.DeviceId == "dev_bj4_801"); rcpt.Status = "Acknowledged"; rcpt.AcknowledgedAt = DateTimeOffset.UtcNow; await db.SaveChangesAsync(); } // 2. Reconnect device var deviceConn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); var received = new List(); deviceConn.On("ReceiveNotification", n => { if (n.Id == msgId) { received.Add(n); } }); await deviceConn.StartAsync(); try { await Task.Delay(1000); // give ample time to catch up if (received.Count > 0) throw new Exception($"Already acknowledged notification {msgId} was redundantly caught up to device!"); } finally { await deviceConn.StopAsync(); } } private static void Test_Client_Notification_Deduplicator_Actual_Class() { // Direct testing of the production ClientNotificationDeduplicator class var deduplicator = new ClientNotificationDeduplicator(maxCapacity: 100); string testId = $"msg_dedup_{Guid.NewGuid():N}"; // Concurrency test: 20 concurrent tasks all calling TryProcess with identical ID int passCount = 0; int suppressCount = 0; Parallel.For(0, 20, _ => { if (deduplicator.TryProcess(testId)) { Interlocked.Increment(ref passCount); } else { Interlocked.Increment(ref suppressCount); } }); // Exactly one concurrent call must win; the other 19 must be atomically suppressed if (passCount != 1 || suppressCount != 19) { throw new Exception($"Atomic deduplication failed under concurrency! Pass={passCount}, Suppressed={suppressCount}"); } // Subsequent call must also return false (idempotent duplicate suppression) if (deduplicator.TryProcess(testId)) { throw new Exception("Subsequent call to TryProcess returned true for duplicate message!"); } // Different ID must return true string otherId = $"msg_dedup_other_{Guid.NewGuid():N}"; if (!deduplicator.TryProcess(otherId)) { throw new Exception("TryProcess returned false for distinct message ID!"); } if (!deduplicator.IsProcessed(testId) || !deduplicator.IsProcessed(otherId)) { throw new Exception("IsProcessed check failed for processed messages"); } // Test clear deduplicator.Clear(); if (deduplicator.Count != 0) { throw new Exception($"Clear did not reset count, current count = {deduplicator.Count}"); } } private static async Task Test_MultiTenant_Classroom_Isolation_On_Catchup(CustomWebApplicationFactory factory, HttpClient client) { // 1. Teacher in Beijing school sends notification to cls_801 var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "孙老师", "t_beijing_no4"); var notif = new NotificationDto { ClassId = "cls_801", Title = "多租户隔离测试", Message = "该消息仅属于北京四中八年级(1)班", Type = NotificationType.Call }; var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); req.Content = JsonContent.Create(notif); var res = await client.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"Send failed: {res.StatusCode}"); var json = await res.Content.ReadFromJsonAsync(); var msgId = json.GetProperty("messageId").GetString()!; // 2. Connect Shanghai school device (cls_801 in t_shanghai_high) -> MUST NOT receive var shConn = CreateDeviceHubConnection(factory, "dev_sh1_801", "dtoken_bj4_801_secret"); var shReceived = new List(); shConn.On("ReceiveNotification", n => shReceived.Add(n)); await shConn.StartAsync(); // 3. Connect Beijing school Class 802 device (cls_802) -> MUST NOT receive var bj802Conn = CreateDeviceHubConnection(factory, "dev_bj4_802", "dtoken_bj4_801_secret"); var bj802Received = new List(); bj802Conn.On("ReceiveNotification", n => bj802Received.Add(n)); await bj802Conn.StartAsync(); // 4. Connect Beijing school Class 801 device (cls_801) -> MUST receive var bj801Conn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); var bj801Received = new List(); bj801Conn.On("ReceiveNotification", n => bj801Received.Add(n)); await bj801Conn.StartAsync(); try { var timeout = DateTime.UtcNow.AddSeconds(3); while (!bj801Received.Any(n => n.Id == msgId) && DateTime.UtcNow < timeout) { await Task.Delay(50); } if (!bj801Received.Any(n => n.Id == msgId)) throw new Exception("Intended target device dev_bj4_801 did not receive catch-up notification"); if (shReceived.Any(n => n.Id == msgId)) throw new Exception("CRITICAL ISOLATION BREACH: Cross-tenant device dev_sh1_801 received catch-up notification!"); if (bj802Received.Any(n => n.Id == msgId)) throw new Exception("CRITICAL ISOLATION BREACH: Cross-classroom device dev_bj4_802 received catch-up notification!"); // Clean up ACK await bj801Conn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = msgId, ClassId = "cls_801", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); } finally { await shConn.StopAsync(); await bj802Conn.StopAsync(); await bj801Conn.StopAsync(); } } private static async Task Test_Legacy_Null_ExpiresAt_Never_Delivered_And_Marked_Expired(CustomWebApplicationFactory factory) { string legacyMsgId = $"msg_legacy_null_{Guid.NewGuid():N}"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var dev = await db.Devices.FirstOrDefaultAsync(d => d.Id == "dev_bj4_801"); if (dev != null) { dev.BindingStartedAtUtc = DateTimeOffset.UtcNow.AddDays(-5); } // Insert pre-Batch 9 legacy notification where ExpiresAt is NULL db.Notifications.Add(new Notification { Id = legacyMsgId, TenantId = "t_beijing_no4", ClassroomId = "cls_801", SenderName = "系统", Title = "历史通知 (无TTL)", Message = "Batch 8 历史遗留通知,ExpiresAt 为 NULL", Priority = "Call", CreatedAt = DateTimeOffset.UtcNow.AddDays(-2), ExpiresAt = null // Legacy NULL }); db.NotificationReceipts.Add(new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = legacyMsgId, DeviceId = "dev_bj4_801", Status = "Sent", // Was left in Sent before Batch 9 UpdatedAt = DateTimeOffset.UtcNow.AddDays(-2) }); await db.SaveChangesAsync(); } // Connect device to DeviceHub var deviceConn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); var received = new List(); deviceConn.On("ReceiveNotification", n => { received.Add(n); }); await deviceConn.StartAsync(); try { await Task.Delay(1000); // Give catch-up time // Verification 1: Legacy notification MUST NEVER be delivered to client if (received.Any(n => n.Id == legacyMsgId)) { throw new Exception("SECURITY VIOLATION: Legacy notification with ExpiresAt=NULL was erroneously caught up to device!"); } // Verification 2: Database receipt status MUST have been migrated to 'Expired' using var scope = factory.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var receipt = await db.NotificationReceipts.FirstAsync(r => r.NotificationId == legacyMsgId && r.DeviceId == "dev_bj4_801"); if (receipt.Status != "Expired") { throw new Exception($"Legacy receipt status should be 'Expired', got '{receipt.Status}'"); } } finally { await deviceConn.StopAsync(); } } private static async Task Test_Transient_Wpf_Unavailable_Does_Not_Drop_Message_And_Delivers_On_Connect(CustomWebApplicationFactory factory, HttpClient client) { var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "孙老师", "t_beijing_no4"); var notifDto = new NotificationDto { ClassId = "cls_801", Title = "UI延迟启动测试", Message = "模拟客户端UI启动耗时较长情况下的可重试投递", Type = NotificationType.Call, DurationSeconds = 60 }; var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); req.Content = JsonContent.Create(notifDto); var res = await client.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"Send failed: {res.StatusCode}"); var json = await res.Content.ReadFromJsonAsync(); var msgId = json.GetProperty("messageId").GetString()!; // Check database: receipt should be "Sent" using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var rcpt = await db.NotificationReceipts.FirstAsync(r => r.NotificationId == msgId && r.DeviceId == "dev_bj4_801"); if (rcpt.Status != "Sent") throw new Exception($"Receipt status should start as 'Sent', got '{rcpt.Status}'"); } // Use the ACTUAL production ClientNotificationBuffer component var buffer = new ClientNotificationBuffer(); bool clientConnected = false; // When notification arrives and client is disconnected: var deliveredImmediately = await buffer.DeliverOrBufferAsync( notifDto, isClientConnected: () => clientConnected, sendToClientAsync: _ => Task.FromResult(true), waitAttempts: 0); if (deliveredImmediately) throw new Exception("DeliverOrBufferAsync should have returned false when client is disconnected!"); if (buffer.PendingCount != 1) throw new Exception($"Expected 1 pending notification in ClientNotificationBuffer, got {buffer.PendingCount}"); // Verify DB receipt is STILL "Sent" (not corrupted to Failed) using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var rcpt = await db.NotificationReceipts.FirstAsync(r => r.NotificationId == msgId && r.DeviceId == "dev_bj4_801"); if (rcpt.Status != "Sent") throw new Exception($"Receipt was prematurely marked '{rcpt.Status}' instead of remaining 'Sent'!"); } // Later (e.g. at second 6), WPF client becomes available and connects to Named Pipe clientConnected = true; var deliveredToClient = new List(); var flushedCount = await buffer.FlushAsync( isClientConnected: () => clientConnected, sendToClientAsync: n => { deliveredToClient.Add(n); return Task.FromResult(true); }); if (flushedCount != 1 || deliveredToClient.Count != 1 || deliveredToClient[0].Title != notifDto.Title) throw new Exception("Pending notification was not flushed to newly connected client via ClientNotificationBuffer"); if (buffer.PendingCount != 0) throw new Exception($"Buffer should be empty after successful flush, remaining: {buffer.PendingCount}"); // Client presents UI and sends ACK to DeviceHub var deviceConn = CreateDeviceHubConnection(factory, "dev_bj4_801", "dtoken_bj4_801_secret"); await deviceConn.StartAsync(); try { await deviceConn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = msgId, ClassId = "cls_801", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); await Task.Delay(200); using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); var finalRcpt = await db.NotificationReceipts.FirstAsync(r => r.NotificationId == msgId && r.DeviceId == "dev_bj4_801"); if (finalRcpt.Status != "Acknowledged") throw new Exception($"Final receipt should be 'Acknowledged', got '{finalRcpt.Status}'"); } } finally { await deviceConn.StopAsync(); } } private static async Task Test_Pipe_Send_Returns_False_Mid_Send_Recovers_And_Delivers_On_Next_Connect() { var buffer = new ClientNotificationBuffer(); var notif = new NotificationDto { Id = $"msg_race_{Guid.NewGuid():N}", Title = "Pipe Race Test", Message = "Test client disconnected mid-send" }; // Scenario 1: Live delivery where IsClientConnected is true, but actual send returns false (pipe disconnected during write) bool clientReportsConnected = true; var delivered = await buffer.DeliverOrBufferAsync( notif, isClientConnected: () => clientReportsConnected, sendToClientAsync: _ => Task.FromResult(false), // Send failed! waitAttempts: 0); if (delivered) throw new Exception("DeliverOrBufferAsync must return false when SendNotificationToClientAsync returns false!"); if (buffer.PendingCount != 1) throw new Exception("Notification must be safely enqueued into buffer when pipe send returns false!"); var singleDeliveryLog = new List(); var flushed = await buffer.FlushAsync( isClientConnected: () => true, sendToClientAsync: n => { singleDeliveryLog.Add(n.Id); return Task.FromResult(true); }); if (flushed != 1 || buffer.PendingCount != 0 || singleDeliveryLog[0] != notif.Id) throw new Exception($"Notification should have been flushed on next connection! Flushed={flushed}, Remaining={buffer.PendingCount}"); buffer.Clear(); // Scenario 2: Strict FIFO order preservation on mid-stream failure // Initial queue: m1 -> m2 -> m3 var n1 = new NotificationDto { Id = "m1", Title = "1" }; var n2 = new NotificationDto { Id = "m2", Title = "2" }; var n3 = new NotificationDto { Id = "m3", Title = "3" }; buffer.Enqueue(n1); buffer.Enqueue(n2); buffer.Enqueue(n3); var deliverySequence = new List(); // Flush attempt 1: m1 succeeds, m2 fails mid-stream (broken pipe). // Under atomic Peek-then-Dequeue, m2 is NOT dequeued and stays at head of queue! var partialFlushed = await buffer.FlushAsync( isClientConnected: () => true, sendToClientAsync: n => { if (n.Id == "m2") return Task.FromResult(false); // Mid-flush failure! deliverySequence.Add(n.Id); return Task.FromResult(true); }); if (partialFlushed != 1) throw new Exception($"Expected 1 flushed before failure, got {partialFlushed}"); // Both m2 (failed) and m3 (unreached) must safely remain in buffer in exact FIFO order [m2, m3]! if (buffer.PendingCount != 2) throw new Exception($"Expected 2 notifications remaining in buffer after mid-flush failure, got {buffer.PendingCount}"); var snapshot = buffer.GetPendingSnapshot().Select(x => x.Id).ToList(); if (snapshot.Count != 2 || snapshot[0] != "m2" || snapshot[1] != "m3") throw new Exception($"FIFO queue inverted! Expected [m2, m3], but snapshot was [{string.Join(", ", snapshot)}]"); // Scenario 3: Backlog barrier: new live notification m4 arrives while backlog [m2, m3] exists. // It must NOT bypass m2 or m3! It must be enqueued at tail -> [m2, m3, m4]. var n4 = new NotificationDto { Id = "m4", Title = "4" }; var delivered4 = await buffer.DeliverOrBufferAsync( n4, isClientConnected: () => false, // client disconnected sendToClientAsync: _ => Task.FromResult(true)); if (delivered4) throw new Exception("m4 should not have been delivered when client is disconnected and backlog exists!"); var snapshotWithBacklog = buffer.GetPendingSnapshot().Select(x => x.Id).ToList(); if (snapshotWithBacklog.Count != 3 || snapshotWithBacklog[0] != "m2" || snapshotWithBacklog[1] != "m3" || snapshotWithBacklog[2] != "m4") { throw new Exception($"Backlog ordering corrupted! Expected [m2, m3, m4], but got [{string.Join(", ", snapshotWithBacklog)}]"); } // Scenario 4: Next connect: client reconnects and all backlog items flush in strict sequence: m2 -> m3 -> m4 var remainingFlushed = await buffer.FlushAsync( isClientConnected: () => true, sendToClientAsync: n => { deliverySequence.Add(n.Id); return Task.FromResult(true); }); if (remainingFlushed != 3 || buffer.PendingCount != 0) throw new Exception($"Expected remaining 3 notifications to be flushed, got {remainingFlushed}"); // STRICTURE ASSERTION: The actual cumulative delivered sequence across reconnects must be EXACTLY [m1, m2, m3, m4]! if (deliverySequence.Count != 4 || deliverySequence[0] != "m1" || deliverySequence[1] != "m2" || deliverySequence[2] != "m3" || deliverySequence[3] != "m4") { throw new Exception($"Strict FIFO delivery order violated! Expected [m1, m2, m3, m4], but received [{string.Join(", ", deliverySequence)}]"); } } private static async Task Test_History_Aggregation_Recognizes_Expired_And_Timeout(CustomWebApplicationFactory factory, HttpClient client) { var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(factory.Services, "u_teacher_1", "李老师", "t_beijing_no4"); string expiredMsgId = $"msg_hist_exp_{Guid.NewGuid():N}"; string timeoutMsgId = $"msg_hist_tout_{Guid.NewGuid():N}"; using (var scope = factory.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); // 1. Notification with Expired receipt db.Notifications.Add(new Notification { Id = expiredMsgId, TenantId = "t_beijing_no4", ClassroomId = "cls_801", SenderName = "李老师", Title = "过期历史聚合测试", Message = "全部收执已过期的消息", Priority = "Call", CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-20), ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(-5) }); db.NotificationReceipts.Add(new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = expiredMsgId, DeviceId = "dev_bj4_801", Status = "Expired", UpdatedAt = DateTimeOffset.UtcNow.AddMinutes(-5) }); // 2. Notification with Timeout receipt db.Notifications.Add(new Notification { Id = timeoutMsgId, TenantId = "t_beijing_no4", ClassroomId = "cls_801", SenderName = "李老师", Title = "超时历史聚合测试", Message = "收执超时的消息", Priority = "Notice", CreatedAt = DateTimeOffset.UtcNow.AddMinutes(-40), ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(20) }); db.NotificationReceipts.Add(new NotificationReceipt { Id = $"rcpt_{Guid.NewGuid():N}", NotificationId = timeoutMsgId, DeviceId = "dev_bj4_801", Status = "Timeout", UpdatedAt = DateTimeOffset.UtcNow.AddMinutes(-10) }); await db.SaveChangesAsync(); } // Call notification history endpoint var req = new HttpRequestMessage(HttpMethod.Get, "/api/notification/history"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); var res = await client.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"History request failed: {res.StatusCode}"); var records = await res.Content.ReadFromJsonAsync>(); if (records == null) throw new Exception("History returned null"); var expiredRecord = records.FirstOrDefault(r => r.Id == expiredMsgId); if (expiredRecord == null) throw new Exception("Expired notification not found in history"); if (expiredRecord.Status != "Expired") throw new Exception($"Aggregated status for expired notification should be 'Expired', got '{expiredRecord.Status}'"); var timeoutRecord = records.FirstOrDefault(r => r.Id == timeoutMsgId); if (timeoutRecord == null) throw new Exception("Timeout notification not found in history"); if (timeoutRecord.Status != "Timeout") throw new Exception($"Aggregated status for timeout notification should be 'Timeout', got '{timeoutRecord.Status}'"); } private static void Test_EFCore_Migration_Batch8_To_Batch9_Upgrade() { // 1. Verify Migration Metadata and Operations var migration = new ClassNotify.Server.Data.Migrations.AddNotificationExpiresAtAndPendingIndex(); var migrationBuilder = new Microsoft.EntityFrameworkCore.Migrations.MigrationBuilder("Npgsql"); var upMethod = typeof(ClassNotify.Server.Data.Migrations.AddNotificationExpiresAtAndPendingIndex) .GetMethod("Up", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (upMethod == null) throw new Exception("Could not find Up method on AddNotificationExpiresAtAndPendingIndex"); upMethod.Invoke(migration, new object[] { migrationBuilder }); var operations = migrationBuilder.Operations; // Check AddColumn for ExpiresAt var addExpiresAt = operations.OfType() .FirstOrDefault(o => o.Table == "Notifications" && o.Name == "ExpiresAt"); if (addExpiresAt == null || !addExpiresAt.IsNullable) throw new Exception("Migration does not correctly add nullable ExpiresAt column to Notifications"); // Check AddColumn for Voice, Shake, DurationSeconds var addVoice = operations.OfType() .FirstOrDefault(o => o.Table == "Notifications" && o.Name == "Voice"); if (addVoice == null || (bool?)addVoice.DefaultValue != true) throw new Exception("Migration does not correctly add Voice column with defaultValue=true"); var addDuration = operations.OfType() .FirstOrDefault(o => o.Table == "Notifications" && o.Name == "DurationSeconds"); if (addDuration == null || (int?)addDuration.DefaultValue != 15) throw new Exception("Migration does not correctly add DurationSeconds column with defaultValue=15"); // Check Composite Indexes var idxPending = operations.OfType() .FirstOrDefault(o => o.Name == "IX_NotificationReceipts_DeviceId_Status"); if (idxPending == null || !idxPending.Columns.SequenceEqual(new[] { "DeviceId", "Status" })) throw new Exception("Migration does not create IX_NotificationReceipts_DeviceId_Status composite index"); var idxNotifExpires = operations.OfType() .FirstOrDefault(o => o.Name == "IX_Notifications_TenantId_ClassroomId_ExpiresAt"); if (idxNotifExpires == null || !idxNotifExpires.Columns.SequenceEqual(new[] { "TenantId", "ClassroomId", "ExpiresAt" })) throw new Exception("Migration does not create IX_Notifications_TenantId_ClassroomId_ExpiresAt composite index"); // Check SQL Backfill var sqlOp = operations.OfType() .FirstOrDefault(s => s.Sql.Contains("UPDATE \"Notifications\" SET \"ExpiresAt\" = \"CreatedAt\" WHERE \"ExpiresAt\" IS NULL")); if (sqlOp == null) throw new Exception("Migration lacks SQL backfill operation to update legacy NULL ExpiresAt to CreatedAt"); // 2. Verify DbContext Model Snapshot var snapshot = new ClassNotify.Server.Data.Migrations.ClassNotifyDbContextModelSnapshot(); var modelBuilder = new ModelBuilder(new Microsoft.EntityFrameworkCore.Metadata.Conventions.ConventionSet()); var buildModelMethod = typeof(ClassNotify.Server.Data.Migrations.ClassNotifyDbContextModelSnapshot) .GetMethod("BuildModel", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); if (buildModelMethod == null) throw new Exception("Could not find BuildModel on ClassNotifyDbContextModelSnapshot"); buildModelMethod.Invoke(snapshot, new object[] { modelBuilder }); var notificationEntity = modelBuilder.Model.FindEntityType(typeof(Notification)); if (notificationEntity == null) throw new Exception("Notification entity not found in model snapshot"); if (notificationEntity.FindProperty("ExpiresAt") == null) throw new Exception("ExpiresAt property missing from Notification model snapshot"); if (notificationEntity.FindProperty("Voice") == null) throw new Exception("Voice property missing from Notification model snapshot"); if (notificationEntity.FindProperty("DurationSeconds") == null) throw new Exception("DurationSeconds property missing from Notification model snapshot"); } private static async Task Test_Server_Restart_Pending_Notification_Survives(CustomWebApplicationFactory originalFactory) { var dbName = originalFactory.DbName; var teacherJwt = CustomWebApplicationFactory.CreateTeacherJwt(originalFactory.Services, "u_teacher_1", "周老师", "t_beijing_no4"); var client1 = originalFactory.CreateClient(); var notifDto = new NotificationDto { ClassId = "cls_801", Title = "服务重启持久化测试", Message = "测试服务端停止/重启后待补发消息依然保留并可在新实例中补发", Type = NotificationType.Call, DurationSeconds = 300 }; var req = new HttpRequestMessage(HttpMethod.Post, "/api/notification/send"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", teacherJwt); req.Content = JsonContent.Create(notifDto); var res = await client1.SendAsync(req); if (!res.IsSuccessStatusCode) throw new Exception($"Send failed: {res.StatusCode}"); var json = await res.Content.ReadFromJsonAsync(); var msgId = json.GetProperty("messageId").GetString()!; // Simulate Server Process Restart: create new factory sharing the same underlying database using var restartedFactory = new CustomWebApplicationFactory(dbName); var deviceConn = CreateDeviceHubConnection(restartedFactory, "dev_bj4_801", "dtoken_bj4_801_secret"); var caughtUp = new List(); deviceConn.On("ReceiveNotification", n => { if (n.Id == msgId) caughtUp.Add(n); }); await deviceConn.StartAsync(); try { var timeout = DateTime.UtcNow.AddSeconds(3); while (caughtUp.Count == 0 && DateTime.UtcNow < timeout) { await Task.Delay(50); } if (caughtUp.Count == 0) throw new Exception("Pending notification was lost across server restart!"); // Acknowledge to clean up await deviceConn.InvokeAsync("SendAckReceipt", new AckReceiptDto { MessageId = msgId, ClassId = "cls_801", Status = AckStatus.Acknowledged, Timestamp = DateTimeOffset.UtcNow }); } finally { await deviceConn.StopAsync(); } } private static async Task Test_PostgreSQL_Batch8_To_Batch9_Migration_Integration_With_Legacy_Data() { var baseConnStr = Environment.GetEnvironmentVariable("CLASSNOTIFY_TEST_DB_CONNECTION"); if (string.IsNullOrWhiteSpace(baseConnStr)) { throw new InvalidOperationException( "Environment variable 'CLASSNOTIFY_TEST_DB_CONNECTION' is not configured. " + "For security, database credentials must be provided via environment variables rather than hardcoded in source code."); } var baseBuilder = new NpgsqlConnectionStringBuilder(baseConnStr); string tempDbName = $"cn_mig_test_{Guid.NewGuid():N}"; var tempDbBuilder = new NpgsqlConnectionStringBuilder(baseConnStr) { Database = tempDbName }; string tempDbConnStr = tempDbBuilder.ConnectionString; // 1. Create temporary isolated PostgreSQL database await using (var conn = new NpgsqlConnection(baseBuilder.ConnectionString)) { await conn.OpenAsync(); await using var cmd = new NpgsqlCommand($"CREATE DATABASE \"{tempDbName}\";", conn); await cmd.ExecuteNonQueryAsync(); } try { // 2. Build DbContext targeting temporary DB var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(tempDbConnStr); using (var db = new ClassNotifyDbContext(optionsBuilder.Options)) { var migrator = db.GetInfrastructure().GetService(); if (migrator == null) throw new Exception("IMigrator service not available"); // 3. Migrate ONLY to Batch 8 (InitialPostgreSql) await migrator.MigrateAsync("20260920225928_InitialPostgreSql"); // Verify that at Batch 8, Notifications table does NOT have ExpiresAt column await using var checkColCmd = db.Database.GetDbConnection().CreateCommand(); if (checkColCmd.Connection!.State != System.Data.ConnectionState.Open) await checkColCmd.Connection.OpenAsync(); checkColCmd.CommandText = "SELECT COUNT(*) FROM information_schema.columns WHERE table_name = 'Notifications' AND column_name = 'ExpiresAt';"; var colCount = Convert.ToInt32(await checkColCmd.ExecuteScalarAsync()); if (colCount != 0) throw new Exception("ExpiresAt column already exists before Batch 9 migration!"); // 4. Insert Batch 8 legacy data (tenant, classroom, device, legacy notification without ExpiresAt, and receipt in 'Sent') var insertSql = @" INSERT INTO ""Tenants"" (""Id"", ""Name"", ""IsActive"", ""CreatedAt"") VALUES ('t_mig', 'Mig Tenant', true, NOW()); INSERT INTO ""Classrooms"" (""Id"", ""TenantId"", ""DisplayName"", ""Grade"", ""RoomNumber"", ""CreatedAt"") VALUES ('c_mig', 't_mig', '101班', '1', '101', NOW()); INSERT INTO ""Devices"" (""Id"", ""TenantId"", ""ClassroomId"", ""DeviceTokenHash"", ""IsActive"", ""CreatedAt"") VALUES ('d_mig', 't_mig', 'c_mig', 'tok_hash', true, NOW() - INTERVAL '3 days'); INSERT INTO ""Notifications"" (""Id"", ""TenantId"", ""ClassroomId"", ""SenderName"", ""Title"", ""Message"", ""Priority"", ""CreatedAt"") VALUES ('legacy_notif_1', 't_mig', 'c_mig', 'Teacher', 'Legacy Title', 'Legacy Message', 'Call', NOW() - INTERVAL '2 days'); INSERT INTO ""NotificationReceipts"" (""Id"", ""NotificationId"", ""DeviceId"", ""Status"", ""UpdatedAt"") VALUES ('legacy_rcpt_1', 'legacy_notif_1', 'd_mig', 'Sent', NOW() - INTERVAL '2 days'); "; await db.Database.ExecuteSqlRawAsync(insertSql); // 5. Execute Migration to Batch 9 (latest) await db.Database.MigrateAsync(); await db.Database.ExecuteSqlRawAsync(@" ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""HardwareComponentsHash"" TEXT NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""DisplayLabel"" TEXT NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""BindingStartedAtUtc"" TIMESTAMPTZ NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""LastHeartbeatCorrelationId"" TEXT NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""ServiceVersion"" TEXT NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""ClientVersion"" TEXT NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""ProtocolVersion"" INTEGER NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""OsVersion"" TEXT NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""Architecture"" TEXT NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""LicensedUntil"" TIMESTAMPTZ NULL; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""LicenseTier"" TEXT NOT NULL DEFAULT 'Trial'; ALTER TABLE ""Devices"" ADD COLUMN IF NOT EXISTS ""TrialUsed"" BOOLEAN NOT NULL DEFAULT TRUE; ALTER TABLE ""Notifications"" ADD COLUMN IF NOT EXISTS ""IsCancelled"" BOOLEAN NOT NULL DEFAULT FALSE; ALTER TABLE ""Notifications"" ADD COLUMN IF NOT EXISTS ""CancelledAt"" TIMESTAMPTZ NULL; ALTER TABLE ""Notifications"" ADD COLUMN IF NOT EXISTS ""CancelledBy"" TEXT NULL; ALTER TABLE ""Notifications"" ADD COLUMN IF NOT EXISTS ""BroadcastId"" TEXT NULL; ALTER TABLE ""Notifications"" ADD COLUMN IF NOT EXISTS ""CorrelationId"" TEXT NOT NULL DEFAULT ''; ALTER TABLE ""NotificationReceipts"" ADD COLUMN IF NOT EXISTS ""VisualReceiptState"" TEXT NOT NULL DEFAULT 'None'; ALTER TABLE ""NotificationReceipts"" ADD COLUMN IF NOT EXISTS ""VisualReceiptPath"" TEXT NULL; ALTER TABLE ""NotificationReceipts"" ADD COLUMN IF NOT EXISTS ""VisualReceiptCapturedAt"" TIMESTAMPTZ NULL; ALTER TABLE ""NotificationReceipts"" ADD COLUMN IF NOT EXISTS ""VisualReceiptExpiresAt"" TIMESTAMPTZ NULL; ALTER TABLE ""NotificationReceipts"" ADD COLUMN IF NOT EXISTS ""VisualReceiptSizeBytes"" BIGINT NULL; ALTER TABLE ""NotificationReceipts"" ADD COLUMN IF NOT EXISTS ""VisualReceiptSha256"" TEXT NULL; "); // 6. Verify Schema Changes in PostgreSQL catalog // A. Check columns exist with correct defaults checkColCmd.CommandText = "SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_name = 'Notifications' AND column_name IN ('ExpiresAt', 'Voice', 'Shake', 'DurationSeconds');"; var foundCols = new Dictionary(); await using (var reader = await checkColCmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { var colName = reader.GetString(0); var type = reader.GetString(1); var def = reader.IsDBNull(2) ? null : reader.GetString(2); foundCols[colName] = (type, def); } } if (!foundCols.ContainsKey("ExpiresAt")) throw new Exception("ExpiresAt column missing after migration!"); if (!foundCols.ContainsKey("Voice")) throw new Exception("Voice column missing after migration!"); if (!foundCols.ContainsKey("Shake")) throw new Exception("Shake column missing after migration!"); if (!foundCols.ContainsKey("DurationSeconds")) throw new Exception("DurationSeconds column missing after migration!"); // B. Check composite indexes exist checkColCmd.CommandText = "SELECT indexname FROM pg_indexes WHERE tablename IN ('Notifications', 'NotificationReceipts');"; var indexNames = new HashSet(); await using (var reader = await checkColCmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { indexNames.Add(reader.GetString(0)); } } if (!indexNames.Contains("IX_Notifications_TenantId_ClassroomId_ExpiresAt")) throw new Exception("Index IX_Notifications_TenantId_ClassroomId_ExpiresAt missing in PostgreSQL!"); if (!indexNames.Contains("IX_NotificationReceipts_DeviceId_Status")) throw new Exception("Index IX_NotificationReceipts_DeviceId_Status missing in PostgreSQL!"); // C. Verify SQL Backfill: legacy_notif_1's ExpiresAt must equal CreatedAt (NOT null!), defaults for Voice, Shake, Duration checkColCmd.CommandText = "SELECT \"ExpiresAt\", \"CreatedAt\", \"Voice\", \"Shake\", \"DurationSeconds\" FROM \"Notifications\" WHERE \"Id\" = 'legacy_notif_1';"; await using (var reader = await checkColCmd.ExecuteReaderAsync()) { if (!await reader.ReadAsync()) throw new Exception("Legacy notification data was lost during migration!"); if (reader.IsDBNull(0)) throw new Exception("SQL Backfill failed: ExpiresAt is still NULL on legacy record!"); var expiresAt = reader.GetDateTime(0); var createdAt = reader.GetDateTime(1); if (Math.Abs((expiresAt - createdAt).TotalSeconds) > 2) throw new Exception($"SQL Backfill failed: ExpiresAt ({expiresAt}) != CreatedAt ({createdAt})"); var voice = reader.GetBoolean(2); var shake = reader.GetBoolean(3); var duration = reader.GetInt32(4); if (!voice || !shake || duration != 15) throw new Exception($"Defaults incorrect on migrated legacy row: Voice={voice}, Shake={shake}, Duration={duration}"); } // D. Verify Receipt preserved in 'Sent' checkColCmd.CommandText = "SELECT \"Status\" FROM \"NotificationReceipts\" WHERE \"Id\" = 'legacy_rcpt_1';"; var rcptStatus = Convert.ToString(await checkColCmd.ExecuteScalarAsync()); if (rcptStatus != "Sent") throw new Exception($"Receipt status changed during migration: expected 'Sent', got '{rcptStatus}'"); // E. Test Server runtime operation on migrated DB: SecurityService.GetPendingNotificationsForDeviceAsync var services = new ServiceCollection(); services.AddLogging(); services.AddDbContext(opt => opt.UseNpgsql(tempDbConnStr)); services.AddDataProtection(); services.AddSingleton, PasswordHasher>(); services.AddSingleton(new ConfigurationBuilder().Build()); services.AddSingleton(new TestWebHostEnvironment()); services.Configure(opt => { opt.SigningKey = "test_signing_key_at_least_thirty_two_bytes_long_here!"; opt.Issuer = "ClassNotify"; opt.Audience = "ClassNotify"; }); services.AddScoped(); var sp = services.BuildServiceProvider(); using (var testScope = sp.CreateScope()) { var secService = testScope.ServiceProvider.GetRequiredService(); var pending = await secService.GetPendingNotificationsForDeviceAsync("d_mig"); // MUST return 0 because legacy notification was backfilled to ExpiresAt == CreatedAt <= now (EXPIRED) if (pending.Count != 0) throw new Exception($"Zero-replay guarantee breached on migrated PostgreSQL: returned {pending.Count} pending items for legacy notification!"); // Receipt in DB must now be marked 'Expired' checkColCmd.CommandText = "SELECT \"Status\" FROM \"NotificationReceipts\" WHERE \"Id\" = 'legacy_rcpt_1';"; var updatedRcptStatus = Convert.ToString(await checkColCmd.ExecuteScalarAsync()); if (updatedRcptStatus != "Expired") throw new Exception($"Receipt status should be updated to 'Expired' by SecurityService, got '{updatedRcptStatus}'"); } } } finally { // 7. Clean up temporary PostgreSQL test database (drop database with force) try { NpgsqlConnection.ClearAllPools(); await using var dropConn = new NpgsqlConnection(baseConnStr); await dropConn.OpenAsync(); await using var dropCmd = new NpgsqlCommand($"DROP DATABASE IF EXISTS \"{tempDbName}\" WITH (FORCE);", dropConn); await dropCmd.ExecuteNonQueryAsync(); } catch (Exception ex) { Console.WriteLine($"[Cleanup Warning] Could not drop temporary DB {tempDbName}: {ex.Message}"); } } } #endregion } public class TestWebHostEnvironment : IWebHostEnvironment { public string EnvironmentName { get; set; } = "Development"; public string ApplicationName { get; set; } = "ClassNotify.DeliveryTests"; public string WebRootPath { get; set; } = ""; public Microsoft.Extensions.FileProviders.IFileProvider WebRootFileProvider { get; set; } = null!; public string ContentRootPath { get; set; } = AppContext.BaseDirectory; public Microsoft.Extensions.FileProviders.IFileProvider ContentRootFileProvider { get; set; } = null!; }