1use std::cell::RefCell;
34
35use super::kinds;
36use super::seal::{self, Key, Parts};
37use super::sync_activity::{self, ActivityBody};
38use super::sync_adapter::{merge_of, Kind, Rotations, VaultAdapter};
39use super::sync_capture;
40use super::sync_links::{self, LinkOwners, Links};
41use super::sync_merge::{self, Decision, Kept, Side as Chose};
42use super::sync_record::{EntryBody, Profiles};
43use super::sync_store::{apply_activity, links_of};
44use super::versions::{self, KEPT_PREFIX, PREVIOUS};
45use crate::backend::storage::store::Store;
46use crate::backend::storage::vault::VaultRow;
47use crate::backend::storage::vault_sync::TakeWrite;
48use crate::backend::storage::vault_versions::VaultVersionRow;
49use crate::backend::user_sync::adapter::{Adapter, Merge};
50use crate::backend::user_sync::hlc::Clock;
51use crate::backend::user_sync::log::{self, Outcome, Pins};
52use crate::backend::user_sync::record::{Header, Record};
53use crate::backend::user_sync::seal::{self as user_seal, KeyRing};
54
55#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum Effect {
58 None,
61 Wrote { entry: String },
63 Deleted { entry: String },
65 Line { machine: String, seq: i64 },
67 Granted { entry: String },
69 Revoked { entry: String },
71 Skipped(String),
73 Deferred(String),
76 KeptInLog(String),
78}
79
80#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct Taken {
83 pub outcome: Outcome,
84 pub effect: Effect,
85 pub kept: Option<String>,
87}
88
89struct Rotating(bool);
91
92impl Rotations for Rotating {
93 fn rotating(&self, _record: &str) -> bool {
94 self.0
95 }
96}
97
98struct Recording<'a> {
100 inner: VaultAdapter<'a>,
101 last: RefCell<Option<Decision>>,
102}
103
104impl Adapter for Recording<'_> {
105 fn merge(&self, local: Option<&Header>, incoming: &Header) -> Merge {
106 let decision = self.inner.decide(local, incoming);
107 let merge = merge_of(&decision);
108 *self.last.borrow_mut() = Some(decision);
109 merge
110 }
111}
112
113struct Reviving<'a> {
116 store: &'a Store,
117 record: &'a str,
118}
119
120impl LinkOwners for Reviving<'_> {
121 fn owner_of(&self, id: &str) -> Option<String> {
122 self.store.owner_of(id)
123 }
124 fn retired(&self, id: &str) -> bool {
125 id != self.record && self.store.retired(id)
126 }
127}
128
129enum Found {
131 None,
132 One(String),
133 Two,
135}
136
137pub struct Taker<'a> {
139 pub machine: &'a str,
141 pub store: &'a Store,
142 pub ring: &'a KeyRing,
143 pub key: &'a Key,
145 pub profiles: &'a dyn Profiles,
146}
147
148pub(super) fn open_body<T: serde::de::DeserializeOwned>(ring: &KeyRing, rec: &Record) -> Result<T, String> {
150 let plain = user_seal::open(ring, &rec.header, &rec.body).map_err(|e| match e {
151 user_seal::OpenError::NoKey => format!("no key for epoch {}", rec.header.epoch),
152 e => format!("a record that does not open: {e:?}"),
153 })?;
154 serde_json::from_slice(&plain).map_err(|_| "a record whose body is not what its id says".to_string())
155}
156
157fn refused(body: &EntryBody) -> Option<String> {
159 let Some(kind) = kinds::kind(&body.kind) else {
160 return Some(format!("a kind this version does not know: {}", body.kind));
161 };
162 body.parts.keys().find(|p| !kind.parts.contains(&p.as_str())).map(|p| format!("a part the kind {} does not have: {p}", kind.name))
163}
164
165fn tags_of(row: &VaultRow) -> Vec<String> {
166 serde_json::from_str(&row.tags).unwrap_or_default()
167}
168
169fn tags_json(tags: &[String]) -> String {
170 serde_json::to_string(tags).unwrap_or_else(|_| "[]".to_string())
171}
172
173fn version(entry_id: &str, created_at: i64, sealed: Vec<u8>, state: String, machine: &str, now_ms: i64) -> VaultVersionRow {
175 VaultVersionRow { seq: 0, entry_id: entry_id.to_string(), entry_created_at: created_at, sealed, replaced_at: now_ms, replaced_by: machine.to_string(), how: "synced".to_string(), state }
176}
177
178impl Taker<'_> {
179 pub fn receive(&self, rec: &Record, pins: &Pins, clock: &mut Clock, now_ms: i64) -> Result<Taken, String> {
184 let h = &rec.header;
185 let holder = match Kind::of(&h.record) {
187 Kind::Entry => match self.find(&self.ids_of(rec))? {
188 Found::One(id) => Some(id),
189 _ => None,
190 },
191 _ => None,
192 };
193 let rotating = match &holder {
194 Some(id) => self.rotation_waits(id)?,
195 None => false,
196 };
197 let (outcome, decision) = {
198 let conn = self.store.conn().lock().unwrap_or_else(|e| e.into_inner());
199 let adapter = Recording { inner: VaultAdapter { conn: &conn, rotations: &Rotating(rotating) }, last: RefCell::new(None) };
200 let outcome = log::apply_remote(&conn, rec, pins, clock, now_ms, &adapter).map_err(|e| format!("{e:?}"))?;
201 (outcome, adapter.last.into_inner())
202 };
203 let none = |outcome| Taken { outcome, effect: Effect::None, kept: None };
204 let Some(decision) = decision else { return Ok(none(outcome)) };
206 let lost = match &decision {
208 Decision::Conflict { current: Chose::Incoming, kept, .. } => Some(kept.label()),
209 _ => None,
210 };
211 let result = match decision {
212 Decision::KeptLocal => return Ok(none(outcome)),
213 Decision::Applied => self.current(rec, None, false, now_ms).map(|effect| Taken { outcome, effect, kept: None }),
214 Decision::Conflict { current: Chose::Incoming, kept, .. } => {
215 let label = kept.label();
216 self.current(rec, Some(&label), false, now_ms).map(|effect| Taken { outcome, effect, kept: Some(label) })
217 }
218 Decision::Conflict { current: Chose::Local, kept, .. } => {
219 let label = kept.label();
220 self.keep_incoming(rec, &label, now_ms).map(|effect| Taken { outcome, effect, kept: Some(label) })
221 }
222 };
223 let (vault, record) = (&h.collection, &h.record);
226 match &result {
227 Err(_) | Ok(Taken { effect: Effect::Deferred(_), .. }) => {
228 sync_capture::retake_mark(self.store, vault, record, lost.as_deref()).map_err(|e| format!("the log holds the record, and it could not be noted for `retake`: {e}"))?;
229 }
230 Ok(_) => drop(sync_capture::retake_clear(self.store, vault, record)),
232 }
233 result.map_err(|e| format!("{e}: the log holds the record, and `retake` takes it again"))
234 }
235
236 pub fn retake(&self, vault: &str, now_ms: i64) -> Result<Vec<(String, Result<Effect, String>)>, String> {
242 let mut out = Vec::new();
243 for (record, lost) in sync_capture::retake_pending(self.store, vault)? {
244 let current = log::current(&self.store.conn().lock().unwrap_or_else(|e| e.into_inner()), vault, &record).map_err(|e| e.to_string())?;
245 let Some(rec) = current else {
246 sync_capture::retake_clear(self.store, vault, &record)?;
247 continue;
248 };
249 let effect = self.current(&rec, lost.as_deref(), true, now_ms);
250 if !matches!(effect, Err(_) | Ok(Effect::Deferred(_))) {
251 sync_capture::retake_clear(self.store, vault, &record)?;
252 }
253 out.push((record, effect));
254 }
255 Ok(out)
256 }
257
258 fn ids_of(&self, rec: &Record) -> Vec<String> {
261 let mut ids = vec![rec.header.record.clone()];
262 if !rec.header.tombstone {
263 if let Ok(body) = open_body::<EntryBody>(self.ring, rec) {
264 ids.extend(body.link_ids.iter().filter(|i| sync_links::is_link_id(i) && **i != rec.header.record).cloned());
265 }
266 }
267 ids
268 }
269
270 fn find(&self, ids: &[String]) -> Result<Found, String> {
273 let mut found: Vec<String> = Vec::new();
274 for id in ids {
275 if let Some(entry) = self.store.vault_entry_of_link(id).map_err(|e| e.to_string())? {
276 if !found.contains(&entry) {
277 found.push(entry);
278 }
279 }
280 }
281 Ok(match found.len() {
282 0 => Found::None,
283 1 => Found::One(found.remove(0)),
284 _ => Found::Two,
285 })
286 }
287
288 fn rotation_waits(&self, entry_id: &str) -> Result<bool, String> {
290 let Some(row) = self.store.vault_get(entry_id).map_err(|e| e.to_string())? else { return Ok(false) };
291 Ok(self.store.vault_versions(&row.id, row.created_at).map_err(|e| e.to_string())?.iter().any(|v| v.state == versions::PENDING))
292 }
293
294 fn current(&self, rec: &Record, lost: Option<&str>, settled: bool, now_ms: i64) -> Result<Effect, String> {
297 match Kind::of(&rec.header.record) {
298 Kind::Activity => return self.line(rec),
299 Kind::Grant => return self.grant(rec),
300 Kind::Entry => {}
301 }
302 if !sync_links::is_link_id(&rec.header.record) {
303 return Ok(Effect::Skipped("a record whose id is not an entry's".to_string()));
304 }
305 if rec.header.tombstone {
306 return self.delete(rec, lost, settled, now_ms);
307 }
308 let body: EntryBody = open_body(self.ring, rec)?;
309 if let Some(why) = refused(&body) {
310 return Ok(Effect::Deferred(why));
311 }
312 match self.write(rec, &body, lost, now_ms)? {
316 Some(effect) => {
317 if let Effect::Wrote { entry } = &effect {
319 self.apply_waiting(entry, &rec.header.collection)?;
320 }
321 Ok(effect)
322 }
323 None => Err("the entry was changed here while its record was taken, so nothing was overwritten".to_string()),
324 }
325 }
326
327 fn write(&self, rec: &Record, body: &EntryBody, lost: Option<&str>, now_ms: i64) -> Result<Option<Effect>, String> {
329 let h = &rec.header;
330 let store = self.store;
331 let mut ids = vec![h.record.clone()];
332 ids.extend(body.link_ids.iter().filter(|i| **i != h.record).cloned());
333 let existing = match self.find(&ids)? {
334 Found::None => None,
335 Found::One(id) => store.vault_get(&id).map_err(|e| e.to_string())?,
336 Found::Two => return Ok(Some(Effect::Deferred("its ids belong to two entries here".to_string()))),
337 };
338 if let Some(old) = existing.as_ref().filter(|r| r.vault_id != h.collection) {
341 let there = log::current(&store.conn().lock().unwrap_or_else(|e| e.into_inner()), &old.vault_id, &h.record).map_err(|e| e.to_string())?;
342 if there.is_some_and(|t| !t.header.tombstone && t.header.version > h.version) {
343 return Ok(Some(Effect::None));
344 }
345 }
346 let mut adopting: Option<(String, String)> = None;
350 if let Some(old) = &existing {
351 if let Some((vault, mine)) = sync_capture::identity_of(store, &old.id)? {
352 if mine != h.record {
353 if h.record > mine {
354 let local = links_of(store, &old.id)?;
355 let settled = sync_links::settle(store, &old.id, &local, &ids);
356 if settled != local {
357 store.vault_links_set(&old.id, settled.primary.as_deref(), &settled.aliases).map_err(|e| e.to_string())?;
358 }
359 return Ok(Some(Effect::Skipped("another record of an entry here: the one with the smaller id is followed".to_string())));
360 }
361 adopting = Some((vault, mine));
362 }
363 }
364 }
365 let entry_id = existing.as_ref().map_or_else(|| uuid::Uuid::new_v4().to_string(), |r| r.id.clone());
366 let local = if existing.is_some() { links_of(store, &entry_id)? } else { Links::default() };
368 let links = sync_links::settle(&Reviving { store, record: &h.record }, &entry_id, &local, &ids);
369 if existing.is_none() && links.primary.as_deref() != Some(h.record.as_str()) {
370 return Ok(Some(Effect::Deferred("its id is held by another entry here".to_string())));
371 }
372 let sealed = seal::seal(self.key, &entry_id, &Parts(body.parts.clone()))?;
373 let mut row = body.into_row(&entry_id, &h.collection, sealed, existing.as_ref(), self.profiles);
374 let machine = h.version.machine.as_str();
375 let adopt_label = Kept::SameTime { machine: self.machine.to_string() }.label();
378 let lost = match (&adopting, &existing) {
379 (Some(_), Some(old)) if lost.is_none() && self.differs(old, &row, body) => Some(adopt_label.as_str()),
380 _ => lost,
381 };
382 let mut kept = Vec::new();
383 match (&existing, lost) {
384 (Some(old), Some(why)) => {
386 kept.push(version(&old.id, old.created_at, old.sealed.clone(), format!("{KEPT_PREFIX}{why}"), machine, now_ms));
387 row.tags = tags_json(&sync_merge::union_tags(&body.tags, &tags_of(old)));
388 }
389 (Some(old), None) => {
391 let same = seal::open(self.key, &old.id, &old.sealed).is_ok_and(|p| p.0 == body.parts);
392 if !same {
393 kept.push(version(&old.id, old.created_at, old.sealed.clone(), PREVIOUS.to_string(), machine, now_ms));
394 }
395 }
396 (None, Some(why)) => kept.push(version(&entry_id, row.created_at, Vec::new(), format!("{KEPT_PREFIX}{why}"), machine, now_ms)),
398 (None, None) => {}
399 }
400 let write = TakeWrite {
401 row: &row,
402 was: existing.as_ref(),
403 primary: links.primary.as_deref(),
404 aliases: &links.aliases,
405 revive: existing.is_none().then_some(h.record.as_str()),
406 kept: &kept,
407 };
408 if !store.vault_take_write(&write).map_err(|e| e.to_string())? {
409 return Ok(None);
410 }
411 sync_capture::mark_seen(store, &row, &h.record, self.key, self.profiles)?;
414 if let Some((vault, mine)) = adopting.filter(|(vault, _)| !vault.is_empty()) {
417 sync_capture::end_record(store, &vault, &mine)?;
418 }
419 Ok(Some(Effect::Wrote { entry: entry_id }))
420 }
421
422 fn line(&self, rec: &Record) -> Result<Effect, String> {
425 let h = &rec.header;
426 let Some((machine, seq)) = sync_activity::parse_record_id(&h.record) else { return Ok(Effect::Skipped("not an activity line".to_string())) };
427 if h.tombstone {
428 return Ok(Effect::Skipped("an activity line is never deleted".to_string()));
429 }
430 if machine != h.origin {
431 return Ok(Effect::Skipped("an activity line named for another machine".to_string()));
432 }
433 let mut body: ActivityBody = open_body(self.ring, rec)?;
434 if let Some(entry) = self.store.vault_entry_of_link(&body.entry_id).map_err(|e| e.to_string())? {
436 body.entry_id = entry;
437 }
438 Ok(match apply_activity(self.store, machine, seq, &body)? {
439 Decision::Applied => Effect::Line { machine: machine.to_string(), seq },
440 _ => Effect::None,
441 })
442 }
443
444 fn delete(&self, rec: &Record, lost: Option<&str>, settled: bool, now_ms: i64) -> Result<Effect, String> {
453 let h = &rec.header;
454 let Some(id) = self.store.vault_entry_of_link(&h.record).map_err(|e| e.to_string())? else { return Ok(Effect::None) };
455 let Some(row) = self.store.vault_get(&id).map_err(|e| e.to_string())? else { return Ok(Effect::None) };
456 if row.vault_id != h.collection {
458 return Ok(Effect::None);
459 }
460 if sync_capture::identity_of(self.store, &id)?.is_some_and(|(_, mine)| mine != h.record) {
462 return Ok(Effect::None);
463 }
464 let moved = log::live_elsewhere(&self.store.conn().lock().unwrap_or_else(|e| e.into_inner()), &h.collection, &h.record).map_err(|e| e.to_string())?;
465 if moved {
466 return Ok(Effect::None);
467 }
468 if self.rotation_waits(&id)? {
472 return self.keep_incoming(rec, &format!("deleted on {} while this was being rotated", h.version.machine), now_ms);
473 }
474 if !settled {
475 return Ok(Effect::Deferred("deleted in this Vault: it waits one round, in case the entry moved to another Vault whose record has not come yet".to_string()));
476 }
477 self.store.vault_delete(&id).map_err(|e| e.to_string())?;
478 sync_capture::forget(self.store, &id)?;
479 Ok(match lost {
480 Some(why) => Effect::KeptInLog(why.to_string()),
481 None => Effect::Deleted { entry: id },
482 })
483 }
484
485 fn differs(&self, old: &VaultRow, new: &VaultRow, body: &EntryBody) -> bool {
487 let same_parts = seal::open(self.key, &old.id, &old.sealed).is_ok_and(|p| p.0 == body.parts);
488 old.kind != new.kind || old.label != new.label || old.fields != new.fields || old.tags != new.tags || !same_parts
489 }
490
491 fn keep_incoming(&self, rec: &Record, label: &str, now_ms: i64) -> Result<Effect, String> {
493 let h = &rec.header;
494 let label = label.to_string();
495 let Some(id) = self.store.vault_entry_of_link(&h.record).map_err(|e| e.to_string())? else { return Ok(Effect::KeptInLog(label)) };
496 let machine = h.version.machine.as_str();
497 let state = format!("{KEPT_PREFIX}{label}");
498 let (sealed, theirs) = if h.tombstone {
500 (Vec::new(), None)
501 } else {
502 let body: EntryBody = open_body(self.ring, rec)?;
503 if let Some(why) = refused(&body) {
504 return Ok(Effect::Skipped(why));
505 }
506 (seal::seal(self.key, &id, &Parts(body.parts.clone()))?, Some(body.tags.clone()))
507 };
508 let Some(row) = self.store.vault_get(&id).map_err(|e| e.to_string())? else { return Ok(Effect::KeptInLog(label)) };
510 let mut next = row.clone();
511 if let Some(theirs) = &theirs {
512 next.tags = tags_json(&sync_merge::union_tags(&tags_of(&row), theirs));
513 }
514 let links = links_of(self.store, &id)?;
515 let kept = [version(&id, row.created_at, sealed, state, machine, now_ms)];
516 let write = TakeWrite { row: &next, was: Some(&row), primary: links.primary.as_deref(), aliases: &links.aliases, revive: None, kept: &kept };
517 if !self.store.vault_take_write(&write).map_err(|e| e.to_string())? {
518 return Err("the entry was changed here while its record was taken, so nothing was overwritten".to_string());
519 }
520 sync_capture::mark_seen(self.store, &next, &h.record, self.key, self.profiles)?;
521 Ok(Effect::Wrote { entry: id })
522 }
523}
524
525#[cfg(test)]
526#[path = "sync_take_tests.rs"]
527mod tests;