Repository navigation
Expand file tree
/
Copy pathhealthChecks.ts
More file actions
446 lines (408 loc) · 13.8 KB
/
Copy pathhealthChecks.ts
File metadata and controls
446 lines (408 loc) · 13.8 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import { healthFailureDiagnostics, hasCheckedStoreStock } from './healthCheckEvidence.js';
import { isKnownCgvBlock, type HealthFailureDetails } from './healthFailurePolicy.js';
/**
* 개별 서비스 헬스 체크 실행기
*/
import {
EMART24_UPSTREAM_403_PATTERNS,
GS25_CLOUDFRONT_403_PATTERNS,
HEALTH_CHECKS,
SEVENELEVEN_UPSTREAM_403_PATTERNS,
} from './healthCheckDefinitions.js';
import { hasRequiredRepresentativeFields, toCount, toFirstName } from './healthCheckShape.js';
import type {
HealthCheckDefinition,
HealthCheckMode,
HealthCheckResult,
HealthCheckStatus,
HealthCheckSummary,
} from './healthCheckTypes.js';
export type {
HealthCheckDefinition,
HealthCheckMode,
HealthCheckResult,
HealthCheckStatus,
HealthCheckSummary,
} from './healthCheckTypes.js';
interface RunHealthChecksParams {
baseUrl: string;
service?: string;
check?: string;
mode?: HealthCheckMode;
timeoutMs?: number;
slowThresholdMs?: number;
includeSamples?: boolean;
fresh?: boolean;
cacheBust?: boolean;
fetchImpl?: typeof fetch;
now?: () => number;
}
interface HealthCheckCacheKeyParams {
baseUrl: string;
service?: string;
check?: string;
mode: HealthCheckMode;
timeoutMs: number;
slowThresholdMs?: number;
includeSamples?: boolean;
cacheBust?: boolean;
}
const HEALTH_CHECK_CACHE_TTL_MS = 300_000;
const DEFAULT_HEALTH_CHECK_TIMEOUT_MS = 7000;
const MAX_HEALTH_CHECK_TIMEOUT_MS = 20_000;
const DEFAULT_HEALTH_CHECK_CONCURRENCY = 1;
const DEFAULT_HEALTH_CHECK_SLOW_THRESHOLD_MS = 0;
const healthCheckCache = new Map<string, { expiresAt: number; summary: HealthCheckSummary }>();
function clampTimeout(timeoutMs: number): number {
if (!Number.isFinite(timeoutMs) || timeoutMs < 1) {
return DEFAULT_HEALTH_CHECK_TIMEOUT_MS;
}
return Math.min(Math.trunc(timeoutMs), MAX_HEALTH_CHECK_TIMEOUT_MS);
}
function createCacheKey(params: HealthCheckCacheKeyParams): string {
return [
params.baseUrl,
params.service || '',
params.check || '',
params.mode,
params.timeoutMs,
params.slowThresholdMs || 0,
params.cacheBust ? 'cache-bust' : 'cache',
params.includeSamples ? 'samples' : 'no-samples',
].join('|');
}
function selectChecks(
params: Pick<RunHealthChecksParams, 'service' | 'check' | 'mode'>,
): HealthCheckDefinition[] {
const mode = params.mode || 'quick';
return HEALTH_CHECKS.filter((check) => {
if (mode !== 'full' && check.mode !== mode) {
return false;
}
if (params.service && check.service !== params.service) {
return false;
}
if (params.check && check.id !== params.check) {
return false;
}
return true;
});
}
async function mapWithConcurrency<T, R>(
items: T[],
concurrency: number,
mapper: (item: T) => Promise<R>,
): Promise<R[]> {
const results = new Array<R>(items.length);
let nextIndex = 0;
const workerCount = Math.min(Math.max(1, concurrency), items.length);
await Promise.all(
Array.from({ length: workerCount }, async () => {
while (nextIndex < items.length) {
const currentIndex = nextIndex;
nextIndex += 1;
results[currentIndex] = await mapper(items[currentIndex]);
}
}),
);
return results;
}
function aggregateStatus(checks: HealthCheckResult[]): HealthCheckStatus {
if (checks.length === 0) {
return 'skipped';
}
if (checks.some((check) => check.status === 'fail')) {
return 'fail';
}
if (checks.some((check) => check.status === 'degraded')) {
return 'degraded';
}
if (checks.every((check) => check.status === 'skipped')) {
return 'skipped';
}
return 'ok';
}
function shouldDegradeFailedResponse(check: HealthCheckDefinition, message: string, status: number, body: HealthFailureDetails): boolean {
if (isKnownCgvBlock(check.path, status, body)) return true;
return check.degradedFailurePatterns?.some((pattern) => message.includes(pattern)) ?? false;
}
function shouldDegradeCliContractPath(path: string, message: string, status: number, body: HealthFailureDetails): boolean {
if (isKnownCgvBlock(path, status, body)) return true;
if (path.startsWith('/api/gs25/')) {
return GS25_CLOUDFRONT_403_PATTERNS.some((pattern) => message.includes(pattern));
}
if (path.startsWith('/api/emart24/')) {
return EMART24_UPSTREAM_403_PATTERNS.some((pattern) => message.includes(pattern));
}
if (path.startsWith('/api/seveneleven/')) {
return SEVENELEVEN_UPSTREAM_403_PATTERNS.some((pattern) => message.includes(pattern));
}
return false;
}
function buildCheckUrl(
baseUrl: string,
check: HealthCheckDefinition,
timeoutMs: number,
cacheBustValue?: number,
): string {
const url = new URL(check.path, baseUrl);
url.searchParams.set('timeoutMs', String(timeoutMs));
if (typeof cacheBustValue === 'number') {
url.searchParam
10BC8
s.set('_healthCheck', String(cacheBustValue));
}
return url.toString();
}
const CLI_CONTRACT_PATHS = [
'/health',
'/api/daiso/products?q=%ED%85%8C%EC%9D%B4%ED%94%84&pageSize=1',
'/api/daiso/stores?keyword=%EA%B0%95%EB%82%A8&pageSize=1',
'/api/daiso-jp/products/4550746075917',
'/api/gs25/products?keyword=%EC%BD%9C%EB%9D%BC&limit=1',
'/api/gs25/stores?keyword=%EA%B0%95%EB%82%A8&limit=1',
'/api/seveneleven/products?query=%EC%BB%A4%ED%94%BC&size=1',
'/api/emart24/products?keyword=%EC%BB%A4%ED%94%BC&pageSize=1',
'/api/oliveyoung/products?keyword=%EC%84%A0%ED%81%AC%EB%A6%BC&size=1',
'/api/megabox/theaters?keyword=%EA%B0%95%EB%82%A8&limit=1',
'/api/lottecinema/theaters?keyword=%EC%9E%A0%EC%8B%A4&limit=1',
'/api/cgv/theaters?keyword=%EA%B0%95%EB%82%A8&limit=1',
];
function isCliCompatibleEnvelope(path: string, body: unknown): boolean {
if (!body || typeof body !== 'object') {
return false;
}
const record = body as Record<string, unknown>;
if (path === '/health') {
return record.status === 'ok';
}
return record.success === true && typeof record.data === 'object' && record.data !== null;
}
async function runCliContractCheck(
check: HealthCheckDefinition,
params: Required<Pick<RunHealthChecksParams, 'baseUrl' | 'fetchImpl' | 'now' | 'timeoutMs'>> &
Pick<RunHealthChecksParams, 'cacheBust'>,
): Promise<HealthCheckResult> {
const startedAt = params.now();
const cacheBustValue = params.cacheBust ? startedAt : undefined;
const degradedMessages: string[] = [];
for (const path of CLI_CONTRACT_PATHS) {
const checkTimeoutMs = params.timeoutMs;
const syntheticCheck = { ...check, path };
try {
const response = await params.fetchImpl(
buildCheckUrl(params.baseUrl, syntheticCheck, checkTimeoutMs, cacheBustValue),
{
signal: AbortSignal.timeout(checkTimeoutMs),
},
);
const body = (await response.json().catch(() => ({}))) as {
success?: boolean;
status?: string;
error?: { message?: string; code?: string };
diagnostics?: { upstreamStatus?: number; quotaReason?: unknown; retryAfter?: unknown };
};
if (!response.ok || !isCliCompatibleEnvelope(path, body)) {
const message = body.error?.message || `${path} CLI 계약 응답이 올바르지 않습니다.`;
if (shouldDegradeCliContractPath(path, message, response.status, body)) {
degradedMessages.push(`${path}: ${message}`);
continue;
}
return {
id: check.id,
service: check.service,
target: check.target,
status: 'fail',
durationMs: params.now() - startedAt,
httpStatus: response.status,
message,
...healthFailureDiagnostics(body),
};
}
} catch (error) {
return {
id: check.id,
service: check.service,
target: check.target,
status: 'fail',
durationMs: params.now() - startedAt,
message: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.',
};
}
}
return {
id: check.id,
service: check.service,
target: check.target,
status: degradedMessages.length > 0 ? 'degraded' : 'ok',
durationMs: params.now() - startedAt,
message:
degradedMessages.length > 0
? `known upstream issue: ${degradedMessages[0]}`
: `${CLI_CONTRACT_PATHS.length} CLI contract endpoint(s) passed`,
};
}
async function runSingleCheck(
check: HealthCheckDefinition,
params: Required<Pick<RunHealthChecksParams, 'baseUrl' | 'fetchImpl' | 'now' | 'timeoutMs'>> &
Pick<RunHealthChecksParams, 'includeSamples' | 'slowThresholdMs' | 'cacheBust'>,
): Promise<HealthCheckResult> {
if (check.kind === 'cli-contract') {
return runCliContractCheck(check, params);
}
const timeoutMs = params.timeoutMs;
const startedAt = params.now();
const cacheBustValue = params.cacheBust ? startedAt : undefined;
try {
const response = await params.fetchImpl(
buildCheckUrl(params.baseUrl, check, timeoutMs, cacheBustValue),
{
signal: AbortSignal.timeout(timeoutMs),
},
);
const body = (await response.json().catch(() => {
if (response.ok) throw new Error('invalid JSON response');
return {};
})) as {
success?: boolean;
data?: unknown;
error?: { message?: string; code?: string };
diagnostics?: { upstreamStatus?: number; quotaReason?: unknown; retryAfter?: unknown };
meta?: { total?: number };
};
const durationMs = params.now() - startedAt;
if (!response.ok || body.success === false) {
const message = body.error?.message || `HTTP ${response.status}`;
return {
id: check.id,
service: check.service,
target: check.target,
status: shouldDegradeFailedResponse(check, message, response.status, body) ? 'degraded' : 'fail',
durationMs,
httpStatus: response.status,
message,
...healthFailureDiagnostics(body),
};
}
const inventory = (body.data as { inventory?: { available?: boolean; unavailableReason?: unknown } } | undefined)?.inventory;
if (check.id === 'cu.inventory' && inventory?.available === false) {
const reason = inventory.unavailableReason;
return {
id: check.id,
service: check.service,
target: check.target,
status: 'degraded',
durationMs,
httpStatus: response.status,
message: typeof reason === 'string' && reason.trim() ? reason.trim() : 'inventory unavailable',
};
}
const count = typeof body.meta?.total === 'number' ? body.meta.total : toCount(body.data);
const shapeOk = hasRequiredRepresentativeFields(
body.data,
check.collectionKey,
check.requiredFields,
);
const stockUnchecked = shapeOk && count !== 0 && !hasCheckedStoreStock(check.id, body.data);
const slowThresholdMs = params.slowThresholdMs || DEFAULT_HEALTH_CHECK_SLOW_THRESHOLD_MS;
const slow = slowThresholdMs > 0 && durationMs > slowThresholdMs;
const optionalEmpty = check.allowEmpty === true && count === 0;
const status: HealthCheckStatus = stockUnchecked
? 'fail'
: slow
? 'degraded'
: optionalEmpty
? 'skipped'
: count === null || count === 0 || !shapeOk
? 'degraded'
: 'ok';
const first = params.includeSamples ? toFirstName(body.data) : undefined;
const message = slow
? `slow response: ${durationMs}ms > ${slowThresholdMs}ms`
: optionalEmpty
? 'optional data unavailable'
: count === null
? 'response count unavailable'
: !shapeOk && count !== 0
? `response missing required fields: ${check.requiredFields!.join(', ')}`
: stockUnchecked
? 'store stock was not verified'
: `${count} item(s) returned`;
return {
id: check.id,
service: check.service,
target: check.target,
status,
durationMs,
httpStatus: response.status,
message,
...(first ? { sample: { first } } : {}),
};
} catch (error) {
return {
id: check.id,
service: check.service,
target: check.target,
status: 'fail',
durationMs: params.now() - startedAt,
message: error instanceof Error ? error.message : '알 수 없는 오류가 발생했습니다.',
};
}
}
export async function runHealthChecks(params: RunHealthChecksParams): Promise<HealthCheckSummary> {
const now = params.now || Date.now;
const fetchImpl = params.fetchImpl || ((input, init) => globalThis.fetch(input, init));
const mode = params.mode || 'quick';
const timeoutMs = clampTimeout(params.timeoutMs ?? DEFAULT_HEALTH_CHECK_TIMEOUT_MS);
const slowThresholdMs =
Number.isFinite(params.slowThresholdMs) && params.slowThresholdMs && params.slowThresholdMs > 0
? Math.trunc(params.slowThresholdMs)
: DEFAULT_HEALTH_CHECK_SLOW_THRESHOLD_MS;
const cacheKey = createCacheKey({
...params,
mode,
timeoutMs,
slowThresholdMs,
baseUrl: params.baseUrl,
});
const cached = healthCheckCache.get(cacheKey);
const startedAt = now();
if (!params.fresh && cached && cached.expiresAt > startedAt) {
return {
...cached.summary,
cached: true,
};
}
const checks = await mapWithConcurrency(
selectChecks(params),
DEFAULT_HEALTH_CHECK_CONCURRENCY,
(check) =>
runSingleCheck(check, {
baseUrl: params.baseUrl,
fetchImpl,
now,
timeoutMs,
slowThresholdMs,
includeSamples: params.includeSamples,
cacheBust: params.cacheBust,
}),
);
const summary: HealthCheckSummary = {
status: aggregateStatus(checks),
checkedAt: new Date(startedAt).toISOString(),
durationMs: now() - startedAt,
cached: false,
filters: {
service: params.service || null,
check: params.check || null,
mode,
},
checks,
};
healthCheckCache.set(cacheKey, {
expiresAt: startedAt + HEALTH_CHECK_CACHE_TTL_MS,
summary,
});
return summary;
}
export function __testOnlyClearHealthCheckCache(): void {
healthCheckCache.clear();
}