1use 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
27pub const MAX_NAMES: usize = 64;
29pub const MAX_BATCH_RECORDS: usize = 200;
31pub const MAX_BATCH_BYTES: usize = 256 * 1024;
34#[cfg(not(test))]
36pub const MAX_ENTRIES: usize = 256;
37#[cfg(test)]
39pub const MAX_ENTRIES: usize = 16;
40pub const MAX_PENDING: usize = 16;
42pub const PENDING_TTL_MS: i64 = 24 * 60 * 60 * 1000;
44pub const AUTO_JOIN_KINDS: [&str; 1] = ["kanban"];
46
47pub const MAX_WIRE_BYTES: usize = MAX_BATCH_BYTES / 3 * 4 + MAX_BATCH_RECORDS * 1024 + 64 * 1024;
50
51const HEADER_WEIGHT: usize = 512;
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum OpError {
56 NotActive,
58 NotMember,
60 TooBig,
62 Bad,
64 NoKey,
66 Db(String),
67}
68
69impl OpError {
70 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
89pub struct Me<'a> {
91 pub id: &'a str,
92 pub private: &'a [u8; 32],
93}
94
95pub trait Proof {
99 fn auto_proven(&self, machine: &str) -> bool;
100}
101
102pub trait KeyDelivery {
104 fn keys_for(&self, collection: &str, to: &Subject) -> Vec<(u32, String)>;
105 fn mint(&self, _collection: &str, _epoch: u32) -> bool {
107 true
108 }
109 fn take(&self, _collection: &str, _keys: &[(u32, String)]) -> usize {
111 0
112 }
113 fn discard(&self, _collection: &str, _epoch: u32) {}
115 fn held(&self, _collection: &str) -> Vec<u32> {
117 Vec::new()
118 }
119 fn ring(&self, _collection: &str) -> KeyRing {
121 KeyRing::new()
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct PendingJoin {
128 pub collection: String,
129 pub subject: Subject,
130 pub asked_at: i64,
131}
132
133pub 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 pub chain_cap: usize,
145 pub active: bool,
147}
148
149enum Standing {
150 Current(State),
151 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
178fn 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
187pub 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#[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
215pub 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 pub more: bool,
243 pub epoch: u32,
244 pub n: u64,
245}
246
247pub 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
261pub 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
276pub 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 pub results: Vec<Result<Outcome, Refused>>,
294 pub vector: Vector,
297 pub epoch: u32,
298}
299
300pub 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 pub have_n: u64,
329 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 pub taken: Vec<Result<Taken, MemberError>>,
339}
340
341pub fn sync_epoch(conn: &Connection, collection: &str, chain: &Chain) -> Result<(), OpError> {
345 atomically(conn, |c| epoch_to_chain(c, collection, chain))
346}
347
348fn 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 let _ = conn.execute_batch("ROLLBACK TO sync_atomic; RELEASE sync_atomic");
359 Err(e)
360 }
361 }
362}
363
364fn 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
381pub(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
392pub(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 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
412pub(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
419fn 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
424pub 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 *chain = before;
455 return Err(e);
456 }
457 discard_lost_keys(ctx.keys, &req.collection, &lost);
458 }
459 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 pub have: Vec<u32>,
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476pub struct KeysAns {
477 pub keys: Vec<(u32, String)>,
479}
480
481pub 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
493pub 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 Added { entries: Vec<Entry>, keys: Vec<(u32, String)> },
509 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
517pub fn change(ctx: &mut Ctx, collection: &str, change: Change) -> Result<Entry, OpError> {
520 gate(ctx)?;
521 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
563fn keys_or_refuse(ctx: &Ctx, collection: &str, subject: &Subject) -> Result<Vec<(u32, String)>, OpError> {
565 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
574pub 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
605fn 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
629pub 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#[derive(Debug, Clone, PartialEq, Eq)]
643pub enum JoinNo {
644 Unsound(MemberError),
646 NotInIt,
648 NoAnchor,
650}
651
652pub 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
666pub 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
679pub 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
688pub 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}