Files with S3 and R2

Keep the bytes in an object store and the facts about them in a collection. A policy says who may have a link; the link itself comes from the store.

A file is two things. The bytes are what an object store (Amazon S3, Cloudflare R2, anything that speaks the S3 API) keeps cheaply and serves from a CDN. The facts are whose it is, how big, what type, whether the upload finished, and those are rows. fennecdb keeps the rows. The app's backend, which can be a Worker, makes the links, and makes one only after fennec-server has said yes: to an insert for an upload, to a read for a download.

Why the bytes stay out of the database file

A text field can hold a megabyte, and a request can carry up to 64 MiB. A file full of them is the wrong place, for reasons that belong to the file:

  • The file only grows until it is compacted. Records are appended; a document that is replaced or deleted leaves its old bytes behind. 200 puts of 1 MiB into a server started with --auto-compact off made a file of 200 MiB; deleting a hundred of them left it 200 MiB; compact brought it to 100 MiB (104 858 800 bytes reclaimed). By default the server compacts a file itself once half of it is dead and it is 64 MB, and each compaction copies every live byte, so its cost follows the bytes you keep (Compaction); fennec-server --help says compact peaks at about 3x the file in memory.
  • The file is mapped and lives in the page cache. A 40 MB photo sits beside the rows that are read a thousand times a second, and the operating system has room for fewer of those.
  • Every byte is replicated, archived and fed. A replica follows the writes, an archive keeps them, and /_changes hands them to consumers from a buffer of 64 MiB by default: a few uploads, and a consumer a moment behind is answered 410 (below).
  • Requests have a ceiling. A body is at most 64 MiB, sent by its length or chunked (Limits).
  • The store is built for it. Ranges, multipart uploads, lifecycle rules, a CDN in front, a price a gigabyte.

A bytes field is for what is small and belongs with the row, a thumbnail's worth or a hash.

The shape

  1. Add. The client asks the backend for an upload, sending its own token. The backend inserts the row, pending, as that person: the policy decides whether they may, pins owner to their sub and caps size. Only then does it make a presigned PUT URL for the key pending/<id>.
  2. Upload. The client sends the bytes to the store with that URL. They never pass the backend.
  3. Done. The client calls the backend. It reads the row as the person, asks the store for the object's size and, if it is the size announced, copies it to files/<id> and moves the row to ready with a token of its own (a done sent again is answered 200). A copy, because the upload URL is good for minutes and can send other bytes to pending/<id> after this: the key that is downloaded is one the client never held a URL for.
  4. Download. The backend reads the row as the person, and if it is theirs and ready, makes a presigned GET URL for files/<id>.
  5. Delete. The person deletes the row, by the backend or with their own token from a page. A consumer of the change stream sees the deletion and deletes the objects.

The backend holds no JWT library and checks no token itself. It passes the Authorization header on, and fennec-server verifies it (Auth with your identity provider). The policy is the whole of who may do what:

files-policy.txt
# collection  access                  rows

# A person lists, reads and deletes their own files' metadata ...
files         read,delete             where owner = $jwt.sub

# ... and adds a file of up to 10 MiB, pending: only the backend, once the
# object is in the bucket, marks it ready.
files         insert                  where owner = $jwt.sub and state = "pending" and size > 0 and size <= 10485760

# ... and renames it.
files         update(name)            where owner = $jwt.sub

# The backend's own token. Its identity is its `sub` and an `iss` that only
# your services sign (service-token.mjs): a `sub` alone is the provider's to
# assign, and a provider's token (a Firebase project's owner picks the uid of a
# custom token) can say `files-backend`; a `role` claim would be the
# provider's to fill, and one a person may set (Supabase's user_metadata,
# Clerk's unsafe_metadata) would be theirs. The backend reads rows to check
# them, and moves a pending one to ready, a transition because one filter asked
# of the row before and after would refuse the move it grants (`new.` is the
# row as the write leaves it).
files         read                    where $jwt.sub = 'files-backend' and $jwt.iss = 'urn:fennec:services'
files         update(state)           where state = "pending" and new.state = "ready" and $jwt.sub = 'files-backend' and $jwt.iss = 'urn:fennec:services'
  • A person adds what is theirs and pending, up to 10 MiB. The insert rule is checked against the document written, so a client that sends state: "ready" or a size of 20 MiB straight to the database with its own token is refused (403). The backend does not have to remember to check.
  • Only the backend moves a file to ready, and only from pending. A rule that names new. is a transition: a plain where state = "pending" would refuse the very write it grants, because the row after it is not pending (Transitions).
  • The backend is files-backend of the issuer urn:fennec:services, and no role. Both are in the rule: a sub alone is what a provider's token can say too (a Firebase project's owner picks the uid of a custom token), and a role claim in the provider's namespace would be one a provider's settings, or a user's own attributes, might fill. The backend signs a five-minute token with a key of its own, whose public half is in the server's keys file (Tokens your own services call with, which also says how to keep that key and rotate it: the server binds no key to an identity, so whoever holds one can sign any identity the policy has a rule for). A hand-minted long-lived token would be refused by --jwt-max-age.
  • The key is the id, not the name a person typed. The change stream names a deleted row by its id alone, and a key made from it needs no lookup to delete. The name is a column, and Content-Disposition carries it on download. On a --dir node every tenant's file numbers its rows from 1: the key starts with the tenant (acme/files/1), and a consumer and a reconcile run for each tenant at /t/<tenant>/.

