railyard/apps/product-analytics/test/qy/migrations.test.ts
caelum0x b4612a4f57 feat(analytics): alerts, weekly dashboard emails and Slack, Discord and HubSpot destinations (QY1.4, A25, A23)
Alerts and subscriptions (A25)
- PA src/alerts: threshold alerts (above/below a number) and anomaly alerts
  (the last complete interval N standard deviations from at least 7 before
  it) on any saved insight, watching one headline value per insight kind
  (metric.ts). Checked by the service scheduler every minute, each alert at
  its own hour or day, leased so two passes never double-send; an alert
  emails once when it starts firing and again only after it clears.
- Weekly dashboard emails at a weekday and hour (UTC): an HTML table of each
  tile's latest value and the interval before (no images), then the next
  weekly slot.
- Mail through the Rally Send transactional contract (Wave E 5.2:
  product, project, to, from_local, subject, html, text, idempotency_key,
  unsubscribe_url, tags; 202/422/429 read) when RALLY_TX_URL/KEY are set.
  The service has no other mail path, so without them each email is
  logged as not_configured (never dropped silently) and the console says so.
- Every email has an unsubscribe link (HMAC-signed, GET page or one-click
  POST); unsubscribed addresses are skipped and logged; per-recipient mail
  log (sent, failed, unsubscribed, not_configured).
- Migrations 0026 alerts, 0027 subscriptions, 0028 mail log and
  unsubscribes, 0029 row level security for all four.
- Console: product-analytics/alerts (one screen: alerts and weekly emails,
  pause, check or send now, delete, latest emails).

Destination catalogue (A23)
- Slack ({text, blocks}), Discord ({content}, no mentions) and HubSpot
  (contacts upserted by email through CRM v3 batch upsert with the
  customer's private app token) next to the webhook and S3 kinds
  (migration 0025). Each request carries Standard Webhooks headers under a
  per-destination signing secret shown once; the target secret (webhook
  address or token) is sealed with it and never read back. Delivery,
  backoff retries, the run log and the on/off switch are the exports
  runner's. Shapes follow PostHog CDP templates slack and hubspot (MIT,
  1348173f5911, nothing from ee/); NOTICE updated. Outside dev/test only
  hooks.slack.com and discord.com webhook addresses are accepted.
- MAX_DESTINATIONS 3 -> 6 (target) so the catalogue fits; the A3 cap test
  follows the constant. Console exports screens list the new kinds.

Also: the A2 lane-scope test now skips QY commits (the QY lane owns RY/
and wires the console on purpose). Deploy fragment and README name
PA_EXPORTS_KEY, PA_PUBLIC_URL, PA_CONSOLE_URL, RALLY_TX_URL, RALLY_TX_KEY.

Tests: product-analytics test/qy 26 (alerts 10 incl. one-tick mail with a
fake clock, anomaly, weekly table, unsubscribe, isolation, not configured,
Rally contract, copy lint of every email, console form mappings;
destinations 3 incl. signatures, isolation, retry with backoff and the
switch; migrations 2) + a3 exports 6 + a1 52/52 + a2 67/67 + a3 49/49;
console 142/142; PA and console tsc clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 13:35:28 +03:00

44 lines
3.8 KiB
TypeScript

// QY1.4 migrations (0025-0029): idempotent; the catalogue kinds are allowed;
// alerts, subscriptions, the mail log and unsubscribes are under row level
// security, so the request role sees and writes only its own project's rows.
import { test } from "node:test";
import assert from "node:assert/strict";
import { randomUUID } from "node:crypto";
import { migrate, MIGRATIONS } from "../../scripts/migrate.ts";
import { migratedPg, skipNoPg } from "../a1/helpers.ts";
const TABLES = ["alerts", "subscriptions", "mail_log", "mail_unsubscribes"];
test("0025-0029 apply twice; every new table is under row level security; the catalogue kinds are allowed", { skip: skipNoPg }, async () => {
const pg = await migratedPg();
for (const m of ["0025", "0026", "0027", "0028", "0029"]) assert.ok(MIGRATIONS.some((x) => x.startsWith(m)), m);
await migrate(pg.url);
assert.equal(pg.psql("select count(*) from pg_class c join pg_namespace n on n.oid = c.relnamespace where n.nspname = 'pa' and c.relkind in ('r','p') and not c.relispartition and not c.relrowsecurity"), "0");
const p = randomUUID();
for (const kind of ["webhook", "s3", "slack", "discord", "hubspot"]) pg.psql(`insert into pa.export_destinations (project_id, name, kind, config, secret_enc) values ('${p}', '${kind}', '${kind}', '{}', 'x')`);
assert.throws(() => pg.psql(`insert into pa.export_destinations (project_id, name, kind, config, secret_enc) values ('${p}', 'ftp', 'ftp', '{}', 'x')`), /check constraint/);
});
test("the request role sees and writes only its own project's alerts, subscriptions and mail rows", { skip: skipNoPg }, async () => {
const pg = await migratedPg();
const a = randomUUID();
const b = randomUUID();
for (const p of [a, b]) {
const i = pg.psql(`insert into pa.saved_insights (project_id, name, kind, query) values ('${p}', 'i', 'trends', '{}') returning id`);
const d = pg.psql(`insert into pa.dashboards (project_id, name) values ('${p}', 'd') returning id`);
const al = pg.psql(`insert into pa.alerts (project_id, insight_id, name, kind, direction, threshold, recipients) values ('${p}', '${i}', 'a', 'threshold', 'above', 1, array['x@y.example']) returning id`);
pg.psql(`insert into pa.subscriptions (project_id, dashboard_id, weekday, hour_utc, recipients, next_send_at) values ('${p}', '${d}', 1, 8, array['x@y.example'], now())`);
pg.psql(`insert into pa.mail_log (project_id, source, source_id, recipient, status) values ('${p}', 'alert', '${al}', 'x@y.example', 'sent')`);
pg.psql(`insert into pa.mail_unsubscribes (project_id, email) values ('${p}', 'x@y.example')`);
}
const asA = (sql: string) => pg.session("begin", "set local role pa_app", `select set_config('pa.project_id', '${a}', true)`, sql, "commit");
for (const t of TABLES) assert.match(asA(`select count(*) from pa.${t}`), /^1$/m, t);
assert.throws(() => asA(`insert into pa.mail_unsubscribes (project_id, email) values ('${b}', 'z@y.example')`), /row-level security/);
assert.doesNotMatch(asA(`update pa.alerts set enabled = false where project_id = '${b}' returning 1`), /^1$/m);
// Shape checks: a threshold alert needs its number; an anomaly its sensitivity; at most 20 recipients.
const i = pg.psql(`select id from pa.saved_insights where project_id = '${a}'`);
assert.throws(() => pg.psql(`insert into pa.alerts (project_id, insight_id, name, kind, direction, recipients) values ('${a}', '${i}', 'n', 'threshold', 'above', array['x@y.example'])`), /check constraint/);
assert.throws(() => pg.psql(`insert into pa.alerts (project_id, insight_id, name, kind, direction, recipients) values ('${a}', '${i}', 'm', 'anomaly', 'either', array['x@y.example'])`), /check constraint/);
assert.throws(() => pg.psql(`insert into pa.alerts (project_id, insight_id, name, kind, direction, threshold, recipients) values ('${a}', '${i}', 'r', 'threshold', 'above', 1, array[]::text[])`), /check constraint/);
});