gent-daemon 0.2.5

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! A rename remains an intent on its originating node until the pinned carrier
//! returns a decision over the authenticated management connection.
use super::*;
use crate::messages::wire::CHAT_RENAME_VERSION;
use gent_protocol::{MAX_REGISTRATION_GENERATION, directory::RenameRequest};
use iroh::{EndpointAddr, EndpointId};
use serde::{Deserialize, Serialize};
use uuid::{NoContext, Timestamp, Uuid};

mod host;

const MAX_PENDING: usize = 128;
const MAX_HISTORY: usize = 1024;
const MAX_RECEIPTS: usize = 4096;
const UNCERTAIN: &str = "The hosting node has not confirmed the outcome. Refresh Chats.";
const UNSUPPORTED: &str = "The hosting node does not support remote chat rename.";

#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct Command {
    pub(crate) id: Uuid,
    agent: Uuid,
    generation: u64,
    name: String,
    publisher: String,
    host: String,
    host_key: gent_crypto::PublicKey,
    authority: gent_crypto::Checkpoint,
}

#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(rename_all = "snake_case")]
pub(crate) enum Decision {
    Applied,
    Changed,
    Denied,
    Expired,
    Unavailable,
    Unconfirmed,
    Waiting,
}
impl Decision {
    fn reason(self) -> Option<&'static str> {
        match self {
            Self::Applied | Self::Waiting => None,
            Self::Changed => Some("The registration changed. Refresh Chats before renaming."),
            Self::Expired => Some("The rename request expired before dispatch."),
            Self::Denied => Some("The requesting node lacks cluster administration rights."),
            Self::Unavailable => Some("The hosting node could not rename this registration."),
            Self::Unconfirmed => Some(UNCERTAIN),
        }
    }
}
pub(crate) struct Delivery {
    pub(crate) command: Command,
    pub(crate) address: EndpointAddr,
}

pub(super) fn schema(db: &Connection) -> Result<()> {
    let db = db.unchecked_transaction()?;
    let new = !db.table_exists(None, "chat_rename_requests")?;
    db.execute_batch("CREATE TABLE IF NOT EXISTS chat_rename_requests (
        id TEXT PRIMARY KEY, agent TEXT NOT NULL, host TEXT NOT NULL, name TEXT NOT NULL,
        generation INTEGER NOT NULL, command BLOB NOT NULL, state TEXT NOT NULL, reason TEXT,
        sent INTEGER NOT NULL DEFAULT 0, due INTEGER NOT NULL DEFAULT 0, expires INTEGER NOT NULL);
        CREATE INDEX IF NOT EXISTS chat_rename_agent ON chat_rename_requests(agent);
        CREATE INDEX IF NOT EXISTS chat_rename_pending ON chat_rename_requests(due) WHERE state='queued';
        CREATE TABLE IF NOT EXISTS chat_rename_receipts (
        origin TEXT NOT NULL,id TEXT NOT NULL,fingerprint BLOB NOT NULL,decision TEXT NOT NULL,
        revision INTEGER, epoch INTEGER, expires INTEGER NOT NULL, PRIMARY KEY(origin,id));
        CREATE INDEX IF NOT EXISTS chat_rename_receipt_expiry ON chat_rename_receipts(expires);
        CREATE TABLE IF NOT EXISTS chat_rename_peers (
        peer TEXT PRIMARY KEY REFERENCES network_links(peer) ON DELETE CASCADE, peer_key BLOB NOT NULL);")?;
    if new {
        db.execute(
            "INSERT OR IGNORE INTO presence_requests SELECT peer FROM network_links",
            [],
        )?;
    }
    db.commit()?;
    Ok(())
}

