Skip to main content

link_cli/engine/
address_allocator.rs

1//! Selected permanent ranges over one linearizable atomic journal key.
2//! A grant is never recycled; author lineage fencing remains caller-owned.
3use super::cluster::{AtomicJournalStore, JournalVersion};
4use crate::LinkError;
5use std::collections::BTreeSet;
6
7#[derive(Clone, Debug)]
8pub struct AddressAllocatorOptions {
9    pub max_entries: usize,
10    pub max_bytes: usize,
11    pub require_durable_flush: bool,
12}
13impl Default for AddressAllocatorOptions {
14    fn default() -> Self {
15        Self {
16            max_entries: 4096,
17            max_bytes: 1_048_576,
18            require_durable_flush: false,
19        }
20    }
21}
22
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct AddressReservation {
25    pub author: String,
26    pub token: String,
27    pub count: u64,
28    pub first: u64,
29    pub last: u64,
30}
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct AddressAllocationSnapshot {
33    pub generation: u64,
34    /// None means the immutable domain is exhausted.
35    pub next: Option<u64>,
36    pub reservations: Vec<AddressReservation>,
37}
38struct Loaded {
39    expected: JournalVersion,
40    next: u128,
41    reservations: Vec<AddressReservation>,
42}
43fn invalid() -> LinkError {
44    LinkError::InvalidFormat("invalid address reservation state or request".into())
45}
46fn identity(value: &str) -> Result<(), LinkError> {
47    if value.len() != 32
48        || value
49            .bytes()
50            .any(|b| !b.is_ascii_digit() && !(b'a'..=b'f').contains(&b))
51        || value.bytes().all(|b| b == b'0')
52    {
53        return Err(invalid());
54    }
55    Ok(())
56}
57fn number(value: &str) -> Result<u64, LinkError> {
58    if value.is_empty()
59        || value.len() > 20
60        || !value.bytes().all(|b| b.is_ascii_digit())
61        || (value.len() > 1 && value.starts_with('0'))
62    {
63        return Err(invalid());
64    }
65    value.parse().map_err(|_| invalid())
66}
67
68/// O(retained journal) per new grant. Every fresh writer in the domain must use
69/// the same coordinator key; initialize above all previously issued identities.
70/// No background work, receipt deletion, blind retry or provider disposal.
71pub struct AddressAllocator<S> {
72    store: S,
73    key: String,
74    first: u64,
75    last: u64,
76    header: String,
77    options: AddressAllocatorOptions,
78}
79impl<S: AtomicJournalStore> AddressAllocator<S> {
80    pub fn new(
81        store: S,
82        key: &str,
83        first: u64,
84        last: u64,
85        options: AddressAllocatorOptions,
86    ) -> Result<Self, LinkError> {
87        if key.is_empty()
88            || key.len() > 128
89            || key
90                .bytes()
91                .any(|b| !b.is_ascii_alphanumeric() && !b"_.-".contains(&b))
92            || first == 0
93            || first > last
94            || !(2..=4096).contains(&options.max_entries)
95            || !(1..=1_048_576).contains(&options.max_bytes)
96            || (options.require_durable_flush && !store.supports_durable_flush())
97        {
98            return Err(invalid());
99        }
100        Ok(Self {
101            store,
102            key: key.into(),
103            first,
104            last,
105            header: serde_json::to_string(&[
106                "address-reservations1",
107                &first.to_string(),
108                &last.to_string(),
109            ])
110            .unwrap(),
111            options,
112        })
113    }
114    pub fn into_store(self) -> S {
115        self.store
116    }
117    fn admit(&self, entries: &[String]) -> Result<(), LinkError> {
118        if entries.len() > self.options.max_entries {
119            return Err(invalid());
120        }
121        let mut bytes = 0;
122        for entry in entries {
123            if entry.len() > 256 {
124                return Err(invalid());
125            }
126            bytes += entry.len();
127            if bytes > self.options.max_bytes {
128                return Err(invalid());
129            }
130        }
131        Ok(())
132    }
133    fn load(&mut self) -> Result<Loaded, LinkError> {
134        let mut values = self.store.read(std::slice::from_ref(&self.key))?;
135        if values.len() != 1 {
136            return Err(invalid());
137        }
138        let expected = values.remove(0);
139        self.admit(&expected.entries)?;
140        let mut next = u128::from(self.first);
141        let mut reservations = Vec::new();
142        let mut tokens = BTreeSet::new();
143        if expected.generation == 0 {
144            if !expected.entries.is_empty() {
145                return Err(invalid());
146            }
147        } else {
148            if expected.entries.first() != Some(&self.header) {
149                return Err(invalid());
150            }
151            for text in expected.entries.iter().skip(1) {
152                let entry: Vec<String> = serde_json::from_str(text).map_err(|_| invalid())?;
153                if entry.len() != 6
154                    || entry[0] != "reserve-addresses1"
155                    || serde_json::to_string(&entry).unwrap() != *text
156                {
157                    return Err(invalid());
158                }
159                identity(&entry[1])?;
160                identity(&entry[2])?;
161                let count = number(&entry[3])?;
162                let first = number(&entry[4])?;
163                let last = number(&entry[5])?;
164                if count == 0
165                    || u128::from(first) != next
166                    || last > self.last
167                    || last < first
168                    || last - first != count - 1
169                    || !tokens.insert(entry[2].clone())
170                {
171                    return Err(invalid());
172                }
173                reservations.push(AddressReservation {
174                    author: entry[1].clone(),
175                    token: entry[2].clone(),
176                    count,
177                    first,
178                    last,
179                });
180                next = u128::from(last) + 1;
181            }
182        }
183        Ok(Loaded {
184            expected,
185            next,
186            reservations,
187        })
188    }
189    pub fn snapshot(&mut self) -> Result<AddressAllocationSnapshot, LinkError> {
190        let state = self.load()?;
191        Ok(AddressAllocationSnapshot {
192            generation: state.expected.generation,
193            next: (state.next <= u128::from(self.last)).then_some(state.next as u64),
194            reservations: state.reservations,
195        })
196    }
197    /// Retry the original author/token/count after conflict or uncertain I/O.
198    /// Retained matching requests publish nothing, even after later grants.
199    pub fn reserve(
200        &mut self,
201        author: &str,
202        token: &str,
203        count: u64,
204    ) -> Result<AddressReservation, LinkError> {
205        identity(author)?;
206        identity(token)?;
207        if count == 0 {
208            return Err(invalid());
209        }
210        let state = self.load()?;
211        if let Some(retained) = state.reservations.iter().find(|v| v.token == token) {
212            return if retained.author == author && retained.count == count {
213                Ok(retained.clone())
214            } else {
215                Err(invalid())
216            };
217        }
218        let end = state.next + u128::from(count) - 1;
219        if end > u128::from(self.last) || state.expected.generation == u64::MAX {
220            return Err(invalid());
221        }
222        let result = AddressReservation {
223            author: author.into(),
224            token: token.into(),
225            count,
226            first: state.next as u64,
227            last: end as u64,
228        };
229        let mut entries = state.expected.entries.clone();
230        if entries.is_empty() {
231            entries.push(self.header.clone());
232        }
233        entries.push(
234            serde_json::to_string(&[
235                "reserve-addresses1",
236                author,
237                token,
238                &count.to_string(),
239                &result.first.to_string(),
240                &result.last.to_string(),
241            ])
242            .unwrap(),
243        );
244        self.admit(&entries)?;
245        let committed = self.store.compare_exchange(std::slice::from_ref(&self.key), &[state.expected], &[Some(entries)])
246            .map_err(|cause| LinkError::StorageError(format!("indeterminate address reservation; retry the original author/token/count: {cause}")))?;
247        if !committed {
248            return Err(LinkError::Transaction(
249                "conflict: address reservations changed; retry the original request".into(),
250            ));
251        }
252        Ok(result)
253    }
254}