Skip to main content

link_cli/
cache_links.rs

1//! A links store used as a cache: links can expire, and the store can be kept
2//! to a number of links by evicting the ones used least recently. It has the API
3//! of any other store, so only a store that selects it pays for it. See
4//! `docs/ENGINE-CACHE.md`. The C# twin is `CacheLinksDecorator<TLinkAddress>`, the
5//! JavaScript one `CacheLinks` of `@link-foundation/link-cli-client`.
6//!
7//! The two rules differ on purpose. A deadline is a promise, so a link that comes
8//! due is deleted with whatever the store's own delete takes with it. Capacity only
9//! has to free a place, so it evicts a link nothing else uses and takes nothing
10//! else along. When every link is in use the create is refused.
11//!
12//! There is no worker. Everything due is deleted by the next call that touches the
13//! store, or by [`CacheLinks::purge_expired`] when a caller wants to run it on a
14//! timer. Deadlines live in memory: a store opened again has links without one.
15
16use std::collections::{BTreeSet, HashMap};
17use std::time::{SystemTime, UNIX_EPOCH};
18
19use anyhow::{bail, Result};
20
21use crate::link::Link;
22use crate::link_storage::ChangeObserver;
23use crate::named_type_links::NamedTypeLinks;
24
25/// What a [`CacheLinks`] enforces. Each is optional, and the default is neither.
26#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
27pub struct CacheOptions {
28    /// How many links the store may hold, reached by evicting.
29    pub max_links: Option<usize>,
30    /// The milliseconds a link created here has before it comes due.
31    pub time_to_live: Option<u64>,
32}
33
34fn system_clock() -> u64 {
35    SystemTime::now()
36        .duration_since(UNIX_EPOCH)
37        .map_or(0, |elapsed| elapsed.as_millis() as u64)
38}
39
40struct Entry {
41    used: u64,
42    deadline: Option<u64>,
43}
44
45/// Follows every change the store reports. It is apart from the store below, so
46/// a write can report to it while the store is borrowed for that write.
47struct Tracker {
48    time_to_live: Option<u64>,
49    now: u64,
50    uses: u64,
51    entries: HashMap<u32, Entry>,
52    /// How many other links refer to an address.
53    usages: HashMap<u32, u32>,
54    /// The links nothing else uses, least recently used first.
55    evictable: BTreeSet<(u64, u32)>,
56    /// The links with a deadline, soonest first.
57    deadlines: BTreeSet<(u64, u32)>,
58}
59
60impl Tracker {
61    fn is_used(&self, id: u32) -> bool {
62        self.usages.contains_key(&id)
63    }
64
65    fn references(link: &Link) -> impl Iterator<Item = u32> {
66        let index = link.index;
67        // A link that refers to itself twice uses nothing else, and the null link
68        // is no link.
69        let target = (link.target != link.source).then_some(link.target);
70        std::iter::once(link.source)
71            .chain(target)
72            .filter(move |&reference| reference != index && reference != 0)
73    }
74
75    fn touch(&mut self, id: u32) {
76        self.uses += 1;
77        let (uses, used) = (self.uses, self.is_used(id));
78        if let Some(entry) = self.entries.get_mut(&id) {
79            let previous = std::mem::replace(&mut entry.used, uses);
80            if !used {
81                self.evictable.remove(&(previous, id));
82                self.evictable.insert((uses, id));
83            }
84        }
85    }
86
87    fn add_usage(&mut self, id: u32) {
88        let usages = self.usages.entry(id).or_default();
89        *usages += 1;
90        if *usages == 1 {
91            if let Some(entry) = self.entries.get(&id) {
92                self.evictable.remove(&(entry.used, id));
93            }
94        }
95    }
96
97    fn remove_usage(&mut self, id: u32) {
98        let Some(usages) = self.usages.get_mut(&id) else {
99            return;
100        };
101        *usages -= 1;
102        if *usages == 0 {
103            self.usages.remove(&id);
104            if let Some(entry) = self.entries.get(&id) {
105                self.evictable.insert((entry.used, id));
106            }
107        }
108    }
109
110    fn insert(&mut self, id: u32, deadline: Option<u64>) {
111        self.uses += 1;
112        self.entries.insert(
113            id,
114            Entry {
115                used: self.uses,
116                deadline,
117            },
118        );
119        if !self.is_used(id) {
120            self.evictable.insert((self.uses, id));
121        }
122        if let Some(deadline) = deadline {
123            self.deadlines.insert((deadline, id));
124        }
125    }
126
127    fn remove(&mut self, id: u32) {
128        if let Some(entry) = self.entries.remove(&id) {
129            self.evictable.remove(&(entry.used, id));
130            if let Some(deadline) = entry.deadline {
131                self.deadlines.remove(&(deadline, id));
132            }
133        }
134    }
135
136    fn set_deadline(&mut self, id: u32, deadline: Option<u64>) {
137        if let Some(entry) = self.entries.get_mut(&id) {
138            if let Some(previous) = std::mem::replace(&mut entry.deadline, deadline) {
139                self.deadlines.remove(&(previous, id));
140            }
141            if let Some(deadline) = deadline {
142                self.deadlines.insert((deadline, id));
143            }
144        }
145    }
146
147    /// A change as the store reports it: a null link is no link.
148    fn changed(&mut self, before: Link, after: Link) {
149        Self::references(&before).for_each(|reference| self.remove_usage(reference));
150        Self::references(&after).for_each(|reference| self.add_usage(reference));
151        match (before.is_null(), after.is_null()) {
152            (false, true) => self.remove(before.index),
153            (false, false) => self.touch(before.index),
154            (true, _) => {
155                let deadline = self
156                    .time_to_live
157                    .map(|time_to_live| self.now.saturating_add(time_to_live));
158                self.insert(after.index, deadline);
159            }
160        }
161    }
162
163    fn next_due(&self) -> Option<u32> {
164        let &(deadline, id) = self.deadlines.first()?;
165        (deadline <= self.now).then_some(id)
166    }
167
168    fn least_recently_used_except(&self, kept: [u32; 2]) -> Option<u32> {
169        self.evictable
170            .iter()
171            .map(|&(_, id)| id)
172            .find(|id| !kept.contains(id))
173    }
174}
175
176/// `links` kept as [`CacheOptions`] tell; see the top of this module. Every write
177/// has to go through it for it to know which links exist.
178pub struct CacheLinks<L> {
179    links: L,
180    max_links: Option<usize>,
181    clock: Box<dyn FnMut() -> u64 + Send>,
182    tracker: Tracker,
183}
184
185impl<L: NamedTypeLinks> CacheLinks<L> {
186    /// `links` on the system clock. A step back in that clock delays what comes due.
187    /// `wasm32-unknown-unknown` has no system clock: there, use [`Self::with_clock`].
188    pub fn new(links: L, options: CacheOptions) -> Self {
189        Self::with_clock(links, options, system_clock)
190    }
191
192    /// `links` on a clock of milliseconds. The links already there are the least
193    /// recently used, in the order of their addresses, and have no deadline.
194    pub fn with_clock(
195        mut links: L,
196        options: CacheOptions,
197        clock: impl FnMut() -> u64 + Send + 'static,
198    ) -> Self {
199        let mut tracker = Tracker {
200            time_to_live: None,
201            now: 0,
202            uses: 0,
203            entries: HashMap::new(),
204            usages: HashMap::new(),
205            evictable: BTreeSet::new(),
206            deadlines: BTreeSet::new(),
207        };
208        for link in links.all_links() {
209            tracker.changed(Link::null(), link);
210        }
211        tracker.time_to_live = options.time_to_live;
212        Self {
213            links,
214            max_links: options.max_links,
215            clock: Box::new(clock),
216            tracker,
217        }
218    }
219
220    /// The store below, to read without using anything.
221    pub fn links(&self) -> &L {
222        &self.links
223    }
224
225    /// The store below, without the cache.
226    pub fn into_inner(self) -> L {
227        self.links
228    }
229
230    /// Deletes what is due now, and how many links that deleted, cascades included.
231    pub fn purge_expired(&mut self) -> Result<usize> {
232        self.tracker.now = (self.clock)();
233        let mut deleted = 0;
234        while let Some(id) = self.tracker.next_due() {
235            let tracker = &mut self.tracker;
236            self.links.delete_observed(id, &mut |before, after| {
237                deleted += usize::from(after.is_null());
238                tracker.changed(before, after);
239            })?;
240        }
241        Ok(deleted)
242    }
243
244    /// Reads have no way to answer a failure, so one that could not delete what came
245    /// due panics. A store that cannot delete has failed the way its `create` does.
246    fn purged(&mut self) -> &mut Self {
247        self.purge_expired()
248            .unwrap_or_else(|error| panic!("{error}"));
249        self
250    }
251
252    /// Gives `id` a deadline in place of any it had; false when there is no such
253    /// link. A time of zero deletes it now, as Redis `EXPIRE` does.
254    pub fn expire(&mut self, id: u32, milliseconds: u64) -> Result<bool> {
255        self.purge_expired()?;
256        if !self.tracker.entries.contains_key(&id) {
257            return Ok(false);
258        }
259        let deadline = self.tracker.now.saturating_add(milliseconds);
260        self.tracker.set_deadline(id, Some(deadline));
261        self.purge_expired()?;
262        Ok(true)
263    }
264
265    /// Takes the deadline of `id` away; false when it had none.
266    pub fn persist(&mut self, id: u32) -> Result<bool> {
267        self.purge_expired()?;
268        let had = self
269            .tracker
270            .entries
271            .get(&id)
272            .is_some_and(|entry| entry.deadline.is_some());
273        self.tracker.set_deadline(id, None);
274        Ok(had)
275    }
276
277    /// The milliseconds `id` has left; `None` when it has no deadline or is gone.
278    pub fn time_to_live(&mut self, id: u32) -> Result<Option<u64>> {
279        self.purge_expired()?;
280        let now = self.tracker.now;
281        Ok(self
282            .tracker
283            .entries
284            .get(&id)
285            .and_then(|entry| entry.deadline)
286            .map(|deadline| deadline - now))
287    }
288
289    /// Frees a place for a link, which will refer to `kept`.
290    fn make_room(&mut self, kept: [u32; 2]) -> Result<()> {
291        let Some(max_links) = self.max_links else {
292            return Ok(());
293        };
294        while self.tracker.entries.len() >= max_links {
295            let Some(victim) = self.tracker.least_recently_used_except(kept) else {
296                bail!("the cache holds {max_links} links and every other one is in use");
297            };
298            let tracker = &mut self.tracker;
299            self.links
300                .delete_observed(victim, &mut |before, after| tracker.changed(before, after))?;
301        }
302        Ok(())
303    }
304}
305
306impl<L: NamedTypeLinks> NamedTypeLinks for CacheLinks<L> {
307    fn query_limits(&self) -> Option<crate::query_options::QueryLimits> {
308        self.links.query_limits()
309    }
310
311    /// Panics when the cache is full; use [`try_create`](NamedTypeLinks::try_create).
312    fn create(&mut self, source: u32, target: u32) -> u32 {
313        self.try_create(source, target)
314            .unwrap_or_else(|error| panic!("{error}"))
315    }
316
317    fn try_create(&mut self, source: u32, target: u32) -> Result<u32> {
318        self.purge_expired()?;
319        self.make_room([source, target])?;
320        let id = self.links.try_create(source, target)?;
321        self.tracker
322            .changed(Link::null(), Link::new(id, source, target));
323        Ok(id)
324    }
325
326    /// Panics when the cache is full; use
327    /// [`try_ensure_created`](NamedTypeLinks::try_ensure_created).
328    fn ensure_created(&mut self, id: u32) -> u32 {
329        self.try_ensure_created(id)
330            .unwrap_or_else(|error| panic!("{error}"))
331    }
332
333    fn try_ensure_created(&mut self, id: u32) -> Result<u32> {
334        self.purge_expired()?;
335        if id == 0 || self.tracker.entries.contains_key(&id) {
336            return self.links.try_ensure_created(id);
337        }
338        self.make_room([0, 0])?;
339        let created = self.links.try_ensure_created(id)?;
340        self.tracker.changed(Link::null(), Link::new(created, 0, 0));
341        Ok(created)
342    }
343
344    fn reference_exists(&mut self, id: u32) -> bool {
345        self.purged().links.reference_exists(id)
346    }
347
348    fn claims(&mut self, id: u32) -> Option<bool> {
349        self.purged().links.claims(id)
350    }
351
352    /// Asked of the store below: asking by creating here could evict.
353    fn next_created_addresses(&mut self, count: usize) -> Result<Vec<u32>> {
354        self.purge_expired()?;
355        self.links.next_created_addresses(count)
356    }
357
358    fn get_link(&mut self, id: u32) -> Option<Link> {
359        let link = self.purged().links.get_link(id);
360        if link.is_some() {
361            self.tracker.touch(id);
362        }
363        link
364    }
365
366    fn exists(&mut self, id: u32) -> bool {
367        self.purged().links.exists(id)
368    }
369
370    fn update_observed(
371        &mut self,
372        id: u32,
373        source: u32,
374        target: u32,
375        observer: ChangeObserver<'_>,
376    ) -> Result<Link> {
377        self.purge_expired()?;
378        let tracker = &mut self.tracker;
379        self.links
380            .update_observed(id, source, target, &mut |before, after| {
381                tracker.changed(before, after);
382                observer(before, after);
383            })
384    }
385
386    fn delete_observed(&mut self, id: u32, observer: ChangeObserver<'_>) -> Result<Link> {
387        self.purge_expired()?;
388        let tracker = &mut self.tracker;
389        self.links.delete_observed(id, &mut |before, after| {
390            tracker.changed(before, after);
391            observer(before, after);
392        })
393    }
394
395    fn all_links(&mut self) -> Vec<Link> {
396        self.purged().links.all_links()
397    }
398
399    fn query_links(
400        &mut self,
401        index: Option<u32>,
402        source: Option<u32>,
403        target: Option<u32>,
404    ) -> Vec<Link> {
405        self.purged().links.query_links(index, source, target)
406    }
407
408    fn search(&mut self, source: u32, target: u32) -> Option<u32> {
409        let found = self.purged().links.search(source, target);
410        if let Some(id) = found {
411            self.tracker.touch(id);
412        }
413        found
414    }
415
416    /// Panics when the cache is full; use
417    /// [`try_get_or_create`](NamedTypeLinks::try_get_or_create).
418    fn get_or_create(&mut self, source: u32, target: u32) -> u32 {
419        self.try_get_or_create(source, target)
420            .unwrap_or_else(|error| panic!("{error}"))
421    }
422
423    fn get_name(&mut self, id: u32) -> Result<Option<String>> {
424        self.purge_expired()?;
425        self.links.get_name(id)
426    }
427
428    fn set_name(&mut self, id: u32, name: &str) -> Result<u32> {
429        self.purge_expired()?;
430        self.links.set_name(id, name)
431    }
432
433    fn get_by_name(&mut self, name: &str) -> Result<Option<u32>> {
434        self.purge_expired()?;
435        self.links.get_by_name(name)
436    }
437
438    fn remove_name(&mut self, id: u32) -> Result<()> {
439        self.purge_expired()?;
440        self.links.remove_name(id)
441    }
442
443    fn save(&mut self) -> Result<()> {
444        self.purge_expired()?;
445        self.links.save()
446    }
447}