forked from Nova-reward/Nova-Rewards
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook.service.ts
More file actions
275 lines (239 loc) · 7.07 KB
/
Copy pathwebhook.service.ts
File metadata and controls
275 lines (239 loc) · 7.07 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
import { Injectable, Logger, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Webhook } from './webhook.entity';
import { WebhookDelivery } from './webhook-delivery.entity';
import * as crypto from 'crypto';
import axios from 'axios';
@Injectable()
export class WebhookService {
private readonly logger = new Logger(WebhookService.name);
constructor(
@InjectRepository(Webhook)
private webhookRepository: Repository<Webhook>,
@InjectRepository(WebhookDelivery)
private deliveryRepository: Repository<WebhookDelivery>,
) {}
/**
* Register a new webhook URL for a merchant
*/
async registerWebhook(
merchantId: string,
url: string,
): Promise<Webhook> {
// Check if merchant already has 5 webhooks
const existingWebhooks = await this.webhookRepository.count({
where: { merchantId, isActive: true },
});
if (existingWebhooks >= 5) {
throw new BadRequestException(
'Maximum of 5 webhook URLs allowed per merchant',
);
}
// Validate URL format
try {
new URL(url);
} catch {
throw new BadRequestException('Invalid URL format');
}
// Generate a unique secret for this webhook
const secret = crypto.randomBytes(32).toString('hex');
const webhook = this.webhookRepository.create({
merchantId,
url,
secret,
isActive: true,
});
return this.webhookRepository.save(webhook);
}
/**
* Get all webhooks for a merchant
*/
async getMerchantWebhooks(merchantId: string): Promise<Webhook[]> {
return this.webhookRepository.find({
where: { merchantId, isActive: true },
});
}
/**
* Delete a webhook (soft delete by setting isActive: false)
*/
async deleteWebhook(webhookId: string, merchantId: string): Promise<void> {
const webhook = await this.webhookRepository.findOne({
where: { id: webhookId, merchantId },
});
if (!webhook) {
throw new NotFoundException('Webhook not found');
}
webhook.isActive = false;
await this.webhookRepository.save(webhook);
}
/**
* Deliver an event to all active webhooks for a merchant
*/
async deliverEvent(
merchantId: string,
eventType: string,
payload: Record<string, any>,
): Promise<void> {
const webhooks = await this.webhookRepository.find({
where: { merchantId, isActive: true },
});
if (webhooks.length === 0) {
this.logger.debug(`No active webhooks for merchant ${merchantId}`);
return;
}
const deliveryPromises = webhooks.map((webhook) =>
this.sendWebhook(webhook, eventType, payload),
);
await Promise.allSettled(deliveryPromises);
}
/**
* Send a webhook with retry logic
*/
private async sendWebhook(
webhook: Webhook,
eventType: string,
payload: Record<string, any>,
): Promise<void> {
const startTime = Date.now();
let attemptCount = 0;
let success = false;
let lastError: Error | null = null;
// Retry up to 5 times with exponential backoff
while (attemptCount < 5 && !success) {
attemptCount++;
try {
const delivery = await this.sendSingleWebhook(
webhook,
eventType,
payload,
attemptCount,
);
success = delivery.success;
lastError = null;
break;
} catch (error) {
lastError = error;
this.logger.error(
`Webhook delivery failed for ${webhook.url} (attempt ${attemptCount}/5): ${error.message}`,
);
// Exponential backoff: 2^attempt * 1000ms (1s, 2s, 4s, 8s, 16s)
if (attemptCount < 5) {
const backoffMs = Math.pow(2, attemptCount) * 1000;
await this.sleep(backoffMs);
}
}
}
// Update webhook with last delivery info
await this.webhookRepository.update(webhook.id, {
lastDeliveryAt: new Date(),
lastDeliveryStatus: success ? 200 : 500,
failureCount: success ? 0 : webhook.failureCount + 1,
});
if (!success) {
this.logger.error(
`Webhook ${webhook.url} failed after 5 attempts: ${lastError?.message}`,
);
}
}
/**
* Send a single webhook delivery
*/
private async sendSingleWebhook(
webhook: Webhook,
eventType: string,
payload: Record<string, any>,
attemptNumber: number,
): Promise<WebhookDelivery> {
const startTime = Date.now();
// Create the payload to send
const deliveryPayload = {
event: eventType,
timestamp: new Date().toISOString(),
data: payload,
};
// Sign the payload
const signature = this.signPayload(
JSON.stringify(deliveryPayload),
webhook.secret,
);
try {
const response = await axios.post(webhook.url, deliveryPayload, {
headers: {
'Content-Type': 'application/json',
'X-Webhook-Signature': signature,
'X-Webhook-Id': webhook.id,
'X-Webhook-Attempt': attemptNumber,
},
timeout: 10000, // 10 second timeout
});
const responseTimeMs = Date.now() - startTime;
// Log successful delivery
const delivery = await this.deliveryRepository.create({
webhookId: webhook.id,
eventType,
payload,
responseStatus: response.status,
responseBody: JSON.stringify(response.data),
responseTimeMs,
attemptCount: attemptNumber,
success: true,
});
await this.deliveryRepository.save(delivery);
this.logger.debug(`Webhook delivered to ${webhook.url} in ${responseTimeMs}ms`);
return delivery;
} catch (error) {
const responseTimeMs = Date.now() - startTime;
// Log failed delivery
const delivery = await this.deliveryRepository.create({
webhookId: webhook.id,
eventType,
payload,
responseStatus: error.response?.status || 500,
responseBody: error.response?.data || error.message,
responseTimeMs,
attemptCount: attemptNumber,
success: false,
errorMessage: error.message,
});
await this.deliveryRepository.save(delivery);
throw error;
}
}
/**
* Sign payload with HMAC-SHA256
*/
private signPayload(payload: string, secret: string): string {
return crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
}
/**
* Get delivery history for a webhook
*/
async getDeliveryHistory(
webhookId: string,
merchantId: string,
limit: number = 50,
): Promise<WebhookDelivery[]> {
// Verify webhook belongs to merchant
const webhook = await this.webhookRepository.findOne({
where: { id: webhookId, merchantId },
});
if (!webhook) {
throw new NotFoundException('Webhook not found');
}
return this.deliveryRepository.find({
where: { webhookId },
order: { createdAt: 'DESC' },
take: limit,
});
}
/**
* Helper function to sleep
*/
private sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
}