The backend

The calls are the AWS SDK's, the same for S3 and for R2. The backend answers what it was asked and no more: a body is at most 4 KiB, the server's own words (which name collections and rules) are not passed on, and what it did not expect is 500 and a line in its own log.

files-backend.mjs
// Files in an object store (S3, R2 or anything that speaks S3), their metadata
// in fennecdb: the app's small backend, docs/files. It holds no JWT library and
// checks no token itself. Each request's `Authorization` goes to fennec-server
// as it came, and the server's rules (files-policy.txt) say whether this
// person may add a file or read one; a presigned URL is made only after the
// server has said yes -- to an insert for an upload, to a read for a download.
//
//   POST   /files          {name, type, size}  a row, pending, and a URL to PUT the bytes to
//   POST   /files/:id/done                     the bytes are there: the row is ready
//   GET    /files                              the person's files
//   GET    /files/:id                          a URL to GET the bytes from
//   DELETE /files/:id                          the row; the bucket's copy goes with it (blobs.mjs)
//
// An upload lands under `pending/<id>` and, once checked, is copied to
// `files/<id>`; both keys are made from the row's id, never from the name a
// person gave the file (store.mjs). The bucket stays private: nothing here
// makes a key public, and a key is no secret either (ids count up).
import { createServer } from 'node:http';
import { CopyObjectCommand, DeleteObjectCommand, GetObjectCommand, HeadObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { connect } from '@fennecdb/web/client';
import { keysOf } from './store.mjs';
import { isMain } from './main.mjs';

const MAX_BODY = 4096; // a request is a name, a type and a number
const TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,63}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,63}$/i;

/**
 * What a download is saved as. `attachment` makes a browser save the bytes
 * instead of showing them: a person fills these files and names them, and an
 * `.html` or `.svg` shown from the bucket's address runs its script there.
 * `filename*` carries a name that is not ASCII (RFC 6266, RFC 5987); the
 * plain `filename` beside it is what an old client reads.
 */
