llm-large-files 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,21 @@ export type DocumentHandlerOptions = {
21
21
  * the upload is read, so a refused upload is not buffered.
22
22
  */
23
23
  getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
24
+ /**
25
+ * The most bytes of uploads these handlers hold at once: an upload is held whole in memory from
26
+ * the moment its body is read until its ingest ends. An upload that would pass it is answered 503
27
+ * with `Retry-After` before its body is read, while another upload is held: one upload alone is
28
+ * always taken. An upload counts its `Content-Length` (or `maxUploadBytes` without one, then its
29
+ * size once read). `Infinity` for no limit (as before 0.8.2). Defaults to twice `maxUploadBytes`.
30
+ * New in 0.8.2.
31
+ */
32
+ maxPendingUploadBytes?: number;
33
+ /**
34
+ * An upload whose body stops arriving for this many milliseconds is answered 408, its connection
35
+ * closed and its room given back: a client that sends its headers and then nothing, or stalls,
36
+ * holds its room no longer. 0 or `Infinity` for no limit. Defaults to 30,000. New in 0.8.2.
37
+ */
38
+ uploadIdleTimeoutMs?: number;
24
39
  };
25
40
 
26
41
  /**
@@ -48,7 +63,8 @@ export type DocumentHandlers = {
48
63
  };
49
64
 
50
65
  class HttpError extends Error {
51
- constructor(readonly status: number, message: string) {
66
+ /** `close`: answer, then close the connection, without waiting for the rest of the body. */
67
+ constructor(readonly status: number, message: string, readonly close = false) {
52
68
  super(message);
53
69
  }
54
70
  }
@@ -164,6 +180,9 @@ async function streamIngest(files: LargeFiles, input: IngestInput, response: Ser
164
180
  // Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
165
181
  // answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
166
182
  await writeSseEvents(response, events());
183
+ // A client that went away ends the stream at once, while the ingest stops (a store write may still
184
+ // be under way): the upload is held until then, as on the JSON path.
185
+ await stream.result.catch(() => undefined);
167
186
  }
168
187
 
