Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Save reservations: in-flight exclusion for same-file saves

Related: issue #2466 (duplicate same-file saves racing to the filename tag)
and PR #4193, which implements this design in `pkgs/id/src/web/`.

## Intent

The web save handler rate-limits saves per filename with a cooldown
(`SaveRateLimiter::check` / `record`), but the cooldown only sees
*completed* saves. Two overlapping saves of the same file — two
collaborators, or one client retrying while its first attempt is still
running — both passed the check and raced to write the filename tag,
so the later finisher silently overwrote the earlier one's snapshot
ordering. The limiter needed to refuse a second save while one is in
flight, not just after one has finished.

## Decision

1. **Reservation at the boundary.** `SaveRateLimiter::acquire(name)`
combines the existing cooldown check with an in-flight reservation,
taken atomically under the in-flight lock. If the name is already
reserved, `acquire` returns `Err(cooldown)` and the handler refuses
with the same `429 / "Try again in Ns"` contract clients already
handle for the cooldown, so no client change is needed to understand
the refusal — clients schedule their normal rate-limit retry.
2. **RAII permit.** On success `acquire` returns a `SavePermit` that
holds the reservation until it is dropped. The handler holds the
permit for its whole run:
- `SavePermit::complete()` (success path only) records the save for
the cooldown, then the reservation is released by `Drop` as the
permit goes out of scope.
- Dropping without `complete()` — every early error return in the
handler — releases the reservation and records nothing, so a
failed save strands neither the filename nor a cooldown it did
not earn.
3. **Synchronous std mutex for the in-flight set, deliberately.** The
set is touched only for O(1) insert/remove and is never held across
an await, and `Drop` cannot await — releasing the reservation from
`Drop` requires a synchronous lock. The cooldown map keeps its
`tokio::sync::Mutex` because it is only used from async contexts.
Poisoning is recovered with `into_inner()` on the acquire path: a
poisoned set must not wedge saves for a filename forever.
4. **Client retry survives the winner's broadcast.** The refusal makes
the losing client schedule a rate-limit retry; the winning save's
`notify_new_version` broadcast must not cancel that retry, because
the broadcast version by construction does not contain the rejected
snapshot. `AutoSaveManager.onNewVersion()` therefore leaves a
pending rate-limit retry (and the dirty state) untouched; the retry
persists the newer local snapshot when it fires. If the edits had
in fact already propagated, the retry is one redundant save — the
safe direction.

## Alternatives considered

- **Serialize instead of refuse** (queue the second save behind the
first): saves carry whole-document snapshots, so a queued stale
snapshot landing after the fresher one is exactly the overwrite
being fixed; the loser must re-read and re-decide, which is what the
client's retry after refusal already does.
- **Per-file async mutex held across the handler:** blocks rather than
refuses (same staleness problem), and cleanup on cancellation is
implicit in ways the explicit permit makes auditable.

## Consequences