export function disposition(name) {
  const ascii = name.replace(/[^\x20-\x7e]|["\\%]/g, '_');
  const star = encodeURIComponent(name).replace(/['()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
  return `attachment; filename="${ascii}"; filename*=UTF-8''${star}`;
}

/**
 * `appToken` is `() => Promise<token>`: the backend's own, signed on demand
 * (service-token.mjs). `prefix` is the tenant on a `--dir` node.
 */
export function backend({ fennec, appToken, s3, bucket, prefix = '', expiresIn = 300, log = console.error }) {
  const as = (token) => connect(fennec, { token });
  const keys = keysOf(prefix);

  return createServer(async (req, res) => {
    const reply = (status, body) => {
      res.writeHead(status, { 'content-type': 'application/json' });
      res.end(body === undefined ? undefined : JSON.stringify(body));
    };
    try {
      const token = (req.headers.authorization ?? '').replace(/^Bearer /, '');
      if (!token) return reply(401, { error: 'no token' });
      const me = as(token); // fennec-server verifies it, and holds every query to its rules
      const [, route, rawId, verb] = new URL(req.url, 'http://x').pathname.split('/');
      if (route !== 'files') return reply(404, { error: 'not found' });
      const id = rawId === undefined ? undefined : Number(rawId);
      if (rawId !== undefined && !Number.isSafeInteger(id)) return reply(404, { error: 'no such file' });
      const body = req.method === 'POST' ? await json(req) : {};

      if (req.method === 'POST' && id === undefined) {
        const { name, type, size } = body;
        if (typeof name !== 'string' || !name || name.length > 255 || typeof type !== 'string' || !TYPE.test(type)
          || !Number.isSafeInteger(size) || size < 1) {
          return reply(400, { error: 'a name, a type and a size' });
        }
        // The row first: if the rules refuse this person, no URL is made.
        const [file] = await me.from('files').insert(
          { name, type, size, state: 'pending', created: new Date() },
          { returning: true },
        );
        const url = await getSignedUrl(
          s3,
          new PutObjectCommand({ Bucket: bucket, Key: keys.pending(file.id), ContentType: type, ContentLength: size }),
          { expiresIn, signableHeaders: new Set(['content-type', 'content-length']) },
        );
        return reply(201, { id: file.id, url, headers: { 'content-type': type } });
      }

      if (req.method === 'POST' && verb === 'done') {
        const file = await me.from('files').where('id', id).first(); // a row this person may read
        if (!file) return reply(404, { error: 'no such file' });
        // A retry after the answer was lost: it is done, and said to be.
        if (file.state === 'ready') return reply(200, { id: file.id, state: 'ready' });
        let held;
        try {
          held = await s3.send(new HeadObjectCommand({ Bucket: bucket, Key: keys.pending(file.id) }));
        } catch (e) {
          // No such object is the one answer that means "not yet"; a store that
          // cannot be reached or refuses us is the backend's to log, not the client's to be told.
          if (e.$metadata?.httpStatusCode === 404) return reply(409, { error: 'the bytes are not in the bucket yet' });
          throw e;
        }
        if (held.ContentLength !== file.size) {
          await me.from('files').where('id', file.id).delete(); // blobs.mjs removes the object
          return reply(422, { error: `the object is ${held.ContentLength} bytes, not the ${file.size} announced` });
        }
        // A copy to a key the client never held a URL for, so that bytes sent
        // to the upload URL after this point do not reach what is downloaded.
        // `CopySourceIfMatch` makes it that object, the one measured, and not
        // one that replaced it between the two calls.
        try {
          await s3.send(new CopyObjectCommand({
            Bucket: bucket, Key: keys.live(file.id), CopySource: `${bucket}/${keys.pending(file.id)}`,
            CopySourceIfMatch: held.ETag,
          }));
        } catch (e) {
          // 412: the upload was replaced between the check and the copy (the SDK's
          // error carries the status in its metadata, whatever it names the error).
          if (e.$metadata?.httpStatusCode === 412) return reply(409, { error: 'the upload changed while it was checked; send it again' });
          throw e;
        }
        const app = as(await appToken());
        await app.from('files').where('id', file.id).update({ state: 'ready' }, { require: 1 });
        await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: keys.pending(file.id) })).catch(() => {});
        return reply(200, { id: file.id, state: 'ready' });
      }

      if (req.method === 'GET' && id === undefined) {
        const rows = await me.from('files').select('id', 'name', 'type', 'size', 'state')
          .order('created', 'desc').limit(100).rows();
        return reply(200, rows);
      }

      if (req.method === 'GET') {
        const file = await me.from('files').where('id', id).first();
        if (!file) return reply(404, { error: 'no such file' }); // not found, whether it is another's or nobody's
        if (file.state !== 'ready') return reply(409, { error: 'not uploaded yet' });
        const url = await getSignedUrl(
          s3,
          new GetObjectCommand({
            Bucket: bucket,
            Key: keys.live(file.id),
            ResponseContentType: file.type,
            ResponseContentDisposition: disposition(file.name),
          }),
          { expiresIn },
        );
        return reply(200, { url, name: file.name, type: file.type, size: file.size });
      }

      if (req.method === 'DELETE') {
        await me.from('files').where('id', id).delete({ require: 1 });
        return reply(204);
      }
      return reply(405, { error: 'not a route' });
    } catch (e) {
      // The server's refusals of this person are theirs to be told, and
      // nothing else is: its words name collections and rules.
      if (e.status === 401) return reply(401, { error: 'not signed in' });
      if (e.status === 403) return reply(403, { error: 'not allowed' });
      if (e.status === 412) return reply(404, { error: 'no such file' }); // `require 1`: no row of this person's
      if (e.status === 413) return reply(413, { error: 'too large' });
      log('files backend:', e);
      return reply(500, { error: 'internal error' });
    }
  });
}

/** A request's JSON body, at most MAX_BODY bytes: a longer one is refused as soon as it is. */
async function json(req) {
  let s = '';
  for await (const chunk of req) {
    s += chunk;
    if (s.length > MAX_BODY) throw Object.assign(new Error('body'), { status: 413 });
  }
  try {
    return s ? JSON.parse(s) : {};
  } catch {
    return {};
  }
}

if (isMain(import.meta.url)) {
  const { readFileSync } = await import('node:fs');
  const { s3From } = await import('./store.mjs');
  const { serviceTokens } = await import('./service-token.mjs');
  const env = process.env;
  const server = backend({
    fennec: env.FENNEC_URL,
    // The key as a PEM file, whose path is SERVICE_KEY_FILE (a Worker keeps its key
    // in a secret instead, as base64 of the DER: the two forms are not the same).
    appToken: serviceTokens({ pem: readFileSync(env.SERVICE_KEY_FILE), sub: 'files-backend' }),
    s3: s3From(env),
    bucket: env.BUCKET,
    prefix: env.KEY_PREFIX ?? '',
  });
  server.listen(Number(env.PORT ?? 0), '127.0.0.1', () =>
    console.log(`files backend on http://127.0.0.1:${server.address().port}`));
}
store.mjs, the client and the keys
// The object store, as the files recipe reaches it: one client, and the keys.
import { S3Client } from '@aws-sdk/client-s3';

export function s3From(env) {
  return new S3Client({
    region: env.S3_REGION ?? 'auto', // R2 wants "auto"; S3 proper, the bucket's region
    endpoint: env.S3_ENDPOINT, // https://<account>.r2.cloudflarestorage.com for R2
    forcePathStyle: env.S3_PATH_STYLE === '1', // a local server has no bucket.localhost
    credentials: { accessKeyId: env.S3_KEY, secretAccessKey: env.S3_SECRET },
    // Recent versions of the SDK add a CRC32 of the body to a request they
    // sign. A presigned PUT is signed before there is a body, so the checksum
    // is the empty body's, and the store answers the real bytes 400 BadDigest
    // (seen on SeaweedFS). The SDK's own option, `WHEN_REQUIRED`, leaves it
    // off; Cloudflare's R2 page for this SDK does not mention it.
    requestChecksumCalculation: 'WHEN_REQUIRED',
    responseChecksumValidation: 'WHEN_REQUIRED',
  });
}

/**
 * Where a file's bytes are. An upload lands under `pending/<id>`, where a
 * lifecycle rule can expire what is left; once the backend has checked it, it
 * is copied to `files/<id>`, a key the client never held a URL for. `prefix`
 * is the tenant on a `--dir` node (`acme/`): every tenant's file numbers its
 * rows from 1, and one bucket holds them all.
 */
export const keysOf = (prefix = '') => ({
  pending: (id) => `${prefix}pending/${id}`,
  live: (id) => `${prefix}files/${id}`,
  /** The row id and the kind of a key of this prefix, or null. */
  parse(key) {
    const m = key.startsWith(prefix) && /^(pending|files)\/(\d+)$/.exec(key.slice(prefix.length));
    return m ? { kind: m[1], id: Number(m[2]) } : null;
  },
});
  • R2 or S3 is the client's configuration. For R2: endpoint: https://<ACCOUNT_ID>.r2.cloudflarestorage.com and region: 'auto', which is all R2 asks of the SDK (R2's SDK page). For S3 the bucket's region and no endpoint.
  • A presigned URL is a bearer token. Anyone holding it can do what it signs until it expires, which is why the backend asks the database first and keeps the lifetime short (300 seconds here; S3 allows up to 7 days with an IAM user's credentials, and R2 from 1 second to 7 days). The key is no secret, and nothing here relies on it being one. The bucket is private: no public read, no public listing, since ids count up and a public files/1 would be a guess away from files/2.
  • R2 signs GET, HEAD, PUT and DELETE, not a POST form, and only on the S3 domain, not on a custom domain (R2's docs). A browser that uploads straight to the bucket needs CORS rules on it for the page's origin.
  • Recent SDK versions checksum the request they sign. A presigned PUT is signed before there is a body, so the checksum is the empty body's, and the store answers the real bytes 400 BadDigest (seen here, on the store below). requestChecksumCalculation: 'WHEN_REQUIRED', and responseChecksumValidation beside it, are the SDK's own options to leave it off (its client notes). Cloudflare's R2 page for this SDK does not mention them.
  • What a download is saved as. The download URL carries response-content-disposition, attachment: a person fills these files and names them, and an .html or .svg shown from the bucket's address would run its script there. attachment makes a browser save it. A name that is not ASCII goes in filename*=UTF-8''… (RFC 6266), with an ASCII filename beside it for old clients; the type is the one the person declared, which is why it is never shown inline.
  • The size cap holds as far as the store holds it. The upload URL is signed for the size announced, and SeaweedFS refuses other bytes (SignatureDoesNotMatch, below). Whether S3 and R2 do the same is not shown here: AWS's page on presigned uploads says the content type has to match what was signed and says nothing of the length, and R2 has no POST policy to bound it with. So the check at done holds the size for whatever a store does, and the pending/ prefix is what bounds the bytes that are never checked (below).

The object goes with its row, and what is left is found

The store is not part of fennec-server's write, so a deleted row could leave its object behind if the delete ran in the backend and the backend died after it. A consumer of the change stream closes that. It runs beside the server (--cdc), reads every write once it is on disk, and deletes the objects of each deleted row, whoever deleted it: the backend, a page's own token, the sweep of pending uploads.

blobs.mjs
// The bucket follows the table, docs/files: a consumer of the change stream
// (`fennec-server --cdc`) that deletes an object once its row is gone, whoever
// deleted the row -- the backend, a person's own token from a page, the sweep
// of pending uploads. The server keeps the consumer's place, so a restart
// carries on where it stopped; a crash between the delete and the commit
// deletes again, which an object store answers as it answered the first time.
//
//   FENNEC_URL=... ADMIN_TOKEN=... S3_ENDPOINT=... S3_KEY=... S3_SECRET=... BUCKET=... node blobs.mjs
//
// /_changes takes the server's own token and no scoped one: it carries every
// row of every person, documents and all.
//
// A deletion names its row by id alone, which is why a key is made from the
// id. If the consumer is further behind than the server keeps (410), the
// deletions it missed are gone from the stream and from every read: it
// reconciles instead (reconcile.mjs), then goes on from the first write the
// server still has.
import { DeleteObjectCommand } from '@aws-sdk/client-s3';
import { reconcile } from './reconcile.mjs';
import { keysOf, s3From } from './store.mjs';
import { isMain } from './main.mjs';

const RETRIES = 8; // answers of the server missed one after another
const pause = (ms, signal) => new Promise((resolve) => {
  const t = setTimeout(resolve, ms);
  signal?.addEventListener('abort', () => (clearTimeout(t), resolve()), { once: true });
});

export async function follow({ fennec, adminToken, s3, bucket, prefix = '', name = 'blobs', wait = 10_000, signal, log = console.log }) {
  const headers = { authorization: `Bearer ${adminToken}`, 'content-type': 'application/json' };
  const keys = keysOf(prefix);
  // PATCH moves the consumer; a POST only makes it.
  const move = (since) => fetch(`${fennec}/_changes/consumers/${name}`, { method: 'PATCH', headers, body: JSON.stringify({ since }) });
  const commit = async (since) => {
    const res = await move(since);
    if (!res.ok) throw new Error(`commit of ${name} at ${since}: ${res.status}`);
  };
  // Made at every start: a POST makes the consumer (201) and leaves one that
  // exists where it stands (200), so a restart carries on from the last commit.
  const made = await fetch(`${fennec}/_changes/consumers/${name}`, { method: 'POST', headers });
  if (!made.ok) throw new Error(`/_changes/consumers/${name}: ${made.status}`);
  // A server restarted, or not answering for a while, is waited for with a back-off;
  // after RETRIES answers missed the follower ends with an error, so that whatever
  // supervises it starts it again. It ends with a zero only at its own signal.
  let missed = 0;
  while (!signal?.aborted) {
    const page = await fetch(`${fennec}/_changes?consumer=${name}&wait=${wait}`, { headers, signal }).catch(() => null);
    if (!page) {
      if (signal?.aborted) break;
      if (++missed >= RETRIES) throw new Error(`/_changes: no answer ${missed} times`);
      await pause(Math.min(500 * 2 ** missed, 30_000), signal);
      continue;
    }
    missed = 0;
    if (page.status === 410) {
      const { since } = await page.json();
      log(`blobs: behind what the server keeps; reconciling, then on from ${since}`);
      const gone = await reconcile({ fennec, adminToken, s3, bucket, prefix });
      log(`blobs: reconciled, ${gone.length} deleted: ${gone.join(', ') || 'none'}`);
      // The first write the server keeps can be past what is on disk yet (a commit
      // there is 409), and can move on while writes are not: not at once, then.
      const moved = await move(since);
      if (!moved.ok && moved.status !== 409) throw new Error(`commit of ${name} at ${since}: ${moved.status}`);
      await pause(500, signal);
      continue;
    }
    if (!page.ok) throw new Error(`/_changes: ${page.status}`);
    const next = Number(page.headers.get('fennec-next'));
    for (const line of (await page.text()).split('\n').filter(Boolean)) {
      const change = JSON.parse(line);
      if (change.collection === 'files' && change.op === 'del') {
        // Either key: a file deleted before it was done has only its upload.
        for (const Key of [keys.pending(change.id), keys.live(change.id)]) {
          await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key }));
        }
        log(`blobs: row ${change.id} deleted, so its objects too`);
      }
    }
    // Only now: the consumer's place moves once everything it read is done.
    await commit(next);
  }
}