pub(super) fn clean(db: &Connection, at: i64, state: &VerifiedState) -> Result<()> {
    // A missing link can be permanent. A dispatched request might already
    // have run even when its host has been removed or downgraded.
    let mut hosts =
        db.prepare_cached("SELECT DISTINCT host FROM chat_rename_requests WHERE state='queued'")?;
    let hosts = hosts
        .query_map([], |r| r.get::<_, String>(0))?
        .collect::<rusqlite::Result<Vec<_>>>()?;
    for host in hosts {
        if !state
            .transport_host(&host)
            .is_ok_and(|native| native == host)
        {
            db.execute("UPDATE chat_rename_requests SET state=CASE sent WHEN 0 THEN 'rejected' ELSE 'unconfirmed' END,
                reason=CASE sent WHEN 0 THEN 'The original hosting node is no longer enrolled.' ELSE ?2 END
                WHERE host=?1 AND state='queued'", params![host,UNCERTAIN])?;
        }
    }
    db.execute("UPDATE chat_rename_requests AS r SET
        state=CASE sent WHEN 0 THEN 'rejected' ELSE 'unconfirmed' END,
        reason=CASE sent WHEN 0 THEN 'The unsent rename expired or its carrier was removed.' ELSE ?2 END
        WHERE state='queued' AND (expires<=?1 OR NOT EXISTS (SELECT 1 FROM network_links l WHERE l.peer=r.host))",
        params![at,UNCERTAIN])?;
    db.execute("DELETE FROM chat_rename_receipts WHERE expires<=?1", [at])?;
    db.execute(
        "DELETE FROM chat_rename_requests WHERE rowid IN (SELECT rowid FROM chat_rename_requests
        WHERE state<>'queued' ORDER BY rowid DESC LIMIT -1 OFFSET ?1)",
        [MAX_HISTORY],
    )?;
    Ok(())
}

fn read(row: &rusqlite::Row<'_>) -> rusqlite::Result<RenameRequest> {
    let id: String = row.get(0)?;
    Ok(RenameRequest {
        request_id: Uuid::parse_str(&id).map_err(|e| {
            rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(e))
        })?,
        name: row.get(1)?,
        expected_generation: row.get(2)?,
        state: row.get(3)?,
        reason: row.get(4)?,
    })
}

