ocre/runtime/storage.rs
1use axum::{body::Body, http::HeaderMap, response::Response};
2use futures_util::StreamExt as _;
3use worker::{
4 Bucket, Conditional, Env, FixedLengthStream, HttpMetadata, Include, Object, Range, ResponseBody,
5 send::{SendFuture, SendWrapper},
6 web_sys,
7};
8
9use super::Ctx;
10use crate::{
11 Error, IntoParam as _, Result,
12 config::Environment,
13 mail::APP_URL,
14 storage::{
15 Attachment, ByteRange, DEV_APP_URL, DirectUpload, DirectUploadRequest, Disposition, Fetch, KEYS_PER_QUERY,
16 Listing, MAX_LIST, Purged, Rules, S3Endpoint, STORAGE_BINDING, STORAGE_PUBLIC_URL, StoredObject, Upload,
17 attachment_from_head, check_expires_in, dev_get_url, dev_url, essence, file_response, join_public_url,
18 missing_binding, not_modified, presign_get_url, r2_endpoint, redirect_response, referenced_keys_sql,
19 stale_keys, unsatisfiable, upload_secret, verify_key,
20 },
21};
22
23pub(super) fn bucket(env: &Env) -> Result<Bucket> {
24 env.bucket(STORAGE_BINDING).map_err(|err| missing_binding(&err.to_string()))
25}
26
27async fn put(env: &Env, attachment: &Attachment, data: worker::Data) -> Result<()> {
28 let metadata = HttpMetadata { content_type: Some(attachment.content_type.clone()), ..Default::default() };
29 bucket(env)?
30 .put(&attachment.key, data)
31 .http_metadata(metadata)
32 .custom_metadata([("filename".to_owned(), attachment.filename.clone())])
33 .execute()
34 .await
35 .map_err(|err| Error::internal(format!("R2 put of `{}` failed: {err}", attachment.key)))?;
36 Ok(())
37}
38
39/// Stores an [`Upload`] in R2 under a new random key starting with `prefix`, and returns the [`Attachment`] to save.
40///
41/// The key is `<prefix>/<22 random characters>` (`posts/avatar/...`),
42/// never derived from the file name; the file name and content type are
43/// cleaned up like [`store_bytes`](crate::storage::store_bytes)'s. Check
44/// the upload with [`Validator::file`](crate::Validator::file) first, and
45/// save the attachment with [`columns`](crate::storage::columns); if saving
46/// the row fails, [`delete`](crate::storage::delete) the new key.
47///
48/// Free plan: one R2 class A operation (1M free per month); copying 10 MB
49/// to R2 takes about 0.15 ms of CPU. Stored files count towards the 10
50/// GB-month of free storage.
51///
52/// # Errors
53///
54/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
55/// binding is missing (the message shows the `STORAGE` entry to add
56/// to cloudflare.config.ts) or the R2 write fails.
57///
58/// # Examples
59///
60/// ```no_run
61/// use axum::extract::State;
62/// use ocre::storage::{self, Multipart, Rules};
63/// use ocre::{Ctx, Error, Result, Validator};
64///
65/// const DOCUMENT: Rules = Rules { max_bytes: 10 * 1024 * 1024, content_types: &["application/pdf"] };
66///
67/// // PUT /documents with `curl -X PUT -F file=@spec.pdf`.
68/// async fn upload(State(ctx): State<Ctx>, Multipart(mut form): Multipart<{ 11 * 1024 * 1024 }>) -> Result<String> {
69/// let file = form.file("file").ok_or_else(|| Error::bad_request("Send the file as `file`"))?;
70/// Validator::new().file("file", &file, &DOCUMENT).finish()?;
71/// let document = storage::store(&ctx, "documents/file", file).await?;
72/// Ok(document.key)
73/// }
74/// ```
75pub fn store(ctx: &Ctx, prefix: &str, upload: Upload) -> impl Future<Output = Result<Attachment>> + Send + use<> {
76 store_bytes(ctx, prefix, &upload.filename, &upload.content_type, Vec::from(upload.bytes))
77}
78
79/// Stores bytes built by the app (a generated report, an export) like [`store`](crate::storage::store).
80///
81/// The object gets a new random key under `prefix`; `filename` is cleaned
82/// up (no directories or control characters, at most 200 characters) and
83/// `content_type` normalized (lowercase, no parameters; empty becomes
84/// `application/octet-stream`). The returned [`Attachment`] records all
85/// four, ready to save with [`columns`](crate::storage::columns).
86///
87/// Free plan: one R2 class A operation (1M free per month); copying 10 MB
88/// to R2 takes about 0.15 ms of CPU.
89///
90/// # Errors
91///
92/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
93/// binding is missing (the message shows the `STORAGE` entry to add
94/// to cloudflare.config.ts) or the R2 write fails.
95///
96/// # Examples
97///
98/// ```no_run
99/// use axum::extract::State;
100/// use ocre::{Ctx, Result, storage};
101/// use serde::Deserialize;
102///
103/// #[derive(Deserialize)]
104/// struct Post {
105/// id: i64,
106/// title: String,
107/// }
108///
109/// // POST /exports: writes every post to a CSV kept in R2.
110/// async fn export(State(ctx): State<Ctx>) -> Result<String> {
111/// let posts: Vec<Post> = ctx.db()?.all("SELECT id, title FROM posts ORDER BY id", vec![]).await?;
112/// let mut csv = String::from("id,title\n");
113/// for post in posts {
114/// csv.push_str(&format!("{},\"{}\"\n", post.id, post.title.replace('"', "\"\"")));
115/// }
116/// let file = storage::store_bytes(&ctx, "exports", "posts.csv", "text/csv", csv.into_bytes()).await?;
117/// Ok(file.key)
118/// }
119/// ```
120pub fn store_bytes(
121 ctx: &Ctx,
122 prefix: &str,
123 filename: &str,
124 content_type: &str,
125 bytes: Vec<u8>,
126) -> impl Future<Output = Result<Attachment>> + Send + use<> {
127 let env = ctx.env().clone();
128 let attachment = Attachment::prepare(prefix, filename, content_type, bytes.len() as u64);
129 SendFuture::new(async move {
130 put(&env, &attachment, bytes.into()).await?;
131 Ok(attachment)
132 })
133}
134
135/// Streams `body` (exactly `size` bytes) into R2 without holding it in memory, and returns its [`Attachment`].
136///
137/// For a raw request body with a `Content-Length` (`curl -T big.zip`),
138/// where [`Multipart`](crate::storage::Multipart) would hold the whole body
139/// in memory. R2 needs the length up front: a body of another length makes
140/// the write fail and nothing is stored. The file name and content type are
141/// cleaned up like [`store_bytes`]'s; no [`Rules`](crate::storage::Rules)
142/// are checked, so check `size` and `content_type` first.
143///
144/// Free plan: one R2 class A operation (1M free per month). Chunks still
145/// pass through WebAssembly, but memory stays flat; Cloudflare refuses
146/// request bodies over 100 MB on the Free plan.
147///
148/// # Errors
149///
150/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
151/// binding is missing (the message shows the `STORAGE` entry to add
152/// to cloudflare.config.ts), the body is not `size` bytes long, or the R2 write fails.
153///
154/// # Examples
155///
156/// ```no_run
157/// use axum::{body::Body, extract::State, http::{HeaderMap, header}};
158/// use ocre::{Ctx, Error, Result, storage};
159///
160/// const MAX: u64 = 50 * 1024 * 1024;
161///
162/// // PUT /backups with `curl -T backup.zip`.
163/// async fn upload(State(ctx): State<Ctx>, headers: HeaderMap, body: Body) -> Result<String> {
164/// let size: u64 = headers
165/// .get(header::CONTENT_LENGTH)
166/// .and_then(|value| value.to_str().ok()?.parse().ok())
167/// .ok_or_else(|| Error::bad_request("Content-Length required"))?;
168/// if size > MAX {
169/// return Err(Error::PayloadTooLarge("The backup is too large (maximum is 50 MB)".into()));
170/// }
171/// let backup = storage::store_body(&ctx, "backups", "backup.zip", "application/zip", size, body).await?;
172/// Ok(backup.key)
173/// }
174/// ```
175pub fn store_body(
176 ctx: &Ctx,
177 prefix: &str,
178 filename: &str,
179 content_type: &str,
180 size: u64,
181 body: Body,
182) -> impl Future<Output = Result<Attachment>> + Send + use<> {
183 let env = ctx.env().clone();
184 let attachment = Attachment::prepare(prefix, filename, content_type, size);
185 SendFuture::new(async move {
186 let chunks = body
187 .into_data_stream()
188 .map(|chunk| chunk.map(|bytes| bytes.to_vec()).map_err(|err| worker::Error::RustError(err.to_string())));
189 put(&env, &attachment, FixedLengthStream::wrap(chunks, size).into()).await?;
190 Ok(attachment)
191 })
192}
193
194/// Reads a whole object into memory, or returns `None` when `key` does not exist.
195///
196/// Meant for files the Worker itself processes (parsing an uploaded CSV,
197/// attaching a file to an email). To send a file to a browser use
198/// [`serve`](crate::storage::serve), which streams it without copying it
199/// into WebAssembly and handles 304 and `Range`.
200///
201/// Free plan: one R2 class B operation (10M free per month); the bytes are
202/// copied into WebAssembly memory (a Worker has 128 MB).
203///
204/// # Errors
205///
206/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
207/// binding is missing (the message shows the `STORAGE` entry to add
208/// to cloudflare.config.ts) or R2 fails.
209///
210/// # Examples
211///
212/// ```no_run
213/// use axum::extract::{Path, State};
214/// use ocre::{Ctx, OptionExt, Result, storage};
215///
216/// // Counts the lines of an uploaded CSV.
217/// async fn line_count(State(ctx): State<Ctx>, Path(key): Path<String>) -> Result<String> {
218/// let bytes = storage::read(&ctx, &key).await?.or_404()?;
219/// Ok(bytes.split(|&b| b == b'\n').filter(|line| !line.is_empty()).count().to_string())
220/// }
221/// ```
222pub fn read(ctx: &Ctx, key: &str) -> impl Future<Output = Result<Option<Vec<u8>>>> + Send + use<> {
223 let env = ctx.env().clone();
224 let key = key.to_owned();
225 SendFuture::new(async move {
226 let Some(object) = bucket(&env)?.get(&key).execute().await? else { return Ok(None) };
227 match object.body() {
228 Some(body) => Ok(Some(body.bytes().await?)),
229 None => Ok(Some(Vec::new())),
230 }
231 })
232}
233
234/// Deletes the object at `key`.
235///
236/// Deleting a missing key is not an error, so a retried cleanup is safe.
237/// Delete the object only once no row points to it any more (after the
238/// database write succeeded). R2 deletes are free.
239///
240/// # Errors
241///
242/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
243/// binding is missing (the message shows the `STORAGE` entry to add
244/// to cloudflare.config.ts) or R2 fails.
245///
246/// # Examples
247///
248/// ```no_run
249/// use axum::{extract::{Path, State}, http::StatusCode};
250/// use ocre::{Ctx, Result, params, storage};
251///
252/// // DELETE /exports/{key}: forget a generated export.
253/// async fn destroy(State(ctx): State<Ctx>, Path(key): Path<String>) -> Result<StatusCode> {
254/// ctx.db()?.execute("DELETE FROM exports WHERE file_key = ?1", params![key.as_str()]).await?;
255/// storage::delete(&ctx, &key).await?;
256/// Ok(StatusCode::NO_CONTENT)
257/// }
258/// ```
259pub fn delete(ctx: &Ctx, key: &str) -> impl Future<Output = Result<()>> + Send + use<> {
260 let env = ctx.env().clone();
261 let key = key.to_owned();
262 SendFuture::new(async move { Ok(bucket(&env)?.delete(key).await?) })
263}
264
265/// Deletes the objects of every `Some` attachment in one R2 call.
266///
267/// `None` entries (optional attachments left empty) are skipped, and
268/// nothing is sent when all are `None`. Generated models call it after a
269/// record is deleted, or after an update replaced or removed its files, so
270/// a failed database write never loses a file that a row still points to.
271/// Missing keys are not an error. R2 deletes are free.
272///
273/// # Errors
274///
275/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
276/// binding is missing (the message shows the `STORAGE` entry to add
277/// to cloudflare.config.ts) or R2 fails.
278///
279/// # Examples
280///
281/// ```no_run
282/// use axum::{extract::{Path, State}, http::StatusCode};
283/// use ocre::storage::{self, Attachment};
284/// use ocre::{Ctx, Result, params};
285///
286/// async fn destroy(State(ctx): State<Ctx>, Path(id): Path<i64>) -> Result<StatusCode> {
287/// let db = ctx.db()?;
288/// let image: Option<Attachment> = db
289/// .first(
290/// "SELECT image_key AS key, image_filename AS filename, image_content_type AS content_type, \
291/// image_size AS size FROM photos WHERE id = ?1 AND image_key IS NOT NULL",
292/// params![id],
293/// )
294/// .await?;
295/// db.execute("DELETE FROM photos WHERE id = ?1", params![id]).await?;
296/// storage::delete_attachments(&ctx, &[image]).await?;
297/// Ok(StatusCode::NO_CONTENT)
298/// }
299/// ```
300pub fn delete_attachments(
301 ctx: &Ctx,
302 attachments: &[Option<Attachment>],
303) -> impl Future<Output = Result<()>> + Send + use<> {
304 let env = ctx.env().clone();
305 let keys: Vec<String> = attachments.iter().flatten().map(|attachment| attachment.key.clone()).collect();
306 SendFuture::new(async move {
307 if !keys.is_empty() {
308 bucket(&env)?.delete_multiple(keys).await?;
309 }
310 Ok(())
311 })
312}
313
314/// The [`StoredObject`] of an R2 object (from `head`, `get` or `list` with metadata).
315fn stored(object: &Object) -> StoredObject {
316 StoredObject {
317 key: object.key(),
318 size: object.size(),
319 content_type: essence(object.http_metadata().content_type.as_deref().unwrap_or_default()),
320 etag: object.etag(),
321 uploaded_at: i64::try_from(object.uploaded().as_millis() / 1000).unwrap_or(i64::MAX),
322 filename: object.custom_metadata().ok().and_then(|mut metadata| metadata.remove("filename")),
323 }
324}
325
326/// The S3 endpoint of the `R2_*` variables and secrets.
327pub(super) fn endpoint(env: &Env) -> Result<S3Endpoint> {
328 r2_endpoint(&|name| env.var(name).ok().map(|value| value.to_string()))
329}
330
331/// In development, the app address presigned URLs point to instead of R2
332/// (`APP_URL`, else `http://localhost:8787`); `None` in release builds.
333pub(super) fn dev_base(env: &Env) -> Option<String> {
334 Environment::current().is_development().then(|| {
335 env.var(APP_URL)
336 .ok()
337 .map(|value| value.to_string().trim().to_owned())
338 .filter(|value| !value.is_empty())
339 .unwrap_or_else(|| DEV_APP_URL.to_owned())
340 })
341}
342
343/// How long the URL of a [`direct_upload`] can be used to start the `PUT`: 10 minutes.
344const DIRECT_UPLOAD_EXPIRES_IN: u64 = 600;
345
346/// Describes the object at `key` without reading it: size, content type, ETag, upload time; `None` when it does not exist.
347///
348/// Active Storage's `blob.byte_size`/`service.exist?` in one call. Direct
349/// uploads are checked with it ([`attach_direct_upload`]), and purges read
350/// the upload time.
351///
352/// Free plan: one R2 class B operation (10M free per month).
353///
354/// # Errors
355///
356/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
357/// binding is missing (the message shows the `STORAGE` entry to add
358/// to cloudflare.config.ts) or R2 fails.
359///
360/// # Examples
361///
362/// ```no_run
363/// use axum::extract::{Path, State};
364/// use ocre::{Ctx, OptionExt, Result, storage};
365///
366/// // GET /files/{*key}/size
367/// async fn size(State(ctx): State<Ctx>, Path(key): Path<String>) -> Result<String> {
368/// let object = storage::head(&ctx, &key).await?.or_404()?;
369/// Ok(format!("{} ({}), uploaded at {}", storage::human_size(object.size), object.content_type, object.uploaded_at))
370/// }
371/// ```
372pub fn head(ctx: &Ctx, key: &str) -> impl Future<Output = Result<Option<StoredObject>>> + Send + use<> {
373 let env = ctx.env().clone();
374 let key = key.to_owned();
375 SendFuture::new(async move { Ok(bucket(&env)?.head(key).await?.as_ref().map(stored)) })
376}
377
378/// Returns whether an object exists at `key` (Active Storage's `exist?`); a [`head`] without the details.
379///
380/// Free plan: one R2 class B operation (10M free per month).
381///
382/// # Errors
383///
384/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
385/// binding is missing or R2 fails.
386///
387/// # Examples
388///
389/// ```no_run
390/// use axum::extract::{Path, State};
391/// use ocre::{Ctx, Result, storage};
392///
393/// async fn check(State(ctx): State<Ctx>, Path(key): Path<String>) -> Result<String> {
394/// Ok(storage::exists(&ctx, &key).await?.to_string())
395/// }
396/// ```
397pub fn exists(ctx: &Ctx, key: &str) -> impl Future<Output = Result<bool>> + Send + use<> {
398 let object = head(ctx, key);
399 async move { Ok(object.await?.is_some()) }
400}
401
402/// Lists one page of the objects whose key starts with `prefix`, in key order, with their size, type and upload time.
403///
404/// Pass `None` as `cursor` for the first page, then the returned
405/// [`Listing::cursor`] until it is `None`. `limit` is clamped to 1..=1000;
406/// a page may hold fewer objects even when more follow (R2 caps the
407/// metadata it returns), so rely on the cursor, not the count.
408///
409/// Free plan: one R2 class A operation per call, like an upload (1M free
410/// per month), and decoding 1,000 entries takes a few ms of the 10 ms of
411/// CPU: list in scheduled tasks or admin pages, never on every request.
412///
413/// # Errors
414///
415/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
416/// binding is missing or R2 fails.
417///
418/// # Examples
419///
420/// ```no_run
421/// use ocre::{Ctx, Result, storage};
422///
423/// // Total size of the exports, 1,000 keys (one class A operation) at a time.
424/// async fn exports_size(ctx: &Ctx) -> Result<u64> {
425/// let (mut total, mut cursor) = (0, None);
426/// loop {
427/// let page = storage::list(ctx, "exports/", cursor.as_deref(), 1000).await?;
428/// total += page.objects.iter().map(|object| object.size).sum::<u64>();
429/// cursor = page.cursor;
430/// if cursor.is_none() {
431/// return Ok(total);
432/// }
433/// }
434/// }
435/// ```
436pub fn list(
437 ctx: &Ctx,
438 prefix: &str,
439 cursor: Option<&str>,
440 limit: u32,
441) -> impl Future<Output = Result<Listing>> + Send + use<> {
442 let env = ctx.env().clone();
443 let prefix = prefix.to_owned();
444 let cursor = cursor.map(str::to_owned);
445 let limit = limit.clamp(1, MAX_LIST);
446 SendFuture::new(async move {
447 let bucket = bucket(&env)?;
448 let mut request =
449 bucket.list().prefix(prefix).limit(limit).include(vec![Include::HttpMetadata, Include::CustomMetadata]);
450 if let Some(cursor) = cursor {
451 request = request.cursor(cursor);
452 }
453 let page = request.execute().await?;
454 let objects = page.objects().iter().map(stored).collect();
455 Ok(Listing { objects, cursor: if page.truncated() { page.cursor() } else { None } })
456 })
457}
458
459/// Reads the first `length` bytes of an object (all of it when shorter), or `None` when `key` does not exist.
460///
461/// For [`analyze`](crate::storage::analyze) on a file uploaded directly:
462/// the signature and image size are in the first few KB (use 256 KB for
463/// JPEGs with large EXIF blocks), so the Worker never holds the whole file.
464///
465/// Free plan: one R2 class B operation (10M free per month).
466///
467/// # Errors
468///
469/// [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
470/// binding is missing or R2 fails.
471///
472/// # Examples
473///
474/// ```no_run
475/// use ocre::{Ctx, Result, storage};
476///
477/// async fn dimensions(ctx: &Ctx, key: &str) -> Result<Option<(u32, u32)>> {
478/// let Some(start) = storage::read_first(ctx, key, 64 * 1024).await? else { return Ok(None) };
479/// let analysis = storage::analyze(&start);
480/// Ok(analysis.width.zip(analysis.height))
481/// }
482/// ```
483pub fn read_first(ctx: &Ctx, key: &str, length: u64) -> impl Future<Output = Result<Option<Vec<u8>>>> + Send + use<> {
484 let env = ctx.env().clone();
485 let key = key.to_owned();
486 let length = length.max(1);
487 SendFuture::new(async move {
488 let bucket = bucket(&env)?;
489 let Some(object) = bucket.get(&key).range(Range::Prefix { length }).execute().await? else { return Ok(None) };
490 match object.body() {
491 Some(body) => Ok(Some(body.bytes().await?)),
492 None => Ok(Some(Vec::new())),
493 }
494 })
495}
496
497/// Presigns a `GET` of an attachment on R2's S3 API, valid `expires_in` seconds (at most 7 days).
498///
499/// The browser downloads straight from R2 (`https://<account>.r2.cloudflarestorage.com/...`),
500/// not through the Worker. R2 answers with the same safe `Content-Type`
501/// and `Content-Disposition` as [`serve`] (the URL carries
502/// `response-content-type` and `response-content-disposition`). Anyone with
503/// the URL can download the file until it expires: authorize before
504/// presigning and keep lifetimes short. [`serve_redirect`] answers a
505/// redirect to it.
506///
507/// Reads the [`R2_ACCOUNT_ID`](crate::storage::R2_ACCOUNT_ID) and
508/// [`R2_BUCKET`](crate::storage::R2_BUCKET) variables and the
509/// [`R2_ACCESS_KEY_ID`](crate::storage::R2_ACCESS_KEY_ID) and
510/// [`R2_SECRET_ACCESS_KEY`](crate::storage::R2_SECRET_ACCESS_KEY) secrets.
511/// Signing is local: no R2 operation, microseconds of CPU; the download
512/// is one class B operation. In debug builds (`ocre dev`, `ocre test`) the
513/// URL points to the app's [`DEV_STORAGE_PATH`](crate::storage::DEV_STORAGE_PATH)
514/// route on the local bucket instead, and no `R2_*` setting is needed.
515///
516/// # Errors
517///
518/// [`Error::Internal`](crate::Error::Internal) (500) when one of the four
519/// settings is missing in a release build (the message names them and how
520/// to set them), or `expires_in` is 0 or over 7 days.
521///
522/// # Examples
523///
524/// ```no_run
525/// use axum::{Json, extract::{Path, State}};
526/// use ocre::storage::{self, Attachment, Disposition};
527/// use ocre::{Ctx, OptionExt, Result, params};
528///
529/// // GET /api/documents/{id}/download_url: a link valid 5 minutes.
530/// async fn download_url(State(ctx): State<Ctx>, Path(id): Path<i64>) -> Result<Json<String>> {
531/// let sql = "SELECT file_key AS key, file_filename AS filename, file_content_type AS content_type, \
532/// file_size AS size FROM documents WHERE id = ?1 AND file_key IS NOT NULL";
533/// let file: Attachment = ctx.db()?.first(sql, params![id]).await?.or_404()?;
534/// Ok(Json(storage::presign_get(&ctx, &file, Disposition::Download, 300)?))
535/// }
536/// ```
537pub fn presign_get(ctx: &Ctx, attachment: &Attachment, disposition: Disposition, expires_in: u64) -> Result<String> {
538 match dev_base(ctx.env()) {
539 Some(base) => dev_get_url(&base, attachment, disposition, expires_in),
540 None => presign_get_url(&endpoint(ctx.env())?, attachment, disposition, crate::now(), expires_in),
541 }
542}
543
544/// Presigns a `PUT` of exactly `size` bytes of type `content_type` at `key`, valid `expires_in` seconds.
545///
546/// The URL signs `Content-Type` (normalized) and `Content-Length`: R2
547/// refuses a `PUT` with another type or size. For browser uploads prefer
548/// [`direct_upload`], which also picks a new key, checks [`Rules`] and
549/// signs the key for [`attach_direct_upload`]. Settings, costs and errors
550/// as [`presign_get`]; the upload is one class A operation.
551///
552/// # Examples
553///
554/// ```no_run
555/// use ocre::{Ctx, Result, storage};
556///
557/// // A URL a backup script can `curl -T` to, valid one hour.
558/// fn backup_url(ctx: &Ctx, size: u64) -> Result<String> {
559/// storage::presign_put(ctx, "backups/latest.tar", "application/x-tar", size, 3600)
560/// }
561/// ```
562pub fn presign_put(ctx: &Ctx, key: &str, content_type: &str, size: u64, expires_in: u64) -> Result<String> {
563 let content_type = essence(content_type);
564 if let Some(base) = dev_base(ctx.env()) {
565 check_expires_in(expires_in)?;
566 return Ok(dev_url(&base, key, &[], expires_in));
567 }
568 let size = size.to_string();
569 let headers = [("content-type", content_type.as_str()), ("content-length", size.as_str())];
570 endpoint(ctx.env())?.presign("PUT", key, &headers, &[], crate::now(), expires_in)
571}
572
573/// Starts a direct upload: checks what the browser declares against `rules` and presigns a `PUT` of a new key under `prefix`.
574///
575/// Rails' `DirectUploadsController#create`. The browser `PUT`s the file to
576/// [`DirectUpload::url`] with [`DirectUpload::headers`] (within 10
577/// minutes), then submits [`DirectUpload::signed_key`] with its form;
578/// [`attach_direct_upload`] checks the stored object and returns its
579/// [`Attachment`]. The file never passes through the Worker: no 100 MB
580/// request limit, no Worker memory or CPU. The key is
581/// `<prefix>/<22 random characters>`; use a prefix of its own (`uploads/photos`)
582/// so [`purge_unattached`] can find abandoned uploads.
583///
584/// Settings as [`presign_get`] (none in debug builds, where the browser
585/// uploads to the app's development route); the bucket also needs a CORS
586/// rule allowing `PUT` from the app's origin (see the file storage guide).
587/// Signing costs no R2 operation; the upload is one class A operation.
588///
589/// # Errors
590///
591/// - [`Error::Invalid`](crate::Error::Invalid) (422) on `field` when the
592/// declared size or type breaks `rules`.
593/// - [`Error::Internal`](crate::Error::Internal) (500) when an `R2_*`
594/// setting is missing.
595///
596/// # Examples
597///
598/// ```no_run
599/// use axum::{Json, extract::State};
600/// use ocre::storage::{self, DirectUpload, DirectUploadRequest, Rules};
601/// use ocre::{ApiResult, Ctx};
602///
603/// const VIDEO: Rules = Rules { max_bytes: 500 * 1024 * 1024, content_types: &["video/mp4"] };
604///
605/// // POST /videos/uploads with {"filename": "a.mp4", "content_type": "video/mp4", "size": 1234}
606/// async fn start(State(ctx): State<Ctx>, Json(request): Json<DirectUploadRequest>) -> ApiResult<Json<DirectUpload>> {
607/// Ok(Json(storage::direct_upload(&ctx, "uploads/videos", "video", &request, &VIDEO)?))
608/// }
609/// ```
610pub fn direct_upload(
611 ctx: &Ctx,
612 prefix: &str,
613 field: &str,
614 request: &DirectUploadRequest,
615 rules: &Rules,
616) -> Result<DirectUpload> {
617 let env = ctx.env();
618 match dev_base(env) {
619 Some(base) => {
620 let secret = upload_secret(&|name| env.var(name).ok().map(|value| value.to_string()))?;
621 DirectUpload::sign_dev(&base, &secret, prefix, field, request, rules, DIRECT_UPLOAD_EXPIRES_IN)
622 }
623 None => {
624 DirectUpload::sign(&endpoint(env)?, prefix, field, request, rules, crate::now(), DIRECT_UPLOAD_EXPIRES_IN)
625 }
626 }
627}
628
629/// Finishes a direct upload (or a [`multipart_uploads`](crate::storage::multipart_uploads) one): checks the object behind `signed_key` against `rules` and returns its [`Attachment`].
630///
631/// Rails' `attach(signed_blob_id)`. `signed_key` must come from
632/// [`direct_upload`] (a key this app signed, so a client cannot claim
633/// another record's file); the object must exist, and its size and
634/// content type (as R2 recorded them) must pass `rules`. A refused object
635/// is deleted. `filename` is the name the form sends (cleaned up). Save
636/// the attachment with [`columns`](crate::storage::columns); if that write
637/// fails, [`delete`] the key.
638///
639/// Free plan: one R2 class B operation (`head`), plus a free delete when
640/// the object is refused.
641///
642/// # Errors
643///
644/// - [`Error::Invalid`](crate::Error::Invalid) (422) on `field`: "is not a
645/// valid upload" (bad signature), "was not uploaded" (no object), or the
646/// messages of [`Validator::file`](crate::Validator::file).
647/// - [`Error::Internal`](crate::Error::Internal) (500) when neither
648/// `R2_SECRET_ACCESS_KEY` nor `SECRET_KEY_BASE` is set (the secret that
649/// signs upload keys), the `STORAGE` binding is missing, or R2 fails.
650///
651/// # Examples
652///
653/// ```no_run
654/// use axum::{Form, extract::{Path, State}};
655/// use ocre::storage::{self, Rules};
656/// use ocre::{Ctx, IntoParam, Result};
657/// use serde::Deserialize;
658///
659/// const VIDEO: Rules = Rules { max_bytes: 500 * 1024 * 1024, content_types: &["video/mp4"] };
660///
661/// #[derive(Deserialize)]
662/// struct VideoForm {
663/// video_key: String,
664/// video_filename: String,
665/// }
666///
667/// async fn update(State(ctx): State<Ctx>, Path(id): Path<i64>, Form(form): Form<VideoForm>) -> Result<String> {
668/// let video = storage::attach_direct_upload(&ctx, "video", &form.video_key, &form.video_filename, &VIDEO).await?;
669/// let mut values = Vec::from(storage::columns(Some(&video)));
670/// values.push(id.into_param());
671/// let sql = "UPDATE lessons SET video_key = ?1, video_filename = ?2, video_content_type = ?3, video_size = ?4 \
672/// WHERE id = ?5";
673/// if let Err(err) = ctx.db()?.execute(sql, values).await {
674/// storage::delete(&ctx, &video.key).await?;
675/// return Err(err);
676/// }
677/// Ok(video.key)
678/// }
679/// ```
680pub fn attach_direct_upload(
681 ctx: &Ctx,
682 field: &str,
683 signed_key: &str,
684 filename: &str,
685 rules: &Rules,
686) -> impl Future<Output = Result<Attachment>> + Send + use<> {
687 let env = ctx.env().clone();
688 let (field, signed_key, filename, rules) = (field.to_owned(), signed_key.to_owned(), filename.to_owned(), *rules);
689 SendFuture::new(async move {
690 let key = verify_key(&field, &upload_secret(&|name| env.var(name).ok().map(|v| v.to_string()))?, &signed_key)?;
691 let bucket = bucket(&env)?;
692 let object = bucket.head(key).await?.as_ref().map(stored);
693 let attached = attachment_from_head(&field, object.as_ref(), &filename, &rules);
694 if let (Err(_), Some(refused)) = (&attached, object) {
695 bucket.delete(refused.key).await?;
696 }
697 attached
698 })
699}
700
701/// Answers `302 Found` to a presigned `GET` of the attachment (Active Storage's redirect mode).
702///
703/// For large or popular files: the browser downloads from R2 directly,
704/// so the Worker only signs a URL. The redirect may be cached privately
705/// for half of `expires_in`. Authorize before calling it, as with
706/// [`serve`]: whoever gets the URL can use it until it expires. Settings,
707/// costs and errors as [`presign_get`].
708///
709/// # Examples
710///
711/// ```no_run
712/// use axum::{extract::{Path, State}, response::Response};
713/// use ocre::storage::{self, Attachment, Disposition};
714/// use ocre::{Ctx, OptionExt, Result, params};
715///
716/// // GET /videos/{id}/file: a redirect valid one hour.
717/// async fn file(State(ctx): State<Ctx>, Path(id): Path<i64>) -> Result<Response> {
718/// let sql = "SELECT file_key AS key, file_filename AS filename, file_content_type AS content_type, \
719/// file_size AS size FROM videos WHERE id = ?1";
720/// let video: Attachment = ctx.db()?.first(sql, params![id]).await?.or_404()?;
721/// storage::serve_redirect(&ctx, &video, Disposition::Inline, 3600)
722/// }
723/// ```
724pub fn serve_redirect(
725 ctx: &Ctx,
726 attachment: &Attachment,
727 disposition: Disposition,
728 expires_in: u64,
729) -> Result<Response> {
730 Ok(redirect_response(&presign_get(ctx, attachment, disposition, expires_in)?, expires_in))
731}
732
733/// The permanent public URL of `key` in a public bucket: `<STORAGE_PUBLIC_URL>/<key>` (Active Storage's `public: true`).
734///
735/// Requires public access on the bucket (an `r2.dev` URL, rate-limited and
736/// meant for development, or a custom domain) and the
737/// [`STORAGE_PUBLIC_URL`](crate::storage::STORAGE_PUBLIC_URL) variable.
738/// Every object of the bucket is then public forever to whoever has its
739/// key, with no authorization and no expiry: use it for avatars and
740/// product images, never for private documents. Pure string building: no
741/// R2 operation; downloads are class B operations on R2's side.
742///
743/// # Errors
744///
745/// [`Error::Internal`](crate::Error::Internal) (500) when
746/// `STORAGE_PUBLIC_URL` is not set (the message says how).
747///
748/// # Examples
749///
750/// ```no_run
751/// use ocre::{Ctx, Result, storage::{self, Attachment}};
752///
753/// fn avatar_src(ctx: &Ctx, avatar: &Attachment) -> Result<String> {
754/// storage::public_url(ctx, &avatar.key) // https://files.example.com/users/avatar/2u1Vd0zJ8sQqS6rJq0rVmA
755/// }
756/// ```
757pub fn public_url(ctx: &Ctx, key: &str) -> Result<String> {
758 join_public_url(ctx.env().var(STORAGE_PUBLIC_URL).ok().map(|value| value.to_string()), key)
759}
760
761/// Deletes the objects under `prefix` older than `max_age` seconds that no `table.column` row references, one listing page per call.
762///
763/// Direct uploads that were never attached (a closed tab, a failed form)
764/// would stay in R2 forever: Rails' `ActiveStorage::Blob.unattached`
765/// purge. Each call lists one page of up to 1,000 keys from `cursor`
766/// (`None` to start), keeps those uploaded more than `max_age` seconds
767/// ago, looks them up with `SELECT <column> FROM <table> WHERE <column> IN
768/// (...)` (100 keys per query) and deletes the others in one call. Pass
769/// the returned [`Purged::cursor`] to the next call until it is `None`.
770/// `table` and `column` are identifiers from your code (letters, digits,
771/// `_`); give the column an index (`CREATE UNIQUE INDEX ... ON
772/// lessons(video_key)`) so each lookup reads only matching rows. Keep
773/// `max_age` well above 10 minutes (the lifetime of an upload URL) plus
774/// the time a form stays open: a day is safe.
775///
776/// Free plan: one R2 class A operation per call (the listing), one D1
777/// query per 100 old keys, deletes free; a few ms of CPU per 1,000 keys.
778/// Run it from a scheduled task, a few pages per run.
779///
780/// # Errors
781///
782/// [`Error::Internal`](crate::Error::Internal) (500) when `table` or
783/// `column` is not a plain identifier, the `STORAGE` or `DB` binding is
784/// missing, or R2 or D1 fails (nothing is deleted for the page then).
785///
786/// # Examples
787///
788/// ```no_run
789/// use ocre::{Ctx, Result, storage};
790///
791/// // src/schedules/purge_uploads.rs, run every day: at most 5 pages (5 class A operations).
792/// pub async fn run(ctx: &Ctx) -> Result<()> {
793/// let mut cursor = None;
794/// for _ in 0..5 {
795/// let purged = storage::purge_unattached(ctx, "uploads/videos", "lessons", "video_key", 86_400, cursor.as_deref()).await?;
796/// println!("purge_uploads: {} unattached uploads deleted", purged.deleted.len());
797/// cursor = purged.cursor;
798/// if cursor.is_none() {
799/// break;
800/// }
801/// }
802/// Ok(())
803/// }
804/// ```
805pub fn purge_unattached(
806 ctx: &Ctx,
807 prefix: &str,
808 table: &str,
809 column: &str,
810 max_age: i64,
811 cursor: Option<&str>,
812) -> impl Future<Output = Result<Purged>> + Send + use<> {
813 #[derive(serde::Deserialize)]
814 struct Row {
815 key: String,
816 }
817 let ctx = ctx.clone();
818 let (table, column) = (table.to_owned(), column.to_owned());
819 let page = list(&ctx, prefix, cursor, MAX_LIST);
820 SendFuture::new(async move {
821 referenced_keys_sql(&table, &column, 0)?;
822 let page = page.await?;
823 let mut stale = stale_keys(&page.objects, crate::now() - max_age);
824 if !stale.is_empty() {
825 let db = ctx.db()?;
826 let mut referenced = std::collections::HashSet::new();
827 for keys in stale.chunks(KEYS_PER_QUERY) {
828 let sql = referenced_keys_sql(&table, &column, keys.len())?;
829 let params = keys.iter().map(|key| key.as_str().into_param()).collect();
830 let rows: Vec<Row> = db.all(&sql, params).await?;
831 referenced.extend(rows.into_iter().map(|row| row.key));
832 }
833 stale.retain(|key| !referenced.contains(key));
834 if !stale.is_empty() {
835 bucket(ctx.env())?.delete_multiple(stale.iter().map(String::as_str).collect()).await?;
836 }
837 }
838 Ok(Purged { deleted: stale, cursor: page.cursor })
839 })
840}
841
842/// Streams a stored file to the client, with the headers a browser needs for caching, seeking and saving it.
843///
844/// The response carries `Content-Type`, `Content-Length`,
845/// `Content-Disposition` (the original file name; `inline` only for types
846/// safe to display, see [`Disposition`](crate::storage::Disposition)),
847/// `ETag` and `Cache-Control` ([`CACHE_CONTROL`](crate::storage::CACHE_CONTROL)).
848/// A matching `If-None-Match` answers `304 Not Modified` without a body; a
849/// single `Range` (video seeking, resumed downloads) answers 206 with
850/// `Content-Range`, or 416 when it lies outside the file (without calling
851/// R2). Several ranges, other units and malformed values send the whole
852/// file, as RFC 9110 allows. The headers come from `attachment`, so it must
853/// be the row saved for that key.
854///
855/// Check that the user may see the record before calling it: the route is
856/// the only protection.
857///
858/// Free plan: one R2 class B operation per call, 304s included (10M free
859/// per month). The bytes never pass through WebAssembly: the R2 stream is
860/// attached to the response and [`crate::serve`] answers with it directly,
861/// so a download costs almost no CPU whatever its size.
862///
863/// # Errors
864///
865/// - [`Error::NotFound`](crate::Error::NotFound) (404) when no object has
866/// `attachment.key`.
867/// - [`Error::Internal`](crate::Error::Internal) (500) when the `STORAGE`
868/// binding is missing (the message shows the `STORAGE` entry to add
869/// to cloudflare.config.ts) or R2 fails.
870///
871/// # Examples
872///
873/// ```no_run
874/// use axum::{extract::{Path, Query, State}, http::HeaderMap, response::Response};
875/// use ocre::storage::{self, Attachment, Disposition};
876/// use ocre::{Ctx, OptionExt, Result, params};
877/// use serde::Deserialize;
878///
879/// #[derive(Deserialize)]
880/// struct Download {
881/// #[serde(default)]
882/// download: bool,
883/// }
884///
885/// // GET /photos/{id}/image, or /photos/{id}/image?download=true for "Save as".
886/// async fn image(
887/// State(ctx): State<Ctx>,
888/// Path(id): Path<i64>,
889/// Query(query): Query<Download>,
890/// headers: HeaderMap,
891/// ) -> Result<Response> {
892/// let sql = "SELECT image_key AS key, image_filename AS filename, image_content_type AS content_type, \
893/// image_size AS size FROM photos WHERE id = ?1";
894/// let image: Attachment = ctx.db()?.first(sql, params![id]).await?.or_404()?;
895/// let disposition = if query.download { Disposition::Download } else { Disposition::Inline };
896/// storage::serve(&ctx, &image, &headers, disposition).await
897/// }
898/// ```
899pub fn serve(
900 ctx: &Ctx,
901 attachment: &Attachment,
902 headers: &HeaderMap,
903 disposition: Disposition,
904) -> impl Future<Output = Result<Response>> + Send + use<> {
905 let env = ctx.env().clone();
906 let attachment = attachment.clone();
907 let fetch = Fetch::from_headers(headers, attachment.size);
908 SendFuture::new(async move {
909 if fetch.range == ByteRange::Unsatisfiable {
910 return Ok(unsatisfiable(attachment.size));
911 }
912 let bucket = bucket(&env)?;
913 let mut get = bucket.get(&attachment.key);
914 if let Some(etag) = fetch.if_none_match {
915 get = get.only_if(Conditional { etag_does_not_match: Some(etag), ..Default::default() });
916 }
917 if let ByteRange::Partial { offset, length } = fetch.range {
918 get = get.range(Range::OffsetWithLength { offset, length });
919 }
920 let object = get.execute().await?.ok_or(Error::NotFound)?;
921 let etag = object.http_etag();
922 let Some(body) = object.body() else { return Ok(not_modified(&etag)) };
923 let mut response = file_response(&attachment, disposition, &etag, fetch.range, Body::empty());
924 match body.response_body()? {
925 // Handed to `ocre::serve`, which answers with this stream itself.
926 ResponseBody::Stream(stream) => {
927 response.extensions_mut().insert(R2Stream(SendWrapper::new(stream)));
928 }
929 ResponseBody::Body(bytes) => *response.body_mut() = Body::from(bytes),
930 ResponseBody::Empty => {}
931 }
932 Ok(response)
933 })
934}
935
936/// An R2 object body attached to a response by [`serve`]: `ocre::serve`
937/// sends it as the JavaScript response body, so the bytes never pass
938/// through WebAssembly and workerd keeps `Content-Length`.
939#[derive(Clone)]
940pub(crate) struct R2Stream(SendWrapper<web_sys::ReadableStream>);
941
942/// The JavaScript response for `response`'s status and headers, with `stream` as its body.
943pub(crate) fn into_js_response(response: Response, stream: R2Stream) -> worker::Result<web_sys::Response> {
944 let headers = web_sys::Headers::new()?;
945 for (name, value) in response.headers() {
946 headers.append(name.as_str(), value.to_str().unwrap_or_default())?;
947 }
948 let init = web_sys::ResponseInit::new();
949 init.set_status(response.status().as_u16());
950 init.set_headers(&headers);
951 Ok(web_sys::Response::new_with_opt_readable_stream_and_init(Some(&stream.0), &init)?)
952}