wezterm_blob_leases/storage.rs
1use crate::{ContentId, Error, LeaseId};
2use std::io::{BufRead, Seek};
3use std::sync::{Arc, Mutex};
4
5static STORAGE: Mutex<Option<Arc<dyn BlobStorage + Send + Sync + 'static>>> = Mutex::new(None);
6
7pub trait BufSeekRead: BufRead + Seek {}
8pub type BoxedReader = Box<dyn BufSeekRead + Send + Sync>;
9
10/// Implements the actual storage mechanism for blobs
11pub trait BlobStorage {
12 /// Store data with the provided content_id.
13 /// lease_id is provided by the caller to identify this store.
14 /// The underlying store is expected to dedup storing data with the same
15 /// content_id.
16 fn store(&self, content_id: ContentId, data: &[u8], lease_id: LeaseId) -> Result<(), Error>;
17
18 /// Resolve the data associated with content_id.
19 /// If found, establish a lease with the given lease_id.
20 /// If not found, returns Err(Error::ContentNotFound)
21 fn lease_by_content(&self, content_id: ContentId, lease_id: LeaseId) -> Result<(), Error>;
22
23 /// Retrieves the data identified by content_id.
24 /// lease_id is provided in order to advise the storage system
25 /// which lease fetched it, so that it can choose to record that
26 /// information to track the liveness of a lease
27 fn get_data(&self, content_id: ContentId, lease_id: LeaseId) -> Result<Vec<u8>, Error>;
28
29 /// Retrieves the data identified by content_id as a readable+seekable
30 /// buffered handle.
31 ///
32 /// lease_id is provided in order to advise the storage system
33 /// which lease fetched it, so that it can choose to record that
34 /// information to track the liveness of a lease.
35 ///
36 /// The returned handle serves to extend the lifetime of the lease.
37 fn get_reader(&self, content_id: ContentId, lease_id: LeaseId) -> Result<BoxedReader, Error>;
38
39 /// Advises the storage manager that a particular lease has been dropped.
40 fn advise_lease_dropped(&self, lease_id: LeaseId, content_id: ContentId) -> Result<(), Error>;
41 /// Advises the storage manager that a given process id is now, or
42 /// continues to be, alive and a valid consumer of the store.
43 fn advise_of_pid(&self, pid: u32) -> Result<(), Error>;
44
45 /// Advises the storage manager that a given process id is, or will
46 /// very shortly, terminate and will cease to be a valid consumer
47 /// of the store.
48 /// It may choose to do something to invalidate all leases with
49 /// a corresponding pid.
50 fn advise_pid_terminated(&self, pid: u32) -> Result<(), Error>;
51}
52
53pub fn register_storage(
54 storage: Arc<dyn BlobStorage + Send + Sync + 'static>,
55) -> Result<(), Error> {
56 STORAGE.lock().unwrap().replace(storage);
57 Ok(())
58}
59
60pub fn get_storage() -> Result<Arc<dyn BlobStorage + Send + Sync + 'static>, Error> {
61 STORAGE
62 .lock()
63 .unwrap()
64 .as_ref()
65 .map(|s| s.clone())
66 .ok_or_else(|| Error::StorageNotInit)
67}
68
69pub fn clear_storage() {
70 STORAGE.lock().unwrap().take();
71}