261013_01_ENH: http stream 통신 추가

This commit is contained in:
2026-10-13 15:04:38 +09:00
parent 25e0d36d8b
commit 28ef14c90e
3 changed files with 259 additions and 2 deletions

View File

@@ -193,6 +193,29 @@ export type RequestOptionsWithoutBody = Omit<
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 => {
if (!params) {
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 = (
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 = <T = unknown>(
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 {
streamGet,
streamPost,
streamPut,
streamPatch,
streamDel,
request,
get,
post,