create-tigra 4.0.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +21 -3
  3. package/bin/create-tigra.js +131 -65
  4. package/lib/installer-transaction.js +275 -0
  5. package/lib/patchers/diagnostics.patcher.js +123 -0
  6. package/lib/patchers/email-verification.patcher.js +86 -92
  7. package/lib/patchers/metrics.patcher.js +145 -0
  8. package/lib/project-files.js +99 -0
  9. package/modules/diagnostics/diagnostics.md +75 -0
  10. package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
  11. package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
  12. package/modules/diagnostics/prisma/migration.sql +20 -0
  13. package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
  14. package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
  15. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +123 -0
  16. package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
  17. package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
  18. package/modules/diagnostics/server/diagnostics.context.ts +73 -0
  19. package/modules/diagnostics/server/diagnostics.repo.ts +79 -0
  20. package/modules/diagnostics/server/diagnostics.routes.ts +16 -0
  21. package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
  22. package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
  23. package/modules/diagnostics/server/diagnostics.service.ts +44 -0
  24. package/modules/email-verification/client/hooks/useVerification.ts +4 -7
  25. package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
  26. package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
  27. package/modules/email-verification/server/verification.service.ts +102 -157
  28. package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
  29. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -0
  30. package/modules/metrics/client/metrics.pages.ts +5 -0
  31. package/modules/metrics/performance.md +56 -0
  32. package/modules/metrics/prisma/metric-bucket.prisma +18 -0
  33. package/modules/metrics/prisma/migration.sql +17 -0
  34. package/modules/metrics/server/__tests__/metrics.collector.test.ts +97 -0
  35. package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
  36. package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
  37. package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
  38. package/modules/metrics/server/metrics.collector.ts +133 -0
  39. package/modules/metrics/server/metrics.pages.ts +3 -0
  40. package/modules/metrics/server/metrics.repo.ts +45 -0
  41. package/modules/metrics/server/metrics.routes.ts +45 -0
  42. package/modules/metrics/server/metrics.schemas.ts +57 -0
  43. package/modules/metrics/server/metrics.service.ts +104 -0
  44. package/package.json +1 -1
  45. package/template/AGENTS.md +18 -10
  46. package/template/client/.dockerignore +2 -5
  47. package/template/client/gitignore +43 -0
  48. package/template/client/src/app/focus-rings.policy.test.ts +88 -0
  49. package/template/client/src/app/globals.css +46 -0
  50. package/template/client/src/app/layout.tsx +5 -0
  51. package/template/client/src/app/page.tsx +2 -2
  52. package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
  53. package/template/client/src/components/ui/input.tsx +3 -2
  54. package/template/client/src/features/auth/components/AuthInitializer.tsx +45 -7
  55. package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
  56. package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
  57. package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
  58. package/template/client/src/features/auth/services/auth.service.ts +3 -2
  59. package/template/client/src/features/auth/store/authSlice.ts +11 -8
  60. package/template/client/src/features/auth/types/auth.types.ts +1 -0
  61. package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
  62. package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
  63. package/template/client/src/lib/api/axios.config.ts +24 -6
  64. package/template/client/src/lib/api/session-events.ts +54 -0
  65. package/template/client/src/lib/input-modality.test.ts +79 -0
  66. package/template/client/src/lib/input-modality.ts +52 -0
  67. package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
  68. package/template/client/src/store/__tests__/store.test.ts +1 -0
  69. package/template/gitignore +3 -2
  70. package/template/server/.dockerignore +2 -5
  71. package/template/server/.env.example +1 -0
  72. package/template/server/.env.example.production +1 -0
  73. package/template/server/README.md +7 -2
  74. package/template/server/docs/deployment.md +66 -0
  75. package/template/server/docs/logging.md +9 -8
  76. package/template/server/docs/rate-limits.md +6 -4
  77. package/template/server/gitignore +33 -0
  78. package/template/server/prisma/migrations/0_init/migration.sql +25 -0
  79. package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
  80. package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
  81. package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
  82. package/template/server/prisma/schema.prisma +25 -1
  83. package/template/server/src/__tests__/routes.integration.test.ts +5 -2
  84. package/template/server/src/app.ts +14 -5
  85. package/template/server/src/config/env.ts +8 -0
  86. package/template/server/src/config/rate-limit.config.ts +1 -1
  87. package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
  88. package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
  89. package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
  90. package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
  91. package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
  92. package/template/server/src/jobs/index.ts +8 -2
  93. package/template/server/src/libs/__tests__/auth.test.ts +1 -1
  94. package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
  95. package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
  96. package/template/server/src/libs/__tests__/http.test.ts +10 -10
  97. package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
  98. package/template/server/src/libs/__tests__/logger.test.ts +10 -1
  99. package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
  100. package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
  101. package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
  102. package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
  103. package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
  104. package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
  105. package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
  106. package/template/server/src/libs/account-mutation.ts +77 -0
  107. package/template/server/src/libs/auth.ts +37 -3
  108. package/template/server/src/libs/cookies.ts +25 -13
  109. package/template/server/src/libs/email-quota.ts +11 -7
  110. package/template/server/src/libs/email.ts +11 -8
  111. package/template/server/src/libs/error-handler.ts +16 -12
  112. package/template/server/src/libs/http.ts +37 -13
  113. package/template/server/src/libs/ip-block.ts +56 -34
  114. package/template/server/src/libs/logger.ts +23 -8
  115. package/template/server/src/libs/monitoring.ts +57 -31
  116. package/template/server/src/libs/observability/sentry.ts +65 -49
  117. package/template/server/src/libs/prisma.ts +1 -1
  118. package/template/server/src/libs/private-cache.ts +6 -0
  119. package/template/server/src/libs/rate-limiting.ts +4 -0
  120. package/template/server/src/libs/requestLogger.ts +3 -3
  121. package/template/server/src/libs/safe-http.ts +58 -18
  122. package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
  123. package/template/server/src/libs/storage/file-storage.service.ts +59 -109
  124. package/template/server/src/libs/storage/file-validator.ts +2 -1
  125. package/template/server/src/libs/url-safety.ts +10 -2
  126. package/template/server/src/libs/validation-errors.ts +11 -8
  127. package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
  128. package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
  129. package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
  130. package/template/server/src/modules/admin/admin.controller.ts +4 -4
  131. package/template/server/src/modules/admin/admin.repo.ts +37 -54
  132. package/template/server/src/modules/admin/admin.routes.ts +3 -5
  133. package/template/server/src/modules/admin/admin.schemas.ts +3 -6
  134. package/template/server/src/modules/admin/admin.service.ts +61 -62
  135. package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
  136. package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
  137. package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
  138. package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
  139. package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
  140. package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
  141. package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
  142. package/template/server/src/modules/auth/auth-link-store.ts +64 -0
  143. package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
  144. package/template/server/src/modules/auth/auth.controller.ts +16 -5
  145. package/template/server/src/modules/auth/auth.repo.ts +152 -61
  146. package/template/server/src/modules/auth/auth.routes.ts +4 -0
  147. package/template/server/src/modules/auth/auth.schemas.ts +7 -3
  148. package/template/server/src/modules/auth/auth.service.ts +33 -237
  149. package/template/server/src/modules/auth/recovery.queue.ts +44 -0
  150. package/template/server/src/modules/auth/recovery.store.ts +7 -0
  151. package/template/server/src/modules/auth/session.repo.ts +5 -4
  152. package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
  153. package/template/server/src/modules/files/files.controller.ts +2 -2
  154. package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
  155. package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
  156. package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
  157. package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
  158. package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
  159. package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
  160. package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
  161. package/template/server/src/modules/users/users.controller.ts +28 -25
  162. package/template/server/src/modules/users/users.repo.ts +12 -51
  163. package/template/server/src/modules/users/users.service.ts +109 -234
  164. package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
  165. package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
  166. package/template/server/src/test/setup.ts +4 -0
