forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
404 lines (368 loc) · 14.1 KB
/
Copy pathindex.js
File metadata and controls
404 lines (368 loc) · 14.1 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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
"use strict";
const express = require("express");
const compression = require("compression");
const helmet = require("helmet");
const config = require("./config");
const { version: appVersion } = require("../package.json");
const logger = require("./logger");
const cache = require("./services/cache");
const priceOracle = require("./services/priceOracle");
const priceRefreshJob = require("./jobs/priceRefresh");
const webhookRetryWorker = require("./jobs/webhookRetryWorker");
const airdropExpiryJob = require("./jobs/airdropExpiry");
const { createLeaderElection } = require("./services/leaderElection");
const { makeLeaderAwareJob } = require("./jobs/leaderAwareJob");
const { warmCache } = require("./startup/cacheWarm");
const buildCorsMiddleware = require("./middleware/cors");
const {
buildRateLimit,
buildApiKeyRateLimit,
} = require("./middleware/rateLimit");
const { requestIdMiddleware } = require("./middleware/requestId");
const requestLoggerMiddleware = require("./middleware/requestLogger");
const {
requireApiKey,
attachApiKey,
auditApiKeyUsage,
} = require("./middleware/auth");
const { errorHandler, notFoundHandler } = require("./middleware/errorHandler");
const { checkDatabase } = require("./services/dbHealth");
const pricesRouter = require("./routes/prices");
const alertsRouter = require("./routes/alerts");
const indexerRouter = require("./routes/indexer");
const indexerPoller = require("./indexer/runtime");
const keysRouter = require("./routes/keys");
const webhooksRouter = require("./routes/webhooks");
const airdropsRouter = require("./routes/airdrops");
const apiDocsRouter = require("./routes/apiDocs");
const {
router: metricsRouter,
requestMetricsMiddleware,
} = require("./routes/metrics");
const priceWebSocket = require("./ws/priceWebSocket");
const subscriptionManager = require("./ws/PriceSubscriptionManager");
const webhookDispatcher = require("./services/webhookDispatcher");
// Wrap background jobs with leader-election coordination so that only one
// replica across the deployment runs each job at any given time.
// See README.md#leader-election for design, failover timing, and configuration.
const leaderElectionPriceRefresh = createLeaderElection("price_refresh");
const leaderElectionWebhookRetry = createLeaderElection("webhook_retry");
const leaderElectionAirdropExpiry = createLeaderElection("airdrop_expiry");
const wrappedPriceRefreshJob = makeLeaderAwareJob({
job: priceRefreshJob,
jobName: "price_refresh",
leaderElection: leaderElectionPriceRefresh,
logger,
});
const wrappedWebhookRetryWorker = makeLeaderAwareJob({
job: webhookRetryWorker,
jobName: "webhook_retry",
leaderElection: leaderElectionWebhookRetry,
logger,
});
const wrappedAirdropExpiryJob = makeLeaderAwareJob({
job: airdropExpiryJob,
jobName: "airdrop_expiry",
leaderElection: leaderElectionAirdropExpiry,
logger,
});
const app = express();
let server = {
close(callback) {
if (callback) callback();
},
};
app.use(requestIdMiddleware);
app.use(requestLoggerMiddleware);
app.use(requestMetricsMiddleware);
app.use(compression());
app.use(helmet());
app.use(buildCorsMiddleware(config.corsAllowedOrigins));
app.use(express.json({ limit: config.airdrops.jsonMaxBytes }));
const EMPTY_QUEUE_STATS = {
pendingRetries: null,
lastBatchSize: null,
avgDeliveryLatencyMs: null,
totalRetriesProcessed: null,
};
async function readWebhookRetryQueueStats() {
if (typeof webhookRetryWorker.getQueueStats !== "function")
return EMPTY_QUEUE_STATS;
try {
return await webhookRetryWorker.getQueueStats();
} catch (err) {
logger.warn("Could not read webhook retry queue stats", {
error: err.message,
});
return EMPTY_QUEUE_STATS;
}
}
app.get("/health", async (req, res) => {
const redisConnected = cache.isConnected();
const redisQueueDepth = cache.getCommandQueueLength();
const redisConcurrency = cache.getConcurrencyStats();
const priceRefreshHealth = wrappedPriceRefreshJob.getHealth();
const webhookWorkerHealth = wrappedWebhookRetryWorker.getHealth();
const airdropExpiryHealth = wrappedAirdropExpiryJob.getHealth();
const database = await checkDatabase();
// Queue depth for the retry worker (issue #235) — "the worker is alive"
// says nothing about whether retries are piling up behind it. Health must
// still answer if this telemetry read fails, so a failure degrades to
// nulls rather than failing the whole endpoint.
const webhookRetryQueue = await readWebhookRetryQueueStats();
// Compute overall status:
// unhealthy – Redis is down, or a job is stalled past its grace period
// degraded – a job has not yet run but is still within its startup grace period
// ok – all dependencies healthy
//
// Note: a non-leader instance reports its jobs as not healthy (since they
// aren't running locally), but that's expected — the leader is doing the
// work. The health check distinguishes "not leader" from "stalled" via the
// `leader` field.
let status = "ok";
if (
!redisConnected ||
!priceRefreshHealth.healthy ||
!webhookWorkerHealth.healthy ||
database.status === "error"
) {
const jobsDegraded =
(!priceRefreshHealth.healthy && !priceRefreshHealth.stalled) ||
(!webhookWorkerHealth.healthy && !webhookWorkerHealth.stalled);
status =
!redisConnected ||
priceRefreshHealth.stalled ||
webhookWorkerHealth.stalled ||
database.status === "error"
? "unhealthy"
: jobsDegraded
? "degraded"
: "unhealthy";
}
res.json({
status,
timestamp: new Date().toISOString(),
redis_connected: redisConnected,
redis_unavailable: !redisConnected,
circuits: priceOracle.getCircuitStates(),
redis: {
connected: redisConnected,
command_queue_depth: redisQueueDepth,
concurrency: redisConcurrency,
},
websocket: {
connections: subscriptionManager.connectionCount,
draining: subscriptionManager.isDraining,
drain_stats: subscriptionManager.drainStats,
},
jobs: {
price_refresh: {
healthy: priceRefreshHealth.healthy,
last_success_at: priceRefreshHealth.lastSuccessAt
? new Date(priceRefreshHealth.lastSuccessAt).toISOString()
: null,
last_error: priceRefreshHealth.lastError,
stalled: priceRefreshHealth.stalled,
leader: priceRefreshHealth.leader,
leader_instance_id: priceRefreshHealth.leaderInstanceId,
leader_since: priceRefreshHealth.leaderSince,
},
webhook_retry_worker: {
healthy: webhookWorkerHealth.healthy,
last_success_at: webhookWorkerHealth.lastSuccessAt
? new Date(webhookWorkerHealth.lastSuccessAt).toISOString()
: null,
last_error: webhookWorkerHealth.lastError,
stalled: webhookWorkerHealth.stalled,
leader: webhookWorkerHealth.leader,
leader_instance_id: webhookWorkerHealth.leaderInstanceId,
leader_since: webhookWorkerHealth.leaderSince,
// null pending_retries means Redis could not be read, which is not
// the same as an empty queue.
pending_retries: webhookRetryQueue.pendingRetries,
last_batch_size: webhookRetryQueue.lastBatchSize,
avg_delivery_latency_ms: webhookRetryQueue.avgDeliveryLatencyMs,
total_retries_processed: webhookRetryQueue.totalRetriesProcessed,
},
airdrop_expiry: {
healthy: airdropExpiryHealth.healthy,
last_success_at: airdropExpiryHealth.lastSuccessAt
? new Date(airdropExpiryHealth.lastSuccessAt).toISOString()
: null,
last_error: airdropExpiryHealth.lastError,
stalled: airdropExpiryHealth.stalled,
leader: airdropExpiryHealth.leader,
leader_instance_id: airdropExpiryHealth.leaderInstanceId,
leader_since: airdropExpiryHealth.leaderSince,
},
},
database,
price_source_circuits: priceOracle.getSourceCircuitStates(),
webhook_metrics: webhookDispatcher.getMetrics(),
leader_election: {
instance_id: config.leaderElection.instanceId,
lease_ttl_ms: config.leaderElection.leaseTtlMs,
renew_interval_ms: config.leaderElection.renewIntervalMs,
},
});
});
const apiKeyLimit = buildApiKeyRateLimit({ keyPrefix: "apikey" });
const globalApiLimit = buildRateLimit({
windowSeconds: Math.floor(config.rateLimit.windowMs / 1000),
max: config.rateLimit.max,
keyPrefix: "api",
});
// Resolve any presented API key first so the per-key limiter can meter it,
// then fall through to the IP-keyed limiter for unauthenticated callers.
// Authentication itself is still enforced per-route by requireApiKey.
app.use("/api/v1", attachApiKey());
app.use("/api/v1", auditApiKeyUsage());
app.use("/api/v1", apiKeyLimit);
app.use("/api/v1", globalApiLimit);
app.use("/api/v1", pricesRouter);
app.use("/api/v1", keysRouter);
app.use("/api/v1/alerts", requireApiKey({ scopes: ["alerts"] }));
app.use("/api/v1", alertsRouter);
app.use("/api/v1", indexerRouter);
app.use("/api/v1/webhooks", requireApiKey({ scopes: ["webhooks"] }));
app.use("/api/v1", webhooksRouter);
app.use("/api/v1", airdropsRouter);
app.use("/api-docs", globalApiLimit);
app.use("/api-docs", apiDocsRouter);
app.use(metricsRouter);
app.use(notFoundHandler);
app.use(errorHandler);
function shutdown(signal) {
return async () => {
const inFlightDeliveries = webhookDispatcher.getInFlightCount();
const wsConnections = subscriptionManager.connectionCount;
logger.info(`${signal} received, shutting down`, {
in_flight_webhook_deliveries: inFlightDeliveries,
ws_connections: wsConnections,
});
// Stop leader-aware jobs (releases leases gracefully)
await wrappedPriceRefreshJob.stop();
await wrappedWebhookRetryWorker.stop();
await wrappedAirdropExpiryJob.stop();
const remainingDeliveries = webhookDispatcher.getInFlightCount();
if (remainingDeliveries > 0) {
logger.warn(
"Shutdown complete with in-flight webhook deliveries still pending",
{
remaining: remainingDeliveries,
},
);
}
// Stop non-leader-elected services
indexerPoller.stop();
// Gracefully drain WebSocket connections: broadcast close frame,
// then force-close any still open after the drain timeout (issue #248).
await subscriptionManager.drain(5000);
if (server) server.close();
await cache.disconnect();
process.exit(0);
};
}
/**
* Redacts credentials from a connection URL so it can be logged (issue #236).
*
* Returns a placeholder rather than the raw string if parsing fails, since a
* malformed URL that we cannot parse is also one whose password we cannot
* locate and strip.
*/
function sanitizeUrl(rawUrl) {
if (!rawUrl) return null;
try {
const parsed = new URL(rawUrl);
if (parsed.password) parsed.password = "****";
if (parsed.username) parsed.username = "****";
return parsed.toString();
} catch {
return "[unparseable]";
}
}
/**
* Logs a one-shot startup summary (issue #236).
*
* Previously startup logged only the port, so an operator looking at a
* running instance could not tell which build it was, which Node it ran on,
* or what it was configured to watch without shelling in.
*/
function logStartupBanner() {
logger.info(`SmartDrop backend running on port ${config.port}`, {
app_version: appVersion,
node_version: process.version,
node_env: config.nodeEnv,
port: config.port,
redis_url: sanitizeUrl(config.redis.url),
database_url: sanitizeUrl(process.env.DATABASE_URL),
watched_assets_count: config.watchedAssets.length,
watched_assets: config.watchedAssets,
indexer_enabled: config.indexer.enabled,
instance_id: config.leaderElection.instanceId,
log_level: process.env.LOG_LEVEL || config.nodeEnv,
});
}
async function startServer() {
await warmCache(config.watchedAssets);
server = app.listen(config.port, () => {
logStartupBanner();
priceWebSocket.attach(server);
// Start leader-aware background jobs.
// Each wrapped job starts a leader-election renewal loop. The underlying
// job (cron / setInterval) is only activated when this instance holds
// the leader lease. Non-leader instances remain ready to take over.
wrappedPriceRefreshJob.start();
wrappedWebhookRetryWorker.start();
wrappedAirdropExpiryJob.start();
// Indexer poller is not leader-elected (it uses its own cursor-based
// persistence in Redis and is safe for multiple replicas to run).
indexerPoller.start();
});
return server;
}
if (require.main === module) {
startServer().catch((err) => {
logger.error("Startup failed", { error: err.message });
process.exit(1);
});
process.on("SIGTERM", shutdown("SIGTERM"));
process.on("SIGINT", shutdown("SIGINT"));
// Last-resort safety net for errors that escape all per-job try/catch blocks.
// These handlers do not replace the existing error handling in priceRefresh.js,
// webhookRetryWorker.js, etc. — they are a fallback for truly unexpected throws.
// unhandledRejection: Node >=20 exits by default; we match that behavior but
// run the cleanup sequence first so Redis connections and in-flight jobs are
// shut down cleanly rather than abandoned abruptly.
process.on("unhandledRejection", (reason) => {
logger.error("Unhandled promise rejection — initiating graceful shutdown", {
reason: reason instanceof Error ? reason.message : String(reason),
stack: reason instanceof Error ? reason.stack : undefined,
});
shutdown("unhandledRejection")();
});
// uncaughtException: the process heap is in an undefined state after this event.
// Log and shut down; never swallow and continue running in a potentially corrupt state.
process.on("uncaughtException", (err) => {
logger.error("Uncaught exception — initiating graceful shutdown", {
error: err.message,
stack: err.stack,
});
shutdown("uncaughtException")();
});
}
module.exports = {
app,
server: server || {
close(callback) {
if (callback) callback();
},
},
startServer,
// Exposed for testing
logStartupBanner,
sanitizeUrl,
wrappedPriceRefreshJob,
wrappedWebhookRetryWorker,
wrappedAirdropExpiryJob,
};