1use serde::de::DeserializeOwned;
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15
16use super::{AppState, RemoteCaller, RemoteRefusal, RemoteResult};
17use crate::backend::storage::store::Store;
18use crate::backend::storage::wan_identity::{self, WanIdentityStore};
19use crate::backend::user_sync::adapter::Adapter;
20use crate::backend::user_sync::hlc::Clock;
21use crate::backend::user_sync::kanban::KanbanAdapter;
22use crate::backend::user_sync::lock::{self, Lock, LEASE_MS};
23use crate::backend::user_sync::keys::{SqlKeys, StoreKeys};
24use crate::backend::user_sync::ops::{self, Ctx, Held, JoinReq, Joined, KeysAns, KeysReq, Me, MembersAns, MembersReq, OpError, Proof, PullAns, PullReq, PushAns, PushReq};
25use crate::backend::user_sync::{chain_store, log};
26
27pub(super) const MIN_PIN_AGE_MS: i64 = 10 * 60 * 1000;
29
30struct LanProof(bool);
32
33impl Proof for LanProof {
34 fn auto_proven(&self, _machine: &str) -> bool {
35 self.0
36 }
37}
38
39#[derive(Deserialize)]
40struct HelloReq {
41 collections: Vec<String>,
42}
43
44#[derive(Serialize, Deserialize)]
45pub(super) struct HelloAns {
46 pub(super) held: Vec<Held>,
47}
48
49fn parse<T: DeserializeOwned>(op: &str, params: Value) -> Result<T, RemoteRefusal> {
50 serde_json::from_value(params).map_err(|e| RemoteRefusal::new("bad_params", format!("{op}: {e}")))
51}
52
53fn refusal(e: OpError) -> RemoteRefusal {
54 let message = match &e {
55 OpError::NotActive => "this install does not hold the computer's sync lock".to_string(),
56 OpError::NotMember => "not a member of that collection".to_string(),
57 OpError::TooBig => "over the size a sync op takes or gives".to_string(),
58 OpError::Bad => "not a request this machine can take".to_string(),
59 OpError::NoKey => "no key to give".to_string(),
60 OpError::Db(m) => m.clone(),
61 };
62 RemoteRefusal::new(e.code(), message)
63}
64
65fn failed(what: impl std::fmt::Display) -> RemoteRefusal {
66 RemoteRefusal::failed(what.to_string())
67}
68
69pub(super) fn with_ctx<R>(store: &Store, wan: &WanIdentityStore, pinned_since: Option<i64>, f: impl FnOnce(&mut Ctx) -> R) -> Result<R, RemoteRefusal> {
73 let me = wan.instance_ensure(&crate::backend::reactive::registry::local_host_label()).map_err(failed)?;
74 let now = agentmux_common::time::now_ms();
75 let conn = store.conn().lock().map_err(|_| failed("the store is busy"))?;
76 log::init(&conn).map_err(failed)?;
77 let active = matches!(lock::acquire(&conn, &me.instance_id, now, LEASE_MS).map_err(failed)?, Lock::Held { .. });
78 let mut chains = chain_store::load_all(&conn).map_err(|e| failed(format!("a stored membership chain is not sound: {e:?}")))?;
79 let mut clock = Clock::new(&me.instance_id);
80 let mut pending = chain_store::load_pending(&conn).map_err(|e| failed(format!("the waiting joins are not readable: {e:?}")))?;
81 let keystore = SqlKeys(&conn);
82 let keys = StoreKeys { store: &keystore, wan_public: me.public_key, wan_seed: me.private_key };
83 let proof = LanProof(pinned_since.is_some_and(|since| now - since >= MIN_PIN_AGE_MS));
84 let answer = {
85 let mut ctx = Ctx {
86 conn: &conn,
87 chains: &mut chains,
88 clock: &mut clock,
89 pending: &mut pending,
90 me: Me { id: &me.instance_id, private: &me.private_key },
91 proof: &proof,
92 keys: &keys,
93 now_ms: now,
94 chain_cap: ops::MAX_ENTRIES,
95 active,
96 };
97 f(&mut ctx)
98 };
99 chain_store::save_pending(&conn, &pending).map_err(failed)?;
100 Ok(answer)
101}
102
103fn exec<Req, Ans>(
104 store: &Store,
105 wan: &WanIdentityStore,
106 machine: &str,
107 pinned_since: Option<i64>,
108 req: Req,
109 run: impl FnOnce(&mut Ctx, &str, Req) -> Result<Ans, OpError>,
110) -> Result<Ans, RemoteRefusal> {
111 with_ctx(store, wan, pinned_since, |ctx| run(ctx, machine, req).map_err(refusal))?
112}
113
114async fn run<Req, Ans>(
115 state: &AppState,
116 caller: &RemoteCaller,
117 op: &'static str,
118 params: Value,
119 f: impl FnOnce(&mut Ctx, &str, Req) -> Result<Ans, OpError> + Send + 'static,
120) -> RemoteResult
121where
122 Req: DeserializeOwned + Send + 'static,
123 Ans: Serialize + Send + 'static,
124{
125 if caller.instance_id.is_empty() {
126 return Err(RemoteRefusal::new("needs_certificate", format!("{op} is answered only for an install that showed a certificate")));
127 }
128 let req: Req = parse(op, params)?;
129 let store = state.id_store.clone();
130 let wan = state.mstore.wan_identity().or_else(wan_identity::global).ok_or_else(|| failed("this install has no identity yet"))?;
131 let pinned_since = state.mstore.lan_peer_pubkey_pin_since(&caller.slug).ok().flatten().map(|(_, at)| at);
132 let machine = caller.instance_id.clone();
133 let answer = tokio::task::spawn_blocking(move || exec(&store, &wan, &machine, pinned_since, req, f))
134 .await
135 .map_err(|e| failed(format!("{op} did not finish: {e}")))??;
136 serde_json::to_value(answer).map_err(failed)
137}
138
139pub(super) fn adapter_for(kind: &str) -> Option<Box<dyn Adapter>> {
141 match kind {
142 "kanban" => Some(Box::new(KanbanAdapter)),
143 _ => None,
144 }
145}
146
147pub(super) async fn hello(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
148 run(state, caller, "sync.hello", params, |ctx, who, req: HelloReq| Ok(HelloAns { held: ops::hello(ctx, who, &req.collections)? })).await
149}
150
151pub(super) async fn pull(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
152 run(state, caller, "sync.pull", params, |ctx, who, req: PullReq| -> Result<PullAns, OpError> { ops::pull(ctx, who, &req) }).await
153}
154
155pub(super) async fn push(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
156 run(state, caller, "sync.push", params, |ctx, who, req: PushReq| -> Result<PushAns, OpError> {
157 ops::admit(ctx, &req.collection, who)?;
159 let kind = ops::kind_of(ctx.conn, &req.collection).map_err(|_| OpError::NotMember)?;
160 let adapter = adapter_for(&kind).ok_or(OpError::Bad)?;
161 ops::push(ctx, who, &req, adapter.as_ref())
162 })
163 .await
164}
165
166pub(super) async fn members(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
167 run(state, caller, "sync.members", params, |ctx, who, req: MembersReq| -> Result<MembersAns, OpError> { ops::members(ctx, who, &req) }).await
168}
169
170pub(super) async fn join(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
171 run(state, caller, "sync.join", params, |ctx, who, req: JoinReq| -> Result<Joined, OpError> { ops::join(ctx, who, &req) }).await
172}
173
174pub(super) async fn keys(state: &AppState, caller: &RemoteCaller, params: Value) -> RemoteResult {
175 run(state, caller, "sync.keys", params, |ctx, who, req: KeysReq| -> Result<KeysAns, OpError> { ops::keys(ctx, who, &req) }).await
176}
177
178#[cfg(test)]
179mod tests;