1
0
Fork 0

feat: notification_outbox Tabelle, Enqueue-Trigger und Batch-Claim-Funktion

This commit is contained in:
Jonny 2026-09-03 17:25:48 +02:00
parent 1800de1cae
commit e38e081373
2 changed files with 196 additions and 0 deletions

View File

@ -0,0 +1,94 @@
-- Transaktionale Outbox fuer ausgehende Benachrichtigungen. Vorerst nur das
-- Ereignis 'auftrag_erstellt' (WhatsApp an eine feste Sammel-Nummer), aber
-- event_type/payload sind generisch fuer spaetere Ereignisse. Geschrieben wird
-- ausschliesslich vom SECURITY DEFINER-Enqueue-Trigger und vom
-- Service-Role-Client der Dispatch-Route; RLS gibt nur admin Leserechte.
create table public.notification_outbox (
id uuid primary key default gen_random_uuid(),
event_type text not null,
auftrag_id uuid references public.auftraege(id) on delete set null,
payload jsonb not null,
status text not null default 'pending'
check (status in ('pending', 'sending', 'sent', 'failed', 'dead')),
versuche int not null default 0,
max_versuche int not null default 5,
naechster_versuch_ab timestamptz not null default now(),
letzter_fehler text,
wa_message_id text,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index notification_outbox_faellig_idx
on public.notification_outbox (status, naechster_versuch_ab);
alter table public.notification_outbox enable row level security;
-- Nur Einsicht fuer admin (Studio / spaeteres Admin-View). Kein
-- INSERT/UPDATE/DELETE fuer authenticated: der Enqueue-Trigger laeuft als
-- SECURITY DEFINER, die Dispatch-Route ueber den Service-Role-Key -- beide
-- umgehen RLS.
create policy "Admin liest notification_outbox"
on public.notification_outbox for select
using (public.user_role() = 'admin');
-- Enqueue: bei jedem INSERT in auftraege genau eine pending-Zeile. Laeuft als
-- AFTER INSERT, auftragsnummer ist zu diesem Zeitpunkt vom BEFORE-Trigger
-- auftragsnummer_generieren bereits gefuellt.
create function public.auftrag_notification_enqueue()
returns trigger
language plpgsql
security definer
set search_path = public
as $$
begin
insert into public.notification_outbox (event_type, auftrag_id, payload)
select
'auftrag_erstellt',
new.id,
jsonb_build_object(
'auftragsnummer', new.auftragsnummer,
'abholort_adresse', abhol.adresse,
'zielort_adresse', ziel.adresse,
'kennzeichen', fz.kennzeichen)
from public.orte abhol
join public.orte ziel on ziel.id = new.zielort_id
join public.fahrzeuge fz on fz.id = new.fahrzeug_id
where abhol.id = new.abholort_id;
return new;
end;
$$;
create trigger auftrag_notification_enqueue_trg
after insert on public.auftraege
for each row execute function public.auftrag_notification_enqueue();
-- Atomare Batch-Uebernahme fuer den Dispatcher: selektiert faellige Zeilen
-- (pending/failed und Zeitpunkt erreicht, oder in 'sending' haengengeblieben
-- seit >15 min) und setzt sie in einem Rutsch auf 'sending'. FOR UPDATE SKIP
-- LOCKED verhindert Doppel-Uebernahme bei ueberlappenden Laeufen.
create function public.claim_notification_batch(p_limit int)
returns setof public.notification_outbox
language sql
security definer
set search_path = public
as $$
update public.notification_outbox o
set status = 'sending', updated_at = now()
where o.id in (
select id from public.notification_outbox
where (status in ('pending', 'failed') and naechster_versuch_ab <= now())
or (status = 'sending' and updated_at < now() - interval '15 minutes')
order by created_at
limit p_limit
for update skip locked
)
returning o.*;
$$;
revoke all on function public.claim_notification_batch(int) from public;
revoke all on function public.claim_notification_batch(int) from anon;
revoke all on function public.claim_notification_batch(int) from authenticated;
-- Nur die Dispatch-Route (Service-Role-Client) darf den Batch uebernehmen.
grant execute on function public.claim_notification_batch(int) to service_role;

View File

@ -0,0 +1,102 @@
begin;
select plan(8);
insert into auth.users (id, email) values
('c1111111-1111-1111-1111-111111111111', 'admin-outbox@auftraege.test.local'),
('c2222222-2222-2222-2222-222222222222', 'disponent-outbox@auftraege.test.local');
update public.profiles set role = 'admin' where id = 'c1111111-1111-1111-1111-111111111111';
update public.profiles set role = 'disponent' where id = 'c2222222-2222-2222-2222-222222222222';
insert into public.orte (id, adresse, ansprechpartner) values
('c3111111-1111-1111-1111-111111111111', 'Startstr. 1, Teststadt', 'Frau A'),
('c3222222-2222-2222-2222-222222222222', 'Zielstr. 2, Teststadt', 'Herr B');
insert into public.fahrzeuge (id, kennzeichen) values
('c3333333-0000-0000-0000-000000000001', 'S-WA 42');
set local role authenticated;
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
-- 1) Disponent legt einen Auftrag an -> Enqueue-Trigger erzeugt genau eine Zeile.
insert into public.auftraege (id, abholort_id, zielort_id, fahrzeug_id, erstellt_von, status)
values (
'c4000000-0000-0000-0000-00000000000a',
'c3111111-1111-1111-1111-111111111111',
'c3222222-2222-2222-2222-222222222222',
'c3333333-0000-0000-0000-000000000001',
'c2222222-2222-2222-2222-222222222222',
'offen'
);
reset role;
reset request.jwt.claims;
select is(
(select count(*)::int from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
1,
'Enqueue-Trigger legt genau eine notification_outbox-Zeile pro neuem Auftrag an'
);
select is(
(select status from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'pending',
'Neue Outbox-Zeile hat status = pending'
);
select is(
(select event_type from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'auftrag_erstellt',
'Neue Outbox-Zeile hat event_type = auftrag_erstellt'
);
select is(
(select payload->>'kennzeichen' from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'S-WA 42',
'payload.kennzeichen kommt aus dem verknuepften Fahrzeug'
);
select is(
(select payload->>'abholort_adresse' from public.notification_outbox
where auftrag_id = 'c4000000-0000-0000-0000-00000000000a'),
'Startstr. 1, Teststadt',
'payload.abholort_adresse kommt aus dem Abholort (nicht dem Zielort)'
);
-- 2) SELECT-RLS: Disponent sieht die Outbox nicht.
set local role authenticated;
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
select is_empty(
$$ select id from public.notification_outbox $$,
'Disponent sieht keine notification_outbox-Zeilen (keine SELECT-Policy fuer disponent)'
);
-- 3) SELECT-RLS: Admin sieht die Outbox.
reset request.jwt.claims;
set local request.jwt.claims to '{"sub": "c1111111-1111-1111-1111-111111111111", "role": "authenticated"}';
select isnt_empty(
$$ select id from public.notification_outbox $$,
'Admin sieht notification_outbox-Zeilen'
);
-- 4) EXECUTE-Recht: authenticated darf die Batch-Claim-Funktion nicht aufrufen
-- (revoke von authenticated, grant nur an service_role).
set local request.jwt.claims to '{"sub": "c2222222-2222-2222-2222-222222222222", "role": "authenticated"}';
-- 2-arg throws_ok(sql, sqlstate): die 3-arg-Form (sql, sqlstate, description)
-- kollidiert mit pgTAPs throws_ok(sql, errcode, errmsg)-Signatur und wuerde die
-- Beschreibung als erwartete Fehlermeldung interpretieren. Getestet wird
-- unveraendert: authenticated laeuft in SQLSTATE 42501 (insufficient_privilege).
select throws_ok(
$$ select public.claim_notification_batch(5) $$,
'42501'
);
reset role;
reset request.jwt.claims;
select * from finish();
rollback;