forked from StellarEdu/StellarEduPay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretryService.js
More file actions
197 lines (173 loc) · 6.5 KB
/
Copy pathretryService.js
File metadata and controls
197 lines (173 loc) · 6.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
'use strict';
/**
* Retry Service — Stellar Network Outage Recovery
*
* When a Stellar network call fails with a transient error, the transaction hash
* is cached in MongoDB as a PendingVerification document (with schoolId so the
* correct wallet is used on retry). This service runs on a configurable interval,
* checks network reachability, and re-attempts verification with exponential backoff.
*/
const PendingVerification = require('../models/pendingVerificationModel');
const School = require('../models/schoolModel');
const { verifyTransaction, recordPayment } = require('./stellarService');
const { server } = require('../config/stellarConfig');
const config = require('../config/index');
const logger = require('../utils/logger').child('RetryService');
const RETRY_INTERVAL_MS = config.RETRY_INTERVAL_MS;
const MAX_ATTEMPTS = config.RETRY_MAX_ATTEMPTS;
// Exponential backoff: 1m, 2m, 4m … capped at 60 minutes
function nextRetryDelay(attempts) {
const delayMs = Math.min(Math.pow(2, attempts) * 60_000, 60 * 60_000);
return new Date(Date.now() + delayMs);
}
async function isStellarReachable() {
try {
await server.ledgers().order('desc').limit(1).call();
return true;
} catch {
return false;
}
}
/**
* Queue a transaction hash for later retry.
* schoolId is stored so the retry worker can use the right wallet address.
*
* @param {string} txHash
* @param {string|null} studentId
* @param {string} errorMessage
* @param {string} schoolId
*/
async function queueForRetry(txHash, studentId = null, errorMessage = '', schoolId) {
await PendingVerification.findOneAndUpdate(
{ txHash },
{
$setOnInsert: { txHash, studentId, schoolId },
$set: {
status: 'pending',
lastError: errorMessage,
nextRetryAt: new Date(),
},
},
{ upsert: true, new: true }
);
logger.info('Queued transaction for retry', { txHash, schoolId, reason: errorMessage });
}
let _running = false;
let _timer = null;
async function processPendingVerifications() {
if (_running) return;
_running = true;
try {
const due = await PendingVerification.find({
status: 'pending',
nextRetryAt: { $lte: new Date() },
}).limit(50);
if (due.length === 0) { _running = false; return; }
const reachable = await isStellarReachable();
if (!reachable) {
logger.warn('Stellar network still unreachable — skipping batch');
_running = false;
return;
}
logger.info(`Processing ${due.length} pending verification(s)`);
for (const item of due) {
await PendingVerification.findByIdAndUpdate(item._id, {
status: 'processing',
lastAttemptAt: new Date(),
$inc: { attempts: 1 },
});
try {
// Look up the school to get the correct wallet address for verification
const school = await School.findOne({ schoolId: item.schoolId, isActive: true }).lean();
if (!school) {
await PendingVerification.findByIdAndUpdate(item._id, {
status: 'dead_letter',
lastError: `School ${item.schoolId} not found or inactive`,
});
continue;
}
const result = await verifyTransaction(item.txHash, school.stellarAddress);
if (!result) {
await PendingVerification.findByIdAndUpdate(item._id, {
status: 'dead_letter',
lastError: 'verifyTransaction returned null — transaction is permanently invalid',
});
logger.warn('Dead-lettered transaction — permanently invalid', { txHash: item.txHash });
continue;
}
await recordPayment({
schoolId: item.schoolId,
studentId: result.studentId || result.memo,
txHash: result.hash,
transactionHash: result.hash,
amount: result.amount,
feeAmount: result.expectedAmount || result.feeAmount,
feeValidationStatus: result.feeValidation.status,
excessAmount: result.feeValidation.excessAmount || 0,
status: 'confirmed',
memo: result.memo,
confirmedAt: result.date ? new Date(result.date) : new Date(),
});
await PendingVerification.findByIdAndUpdate(item._id, {
status: 'resolved',
resolvedAt: new Date(),
lastError: null,
});
logger.info('Transaction resolved', { txHash: item.txHash, attempts: item.attempts + 1 });
} catch (err) {
const attempts = item.attempts + 1;
const isPermanentError = ['TX_FAILED', 'MISSING_MEMO', 'INVALID_DESTINATION', 'UNSUPPORTED_ASSET', 'DUPLICATE_TX'].includes(err.code);
const isStellarError = !err.code || err.code === 'STELLAR_NETWORK_ERROR';
if (isPermanentError || attempts >= MAX_ATTEMPTS) {
await PendingVerification.findByIdAndUpdate(item._id, {
status: 'dead_letter',
lastError: err.message,
});
logger.error('Dead-lettered transaction', { txHash: item.txHash, reason: isPermanentError ? 'permanent error' : 'max attempts reached', error: err.message, code: err.code });
} else if (isStellarError) {
await PendingVerification.findByIdAndUpdate(item._id, {
status: 'pending',
lastError: err.message,
nextRetryAt: nextRetryDelay(attempts),
});
logger.warn('Rescheduled transaction after Stellar error', { txHash: item.txHash, attempt: attempts, error: err.message });
} else {
await PendingVerification.findByIdAndUpdate(item._id, {
status: 'pending',
lastError: err.message,
nextRetryAt: nextRetryDelay(attempts),
});
logger.error('Unknown error processing transaction', { txHash: item.txHash, error: err.message, code: err.code });
}
}
}
} catch (err) {
logger.error('Unexpected error in processPendingVerifications', { error: err.message, stack: err.stack });
} finally {
_running = false;
}
}
function startRetryWorker() {
if (_timer) return;
logger.info(`Starting — interval: ${RETRY_INTERVAL_MS}ms, max attempts: ${MAX_ATTEMPTS}`);
processPendingVerifications();
_timer = setInterval(processPendingVerifications, RETRY_INTERVAL_MS);
}
function stopRetryWorker() {
if (_timer) {
clearInterval(_timer);
_timer = null;
logger.info('Stopped');
}
}
function isRetryWorkerRunning() {
return _running;
}
module.exports = {
queueForRetry,
processPendingVerifications,
isStellarReachable,
startRetryWorker,
stopRetryWorker,
isRetryWorkerRunning,
};