mirror of
https://github.com/lexmount/moli.git
synced 2026-11-23 16:02:35 +00:00
fix(storage): isolate bucket quota waits
Run quota waits independently for each bucket so a blocked bucket does not stall unrelated storage. Keep deletion and shutdown ordered with the existing lifecycle. Validation: cargo fmt --all; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo nextest run --no-fail-fast.
This commit is contained in:
@@ -125,34 +125,28 @@ async fn idb_sqlite_bucket_delete_continues_after_the_accepting_page_retires() {
|
||||
.bucket_identity(&storage_key(), "retire")
|
||||
.unwrap();
|
||||
let storage = store.lock().storage_service();
|
||||
// Keep maintenance before the deletion itself starts, so retirement is
|
||||
// tested before metadata publication as well as before SQL cleanup.
|
||||
let (entered, waiting) = std::sync::mpsc::channel();
|
||||
let (release, resume) = std::sync::mpsc::channel();
|
||||
let default = moli_storage_service::StorageBucketLocator::default_bucket(storage_key());
|
||||
// Contention selects the maintenance queue; the uncontended fast path
|
||||
// uses the distinct file-I/O queue and would not gate this operation.
|
||||
let select_maintenance = storage.reserve_quota_commit(&default);
|
||||
storage
|
||||
.dispatch_opfs_quota_commit(
|
||||
default,
|
||||
move |_| {
|
||||
entered.send(()).unwrap();
|
||||
resume
|
||||
.recv_timeout(std::time::Duration::from_secs(10))
|
||||
.unwrap();
|
||||
},
|
||||
|result| {
|
||||
result.unwrap();
|
||||
},
|
||||
)
|
||||
// A real earlier bucket operation holds the maintenance sequence before
|
||||
// the target deletion can publish metadata or clean up SQL. OPFS quota
|
||||
// work deliberately uses an independent queue.
|
||||
let gate = store
|
||||
.lock()
|
||||
.open_bucket(&storage_key(), "retirement-gate")
|
||||
.unwrap();
|
||||
drop(select_maintenance);
|
||||
waiting
|
||||
.recv_timeout(std::time::Duration::from_secs(10))
|
||||
.unwrap();
|
||||
// The final marker must select the same maintenance queue as deletion.
|
||||
let quota = storage.reserve_quota_commit(&identity.locator());
|
||||
let gate_quota = storage.reserve_quota_commit(&gate.locator());
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
moli_storage_service::prepare_sql_bucket_maintenance(
|
||||
&store,
|
||||
moli_storage_service::SqlBucketOperation::Delete {
|
||||
storage_key: storage_key(),
|
||||
name: "retirement-gate".into(),
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.dispatch(move |reply| {
|
||||
let _ = sender.send(reply);
|
||||
})
|
||||
.unwrap();
|
||||
page.eval(r#"
|
||||
globalThis.deletionSettled = false;
|
||||
navigator.storageBuckets.delete('retire').then(() => deletionSettled = true, () => deletionSettled = true);
|
||||
@@ -163,26 +157,24 @@ async fn idb_sqlite_bucket_delete_continues_after_the_accepting_page_retires() {
|
||||
.unwrap(),
|
||||
"false:42"
|
||||
);
|
||||
assert!(store.lock().pending_deletions().is_empty());
|
||||
assert!(
|
||||
store
|
||||
.lock()
|
||||
.pending_deletions()
|
||||
.iter()
|
||||
.all(|old| old != &identity),
|
||||
"the target deletion must still be behind the earlier maintenance operation"
|
||||
);
|
||||
assert!(store.lock().bucket_identity_is_live(&identity));
|
||||
// This marker is behind deletion on the existing maintenance sequence.
|
||||
// Its receipt proves metadata publication and cleanup ran after Page drop.
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
storage
|
||||
.dispatch_opfs_quota_commit(
|
||||
identity.locator(),
|
||||
|_| (),
|
||||
move |reply| {
|
||||
let _ = sender.send(reply);
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
drop(page);
|
||||
release.send(()).unwrap();
|
||||
drop(quota);
|
||||
drop(gate_quota);
|
||||
// The public maintenance receipt covers both deletion jobs, including
|
||||
// the one whose accepting Page and Promise owner have already retired.
|
||||
storage.drain_maintenance().unwrap();
|
||||
receiver
|
||||
.recv_timeout(std::time::Duration::from_secs(10))
|
||||
.unwrap()
|
||||
.result
|
||||
.unwrap();
|
||||
assert!(store.lock().pending_deletions().is_empty());
|
||||
assert_eq!(
|
||||
|
||||
@@ -57,7 +57,7 @@ impl SqlBucketDeletion {
|
||||
clear,
|
||||
} = self;
|
||||
let worker_service = service.clone();
|
||||
service.quota_wait_queue.dispatch(
|
||||
service.maintenance_queue.dispatch(
|
||||
move || -> std::result::Result<(), String> {
|
||||
let _quota = worker_service.reserve_quota_commit(&identity.locator());
|
||||
// Another queued delete may already have completed this exact
|
||||
|
||||
@@ -120,7 +120,7 @@ impl Fixture {
|
||||
self.store
|
||||
.lock()
|
||||
.storage_service()
|
||||
.quota_wait_queue
|
||||
.maintenance_queue
|
||||
.dispatch(
|
||||
move || {
|
||||
entered.send(()).unwrap();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! SQL submissions retain the shared bucket reservation through publication.
|
||||
//! Waiting and aggregate usage sampling happen outside both V8 and SQL workers.
|
||||
//! Quota contention occupies no worker; usage sampling is off V8 and SQL.
|
||||
|
||||
use super::*;
|
||||
use moli_indexeddb::{
|
||||
@@ -20,15 +20,12 @@ impl StorageBucketQuotaOwner {
|
||||
mut command: Command,
|
||||
completion: impl FnOnce(Result<Completion, IndexedDbError>) + Send + 'static,
|
||||
) -> Result<(), crate::StorageServiceDispatchError> {
|
||||
let quota_coordinator = self.storage_service.quota_coordinator.clone();
|
||||
let locator = self.locator.clone();
|
||||
let owner = self.clone();
|
||||
let sampling_client = client.clone();
|
||||
self.storage_service.quota_wait_queue.dispatch(
|
||||
move || {
|
||||
// Acquire only after this job starts. Holding a reservation
|
||||
// while queued can deadlock an earlier job waiting for it.
|
||||
let quota = quota_coordinator.reserve(&locator);
|
||||
self.storage_service.dispatch_quota_commit(
|
||||
locator,
|
||||
move |quota| {
|
||||
let check = owner.indexed_db_quota_check(&sampling_client);
|
||||
(quota, check)
|
||||
},
|
||||
|
||||
@@ -115,7 +115,7 @@ impl Fixture {
|
||||
let (release, resume) = mpsc::channel();
|
||||
self.owner
|
||||
.storage_service
|
||||
.quota_wait_queue
|
||||
.quota_queue
|
||||
.dispatch(
|
||||
move || {
|
||||
entered.send(()).unwrap();
|
||||
@@ -274,3 +274,128 @@ fn aborting_during_quota_wait_prevents_a_delayed_commit_from_publishing_data() {
|
||||
));
|
||||
receive(&fixture.commit(&client)).unwrap().result.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_waiting_bucket_does_not_block_another_buckets_sql_commit() {
|
||||
let first = Fixture::new();
|
||||
let store = &first.owner.store;
|
||||
let identity = store
|
||||
.lock()
|
||||
.open_bucket("test-storage-key", "independent")
|
||||
.unwrap();
|
||||
let second = Fixture {
|
||||
owner: storage_bucket_quota_owner(store, &identity.locator()).unwrap(),
|
||||
_manager: first._manager.clone(),
|
||||
};
|
||||
assert!(Arc::ptr_eq(
|
||||
&first.owner.storage_service,
|
||||
&second.owner.storage_service
|
||||
));
|
||||
let blocked = first.database("waiting-for-quota");
|
||||
let independent = second.database("independent");
|
||||
let token = first.owner.reserve_commit();
|
||||
let waiting = first.commit(&blocked);
|
||||
let progressing = second.commit(&independent);
|
||||
receive(&progressing).unwrap().result.unwrap();
|
||||
assert_eq!(independent.committed().unwrap().version, 2);
|
||||
assert_eq!(blocked.committed().unwrap().version, 1);
|
||||
assert!(matches!(waiting.try_recv(), Err(mpsc::TryRecvError::Empty)));
|
||||
drop(token);
|
||||
receive(&waiting).unwrap().result.unwrap();
|
||||
assert_eq!(blocked.committed().unwrap().version, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocked_bucket_maintenance_cannot_block_ready_sql_quota_work() {
|
||||
let first = Fixture::new();
|
||||
let store = &first.owner.store;
|
||||
let identity = store
|
||||
.lock()
|
||||
.open_bucket("test-storage-key", "independent")
|
||||
.unwrap();
|
||||
let second = Fixture {
|
||||
owner: storage_bucket_quota_owner(store, &identity.locator()).unwrap(),
|
||||
_manager: first._manager.clone(),
|
||||
};
|
||||
let blocked = first.database("waiting-behind-maintenance");
|
||||
let independent = second.database("independent");
|
||||
let token = first.owner.reserve_commit();
|
||||
let coordinator = first.owner.storage_service.quota_coordinator.clone();
|
||||
let locator = first.owner.locator.clone();
|
||||
let (entered, waiting) = mpsc::channel();
|
||||
let (done, completed) = mpsc::channel();
|
||||
first
|
||||
.owner
|
||||
.storage_service
|
||||
.maintenance_queue
|
||||
.dispatch(
|
||||
move || {
|
||||
entered.send(()).unwrap();
|
||||
let _quota = coordinator.reserve(&locator);
|
||||
},
|
||||
move |result| {
|
||||
done.send(result).unwrap();
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
receive(&waiting);
|
||||
let first_reply = first.commit(&blocked);
|
||||
let second_reply = second.commit(&independent);
|
||||
receive(&second_reply).unwrap().result.unwrap();
|
||||
assert_eq!(independent.committed().unwrap().version, 2);
|
||||
assert!(matches!(
|
||||
first_reply.try_recv(),
|
||||
Err(mpsc::TryRecvError::Empty)
|
||||
));
|
||||
drop(token);
|
||||
receive(&first_reply).unwrap().result.unwrap();
|
||||
receive(&completed).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_dispatches_a_waiting_quota_commit_before_closing_sql() {
|
||||
let fixture = Fixture::new();
|
||||
let client = fixture.database("shutdown-with-quota-waiter");
|
||||
let token = fixture.owner.reserve_commit();
|
||||
let reply = fixture.commit(&client);
|
||||
let service = fixture.owner.storage_service.clone();
|
||||
let manager = fixture._manager.clone();
|
||||
let (started, starting) = mpsc::channel();
|
||||
let (done, finished) = mpsc::channel();
|
||||
let shutdown = std::thread::spawn(move || {
|
||||
started.send(()).unwrap();
|
||||
service.drain_maintenance().unwrap();
|
||||
manager.lock().shutdown_sqlite().unwrap();
|
||||
done.send(()).unwrap();
|
||||
});
|
||||
receive(&starting);
|
||||
// The accepted commit cannot be dispatched while this exact bucket's
|
||||
// reservation is held. Shutdown must keep SQL alive until it can be sent.
|
||||
assert!(finished.recv_timeout(Duration::from_millis(50)).is_err());
|
||||
drop(token);
|
||||
receive(&finished);
|
||||
receive(&reply).unwrap().result.unwrap();
|
||||
shutdown.join().unwrap();
|
||||
assert!(client.is_retired());
|
||||
assert_eq!(client.committed().unwrap().version, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maintenance_drain_rejects_a_quota_worker_before_waiting_on_its_own_reservation() {
|
||||
let fixture = Fixture::new();
|
||||
let service = fixture.owner.storage_service.clone();
|
||||
let draining = service.clone();
|
||||
let locator = fixture.owner.locator.clone();
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
service
|
||||
.dispatch_quota_commit(
|
||||
locator,
|
||||
move |_quota| draining.drain_maintenance(),
|
||||
move |result| sender.send(result).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
receive(&receiver).unwrap(),
|
||||
Err(crate::StorageServiceDispatchError::ReentrantDrain)
|
||||
));
|
||||
}
|
||||
|
||||
@@ -191,7 +191,7 @@ impl SqlBucketMaintenance {
|
||||
operation,
|
||||
} = self;
|
||||
let service = store.lock().storage_service();
|
||||
service.quota_wait_queue.dispatch(
|
||||
service.maintenance_queue.dispatch(
|
||||
move || -> std::result::Result<SqlBucketOperationValue, String> {
|
||||
if sql.is_closed() {
|
||||
return Err("IndexedDB storage service is closed".into());
|
||||
|
||||
@@ -175,7 +175,7 @@ fn bucket_creation_is_queued_before_identity_publication_and_leaves_sql_availabl
|
||||
let (release, resume) = mpsc::channel();
|
||||
let gate = Gate(Some(release));
|
||||
storage
|
||||
.quota_wait_queue
|
||||
.maintenance_queue
|
||||
.dispatch(
|
||||
move || {
|
||||
entered.send(()).unwrap();
|
||||
|
||||
@@ -42,16 +42,19 @@ impl Error for StorageServiceDispatchError {
|
||||
}
|
||||
|
||||
/// Failure produced while executing one accepted storage IO task.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub enum StorageServiceTaskError {
|
||||
/// The operation panicked. The queue catches it so later tasks can still run.
|
||||
Panicked,
|
||||
/// A deferred quota waiter could not enqueue its now-ready operation.
|
||||
Dispatch(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for StorageServiceTaskError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Panicked => f.write_str("storage IO task panicked"),
|
||||
Self::Dispatch(error) => f.write_str(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -187,6 +190,14 @@ fn advance_cancelled_storage_tickets(state: &mut StorageIoSequenceState) {
|
||||
}
|
||||
|
||||
impl StorageIoQueue {
|
||||
pub(crate) fn ensure_started(&self) -> Result<(), StorageServiceDispatchError> {
|
||||
self.sender().map(|_| ())
|
||||
}
|
||||
|
||||
pub(crate) fn is_worker_thread(&self) -> bool {
|
||||
self.state.lock().worker == Some(thread::current().id())
|
||||
}
|
||||
|
||||
/// The caller has stopped producers. Wait only on the partition owner,
|
||||
/// never on this queue's worker or a V8 event loop.
|
||||
pub(crate) fn drain(&self) -> Result<(), StorageServiceDispatchError> {
|
||||
|
||||
@@ -59,7 +59,8 @@ struct OpfsUniqueIdKey {
|
||||
pub struct StorageService {
|
||||
opfs: Opfs,
|
||||
io_queue: io_queue::StorageIoQueue,
|
||||
quota_wait_queue: io_queue::StorageIoQueue,
|
||||
maintenance_queue: io_queue::StorageIoQueue,
|
||||
quota_queue: io_queue::StorageIoQueue,
|
||||
io_sequence: io_queue::StorageIoSequence,
|
||||
quota_coordinator: quota::StorageQuotaCoordinator,
|
||||
opfs_unique_ids: Arc<Mutex<HashMap<OpfsUniqueIdKey, String>>>,
|
||||
@@ -72,7 +73,17 @@ impl StorageService {
|
||||
/// After renderer/network producers join, finish accepted quota and bucket
|
||||
/// maintenance jobs before shutting down the SQL service they may use.
|
||||
pub fn drain_maintenance(&self) -> Result<(), StorageServiceDispatchError> {
|
||||
self.quota_wait_queue.drain()
|
||||
if [&self.io_queue, &self.maintenance_queue, &self.quota_queue]
|
||||
.into_iter()
|
||||
.any(|queue| queue.is_worker_thread())
|
||||
{
|
||||
return Err(StorageServiceDispatchError::ReentrantDrain);
|
||||
}
|
||||
// Maintenance may wait for a quota holder, whose ready work runs on
|
||||
// the independent quota queue while SQL is still alive.
|
||||
self.maintenance_queue.drain()?;
|
||||
self.quota_coordinator.wait_for_dispatch();
|
||||
self.quota_queue.drain()
|
||||
}
|
||||
|
||||
/// After SQL shutdown, finish accepted OPFS work before releasing a profile.
|
||||
@@ -85,7 +96,8 @@ impl StorageService {
|
||||
Arc::new(Self {
|
||||
opfs: Opfs::in_memory(),
|
||||
io_queue: io_queue::StorageIoQueue::default(),
|
||||
quota_wait_queue: io_queue::StorageIoQueue::default(),
|
||||
maintenance_queue: io_queue::StorageIoQueue::default(),
|
||||
quota_queue: io_queue::StorageIoQueue::default(),
|
||||
io_sequence: io_queue::StorageIoSequence::default(),
|
||||
quota_coordinator: quota::StorageQuotaCoordinator::default(),
|
||||
opfs_unique_ids: Arc::new(Mutex::new(HashMap::new())),
|
||||
@@ -97,7 +109,8 @@ impl StorageService {
|
||||
Ok(Arc::new(Self {
|
||||
opfs: Opfs::on_disk(opfs_root)?,
|
||||
io_queue: io_queue::StorageIoQueue::default(),
|
||||
quota_wait_queue: io_queue::StorageIoQueue::default(),
|
||||
maintenance_queue: io_queue::StorageIoQueue::default(),
|
||||
quota_queue: io_queue::StorageIoQueue::default(),
|
||||
io_sequence: io_queue::StorageIoSequence::default(),
|
||||
quota_coordinator: quota::StorageQuotaCoordinator::default(),
|
||||
opfs_unique_ids: Arc::new(Mutex::new(HashMap::new())),
|
||||
@@ -148,6 +161,41 @@ impl StorageService {
|
||||
self.quota_coordinator.reserve(locator)
|
||||
}
|
||||
|
||||
/// Acquire quota before enqueueing work. A busy bucket retains only its
|
||||
/// callback; it never occupies the shared storage worker while waiting.
|
||||
pub(crate) fn dispatch_quota_commit<T, Operation, Completion>(
|
||||
&self,
|
||||
locator: StorageBucketLocator,
|
||||
operation: Operation,
|
||||
completion: Completion,
|
||||
) -> Result<(), StorageServiceDispatchError>
|
||||
where
|
||||
T: Send + 'static,
|
||||
Operation: FnOnce(StorageQuotaReservation) -> T + Send + 'static,
|
||||
Completion: FnOnce(Result<T, StorageServiceTaskError>) + Send + 'static,
|
||||
{
|
||||
let queue = self.quota_queue.clone();
|
||||
queue.ensure_started()?;
|
||||
let completion = Arc::new(Mutex::new(Some(completion)));
|
||||
self.quota_coordinator.reserve_async(locator, move |quota| {
|
||||
let delivered = completion.clone();
|
||||
let submitted = queue.dispatch(
|
||||
move || operation(quota),
|
||||
move |result| {
|
||||
if let Some(completion) = delivered.lock().take() {
|
||||
completion(result);
|
||||
}
|
||||
},
|
||||
);
|
||||
if let Err(error) = submitted
|
||||
&& let Some(completion) = completion.lock().take()
|
||||
{
|
||||
completion(Err(StorageServiceTaskError::Dispatch(error.to_string())));
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run one synchronous OPFS commit under the bucket quota reservation and
|
||||
/// the partition's ordered storage sequence, in that lock order.
|
||||
pub fn with_opfs_quota_commit<T>(
|
||||
@@ -163,9 +211,9 @@ impl StorageService {
|
||||
///
|
||||
/// An uncontended reservation is captured synchronously so later OPFS
|
||||
/// submissions cannot overtake this commit. A contended reservation waits
|
||||
/// on a separate storage worker and does not reserve an OPFS sequence turn;
|
||||
/// this lets the current quota holder take the fresh OPFS usage snapshot
|
||||
/// it needs before releasing the bucket.
|
||||
/// in the coordinator without occupying a worker or OPFS sequence turn;
|
||||
/// this lets the current quota holder take its fresh usage snapshot before
|
||||
/// releasing the bucket and enqueueing the next commit.
|
||||
pub fn dispatch_opfs_quota_commit<T, Operation, Completion>(
|
||||
&self,
|
||||
locator: StorageBucketLocator,
|
||||
@@ -192,9 +240,10 @@ impl StorageService {
|
||||
}
|
||||
|
||||
let io_sequence = self.io_sequence.clone();
|
||||
self.quota_wait_queue.dispatch(
|
||||
move || {
|
||||
let _quota = quota_coordinator.reserve(&locator);
|
||||
self.dispatch_quota_commit(
|
||||
locator,
|
||||
move |quota| {
|
||||
let _quota = quota;
|
||||
let _turn = io_sequence.reserve().enter();
|
||||
operation(&opfs)
|
||||
},
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, VecDeque},
|
||||
fmt,
|
||||
panic::{AssertUnwindSafe, catch_unwind},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use parking_lot::{Condvar, Mutex};
|
||||
|
||||
use crate::StorageBucketLocator;
|
||||
|
||||
/// Partition-owned serializer for aggregate bucket quota commits.
|
||||
///
|
||||
/// Backend staging may happen independently, but every commit which can grow
|
||||
/// a bucket must hold one reservation while it takes a fresh aggregate
|
||||
/// usage snapshot and publishes the backend mutation. Reservations are scoped
|
||||
/// by persistent bucket locator, so unrelated buckets remain independent.
|
||||
type QuotaReady = Box<dyn FnOnce(StorageQuotaReservation) + Send>;
|
||||
|
||||
/// Serialize aggregate quota publication for each persistent bucket. Async
|
||||
/// callers wait here without occupying a storage or SQLite worker.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct StorageQuotaCoordinator {
|
||||
inner: Arc<StorageQuotaCoordinatorInner>,
|
||||
@@ -17,8 +20,27 @@ pub(crate) struct StorageQuotaCoordinator {
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct StorageQuotaCoordinatorInner {
|
||||
active: Mutex<BTreeSet<StorageBucketLocator>>,
|
||||
released: Condvar,
|
||||
state: Mutex<QuotaState>,
|
||||
changed: Condvar,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct QuotaState {
|
||||
active: BTreeSet<StorageBucketLocator>,
|
||||
waiting: BTreeMap<StorageBucketLocator, VecDeque<QuotaReady>>,
|
||||
ready: VecDeque<(StorageBucketLocator, QuotaReady)>,
|
||||
draining: bool,
|
||||
}
|
||||
|
||||
impl fmt::Debug for QuotaState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("QuotaState")
|
||||
.field("active", &self.active)
|
||||
.field("waiting_buckets", &self.waiting.len())
|
||||
.field("ready", &self.ready.len())
|
||||
.field("draining", &self.draining)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl StorageQuotaCoordinator {
|
||||
@@ -26,12 +48,10 @@ impl StorageQuotaCoordinator {
|
||||
&self,
|
||||
locator: &StorageBucketLocator,
|
||||
) -> Option<StorageQuotaReservation> {
|
||||
let mut active = self.inner.active.lock();
|
||||
if active.contains(locator) {
|
||||
let mut state = self.inner.state.lock();
|
||||
if !state.active.insert(locator.clone()) {
|
||||
return None;
|
||||
}
|
||||
let inserted = active.insert(locator.clone());
|
||||
debug_assert!(inserted, "free bucket quota reservation must be insertable");
|
||||
Some(StorageQuotaReservation {
|
||||
coordinator: self.clone(),
|
||||
locator: Some(locator.clone()),
|
||||
@@ -39,32 +59,112 @@ impl StorageQuotaCoordinator {
|
||||
}
|
||||
|
||||
pub(crate) fn reserve(&self, locator: &StorageBucketLocator) -> StorageQuotaReservation {
|
||||
let mut active = self.inner.active.lock();
|
||||
while active.contains(locator) {
|
||||
self.inner.released.wait(&mut active);
|
||||
let mut state = self.inner.state.lock();
|
||||
while state.active.contains(locator) {
|
||||
self.inner.changed.wait(&mut state);
|
||||
}
|
||||
let inserted = active.insert(locator.clone());
|
||||
debug_assert!(inserted, "waited bucket quota reservation must be free");
|
||||
state.active.insert(locator.clone());
|
||||
StorageQuotaReservation {
|
||||
coordinator: self.clone(),
|
||||
locator: Some(locator.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The callback only enqueues work; it never performs storage I/O itself.
|
||||
pub(crate) fn reserve_async(
|
||||
&self,
|
||||
locator: StorageBucketLocator,
|
||||
ready: impl FnOnce(StorageQuotaReservation) + Send + 'static,
|
||||
) {
|
||||
let ready: QuotaReady = Box::new(ready);
|
||||
let drain = {
|
||||
let mut state = self.inner.state.lock();
|
||||
if !state.active.insert(locator.clone()) {
|
||||
state.waiting.entry(locator).or_default().push_back(ready);
|
||||
return;
|
||||
}
|
||||
state.enqueue_ready(locator, ready)
|
||||
};
|
||||
if drain {
|
||||
self.drain_ready();
|
||||
}
|
||||
}
|
||||
|
||||
fn drain_ready(&self) {
|
||||
loop {
|
||||
let next = {
|
||||
let mut state = self.inner.state.lock();
|
||||
let next = state.ready.pop_front();
|
||||
if next.is_none() {
|
||||
state.draining = false;
|
||||
}
|
||||
next
|
||||
};
|
||||
let Some((locator, ready)) = next else {
|
||||
self.inner.changed.notify_all();
|
||||
return;
|
||||
};
|
||||
// A failed enqueue may immediately drop its reservation. Drain
|
||||
// handoffs iteratively, including panicking completion callbacks.
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| {
|
||||
ready(StorageQuotaReservation {
|
||||
coordinator: self.clone(),
|
||||
locator: Some(locator),
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Shutdown waits for accepted waiters to enqueue their work, rather than
|
||||
/// shutting down SQL while a quota callback still needs to submit to it.
|
||||
/// Synchronous reservations without pending async work do not delay this.
|
||||
pub(crate) fn wait_for_dispatch(&self) {
|
||||
let mut state = self.inner.state.lock();
|
||||
while !state.waiting.is_empty() || state.draining {
|
||||
self.inner.changed.wait(&mut state);
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&self, locator: StorageBucketLocator) {
|
||||
let mut active = self.inner.active.lock();
|
||||
let removed = active.remove(&locator);
|
||||
debug_assert!(removed, "released bucket quota reservation must be active");
|
||||
drop(active);
|
||||
self.inner.released.notify_all();
|
||||
let drain = {
|
||||
let mut state = self.inner.state.lock();
|
||||
let next = state
|
||||
.waiting
|
||||
.get_mut(&locator)
|
||||
.and_then(VecDeque::pop_front);
|
||||
if state.waiting.get(&locator).is_some_and(VecDeque::is_empty) {
|
||||
state.waiting.remove(&locator);
|
||||
}
|
||||
match next {
|
||||
Some(ready) => state.enqueue_ready(locator, ready),
|
||||
None => {
|
||||
let removed = state.active.remove(&locator);
|
||||
debug_assert!(removed, "released bucket quota reservation must be active");
|
||||
false
|
||||
}
|
||||
}
|
||||
};
|
||||
self.inner.changed.notify_all();
|
||||
if drain {
|
||||
self.drain_ready();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned reservation for one bucket's aggregate quota commit window.
|
||||
///
|
||||
/// The reservation is `Send`, so an asynchronous storage task can acquire it
|
||||
/// on the storage worker and release it before its owner-thread completion is
|
||||
/// delivered. Dropping it on any error or panic always releases the bucket.
|
||||
impl QuotaState {
|
||||
fn enqueue_ready(&mut self, locator: StorageBucketLocator, ready: QuotaReady) -> bool {
|
||||
self.ready.push_back((locator, ready));
|
||||
if self.draining {
|
||||
false
|
||||
} else {
|
||||
self.draining = true;
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Owned guard for one bucket's aggregate publication window. Release before
|
||||
/// delivering the result; dropping on error also advances the next waiter.
|
||||
#[derive(Debug)]
|
||||
pub struct StorageQuotaReservation {
|
||||
coordinator: StorageQuotaCoordinator,
|
||||
@@ -72,7 +172,6 @@ pub struct StorageQuotaReservation {
|
||||
}
|
||||
|
||||
impl StorageQuotaReservation {
|
||||
/// Return the exact persistent bucket protected by this reservation.
|
||||
pub fn locator(&self) -> &StorageBucketLocator {
|
||||
self.locator
|
||||
.as_ref()
|
||||
@@ -173,4 +272,53 @@ mod tests {
|
||||
}
|
||||
assert_eq!(peak.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn async_waiters_preserve_bucket_fifo_without_blocking_other_buckets() {
|
||||
let coordinator = StorageQuotaCoordinator::default();
|
||||
let first = coordinator.reserve(&named_bucket(1));
|
||||
let (sender, receiver) = mpsc::channel();
|
||||
for index in [1, 2] {
|
||||
let sender = sender.clone();
|
||||
coordinator.reserve_async(named_bucket(1), move |guard| {
|
||||
sender.send((index, guard)).unwrap();
|
||||
});
|
||||
}
|
||||
coordinator.reserve_async(named_bucket(2), move |guard| {
|
||||
sender.send((3, guard)).unwrap();
|
||||
});
|
||||
let (index, unrelated) = receiver.recv_timeout(Duration::from_secs(1)).unwrap();
|
||||
assert_eq!(index, 3);
|
||||
drop(unrelated);
|
||||
assert!(receiver.try_recv().is_err());
|
||||
drop(first);
|
||||
let (index, second) = receiver.recv_timeout(Duration::from_secs(1)).unwrap();
|
||||
assert_eq!(index, 1);
|
||||
assert!(receiver.try_recv().is_err());
|
||||
drop(second);
|
||||
let (index, third) = receiver.recv_timeout(Duration::from_secs(1)).unwrap();
|
||||
assert_eq!(index, 2);
|
||||
coordinator.wait_for_dispatch();
|
||||
assert!(coordinator.try_reserve(&named_bucket(1)).is_none());
|
||||
drop(third);
|
||||
assert!(coordinator.try_reserve(&named_bucket(1)).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediately_released_async_waiters_do_not_recurse_or_stall_after_a_panic() {
|
||||
let coordinator = StorageQuotaCoordinator::default();
|
||||
let first = coordinator.reserve(&named_bucket(1));
|
||||
let completed = Arc::new(AtomicUsize::new(0));
|
||||
for index in 0..10_000 {
|
||||
let completed = completed.clone();
|
||||
coordinator.reserve_async(named_bucket(1), move |_guard| {
|
||||
completed.fetch_add(1, Ordering::Relaxed);
|
||||
assert_ne!(index, 5_000, "injected callback panic");
|
||||
});
|
||||
}
|
||||
drop(first);
|
||||
coordinator.wait_for_dispatch();
|
||||
assert_eq!(completed.load(Ordering::Relaxed), 10_000);
|
||||
assert!(coordinator.try_reserve(&named_bucket(1)).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user