create-tigra 4.0.0 → 4.1.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.
- package/CHANGELOG.md +178 -0
- package/README.md +236 -82
- package/bin/create-tigra.js +74 -1
- package/lib/patchers/diagnostics.patcher.js +149 -0
- package/lib/patchers/metrics.patcher.js +145 -0
- package/modules/diagnostics/diagnostics.md +65 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/migration.sql +43 -0
- package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
- package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
- package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +107 -0
- package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
- package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
- package/modules/diagnostics/server/diagnostics.context.ts +73 -0
- package/modules/diagnostics/server/diagnostics.repo.ts +69 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +17 -0
- package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
- package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
- package/modules/diagnostics/server/diagnostics.service.ts +44 -0
- package/modules/metrics/client/WebVitalsReporter.tsx +35 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +65 -0
- package/modules/metrics/client/metrics.pages.ts +5 -0
- package/modules/metrics/performance.md +56 -0
- package/modules/metrics/prisma/metric-bucket.prisma +18 -0
- package/modules/metrics/prisma/migration.sql +17 -0
- package/modules/metrics/server/__tests__/metrics.collector.test.ts +75 -0
- package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
- package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
- package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
- package/modules/metrics/server/metrics.collector.ts +130 -0
- package/modules/metrics/server/metrics.pages.ts +3 -0
- package/modules/metrics/server/metrics.repo.ts +45 -0
- package/modules/metrics/server/metrics.routes.ts +46 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +100 -0
- package/package.json +3 -2
- package/template/AGENTS.md +17 -10
- package/template/README.md +79 -0
- package/template/client/README.md +92 -21
- package/template/client/src/app/focus-rings.policy.test.ts +88 -0
- package/template/client/src/app/globals.css +46 -0
- package/template/client/src/app/layout.tsx +5 -0
- package/template/client/src/app/page.tsx +2 -2
- package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
- package/template/client/src/components/ui/input.tsx +3 -2
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
- package/template/server/README.md +108 -0
- package/template/server/docs/logging.md +16 -2
- package/template/server/docs/testing.md +20 -2
|
@@ -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,107 @@
|
|
|
1
|
+
import { afterAll, beforeAll, expect, it } from 'vitest';
|
|
2
|
+
import type { FastifyInstance } from 'fastify';
|
|
3
|
+
import { buildTestApp, db, registerAdmin, registerUser } from '@/test/integration-helpers.js';
|
|
4
|
+
|
|
5
|
+
let app: FastifyInstance;
|
|
6
|
+
const base = '/api/v1/admin/diagnostics';
|
|
7
|
+
const from = '2026-07-20T12:00:00Z';
|
|
8
|
+
const to = '2026-07-20T13:00:00Z';
|
|
9
|
+
const url = `${base}?from=${from}&to=${to}`;
|
|
10
|
+
|
|
11
|
+
beforeAll(async () => { app = await buildTestApp(); });
|
|
12
|
+
afterAll(async () => { await app?.close(); });
|
|
13
|
+
|
|
14
|
+
it('allows only administrators to read stored diagnostics and validates bounded windows', async () => {
|
|
15
|
+
const user = await registerUser(app, 'diagnostics-user');
|
|
16
|
+
const admin = await registerAdmin(app, 'diagnostics-admin');
|
|
17
|
+
|
|
18
|
+
expect((await app.inject(url)).statusCode).toBe(401);
|
|
19
|
+
expect((await app.inject({ url, headers: { cookie: user.jar.header() } })).statusCode).toBe(403);
|
|
20
|
+
const headers = { cookie: admin.jar.header() };
|
|
21
|
+
const read = await app.inject({ url, headers });
|
|
22
|
+
expect(read.statusCode).toBe(200);
|
|
23
|
+
expect(read.headers['cache-control']).toBe('no-store');
|
|
24
|
+
expect(read.json().data).toEqual({ groups: [], nextCursor: null });
|
|
25
|
+
for (const query of [
|
|
26
|
+
`from=invalid&to=${to}`,
|
|
27
|
+
`from=2026-07-20T12:01:00Z&to=${to}`,
|
|
28
|
+
`from=2026-07-20T12:00:00&to=${to}`,
|
|
29
|
+
`from=${from}&to=2026-08-01T13:00:00Z`,
|
|
30
|
+
`from=${from}&to=${to}&limit=101`,
|
|
31
|
+
`from=${from}&to=${to}&cursor=broken`,
|
|
32
|
+
]) expect((await app.inject({ url: `${base}?${query}`, headers })).statusCode).toBe(422);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('stores typed failures and jobs once and ignores expected errors and raw messages', async () => {
|
|
36
|
+
const { buildApp } = await import('@/app.js');
|
|
37
|
+
const { startRecurringJob } = await import('@/jobs/schedule.js');
|
|
38
|
+
const { ServiceUnavailableError, NotFoundError } = await import('@shared/errors/errors.js');
|
|
39
|
+
const { recordDiagnostic } = await import('../diagnostics.context.js');
|
|
40
|
+
const fixture = await buildApp();
|
|
41
|
+
const privateInput = 'fixture-user@example.test';
|
|
42
|
+
const sharedError = new ServiceUnavailableError();
|
|
43
|
+
fixture.get('/diagnostics-fixture/:id', async () => {
|
|
44
|
+
recordDiagnostic({ severity: 'error', operation: 'fixture.lookup', reason: 'SERVICE_UNAVAILABLE', error: sharedError });
|
|
45
|
+
throw sharedError;
|
|
46
|
+
});
|
|
47
|
+
fixture.get('/diagnostics-fixture-typed', async () => { throw new ServiceUnavailableError(); });
|
|
48
|
+
fixture.get('/diagnostics-fixture-warning', async () => {
|
|
49
|
+
recordDiagnostic({ severity: 'warning', operation: 'fixture.retry', reason: 'DEPENDENCY_TIMEOUT' });
|
|
50
|
+
throw new NotFoundError();
|
|
51
|
+
});
|
|
52
|
+
let signal!: () => void;
|
|
53
|
+
const ran = new Promise<void>((resolve) => { signal = resolve; });
|
|
54
|
+
startRecurringJob(fixture, { name: 'diagnostics-fixture-job', firstRunDelayMs: 5, intervalMs: 600_000, run: async () => {
|
|
55
|
+
signal();
|
|
56
|
+
throw new Error(privateInput);
|
|
57
|
+
} });
|
|
58
|
+
try {
|
|
59
|
+
expect((await fixture.inject('/diagnostics-fixture/a?private=one')).statusCode).toBe(503);
|
|
60
|
+
expect((await fixture.inject('/diagnostics-fixture/b')).statusCode).toBe(503);
|
|
61
|
+
expect((await fixture.inject('/diagnostics-fixture-typed')).statusCode).toBe(503);
|
|
62
|
+
expect((await fixture.inject('/diagnostics-fixture-warning')).statusCode).toBe(404);
|
|
63
|
+
await ran;
|
|
64
|
+
} finally { await fixture.close(); }
|
|
65
|
+
const rows = await (await db()).diagnosticBucket.findMany({ where: { label: { in: [
|
|
66
|
+
'fixture.lookup', 'fixture.retry', 'diagnostics-fixture-job',
|
|
67
|
+
'GET /diagnostics-fixture/:id', 'GET /diagnostics-fixture-typed', 'GET /diagnostics-fixture-warning',
|
|
68
|
+
] } } });
|
|
69
|
+
expect(rows.map(({ label, occurrences, severity }) => [label, occurrences, severity]).sort()).toEqual([
|
|
70
|
+
['GET /diagnostics-fixture-typed', 1, 'error'], ['diagnostics-fixture-job', 1, 'error'],
|
|
71
|
+
['fixture.lookup', 2, 'error'], ['fixture.retry', 1, 'warning'],
|
|
72
|
+
]);
|
|
73
|
+
expect(JSON.stringify(rows)).not.toContain(privateInput);
|
|
74
|
+
expect(rows.find(({ label }) => label === 'diagnostics-fixture-job')?.message).toBe('Unexpected job failure');
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('returns stable pages and agrees with the indexed hourly top view', async () => {
|
|
78
|
+
const prisma = await db();
|
|
79
|
+
const start = new Date('2026-07-21T12:00:00Z');
|
|
80
|
+
const end = new Date('2026-07-21T13:00:00Z');
|
|
81
|
+
const { persistDiagnosticBuckets } = await import('../diagnostics.repo.js');
|
|
82
|
+
const fixtures = Array.from({ length: 12 }, (_, i) => ({
|
|
83
|
+
id: (i + 40).toString(16).padStart(64, '0'), groupId: i.toString(16).padStart(64, '0'),
|
|
84
|
+
hourStart: start, bucketStart: start, firstSeen: start, lastSeen: start,
|
|
85
|
+
label: `fixture-${i}`, source: 'job' as const, severity: 'error' as const, code: null,
|
|
86
|
+
occurrences: i < 2 ? 5 : 1, message: 'Unexpected job failure', frames: [], release: null,
|
|
87
|
+
}));
|
|
88
|
+
const newer = { ...fixtures[0], id: 'a'.repeat(64), lastSeen: new Date(+start + 50), occurrences: 3, release: 'abcdef0' };
|
|
89
|
+
const boundary = { ...fixtures[0], id: 'b'.repeat(64), bucketStart: end, hourStart: end, firstSeen: end, lastSeen: end };
|
|
90
|
+
await Promise.all([persistDiagnosticBuckets([...fixtures, boundary]), persistDiagnosticBuckets([newer])]);
|
|
91
|
+
await persistDiagnosticBuckets([newer]);
|
|
92
|
+
const admin = await registerAdmin(app, 'diagnostics-page');
|
|
93
|
+
const headers = { cookie: admin.jar.header() };
|
|
94
|
+
const query = new URLSearchParams({ from: '2026-07-21T16:00:00+04:00', to: end.toISOString(), severity: 'error', limit: '10' });
|
|
95
|
+
const first = (await app.inject({ url: `${base}?${query}`, headers })).json().data;
|
|
96
|
+
expect(first.groups.map(({ count }: { count: number }) => count)).toEqual([8, 5, 1, 1, 1, 1, 1, 1, 1, 1]);
|
|
97
|
+
expect(first.groups[0]).toMatchObject({ groupId: fixtures[0].groupId, rank: 1, release: 'abcdef0' });
|
|
98
|
+
query.set('cursor', first.nextCursor);
|
|
99
|
+
const second = (await app.inject({ url: `${base}?${query}`, headers })).json().data;
|
|
100
|
+
expect(second.groups.map(({ rank }: { rank: number }) => rank)).toEqual([11, 12]);
|
|
101
|
+
expect(second.nextCursor).toBeNull();
|
|
102
|
+
const rows = await prisma.$queryRaw<{ group_id: string; occurrence_count: bigint }[]>`
|
|
103
|
+
SELECT group_id, occurrence_count FROM diagnostic_hourly_top
|
|
104
|
+
WHERE hour_start = ${start} AND severity = 'error' ORDER BY group_rank`;
|
|
105
|
+
expect(rows.map(({ group_id, occurrence_count }) => [group_id, Number(occurrence_count)]))
|
|
106
|
+
.toEqual(first.groups.map(({ groupId, count }: { groupId: string; count: number }) => [groupId, count]));
|
|
107
|
+
});
|
|
@@ -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,69 @@
|
|
|
1
|
+
import { Prisma } from '@prisma/client';
|
|
2
|
+
import { prisma } from '@libs/prisma.js';
|
|
3
|
+
import type { DiagnosticBucket } from './diagnostics.collector.js';
|
|
4
|
+
import type { DiagnosticFrame, DiagnosticSeverity, DiagnosticSource } from './diagnostics.sample.js';
|
|
5
|
+
import type { DiagnosticsQuery } from './diagnostics.schemas.js';
|
|
6
|
+
|
|
7
|
+
export async function persistDiagnosticBuckets(rows: DiagnosticBucket[]): Promise<void> {
|
|
8
|
+
// A lost acknowledgement may follow a successful commit. The original
|
|
9
|
+
// contribution IDs are unique, so retrying the batch leaves counts intact.
|
|
10
|
+
await prisma.$transaction(async (tx) => {
|
|
11
|
+
await tx.diagnosticBucket.createMany({
|
|
12
|
+
data: rows.map(({ frames, ...row }) => ({ ...row, frames: frames.map((frame) => ({ ...frame })) })),
|
|
13
|
+
skipDuplicates: true,
|
|
14
|
+
});
|
|
15
|
+
}, { maxWait: 300, timeout: 1_200 });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface DiagnosticGroup {
|
|
19
|
+
rank: number;
|
|
20
|
+
groupId: string;
|
|
21
|
+
count: number;
|
|
22
|
+
firstSeen: Date;
|
|
23
|
+
lastSeen: Date;
|
|
24
|
+
severity: DiagnosticSeverity;
|
|
25
|
+
source: DiagnosticSource;
|
|
26
|
+
label: string;
|
|
27
|
+
code: string | null;
|
|
28
|
+
message: string;
|
|
29
|
+
frames: DiagnosticFrame[];
|
|
30
|
+
release: string | null;
|
|
31
|
+
}
|
|
32
|
+
type RankedRow = Omit<DiagnosticGroup, 'count' | 'rank'> & { occurrenceCount: bigint; groupRank: bigint };
|
|
33
|
+
|
|
34
|
+
export async function readDiagnosticGroups(query: DiagnosticsQuery): Promise<{
|
|
35
|
+
groups: DiagnosticGroup[]; nextCursor: string | null;
|
|
36
|
+
}> {
|
|
37
|
+
const { from, to, severity, groupId, limit, cursor } = query;
|
|
38
|
+
const rows = await prisma.$queryRaw<RankedRow[]>`
|
|
39
|
+
WITH summaries AS (
|
|
40
|
+
SELECT group_id, CAST(SUM(occurrences) AS UNSIGNED) AS occurrence_count,
|
|
41
|
+
MIN(first_seen) AS first_seen, MAX(last_seen) AS last_seen,
|
|
42
|
+
MAX(CONCAT(DATE_FORMAT(last_seen, '%Y%m%d%H%i%s%f'), id)) AS sample_position
|
|
43
|
+
FROM diagnostic_buckets
|
|
44
|
+
WHERE bucket_start >= ${from} AND bucket_start < ${to}
|
|
45
|
+
${severity ? Prisma.sql`AND severity = ${severity}` : Prisma.empty}
|
|
46
|
+
${groupId ? Prisma.sql`AND group_id = ${groupId}` : Prisma.empty}
|
|
47
|
+
GROUP BY group_id
|
|
48
|
+
), ranked AS (
|
|
49
|
+
SELECT summaries.*, ROW_NUMBER() OVER (ORDER BY occurrence_count DESC, group_id ASC) AS group_rank
|
|
50
|
+
FROM summaries
|
|
51
|
+
)
|
|
52
|
+
SELECT ranked.group_rank AS groupRank, ranked.group_id AS groupId, ranked.occurrence_count AS occurrenceCount,
|
|
53
|
+
ranked.first_seen AS firstSeen, ranked.last_seen AS lastSeen,
|
|
54
|
+
sample.severity, sample.source, sample.label, sample.code, sample.message, sample.frames, sample.release
|
|
55
|
+
FROM ranked
|
|
56
|
+
JOIN diagnostic_buckets AS sample ON sample.id = RIGHT(ranked.sample_position, 64)
|
|
57
|
+
${cursor ? Prisma.sql`WHERE ranked.occurrence_count < ${cursor[0]}
|
|
58
|
+
OR (ranked.occurrence_count = ${cursor[0]} AND ranked.group_id > ${cursor[1]})` : Prisma.empty}
|
|
59
|
+
ORDER BY ranked.group_rank ASC
|
|
60
|
+
LIMIT ${limit + 1}`;
|
|
61
|
+
const groups = rows.slice(0, limit).map(({ groupRank, occurrenceCount, ...row }) => ({
|
|
62
|
+
...row, rank: Number(groupRank), count: Number(occurrenceCount),
|
|
63
|
+
}));
|
|
64
|
+
const last = groups.at(-1);
|
|
65
|
+
return {
|
|
66
|
+
groups,
|
|
67
|
+
nextCursor: last && rows.length > limit ? Buffer.from(JSON.stringify([last.count, last.groupId])).toString('base64url') : null,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
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, reply) => {
|
|
14
|
+
reply.header('Cache-Control', 'no-store');
|
|
15
|
+
return successResponse('Diagnostic groups', await readDiagnosticGroups(request.query));
|
|
16
|
+
});
|
|
17
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
|
|
5
|
+
/** Add static, application-owned summaries here. Never interpolate inputs. */
|
|
6
|
+
export const diagnosticMessages = {
|
|
7
|
+
DEPENDENCY_TIMEOUT: 'A dependency operation timed out',
|
|
8
|
+
DEPENDENCY_UNAVAILABLE: 'A dependency connection failed',
|
|
9
|
+
DEPENDENCY_HTTP_FAILURE: 'A dependency returned an unsuccessful HTTP response',
|
|
10
|
+
DEPENDENCY_RESPONSE_LIMIT: 'A dependency response exceeded its configured size limit',
|
|
11
|
+
DEPENDENCY_TARGET_REJECTED: 'The configured dependency target was rejected',
|
|
12
|
+
DATABASE_UNAVAILABLE: 'The database connection was unavailable',
|
|
13
|
+
DATABASE_POOL_TIMEOUT: 'The database pool did not provide a connection in time',
|
|
14
|
+
SERVICE_UNAVAILABLE: 'A required service was temporarily unavailable',
|
|
15
|
+
} as const;
|
|
16
|
+
|
|
17
|
+
export type DiagnosticReason = keyof typeof diagnosticMessages;
|
|
18
|
+
export type DiagnosticSeverity = 'error' | 'warning';
|
|
19
|
+
export type DiagnosticSource = 'request' | 'job' | 'operation';
|
|
20
|
+
export interface DiagnosticFrame { file: string; line: number | null; function: string | null }
|
|
21
|
+
export interface DiagnosticContext { severity: DiagnosticSeverity; source: DiagnosticSource; label: string }
|
|
22
|
+
export interface DiagnosticSample extends DiagnosticContext {
|
|
23
|
+
groupId: string;
|
|
24
|
+
code: string | null;
|
|
25
|
+
message: string;
|
|
26
|
+
frames: DiagnosticFrame[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const serverRoot = fileURLToPath(new URL('../../../', import.meta.url));
|
|
30
|
+
const dependencyCodes = new Map<string, DiagnosticReason>([
|
|
31
|
+
['ETIMEDOUT', 'DEPENDENCY_TIMEOUT'], ['ECONNABORTED', 'DEPENDENCY_TIMEOUT'],
|
|
32
|
+
['ECONNREFUSED', 'DEPENDENCY_UNAVAILABLE'], ['ECONNRESET', 'DEPENDENCY_UNAVAILABLE'],
|
|
33
|
+
['ENOTFOUND', 'DEPENDENCY_UNAVAILABLE'], ['EAI_AGAIN', 'DEPENDENCY_UNAVAILABLE'],
|
|
34
|
+
['P1001', 'DATABASE_UNAVAILABLE'], ['P1017', 'DATABASE_UNAVAILABLE'], ['P2024', 'DATABASE_POOL_TIMEOUT'],
|
|
35
|
+
['SERVICE_UNAVAILABLE', 'SERVICE_UNAVAILABLE'],
|
|
36
|
+
]);
|
|
37
|
+
const outboundKinds = new Map<string, DiagnosticReason>([
|
|
38
|
+
['timeout', 'DEPENDENCY_TIMEOUT'], ['network', 'DEPENDENCY_UNAVAILABLE'],
|
|
39
|
+
['http', 'DEPENDENCY_HTTP_FAILURE'], ['too-large', 'DEPENDENCY_RESPONSE_LIMIT'],
|
|
40
|
+
['blocked', 'DEPENDENCY_TARGET_REJECTED'],
|
|
41
|
+
]);
|
|
42
|
+
const fallback: Record<DiagnosticSource, string> = {
|
|
43
|
+
request: 'Unexpected request failure', job: 'Unexpected job failure', operation: 'Unexpected operation failure',
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Drop the complete message header, including multiline messages. Accept
|
|
47
|
+
* only structured V8 frames under this app's src or dist directory. */
|
|
48
|
+
function applicationFrames(error: Error): DiagnosticFrame[] {
|
|
49
|
+
const stack = error.stack;
|
|
50
|
+
const header = `${Error.prototype.toString.call(error)}\n`;
|
|
51
|
+
if (!stack?.startsWith(header)) return [];
|
|
52
|
+
const frames: DiagnosticFrame[] = [];
|
|
53
|
+
for (const row of stack.slice(header.length, header.length + 4_096).split('\n')) {
|
|
54
|
+
const match = /^\s+at (?:(.*?) \()?(.+):(\d+):\d+\)?$/.exec(row);
|
|
55
|
+
if (!match) continue;
|
|
56
|
+
const [, name, location, line] = match;
|
|
57
|
+
let absolute: string;
|
|
58
|
+
try { absolute = location.startsWith('file:') ? fileURLToPath(location) : location; } catch { continue; }
|
|
59
|
+
if (!path.isAbsolute(absolute)) continue;
|
|
60
|
+
const file = path.relative(serverRoot, absolute).split(path.sep).join('/');
|
|
61
|
+
if (file.length > 180 || !/^(?:src|dist)\/(?:[\w.-]+\/)*[\w.-]+\.(?:ts|js)$/.test(file) ||
|
|
62
|
+
/\/modules\/diagnostics\/diagnostics\.(?:context|sample)\./.test(file)) continue;
|
|
63
|
+
const compiled = file.startsWith('dist/');
|
|
64
|
+
const functionName = name?.replace(/^async /, '');
|
|
65
|
+
frames.push({
|
|
66
|
+
file: compiled ? file.replace(/^dist\//, 'src/').replace(/\.js$/, '.ts') : file,
|
|
67
|
+
// Compiled line numbers do not refer to the source file without source maps.
|
|
68
|
+
line: compiled ? null : Number(line),
|
|
69
|
+
function: functionName && /^[\w.$<>]{1,100}$/.test(functionName) ? functionName : null,
|
|
70
|
+
});
|
|
71
|
+
if (frames.length === 4) break;
|
|
72
|
+
}
|
|
73
|
+
return frames;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Raw exception messages and arbitrary error codes never enter a stored row. */
|
|
77
|
+
export function diagnosticSample(context: DiagnosticContext, error?: unknown, reason?: DiagnosticReason): DiagnosticSample {
|
|
78
|
+
let code = reason && Object.hasOwn(diagnosticMessages, reason) ? reason : undefined;
|
|
79
|
+
let frames: DiagnosticFrame[] = [];
|
|
80
|
+
if (error instanceof Error) {
|
|
81
|
+
const { code: rawCode, kind } = error as Error & { code?: string; kind?: string };
|
|
82
|
+
code ??= (error.name === 'OutboundHttpError' && kind ? outboundKinds.get(kind) : undefined) ??
|
|
83
|
+
(rawCode ? dependencyCodes.get(rawCode) : undefined);
|
|
84
|
+
frames = applicationFrames(error);
|
|
85
|
+
}
|
|
86
|
+
const location = frames[0];
|
|
87
|
+
const groupId = createHash('sha256').update(JSON.stringify([
|
|
88
|
+
context.severity, context.source, context.label,
|
|
89
|
+
code ?? null, location?.file ?? null, location?.function ?? null,
|
|
90
|
+
])).digest('hex');
|
|
91
|
+
return { ...context, groupId, code: code ?? null, message: code ? diagnosticMessages[code] : fallback[context.source], frames };
|
|
92
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { DIAGNOSTIC_WINDOW_MS } from './diagnostics.collector.js';
|
|
3
|
+
|
|
4
|
+
const maxRange = 7 * 24 * 60 * 60_000;
|
|
5
|
+
const groupId = z.string().regex(/^[a-f0-9]{64}$/);
|
|
6
|
+
const boundary = z.iso.datetime({ offset: true }).transform((value) => new Date(value))
|
|
7
|
+
.pipe(z.date().min(new Date('1000-01-01T00:00:00Z')).max(new Date('9999-12-31T23:59:59.999Z')))
|
|
8
|
+
.refine((date) => +date % DIAGNOSTIC_WINDOW_MS === 0, 'Use five-minute boundaries');
|
|
9
|
+
const position = z.tuple([z.number().int().positive(), groupId]);
|
|
10
|
+
const cursor = z.string().max(160).regex(/^[a-zA-Z0-9_-]+$/).transform((value, ctx) => {
|
|
11
|
+
let parsed: unknown;
|
|
12
|
+
try { parsed = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); } catch { /* invalid cursor */ }
|
|
13
|
+
const result = position.safeParse(parsed);
|
|
14
|
+
if (result.success) return result.data;
|
|
15
|
+
ctx.addIssue({ code: 'custom', message: 'Invalid diagnostics cursor' });
|
|
16
|
+
return z.NEVER;
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
export const diagnosticsQuerySchema = z.strictObject({
|
|
20
|
+
from: boundary,
|
|
21
|
+
to: boundary,
|
|
22
|
+
severity: z.enum(['error', 'warning']).optional(),
|
|
23
|
+
groupId: groupId.optional(),
|
|
24
|
+
limit: z.string().regex(/^\d{1,3}$/).transform(Number).pipe(z.number().int().min(1).max(100)).default(20),
|
|
25
|
+
cursor: cursor.optional(),
|
|
26
|
+
}).superRefine(({ from, to }, ctx) => {
|
|
27
|
+
if (!(from instanceof Date) || !(to instanceof Date)) return;
|
|
28
|
+
if (+to - +from <= 0 || +to - +from > maxRange) {
|
|
29
|
+
ctx.addIssue({ code: 'custom', path: ['to'], message: 'The interval must be positive and at most seven days' });
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
export type DiagnosticsQuery = z.output<typeof diagnosticsQuerySchema>;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { FastifyInstance } from 'fastify';
|
|
2
|
+
import { env } from '@config/env.js';
|
|
3
|
+
import { logger } from '@libs/logger.js';
|
|
4
|
+
import { DiagnosticCollector } from './diagnostics.collector.js';
|
|
5
|
+
import { bindDiagnostics } from './diagnostics.context.js';
|
|
6
|
+
import { persistDiagnosticBuckets } from './diagnostics.repo.js';
|
|
7
|
+
|
|
8
|
+
/** Run the writer outside request and job scopes. Its own failures are
|
|
9
|
+
* operational logs only, which avoids feeding an outage back into the queue. */
|
|
10
|
+
export function registerDiagnostics(app: FastifyInstance): void {
|
|
11
|
+
const commit = env.SOURCE_COMMIT?.trim();
|
|
12
|
+
const collector = new DiagnosticCollector(persistDiagnosticBuckets, {
|
|
13
|
+
release: commit && /^[a-f0-9]{7,64}$/i.test(commit) ? commit.toLowerCase() : null,
|
|
14
|
+
});
|
|
15
|
+
bindDiagnostics(app, collector);
|
|
16
|
+
let failing = false;
|
|
17
|
+
const timer = setInterval(() => {
|
|
18
|
+
void collector.flush().then(() => { failing = false; }, () => {
|
|
19
|
+
if (!failing) logger.warn('[DIAGNOSTICS] Storage unavailable. Pending contributions will be retried.');
|
|
20
|
+
failing = true;
|
|
21
|
+
});
|
|
22
|
+
}, 15_000);
|
|
23
|
+
timer.unref();
|
|
24
|
+
|
|
25
|
+
app.addHook('onClose', async () => {
|
|
26
|
+
clearInterval(timer);
|
|
27
|
+
const stop = new AbortController();
|
|
28
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
29
|
+
try {
|
|
30
|
+
await Promise.race([
|
|
31
|
+
collector.close(stop.signal),
|
|
32
|
+
new Promise<never>((_resolve, reject) => {
|
|
33
|
+
// Leave time for the optional metrics flush and infrastructure cleanup.
|
|
34
|
+
timeout = setTimeout(() => { stop.abort(); reject(new Error('Diagnostics flush deadline')); }, 2_000);
|
|
35
|
+
}),
|
|
36
|
+
]);
|
|
37
|
+
} catch {
|
|
38
|
+
logger.warn('[DIAGNOSTICS] Pending contributions could not be flushed before shutdown');
|
|
39
|
+
} finally {
|
|
40
|
+
clearTimeout(timeout);
|
|
41
|
+
if (collector.droppedSamples) logger.warn({ droppedSamples: collector.droppedSamples }, '[DIAGNOSTICS] Buffer limit reached');
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
import { useCallback, useRef, useState } from 'react';
|
|
4
|
+
import { useReportWebVitals } from 'next/web-vitals';
|
|
5
|
+
import { env } from '@/lib/env';
|
|
6
|
+
import { metricsPageGroup } from './metrics.pages';
|
|
7
|
+
|
|
8
|
+
export function WebVitalsReporter(): null {
|
|
9
|
+
// Web Vitals describe a document visit. A subsequent SPA navigation must
|
|
10
|
+
// not relabel an earlier navigation's LCP or interaction measurements.
|
|
11
|
+
const [visit] = useState(() => typeof window === 'undefined' ? null : {
|
|
12
|
+
page: metricsPageGroup(window.location.pathname),
|
|
13
|
+
sampled: Math.random() < env.NEXT_PUBLIC_METRICS_SAMPLE_RATE,
|
|
14
|
+
});
|
|
15
|
+
const seen = useRef(new Set<string>());
|
|
16
|
+
const send = useCallback<Parameters<typeof useReportWebVitals>[0]>(({ name, value }) => {
|
|
17
|
+
if (!visit?.sampled || (name !== 'LCP' && name !== 'INP' && name !== 'CLS')) return;
|
|
18
|
+
// React may replay the observer effect and create a new ID for the same
|
|
19
|
+
// navigation. Count each vital once per document, including bfcache restores.
|
|
20
|
+
if (seen.current.has(name)) return;
|
|
21
|
+
seen.current.add(name);
|
|
22
|
+
|
|
23
|
+
// Anonymous, best-effort delivery: skip the credentialed client and its
|
|
24
|
+
// refresh/retry hooks. Retrying an uncertain send would double count.
|
|
25
|
+
void fetch(`${env.NEXT_PUBLIC_API_BASE_URL.replace(/\/$/, '')}/metrics/web-vitals`, {
|
|
26
|
+
method: 'POST',
|
|
27
|
+
headers: { 'Content-Type': 'application/json' },
|
|
28
|
+
credentials: 'omit',
|
|
29
|
+
keepalive: true,
|
|
30
|
+
body: JSON.stringify({ page: visit.page, samples: [{ kind: name.toLowerCase(), value }] }),
|
|
31
|
+
}).catch(() => {});
|
|
32
|
+
}, [visit]);
|
|
33
|
+
useReportWebVitals(send);
|
|
34
|
+
return null;
|
|
35
|
+
}
|