using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using ClassNotify.Server.Data; using ClassNotify.Server.Domain.Entities; using Microsoft.EntityFrameworkCore; using Npgsql; namespace BenchmarkRunner; public class Program { public static async Task Main(string[] args) { Console.WriteLine("================================================================"); Console.WriteLine(" ClassNotify Benchmark & Production Guard Verification Suite"); Console.WriteLine("================================================================\n"); // ------------------------------------------------------------- // PART 1: VERIFY HARD PRODUCTION GUARD // ------------------------------------------------------------- Console.WriteLine(">>> [GUARD TEST 1] Verifying Production Database Rejection Guard..."); string prodConnStr = "Host=127.0.0.1;Port=5432;Database=classnotify;Username=classnotify;Password=fake;"; bool prodBlocked = false; try { EnforceDatabaseGuard(prodConnStr); } catch (InvalidOperationException ex) when (ex.Message.Contains("Refusing to run destructive/integration/benchmark tests against production database")) { prodBlocked = true; Console.WriteLine($" [GUARD ENGAGED] Successfully caught: {ex.Message}"); } if (!prodBlocked) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" [FATAL FAILURE] Production database guard was bypassed!"); Console.ResetColor(); return 1; } Console.WriteLine(">>> [GUARD TEST 2] Verifying Non-Test/Non-Benchmark Database Rejection..."); string otherConnStr = "Host=127.0.0.1;Port=5432;Database=classnotify_dev;Username=classnotify;Password=fake;"; bool otherBlocked = false; try { EnforceDatabaseGuard(otherConnStr); } catch (InvalidOperationException ex) when (ex.Message.Contains("must end with '_test' or '_benchmark'")) { otherBlocked = true; Console.WriteLine($" [GUARD ENGAGED] Successfully caught: {ex.Message}"); } if (!otherBlocked) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(" [FATAL FAILURE] Suffix guard was bypassed!"); Console.ResetColor(); return 1; } Console.WriteLine(" [PASS] All Hard Production Guards Verified Successfully!\n"); // ------------------------------------------------------------- // PART 2: RUN BENCHMARK IN DEDICATED classnotify_benchmark DB // ------------------------------------------------------------- string? benchConnStr = Environment.GetEnvironmentVariable("CLASSNOTIFY_BENCHMARK_DB_CONNECTION") ?? Environment.GetEnvironmentVariable("CLASSNOTIFY_TEST_DB_CONNECTION"); if (string.IsNullOrWhiteSpace(benchConnStr)) { throw new InvalidOperationException("Environment variable 'CLASSNOTIFY_BENCHMARK_DB_CONNECTION' or 'CLASSNOTIFY_TEST_DB_CONNECTION' is required to run benchmarks. Hardcoded credential fallbacks are strictly prohibited."); } EnforceDatabaseGuard(benchConnStr); var optionsBuilder = new DbContextOptionsBuilder(); optionsBuilder.UseNpgsql(benchConnStr); using var db = new ClassNotifyDbContext(optionsBuilder.Options); var tenantId = "t_beijing_no4"; var classId = "cls_802"; var dev1 = "dev_bench_1"; var dev2 = "dev_bench_2"; // Seed tenant, class, and test devices strictly inside classnotify_benchmark if (!await db.Tenants.AnyAsync(t => t.Id == tenantId)) { db.Tenants.Add(new Tenant { Id = tenantId, Name = "北京四中(压测)", IsActive = true, CreatedAt = DateTimeOffset.UtcNow }); await db.SaveChangesAsync(); } if (!await db.Classrooms.AnyAsync(c => c.TenantId == tenantId && c.Id == classId)) { db.Classrooms.Add(new Classroom { Id = classId, TenantId = tenantId, DisplayName = "八年级(2)班(压测)", Grade = "初二" }); await db.SaveChangesAsync(); } if (!await db.Devices.AnyAsync(d => d.Id == dev1)) { db.Devices.Add(new Device { Id = dev1, TenantId = tenantId, ClassroomId = classId, DeviceTokenHash = "bench_hash_1", InstallationId = "inst_b1" }); } if (!await db.Devices.AnyAsync(d => d.Id == dev2)) { db.Devices.Add(new Device { Id = dev2, TenantId = tenantId, ClassroomId = classId, DeviceTokenHash = "bench_hash_2", InstallationId = "inst_b2" }); } await db.SaveChangesAsync(); int existingNotifs = await db.Notifications.CountAsync(n => n.TenantId == tenantId); int targetNotifs = 10000; int needed = targetNotifs - existingNotifs; if (needed > 0) { Console.WriteLine($" Seeding {needed} notifications and {needed * 2} receipts into classnotify_benchmark..."); var swSeed = Stopwatch.StartNew(); int batchSize = 1000; int batches = (needed + batchSize - 1) / batchSize; for (int b = 0; b < batches; b++) { var notifList = new List(); var receiptList = new List(); int currentBatchCount = Math.Min(batchSize, needed - (b * batchSize)); for (int i = 0; i < currentBatchCount; i++) { var nId = $"msg_bench_{b}_{i}_{Guid.NewGuid():N}"[..32]; var createdAt = DateTimeOffset.UtcNow.AddMinutes(-1 * (b * batchSize + i)); notifList.Add(new Notification { Id = nId, TenantId = tenantId, ClassroomId = classId, SenderName = "性能压测教师", Message = $"Benchmark test payload #{b * batchSize + i}", Title = "🔔 性能测试通知", Priority = "Normal", CreatedAt = createdAt }); receiptList.Add(new NotificationReceipt { Id = $"rcpt_b1_{b}_{i}_{Guid.NewGuid():N}"[..32], NotificationId = nId, DeviceId = dev1, Status = (i % 2 == 0) ? "Acknowledged" : "Displayed", AcknowledgedAt = (i % 2 == 0) ? createdAt.AddSeconds(2) : null, UpdatedAt = createdAt }); receiptList.Add(new NotificationReceipt { Id = $"rcpt_b2_{b}_{i}_{Guid.NewGuid():N}"[..32], NotificationId = nId, DeviceId = dev2, Status = (i % 5 == 0) ? "Failed" : "Displayed", FailedAt = (i % 5 == 0) ? createdAt.AddSeconds(3) : null, FailureReason = (i % 5 == 0) ? "Simulated error" : null, UpdatedAt = createdAt }); } db.Notifications.AddRange(notifList); db.NotificationReceipts.AddRange(receiptList); await db.SaveChangesAsync(); db.ChangeTracker.Clear(); } swSeed.Stop(); Console.WriteLine($" Seeding completed in {swSeed.ElapsedMilliseconds} ms."); } int totalNotifs = await db.Notifications.CountAsync(); int totalReceipts = await db.NotificationReceipts.CountAsync(); Console.WriteLine($" Total Notifications in classnotify_benchmark: {totalNotifs}"); Console.WriteLine($" Total Receipts in classnotify_benchmark: {totalReceipts}"); // Warm up await db.Notifications.AsNoTracking().Take(1).ToListAsync(); // Query 1: Recent 50 var sw1 = Stopwatch.StartNew(); var q1 = await db.Notifications.AsNoTracking() .Include(n => n.Receipts) .OrderByDescending(n => n.CreatedAt) .Take(50) .ToListAsync(); sw1.Stop(); Console.WriteLine($" [Query 1] Recent 50 Notifications (with Receipts): {q1.Count} items in {sw1.Elapsed.TotalMilliseconds:F2} ms"); // Query 2: Tenant 50 var sw2 = Stopwatch.StartNew(); var q2 = await db.Notifications.AsNoTracking() .Include(n => n.Receipts) .Where(n => n.TenantId == tenantId) .OrderByDescending(n => n.CreatedAt) .Take(50) .ToListAsync(); sw2.Stop(); Console.WriteLine($" [Query 2] By Tenant ({tenantId}) limit 50: {q2.Count} items in {sw2.Elapsed.TotalMilliseconds:F2} ms"); // Query 3: Classroom 50 var sw3 = Stopwatch.StartNew(); var q3 = await db.Notifications.AsNoTracking() .Include(n => n.Receipts) .Where(n => n.ClassroomId == classId) .OrderByDescending(n => n.CreatedAt) .Take(50) .ToListAsync(); sw3.Stop(); Console.WriteLine($" [Query 3] By Classroom ({classId}) limit 50: {q3.Count} items in {sw3.Elapsed.TotalMilliseconds:F2} ms"); // EXPLAIN ANALYZE Console.WriteLine(" [PostgreSQL Server EXPLAIN ANALYZE for Tenant Query]:"); using (var cmd = db.Database.GetDbConnection().CreateCommand()) { if (cmd.Connection!.State != System.Data.ConnectionState.Open) { await cmd.Connection.OpenAsync(); } cmd.CommandText = "EXPLAIN ANALYZE SELECT * FROM \"Notifications\" WHERE \"TenantId\" = 't_beijing_no4' ORDER BY \"CreatedAt\" DESC LIMIT 50;"; using var reader = await cmd.ExecuteReaderAsync(); while (await reader.ReadAsync()) { var line = reader.GetString(0); Console.WriteLine($" {line}"); } } Console.WriteLine("\n================================================================"); Console.WriteLine(" Benchmark Completed Successfully in classnotify_benchmark!"); Console.WriteLine(" Production database (classnotify) remained 100% UNTOUCHED."); Console.WriteLine("================================================================"); return 0; } public static void EnforceDatabaseGuard(string connectionString) { var builder = new NpgsqlConnectionStringBuilder(connectionString); string dbName = builder.Database?.Trim() ?? string.Empty; // Hard rule 1: Never target production database 'classnotify' if (dbName.Equals("classnotify", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( "Refusing to run destructive/integration/benchmark tests against production database." ); } // Hard rule 2: Must explicitly target _test or _benchmark if (!dbName.EndsWith("_test", StringComparison.OrdinalIgnoreCase) && !dbName.EndsWith("_benchmark", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( $"Benchmark database name must end with '_test' or '_benchmark', got '{dbName}'." ); } } }