# Large uploads

Take files of up to 64 MiB straight into your application's Object Storage with an upload route that your own code authorizes before a byte is read.

An `upload` route streams the body of a `PUT` into your application's own [Object Storage](/developers/object-storage/). Your code decides whether an upload may start and under which key it is stored, and hears when it has arrived, but the bytes never pass through your request handler. One upload holds up to 64 MiB.

## Declare the route

An `upload` route binds a `blob` service and names the `key_prefix` its files are stored under. It sits beneath an `api` route of the same application, which answers for it:

```json filename="ferrite.json"
{
  "services": [
    { "name": "requests", "primitive": "queue",
      "workload": { "read_qps": 20, "write_qps": 10, "record_size_kb": 0, "keying": "PerKey", "hot_set_gib": 0 } },
    { "name": "records", "primitive": "store",
      "workload": { "read_qps": 20, "write_qps": 10, "record_size_kb": 1, "keying": "PerKey", "hot_set_gib": 0 } },
    { "name": "files", "primitive": "blob",
      "workload": { "read_qps": 10, "write_qps": 5, "record_size_kb": 0, "keying": "PerKey", "hot_set_gib": 0 } }
  ],
  "applications": [{
    "name": "files",
    "artifact_key": "apps/files@v1",
    "artifact_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
    "bindings": [
      { "handle": "requests", "kind": "queue", "service": "requests" },
      { "handle": "records", "kind": "store", "service": "records" },
      { "handle": "files", "kind": "blob", "service": "files" }
    ],
    "routes": [
      { "prefix": "/files/", "binding": "requests", "kind": "api", "public": true,
        "forward_headers": ["authorization"] },
      { "prefix": "/files/upload/", "binding": "files", "kind": "upload", "key_prefix": "uploads/" }
    ],
    "compute": { "memory_mb": 256, "cpu_percent": 50 }
  }]
}
```

`PUT /files/upload/` goes to Object Storage, and every other method and path under `/files/` is an ordinary request to your handler. The `api` route's `forward_headers` decide which caller headers your code sees, for uploads too.

## What your code receives

The gateway sends your `api` route two requests for each upload. Both are a `PUT` to the same path with an empty body, and both carry headers that only the gateway can write:

| `x-ferrite-upload-phase` | When | It also carries | Your reply |
| --- | --- | --- | --- |
| `begin` | Before the body is read | `x-ferrite-upload-size` | `200` with `x-ferrite-upload-key` takes the upload. Any other reply goes to the client, and the body is never read. |
| `complete` | After the file is stored | `x-ferrite-upload-key`, `x-ferrite-upload-size`, and `x-ferrite-upload-sha256` in lower-case hex | Goes to the client. |
| `abort` | When the body did not arrive whole | `x-ferrite-upload-key` | Not sent on. Mark the upload stopped and delete it later. |

Name a new key for every `begin`, and never give one key to two uploads. The gateway looks at the key first and answers `502` when it already holds a file or part of one, without reading the body and without sending `abort`, because the key belongs to another upload. Two uploads that start under one new key at the same moment would damage each other. Record the key before you answer, so your own records list everything that could be stored. A key is relative to `key_prefix`, holds at most 256 bytes, has no `.` or `..` segment, and does not end in `/`.

Because `begin` arrives first, a caller without permission, a file that is too large, or a used link is refused before anything is sent. A client that sends `Expect: 100-continue` waits for your answer before it sends the body.

## A complete example

`src/uploads.rs` keeps one record per upload in the [Key-value Store](/developers/store/) and reads stored files back with `large_object`:

