@yaks/blob 0.0.0-stage ā 0.2.36
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/LICENSE +202 -0
- package/README.md +946 -2
- package/_dist/accepts.d.ts +38 -0
- package/_dist/accepts.d.ts.map +1 -0
- package/_dist/artifact.d.ts +29 -0
- package/_dist/artifact.d.ts.map +1 -0
- package/_dist/attachment.d.ts +53 -0
- package/_dist/attachment.d.ts.map +1 -0
- package/_dist/backend.d.ts +20 -0
- package/_dist/backend.d.ts.map +1 -0
- package/_dist/broken.d.ts +24 -0
- package/_dist/broken.d.ts.map +1 -0
- package/_dist/browser.d.ts +27 -0
- package/_dist/browser.d.ts.map +1 -0
- package/_dist/compare.d.ts +4 -0
- package/_dist/compare.d.ts.map +1 -0
- package/_dist/content_type.d.ts +20 -0
- package/_dist/content_type.d.ts.map +1 -0
- package/_dist/graph.d.ts +13 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/hydrate.d.ts +36 -0
- package/_dist/hydrate.d.ts.map +1 -0
- package/_dist/identify.d.ts +7 -0
- package/_dist/identify.d.ts.map +1 -0
- package/_dist/image.d.ts +37 -0
- package/_dist/image.d.ts.map +1 -0
- package/_dist/keywords.d.ts +10 -0
- package/_dist/keywords.d.ts.map +1 -0
- package/_dist/mime.d.ts +2 -0
- package/_dist/mime.d.ts.map +1 -0
- package/_dist/mod.d.ts +97 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/object-put.d.ts +2 -0
- package/_dist/object-put.d.ts.map +1 -0
- package/_dist/object.d.ts +175 -0
- package/_dist/object.d.ts.map +1 -0
- package/_dist/parts.d.ts +91 -0
- package/_dist/parts.d.ts.map +1 -0
- package/_dist/plugin.d.ts +38 -0
- package/_dist/plugin.d.ts.map +1 -0
- package/_dist/png.d.ts +14 -0
- package/_dist/png.d.ts.map +1 -0
- package/_dist/props.d.ts +20 -0
- package/_dist/props.d.ts.map +1 -0
- package/_dist/representation.d.ts +17 -0
- package/_dist/representation.d.ts.map +1 -0
- package/_dist/representation_rules.d.ts +3 -0
- package/_dist/representation_rules.d.ts.map +1 -0
- package/_dist/routes.d.ts +65 -0
- package/_dist/routes.d.ts.map +1 -0
- package/_dist/serve.d.ts +29 -0
- package/_dist/serve.d.ts.map +1 -0
- package/_dist/sha256.d.ts +26 -0
- package/_dist/sha256.d.ts.map +1 -0
- package/_dist/sqlite.d.ts +57 -0
- package/_dist/sqlite.d.ts.map +1 -0
- package/_dist/store.d.ts +41 -0
- package/_dist/store.d.ts.map +1 -0
- package/_dist/stream.d.ts +91 -0
- package/_dist/stream.d.ts.map +1 -0
- package/_dist/upload.d.ts +114 -0
- package/_dist/upload.d.ts.map +1 -0
- package/_dist/value.d.ts +62 -0
- package/_dist/value.d.ts.map +1 -0
- package/_dist/vocab.d.ts +13 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/accepts.js +76 -0
- package/accepts.js.map +1 -0
- package/accepts.ts +95 -0
- package/artifact.js +50 -0
- package/artifact.js.map +1 -0
- package/artifact.ts +93 -0
- package/attachment.js +190 -0
- package/attachment.js.map +1 -0
- package/attachment.ts +201 -0
- package/backend.js +37 -0
- package/backend.js.map +1 -0
- package/backend.ts +44 -0
- package/broken.js +278 -0
- package/broken.js.map +1 -0
- package/broken.ts +217 -0
- package/browser.js +124 -0
- package/browser.js.map +1 -0
- package/browser.ts +179 -0
- package/compare.js +82 -0
- package/compare.js.map +1 -0
- package/compare.ts +90 -0
- package/content_type.js +43 -0
- package/content_type.js.map +1 -0
- package/content_type.ts +58 -0
- package/deno.json +1 -0
- package/fixed.js +53 -0
- package/fixed.js.map +1 -0
- package/fixed.ts +61 -0
- package/graph.js +15 -0
- package/graph.js.map +1 -0
- package/graph.ts +22 -0
- package/hydrate.js +69 -0
- package/hydrate.js.map +1 -0
- package/hydrate.ts +72 -0
- package/identify.js +38 -0
- package/identify.js.map +1 -0
- package/identify.ts +50 -0
- package/image.js +111 -0
- package/image.js.map +1 -0
- package/image.ts +120 -0
- package/keywords.js +28 -0
- package/keywords.js.map +1 -0
- package/keywords.ts +28 -0
- package/meta/blob.vocab.json +17 -0
- package/mime.js +72 -0
- package/mime.js.map +1 -0
- package/mime.ts +73 -0
- package/mod.js +97 -0
- package/mod.js.map +1 -0
- package/mod.ts +115 -0
- package/object-put.js +90 -0
- package/object-put.js.map +1 -0
- package/object-put.ts +114 -0
- package/object.js +369 -0
- package/object.js.map +1 -0
- package/object.ts +592 -0
- package/package.json +84 -4
- package/parts.js +354 -0
- package/parts.js.map +1 -0
- package/parts.ts +423 -0
- package/plugin.js +158 -0
- package/plugin.js.map +1 -0
- package/plugin.ts +184 -0
- package/png.js +74 -0
- package/png.js.map +1 -0
- package/png.ts +58 -0
- package/props.js +32 -0
- package/props.js.map +1 -0
- package/props.ts +47 -0
- package/purge.js +65 -0
- package/purge.js.map +1 -0
- package/purge.ts +72 -0
- package/representation.js +34 -0
- package/representation.js.map +1 -0
- package/representation.ts +44 -0
- package/representation_rules.js +44 -0
- package/representation_rules.js.map +1 -0
- package/representation_rules.ts +57 -0
- package/routes.js +454 -0
- package/routes.js.map +1 -0
- package/routes.ts +575 -0
- package/serve.js +196 -0
- package/serve.js.map +1 -0
- package/serve.ts +242 -0
- package/sha256.js +185 -0
- package/sha256.js.map +1 -0
- package/sha256.ts +210 -0
- package/sqlite.js +201 -0
- package/sqlite.js.map +1 -0
- package/sqlite.ts +250 -0
- package/store.js +40 -0
- package/store.js.map +1 -0
- package/store.ts +93 -0
- package/stream.js +203 -0
- package/stream.js.map +1 -0
- package/stream.ts +256 -0
- package/upload.js +256 -0
- package/upload.js.map +1 -0
- package/upload.ts +404 -0
- package/value.js +234 -0
- package/value.js.map +1 -0
- package/value.ts +281 -0
- package/vocab.js +27 -0
- package/vocab.js.map +1 -0
- package/vocab.json +123 -0
- package/vocab.ts +32 -0
package/README.md
CHANGED
|
@@ -1,3 +1,947 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yaks/blob
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Stores text and binary content under SHA-256 addresses, with transparent graph
|
|
4
|
+
text reads and writes, verified artifacts and HTTP responses. Text lives in a
|
|
5
|
+
separate table, directory or object store, and identical values share content.
|
|
6
|
+
|
|
7
|
+
An **address** is the lowercase hexadecimal SHA-256 of content's bytes, such as
|
|
8
|
+
`address('hello')`. A **body** is a string
|
|
9
|
+
[property](../graph/README.md#data-model) marked `store: 'blob'` in the
|
|
10
|
+
[vocabulary](../vocab/README.md#vocabulary). A **Blobs** store holds bytes under
|
|
11
|
+
their addresses and exposes `has`, `get` and `put`; these methods may return
|
|
12
|
+
values or promises.
|
|
13
|
+
|
|
14
|
+
An **artifact** describes stored bytes with `{ address, media_type, size }`. A
|
|
15
|
+
**representation** fixes how an address is served: its scope, media type and
|
|
16
|
+
optional filename determine its immutable identity and URL. An **attachment** is
|
|
17
|
+
a [component](../graph/README.md#data-model) referencing an artifact, with
|
|
18
|
+
optional filename, audience and generation metadata.
|
|
19
|
+
|
|
20
|
+
Graph writes use [bundles and transactions](../graph/README.md#data-model); this
|
|
21
|
+
package supplies a [plugin](../graph/README.md#data-model) that stores bodies.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
deno add jsr:@yaks/blob
|
|
27
|
+
# or: npx jsr add @yaks/blob
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Store a body
|
|
31
|
+
|
|
32
|
+
Register `blobKeywords` when loading the vocabulary, then configure the write
|
|
33
|
+
plugin and SQL read expressions on the same SQLite driver. Without that keyword
|
|
34
|
+
registration, `bodies()` returns no bodies and the plugin leaves text unchanged:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { equal } from '@yaks/testing'
|
|
38
|
+
import { loadVocab } from '@yaks/vocab'
|
|
39
|
+
import { graph } from '@yaks/graph'
|
|
40
|
+
import { storage } from '@yaks/sqlite'
|
|
41
|
+
import { open } from '@yaks/sqlite/db'
|
|
42
|
+
import {
|
|
43
|
+
address,
|
|
44
|
+
blobKeywords,
|
|
45
|
+
blobRead,
|
|
46
|
+
blobs,
|
|
47
|
+
blobSchema,
|
|
48
|
+
bodies,
|
|
49
|
+
sqliteBlobs,
|
|
50
|
+
} from '@yaks/blob'
|
|
51
|
+
|
|
52
|
+
let post = {
|
|
53
|
+
component: true,
|
|
54
|
+
type: 'object',
|
|
55
|
+
properties: { body: { type: 'string', store: 'blob' } },
|
|
56
|
+
}
|
|
57
|
+
let vocab = loadVocab([{ $defs: { post } }], [blobKeywords])
|
|
58
|
+
equal(bodies(vocab), [{ comp: 'post', prop: 'body' }])
|
|
59
|
+
let driver = open(':memory:')
|
|
60
|
+
let store = storage(driver, vocab, { derived: blobRead(vocab) })
|
|
61
|
+
let bytes = sqliteBlobs(store.statements)
|
|
62
|
+
for (let statement of [...store.ddl(), ...blobSchema()]) {
|
|
63
|
+
driver.query(statement)
|
|
64
|
+
}
|
|
65
|
+
let g = graph({ storage: store, vocab, plugins: [blobs(vocab, bytes)] })
|
|
66
|
+
|
|
67
|
+
g.apply([{ entity: { eid: 'p1' }, post: { body: 'A long essay.' } }])
|
|
68
|
+
equal(store.read('.post')[0].post, { body: 'A long essay.' })
|
|
69
|
+
equal(
|
|
70
|
+
new TextDecoder().decode(bytes.get(address('A long essay.'))!),
|
|
71
|
+
'A long essay.',
|
|
72
|
+
)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
The component table contains the address; `blob_text` contains the text. Both
|
|
76
|
+
use the same driver so their writes participate in the same transaction. Since
|
|
77
|
+
only this plugin reads an address back as text, a store it wrote requires it: a
|
|
78
|
+
host records that, and refuses the store to a config without @yaks/blob
|
|
79
|
+
([required plugins](../host/README.md#required-plugins)).
|
|
80
|
+
|
|
81
|
+
## Exports
|
|
82
|
+
|
|
83
|
+
| Root export | Purpose |
|
|
84
|
+
| ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- |
|
|
85
|
+
| `blobKeywords`, `BLOB_URI` | Register the `store` and `address` keywords |
|
|
86
|
+
| `Body`, `bodies`, `isBody`, `holders` | Select marked properties |
|
|
87
|
+
| `blobs`, `BlobOpts`, `Reference` | Graph write plugin and optional stored-reference mapping |
|
|
88
|
+
| `Blobs`, `memoryBlobs`, `address`, `encode`, `decode` | Store interface and text addressing |
|
|
89
|
+
| `sqliteBlobs`, `blobSchema`, `dropSql`, `Layout` | SQLite text storage |
|
|
90
|
+
| `objectBlobs`, `Bucket`, `patient` | Object storage |
|
|
91
|
+
| `Objects`, `Opened`, `Loaded`, `bucketObjects`, `prefixed` | A bucket keyed by name: read, delete, list |
|
|
92
|
+
| `parts`, `purgeParts`, `Multipart`, `Assembly`, `memoryMultipart`, `sized`, `Gone`, `Wrong`, `MOST`, `MiB` | Resumable uploads in parts, checked against their hash |
|
|
93
|
+
| `hasher`, `fold`, `START` | SHA-256 carried from one piece of bytes to the next |
|
|
94
|
+
| `Accepts`, `acceptsErrors`, `fits`, `takes`, `taken` | Which blobs an application takes, by size and media type |
|
|
95
|
+
| `blobRead`, `hydrate` | SQL and post-read text resolution |
|
|
96
|
+
| `Artifact`, `ArtifactStore`, `addressOf`, `keep`, `artifactBytes`, `artifactDoc` | Artifact storage, verified reads and declarations |
|
|
97
|
+
| `Size`, `sizeOf`, `mediaTypeOf`, `mediaType`, `matchesMediaType`, `mimeOf` | Image dimensions, signatures and media types |
|
|
98
|
+
| `Served`, `served`, `servedOpen`, `servedVia`, `ranged`, `rangedOpen`, `validator`, `matches` | HTTP responses, streaming and validators |
|
|
99
|
+
| `Representation`, `representation`, `represents`, `addressed`, `representations` | Immutable representations and their graph plugin |
|
|
100
|
+
| `valueTools`, `valueRange`, `valueSearch`, `VALUE_LIMIT`, `ValueTool` | Bounded text-inspection tools |
|
|
101
|
+
|
|
102
|
+
| Sub-module export | Purpose |
|
|
103
|
+
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
104
|
+
| `@yaks/blob/vocab` | `docs`, `keywords`, `derived` and declaration/read helpers |
|
|
105
|
+
| `@yaks/blob/graph` | `plugins(host)`: the graph plugin over the host's blob store, and `required`: a store it wrote requires it |
|
|
106
|
+
| `@yaks/blob/routes` | `routes(host, options)` and route settings |
|
|
107
|
+
| `@yaks/blob/identify` | `contentType`, `artifactStore`: host byte detection and artifact storage |
|
|
108
|
+
| `@yaks/blob/backend` | `Backend`, `backend`: a configured artifact backend, its directory store given by the host |
|
|
109
|
+
| `@yaks/blob/store` | `Blobs`, `memoryBlobs()`, `address`: the store shape and the memory store, without the rest of the package |
|
|
110
|
+
| `@yaks/blob/serve` | the HTTP responses above, `matches` among them, without the rest of the package |
|
|
111
|
+
| `@yaks/blob/attachment` | `attachmentRows`, `attachmentOf`, `artifactsOf`, `attachmentsSeen`: a file's artifact and its use beside each message, and a reader shown only the attachments a clause admits |
|
|
112
|
+
| `@yaks/blob/upload` | `filed`, `described`, `admit`, `Untaken`, `useOf`, `servable`, `Naming`: an upload's write half and the words its rows speak |
|
|
113
|
+
|
|
114
|
+
## Addresses
|
|
115
|
+
|
|
116
|
+
`address(text)` computes the lowercase hexadecimal SHA-256 of UTF-8 text
|
|
117
|
+
synchronously using `@yaks/graph`'s digest. `addressOf(bytes)` computes the same
|
|
118
|
+
kind of address for arbitrary bytes using asynchronous `crypto.subtle.digest`.
|
|
119
|
+
`encode()` and `decode()` convert between strings and UTF-8 bytes.
|
|
120
|
+
|
|
121
|
+
The low-level store interface expects a valid address supplied by the caller; it
|
|
122
|
+
does not itself prove that bytes match that address. `artifactStore()` computes
|
|
123
|
+
addresses, and `keep()` verifies stored content. Use these helpers when storing
|
|
124
|
+
binary artifacts rather than assuming every backend validates keys and data.
|
|
125
|
+
|
|
126
|
+
```ts
|
|
127
|
+
import { equal } from '@yaks/testing'
|
|
128
|
+
import { address, addressOf, decode, encode, memoryBlobs } from '@yaks/blob'
|
|
129
|
+
|
|
130
|
+
let bytes = encode('Hello')
|
|
131
|
+
let sha = address('Hello')
|
|
132
|
+
equal(await addressOf(bytes), sha)
|
|
133
|
+
let store = memoryBlobs()
|
|
134
|
+
store.put(sha, bytes)
|
|
135
|
+
equal(store.has(sha), true)
|
|
136
|
+
equal(decode(store.get(sha)!), 'Hello')
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## When the swap happens
|
|
140
|
+
|
|
141
|
+
A **Reference** is a function that translates an address into the value a
|
|
142
|
+
component row holds, usually the address itself; `BlobOpts.reference` can
|
|
143
|
+
instead supply an integer key. `BlobOpts.props` narrows the bodies the plugin
|
|
144
|
+
handles.
|
|
145
|
+
|
|
146
|
+
The plugin replaces each body with the value its Reference returns during
|
|
147
|
+
`precondition`, inside the transaction and after the graph's `$was` guard checks
|
|
148
|
+
the text the caller read. It restores text in the bundles returned from
|
|
149
|
+
`apply()` during `commit`.
|
|
150
|
+
|
|
151
|
+
External stores keep their content during `prepare`, before the graph takes its
|
|
152
|
+
write lock. Preparation leaves text intact for the guard and carries the results
|
|
153
|
+
of Reference on the bundles. A later graph failure or dry run can leave
|
|
154
|
+
unreferenced content in these stores, as their writes cannot roll back with the
|
|
155
|
+
graph.
|
|
156
|
+
|
|
157
|
+
`sqliteBlobs` declares `transactional: true`: its inserts stay in `precondition`
|
|
158
|
+
and commit or roll back with the component rows on the same active connection.
|
|
159
|
+
`mutate` hooks run after storage has received component rows, too late to swap.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import { equal } from '@yaks/testing'
|
|
163
|
+
import { graph } from '@yaks/graph'
|
|
164
|
+
import { ram } from '@yaks/ram'
|
|
165
|
+
import { loadVocab } from '@yaks/vocab'
|
|
166
|
+
import { blobKeywords, blobs, memoryBlobs } from '@yaks/blob'
|
|
167
|
+
|
|
168
|
+
let body = { type: 'string', store: 'blob' }
|
|
169
|
+
let post = {
|
|
170
|
+
component: true,
|
|
171
|
+
type: 'object',
|
|
172
|
+
properties: { body, caption: body },
|
|
173
|
+
}
|
|
174
|
+
let vocab = loadVocab([{ $defs: { post } }], [blobKeywords])
|
|
175
|
+
let db = ram(vocab)
|
|
176
|
+
let plugin = blobs(vocab, memoryBlobs(), {
|
|
177
|
+
props: [{ comp: 'post', prop: 'body' }],
|
|
178
|
+
reference: () => 7,
|
|
179
|
+
})
|
|
180
|
+
let g = graph({ storage: db, vocab, plugins: [plugin] })
|
|
181
|
+
let [written] = await g.apply([
|
|
182
|
+
{ entity: { eid: 'p1' }, post: { body: 'Essay', caption: 'Caption' } },
|
|
183
|
+
])
|
|
184
|
+
equal(written.post, { body: 'Essay', caption: 'Caption' })
|
|
185
|
+
equal((await db.read('.post'))[0].post, { body: 7, caption: 'Caption' })
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
A custom Reference needs a matching read resolver; `hydrate()` resolves
|
|
189
|
+
addresses, while `blobRead()` resolves the keys in its Layout.
|
|
190
|
+
|
|
191
|
+
## Blobs stores
|
|
192
|
+
|
|
193
|
+
Methods can return values or promises. Synchronous storage preserves synchronous
|
|
194
|
+
graph writes; an asynchronous backend makes those writes asynchronous.
|
|
195
|
+
|
|
196
|
+
| Backend | Storage | Return style |
|
|
197
|
+
| ---------------------------------- | ---------------------------------------------------------- | ------------- |
|
|
198
|
+
| `sqliteBlobs(statements, layout?)` | A SQL table, default `blob_text(sha, value)` | Sync or async |
|
|
199
|
+
| `fileBlobs(dir)` | One file per address at `<dir>/<sha>` | Asynchronous |
|
|
200
|
+
| `objectBlobs(bucket, prefix?)` | Objects accessed through `head`, `get`, `put` and `delete` | Asynchronous |
|
|
201
|
+
| `memoryBlobs()` | This process's memory, while it runs | Synchronous |
|
|
202
|
+
|
|
203
|
+
`sqliteBlobs` stores text and rejects bytes that are not valid UTF-8. Its
|
|
204
|
+
inserts use `insert or ignore`. Writes use the SQL store's atomic boundary,
|
|
205
|
+
sharing the graph's transaction or waiting asynchronously for another writer.
|
|
206
|
+
`sqliteBlobs(statements, layout, reader)` can send committed reads to another
|
|
207
|
+
connection; `statements.inside()` keeps transaction reads on their owner.
|
|
208
|
+
`blobSchema(layout?)` returns its DDL statements. A **Layout** names the SQL
|
|
209
|
+
table and columns holding body text. It can rename `table`, `key` and `value`,
|
|
210
|
+
whose defaults are `blob_text`, `sha` and `value`. Existing tables must have the
|
|
211
|
+
matching shape.
|
|
212
|
+
|
|
213
|
+
`fileBlobs` comes from `@yaks/file/blobs`, beside the filesystem boundary, so a
|
|
214
|
+
Worker or a browser tab never loads it. It creates the directory on the first
|
|
215
|
+
write, and reads return `undefined` on filesystem errors. Pass only validated
|
|
216
|
+
SHA-256 addresses to this low-level adapter: it joins the supplied key directly
|
|
217
|
+
to the directory path.
|
|
218
|
+
|
|
219
|
+
A **Bucket** supplies object storage operations (`head`, `get`, `put`, `delete`
|
|
220
|
+
and `list`). `objectBlobs` accepts its `head`, `get` and `put` methods.
|
|
221
|
+
Cloudflare R2 bindings satisfy that interface; other object storage clients may
|
|
222
|
+
need a wrapper. Its `open(sha)` reads object metadata first, then streams only a
|
|
223
|
+
requested byte span. The package imports no cloud SDK.
|
|
224
|
+
|
|
225
|
+
Both stores send every bucket call through `patient(call)`, which sends it again
|
|
226
|
+
with a jittered, doubling wait while the bucket answers that it is busy (R2's
|
|
227
|
+
10001, 10043 and 10058, as a code or in the binding's error message, and HTTP
|
|
228
|
+
5xx). After seven attempts, about six seconds of waiting, `BucketUnavailable`
|
|
229
|
+
carries the original error as its cause; other failures are thrown at once.
|
|
230
|
+
Buffered reads retry the body too, and buffered writes can be sent again safely.
|
|
231
|
+
A consumed upload stream cannot be resent. A caller reaching the bucket itself
|
|
232
|
+
uses the same. Both stores accept a final `pause` function for spending the
|
|
233
|
+
waits (a timer by default).
|
|
234
|
+
|
|
235
|
+
`bucketObjects(bucket)` is the same bucket keyed by name rather than by content:
|
|
236
|
+
an **Objects** store whose caller chooses each key, as a host does for an app's
|
|
237
|
+
files. Besides `has`, `put` and `get` (which throws on a miss) it has `read`
|
|
238
|
+
(null on a miss), `load` (bytes and a validator in one read), `open` (metadata
|
|
239
|
+
then a streamed span), `delete`, `list(prefix)` and `uploaded(prefix)`, which
|
|
240
|
+
maps each key to when it landed. `list` and `uploaded` read every page.
|
|
241
|
+
|
|
242
|
+
The following in-memory bucket shows both interfaces without a cloud account. An
|
|
243
|
+
**Opened** object is metadata (`size`, `version`) with a `read(range?)` function
|
|
244
|
+
that streams bytes on demand; **Loaded** is bytes and their version returned
|
|
245
|
+
together.
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
import { equal } from '@yaks/testing'
|
|
249
|
+
import {
|
|
250
|
+
address,
|
|
251
|
+
type Bucket,
|
|
252
|
+
bucketObjects,
|
|
253
|
+
encode,
|
|
254
|
+
objectBlobs,
|
|
255
|
+
} from '@yaks/blob'
|
|
256
|
+
|
|
257
|
+
let held = new Map<string, Uint8Array<ArrayBuffer>>()
|
|
258
|
+
let bucket: Bucket = {
|
|
259
|
+
head: async (key) =>
|
|
260
|
+
held.has(key) ? { size: held.get(key)!.length, etag: 'v1' } : null,
|
|
261
|
+
get: async (key, options) => {
|
|
262
|
+
let bytes = held.get(key)
|
|
263
|
+
if (!bytes) return null
|
|
264
|
+
let start = options?.range.offset ?? 0
|
|
265
|
+
let part = bytes.slice(
|
|
266
|
+
start,
|
|
267
|
+
options ? start + options.range.length : undefined,
|
|
268
|
+
)
|
|
269
|
+
return {
|
|
270
|
+
size: bytes.length,
|
|
271
|
+
etag: 'v1',
|
|
272
|
+
body: new Response(part).body!,
|
|
273
|
+
arrayBuffer: async () => part.buffer,
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
put: async (key, value) => {
|
|
277
|
+
held.set(key, new Uint8Array(value as Uint8Array))
|
|
278
|
+
},
|
|
279
|
+
delete: async (keys) => {
|
|
280
|
+
for (let key of [keys].flat()) held.delete(key)
|
|
281
|
+
},
|
|
282
|
+
list: async ({ prefix }) => ({
|
|
283
|
+
truncated: false,
|
|
284
|
+
objects: [...held].filter(([key]) => key.startsWith(prefix))
|
|
285
|
+
.map(([key, bytes]) => ({
|
|
286
|
+
key,
|
|
287
|
+
size: bytes.length,
|
|
288
|
+
uploaded: new Date(0),
|
|
289
|
+
})),
|
|
290
|
+
}),
|
|
291
|
+
}
|
|
292
|
+
let blobs = objectBlobs(bucket, 'bodies/')
|
|
293
|
+
await blobs.put(address('Hi'), encode('Hi'))
|
|
294
|
+
equal(await blobs.get(address('Hi')), encode('Hi'))
|
|
295
|
+
let files = bucketObjects(bucket)
|
|
296
|
+
await files.put('page.txt', encode('Hello'))
|
|
297
|
+
equal(await files.list('page'), ['page.txt'])
|
|
298
|
+
equal(await files.uploaded('page'), { 'page.txt': 0 })
|
|
299
|
+
equal((await files.load('page.txt'))!.version, 'v1')
|
|
300
|
+
let opened = (await files.open('page.txt'))!
|
|
301
|
+
equal(await new Response(await opened.read({ from: 1, to: 3 })).text(), 'ell')
|
|
302
|
+
await files.delete('page.txt')
|
|
303
|
+
equal(await files.read('page.txt'), null)
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
## Streaming files
|
|
307
|
+
|
|
308
|
+
A file is never read whole into memory to be kept or served. Its bytes pass as a
|
|
309
|
+
`ReadableStream`, a chunk at a time, from where they arrive to where they are
|
|
310
|
+
kept, and from there to whoever reads them.
|
|
311
|
+
|
|
312
|
+
- `bodyOf(request)` is a request's or a response's body as a **Streamed**:
|
|
313
|
+
`{ stream, size? }`, with the length it declares.
|
|
314
|
+
- `Objects.put(key, streamed)` sends a known-length stream of at most `PIECE` (8
|
|
315
|
+
MiB) in one PUT. Larger streams use multipart when the bucket supports it. A
|
|
316
|
+
stream of unknown length is read up to one part to choose the method. The
|
|
317
|
+
multipart writer sends up to three parts in parallel and can fill the next
|
|
318
|
+
part while they are in flight.
|
|
319
|
+
- `stage(store, put, most?)` lands bytes in a content-addressed store, hashed as
|
|
320
|
+
they pass, and answers their address, length and first `HEAD` bytes, with
|
|
321
|
+
`keep` and `drop`. A bucket store stages under `STAGING` and moves the object
|
|
322
|
+
to its address on `keep`. `stored` stages and keeps in one call. A stream past
|
|
323
|
+
`most` fails with `TooMany`.
|
|
324
|
+
- `filed` can publish a signed upload directly at its expected address. It
|
|
325
|
+
checks the digest, length and upload policy before the bucket publishes the
|
|
326
|
+
object. Without an expected address, `filed` stages the stream first.
|
|
327
|
+
- `open(key).read(range?)` streams an object back, a range or all of it.
|
|
328
|
+
- `holding(put, most)` holds bytes whole only up to `most`, for a caller that
|
|
329
|
+
does better with small files whole.
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
import { equal } from '@yaks/testing'
|
|
333
|
+
import { address, bucketObjects, prefixed, stored } from '@yaks/blob'
|
|
334
|
+
import { memoryBucket } from './testing.ts'
|
|
335
|
+
|
|
336
|
+
let { bucket, held } = memoryBucket()
|
|
337
|
+
let blobs = prefixed(bucketObjects(bucket), 'files/')
|
|
338
|
+
let body = new Response('a photo').body!
|
|
339
|
+
let { sha, size } = await stored(blobs, { stream: body })
|
|
340
|
+
equal([sha, size], [address('a photo'), 7])
|
|
341
|
+
equal([...held.keys()], [`files/${sha}`])
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
### What reads whole, and its bound
|
|
345
|
+
|
|
346
|
+
Some work needs the bytes whole. Each holds them to a stated bound and refuses
|
|
347
|
+
what is past it, rather than loading it:
|
|
348
|
+
|
|
349
|
+
| What | Why whole | Bound |
|
|
350
|
+
| --------------------------------------------------------------------- | -------------------------------------------------- | ----------------------------------------------------- |
|
|
351
|
+
| A file a write or a drop holds (workers/yak tools.ts `pinning`) | puts several at once; a PNG is decoded to check it | `PIECE`, 8 MiB; larger streams, unchecked |
|
|
352
|
+
| A part of an upload in parts (`parts`) | kept again as its recovery copy | the part size, 8 MiB by default |
|
|
353
|
+
| An upload's type and picture size (`described`) | read off the first bytes | `HEAD`, 256 KiB |
|
|
354
|
+
| An Operator attachment (workers/yak `keepFile`) | a model's input, OCR, base64 | 16 MiB, refused past it |
|
|
355
|
+
| A document's text extracted (workers/yak documents.ts) | parsed by its extractor | 16 MiB, refused past it |
|
|
356
|
+
| A browser visit's mockup files (@yaks/platform/browser-mockup) | the browser requests each asset after the upload | 32 MiB, refused past it |
|
|
357
|
+
| A logo (workers/yak logo.ts) | drawn into an SVG | 1 MB, refused past it |
|
|
358
|
+
| A published file's request (workers/yak public-files.ts) | none: it streams | the spaceās available storage |
|
|
359
|
+
| Words framed in place (workers/yak operator-page.ts) | drawn as a page | 1 MiB; longer ones stream as text |
|
|
360
|
+
| A Durable Object's answer (@yaks/durable-object `received`) | sent again if a restart cuts it off | `WHOLE`, 1 MiB; a larger one streams |
|
|
361
|
+
| An outbound call's body (@yaks/egress, @yaks/connections) | secrets substituted, sent again on an OAuth retry | none yet: T-2794 |
|
|
362
|
+
| A store's sandbox `/apply` or a form's fields | parsed as rows | the store's own limits; files go through `./api/blob` |
|
|
363
|
+
| A body read in a box's tools (git packs, npm tarballs, model weights) | parsed whole by their libraries | the box's memory, not a Worker's |
|
|
364
|
+
| A fixed sample sentence spoken (workers/yak speech.ts `sampled`) | kept and served as one MP3 | one sentence of audio |
|
|
365
|
+
|
|
366
|
+
A store that holds bytes in this process anyway (`memoryBlobs`, `sqliteBlobs`,
|
|
367
|
+
`fileBlobs`) is given a stream whole.
|
|
368
|
+
|
|
369
|
+
## Uploads in parts
|
|
370
|
+
|
|
371
|
+
`parts(objects, bucket, {key, sha, ledger, part})` uploads the bytes whose
|
|
372
|
+
SHA-256 is `sha` into `key` in parts of `part` bytes, through the bucket's own
|
|
373
|
+
**multipart** upload (S3's protocol, which R2 speaks; `Multipart` is that slice
|
|
374
|
+
of R2's binding). Its **ledger** is empty objects under `ledger` whose keys
|
|
375
|
+
record the upload under way and each part that landed, which R2's binding has no
|
|
376
|
+
call to list. So an upload cut short resumes: `post(bytes)` says which parts are
|
|
377
|
+
still `need`ed, beginning the upload if none is under way, and once none are it
|
|
378
|
+
assembles them and answers the `whole`: its length and first bytes, and `made`
|
|
379
|
+
when that `post` assembled it rather than finding it kept already.
|
|
380
|
+
|
|
381
|
+
`put(n, body, length, from)` keeps part `n`, hashing it as it passes on from
|
|
382
|
+
`from`, the SHA-256 **state** the bytes before it leave (`START` for the first).
|
|
383
|
+
The ledger keeps each part's state before and after. Accepted bytes also have
|
|
384
|
+
private immutable recovery objects under `<ledger>/<sha>/retained/`, with upload
|
|
385
|
+
id, total size, part size, part number and hash states in the key. A provider
|
|
386
|
+
losing its multipart id leaves those objects and its old receipts recoverable; a
|
|
387
|
+
new upload can begin. A broken chain never aborts or discards accepted parts.
|
|
388
|
+
Disable lifecycle expiry and multipart abort rules on the bucket.
|
|
389
|
+
|
|
390
|
+
The parts are assembled only when those chain from `START` to `sha`, so nothing
|
|
391
|
+
is read back to check the whole. A broken chain, or a part of the wrong length,
|
|
392
|
+
throws `Wrong`. `Gone` says the upload is not under way, so it is begun again.
|
|
393
|
+
`memoryMultipart(put)` holds the parts in memory for a bucket with no multipart
|
|
394
|
+
of its own. A verified whole removes its active receipts and recovery copies of
|
|
395
|
+
the same valid parts. Other accepted attempts remain private until a person
|
|
396
|
+
chooses permanent purge.
|
|
397
|
+
|
|
398
|
+
The complete three-part bucket example runs in
|
|
399
|
+
[`multipart_example_test.ts`](./multipart_example_test.ts): a third part lands,
|
|
400
|
+
a new uploader reads its ledger, and only the two missing parts are sent before
|
|
401
|
+
checking the exact completed bytes and empty ledger. Its bucket and bytes are
|
|
402
|
+
prepared outside that behavior's timer.
|
|
403
|
+
|
|
404
|
+
```ts
|
|
405
|
+
import { parts } from '@yaks/blob'
|
|
406
|
+
|
|
407
|
+
// const upload = parts(objects, multipart, { key, sha, ledger: 'uploads/' })
|
|
408
|
+
// const { need } = await upload.post(bytes) // resume from its durable ledger
|
|
409
|
+
// await upload.put(part, stream, length, stateBeforePart)
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
R2 takes parts of at least 5 MiB, every one but the last the same size, and
|
|
413
|
+
10,000 of them (`MOST`). `sized(bytes, part)` grows the part in whole `MiB` for
|
|
414
|
+
a file that would need more. A part's state is a whole number of 64-byte blocks
|
|
415
|
+
in, so a part size is too.
|
|
416
|
+
|
|
417
|
+
`hasher(from?)` hashes bytes a piece at a time with `add`; `end()` answers the
|
|
418
|
+
state after them, and `end(total)` the finished digest, `total` being every byte
|
|
419
|
+
hashed since `START`. `fold(from, bytes, total?)` is the same over one buffer.
|
|
420
|
+
|
|
421
|
+
## Retained bodies
|
|
422
|
+
|
|
423
|
+
A body's bytes outlive edits, removals and expiration. Trash and retained
|
|
424
|
+
history still read the old text. The plugin keeps those bytes; ordinary graph
|
|
425
|
+
writes never release them.
|
|
426
|
+
|
|
427
|
+
A byte store's `drop(shas, holders)` releases addresses only when none of the
|
|
428
|
+
supplied holding columns names them. It is a storage primitive, so callers must
|
|
429
|
+
also account for retained history and trash before requesting a release. Stores
|
|
430
|
+
without `drop` keep everything.
|
|
431
|
+
|
|
432
|
+
After a person's confirmed history purge, the plugin releases pooled bytes only
|
|
433
|
+
when no live row, retained version, trash snapshot or plugin history still names
|
|
434
|
+
them. It recognizes retired properties' stored addresses too. Storage without
|
|
435
|
+
retained-value accounting and stores using custom integer references keep their
|
|
436
|
+
bytes.
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
import { equal } from '@yaks/testing'
|
|
440
|
+
import { address, blobSchema, encode, sqliteBlobs } from '@yaks/blob'
|
|
441
|
+
import { open } from '@yaks/sqlite/db'
|
|
442
|
+
import { val } from '@yaks/sql'
|
|
443
|
+
import { statements } from '@yaks/sqlite'
|
|
444
|
+
|
|
445
|
+
let driver = open(':memory:')
|
|
446
|
+
for (let stmt of blobSchema()) driver.query(stmt)
|
|
447
|
+
driver.query({ t: 'create table', name: 'copy', cols: [{ name: 'sha' }] })
|
|
448
|
+
let store = sqliteBlobs(statements(driver))
|
|
449
|
+
for (let text of ['lone', 'kept']) store.put(address(text), encode(text))
|
|
450
|
+
let kept = val(address('kept'))
|
|
451
|
+
driver.query({ t: 'insert', into: 'copy', cols: ['sha'], rows: [[kept]] })
|
|
452
|
+
let copy = { comp: 'copy', prop: 'sha' }
|
|
453
|
+
store.drop!([address('lone'), address('kept')], [copy])
|
|
454
|
+
equal(store.has(address('lone')), false)
|
|
455
|
+
equal(store.has(address('kept')), true)
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
## Which blobs are taken
|
|
459
|
+
|
|
460
|
+
`Accepts` is what an application takes as a blob, in JSON Schema's words for a
|
|
461
|
+
string of bytes: `maxLength`, the most bytes one may hold, and
|
|
462
|
+
`contentMediaType`, one media type or a list, where `image/*` is a range.
|
|
463
|
+
`acceptsErrors(said)` says what is wrong with a declaration,
|
|
464
|
+
`fits(accepts,
|
|
465
|
+
bytes)` checks a size, and `takes(accepts, type)` checks the type
|
|
466
|
+
read off the bytes (`contentType`), never the one an upload declares. Nothing
|
|
467
|
+
declared takes everything.
|
|
468
|
+
|
|
469
|
+
## Reading it back
|
|
470
|
+
|
|
471
|
+
`blobRead(vocab, layout?)` produces `@yaks/sql` derived read overrides. Pass
|
|
472
|
+
these to `storage(..., { derived })` so both predicates and returned properties
|
|
473
|
+
use the text. It requires a SQL-accessible text table such as `sqliteBlobs`; it
|
|
474
|
+
cannot read an external directory or bucket inside a query.
|
|
475
|
+
|
|
476
|
+
`hydrate(vocab, store, bundles)` fetches marked values after a read and returns
|
|
477
|
+
bundles containing text. It returns a promise only when the backend does. If an
|
|
478
|
+
address is missing, it leaves the address in place. Hydration alone does not
|
|
479
|
+
make SQL predicates on externally stored text work.
|
|
480
|
+
|
|
481
|
+
```ts
|
|
482
|
+
import { equal } from '@yaks/testing'
|
|
483
|
+
import { loadVocab } from '@yaks/vocab'
|
|
484
|
+
import { address, blobKeywords, encode, hydrate, memoryBlobs } from '@yaks/blob'
|
|
485
|
+
|
|
486
|
+
let post = {
|
|
487
|
+
component: true,
|
|
488
|
+
type: 'object',
|
|
489
|
+
properties: { body: { type: 'string', store: 'blob' } },
|
|
490
|
+
}
|
|
491
|
+
let vocab = loadVocab([{ $defs: { post } }], [blobKeywords])
|
|
492
|
+
let store = memoryBlobs()
|
|
493
|
+
store.put(address('Hello'), encode('Hello'))
|
|
494
|
+
let [bundle] = await hydrate(vocab, store, [
|
|
495
|
+
{ entity: { eid: 'p1' }, post: { body: address('Hello') } },
|
|
496
|
+
])
|
|
497
|
+
equal(bundle.post, { body: 'Hello' })
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
## Indexing the text
|
|
501
|
+
|
|
502
|
+
A [full-text index](../fts/README.md) built directly from a body would index
|
|
503
|
+
addresses. Supply text-resolution expressions when creating the index:
|
|
504
|
+
|
|
505
|
+
```ts
|
|
506
|
+
import { loadVocab } from '@yaks/vocab'
|
|
507
|
+
import { open } from '@yaks/sqlite/db'
|
|
508
|
+
import { storage } from '@yaks/sqlite'
|
|
509
|
+
import { fields, find, schema } from '@yaks/fts'
|
|
510
|
+
import { graph } from '@yaks/graph'
|
|
511
|
+
import { equal } from '@yaks/testing'
|
|
512
|
+
import {
|
|
513
|
+
blobKeywords,
|
|
514
|
+
blobRead,
|
|
515
|
+
blobs,
|
|
516
|
+
blobSchema,
|
|
517
|
+
sqliteBlobs,
|
|
518
|
+
} from '@yaks/blob'
|
|
519
|
+
|
|
520
|
+
let post = {
|
|
521
|
+
component: true,
|
|
522
|
+
type: 'object',
|
|
523
|
+
properties: { body: { type: 'string', store: 'blob', search: true } },
|
|
524
|
+
}
|
|
525
|
+
let vocab = loadVocab([{ $defs: { post } }], [blobKeywords])
|
|
526
|
+
let driver = open(':memory:')
|
|
527
|
+
let db = storage(driver, vocab, { derived: blobRead(vocab) })
|
|
528
|
+
for (let statement of [...db.ddl(), ...blobSchema()]) {
|
|
529
|
+
driver.query(statement)
|
|
530
|
+
}
|
|
531
|
+
for (let statement of schema(fields(vocab), blobRead(vocab))) {
|
|
532
|
+
driver.query(statement)
|
|
533
|
+
}
|
|
534
|
+
let g = graph({
|
|
535
|
+
storage: db,
|
|
536
|
+
vocab,
|
|
537
|
+
plugins: [blobs(vocab, sqliteBlobs(db.statements))],
|
|
538
|
+
})
|
|
539
|
+
g.apply([{ entity: { eid: 'p1' }, post: { body: 'orchard' } }])
|
|
540
|
+
equal(find(driver, fields(vocab), 'orchard').map((hit) => hit.entity), ['p1'])
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
`blobRead()` maps `component.property` to two @yaks/sql expressions:
|
|
544
|
+
`expr(owner)` reads the text through the owner's row, for ordinary reads, and
|
|
545
|
+
`text(stored)` turns an address already in hand into its text, for the
|
|
546
|
+
delete/update triggers that must read the old value and for `@yaks/sqlite`'s
|
|
547
|
+
`doc_value` view. Triggers and the FTS content view resolve the same text, so
|
|
548
|
+
graph writes, direct SQL writes and index rebuilds use consistent content. Store
|
|
549
|
+
the content before inserting a referencing component row. For existing rows and
|
|
550
|
+
indexes, see [@yaks/fts](../fts/README.md).
|
|
551
|
+
|
|
552
|
+
## Binary files
|
|
553
|
+
|
|
554
|
+
Byte identification lives at `@yaks/blob/identify`, beside the detector it uses.
|
|
555
|
+
A portable consumer takes an `ArtifactStore` from its host; it reads artifacts
|
|
556
|
+
through `artifactBytes` without loading the detector.
|
|
557
|
+
|
|
558
|
+
`artifactStore(store)` from `@yaks/blob/identify` returns a function accepting
|
|
559
|
+
`(bytes, mediaType)` and resolving to `{ address, media_type, size }` after
|
|
560
|
+
storing and verifying the bytes. Known binary signatures determine the media
|
|
561
|
+
type. Text with valid UTF-8 keeps a valid declared type; unknown bytes use
|
|
562
|
+
`application/octet-stream`:
|
|
563
|
+
|
|
564
|
+
```ts
|
|
565
|
+
import { equal } from '@yaks/testing'
|
|
566
|
+
import { artifactBytes } from '@yaks/blob'
|
|
567
|
+
import { artifactStore } from '@yaks/blob/identify'
|
|
568
|
+
import { fileBlobs } from '@yaks/file/blobs'
|
|
569
|
+
|
|
570
|
+
let dir = await Deno.makeTempDir()
|
|
571
|
+
try {
|
|
572
|
+
let store = fileBlobs(dir)
|
|
573
|
+
let bytes = new Uint8Array([0, 255])
|
|
574
|
+
let artifact = await artifactStore(store)(bytes, 'application/octet-stream')
|
|
575
|
+
equal(artifact.size, 2)
|
|
576
|
+
equal(await artifactBytes(store, artifact), bytes)
|
|
577
|
+
} finally {
|
|
578
|
+
await Deno.remove(dir, { recursive: true })
|
|
579
|
+
}
|
|
580
|
+
```
|
|
581
|
+
|
|
582
|
+
`artifactBytes(store, artifact)` reads the bytes an artifact row names back:
|
|
583
|
+
`undefined` when the store holds nothing under its address, and an error when
|
|
584
|
+
the bytes it holds are another size or another SHA-256.
|
|
585
|
+
|
|
586
|
+
Use a file or object store for arbitrary binary content.
|
|
587
|
+
`keep(store, address,
|
|
588
|
+
bytes)` performs the store-and-read-back check directly. A
|
|
589
|
+
matching existing object needs no write; mismatched bytes cause another write
|
|
590
|
+
and a verification failure throws. A backend that cannot overwrite corrupt
|
|
591
|
+
content may still fail that repair.
|
|
592
|
+
|
|
593
|
+
## Attachments
|
|
594
|
+
|
|
595
|
+
`artifactDoc` declares `artifact { address, media_type, size }` and an
|
|
596
|
+
`attachment` component referencing an artifact. An attachment can also record
|
|
597
|
+
the provider call ID and revised prompt associated with generation.
|
|
598
|
+
|
|
599
|
+
```ts
|
|
600
|
+
import { equal } from '@yaks/testing'
|
|
601
|
+
import { graph } from '@yaks/graph'
|
|
602
|
+
import { ram } from '@yaks/ram'
|
|
603
|
+
import { loadVocab } from '@yaks/vocab'
|
|
604
|
+
import { artifactDoc, encode, memoryBlobs } from '@yaks/blob'
|
|
605
|
+
import { artifactStore } from '@yaks/blob/identify'
|
|
606
|
+
|
|
607
|
+
let vocab = loadVocab([artifactDoc])
|
|
608
|
+
let g = graph({ storage: ram(vocab), vocab })
|
|
609
|
+
let artifact = await artifactStore(memoryBlobs())(
|
|
610
|
+
encode('Hello'),
|
|
611
|
+
'text/plain',
|
|
612
|
+
)
|
|
613
|
+
await g.apply([
|
|
614
|
+
{ entity: { eid: artifact.address }, artifact },
|
|
615
|
+
{
|
|
616
|
+
entity: { eid: 'a1' },
|
|
617
|
+
attachment: { artifact: artifact.address, name: 'hello.txt' },
|
|
618
|
+
},
|
|
619
|
+
])
|
|
620
|
+
equal((await g.read('.attachment'))[0].attachment, {
|
|
621
|
+
artifact: artifact.address,
|
|
622
|
+
name: 'hello.txt',
|
|
623
|
+
})
|
|
624
|
+
```
|
|
625
|
+
|
|
626
|
+
## Image headers and media types
|
|
627
|
+
|
|
628
|
+
`sizeOf(bytes)` reads `{ w, h }` from PNG, JPEG, GIF and WebP headers without
|
|
629
|
+
bitmap decoding. Unsupported or invalid headers, including zero dimensions,
|
|
630
|
+
return `undefined`. `mediaTypeOf(bytes)` names the same four formats from their
|
|
631
|
+
signatures (`image/png`, `image/jpeg`, `image/gif`, `image/webp`), and
|
|
632
|
+
`undefined` for anything else.
|
|
633
|
+
|
|
634
|
+
```ts
|
|
635
|
+
import { equal } from '@yaks/testing'
|
|
636
|
+
import { encode, mediaTypeOf, mimeOf, sizeOf } from '@yaks/blob'
|
|
637
|
+
import { contentType } from '@yaks/blob/identify'
|
|
638
|
+
|
|
639
|
+
let gif = new Uint8Array([...encode('GIF89a'), 2, 0, 3, 0])
|
|
640
|
+
equal(sizeOf(gif), { w: 2, h: 3 })
|
|
641
|
+
equal(mediaTypeOf(gif), 'image/gif')
|
|
642
|
+
equal(await contentType(gif, 'text/plain'), 'image/gif')
|
|
643
|
+
equal(await contentType(encode('<svg/>'), 'image/svg+xml'), 'image/svg+xml')
|
|
644
|
+
equal(mimeOf('report.pdf'), 'application/pdf')
|
|
645
|
+
```
|
|
646
|
+
|
|
647
|
+
`broken(bytes, type)` says what is wrong with bytes that claim to be a picture
|
|
648
|
+
of `type`, as a clause, or `undefined` when they decode as one. A PNG is checked
|
|
649
|
+
whole: each chunk's CRC, its header, and its pixel data inflated scanline by
|
|
650
|
+
scanline. JPEG, GIF and WebP are checked as far as their headers go, an SVG is
|
|
651
|
+
text with an `<svg>` element, and a type nothing here reads passes.
|
|
652
|
+
|
|
653
|
+
```ts
|
|
654
|
+
import { equal } from '@yaks/testing'
|
|
655
|
+
import { broken, encode } from '@yaks/blob'
|
|
656
|
+
|
|
657
|
+
let gif = new Uint8Array([...encode('GIF89a'), 2, 0, 3, 0])
|
|
658
|
+
equal(await broken(gif, 'image/png'), 'its bytes are a GIF, not a PNG')
|
|
659
|
+
equal(await broken(gif, 'image/gif'), undefined)
|
|
660
|
+
equal(
|
|
661
|
+
await broken(encode('<html>'), 'image/svg+xml'),
|
|
662
|
+
'it has no <svg> element',
|
|
663
|
+
)
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
## HTTP responses
|
|
667
|
+
|
|
668
|
+
`served(bytes, { mime?, name?, etag?, cache? }, request)` creates a byte-range
|
|
669
|
+
capable HTTP response with `x-content-type-options: nosniff` and an optional
|
|
670
|
+
inline filename disposition. Documents keep
|
|
671
|
+
`content-security-policy: sandbox;
|
|
672
|
+
script-src 'none'`; audio and video keep
|
|
673
|
+
their origin with `script-src 'none'` so a browser's native player can fetch
|
|
674
|
+
them. A mutable response revalidates. A versioned public response can use
|
|
675
|
+
`cache: 'immutable'` for a one-year cache; an app response can use `browser`,
|
|
676
|
+
kept a year by the reader's own browser and by no shared cache.
|
|
677
|
+
`validator(address, meta)` makes the ETag for bytes and metadata. Scripts are
|
|
678
|
+
blocked; the policy does not mean an HTML or SVG document cannot render.
|
|
679
|
+
`ranged(bytes, request, headers)` serves the same byte-range behavior when a
|
|
680
|
+
caller supplies its own response headers. `servedOpen` and `rangedOpen` accept
|
|
681
|
+
an opened object and stream the selected span without loading the whole file;
|
|
682
|
+
conditional responses and HEAD need no body read. `mimeOf(name)` gives deployed
|
|
683
|
+
files and named uploads one media type lookup. `servedVia(read, meta, request)`
|
|
684
|
+
applies the same headers and conditional handling when a cache or another store
|
|
685
|
+
supplies the byte response.
|
|
686
|
+
|
|
687
|
+
```ts
|
|
688
|
+
import { equal } from '@yaks/testing'
|
|
689
|
+
import {
|
|
690
|
+
address,
|
|
691
|
+
encode,
|
|
692
|
+
ranged,
|
|
693
|
+
served,
|
|
694
|
+
servedOpen,
|
|
695
|
+
servedVia,
|
|
696
|
+
validator,
|
|
697
|
+
} from '@yaks/blob'
|
|
698
|
+
|
|
699
|
+
let bytes = encode('Hello')
|
|
700
|
+
let meta = { mime: 'text/plain', etag: await validator(address('Hello'), {}) }
|
|
701
|
+
let request = new Request('https://blob.invalid/', {
|
|
702
|
+
headers: { range: 'bytes=1-3' },
|
|
703
|
+
})
|
|
704
|
+
let response = served(bytes, meta, request)
|
|
705
|
+
equal(response.status, 206)
|
|
706
|
+
equal(await response.text(), 'ell')
|
|
707
|
+
let streamed = await servedOpen(
|
|
708
|
+
{
|
|
709
|
+
size: bytes.length,
|
|
710
|
+
version: 'v1',
|
|
711
|
+
read: async (range) =>
|
|
712
|
+
new Response(range ? bytes.slice(range.from, range.to + 1) : bytes).body!,
|
|
713
|
+
},
|
|
714
|
+
meta,
|
|
715
|
+
request,
|
|
716
|
+
)
|
|
717
|
+
equal(await streamed.text(), 'ell')
|
|
718
|
+
let unchanged = served(
|
|
719
|
+
bytes,
|
|
720
|
+
meta,
|
|
721
|
+
new Request('https://blob.invalid/', {
|
|
722
|
+
headers: { 'if-none-match': meta.etag },
|
|
723
|
+
}),
|
|
724
|
+
)
|
|
725
|
+
equal(unchanged.status, 304)
|
|
726
|
+
let forwarded = await servedVia(
|
|
727
|
+
async (request) => ranged(bytes, request),
|
|
728
|
+
meta,
|
|
729
|
+
request,
|
|
730
|
+
)
|
|
731
|
+
equal(forwarded.status, 206)
|
|
732
|
+
equal(await forwarded.text(), 'ell')
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
## The HTTP endpoints
|
|
736
|
+
|
|
737
|
+
`@yaks/blob/routes` exports `routes(host, options)` for plugin servers such as
|
|
738
|
+
[`yak serve`](../cli/README.md). It mounts its doors under `options.at` (default
|
|
739
|
+
`/blob/`):
|
|
740
|
+
|
|
741
|
+
- `POST /blob` keeps the body's bytes. `content-type` says their type and
|
|
742
|
+
`x-yak-name` their name, percent-encoded.
|
|
743
|
+
- `PUT /blob/<sha256>` does the same for bytes hashing to that address, which
|
|
744
|
+
must be 64 lowercase hex digits; either mismatch returns 400.
|
|
745
|
+
- `POST /blob/<sha256>` with `{bytes, name, mime}` begins or resumes an
|
|
746
|
+
[upload in parts](#uploads-in-parts) where `options.parts` names a bucket for
|
|
747
|
+
them: it answers `{part, need}`, the part size and the parts still missing,
|
|
748
|
+
until none are, and then it answers as an upload does.
|
|
749
|
+
`PUT
|
|
750
|
+
/blob/<sha256>/<n>` sends part `n`, with `x-yak-state` the SHA-256
|
|
751
|
+
state the bytes before it leave. A door with no bucket for parts answers 501.
|
|
752
|
+
- A bare `GET` or `HEAD` redirects to the current representation, which the
|
|
753
|
+
browser keeps for a week. An address its rows name without a representation
|
|
754
|
+
gets one on first read.
|
|
755
|
+
- A versioned `GET` or `HEAD` returns bytes and immutable media type and
|
|
756
|
+
filename headers, cached by the browser for a year, while a row still names
|
|
757
|
+
the bytes. Invalid addresses, missing objects and bytes no row names return
|
|
758
|
+
404. The route itself performs no authentication check.
|
|
759
|
+
|
|
760
|
+
Each upload answers `{eid, attachment, url, mime, bytes}`, with `w` and `h` for
|
|
761
|
+
a picture, and the versioned `url` again in `Location`. `eid` is the address and
|
|
762
|
+
the content row's eid; `attachment` is the eid of its use, `useOf(eid)`, the row
|
|
763
|
+
saying what the bytes are called and what they are. The rows are an `artifact`
|
|
764
|
+
and an `attachment` naming it, or the words a host passes as `naming`
|
|
765
|
+
(`@yaks/blob/upload` `Naming`). The same bytes again are the same two rows, and
|
|
766
|
+
an upload that names nothing keeps the name they had.
|
|
767
|
+
|
|
768
|
+
Every upload counts streamed body bytes. It returns 413 above the `limit`, above
|
|
769
|
+
the `maxLength` of `accepts` (which blobs are taken), or past the `room` a host
|
|
770
|
+
says its store has, and 415 for bytes whose type, read off them, `accepts` does
|
|
771
|
+
not list. A refusal carries the door's word for it as `code`: `too_large`,
|
|
772
|
+
`unsupported_media_type`, `space_full`, `no_bytes` or `upload_gone`.
|
|
773
|
+
|
|
774
|
+
An upload first checks its proposed rows with
|
|
775
|
+
`graph.apply(..., { check: true
|
|
776
|
+
})`, then stores/verifies bytes, then applies
|
|
777
|
+
the rows. The graph's write rules determine whether the upload is allowed.
|
|
778
|
+
`host.who`, when configured, supplies actor attribution as it does for `/apply`.
|
|
779
|
+
This route adds no separate upload permission policy. The same write half
|
|
780
|
+
without a request is `@yaks/blob/upload` `filed`, for bytes that arrive another
|
|
781
|
+
way.
|
|
782
|
+
|
|
783
|
+
If the final graph write fails, stored content may remain without its rows.
|
|
784
|
+
Repeating a successful upload uses the same address and entity IDs.
|
|
785
|
+
|
|
786
|
+
```json
|
|
787
|
+
{
|
|
788
|
+
"use": "@yaks/blob",
|
|
789
|
+
"with": {
|
|
790
|
+
"store": { "via": "file", "dir": "/var/lib/blobs" },
|
|
791
|
+
"limit": 26214400
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
`limit` defaults to 25 MiB (`LIMIT`). A composed `yak` host gives the route and
|
|
797
|
+
the harness the same artifact store. By default, a file-backed graph keeps
|
|
798
|
+
binary artifacts in `images/` beside its database; an in-memory graph keeps them
|
|
799
|
+
in memory. The plugin's `store` option changes that store for both. Graph text
|
|
800
|
+
properties remain in the SQLite text table. The routes keep bytes in the host's
|
|
801
|
+
artifact store (`host.artifacts`), else its blob store (`host.blobs`), and mount
|
|
802
|
+
no door when it has neither; they never open a database connection, and they
|
|
803
|
+
never build a store from configuration, so a host without files, a Worker, never
|
|
804
|
+
loads `@yaks/file/blobs`. A host builds the configured store with
|
|
805
|
+
`@yaks/blob/backend`:
|
|
806
|
+
|
|
807
|
+
- `{ "via": "sqlite" }`: the host's blob store (`host.blobs`). A host using
|
|
808
|
+
`sqliteBlobs(statements)` lends the text table, which rejects invalid UTF-8
|
|
809
|
+
uploads.
|
|
810
|
+
- `{ "via": "file", "dir": "..." }`: a directory for binary or text uploads,
|
|
811
|
+
made by the host's `files` (a box gives `@yaks/file/blobs` `fileBlobs`).
|
|
812
|
+
- `{ via: 'object', bucket, prefix? }`: an object-store binding supplied in
|
|
813
|
+
code, not serializable JSON configuration.
|
|
814
|
+
|
|
815
|
+
The `graph` sub-module keeps marked graph text properties in the host's blob
|
|
816
|
+
store (`host.blobs`, supplied by the host). A composed host refuses an invalid
|
|
817
|
+
artifact backend at startup.
|
|
818
|
+
|
|
819
|
+
The representation plugin refuses changes and deletions to representations.
|
|
820
|
+
`representation()` derives their identities; `represents()` verifies them. The
|
|
821
|
+
`graph` sub-module registers this plugin alongside the body plugin.
|
|
822
|
+
|
|
823
|
+
```ts
|
|
824
|
+
import { equal } from '@yaks/testing'
|
|
825
|
+
import { representation, represents } from '@yaks/blob'
|
|
826
|
+
|
|
827
|
+
let fixed = representation(
|
|
828
|
+
'blob',
|
|
829
|
+
'a'.repeat(64),
|
|
830
|
+
'TEXT/PLAIN; charset=utf-8',
|
|
831
|
+
'notes.txt',
|
|
832
|
+
)
|
|
833
|
+
equal(represents(fixed.eid, fixed.row), true)
|
|
834
|
+
equal(fixed.row.media_type, 'text/plain')
|
|
835
|
+
equal(fixed.path, `${'a'.repeat(64)}/${fixed.eid}`)
|
|
836
|
+
equal(represents(fixed.eid, { ...fixed.row, name: 'other.txt' }), false)
|
|
837
|
+
```
|
|
838
|
+
|
|
839
|
+
The endpoints can be exercised through their route handlers without starting a
|
|
840
|
+
server. The supplied graph registers the package's rules and declarations.
|
|
841
|
+
|
|
842
|
+
```ts
|
|
843
|
+
import { equal } from '@yaks/testing'
|
|
844
|
+
import { graph } from '@yaks/graph'
|
|
845
|
+
import { loadVocab } from '@yaks/vocab'
|
|
846
|
+
import { storage } from '@yaks/sqlite'
|
|
847
|
+
import { open } from '@yaks/sqlite/db'
|
|
848
|
+
import { address, blobSchema, encode, memoryBlobs } from '@yaks/blob'
|
|
849
|
+
import { docs, keywords } from '@yaks/blob/vocab'
|
|
850
|
+
import { plugins } from '@yaks/blob/graph'
|
|
851
|
+
import { routes } from '@yaks/blob/routes'
|
|
852
|
+
|
|
853
|
+
let vocab = loadVocab(docs, keywords)
|
|
854
|
+
let sql = open(':memory:')
|
|
855
|
+
let db = storage(sql, vocab)
|
|
856
|
+
for (let statement of [...db.ddl(), ...blobSchema()]) sql.query(statement)
|
|
857
|
+
let bytes = memoryBlobs()
|
|
858
|
+
let g = graph({
|
|
859
|
+
storage: db,
|
|
860
|
+
vocab,
|
|
861
|
+
plugins: plugins({ vocab, blobs: bytes }),
|
|
862
|
+
})
|
|
863
|
+
let table = routes({ blobs: bytes, graph: g, artifacts: bytes })
|
|
864
|
+
let upload = table.find((route) => route.method == 'PUT')!
|
|
865
|
+
let read = table.find((route) => route.method == 'GET')!
|
|
866
|
+
let url = `https://blob.invalid/blob/${address('Hello')}`
|
|
867
|
+
let response = await upload.handle(
|
|
868
|
+
new Request(url, {
|
|
869
|
+
method: 'PUT',
|
|
870
|
+
body: encode('Hello'),
|
|
871
|
+
headers: { 'content-type': 'text/plain' },
|
|
872
|
+
}),
|
|
873
|
+
)
|
|
874
|
+
equal(response.status, 200)
|
|
875
|
+
equal((await response.json()).bytes, 5)
|
|
876
|
+
let versioned = new URL(response.headers.get('location')!, url)
|
|
877
|
+
equal((await read.handle(new Request(url))).status, 302)
|
|
878
|
+
equal(await (await read.handle(new Request(versioned))).text(), 'Hello')
|
|
879
|
+
```
|
|
880
|
+
|
|
881
|
+
## Bounded text inspection for tools
|
|
882
|
+
|
|
883
|
+
`valueTools(readEntity)` returns provider-neutral `graph_value_read` and
|
|
884
|
+
`graph_value_search` tool declarations with executable `run` functions. Supply
|
|
885
|
+
the authorized entity reader used by the application's other graph tools. These
|
|
886
|
+
tools accept entity/component/property names, not filesystem paths or raw blob
|
|
887
|
+
addresses, and work with any string property. Each `run` answers a model in
|
|
888
|
+
text: a first line saying where the piece lies, then the piece itself, never
|
|
889
|
+
escaped inside a JSON string. Code reads the same pieces as data through
|
|
890
|
+
`valueRange(readEntity)` and `valueSearch(readEntity)`.
|
|
891
|
+
|
|
892
|
+
Both take `entity`, `component` and `property`. Optional `revision` must match
|
|
893
|
+
the SHA-256 of the current UTF-8 text; a mismatch is refused with the current
|
|
894
|
+
revision, and says whether the one passed is that revision copied wrong or text
|
|
895
|
+
that changed since. Missing, denied or non-text values fail.
|
|
896
|
+
|
|
897
|
+
- Read uses a zero-based Unicode code-point `start`. `count` defaults to 2048,
|
|
898
|
+
with a maximum of 8192 (`VALUE_LIMIT`). A range (`valueRange`) has `start`,
|
|
899
|
+
`end`, `total`, `revision`, `text` and `next` (null at the end); the tool says
|
|
900
|
+
`[Code points 0 to 2048 of 9000, revision ā¦; next start=2048.]` and then the
|
|
901
|
+
text.
|
|
902
|
+
- Search uses a nonempty, case-sensitive literal `query` of at most 256 UTF-16
|
|
903
|
+
code units. `start` skips earlier characters; `limit` defaults to 10 and is at
|
|
904
|
+
most 20. Matches (`valueSearch`) have offsets and excerpts; the tool says a
|
|
905
|
+
line for each, `at 4: A š³ tree`, its line breaks shown as spaces. `next` is a
|
|
906
|
+
continuation offset when the match limit was reached, even if no further match
|
|
907
|
+
exists.
|
|
908
|
+
|
|
909
|
+
Offsets count code points, not grapheme clusters or terminal columns. Both tools
|
|
910
|
+
read the entire value before slicing/searching; only the output is bounded.
|
|
911
|
+
|
|
912
|
+
```ts
|
|
913
|
+
import { equal } from '@yaks/testing'
|
|
914
|
+
import { address, valueRange, valueSearch, valueTools } from '@yaks/blob'
|
|
915
|
+
|
|
916
|
+
let reader = async (eid: string) =>
|
|
917
|
+
eid == 'p1' ? { entity: { eid }, post: { body: 'A š³ tree' } } : undefined
|
|
918
|
+
let revision = address('A š³ tree')
|
|
919
|
+
let args = { entity: 'p1', component: 'post', property: 'body', revision }
|
|
920
|
+
let slice = await valueRange(reader)({ ...args, start: 2, count: 1 })
|
|
921
|
+
equal(slice.text, 'š³')
|
|
922
|
+
equal(slice.next, 3)
|
|
923
|
+
let result = await valueSearch(reader)({ ...args, query: 'tree' })
|
|
924
|
+
equal(result.matches[0].offset, 4)
|
|
925
|
+
let read = valueTools(reader).find((tool) => tool.name == 'graph_value_read')!
|
|
926
|
+
equal(
|
|
927
|
+
await read.run({ ...args, start: 2, count: 1 }),
|
|
928
|
+
`[Code points 2 to 3 of 8, revision ${revision}; next start=3.]\nš³`,
|
|
929
|
+
)
|
|
930
|
+
```
|
|
931
|
+
|
|
932
|
+
## Limits
|
|
933
|
+
|
|
934
|
+
There is no garbage collection for unreferenced content. Applications own
|
|
935
|
+
retention and backups, including separate file or object stores. A database
|
|
936
|
+
backup alone cannot restore external bytes.
|
|
937
|
+
|
|
938
|
+
Removing the plugin leaves stored addresses and content intact, but ordinary
|
|
939
|
+
reads need the configured resolver to return text. The underlying table/file
|
|
940
|
+
format remains accessible to application code.
|
|
941
|
+
|
|
942
|
+
## Compatibility
|
|
943
|
+
|
|
944
|
+
The core keyword, plugin and SQLite store use no platform-specific storage API.
|
|
945
|
+
They work wherever the supplied driver and required standard web APIs work. The
|
|
946
|
+
bundled filesystem adapter specifically requires Deno filesystem functions; use
|
|
947
|
+
another Blobs implementation for Node, browsers or Workers without them.
|