Howdy Storage
howdy_storage is an optional package for keeping files: uploads, avatars,
exports, anything too big or too binary for a database column. It gives you
one API over:
- an S3-compatible bucket: AWS S3, Cloudflare R2, Tigris, MinIO, Garage, SeaweedFS, Backblaze B2 and others
- a local folder, for development and apps on one server
- memory, for tests
- an adapter of your own
Browsers fetch files through signed URLs that expire, straight from the bucket, and can upload straight to it too, so large files never pass through your app.
Install
Add the package to your project, next to howdy:
gleam add howdy_storage@1
Objects and keys
A file in storage is an object, stored under a key such as
avatars/3f9c0b…e1.png. Keys look like paths, but there are no folders:
/ is just a character that listing by prefix makes useful.
Make keys with storage.new_key, which gives a random, unguessable name
under a prefix and keeps the extension of the original file:
let key = storage.new_key(prefix: "avatars", file_name: upload.file_name)
// "avatars/3f9c0b5e8d1a4c7f9e2b6a0d1c3e5f71.png"
Never build a key from a name a user chose. Two users upload photo.jpg;
one replaces the other's. Keep the original name in your database if you
want to show it, and pass it to download_url.
Keys are checked before any adapter sees them, so a key that works with one
adapter works with all of them: 1 to 1024 bytes, /-separated segments that
are not empty, . or .., and no control characters or backslashes.
storage.valid_key tells you whether a key passes. Anything else gets
Error(Invalid(...)).
Storing and reading
import howdy/storage
// From memory
storage.put(files, "reports/q3.csv", csv, content_type: "text/csv")
// From a file on disk, such as an upload. Read in parts, never all at once.
storage.put_file(files, key, upload.path, content_type: "image/png")
// With every option
storage.write(key, storage.File(upload.path))
|> storage.content_type("image/png")
|> storage.cache_control("public, max-age=31536000, immutable")
|> storage.download_as("avatar.png")
|> storage.put_with(files, _)
A put replaces whatever was under the key. The rest of the API:
-
storage.get(files, key)reads the whole object into memory. To send a file to a browser, redirect to a URL instead. -
storage.head(files, key)gives theObject: its size, content type, ETag and when it was last changed. -
storage.exists(files, key)asks whether anything is there. -
storage.delete(files, key)removes it. Deleting what is not there succeeds, so retrying a delete is safe. -
storage.list(files, prefix:, after:, limit:)gives aPageof up tolimitobjects, at most 1000, in key order. When there are more,page.nextis the key to pass asafterfor the next page.
Every call waits for its answer, up to the adapter's timeout.
Uploads from forms
howdy/form writes each uploaded file to a
temporary file and deletes it when the handler returns. Store it before
then:
fn change_avatar(ctx: Context, files: storage.Storage) {
let limits =
form.limits() |> form.accept_files(max_files: 1, max_file_size: 5_000_000)
use fields <- form.read_with(ctx, limits)
let avatar = {
use avatar <- form.file(fields, "avatar", [
form.file_type(["image/png", "image/jpeg"]),
])
validate.ok(avatar)
}
case avatar {
Error(errors) ->
controller.html(ctx, avatar_page(errors)) |> controller.with_status(422)
Ok(avatar) -> {
let key = storage.new_key(prefix: "avatars", file_name: avatar.file_name)
case storage.put_file(files, key, avatar.path, content_type: avatar.content_type) {
Ok(Nil) -> {
save_avatar_key(ctx, key)
controller.status(ctx, 303) |> response.set_header("location", "/profile")
}
Error(error) ->
service.error_response(ctx, storage.to_service_error(error))
}
}
}
}
The content type here is what the browser claimed. The file_type rule
keeps it to types you expect, but check the content itself before trusting
it, especially for files you show to other people.
URLs
storage.url gives a URL that anyone holding it can fetch the object from,
until it expires. It is signed, so it cannot be changed to name another
object or to last longer:
let assert Ok(url) = storage.url(files, key, expires_in: 3600)
controller.status(ctx, 303) |> response.set_header("location", url)
storage.download_url(files, key, expires_in:, file_name:) makes the
browser download the file under that name rather than show it. URLs last
from one second to seven days, the most S3 allows.
For files everyone may see, such as public avatars behind a CDN,
storage.public_url(files, key) gives a permanent unsigned URL. It needs
storage set up for it: s3.public_url or local.public.
Direct uploads
An upload through a form passes through your app: the browser sends it to you, and you send it on to storage. For large files, or a bucket far from your servers, the browser can send it to storage itself. Your app only signs the way in, and checks the result:
- The browser tells your app the file's name, type and size.
-
Your app checks the type and size against its own limits, chooses a key,
and answers with
storage.upload_url: a URL, a method and headers. - The browser sends the file there.
-
The browser tells your app it is done, and your app checks the object
with
storage.headbefore using it.
The URL is signed for one key, one content type and one exact size, and expires. Storage refuses an upload of any other size or type, so the limits your app checked in step 2 hold even though the file never reaches it.
import gleam/dynamic/decode
import gleam/json
import howdy/body
import howdy/storage
type UploadInput {
UploadInput(name: String, content_type: String, size: Int)
}
fn upload_input() -> decode.Decoder(UploadInput) {
use name <- decode.field("name", decode.string)
use content_type <- decode.field("type", decode.string)
use size <- decode.field("size", decode.int)
decode.success(UploadInput(name:, content_type:, size:))
}
fn check_upload(input: UploadInput) -> validate.Result(UploadInput) {
use content_type <- validate.field("type", input.content_type, [
validate.one_of(["image/png", "image/jpeg"], fn(type_) { type_ }),
])
use size <- validate.field("size", input.size, [
validate.min(1),
validate.max(5_000_000),
])
validate.ok(UploadInput(..input, content_type:, size:))
}
/// Step 2: POST /avatar/uploads
fn start_upload(ctx: GuardedContext(User), files: storage.Storage) {
use input <- body.validated(ctx, upload_input(), check_upload)
let key =
storage.new_key(prefix: "avatars/" <> ctx.guard.id, file_name: input.name)
let upload =
storage.upload_url(
files,
key,
content_type: input.content_type,
size: input.size,
expires_in: 600,
)
case upload {
Ok(upload) ->
controller.json(ctx, json.object([
#("key", json.string(key)),
#("upload", storage.direct_upload_to_json(upload)),
]))
Error(error) -> service.error_response(ctx, storage.to_service_error(error))
}
}
/// Step 4: POST /avatar
fn finish_upload(ctx: GuardedContext(User), files: storage.Storage) {
use key <- body.json(ctx, decode.at(["key"], decode.string))
// Only a key this user was given.
case string.starts_with(key, "avatars/" <> ctx.guard.id <> "/") {
False -> service.error_response(ctx, service.Forbidden)
True ->
case storage.head(files, key) {
Ok(_) -> {
save_avatar(ctx.guard, key)
controller.status(ctx, 204)
}
Error(error) ->
service.error_response(ctx, storage.to_service_error(error))
}
}
}
Putting the user's id in the key's prefix lets step 4 check that the key is one this user was given, without keeping a list of the URLs you handed out.
howdy_ui's uploader does the browser's part:
uploader.new(name: "avatar", start: "/avatar/uploads")
|> uploader.accept(["image/png", "image/jpeg"])
|> uploader.max_size(5_000_000)
|> uploader.view
It posts to start_upload for each file dropped on it or chosen, sends the
file, and shows its progress. When the file has arrived it adds a hidden
input named avatar holding the key, so the form around it posts the key,
and the form's handler checks it as finish_upload does. The form will not
submit while a file is still on its way.
To write the browser's part yourself, XMLHttpRequest reports how much of
the file has been sent, which fetch cannot yet do:
<input type="file" id="avatar" accept="image/png,image/jpeg">
<progress id="progress" max="100" value="0" hidden></progress>
<script type="module">
const input = document.getElementById("avatar")
const progress = document.getElementById("progress")
const post = (url, data) =>
fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(data),
})
input.addEventListener("change", async () => {
const file = input.files[0]
if (!file) return
const started = await post("/avatar/uploads", {
name: file.name,
type: file.type,
size: file.size,
})
if (!started.ok) return alert("That file cannot be uploaded.")
const { key, upload } = await started.json()
await new Promise((resolve, reject) => {
const request = new XMLHttpRequest()
request.open(upload.method, upload.url)
for (const [name, value] of Object.entries(upload.headers)) {
request.setRequestHeader(name, value)
}
request.upload.onprogress = (event) => {
progress.hidden = false
progress.value = (event.loaded / event.total) * 100
}
request.onload = () => (request.status < 300 ? resolve() : reject())
request.onerror = reject
request.send(file)
})
await post("/avatar", { key })
})
</script>
The browser sets Content-Length from the file itself, so a file that is
not the size it claimed is refused by storage.
An S3 bucket on another origin needs a CORS rule letting your site send the
upload. s3.put_cors sets the bucket's rules with your app's key, if the
key may change the bucket's settings, as an owner's may:
import gleam/http
import howdy/storage/s3
let assert Ok(Nil) =
s3.put_cors(config, [
s3.cors_rule(origins: ["https://app.example.com"], methods: [http.Put]),
])
cors_rule lets the page send a Content-Type and has the browser
remember the answer for an hour. The rules stay on the bucket, so run it
once by hand or each time the app starts. They replace any the bucket had.
Some services set CORS only in their console; the same rule there, for AWS
S3 and Cloudflare R2:
[
{
"AllowedOrigins": ["https://app.example.com"],
"AllowedMethods": ["PUT"],
"AllowedHeaders": ["content-type"],
"MaxAgeSeconds": 3600
}
]
Local storage takes direct uploads too: local.controller answers its
upload URLs and writes the file to disk as it arrives. It is on your own
origin, so it needs no CORS rule, and an app can use the same code in
development as against a bucket in production. Memory storage gives
memory: URLs that nothing can upload to; in tests, store what the browser
would have sent with storage.put and go on to step 4.
A browser that asks for a URL and never finishes leaves nothing behind. One
that uploads and never says it is done leaves an object no record points
to. If that matters, storage.delete_unused deletes the objects under a
prefix that are older than a time you give and that nothing refers to,
asking you about each one. Run it from a
scheduled job, or set a lifecycle rule on the
bucket:
let day_ago = timestamp.add(timestamp.system_time(), duration.hours(-24))
storage.delete_unused(files, prefix: "uploads/", before: day_ago,
in_use: fn(key) { documents.refers_to(db, key) |> result.unwrap(True) },
)
Answer True when unsure, such as when the database cannot say, and the
object is kept until next time.
S3 and compatible services
import howdy/storage/s3
let assert Ok(config) = s3.from_env()
let files = s3.adapter(config)
s3.from_env reads the variables AWS's own tools use, which hosts such as
Fly.io's Tigris set for you:
-
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY, andAWS_SESSION_TOKENfor temporary credentials -
S3_BUCKET, orBUCKET_NAME -
AWS_REGIONorAWS_DEFAULT_REGION, elseus-east-1 -
AWS_ENDPOINT_URL_S3orAWS_ENDPOINT_URLfor a service other than AWS
Or describe the bucket in code:
s3.new(
bucket: "acme-uploads",
region: "auto",
access_key_id: key_id,
secret_access_key: secret,
)
|> s3.endpoint("https://<account>.r2.cloudflarestorage.com")
|> s3.adapter
Without an endpoint the bucket is on AWS and goes in the host name,
acme-uploads.s3.<region>.amazonaws.com. With one, the bucket goes in the
path, which every compatible service understands. s3.path_style changes
either default.
put_file sends files up to 16 MiB in one request and larger ones in 8 MiB
parts, so no more than one part is in memory. A failed upload in parts is
aborted, so its parts are not left in the bucket to be charged for.
s3.multipart changes the sizes, and s3.timeout how long each request may
take, 60 seconds by default.
Browsers that fetch a signed URL from another origin, such as an <img> on
your site, need nothing more. JavaScript that reads the response with
fetch, or uploads directly, needs a CORS rule on the
bucket: s3.put_cors sets one, or set it in your provider's console.
A local folder
import howdy/storage/local
let config =
local.new("storage")
|> local.serve(at: "/files", secret: storage_secret)
let files = local.adapter(config)
howdy.new()
|> howdy.controller(local.controller(config))
Each object is a file at its key under the folder, so you can look inside,
back it up or sync it like any other folder. Each object's content type
and other details are kept beside it under .howdy-storage, which keys may
not start with. A file you copy into the folder by hand is found too, with
a content type from its extension.
local.serve is needed for URLs: storage.url gives a URL under that path,
and local.controller answers it until it expires, or with a 403. Use a
secret of at least 32 random bytes from your configuration, the same on
every node.
Files are served from your app's own origin, where a script could read your
cookies and act as the user. So the controller sends every file with
X-Content-Type-Options: nosniff and a sandboxing
Content-Security-Policy, and makes the browser download anything but
images, audio, video, PDFs and plain text rather than show it. An HTML or
SVG file someone uploaded cannot run script on your site.
local.public serves every object without a signature and gives
public_urls, like a public bucket.
A folder cannot hold both a file a and a folder a/, so storing a key
a/b when a exists is refused, unlike in a bucket.
Errors
Every call returns a storage.Error:
-
NotFound: nothing is stored under the key. -
Invalid(reason): the call is wrong, such as a keyvalid_keyrefuses. -
Unavailable(reason): the service could not be reached, timed out or asked to be tried later.storage.retryableisTruefor these alone. -
Refused(reason): bad credentials, no permission, or a bucket that does not exist.
storage.to_service_error turns one into a service
error: NotFound is a 404, Invalid a
400, and the service's own failures a 500, logged and not shown to the
client.
Each call is a storage.put, storage.get and so on span when telemetry
is on, with the adapter and the key.
Your own adapter
storage.adapter builds storage from your functions. Keys and URL requests
are checked before your functions see them:
storage.adapter(
named: "archive",
put: fn(put) { ... }, // put.key, put.body, put.content_type, ...
get: fn(key) { ... },
head: fn(key) { ... },
delete: fn(key) { ... }, // succeed for a missing key
list: fn(prefix, after, limit) { ... },
url: fn(request) { ... }, // request.key, request.expires_in, ...
)
|> storage.with_direct_uploads(fn(request) { ... }) // optional
Testing
howdy/storage/memory keeps objects in a process, so tests need no bucket
and no folder:
import howdy/storage/memory
pub fn avatar_is_stored_test() {
let files = memory.new()
let res =
testing.post_multipart("/avatar", [], [
testing.FormFile("avatar", "me.png", "image/png", <<137, 80, 78, 71>>),
])
|> testing.send(app(files))
assert res.status == 303
let assert Ok(page) = storage.list(files, prefix: "avatars/", after: None, limit: 10)
assert list.length(page.objects) == 1
}
Its URLs are memory: followed by the key, which no browser can open, so
a test can check that a URL was made without fetching it.