if (isMain(import.meta.url)) {
  const env = process.env;
  await follow({
    fennec: env.FENNEC_URL, adminToken: env.ADMIN_TOKEN, s3: s3From(env), bucket: env.BUCKET, prefix: env.KEY_PREFIX ?? '',
  });
}
  • At least once, and deleting twice is fine. The server keeps the consumer's place; a crash between the delete and the commit repeats it, and a store answers the second delete as the first. A consumer is the server's token alone: /_changes carries every row of every person, so a scoped token is refused (Change data capture, Consumers). A consumer is made at every start: a POST makes it (201) and leaves one that exists where it stands (200), so what was deleted while it was stopped is still to come. Only a PATCH moves it.
  • An upload URL outlives its row. A row deleted while the URL has minutes to live, and a PUT with it, leaves an object nobody will delete: storage outside every quota the database holds (seen below). Two things bound it. A lifecycle rule on the pending/ prefix expires what is left there after a day (a day is R2's finest grain, and objects go "within 24 hours" after it: R2's rules, set with putBucketLifecycleConfiguration as S3's are; S3's expiry notes), and a reconcile from cron, every hour, which lists the objects and deletes those with no row to be there. A short URL lifetime shortens the window. The lifecycle rule is the store's and was not run here; the reconcile was.
  • The reconcile deletes, so it checks itself first. --dry-run says what would go. It refuses a database with no file row at all over a bucket that holds objects (the wrong server, a restore not yet done), and more than half of the objects going once there are ten to go (a table emptied, another tenant's prefix); --force goes on. The listing is read before the rows, so an upload that lands in between is not taken for an orphan. And an id is not given to a second row until a restore to a backup older than some ids hands them out again: reconcile before the first upload after a restore, not after, or an object of the lost rows would pass for the new ones'.
  • A consumer past the buffer must reconcile. One further behind than --replication-buffer keeps is answered 410, with the first since the server does have (a commit there can be 409 for a moment, while that write is not yet on disk, and is tried again). "Start over from a read" cannot find the objects of rows already deleted, since a deletion is in no read of the table; the reconcile can. So the consumer reconciles on a 410 and goes on from that since (below).
  • A queue job is the other way. When a key cannot be made from the id, write the job in the same /batch as the delete: del files where id = $1 require 1 and put jobs {kind: "delete-object", ...} land together or not at all, and a worker with a lease and a back-off deletes the object (Functions and webhooks).
  • An upload never finished leaves a pending row and, at most, an object under pending/. A scheduled statement sweeps the row, and the consumer sees the deletion like any other: del files where state = "pending" and created < now() - 3600000.
reconcile.mjs
// The bucket held to the table, docs/files: every object under `pending/` and
// `files/` with no row to be there is deleted. Run it from cron every hour, and
// it is also what a consumer of the change stream does when it was answered 410.
//
// Why a consumer alone is not enough:
//   - An upload URL outlives the row it was made for. A row deleted (by the
//     person, by the sweep) while the URL still has minutes to live, and a PUT
//     with it, leaves an object nobody will ever delete: storage outside every
//     quota the database holds.
//   - A consumer that fell further behind than `--replication-buffer` keeps is
//     answered 410. A deletion is not in a read of the table, so "start over
//     from a read" cannot find the objects whose rows are gone: this can.
//
//   FENNEC_URL=... ADMIN_TOKEN=... S3_ENDPOINT=... S3_KEY=... S3_SECRET=... BUCKET=... node reconcile.mjs
//
// The objects are listed first and the rows read after: a row is made before
// its URL, so an object listed has a row made earlier, and a row deleted since
// is what makes it an orphan. Read the other way round, an upload that landed
// between the two would look like one. An id is not given to a second row --
// until the database is restored to a backup older than some of its ids, which
// hands those ids out again: reconcile before the restore's first upload, not
// after, or an object of the lost rows becomes the object of the new ones.
//
// It deletes, so it refuses what looks like a mistake before it does:
//   --dry-run            says what it would delete and deletes nothing
//   a database with no file row at all, over a bucket that has objects: the
//     wrong server, a file not yet restored (--force goes on)
//   more than --max-delete-percent N (50) of the objects, once there are ten to
//     go: a table emptied, a prefix of another tenant's (--force goes on)
import { DeleteObjectCommand, ListObjectsV2Command } from '@aws-sdk/client-s3';
import { keysOf, s3From } from './store.mjs';
import { isMain } from './main.mjs';

async function* objects(s3, bucket, prefix) {
  let token;
  do {
    const page = await s3.send(new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, ContinuationToken: token }));
    for (const o of page.Contents ?? []) yield o.Key;
    token = page.NextContinuationToken;
  } while (token);
}

