261013_01_ENH: http stream 통신 추가
This commit is contained in:
@@ -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` |
|
| 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.
|
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.
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@kri/common",
|
"name": "@kri/common",
|
||||||
"version": "0.19.0",
|
"version": "0.19.1",
|
||||||
"description": "KRI 프런트엔드 공통 유틸리티",
|
"description": "KRI 프런트엔드 공통 유틸리티",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.js",
|
"main": "./dist/index.js",
|
||||||
|
|||||||
@@ -193,6 +193,29 @@ export type RequestOptionsWithoutBody = Omit<
|
|||||||
|
|
||||||
export type DeleteRequestOptions = Omit<RequestOptions, "method">;
|
export type DeleteRequestOptions = Omit<RequestOptions, "method">;
|
||||||
|
|
||||||
|
export type StreamRequestOptions = Omit<
|
||||||
|
RequestOptions,
|
||||||
|
"expectText" | "expectBinary"
|
||||||
|
> & {
|
||||||
|
signal?: AbortSignal;
|
||||||
|
/** 응답 수신 중 무응답 제한. 기본 60초, 0은 제한 없음. */
|
||||||
|
idleTimeoutMs?: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type StreamOptionsWithoutBody = Omit<
|
||||||
|
StreamRequestOptions,
|
||||||
|
RequestOptionBodyKeys
|
||||||
|
>;
|
||||||
|
export type StreamDeleteOptions = Omit<StreamRequestOptions, "method">;
|
||||||
|
|
||||||
|
export type HttpStreamResponse = {
|
||||||
|
status: number;
|
||||||
|
statusText: string;
|
||||||
|
headers: Headers;
|
||||||
|
url: string;
|
||||||
|
body: ReadableStream<Uint8Array> | null;
|
||||||
|
};
|
||||||
|
|
||||||
const replacePathParams = (path: string, params?: PathParams): string => {
|
const replacePathParams = (path: string, params?: PathParams): string => {
|
||||||
if (!params) {
|
if (!params) {
|
||||||
return path;
|
return path;
|
||||||
@@ -665,11 +688,198 @@ const createRequest = (
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const createStreamRequest = (
|
||||||
|
baseUrl: string,
|
||||||
|
clientOptions: RequestFactoryOptions,
|
||||||
|
) => {
|
||||||
|
return async (
|
||||||
|
path: string,
|
||||||
|
options: StreamRequestOptions = {},
|
||||||
|
): Promise<HttpStreamResponse> => {
|
||||||
|
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<typeof setTimeout> | 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<Uint8Array>;
|
||||||
|
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<Uint8Array>({
|
||||||
|
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 = (
|
export const createHttpClient = (
|
||||||
baseUrl: string,
|
baseUrl: string,
|
||||||
options: HttpClientOptions = {},
|
options: HttpClientOptions = {},
|
||||||
) => {
|
) => {
|
||||||
const request = createRequest(baseUrl, createResolvedOptions(options));
|
const resolvedOptions = createResolvedOptions(options);
|
||||||
|
const request = createRequest(baseUrl, resolvedOptions);
|
||||||
|
const streamRequest = createStreamRequest(baseUrl, resolvedOptions);
|
||||||
|
|
||||||
const get = <T = unknown>(
|
const get = <T = unknown>(
|
||||||
path: string,
|
path: string,
|
||||||
@@ -763,7 +973,45 @@ export const createHttpClient = (
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const streamGet = (
|
||||||
|
path: string,
|
||||||
|
requestOptions?: StreamOptionsWithoutBody,
|
||||||
|
): Promise<HttpStreamResponse> =>
|
||||||
|
streamRequest(path, { ...requestOptions, method: "GET" });
|
||||||
|
|
||||||
|
const streamPost = (
|
||||||
|
path: string,
|
||||||
|
json?: unknown,
|
||||||
|
requestOptions?: StreamOptionsWithoutBody,
|
||||||
|
): Promise<HttpStreamResponse> =>
|
||||||
|
streamRequest(path, { ...requestOptions, method: "POST", json });
|
||||||
|
|
||||||
|
const streamPut = (
|
||||||
|
path: string,
|
||||||
|
json?: unknown,
|
||||||
|
requestOptions?: StreamOptionsWithoutBody,
|
||||||
|
): Promise<HttpStreamResponse> =>
|
||||||
|
streamRequest(path, { ...requestOptions, method: "PUT", json });
|
||||||
|
|
||||||
|
const streamPatch = (
|
||||||
|
path: string,
|
||||||
|
json?: unknown,
|
||||||
|
requestOptions?: StreamOptionsWithoutBody,
|
||||||
|
): Promise<HttpStreamResponse> =>
|
||||||
|
streamRequest(path, { ...requestOptions, method: "PATCH", json });
|
||||||
|
|
||||||
|
const streamDel = (
|
||||||
|
path: string,
|
||||||
|
requestOptions?: StreamDeleteOptions,
|
||||||
|
): Promise<HttpStreamResponse> =>
|
||||||
|
streamRequest(path, { ...requestOptions, method: "DELETE" });
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
streamGet,
|
||||||
|
streamPost,
|
||||||
|
streamPut,
|
||||||
|
streamPatch,
|
||||||
|
streamDel,
|
||||||
request,
|
request,
|
||||||
get,
|
get,
|
||||||
post,
|
post,
|
||||||
|
|||||||
Reference in New Issue
Block a user