1use super::*;
3use rusqlite::{params_from_iter, types::Value as SqlValue};
4use serde::{Deserialize, Serialize};
5
6const SCOPE: &str = "WITH wa AS (SELECT id FROM agents WHERE node_id=?1),
7 wm AS (SELECT id FROM messages WHERE sender IN wa OR recipient IN wa),
8 wp AS (SELECT id FROM wa UNION SELECT sender FROM messages WHERE id IN wm
9 UNION SELECT recipient FROM messages WHERE id IN wm
10 UNION SELECT target FROM relay_attachments WHERE intermediary IN wa),
11 wf AS (SELECT object_id FROM agent_files WHERE agent IN wa OR message IN wm
12 UNION SELECT json_extract(j.value,'$.id') FROM messages m,json_each(m.payload,'$.attachments') j WHERE m.id IN wm) ";
13
14const TABLES: &[(&str, &str)] = &[
15 ("agents", "id IN wp"),
16 ("network_origins", "agent IN wp"),
17 ("exchanges", "a IN wa OR b IN wa"),
18 ("messages", "id IN wm"),
19 ("relay_attachments", "intermediary IN wa"),
20 ("relay_turns", "intermediary IN wa OR target IN wa"),
21 ("request_clock", "1=1"),
22 ("work_entries", "agent IN wa"),
23 (
24 "work_events",
25 "message_id IN (SELECT message_id FROM work_entries WHERE agent IN wa)",
26 ),
27 ("wake_dispatches", "agent IN wa"),
28 ("dashboards", "agent IN wa"),
29 ("dashboard_times", "agent IN wa"),
30 ("dashboard_publications", "agent IN wa"),
31 ("dashboard_grants", "agent IN wa"),
32 ("file_objects", "id IN wf"),
33 ("agent_files", "object_id IN wf"),
34 ("file_imports", "agent IN wa"),
35 ("message_file_proofs", "message IN wm"),
36 ("network_rejections", "message IN wm"),
37 ("agent_activity", "agent IN wp"),
38 ("chat_message_dates", "agent IN wa"),
39 ("recovered_sources", "target IN wa"),
40 (
41 "recovered_messages",
42 "source IN (SELECT id FROM recovered_sources WHERE target IN wa)",
43 ),
44 (
45 "recovered_files",
46 "source IN (SELECT id FROM recovered_sources WHERE target IN wa)",
47 ),
48 (
49 "recovered_chunks",
50 "source IN (SELECT id FROM recovered_sources WHERE target IN wa)",
51 ),
52];
53
54#[derive(Clone, Serialize, Deserialize)]
56#[serde(
57 tag = "kind",
58 content = "value",
59 rename_all = "snake_case",
60 deny_unknown_fields
61)]
62enum Cell {
63 Null,
64 Integer(i64),
65 Real(f64),
66 Text(String),
67 Blob(String),
68}
69
70impl Cell {
71 fn read(value: SqlValue) -> Self {
72 match value {
73 SqlValue::Null => Self::Null,
74 SqlValue::Integer(v) => Self::Integer(v),
75 SqlValue::Real(v) => Self::Real(v),
76 SqlValue::Text(v) => Self::Text(v),
77 SqlValue::Blob(v) => Self::Blob(STANDARD.encode(v)),
78 }
79 }
80 fn sql(&self) -> Result<SqlValue> {
81 Ok(match self {
82 Self::Null => SqlValue::Null,
83 Self::Integer(v) => SqlValue::Integer(*v),
84 Self::Real(v) => {
85 ensure!(v.is_finite(), "invalid checkpoint number");
86 SqlValue::Real(*v)
87 }
88 Self::Text(v) => SqlValue::Text(v.clone()),
89 Self::Blob(v) => SqlValue::Blob(STANDARD.decode(v)?),
90 })
91 }
92}
93
94#[derive(Serialize, Deserialize)]
95#[serde(deny_unknown_fields)]
96struct Table {
97 columns: Vec<String>,
98 rows: Vec<Vec<Cell>>,
99}
100
101pub(super) fn read(path: &Path) -> Result<Snapshot> {
102 use rustix::fs::{Mode, OFlags, open};
103 use std::{io::Read, os::unix::fs::MetadataExt};
104 let file = std::fs::File::from(open(
105 path,
106 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
107 Mode::empty(),
108 )?);
109 let metadata = file.metadata()?;
110 let limit = gent_protocol::web_failover::CHUNK_BYTES * gent_protocol::web_failover::MAX_CHUNKS;
111 ensure!(
112 metadata.is_file()
113 && metadata.nlink() == 1
114 && metadata.uid() == rustix::process::geteuid().as_raw()
115 && metadata.mode() & 0o077 == 0
116 && metadata.len() <= limit as u64,
117 "web checkpoint must be a bounded private owned file"
118 );
119 let mut bytes = Vec::new();
120 file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
121 ensure!(bytes.len() <= limit, "web checkpoint too large");
122 Ok(serde_json::from_slice(&bytes)?)
123}
124
125#[derive(Serialize, Deserialize)]
126#[serde(deny_unknown_fields)]
127pub struct Snapshot {
128 version: u8,
129 pub cluster: String,
130 pub node: String,
131 pub revision: u64,
132 tables: BTreeMap<String, Table>,
133}
134
135fn columns(db: &Connection, table: &str) -> Result<Vec<String>> {
136 Ok(db
137 .prepare(&format!("PRAGMA table_info({table})"))?
138 .query_map([], |r| r.get(1))?
139 .collect::<rusqlite::Result<_>>()?)
140}
141
142pub fn export(home: &Path, node: &str) -> Result<Snapshot> {
143 export_scoped(home, node, None)
144}
145
146pub fn export_for_epoch(home: &Path, node: &str, epoch: u64) -> Result<Snapshot> {
147 export_scoped(home, node, Some(epoch))
148}
149
150fn export_scoped(home: &Path, node: &str, epoch: Option<u64>) -> Result<Snapshot> {
151 let cfg = config::load_for_runtime(home)?;
152 super::require_pro(home, &cfg, "Hosted node checkpoints")?;
153 let mut db = encrypted::open_database(home, "state.sqlite3")?;
154 db.execute_batch("PRAGMA query_only=ON;")?;
155 let tx = db.transaction()?;
156 super::check_epoch(&tx, node, epoch)?;
157 let revision = tx.query_row(
158 "SELECT revision FROM hosted_checkpoints WHERE node=?1 AND lease_until>?2",
159 params![node, now()],
160 |r| r.get(0),
161 )?;
162 let uploading: bool = tx.query_row(
165 &format!(
166 "{SCOPE} SELECT EXISTS(SELECT 1 FROM file_chunks
167 WHERE object_id IN wf AND uploaded=0)"
168 ),
169 [node],
170 |r| r.get(0),
171 )?;
172 ensure!(
173 !uploading,
174 "web file upload is pending; checkpoint will retry"
175 );
176 let min_capability: u8 = tx.query_row(
179 "SELECT COALESCE(MIN(COALESCE(w.version,0)),?1) FROM network_links l LEFT JOIN wire_peers w
180 ON w.peer=l.peer AND w.peer_key=l.peer_key",
181 [crate::messages::wire::CURRENT_CAPABILITY],
182 |r| r.get(0),
183 )?;
184 let mut tables = BTreeMap::new();
185 for &(table, predicate) in TABLES {
186 if (table == "chat_message_dates"
187 && min_capability < crate::messages::wire::MESSAGE_DATES_VERSION)
188 || (table == "dashboard_times"
189 && min_capability < crate::messages::wire::DASHBOARD_TIME_VERSION)
190 {
191 continue;
192 }
193 let names = columns(&tx, table)?;
194 if matches!(
195 table,
196 "dashboards"
197 | "dashboard_times"
198 | "dashboard_publications"
199 | "dashboard_grants"
200 | "chat_message_dates"
201 ) && names.is_empty()
202 {
203 continue;
204 }
205 let mut rows = tx
206 .prepare(&format!("{SCOPE} SELECT * FROM {table} WHERE {predicate}"))?
207 .query_map([node], |r| {
208 (0..r.as_ref().column_count())
209 .map(|i| r.get(i).map(Cell::read))
210 .collect::<rusqlite::Result<Vec<_>>>()
211 })?
212 .collect::<rusqlite::Result<Vec<_>>>()?;
213 if matches!(
214 table,
215 "dashboards"
216 | "dashboard_times"
217 | "dashboard_publications"
218 | "dashboard_grants"
219 | "chat_message_dates"
220 ) && rows.is_empty()
221 {
222 continue;
223 }
224 for row in &mut rows {
225 if table == "agents" && !matches!(&row[2], Cell::Text(n) if n == node) {
226 let Cell::Text(id) = &row[0] else {
227 anyhow::bail!("invalid chat identity");
228 };
229 row[1] = Cell::Text(format!("remote:{id}"));
230 }
231 if table == "messages" {
232 let Cell::Text(payload) = &row[5] else {
233 anyhow::bail!("invalid message payload");
234 };
235 let message: Message = serde_json::from_str(payload)?;
236 let own: bool = tx.query_row(
237 "SELECT node_id=?2 FROM agents WHERE id=?1",
238 params![message.sender, node],
239 |r| r.get(0),
240 )?;
241 if !own {
242 row[4] = Cell::Text(message_fingerprint(
243 &message.recipient,
244 &message.text,
245 &message.files,
246 &message.reply_to,
247 &message.relay,
248 &[],
249 )?);
250 }
251 }
252 if table == "file_objects" {
253 row[5] = Cell::Integer(0);
254 }
255 if table == "agent_files"
256 && let Cell::Text(agent) = &row[1]
257 {
258 let own: bool = tx.query_row(
259 "SELECT node_id=?2 FROM agents WHERE id=?1",
260 params![agent, node],
261 |r| r.get(0),
262 )?;
263 if !own {
264 let Cell::Text(object) = &row[0] else {
265 anyhow::bail!("invalid file identity");
266 };
267 let message: String = tx.query_row(&format!("{SCOPE} SELECT m.id FROM messages m,json_each(m.payload,'$.attachments') j
268 WHERE m.id IN wm AND json_extract(j.value,'$.id')=?2 ORDER BY m.rowid LIMIT 1"), params![node,object], |r|r.get(0))?;
269 row[1] = Cell::Null;
270 row[2] = Cell::Text(message);
271 }
272 }
273 }
274 tables.insert(
275 table.into(),
276 Table {
277 columns: names,
278 rows,
279 },
280 );
281 }
282 tx.commit()?;
284 if epoch.is_some() {
285 super::check_epoch(&db, node, epoch)?;
286 }
287 Ok(Snapshot {
288 version: if tables.contains_key("dashboard_grants") {
289 3
290 } else if tables.contains_key("dashboard_publications") {
291 2
292 } else {
293 1
294 },
295 cluster: cfg.cluster.id,
296 node: node.into(),
297 revision,
298 tables,
299 })
300}
301
302pub(in crate::store) fn restore(
303 parent: &Connection,
304 snapshot: &Snapshot,
305 anchor: &gent_crypto::TrustAnchor,
306 node: &str,
307) -> Result<()> {
308 ensure!(!parent.is_autocommit(), "web restore requires transaction");
309 ensure!(
310 snapshot.version
311 == if snapshot.tables.contains_key("dashboard_grants") {
312 3
313 } else if snapshot.tables.contains_key("dashboard_publications") {
314 2
315 } else {
316 1
317 }
318 && snapshot.cluster == anchor.cluster_id
319 && snapshot.node == node
320 && snapshot
321 .tables
322 .keys()
323 .all(|t| TABLES.iter().any(|(name, _)| *name == t)),
324 "web checkpoint scope or version mismatch"
325 );
326 let source = Connection::open_in_memory()?;
327 for &(table, _) in TABLES {
328 let ddl: String = parent.query_row(
330 "SELECT sql FROM sqlite_master WHERE type='table' AND name=?1",
331 [table],
332 |r| r.get(0),
333 )?;
334 source.execute_batch(&ddl)?;
335 if matches!(
336 table,
337 "dashboards"
338 | "dashboard_times"
339 | "dashboard_publications"
340 | "dashboard_grants"
341 | "chat_message_dates"
342 ) && !snapshot.tables.contains_key(table)
343 {
344 continue;
345 }
346 let incoming = snapshot
347 .tables
348 .get(table)
349 .context("checkpoint table missing")?;
350 ensure!(
351 incoming.columns == columns(parent, table)?,
352 "web checkpoint schema mismatch"
353 );
354 let marks = (1..=incoming.columns.len())
355 .map(|i| format!("?{i}"))
356 .collect::<Vec<_>>()
357 .join(",");
358 let mut insert = source.prepare(&format!("INSERT INTO {table} VALUES({marks})"))?;
359 for row in &incoming.rows {
360 ensure!(
361 row.len() == incoming.columns.len(),
362 "invalid checkpoint row"
363 );
364 let values = row.iter().map(Cell::sql).collect::<Result<Vec<_>>>()?;
365 insert.execute(params_from_iter(values))?;
366 }
367 }
368 for &(table, predicate) in TABLES {
370 let outside: bool = source.query_row(
371 &format!(
372 "{SCOPE} SELECT EXISTS(SELECT 1 FROM {table} WHERE ({predicate}) IS NOT TRUE)"
373 ),
374 [node],
375 |r| r.get(0),
376 )?;
377 ensure!(!outside, "checkpoint contains unrelated native records");
378 }
379 source.execute(
382 "UPDATE file_objects SET incomplete_until=MIN(expires_at,?1) WHERE complete=0",
383 [now() + crate::file_objects::INCOMPLETE_TTL_SECONDS as i64],
384 )?;
385 let finals=parent.prepare("SELECT t.id,t.final_message FROM relay_turns t JOIN messages m ON m.id=t.final_message
386 JOIN agents a ON a.id=m.sender WHERE a.node_id!=?1 AND t.intermediary IN (SELECT id FROM agents WHERE node_id=?1)")?
387 .query_map([node],|r|Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?)))?.collect::<rusqlite::Result<Vec<_>>>()?;
388 rollback_speculative(parent, &source, node)?;
389 import::agents(parent, &source, node, anchor)?;
390 let files = source
393 .prepare("SELECT object_id FROM agent_files")?
394 .query_map([], |r| r.get::<_, String>(0))?
395 .collect::<rusqlite::Result<Vec<_>>>()?;
396 for file in files {
397 if let Some((agent, message, manifest)) = parent
398 .query_row(
399 "SELECT agent,message,manifest FROM agent_files WHERE object_id=?1",
400 [&file],
401 |r| {
402 Ok((
403 r.get::<_, Option<String>>(0)?,
404 r.get::<_, Option<String>>(1)?,
405 r.get::<_, String>(2)?,
406 ))
407 },
408 )
409 .optional()?
410 {
411 source.execute(
412 "UPDATE agent_files SET agent=?2,message=?3,manifest=?4 WHERE object_id=?1",
413 params![file, agent, message, manifest],
414 )?;
415 }
416 }
417 for &(table, _) in &TABLES[2..] {
418 if matches!(
419 table,
420 "dashboard_times" | "dashboard_publications" | "dashboard_grants"
421 ) {
422 continue;
424 }
425 if table == "dashboards" {
426 import::dashboards(parent, &source, node)?;
427 } else {
428 import::copy(parent, &source, table, node)?;
429 }
430 }
431 if !snapshot.tables.contains_key("chat_message_dates") {
432 crate::store::message_dates::backfill(parent, &source, node)?;
433 }
434 for (id, final_message) in finals {
435 parent.execute(
436 "UPDATE relay_turns SET final_message=COALESCE(final_message,?2)
437 WHERE id=?1 AND EXISTS(SELECT 1 FROM messages WHERE id=?2)",
438 params![id, final_message],
439 )?;
440 }
441 import::capacity(parent)?;
442 parent.execute("DELETE FROM hosted_directory WHERE node=?1", [node])?;
443 for registration in source
444 .prepare(
445 "SELECT a.id,a.name,a.provider,a.revoked,o.nonce,o.legacy,o.generation
446 FROM agents a JOIN network_origins o ON o.agent=a.id WHERE a.node_id=?1",
447 )?
448 .query_map([node], |r| {
449 Ok((
450 r.get::<_, String>(0)?,
451 r.get::<_, String>(1)?,
452 r.get::<_, String>(2)?,
453 r.get::<_, bool>(3)?,
454 r.get::<_, Option<String>>(4)?,
455 r.get::<_, Option<Vec<u8>>>(5)?,
456 r.get::<_, u64>(6)?,
457 ))
458 })?
459 {
460 let (id, name, provider, revoked, nonce, legacy, generation) = registration?;
461 let registration = crate::messages::Registration {
462 id,
463 name,
464 provider,
465 revoked,
466 node: node.into(),
467 nonce: nonce.map(|n| uuid::Uuid::parse_str(&n)).transpose()?,
468 legacy: legacy.map(|b| serde_json::from_slice(&b)).transpose()?,
469 generation,
470 };
471 parent.execute(
472 "INSERT INTO hosted_directory VALUES(?1,?2,?3,?4)",
473 params![
474 registration.id,
475 node,
476 snapshot.revision,
477 serde_json::to_vec(®istration)?
478 ],
479 )?;
480 }
481 ensure!(
482 !parent.prepare("PRAGMA foreign_key_check")?.exists([])?,
483 "invalid checkpoint references"
484 );
485 Ok(())
486}
487
488fn rollback_speculative(parent: &Connection, source: &Connection, node: &str) -> Result<()> {
489 parent.execute_batch(
492 "CREATE TEMP TABLE IF NOT EXISTS web_restore_messages(id TEXT PRIMARY KEY);
493 DELETE FROM web_restore_messages;",
494 )?;
495 for id in source
496 .prepare("SELECT id FROM messages")?
497 .query_map([], |r| r.get::<_, String>(0))?
498 {
499 parent.execute("INSERT INTO web_restore_messages VALUES(?1)", [id?])?;
500 }
501 let extra = "SELECT id FROM messages WHERE sender IN (SELECT id FROM agents WHERE node_id=?1)
502 AND id NOT IN web_restore_messages";
503 for (table, column) in [
504 ("relay_turns", "id"),
505 ("message_file_proofs", "message"),
506 ("agent_files", "message"),
507 ] {
508 parent.execute(
509 &format!("DELETE FROM {table} WHERE {column} IN ({extra})"),
510 [node],
511 )?;
512 }
513 parent.execute(
514 &format!("DELETE FROM messages WHERE id IN ({extra})"),
515 [node],
516 )?;
517 parent.execute("DELETE FROM exchanges WHERE a IN (SELECT id FROM agents WHERE node_id=?1)
518 AND NOT EXISTS(SELECT 1 FROM messages WHERE json_extract(payload,'$.exchange_id')=exchanges.id)",[node])?;
519 for (table, condition) in [
520 (
521 "relay_attachments",
522 "intermediary IN (SELECT id FROM agents WHERE node_id=?1)",
523 ),
524 (
525 "relay_turns",
526 "intermediary IN (SELECT id FROM agents WHERE node_id=?1)",
527 ),
528 (
529 "work_events",
530 "message_id IN (SELECT message_id FROM work_entries WHERE agent IN (SELECT id FROM agents WHERE node_id=?1))",
531 ),
532 (
533 "dashboards",
534 "agent IN (SELECT id FROM agents WHERE node_id=?1)",
535 ),
536 (
537 "dashboard_sent",
538 "agent IN (SELECT id FROM agents WHERE node_id=?1)",
539 ),
540 ("hosted_dashboard_gates", "node=?1"),
541 (
542 "work_entries",
543 "agent IN (SELECT id FROM agents WHERE node_id=?1)",
544 ),
545 (
546 "file_imports",
547 "agent IN (SELECT id FROM agents WHERE node_id=?1)",
548 ),
549 ] {
550 parent.execute(&format!("DELETE FROM {table} WHERE {condition}"), [node])?;
551 }
552 parent.execute("UPDATE messages SET acknowledged=0 WHERE recipient IN (SELECT id FROM agents WHERE node_id=?1)",[node])?;
554 for (id,name,provider,last_seen,revoked,generation) in source.prepare("SELECT a.id,a.name,a.provider,a.last_seen,a.revoked,o.generation FROM agents a JOIN network_origins o ON o.agent=a.id WHERE a.node_id=?1")?
555 .query_map([node], |r| Ok((r.get::<_,String>(0)?,r.get::<_,String>(1)?,r.get::<_,String>(2)?,r.get::<_,i64>(3)?,r.get::<_,bool>(4)?,r.get::<_,u64>(5)?)))?
556 .collect::<rusqlite::Result<Vec<_>>>()? {
557 parent.execute("UPDATE agents SET name=?2,provider=?3,last_seen=?4,revoked=?5 WHERE id=?1 AND node_id=?6", params![id,name,provider,last_seen,revoked,node])?;
558 parent.execute("UPDATE network_origins SET generation=?2 WHERE agent=?1 AND EXISTS(SELECT 1 FROM agents WHERE id=?1 AND node_id=?3)",params![id,generation,node])?;
559 }
560 parent.execute(
563 "DELETE FROM network_events WHERE id IN (SELECT id FROM hosted_event_gates WHERE node=?1)",
564 [node],
565 )?;
566 parent.execute("DELETE FROM hosted_event_gates WHERE node=?1", [node])?;
567 parent.execute("DELETE FROM hosted_message_gates WHERE node=?1", [node])?;
568 let committed: std::collections::BTreeSet<String> = source
571 .prepare("SELECT id FROM agents WHERE node_id=?1")?
572 .query_map([node], |r| r.get(0))?
573 .collect::<rusqlite::Result<_>>()?;
574 let candidates = parent
575 .prepare(
576 "SELECT id FROM agents WHERE node_id=?1
577 AND id NOT IN (SELECT sender FROM messages UNION SELECT recipient FROM messages
578 UNION SELECT a FROM exchanges UNION SELECT b FROM exchanges
579 UNION SELECT target FROM relay_attachments UNION SELECT target FROM recovered_sources)",
580 )?
581 .query_map([node], |r| r.get::<_, String>(0))?
582 .collect::<rusqlite::Result<Vec<_>>>()?;
583 for id in candidates.into_iter().filter(|id| !committed.contains(id)) {
584 for (table, column) in [
585 ("agent_activity", "agent"),
586 ("directory_cleared", "agent"),
587 ("network_origins", "agent"),
588 ("agent_files", "agent"),
589 ("wake_dispatches", "agent"),
590 ("file_exports", "agent"),
591 ("file_handoffs", "agent"),
592 ] {
593 parent.execute(&format!("DELETE FROM {table} WHERE {column}=?1"), [&id])?;
594 }
595 parent.execute("DELETE FROM agents WHERE id=?1", [&id])?;
596 }
597 parent.execute_batch("DROP TABLE web_restore_messages;")?;
598 Ok(())
599}