8000 CU 오류 출처와 Safari 종료 경합 수정 by hmmhmmhm · Pull Request #398 · hmmhmmhm/daiso-mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 24 additions & 7 deletions scripts/relay/convenience.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { emart24DirectRouteSpecs, isEmart24Operation } from '../../src/services/emart24/relaySpecs.js';
import {
emart24DirectRouteSpecs,
isEmart24Operation,
} from '../../src/services/emart24/relaySpecs.js';
import { parseSevenStockFailure } from '../../src/utils/sevenStockFailure.js';
import { CU_DEFAULT_HEADERS } from '../../src/services/cu/client.js';
import { GS25_DEFAULT_HEADERS } from '../../src/services/gs25/client.js';
Expand Down Expand Up @@ -267,19 +270,28 @@ export function createConvenienceRelay(
return createHttpRelay(token, {
...options,
cacheTtl: (operation) =>
['cu-store', 'seven-stock', 'gs25-stock', 'emart24-stock'].includes(operation) ? 30000 : 300000,
['cu-store', 'seven-stock', 'gs25-stock', 'emart24-stock'].includes(operation)
? 30000
: 300000,
prefix: '/v1/convenience/',
operations: [...Object.keys(paths), ...Object.keys(emart24DirectRouteSpecs)],
validate(value, operation) {
const parsed = (isEmart24Operation(operation) ? emart24DirectRouteSpecs[operation].input : schemas[operation as Operation]).safeParse(value);
const parsed = (
isEmart24Operation(operation)
? emart24DirectRouteSpecs[operation].input
: schemas[operation as Operation]
).safeParse(value);
if (!parsed.success) throw new RelayError(400);
return parsed.data;
},
async upstream(operation, params, signal, fetcher) {
if (isEmart24Operation(operation)) {
const spec = emart24DirectRouteSpecs[operation];
const { url, init } = spec.build(params);
const response = await abortable(fetcher(url, { ...init, redirect: 'manual', signal }), signal);
const response = await abortable(
fetcher(url, { ...init, redirect: 'manual', signal }),
signal,
);
if (response.status !== 200) {
void response.body?.cancel().catch(() => undefined);
throw new RelayError(502, undefined, undefined, response.status);
Expand Down Expand Up @@ -332,7 +344,9 @@ export function createConvenienceRelay(
.safeParse(data);
throw new RelayError(
502,
rejected.success ? parseSevenStockFailure({ ...rejected.data, status: 400 }) : undefined,
rejected.success
? parseSevenStockFailure({ ...rejected.data, status: 400 })
: undefined,
);
}
if (response.status !== 200) {
Expand Down Expand Up @@ -363,8 +377,11 @@ export function createConvenienceRelay(
if (!successSchema.and(schema).safeParse(data).success) throw new RelayError(502);
return data;
} catch (error) {
// 원본 본문·인증·검색 조건은 보존하지 않고 Seven 오류의 HTTP 상태만 기록합니다.
if (operation.startsWith('seven-') && error instanceof RelayError)
// 원본 본문·인증·검색 조건은 보존하지 않고 HTTP 상태만 기록합니다.
if (
(operation.startsWith('seven-') || operation.startsWith('cu-')) &&
error instanceof RelayError
)
throw new RelayError(error.status, error.upstreamError, error.quota, response.status);
throw error;
}
Expand Down
5 changes: 4 additions & 1 deletion scripts/relay/safari-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export function createSafariLifecycle(
.map((key) => [key, process.env[key]!]),
);
let state = 'idle';
let lifecycleClosed = false;
let active = false;
let calls = 0;
let uncertain = false;
Expand All @@ -44,7 +45,7 @@ export function createSafariLifecycle(
// 진단 기록 실패는 helper 오류 처리를 바꾸지 않습니다.
}
};
const closed = () => state === 'closed';
const closed = () => lifecycleClosed;
const execute = (input?: string): Promise<unknown> => {
pending = new Promise((resolve, reject) => {
child = execFile(
Expand Down Expand Up @@ -142,6 +143,7 @@ export function createSafariLifecycle(
try {
if (((await execute()) as { ready?: boolean })?.ready !== true)
throw new BrowserRequestError('safari-helper');
if (closed()) throw new Error('Safari lifecycle closed');
state = 'ready';
uncertain = false;
} catch (error) {
Expand All @@ -161,6 +163,7 @@ export function createSafariLifecycle(
evaluate: (script: string, args: Record<string, unknown>) =>
runTask(() => execute(JSON.stringify({ script, args }))),
async close() {
lifecycleClosed = true;
state = 'closed';
clearTimeout(recoveryTimer);
recoveryTimer = undefined;
Expand Down
94 changes: 92 additions & 2 deletions src/utils/convenienceTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,79 @@ import { diagnosticHeaders } from './diagnostics.js';
import { isValidDtryxRelayUrl } from '../services/dtryx/transport.js';
import { createTimeoutController, parseRetryAfterDelayMs } from './http.js';
import { parseRelayQuota } from './relayQuota.js';

const CU_RELAY_ERROR_BODY_LIMIT = 4096;
const CU_RELAY_ERROR_CHUNK_LIMIT = 128;

/** CU 원본 상태 헤더를 신뢰하기 전에 고정된 중계 오류 응답인지 확인합니다. */
async function isCuRelayErrorEnvelope(response: Response, signal: AbortSignal): Promise<boolean> {
const rejectBody = () => {
void response.body?.cancel().catch(() => undefined);
return false;
};
if (
response.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() !==
'application/json'
)
return rejectBody();
const contentLength = response.headers.get('content-length');
if (
contentLength !== null &&
(!/^\d+$/.test(contentLength) || Number(contentLength) > CU_RELAY_ERROR_BODY_LIMIT)
)
return rejectBody();
if (!response.body || signal.abo 8000 rted) return rejectBody();

const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let bytes = 0;
let chunkCount = 0;
let resolveAbort!: (reason: 'aborted') => void;
const aborted = new Promise<'aborted'>((resolve) => {
resolveAbort = resolve;
});
const abortListener = () => resolveAbort('aborted');
signal.addEventListener('abort', abortListener, { once: true });
try {
while (true) {
const result = await Promise.race([reader.read(), aborted]);
if (result === 'aborted') return false;
if (result.done) break;
chunkCount += 1;
if (chunkCount > CU_RELAY_ERROR_CHUNK_LIMIT) return false;
bytes += result.value.byteLength;
if (bytes > CU_RELAY_ERROR_BODY_LIMIT) return false;
chunks.push(result.value);
}
} catch {
return false;
} finally {
signal.removeEventListener('abort', abortListener);
void reader.cancel().catch(() => undefined);
}

try {
const bodyBytes = new Uint8Array(bytes);
let offset = 0;
for (const chunk of chunks) {
bodyBytes.set(chunk, offset);
offset += chunk.byteLength;
}
const body = new TextDecoder('utf-8', { fatal: true, ignoreBOM: false }).decode(bodyBytes);
const parsed: unknown = JSON.parse(body);
return (
!!parsed &&
typeof parsed === 'object' &&
!Array.isArray(parsed) &&
Object.keys(parsed).length === 1 &&
'error' in parsed &&
parsed.error === 'Relay request failed'
);
} catch {
return false;
}
}

export interface ConvenienceTransportOptions {
bypassCache?: boolean;
convenienceRelayUrl?: string;
Expand Down 8BD0 Expand Up @@ -136,6 +209,7 @@ async function requestConvenienceRelayRaw<T>(
signal: controller.signal,
});
if (response.status !== 200) {
let cuRelayErrorEnvelope = false;
if (operation === 'seven-stock' && response.status === 502) {
const data: unknown = await response.json().catch(() => undefined);
const failure = parseSevenStockFailure(
Expand All @@ -153,6 +227,19 @@ async function requestConvenienceRelayRaw<T>(
undefined,
failure,
);
} else if (
operation.startsWith('cu-') &&
response.status === 502 &&
/^[1-5]\d{2}$/.test(response.headers.get('x-relay-upstream-status') ?? '')
) {
cuRelayErrorEnvelope = await isCuRelayErrorEnvelope(response, controller.signal);
if (controller.signal.aborted)
throw new ServiceError(
'CONVENIENCE_RELAY_TIMEOUT',
'편의점 릴레이 요청 시간이 초과되었습니다.',
504,
true,
);
} else void response.body?.cancel().catch(() => undefined);
const status = response.status;
const delay = parseRetryAfterDelayMs(response) ?? 250;
Expand All @@ -171,9 +258,12 @@ async function requestConvenienceRelayRaw<T>(
'편의점 릴레이 요청에 실패했습니다.',
status === 429 || status === 503 || status === 504 ? status : 502,
status === 429 || status >= 500,
/^[1-5]\d{2}$/.test(response.headers.get('x-relay-upstream-status') ?? '')
(!operation.startsWith('cu-') || (status === 502 && cuRelayErrorEnvelope)) &&
/^[1-5]\d{2}$/.test(response.headers.get('x-relay-upstream-status') ?? '')
? Number(response.headers.get('x-relay-upstream-status'))
: operation.startsWith('seven-') && status === 502 ? undefined : status,
: operation.startsWith('cu-') || (operation.startsWith('seven-') && status === 502)
? undefined
: status,
parseRelayQuota(status, response.headers),
);
}
Expand Down
55 changes: 53 additions & 2 deletions tests/api/cu-handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,39 @@ describe('handleCuFindStores', () => {
});
});

it.each([
['원본 403', { 'x-relay-upstream-status': '403' }, 403],
['원본 상태 미확인', {}, undefined],
])('CU 재고 handler가 %s 진단을 전달한다', async (_label, headers, expected) => {
mockFetch.mockImplementation(
async () =>
new Response(
expected === undefined
? 'private-upstream-body'
: JSON.stringify({ error: 'Relay request failed' }),
{
status: 502,
headers:
expected === undefined ? headers : { 'content-type': 'application/json', ...headers },
},
),
);
const ctx = createMockContextWithEnv(
{ keyword: '과자' },
{ CONVENIENCE_RELAY_URL: 'https://relay.example', CONVENIENCE_RELAY_TOKEN: 'test-token' },
);
await handleCuCheckInventory(ctx);
expect(ctx.json).toHaveBeenCalledWith(
expect.objectContaining({
success: false,
diagnostics: expect.objectContaining({ upstreamStatus: expected }),
}),
502,
);
expect(JSON.stringify(vi.mocked(ctx.json).mock.calls)).not.toContain('private-upstream-body');
expect(JSON.stringify(vi.mocked(ctx.json).mock.calls)).not.toContain('test-token');
});

describe('handleCuCheckInventory', () => {
it('원본 차단은 유료 호출 없이 재고 이용 불가로 반환한다', async () => {
mockFetch
Expand Down Expand Up @@ -481,7 +514,16 @@ describe('handleCuCheckInventory', () => {
)
.mockResolvedValueOnce(
new Response(
JSON.stringify({ documents: [{ place_name: '안산 중앙역', address_name: '경기도 안산시 단원구 중앙대로 885', y: 37.3172, x: 126.8354 }] }),
JSON.stringify({
documents: [
{
place_name: '안산 중앙역',
address_name: '경기도 안산시 단원구 중앙대로 885',
y: 37.3172,
x: 126.8354,
},
],
}),
),
)
.mockResolvedValueOnce(new Response(JSON.stringify({ totalCnt: 0, storeList: [] })));
Expand Down Expand Up @@ -526,7 +568,16 @@ describe('handleCuCheckInventory', () => {
)
.mockResolvedValueOnce(
new Response(
JSON.stringify({ documents: [{ place_name: '안산 중앙역', address_name: '경기도 안산시 단원구 중앙대로 885', y: 37.3172, x: 126.8354 }] }),
JSON.stringify({
documents: [
{
place_name: '안산 중앙역',
address_name: '경기도 안산시 단원구 중앙대로 885',
y: 37.3172,
x: 126.8354,
},
],
}),
),
)
.mockResolvedValueOnce(new Response(JSON.stringify({ totalCnt: 0, storeList: [] })));
Expand Down
57 changes: 53 additions & 4 deletions tests/app/app-api-cu.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,57 @@ describe('GET /api/cu/stores', () => {
});

describe('GET /api/cu/inventory', () => {
it.each([
['CU 원본 403', 502, { 'x-relay-upstream-status': '403' }, 403, undefined, 502],
['릴레이 또는 Access 502', 502, {}, undefined, undefined, 502],
[
'자체 quota 429',
429,
{ 'x-relay-quota-reason': 'minute', 'retry-after': '60' },
undefined,
'minute',
429,
],
])(
'%s 상태를 공개 JSON 진단으로 직렬화하고 민감한 값을 제외한다',
async (_label, status, headers, expected, quotaReason, apiStatus) => {
mockFetch.mockImplementation(
async () =>
new Response(
expected === undefined
? 'private upstream body'
: JSON.stringify({ error: 'Relay request failed' }),
{
status,
headers:
expected === undefined
? headers
: { 'content-type': 'application/json', ...headers },
},
),
);
const res = await app.request('/api/cu/inventory?keyword=과자&storeCheck=false', undefined, {
CONVENIENCE_RELAY_URL: 'https://relay.example',
CONVENIENCE_RELAY_TOKEN: 'private-relay-token',
});
expect(res.status).toBe(apiStatus);
const serialized = await res.text();
const body = JSON.parse(serialized);
expect(body.success).toBe(false);
if (expected === undefined) expect(body.diagnostics).not.toHaveProperty('upstreamStatus');
else expect(body.diagnostics.upstreamStatus).toBe(expected);
if (quotaReason === undefined) expect(body.diagnostics).not.toHaveProperty('quotaReason');
else expect(body.diagnostics.quotaReason).toBe(quotaReason);
expect(res.headers.get('retry-after')).toBe(quotaReason ? '60' : null);
expect(serialized).not.toContain('private upstream body');
expect(serialized).not.toContain('private-relay-token');
},
);

it('HTML 응답은 재고 확인 불가 사유를 API 응답에 보존한다', async () => {
mockFetch.mockResolvedValueOnce(new Response('{}')).mockResolvedValueOnce(
new Response('<!DOCTYPE html><html>private upstream page</html>'),
);
mockFetch
.mockResolvedValueOnce(new Response('{}'))
.mockResolvedValueOnce(new Response('<!DOCTYPE html><html>private upstream page</html>'));
const res = await app.request('/api/cu/inventory?keyword=과자&storeCheck=false');
const body = await res.json();
expect(body.data.inventory).toMatchObject({
Expand Down Expand Up @@ -102,7 +149,9 @@ describe('GET /api/cu/inventory', () => {
new Response(
JSON.stringify({
totalCnt: 1,
storeList: [{ storeCd: '1', storeNm: '강남점', latVal: 37.5, longVal: 127.0, stock: '4' }],
storeList: [
{ storeCd: '1', storeNm: '강남점', latVal: 37.5, longVal: 127.0, stock: '4' },
],
}),
),
);
Expand Down
Loading
Loading
0