vector_core/self_destruct.rs
1//! Self-Destruct Timer — per-chat NIP-40 message expiry ("disappearing
2//! messages"). The per-chat lifespan is a DURATION stored in the account
3//! settings KV; each outgoing DM in that chat is stamped with an absolute
4//! NIP-40 expiry so relays drop the gift-wrap and every compliant client
5//! purges its local copy on schedule. Purge is local-only per client — the
6//! expiry tag travels with the message, so no delete broadcast is needed.
7
8use std::sync::atomic::{AtomicBool, Ordering};
9
10const KEY_PREFIX: &str = "self_destruct:";
11
12/// Longest the sweeper sleeps when nothing is near expiry — bounds how quickly
13/// a newly-arrived self-destruct message is first noticed (it's then scheduled
14/// precisely). Kept below the shortest offered timer (10s) so even a fresh
15/// short-fused message is always seen before it expires. Near an expiry the
16/// loop sleeps exactly until it, down to a 1s floor.
17const SWEEP_MAX_SECS: u64 = 8;
18
19/// Configured self-destruct DURATION in seconds for a chat, or `None` when the
20/// chat keeps messages permanently. Stored per-account, so it naturally follows
21/// the active account's DB pool.
22pub fn chat_duration_secs(chat_id: &str) -> Option<u64> {
23 crate::db::settings::get_sql_setting(format!("{KEY_PREFIX}{chat_id}"))
24 .ok()
25 .flatten()
26 .and_then(|v| v.parse::<u64>().ok())
27 .filter(|d| *d > 0)
28}
29
30/// Set the self-destruct duration for a chat. `None` (or 0) clears it back to
31/// permanent by removing the key.
32pub fn set_chat_duration_secs(chat_id: &str, secs: Option<u64>) -> Result<(), String> {
33 let key = format!("{KEY_PREFIX}{chat_id}");
34 match secs {
35 Some(d) if d > 0 => crate::db::settings::set_sql_setting(key, d.to_string()),
36 _ => crate::db::settings::remove_setting(&key),
37 }
38}
39
40/// Resolve the absolute NIP-40 expiry (unix seconds) to stamp on a NEW message
41/// sent to `chat_id`, honoring the chat's configured lifespan. `None` when the
42/// chat is permanent.
43pub fn resolve_send_expiry(chat_id: &str) -> Option<u64> {
44 let duration = chat_duration_secs(chat_id)?;
45 let now = std::time::SystemTime::now()
46 .duration_since(std::time::UNIX_EPOCH)
47 .ok()?
48 .as_secs();
49 Some(now + duration)
50}
51
52/// Reset the in-flight flag whatever exit `sweep_expired` takes.
53struct SweepGuard;
54impl Drop for SweepGuard {
55 fn drop(&mut self) {
56 SWEEP_RUNNING.store(false, Ordering::Release);
57 }
58}
59static SWEEP_RUNNING: AtomicBool = AtomicBool::new(false);
60
61/// Purge every message whose NIP-40 expiry has passed: drop it from STATE and
62/// the DB, remove cached attachment files no sibling still needs, and — for OUR
63/// OWN file messages — issue a Blossom blob delete (blobs carry no self-expiry).
64/// Emits `message_removed` with reason "self-destruct" per purged row so the UI
65/// can derez it.
66///
67/// Local-only: every client honors the same NIP-40 tag independently, so no
68/// delete is broadcast. Safe to call repeatedly (a ticker + a boot catch-up).
69pub async fn sweep_expired() -> Option<u64> {
70 if SWEEP_RUNNING.swap(true, Ordering::AcqRel) {
71 return None; // a sweep is already in flight
72 }
73 let _guard = SweepGuard;
74
75 // Snapshot the session so a mid-sweep account swap can't purge account A's
76 // rows against account B's DB (see SessionGuard contract).
77 let session = crate::state::SessionGuard::capture();
78
79 let now = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
80 Ok(d) => d.as_secs(),
81 Err(_) => return None,
82 };
83
84 // Pass 1 — scan under the lock: collect the expired, and track the soonest
85 // still-pending expiry so the loop can time the next sweep to the second.
86 let mut soonest: Option<u64> = None;
87 let expired_ids: Vec<String> = {
88 let state = crate::state::STATE.lock().await;
89 let mut ids = Vec::new();
90 for chat in &state.chats {
91 for msg in chat.messages.iter() {
92 let exp = msg.expiration_secs;
93 if exp == 0 {
94 continue;
95 }
96 let exp = exp as u64;
97 if exp <= now {
98 ids.push(msg.id_hex());
99 } else {
100 soonest = Some(soonest.map_or(exp, |s| s.min(exp)));
101 }
102 }
103 }
104 ids
105 };
106 if !session.is_valid() {
107 return None;
108 }
109 if expired_ids.is_empty() {
110 return soonest;
111 }
112
113 // Pass 2 — purge each. Re-lock per id so the sweep never holds STATE across
114 // an await (DB delete, blob delete).
115 for id in expired_ids {
116 purge_one(&id, None).await;
117 }
118
119 soonest
120}
121
122/// Purge one expired message everywhere it lives: STATE (emitting the derez
123/// event when it was resident), cached attachment files, our own Blossom
124/// blobs, and the DB row. `db_fallback` supplies (attachments, mine) for rows
125/// that never hydrated into STATE (a DB load caught them first); `None` keeps
126/// the sweep's contract of skipping ids something else already removed.
127pub(crate) async fn purge_one(id: &str, db_fallback: Option<(Vec<crate::types::Attachment>, bool)>) {
128 let removed = {
129 let mut state = crate::state::STATE.lock().await;
130 state.remove_message(id)
131 };
132 let (attachments, mine, resident_chat) = match removed {
133 Some((chat_id, msg)) => (msg.attachments, msg.mine, Some(chat_id)),
134 None => match db_fallback {
135 Some((attachments, mine)) => (attachments, mine, None),
136 None => return, // already gone (client-side derez or a prior sweep)
137 },
138 };
139
140 if !attachments.is_empty() {
141 // Refcount filter: keep files/blobs a sibling message still points at.
142 let unique = crate::deletion::filter_unreferenced_attachments(id, attachments).await;
143 crate::deletion::delete_cached_attachment_files_pub(&unique);
144
145 // Our own, now-unreferenced blob → wipe it network-side too.
146 if mine {
147 let urls: Vec<String> = unique
148 .iter()
149 .flat_map(|a| a.all_urls().map(str::to_string))
150 .collect();
151 if !urls.is_empty() {
152 if crate::state::nostr_client().is_some() {
153 if let Ok(signer) = crate::signer::active_signer() {
154 crate::blossom::delete_blobs_best_effort(signer, urls);
155 }
156 }
157 }
158 }
159 }
160
161 let _ = crate::db::events::delete_event(id).await;
162
163 // Only a STATE-resident message can be on screen — DB-only rows were
164 // caught before rendering and vanish silently.
165 if let Some(chat_id) = resident_chat {
166 crate::traits::emit_event(
167 "message_removed",
168 &serde_json::json!({ "id": id, "chat_id": chat_id, "reason": "self-destruct" }),
169 );
170 }
171}
172
173/// Drop already-expired messages from a freshly-loaded DB window, purging
174/// their remnants in the background. Rows that expired while the app was
175/// closed (or while their chat was out of STATE) must NEVER render — not
176/// even for the frame between hydration and the next sweep tick.
177pub fn strip_expired(messages: &mut Vec<crate::types::Message>) {
178 let now = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
179 Ok(d) => d.as_secs(),
180 Err(_) => return,
181 };
182 let mut expired: Vec<(String, Vec<crate::types::Attachment>, bool)> = Vec::new();
183 messages.retain(|m| match m.expiration {
184 Some(exp) if exp <= now => {
185 expired.push((m.id.clone(), m.attachments.clone(), m.mine));
186 false
187 }
188 _ => true,
189 });
190 if expired.is_empty() {
191 return;
192 }
193 let session = crate::state::SessionGuard::capture();
194 tokio::spawn(async move {
195 for (id, attachments, mine) in expired {
196 if !session.is_valid() {
197 return;
198 }
199 purge_one(&id, Some((attachments, mine))).await;
200 }
201 });
202}
203
204/// Time until the next sweep: sleep exactly until the soonest pending expiry
205/// (down to a 1s floor) so the final stretch purges in real time, but never
206/// longer than SWEEP_MAX_SECS so a newly-arrived message is noticed promptly.
207fn next_sweep_delay(soonest: Option<u64>) -> std::time::Duration {
208 let now = std::time::SystemTime::now()
209 .duration_since(std::time::UNIX_EPOCH)
210 .map(|d| d.as_secs())
211 .unwrap_or(0);
212 let secs = match soonest {
213 Some(exp) => exp.saturating_sub(now).clamp(1, SWEEP_MAX_SECS),
214 None => SWEEP_MAX_SECS,
215 };
216 std::time::Duration::from_secs(secs)
217}
218
219/// The self-destruct sweep loop: purge, then sleep until the next expiry is due
220/// (adaptive — 1s-tight near a deadline, up to SWEEP_MAX_SECS when idle). The
221/// immediate first pass catches anything that expired while offline. Hosts with
222/// their own async runtime (e.g. Tauri) should spawn this directly.
223pub async fn run_sweeper_loop() {
224 loop {
225 let soonest = sweep_expired().await;
226 tokio::time::sleep(next_sweep_delay(soonest)).await;
227 }
228}
229
230/// Convenience for tokio-native hosts (CLI/SDK): spawn `run_sweeper_loop` once.
231/// Idempotent — a second call is a no-op.
232pub fn start_sweeper() {
233 static STARTED: AtomicBool = AtomicBool::new(false);
234 if STARTED.swap(true, Ordering::AcqRel) {
235 return;
236 }
237 tokio::spawn(run_sweeper_loop());
238}