gent-daemon 0.2.1

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
use super::*;
use crate::messages::{
    Event,
    dashboard::{display_board, encode_board, update_board},
    wire::DASHBOARD_VERSION,
};
use gent_protocol::dashboard::{Board, Kind};

mod grant_route;
mod grants;
pub use grants::grant_verifier;
pub(in crate::store) mod publication;
mod static_html;

pub(super) fn schema(db: &Connection) -> Result<()> {
    let tx = db.unchecked_transaction()?;
    let first_dashboard_schema = !tx.table_exists(None, "dashboards")?;
    tx.execute_batch("CREATE TABLE IF NOT EXISTS dashboards(agent TEXT PRIMARY KEY REFERENCES agents(id),revision INTEGER NOT NULL CHECK(revision>0),body TEXT,mutation TEXT);
    CREATE TABLE IF NOT EXISTS dashboard_sent(peer TEXT NOT NULL,agent TEXT NOT NULL, revision INTEGER NOT NULL,event TEXT NOT NULL,peer_key BLOB,PRIMARY KEY(peer,agent));
    CREATE TABLE IF NOT EXISTS hosted_dashboard_gates(agent TEXT PRIMARY KEY REFERENCES agents(id) ON DELETE CASCADE,node TEXT NOT NULL,revision INTEGER NOT NULL);
    CREATE TRIGGER IF NOT EXISTS dashboard_forget_peer AFTER DELETE ON network_links BEGIN DELETE FROM dashboard_sent WHERE peer=OLD.peer;
        DELETE FROM metadata WHERE key='dashboard_discovery:' || OLD.peer; END;
    CREATE TRIGGER IF NOT EXISTS dashboard_forget_agent AFTER DELETE ON agents BEGIN DELETE FROM dashboard_sent WHERE agent=OLD.id; END;")?;
    static_html::schema(&tx)?;
    publication::schema(&tx)?;
    grants::schema(&tx)?;
    if !tx
        .prepare("SELECT 1 FROM pragma_table_info('dashboard_sent') WHERE name='peer_key'")?
        .exists([])?
    {
        // Existing cursors have no proof of the recipient's current key.
        tx.execute("ALTER TABLE dashboard_sent ADD COLUMN peer_key BLOB", [])?;
        tx.execute(
            "UPDATE network_events SET retire_after=NULL,announcement=1
             WHERE id IN (SELECT event FROM dashboard_sent)",
            [],
        )?;
    }
    if first_dashboard_schema {
        // Established pre-V9 links can be completely idle when this receiver
        // upgrades. Discover their capabilities once, even with no local board.
        tx.execute_batch("INSERT OR IGNORE INTO presence_requests SELECT peer FROM network_links;
            INSERT OR REPLACE INTO metadata SELECT 'dashboard_discovery:' || peer,hex(peer_key) FROM network_links;")?;
    }
    tx.commit()?;
    Ok(())
}

impl StoreSession<'_> {
    fn board(&self, id: &str) -> Result<(u64, Option<Board>, Option<String>)> {
        require_pro(self.home, &self.config, "Dashboard access")?;
        let row = self
            .db
            .query_row(
                "SELECT revision,body,mutation FROM dashboards WHERE agent=?1",
                [id],
                |r| Ok((r.get(0)?, r.get::<_, Option<String>>(1)?, r.get(2)?)),
            )
            .optional()?;
        match row {
            None => Ok((0, None, None)),
            Some((revision, body, op)) => Ok((
                revision,
                body.map(|s| serde_json::from_str(&s)).transpose()?,
                op,
            )),
        }
    }
    pub(super) fn dashboard_get(&self, who: &Agent) -> Result<Value> {
        let (revision, board, _) = self.board(&who.id)?;
        let board = board
            .map(|board| {
                let actions = publication::pin(&board).map(|_| {
                    board
                        .widgets
                        .iter()
                        .filter(|w| w.kind == Kind::Button)
                        .map(|w| json!({"id":w.id, "label":w.label, "message":w.value}))
                        .collect::<Vec<_>>()
                });
                let mut view = self.project_publication(&who.id, revision, board)?;
                if let Some(actions) = actions {
                    view["actions"] = actions.into();
                }
                Ok::<_, anyhow::Error>(view)
            })
            .transpose()?;
        Ok(json!({"revision":revision,"board":board}))
    }
    pub(super) fn dashboard_mutate(&self, who: &Agent, mut op: AgentOp) -> Result<Value> {
        let (revision, previous, last) = self.board(&who.id)?;
        // A retry through an older daemon sees the same define fingerprint.
        if let AgentOp::DashboardDefine { board, .. } = &mut op {
            encode_board(board)?;
        }
        let mut fingerprint = hash(&serde_json::to_string(&op)?);
        if last.as_ref() == Some(&fingerprint) {
            if matches!(op, AgentOp::DashboardPublish { .. }) {
                return self.publication_receipt(&who.id, revision);
            }
            return Ok(json!({"revision":revision}));
        }
        if matches!(
            op,
            AgentOp::DashboardUpdate { .. } | AgentOp::DashboardAttachHtml { .. }
        ) && self.publication_exists(&who.id, revision)?
        {
            anyhow::bail!("use gent_dashboard_publish to replace this HTML dashboard");
        }
        let mut publication = None;
        let mut attachment = None;
        let (expected, next) = match op {
            AgentOp::DashboardPublish {
                expected_revision,
                title,
                file_id,
                html,
                actions,
            } => {
                let html = self.publication_input(who, file_id, html)?;
                let digest = hash(&html);
                let board = publication::fallback(title, &digest, actions, previous.as_ref())?;
                if previous.as_ref() == Some(&board)
                    && self.publication_exists(&who.id, revision)?
                    && (expected_revision == revision
                        || revision.checked_sub(1) == Some(expected_revision))
                {
                    return self.publication_receipt(&who.id, revision);
                }
                publication = Some((digest, html));
                (expected_revision, Some(board))
            }
            AgentOp::DashboardDefine {
                expected_revision,
                board,
            } => (expected_revision, Some(board)),
            AgentOp::DashboardAttachHtml {
                expected_revision,
                file_id,
            } => {
                attachment = Some(file_id.to_string());
                (
                    expected_revision,
                    Some(previous.context("define a dashboard before attaching HTML")?),
                )
            }
            AgentOp::DashboardDelete { expected_revision } => (expected_revision, None),
            AgentOp::DashboardUpdate {
                expected_revision,
                mut values,
            } => {
                let board = update_board(
                    previous.context("define a dashboard before updating it")?,
                    &mut values,
                )?;
                fingerprint = hash(&serde_json::to_string(&AgentOp::DashboardUpdate {
                    expected_revision,
                    values,
                })?);
                if last.as_ref() == Some(&fingerprint) {
                    return Ok(json!({"revision":revision}));
                }
                (expected_revision, Some(board))
            }
            _ => unreachable!(),
        };
        ensure!(
            expected == revision,
            "dashboard revision conflict; read gent_dashboard_get"
        );
        let grant = if publication.is_some() {
            self.current_board_grant(&who.id)?
        } else {
            None
        };
        let revision = self.commit_board(who, revision, next.as_ref(), &fingerprint)?;
        if let Some((digest, html)) = &publication {
            self.save_publication(&who.id, revision, digest, html)?;
            if let Some(verifier) = grant {
                self.save_board_grant(&who.id, &verifier)?;
            }
        }
        if let Some(id) = attachment {
            self.attach_board_html(who, revision, &id)?;
        }
        self.sync_board()?;
        if publication.is_some() {
            return self.publication_receipt(&who.id, revision);
        }
        Ok(json!({"revision":revision}))
    }

    fn commit_board(
        &self,
        who: &Agent,
        revision: u64,
        board: Option<&Board>,
        fingerprint: &str,
    ) -> Result<u64> {
        let revision = revision.checked_add(1).context("revision exhausted")?;
        ensure!(
            revision <= MAX_REGISTRATION_GENERATION,
            "dashboard revision exhausted"
        );
        self.web_state_changed(&who.node_id)?;
        self.db.execute("INSERT INTO hosted_dashboard_gates SELECT ?1,node,revision FROM hosted_checkpoints
            WHERE node=?2 AND revision>durable ON CONFLICT(agent) DO UPDATE SET revision=excluded.revision",
            params![who.id,who.node_id])?;
        self.save_board(&who.id, revision, board, Some(fingerprint))?;
        Ok(revision)
    }

    fn sync_board(&self) -> Result<()> {
        let peers = self
            .db
            .prepare("SELECT peer,peer_key FROM network_links")?
            .query_map([], |r| {
                Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
            })?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        for (peer, key) in peers {
            if network::active_peer(&self.state, &peer, &key, self.timestamp).is_ok() {
                match self.wire_version(&peer)? {
                    v if v >= DASHBOARD_VERSION => self.dashboard_sync(&peer, &key)?,
                    1 => self.defer_dashboard_sync(&peer)?,
                    _ => {}
                }
            }
        }
        Ok(())
    }
    fn save_board(
        &self,
        agent: &str,
        revision: u64,
        board: Option<&Board>,
        mutation: Option<&str>,
    ) -> Result<()> {
        self.db.execute("INSERT INTO dashboards VALUES(?1,?2,?3,?4) ON CONFLICT(agent) DO UPDATE SET revision=excluded.revision,body=excluded.body,mutation=excluded.mutation",params![agent,revision,board.map(serde_json::to_string).transpose()?,mutation])?;
        Ok(())
    }
    pub(super) fn dashboard_receive(
        &self,
        agent: &str,
        revision: u64,
        board: Option<Board>,
        html: Option<&str>,
    ) -> Result<()> {
        ensure!(
            (1..=MAX_REGISTRATION_GENERATION).contains(&revision),
            "invalid dashboard revision"
        );
        if let Some(b) = &board {
            b.validate().map_err(anyhow::Error::msg)?;
        }
        let digest = html
            .map(|html| publication::verify(board.as_ref(), html))
            .transpose()?;
        // A previous carrier can retain an edit which was never committed.
        // The caller verified the registration and the current remote carrier.
        if self
            .db
            .execute("DELETE FROM hosted_dashboard_gates WHERE agent=?1", [agent])?
            != 0
        {
            self.db
                .execute("DELETE FROM dashboards WHERE agent=?1", [agent])?;
            self.db
                .execute("DELETE FROM dashboard_sent WHERE agent=?1", [agent])?;
        }
        let (current, old, _) = self.board(agent)?;
        if revision > current {
            self.save_board(agent, revision, board.as_ref(), None)?;
        } else if revision == current {
            ensure!(old == board, "conflicting dashboard revision");
        }
        if revision >= current
            && let (Some(digest), Some(html)) = (digest, html)
        {
            self.save_publication(agent, revision, digest, html)?;
        }
        Ok(())
    }
    pub(super) fn dashboard_sync(&self, peer: &str, key: &[u8]) -> Result<()> {
        if !crate::entitlements::paid(self.home, &self.config) {
            return Ok(());
        }
        // Include hosted conversations whose current signed carrier is this node.
        let local: Vec<_> = self
            .state
            .state()
            .nodes
            .keys()
            .filter(|node| self.local_node(node))
            .collect();
        let send_publications =
            self.wire_version(peer)? >= crate::messages::wire::PUBLICATION_VERSION;
        let mut query=self.db.prepare("SELECT d.agent,d.revision,d.body,
            EXISTS(SELECT 1 FROM network_events e WHERE e.id=s.event) AS pending, p.html FROM dashboards d
            LEFT JOIN dashboard_publications p ON ?4 AND p.agent=d.agent AND p.revision=d.revision
            JOIN agents a ON a.id=d.agent LEFT JOIN dashboard_sent s ON s.peer=?1 AND s.agent=d.agent
            WHERE a.node_id IN (SELECT value FROM json_each(?2)) AND a.revoked=0
            AND (s.peer_key IS NOT ?3 OR d.revision>s.revision OR p.html IS NOT NULL AND s.publication=0)
            ORDER BY pending,d.agent LIMIT 9")?;
        let records = query
            .query_map(
                params![peer, serde_json::to_string(&local)?, key, send_publications],
                |r| {
                    Ok((
                        r.get::<_, String>(0)?,
                        r.get::<_, u64>(1)?,
                        r.get::<_, Option<String>>(2)?,
                        r.get::<_, bool>(3)?,
                        r.get::<_, Option<String>>(4)?,
                    ))
                },
            )?
            .collect::<rusqlite::Result<Vec<_>>>()?;
        for (index, (id, revision, body, pending, html)) in records.into_iter().enumerate() {
            if index == 8 || pending {
                self.defer_dashboard_sync(peer)?;
                break;
            }
            let published = html.is_some();
            let event = Event::Dashboard {
                html,
                agent: self.registration(&id)?,
                revision,
                board: body.map(|s| serde_json::from_str(&s)).transpose()?,
            };
            let event_id = uuid::Uuid::new_v4();
            // queue() also installs hosted durability gates. Its optional
            // work must not roll back the chat mutation or incoming proof.
            self.db.execute_batch("SAVEPOINT dashboard_event")?;
            if let Err(error) = self.queue(peer, event_id, event, None) {
                self.db
                    .execute_batch("ROLLBACK TO dashboard_event; RELEASE dashboard_event")?;
                if !error.is::<network::retention::QueueFull>() {
                    return Err(error);
                }
                self.defer_dashboard_sync(peer)?;
                break;
            }
            self.db.execute("INSERT INTO dashboard_sent(peer,agent,revision,event,peer_key,publication) VALUES(?1,?2,?3,?4,?5,?6) ON CONFLICT(peer,agent) DO UPDATE SET revision=excluded.revision,event=excluded.event,peer_key=excluded.peer_key,publication=excluded.publication",params![peer,id,revision,event_id.to_string(),key,published])?;
            self.db.execute_batch("RELEASE dashboard_event")?;
        }
        Ok(())
    }

    fn defer_dashboard_sync(&self, peer: &str) -> Result<()> {
        // One durable request per peer. Presence honors the ordinary probe
        // interval and confirms the codec before retrying the latest boards.
        self.db
            .execute("INSERT OR IGNORE INTO presence_requests VALUES(?1)", [peer])?;
        Ok(())
    }
    pub(super) fn dashboards(&self, after: Option<&str>) -> Result<Value> {
        require_pro(self.home, &self.config, "Dashboard access")?;
        let members = self.state.state().nodes.keys().collect::<Vec<_>>();
        let mut query = self.db.prepare(
            "SELECT a.id,a.name,d.revision,d.body,h.file,h.sha256,a.node_id FROM dashboards d
            LEFT JOIN dashboard_html h ON h.agent=d.agent AND h.revision=d.revision
            JOIN agents a ON a.id=d.agent WHERE d.body IS NOT NULL AND a.revoked=0
            AND a.node_id IN (SELECT value FROM json_each(?2)) AND a.id>?1
            AND NOT EXISTS(SELECT 1 FROM hosted_dashboard_gates g WHERE g.agent=a.id)
            ORDER BY a.id LIMIT 33",
        )?;
        let mut records = query.query(params![
            after.unwrap_or(""),
            serde_json::to_string(&members)?
        ])?;
        let mut rows = Vec::new();
        let mut next = None;
        let mut html_bytes = 0;
        let mut remote = BTreeMap::<String, Vec<String>>::new();
        while let Some(row) = records.next()? {
            // Leave room for 32 native boards and worst-case JSON escaping in the RPC frame.
            if rows.len() == 32 || html_bytes >= 512 * 1024 {
                next = rows
                    .last()
                    .and_then(|r: &Value| r["agent"].as_str())
                    .map(str::to_owned);
                break;
            }
            let board = serde_json::from_str::<Board>(&row.get::<_, String>(3)?)?;
            let agent: String = row.get(0)?;
            let mut board = self.project_publication(&agent, row.get(2)?, board)?;
            let published = board["html"].as_str().map(str::len);
            html_bytes += published.unwrap_or(0);
            if let Some(file) = row.get::<_, Option<String>>(4)? {
                let who = self.get_agent(&agent)?;
                if self.local_node(&who.node_id)
                    && let Ok((digest, html)) = self.board_html_file(&who, &file)
                    && digest == row.get::<_, String>(5)?
                {
                    html_bytes += html.len();
                    board["static_html"] = Value::String(html);
                }
            }
            let node: String = row.get(6)?;
            if published.is_none()
                && let Ok(host) = self.state.transport_host(&node)
                && host != self.identity.node.id()
            {
                remote.entry(host.into()).or_default().push(agent.clone());
            }
            rows.push(json!({"agent":agent,"chat":row.get::<_,String>(1)?,"revision":row.get::<_,u64>(2)?,"board":board}));
        }
        let mut page = json!({"rows":rows,"next":next});
        if !remote.is_empty() {
            page["remote_html_candidates"] = json!(remote);
        }
        Ok(page)
    }
    pub(super) fn dashboard_action(
        &mut self,
        id: &str,
        expected: u64,
        widget: Option<&str>,
        request_id: &str,
    ) -> Result<Value> {
        let (revision, board, _) = self.board(id)?;
        ensure!(
            revision == expected
                && !self.db.query_row(
                    "SELECT EXISTS(SELECT 1 FROM hosted_dashboard_gates WHERE agent=?1)",
                    [id],
                    |r| r.get::<_, bool>(0)
                )?,
            "dashboard changed; refresh before clicking"
        );
        let board = board.context("dashboard no longer available")?;
        let text = if let Some(key) = widget {
            let button = board
                .widgets
                .iter()
                .find(|w| w.id == key && w.kind == Kind::Button)
                .context("button no longer available")?;
            format!(
                "Dashboard action {} ({key}) selected in Gent Desktop:\n{}",
                button.label,
                button.value.as_str().context("invalid button")?
            )
        } else {
            format!(
                "Refresh requested in Gent Desktop. Board ID {id}, viewed revision {revision}, request ID {request_id}. \
                 Please update your dashboard with the latest available data. If it is already current, reply with the time of the latest observation."
            )
        };
        let node = self.identity.node.id().to_string();
        self.db.execute("INSERT OR IGNORE INTO metadata VALUES('desktop_callback_credential',lower(hex(randomblob(32))))",[])?;
        let credential: String = self.db.query_row(
            "SELECT value FROM metadata WHERE key='desktop_callback_credential'",
            [],
            |r| r.get(0),
        )?;
        let sender = self.agent(
            &node,
            &credential,
            AgentOp::Register {
                name: "Gent Desktop".into(),
                provider: "desktop".into(),
            },
            files::ExportStep::Reserve,
        )?;
        let sender = self.get_agent(
            sender["agent"]["id"]
                .as_str()
                .context("desktop identity unavailable")?,
        )?;
        self.send(
            &sender,
            id,
            request_id,
            text,
            vec![],
            SendContext::default(),
        )
    }
}