|
| 1 | +import assert from 'node:assert/strict'; |
| 2 | +import { readFile } from 'node:fs/promises'; |
| 3 | +import test from 'node:test'; |
| 4 | +import { targetPool } from '../../../scripts/ad-networks/runtime-db.mjs'; |
| 5 | + |
| 6 | +// All writes and new functions are session-local fixtures, rolled back. This |
| 7 | +// exercises the migration SQL without installing it or touching public data. |
| 8 | +test('report revision tracks public changes, ignores bookkeeping and rolls back with the data', { |
| 9 | + skip: process.env.AD_NETWORKS_TEST_ENVIRONMENT !== 'development', |
| 10 | +}, async () => { |
| 11 | + const migration = await readFile(new URL('../../../supabase/migrations/20261019102740_ad_network_report_revision_counter.sql', import.meta.url), 'utf8'); |
| 12 | + const pool = targetPool({ environment: 'development' }); |
| 13 | + const client = await pool.connect(); |
| 14 | + const tables = ['ad_networks', 'ad_network_publishers', 'ad_network_publisher_relationships', |
| 15 | + 'ad_network_daily_counts', 'ad_network_relationship_events']; |
| 16 | + try { |
| 17 | + await client.query('begin'); |
| 18 | + await client.query(migration.match(/create table public.stack127_ad_network_report_revision \([\s\S]*?\n\);/)[0] |
| 19 | + .replace('create table public.', 'create temporary table ')); |
| 20 | + await client.query('insert into pg_temp.stack127_ad_network_report_revision(id) values(true)'); |
| 21 | + for (const table of tables) { |
| 22 | + // CTAS inherits column types, without defaults/sequences, public triggers |
| 23 | + // or constraints. All fixture IDs and values are supplied explicitly. |
| 24 | + await client.query(`create temporary table ${table} as select * from public.${table} with no data`); |
| 25 | + } |
| 26 | + await client.query('create temporary table stack127_pages(slug text)'); |
| 27 | + await client.query('create temporary table report_queue(entity_type text,slug text,source text)'); |
| 28 | + await client.query(`create function pg_temp.stack127_enqueue_revalidation(text,text,text) returns void language sql as $$ |
| 29 | + insert into pg_temp.report_queue values($1,$2,$3) $$`); |
| 30 | + await client.query(`create function pg_temp.stack127_touch_page(text,text) returns void language plpgsql as $$begin return; end$$`); |
| 31 | + const trigger = migration.match(/create or replace function public.stack127_touch_ad_network_reports\(\)[\s\S]*?\$\$;/)[0] |
| 32 | + .replaceAll('public.stack127_touch_ad_network_reports', 'pg_temp.stack127_touch_ad_network_reports') |
| 33 | + .replaceAll('public.stack127_ad_network_report_revision', 'pg_temp.stack127_ad_network_report_revision') |
| 34 | + .replaceAll('public.stack127_enqueue_revalidation', 'pg_temp.stack127_enqueue_revalidation') |
| 35 | + .replaceAll('public.stack127_touch_page', 'pg_temp.stack127_touch_page') |
| 36 | + .replaceAll('public.stack127_pages', 'pg_temp.stack127_pages'); |
| 37 | + await client.query(trigger); |
| 38 | + const revisions = migration.match(/create or replace function public.stack127_cache_source_revisions\([\s\S]*?\$\$;/)[0] |
| 39 | + .replace('public.stack127_cache_source_revisions', 'pg_temp.stack127_cache_source_revisions') |
| 40 | + .replaceAll('public.stack127_ad_network_report_revision', 'pg_temp.stack127_ad_network_report_revision') |
| 41 | + .replaceAll('public.ad_networks', 'pg_temp.ad_networks'); |
| 42 | + await client.query(revisions); |
| 43 | + for (const table of tables) { |
| 44 | + await client.query(`create trigger report_insert after insert on pg_temp.${table} |
| 45 | + referencing new table as new_rows for each statement execute function pg_temp.stack127_touch_ad_network_reports()`); |
| 46 | + await client.query(`create trigger report_update after update on pg_temp.${table} |
| 47 | + referencing old table as old_rows new table as new_rows for each statement execute function pg_temp.stack127_touch_ad_network_reports()`); |
| 48 | + await client.query(`create trigger report_delete after delete on pg_temp.${table} |
| 49 | + referencing old table as old_rows for each statement execute function pg_temp.stack127_touch_ad_network_reports()`); |
| 50 | + await client.query(`create trigger report_truncate after truncate on pg_temp.${table} |
| 51 | + for each statement execute function pg_temp.stack127_touch_ad_network_reports()`); |
| 52 | + } |
| 53 | + const revision = async () => BigInt((await client.query('select revision from pg_temp.stack127_ad_network_report_revision')).rows[0].revision); |
| 54 | + const fingerprints = async slugs => (await client.query(`select slug,fingerprint |
| 55 | + from pg_temp.stack127_cache_source_revisions(array['ad_networks'],$1::text[]) order by slug`, [slugs ?? null])).rows; |
| 56 | + const change = async (sql, expected = true) => { |
| 57 | + const before = await revision(), fingerprintsBefore = await fingerprints(); |
| 58 | + const queued = (await client.query('select count(*) as n from pg_temp.report_queue')).rows[0].n; |
| 59 | + await client.query(sql); |
| 60 | + assert.equal(await revision(), before + (expected ? 1n : 0n), sql); |
| 61 | + const after = await fingerprints(); |
| 62 | + for (const previous of fingerprintsBefore) { |
| 63 | + const current = after.find(row => row.slug === previous.slug); |
| 64 | + if (current) assert.equal(current.fingerprint !== previous.fingerprint, expected, `${sql}: ${previous.slug}`); |
| 65 | + } |
| 66 | + assert.equal(BigInt((await client.query('select count(*) as n from pg_temp.report_queue')).rows[0].n), |
| 67 | + BigInt(queued) + (expected ? 1n : 0n)); |
| 68 | + }; |
| 69 | + assert.deepEqual((await fingerprints()).map(row => row.slug), ['all']); |
| 70 | + await change("insert into pg_temp.ad_networks(id,slug,name) values(1,'fixture-a','A'),(2,'fixture-b','B')"); |
| 71 | + await change("insert into pg_temp.ad_network_publishers(id,normalized_domain,niche) values(1,'fixture.example','food')"); |
| 72 | + await change(`insert into pg_temp.ad_network_publisher_relationships(ad_network_id,publisher_id,status,relationship_type,evidence) |
| 73 | + values(1,1,'confirmed','active_network_use','{}')`); |
| 74 | + await change(`insert into pg_temp.ad_network_daily_counts(ad_network_id,snapshot_on,listed_count,confirmed_count,stale_count) |
| 75 | + values(1,'2026-10-19',1,1,0)`); |
| 76 | + await change(`insert into pg_temp.ad_network_relationship_events(ad_network_id,publisher_id,event,observed_at,relationship_type) |
| 77 | + values(1,1,'joined','2026-10-19','active_network_use')`); |
| 78 | + assert.deepEqual((await fingerprints()).map(row => row.slug), ['all', 'fixture-a', 'fixture-b']); |
| 79 | + assert.equal((await fingerprints(['all'])).length, 1); |
| 80 | + assert.deepEqual(await fingerprints(['missing']), []); |
| 81 | + assert.equal((await client.query("select * from pg_temp.stack127_cache_source_revisions(array['missing'])")).rowCount, 0); |
| 82 | + |
| 83 | + await change("update pg_temp.ad_network_publishers set next_check_at=now(),updated_at=now(),check_attempt_count=10,ads_txt_etag='new'", false); |
| 84 | + await change("update pg_temp.ad_network_publisher_relationships set consecutive_misses=2,evidence='{\"ignored\":true}'", false); |
| 85 | + await change('update pg_temp.ad_networks set updated_at=now()', false); |
| 86 | + await change('update pg_temp.ad_network_daily_counts set captured_at=now()', false); |
| 87 | + await change("update pg_temp.ad_network_publishers set niche='food'", false); |
| 88 | + await change("update pg_temp.ad_network_publishers set niche='tech' where id=-1", false); |
| 89 | + await change("update pg_temp.ad_network_publishers set niche='tech'"); |
| 90 | + await change(`update pg_temp.ad_network_publishers set last_check_evidence='{"homepage":{"title":"Changed"}}'`); |
| 91 | + await change(`update pg_temp.ad_network_publishers set discovery_sources='["new-source"]'`); |
| 92 | + await change(`update pg_temp.ad_network_publisher_relationships set verification_method='direct_ads_txt'`); |
| 93 | + await change(`update pg_temp.ad_network_publisher_relationships set evidence='{"manager_domain":"manager.example"}'`); |
| 94 | + await change("update pg_temp.ad_networks set manager_domains=array['manager.example']"); |
| 95 | + await change('update pg_temp.ad_network_daily_counts set listed_count=2'); |
| 96 | + await change("update pg_temp.ad_network_relationship_events set observed_at='2026-10-20'"); |
| 97 | + await change(`insert into pg_temp.ad_network_publisher_relationships(ad_network_id,publisher_id,status) |
| 98 | + values(2,1,'candidate')`, false); |
| 99 | + await change("update pg_temp.ad_network_publisher_relationships set status='needs_review' where ad_network_id=2", false); |
| 100 | + await change("update pg_temp.ad_network_publisher_relationships set status='confirmed' where ad_network_id=2"); |
| 101 | + await change("update pg_temp.ad_network_publisher_relationships set status='needs_review' where ad_network_id=2"); |
| 102 | + await change('delete from pg_temp.ad_network_publisher_relationships where ad_network_id=2', false); |
| 103 | + |
| 104 | + const beforeRollback = await fingerprints(), versionBeforeRollback = await revision(); |
| 105 | + await client.query('savepoint mutation'); |
| 106 | + await change("update pg_temp.ad_network_publishers set niche='gaming'"); |
| 107 | + await client.query('rollback to savepoint mutation'); |
| 108 | + assert.equal(await revision(), versionBeforeRollback); |
| 109 | + assert.deepEqual(await fingerprints(), beforeRollback); |
| 110 | + for (const table of [...tables].reverse()) await change(`delete from pg_temp.${table}`); |
| 111 | + for (const table of tables) await change(`truncate pg_temp.${table}`); |
| 112 | + assert.deepEqual((await fingerprints()).map(row => row.slug), ['all']); |
| 113 | + } finally { |
| 114 | + await client.query('rollback').catch(() => {}); |
| 115 | + client.release(); await pool.end(); |
| 116 | + } |
| 117 | +}); |
0 commit comments