impl StoreSession<'_> {
    pub(super) fn latest_rename(&self, agent: &str) -> Result<Option<RenameRequest>> {
        Ok(self
            .db
            .prepare_cached(
                "SELECT id,name,generation,state,reason FROM chat_rename_requests
            WHERE agent=?1 ORDER BY rowid DESC LIMIT 1",
            )?
            .query_row([agent], read)
            .optional()?)
    }

    pub(super) fn rename_capability(&self, peer: &str, version: u8, key: &[u8]) -> Result<()> {
        if version >= CHAT_RENAME_VERSION {
            self.db.execute(
                "INSERT INTO chat_rename_peers VALUES(?1,?2) ON CONFLICT(peer) DO UPDATE
                 SET peer_key=excluded.peer_key WHERE peer_key<>excluded.peer_key",
                params![peer, key],
            )?;
        } else {
            self.db
                .execute("DELETE FROM chat_rename_peers WHERE peer=?1", [peer])?;
            self.db.execute("UPDATE chat_rename_requests SET state=CASE sent WHEN 0 THEN 'rejected' ELSE 'unconfirmed' END,
                reason=CASE sent WHEN 0 THEN ?2 ELSE ?3 END WHERE host=?1 AND state='queued'",params![peer,UNSUPPORTED,UNCERTAIN])?;
        }
        Ok(())
    }

    fn compatible_host(&self, host: &str) -> Result<bool> {
        let Some(member) = self.state.state().nodes.get(host) else {
            return Ok(false);
        };
        Ok(
            network::active_peer(&self.state, host, &member.signing_key, self.timestamp).is_ok()
                && self
                    .db
                    .prepare_cached(
                        "SELECT 1 FROM chat_rename_peers p JOIN network_links l USING(peer)
                WHERE peer=?1 AND p.peer_key=l.peer_key AND p.peer_key=?2",
                    )?
                    .exists(params![host, member.signing_key.as_slice()])?,
        )
    }

    pub(super) fn rename_hosts(&self) -> Result<BTreeSet<String>> {
        let mut hosts = BTreeSet::from([self.identity.node.id().to_owned()]);
        let mut links = self.db.prepare_cached(
            "SELECT l.peer,l.peer_key FROM chat_rename_peers p
            JOIN network_links l ON p.peer=l.peer AND p.peer_key=l.peer_key",
        )?;
        let links = links
            .query_map([], |r| {
                Ok((
                    r.get::<_, String>(0)?,
                    r.get::<_, gent_crypto::PublicKey>(1)?,
                ))
            })?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        if !links.is_empty()
            && crate::entitlements::paid(self.home, &self.config)
            && self
                .authorize_registration_admin(self.identity.node.id())
                .is_ok()
        {
            for (peer, key) in links {
                if network::active_peer(&self.state, &peer, &key, self.timestamp).is_ok() {
                    hosts.insert(peer);
                }
            }
        }
        Ok(hosts)
    }

    pub(super) fn request_rename(&self, id: &str, name: &str, generation: u64) -> Result<Value> {
        let agent = self.get_agent(id)?;
        let host = self.state.transport_host(&agent.node_id)?;
        // An identical retry can arrive after the logical publisher moved here.
        // It cannot transfer an outstanding intent to another carrier.
        let moved: Option<(String,bool)> = self.db.query_row(
            "SELECT id,sent FROM chat_rename_requests
            WHERE agent=?1 AND host<>?2 AND name=?3 AND generation=?4 AND state IN ('queued','unconfirmed')
            ORDER BY rowid DESC LIMIT 1",
            params![id,host,name,generation],|r|Ok((r.get(0)?,r.get(1)?)),
        ).optional()?;
        if let Some((request, sent)) = moved {
            let (state, reason) = if sent {
                ("unconfirmed", UNCERTAIN)
            } else {
                ("rejected", "The chat moved before the rename was sent.")
            };
            self.db.execute(
                "UPDATE chat_rename_requests SET state=?2,reason=?3 WHERE id=?1",
                params![request, state, reason],
            )?;
            let mut value = self.agent_details(id)?;
            value["state"] = json!(state);
            value["reason"] = json!(reason);
            value["request_id"] = json!(request);
            return Ok(value);
        }
        if host == self.identity.node.id() {
            self.rename_agent(id, name, generation)?;
            let mut value = self.agent_details(id)?;
            value["state"] = json!("applied");
            return Ok(value);
        }
        self.require_local_membership()?;
        require_pro(self.home, &self.config, "Cross-node delivery")?;
        self.authorize_registration_admin(self.identity.node.id())?;
        config::label(name)?;
        ensure!(
            (1..MAX_REGISTRATION_GENERATION).contains(&generation),
            "invalid expected registration generation"
        );
        clean(self.db, self.timestamp, &self.state)?;
        let prior = self
            .db
            .query_row(
                "SELECT id,name,generation,state,reason FROM chat_rename_requests
            WHERE agent=?1 AND host=?2 AND name=?3 AND generation=?4 ORDER BY rowid DESC LIMIT 1",
                params![id, host, name, generation],
                read,
            )
            .optional()?;
        let published = self
            .published_registration(id, &agent.node_id)?
            .context("registration is not published")?;
        let current = published.generation;
        let same_result = current == generation + 1 && published.name == name;
        let status = if let Some(mut saved) = prior.filter(|r| r.state != "rejected") {
            // After a receiver upgrade, an explicit retry can recover a lost
            // result under its original ID. Keep an expired outcome uncertain.
            if saved.state == "unconfirmed" && self.compatible_host(host)? {
                let id = saved.request_id.to_string();
                let resumed = self.db.execute(
                    "UPDATE chat_rename_requests SET state='queued',reason=NULL,due=0
                    WHERE id=?1 AND expires>?2 AND (SELECT COUNT(*) FROM chat_rename_requests WHERE state='queued')<?3
                    AND (SELECT COUNT(*) FROM chat_rename_requests WHERE state='queued' AND host=?4)<?5",
                    params![id,self.timestamp,MAX_PENDING,host,MAX_PENDING/4],
                )?;
                if resumed == 1 {
                    saved.state = "queued".into();
                    saved.reason = None;
                }
            }
            if saved.state == "applied" {
                ensure!(
                    !agent.revoked && (current <= generation || same_result),
                    "registration changed after this request; refresh Chats before renaming"
                );
            }
            saved
        } else {
            ensure!(self.compatible_host(host)?, UNSUPPORTED);
            ensure!(
                !agent.revoked && (current == generation || same_result),
                "registration changed; refresh Chats before renaming"
            );
            let (all, on_host): (usize, usize) = self.db.query_row(
                "SELECT COUNT(*),COUNT(*) FILTER (WHERE host=?1)
                 FROM chat_rename_requests WHERE state='queued'",
                [host],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )?;
            ensure!(
                all < MAX_PENDING && on_host < MAX_PENDING / 4,
                "too many outstanding chat renames"
            );
            let request_id =
                Uuid::new_v7(Timestamp::from_unix(NoContext, self.timestamp as u64, 0));
            let command = Command {
                id: request_id,
                agent: Uuid::parse_str(id)?,
                name: name.into(),
                generation,
                publisher: agent.node_id.clone(),
                host: host.into(),
                host_key: self.state.state().nodes[host].signing_key,
                authority: self.state.checkpoint().clone(),
            };
            self.db.execute("INSERT INTO chat_rename_requests(id,agent,host,name,generation,command,state,expires)
                VALUES(?1,?2,?3,?4,?5,?6,'queued',?7)",
                params![request_id.to_string(),id,host,name,generation,serde_json::to_vec(&command)?,self.timestamp+requests::LIFETIME],
            )?;
            self.db
                .execute("INSERT OR IGNORE INTO presence_requests VALUES(?1)", [host])?;
            RenameRequest {
                request_id,
                name: name.into(),
                expected_generation: generation,
                state: "queued".into(),
                reason: None,
            }
        };
        let mut value = self.agent_details(id)?;
        value["name"] = json!(published.name);
        value["registration_generation"] = json!(published.generation);
        value["state"] = json!(status.state);
        value["request_id"] = json!(status.request_id);
        if let Some(reason) = status.reason {
            value["reason"] = json!(reason);
        }
        Ok(value)
    }

    fn pinned(&self, command: &Command) -> bool {
        self.state
            .transport_host(&command.publisher)
            .is_ok_and(|host| host == command.host)
            && self
                .state
                .state()
                .nodes
                .get(&command.host)
                .is_some_and(|n| n.signing_key == command.host_key)
            && (command.publisher == command.host || self.state.checkpoint() == &command.authority)
    }

    fn management_peer(&self, endpoint: EndpointId) -> Result<(String, gent_crypto::PublicKey)> {
        require_pro(self.home, &self.config, "Cross-node delivery")?;
        ensure!(
            matches!(
                config::load(self.home)?.transport()?.direct,
                config::Direct::Auto
            ),
            "direct transport disabled"
        );
        self.require_local_membership()?;
        self.endpoint_binding(endpoint, true)?
            .context("unrecognized rename endpoint")
    }

    fn settle(&self, command: &Command, decision: Decision) -> Result<()> {
        if decision == Decision::Waiting {
            return Ok(());
        }
        let state = match decision {
            Decision::Applied => "applied",
            Decision::Unconfirmed => "unconfirmed",
            _ => "rejected",
        };
        self.db.execute("UPDATE chat_rename_requests SET state=?2,reason=?3 WHERE id=?1 AND state IN ('queued','unconfirmed')",
            params![command.id.to_string(),state,decision.reason()])?;
        Ok(())
    }
}

