# Uploading

Files go straight from the client to the store, not through your app's
routes, so the 1 MB limit on a request body
([What is refused](/docs/one-input.md#what-is-refused)) isn't in the way:

1. An action calls the generated `PriceSheet.sheet_upload()`, one for each
   `File` field of the entity, which returns an `UploadSlot`.
2. The client sends the file to the slot's address, `PUT` to its `url`.
3. The client sends the slot's `token` in an ordinary create or update, in
   an `Input` field of type `FileUpload`. A write takes a `FileUpload` for a
   `File` field in `set:` or `patch:`, as it takes a `File`.

`domains/bakery/entities/price_sheet.jadpo` keeps a sheet a supplier sends:

```jadpo
/// A supplier's price sheet, kept as it was sent.
entity PriceSheet {
    id: Uuid
    sheet: File {
        store: sheets
        max_size: 5mb
        types: [FileType.csv]
    }

    policy: {
        create: [Access.public]
        read: [Access.public]
    }
}
```

`domains/bakery/types/sheet_upload.jadpo` is what the client sends once the
file has gone:

```jadpo
/// The sheet a supplier has uploaded.
type SheetUpload = Input {
    sheet: FileUpload
}
```

`domains/bakery/types/sheet_view.jadpo`:

```jadpo
use bakery/entities { PriceSheet }

/// A kept sheet and the link to its file.
type SheetView = Output {
    pick: [PriceSheet.id, PriceSheet.sheet]
}
```

`domains/bakery/actions/sheet_slot.jadpo` and
`domains/bakery/actions/keep_sheet.jadpo`:

```jadpo
use bakery/entities { PriceSheet }

/// Where a supplier sends their sheet.
action sheet_slot() -> UploadSlot {
    return PriceSheet.sheet_upload()
}
```

```jadpo
use bakery/entities { PriceSheet }
use bakery/types { SheetUpload, SheetView }

/// Keeps the sheet a supplier has uploaded.
action keep_sheet(input: SheetUpload) -> SheetView {
    var saved_sheet: PriceSheet = PriceSheet.create {
        set: {
            sheet: input.sheet
        }
    }
    return SheetView {
        id: saved_sheet.id
        sheet: saved_sheet.sheet
    }
}
```

`domains/bakery/routes/sheets.jadpo`:

```jadpo
use bakery/types { SheetUpload, SheetView }
use bakery/actions { keep_sheet, sheet_slot }

routes Sheets {
    prefix: /sheets

    POST /slot {
        authentication: RouteAuthentication.none
        output: UploadSlot
        run: sheet_slot()
    }

    POST / {
        authentication: RouteAuthentication.none
        input: SheetUpload
        output: SheetView
        status: SuccessStatus.created
        run: keep_sheet(input)
    }
}
```

The slot is an object: `url` is relative, since your app's own origin takes
the file, `token` is what the client sends back, and `max_size` the most
bytes the address accepts:

```json
{ "url": "/files/sheets/uploads/upl_eyJrIjoi…", "token": "upl_eyJrIjoi…", "max_size": 5000000 }
```

A slot's address is good for 15 minutes from when it was given, and for one
file, whose bytes then never change. The token is good for as long as the
bytes are there, so a slow client can attach after the address has expired.
Uploads that are never attached are deleted after a day
([Deleting and erasing](/docs/files.md#deleting-and-erasing)).

Asking for a slot needs the `create` or `update` grant on the entity
([Asking for an upload slot](/docs/grants.md#asking-for-an-upload-slot)). A
slot is signed for its store, so asking for one asks nothing of it.

Sending the file:

- The address is `PUT /files/<store>/uploads/<token>`, or, on the S3 driver, the
  presigned address the slot's `url` gives ([The S3 driver](/docs/files.md#the-s3-driver)); for
  a field over 100 MB, see [Large uploads go in parts](/docs/uploading.md#large-uploads-go-in-parts). It answers
  `204` once the file is kept. These answers count against the default rate limits
  as any request does.
- `Content-Type` may say the file's type, and `Content-Disposition` its name
  (`filename*=UTF-8''…`, RFC 8187), which is the name its signed link and
  download give it. The type is only ever a hint: a file's type comes from its
  first bytes. Text that has no magic number of its own takes the type its
  field lists when there is only one, or the type `Content-Type` claims, among
  the text types its first bytes could be.

| What the address refuses | Answer |
|---|---|
| An altered address, or one past its 15 minutes | `403`, `link_invalid` or `link_expired` |
| A body over `max_size:`, at its first byte over | `413` `file_too_large` |
| A body whose first bytes aren't a type its field takes | `415` `file_type_refused` |
| A `Content-Encoding` ([Compressed uploads](/docs/uploading.md#compressed-uploads)) | `415` `content_encoding_refused` |
| A second file to the same slot | `409` `upload_already_sent` |
| A disk that would be left below `free_space_floor:` | `503` `storage_full` |

On the disk driver the file is streamed to a temporary file as it arrives,
counted, hashed and type-checked, then synced and linked into place, and the
directory is synced, so a client that stops part-way leaves nothing and a
crash leaves the whole file or none of it.

Attaching it. Before the write's statement runs, the runtime checks the
`FileUpload`: that the token is one the field's store signed for that field
and no other, that the file is there, its size, and its type from its first
bytes rather than what the client claimed. A mismatch is `invalid_value`,
`422`, and nothing is written. What fits is then held to the field's settings
as any `File` is ([What a write checks](/docs/files-put-read-and-the-disk-driver-in-development.md#what-a-write-checks)). Asking the
store is an outside call, so a write that attaches an upload comes before the
action's first write, as any outside call does
([`data.write_before_call`](/docs/errors/data.write_before_call.md)), and the
reads before it are a snapshot ([Outside calls hold no
transaction](/docs/all-or-nothing-actions-and-concurrent-changes.md#outside-calls-hold-no-transaction)).

## Large uploads go in parts

A field whose `max_size` is over 100 MB gets a slot in parts instead of a
single address: the same `UploadSlot`, on every store, holding `part_size`,
the size of each part, and `parts_url`, the address its parts go to, in place
of `url`. A slot in parts is good for six hours from when it was given rather
than 15 minutes, so a large file on a slow connection can finish:

```json
{ "token": "upl_eyJrIjoi…", "max_size": 200000000, "part_size": 16777216, "parts_url": "/files/sheets/uploads/upl_eyJrIjoi…/parts" }
```

The client splits the file into parts of exactly `part_size` bytes, the last
one no larger, and sends each to
`PUT /files/<store>/uploads/<token>/parts/<n>`, numbered from 1, in any order
and as many at once as it likes. A part is 16 MiB, unless the field is so
large that it would then take more than 10,000 parts, when `part_size` is the
whole number of MiB that keeps it within them. A part the connection dropped
on leaves nothing, and any part may be sent again, the last one to finish
standing:

```text
POST /imports/slot                          an app route calling CustomerImport.sheet_upload()
<- 200 { "token": "upl_…", "max_size": 200000000, "part_size": 16777216, "parts_url": "/files/sheets/uploads/upl_…/parts" }
PUT /files/sheets/uploads/upl_…/parts/1     16 MiB
<- 204
PUT /files/sheets/uploads/upl_…/parts/2     the connection drops; the client resends part 2
<- 204
POST /imports { "sheet": "upl_…" }          the ordinary create joins the parts, checks size and type
<- 201
```

The file's name and the type it claims are read from the first part's
`Content-Disposition` and `Content-Type`, and the first part's bytes are the
ones its type is told from. The token is attached as for any upload.

| What a part's address refuses | Answer |
|---|---|
| An altered address, one past its six hours, or a part number that isn't a whole number from 1 | `403`, `link_invalid` or `link_expired` |
| A slot's own address sent parts, or a plain slot's sent part numbers | `403` `link_invalid` |
| A part over `part_size`, or over what is left of `max_size`, or numbered past the last a field of `max_size` can have | `413` `file_too_large` |
| A first part whose first bytes aren't a type its field takes | `415` `file_type_refused` |
| A `Content-Encoding` | `415` `content_encoding_refused` |
| A part sent once its file is joined | `409` `upload_already_sent` |
| A disk that would be left below `free_space_floor:` | `503` `storage_full` |

Attaching the `FileUpload` joins the parts, then checks the whole file as any
upload is checked. A part that hasn't been sent is `invalid_value`, `422`, and
so are parts that aren't equal: every part but the last must be exactly
`part_size`, and the last no larger and not empty. The parts are kept, so the
client can send what is missing and attach again. Joining them on a disk that
has no room is `503` `storage_full`.

On the disk driver each part goes to a temporary file as it arrives and is
renamed into place once whole, so a resend replaces it atomically. The parts
are joined in order into one file, which is linked into place, and removed.
Parts of an upload never attached are deleted with it after a day ([Deleting
and erasing](/docs/files.md#deleting-and-erasing)).

## Compressed uploads

An upload sent with a `Content-Encoding` is refused, `415`
`content_encoding_refused`, before any of it is read. A gzip file, such as
`.csv.gz`, is read only by a batch helper given `max_unpacked_size:`, and
going past that size fails the file, so a small upload can't unpack to
gigabytes. That reading is built ([Reading gzip](/docs/reading-gzip.md)). Jadpo
unpacks no other compression and no archives, such as zip.
