@davoodmehraban89 / VELYQOR / commits / 014bf16
Fork 0

Intelligence, Advanced Charting & Trading Platform

db(risk): add transactional opt-in alert outbox, atomic claims and fail-closed uncertain delivery state

davoodmehraban89 committed Oct 22, 2026 at 23:13 UTC 014bf160736209220a93f2463082cbb74335db27
1 file changed +264
db/migrations/0004_notification_outbox.sql new
+264
@@ -0,0 +1,264 @@
1 +BEGIN;
2 +
3 +-- ChartNova informational-alert outbox. SCHEMA ONLY: applying this file does
4 +-- not create an alert, contact a user, contact a broker or enable a Worker.
5 +-- Do not apply to live Neon without separate authorization.
6 +-- This outbox stores opaque recipient references, NOT chat IDs or bot tokens.
7 +-- Producer must ensure provider display/derived-alert rights before enqueueing.
8 +
9 +CREATE TABLE notification_outbox (
10 + id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
11 + user_id UUID NOT NULL REFERENCES app_users(id),
12 + event_key TEXT NOT NULL CHECK (length(trim(event_key)) BETWEEN 1 AND 128),
13 + channel TEXT NOT NULL CHECK (channel IN ('BALE','EITA','PWA')),
14 + recipient_ref UUID NOT NULL,
15 + status TEXT NOT NULL DEFAULT 'PENDING'
16 + CHECK (status IN ('PENDING','LEASED','FAILED','UNKNOWN','SENT','ACKNOWLEDGED')),
17 + attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 10),
18 + max_attempts INTEGER NOT NULL DEFAULT 3 CHECK (max_attempts BETWEEN 1 AND 10),
19 + lease_token UUID,
20 + leased_at TIMESTAMPTZ,
21 + lease_until TIMESTAMPTZ,
22 + next_retry_at TIMESTAMPTZ,
23 + provider_message_id TEXT,
24 + provider_accepted_at TIMESTAMPTZ,
25 + acknowledged_at TIMESTAMPTZ,
26 + failure_reason TEXT,
27 + created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
28 + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
29 + CONSTRAINT notification_outbox_event_once
30 + UNIQUE (user_id, event_key, channel, recipient_ref),
31 + CONSTRAINT notification_outbox_attempt_limit CHECK (attempts <= max_attempts),
32 + CONSTRAINT notification_outbox_lease_consistency CHECK (
33 + (status = 'LEASED') =
34 + (lease_token IS NOT NULL AND leased_at IS NOT NULL AND lease_until IS NOT NULL)
35 + ),
36 + CONSTRAINT notification_outbox_lease_time CHECK (
37 + lease_until IS NULL OR leased_at IS NOT NULL AND lease_until > leased_at
38 + ),
39 + CONSTRAINT notification_outbox_receipt_consistency CHECK (
40 + status NOT IN ('SENT','ACKNOWLEDGED') OR
41 + (provider_message_id IS NOT NULL AND length(trim(provider_message_id)) > 0
42 + AND provider_accepted_at IS NOT NULL)
43 + ),
44 + CONSTRAINT notification_outbox_ack_consistency CHECK (
45 + (status = 'ACKNOWLEDGED') = (acknowledged_at IS NOT NULL)
46 + ),
47 + CONSTRAINT notification_outbox_ack_chronology CHECK (
48 + acknowledged_at IS NULL OR
49 + provider_accepted_at IS NOT NULL AND acknowledged_at >= provider_accepted_at
50 + )
51 +);
52 +
53 +CREATE INDEX notification_outbox_ready_idx
54 + ON notification_outbox (next_retry_at, created_at, id)
55 + WHERE status IN ('PENDING','FAILED');
56 +
57 +CREATE INDEX notification_outbox_expired_idx
58 + ON notification_outbox (lease_until, id)
59 + WHERE status = 'LEASED';
60 +
61 +CREATE INDEX notification_outbox_user_history_idx
62 + ON notification_outbox (user_id, created_at DESC);
63 +
64 +-- Idempotent enqueue. A duplicate logical event cannot create another send,
65 +-- including when submitted concurrently from independent Workers.
66 +CREATE FUNCTION notification_outbox_enqueue(
67 + p_user_id UUID,
68 + p_event_key TEXT,
69 + p_channel TEXT,
70 + p_recipient_ref UUID,
71 + p_max_attempts INTEGER DEFAULT 3
72 +) RETURNS UUID
73 +LANGUAGE plpgsql
74 +SECURITY INVOKER
75 +SET search_path = pg_catalog, public
76 +AS $$
77 +DECLARE v_id UUID;
78 +BEGIN
79 + IF p_user_id IS NULL OR p_recipient_ref IS NULL OR p_event_key IS NULL
80 + OR length(trim(p_event_key)) NOT BETWEEN 1 AND 128
81 + OR p_channel NOT IN ('BALE','EITA','PWA') OR p_channel IS NULL
82 + OR p_max_attempts NOT BETWEEN 1 AND 10 OR p_max_attempts IS NULL
83 + THEN
84 + RAISE EXCEPTION 'invalid non-secret outbox metadata' USING ERRCODE = '22023';
85 + END IF;
86 +
87 + INSERT INTO public.notification_outbox
88 + (user_id, event_key, channel, recipient_ref, max_attempts)
89 + VALUES (p_user_id, p_event_key, p_channel, p_recipient_ref, p_max_attempts)
90 + ON CONFLICT (user_id, event_key, channel, recipient_ref) DO NOTHING
91 + RETURNING id INTO v_id;
92 +
93 + IF v_id IS NULL THEN
94 + SELECT o.id INTO v_id FROM public.notification_outbox AS o
95 + WHERE o.user_id = p_user_id AND o.event_key = p_event_key
96 + AND o.channel = p_channel AND o.recipient_ref = p_recipient_ref;
97 + END IF;
98 +
99 + IF v_id IS NULL THEN
100 + RAISE EXCEPTION 'could not resolve concurrent outbox enqueue'
101 + USING ERRCODE = '40001';
102 + END IF;
103 + RETURN v_id;
104 +END;
105 +$$;
106 +
107 +-- One atomic claim: SELECT FOR UPDATE SKIP LOCKED + UPDATE in one statement.
108 +-- Claim MAY return zero rows. Expired in-flight leases are UNKNOWN, NEVER
109 +-- automatically retried: prior Worker may have sent before crashing.
110 +CREATE FUNCTION notification_outbox_claim(
111 + p_now TIMESTAMPTZ DEFAULT now(),
112 + p_lease_seconds INTEGER DEFAULT 30
113 +) RETURNS TABLE (
114 + outbox_id UUID,
115 + event_key TEXT,
116 + channel TEXT,
117 + recipient_ref UUID,
118 + claim_token UUID,
119 + attempt_number INTEGER
120 +)
121 +LANGUAGE plpgsql
122 +SECURITY INVOKER
123 +SET search_path = pg_catalog, public
124 +AS $$
125 +BEGIN
126 + IF p_now IS NULL OR p_lease_seconds NOT BETWEEN 1 AND 300
127 + OR p_lease_seconds IS NULL
128 + THEN RAISE EXCEPTION 'invalid lease parameters' USING ERRCODE = '22023';
129 + END IF;
130 +
131 + UPDATE public.notification_outbox AS expired
132 + SET status = 'UNKNOWN',
133 + failure_reason = 'LEASE_EXPIRED_DELIVERY_UNCERTAIN',
134 + lease_token = NULL,
135 + leased_at = NULL,
136 + lease_until = NULL,
137 + next_retry_at = NULL,
138 + updated_at = p_now
139 + WHERE expired.status = 'LEASED' AND expired.lease_until <= p_now;
140 +
141 + RETURN QUERY
142 + WITH candidate AS (
143 + SELECT o.id
144 + FROM public.notification_outbox AS o
145 + WHERE o.status IN ('PENDING','FAILED')
146 + AND o.attempts < o.max_attempts
147 + AND (o.next_retry_at IS NULL OR o.next_retry_at <= p_now)
148 + ORDER BY o.created_at, o.id
149 + LIMIT 1 FOR UPDATE OF o SKIP LOCKED
150 + )
151 + UPDATE public.notification_outbox AS claimed
152 + SET status = 'LEASED',
153 + attempts = claimed.attempts + 1,
154 + lease_token = gen_random_uuid(),
155 + leased_at = p_now,
156 + lease_until = p_now + make_interval(secs => p_lease_seconds),
157 + next_retry_at = NULL,
158 + failure_reason = NULL,
159 + updated_at = p_now
160 + FROM candidate
161 + WHERE claimed.id = candidate.id
162 + RETURNING claimed.id, claimed.event_key, claimed.channel,
163 + claimed.recipient_ref, claimed.lease_token, claimed.attempts;
164 +END;
165 +$$;
166 +
167 +-- A source can only finish the exact lease it claimed. Unknown results are
168 +-- terminal pending manual reconciliation, never "safe to retry".
169 +-- Decision REJECTED is only for a provider-confirmed non-delivery.
170 +CREATE FUNCTION notification_outbox_finish(
171 + p_outbox_id UUID,
172 + p_claim_token UUID,
173 + p_decision TEXT,
174 + p_provider_message_id TEXT DEFAULT NULL,
175 + p_at TIMESTAMPTZ DEFAULT now(),
176 + p_retry_seconds INTEGER DEFAULT 60
177 +) RETURNS TEXT
178 +LANGUAGE plpgsql
179 +SECURITY INVOKER
180 +SET search_path = pg_catalog, public
181 +AS $$
182 +DECLARE v_status TEXT;
183 +BEGIN
184 + IF p_outbox_id IS NULL OR p_claim_token IS NULL
185 + OR p_decision NOT IN ('SENT','REJECTED','UNKNOWN') OR p_decision IS NULL
186 + OR p_at IS NULL OR p_retry_seconds NOT BETWEEN 1 AND 86400
187 + OR p_retry_seconds IS NULL
188 + OR (p_decision = 'SENT' AND
189 + (p_provider_message_id IS NULL OR length(trim(p_provider_message_id)) = 0))
190 + OR (p_decision <> 'SENT' AND p_provider_message_id IS NOT NULL)
191 + THEN RAISE EXCEPTION 'invalid outbox completion' USING ERRCODE = '22023';
192 + END IF;
193 +
194 + UPDATE public.notification_outbox AS o
195 + SET status = CASE
196 + WHEN p_decision = 'SENT' THEN 'SENT'
197 + WHEN p_decision = 'UNKNOWN' THEN 'UNKNOWN'
198 + ELSE 'FAILED'
199 + END,
200 + lease_token = NULL,
201 + leased_at = NULL,
202 + lease_until = NULL,
203 + provider_message_id = CASE WHEN p_decision = 'SENT'
204 + THEN p_provider_message_id ELSE NULL END,
205 + provider_accepted_at = CASE WHEN p_decision = 'SENT'
206 + THEN p_at ELSE NULL END,
207 + failure_reason = CASE
208 + WHEN p_decision = 'UNKNOWN' THEN 'AMBIGUOUS_PROVIDER_RESPONSE'
209 + WHEN p_decision = 'REJECTED' AND o.attempts >= o.max_attempts
210 + THEN 'ATTEMPTS_EXHAUSTED'
211 + WHEN p_decision = 'REJECTED' THEN 'PROVIDER_CONFIRMED_REJECTION'
212 + ELSE NULL END,
213 + next_retry_at = CASE WHEN p_decision = 'REJECTED'
214 + AND o.attempts < o.max_attempts
215 + THEN p_at + make_interval(secs => p_retry_seconds)
216 + ELSE NULL END,
217 + updated_at = p_at
218 + WHERE o.id = p_outbox_id AND o.status = 'LEASED'
219 + AND o.lease_token = p_claim_token
220 + AND o.leased_at <= p_at AND o.lease_until > p_at
221 + RETURNING o.status INTO v_status;
222 +
223 + RETURN COALESCE(v_status, 'IGNORED_STALE_OR_INELIGIBLE');
224 +END;
225 +$$;
226 +
227 +-- User read/ack requires an external verified identity/consent mechanism.
228 +-- An API success must NEVER be passed to this function as proof of reading.
229 +CREATE FUNCTION notification_outbox_acknowledge(
230 + p_outbox_id UUID,
231 + p_user_id UUID,
232 + p_at TIMESTAMPTZ DEFAULT now()
233 +) RETURNS BOOLEAN
234 +LANGUAGE plpgsql
235 +SECURITY INVOKER
236 +SET search_path = pg_catalog, public
237 +AS $$
238 +DECLARE v_id UUID;
239 +BEGIN
240 + IF p_outbox_id IS NULL OR p_user_id IS NULL OR p_at IS NULL
241 + THEN RAISE EXCEPTION 'invalid acknowledgement' USING ERRCODE = '22023';
242 + END IF;
243 + UPDATE public.notification_outbox AS o
244 + SET status = 'ACKNOWLEDGED', acknowledged_at = p_at, updated_at = p_at
245 + WHERE o.id = p_outbox_id AND o.user_id = p_user_id
246 + AND o.status = 'SENT' AND o.provider_accepted_at <= p_at
247 + RETURNING o.id INTO v_id;
248 + RETURN v_id IS NOT NULL;
249 +END;
250 +$$;
251 +
252 +-- Fail closed on unspecified database roles. No anon/public execution grants,
253 +-- no SECURITY DEFINER bypass, and no encrypted/private destination stored here.
254 +REVOKE ALL ON TABLE public.notification_outbox FROM PUBLIC;
255 +REVOKE ALL ON FUNCTION public.notification_outbox_enqueue(
256 + UUID, TEXT, TEXT, UUID, INTEGER) FROM PUBLIC;
257 +REVOKE ALL ON FUNCTION public.notification_outbox_claim(
258 + TIMESTAMPTZ, INTEGER) FROM PUBLIC;
259 +REVOKE ALL ON FUNCTION public.notification_outbox_finish(
260 + UUID, UUID, TEXT, TEXT, TIMESTAMPTZ, INTEGER) FROM PUBLIC;
261 +REVOKE ALL ON FUNCTION public.notification_outbox_acknowledge(
262 + UUID, UUID, TIMESTAMPTZ) FROM PUBLIC;
263 +
264 +COMMIT;