Skip to main content

vector_core/db/
bots.rs

1//! Last-known bot manifests (kind 10304) — the `/` command picker's persistent
2//! layer. One row per bot pubkey, replaced only by a NEWER manifest edition, so
3//! the picker serves instantly from boot while a background refetch converges.
4//! Manifests are PUBLIC replaceable events: rows are plaintext by design.
5
6use rusqlite::{params, OptionalExtension};
7
8fn now_secs() -> u64 {
9    crate::clock::now_secs()
10}
11
12/// Store a validated manifest for `pubkey_hex`, keeping whichever edition is
13/// newest (`event_created_at` = the manifest event's timestamp). An equal-time
14/// re-fetch refreshes `fetched_at` only via the replace (idempotent).
15pub fn upsert_bot_manifest(pubkey_hex: &str, manifest_json: &str, event_created_at: u64) -> Result<(), String> {
16    let conn = super::get_write_connection_guard_static()?;
17    conn.execute(
18        "INSERT INTO bot_manifests (pubkey, manifest, event_created_at, fetched_at)
19         VALUES (?1, ?2, ?3, ?4)
20         ON CONFLICT(pubkey) DO UPDATE SET
21             manifest = excluded.manifest,
22             event_created_at = excluded.event_created_at,
23             fetched_at = excluded.fetched_at
24         WHERE excluded.event_created_at >= bot_manifests.event_created_at",
25        params![pubkey_hex, manifest_json, event_created_at as i64, now_secs() as i64],
26    )
27    .map_err(|e| format!("upsert bot manifest: {e}"))?;
28    Ok(())
29}
30
31/// Last-known manifest JSON for one bot, with its edition timestamp.
32pub fn get_bot_manifest(pubkey_hex: &str) -> Result<Option<(String, u64)>, String> {
33    let conn = super::get_db_connection_guard_static()?;
34    conn.query_row(
35        "SELECT manifest, event_created_at FROM bot_manifests WHERE pubkey = ?1",
36        params![pubkey_hex],
37        |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)? as u64)),
38    )
39    .optional()
40    .map_err(|e| format!("get bot manifest: {e}"))
41}
42
43/// Last-known manifests for a set of bots: `(pubkey_hex, manifest_json)`.
44/// Bots with no stored manifest are simply absent.
45pub fn get_bot_manifests(pubkeys: &[String]) -> Result<Vec<(String, String)>, String> {
46    if pubkeys.is_empty() {
47        return Ok(Vec::new());
48    }
49    let conn = super::get_db_connection_guard_static()?;
50    let placeholders = vec!["?"; pubkeys.len()].join(",");
51    let sql = format!("SELECT pubkey, manifest FROM bot_manifests WHERE pubkey IN ({placeholders})");
52    let mut stmt = conn.prepare(&sql).map_err(|e| format!("get bot manifests: {e}"))?;
53    let rows = stmt
54        .query_map(rusqlite::params_from_iter(pubkeys.iter()), |r| {
55            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
56        })
57        .map_err(|e| format!("get bot manifests: {e}"))?
58        .filter_map(|r| r.ok())
59        .collect();
60    Ok(rows)
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
68        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
69        crate::db::close_database();
70        crate::db::clear_id_caches();
71        use nostr_sdk::prelude::ToBech32;
72        let tmp = tempfile::tempdir().unwrap();
73        let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
74        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
75        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
76        crate::db::set_current_account(account.clone()).unwrap();
77        crate::db::init_database(&account).unwrap();
78        (tmp, guard)
79    }
80
81    #[test]
82    fn manifest_store_keeps_the_newest_edition() {
83        let (_tmp, _guard) = init_test_db();
84
85        upsert_bot_manifest("aa", r#"{"v":1,"commands":[]}"#, 100).unwrap();
86        assert_eq!(get_bot_manifest("aa").unwrap().unwrap().1, 100);
87
88        // A newer edition replaces…
89        upsert_bot_manifest("aa", r#"{"v":1,"commands":[{"name":"x","description":"d"}]}"#, 200).unwrap();
90        let (json, at) = get_bot_manifest("aa").unwrap().unwrap();
91        assert_eq!(at, 200);
92        assert!(json.contains("\"x\""));
93
94        // …while an OLDER one is refused (a lagging relay can't roll us back).
95        upsert_bot_manifest("aa", r#"{"v":1,"commands":[]}"#, 150).unwrap();
96        let (json, at) = get_bot_manifest("aa").unwrap().unwrap();
97        assert_eq!(at, 200);
98        assert!(json.contains("\"x\""));
99
100        upsert_bot_manifest("bb", r#"{"v":1,"commands":[]}"#, 50).unwrap();
101        let batch = get_bot_manifests(&["aa".into(), "bb".into(), "cc".into()]).unwrap();
102        assert_eq!(batch.len(), 2, "absent bots are simply missing");
103        assert!(get_bot_manifests(&[]).unwrap().is_empty());
104    }
105}