Intelligence, Advanced Charting & Trading Platform

1 /**
2 * Notification outbox state transitions; transport injected, never imported.
3 * Caller MUST persist via an atomic compare-and-swap store for cross-worker
4 * idempotency. Pure logic cannot promise exactly-once network delivery.
5 */
6 const allowed=new Set(['PENDING','LEASED','SENT','FAILED','UNKNOWN','ACKNOWLEDGED']);
7 export function notificationRecord({id,recipientChannel,eventId,createdAt,maxAttempts=3}){
8 if(typeof id!=='string'||!id||typeof eventId!=='string'||!eventId||
9 !['BALE','PWA','EITA'].includes(recipientChannel)||!Number.isInteger(maxAttempts)||
10 maxAttempts<1||maxAttempts>10||!Number.isFinite(Date.parse(createdAt)))
11 throw new RangeError('invalid message metadata');
12 return {id,eventId,recipientChannel,status:'PENDING',createdAt,
13 attempts:0,maxAttempts,leasedAt:null,leaseUntil:null,providerMessageId:null,deliveredAt:null,
14 failedAt:null,nextRetryAt:null,reason:null};
15 }
16 export function claimDelivery(record,{now,leaseMs=30000}){
17 if(!allowed.has(record?.status)||!Number.isFinite(Date.parse(now))||
18 !Number.isSafeInteger(leaseMs)||leaseMs<=0)throw new RangeError('invalid claim');
19 if(record.status==='SENT'||record.status==='ACKNOWLEDGED'||record.status==='UNKNOWN'||record.attempts>=record.maxAttempts)
20 return {record,claimed:false};
21 const at=Date.parse(now);
22 if(record.status==='LEASED') {
23 if(!Number.isFinite(Date.parse(record.leaseUntil))||
24 !Number.isFinite(Date.parse(record.leasedAt)))
25 throw new RangeError('invalid existing lease');
26 if(Date.parse(record.leaseUntil)>at)
27 return {record,claimed:false};
28 // A prior worker could have sent the message and crashed before persisting
29 // the provider response. Never steal an expired lease and send twice.
30 return {record:{...record,status:'UNKNOWN',leaseUntil:null,nextRetryAt:null,
31 reason:'LEASE_EXPIRED_DELIVERY_UNCERTAIN'},claimed:false};
32 }
33 if(record.nextRetryAt&&Date.parse(record.nextRetryAt)>at)
34 return {record,claimed:false};
35 const updated={...record,status:'LEASED',attempts:record.attempts+1,
36 leasedAt:now,leaseUntil:new Date(at+leaseMs).toISOString(),nextRetryAt:null};
37 return {record:updated,claimed:true};
38 }
39 export function recordDeliveryOutcome(record,{at,success,unknown=false,providerMessageId=null,retryDelayMs=60000}){
40 if(record?.status!=='LEASED'||typeof at!=='string'||!Number.isFinite(Date.parse(at))||
41 !Number.isFinite(Date.parse(record.leasedAt))||
42 Date.parse(at)<Date.parse(record.leasedAt)||typeof success!=='boolean'||
43 typeof unknown!=='boolean'||(unknown&&success)||
44 !Number.isSafeInteger(retryDelayMs)||retryDelayMs<1000)
45 throw new RangeError('invalid completion');
46 // Network timeout after a POST is ambiguous: it might already have been accepted.
47 // Automatic retry risks duplicate user notifications; require manual reconciliation.
48 if(unknown)return {...record,status:'UNKNOWN',leaseUntil:null,failedAt:at,
49 nextRetryAt:null,reason:'OUTCOME_UNKNOWN_RECONCILE_MANUALLY'};
50 if(success){
51 if(typeof providerMessageId!=='string'||!providerMessageId)
52 throw new RangeError('verified provider message ID required');
53 return {...record,status:'SENT',leaseUntil:null,providerMessageId,
54 deliveredAt:at,reason:null};
55 }
56 const exhausted=record.attempts>=record.maxAttempts;
57 return {...record,status:'FAILED',leaseUntil:null,failedAt:at,
58 nextRetryAt:exhausted?null:new Date(Date.parse(at)+retryDelayMs).toISOString(),
59 reason:exhausted?'ATTEMPTS_EXHAUSTED':'RETRY_PENDING'};
60 }
61 export function acknowledgeDelivery(record,{at}){
62 if(record?.status!=='SENT'||!Number.isFinite(Date.parse(at))||
63 Date.parse(at)<Date.parse(record.deliveredAt))
64 throw new RangeError('only sent messages may be acknowledged');
65 return {...record,status:'ACKNOWLEDGED',acknowledgedAt:at};
66 }
67 export function notificationUiStatus(record){
68 switch(record?.status){
69 case 'PENDING':return 'در صف ارسال';
70 case 'LEASED':return 'در حال تلاش برای ارسال';
71 case 'SENT':return 'ارسال توسط ارائه‌دهنده پذیرفته شد؛ مشاهده کاربر تأییدنشده';
72 case 'ACKNOWLEDGED':return 'دریافت توسط کاربر تأیید شد';
73 case 'UNKNOWN':return 'نتیجهٔ ارسال نامشخص است؛ برای جلوگیری از پیام تکراری تلاش مجدد متوقف شد';
74 case 'FAILED':return record.reason==='ATTEMPTS_EXHAUSTED'?'ارسال ناموفق؛ تلاش مجدد متوقف شد':'ارسال ناموفق؛ تلاش مجدد زمان‌بندی شده';
75 default:return 'وضعیت اعلان تأییدنشده';
76 }
77 }