1use super::cluster::{validate_keys, AtomicJournalStore, JournalVersion};
3use crate::LinkError;
4use std::collections::BTreeSet;
5#[derive(Clone, Debug)]
6pub struct AuthorFenceOptions {
7 pub max_entries: usize,
8 pub max_bytes: usize,
9 pub require_durable_flush: bool,
10}
11impl Default for AuthorFenceOptions {
12 fn default() -> Self {
13 Self {
14 max_entries: 4096,
15 max_bytes: 1_048_576,
16 require_durable_flush: false,
17 }
18 }
19}
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub struct AuthorClaim {
22 pub author: String,
23 pub token: String,
24 pub epoch: u64,
25}
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct AuthorFenceSnapshot {
28 pub generation: u64,
29 pub epoch: u64,
30 pub claims: Vec<AuthorClaim>,
31}
32fn invalid() -> LinkError {
33 LinkError::InvalidFormat("invalid author fence state or request".into())
34}
35fn fenced() -> LinkError {
36 LinkError::Transaction("author owner is fenced by a later takeover".into())
37}
38fn identity(value: &str) -> Result<(), LinkError> {
39 if value.len() != 32
40 || value.bytes().all(|b| b == b'0')
41 || value
42 .bytes()
43 .any(|b| !b.is_ascii_digit() && !(b'a'..=b'f').contains(&b))
44 {
45 return Err(invalid());
46 }
47 Ok(())
48}
49struct Loaded {
50 expected: JournalVersion,
51 claims: Vec<AuthorClaim>,
52 values: Vec<JournalVersion>,
53}
54pub struct AuthorFence<S> {
57 store: S,
58 key: String,
59 author: String,
60 header: String,
61 options: AuthorFenceOptions,
62}
63impl<S: AtomicJournalStore> AuthorFence<S> {
64 pub fn new(
65 store: S,
66 key: &str,
67 author: &str,
68 options: AuthorFenceOptions,
69 ) -> Result<Self, LinkError> {
70 identity(author)?;
71 validate_keys(&[key.into()])?;
72 if !(2..=4096).contains(&options.max_entries)
73 || !(1..=1_048_576).contains(&options.max_bytes)
74 || (options.require_durable_flush && !store.supports_durable_flush())
75 {
76 return Err(invalid());
77 }
78 Ok(Self {
79 store,
80 key: key.into(),
81 author: author.into(),
82 header: serde_json::to_string(&["author-fence1", author]).unwrap(),
83 options,
84 })
85 }
86 pub fn into_store(self) -> S {
87 self.store
88 }
89 fn admit(&self, entries: &[String]) -> Result<(), LinkError> {
90 if entries.len() > self.options.max_entries {
91 return Err(invalid());
92 }
93 let mut bytes = 0;
94 for entry in entries {
95 if entry.len() > 256 || !entry.is_ascii() {
96 return Err(invalid());
97 }
98 bytes += entry.len();
99 if bytes > self.options.max_bytes {
100 return Err(invalid());
101 }
102 }
103 Ok(())
104 }
105 fn read(&mut self, keys: &[String]) -> Result<Loaded, LinkError> {
106 let mut selected = vec![self.key.clone()];
107 selected.extend_from_slice(keys);
108 let mut values = self.store.read(&selected)?;
109 if values.len() != selected.len() {
110 return Err(invalid());
111 }
112 let expected = values.remove(0);
113 self.admit(&expected.entries)?;
114 let mut claims = Vec::new();
115 let mut tokens = BTreeSet::new();
116 if expected.generation == 0 {
117 if !expected.entries.is_empty() {
118 return Err(invalid());
119 }
120 } else {
121 if expected.entries.first() != Some(&self.header) {
122 return Err(invalid());
123 }
124 for text in expected.entries.iter().skip(1) {
125 let entry: Vec<String> = serde_json::from_str(text).map_err(|_| invalid())?;
126 if entry.len() != 3
127 || entry[0] != "claim-author1"
128 || serde_json::to_string(&entry).unwrap() != *text
129 {
130 return Err(invalid());
131 }
132 identity(&entry[1])?;
133 let epoch = claims.len() as u64 + 1;
134 if entry[2] != epoch.to_string() || !tokens.insert(entry[1].clone()) {
135 return Err(invalid());
136 }
137 claims.push(AuthorClaim {
138 author: self.author.clone(),
139 token: entry[1].clone(),
140 epoch,
141 });
142 }
143 }
144 Ok(Loaded {
145 expected,
146 claims,
147 values,
148 })
149 }
150 pub fn snapshot(&mut self) -> Result<AuthorFenceSnapshot, LinkError> {
151 let state = self.read(&[])?;
152 Ok(AuthorFenceSnapshot {
153 generation: state.expected.generation,
154 epoch: state.claims.len() as u64,
155 claims: state.claims,
156 })
157 }
158 pub fn claim(&mut self, expected_epoch: u64, token: &str) -> Result<AuthorClaim, LinkError> {
161 identity(token)?;
162 let state = self.read(&[])?;
163 if let Some(retained) = state.claims.iter().find(|value| value.token == token) {
164 if retained.epoch != state.claims.len() as u64
165 || Some(retained.epoch) != expected_epoch.checked_add(1)
166 {
167 return Err(fenced());
168 }
169 return Ok(retained.clone());
170 }
171 if expected_epoch != state.claims.len() as u64 {
172 return Err(LinkError::Transaction(
173 "conflict: author epoch changed".into(),
174 ));
175 }
176 if state.expected.generation == u64::MAX {
177 return Err(invalid());
178 }
179 let result = AuthorClaim {
180 author: self.author.clone(),
181 token: token.into(),
182 epoch: expected_epoch + 1,
183 };
184 let mut entries = state.expected.entries.clone();
185 if entries.is_empty() {
186 entries.push(self.header.clone());
187 }
188 entries.push(
189 serde_json::to_string(&["claim-author1", token, &result.epoch.to_string()]).unwrap(),
190 );
191 self.admit(&entries)?;
192 let committed = self
193 .store
194 .compare_exchange(
195 std::slice::from_ref(&self.key),
196 &[state.expected],
197 &[Some(entries)],
198 )
199 .map_err(|cause| {
200 LinkError::StorageError(format!(
201 "indeterminate author takeover; retry original predecessor/token: {cause}"
202 ))
203 })?;
204 if !committed {
205 return Err(LinkError::Transaction(
206 "conflict: author epoch changed".into(),
207 ));
208 }
209 Ok(result)
210 }
211 pub fn bind(self, claim: AuthorClaim) -> Result<GuardedJournalStore<S>, LinkError> {
212 identity(&claim.token)?;
213 if claim.author != self.author || claim.epoch == 0 {
214 return Err(invalid());
215 }
216 Ok(GuardedJournalStore { owner: self, claim })
217 }
218}
219pub struct GuardedJournalStore<S> {
223 owner: AuthorFence<S>,
224 claim: AuthorClaim,
225}
226impl<S: AtomicJournalStore> GuardedJournalStore<S> {
227 pub fn into_store(self) -> S {
228 self.owner.store
229 }
230 fn keys(&self, keys: &[String]) -> Result<(), LinkError> {
231 validate_keys(keys)?;
232 if keys.len() > 31 || keys.contains(&self.owner.key) {
233 return Err(invalid());
234 }
235 Ok(())
236 }
237 fn current(&mut self, keys: &[String]) -> Result<Loaded, LinkError> {
238 let state = self.owner.read(keys)?;
239 if state.claims.last() != Some(&self.claim) {
240 return Err(fenced());
241 }
242 Ok(state)
243 }
244}
245impl<S: AtomicJournalStore> AtomicJournalStore for GuardedJournalStore<S> {
246 fn supports_durable_flush(&self) -> bool {
247 self.owner.store.supports_durable_flush()
248 }
249 fn read(&mut self, keys: &[String]) -> Result<Vec<JournalVersion>, LinkError> {
250 self.keys(keys)?;
251 Ok(self.current(keys)?.values)
252 }
253 fn compare_exchange(
254 &mut self,
255 keys: &[String],
256 expected: &[JournalVersion],
257 updates: &[Option<Vec<String>>],
258 ) -> Result<bool, LinkError> {
259 self.keys(keys)?;
260 if expected.len() != keys.len() || updates.len() != keys.len() {
261 return Err(invalid());
262 }
263 let state = self.current(&[])?;
264 let mut selected = vec![self.owner.key.clone()];
265 selected.extend_from_slice(keys);
266 let mut versions = vec![state.expected];
267 versions.extend_from_slice(expected);
268 let mut writes = vec![None];
269 writes.extend_from_slice(updates);
270 self.owner
271 .store
272 .compare_exchange(&selected, &versions, &writes)
273 }
274}