|
1 | 1 | import { Agent, setGlobalDispatcher } from "undici"; |
| 2 | +import { readBoundedResponseText as readBoundedResponseTextWithLimit } from "./lib/bounded-response-text.mjs"; |
2 | 3 | |
3 | 4 | const baseUrl = process.env.OPENWEBUI_BASE_URL ?? ""; |
4 | 5 | const email = process.env.OPENWEBUI_ADMIN_EMAIL ?? ""; |
@@ -69,12 +70,6 @@ function createTimeoutError(label, timeoutMs) {
|
69 | 70 | return error; |
70 | 71 | } |
71 | 72 | |
72 | | -function createBodyTooLargeError(label, byteLimit) { |
73 | | -const error = new Error(`${label} response body exceeded ${byteLimit} bytes`); |
74 | | -error.code = "ETOOBIG"; |
75 | | -return error; |
76 | | -} |
77 | | - |
78 | 73 | async function withRequestTimeout(label, timeoutMs, run) { |
79 | 74 | const controller = new AbortController(); |
80 | 75 | const timeoutError = createTimeoutError(label, timeoutMs); |
@@ -95,38 +90,7 @@ async function withRequestTimeout(label, timeoutMs, run) {
|
95 | 90 | } |
96 | 91 | |
97 | 92 | async function readBoundedResponseText(response, label, byteLimit = responseBodyMaxBytes) { |
98 | | -const contentLength = response.headers.get("content-length"); |
99 | | -if (contentLength) { |
100 | | -const parsedLength = Number(contentLength); |
101 | | -if (Number.isSafeInteger(parsedLength) && parsedLength > byteLimit) { |
102 | | -await response.body?.cancel().catch(() => {}); |
103 | | -throw createBodyTooLargeError(label, byteLimit); |
104 | | -} |
105 | | -} |
106 | | -if (!response.body) { |
107 | | -return ""; |
108 | | -} |
109 | | - |
110 | | -const reader = response.body.getReader(); |
111 | | -const decoder = new TextDecoder(); |
112 | | -let byteCount = 0; |
113 | | -let text = ""; |
114 | | -try { |
115 | | -while (true) { |
116 | | -const { done, value } = await reader.read(); |
117 | | -if (done) { |
118 | | -return text + decoder.decode(); |
119 | | -} |
120 | | -byteCount += value.byteLength; |
121 | | -if (byteCount > byteLimit) { |
122 | | -await reader.cancel().catch(() => {}); |
123 | | -throw createBodyTooLargeError(label, byteLimit); |
124 | | -} |
125 | | -text += decoder.decode(value, { stream: true }); |
126 | | -} |
127 | | -} finally { |
128 | | -reader.releaseLock(); |
129 | | -} |
| 93 | +return await readBoundedResponseTextWithLimit(response, label, byteLimit); |
130 | 94 | } |
131 | 95 | |
132 | 96 | async function readBoundedResponseJson(response, label) { |
|