@hamur/blob 0.0.0-stage → 0.0.1

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 (43) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +51 -2
  3. package/dist/src/client/index.js +158 -0
  4. package/dist/src/index.js +220 -0
  5. package/dist/src/server/index.js +498 -0
  6. package/dist/types/src/build/setup.d.ts +7 -0
  7. package/dist/types/src/client/index.d.ts +28 -0
  8. package/dist/types/src/drivers/cloudflare-r2.d.ts +75 -0
  9. package/dist/types/src/drivers/fs.d.ts +14 -0
  10. package/dist/types/src/drivers/s3.d.ts +12 -0
  11. package/dist/types/src/drivers/suite.d.ts +9 -0
  12. package/dist/types/src/index.d.ts +2 -0
  13. package/dist/types/src/module.d.ts +3 -0
  14. package/dist/types/src/options.d.ts +19 -0
  15. package/dist/types/src/runtime/choose.d.ts +3 -0
  16. package/dist/types/src/runtime/driver.d.ts +29 -0
  17. package/dist/types/src/runtime/mime.d.ts +6 -0
  18. package/dist/types/src/runtime/multipart.d.ts +34 -0
  19. package/dist/types/src/runtime/store.d.ts +10 -0
  20. package/dist/types/src/server/blob.d.ts +3 -0
  21. package/dist/types/src/server/ensure.d.ts +22 -0
  22. package/dist/types/src/server/index.d.ts +12 -0
  23. package/dist/types/src/types.d.ts +152 -0
  24. package/package.json +32 -4
  25. package/src/build/setup.ts +137 -0
  26. package/src/client/index.ts +206 -0
  27. package/src/drivers/cloudflare-r2.ts +232 -0
  28. package/src/drivers/fs.ts +398 -0
  29. package/src/drivers/s3.ts +311 -0
  30. package/src/drivers/suite.ts +314 -0
  31. package/src/env.d.ts +16 -0
  32. package/src/index.ts +10 -0
  33. package/src/module.ts +11 -0
  34. package/src/options.ts +102 -0
  35. package/src/runtime/choose.ts +18 -0
  36. package/src/runtime/driver.ts +82 -0
  37. package/src/runtime/mime.ts +18 -0
  38. package/src/runtime/multipart.ts +319 -0
  39. package/src/runtime/store.ts +190 -0
  40. package/src/server/blob.ts +26 -0
  41. package/src/server/ensure.ts +52 -0
  42. package/src/server/index.ts +20 -0
  43. package/src/types.ts +155 -0
