-
Notifications
You must be signed in to change notification settings - Fork 230
Expand file tree
/
Copy pathcouponService.ts
More file actions
178 lines (154 loc) · 5.91 KB
/
couponService.ts
File metadata and controls
178 lines (154 loc) · 5.91 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
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"
import { DynamoDBDocumentClient, UpdateCommand, ScanCommand } from "@aws-sdk/lib-dynamodb"
import { Mutex, MutexInterface } from 'async-mutex'
import { CouponValidity } from "../types"
export type Coupon = {
id: string,
faucetConfigId: string,
maxLimitAmount: number,
consumedAmount: number,
expiry: number,
amountPerCoupon: number,
reset: boolean,
skipIpRateLimit?: boolean,
skipWalletRateLimit?: boolean,
}
type CouponConfig = {
IS_ENABLED: boolean,
MAX_LIMIT_CAP: number,
}
function validateCouponData(coupon: any, couponConfig: CouponConfig, ignoreCouponLimitCheck = true): Coupon | undefined {
if (
coupon.id &&
coupon.faucetConfigId &&
coupon.maxLimitAmount > 0 &&
(ignoreCouponLimitCheck || coupon.maxLimitAmount <= couponConfig.MAX_LIMIT_CAP) &&
coupon.consumedAmount <= coupon.maxLimitAmount &&
coupon.expiry > 0
) {
return coupon
}
return undefined
}
export class CouponService {
private readonly mutex: MutexInterface
private readonly documentClient?: DynamoDBDocumentClient
private readonly couponConfig: CouponConfig
coupons: Map<string, Coupon>
constructor(couponConfig: CouponConfig) {
this.mutex = new Mutex()
this.coupons = new Map<string, Coupon>()
this.couponConfig = couponConfig
// Return early if coupon system is disabled
if (!couponConfig.IS_ENABLED) return
const ddbClient = new DynamoDBClient({ region: 'us-east-1' })
this.documentClient = DynamoDBDocumentClient.from(ddbClient)
this.syncCoupons()
// Syncs coupon between DynamoDB and memory at regular intervals
setInterval(() => {
this.syncCoupons()
}, 10_000)
}
/**
* Syncs coupons in memory with database
* 1. Fetches new coupons from database into memory
* 2. Remove coupons which were deleted in database from memory
* 3. Updates coupon usage limits in database
* 4. TODO(raj): Delete expired (or few days after expiry) coupons from database
*/
private async syncCoupons(): Promise<void> {
const params = new ScanCommand({
TableName: 'coupons',
})
const result = await this.documentClient?.send(params)
// Required for quick lookup of coupons in DB fetched list
const dbItemSet = new Set<string>()
// Fetches new coupons from database into memory
result?.Items?.forEach((item: Record<string, any>) => {
const coupon: Coupon | undefined = validateCouponData(item, this.couponConfig, true)
if (coupon) {
dbItemSet.add(coupon.id)
// Only load new coupons into memory
if (this.coupons.get(coupon.id) === undefined || coupon.reset) {
coupon.reset = false
this.coupons.set(coupon.id, coupon)
}
} else {
console.log(JSON.stringify({
date: new Date(),
type: 'InvalidCouponFetched',
item
}))
}
})
// Remove coupons which were deleted in database from memory
for (const [id, _item] of this.coupons.entries()) {
if (!dbItemSet.has(id)) {
this.coupons.delete(id)
}
}
// Updates coupon usage limits in database
await this.batchUpdateCoupons()
}
// Iterates over every coupon in memory and updates database with their `consumedAmount`
async batchUpdateCoupons(): Promise<void> {
this.coupons.forEach(async (couponItem, _id) => {
const updateRequest = {
TableName: 'coupons',
Key: {
id: couponItem.id,
},
UpdateExpression: 'SET consumedAmount = :consumedAmount, #resetBool = :resetBool',
ExpressionAttributeNames: {
// 'reset' is a reserved keyword in DynamoDB
'#resetBool': 'reset'
},
ExpressionAttributeValues: {
':consumedAmount': couponItem.consumedAmount,
':resetBool': couponItem.reset ?? false,
},
}
const params = new UpdateCommand(updateRequest)
await this.documentClient?.send(params)
})
}
async consumeCouponAmount(id: string, faucetConfigId: string, amount: number): Promise<CouponValidity> {
// Return `true` early, if coupon system is disabled (for debugging)
if (!this.couponConfig.IS_ENABLED) return { isValid: true, amount }
const release = await this.mutex.acquire()
try {
const coupon = this.coupons.get(id)
const couponAmount = coupon?.amountPerCoupon ?? amount
if (
coupon &&
coupon.faucetConfigId === faucetConfigId &&
coupon.expiry > (Date.now() / 1000) &&
coupon.consumedAmount + couponAmount < coupon.maxLimitAmount
) {
coupon.consumedAmount += couponAmount
return { isValid: true, amount: couponAmount}
}
return { isValid: false, amount: couponAmount}
} finally {
release()
}
}
async reclaimCouponAmount(id: string, amount: number): Promise<void> {
const release = await this.mutex.acquire()
try {
const coupon = this.coupons.get(id)
if (
coupon &&
coupon.expiry > (Date.now() / 1000) &&
coupon.consumedAmount - amount > 0
) {
coupon.consumedAmount -= amount
}
} finally {
release()
}
}
getCoupon(id: string): Coupon | undefined {
return this.coupons.get(id)
}
}