@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/object.ts
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
1
|
+
// The byte store that is a bucket: one object per address, in an S3-shaped
|
|
2
|
+
// object store. It is the store for content that outgrows the database —
|
|
3
|
+
// images, attachments, anything measured in megabytes — and for a deployment
|
|
4
|
+
// where the database is small and the content is not.
|
|
5
|
+
//
|
|
6
|
+
// The bucket is passed in as an argument and its type is structural: the
|
|
7
|
+
// methods this package calls, and nothing else. Cloudflare's `R2Bucket`
|
|
8
|
+
// satisfies it as it stands (conform.ts type-checks that against the runtime's
|
|
9
|
+
// own types), and so does any wrapper offering the same — which is why this
|
|
10
|
+
// package depends on no cloud SDK and still runs inside one.
|
|
11
|
+
//
|
|
12
|
+
// Two stores are built on it. `objectBlobs` is content-addressed: the object's
|
|
13
|
+
// key is its address, so a write is idempotent and a stored object can never
|
|
14
|
+
// be the wrong one for its key, and it needs only `head`, `get` and `put`, and
|
|
15
|
+
// `delete` to let go of a stream staged until its address was known.
|
|
16
|
+
// `bucketObjects` is keyed by name, the way a host keeps an app's files: the
|
|
17
|
+
// caller chooses the key, and it also deletes and lists, since files are
|
|
18
|
+
// replaced and swept where content-addressed bytes are not.
|
|
19
|
+
|
|
20
|
+
import { type Clock, hedge, sleep, system } from '@yaks/fp'
|
|
21
|
+
import {
|
|
22
|
+
type Discard,
|
|
23
|
+
discardNow,
|
|
24
|
+
publishing,
|
|
25
|
+
streaming,
|
|
26
|
+
} from './object-put.js'
|
|
27
|
+
import type { Multipart } from './parts.ts'
|
|
28
|
+
import type { Blobs } from './store.ts'
|
|
29
|
+
import { hashing, type Put, type Staged, type Streamed } from './stream.js'
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The bucket these stores call, keyed by string. Cloudflare R2's `R2Bucket` is
|
|
33
|
+
* one of these; so is any object store wrapped to match.
|
|
34
|
+
*/
|
|
35
|
+
export type Bucket = {
|
|
36
|
+
/** whether an object exists under this key (its metadata, or null) */
|
|
37
|
+
head: (key: string) => Promise<{ size: number; etag: string } | null>
|
|
38
|
+
/** the object under this key, or null */
|
|
39
|
+
get: (
|
|
40
|
+
key: string,
|
|
41
|
+
options?: { range: { offset: number; length: number } },
|
|
42
|
+
) => Promise<
|
|
43
|
+
{
|
|
44
|
+
size: number
|
|
45
|
+
etag: string
|
|
46
|
+
body: ReadableStream<Uint8Array>
|
|
47
|
+
arrayBuffer: () => Promise<ArrayBuffer>
|
|
48
|
+
} | null
|
|
49
|
+
>
|
|
50
|
+
/** write an object under this key; a stream must be of a known length,
|
|
51
|
+
* which {@link bucketObjects} gives it */
|
|
52
|
+
put: (
|
|
53
|
+
key: string,
|
|
54
|
+
value: ArrayBuffer | ArrayBufferView | string | ReadableStream<Uint8Array>,
|
|
55
|
+
) => Promise<unknown>
|
|
56
|
+
/** remove the object under this key, or under each of these keys: at most
|
|
57
|
+
* {@link DELETES} of them in one call */
|
|
58
|
+
delete: (keys: string | string[]) => Promise<unknown>
|
|
59
|
+
/** one page of the objects whose keys start with `prefix`, each with the
|
|
60
|
+
* moment it landed and its size in bytes; `cursor` continues a truncated
|
|
61
|
+
* page */
|
|
62
|
+
list: (
|
|
63
|
+
opts: {
|
|
64
|
+
prefix: string
|
|
65
|
+
cursor?: string
|
|
66
|
+
limit?: number
|
|
67
|
+
startAfter?: string
|
|
68
|
+
},
|
|
69
|
+
) => Promise<{
|
|
70
|
+
objects: { key: string; uploaded: Date; size: number }[]
|
|
71
|
+
truncated: boolean
|
|
72
|
+
cursor?: string
|
|
73
|
+
}>
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The most keys one bucket delete takes: R2's own limit. */
|
|
77
|
+
export let DELETES = 1000
|
|
78
|
+
|
|
79
|
+
// R2's answers that say "not now" rather than "no", each of which its error
|
|
80
|
+
// codes page says to retry: an internal error (10001), the service unavailable
|
|
81
|
+
// (10043), and too many requests at once for one key or prefix (10058).
|
|
82
|
+
let BUSY = [10001, 10043, 10058]
|
|
83
|
+
|
|
84
|
+
/** R2's code, whether carried as a property or in the Workers binding's message. */
|
|
85
|
+
export let bucketCode = (e: unknown): number | undefined => {
|
|
86
|
+
let { code, message } = Object(e)
|
|
87
|
+
if (code != null && Number.isFinite(Number(code))) return Number(code)
|
|
88
|
+
let match = typeof message == 'string' ? /\((\d+)\)\s*$/.exec(message) : null
|
|
89
|
+
return match ? Number(match[1]) : undefined
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Whether the bucket failed on its own side, including the Workers binding
|
|
93
|
+
* which carries R2's code in its message rather than on the Error. */
|
|
94
|
+
export let busy = (e: unknown): boolean => {
|
|
95
|
+
let { status, statusCode, message, retryable } = Object(e)
|
|
96
|
+
let http = Number(status ?? statusCode)
|
|
97
|
+
return BUSY.includes(bucketCode(e) ?? 0) ||
|
|
98
|
+
retryable === true && message === 'Network connection lost.' ||
|
|
99
|
+
// workerd uses this fallback when the HTTP error has no CF-R2-Error
|
|
100
|
+
// header. Uploading the same numbered part can safely be sent again.
|
|
101
|
+
message === 'uploadPart: Unspecified error (0)' ||
|
|
102
|
+
http >= 500 && http < 600 ||
|
|
103
|
+
typeof message == 'string' &&
|
|
104
|
+
/\b(?:HTTP|status(?: code)?)[: =]+5\d\d\b/i.test(message)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A bucket that kept failing on its own side through every attempt. */
|
|
108
|
+
export class BucketUnavailable extends Error {
|
|
109
|
+
override name = 'BucketUnavailable'
|
|
110
|
+
constructor(cause: unknown) {
|
|
111
|
+
super(
|
|
112
|
+
typeof Object(cause).message == 'string'
|
|
113
|
+
? Object(cause).message
|
|
114
|
+
: String(cause),
|
|
115
|
+
{ cause },
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* A bucket call, sent again while the bucket answers that it is busy: a burst
|
|
122
|
+
* of uploads to one space is enough for R2 to refuse some of them, and R2's
|
|
123
|
+
* internal error (10001) can last a few seconds. Each wait
|
|
124
|
+
* doubles from `wait` milliseconds, jittered so calls that collided once do not
|
|
125
|
+
* collide again, and after `tries` throws {@link BucketUnavailable} with the
|
|
126
|
+
* last answer as its cause: by default about six seconds of waiting, since a
|
|
127
|
+
* file that opens late is better than one that fails. Other failures are
|
|
128
|
+
* thrown at once. `pause` spends each wait, a timer unless the caller brings
|
|
129
|
+
* its own. Every call the stores below make to a bucket goes through it; a
|
|
130
|
+
* stream is read once, so a put of one is sent again only by a caller that
|
|
131
|
+
* can open its source again (`staging`).
|
|
132
|
+
*
|
|
133
|
+
* ```ts
|
|
134
|
+
* import { patient } from '@yaks/blob'
|
|
135
|
+
* import { equal } from '@yaks/testing'
|
|
136
|
+
*
|
|
137
|
+
* let calls = 0, waits: number[] = []
|
|
138
|
+
* let list = () =>
|
|
139
|
+
* ++calls < 3 ? Promise.reject({ code: 10058 }) : Promise.resolve(['a/x'])
|
|
140
|
+
* let pause = (ms: number) => Promise.resolve(void waits.push(ms))
|
|
141
|
+
* equal(await patient(list, pause), ['a/x'])
|
|
142
|
+
* equal(waits.length, 2)
|
|
143
|
+
* ```
|
|
144
|
+
*/
|
|
145
|
+
export let patient = async <T>(
|
|
146
|
+
call: () => Promise<T>,
|
|
147
|
+
pause: (ms: number) => Promise<void> = sleep,
|
|
148
|
+
tries = 7,
|
|
149
|
+
wait = 100,
|
|
150
|
+
): Promise<T> => {
|
|
151
|
+
for (let i = 1;; i++) {
|
|
152
|
+
try {
|
|
153
|
+
return await call()
|
|
154
|
+
} catch (e) {
|
|
155
|
+
if (!busy(e)) throw e
|
|
156
|
+
if (i >= tries) throw new BucketUnavailable(e)
|
|
157
|
+
await pause(wait * 2 ** (i - 1) * (0.5 + Math.random()))
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** An object replaced by another writer between opening it and reading its
|
|
163
|
+
* bytes. Its reader holds a stale version: open the key again. */
|
|
164
|
+
export class ObjectChanged extends Error {
|
|
165
|
+
override name = 'ObjectChanged'
|
|
166
|
+
constructor(key: string) {
|
|
167
|
+
super(`object at ${key} changed while reading`)
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** A stored object's length and validator, with its body read on demand. */
|
|
172
|
+
export type Opened = {
|
|
173
|
+
size: number
|
|
174
|
+
version: string
|
|
175
|
+
read: (
|
|
176
|
+
range?: { from: number; to: number },
|
|
177
|
+
) => Promise<ReadableStream<Uint8Array>>
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** Bytes in hand, opened the way a stored object is. */
|
|
181
|
+
export let openedOf = (bytes: Uint8Array, version = ''): Opened => ({
|
|
182
|
+
size: bytes.length,
|
|
183
|
+
version,
|
|
184
|
+
read: ({ from, to } = { from: 0, to: bytes.length - 1 }) =>
|
|
185
|
+
Promise.resolve(
|
|
186
|
+
new Blob([bytes.slice(from, to + 1)]).stream() as ReadableStream<
|
|
187
|
+
Uint8Array
|
|
188
|
+
>,
|
|
189
|
+
),
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
/** View a bounded span of an opened object as a file in its own right. */
|
|
193
|
+
export let sliceOf = (
|
|
194
|
+
object: Opened | null | undefined,
|
|
195
|
+
offset: number,
|
|
196
|
+
size: number,
|
|
197
|
+
version: string,
|
|
198
|
+
): Opened | null => {
|
|
199
|
+
if (
|
|
200
|
+
!object || !Number.isSafeInteger(offset) || offset < 0 ||
|
|
201
|
+
!Number.isSafeInteger(size) || size < 1 || size > object.size - offset
|
|
202
|
+
) return null
|
|
203
|
+
return {
|
|
204
|
+
size,
|
|
205
|
+
version,
|
|
206
|
+
read: ({ from, to } = { from: 0, to: size - 1 }) =>
|
|
207
|
+
object.read({ from: offset + from, to: offset + to }),
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export type Loaded = { bytes: Uint8Array<ArrayBuffer>; version: string }
|
|
212
|
+
|
|
213
|
+
type Pause = (ms: number) => Promise<void>
|
|
214
|
+
|
|
215
|
+
/** How long a whole read waits before asking the bucket a second time. */
|
|
216
|
+
let HEDGE = 1000
|
|
217
|
+
|
|
218
|
+
// Consume a buffered read inside the retry: an R2 body can fail after GET
|
|
219
|
+
// has answered, and sending GET again gives that read a fresh body. A read
|
|
220
|
+
// still unanswered after `HEDGE` is sent again beside it (@yaks/fp `hedge`):
|
|
221
|
+
// a slow bucket's tail held one preview read 9.3 s (T-5020).
|
|
222
|
+
let load = (
|
|
223
|
+
bucket: Pick<Bucket, 'get'>,
|
|
224
|
+
key: string,
|
|
225
|
+
pause: Pause,
|
|
226
|
+
time: Clock = system,
|
|
227
|
+
) =>
|
|
228
|
+
patient(
|
|
229
|
+
() =>
|
|
230
|
+
hedge(
|
|
231
|
+
async (): Promise<Loaded | null> => {
|
|
232
|
+
let object = await bucket.get(key)
|
|
233
|
+
return object
|
|
234
|
+
? {
|
|
235
|
+
bytes: new Uint8Array(await object.arrayBuffer()),
|
|
236
|
+
version: object.etag.replace(/^"|"$/g, ''),
|
|
237
|
+
}
|
|
238
|
+
: null
|
|
239
|
+
},
|
|
240
|
+
HEDGE,
|
|
241
|
+
time,
|
|
242
|
+
),
|
|
243
|
+
pause,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
// A stream can fail after GET answered. Resume at the first byte not yet
|
|
247
|
+
// delivered, and require the same validator so two versions never mix. Read
|
|
248
|
+
// its first chunk before answering, while a failure can still become HTTP 500.
|
|
249
|
+
let reading = async (
|
|
250
|
+
bucket: Pick<Bucket, 'get'>,
|
|
251
|
+
key: string,
|
|
252
|
+
head: { size: number; etag: string },
|
|
253
|
+
range: { from: number; to: number } | undefined,
|
|
254
|
+
pause: Pause,
|
|
255
|
+
initial?: ReadableStreamDefaultReader<Uint8Array>,
|
|
256
|
+
) => {
|
|
257
|
+
let offset = range?.from ?? 0, end = range?.to ?? head.size - 1
|
|
258
|
+
let reader = initial
|
|
259
|
+
let cancelled = false, reason: unknown
|
|
260
|
+
let next = () =>
|
|
261
|
+
patient(
|
|
262
|
+
async () => {
|
|
263
|
+
if (cancelled) return { done: true, value: undefined } as const
|
|
264
|
+
try {
|
|
265
|
+
if (!reader) {
|
|
266
|
+
let object = await bucket.get(
|
|
267
|
+
key,
|
|
268
|
+
range || offset
|
|
269
|
+
? { range: { offset, length: end - offset + 1 } }
|
|
270
|
+
: undefined,
|
|
271
|
+
)
|
|
272
|
+
if (cancelled) {
|
|
273
|
+
await object?.body.cancel(reason)
|
|
274
|
+
return { done: true, value: undefined } as const
|
|
275
|
+
}
|
|
276
|
+
if (!object) throw new Error(`no object at ${key}`)
|
|
277
|
+
if (object.etag != head.etag) {
|
|
278
|
+
await object.body.cancel().catch(() => {})
|
|
279
|
+
throw new ObjectChanged(key)
|
|
280
|
+
}
|
|
281
|
+
reader = object.body.getReader()
|
|
282
|
+
}
|
|
283
|
+
return await reader.read()
|
|
284
|
+
} catch (error) {
|
|
285
|
+
await reader?.cancel().catch(() => {})
|
|
286
|
+
reader = undefined
|
|
287
|
+
throw error
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
pause,
|
|
291
|
+
)
|
|
292
|
+
let first = await next()
|
|
293
|
+
let send = (
|
|
294
|
+
controller: ReadableStreamDefaultController<Uint8Array>,
|
|
295
|
+
chunk: ReadableStreamReadResult<Uint8Array>,
|
|
296
|
+
) => {
|
|
297
|
+
if (cancelled) return
|
|
298
|
+
if (chunk.done) return controller.close()
|
|
299
|
+
offset += chunk.value.byteLength
|
|
300
|
+
controller.enqueue(chunk.value)
|
|
301
|
+
if (offset > end) {
|
|
302
|
+
controller.close()
|
|
303
|
+
void reader?.cancel().catch(() => {})
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return new ReadableStream<Uint8Array>({
|
|
307
|
+
start: (controller) => send(controller, first),
|
|
308
|
+
pull: async (controller) => send(controller, await next()),
|
|
309
|
+
cancel: (why) => {
|
|
310
|
+
cancelled = true
|
|
311
|
+
reason = why
|
|
312
|
+
return reader?.cancel(why)
|
|
313
|
+
},
|
|
314
|
+
})
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Open a whole object with a single GET. A first-chunk failure can still
|
|
318
|
+
* fail the response, and an interrupted body resumes at its last byte. */
|
|
319
|
+
export let wholeObject = async (
|
|
320
|
+
bucket: Pick<Bucket, 'get'>,
|
|
321
|
+
key: string,
|
|
322
|
+
pause: Pause = sleep,
|
|
323
|
+
): Promise<{ size: number; body: ReadableStream<Uint8Array> } | null> => {
|
|
324
|
+
let object = await patient(() => bucket.get(key), pause)
|
|
325
|
+
return object && {
|
|
326
|
+
size: object.size,
|
|
327
|
+
body: await reading(
|
|
328
|
+
bucket,
|
|
329
|
+
key,
|
|
330
|
+
object,
|
|
331
|
+
undefined,
|
|
332
|
+
pause,
|
|
333
|
+
object.body.getReader(),
|
|
334
|
+
),
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Read an object up to the caller's byte limit. Missing objects return null;
|
|
339
|
+
* objects above the limit return undefined. */
|
|
340
|
+
export let smallObject = (
|
|
341
|
+
bucket: Pick<Bucket, 'get'>,
|
|
342
|
+
key: string,
|
|
343
|
+
most: number,
|
|
344
|
+
pause: Pause = sleep,
|
|
345
|
+
): Promise<Uint8Array<ArrayBuffer> | null | undefined> =>
|
|
346
|
+
patient(async () => {
|
|
347
|
+
let object = await bucket.get(key)
|
|
348
|
+
if (!object) return null
|
|
349
|
+
if (object.size <= most) return new Uint8Array(await object.arrayBuffer())
|
|
350
|
+
await object.body.cancel()
|
|
351
|
+
}, pause)
|
|
352
|
+
|
|
353
|
+
let open = async (
|
|
354
|
+
bucket: Pick<Bucket, 'head' | 'get'>,
|
|
355
|
+
key: string,
|
|
356
|
+
pause: Pause,
|
|
357
|
+
) => {
|
|
358
|
+
let head = await patient(() => bucket.head(key), pause)
|
|
359
|
+
if (!head) return null
|
|
360
|
+
return {
|
|
361
|
+
size: head.size,
|
|
362
|
+
version: head.etag.replace(/^"|"$/g, ''),
|
|
363
|
+
read: (range?: { from: number; to: number }) =>
|
|
364
|
+
reading(bucket, key, head, range, pause),
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* A {@link Blobs} over an object store. `prefix` namespaces the keys, for a
|
|
370
|
+
* bucket that holds more than these objects.
|
|
371
|
+
*
|
|
372
|
+
* ```ts
|
|
373
|
+
* import { objectBlobs } from '@yaks/blob'
|
|
374
|
+
*
|
|
375
|
+
* // in a Worker, where `env.BLOBS` is an R2 binding
|
|
376
|
+
* // let store = objectBlobs(env.BLOBS, 'bodies/')
|
|
377
|
+
* ```
|
|
378
|
+
*
|
|
379
|
+
* Asynchronous, so a graph writing through it applies asynchronously.
|
|
380
|
+
*/
|
|
381
|
+
export let objectBlobs = (
|
|
382
|
+
bucket: Pick<Bucket, 'head' | 'get' | 'put' | 'delete'> & Partial<Multipart>,
|
|
383
|
+
prefix = '',
|
|
384
|
+
pause: Pause = sleep,
|
|
385
|
+
): Blobs => ({
|
|
386
|
+
exact: true,
|
|
387
|
+
has: async (sha) =>
|
|
388
|
+
(await patient(() => bucket.head(prefix + sha), pause)) != null,
|
|
389
|
+
get: async (sha) => {
|
|
390
|
+
let found = await load(bucket, prefix + sha, pause)
|
|
391
|
+
return found?.bytes
|
|
392
|
+
},
|
|
393
|
+
open: (sha) => open(bucket, prefix + sha, pause),
|
|
394
|
+
put: async (sha, bytes) => {
|
|
395
|
+
await patient(() => bucket.put(prefix + sha, bytes), pause)
|
|
396
|
+
},
|
|
397
|
+
...bucket.createMultipartUpload && bucket.resumeMultipartUpload
|
|
398
|
+
? {
|
|
399
|
+
publish: (sha, sent, check) =>
|
|
400
|
+
publishing(bucket, pause, discardNow)(prefix + sha, sent, check),
|
|
401
|
+
}
|
|
402
|
+
: {},
|
|
403
|
+
stage: staging(
|
|
404
|
+
{
|
|
405
|
+
put: streaming(bucket, pause, discardNow),
|
|
406
|
+
open: (key) => open(bucket, key, pause),
|
|
407
|
+
has: async (key) =>
|
|
408
|
+
(await patient(() => bucket.head(key), pause)) != null,
|
|
409
|
+
delete: (key) => patient(() => bucket.delete(key), pause).then(() => {}),
|
|
410
|
+
},
|
|
411
|
+
prefix,
|
|
412
|
+
pause,
|
|
413
|
+
),
|
|
414
|
+
})
|
|
415
|
+
|
|
416
|
+
/** Where a stream waits, under a key of its own, until its address is known
|
|
417
|
+
* (`staging`). Whatever is left here was dropped by a process that ended
|
|
418
|
+
* before it could let it go. */
|
|
419
|
+
export let STAGING = 'staging/'
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* A content-addressed store's `stage` over a store keyed by name: the stream
|
|
423
|
+
* lands at a key under {@link STAGING}, hashed as it passes, and `keep` moves
|
|
424
|
+
* it to `prefix` and its address. A bucket has no copy, so the move streams
|
|
425
|
+
* the staged object into the put, and is sent again, from a fresh read, while
|
|
426
|
+
* the bucket answers that it is busy.
|
|
427
|
+
*/
|
|
428
|
+
export let staging = (
|
|
429
|
+
objects: Pick<Objects, 'open' | 'has' | 'delete'> & {
|
|
430
|
+
put: (key: string, sent: Streamed) => Promise<void>
|
|
431
|
+
},
|
|
432
|
+
prefix: string,
|
|
433
|
+
pause: Pause = sleep,
|
|
434
|
+
discard: Discard = discardNow,
|
|
435
|
+
) =>
|
|
436
|
+
async (sent: Streamed, most = Infinity): Promise<Staged> => {
|
|
437
|
+
let key = `${STAGING}${Date.now()}.${crypto.randomUUID()}`
|
|
438
|
+
let drop = () => discard(() => objects.delete(key))
|
|
439
|
+
let { through, seen } = hashing(sent.size, most)
|
|
440
|
+
try {
|
|
441
|
+
await objects.put(key, {
|
|
442
|
+
stream: sent.stream.pipeThrough(through),
|
|
443
|
+
size: sent.size,
|
|
444
|
+
})
|
|
445
|
+
let { sha, size, head } = await seen
|
|
446
|
+
let read = async () => {
|
|
447
|
+
let held = await objects.open(key)
|
|
448
|
+
if (!held) throw new Error(`no object at ${key}`)
|
|
449
|
+
return await held.read()
|
|
450
|
+
}
|
|
451
|
+
let keep = async () => {
|
|
452
|
+
if (await objects.has(prefix + sha)) return
|
|
453
|
+
await patient(async () => {
|
|
454
|
+
await objects.put(prefix + sha, {
|
|
455
|
+
stream: await read(),
|
|
456
|
+
size,
|
|
457
|
+
})
|
|
458
|
+
}, pause)
|
|
459
|
+
}
|
|
460
|
+
return { sha, size, head, read, keep, drop }
|
|
461
|
+
} catch (e) {
|
|
462
|
+
await drop().catch(() => {})
|
|
463
|
+
throw e
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* The {@link Blobs} kept in `objects` under `prefix`, each by its address
|
|
469
|
+
* after it: a host's bucket as the host reaches it, counted or cached,
|
|
470
|
+
* holding one app's files beside every other's.
|
|
471
|
+
*
|
|
472
|
+
* ```ts
|
|
473
|
+
* import { bucketObjects, prefixed } from '@yaks/blob'
|
|
474
|
+
*
|
|
475
|
+
* // in a Worker, where `env.BLOBS` is an R2 binding
|
|
476
|
+
* // let photos = prefixed(bucketObjects(env.BLOBS), 'ada/photos/blobs/')
|
|
477
|
+
* ```
|
|
478
|
+
*/
|
|
479
|
+
export let prefixed = (
|
|
480
|
+
objects: Objects,
|
|
481
|
+
prefix: string,
|
|
482
|
+
discard?: Discard,
|
|
483
|
+
): Blobs => ({
|
|
484
|
+
exact: true,
|
|
485
|
+
has: (sha) => objects.has(prefix + sha),
|
|
486
|
+
get: async (sha) => (await objects.read(prefix + sha)) ?? undefined,
|
|
487
|
+
open: (sha) => objects.open(prefix + sha),
|
|
488
|
+
put: (sha, bytes) => objects.put(prefix + sha, bytes),
|
|
489
|
+
publish: objects.publish &&
|
|
490
|
+
((sha, sent, check) => objects.publish!(prefix + sha, sent, check)),
|
|
491
|
+
stage: staging(objects, prefix, undefined, discard),
|
|
492
|
+
})
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* A byte store keyed by name: the caller chooses each key, where {@link Blobs}
|
|
496
|
+
* derives it from the bytes. It is how a host keeps files that are replaced
|
|
497
|
+
* and swept, an app's pages among them.
|
|
498
|
+
*/
|
|
499
|
+
export type Objects = {
|
|
500
|
+
/** whether an object is stored under this key */
|
|
501
|
+
has(key: string): Promise<boolean>
|
|
502
|
+
/** store these bytes under this key, replacing what was there: held
|
|
503
|
+
* whole, or streamed ({@link Streamed}) */
|
|
504
|
+
put(key: string, bytes: Put): Promise<void>
|
|
505
|
+
/** Stream bytes to this key, making them visible only after `check` passes. */
|
|
506
|
+
publish?<T>(key: string, sent: Streamed, check: () => Promise<T>): Promise<T>
|
|
507
|
+
/** the bytes under this key, or null; a miss is one round trip, like a hit,
|
|
508
|
+
* where `has` then `get` is two */
|
|
509
|
+
read(key: string): Promise<Uint8Array<ArrayBuffer> | null>
|
|
510
|
+
/** bytes and their validator in the same object-store read */
|
|
511
|
+
load(key: string): Promise<Loaded | null>
|
|
512
|
+
/** the bytes under a key the caller knows is there; a miss throws */
|
|
513
|
+
get(key: string): Promise<Uint8Array<ArrayBuffer>>
|
|
514
|
+
/** length and validator first, then stream only the bytes the caller needs */
|
|
515
|
+
open(key: string): Promise<Opened | null>
|
|
516
|
+
/** remove the object under this key, or under each of these keys in as few
|
|
517
|
+
* round trips as the bucket allows: a sweep of a thousand objects is one
|
|
518
|
+
* call, not a thousand */
|
|
519
|
+
delete(keys: string | string[]): Promise<void>
|
|
520
|
+
/** every key under a prefix, sorted */
|
|
521
|
+
list(prefix: string): Promise<string[]>
|
|
522
|
+
/** the same keys, each with the moment it landed in epoch milliseconds: a
|
|
523
|
+
* sweep must not delete bytes written a minute ago for a row that has not
|
|
524
|
+
* landed yet */
|
|
525
|
+
uploaded(prefix: string): Promise<Record<string, number>>
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// One walk of the prefix, every page of it, as key to when the object landed.
|
|
529
|
+
// `list` is this with the times dropped, so the two answers can never disagree
|
|
530
|
+
// about what is in the bucket.
|
|
531
|
+
let walk = async (bucket: Bucket, prefix: string, pause: Pause) => {
|
|
532
|
+
let at: Record<string, number> = {}
|
|
533
|
+
let cursor: string | undefined
|
|
534
|
+
do {
|
|
535
|
+
let page = await patient(
|
|
536
|
+
() => bucket.list({ prefix, cursor }),
|
|
537
|
+
pause,
|
|
538
|
+
)
|
|
539
|
+
for (let o of page.objects) at[o.key] = o.uploaded.getTime()
|
|
540
|
+
cursor = page.truncated ? page.cursor : undefined
|
|
541
|
+
} while (cursor)
|
|
542
|
+
return at
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* An {@link Objects} over a bucket, key for key.
|
|
547
|
+
*
|
|
548
|
+
* ```ts
|
|
549
|
+
* import { bucketObjects } from '@yaks/blob'
|
|
550
|
+
*
|
|
551
|
+
* // in a Worker, where `env.BLOBS` is an R2 binding
|
|
552
|
+
* // let files = bucketObjects(env.BLOBS)
|
|
553
|
+
* ```
|
|
554
|
+
*/
|
|
555
|
+
export let bucketObjects = (
|
|
556
|
+
bucket: Bucket & Partial<Multipart>,
|
|
557
|
+
pause: Pause = sleep,
|
|
558
|
+
discard: Discard = discardNow,
|
|
559
|
+
time: Clock = system,
|
|
560
|
+
): Objects => ({
|
|
561
|
+
has: async (key) => (await patient(() => bucket.head(key), pause)) != null,
|
|
562
|
+
put: async (key, bytes) => {
|
|
563
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
564
|
+
return streaming(bucket, pause, discard)(key, bytes)
|
|
565
|
+
}
|
|
566
|
+
await patient(() => bucket.put(key, bytes), pause)
|
|
567
|
+
},
|
|
568
|
+
publish: bucket.createMultipartUpload && bucket.resumeMultipartUpload
|
|
569
|
+
? publishing(bucket, pause, discard)
|
|
570
|
+
: undefined,
|
|
571
|
+
read: async (key) => (await load(bucket, key, pause, time))?.bytes ?? null,
|
|
572
|
+
load: (key) => load(bucket, key, pause, time),
|
|
573
|
+
get: async (key) => {
|
|
574
|
+
let object = await load(bucket, key, pause, time)
|
|
575
|
+
if (!object) throw new Error(`no object at ${key}`)
|
|
576
|
+
return object.bytes
|
|
577
|
+
},
|
|
578
|
+
open: (key) => open(bucket, key, pause),
|
|
579
|
+
delete: async (keys) => {
|
|
580
|
+
if (typeof keys == 'string') {
|
|
581
|
+
return void await patient(() => bucket.delete(keys), pause)
|
|
582
|
+
}
|
|
583
|
+
for (let at = 0; at < keys.length; at += DELETES) {
|
|
584
|
+
await patient(
|
|
585
|
+
() => bucket.delete(keys.slice(at, at + DELETES)),
|
|
586
|
+
pause,
|
|
587
|
+
)
|
|
588
|
+
}
|
|
589
|
+
},
|
|
590
|
+
list: async (prefix) => Object.keys(await walk(bucket, prefix, pause)).sort(),
|
|
591
|
+
uploaded: (prefix) => walk(bucket, prefix, pause),
|
|
592
|
+
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,86 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yaks/blob",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.36",
|
|
4
|
+
"homepage": "https://jsr.io/@yaks/blob",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./_dist/mod.d.ts",
|
|
9
|
+
"default": "./mod.js"
|
|
10
|
+
},
|
|
11
|
+
"./attachment": {
|
|
12
|
+
"types": "./_dist/attachment.d.ts",
|
|
13
|
+
"default": "./attachment.js"
|
|
14
|
+
},
|
|
15
|
+
"./identify": {
|
|
16
|
+
"types": "./_dist/identify.d.ts",
|
|
17
|
+
"default": "./identify.js"
|
|
18
|
+
},
|
|
19
|
+
"./object": {
|
|
20
|
+
"types": "./_dist/object.d.ts",
|
|
21
|
+
"default": "./object.js"
|
|
22
|
+
},
|
|
23
|
+
"./backend": {
|
|
24
|
+
"types": "./_dist/backend.d.ts",
|
|
25
|
+
"default": "./backend.js"
|
|
26
|
+
},
|
|
27
|
+
"./store": {
|
|
28
|
+
"types": "./_dist/store.d.ts",
|
|
29
|
+
"default": "./store.js"
|
|
30
|
+
},
|
|
31
|
+
"./stream": {
|
|
32
|
+
"types": "./_dist/stream.d.ts",
|
|
33
|
+
"default": "./stream.js"
|
|
34
|
+
},
|
|
35
|
+
"./compare": {
|
|
36
|
+
"types": "./_dist/compare.d.ts",
|
|
37
|
+
"default": "./compare.js"
|
|
38
|
+
},
|
|
39
|
+
"./sqlite": {
|
|
40
|
+
"types": "./_dist/sqlite.d.ts",
|
|
41
|
+
"default": "./sqlite.js"
|
|
42
|
+
},
|
|
43
|
+
"./vocab": {
|
|
44
|
+
"types": "./_dist/vocab.d.ts",
|
|
45
|
+
"default": "./vocab.js"
|
|
46
|
+
},
|
|
47
|
+
"./graph": {
|
|
48
|
+
"types": "./_dist/graph.d.ts",
|
|
49
|
+
"default": "./graph.js"
|
|
50
|
+
},
|
|
51
|
+
"./routes": {
|
|
52
|
+
"types": "./_dist/routes.d.ts",
|
|
53
|
+
"default": "./routes.js"
|
|
54
|
+
},
|
|
55
|
+
"./upload": {
|
|
56
|
+
"types": "./_dist/upload.d.ts",
|
|
57
|
+
"default": "./upload.js"
|
|
58
|
+
},
|
|
59
|
+
"./serve": {
|
|
60
|
+
"types": "./_dist/serve.d.ts",
|
|
61
|
+
"default": "./serve.js"
|
|
62
|
+
},
|
|
63
|
+
"./png": {
|
|
64
|
+
"types": "./_dist/png.d.ts",
|
|
65
|
+
"default": "./png.js"
|
|
66
|
+
},
|
|
67
|
+
"./browser": {
|
|
68
|
+
"types": "./_dist/browser.d.ts",
|
|
69
|
+
"default": "./browser.js"
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"license": "Apache-2.0",
|
|
73
|
+
"dependencies": {
|
|
74
|
+
"@yaks/api": "0.2.36",
|
|
75
|
+
"@yaks/fp": "0.2.36",
|
|
76
|
+
"@yaks/graph": "0.2.36",
|
|
77
|
+
"@yaks/query": "0.2.36",
|
|
78
|
+
"@yaks/ram": "0.2.36",
|
|
79
|
+
"@yaks/sql": "0.2.36",
|
|
80
|
+
"@yaks/tools": "0.2.36",
|
|
81
|
+
"@yaks/vocab": "0.2.36",
|
|
82
|
+
"file-type": "21.3.4"
|
|
83
|
+
},
|
|
84
|
+
"description": "Stores text and binary content under SHA-256 addresses, with transparent graph text reads and writes, verified artifacts and HTTP responses.",
|
|
85
|
+
"repository": "https://github.com/yak-sh/yak.git"
|
|
86
|
+
}
|