```rust filename="src/uploads.rs"
use std::io;

use ferrite_app::serde_json::{self, json, Value};
use ferrite_app::{crypto, large_object, AppContext, IngressReply, IngressRequest};

/// The largest file this application takes.
const MAX_BYTES: u64 = 25 * 1024 * 1024;
/// Counted from `begin`. The gateway ends an upload within ten minutes, so by
/// now it has completed or never will, and no write is still on its way.
const SETTLED_MS: u64 = 15 * 60 * 1000;

fn header<'a>(req: &'a IngressRequest, name: &str) -> Option<&'a str> {
    req.headers
        .iter()
        .find(|(n, _)| n == name)
        .map(|(_, value)| value.as_str())
}

fn answer(req: &IngressRequest, status: u16, body: Value) -> IngressReply {
    let mut reply = IngressReply::new(req.correlation_id.clone(), status, body.to_string().into_bytes());
    reply.headers.push(("content-type".into(), "application/json".into()));
    reply
}

fn record_key(key: &str) -> Vec<u8> {
    format!("upload/{key}").into_bytes()
}

fn object_key(key: &str) -> Vec<u8> {
    format!("uploads/{key}").into_bytes()
}

/// Whether a record is of an upload that may still complete.
fn receiving(ctx: &AppContext, record: &[u8]) -> bool {
    serde_json::from_slice::<Value>(record).is_ok_and(|record| {
        record["state"] == "receiving" && record["until"].as_u64().is_some_and(|until| until > ctx.now_ms())
    })
}

/// Answer one step of an upload by `owner`, or `None` for any other request.
pub async fn step(ctx: &AppContext, req: &IngressRequest, owner: &str) -> io::Result<Option<IngressReply>> {
    let Some(phase) = header(req, "x-ferrite-upload-phase") else {
        return Ok(None);
    };
    let mut records = ctx.store("records")?;

    if phase == "begin" {
        let size = header(req, "x-ferrite-upload-size").and_then(|n| n.parse::<u64>().ok()).unwrap_or(0);
        if size == 0 || size > MAX_BYTES {
            return Ok(Some(answer(req, 413, json!({ "error": "a file holds 1 byte to 25 MiB" }))));
        }
        // The gateway names each upload's request itself, so this key belongs to
        // one upload, and stays the same if the request is delivered twice.
        let key = crypto::hex(&crypto::sha256(req.idempotency_key.as_bytes()));
        let record = json!({ "owner": owner, "state": "receiving", "until": ctx.now_ms() + SETTLED_MS });
        let recorded = records
            .put_if_version(&record_key(&key), record.to_string().as_bytes(), None)
            .await?;
        if recorded.is_err() {
            // Delivered twice: the same key while that upload runs, none once it ended.
            let record = records.get(&record_key(&key)).await?;
            if !record.is_some_and(|bytes| receiving(ctx, &bytes)) {
                return Ok(Some(answer(req, 409, json!({ "error": "this upload has ended" }))));
            }
        }
        let mut reply = answer(req, 200, json!({}));
        reply.headers.push(("x-ferrite-upload-key".into(), key));
        return Ok(Some(reply));
    }

    let Some(key) = header(req, "x-ferrite-upload-key") else {
        return Ok(Some(answer(req, 400, json!({ "error": "no key" }))));
    };
    loop {
        let Some((bytes, version)) = records.get_versioned(&record_key(key)).await? else {
            return Ok(Some(answer(req, 404, json!({ "error": "unknown upload" }))));
        };
        let mut record: Value = serde_json::from_slice(&bytes)?;
        if record["owner"] != owner {
            return Ok(Some(answer(req, 404, json!({ "error": "unknown upload" }))));
        }
        match phase {
            // Told twice: the first answer stands.
            "complete" if record["state"] == "stored" => {
                let done = json!({ "id": key, "size": record["size"], "sha256": record["sha256"] });
                return Ok(Some(answer(req, 201, done)));
            }
            "complete" if receiving(ctx, &bytes) => {
                record["state"] = json!("stored");
                record["size"] = json!(header(req, "x-ferrite-upload-size"));
                record["sha256"] = json!(header(req, "x-ferrite-upload-sha256"));
            }
            // The sweep deletes it, once nothing can still be arriving.
            "abort" if receiving(ctx, &bytes) => record["state"] = json!("stopped"),
            "abort" => return Ok(Some(answer(req, 200, json!({})))),
            "complete" => return Ok(Some(answer(req, 409, json!({ "error": "this upload has ended" })))),
            _ => return Ok(Some(answer(req, 400, json!({ "error": "unknown step" })))),
        }
        // Whether this delivery wrote it or another did, the record now says.
        let _written = records
            .put_if_version(&record_key(key), record.to_string().as_bytes(), Some(version))
            .await?;
    }
}

/// The bytes of a stored upload that `owner` may read, verified.
pub async fn read(ctx: &AppContext, owner: &str, key: &str) -> io::Result<Option<Vec<u8>>> {
    let Some(bytes) = ctx.store("records")?.get(&record_key(key)).await? else {
        return Ok(None);
    };
    let record: Value = serde_json::from_slice(&bytes)?;
    if record["owner"] != owner || record["state"] != "stored" {
        return Ok(None);
    }
    large_object::get(&mut ctx.blob("files")?, &object_key(key)).await
}

/// Remove what stopped uploads left. Run it on a schedule.
pub async fn sweep(ctx: &AppContext) -> io::Result<usize> {
    let mut records = ctx.store("records")?;
    let mut removed = 0;
    let mut after: Option<Vec<u8>> = None;
    loop {
        let (rows, more) = records.scan_prefix(b"upload/", after.as_deref(), 256).await?;
        for (row, bytes, version) in &rows {
            let mut record: Value = serde_json::from_slice(bytes)?;
            let settled = record["until"]
                .as_u64()
                .is_some_and(|until| until <= ctx.now_ms());
            let (true, Some(key)) = (settled && record["state"] != "stored", row.strip_prefix(b"upload/")) else {
                continue;
            };
            // Ended here first, so a completion arriving now loses to it.
            record["state"] = json!("stopped");
            let ended = records
                .put_if_version(row, record.to_string().as_bytes(), Some(*version))
                .await?;
            if ended.is_ok() {
                let object = [b"uploads/".as_slice(), key].concat();
                large_object::delete(&mut ctx.blob("files")?, &object).await?;
                records.delete(row).await?;
                removed += 1;
            }
        }
        after = rows.last().map(|(row, _, _)| row.clone());
        if !more || after.is_none() {
            return Ok(removed);
        }
    }
}
```

`src/lib.rs` checks the caller once, for uploads and for downloads:

