From 4607f4a643a2ac8a1039eb36b15009716789cee6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 01:31:57 +0300 Subject: [PATCH] =?UTF-8?q?feat(files):=20bytes=20stream=20off=20disk=20?= =?UTF-8?q?=E2=80=94=20plays=20start=20on=20the=20first=20frame,=20not=20t?= =?UTF-8?q?he=20whole=20file?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every byte serve buffered the whole file in memory first: a play waited for the full read, and a range probe re-read the file to slice it. The store now answers a clamped span as a 64 KiB-frame stream (file_stream), the row's declared size never trusted against the file on disk, and the byte routes serve it with an honest Content-Length — the signed-in route and the public link share bytes_response, so ranges answer 206 with a real span on both. Speed button: width fixed in ch at the ladder's longest label, so cycling stops moving the bar's other controls. Fullscreen: the vol/speed wiring had replaced the `var full` declaration, and the ReferenceError after the other listeners attached left the button dead — restored, verified clicking in and out. Measured on a 150 MiB file: full serve TTFB 28ms with RSS flat (previously a whole-file buffer), a 1 MiB tail range answers 206 in 30ms reading only its span, and the served bytes compare identical to disk. --- Cargo.lock | 5 + crates/in-core/Cargo.toml | 6 + crates/in-core/src/store/mod.rs | 23 ++ crates/in-core/src/store/turso_store.rs | 285 +++++++++++++++--------- crates/in-web/Cargo.toml | 5 + crates/in-web/src/files.rs | 89 +++++--- crates/in-web/src/share.rs | 29 +-- style/main.scss | 7 +- 8 files changed, 297 insertions(+), 152 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 019adbf..4cb3116 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1799,7 +1799,9 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.22.1", + "bytes", "chacha20poly1305", + "futures-core", "image", "rand 0.10.2", "serde", @@ -1810,6 +1812,7 @@ dependencies = [ "thiserror", "time", "tokio", + "tokio-util", "toml", "turso", "ulid", @@ -1821,9 +1824,11 @@ name = "in-web" version = "0.1.0" dependencies = [ "async-trait", + "bytes", "futures-util", "grass", "http", + "http-body", "http-body-util", "in-client", "in-core", diff --git a/crates/in-core/Cargo.toml b/crates/in-core/Cargo.toml index e66198e..b9401d2 100644 --- a/crates/in-core/Cargo.toml +++ b/crates/in-core/Cargo.toml @@ -13,6 +13,9 @@ description = "Domain model and storage for In" default = ["server"] server = [ "dep:async-trait", + "dep:bytes", + "dep:futures-core", + "dep:tokio-util", "dep:base64", "dep:chacha20poly1305", "dep:image", @@ -26,6 +29,9 @@ server = [ [dependencies] async-trait = { version = "0.1.92", optional = true } +bytes = { version = "1", optional = true } +futures-core = { version = "0.3", optional = true } +tokio-util = { version = "0.7", features = ["io"], optional = true } base64 = { workspace = true, optional = true } chacha20poly1305 = { workspace = true, optional = true } image = { workspace = true, optional = true } diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 860a4d2..2171347 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -142,6 +142,20 @@ pub struct File { pub deleted_at: Option, } +/// A file's bytes as chunked frames: the serving shape of +/// [`Store::file_stream`], so a response can stream off disk instead of +/// holding the whole file in memory. +pub type ByteStream = + std::pin::Pin> + Send>>; + +/// One clamped span of a file's bytes: `len` is exactly what `stream` will +/// yield — the row's declared size can drift from the file on disk, and the +/// served length must be the honest one. +pub struct FileSpan { + pub len: u64, + pub stream: ByteStream, +} + /// Whether a file's thumbnail exists. `None` for bytes no thumbnail is /// attempted for; `Pending` while one is being made; `Ready` or `Failed` /// once the attempt settled. @@ -447,6 +461,15 @@ pub trait Store: 'static + Send + Sync { /// when there is no such row, or its file went missing. async fn file_bytes(&self, id: &str) -> Result>>; + /// The bytes as a stream, for the serving routes: `len` of them starting + /// at `start`, read off disk in chunks — a serve never buffers the whole + /// file, and a range serve reads only its span. The span is clamped to + /// what the file really holds, and [`FileSpan::len`] says how much the + /// stream will yield, so a row whose size drifted from its file cannot + /// hang a response. `None` when there is no such row, or its file went + /// missing. + async fn file_stream(&self, id: &str, start: u64, len: u64) -> Result>; + /// The thumbnail's bytes, for the one handler that serves them. `None` /// when no thumbnail was made, or its file went missing. async fn thumb_bytes(&self, id: &str) -> Result>>; diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index f377c1d..661981a 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -7,8 +7,8 @@ use async_trait::async_trait; use rand::Rng; -use time::format_description::well_known::Rfc3339; use time::OffsetDateTime; +use time::format_description::well_known::Rfc3339; use turso::transaction::{Transaction, TransactionBehavior}; use turso::{Builder, Connection, Row, params}; use ulid::Ulid; @@ -35,15 +35,12 @@ const UPLOADS_DIR: &str = "uploads"; /// row wears `failed` rather than pinning memory the size of the file. const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024; -const USER_COLUMNS: &str = - "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language"; +const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language"; const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; -const FILE_COLUMNS: &str = - "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count"; +const FILE_COLUMNS: &str = "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count"; const LINK_COLUMNS: &str = "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at"; -const SESSION_COLUMNS: &str = - "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at"; +const SESSION_COLUMNS: &str = "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at"; pub struct TursoStore { /// Shared by every single-statement call. Turso serialises statements on a @@ -111,7 +108,10 @@ impl TursoStore { // is rebuilt now, while no handle of ours points at the file that the // rebuild is about to replace. Self::repair_if_stale(database, storage).await?; - let db = Builder::new_local(database).build().await.map_err(backend)?; + let db = Builder::new_local(database) + .build() + .await + .map_err(backend)?; let conn = db.connect().map_err(backend)?; // Turso is a single-writer engine. Two connections on one Database // handle serialise by themselves, but a second handle on the same file @@ -143,7 +143,9 @@ impl TursoStore { storage: storage.to_path_buf(), }; store.migrate(database).await?; - store.prune_expired_uploads(OffsetDateTime::now_utc()).await?; + store + .prune_expired_uploads(OffsetDateTime::now_utc()) + .await?; // Trash is deliberately NOT purged here: the age cutoff is the // deployment's `purge_after_days`, which this signature never sees. // The server calls `purge_expired` with its configured cutoff right @@ -171,11 +173,7 @@ impl TursoStore { async fn sweep_orphan_files(&self) -> Result<()> { let conn = self.conn.lock().await; let files = known_ids(&conn, "SELECT id FROM file").await?; - let thumbs = known_ids( - &conn, - "SELECT id FROM file WHERE thumb_state = 'ready'", - ) - .await?; + let thumbs = known_ids(&conn, "SELECT id FROM file WHERE thumb_state = 'ready'").await?; let sessions = known_ids( &conn, "SELECT id FROM upload_session WHERE state = 'active'", @@ -578,11 +576,7 @@ fn session_dir(storage: &std::path::Path, id: &str) -> std::path::PathBuf { } /// Where chunk `index` of session `id` stages. -fn chunk_path( - storage: &std::path::Path, - id: &str, - index: u64, -) -> std::path::PathBuf { +fn chunk_path(storage: &std::path::Path, id: &str, index: u64) -> std::path::PathBuf { session_dir(storage, id).join(index.to_string()) } @@ -898,7 +892,11 @@ impl Store for TursoStore { .await .map_err(backend)?; let mut back = tx.query(&sql, params![sub]).await.map_err(backend)?; - let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = back + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let user = user_from(&row)?; drop(back); tx.commit().await.map_err(backend)?; @@ -943,7 +941,11 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = back + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let user = user_from(&row)?; drop(back); tx.commit().await.map_err(backend)?; @@ -1045,7 +1047,11 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = rows + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let folder = folder_from(&row)?; drop(rows); tx.commit().await.map_err(backend)?; @@ -1074,12 +1080,20 @@ impl Store for TursoStore { } // A live sibling wearing the name is no refusal: the rename lands // on the first free `name (2)` postfix instead. - let name = - free_folder_name(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id)) - .await?; - tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id]) - .await - .map_err(backend)?; + let name = free_folder_name( + &tx, + &folder.owner_id, + folder.parent_id.as_deref(), + &name, + Some(id), + ) + .await?; + tx.execute( + "UPDATE folder SET name = ?1 WHERE id = ?2", + params![name, id], + ) + .await + .map_err(backend)?; refresh_usage(&tx, &folder.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([Topic::Library(folder.owner_id)]); @@ -1173,11 +1187,7 @@ impl Store for TursoStore { Ok(()) } - async fn list_children( - &self, - owner_id: &str, - parent_id: Option<&str>, - ) -> Result { + async fn list_children(&self, owner_id: &str, parent_id: Option<&str>) -> Result { let conn = self.conn.lock().await; let mut folders = Vec::new(); let mut files = Vec::new(); @@ -1283,9 +1293,7 @@ impl Store for TursoStore { let _ = std::fs::remove_file(thumb_path(&self.storage, &id)); } } - let stored_thumb = if thumb_bytes.is_some() - && thumb_path(&self.storage, &id).is_file() - { + let stored_thumb = if thumb_bytes.is_some() && thumb_path(&self.storage, &id).is_file() { ThumbState::Ready } else if thumb_state == ThumbState::Ready { ThumbState::Failed @@ -1325,7 +1333,11 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = rows + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let file = file_from(&row)?; drop(rows); tx.commit().await.map_err(backend)?; @@ -1354,8 +1366,14 @@ impl Store for TursoStore { } // A live sibling wearing the name is no refusal: the rename lands // on the first free `stem (2).ext` postfix instead. - let name = - free_file_name(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await?; + let name = free_file_name( + &tx, + &file.owner_id, + file.folder_id.as_deref(), + &name, + Some(id), + ) + .await?; let now = now_text()?; tx.execute( "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3", @@ -1438,6 +1456,45 @@ impl Store for TursoStore { } } + async fn file_stream(&self, id: &str, start: u64, len: u64) -> Result> { + let conn = self.conn.lock().await; + let mut rows = conn + .query("SELECT 1 FROM file WHERE id = ?1", params![id]) + .await + .map_err(backend)?; + let known = rows.next().await.map_err(backend)?.is_some(); + drop(conn); + if !known { + return Ok(None); + } + let mut file = match tokio::fs::File::open(file_path(&self.storage, id)).await { + Ok(file) => file, + // Same answer as `file_bytes`: a missing file is "nothing to + // serve", not a stack. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(StoreError::Backend(e.to_string())), + }; + // Clamp against the real file, not the row: the span served is the + // span that exists. + let on_disk = file + .metadata() + .await + .map_err(|e| StoreError::Backend(e.to_string()))? + .len(); + let len = len.min(on_disk.saturating_sub(start)); + use tokio::io::{AsyncReadExt, AsyncSeekExt}; + file.seek(std::io::SeekFrom::Start(start)) + .await + .map_err(|e| StoreError::Backend(e.to_string()))?; + // 64 KiB frames: big enough that a serve is a handful of reads, + // small enough that a canceled download leaves nothing held. + let stream = tokio_util::io::ReaderStream::with_capacity(file.take(len), 64 * 1024); + Ok(Some(super::FileSpan { + len, + stream: Box::pin(stream), + })) + } + async fn record_download(&self, id: &str) -> Result<()> { let conn = self.conn.lock().await; let mut rows = conn @@ -1485,10 +1542,7 @@ impl Store for TursoStore { async fn thumb_bytes(&self, id: &str) -> Result>> { let conn = self.conn.lock().await; let mut rows = conn - .query( - "SELECT thumb_state FROM file WHERE id = ?1", - params![id], - ) + .query("SELECT thumb_state FROM file WHERE id = ?1", params![id]) .await .map_err(backend)?; let ready = match rows.next().await.map_err(backend)? { @@ -1639,9 +1693,12 @@ impl Store for TursoStore { Some(id), ) .await?; - tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id]) - .await - .map_err(backend)?; + tx.execute( + "UPDATE folder SET name = ?1 WHERE id = ?2", + params![name, id], + ) + .await + .map_err(backend)?; refresh_usage(&tx, &folder.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([ @@ -1801,7 +1858,10 @@ impl Store for TursoStore { .map_err(backend)?; delete_file_rows( &tx, - &file_ids.iter().map(|(id, _)| id.clone()).collect::>(), + &file_ids + .iter() + .map(|(id, _)| id.clone()) + .collect::>(), ) .await?; delete_folder_rows(&tx, &folder_ids).await?; @@ -1914,7 +1974,11 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = rows + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let link = link_from(&row)?; drop(rows); drop(conn); @@ -2030,10 +2094,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([ - Topic::Shares(owner), - Topic::Shares(user_id.to_string()), - ]); + self.announce([Topic::Shares(owner), Topic::Shares(user_id.to_string())]); Ok(()) } @@ -2057,10 +2118,7 @@ impl Store for TursoStore { .await .map_err(backend)?; drop(conn); - self.announce([ - Topic::Shares(owner), - Topic::Shares(user_id.to_string()), - ]); + self.announce([Topic::Shares(owner), Topic::Shares(user_id.to_string())]); Ok(()) } @@ -2191,12 +2249,7 @@ impl Store for TursoStore { } } - async fn can_download( - &self, - kind: ShareKind, - target_id: &str, - user_id: &str, - ) -> Result { + async fn can_download(&self, kind: ShareKind, target_id: &str, user_id: &str) -> Result { // The owner always downloads. Anyone else downloads only through a // grant whose `can_download` is set — on the target or above it. A // view-only grant opens the page but not the bytes. @@ -2257,7 +2310,11 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = rows + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let session = session_from(&row)?; drop(rows); drop(conn); @@ -2276,8 +2333,7 @@ impl Store for TursoStore { async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result { let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?; - if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() - { + if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() { return Err(StoreError::UploadExpired); } let count = chunk_count(session.size_bytes); @@ -2308,7 +2364,11 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = rows + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let session = session_from(&row)?; drop(rows); drop(conn); @@ -2317,8 +2377,7 @@ impl Store for TursoStore { async fn finish_upload(&self, id: &str) -> Result { let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?; - if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() - { + if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() { return Err(StoreError::UploadExpired); } // Every chunk present, every chunk exact: the finish assembles what @@ -2350,7 +2409,8 @@ impl Store for TursoStore { total += std::io::copy(&mut chunk, &mut out) .map_err(|e| StoreError::Backend(e.to_string()))?; } - out.flush().map_err(|e| StoreError::Backend(e.to_string()))?; + out.flush() + .map_err(|e| StoreError::Backend(e.to_string()))?; drop(out); if total != session.size_bytes { let _ = std::fs::remove_file(&tmp); @@ -2366,8 +2426,7 @@ impl Store for TursoStore { })?; head.truncate(head_len.min(session.size_bytes as usize)); let mime = sniff::sniff(&head).to_string(); - let thumb_bytes = if !thumbs::thumbnailed(&mime) || session.size_bytes > THUMB_SOURCE_CAP - { + let thumb_bytes = if !thumbs::thumbnailed(&mime) || session.size_bytes > THUMB_SOURCE_CAP { None } else if thumbs::is_video_mime(&mime) { // The assembled file is already on disk: frame it in place @@ -2425,7 +2484,9 @@ impl Store for TursoStore { }; if std::fs::rename(&tmp, &dest).is_err() { let _ = std::fs::remove_file(&tmp); - return Err(StoreError::Backend("could not place the assembled file".into())); + return Err(StoreError::Backend( + "could not place the assembled file".into(), + )); } if let Some(thumb) = thumb_bytes.as_ref() { if write_file_atomic(&thumb_path(&self.storage, &file_id), thumb).is_err() { @@ -2480,7 +2541,11 @@ impl Store for TursoStore { ) .await .map_err(backend)?; - let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?; + let row = rows + .next() + .await + .map_err(backend)? + .ok_or(StoreError::NotFound)?; let file = file_from(&row)?; drop(rows); tx.commit().await.map_err(backend)?; @@ -2665,24 +2730,22 @@ async fn file_name_taken( ) -> Result { let exclude = exclude.unwrap_or(""); let mut rows = match folder_id { - Some(folder) => { - conn.query( + Some(folder) => conn + .query( "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id = ?2 \ AND name = ?3 AND deleted_at IS NULL AND id <> ?4", params![owner_id, folder, name, exclude], ) .await - .map_err(backend)? - } - None => { - conn.query( + .map_err(backend)?, + None => conn + .query( "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id IS NULL \ AND name = ?2 AND deleted_at IS NULL AND id <> ?3", params![owner_id, name, exclude], ) .await - .map_err(backend)? - } + .map_err(backend)?, }; Ok(rows.next().await.map_err(backend)?.is_some()) } @@ -2700,24 +2763,22 @@ async fn folder_name_taken( ) -> Result { let exclude = exclude.unwrap_or(""); let mut rows = match parent_id { - Some(parent) => { - conn.query( + Some(parent) => conn + .query( "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \ AND name = ?3 AND deleted_at IS NULL AND id <> ?4", params![owner_id, parent, name, exclude], ) .await - .map_err(backend)? - } - None => { - conn.query( + .map_err(backend)?, + None => conn + .query( "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \ AND name = ?2 AND deleted_at IS NULL AND id <> ?3", params![owner_id, name, exclude], ) .await - .map_err(backend)? - } + .map_err(backend)?, }; Ok(rows.next().await.map_err(backend)?.is_some()) } @@ -2864,19 +2925,20 @@ async fn row_owner( ) -> Result> { let conn = conn.lock().await; let mut rows = match kind { - ShareKind::File => { - conn.query("SELECT owner_id FROM file WHERE id = ?1", params![target_id]) - .await - .map_err(backend)? - } - ShareKind::Folder => { - conn.query( + ShareKind::File => conn + .query( + "SELECT owner_id FROM file WHERE id = ?1", + params![target_id], + ) + .await + .map_err(backend)?, + ShareKind::Folder => conn + .query( "SELECT owner_id FROM folder WHERE id = ?1", params![target_id], ) .await - .map_err(backend)? - } + .map_err(backend)?, }; match rows.next().await.map_err(backend)? { Some(row) => Ok(Some(text(&row, 0)?)), @@ -2894,22 +2956,20 @@ async fn target_owner( ) -> Result> { let conn = conn.lock().await; let mut rows = match kind { - ShareKind::File => { - conn.query( + ShareKind::File => conn + .query( "SELECT owner_id FROM file WHERE id = ?1 AND deleted_at IS NULL", params![target_id], ) .await - .map_err(backend)? - } - ShareKind::Folder => { - conn.query( + .map_err(backend)?, + ShareKind::Folder => conn + .query( "SELECT owner_id FROM folder WHERE id = ?1 AND deleted_at IS NULL", params![target_id], ) .await - .map_err(backend)? - } + .map_err(backend)?, }; match rows.next().await.map_err(backend)? { Some(row) => Ok(Some(text(&row, 0)?)), @@ -2992,7 +3052,11 @@ fn order_deepest_first(rows: &[(String, Option)]) -> Vec { /// How deep `id` sits inside `rows`: the ancestors it names that are /// themselves in the set. A row whose parent is outside the set counts depth /// only within it. -fn depth_in(id: &str, parents: &std::collections::HashMap<&str, &str>, in_set: &std::collections::HashSet<&str>) -> usize { +fn depth_in( + id: &str, + parents: &std::collections::HashMap<&str, &str>, + in_set: &std::collections::HashSet<&str>, +) -> usize { let mut depth = 0; let mut cursor = id; while let Some(parent) = parents.get(cursor) { @@ -3084,7 +3148,10 @@ mod tests { #[test] fn postfixes_split_at_the_last_dot() { assert_eq!(postfixed_file_name("report.txt", 2), "report (2).txt"); - assert_eq!(postfixed_file_name("archive.tar.gz", 2), "archive.tar (2).gz"); + assert_eq!( + postfixed_file_name("archive.tar.gz", 2), + "archive.tar (2).gz" + ); assert_eq!(postfixed_file_name("name", 2), "name (2)"); assert_eq!(postfixed_file_name("name", 3), "name (3)"); // A leading dot is the whole stem, not an extension: dotfiles keep @@ -3109,4 +3176,4 @@ mod tests { assert!(cut.ends_with(" (2)")); assert!(cut.starts_with("é")); } -} \ No newline at end of file +} diff --git a/crates/in-web/Cargo.toml b/crates/in-web/Cargo.toml index 75a0df2..e92336f 100644 --- a/crates/in-web/Cargo.toml +++ b/crates/in-web/Cargo.toml @@ -30,6 +30,11 @@ async-trait = "0.1.92" # The live stream is built with `futures_util::stream::unfold`; topcoat does # not re-export the futures traits, so this is named directly. futures-util = { version = "0.3", default-features = false } +# The byte routes build streamed bodies from `bytes::Bytes` frames; topcoat +# re-exports neither, so both are named directly. +bytes = "1" +http-body-util = "0.1" +http-body = "1" # Hashes the compiled stylesheet against the bundle's bytes at boot, so a # bundle from another generation refuses the boot instead of serving under # this binary (see `server.rs`'s `stylesheet_guard`). diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index 6aa57af..181a81a 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -69,8 +69,8 @@ fn back_to_folder( redirect_to(&location) } -fn not_found() -> (StatusCode, HeaderMap, Vec) { - (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new()) +fn not_found>>() -> (StatusCode, HeaderMap, B) { + (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new().into()) } /// Whether the browser renders this stored mime on its own rather than only @@ -204,15 +204,22 @@ async fn visible_file( /// belongs to somebody else's drive. Inline bytes are the viewer's preview: /// anyone who may see the file reads them. Taking the file away is a /// different act — `?dl=1` needs the download grant, and only it counts. +/// +/// The body streams off disk through [`bytes_response`]: a play starts on +/// the first 64 KiB frame, not on the whole file landing in memory, and a +/// range serve reads only its span. #[route(GET "/file/{id}")] -async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { +async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::router::Body)> { let id: &str = path_param::(cx); let user = match require_user(cx).await { Ok(user) => user, // A byte route has no page to carry a refusal on: back to the // front door, where the sign-in card says what to do. - Err(_) => return Ok(redirect_to("/")), + Err(_) => { + let (status, headers, body) = redirect_to("/"); + return Ok((status, headers, body.into())); + } }; let store = app(cx).store.clone(); @@ -232,9 +239,6 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> if forced && !may_download { return Ok(not_found()); } - let Ok(Some(bytes)) = store.file_bytes(id).await else { - return Ok(not_found()); - }; let inline = !forced && inline_ok(&file.mime); @@ -263,39 +267,69 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> HeaderValue::from_static("private, max-age=31536000, immutable"), ); - let total = bytes.len() as u64; let range = request_headers(cx) .get(header::RANGE) .and_then(|value| value.to_str().ok()); - match range.and_then(|range| parse_range(range, total)) { - Some(Ok((start, end))) => { - // Only a real download counts — `?dl=1` — never the viewer's - // inline bytes. A resumed download counts once, on its first - // chunk; later chunks are the same download going on. - if forced && start == 0 { + // Only a real download counts — `?dl=1` — never the viewer's inline + // bytes. A resumed download counts once, on its first chunk; later + // chunks are the same download going on. + let counts = forced + && match range.and_then(|range| parse_range(range, file.size_bytes)) { + Some(Ok((0, _))) | None => true, + _ => false, + }; + match bytes_response(store.as_ref(), id, file.size_bytes, range, headers).await { + Some((status, headers, body)) => { + if counts && status.is_success() { let _ = store.record_download(id).await; } - let slice = bytes[start as usize..=end as usize].to_vec(); - headers.insert( - header::CONTENT_RANGE, - HeaderValue::from_str(&format!("bytes {start}-{end}/{total}")).unwrap(), - ); - Ok((StatusCode::PARTIAL_CONTENT, headers, slice)) + Ok((status, headers, body)) } + None => Ok(not_found()), + } +} + +/// The streamed answer for a file's bytes: the whole file from 0, or the +/// parsed range's span — [`Store::file_stream`] clamps both against what is +/// really on disk, and the `Content-Length` (and a 206's `Content-Range`) +/// say the clamped truth. `None` when the bytes are not there. Shared by the +/// signed-in route above and the public link's `download_bytes`. +pub(crate) async fn bytes_response( + store: &dyn Store, + id: &str, + total: u64, + range: Option<&str>, + mut headers: HeaderMap, +) -> Option<(StatusCode, HeaderMap, topcoat::router::Body)> { + use futures_util::StreamExt; + use http_body::Frame; + use http_body_util::StreamBody; + use topcoat::router::Body; + let (status, start, len) = match range.and_then(|range| parse_range(range, total)) { + Some(Ok((start, end))) => (StatusCode::PARTIAL_CONTENT, start, end - start + 1), Some(Err(())) => { headers.insert( header::CONTENT_RANGE, HeaderValue::from_str(&format!("bytes */{total}")).unwrap(), ); - Ok((StatusCode::RANGE_NOT_SATISFIABLE, headers, Vec::new())) - } - None => { - if forced { - let _ = store.record_download(id).await; - } - Ok((StatusCode::OK, headers, bytes)) + return Some((StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty())); } + None => (StatusCode::OK, 0, total), + }; + let span = store.file_stream(id, start, len).await.ok().flatten()?; + if status == StatusCode::PARTIAL_CONTENT { + let end = start + span.len.saturating_sub(1); + headers.insert( + header::CONTENT_RANGE, + HeaderValue::from_str(&format!("bytes {start}-{end}/{total}")).unwrap(), + ); } + headers.insert( + header::CONTENT_LENGTH, + HeaderValue::from_str(&span.len.to_string()).unwrap(), + ); + let frames = span.stream.map(|chunk| chunk.map(Frame::data)); + Some((status, headers, Body::new(StreamBody::new(frames)))) } /// Serves one file's webp thumbnail under the same visibility as the file @@ -597,6 +631,7 @@ async fn media_player_script(cx: &Cx) -> Result { var volBtn = player.querySelector('.media-vol'); \ var volSlider = player.querySelector('.media-vol-slider'); \ var speed = player.querySelector('.media-speed'); \ + var full = player.querySelector('.media-full'); \ function clock(s) { \ if (!isFinite(s)) { return '0:00'; } \ var m = Math.floor(s / 60); \ diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index edfb6eb..586fa9f 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -25,9 +25,7 @@ use topcoat::context::Cx; use topcoat::router::content::Form; use topcoat::router::request::{headers as request_headers, uri}; use topcoat::router::response::IntoResponse; -use topcoat::router::{ - HeaderName, StatusCode, header, page, path_param, query_params, route, -}; +use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route}; use topcoat::view::view; use crate::files::entry_chip; @@ -459,6 +457,7 @@ async fn shared_link(cx: &Cx) -> topcoat::Result topcoat::Result topcoat::Result