169
188
  /**
@@ -192,8 +211,33 @@ function header(request: IncomingMessage, name: string): string {
192
211
  }
193
212
  }
194
213
 
195
- /** Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()). */
196
- async function readBody(request: IncomingMessage, limit: number): Promise<Uint8Array> {
214
+ /** The longest a timer can wait. */
215
+ const LONGEST_TIMER_MS = 2_147_483_647;
216
+
217
+ /** `next`, or a 408 once `idleMs` pass without it. */
218
+ function withinIdle<T>(next: Promise<T>, idleMs: number): Promise<T> {
219
+ // Once the upload is refused, the read it waited on ends with the connection: nobody awaits it.
220
+ next.catch(() => undefined);
221
+ let settled = false;
222
+ let timer: ReturnType<typeof setTimeout> | undefined;
223
+ const idle = new Promise<never>((_, reject) => {
224
+ const after = idleMs >= 1_000 ? `${Math.round(idleMs / 1_000)} s` : `${idleMs} ms`;
225
+ timer = setTimeout(() => {
226
+ // After the thread was held longer than `idleMs`, timers run before the data that came in the
227
+ // meantime is read: it is read first, in this turn of the loop, and the upload goes on.
228
+ setImmediate(() => {
229
+ if (!settled) reject(new HttpError(408, `The upload stopped arriving: nothing came for ${after}. Send it again.`, true));
230
+ });
231
+ }, idleMs);
232
+ });
233
+ return Promise.race([next.finally(() => (settled = true)), idle]).finally(() => clearTimeout(timer));
234
+ }
235
+
236
+ /**
237
+ * Reads the raw body, or uses one a framework already parsed into a Buffer (e.g. express.raw()).
238
+ * `idleMs`: the longest wait for the next piece of the body (0 for no limit).
239
+ */
240
+ async function readBody(request: IncomingMessage, limit: number, idleMs = 0): Promise<Uint8Array> {
197
241
  const parsed = (request as IncomingMessage & { body?: unknown }).body;
198
242
  if (parsed instanceof Uint8Array) {
199
243
  if (parsed.byteLength > limit) throw new HttpError(413, "");
@@ -208,16 +252,60 @@ async function readBody(request: IncomingMessage, limit: number): Promise<Uint8A
208
252
  let size = 0;
209
253
  // Leaving the loop early must not destroy the request: the rest of the body is drained after
210
254
  // the answer (see `drain`), which a destroyed request would not do.
211
- for await (const chunk of request.iterator({ destroyOnReturn: false })) {
212
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
213
- size += buffer.byteLength;
214
- if (size > limit) throw new HttpError(413, "");
215
- chunks.push(buffer);
255
+ const pieces = request.iterator({ destroyOnReturn: false });
256
+ const timed = idleMs > 0 && idleMs <= LONGEST_TIMER_MS;
257
+ try {
258
+ for (;;) {
259
+ const next = pieces.next();
260
+ const { done, value: chunk } = timed ? await withinIdle(next, idleMs) : await next;
261
+ if (done) break;
262
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
263
+ size += buffer.byteLength;
264
+ if (size > limit) throw new HttpError(413, "");
265
+ chunks.push(buffer);
266
+ }
267
+ } finally {
268
+ // As a `for await` does on leaving early; the request is not destroyed (see above).
269
+ void pieces.return?.().catch(() => undefined);
216
270
  }
217
271
  const body = Buffer.concat(chunks);
218
272
  return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
219
273
  }
220
274
 
275
+ const BUSY = "The server is receiving other files right now. Try again in a moment.";
276
+ /** When a client refused for `maxPendingUploadBytes` is told to try again. */
277
+ const BUSY_RETRY_MS = 5_000;
278
+
279
+ /** `uploadIdleTimeoutMs`, checked: a number of 0 or more (0 and Infinity for no limit). */
280
+ function idleLimit(value: unknown): number {
281
+ if (value === undefined) return 30_000;
282
+ if (typeof value !== "number" || Number.isNaN(value) || value < 0) {
283
+ throw new RangeError(`uploadIdleTimeoutMs must be a number of 0 or more, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
284
+ }
285
+ return value;
286
+ }
287
+
288
+ /** `maxPendingUploadBytes`, checked: a number above 0 (Infinity for no limit). */
289
+ function pendingLimit(value: unknown, maxUploadBytes: number): number {
290
+ if (value === undefined) return 2 * maxUploadBytes;
291
+ if (typeof value !== "number" || Number.isNaN(value) || value <= 0) {
292
+ throw new RangeError(`maxPendingUploadBytes must be a number above 0, and is ${typeof value === "number" ? value : typeof value}. Leave it out for the default.`);
293
+ }
294
+ return value;
295
+ }
296
+
297
+ /**
298
+ * The bytes an upload will hold: a body a framework already read, its declared `Content-Length`,
299
+ * or the upload limit when it declares none. Never more than the limit: a larger one is refused
300
+ * when it is read (413).
301
+ */
302
+ function expectedSize(request: IncomingMessage, limit: number): number {
303
+ const parsed = (request as IncomingMessage & { body?: unknown }).body;
304
+ if (parsed instanceof Uint8Array) return Math.min(parsed.byteLength, limit);
305
+ const declared = Number(request.headers["content-length"]);
306
+ return Number.isFinite(declared) && declared >= 0 ? Math.min(declared, limit) : limit;
307
+ }
308
+
221
309
  /**
222
310
  * The most bytes of an upload's body that are read and dropped after it was answered before the
223
311
  * body was read to its end (too large, no name). Past it the connection is closed.
@@ -262,6 +350,17 @@ function drain(request: IncomingMessage, response: ServerResponse): void {
262
350
  export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
263
351
  const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
264
352
  const owner = async (request: IncomingMessage) => options.getOwner?.(request);
353
+ // The upload limit bounds each body, and the room for all of them: a LargeFiles of your own
354
+ // without it (from JavaScript) had neither.
355
+ if (typeof files.maxUploadBytes !== "number" || !(files.maxUploadBytes > 0)) {
356
+ throw new TypeError(`createDocumentHandlers needs files.maxUploadBytes, a number above 0, and it is ${String(files.maxUploadBytes)}. A LargeFiles of your own must keep the one of the library it wraps.`);
357
+ }
358
+ const maxPending = pendingLimit(options.maxPendingUploadBytes, files.maxUploadBytes);
359
+ const idleMs = idleLimit(options.uploadIdleTimeoutMs);
360
+ /** Whether uploads are counted at all (`maxPendingUploadBytes` is not Infinity). */
361
+ const counted = maxPending !== Number.POSITIVE_INFINITY;
362
+ /** The bytes of the uploads held now, from the reading of their body to the end of their ingest. */
363
+ let pending = 0;
265
364
 
266
365
  return {
267
366
  async upload(request, response) {
@@ -280,34 +379,62 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
280
379
  const empty = typeof currentOwner === "string" || currentOwner === null;
281
380
  throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
282
381
  }
283
- const bytes = await readBody(request, files.maxUploadBytes);
284
- const contentType = header(request, "content-type");
285
- const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
286
- // A client that goes away before the answer stops the reading of its file: nobody would
287
- // get the document, and the server has other work.
288
- const gone = new AbortController();
289
- const onClose = () => {
290
- if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
291
- };
292
- response.once("close", onClose);
293
- const input: IngestInput = {
294
- name,
295
- bytes,
296
- ...(mimeType ? { mimeType } : {}),
297
- ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
298
- signal: gone.signal,
299
- };
300
- let meta;
382
+ // Too large is said first, before any wait for room.
383
+ const declared = Number(request.headers["content-length"]);
384
+ const parsed = (request as IncomingMessage & { body?: unknown }).body;
385
+ if ((Number.isFinite(declared) && declared > files.maxUploadBytes) || (parsed instanceof Uint8Array && parsed.byteLength > files.maxUploadBytes)) {
386
+ throw new HttpError(413, "");
387
+ }
388
+ // Room for the upload, before its body is read: a refused upload is not buffered. Never
389
+ // more than the room itself, so that the count stays a number with an upload limit of Infinity.
390
+ let held = counted ? Math.min(expectedSize(request, files.maxUploadBytes), maxPending) : 0;
391
+ if (pending > 0 && pending + held > maxPending) throw new IngestError("busy", BUSY, { retryAfterMs: BUSY_RETRY_MS });
392
+ pending += held;
301
393
  try {
302
- if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
303
- meta = await files.ingest(input);
304
- } catch (error) {
305
- throw ingestFailure(error);
394
+ const bytes = await readBody(request, files.maxUploadBytes, idleMs);
395
+ // Counted at its size once read (an upload without a Content-Length was counted at the limit).
396
+ if (counted) {
397
+ pending += bytes.byteLength - held;
398
+ held = bytes.byteLength;
399
+ }
400
+ const contentType = header(request, "content-type");
401
+ const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
402
+ // A client that goes away before the answer stops the reading of its file: nobody would
403
+ // get the document, and the server has other work.
404
+ const gone = new AbortController();
405
+ const onClose = () => {
406
+ if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
407
+ };
408
+ response.once("close", onClose);
409
+ const input: IngestInput = {
410
+ name,
411
+ bytes,
412
+ ...(mimeType ? { mimeType } : {}),
413
+ ...(currentOwner !== undefined ? { owner: currentOwner } : {}),
414
+ signal: gone.signal,
415
+ };
416
+ let meta;
417
+ try {
418
+ if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
419
+ meta = await files.ingest(input);
420
+ } catch (error) {
421
+ throw ingestFailure(error);
422
+ } finally {
423
+ response.off("close", onClose);
424
+ }
425
+ send(response, 201, toDocumentSummary(meta));
306
426
  } finally {
307
- response.off("close", onClose);
427
+ pending -= held;
308
428
  }
309
- send(response, 201, toDocumentSummary(meta));
310
429
  } catch (error) {
430
+ // A body that stopped arriving is not drained: the answer ends, and so does the connection.
431
+ if (error instanceof HttpError && error.close) {
432
+ if (!response.headersSent) response.setHeader("Connection", "close");
433
+ send(response, error.status, { error: error.message });
434
+ if (response.writableFinished) request.destroy();
435
+ else response.once("finish", () => request.destroy());
436
+ return;
437
+ }
311
438
  // Answered before the body was read to its end (too large, no name): the rest is drained.
312
439
  fail(response, error, "Upload failed", tooLarge, request);
313
440
  // An event stream that failed after its headers were sent cannot answer with a status. (An
package/src/ranged.ts CHANGED
@@ -48,7 +48,14 @@ const YIELD_AFTER_MS = 15;
48
48
  // starts at a line, so a line that began with one lost it, and its piece no longer matched the index.
49
49
  const decoder = new TextDecoder("utf-8", { ignoreBOM: true });
50
50
 
51
- const gone = (id: string) => new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
51
+ /**
52
+ * The text of a document is gone from the store while its metadata is still there (removed by hand,
53
+ * or by a cleanup outside the library). Told apart from other read errors, so that a question can
54
+ * report the document as missing.
55
+ */
56
+ export class DocumentGoneError extends Error {}
57
+
58
+ const gone = (id: string) => new DocumentGoneError(`${id} is no longer available on the server. Ask the user to attach the file again.`);
52
59
 
53
60
  /** A scan of a document: fed the pieces in order until it says it is done. */
54
61
  type Consumer = { feed: ScanFeed; done: boolean; settle: (error?: unknown) => void };