Repository navigation
Expand file tree
/
Copy pathrouteHealth.ts
More file actions
354 lines (353 loc) · 11 KB
/
Copy pathrouteHealth.ts
File metadata and controls
354 lines (353 loc) · 11 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
/** 사전 점검 결과를 이용하며 요청 경로에서는 상태 저장소를 기다리지 않습니다. */
import { AsyncLocalStorage } from 'node:async_hooks';
import { ServiceError } from '../core/errors.js';
import { HttpError } from './http.js';
export const ROUTE_KEYS = [
'oy-find-store',
'oy-product-search',
'oy-goods-info',
'oy-stock-stores',
'cu-prime',
'cu-stock',
'cu-store',
'emart24-stores',
'emart24-products',
'emart24-stock',
'emart24-store-detail',
'gs25-products',
'gs25-stock',
'seven-goods',
'seven-store',
'seven-popwords',
'seven-stock-meta',
'seven-stock',
'seven-pages',
'seven-issues',
'seven-exhibitions',
'dtryx-movies',
'dtryx-play-dates',
'dtryx-timetable',
'cgv-theaters',
'cgv-movies',
'cgv-timetable',
'cgv-timetable-movie',
] as const;
export type RouteKey = (typeof ROUTE_KEYS)[number];
export const ROUTE_GROUPS = ['oliveyoung', 'convenience', 'dtryx', 'cgv'] as const;
export type RelayGroup = (typeof ROUTE_GROUPS)[number];
export const CU_REDIRECT_LOCATION_CLASSES = [
'missing',
'invalid-or-unsafe',
'same-origin',
'other-origin',
] as const;
export type CuRedirectLocationClass = (typeof CU_REDIRECT_LOCATION_CLASSES)[number];
export interface RouteCheck {
key: RouteKey;
direct: boolean;
checkedAt: number;
reason?: string;
cuRedirectLocation?: CuRedirectLocationClass;
}
export interface RelayCheck {
group: RelayGroup;
healthy: boolean;
checkedAt: number;
reason?: string;
}
export interface RouteSnapshot {
routes: Partial<Record<RouteKey, RouteCheck & { failedAt?: number; blockedUntil?: number }>>;
relays: Partial<Record<RelayGroup, RelayCheck>>;
}
export const ROUTE_MAX_AGE_MS = 600000;
export const ROUTE_COOLDOWN_MS = 300000;
const SNAPSHOT_REFRESH_MS = 30000;
const STORAGE_NAME = 'upstream-route-health-v1';
type Context = { namespace: DurableObjectNamespace; waitUntil: (p: Promise<unknown>) => void };
type Cached = { snapshot: RouteSnapshot; refreshAt: number; snapshotAt: number };
const context = new AsyncLocalStorage<Context>();
const cache = new Map<string, Cached>();
const empty = (): RouteSnapshot => ({ routes: {}, relays: {} });
export function isRouteKey(value: unknown): value is RouteKey {
return typeof value === 'string' && (ROUTE_KEYS as readonly string[]).includes(value);
}
export function isRelayGroup(value: unknown): value is RelayGroup {
return typeof value === 'string' && (ROUTE_GROUPS as readonly string[]).includes(value);
}
/** 원문이나 토큰 대신 사전에 정한 진단 코드만 보관합니다. */
export function validReason(value: unknown): boolean {
return (
value === undefined ||
(typeof value === 'string' &&
([
'ok',
'http',
'network',
'shape',
'timeout',
'unavailable',
'quota',
'configuration',
'pinned',
'pinned-relay',
'http-error',
'network-error',
'invalid-response',
'response-too-large',
'cancelled',
'invalid-input',
'recovered-network-error',
'recovered-timeout',
].includes(value) ||
/^(?:http-[1-5][0-9]{2}|recovered-http-5[0-9]{2})$/.test(value)))
);
}
export function validTime(value: unknown): value is number {
return (
typeof value === 'number' &&
Number.isSafeInteger(value) &&
value >= 0 &&
value <= Date.now() + 60000
);
}
export function validRouteCheck(value: unknown): value is RouteCheck {
if (!value || typeof value !== 'object') return false;
const row = value as RouteCheck;
const cuRedirectLocation = row.cuRedirectLocation;
return (
isRouteKey(row.key) &&
typeof row.direct === 'boolean' &&
validTime(row.checkedAt) &&
validReason(row.reason) &&
(cuRedirectLocation === undefined ||
((row.key === 'cu-prime' || row.key === 'cu-stock' || row.key === 'cu-store') &&
row.direct === false &&
row.reason === 'http-302' &&
CU_REDIRECT_LOCATION_CLASSES.includes(cuRedirectLocation)))
);
}
export function validRelayCheck(value: unknown): value is RelayCheck {
if (!value || typeof value !== 'object') return false;
const row = value as RelayCheck;
return (
isRelayGroup(row.group) &&
typeof row.healthy === 'boolean' &&
validTime(row.checkedAt) &&
validReason(row.reason)
);
}
export function withRouteRouting<T>(
namespace: DurableObjectNamespace | undefined,
waitUntil: ((p: Promise<unknown>) => void) | undefined,
work: () => T,
): T {
return namespace && waitUntil ? context.run({ namespace, waitUntil }, work) : context.exit(work);
}
function objectId(namespace: DurableObjectNamespace) {
return namespace.idFromName(STORAGE_NAME);
}
async function storageRequest<T = Response>(
namespace: DurableObjectNamespace,
path: string,
data?: unknown,
consume: (response: Response) => Promise<T> = async (response) => response as T,
): Promise<T> {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout>;
// fetch가 중단 신호를 무시해도 상태 호출의 대기 시간을 제한합니다.
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
controller.abort();
reject(new Error('timeout'));
}, 2000);
});
try {
return await Promise.race([
namespace
.get(objectId(namespace))
.fetch(`https://route-health.internal${path}`, {
method: data === undefined ? 'GET' : 'POST',
...(data === undefined
? {}
: { body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }),
signal: controller.signal,
})
.then(consume),
timeout,
]);
} finally {
clearTimeout(timer!);
}
}
export async function readRouteSnapshot(namespace: DurableObjectNamespace): Promise<RouteSnapshot> {
try {
const raw = await storageRequest(namespace, '/snapshot', undefined, async (response) =>
response.ok ? ((await response.json()) as RouteSnapshot) : null,
);
if (
!raw ||
typeof raw.routes !== 'object' ||
!raw.routes ||
typeof raw.relays !== 'object' ||
!raw.relays
)
return empty();
const snapshot = empty();
for (const key of ROUTE_KEYS) {
const row = raw.routes[key];
if (!validRouteCheck(row) || row.key !== key) continue;
snapshot.routes[key] = {
key,
direct: key !== 'gs25-stock' && row.direct,
checkedAt: row.checkedAt,
...(row.reason === undefined ? {} : { reason: row.reason }),
...(row.cuRedirectLocation === undefined
? {}
: { cuRedirectLocation: row.cuRedirectLocation }),
...(validTime(row.failedAt) ? { failedAt: row.failedAt } : {}),
...(typeof row.blockedUntil === 'number' &&
Number.isSafeInteger(row.blockedUntil) &&
row.blockedUntil >= 0 &&
row.blockedUntil <= Date.now() + ROUTE_COOLDOWN_MS + 60000
? { blockedUntil: row.blockedUntil }
: {}),
};
}
for (const group of ROUTE_GROUPS) {
const row = raw.relays[group];
if (validRelayCheck(row) && row.group === group)
snapshot.relays[group] = {
group,
healthy: row.healthy,
checkedAt: row.checkedAt,
...(row.reason === undefined ? {} : { reason: row.reason }),
};
}
return snapshot;
} catch {
return empty();
}
}
export async function writeRouteChecks(
namespace: DurableObjectNamespace,
checks: RouteCheck[],
relays: RelayCheck[],
): Promise<void> {
try {
await storageRequest(namespace, '/checks', { checks, relays });
} catch {
/* 상태 쓰기 장애는 서비스 요청에 전파하지 않습니다. */
}
}
function background(ctx: Context, task: Promise<unknown>) {
ctx.waitUntil(task.catch(() => undefined));
}
function groupFor(key: RouteKey): RelayGroup {
return key.startsWith('cgv-')
? 'cgv'
: key.startsWith('oy-')
? 'oliveyoung'
: key.startsWith('dtryx-')
? 'dtryx'
: 'convenience';
}
function fresh(at: number, now: number) {
return at <= now && now - at <= ROUTE_MAX_AGE_MS;
}
export async function routeOperation<T>(
key: RouteKey,
budgetMs: number,
direct: (ms: number) => Promise<T>,
relay: (ms: number) => Promise<T>,
signal?: AbortSignal,
): Promise<T> {
signal?.throwIfAborted();
const ctx = context.getStore();
if (!ctx) return relay(budgetMs);
let cacheKey: string;
try {
cacheKey = objectId(ctx.namespace).toString();
} catch {
return relay(budgetMs);
}
const now = Date.now();
let cached = cache.get(cacheKey);
if (!cached) {
cached = { snapshot: empty(), refreshAt: 0, snapshotAt: 0 };
cache.set(cacheKey, cached);
}
if (now - cached.refreshAt >= SNAPSHOT_REFRESH_MS) {
cached.refreshAt = now;
const target = cached;
background(
ctx,
readRouteSnapshot(ctx.namespace).then((snapshot) => {
// 비동기 읽기 중 발생한 실제 실패를 이전 저장소 응답으로 덮어쓰지 않습니다.
for (const route of ROUTE_KEYS) {
const local = target.snapshot.routes[route];
if (
local?.failedAt &&
local.failedAt > (snapshot.routes[route]?.failedAt || 0) &&
(snapshot.routes[route]?.checkedAt || 0) < local.failedAt + ROUTE_COOLDOWN_MS
)
snapshot.routes[route] = local;
}
target.snapshot = snapshot;
target.snapshotAt = Date.now();
}),
);
}
const state = cached.snapshot.routes[key];
const relayState = cached.snapshot.relays[groupFor(key)];
const cacheFresh = now - cached.snapshotAt < SNAPSHOT_REFRESH_MS;
const directUsable =
cacheFresh &&
key !== 'gs25-stock' &&
state &&
fresh(state.checkedAt, now) &&
state.direct &&
(state.blockedUntil || 0) <= now;
if (!directUsable) {
if (
cacheFresh &&
state &&
fresh(state.checkedAt, now) &&
!state.direct &&
relayState &&
fresh(relayState.checkedAt, now) &&
!relayState.healthy
)
throw new ServiceError(
'UPSTREAM_ROUTE_UNAVAILABLE',
'외부 서비스 연결을 사용할 수 없습니다.',
503,
true,
);
return relay(budgetMs);
}
try {
return await direct(Math.min(3000, budgetMs));
} catch (error) {
if (signal?.aborted || (error instanceof HttpError && [400, 404, 422].includes(error.status)))
throw error;
const at = Date.now();
cached.snapshot.routes[key] = {
...state,
direct: false,
failedAt: at,
blockedUntil: at + ROUTE_COOLDOWN_MS,
};
background(ctx, storageRequest(ctx.namespace, '/failure', { key, at }));
const remaining = budgetMs - (at - now);
if (remaining <= 0) throw error;
signal?.throwIfAborted();
if (relayState && fresh(relayState.checkedAt, at) && !relayState.healthy)
throw new ServiceError(
'UPSTREAM_ROUTE_UNAVAILABLE',
'외부 서비스 연결을 사용할 수 없습니다.',
503,
true,
);
return relay(remaining);
}
}