@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.
Files changed (172) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +946 -2
  3. package/_dist/accepts.d.ts +38 -0
  4. package/_dist/accepts.d.ts.map +1 -0
  5. package/_dist/artifact.d.ts +29 -0
  6. package/_dist/artifact.d.ts.map +1 -0
  7. package/_dist/attachment.d.ts +53 -0
  8. package/_dist/attachment.d.ts.map +1 -0
  9. package/_dist/backend.d.ts +20 -0
  10. package/_dist/backend.d.ts.map +1 -0
  11. package/_dist/broken.d.ts +24 -0
  12. package/_dist/broken.d.ts.map +1 -0
  13. package/_dist/browser.d.ts +27 -0
  14. package/_dist/browser.d.ts.map +1 -0
  15. package/_dist/compare.d.ts +4 -0
  16. package/_dist/compare.d.ts.map +1 -0
  17. package/_dist/content_type.d.ts +20 -0
  18. package/_dist/content_type.d.ts.map +1 -0
  19. package/_dist/graph.d.ts +13 -0
  20. package/_dist/graph.d.ts.map +1 -0
  21. package/_dist/hydrate.d.ts +36 -0
  22. package/_dist/hydrate.d.ts.map +1 -0
  23. package/_dist/identify.d.ts +7 -0
  24. package/_dist/identify.d.ts.map +1 -0
  25. package/_dist/image.d.ts +37 -0
  26. package/_dist/image.d.ts.map +1 -0
  27. package/_dist/keywords.d.ts +10 -0
  28. package/_dist/keywords.d.ts.map +1 -0
  29. package/_dist/mime.d.ts +2 -0
  30. package/_dist/mime.d.ts.map +1 -0
  31. package/_dist/mod.d.ts +97 -0
  32. package/_dist/mod.d.ts.map +1 -0
  33. package/_dist/object-put.d.ts +2 -0
  34. package/_dist/object-put.d.ts.map +1 -0
  35. package/_dist/object.d.ts +175 -0
  36. package/_dist/object.d.ts.map +1 -0
  37. package/_dist/parts.d.ts +91 -0
  38. package/_dist/parts.d.ts.map +1 -0
  39. package/_dist/plugin.d.ts +38 -0
  40. package/_dist/plugin.d.ts.map +1 -0
  41. package/_dist/png.d.ts +14 -0
  42. package/_dist/png.d.ts.map +1 -0
  43. package/_dist/props.d.ts +20 -0
  44. package/_dist/props.d.ts.map +1 -0
  45. package/_dist/representation.d.ts +17 -0
  46. package/_dist/representation.d.ts.map +1 -0
  47. package/_dist/representation_rules.d.ts +3 -0
  48. package/_dist/representation_rules.d.ts.map +1 -0
  49. package/_dist/routes.d.ts +65 -0
  50. package/_dist/routes.d.ts.map +1 -0
  51. package/_dist/serve.d.ts +29 -0
  52. package/_dist/serve.d.ts.map +1 -0
  53. package/_dist/sha256.d.ts +26 -0
  54. package/_dist/sha256.d.ts.map +1 -0
  55. package/_dist/sqlite.d.ts +57 -0
  56. package/_dist/sqlite.d.ts.map +1 -0
  57. package/_dist/store.d.ts +41 -0
  58. package/_dist/store.d.ts.map +1 -0
  59. package/_dist/stream.d.ts +91 -0
  60. package/_dist/stream.d.ts.map +1 -0
  61. package/_dist/upload.d.ts +114 -0
  62. package/_dist/upload.d.ts.map +1 -0
  63. package/_dist/value.d.ts +62 -0
  64. package/_dist/value.d.ts.map +1 -0
  65. package/_dist/vocab.d.ts +13 -0
  66. package/_dist/vocab.d.ts.map +1 -0
  67. package/accepts.js +76 -0
  68. package/accepts.js.map +1 -0
  69. package/accepts.ts +95 -0
  70. package/artifact.js +50 -0
  71. package/artifact.js.map +1 -0
  72. package/artifact.ts +93 -0
  73. package/attachment.js +190 -0
  74. package/attachment.js.map +1 -0
  75. package/attachment.ts +201 -0
  76. package/backend.js +37 -0
  77. package/backend.js.map +1 -0
  78. package/backend.ts +44 -0
  79. package/broken.js +278 -0
  80. package/broken.js.map +1 -0
  81. package/broken.ts +217 -0
  82. package/browser.js +124 -0
  83. package/browser.js.map +1 -0
  84. package/browser.ts +179 -0
  85. package/compare.js +82 -0
  86. package/compare.js.map +1 -0
  87. package/compare.ts +90 -0
  88. package/content_type.js +43 -0
  89. package/content_type.js.map +1 -0
  90. package/content_type.ts +58 -0
  91. package/deno.json +1 -0
  92. package/fixed.js +53 -0
  93. package/fixed.js.map +1 -0
  94. package/fixed.ts +61 -0
  95. package/graph.js +15 -0
  96. package/graph.js.map +1 -0
  97. package/graph.ts +22 -0
  98. package/hydrate.js +69 -0
  99. package/hydrate.js.map +1 -0
  100. package/hydrate.ts +72 -0
  101. package/identify.js +38 -0
  102. package/identify.js.map +1 -0
  103. package/identify.ts +50 -0
  104. package/image.js +111 -0
  105. package/image.js.map +1 -0
  106. package/image.ts +120 -0
  107. package/keywords.js +28 -0
  108. package/keywords.js.map +1 -0
  109. package/keywords.ts +28 -0
  110. package/meta/blob.vocab.json +17 -0
  111. package/mime.js +72 -0
  112. package/mime.js.map +1 -0
  113. package/mime.ts +73 -0
  114. package/mod.js +97 -0
  115. package/mod.js.map +1 -0
  116. package/mod.ts +115 -0
  117. package/object-put.js +90 -0
  118. package/object-put.js.map +1 -0
  119. package/object-put.ts +114 -0
  120. package/object.js +369 -0
  121. package/object.js.map +1 -0
  122. package/object.ts +592 -0
  123. package/package.json +84 -4
  124. package/parts.js +354 -0
  125. package/parts.js.map +1 -0
  126. package/parts.ts +423 -0
  127. package/plugin.js +158 -0
  128. package/plugin.js.map +1 -0
  129. package/plugin.ts +184 -0
  130. package/png.js +74 -0
  131. package/png.js.map +1 -0
  132. package/png.ts +58 -0
  133. package/props.js +32 -0
  134. package/props.js.map +1 -0
  135. package/props.ts +47 -0
  136. package/purge.js +65 -0
  137. package/purge.js.map +1 -0
  138. package/purge.ts +72 -0
  139. package/representation.js +34 -0
  140. package/representation.js.map +1 -0
  141. package/representation.ts +44 -0
  142. package/representation_rules.js +44 -0
  143. package/representation_rules.js.map +1 -0
  144. package/representation_rules.ts +57 -0
  145. package/routes.js +454 -0
  146. package/routes.js.map +1 -0
  147. package/routes.ts +575 -0
  148. package/serve.js +196 -0
  149. package/serve.js.map +1 -0
  150. package/serve.ts +242 -0
  151. package/sha256.js +185 -0
  152. package/sha256.js.map +1 -0
  153. package/sha256.ts +210 -0
  154. package/sqlite.js +201 -0
  155. package/sqlite.js.map +1 -0
  156. package/sqlite.ts +250 -0
  157. package/store.js +40 -0
  158. package/store.js.map +1 -0
  159. package/store.ts +93 -0
  160. package/stream.js +203 -0
  161. package/stream.js.map +1 -0
  162. package/stream.ts +256 -0
  163. package/upload.js +256 -0
  164. package/upload.js.map +1 -0
  165. package/upload.ts +404 -0
  166. package/value.js +234 -0
  167. package/value.js.map +1 -0
  168. package/value.ts +281 -0
  169. package/vocab.js +27 -0
  170. package/vocab.js.map +1 -0
  171. package/vocab.json +123 -0
  172. package/vocab.ts +32 -0
