Intelligence, Advanced Charting & Trading Platform

1 /**
2 * Local, disposable GitHub Actions PostgreSQL only.
3 * Cross-session compare-and-swap: two worker-like evaluations of same rule,
4 * same revision and same trigger may commit exactly one outbox event.
5 */
6 import assert from 'node:assert/strict';
7 import {execFileSync,spawn} from 'node:child_process';
8
9 const env={...process.env};
10 if(env.CI!=='true'||!['localhost','127.0.0.1'].includes(env.PGHOST)||
11 env.PGDATABASE!=='velyqor_test'||env.VELYQOR_TEST_DATABASE!=='velyqor_test')
12 throw new Error('REFUSING_NON_LOCAL_DATABASE');
13 const user='c1111111-1111-4111-8111-111111111111';
14 const dest='d2222222-2222-4222-8222-222222222222';
15 const event='cross-session-alert:2026-10-22T12:00:00.000Z:0';
16 const rule='cross-session-alert';
17 const time='2026-10-22T12:00:00.000Z';
18 const state=JSON.stringify({alert:{
19 id:rule,phase:'TRIGGERED',eventId:event,triggeredAt:time,lastTimestamp:time
20 },gate:{suspended:false,lastSampleAt:time,lastAccepted:{
21 timestamp:time,provider:'S1',symbol:'USD_IRT_FREE',
22 side:'SELL',unit:'IRT_PER_USD',price:1100
23 }}});
24 const stmt=q=>execFileSync('psql',['-X','-q','-A','-t','-v','ON_ERROR_STOP=1','-c',q],
25 {env,encoding:'utf8',timeout:14000,stdio:['ignore','pipe','pipe']}).trim();
26
27 assert.equal(stmt('SELECT current_database()'),'velyqor_test');
28 stmt("INSERT INTO public.app_users(id) VALUES ('"+user+"') ON CONFLICT DO NOTHING");
29 stmt("INSERT INTO public.alert_notification_consents(user_id,recipient_ref,channel,consented_at) VALUES ('"+
30 user+"','"+dest+"','BALE','2026-10-22T11:00:00Z')");
31 const sql="SELECT outcome||'|'||new_revision::text||'|'||coalesce(outbox_id::text,'') "+
32 "FROM public.alert_rule_commit('"+user+"','"+rule+"',0,'"+
33 state+"'::jsonb,'"+event+"','BALE','"+dest+"','2026-10-22T12:00:00Z')";
34 const output=await Promise.all([0,1].map(()=>new Promise((resolve,reject)=>{
35 const child=spawn('psql',['-X','-q','-A','-t','-v','ON_ERROR_STOP=1','-c',sql],
36 {env,stdio:['ignore','pipe','pipe']});
37 let out='';
38 child.stdout.on('data',x=>out+=x.toString());
39 child.on('error',reject);
40 child.on('close',code=>code===0?resolve(out.trim()):
41 reject(new Error('CONCURRENT_CAS_STATEMENT_FAILED_REDACTED')));
42 })));
43 const success=output.filter(s=>s.startsWith('TRIGGERED_ENQUEUED|1|'));
44 const losing=output.filter(s=>s==='STALE_REVISION|1|'||s==='ALREADY_TERMINAL|1|');
45 assert.equal(success.length,1);
46 assert.equal(losing.length,1);
47 const count=stmt("SELECT count(*) FROM public.notification_outbox WHERE user_id='"+
48 user+"' AND event_key='"+event+"'");
49 assert.equal(count,'1');
50 const runtime=stmt("SELECT revision::text||':'||(state #>> '{alert,phase}') "+
51 "FROM public.alert_rule_runtime WHERE user_id='"+user+"' AND rule_key='"+rule+"'");
52 assert.equal(runtime,'1:TRIGGERED');
53 // Distinct process race after one CONSENTED claim: a single-use send permit
54 // must authorize exactly one sender, even for the SAME valid claim token.
55 const row=stmt("SELECT outbox_id::text||'|'||claim_token::text "+
56 "FROM public.alert_notification_claim_consented('2026-10-22T12:00:05Z',30)");
57 const [claimedId,token]=row.split('|');
58 assert.equal(claimedId,success[0].split('|')[2]);
59 assert.match(token,/^[a-f0-9-]{36}$/i);
60 const begin="SELECT public.alert_notification_begin_egress('"+claimedId+
61 "','"+token+"','"+dest+"','BALE','2026-10-22T12:00:06Z')::text";
62 const competing=await Promise.all([0,1].map(()=>new Promise((resolve,reject)=>{
63 const proc=spawn('psql',['-X','-q','-A','-t','-v','ON_ERROR_STOP=1','-c',begin],
64 {env,stdio:['ignore','pipe','pipe']});
65 let out='';
66 proc.stdout.on('data',x=>out+=x.toString());
67 proc.on('error',reject);
68 proc.on('close',code=>code===0?resolve(out.trim()):
69 reject(new Error('CONCURRENT_SEND_PERMIT_FAILED_REDACTED')));
70 })));
71 assert.deepEqual(competing.slice().sort(),['false','true']);
72 const permitState=stmt("SELECT count(*) FROM public.notification_outbox "+
73 "WHERE id='"+claimedId+"' AND send_started_at='2026-10-22T12:00:06Z'");
74 assert.equal(permitState,'1');
75 assert.equal(stmt("SELECT public.alert_notification_egress_allowed('"+
76 claimedId+"','"+token+"','"+dest+"','BALE','2026-10-22T12:00:07Z')::text"),'true');
77 stmt("UPDATE public.alert_notification_consents SET revoked_at='2026-10-22T12:00:08Z' "+
78 "WHERE user_id='"+user+"' AND recipient_ref='"+dest+"' AND channel='BALE'");
79 assert.equal(stmt("SELECT public.alert_notification_egress_allowed('"+
80 claimedId+"','"+token+"','"+dest+"','BALE','2026-10-22T12:00:09Z')::text"),'false');
81
82 console.log('ALERT_STATE_OUTBOX_CAS_VERIFIED',JSON.stringify({
83 simultaneousEvaluations:2,successfulTriggers:1,staleOrTerminal:1,
84 outboxRows:1,revision:1,parallelSendPermits:2,successfulSendPermits:1,
85 consentRevokedAfterPermitPreventsEgress:true,liveDatabaseTouched:false,
86 location:'disposable_local_postgres_ci'
87 }));