Skip to main content

link_cli/engine/
cluster.rs

1//! Optional optimistic coordination across namespaced shards. A coordinator
2//! must provide atomic snapshots/CAS; local workspaces are never shared state.
3use super::{
4    error, ConcurrencyControl, Engine, EngineOptions, EngineTransaction, IsolationLevel, MemoryLog,
5};
6use crate::{GenericLink, LinkError, LinksStorage};
7use doublets::data::LinkReference;
8use std::{
9    marker::PhantomData,
10    sync::{Arc, Mutex},
11};
12
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
14pub struct JournalVersion {
15    /// A non-reusable modification generation, zero only for an absent key.
16    pub generation: u64,
17    pub entries: Vec<String>,
18}
19
20/// All keys in `read` must be read at one linearizable serialization point.
21/// CAS checks EVERY selected generation and writes all updates atomically.
22/// Never retry a mutation on transport errors: its outcome may be unknown.
23pub trait AtomicJournalStore {
24    fn supports_durable_flush(&self) -> bool {
25        false
26    }
27    fn read(&mut self, keys: &[String]) -> Result<Vec<JournalVersion>, LinkError>;
28    fn compare_exchange(
29        &mut self,
30        keys: &[String],
31        expected: &[JournalVersion],
32        updates: &[Option<Vec<String>>],
33    ) -> Result<bool, LinkError>;
34}
35
36pub struct ClusterEngine<T, S> {
37    store: Arc<Mutex<S>>,
38    options: EngineOptions,
39    journal_checkpoint_interval: Option<u64>,
40    marker: PhantomData<T>,
41}
42impl<T: LinkReference, S: AtomicJournalStore> ClusterEngine<T, S> {
43    pub fn new(store: S, mut options: EngineOptions) -> Result<Self, LinkError> {
44        if options.concurrency != ConcurrencyControl::Optimistic
45            || options.isolation != IsolationLevel::Serializable
46        {
47            return Err(error(
48                "network sessions require optimistic admission and serializable validation",
49            ));
50        }
51        if options.require_durable_flush && !store.supports_durable_flush() {
52            return Err(error("coordinator does not support durable flush"));
53        }
54        // Local memory journals are private workspaces, never the durability boundary.
55        options.require_durable_flush = false;
56        Ok(Self {
57            store: Arc::new(Mutex::new(store)),
58            options,
59            journal_checkpoint_interval: None,
60            marker: PhantomData,
61        })
62    }
63    /// Replace the published journal with retained snapshots every N revisions.
64    /// Disabled by default. The atomic store remains the publication boundary.
65    pub fn with_journal_checkpoint_interval(mut self, interval: u64) -> Result<Self, LinkError> {
66        if interval == 0 {
67            return Err(error("journal checkpoint interval must be positive"));
68        }
69        self.journal_checkpoint_interval = Some(interval);
70        Ok(self)
71    }
72    pub fn begin(&self, keys: &[&str]) -> Result<ClusterTransaction<T, S>, LinkError> {
73        let keys: Vec<String> = keys.iter().map(|key| (*key).into()).collect();
74        validate_keys(&keys)?;
75        let expected = self
76            .store
77            .lock()
78            .map_err(|_| error("coordinator mutex poisoned"))?
79            .read(&keys)?;
80        if expected.len() != keys.len() {
81            return Err(error("incomplete coordinator snapshot"));
82        }
83        let mut shards = Vec::new();
84        for version in &expected {
85            let engine = Engine::open(
86                MemoryLog {
87                    entries: version.entries.clone(),
88                },
89                self.options.clone(),
90            )?;
91            let session = engine.begin()?;
92            shards.push(ShardSession { engine, session });
93        }
94        Ok(ClusterTransaction {
95            store: self.store.clone(),
96            keys,
97            expected,
98            shards,
99            journal_checkpoint_interval: self.journal_checkpoint_interval,
100            closed: false,
101        })
102    }
103}
104
105pub(super) fn validate_keys(keys: &[String]) -> Result<(), LinkError> {
106    if keys.is_empty()
107        || keys.len() > 32
108        || keys.iter().enumerate().any(|(index, key)| {
109            key.is_empty()
110                || key.len() > 128
111                || !key
112                    .bytes()
113                    .all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b))
114                || keys[..index].contains(key)
115        })
116    {
117        return Err(error(
118            "select 1..32 distinct shard names using letters, numbers, dot, underscore or dash",
119        ));
120    }
121    Ok(())
122}
123
124pub struct ClusterTransaction<T: LinkReference, S: AtomicJournalStore> {
125    store: Arc<Mutex<S>>,
126    keys: Vec<String>,
127    expected: Vec<JournalVersion>,
128    shards: Vec<ShardSession<T>>,
129    journal_checkpoint_interval: Option<u64>,
130    closed: bool,
131}
132impl<T: LinkReference, S: AtomicJournalStore> ClusterTransaction<T, S> {
133    pub fn shard(&mut self, key: &str) -> Result<&mut ShardSession<T>, LinkError> {
134        if self.closed {
135            return Err(error("cluster transaction is closed"));
136        }
137        let index = self
138            .keys
139            .iter()
140            .position(|candidate| candidate == key)
141            .ok_or_else(|| error("shard was not selected at begin"))?;
142        Ok(&mut self.shards[index])
143    }
144    /// Every attempt ends this transaction. An error after CAS may be unknown;
145    /// use a new transaction to discover the authoritative state.
146    pub fn commit(&mut self) -> Result<(), LinkError> {
147        if self.closed {
148            return Err(error("cluster transaction is closed"));
149        }
150        self.closed = true;
151        let mut updates = Vec::new();
152        for (shard, expected) in self.shards.iter_mut().zip(&self.expected) {
153            shard.session.commit()?;
154            let mut entries = shard.engine.with_log(|log| Ok(log.entries.clone()))?;
155            // Compare before compaction: a checkpoint can shrink the journal or
156            // leave its length unchanged. Read-only groups publish no rewrite.
157            if entries.len() == expected.entries.len() {
158                updates.push(None);
159            } else {
160                if let Some(interval) = self.journal_checkpoint_interval {
161                    if shard.engine.snapshot()?.revision.is_multiple_of(interval) {
162                        entries = shard.engine.export_checkpoint()?;
163                    }
164                }
165                updates.push(Some(entries));
166            }
167        }
168        let outcome = self
169            .store
170            .lock()
171            .map_err(|_| error("coordinator mutex poisoned"))?
172            .compare_exchange(&self.keys, &self.expected, &updates);
173        match outcome {
174            Ok(true) => Ok(()),
175            Ok(false) => Err(error("conflict: a selected shard changed since begin")),
176            Err(cause) => Err(error(&format!("indeterminate coordinated commit: {cause}; read fresh journals to discover the outcome"))),
177        }
178    }
179    pub fn rollback(&mut self) {
180        self.closed = true;
181        for shard in &mut self.shards {
182            shard.session.rollback();
183        }
184    }
185}
186impl<T: LinkReference, S: AtomicJournalStore> Drop for ClusterTransaction<T, S> {
187    fn drop(&mut self) {
188        self.rollback();
189    }
190}
191
192/// Standard raw links operations in a selected shard. Commit the containing
193/// group explicitly; individual shard flushes cannot publish a partial group.
194pub struct ShardSession<T: LinkReference> {
195    engine: Engine<T, MemoryLog>,
196    pub(super) session: EngineTransaction<T, MemoryLog>,
197}
198impl<T: LinkReference> ShardSession<T> {
199    pub fn get_name(&self, id: T) -> Option<String> {
200        self.session.get_name(id)
201    }
202    pub fn get_by_name(&self, name: &str) -> Option<T> {
203        self.session.get_by_name(name)
204    }
205    pub fn set_name(&mut self, id: T, name: Option<String>) -> Result<(), LinkError> {
206        self.session.set_name(id, name)
207    }
208    /// A savepoint covers this shard only, not the containing group.
209    pub fn savepoint(&mut self) -> Result<super::Savepoint, LinkError> {
210        self.session.savepoint()
211    }
212    pub fn rollback_to_savepoint(&mut self, savepoint: super::Savepoint) -> Result<(), LinkError> {
213        self.session.rollback_to_savepoint(savepoint)
214    }
215    pub fn release_savepoint(&mut self, savepoint: super::Savepoint) -> Result<(), LinkError> {
216        self.session.release_savepoint(savepoint)
217    }
218}
219impl<T: LinkReference> LinksStorage<T> for ShardSession<T> {
220    fn create_link(&mut self, source: T, target: T) -> Result<T, LinkError> {
221        self.session.create_link(source, target)
222    }
223    fn ensure_link_created(&mut self, index: T) -> Result<T, LinkError> {
224        self.session.ensure_link_created(index)
225    }
226    fn get_link(&self, index: T) -> Option<GenericLink<T>> {
227        self.session.get_link(index)
228    }
229    fn update_link(&mut self, index: T, source: T, target: T) -> Result<GenericLink<T>, LinkError> {
230        self.session.update_link(index, source, target)
231    }
232    fn delete_link(&mut self, index: T) -> Result<GenericLink<T>, LinkError> {
233        self.session.delete_link(index)
234    }
235    fn all_links(&self) -> Vec<GenericLink<T>> {
236        self.session.all_links()
237    }
238    fn flush(&mut self) -> Result<(), LinkError> {
239        Err(error("commit the containing cluster transaction"))
240    }
241}