/** Every file row's state, by id, read in pages of a thousand. */
async function states(fennec, adminToken) {
  const rows = new Map();
  for (let after = 0; ;) {
    const res = await fetch(`${fennec}/query`, {
      method: 'POST',
      headers: { authorization: `Bearer ${adminToken}`, 'content-type': 'application/json' },
      body: JSON.stringify({ query: 'get files select id, state where id > $1 order id limit 1000', params: [after] }),
    });
    if (!res.ok) throw new Error(`reconcile: ${res.status}`);
    const page = await res.json();
    for (const r of page) rows.set(r.id, r.state);
    if (page.length < 1000) return rows;
    after = page[page.length - 1].id;
  }
}

/**
 * The keys deleted, in order (with `dryRun`, the keys that would be). `prefix`
 * is the tenant on a `--dir` node, and `fennec` that tenant's address.
 */
export async function reconcile({ fennec, adminToken, s3, bucket, prefix = '', dryRun = false, maxDeletePercent = 50, force = false }) {
  const keys = keysOf(prefix);
  const listed = [];
  for await (const key of objects(s3, bucket, prefix)) if (keys.parse(key)) listed.push(key);
  const rows = await states(fennec, adminToken);
  const doomed = listed.sort().filter((key) => {
    const { kind, id } = keys.parse(key);
    // An upload belongs to a pending row; what a ready row left under pending/
    // (the copy was made, the delete failed) and what has no row go.
    return !(kind === 'pending' ? rows.get(id) === 'pending' : rows.has(id));
  });
  if (!force) {
    if (rows.size === 0 && listed.length > 0) {
      throw new Error(`reconcile: the database holds no file rows and the bucket ${listed.length} objects; the wrong server, or a restore not done? (--force goes on)`);
    }
    if (doomed.length >= 10 && doomed.length * 100 > listed.length * maxDeletePercent) {
      throw new Error(`reconcile: ${doomed.length} of ${listed.length} objects would go, more than ${maxDeletePercent}%; --force goes on`);
    }
  }
  if (dryRun) return doomed;
  for (const Key of doomed) await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key }));
  return doomed;
}

