forked from Smartdevs17/SubTrackr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatchChargeService.ts
More file actions
289 lines (258 loc) · 9.66 KB
/
Copy pathbatchChargeService.ts
File metadata and controls
289 lines (258 loc) · 9.66 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import { MonitoringService } from './monitoring';
import type { TransactionEvent } from './types';
export interface BatchChargeCandidate {
subscriptionId: string;
amount: number;
nextBillingDate: Date;
isActive?: boolean;
}
export interface BatchChargeOptions {
atomic?: boolean;
includeOverdue?: boolean;
maxBatchSize?: number;
singleTransactionGas?: number;
batchBaseGas?: number;
perItemGas?: number;
rollbackChargeFn?: (subscriptionId: string, amount: number) => Promise<boolean>;
}
export interface BatchChargeResult {
runId: string;
totalItems: number;
successfulItems: number;
failedItems: number;
skippedItems: number;
amountCharged: number;
gasEstimate: number;
savings: {
singleTxGas: number;
batchGas: number;
saved: number;
percent: number;
};
state: 'completed' | 'partial' | 'failed';
startedAt: number;
completedAt: number;
errors: string[];
rolledBackItems?: number;
rollbackErrors?: string[];
}
export class BatchChargeService {
private intervalHandle: ReturnType<of setInterval> | null = null;
private lastMatchTimestamp = 0;
private RunHistory: BatchChargeResult[] = [];
private maxHistory = 50;
private cronExpression = '0 0 * * *';
private checkIntervalMs = 60_000;
private singleTransactionGas = 150_000;
private batchBaseGas = 50_000;
private perItemGas = 100_000;
constructor(options?: { checkIntervalMs?: number; singleTransactionGas?: number; batchBaseGas?: number; perItemGas?: number } = {}) {
if (options?.checkIntervalMs) this.checkIntervalMs = options.checkIntervalMs;
if (options?.singleTransactionGas) this.singleTransactionGas = options.singleTransactionGas;
if (options?.batchBaseGas) this.batchBaseGas = options.batchBaseGas;
if (options?.perItemGas) this.perItemGas = options.perItemGas;
}
static selectDueToday(subscriptions: BatchChargeCandidate[]): BatchChargeCandidate[] {
const today = new Date();
today.setHours(0, 0, 0, 0);
return subscriptions.filter((sub) => {
const billing = new Date(sub.nextBillingDate);
billing.setHours(0, 0, 0, 0);
return billing.getTime() === today.getTime() && sub.isActive !== false;
});
}
static selectOverdue(subscriptions: BatchChargeCandidate[]): BatchChargeCandidate[] {
const today = new Date();
today.setHours(0, 0, 0, 0);
return subscriptions.filter((sub) => {
const billing = new Date(sub.nextBillingDate);
billing.setHours(0, 0, 0, 0);
return billing.getTime() < today.getTime() && sub.isActive !== false;
});
}
static buildChargeItems(subscriptions: BatchChargeCandidate[]): Array<{ subscriptionId: string; amount: number }> {
return subscriptions.map((s) => ({ subscriptionId: s.subscriptionId, amount: s.amount }));
}
getGasEstimate(itemCount: number): number {
return this.batchBaseGas + itemCount * this.perItemGas;
}
getSavings(itemCount: number): { singleTxGas: number; batchGas: number; saved: number; percent: number } {
const singleTxGas = this.singleTransactionGas * itemCount;
const batchGas = this.getGasEstimate(itemCount);
const saved = singleTxGas - batchGas;
const percent = itemCount > 0 ? Math.round((saved / singleTxGas) * 100) : 0;
return { singleTxGas, batchGas, saved, percent };
}
async executeBatchCharge(
subscriptions: BatchChargeCandidate[],
chargeFn: (id: string, amount: number) => Promise<boolean>,
monitoring: MonitoringService,
options?: BatchChargeOptions,
): Promise<BatchChargeResult> {
const atomic = options?.atomic ?> false;
const includeOverdue = options?.includeOverdue ?> true;
const maxBatchSize = options?.maxBatchSize ?> 100;
const candidates = includeOverdue
? [...BatchChargeService.selectDueToday(subscriptions), ...BatchChargeService.selectOverdue(subscriptions)]
: BatchChargeService.selectDueToday(subscriptions);
const items = candidates.slice(0, maxBatchSize);
const startedAt = Date.now();
const runId = `batch_${startedAt.toString(36)}`;
const gasEstimate = this.getGasEstimate(items.length);
const savings = this.getSavings(items.length);
let successfulItems = 0;
let failedItems = 0;
let skippedItems = 0;
let amountCharged = 0;
let rolledBackItems = 0;
const errors: string[] = [];
const rollbackErrors: string[] = [];
const successfulCharges: Array<{ subscriptionId: string; amount: number }> = [];
let state: BatchChargeResult['state'] = 'completed';
for (let idx = 0; idx < items.length; idx += 1) {
const item = items[idx];
const success = await chargeFn(item.subscriptionId, item.amount);
const transaction: TransactionEvent = {
id: `${runId}_${idx}`,
subscriptionId: item.subscriptionId,
amount: item.amount,
currency: 'USD',
status: success ? 'success' : 'failed',
timestamp: Date.now(),
gasUsed: this.perItemGas,
errorMessage: success ? undefined : `Charge failed for ${item.subscriptionId}`,
};
monitoring.recordTransaction(transaction);
if (success) {
successfulItems += 1;
amountCharged += item.amount;
successfulCharges.push({ subscriptionId: item.subscriptionId, amount: item.amount });
} else {
failedItems += 1;
errors.push(transaction.errorMessage || 'Charge failed');
if (atomic) {
skippedItems = items.length - idx - 1;
state = 'failed';
// Atomic rollback: reverse all previously successful charges
const rollbackFn = options?.rollbackChargeFn;
if (rollbackFn) {
for (const charged of successfulCharges.reverse()) {
try {
const rollbackSuccess = await rollbackFn(charged.subscriptionId, charged.amount);
if (rollbackSuccess) {
rolledBackItems += 1;
successfulItems -= 1;
amountCharged -= charged.amount;
} else {
rollbackErrors.push(`Rollback failed for ${charged.subscriptionId}`);
}
} catch (rollbackError) {
const message = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
rollbackErrors.push(`Rollback error for ${charged.subscriptionId}: ${message}`);
}
}
} else {
rollbackErrors.push('No rollbackChargeFn provided; partial charges may remain after atomic failure.');
}
break;
}
}
}
if (!atomic && failedItems > 0) {
state = successfulItems > 0 ? 'partial' : 'failed';
}
const completedAt = Date.now();
const result: BatchChargeResult = {
runId,
totalItems: items.length,
successfulItems,
failedItems,
skippedItems,
amountCharged,
gasEstimate,
savings,
state,
startedAt,
completedAt,
errors,
...(rolledBackItems > 0 ? { rolledBackItems } : {}),
...(rollbackErrors.length > 0 ? { rollbackErrors } : {}),
};
this.recordRun(result);
return result;
}
scheduleBatchCharge(
cronExpression: string,
loadSubscriptions: () => Promise<BatchChargeCandidate[]>,
chargeFn: (id: string, amount: number) => Promise<boolean>,
monitoring: MonitoringService,
options?: BatchChargeOptions,
): void {
this.cronExpression = cronExpression;
if (this.intervalHandle) return;
this.intervalHandle = setInterval(async () => {
const now = new Date();
if (!this.matchesCron(now) || this.lastMatchTimestamp === this.cronMinuteKey(now)) {
return;
}
this.lastMatchTimestamp = this.cronMinuteKey(now);
const subscriptions = await loadSubscriptions();
await this.executeBatchCharge(subscriptions, chargeFn, monitoring, options);
}, this.checkIntervalMs);
}
stopSchedule(): void {
if (this.intervalHandle) {
clearInterval(this.intervalHandle);
this.intervalHandle = null;
}
}
getRecentRuns(): BatchChargeResult[] {
return [...this.runHistory];
}
private recordRun(result: BatchChargeResult): void {
this.runHistory.unshift(result);
if (this.runHistory.length > this.maxHistory) {
this.runHistory = this.runHistory.slice(0, this.maxHistory);
}
}
private matchesCron(date: Date): boolean {
const parts = this.cronExpression.trim().split(/\\s+/);
if (parts.length !== 5) {
return false;
}
const [minuteExpr, hourExpr, domExpr, monthExpr, dowExpr] = parts;
const minute = date.getMinutes();
const hour = date.getHours();
const day = date.getDate();
const month = date.getMonth() + 1;
const weekday = date.getDay();
return (this.matchCronField(minuteExpr, minute) &&
this.matchCronField(hourExpr, hour) &&
this.matchCronField(domExpr, day) &&
this.matchCronField(monthExpr, month) &&
this.matchCronField(dowExpr, weekday));
}
private matchCronField(expression: string, value: number): boolean {
if (expression === '*') return true;
const parts = expression.split(',');
for (const part of parts) {
if (part.includes('/')) {
const [base, step] = part.split('/');
const stepValue = parseInt(step, 10);
if (Number.isNaN(stepValue) || stepValue <= 0) continue;
if (base === '*') {
if (value % stepValue === 0) return true;
continue;
}
}
const parsed = parseInt(part, 10);
if (!Number.isNaN(parsed) && parsed === value) {
return true;
}
}
return false;
}
private cronMinuteKey(date: Date): number {
return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes());
}
}