Skip to main content

agentmux_srv_core/backend/user_sync/
ops.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The bodies of the `sync.*` ops as pure functions (SPEC_USER_DATA_SYNC_LAYER §3.1, §4): `hello`, `pull`, `push`,
5//! `members` and `join`, over the log, the membership chains and the caller's proven machine id. Nothing here opens a
6//! connection or sends anything: a request comes in, an answer goes out, and what a function may touch is what
7//! [`Ctx`] hands it. The transport (the remote-ops route on the LAN) is wired to these separately.
8//!
9//! Every op starts with the same two checks: this install holds the computer's sync lock (otherwise it answers
10//! nothing), and the caller is a current member of the collection it names (a stranger, and a collection this
11//! machine does not hold, get the same refusal). Both answers are capped: at the handler on the way out, and by
12//! [`check_pull_answer`] on the way in.
13
14use std::collections::BTreeMap;
15
16use rusqlite::Connection;
17use serde::{Deserialize, Serialize};
18
19use super::adapter::Adapter;
20use super::chain_store;
21use super::hlc::Clock;
22use super::log::{self, Outcome, Refused, Signer, SyncError, Vector};
23use super::members::{Chain, Change, Entry, Kind, MemberError, Policy, State, Subject, Taken};
24use super::record::{Record, MAX_RECORD_BYTES};
25use super::seal::{self, KeyRing};
26
27/// Most collections one `hello` may ask about, and most origins one vector may name.
28pub const MAX_NAMES: usize = 64;
29/// Most records in one `pull` answer or `push` request.
30pub const MAX_BATCH_RECORDS: usize = 200;
31/// Most bytes in one batch, counting each record's body and a fixed amount for its header. One record larger than
32/// this goes alone (up to `MAX_RECORD_BYTES`).
33pub const MAX_BATCH_BYTES: usize = 256 * 1024;
34/// Most entries of a membership chain one answer carries; a longer chain is not served until it is compacted.
35#[cfg(not(test))]
36pub const MAX_ENTRIES: usize = 256;
37/// Small under test, so a chain over it is built with a few entries.
38#[cfg(test)]
39pub const MAX_ENTRIES: usize = 16;
40/// Most join requests one collection keeps waiting for a person.
41pub const MAX_PENDING: usize = 16;
42/// How long a join waits for a person before it is dropped (the machine asks again).
43pub const PENDING_TTL_MS: i64 = 24 * 60 * 60 * 1000;
44/// Kinds of collection whose joins may go ahead without a person confirming (a Vault never does yet).
45pub const AUTO_JOIN_KINDS: [&str; 1] = ["kanban"];
46
47/// The most bytes of JSON params a sync op takes: a batch at its largest as base64, its headers, and what is around
48/// them. A record too large for a push is pulled by the peer instead (an answer is not held to this).
49pub const MAX_WIRE_BYTES: usize = MAX_BATCH_BYTES / 3 * 4 + MAX_BATCH_RECORDS * 1024 + 64 * 1024;
50
51const HEADER_WEIGHT: usize = 512;
52
53/// Why an op did not run.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum OpError {
56    /// This install does not hold the computer's sync lock.
57    NotActive,
58    /// The caller is not a member of the collection, or this machine does not hold it.
59    NotMember,
60    /// A request or an answer over a cap.
61    TooBig,
62    /// A request that is not what it says (a join for another machine, an entry that does not sign or extend).
63    Bad,
64    /// A member was added but no key could be sealed to it: nothing was done.
65    NoKey,
66    Db(String),
67}
68
69impl OpError {
70    /// The code an op's refusal carries to the asker.
71    pub fn code(&self) -> &'static str {
72        match self {
73            OpError::NotActive => "not_active",
74            OpError::NotMember => "not_member",
75            OpError::TooBig => "too_big",
76            OpError::Bad => "bad_request",
77            OpError::NoKey => "no_key",
78            OpError::Db(_) => "failed",
79        }
80    }
81}
82
83impl From<rusqlite::Error> for OpError {
84    fn from(e: rusqlite::Error) -> Self {
85        OpError::Db(e.to_string())
86    }
87}
88
89/// This machine as a member: its id and its signing key's seed (held only while it holds the lock).
90pub struct Me<'a> {
91    pub id: &'a str,
92    pub private: &'a [u8; 32],
93}
94
95/// Whether a machine asking to join is proven enough for a join without a person: pinned here for at least a minimum
96/// age, listed in the account's directory, and hosted by an install whose certificate chain is the one remote writes
97/// already require. The transport supplies it.
98pub trait Proof {
99    fn auto_proven(&self, machine: &str) -> bool;
100}
101
102/// Seals the collection's keys to a new member's box key: one sealed key for each epoch the member needs.
103pub trait KeyDelivery {
104    fn keys_for(&self, collection: &str, to: &Subject) -> Vec<(u32, String)>;
105    /// Makes and keeps the key of an epoch before a change that starts it is signed: false if it could not be made.
106    fn mint(&self, _collection: &str, _epoch: u32) -> bool {
107        true
108    }
109    /// Opens keys another member sealed to this machine and keeps them: how many were taken.
110    fn take(&self, _collection: &str, _keys: &[(u32, String)]) -> usize {
111        0
112    }
113    /// Forgets the key this machine made for an epoch whose removal lost a fork to another entry.
114    fn discard(&self, _collection: &str, _epoch: u32) {}
115    /// The epochs this machine holds a key for.
116    fn held(&self, _collection: &str) -> Vec<u32> {
117        Vec::new()
118    }
119    /// The keys this machine holds for a collection, to open what it wrote at an older epoch and seal it again.
120    fn ring(&self, _collection: &str) -> KeyRing {
121        KeyRing::new()
122    }
123}
124
125/// A machine waiting for a person to confirm its join on this member.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct PendingJoin {
128    pub collection: String,
129    pub subject: Subject,
130    pub asked_at: i64,
131}
132
133/// Everything an op may touch.
134pub struct Ctx<'a> {
135    pub conn: &'a Connection,
136    pub chains: &'a mut BTreeMap<String, Chain>,
137    pub clock: &'a mut Clock,
138    pub pending: &'a mut Vec<PendingJoin>,
139    pub me: Me<'a>,
140    pub proof: &'a dyn Proof,
141    pub keys: &'a dyn KeyDelivery,
142    pub now_ms: i64,
143    /// The longest chain this machine hands over (`MAX_ENTRIES` unless a caller sets less).
144    pub chain_cap: usize,
145    /// Whether this install holds the computer's sync lock right now.
146    pub active: bool,
147}
148
149enum Standing {
150    Current(State),
151    /// Was a member and is not now: may learn how it was removed, and nothing else.
152    Former,
153    Stranger,
154}
155
156fn standing(ctx: &Ctx, collection: &str, caller: &str) -> Standing {
157    let Some(chain) = ctx.chains.get(collection) else { return Standing::Stranger };
158    let Ok(state) = chain.state(collection) else { return Standing::Stranger };
159    if state.members.get(caller).is_some_and(|m| m.kind == Kind::Machine) {
160        return Standing::Current(state);
161    }
162    let was = chain.entries.iter().any(|e| matches!(&e.change, Change::Found { member, .. } | Change::Add { member } if member.id == caller));
163    if was {
164        Standing::Former
165    } else {
166        Standing::Stranger
167    }
168}
169
170fn gate(ctx: &Ctx) -> Result<(), OpError> {
171    if ctx.active {
172        Ok(())
173    } else {
174        Err(OpError::NotActive)
175    }
176}
177
178/// The state of a collection whose current member the caller is: the check made before any op that reads or writes.
179fn member(ctx: &Ctx, collection: &str, caller: &str) -> Result<State, OpError> {
180    gate(ctx)?;
181    match standing(ctx, collection, caller) {
182        Standing::Current(state) => Ok(state),
183        _ => Err(OpError::NotMember),
184    }
185}
186
187/// The checks every op that reads or writes makes first (this install holds the lock, the caller is a current member),
188/// for a caller that has more to look up before the op itself: nothing about a collection (its kind, whether this build
189/// merges it) is told to a caller that fails them.
190pub fn admit(ctx: &Ctx, collection: &str, caller: &str) -> Result<(), OpError> {
191    member(ctx, collection, caller).map(|_| ())
192}
193
194fn weight(r: &Record) -> usize {
195    r.body.len() + HEADER_WEIGHT
196}
197
198fn within_caps(records: &[Record]) -> bool {
199    let bytes: usize = records.iter().map(weight).sum();
200    records.len() <= MAX_BATCH_RECORDS
201        && (records.len() <= 1 || bytes <= MAX_BATCH_BYTES)
202        && records.iter().all(|r| r.body.len() as u64 <= MAX_RECORD_BYTES)
203}
204
205/// What a machine holds of one collection.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207pub struct Held {
208    pub collection: String,
209    pub n: u64,
210    pub head: Option<String>,
211    pub epoch: u32,
212    pub vector: Vector,
213}
214
215/// `sync.hello`: for each named collection the caller is a member of, the chain position, the key epoch and what this
216/// machine holds. A collection the caller is not a member of is left out, as if it did not exist.
217pub fn hello(ctx: &Ctx, caller: &str, collections: &[String]) -> Result<Vec<Held>, OpError> {
218    gate(ctx)?;
219    if collections.len() > MAX_NAMES {
220        return Err(OpError::TooBig);
221    }
222    let mut out = Vec::new();
223    for c in collections {
224        if let Standing::Current(state) = standing(ctx, c, caller) {
225            out.push(Held { collection: c.clone(), n: state.n, head: state.head.clone(), epoch: state.epoch, vector: log::vector(ctx.conn, c)? });
226        }
227    }
228    Ok(out)
229}
230
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232pub struct PullReq {
233    pub collection: String,
234    pub vector: Vector,
235    pub limit: usize,
236}
237
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239pub struct PullAns {
240    pub records: Vec<Record>,
241    /// More remain: ask again with the vector after applying these.
242    pub more: bool,
243    pub epoch: u32,
244    pub n: u64,
245}
246
247/// `sync.pull`: the records the caller lacks, capped in count and bytes.
248pub fn pull(ctx: &Ctx, caller: &str, req: &PullReq) -> Result<PullAns, OpError> {
249    let state = member(ctx, &req.collection, caller)?;
250    if req.vector.len() > MAX_NAMES {
251        return Err(OpError::TooBig);
252    }
253    let cap = req.limit.clamp(1, MAX_BATCH_RECORDS);
254    let mut records = log::since(ctx.conn, &req.collection, &req.vector, cap + 1)?;
255    let mut more = records.len() > cap;
256    records.truncate(cap);
257    more |= cap_bytes(&mut records);
258    Ok(PullAns { records, more, epoch: state.epoch, n: state.n })
259}
260
261/// Cuts a batch to the byte cap (a first record always stays): whether anything was cut.
262pub fn cap_bytes(records: &mut Vec<Record>) -> bool {
263    let (mut bytes, mut keep) = (0, 0);
264    for r in records.iter() {
265        if keep > 0 && bytes + weight(r) > MAX_BATCH_BYTES {
266            break;
267        }
268        bytes += weight(r);
269        keep += 1;
270    }
271    let cut = keep < records.len();
272    records.truncate(keep);
273    cut
274}
275
276/// The asker's side of the cap: an answer over what was asked, or over the byte cap, is refused whole.
277pub fn check_pull_answer(ans: &PullAns, asked: usize) -> Result<(), OpError> {
278    if ans.records.len() > asked.clamp(1, MAX_BATCH_RECORDS) || !within_caps(&ans.records) {
279        return Err(OpError::TooBig);
280    }
281    Ok(())
282}
283
284#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
285pub struct PushReq {
286    pub collection: String,
287    pub records: Vec<Record>,
288}
289
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291pub struct PushAns {
292    /// One result per record, in order.
293    pub results: Vec<Result<Outcome, Refused>>,
294    /// What this machine holds now, so the pusher sends what is still lacking (after a `Gap`, or a cut-off write
295    /// re-issued at the new epoch).
296    pub vector: Vector,
297    pub epoch: u32,
298}
299
300/// `sync.push`: records from the caller (its own, or ones it forwards). A request over the caps is refused before
301/// anything is applied; each record is checked and applied on its own.
302pub fn push(ctx: &mut Ctx, caller: &str, req: &PushReq, adapter: &dyn Adapter) -> Result<PushAns, OpError> {
303    let state = member(ctx, &req.collection, caller)?;
304    if !within_caps(&req.records) {
305        return Err(OpError::TooBig);
306    }
307    let pins = state.pins();
308    let mut results = Vec::with_capacity(req.records.len());
309    for rec in &req.records {
310        if rec.header.collection != req.collection {
311            results.push(Err(Refused::UnknownCollection));
312            continue;
313        }
314        match log::apply_remote(ctx.conn, rec, &pins, ctx.clock, ctx.now_ms, adapter) {
315            Ok(o) => results.push(Ok(o)),
316            Err(SyncError::Refused(r)) => results.push(Err(r)),
317            Err(SyncError::Db(e)) => return Err(e.into()),
318            Err(SyncError::Seal(e)) => return Err(OpError::Db(e)),
319        }
320    }
321    Ok(PushAns { results, vector: log::vector(ctx.conn, &req.collection)?, epoch: state.epoch })
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325pub struct MembersReq {
326    pub collection: String,
327    /// How many entries the caller holds.
328    pub have_n: u64,
329    /// Entries the caller offers (a member only).
330    pub offered: Vec<Entry>,
331}
332
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
334pub struct MembersAns {
335    pub entries: Vec<Entry>,
336    pub n: u64,
337    /// One result per offered entry, in order.
338    pub taken: Vec<Result<Taken, MemberError>>,
339}
340
341/// Puts the log's key epoch, and the end each remaining member had at each epoch left, exactly where the chain says
342/// (one removal moves it one epoch): in either direction, so a removal that lost a fork to another entry leaves
343/// nothing behind. Called after every change to a chain.
344pub fn sync_epoch(conn: &Connection, collection: &str, chain: &Chain) -> Result<(), OpError> {
345    atomically(conn, |c| epoch_to_chain(c, collection, chain))
346}
347
348/// Runs `f` as one change to the store: all of what it wrote stays, or (when it fails) none of it.
349fn atomically<T>(conn: &Connection, f: impl FnOnce(&Connection) -> Result<T, OpError>) -> Result<T, OpError> {
350    conn.execute_batch("SAVEPOINT sync_atomic")?;
351    match f(conn) {
352        Ok(v) => {
353            conn.execute_batch("RELEASE sync_atomic")?;
354            Ok(v)
355        }
356        Err(e) => {
357            // Undone, then closed: a savepoint left open would hold the store's write lock.
358            let _ = conn.execute_batch("ROLLBACK TO sync_atomic; RELEASE sync_atomic");
359            Err(e)
360        }
361    }
362}
363
364/// The key epoch and the stored chain, moved together: the log never keeps an epoch its stored chain does not say, nor
365/// a chain whose epoch was not moved with it, whatever stops the write part-way.
366fn store_chain(conn: &Connection, collection: &str, chain: &Chain) -> Result<(), OpError> {
367    atomically(conn, |c| {
368        epoch_to_chain(c, collection, chain)?;
369        chain_store::save_in(c, collection, chain)?;
370        Ok(())
371    })
372}
373
374fn epoch_to_chain(conn: &Connection, collection: &str, chain: &Chain) -> Result<(), OpError> {
375    let removals: Vec<&BTreeMap<String, u64>> = chain.entries.iter().filter_map(|e| if let Change::Remove { ended, .. } = &e.change { Some(ended) } else { None }).collect();
376    let cuts: Vec<(u32, &log::Vector)> = removals.iter().enumerate().map(|(i, ended)| (i as u32, *ended)).collect();
377    log::reset_epochs(conn, collection, removals.len() as u32, &cuts)?;
378    Ok(())
379}
380
381/// How many removals each prefix of the chain holds: `[k]` is the epoch a branch that starts at entry `k + 1` begins at.
382/// Read before an entry is taken, because taking it can replace the very entries the epoch is counted from.
383pub(super) fn removals_before(chain: &Chain) -> Vec<u32> {
384    let mut counts = vec![0u32];
385    for e in &chain.entries {
386        let last = counts.last().copied().unwrap_or(0);
387        counts.push(last + u32::from(matches!(e.change, Change::Remove { .. })));
388    }
389    counts
390}
391
392/// The key epochs of the removals one taken entry displaced. A removal that lost a fork to another entry leaves no key
393/// behind for its epoch, whichever machine signed it or made the key: the winner's key is the one that counts, and is taken
394/// when it is offered. A branch that lost may hold several removals, each at the epoch the entries before it on that branch
395/// made. `before` is [`removals_before`] of the chain as it was just before this entry was taken, so the epoch the displaced
396/// branch started at is the one that chain had there, whatever later entries of the same batch replace.
397pub(super) fn lost_epochs(before: &[u32], taken: &Result<Taken, MemberError>) -> Vec<u32> {
398    let Ok(Taken::Replaced(lost)) = taken else {
399        return Vec::new();
400    };
401    // The entries before the first one lost are the chain's own, which the lost branch shared.
402    let shared = lost.first().map_or(0, |e| e.n.saturating_sub(1) as usize);
403    let mut epoch = before.get(shared).or(before.last()).copied().unwrap_or(0);
404    let mut out = Vec::new();
405    for e in lost.iter().filter(|e| matches!(e.change, Change::Remove { .. })) {
406        epoch += 1;
407        out.push(epoch);
408    }
409    out
410}
411
412/// Forgets the keys of the epochs `lost_epochs` named, once the chain they came from is stored.
413pub(super) fn discard_lost_keys(keys: &dyn KeyDelivery, collection: &str, epochs: &[u32]) {
414    for epoch in epochs {
415        keys.discard(collection, *epoch);
416    }
417}
418
419/// A former member is told how it was removed and nothing that came after.
420fn visible_to_former(entries: &[Entry], caller: &str) -> usize {
421    entries.iter().position(|e| matches!(&e.change, Change::Remove { id, .. } if id == caller)).map_or(0, |i| i + 1)
422}
423
424/// `sync.members`: takes the entries a member offers (each one verified against the chain, so an entry no member
425/// signed is refused), and answers with the entries after the caller's position. A machine that was removed may ask
426/// too, and learns up to its own removal.
427pub fn members(ctx: &mut Ctx, caller: &str, req: &MembersReq) -> Result<MembersAns, OpError> {
428    gate(ctx)?;
429    if req.offered.len() > MAX_ENTRIES {
430        return Err(OpError::TooBig);
431    }
432    let was_current = match standing(ctx, &req.collection, caller) {
433        Standing::Current(_) => true,
434        Standing::Former => false,
435        Standing::Stranger => return Err(OpError::NotMember),
436    };
437    let mut taken = Vec::new();
438    let mut lost: Vec<u32> = Vec::new();
439    if was_current {
440        let chain = ctx.chains.get_mut(&req.collection).ok_or(OpError::NotMember)?;
441        let before = chain.clone();
442        taken = req
443            .offered
444            .iter()
445            .map(|e| {
446                let epochs = removals_before(chain);
447                let t = chain.take(&req.collection, e.clone());
448                lost.extend(lost_epochs(&epochs, &t));
449                t
450            })
451            .collect();
452        if let Err(e) = store_chain(ctx.conn, &req.collection, chain) {
453            // Not stored: the chain held here stays what the store says, and no key is discarded for it.
454            *chain = before;
455            return Err(e);
456        }
457        discard_lost_keys(ctx.keys, &req.collection, &lost);
458    }
459    // What the caller may read is decided after its offers are taken: one that removes the caller itself ends what it sees.
460    let still_current = matches!(standing(ctx, &req.collection, caller), Standing::Current(_));
461    let chain = &ctx.chains[&req.collection];
462    let upto = if still_current { chain.entries.len() } else { visible_to_former(&chain.entries, caller) };
463    let from = (req.have_n as usize).min(upto);
464    let entries: Vec<Entry> = chain.entries[from..upto].iter().take(MAX_ENTRIES).cloned().collect();
465    Ok(MembersAns { entries, n: chain.entries.len() as u64, taken })
466}
467
468#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
469pub struct KeysReq {
470    pub collection: String,
471    /// The epochs the caller already holds a key for.
472    pub have: Vec<u32>,
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476pub struct KeysAns {
477    /// The keys the caller lacks, each sealed to the caller's box key as the chain lists it, for its epoch only.
478    pub keys: Vec<(u32, String)>,
479}
480
481/// `sync.keys`: the collection's keys a current member lacks (it learned of a removal, or lost one), sealed to it. A
482/// machine that is not a current member is given none, and never a key of an epoch the chain has not reached.
483pub fn keys(ctx: &Ctx, caller: &str, req: &KeysReq) -> Result<KeysAns, OpError> {
484    let state = member(ctx, &req.collection, caller)?;
485    if req.have.len() > MAX_NAMES {
486        return Err(OpError::TooBig);
487    }
488    let to = state.members.get(caller).ok_or(OpError::NotMember)?;
489    let keys = ctx.keys.keys_for(&req.collection, to).into_iter().filter(|(epoch, _)| *epoch <= state.epoch && !req.have.contains(epoch)).collect();
490    Ok(KeysAns { keys })
491}
492
493/// Whether this machine may seal a new record for the collection. Not while a removal at the chain's head is
494/// contested: the key epoch it would seal at may be replaced by another's.
495pub fn may_seal(ctx: &Ctx, collection: &str) -> bool {
496    ctx.chains.get(collection).is_some_and(|c| !c.epoch_contested())
497}
498
499#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
500pub struct JoinReq {
501    pub collection: String,
502    pub subject: Subject,
503}
504
505#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
506pub enum Joined {
507    /// The caller is a member: the whole chain, and the collection's keys sealed to it.
508    Added { entries: Vec<Entry>, keys: Vec<(u32, String)> },
509    /// A person must confirm on a member before it is added.
510    Pending,
511}
512
513pub fn kind_of(conn: &Connection, collection: &str) -> Result<String, OpError> {
514    Ok(conn.query_row("SELECT kind FROM db_sync_collections WHERE id = ?1", [collection], |r| r.get(0))?)
515}
516
517/// A membership change signed by this machine and taken into its own chain (the key epoch moves too, for a removal):
518/// the entry to hand to the other members. Nothing is signed unless this install holds the lock.
519pub fn change(ctx: &mut Ctx, collection: &str, change: Change) -> Result<Entry, OpError> {
520    gate(ctx)?;
521    // A removal starts the next key epoch: its key is made first, fresh (one left by an earlier attempt is never
522    // reused), so no member is removed that cannot be given one. If the removal is not then signed and taken, the key
523    // is forgotten again, so no key exists for an epoch that has not started.
524    let starts = if matches!(change, Change::Remove { .. }) { Some(chain_epoch(ctx, collection)? + 1) } else { None };
525    if let Some(next) = starts {
526        ctx.keys.discard(collection, next);
527        if !ctx.keys.mint(collection, next) {
528            return Err(OpError::NoKey);
529        }
530    }
531    let done = sign_and_take(ctx, collection, change);
532    if let (Err(_), Some(next)) = (&done, starts) {
533        ctx.keys.discard(collection, next);
534    }
535    done
536}
537
538fn chain_epoch(ctx: &Ctx, collection: &str) -> Result<u32, OpError> {
539    let chain = ctx.chains.get(collection).ok_or(OpError::NotMember)?;
540    Ok(chain.state(collection).map_err(|_| OpError::Bad)?.epoch)
541}
542
543fn sign_and_take(ctx: &mut Ctx, collection: &str, change: Change) -> Result<Entry, OpError> {
544    let chain = ctx.chains.get_mut(collection).ok_or(OpError::NotMember)?;
545    let entry = chain.next(ctx.me.private, collection, ctx.me.id, change).ok_or(OpError::Bad)?;
546    let before = chain.clone();
547    chain.take(collection, entry.clone()).map_err(|_| OpError::Bad)?;
548    if let Err(e) = store_chain(ctx.conn, collection, chain) {
549        *chain = before;
550        return Err(e);
551    }
552    Ok(entry)
553}
554
555fn added(ctx: &Ctx, collection: &str, keys: Vec<(u32, String)>) -> Result<Joined, OpError> {
556    let chain = &ctx.chains[collection];
557    if chain.entries.len() > ctx.chain_cap {
558        return Err(OpError::TooBig);
559    }
560    Ok(Joined::Added { entries: chain.entries.clone(), keys })
561}
562
563/// The keys to hand a machine that is about to be a member: none means nothing is done.
564fn keys_or_refuse(ctx: &Ctx, collection: &str, subject: &Subject) -> Result<Vec<(u32, String)>, OpError> {
565    // Only the epochs the chain has reached: a key for one that has not started is never handed out.
566    let reached = chain_epoch(ctx, collection)?;
567    let keys: Vec<(u32, String)> = ctx.keys.keys_for(collection, subject).into_iter().filter(|(epoch, _)| *epoch <= reached).collect();
568    if keys.is_empty() {
569        return Err(OpError::NoKey);
570    }
571    Ok(keys)
572}
573
574/// `sync.join`: a machine asks to be added. The caller must be the machine the subject names. If it is already a
575/// member it is answered again (a retry after a person confirmed). Otherwise it joins at once only when the
576/// collection's policy is `auto_proven`, the collection is of a kind that allows it and the caller is proven; any
577/// other join waits for a person to confirm on a member ([`approve`]).
578pub fn join(ctx: &mut Ctx, caller: &str, req: &JoinReq) -> Result<Joined, OpError> {
579    gate(ctx)?;
580    let state = ctx.chains.get(&req.collection).and_then(|c| c.state(&req.collection).ok()).ok_or(OpError::NotMember)?;
581    if !state.members.contains_key(ctx.me.id) {
582        return Err(OpError::NotMember);
583    }
584    if req.subject.kind != Kind::Machine || req.subject.id != caller {
585        return Err(OpError::Bad);
586    }
587    if !req.subject.valid() {
588        return Err(OpError::Bad);
589    }
590    let kind = kind_of(ctx.conn, &req.collection)?;
591    let already = state.members.get(caller) == Some(&req.subject);
592    let at_once = state.policy == Policy::AutoProven && AUTO_JOIN_KINDS.contains(&kind.as_str()) && ctx.proof.auto_proven(caller);
593    if !already && !at_once {
594        return wait_for_person(ctx, &req.collection, &req.subject);
595    }
596    let keys = keys_or_refuse(ctx, &req.collection, &req.subject)?;
597    if !already {
598        room_for_one_more(ctx, &req.collection)?;
599        change(ctx, &req.collection, Change::Add { member: req.subject.clone() })?;
600        ctx.pending.retain(|p| !(p.collection == req.collection && p.subject.id == caller));
601    }
602    added(ctx, &req.collection, keys)
603}
604
605/// Refuses before anything is signed when one more entry would make the chain longer than an answer may carry (a
606/// member added whose chain could then not be handed over is never left behind).
607fn room_for_one_more(ctx: &Ctx, collection: &str) -> Result<(), OpError> {
608    let len = ctx.chains.get(collection).map_or(0, |c| c.entries.len());
609    if len + 1 > ctx.chain_cap {
610        return Err(OpError::TooBig);
611    }
612    Ok(())
613}
614
615fn wait_for_person(ctx: &mut Ctx, collection: &str, subject: &Subject) -> Result<Joined, OpError> {
616    let now = ctx.now_ms;
617    ctx.pending.retain(|p| now - p.asked_at < PENDING_TTL_MS);
618    let waiting = ctx.pending.iter().filter(|p| p.collection == collection).count();
619    let already = ctx.pending.iter().any(|p| p.collection == collection && p.subject.id == subject.id);
620    if !already {
621        if waiting >= MAX_PENDING {
622            return Err(OpError::TooBig);
623        }
624        ctx.pending.push(PendingJoin { collection: collection.to_string(), subject: subject.clone(), asked_at: ctx.now_ms });
625    }
626    Ok(Joined::Pending)
627}
628
629/// A person confirmed, on this member, that a waiting machine may join: the signed `Add` (the member then answers the
630/// machine's next `join` with the chain and keys).
631pub fn approve(ctx: &mut Ctx, collection: &str, machine: &str) -> Result<Entry, OpError> {
632    gate(ctx)?;
633    let at = ctx.pending.iter().position(|p| p.collection == collection && p.subject.id == machine).ok_or(OpError::Bad)?;
634    let subject = ctx.pending[at].subject.clone();
635    keys_or_refuse(ctx, collection, &subject)?;
636    ctx.pending.remove(at);
637    room_for_one_more(ctx, collection)?;
638    change(ctx, collection, Change::Add { member: subject })
639}
640
641/// Why a joiner did not take the chain it was given.
642#[derive(Debug, Clone, PartialEq, Eq)]
643pub enum JoinNo {
644    /// A chain that does not verify entry by entry.
645    Unsound(MemberError),
646    /// It does not list this machine.
647    NotInIt,
648    /// No member of it is one this machine itself trusts (its own LAN pin and account check).
649    NoAnchor,
650}
651
652/// The joiner's side: takes a chain only if every entry verifies, it lists this machine and at least one of its
653/// machine members is one this machine itself trusts. The peer that sent it is not taken on its word.
654pub fn take_join(collection: &str, me: &str, entries: Vec<Entry>, trusted: &dyn Fn(&str) -> bool) -> Result<Chain, JoinNo> {
655    let chain = Chain::from_entries(collection, entries).map_err(JoinNo::Unsound)?;
656    let state = chain.state(collection).map_err(JoinNo::Unsound)?;
657    if !state.members.contains_key(me) {
658        return Err(JoinNo::NotInIt);
659    }
660    if !state.anchored(trusted) {
661        return Err(JoinNo::NoAnchor);
662    }
663    Ok(chain)
664}
665
666/// Founds a collection here: its first entry, signed by this machine, and the collection in the log.
667pub fn found(conn: &Connection, chains: &mut BTreeMap<String, Chain>, keys: &dyn KeyDelivery, collection: &str, kind: &str, me: &Subject, private: &[u8; 32], policy: Policy, now_ms: i64) -> Result<(), OpError> {
668    if !keys.mint(collection, 0) {
669        return Err(OpError::NoKey);
670    }
671    log::ensure_collection(conn, collection, kind, now_ms)?;
672    let first = Entry::sign(private, collection, 1, None, Change::Found { member: me.clone(), policy }, &me.id).ok_or(OpError::Bad)?;
673    let chain = Chain::from_entries(collection, vec![first]).map_err(|_| OpError::Bad)?;
674    chain_store::save(conn, collection, &chain)?;
675    chains.insert(collection.to_string(), chain);
676    Ok(())
677}
678
679/// A joiner keeps the chain it took ([`take_join`]): the collection in the log, the chain in the store, and the log's
680/// key epoch where the chain says it is.
681pub fn adopt(conn: &Connection, chains: &mut BTreeMap<String, Chain>, collection: &str, kind: &str, chain: Chain, now_ms: i64) -> Result<(), OpError> {
682    log::ensure_collection(conn, collection, kind, now_ms)?;
683    store_chain(conn, collection, &chain)?;
684    chains.insert(collection.to_string(), chain);
685    Ok(())
686}
687
688/// Writes again, at the collection's current key epoch, what this machine wrote at an older epoch beyond the end its
689/// removal-of-another entry named (those writes are refused by the others): each record whose current state is one of
690/// them is opened with the key of its epoch and sealed with the current one. Returns how many were re-issued.
691pub fn reissue(conn: &Connection, signer: &mut Signer, ring: &KeyRing, collection: &str, now_ms: i64) -> Result<usize, SyncError> {
692    let cut = log::cut_off(conn, collection, signer.machine)?;
693    for rec in &cut {
694        if rec.header.tombstone {
695            log::append_local(conn, signer, collection, &rec.header.record, Vec::new(), true, now_ms)?;
696        } else {
697            let plain = seal::open(ring, &rec.header, &rec.body).map_err(|e| SyncError::Seal(format!("{e:?}")))?;
698            log::append_local_with(conn, signer, collection, &rec.header.record, false, now_ms, seal::sealer(ring, &plain))?;
699        }
700    }
701    Ok(cut.len())
702}