forge
Explore
Log in

Don't you dare go Hollow

in-core: staged chunk sessions count against quota; temp names not received bytes

Browse files at this commit

3133ade7dc241e35cbbd5859736270b50c84478aAhmet Kaan GümüşParent: f31aab3
- staged_claim(): active upload sessions' declared sizes join every quota
  check (single put, session open, finish, external push) — N concurrent
  sessions can no longer overshoot the ceiling N times
- staged_received skips write_file_atomic temp names
- quota test rewritten to the reservation contract
crates/in-core/src/store/turso_store.rsmodified+34 -4
@@ -547,6 +547,26 @@ async fn check_quota(conn: &Connection, owner_id: &str) -> Result<(u64, u64)> {
547547 }
548548 }
549549
550+/// The bytes this owner's in-flight chunk sessions have already claimed:
551+/// their declared full sizes while they are still arriving. Quota checks
552+/// count them, so N concurrent sessions cannot each see an empty library
553+/// and overshoot the ceiling N times over. `except` lets a finishing
554+/// session not count its own claim against itself.
555+async fn staged_claim(conn: &Connection, owner_id: &str, except: Option<&str>) -> Result<u64> {
556+ let mut rows = conn
557+ .query(
558+ "SELECT COALESCE(SUM(size_bytes), 0) FROM upload_session \
559+ WHERE owner_id = ?1 AND state = 'active' AND (?2 IS NULL OR id != ?2)",
560+ params![owner_id, except],
561+ )
562+ .await
563+ .map_err(backend)?;
564+ match rows.next().await.map_err(backend)? {
565+ Some(row) => Ok(row.get::<i64>(0).map_err(backend)?.max(0) as u64),
566+ None => Ok(0),
567+ }
568+}
569+
550570 fn fit_quota(quota: u64, used: u64, extra: u64) -> Result<()> {
551571 // A zero-byte write costs nothing, so it always fits — even under an
552572 // account whose quota was lowered below current usage, which must still
@@ -756,7 +776,12 @@ fn staged_received(storage: &std::path::Path, id: &str) -> u64 {
756776 Err(_) => return 0,
757777 };
758778 for entry in entries.flatten() {
759- if entry.path().is_file() {
779+ // A mid-write temp name from write_file_atomic is not received
780+ // bytes: it exists between create and rename, and a crash leaves it
781+ // for the boot sweep — neither state belongs in the sum.
782+ let name = entry.file_name();
783+ let is_tmp = name.to_string_lossy().ends_with(".tmp");
784+ if !is_tmp && entry.path().is_file() {
760785 total = total.saturating_add(entry.metadata().map(|m| m.len()).unwrap_or(0));
761786 }
762787 }
@@ -1533,7 +1558,8 @@ impl Store for TursoStore {
15331558 .map_err(backend)?;
15341559 check_live_parent(&tx, owner_id, folder_id).await?;
15351560 let (quota, used) = check_quota(&tx, owner_id).await?;
1536- fit_quota(quota, used, size)?;
1561+ let claimed = staged_claim(&tx, owner_id, None).await?;
1562+ fit_quota(quota, used.saturating_add(claimed), size)?;
15371563 // A live sibling wearing the name is no refusal: the file takes the
15381564 // first free `stem (2).ext` postfix instead.
15391565 let name = free_file_name(&tx, owner_id, folder_id, &name, None).await?;
@@ -2508,7 +2534,8 @@ impl Store for TursoStore {
25082534 let conn = self.conn.lock().await;
25092535 check_live_parent_on(&conn, owner_id, folder_id).await?;
25102536 let (quota, used) = check_quota(&conn, owner_id).await?;
2511- fit_quota(quota, used, size_bytes)?;
2537+ let claimed = staged_claim(&conn, owner_id, None).await?;
2538+ fit_quota(quota, used.saturating_add(claimed), size_bytes)?;
25122539 let id = Ulid::generate().to_string();
25132540 let now = OffsetDateTime::now_utc();
25142541 let created = stamp(now)?;
@@ -2703,7 +2730,8 @@ impl Store for TursoStore {
27032730 finishable_session(&tx, id).await?;
27042731 check_live_parent(&tx, &session.owner_id, session.folder_id.as_deref()).await?;
27052732 let (quota, used) = check_quota(&tx, &session.owner_id).await?;
2706- fit_quota(quota, used, session.size_bytes)?;
2733+ let claimed = staged_claim(&tx, &session.owner_id, Some(id)).await?;
2734+ fit_quota(quota, used.saturating_add(claimed), session.size_bytes)?;
27072735 // A live sibling wearing the session's name is no refusal: the
27082736 // finished file takes the first free `stem (2).ext` postfix.
27092737 free_file_name(
@@ -3051,6 +3079,8 @@ impl Store for TursoStore {
30513079 .await
30523080 .map_err(backend)?;
30533081 let (quota, used) = check_quota(&tx, owner_id).await?;
3082+ let claimed = staged_claim(&tx, owner_id, None).await?;
3083+ let used = used.saturating_add(claimed);
30543084 let mut rows = tx
30553085 .query(
30563086 "SELECT id, size_bytes FROM file WHERE owner_id = ?1 AND external_id = ?2",
crates/in-core/tests/store.rsmodified+10 -9
@@ -630,24 +630,25 @@ async fn quota_is_enforced_at_start_and_at_finish() {
630630 Err(StoreError::QuotaExceeded)
631631 ));
632632
633- // Fits at open, over quota by finish: the chunks stay staged for another
634- // attempt once space is freed.
633+ // A staged session's declared size is a reservation: nothing else — not
634+ // a direct write, not a second session — may spend those bytes while
635+ // the chunks arrive, and the finish re-checks against everything else
636+ // that landed since the open (the claim itself excluded).
635637 let session = scratch
636638 .store
637639 .create_upload_session(&user.id, None, "late", 90)
638640 .await
639641 .unwrap();
640642 scratch.store.record_chunk(&session.id, 0, &[7u8; 90]).await.unwrap();
641- scratch.store.insert_file(&user.id, None, "filler", &[0u8; 20]).await.unwrap();
642643 assert!(matches!(
643- scratch.store.finish_upload(&session.id).await,
644+ scratch.store.insert_file(&user.id, None, "filler", &[0u8; 20]).await,
644645 Err(StoreError::QuotaExceeded)
645646 ));
646- let back = scratch.store.upload_session(&session.id).await.unwrap().unwrap();
647- assert_eq!(back.state, UploadState::Active);
648-
649- // Room freed, the same chunks finish.
650- scratch.store.set_user_quota(&user.id, 200).await.unwrap();
647+ assert!(matches!(
648+ scratch.store.create_upload_session(&user.id, None, "second", 20).await,
649+ Err(StoreError::QuotaExceeded)
650+ ));
651+ // The reservation is honored at finish: the room it set aside is there.
651652 let file = scratch.store.finish_upload(&session.id).await.unwrap();
652653 assert_eq!(file.size_bytes, 90);
653654 }