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.
- package/CHANGELOG.md +43 -0
- package/README.md +21 -3
- package/bin/create-tigra.js +131 -65
- package/lib/installer-transaction.js +275 -0
- package/lib/patchers/diagnostics.patcher.js +123 -0
- package/lib/patchers/email-verification.patcher.js +86 -92
- package/lib/patchers/metrics.patcher.js +145 -0
- package/lib/project-files.js +99 -0
- package/modules/diagnostics/diagnostics.md +75 -0
- package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
- package/modules/diagnostics/prisma/diagnostic-hourly-view.sql +24 -0
- package/modules/diagnostics/prisma/migration.sql +20 -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 +123 -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 +79 -0
- package/modules/diagnostics/server/diagnostics.routes.ts +16 -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/email-verification/client/hooks/useVerification.ts +4 -7
- package/modules/email-verification/server/__tests__/verification.integration.test.ts +17 -0
- package/modules/email-verification/server/__tests__/verification.service.test.ts +71 -0
- package/modules/email-verification/server/verification.service.ts +102 -157
- package/modules/metrics/client/WebVitalsReporter.tsx +37 -0
- package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +66 -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 +97 -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 +133 -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 +45 -0
- package/modules/metrics/server/metrics.schemas.ts +57 -0
- package/modules/metrics/server/metrics.service.ts +104 -0
- package/package.json +1 -1
- package/template/AGENTS.md +18 -10
- package/template/client/.dockerignore +2 -5
- package/template/client/gitignore +43 -0
- 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/features/auth/components/AuthInitializer.tsx +45 -7
- package/template/client/src/features/auth/hooks/useAuth.ts +10 -33
- package/template/client/src/features/auth/hooks/useCurrentUser.ts +3 -3
- package/template/client/src/features/auth/hooks/useSessionTransition.ts +51 -0
- package/template/client/src/features/auth/services/auth.service.ts +3 -2
- package/template/client/src/features/auth/store/authSlice.ts +11 -8
- package/template/client/src/features/auth/types/auth.types.ts +1 -0
- package/template/client/src/lib/api/__tests__/axios.config.test.ts +17 -0
- package/template/client/src/lib/api/__tests__/session-events.test.ts +23 -0
- package/template/client/src/lib/api/axios.config.ts +24 -6
- package/template/client/src/lib/api/session-events.ts +54 -0
- package/template/client/src/lib/input-modality.test.ts +79 -0
- package/template/client/src/lib/input-modality.ts +52 -0
- package/template/client/src/lib/observability/sentry-scrub.ts +63 -46
- package/template/client/src/store/__tests__/store.test.ts +1 -0
- package/template/gitignore +3 -2
- package/template/server/.dockerignore +2 -5
- package/template/server/.env.example +1 -0
- package/template/server/.env.example.production +1 -0
- package/template/server/README.md +7 -2
- package/template/server/docs/deployment.md +66 -0
- package/template/server/docs/logging.md +9 -8
- package/template/server/docs/rate-limits.md +6 -4
- package/template/server/gitignore +33 -0
- package/template/server/prisma/migrations/0_init/migration.sql +25 -0
- package/template/server/prisma/retrofits/20261116000000_retired_refresh_tokens/migration.sql +13 -0
- package/template/server/prisma/retrofits/20261116000100_avatar_cleanup/migration.sql +9 -0
- package/template/server/prisma/retrofits/20261117000000_account_purge/migration.sql +1 -0
- package/template/server/prisma/schema.prisma +25 -1
- package/template/server/src/__tests__/routes.integration.test.ts +5 -2
- package/template/server/src/app.ts +14 -5
- package/template/server/src/config/env.ts +8 -0
- package/template/server/src/config/rate-limit.config.ts +1 -1
- package/template/server/src/jobs/__tests__/cleanup-deleted-accounts.job.test.ts +26 -9
- package/template/server/src/jobs/__tests__/cleanup-expired-auth.job.test.ts +2 -1
- package/template/server/src/jobs/__tests__/jobs.integration.test.ts +51 -5
- package/template/server/src/jobs/cleanup-deleted-accounts.job.ts +30 -34
- package/template/server/src/jobs/cleanup-expired-auth.job.ts +2 -0
- package/template/server/src/jobs/index.ts +8 -2
- package/template/server/src/libs/__tests__/auth.test.ts +1 -1
- package/template/server/src/libs/__tests__/cookies.test.ts +16 -0
- package/template/server/src/libs/__tests__/error-handler.test.ts +20 -1
- package/template/server/src/libs/__tests__/http.test.ts +10 -10
- package/template/server/src/libs/__tests__/ip-block.test.ts +39 -7
- package/template/server/src/libs/__tests__/logger.test.ts +10 -1
- package/template/server/src/libs/__tests__/monitoring.test.ts +19 -0
- package/template/server/src/libs/__tests__/outbound.integration.test.ts +7 -10
- package/template/server/src/libs/__tests__/rate-limits.integration.test.ts +32 -3
- package/template/server/src/libs/__tests__/requestLogger.test.ts +9 -1
- package/template/server/src/libs/__tests__/safe-http.test.ts +65 -3
- package/template/server/src/libs/__tests__/sentry-scrub.test.ts +22 -6
- package/template/server/src/libs/__tests__/url-safety.test.ts +3 -1
- package/template/server/src/libs/account-mutation.ts +77 -0
- package/template/server/src/libs/auth.ts +37 -3
- package/template/server/src/libs/cookies.ts +25 -13
- package/template/server/src/libs/email-quota.ts +11 -7
- package/template/server/src/libs/email.ts +11 -8
- package/template/server/src/libs/error-handler.ts +16 -12
- package/template/server/src/libs/http.ts +37 -13
- package/template/server/src/libs/ip-block.ts +56 -34
- package/template/server/src/libs/logger.ts +23 -8
- package/template/server/src/libs/monitoring.ts +57 -31
- package/template/server/src/libs/observability/sentry.ts +65 -49
- package/template/server/src/libs/prisma.ts +1 -1
- package/template/server/src/libs/private-cache.ts +6 -0
- package/template/server/src/libs/rate-limiting.ts +4 -0
- package/template/server/src/libs/requestLogger.ts +3 -3
- package/template/server/src/libs/safe-http.ts +58 -18
- package/template/server/src/libs/storage/__tests__/upload-persistence.test.ts +15 -2
- package/template/server/src/libs/storage/file-storage.service.ts +59 -109
- package/template/server/src/libs/storage/file-validator.ts +2 -1
- package/template/server/src/libs/url-safety.ts +10 -2
- package/template/server/src/libs/validation-errors.ts +11 -8
- package/template/server/src/modules/admin/__tests__/admin.repo.test.ts +21 -4
- package/template/server/src/modules/admin/__tests__/admin.schemas.test.ts +11 -0
- package/template/server/src/modules/admin/__tests__/admin.service.test.ts +83 -40
- package/template/server/src/modules/admin/admin.controller.ts +4 -4
- package/template/server/src/modules/admin/admin.repo.ts +37 -54
- package/template/server/src/modules/admin/admin.routes.ts +3 -5
- package/template/server/src/modules/admin/admin.schemas.ts +3 -6
- package/template/server/src/modules/admin/admin.service.ts +61 -62
- package/template/server/src/modules/auth/__tests__/auth.schemas.test.ts +12 -0
- package/template/server/src/modules/auth/__tests__/auth.service.test.ts +58 -295
- package/template/server/src/modules/auth/__tests__/recovery.integration.test.ts +177 -0
- package/template/server/src/modules/auth/__tests__/recovery.queue.test.ts +159 -0
- package/template/server/src/modules/auth/__tests__/session-cleanup.test.ts +5 -10
- package/template/server/src/modules/auth/__tests__/sessions.integration.test.ts +1 -1
- package/template/server/src/modules/auth/__tests__/token-fingerprints.test.ts +115 -44
- package/template/server/src/modules/auth/auth-link-store.ts +64 -0
- package/template/server/src/modules/auth/auth-mail-queue.ts +124 -0
- package/template/server/src/modules/auth/auth.controller.ts +16 -5
- package/template/server/src/modules/auth/auth.repo.ts +152 -61
- package/template/server/src/modules/auth/auth.routes.ts +4 -0
- package/template/server/src/modules/auth/auth.schemas.ts +7 -3
- package/template/server/src/modules/auth/auth.service.ts +33 -237
- package/template/server/src/modules/auth/recovery.queue.ts +44 -0
- package/template/server/src/modules/auth/recovery.store.ts +7 -0
- package/template/server/src/modules/auth/session.repo.ts +5 -4
- package/template/server/src/modules/files/__tests__/files.integration.test.ts +29 -1
- package/template/server/src/modules/files/files.controller.ts +2 -2
- package/template/server/src/modules/users/__tests__/avatar-cleanup.test.ts +49 -0
- package/template/server/src/modules/users/__tests__/avatar-controller.test.ts +50 -0
- package/template/server/src/modules/users/__tests__/avatar-upload.test.ts +56 -105
- package/template/server/src/modules/users/__tests__/users.integration.test.ts +2 -2
- package/template/server/src/modules/users/__tests__/users.repo.test.ts +8 -11
- package/template/server/src/modules/users/__tests__/users.service.test.ts +116 -44
- package/template/server/src/modules/users/avatar-cleanup.ts +70 -0
- package/template/server/src/modules/users/users.controller.ts +28 -25
- package/template/server/src/modules/users/users.repo.ts +12 -51
- package/template/server/src/modules/users/users.service.ts +109 -234
- package/template/server/src/shared/responses/paginatedResponse.ts +4 -1
- package/template/server/src/shared/schemas/pagination.schema.ts +5 -1
- package/template/server/src/test/setup.ts +4 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
import { act, createElement } from 'react';
|
|
3
|
+
import { createRoot } from 'react-dom/client';
|
|
4
|
+
import { afterEach, expect, it, vi } from 'vitest';
|
|
5
|
+
import { WebVitalsReporter } from '../WebVitalsReporter';
|
|
6
|
+
|
|
7
|
+
type Sample = { name: string; id: string; value: number };
|
|
8
|
+
const fixture = vi.hoisted(() => ({
|
|
9
|
+
callback: undefined as ((sample: Sample) => void) | undefined,
|
|
10
|
+
env: { NEXT_PUBLIC_API_BASE_URL: 'http://localhost:8000/api/v1', NEXT_PUBLIC_METRICS_SAMPLE_RATE: 1 },
|
|
11
|
+
}));
|
|
12
|
+
vi.mock('next/web-vitals', () => ({
|
|
13
|
+
useReportWebVitals: (callback: (sample: Sample) => void) => { fixture.callback = callback; },
|
|
14
|
+
}));
|
|
15
|
+
vi.mock('@/lib/env', () => ({ env: fixture.env }));
|
|
16
|
+
|
|
17
|
+
async function mount(rate: number) {
|
|
18
|
+
fixture.env.NEXT_PUBLIC_METRICS_SAMPLE_RATE = rate;
|
|
19
|
+
window.history.replaceState({}, '', '/');
|
|
20
|
+
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
|
|
21
|
+
const send = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
|
|
22
|
+
vi.stubGlobal('fetch', send);
|
|
23
|
+
const element = document.createElement('div');
|
|
24
|
+
document.body.append(element);
|
|
25
|
+
const root = createRoot(element);
|
|
26
|
+
await act(async () => root.render(createElement(WebVitalsReporter)));
|
|
27
|
+
return { send, unmount: async () => {
|
|
28
|
+
await act(async () => root.unmount());
|
|
29
|
+
element.remove();
|
|
30
|
+
} };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
afterEach(() => vi.unstubAllGlobals());
|
|
34
|
+
|
|
35
|
+
it('sends one anonymous measurement per vital and retains its document page group', async () => {
|
|
36
|
+
const { send, unmount } = await mount(1);
|
|
37
|
+
try {
|
|
38
|
+
window.history.pushState({}, '', '/account/a-private-id?token=local-fixture');
|
|
39
|
+
fixture.callback?.({ name: 'LCP', id: 'fixture-1', value: 160 });
|
|
40
|
+
fixture.callback?.({ name: 'LCP', id: 'fixture-1', value: 180 });
|
|
41
|
+
// React development effect replay can attach two observers with
|
|
42
|
+
// different metric IDs to the same document.
|
|
43
|
+
fixture.callback?.({ name: 'LCP', id: 'second-observer', value: 160 });
|
|
44
|
+
fixture.callback?.({ name: 'TTFB', id: 'fixture-2', value: 30 });
|
|
45
|
+
expect(send).toHaveBeenCalledExactlyOnceWith('http://localhost:8000/api/v1/metrics/web-vitals', {
|
|
46
|
+
method: 'POST',
|
|
47
|
+
headers: { 'Content-Type': 'application/json' },
|
|
48
|
+
credentials: 'omit',
|
|
49
|
+
referrerPolicy: 'no-referrer',
|
|
50
|
+
keepalive: true,
|
|
51
|
+
body: '{"page":"home","samples":[{"kind":"lcp","value":160}]}',
|
|
52
|
+
});
|
|
53
|
+
} finally {
|
|
54
|
+
await unmount();
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('keeps browser collection off at a zero sample rate', async () => {
|
|
59
|
+
const { send, unmount } = await mount(0);
|
|
60
|
+
try {
|
|
61
|
+
fixture.callback?.({ name: 'LCP', id: 'fixture-1', value: 160 });
|
|
62
|
+
expect(send).not.toHaveBeenCalled();
|
|
63
|
+
} finally {
|
|
64
|
+
await unmount();
|
|
65
|
+
}
|
|
66
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Performance metrics
|
|
2
|
+
|
|
3
|
+
The optional metrics module collects HTTP latency, Node process measurements,
|
|
4
|
+
named operation timings, and browser LCP, INP and CLS. Install with the Tigra
|
|
5
|
+
wizard or `npx create-tigra add metrics`, then apply the new Prisma migration
|
|
6
|
+
and regenerate the client before starting the server.
|
|
7
|
+
|
|
8
|
+
Set `METRICS_ENABLED=false` on the server to pause collection. Administrators
|
|
9
|
+
can still read earlier buckets. `NEXT_PUBLIC_METRICS_SAMPLE_RATE` is the
|
|
10
|
+
fraction of browser visits sampled, from 0 to 1, and defaults to 1. Set it
|
|
11
|
+
at client build time. Zero stops browser submissions.
|
|
12
|
+
|
|
13
|
+
## Reading stored measurements
|
|
14
|
+
|
|
15
|
+
`GET /api/v1/admin/metrics?from=2026-11-10T00:00:00Z&to=2026-11-11T00:00:00Z`
|
|
16
|
+
requires the normal admin session. The range includes the start and excludes
|
|
17
|
+
the end and may span at most seven days. Filter with `kind` and paginate with
|
|
18
|
+
`limit` (1–100) and the returned `nextCursor`. Use the same filters on later
|
|
19
|
+
pages. The response data has `buckets` and `nextCursor`.
|
|
20
|
+
|
|
21
|
+
One row represents one process's contribution to a five-minute UTC window.
|
|
22
|
+
Rows become visible after the window closes and the flush succeeds. Shutdown
|
|
23
|
+
attempts a final partial flush. A retry uses the original row IDs. Multiple
|
|
24
|
+
rows with the same time and labels may be contributions from separate process
|
|
25
|
+
lifetimes. Combine their counts, sums and histogram bins when bounds and
|
|
26
|
+
units match. Bounds are inclusive and the final count is for overflow.
|
|
27
|
+
A null release means the commit was unknown. Browser metrics do not inherit
|
|
28
|
+
the server's release identity.
|
|
29
|
+
|
|
30
|
+
Stored buckets have no automatic expiry. Each process caps active series and
|
|
31
|
+
pending windows. When storage stays unavailable beyond that buffer, newer
|
|
32
|
+
samples can be dropped. Missing buckets can mean inactivity or lost samples.
|
|
33
|
+
|
|
34
|
+
## Extending coverage
|
|
35
|
+
|
|
36
|
+
New Fastify routes are timed automatically by registered route template and
|
|
37
|
+
method. Measurements cover completed replies from the earliest request hook
|
|
38
|
+
through response completion. Aborts and timeouts that end before a reply
|
|
39
|
+
are excluded. Probes, CORS preflights and metrics endpoints are excluded.
|
|
40
|
+
|
|
41
|
+
Use `measureOperation` in the server metrics service for meaningful operations
|
|
42
|
+
such as a database call, worker job or time to first streamed chunk. Give the
|
|
43
|
+
operation a stable name such as `search.database`. Do not include identifiers
|
|
44
|
+
or duplicate the request timer. The operation's return value and errors still
|
|
45
|
+
reach its caller.
|
|
46
|
+
|
|
47
|
+
For new browser page groups, update the client metrics page matcher and the
|
|
48
|
+
server metrics page allowlist together. Match dynamic routes to a fixed group.
|
|
49
|
+
Web Vitals describe a document visit, so client navigation does not relabel
|
|
50
|
+
earlier observations. Browser delivery is best-effort. Each vital is sent at
|
|
51
|
+
most once per document, including when Back restores that document from
|
|
52
|
+
cache. Sends omit credentials and referrers and are not automatically retried.
|
|
53
|
+
Node event-loop delay records one mean per sample period.
|
|
54
|
+
|
|
55
|
+
Verify new measurements in a running generated app and check stored buckets
|
|
56
|
+
through the admin API. Keep user data and secrets out of metric labels.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// Immutable aggregate per process, UTC window, and metric dimensions.
|
|
2
|
+
model MetricBucket {
|
|
3
|
+
id String @id @db.Char(64)
|
|
4
|
+
bucketStart DateTime @map("bucket_start") @db.DateTime(3)
|
|
5
|
+
kind String @db.VarChar(24)
|
|
6
|
+
label String @db.VarChar(191)
|
|
7
|
+
method String @db.VarChar(16)
|
|
8
|
+
unit String @db.VarChar(12)
|
|
9
|
+
count Int @db.UnsignedInt
|
|
10
|
+
sum Float
|
|
11
|
+
bounds Json
|
|
12
|
+
histogram Json
|
|
13
|
+
release String? @db.VarChar(64)
|
|
14
|
+
|
|
15
|
+
@@index([bucketStart, id])
|
|
16
|
+
@@index([kind, bucketStart, id])
|
|
17
|
+
@@map("metric_buckets")
|
|
18
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
-- Additive: existing application tables and migration history are untouched.
|
|
2
|
+
CREATE TABLE `metric_buckets` (
|
|
3
|
+
`id` CHAR(64) NOT NULL,
|
|
4
|
+
`bucket_start` DATETIME(3) NOT NULL,
|
|
5
|
+
`kind` VARCHAR(24) NOT NULL,
|
|
6
|
+
`label` VARCHAR(191) NOT NULL,
|
|
7
|
+
`method` VARCHAR(16) NOT NULL,
|
|
8
|
+
`unit` VARCHAR(12) NOT NULL,
|
|
9
|
+
`count` INTEGER UNSIGNED NOT NULL,
|
|
10
|
+
`sum` DOUBLE NOT NULL,
|
|
11
|
+
`bounds` JSON NOT NULL,
|
|
12
|
+
`histogram` JSON NOT NULL,
|
|
13
|
+
`release` VARCHAR(64) NULL,
|
|
14
|
+
INDEX `metric_buckets_bucket_start_id_idx`(`bucket_start`, `id`),
|
|
15
|
+
INDEX `metric_buckets_kind_bucket_start_id_idx`(`kind`, `bucket_start`, `id`),
|
|
16
|
+
PRIMARY KEY (`id`)
|
|
17
|
+
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import { test } from 'vitest';
|
|
3
|
+
import { MetricCollector, type MetricBucket } from '../metrics.collector.js';
|
|
4
|
+
|
|
5
|
+
const start = Date.UTC(2026, 0, 1);
|
|
6
|
+
const windowMs = 300_000;
|
|
7
|
+
|
|
8
|
+
test('aggregates completed UTC windows with mergeable histogram counts and independent replicas', async () => {
|
|
9
|
+
let now = start;
|
|
10
|
+
const written = new Map<string, MetricBucket>();
|
|
11
|
+
const writer = async (rows: MetricBucket[]): Promise<void> => {
|
|
12
|
+
for (const row of rows) written.set(row.id, row);
|
|
13
|
+
};
|
|
14
|
+
const clock = (): number => now;
|
|
15
|
+
const first = new MetricCollector(writer, { clock, release: 'abc1234' });
|
|
16
|
+
const second = new MetricCollector(writer, { clock, release: null });
|
|
17
|
+
first.record('request', '/api/v1/users/:id', 9, 'GET');
|
|
18
|
+
first.record('request', '/api/v1/users/:id', 14, 'GET');
|
|
19
|
+
first.record('request', '/api/v1/users/:id', 126, 'GET');
|
|
20
|
+
second.record('request', '/api/v1/users/:id', 110, 'GET');
|
|
21
|
+
await first.flush();
|
|
22
|
+
assert.equal(written.size, 0);
|
|
23
|
+
now += windowMs;
|
|
24
|
+
await Promise.all([first.flush(), second.flush()]);
|
|
25
|
+
const rows = [...written.values()];
|
|
26
|
+
assert.equal(rows.length, 2);
|
|
27
|
+
const a = rows.find((row) => row.release === 'abc1234')!;
|
|
28
|
+
assert.equal(a.bucketStart.toISOString(), '2026-01-01T00:00:00.000Z');
|
|
29
|
+
assert.equal(a.count, 3);
|
|
30
|
+
assert.equal(a.sum, 149);
|
|
31
|
+
assert.equal(a.histogram.reduce((sum, count) => sum + count, 0), 3);
|
|
32
|
+
assert.equal(a.histogram[a.bounds.indexOf(10)], 1);
|
|
33
|
+
assert.equal(a.histogram[a.bounds.indexOf(25)], 1);
|
|
34
|
+
assert.equal(a.histogram[a.bounds.indexOf(250)], 1);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('retries an uncertain write with the same identities and no double contribution', async () => {
|
|
38
|
+
let now = start;
|
|
39
|
+
const stored = new Map<string, MetricBucket>();
|
|
40
|
+
const writes: string[][] = [];
|
|
41
|
+
const collector = new MetricCollector(async (rows) => {
|
|
42
|
+
writes.push(rows.map((row) => row.id));
|
|
43
|
+
for (const row of rows) if (!stored.has(row.id)) stored.set(row.id, row);
|
|
44
|
+
if (writes.length === 1) throw new Error('connection lost after commit');
|
|
45
|
+
}, { clock: (): number => now, release: null });
|
|
46
|
+
collector.record('operation', 'fixture.slow', 25);
|
|
47
|
+
now += windowMs;
|
|
48
|
+
await assert.rejects(collector.flush(), /connection lost/);
|
|
49
|
+
await collector.flush();
|
|
50
|
+
assert.deepEqual(writes[0], writes[1]);
|
|
51
|
+
assert.equal(stored.size, 1);
|
|
52
|
+
assert.equal([...stored.values()][0]?.count, 1);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test('bounds labels and pending windows during storage failure', async () => {
|
|
56
|
+
let now = start;
|
|
57
|
+
let recovered = false;
|
|
58
|
+
const written: MetricBucket[] = [];
|
|
59
|
+
const collector = new MetricCollector(async (rows) => {
|
|
60
|
+
if (!recovered) throw new Error('offline');
|
|
61
|
+
written.push(...rows);
|
|
62
|
+
}, { clock: (): number => now, release: null, maxSeries: 2, maxPending: 1 });
|
|
63
|
+
collector.record('operation', 'first', 10);
|
|
64
|
+
collector.record('operation', 'second', 10);
|
|
65
|
+
collector.record('operation', 'third', 10);
|
|
66
|
+
for (let i = 0; i < 4; i++) {
|
|
67
|
+
now += windowMs;
|
|
68
|
+
collector.record('operation', 'first', 10);
|
|
69
|
+
await assert.rejects(collector.flush(), /offline/);
|
|
70
|
+
}
|
|
71
|
+
recovered = true;
|
|
72
|
+
await collector.close();
|
|
73
|
+
assert.deepEqual(written.map((row) => row.label), ['first', 'second', 'first']);
|
|
74
|
+
assert.ok(collector.droppedSamples >= 4);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test('stops draining future writes after the shutdown signal aborts', async () => {
|
|
78
|
+
let now = start;
|
|
79
|
+
let finish!: () => void;
|
|
80
|
+
const firstWrite = new Promise<void>((resolve) => { finish = resolve; });
|
|
81
|
+
const calls: MetricBucket[][] = [];
|
|
82
|
+
const collector = new MetricCollector(async (rows) => {
|
|
83
|
+
calls.push(rows);
|
|
84
|
+
if (calls.length === 1) await firstWrite;
|
|
85
|
+
}, { clock: (): number => now, release: null });
|
|
86
|
+
collector.record('operation', 'first', 10);
|
|
87
|
+
now += windowMs;
|
|
88
|
+
void collector.flush();
|
|
89
|
+
collector.record('operation', 'second', 10);
|
|
90
|
+
const controller = new AbortController();
|
|
91
|
+
const closing = collector.close(controller.signal);
|
|
92
|
+
await Promise.resolve();
|
|
93
|
+
controller.abort();
|
|
94
|
+
finish();
|
|
95
|
+
await closing;
|
|
96
|
+
assert.equal(calls.length, 1);
|
|
97
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
|
2
|
+
import type { FastifyInstance } from 'fastify';
|
|
3
|
+
import { buildTestApp, call, db, registerAdmin, registerUser } from '@/test/integration-helpers.js';
|
|
4
|
+
|
|
5
|
+
const from = '2000-01-01T00:00:00Z';
|
|
6
|
+
const to = '2000-01-02T00:00:00Z';
|
|
7
|
+
const range = `/admin/metrics?from=${from}&to=${to}`;
|
|
8
|
+
let app: FastifyInstance;
|
|
9
|
+
let admin: Awaited<ReturnType<typeof registerAdmin>>;
|
|
10
|
+
let user: Awaited<ReturnType<typeof registerUser>>;
|
|
11
|
+
|
|
12
|
+
beforeAll(async () => {
|
|
13
|
+
app = await buildTestApp();
|
|
14
|
+
[admin, user] = await Promise.all([registerAdmin(app, 'metrics-admin'), registerUser(app, 'metrics-user')]);
|
|
15
|
+
});
|
|
16
|
+
afterAll(async () => { await app?.close(); });
|
|
17
|
+
|
|
18
|
+
describe('metrics trust boundaries', () => {
|
|
19
|
+
it('only lets admins read stored metrics and validates their query', async () => {
|
|
20
|
+
expect((await call(app, 'GET', range)).status).toBe(401);
|
|
21
|
+
expect((await call(app, 'GET', range, { jar: user.jar })).status).toBe(403);
|
|
22
|
+
expect((await call(app, 'GET', range, { jar: admin.jar })).body?.data).toEqual({ buckets: [], nextCursor: null });
|
|
23
|
+
for (const query of ['from=2000-01-01&to=2000-01-02', `from=${to}&to=${from}`, `from=${from}&to=2000-02-01T00:00:00Z`, `from=${from}&to=${to}&limit=101`]) {
|
|
24
|
+
expect((await call(app, 'GET', `/admin/metrics?${query}`, { jar: admin.jar })).code).toBe('VALIDATION_FAILED');
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('pages ordered buckets across an inclusive start and exclusive end', async () => {
|
|
29
|
+
const prisma = await db();
|
|
30
|
+
await prisma.metricBucket.createMany({ data: [
|
|
31
|
+
{ id: 'a'.repeat(64), bucketStart: new Date(from), kind: 'request', label: '/fixture/:id', method: 'GET', unit: 'ms', count: 2, sum: 30, bounds: [25], histogram: [2, 0], release: null },
|
|
32
|
+
{ id: 'b'.repeat(64), bucketStart: new Date(from), kind: 'request', label: '/other', method: 'GET', unit: 'ms', count: 1, sum: 10, bounds: [25], histogram: [1, 0], release: null },
|
|
33
|
+
{ id: 'c'.repeat(64), bucketStart: new Date(to), kind: 'request', label: '/end', method: 'GET', unit: 'ms', count: 1, sum: 10, bounds: [25], histogram: [1, 0], release: null },
|
|
34
|
+
] });
|
|
35
|
+
const first = await call(app, 'GET', `${range}&limit=1`, { jar: admin.jar });
|
|
36
|
+
expect(first.status).toBe(200);
|
|
37
|
+
expect(first.body?.data.buckets.map((row: { label: string }) => row.label)).toEqual(['/fixture/:id']);
|
|
38
|
+
const second = await call(app, 'GET', `${range}&limit=1&cursor=${first.body?.data.nextCursor}`, { jar: admin.jar });
|
|
39
|
+
expect(second.body?.data.buckets.map((row: { label: string }) => row.label)).toEqual(['/other']);
|
|
40
|
+
expect(second.body?.data.nextCursor).toBeNull();
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('accepts bounded vitals without a session and rejects extra labels or oversized input', async () => {
|
|
44
|
+
const endpoint = '/metrics/web-vitals';
|
|
45
|
+
const payload = { page: 'home', samples: [{ kind: 'lcp', value: 124 }] };
|
|
46
|
+
const headers = { origin: 'http://localhost:3000' };
|
|
47
|
+
expect((await call(app, 'POST', endpoint, { headers, payload })).status).toBe(204);
|
|
48
|
+
expect((await call(app, 'POST', endpoint, { payload })).status).toBe(403);
|
|
49
|
+
expect((await call(app, 'POST', endpoint, { headers: { origin: 'https://other.example.test' }, payload })).status).toBe(403);
|
|
50
|
+
expect((await call(app, 'POST', endpoint, { headers, payload: { ...payload, url: '/profile/123' } })).status).toBe(422);
|
|
51
|
+
expect((await call(app, 'POST', endpoint, { headers, payload: { ...payload, page: 'arbitrary' } })).status).toBe(422);
|
|
52
|
+
expect((await call(app, 'POST', endpoint, { headers, payload: { ...payload, samples: [{ kind: 'cls', value: -1 }] } })).status).toBe(422);
|
|
53
|
+
expect((await call(app, 'POST', endpoint, { headers, payload: { ...payload, padding: 'x'.repeat(5000) } })).status).toBe(413);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('persists one contribution per replica and retries immutable bucket IDs safely', async () => {
|
|
57
|
+
const { persistMetricBuckets } = await import('../metrics.repo.js');
|
|
58
|
+
const first = { id: 'd'.repeat(64), bucketStart: new Date(to), kind: 'operation' as const, label: 'fixture.retry', method: '', unit: 'ms', count: 2, sum: 30, bounds: [25], histogram: [2, 0], release: null };
|
|
59
|
+
const second = { ...first, id: 'e'.repeat(64), count: 1, sum: 50, histogram: [0, 1] };
|
|
60
|
+
await Promise.all([persistMetricBuckets([first]), persistMetricBuckets([second])]);
|
|
61
|
+
await persistMetricBuckets([first]);
|
|
62
|
+
const rows = await (await db()).metricBucket.findMany({ where: { label: 'fixture.retry' } });
|
|
63
|
+
expect(rows).toHaveLength(2);
|
|
64
|
+
expect(rows.reduce((count, row) => count + row.count, 0)).toBe(3);
|
|
65
|
+
expect(rows.reduce((sum, row) => sum + row.sum, 0)).toBe(80);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('collects new route templates and named operations through the root hook', async () => {
|
|
69
|
+
const { buildApp } = await import('@/app.js');
|
|
70
|
+
const { measureOperation } = await import('../metrics.service.js');
|
|
71
|
+
const fixture = await buildApp();
|
|
72
|
+
fixture.get('/api/v1/metrics-fixture/:id', async () => measureOperation('fixture.delay', async () => {
|
|
73
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
74
|
+
return { ok: true };
|
|
75
|
+
}));
|
|
76
|
+
try {
|
|
77
|
+
expect((await call(fixture, 'GET', '/metrics-fixture/a?test=private')).status).toBe(200);
|
|
78
|
+
expect((await call(fixture, 'GET', '/metrics-fixture/b')).status).toBe(200);
|
|
79
|
+
} finally {
|
|
80
|
+
await fixture.close();
|
|
81
|
+
}
|
|
82
|
+
const rows = await (await db()).metricBucket.findMany({
|
|
83
|
+
where: { label: { in: ['/api/v1/metrics-fixture/:id', 'fixture.delay'] } },
|
|
84
|
+
});
|
|
85
|
+
expect(rows.map(({ kind, count }) => [kind, count]).sort()).toEqual([['operation', 2], ['request', 2]]);
|
|
86
|
+
for (const row of rows) expect(row.sum).toBeGreaterThanOrEqual(40);
|
|
87
|
+
});
|
|
88
|
+
});
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { metricsQuerySchema, webVitalsSchema } from '../metrics.schemas.js';
|
|
3
|
+
|
|
4
|
+
describe('metrics query', () => {
|
|
5
|
+
const from = '2026-11-10T04:00:00+04:00';
|
|
6
|
+
const to = '2026-11-17T00:00:00Z';
|
|
7
|
+
|
|
8
|
+
it('normalizes offset timestamps at the inclusive seven-day limit', () => {
|
|
9
|
+
const query = metricsQuerySchema.parse({ from, to });
|
|
10
|
+
expect(query.from.toISOString()).toBe('2026-11-10T00:00:00.000Z');
|
|
11
|
+
expect(query.to.toISOString()).toBe('2026-11-17T00:00:00.000Z');
|
|
12
|
+
expect(query.limit).toBe(50);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
it.each([
|
|
16
|
+
{ from: '2026-11-10' },
|
|
17
|
+
{ from: '0001-01-01T00:00:00Z' },
|
|
18
|
+
{ to: '2026-11-17T00:00:00.001Z' },
|
|
19
|
+
{ cursor: 'bad' },
|
|
20
|
+
{ cursor: Buffer.from(JSON.stringify([to, 'a'.repeat(64)])).toString('base64url') },
|
|
21
|
+
{ kind: 'constructor' },
|
|
22
|
+
{ limit: '101' },
|
|
23
|
+
])('rejects invalid query fields %j without throwing', (change) => {
|
|
24
|
+
expect(metricsQuerySchema.safeParse({ from, to, ...change }).success).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
describe('browser metric batch', () => {
|
|
29
|
+
it('rejects repeated metric kinds, arbitrary dimensions and unreasonable CLS', () => {
|
|
30
|
+
const sample = { kind: 'cls', value: 0.2 };
|
|
31
|
+
expect(webVitalsSchema.safeParse({ page: 'home', samples: [sample] }).success).toBe(true);
|
|
32
|
+
expect(webVitalsSchema.safeParse({ page: 'home', samples: [sample, sample] }).success).toBe(false);
|
|
33
|
+
expect(webVitalsSchema.safeParse({ page: 'home', samples: [{ ...sample, value: 101 }] }).success).toBe(false);
|
|
34
|
+
expect(webVitalsSchema.safeParse({ page: '/users/42', samples: [sample] }).success).toBe(false);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import Fastify from 'fastify';
|
|
2
|
+
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
|
3
|
+
import type { MetricBucket } from '../metrics.collector.js';
|
|
4
|
+
import { measureOperation, registerMetrics } from '../metrics.service.js';
|
|
5
|
+
|
|
6
|
+
const state = vi.hoisted(() => ({
|
|
7
|
+
enabled: true,
|
|
8
|
+
release: ' ABCDEF12 ' as string | undefined,
|
|
9
|
+
persist: vi.fn<(rows: MetricBucket[]) => Promise<void>>(),
|
|
10
|
+
}));
|
|
11
|
+
vi.mock('@config/env.js', async (original) => ({
|
|
12
|
+
env: {
|
|
13
|
+
...(await original<{ env: object }>()).env,
|
|
14
|
+
get METRICS_ENABLED(): boolean { return state.enabled; },
|
|
15
|
+
get SOURCE_COMMIT(): string | undefined { return state.release; },
|
|
16
|
+
},
|
|
17
|
+
}));
|
|
18
|
+
vi.mock('../metrics.repo.js', () => ({ persistMetricBuckets: state.persist }));
|
|
19
|
+
|
|
20
|
+
beforeEach(() => {
|
|
21
|
+
state.enabled = true;
|
|
22
|
+
state.release = ' ABCDEF12 ';
|
|
23
|
+
state.persist.mockReset().mockResolvedValue(undefined);
|
|
24
|
+
});
|
|
25
|
+
afterEach(() => { vi.useRealTimers(); });
|
|
26
|
+
|
|
27
|
+
it('measures future route templates and operations without leaking request paths', async () => {
|
|
28
|
+
const app = Fastify();
|
|
29
|
+
registerMetrics(app);
|
|
30
|
+
app.get('/feature/:id', async () => measureOperation('feature.load', () => ({ ok: true })));
|
|
31
|
+
app.get('/api/v1/live', async () => ({ ok: true }));
|
|
32
|
+
app.options('/feature/:id', async () => ({}));
|
|
33
|
+
try {
|
|
34
|
+
await app.inject('/feature/one?token=fixture');
|
|
35
|
+
await app.inject('/feature/two');
|
|
36
|
+
await app.inject('/private-missing/a');
|
|
37
|
+
await app.inject('/private-missing/b');
|
|
38
|
+
await app.inject('/api/v1/live');
|
|
39
|
+
await app.inject({ url: '/feature/a', method: 'OPTIONS' });
|
|
40
|
+
await expect(measureOperation('feature.failure', () => { throw new Error('fixture failure'); })).rejects.toThrow('fixture failure');
|
|
41
|
+
await expect(measureOperation('invalid/label', () => 'ok')).resolves.toBe('ok');
|
|
42
|
+
} finally {
|
|
43
|
+
await app.close();
|
|
44
|
+
}
|
|
45
|
+
const buckets = state.persist.mock.calls.flatMap(([rows]) => rows);
|
|
46
|
+
expect(buckets.map(({ label, count, release }) => ({ label, count, release }))).toEqual([
|
|
47
|
+
{ label: 'feature.load', count: 2, release: 'abcdef12' },
|
|
48
|
+
{ label: '/feature/:id', count: 2, release: 'abcdef12' },
|
|
49
|
+
{ label: '(unmatched)', count: 2, release: 'abcdef12' },
|
|
50
|
+
{ label: 'feature.failure', count: 1, release: 'abcdef12' },
|
|
51
|
+
]);
|
|
52
|
+
await expect(measureOperation('after.shutdown', () => 42)).resolves.toBe(42);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('samples the runtime periodically and skips the collector when paused', async () => {
|
|
56
|
+
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
|
|
57
|
+
state.release = undefined;
|
|
58
|
+
const app = Fastify();
|
|
59
|
+
registerMetrics(app);
|
|
60
|
+
await vi.advanceTimersByTimeAsync(5_000);
|
|
61
|
+
await app.close();
|
|
62
|
+
const buckets = state.persist.mock.calls.flatMap(([rows]) => rows);
|
|
63
|
+
expect(buckets).toEqual(expect.arrayContaining([
|
|
64
|
+
expect.objectContaining({ kind: 'rss', release: null, count: 1, unit: 'bytes' }),
|
|
65
|
+
expect.objectContaining({ kind: 'heap', release: null, count: 1, unit: 'bytes' }),
|
|
66
|
+
]));
|
|
67
|
+
state.persist.mockClear();
|
|
68
|
+
state.enabled = false;
|
|
69
|
+
const paused = Fastify();
|
|
70
|
+
expect(registerMetrics(paused)).toBeUndefined();
|
|
71
|
+
await paused.close();
|
|
72
|
+
expect(state.persist).not.toHaveBeenCalled();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('bounds Fastify shutdown even if persistence never settles', async () => {
|
|
76
|
+
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
|
|
77
|
+
state.persist.mockImplementation(() => new Promise<void>(() => {}));
|
|
78
|
+
const app = Fastify();
|
|
79
|
+
const collector = registerMetrics(app)!;
|
|
80
|
+
collector.record('operation', 'fixture.pending', 25);
|
|
81
|
+
const closing = app.close();
|
|
82
|
+
await vi.advanceTimersByTimeAsync(2_600);
|
|
83
|
+
await expect(closing).resolves.toBeUndefined();
|
|
84
|
+
});
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
export const WINDOW_MS = 5 * 60_000;
|
|
4
|
+
const timings = [1, 5, 10, 25, 50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000, 60_000];
|
|
5
|
+
const memory = [32, 64, 128, 256, 512, 1_024, 2_048, 4_096].map((mb) => mb * 1024 * 1024);
|
|
6
|
+
|
|
7
|
+
/** Bounds are inclusive and each histogram ends with an overflow bucket. */
|
|
8
|
+
export const METRICS = {
|
|
9
|
+
request: { unit: 'ms', bounds: timings },
|
|
10
|
+
operation: { unit: 'ms', bounds: timings },
|
|
11
|
+
rss: { unit: 'bytes', bounds: memory },
|
|
12
|
+
heap: { unit: 'bytes', bounds: memory },
|
|
13
|
+
cpu: { unit: 'percent', bounds: [1, 5, 10, 25, 50, 100, 200, 400] },
|
|
14
|
+
'event-loop-delay': { unit: 'ms', bounds: timings },
|
|
15
|
+
lcp: { unit: 'ms', bounds: timings },
|
|
16
|
+
inp: { unit: 'ms', bounds: timings },
|
|
17
|
+
cls: { unit: 'score', bounds: [0, 0.01, 0.05, 0.1, 0.25, 0.5, 1] },
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export type MetricKind = keyof typeof METRICS;
|
|
21
|
+
export interface MetricBucket {
|
|
22
|
+
id: string;
|
|
23
|
+
bucketStart: Date;
|
|
24
|
+
kind: MetricKind;
|
|
25
|
+
label: string;
|
|
26
|
+
method: string;
|
|
27
|
+
unit: string;
|
|
28
|
+
count: number;
|
|
29
|
+
sum: number;
|
|
30
|
+
bounds: number[];
|
|
31
|
+
histogram: number[];
|
|
32
|
+
release: string | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type Series = Pick<MetricBucket, 'kind' | 'label' | 'method' | 'count' | 'sum' | 'histogram'>;
|
|
36
|
+
type Writer = (rows: MetricBucket[]) => Promise<void>;
|
|
37
|
+
interface CollectorOptions {
|
|
38
|
+
release: string | null;
|
|
39
|
+
clock?: () => number;
|
|
40
|
+
maxSeries?: number;
|
|
41
|
+
maxPending?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Only sealed windows reach the writer. Their immutable, process-specific
|
|
45
|
+
* IDs make an ambiguous database commit safe to retry and keep replicas additive. */
|
|
46
|
+
export class MetricCollector {
|
|
47
|
+
private readonly instance = randomUUID();
|
|
48
|
+
private readonly clock: () => number;
|
|
49
|
+
private readonly maxSeries: number;
|
|
50
|
+
private readonly maxPending: number;
|
|
51
|
+
private readonly series = new Map<string, Series>();
|
|
52
|
+
private readonly pending: MetricBucket[][] = [];
|
|
53
|
+
private window = -1;
|
|
54
|
+
private writing: Promise<void> | undefined;
|
|
55
|
+
private closed = false;
|
|
56
|
+
droppedSamples = 0;
|
|
57
|
+
|
|
58
|
+
constructor(private readonly write: Writer, private readonly options: CollectorOptions) {
|
|
59
|
+
this.clock = options.clock ?? Date.now;
|
|
60
|
+
this.maxSeries = options.maxSeries ?? 512;
|
|
61
|
+
this.maxPending = options.maxPending ?? 2;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
record(kind: MetricKind, label: string, value: number, method = ''): void {
|
|
65
|
+
if (this.closed || !Number.isFinite(value) || value < 0) return;
|
|
66
|
+
this.rotate();
|
|
67
|
+
const key = `${kind}\0${method}\0${label}`;
|
|
68
|
+
const { bounds } = METRICS[kind];
|
|
69
|
+
let series = this.series.get(key);
|
|
70
|
+
if (!series) {
|
|
71
|
+
if (this.series.size >= this.maxSeries) {
|
|
72
|
+
this.droppedSamples++;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
series = { kind, label, method, count: 0, sum: 0, histogram: Array<number>(bounds.length + 1).fill(0) };
|
|
76
|
+
this.series.set(key, series);
|
|
77
|
+
}
|
|
78
|
+
const index = bounds.findIndex((bound) => value <= bound);
|
|
79
|
+
series.histogram[index === -1 ? bounds.length : index]++;
|
|
80
|
+
series.count++;
|
|
81
|
+
series.sum += value;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
private rotate(): void {
|
|
85
|
+
const window = Math.floor(this.clock() / WINDOW_MS) * WINDOW_MS;
|
|
86
|
+
// A backward wall-clock adjustment must not reopen a sealed window.
|
|
87
|
+
if (window <= this.window) return;
|
|
88
|
+
this.seal();
|
|
89
|
+
this.window = window;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private seal(): void {
|
|
93
|
+
if (this.series.size === 0) return;
|
|
94
|
+
if (this.pending.length < this.maxPending) {
|
|
95
|
+
const bucketStart = new Date(this.window);
|
|
96
|
+
this.pending.push([...this.series].map(([key, value]) => ({
|
|
97
|
+
...value,
|
|
98
|
+
id: createHash('sha256').update(`${this.instance}\0${this.window}\0${key}`).digest('hex'),
|
|
99
|
+
bucketStart,
|
|
100
|
+
unit: METRICS[value.kind].unit,
|
|
101
|
+
bounds: [...METRICS[value.kind].bounds],
|
|
102
|
+
release: value.kind === 'lcp' || value.kind === 'inp' || value.kind === 'cls'
|
|
103
|
+
? null : this.options.release,
|
|
104
|
+
})));
|
|
105
|
+
} else {
|
|
106
|
+
// Preserve the oldest immutable retry batch and cap memory during outages.
|
|
107
|
+
for (const series of this.series.values()) this.droppedSamples += series.count;
|
|
108
|
+
}
|
|
109
|
+
this.series.clear();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
flush(): Promise<void> {
|
|
113
|
+
if (!this.closed) this.rotate();
|
|
114
|
+
if (this.writing) return this.writing;
|
|
115
|
+
const batch = this.pending[0];
|
|
116
|
+
if (!batch) return Promise.resolve();
|
|
117
|
+
this.writing = Promise.resolve().then(() => this.write(batch)).then(() => {
|
|
118
|
+
this.pending.shift();
|
|
119
|
+
}).finally(() => { this.writing = undefined; });
|
|
120
|
+
return this.writing;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Publish a partial final window only while the shutdown budget allows it. */
|
|
124
|
+
async close(signal?: AbortSignal): Promise<void> {
|
|
125
|
+
this.closed = true;
|
|
126
|
+
while (this.pending.length && !signal?.aborted) await this.flush();
|
|
127
|
+
// An already-running transaction has its own timeout. On return from it,
|
|
128
|
+
// the close hook must avoid starting any additional database work.
|
|
129
|
+
if (signal?.aborted) return;
|
|
130
|
+
this.seal();
|
|
131
|
+
await this.flush();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { prisma } from '@libs/prisma.js';
|
|
2
|
+
import type { MetricBucket as StoredBucket } from '@prisma/client';
|
|
3
|
+
import type { MetricBucket } from './metrics.collector.js';
|
|
4
|
+
import type { MetricsQuery } from './metrics.schemas.js';
|
|
5
|
+
|
|
6
|
+
export async function persistMetricBuckets(rows: MetricBucket[]): Promise<void> {
|
|
7
|
+
// One bounded transaction per sealed window. A retry with the same row IDs
|
|
8
|
+
// is a no-op for rows that committed before a lost acknowledgement.
|
|
9
|
+
await prisma.$transaction(async (tx) => {
|
|
10
|
+
await tx.metricBucket.createMany({ data: rows, skipDuplicates: true });
|
|
11
|
+
}, { maxWait: 500, timeout: 1_500 });
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function readMetricBuckets(query: MetricsQuery): Promise<{
|
|
15
|
+
buckets: Omit<StoredBucket, 'id'>[];
|
|
16
|
+
nextCursor: string | null;
|
|
17
|
+
}> {
|
|
18
|
+
const { from, to, kind, limit, cursor } = query;
|
|
19
|
+
const rows = await prisma.metricBucket.findMany({
|
|
20
|
+
where: {
|
|
21
|
+
bucketStart: { gte: from, lt: to },
|
|
22
|
+
...(kind ? { kind } : {}),
|
|
23
|
+
...(cursor ? {
|
|
24
|
+
OR: [
|
|
25
|
+
{ bucketStart: { gt: cursor[0] } },
|
|
26
|
+
{ bucketStart: cursor[0], id: { gt: cursor[1] } },
|
|
27
|
+
],
|
|
28
|
+
} : {}),
|
|
29
|
+
},
|
|
30
|
+
orderBy: [{ bucketStart: 'asc' }, { id: 'asc' }],
|
|
31
|
+
take: limit + 1,
|
|
32
|
+
select: {
|
|
33
|
+
id: true, bucketStart: true, kind: true, label: true, method: true,
|
|
34
|
+
unit: true, count: true, sum: true, bounds: true, histogram: true, release: true,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
const page = rows.slice(0, limit);
|
|
38
|
+
const last = page.at(-1);
|
|
39
|
+
return {
|
|
40
|
+
buckets: page.map(({ id: _id, ...row }) => row),
|
|
41
|
+
nextCursor: last && rows.length > limit
|
|
42
|
+
? Buffer.from(JSON.stringify([last.bucketStart.toISOString(), last.id])).toString('base64url')
|
|
43
|
+
: null,
|
|
44
|
+
};
|
|
45
|
+
}
|