Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

bucket

Declare a bucket of files in a luna, and store, read, list and sign URLs for them with ctx.blobs.

bucket declares a bucket of objects, files with a content type and metadata, under the luna type’s blobs option. A handler uses it as ctx.blobs.<name>.

import { bucket, defineLuna, t } from "luna";

export const Profile = defineLuna({
  name: "Profile",
  key: { id: t.string() },
  blobs: {
    files: bucket({ path: "files/{name...}" }),
  },
  handlers: (h) => ({
    save: h({ args: { name: t.string(), text: t.string() } }, async (ctx, { name, text }) => {
      await ctx.blobs.files.put(`files/${name}`, text);
    }),
    read: h({ args: { name: t.string() } }, (ctx, { name }) => ctx.blobs.files.text(`files/${name}`)),
  }),
});

Reference

bucket(spec)

PropType
pathstring

Where objects go: segments split by `/`, where `{name}` stands for one segment and a last `{name...}` for the rest.

Typestring
types?string[]

The content types allowed, such as `"image/png"` or `"image/*"`, and with none, any type.

Typestring[]
maxSize?number

The largest object in bytes, at most 10 GiB.

Typenumber
Default10 GiB
meta?Ty<M>

Each object's metadata type, built with `t`.

TypeTy<M>
public?boolean

Anyone may read objects at a plain URL, and otherwise only through a signed one.

Typeboolean
Defaultfalse
onUpload?(ctx, object: BlobObject<M>) => void

Runs when an upload through a signed URL finishes, and throwing rejects the upload.

Type(ctx, object: BlobObject<M>) => void

Bucket

PropType
namestring

The bucket's name.

Typestring
put(path, data, opts?)Promise<BlobObject<M>>

Stores an object of up to 256 MiB at `path`, replacing what is there, with `opts.contentType` and `opts.meta`.

TypePromise<BlobObject<M>>
get(path, opts?)Promise<{ object: BlobObject<M>; bytes: Uint8Array } | null>

The object and its bytes, or `null`, with `opts.range` as `[from, to)` in bytes.

TypePromise<{ object: BlobObject<M>; bytes: Uint8Array } | null>
text(path)Promise<string | null>

The object's bytes as UTF-8 text, or `null`.

TypePromise<string | null>
head(path)BlobObject<M> | null

The object without its bytes, or `null`.

TypeBlobObject<M> | null
list(opts?){ objects: BlobObject<M>[]; cursor: string | null }

Objects whose path starts with `prefix`, in path order, `limit` at a time, 100 by default and 1,000 at most.

Type{ objects: BlobObject<M>[]; cursor: string | null }
delete(path)boolean

Deletes the object, and returns `false` if there was none.

Typeboolean
copy(path, to)BlobObject | null

Copies the object to a `BlobDestination`, or returns `null` if there was none.

TypeBlobObject | null
move(path, to)BlobObject | null

Moves the object to a `BlobDestination`, or returns `null` if there was none.

TypeBlobObject | null
signUpload(path, opts?)SignedUrl

A URL an app uploads `path` to with `PUT`, limited by `opts.maxSize` and `opts.contentType`.

TypeSignedUrl
signDownload(path, opts?)SignedUrl

A URL an app downloads `path` from with `GET`.

TypeSignedUrl

data is a Uint8Array or a string. A string is stored as text/plain; charset=utf-8 and bytes as application/octet-stream, unless you pass contentType. opts.expiresIn of both sign methods is in milliseconds, one hour by default.

BlobObject

PropType
bucketstring

The bucket it is in.

Typestring
pathstring

Its path.

Typestring
hashstring

Its ETag, which changes whenever the bytes do.

Typestring
sizenumber

Its size in bytes.

Typenumber
contentTypestring

Its content type.

Typestring
metaM | null

Its metadata.

TypeM | null
creatednumber

When it was made, in milliseconds since the epoch.

Typenumber
updatednumber

When it last changed, in milliseconds since the epoch.

Typenumber

SignedUrl

PropType
urlstring

A path and query, to add to your app's URL.

Typestring
method"PUT" | "GET"

The method to send.

Type"PUT" | "GET"
expiresnumber

When it stops working, in milliseconds since the epoch.

Typenumber

BlobDestination

A path in the same bucket as a string, or { bucket, path } for another bucket of the same luna.

Good to know

  • An object written by a handler is there once the handler commits. A handler that fails leaves no object behind.
  • An object’s path must match its bucket’s path, its type must be one of types, and its size at most maxSize. Otherwise the write fails.
  • put and get handle at most 256 MiB at once. Read a larger object in parts with range, and upload one through signUpload.
  • onUpload runs in one transaction with the object it commits. It must be synchronous, since writes cannot span an await. Start slower work with ctx.send.
  • A signed URL is its own credential. Downloads through it, or from a public bucket, do not wake the luna.
  • A public bucket’s object is read at the same path as its signed download URL, without the query.
  • Rows that reference an object with t.blobRef follow their onDelete when it is deleted. By default the delete fails. A move inside the bucket takes those references with it.

Examples

Read part of a large object

head: h({ args: { name: t.string() } }, async (ctx, { name }) => {
  const got = await ctx.blobs.files.get(`files/${name}`, { range: [0, 1024] });
  return got ? { type: got.object.contentType, first: got.bytes.length } : null;
}),

Let an app upload a photo

import { bucket, defineLuna, t, table } from "luna";

export const Profile = defineLuna({
  name: "Profile",
  key: { id: t.string() },
  schema: { uploads: table({ id: t.id(), path: t.string(), size: t.int() }) },
  blobs: {
    photos: bucket({
      path: "photos/{photo}",
      types: ["image/*"],
      maxSize: 20 * 1024 * 1024,
      meta: t.object({ caption: t.string() }),
      onUpload: (ctx, object) => {
        ctx.db.uploads.insert({ path: object.path, size: object.size });
      },
    }),
  },
  handlers: (h) => ({
    uploadUrl: h({ args: { photo: t.string() } }, (ctx, { photo }) =>
      ctx.blobs.photos.signUpload(`photos/${photo}`, { expiresIn: 600_000, contentType: "image/png" }),
    ),
  }),
});

The app sends the file’s bytes with PUT to LUNA_URL followed by url.

Serve avatars to anyone

blobs: {
  avatars: bucket({ path: "avatar", types: ["image/png", "image/jpeg"], public: true }),
},

Delete empty objects a page at a time

tidy: h({}, (ctx) => {
  let page = ctx.blobs.files.list({ prefix: "files/", limit: 100 });
  for (;;) {
    for (const o of page.objects) if (o.size === 0) ctx.blobs.files.delete(o.path);
    if (!page.cursor) break;
    page = ctx.blobs.files.list({ prefix: "files/", cursor: page.cursor, limit: 100 });
  }
}),

Copy a photo to another bucket

useAsAvatar: h({ args: { photo: t.string() } }, (ctx, { photo }) => {
  ctx.blobs.photos.copy(`photos/${photo}`, { bucket: "avatars", path: "avatar" });
}),

A copy moves no bytes.

Was this page helpful?