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.
- package/CHANGELOG.md +96 -0
- package/dist/library.d.ts +7 -0
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +103 -16
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -2
- package/dist/limiter.js +2 -2
- package/dist/node/handlers.d.ts +15 -0
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +155 -36
- package/dist/node/handlers.js.map +1 -1
- package/dist/ranged.d.ts +7 -0
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +8 -1
- package/dist/ranged.js.map +1 -1
- package/docs/guides/deployment.md +27 -6
- package/docs/guides/storage.md +5 -2
- package/docs/guides/web-app.md +14 -3
- package/docs/measurements.md +20 -0
- package/docs/reference/library.md +5 -2
- package/docs/reference/node.md +29 -14
- package/docs/security.md +15 -6
- package/docs/troubleshooting.md +28 -0
- package/package.json +1 -1
- package/src/library.ts +107 -14
- package/src/limiter.ts +2 -2
- package/src/node/handlers.ts +159 -32
- package/src/ranged.ts +8 -1
|
@@ -107,6 +107,7 @@ type LargeFilesOptions = {
|
|
|
107
107
|
wholeDocumentBytes?: number;
|
|
108
108
|
scanChunkBytes?: number;
|
|
109
109
|
maxConcurrentScans?: number;
|
|
110
|
+
maxConcurrentIngests?: number;
|
|
110
111
|
now?: () => Date;
|
|
111
112
|
};
|
|
112
113
|
```
|
|
@@ -119,7 +120,7 @@ type LargeFilesOptions = {
|
|
|
119
120
|
| `maxUploadBytes` | `number` | 100 MB (104,857,600) | The largest file `ingest` accepts. The upload handler of [`llm-large-files/node`](./node.md) reads no more than this. |
|
|
120
121
|
| `maxTextBytes` | `number` | [`DEFAULT_MAX_TEXT_BYTES`](#default_max_text_bytes), 100 MB, or `maxUploadBytes` when that is larger | The most text kept from one file, in UTF-8 bytes. A file's text can be larger than the file: a PDF of 3 KB built for it drew 107 MB. The PDF, DOCX, PPTX and XLSX extractors refuse a file as soon as its text passes this (a PDF page by page, and also past 100 times its size after the first 16 MB; an Office file also past 32 million characters, whatever this allows), and `ingest` refuses a larger text from any other extractor, the text extractor and yours included. Your extractor receives it as `ExtractInput.maxTextBytes`. At least 1. |
|
|
121
122
|
| `maxPdfPages` | `number` | [`DEFAULT_MAX_PDF_PAGES`](#default_max_pdf_pages), 5,000 | The most pages read from one PDF. A PDF with more is refused before any page is read. Your PDF extractor receives it as `ExtractInput.maxPages`. At least 1. |
|
|
122
|
-
| `ingestTimeoutMs` | `number` | [`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms), 120,000 (2 minutes) | The most time one `ingest` may take to extract the text, build its line index and profile it, in milliseconds. The store's writes are not counted. Past it, `ingest` throws `<name> took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`, and stores nothing. 0 sets no limit, and so does a value past what a timer can wait (2,147,483,647 ms, 24.8 days). Your extractor receives the limit as `ExtractInput.signal`. Within one page of a PDF the limit is not looked at: see [security](../security.md#uploads). |
|
|
123
|
+
| `ingestTimeoutMs` | `number` | [`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms), 120,000 (2 minutes) | The most time one `ingest` may take to extract the text, build its line index and profile it, in milliseconds. The store's writes are not counted, but a store write that does not end within this time (2 minutes when it is 0) fails the ingest with `The store did not finish writing <name> within 2 min.`, as a failure of the store, and the document is removed once the write ends (new in 0.8.2). Past it, `ingest` throws `<name> took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`, and stores nothing. 0 sets no limit, and so does a value past what a timer can wait (2,147,483,647 ms, 24.8 days). Your extractor receives the limit as `ExtractInput.signal`. Within one page of a PDF the limit is not looked at: see [security](../security.md#uploads). |
|
|
123
124
|
| `extractors` | `Partial<Record<DocumentFormat, Extractor>>` | the built-ins, [`defaultExtractors`](#defaultextractors) | An [`Extractor`](#extractor) per format, used in place of the built-in one. The formats are fixed ([`DocumentFormat`](#documentformat)): you can replace the extractor of a format, not add a format. |
|
|
124
125
|
| `keepOriginals` | `DocumentFormat[]` | `[]` | Formats whose uploaded file is kept in the store next to its text, for example `["pdf"]`, which `view_pages` needs. Takes effect only with a store that has `putOriginal`. A kept file takes as much space as the upload until its document expires or is deleted. |
|
|
125
126
|
| `scannedPdfPages` | `number` | 30 | The most pages a PDF without any text (a scan) may have and still be accepted, so that its pages can be shown to the model. It applies only when `"pdf"` is in `keepOriginals` and the store has `putOriginal`. Otherwise, and with 0, such a PDF is refused. Your own PDF extractor receives it as `ExtractInput.scannedPages`. |
|
|
@@ -128,10 +129,12 @@ type LargeFilesOptions = {
|
|
|
128
129
|
| `wholeDocumentBytes` | `number` | [`DEFAULT_WHOLE_DOCUMENT_BYTES`](#default_whole_document_bytes), 2 MB | Documents whose text (`textBytes`) is at most this size are loaded whole into memory. Larger ones are read by range when the store has `readTextRange`, as `FileDocumentStore` does: a tool call reads only the lines it needs, and a search reads the text a piece at a time. `Infinity` loads every document whole; 0 reads every one by range. |
|
|
129
130
|
| `scanChunkBytes` | `number` | 1 MB (1,048,576) | Reading by range: about how many bytes of text are read and searched at a time. At least 1. |
|
|
130
131
|
| `maxConcurrentScans` | `number` | 4 | Reading by range: how many scans of whole documents (searches, counting the parts of a file) run at once in this library (each `createLargeFiles` call has its own queue). The others wait their turn. At least 1. |
|
|
132
|
+
| `maxConcurrentIngests` | `number` | 2 | How many ingests do their work at once in this library. The others wait their turn, in the order they came; their `ingestTimeoutMs` starts when their turn comes, and a caller that aborts its `signal` while it waits gets its own reason, with nothing stored. An empty file, or one over `maxUploadBytes`, is refused without waiting. An ingest holds about five times its file in memory while it works, and the steps it runs in your server's thread share that thread with the others: more of them at once do not finish sooner (100 logs of 2 MB: all answered in 28 to 42 s all at once, 28 to 33 s two at a time, with a peak of 817 to 830 MB of memory against 329 to 356 MB). An ingest keeps its turn until its work ends: when its time is up or its caller left while an extractor goes on (one that does not stop on the signal, such as the parse of a PDF by `@cantoo/pdf-lib`), until that extractor ends; such an extractor that never ends gives the turn back after `ingestTimeoutMs` more (2 minutes when that is 0), and a store write that never ends fails the ingest after `ingestTimeoutMs` (above). An extractor of your own must not wait on an ingest of the same library (to store the parts of an archive, say): that ingest waits for a turn like any other, and with every turn held by such extractors, each waits on itself until its time is up. With [`createIsolatedExtractors`](./node.md#createisolatedextractorsoptions), at most this many files reach its readers at once from this library. `Infinity` for no limit, as before 0.8.2. At least 1. New in 0.8.2. |
|
|
131
133
|
| `now` | `() => Date` | `() => new Date()` | The clock, for tests. It dates `createdAt` and `expiresAt`, decides whether a document has expired, and is passed to the store's `sweep`. |
|
|
132
134
|
|
|
133
135
|
Since 0.7.1, `ttlMs`, `maxUploadBytes`, `scannedPdfPages`, `cacheBytes`, `cacheSize`,
|
|
134
|
-
`wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans`
|
|
136
|
+
`wholeDocumentBytes`, `scanChunkBytes` and `maxConcurrentScans` (and `maxConcurrentIngests`, new in
|
|
137
|
+
0.8.2) are checked when the library is
|
|
135
138
|
made: NaN, which `Number(process.env.X)` gives for a variable that is not set, throws a
|
|
136
139
|
`RangeError` ("maxConcurrentScans must be a number, and is NaN. Leave it out for the default."),
|
|
137
140
|
a value that is not a number throws a `TypeError`, and so does `Infinity` for `scanChunkBytes`. NaN
|
package/docs/reference/node.md
CHANGED
|
@@ -50,10 +50,12 @@ included, and never rejects, so it can be called without a `catch`.
|
|
|
50
50
|
| Parameter | Type | Default | What it does |
|
|
51
51
|
|---|---|---|---|
|
|
52
52
|
| `files` | [`LargeFiles`](./library.md#largefiles) | required | The library that uploads are ingested into and documents are looked up in. Its `maxUploadBytes` ([`LargeFilesOptions`](./library.md#largefilesoptions), 100 MB by default) is the upload limit. |
|
|
53
|
-
| `options` | [`DocumentHandlerOptions`](#documenthandleroptions) | `{}` | Who owns a request. |
|
|
53
|
+
| `options` | [`DocumentHandlerOptions`](#documenthandleroptions) | `{}` | Who owns a request, how many bytes of uploads are held at once, and how long a body may stop arriving. |
|
|
54
54
|
|
|
55
|
-
**Returns** the three [`DocumentHandlers`](#documenthandlers). It makes no request
|
|
56
|
-
store
|
|
55
|
+
**Returns** the three [`DocumentHandlers`](#documenthandlers). It makes no request and reads no
|
|
56
|
+
store. It throws a `RangeError` for a `maxPendingUploadBytes` or `uploadIdleTimeoutMs` that is not
|
|
57
|
+
a number in range, and a `TypeError` when `files` has no `maxUploadBytes` above 0 (a `LargeFiles`
|
|
58
|
+
of your own, from JavaScript, must keep the one of the library it wraps; new in 0.8.2).
|
|
57
59
|
|
|
58
60
|
The handlers do not check the method or the path of a request: route each request to the one you
|
|
59
61
|
mean. Every response they write has the header `Content-Type: application/json; charset=utf-8`
|
|
@@ -94,6 +96,8 @@ upload route of your own for multipart forms or the Fetch API's `Request`.
|
|
|
94
96
|
```ts
|
|
95
97
|
type DocumentHandlerOptions = {
|
|
96
98
|
getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
|
|
99
|
+
maxPendingUploadBytes?: number;
|
|
100
|
+
uploadIdleTimeoutMs?: number;
|
|
97
101
|
};
|
|
98
102
|
```
|
|
99
103
|
|
|
@@ -102,6 +106,8 @@ The options of [`createDocumentHandlers()`](#createdocumenthandlersfiles-options
|
|
|
102
106
|
| Option | Type | Default | What it does |
|
|
103
107
|
|---|---|---|---|
|
|
104
108
|
| `getOwner` | `(request: IncomingMessage) => string \| undefined \| Promise<string \| undefined>` | none: every request is anonymous | The owner of this request, usually the signed-in user's ID. Called at most once per request. In `upload` it runs after the name is read and before the body: an upload without a name is answered `400` without calling it, and a refused upload is never buffered. An empty owner (`""`, or spaces only) is the server's mistake: the upload is answered `500` `{ "error": "Upload failed (empty owner)." }`, before its body is read. So is an owner from JavaScript that is neither a string nor a finite number (`req.user` in place of `req.user.id`, say): `{ "error": "Upload failed (owner is not a string)." }`. |
|
|
109
|
+
| `maxPendingUploadBytes` | `number` | twice `files.maxUploadBytes` (200 MB by default) | The most bytes of uploads these handlers hold at once. An upload is held whole in memory from the moment its body is read until its ingest ends (on the event-stream path too, also after its client went away). Its room is taken before its body is read: its `Content-Length`, or, when it declares none, `maxUploadBytes` (at most this limit) until the body is read, then its size. One that would bring the uploads held past the limit, while another is held, is answered `503` with `Retry-After: 5` before its body is read (the body is drained as for a `413`); one upload alone is always taken. A client that sends its headers and then nothing holds its room until `uploadIdleTimeoutMs` ends it. `Infinity` for no limit, as before 0.8.2. A value that is not a number above 0 throws a `RangeError` when the handlers are made. New in 0.8.2. |
|
|
110
|
+
| `uploadIdleTimeoutMs` | `number` | 30,000 | How long the body of an upload may stop arriving. Past it, the upload is answered `408` `{ "error": "The upload stopped arriving: nothing came for 30 s. Send it again." }` with `Connection: close`, the connection is closed, and the upload's room is given back. It bounds the wait for each piece of the body, not the whole upload: Node's `server.requestTimeout` (300 s by default) bounds that. 0 or `Infinity` for no limit. A value below 0 throws a `RangeError`. New in 0.8.2. |
|
|
105
111
|
|
|
106
112
|
What `getOwner` returns decides what each handler does:
|
|
107
113
|
|
|
@@ -170,12 +176,17 @@ What it does, in order:
|
|
|
170
176
|
2. Calls `getOwner`, and checks what it returned: `""`, spaces only or `null`, or from JavaScript
|
|
171
177
|
a value that is neither a string nor a finite number, is answered `500` (see
|
|
172
178
|
[`DocumentHandlerOptions`](#documenthandleroptions)).
|
|
173
|
-
3.
|
|
179
|
+
3. Makes room for the upload ([`maxPendingUploadBytes`](#documenthandleroptions)): a
|
|
180
|
+
`Content-Length`, or a body in `request.body`, over `maxUploadBytes` is answered `413` first; an
|
|
181
|
+
upload that would bring the uploads held past the limit, while others are held, is answered
|
|
182
|
+
`503`, before its body is read. New in 0.8.2.
|
|
183
|
+
4. Reads the body, up to `files.maxUploadBytes`:
|
|
174
184
|
- a `Uint8Array` or `Buffer` that a framework left in `request.body` (`express.raw()`) is used
|
|
175
185
|
as the file, with the same limit;
|
|
176
186
|
- an object with fields in `request.body` (`express.json()` on a JSON request) is answered
|
|
177
187
|
`400`;
|
|
178
|
-
- otherwise it reads the request stream
|
|
188
|
+
- otherwise it reads the request stream, waiting at most `uploadIdleTimeoutMs` (30 s) for each
|
|
189
|
+
piece; past that it answers `408` and closes the connection (new in 0.8.2). Past the limit it stops keeping the bytes, and
|
|
179
190
|
answers `413` at once. The rest of the body is then read and dropped, up to 8 MB, and the
|
|
180
191
|
answer ends when the body does: a client that is still sending reads the `413`, and can send
|
|
181
192
|
its next request on the same keep-alive connection. A body that goes on more than 8 MB past
|
|
@@ -188,11 +199,12 @@ What it does, in order:
|
|
|
188
199
|
client stuck sending into it. The answer to such a body has no `Content-Length`. A stream
|
|
189
200
|
that another middleware has already read gives no bytes, and the upload is answered `422` as
|
|
190
201
|
an empty file.
|
|
191
|
-
|
|
192
|
-
only when there are any. The
|
|
193
|
-
|
|
194
|
-
answer
|
|
195
|
-
|
|
202
|
+
5. Ingests it: `files.ingest({ name, bytes, mimeType, owner, signal })`, `mimeType` and `owner`
|
|
203
|
+
only when there are any. The ingest may first wait its turn (`maxConcurrentIngests` of
|
|
204
|
+
`createLargeFiles`, 2 by default). The `signal` aborts when the client closes the connection
|
|
205
|
+
before the answer is sent: the ingest stops between two pages or pieces (or leaves the queue),
|
|
206
|
+
and nothing is stored. The answer then goes to no one.
|
|
207
|
+
6. Answers `201` with the document's summary. With `Accept: text/event-stream`, steps 5 and 6 are
|
|
196
208
|
a stream of events instead ([below](#upload-with-progress-accept-textevent-stream)).
|
|
197
209
|
|
|
198
210
|
The responses:
|
|
@@ -204,13 +216,15 @@ The responses:
|
|
|
204
216
|
| `400` | `{ "error": "The upload body was already parsed by another middleware. Mount the upload route before body parsers, or send Content-Type: application/octet-stream." }` | `request.body` is an object with fields. |
|
|
205
217
|
| `413` | `{ "error": "The file is larger than the 100 MB upload limit." }`, with your `maxUploadBytes` in its place (`512 KB`, `1000 B`) | `Content-Length`, the bytes read, or the `Buffer` in `request.body` are over `maxUploadBytes`. |
|
|
206
218
|
| `422` | `{ "error": <the message of files.ingest> }` | The file cannot be read: `files.ingest` threw an [`IngestError`](./library.md#ingesterror), whose `status` is 422. The message says why and is meant for the user: "app.log is empty.", "app.log did not contain any text.", "This file looks binary, not text. Attach a text, log, PDF, Word, PowerPoint, Excel or HTML file.", "This file is gzip-compressed. Decompress it, then attach the text file inside.", "This file is a ZIP archive. Extract it, then attach the text file you need.", an Office file of before 2007 or with a password, a PDF with a password or with no text layer, and a PDF, DOCX, PPTX or XLSX while the optional dependency that reads it is missing ("Reading PDF files needs the optional dependency "unpdf".") or, for a PDF, cannot run on this Node ("The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.", see [defaultExtractors](./library.md#defaultextractors)). A text file is never refused for its encoding. A file past the limits of `createLargeFiles`: more text than `maxTextBytes`, more pages than `maxPdfPages`, longer to read than `ingestTimeoutMs` ("report.pdf took too long to read (more than 2 min). Split it, or save it as plain text, and attach that."), or built to exhaust the server ([every message](../guides/pdfs.md#what-is-refused)). With [`createIsolatedExtractors`](#createisolatedextractorsoptions), also a file whose reader ran out of memory or time. An extractor of your own that throws an `Error` gives its message here too. |
|
|
219
|
+
| `408` | `{ "error": "The upload stopped arriving: nothing came for 30 s. Send it again." }`, with `Connection: close` | The body stopped arriving for `uploadIdleTimeoutMs`. The connection is closed. New in 0.8.2. |
|
|
220
|
+
| `503` | `{ "error": "The server is receiving other files right now. Try again in a moment." }`, with `Retry-After: 5` | Uploads are already held, and this one would bring them past `maxPendingUploadBytes`. Answered before the body is read, also to a request with `Accept: text/event-stream`. New in 0.8.2. |
|
|
207
221
|
| `503` | `{ "error": "The server is reading other files right now. Try again in a moment." }`, with `Retry-After: 5` | The isolated readers of [`createIsolatedExtractors`](#createisolatedextractorsoptions) are all busy and their queue is full: an `IngestError` of code `"busy"`. The header is its `retryAfterMs` in seconds, rounded up, at least 1. While they shut down (`close()`): "The server is shutting down. Try again in a moment." New in 0.8.0. |
|
|
208
222
|
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner`, an extractor or the store threw an error with that `status` or `statusCode`. |
|
|
209
223
|
| `500` | `{ "error": "Upload failed (empty owner)." }` | `getOwner` returned `""`, spaces only or `null`. The body is not read. New in 0.6.0. |
|
|
210
224
|
| `500` | `{ "error": "Upload failed (owner is not a string)." }` | `getOwner` returned, from JavaScript, something that is neither a string nor a finite number: an object such as `req.user`, `true`, `NaN`, an array. The body is not read. New in 0.6.0. |
|
|
211
225
|
| `500` | `{ "error": "Upload failed (ENOSPC)." }` | The store failed with a Node system error, one with a `code` and a `syscall`. Only the code is passed on. |
|
|
212
226
|
| `500` | `{ "error": "Upload failed." }` | `getOwner` threw an error without a status, or the request body could not be read: the client went away, or a proxy cut the upload. Node's error for a client that went away has a `code` (`ECONNRESET`) but no `syscall`, so no code is added. An error of either kind that has a `code` and a `syscall` is answered as in the row above, with its code. |
|
|
213
|
-
| `500` | `{ "error": "Upload failed." }` | The store failed while it wrote the document, with an error that has no `status` or `statusCode` from 400 to 599 and is not a Node system error (a database driver's error, say). Or `files.ingest` threw a value that is not an `Error` (an extractor of your own that throws a string, say). Such a value with a `code` and a `syscall` gets its code, as in the `ENOSPC` row. The error's own message is not sent. See below. |
|
|
227
|
+
| `500` | `{ "error": "Upload failed." }` | The store failed while it wrote the document, with an error that has no `status` or `statusCode` from 400 to 599 and is not a Node system error (a database driver's error, say), or did not finish writing it within `ingestTimeoutMs` (new in 0.8.2). Or `files.ingest` threw a value that is not an `Error` (an extractor of your own that throws a string, say). Such a value with a `code` and a `syscall` gets its code, as in the `ENOSPC` row. The error's own message is not sent. See below. |
|
|
214
228
|
|
|
215
229
|
A store that fails while it writes is answered `500` "Upload failed." when its error has neither a
|
|
216
230
|
`status` (or `statusCode`) from 400 to 599 nor a Node system error's `code` and `syscall`. Its
|
|
@@ -250,7 +264,8 @@ The handler reads the `Accept` header this way:
|
|
|
250
264
|
What stays JSON: every check that runs before the ingest answers as it always did, with its status
|
|
251
265
|
and `{ "error": "…" }`, because the stream has not started yet. That is a missing name (`400`), a
|
|
252
266
|
refusal or a bad owner from `getOwner` (its status, or `500`), a body another middleware parsed
|
|
253
|
-
(`400`),
|
|
267
|
+
(`400`), a file over `maxUploadBytes` (`413`), an upload that finds no room (`503`, new in 0.8.2),
|
|
268
|
+
and a body that stops arriving (`408`, new in 0.8.2). Only a file that passes them is answered `200`
|
|
254
269
|
with the event-stream headers of [`writeSseEvents()`](#writesseeventsresponse-events-options) and
|
|
255
270
|
a `: keep-alive` comment every 15 seconds.
|
|
256
271
|
|
|
@@ -285,7 +300,7 @@ data: {"type":"ingest.finish","document":{"id":"doc_f6502d2f94694d709c7db2ec634c
|
|
|
285
300
|
that a page can say why in its own words.
|
|
286
301
|
- **The status is `200` whatever happens next.** Once the stream has started, a failure can only be
|
|
287
302
|
an `ingest.error` event.
|
|
288
|
-
- **A client that goes away stops the ingest**, as in step
|
|
303
|
+
- **A client that goes away stops the ingest**, as in step 5: nothing is stored, and nothing more
|
|
289
304
|
is written.
|
|
290
305
|
- **The handler still never rejects.**
|
|
291
306
|
|
|
@@ -468,7 +483,7 @@ type IsolatedExtractorOptions = {
|
|
|
468
483
|
|---|---|---|---|
|
|
469
484
|
| `maxHeapMb` | `number` | 512 | The heap of each child process, in MB, given as `--max-old-space-size`. A file that needs more is refused (`"out_of_memory"`), and the server goes on. From 1 to 1,048,576, and finite; a fraction is cut to a whole number. Node reads `--max-old-space-size=0` as its default heap, so a value below 1 is refused rather than cut to 0. |
|
|
470
485
|
| `timeoutMs` | `number` | 120,000 | The most time one file may take, in milliseconds. Past it, its child is killed and the file refused (`"timeout"`). 0 sets none, and so does a value past what a timer can wait (2,147,483,647 ms, 24.8 days), `Infinity` included, as for `ingestTimeoutMs`. With both at their defaults, the `ingestTimeoutMs` of `createLargeFiles` usually ends the ingest first, and its signal kills the child too. |
|
|
471
|
-
| `concurrency` | `number` | 2 | How many files are read at once, each in a child process of its own. At least 1. |
|
|
486
|
+
| `concurrency` | `number` | 2 | How many files are read at once, each in a child process of its own. At least 1. A library sends the readers at most its `maxConcurrentIngests` files at once (2 by default, since 0.8.2): for more children at work, raise that too. |
|
|
472
487
|
| `maxQueue` | `number` | 8 | How many files may wait for a child. Past it, a file is refused at once as `"busy"`. 0: none waits. |
|
|
473
488
|
| `formats` | `DocumentFormat[]` | `["pdf", "docx", "pptx", "xlsx"]` | The formats read in child processes: by default those whose parsers a hostile file can exhaust. `extractors` has an entry for each. |
|
|
474
489
|
| `pdf` | [`PdfExtractorOptions`](./library.md#pdfextractoroptions) | `{}` | Options of the built-in PDF extractor in the children, as for [`createPdfExtractor`](./library.md#createpdfextractoroptions). |
|
package/docs/security.md
CHANGED
|
@@ -584,10 +584,18 @@ server that memory is the server's heap. Choose the isolation with care:
|
|
|
584
584
|
too. `files.ingest` checks the bytes you give it, which are already in memory.
|
|
585
585
|
- **Memory.** The handlers buffer the whole upload, up to `maxUploadBytes`, before reading its
|
|
586
586
|
text, and an ingest then holds several copies of the text at once (several times the size of the
|
|
587
|
-
text), in your server's heap.
|
|
588
|
-
|
|
589
|
-
`
|
|
590
|
-
|
|
587
|
+
text), in your server's heap. Since 0.8.2 the handlers hold uploads of at most
|
|
588
|
+
`maxPendingUploadBytes` at once (twice `maxUploadBytes`), and answer the others 503 before reading
|
|
589
|
+
their body; each library lets `maxConcurrentIngests` (2) ingests work at once, and queues the
|
|
590
|
+
others. A route of your own must bound the bodies it reads itself. The room of an upload is
|
|
591
|
+
taken from its `Content-Length` before its body arrives, so a few clients that send headers and
|
|
592
|
+
then trickle their bodies can hold all of it: `uploadIdleTimeoutMs` (30 s) frees the room of a
|
|
593
|
+
body that stops, and `server.requestTimeout` that of one that trickles. A reverse proxy that reads
|
|
594
|
+
whole bodies before passing them on, and a limit on the connections and uploads of each client,
|
|
595
|
+
keep that room for the others ([Deployment](./guides/deployment.md#uploads-and-ingest)). Read PDF and Office files with
|
|
596
|
+
`createIsolatedExtractors`, whose `concurrency` (2) and `maxQueue` (8) bound how many are read and
|
|
597
|
+
wait, or ingest in a process of its own: [Deployment](./guides/deployment.md) has measurements
|
|
598
|
+
and recipes.
|
|
591
599
|
- **Text.** A small file can hold far more text than its size: a PDF of 3 KB whose page tree listed
|
|
592
600
|
one dense page 150 times drew 107 MB of text in 0.5.0. `maxTextBytes` (100 MB by default, or
|
|
593
601
|
`maxUploadBytes` when that is larger) bounds the text kept from one file, in UTF-8 bytes. The PDF
|
|
@@ -957,8 +965,9 @@ What you log is your choice, and some of what the library hands you holds user d
|
|
|
957
965
|
([Original files](#original-files)).
|
|
958
966
|
- Set `limits` and a deadline, and log `usage` for failed questions too
|
|
959
967
|
([What a question can cost](#what-a-question-can-cost)).
|
|
960
|
-
-
|
|
961
|
-
|
|
968
|
+
- Keep the bound on uploads held at once (`maxPendingUploadBytes` of the handlers, or your own in a
|
|
969
|
+
route of your own), limit uploads per user, and set the limit of any body parser in front of the
|
|
970
|
+
handlers ([Uploads](#uploads)).
|
|
962
971
|
- Keep the limits on one file (`maxTextBytes`, `maxPdfPages`, `ingestTimeoutMs`) as low as your
|
|
963
972
|
users allow ([Uploads](#uploads)).
|
|
964
973
|
- For untrusted uploads, parse them in a process of their own with a memory limit, not in a worker
|
package/docs/troubleshooting.md
CHANGED
|
@@ -258,6 +258,31 @@ is read and its text extracted, so a higher limit is more memory for each upload
|
|
|
258
258
|
|
|
259
259
|
See [Web app](./guides/web-app.md) and [Deployment](./guides/deployment.md).
|
|
260
260
|
|
|
261
|
+
### `503`: "The server is receiving other files right now. Try again in a moment."
|
|
262
|
+
|
|
263
|
+
New in 0.8.2. `createDocumentHandlers` answers `503` with `Retry-After: 5`, before reading the body.
|
|
264
|
+
|
|
265
|
+
**Cause.** The handlers already hold uploads, and this one would bring them past
|
|
266
|
+
`maxPendingUploadBytes` (twice `maxUploadBytes`, 200 MB by default). An upload is held from the
|
|
267
|
+
reading of its body to the end of its ingest, and its room is taken from its `Content-Length`
|
|
268
|
+
before its body arrives. Many users sending files at once, or a few clients that send their
|
|
269
|
+
headers and then their bodies slowly, fill it.
|
|
270
|
+
|
|
271
|
+
**Fix.** Send the file again after `Retry-After` seconds, as the browser code in
|
|
272
|
+
[Web app](./guides/web-app.md#upload-from-the-browser) does. To take more at once, raise
|
|
273
|
+
`maxPendingUploadBytes` and size the server for it (each upload under way takes about five to seven
|
|
274
|
+
times its size while it is ingested; ingests take turns, `maxConcurrentIngests`). Put a proxy that
|
|
275
|
+
reads whole bodies before passing them on in front, so that slow clients hold no room. "The server
|
|
276
|
+
is reading other files right now." is the other `503`: the readers of `createIsolatedExtractors`
|
|
277
|
+
are busy ([Node reference](./reference/node.md#uploadrequest-response)).
|
|
278
|
+
|
|
279
|
+
### `408`: "The upload stopped arriving: nothing came for 30 s. Send it again."
|
|
280
|
+
|
|
281
|
+
New in 0.8.2. **Cause.** The body of an upload stopped arriving for `uploadIdleTimeoutMs` (30 s):
|
|
282
|
+
the client's connection stalled, or a proxy held the body. The connection is closed. **Fix.** Send
|
|
283
|
+
the file again. For users on slow or unsteady links, raise `uploadIdleTimeoutMs` of
|
|
284
|
+
`createDocumentHandlers`.
|
|
285
|
+
|
|
261
286
|
### `400`: "Name the file with an X-File-Name header or a ?name= query parameter."
|
|
262
287
|
|
|
263
288
|
**Cause.** The upload request names no file. The name decides the format, and is shown to the
|
|
@@ -490,6 +515,9 @@ handler's `get` answers `404` with `This file is no longer available.` for the s
|
|
|
490
515
|
- belongs to another `owner`, or has an owner while the question passes none. A document with an
|
|
491
516
|
owner is reported as missing, never as forbidden;
|
|
492
517
|
- was stored in a `MemoryDocumentStore` of another process, or of this one before it restarted;
|
|
518
|
+
- has lost its text in the store while its metadata stayed (removed outside the library). Since
|
|
519
|
+
0.8.2 such a document is missing here too; before, a question about one read by range failed
|
|
520
|
+
with a plain `Error`;
|
|
493
521
|
- is not a document ID at all (`isDocumentId` is false for it).
|
|
494
522
|
|
|
495
523
|
**Fix.** Pass the same `owner` to the question as to the upload: the value `getOwner` returned for
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "llm-large-files",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.2",
|
|
4
4
|
"description": "Let an LLM answer questions about books, logs, and other files larger than its request limit or context window: upload, plan, search and read tools, map-reduce, a look at the pages of a PDF, and one tool loop for any model. Adapters for Gemini and Vertex AI, OpenAI-compatible endpoints, and Claude.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"llm",
|
package/src/library.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { Limiter } from "./limiter.js";
|
|
|
9
9
|
import { TimeSlicer } from "./pause.js";
|
|
10
10
|
import { canBeReadWhole, CARD_LINES, documentToolsInstruction, formatBytes, planDocuments, renderCard, renderInline, TABLE_FORMATS, type WholeRead } from "./plan.js";
|
|
11
11
|
import { measureQuality, type TextQuality } from "./quality.js";
|
|
12
|
-
import { openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
12
|
+
import { DocumentGoneError, openRangedDocument, pieceKey, type CachedPiece, type RangeStore, type ScanSettings } from "./ranged.js";
|
|
13
13
|
import { numberLines, SearchableDocument, type DocumentSource } from "./search.js";
|
|
14
14
|
import { DOCUMENT_ID_PATTERN } from "./stores.js";
|
|
15
15
|
import { buildTextIndexInSlices, canSerialize, serializeTextIndex } from "./text-index.js";
|
|
@@ -111,6 +111,13 @@ export type LargeFilesOptions = {
|
|
|
111
111
|
* run at once in this process. The others wait their turn. Defaults to 4.
|
|
112
112
|
*/
|
|
113
113
|
maxConcurrentScans?: number;
|
|
114
|
+
/**
|
|
115
|
+
* How many ingests do their work at once in this library. The others wait their turn, in order,
|
|
116
|
+
* and their time limit (`ingestTimeoutMs`) starts when their turn comes. An ingest holds about five
|
|
117
|
+
* times its file in memory while it works, and ingests at once share one thread: more of them do
|
|
118
|
+
* not finish sooner. `Infinity` for no limit (as before 0.8.2). Defaults to 2. New in 0.8.2.
|
|
119
|
+
*/
|
|
120
|
+
maxConcurrentIngests?: number;
|
|
114
121
|
/** Clock override, for tests. */
|
|
115
122
|
now?: () => Date;
|
|
116
123
|
};
|
|
@@ -350,6 +357,56 @@ export const DEFAULT_INGEST_TIMEOUT_MS = 120_000;
|
|
|
350
357
|
/** The longest a Node.js timer waits: a longer one fires at once. A limit past it is no limit. */
|
|
351
358
|
const LONGEST_TIMER_MS = 2 ** 31 - 1;
|
|
352
359
|
|
|
360
|
+
/** `value` copied through JSON: new strings, none of them a piece of a larger one. */
|
|
361
|
+
function jsonCopy<T>(value: T): T {
|
|
362
|
+
return JSON.parse(JSON.stringify(value)) as T;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** `work`, or the error `late` makes once `ms` have passed without it settling. */
|
|
366
|
+
function settleWithin<T>(work: Promise<T>, ms: number, late: () => Error): Promise<T> {
|
|
367
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
368
|
+
const timeUp = new Promise<never>((_, reject) => {
|
|
369
|
+
timer = setTimeout(() => reject(late()), ms);
|
|
370
|
+
});
|
|
371
|
+
return Promise.race([work, timeUp]).finally(() => clearTimeout(timer));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* The turn of one ingest (`maxConcurrentIngests`). It is given back when the ingest ends; when the
|
|
376
|
+
* ingest gave up on work that goes on (an extractor that does not stop on the signal, such as a
|
|
377
|
+
* PDF being parsed when its caller left), once that work ends, or `capMs` later when it does not.
|
|
378
|
+
* (Store writes that do not end fail the ingest after `capMs`: see `ingestFile`.)
|
|
379
|
+
*/
|
|
380
|
+
class IngestSlot {
|
|
381
|
+
private released = false;
|
|
382
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
383
|
+
|
|
384
|
+
constructor(private readonly release: () => void, private readonly capMs: number) {}
|
|
385
|
+
|
|
386
|
+
private readonly free = () => {
|
|
387
|
+
if (this.released) return;
|
|
388
|
+
this.released = true;
|
|
389
|
+
clearTimeout(this.timer);
|
|
390
|
+
this.release();
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Gives the turn back `capMs` from now at the latest. The timer keeps the process alive: work
|
|
395
|
+
* that never ends may hold nothing that does, and ingests waiting for the turn would be lost.
|
|
396
|
+
*/
|
|
397
|
+
limit(): void {
|
|
398
|
+
if (this.released || this.timer !== undefined) return;
|
|
399
|
+
this.timer = setTimeout(this.free, this.capMs);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** The ingest is over: the turn goes back now, or once `abandoned` ends (`capMs` at the latest). */
|
|
403
|
+
end(abandoned?: Promise<unknown>): void {
|
|
404
|
+
if (!abandoned) return this.free();
|
|
405
|
+
abandoned.then(this.free, this.free);
|
|
406
|
+
this.limit();
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
353
410
|
/** A time limit in the words of a message: "500 ms", "45 s", "2 min". */
|
|
354
411
|
function formatDuration(ms: number): string {
|
|
355
412
|
if (ms < 1_000) return `${Math.max(1, Math.round(ms))} ms`;
|
|
@@ -546,6 +603,11 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
546
603
|
},
|
|
547
604
|
};
|
|
548
605
|
const keepOriginals = new Set<DocumentFormat>(options.keepOriginals ?? []);
|
|
606
|
+
/** The ingests doing their work, and those waiting their turn (`maxConcurrentIngests`). */
|
|
607
|
+
const ingests = new Limiter(Math.max(1, Math.trunc(numberOption("maxConcurrentIngests", options.maxConcurrentIngests, 2))));
|
|
608
|
+
/** How long work an ingest waits on, or gave up on, may keep its turn (see `IngestSlot`). */
|
|
609
|
+
const slotCapMs = ingestTimeoutMs > 0 && ingestTimeoutMs <= LONGEST_TIMER_MS ? ingestTimeoutMs : DEFAULT_INGEST_TIMEOUT_MS;
|
|
610
|
+
|
|
549
611
|
const scannedPdfPages = Math.max(0, Math.trunc(numberOption("scannedPdfPages", options.scannedPdfPages, 30)));
|
|
550
612
|
/** Whether the uploaded file of a document of this format is kept. */
|
|
551
613
|
const keeps = (format: DocumentFormat) => keepOriginals.has(format) && typeof options.store.putOriginal === "function";
|
|
@@ -611,6 +673,9 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
611
673
|
? renderInline(document.meta, await document.readText())
|
|
612
674
|
: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead);
|
|
613
675
|
} catch (error) {
|
|
676
|
+
// The text is gone while its metadata is still there (removed outside the library): the
|
|
677
|
+
// same as missing. It was a plain Error, which failed the whole question.
|
|
678
|
+
if (error instanceof DocumentGoneError) return undefined;
|
|
614
679
|
if (!document.broken) {
|
|
615
680
|
// Deleted between the look-up and the read: the same as missing.
|
|
616
681
|
if (!await currentMeta(id)) return undefined;
|
|
@@ -638,11 +703,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
638
703
|
detected: DocumentFormat,
|
|
639
704
|
progress: IngestProgress | undefined,
|
|
640
705
|
storeFailed: () => void,
|
|
706
|
+
work: { abandoned?: Promise<unknown> },
|
|
641
707
|
): Promise<DocumentMeta> {
|
|
642
|
-
if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
|
|
643
|
-
if (input.bytes.byteLength > maxUploadBytes) {
|
|
644
|
-
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
645
|
-
}
|
|
646
708
|
let format = detected;
|
|
647
709
|
const { signal, dispose } = ingestSignal(name, input.signal, ingestTimeoutMs);
|
|
648
710
|
// Each long step works in slices, with pauses for other requests: one large upload no longer
|
|
@@ -668,7 +730,9 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
668
730
|
let extracting = true;
|
|
669
731
|
let extracted: ExtractedText;
|
|
670
732
|
try {
|
|
671
|
-
|
|
733
|
+
// Kept, so that an ingest that stops waiting for it (its time is up, its caller left)
|
|
734
|
+
// keeps its turn until the extractor is done too: it still holds memory.
|
|
735
|
+
const extraction = extractText(input.bytes, {
|
|
672
736
|
name,
|
|
673
737
|
mimeType,
|
|
674
738
|
format,
|
|
@@ -678,7 +742,10 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
678
742
|
maxTextBytes,
|
|
679
743
|
maxPages: maxPdfPages,
|
|
680
744
|
...(progress ? { onProgress: (report: ExtractProgress) => { if (extracting) progress.extracted(report); } } : {}),
|
|
681
|
-
}, options.extractors)
|
|
745
|
+
}, options.extractors);
|
|
746
|
+
work.abandoned = extraction;
|
|
747
|
+
extracted = await untilAborted(extraction, signal);
|
|
748
|
+
work.abandoned = undefined;
|
|
682
749
|
} finally {
|
|
683
750
|
extracting = false;
|
|
684
751
|
}
|
|
@@ -711,7 +778,11 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
711
778
|
const created = now();
|
|
712
779
|
const expires = created.getTime() + ttlMs;
|
|
713
780
|
const keepOriginal = keeps(format);
|
|
714
|
-
|
|
781
|
+
// A copy: the outline's headings and the log's timestamps are pieces of the text, and a piece
|
|
782
|
+
// keeps the whole text in memory as long as it is held. A meta an application kept held its
|
|
783
|
+
// text: 25 MB of heap for a log of 10 MB in Hebrew, 194 MB for one of 100 MB. Copied through
|
|
784
|
+
// JSON, as a store that keeps it as JSON gives it back.
|
|
785
|
+
const meta: DocumentMeta = jsonCopy<DocumentMeta>({
|
|
715
786
|
id: `doc_${randomUUID().replaceAll("-", "")}`,
|
|
716
787
|
...(input.owner !== undefined ? { owner: input.owner } : {}),
|
|
717
788
|
name,
|
|
@@ -733,7 +804,7 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
733
804
|
createdAt: created.toISOString(),
|
|
734
805
|
// Never, for a time to live without end (or one that runs past what a date can hold).
|
|
735
806
|
expiresAt: expires >= Date.parse(NEVER_EXPIRES) ? NEVER_EXPIRES : new Date(expires).toISOString(),
|
|
736
|
-
};
|
|
807
|
+
});
|
|
737
808
|
const savedIndex = index && canSerialize(index) && index.lineCount === meta.lines && index.characters === meta.characters && index.textBytes === meta.textBytes
|
|
738
809
|
? serializeTextIndex(index)
|
|
739
810
|
: undefined;
|
|
@@ -751,8 +822,8 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
751
822
|
throw error;
|
|
752
823
|
}
|
|
753
824
|
};
|
|
754
|
-
|
|
755
|
-
|
|
825
|
+
// The files first, the document last: a document is there once its metadata is.
|
|
826
|
+
const storing = (async () => {
|
|
756
827
|
if (keepOriginal) {
|
|
757
828
|
await store.putOriginal!(meta.id, input.bytes);
|
|
758
829
|
wrote(false);
|
|
@@ -763,10 +834,17 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
763
834
|
}
|
|
764
835
|
await store.put({ meta, text });
|
|
765
836
|
wrote(true);
|
|
837
|
+
})();
|
|
838
|
+
try {
|
|
839
|
+
// A store that does not answer fails the ingest after `slotCapMs`: it held the ingest's turn,
|
|
840
|
+
// and the upload handler's room for the file, for as long as it did not answer.
|
|
841
|
+
await settleWithin(storing, slotCapMs, () => new Error(`The store did not finish writing ${name} within ${formatDuration(slotCapMs)}.`));
|
|
766
842
|
} catch (error) {
|
|
767
843
|
// Do not leave a file of up to the upload limit, or a part of one, behind for a document
|
|
768
|
-
// that does not exist.
|
|
769
|
-
|
|
844
|
+
// that does not exist: once the writes have ended, when they have not yet. The removal is not
|
|
845
|
+
// waited for longer than the writes were.
|
|
846
|
+
const removal = storing.then(() => store.delete(meta.id), () => store.delete(meta.id)).catch(() => undefined);
|
|
847
|
+
await settleWithin(removal, slotCapMs, () => new Error("")).catch(() => undefined);
|
|
770
848
|
if (listenerFailed?.error !== error) {
|
|
771
849
|
noteStoreWriteFailure(error);
|
|
772
850
|
storeFailed();
|
|
@@ -806,7 +884,22 @@ export function createLargeFiles(options: LargeFilesOptions): LargeFiles {
|
|
|
806
884
|
const progress = events.active ? new IngestProgress(events) : undefined;
|
|
807
885
|
let meta: DocumentMeta;
|
|
808
886
|
try {
|
|
809
|
-
|
|
887
|
+
// Refused at once, without waiting for a turn.
|
|
888
|
+
if (input.bytes.byteLength === 0) throw new Error(`${name} is empty.`);
|
|
889
|
+
if (input.bytes.byteLength > maxUploadBytes) {
|
|
890
|
+
throw new Error(`${name} is larger than the ${formatBytes(maxUploadBytes)} upload limit.`);
|
|
891
|
+
}
|
|
892
|
+
// Its turn (`maxConcurrentIngests`): a caller that gives up while it waits gets its own
|
|
893
|
+
// reason, as it would once the work had begun. (An ingest started inside another of this
|
|
894
|
+
// library, by an extractor of your own, waits for a turn like any other. Telling it apart
|
|
895
|
+
// with AsyncLocalStorage made pdf.js about five times slower on Node 22, for every PDF.)
|
|
896
|
+
const slot = new IngestSlot(await ingests.acquire(input.signal), slotCapMs);
|
|
897
|
+
const work: { abandoned?: Promise<unknown> } = {};
|
|
898
|
+
try {
|
|
899
|
+
meta = await ingestFile(input, name, mimeType, format, progress, () => (storeFailed = true), work);
|
|
900
|
+
} finally {
|
|
901
|
+
slot.end(work.abandoned);
|
|
902
|
+
}
|
|
810
903
|
} catch (error) {
|
|
811
904
|
// A store that failed, and a caller that gave up (its own reason), are passed on as they
|
|
812
905
|
// are; a file that could not be read is told with a code.
|
package/src/limiter.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Lets at most `max` tasks hold a slot at once; the others wait their turn, in order. Used for
|
|
3
|
-
* scans of whole documents: on one thread more of them at once do not finish
|
|
4
|
-
* hold more memory.
|
|
3
|
+
* scans of whole documents and for ingests: on one thread more of them at once do not finish
|
|
4
|
+
* sooner, they only hold more memory.
|
|
5
5
|
*/
|
|
6
6
|
export class Limiter {
|
|
7
7
|
private active = 0;
|