Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

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:

main.roc's header
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):

server/test/app/Samples.roc, in part
## 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:

STORAGE_URL
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

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).

server/test/app/Samples.roc, in part
## 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)
}

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:

server/test/app/Samples.roc, in part
## 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)
}
  1. Storage.start_upload! starts the upload and answers its id.
  2. 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.
  3. 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.

server/test/app/Samples.roc, in part
## 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.

routes/_storage/+server.roc
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#

server/test/app/Samples.roc, in part
## 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:

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:

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#