--- lib/http/backend-fetch.ts
+++ lib/http/backend-fetch.ts
... | ... | @@ -137,24 +137,102 @@ |
| 137 | 137 |
}; |
| 138 | 138 |
} |
| 139 | 139 |
|
| 140 |
+/** 로그가 켜지는 환경. 운영에서는 요청·응답을 남기지 않는다. */ |
|
| 141 |
+function loggingEnabled(): boolean {
|
|
| 142 |
+ return process.env.NODE_ENV !== 'production'; |
|
| 143 |
+} |
|
| 144 |
+ |
|
| 145 |
+/** 요청과 응답을 짝지어 읽기 위한 일련번호. 동시 호출이 섞여도 쌍을 찾을 수 있다. */ |
|
| 146 |
+let callSeq = 0; |
|
| 147 |
+ |
|
| 148 |
+/** 로그에 남기면 안 되는 값. 키 이름으로 가린다 — 토큰이 콘솔·로그 파일에 남으면 그 자체가 유출이다. */ |
|
| 149 |
+const SECRET_KEY_PATTERN = /token|password|secret|authorization/i; |
|
| 150 |
+ |
|
| 151 |
+/** 한 번에 남길 본문의 최대 길이. 넘으면 잘라내고 잘렸다고 적는다. */ |
|
| 152 |
+const LOG_BODY_LIMIT = 4000; |
|
| 153 |
+ |
|
| 154 |
+function redactSecrets(value: unknown): unknown {
|
|
| 155 |
+ if (Array.isArray(value)) {
|
|
| 156 |
+ return value.map(redactSecrets); |
|
| 157 |
+ } |
|
| 158 |
+ if (value !== null && typeof value === 'object') {
|
|
| 159 |
+ return Object.fromEntries( |
|
| 160 |
+ Object.entries(value as Record<string, unknown>).map(([key, item]) => |
|
| 161 |
+ SECRET_KEY_PATTERN.test(key) ? [key, '***'] : [key, redactSecrets(item)] |
|
| 162 |
+ ) |
|
| 163 |
+ ); |
|
| 164 |
+ } |
|
| 165 |
+ return value; |
|
| 166 |
+} |
|
| 167 |
+ |
|
| 168 |
+function clip(text: string): string {
|
|
| 169 |
+ return text.length > LOG_BODY_LIMIT |
|
| 170 |
+ ? `${text.slice(0, LOG_BODY_LIMIT)}\n… (${text.length}자 중 앞부분만)`
|
|
| 171 |
+ : text; |
|
| 172 |
+} |
|
| 173 |
+ |
|
| 174 |
+/** 본문 문자열을 JSON이면 보기 좋게, 아니면 그대로 — 어느 쪽이든 민감값은 가리고 길면 자른다. */ |
|
| 175 |
+function formatBody(raw: string): string {
|
|
| 176 |
+ try {
|
|
| 177 |
+ return clip(JSON.stringify(redactSecrets(JSON.parse(raw)), null, 2)); |
|
| 178 |
+ } catch {
|
|
| 179 |
+ return clip(raw); |
|
| 180 |
+ } |
|
| 181 |
+} |
|
| 182 |
+ |
|
| 183 |
+/** |
|
| 184 |
+ * 백엔드에서 **받은** 것을 남긴다. 요청 로그와 같은 번호가 붙는다. |
|
| 185 |
+ * |
|
| 186 |
+ * 본문은 호출부가 이미 읽어 둔 글자를 받는다 — 여기서 `response.text()`를 부르면 스트림이 |
|
| 187 |
+ * 소비돼 호출부가 같은 본문을 다시 읽을 수 없다. |
|
| 188 |
+ */ |
|
| 189 |
+function logResponse( |
|
| 190 |
+ call: { id: number; startedAt: number },
|
|
| 191 |
+ status: number, |
|
| 192 |
+ raw: string | null, |
|
| 193 |
+ note?: string |
|
| 194 |
+): void {
|
|
| 195 |
+ if (!loggingEnabled()) {
|
|
| 196 |
+ return; |
|
| 197 |
+ } |
|
| 198 |
+ |
|
| 199 |
+ const lines = [ |
|
| 200 |
+ `[backend-fetch] #${call.id} ← ${status} (${Date.now() - call.startedAt}ms)`,
|
|
| 201 |
+ ]; |
|
| 202 |
+ if (note) {
|
|
| 203 |
+ lines.push(note); |
|
| 204 |
+ } |
|
| 205 |
+ if (raw !== null) {
|
|
| 206 |
+ lines.push(raw.trim() === '' ? '(본문 없음)' : `response:\n${formatBody(raw)}`);
|
|
| 207 |
+ } |
|
| 208 |
+ |
|
| 209 |
+ console.info(lines.join('\n'));
|
|
| 210 |
+} |
|
| 211 |
+ |
|
| 140 | 212 |
/** |
| 141 | 213 |
* 테스트 환경에서는 백엔드로 나가는 **모든** 요청을 서버 콘솔에 남긴다 — 브라우저 네트워크 |
| 142 | 214 |
* 탭에는 이 호출이 뜨지 않아(BFF) 여기가 유일하게 보이는 자리다. 운영에서는 찍지 않는다. |
| 143 | 215 |
* JSON 본문은 Swagger Request body에 그대로 붙여 넣을 수 있는 모양으로 찍는다. |
| 216 |
+ * |
|
| 217 |
+ * 돌려주는 값을 `logResponse`에 넘기면 요청·응답이 같은 번호로 묶인다. |
|
| 144 | 218 |
*/ |
| 145 | 219 |
function logRequest( |
| 146 | 220 |
method: string, |
| 147 | 221 |
url: string, |
| 148 | 222 |
payload?: { body?: unknown; form?: Record<string, string | number | undefined>; multipart?: FormData; note?: string }
|
| 149 |
-): void {
|
|
| 150 |
- if (process.env.NODE_ENV === 'production') {
|
|
| 151 |
- return; |
|
| 223 |
+): { id: number; startedAt: number } {
|
|
| 224 |
+ const call = { id: (callSeq += 1), startedAt: Date.now() };
|
|
| 225 |
+ |
|
| 226 |
+ if (!loggingEnabled()) {
|
|
| 227 |
+ return call; |
|
| 152 | 228 |
} |
| 153 | 229 |
|
| 154 |
- const lines = [`[backend-fetch] ${method} ${url}`];
|
|
| 230 |
+ const lines = [`[backend-fetch] #${call.id} → ${method} ${url}`];
|
|
| 155 | 231 |
|
| 156 | 232 |
if (payload?.body !== undefined) {
|
| 157 |
- lines.push(`body(JSON):\n${JSON.stringify(payload.body, null, 2)}`);
|
|
| 233 |
+ lines.push( |
|
| 234 |
+ `body(JSON):\n${clip(JSON.stringify(redactSecrets(payload.body), null, 2))}`
|
|
| 235 |
+ ); |
|
| 158 | 236 |
} |
| 159 | 237 |
if (payload?.form) {
|
| 160 | 238 |
const params = new URLSearchParams(); |
... | ... | @@ -178,6 +256,7 @@ |
| 178 | 256 |
} |
| 179 | 257 |
|
| 180 | 258 |
console.info(lines.join('\n'));
|
| 259 |
+ return call; |
|
| 181 | 260 |
} |
| 182 | 261 |
|
| 183 | 262 |
function resolveUrl( |
... | ... | @@ -196,11 +275,9 @@ |
| 196 | 275 |
} |
| 197 | 276 |
|
| 198 | 277 |
/** 봉투 파싱 실패를 예외로 만들지 않는다 — 실패 응답의 형태가 깨져 있어도 호출부는 계속 진행한다. */ |
| 199 |
-async function readEnvelopeSafely( |
|
| 200 |
- response: Response |
|
| 201 |
-): Promise<Partial<BackendEnvelope<unknown>> | null> {
|
|
| 278 |
+function parseEnvelope(raw: string): Partial<BackendEnvelope<unknown>> | null {
|
|
| 202 | 279 |
try {
|
| 203 |
- const parsed: unknown = await response.json(); |
|
| 280 |
+ const parsed: unknown = JSON.parse(raw); |
|
| 204 | 281 |
return parsed !== null && typeof parsed === 'object' |
| 205 | 282 |
? (parsed as Partial<BackendEnvelope<unknown>>) |
| 206 | 283 |
: null; |
... | ... | @@ -229,7 +306,7 @@ |
| 229 | 306 |
init: BackendStreamRequestInit |
| 230 | 307 |
): Promise<BackendResult<Response>> {
|
| 231 | 308 |
const url = resolveUrl(path, init.query); |
| 232 |
- logRequest('GET', url, { note: '(파일 응답 스트림)' });
|
|
| 309 |
+ const call = logRequest('GET', url, { note: '(파일 응답 스트림)' });
|
|
| 233 | 310 |
|
| 234 | 311 |
let response: Response; |
| 235 | 312 |
try {
|
... | ... | @@ -244,11 +321,15 @@ |
| 244 | 321 |
cache: 'no-store', |
| 245 | 322 |
}); |
| 246 | 323 |
} catch (error) {
|
| 324 |
+ logResponse(call, 0, null, '(응답 없음 — 네트워크·타임아웃)'); |
|
| 247 | 325 |
return communicationError('파일 요청 실패(네트워크·타임아웃)', error);
|
| 248 | 326 |
} |
| 249 | 327 |
|
| 250 | 328 |
if (!response.ok) {
|
| 251 |
- const envelope = await readEnvelopeSafely(response); |
|
| 329 |
+ // 실패 응답은 JSON 봉투라 읽어도 스트림을 낭비하지 않는다. |
|
| 330 |
+ const raw = await response.text().catch(() => ''); |
|
| 331 |
+ logResponse(call, response.status, raw); |
|
| 332 |
+ const envelope = parseEnvelope(raw); |
|
| 252 | 333 |
if (envelope && typeof envelope.code === 'number') {
|
| 253 | 334 |
return {
|
| 254 | 335 |
ok: false, |
... | ... | @@ -265,6 +346,15 @@ |
| 265 | 346 |
); |
| 266 | 347 |
} |
| 267 | 348 |
|
| 349 |
+ // 성공 본문은 파일 스트림이다 — 읽으면 호출부가 흘려보낼 것이 사라지므로 머리말만 남긴다. |
|
| 350 |
+ logResponse( |
|
| 351 |
+ call, |
|
| 352 |
+ response.status, |
|
| 353 |
+ null, |
|
| 354 |
+ `(파일 스트림 ${response.headers.get('content-type') ?? '형식 미상'}, ${
|
|
| 355 |
+ response.headers.get('content-length') ?? '길이 미상'
|
|
| 356 |
+ }바이트)` |
|
| 357 |
+ ); |
|
| 268 | 358 |
return { ok: true, data: response };
|
| 269 | 359 |
} |
| 270 | 360 |
|
... | ... | @@ -310,7 +400,7 @@ |
| 310 | 400 |
const { body, contentType } = buildRequestBody(init);
|
| 311 | 401 |
const url = resolveUrl(path, init.query); |
| 312 | 402 |
|
| 313 |
- logRequest(init.method, url, {
|
|
| 403 |
+ const call = logRequest(init.method, url, {
|
|
| 314 | 404 |
body: init.body, |
| 315 | 405 |
form: init.form, |
| 316 | 406 |
multipart: init.multipart, |
... | ... | @@ -332,14 +422,27 @@ |
| 332 | 422 |
next: init.next, |
| 333 | 423 |
}); |
| 334 | 424 |
} catch (error) {
|
| 425 |
+ logResponse(call, 0, null, '(응답 없음 — 네트워크·타임아웃)'); |
|
| 335 | 426 |
return communicationError('요청 실패(네트워크·타임아웃)', error);
|
| 336 | 427 |
} |
| 428 |
+ |
|
| 429 |
+ // 본문은 여기서 딱 한 번 읽는다 — 로그와 파싱이 같은 글자를 쓰고, 스트림을 두 번 읽는 실수를 |
|
| 430 |
+ // 구조적으로 막는다. 아래 분기들은 모두 이 문자열만 본다. |
|
| 431 |
+ let raw: string; |
|
| 432 |
+ try {
|
|
| 433 |
+ raw = await response.text(); |
|
| 434 |
+ } catch (error) {
|
|
| 435 |
+ logResponse(call, response.status, null, '(본문 읽기 실패)'); |
|
| 436 |
+ return communicationError('응답 읽기 실패', error);
|
|
| 437 |
+ } |
|
| 438 |
+ |
|
| 439 |
+ logResponse(call, response.status, raw); |
|
| 337 | 440 |
|
| 338 | 441 |
if (!response.ok) {
|
| 339 | 442 |
// 인증 실패만은 HTTP status로도 온다 — 미인증·권한부족 모두 401 + `{success:true, auth:false,
|
| 340 | 443 |
// code:401}`이다(실측). status만 보고 통신 오류로 뭉뚱그리면 "세션이 끊겼다"와 "서버가 죽었다"를 |
| 341 | 444 |
// 호출부가 구분할 수 없으므로, 봉투에 code가 실려 있으면 그것을 살려서 내려준다. |
| 342 |
- const envelope = await readEnvelopeSafely(response); |
|
| 445 |
+ const envelope = parseEnvelope(raw); |
|
| 343 | 446 |
if (envelope && typeof envelope.code === 'number') {
|
| 344 | 447 |
return {
|
| 345 | 448 |
ok: false, |
... | ... | @@ -363,35 +466,22 @@ |
| 363 | 466 |
return communicationError(`예상치 못한 HTTP 상태: ${response.status}`);
|
| 364 | 467 |
} |
| 365 | 468 |
|
| 366 |
- // 본문 없는 2xx를 허용한 호출은 먼저 글자를 읽어 비었는지 본다 — 비어 있으면 `response.json()`이 |
|
| 367 |
- // 파싱 오류를 던지므로 그 전에 갈라야 한다. |
|
| 368 |
- if (init.canHaveEmptyBody) {
|
|
| 369 |
- let raw: string; |
|
| 370 |
- try {
|
|
| 371 |
- raw = await response.text(); |
|
| 372 |
- } catch (error) {
|
|
| 373 |
- return communicationError('응답 읽기 실패', error);
|
|
| 374 |
- } |
|
| 375 |
- |
|
| 376 |
- if (raw.trim() === '') {
|
|
| 377 |
- return { ok: true, data: null as T };
|
|
| 378 |
- } |
|
| 379 |
- |
|
| 380 |
- try {
|
|
| 381 |
- const parsed = JSON.parse(raw) as BackendEnvelope<T>; |
|
| 382 |
- return parsed.success |
|
| 383 |
- ? { ok: true, data: parsed.data as T }
|
|
| 384 |
- : { ok: false, code: parsed.code, message: parsed.message };
|
|
| 385 |
- } catch (error) {
|
|
| 386 |
- return communicationError('응답 파싱 실패', error);
|
|
| 387 |
- } |
|
| 469 |
+ // 본문 없는 2xx를 허용한 호출은 빈 본문을 정상으로 본다. |
|
| 470 |
+ if (init.canHaveEmptyBody && raw.trim() === '') {
|
|
| 471 |
+ return { ok: true, data: null as T };
|
|
| 388 | 472 |
} |
| 389 | 473 |
|
| 390 | 474 |
let envelope: BackendEnvelope<T>; |
| 391 | 475 |
try {
|
| 392 |
- envelope = (await response.json()) as BackendEnvelope<T>; |
|
| 476 |
+ envelope = JSON.parse(raw) as BackendEnvelope<T>; |
|
| 393 | 477 |
} catch (error) {
|
| 394 | 478 |
return communicationError('응답 파싱 실패', error);
|
| 479 |
+ } |
|
| 480 |
+ |
|
| 481 |
+ if (init.canHaveEmptyBody) {
|
|
| 482 |
+ return envelope.success |
|
| 483 |
+ ? { ok: true, data: envelope.data as T }
|
|
| 484 |
+ : { ok: false, code: envelope.code, message: envelope.message };
|
|
| 395 | 485 |
} |
| 396 | 486 |
|
| 397 | 487 |
if (!envelope.success || (envelope.data === null && !init.canHaveNullData)) {
|
... | ... | @@ -422,7 +512,9 @@ |
| 422 | 512 |
} |
| 423 | 513 |
): Promise<BackendResult<T>> {
|
| 424 | 514 |
const url = resolveUrl(path, undefined); |
| 425 |
- logRequest('POST', url, { note: '(multipart 스트림 본문 — 내용 생략)' });
|
|
| 515 |
+ const call = logRequest('POST', url, {
|
|
| 516 |
+ note: '(multipart 스트림 본문 — 내용 생략)', |
|
| 517 |
+ }); |
|
| 426 | 518 |
|
| 427 | 519 |
let response: Response; |
| 428 | 520 |
try {
|
... | ... | @@ -441,10 +533,14 @@ |
| 441 | 533 |
cache: 'no-store', |
| 442 | 534 |
} as RequestInit); |
| 443 | 535 |
} catch (error) {
|
| 536 |
+ logResponse(call, 0, null, '(응답 없음 — 네트워크·타임아웃)'); |
|
| 444 | 537 |
return communicationError('업로드 실패(네트워크·타임아웃)', error);
|
| 445 | 538 |
} |
| 446 | 539 |
|
| 447 |
- const envelope = await readEnvelopeSafely(response); |
|
| 540 |
+ const raw = await response.text().catch(() => ''); |
|
| 541 |
+ logResponse(call, response.status, raw); |
|
| 542 |
+ |
|
| 543 |
+ const envelope = parseEnvelope(raw); |
|
| 448 | 544 |
|
| 449 | 545 |
if (!response.ok || !envelope || envelope.success !== true) {
|
| 450 | 546 |
if (envelope && typeof envelope.code === 'number') {
|
Add a comment
Delete comment
Once you delete this comment, you won't be able to recover it. Are you sure you want to delete this comment?