railyard/apps/insights/tests/api/report-migration.spec.ts
caelum0x 1bc04fa81b feat(insights): the Insights fork behind the add-on, site entries, tenant summaries, caps that say what happens (PY1.3)
Railyard side of PY1.3 (RYP-D2, RYP-E1, SC-E3). Acceptance:
1. apps/insights: umami-software/umami v3.4.0 (MIT, commit ec0ff503),
   vendored --depth 1, LICENSE kept, NOTICE added. Fork additions only:
   src/railyard/{ingest,summary,tenancy,api-only}.ts, /v1/ingest/batch (the
   edge collector contract v1, bearer INSIGHTS_INGEST_TOKEN, no IP ever,
   retried batches de-duplicated by migration 90_railyard_ingest_receipts),
   /api/v1/tenants/{org}/summary (bearer INSIGHTS_API_TOKEN), src/proxy.ts
   (INSIGHTS_API_ONLY=1 serves only the Railyard API and the heartbeat).
   Tenant isolation is tested at the API level (an app id owned by another org
   is refused) and at the SQL level (upstream migrations 01-26 plus 90 on a
   throwaway cluster: org B never reads org A's rows, even naming its app).
   Upstream vitest suite: not run on the Mac (pnpm 12.3.4 pinned upstream,
   disk floor); it runs in the image build on box 2 or CI.
2. No upstream product name in anything a customer loads: the page tag, the
   console pages and the fork's additions (tests); the upstream dashboard is
   never served in API-only mode.
3. The console writes the collector's site entry on "Add app", on
   auto-created apps from deploys, and rewrites every entry on add-on, plan or
   pause changes (lib/sites.ts, SITES KV binding). The bridge gains
   `sites` (the project's app, site key, page tag and collector URLs, entry
   written) and the analytics proof is the first event from Insights. The
   console's Insights page shows visitors, events, first event and the
   visit -> signup -> first action funnel.
5. insights-edge/src/caps.ts: at 100% of the cap events are still counted and
   not stored until the next UTC month; the console shows the same message
   from a byte-identical copy (lib/caps.ts, tested).
4 (384 MB at 50 events a second for 10 min) is measured on staging before deploy.

Env: INSIGHTS_API_URL, INSIGHTS_API_TOKEN, SITES KV binding (console);
INSIGHTS_INGEST_TOKEN, INSIGHTS_API_TOKEN, INSIGHTS_API_ONLY (Insights).

Tests: console 54/54 (tsc clean), insights fork 7/7 (incl. SQL isolation),
insights-edge caps + collector + sim 14/14, tests/contract 3/3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 21:23:38 +03:00

191 lines
6.8 KiB
TypeScript

import { serializeAnalyticsQuery } from '../../src/lib/analytics-query';
import { expect, test } from './fixtures';
import { dateRange } from './helpers/dates';
import { uniqueName } from './helpers/entities';
const calculations = [
['journey', 'journeys', { steps: 3 }],
['retention', 'retention', {}],
['breakdown', 'breakdown', { fields: ['path', 'country'] }],
['attribution', 'attribution', { model: 'first-click', type: 'path', step: '/pricing' }],
['heatmap', 'heatmaps', { mode: 'click', urlPath: '/' }],
[
'funnel',
'funnels/stats',
{
window: 60,
steps: [
{ type: 'path', value: '/' },
{ type: 'path', value: '/pricing' },
],
},
],
['goal', 'goals/stats', { type: 'path', value: '/' }],
] as const;
// SQL rankings can have ties, so compare result content independently of tied row order.
function canonical(value: any): any {
if (Array.isArray(value))
return value.map(canonical).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
if (value && typeof value === 'object')
return Object.fromEntries(
Object.keys(value)
.sort()
.map(key => [key, canonical(value[key])]),
);
return value;
}
for (const [type, path, parameters] of calculations) {
test(`GET ${path} matches legacy ${type} results and access`, async ({
admin,
share,
viewer,
seed,
}) => {
const range = { ...dateRange(seed), timezone: 'UTC', unit: 'day' };
const body = {
websiteId: seed.website.id,
type,
filters: range,
parameters: {
startDate: new Date(range.startAt).toISOString(),
endDate: new Date(range.endAt).toISOString(),
timezone: 'UTC',
unit: 'day',
...parameters,
},
};
const url = `/api/websites/${seed.website.id}/${path}`;
const params = serializeAnalyticsQuery({ ...range, ...parameters });
const legacy = await admin.post(`/api/reports/${type}`, body);
const result = await admin.get(url, { params });
expect(legacy.status).toBe(200);
expect(result.status).toBe(200);
expect(canonical(result.body)).toEqual(canonical(legacy.body));
expect((await viewer.get(url, { params })).status).toBe(401);
expect((await (await share()).get(url, { params })).status).toBe(
type === 'heatmap' ? 401 : 200,
);
expect((await admin.get(url)).status).toBe(400);
});
}
for (const [type, parameters] of [
[
'funnel',
{
window: 60,
steps: [
{ type: 'path', value: '/' },
{ type: 'event', value: 'signup' },
],
},
],
['goal', { type: 'path', value: '/' }],
] as const) {
test(`${type} definitions preserve IDs and scope saved stats to the website`, async ({
admin,
viewer,
share,
seed,
}) => {
const base = `/api/websites/${seed.website.id}/${type}s`;
const created = await admin.post(base, { name: uniqueName(type), parameters });
expect(created.status).toBe(200);
const id = created.body.id;
try {
expect((await admin.get(`/api/reports/${id}`)).body.id).toBe(id);
expect((await admin.get(`${base}/${id}`)).body.parameters).toEqual(parameters);
expect((await (await share()).get(base)).status).toBe(200);
const range = dateRange(seed);
const saved = await admin.get(`${base}/${id}/stats`, { params: range });
const preview = await admin.get(`${base}/stats`, {
params: serializeAnalyticsQuery({ ...range, ...parameters }),
});
expect(saved.status).toBe(200);
expect(saved.body).toEqual(preview.body);
expect((await viewer.post(`${base}/${id}`, { name: 'Denied', parameters })).status).toBe(401);
const otherBase = `/api/websites/${seed.website2.id}/${type}s/${id}`;
expect((await admin.get(otherBase)).status).toBe(404);
expect((await admin.post(otherBase, { name: 'Wrong website', parameters })).status).toBe(404);
expect((await admin.del(otherBase)).status).toBe(404);
const otherType = type === 'goal' ? 'funnels' : 'goals';
expect((await admin.get(`/api/websites/${seed.website.id}/${otherType}/${id}`)).status).toBe(
404,
);
const updated = await admin.post(`${base}/${id}`, {
name: 'Updated',
websiteId: seed.website2.id,
type: otherType,
parameters,
});
expect(updated.status).toBe(200);
expect(updated.body).toMatchObject({ id, name: 'Updated', websiteId: seed.website.id, type });
} finally {
expect((await admin.del(`${base}/${id}`)).status).toBe(200);
}
expect((await admin.get(`${base}/${id}`)).status).toBe(404);
});
}
test('performance and UTM datasets reproduce legacy aggregates', async ({
admin,
viewer,
share,
seed,
}) => {
const range = { ...dateRange(seed), timezone: 'UTC', unit: 'day' };
const body = (type: string) => ({
websiteId: seed.website.id,
type,
filters: range,
parameters: {
startDate: new Date(range.startAt).toISOString(),
endDate: new Date(range.endAt).toISOString(),
timezone: 'UTC',
unit: 'day',
metric: 'lcp',
},
});
const base = `/api/websites/${seed.website.id}`;
const performance = await admin.post('/api/reports/performance', body('performance'));
expect(performance.status).toBe(200);
for (const [path, key] of [
['performance/stats', 'summary'],
['performance/chart', 'chart'],
] as const) {
const response = await admin.get(`${base}/${path}`, { params: range });
expect(response.status).toBe(200);
expect(canonical(key === 'chart' ? response.body.chart : response.body)).toEqual(
canonical(performance.body[key]),
);
expect((await viewer.get(`${base}/${path}`, { params: range })).status).toBe(401);
expect((await (await share()).get(`${base}/${path}`, { params: range })).status).toBe(200);
}
for (const [type, key] of [
['path', 'pages'],
['title', 'pageTitles'],
['device', 'devices'],
['browser', 'browsers'],
]) {
const response = await admin.get(`${base}/performance/metrics`, { params: { ...range, type } });
expect(response.status).toBe(200);
expect(canonical(response.body)).toEqual(canonical(performance.body[key]));
}
const utm = await admin.post('/api/reports/utm', body('utm'));
expect(utm.status).toBe(200);
for (const type of ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']) {
const response = await admin.get(`${base}/utm/metrics`, { params: { ...range, type } });
expect(response.status).toBe(200);
expect(canonical(response.body)).toEqual(canonical(utm.body[type]));
}
expect(
(await admin.get(`${base}/utm/metrics`, { params: { ...range, type: 'invalid' } })).status,
).toBe(400);
expect(
(await admin.get(`${base}/performance/metrics`, { params: { ...range, type: 'invalid' } }))
.status,
).toBe(400);
});