if (isMain(import.meta.url)) {
  const env = process.env;
  const args = process.argv.slice(2);
  const percent = args.indexOf('--max-delete-percent');
  try {
    const gone = await reconcile({
      fennec: env.FENNEC_URL, adminToken: env.ADMIN_TOKEN, s3: s3From(env), bucket: env.BUCKET, prefix: env.KEY_PREFIX ?? '',
      dryRun: args.includes('--dry-run'), force: args.includes('--force'),
      ...(percent >= 0 && { maxDeletePercent: Number(args[percent + 1]) }),
    });
    const verb = args.includes('--dry-run') ? 'would be deleted' : 'deleted';
    console.log(`reconcile: ${gone.length} objects with no row ${verb}${gone.length ? `: ${gone.join(', ')}` : ''}`);
  } catch (e) {
    console.error(e.message);
    process.exit(1);
  }
}

A run

Two people, a real fennec-server with files-policy.txt, the backend above, the consumer, and an S3-compatible server in Docker (npm install in examples/recipes, then node files-demo.mjs, which pulls the image quietly (and again, if Docker Hub answers with a limit), starts the container and removes it; give S3_ENDPOINT, S3_KEY, S3_SECRET and BUCKET to use a store of your own). The signed URLs are shortened here. The store was SeaweedFS's S3 gateway, release 4.50: MinIO's container images and binaries could not be downloaded when this was written (quay.io refused the pull, dl.min.io answered 410), and any S3-compatible server takes the same SDK calls. S3 and R2 themselves were not run for this page. make recipes-test holds the lines below to what the demo prints.