impl Store {
    pub(crate) fn rename_retry_delay(&self) -> Result<Option<std::time::Duration>> {
        let due: Option<i64> = self.db.query_row(
            "SELECT MIN(due) FROM chat_rename_requests WHERE state='queued'",
            [],
            |r| r.get(0),
        )?;
        Ok(due.map(|due| std::time::Duration::from_secs((due - now()).clamp(1, 15) as u64)))
    }

    pub(crate) fn next_rename(&self) -> Result<Option<Delivery>> {
        let tx = self.db.unchecked_transaction()?;
        let mut session = self.network_session(&tx, self.identity.state(&tx)?);
        session.timestamp = requests::diagnostic_clock(&tx, now())?;
        let row: Option<(Vec<u8>, bool)> = tx
            .query_row(
                "SELECT command,sent FROM chat_rename_requests
            WHERE state='queued' AND due<=?1 ORDER BY due,rowid LIMIT 1",
                [session.timestamp],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .optional()?;
        let Some((bytes, sent)) = row else {
            return Ok(None);
        };
        let command: Command = serde_json::from_slice(&bytes)?;
        let id = command.id.to_string();
        tx.execute(
            "UPDATE chat_rename_requests SET due=?2 WHERE id=?1",
            params![id, session.timestamp + 15],
        )?;
        if session
            .state
            .require_fresh(session.timestamp as u64)
            .is_err()
        {
            tx.commit()?;
            return Ok(None);
        }
        let denied = if !session.pinned(&command) {
            Some(Decision::Unavailable)
        } else if session
            .authorize_registration_admin(self.local_node_id())
            .is_err()
        {
            Some(Decision::Denied)
        } else if requests::admit(&id, session.timestamp).is_err() {
            Some(Decision::Expired)
        } else {
            None
        };
        let mut delivery = None;
        if let Some(decision) = denied {
            session.settle(
                &command,
                if sent {
                    Decision::Unconfirmed
                } else {
                    decision
                },
            )?;
        } else {
            tx.execute("INSERT OR IGNORE INTO presence_requests SELECT peer FROM network_links WHERE peer=?1",[&command.host])?;
            if let Some(direct::NativeTarget::Advertised(address)) =
                session.native_target(&command.host)?
            {
                delivery = Some(Delivery { command, address });
            }
        }
        tx.commit()?;
        Ok(delivery)
    }

    // Runs after QUIC authentication, immediately before writing any command bytes.
    pub(crate) fn dispatch_rename(&self, endpoint: EndpointId, command: &Command) -> Result<()> {
        let tx = self.db.unchecked_transaction()?;
        let session = self.network_session(&tx, self.identity.state(&tx)?);
        let (peer, key) = session.management_peer(endpoint)?;
        ensure!(
            session.pinned(command)
                && peer == command.host
                && key == command.host_key
                && session.compatible_host(&peer)?,
            "rename carrier changed"
        );
        session.authorize_registration_admin(self.local_node_id())?;
        ensure!(tx.execute("UPDATE chat_rename_requests SET sent=1 WHERE id=?1 AND state='queued' AND expires>?2",
            params![command.id.to_string(),requests::diagnostic_clock(&tx,now())?])?==1,"rename no longer pending");
        tx.commit()?;
        Ok(())
    }

    pub(crate) fn finish_rename(
        &self,
        endpoint: EndpointId,
        command: &Command,
        decision: Decision,
    ) -> Result<()> {
        let tx = self.db.unchecked_transaction()?;
        let session = self.network_session(&tx, self.identity.state(&tx)?);
        let (peer, key) = session.management_peer(endpoint)?;
        ensure!(
            peer == command.host && key == command.host_key,
            "rename receipt carrier mismatch"
        );
        session.settle(
            command,
            if session.pinned(command) {
                decision
            } else {
                Decision::Unconfirmed
            },
        )?;
        tx.commit()?;
        Ok(())
    }
}