\set ON_ERROR_STOP on begin; -- ----------------------------------------------------------------------------- -- Badge print queue regression suite (rollback only). -- -- Run it TOGETHER with the migration in one transaction so nothing is persisted: -- -- (echo 'begin;'; \ -- cat supabase/migrations/20261018170000_badge_print_queue.sql; \ -- sed '/^begin;$/d' supabase/tests/badge_print_tests.sql) \ -- | docker exec -i supabase_db_Convivo psql -X -U postgres -d postgres \ -- -v ON_ERROR_STOP=1 -- -- The migration is re-runnable, so the same stream also works after the -- migration has been applied for real (idempotency check). -- ----------------------------------------------------------------------------- -- Start from empty stations/queues so real local data can't skew counts (rolled back). delete from public.print_stations; delete from pgmq.q_badge_print; delete from pgmq.q_badge_print_dlq; delete from pgmq.a_badge_print; delete from pgmq.a_badge_print_dlq; create temporary table bp_results (name text); grant insert, select on bp_results to authenticated, anon; create function pg_temp.assert_bp(p_condition boolean, p_name text) returns void language plpgsql as $$ begin if p_condition is distinct from true then raise exception 'FAIL: %', p_name; end if; insert into bp_results values (p_name); end; $$; -- Scratch tables (owned by postgres, writable/readable by the API roles so the -- anon blocks can store and read RPC results). create temporary table bp_station (id uuid, token text); create temporary table bp_station2 (id uuid, token text); create temporary table bp_hb (hb jsonb); create temporary table bp_claim (msg_id bigint, read_ct integer, payload jsonb); create temporary table bp_enq (msg_id bigint); create temporary table bp_res (res text); create temporary table bp_done (ok boolean); create temporary table bp_ov (ov jsonb); grant insert, select, delete on bp_station, bp_station2, bp_hb, bp_claim, bp_enq, bp_res, bp_done, bp_ov to authenticated, anon; -- ----------------------------------------------------------------------------- -- 1. FIXTURES -- ----------------------------------------------------------------------------- -- One active event with a badge layout, one inactive event without a layout. update public.events set is_active = false where is_active; insert into public.events (id, name, start_date, end_date, is_active, company) values ('b9d00001-0000-0000-0000-00000000000a', 'Print event A', current_date, current_date, true, 'Convivo GmbH'), ('b9d00002-0000-0000-0000-00000000000b', 'Print event B', current_date, current_date, false, null); insert into public.contacts (email, full_name, is_admin) values ('bp-admin@example.test', 'Print Admin', true), ('bp-staff@appe.at', 'Print Staff', false), ('bp-viewer@example.test','Plain Viewer', false), ('bp-att1@example.test', 'Ada Attendee', false), ('bp-att2@example.test', 'Checked Ina', false), ('bp-att3@example.test', 'Session Sam', false), ('bp-att4@example.test', 'Direct Dana', false), ('bp-att5@example.test', 'Savepoint Sol', false), ('bp-attb@example.test', 'No-layout Nia', false); insert into public.registrations (event_id, contact_email, type, checked_in, qr_token) values ('b9d00001-0000-0000-0000-00000000000a', 'bp-staff@appe.at', 'staff', false, null), ('b9d00001-0000-0000-0000-00000000000a', 'bp-att1@example.test', 'attendee', false, 'BPQR-ATT-1'), ('b9d00001-0000-0000-0000-00000000000a', 'bp-att2@example.test', 'attendee', true, 'BPQR-ATT-2'), ('b9d00001-0000-0000-0000-00000000000a', 'bp-att3@example.test', 'attendee', false, 'BPQR-ATT-3'), ('b9d00001-0000-0000-0000-00000000000a', 'bp-att4@example.test', 'attendee', false, 'BPQR-ATT-4'), ('b9d00001-0000-0000-0000-00000000000a', 'bp-att5@example.test', 'attendee', false, 'BPQR-ATT-5'), ('b9d00002-0000-0000-0000-00000000000b', 'bp-attb@example.test', 'attendee', false, 'BPQR-ATT-B'); -- Event A: an empty layout that sorts first (created_at) plus the default one -- that actually has elements. The payload must pick the default with elements. insert into public.badge_layouts (id, event_id, name, is_default, page_width_mm, page_height_mm, elements, created_at) values ('b9d00004-0000-0000-0000-00000000000a', 'b9d00001-0000-0000-0000-00000000000a', 'AAA Empty', false, 100, 70, '[]'::jsonb, now() - interval '3 hours'), ('b9d00005-0000-0000-0000-00000000000a', 'b9d00001-0000-0000-0000-00000000000a', 'Default', true, 100, 70, '[{"id":"t1","type":"text","x":5,"y":5,"width":90,"height":12,"rotation":0,"content":"attendee_name","text":"","font":"Open Sans","font_size":14,"line_height":1,"color":"#000000","bold":true,"italic":false,"align_h":"center","align_v":"middle","transform":"none"}]'::jsonb, now() - interval '2 hours'); -- A session so the regular session check-in path can be exercised. insert into public.slots (id, event_id, type, name, slot_date, start_time, end_time) values (900001, 'b9d00001-0000-0000-0000-00000000000a', 'session', 'Print slot', current_date, '10:00', '11:00'); insert into public.sessions (id, event_id, slot_id, title) values ('b9d00003-0000-0000-0000-00000000000a', 'b9d00001-0000-0000-0000-00000000000a', 900001, 'Print session'); -- Deterministic, empty queues for this run (rolled back with everything else). delete from pgmq.q_badge_print; delete from pgmq.q_badge_print_dlq; delete from pgmq.a_badge_print; select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print), 'queues start empty for the run'); select pg_temp.assert_bp( (select count(*) = 1 from public.events where is_active) and (select is_active from public.events where id = 'b9d00001-0000-0000-0000-00000000000a'), 'exactly one active event, and it is the print event'); -- ----------------------------------------------------------------------------- -- 2. WELCOME CHECK-IN ENQUEUES A BADGE JOB -- ----------------------------------------------------------------------------- select set_config('request.jwt.claims', '{"email":"bp-staff@appe.at","role":"authenticated"}', true); create temporary table bp_scan1 as select * from public.welcome_checkin('BPQR-ATT-1'); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'first welcome check-in enqueues exactly one job'); select pg_temp.assert_bp( (select already = false from bp_scan1), 'first check-in reports already = false'); select pg_temp.assert_bp( (select attendee_email = 'bp-att1@example.test' and attendee_name = 'Ada Attendee' from bp_scan1), 'check-in still returns the attendee'); select pg_temp.assert_bp( (select checked_in from public.registrations where contact_email = 'bp-att1@example.test'), 'check-in marks the attendee checked in'); -- Payload shape: exactly the seven documented keys plus requested_at. select pg_temp.assert_bp( (select array_agg(k order by k) from (select jsonb_object_keys(q.message) as k from (select message from pgmq.q_badge_print limit 1) q) x) = array['event','kind','layout','registration','requested_at','requested_by','sample','schema'], 'payload top level keys are exact'); select pg_temp.assert_bp( (select array_agg(k order by k) from (select jsonb_object_keys(q.message -> 'sample') as k from (select message from pgmq.q_badge_print limit 1) q) x) = array['company','email','event_name','full_name','qr_token','ticket_type'], 'payload sample keys are exact'); select pg_temp.assert_bp( (select array_agg(k order by k) from (select jsonb_object_keys(q.message -> 'event') as k from (select message from pgmq.q_badge_print limit 1) q) x) = array['company','id','name'], 'payload event keys are exact'); select pg_temp.assert_bp( (select array_agg(k order by k) from (select jsonb_object_keys(q.message -> 'registration') as k from (select message from pgmq.q_badge_print limit 1) q) x) = array['email','id','type'], 'payload registration keys are exact'); select pg_temp.assert_bp( (select array_agg(k order by k) from (select jsonb_object_keys(q.message -> 'layout') as k from (select message from pgmq.q_badge_print limit 1) q) x) = array['elements','id','name','page_height_mm','page_width_mm'], 'payload layout keys are exact'); select pg_temp.assert_bp( (select message ->> 'schema' = 'convivo.badge-print/v1' and message ->> 'kind' = 'checkin' and message ->> 'requested_by' = 'bp-staff@appe.at' from pgmq.q_badge_print limit 1), 'payload schema/kind/requested_by are correct'); select pg_temp.assert_bp( (select message -> 'sample' ->> 'full_name' = 'Ada Attendee' and message -> 'sample' ->> 'email' = 'bp-att1@example.test' and message -> 'sample' ->> 'ticket_type' = 'attendee' and message -> 'sample' ->> 'qr_token' = 'BPQR-ATT-1' and message -> 'sample' ->> 'event_name' = 'Print event A' and message -> 'sample' ->> 'company' = 'Convivo GmbH' from pgmq.q_badge_print limit 1), 'payload sample values are correct'); select pg_temp.assert_bp( (select jsonb_typeof(message -> 'layout' -> 'page_width_mm') = 'number' and jsonb_typeof(message -> 'layout' -> 'page_height_mm') = 'number' and (message -> 'layout' ->> 'page_width_mm')::numeric = 100 and (message -> 'layout' ->> 'page_height_mm')::numeric = 70 and jsonb_array_length(message -> 'layout' -> 'elements') = 1 from pgmq.q_badge_print limit 1), 'layout page sizes are JSON numbers with the right elements'); select pg_temp.assert_bp( (select message -> 'layout' ->> 'name' = 'Default' from pgmq.q_badge_print limit 1), 'layout choice prefers the default layout that has elements'); select pg_temp.assert_bp( (select (message ->> 'requested_at')::timestamptz between now() - interval '5 minutes' and now() + interval '5 minutes' from pgmq.q_badge_print limit 1), 'requested_at is a usable timestamp'); -- Full document equality (requested_at excluded: it is generated per call). select pg_temp.assert_bp( (select m.message - 'requested_at' = jsonb_build_object( 'schema', 'convivo.badge-print/v1', 'kind', 'checkin', 'requested_by', 'bp-staff@appe.at', 'event', jsonb_build_object('id', e.id, 'name', e.name, 'company', e.company), 'registration', jsonb_build_object('id', r.id, 'email', r.contact_email, 'type', r."type"), 'sample', jsonb_build_object( 'full_name', c.full_name, 'email', r.contact_email, 'ticket_type', r."type"::text, 'qr_token', r.qr_token, 'event_name', e.name, 'company', coalesce(e.company, '')), 'layout', jsonb_build_object( 'id', l.id, 'name', l.name, 'page_width_mm', l.page_width_mm, 'page_height_mm', l.page_height_mm, 'elements', l.elements)) - 'requested_at' from pgmq.q_badge_print m join public.registrations r on r.id = (m.message -> 'registration' ->> 'id')::uuid join public.events e on e.id = r.event_id join public.contacts c on c.email = r.contact_email join public.badge_layouts l on l.id = (m.message -> 'layout' ->> 'id')::uuid limit 1), 'check-in payload equals the expected badge document'); -- A second scan of the same lanyard is a no-op for the queue. create temporary table bp_scan2 as select * from public.welcome_checkin('BPQR-ATT-1'); select pg_temp.assert_bp((select already = true from bp_scan2), 'second scan reports already = true'); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'second check-in enqueues nothing'); -- An attendee that was already checked in before the scan produces no job. create temporary table bp_scan3 as select * from public.welcome_checkin('BPQR-ATT-2'); select pg_temp.assert_bp((select already = true from bp_scan3), 'pre-checked-in attendee reports already = true'); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'already checked-in attendee enqueues nothing'); -- An event without a badge layout: check-in works, nothing is queued. update public.events set is_active = true where id = 'b9d00002-0000-0000-0000-00000000000b'; create temporary table bp_scan4 as select * from public.welcome_checkin('BPQR-ATT-B'); select pg_temp.assert_bp( (select attendee_email = 'bp-attb@example.test' from bp_scan4), 'check-in succeeds for an event without a layout'); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'event without a layout enqueues nothing'); update public.events set is_active = true where id = 'b9d00001-0000-0000-0000-00000000000a'; -- The regular session check-in must not print badges. It now requires a prior -- front-desk (welcome) check-in, so mark the attendee checked in first. update public.registrations set checked_in = true where contact_email = 'bp-att3@example.test'; select public.checkin_attendee('b9d00003-0000-0000-0000-00000000000a', 'BPQR-ATT-3'); select pg_temp.assert_bp( (select count(*) = 1 from public.checkins where session_id = 'b9d00003-0000-0000-0000-00000000000a'), 'session check-in recorded'); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'session check-in enqueues nothing'); -- Front-desk gate: an attendee not checked in at the event cannot be scanned -- into a session (raises a clear message, records nothing). do $$ begin begin perform public.checkin_attendee('b9d00003-0000-0000-0000-00000000000a', 'BPQR-ATT-5'); raise exception 'front-desk gate allowed a session check-in'; exception when raise_exception then if sqlerrm not like '%front desk%' then raise; end if; end; perform pg_temp.assert_bp(true, 'session check-in requires a front-desk check-in'); end; $$; -- A direct write of checked_in (admin edit) must not print badges either. update public.registrations set checked_in = true where contact_email = 'bp-att4@example.test'; select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'direct checked_in update enqueues nothing'); -- The enqueue is transactional with the check-in itself. savepoint bp_sp; select public.welcome_checkin('BPQR-ATT-5'); rollback to savepoint bp_sp; select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'rolled back check-in leaves no queue message'); select pg_temp.assert_bp( (select not checked_in from public.registrations where contact_email = 'bp-att5@example.test'), 'rolled back check-in leaves the attendee unchecked'); -- Badge copies: a welcome check-in prints events.badge_copies labels (default -- 1 is covered by the first check-in above). Isolated in a savepoint so the -- queue returns to one for the rest of the run. savepoint bp_copies; update public.events set badge_copies = 3 where id = 'b9d00001-0000-0000-0000-00000000000a'; select public.welcome_checkin('BPQR-ATT-5'); select pg_temp.assert_bp( (select count(*) = 4 from pgmq.q_badge_print), 'welcome check-in enqueues badge_copies (3) labels'); rollback to savepoint bp_copies; select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'copies test rolled back cleanly'); -- ----------------------------------------------------------------------------- -- 2b. WELCOME CHECK-IN PREVIEW (read-only: resolves the name + will_print) -- ----------------------------------------------------------------------------- -- bp-att5 is still unchecked (its scan was rolled back) and event A has a -- layout, so the preview must report will_print = true WITHOUT checking in or -- enqueueing anything. create temporary table bp_prev1 as select * from public.preview_welcome_checkin('BPQR-ATT-5'); select pg_temp.assert_bp( (select attendee_email = 'bp-att5@example.test' and attendee_name = 'Savepoint Sol' from bp_prev1), 'preview resolves the attendee name from the QR token'); select pg_temp.assert_bp( (select already = false and will_print = true from bp_prev1), 'preview of an unchecked attendee reports will_print'); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print), 'preview enqueues nothing'); select pg_temp.assert_bp( (select not checked_in from public.registrations where contact_email = 'bp-att5@example.test'), 'preview does not check the attendee in'); -- An already-checked-in attendee: preview reports already and will_print = false. create temporary table bp_prev2 as select * from public.preview_welcome_checkin('BPQR-ATT-2'); select pg_temp.assert_bp( (select already = true and will_print = false from bp_prev2), 'preview of a checked-in attendee reports no print'); -- The preview also states how many labels a confirm would print, so the scanner -- popup can be truthful about the copy count instead of "this person's label". select pg_temp.assert_bp( (select copies = 1 from bp_prev1), 'preview reports copies = 1 by default'); select pg_temp.assert_bp( (select copies = 0 from bp_prev2), 'preview reports no copies when nothing will print'); savepoint bp_prev_copies; update public.events set badge_copies = 3 where id = 'b9d00001-0000-0000-0000-00000000000a'; select pg_temp.assert_bp( (select copies = 3 from public.preview_welcome_checkin('BPQR-ATT-5')), 'preview reports the event badge_copies'); rollback to savepoint bp_prev_copies; -- An event without a badge layout: check-in would work but nothing prints. -- (bp-attb was checked in by the section-2 scan; reset it so the preview -- isolates the "no layout" reason rather than "already checked in".) update public.registrations set checked_in = false where contact_email = 'bp-attb@example.test'; update public.events set is_active = true where id = 'b9d00002-0000-0000-0000-00000000000b'; update public.events set is_active = false where id = 'b9d00001-0000-0000-0000-00000000000a'; create temporary table bp_prev3 as select * from public.preview_welcome_checkin('BPQR-ATT-B'); select pg_temp.assert_bp( (select already = false and will_print = false from bp_prev3), 'preview without a layout reports no print'); update public.events set is_active = true where id = 'b9d00001-0000-0000-0000-00000000000a'; update public.events set is_active = false where id = 'b9d00002-0000-0000-0000-00000000000b'; -- A plain (non-staff) viewer cannot preview; the guard matches welcome_checkin -- (a plain RAISE EXCEPTION, i.e. sqlstate P0001 / raise_exception). select set_config('request.jwt.claims', '{"email":"bp-viewer@example.test","role":"authenticated"}', true); do $$ begin begin perform * from public.preview_welcome_checkin('BPQR-ATT-5'); raise exception 'non-staff preview allowed'; exception when raise_exception then if sqlerrm <> 'staff or admin only' then raise; end if; end; perform pg_temp.assert_bp(true, 'preview is staff/admin only'); end; $$; -- The anonymous role cannot preview either. select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; do $$ begin begin perform * from public.preview_welcome_checkin('BPQR-ATT-5'); raise exception 'anon preview allowed'; exception when insufficient_privilege then null; end; perform pg_temp.assert_bp(true, 'anon cannot preview a check-in'); end; $$; reset role; -- ----------------------------------------------------------------------------- -- 3. PRINT STATION PROVISIONING AND PERMISSIONS -- ----------------------------------------------------------------------------- select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); insert into bp_station select * from public.create_print_station('Front desk'); select pg_temp.assert_bp( (select count(*) = 1 from bp_station), 'admin can create a print station'); select pg_temp.assert_bp( (select token like 'cvp_%' and length(token) = 68 from bp_station), 'station token is cvp_ plus 64 hex chars'); select pg_temp.assert_bp( (select p.token_hash = encode(extensions.digest(s.token, 'sha256'), 'hex') and p.token_hash !~ 'cvp_' from public.print_stations p, bp_station s where p.id = s.id), 'only the sha256 of the token is stored'); select pg_temp.assert_bp( (select name = 'Front desk' and revoked_at is null and last_seen_at is null from public.print_stations p join bp_station s on s.id = p.id), 'new station starts unseen and active'); -- Blank names are rejected. do $$ begin begin perform * from public.create_print_station(' '); raise exception 'blank station name allowed'; exception when raise_exception then if sqlerrm <> 'station name is required' then raise; end if; end; perform pg_temp.assert_bp(true, 'blank station name rejected'); end; $$; -- Non-admins get a hard permission error. select set_config('request.jwt.claims', '{"email":"bp-viewer@example.test","role":"authenticated"}', true); do $$ begin begin perform public.create_print_station('Sneaky'); raise exception 'non-admin create allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; begin perform public.get_print_overview(); raise exception 'non-admin overview allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; perform pg_temp.assert_bp(true, 'non-admin cannot create stations or read the overview'); end; $$; -- The API roles have no direct access to the queues or the station table. select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; do $$ begin begin perform count(*) from pgmq.q_badge_print; raise exception 'anon read the queue'; exception when insufficient_privilege then null; end; begin perform count(*) from pgmq.q_badge_print_dlq; raise exception 'anon read the dead letter queue'; exception when insufficient_privilege then null; end; begin perform count(*) from public.print_stations; raise exception 'anon read print_stations'; exception when insufficient_privilege then null; end; begin perform count(*) from pgmq.send('badge_print', '{}'::jsonb); raise exception 'anon called pgmq.send'; exception when insufficient_privilege then null; end; perform pg_temp.assert_bp(true, 'anon cannot touch pgmq or print_stations directly'); end; $$; reset role; -- ----------------------------------------------------------------------------- -- 4. PRINTER PROTOCOL (token gated, called as anon) -- ----------------------------------------------------------------------------- select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_hb; insert into bp_hb select public.printer_heartbeat(s.token, '{"printer": {"connected": true, "ready": true, "errors": []}, "worker": "idle"}'::jsonb) from bp_station s; select pg_temp.assert_bp( (select hb ? 'station_id' and hb ->> 'name' = 'Front desk' from bp_hb), 'heartbeat returns the station identity'); -- Oversized status blobs are refused. do $$ begin begin perform public.printer_heartbeat(s.token, jsonb_build_object('blob', repeat('x', 20000))::jsonb) from bp_station s; raise exception 'oversized heartbeat accepted'; exception when raise_exception then if sqlerrm <> 'printer status payload too large' then raise; end if; end; perform pg_temp.assert_bp(true, 'oversized heartbeat rejected'); end; $$; -- Claim the queued job (no polling in tests). insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0); select pg_temp.assert_bp( (select count(*) = 1 from bp_claim), 'anon with a valid token claims the job'); select pg_temp.assert_bp( (select read_ct = 1 and payload ->> 'kind' = 'checkin' from bp_claim), 'claimed row carries read_ct and the payload'); -- Nothing else to claim. select pg_temp.assert_bp( (select count(*) = 0 from public.printer_claim_badge_job((select token from bp_station), 120, 0)), 'second claim returns no row'); -- Bad tokens are rejected with 28000. do $$ begin begin perform public.printer_heartbeat('cvp_deadbeef', '{}'::jsonb); raise exception 'bad token accepted'; exception when others then if sqlstate <> '28000' then raise; end if; end; begin perform * from public.printer_claim_badge_job(null, 120, 0); raise exception 'null token accepted'; exception when others then if sqlstate <> '28000' then raise; end if; end; perform pg_temp.assert_bp(true, 'invalid token rejected with 28000'); end; $$; -- Completing archives it. reset role; select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print where vt > now()), 'claim hides the job behind a visibility timeout'); select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_done; insert into bp_done select public.printer_complete_badge_job(s.token, c.msg_id) from bp_station s, bp_claim c; select pg_temp.assert_bp((select ok = true from bp_done), 'complete archives the job'); reset role; select pg_temp.assert_bp( (select last_seen_at is not null and last_status -> 'printer' ->> 'ready' = 'true' from public.print_stations p join bp_station s on s.id = p.id), 'heartbeat stores status and last_seen_at'); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.a_badge_print), 'archive table holds the completed job'); select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print), 'queue is empty after completion'); select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); insert into bp_station2 select * from public.create_print_station('Back office'); select public.revoke_print_station((select id from bp_station2)); -- Both stations are created inside the same statement, so make the creation -- order (and therefore the overview order) unambiguous. update public.print_stations set created_at = created_at + interval '1 minute' where id = (select id from bp_station2); select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; do $$ begin begin perform * from public.printer_claim_badge_job((select token from bp_station2), 120, 0); raise exception 'revoked token accepted'; exception when others then if sqlstate <> '28000' then raise; end if; end; perform pg_temp.assert_bp(true, 'revoked token rejected with 28000'); end; $$; reset role; -- ----------------------------------------------------------------------------- -- 5. RETRY, DEAD LETTERS, REQUEUE, DISCARD -- ----------------------------------------------------------------------------- select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); insert into bp_enq select public.enqueue_badge_print( (select id from public.registrations where contact_email = 'bp-att1@example.test')); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq)), 'admin enqueue_badge_print queues a job'); select pg_temp.assert_bp( (select message ->> 'kind' = 'reprint' and message ->> 'requested_by' = 'bp-admin@example.test' from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq)), 'manual job is a reprint requested by the admin'); select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; -- Retryable failure keeps the job and pushes the visibility timeout out. delete from bp_claim; insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0); delete from bp_res; insert into bp_res select public.printer_fail_badge_job(s.token, c.msg_id, 'printer offline', true) from bp_station s, bp_claim c where c.read_ct = 1; select pg_temp.assert_bp((select res = 'retry' from bp_res), 'retryable failure returns retry'); -- Unknown jobs cannot be failed. do $$ begin begin perform public.printer_fail_badge_job((select token from bp_station), 999999, 'nope', false); raise exception 'missing job accepted'; exception when raise_exception then if sqlerrm <> 'job not found' then raise; end if; end; perform pg_temp.assert_bp(true, 'failing an unknown job raises job not found'); end; $$; reset role; select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq) and vt > now()), 'retry keeps the job with a future visibility timeout'); select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print_dlq), 'retry leaves the dead letter queue empty'); -- Simulate the backoff elapsing, claim again, then fail permanently. update pgmq.q_badge_print set vt = now() - interval '1 second' where msg_id = (select msg_id from bp_enq); select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_claim; insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0); select pg_temp.assert_bp( (select count(*) = 1 and bool_and(read_ct = 2) from bp_claim), 'job becomes claimable again after the backoff'); delete from bp_res; insert into bp_res select public.printer_fail_badge_job(s.token, c.msg_id, 'paper jam', false) from bp_station s, bp_claim c; select pg_temp.assert_bp((select res = 'dead_letter' from bp_res), 'fatal failure returns dead_letter'); reset role; select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print_dlq), 'fatal failure lands in the dead letter queue'); select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print), 'dead-lettered job leaves the queue'); select pg_temp.assert_bp( (select d.message -> 'original' = c.payload and d.message ->> 'error' = 'paper jam' and (d.message ->> 'attempts')::int = 2 and d.message ->> 'station_id' = (select id::text from bp_station) and (d.message ->> 'source_msg_id')::bigint = (select msg_id from bp_enq) and (d.message ->> 'failed_at')::timestamptz is not null from pgmq.q_badge_print_dlq d, bp_claim c), 'dead letter envelope carries the original payload and context'); select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); do $$ begin begin perform public.requeue_dead_badge_print(999999); raise exception 'unknown dead letter requeued'; exception when raise_exception then if sqlerrm <> 'dead letter not found' then raise; end if; end; begin perform public.discard_dead_badge_print(999999); raise exception 'unknown dead letter discarded'; exception when raise_exception then if sqlerrm <> 'dead letter not found' then raise; end if; end; perform pg_temp.assert_bp(true, 'requeue/discard reject unknown dead letters'); end; $$; -- Requeue puts the byte-identical payload back on the live queue. delete from bp_enq; insert into bp_enq select public.requeue_dead_badge_print( (select msg_id from pgmq.q_badge_print_dlq)); select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print where msg_id = (select msg_id from bp_enq)), 'requeue puts the job back on badge_print'); select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print_dlq), 'requeue removes the dead letter'); select pg_temp.assert_bp( (select q.message = c.payload from pgmq.q_badge_print q, bp_claim c where q.msg_id = (select msg_id from bp_enq)), 'requeued payload is identical to the original'); -- And it prints again: fail it once more, then discard it for good. select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_claim; insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0); delete from bp_res; insert into bp_res select public.printer_fail_badge_job(s.token, c.msg_id, 'still jammed', false) from bp_station s, bp_claim c; select pg_temp.assert_bp((select res = 'dead_letter' from bp_res), 'requeued job can dead-letter again'); reset role; select pg_temp.assert_bp( (select count(*) = 1 from pgmq.q_badge_print_dlq), 'the re-run job dead-lettered once more'); select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); select public.discard_dead_badge_print((select msg_id from pgmq.q_badge_print_dlq)); select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print_dlq), 'discard removes the dead letter'); -- ----------------------------------------------------------------------------- -- 6. MAX ATTEMPTS AUTO DEAD-LETTER ON CLAIM -- ----------------------------------------------------------------------------- delete from bp_enq; insert into bp_enq select public.enqueue_badge_print( (select id from public.registrations where contact_email = 'bp-att1@example.test')); -- Pretend the job was handed out three times already (the claim below makes it -- the fourth read, which is past the max-attempts limit). update pgmq.q_badge_print set read_ct = 3, vt = now() - interval '1 second' where msg_id = (select msg_id from bp_enq); select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_claim; insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0); select pg_temp.assert_bp( (select count(*) = 0 from bp_claim), 'claim refuses a job that exceeded max attempts'); reset role; select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print), 'exhausted job leaves the queue'); select pg_temp.assert_bp( (select count(*) = 1 and bool_and(message ->> 'error' = 'max attempts exceeded') and bool_and((message ->> 'attempts')::int = 4) from pgmq.q_badge_print_dlq), 'exhausted job is dead-lettered as max attempts exceeded'); select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); select public.discard_dead_badge_print((select msg_id from pgmq.q_badge_print_dlq)); select pg_temp.assert_bp( (select count(*) = 0 from pgmq.q_badge_print_dlq), 'admin can discard the exhausted job'); -- ----------------------------------------------------------------------------- -- 7. ADMIN OVERVIEW -- ----------------------------------------------------------------------------- select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_hb; insert into bp_hb select public.printer_heartbeat(s.token, '{"printer": {"connected": true, "ready": true, "errors": []}, "worker": "idle"}'::jsonb) from bp_station s; reset role; select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); delete from bp_ov; insert into bp_ov select public.get_print_overview(); select pg_temp.assert_bp( (select array_agg(k order by k) from (select jsonb_object_keys(o.ov) as k from (select ov from bp_ov limit 1) o) x) = array['dead_letters','queue','recent','stations'], 'overview top level keys are exact'); select pg_temp.assert_bp( (select ov #> '{stations,0,state}' = '"ready"'::jsonb from bp_ov), 'station state is ready after a healthy heartbeat'); select pg_temp.assert_bp( (select jsonb_array_length(ov -> 'stations') = 2 from bp_ov), 'overview lists both stations'); select pg_temp.assert_bp( (select (ov -> 'stations' -> 0 ->> 'name') = 'Front desk' from bp_ov), 'stations are ordered by creation'); select pg_temp.assert_bp( (select ov #> '{stations,1,state}' = '"revoked"'::jsonb from bp_ov), 'revoked station reports state revoked'); select pg_temp.assert_bp( (select ov -> 'queue' ->> 'completed' = '1' and ov -> 'queue' ->> 'pending' = '0' and ov -> 'queue' ->> 'in_flight' = '0' and ov -> 'queue' ->> 'dead_letter' = '0' from bp_ov), 'queue counters match the queue state'); select pg_temp.assert_bp( (select jsonb_array_length(ov -> 'recent') = 1 and (ov -> 'recent' -> 0 ->> 'full_name') = 'Ada Attendee' and (ov -> 'recent' -> 0 ->> 'kind') = 'checkin' from bp_ov), 'recent lists the completed job summary'); select pg_temp.assert_bp( (select array_agg(k order by k) from (select jsonb_object_keys(o.ov -> 'recent' -> 0) as k from (select ov from bp_ov limit 1) o) x) = array['archived_at','email','event_name','full_name','kind','msg_id','registration_id'], 'recent rows expose only summary fields'); select pg_temp.assert_bp( (select position('BPQR-ATT-1' in ov::text) = 0 and position('qr_token' in ov::text) = 0 from bp_ov), 'overview never leaks the qr token or raw payloads'); -- Printer reports an error -> state error. select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_hb; insert into bp_hb select public.printer_heartbeat(s.token, '{"printer": {"connected": true, "ready": true, "errors": ["paper jam"]}, "worker": "printing"}'::jsonb) from bp_station s; reset role; select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); select pg_temp.assert_bp( (select get_print_overview() #> '{stations,0,state}' = '"error"'::jsonb), 'station state is error when the printer reports errors'); -- A disconnected printer is also an error, even without an error list. select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_hb; insert into bp_hb select public.printer_heartbeat(s.token, '{"printer": {"connected": false, "ready": false, "errors": []}, "worker": "idle"}'::jsonb) from bp_station s; reset role; select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); select pg_temp.assert_bp( (select get_print_overview() #> '{stations,0,state}' = '"error"'::jsonb), 'station state is error when the printer is disconnected'); -- A stale heartbeat makes it offline. update public.print_stations set last_seen_at = now() - interval '60 seconds' where id = (select id from bp_station); select pg_temp.assert_bp( (select get_print_overview() #> '{stations,0,state}' = '"offline"'::jsonb), 'station state is offline when the heartbeat is stale'); select pg_temp.assert_bp( (select get_print_overview() #> '{stations,1,state}' = '"revoked"'::jsonb), 'revoked wins over a missing heartbeat'); -- Dead letters surface in the overview too. delete from bp_enq; insert into bp_enq select public.enqueue_badge_print( (select id from public.registrations where contact_email = 'bp-att1@example.test')); select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_claim; insert into bp_claim select * from public.printer_claim_badge_job((select token from bp_station), 120, 0); select public.printer_fail_badge_job((select token from bp_station), (select msg_id from bp_claim), 'usb error', false); reset role; select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); select pg_temp.assert_bp( (select jsonb_array_length(get_print_overview() -> 'dead_letters') = 1 and (get_print_overview() -> 'dead_letters' -> 0 ->> 'error') = 'usb error' and (get_print_overview() -> 'dead_letters' -> 0 ->> 'full_name') = 'Ada Attendee' and position('BPQR-ATT-1' in get_print_overview()::text) = 0), 'dead letters are summarised without leaking payloads'); select pg_temp.assert_bp( (select get_print_overview() -> 'queue' ->> 'dead_letter' = '1'), 'dead letter counter reflects the queue'); -- Non-admins cannot read the overview. select set_config('request.jwt.claims', '{"email":"bp-viewer@example.test","role":"authenticated"}', true); do $$ begin begin perform public.get_print_overview(); raise exception 'non-admin overview allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; perform pg_temp.assert_bp(true, 'overview is admin only'); end; $$; -- ----------------------------------------------------------------------------- -- 7b. STATION RENAME -- ----------------------------------------------------------------------------- select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); select public.rename_print_station((select id from bp_station), ' Front desk 2 '); select pg_temp.assert_bp( (select name = 'Front desk 2' from public.print_stations p join bp_station s on s.id = p.id), 'admin rename updates and trims the name'); -- Revoked stations stay renamable so their history remains readable. select public.rename_print_station((select id from bp_station2), 'Back office (old)'); select pg_temp.assert_bp( (select name = 'Back office (old)' and revoked_at is not null from public.print_stations p join bp_station2 s on s.id = p.id), 'a revoked station can still be renamed'); -- The heartbeat echoes the new name (the station treats it as authoritative). select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; delete from bp_hb; insert into bp_hb select public.printer_heartbeat(s.token, '{"printer": {"connected": true, "ready": true, "errors": []}, "worker": "idle"}'::jsonb) from bp_station s; reset role; select pg_temp.assert_bp( (select hb ->> 'name' = 'Front desk 2' from bp_hb), 'heartbeat after a rename returns the new name'); select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); select pg_temp.assert_bp( (select get_print_overview() -> 'stations' -> 0 ->> 'name' = 'Front desk 2'), 'overview shows the renamed station'); do $$ begin begin perform public.rename_print_station((select id from bp_station), ' '); raise exception 'blank station name accepted by rename'; exception when raise_exception then if sqlerrm <> 'station name is required' then raise; end if; end; perform pg_temp.assert_bp(true, 'blank rename rejected'); end; $$; do $$ begin begin perform public.rename_print_station((select id from bp_station), repeat('x', 81)); raise exception 'over-long station name accepted by rename'; exception when raise_exception then if sqlerrm <> 'station name is too long' then raise; end if; end; perform pg_temp.assert_bp(true, 'over-long rename rejected'); end; $$; -- Exactly 80 chars is still allowed. select public.rename_print_station((select id from bp_station), repeat('y', 80)); select pg_temp.assert_bp( (select name = repeat('y', 80) from public.print_stations p join bp_station s on s.id = p.id), 'rename accepts a name of exactly 80 chars'); select public.rename_print_station((select id from bp_station), 'Front desk 2'); do $$ begin begin perform public.rename_print_station('b9d00009-0000-0000-0000-000000000009', 'Ghost'); raise exception 'unknown station rename accepted'; exception when raise_exception then if sqlerrm <> 'station not found' then raise; end if; end; perform pg_temp.assert_bp(true, 'rename of an unknown station raises station not found'); end; $$; select pg_temp.assert_bp( (select name = 'Front desk 2' from public.print_stations p join bp_station s on s.id = p.id), 'rejected rename attempts leave the name unchanged'); select set_config('request.jwt.claims', '{"email":"bp-viewer@example.test","role":"authenticated"}', true); do $$ begin begin perform public.rename_print_station((select id from bp_station), 'Sneaky'); raise exception 'non-admin rename allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; perform pg_temp.assert_bp(true, 'non-admin cannot rename stations'); end; $$; -- ----------------------------------------------------------------------------- -- 8. ENQUEUE GUARDS -- ----------------------------------------------------------------------------- select set_config('request.jwt.claims', '{"email":"bp-admin@example.test","role":"authenticated"}', true); -- Event B has no layout at all. do $$ begin begin perform * from public.enqueue_badge_print( (select id from public.registrations where contact_email = 'bp-attb@example.test')); raise exception 'enqueue without a layout allowed'; exception when raise_exception then if sqlerrm <> 'no badge layout configured for this event' then raise; end if; end; perform pg_temp.assert_bp(true, 'enqueue raises when the event has no layout'); end; $$; do $$ begin begin perform * from public.enqueue_badge_print('b9d00009-0000-0000-0000-000000000009'); raise exception 'enqueue of a missing registration allowed'; exception when raise_exception then if sqlerrm <> 'registration not found' then raise; end if; end; perform pg_temp.assert_bp(true, 'enqueue raises for an unknown registration'); end; $$; select set_config('request.jwt.claims', '{"email":"bp-viewer@example.test","role":"authenticated"}', true); do $$ begin begin perform * from public.enqueue_badge_print( (select id from public.registrations where contact_email = 'bp-att1@example.test')); raise exception 'non-admin enqueue allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; begin perform public.revoke_print_station((select id from bp_station)); raise exception 'non-admin revoke allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; begin perform public.requeue_dead_badge_print(1); raise exception 'non-admin requeue allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; begin perform public.discard_dead_badge_print(1); raise exception 'non-admin discard allowed'; exception when insufficient_privilege then if sqlerrm <> 'admin only' then raise; end if; end; perform pg_temp.assert_bp(true, 'admin print RPCs are admin only'); end; $$; -- The anonymous role cannot call the admin RPCs either. select set_config('request.jwt.claims', '{"role":"anon"}', true); set local role anon; do $$ begin begin perform * from public.enqueue_badge_print( (select id from public.registrations where contact_email = 'bp-att1@example.test')); raise exception 'anon enqueue allowed'; exception when insufficient_privilege then null; end; perform pg_temp.assert_bp(true, 'anon cannot enqueue badge jobs'); end; $$; reset role; -- ----------------------------------------------------------------------------- -- 9. MIGRATION IDEMPOTENCY (the stream re-runs the migration on an applied DB) -- ----------------------------------------------------------------------------- select pg_temp.assert_bp( (select count(*) = 2 from pgmq.meta where queue_name in ('badge_print', 'badge_print_dlq')), 'both queues exist exactly once'); select pg_temp.assert_bp( (select count(*) = 2 from pgmq.list_queues() l where (l).queue_name in ('badge_print', 'badge_print_dlq')), 'list_queues reports both queues'); select count(*) as passed_assertions from bp_results; rollback;