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