fennec-server and the bucket recipes are up

-- alice adds a file
POST /files             201 {"id":1,"url":"<store>/recipes/pending/1?…"}
the row the server holds: [{"id":1,"owner":"alice","name":"hello.txt","type":"text/plain","size":17,"state":"pending"}]

-- she sends the bytes to the bucket herself, with the URL
PUT <presigned>         200
GET /files/1 before done 409 {"error":"not uploaded yet"}
POST /files/1/done    200 {"id":1,"state":"ready"}
POST /files/1/done again 200 {"id":1,"state":"ready"}
the upload copied to files/1, pending/1 gone

-- she downloads it; bob is told there is no such file
GET /files/1 (alice)   200 {"url":"<store>/recipes/files/1?…","name":"hello.txt","size":17}
GET <presigned>         200 "hello from alice\n"
GET /files/1 (bob)     404 {"error":"no such file"}
DELETE /files/1 (bob)  404 {"error":"no such file"}
GET /files (bob)        200 []
alice's total, for a quota   200 [{"sum(size)":17}]

-- a name that is not ASCII, and what a download is saved as
Content-Disposition: attachment; filename="r_sum_ _final_.pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9%20%22final%22.pdf
Content-Type: application/pdf

-- a token of the provider that says it is the backend
provider token, sub files-backend: read files    200 []
provider token, sub files-backend: mark ready    200 {"affected":0}