@@ -0,0 +1,22 @@
1
+ // An immutable contribution from one process and flush batch.
2
+ model DiagnosticBucket {
3
+ id String @id @db.Char(64)
4
+ bucketStart DateTime @map("bucket_start") @db.DateTime(3)
5
+ hourStart DateTime @map("hour_start") @db.DateTime(3)
6
+ groupId String @map("group_id") @db.Char(64)
7
+ severity String @db.VarChar(8)
8
+ source String @db.VarChar(12)
9
+ label String @db.VarChar(191)
10
+ code String? @db.VarChar(64)
11
+ message String @db.VarChar(255)
12
+ frames Json
13
+ occurrences Int @db.UnsignedInt
14
+ firstSeen DateTime @map("first_seen") @db.DateTime(3)
15
+ lastSeen DateTime @map("last_seen") @db.DateTime(3)
16
+ release String? @db.VarChar(64)
17
+
18
+ @@index([bucketStart, severity, groupId])
19
+ @@index([hourStart, severity, groupId])
20
+ @@index([groupId, bucketStart])
21
+ @@map("diagnostic_buckets")
22
+ }
@@ -0,0 +1,24 @@
1
+ -- The fixed projection lets a read-only principal hold SELECT on the view
2
+ -- alone. Run under the application's stable, schema-scoped migration account.
3
+ -- Both equality filters are window partition columns so MySQL can push them
4
+ -- down into the indexed aggregation. The sample tie breaks on immutable ID.
5
+ CREATE OR REPLACE SQL SECURITY DEFINER VIEW `diagnostic_hourly_top` AS
6
+ WITH summaries AS (
7
+ SELECT hour_start, severity, group_id,
8
+ CAST(SUM(occurrences) AS UNSIGNED) AS occurrence_count,
9
+ MIN(first_seen) AS first_seen, MAX(last_seen) AS last_seen,
10
+ MAX(CONCAT(DATE_FORMAT(last_seen, '%Y%m%d%H%i%s%f'), id)) AS sample_position
11
+ FROM diagnostic_buckets
12
+ GROUP BY hour_start, severity, group_id
13
+ ), ranked AS (
14
+ SELECT summaries.*, ROW_NUMBER() OVER (
15
+ PARTITION BY hour_start, severity ORDER BY occurrence_count DESC, group_id ASC
16
+ ) AS group_rank
17
+ FROM summaries
18
+ )
19
+ SELECT ranked.hour_start, ranked.severity, ranked.group_rank, ranked.group_id,
20
+ ranked.occurrence_count, ranked.first_seen, ranked.last_seen,
21
+ sample.source, sample.label, sample.code, sample.message, sample.frames, sample.release
22
+ FROM ranked
23
+ JOIN diagnostic_buckets AS sample ON sample.id = RIGHT(ranked.sample_position, 64)
24
+ WHERE ranked.group_rank <= 10;
@@ -0,0 +1,20 @@
1
+ CREATE TABLE `diagnostic_buckets` (
2
+ `id` CHAR(64) NOT NULL,
3
+ `bucket_start` DATETIME(3) NOT NULL,
4
+ `hour_start` DATETIME(3) NOT NULL,
5
+ `group_id` CHAR(64) NOT NULL,
6
+ `severity` VARCHAR(8) NOT NULL,
7
+ `source` VARCHAR(12) NOT NULL,
8
+ `label` VARCHAR(191) NOT NULL,
9
+ `code` VARCHAR(64) NULL,
10
+ `message` VARCHAR(255) NOT NULL,
11
+ `frames` JSON NOT NULL,
12
+ `occurrences` INTEGER UNSIGNED NOT NULL,
13
+ `first_seen` DATETIME(3) NOT NULL,
14
+ `last_seen` DATETIME(3) NOT NULL,
15
+ `release` VARCHAR(64) NULL,
16
+ INDEX `diagnostic_buckets_bucket_start_severity_group_id_idx`(`bucket_start`, `severity`, `group_id`),
17
+ INDEX `diagnostic_buckets_hour_start_severity_group_id_idx`(`hour_start`, `severity`, `group_id`),
18
+ INDEX `diagnostic_buckets_group_id_bucket_start_idx`(`group_id`, `bucket_start`),
19
+ PRIMARY KEY (`id`)
20
+ ) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -0,0 +1,72 @@
1
+ import { expect, it } from 'vitest';
2
+ import { DiagnosticCollector, type DiagnosticBucket } from '../diagnostics.collector.js';
3
+ import { diagnosticSample } from '../diagnostics.sample.js';
4
+
5
+ const start = Date.UTC(2026, 6, 20, 12);
6
+ const context = { severity: 'error', source: 'request', label: 'GET /fixture/:id' } as const;
7
+
8
+ function failedLookup(text: string): Error {
9
+ return Object.assign(new Error(text), { code: 'ETIMEDOUT' });
10
+ }
11
+
12
+ it('keeps safe diagnostic messages and application frames while ignoring variable error text', () => {
13
+ const secret = 'fixture-customer@example.test https://private.example/?token=fake';
14
+ const first = diagnosticSample(context, failedLookup(secret));
15
+ const second = diagnosticSample(context, failedLookup('other private input'));
16
+ expect(first.groupId).toBe(second.groupId);
17
+ expect(first.message).toBe('A dependency operation timed out');
18
+ expect(first.frames[0].file).toBe('src/modules/diagnostics/__tests__/diagnostics.collector.test.ts');
19
+ expect(JSON.stringify(first)).not.toContain(secret);
20
+ const unknown = diagnosticSample(context, new Error(`raw message ${secret}`));
21
+ expect(unknown.message).toBe('Unexpected request failure');
22
+ expect(JSON.stringify(unknown)).not.toContain(secret);
23
+ expect(unknown.groupId).not.toBe(first.groupId);
24
+ });
25
+
26
+ it('retries the same sealed contribution and keeps replicas and time windows independent', async () => {
27
+ let now = start;
28
+ const stored = new Map<string, DiagnosticBucket>();
29
+ let disconnectAfterCommit = true;
30
+ const write = async (rows: DiagnosticBucket[]): Promise<void> => {
31
+ for (const row of rows) if (!stored.has(row.id)) stored.set(row.id, row);
32
+ if (disconnectAfterCommit) {
33
+ disconnectAfterCommit = false;
34
+ throw new Error('connection closed after commit');
35
+ }
36
+ };
37
+ const first = new DiagnosticCollector(write, { clock: (): number => now, release: 'abcdef0' });
38
+ const replica = new DiagnosticCollector(write, { clock: (): number => now, release: null });
39
+ const sample = diagnosticSample(context, failedLookup('fixture'));
40
+ first.record(sample);
41
+ now += 100;
42
+ first.record(sample);
43
+ await expect(first.flush()).rejects.toThrow('after commit');
44
+ replica.record(sample);
45
+ await Promise.all([first.flush(), replica.flush()]);
46
+ expect(stored.size).toBe(2);
47
+ expect([...stored.values()].map(({ occurrences }) => occurrences).sort()).toEqual([1, 2]);
48
+ const row = [...stored.values()].find(({ release }) => release === 'abcdef0');
49
+ expect(row).toMatchObject({ firstSeen: new Date(start), lastSeen: new Date(start + 100), hourStart: new Date(start) });
50
+ now += 300_000;
51
+ first.record(sample);
52
+ await first.close();
53
+ expect([...stored.values()].map(({ bucketStart }) => +bucketStart).sort()).toEqual([start, start, start + 300_000]);
54
+ });
55
+
56
+ it('caps outage buffering while preserving queued contributions', async () => {
57
+ let failing = true;
58
+ const counts: number[] = [];
59
+ const collector = new DiagnosticCollector(async (rows) => {
60
+ if (failing) throw new Error('offline');
61
+ counts.push(...rows.map(({ occurrences }) => occurrences));
62
+ }, { clock: (): number => start, release: null, maxPending: 1, maxSeries: 1 });
63
+ const sample = diagnosticSample(context, failedLookup('fixture'));
64
+ collector.record(sample);
65
+ await expect(collector.flush()).rejects.toThrow('offline');
66
+ for (let i = 0; i < 30; i++) collector.record(sample);
67
+ await expect(collector.flush()).rejects.toThrow('offline');
68
+ failing = false;
69
+ await collector.close();
70
+ expect(counts).toEqual([1]);
71
+ expect(collector.droppedSamples).toBe(30);
72
+ });
@@ -0,0 +1,51 @@
1
+ import Fastify from 'fastify';
2
+ import { expect, it } from 'vitest';
3
+ import { DiagnosticCollector, type DiagnosticBucket } from '../diagnostics.collector.js';
4
+ import { bindDiagnostics, captureJobFailure, captureRequestFailure, recordDiagnostic, withDiagnosticJob } from '../diagnostics.context.js';
5
+ import { diagnosticsQuerySchema } from '../diagnostics.schemas.js';
6
+
7
+ it('isolates requests and nested jobs and excludes the diagnostic read path', async () => {
8
+ const rows: DiagnosticBucket[] = [];
9
+ const app = Fastify();
10
+ const collector = new DiagnosticCollector(async (batch) => { rows.push(...batch); }, { release: null });
11
+ bindDiagnostics(app, collector);
12
+ const shared = new Error('private dependency text');
13
+ app.get('/feature/:id', async () => {
14
+ recordDiagnostic({ severity: 'error', operation: 'feature.lookup', reason: 'DEPENDENCY_TIMEOUT', error: shared });
15
+ captureRequestFailure(shared);
16
+ return { ok: true };
17
+ });
18
+ app.get('/api/v1/admin/diagnostics', async () => {
19
+ captureRequestFailure(shared);
20
+ recordDiagnostic({ severity: 'warning', operation: 'read.failure', reason: 'DATABASE_UNAVAILABLE' });
21
+ return { ok: true };
22
+ });
23
+ await app.register(async (child) => {
24
+ await withDiagnosticJob(child, 'child-job', async () => {
25
+ captureJobFailure(shared);
26
+ captureJobFailure(shared);
27
+ });
28
+ });
29
+ await Promise.all([app.inject('/feature/a'), app.inject('/feature/b'), app.inject('/api/v1/admin/diagnostics')]);
30
+ await withDiagnosticJob(app, 'diagnostics-flush', async () => { captureJobFailure(shared); });
31
+ await collector.close();
32
+ await app.close();
33
+ expect(rows.map(({ label, occurrences }) => [label, occurrences]).sort()).toEqual([
34
+ ['child-job', 1], ['feature.lookup', 2],
35
+ ]);
36
+ });
37
+
38
+ it('validates equivalent timestamps and rejects malformed or oversized inputs', () => {
39
+ const query = { from: '2026-07-21T16:00:00+04:00', to: '2026-07-21T13:00:00Z' };
40
+ const parsed = diagnosticsQuerySchema.parse(query);
41
+ expect(parsed.from.toISOString()).toBe('2026-07-21T12:00:00.000Z');
42
+ expect(parsed.limit).toBe(20);
43
+ const cursor = Buffer.from(JSON.stringify([3, 'a'.repeat(64)])).toString('base64url');
44
+ expect(diagnosticsQuerySchema.parse({ ...query, cursor }).cursor).toEqual([3, 'a'.repeat(64)]);
45
+ for (const invalid of [
46
+ { from: '2026-07-21T16:01:00+04:00' }, { from: '2026-07-21T12:00:00' },
47
+ { to: '2026-07-21T11:00:00Z' }, { to: '2026-07-29T12:00:00Z' },
48
+ { limit: '0' }, { limit: '1000' }, { severity: 'info' }, { groupId: 'unknown' },
49
+ { cursor: '*'.repeat(200) }, { cursor: 'broken' }, { unknown: 'field' },
50
+ ]) expect(diagnosticsQuerySchema.safeParse({ ...query, ...invalid }).success).toBe(false);
51
+ });
@@ -0,0 +1,123 @@
1
+ import { afterAll, beforeAll, expect, it, vi } from 'vitest';
2
+ import { Prisma } from '@prisma/client';
3
+ import type { FastifyInstance } from 'fastify';
4
+ import { buildTestApp, db, registerAdmin, registerUser } from '@/test/integration-helpers.js';
5
+
6
+ let app: FastifyInstance;
7
+ const base = '/api/v1/admin/diagnostics';
8
+ const from = '2026-07-20T12:00:00Z';
9
+ const to = '2026-07-20T13:00:00Z';
10
+ const url = `${base}?from=${from}&to=${to}`;
11
+
12
+ beforeAll(async () => { app = await buildTestApp(); });
13
+ afterAll(async () => { await app?.close(); });
14
+
15
+ it('allows only administrators to read stored diagnostics and validates bounded windows', async () => {
16
+ const user = await registerUser(app, 'diagnostics-user');
17
+ const admin = await registerAdmin(app, 'diagnostics-admin');
18
+
19
+ expect((await app.inject(url)).statusCode).toBe(401);
20
+ expect((await app.inject({ url, headers: { cookie: user.jar.header() } })).statusCode).toBe(403);
21
+ const headers = { cookie: admin.jar.header() };
22
+ const read = await app.inject({ url, headers });
23
+ expect(read.statusCode).toBe(200);
24
+ expect(read.headers['cache-control']).toBe('private, no-store');
25
+ expect(read.json().data).toEqual({ groups: [], nextCursor: null });
26
+ for (const query of [
27
+ `from=invalid&to=${to}`,
28
+ `from=2026-07-20T12:01:00Z&to=${to}`,
29
+ `from=2026-07-20T12:00:00&to=${to}`,
30
+ `from=${from}&to=2026-08-01T13:00:00Z`,
31
+ `from=${from}&to=${to}&limit=101`,
32
+ `from=${from}&to=${to}&cursor=broken`,
33
+ ]) expect((await app.inject({ url: `${base}?${query}`, headers })).statusCode).toBe(422);
34
+ });
35
+
36
+ it('returns a safe retryable error when MySQL cancels an expensive diagnostic query', async () => {
37
+ const { prisma } = await import('@libs/prisma.js');
38
+ const admin = await registerAdmin(app, 'diagnostics-timeout');
39
+ const query = vi.spyOn(prisma, '$queryRaw').mockRejectedValueOnce(new Prisma.PrismaClientKnownRequestError('Fixture private detail', {
40
+ code: 'P2010', clientVersion: 'fixture', meta: { code: '3024' },
41
+ }));
42
+ try {
43
+ const read = await app.inject({ url, headers: { cookie: admin.jar.header() } });
44
+ expect(query.mock.calls[0]?.[0].toString()).toContain('MAX_EXECUTION_TIME(1500)');
45
+ expect(read.statusCode).toBe(503);
46
+ expect(read.json().error.code).toBe('DIAGNOSTICS_QUERY_TIMEOUT');
47
+ expect(read.body).not.toContain('Fixture private detail');
48
+ } finally { query.mockRestore(); }
49
+ });
50
+
51
+ it('stores typed failures and jobs once and ignores expected errors and raw messages', async () => {
52
+ const { buildApp } = await import('@/app.js');
53
+ const { startRecurringJob } = await import('@/jobs/schedule.js');
54
+ const { ServiceUnavailableError, NotFoundError } = await import('@shared/errors/errors.js');
55
+ const { recordDiagnostic } = await import('../diagnostics.context.js');
56
+ const fixture = await buildApp();
57
+ const privateInput = 'fixture-user@example.test';
58
+ const sharedError = new ServiceUnavailableError();
59
+ fixture.get('/diagnostics-fixture/:id', async () => {
60
+ recordDiagnostic({ severity: 'error', operation: 'fixture.lookup', reason: 'SERVICE_UNAVAILABLE', error: sharedError });
61
+ throw sharedError;
62
+ });
63
+ fixture.get('/diagnostics-fixture-typed', async () => { throw new ServiceUnavailableError(); });
64
+ fixture.get('/diagnostics-fixture-warning', async () => {
65
+ recordDiagnostic({ severity: 'warning', operation: 'fixture.retry', reason: 'DEPENDENCY_TIMEOUT' });
66
+ throw new NotFoundError();
67
+ });
68
+ let signal!: () => void;
69
+ const ran = new Promise<void>((resolve) => { signal = resolve; });
70
+ startRecurringJob(fixture, { name: 'diagnostics-fixture-job', firstRunDelayMs: 5, intervalMs: 600_000, run: async () => {
71
+ signal();
72
+ throw new Error(privateInput);
73
+ } });
74
+ try {
75
+ expect((await fixture.inject('/diagnostics-fixture/a?private=one')).statusCode).toBe(503);
76
+ expect((await fixture.inject('/diagnostics-fixture/b')).statusCode).toBe(503);
77
+ expect((await fixture.inject('/diagnostics-fixture-typed')).statusCode).toBe(503);
78
+ expect((await fixture.inject('/diagnostics-fixture-warning')).statusCode).toBe(404);
79
+ await ran;
80
+ } finally { await fixture.close(); }
81
+ const rows = await (await db()).diagnosticBucket.findMany({ where: { label: { in: [
82
+ 'fixture.lookup', 'fixture.retry', 'diagnostics-fixture-job',
83
+ 'GET /diagnostics-fixture/:id', 'GET /diagnostics-fixture-typed', 'GET /diagnostics-fixture-warning',
84
+ ] } } });
85
+ expect(rows.map(({ label, occurrences, severity }) => [label, occurrences, severity]).sort()).toEqual([
86
+ ['GET /diagnostics-fixture-typed', 1, 'error'], ['diagnostics-fixture-job', 1, 'error'],
87
+ ['fixture.lookup', 2, 'error'], ['fixture.retry', 1, 'warning'],
88
+ ]);
89
+ expect(JSON.stringify(rows)).not.toContain(privateInput);
90
+ expect(rows.find(({ label }) => label === 'diagnostics-fixture-job')?.message).toBe('Unexpected job failure');
91
+ });
92
+
93
+ it('returns stable pages and agrees with the indexed hourly top view', async () => {
94
+ const prisma = await db();
95
+ const start = new Date('2026-07-21T12:00:00Z');
96
+ const end = new Date('2026-07-21T13:00:00Z');
97
+ const { persistDiagnosticBuckets } = await import('../diagnostics.repo.js');
98
+ const fixtures = Array.from({ length: 12 }, (_, i) => ({
99
+ id: (i + 40).toString(16).padStart(64, '0'), groupId: i.toString(16).padStart(64, '0'),
100
+ hourStart: start, bucketStart: start, firstSeen: start, lastSeen: start,
101
+ label: `fixture-${i}`, source: 'job' as const, severity: 'error' as const, code: null,
102
+ occurrences: i < 2 ? 5 : 1, message: 'Unexpected job failure', frames: [], release: null,
103
+ }));
104
+ const newer = { ...fixtures[0], id: 'a'.repeat(64), lastSeen: new Date(+start + 50), occurrences: 3, release: 'abcdef0' };
105
+ const boundary = { ...fixtures[0], id: 'b'.repeat(64), bucketStart: end, hourStart: end, firstSeen: end, lastSeen: end };
106
+ await Promise.all([persistDiagnosticBuckets([...fixtures, boundary]), persistDiagnosticBuckets([newer])]);
107
+ await persistDiagnosticBuckets([newer]);
108
+ const admin = await registerAdmin(app, 'diagnostics-page');
109
+ const headers = { cookie: admin.jar.header() };
110
+ const query = new URLSearchParams({ from: '2026-07-21T16:00:00+04:00', to: end.toISOString(), severity: 'error', limit: '10' });
111
+ const first = (await app.inject({ url: `${base}?${query}`, headers })).json().data;
112
+ expect(first.groups.map(({ count }: { count: number }) => count)).toEqual([8, 5, 1, 1, 1, 1, 1, 1, 1, 1]);
113
+ expect(first.groups[0]).toMatchObject({ groupId: fixtures[0].groupId, rank: 1, release: 'abcdef0' });
114
+ query.set('cursor', first.nextCursor);
115
+ const second = (await app.inject({ url: `${base}?${query}`, headers })).json().data;
116
+ expect(second.groups.map(({ rank }: { rank: number }) => rank)).toEqual([11, 12]);
117
+ expect(second.nextCursor).toBeNull();
118
+ const rows = await prisma.$queryRaw<{ group_id: string; occurrence_count: bigint }[]>`
119
+ SELECT group_id, occurrence_count FROM diagnostic_hourly_top
120
+ WHERE hour_start = ${start} AND severity = 'error' ORDER BY group_rank`;
121
+ expect(rows.map(({ group_id, occurrence_count }) => [group_id, Number(occurrence_count)]))
122
+ .toEqual(first.groups.map(({ groupId, count }: { groupId: string; count: number }) => [groupId, count]));
123
+ });
@@ -0,0 +1,31 @@
1
+ import Fastify from 'fastify';
2
+ import { expect, it, vi } from 'vitest';
3
+ import { recordDiagnostic } from '../diagnostics.context.js';
4
+ import type { DiagnosticBucket } from '../diagnostics.collector.js';
5
+ import { registerDiagnostics } from '../diagnostics.service.js';
6
+
7
+ const store = vi.hoisted(() => ({ write: vi.fn<(rows: DiagnosticBucket[]) => Promise<void>>() }));
8
+ vi.mock('../diagnostics.repo.js', () => ({ persistDiagnosticBuckets: store.write }));
9
+
10
+ it('returns healthy replies while an unavailable store cannot hold shutdown open', async () => {
11
+ const app = Fastify();
12
+ registerDiagnostics(app);
13
+ app.get('/warning', async () => {
14
+ recordDiagnostic({ severity: 'warning', operation: 'fixture.retry', reason: 'DEPENDENCY_TIMEOUT' });
15
+ return { ok: true };
16
+ });
17
+ store.write.mockImplementationOnce(() => new Promise<void>(() => {}));
18
+ expect((await app.inject('/warning')).statusCode).toBe(200);
19
+ expect(store.write).not.toHaveBeenCalled();
20
+
21
+ let timeout: ReturnType<typeof setTimeout> | undefined;
22
+ try {
23
+ await Promise.race([
24
+ app.close(),
25
+ new Promise<never>((_resolve, reject) => {
26
+ timeout = setTimeout(() => reject(new Error('Shutdown blocked on the store')), 5_000);
27
+ }),
28
+ ]);
29
+ } finally { clearTimeout(timeout); }
30
+ expect(store.write).toHaveBeenCalledTimes(1);
31
+ });
@@ -0,0 +1,95 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import type { DiagnosticSample } from './diagnostics.sample.js';
3
+
4
+ export const DIAGNOSTIC_WINDOW_MS = 5 * 60_000;
5
+ const HOUR_MS = 60 * 60_000;
6
+
7
+ export interface DiagnosticBucket extends DiagnosticSample {
8
+ id: string;
9
+ bucketStart: Date;
10
+ hourStart: Date;
11
+ firstSeen: Date;
12
+ lastSeen: Date;
13
+ occurrences: number;
14
+ release: string | null;
15
+ }
16
+
17
+ type Contribution = Omit<DiagnosticBucket, 'id' | 'release'>;
18
+ type Writer = (rows: DiagnosticBucket[]) => Promise<void>;
19
+ interface CollectorOptions {
20
+ clock?: () => number;
21
+ release: string | null;
22
+ maxPending?: number;
23
+ maxSeries?: number;
24
+ }
25
+
26
+ /** A short flush can seal part of a five-minute window. Its process and batch
27
+ * identity stay fixed across retries, while later contributions remain additive. */
28
+ export class DiagnosticCollector {
29
+ private readonly instance = randomUUID();
30
+ private readonly active = new Map<string, Contribution>();
31
+ private readonly pending: DiagnosticBucket[][] = [];
32
+ private readonly clock: () => number;
33
+ private readonly maxPending: number;
34
+ private readonly maxSeries: number;
35
+ private sequence = 0;
36
+ private writing: Promise<void> | undefined;
37
+ private closed = false;
38
+ droppedSamples = 0;
39
+
40
+ constructor(private readonly write: Writer, private readonly options: CollectorOptions) {
41
+ this.clock = options.clock ?? Date.now;
42
+ this.maxPending = options.maxPending ?? 2;
43
+ this.maxSeries = options.maxSeries ?? 256;
44
+ }
45
+
46
+ record(sample: DiagnosticSample): void {
47
+ if (this.closed) return;
48
+ if (this.pending.length >= this.maxPending) {
49
+ this.droppedSamples++;
50
+ return;
51
+ }
52
+ const now = this.clock();
53
+ const start = Math.floor(now / DIAGNOSTIC_WINDOW_MS) * DIAGNOSTIC_WINDOW_MS;
54
+ const key = `${start}:${sample.groupId}`;
55
+ const current = this.active.get(key);
56
+ const seen = new Date(now);
57
+ if (current) {
58
+ current.occurrences++;
59
+ if (seen < current.firstSeen) current.firstSeen = seen;
60
+ if (seen >= current.lastSeen) Object.assign(current, sample, { lastSeen: seen });
61
+ } else if (this.active.size < this.maxSeries) {
62
+ this.active.set(key, {
63
+ ...sample, bucketStart: new Date(start), hourStart: new Date(Math.floor(now / HOUR_MS) * HOUR_MS),
64
+ firstSeen: seen, lastSeen: seen, occurrences: 1,
65
+ });
66
+ } else {
67
+ this.droppedSamples++;
68
+ }
69
+ }
70
+
71
+ flush(): Promise<void> {
72
+ if (this.writing) return this.writing;
73
+ if (this.active.size && this.pending.length < this.maxPending) {
74
+ const sequence = this.sequence++;
75
+ this.pending.push([...this.active].map(([key, sample]) => ({
76
+ ...sample,
77
+ id: createHash('sha256').update(`${this.instance}:${sequence}:${key}`).digest('hex'),
78
+ release: this.options.release,
79
+ })));
80
+ this.active.clear();
81
+ }
82
+ const batch = this.pending[0];
83
+ if (!batch) return Promise.resolve();
84
+ this.writing = Promise.resolve().then(() => this.write(batch)).then(() => {
85
+ this.pending.shift();
86
+ }).finally(() => { this.writing = undefined; });
87
+ return this.writing;
88
+ }
89
+
90
+ /** Stop taking samples before draining. The caller owns the shutdown deadline. */
91
+ async close(signal?: AbortSignal): Promise<void> {
92
+ this.closed = true;
93
+ while ((this.pending.length || this.active.size) && !signal?.aborted) await this.flush();
94
+ }
95
+ }
@@ -0,0 +1,73 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import type { FastifyInstance } from 'fastify';
3
+ import type { DiagnosticCollector } from './diagnostics.collector.js';
4
+ import { diagnosticSample, type DiagnosticContext, type DiagnosticReason } from './diagnostics.sample.js';
5
+
6
+ interface Scope {
7
+ collector: DiagnosticCollector;
8
+ label: string;
9
+ source: 'request' | 'job';
10
+ captured: WeakSet<object>;
11
+ }
12
+
13
+ const scopes = new AsyncLocalStorage<Scope | undefined>();
14
+ const collectorDecorator = Symbol('diagnosticsCollector');
15
+
16
+ export const DIAGNOSTICS_PATH = '/admin/diagnostics';
17
+
18
+ export function bindDiagnostics(app: FastifyInstance, collector: DiagnosticCollector): void {
19
+ // Fastify inherits decorators into child plugin scopes, including jobs
20
+ // that are registered by a future feature plugin.
21
+ app.decorate(collectorDecorator, collector);
22
+ app.addHook('onRequest', (request, _reply, done) => {
23
+ const route = request.routeOptions.url;
24
+ // Suppress the whole scope so explicit captures in the read path are also excluded.
25
+ if (route === DIAGNOSTICS_PATH || route === `/api/v1${DIAGNOSTICS_PATH}`) {
26
+ return scopes.run(undefined, done);
27
+ }
28
+ const label = route && route.length <= 170 && !request.is404 ? route : '(unmatched)';
29
+ scopes.run({ collector, label: `${request.method} ${label}`, source: 'request', captured: new WeakSet() }, done);
30
+ });
31
+ }
32
+
33
+ export function withDiagnosticJob<T>(app: FastifyInstance, name: string, run: () => T): T {
34
+ // The scheduler also accepts thin app adapters that only manage onClose.
35
+ if (name === 'diagnostics-flush' || !app.hasDecorator?.(collectorDecorator)) return scopes.run(undefined, run);
36
+ const collector = app.getDecorator<DiagnosticCollector>(collectorDecorator);
37
+ const label = /^[a-z][a-z0-9._-]{0,79}$/.test(name) ? name : '(unnamed job)';
38
+ return scopes.run({ collector, label, source: 'job', captured: new WeakSet() }, run);
39
+ }
40
+
41
+ function capture(scope: Scope, context: DiagnosticContext, error?: unknown, reason?: DiagnosticReason): void {
42
+ const track = context.severity === 'error' && typeof error === 'object' && error !== null;
43
+ if (track && scope.captured.has(error)) return;
44
+ try {
45
+ scope.collector.record(diagnosticSample(context, error, reason));
46
+ // Scope deduplication to one request or run. A reused Error in another
47
+ // request is another occurrence. Weak references let long jobs release errors.
48
+ if (track) scope.captured.add(error);
49
+ } catch {
50
+ // Diagnostics must never alter the request or job, even if an error
51
+ // supplies a throwing accessor in place of ordinary stack properties.
52
+ }
53
+ }
54
+
55
+ export function captureRequestFailure(error: unknown): void {
56
+ const scope = scopes.getStore();
57
+ if (scope?.source === 'request') capture(scope, { severity: 'error', source: 'request', label: scope.label }, error);
58
+ }
59
+
60
+ export function captureJobFailure(error: unknown): void {
61
+ const scope = scopes.getStore();
62
+ if (scope?.source === 'job') capture(scope, { severity: 'error', source: 'job', label: scope.label }, error);
63
+ }
64
+
65
+ /** Use a static operation label and a reason from diagnosticMessages. Pass
66
+ * the same Error if it may be rethrown so automatic capture can deduplicate it. */
67
+ export function recordDiagnostic(input: {
68
+ severity: 'error' | 'warning'; operation: string; reason: DiagnosticReason; error?: unknown;
69
+ }): void {
70
+ const scope = scopes.getStore();
71
+ if (!scope || !/^[a-z][a-z0-9._-]{0,79}$/.test(input.operation)) return;
72
+ capture(scope, { severity: input.severity, source: 'operation', label: input.operation }, input.error ?? new Error(), input.reason);
73
+ }
@@ -0,0 +1,79 @@
1
+ import { Prisma } from '@prisma/client';
2
+ import { prisma } from '@libs/prisma.js';
3
+ import { ServiceUnavailableError } from '@shared/errors/errors.js';
4
+ import type { DiagnosticBucket } from './diagnostics.collector.js';
5
+ import type { DiagnosticFrame, DiagnosticSeverity, DiagnosticSource } from './diagnostics.sample.js';
6
+ import type { DiagnosticsQuery } from './diagnostics.schemas.js';
7
+
8
+ export async function persistDiagnosticBuckets(rows: DiagnosticBucket[]): Promise<void> {
9
+ // A lost acknowledgement may follow a successful commit. The original
10
+ // contribution IDs are unique, so retrying the batch leaves counts intact.
11
+ await prisma.$transaction(async (tx) => {
12
+ await tx.diagnosticBucket.createMany({
13
+ data: rows.map(({ frames, ...row }) => ({ ...row, frames: frames.map((frame) => ({ ...frame })) })),
14
+ skipDuplicates: true,
15
+ });
16
+ }, { maxWait: 300, timeout: 1_200 });
17
+ }
18
+
19
+ interface DiagnosticGroup {
20
+ rank: number;
21
+ groupId: string;
22
+ count: number;
23
+ firstSeen: Date;
24
+ lastSeen: Date;
25
+ severity: DiagnosticSeverity;
26
+ source: DiagnosticSource;
27
+ label: string;
28
+ code: string | null;
29
+ message: string;
30
+ frames: DiagnosticFrame[];
31
+ release: string | null;
32
+ }
33
+ type RankedRow = Omit<DiagnosticGroup, 'count' | 'rank'> & { occurrenceCount: bigint; groupRank: bigint };
34
+
35
+ export async function readDiagnosticGroups(query: DiagnosticsQuery): Promise<{
36
+ groups: DiagnosticGroup[]; nextCursor: string | null;
37
+ }> {
38
+ const { from, to, severity, groupId, limit, cursor } = query;
39
+ // LIMIT bounds the response. The optimizer hint bounds the aggregation
40
+ // that MySQL has to complete before it can return that response.
41
+ const rows = await prisma.$queryRaw<RankedRow[]>`
42
+ WITH summaries AS (
43
+ SELECT group_id, CAST(SUM(occurrences) AS UNSIGNED) AS occurrence_count,
44
+ MIN(first_seen) AS first_seen, MAX(last_seen) AS last_seen,
45
+ MAX(CONCAT(DATE_FORMAT(last_seen, '%Y%m%d%H%i%s%f'), id)) AS sample_position
46
+ FROM diagnostic_buckets
47
+ WHERE bucket_start >= ${from} AND bucket_start < ${to}
48
+ ${severity ? Prisma.sql`AND severity = ${severity}` : Prisma.empty}
49
+ ${groupId ? Prisma.sql`AND group_id = ${groupId}` : Prisma.empty}
50
+ GROUP BY group_id
51
+ ), ranked AS (
52
+ SELECT summaries.*, ROW_NUMBER() OVER (ORDER BY occurrence_count DESC, group_id ASC) AS group_rank
53
+ FROM summaries
54
+ )
55
+ SELECT /*+ MAX_EXECUTION_TIME(1500) */ ranked.group_rank AS groupRank,
56
+ ranked.group_id AS groupId, ranked.occurrence_count AS occurrenceCount,
57
+ ranked.first_seen AS firstSeen, ranked.last_seen AS lastSeen,
58
+ sample.severity, sample.source, sample.label, sample.code, sample.message, sample.frames, sample.release
59
+ FROM ranked
60
+ JOIN diagnostic_buckets AS sample ON sample.id = RIGHT(ranked.sample_position, 64)
61
+ ${cursor ? Prisma.sql`WHERE ranked.occurrence_count < ${cursor[0]}
62
+ OR (ranked.occurrence_count = ${cursor[0]} AND ranked.group_id > ${cursor[1]})` : Prisma.empty}
63
+ ORDER BY ranked.group_rank ASC
64
+ LIMIT ${limit + 1}`.catch((error: unknown) => {
65
+ // Prisma wraps MySQL's statement-timeout code in raw-query metadata.
66
+ if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2010' && String(error.meta?.code) === '3024') {
67
+ throw new ServiceUnavailableError('Diagnostics query timed out. Try a narrower interval.', 'DIAGNOSTICS_QUERY_TIMEOUT');
68
+ }
69
+ throw error;
70
+ });
71
+ const groups = rows.slice(0, limit).map(({ groupRank, occurrenceCount, ...row }) => ({
72
+ ...row, rank: Number(groupRank), count: Number(occurrenceCount),
73
+ }));
74
+ const last = groups.at(-1);
75
+ return {
76
+ groups,
77
+ nextCursor: last && rows.length > limit ? Buffer.from(JSON.stringify([last.count, last.groupId])).toString('base64url') : null,
78
+ };
79
+ }
@@ -0,0 +1,16 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import { RATE_LIMITS } from '@config/rate-limit.config.js';
3
+ import { successResponse } from '@shared/responses/successResponse.js';
4
+ import { DIAGNOSTICS_PATH } from './diagnostics.context.js';
5
+ import { readDiagnosticGroups } from './diagnostics.repo.js';
6
+ import { diagnosticsQuerySchema, type DiagnosticsQuery } from './diagnostics.schemas.js';
7
+
8
+ /** Register inside the existing authenticated ADMIN scope. */
9
+ export function registerAdminDiagnosticsRoute(app: FastifyInstance): void {
10
+ app.get<{ Querystring: DiagnosticsQuery }>(DIAGNOSTICS_PATH, {
11
+ schema: { querystring: diagnosticsQuerySchema },
12
+ config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
13
+ }, async (request) => {
14
+ return successResponse('Diagnostic groups', await readDiagnosticGroups(request.query));
15
+ });
16
+ }