forked from PayButton/paybutton-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaymentCache.ts
More file actions
executable file
·320 lines (292 loc) · 11 KB
/
paymentCache.ts
File metadata and controls
executable file
·320 lines (292 loc) · 11 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { redis } from 'redis/clientInstance'
import { Address, Prisma } from '@prisma/client'
import {
generateTransactionsWithPaybuttonsAndPricesForAddress,
getTransactionValue,
TransactionsWithPaybuttonsAndPrices,
TransactionWithAddressAndPrices,
TransactionWithAddressAndPricesAndInvoices
} from 'services/transactionService'
import { fetchAllUserAddresses, AddressPaymentInfo } from 'services/addressService'
import { fetchPaybuttonArrayByUserId } from 'services/paybuttonService'
import { RESPONSE_MESSAGES, PAYMENT_WEEK_KEY_FORMAT, KeyValueT } from 'constants/index'
import moment from 'moment-timezone'
import { CacheSet } from 'redis/index'
import { ButtonDisplayData, Payment } from './types'
import { getUserDashboardData } from './dashboardCache'
// ADDRESS:payments:YYYY:MM
const getPaymentsWeekKey = (addressString: string, timestamp: number): string => {
return `${addressString}:payments:${moment.unix(timestamp).format(PAYMENT_WEEK_KEY_FORMAT)}`
}
export async function * getUserUncachedAddresses (userId: string): AsyncGenerator<Address> {
const addresses = await fetchAllUserAddresses(userId, false, false) as Address[]
for (const address of addresses) {
const keys = await getCachedWeekKeysForAddress(address.address)
if (keys.length === 0) {
yield address
}
}
}
export const getPaymentList = async (userId: string): Promise<Payment[]> => {
const uncachedAddressStream = getUserUncachedAddresses(userId)
for await (const address of uncachedAddressStream) {
void await CacheSet.addressCreation(address)
}
return await getCachedPaymentsForUser(userId)
}
const getCachedWeekKeysForAddress = async (addressString: string): Promise<string[]> => {
return await redis.keys(`${addressString}:payments:*`)
}
export const getCachedWeekKeysForUser = async (userId: string): Promise<string[]> => {
const addresses = await fetchAllUserAddresses(userId)
let ret: string[] = []
for (const addr of addresses) {
ret = ret.concat(await getCachedWeekKeysForAddress(addr.address))
}
return ret
}
const getPaymentsByWeek = (addressString: string, payments: Payment[]): KeyValueT<Payment[]> => {
const paymentsGroupedByKey: KeyValueT<Payment[]> = {}
for (const payment of payments) {
const weekKey = getPaymentsWeekKey(addressString, payment.timestamp)
if (weekKey in paymentsGroupedByKey) {
paymentsGroupedByKey[weekKey].push(payment)
} else {
paymentsGroupedByKey[weekKey] = [payment]
}
}
return paymentsGroupedByKey
}
interface GroupedPaymentsAndInfoObject {
groupedPayments: KeyValueT<Payment[]>
info: AddressPaymentInfo
}
export const generatePaymentFromTx = (tx: TransactionsWithPaybuttonsAndPrices): Payment => {
const values = getTransactionValue(tx)
let buttonDisplayDataList: Array<{ name: string, id: string}> = []
if (tx.address.paybuttons !== undefined) {
buttonDisplayDataList = tx.address.paybuttons.map(
(conn) => {
return {
name: conn.paybutton.name,
id: conn.paybutton.id,
providerUserId: conn.paybutton.providerUserId
}
}
)
} else {
console.warn('Orphan address:', tx.address.address)
}
return {
id: tx.id,
timestamp: tx.timestamp,
values,
amount: tx.amount,
networkId: tx.address.networkId,
hash: tx.hash,
buttonDisplayDataList,
address: tx.address.address
}
}
export const generatePaymentFromTxWithInvoices = (tx: TransactionWithAddressAndPricesAndInvoices, userId?: string): Payment => {
const values = getTransactionValue(tx)
let buttonDisplayDataList: Array<{ name: string, id: string}> = []
if (tx.address.paybuttons !== undefined) {
buttonDisplayDataList = tx.address.paybuttons.map(
(conn) => {
return {
name: conn.paybutton.name,
id: conn.paybutton.id,
providerUserId: conn.paybutton.providerUserId
}
}
)
} else {
console.warn('Orphan address:', tx.address.address)
}
let invoices = null
if (tx.invoices.length > 0) {
invoices = tx.invoices.filter(invoice => {
return invoice !== null && invoice.userId === userId
})
}
return {
id: tx.id,
timestamp: tx.timestamp,
values,
amount: tx.amount,
networkId: tx.address.networkId,
hash: tx.hash,
buttonDisplayDataList,
address: tx.address.address,
invoices: invoices ?? []
}
}
export const generateAndCacheGroupedPaymentsAndInfoForAddress = async (address: Address): Promise<GroupedPaymentsAndInfoObject> => {
let paymentList: Payment[] = []
let balance = new Prisma.Decimal(0)
let paymentCount = 0
const txsWithPaybuttonsGenerator = generateTransactionsWithPaybuttonsAndPricesForAddress(address.id)
for await (const batch of txsWithPaybuttonsGenerator) {
for (const tx of batch) {
balance = balance.plus(tx.amount)
if (tx.amount.gt(0)) {
const payment = generatePaymentFromTx(tx)
paymentList.push(payment)
paymentCount++
}
}
}
const info: AddressPaymentInfo = {
balance,
paymentCount
}
paymentList = paymentList.filter((p) => p.values.usd > new Prisma.Decimal(0))
const groupedPayments = getPaymentsByWeek(address.address, paymentList)
return {
groupedPayments,
info
}
}
export const getCachedPaymentsForUser = async (userId: string): Promise<Payment[]> => {
const weekKeys = await getCachedWeekKeysForUser(userId)
const userButtonIds: string[] = (await fetchPaybuttonArrayByUserId(userId))
.map(p => p.id)
let allPayments: Payment[] = []
for (const weekKey of weekKeys) {
const paymentsString = await redis.get(weekKey)
if (paymentsString === null) {
throw new Error(RESPONSE_MESSAGES.CACHED_PAYMENT_NOT_FOUND_404.message)
}
let weekPayments: Payment[] = JSON.parse(paymentsString)
weekPayments = weekPayments
.map(pay => {
pay.buttonDisplayDataList = pay.buttonDisplayDataList.filter(d =>
userButtonIds.includes(d.id)
)
return pay
})
allPayments = allPayments.concat(weekPayments)
}
return allPayments
}
export const getCachedPaymentsCountForUser = async (userId: string, timezone: string): Promise<number> => {
const dashboardData = await getUserDashboardData(userId, timezone)
return dashboardData.total.payments
}
export const cacheGroupedPayments = async (paymentsGroupedByKey: KeyValueT<Payment[]>): Promise<void> => {
await Promise.all(
Object.keys(paymentsGroupedByKey).map(async key =>
await redis.set(key, JSON.stringify(paymentsGroupedByKey[key]))
)
)
}
export const getPaymentsForWeekKey = async (weekKey: string): Promise<Payment[]> => {
const paymentsString = await redis.get(weekKey)
return (paymentsString === null) ? [] : JSON.parse(paymentsString)
}
const cacheGroupedPaymentsRemove = async (weekKey: string, hash: string): Promise<void> => {
const paymentsString = await redis.get(weekKey)
let cachedPayments: Payment[] = (paymentsString === null) ? [] : JSON.parse(paymentsString)
cachedPayments = cachedPayments.filter(pay => pay.hash !== hash)
await redis.set(weekKey, JSON.stringify(cachedPayments))
}
export const uncacheManyTxs = async (txs: TransactionWithAddressAndPrices[]): Promise<void> => {
for (const tx of txs) {
const weekKey = getPaymentsWeekKey(tx.address.address, tx.timestamp)
void await cacheGroupedPaymentsRemove(weekKey, tx.hash)
}
}
const cacheGroupedPaymentsAppend = async (paymentsGroupedByKey: KeyValueT<Payment[]>): Promise<void> => {
await Promise.all(
Object.keys(paymentsGroupedByKey).map(async key => {
const paymentsString = await redis.get(key)
let cachedPayments: Payment[] = (paymentsString === null) ? [] : JSON.parse(paymentsString)
const hashes = paymentsGroupedByKey[key].map(p => p.hash)
cachedPayments = cachedPayments
.filter(p => !hashes.includes(p.hash))
.concat(
paymentsGroupedByKey[key]
)
await redis.set(key, JSON.stringify(cachedPayments))
})
)
}
export const cacheManyTxs = async (txs: TransactionsWithPaybuttonsAndPrices[]): Promise<void> => {
const zero = new Prisma.Decimal(0)
for (const tx of txs.filter(tx => tx.amount > zero)) {
const payment = generatePaymentFromTx(tx)
if (payment.values.usd !== new Prisma.Decimal(0)) {
const paymentsGroupedByKey = getPaymentsByWeek(tx.address.address, [payment])
void await cacheGroupedPaymentsAppend(paymentsGroupedByKey)
}
}
}
export const removePaybuttonToAddressesCache = async (addressStringList: string[], buttonId: string): Promise<void> => {
for (const addressString of addressStringList) {
const keys = await getCachedWeekKeysForAddress(addressString)
for (const key of keys) {
const paymentsString = await redis.get(key)
const weekPayments: Payment[] = (paymentsString === null) ? [] : JSON.parse(paymentsString)
weekPayments.forEach((p) => {
p.buttonDisplayDataList = p.buttonDisplayDataList.filter(dd => dd.id !== buttonId)
})
await redis.set(key, JSON.stringify(weekPayments))
}
}
}
export const appendPaybuttonToAddressesCache = async (addressStringList: string[], buttonDisplayData: ButtonDisplayData): Promise<void> => {
for (const addressString of addressStringList) {
const keys = await getCachedWeekKeysForAddress(addressString)
for (const key of keys) {
const paymentsString = await redis.get(key)
const weekPayments: Payment[] = (paymentsString === null) ? [] : JSON.parse(paymentsString)
weekPayments.forEach((p) =>
p.buttonDisplayDataList.push(buttonDisplayData)
)
await redis.set(key, JSON.stringify(weekPayments))
}
}
}
export const clearRecentAddressCache = async (addressString: string, timestamps: number[]): Promise<void> => {
const weekKeys = timestamps.map(t => getPaymentsWeekKey(addressString, t))
await Promise.all(
weekKeys.map(async (k) =>
await redis.del(k, () => {})
)
)
}
export const initPaymentCache = async (address: Address): Promise<boolean> => {
const cachedKeys = await getCachedWeekKeysForAddress(address.address)
if (cachedKeys.length === 0) {
await CacheSet.addressCreation(address)
return true
}
return false
}
export async function * getPaymentStream (userId: string): AsyncGenerator<Payment> {
const uncachedAddressStream = getUserUncachedAddresses(userId)
for await (const address of uncachedAddressStream) {
console.log('[CACHE]: Creating cache for address', address.address)
await CacheSet.addressCreation(address)
}
const userButtonIds: string[] = (await fetchPaybuttonArrayByUserId(userId))
.map(p => p.id)
const weekKeys = await getCachedWeekKeysForUser(userId)
for (const weekKey of weekKeys) {
const paymentsString = await redis.get(weekKey)
if (paymentsString !== null) {
let weekPayments: Payment[] = JSON.parse(paymentsString)
weekPayments = weekPayments
.map(pay => {
pay.buttonDisplayDataList = pay.buttonDisplayDataList.filter(d =>
userButtonIds.includes(d.id)
)
return pay
})
for (const payment of weekPayments) {
yield payment // Yield one payment at a time
}
}
}
}