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
|
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 insufficientString = KEYS[3];
local amount = tonumber(ARGV[1])
local tip = tonumber(ARGV[2])
local fee = tonumber(ARGV[3])
local ourfee = tonumber(ARGV[4])
local frozen = tonumber(ARGV[5])
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 - frozen < amount + tip + fee + ourfee then
return {err = insufficientString .. ' ⚡️' .. balance - frozen .. ' / ' .. 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 = `
local paymentKey = KEYS[1]
local balanceKey = KEYS[2]
local creditKey = KEYS[3]
local hashKey = KEYS[4]
local paymentsKey = KEYS[5]
local pid = KEYS[6]
local total = tonumber(ARGV[1])
local credit = tonumber(ARGV[2])
local hash = ARGV[3]
if redis.call('exists', paymentKey) == 1 then
redis.call('del', paymentKey)
redis.call('srem', 'pending', hash)
redis.call('incrby', balanceKey, total)
redis.call('incrby', creditKey, credit)
redis.call('del', hashKey)
redis.call('lrem', paymentsKey, 0, pid)
redis.call('lrem', 'payments', 0, pid)
return pid
else
error("Payment has already been reversed" .. paymentKey)
end
`;
const debit = defineScript({
NUMBER_OF_KEYS: 3,
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 {
if (!archive.isOpen) 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));
};
// Get with fallback to archive
export const gf = async (k) => {
let v = await db.get(k);
if (v === null) v = await archive.get(k);
try {
return JSON.parse(v);
} catch (e) {
return v;
}
};
// lRange with fallback to archive for missing items
export const lRangeWithArchive = async (k, start, end) => {
const items = await db.lRange(k, start, end);
return items || [];
};
// Get payment/invoice with archive fallback - for individual lookups
export const getWithArchive = async (prefix, id) => {
let v = await db.get(`${prefix}:${id}`);
if (v === null) v = await archive.get(`${prefix}:${id}`);
if (v === null) return null;
try {
const parsed = JSON.parse(v);
// If it's a reference to another key, follow it
if (typeof parsed === "string") {
let ref = await db.get(`${prefix}:${parsed}`);
if (ref === null) ref = await archive.get(`${prefix}:${parsed}`);
if (ref === null) return null;
return JSON.parse(ref);
}
return parsed;
} catch (e) {
return 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];
};
|