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    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    let now = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
76        Ok(d) => d.as_secs(),
77        Err(_) => return None,
78    };
79
80    // Pass 1 — scan under the lock: collect the expired, and track the soonest
81    // still-pending expiry so the loop can time the next sweep to the second.
82    let mut soonest: Option<u64> = None;
83    let expired_ids: Vec<String> = {
84        let state = crate::state::STATE.lock().await;
85        let mut ids = Vec::new();
86        for chat in &state.chats {
87            for msg in chat.messages.iter() {
88                let exp = msg.expiration_secs;
89                if exp == 0 {
90                    continue;
91                }
92                let exp = exp as u64;
93                if exp <= now {
94                    ids.push(msg.id_hex());
95                } else {
96                    soonest = Some(soonest.map_or(exp, |s| s.min(exp)));
97                }
98            }
99        }
100        ids
101    };
102    if expired_ids.is_empty() {
103        return soonest;
104    }
105
106    // Pass 2 — purge each. Re-lock per id so the sweep never holds STATE across
107    // an await (DB delete, blob delete).
108    for id in expired_ids {
109        purge_one(&id, None).await;
110    }
111
112    soonest
113}
114
115/// Purge one expired message everywhere it lives: STATE (emitting the derez
116/// event when it was resident), cached attachment files, our own Blossom
117/// blobs, and the DB row. `db_fallback` supplies (attachments, mine) for rows
118/// that never hydrated into STATE (a DB load caught them first); `None` keeps
119/// the sweep's contract of skipping ids something else already removed.
120pub(crate) async fn purge_one(id: &str, db_fallback: Option<(Vec<crate::types::Attachment>, bool)>) {
121    let removed = {
122        let mut state = crate::state::STATE.lock().await;
123        state.remove_message(id)
124    };
125    let (attachments, mine, resident_chat) = match removed {
126        Some((chat_id, msg)) => (msg.attachments, msg.mine, Some(chat_id)),
127        None => match db_fallback {
128            Some((attachments, mine)) => (attachments, mine, None),
129            None => return, // already gone (client-side derez or a prior sweep)
130        },
131    };
132
133    if !attachments.is_empty() {
134        // Refcount filter: keep files/blobs a sibling message still points at.
135        let unique = crate::deletion::filter_unreferenced_attachments(id, attachments).await;
136        crate::deletion::delete_cached_attachment_files_pub(&unique);
137
138        // Our own, now-unreferenced blob → wipe it network-side too.
139        if mine {
140            let urls: Vec<String> = unique
141                .iter()
142                .flat_map(|a| a.all_urls().map(str::to_string))
143                .collect();
144            if !urls.is_empty() {
145                if crate::state::nostr_client().is_some() {
146                    if let Ok(signer) = crate::signer::active_signer() {
147                        crate::blossom::delete_blobs_best_effort(signer, urls);
148                    }
149                }
150            }
151        }
152    }
153
154    let _ = crate::db::events::delete_event(id).await;
155
156    // Only a STATE-resident message can be on screen — DB-only rows were
157    // caught before rendering and vanish silently.
158    if let Some(chat_id) = resident_chat {
159        crate::traits::emit_event(
160            "message_removed",
161            &serde_json::json!({ "id": id, "chat_id": chat_id, "reason": "self-destruct" }),
162        );
163    }
164}
165
166/// Drop already-expired messages from a freshly-loaded DB window, purging
167/// their remnants in the background. Rows that expired while the app was
168/// closed (or while their chat was out of STATE) must NEVER render — not
169/// even for the frame between hydration and the next sweep tick.
170pub fn strip_expired(messages: &mut Vec<crate::types::Message>) {
171    let now = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
172        Ok(d) => d.as_secs(),
173        Err(_) => return,
174    };
175    let mut expired: Vec<(String, Vec<crate::types::Attachment>, bool)> = Vec::new();
176    messages.retain(|m| match m.expiration {
177        Some(exp) if exp <= now => {
178            expired.push((m.id.clone(), m.attachments.clone(), m.mine));
179            false
180        }
181        _ => true,
182    });
183    if expired.is_empty() {
184        return;
185    }
186    crate::db::spawn_bound(async move {
187        for (id, attachments, mine) in expired {
188            purge_one(&id, Some((attachments, mine))).await;
189        }
190    });
191}
192
193/// Time until the next sweep: sleep exactly until the soonest pending expiry
194/// (down to a 1s floor) so the final stretch purges in real time, but never
195/// longer than SWEEP_MAX_SECS so a newly-arrived message is noticed promptly.
196fn next_sweep_delay(soonest: Option<u64>) -> std::time::Duration {
197    let now = std::time::SystemTime::now()
198        .duration_since(std::time::UNIX_EPOCH)
199        .map(|d| d.as_secs())
200        .unwrap_or(0);
201    let secs = match soonest {
202        Some(exp) => exp.saturating_sub(now).clamp(1, SWEEP_MAX_SECS),
203        None => SWEEP_MAX_SECS,
204    };
205    std::time::Duration::from_secs(secs)
206}
207
208/// The self-destruct sweep loop: purge, then sleep until the next expiry is due
209/// (adaptive — 1s-tight near a deadline, up to SWEEP_MAX_SECS when idle). The
210/// immediate first pass catches anything that expired while offline. Hosts with
211/// their own async runtime (e.g. Tauri) should spawn this directly.
212pub async fn run_sweeper_loop() {
213    loop {
214        let soonest = sweep_expired().await;
215        tokio::time::sleep(next_sweep_delay(soonest)).await;
216    }
217}
218
219/// Convenience for tokio-native hosts (CLI/SDK): spawn `run_sweeper_loop` once.
220/// Idempotent — a second call is a no-op.
221pub fn start_sweeper() {
222    static STARTED: AtomicBool = AtomicBool::new(false);
223    if STARTED.swap(true, Ordering::AcqRel) {
224        return;
225    }
226    // NOT bound: this loop runs for the process lifetime and must sweep
227    // whichever account is live. Binding would pin it to whoever logged in
228    // first, and every later account would silently stop expiring messages.
229    // spawn-detached: the sweeper must expire messages for whichever account is live; see above.
230    tokio::spawn(run_sweeper_loop());
231}