@@ -0,0 +1,398 @@
1
+ import { createHash, randomUUID } from "node:crypto"
2
+ import { openAsBlob } from "node:fs"
3
+ import { mkdir, open, readdir, readFile, rename, rm, stat, writeFile, type FileHandle } from "node:fs/promises"
4
+ import { dirname, join, resolve, sep } from "node:path"
5
+ import {
6
+ invalidPathname,
7
+ invalidUpload,
8
+ page,
9
+ presignUnavailable,
10
+ uploadNotFound,
11
+ type OpenDriver,
12
+ } from "../runtime/driver.ts"
13
+ import type { BlobDriver, BlobListItem, BlobObject, BlobUploadedPart, BlobWrite, ResolvedBlobDriver } from "../types.ts"
14
+
15
+ interface Meta {
16
+ /** The name of the object file this metadata describes; an object file is never written again after it is named. */
17
+ id: string
18
+ contentType: string
19
+ size: number
20
+ etag: string
21
+ uploadedAt: string
22
+ customMetadata: Record<string, string>
23
+ }
24
+
25
+ /** What `<base>/multipart/<uploadId>/upload.json` holds: what `complete` writes, and the pathname the upload is for. */
26
+ interface UploadRecord extends BlobWrite {
27
+ pathname: string
28
+ }
29
+
30
+ const META = ".json"
31
+ const UPLOAD_ID = /^[0-9a-f]{32}$/
32
+ /** An upload folder this old is dropped at the next `create`. */
33
+ const STALE_UPLOAD_MS = 24 * 60 * 60 * 1000
34
+ /** An encoded segment longer than this would push a file name past the 255 bytes of common file systems. */
35
+ const MAX_SEGMENT = 200
36
+ const CHUNK = 64 * 1024
37
+
38
+ const encodeSegment = (segment: string) => encodeURIComponent(segment).replace(/\./g, "%2E").replace(/\*/g, "%2A")
39
+
40
+ const isMissing = (error: unknown) => ["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException)?.code ?? "")
41
+
42
+ const toCursor = (name: string) =>
43
+ btoa(String.fromCharCode(...new TextEncoder().encode(name)))
44
+ .replace(/\+/g, "-")
45
+ .replace(/\//g, "_")
46
+ .replace(/=+$/, "")
47
+
48
+ function fromCursor(cursor: string): string {
49
+ try {
50
+ return new TextDecoder("utf-8", { fatal: true }).decode(
51
+ Uint8Array.from(atob(cursor.replace(/-/g, "+").replace(/_/g, "/")), (char) => char.charCodeAt(0)),
52
+ )
53
+ } catch {
54
+ throw new TypeError(`Invalid blob list cursor ${JSON.stringify(cursor)}`)
55
+ }
56
+ }
57
+
58
+ /** The ETag of `put`: the size in hex and the first 16 hex of the SHA-256. */
59
+ const etagOf = (size: number, hash: ReturnType<typeof createHash>) =>
60
+ `"${size.toString(16)}-${hash.digest("hex").slice(0, 16)}"`
61
+
62
+ const objectOf = (pathname: string, meta: Meta): BlobObject => ({
63
+ pathname,
64
+ contentType: meta.contentType,
65
+ size: meta.size,
66
+ etag: meta.etag,
67
+ uploadedAt: new Date(meta.uploadedAt),
68
+ customMetadata: meta.customMetadata,
69
+ })
70
+
71
+ /** The bytes `[start, end]` of an open file as a stream; the handle closes at the end or on cancel. */
72
+ function streamOf(handle: FileHandle, start: number, end: number): ReadableStream<Uint8Array> {
73
+ let position = start
74
+ return new ReadableStream<Uint8Array>({
75
+ async pull(controller) {
76
+ const length = Math.min(CHUNK, end + 1 - position)
77
+ if (length <= 0) {
78
+ await handle.close()
79
+ return controller.close()
80
+ }
81
+ const { bytesRead, buffer } = await handle.read(new Uint8Array(length), 0, length, position)
82
+ if (bytesRead === 0) {
83
+ await handle.close()
84
+ return controller.close()
85
+ }
86
+ position += bytesRead
87
+ controller.enqueue(buffer.subarray(0, bytesRead))
88
+ },
89
+ async cancel() {
90
+ await handle.close()
91
+ },
92
+ })
93
+ }
94
+
95
+ /**
96
+ * The metadata of a pathname at `<base>/meta/<pathname>.json` names its object file
97
+ * `<base>/objects/<pathname>.<id>.data`, each segment percent-encoded with `.` too. A put streams the bytes to a temporary
98
+ * file, renames it to a new id, then renames a temporary metadata file over the old one, and only then removes the object
99
+ * file the old metadata named: a reader sees the old pair or the new pair, never a mix, and an object file it opened keeps
100
+ * its bytes. Commits to one pathname run one at a time in the process, so a put that loses a race removes nothing it
101
+ * should keep and leaves nothing behind; processes sharing one `base` can still leave an unread object file.
102
+ */
103
+ export const openFsDriver: OpenDriver<Extract<ResolvedBlobDriver, { driver: "fs" }>> = (config) => {
104
+ const base = resolve(config.base)
105
+ const objects = join(base, "objects")
106
+ const metas = join(base, "meta")
107
+ const temp = join(base, "tmp")
108
+ const fileIn = (root: string, pathname: string, suffix: string) => {
109
+ const segments = pathname.split("/").map(encodeSegment)
110
+ if (segments.some((segment) => segment.length > MAX_SEGMENT)) throw invalidPathname(pathname)
111
+ const file = `${join(root, ...segments)}${suffix}`
112
+ if (!file.startsWith(root + sep)) throw invalidPathname(pathname)
113
+ return file
114
+ }
115
+ const objectFile = (pathname: string, id: string) => fileIn(objects, pathname, `.${id}.data`)
116
+ const metaFile = (pathname: string) => fileIn(metas, pathname, META)
117
+
118
+ async function readMeta(pathname: string): Promise<Meta | undefined> {
119
+ try {
120
+ return JSON.parse(await readFile(metaFile(pathname), "utf8")) as Meta
121
+ } catch (error) {
122
+ if (isMissing(error)) return undefined
123
+ throw error
124
+ }
125
+ }
126
+
127
+ async function pathnames(): Promise<string[]> {
128
+ let names: string[]
129
+ try {
130
+ names = (await readdir(metas, { recursive: true })) as string[]
131
+ } catch (error) {
132
+ if (isMissing(error)) return []
133
+ throw error
134
+ }
135
+ const found: string[] = []
136
+ for (const name of names) {
137
+ if (!name.endsWith(META)) continue
138
+ try {
139
+ found.push(name.slice(0, -META.length).split(sep).map(decodeURIComponent).join("/"))
140
+ } catch {}
141
+ }
142
+ return found.sort()
143
+ }
144
+
145
+ async function writeTemp(write: (file: string) => Promise<void>): Promise<string> {
146
+ await mkdir(temp, { recursive: true })
147
+ const file = join(temp, randomUUID())
148
+ try {
149
+ await write(file)
150
+ } catch (error) {
151
+ await rm(file, { force: true })
152
+ throw error
153
+ }
154
+ return file
155
+ }
156
+
157
+ const commits = new Map<string, Promise<void>>()
158
+
159
+ /** Runs the commits of one metadata file one after another, so each removes the object file the one before it named. */
160
+ async function commit(metaPath: string, step: () => Promise<void>): Promise<void> {
161
+ const before = commits.get(metaPath) ?? Promise.resolve()
162
+ const done = before.then(step)
163
+ const settled = done.catch(() => {})
164
+ commits.set(metaPath, settled)
165
+ try {
166
+ await done
167
+ } finally {
168
+ if (commits.get(metaPath) === settled) commits.delete(metaPath)
169
+ }
170
+ }
171
+
172
+ async function moveInto(from: string, to: string): Promise<void> {
173
+ await mkdir(dirname(to), { recursive: true })
174
+ await rename(from, to)
175
+ }
176
+
177
+ const uploads = join(base, "multipart")
178
+
179
+ /** The folder of an upload held for `pathname`; any other id, or one held for another pathname, is not found. */
180
+ async function uploadFolder(pathname: string, uploadId: string): Promise<{ folder: string; record: UploadRecord }> {
181
+ if (!UPLOAD_ID.test(uploadId)) throw uploadNotFound()
182
+ const folder = join(uploads, uploadId)
183
+ let record: UploadRecord
184
+ try {
185
+ record = JSON.parse(await readFile(join(folder, "upload.json"), "utf8")) as UploadRecord
186
+ } catch (error) {
187
+ if (isMissing(error)) throw uploadNotFound()
188
+ throw error
189
+ }
190
+ if (record.pathname !== pathname) throw uploadNotFound()
191
+ return { folder, record }
192
+ }
193
+
194
+ async function dropStaleUploads(): Promise<void> {
195
+ let names: string[]
196
+ try {
197
+ names = await readdir(uploads)
198
+ } catch (error) {
199
+ if (isMissing(error)) return
200
+ throw error
201
+ }
202
+ const before = Date.now() - STALE_UPLOAD_MS
203
+ for (const name of names) {
204
+ const folder = join(uploads, name)
205
+ const changed = await stat(folder).then(
206
+ (info) => info.mtimeMs,
207
+ () => undefined,
208
+ )
209
+ if (changed !== undefined && changed < before) await rm(folder, { recursive: true, force: true })
210
+ }
211
+ }
212
+
213
+ /** The listed part files one after another, each hashed as it is read; a missing part, or one whose ETag is not the listed one, fails the stream. */
214
+ function joinedParts(folder: string, parts: BlobUploadedPart[]): ReadableStream<Uint8Array> {
215
+ let at = 0
216
+ let current: { handle: FileHandle; hash: ReturnType<typeof createHash>; size: number; etag: string } | undefined
217
+ return new ReadableStream<Uint8Array>({
218
+ async pull(controller) {
219
+ while (true) {
220
+ if (!current) {
221
+ const part = parts[at++]
222
+ if (!part) return controller.close()
223
+ let handle: FileHandle
224
+ try {
225
+ handle = await open(join(folder, String(part.partNumber)), "r")
226
+ } catch (error) {
227
+ if (isMissing(error)) throw invalidUpload()
228
+ throw error
229
+ }
230
+ current = { handle, hash: createHash("sha256"), size: 0, etag: part.etag }
231
+ }
232
+ const { bytesRead, buffer } = await current.handle.read(new Uint8Array(CHUNK), 0, CHUNK, null)
233
+ if (bytesRead > 0) {
234
+ const chunk = buffer.subarray(0, bytesRead)
235
+ current.hash.update(chunk)
236
+ current.size += bytesRead
237
+ return controller.enqueue(chunk)
238
+ }
239
+ await current.handle.close()
240
+ const matches = etagOf(current.size, current.hash) === current.etag
241
+ current = undefined
242
+ if (!matches) throw invalidUpload()
243
+ }
244
+ },
245
+ async cancel() {
246
+ await current?.handle.close()
247
+ },
248
+ })
249
+ }
250
+
251
+ const driver: BlobDriver = {
252
+ name: "fs",
253
+ async put(pathname, body, write) {
254
+ const metaPath = metaFile(pathname)
255
+ const id = randomUUID().replace(/-/g, "")
256
+ const target = objectFile(pathname, id)
257
+ const hash = createHash("sha256")
258
+ let size = 0
259
+ const bytes = await writeTemp(async (file) => {
260
+ const handle = await open(file, "w")
261
+ try {
262
+ const stream =
263
+ body instanceof Uint8Array
264
+ ? new Blob([body as Uint8Array<ArrayBuffer>]).stream()
265
+ : body instanceof Blob
266
+ ? body.stream()
267
+ : body
268
+ for await (const chunk of stream as ReadableStream<Uint8Array>) {
269
+ hash.update(chunk)
270
+ size += chunk.length
271
+ await handle.write(chunk)
272
+ }
273
+ } finally {
274
+ await handle.close()
275
+ }
276
+ })
277
+ await moveInto(bytes, target)
278
+ const meta: Meta = {
279
+ id,
280
+ contentType: write.contentType,
281
+ size,
282
+ etag: etagOf(size, hash),
283
+ uploadedAt: new Date().toISOString(),
284
+ customMetadata: write.customMetadata,
285
+ }
286
+ const metaTemp = await writeTemp((file) => writeFile(file, JSON.stringify(meta)))
287
+ await commit(metaPath, async () => {
288
+ const previous = await readMeta(pathname).catch(() => undefined)
289
+ await moveInto(metaTemp, metaPath)
290
+ if (previous && previous.id !== id) await rm(objectFile(pathname, previous.id), { force: true })
291
+ })
292
+ return objectOf(pathname, meta)
293
+ },
294
+ async get(pathname) {
295
+ const meta = await readMeta(pathname)
296
+ if (!meta) return undefined
297
+ const file = objectFile(pathname, meta.id)
298
+ if (typeof Bun !== "undefined") {
299
+ const blob = Bun.file(file, { type: meta.contentType })
300
+ return (await blob.exists()) ? blob : undefined
301
+ }
302
+ try {
303
+ return await openAsBlob(file, { type: meta.contentType })
304
+ } catch (error) {
305
+ if (isMissing(error)) return undefined
306
+ throw error
307
+ }
308
+ },
309
+ async head(pathname) {
310
+ const meta = await readMeta(pathname)
311
+ return meta && objectOf(pathname, meta)
312
+ },
313
+ async list({ prefix, limit, cursor, folded }) {
314
+ const entries: { name: string; folder: boolean }[] = []
315
+ for (const pathname of await pathnames()) {
316
+ if (!pathname.startsWith(prefix)) continue
317
+ const slash = folded ? pathname.indexOf("/", prefix.length) : -1
318
+ const name = slash === -1 ? pathname : pathname.slice(0, slash + 1)
319
+ if (entries.at(-1)?.name !== name) entries.push({ name, folder: slash !== -1 })
320
+ }
321
+ const { items, hasMore } = page(entries, cursor === undefined ? undefined : fromCursor(cursor), limit)
322
+ const blobs: BlobListItem[] = []
323
+ for (const item of items) {
324
+ if (item.folder) continue
325
+ const meta = await readMeta(item.name)
326
+ if (meta)
327
+ blobs.push({ pathname: item.name, size: meta.size, etag: meta.etag, uploadedAt: new Date(meta.uploadedAt) })
328
+ }
329
+ return {
330
+ blobs,
331
+ hasMore,
332
+ ...(hasMore ? { cursor: toCursor(items.at(-1)!.name) } : {}),
333
+ ...(folded ? { folders: items.filter((item) => item.folder).map((item) => item.name) } : {}),
334
+ }
335
+ },
336
+ async delete(paths) {
337
+ for (const pathname of paths) {
338
+ const meta = await readMeta(pathname)
339
+ if (!meta) continue
340
+ await rm(metaFile(pathname), { force: true })
341
+ await rm(objectFile(pathname, meta.id), { force: true })
342
+ }
343
+ },
344
+ async open(pathname, etag, range) {
345
+ for (let tries = 0; tries < 3; tries++) {
346
+ const meta = await readMeta(pathname)
347
+ if (!meta) return undefined
348
+ if (meta.etag !== etag) return "changed"
349
+ let handle: FileHandle
350
+ try {
351
+ handle = await open(objectFile(pathname, meta.id), "r")
352
+ } catch (error) {
353
+ if (isMissing(error)) continue
354
+ throw error
355
+ }
356
+ return streamOf(handle, range?.start ?? 0, range?.end ?? meta.size - 1)
357
+ }
358
+ return "changed"
359
+ },
360
+ async presign() {
361
+ throw presignUnavailable("fs")
362
+ },
363
+ multipart: {
364
+ async create(pathname, write) {
365
+ fileIn(objects, pathname, "")
366
+ await dropStaleUploads()
367
+ const uploadId = randomUUID().replace(/-/g, "")
368
+ const folder = join(uploads, uploadId)
369
+ await mkdir(folder, { recursive: true })
370
+ const record: UploadRecord = { pathname, ...write }
371
+ await writeFile(join(folder, "upload.json"), JSON.stringify(record))
372
+ return uploadId
373
+ },
374
+ async uploadPart(pathname, uploadId, partNumber, body) {
375
+ const { folder } = await uploadFolder(pathname, uploadId)
376
+ const file = await writeTemp((file) => writeFile(file, body))
377
+ await rename(file, join(folder, String(partNumber)))
378
+ return etagOf(body.length, createHash("sha256").update(body))
379
+ },
380
+ async complete(pathname, uploadId, parts) {
381
+ const { folder, record } = await uploadFolder(pathname, uploadId)
382
+ const stored = await driver.put(pathname, joinedParts(folder, parts), {
383
+ contentType: record.contentType,
384
+ customMetadata: record.customMetadata,
385
+ })
386
+ await rm(folder, { recursive: true, force: true })
387
+ return stored
388
+ },
389
+ async abort(pathname, uploadId) {
390
+ const found = await uploadFolder(pathname, uploadId).catch(() => undefined)
391
+ if (found) await rm(found.folder, { recursive: true, force: true })
392
+ },
393
+ },
394
+ }
395
+ return driver
396
+ }
397
+
398
+ export default openFsDriver