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