Skip to main content

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    expiry_after(chat_duration_secs(chat_id)?)
45}
46
47/// The absolute NIP-40 expiry for a lifespan that starts now. A file send calls this
48/// after its upload, so the clock starts at publish, not at the moment the send was asked
49/// for.
50pub fn expiry_after(duration_secs: u64) -> Option<u64> {
51    Some(crate::clock::now_secs() + duration_secs)
52}
53
54/// The NIP-40 expiry an edit of `message_id` carries: the message's own, so the edit
55/// expires with it and never outlives it. Errs once that moment has passed.
56pub async fn edit_expiry(message_id: &str) -> Result<Option<u64>, String> {
57    let resident = {
58        let state = crate::state::STATE.lock().await;
59        state.find_message(message_id).map(|(_, m)| m.expiration)
60    };
61    let expiry = match resident {
62        Some(exp) => exp,
63        None => crate::db::events::event_expiration(message_id)?,
64    };
65    let now = crate::clock::now_secs();
66    if expiry.is_some_and(|exp| exp <= now) {
67        return Err("That message has already expired".into());
68    }
69    Ok(expiry)
70}
71
72/// Reset the in-flight flag whatever exit `sweep_expired` takes.
73struct SweepGuard;
74impl Drop for SweepGuard {
75    fn drop(&mut self) {
76        SWEEP_RUNNING.store(false, Ordering::Release);
77    }
78}
79static SWEEP_RUNNING: AtomicBool = AtomicBool::new(false);
80
81/// Purge every message whose NIP-40 expiry has passed: drop it from STATE and
82/// the DB, remove cached attachment files no sibling still needs, and — for OUR
83/// OWN file messages — issue a Blossom blob delete (blobs carry no self-expiry).
84/// Emits `message_removed` with reason "self-destruct" per purged row so the UI
85/// can derez it.
86///
87/// Local-only: every client honors the same NIP-40 tag independently, so no
88/// delete is broadcast. Safe to call repeatedly (a ticker + a boot catch-up).
89pub async fn sweep_expired() -> Option<u64> {
90    if SWEEP_RUNNING.swap(true, Ordering::AcqRel) {
91        return None; // a sweep is already in flight
92    }
93    let _guard = SweepGuard;
94
95    let now = crate::clock::now_secs();
96
97    // Pass 1 — scan under the lock: collect the expired, and track the soonest
98    // still-pending expiry so the loop can time the next sweep to the second.
99    let mut soonest: Option<u64> = None;
100    let expired_ids: Vec<String> = {
101        let state = crate::state::STATE.lock().await;
102        let mut ids = Vec::new();
103        for chat in &state.chats {
104            for msg in chat.messages.iter() {
105                let exp = msg.expiration_secs;
106                if exp == 0 {
107                    continue;
108                }
109                let exp = exp as u64;
110                if exp <= now {
111                    ids.push(msg.id_hex());
112                } else {
113                    soonest = Some(soonest.map_or(exp, |s| s.min(exp)));
114                }
115            }
116        }
117        ids
118    };
119    if expired_ids.is_empty() {
120        return soonest;
121    }
122
123    // Pass 2 — purge each. Re-lock per id so the sweep never holds STATE across
124    // an await (DB delete, blob delete).
125    for id in expired_ids {
126        purge_one(&id, None).await;
127    }
128
129    soonest
130}
131
132/// Purge one expired message everywhere it lives: STATE (emitting the derez
133/// event when it was resident), cached attachment files, our own Blossom
134/// blobs, and the DB row. `db_fallback` supplies (attachments, mine) for rows
135/// that never hydrated into STATE (a DB load caught them first); `None` keeps
136/// the sweep's contract of skipping ids something else already removed.
137pub(crate) async fn purge_one(id: &str, db_fallback: Option<(Vec<crate::types::Attachment>, bool)>) {
138    let removed = {
139        let mut state = crate::state::STATE.lock().await;
140        state.remove_message(id)
141    };
142    let (attachments, mine, resident_chat) = match removed {
143        Some((chat_id, msg)) => (msg.attachments, msg.mine, Some(chat_id)),
144        None => match db_fallback {
145            Some((attachments, mine)) => (attachments, mine, None),
146            None => return, // already gone (client-side derez or a prior sweep)
147        },
148    };
149
150    if !attachments.is_empty() {
151        // Refcount filter: keep files/blobs a sibling message still points at.
152        let unique = crate::deletion::filter_unreferenced_attachments(id, attachments).await;
153        crate::deletion::delete_cached_attachment_files_pub(&unique);
154
155        // Our own, now-unreferenced blob → wipe it network-side too, minus any
156        // url the ledger says another message still rides (smart-forward).
157        if mine {
158            let urls: Vec<String> = crate::deletion::scrub_safe_urls(&unique, id);
159            if !urls.is_empty() && crate::state::nostr_client().is_some() {
160                if let Ok(signer) = crate::signer::active_signer() {
161                    crate::blossom::delete_blobs_best_effort(signer, urls);
162                }
163            }
164        }
165    }
166
167    let _ = crate::db::events::delete_event(id).await;
168
169    // Only a STATE-resident message can be on screen — DB-only rows were
170    // caught before rendering and vanish silently.
171    if let Some(chat_id) = resident_chat {
172        crate::traits::emit_event(
173            "message_removed",
174            &serde_json::json!({ "id": id, "chat_id": chat_id, "reason": "self-destruct" }),
175        );
176    }
177}
178
179/// Drop already-expired messages from a freshly-loaded DB window, purging
180/// their remnants in the background. Rows that expired while the app was
181/// closed (or while their chat was out of STATE) must NEVER render — not
182/// even for the frame between hydration and the next sweep tick.
183pub fn strip_expired(messages: &mut Vec<crate::types::Message>) {
184    let now = crate::clock::now_secs();
185    let mut expired: Vec<(String, Vec<crate::types::Attachment>, bool)> = Vec::new();
186    messages.retain(|m| match m.expiration {
187        Some(exp) if exp <= now => {
188            expired.push((m.id.clone(), m.attachments.clone(), m.mine));
189            false
190        }
191        _ => true,
192    });
193    if expired.is_empty() {
194        return;
195    }
196    crate::db::spawn_bound(async move {
197        for (id, attachments, mine) in expired {
198            purge_one(&id, Some((attachments, mine))).await;
199        }
200    });
201}
202
203/// Time until the next sweep: sleep exactly until the soonest pending expiry
204/// (down to a 1s floor) so the final stretch purges in real time, but never
205/// longer than SWEEP_MAX_SECS so a newly-arrived message is noticed promptly.
206fn next_sweep_delay(soonest: Option<u64>) -> std::time::Duration {
207    let now = crate::clock::now_secs();
208    let secs = match soonest {
209        Some(exp) => exp.saturating_sub(now).clamp(1, SWEEP_MAX_SECS),
210        None => SWEEP_MAX_SECS,
211    };
212    std::time::Duration::from_secs(secs)
213}
214
215/// The self-destruct sweep loop: purge, then sleep until the next expiry is due
216/// (adaptive — 1s-tight near a deadline, up to SWEEP_MAX_SECS when idle). The
217/// immediate first pass catches anything that expired while offline. Hosts with
218/// their own async runtime (e.g. Tauri) should spawn this directly.
219pub async fn run_sweeper_loop() {
220    loop {
221        let soonest = sweep_expired().await;
222        crate::rt::time::sleep(next_sweep_delay(soonest)).await;
223    }
224}
225
226/// Convenience for tokio-native hosts (CLI/SDK): spawn `run_sweeper_loop` once.
227/// Idempotent — a second call is a no-op.
228pub fn start_sweeper() {
229    static STARTED: AtomicBool = AtomicBool::new(false);
230    if STARTED.swap(true, Ordering::AcqRel) {
231        return;
232    }
233    // NOT bound: this loop runs for the process lifetime and must sweep
234    // whichever account is live. Binding would pin it to whoever logged in
235    // first, and every later account would silently stop expiring messages.
236    // spawn-detached: the sweeper must expire messages for whichever account is live; see above.
237    crate::rt::spawn(run_sweeper_loop());
238}