Skip to main content

agentmux_srv_core/backend/user_sync/
lock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The computer-wide sync lock (SPEC_USER_DATA_SYNC_LAYER ยง3.1). The identity store, and with it the Kanban and the
5//! Vaults, is shared by every AgentMux on a computer, so only one install may act as the computer's member: sign
6//! records as it, run the sync loop and answer `sync.*` ops. That install holds this lock, a single row in the shared
7//! store taken by compare-and-set with a lease. An install that does not hold it never signs as the member and never
8//! runs the loop; a crashed holder is replaced when its lease runs out. Each taking raises a generation, so a holder
9//! that was replaced finds its renewal refused and stops (a fence, like a task claim's attempt).
10
11use rusqlite::{params, Connection, OptionalExtension};
12
13/// The table, created by `log::init` with the log's.
14pub(crate) const SCHEMA: &str = "
15    CREATE TABLE IF NOT EXISTS db_sync_lock (
16        id         INTEGER PRIMARY KEY CHECK (id = 1),
17        holder     TEXT NOT NULL,
18        generation INTEGER NOT NULL,
19        expires_at INTEGER NOT NULL
20    );";
21
22/// How long a lease lasts before a crashed holder can be replaced.
23pub const LEASE_MS: i64 = 60_000;
24
25/// The answer to a request for the lock.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum Lock {
28    /// This install holds it, at this generation. Renew before the lease ends.
29    Held { generation: i64 },
30    /// Another install holds it until `until`.
31    Busy { by: String, until: i64 },
32}
33
34pub fn init(conn: &Connection) -> rusqlite::Result<()> {
35    conn.execute_batch(SCHEMA)
36}
37
38fn row(conn: &Connection) -> rusqlite::Result<Option<(String, i64, i64)>> {
39    conn.query_row("SELECT holder, generation, expires_at FROM db_sync_lock WHERE id = 1", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
40        .optional()
41}
42
43/// Takes the lock for `install` if it is free, expired or already its own. One statement decides, so two installs
44/// asking at once cannot both get it.
45pub fn acquire(conn: &Connection, install: &str, now_ms: i64, lease_ms: i64) -> rusqlite::Result<Lock> {
46    conn.execute(
47        "INSERT INTO db_sync_lock (id, holder, generation, expires_at) VALUES (1, ?1, 1, ?2)
48         ON CONFLICT (id) DO UPDATE SET
49             holder = excluded.holder,
50             generation = CASE WHEN db_sync_lock.holder = excluded.holder THEN db_sync_lock.generation ELSE db_sync_lock.generation + 1 END,
51             expires_at = excluded.expires_at
52         WHERE db_sync_lock.holder = excluded.holder OR db_sync_lock.expires_at <= ?3",
53        params![install, now_ms + lease_ms, now_ms],
54    )?;
55    Ok(match row(conn)? {
56        Some((holder, generation, _)) if holder == install => Lock::Held { generation },
57        Some((by, _, until)) => Lock::Busy { by, until },
58        None => Lock::Busy { by: String::new(), until: 0 },
59    })
60}
61
62/// Extends the lease if `install` still holds the lock at `generation`; false means it was replaced and must stop.
63pub fn renew(conn: &Connection, install: &str, generation: i64, now_ms: i64, lease_ms: i64) -> rusqlite::Result<bool> {
64    let n = conn.execute(
65        "UPDATE db_sync_lock SET expires_at = ?3 WHERE id = 1 AND holder = ?1 AND generation = ?2 AND expires_at > ?4",
66        params![install, generation, now_ms + lease_ms, now_ms],
67    )?;
68    Ok(n == 1)
69}
70
71/// Gives the lock up (an install shutting down), if it holds it.
72pub fn release(conn: &Connection, install: &str, generation: i64) -> rusqlite::Result<()> {
73    conn.execute("UPDATE db_sync_lock SET expires_at = 0 WHERE id = 1 AND holder = ?1 AND generation = ?2", params![install, generation])?;
74    Ok(())
75}
76
77/// Whether `install` holds the lock at `generation` right now: the check made before signing as the member.
78pub fn holds(conn: &Connection, install: &str, generation: i64, now_ms: i64) -> rusqlite::Result<bool> {
79    Ok(row(conn)?.is_some_and(|(h, g, until)| h == install && g == generation && until > now_ms))
80}