- One in-flight save per filename per server process; a second is a
429 with the cooldown duration, indistinguishable on the wire from a
cooldown refusal.
- The reservation lifecycle is: `acquire` → handler runs → `complete`
(record + release) or drop (release only). Tests in
`pkgs/id/src/web/mod.rs` pin all three outcomes plus concurrent
acquires admitting exactly one save; `pkgs/id/web/src/auto-save.test.ts`
pins the client retry surviving a NewVersion broadcast.
117 changes: 116 additions & 1 deletion pkgs/id/src/web/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub use markdown::{

use axum::Router;
use iroh_blobs::api::Store;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
Expand Down Expand Up @@ -95,6 +95,14 @@ pub const DEFAULT_SAVE_COOLDOWN: Duration = Duration::from_secs(5);
pub struct SaveRateLimiter {
/// Map of filename → last save time.
last_save: Arc<Mutex<HashMap<String, Instant>>>,
/// Filenames with a save currently in flight (#2466). `check` alone
/// cannot stop overlapping saves — it only sees *completed* saves —
/// so `acquire` reserves the name here for the whole handler run and
/// a second same-file save is refused instead of racing the first.
/// A std mutex: the set is only touched for O(1) insert/remove, never
/// held across an await, and `SavePermit::drop` must release the
/// reservation synchronously on every handler exit path.
in_flight: Arc<std::sync::Mutex<HashSet<String>>>,
/// Minimum time between saves for the same file.
pub cooldown: Duration,
}
Expand All @@ -104,6 +112,7 @@ impl SaveRateLimiter {
pub fn new(cooldown: Duration) -> Self {
Self {
last_save: Arc::new(Mutex::new(HashMap::new())),
in_flight: Arc::new(std::sync::Mutex::new(HashSet::new())),
cooldown,
}
}
Expand All @@ -128,6 +137,30 @@ impl SaveRateLimiter {
Ok(())
}

/// Reserve a filename for a save that is about to run (#2466).
///
/// Combines the cooldown `check` with an in-flight reservation taken
/// atomically under the in-flight lock: if a save for the same name
/// is already running, returns `Err(self.cooldown)` so the caller can
/// refuse with the usual "Try again in Ns" contract instead of
/// racing the in-flight save to the filename tag. On success the
/// returned `SavePermit` holds the reservation until it is dropped —
/// on completion (after `complete` records the save) or on any early
/// error return, which releases the name without recording a save,
/// so a failed save never strands the filename.
pub async fn acquire(&self, name: &str) -> Result<SavePermit, Duration> {
Comment thread
dezren39 marked this conversation as resolved.
Resolved
self.check(name).await?;
let mut flight =
self.in_flight.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
if !flight.insert(name.to_owned()) {
return Err(self.cooldown);
Comment thread
dezren39 marked this conversation as resolved.
Resolved
}
Ok(SavePermit {
limiter: self.clone(),
name: name.to_owned(),
})
}

/// Record a successful save for the given filename.
pub async fn record(&self, name: &str) {
let mut map = self.last_save.lock().await;
Expand All @@ -139,6 +172,37 @@ impl SaveRateLimiter {
}
}

/// An in-flight save reservation handed out by `SaveRateLimiter::acquire`.
///
/// Dropping the permit releases the filename reservation. Call
/// `complete` once the save has succeeded so the cooldown is recorded;
/// dropping without completing (any early error path in the handler)
/// records nothing.
#[derive(Debug)]
pub struct SavePermit {
/// The limiter that issued the reservation (cloned handle).
limiter: SaveRateLimiter,
/// The reserved filename.
name: String,
}

impl SavePermit {
/// Record the save as successful and release the reservation.
pub async fn complete(self) {
self.limiter.record(&self.name).await;
// The reservation itself is released by Drop as `self` goes out
// of scope at the end of this call.
}
}

impl Drop for SavePermit {
fn drop(&mut self) {
if let Ok(mut flight) = self.limiter.in_flight.lock() {
flight.remove(&self.name);
}
}
}

/// Shared application state for web handlers.
///
/// Contains references to the blob store, collaborative editing state,
Expand Down Expand Up @@ -400,6 +464,57 @@ mod tests {
);
}

#[tokio::test]
async fn test_save_limiter_acquire_refuses_a_second_in_flight_save() {
let limiter = SaveRateLimiter::new(Duration::from_secs(5));
let _permit = limiter.acquire("a.txt").await.expect("first save proceeds");
let remaining = limiter.acquire("a.txt").await.unwrap_err();
assert_eq!(remaining, Duration::from_secs(5), "in-flight refusal quotes the cooldown");
assert!(
limiter.acquire("b.txt").await.is_ok(),
"a different file is not refused"
);
}

#[tokio::test]
async fn test_save_limiter_concurrent_acquires_admit_exactly_one() {
let limiter = SaveRateLimiter::new(Duration::from_secs(5));
let (first, second) = tokio::join!(
limiter.acquire("a.txt"),
limiter.acquire("a.txt")
);
let admitted = [first.is_ok(), second.is_ok()]
.into_iter()
.filter(|ok| *ok)
.count();
assert_eq!(admitted, 1, "exactly one overlapping save proceeds");
}

#[tokio::test]
async fn test_save_limiter_dropped_permit_releases_without_recording() {
let limiter = SaveRateLimiter::new(Duration::from_secs(5));
{
let _permit = limiter.acquire("a.txt").await.expect("first save proceeds");
} // dropped without complete(): the save failed / the handler bailed
assert!(
limiter.acquire("a.txt").await.is_ok(),
"a failed save strands neither the reservation nor a cooldown"
);
assert!(limiter.check("a.txt").await.is_ok(), "nothing was recorded");
}

#[tokio::test]
async fn test_save_limiter_completed_permit_records_the_cooldown() {
let limiter = SaveRateLimiter::new(Duration::from_secs(5));
let permit = limiter.acquire("a.txt").await.expect("first save proceeds");
permit.complete().await;
assert!(
limiter.acquire("a.txt").await.is_err(),
"the completed save's cooldown refuses the next save"
);
assert!(limiter.check("a.txt").await.is_err());
}

#[tokio::test]
async fn test_save_limiter_record_sweeps_expired_entries() {
let limiter = SaveRateLimiter::new(Duration::from_millis(60));
Expand Down
55 changes: 31 additions & 24 deletions pkgs/id/src/web/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1205,28 +1205,34 @@ async fn save_handler(State(state): State<AppState>, Json(req): Json<SaveRequest
req.name
);

// Check save rate limit
if let Err(remaining) = state.save_limiter.check(&req.name).await {
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
let secs = remaining.as_secs_f64().ceil() as u64;
tracing::info!(
"[routes] Save rate limited for '{}': {}s remaining",
req.name,
secs
);
// Structured refusal (#2244 P0-A): machine-readable reason and
// retry value in the body, `Retry-After` header alongside.
return (
StatusCode::TOO_MANY_REQUESTS,
[(header::RETRY_AFTER, secs.to_string())],
Json(serde_json::json!({
"error": format!("Save rate limited. Try again in {secs}s."),
"reason": "rate_limited",
"retry_after_ms": secs.saturating_mul(1_000),
})),
)
.into_response();
}
// Check save rate limit and reserve the filename for this save
// (#2466): a second save of the same file arriving while this one is
// in flight is refused here instead of racing to the filename tag.
// The permit releases the reservation on every exit path below.
let permit = match state.save_limiter.acquire(&req.name).await {
Ok(permit) => permit,
Err(remaining) => {
#[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
let secs = remaining.as_secs_f64().ceil() as u64;
tracing::info!(
"[routes] Save rate limited for '{}': {}s remaining",
req.name,
secs
);
// Structured refusal (#2244 P0-A): machine-readable reason and
// retry value in the body, `Retry-After` header alongside.
return (
StatusCode::TOO_MANY_REQUESTS,
[(header::RETRY_AFTER, secs.to_string())],
Json(serde_json::json!({
"error": format!("Save rate limited. Try again in {secs}s."),
"reason": "rate_limited",
"retry_after_ms": secs.saturating_mul(1_000),
})),
)
.into_response();
}
};

// Convert ProseMirror doc to the appropriate format based on file name
let bytes = match convert_doc_to_bytes(&req.name, &req.doc) {
Expand Down Expand Up @@ -1336,8 +1342,9 @@ async fn save_handler(State(state): State<AppState>, Json(req): Json<SaveRequest
.notify_new_version(&req.name, &new_hash_str)
.await;

// Record successful save for rate limiting
state.save_limiter.record(&req.name).await;
// Record successful save for rate limiting (also releases the
// in-flight reservation as the permit drops)
permit.complete().await;

Json(SaveResponse {
hash: new_hash_str,
Expand Down
51 changes: 51 additions & 0 deletions pkgs/id/web/src/auto-save.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,54 @@ describe("AutoSaveManager serialization (#1440)", () => {
expect(save.calls).toBe(1);
});
});

describe("AutoSaveManager.onNewVersion vs a pending rate-limit retry (#2466)", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});

it("does not cancel a pending rate-limit retry — the broadcast version cannot contain the rejected snapshot", async () => {
const save = deferredSaveFn();
const mgr = new AutoSaveManager(save.fn);

mgr.onContentChange();
mgr.saveNow();
await flush();
expect(save.calls).toBe(1);

// Refused: another client's save was in flight on the server (#2466).
save.resolveNext({ ok: false, retryAfterMs: 5000 });
await flush();
expect(mgr.state).toBe("rate-limited");

// The winning save now broadcasts NewVersion. The retry must survive:
// this client's snapshot is not in that broadcast version.
mgr.onNewVersion();
expect(mgr.state).toBe("rate-limited");

await vi.advanceTimersByTimeAsync(5000);
expect(save.calls).toBe(2);
save.resolveNext({ ok: true });
await flush();
expect(mgr.state).toBe("saved");
});

it("still marks the document saved on NewVersion when no retry is pending", async () => {
const save = deferredSaveFn();
const mgr = new AutoSaveManager(save.fn);

mgr.onContentChange();
expect(mgr.state).toBe("unsaved");

mgr.onNewVersion();
expect(mgr.state).toBe("saved");

// The pending debounce was cancelled — no save of the superseded doc.
await vi.advanceTimersByTimeAsync(10_000);
expect(save.calls).toBe(0);
expect(mgr.state).toBe("idle");
});
});
11 changes: 11 additions & 0 deletions pkgs/id/web/src/auto-save.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ export class AutoSaveManager {

/** Called when another client saves (NewVersion received) */
onNewVersion(): void {
// A pending rate-limit retry means a save of THIS client's newer
// snapshot was refused — with the #2466 in-flight exclusion, by the
// very save whose broadcast this is — so the broadcast version cannot
// contain that snapshot. Cancelling the retry here would mark
// never-persisted content as saved and lose it: keep the retry (and
// the rate-limited state) and let it persist the snapshot when it
// fires. If the edits had already propagated, the retry is one
// redundant save — the safe direction.
if (this.retryTimer !== null) {
return;
}
// Cancel any pending save — their version is newer
if (this.debounceTimer !== null) {
clearTimeout(this.debounceTimer);
Expand Down
Loading