-- ----------------------------------------------------------------------------- -- 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';