llm-large-files 0.8.1 → 0.9.0
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 +631 -0
- package/README.md +9 -10
- package/dist/access.d.ts +86 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +131 -0
- package/dist/access.js.map +1 -0
- package/dist/ask.d.ts +45 -1
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +181 -20
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +57 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +217 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +72 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +102 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +35 -9
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +14 -3
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +46 -35
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +19 -3
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +84 -12
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +18 -6
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +2 -0
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/index.d.ts +1 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/index.d.ts +9 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +70 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +868 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +176 -34
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +332 -512
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -2
- package/dist/limiter.js +2 -2
- package/dist/map-reduce.js +3 -3
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +43 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +63 -3
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +234 -7
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +482 -121
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +18 -3
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +102 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +365 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +4 -3
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +7 -6
- package/dist/node/sse.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/ranged.d.ts +22 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +50 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +120 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +582 -139
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +25 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +135 -13
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +116 -13
- package/dist/types.d.ts.map +1 -1
- package/docs/README.md +17 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +12 -8
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +16 -7
- package/docs/guides/deployment.md +309 -87
- package/docs/guides/errors-and-reliability.md +161 -23
- package/docs/guides/own-adapter-and-loop.md +27 -10
- package/docs/guides/pdfs.md +123 -29
- package/docs/guides/storage.md +634 -143
- package/docs/guides/testing.md +78 -129
- package/docs/guides/vertex-and-gemini.md +10 -7
- package/docs/guides/web-app.md +322 -77
- package/docs/how-it-works.md +35 -8
- package/docs/measurements.md +63 -8
- package/docs/publishing.md +112 -36
- package/docs/reference/ask.md +154 -13
- package/docs/reference/errors-and-retries.md +166 -14
- package/docs/reference/events.md +53 -20
- package/docs/reference/gemini.md +70 -21
- package/docs/reference/library.md +709 -165
- package/docs/reference/node.md +633 -104
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +15 -5
- package/docs/security.md +316 -70
- package/docs/troubleshooting.md +165 -58
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +12 -3
- package/src/access.ts +144 -0
- package/src/ask.ts +230 -19
- package/src/cache.ts +20 -5
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +255 -0
- package/src/errors.ts +129 -15
- package/src/events.ts +86 -21
- package/src/evidence.ts +14 -3
- package/src/extract.ts +50 -33
- package/src/gemini/adapter.ts +97 -11
- package/src/gemini/chat.ts +20 -6
- package/src/gemini/index.ts +1 -1
- package/src/index.ts +9 -6
- package/src/ingest.ts +927 -0
- package/src/library.ts +482 -523
- package/src/limiter.ts +2 -2
- package/src/map-reduce.ts +3 -3
- package/src/model.ts +69 -5
- package/src/node/handlers.ts +691 -117
- package/src/node/index.ts +13 -2
- package/src/node/ingest-child.ts +23 -5
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +365 -0
- package/src/node/sse.ts +7 -6
- package/src/pdf-layout.ts +69 -11
- package/src/ranged.ts +42 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/source.ts +178 -0
- package/src/stores.ts +635 -140
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +150 -14
- package/src/types.ts +106 -13
package/docs/reference/node.md
CHANGED
|
@@ -1,35 +1,44 @@
|
|
|
1
1
|
# `llm-large-files/node`
|
|
2
2
|
|
|
3
|
-
This page lists every export of `llm-large-files/node`: `createDocumentHandlers`, its options
|
|
4
|
-
the three HTTP handlers it returns, with the request each one expects and every status
|
|
5
|
-
can answer; `
|
|
6
|
-
|
|
3
|
+
This page lists every export of `llm-large-files/node`: `createDocumentHandlers`, its options and
|
|
4
|
+
hooks, and the three HTTP handlers it returns, with the request each one expects and every status
|
|
5
|
+
and body it can answer; `uploadAnswerOf`, the rule by which they answer an error;
|
|
6
|
+
`createIsolatedExtractors`, which reads PDF and Office files in child processes with a
|
|
7
|
+
memory limit and a kill timer; `fileOriginals`, which reads back the uploads your application keeps
|
|
8
|
+
in a folder; and `writeSseEvents` and `sseMessageOf`, which send the events of a
|
|
7
9
|
question or an ingest to a browser as Server-Sent Events. It is for you if your server runs on Node
|
|
8
|
-
and you want uploads, look-ups and deletes of documents without writing the routes yourself
|
|
10
|
+
and you want uploads, look-ups and deletes of documents without writing the routes yourself (with
|
|
11
|
+
the body saved where you keep your uploads, or spooled to disk, if you like), files
|
|
9
12
|
from users read apart from your server, or a streamed answer without writing the stream yourself.
|
|
10
13
|
How to mount them, what the browser sends, and how to read the stream in the browser are in the
|
|
11
14
|
guide [web app](../guides/web-app.md).
|
|
12
15
|
|
|
13
16
|
```ts
|
|
14
|
-
import { createDocumentHandlers, createIsolatedExtractors, sseMessageOf, writeSseEvents } from "llm-large-files/node";
|
|
17
|
+
import { createDocumentHandlers, createIsolatedExtractors, fileOriginals, sseMessageOf, uploadAnswerOf, writeSseEvents } from "llm-large-files/node";
|
|
15
18
|
import type {
|
|
16
|
-
DocumentHandlerOptions, DocumentHandlers, IsolatedExtractorOptions, IsolatedExtractors,
|
|
19
|
+
DocumentHandlerOptions, DocumentHandlers, IsolatedExtractorOptions, IsolatedExtractors, PreparedUpload, PrepareUploadInfo,
|
|
20
|
+
RemovedContext, SseMessage, SseWriteOptions, UploadAnswer, UploadedContext, UploadedResult, UploadSpoolOptions,
|
|
17
21
|
} from "llm-large-files/node";
|
|
18
22
|
// What the signatures below use:
|
|
19
23
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
20
|
-
import type { DocumentFormat, Extractor, LargeFiles, PdfExtractorOptions } from "llm-large-files";
|
|
24
|
+
import type { DocumentFormat, DocumentMeta, DocumentScope, Extractor, IngestErrorCode, LargeFiles, OriginalsReader, PdfExtractorOptions } from "llm-large-files";
|
|
21
25
|
```
|
|
22
26
|
|
|
23
27
|
## Contents
|
|
24
28
|
|
|
25
29
|
- [`createDocumentHandlers()`](#createdocumenthandlersfiles-options)
|
|
26
|
-
- [`DocumentHandlerOptions`](#documenthandleroptions)
|
|
30
|
+
- [`DocumentHandlerOptions`](#documenthandleroptions), with
|
|
31
|
+
[`getScope`](#what-getscope-returns), [the hooks](#the-hooks-onuploaded-and-onremoved),
|
|
32
|
+
[saving the body: `prepareUpload`](#saving-the-body-prepareupload) and
|
|
33
|
+
[spooling: `uploadSpool`](#spooling-uploadspool)
|
|
27
34
|
- [`DocumentHandlers`](#documenthandlers): [`upload()`](#uploadrequest-response) and
|
|
28
35
|
[its progress as events](#upload-with-progress-accept-textevent-stream),
|
|
29
36
|
[`get()`](#getrequest-response-id), [`remove()`](#removerequest-response-id)
|
|
30
|
-
- [How errors are answered](#how-errors-are-answered)
|
|
37
|
+
- [How errors are answered](#how-errors-are-answered):
|
|
38
|
+
[`uploadAnswerOf()`](#uploadansweroferror), [`UploadAnswer`](#uploadanswer)
|
|
31
39
|
- [Isolated ingest](#isolated-ingest): [`createIsolatedExtractors()`](#createisolatedextractorsoptions),
|
|
32
40
|
[`IsolatedExtractorOptions`](#isolatedextractoroptions), [`IsolatedExtractors`](#isolatedextractors)
|
|
41
|
+
- [Uploads your application keeps](#uploads-your-application-keeps): [`fileOriginals()`](#fileoriginalsroot)
|
|
33
42
|
- [Server-Sent Events](#server-sent-events): [`writeSseEvents()`](#writesseeventsresponse-events-options),
|
|
34
43
|
[`sseMessageOf()`](#ssemessageofevent), [`SseMessage`](#ssemessage),
|
|
35
44
|
[`SseWriteOptions`](#ssewriteoptions)
|
|
@@ -50,10 +59,24 @@ included, and never rejects, so it can be called without a `catch`.
|
|
|
50
59
|
| Parameter | Type | Default | What it does |
|
|
51
60
|
|---|---|---|---|
|
|
52
61
|
| `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. |
|
|
54
|
-
|
|
55
|
-
**Returns** the three [`DocumentHandlers`](#documenthandlers). It makes no request
|
|
56
|
-
store
|
|
62
|
+
| `options` | [`DocumentHandlerOptions`](#documenthandleroptions) | `{}` | Who owns a request, how many bytes of uploads are held at once, and how long a body may stop arriving. |
|
|
63
|
+
|
|
64
|
+
**Returns** the three [`DocumentHandlers`](#documenthandlers). It makes no request and reads no
|
|
65
|
+
store. It throws:
|
|
66
|
+
|
|
67
|
+
- a `RangeError` for a `maxPendingUploadBytes`, `maxSpooledUploadBytes`, `uploadIdleTimeoutMs` or
|
|
68
|
+
`uploadSpool.minBytes` that is not a number in range;
|
|
69
|
+
- a `TypeError` when `files` has no `maxUploadBytes` above 0 (a `LargeFiles` of your own, from
|
|
70
|
+
JavaScript, must keep the one of the library it wraps; new in 0.8.2);
|
|
71
|
+
- a `TypeError` when `files.access.requireOwner` is on and there is no `getOwner`, or
|
|
72
|
+
`files.access.requireScope` is on and there is no `getScope` (new in 0.9.0). Every request would
|
|
73
|
+
fail otherwise. The message names the option:
|
|
74
|
+
"createDocumentHandlers needs getOwner: the library requires an owner on every call (requireOwner).";
|
|
75
|
+
- a `TypeError` when `getScope`, `prepareUpload`, `onUploaded` or `onRemoved` is given and is not
|
|
76
|
+
a function (new in 0.9.0);
|
|
77
|
+
- a `TypeError` for an `uploadSpool` that is not `true`, `false` or an object, a
|
|
78
|
+
`uploadSpool.directory` that is not a string with something in it, or an `uploadFileMode` that is
|
|
79
|
+
not a whole number from 0 to `0o777` (new in 0.9.0).
|
|
57
80
|
|
|
58
81
|
The handlers do not check the method or the path of a request: route each request to the one you
|
|
59
82
|
mean. Every response they write has the header `Content-Type: application/json; charset=utf-8`
|
|
@@ -94,6 +117,15 @@ upload route of your own for multipart forms or the Fetch API's `Request`.
|
|
|
94
117
|
```ts
|
|
95
118
|
type DocumentHandlerOptions = {
|
|
96
119
|
getOwner?: (request: IncomingMessage) => string | undefined | Promise<string | undefined>;
|
|
120
|
+
getScope?: (request: IncomingMessage) => DocumentScope | undefined | Promise<DocumentScope | undefined>;
|
|
121
|
+
onUploaded?: (document: DocumentMeta, context: UploadedContext) => UploadedResult | Promise<UploadedResult>;
|
|
122
|
+
onRemoved?: (id: string, context: RemovedContext) => void | Promise<void>;
|
|
123
|
+
prepareUpload?: (request: IncomingMessage, info: PrepareUploadInfo) => PreparedUpload | void | Promise<PreparedUpload | void>;
|
|
124
|
+
uploadSpool?: boolean | UploadSpoolOptions;
|
|
125
|
+
maxSpooledUploadBytes?: number;
|
|
126
|
+
uploadFileMode?: number;
|
|
127
|
+
maxPendingUploadBytes?: number;
|
|
128
|
+
uploadIdleTimeoutMs?: number;
|
|
97
129
|
};
|
|
98
130
|
```
|
|
99
131
|
|
|
@@ -101,25 +133,349 @@ The options of [`createDocumentHandlers()`](#createdocumenthandlersfiles-options
|
|
|
101
133
|
|
|
102
134
|
| Option | Type | Default | What it does |
|
|
103
135
|
|---|---|---|---|
|
|
104
|
-
| `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)." }`. |
|
|
136
|
+
| `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)." }`. Required when the library has `requireOwner` (new in 0.9.0): an owner of `undefined`, or `null` from JavaScript (`req.user?.id ?? null`), is then answered `401` `{ "error": "Sign in first." }`, on every route, before the body is read, and an empty owner `500` "(empty owner)" on every route too. |
|
|
137
|
+
| `getScope` | `(request: IncomingMessage) => DocumentScope \| undefined \| Promise<DocumentScope \| undefined>` | none: no scope | New in 0.9.0. The scope of this request, such as `[userId, chatId]` ([`DocumentScope`](./library.md#documentscope)). Called after `getOwner`, at most once per request, before the body is read, on every route. The upload is stored in that scope, and `get` and `remove` find only documents of that scope. Required when the library has `requireScope`. See [what `getScope` returns](#what-getscope-returns). |
|
|
138
|
+
| `onUploaded` | `(document: DocumentMeta, context: UploadedContext) => UploadedResult \| Promise<UploadedResult>` | none | New in 0.9.0. Called once an upload is stored, before it is answered: to record the document in your database, for example. What it returns can add fields to the answer. When it throws, the document is deleted and the upload fails. See [the hooks](#the-hooks-onuploaded-and-onremoved). |
|
|
139
|
+
| `onRemoved` | `(id: string, context: RemovedContext) => void \| Promise<void>` | none | New in 0.9.0. Called after `remove` deleted a document, before it answers `{ "deleted": true }`. See [the hooks](#the-hooks-onuploaded-and-onremoved). |
|
|
140
|
+
| `prepareUpload` | `(request: IncomingMessage, info: PrepareUploadInfo) => PreparedUpload \| void \| Promise<PreparedUpload \| void>` | none | New in 0.9.0. Called after `getOwner` and `getScope`, before the body is read. Returns the document's `id`, a `path` to save the body to, and the `original` ref of that file, or nothing. With a `path`, the body is written there as it arrives, ingested from the file, and kept once the document is stored. See [saving the body](#saving-the-body-prepareupload). |
|
|
141
|
+
| `uploadSpool` | `boolean \| UploadSpoolOptions` | `false` | New in 0.9.0. Writes bodies over `minBytes` (1 MiB), and those without a `Content-Length`, to a temporary file of mode `0o600` in `directory` (`os.tmpdir()`), ingests them from there, and removes the file once the ingest ends. `true` for the defaults. See [spooling](#spooling-uploadspool). |
|
|
142
|
+
| `maxSpooledUploadBytes` | `number` | ten times `files.maxUploadBytes` (1 GB by default) | New in 0.9.0. The most bytes of the spool's files at once, counted as `maxPendingUploadBytes` counts memory. An upload that would pass it is answered `503` with `Retry-After: 5` before its body is read. `Infinity` for no limit. A value that is not a number above 0 throws a `RangeError`. |
|
|
143
|
+
| `uploadFileMode` | `number` | `0o600` | New in 0.9.0. The mode of the files saved to the `path` of `prepareUpload`, minus the umask of the process. `0o640` lets a group read them: pods of another user that share the volume through a group (`fsGroup`). The spool's files are always `0o600`. |
|
|
144
|
+
| `maxPendingUploadBytes` | `number` | twice `files.maxUploadBytes` (200 MB by default) | The most bytes of uploads these handlers hold in memory at once. Since 0.9.0 a body written to a file (the `path` of `prepareUpload`, or `uploadSpool`) does not count. 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). Since 0.9.0 its room is given back, and the body the handler read is freed, before `onUploaded` runs: a hook that waits on your database holds neither. 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. |
|
|
145
|
+
| `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. Since 0.9.0, for a body written to a file (the `path` of `prepareUpload`, or `uploadSpool`), it also bounds each call to the disk: the check of its folders for a link (a `path` with a ref), the opening of the file, each write, and its closing. A volume that stops answering then fails the upload with `500` `{ "error": "Upload failed (ETIMEDOUT)." }`, and its room is given back. The removal of the file is waited for no longer either: past it, the removal goes on alone, and the upload is answered all the same. 0 or `Infinity` for no limit. A value below 0 throws a `RangeError`. New in 0.8.2. |
|
|
105
146
|
|
|
106
147
|
What `getOwner` returns decides what each handler does:
|
|
107
148
|
|
|
108
149
|
| `getOwner` | `upload` | `get` and `remove` |
|
|
109
150
|
|---|---|---|
|
|
110
151
|
| Returns a string that is not empty or only spaces | The document is ingested with that `owner`. | They pass `{ owner }`: they find the documents of that owner, and those that have no owner. A document of another owner answers as one that does not exist. |
|
|
111
|
-
| Returns `undefined`, or there is no `getOwner` | The document has no owner: anyone who has its ID can read it, delete it and ask about it. | They pass no owner: they find only documents that have no owner. |
|
|
112
|
-
| Returns `""`, spaces only, or `null` from JavaScript | Answered `500` `{ "error": "Upload failed (empty owner)." }`, before the body is read, and nothing is logged. Such an owner would be one owner shared by every caller without a user: `user?.id ?? ""` gives it for a user who is not signed in. New in 0.6.0: 0.5.0 stored the document with that owner. | As before: they pass it as `owner`, so documents that 0.5.0 stored with the owner `""` stay readable until they expire. |
|
|
113
|
-
| Returns, from JavaScript, something that is neither a string nor a finite number: an object such as `req.user`, `true`, `NaN`, an array | Answered `500` `{ "error": "Upload failed (owner is not a string)." }`, before the body is read, and nothing is logged. New in 0.6.0. A finite number is taken as the owner, as before. | They pass it as `owner`, as before. |
|
|
152
|
+
| Returns `undefined`, or there is no `getOwner` | The document has no owner: anyone who has its ID can read it, delete it and ask about it. Under `requireOwner`: answered `401` `{ "error": "Sign in first." }`, before the body is read (new in 0.9.0). | They pass no owner: they find only documents that have no owner. Under `requireOwner`: `401` `{ "error": "Sign in first." }`. |
|
|
153
|
+
| Returns `""`, spaces only, or `null` from JavaScript | Answered `500` `{ "error": "Upload failed (empty owner)." }`, before the body is read, and nothing is logged. Under `requireOwner`, `null` is a request that is not signed in: `401`, as `undefined` (new in 0.9.0). Such an owner would be one owner shared by every caller without a user: `user?.id ?? ""` gives it for a user who is not signed in. New in 0.6.0: 0.5.0 stored the document with that owner. | As before: they pass it as `owner`, so documents that 0.5.0 stored with the owner `""` stay readable until they expire. Under `requireOwner`, where the library refuses such an owner on every call, `""` or spaces only (`null` is a `401` there, as `undefined`) are answered `500` `{ "error": "The file could not be looked up (empty owner)." }` and `{ "error": "The file could not be deleted (empty owner)." }` without calling it (new in 0.9.0: they called it, and answered its `TypeError` with a bare `500`). |
|
|
154
|
+
| Returns, from JavaScript, something that is neither a string nor a finite number: an object such as `req.user`, `true`, `NaN`, an array | Answered `500` `{ "error": "Upload failed (owner is not a string)." }`, before the body is read, and nothing is logged. New in 0.6.0. A finite number is taken as the owner, as before. | They pass it as `owner`, as before. Under `requireOwner`: `500` "(owner is not a string)", as the upload (new in 0.9.0). |
|
|
114
155
|
| Throws an `Error` whose `status` (or `statusCode`) is a whole number from 400 to 599, as the `http-errors` package makes them | Answered with that status and `{ "error": <the error's message> }`. | The same. |
|
|
115
156
|
| Throws anything else | Answered `500` without the error's message, which may name your hosts: `{ "error": "Upload failed." }` (with the code of a Node system error: "Upload failed (ECONNREFUSED)."). | `500`: "The file could not be looked up." or "The file could not be deleted.", the same way. |
|
|
116
157
|
|
|
117
158
|
The owner is one opaque string, compared as it is. Pass the same string as `owner` to
|
|
118
|
-
`askWithFiles` or `askGemini`, and to `files.getMeta`, `files.getOriginal` and `files.delete`.
|
|
119
|
-
|
|
120
|
-
[storage](../guides/storage.md). What ownership protects and what it does not:
|
|
159
|
+
`askWithFiles` or `askGemini`, and to `files.getMeta`, `files.getOriginal` and `files.delete`. To
|
|
160
|
+
keep each chat's files apart, give a scope with `getScope` rather than an owner per chat session
|
|
161
|
+
([storage](../guides/storage.md)). What ownership protects and what it does not:
|
|
121
162
|
[security](../security.md).
|
|
122
163
|
|
|
164
|
+
#### What `getScope` returns
|
|
165
|
+
|
|
166
|
+
New in 0.9.0. The scope keeps the documents of one chat apart from those of another, in the
|
|
167
|
+
library and, with a scoped [`FileDocumentStore`](./library.md#filedocumentstore), on disk.
|
|
168
|
+
|
|
169
|
+
| `getScope` | `upload` | `get` and `remove` |
|
|
170
|
+
|---|---|---|
|
|
171
|
+
| Returns a valid scope: an array of 1 to 8 strings, such as `[userId, chatId]` | The document is stored in that scope (`IngestInput.scope`). | They pass `{ owner, scope }`: a document of another scope answers as one that does not exist, `404` or `{ "deleted": false }`. |
|
|
172
|
+
| Returns `undefined` (or `null` from JavaScript), or there is no `getScope` | The document has no scope. Under `requireScope`: answered `500` `{ "error": "Upload failed (no scope)." }`, before the body is read. | They pass no scope: they find only documents without one. Under `requireScope`: `500`, "The file could not be looked up (no scope)." or "The file could not be deleted (no scope).". |
|
|
173
|
+
| Returns a scope that is not valid (not an array, a segment with "/" or a control character, more than 8 segments…) | Answered `500` `{ "error": "Upload failed (invalid scope)." }`, before the body is read. It is the server's mistake: the message says nothing more. | `500`, "The file could not be looked up (invalid scope)." or "The file could not be deleted (invalid scope).". |
|
|
174
|
+
| Throws an `Error` with a `status` from 400 to 599 | Answered with that status and the error's message, as for `getOwner`. | The same. |
|
|
175
|
+
| Throws anything else | `500` "Upload failed.", without the error's message. | `500`, the same way. |
|
|
176
|
+
|
|
177
|
+
`getScope` runs after `getOwner`: a request refused by `getOwner` never reaches it. The scope a
|
|
178
|
+
handler passes is a frozen copy of what `getScope` returned. Pass the same scope to `askWithFiles`.
|
|
179
|
+
|
|
180
|
+
#### The hooks: `onUploaded` and `onRemoved`
|
|
181
|
+
|
|
182
|
+
New in 0.9.0. `onUploaded` lets your app record each upload where it keeps its chats, in the same
|
|
183
|
+
request, and fail the upload when it cannot:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
187
|
+
import { createDocumentHandlers } from "llm-large-files/node";
|
|
188
|
+
|
|
189
|
+
const files = createLargeFiles({ store: new FileDocumentStore("/data", { scopes: { depth: 2 } }), requireOwner: true, requireScope: true });
|
|
190
|
+
|
|
191
|
+
const documents = createDocumentHandlers(files, {
|
|
192
|
+
getOwner: (request) => userIdOf(request), // your sign-in
|
|
193
|
+
getScope: (request) => [userIdOf(request), chatIdOf(request)], // safe IDs: lowercase letters, digits, "_" and "-"
|
|
194
|
+
onUploaded: async (document, { owner, scope, clientGone }) => {
|
|
195
|
+
// Throw to fail the upload: the document is deleted, and the error is answered.
|
|
196
|
+
const record = await chats.addFile(scope![1]!, { documentId: document.id, name: document.name, owner, clientGone });
|
|
197
|
+
return { answer: { fileNumber: record.number } }; // in the 201, and in ingest.finish.app
|
|
198
|
+
},
|
|
199
|
+
onRemoved: async (id, { scope }) => {
|
|
200
|
+
await chats.removeFile(scope![1]!, id);
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`onUploaded(document, context)`:
|
|
206
|
+
|
|
207
|
+
- **When.** Once `files.ingest` has stored the document, and before the upload is answered: before
|
|
208
|
+
the `201`, or before `ingest.finish` on the [event-stream path](#upload-with-progress-accept-textevent-stream).
|
|
209
|
+
The answer waits for it, with no time limit: bound the calls of your own (a database's
|
|
210
|
+
timeout), or a hook that hangs leaves the client waiting. The upload's room
|
|
211
|
+
(`maxPendingUploadBytes`) is given back, and the body the handler read is freed, before the hook is called, so a slow
|
|
212
|
+
hook does not hold up other uploads (new in 0.9.0). It is called once per upload, and never for
|
|
213
|
+
an upload that failed.
|
|
214
|
+
- **`document`** is the whole [`DocumentMeta`](./library.md#documentmeta), with its `owner` and
|
|
215
|
+
`scope`: for your server, not for the browser.
|
|
216
|
+
- **`context`** is an [`UploadedContext`](#uploadedcontext): the `request` (its body is read; the
|
|
217
|
+
bytes are not in the context, unless a framework left them in `request.body`, as `express.raw()`
|
|
218
|
+
does: those stay until the request ends), the `owner` and the `scope` the handler used,
|
|
219
|
+
`clientGone`, and the `path` where the body was saved, for an upload that `prepareUpload` gave
|
|
220
|
+
one (new in 0.9.0).
|
|
221
|
+
- **A client that went away.** The hook is still called, with `clientGone: true`, for a document
|
|
222
|
+
that was stored. Nobody gets the answer. Record the document, or delete it, as your app needs.
|
|
223
|
+
With the library's own `ingest`, a client that leaves before the ingest ends leaves nothing
|
|
224
|
+
stored, and the hook is not called (new in 0.9.0). So `clientGone` is `true` for a client that
|
|
225
|
+
left after the ingest ended, while its answer waited, or with an `ingest` of your own that does
|
|
226
|
+
not stop on its `signal`.
|
|
227
|
+
- **What it returns.** Nothing, or `{ answer }`. `answer` is a plain object that JSON can hold. Its
|
|
228
|
+
fields are added to the `201` JSON; the summary's own fields win when a name is the same. On the
|
|
229
|
+
event-stream path it is `ingest.finish`'s `app` field. Anything it returns without an `answer`
|
|
230
|
+
(a database's own result) adds nothing.
|
|
231
|
+
- **When it throws,** or returns an `answer` that is not a plain object JSON can hold, the document
|
|
232
|
+
is deleted (best effort: a delete that fails is not told), and the file saved to the `path` of
|
|
233
|
+
[`prepareUpload`](#saving-the-body-prepareupload) is removed. The upload is then answered as an
|
|
234
|
+
error of `ingest` is ([`uploadAnswerOf`](#uploadansweroferror)): an error with a `status` from
|
|
235
|
+
400 to 599 gives that status and its message, and any other error a `500`
|
|
236
|
+
`{ "error": "Upload failed." }`. On the event-stream path, that is the `ingest.error` event, and
|
|
237
|
+
no `ingest.finish` is sent.
|
|
238
|
+
|
|
239
|
+
`onRemoved(id, context)` is called after `remove` deleted the document (`files.delete` returned
|
|
240
|
+
`true`), and before the answer `{ "deleted": true }`. `context` is a [`RemovedContext`](#removedcontext):
|
|
241
|
+
the `request`, the `owner` and the `scope`. It is not called for `{ "deleted": false }`. When it
|
|
242
|
+
throws, `remove` answers its error, as for an error of `files.delete`; the document is deleted all
|
|
243
|
+
the same, and a second `remove` answers `{ "deleted": false }` without calling it again.
|
|
244
|
+
|
|
245
|
+
##### `UploadedContext`
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
type UploadedContext = {
|
|
249
|
+
request: IncomingMessage;
|
|
250
|
+
owner?: string;
|
|
251
|
+
scope?: DocumentScope;
|
|
252
|
+
clientGone: boolean;
|
|
253
|
+
path?: string;
|
|
254
|
+
};
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
| Field | What it holds |
|
|
258
|
+
|---|---|
|
|
259
|
+
| `request` | The upload's request, for its headers and URL. Its body has been read. A body a framework left in `request.body` (`express.raw()`) is still there: it is the framework's. |
|
|
260
|
+
| `owner` | What `getOwner` returned, when it returned an owner. |
|
|
261
|
+
| `scope` | What `getScope` returned, when it returned a scope (a frozen copy). |
|
|
262
|
+
| `clientGone` | `true` when the client went away before the hook was called: after the ingest ended, or during an `ingest` of your own that does not stop on its `signal`. |
|
|
263
|
+
| `path` | The `path` that `prepareUpload` returned, where the body is saved. Only for such an upload: the file is there while the hook runs, and stays, unless the hook throws. A file of the spool is removed before the hook, and is not told. New in 0.9.0. |
|
|
264
|
+
|
|
265
|
+
##### `UploadedResult`
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
type UploadedResult = void | { answer?: Record<string, unknown> };
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
##### `RemovedContext`
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
type RemovedContext = { request: IncomingMessage; owner?: string; scope?: DocumentScope };
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
#### Saving the body: `prepareUpload`
|
|
278
|
+
|
|
279
|
+
New in 0.9.0. An app that keeps each upload in a folder of its own (to show it again, or to let
|
|
280
|
+
`view_pages` read it there) can have the handler save the body there, once, as it arrives. The file
|
|
281
|
+
is then ingested from its path, and kept by reference: the store keeps no copy.
|
|
282
|
+
|
|
283
|
+
```ts
|
|
284
|
+
import path from "node:path";
|
|
285
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
286
|
+
import { createDocumentHandlers, fileOriginals } from "llm-large-files/node";
|
|
287
|
+
|
|
288
|
+
const VOLUME = "/data";
|
|
289
|
+
const files = createLargeFiles({
|
|
290
|
+
store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }),
|
|
291
|
+
keepOriginals: ["pdf"],
|
|
292
|
+
originals: fileOriginals(VOLUME),
|
|
293
|
+
ttlMs: Infinity, // kept as long as the chat, as its uploads are
|
|
294
|
+
requireOwner: true,
|
|
295
|
+
requireScope: true,
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
const documents = createDocumentHandlers(files, {
|
|
299
|
+
getOwner: (request) => userIdOf(request), // your sign-in
|
|
300
|
+
getScope: (request) => [userIdOf(request), chatIdOf(request)],
|
|
301
|
+
prepareUpload: async (_request, { scope }) => {
|
|
302
|
+
const id = await uploads.newId(); // your database: lowercase letters, digits, "_" and "-"
|
|
303
|
+
// <user>/<chat>/uploads is made with the chat (below): the handler makes no folder.
|
|
304
|
+
const ref = [...scope!, "uploads", id].join("/"); // <user>/<chat>/uploads/<id>
|
|
305
|
+
return { id, path: path.join(VOLUME, ref), original: { ref } };
|
|
306
|
+
},
|
|
307
|
+
});
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
The folders are yours: the handler makes no folder. Make `<user>/<chat>/uploads` when the chat is
|
|
311
|
+
made, with `mode: 0o700`, as
|
|
312
|
+
[the web app guide](../guides/web-app.md#save-each-upload-where-you-keep-it-prepareupload) says:
|
|
313
|
+
`mkdir(path.join(VOLUME, user, chat, "uploads"), { recursive: true, mode: 0o700 })`, with the IDs
|
|
314
|
+
checked first ([Storage](../guides/storage.md#files-in-a-folder-per-user-or-per-chat)). Without it,
|
|
315
|
+
every upload is answered `500` `{ "error": "Upload failed (ENOENT)." }`, even when the chat's own
|
|
316
|
+
folder is there.
|
|
317
|
+
|
|
318
|
+
`prepareUpload(request, info)`:
|
|
319
|
+
|
|
320
|
+
- **When.** After `getOwner` and `getScope`, and after a `Content-Length` over `maxUploadBytes` is
|
|
321
|
+
answered `413`; before the room of the upload is taken and before its body is read. It is called
|
|
322
|
+
once per upload. An upload can still fail after it (no room, too large, a body that stops, a file
|
|
323
|
+
that cannot be read): choose here, and record the upload in `onUploaded`.
|
|
324
|
+
- **`info`** is a [`PrepareUploadInfo`](#prepareuploadinfo): the file's `name` as the document will
|
|
325
|
+
have it (the last part of the name sent, cleaned), and the `owner` and `scope` the handler uses.
|
|
326
|
+
The name is the client's: never build a path from it.
|
|
327
|
+
- **What it returns.** Nothing, or a [`PreparedUpload`](#preparedupload). Each field is optional,
|
|
328
|
+
and a field of `null` counts as none:
|
|
329
|
+
- `id`: the document's ID (`IngestInput.id`). A document of that ID already stored fails the
|
|
330
|
+
upload with `409` (`IngestError` `"exists"`).
|
|
331
|
+
- `path`: an absolute path where the body is saved. See below.
|
|
332
|
+
- `original`: `{ ref }` of the saved file, for `LargeFilesOptions.originals`
|
|
333
|
+
(`IngestInput.original`). Only with `path`: the handler does not make a ref of a path, and does
|
|
334
|
+
not check that the ref names the file at `path` (a reader of your own may have refs of its
|
|
335
|
+
own). With `fileOriginals(root)`, the path is `<root>/<ref>`: see the folders below.
|
|
336
|
+
Without `original`, the file is saved and ingested all the same, and a store with `putOriginal`
|
|
337
|
+
keeps its own copy, as `keepOriginals` says. A library without `originals` refuses a ref
|
|
338
|
+
(`TypeError`): `500` "Upload failed.", and the file is removed.
|
|
339
|
+
- Anything else (a relative path, an ID that is not a string, a ref without a path) is the
|
|
340
|
+
server's mistake: `500` `{ "error": "Upload failed." }`, before the body is read.
|
|
341
|
+
- **When it throws,** the upload is answered as for `getOwner`: an error with a `status` from 400
|
|
342
|
+
to 599 gives that status and its message, and any other error a `500` "Upload failed.". Nothing
|
|
343
|
+
is written.
|
|
344
|
+
|
|
345
|
+
With a `path`:
|
|
346
|
+
|
|
347
|
+
- **The file is made new.** It is opened with `"wx"` and mode `uploadFileMode` (`0o600`), minus the
|
|
348
|
+
umask. A file already at the path, or a link (even one that points nowhere), is never written
|
|
349
|
+
through: the upload is answered `409` `{ "error": "A file is already saved for this upload." }`,
|
|
350
|
+
before its body is read, and what is there stays as it is. That `409` is not an `IngestError`,
|
|
351
|
+
and has no `code`: `"exists"` is the code of a taken ID.
|
|
352
|
+
- **Its folder must exist.** The handler makes no folder. A folder that is not there is answered
|
|
353
|
+
`500` `{ "error": "Upload failed (ENOENT)." }`. A chat your app deleted should be refused before,
|
|
354
|
+
in `getScope` or `prepareUpload`, with a `404`.
|
|
355
|
+
- **No link in its folders, with a ref.** `"wx"` refuses a link only at the file's own name: a link
|
|
356
|
+
in a folder above it (`uploads` pointing to another disk) is followed. `fileOriginals` refuses a
|
|
357
|
+
link at any level below its root, so such a file could never be read back. So when the path ends
|
|
358
|
+
with the ref of `original` (`<root>/<ref>`), the handler checks the folders from that root down
|
|
359
|
+
before it reads the body. A link among them is answered `500`
|
|
360
|
+
`{ "error": "Upload failed (ELOOP)." }`, and nothing is written. The root itself may be a link,
|
|
361
|
+
as for `fileOriginals`. A ref that is not the end of the path is not checked. The check is
|
|
362
|
+
waited for no longer than `uploadIdleTimeoutMs`: a volume that stops answering is answered `500`
|
|
363
|
+
`{ "error": "Upload failed (ETIMEDOUT)." }`, and nothing is written.
|
|
364
|
+
- **The body is written as it arrives,** under the same limits as in memory: a body over
|
|
365
|
+
`maxUploadBytes` is answered `413`, and one that stops arriving for `uploadIdleTimeoutMs` `408`.
|
|
366
|
+
A disk that is full (`ENOSPC`, `EDQUOT`) is answered `503`
|
|
367
|
+
`{ "error": "The server has no room for this file right now. Try again later." }` with
|
|
368
|
+
`Retry-After: 30`. Each call to the disk (the opening, each write, the closing) is waited for no
|
|
369
|
+
longer than `uploadIdleTimeoutMs`: a volume that stops answering is answered `500`
|
|
370
|
+
`{ "error": "Upload failed (ETIMEDOUT)." }`. A body a framework already read (`express.raw()`) is
|
|
371
|
+
written whole.
|
|
372
|
+
- **It is ingested from the file:** `files.ingest({ name, source: { path }, id, original, … })`
|
|
373
|
+
([`IngestFromSource`](./library.md#ingestfromsource)). The body is never held in memory, and the
|
|
374
|
+
upload takes no room of `maxPendingUploadBytes` or `maxSpooledUploadBytes`: it is on your disk.
|
|
375
|
+
- **It stays once the document is stored.** It is yours: `onUploaded` is told its `path`, and the
|
|
376
|
+
library never removes it, even when the document is deleted or expires. Remove it yourself, in
|
|
377
|
+
`onRemoved` or with its chat. A document that expires (`ttlMs`) is removed without a call to
|
|
378
|
+
`onRemoved`, and leaves its file: keep the documents as long as their chat (`ttlMs: Infinity`, as
|
|
379
|
+
above), or remove the files with the chat.
|
|
380
|
+
- **It is removed when the upload fails,** whatever the reason: too large, a body that stops, a
|
|
381
|
+
client that leaves while the body arrives or while it is ingested, a full disk, a file the ingest
|
|
382
|
+
refuses, an ID that is taken, or `onUploaded` throwing. After a call to the disk that did not
|
|
383
|
+
answer, it is removed at once, or once the volume answers. A file that was already at the path is
|
|
384
|
+
never removed. A server process that is killed in the middle of an upload (past its grace period,
|
|
385
|
+
or out of memory) cannot remove it: the partial file stays, and nothing removes it, since the
|
|
386
|
+
sweep removes only the store's files. Remove such files with a job of your own:
|
|
387
|
+
[Stopping a server](../guides/deployment.md#stopping-a-server).
|
|
388
|
+
- **Nothing of it is sent.** The path and the ref are not in the answer, the events, the
|
|
389
|
+
summaries, or anything sent to the model.
|
|
390
|
+
|
|
391
|
+
#### Spooling: `uploadSpool`
|
|
392
|
+
|
|
393
|
+
New in 0.9.0. Without it, the handler holds each body whole in memory from the moment it is read
|
|
394
|
+
until its ingest ends: `maxPendingUploadBytes` of them at once. With `uploadSpool`, larger bodies go
|
|
395
|
+
to a temporary file instead, and are ingested from its path.
|
|
396
|
+
|
|
397
|
+
```ts
|
|
398
|
+
const documents = createDocumentHandlers(files, {
|
|
399
|
+
getOwner: (request) => userIdOf(request),
|
|
400
|
+
uploadSpool: { directory: "/var/spool/uploads" }, // this server's own folder, on a disk
|
|
401
|
+
});
|
|
402
|
+
```
|
|
403
|
+
|
|
404
|
+
- **Which bodies.** Those whose `Content-Length` is over `minBytes` (1 MiB by default), and those
|
|
405
|
+
without a `Content-Length` (sent chunked). A smaller body is held in memory, as without a spool,
|
|
406
|
+
and so is a body a framework already read into `request.body`. `minBytes: 0` spools every body
|
|
407
|
+
that has bytes. The `path` of `prepareUpload` wins over the spool.
|
|
408
|
+
- **The file.** It is made new in `directory` (`os.tmpdir()` by default, which must exist), named
|
|
409
|
+
`llf-upload-` and a random UUID, opened with `"wx"` and mode `0o600`. The body is written as it
|
|
410
|
+
arrives, under `maxUploadBytes` and `uploadIdleTimeoutMs` (for each piece of the body, and each
|
|
411
|
+
call to the disk), then ingested with `files.ingest({ name, source: { path }, … })`. With
|
|
412
|
+
`createIsolatedExtractors`, a PDF or Office file is read from that path by its child process,
|
|
413
|
+
unless the store keeps a copy of it (`keepOriginals`, a store with `putOriginal`, and no
|
|
414
|
+
`original`): the server then reads it to copy it, and sends the bytes to the child.
|
|
415
|
+
- **It is always removed,** once the ingest ends: stored, refused, aborted because the client left,
|
|
416
|
+
or failed. A body that fails while it is written (`413`, `408`, a client that leaves) is removed
|
|
417
|
+
then. `onUploaded` runs after the removal, and is not told the path. A removal is waited for no
|
|
418
|
+
longer than `uploadIdleTimeoutMs`: on a volume that stops answering, the upload is answered and
|
|
419
|
+
gives its room back, and the removal goes on alone. A server that stops in the middle of an
|
|
420
|
+
upload leaves its file. So the folder belongs to one server process: a disk-backed `emptyDir`,
|
|
421
|
+
or a folder of its own on the shared volume, such as `path.join("/data/spool", os.hostname())`.
|
|
422
|
+
Both are one folder a pod or a host: with several server processes on one, add a number of each
|
|
423
|
+
process ([Deployment](../guides/deployment.md#uploads-and-ingest)). Each server empties its own
|
|
424
|
+
folder when it starts, and no other. Never empty a folder that several servers share: the
|
|
425
|
+
uploads still arriving or waiting for their turn would lose their files, and fail with `500`
|
|
426
|
+
"Upload failed (ENOENT).".
|
|
427
|
+
- **Room.** `maxSpooledUploadBytes` (ten times `maxUploadBytes`) bounds the bytes of the spool's
|
|
428
|
+
files at once, as `maxPendingUploadBytes` bounds memory: an upload takes its `Content-Length`, or
|
|
429
|
+
`maxUploadBytes` without one, before its body is read, then its size once written, until its file
|
|
430
|
+
is removed. One that would pass the limit while others hold room is answered `503` with
|
|
431
|
+
`Retry-After: 5` before its body is read; one upload alone is always taken. A disk that is full is
|
|
432
|
+
answered `503` with `Retry-After: 30`, and the file is removed. A disk that does not answer within
|
|
433
|
+
`uploadIdleTimeoutMs` is answered `500` "Upload failed (ETIMEDOUT).", and gives the room back.
|
|
434
|
+
- **Memory.** `maxPendingUploadBytes` then counts only the bodies held in memory. In memory, a body
|
|
435
|
+
without a `Content-Length` takes `maxUploadBytes` of room until it is read, so two of them filled
|
|
436
|
+
the default room and a third was answered `503`. Spooled, they take room on disk.
|
|
437
|
+
- **A `LargeFiles` of your own** gets `IngestFromSource` (`source: { path }`, no `bytes`) for a
|
|
438
|
+
spooled or saved body: it must take one. The `ingestInProcess` recipe in
|
|
439
|
+
[deployment](../guides/deployment.md#uploads-and-ingest) sends the path to its process.
|
|
440
|
+
|
|
441
|
+
Where to put the spool, and why not a memory-backed volume:
|
|
442
|
+
[deployment](../guides/deployment.md#uploads-and-ingest).
|
|
443
|
+
|
|
444
|
+
##### `PrepareUploadInfo`
|
|
445
|
+
|
|
446
|
+
```ts
|
|
447
|
+
type PrepareUploadInfo = { name: string; owner?: string; scope?: DocumentScope };
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
| Field | What it holds |
|
|
451
|
+
|---|---|
|
|
452
|
+
| `name` | The file's name as the document will have it: the last part of the name sent, without control characters and characters that show nothing (as `files.ingest` cleans it). The client's words: never build a path from it. |
|
|
453
|
+
| `owner` | What `getOwner` returned, when it returned an owner. |
|
|
454
|
+
| `scope` | What `getScope` returned, when it returned a scope (a frozen copy). |
|
|
455
|
+
|
|
456
|
+
##### `PreparedUpload`
|
|
457
|
+
|
|
458
|
+
```ts
|
|
459
|
+
type PreparedUpload = { id?: string; path?: string; original?: { ref: string } };
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
| Field | What it does |
|
|
463
|
+
|---|---|
|
|
464
|
+
| `id` | The document's ID (`IngestInput.id`): lowercase letters, digits, `_` and `-`, up to 64 characters (`APP_DOCUMENT_ID_PATTERN`). The model sees it: no personal data in it. |
|
|
465
|
+
| `path` | An absolute path where the body is saved, made new, then ingested from. The file stays once the document is stored, and is removed when the upload fails. |
|
|
466
|
+
| `original` | `{ ref }`: where `LargeFilesOptions.originals` reads the saved file, such as its path under the folder of [`fileOriginals`](#fileoriginalsroot). Only with `path`. When `path` ends with the ref, a link in a folder below that root is refused (`500` "Upload failed (ELOOP)."). |
|
|
467
|
+
|
|
468
|
+
##### `UploadSpoolOptions`
|
|
469
|
+
|
|
470
|
+
```ts
|
|
471
|
+
type UploadSpoolOptions = { directory?: string; minBytes?: number };
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
| Field | Default | What it does |
|
|
475
|
+
|---|---|---|
|
|
476
|
+
| `directory` | `os.tmpdir()` | The folder of the temporary files. It must exist; a relative path is resolved when the handlers are made. |
|
|
477
|
+
| `minBytes` | 1 MiB (1,048,576) | Bodies whose `Content-Length` is this many bytes or fewer are held in memory. Larger ones, and those without a `Content-Length`, are spooled. `0` spools every body with bytes; `Infinity` only those without a `Content-Length`. |
|
|
478
|
+
|
|
123
479
|
### `DocumentHandlers`
|
|
124
480
|
|
|
125
481
|
```ts
|
|
@@ -154,8 +510,8 @@ The request:
|
|
|
154
510
|
| Body | The file itself, as raw bytes. Not a multipart form: the handler does not parse one. |
|
|
155
511
|
| `X-File-Name` header | The file name, URI-encoded with `encodeURIComponent` so that any name survives a header. It is decoded with `decodeURIComponent` (a value that does not decode is used as it is) and trimmed. |
|
|
156
512
|
| `?name=` query parameter | The file name, when there is no `X-File-Name`. One of the two is required. |
|
|
157
|
-
| `X-File-Type` header | Optional: the MIME type, URI-decoded. |
|
|
158
|
-
| `Content-Type` header | The MIME type when there is no `X-File-Type`, unless it starts with `application/octet-stream`.
|
|
513
|
+
| `X-File-Type` header | Optional: the MIME type, URI-decoded (a value that does not decode is used as it is). |
|
|
514
|
+
| `Content-Type` header | The MIME type when there is no `X-File-Type`, unless it starts with `application/octet-stream`. It is taken as it came: since 0.9.0 it is not URI-decoded, so `%0D%0A` in it stays three characters and cannot become a line break (S11). It is passed to `files.ingest` with its parameters, and `files.ingest` keeps only its type/subtype, in lower case: that is the document's `mimeType`. A `fetch` with a string body sends `text/plain;charset=UTF-8`, and the document's `mimeType` is `text/plain`. The type sets the format when the name has no known extension: `text/csv; charset=utf-8` with the name `data` is read as CSV. With neither header, the document's `mimeType` is `application/octet-stream`. Send `application/octet-stream`, which JSON and form parsers leave alone. |
|
|
159
515
|
| `Content-Length` header | Optional. When it is larger than `maxUploadBytes`, the handler answers `413` before it reads anything. |
|
|
160
516
|
| `Accept` header | Optional. When it names `text/event-stream`, the ingest is answered with its progress as Server-Sent Events: see [upload with progress](#upload-with-progress-accept-textevent-stream). New in 0.7.0. |
|
|
161
517
|
|
|
@@ -169,13 +525,30 @@ What it does, in order:
|
|
|
169
525
|
1. Reads the name. Without one, it answers `400`.
|
|
170
526
|
2. Calls `getOwner`, and checks what it returned: `""`, spaces only or `null`, or from JavaScript
|
|
171
527
|
a value that is neither a string nor a finite number, is answered `500` (see
|
|
172
|
-
[`DocumentHandlerOptions`](#documenthandleroptions)).
|
|
173
|
-
|
|
528
|
+
[`DocumentHandlerOptions`](#documenthandleroptions)). Under `requireOwner`, `undefined` is
|
|
529
|
+
answered `401` (new in 0.9.0).
|
|
530
|
+
3. Calls `getScope`, and checks what it returned: a scope that is not valid, or none under
|
|
531
|
+
`requireScope`, is answered `500` ([what `getScope` returns](#what-getscope-returns)). New in
|
|
532
|
+
0.9.0.
|
|
533
|
+
4. Answers `413` a `Content-Length`, or a body in `request.body`, over `maxUploadBytes`. Then
|
|
534
|
+
calls `prepareUpload`, when there is one, and checks the folders of a path with a ref (`500`
|
|
535
|
+
"Upload failed (ELOOP)." for a link) ([saving the body](#saving-the-body-prepareupload); new in
|
|
536
|
+
0.9.0).
|
|
537
|
+
5. Makes room for the upload: in memory ([`maxPendingUploadBytes`](#documenthandleroptions)), or in
|
|
538
|
+
the spool for a body that is spooled (`maxSpooledUploadBytes`, new in 0.9.0). A body saved to the
|
|
539
|
+
`path` of `prepareUpload` takes none. An upload that would bring the uploads held past the
|
|
540
|
+
limit, while others are held, is answered `503`, before its body is read. New in 0.8.2.
|
|
541
|
+
6. Reads the body, up to `files.maxUploadBytes`: into memory, or, new in 0.9.0, into a file as it
|
|
542
|
+
arrives, at the `path` of `prepareUpload` or in the spool (`uploadSpool`). A file is made new
|
|
543
|
+
(`"wx"`): one already at the path is answered `409`, a disk that is full `503` with
|
|
544
|
+
`Retry-After: 30`, and a call to the disk that does not end within `uploadIdleTimeoutMs` `500`
|
|
545
|
+
"Upload failed (ETIMEDOUT).". On any failure of the body, the file is removed.
|
|
174
546
|
- a `Uint8Array` or `Buffer` that a framework left in `request.body` (`express.raw()`) is used
|
|
175
547
|
as the file, with the same limit;
|
|
176
548
|
- an object with fields in `request.body` (`express.json()` on a JSON request) is answered
|
|
177
549
|
`400`;
|
|
178
|
-
- otherwise it reads the request stream
|
|
550
|
+
- otherwise it reads the request stream, waiting at most `uploadIdleTimeoutMs` (30 s) for each
|
|
551
|
+
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
552
|
answers `413` at once. The rest of the body is then read and dropped, up to 8 MB, and the
|
|
180
553
|
answer ends when the body does: a client that is still sending reads the `413`, and can send
|
|
181
554
|
its next request on the same keep-alive connection. A body that goes on more than 8 MB past
|
|
@@ -188,46 +561,62 @@ What it does, in order:
|
|
|
188
561
|
client stuck sending into it. The answer to such a body has no `Content-Length`. A stream
|
|
189
562
|
that another middleware has already read gives no bytes, and the upload is answered `422` as
|
|
190
563
|
an empty file.
|
|
191
|
-
|
|
192
|
-
only when there are any
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
564
|
+
7. Ingests it: `files.ingest({ name, bytes, mimeType, owner, scope, signal })`, `mimeType`,
|
|
565
|
+
`owner` and `scope` only when there are any, and the `id` and `original` of `prepareUpload`. A
|
|
566
|
+
body in a file is given as `source: { path }` in place of `bytes` (new in 0.9.0): a file of the
|
|
567
|
+
spool is removed when the ingest ends, and the file of `prepareUpload` when it fails. The ingest may first wait its turn
|
|
568
|
+
(`maxConcurrentIngests` of `createLargeFiles`, 2 by default). The `signal` aborts when the
|
|
569
|
+
client closes the connection before the answer is sent: the ingest stops between two pages or
|
|
570
|
+
pieces (or leaves the queue), and nothing is stored. The answer then goes to no one.
|
|
571
|
+
8. Gives back the upload's room, then calls `onUploaded` with the stored document
|
|
572
|
+
([the hooks](#the-hooks-onuploaded-and-onremoved)), also when the client went away. When it
|
|
573
|
+
throws, the document is deleted (and the file of `prepareUpload` removed) and the upload is
|
|
574
|
+
answered with its error. New in 0.9.0.
|
|
575
|
+
9. Answers `201` with the document's summary, and the fields of `onUploaded`'s `answer`. With
|
|
576
|
+
`Accept: text/event-stream`, steps 7 to 9 are a stream of events instead
|
|
577
|
+
([below](#upload-with-progress-accept-textevent-stream)).
|
|
197
578
|
|
|
198
579
|
The responses:
|
|
199
580
|
|
|
200
581
|
| Status | Body | When |
|
|
201
582
|
|---|---|---|
|
|
202
|
-
| `201` | The [`DocumentSummary`](./library.md#documentsummary) of the new document | It was ingested. |
|
|
583
|
+
| `201` | The [`DocumentSummary`](./library.md#documentsummary) of the new document, with the fields of `onUploaded`'s `answer` (the summary's win) | It was ingested, and `onUploaded`, when there is one, did not throw. |
|
|
584
|
+
| `401` | `{ "error": "Sign in first." }` | The library has `requireOwner`, and `getOwner` returned `undefined` (or `null`). The body is not read. New in 0.9.0. |
|
|
585
|
+
| `404` | `{ "error": "This chat no longer exists." }` | The store threw a [`DocumentScopeError`](./library.md#documentscopeerror) of code `"scope_missing"`: the scope's folder is gone (a scoped `FileDocumentStore` whose session folder your app removed). New in 0.9.0: it was `422` with the error's message. |
|
|
203
586
|
| `400` | `{ "error": "Name the file with an X-File-Name header or a ?name= query parameter." }` | No name. |
|
|
204
587
|
| `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
588
|
| `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
|
-
| `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,
|
|
589
|
+
| `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, would stop the server on this Node ("The unpdf installed would stop the whole server at the first PDF file on Node 22, so PDF files are not read. Install unpdf 1.6.1 or later, or run Node 24 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. A file of code `"unreadable"`, damaged or not of the type its name says, is answered with fixed words: "This file could not be read. It may be damaged, or not of the type its name says." Its own message is a parser's ("Invalid PDF structure."), or that of an extractor of your own that threw an `Error` (an OCR service's, which may name its host): it stays on the error, for your log. New in 0.9.0: that message was sent. |
|
|
590
|
+
| `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. |
|
|
591
|
+
| `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`, or, for a body that is spooled, past `maxSpooledUploadBytes` (new in 0.9.0). Answered before the body is read, also to a request with `Accept: text/event-stream`. New in 0.8.2. |
|
|
207
592
|
| `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
|
-
|
|
|
209
|
-
| `
|
|
593
|
+
| `409` | `{ "error": "report.pdf: a document with this ID already exists." }` | `files.ingest` threw an `IngestError` of code `"exists"`: a document of the ID the upload was given (`prepareUpload`'s `id`) is there. New in 0.9.0. |
|
|
594
|
+
| `409` | `{ "error": "A file is already saved for this upload." }` | A file or a link is already at the `path` of `prepareUpload`. It is not written through, nor removed. The body is not read. It is not an `IngestError`, and has no `code`: `"exists"` is the code of a taken ID (the row above). New in 0.9.0. |
|
|
595
|
+
| `503` | `{ "error": "The server has no room for this file right now. Try again later." }`, with `Retry-After: 30` | The disk the body was written to is full (`ENOSPC`, `EDQUOT`): the `path` of `prepareUpload`, or the spool. The file is removed. New in 0.9.0. |
|
|
596
|
+
| `503` | `{ "error": "The document could not be stored (ENOSPC). Try again." }`, with `Retry-After: 5` | The store failed while it wrote the document, or did not finish writing it within `ingestTimeoutMs` (code `ETIMEDOUT`): `files.ingest` threw a [`DocumentStoreError`](./library.md#documentstoreerror) of operation `"write"`. The code is shown only when the store's error has one. The store's own message is not sent. New in 0.9.0: it was answered `500` "Upload failed (ENOSPC)." or "Upload failed.", with no `Retry-After`. |
|
|
597
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner`, `getScope`, `prepareUpload`, `onUploaded` or an extractor threw an error with that `status` or `statusCode`. A model's error (`ModelRequestError`) is the exception: it is answered with the status and words of [`errorInfoOf`](./errors-and-retries.md#errorinfooferror), never the provider's. |
|
|
598
|
+
| `500` | `{ "error": "Upload failed (empty owner)." }` | `getOwner` returned `""`, spaces only or `null` (`null` is a `401` under `requireOwner`). The body is not read. New in 0.6.0. |
|
|
599
|
+
| `500` | `{ "error": "Upload failed (invalid scope)." }` | `getScope` returned a scope that is not valid. The body is not read. New in 0.9.0. |
|
|
600
|
+
| `500` | `{ "error": "Upload failed (no scope)." }` | The library has `requireScope`, and `getScope` returned `undefined`. The body is not read. New in 0.9.0. |
|
|
210
601
|
| `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
|
-
| `500` | `{ "error": "Upload failed (
|
|
212
|
-
| `500` | `{ "error": "Upload failed." }` |
|
|
213
|
-
| `500` | `{ "error": "Upload failed." }` |
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
`status`, and a system error's `code` and `syscall`, onto the error it throws.
|
|
230
|
-
[Storage](../guides/storage.md) has the rules for a store's errors.
|
|
602
|
+
| `500` | `{ "error": "Upload failed (ELOOP)." }` | `prepareUpload` gave a `path` that ends with the ref of its `original`, and a folder between that root and the file is a link: `fileOriginals` would never read the file back. Nothing is written, and the body is not read. New in 0.9.0. |
|
|
603
|
+
| `500` | `{ "error": "Upload failed (ETIMEDOUT)." }` | A call to the disk for the file of `prepareUpload` or of the spool (the check of its folders for a link, its opening, a write, its closing) did not end within `uploadIdleTimeoutMs`: the volume stopped answering. The upload's room is given back, and the file is removed at once, or once the volume answers. When the check of the folders did not end, nothing is written. New in 0.9.0. |
|
|
604
|
+
| `500` | `{ "error": "Upload failed (ENOSPC)." }` | An extractor of your own failed with a Node system error, one with a `code` and a `syscall`; or the file of `prepareUpload` or of the spool could not be made, as `"Upload failed (ENOENT)."` for a folder that is not there (new in 0.9.0). Only the code is passed on, and only when it reads as one (capitals, digits and `_`): since 0.9.0 a code that does not, such as a host a driver put in `code`, is left out, and the answer is "Upload failed.". |
|
|
605
|
+
| `500` | `{ "error": "Upload failed." }` | `getOwner`, `getScope` or `prepareUpload` threw an error without a status, or `prepareUpload` returned a value that is not a `PreparedUpload` (a relative path, an ID that is not a string, a ref without a path): the body is not read (`prepareUpload` is new in 0.9.0). 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 one of these kinds that has a `code` and a `syscall` is answered as in the row above, with its code. |
|
|
606
|
+
| `500` | `{ "error": "Upload failed." }` | `files.ingest` or `onUploaded` threw an error that is none of the above: not an `IngestError`, with no status and no system error's `code` and `syscall`. Its message is not sent: it may name a host, as a database driver's does. A `DocumentScopeError` of code `"scope_invalid"` or `"scope_required"`, the server's mistake, is answered so too. New in 0.9.0: an `Error` of a `LargeFiles` of your own was answered `422` with its message (S12). So is a value that is not an `Error` (an extractor of your own that throws a string, say), as before. |
|
|
607
|
+
|
|
608
|
+
A store that fails while it writes reaches the handler as a `DocumentStoreError` since 0.9.0, and is
|
|
609
|
+
answered `503` with `Retry-After: 5` and its message, which names no path or host. The store's own
|
|
610
|
+
error is its `cause`, and the handlers log nothing: log it in your store.
|
|
611
|
+
|
|
612
|
+
Only an [`IngestError`](./library.md#ingesterror) is answered `422`, since 0.9.0. A `LargeFiles` of
|
|
613
|
+
your own that refuses a file must throw one, `new IngestError(code, message)`, as `ingestInProcess`
|
|
614
|
+
in [deployment](../guides/deployment.md#uploads-and-ingest) does. A plain `Error` is answered `500`
|
|
615
|
+
"Upload failed.", whatever its message. A route of your own around `files.ingest` answers the same
|
|
616
|
+
way with [`uploadAnswerOf`](#uploadansweroferror) ([web app](../guides/web-app.md#filesingest-and-its-errors)).
|
|
617
|
+
Pass a `DocumentStoreError` on as it is: an `ingest` of your own must not throw a new error in its
|
|
618
|
+
place, or must copy its `status` onto the error it throws. [Storage](../guides/storage.md) has the
|
|
619
|
+
rules for a store's errors.
|
|
231
620
|
|
|
232
621
|
#### Upload with progress: `Accept: text/event-stream`
|
|
233
622
|
|
|
@@ -249,8 +638,13 @@ The handler reads the `Accept` header this way:
|
|
|
249
638
|
|
|
250
639
|
What stays JSON: every check that runs before the ingest answers as it always did, with its status
|
|
251
640
|
and `{ "error": "…" }`, because the stream has not started yet. That is a missing name (`400`), a
|
|
252
|
-
refusal or a bad owner from `getOwner` (its status, or `500`), a
|
|
253
|
-
|
|
641
|
+
refusal or a bad owner from `getOwner` (its status, `401` or `500`), a refusal or a bad scope from
|
|
642
|
+
`getScope` (its status, or `500`; new in 0.9.0), a refusal from `prepareUpload` or what it should not
|
|
643
|
+
return (its status, or `500`; new in 0.9.0), a body another middleware parsed (`400`), a file over
|
|
644
|
+
`maxUploadBytes` (`413`), an upload that finds no room (`503`, new in 0.8.2), a file already at the
|
|
645
|
+
path of `prepareUpload` (`409`), a link in the folders of a path with a ref (`500` "ELOOP"), a full
|
|
646
|
+
disk (`503`) or a disk that does not answer (`500` "ETIMEDOUT"), all new in 0.9.0, and a body that
|
|
647
|
+
stops arriving (`408`, new in 0.8.2). Only a file that passes them is answered `200`
|
|
254
648
|
with the event-stream headers of [`writeSseEvents()`](#writesseeventsresponse-events-options) and
|
|
255
649
|
a `: keep-alive` comment every 15 seconds.
|
|
256
650
|
|
|
@@ -262,8 +656,8 @@ of [`IngestEvent`](./events.md#ingestevent), stamped with `seq` (1, 2, 3… with
|
|
|
262
656
|
|---|---|---|
|
|
263
657
|
| `ingest.start` | `name` (cleaned), `format` (what the name and the type say: a text file can still become a log), `bytes` | First. |
|
|
264
658
|
| `ingest.progress` | `stage` (`"decode"`, `"extract"`, `"check"`, `"pictures"`, `"prepare"`, `"index"` or `"store"`), `done`, `total` (absent when not known), `unit` (`"pages"`, `"parts"`, `"bytes"` or `"characters"`) | At most about every 12 ms for a stage, and once more when the stage ends. A stage with nothing to report may send none ([stages and units](./events.md#stages-and-units)). |
|
|
265
|
-
| `ingest.finish` | `document`: the [`DocumentSummary`](./library.md#documentsummary), the same fields as the body of a `201` | Last, when the document is stored. |
|
|
266
|
-
| `ingest.error` | `error`: `{ "message": …, "status": … }`, the message and status the JSON answer would have, and for a file that could not be read `"code"`, the [`IngestError`](./library.md#ingesterror) code (new in 0.8.0) | Last, when the ingest fails. |
|
|
659
|
+
| `ingest.finish` | `document`: the [`DocumentSummary`](./library.md#documentsummary), the same fields as the body of a `201`. `app`: the `answer` of `onUploaded`, when it returned one (new in 0.9.0) | Last, when the document is stored and `onUploaded`, when there is one, is done. |
|
|
660
|
+
| `ingest.error` | `error`: `{ "message": …, "status": … }`, the message and status the JSON answer would have, and for a file that could not be read `"code"`, the [`IngestError`](./library.md#ingesterror) code (new in 0.8.0). For a store that failed, `"name": "DocumentStoreError"`; for a scope error, `"name": "DocumentScopeError"` and its `"code"`; for documents that are gone, `"name": "DocumentsNotFoundError"`; for a model's error, its `"kind"` (new in 0.9.0) | Last, when the ingest fails. |
|
|
267
661
|
|
|
268
662
|
```text
|
|
269
663
|
id: 4
|
|
@@ -279,14 +673,32 @@ data: {"type":"ingest.finish","document":{"id":"doc_f6502d2f94694d709c7db2ec634c
|
|
|
279
673
|
`{ "message": "This file looks binary, not text. …", "status": 422, "code": "not_text" }`, and
|
|
280
674
|
isolated readers that are all busy `{ "message": "The server is reading other files right now. Try
|
|
281
675
|
again in a moment.", "status": 503, "code": "busy" }`, with no `Retry-After` (the headers are
|
|
282
|
-
sent). A store that failed is `{ "message": "
|
|
283
|
-
own message, which may name a host. An error with a status keeps it.
|
|
284
|
-
|
|
285
|
-
|
|
676
|
+
sent). A store that failed is `{ "message": "The document could not be stored. Try again.", "status": 503 }`
|
|
677
|
+
(since 0.9.0; it was `"Upload failed."` and 500), never the store's own message, which may name a host. An error with a status keeps it. `code` is new in 0.8.0, so that a
|
|
678
|
+
page can say why in its own words. Since 0.9.0 the library's own errors other than a refused file
|
|
679
|
+
also have their `name`: `"DocumentStoreError"` (with `"name"` added to the 503 above),
|
|
680
|
+
`"DocumentScopeError"` with its `code` (`{ "message": "This chat no longer exists.", "status":
|
|
681
|
+
404, "name": "DocumentScopeError", "code": "scope_missing" }`), and `"DocumentsNotFoundError"`.
|
|
682
|
+
A model's error (a `ModelRequestError`, or any error with a `kind`, from an ingest or a hook of
|
|
683
|
+
yours that asks a model) has its `kind`, as in the `EventError` of a question: `{ "message":
|
|
684
|
+
"The model failed on its side (HTTP 503).", "status": 502, "kind": "server" }`. Until 0.9.0 the
|
|
685
|
+
handler's `ingest.error` had no `kind`.
|
|
686
|
+
So [`errorInfoOf`](./errors-and-retries.md#errorinfooferror) reads `ingest.error` as the
|
|
687
|
+
handler answered the error: a store that failed, a chat that is gone, a model's error by its
|
|
688
|
+
kind, each with the status of the JSON answer. An error that is none of these is `"unknown"`
|
|
689
|
+
there, with its status (a hook of yours that threw a `409`). The event carries no wait
|
|
690
|
+
(`retryAfterMs`), and no system error's code for a store: the JSON answer's `Retry-After` and the
|
|
691
|
+
store's message hold them.
|
|
692
|
+
- **`onUploaded` runs before `ingest.finish`.** The event waits for it. When it throws, the
|
|
693
|
+
document is deleted, and the stream ends with `ingest.error` holding the error's answer instead
|
|
694
|
+
([the hooks](#the-hooks-onuploaded-and-onremoved)). New in 0.9.0.
|
|
286
695
|
- **The status is `200` whatever happens next.** Once the stream has started, a failure can only be
|
|
287
696
|
an `ingest.error` event.
|
|
288
|
-
- **A client that goes away stops the ingest**, as in step
|
|
289
|
-
is
|
|
697
|
+
- **A client that goes away stops the ingest**, as in step 7: nothing is stored, nothing more is
|
|
698
|
+
written, and a file of the spool or of `prepareUpload` is removed. A document stored before the
|
|
699
|
+
client left (the ingest had ended, and the events were still being written), or by an `ingest` of
|
|
700
|
+
your own that does not stop on its `signal`, still goes to `onUploaded`, once, with
|
|
701
|
+
`clientGone: true`, and the file of `prepareUpload` stays with it.
|
|
290
702
|
- **The handler still never rejects.**
|
|
291
703
|
|
|
292
704
|
How to read the stream in the browser: [web app](../guides/web-app.md#upload-with-progress).
|
|
@@ -294,48 +706,101 @@ How to read the stream in the browser: [web app](../guides/web-app.md#upload-wit
|
|
|
294
706
|
#### get(request, response, id)
|
|
295
707
|
|
|
296
708
|
The request: route `GET` to it; the handler does not check the method. `id` is the document ID,
|
|
297
|
-
taken from your route. Nothing else is read but what `getOwner`
|
|
709
|
+
taken from your route. Nothing else is read but what `getOwner` and `getScope` read. It calls
|
|
710
|
+
`files.getMeta(id, { owner, scope })`.
|
|
298
711
|
|
|
299
712
|
| Status | Body | When |
|
|
300
713
|
|---|---|---|
|
|
301
|
-
| `200` | The [`DocumentSummary`](./library.md#documentsummary) | The document is there, has not expired,
|
|
302
|
-
| `404` | `{ "error": "This file is no longer available." }` | `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner. |
|
|
303
|
-
|
|
|
304
|
-
|
|
|
305
|
-
| `
|
|
714
|
+
| `200` | The [`DocumentSummary`](./library.md#documentsummary) | The document is there, has not expired, has no owner or the owner `getOwner` returned, and has no scope or the scope `getScope` returned. |
|
|
715
|
+
| `404` | `{ "error": "This file is no longer available." }` | `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner or another scope. |
|
|
716
|
+
| `401` | `{ "error": "Sign in first." }` | The library has `requireOwner`, and `getOwner` returned `undefined` (or `null`). New in 0.9.0. |
|
|
717
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner` or `getScope` threw an error with that `status` or `statusCode`. |
|
|
718
|
+
| `503` | `{ "error": "The document store could not be read (EIO). Try again." }`, with `Retry-After: 5` | The store could not be read: the message of its [`DocumentStoreError`](./library.md#documentstoreerror), with the code of the system error behind it, when there is one. Since 0.9.0, the status of that error; before, `500` "The file could not be looked up (EIO).". `Retry-After` is new in 0.9.0. |
|
|
719
|
+
| `500` | `{ "error": "The file could not be looked up (empty owner)." }` | The library has `requireOwner`, and `getOwner` returned `""` or spaces only; "(owner is not a string)" for an object, as for the upload. `files.getMeta` is not called. New in 0.9.0. |
|
|
720
|
+
| `500` | `{ "error": "The file could not be looked up (invalid scope)." }` | `getScope` returned a scope that is not valid; "(no scope)" for none under `requireScope`. New in 0.9.0. |
|
|
721
|
+
| `500` | `{ "error": "The file could not be looked up." }` | `getOwner` or `getScope` threw an error without a status. |
|
|
306
722
|
|
|
307
723
|
#### remove(request, response, id)
|
|
308
724
|
|
|
309
725
|
The request: route `DELETE` to it; the handler does not check the method. `id` is the document
|
|
310
|
-
ID, taken from your route. It deletes the document through `files.delete
|
|
311
|
-
the store: its text, its index and any kept original, as far as your store's
|
|
726
|
+
ID, taken from your route. It deletes the document through `files.delete(id, { owner, scope })`,
|
|
727
|
+
which removes it from the store: its text, its index and any kept original, as far as your store's
|
|
728
|
+
`delete` does. Then it calls `onRemoved`, when the document was deleted.
|
|
312
729
|
|
|
313
730
|
| Status | Body | When |
|
|
314
731
|
|---|---|---|
|
|
315
|
-
| `200` | `{ "deleted": true }` | The document was deleted. |
|
|
316
|
-
| `200` | `{ "deleted": false }` | This owner has no such document: `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner. Also when the store's `delete` returned `false`. It never answers `404`. |
|
|
317
|
-
|
|
|
318
|
-
|
|
|
319
|
-
| `
|
|
732
|
+
| `200` | `{ "deleted": true }` | The document was deleted, and `onRemoved`, when there is one, did not throw. |
|
|
733
|
+
| `200` | `{ "deleted": false }` | This owner has no such document in this scope: `id` is not a document ID, was never uploaded, has expired or been deleted, or belongs to another owner or another scope. Also when the store's `delete` returned `false`. It never answers `404`. `onRemoved` is not called. |
|
|
734
|
+
| `401` | `{ "error": "Sign in first." }` | The library has `requireOwner`, and `getOwner` returned `undefined` (or `null`). New in 0.9.0. |
|
|
735
|
+
| 400 to 599 | `{ "error": <the error's message> }` | `getOwner`, `getScope` or `onRemoved` threw an error with that `status` or `statusCode`. When `onRemoved` threw, the document is deleted all the same. |
|
|
736
|
+
| `503` | `{ "error": "The document store could not be read (EIO). Try again." }`, with `Retry-After: 5` | The look-up before the delete could not read the store, as for `get`. Since 0.9.0. |
|
|
737
|
+
| `503` | `{ "error": "The document could not be deleted (EIO). Try again." }`, with `Retry-After: 5` | The store's `delete` failed: `files.delete` threw a `DocumentStoreError` of operation `"delete"`, with the code of the store's error when it has one. Since 0.9.0: it was `500` "The file could not be deleted (EIO).". |
|
|
738
|
+
| `500` | `{ "error": "The file could not be deleted (empty owner)." }` | The library has `requireOwner`, and `getOwner` returned `""` or spaces only; "(owner is not a string)" for an object, as for the upload. `files.delete` is not called. New in 0.9.0. |
|
|
739
|
+
| `500` | `{ "error": "The file could not be deleted (invalid scope)." }` | `getScope` returned a scope that is not valid; "(no scope)" for none under `requireScope`. New in 0.9.0. |
|
|
740
|
+
| `500` | `{ "error": "The file could not be deleted." }` | `getOwner`, `getScope` or `onRemoved` threw an error without a status. |
|
|
320
741
|
|
|
321
742
|
## How errors are answered
|
|
322
743
|
|
|
323
|
-
The three handlers answer an error by one rule
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
744
|
+
The three handlers answer an error by one rule, [`uploadAnswerOf`](#uploadansweroferror). Since
|
|
745
|
+
0.9.0 it reads the library's errors by their brand (`IngestError.is` and the others), so it also
|
|
746
|
+
knows them when another copy of the package made them:
|
|
747
|
+
|
|
748
|
+
| Error | Status | `{ "error": … }` |
|
|
749
|
+
|---|---|---|
|
|
750
|
+
| [`IngestError`](./library.md#ingesterror): a file that could not be read | Its `status`: 422, 413 for `"too_large"`, 409 for `"exists"`, 503 for `"busy"` (with `Retry-After`, its `retryAfterMs` in seconds) | Its message, written for the user. A `413` gets the size message of `upload`. A file of code `"unreadable"` gets "This file could not be read. It may be damaged, or not of the type its name says.": its message is a parser's, or an extractor's of your own (new in 0.9.0). |
|
|
751
|
+
| [`DocumentStoreError`](./library.md#documentstoreerror): the store failed | 503, with `Retry-After: 5` | Its message, which names what failed and a code, never a path or a host. |
|
|
752
|
+
| [`DocumentScopeError`](./library.md#documentscopeerror) `"scope_missing"`: the chat's folder is gone | 404 | "This chat no longer exists." |
|
|
753
|
+
| `DocumentScopeError` `"scope_invalid"` or `"scope_required"`: the server's mistake | 500 | What failed: "Upload failed.", "The file could not be looked up.", "The file could not be deleted." |
|
|
754
|
+
| A model's error (`ModelRequestError`, or any error with a `kind`) | The status of [`errorInfoOf`](./errors-and-retries.md#errorinfooferror) (429 for `"rate_limit"`, with `Retry-After` when the provider named a wait; 502, 503, 504, 413 or 500 for the others) | `errorInfoOf`'s words ("The model was busy (HTTP 429)."), never the provider's, which can name a project or a key. |
|
|
755
|
+
| Any other `Error` whose `status`, or else `statusCode`, is a whole number from 400 to 599 (`http-errors`) | That status. A `503` whose error has a `retryAfterMs` gets `Retry-After`. | Its message, or what failed when it is empty. |
|
|
756
|
+
| A Node system error (a `code` and a `syscall`), such as a path `ingest({ source: { path } })` does not read: a link (`ELOOP`), a folder (`EISDIR`), a pipe (`EINVAL`), a file that is not there (`ENOENT`), a volume that did not answer (`ETIMEDOUT`) | 500 | What failed, with the code: "Upload failed (ENOSPC).". Never the path, which Node's own messages name. The code is given only when it reads as one (capitals, digits and `_`); a host a driver put in `code` is left out: "Upload failed." (new in 0.9.0). |
|
|
757
|
+
| Anything else: a plain `Error`, a value that is not an `Error` | 500 | What failed: "Upload failed.". Never the error's own message, which can name paths and hosts of your server. |
|
|
758
|
+
|
|
759
|
+
Until 0.9.0, `upload` answered any `Error` from `files.ingest` without a status `422` with its
|
|
760
|
+
message, as a file that could not be read. A `LargeFiles` of your own whose `ingest` threw a
|
|
761
|
+
database driver's error sent its host to the browser (S12). A store that failed was answered
|
|
762
|
+
without `Retry-After`.
|
|
763
|
+
|
|
764
|
+
### uploadAnswerOf(error)
|
|
765
|
+
|
|
766
|
+
```ts
|
|
767
|
+
declare function uploadAnswerOf(error: unknown): UploadAnswer;
|
|
768
|
+
```
|
|
769
|
+
|
|
770
|
+
New in 0.9.0. The answer the upload handler gives an error, by the table above, for a route of your
|
|
771
|
+
own that ingests files: a multipart form, the Fetch API's `Request`, a job in the background. It
|
|
772
|
+
never throws, and reads the errors of every copy of the package. The upload limit's own message of
|
|
773
|
+
a `413` is not in it: say it yourself, or keep the error's.
|
|
774
|
+
|
|
775
|
+
```ts
|
|
776
|
+
import type { ServerResponse } from "node:http";
|
|
777
|
+
import { uploadAnswerOf } from "llm-large-files/node";
|
|
778
|
+
|
|
779
|
+
/** Answers an error of files.ingest as createDocumentHandlers would. */
|
|
780
|
+
export function answerUploadError(response: ServerResponse, error: unknown): void {
|
|
781
|
+
const { status, error: message, code, retryAfterMs } = uploadAnswerOf(error);
|
|
782
|
+
if (status >= 500) console.error("An upload failed", error); // the error itself, for your log
|
|
783
|
+
const headers: Record<string, string> = { "Content-Type": "application/json; charset=utf-8" };
|
|
784
|
+
if (retryAfterMs !== undefined) headers["Retry-After"] = String(Math.max(1, Math.ceil(retryAfterMs / 1_000)));
|
|
785
|
+
response.writeHead(status, headers).end(JSON.stringify({ error: message, ...(code ? { code } : {}) }));
|
|
786
|
+
}
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
### `UploadAnswer`
|
|
790
|
+
|
|
791
|
+
```ts
|
|
792
|
+
type UploadAnswer = { status: number; error: string; code?: IngestErrorCode; retryAfterMs?: number };
|
|
793
|
+
```
|
|
794
|
+
|
|
795
|
+
| Field | What it holds |
|
|
796
|
+
|---|---|
|
|
797
|
+
| `status` | The HTTP status: 400 to 599. |
|
|
798
|
+
| `error` | The message of the JSON body, `{ "error": … }`. Safe to show: it never holds a path, a host or a provider's words. An `"unreadable"` file is told in fixed words, as `errorInfoOf` tells it (new in 0.9.0). What it does hold is the message of an error that has a `status` (one your hooks threw) and of an `IngestError` of another code: keep hosts out of those. |
|
|
799
|
+
| `code` | For an `IngestError`: its code (`"too_large"`, `"busy"`…). |
|
|
800
|
+
| `retryAfterMs` | How long to wait before trying again, for the `Retry-After` header: 5,000 for a store that failed, an `IngestError`'s own for `"busy"`, a model's for a rate limit. |
|
|
801
|
+
|
|
802
|
+
To word an error in your users' language rather than with these messages, use
|
|
803
|
+
[`errorInfoOf`](./errors-and-retries.md#errorinfooferror) from the main entry.
|
|
339
804
|
|
|
340
805
|
Guide: [errors and reliability](../guides/errors-and-reliability.md), for the errors of a question
|
|
341
806
|
itself; [web app](../guides/web-app.md), for what to show in the browser.
|
|
@@ -389,9 +854,18 @@ What happens to a file of one of its formats:
|
|
|
389
854
|
as `"busy"`.
|
|
390
855
|
2. Its bytes are copied to a child process, with its name, MIME type, format and the limits of
|
|
391
856
|
`createLargeFiles` (`maxTextBytes`, `maxPdfPages`, `scannedPdfPages`). The child reads it with the
|
|
392
|
-
built-in extractor of its format, and sends its progress and then its text back.
|
|
857
|
+
built-in extractor of its format, and sends its progress and then its text back. A file ingested
|
|
858
|
+
from a path ([`IngestFromSource`](./library.md#ingestfromsource), new in 0.9.0) is sent as its
|
|
859
|
+
path instead, made absolute when `ingest` was called (the child's own working folder plays no
|
|
860
|
+
part): the extractors have `readsPath`, so the child reads the file itself, once, at most
|
|
861
|
+
`maxUploadBytes + 1` bytes (a larger one is refused as `"too_large"`), opened without following
|
|
862
|
+
a link at its name, and sends back its size and SHA-256 with the text. The server reads none of
|
|
863
|
+
the file, and holds none of it while it waits for a child. When the store keeps a copy of the
|
|
864
|
+
file (`keepOriginals` without `IngestInput.original`), the server reads it, and the bytes are
|
|
865
|
+
sent as before.
|
|
393
866
|
3. The rest of the ingest runs in your server, as without it: the text is normalized, profiled,
|
|
394
|
-
indexed and stored. A file costs its bytes copied to the child and its text
|
|
867
|
+
indexed and stored. A file costs its bytes copied to the child (none from a path) and its text
|
|
868
|
+
copied back.
|
|
395
869
|
4. A child reads one file at a time. It is replaced by a new one after `maxFilesPerChild` files,
|
|
396
870
|
since some parsers keep memory for the life of their process (`@cantoo/pdf-lib` keeps every name
|
|
397
871
|
it reads), and stopped after `idleMs` with nothing to read. An idle child does not keep your
|
|
@@ -414,6 +888,10 @@ numbers in its message:
|
|
|
414
888
|
| `"unreadable"` | `report.pdf could not be read: its reader stopped (SIGSEGV).`, or `(exit code 1)` | The child ended another way. |
|
|
415
889
|
| `"unreadable"` | `report.pdf could not be read: its reader could not be reached.` | The file could not be sent to the child. |
|
|
416
890
|
|
|
891
|
+
The upload handler answers a file of code `"unreadable"` with fixed words, not these messages
|
|
892
|
+
(new in 0.9.0): "This file could not be read. It may be damaged, or not of the type its name says."
|
|
893
|
+
The messages stay on the error, for your log.
|
|
894
|
+
|
|
417
895
|
A child that stops before it is ready to read, so before it was sent the file, is the server's
|
|
418
896
|
trouble, not the file's: a `childScript` that is not there, an `execArgv` that Node does not know.
|
|
419
897
|
Such a file is refused with an `Error` that is not an `IngestError`, with `status` 500:
|
|
@@ -439,7 +917,7 @@ server, and the code of its words: a zip bomb or a PDF that would hold the serve
|
|
|
439
917
|
PDF without text `"no_text"`, and so on ([`IngestError`](./library.md#ingesterror)).
|
|
440
918
|
|
|
441
919
|
**The heap limit.** Each child runs with `--max-old-space-size` set to `maxHeapMb`, and Node adds
|
|
442
|
-
its young generation above it: with 512, a heap limit of 560 MB on Node
|
|
920
|
+
its young generation above it: with 512, a heap limit of 560 MB on Node 22, 704 MB on Node
|
|
443
921
|
24 and 608 MB on Node 26 ([Deployment](../guides/deployment.md#memory-on-each-server)). The
|
|
444
922
|
server's own `NODE_OPTIONS` are not passed to the children: a `--max-old-space-size` there would
|
|
445
923
|
replace this one. The rest of its environment is. The limit bounds the heap only: what a parser
|
|
@@ -468,7 +946,7 @@ type IsolatedExtractorOptions = {
|
|
|
468
946
|
|---|---|---|---|
|
|
469
947
|
| `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
948
|
| `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. |
|
|
949
|
+
| `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
950
|
| `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
951
|
| `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
952
|
| `pdf` | [`PdfExtractorOptions`](./library.md#pdfextractoroptions) | `{}` | Options of the built-in PDF extractor in the children, as for [`createPdfExtractor`](./library.md#createpdfextractoroptions). |
|
|
@@ -496,10 +974,59 @@ type IsolatedExtractors = {
|
|
|
496
974
|
|
|
497
975
|
| Member | What it is |
|
|
498
976
|
|---|---|
|
|
499
|
-
| `extractors` | One extractor for each of `formats`, to pass to `createLargeFiles({ extractors })`. To add one of your own for another format: `{ ...isolated.extractors, text: myText }`. |
|
|
977
|
+
| `extractors` | One extractor for each of `formats`, to pass to `createLargeFiles({ extractors })`. Each has `readsPath: true` (new in 0.9.0): a file ingested from a path is read by the child. A wrapper of one (as above) reads no paths unless it sets `readsPath` too and passes `ExtractInput` on as it is. To add one of your own for another format: `{ ...isolated.extractors, text: myText }`. |
|
|
500
978
|
| `stats()` | The files being read (`running`), the files waiting (`queued`) and the child processes alive (`children`): for a health check or a metric. |
|
|
501
979
|
| `close()` | Kills every child process, and refuses the files waiting, those being read and those sent while it runs as `"busy"` ("The server is shutting down. Try again in a moment."). Resolves once the children have exited, also when nothing else keeps your process open, so code after `await isolated.close()` runs. Files sent after that start new children. Call it when the server stops, next to the server's own `close()`: a SIGTERM listener replaces Node's own exit ([above](#createisolatedextractorsoptions)). |
|
|
502
980
|
|
|
981
|
+
## Uploads your application keeps
|
|
982
|
+
|
|
983
|
+
### fileOriginals(root)
|
|
984
|
+
|
|
985
|
+
```ts
|
|
986
|
+
declare function fileOriginals(root: string): OriginalsReader;
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
New in 0.9.0. Reads back the uploads your application keeps under the folder `root`, by their ref
|
|
990
|
+
(`IngestInput.original.ref`), for `createLargeFiles({ originals })`
|
|
991
|
+
([`OriginalsReader`](./library.md#originalsreader)). With it, a kept PDF is read from your upload,
|
|
992
|
+
not from a second copy in the store.
|
|
993
|
+
|
|
994
|
+
```ts
|
|
995
|
+
import path from "node:path";
|
|
996
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
997
|
+
import { fileOriginals } from "llm-large-files/node";
|
|
998
|
+
|
|
999
|
+
const VOLUME = process.env.DOCUMENTS_DIR!;
|
|
1000
|
+
const files = createLargeFiles({
|
|
1001
|
+
store: new FileDocumentStore(VOLUME, { scopes: { depth: 2 } }),
|
|
1002
|
+
keepOriginals: ["pdf"],
|
|
1003
|
+
originals: fileOriginals(VOLUME),
|
|
1004
|
+
});
|
|
1005
|
+
|
|
1006
|
+
// Your route saved the upload at <VOLUME>/user-42/chat-7/uploads/upload-3f9a.
|
|
1007
|
+
const ref = "user-42/chat-7/uploads/upload-3f9a";
|
|
1008
|
+
await files.ingest({ name: "report.pdf", source: { path: path.join(VOLUME, ref) }, original: { ref }, owner: "user-42", scope: ["user-42", "chat-7"], id: "upload-3f9a" });
|
|
1009
|
+
```
|
|
1010
|
+
|
|
1011
|
+
- A ref is a path relative to `root`. One that leads out of it (an absolute path elsewhere, `..`
|
|
1012
|
+
that climbs out), or that is empty, longer than 1,024 characters or holds a NUL, throws
|
|
1013
|
+
`TypeError("The ref of an original must be a relative path to a file inside the folder of fileOriginals.")`.
|
|
1014
|
+
The library passes it on as a `DocumentStoreError` with that `TypeError` as `cause`. The message
|
|
1015
|
+
does not repeat the ref.
|
|
1016
|
+
- No link below `root` is followed, at any level: the real path of the file must be the path the
|
|
1017
|
+
ref names, under the real path of `root`. A file reached through a link reads as missing
|
|
1018
|
+
(`undefined`), as does one that is not there, or a folder. `root` itself may be a link. The file
|
|
1019
|
+
is opened without following a link at its name, where the platform can (not on Windows), which
|
|
1020
|
+
closes the moment between the check and the read for the file itself; a folder swapped for a
|
|
1021
|
+
link in that moment is not seen.
|
|
1022
|
+
- A file is read once, and no more than one byte past the size it had at ingest
|
|
1023
|
+
(`OriginalReadContext.bytes`): a file that has grown is not read whole, and the library finds it
|
|
1024
|
+
changed.
|
|
1025
|
+
- It only reads. It never writes, moves or deletes a file: removing the uploads, with their chat or
|
|
1026
|
+
on your own schedule, is yours to do.
|
|
1027
|
+
- Errors other than a file that is not there (`EACCES`, `EIO`) are thrown as they are, and the
|
|
1028
|
+
library passes them on as a `DocumentStoreError`.
|
|
1029
|
+
|
|
503
1030
|
## Server-Sent Events
|
|
504
1031
|
|
|
505
1032
|
New in 0.7.0. Two functions send the events of a question (`askStream`, or
|
|
@@ -639,11 +1166,13 @@ It returns `{ event: <type>, id: <seq>, data }`. The `data` is the event itself,
|
|
|
639
1166
|
|
|
640
1167
|
| Event | `data` |
|
|
641
1168
|
|---|---|
|
|
642
|
-
| `run.finish` | `{ type, seq, runId, time, result }`, where `result` holds only `answered`, `text`, `finishReason`, `blockReason`, `steps`, `evidence`, `turns` and `
|
|
643
|
-
| `run.error` | `{ type, seq, runId, time, error, partial }`, where `error` is the event's [`EventError`](./events.md#errors-eventerror) and `partial` holds only `steps`, `evidence` and `
|
|
644
|
-
| Any other event, ingest events included | The event as it is. |
|
|
1169
|
+
| `run.finish` | `{ type, seq, runId, time, result }`, where `result` holds only `answered`, `text`, `finishReason`, `blockReason`, `steps`, `evidence`, `turns`, `usage` and `missing`. Not `toolTurns`, `plan`, `budget` or `lastUsage`. |
|
|
1170
|
+
| `run.error` | `{ type, seq, runId, time, error, partial }`, where `error` is the event's [`EventError`](./events.md#errors-eventerror) and `partial` holds only `steps`, `evidence`, `usage` and `missing` of the partial result. Without a partial result, `partial` is left out of the JSON. |
|
|
1171
|
+
| Any other event, ingest events included | The event as it is: a notice's `documentIds` and `ingest.finish`'s `app` included. |
|
|
645
1172
|
|
|
646
|
-
A field that is `undefined`, such as `finishReason` or `
|
|
1173
|
+
A field that is `undefined`, such as `finishReason`, `blockReason` or `missing`, is left out of the
|
|
1174
|
+
JSON. `missing` lists the documents a question answered without (`onMissingDocuments: "drop"`); it
|
|
1175
|
+
is sent since 0.9.0, as `AskResult.missing` is new in 0.9.0.
|
|
647
1176
|
|
|
648
1177
|
`toolTurns` are left out even when the question ran with `eventResults: true`: keep them on the
|
|
649
1178
|
server, from the stream's `result` or from `partialResultOf(error)`
|