forked from SmartDropLabs/smartdrop-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhealth.test.js
More file actions
404 lines (338 loc) · 13.4 KB
/
Copy pathhealth.test.js
File metadata and controls
404 lines (338 loc) · 13.4 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 request = require('supertest');
jest.mock('../src/services/cache', () => ({
isConnected: jest.fn(() => false),
disconnect: jest.fn(),
getConcurrencyStats: jest.fn(() => ({ active: 0, waiting: 0, available: 50, max: 50 })),
getCommandQueueLength: jest.fn(() => 0),
}));
jest.mock('../src/services/priceOracle', () => ({
getCircuitStates: jest.fn(() => ({
coingecko: 'closed',
coinmarketcap: 'open',
stellar_dex: 'half-open',
})),
getSourceCircuitStates: jest.fn(() => [
{ source: 'coingecko', open: false, openUntil: null },
{ source: 'coinmarketcap', open: false, openUntil: null },
]),
refreshAllCachedPrices: jest.fn(),
}));
jest.mock('../src/jobs/priceRefresh', () => ({
start: jest.fn(),
stop: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
jest.mock('../src/jobs/webhookRetryWorker', () => ({
start: jest.fn(),
stop: jest.fn(),
tick: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
jest.mock('../src/ws/priceWebSocket', () => ({
attach: jest.fn(),
}));
// ---------------------------------------------------------------------------
// Helpers – reset modules between tests so mocks are applied cleanly
// ---------------------------------------------------------------------------
function loadApp() {
return require('../src/index').app;
}
// ---------------------------------------------------------------------------
// GET /health – price_source_circuits (pre-existing behaviour)
// ---------------------------------------------------------------------------
describe('GET /health – price_source_circuits', () => {
test('includes an entry per source that has a circuit breaker', async () => {
jest.resetModules();
const app = loadApp();
const res = await request(app).get('/health');
expect(res.status).toBe(200);
expect(Array.isArray(res.body.price_source_circuits)).toBe(true);
const sourceNames = res.body.price_source_circuits.map((c) => c.source);
expect(sourceNames).toEqual(expect.arrayContaining(['coingecko', 'coinmarketcap']));
expect(sourceNames).not.toContain('stellar_dex');
});
test('every circuit starts closed with a null openUntil', async () => {
jest.resetModules();
const app = loadApp();
const res = await request(app).get('/health');
for (const circuit of res.body.price_source_circuits) {
expect(circuit.open).toBe(false);
expect(circuit.openUntil).toBeNull();
}
});
});
// ---------------------------------------------------------------------------
// GET /health – overall response shape
// ---------------------------------------------------------------------------
describe('GET /health – response shape', () => {
test('returns expected top-level fields', async () => {
jest.resetModules();
const app = loadApp();
const res = await request(app).get('/health');
expect(res.status).toBe(200);
expect(res.body.circuits).toEqual({
coingecko: 'closed',
coinmarketcap: 'open',
stellar_dex: 'half-open',
});
expect(res.body).toHaveProperty('status');
expect(res.body).toHaveProperty('timestamp');
expect(res.body).toHaveProperty('redis');
expect(res.body).toHaveProperty('jobs');
expect(res.body).toHaveProperty('database');
expect(res.body).toHaveProperty('price_source_circuits');
});
test('database field reflects configured-but-unused state', async () => {
jest.resetModules();
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.database).toEqual({
configured: true,
checked: false,
status: 'unused',
});
});
test('jobs field contains price_refresh and webhook_retry_worker entries', async () => {
jest.resetModules();
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.jobs).toHaveProperty('price_refresh');
expect(res.body.jobs).toHaveProperty('webhook_retry_worker');
for (const key of ['price_refresh', 'webhook_retry_worker']) {
const job = res.body.jobs[key];
expect(job).toHaveProperty('healthy');
expect(job).toHaveProperty('last_success_at');
expect(job).toHaveProperty('last_error');
expect(job).toHaveProperty('stalled');
}
});
});
// ---------------------------------------------------------------------------
// GET /health – status computation
// ---------------------------------------------------------------------------
describe('GET /health – status computation', () => {
test('status is ok when Redis is connected and jobs are healthy', async () => {
jest.resetModules();
jest.mock('../src/services/cache', () => ({
isConnected: () => true,
disconnect: jest.fn(),
getConcurrencyStats: () => ({ active: 0, waiting: 0, available: 50, max: 50 }),
getCommandQueueLength: () => 0,
}));
jest.mock('../src/jobs/priceRefresh', () => ({
start: jest.fn(),
stop: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
jest.mock('../src/jobs/webhookRetryWorker', () => ({
start: jest.fn(),
stop: jest.fn(),
tick: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.status).toBe('ok');
});
test('status is unhealthy when Redis is disconnected', async () => {
jest.resetModules();
jest.mock('../src/services/cache', () => ({
isConnected: () => false,
disconnect: jest.fn(),
getConcurrencyStats: () => ({ active: 0, waiting: 0, available: 50, max: 50 }),
getCommandQueueLength: () => 0,
}));
jest.mock('../src/jobs/priceRefresh', () => ({
start: jest.fn(),
stop: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
jest.mock('../src/jobs/webhookRetryWorker', () => ({
start: jest.fn(),
stop: jest.fn(),
tick: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.status).toBe('unhealthy');
expect(res.body.redis.connected).toBe(false);
});
test('status is unhealthy when a job is stalled', async () => {
jest.resetModules();
jest.mock('../src/services/cache', () => ({
isConnected: () => true,
disconnect: jest.fn(),
getConcurrencyStats: () => ({ active: 0, waiting: 0, available: 50, max: 50 }),
getCommandQueueLength: () => 0,
}));
jest.mock('../src/jobs/priceRefresh', () => ({
start: jest.fn(),
stop: jest.fn(),
getHealth: () => ({ healthy: false, lastSuccessAt: null, lastError: 'timeout', stalled: true }),
}));
jest.mock('../src/jobs/webhookRetryWorker', () => ({
start: jest.fn(),
stop: jest.fn(),
tick: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.status).toBe('unhealthy');
expect(res.body.jobs.price_refresh.stalled).toBe(true);
expect(res.body.jobs.price_refresh.last_error).toBe('timeout');
});
test('status is degraded during startup grace period (job not yet run)', async () => {
jest.resetModules();
jest.mock('../src/services/cache', () => ({
isConnected: () => true,
disconnect: jest.fn(),
getConcurrencyStats: () => ({ active: 0, waiting: 0, available: 50, max: 50 }),
getCommandQueueLength: () => 0,
}));
jest.mock('../src/jobs/priceRefresh', () => ({
start: jest.fn(),
stop: jest.fn(),
// healthy=false, stalled=false → still in grace period
getHealth: () => ({ healthy: false, lastSuccessAt: null, lastError: null, stalled: false }),
}));
jest.mock('../src/jobs/webhookRetryWorker', () => ({
start: jest.fn(),
stop: jest.fn(),
tick: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.status).toBe('degraded');
});
test('overall status is never ok when any dependency is unhealthy', async () => {
jest.resetModules();
jest.mock('../src/services/cache', () => ({
isConnected: () => false,
disconnect: jest.fn(),
getConcurrencyStats: () => ({ active: 0, waiting: 0, available: 50, max: 50 }),
getCommandQueueLength: () => 0,
}));
jest.mock('../src/jobs/priceRefresh', () => ({
start: jest.fn(),
stop: jest.fn(),
getHealth: () => ({ healthy: false, lastSuccessAt: null, lastError: 'err', stalled: true }),
}));
jest.mock('../src/jobs/webhookRetryWorker', () => ({
start: jest.fn(),
stop: jest.fn(),
tick: jest.fn(),
getHealth: () => ({ healthy: false, lastSuccessAt: null, lastError: 'err', stalled: true }),
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.status).not.toBe('ok');
});
});
// ---------------------------------------------------------------------------
// priceRefresh.getHealth() – unit tests for grace-period logic
// ---------------------------------------------------------------------------
describe('priceRefresh.getHealth() – grace period', () => {
test('returns healthy=false and stalled=false before start() is called', () => {
// Load the real module, bypassing any jest.mock registrations from prior tests
const job = jest.requireActual('../src/jobs/priceRefresh');
// Reset internal state by reloading via isolateModules
let freshJob;
jest.isolateModules(() => {
jest.unmock('../src/jobs/priceRefresh');
freshJob = require('../src/jobs/priceRefresh');
});
const h = freshJob.getHealth();
expect(h.healthy).toBe(false);
expect(h.stalled).toBe(false);
});
});
// ---------------------------------------------------------------------------
// webhookRetryWorker.getHealth() – unit tests for grace-period logic
// ---------------------------------------------------------------------------
describe('webhookRetryWorker.getHealth() – grace period', () => {
test('returns healthy=false and stalled=false before start() is called', () => {
let freshWorker;
jest.isolateModules(() => {
jest.unmock('../src/jobs/webhookRetryWorker');
freshWorker = require('../src/jobs/webhookRetryWorker');
});
const h = freshWorker.getHealth();
expect(h.healthy).toBe(false);
expect(h.stalled).toBe(false);
});
});
// ---------------------------------------------------------------------------
// GET /health – webhook retry queue depth (issue #235)
// ---------------------------------------------------------------------------
describe('GET /health – webhook_retry_worker queue depth', () => {
function mockWorkerWithQueueStats(mockQueueStats) {
jest.mock('../src/jobs/webhookRetryWorker', () => ({
start: jest.fn(),
stop: jest.fn(),
tick: jest.fn(),
getHealth: () => ({ healthy: true, lastSuccessAt: Date.now(), lastError: null, stalled: false }),
getQueueStats: mockQueueStats,
}));
}
test('reports pending retries, last batch size, and average delivery latency', async () => {
jest.resetModules();
mockWorkerWithQueueStats(async () => ({
pendingRetries: 4,
lastBatchSize: 2,
avgDeliveryLatencyMs: 12.5,
totalRetriesProcessed: 9,
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.status).toBe(200);
expect(res.body.jobs.webhook_retry_worker).toEqual(expect.objectContaining({
pending_retries: 4,
last_batch_size: 2,
avg_delivery_latency_ms: 12.5,
total_retries_processed: 9,
}));
});
test('keeps the existing liveness fields alongside the queue depth fields', async () => {
jest.resetModules();
mockWorkerWithQueueStats(async () => ({
pendingRetries: 0,
lastBatchSize: 0,
avgDeliveryLatencyMs: null,
totalRetriesProcessed: 0,
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.body.jobs.webhook_retry_worker).toEqual(expect.objectContaining({
healthy: true,
stalled: false,
pending_retries: 0,
}));
});
test('reports null pending retries rather than zero when the queue cannot be read', async () => {
jest.resetModules();
mockWorkerWithQueueStats(async () => ({
pendingRetries: null,
lastBatchSize: null,
avgDeliveryLatencyMs: null,
totalRetriesProcessed: null,
}));
const app = loadApp();
const res = await request(app).get('/health');
expect(res.status).toBe(200);
expect(res.body.jobs.webhook_retry_worker.pending_retries).toBeNull();
});
test('still answers when reading the queue stats throws', async () => {
jest.resetModules();
mockWorkerWithQueueStats(async () => {
throw new Error('redis unreachable');
});
const app = loadApp();
const res = await request(app).get('/health');
expect(res.status).toBe(200);
expect(res.body.jobs.webhook_retry_worker.pending_retries).toBeNull();
});
});