-- what the rules and the bucket refuse
POST /files, 20 MiB     403 {"error":"not allowed"}
alice's own token, state ready  403 {"error":"the document is outside what this token may write to `files`"}
PUT 20 bytes to a URL signed for 5   403 SignatureDoesNotMatch
POST /files/3/done            409 {"error":"the bytes are not in the bucket yet"}
POST /files/3/done, 20 bytes there   422 {"error":"the object is 20 bytes, not the 5 announced"}
HEAD pending/3: gone with its row
blobs: row 3 deleted, so its objects too

-- alice deletes the file: the objects go with the row
DELETE /files/1 (alice) 204
HEAD files/1: gone
blobs: row 1 deleted, so its objects too

-- an upload URL that outlives its row
DELETE /files/4 (alice) before the upload
blobs: row 4 deleted, so its objects too
PUT <presigned>, after the delete   200
HEAD pending/4: there, with no row
reconcile deleted pending/4

-- a pending upload nobody finished is swept
del files where state = "pending" and created < now() - 3600000: {"affected":1}
blobs: row 5 deleted, so its objects too

-- the follower is stopped, a file is deleted, and the stream moves past what the server keeps
files/6 is still in the bucket, its row deleted
files/6: gone
blobs: behind what the server keeps; reconciling, then on from 27
blobs: reconciled, 1 deleted: files/6
  • No row, no URL. The 20 MiB request, and the insert with state: "ready" sent straight to the database, were refused by the rules (403): the backend never got as far as the store.
  • Another person's file is no file. Bob's request for alice's is a 404, whether it is hers or nobody's, and so is his delete: his del with require 1 found no row of his.
  • A token that says it is the backend is not. A token of the provider with sub: files-backend reads no file and marks none ready: it lacks the issuer the backend's rules ask for.
  • A retry is answered as the first was. done sent again, as after an answer that was lost, is 200 for a file that is ready.
  • A URL signed for 5 bytes does not take 20. The store refused (403, SignatureDoesNotMatch) because the length is part of what was signed. That is this store; the check at done deletes the row and the object of one whose size is not the announced one (422 above, with the 20 bytes put there directly).
  • The download is saved under its name, filename* carrying the accents and the plain filename a fallback with an underscore for what is not ASCII or not safe in a quoted string.
  • The orphan of the upload sent after the delete is the one the reconcile found. The last step stopped the consumer, deleted a file's row, wrote past the 1 MiB buffer the demo's server was started with, and started the consumer again: 410, a reconcile, and the object gone.

What this does not do

  • It does not scan, resize or transcode. A consumer of the change stream that sees a file go ready is where that belongs (Functions and webhooks).
  • It does not do multipart or resumable uploads, for files past what one PUT takes. The row and the check at done stay the same; the URLs for the parts are the store's and the SDK's.
  • It does not meter a person's total. The policy caps one file; a quota across files is a statement the backend reads before it presigns, run above as get files select sum(size).
  • It does not close the window of the upload URL on pending/: until it expires, bytes sent with it replace the upload, which no one reads once it is copied.