diff --git a/crates/in-core/src/config.rs b/crates/in-core/src/config.rs index 87f9f9c..d231918 100644 --- a/crates/in-core/src/config.rs +++ b/crates/in-core/src/config.rs @@ -60,10 +60,6 @@ live_seconds = 300 purge_after_days = 30 # The quota a newly provisioned account starts on, in bytes. 10 GiB. default_quota_bytes = 10737418240 -# The default per-file upload ceiling, in bytes. 1 GiB. An admin can move it -# from the settings page without touching this file; this key is only the -# default the stored setting falls back to. -max_upload_bytes = 1073741824 # Where drive files, thumbnails and staged upload chunks live as files, # created on boot. Not written here: it defaults to beside the database file, # and the boot completes this file with the value it resolved. @@ -105,10 +101,6 @@ const DEFAULT_PURGE_AFTER_DAYS: u32 = 30; /// The quota a newly provisioned account starts on: 10 GiB. const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024; -/// The per-file upload ceiling when neither the stored setting nor the config -/// key names one: 1 GiB. -const DEFAULT_MAX_UPLOAD_BYTES: u64 = 1024 * 1024 * 1024; - /// Every completable top-level key, with the comment and default a file /// missing it is completed with. `database` is not here: it has no default /// worth guessing, so its absence stops the boot instead. `storage` is @@ -148,15 +140,6 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[ "default_quota_bytes = 10737418240\n" ), ), - ( - "max_upload_bytes", - concat!( - "# The default per-file upload ceiling, in bytes. 1 GiB. The settings\n", - "# page stores the live value in the database; this key is only the\n", - "# default it falls back to.\n", - "max_upload_bytes = 1073741824\n" - ), - ), ]; /// The `[oidc]` table of `config/in.toml`, before the values are checked. @@ -183,7 +166,6 @@ struct Toml { live_seconds: Option, purge_after_days: Option, default_quota_bytes: Option, - max_upload_bytes: Option, oidc: Option, #[serde(flatten)] other: std::collections::BTreeMap, @@ -224,9 +206,6 @@ pub struct Config { pub purge_after_days: u32, /// The quota a newly provisioned account starts on, in bytes. pub default_quota_bytes: u64, - /// The default per-file upload ceiling, in bytes. The settings page's - /// live value wins over this; this is only what an unset install enforces. - pub max_upload_bytes: u64, /// The OIDC provider In trusts. pub oidc: OidcConfig, /// Keys the file sets that nothing here reads, in the order the file @@ -355,12 +334,6 @@ impl Config { let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS); let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES); - // Zero names no usable ceiling — it would refuse every upload — so it - // reads as unset and falls through to the 1 GiB default. - let max_upload_bytes = toml - .max_upload_bytes - .filter(|limit| *limit > 0) - .unwrap_or(DEFAULT_MAX_UPLOAD_BYTES); let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; @@ -382,7 +355,6 @@ impl Config { live_seconds, purge_after_days, default_quota_bytes, - max_upload_bytes, oidc: OidcConfig { issuer, client_id, @@ -616,7 +588,6 @@ mod tests { const FULL: &str = r#"database = "in.db" listen = "127.0.0.1:7655" live_seconds = 300 -max_upload_bytes = 1073741824 purge_after_days = 30 default_quota_bytes = 10737418240 [oidc] @@ -657,7 +628,6 @@ client_secret = "s3cret" assert_eq!(config.live_seconds, 300); assert_eq!(config.purge_after_days, 30); assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024); - assert_eq!(config.max_upload_bytes, 1024 * 1024 * 1024); assert_eq!(config.oidc.issuer, "https://id.example.com"); assert_eq!( config.oidc.redirect_uri, @@ -773,39 +743,4 @@ client_secret = "s3cret" .join("storage") ); } - - #[test] - fn an_explicit_max_upload_bytes_wins_and_absence_defaults_to_1gib() { - let scratch = Scratch::new(); - scratch.write(&FULL.replace( - "max_upload_bytes = 1073741824", - "max_upload_bytes = 67108864", - )); - assert_eq!(scratch.load().unwrap().max_upload_bytes, 67108864); - // A file silent about the key still loads, at the 1 GiB default, and - // is completed with the key for the next boot to read. - let scratch = Scratch::new(); - scratch.write(&FULL.replace("max_upload_bytes = 1073741824\n", "")); - assert_eq!( - scratch.load().unwrap().max_upload_bytes, - 1024 * 1024 * 1024 - ); - let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap(); - assert!(completed.contains("max_upload_bytes = 1073741824")); - } - - #[test] - fn zero_max_upload_bytes_reads_as_unset() { - // Zero names no usable ceiling — it would refuse every upload — so it - // falls through to the 1 GiB default instead of becoming the limit. - let scratch = Scratch::new(); - scratch.write(&FULL.replace( - "max_upload_bytes = 1073741824", - "max_upload_bytes = 0", - )); - assert_eq!( - scratch.load().unwrap().max_upload_bytes, - 1024 * 1024 * 1024 - ); - } } diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 2171347..91f8267 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -635,6 +635,13 @@ pub trait Store: 'static + Send + Sync { /// active and unexpired, is refused. async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result; + /// The indexes of a session's staged chunks, sorted ascending, read off + /// the chunk files on disk — exactly what a resuming uploader may skip + /// re-sending. An unknown session is [`StoreError::NotFound`]; the + /// session's state is not checked, so an expired one still answers what + /// it holds. + async fn uploaded_chunks(&self, id: &str) -> Result>; + /// Assembles a session's chunks in order, rechecks the quota, sniffs the /// mime (never trusting anything the uploader said), writes the file, /// attempts a thumbnail for images and video, inserts the row and marks the session diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 661981a..6e8b99e 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -596,6 +596,21 @@ fn staged_received(storage: &std::path::Path, id: &str) -> u64 { } total } + +/// The indexes of the chunk files a session holds, unsorted — the same +/// on-disk truth `staged_received` sums. +fn staged_indexes(storage: &std::path::Path, id: &str) -> Vec { + let dir = session_dir(storage, id); + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(_) => return Vec::new(), + }; + entries + .flatten() + .filter(|entry| entry.path().is_file()) + .filter_map(|entry| entry.file_name().to_str()?.parse::().ok()) + .collect() +} /// Creates the storage tree — the root and one directory per payload kind — /// and locks each to 0700 on unix. Every writer past `open` assumes the tree /// is there. @@ -2375,6 +2390,13 @@ impl Store for TursoStore { Ok(session) } + async fn uploaded_chunks(&self, id: &str) -> Result> { + self.upload_session(id).await?.ok_or(StoreError::NotFound)?; + let mut indexes = staged_indexes(&self.storage, id); + indexes.sort_unstable(); + Ok(indexes) + } + 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() { diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 8d6b4c5..a5c2fac 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -760,6 +760,35 @@ async fn an_empty_upload_finishes_an_empty_file() { assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), Vec::::new()); } +#[tokio::test] +async fn uploaded_chunks_names_what_a_resume_may_skip() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let session = scratch + .store + .create_upload_session(&user.id, None, "resume.bin", CHUNK_SIZE + 4) + .await + .unwrap(); + assert_eq!( + scratch.store.uploaded_chunks(&session.id).await.unwrap(), + Vec::::new() + ); + // Out of order on purpose: the answer is read off the chunk files on + // disk and comes back sorted, whatever order the calls arrived in. + scratch.store.record_chunk(&session.id, 1, b"tail").await.unwrap(); + assert_eq!(scratch.store.uploaded_chunks(&session.id).await.unwrap(), vec![1]); + scratch + .store + .record_chunk(&session.id, 0, &vec![7u8; CHUNK_SIZE as usize]) + .await + .unwrap(); + assert_eq!(scratch.store.uploaded_chunks(&session.id).await.unwrap(), vec![0, 1]); + assert!(matches!( + scratch.store.uploaded_chunks("no-such-session").await, + Err(StoreError::NotFound) + )); +} + #[tokio::test] async fn uploads_abort_and_prune() { let scratch = Scratch::open().await; diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index bbc410e..20619b3 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -1035,15 +1035,54 @@ async fn upload_script(cx: &Cx) -> Result { if (!answer.ok) { throw new Error(answer.err || 'start'); } \ return answer.ok; \ } \ + /* A cut upload resumes: the session id waits in localStorage \ + under the file's identity, and a re-send of the same file \ + asks the server which chunks it already holds instead of \ + starting over. The store is best-effort — private windows may \ + refuse it, and an upload without it just cannot resume. */ \ + function resumeKey(folder, file) { return 'in-upload:' + (folder || '') + ':' + file.name + ':' + file.size; } \ + function saveResume(key, id) { try { window.localStorage.setItem(key, id); } catch (err) {} } \ + function loadResume(key) { try { return window.localStorage.getItem(key); } catch (err) { return null; } } \ + function dropResume(key) { try { window.localStorage.removeItem(key); } catch (err) {} } \ + /* A backoff the cancel button still interrupts: the flag is \ + polled, so a cancel during a wait does not ride out the \ + delay. */ \ + function wait(ms, u) { \ + return new Promise(function (resolve, reject) { \ + var timer = setTimeout(done, ms); \ + var watch = u ? setInterval(function () { if (u.cancelled) { cleanup(); reject(canceledErr()); } }, 100) : null; \ + function done() { cleanup(); resolve(); } \ + function cleanup() { clearTimeout(timer); if (watch) { clearInterval(watch); } } \ + }); \ + } \ async function sendBig(file, folder, onProgress, u) { \ - var session = await startChunked(folder, file.name, file.size); \ + var key = resumeKey(folder, file); \ + var session = null; \ + var staged = {}; \ + var saved = loadResume(key); \ + if (saved) { \ + var probe = await fetch('/api/upload/' + saved, { headers: { accept: 'application/json' } }); \ + var status = await probe.json(); \ + if (status.ok && status.ok.size_bytes === file.size && status.ok.chunk_size === LIMIT && status.ok.name === file.name) { \ + session = { id: saved }; \ + (status.ok.uploaded || []).forEach(function (index) { staged[index] = true; }); \ + } else { \ + dropResume(key); \ + } \ + } \ + if (!session) { \ + session = await startChunked(folder, file.name, file.size); \ + saveResume(key, session.id); \ + } \ /* The session id lives on the mirror entry, so the row's \ cancel control still reaches the abort endpoint after a \ soft navigation rebuilt the page around it. A cancel that \ landed during the start flight aborts the fresh session \ - straight away instead of leaking it. */ \ + straight away instead of leaking it. Cancel also drops \ + the resume key: a deliberate cancel is not resumable. */ \ if (u) { \ if (u.cancelled) { \ + dropResume(key); \ fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ throw canceledErr(); \ } \ @@ -1051,38 +1090,69 @@ async fn upload_script(cx: &Cx) -> Result { u.cancel = function () { \ u.cancelled = true; \ try { u.abortChunk(); } catch (err) {} \ + dropResume(key); \ fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ }; \ } \ var total = Math.max(1, file.size); \ - var index = 0; \ var flight = null; \ if (u) { \ u.abortChunk = function () { if (flight) { try { flight.abort(); } catch (err) {} } }; \ } \ - for (var off = 0; off < file.size; off += LIMIT, index++) { \ + /* A chunk that meets a network cut is retried in place with \ + a backoff; only after three misses does the upload fail — \ + and even then the resume key stays, so picking the file \ + again carries on where it stopped. An expired session \ + restarts the walk once against a fresh session; a second \ + expiry fails like any other error. */ \ + var restarted = false; \ + walk: for (var off = 0, index = 0; off < file.size; off += LIMIT, index++) { \ if (u && u.cancelled) { throw canceledErr(); } \ var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \ - flight = new AbortController(); \ - var r; \ - try { \ - r = await fetch('/api/upload/' + session.id + '/' + index, { \ - method: 'PUT', \ - headers: { 'content-type': 'application/octet-stream' }, \ - body: piece, \ - signal: flight.signal \ - }); \ - } catch (err) { \ + if (staged[index]) { onProgress((off + piece.size) / total); continue; } \ + var sent = false; \ + for (var attempt = 0; attempt < 3 && !sent; attempt++) { \ if (u && u.cancelled) { throw canceledErr(); } \ - throw err; \ + if (attempt > 0) { await wait(1000 * attempt, u); } \ + flight = new AbortController(); \ + var r; \ + try { \ + r = await fetch('/api/upload/' + session.id + '/' + index, { \ + method: 'PUT', \ + headers: { 'content-type': 'application/octet-stream' }, \ + body: piece, \ + signal: flight.signal \ + }); \ + } catch (err) { \ + if (u && u.cancelled) { throw canceledErr(); } \ + continue; \ + } \ + if (!r.ok) { continue; } \ + var answer = await r.json(); \ + if (answer.ok) { sent = true; } \ + else if (answer.err === 'UploadExpired' && !restarted) { \ + restarted = true; \ + dropResume(key); \ + session = await startChunked(folder, file.name, file.size); \ + saveResume(key, session.id); \ + if (u) { u.sessionId = session.id; } \ + staged = {}; \ + off = -LIMIT; \ + index = -1; \ + continue walk; \ + } \ + else { throw new Error(answer.err || 'chunk'); } \ } \ - if (!r.ok) { throw new Error('chunk'); } \ + if (!sent) { throw new Error('chunk'); } \ onProgress((off + piece.size) / total); \ } \ if (u && u.cancelled) { throw canceledErr(); } \ var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \ var fin = await done.json(); \ + /* A refused finish keeps the chunks staged, so the key stays \ + too: picking the file again resumes into another finish. */ \ if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \ + dropResume(key); \ onProgress(1); \ } \ function sendSmall(action, folder, files, onProgress, u) { \ diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index 181a81a..9d25683 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -784,16 +784,8 @@ async fn upload( return Ok(back_to_folder(folder_id.as_deref(), None)); } - let limit = crate::server::effective_upload_limit(cx).await; - let mut refusal: Option = None; for (name, bytes) in files { - // One file may not pass the instance ceiling; oversize files never - // reach the store. - if bytes.len() as u64 > limit { - refusal = Some(Refusal::UploadTooLarge); - break; - } // The store sanitises the label, sniffs the mime off the bytes, // checks the quota, writes the file and attempts the thumbnail. if let Err(error) = store diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index f3c91ac..9845f8c 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -187,10 +187,6 @@ pub enum Key { // File viewer. UploadedLabel, DownloadsLabel, - // Wave-1 upload limits. - UploadLimits, - CurrentUploadLimit, - MaxUploadBytes, // Wave-2 drive additions (DriveBuild owns this block). Options, DropFilesToUpload, @@ -337,9 +333,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { Saved => "Saved.", UploadedLabel => "Uploaded", DownloadsLabel => "Downloads", - UploadLimits => "Upload limit", - CurrentUploadLimit => "Current limit", - MaxUploadBytes => "Upload limit", Options => "Options", DropFilesToUpload => "Drop files to upload", Dismiss => "Dismiss", @@ -480,9 +473,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { Saved => "Kaydedildi.", UploadedLabel => "Yüklendi", DownloadsLabel => "İndirme", - UploadLimits => "Yükleme sınırı", - CurrentUploadLimit => "Geçerli sınır", - MaxUploadBytes => "Yükleme sınırı", Options => "Seçenekler", DropFilesToUpload => "Yüklemek için dosyaları bırakın", Dismiss => "Kapat", diff --git a/crates/in-web/src/main.rs b/crates/in-web/src/main.rs index d98b88d..111b242 100644 --- a/crates/in-web/src/main.rs +++ b/crates/in-web/src/main.rs @@ -150,11 +150,11 @@ async fn main() { let router = in_client::mount( Router::builder() .discover() - // BodyLimit is only a memory guard here, not the upload policy: the - // real per-file ceiling is the admin-controlled limit enforced in - // the handlers (`effective_upload_limit`). `/files` takes whole - // multipart bodies, so its guard sits at a hard 2 GiB; `/api/upload` - // carries single 8 MiB chunks, so 32 MiB leaves ample headroom. + // BodyLimit is only a memory guard here, not the upload policy: + // the account quota, enforced in the store at start and finish, + // is the only size limit. `/files` takes whole multipart bodies, + // so its guard sits at a hard 2 GiB; `/api/upload` carries single + // 8 MiB chunks, so 32 MiB leaves ample headroom. .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files")) .cookies() diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index fb14808..144fc75 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -216,10 +216,8 @@ pub enum Refusal { BadTheme, /// The language field was not one of the values the form offers. BadLanguage, - /// One file carries more bytes than the instance upload ceiling allows. - UploadTooLarge, - /// The admin's upload-limit form named zero, which would refuse every upload. - /// (The form speaks bytes, so nothing can overflow; zero is the only refusal.) + /// The admin's quota form named something unusable — unparseable, or a + /// unit the form does not offer. BadLimit, } @@ -243,7 +241,6 @@ impl Refusal { Refusal::BadUi => "That interface choice is not offered.".to_string(), Refusal::BadTheme => "That is not a theme.".to_string(), Refusal::BadLanguage => "That is not a language.".to_string(), - Refusal::UploadTooLarge => "That file is larger than the upload limit.".to_string(), Refusal::BadLimit => "That limit is not usable.".to_string(), } } @@ -269,7 +266,6 @@ impl Refusal { Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(), Refusal::BadTheme => "Bu bir tema değil.".to_string(), Refusal::BadLanguage => "Bu bir dil değil.".to_string(), - Refusal::UploadTooLarge => "Bu dosya yükleme sınırından büyük.".to_string(), Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(), } } @@ -293,7 +289,6 @@ impl Refusal { "bad-ui" => Refusal::BadUi, "bad-theme" => Refusal::BadTheme, "bad-language" => Refusal::BadLanguage, - "upload-too-large" => Refusal::UploadTooLarge, "bad-limit" => Refusal::BadLimit, _ => return None, }) @@ -321,38 +316,11 @@ impl Refusal { Refusal::BadUi => "bad-ui", Refusal::BadTheme => "bad-theme", Refusal::BadLanguage => "bad-language", - Refusal::UploadTooLarge => "upload-too-large", Refusal::BadLimit => "bad-limit", } } } -/// The instance setting holding the per-file upload ceiling, in bytes. -/// Written by the admin's upload-limit form; read here. -pub(crate) const MAX_UPLOAD_SETTING: &str = "max_upload_bytes"; - -/// The per-file upload ceiling in force for this request: the -/// [`MAX_UPLOAD_SETTING`] instance setting first, then the -/// `max_upload_bytes` key from `config/in.toml`, then 1 GiB when neither -/// names one. -/// -/// A setting that is missing, unreadable, unparseable or zero falls through -/// to the config default — the save form only ever writes positive integers, -/// so anything else is a hand-edited row, not a choice. Quota is untouched: -/// this caps one file's size, quota caps an account's total. -pub(crate) async fn effective_upload_limit(cx: &Cx) -> u64 { - let ctx = app(cx); - match ctx.store.get_setting(MAX_UPLOAD_SETTING).await { - Ok(Some(raw)) => raw - .trim() - .parse::() - .ok() - .filter(|limit| *limit > 0) - .unwrap_or(ctx.config.max_upload_bytes), - Ok(None) | Err(_) => ctx.config.max_upload_bytes, - } -} - /// Which call a carried refusal belongs to. Two forms on one page must not both /// claim the same sentence, so the redirect names the call and this is the name: /// the last piece of the server function's path, with anything that is not a diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index 09ee3c7..97aac34 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -4,13 +4,11 @@ //! quota usage bar beside it, and the reader's own live share links with //! their revoke buttons — including the copy-once banner after a creation //! (`?created=` on the query, rendered once and never stored). -//! Admins additionally see every account with its quota and disabled flag, -//! plus the instance-wide per-file upload limit in the same Everyone panel. -//! `POST /api/settings/quota|disable|upload-limit` are admin-only: the first -//! sets a user's byte quota, the second disables or re-enables them (a disabled -//! account reads as signed-out everywhere, the im session untouched, and -//! disabling yourself is refused), and the third sets the per-file ceiling -//! for the whole install. +//! Admins additionally see every account with its quota and disabled flag in +//! the Everyone panel. `POST /api/settings/quota|disable` are admin-only: +//! the first sets a user's byte quota, the second disables or re-enables +//! them (a disabled account reads as signed-out everywhere, the im session +//! untouched, and disabling yourself is refused). use in_core::store::{ShareKind, User}; use serde::Deserialize; @@ -78,9 +76,8 @@ fn trim_amount(value: f64) -> String { } /// The bytes an `(amount, unit)` pair names, or `None` when the pair is not -/// a usable limit: an unknown unit, or an amount that is not a finite -/// positive number. Callers decide whether zero passes (quota) or not -/// (upload limit). +/// a usable quota: an unknown unit, or an amount that is not a finite +/// positive number. fn unit_bytes(amount: &str, unit: &str) -> Option { let per = match unit { "MiB" => MIB_BYTES, @@ -140,38 +137,6 @@ async fn set_quota(cx: &Cx, Form(input): Form) -> Redirect { } } -#[derive(Deserialize)] -struct UploadLimitForm { - #[serde(default)] - max_upload: String, - #[serde(default)] - max_upload_unit: String, -} -/// Sets the instance-wide per-file upload ceiling from a human-unit pair -/// (`max_upload` amount in `max_upload_unit` MiB/GiB), converted to bytes -/// for the `max_upload_bytes` instance setting — so `2 GiB` stores -/// `2147483648` and the panel reads it back as `2.0 GiB`. The fallback chain -/// in [`crate::server::effective_upload_limit`] is untouched, and zero (or -/// anything unparseable) is refused with `BadLimit`: an install must always -/// have a positive per-file ceiling. -#[route(POST "/api/settings/upload-limit")] -async fn set_upload_limit(cx: &Cx, Form(input): Form) -> Redirect { - if let Err(refusal) = require_admin(cx).await { - return redirect_back(cx, "upload-limit", Some(refusal)); - } - match unit_bytes(&input.max_upload, &input.max_upload_unit) { - Some(bytes) if bytes > 0 => match app(cx) - .store - .set_setting(crate::server::MAX_UPLOAD_SETTING, &bytes.to_string()) - .await - { - Ok(()) => redirect_back(cx, "upload-limit", None), - Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))), - }, - _ => redirect_back(cx, "upload-limit", Some(Refusal::BadLimit)), - } -} - #[derive(Deserialize)] struct DisableForm { user_id: String, @@ -307,13 +272,6 @@ async fn settings(cx: &Cx) -> Result { } else { Vec::new() }; - // The live per-file ceiling, read once for the Everyone panel below. Only - // admins see it, so only they pay the extra setting read. - let upload_limit = if fresh.admin { - Some(crate::server::effective_upload_limit(cx).await) - } else { - None - }; let created = created_token(uri(cx).query().unwrap_or("")); let origin = app(cx).config.listen_url(); view! { @@ -322,7 +280,7 @@ async fn settings(cx: &Cx) -> Result {

