relate_executor/graph/
pin.rs1use relate_core::Result;
6
7use super::*;
8
9pub(super) const PIN_SLOTS: usize = 256;
12pub(super) const PIN_FREE: u64 = 0;
13pub(super) const PIN_CLAIMING: u64 = u64::MAX;
14pub(super) const PIN_ACQUIRE_RETRIES: u32 = 1024;
19
20pub struct SnapshotPin<'a> {
22 graph: &'a Graph,
23 ts: u64,
24 slot: usize,
25}
26
27impl SnapshotPin<'_> {
28 pub fn ts(&self) -> u64 {
29 self.ts
30 }
31
32 pub fn detach(self) -> usize {
34 let slot = self.slot;
35 std::mem::forget(self);
36 slot
37 }
38}
39
40impl Drop for SnapshotPin<'_> {
41 fn drop(&mut self) {
42 self.graph.unpin_slot(self.slot);
43 }
44}
45
46impl Graph {
47 pub fn pin_now(&self) -> Result<SnapshotPin<'_>> {
55 self.pin_now_with_retry(std::thread::yield_now)
56 }
57
58 pub(super) fn pin_now_with_retry(&self, mut retry: impl FnMut()) -> Result<SnapshotPin<'_>> {
60 let start = self.pin_cursor.fetch_add(1, Ordering::Relaxed) as usize;
61 for _ in 0..PIN_ACQUIRE_RETRIES {
62 for i in 0..PIN_SLOTS {
63 let slot = (start + i) % PIN_SLOTS;
64 if self.pins[slot]
65 .compare_exchange(PIN_FREE, PIN_CLAIMING, Ordering::AcqRel, Ordering::Acquire)
66 .is_ok()
67 {
68 let ts = self.commit_ts();
69 self.pins[slot].store(ts.saturating_add(1), Ordering::Release);
70 return Ok(SnapshotPin {
71 graph: self,
72 ts,
73 slot,
74 });
75 }
76 }
77 retry();
78 }
79 Err(relate_core::Error::execution(format!(
80 "snapshot pin: all {PIN_SLOTS} slots are held"
81 )))
82 }
83
84 pub fn unpin_slot(&self, slot: usize) {
85 self.pins[slot].store(PIN_FREE, Ordering::Release);
86 }
87
88 pub fn snapshot_pinned(&self) -> bool {
90 self.pins
91 .iter()
92 .any(|slot| slot.load(Ordering::Acquire) != PIN_FREE)
93 }
94
95 pub fn gc_horizon(&self) -> u64 {
97 let commit = self.commit_ts();
98 let mut min_pin: Option<u64> = None;
99 for slot in self.pins.iter() {
100 let v = slot.load(Ordering::Acquire);
101 if v == PIN_CLAIMING {
102 return 0;
103 }
104 if v != PIN_FREE {
105 let ts = v - 1;
106 min_pin = Some(min_pin.map_or(ts, |m| m.min(ts)));
107 }
108 }
109 min_pin.unwrap_or(commit).min(commit)
110 }
111}