Intelligence, Advanced Charting & Trading Platform

1 BEGIN;
2
3 -- ChartNova advisory-only evaluation state, versioned CAS and consent-guarded
4 -- outbox creation. Depends on unmerged PR #34 / migration 0004. Migration 0005
5 -- is intentionally NOT included, applied or modified.
6 -- DO NOT deploy to Neon production without separate explicit authorization.
7
8 CREATE TABLE public.alert_rule_runtime (
9 user_id UUID NOT NULL REFERENCES public.app_users(id),
10 rule_key TEXT NOT NULL CHECK (length(trim(rule_key)) BETWEEN 1 AND 96),
11 revision BIGINT NOT NULL DEFAULT 0 CHECK (revision >= 0),
12 state JSONB NOT NULL DEFAULT '{"alert":{"phase":"ARMED"}}'::jsonb
13 CHECK (jsonb_typeof(state) = 'object' AND length(state::text) <= 8192),
14 last_event_key TEXT,
15 updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
16 PRIMARY KEY (user_id, rule_key),
17 CONSTRAINT alert_runtime_event_key_consistency CHECK (
18 (last_event_key IS NULL) OR length(last_event_key) BETWEEN 1 AND 128
19 )
20 );
21
22 CREATE TABLE public.alert_notification_consents (
23 user_id UUID NOT NULL REFERENCES public.app_users(id),
24 recipient_ref UUID NOT NULL,
25 channel TEXT NOT NULL CHECK (channel IN ('BALE','EITA','PWA')),
26 consented_at TIMESTAMPTZ NOT NULL,
27 revoked_at TIMESTAMPTZ,
28 PRIMARY KEY (user_id, recipient_ref, channel),
29 CHECK (revoked_at IS NULL OR revoked_at >= consented_at)
30 );
31
32 CREATE INDEX alert_notification_active_consents_idx
33 ON public.alert_notification_consents (user_id, recipient_ref, channel)
34 WHERE revoked_at IS NULL;
35
36 -- Optimistic concurrency at the PostgreSQL row lock. The domain engine
37 -- independently evaluates only quality-approved, entitled observations;
38 -- this function ensures an event and its state are committed atomically.
39 --
40 -- No broker, external HTTP, live data, secret or notification is involved.
41 -- Enqueued messages remain unsent until an independently approved sender exists.
42 CREATE FUNCTION public.alert_rule_commit(
43 p_user_id UUID,
44 p_rule_key TEXT,
45 p_expected_revision BIGINT,
46 p_next_state JSONB,
47 p_event_key TEXT DEFAULT NULL,
48 p_channel TEXT DEFAULT NULL,
49 p_recipient_ref UUID DEFAULT NULL,
50 p_at TIMESTAMPTZ DEFAULT now()
51 ) RETURNS TABLE (
52 outcome TEXT,
53 new_revision BIGINT,
54 outbox_id UUID
55 )
56 LANGUAGE plpgsql
57 SECURITY INVOKER
58 SET search_path = pg_catalog, public
59 AS $$
60 DECLARE
61 v_current public.alert_rule_runtime%ROWTYPE;
62 v_old_phase TEXT;
63 v_new_phase TEXT;
64 v_old_timestamp TIMESTAMPTZ;
65 v_new_timestamp TIMESTAMPTZ;
66 v_outbox UUID := NULL;
67 BEGIN
68 IF p_user_id IS NULL OR p_rule_key IS NULL
69 OR length(trim(p_rule_key)) NOT BETWEEN 1 AND 96
70 OR p_expected_revision IS NULL OR p_expected_revision < 0
71 OR p_next_state IS NULL OR jsonb_typeof(p_next_state) <> 'object'
72 OR length(p_next_state::text) > 8192
73 OR p_at IS NULL
74 THEN RAISE EXCEPTION 'invalid alert revision request' USING ERRCODE = '22023';
75 END IF;
76
77 v_new_phase := p_next_state #>> '{alert,phase}';
78 IF v_new_phase NOT IN ('ARMED','TRIGGERED') OR v_new_phase IS NULL
79 OR p_next_state #>> '{alert,id}' IS DISTINCT FROM p_rule_key
80 THEN RAISE EXCEPTION 'invalid alert state or identity' USING ERRCODE = '22023';
81 END IF;
82
83 -- First writer creates a lockable baseline. All subsequent writers lock it.
84 -- The initial state is ARMED revision 0 and has no pending notification.
85 INSERT INTO public.alert_rule_runtime(user_id, rule_key, state)
86 VALUES (p_user_id, p_rule_key,
87 jsonb_build_object('alert',jsonb_build_object('phase','ARMED','id',p_rule_key)))
88 ON CONFLICT (user_id, rule_key) DO NOTHING;
89
90 SELECT * INTO v_current FROM public.alert_rule_runtime AS r
91 WHERE r.user_id = p_user_id AND r.rule_key = p_rule_key
92 FOR UPDATE;
93
94 IF NOT FOUND THEN
95 RAISE EXCEPTION 'missing locked alert row' USING ERRCODE = '40001';
96 END IF;
97
98 IF v_current.revision <> p_expected_revision THEN
99 outcome := 'STALE_REVISION';
100 new_revision := v_current.revision;
101 outbox_id := NULL;
102 RETURN NEXT;
103 RETURN;
104 END IF;
105
106 v_old_phase := v_current.state #>> '{alert,phase}';
107 IF v_old_phase <> 'ARMED' THEN
108 outcome := 'ALREADY_TERMINAL';
109 new_revision := v_current.revision;
110 outbox_id := NULL;
111 RETURN NEXT;
112 RETURN;
113 END IF;
114
115 IF p_next_state #>> '{alert,lastTimestamp}' IS NOT NULL THEN
116 BEGIN
117 v_new_timestamp := (p_next_state #>> '{alert,lastTimestamp}')::timestamptz;
118 IF v_current.state #>> '{alert,lastTimestamp}' IS NOT NULL THEN
119 v_old_timestamp := (v_current.state #>> '{alert,lastTimestamp}')::timestamptz;
120 END IF;
121 EXCEPTION WHEN invalid_datetime_format OR datetime_field_overflow THEN
122 RAISE EXCEPTION 'invalid sample timestamp in alert state'
123 USING ERRCODE = '22023';
124 END;
125 IF (v_old_timestamp IS NOT NULL AND v_new_timestamp < v_old_timestamp)
126 OR v_new_timestamp > p_at + interval '30 seconds' THEN
127 RAISE EXCEPTION 'out of sequence alert state' USING ERRCODE = '22023';
128 END IF;
129 END IF;
130
131 IF v_new_phase = 'TRIGGERED' THEN
132 IF p_event_key IS NULL OR length(p_event_key) NOT BETWEEN 1 AND 128
133 OR p_next_state #>> '{alert,eventId}' IS DISTINCT FROM p_event_key
134 OR p_next_state #>> '{alert,triggeredAt}' IS NULL
135 OR p_next_state #>> '{alert,lastTimestamp}' IS NULL
136 OR p_next_state #>> '{alert,triggeredAt}'
137 IS DISTINCT FROM p_next_state #>> '{alert,lastTimestamp}'
138 OR p_recipient_ref IS NULL OR p_channel NOT IN ('BALE','EITA','PWA')
139 OR p_channel IS NULL
140 OR (v_old_timestamp IS NOT NULL AND v_new_timestamp <= v_old_timestamp)
141 THEN RAISE EXCEPTION 'invalid triggered event or recipient' USING ERRCODE = '22023';
142 END IF;
143
144 -- Defense in depth: the data-integrity gate must have accepted the
145 -- same exact timestamp; an event cannot bypass a suspended price feed.
146 IF p_next_state #>> '{gate,suspended}' IS DISTINCT FROM 'false'
147 OR p_next_state #>> '{gate,lastSampleAt}'
148 IS DISTINCT FROM p_next_state #>> '{alert,lastTimestamp}'
149 OR p_next_state #>> '{gate,lastAccepted,timestamp}'
150 IS DISTINCT FROM p_next_state #>> '{alert,lastTimestamp}'
151 THEN
152 RAISE EXCEPTION 'unverified or stale quality gate cannot enqueue'
153 USING ERRCODE = '22023';
154 END IF;
155
156 -- No implicit consent, no stored chat identifiers. Lock the opt-in row so
157 -- revocation and enqueue cannot commit in the opposite order.
158 PERFORM 1 FROM public.alert_notification_consents AS consent
159 WHERE consent.user_id = p_user_id
160 AND consent.recipient_ref = p_recipient_ref
161 AND consent.channel = p_channel
162 AND consent.consented_at <= p_at
163 AND consent.revoked_at IS NULL
164 FOR SHARE;
165
166 IF NOT FOUND THEN
167 RAISE EXCEPTION 'notification recipient consent not verified'
168 USING ERRCODE = '42501';
169 END IF;
170
171 v_outbox := public.notification_outbox_enqueue(
172 p_user_id, p_event_key, p_channel, p_recipient_ref, 3
173 );
174 ELSE
175 IF p_event_key IS NOT NULL OR p_channel IS NOT NULL
176 OR p_recipient_ref IS NOT NULL
177 THEN RAISE EXCEPTION 'ARMED state cannot enqueue event' USING ERRCODE = '22023';
178 END IF;
179 END IF;
180
181 UPDATE public.alert_rule_runtime AS r
182 SET revision = r.revision + 1,
183 state = p_next_state,
184 last_event_key = CASE WHEN v_new_phase = 'TRIGGERED'
185 THEN p_event_key ELSE r.last_event_key END,
186 updated_at = p_at
187 WHERE r.user_id = p_user_id AND r.rule_key = p_rule_key
188 RETURNING r.revision INTO new_revision;
189
190 outcome := CASE WHEN v_new_phase = 'TRIGGERED'
191 THEN 'TRIGGERED_ENQUEUED' ELSE 'STATE_SAVED' END;
192 outbox_id := v_outbox;
193 RETURN NEXT;
194 END;
195 $$;
196
197 -- Optional future sender MUST claim through this consent-aware wrapper,
198 -- not through the raw generic outbox claimant. A revoked consent permanently
199 -- suppresses pending notification and never leaks it to a transport worker.
200 -- The later live sender will require a second check just before HTTP send.
201 CREATE FUNCTION public.alert_notification_claim_consented(
202 p_now TIMESTAMPTZ DEFAULT now(),
203 p_lease_seconds INTEGER DEFAULT 30
204 ) RETURNS TABLE (
205 outbox_id UUID,
206 event_key TEXT,
207 channel TEXT,
208 recipient_ref UUID,
209 claim_token UUID,
210 attempt_number INTEGER
211 )
212 LANGUAGE plpgsql
213 SECURITY INVOKER
214 SET search_path = pg_catalog, public
215 AS $alert_claim$
216 DECLARE
217 v_claim RECORD;
218 v_authorized BOOLEAN;
219 v_scan INTEGER;
220 BEGIN
221 IF p_now IS NULL OR p_lease_seconds IS NULL
222 OR p_lease_seconds NOT BETWEEN 1 AND 300 THEN
223 RAISE EXCEPTION 'invalid consent-aware claim parameters'
224 USING ERRCODE = '22023';
225 END IF;
226
227 -- Skip a bounded revoked-recipient backlog within the same claim,
228 -- otherwise a revoked queue head could starve valid users.
229 FOR v_scan IN 1..16 LOOP
230 v_authorized := false;
231 SELECT * INTO v_claim
232 FROM public.notification_outbox_claim(p_now, p_lease_seconds);
233 IF NOT FOUND THEN RETURN; END IF;
234
235 -- Check actual persisted user and recipient/owner binding rather than
236 -- trusting the caller or relying solely on opt-in at enqueue time.
237 SELECT true INTO v_authorized
238 FROM public.notification_outbox AS o
239 JOIN public.alert_notification_consents AS consent
240 ON consent.user_id = o.user_id
241 AND consent.recipient_ref = o.recipient_ref
242 AND consent.channel = o.channel
243 WHERE o.id = v_claim.outbox_id
244 AND o.status = 'LEASED'
245 AND o.lease_token = v_claim.claim_token
246 AND consent.consented_at <= p_now
247 AND consent.revoked_at IS NULL
248 FOR SHARE OF consent;
249
250 IF NOT COALESCE(v_authorized,false) THEN
251 -- No network call is performed. UNKNOWN is terminal under PR #34 schema;
252 -- the explicit reason distinguishes revoked consent from uncertain send.
253 UPDATE public.notification_outbox AS o
254 SET status = 'UNKNOWN',
255 failure_reason = 'RECIPIENT_CONSENT_REVOKED_OR_MISSING',
256 lease_token = NULL,
257 leased_at = NULL,
258 lease_until = NULL,
259 next_retry_at = NULL,
260 updated_at = p_now
261 WHERE o.id = v_claim.outbox_id
262 AND o.status = 'LEASED'
263 AND o.lease_token = v_claim.claim_token;
264 CONTINUE;
265 END IF;
266
267 outbox_id := v_claim.outbox_id;
268 event_key := v_claim.event_key;
269 channel := v_claim.channel;
270 recipient_ref := v_claim.recipient_ref;
271 claim_token := v_claim.claim_token;
272 attempt_number := v_claim.attempt_number;
273 RETURN NEXT;
274 RETURN;
275 END LOOP;
276 RETURN;
277 END;
278 $alert_claim$;
279
280 -- A message leased to a sender may be processed by overlapping job retries.
281 -- Atomically consume a single send permit before ANY external network call.
282 -- If the sender crashes after this point, lease expiry becomes terminal UNKNOWN
283 -- under PR #34 (at-most-once attempt, possibly no delivery).
284 ALTER TABLE public.notification_outbox
285 ADD COLUMN send_started_at TIMESTAMPTZ;
286
287
288 -- PR #34 explicitly permits bounded retry ONLY after a provider-confirmed
289 -- REJECTED outcome. Such a delivery attempt may already have consumed its
290 -- one-send permit. A *new* legitimate lease must obtain a *new* permit;
291 -- otherwise the old send_started_at marker deadlocks all authorized retries.
292 -- Expired/ambiguous/UNKNOWN sends NEVER become retry-eligible.
293 CREATE FUNCTION public.alert_notification_reset_permit_for_verified_retry()
294 RETURNS trigger
295 LANGUAGE plpgsql
296 SECURITY INVOKER
297 SET search_path = pg_catalog, public
298 AS $retry_permit$
299 BEGIN
300 IF OLD.status = 'FAILED' AND NEW.status = 'LEASED'
301 AND OLD.lease_token IS DISTINCT FROM NEW.lease_token
302 AND NEW.attempts > OLD.attempts
303 THEN
304 NEW.send_started_at := NULL;
305 END IF;
306 RETURN NEW;
307 END;
308 $retry_permit$;
309
310 CREATE TRIGGER notification_outbox_verified_retry_permit
311 BEFORE UPDATE ON public.notification_outbox
312 FOR EACH ROW
313 EXECUTE FUNCTION public.alert_notification_reset_permit_for_verified_retry();
314
315 REVOKE ALL ON FUNCTION public.alert_notification_reset_permit_for_verified_retry()
316 FROM PUBLIC;
317
318 CREATE FUNCTION public.alert_notification_begin_egress(
319 p_outbox_id UUID,
320 p_claim_token UUID,
321 p_recipient_ref UUID,
322 p_channel TEXT,
323 p_at TIMESTAMPTZ DEFAULT now()
324 ) RETURNS BOOLEAN
325 LANGUAGE plpgsql
326 SECURITY INVOKER
327 SET search_path = pg_catalog, public
328 AS $egress_begin$
329 DECLARE
330 v_id UUID;
331 BEGIN
332 IF p_outbox_id IS NULL OR p_claim_token IS NULL OR p_recipient_ref IS NULL
333 OR p_channel IS NULL OR p_channel NOT IN ('BALE','EITA','PWA')
334 OR p_at IS NULL THEN
335 RAISE EXCEPTION 'invalid one-send authorization parameters'
336 USING ERRCODE = '22023';
337 END IF;
338
339 -- The UPDATE row-lock is the linearization point for all overlapping
340 -- senders using the same lease. WHERE send_started_at IS NULL ensures a
341 -- repeat caller receives FALSE without attempting a duplicate message.
342 UPDATE public.notification_outbox AS o
343 SET send_started_at = p_at, updated_at = p_at
344 FROM public.alert_notification_consents AS c
345 WHERE o.id = p_outbox_id
346 AND o.lease_token = p_claim_token
347 AND o.recipient_ref = p_recipient_ref
348 AND o.channel = p_channel
349 AND o.status = 'LEASED'
350 AND o.send_started_at IS NULL
351 AND o.leased_at <= p_at AND o.lease_until > p_at
352 AND c.user_id = o.user_id
353 AND c.channel = o.channel
354 AND c.recipient_ref = o.recipient_ref
355 AND c.consented_at <= p_at
356 AND c.revoked_at IS NULL
357 RETURNING o.id INTO v_id;
358
359 RETURN v_id IS NOT NULL;
360 END;
361 $egress_begin$;
362
363 -- Second consent checkpoint immediately before a sender attempts HTTPS.
364 -- A claim-time check alone is insufficient: the user can revoke consent later.
365 -- This function is side-effect-free on a valid row, returns ONLY a boolean,
366 -- and never reads or reveals a chat ID, token or message payload.
367 CREATE FUNCTION public.alert_notification_egress_allowed(
368 p_outbox_id UUID,
369 p_claim_token UUID,
370 p_recipient_ref UUID,
371 p_channel TEXT,
372 p_at TIMESTAMPTZ DEFAULT now()
373 ) RETURNS BOOLEAN
374 LANGUAGE plpgsql
375 SECURITY INVOKER
376 SET search_path = pg_catalog, public
377 AS $egress_check$
378 DECLARE
379 v_can_send BOOLEAN := FALSE;
380 BEGIN
381 IF p_outbox_id IS NULL OR p_claim_token IS NULL OR p_recipient_ref IS NULL
382 OR p_channel IS NULL OR p_channel NOT IN ('BALE','EITA','PWA')
383 OR p_at IS NULL THEN
384 RAISE EXCEPTION 'invalid outbound authorization parameters'
385 USING ERRCODE = '22023';
386 END IF;
387
388 -- Keep the outbox row locked during the check. The caller must use a
389 -- trusted backend role; no frontend, browser or PUBLIC access is granted.
390 SELECT true INTO v_can_send
391 FROM public.notification_outbox AS o
392 JOIN public.alert_notification_consents AS c
393 ON c.user_id = o.user_id
394 AND c.recipient_ref = o.recipient_ref
395 AND c.channel = o.channel
396 WHERE o.id = p_outbox_id AND o.lease_token = p_claim_token
397 AND o.recipient_ref = p_recipient_ref AND o.channel = p_channel
398 AND o.status = 'LEASED'
399 AND o.send_started_at IS NOT NULL
400 AND o.send_started_at <= p_at
401 AND o.leased_at <= p_at AND o.lease_until > p_at
402 AND c.consented_at <= p_at AND c.revoked_at IS NULL
403 FOR SHARE OF c;
404
405 RETURN COALESCE(v_can_send, FALSE);
406 END;
407 $egress_check$;
408
409 -- Persisted state is owned by backend service only. No default browser/anon
410 -- SELECT/INSERT/UPDATE or function EXECUTE grants are introduced.
411 REVOKE ALL ON public.alert_rule_runtime FROM PUBLIC;
412 REVOKE ALL ON public.alert_notification_consents FROM PUBLIC;
413 REVOKE ALL ON FUNCTION public.alert_rule_commit(
414 UUID, TEXT, BIGINT, JSONB, TEXT, TEXT, UUID, TIMESTAMPTZ) FROM PUBLIC;
415 REVOKE ALL ON FUNCTION public.alert_notification_claim_consented(
416 TIMESTAMPTZ, INTEGER) FROM PUBLIC;
417 REVOKE ALL ON FUNCTION public.alert_notification_egress_allowed(
418 UUID, UUID, UUID, TEXT, TIMESTAMPTZ) FROM PUBLIC;
419 REVOKE ALL ON FUNCTION public.alert_notification_begin_egress(
420 UUID, UUID, UUID, TEXT, TIMESTAMPTZ) FROM PUBLIC;
421
422 COMMIT;