(t(language, Key::Settings))

- (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "upload-limit"]).await?) + (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences"]).await?) if let Some(token) = created {
@@ -465,23 +423,6 @@ async fn settings(cx: &Cx) -> Result {
- if let Some(limit) = upload_limit { - // The instance-wide limit, one labeled row under the member table — - // same compact amount+unit form the per-user quota cells use. -
- (t(language, Key::MaxUploadBytes)) - (format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit))) -
-
- - - -
-
- }
} diff --git a/crates/in-web/src/upload.rs b/crates/in-web/src/upload.rs index 3d4e474..16d29ef 100644 --- a/crates/in-web/src/upload.rs +++ b/crates/in-web/src/upload.rs @@ -1,11 +1,12 @@ //! The chunked-upload protocol. //! -//! Four owner-only JSON calls, all UTF-8: `POST /api/upload/start` +//! Five owner-only JSON calls, all UTF-8: `POST /api/upload/start` //! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the //! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota -//! says no, `Refusal::UploadTooLarge` past the instance upload ceiling); -//! `PUT /api/upload/{id}/{index}` takes one raw chunk (32 MiB cap, layered -//! in `main.rs` — the real per-file ceiling lives in the start handler); +//! says no — the account quota is the only size limit); `GET /api/upload/{id}` +//! answers the session with the indexes already staged, so an interrupted +//! upload resumes instead of starting over; `PUT /api/upload/{id}/{index}` +//! takes one raw chunk (32 MiB cap, layered in `main.rs`); //! `POST /api/upload/{id}/finish` assembles the //! staged chunks, sniffs the mime, moves the bytes to `files/` //! and answers with the created file id; `POST /api/upload/{id}/abort` @@ -110,12 +111,6 @@ async fn start(cx: &Cx, Json(input): Json) -> Result return Ok(Json(Answer::Err(Refusal::Unavailable))), } } - // The instance ceiling is checked against the declared total before a - // single chunk is sent: chunks can never add past the declared total - // (the store refuses that), so this one check caps the whole session. - if input.size_bytes > crate::server::effective_upload_limit(cx).await { - return Ok(Json(Answer::Err(Refusal::UploadTooLarge))); - } match store .create_upload_session(&user.id, folder, &input.name, input.size_bytes) .await @@ -163,6 +158,42 @@ async fn chunk(cx: &Cx, body: Bytes) -> Result>> { } } +#[derive(serde::Serialize)] +struct StatusOut { + id: String, + chunk_size: u64, + size_bytes: u64, + name: String, + folder_id: Option, + uploaded: Vec, +} + +/// The session and the indexes already staged, for a resuming uploader: +/// the client skips every index in `uploaded` and sends only what is +/// missing. An expired session still answers — the chunks it holds are +/// real until the sweep takes them — so the client reads the expiry off +/// `chunk`'s refusal, not here. +#[route(GET "/api/upload/{id}")] +async fn status(cx: &Cx) -> Result>> { + let id: &str = path_param::(cx); + let session = match owned_session(cx, id).await { + Ok(session) => session, + Err(refusal) => return Ok(Json(Answer::Err(refusal))), + }; + let store = app(cx).store.clone(); + match store.uploaded_chunks(&session.id).await { + Ok(uploaded) => Ok(Json(Answer::Ok(StatusOut { + id: session.id, + chunk_size: session.chunk_size, + size_bytes: session.size_bytes, + name: session.name, + folder_id: session.folder_id, + uploaded, + }))), + Err(error) => Ok(Json(Answer::Err(store_refusal(error)))), + } +} + /// Assembles the staged chunks — rechecking the quota, sniffing the mime /// off the bytes, attempting the thumbnail — and answers the created file /// id. The chunks stay staged on refusal, so the browser may retry. diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index df0d4b8..47c4374 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -282,7 +282,6 @@ impl TestApp { live_seconds: 300, purge_after_days: 30, default_quota_bytes: 10 * 1024 * 1024 * 1024, - max_upload_bytes: 1024 * 1024 * 1024, oidc: OidcConfig { issuer: fake.url(), client_id: "in-test".to_string(), @@ -589,6 +588,10 @@ impl Raw { fn text(&self) -> String { String::from_utf8(self.bytes.clone()).unwrap() } + + fn json(&self) -> serde_json::Value { + serde_json::from_str(&self.text()).unwrap() + } } /// Form encoding, enough for the names these tests send. @@ -885,6 +888,74 @@ async fn chunked_upload_round_trip() { assert_eq!(row.owner_id, user.id); } +#[tokio::test] +async fn an_interrupted_upload_resumes_from_its_staged_chunks() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-resume", "resume@in.test", "Resume").await; + + // Two chunks: stage the first, ask the status what a resume may skip, + // then land the second and finish. + let total = 8 * 1024 * 1024 + 100; + let mut bytes = Vec::with_capacity(total); + for i in 0..total { + bytes.push((i % 251) as u8); + } + let answer = app + .post_json( + "/api/upload/start", + Some(&cookie), + serde_json::json!({"folder_id": null, "name": "resume.bin", "size_bytes": total}), + ) + .await; + let session = answer.json()["ok"]["id"] + .as_str() + .expect("start was refused") + .to_string(); + + app.put_bytes( + &format!("/api/upload/{session}/0"), + Some(&cookie), + &bytes[..8 * 1024 * 1024], + ) + .await; + + let status = app + .get(&format!("/api/upload/{session}"), Some(&cookie)) + .await; + assert_eq!(status.status, StatusCode::OK, "{}", status.text()); + let body = status.json(); + assert_eq!(body["ok"]["size_bytes"].as_u64(), Some(total as u64)); + assert_eq!(body["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024)); + assert_eq!(body["ok"]["name"].as_str(), Some("resume.bin")); + assert_eq!(body["ok"]["uploaded"], serde_json::json!([0])); + + // Another owner's probe of the same id is not found, not forbidden. + let other = app.sign_in("sub-nosey", "nosey@in.test", "Nosey").await; + let status = app + .get(&format!("/api/upload/{session}"), Some(&other)) + .await; + assert_eq!(status.json()["err"].as_str(), Some("NotFound")); + + app.put_bytes( + &format!("/api/upload/{session}/1"), + Some(&cookie), + &bytes[8 * 1024 * 1024..], + ) + .await; + let answer = app + .post_json( + &format!("/api/upload/{session}/finish"), + Some(&cookie), + serde_json::json!({}), + ) + .await; + let file_id = answer.json()["ok"] + .as_str() + .expect("finish was refused") + .to_string(); + let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await; + assert_eq!(got.bytes, bytes); +} #[tokio::test] async fn range_request_serves_a_slice() { let app = TestApp::build().await; @@ -3350,3 +3421,4 @@ async fn an_empty_folder_says_how_to_fill_it() { assert!(body.contains("id=\"upload-form\""), "{body}"); assert!(body.contains("__inDrop"), "{body}"); } + diff --git a/style/main.scss b/style/main.scss index 27ab239..8d653aa 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4801,17 +4801,6 @@ input[type="radio"] { flex: none; } -// The instance-wide upload limit: one labeled row under the register, the -// same compact amount+unit form the quota cells use. -.upload-limit { - display: flex; - align-items: center; - gap: 10px; - flex-wrap: wrap; - margin-top: 14px; - padding-top: 14px; - border-top: 1px solid var(--border); -} .member-table .member-col-address { min-width: 26ch; }