Quota is the only size limit
Browse files at this commit3cd7a8eca3dcdf2949b1f64a8ea4ccc249099a07Parent: 888f97d- feat
- quota is the only size limit
- interrupted uploads resume
13 changed files +273 -227
- crates/in-core/src/config.rs +0 -65
- crates/in-core/src/store/mod.rs +7 -0
- crates/in-core/src/store/turso_store.rs +22 -0
- crates/in-core/tests/store.rs +29 -0
- crates/in-web/src/drive.rs +86 -16
- crates/in-web/src/files.rs +0 -8
- crates/in-web/src/i18n.rs +0 -10
- crates/in-web/src/main.rs +5 -5
- crates/in-web/src/server.rs +2 -34
- crates/in-web/src/settings.rs +8 -67
- crates/in-web/src/upload.rs +41 -10
- crates/in-web/tests/http.rs +73 -1
- style/main.scss +0 -11
crates/in-core/src/config.rsmodified+0 -65
| @@ -60,10 +60,6 @@ live_seconds = 300 | |||
| 60 | purge_after_days = 30 | 60 | purge_after_days = 30 |
| 61 | # The quota a newly provisioned account starts on, in bytes. 10 GiB. | 61 | # The quota a newly provisioned account starts on, in bytes. 10 GiB. |
| 62 | default_quota_bytes = 10737418240 | 62 | default_quota_bytes = 10737418240 |
| 63 | -# The default per-file upload ceiling, in bytes. 1 GiB. An admin can move it | ||
| 64 | -# from the settings page without touching this file; this key is only the | ||
| 65 | -# default the stored setting falls back to. | ||
| 66 | -max_upload_bytes = 1073741824 | ||
| 67 | # Where drive files, thumbnails and staged upload chunks live as files, | 63 | # Where drive files, thumbnails and staged upload chunks live as files, |
| 68 | # created on boot. Not written here: it defaults to beside the database file, | 64 | # created on boot. Not written here: it defaults to beside the database file, |
| 69 | # and the boot completes this file with the value it resolved. | 65 | # and the boot completes this file with the value it resolved. |
| @@ -105,10 +101,6 @@ const DEFAULT_PURGE_AFTER_DAYS: u32 = 30; | |||
| 105 | /// The quota a newly provisioned account starts on: 10 GiB. | 101 | /// The quota a newly provisioned account starts on: 10 GiB. |
| 106 | const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024; | 102 | const DEFAULT_QUOTA_BYTES: u64 = 10 * 1024 * 1024 * 1024; |
| 107 | 103 | ||
| 108 | -/// The per-file upload ceiling when neither the stored setting nor the config | ||
| 109 | -/// key names one: 1 GiB. | ||
| 110 | -const DEFAULT_MAX_UPLOAD_BYTES: u64 = 1024 * 1024 * 1024; | ||
| 111 | - | ||
| 112 | /// Every completable top-level key, with the comment and default a file | 104 | /// Every completable top-level key, with the comment and default a file |
| 113 | /// missing it is completed with. `database` is not here: it has no default | 105 | /// missing it is completed with. `database` is not here: it has no default |
| 114 | /// worth guessing, so its absence stops the boot instead. `storage` is | 106 | /// worth guessing, so its absence stops the boot instead. `storage` is |
| @@ -148,15 +140,6 @@ const OPTIONAL_KEYS: &[(&str, &str)] = &[ | |||
| 148 | "default_quota_bytes = 10737418240\n" | 140 | "default_quota_bytes = 10737418240\n" |
| 149 | ), | 141 | ), |
| 150 | ), | 142 | ), |
| 151 | - ( | ||
| 152 | - "max_upload_bytes", | ||
| 153 | - concat!( | ||
| 154 | - "# The default per-file upload ceiling, in bytes. 1 GiB. The settings\n", | ||
| 155 | - "# page stores the live value in the database; this key is only the\n", | ||
| 156 | - "# default it falls back to.\n", | ||
| 157 | - "max_upload_bytes = 1073741824\n" | ||
| 158 | - ), | ||
| 159 | - ), | ||
| 160 | ]; | 143 | ]; |
| 161 | 144 | ||
| 162 | /// The `[oidc]` table of `config/in.toml`, before the values are checked. | 145 | /// The `[oidc]` table of `config/in.toml`, before the values are checked. |
| @@ -183,7 +166,6 @@ struct Toml { | |||
| 183 | live_seconds: Option<u64>, | 166 | live_seconds: Option<u64>, |
| 184 | purge_after_days: Option<u32>, | 167 | purge_after_days: Option<u32>, |
| 185 | default_quota_bytes: Option<u64>, | 168 | default_quota_bytes: Option<u64>, |
| 186 | - max_upload_bytes: Option<u64>, | ||
| 187 | oidc: Option<OidcToml>, | 169 | oidc: Option<OidcToml>, |
| 188 | #[serde(flatten)] | 170 | #[serde(flatten)] |
| 189 | other: std::collections::BTreeMap<String, toml::Value>, | 171 | other: std::collections::BTreeMap<String, toml::Value>, |
| @@ -224,9 +206,6 @@ pub struct Config { | |||
| 224 | pub purge_after_days: u32, | 206 | pub purge_after_days: u32, |
| 225 | /// The quota a newly provisioned account starts on, in bytes. | 207 | /// The quota a newly provisioned account starts on, in bytes. |
| 226 | pub default_quota_bytes: u64, | 208 | pub default_quota_bytes: u64, |
| 227 | - /// The default per-file upload ceiling, in bytes. The settings page's | ||
| 228 | - /// live value wins over this; this is only what an unset install enforces. | ||
| 229 | - pub max_upload_bytes: u64, | ||
| 230 | /// The OIDC provider In trusts. | 209 | /// The OIDC provider In trusts. |
| 231 | pub oidc: OidcConfig, | 210 | pub oidc: OidcConfig, |
| 232 | /// Keys the file sets that nothing here reads, in the order the file | 211 | /// Keys the file sets that nothing here reads, in the order the file |
| @@ -355,12 +334,6 @@ impl Config { | |||
| 355 | 334 | ||
| 356 | let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS); | 335 | let purge_after_days = toml.purge_after_days.unwrap_or(DEFAULT_PURGE_AFTER_DAYS); |
| 357 | let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES); | 336 | let default_quota_bytes = toml.default_quota_bytes.unwrap_or(DEFAULT_QUOTA_BYTES); |
| 358 | - // Zero names no usable ceiling — it would refuse every upload — so it | ||
| 359 | - // reads as unset and falls through to the 1 GiB default. | ||
| 360 | - let max_upload_bytes = toml | ||
| 361 | - .max_upload_bytes | ||
| 362 | - .filter(|limit| *limit > 0) | ||
| 363 | - .unwrap_or(DEFAULT_MAX_UPLOAD_BYTES); | ||
| 364 | 337 | ||
| 365 | let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; | 338 | let oidc_toml = toml.oidc.ok_or(ConfigError::Missing("[oidc]"))?; |
| 366 | let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; | 339 | let issuer = value(oidc_toml.issuer).ok_or(ConfigError::Missing("oidc.issuer"))?; |
| @@ -382,7 +355,6 @@ impl Config { | |||
| 382 | live_seconds, | 355 | live_seconds, |
| 383 | purge_after_days, | 356 | purge_after_days, |
| 384 | default_quota_bytes, | 357 | default_quota_bytes, |
| 385 | - max_upload_bytes, | ||
| 386 | oidc: OidcConfig { | 358 | oidc: OidcConfig { |
| 387 | issuer, | 359 | issuer, |
| 388 | client_id, | 360 | client_id, |
| @@ -616,7 +588,6 @@ mod tests { | |||
| 616 | const FULL: &str = r#"database = "in.db" | 588 | const FULL: &str = r#"database = "in.db" |
| 617 | listen = "127.0.0.1:7655" | 589 | listen = "127.0.0.1:7655" |
| 618 | live_seconds = 300 | 590 | live_seconds = 300 |
| 619 | -max_upload_bytes = 1073741824 | ||
| 620 | purge_after_days = 30 | 591 | purge_after_days = 30 |
| 621 | default_quota_bytes = 10737418240 | 592 | default_quota_bytes = 10737418240 |
| 622 | [oidc] | 593 | [oidc] |
| @@ -657,7 +628,6 @@ client_secret = "s3cret" | |||
| 657 | assert_eq!(config.live_seconds, 300); | 628 | assert_eq!(config.live_seconds, 300); |
| 658 | assert_eq!(config.purge_after_days, 30); | 629 | assert_eq!(config.purge_after_days, 30); |
| 659 | assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024); | 630 | assert_eq!(config.default_quota_bytes, 10 * 1024 * 1024 * 1024); |
| 660 | - assert_eq!(config.max_upload_bytes, 1024 * 1024 * 1024); | ||
| 661 | assert_eq!(config.oidc.issuer, "https://id.example.com"); | 631 | assert_eq!(config.oidc.issuer, "https://id.example.com"); |
| 662 | assert_eq!( | 632 | assert_eq!( |
| 663 | config.oidc.redirect_uri, | 633 | config.oidc.redirect_uri, |
| @@ -773,39 +743,4 @@ client_secret = "s3cret" | |||
| 773 | .join("storage") | 743 | .join("storage") |
| 774 | ); | 744 | ); |
| 775 | } | 745 | } |
| 776 | - | ||
| 777 | - #[test] | ||
| 778 | - fn an_explicit_max_upload_bytes_wins_and_absence_defaults_to_1gib() { | ||
| 779 | - let scratch = Scratch::new(); | ||
| 780 | - scratch.write(&FULL.replace( | ||
| 781 | - "max_upload_bytes = 1073741824", | ||
| 782 | - "max_upload_bytes = 67108864", | ||
| 783 | - )); | ||
| 784 | - assert_eq!(scratch.load().unwrap().max_upload_bytes, 67108864); | ||
| 785 | - // A file silent about the key still loads, at the 1 GiB default, and | ||
| 786 | - // is completed with the key for the next boot to read. | ||
| 787 | - let scratch = Scratch::new(); | ||
| 788 | - scratch.write(&FULL.replace("max_upload_bytes = 1073741824\n", "")); | ||
| 789 | - assert_eq!( | ||
| 790 | - scratch.load().unwrap().max_upload_bytes, | ||
| 791 | - 1024 * 1024 * 1024 | ||
| 792 | - ); | ||
| 793 | - let completed = std::fs::read_to_string(scratch.dir.join(FILE_NAME)).unwrap(); | ||
| 794 | - assert!(completed.contains("max_upload_bytes = 1073741824")); | ||
| 795 | - } | ||
| 796 | - | ||
| 797 | - #[test] | ||
| 798 | - fn zero_max_upload_bytes_reads_as_unset() { | ||
| 799 | - // Zero names no usable ceiling — it would refuse every upload — so it | ||
| 800 | - // falls through to the 1 GiB default instead of becoming the limit. | ||
| 801 | - let scratch = Scratch::new(); | ||
| 802 | - scratch.write(&FULL.replace( | ||
| 803 | - "max_upload_bytes = 1073741824", | ||
| 804 | - "max_upload_bytes = 0", | ||
| 805 | - )); | ||
| 806 | - assert_eq!( | ||
| 807 | - scratch.load().unwrap().max_upload_bytes, | ||
| 808 | - 1024 * 1024 * 1024 | ||
| 809 | - ); | ||
| 810 | - } | ||
| 811 | } | 746 | } |
crates/in-core/src/store/mod.rsmodified+7 -0
| @@ -635,6 +635,13 @@ pub trait Store: 'static + Send + Sync { | |||
| 635 | /// active and unexpired, is refused. | 635 | /// active and unexpired, is refused. |
| 636 | async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result<UploadSession>; | 636 | async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result<UploadSession>; |
| 637 | 637 | ||
| 638 | + /// The indexes of a session's staged chunks, sorted ascending, read off | ||
| 639 | + /// the chunk files on disk — exactly what a resuming uploader may skip | ||
| 640 | + /// re-sending. An unknown session is [`StoreError::NotFound`]; the | ||
| 641 | + /// session's state is not checked, so an expired one still answers what | ||
| 642 | + /// it holds. | ||
| 643 | + async fn uploaded_chunks(&self, id: &str) -> Result<Vec<u64>>; | ||
| 644 | + | ||
| 638 | /// Assembles a session's chunks in order, rechecks the quota, sniffs the | 645 | /// Assembles a session's chunks in order, rechecks the quota, sniffs the |
| 639 | /// mime (never trusting anything the uploader said), writes the file, | 646 | /// mime (never trusting anything the uploader said), writes the file, |
| 640 | /// attempts a thumbnail for images and video, inserts the row and marks the session | 647 | /// attempts a thumbnail for images and video, inserts the row and marks the session |
crates/in-core/src/store/turso_store.rsmodified+22 -0
| @@ -596,6 +596,21 @@ fn staged_received(storage: &std::path::Path, id: &str) -> u64 { | |||
| 596 | } | 596 | } |
| 597 | total | 597 | total |
| 598 | } | 598 | } |
| 599 | + | ||
| 600 | +/// The indexes of the chunk files a session holds, unsorted — the same | ||
| 601 | +/// on-disk truth `staged_received` sums. | ||
| 602 | +fn staged_indexes(storage: &std::path::Path, id: &str) -> Vec<u64> { | ||
| 603 | + let dir = session_dir(storage, id); | ||
| 604 | + let entries = match std::fs::read_dir(&dir) { | ||
| 605 | + Ok(entries) => entries, | ||
| 606 | + Err(_) => return Vec::new(), | ||
| 607 | + }; | ||
| 608 | + entries | ||
| 609 | + .flatten() | ||
| 610 | + .filter(|entry| entry.path().is_file()) | ||
| 611 | + .filter_map(|entry| entry.file_name().to_str()?.parse::<u64>().ok()) | ||
| 612 | + .collect() | ||
| 613 | +} | ||
| 599 | /// Creates the storage tree — the root and one directory per payload kind — | 614 | /// Creates the storage tree — the root and one directory per payload kind — |
| 600 | /// and locks each to 0700 on unix. Every writer past `open` assumes the tree | 615 | /// and locks each to 0700 on unix. Every writer past `open` assumes the tree |
| 601 | /// is there. | 616 | /// is there. |
| @@ -2375,6 +2390,13 @@ impl Store for TursoStore { | |||
| 2375 | Ok(session) | 2390 | Ok(session) |
| 2376 | } | 2391 | } |
| 2377 | 2392 | ||
| 2393 | + async fn uploaded_chunks(&self, id: &str) -> Result<Vec<u64>> { | ||
| 2394 | + self.upload_session(id).await?.ok_or(StoreError::NotFound)?; | ||
| 2395 | + let mut indexes = staged_indexes(&self.storage, id); | ||
| 2396 | + indexes.sort_unstable(); | ||
| 2397 | + Ok(indexes) | ||
| 2398 | + } | ||
| 2399 | + | ||
| 2378 | async fn finish_upload(&self, id: &str) -> Result<File> { | 2400 | async fn finish_upload(&self, id: &str) -> Result<File> { |
| 2379 | let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?; | 2401 | let session = self.upload_session(id).await?.ok_or(StoreError::NotFound)?; |
| 2380 | if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() { | 2402 | if session.state != UploadState::Active || session.expires_at <= OffsetDateTime::now_utc() { |
crates/in-core/tests/store.rsmodified+29 -0
| @@ -760,6 +760,35 @@ async fn an_empty_upload_finishes_an_empty_file() { | |||
| 760 | assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), Vec::<u8>::new()); | 760 | assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), Vec::<u8>::new()); |
| 761 | } | 761 | } |
| 762 | 762 | ||
| 763 | +#[tokio::test] | ||
| 764 | +async fn uploaded_chunks_names_what_a_resume_may_skip() { | ||
| 765 | + let scratch = Scratch::open().await; | ||
| 766 | + let user = alice(&scratch.store).await; | ||
| 767 | + let session = scratch | ||
| 768 | + .store | ||
| 769 | + .create_upload_session(&user.id, None, "resume.bin", CHUNK_SIZE + 4) | ||
| 770 | + .await | ||
| 771 | + .unwrap(); | ||
| 772 | + assert_eq!( | ||
| 773 | + scratch.store.uploaded_chunks(&session.id).await.unwrap(), | ||
| 774 | + Vec::<u64>::new() | ||
| 775 | + ); | ||
| 776 | + // Out of order on purpose: the answer is read off the chunk files on | ||
| 777 | + // disk and comes back sorted, whatever order the calls arrived in. | ||
| 778 | + scratch.store.record_chunk(&session.id, 1, b"tail").await.unwrap(); | ||
| 779 | + assert_eq!(scratch.store.uploaded_chunks(&session.id).await.unwrap(), vec![1]); | ||
| 780 | + scratch | ||
| 781 | + .store | ||
| 782 | + .record_chunk(&session.id, 0, &vec![7u8; CHUNK_SIZE as usize]) | ||
| 783 | + .await | ||
| 784 | + .unwrap(); | ||
| 785 | + assert_eq!(scratch.store.uploaded_chunks(&session.id).await.unwrap(), vec![0, 1]); | ||
| 786 | + assert!(matches!( | ||
| 787 | + scratch.store.uploaded_chunks("no-such-session").await, | ||
| 788 | + Err(StoreError::NotFound) | ||
| 789 | + )); | ||
| 790 | +} | ||
| 791 | + | ||
| 763 | #[tokio::test] | 792 | #[tokio::test] |
| 764 | async fn uploads_abort_and_prune() { | 793 | async fn uploads_abort_and_prune() { |
| 765 | let scratch = Scratch::open().await; | 794 | let scratch = Scratch::open().await; |
crates/in-web/src/drive.rsmodified+86 -16
| @@ -1035,15 +1035,54 @@ async fn upload_script(cx: &Cx) -> Result { | |||
| 1035 | if (!answer.ok) { throw new Error(answer.err || 'start'); } \ | 1035 | if (!answer.ok) { throw new Error(answer.err || 'start'); } \ |
| 1036 | return answer.ok; \ | 1036 | return answer.ok; \ |
| 1037 | } \ | 1037 | } \ |
| 1038 | + /* A cut upload resumes: the session id waits in localStorage \ | ||
| 1039 | + under the file's identity, and a re-send of the same file \ | ||
| 1040 | + asks the server which chunks it already holds instead of \ | ||
| 1041 | + starting over. The store is best-effort — private windows may \ | ||
| 1042 | + refuse it, and an upload without it just cannot resume. */ \ | ||
| 1043 | + function resumeKey(folder, file) { return 'in-upload:' + (folder || '') + ':' + file.name + ':' + file.size; } \ | ||
| 1044 | + function saveResume(key, id) { try { window.localStorage.setItem(key, id); } catch (err) {} } \ | ||
| 1045 | + function loadResume(key) { try { return window.localStorage.getItem(key); } catch (err) { return null; } } \ | ||
| 1046 | + function dropResume(key) { try { window.localStorage.removeItem(key); } catch (err) {} } \ | ||
| 1047 | + /* A backoff the cancel button still interrupts: the flag is \ | ||
| 1048 | + polled, so a cancel during a wait does not ride out the \ | ||
| 1049 | + delay. */ \ | ||
| 1050 | + function wait(ms, u) { \ | ||
| 1051 | + return new Promise(function (resolve, reject) { \ | ||
| 1052 | + var timer = setTimeout(done, ms); \ | ||
| 1053 | + var watch = u ? setInterval(function () { if (u.cancelled) { cleanup(); reject(canceledErr()); } }, 100) : null; \ | ||
| 1054 | + function done() { cleanup(); resolve(); } \ | ||
| 1055 | + function cleanup() { clearTimeout(timer); if (watch) { clearInterval(watch); } } \ | ||
| 1056 | + }); \ | ||
| 1057 | + } \ | ||
| 1038 | async function sendBig(file, folder, onProgress, u) { \ | 1058 | async function sendBig(file, folder, onProgress, u) { \ |
| 1039 | - var session = await startChunked(folder, file.name, file.size); \ | 1059 | + var key = resumeKey(folder, file); \ |
| 1060 | + var session = null; \ | ||
| 1061 | + var staged = {}; \ | ||
| 1062 | + var saved = loadResume(key); \ | ||
| 1063 | + if (saved) { \ | ||
| 1064 | + var probe = await fetch('/api/upload/' + saved, { headers: { accept: 'application/json' } }); \ | ||
| 1065 | + var status = await probe.json(); \ | ||
| 1066 | + if (status.ok && status.ok.size_bytes === file.size && status.ok.chunk_size === LIMIT && status.ok.name === file.name) { \ | ||
| 1067 | + session = { id: saved }; \ | ||
| 1068 | + (status.ok.uploaded || []).forEach(function (index) { staged[index] = true; }); \ | ||
| 1069 | + } else { \ | ||
| 1070 | + dropResume(key); \ | ||
| 1071 | + } \ | ||
| 1072 | + } \ | ||
| 1073 | + if (!session) { \ | ||
| 1074 | + session = await startChunked(folder, file.name, file.size); \ | ||
| 1075 | + saveResume(key, session.id); \ | ||
| 1076 | + } \ | ||
| 1040 | /* The session id lives on the mirror entry, so the row's \ | 1077 | /* The session id lives on the mirror entry, so the row's \ |
| 1041 | cancel control still reaches the abort endpoint after a \ | 1078 | cancel control still reaches the abort endpoint after a \ |
| 1042 | soft navigation rebuilt the page around it. A cancel that \ | 1079 | soft navigation rebuilt the page around it. A cancel that \ |
| 1043 | landed during the start flight aborts the fresh session \ | 1080 | landed during the start flight aborts the fresh session \ |
| 1044 | - straight away instead of leaking it. */ \ | 1081 | + straight away instead of leaking it. Cancel also drops \ |
| 1082 | + the resume key: a deliberate cancel is not resumable. */ \ | ||
| 1045 | if (u) { \ | 1083 | if (u) { \ |
| 1046 | if (u.cancelled) { \ | 1084 | if (u.cancelled) { \ |
| 1085 | + dropResume(key); \ | ||
| 1047 | fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ | 1086 | fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ |
| 1048 | throw canceledErr(); \ | 1087 | throw canceledErr(); \ |
| 1049 | } \ | 1088 | } \ |
| @@ -1051,38 +1090,69 @@ async fn upload_script(cx: &Cx) -> Result { | |||
| 1051 | u.cancel = function () { \ | 1090 | u.cancel = function () { \ |
| 1052 | u.cancelled = true; \ | 1091 | u.cancelled = true; \ |
| 1053 | try { u.abortChunk(); } catch (err) {} \ | 1092 | try { u.abortChunk(); } catch (err) {} \ |
| 1093 | + dropResume(key); \ | ||
| 1054 | fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ | 1094 | fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ |
| 1055 | }; \ | 1095 | }; \ |
| 1056 | } \ | 1096 | } \ |
| 1057 | var total = Math.max(1, file.size); \ | 1097 | var total = Math.max(1, file.size); \ |
| 1058 | - var index = 0; \ | ||
| 1059 | var flight = null; \ | 1098 | var flight = null; \ |
| 1060 | if (u) { \ | 1099 | if (u) { \ |
| 1061 | u.abortChunk = function () { if (flight) { try { flight.abort(); } catch (err) {} } }; \ | 1100 | u.abortChunk = function () { if (flight) { try { flight.abort(); } catch (err) {} } }; \ |
| 1062 | } \ | 1101 | } \ |
| 1063 | - for (var off = 0; off < file.size; off += LIMIT, index++) { \ | 1102 | + /* A chunk that meets a network cut is retried in place with \ |
| 1103 | + a backoff; only after three misses does the upload fail — \ | ||
| 1104 | + and even then the resume key stays, so picking the file \ | ||
| 1105 | + again carries on where it stopped. An expired session \ | ||
| 1106 | + restarts the walk once against a fresh session; a second \ | ||
| 1107 | + expiry fails like any other error. */ \ | ||
| 1108 | + var restarted = false; \ | ||
| 1109 | + walk: for (var off = 0, index = 0; off < file.size; off += LIMIT, index++) { \ | ||
| 1064 | if (u && u.cancelled) { throw canceledErr(); } \ | 1110 | if (u && u.cancelled) { throw canceledErr(); } \ |
| 1065 | var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \ | 1111 | var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \ |
| 1066 | - flight = new AbortController(); \ | 1112 | + if (staged[index]) { onProgress((off + piece.size) / total); continue; } \ |
| 1067 | - var r; \ | 1113 | + var sent = false; \ |
| 1068 | - try { \ | 1114 | + for (var attempt = 0; attempt < 3 && !sent; attempt++) { \ |
| 1069 | - r = await fetch('/api/upload/' + session.id + '/' + index, { \ | ||
| 1070 | - method: 'PUT', \ | ||
| 1071 | - headers: { 'content-type': 'application/octet-stream' }, \ | ||
| 1072 | - body: piece, \ | ||
| 1073 | - signal: flight.signal \ | ||
| 1074 | - }); \ | ||
| 1075 | - } catch (err) { \ | ||
| 1076 | if (u && u.cancelled) { throw canceledErr(); } \ | 1115 | if (u && u.cancelled) { throw canceledErr(); } \ |
| 1077 | - throw err; \ | 1116 | + if (attempt > 0) { await wait(1000 * attempt, u); } \ |
| 1117 | + flight = new AbortController(); \ | ||
| 1118 | + var r; \ | ||
| 1119 | + try { \ | ||
| 1120 | + r = await fetch('/api/upload/' + session.id + '/' + index, { \ | ||
| 1121 | + method: 'PUT', \ | ||
| 1122 | + headers: { 'content-type': 'application/octet-stream' }, \ | ||
| 1123 | + body: piece, \ | ||
| 1124 | + signal: flight.signal \ | ||
| 1125 | + }); \ | ||
| 1126 | + } catch (err) { \ | ||
| 1127 | + if (u && u.cancelled) { throw canceledErr(); } \ | ||
| 1128 | + continue; \ | ||
| 1129 | + } \ | ||
| 1130 | + if (!r.ok) { continue; } \ | ||
| 1131 | + var answer = await r.json(); \ | ||
| 1132 | + if (answer.ok) { sent = true; } \ | ||
| 1133 | + else if (answer.err === 'UploadExpired' && !restarted) { \ | ||
| 1134 | + restarted = true; \ | ||
| 1135 | + dropResume(key); \ | ||
| 1136 | + session = await startChunked(folder, file.name, file.size); \ | ||
| 1137 | + saveResume(key, session.id); \ | ||
| 1138 | + if (u) { u.sessionId = session.id; } \ | ||
| 1139 | + staged = {}; \ | ||
| 1140 | + off = -LIMIT; \ | ||
| 1141 | + index = -1; \ | ||
| 1142 | + continue walk; \ | ||
| 1143 | + } \ | ||
| 1144 | + else { throw new Error(answer.err || 'chunk'); } \ | ||
| 1078 | } \ | 1145 | } \ |
| 1079 | - if (!r.ok) { throw new Error('chunk'); } \ | 1146 | + if (!sent) { throw new Error('chunk'); } \ |
| 1080 | onProgress((off + piece.size) / total); \ | 1147 | onProgress((off + piece.size) / total); \ |
| 1081 | } \ | 1148 | } \ |
| 1082 | if (u && u.cancelled) { throw canceledErr(); } \ | 1149 | if (u && u.cancelled) { throw canceledErr(); } \ |
| 1083 | var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \ | 1150 | var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \ |
| 1084 | var fin = await done.json(); \ | 1151 | var fin = await done.json(); \ |
| 1152 | + /* A refused finish keeps the chunks staged, so the key stays \ | ||
| 1153 | + too: picking the file again resumes into another finish. */ \ | ||
| 1085 | if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \ | 1154 | if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \ |
| 1155 | + dropResume(key); \ | ||
| 1086 | onProgress(1); \ | 1156 | onProgress(1); \ |
| 1087 | } \ | 1157 | } \ |
| 1088 | function sendSmall(action, folder, files, onProgress, u) { \ | 1158 | function sendSmall(action, folder, files, onProgress, u) { \ |
crates/in-web/src/files.rsmodified+0 -8
| @@ -784,16 +784,8 @@ async fn upload( | |||
| 784 | return Ok(back_to_folder(folder_id.as_deref(), None)); | 784 | return Ok(back_to_folder(folder_id.as_deref(), None)); |
| 785 | } | 785 | } |
| 786 | 786 | ||
| 787 | - let limit = crate::server::effective_upload_limit(cx).await; | ||
| 788 | - | ||
| 789 | let mut refusal: Option<Refusal> = None; | 787 | let mut refusal: Option<Refusal> = None; |
| 790 | for (name, bytes) in files { | 788 | for (name, bytes) in files { |
| 791 | - // One file may not pass the instance ceiling; oversize files never | ||
| 792 | - // reach the store. | ||
| 793 | - if bytes.len() as u64 > limit { | ||
| 794 | - refusal = Some(Refusal::UploadTooLarge); | ||
| 795 | - break; | ||
| 796 | - } | ||
| 797 | // The store sanitises the label, sniffs the mime off the bytes, | 789 | // The store sanitises the label, sniffs the mime off the bytes, |
| 798 | // checks the quota, writes the file and attempts the thumbnail. | 790 | // checks the quota, writes the file and attempts the thumbnail. |
| 799 | if let Err(error) = store | 791 | if let Err(error) = store |
crates/in-web/src/i18n.rsmodified+0 -10
| @@ -187,10 +187,6 @@ pub enum Key { | |||
| 187 | // File viewer. | 187 | // File viewer. |
| 188 | UploadedLabel, | 188 | UploadedLabel, |
| 189 | DownloadsLabel, | 189 | DownloadsLabel, |
| 190 | - // Wave-1 upload limits. | ||
| 191 | - UploadLimits, | ||
| 192 | - CurrentUploadLimit, | ||
| 193 | - MaxUploadBytes, | ||
| 194 | // Wave-2 drive additions (DriveBuild owns this block). | 190 | // Wave-2 drive additions (DriveBuild owns this block). |
| 195 | Options, | 191 | Options, |
| 196 | DropFilesToUpload, | 192 | DropFilesToUpload, |
| @@ -337,9 +333,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 337 | Saved => "Saved.", | 333 | Saved => "Saved.", |
| 338 | UploadedLabel => "Uploaded", | 334 | UploadedLabel => "Uploaded", |
| 339 | DownloadsLabel => "Downloads", | 335 | DownloadsLabel => "Downloads", |
| 340 | - UploadLimits => "Upload limit", | ||
| 341 | - CurrentUploadLimit => "Current limit", | ||
| 342 | - MaxUploadBytes => "Upload limit", | ||
| 343 | Options => "Options", | 336 | Options => "Options", |
| 344 | DropFilesToUpload => "Drop files to upload", | 337 | DropFilesToUpload => "Drop files to upload", |
| 345 | Dismiss => "Dismiss", | 338 | Dismiss => "Dismiss", |
| @@ -480,9 +473,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { | |||
| 480 | Saved => "Kaydedildi.", | 473 | Saved => "Kaydedildi.", |
| 481 | UploadedLabel => "Yüklendi", | 474 | UploadedLabel => "Yüklendi", |
| 482 | DownloadsLabel => "İndirme", | 475 | DownloadsLabel => "İndirme", |
| 483 | - UploadLimits => "Yükleme sınırı", | ||
| 484 | - CurrentUploadLimit => "Geçerli sınır", | ||
| 485 | - MaxUploadBytes => "Yükleme sınırı", | ||
| 486 | Options => "Seçenekler", | 476 | Options => "Seçenekler", |
| 487 | DropFilesToUpload => "Yüklemek için dosyaları bırakın", | 477 | DropFilesToUpload => "Yüklemek için dosyaları bırakın", |
| 488 | Dismiss => "Kapat", | 478 | Dismiss => "Kapat", |
crates/in-web/src/main.rsmodified+5 -5
| @@ -150,11 +150,11 @@ async fn main() { | |||
| 150 | let router = in_client::mount( | 150 | let router = in_client::mount( |
| 151 | Router::builder() | 151 | Router::builder() |
| 152 | .discover() | 152 | .discover() |
| 153 | - // BodyLimit is only a memory guard here, not the upload policy: the | 153 | + // BodyLimit is only a memory guard here, not the upload policy: |
| 154 | - // real per-file ceiling is the admin-controlled limit enforced in | 154 | + // the account quota, enforced in the store at start and finish, |
| 155 | - // the handlers (`effective_upload_limit`). `/files` takes whole | 155 | + // is the only size limit. `/files` takes whole multipart bodies, |
| 156 | - // multipart bodies, so its guard sits at a hard 2 GiB; `/api/upload` | 156 | + // so its guard sits at a hard 2 GiB; `/api/upload` carries single |
| 157 | - // carries single 8 MiB chunks, so 32 MiB leaves ample headroom. | 157 | + // 8 MiB chunks, so 32 MiB leaves ample headroom. |
| 158 | .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) | 158 | .layer(BodyLimit::max(32 * 1024 * 1024).at("/api/upload")) |
| 159 | .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files")) | 159 | .layer(BodyLimit::max(2usize * 1024 * 1024 * 1024).at("/files")) |
| 160 | .cookies() | 160 | .cookies() |
crates/in-web/src/server.rsmodified+2 -34
| @@ -216,10 +216,8 @@ pub enum Refusal { | |||
| 216 | BadTheme, | 216 | BadTheme, |
| 217 | /// The language field was not one of the values the form offers. | 217 | /// The language field was not one of the values the form offers. |
| 218 | BadLanguage, | 218 | BadLanguage, |
| 219 | - /// One file carries more bytes than the instance upload ceiling allows. | 219 | + /// The admin's quota form named something unusable — unparseable, or a |
| 220 | - UploadTooLarge, | 220 | + /// unit the form does not offer. |
| 221 | - /// The admin's upload-limit form named zero, which would refuse every upload. | ||
| 222 | - /// (The form speaks bytes, so nothing can overflow; zero is the only refusal.) | ||
| 223 | BadLimit, | 221 | BadLimit, |
| 224 | } | 222 | } |
| 225 | 223 | ||
| @@ -243,7 +241,6 @@ impl Refusal { | |||
| 243 | Refusal::BadUi => "That interface choice is not offered.".to_string(), | 241 | Refusal::BadUi => "That interface choice is not offered.".to_string(), |
| 244 | Refusal::BadTheme => "That is not a theme.".to_string(), | 242 | Refusal::BadTheme => "That is not a theme.".to_string(), |
| 245 | Refusal::BadLanguage => "That is not a language.".to_string(), | 243 | Refusal::BadLanguage => "That is not a language.".to_string(), |
| 246 | - Refusal::UploadTooLarge => "That file is larger than the upload limit.".to_string(), | ||
| 247 | Refusal::BadLimit => "That limit is not usable.".to_string(), | 244 | Refusal::BadLimit => "That limit is not usable.".to_string(), |
| 248 | } | 245 | } |
| 249 | } | 246 | } |
| @@ -269,7 +266,6 @@ impl Refusal { | |||
| 269 | Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(), | 266 | Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(), |
| 270 | Refusal::BadTheme => "Bu bir tema değil.".to_string(), | 267 | Refusal::BadTheme => "Bu bir tema değil.".to_string(), |
| 271 | Refusal::BadLanguage => "Bu bir dil değil.".to_string(), | 268 | Refusal::BadLanguage => "Bu bir dil değil.".to_string(), |
| 272 | - Refusal::UploadTooLarge => "Bu dosya yükleme sınırından büyük.".to_string(), | ||
| 273 | Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(), | 269 | Refusal::BadLimit => "Bu sınır kullanılamaz.".to_string(), |
| 274 | } | 270 | } |
| 275 | } | 271 | } |
| @@ -293,7 +289,6 @@ impl Refusal { | |||
| 293 | "bad-ui" => Refusal::BadUi, | 289 | "bad-ui" => Refusal::BadUi, |
| 294 | "bad-theme" => Refusal::BadTheme, | 290 | "bad-theme" => Refusal::BadTheme, |
| 295 | "bad-language" => Refusal::BadLanguage, | 291 | "bad-language" => Refusal::BadLanguage, |
| 296 | - "upload-too-large" => Refusal::UploadTooLarge, | ||
| 297 | "bad-limit" => Refusal::BadLimit, | 292 | "bad-limit" => Refusal::BadLimit, |
| 298 | _ => return None, | 293 | _ => return None, |
| 299 | }) | 294 | }) |
| @@ -321,38 +316,11 @@ impl Refusal { | |||
| 321 | Refusal::BadUi => "bad-ui", | 316 | Refusal::BadUi => "bad-ui", |
| 322 | Refusal::BadTheme => "bad-theme", | 317 | Refusal::BadTheme => "bad-theme", |
| 323 | Refusal::BadLanguage => "bad-language", | 318 | Refusal::BadLanguage => "bad-language", |
| 324 | - Refusal::UploadTooLarge => "upload-too-large", | ||
| 325 | Refusal::BadLimit => "bad-limit", | 319 | Refusal::BadLimit => "bad-limit", |
| 326 | } | 320 | } |
| 327 | } | 321 | } |
| 328 | } | 322 | } |
| 329 | 323 | ||
| 330 | -/// The instance setting holding the per-file upload ceiling, in bytes. | ||
| 331 | -/// Written by the admin's upload-limit form; read here. | ||
| 332 | -pub(crate) const MAX_UPLOAD_SETTING: &str = "max_upload_bytes"; | ||
| 333 | - | ||
| 334 | -/// The per-file upload ceiling in force for this request: the | ||
| 335 | -/// [`MAX_UPLOAD_SETTING`] instance setting first, then the | ||
| 336 | -/// `max_upload_bytes` key from `config/in.toml`, then 1 GiB when neither | ||
| 337 | -/// names one. | ||
| 338 | -/// | ||
| 339 | -/// A setting that is missing, unreadable, unparseable or zero falls through | ||
| 340 | -/// to the config default — the save form only ever writes positive integers, | ||
| 341 | -/// so anything else is a hand-edited row, not a choice. Quota is untouched: | ||
| 342 | -/// this caps one file's size, quota caps an account's total. | ||
| 343 | -pub(crate) async fn effective_upload_limit(cx: &Cx) -> u64 { | ||
| 344 | - let ctx = app(cx); | ||
| 345 | - match ctx.store.get_setting(MAX_UPLOAD_SETTING).await { | ||
| 346 | - Ok(Some(raw)) => raw | ||
| 347 | - .trim() | ||
| 348 | - .parse::<u64>() | ||
| 349 | - .ok() | ||
| 350 | - .filter(|limit| *limit > 0) | ||
| 351 | - .unwrap_or(ctx.config.max_upload_bytes), | ||
| 352 | - Ok(None) | Err(_) => ctx.config.max_upload_bytes, | ||
| 353 | - } | ||
| 354 | -} | ||
| 355 | - | ||
| 356 | /// Which call a carried refusal belongs to. Two forms on one page must not both | 324 | /// Which call a carried refusal belongs to. Two forms on one page must not both |
| 357 | /// claim the same sentence, so the redirect names the call and this is the name: | 325 | /// claim the same sentence, so the redirect names the call and this is the name: |
| 358 | /// the last piece of the server function's path, with anything that is not a | 326 | /// the last piece of the server function's path, with anything that is not a |
crates/in-web/src/settings.rsmodified+8 -67
| @@ -4,13 +4,11 @@ | |||
| 4 | //! quota usage bar beside it, and the reader's own live share links with | 4 | //! quota usage bar beside it, and the reader's own live share links with |
| 5 | //! their revoke buttons — including the copy-once banner after a creation | 5 | //! their revoke buttons — including the copy-once banner after a creation |
| 6 | //! (`?created=<token>` on the query, rendered once and never stored). | 6 | //! (`?created=<token>` on the query, rendered once and never stored). |
| 7 | -//! Admins additionally see every account with its quota and disabled flag, | 7 | +//! Admins additionally see every account with its quota and disabled flag in |
| 8 | -//! plus the instance-wide per-file upload limit in the same Everyone panel. | 8 | +//! the Everyone panel. `POST /api/settings/quota|disable` are admin-only: |
| 9 | -//! `POST /api/settings/quota|disable|upload-limit` are admin-only: the first | 9 | +//! the first sets a user's byte quota, the second disables or re-enables |
| 10 | -//! sets a user's byte quota, the second disables or re-enables them (a disabled | 10 | +//! them (a disabled account reads as signed-out everywhere, the im session |
| 11 | -//! account reads as signed-out everywhere, the im session untouched, and | 11 | +//! untouched, and disabling yourself is refused). |
| 12 | -//! disabling yourself is refused), and the third sets the per-file ceiling | ||
| 13 | -//! for the whole install. | ||
| 14 | 12 | ||
| 15 | use in_core::store::{ShareKind, User}; | 13 | use in_core::store::{ShareKind, User}; |
| 16 | use serde::Deserialize; | 14 | use serde::Deserialize; |
| @@ -78,9 +76,8 @@ fn trim_amount(value: f64) -> String { | |||
| 78 | } | 76 | } |
| 79 | 77 | ||
| 80 | /// The bytes an `(amount, unit)` pair names, or `None` when the pair is not | 78 | /// The bytes an `(amount, unit)` pair names, or `None` when the pair is not |
| 81 | -/// a usable limit: an unknown unit, or an amount that is not a finite | 79 | +/// a usable quota: an unknown unit, or an amount that is not a finite |
| 82 | -/// positive number. Callers decide whether zero passes (quota) or not | 80 | +/// positive number. |
| 83 | -/// (upload limit). | ||
| 84 | fn unit_bytes(amount: &str, unit: &str) -> Option<u64> { | 81 | fn unit_bytes(amount: &str, unit: &str) -> Option<u64> { |
| 85 | let per = match unit { | 82 | let per = match unit { |
| 86 | "MiB" => MIB_BYTES, | 83 | "MiB" => MIB_BYTES, |
| @@ -140,38 +137,6 @@ async fn set_quota(cx: &Cx, Form(input): Form<QuotaForm>) -> Redirect { | |||
| 140 | } | 137 | } |
| 141 | } | 138 | } |
| 142 | 139 | ||
| 143 | -#[derive(Deserialize)] | ||
| 144 | -struct UploadLimitForm { | ||
| 145 | - #[serde(default)] | ||
| 146 | - max_upload: String, | ||
| 147 | - #[serde(default)] | ||
| 148 | - max_upload_unit: String, | ||
| 149 | -} | ||
| 150 | -/// Sets the instance-wide per-file upload ceiling from a human-unit pair | ||
| 151 | -/// (`max_upload` amount in `max_upload_unit` MiB/GiB), converted to bytes | ||
| 152 | -/// for the `max_upload_bytes` instance setting — so `2 GiB` stores | ||
| 153 | -/// `2147483648` and the panel reads it back as `2.0 GiB`. The fallback chain | ||
| 154 | -/// in [`crate::server::effective_upload_limit`] is untouched, and zero (or | ||
| 155 | -/// anything unparseable) is refused with `BadLimit`: an install must always | ||
| 156 | -/// have a positive per-file ceiling. | ||
| 157 | -#[route(POST "/api/settings/upload-limit")] | ||
| 158 | -async fn set_upload_limit(cx: &Cx, Form(input): Form<UploadLimitForm>) -> Redirect { | ||
| 159 | - if let Err(refusal) = require_admin(cx).await { | ||
| 160 | - return redirect_back(cx, "upload-limit", Some(refusal)); | ||
| 161 | - } | ||
| 162 | - match unit_bytes(&input.max_upload, &input.max_upload_unit) { | ||
| 163 | - Some(bytes) if bytes > 0 => match app(cx) | ||
| 164 | - .store | ||
| 165 | - .set_setting(crate::server::MAX_UPLOAD_SETTING, &bytes.to_string()) | ||
| 166 | - .await | ||
| 167 | - { | ||
| 168 | - Ok(()) => redirect_back(cx, "upload-limit", None), | ||
| 169 | - Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))), | ||
| 170 | - }, | ||
| 171 | - _ => redirect_back(cx, "upload-limit", Some(Refusal::BadLimit)), | ||
| 172 | - } | ||
| 173 | -} | ||
| 174 | - | ||
| 175 | #[derive(Deserialize)] | 140 | #[derive(Deserialize)] |
| 176 | struct DisableForm { | 141 | struct DisableForm { |
| 177 | user_id: String, | 142 | user_id: String, |
| @@ -307,13 +272,6 @@ async fn settings(cx: &Cx) -> Result { | |||
| 307 | } else { | 272 | } else { |
| 308 | Vec::new() | 273 | Vec::new() |
| 309 | }; | 274 | }; |
| 310 | - // The live per-file ceiling, read once for the Everyone panel below. Only | ||
| 311 | - // admins see it, so only they pay the extra setting read. | ||
| 312 | - let upload_limit = if fresh.admin { | ||
| 313 | - Some(crate::server::effective_upload_limit(cx).await) | ||
| 314 | - } else { | ||
| 315 | - None | ||
| 316 | - }; | ||
| 317 | let created = created_token(uri(cx).query().unwrap_or("")); | 275 | let created = created_token(uri(cx).query().unwrap_or("")); |
| 318 | let origin = app(cx).config.listen_url(); | 276 | let origin = app(cx).config.listen_url(); |
| 319 | view! { | 277 | view! { |
| @@ -322,7 +280,7 @@ async fn settings(cx: &Cx) -> Result { | |||
| 322 | <div class="settings-shell"> | 280 | <div class="settings-shell"> |
| 323 | <main class="settings-stage stage-wide"> | 281 | <main class="settings-stage stage-wide"> |
| 324 | <h1 class="settings-title">(t(language, Key::Settings))</h1> | 282 | <h1 class="settings-title">(t(language, Key::Settings))</h1> |
| 325 | - (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "upload-limit"]).await?) | 283 | + (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences"]).await?) |
| 326 | if let Some(token) = created { | 284 | if let Some(token) = created { |
| 327 | <section class="panel"> | 285 | <section class="panel"> |
| 328 | <div class="panel-head"> | 286 | <div class="panel-head"> |
| @@ -465,23 +423,6 @@ async fn settings(cx: &Cx) -> Result { | |||
| 465 | </tbody> | 423 | </tbody> |
| 466 | </table> | 424 | </table> |
| 467 | </div> | 425 | </div> |
| 468 | - if let Some(limit) = upload_limit { | ||
| 469 | - // The instance-wide limit, one labeled row under the member table — | ||
| 470 | - // same compact amount+unit form the per-user quota cells use. | ||
| 471 | - <div class="upload-limit"> | ||
| 472 | - <span class="field-label">(t(language, Key::MaxUploadBytes))</span> | ||
| 473 | - <span class="field-note">(format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit)))</span> | ||
| 474 | - <div class="spacer"></div> | ||
| 475 | - <form class="pop-row-form member-quota" method="post" action="/api/settings/upload-limit"> | ||
| 476 | - <input class="field-input" type="number" name="max_upload" min="0" step="any" value=(bytes_as_unit(limit).0) aria-label=(t(language, Key::MaxUploadBytes))> | ||
| 477 | - <select class="field-input" name="max_upload_unit" aria-label=(t(language, Key::MaxUploadBytes))> | ||
| 478 | - <option value="MiB" selected=(bytes_as_unit(limit).1 == "MiB")>"MiB"</option> | ||
| 479 | - <option value="GiB" selected=(bytes_as_unit(limit).1 == "GiB")>"GiB"</option> | ||
| 480 | - </select> | ||
| 481 | - <button class="quiet" type="submit">(t(language, Key::Save))</button> | ||
| 482 | - </form> | ||
| 483 | - </div> | ||
| 484 | - } | ||
| 485 | </div> | 426 | </div> |
| 486 | </section> | 427 | </section> |
| 487 | } | 428 | } |
crates/in-web/src/upload.rsmodified+41 -10
| @@ -1,11 +1,12 @@ | |||
| 1 | //! The chunked-upload protocol. | 1 | //! The chunked-upload protocol. |
| 2 | //! | 2 | //! |
| 3 | -//! Four owner-only JSON calls, all UTF-8: `POST /api/upload/start` | 3 | +//! Five owner-only JSON calls, all UTF-8: `POST /api/upload/start` |
| 4 | //! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the | 4 | //! `{folder_id, name, size_bytes}` answers `{id, chunk_size}` with the |
| 5 | //! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota | 5 | //! server-fixed 8 MiB chunk size (`Refusal::QuotaExceeded` when the quota |
| 6 | -//! says no, `Refusal::UploadTooLarge` past the instance upload ceiling); | 6 | +//! says no — the account quota is the only size limit); `GET /api/upload/{id}` |
| 7 | -//! `PUT /api/upload/{id}/{index}` takes one raw chunk (32 MiB cap, layered | 7 | +//! answers the session with the indexes already staged, so an interrupted |
| 8 | -//! in `main.rs` — the real per-file ceiling lives in the start handler); | 8 | +//! upload resumes instead of starting over; `PUT /api/upload/{id}/{index}` |
| 9 | +//! takes one raw chunk (32 MiB cap, layered in `main.rs`); | ||
| 9 | //! `POST /api/upload/{id}/finish` assembles the | 10 | //! `POST /api/upload/{id}/finish` assembles the |
| 10 | //! staged chunks, sniffs the mime, moves the bytes to `files/<new file id>` | 11 | //! staged chunks, sniffs the mime, moves the bytes to `files/<new file id>` |
| 11 | //! and answers with the created file id; `POST /api/upload/{id}/abort` | 12 | //! and answers with the created file id; `POST /api/upload/{id}/abort` |
| @@ -110,12 +111,6 @@ async fn start(cx: &Cx, Json(input): Json<StartIn>) -> Result<Json<Answer<StartO | |||
| 110 | Err(_) => return Ok(Json(Answer::Err(Refusal::Unavailable))), | 111 | Err(_) => return Ok(Json(Answer::Err(Refusal::Unavailable))), |
| 111 | } | 112 | } |
| 112 | } | 113 | } |
| 113 | - // The instance ceiling is checked against the declared total before a | ||
| 114 | - // single chunk is sent: chunks can never add past the declared total | ||
| 115 | - // (the store refuses that), so this one check caps the whole session. | ||
| 116 | - if input.size_bytes > crate::server::effective_upload_limit(cx).await { | ||
| 117 | - return Ok(Json(Answer::Err(Refusal::UploadTooLarge))); | ||
| 118 | - } | ||
| 119 | match store | 114 | match store |
| 120 | .create_upload_session(&user.id, folder, &input.name, input.size_bytes) | 115 | .create_upload_session(&user.id, folder, &input.name, input.size_bytes) |
| 121 | .await | 116 | .await |
| @@ -163,6 +158,42 @@ async fn chunk(cx: &Cx, body: Bytes) -> Result<Json<Answer<ChunkOut>>> { | |||
| 163 | } | 158 | } |
| 164 | } | 159 | } |
| 165 | 160 | ||
| 161 | +#[derive(serde::Serialize)] | ||
| 162 | +struct StatusOut { | ||
| 163 | + id: String, | ||
| 164 | + chunk_size: u64, | ||
| 165 | + size_bytes: u64, | ||
| 166 | + name: String, | ||
| 167 | + folder_id: Option<String>, | ||
| 168 | + uploaded: Vec<u64>, | ||
| 169 | +} | ||
| 170 | + | ||
| 171 | +/// The session and the indexes already staged, for a resuming uploader: | ||
| 172 | +/// the client skips every index in `uploaded` and sends only what is | ||
| 173 | +/// missing. An expired session still answers — the chunks it holds are | ||
| 174 | +/// real until the sweep takes them — so the client reads the expiry off | ||
| 175 | +/// `chunk`'s refusal, not here. | ||
| 176 | +#[route(GET "/api/upload/{id}")] | ||
| 177 | +async fn status(cx: &Cx) -> Result<Json<Answer<StatusOut>>> { | ||
| 178 | + let id: &str = path_param::<Id>(cx); | ||
| 179 | + let session = match owned_session(cx, id).await { | ||
| 180 | + Ok(session) => session, | ||
| 181 | + Err(refusal) => return Ok(Json(Answer::Err(refusal))), | ||
| 182 | + }; | ||
| 183 | + let store = app(cx).store.clone(); | ||
| 184 | + match store.uploaded_chunks(&session.id).await { | ||
| 185 | + Ok(uploaded) => Ok(Json(Answer::Ok(StatusOut { | ||
| 186 | + id: session.id, | ||
| 187 | + chunk_size: session.chunk_size, | ||
| 188 | + size_bytes: session.size_bytes, | ||
| 189 | + name: session.name, | ||
| 190 | + folder_id: session.folder_id, | ||
| 191 | + uploaded, | ||
| 192 | + }))), | ||
| 193 | + Err(error) => Ok(Json(Answer::Err(store_refusal(error)))), | ||
| 194 | + } | ||
| 195 | +} | ||
| 196 | + | ||
| 166 | /// Assembles the staged chunks — rechecking the quota, sniffing the mime | 197 | /// Assembles the staged chunks — rechecking the quota, sniffing the mime |
| 167 | /// off the bytes, attempting the thumbnail — and answers the created file | 198 | /// off the bytes, attempting the thumbnail — and answers the created file |
| 168 | /// id. The chunks stay staged on refusal, so the browser may retry. | 199 | /// id. The chunks stay staged on refusal, so the browser may retry. |
crates/in-web/tests/http.rsmodified+73 -1
| @@ -282,7 +282,6 @@ impl TestApp { | |||
| 282 | live_seconds: 300, | 282 | live_seconds: 300, |
| 283 | purge_after_days: 30, | 283 | purge_after_days: 30, |
| 284 | default_quota_bytes: 10 * 1024 * 1024 * 1024, | 284 | default_quota_bytes: 10 * 1024 * 1024 * 1024, |
| 285 | - max_upload_bytes: 1024 * 1024 * 1024, | ||
| 286 | oidc: OidcConfig { | 285 | oidc: OidcConfig { |
| 287 | issuer: fake.url(), | 286 | issuer: fake.url(), |
| 288 | client_id: "in-test".to_string(), | 287 | client_id: "in-test".to_string(), |
| @@ -589,6 +588,10 @@ impl Raw { | |||
| 589 | fn text(&self) -> String { | 588 | fn text(&self) -> String { |
| 590 | String::from_utf8(self.bytes.clone()).unwrap() | 589 | String::from_utf8(self.bytes.clone()).unwrap() |
| 591 | } | 590 | } |
| 591 | + | ||
| 592 | + fn json(&self) -> serde_json::Value { | ||
| 593 | + serde_json::from_str(&self.text()).unwrap() | ||
| 594 | + } | ||
| 592 | } | 595 | } |
| 593 | 596 | ||
| 594 | /// Form encoding, enough for the names these tests send. | 597 | /// Form encoding, enough for the names these tests send. |
| @@ -885,6 +888,74 @@ async fn chunked_upload_round_trip() { | |||
| 885 | assert_eq!(row.owner_id, user.id); | 888 | assert_eq!(row.owner_id, user.id); |
| 886 | } | 889 | } |
| 887 | 890 | ||
| 891 | +#[tokio::test] | ||
| 892 | +async fn an_interrupted_upload_resumes_from_its_staged_chunks() { | ||
| 893 | + let app = TestApp::build().await; | ||
| 894 | + let cookie = app.sign_in("sub-resume", "resume@in.test", "Resume").await; | ||
| 895 | + | ||
| 896 | + // Two chunks: stage the first, ask the status what a resume may skip, | ||
| 897 | + // then land the second and finish. | ||
| 898 | + let total = 8 * 1024 * 1024 + 100; | ||
| 899 | + let mut bytes = Vec::with_capacity(total); | ||
| 900 | + for i in 0..total { | ||
| 901 | + bytes.push((i % 251) as u8); | ||
| 902 | + } | ||
| 903 | + let answer = app | ||
| 904 | + .post_json( | ||
| 905 | + "/api/upload/start", | ||
| 906 | + Some(&cookie), | ||
| 907 | + serde_json::json!({"folder_id": null, "name": "resume.bin", "size_bytes": total}), | ||
| 908 | + ) | ||
| 909 | + .await; | ||
| 910 | + let session = answer.json()["ok"]["id"] | ||
| 911 | + .as_str() | ||
| 912 | + .expect("start was refused") | ||
| 913 | + .to_string(); | ||
| 914 | + | ||
| 915 | + app.put_bytes( | ||
| 916 | + &format!("/api/upload/{session}/0"), | ||
| 917 | + Some(&cookie), | ||
| 918 | + &bytes[..8 * 1024 * 1024], | ||
| 919 | + ) | ||
| 920 | + .await; | ||
| 921 | + | ||
| 922 | + let status = app | ||
| 923 | + .get(&format!("/api/upload/{session}"), Some(&cookie)) | ||
| 924 | + .await; | ||
| 925 | + assert_eq!(status.status, StatusCode::OK, "{}", status.text()); | ||
| 926 | + let body = status.json(); | ||
| 927 | + assert_eq!(body["ok"]["size_bytes"].as_u64(), Some(total as u64)); | ||
| 928 | + assert_eq!(body["ok"]["chunk_size"].as_u64(), Some(8 * 1024 * 1024)); | ||
| 929 | + assert_eq!(body["ok"]["name"].as_str(), Some("resume.bin")); | ||
| 930 | + assert_eq!(body["ok"]["uploaded"], serde_json::json!([0])); | ||
| 931 | + | ||
| 932 | + // Another owner's probe of the same id is not found, not forbidden. | ||
| 933 | + let other = app.sign_in("sub-nosey", "nosey@in.test", "Nosey").await; | ||
| 934 | + let status = app | ||
| 935 | + .get(&format!("/api/upload/{session}"), Some(&other)) | ||
| 936 | + .await; | ||
| 937 | + assert_eq!(status.json()["err"].as_str(), Some("NotFound")); | ||
| 938 | + | ||
| 939 | + app.put_bytes( | ||
| 940 | + &format!("/api/upload/{session}/1"), | ||
| 941 | + Some(&cookie), | ||
| 942 | + &bytes[8 * 1024 * 1024..], | ||
| 943 | + ) | ||
| 944 | + .await; | ||
| 945 | + let answer = app | ||
| 946 | + .post_json( | ||
| 947 | + &format!("/api/upload/{session}/finish"), | ||
| 948 | + Some(&cookie), | ||
| 949 | + serde_json::json!({}), | ||
| 950 | + ) | ||
| 951 | + .await; | ||
| 952 | + let file_id = answer.json()["ok"] | ||
| 953 | + .as_str() | ||
| 954 | + .expect("finish was refused") | ||
| 955 | + .to_string(); | ||
| 956 | + let got = app.get(&format!("/file/{file_id}"), Some(&cookie)).await; | ||
| 957 | + assert_eq!(got.bytes, bytes); | ||
| 958 | +} | ||
| 888 | #[tokio::test] | 959 | #[tokio::test] |
| 889 | async fn range_request_serves_a_slice() { | 960 | async fn range_request_serves_a_slice() { |
| 890 | let app = TestApp::build().await; | 961 | let app = TestApp::build().await; |
| @@ -3350,3 +3421,4 @@ async fn an_empty_folder_says_how_to_fill_it() { | |||
| 3350 | assert!(body.contains("id=\"upload-form\""), "{body}"); | 3421 | assert!(body.contains("id=\"upload-form\""), "{body}"); |
| 3351 | assert!(body.contains("__inDrop"), "{body}"); | 3422 | assert!(body.contains("__inDrop"), "{body}"); |
| 3352 | } | 3423 | } |
| 3424 | + | ||
style/main.scssmodified+0 -11
| @@ -4801,17 +4801,6 @@ input[type="radio"] { | |||
| 4801 | flex: none; | 4801 | flex: none; |
| 4802 | } | 4802 | } |
| 4803 | 4803 | ||
| 4804 | -// The instance-wide upload limit: one labeled row under the register, the | ||
| 4805 | -// same compact amount+unit form the quota cells use. | ||
| 4806 | -.upload-limit { | ||
| 4807 | - display: flex; | ||
| 4808 | - align-items: center; | ||
| 4809 | - gap: 10px; | ||
| 4810 | - flex-wrap: wrap; | ||
| 4811 | - margin-top: 14px; | ||
| 4812 | - padding-top: 14px; | ||
| 4813 | - border-top: 1px solid var(--border); | ||
| 4814 | -} | ||
| 4815 | .member-table .member-col-address { | 4804 | .member-table .member-col-address { |
| 4816 | min-width: 26ch; | 4805 | min-width: 26ch; |
| 4817 | } | 4806 | } |