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
|
import config from "$config";
import { fail, sleep } from "$lib/utils";
import { createClient, defineScript } from "redis";
import { warn, err } from "$lib/logging";
const DEBIT = `
local balanceKey = KEYS[1]
local creditKey = KEYS[2]
local amount = tonumber(ARGV[1])
local tip = tonumber(ARGV[2])
local fee = tonumber(ARGV[3])
local ourfee = tonumber(ARGV[4])
local balance = tonumber(redis.call('get', balanceKey) or '0')
local credit = tonumber(redis.call('get', creditKey) or '0')
local covered = math.min(credit, ourfee)
ourfee = ourfee - covered
if balance < amount + tip + fee + ourfee then
return {err = 'Insufficient funds ⚡️' .. balance .. ' of ⚡️' .. amount + tip + fee + ourfee}
end
redis.call('decrby', creditKey, tostring(math.floor(covered)))
redis.call('decrby', balanceKey, tostring(math.floor(amount + tip + fee + ourfee)))
return ourfee
`;
const REVERSE = `
-- Keys
local paymentKey = KEYS[1]
local balanceKey = KEYS[2]
local creditKey = KEYS[3]
local hashKey = KEYS[4]
local paymentsKey = KEYS[5]
local pid = KEYS[6]
-- Arguments
local total = tonumber(ARGV[1])
local credit = tonumber(ARGV[2])
local hash = ARGV[3]
-- Hardcoded TTL for the processing state (in milliseconds)
local processingTTL = 5000
-- Generate a unique lock identifier for this script instance
local uniqueId = tostring(redis.call('incr', 'lock:counter')) .. ':' .. redis.call('time')[2]
-- Attempt to atomically claim the payment with a lock
local lockSet = redis.call('set', paymentKey, uniqueId, 'NX', 'PX', processingTTL)
if lockSet then
-- Remove the lock immediately to prevent re-entry
redis.call('del', paymentKey)
-- Proceed with processing
redis.call('incrby', balanceKey, total)
redis.call('incrby', creditKey, credit)
redis.call('del', hashKey)
redis.call('lrem', paymentsKey, 0, pid)
redis.call('srem', 'pending', hash)
return pid
else
-- Another process holds the lock; throw an error
error("Payment has already been reversed")
end
`;
const debit = defineScript({
NUMBER_OF_KEYS: 2,
SCRIPT: DEBIT,
transformArguments: (...args) => args.map((a) => a.toString()),
});
const reverse = defineScript({
NUMBER_OF_KEYS: 6,
SCRIPT: REVERSE,
transformArguments: (...args) => args.map((a) => a.toString()),
});
export const db = createClient({
url: config.db,
scripts: { debit, reverse },
socket: {
reconnectStrategy: (retries) => Math.min(retries * 50, 5000),
},
});
export const archive = createClient({
url: config.archive,
socket: {
reconnectStrategy: (retries) => Math.min(retries * 50, 5000),
},
});
export const arc2 = createClient({
url: config.arc2,
socket: {
reconnectStrategy: (retries) => Math.min(retries * 50, 5000),
},
});
async function dbReconnect() {
try {
await db.connect();
} catch (err) {
console.error("Failed to connect to Redis, retrying...", err);
setTimeout(dbReconnect, 5000); // Retry after 5 seconds
}
}
async function archiveReconnect() {
try {
await archive.connect();
} catch (err) {
console.error("Failed to connect to Redis, retrying...", err);
setTimeout(archiveReconnect, 5000); // Retry after 5 seconds
}
}
dbReconnect();
archiveReconnect();
db.on("error", (e) => {
if (e.message.startsWith("getaddr")) return;
err("Redis error", e.message);
});
db.on("end", () => {
warn("Redis connection ended");
});
export default db;
export const g = async (k) => {
const v = await db.get(k);
try {
return JSON.parse(v);
} catch (e) {
return v;
}
};
export const s = (k, v) => {
if (k === "user:null" || k === "user:undefined") fail("null user");
db.set(k, JSON.stringify(v));
};
export const ga = async (k) => {
const v = await archive.get(k);
try {
return JSON.parse(v);
} catch (e) {
return v;
}
};
export const sa = (k, v) => {
if (k === "user:null" || k === "user:undefined") {
warn("###### NULL USER #######");
console.trace();
}
archive.set(k, JSON.stringify(v));
};
const retries = {};
export const t = async (k, f) => {
try {
await db.watch(k);
await f(await db.get(k), db);
} catch (err) {
if (!err.message.includes("watch")) throw err;
const r = retries[k] || 0;
retries[k] = r + 1;
if (r < 10) {
await sleep(100);
await t(k, f);
} else {
delete retries[k];
fail("unable to obtain lock");
}
}
delete retries[k];
};
|