forge
Explore
Log in

Don't you dare go Hollow

Bytes stream off disk — plays start on the first frame, not the whole file

Browse files at this commit

4607f4a643a2ac8a1039eb36b15009716789cee6Ahmet Kaan GümüşParent: f00f8a3
  • feat
    • bytes stream off disk — plays start on the first frame, not the whole file
Show full message
feat(files): bytes stream off disk — plays start on the first frame, not the whole file

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.lockmodified+5 -0
@@ -1799,7 +1799,9 @@ version = "0.1.0"
1799 dependencies = [1799 dependencies = [
1800 "async-trait",1800 "async-trait",
1801 "base64 0.22.1",1801 "base64 0.22.1",
1802+ "bytes",
1802 "chacha20poly1305",1803 "chacha20poly1305",
1804+ "futures-core",
1803 "image",1805 "image",
1804 "rand 0.10.2",1806 "rand 0.10.2",
1805 "serde",1807 "serde",
@@ -1810,6 +1812,7 @@ dependencies = [
1810 "thiserror",1812 "thiserror",
1811 "time",1813 "time",
1812 "tokio",1814 "tokio",
1815+ "tokio-util",
1813 "toml",1816 "toml",
1814 "turso",1817 "turso",
1815 "ulid",1818 "ulid",
@@ -1821,9 +1824,11 @@ name = "in-web"
1821 version = "0.1.0"1824 version = "0.1.0"
1822 dependencies = [1825 dependencies = [
1823 "async-trait",1826 "async-trait",
1827+ "bytes",
1824 "futures-util",1828 "futures-util",
1825 "grass",1829 "grass",
1826 "http",1830 "http",
1831+ "http-body",
1827 "http-body-util",1832 "http-body-util",
1828 "in-client",1833 "in-client",
1829 "in-core",1834 "in-core",
crates/in-core/Cargo.tomlmodified+6 -0
@@ -13,6 +13,9 @@ description = "Domain model and storage for In"
13 default = ["server"]13 default = ["server"]
14 server = [14 server = [
15 "dep:async-trait",15 "dep:async-trait",
16+ "dep:bytes",
17+ "dep:futures-core",
18+ "dep:tokio-util",
16 "dep:base64",19 "dep:base64",
17 "dep:chacha20poly1305",20 "dep:chacha20poly1305",
18 "dep:image",21 "dep:image",
@@ -26,6 +29,9 @@ server = [
26 29
27 [dependencies]30 [dependencies]
28 async-trait = { version = "0.1.92", optional = true }31 async-trait = { version = "0.1.92", optional = true }
32+bytes = { version = "1", optional = true }
33+futures-core = { version = "0.3", optional = true }
34+tokio-util = { version = "0.7", features = ["io"], optional = true }
29 base64 = { workspace = true, optional = true }35 base64 = { workspace = true, optional = true }
30 chacha20poly1305 = { workspace = true, optional = true }36 chacha20poly1305 = { workspace = true, optional = true }
31 image = { workspace = true, optional = true }37 image = { workspace = true, optional = true }
crates/in-core/src/store/mod.rsmodified+23 -0
@@ -142,6 +142,20 @@ pub struct File {
142 pub deleted_at: Option<OffsetDateTime>,142 pub deleted_at: Option<OffsetDateTime>,
143 }143 }
144 144
145+/// A file's bytes as chunked frames: the serving shape of
146+/// [`Store::file_stream`], so a response can stream off disk instead of
147+/// holding the whole file in memory.
148+pub type ByteStream =
149+ std::pin::Pin<Box<dyn futures_core::Stream<Item = std::io::Result<bytes::Bytes>> + Send>>;
150+
151+/// One clamped span of a file's bytes: `len` is exactly what `stream` will
152+/// yield — the row's declared size can drift from the file on disk, and the
153+/// served length must be the honest one.
154+pub struct FileSpan {
155+ pub len: u64,
156+ pub stream: ByteStream,
157+}
158+
145 /// Whether a file's thumbnail exists. `None` for bytes no thumbnail is159 /// Whether a file's thumbnail exists. `None` for bytes no thumbnail is
146 /// attempted for; `Pending` while one is being made; `Ready` or `Failed`160 /// attempted for; `Pending` while one is being made; `Ready` or `Failed`
147 /// once the attempt settled.161 /// once the attempt settled.
@@ -447,6 +461,15 @@ pub trait Store: 'static + Send + Sync {
447 /// when there is no such row, or its file went missing.461 /// when there is no such row, or its file went missing.
448 async fn file_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;462 async fn file_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;
449 463
464+ /// The bytes as a stream, for the serving routes: `len` of them starting
465+ /// at `start`, read off disk in chunks — a serve never buffers the whole
466+ /// file, and a range serve reads only its span. The span is clamped to
467+ /// what the file really holds, and [`FileSpan::len`] says how much the
468+ /// stream will yield, so a row whose size drifted from its file cannot
469+ /// hang a response. `None` when there is no such row, or its file went
470+ /// missing.
471+ async fn file_stream(&self, id: &str, start: u64, len: u64) -> Result<Option<FileSpan>>;
472+
450 /// The thumbnail's bytes, for the one handler that serves them. `None`473 /// The thumbnail's bytes, for the one handler that serves them. `None`
451 /// when no thumbnail was made, or its file went missing.474 /// when no thumbnail was made, or its file went missing.
452 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;475 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>>;
crates/in-core/src/store/turso_store.rsmodified+176 -109
@@ -7,8 +7,8 @@
7 7
8 use async_trait::async_trait;8 use async_trait::async_trait;
9 use rand::Rng;9 use rand::Rng;
10-use time::format_description::well_known::Rfc3339;
11 use time::OffsetDateTime;10 use time::OffsetDateTime;
11+use time::format_description::well_known::Rfc3339;
12 use turso::transaction::{Transaction, TransactionBehavior};12 use turso::transaction::{Transaction, TransactionBehavior};
13 use turso::{Builder, Connection, Row, params};13 use turso::{Builder, Connection, Row, params};
14 use ulid::Ulid;14 use ulid::Ulid;
@@ -35,15 +35,12 @@ const UPLOADS_DIR: &str = "uploads";
35 /// row wears `failed` rather than pinning memory the size of the file.35 /// row wears `failed` rather than pinning memory the size of the file.
36 const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024;36 const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024;
37 37
38-const USER_COLUMNS: &str =38+const USER_COLUMNS: &str = "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language";
39- "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at, theme, language";
40 const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at";39 const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at";
41-const FILE_COLUMNS: &str =40+const FILE_COLUMNS: &str = "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count";
42- "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at, download_count";
43 const LINK_COLUMNS: &str =41 const LINK_COLUMNS: &str =
44 "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at";42 "id, token_hash, kind, target_id, created_by, can_download, created_at, expires_at, revoked_at";
45-const SESSION_COLUMNS: &str =43+const SESSION_COLUMNS: &str = "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at";
46- "id, owner_id, folder_id, name, size_bytes, chunk_size, received_bytes, state, created_at, expires_at";
47 44
48 pub struct TursoStore {45 pub struct TursoStore {
49 /// Shared by every single-statement call. Turso serialises statements on a46 /// Shared by every single-statement call. Turso serialises statements on a
@@ -111,7 +108,10 @@ impl TursoStore {
111 // is rebuilt now, while no handle of ours points at the file that the108 // is rebuilt now, while no handle of ours points at the file that the
112 // rebuild is about to replace.109 // rebuild is about to replace.
113 Self::repair_if_stale(database, storage).await?;110 Self::repair_if_stale(database, storage).await?;
114- let db = Builder::new_local(database).build().await.map_err(backend)?;111+ let db = Builder::new_local(database)
112+ .build()
113+ .await
114+ .map_err(backend)?;
115 let conn = db.connect().map_err(backend)?;115 let conn = db.connect().map_err(backend)?;
116 // Turso is a single-writer engine. Two connections on one Database116 // Turso is a single-writer engine. Two connections on one Database
117 // handle serialise by themselves, but a second handle on the same file117 // handle serialise by themselves, but a second handle on the same file
@@ -143,7 +143,9 @@ impl TursoStore {
143 storage: storage.to_path_buf(),143 storage: storage.to_path_buf(),
144 };144 };
145 store.migrate(database).await?;145 store.migrate(database).await?;
146- store.prune_expired_uploads(OffsetDateTime::now_utc()).await?;146+ store
147+ .prune_expired_uploads(OffsetDateTime::now_utc())
148+ .await?;
147 // Trash is deliberately NOT purged here: the age cutoff is the149 // Trash is deliberately NOT purged here: the age cutoff is the
148 // deployment's `purge_after_days`, which this signature never sees.150 // deployment's `purge_after_days`, which this signature never sees.
149 // The server calls `purge_expired` with its configured cutoff right151 // The server calls `purge_expired` with its configured cutoff right
@@ -171,11 +173,7 @@ impl TursoStore {
171 async fn sweep_orphan_files(&self) -> Result<()> {173 async fn sweep_orphan_files(&self) -> Result<()> {
172 let conn = self.conn.lock().await;174 let conn = self.conn.lock().await;
173 let files = known_ids(&conn, "SELECT id FROM file").await?;175 let files = known_ids(&conn, "SELECT id FROM file").await?;
174- let thumbs = known_ids(176+ let thumbs = known_ids(&conn, "SELECT id FROM file WHERE thumb_state = 'ready'").await?;
175- &conn,
176- "SELECT id FROM file WHERE thumb_state = 'ready'",
177- )
178- .await?;
179 let sessions = known_ids(177 let sessions = known_ids(
180 &conn,178 &conn,
181 "SELECT id FROM upload_session WHERE state = 'active'",179 "SELECT id FROM upload_session WHERE state = 'active'",
@@ -578,11 +576,7 @@ fn session_dir(storage: &std::path::Path, id: &str) -> std::path::PathBuf {
578 }576 }
579 577
580 /// Where chunk `index` of session `id` stages.578 /// Where chunk `index` of session `id` stages.
581-fn chunk_path(579+fn chunk_path(storage: &std::path::Path, id: &str, index: u64) -> std::path::PathBuf {
582- storage: &std::path::Path,
583- id: &str,
584- index: u64,
585-) -> std::path::PathBuf {
586 session_dir(storage, id).join(index.to_string())580 session_dir(storage, id).join(index.to_string())
587 }581 }
588 582
@@ -898,7 +892,11 @@ impl Store for TursoStore {
898 .await892 .await
899 .map_err(backend)?;893 .map_err(backend)?;
900 let mut back = tx.query(&sql, params![sub]).await.map_err(backend)?;894 let mut back = tx.query(&sql, params![sub]).await.map_err(backend)?;
901- let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;895+ let row = back
896+ .next()
897+ .await
898+ .map_err(backend)?
899+ .ok_or(StoreError::NotFound)?;
902 let user = user_from(&row)?;900 let user = user_from(&row)?;
903 drop(back);901 drop(back);
904 tx.commit().await.map_err(backend)?;902 tx.commit().await.map_err(backend)?;
@@ -943,7 +941,11 @@ impl Store for TursoStore {
943 )941 )
944 .await942 .await
945 .map_err(backend)?;943 .map_err(backend)?;
946- let row = back.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;944+ let row = back
945+ .next()
946+ .await
947+ .map_err(backend)?
948+ .ok_or(StoreError::NotFound)?;
947 let user = user_from(&row)?;949 let user = user_from(&row)?;
948 drop(back);950 drop(back);
949 tx.commit().await.map_err(backend)?;951 tx.commit().await.map_err(backend)?;
@@ -1045,7 +1047,11 @@ impl Store for TursoStore {
1045 )1047 )
1046 .await1048 .await
1047 .map_err(backend)?;1049 .map_err(backend)?;
1048- let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;1050+ let row = rows
1051+ .next()
1052+ .await
1053+ .map_err(backend)?
1054+ .ok_or(StoreError::NotFound)?;
1049 let folder = folder_from(&row)?;1055 let folder = folder_from(&row)?;
1050 drop(rows);1056 drop(rows);
1051 tx.commit().await.map_err(backend)?;1057 tx.commit().await.map_err(backend)?;
@@ -1074,12 +1080,20 @@ impl Store for TursoStore {
1074 }1080 }
1075 // A live sibling wearing the name is no refusal: the rename lands1081 // A live sibling wearing the name is no refusal: the rename lands
1076 // on the first free `name (2)` postfix instead.1082 // on the first free `name (2)` postfix instead.
1077- let name =1083+ let name = free_folder_name(
1078- free_folder_name(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id))1084+ &tx,
1079- .await?;1085+ &folder.owner_id,
1080- tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])1086+ folder.parent_id.as_deref(),
1081- .await1087+ &name,
1082- .map_err(backend)?;1088+ Some(id),
1089+ )
1090+ .await?;
1091+ tx.execute(
1092+ "UPDATE folder SET name = ?1 WHERE id = ?2",
1093+ params![name, id],
1094+ )
1095+ .await
1096+ .map_err(backend)?;
1083 refresh_usage(&tx, &folder.owner_id).await?;1097 refresh_usage(&tx, &folder.owner_id).await?;
1084 tx.commit().await.map_err(backend)?;1098 tx.commit().await.map_err(backend)?;
1085 self.announce([Topic::Library(folder.owner_id)]);1099 self.announce([Topic::Library(folder.owner_id)]);
@@ -1173,11 +1187,7 @@ impl Store for TursoStore {
1173 Ok(())1187 Ok(())
1174 }1188 }
1175 1189
1176- async fn list_children(1190+ async fn list_children(&self, owner_id: &str, parent_id: Option<&str>) -> Result<Listing> {
1177- &self,
1178- owner_id: &str,
1179- parent_id: Option<&str>,
1180- ) -> Result<Listing> {
1181 let conn = self.conn.lock().await;1191 let conn = self.conn.lock().await;
1182 let mut folders = Vec::new();1192 let mut folders = Vec::new();
1183 let mut files = Vec::new();1193 let mut files = Vec::new();
@@ -1283,9 +1293,7 @@ impl Store for TursoStore {
1283 let _ = std::fs::remove_file(thumb_path(&self.storage, &id));1293 let _ = std::fs::remove_file(thumb_path(&self.storage, &id));
1284 }1294 }
1285 }1295 }
1286- let stored_thumb = if thumb_bytes.is_some()1296+ let stored_thumb = if thumb_bytes.is_some() && thumb_path(&self.storage, &id).is_file() {
1287- && thumb_path(&self.storage, &id).is_file()
1288- {
1289 ThumbState::Ready1297 ThumbState::Ready
1290 } else if thumb_state == ThumbState::Ready {1298 } else if thumb_state == ThumbState::Ready {
1291 ThumbState::Failed1299 ThumbState::Failed
@@ -1325,7 +1333,11 @@ impl Store for TursoStore {
1325 )1333 )
1326 .await1334 .await
1327 .map_err(backend)?;1335 .map_err(backend)?;
1328- let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;1336+ let row = rows
1337+ .next()
1338+ .await
1339+ .map_err(backend)?
1340+ .ok_or(StoreError::NotFound)?;
1329 let file = file_from(&row)?;1341 let file = file_from(&row)?;
1330 drop(rows);1342 drop(rows);
1331 tx.commit().await.map_err(backend)?;1343 tx.commit().await.map_err(backend)?;
@@ -1354,8 +1366,14 @@ impl Store for TursoStore {
1354 }1366 }
1355 // A live sibling wearing the name is no refusal: the rename lands1367 // A live sibling wearing the name is no refusal: the rename lands
1356 // on the first free `stem (2).ext` postfix instead.1368 // on the first free `stem (2).ext` postfix instead.
1357- let name =1369+ let name = free_file_name(
1358- free_file_name(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await?;1370+ &tx,
1371+ &file.owner_id,
1372+ file.folder_id.as_deref(),
1373+ &name,
1374+ Some(id),
1375+ )
1376+ .await?;
1359 let now = now_text()?;1377 let now = now_text()?;
1360 tx.execute(1378 tx.execute(
1361 "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3",1379 "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3",
@@ -1438,6 +1456,45 @@ impl Store for TursoStore {
1438 }1456 }
1439 }1457 }
1440 1458
1459+ async fn file_stream(&self, id: &str, start: u64, len: u64) -> Result<Option<super::FileSpan>> {
1460+ let conn = self.conn.lock().await;
1461+ let mut rows = conn
1462+ .query("SELECT 1 FROM file WHERE id = ?1", params![id])
1463+ .await
1464+ .map_err(backend)?;
1465+ let known = rows.next().await.map_err(backend)?.is_some();
1466+ drop(conn);
1467+ if !known {
1468+ return Ok(None);
1469+ }
1470+ let mut file = match tokio::fs::File::open(file_path(&self.storage, id)).await {
1471+ Ok(file) => file,
1472+ // Same answer as `file_bytes`: a missing file is "nothing to
1473+ // serve", not a stack.
1474+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1475+ Err(e) => return Err(StoreError::Backend(e.to_string())),
1476+ };
1477+ // Clamp against the real file, not the row: the span served is the
1478+ // span that exists.
1479+ let on_disk = file
1480+ .metadata()
1481+ .await
1482+ .map_err(|e| StoreError::Backend(e.to_string()))?
1483+ .len();
1484+ let len = len.min(on_disk.saturating_sub(start));
1485+ use tokio::io::{AsyncReadExt, AsyncSeekExt};
1486+ file.seek(std::io::SeekFrom::Start(start))
1487+ .await
1488+ .map_err(|e| StoreError::Backend(e.to_string()))?;
1489+ // 64 KiB frames: big enough that a serve is a handful of reads,
1490+ // small enough that a canceled download leaves nothing held.
1491+ let stream = tokio_util::io::ReaderStream::with_capacity(file.take(len), 64 * 1024);
1492+ Ok(Some(super::FileSpan {
1493+ len,
1494+ stream: Box::pin(stream),
1495+ }))
1496+ }
1497+
1441 async fn record_download(&self, id: &str) -> Result<()> {1498 async fn record_download(&self, id: &str) -> Result<()> {
1442 let conn = self.conn.lock().await;1499 let conn = self.conn.lock().await;
1443 let mut rows = conn1500 let mut rows = conn
@@ -1485,10 +1542,7 @@ impl Store for TursoStore {
1485 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {1542 async fn thumb_bytes(&self, id: &str) -> Result<Option<Vec<u8>>> {
1486 let conn = self.conn.lock().await;1543 let conn = self.conn.lock().await;
1487 let mut rows = conn1544 let mut rows = conn
1488- .query(1545+ .query("SELECT thumb_state FROM file WHERE id = ?1", params![id])
1489- "SELECT thumb_state FROM file WHERE id = ?1",
1490- params![id],
1491- )
1492 .await1546 .await
1493 .map_err(backend)?;1547 .map_err(backend)?;
1494 let ready = match rows.next().await.map_err(backend)? {1548 let ready = match rows.next().await.map_err(backend)? {
@@ -1639,9 +1693,12 @@ impl Store for TursoStore {
1639 Some(id),1693 Some(id),
1640 )1694 )
1641 .await?;1695 .await?;
1642- tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])1696+ tx.execute(
1643- .await1697+ "UPDATE folder SET name = ?1 WHERE id = ?2",
1644- .map_err(backend)?;1698+ params![name, id],
1699+ )
1700+ .await
1701+ .map_err(backend)?;
1645 refresh_usage(&tx, &folder.owner_id).await?;1702 refresh_usage(&tx, &folder.owner_id).await?;
1646 tx.commit().await.map_err(backend)?;1703 tx.commit().await.map_err(backend)?;
1647 self.announce([1704 self.announce([
@@ -1801,7 +1858,10 @@ impl Store for TursoStore {
1801 .map_err(backend)?;1858 .map_err(backend)?;
1802 delete_file_rows(1859 delete_file_rows(
1803 &tx,1860 &tx,
1804- &file_ids.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>(),1861+ &file_ids
1862+ .iter()
1863+ .map(|(id, _)| id.clone())
1864+ .collect::<Vec<_>>(),
1805 )1865 )
1806 .await?;1866 .await?;
1807 delete_folder_rows(&tx, &folder_ids).await?;1867 delete_folder_rows(&tx, &folder_ids).await?;
@@ -1914,7 +1974,11 @@ impl Store for TursoStore {
1914 )1974 )
1915 .await1975 .await
1916 .map_err(backend)?;1976 .map_err(backend)?;
1917- let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;1977+ let row = rows
1978+ .next()
1979+ .await
1980+ .map_err(backend)?
1981+ .ok_or(StoreError::NotFound)?;
1918 let link = link_from(&row)?;1982 let link = link_from(&row)?;
1919 drop(rows);1983 drop(rows);
1920 drop(conn);1984 drop(conn);
@@ -2030,10 +2094,7 @@ impl Store for TursoStore {
2030 .await2094 .await
2031 .map_err(backend)?;2095 .map_err(backend)?;
2032 drop(conn);2096 drop(conn);
2033- self.announce([2097+ self.announce([Topic::Shares(owner), Topic::Shares(user_id.to_string())]);
2034- Topic::Shares(owner),
2035- Topic::Shares(user_id.to_string()),
2036- ]);
2037 Ok(())2098 Ok(())
2038 }2099 }
2039 2100
@@ -2057,10 +2118,7 @@ impl Store for TursoStore {
2057 .await2118 .await
2058 .map_err(backend)?;2119 .map_err(backend)?;
2059 drop(conn);2120 drop(conn);
2060- self.announce([2121+ self.announce([Topic::Shares(owner), Topic::Shares(user_id.to_string())]);
2061- Topic::Shares(owner),
2062- Topic::Shares(user_id.to_string()),
2063- ]);
2064 Ok(())2122 Ok(())
2065 }2123 }
2066 2124
@@ -2191,12 +2249,7 @@ impl Store for TursoStore {
2191 }2249 }
2192 }2250 }
2193 2251
2194- async fn can_download(2252+ async fn can_download(&self, kind: ShareKind, target_id: &str, user_id: &str) -> Result<bool> {
2195- &self,
2196- kind: ShareKind,
2197- target_id: &str,
2198- user_id: &str,
2199- ) -> Result<bool> {
2200 // The owner always downloads. Anyone else downloads only through a2253 // The owner always downloads. Anyone else downloads only through a
2201 // grant whose `can_download` is set — on the target or above it. A2254 // grant whose `can_download` is set — on the target or above it. A
2202 // view-only grant opens the page but not the bytes.2255 // view-only grant opens the page but not the bytes.
@@ -2257,7 +2310,11 @@ impl Store for TursoStore {
2257 )2310 )
2258 .await2311 .await
2259 .map_err(backend)?;2312 .map_err(backend)?;
2260- let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;2313+ let row = rows
2314+ .next()
2315+ .await
2316+ .map_err(backend)?
2317+ .ok_or(StoreError::NotFound)?;
2261 let session = session_from(&row)?;2318 let session = session_from(&row)?;
2262 drop(rows);2319 drop(rows);
2263 drop(conn);2320 drop(conn);
@@ -2276,8 +2333,7 @@ impl Store for TursoStore {
2276 2333
2277 async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result<UploadSession> {2334 async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result<UploadSession> {
2278 let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?;2335 let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?;
2279- if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc()2336+ if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() {
2280- {
2281 return Err(StoreError::UploadExpired);2337 return Err(StoreError::UploadExpired);
2282 }2338 }
2283 let count = chunk_count(session.size_bytes);2339 let count = chunk_count(session.size_bytes);
@@ -2308,7 +2364,11 @@ impl Store for TursoStore {
2308 )2364 )
2309 .await2365 .await
2310 .map_err(backend)?;2366 .map_err(backend)?;
2311- let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;2367+ let row = rows
2368+ .next()
2369+ .await
2370+ .map_err(backend)?
2371+ .ok_or(StoreError::NotFound)?;
2312 let session = session_from(&row)?;2372 let session = session_from(&row)?;
2313 drop(rows);2373 drop(rows);
2314 drop(conn);2374 drop(conn);
@@ -2317,8 +2377,7 @@ impl Store for TursoStore {
2317 2377
2318 async fn finish_upload(&self, id: &str) -> Result<File> {2378 async fn finish_upload(&self, id: &str) -> Result<File> {
2319 let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?;2379 let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?;
2320- if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc()2380+ if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() {
2321- {
2322 return Err(StoreError::UploadExpired);2381 return Err(StoreError::UploadExpired);
2323 }2382 }
2324 // Every chunk present, every chunk exact: the finish assembles what2383 // Every chunk present, every chunk exact: the finish assembles what
@@ -2350,7 +2409,8 @@ impl Store for TursoStore {
2350 total += std::io::copy(&mut chunk, &mut out)2409 total += std::io::copy(&mut chunk, &mut out)
2351 .map_err(|e| StoreError::Backend(e.to_string()))?;2410 .map_err(|e| StoreError::Backend(e.to_string()))?;
2352 }2411 }
2353- out.flush().map_err(|e| StoreError::Backend(e.to_string()))?;2412+ out.flush()
2413+ .map_err(|e| StoreError::Backend(e.to_string()))?;
2354 drop(out);2414 drop(out);
2355 if total != session.size_bytes {2415 if total != session.size_bytes {
2356 let _ = std::fs::remove_file(&tmp);2416 let _ = std::fs::remove_file(&tmp);
@@ -2366,8 +2426,7 @@ impl Store for TursoStore {
2366 })?;2426 })?;
2367 head.truncate(head_len.min(session.size_bytes as usize));2427 head.truncate(head_len.min(session.size_bytes as usize));
2368 let mime = sniff::sniff(&head).to_string();2428 let mime = sniff::sniff(&head).to_string();
2369- let thumb_bytes = if !thumbs::thumbnailed(&mime) || session.size_bytes > THUMB_SOURCE_CAP2429+ let thumb_bytes = if !thumbs::thumbnailed(&mime) || session.size_bytes > THUMB_SOURCE_CAP {
2370- {
2371 None2430 None
2372 } else if thumbs::is_video_mime(&mime) {2431 } else if thumbs::is_video_mime(&mime) {
2373 // The assembled file is already on disk: frame it in place2432 // The assembled file is already on disk: frame it in place
@@ -2425,7 +2484,9 @@ impl Store for TursoStore {
2425 };2484 };
2426 if std::fs::rename(&tmp, &dest).is_err() {2485 if std::fs::rename(&tmp, &dest).is_err() {
2427 let _ = std::fs::remove_file(&tmp);2486 let _ = std::fs::remove_file(&tmp);
2428- return Err(StoreError::Backend("could not place the assembled file".into()));2487+ return Err(StoreError::Backend(
2488+ "could not place the assembled file".into(),
2489+ ));
2429 }2490 }
2430 if let Some(thumb) = thumb_bytes.as_ref() {2491 if let Some(thumb) = thumb_bytes.as_ref() {
2431 if write_file_atomic(&thumb_path(&self.storage, &file_id), thumb).is_err() {2492 if write_file_atomic(&thumb_path(&self.storage, &file_id), thumb).is_err() {
@@ -2480,7 +2541,11 @@ impl Store for TursoStore {
2480 )2541 )
2481 .await2542 .await
2482 .map_err(backend)?;2543 .map_err(backend)?;
2483- let row = rows.next().await.map_err(backend)?.ok_or(StoreError::NotFound)?;2544+ let row = rows
2545+ .next()
2546+ .await
2547+ .map_err(backend)?
2548+ .ok_or(StoreError::NotFound)?;
2484 let file = file_from(&row)?;2549 let file = file_from(&row)?;
2485 drop(rows);2550 drop(rows);
2486 tx.commit().await.map_err(backend)?;2551 tx.commit().await.map_err(backend)?;
@@ -2665,24 +2730,22 @@ async fn file_name_taken(
2665 ) -> Result<bool> {2730 ) -> Result<bool> {
2666 let exclude = exclude.unwrap_or("");2731 let exclude = exclude.unwrap_or("");
2667 let mut rows = match folder_id {2732 let mut rows = match folder_id {
2668- Some(folder) => {2733+ Some(folder) => conn
2669- conn.query(2734+ .query(
2670 "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id = ?2 \2735 "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id = ?2 \
2671 AND name = ?3 AND deleted_at IS NULL AND id <> ?4",2736 AND name = ?3 AND deleted_at IS NULL AND id <> ?4",
2672 params![owner_id, folder, name, exclude],2737 params![owner_id, folder, name, exclude],
2673 )2738 )
2674 .await2739 .await
2675- .map_err(backend)?2740+ .map_err(backend)?,
2676- }2741+ None => conn
2677- None => {2742+ .query(
2678- conn.query(
2679 "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id IS NULL \2743 "SELECT 1 FROM file WHERE owner_id = ?1 AND folder_id IS NULL \
2680 AND name = ?2 AND deleted_at IS NULL AND id <> ?3",2744 AND name = ?2 AND deleted_at IS NULL AND id <> ?3",
2681 params![owner_id, name, exclude],2745 params![owner_id, name, exclude],
2682 )2746 )
2683 .await2747 .await
2684- .map_err(backend)?2748+ .map_err(backend)?,
2685- }
2686 };2749 };
2687 Ok(rows.next().await.map_err(backend)?.is_some())2750 Ok(rows.next().await.map_err(backend)?.is_some())
2688 }2751 }
@@ -2700,24 +2763,22 @@ async fn folder_name_taken(
2700 ) -> Result<bool> {2763 ) -> Result<bool> {
2701 let exclude = exclude.unwrap_or("");2764 let exclude = exclude.unwrap_or("");
2702 let mut rows = match parent_id {2765 let mut rows = match parent_id {
2703- Some(parent) => {2766+ Some(parent) => conn
2704- conn.query(2767+ .query(
2705 "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \2768 "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \
2706 AND name = ?3 AND deleted_at IS NULL AND id <> ?4",2769 AND name = ?3 AND deleted_at IS NULL AND id <> ?4",
2707 params![owner_id, parent, name, exclude],2770 params![owner_id, parent, name, exclude],
2708 )2771 )
2709 .await2772 .await
2710- .map_err(backend)?2773+ .map_err(backend)?,
2711- }2774+ None => conn
2712- None => {2775+ .query(
2713- conn.query(
2714 "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \2776 "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \
2715 AND name = ?2 AND deleted_at IS NULL AND id <> ?3",2777 AND name = ?2 AND deleted_at IS NULL AND id <> ?3",
2716 params![owner_id, name, exclude],2778 params![owner_id, name, exclude],
2717 )2779 )
2718 .await2780 .await
2719- .map_err(backend)?2781+ .map_err(backend)?,
2720- }
2721 };2782 };
2722 Ok(rows.next().await.map_err(backend)?.is_some())2783 Ok(rows.next().await.map_err(backend)?.is_some())
2723 }2784 }
@@ -2864,19 +2925,20 @@ async fn row_owner(
2864 ) -> Result<Option<String>> {2925 ) -> Result<Option<String>> {
2865 let conn = conn.lock().await;2926 let conn = conn.lock().await;
2866 let mut rows = match kind {2927 let mut rows = match kind {
2867- ShareKind::File => {2928+ ShareKind::File => conn
2868- conn.query("SELECT owner_id FROM file WHERE id = ?1", params![target_id])2929+ .query(
2869- .await2930+ "SELECT owner_id FROM file WHERE id = ?1",
2870- .map_err(backend)?2931+ params![target_id],
2871- }2932+ )
2872- ShareKind::Folder => {2933+ .await
2873- conn.query(2934+ .map_err(backend)?,
2935+ ShareKind::Folder => conn
2936+ .query(
2874 "SELECT owner_id FROM folder WHERE id = ?1",2937 "SELECT owner_id FROM folder WHERE id = ?1",
2875 params![target_id],2938 params![target_id],
2876 )2939 )
2877 .await2940 .await
2878- .map_err(backend)?2941+ .map_err(backend)?,
2879- }
2880 };2942 };
2881 match rows.next().await.map_err(backend)? {2943 match rows.next().await.map_err(backend)? {
2882 Some(row) => Ok(Some(text(&row, 0)?)),2944 Some(row) => Ok(Some(text(&row, 0)?)),
@@ -2894,22 +2956,20 @@ async fn target_owner(
2894 ) -> Result<Option<String>> {2956 ) -> Result<Option<String>> {
2895 let conn = conn.lock().await;2957 let conn = conn.lock().await;
2896 let mut rows = match kind {2958 let mut rows = match kind {
2897- ShareKind::File => {2959+ ShareKind::File => conn
2898- conn.query(2960+ .query(
2899 "SELECT owner_id FROM file WHERE id = ?1 AND deleted_at IS NULL",2961 "SELECT owner_id FROM file WHERE id = ?1 AND deleted_at IS NULL",
2900 params![target_id],2962 params![target_id],
2901 )2963 )
2902 .await2964 .await
2903- .map_err(backend)?2965+ .map_err(backend)?,
2904- }2966+ ShareKind::Folder => conn
2905- ShareKind::Folder => {2967+ .query(
2906- conn.query(
2907 "SELECT owner_id FROM folder WHERE id = ?1 AND deleted_at IS NULL",2968 "SELECT owner_id FROM folder WHERE id = ?1 AND deleted_at IS NULL",
2908 params![target_id],2969 params![target_id],
2909 )2970 )
2910 .await2971 .await
2911- .map_err(backend)?2972+ .map_err(backend)?,
2912- }
2913 };2973 };
2914 match rows.next().await.map_err(backend)? {2974 match rows.next().await.map_err(backend)? {
2915 Some(row) => Ok(Some(text(&row, 0)?)),2975 Some(row) => Ok(Some(text(&row, 0)?)),
@@ -2992,7 +3052,11 @@ fn order_deepest_first(rows: &[(String, Option<String>)]) -> Vec<String> {
2992 /// How deep `id` sits inside `rows`: the ancestors it names that are3052 /// How deep `id` sits inside `rows`: the ancestors it names that are
2993 /// themselves in the set. A row whose parent is outside the set counts depth3053 /// themselves in the set. A row whose parent is outside the set counts depth
2994 /// only within it.3054 /// only within it.
2995-fn depth_in(id: &str, parents: &std::collections::HashMap<&str, &str>, in_set: &std::collections::HashSet<&str>) -> usize {3055+fn depth_in(
3056+ id: &str,
3057+ parents: &std::collections::HashMap<&str, &str>,
3058+ in_set: &std::collections::HashSet<&str>,
3059+) -> usize {
2996 let mut depth = 0;3060 let mut depth = 0;
2997 let mut cursor = id;3061 let mut cursor = id;
2998 while let Some(parent) = parents.get(cursor) {3062 while let Some(parent) = parents.get(cursor) {
@@ -3084,7 +3148,10 @@ mod tests {
3084 #[test]3148 #[test]
3085 fn postfixes_split_at_the_last_dot() {3149 fn postfixes_split_at_the_last_dot() {
3086 assert_eq!(postfixed_file_name("report.txt", 2), "report (2).txt");3150 assert_eq!(postfixed_file_name("report.txt", 2), "report (2).txt");
3087- assert_eq!(postfixed_file_name("archive.tar.gz", 2), "archive.tar (2).gz");3151+ assert_eq!(
3152+ postfixed_file_name("archive.tar.gz", 2),
3153+ "archive.tar (2).gz"
3154+ );
3088 assert_eq!(postfixed_file_name("name", 2), "name (2)");3155 assert_eq!(postfixed_file_name("name", 2), "name (2)");
3089 assert_eq!(postfixed_file_name("name", 3), "name (3)");3156 assert_eq!(postfixed_file_name("name", 3), "name (3)");
3090 // A leading dot is the whole stem, not an extension: dotfiles keep3157 // A leading dot is the whole stem, not an extension: dotfiles keep
@@ -3109,4 +3176,4 @@ mod tests {
3109 assert!(cut.ends_with(" (2)"));3176 assert!(cut.ends_with(" (2)"));
3110 assert!(cut.starts_with("é"));3177 assert!(cut.starts_with("é"));
3111 }3178 }
3112-}
\ No newline at end of file\ No newline at end of file
3179+}
crates/in-web/Cargo.tomlmodified+5 -0
@@ -30,6 +30,11 @@ async-trait = "0.1.92"
30 # The live stream is built with `futures_util::stream::unfold`; topcoat does30 # The live stream is built with `futures_util::stream::unfold`; topcoat does
31 # not re-export the futures traits, so this is named directly.31 # not re-export the futures traits, so this is named directly.
32 futures-util = { version = "0.3", default-features = false }32 futures-util = { version = "0.3", default-features = false }
33+# The byte routes build streamed bodies from `bytes::Bytes` frames; topcoat
34+# re-exports neither, so both are named directly.
35+bytes = "1"
36+http-body-util = "0.1"
37+http-body = "1"
33 # Hashes the compiled stylesheet against the bundle's bytes at boot, so a38 # Hashes the compiled stylesheet against the bundle's bytes at boot, so a
34 # bundle from another generation refuses the boot instead of serving under39 # bundle from another generation refuses the boot instead of serving under
35 # this binary (see `server.rs`'s `stylesheet_guard`).40 # this binary (see `server.rs`'s `stylesheet_guard`).
crates/in-web/src/files.rsmodified+62 -27
@@ -69,8 +69,8 @@ fn back_to_folder(
69 redirect_to(&location)69 redirect_to(&location)
70 }70 }
71 71
72-fn not_found() -> (StatusCode, HeaderMap, Vec<u8>) {72+fn not_found<B: From<Vec<u8>>>() -> (StatusCode, HeaderMap, B) {
73- (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new())73+ (StatusCode::NOT_FOUND, HeaderMap::new(), Vec::new().into())
74 }74 }
75 75
76 /// Whether the browser renders this stored mime on its own rather than only76 /// Whether the browser renders this stored mime on its own rather than only
@@ -204,15 +204,22 @@ async fn visible_file(
204 /// belongs to somebody else's drive. Inline bytes are the viewer's preview:204 /// belongs to somebody else's drive. Inline bytes are the viewer's preview:
205 /// anyone who may see the file reads them. Taking the file away is a205 /// anyone who may see the file reads them. Taking the file away is a
206 /// different act — `?dl=1` needs the download grant, and only it counts.206 /// different act — `?dl=1` needs the download grant, and only it counts.
207+///
208+/// The body streams off disk through [`bytes_response`]: a play starts on
209+/// the first 64 KiB frame, not on the whole file landing in memory, and a
210+/// range serve reads only its span.
207 #[route(GET "/file/{id}")]211 #[route(GET "/file/{id}")]
208-async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)> {212+async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, topcoat::router::Body)> {
209 let id: &str = path_param::<Id>(cx);213 let id: &str = path_param::<Id>(cx);
210 214
211 let user = match require_user(cx).await {215 let user = match require_user(cx).await {
212 Ok(user) => user,216 Ok(user) => user,
213 // A byte route has no page to carry a refusal on: back to the217 // A byte route has no page to carry a refusal on: back to the
214 // front door, where the sign-in card says what to do.218 // front door, where the sign-in card says what to do.
215- Err(_) => return Ok(redirect_to("/")),219+ Err(_) => {
220+ let (status, headers, body) = redirect_to("/");
221+ return Ok((status, headers, body.into()));
222+ }
216 };223 };
217 224
218 let store = app(cx).store.clone();225 let store = app(cx).store.clone();
@@ -232,9 +239,6 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
232 if forced && !may_download {239 if forced && !may_download {
233 return Ok(not_found());240 return Ok(not_found());
234 }241 }
235- let Ok(Some(bytes)) = store.file_bytes(id).await else {
236- return Ok(not_found());
237- };
238 242
239 let inline = !forced && inline_ok(&file.mime);243 let inline = !forced && inline_ok(&file.mime);
240 244
@@ -263,39 +267,69 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec<u8>)>
263 HeaderValue::from_static("private, max-age=31536000, immutable"),267 HeaderValue::from_static("private, max-age=31536000, immutable"),
264 );268 );
265 269
266- let total = bytes.len() as u64;
267 let range = request_headers(cx)270 let range = request_headers(cx)
268 .get(header::RANGE)271 .get(header::RANGE)
269 .and_then(|value| value.to_str().ok());272 .and_then(|value| value.to_str().ok());
270- match range.and_then(|range| parse_range(range, total)) {273+ // Only a real download counts — `?dl=1` — never the viewer's inline
271- Some(Ok((start, end))) => {274+ // bytes. A resumed download counts once, on its first chunk; later
272- // Only a real download counts — `?dl=1` — never the viewer's275+ // chunks are the same download going on.
273- // inline bytes. A resumed download counts once, on its first276+ let counts = forced
274- // chunk; later chunks are the same download going on.277+ && match range.and_then(|range| parse_range(range, file.size_bytes)) {
275- if forced && start == 0 {278+ Some(Ok((0, _))) | None => true,
279+ _ => false,
280+ };
281+ match bytes_response(store.as_ref(), id, file.size_bytes, range, headers).await {
282+ Some((status, headers, body)) => {
283+ if counts && status.is_success() {
276 let _ = store.record_download(id).await;284 let _ = store.record_download(id).await;
277 }285 }
278- let slice = bytes[start as usize..=end as usize].to_vec();286+ Ok((status, headers, body))
279- headers.insert(
280- header::CONTENT_RANGE,
281- HeaderValue::from_str(&format!("bytes {start}-{end}/{total}")).unwrap(),
282- );
283- Ok((StatusCode::PARTIAL_CONTENT, headers, slice))
284 }287 }
288+ None => Ok(not_found()),
289+ }
290+}
291+
292+/// The streamed answer for a file's bytes: the whole file from 0, or the
293+/// parsed range's span — [`Store::file_stream`] clamps both against what is
294+/// really on disk, and the `Content-Length` (and a 206's `Content-Range`)
295+/// say the clamped truth. `None` when the bytes are not there. Shared by the
296+/// signed-in route above and the public link's `download_bytes`.
297+pub(crate) async fn bytes_response(
298+ store: &dyn Store,
299+ id: &str,
300+ total: u64,
301+ range: Option<&str>,
302+ mut headers: HeaderMap,
303+) -> Option<(StatusCode, HeaderMap, topcoat::router::Body)> {
304+ use futures_util::StreamExt;
305+ use http_body::Frame;
306+ use http_body_util::StreamBody;
307+ use topcoat::router::Body;
308+ let (status, start, len) = match range.and_then(|range| parse_range(range, total)) {
309+ Some(Ok((start, end))) => (StatusCode::PARTIAL_CONTENT, start, end - start + 1),
285 Some(Err(())) => {310 Some(Err(())) => {
286 headers.insert(311 headers.insert(
287 header::CONTENT_RANGE,312 header::CONTENT_RANGE,
288 HeaderValue::from_str(&format!("bytes */{total}")).unwrap(),313 HeaderValue::from_str(&format!("bytes */{total}")).unwrap(),
289 );314 );
290- Ok((StatusCode::RANGE_NOT_SATISFIABLE, headers, Vec::new()))315+ return Some((StatusCode::RANGE_NOT_SATISFIABLE, headers, Body::empty()));
291- }
292- None => {
293- if forced {
294- let _ = store.record_download(id).await;
295- }
296- Ok((StatusCode::OK, headers, bytes))
297 }316 }
317+ None => (StatusCode::OK, 0, total),
318+ };
319+ let span = store.file_stream(id, start, len).await.ok().flatten()?;
320+ if status == StatusCode::PARTIAL_CONTENT {
321+ let end = start + span.len.saturating_sub(1);
322+ headers.insert(
323+ header::CONTENT_RANGE,
324+ HeaderValue::from_str(&format!("bytes {start}-{end}/{total}")).unwrap(),
325+ );
298 }326 }
327+ headers.insert(
328+ header::CONTENT_LENGTH,
329+ HeaderValue::from_str(&span.len.to_string()).unwrap(),
330+ );
331+ let frames = span.stream.map(|chunk| chunk.map(Frame::data));
332+ Some((status, headers, Body::new(StreamBody::new(frames))))
299 }333 }
300 334
301 /// Serves one file's webp thumbnail under the same visibility as the file335 /// 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 {
597 var volBtn = player.querySelector('.media-vol'); \631 var volBtn = player.querySelector('.media-vol'); \
598 var volSlider = player.querySelector('.media-vol-slider'); \632 var volSlider = player.querySelector('.media-vol-slider'); \
599 var speed = player.querySelector('.media-speed'); \633 var speed = player.querySelector('.media-speed'); \
634+ var full = player.querySelector('.media-full'); \
600 function clock(s) { \635 function clock(s) { \
601 if (!isFinite(s)) { return '0:00'; } \636 if (!isFinite(s)) { return '0:00'; } \
602 var m = Math.floor(s / 60); \637 var m = Math.floor(s / 60); \
crates/in-web/src/share.rsmodified+15 -14
@@ -25,9 +25,7 @@ use topcoat::context::Cx;
25 use topcoat::router::content::Form;25 use topcoat::router::content::Form;
26 use topcoat::router::request::{headers as request_headers, uri};26 use topcoat::router::request::{headers as request_headers, uri};
27 use topcoat::router::response::IntoResponse;27 use topcoat::router::response::IntoResponse;
28-use topcoat::router::{28+use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route};
29- HeaderName, StatusCode, header, page, path_param, query_params, route,
30-};
31 use topcoat::view::view;29 use topcoat::view::view;
32 30
33 use crate::files::entry_chip;31 use crate::files::entry_chip;
@@ -459,6 +457,7 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
459 cx,457 cx,
460 store.as_ref(),458 store.as_ref(),
461 &file.id,459 &file.id,
460+ file.size_bytes,
462 &file.name,461 &file.name,
463 &file.mime,462 &file.mime,
464 link.can_download,463 link.can_download,
@@ -503,6 +502,7 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
503 cx,502 cx,
504 store.as_ref(),503 store.as_ref(),
505 &file.id,504 &file.id,
505+ file.size_bytes,
506 &file.name,506 &file.name,
507 &file.mime,507 &file.mime,
508 link.can_download,508 link.can_download,
@@ -532,11 +532,14 @@ async fn shared_link(cx: &Cx) -> topcoat::Result<topcoat::router::response::Resp
532 532
533 /// The bytes behind a public link. A view-only link answers the dead card533 /// The bytes behind a public link. A view-only link answers the dead card
534 /// here — the same answer as a spent token — so the surface never says which534 /// here — the same answer as a spent token — so the surface never says which
535-/// tokens exist.535+/// tokens exist. The body streams off disk through
536+/// [`crate::files::bytes_response`], the same shape the signed-in route
537+/// serves: a range reads only its span, and no fetch buffers the file whole.
536 async fn download_bytes(538 async fn download_bytes(
537 cx: &Cx,539 cx: &Cx,
538 store: &dyn Store,540 store: &dyn Store,
539 file_id: &str,541 file_id: &str,
542+ size_bytes: u64,
540 name: &str,543 name: &str,
541 mime: &str,544 mime: &str,
542 can_download: bool,545 can_download: bool,
@@ -546,13 +549,6 @@ async fn download_bytes(
546 if !can_download {549 if !can_download {
547 return dead_link(cx).await.into_response(cx);550 return dead_link(cx).await.into_response(cx);
548 }551 }
549- let bytes = store
550- .file_bytes(file_id)
551- .await
552- .map_err(|_| Refusal::Unavailable);
553- let Ok(Some(bytes)) = bytes else {
554- return dead_link(cx).await.into_response(cx);
555- };
556 // A fetch counts once: a full fetch, or a range resuming from byte 0.552 // A fetch counts once: a full fetch, or a range resuming from byte 0.
557 // A mid-file chunk is the same view going on, not a new one — the way553 // A mid-file chunk is the same view going on, not a new one — the way
558 // the signed-in download route counts its first chunk only.554 // the signed-in download route counts its first chunk only.
@@ -578,7 +574,12 @@ async fn download_bytes(
578 header::CACHE_CONTROL,574 header::CACHE_CONTROL,
579 HeaderValue::from_static("private, no-cache"),575 HeaderValue::from_static("private, no-cache"),
580 );576 );
581- Ok((StatusCode::OK, headers, bytes).into_response(cx)?)577+ let Some(parts) =
578+ crate::files::bytes_response(store, file_id, size_bytes, range, headers).await
579+ else {
580+ return dead_link(cx).await.into_response(cx);
581+ };
582+ Ok(parts.into_response(cx)?)
582 }583 }
583 584
584 /// Whether a `Range` header starts at byte 0: only those ranges (and the585 /// Whether a `Range` header starts at byte 0: only those ranges (and the
@@ -1147,7 +1148,8 @@ pub(crate) async fn share_modal(
1147 people.push((grantee.display_name, grantee.email, grant.can_download));1148 people.push((grantee.display_name, grantee.email, grant.can_download));
1148 }1149 }
1149 }1150 }
1150- let refusal = query_value(uri(cx).query().unwrap_or(""), "refusal").and_then(|code| Refusal::from_code(&code));1151+ let refusal = query_value(uri(cx).query().unwrap_or(""), "refusal")
1152+ .and_then(|code| Refusal::from_code(&code));
1151 Ok(Some(view! {1153 Ok(Some(view! {
1152 cx =>1154 cx =>
1153 <div class="modal-scrim">1155 <div class="modal-scrim">
@@ -1264,7 +1266,6 @@ async fn share_copy_script(cx: &Cx) -> Result {
1264 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }1266 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
1265 }1267 }
1266 1268
1267-
1268 /// When the link stops opening, or never on its own. Twins the settings1269 /// When the link stops opening, or never on its own. Twins the settings
1269 /// page's helper; the share page renders the same expiry line.1270 /// page's helper; the share page renders the same expiry line.
1270 fn expiry_line(language: Lang, expires_at: Option<OffsetDateTime>) -> String {1271 fn expiry_line(language: Lang, expires_at: Option<OffsetDateTime>) -> String {
style/main.scssmodified+5 -2
@@ -1445,11 +1445,14 @@ img.avatar {
1445 }1445 }
1446 1446
1447 // The speed cycle reads as a value, not an icon: mono, quiet, button-sized.1447 // The speed cycle reads as a value, not an icon: mono, quiet, button-sized.
1448+// The width is fixed in ch — the longest label on the ladder ("0.75×") — so
1449+// cycling never moves the bar's other controls.
1448 .media-speed {1450 .media-speed {
1449 flex: none;1451 flex: none;
1450- min-width: 38px;1452+ width: 5.5ch;
1451 height: 28px;1453 height: 28px;
1452- padding: 0 4px;1454+ padding: 0;
1455+ text-align: center;
1453 border: none;1456 border: none;
1454 border-radius: var(--radius);1457 border-radius: var(--radius);
1455 background: none;1458 background: none;