Skip to main content

link_cli/storage/
decorator_impls.rs

1//! [`LinksStorage`] implementations for the CLI's in-memory decorators.
2//!
3//! These make [`LinkStorage`], [`PinnedTypesDecorator`] and
4//! [`NamedTypesDecorator`] usable anywhere the generic transactions layer
5//! expects a storage, without changing their existing inherent API.
6//!
7//! # Durability
8//!
9//! All three keep their links in memory and rewrite the whole database
10//! file on [`LinksStorage::flush`], so **`flush` (or the inherent `save`)
11//! is required for durability**: nothing reaches the disk before it. The
12//! rewrite atomically replaces the file, syncs it and (on Unix) its parent
13//! directory. Other processes must reload after acquiring their advisory lock.
14
15use doublets::data::LinkReference;
16
17use crate::error::LinkError;
18use crate::link::{GenericLink, Link};
19use crate::link_storage::LinkStorage;
20use crate::named_types::NamedTypesDecorator;
21use crate::pinned_types::PinnedTypesDecorator;
22use crate::storage::traits::{LinksStorage, LinksStorageRef, StorageRevision};
23
24fn storage_error(error: anyhow::Error) -> LinkError {
25    LinkError::StorageError(format!("{error:#}"))
26}
27
28/// Generates the delegating [`LinksStorage`]/[`LinksStorageRef`] impls
29/// shared by the three in-memory decorators, which expose the same
30/// inherent method set.
31macro_rules! impl_in_memory_links_storage {
32    ($type:ty, $create:expr, $flush:expr, $external:expr, $reload:expr $(, $extra:item)*) => {
33        impl LinksStorage<u32> for $type {
34            $($extra)*
35            fn create_link(&mut self, source: u32, target: u32) -> Result<u32, LinkError> {
36                #[allow(clippy::redundant_closure_call)]
37                Ok($create(self, source, target))
38            }
39
40            fn ensure_link_created(&mut self, index: u32) -> Result<u32, LinkError> {
41                Ok(self.ensure_created(index))
42            }
43
44            fn ensure_link_created_observed(
45                &mut self,
46                index: u32,
47                observer: &mut dyn FnMut(GenericLink<u32>, GenericLink<u32>),
48            ) -> Result<u32, LinkError> {
49                let existing = self.exists(index);
50                let created = self.ensure_created(index);
51                // These adapters remove intermediate allocations; only the
52                // requested address survives. Avoid copying every stored row.
53                if index != 0 && !existing {
54                    observer(GenericLink::null(), *self.get(index).expect("ensured row"));
55                }
56                Ok(created)
57            }
58
59            fn get_link(&self, index: u32) -> Option<GenericLink<u32>> {
60                self.get(index).copied()
61            }
62
63            fn link_exists(&self, index: u32) -> bool {
64                self.exists(index)
65            }
66
67            fn update_link(
68                &mut self,
69                index: u32,
70                source: u32,
71                target: u32,
72            ) -> Result<GenericLink<u32>, LinkError> {
73                self.update(index, source, target).map_err(storage_error)
74            }
75
76            fn restore_link(
77                &mut self,
78                index: u32,
79                source: u32,
80                target: u32,
81            ) -> Result<GenericLink<u32>, LinkError> {
82                self.update_raw(index, source, target).map_err(storage_error)
83            }
84
85            fn delete_link(&mut self, index: u32) -> Result<GenericLink<u32>, LinkError> {
86                self.delete(index).map_err(storage_error)
87            }
88
89            fn update_link_observed(
90                &mut self,
91                index: u32,
92                source: u32,
93                target: u32,
94                observer: &mut dyn FnMut(GenericLink<u32>, GenericLink<u32>),
95            ) -> Result<GenericLink<u32>, LinkError> {
96                self.update_observed(index, source, target, observer)
97                    .map_err(storage_error)
98            }
99
100            fn delete_link_observed(
101                &mut self,
102                index: u32,
103                observer: &mut dyn FnMut(GenericLink<u32>, GenericLink<u32>),
104            ) -> Result<GenericLink<u32>, LinkError> {
105                self.delete_observed(index, observer).map_err(storage_error)
106            }
107
108            fn all_links(&self) -> Vec<GenericLink<u32>> {
109                self.all().into_iter().copied().collect()
110            }
111
112            fn query_links(
113                &self,
114                index: Option<u32>,
115                source: Option<u32>,
116                target: Option<u32>,
117            ) -> Vec<GenericLink<u32>> {
118                self.query(index, source, target)
119                    .into_iter()
120                    .copied()
121                    .collect()
122            }
123
124            fn search_link(&self, source: u32, target: u32) -> Option<u32> {
125                self.search(source, target)
126            }
127
128            fn get_or_create_link(&mut self, source: u32, target: u32) -> Result<u32, LinkError> {
129                Ok(self.get_or_create(source, target))
130            }
131
132            fn flush(&mut self) -> Result<(), LinkError> {
133                #[allow(clippy::redundant_closure_call)]
134                $flush(self)
135            }
136
137            fn has_external_changes(&self) -> Result<bool, LinkError> {
138                #[allow(clippy::redundant_closure_call)]
139                $external(self)
140            }
141
142            fn reload(&mut self) -> Result<(), LinkError> {
143                #[allow(clippy::redundant_closure_call)]
144                $reload(self)
145            }
146        }
147
148        impl LinksStorageRef<u32> for $type {
149            fn get_link_ref(&self, index: u32) -> Option<&Link> {
150                self.get(index)
151            }
152
153            fn all_link_refs(&self) -> Vec<&Link> {
154                self.all()
155            }
156
157            fn query_link_refs(
158                &self,
159                index: Option<u32>,
160                source: Option<u32>,
161                target: Option<u32>,
162            ) -> Vec<&Link> {
163                self.query(index, source, target)
164            }
165        }
166    };
167}
168
169impl_in_memory_links_storage!(
170    LinkStorage,
171    |storage: &mut LinkStorage, source, target| storage.create(source, target),
172    |storage: &mut LinkStorage| {
173        storage.save().map_err(storage_error)?;
174        if !storage.is_in_memory() {
175            // FlushFileBuffers on Windows requires a writable handle, even
176            // though flushing does not itself modify the file's contents.
177            std::fs::OpenOptions::new()
178                .read(true)
179                .write(true)
180                .open(storage.database_path())?
181                .sync_all()?;
182            #[cfg(unix)]
183            std::fs::File::open(
184                storage
185                    .database_path()
186                    .parent()
187                    .filter(|p| !p.as_os_str().is_empty())
188                    .unwrap_or_else(|| std::path::Path::new(".")),
189            )?
190            .sync_all()?;
191        }
192        storage.refresh_observed_revision()
193    },
194    |storage: &LinkStorage| {
195        Ok(!storage.is_in_memory()
196            && StorageRevision::of(storage.database_path())? != storage.observed_revision())
197    },
198    |storage: &mut LinkStorage| storage.reload_from_disk().map_err(storage_error)
199);
200
201impl_in_memory_links_storage!(
202    PinnedTypesDecorator,
203    |storage: &mut PinnedTypesDecorator, source, target| storage.create(source, target),
204    |storage: &mut PinnedTypesDecorator| { storage.links_mut().flush() },
205    |storage: &PinnedTypesDecorator| storage.links().has_external_changes(),
206    |storage: &mut PinnedTypesDecorator| storage.links_mut().reload()
207);
208
209impl_in_memory_links_storage!(
210    NamedTypesDecorator,
211    |storage: &mut NamedTypesDecorator, source, target| storage.create(source, target),
212    |storage: &mut NamedTypesDecorator| {
213        storage.links_mut().flush()?;
214        storage.names_links_mut().flush()
215    },
216    |storage: &NamedTypesDecorator| {
217        Ok(storage.links().has_external_changes()?
218            || storage.names_links().has_external_changes()?)
219    },
220    |storage: &mut NamedTypesDecorator| {
221        storage.links_mut().reload()?;
222        storage.names_links_mut().reload()
223    },
224    fn capture_names(
225        &mut self,
226    ) -> Result<Option<std::collections::BTreeMap<u32, String>>, LinkError> {
227        self.logical_names().map(Some).map_err(storage_error)
228    },
229    fn set_link_name(&mut self, index: u32, name: Option<&str>) -> Result<u32, LinkError> {
230        use crate::named_types::NamedTypes;
231        match name {
232            Some(name) => self.set_name(index, name).map_err(storage_error),
233            None => {
234                self.remove_name(index).map_err(storage_error)?;
235                Ok(0)
236            }
237        }
238    }
239);
240
241/// Compile-time proof that the address type is not hard-coded to `u32`:
242/// the generic bound below accepts any `doublets` address type.
243#[allow(dead_code)]
244fn assert_generic_over_address<T: LinkReference, S: LinksStorage<T>>(_storage: &S) {}