package/parts.ts ADDED
@@ -0,0 +1,423 @@
1
+ // Bytes too many for one request go to a bucket in parts: several at once,
2
+ // each kept as it lands, so an upload that a dropped connection, a closed tab
3
+ // or a sleeping phone cut short picks up where it stopped instead of starting
4
+ // over. The parts are the bucket's own multipart upload, the protocol S3
5
+ // defined and R2 speaks. What this module adds is what R2's Workers binding
6
+ // leaves out, the list of an upload's parts: a **ledger** of empty objects
7
+ // whose keys say which upload is under way for some bytes and which of its
8
+ // parts have landed, read back in one listing.
9
+ //
10
+ // An upload is named by the SHA-256 of its bytes, the address they are kept
11
+ // under once whole, so sending the same file again, from any device, resumes
12
+ // the same upload. Each part is hashed as it passes, on from the hash state
13
+ // the sender says the bytes before it left (sha256.ts), and its ledger entry
14
+ // keeps both states. The parts are assembled only when those states chain
15
+ // from SHA-256's start to the address, so the bytes under a key are always
16
+ // the bytes its name says, with nothing read back to check.
17
+ //
18
+ // Accepted parts also have private immutable recovery objects beside their
19
+ // receipts. Nothing expires an unfinished upload or its ledger. Only after a
20
+ // verified whole exists are its duplicate parts and active receipts removed;
21
+ // other attempts stay recoverable until a person purges them.
22
+
23
+ import { bucketCode, busy, type Objects, patient } from './object.js'
24
+ import { sleep } from '@yaks/fp'
25
+ import { fixed } from './fixed.js'
26
+ import { hasher, START } from './sha256.js'
27
+ import { HEAD } from './stream.js'
28
+
29
+ /** A bucket's multipart upload, as R2's Workers binding offers it. */
30
+ export type Multipart = {
31
+ createMultipartUpload: (key: string) => Promise<{ uploadId: string }>
32
+ resumeMultipartUpload: (key: string, uploadId: string) => Assembly
33
+ }
34
+
35
+ /** One multipart upload under way: its parts, then the whole, or nothing. */
36
+ export type Assembly = {
37
+ uploadPart: (
38
+ n: number,
39
+ value: ReadableStream<Uint8Array> | Uint8Array<ArrayBuffer>,
40
+ ) => Promise<{ partNumber: number; etag: string }>
41
+ complete: (
42
+ parts: { partNumber: number; etag: string }[],
43
+ ) => Promise<{ size: number }>
44
+ abort: () => Promise<void>
45
+ }
46
+
47
+ /** The most parts one upload has. */
48
+ export let MOST = 10_000
49
+
50
+ /** Every part size is a whole number of these, so a sender records its hash
51
+ * state once per MiB and holds the state at every part's start. */
52
+ export let MiB = 1024 * 1024
53
+
54
+ /** An upload that is not under way, never begun or aborted: begin again. */
55
+ export class Gone extends Error {}
56
+
57
+ /** A part, or a whole, that is not what it was said to be. */
58
+ export class Wrong extends Error {}
59
+
60
+ /** What a finished upload holds: its length and its first bytes, and `made`
61
+ * when this `post` assembled it rather than finding it kept already. */
62
+ export type Whole = {
63
+ bytes: number
64
+ head: Uint8Array<ArrayBuffer>
65
+ made?: boolean
66
+ }
67
+
68
+ /** Where an upload stands: the size of every part but the last, the parts
69
+ * still to send, and the whole once none are. */
70
+ export type Standing = { part: number; need: number[]; whole?: Whole }
71
+
72
+ /** One upload in parts, as {@link parts} answers it. */
73
+ export type Parts = {
74
+ post: (bytes: number) => Promise<Standing>
75
+ put: (
76
+ n: number,
77
+ body: ReadableStream<Uint8Array>,
78
+ length: number,
79
+ from?: string,
80
+ ) => Promise<void>
81
+ }
82
+
83
+ /**
84
+ * The part size for `bytes`: `part`, unless that would take more than
85
+ * {@link MOST} parts, in whole {@link MiB}. Every part but the last is this
86
+ * size, which R2 requires.
87
+ *
88
+ * ```ts
89
+ * import { equal } from '@yaks/testing'
90
+ * import { MiB, sized } from '@yaks/blob'
91
+ *
92
+ * equal(sized(20 * MiB, 8 * MiB), 8 * MiB)
93
+ * equal(sized(100_000 * MiB, 8 * MiB), 10 * MiB)
94
+ * ```
95
+ */
96
+ export let sized = (bytes: number, part: number): number =>
97
+ bytes <= part * MOST ? part : Math.ceil(bytes / MOST / MiB) * MiB
98
+
99
+ // R2's "the specified multipart upload does not exist": aborted, expired, or
100
+ // an id it never gave out.
101
+ let NO_UPLOAD = 10024
102
+
103
+ let lost = (e: unknown) => {
104
+ if (bucketCode(e) != NO_UPLOAD) throw e
105
+ }
106
+
107
+ let range = (n: number) => Array.from({ length: n }, (_, i) => i + 1)
108
+
109
+ type Ticket = { id: string; bytes: number; part: number; at: number }
110
+ type Receipt = { from: string; to: string; etag: string; at: number }
111
+
112
+ /**
113
+ * The upload of the bytes named `sha` into `key`, in parts of `part` bytes
114
+ * (more, for a file that would need over {@link MOST}), its ledger kept under
115
+ * `ledger`. `objects` is the bucket keyed by name and `bucket` the same
116
+ * bucket's multipart upload.
117
+ *
118
+ * - `post(bytes)` says where the upload stands, beginning it if nothing is
119
+ * under way, and once nothing is missing makes it whole: `whole` is set,
120
+ * and `need` is empty.
121
+ * - `put(n, body, length, from)` keeps part `n`, hashed on from `from`, the
122
+ * state the bytes before it leave ({@link START} for the first). A length
123
+ * that is not the part's is refused before anything is read, and a part
124
+ * sent twice is kept once.
125
+ *
126
+ * {@link Gone} says the upload is not under way, so it is begun again;
127
+ * {@link Wrong} says what was sent is not what was said.
128
+ */
129
+ export let parts = (
130
+ objects: Objects,
131
+ bucket: Multipart,
132
+ at: { key: string; sha: string; ledger: string; part: number },
133
+ pause: (ms: number) => Promise<void> = sleep,
134
+ ): Parts => {
135
+ let { key, sha, ledger } = at
136
+ let begun = `${ledger}${sha}.`
137
+ let ticket = (t: Omit<Ticket, 'at'>) =>
138
+ `${begun}${t.bytes}.${t.part}.${encodeURIComponent(t.id)}`
139
+ let landed = (t: Ticket) => `${ledger}${sha}/${encodeURIComponent(t.id)}/`
140
+ let count = (t: Ticket) => Math.ceil(t.bytes / t.part)
141
+ let missing = (t: Ticket) =>
142
+ `${ledger}${sha}/missing/${encodeURIComponent(t.id)}`
143
+ let retained = (t: Ticket) =>
144
+ `${ledger}${sha}/retained/${t.bytes}.${t.part}/${encodeURIComponent(t.id)}/`
145
+
146
+ // The uploads begun for these bytes, newest first: two tabs may begin one
147
+ // each, and whoever comes next carries on the newer.
148
+ let tickets = (held: Record<string, number>): Ticket[] =>
149
+ Object.entries(held).filter(([k]) => k.startsWith(begun))
150
+ .map(([k, at]) => {
151
+ let [bytes, part, ...id] = k.slice(begun.length).split('.')
152
+ let t = {
153
+ id: decodeURIComponent(id.join('.')),
154
+ bytes: +bytes,
155
+ part: +part,
156
+ }
157
+ return { ...t, at }
158
+ }).filter((t) => !(missing(t) in held)).sort((a, b) => b.at - a.at)
159
+
160
+ // Each part's states and tag, the newest where a part was sent again: the
161
+ // bucket keeps the last part sent under a number.
162
+ let receipts = (held: Record<string, number>, t: Ticket) => {
163
+ let prefix = landed(t)
164
+ let got = new Map<number, Receipt>()
165
+ for (let [k, at] of Object.entries(held)) {
166
+ if (!k.startsWith(prefix)) continue
167
+ let [n, from, to, ...etag] = k.slice(prefix.length).split('.')
168
+ let was = got.get(+n)
169
+ if (!was || was.at <= at) {
170
+ got.set(+n, { from, to, etag: decodeURIComponent(etag.join('.')), at })
171
+ }
172
+ }
173
+ return got
174
+ }
175
+
176
+ // Everything the ledger says of these bytes, in one listing.
177
+ let book = () => objects.uploaded(`${ledger}${sha}`)
178
+
179
+ let drop = (held: Record<string, number>, t: Ticket, chain: Receipt[]) =>
180
+ objects.delete([
181
+ ticket(t),
182
+ ...Object.keys(held).filter((k) =>
183
+ k.startsWith(landed(t)) ||
184
+ chain.some((r, i) =>
185
+ k.startsWith(`${retained(t)}${i + 1}.${r.from}.${r.to}.`)
186
+ )
187
+ ),
188
+ ])
189
+
190
+ let whole = async (): Promise<Whole | null> => {
191
+ let held = await objects.open(key)
192
+ if (!held) return null
193
+ let to = Math.min(HEAD, held.size) - 1
194
+ let head = to < 0 ? new Uint8Array() : new Uint8Array(
195
+ await new Response(await held.read({ from: 0, to })).arrayBuffer(),
196
+ )
197
+ return { bytes: held.size, head }
198
+ }
199
+
200
+ // The parts made whole, when their states chain from the start to `sha`.
201
+ let assemble = async (
202
+ held: Record<string, number>,
203
+ t: Ticket,
204
+ have: Map<number, Receipt>,
205
+ ) => {
206
+ let chain = range(count(t)).map((n) => have.get(n)!)
207
+ let up = bucket.resumeMultipartUpload(key, t.id)
208
+ if (
209
+ chain.some((r, i) => r.from != (i ? chain[i - 1].to : START)) ||
210
+ chain[chain.length - 1].to != sha
211
+ ) {
212
+ throw new Wrong(`the parts sent do not hash to ${sha}`)
213
+ }
214
+ try {
215
+ await patient(
216
+ async () => {
217
+ try {
218
+ return await up.complete(
219
+ chain.map((r, i) => ({ partNumber: i + 1, etag: r.etag })),
220
+ )
221
+ } catch (error) {
222
+ if (!busy(error) && bucketCode(error) != NO_UPLOAD) throw error
223
+ // Completion may have landed before its acknowledgment failed.
224
+ // Reconcile that outcome before repeating the same completion.
225
+ let done = await whole()
226
+ if (done) return { size: done.bytes }
227
+ throw error
228
+ }
229
+ },
230
+ pause,
231
+ )
232
+ } catch (e) {
233
+ // Another request finished it first, or the upload expired. Any other
234
+ // failure remains a failure and leaves the parts available to recover.
235
+ if (bucketCode(e) != NO_UPLOAD) throw e
236
+ let done = await whole()
237
+ if (done) return done
238
+ await objects.put(missing(t), new Uint8Array())
239
+ throw new Gone(`the parts of ${sha} could not be assembled: ${e}`)
240
+ }
241
+ let done = await whole()
242
+ if (!done) throw new Error(`no object at ${key} once assembled`)
243
+ await drop(held, t, chain)
244
+ return { ...done, made: true }
245
+ }
246
+
247
+ return {
248
+ post: async (bytes: number): Promise<Standing> => {
249
+ let part = sized(bytes, at.part)
250
+ let [done, held] = await Promise.all([whole(), book()])
251
+ if (done) return { part, need: [], whole: done }
252
+ let [t] = tickets(held).filter((t) => t.bytes == bytes)
253
+ if (!t) {
254
+ // Creating twice makes two uploads: unlike the numbered parts and
255
+ // their completion, this operation cannot safely be resent.
256
+ let { uploadId } = await bucket.createMultipartUpload(key)
257
+ let fresh = { id: uploadId, bytes, part, at: 0 }
258
+ await objects.put(ticket(fresh), new Uint8Array())
259
+ return { part, need: range(count(fresh)) }
260
+ }
261
+ let have = receipts(held, t)
262
+ let need = range(count(t)).filter((n) => !have.has(n))
263
+ if (need.length) return { part: t.part, need }
264
+ return { part: t.part, need, whole: await assemble(held, t, have) }
265
+ },
266
+
267
+ put: async (
268
+ n: number,
269
+ body: ReadableStream<Uint8Array>,
270
+ length: number,
271
+ from = START,
272
+ ): Promise<void> => {
273
+ let held = await book()
274
+ let [t] = tickets(held)
275
+ if (!t) throw new Gone(`no upload of ${sha} is under way`)
276
+ let last = count(t)
277
+ if (!(Number.isInteger(n) && n >= 1 && n <= last)) {
278
+ throw new Wrong(`part ${n} is not one of parts 1 to ${last}`)
279
+ }
280
+ let size = n < last ? t.part : t.bytes - t.part * (last - 1)
281
+ if (length != size) {
282
+ throw new Wrong(`part ${n} is ${size} bytes, not ${length}`)
283
+ }
284
+ if (!/^[0-9a-f]{64}$/.test(from)) {
285
+ throw new Wrong(`part ${n} needs the hash state it starts from`)
286
+ }
287
+ // The part goes to the bucket and through the hash side by side. A
288
+ // stream the bucket reads through JavaScript, hashing as it passes,
289
+ // sends a part at a third of the speed (T-124790).
290
+ let hash = hasher(from)
291
+ let recovery = new Uint8Array(length), offset = 0
292
+ let [kept, read] = body.tee()
293
+ let reader = read.getReader()
294
+ let hashed = (async () => {
295
+ for (let got; !(got = await reader.read()).done;) {
296
+ hash.add(got.value)
297
+ recovery.set(got.value, offset)
298
+ offset += got.value.byteLength
299
+ }
300
+ })()
301
+ hashed.catch(() => {})
302
+ let upload = fixed(kept, length)
303
+ let sent
304
+ try {
305
+ sent = await bucket.resumeMultipartUpload(key, t.id)
306
+ .uploadPart(n, upload.body)
307
+ await upload.done
308
+ await hashed
309
+ } catch (e) {
310
+ await Promise.allSettled([reader.cancel(e), upload.cancel(e)])
311
+ lost(e)
312
+ await objects.put(missing(t), new Uint8Array())
313
+ throw new Gone(`the upload of ${sha} has expired`)
314
+ }
315
+ let to = hash.end(n == last ? t.bytes : undefined)
316
+ // A native multipart part cannot be read back. Keep accepted bytes in
317
+ // ordinary private objects too, including attempts another part replaces.
318
+ // Its key carries enough to recover without the sender or resume token.
319
+ await objects.put(
320
+ `${retained(t)}${n}.${from}.${to}.${crypto.randomUUID()}`,
321
+ recovery,
322
+ )
323
+ let etag = encodeURIComponent(sent.etag)
324
+ await objects.put(
325
+ `${landed(t)}${n}.${from}.${to}.${etag}`,
326
+ new Uint8Array(),
327
+ )
328
+ },
329
+ }
330
+ }
331
+
332
+ /** Abort ticketed native uploads only for a person's confirmed permanent purge.
333
+ * Keep recovery objects and receipts until the caller removes that private
334
+ * ledger prefix after every abort succeeds. A retry tolerates uploads already
335
+ * completed or purged; ordinary upload cleanup never calls this. */
336
+ export let purgeParts = async (
337
+ objects: Objects,
338
+ bucket: Multipart,
339
+ at: { prefix: string; ledger: string },
340
+ pause: (ms: number) => Promise<void> = sleep,
341
+ ): Promise<void> => {
342
+ for (let key of await objects.list(at.ledger)) {
343
+ let ticket = /^([0-9a-f]{64})\.(\d+)\.(\d+)\.(.+)$/.exec(
344
+ key.slice(at.ledger.length),
345
+ )
346
+ if (!ticket) continue
347
+ let [, sha, , , id] = ticket
348
+ let up = bucket.resumeMultipartUpload(
349
+ at.prefix + sha,
350
+ decodeURIComponent(id),
351
+ )
352
+ await patient(async () => {
353
+ try {
354
+ await up.abort()
355
+ } catch (error) {
356
+ lost(error)
357
+ }
358
+ }, pause)
359
+ }
360
+ }
361
+
362
+ /**
363
+ * Multipart for a bucket that has none, its parts held in this process's
364
+ * memory and the whole written through `put`: a host's memory bucket, or a
365
+ * test's.
366
+ */
367
+ export let memoryMultipart = (
368
+ put: (key: string, bytes: Uint8Array) => Promise<unknown>,
369
+ ): Multipart => {
370
+ let open = new Map<
371
+ string,
372
+ {
373
+ key: string
374
+ parts: Map<number, { bytes: Uint8Array<ArrayBuffer>; etag: string }>
375
+ }
376
+ >()
377
+ let n = 0
378
+ let gone = () =>
379
+ Object.assign(new Error('no such upload'), { code: NO_UPLOAD })
380
+ let held = (key: string, id: string) => {
381
+ let up = open.get(id)
382
+ if (!up || up.key != key) throw gone()
383
+ return up
384
+ }
385
+ return {
386
+ createMultipartUpload: (key) => {
387
+ let uploadId = `up.${++n}/${crypto.randomUUID()}`
388
+ open.set(uploadId, { key, parts: new Map() })
389
+ return Promise.resolve({ uploadId })
390
+ },
391
+ resumeMultipartUpload: (key, id) => ({
392
+ uploadPart: async (partNumber, value) => {
393
+ let bytes = value instanceof Uint8Array
394
+ ? value.slice()
395
+ : new Uint8Array(await new Response(value).arrayBuffer())
396
+ let etag = `${partNumber}.${++n}`
397
+ held(key, id).parts.set(partNumber, { bytes, etag })
398
+ return { partNumber, etag }
399
+ },
400
+ complete: async (parts) => {
401
+ let up = held(key, id)
402
+ let chunks = parts.map(({ partNumber, etag }) => {
403
+ let part = up.parts.get(partNumber)
404
+ if (part?.etag != etag) {
405
+ throw Object.assign(new Error(`no part ${partNumber}`), {
406
+ code: 10025,
407
+ })
408
+ }
409
+ return part.bytes
410
+ })
411
+ open.delete(id)
412
+ let whole = new Uint8Array(await new Blob(chunks).arrayBuffer())
413
+ await put(key, whole)
414
+ return { size: whole.byteLength }
415
+ },
416
+ abort: () => {
417
+ held(key, id)
418
+ open.delete(id)
419
+ return Promise.resolve()
420
+ },
421
+ }),
422
+ }
423
+ }
package/plugin.js ADDED
@@ -0,0 +1,158 @@
1
+ // The substitution, as a graph plugin. A writer sends text; the row keeps the
2
+ // text's address and the bytes go to the store; a reader gets text back.
3
+ // External stores keep content in `prepare`, before the graph takes its write
4
+ // lock. Transactional stores keep it after the `$was` guard, so bytes and rows
5
+ // roll back together. Both leave text intact until the guard checks it, then
6
+ // substitute references in `precondition` and restore text in `commit`. `$blob`
7
+ // carries the prepared references and original text through the batch.
8
+ //
9
+ // Bytes outlive edits, removals and expiration: trash and history still read
10
+ // their text. Only an explicit purge may release objects no surviving row or
11
+ // historical copy names.
12
+ import { hook } from "@yaks/graph/plugin";
13
+ import { after, each } from "@yaks/fp";
14
+ import { bodies, holders } from "./props.js";
15
+ import { address, encode } from "./store.js";
16
+ import { purged } from "./purge.js";
17
+ let STASH = '$blob';
18
+ // The bundle's patch for a component, when it carries one at all. A `null`
19
+ // component is a deletion, not a value, and has no text to move.
20
+ let patch = (b, comp)=>{
21
+ let c = b[comp];
22
+ return c && typeof c == 'object' && !Array.isArray(c) ? c : undefined;
23
+ };
24
+ // One bundle's content-addressed properties that carry a string in this write.
25
+ let written = (b, props)=>props.flatMap(({ comp, prop })=>{
26
+ let value = patch(b, comp)?.[prop];
27
+ return typeof value == 'string' ? [
28
+ [
29
+ {
30
+ comp,
31
+ prop
32
+ },
33
+ value
34
+ ]
35
+ ] : [];
36
+ });
37
+ // Keep content while leaving the text available to the graph's guard.
38
+ let stage = (b, props, intern)=>{
39
+ let mine = written(b, props);
40
+ if (!mine.length) return b;
41
+ let stash = {};
42
+ let out = {
43
+ ...b
44
+ };
45
+ return after(each(mine, null, (_, [{ comp, prop }, value])=>{
46
+ return after(intern(value), (ref)=>{
47
+ stash[`${comp}.${prop}`] = {
48
+ value,
49
+ ref
50
+ };
51
+ return null;
52
+ });
53
+ }), ()=>{
54
+ out[STASH] = stash;
55
+ return out;
56
+ });
57
+ };
58
+ let swap = (b)=>{
59
+ let stash = b[STASH];
60
+ if (!stash) return b;
61
+ let out = {
62
+ ...b
63
+ };
64
+ for (let [key, { ref }] of Object.entries(stash)){
65
+ let [comp, prop] = key.split('.');
66
+ out[comp] = {
67
+ ...patch(out, comp),
68
+ [prop]: ref
69
+ };
70
+ }
71
+ return out;
72
+ };
73
+ // Put the text back where the caller wrote it, and take the stash away.
74
+ let restore = (b)=>{
75
+ let stash = b[STASH];
76
+ if (!stash) return b;
77
+ let out = {
78
+ ...b
79
+ };
80
+ delete out[STASH];
81
+ for (let [key, { value }] of Object.entries(stash)){
82
+ let [comp, prop] = key.split('.');
83
+ let held = patch(out, comp);
84
+ if (held) out[comp] = {
85
+ ...held,
86
+ [prop]: value
87
+ };
88
+ }
89
+ return out;
90
+ };
91
+ /**
92
+ * The blob plugin: content-addressed storage for every property the vocabulary
93
+ * marks `store: "blob"`.
94
+ *
95
+ * ```ts
96
+ * import { loadVocab } from '@yaks/vocab'
97
+ * import { graph } from '@yaks/graph'
98
+ * import { ram } from '@yaks/ram'
99
+ * import { blobKeywords, blobs, memoryBlobs } from '@yaks/blob'
100
+ *
101
+ * let body = { type: 'string', store: 'blob' }
102
+ * let post = { component: true, type: 'object', properties: { body } }
103
+ * let vocab = loadVocab([{ $defs: { post } }], [blobKeywords])
104
+ * let store = memoryBlobs()
105
+ * let g = graph({ storage: ram(vocab), vocab, plugins: [blobs(vocab, store)] })
106
+ * g.apply([{ entity: { eid: 'p1' }, post: { body: 'a long essay…' } }])
107
+ * ```
108
+ *
109
+ * The write side is here. The read side belongs to the storage adapter, which
110
+ * is the half that knows its own layout: over SQL, register {@link blobRead}'s
111
+ * property overrides and a row resolves in the statement itself; over any other
112
+ * store, {@link hydrate} resolves the bundles a read returned.
113
+ *
114
+ * A vocabulary loaded without {@link blobKeywords} declares no body properties,
115
+ * so this plugin is a no-op on it rather than a surprise.
116
+ */ export let blobs = (vocab, store, opts = {})=>{
117
+ let props = opts.props ?? bodies(vocab);
118
+ let keys = [
119
+ ...new Set(props.map((p)=>p.comp))
120
+ ];
121
+ let reference = opts.reference ?? ((sha)=>sha);
122
+ let prepare = (bundles)=>{
123
+ // Cache only within this batch: a rolled-back transactional reference
124
+ // must never be reused. Equal values need one hash and one store call.
125
+ let refs = new Map();
126
+ let intern = (value)=>{
127
+ let held = refs.get(value);
128
+ if (held !== undefined) return held;
129
+ let sha = address(value);
130
+ return after(store.has(sha), (exists)=>after(exists ? undefined : store.put(sha, encode(value)), ()=>after(reference(sha), (ref)=>{
131
+ refs.set(value, ref);
132
+ return ref;
133
+ })));
134
+ };
135
+ return each(bundles, [], (out, b)=>after(stage(b, props, intern), (one)=>[
136
+ ...out,
137
+ one
138
+ ]));
139
+ };
140
+ return {
141
+ name: '@yaks/blob',
142
+ purged: opts.reference ? undefined : purged(store, holders(vocab)),
143
+ // Preparing a body may retain external bytes or mint a local reference.
144
+ admission: (bundles)=>bundles.every((b)=>!written(b, props).length),
145
+ hooks: {
146
+ prepare: hook(keys, (bundles)=>store.transactional ? bundles : prepare(bundles)),
147
+ precondition: hook([
148
+ ...keys,
149
+ STASH
150
+ ], (bundles)=>after(store.transactional ? prepare(bundles) : bundles, (ready)=>ready.map(swap))),
151
+ commit: hook([
152
+ ...keys,
153
+ STASH
154
+ ], (bundles)=>bundles.map(restore))
155
+ }
156
+ };
157
+ };
158
+ //# sourceMappingURL=plugin.js.map
package/plugin.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sources":["./plugin.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,yEAAyE;AACzE,8EAA8E;AAC9E,+EAA+E;AAC/E,6EAA6E;AAC7E,gFAAgF;AAChF,uEAAuE;AACvE,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,yBAAyB;AAGzB,SAAS,IAAI,kCAAoD;AACjE,SAAS,KAAK,EAAE,IAAI,wBAA6B;AAEjD,SAAS,MAAM,EAAa,OAAO,qBAAoB;AACvD,SAAS,OAAO,EAAc,MAAM,qBAAoB;AACxD,SAAS,MAAM,qBAAoB;AAEnC,IAAI,QAAQ;AAIZ,2EAA2E;AAC3E,iEAAiE;AACjE,IAAI,QAAQ,CAAC,GAAW;EACtB,IAAI,IAAI,CAAC,CAAC,KAAK;EACf,OAAO,KAAK,OAAO,KAAK,YAAY,CAAC,MAAM,OAAO,CAAC,KAAK,IAAY;AACtE;AAEA,+EAA+E;AAC/E,IAAI,UAAU,CAAC,GAAW,QACxB,MAAM,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE;IAC3B,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