Skip to main content

coven_storage/
memory_connector.rs

1//! The in-memory provider as an application's storage connector: settings
2//! saved through the builder's connector hook, S3 detection that conforms to
3//! any settings, and the new-store check of a location that holds one store.
4use super::*;
5
6impl MemoryStorage {
7    /// Rename the store's folder as its owner would in Dropbox or OneDrive,
8    /// without a request: the next folder label read answers `name`.
9    pub async fn rename_folder(&self, name: &str) {
10        self.provider.state.lock().await.folder_name = name.into();
11    }
12    /// Replace or remove the location marker as an external actor, without a request.
13    pub async fn plant_location_marker(&self, bytes: Option<Vec<u8>>) {
14        self.provider.state.lock().await.location_marker = bytes;
15    }
16    /// Bind a simulated installation to the real synchronization gate, preserving
17    /// this provider's credentials, durable objects and request observations.
18    pub fn with_publication_gate(&self, publications: Arc<dyn PublicationGate>) -> Self {
19        Self::with_gate(
20            self.provider.clone(),
21            self.device,
22            publications,
23            self.cooldown.clone(),
24            self.transfers.clone(),
25            self.provider.clock.clone(),
26        )
27    }
28
29    /// Write for `device` on this simulated connection: what it stages sits
30    /// in that device's reserved folder (D10).
31    pub fn with_device(&self, device: coven_foundation::id_source::DeviceId) -> Self {
32        Self::with_gate(
33            self.provider.clone(),
34            device,
35            self.publications.clone(),
36            self.cooldown.clone(),
37            self.transfers.clone(),
38            self.provider.clock.clone(),
39        )
40    }
41
42    /// Bind this connection to the store's shared provider cooldown.
43    pub fn with_cooldown(&self, cooldown: Arc<dyn crate::Cooldown>) -> Self {
44        Self::with_gate(
45            self.provider.clone(),
46            self.device,
47            self.publications.clone(),
48            cooldown,
49            self.transfers.clone(),
50            self.provider.clock.clone(),
51        )
52    }
53
54    /// Use the handle's transfer budget on this simulated connection.
55    pub fn with_transfers(&self, transfers: Arc<crate::TransferBudget>) -> Self {
56        Self::with_gate(
57            self.provider.clone(),
58            self.device,
59            self.publications.clone(),
60            self.cooldown.clone(),
61            transfers,
62            self.provider.clock.clone(),
63        )
64    }
65
66    /// Erase the provider type while retaining this exact connection's
67    /// credentials.
68    pub fn shared_connection(&self) -> Arc<StorageConnection> {
69        let connection = StorageConnection::with_gate(
70            self.provider.clone() as Arc<dyn ProviderOps>,
71            self.device,
72            self.publications.clone(),
73            self.cooldown.clone(),
74            self.transfers.clone(),
75            self.provider.clock.clone(),
76        );
77        Arc::new(connection)
78    }
79}
80
81#[async_trait]
82impl crate::providers::StorageConnector for MemoryStorage {
83    async fn account_label(
84        &self,
85        auth: crate::ProviderAuth,
86        cooldown: Arc<dyn crate::Cooldown>,
87    ) -> Result<String, StorageError> {
88        self.connect(
89            self.config(),
90            auth,
91            self.device,
92            self.publications.clone(),
93            cooldown,
94            self.transfers.clone(),
95        )
96        .await?
97        .account()
98        .await
99    }
100
101    async fn signed_in_account(
102        &self,
103        auth: crate::ProviderAuth,
104        cooldown: Arc<dyn crate::Cooldown>,
105    ) -> Result<crate::ProviderAccount, StorageError> {
106        self.connect(
107            self.config(),
108            auth,
109            self.device,
110            self.publications.clone(),
111            cooldown,
112            self.transfers.clone(),
113        )
114        .await?
115        .account_identity()
116        .await
117    }
118
119    async fn prepare_cloudkit(
120        &self,
121        container: &str,
122        _store: coven_foundation::id_source::StoreId,
123    ) -> Result<StorageConfig, StorageError> {
124        let config = self.config();
125        if !matches!(&config, StorageConfig::CloudKit { container: expected, .. } if expected == container)
126        {
127            return Err(StorageFailure::InvalidConfiguration
128                .with_source("memory connector container mismatch"));
129        }
130        Ok(config)
131    }
132    async fn connect(
133        &self,
134        config: StorageConfig,
135        auth: crate::ProviderAuth,
136        device: coven_foundation::id_source::DeviceId,
137        publications: Arc<dyn crate::PublicationGate>,
138        cooldown: Arc<dyn crate::Cooldown>,
139        transfers: Arc<crate::TransferBudget>,
140    ) -> Result<Arc<StorageConnection>, StorageError> {
141        let connection = self
142            .connect_device(config, auth)
143            .await?
144            .with_device(device)
145            .with_publication_gate(publications)
146            .with_cooldown(cooldown)
147            .with_transfers(transfers);
148        Ok(connection.shared_connection())
149    }
150    /// Memory behaves as any settings demand: the detection conforms to the
151    /// location's own settings, or to plain S3 settings for detection.
152    /// Memory holds no probes, so no run, this one or an earlier one, has
153    /// left anything.
154    async fn detect_s3(
155        &self,
156        config: StorageConfig,
157        _credentials: crate::S3Credentials,
158        _store: coven_foundation::id_source::StoreId,
159        runs: &crate::S3DetectionRuns,
160        _waits: &crate::SetupWaits,
161    ) -> crate::S3DetectionRun {
162        let detection = async {
163            config.validate()?;
164            let StorageConfig::S3 { endpoint, profile, .. } = &config else {
165                return Err(StorageFailure::InvalidConfiguration.with_source("expected S3"));
166            };
167            Ok(conforming_detection(
168                crate::providers::s3_settings(endpoint.as_ref(), profile.as_ref())?
169                    .unwrap_or(DETECTED_S3_SETTINGS),
170            ))
171        }
172        .await;
173        let cleaned = std::iter::once(runs.run).chain(runs.earlier.iter().copied()).collect();
174        crate::S3DetectionRun { detection, cleaned }
175    }
176    /// Memory's objects are one location, which another store's object
177    /// occupies.
178    async fn check_new_store(
179        &self,
180        config: StorageConfig,
181        _auth: crate::ProviderAuth,
182        store: coven_foundation::id_source::StoreId,
183        _waits: &crate::SetupWaits,
184    ) -> Result<(), StorageError> {
185        config.validate()?;
186        if !config.holds_one_store() {
187            return Err(StorageFailure::InvalidConfiguration
188                .with_source("the location holds several stores, so nothing checks it"));
189        }
190        if self.provider.state.lock().await.objects.keys().any(|path| path.store() != store) {
191            return Err(StorageFailure::OwnLocationRequired.into());
192        }
193        Ok(())
194    }
195}
196
197/// What memory's detection reports where the location needs detection.
198pub const DETECTED_S3_SETTINGS: S3Settings = S3Settings {
199    signing: S3Signing::AwsSigV4,
200    single_put: S3SinglePut::IfNoneMatch,
201    copy_publication: S3CopyPublication::Never,
202    multipart_timestamp: S3MultipartTimestamp::Completion,
203    checksums: S3Checksums::Absent,
204    listing: S3Listing::V2,
205    revision: S3Revision::ETag,
206    response_headers: S3ResponseHeaders::S3,
207    request_checksums: false,
208};
209
210/// A detection whose every observation agrees with these settings.
211pub fn conforming_detection(settings: S3Settings) -> S3Detection {
212    let completion = settings.multipart_timestamp == S3MultipartTimestamp::Completion;
213    let results = [
214        (S3Probe::Signing(settings.signing), true),
215        (S3Probe::SinglePut(settings.single_put), true),
216        (S3Probe::PartialUploadHidden, true),
217        (S3Probe::ConditionalCompletion, settings.copy_publication == S3CopyPublication::Never),
218        (S3Probe::CompletionTimestamp, completion),
219        (S3Probe::CopyTimestamp, true),
220        (S3Probe::Listing(S3Listing::V1), true),
221        (S3Probe::Listing(settings.listing), true),
222        (S3Probe::ChecksumMode, settings.request_checksums),
223        (S3Probe::ChecksumReturned, settings.checksums != S3Checksums::Absent),
224        (S3Probe::ChecksumScopeStated, settings.checksums != S3Checksums::UnstatedIgnored),
225        (S3Probe::GoogleGeneration, settings.revision == S3Revision::Generation),
226        (S3Probe::GoogleHeaders, settings.response_headers == S3ResponseHeaders::Google),
227        (S3Probe::BucketList, true),
228    ]
229    .into_iter()
230    .chain(
231        settings
232            .copy_publication
233            .multipart()
234            .map(|condition| (S3Probe::CopyPublication(condition), true)),
235    )
236    .map(|(probe, held)| S3ProbeResult { probe, held, detail: "memory".into() })
237    .collect();
238    S3Detection { versioning: Ok(S3BucketVersioning::Disabled), settings, results }
239}