diff --git a/.agent/consumer.md b/.agent/consumer.md index aa59e41..af2543c 100644 --- a/.agent/consumer.md +++ b/.agent/consumer.md @@ -16,3 +16,12 @@ Before each related task, read the current contents of every matching reference, | Package upgrade, dependency changes, lockfile, or verification | `.agent-harness/references/kri-front-common/change-and-verification.md` | If a task spans multiple scopes, read every matching reference. Generated files under `.agent-harness/references/` are read-only copies; edit KriFrontCommon's `.agent/consumer.md` or `.agent/consumer-references/` and recompose instead. + +## HTTP Streaming + +- `@kri/common/http` HTTP clients expose streamGet/streamPost/streamPut/streamPatch/streamDel, returning HttpStreamResponse (status, statusText, headers, url, nullable body). +- Streaming shares ordinary authentication, URL, body and HTTP-error policy. Read body incrementally; no automatic JSON/NDJSON/SSE parsing or reconnect is performed. +- Streaming options accept an external AbortSignal. Caller cancellation raises AbortError without an HTTP error notification. Cancel the body when it will not be consumed. +- timeoutMs covers connection/headers (and an HTTP error body); idleTimeoutMs covers inactivity after successful headers and resets on consumed chunks. Both default to the client's defaultTimeoutMs (60 seconds by default), and 0 disables that timer for streaming only. +- Mid-stream transport/time-out errors reach the body reader. HTTP error statuses use existing HttpError handlers before a stream is returned. A 204 response has body=null. +- See HTTP_STREAMING.md for examples and node --test tests/http-stream.test.mjs for focused validation after npm run build. diff --git a/package.json b/package.json index a64c3c1..a653c0b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kri/common", - "version": "0.19.0", + "version": "0.19.1", "description": "KRI 프런트엔드 공통 유틸리티", "type": "module", "main": "./dist/index.js", diff --git a/src/http/http-client.ts b/src/http/http-client.ts index 0a541cc..0d5173e 100644 --- a/src/http/http-client.ts +++ b/src/http/http-client.ts @@ -193,6 +193,29 @@ export type RequestOptionsWithoutBody = Omit< export type DeleteRequestOptions = Omit; +export type StreamRequestOptions = Omit< + RequestOptions, + "expectText" | "expectBinary" +> & { + signal?: AbortSignal; + /** 응답 수신 중 무응답 제한. 기본 60초, 0은 제한 없음. */ + idleTimeoutMs?: number; +}; + +export type StreamOptionsWithoutBody = Omit< + StreamRequestOptions, + RequestOptionBodyKeys +>; +export type StreamDeleteOptions = Omit; + +export type HttpStreamResponse = { + status: number; + statusText: string; + headers: Headers; + url: string; + body: ReadableStream | null; +}; + const replacePathParams = (path: string, params?: PathParams): string => { if (!params) { return path; @@ -665,11 +688,198 @@ const createRequest = ( }; }; +const createStreamRequest = ( + baseUrl: string, + clientOptions: RequestFactoryOptions, +) => { + return async ( + path: string, + options: StreamRequestOptions = {}, + ): Promise => { + const url = buildUrl(baseUrl, path, options); + appendQuery(url, options.query); + const headers = buildHeaders( + clientOptions.defaultHeaders, + clientOptions.getToken, + options.headers, + ); + const body = buildBody(options, headers); + const controller = new AbortController(); + const timeoutMs = options.timeoutMs ?? clientOptions.defaultTimeoutMs; + const idleTimeoutMs = options.idleTimeoutMs ?? clientOptions.defaultTimeoutMs; + if ( + !Number.isFinite(timeoutMs) || timeoutMs < 0 || + !Number.isFinite(idleTimeoutMs) || idleTimeoutMs < 0 + ) { + throw new RangeError("Stream timeouts must be finite non-negative numbers."); + } + let timedOut = false; + let timer: ReturnType | undefined; + const clearTimer = () => clearTimeout(timer); + const armTimer = (duration: number) => { + clearTimer(); + if (duration > 0) { + timer = setTimeout(() => { + timedOut = true; + controller.abort(); + }, duration); + } + }; + const abort = () => controller.abort(); + options.signal?.addEventListener("abort", abort, { once: true }); + if (options.signal?.aborted) { + abort(); + } + const cleanup = () => { + clearTimer(); + options.signal?.removeEventListener("abort", abort); + }; + const failure = (error: unknown): never => { + if (error instanceof HttpError) { + throw error; + } + if (controller.signal.aborted && !timedOut) { + throw new DOMException("The stream request was cancelled.", "AbortError"); + } + const status = timedOut + ? 408 + : extractErrorCode(error) === "ECONNREFUSED" ? 503 : 0; + const message = timedOut + ? "스트림 요청 시간이 초과되었습니다." + : status === 503 ? "백엔드 서버에 연결할 수 없습니다." + : "스트림을 수신하지 못했습니다."; + return processHttpError( + new HttpError(status, { message }, url.toString()), + options, + clientOptions, + ); + }; + const isServer = typeof window === "undefined"; + const init: NextRequestInit = { + method: options.method ?? (body === undefined ? "GET" : "POST"), + headers, + signal: controller.signal, + cache: options.cache ?? (isServer && options.next ? "force-cache" : "no-store"), + }; + if (body !== undefined) { + init.body = body; + } + if (isServer && options.next !== undefined) { + init.next = options.next; + } + armTimer(timeoutMs); + try { + const response = await fetch(url.toString(), init); + if (!response.ok) { + const rawText = await response.text(); + processErrorResponse( + response, + parseErrorBody(rawText, response.headers.get("content-type") ?? ""), + url, + options, + clientOptions, + ); + } + clearTimer(); + const metadata = { + status: response.status, + statusText: response.statusText, + headers: response.headers, + url: response.url || url.toString(), + }; + if (!response.body) { + cleanup(); + return { ...metadata, body: null }; + } + const reader = response.body.getReader(); + let finished = false; + let streamController: ReadableStreamDefaultController; + const finish = () => { + finished = true; + cleanup(); + controller.signal.removeEventListener("abort", onAbort); + }; + const cancelReader = async () => { + try { + await reader.cancel(); + } catch { + // Cancellation must not replace the original error. + } finally { + reader.releaseLock(); + } + }; + const onAbort = () => { + if (finished) { + return; + } + finish(); + try { + failure(new DOMException("The stream was aborted.", "AbortError")); + } catch (error) { + streamController.error(error); + } + void cancelReader(); + }; + const stream = new ReadableStream({ + start(currentController) { + streamController = currentController; + controller.signal.addEventListener("abort", onAbort, { once: true }); + if (controller.signal.aborted) { + onAbort(); + } else { + armTimer(idleTimeoutMs); + } + }, + async pull(currentController) { + try { + const chunk = await reader.read(); + if (finished) { + return; + } + if (chunk.done) { + finish(); + reader.releaseLock(); + currentController.close(); + } else { + armTimer(idleTimeoutMs); + currentController.enqueue(chunk.value); + } + } catch (error) { + if (finished) { + return; + } + finish(); + try { + failure(error); + } catch (streamError) { + currentController.error(streamError); + } + await cancelReader(); + } + }, + async cancel() { + if (!finished) { + finish(); + controller.abort(); + await cancelReader(); + } + }, + }, { highWaterMark: 0 }); + return { ...metadata, body: stream }; + } catch (error) { + cleanup(); + return failure(error); + } + }; +}; + export const createHttpClient = ( baseUrl: string, options: HttpClientOptions = {}, ) => { - const request = createRequest(baseUrl, createResolvedOptions(options)); + const resolvedOptions = createResolvedOptions(options); + const request = createRequest(baseUrl, resolvedOptions); + const streamRequest = createStreamRequest(baseUrl, resolvedOptions); const get = ( path: string, @@ -763,7 +973,45 @@ export const createHttpClient = ( }); }; + const streamGet = ( + path: string, + requestOptions?: StreamOptionsWithoutBody, + ): Promise => + streamRequest(path, { ...requestOptions, method: "GET" }); + + const streamPost = ( + path: string, + json?: unknown, + requestOptions?: StreamOptionsWithoutBody, + ): Promise => + streamRequest(path, { ...requestOptions, method: "POST", json }); + + const streamPut = ( + path: string, + json?: unknown, + requestOptions?: StreamOptionsWithoutBody, + ): Promise => + streamRequest(path, { ...requestOptions, method: "PUT", json }); + + const streamPatch = ( + path: string, + json?: unknown, + requestOptions?: StreamOptionsWithoutBody, + ): Promise => + streamRequest(path, { ...requestOptions, method: "PATCH", json }); + + const streamDel = ( + path: string, + requestOptions?: StreamDeleteOptions, + ): Promise => + streamRequest(path, { ...requestOptions, method: "DELETE" }); + return { + streamGet, + streamPost, + streamPut, + streamPatch, + streamDel, request, get, post,