1use rusqlite::{params, Row};
13use serde::{Deserialize, Serialize};
14
15use super::store::Store;
16use super::StoreError;
17
18#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
21pub struct Bulletin {
22 pub id: String,
23 pub key: String,
24 pub author: String,
25 pub author_uid: String,
26 pub body: String,
27 pub targets: Vec<String>,
28 pub created_at: i64,
29 pub expires_at: i64,
30}
31
32pub(crate) const SCHEMA: &str = "
34 CREATE TABLE IF NOT EXISTS db_bulletins (
35 id TEXT PRIMARY KEY,
36 topic TEXT NOT NULL DEFAULT '',
37 author TEXT NOT NULL,
38 author_uid TEXT NOT NULL DEFAULT '',
39 body TEXT NOT NULL,
40 targets TEXT NOT NULL DEFAULT '',
41 created_at INTEGER NOT NULL,
42 expires_at INTEGER NOT NULL
43 );
44 CREATE INDEX IF NOT EXISTS idx_ids_bulletins_expires ON db_bulletins(expires_at);
45 CREATE TABLE IF NOT EXISTS db_bulletin_log (
46 author TEXT NOT NULL,
47 at INTEGER NOT NULL
48 );
49 CREATE INDEX IF NOT EXISTS idx_ids_bulletin_log_at ON db_bulletin_log(at);
50 CREATE TABLE IF NOT EXISTS db_bulletin_seen (
51 reader TEXT NOT NULL,
52 bulletin_id TEXT NOT NULL,
53 PRIMARY KEY (reader, bulletin_id)
54 );";
55
56const LOG_KEPT_MS: i64 = 2 * 60 * 60 * 1000;
58
59const COLS: &str = "id, topic, author, author_uid, body, targets, created_at, expires_at";
60
61fn row_to_bulletin(row: &Row) -> rusqlite::Result<Bulletin> {
62 let targets: String = row.get("targets")?;
63 Ok(Bulletin {
64 id: row.get("id")?,
65 key: row.get("topic")?,
66 author: row.get("author")?,
67 author_uid: row.get("author_uid")?,
68 body: row.get("body")?,
69 targets: targets.split(',').filter(|t| !t.is_empty()).map(str::to_string).collect(),
70 created_at: row.get("created_at")?,
71 expires_at: row.get("expires_at")?,
72 })
73}
74
75impl Bulletin {
76 pub fn is_for(&self, reader: &str) -> bool {
78 self.targets.is_empty() || self.targets.iter().any(|t| t == reader)
79 }
80}
81
82impl Store {
83 pub fn bulletin_put(&self, b: &Bulletin, now_ms: i64) -> Result<(), StoreError> {
87 self.bulletin_put_replacing(b, now_ms, false)
88 }
89
90 pub fn bulletin_put_for_fleet(&self, b: &Bulletin, now_ms: i64) -> Result<(), StoreError> {
93 self.bulletin_put_replacing(b, now_ms, true)
94 }
95
96 fn bulletin_put_replacing(&self, b: &Bulletin, now_ms: i64, any_author: bool) -> Result<(), StoreError> {
97 let conn = self.conn().lock().unwrap();
98 conn.execute(
99 "DELETE FROM db_bulletins WHERE expires_at <= ?1
100 OR (?2 <> '' AND topic = ?2 AND (?4 OR author = ?3 COLLATE NOCASE))",
101 params![now_ms, b.key, b.author, any_author],
102 )?;
103 conn.execute("DELETE FROM db_bulletin_log WHERE at < ?1", params![now_ms - LOG_KEPT_MS])?;
104 conn.execute("INSERT INTO db_bulletin_log (author, at) VALUES (?1, ?2)", params![b.author.to_lowercase(), b.created_at])?;
105 conn.execute("DELETE FROM db_bulletin_seen WHERE bulletin_id NOT IN (SELECT id FROM db_bulletins)", [])?;
106 conn.execute(
107 &format!("INSERT INTO db_bulletins ({COLS}) VALUES (?1,?2,?3,?4,?5,?6,?7,?8)"),
108 params![b.id, b.key, b.author, b.author_uid, b.body, b.targets.join(","), b.created_at, b.expires_at],
109 )?;
110 Ok(())
111 }
112
113 pub fn bulletin_counts(&self, author: &str, since_ms: i64, now_ms: i64) -> Result<(i64, i64), StoreError> {
115 let conn = self.conn().lock().unwrap();
116 let recent = conn.query_row(
117 "SELECT COUNT(*) FROM db_bulletin_log WHERE author = ?1 AND at >= ?2",
118 params![author.to_lowercase(), since_ms],
119 |r| r.get(0),
120 )?;
121 let live = conn.query_row(
122 "SELECT COUNT(*) FROM db_bulletins WHERE author = ?1 COLLATE NOCASE AND expires_at > ?2",
123 params![author, now_ms],
124 |r| r.get(0),
125 )?;
126 Ok((recent, live))
127 }
128
129 pub fn bulletins_unseen(&self, reader: &str, now_ms: i64) -> Result<Vec<Bulletin>, StoreError> {
131 let conn = self.conn().lock().unwrap();
132 let mut stmt = conn.prepare(&format!(
133 "SELECT {COLS} FROM db_bulletins
134 WHERE expires_at > ?1 AND author <> ?2 COLLATE NOCASE
135 AND id NOT IN (SELECT bulletin_id FROM db_bulletin_seen WHERE reader = ?2)
136 ORDER BY created_at ASC, rowid ASC"
137 ))?;
138 let rows = stmt.query_map(params![now_ms, reader], row_to_bulletin)?;
139 Ok(rows.collect::<Result<Vec<_>, _>>()?.into_iter().filter(|b| b.is_for(reader)).collect())
140 }
141
142 pub fn bulletins_mark_seen(&self, reader: &str, ids: &[String]) -> Result<(), StoreError> {
144 let conn = self.conn().lock().unwrap();
145 for id in ids {
146 conn.execute("INSERT OR IGNORE INTO db_bulletin_seen (reader, bulletin_id) VALUES (?1, ?2)", params![reader, id])?;
147 }
148 Ok(())
149 }
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 const NOW: i64 = 1_000_000_000_000;
157 const MIN: i64 = 60_000;
158
159 fn store() -> (tempfile::TempDir, Store) {
160 let dir = tempfile::tempdir().unwrap();
161 let s = Store::open_identity_store(&dir.path().join("identity-store.db")).unwrap();
162 (dir, s)
163 }
164
165 fn bulletin(id: &str, key: &str, author: &str, targets: &[&str], at: i64) -> Bulletin {
166 Bulletin {
167 id: id.into(),
168 key: key.into(),
169 author: author.into(),
170 body: format!("text {id}"),
171 targets: targets.iter().map(|t| t.to_string()).collect(),
172 created_at: at,
173 expires_at: at + 60 * MIN,
174 ..Default::default()
175 }
176 }
177
178 #[test]
179 fn a_reader_sees_each_bulletin_for_it_once_and_never_its_own() {
180 let (_d, s) = store();
181 s.bulletin_put(&bulletin("a", "", "AgentX", &[], NOW - 2 * MIN), NOW).unwrap();
182 s.bulletin_put(&bulletin("b", "", "AgentY", &["agent1"], NOW - MIN), NOW).unwrap();
183 s.bulletin_put(&bulletin("c", "", "AgentY", &["camper"], NOW - MIN), NOW).unwrap();
184 let got = s.bulletins_unseen("agent1", NOW).unwrap();
185 assert_eq!(got.iter().map(|b| b.id.as_str()).collect::<Vec<_>>(), vec!["a", "b"], "oldest first, targets honoured");
186 s.bulletins_mark_seen("agent1", &["a".into(), "b".into()]).unwrap();
187 assert!(s.bulletins_unseen("agent1", NOW).unwrap().is_empty(), "shown once");
188 assert_eq!(s.bulletins_unseen("camper", NOW).unwrap().len(), 2, "another reader still sees them");
189 assert!(s.bulletins_unseen("agentx", NOW).unwrap().iter().all(|b| b.author != "AgentX"), "not its own");
190 }
191
192 #[test]
193 fn a_later_post_under_the_same_key_replaces_the_earlier_and_is_shown_again() {
194 let (_d, s) = store();
195 s.bulletin_put(&bulletin("m1", "mode", "AgentY", &[], NOW - 2 * MIN), NOW).unwrap();
196 s.bulletins_mark_seen("agent1", &["m1".into()]).unwrap();
197 s.bulletin_put(&bulletin("m2", "mode", "AgentY", &[], NOW - MIN), NOW).unwrap();
198 let got = s.bulletins_unseen("agent1", NOW).unwrap();
199 assert_eq!(got.iter().map(|b| b.id.as_str()).collect::<Vec<_>>(), vec!["m2"]);
200 }
201
202 #[test]
203 fn the_fleets_notice_replaces_every_authors_earlier_one_and_an_ordinary_post_only_its_own() {
204 let (_d, s) = store();
205 s.bulletin_put_for_fleet(&bulletin("m1", "mode", "AgentY", &[], NOW - 3 * MIN), NOW).unwrap();
206 s.bulletin_put_for_fleet(&bulletin("m2", "mode", "AgentX", &[], NOW - 2 * MIN), NOW).unwrap();
207 let got = s.bulletins_unseen("agent1", NOW).unwrap();
208 assert_eq!(got.iter().map(|b| b.id.as_str()).collect::<Vec<_>>(), vec!["m2"], "the last setter's notice is the only one");
209 s.bulletin_put(&bulletin("s1", "status", "AgentY", &[], NOW - MIN), NOW).unwrap();
210 s.bulletin_put(&bulletin("s2", "status", "AgentX", &[], NOW), NOW).unwrap();
211 let ids: Vec<String> = s.bulletins_unseen("agent1", NOW).unwrap().into_iter().map(|b| b.id).collect();
212 assert_eq!(ids, vec!["m2", "s1", "s2"], "an ordinary key is still per author");
213 }
214
215 #[test]
216 fn expired_bulletins_are_not_read_and_the_next_write_deletes_them() {
217 let (_d, s) = store();
218 s.bulletin_put(&bulletin("old", "", "AgentY", &[], NOW), NOW).unwrap();
219 let later = NOW + 61 * MIN;
220 assert!(s.bulletins_unseen("agent1", later).unwrap().is_empty());
221 s.bulletin_put(&bulletin("new", "", "AgentY", &[], later), later).unwrap();
222 let count: i64 = s.conn().lock().unwrap().query_row("SELECT COUNT(*) FROM db_bulletins", [], |r| r.get(0)).unwrap();
223 assert_eq!(count, 1);
224 }
225
226 #[test]
227 fn replacing_or_expiring_a_post_does_not_reset_the_hourly_count() {
228 let (_d, s) = store();
229 for i in 0..3 {
230 let b = Bulletin { expires_at: NOW - 5 * MIN + i * 1000 + 1_000, ..bulletin(&format!("m{i}"), "mode", "AgentY", &[], NOW - 5 * MIN + i * 1000) };
231 s.bulletin_put(&b, NOW - 5 * MIN + i * 1000).unwrap();
232 }
233 assert_eq!(s.bulletin_counts("AgentY", NOW - 60 * MIN, NOW).unwrap().0, 3, "three posts under one key still count three");
234 }
235
236 #[test]
237 fn a_key_is_replaced_only_by_the_same_author() {
238 let (_d, s) = store();
239 s.bulletin_put(&bulletin("x1", "mode", "AgentX", &[], NOW - 2 * MIN), NOW).unwrap();
240 s.bulletin_put(&bulletin("y1", "mode", "AgentY", &[], NOW - MIN), NOW).unwrap();
241 let ids: Vec<String> = s.bulletins_unseen("agent1", NOW).unwrap().into_iter().map(|b| b.id).collect();
242 assert_eq!(ids, vec!["x1", "y1"], "AgentY's post under the key did not remove AgentX's");
243 s.bulletin_put(&bulletin("y2", "mode", "agenty", &[], NOW), NOW).unwrap();
244 let ids: Vec<String> = s.bulletins_unseen("agent1", NOW).unwrap().into_iter().map(|b| b.id).collect();
245 assert_eq!(ids, vec!["x1", "y2"], "its own earlier one was replaced");
246 }
247
248 #[test]
249 fn counts_are_an_authors_recent_and_live_posts() {
250 let (_d, s) = store();
251 s.bulletin_put(&bulletin("a", "", "AgentY", &[], NOW - 90 * MIN), NOW - 90 * MIN).unwrap();
252 s.bulletin_put(&bulletin("b", "", "agenty", &[], NOW - 10 * MIN), NOW - 10 * MIN).unwrap();
253 s.bulletin_put(&bulletin("c", "", "AgentX", &[], NOW - MIN), NOW - MIN).unwrap();
254 assert_eq!(s.bulletin_counts("AgentY", NOW - 60 * MIN, NOW).unwrap(), (1, 1), "one an hour ago, one still live");
255 }
256}