feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view

- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations,
  token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs,
  welcome_checkin enqueue; badge_print_tests.sql (101 assertions)
- apps/printer: Python worker (Playwright render -> brother_ql via pyusb),
  comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token),
  arm64 image build + idempotent Pi setup/install scripts, 77 pytest
- apps/admin: Printing view, station management/DLQ, global printer status
  pill, Print button on Registrations, standalone print renderer entry
  (print.html -> dist-print) with bundled fonts
- docs: printing.md + architecture/schema/rpcs/tests/admin-app updates,
  apps/printer/AGENT.md operating manual
- e2e: printing.spec.ts

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
This commit is contained in:
committed 2026-10-18 22:25:38 +02:00
1 parent 0f3720d48a
commit 00c89c1b48
55 files changed
+7406 -29

No files matched your search

@@ -0,0 +1,644 @@
-- -----------------------------------------------------------------------------
-- Badge print queue (pgmq) + printer stations.
--
-- When staff check an attendee in with a welcome scan, the badge for that
-- attendee is pushed onto a `badge_print` queue. A headless printer station
-- (Raspberry Pi + Brother QL) long-polls the queue through token-gated RPCs,
-- renders the badge layout and reports success/failure. Jobs that keep failing
-- move to `badge_print_dlq` where an admin can requeue or discard them.
--
-- Design notes:
-- * pgmq is reachable ONLY through the RPCs below. The schema, its tables and
-- its functions are revoked from anon/authenticated/public, so the API never
-- exposes queue contents.
-- * Printer stations authenticate with a bearer token (`cvp_...`). Only the
-- SHA-256 hex digest is stored; the token itself is shown once at creation.
-- * `print_stations` has RLS enabled with no policies: every access goes
-- through a security definer function.
-- * The queue payload is a self-contained badge document
-- (`convivo.badge-print/v1`): event, registration, sample data and the
-- resolved layout. The station needs no further reads to print a badge.
--
-- This migration is written to be re-runnable (idempotent) so it can be
-- replayed inside the rollback test stream.
-- -----------------------------------------------------------------------------
-- -----------------------------------------------------------------------------
-- 1. QUEUE EXTENSION AND QUEUES
-- -----------------------------------------------------------------------------
create extension if not exists pgmq;
-- Idempotent queue creation: pgmq.create() inserts into pgmq.meta, so guard on
-- the catalogue instead of relying on the "already exists, skipping" notices.
do $$
begin
if not exists (select 1 from pgmq.meta where queue_name = 'badge_print') then
perform pgmq.create('badge_print');
end if;
if not exists (select 1 from pgmq.meta where queue_name = 'badge_print_dlq') then
perform pgmq.create('badge_print_dlq');
end if;
end;
$$;
-- No direct queue access from the API roles: everything goes through the RPCs.
revoke all on schema pgmq from public, anon, authenticated;
revoke all on all tables in schema pgmq from public, anon, authenticated;
revoke all on all sequences in schema pgmq from public, anon, authenticated;
revoke execute on all functions in schema pgmq from public, anon, authenticated;
-- -----------------------------------------------------------------------------
-- 2. PRINTER STATIONS
-- -----------------------------------------------------------------------------
create table if not exists public.print_stations (
id uuid primary key default gen_random_uuid(),
name text not null check (btrim(name) <> ''),
token_hash text not null unique,
created_at timestamptz not null default now(),
revoked_at timestamptz,
last_seen_at timestamptz,
last_status jsonb
);
alter table public.print_stations enable row level security;
revoke all on public.print_stations from public, anon, authenticated;
grant all on public.print_stations to service_role;
-- -----------------------------------------------------------------------------
-- 3. INTERNAL HELPERS
-- -----------------------------------------------------------------------------
-- Build the badge document for one registration, or NULL when the registration
-- (or its event) has no layout with at least one element. Layout choice: the
-- default layout that has elements, else the first (created_at, name) that has.
create or replace function public._badge_print_payload(
p_registration_id uuid,
p_kind text,
p_requested_by text
) returns jsonb
language plpgsql stable security definer set search_path = '' as $$
declare
v_reg public.registrations;
v_event public.events;
v_name text;
v_layout public.badge_layouts;
begin
select r.* into v_reg
from public.registrations r
where r.id = p_registration_id;
if not found then
return null;
end if;
select e.* into v_event
from public.events e
where e.id = v_reg.event_id;
if not found then
return null;
end if;
select l.* into v_layout
from public.badge_layouts l
where l.event_id = v_event.id
and jsonb_typeof(l.elements) = 'array'
and jsonb_array_length(l.elements) > 0
order by l.is_default desc, l.created_at, l.name
limit 1;
if not found then
return null;
end if;
select c.full_name into v_name
from public.contacts c
where c.email = v_reg.contact_email;
return jsonb_build_object(
'schema', 'convivo.badge-print/v1',
'kind', p_kind,
'requested_at', now(),
'requested_by', p_requested_by,
'event', jsonb_build_object(
'id', v_event.id,
'name', v_event.name,
'company', v_event.company
),
'registration', jsonb_build_object(
'id', v_reg.id,
'email', v_reg.contact_email,
'type', v_reg."type"
),
'sample', jsonb_build_object(
'full_name', coalesce(v_name, v_reg.contact_email),
'email', v_reg.contact_email,
'ticket_type', v_reg."type"::text,
'qr_token', coalesce(v_reg.qr_token, ''),
'event_name', v_event.name,
'company', coalesce(v_event.company, '')
),
'layout', jsonb_build_object(
'id', v_layout.id,
'name', v_layout.name,
'page_width_mm', v_layout.page_width_mm,
'page_height_mm', v_layout.page_height_mm,
'elements', v_layout.elements
)
);
end;
$$;
-- Resolve a bearer token to its (non-revoked) station id.
create or replace function public._print_station_from_token(p_token text)
returns uuid
language plpgsql stable security definer set search_path = '' as $$
declare
v_id uuid;
begin
if p_token is null or btrim(p_token) = '' then
raise exception 'invalid printer token' using errcode = '28000';
end if;
select s.id into v_id
from public.print_stations s
where s.token_hash = encode(extensions.digest(p_token, 'sha256'), 'hex')
and s.revoked_at is null;
if v_id is null then
raise exception 'invalid printer token' using errcode = '28000';
end if;
return v_id;
end;
$$;
revoke execute on function public._badge_print_payload(uuid, text, text)
from public, anon, authenticated;
revoke execute on function public._print_station_from_token(text)
from public, anon, authenticated;
grant execute on function public._badge_print_payload(uuid, text, text) to service_role;
grant execute on function public._print_station_from_token(text) to service_role;
-- -----------------------------------------------------------------------------
-- 4. WELCOME CHECK-IN: enqueue a badge job on the first check-in
--
-- Re-created verbatim from 20260829000000 (same signature, return type,
-- security definer / search_path and behaviour). The only addition is the
-- `badge_print` enqueue for an attendee that was not checked in yet, inside the
-- same transaction as the checked_in update.
-- -----------------------------------------------------------------------------
create or replace function public.welcome_checkin(p_attendee_qr text)
returns table (attendee_email text, attendee_name text, already boolean)
language plpgsql security definer set search_path = public as $$
declare
v_staff text := public.current_email();
v_attendee text;
v_name text;
v_event_id uuid;
v_checked boolean;
v_reg_id uuid;
v_payload jsonb;
begin
if v_staff is null then raise exception 'not authenticated'; end if;
if not public.is_staff_or_admin() then raise exception 'staff or admin only'; end if;
select id into v_event_id from public.events where is_active limit 1;
if v_event_id is null then raise exception 'no active event'; end if;
select r.contact_email, c.full_name, r.id into v_attendee, v_name, v_reg_id
from public.registrations r
join public.contacts c on c.email = r.contact_email
where r.qr_token = p_attendee_qr
and r.event_id = v_event_id;
if v_attendee is null then raise exception 'no attendee found for that QR code'; end if;
select checked_in into v_checked
from public.registrations
where event_id = v_event_id and contact_email = v_attendee;
update public.registrations set checked_in = true
where event_id = v_event_id and contact_email = v_attendee;
-- Badge printing: only for a genuine first check-in, and only when the event
-- actually has a badge layout. No payload -> no job.
if v_checked is not true then
v_payload := public._badge_print_payload(v_reg_id, 'checkin', v_staff);
if v_payload is not null then
perform pgmq.send('badge_print', v_payload);
end if;
end if;
return query select v_attendee, v_name, coalesce(v_checked, false);
end;
$$;
grant execute on function public.welcome_checkin(text) to authenticated;
-- -----------------------------------------------------------------------------
-- 5. ADMIN RPCs
-- -----------------------------------------------------------------------------
-- Manual reprint: queue the badge of one registration again.
create or replace function public.enqueue_badge_print(p_registration_id uuid)
returns bigint
language plpgsql security definer set search_path = '' as $$
declare
v_found boolean;
v_payload jsonb;
v_msg_id bigint;
begin
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
select exists (
select 1 from public.registrations r where r.id = p_registration_id
) into v_found;
if not v_found then
raise exception 'registration not found';
end if;
v_payload := public._badge_print_payload(
p_registration_id, 'reprint', public.current_email());
if v_payload is null then
raise exception 'no badge layout configured for this event';
end if;
select pgmq.send('badge_print', v_payload) into v_msg_id;
return v_msg_id;
end;
$$;
-- Register a printer station. The plaintext token is returned once; only its
-- SHA-256 digest is stored.
create or replace function public.create_print_station(p_name text)
returns table (id uuid, token text)
language plpgsql security definer set search_path = '' as $$
declare
v_id uuid;
v_token text;
begin
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
if p_name is null or btrim(p_name) = '' then
raise exception 'station name is required';
end if;
v_token := 'cvp_' || encode(extensions.gen_random_bytes(32), 'hex');
insert into public.print_stations (name, token_hash)
values (btrim(p_name), encode(extensions.digest(v_token, 'sha256'), 'hex'))
returning print_stations.id into v_id;
return query select v_id, v_token;
end;
$$;
-- Retire a station: its token stops working immediately.
create or replace function public.revoke_print_station(p_id uuid)
returns void
language plpgsql security definer set search_path = '' as $$
begin
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
update public.print_stations
set revoked_at = coalesce(revoked_at, now())
where id = p_id;
end;
$$;
-- Rename a station. Revoked stations may be renamed too, so their history
-- stays readable in the overview.
create or replace function public.rename_print_station(p_id uuid, p_name text)
returns void
language plpgsql security definer set search_path = '' as $$
declare
v_name text := btrim(coalesce(p_name, ''));
begin
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
if v_name = '' then
raise exception 'station name is required';
end if;
if length(v_name) > 80 then
raise exception 'station name is too long';
end if;
update public.print_stations set name = v_name where id = p_id;
if not found then
raise exception 'station not found';
end if;
end;
$$;
-- Admin dashboard snapshot: stations (with a derived state), queue counters,
-- the last completed jobs and the dead letters. Never exposes qr_token or the
-- full job payloads.
create or replace function public.get_print_overview()
returns jsonb
language plpgsql stable security definer set search_path = '' as $$
declare
v_stations jsonb;
v_queue jsonb;
v_recent jsonb;
v_dead jsonb;
begin
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
select coalesce(jsonb_agg(jsonb_build_object(
'id', s.id,
'name', s.name,
'created_at', s.created_at,
'revoked_at', s.revoked_at,
'last_seen_at', s.last_seen_at,
'last_status', s.last_status,
'state', case
when s.revoked_at is not null then 'revoked'
when s.last_seen_at is null
or s.last_seen_at < now() - interval '45 seconds' then 'offline'
when coalesce(s.last_status -> 'printer' ->> 'connected', '') <> 'true'
or coalesce(s.last_status -> 'printer' ->> 'ready', '') <> 'true'
or (jsonb_typeof(s.last_status -> 'printer' -> 'errors') = 'array'
and jsonb_array_length(s.last_status -> 'printer' -> 'errors') > 0) then 'error'
when s.last_status ->> 'worker' = 'printing' then 'printing'
else 'ready'
end
) order by s.created_at, s.name), '[]'::jsonb)
into v_stations
from public.print_stations s;
select jsonb_build_object(
'pending', (select count(*) from pgmq.q_badge_print where vt <= now()),
'in_flight', (select count(*) from pgmq.q_badge_print where vt > now()),
'dead_letter', (select count(*) from pgmq.q_badge_print_dlq),
'completed', (select count(*) from pgmq.a_badge_print)
)
into v_queue;
select coalesce(jsonb_agg(x.row_data order by x.archived_at desc), '[]'::jsonb)
into v_recent
from (
select
m.archived_at,
jsonb_build_object(
'msg_id', m.msg_id,
'archived_at', m.archived_at,
'kind', m.message ->> 'kind',
'full_name', m.message -> 'sample' ->> 'full_name',
'email', m.message -> 'sample' ->> 'email',
'event_name', m.message -> 'event' ->> 'name',
'registration_id', m.message -> 'registration' ->> 'id'
) as row_data
from pgmq.a_badge_print m
order by m.archived_at desc
limit 20
) x;
select coalesce(jsonb_agg(y.row_data order by y.enqueued_at desc), '[]'::jsonb)
into v_dead
from (
select
d.enqueued_at,
jsonb_build_object(
'msg_id', d.msg_id,
'enqueued_at', d.enqueued_at,
'failed_at', d.message ->> 'failed_at',
'error', d.message ->> 'error',
'attempts', d.message ->> 'attempts',
'kind', d.message -> 'original' ->> 'kind',
'full_name', d.message -> 'original' -> 'sample' ->> 'full_name',
'email', d.message -> 'original' -> 'sample' ->> 'email',
'event_name', d.message -> 'original' -> 'event' ->> 'name',
'registration_id', d.message -> 'original' -> 'registration' ->> 'id'
) as row_data
from pgmq.q_badge_print_dlq d
) y;
return jsonb_build_object(
'stations', v_stations,
'queue', v_queue,
'recent', v_recent,
'dead_letters', v_dead
);
end;
$$;
-- Push a dead letter's original payload back onto the live queue unchanged.
create or replace function public.requeue_dead_badge_print(p_msg_id bigint)
returns bigint
language plpgsql security definer set search_path = '' as $$
declare
v_original jsonb;
v_msg_id bigint;
begin
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
select d.message -> 'original' into v_original
from pgmq.q_badge_print_dlq d
where d.msg_id = p_msg_id;
if not found or v_original is null then
raise exception 'dead letter not found';
end if;
select pgmq.send('badge_print', v_original) into v_msg_id;
perform pgmq.delete('badge_print_dlq', p_msg_id);
return v_msg_id;
end;
$$;
-- Drop a dead letter without retrying it.
create or replace function public.discard_dead_badge_print(p_msg_id bigint)
returns void
language plpgsql security definer set search_path = '' as $$
declare
v_found boolean;
begin
if not public.is_admin() then
raise exception 'admin only' using errcode = '42501';
end if;
select pgmq.delete('badge_print_dlq', p_msg_id) into v_found;
if not v_found then
raise exception 'dead letter not found';
end if;
end;
$$;
revoke execute on function public.enqueue_badge_print(uuid) from public, anon, authenticated;
revoke execute on function public.create_print_station(text) from public, anon, authenticated;
revoke execute on function public.revoke_print_station(uuid) from public, anon, authenticated;
revoke execute on function public.rename_print_station(uuid, text) from public, anon, authenticated;
revoke execute on function public.get_print_overview() from public, anon, authenticated;
revoke execute on function public.requeue_dead_badge_print(bigint) from public, anon, authenticated;
revoke execute on function public.discard_dead_badge_print(bigint) from public, anon, authenticated;
grant execute on function public.enqueue_badge_print(uuid) to authenticated, service_role;
grant execute on function public.create_print_station(text) to authenticated, service_role;
grant execute on function public.rename_print_station(uuid, text) to authenticated, service_role;
grant execute on function public.revoke_print_station(uuid) to authenticated, service_role;
grant execute on function public.get_print_overview() to authenticated, service_role;
grant execute on function public.requeue_dead_badge_print(bigint) to authenticated, service_role;
grant execute on function public.discard_dead_badge_print(bigint) to authenticated, service_role;
-- -----------------------------------------------------------------------------
-- 6. PRINTER STATION RPCs (token gated, no user session required)
-- -----------------------------------------------------------------------------
-- Long-poll for the next badge job. A job that has been handed out more than
-- three times is moved to the dead letter queue instead of looping forever.
create or replace function public.printer_claim_badge_job(
p_token text,
p_vt integer default 120,
p_wait_seconds integer default 2
) returns table (msg_id bigint, read_ct integer, payload jsonb)
language plpgsql security definer set search_path = '' as $$
declare
v_station uuid;
v_vt integer;
v_wait integer;
v_rec pgmq.message_record;
begin
v_station := public._print_station_from_token(p_token);
v_vt := least(600, greatest(30, coalesce(p_vt, 120)));
-- PostgREST runs this as anon, whose statement_timeout is 3 s.
v_wait := least(2, greatest(0, coalesce(p_wait_seconds, 2)));
update public.print_stations
set last_seen_at = now()
where id = v_station;
if v_wait > 0 then
select * into v_rec from pgmq.read_with_poll('badge_print', v_vt, 1, v_wait);
else
select * into v_rec from pgmq.read('badge_print', v_vt, 1);
end if;
if not found then
return;
end if;
if v_rec.read_ct > 3 then
perform pgmq.send('badge_print_dlq', jsonb_build_object(
'original', v_rec.message,
'error', 'max attempts exceeded',
'attempts', v_rec.read_ct,
'failed_at', now(),
'station_id', v_station,
'source_msg_id', v_rec.msg_id
));
perform pgmq.delete('badge_print', v_rec.msg_id);
return;
end if;
return query select v_rec.msg_id, v_rec.read_ct, v_rec.message;
end;
$$;
-- Report success: the job leaves the queue for good (pgmq archive).
create or replace function public.printer_complete_badge_job(
p_token text,
p_msg_id bigint
) returns boolean
language plpgsql security definer set search_path = '' as $$
declare
v_station uuid;
v_done boolean;
begin
v_station := public._print_station_from_token(p_token);
update public.print_stations set last_seen_at = now() where id = v_station;
select pgmq.archive('badge_print', p_msg_id) into v_done;
return v_done;
end;
$$;
-- Report a failure: retry with backoff while the job still has attempts left,
-- otherwise dead-letter it.
create or replace function public.printer_fail_badge_job(
p_token text,
p_msg_id bigint,
p_error text,
p_retryable boolean default false
) returns text
language plpgsql security definer set search_path = '' as $$
declare
v_station uuid;
v_rec pgmq.message_record;
begin
v_station := public._print_station_from_token(p_token);
update public.print_stations set last_seen_at = now() where id = v_station;
select * into v_rec from pgmq.q_badge_print m where m.msg_id = p_msg_id;
if not found then
raise exception 'job not found';
end if;
if coalesce(p_retryable, false) and v_rec.read_ct < 3 then
perform pgmq.set_vt('badge_print', p_msg_id, least(300, 15 * v_rec.read_ct));
return 'retry';
end if;
perform pgmq.send('badge_print_dlq', jsonb_build_object(
'original', v_rec.message,
'error', left(coalesce(p_error, ''), 2000),
'attempts', v_rec.read_ct,
'failed_at', now(),
'station_id', v_station,
'source_msg_id', p_msg_id
));
perform pgmq.delete('badge_print', p_msg_id);
return 'dead_letter';
end;
$$;
-- Liveness + status beacon. The status blob is size-capped so a chatty station
-- cannot bloat the row.
create or replace function public.printer_heartbeat(
p_token text,
p_status jsonb
) returns jsonb
language plpgsql security definer set search_path = '' as $$
declare
v_station uuid;
v_name text;
begin
v_station := public._print_station_from_token(p_token);
if p_status is not null and pg_column_size(p_status) > 16384 then
raise exception 'printer status payload too large';
end if;
update public.print_stations
set last_status = coalesce(p_status, '{}'::jsonb),
last_seen_at = now()
where id = v_station
returning print_stations.name into v_name;
return jsonb_build_object('station_id', v_station, 'name', v_name);
end;
$$;
revoke execute on function public.printer_claim_badge_job(text, integer, integer)
from public, anon, authenticated;
revoke execute on function public.printer_complete_badge_job(text, bigint)
from public, anon, authenticated;
revoke execute on function public.printer_fail_badge_job(text, bigint, text, boolean)
from public, anon, authenticated;
revoke execute on function public.printer_heartbeat(text, jsonb)
from public, anon, authenticated;
grant execute on function public.printer_claim_badge_job(text, integer, integer)
to anon, authenticated, service_role;
grant execute on function public.printer_complete_badge_job(text, bigint)
to anon, authenticated, service_role;
grant execute on function public.printer_fail_badge_job(text, bigint, text, boolean)
to anon, authenticated, service_role;
grant execute on function public.printer_heartbeat(text, jsonb)
to anon, authenticated, service_role;
-- -----------------------------------------------------------------------------
-- 7. API RELOAD
-- -----------------------------------------------------------------------------
notify pgrst, 'reload schema';
+918
View File
@@ -0,0 +1,918 @@
\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
('[email protected]', 'Print Admin', true),
('[email protected]', 'Print Staff', false),
('[email protected]','Plain Viewer', false),
('[email protected]', 'Ada Attendee', false),
('[email protected]', 'Checked Ina', false),
('[email protected]', 'Session Sam', false),
('[email protected]', 'Direct Dana', false),
('[email protected]', 'Savepoint Sol', false),
('[email protected]', 'No-layout Nia', false);
insert into public.registrations (event_id, contact_email, type, checked_in, qr_token) values
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'staff', false, null),
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-1'),
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', true, 'BPQR-ATT-2'),
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-3'),
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-4'),
('b9d00001-0000-0000-0000-00000000000a', '[email protected]', 'attendee', false, 'BPQR-ATT-5'),
('b9d00002-0000-0000-0000-00000000000b', '[email protected]', '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":"[email protected]","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 = '[email protected]' 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 = '[email protected]'),
'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' = '[email protected]'
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' = '[email protected]'
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', '[email protected]',
'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 = '[email protected]' 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.
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');
-- A direct write of checked_in (admin edit) must not print badges either.
update public.registrations set checked_in = true where contact_email = '[email protected]';
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 = '[email protected]'),
'rolled back check-in leaves the attendee unchecked');
-- -----------------------------------------------------------------------------
-- 3. PRINT STATION PROVISIONING AND PERMISSIONS
-- -----------------------------------------------------------------------------
select set_config('request.jwt.claims', '{"email":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","role":"authenticated"}', true);
insert into bp_enq
select public.enqueue_badge_print(
(select id from public.registrations where contact_email = '[email protected]'));
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' = '[email protected]'
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":"[email protected]","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":"[email protected]","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 = '[email protected]'));
-- 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":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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 = '[email protected]'));
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":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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 = '[email protected]'));
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":"[email protected]","role":"authenticated"}', true);
do $$ begin
begin
perform * from public.enqueue_badge_print(
(select id from public.registrations where contact_email = '[email protected]'));
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 = '[email protected]'));
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;