```rust filename="src/lib.rs"
#![forbid(unsafe_code)]

use ferrite_app::{crypto, serde_json, AppContext, IngressReply, IngressRequest};

pub mod uploads;

/// Who is calling. Replace this with your own sign-in.
fn owner(ctx: &AppContext, req: &IngressRequest) -> Option<String> {
    let token = ctx.secret("upload_token")?;
    let (_, sent) = req.headers.iter().find(|(name, _)| name == "authorization")?;
    let sent = sent.strip_prefix("Bearer ")?;
    crypto::ct_eq(sent.as_bytes(), token.as_bytes()).then(|| "owner".to_string())
}

async fn handle(ctx: &AppContext, req: &IngressRequest) -> std::io::Result<IngressReply> {
    let reply = |status, body| IngressReply::new(req.correlation_id.clone(), status, body);
    let Some(owner) = owner(ctx, req) else {
        return Ok(reply(401, b"sign in first".to_vec()));
    };
    if let Some(answered) = uploads::step(ctx, req, &owner).await? {
        return Ok(answered);
    }
    let path = req.path.split('?').next().unwrap_or("");
    if let ("GET", Some(key)) = (req.method.as_str(), path.strip_prefix("/files/")) {
        return Ok(match uploads::read(ctx, &owner, key).await? {
            Some(bytes) if bytes.len() <= 4_000_000 => reply(200, bytes),
            Some(_) => reply(413, b"too large for one reply".to_vec()),
            None => reply(404, Vec::new()),
        });
    }
    Ok(reply(404, Vec::new()))
}

pub async fn run(ctx: AppContext) -> std::io::Result<()> {
    let mut requests = ctx.queue("requests")?;
    loop {
        let Ok(Some(lease)) = requests.poll_wait(1_000).await else {
            continue;
        };
        let Ok(req) = serde_json::from_slice::<IngressRequest>(&lease.payload) else {
            let _ = requests.ack(lease.token).await;
            continue;
        };
        let Ok(reply) = handle(&ctx, &req).await else {
            continue; // the lease is delivered again
        };
        let mut replies = ctx.reply_to_queue(&req.reply_to).await?;
        if replies.publish(&serde_json::to_vec(&reply)?).await.is_ok() {
            let _ = requests.ack(lease.token).await;
        }
    }
}
```

Set the token and try it. In `ferrite.local.toml`, add `upload_token = "t0ken"` under `[secrets]`, then start `ferrite dev` and send a file:

```bash
ferrite dev
curl -T photo.jpg -H 'authorization: Bearer t0ken' http://localhost:8787/files/upload/
```

```json
{"id":"ab823c4a…","sha256":"c174b25c…","size":"20000000"}
```

Before you deploy, set the secret with `printf %s "$TOKEN" | ferrite secrets set upload_token`.

From a browser, send the file itself. The page and the route share an origin, so the request needs no preflight:

```js
const reply = await fetch("/files/upload/photo.jpg", {
  method: "PUT",
  headers: { authorization: `Bearer ${token}` },
  body: input.files[0],
});
```

## Read a stored file

The gateway writes each file as a large object, in 4 MiB chunks, at `key_prefix` followed by your key. `large_object::get` returns the whole file after checking every chunk against its digest. For a file that should not sit in memory, open it and read one chunk at a time:

```rust
let mut files = ctx.blob("files")?;
if let Some(live) = large_object::open(&mut files, b"uploads/ab823c4a").await? {
    for index in 0..live.chunk_count() {
        let chunk = large_object::read_chunk(&mut files, b"uploads/ab823c4a", &live, index).await?;
        // Parse, forward or copy this part.
    }
}
```

An `api` reply carries about 4 MiB, so return a larger file in parts. Delete one with `large_object::delete`, which also removes whatever an interrupted upload left under that key. The gateway deletes nothing. When an upload stops, a last write may still be on its way, so delete it no sooner than 15 minutes after its `begin`, as `sweep` in the example does for every upload that began and did not finish.

## Bounds

| Bound | Value |
| --- | --- |
| File | 64 MiB, with a `Content-Length`. No length returns `411`, a larger one `413`, and `Transfer-Encoding: chunked` returns `400`. |
| At once | 4 uploads for one application and 64 on one gateway. One more returns `429` with `Retry-After`. |
| Time | 30 seconds without a byte ends the upload with `408`. So does a body that takes longer than 60 seconds plus a second for every 32 KiB, up to 10 minutes. |
| Your replies | The same deadline as any `api` request, for each of `begin` and `complete`. |

## Who can reach an upload

Nothing is served through an `upload` route, and admission keeps it that way: the route cannot be `public`, and no public `content` route may serve the keys it stores under. Files become readable only through code you write. The `x-ferrite-upload-` headers belong to the gateway: it drops any a caller sends, and no route may forward one.

## Next

[MCP file transfers](/developers/mcp-files/) uses an upload route to give assistants large files, [Routing](/developers/routing/) lists every route kind, and [Why ferrite check rejects your spec](/kb/guide/why-ferrite-check-rejects-your-spec/) explains the `APP_ROUTE_UPLOAD_` codes.
