@davoodmehraban89 / VELYQOR / commits / a20a03a
Fork 0

Intelligence, Advanced Charting & Trading Platform

feat(risk): compose licensed quote gate and pure alert engine with atomic SQL state/outbox commit

davoodmehraban89 committed Oct 22, 2026 at 23:33 UTC a20a03a6bd3b8a5e2d0ea0924acf754390182c16
1 file changed +126
packages/market-domain/src/alert-postgres-coordinator.mjs new
+126
@@ -0,0 +1,126 @@
1 +/**
2 + * Domain-to-PostgreSQL integration boundary (NO broker or notification send).
3 + * Intended for a trusted server with a verified auth principal, a rights-aware
4 + * data gate and the independently tested PR #33 stepAlert function.
5 + *
6 + * Depends on PR #34 outbox and 0006_alert_runtime_atomic.sql.
7 + * No DB library import, transport, secrets, browser API or market-data fetch.
8 + * Caller injects trusted pg.query + deterministic domain functions.
9 + * NEVER expose as a browser-callable endpoint without separate auth review.
10 + */
11 +const ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
12 +const ALLOWED_CHANNELS=new Set(['BALE','EITA','PWA']);
13 +const NON_ADVISORY='اطلاعات آموزشی و غیرتوصیه‌ای';
14 +const sqlRead='SELECT revision, state FROM public.alert_rule_runtime WHERE user_id = $1::uuid AND rule_key = $2::text';
15 +const sqlCommit='SELECT outcome, new_revision, outbox_id FROM public.alert_rule_commit($1::uuid, $2::text, $3::bigint, $4::jsonb, $5::text, $6::text, $7::uuid, $8::timestamptz)';
16 +const hasOwn=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
17 +
18 +function safeRevision(v){
19 + const n=typeof v==='string'&&/^\d{1,16}$/.test(v)?Number(v):v;
20 + if(!Number.isSafeInteger(n)||n<0)throw new TypeError('unsafe alert revision');
21 + return n;
22 +}
23 +function ensureEvent(event,rule,quote,gate,next){
24 + if(!event||event.kind!=='INFORMATIONAL_THRESHOLD'||
25 + event.ruleId!==rule.id||event.symbol!==rule.symbol||
26 + event.source!==rule.provider||event.side!==quote.side||
27 + event.price!==quote.price||event.at!==quote.timestamp||
28 + event.legIndex<0||!Number.isInteger(event.legIndex)||
29 + !rule.legs[event.legIndex]||event.ruleType!==rule.legs[event.legIndex].type||
30 + !event.labels?.includes(NON_ADVISORY)||
31 + typeof event.id!=='string'||event.id.length>128||event.id.length<1||
32 + !/^[\x20-\x7E]+$/.test(event.id)||
33 + next.state.phase!=='TRIGGERED'||next.state.eventId!==event.id||
34 + next.state.triggeredAt!==event.at||
35 + gate.status!=='GOOD'||gate.alertsSuspended||
36 + gate.accepted?.timestamp!==quote.timestamp||
37 + gate.accepted?.provider!==rule.provider||
38 + gate.accepted?.unit!==rule.unit||
39 + gate.accepted?.symbol!==rule.symbol||
40 + gate.accepted?.side!==quote.side||
41 + gate.accepted?.price!==quote.price)
42 + throw new Error('UNVERIFIED_EVENT_PROVENANCE');
43 +}
44 +function validateArgs({db,domain,principal,rule,recipient,observation,now}){
45 + if(typeof db?.query!=='function'||typeof domain?.evaluateQuoteGate!=='function'||
46 + typeof domain?.stepAlert!=='function')throw new TypeError('trusted database/domain functions required');
47 + if(principal?.kind!=='VERIFIED_SERVER_PRINCIPAL'||principal.verified!==true||
48 + !ID.test(principal.userId))
49 + throw new TypeError('verified server user required');
50 + if(typeof rule?.id!=='string'||rule.id.length<1||rule.id.length>96||
51 + typeof rule.provider!=='string'||!rule.provider||
52 + typeof rule.symbol!=='string'||!rule.symbol||
53 + typeof rule.unit!=='string'||!rule.unit||
54 + !Array.isArray(rule.legs))
55 + throw new TypeError('trusted rule contract required');
56 + if(!ID.test(recipient?.recipientRef)||!ALLOWED_CHANNELS.has(recipient?.channel)||
57 + recipient.optInVerified!==true)
58 + throw new TypeError('verified recipient mapping required');
59 + if(!observation||typeof observation!=='object')
60 + throw new TypeError('observation required');
61 + if(typeof now!=='string'||!Number.isFinite(Date.parse(now)))
62 + throw new TypeError('valid server time required');
63 +}
64 +/**
65 + * @returns {outcome,revision,outboxId,reason} without user private data.
66 + * Database provides row-locked compare-and-swap. At most three refreshed
67 + * retries are allowed after STALE_REVISION to resolve Worker races.
68 + */
69 +export async function evaluateAndPersistAlert({
70 + db,domain,principal,rule,recipient,observation,now,
71 + gateOptions={},maxAttempts=3
72 +}){
73 + validateArgs({db,domain,principal,rule,recipient,observation,now});
74 + if(!Number.isInteger(maxAttempts)||maxAttempts<1||maxAttempts>5)
75 + throw new RangeError('maxAttempts');
76 + const userId=principal.userId,ruleId=rule.id;
77 + const gateConfig={...gateOptions,nowMs:Date.parse(now)};
78 + for(let attempt=0;attempt<maxAttempts;attempt++){
79 + const r=await db.query(sqlRead,[userId,ruleId]);
80 + if(!Array.isArray(r?.rows)||r.rows.length>1)
81 + throw new Error('CORRUPT_ALERT_STATE_RESULT');
82 + const row=r.rows[0];
83 + const revision=row?safeRevision(row.revision):0;
84 + const snapshot=row?.state??null;
85 + if(snapshot!==null&&(typeof snapshot!=='object'||Array.isArray(snapshot)))
86 + throw new Error('CORRUPT_ALERT_STATE');
87 + const previousAlert=snapshot?.alert??null;
88 + if(previousAlert?.phase==='TRIGGERED'||previousAlert?.phase==='NOTIFIED'||
89 + previousAlert?.phase==='CLOSED')
90 + return {outcome:'ALREADY_TERMINAL',revision,outboxId:null,reason:'NOT_REARMED'};
91 + const evaluation=domain.evaluateQuoteGate(snapshot?.gate??null,observation,gateConfig);
92 + if(!evaluation||typeof evaluation.status!=='string'||!evaluation.state)
93 + throw new Error('INVALID_DOMAIN_GATE');
94 + const computed=domain.stepAlert(rule,previousAlert,observation,evaluation);
95 + if(!computed||!computed.state||!Array.isArray(computed.events)||
96 + computed.events.length>1)
97 + throw new Error('INVALID_DOMAIN_EVALUATION');
98 + const event=computed.events[0]??null;
99 + if(event)ensureEvent(event,rule,observation,evaluation,computed);
100 + // Suspensions and recovery are preserved durably, even with no alert event.
101 + if(!event&&computed.state.phase!=='ARMED')
102 + throw new Error('EVENTLESS_TERMINAL_TRANSITION');
103 + const nextState={alert:computed.state,gate:evaluation.state};
104 + const values=[
105 + userId,ruleId,revision,JSON.stringify(nextState),
106 + event?.id??null,event?recipient.channel:null,
107 + event?recipient.recipientRef:null,now
108 + ];
109 + const saved=await db.query(sqlCommit,values);
110 + if(!Array.isArray(saved?.rows)||saved.rows.length!==1||
111 + !hasOwn(saved.rows[0],'outcome'))throw new Error('CORRUPT_CAS_RESULT');
112 + const result=saved.rows[0];
113 + if(result.outcome==='STALE_REVISION')continue;
114 + if(result.outcome==='ALREADY_TERMINAL')
115 + return {outcome:'ALREADY_TERMINAL',revision:safeRevision(result.new_revision),
116 + outboxId:null,reason:'RACED_WITH_TERMINAL_ALERT'};
117 + if(!['STATE_SAVED','TRIGGERED_ENQUEUED'].includes(result.outcome)||
118 + Boolean(event)!==(result.outcome==='TRIGGERED_ENQUEUED')||
119 + Boolean(result.outbox_id)!==Boolean(event))
120 + throw new Error('PERSISTENCE_RESULT_MISMATCH');
121 + return {outcome:result.outcome,revision:safeRevision(result.new_revision),
122 + outboxId:result.outbox_id??null,reason:computed.reason};
123 + }
124 + return {outcome:'REVISION_CONFLICT',revision:null,outboxId:null,
125 + reason:'RETRY_LIMIT_REACHED_NO_NEW_ALERT'};
126 +}