The ecosystem · packages/storage
Files, in S3 or beside the server
Uploads, avatars, videos: files that don't belong in the database go in a bucket. This package keeps a file, reads it back whole or in part, uploads a large one in parts, hands out links the browser uploads or downloads with directly, and serves a file of any size, ranges included.
The bucket can be any S3 (AWS, Cloudflare R2, or rustfs or MinIO on your machine), a directory beside the server, or the server's memory for tests. A URL picks which; your code is the same for all three. The package runs on the server only. The browser reaches the files through links and answers your server gives it.
The samples come from server/test/app/Samples.roc, which the server platform's tests run on memory, on a directory, and on a real S3 bucket when one is configured.
A bucket#
Name the package in the server's header, beside the server platform:
app [program] { pf: platform "../server/platform/main.roc", storage: "../packages/storage/main.roc" }Then make a bucket from its URL, kept in the server's environment (here STORAGE_URL):
## The app's bucket: the one its `STORAGE_URL` names (`s3://…`, `file:<dir>`, `memory:`).
files! : {} => Try(Storage.Bucket, [StorageErr(Str)])
files! = |{}| Storage.from_url(Env.var!("STORAGE_URL") ?? "")Storage.from_url only reads the URL; it doesn't contact the bucket. An empty or unreadable URL is a StorageErr that says what is wrong. The URL's scheme picks the backend:
s3://KEY:SECRET@127.0.0.1:9000/uploads?region=us-east-1&style=path&tls=no # rustfs or MinIO
s3://KEY:SECRET@<account>.r2.cloudflarestorage.com/uploads?region=auto # R2
s3://KEY:SECRET@s3.eu-west-1.amazonaws.com/uploads?region=eu-west-1 # AWS
file:data/uploads?secret=… # files beside the server
memory: # the server's memory: tests- S3 (
s3://). The URL's path is the bucket's name.regionis the region the keys sign for:us-east-1if left out,autofor R2.style=pathputs the bucket in the request's path, as rustfs and MinIO want; without it, the bucket goes in the host name, as AWS and R2 prefer.tls=nouses plainhttp. Write any character the URL would misread as%XX. Any other parameter is refused, so a typo such asstlye=pathfails at once. - A directory (
file:data/uploads, relative to where the server starts; created if missing). Each file is a real file at its key, written to a temporary file and then moved into place, so a crash never leaves half a file. Its content type and ETag are kept beside it, in.storage/. A directory suits an app on one server, as SQLite does (the database); in production, put it on a volume. - Memory (
memory:, ormemory:namefor a separate bucket). Gone when the server stops. Use it in tests, which then need no S3.
A directory or memory URL may also give secret, the key for its signed links. Without it, the server picks a random one at each start, and links given out before a restart stop working.
Storage.check!(bucket) asks whether the bucket answers: for S3, that the keys work for this bucket; for a directory, that it can be written to; memory always answers. Call it from a health check, so a wrong URL shows before the first upload.
Keeping a file#
A file in a bucket is an object, stored under a key: its name in the bucket, slashes included (avatars/ada). Its bytes are a List(U8).
## A member's avatar, the bytes the browser sent, kept under the member's name.
save_avatar! : Str, Server.Request => Try({}, [S3Err(Storage.Refusal), StorageErr(Str)])
save_avatar! = |member, request| {
type = Server.header(request, "content-type") ?? "application/octet-stream"
Storage.put!(Samples.files!({})?, "avatars/${member}", request.body, { content_type: type })
}
## Its size and type, asked without its bytes.
avatar_size! : Str => Try(Str, [NotFound, S3Err(Storage.Refusal), StorageErr(Str)])
avatar_size! = |member| {
info = Storage.head!(Samples.files!({})?, "avatars/${member}")?
Ok("${info.size.to_str()} bytes of ${info.content_type}")
}
## Its bytes, read whole (64 MiB at most), and gone again.
take_avatar! : Str => Try(List(U8), [NotFound, S3Err(Storage.Refusal), StorageErr(Str)])
take_avatar! = |member| {
files = Samples.files!({})?
bytes = Storage.get!(files, "avatars/${member}")?
Storage.delete!(files, "avatars/${member}")?
Ok(bytes)
}Storage.put!(bucket, key, bytes, { content_type })keeps a file under a key, replacing whatever was there.Storage.put_upload!(bucket, key, upload)keeps a file a form sent, asServer.file(request, "photo")reads it (forms), with the browser's type.Storage.get!(bucket, key)reads a file whole. From S3, a file over 64 MiB is refused; read it in pieces instead.Storage.get_range!(bucket, key, { offset, length })reads a piece of a file and answers the file's whole size, so you can read a large one piece by piece.Storage.head!(bucket, key)describes a file without reading it: its size, content type and ETag. For a file put whole, the ETag is its MD5, on every backend.Storage.delete!(bucket, key)deletes a file. Deleting a missing file isOk, so a cleanup can safely run twice.
On a directory or memory bucket, a key must be a plain path, so it can never reach outside the directory. Refused: an empty key, an empty segment (a leading /, or a//b), a . or .. segment, and a key that starts with .storage.
A large file, in parts#
A video is too large for one request. A multipart upload sends it in numbered parts, then joins them:
## A video in parts, as a browser sends a large file: started, each part sent (5 MiB or more,
## but the last, for S3), then finished, the parts put together.
save_in_parts! : Str, List(List(U8)) => Try({}, [NotFound, S3Err(Storage.Refusal), StorageErr(Str)])
save_in_parts! = |key, parts| {
files = Samples.files!({})?
upload = Storage.start_upload!(files, key, { content_type: "video/mp4" })?
var $sent = []
for part in parts {
number = $sent.len() + 1
etag = Storage.upload_part!(files, key, upload, number, part)?
$sent = $sent.append({ number, etag })
}
Storage.finish_upload!(files, key, upload, $sent)
}Storage.start_upload!starts the upload and answers its id.Storage.upload_part!sends one part by its number (1 to 10,000) and answers the part's ETag. Sending a number again replaces that part.Storage.finish_upload!joins the parts you list, in number order, into one file. A part listed with an ETag that isn't its own is refused, and a part you don't list is dropped. The file's ETag is the MD5 of the parts' MD5s and their count (…-3), as S3 makes it.
Storage.abort_upload! drops an upload and its parts. On S3, every part but the last must be 5 MiB or more; S3 refuses a smaller one at the end with EntityTooSmall.
Signed links#
A signed link lets the browser upload or download one file directly, without your server code in the middle. Anyone holding it can make that one request until it expires, so treat it as a secret.
## A link the browser uploads a file with itself, for an hour: to S3, which the app's server never
## sees; or to the app, the storage plugin's (`file:`, `memory:`).
upload_link! : Str => Try(Str, [BadExpiry, StorageErr(Str)])
upload_link! = |key| Storage.signed_url!(Samples.files!({})?, key, { method: "PUT", expires_s: 3600 })Storage.signed_url!(bucket, key, { method, expires_s }) makes a link for a GET or a PUT of that key, valid for expires_s seconds, from 1 up to a week. Anything else is BadExpiry.
- On S3 it is S3's own presigned URL. The browser talks to S3, so your server never holds the bytes. Only the host is signed, so a
PUTmay send any content type. - On a directory or memory it is a link to your own app, at
/_storageunder its public URL (or the path you give asat,{ method: "GET", expires_s: 600, at: "/files/signed" }). A route of yours answers it there (D-116) by calling the package's handler. Each link is signed, so the route needs no middleware of yours:
import storage.Storage
# The signed links of the bucket STORAGE_URL names.
respond! = |{ request, .. }| Storage.signed_route!(request, "STORAGE_URL")The handler reads the bucket from the variable it is given (STORAGE_URL here). Before it serves the file (ranges included) or keeps the one sent, it checks the link's method, its expiry and its signature: an HMAC-SHA256 of the method, the key and the expiry, made with the bucket's secret. A link it didn't make, a changed one or an expired one gets a 403. A PUT through the route is an ordinary request body, so it is limited to 16 MiB unless the server's --max-body allows more; send larger files in parts. For an S3 bucket the route has nothing to answer: S3 answers its own links.
Serving one#
## A video, sent to whoever asks, ranges and all, never through Roc. Without a bucket, a 500,
## and the log says why.
serve_video! : Str, Server.Request => Server.Response
serve_video! = |key, request|
match Samples.files!({}) {
Ok(files) => Storage.serve!(files, key, request, { content_type: "video/mp4", cache_control: "private, max-age=3600" })
Err(StorageErr(why)) => {
Log.error!("no storage", { why: why })
Server.refused(500, "Something went wrong.")
}
}
## The same, always whole: the request's range dropped before the bucket is asked.
serve_whole! : Str, Server.Request => Server.Response
serve_whole! = |key, request| {
whole = { ..request, headers: request.headers.drop_if(|header| header.name == "range") }
match Samples.files!({}) {
Ok(files) => Storage.serve!(files, key, whole, { content_type: "video/mp4", cache_control: "private" })
Err(_) => Server.refused(500, "Something went wrong.")
}
}Storage.serve!(bucket, key, request, { content_type, cache_control }) answers a request with a file of any size. The bytes never pass through Roc:
- From S3, the answer is a forward: the server streams the file from S3 to the browser as it arrives (a body from elsewhere).
- From a directory or memory, the server sends the file it keeps (
Server.stored).
The request's Range and If-None-Match headers are passed on, so a video player's range requests get 206s and a browser's cache gets its 304s. A missing file is a 404. An empty content_type sends the type the file was stored with, and an empty cache_control sends none. The headers come from the request record, so you can change them first: serve_whole! above drops the range to always send the whole file.
Errors#
Each function's error type lists only the errors it can give:
NotFound: no such file, or no such upload.S3Err({ status, code, message }): S3 answered with an error, such asAccessDenied,SignatureDoesNotMatch,NoSuchBucket,EntityTooSmall,InvalidPartorInvalidRange.Storage.said(refusal)writes one as a line for the log.StorageErr(why): S3 didn't answer, or answered too late; a file couldn't be written; or the key isn't valid.Storage.from_urlgives one too, for a missing or unreadable URL.
A directory or memory bucket gives a StorageErr where S3 gives an S3Err (a part listed with the wrong ETag, say). A range that starts past a file's end is no bytes on a directory or memory, and InvalidRange on S3.
How it works#
For S3, the package signs each request itself with AWS Signature Version 4 (its SigV4 module, checked against AWS's worked examples) and sends it with the server platform's Http.send! (asking another server). Requests time out after 30 seconds, or 5 minutes for one that carries or reads a file. put! signs its body's SHA-256, so S3 refuses the file if anything changed on the way.
For a directory or memory, the server's host keeps the files (the platform's Blobs module), reading and writing them on its threads for blocking work, so a call waiting on a file doesn't hold up other Roc calls. A multipart upload keeps its parts under .uploads/ until it is finished or aborted.
The full API, with each function's type, is in packages/storage/README.md.
Not yet#
- Whole files in memory:
put!andget!hold the whole file in memory. Read a large one withget_range!, or send it to the browser withserve!. - No listing of a bucket's files, and no copying a file to another key.
- A directory belongs to one server: two servers can't share one.
- S3's static keys only: no session tokens.