Skip to main content

agentmux_srv_core/backend/vault/
sync_store.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Vault's sync rules applied to the store: an entry's link ids and the activity lines other machines made. The rules
5//! are `sync_links` and `sync_activity`; this is what reads and writes the tables they decide for.
6
7use super::sync_activity::{self, ActivityBody};
8use super::sync_links::{self, LinkOwners, Links};
9use super::sync_merge::Decision;
10use crate::backend::storage::store::Store;
11
12/// The store as the one that knows which entry holds an id. A store that cannot answer is taken to hold the id, so an id
13/// is never given away on a failed read.
14impl LinkOwners for Store {
15    fn owner_of(&self, id: &str) -> Option<String> {
16        self.vault_link_holder(id).unwrap_or_else(|_| Some(String::new()))
17    }
18    fn retired(&self, id: &str) -> bool {
19        self.vault_link_retired(id).unwrap_or(true)
20    }
21}
22
23/// The link ids `entry_id` has here: the one this machine gave it, and its aliases.
24pub fn links_of(store: &Store, entry_id: &str) -> Result<Links, String> {
25    Ok(Links { primary: store.vault_link_primary(entry_id).map_err(|e| e.to_string())?, aliases: store.vault_link_aliases(entry_id).map_err(|e| e.to_string())? })
26}
27
28/// Takes the link ids a record for `entry_id` carries (`EntryBody::link_ids`): what this machine had plus the ids it did
29/// not, except those another entry holds or a removed entry had. Returns the ids the entry has now.
30pub fn apply_links(store: &Store, entry_id: &str, incoming: &[String]) -> Result<Links, String> {
31    let local = links_of(store, entry_id)?;
32    let settled = sync_links::settle(store, entry_id, &local, incoming);
33    if settled != local {
34        store.vault_links_set(entry_id, settled.primary.as_deref(), &settled.aliases).map_err(|e| e.to_string())?;
35    }
36    links_of(store, entry_id)
37}
38
39/// Adds the activity line machine `machine` made as its number `seq`, unless this machine already has it. The line goes
40/// in the table of other machines' lines, outside this machine's hash chain.
41pub fn apply_activity(store: &Store, machine: &str, seq: i64, body: &ActivityBody) -> Result<Decision, String> {
42    let have = store.vault_activity_remote_has(machine, seq).map_err(|e| e.to_string())?;
43    let decision = sync_activity::merge(have);
44    if decision == Decision::Applied {
45        store.vault_activity_remote_add(machine, seq, &body.into_row(seq)).map_err(|e| e.to_string())?;
46    }
47    Ok(decision)
48}
49
50#[cfg(test)]
51#[path = "sync_store_tests.rs"]
52mod tests;