Skip to main content

vector_core/
inbox_relays.rs

1//! NIP-17 Kind 10050 (DM Relay List) support.
2//!
3//! Fetches, caches, and publishes kind 10050 events so that DM gift wraps
4//! are delivered to the recipient's preferred inbox relays.
5
6use std::collections::{HashMap, HashSet};
7use crate::event_ext::FinalizeOnClock;
8use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
9use std::sync::{Arc, Mutex, Weak};
10use web_time::Instant;
11
12use nostr_sdk::prelude::*;
13use std::sync::LazyLock;
14
15use crate::state::nostr_client;
16use crate::ClientRelayExt;
17
18// ============================================================================
19// Per-relay publish tracker — closes "dependent-event-races-parent" races
20// ============================================================================
21//
22// Vector returns on the first relay ack so the UI can mark a message
23// as "Sent" without waiting for stragglers. Other relays continue
24// receiving the event in the background. Any operation that publishes
25// a *dependent* event referencing the just-sent one (NIP-09 deletion,
26// edit, reaction, reply, …) can race those background publishes: at
27// a relay where the parent hasn't arrived yet, the dependent gets
28// dropped or stored disconnected, and when the parent arrives later
29// it stays without the dependent ever being applied.
30//
31// `EventPublishTracker` exposes a per-relay event stream of "parent
32// successfully published to X". Dependent senders subscribe, drain
33// relays that have already settled, then wait for stragglers and
34// fire their dependent event to each one as soon as it confirms the
35// parent. Every relay that ever received the parent gets the
36// dependent in real time, and the user sees no UX latency on either
37// the parent send or the dependent action.
38//
39// This pattern is generic: deletion is the first consumer, but rapid
40// edits, self-reactions, and replies-to-just-sent all benefit. The
41// tracker doesn't care what the event is or what the dependent
42// operation does — it only knows "this parent landed at this relay".
43
44/// Per-relay publish tracker. One per outbound event whose dependents
45/// (deletions, edits, reactions, replies, ...) need to fire only
46/// after the parent has actually landed at each individual relay.
47pub struct EventPublishTracker {
48    event_id: EventId,
49    /// Successful relays in arrival order. Subscribers walk this with
50    /// a cursor and wait on `notify` for new entries.
51    successes: Mutex<Vec<RelayUrl>>,
52    notify: tokio::sync::Notify,
53    /// Relays still publishing. When this hits 0, the tracker
54    /// removes itself from the global registry and any pending
55    /// `next_success` waiters are woken so they observe end-of-stream.
56    in_flight: AtomicUsize,
57}
58
59impl EventPublishTracker {
60    fn new(event_id: EventId, initial_in_flight: usize) -> Arc<Self> {
61        Arc::new(Self {
62            event_id,
63            successes: Mutex::new(Vec::new()),
64            notify: tokio::sync::Notify::new(),
65            in_flight: AtomicUsize::new(initial_in_flight),
66        })
67    }
68
69    /// Called by a per-relay publish task on success.
70    fn note_success(&self, url: RelayUrl) {
71        self.successes.lock().unwrap().push(url);
72        self.notify.notify_waiters();
73    }
74
75    /// Called by every per-relay task on completion (success OR fail).
76    /// When the last in-flight task settles, drops the tracker from
77    /// the global registry.
78    fn note_settled(&self) {
79        // Registry lock spans the final decrement: idempotent retries
80        // republish the same event id, and a concurrent in_flight bump in
81        // spawn_tracked_publish must not interleave with this removal.
82        let mut trackers = PUBLISH_TRACKERS.lock().unwrap();
83        if self.in_flight.fetch_sub(1, Ordering::SeqCst) == 1 {
84            self.notify.notify_waiters();
85            match trackers.get(&self.event_id) {
86                Some(current) if std::ptr::eq(Arc::as_ptr(current), self) => {
87                    trackers.remove(&self.event_id);
88                }
89                _ => {}
90            }
91        }
92    }
93
94    /// Async iterator over successful relays. Yields each URL once,
95    /// regardless of whether it settled before or after the call.
96    /// Returns `None` when every spawned per-relay task has settled
97    /// AND the cursor has consumed every success — i.e. the dependent
98    /// sender has visited every relay that ever held the parent.
99    pub async fn next_success(&self, cursor: &mut usize) -> Option<RelayUrl> {
100        loop {
101            // Pre-create the notified future BEFORE inspecting state
102            // so a notify_waiters() that fires between the check and
103            // the await doesn't get lost.
104            let notified = self.notify.notified();
105            tokio::pin!(notified);
106            notified.as_mut().enable();
107
108            let (next, done) = {
109                let successes = self.successes.lock().unwrap();
110                let next = successes.get(*cursor).cloned();
111                let done = self.in_flight.load(Ordering::SeqCst) == 0
112                    && *cursor >= successes.len();
113                (next, done)
114            };
115
116            if let Some(url) = next {
117                *cursor += 1;
118                return Some(url);
119            }
120            if done {
121                return None;
122            }
123
124            notified.await;
125        }
126    }
127}
128
129/// Global registry of in-flight tracked publishes. Keyed by event id.
130/// Trackers self-remove once all per-relay tasks settle.
131static PUBLISH_TRACKERS: LazyLock<Mutex<HashMap<EventId, Arc<EventPublishTracker>>>> =
132    LazyLock::new(|| Mutex::new(HashMap::new()));
133
134/// Look up the tracker for an event currently being published.
135/// Returns `None` if the publish has fully settled (all relays done)
136/// or if the tracker never existed (e.g. the event was sent in a
137/// previous app session, or via a non-tracked send path). Dependent
138/// senders fall back to a best-effort broadcast in that case.
139pub fn get_publish_tracker(event_id: &EventId) -> Option<Arc<EventPublishTracker>> {
140    PUBLISH_TRACKERS.lock().unwrap().get(event_id).cloned()
141}
142
143/// Spawn one publish task per resolved relay and register a tracker
144/// keyed by the event id. Returns the join handles so the caller can
145/// race them for first-ok or wait for all to settle as needed. The
146/// spawned tasks continue updating the tracker after the caller
147/// stops waiting on the handles.
148///
149/// Generic primitive — any send path that wants its event referenced
150/// by a future dependent (deletions, edits, reactions, replies)
151/// should publish via this helper so the dependent can later look up
152/// the tracker via `get_publish_tracker(parent_id)`.
153pub fn spawn_tracked_publish(
154    resolved: Vec<(RelayUrl, Relay)>,
155    event: Event,
156) -> Vec<crate::rt::JoinHandle<(RelayUrl, Result<EventId, String>)>> {
157    let event_id = event.id;
158    // Zero relays → zero tasks → nobody ever calls note_settled; a registered tracker
159    // would leak forever.
160    if resolved.is_empty() {
161        return Vec::new();
162    }
163    // Idempotent retries republish the same event id: reuse a still-live
164    // tracker (bump its in_flight) so dependents waiting on it keep seeing
165    // every relay confirmation; register fresh only when none is live.
166    let tracker = {
167        let mut trackers = PUBLISH_TRACKERS.lock().unwrap();
168        match trackers.get(&event_id) {
169            Some(existing) if existing.in_flight.load(Ordering::SeqCst) > 0 => {
170                existing.in_flight.fetch_add(resolved.len(), Ordering::SeqCst);
171                existing.clone()
172            }
173            _ => {
174                let t = EventPublishTracker::new(event_id, resolved.len());
175                trackers.insert(event_id, t.clone());
176                t
177            }
178        }
179    };
180
181    let mut handles = Vec::with_capacity(resolved.len());
182    for (url, relay) in resolved {
183        let event = event.clone();
184        let tracker = tracker.clone();
185        handles.push(crate::db::spawn_bound(async move {
186            // A relay still connecting gets its connect budget on top: the event waits in its
187            // queue until the socket is up.
188            let mut wait = crate::relay_request_timeout(std::time::Duration::from_secs(10));
189            if matches!(relay.status(), RelayStatus::Initialized | RelayStatus::Pending | RelayStatus::Connecting) {
190                wait += crate::relay_connect_timeout(std::time::Duration::from_secs(6));
191            }
192            let result = relay
193                .send_event(&event)
194                .ok_timeout(wait)
195                .authentication_timeout(wait)
196                .await
197                .map(|o| *o.id())
198                .map_err(|e| e.to_string());
199            if result.is_ok() {
200                tracker.note_success(url.clone());
201            }
202            tracker.note_settled();
203            (url, result)
204        }));
205    }
206    handles
207}
208
209// ============================================================================
210// Cache
211// ============================================================================
212
213/// A known list is used whatever its age, so a send never waits on someone looked up before.
214/// Past this it is refreshed in the background (a send, or their chat opening), at most this
215/// often per person.
216const REFRESH_AFTER_SECS: u64 = 3600;
217
218/// A failed lookup with no list to fall back on is asked again after this.
219const CACHE_TTL_ERROR_SECS: u64 = 60;
220
221/// After a send whose every relay refused, the list is asked for again unless it is this fresh.
222const RECHECK_AFTER_SECS: u64 = 300;
223
224#[derive(Clone)]
225struct CachedRelays {
226    relays: Vec<String>,
227    /// Unix seconds.
228    fetched_at: u64,
229    /// Whether the fetch succeeded (true) or failed/timed out (false).
230    fetch_ok: bool,
231    /// The kind 10050's `created_at`; 0 when no list was found.
232    event_at: u64,
233}
234
235impl CachedRelays {
236    fn age(&self) -> u64 {
237        now_secs().saturating_sub(self.fetched_at)
238    }
239
240    /// Served without asking: any list a lookup found, or a failure still fresh.
241    fn usable(&self) -> bool {
242        self.fetch_ok || self.age() < CACHE_TTL_ERROR_SECS
243    }
244
245    fn served(&self) -> FetchResult {
246        FetchResult {
247            relays: self.relays.clone(),
248            fetch_ok: self.fetch_ok,
249            blind: None,
250            cached_at: Some(self.fetched_at),
251            event_at: (self.event_at > 0).then_some(self.event_at),
252        }
253    }
254}
255
256fn now_secs() -> u64 {
257    crate::clock::now_secs()
258}
259
260/// Relay urls as a set, for telling whether two lists name the same relays.
261fn relay_set(relays: &[String]) -> HashSet<String> {
262    relays.iter().map(|r| normalize_relay_url(r)).collect()
263}
264
265/// Recipient-keyed, so technically account-agnostic — but the set of
266/// recipients is a record of who this account has messaged.
267struct InboxRelayCache;
268
269fn inbox_relay_cache() -> Arc<Mutex<HashMap<PublicKey, CachedRelays>>> {
270    crate::db::current_session().scoped::<InboxRelayCache, _>()
271}
272
273/// When each person's list was last asked for, this session: the gate on background refreshes.
274struct InboxRelayAsked;
275
276fn asked_at() -> Arc<Mutex<HashMap<PublicKey, u64>>> {
277    crate::db::current_session().scoped::<InboxRelayAsked, _>()
278}
279
280/// The list known for `pubkey`: in memory, else in the account's database (where only lists a
281/// lookup found are kept, never failures).
282fn cached(pubkey: &PublicKey) -> Option<CachedRelays> {
283    let owner = inbox_relay_cache();
284    if let Some(entry) = owner.lock().unwrap().get(pubkey) {
285        return Some(entry.clone());
286    }
287    let stored = load_stored(pubkey)?;
288    let entry = owner.lock().unwrap().entry(*pubkey).or_insert(stored).clone();
289    Some(entry)
290}
291
292/// Keep what a lookup found. A known list is only ever replaced by a newer revision: a
293/// failure, an older revision, or finding none at all (a struggling network can answer empty)
294/// leaves it, and the next refresh asks again. A blind lookup keeps nothing.
295fn keep(pubkey: &PublicKey, result: &FetchResult) {
296    if result.blind.is_some() {
297        return;
298    }
299    let now = now_secs();
300    asked_at().lock().unwrap().insert(*pubkey, now);
301    let known = cached(pubkey).filter(|e| e.fetch_ok);
302    let next = if !result.fetch_ok {
303        if known.is_some() {
304            return;
305        }
306        CachedRelays { relays: Vec::new(), fetched_at: now, fetch_ok: false, event_at: 0 }
307    } else {
308        match (result.event_at, known) {
309            // An older revision than ours: ours stands, and is confirmed current.
310            (Some(at), Some(k)) if at < k.event_at => CachedRelays { fetched_at: now, ..k },
311            (Some(at), _) => CachedRelays { relays: result.relays.clone(), fetched_at: now, fetch_ok: true, event_at: at },
312            (None, Some(k)) if !k.relays.is_empty() => return,
313            (None, _) => CachedRelays { relays: result.relays.clone(), fetched_at: now, fetch_ok: true, event_at: 0 },
314        }
315    };
316    inbox_relay_cache().lock().unwrap().insert(*pubkey, next.clone());
317    if next.fetch_ok {
318        store(pubkey, &next);
319    }
320}
321
322/// Our own list, as just published or confirmed: self-send copies go where it says now.
323fn keep_own(pubkey: &PublicKey, relays: &[String], event_at: u64) {
324    keep(pubkey, &FetchResult { relays: relays.to_vec(), fetch_ok: true, blind: None, cached_at: None, event_at: Some(event_at) });
325}
326
327/// The persisted lists: per account, so a restart starts warm.
328pub(crate) fn migrate(tx: &rusqlite::Transaction<'_>) -> Result<(), String> {
329    tx.execute_batch(
330        "CREATE TABLE IF NOT EXISTS inbox_relays (
331            pubkey     TEXT    PRIMARY KEY,
332            relays     TEXT    NOT NULL,
333            fetched_at INTEGER NOT NULL
334        );",
335    )
336    .map_err(|e| format!("create inbox_relays: {e}"))
337}
338
339/// Which revision each persisted list is, so an older or empty answer never replaces it.
340pub(crate) fn migrate_event_at(tx: &rusqlite::Transaction<'_>) -> Result<(), String> {
341    tx.execute("ALTER TABLE inbox_relays ADD COLUMN event_at INTEGER NOT NULL DEFAULT 0", [])
342        .map(|_| ())
343        .map_err(|e| format!("add inbox_relays.event_at: {e}"))
344}
345
346fn load_stored(pubkey: &PublicKey) -> Option<CachedRelays> {
347    let conn = crate::db::get_db_connection_guard_static().ok()?;
348    let (relays, fetched_at, event_at): (String, i64, i64) = conn
349        .query_row(
350            "SELECT relays, fetched_at, event_at FROM inbox_relays WHERE pubkey = ?1",
351            [pubkey.to_hex()],
352            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
353        )
354        .ok()?;
355    Some(CachedRelays {
356        relays: serde_json::from_str(&relays).ok()?,
357        // A row written while the clock ran ahead would read as fresh until it caught up.
358        fetched_at: (fetched_at.max(0) as u64).min(now_secs()),
359        fetch_ok: true,
360        event_at: event_at.max(0) as u64,
361    })
362}
363
364fn store(pubkey: &PublicKey, entry: &CachedRelays) {
365    let Ok(conn) = crate::db::get_write_connection_guard_static() else { return };
366    let Ok(json) = serde_json::to_string(&entry.relays) else { return };
367    if let Err(e) = conn.execute(
368        "INSERT INTO inbox_relays (pubkey, relays, fetched_at, event_at) VALUES (?1, ?2, ?3, ?4)
369         ON CONFLICT(pubkey) DO UPDATE SET relays = excluded.relays, fetched_at = excluded.fetched_at, event_at = excluded.event_at",
370        rusqlite::params![pubkey.to_hex(), json, entry.fetched_at as i64, entry.event_at as i64],
371    ) {
372        crate::log_warn!("[InboxRelays] couldn't keep the list for {}: {}", pubkey, e);
373    }
374}
375
376/// A recipient's inbox relays as if just fetched.
377#[cfg(test)]
378pub(crate) fn seed_inbox_relays_for_test(pk: PublicKey, relays: &[&str]) {
379    inbox_relay_cache().lock().unwrap().insert(
380        pk,
381        CachedRelays { relays: relays.iter().map(|s| s.to_string()).collect(), fetched_at: now_secs(), fetch_ok: true, event_at: 1 },
382    );
383}
384
385#[cfg(test)]
386pub(crate) fn is_cached_for_test(pk: &PublicKey) -> bool {
387    inbox_relay_cache().lock().unwrap().contains_key(pk)
388}
389
390/// Per-key locks to prevent cache stampede (thundering herd).
391/// When multiple messages target the same recipient with a cold cache, only the
392/// first fetch runs — others wait on the per-key lock, then hit the cache.
393/// Uses Weak references: the Mutex allocation is freed when Arc refcount drops.
394/// HashMap entries are removed eagerly by a per-call drop guard (normal return,
395/// cancellation, or panic unwind). Periodic retain() remains a fallback safety net.
396static FETCH_LOCKS: LazyLock<Mutex<HashMap<PublicKey, Weak<tokio::sync::Mutex<()>>>>> =
397    LazyLock::new(|| Mutex::new(HashMap::new()));
398
399/// Counter for periodic fallback pruning of dead Weak entries in FETCH_LOCKS.
400/// Prune every PRUNE_INTERVAL cache misses to avoid O(n) scans on every access.
401/// This complements eager per-key cleanup after each completed call.
402static PRUNE_COUNTER: AtomicU64 = AtomicU64::new(0);
403
404/// Prune dead Weak entries every N cache misses. Lower = more CPU for pruning,
405/// higher = more memory for stale entries. 100 is a good balance for production.
406#[cfg(not(test))]
407const PRUNE_INTERVAL: u64 = 100;
408
409/// In tests, prune every access for deterministic behavior (tests rely on
410/// immediate cleanup to verify pruning logic works correctly).
411#[cfg(test)]
412const PRUNE_INTERVAL: u64 = 1;
413
414/// Drop-guard for eager per-key lock-map cleanup.
415/// Runs on normal return and when the future is dropped (e.g. cancellation).
416struct FetchLockEntryCleanup {
417    pubkey: PublicKey,
418    key_lock: Arc<tokio::sync::Mutex<()>>,
419}
420
421impl FetchLockEntryCleanup {
422    fn new(pubkey: PublicKey, key_lock: Arc<tokio::sync::Mutex<()>>) -> Self {
423        Self { pubkey, key_lock }
424    }
425}
426
427impl Drop for FetchLockEntryCleanup {
428    fn drop(&mut self) {
429        let mut locks = match FETCH_LOCKS.lock() {
430            Ok(locks) => locks,
431            Err(_) => return, // fallback retain() handles stale entries later
432        };
433
434        let should_remove = match locks.get(&self.pubkey).and_then(|weak| weak.upgrade()) {
435            Some(current) => {
436                // upgrade() adds one temporary Arc. If strong_count == 2, only:
437                // 1) this drop-guard's Arc, 2) upgrade() temporary Arc.
438                // That means no other in-flight callers still hold this key lock.
439                Arc::ptr_eq(&current, &self.key_lock) && Arc::strong_count(&current) == 2
440            }
441            None => false,
442        };
443        if should_remove {
444            locks.remove(&self.pubkey);
445        }
446    }
447}
448
449// ============================================================================
450// Fetch
451// ============================================================================
452
453/// Canonical string form for relay-url comparison. nostr-sdk canonicalises
454/// differently between published-10050 strings and pool keys (trailing
455/// slashes, default ports, case), so equality checks must go through this.
456pub fn normalize_relay_url(s: &str) -> String {
457    s.trim_end_matches('/').to_ascii_lowercase()
458}
459
460/// Relay-url targets for 10050 traffic: every READ-flagged pool relay plus
461/// any pooled Discovery Relay (GOSSIP-flagged, so invisible to `has_read()`
462/// — matched by url instead). Only urls actually in the pool are returned;
463/// `fetch_events_from`/`send_event_to` error on unknown urls.
464async fn inbox_query_targets(client: &Client) -> Vec<RelayUrl> {
465    let discovery: HashSet<String> = crate::state::discovery_relay_iter()
466        .map(normalize_relay_url)
467        .collect();
468    client
469        .relays().all()
470        .await
471        .iter()
472        .filter(|(url, relay)| {
473            // The READ flag itself: can_read() also counts GOSSIP, which would ask every
474            // Community relay about our npub.
475            relay.capabilities().load().has_any(RelayCapabilities::READ) || discovery.contains(&normalize_relay_url(url.as_str()))
476        })
477        .map(|(url, _)| url.clone())
478        .collect()
479}
480
481/// Why a lookup that found nothing says nothing about the recipient's list.
482#[derive(Clone, Debug, PartialEq, Eq)]
483enum Blind {
484    /// The exit policy keeps some of the relays asked out of reach (I2P-Only).
485    Policy(crate::transport::Refusal),
486    /// The network was down, changed, or failed to reach a relay asked: its words.
487    Network(String),
488}
489
490/// Result of a 10050 fetch: relays found, or whether the fetch itself failed.
491struct FetchResult {
492    relays: Vec<String>,
493    /// `true` if the network request succeeded (even if no events were found).
494    fetch_ok: bool,
495    /// Nothing found while some of the relays asked were out of reach: unknown, not absent,
496    /// so it is never cached or read as "no inbox relays".
497    blind: Option<Blind>,
498    /// When the list served was fetched (unix seconds), or None when it was fetched just now.
499    cached_at: Option<u64>,
500    /// The kind 10050's `created_at`, or None when no list was found.
501    event_at: Option<u64>,
502}
503
504impl FetchResult {
505    #[cfg(test)]
506    fn found(relays: Vec<String>, fetch_ok: bool) -> Self {
507        FetchResult { relays, fetch_ok, blind: None, cached_at: None, event_at: None }
508    }
509}
510
511/// Whether the network kept a lookup from asking its relays: down or switched while it ran, or
512/// a relay asked that isn't up because our side of the connection failed.
513async fn network_blind(client: &Client, targets: &[RelayUrl], started_epoch: u64, usable_at_start: bool) -> Option<String> {
514    if let Some(why) = crate::transport::blocked_reason() {
515        return Some(why);
516    }
517    if !usable_at_start || crate::transport::epoch() != started_epoch {
518        return Some(crate::transport::ConnectError::Stale.text());
519    }
520    let active = crate::transport::host::active()?;
521    let pool = client.relays().all().await;
522    targets.iter().find_map(|url| {
523        let up = pool.get(url).is_some_and(|r| r.status() == RelayStatus::Connected);
524        let (host, _) = crate::transport::host_port(url.as_str())?;
525        let (_, e) = active.last_failure(&host).filter(|_| !up)?;
526        e.is_network().then(|| e.text())
527    })
528}
529
530/// Fetch a pubkey's kind 10050 relay list from the network. Queries the
531/// Discovery Relays alongside our read relays: a recipient on another client
532/// often publishes their list where our own relay set has no overlap.
533async fn fetch_inbox_relays(client: &Client, pubkey: &PublicKey) -> FetchResult {
534    let filter = Filter::new()
535        .author(*pubkey)
536        .kind(Kind::Custom(10050))
537        .limit(1);
538
539    let targets = inbox_query_targets(client).await;
540    let started_epoch = crate::transport::epoch();
541    let usable_at_start = crate::transport::blocked_reason().is_none();
542    let policy = targets
543        .iter()
544        .filter_map(|u| crate::transport::refusal(u.as_str()))
545        .find(|r| *r == crate::transport::Refusal::ExitOff)
546        .map(Blind::Policy);
547    let asked = targets.clone();
548    let fetched = if targets.is_empty() {
549        client
550            .fetch_events(filter).timeout(crate::relay_request_timeout(std::time::Duration::from_secs(5)))
551            .await
552    } else {
553        client
554            .fetch_events(nostr_sdk::prelude::ReqTarget::manual(
555                targets.into_iter().map(|u| (u, vec![filter.clone()])),
556            ))
557            .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(5)))
558            .await
559    };
560    let blind = match policy {
561        Some(p) => Some(p),
562        None => network_blind(client, &asked, started_epoch, usable_at_start).await.map(Blind::Network),
563    };
564    let events = match fetched {
565        Ok(events) => events,
566        Err(e) => {
567            eprintln!("[InboxRelays] Failed to fetch 10050 for {}: {}", pubkey, e);
568            return FetchResult { relays: Vec::new(), fetch_ok: false, blind, cached_at: None, event_at: None };
569        }
570    };
571
572    // Replaceable event: several relays can answer with different revisions —
573    // only the newest is the user's current list.
574    let event = match events.into_iter().max_by_key(|e| e.created_at) {
575        Some(e) => e,
576        None => return FetchResult { relays: Vec::new(), fetch_ok: true, blind, cached_at: None, event_at: None },
577    };
578
579    FetchResult { relays: parse_relay_tags(&event.tags), fetch_ok: true, blind: None, cached_at: None, event_at: Some(event.created_at.as_secs()) }
580}
581
582/// Extract relay URLs from kind 10050 event tags.
583/// Looks for `["relay", "wss://..."]` tag entries.
584fn parse_relay_tags(tags: &Tags) -> Vec<String> {
585    tags.iter()
586        .filter_map(|tag| {
587            let values: Vec<&str> = tag.as_slice().iter().map(|s| s.as_str()).collect();
588            if values.len() >= 2 && values[0] == "relay" {
589                Some(values[1].to_string())
590            } else {
591                None
592            }
593        })
594        .collect()
595}
596
597/// This pubkey's fetch lock, behind a guard that tidies the lock map when it drops.
598fn key_lock(pubkey: &PublicKey) -> FetchLockEntryCleanup {
599    let mut locks = FETCH_LOCKS.lock().unwrap();
600
601    // Periodic cleanup: remove dead Weak entries every PRUNE_INTERVAL accesses.
602    // Avoids O(n) scan in global critical section on every cache miss; instead
603    // amortizes cost to O(n/PRUNE_INTERVAL) per miss under heavy fan-out.
604    if PRUNE_COUNTER.fetch_add(1, Ordering::Relaxed).is_multiple_of(PRUNE_INTERVAL) {
605        locks.retain(|_, weak| Weak::strong_count(weak) > 0);
606    }
607
608    let weak = locks.entry(*pubkey).or_default();
609    let key_lock = match weak.upgrade() {
610        Some(arc) => arc,
611        None => {
612            let new_arc = Arc::new(tokio::sync::Mutex::new(()));
613            *weak = Arc::downgrade(&new_arc);
614            new_arc
615        }
616    };
617    // Wrap lock Arc in drop-guard so map cleanup runs even on cancellation.
618    FetchLockEntryCleanup::new(*pubkey, key_lock)
619}
620
621/// Generic cache-with-lock implementation used by both production and test code.
622/// Any known list is served at once, whatever its age. Otherwise rapid requests for
623/// the same pubkey serialize through a per-key lock, so only one fetch happens.
624/// Different pubkeys never block each other.
625async fn get_or_fetch_with_lock<F, Fut>(pubkey: &PublicKey, fetch_fn: F) -> FetchResult
626where
627    F: FnOnce() -> Fut,
628    Fut: std::future::Future<Output = FetchResult>,
629{
630    if let Some(entry) = cached(pubkey).filter(CachedRelays::usable) {
631        return entry.served();
632    }
633
634    let cleanup_guard = key_lock(pubkey);
635    let result = {
636        let _guard = cleanup_guard.key_lock.lock().await;
637        // Double-check: another task may have filled the cache while we waited.
638        match cached(pubkey).filter(CachedRelays::usable) {
639            Some(entry) => entry.served(),
640            None => {
641                let result = fetch_fn().await;
642                keep(pubkey, &result);
643                result
644            }
645        }
646    };
647    // Explicit drop on normal path. On cancellation/panic unwind this still runs
648    // via Drop when the future is torn down.
649    drop(cleanup_guard);
650    result
651}
652
653/// Get inbox relays for a pubkey: a known list at once, refreshed in the background when old.
654/// Bound to the account it started under, so a swap mid-lookup keeps it in that account.
655async fn get_or_fetch_inbox_relays(client: &Client, pubkey: &PublicKey) -> FetchResult {
656    let result = crate::db::scoped(get_or_fetch_with_lock(pubkey, || fetch_inbox_relays(client, pubkey))).await;
657    if result.fetch_ok && result.cached_at.is_some_and(|at| now_secs().saturating_sub(at) >= REFRESH_AFTER_SECS) {
658        refresh_in_background(*pubkey);
659    }
660    result
661}
662
663/// Look up `pubkey`'s list in the background (their chat opening, a send on an old list), unless
664/// it is under an hour old or was asked for in the last hour.
665pub fn refresh_in_background(pubkey: PublicKey) {
666    if cached(&pubkey).is_some_and(|e| e.fetch_ok && e.age() < REFRESH_AFTER_SECS) {
667        return;
668    }
669    let now = now_secs();
670    {
671        let owner = asked_at();
672        let mut asked = owner.lock().unwrap();
673        if asked.get(&pubkey).is_some_and(|at| now.saturating_sub(*at) < REFRESH_AFTER_SECS) {
674            return;
675        }
676        asked.insert(pubkey, now);
677    }
678    crate::db::spawn_bound(async move {
679        if let Some(client) = nostr_client() {
680            refresh_now(&client, &pubkey, REFRESH_AFTER_SECS).await;
681        }
682    });
683}
684
685/// Ask for `pubkey`'s list past the cache, unless, once its lock is held, it is younger than
686/// `fresh_for` seconds (another lookup just ran).
687async fn refresh_now(client: &Client, pubkey: &PublicKey, fresh_for: u64) {
688    let cleanup_guard = key_lock(pubkey);
689    {
690        let _guard = cleanup_guard.key_lock.lock().await;
691        if !cached(pubkey).is_some_and(|e| e.fetch_ok && e.age() < fresh_for) {
692            let result = fetch_inbox_relays(client, pubkey).await;
693            keep(pubkey, &result);
694        }
695    }
696    drop(cleanup_guard);
697}
698
699/// A send to `pubkey` that its relays refused, on a list the cache served: ask again unless it
700/// was just asked for. True when the list now known names other relays than `tried`, the ones
701/// the send used, so the next attempt goes to those.
702pub async fn recheck_after_failure(client: &Client, pubkey: &PublicKey, tried: &[String]) -> bool {
703    crate::db::scoped(async {
704        refresh_now(client, pubkey, RECHECK_AFTER_SECS).await;
705        list_moved(pubkey, tried)
706    })
707    .await
708}
709
710/// Whether the list known for `pubkey` names other relays than `tried`.
711fn list_moved(pubkey: &PublicKey, tried: &[String]) -> bool {
712    cached(pubkey).is_some_and(|e| e.fetch_ok && relay_set(&e.relays) != relay_set(tried))
713}
714
715// ============================================================================
716// Send helper
717// ============================================================================
718
719/// Send an event to specific relays, returning as soon as the **first** relay
720/// acknowledges success. Remaining relays continue sending in the background.
721///
722/// Uses `spawn_tracked_publish` under the hood, so every event published
723/// here automatically registers an `EventPublishTracker` keyed by event
724/// id. Dependent operations (NIP-09 deletions, edits, reactions, replies)
725/// can look up the tracker via `get_publish_tracker(event_id)` and drive
726/// per-relay dispatch only after each relay confirms the parent — closing
727/// the publish/dependent race for any send that goes through here.
728pub async fn send_event_first_ok(
729    client: &Client,
730    urls: Vec<RelayUrl>,
731    event: &Event,
732) -> Result<nostr_sdk::prelude::SendEventOutput, nostr_sdk::prelude::Error> {
733    let pool = client;
734    let relays = pool.relays().await;
735    let event_id = event.id;
736
737    // Resolve URL -> Relay handles, filtering to relays we actually have
738    let mut resolved: Vec<(RelayUrl, Relay)> = Vec::new();
739    for url in urls {
740        if let Some(relay) = relays.get(&url) {
741            resolved.push((url, relay.clone()));
742        }
743    }
744
745    if resolved.is_empty() {
746        return crate::transport_aware(client.send_event(event)).await;
747    }
748
749    // Spawn tracked per-relay tasks. This registers a tracker so any
750    // future dependent send (deletion, edit, reaction) can fire only
751    // after each relay confirms the parent.
752    let handles = spawn_tracked_publish(resolved, event.clone());
753
754    // Race: return as soon as the first relay succeeds
755    let mut output = Output::new(event_id);
756
757    let mut remaining = handles;
758    while !remaining.is_empty() {
759        let (result, _index, rest) = futures_util::future::select_all(remaining).await;
760        remaining = rest;
761
762        if let Ok((url, relay_result)) = result {
763            match relay_result {
764                Ok(_) => {
765                    output.success.insert(url, nostr_sdk::prelude::EventSendStatus::Sent);
766                    // First success — remaining spawned tasks continue in background
767                    // updating the tracker as they settle. Dropping JoinHandles
768                    // detaches but does NOT cancel them.
769                    drop(remaining);
770                    return Ok(output);
771                }
772                Err(e) => {
773                    output.failed.insert(url, e);
774                }
775            }
776        }
777    }
778
779    // All relays failed — return output so caller can inspect .failed
780    Ok(output)
781}
782
783/// Send an event to all write-relays in the pool, returning as soon as the
784/// **first** relay acknowledges success.
785pub async fn send_event_pool_first_ok(
786    client: &Client,
787    event: &Event,
788) -> Result<nostr_sdk::prelude::SendEventOutput, nostr_sdk::prelude::Error> {
789    let pool = client;
790    let relays = pool.relays().await;
791    let write_urls: Vec<RelayUrl> = relays
792        .iter()
793        .filter(|(_, r)| r.capabilities().load().can_write())
794        .map(|(url, _)| url.clone())
795        .collect();
796    send_event_first_ok(client, write_urls, event).await
797}
798
799/// Build a NIP-59 kind-1059 gift wrap from a sealed event, returning
800/// **both** the signed wrap event and the ephemeral secp256k1 secret
801/// used to sign it.
802///
803/// Wire-compatible with `GiftWrapBuilder` — other
804/// clients cannot tell the wraps apart. The only difference is that we
805/// keep the ephemeral key instead of dropping it on the floor, so the
806/// user can later sign a NIP-09 deletion against the wrap event id and
807/// have relays drop it. This is Vector's "delete from network" primitive.
808pub fn wrap_with_retained_key(
809    receiver: &PublicKey,
810    seal: &Event,
811    extra_tags: impl IntoIterator<Item = Tag>,
812) -> Result<(Event, SecretKey), String> {
813    use nostr_sdk::prelude::nip44;
814
815    if seal.kind != Kind::Seal {
816        return Err(format!("expected Seal kind, got {:?}", seal.kind));
817    }
818    let keys = Keys::generate();
819    let secret = keys.secret_key().clone();
820    let content = nip44::encrypt(
821        keys.secret_key(),
822        receiver,
823        seal.as_json(),
824        nip44::Version::default(),
825    )
826    .map_err(|e| format!("nip44 encrypt: {}", e))?;
827    let mut tags: Vec<Tag> = extra_tags.into_iter().collect();
828    tags.push(Tag::public_key(*receiver));
829    let event = EventBuilder::new(Kind::GiftWrap, content)
830        .tags(tags)
831        .custom_created_at(crate::sending::tweaked_timestamp())
832        .finalize_on_clock(&keys)
833        .map_err(|e| format!("sign wrap: {}", e))?;
834    crate::event_size::check(&event)?;
835    Ok((event, secret))
836}
837
838/// Outcome of a retained-key gift-wrap send. Caller is expected to
839/// persist `wrap_event_id`, `wrap_secret`, and `targeted_relays` for
840/// future deletion.
841pub struct GiftWrapSendOutcome {
842    pub output: nostr_sdk::prelude::SendEventOutput,
843    pub wrap_event_id: EventId,
844    pub wrap_secret: SecretKey,
845    /// Relay URL set we attempted (inbox if known, pool write-relays as
846    /// fallback). Deletion publishes the NIP-09 to this same set.
847    pub targeted_relays: Vec<String>,
848}
849
850/// A gift wrap built once and re-publishable verbatim.
851///
852/// Retries MUST republish these exact bytes rather than re-wrapping:
853/// a relay that already stored the wrap answers the resend with
854/// OK-true "duplicate", so a lost OK becomes a delivery confirmation
855/// on the next attempt instead of an unconfirmed extra copy.
856pub struct BuiltGiftWrap {
857    pub event: Event,
858    pub secret: SecretKey,
859}
860
861/// Seal + wrap a rumor with a retained ephemeral key, without publishing.
862pub async fn build_gift_wrap_retained(
863    _client: &Client,
864    recipient: &PublicKey,
865    rumor: UnsignedEvent,
866    extra_tags: impl IntoIterator<Item = Tag>,
867) -> Result<BuiltGiftWrap, String> {
868    crate::event_size::check_rumor(&rumor)?;
869    let seal = crate::signer::seal_rumor(rumor, recipient).await?;
870    let (event, secret) = wrap_with_retained_key(recipient, &seal, extra_tags)?;
871    Ok(BuiltGiftWrap { event, secret })
872}
873
874/// Resolved publish targets for a gift wrap. Reusable across retry
875/// attempts so transient inbox-relay connections survive the whole
876/// retry window instead of reconnecting per attempt. Callers must
877/// `teardown_gift_wrap_targets` when done — transient inbox relays
878/// belong to the recipient, not our pool.
879pub struct GiftWrapTargets {
880    pub resolved: Vec<(RelayUrl, Relay)>,
881    /// Relay URL set attempted (inbox if known, pool write-relays as
882    /// fallback). Deletion publishes the NIP-09 to this same set.
883    pub targeted_relays: Vec<String>,
884    transient_added: Vec<RelayUrl>,
885    /// The recipient advertised inbox relays and the network in use refuses every one: the
886    /// reason, for a send that must fail rather than land on relays they never read.
887    pub refused: Option<String>,
888    /// The lookup couldn't reach the relays that would list their inbox (the network down,
889    /// switching, or failing): why. No target this time; the next attempt looks again.
890    pub unknown: Option<String>,
891    /// The inbox list came from the cache rather than a lookup just now, so may be out of date.
892    pub from_cache: bool,
893    /// The inbox list this was resolved from, before any relay was refused: what a re-check
894    /// compares against.
895    pub inbox_tried: Vec<String>,
896}
897
898/// Why a recipient whose every inbox relay the network refuses can't be sent to.
899fn inbox_refusal_text(r: crate::transport::Refusal) -> String {
900    use crate::transport::Refusal;
901    match r {
902        Refusal::ExitOff => "I2P-Only is on, so their inbox relays are off.".to_string(),
903        Refusal::WrongNetwork { needs } => format!("Their inbox relays are only reachable over {}.", needs.label()),
904        _ => "None of their inbox relays are reachable on this network.".to_string(),
905    }
906}
907
908/// Why a recipient's inbox relays couldn't be looked up at all.
909fn inbox_lookup_refusal_text(r: crate::transport::Refusal) -> String {
910    match r {
911        crate::transport::Refusal::ExitOff => "I2P-Only is on, so Vector can't find their inbox relays.".to_string(),
912        _ => "Vector can't find their inbox relays on this network.".to_string(),
913    }
914}
915
916/// Send a gift-wrapped rumor to a recipient using a retained ephemeral
917/// key. Routes to the recipient's inbox relays (kind 10050) when
918/// available, falling back to pool write-relays otherwise.
919///
920/// Spawns one publish task per resolved relay and registers a
921/// `EventPublishTracker` keyed by wrap event id so the deletion path
922/// can fire NIP-09 to each relay as soon as that relay confirms the
923/// wrap (closing the publish/delete race for fast deleters). Returns
924/// the wrap event id, the ephemeral secret, and the relay set
925/// attempted.
926pub async fn send_gift_wrap_retained(
927    client: &Client,
928    recipient: &PublicKey,
929    rumor: UnsignedEvent,
930    extra_tags: impl IntoIterator<Item = Tag>,
931) -> Result<GiftWrapSendOutcome, String> {
932    let built = build_gift_wrap_retained(client, recipient, rumor, extra_tags).await?;
933    let mut targets = resolve_gift_wrap_targets(client, recipient).await;
934    // A cached list may be out of date: one the network refuses, or whose every relay refuses
935    // the wrap, is asked for again once, and the same wrap goes to the new list.
936    if targets.refused.is_some()
937        && targets.from_cache
938        && recheck_after_failure(client, recipient, &targets.inbox_tried).await
939    {
940        targets = resolve_gift_wrap_targets(client, recipient).await;
941    }
942    if let Some(why) = targets.refused.clone().or_else(|| targets.unknown.clone()) {
943        return Err(why);
944    }
945    let mut publish_result = publish_gift_wrap_to_targets(client, &targets, &built.event).await;
946    let landed = matches!(&publish_result, Ok(out) if !out.success.is_empty());
947    if !landed && targets.from_cache && recheck_after_failure(client, recipient, &targets.inbox_tried).await {
948        let fresh = resolve_gift_wrap_targets(client, recipient).await;
949        if fresh.refused.is_none() && fresh.unknown.is_none() {
950            teardown_gift_wrap_targets(client, &targets).await;
951            targets = fresh;
952            publish_result = publish_gift_wrap_to_targets(client, &targets, &built.event).await;
953        }
954    }
955    teardown_gift_wrap_targets(client, &targets).await;
956    Ok(GiftWrapSendOutcome {
957        output: publish_result?,
958        wrap_event_id: built.event.id,
959        wrap_secret: built.secret,
960        targeted_relays: targets.targeted_relays,
961    })
962}
963
964/// Resolve where a gift wrap for `recipient` should be published:
965/// their kind-10050 inbox relays when advertised (on-demand connecting
966/// any that are not already pooled, as transient members), otherwise
967/// our pool's write-relays.
968pub async fn resolve_gift_wrap_targets(
969    client: &Client,
970    recipient: &PublicKey,
971) -> GiftWrapTargets {
972    // A refused inbox relay is no target; when every one is refused the send fails with why, since
973    // our own write relays are no fallback for an inbox the recipient named.
974    let mut refusal = None;
975    let lookup = get_or_fetch_inbox_relays(client, recipient).await;
976    let from_cache = lookup.cached_at.is_some();
977    let inbox_tried = lookup.relays.clone();
978    let inbox_strs: Vec<String> = lookup
979        .relays
980        .into_iter()
981        .filter(|s| match crate::transport::refusal(s) {
982            Some(r) => {
983                refusal.get_or_insert(r);
984                false
985            }
986            None => true,
987        })
988        .collect();
989    if inbox_strs.is_empty() {
990        let (refused, unknown) = match (refusal, lookup.blind) {
991            (Some(r), _) => (Some(inbox_refusal_text(r)), None),
992            // Unknown, not absent: the relays they publish on were out of reach.
993            (None, Some(Blind::Policy(r))) => (Some(inbox_lookup_refusal_text(r)), None),
994            (None, Some(Blind::Network(why))) => (None, Some(why)),
995            (None, None) => (None, None),
996        };
997        if refused.is_some() || unknown.is_some() {
998            crate::log_warn!("[InboxRelays] the inbox relays of {} are out of reach on this network", recipient);
999            return GiftWrapTargets {
1000                resolved: Vec::new(),
1001                targeted_relays: Vec::new(),
1002                transient_added: Vec::new(),
1003                refused,
1004                unknown,
1005                from_cache,
1006                inbox_tried,
1007            };
1008        }
1009    }
1010    let targeted_strs: Vec<String> = if !inbox_strs.is_empty() {
1011        inbox_strs.clone()
1012    } else {
1013        let pool = client;
1014        let relays = pool.relays().await;
1015        relays.iter()
1016            .filter(|(_, r)| r.capabilities().load().can_write())
1017            .map(|(url, _)| url.to_string())
1018            .collect()
1019    };
1020    // Resolve to live Relay handles in the pool. Strict HashMap lookup by
1021    // `RelayUrl` was missing visually-identical URLs because nostr-sdk
1022    // canonicalises differently between published-10050 strings and pool
1023    // keys (trailing slashes, default ports, case). Normalise both sides
1024    // and match on the canonical string form so e.g. `wss://relay.damus.io`
1025    // and `wss://relay.damus.io/` count as the same relay.
1026    use normalize_relay_url as normalize_url_for_match;
1027    let pool = client;
1028    // all_relays(): GOSSIP-flagged pool members (discovery/community relays)
1029    // must count as pooled here — classifying one as transient would remove
1030    // it from the pool after the send, silently killing its real role.
1031    let pool_relays = pool.relays().all().await;
1032    let pool_norm: Vec<(String, RelayUrl, Relay)> = pool_relays.iter()
1033        .map(|(url, relay)| (
1034            normalize_url_for_match(&url.to_string()),
1035            url.clone(),
1036            relay.clone(),
1037        ))
1038        .collect();
1039    let mut resolved: Vec<(RelayUrl, Relay)> = targeted_strs
1040        .iter()
1041        .filter_map(|s| {
1042            let norm = normalize_url_for_match(s);
1043            pool_norm.iter()
1044                .find(|(pnorm, _, _)| pnorm == &norm)
1045                .map(|(_, url, relay)| (url.clone(), relay.clone()))
1046        })
1047        .collect();
1048
1049    // On-demand connect: inbox relays not already in the pool are added +
1050    // connected just for this send, then removed afterwards (transient_added).
1051    // The recipient's inbox relays are theirs, not ours — keeping them would
1052    // pollute the pool, which the reconcile loop owns. Only for real inbox
1053    // relays; the pool-write fallback already targets live pool members.
1054    // Not awaited: the publish queues on a relay still connecting, so a pooled target answers
1055    // first instead of every slow inbox being waited on in turn.
1056    let mut transient_added: Vec<RelayUrl> = Vec::new();
1057    if !inbox_strs.is_empty() {
1058        for s in &targeted_strs {
1059            let norm = normalize_url_for_match(s);
1060            let in_pool = pool_norm.iter().any(|(p, _, _)| p == &norm);
1061            let already_added = transient_added.iter()
1062                .any(|u| normalize_url_for_match(&u.to_string()) == norm);
1063            if in_pool || already_added { continue; }
1064            // Write-only: someone else's inbox carries this send and nothing else. Read
1065            // capability would put our own subscriptions on it, and count it as ours.
1066            if pool.add_managed_relay(s.as_str()).capabilities(nostr_sdk::prelude::RelayCapabilities::WRITE).await.is_ok() {
1067                if let Ok(Some(relay)) = pool.relay(s.as_str()).await {
1068                    relay.connect();
1069                    transient_added.push(relay.url().clone());
1070                    resolved.push((relay.url().clone(), relay));
1071                }
1072            }
1073        }
1074        if !transient_added.is_empty() {
1075            crate::log_info!(
1076                "[InboxRelays] on-demand connected {} inbox relay(s) for {} (transient)",
1077                transient_added.len(),
1078                recipient,
1079            );
1080        }
1081    }
1082
1083    if !inbox_strs.is_empty() {
1084        crate::log_info!(
1085            "[InboxRelays] Routing gift-wrap to {} inbox relays for {}",
1086            resolved.len(),
1087            recipient
1088        );
1089    }
1090
1091    GiftWrapTargets {
1092        resolved,
1093        targeted_relays: targeted_strs,
1094        transient_added,
1095        refused: None,
1096        unknown: None,
1097        from_cache,
1098        inbox_tried,
1099    }
1100}
1101
1102/// Nudge any non-connected target relay back up before a retry attempt.
1103/// Transient inbox relays are added with `reconnect(false)`, so a drop
1104/// mid-retry-window would otherwise leave them dead for every remaining
1105/// attempt.
1106pub async fn reconnect_gift_wrap_targets(targets: &GiftWrapTargets) {
1107    let stale: Vec<&Relay> = targets.resolved.iter()
1108        .filter(|(_, r)| r.status() != RelayStatus::Connected)
1109        .map(|(_, r)| r)
1110        .collect();
1111    if stale.is_empty() {
1112        return;
1113    }
1114    // TryConnect is IntoFuture, not Future, so join_all needs it awaited inside.
1115    futures_util::future::join_all(stale.into_iter().map(|r| async move {
1116        r.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(6))).await
1117    }))
1118    .await;
1119}
1120
1121/// Publish an already-built wrap to resolved targets, racing for the
1122/// first relay OK. Safe to call repeatedly with the same event —
1123/// relays that already stored it acknowledge the duplicate.
1124///
1125/// Spawns tracked per-relay publish tasks: the tracker is keyed by
1126/// the wrap event id; the deletion path looks it up via
1127/// get_publish_tracker(wrap_event_id) and walks next_success() to
1128/// fire NIP-09 only at relays that have actually received the
1129/// wrap. The same primitive is used by any other operation whose
1130/// dependent event must arrive after the parent on each relay
1131/// (rapid edits, self-reactions, replies-to-just-sent).
1132pub async fn publish_gift_wrap_to_targets(
1133    client: &Client,
1134    targets: &GiftWrapTargets,
1135    event: &Event,
1136) -> Result<nostr_sdk::prelude::SendEventOutput, String> {
1137    if let Some(why) = targets.refused.as_ref().or(targets.unknown.as_ref()) {
1138        return Err(why.clone());
1139    }
1140    // `resolved.is_empty()` implies no transient add succeeded (each success
1141    // pushes onto `resolved`), so this branch can't leak a transient relay.
1142    if targets.resolved.is_empty() {
1143        // No matching relays in the pool — last-ditch broadcast via
1144        // client.send_event(). No tracker (no per-relay machinery).
1145        return crate::transport_aware(client.send_event(event))
1146            .await
1147            .map_err(|e| e.to_string());
1148    }
1149
1150    let handles = spawn_tracked_publish(targets.resolved.clone(), event.clone());
1151
1152    // Race for first-ok so the caller (and UI) sees "Sent" the
1153    // moment any one relay accepts. Remaining tasks continue in
1154    // the background, updating the tracker as they settle. The
1155    // dropped JoinHandles detach but do not cancel the tasks.
1156    let mut output = Output::new(event.id);
1157    let mut remaining = handles;
1158    while !remaining.is_empty() {
1159        let (result, _idx, rest) = futures_util::future::select_all(remaining).await;
1160        remaining = rest;
1161        if let Ok((url, relay_result)) = result {
1162            match relay_result {
1163                Ok(_) => {
1164                    output.success.insert(url, nostr_sdk::prelude::EventSendStatus::Sent);
1165                    drop(remaining);
1166                    break;
1167                }
1168                Err(e) => {
1169                    output.failed.insert(url, e.to_string());
1170                }
1171            }
1172        }
1173    }
1174    Ok(output)
1175}
1176
1177/// Tear down transiently-added inbox relays — they belong to the
1178/// recipient, not us. Delivery has already raced to first-ok; one
1179/// confirmed inbox relay satisfies NIP-17, so cutting any still-in-flight
1180/// background publishes to the others is acceptable.
1181pub async fn teardown_gift_wrap_targets(client: &Client, targets: &GiftWrapTargets) {
1182    let pool = client;
1183    for url in &targets.transient_added {
1184        let _ = pool.remove_relay(url).await;
1185    }
1186}
1187
1188/// Send a gift-wrapped rumor to a recipient, routing to their inbox relays
1189/// (kind 10050) when available. Falls back to pool broadcast if no inbox
1190/// relays are found or if targeted delivery fails entirely.
1191///
1192/// Returns as soon as the first relay acknowledges success — remaining relays
1193/// continue in the background. This minimises the time messages spend in
1194/// "pending" state.
1195///
1196/// Thin wrapper over `send_gift_wrap_retained`. Discards the retained
1197/// ephemeral key — use this for sends where future deletion is not
1198/// required (e.g. PIVX payment rumors). For user-facing DMs, prefer
1199/// `send_gift_wrap_retained` and persist the secret.
1200pub async fn send_gift_wrap(
1201    client: &Client,
1202    recipient: &PublicKey,
1203    rumor: UnsignedEvent,
1204    extra_tags: impl IntoIterator<Item = Tag>,
1205) -> Result<nostr_sdk::prelude::SendEventOutput, String> {
1206    let outcome = send_gift_wrap_retained(client, recipient, rumor, extra_tags).await?;
1207    Ok(outcome.output)
1208}
1209
1210// ============================================================================
1211// Publish own inbox relays (sync-first, merge, never clobber)
1212// ============================================================================
1213
1214/// KV key holding the relay urls Vector itself contributed to the published
1215/// kind 10050 (JSON array, normalized). Foreign entries (added by other
1216/// clients) are everything in the network list minus this set — they are
1217/// preserved verbatim on every publish and never removed by a Vector config
1218/// change.
1219const CONTRIBUTED_KEY: &str = "dm_relays_contributed";
1220
1221/// Cap on foreign relay entries adopted into our published list. Bounds a
1222/// hostile or bloated remote list from being re-signed and amplified by us.
1223const MAX_FOREIGN_RELAYS: usize = 10;
1224
1225fn load_contributed() -> HashSet<String> {
1226    crate::db::get_sql_setting(CONTRIBUTED_KEY.to_string())
1227        .ok()
1228        .flatten()
1229        .and_then(|json| serde_json::from_str::<Vec<String>>(&json).ok())
1230        .map(|v| v.into_iter().map(|s| normalize_relay_url(&s)).collect())
1231        .unwrap_or_default()
1232}
1233
1234fn store_contributed(contributed: &[String]) {
1235    if let Ok(json) = serde_json::to_string(contributed) {
1236        let _ = crate::db::set_sql_setting(CONTRIBUTED_KEY.to_string(), json);
1237    }
1238}
1239
1240/// The merged list to publish and whether the network needs updating.
1241struct MergePlan {
1242    /// Final relay list, original string forms preserved (remote order first,
1243    /// then our additions).
1244    list: Vec<String>,
1245    /// `true` if the final list differs (as a set) from the remote list.
1246    changed: bool,
1247    /// Normalized urls that count as Vector's contribution going forward:
1248    /// our current read relays minus anything another client also lists.
1249    contributed: Vec<String>,
1250}
1251
1252/// Merge the network's current 10050 with our read relays. Foreign entries
1253/// (remote minus our previous contribution) always survive; entries we
1254/// contributed earlier but no longer read are dropped — a relay removed in
1255/// Vector's settings leaves the list, a relay added by another app never does.
1256fn merge_inbox_relays(
1257    remote: &[String],
1258    contributed_before: &HashSet<String>,
1259    ours: &[String],
1260) -> MergePlan {
1261    let mut seen: HashSet<String> = HashSet::new();
1262    let mut list: Vec<String> = Vec::new();
1263    let mut foreign_norm: HashSet<String> = HashSet::new();
1264    let mut dropped_foreign = 0usize;
1265
1266    for url in remote {
1267        let norm = normalize_relay_url(url);
1268        if seen.contains(&norm) || contributed_before.contains(&norm) {
1269            continue;
1270        }
1271        if foreign_norm.len() >= MAX_FOREIGN_RELAYS {
1272            dropped_foreign += 1;
1273            continue;
1274        }
1275        seen.insert(norm.clone());
1276        foreign_norm.insert(norm);
1277        list.push(url.clone());
1278    }
1279    if dropped_foreign > 0 {
1280        crate::log_warn!(
1281            "[InboxRelays] remote 10050 over the {}-relay foreign cap, dropped {}",
1282            MAX_FOREIGN_RELAYS,
1283            dropped_foreign
1284        );
1285    }
1286
1287    let mut contributed: Vec<String> = Vec::new();
1288    for url in ours {
1289        let norm = normalize_relay_url(url);
1290        if seen.insert(norm.clone()) {
1291            list.push(url.clone());
1292        }
1293        if !foreign_norm.contains(&norm) && !contributed.contains(&norm) {
1294            contributed.push(norm);
1295        }
1296    }
1297
1298    // Publish only on an OWN diff: something of ours missing from the remote
1299    // list, or a previous contribution of ours still listed that we no longer
1300    // read. A foreign-cap trim alone must never drive a publish — two devices
1301    // straddling the cap would ping-pong trimmed/untrimmed lists forever.
1302    let remote_set: HashSet<String> = remote.iter().map(|s| normalize_relay_url(s)).collect();
1303    let ours_norm: HashSet<String> = ours.iter().map(|s| normalize_relay_url(s)).collect();
1304    let has_addition = ours_norm.iter().any(|n| !remote_set.contains(n));
1305    let has_removal = contributed_before
1306        .iter()
1307        .any(|n| remote_set.contains(n) && !ours_norm.contains(n));
1308    MergePlan { list, changed: has_addition || has_removal, contributed }
1309}
1310
1311/// Most outbox relays joined for one look at our own list.
1312const OUTBOX_LOOKUP_CAP: usize = 8;
1313
1314/// Our 10050 from the relays our kind 10002 names that the first pass did not ask, each joined
1315/// just for this read and dropped after. `Ok(None)` only when one of them answered without it.
1316async fn fetch_from_outbox(
1317    client: &Client,
1318    filter: &Filter,
1319    relay_list: &Event,
1320    asked: &[RelayUrl],
1321) -> Result<Option<(Vec<String>, u64)>, String> {
1322    let asked: HashSet<String> = asked.iter().map(|u| normalize_relay_url(u.as_str())).collect();
1323    let mut wanted: Vec<RelayUrl> = Vec::new();
1324    for (url, _) in nip65::extract_relay_list(relay_list) {
1325        let norm = normalize_relay_url(url.as_str());
1326        if !asked.contains(&norm) && !wanted.iter().any(|u| normalize_relay_url(u.as_str()) == norm) {
1327            wanted.push(url.clone());
1328        }
1329    }
1330    wanted.truncate(OUTBOX_LOOKUP_CAP);
1331    if wanted.is_empty() {
1332        return Ok(None);
1333    }
1334
1335    let pooled: HashSet<String> = client.relays().all().await.keys().map(|u| normalize_relay_url(u.as_str())).collect();
1336    let mut added: Vec<RelayUrl> = Vec::new();
1337    for url in &wanted {
1338        if pooled.contains(&normalize_relay_url(url.as_str())) {
1339            continue;
1340        }
1341        // GOSSIP: reachable by this targeted read, invisible to pool-wide DM and profile ops.
1342        if client.add_managed_relay(url.as_str()).capabilities(crate::community_relay_capabilities()).await.is_ok() {
1343            if let Ok(Some(relay)) = client.relay(url.as_str()).await {
1344                relay.connect();
1345                added.push(relay.url().clone());
1346            }
1347        }
1348    }
1349
1350    let found = async {
1351        let deadline = Instant::now() + crate::relay_connect_timeout(std::time::Duration::from_secs(6));
1352        let live: Vec<RelayUrl> = loop {
1353            let relays = client.relays().all().await;
1354            let live: Vec<RelayUrl> = wanted
1355                .iter()
1356                .filter_map(|u| relays.iter().find(|(p, _)| normalize_relay_url(p.as_str()) == normalize_relay_url(u.as_str())))
1357                .filter(|(_, r)| r.status() == RelayStatus::Connected)
1358                .map(|(p, _)| p.clone())
1359                .collect();
1360            if live.len() == wanted.len() || Instant::now() >= deadline {
1361                break live;
1362            }
1363            crate::rt::time::sleep(std::time::Duration::from_millis(250)).await;
1364        };
1365        if live.is_empty() {
1366            return Err("no 10050 found and none of our outbox relays reachable; refusing to bootstrap".to_string());
1367        }
1368        let budget = crate::relay_request_timeout(std::time::Duration::from_secs(6));
1369        let asked = Instant::now();
1370        let events = client
1371            .fetch_events(nostr_sdk::prelude::ReqTarget::manual(live.into_iter().map(|u| (u, vec![filter.clone()]))))
1372            .timeout(budget)
1373            .await
1374            .map_err(|e| e.to_string())?;
1375        let newest = events
1376            .into_iter()
1377            .max_by(|a, b| a.created_at.cmp(&b.created_at).then(b.id.cmp(&a.id)))
1378            .map(|e| (parse_relay_tags(&e.tags), e.created_at.as_secs()));
1379        if newest.is_none() && asked.elapsed() >= budget {
1380            return Err("no 10050 found before an outbox relay answered; refusing to bootstrap".to_string());
1381        }
1382        Ok(newest)
1383    }
1384    .await;
1385
1386    for url in &added {
1387        let _ = client.remove_relay(url).await;
1388    }
1389    found
1390}
1391
1392/// Fetch our OWN current 10050 from read + Discovery relays, with its
1393/// created_at. `Ok(None)` means the network answered and no list exists;
1394/// `Err` means we could not get a trustworthy answer (offline, nothing
1395/// connected) — callers must NOT publish on `Err`, that is exactly the blind
1396/// overwrite this module exists to stop.
1397pub async fn fetch_own_inbox_list(client: &Client) -> Result<Option<(Vec<String>, u64)>, String> {
1398    let me = crate::state::my_public_key().ok_or("no active pubkey")?;
1399    let targets = inbox_query_targets(client).await;
1400    if targets.is_empty() {
1401        return Err("no query targets in pool".to_string());
1402    }
1403
1404    // Wait (bounded) for targets to be live: a fetch raced against boot-time
1405    // connection setup returns empty, which reads as "no list exists" and
1406    // triggers a bootstrap publish over a list we simply couldn't see yet.
1407    // Every Discovery Relay gets the deadline, not just the first: the first up
1408    // may hold no copy, and its empty answer alone would read as "no list".
1409    // Any connected target at the deadline is best-effort; zero aborts the sync.
1410    let discovery: HashSet<String> = crate::state::discovery_relay_iter()
1411        .map(normalize_relay_url)
1412        .collect();
1413    let deadline = Instant::now() + crate::relay_connect_timeout(std::time::Duration::from_secs(8));
1414    loop {
1415        let (any_up, discovery_waiting) = {
1416            let relays = client.relays().all().await;
1417            let mut any_up = false;
1418            let mut discovery_waiting = false;
1419            for url in &targets {
1420                let up = relays.get(url).is_some_and(|r| r.status() == RelayStatus::Connected);
1421                any_up |= up;
1422                discovery_waiting |= !up && discovery.contains(&normalize_relay_url(url.as_str()));
1423            }
1424            (any_up, discovery_waiting)
1425        };
1426        if any_up && !discovery_waiting {
1427            break;
1428        }
1429        if Instant::now() >= deadline {
1430            if !any_up {
1431                return Err("no query target connected".to_string());
1432            }
1433            break;
1434        }
1435        crate::rt::time::sleep(std::time::Duration::from_millis(250)).await;
1436    }
1437
1438    let filter = Filter::new().author(me).kind(Kind::Custom(10050)).limit(1);
1439    let outbox = Filter::new().author(me).kind(Kind::RelayList).limit(1);
1440    let budget = crate::relay_request_timeout(std::time::Duration::from_secs(6));
1441    // Ask only live sockets, so a timeout below means a connected relay went quiet, not that
1442    // one target was down.
1443    let pool = client.relays().all().await;
1444    let live: Vec<RelayUrl> = targets
1445        .iter()
1446        .filter(|url| pool.get(*url).is_some_and(|r| r.status() == RelayStatus::Connected))
1447        .cloned()
1448        .collect();
1449    drop(pool);
1450    let asked = Instant::now();
1451    let events = client
1452        .fetch_events(nostr_sdk::prelude::ReqTarget::manual(
1453            live.iter().cloned().map(|u| (u, vec![filter.clone(), outbox.clone()])),
1454        ))
1455        .timeout(budget)
1456        .await
1457        .map_err(|e| e.to_string())?;
1458    // A fetch that ran its whole budget returns whatever arrived: some target never answered.
1459    let timed_out = asked.elapsed() >= budget;
1460    let (lists, relay_lists): (Vec<Event>, Vec<Event>) =
1461        events.into_iter().partition(|e| e.kind == Kind::Custom(10050));
1462    // NIP-01 replaceable tie-break: newest created_at, lowest id on a tie.
1463    let mut newest = lists
1464        .into_iter()
1465        .max_by(|a, b| a.created_at.cmp(&b.created_at).then(b.id.cmp(&a.id)))
1466        .map(|e| (parse_relay_tags(&e.tags), e.created_at.as_secs()));
1467
1468    // A client that writes only to the account's outbox leaves the list where neither our pool
1469    // nor a Discovery Relay looks: ask the relays its kind 10002 names before calling it absent.
1470    if newest.is_none() && !timed_out {
1471        if let Some(relay_list) = relay_lists.iter().max_by_key(|e| e.created_at) {
1472            newest = fetch_from_outbox(client, &filter, relay_list, &live).await?;
1473        }
1474    }
1475
1476    // "No list found" is only trustworthy when a Discovery Relay answered:
1477    // a list curated elsewhere may live on none of our own relays, and a
1478    // bootstrap publish over an unseen list is a PERMANENT clobber (the
1479    // bootstrap gets the newer created_at, so later syncs adopt it and
1480    // relays delete the old list). Pools with no Discovery Relay at all
1481    // (SDK/CLI) keep the any-target answer.
1482    if newest.is_none() && timed_out {
1483        return Err("no 10050 found before a relay answered; refusing to bootstrap".to_string());
1484    }
1485    if newest.is_none() {
1486        let has_discovery_target = targets
1487            .iter()
1488            .any(|url| discovery.contains(&normalize_relay_url(url.as_str())));
1489        if has_discovery_target {
1490            let relays = client.relays().all().await;
1491            let discovery_answered = targets.iter().any(|url| {
1492                discovery.contains(&normalize_relay_url(url.as_str()))
1493                    && relays
1494                        .get(url)
1495                        .map(|r| r.status() == RelayStatus::Connected)
1496                        .unwrap_or(false)
1497            });
1498            if !discovery_answered {
1499                return Err(
1500                    "no 10050 found and no Discovery Relay connected; refusing to bootstrap"
1501                        .to_string(),
1502                );
1503            }
1504        }
1505    }
1506    Ok(newest)
1507}
1508
1509/// KV key holding the created_at of the newest 10050 we have published or
1510/// applied locally. Inbound reconcile actions are gated on a STRICTLY newer
1511/// remote event: acting on a stale fetch would resurrect relays the user
1512/// already retired.
1513const LIST_SEEN_TS_KEY: &str = "dm_list_last_ts";
1514
1515fn load_list_seen() -> u64 {
1516    crate::db::get_sql_setting(LIST_SEEN_TS_KEY.to_string())
1517        .ok()
1518        .flatten()
1519        .and_then(|v| v.parse::<u64>().ok())
1520        .unwrap_or(0)
1521}
1522
1523/// Union urls into the contributed set. Adopted/revived relays must count as
1524/// OUR contribution immediately: retire only fires for contributed entries,
1525/// and a merge would otherwise re-add ("resurrect") a relay that a newer
1526/// remote list deliberately dropped.
1527pub fn note_contributed(urls: &[String]) {
1528    if urls.is_empty() {
1529        return;
1530    }
1531    let mut set = load_contributed();
1532    for url in urls {
1533        set.insert(normalize_relay_url(url));
1534    }
1535    let list: Vec<String> = set.into_iter().collect();
1536    store_contributed(&list);
1537}
1538
1539/// Advance the list-freshness anchor (monotonic).
1540pub fn note_list_seen(ts: u64) {
1541    if ts > load_list_seen() {
1542        let _ = crate::db::set_sql_setting(LIST_SEEN_TS_KEY.to_string(), ts.to_string());
1543    }
1544}
1545
1546/// Local actions needed to make the in-app relay list mirror a newer remote
1547/// 10050 (the Relays tab IS the DM Relay List, synced across devices/apps).
1548#[derive(Debug, Default, PartialEq)]
1549pub struct InboundReconcile {
1550    /// Remote entries unknown locally: add as enabled relays.
1551    pub adopt: Vec<String>,
1552    /// Locally-disabled entries a newer remote (re-)lists: re-enable.
1553    pub revive: Vec<String>,
1554    /// Entries we previously published that a newer remote dropped: another
1555    /// client removed them, disable locally.
1556    pub retire: Vec<String>,
1557}
1558
1559/// Plan the inbound half of the sync. `ours` = locally enabled relay urls,
1560/// `declined` = locally known but disabled urls. Reads the contributed set
1561/// and freshness anchor from the account KV.
1562pub fn plan_inbound_reconcile(
1563    remote: &[String],
1564    remote_ts: u64,
1565    ours: &[String],
1566    declined: &[String],
1567) -> InboundReconcile {
1568    plan_inbound_reconcile_pure(
1569        remote,
1570        remote_ts,
1571        ours,
1572        declined,
1573        &load_contributed(),
1574        load_list_seen(),
1575    )
1576}
1577
1578fn plan_inbound_reconcile_pure(
1579    remote: &[String],
1580    remote_ts: u64,
1581    ours: &[String],
1582    declined: &[String],
1583    contributed_before: &HashSet<String>,
1584    last_seen_ts: u64,
1585) -> InboundReconcile {
1586    if remote_ts <= last_seen_ts {
1587        return InboundReconcile::default();
1588    }
1589    let ours_norm: HashSet<String> = ours.iter().map(|s| normalize_relay_url(s)).collect();
1590    let declined_norm: HashSet<String> = declined.iter().map(|s| normalize_relay_url(s)).collect();
1591    let remote_norm: HashSet<String> = remote.iter().map(|s| normalize_relay_url(s)).collect();
1592
1593    let mut seen: HashSet<String> = HashSet::new();
1594    let mut adopt: Vec<String> = Vec::new();
1595    let mut revive: Vec<String> = Vec::new();
1596    for url in remote {
1597        let norm = normalize_relay_url(url);
1598        if !seen.insert(norm.clone()) {
1599            continue;
1600        }
1601        if ours_norm.contains(&norm) {
1602            continue;
1603        }
1604        if declined_norm.contains(&norm) {
1605            revive.push(url.clone());
1606        } else if adopt.len() < MAX_FOREIGN_RELAYS
1607            && crate::transport::validate_relay_url(url).is_ok()
1608            && url.len() <= 256
1609        {
1610            adopt.push(url.clone());
1611        }
1612    }
1613
1614    let retire: Vec<String> = ours
1615        .iter()
1616        .filter(|url| {
1617            let norm = normalize_relay_url(url);
1618            contributed_before.contains(&norm) && !remote_norm.contains(&norm)
1619        })
1620        .cloned()
1621        .collect();
1622
1623    InboundReconcile { adopt, revive, retire }
1624}
1625
1626/// Serializes publish_inbox_relays bodies. Overlapping runs (boot spawn vs a
1627/// debounced republish) can sign in inverted order — the stale list gets the
1628/// newer created_at and its stale contributed-set lands last in the KV.
1629static PUBLISH_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
1630
1631/// Sync our kind 10050 from the network, merge our readable relays into it,
1632/// and publish ONLY if that changes the list. Lists curated in other clients
1633/// are preserved: foreign entries are re-signed verbatim, never dropped.
1634/// Publishes to our write relays AND the Discovery Relays so the result is
1635/// findable by clients with no relay overlap.
1636pub async fn publish_inbox_relays(client: &Client) -> Result<(), String> {
1637    // A failed sync must skip the publish: publishing blind clobbers lists
1638    // curated in other clients.
1639    let remote = fetch_own_inbox_list(client).await?;
1640    publish_inbox_relays_synced(client, remote, None).await
1641}
1642
1643/// Publish with an already-synced remote list (avoids a second network fetch
1644/// when the caller just ran the inbound reconcile). `ours_override` supplies
1645/// the caller's store-derived relay list: the live pool momentarily contains
1646/// relays that are not ours (a recipient's transient inbox relays mid-DM) and
1647/// can be missing ours (an adopted relay whose connect failed) — publishing
1648/// pool state would leak the former fleet-wide and oscillate the latter.
1649pub async fn publish_inbox_relays_synced(
1650    client: &Client,
1651    remote: Option<(Vec<String>, u64)>,
1652    ours_override: Option<Vec<String>>,
1653) -> Result<(), String> {
1654    let _serial = PUBLISH_MUTEX.lock().await;
1655    let session = crate::db::current_session();
1656
1657    // Relays we read from — senders must write to these for us to receive DMs.
1658    let ours: Vec<String> = match ours_override {
1659        Some(list) => list,
1660        None => client
1661            .relays()
1662            .await
1663            .iter()
1664            .filter(|(_, relay)| relay.capabilities().load().can_read())
1665            .map(|(url, _)| url.to_string())
1666            .collect(),
1667    };
1668
1669    let remote_found = remote.is_some();
1670    let (remote, remote_ts) = remote.unwrap_or_default();
1671    // A fetch can answer with an OLDER revision than one we've already seen
1672    // (the relay holding the newest missed the timeout). Merging against it
1673    // would republish removed-elsewhere entries at a newer created_at —
1674    // resurrection the inbound gate cannot defend against.
1675    if remote_found && remote_ts < load_list_seen() {
1676        return Err("stale 10050 fetch (older than last seen), skipping publish".to_string());
1677    }
1678
1679    let plan = merge_inbox_relays(&remote, &load_contributed(), &ours);
1680
1681    if !session.is_live() {
1682        return Ok(());
1683    }
1684    store_contributed(&plan.contributed);
1685    if remote_found {
1686        note_list_seen(remote_ts);
1687    }
1688
1689    // Our own copies (self-sends) go where the list says now, not where the cache last saw it.
1690    if remote_found && !plan.changed {
1691        if let Some(me) = crate::state::my_public_key() {
1692            keep_own(&me, &remote, remote_ts);
1693        }
1694        crate::log_info!(
1695            "[InboxRelays] kind 10050 already in sync ({} relay(s)), not publishing",
1696            plan.list.len()
1697        );
1698        return Ok(());
1699    }
1700    if plan.list.is_empty() && !remote_found {
1701        // Nothing to say and nothing to update.
1702        return Ok(());
1703    }
1704
1705    let mut builder = EventBuilder::new(Kind::Custom(10050), "");
1706    for url in &plan.list {
1707        builder = builder.tag(Tag::custom("relay", vec![url.clone()]));
1708    }
1709    let event = crate::sign_builder(builder)
1710        .await
1711        .map_err(|e| format!("Failed to sign inbox relays: {}", e))?;
1712
1713    if !session.is_live() {
1714        return Ok(());
1715    }
1716    let pool_send = crate::transport_aware(client.send_event(&event)).await;
1717
1718    // Copy to the pooled Discovery Relays (GOSSIP-flagged, so the pool-wide
1719    // send skipped them). Runs regardless of the pool send: a user with zero
1720    // write relays still gets their list onto the rendezvous points.
1721    let discovery: HashSet<String> = crate::state::DISCOVERY_RELAYS
1722        .iter()
1723        .map(|s| normalize_relay_url(s))
1724        .collect();
1725    let discovery_targets: Vec<RelayUrl> = client
1726        .relays().all()
1727        .await
1728        .iter()
1729        .filter(|(url, relay)| {
1730            // The WRITE flag itself: can_write() also counts GOSSIP, which every Discovery Relay has.
1731            !relay.capabilities().load().has_any(RelayCapabilities::WRITE) && discovery.contains(&normalize_relay_url(url.as_str()))
1732        })
1733        .map(|(url, _)| url.clone())
1734        .collect();
1735    let mut discovery_ok = false;
1736    if !discovery_targets.is_empty() {
1737        if let Ok(out) = crate::transport_aware(client.send_event(&event)).to(discovery_targets).await {
1738            discovery_ok = !out.success.is_empty();
1739        }
1740    }
1741
1742    let pool_ok = matches!(&pool_send, Ok(out) if !out.success.is_empty());
1743    if !pool_ok {
1744        if !discovery_ok {
1745            return Err(match pool_send {
1746                Err(e) => format!("Failed to publish inbox relays: {}", e),
1747                Ok(_) => "Failed to publish inbox relays: no relay accepted it".to_string(),
1748            });
1749        }
1750        crate::log_warn!(
1751            "[InboxRelays] pool publish failed, list delivered via Discovery Relays only"
1752        );
1753    }
1754    // Anchor only on a confirmed landing in a still-current session: a
1755    // wrongly-advanced anchor gates future syncs off real network state.
1756    if session.is_live() {
1757        note_list_seen(event.created_at.as_secs().max(remote_ts));
1758        keep_own(&event.pubkey, &plan.list, event.created_at.as_secs());
1759    }
1760
1761    crate::log_info!(
1762        "[InboxRelays] Published kind 10050 with {} relay(s) ({} foreign preserved)",
1763        plan.list.len(),
1764        plan.list.len().saturating_sub(plan.contributed.len())
1765    );
1766    Ok(())
1767}
1768
1769/// Monotonic generation counter used to debounce republish calls.
1770/// Only the most recent spawn actually publishes; earlier ones exit early.
1771static REPUBLISH_GEN: AtomicU64 = AtomicU64::new(0);
1772
1773/// Counts how many spawned tasks pass the generation gate (test-only).
1774#[cfg(test)]
1775static DEBOUNCE_PASS_COUNT: AtomicU64 = AtomicU64::new(0);
1776
1777/// Republish kind 10050 in the background (debounced).
1778/// Called after relay config changes (add/remove/toggle/mode update).
1779/// Rapid successive calls coalesce into a single publish.
1780pub fn republish_inbox_relays_debounced() {
1781    let gen = REPUBLISH_GEN.fetch_add(1, Ordering::SeqCst) + 1;
1782    // REPUBLISH_GEN dedupes within a session; std::sync::Arc<crate::db::Session> dedupes
1783    // across sessions. Without the guard, a swap during the 800ms
1784    // debounce window would publish account A's inbox-relay claim
1785    // signed by account B's client.
1786    let session = crate::db::current_session();
1787    crate::db::spawn_bound(async move {
1788        // Wait for the relay pool to settle; if another call arrives
1789        // during this window it will bump the generation and we'll exit.
1790        crate::rt::time::sleep(std::time::Duration::from_millis(800)).await;
1791        if REPUBLISH_GEN.load(Ordering::SeqCst) != gen {
1792            return; // superseded by a newer call
1793        }
1794        if !session.is_live() {
1795            return; // swap occurred during the debounce window
1796        }
1797        #[cfg(test)]
1798        DEBOUNCE_PASS_COUNT.fetch_add(1, Ordering::SeqCst);
1799        let client = match nostr_client() {
1800            Some(c) => c,
1801            None => return,
1802        };
1803        if let Err(e) = publish_inbox_relays(&client).await {
1804            eprintln!("[InboxRelays] Failed to republish after config change: {}", e);
1805        }
1806    });
1807}
1808
1809#[cfg(test)]
1810mod tests {
1811    use super::*;
1812
1813    // ---- Merge (sync-first publish) ----
1814
1815    fn strs(v: &[&str]) -> Vec<String> {
1816        v.iter().map(|s| s.to_string()).collect()
1817    }
1818
1819    fn norm_set(v: &[&str]) -> HashSet<String> {
1820        v.iter().map(|s| normalize_relay_url(s)).collect()
1821    }
1822
1823    #[test]
1824    fn merge_preserves_foreign_entries() {
1825        let remote = strs(&["wss://other-app.example", "wss://alice.example"]);
1826        let ours = strs(&["wss://vector.example"]);
1827        let plan = merge_inbox_relays(&remote, &HashSet::new(), &ours);
1828        assert!(plan.changed);
1829        assert_eq!(plan.list, strs(&["wss://other-app.example", "wss://alice.example", "wss://vector.example"]));
1830        assert_eq!(plan.contributed, strs(&["wss://vector.example"]));
1831    }
1832
1833    #[test]
1834    fn merge_noop_when_remote_covers_ours() {
1835        let remote = strs(&["wss://other-app.example", "wss://vector.example/"]);
1836        let ours = strs(&["wss://vector.example"]);
1837        let plan = merge_inbox_relays(&remote, &HashSet::new(), &ours);
1838        assert!(!plan.changed, "trailing-slash variants are the same relay");
1839        assert_eq!(plan.list.len(), 2);
1840    }
1841
1842    #[test]
1843    fn merge_drops_only_our_own_removed_contribution() {
1844        // We contributed X earlier; the user removed it in Vector. Foreign F
1845        // stays, X leaves.
1846        let remote = strs(&["wss://foreign.example", "wss://x.example"]);
1847        let contributed = norm_set(&["wss://x.example"]);
1848        let ours = strs(&["wss://new.example"]);
1849        let plan = merge_inbox_relays(&remote, &contributed, &ours);
1850        assert!(plan.changed);
1851        assert_eq!(plan.list, strs(&["wss://foreign.example", "wss://new.example"]));
1852    }
1853
1854    #[test]
1855    fn merge_never_clears_a_foreign_list() {
1856        // No readable relays of our own must NOT nuke another client's list.
1857        let remote = strs(&["wss://foreign.example"]);
1858        let plan = merge_inbox_relays(&remote, &HashSet::new(), &[]);
1859        assert!(!plan.changed);
1860        assert_eq!(plan.list, remote);
1861        assert!(plan.contributed.is_empty());
1862    }
1863
1864    #[test]
1865    fn merge_contributed_excludes_foreign_overlap() {
1866        // At the MERGE layer a co-listed relay classifies foreign-first (a
1867        // bare publish never strips it). Propagating removals of co-listed
1868        // entries is the reconcile layer's job: it seeds co-ownership into
1869        // the contributed set for entries both remote-listed and locally
1870        // enabled (see reconcile_two_devices_propagates_default_disable).
1871        let remote = strs(&["wss://shared.example"]);
1872        let ours = strs(&["wss://shared.example", "wss://mine.example"]);
1873        let plan = merge_inbox_relays(&remote, &HashSet::new(), &ours);
1874        assert_eq!(plan.contributed, strs(&["wss://mine.example"]));
1875        let next = merge_inbox_relays(
1876            &plan.list,
1877            &plan.contributed.iter().cloned().collect(),
1878            &[],
1879        );
1880        assert!(next.list.contains(&"wss://shared.example".to_string()));
1881        assert!(!next.list.contains(&"wss://mine.example".to_string()));
1882    }
1883
1884    #[test]
1885    fn merge_caps_foreign_bloat_without_publishing() {
1886        // The cap bounds what WE would re-sign, but a trim alone is not an
1887        // own diff — publishing it would ping-pong against any client
1888        // maintaining an 11+ list.
1889        let remote: Vec<String> = (0..30).map(|i| format!("wss://r{}.example", i)).collect();
1890        let plan = merge_inbox_relays(&remote, &HashSet::new(), &[]);
1891        assert_eq!(plan.list.len(), MAX_FOREIGN_RELAYS);
1892        assert!(!plan.changed, "a trim alone must not drive a publish");
1893    }
1894
1895    #[test]
1896    fn merge_cap_applies_when_own_diff_publishes() {
1897        let remote: Vec<String> = (0..30).map(|i| format!("wss://r{}.example", i)).collect();
1898        let ours = strs(&["wss://mine.example"]);
1899        let plan = merge_inbox_relays(&remote, &HashSet::new(), &ours);
1900        assert!(plan.changed, "our addition is a real diff");
1901        assert_eq!(plan.list.len(), MAX_FOREIGN_RELAYS + 1);
1902        assert!(plan.list.contains(&"wss://mine.example".to_string()));
1903    }
1904
1905    #[test]
1906    fn merge_two_devices_reach_fixpoint() {
1907        // Two devices with different configs alternating sync->merge->publish
1908        // must converge: bounded publishes, then permanent in-sync.
1909        let ours_a = strs(&["wss://a1.example", "wss://shared.example"]);
1910        let ours_b = strs(&["wss://b1.example", "wss://shared.example"]);
1911        let mut network = strs(&["wss://foreign.example"]);
1912        let mut contributed_a: HashSet<String> = HashSet::new();
1913        let mut contributed_b: HashSet<String> = HashSet::new();
1914        let mut publishes = 0;
1915        for round in 0..6 {
1916            for device in 0..2 {
1917                let (ours, contributed) = if device == 0 {
1918                    (&ours_a, &mut contributed_a)
1919                } else {
1920                    (&ours_b, &mut contributed_b)
1921                };
1922                let plan = merge_inbox_relays(&network, contributed, ours);
1923                *contributed = plan.contributed.iter().cloned().collect();
1924                if plan.changed {
1925                    publishes += 1;
1926                    network = plan.list;
1927                }
1928                if round >= 2 {
1929                    assert!(!plan.changed, "no publish after convergence (round {round})");
1930                }
1931            }
1932        }
1933        assert!(publishes <= 2, "one publish per device to converge, got {publishes}");
1934        for url in ["wss://foreign.example", "wss://a1.example", "wss://b1.example", "wss://shared.example"] {
1935            assert!(network.contains(&url.to_string()), "union must hold {url}");
1936        }
1937    }
1938
1939    #[test]
1940    fn merge_first_run_publishes_ours() {
1941        let ours = strs(&["wss://a.example", "wss://b.example"]);
1942        let plan = merge_inbox_relays(&[], &HashSet::new(), &ours);
1943        assert!(plan.changed);
1944        assert_eq!(plan.list, ours);
1945        assert_eq!(plan.contributed, ours);
1946    }
1947
1948    // ---- Inbound reconcile planner ----
1949
1950    #[test]
1951    fn reconcile_stale_remote_is_a_no_op() {
1952        let remote = strs(&["wss://foreign.example"]);
1953        let plan = plan_inbound_reconcile_pure(&remote, 100, &[], &[], &HashSet::new(), 100);
1954        assert_eq!(plan, InboundReconcile::default(), "ts <= last_seen must not act");
1955    }
1956
1957    #[test]
1958    fn reconcile_adopts_unknown_entries_capped_and_wss_only() {
1959        let mut remote: Vec<String> = (0..12).map(|i| format!("wss://r{}.example", i)).collect();
1960        remote.push("ws://plaintext.example".to_string());
1961        remote.push("http://nope.example".to_string());
1962        let plan = plan_inbound_reconcile_pure(&remote, 200, &[], &[], &HashSet::new(), 100);
1963        assert_eq!(plan.adopt.len(), MAX_FOREIGN_RELAYS);
1964        assert!(plan.adopt.iter().all(|u| u.starts_with("wss://")));
1965        assert!(plan.revive.is_empty() && plan.retire.is_empty());
1966    }
1967
1968    #[test]
1969    fn reconcile_adopts_plain_ws_only_for_i2p() {
1970        let i2p = "ws://nostrajmjieip3dqgeefsgpydy3bbshe3o32z65dwkssl7qxkn5a.b32.i2p".to_string();
1971        let remote = vec![i2p.clone(), "ws://plaintext.example".to_string()];
1972        let plan = plan_inbound_reconcile_pure(&remote, 200, &[], &[], &HashSet::new(), 100);
1973        assert_eq!(plan.adopt, vec![i2p]);
1974    }
1975
1976    #[test]
1977    fn reconcile_revives_locally_disabled_entry() {
1978        let remote = strs(&["wss://back.example"]);
1979        let declined = strs(&["wss://back.example/"]);
1980        let plan = plan_inbound_reconcile_pure(&remote, 200, &[], &declined, &HashSet::new(), 100);
1981        assert_eq!(plan.revive, strs(&["wss://back.example"]));
1982        assert!(plan.adopt.is_empty());
1983    }
1984
1985    #[test]
1986    fn reconcile_retires_contributed_entry_dropped_by_newer_remote() {
1987        let remote = strs(&["wss://keep.example"]);
1988        let ours = strs(&["wss://keep.example", "wss://gone.example"]);
1989        let contributed = norm_set(&["wss://keep.example", "wss://gone.example"]);
1990        let plan = plan_inbound_reconcile_pure(&remote, 200, &ours, &[], &contributed, 100);
1991        assert_eq!(plan.retire, strs(&["wss://gone.example"]));
1992    }
1993
1994    #[test]
1995    fn reconcile_never_retires_unpublished_local_addition() {
1996        // A relay added locally but not yet published is absent from any
1997        // remote; retiring it would erase fresh user intent.
1998        let remote = strs(&["wss://old.example"]);
1999        let ours = strs(&["wss://old.example", "wss://just-added.example"]);
2000        let contributed = norm_set(&["wss://old.example"]);
2001        let plan = plan_inbound_reconcile_pure(&remote, 200, &ours, &[], &contributed, 100);
2002        assert!(plan.retire.is_empty());
2003    }
2004
2005    #[test]
2006    fn reconcile_two_devices_propagates_default_disable() {
2007        // Both devices ship the same defaults. The co-ownership seed (ours
2008        // that are also remote-listed join contributed) is what lets a
2009        // disable on one device propagate instead of being reverted.
2010        #[derive(Clone)]
2011        struct Device {
2012            ours: Vec<String>,
2013            declined: Vec<String>,
2014            contributed: HashSet<String>,
2015            last_seen: u64,
2016        }
2017        impl Device {
2018            fn new(defaults: &[&str]) -> Self {
2019                Device {
2020                    ours: strs(defaults),
2021                    declined: Vec::new(),
2022                    contributed: HashSet::new(),
2023                    last_seen: 0,
2024                }
2025            }
2026            /// Boot reconcile + publish, mirroring reconcile_dm_relay_list.
2027            fn sync(&mut self, network: &mut (Vec<String>, u64)) -> bool {
2028                let (remote, ts) = network.clone();
2029                for u in &self.ours {
2030                    if remote.iter().any(|r| normalize_relay_url(r) == normalize_relay_url(u)) {
2031                        self.contributed.insert(normalize_relay_url(u));
2032                    }
2033                }
2034                let plan = plan_inbound_reconcile_pure(
2035                    &remote, ts, &self.ours, &self.declined, &self.contributed, self.last_seen,
2036                );
2037                for u in &plan.retire {
2038                    self.ours.retain(|o| o != u);
2039                    self.declined.push(u.clone());
2040                }
2041                for u in &plan.revive {
2042                    self.declined.retain(|d| normalize_relay_url(d) != normalize_relay_url(u));
2043                    self.ours.push(u.clone());
2044                    self.contributed.insert(normalize_relay_url(u));
2045                }
2046                for u in &plan.adopt {
2047                    self.ours.push(u.clone());
2048                    self.contributed.insert(normalize_relay_url(u));
2049                }
2050                self.last_seen = self.last_seen.max(ts);
2051                let m = merge_inbox_relays(&remote, &self.contributed, &self.ours);
2052                self.contributed = m.contributed.iter().cloned().collect();
2053                if m.changed {
2054                    network.1 += 1;
2055                    network.0 = m.list;
2056                    self.last_seen = network.1;
2057                }
2058                m.changed
2059            }
2060        }
2061
2062        const DEFAULTS: &[&str] = &["wss://d1.example", "wss://d2.example"];
2063        let mut network: (Vec<String>, u64) = (Vec::new(), 0);
2064        let mut a = Device::new(DEFAULTS);
2065        let mut b = Device::new(DEFAULTS);
2066
2067        assert!(a.sync(&mut network), "first device bootstraps the list");
2068        assert!(!b.sync(&mut network), "second device is already in sync");
2069
2070        // B disables d2 locally, publishes the removal.
2071        b.ours.retain(|u| u != "wss://d2.example");
2072        b.declined.push("wss://d2.example".to_string());
2073        assert!(b.sync(&mut network), "disable must publish");
2074        assert!(!network.0.contains(&"wss://d2.example".to_string()));
2075
2076        // A's next boot retires d2 rather than re-adding it.
2077        assert!(!a.sync(&mut network), "A must adopt the removal, not republish d2");
2078        assert!(a.declined.contains(&"wss://d2.example".to_string()));
2079        assert!(!network.0.contains(&"wss://d2.example".to_string()), "no resurrection");
2080
2081        // B re-enables d2: A revives it too.
2082        b.declined.retain(|u| u != "wss://d2.example");
2083        b.ours.push("wss://d2.example".to_string());
2084        assert!(b.sync(&mut network), "re-enable must publish");
2085        assert!(!a.sync(&mut network), "revive is inbound-only, no republish");
2086        assert!(a.ours.contains(&"wss://d2.example".to_string()), "A revives d2");
2087
2088        // Fixpoint: quiet forever after.
2089        for _ in 0..3 {
2090            assert!(!a.sync(&mut network));
2091            assert!(!b.sync(&mut network));
2092        }
2093    }
2094
2095    // ---- Tag parsing ----
2096
2097    #[test]
2098    fn parse_relay_tags_extracts_urls() {
2099        let tags = Tags::from_list(vec![
2100            Tag::custom("relay", vec!["wss://relay.example.com"]),
2101            Tag::custom("relay", vec!["wss://other.example.com"]),
2102        ]);
2103        let result = parse_relay_tags(&tags);
2104        assert_eq!(result, vec![
2105            "wss://relay.example.com".to_string(),
2106            "wss://other.example.com".to_string(),
2107        ]);
2108    }
2109
2110    #[test]
2111    fn parse_relay_tags_ignores_non_relay_tags() {
2112        let tags = Tags::from_list(vec![
2113            Tag::custom("relay", vec!["wss://good.example.com"]),
2114            Tag::custom("p", vec!["deadbeef"]),
2115            Tag::custom("e", vec!["cafebabe"]),
2116        ]);
2117        let result = parse_relay_tags(&tags);
2118        assert_eq!(result, vec!["wss://good.example.com".to_string()]);
2119    }
2120
2121    #[test]
2122    fn parse_relay_tags_empty() {
2123        let tags = Tags::new();
2124        let result = parse_relay_tags(&tags);
2125        assert!(result.is_empty());
2126    }
2127
2128    #[test]
2129    fn parse_relay_tags_ignores_relay_tag_without_value() {
2130        // A ["relay"] tag with no URL should be skipped (len < 2)
2131        let tags = Tags::from_list(vec![
2132            Tag::custom("relay", Vec::<String>::new()),
2133        ]);
2134        let result = parse_relay_tags(&tags);
2135        assert!(result.is_empty());
2136    }
2137
2138    // ---- Cache ----
2139
2140    fn test_pubkey() -> PublicKey {
2141        let keys = Keys::generate();
2142        keys.public_key()
2143    }
2144
2145    // Serialize tests that mutate global cache/lock statics.
2146    static TEST_GLOBALS_LOCK: LazyLock<tokio::sync::Mutex<()>> =
2147        LazyLock::new(|| tokio::sync::Mutex::new(()));
2148
2149    /// The test's own session: no database, nothing shared with a test that has one open.
2150    async fn isolated<F: std::future::Future>(fut: F) -> F::Output {
2151        crate::db::with_session(crate::db::Session::empty(), fut).await
2152    }
2153
2154    fn put(pk: PublicKey, relays: &[&str], age: u64, fetch_ok: bool, event_at: u64) {
2155        inbox_relay_cache().lock().unwrap().insert(pk, CachedRelays {
2156            relays: relays.iter().map(|s| s.to_string()).collect(),
2157            fetched_at: now_secs() - age,
2158            fetch_ok,
2159            event_at,
2160        });
2161    }
2162
2163    fn answer(relays: &[&str], event_at: Option<u64>) -> FetchResult {
2164        FetchResult { relays: relays.iter().map(|s| s.to_string()).collect(), fetch_ok: true, blind: None, cached_at: None, event_at }
2165    }
2166
2167    fn relays_of(pk: &PublicKey) -> Vec<String> {
2168        cached(pk).unwrap().relays
2169    }
2170
2171    #[tokio::test]
2172    async fn a_known_list_is_served_at_any_age_without_a_lookup() {
2173        isolated(async {
2174            let pk = test_pubkey();
2175            put(pk, &["wss://old.example.com"], 30 * 24 * 3600, true, 10);
2176            let r = get_or_fetch_with_lock(&pk, || async { panic!("a known list must not wait on a lookup") }).await;
2177            assert_eq!(r.relays, vec!["wss://old.example.com".to_string()]);
2178            assert!(r.cached_at.is_some(), "served from the cache, so a send may re-check it");
2179        })
2180        .await;
2181    }
2182
2183    #[tokio::test]
2184    async fn a_failed_lookup_is_served_briefly_then_asked_again() {
2185        isolated(async {
2186            let pk = test_pubkey();
2187            put(pk, &[], 10, false, 0);
2188            let r = get_or_fetch_with_lock(&pk, || async { panic!("a fresh failure is served") }).await;
2189            assert!(!r.fetch_ok);
2190            put(pk, &[], CACHE_TTL_ERROR_SECS + 1, false, 0);
2191            let r = get_or_fetch_with_lock(&pk, || async { answer(&["wss://new.example.com"], Some(5)) }).await;
2192            assert_eq!(r.relays, vec!["wss://new.example.com".to_string()]);
2193            assert!(r.cached_at.is_none());
2194        })
2195        .await;
2196    }
2197
2198    #[tokio::test]
2199    async fn only_a_newer_revision_replaces_a_known_list() {
2200        isolated(async {
2201            let pk = test_pubkey();
2202            put(pk, &["wss://known.example.com"], 7200, true, 100);
2203            // A failed lookup, an older revision, and finding no list at all leave it.
2204            keep(&pk, &FetchResult { relays: Vec::new(), fetch_ok: false, blind: None, cached_at: None, event_at: None });
2205            keep(&pk, &answer(&["wss://older.example.com"], Some(99)));
2206            keep(&pk, &answer(&[], None));
2207            assert_eq!(relays_of(&pk), vec!["wss://known.example.com".to_string()]);
2208            // The older revision still confirmed it current.
2209            assert!(cached(&pk).unwrap().age() < 5);
2210            // A newer revision replaces it, even one that names no relays: they removed it.
2211            keep(&pk, &answer(&["wss://newer.example.com"], Some(101)));
2212            assert_eq!(relays_of(&pk), vec!["wss://newer.example.com".to_string()]);
2213            keep(&pk, &answer(&[], Some(102)));
2214            assert!(relays_of(&pk).is_empty());
2215        })
2216        .await;
2217    }
2218
2219    #[tokio::test]
2220    async fn a_recheck_compares_with_the_relays_the_send_used_not_the_cache() {
2221        isolated(async {
2222            let pk = test_pubkey();
2223            let tried = vec!["wss://a.example.com".to_string()];
2224            put(pk, &["wss://a.example.com/"], 0, true, 1);
2225            assert!(!list_moved(&pk, &tried), "same relays, however they are spelled");
2226            // A refresh (their chat opening) learned the new list after the send resolved.
2227            keep(&pk, &answer(&["wss://b.example.com"], Some(2)));
2228            assert!(list_moved(&pk, &tried));
2229        })
2230        .await;
2231    }
2232
2233    #[tokio::test]
2234    async fn a_background_refresh_runs_at_most_hourly_and_not_for_a_fresh_list() {
2235        isolated(async {
2236            let fresh = test_pubkey();
2237            put(fresh, &["wss://a.example.com"], 60, true, 1);
2238            refresh_in_background(fresh);
2239            assert!(!asked_at().lock().unwrap().contains_key(&fresh), "under an hour old: nothing to ask");
2240
2241            let stale = test_pubkey();
2242            put(stale, &["wss://a.example.com"], REFRESH_AFTER_SECS + 1, true, 1);
2243            refresh_in_background(stale);
2244            let first = *asked_at().lock().unwrap().get(&stale).expect("asked for");
2245            asked_at().lock().unwrap().insert(stale, first - 10);
2246            refresh_in_background(stale);
2247            assert_eq!(asked_at().lock().unwrap().get(&stale), Some(&(first - 10)), "not again within the hour");
2248        })
2249        .await;
2250    }
2251
2252    #[test]
2253    fn a_list_found_survives_a_restart() {
2254        let _globals = TEST_GLOBALS_LOCK.blocking_lock();
2255        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2256        crate::db::close_database();
2257        crate::db::clear_id_caches();
2258        let account = Keys::generate().public_key().to_bech32().unwrap();
2259        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
2260        crate::db::set_current_account(account.clone()).unwrap();
2261        crate::db::init_database(&account).unwrap();
2262
2263        let pk = test_pubkey();
2264        let other = test_pubkey();
2265        keep(&pk, &answer(&["wss://kept.example.com"], Some(42)));
2266        keep(&other, &FetchResult { relays: Vec::new(), fetch_ok: false, blind: None, cached_at: None, event_at: None });
2267
2268        crate::db::close_database();
2269        crate::db::init_database(&account).unwrap();
2270        inbox_relay_cache().lock().unwrap().clear();
2271
2272        let entry = cached(&pk).expect("read back from the database");
2273        assert_eq!(entry.relays, vec!["wss://kept.example.com".to_string()]);
2274        assert_eq!(entry.event_at, 42);
2275        assert!(entry.fetch_ok && entry.age() < 5);
2276        // A failure is never written down: a restart asks again rather than trusting it.
2277        assert!(cached(&other).is_none());
2278    }
2279
2280    #[tokio::test]
2281    async fn concurrent_fetches_for_same_pubkey_serialize() {
2282        let _guard = TEST_GLOBALS_LOCK.lock().await;
2283        isolated(async {
2284            let pk = test_pubkey();
2285
2286            // Clear cache so all tasks see a cold cache
2287            {
2288                let owner = inbox_relay_cache();
2289                let mut cache = owner.lock().unwrap();
2290                cache.remove(&pk);
2291            }
2292
2293            let fetch_counter = Arc::new(AtomicU64::new(0));
2294
2295            // Spawn 10 concurrent tasks all trying to fetch the same pubkey.
2296            // Uses production get_or_fetch_with_lock so this tests actual code path.
2297            let mut handles = vec![];
2298            for _ in 0..10 {
2299                let counter = fetch_counter.clone();
2300                let handle = crate::db::spawn_bound(async move {
2301                    get_or_fetch_with_lock(&pk, || async {
2302                        counter.fetch_add(1, Ordering::SeqCst);
2303                        // Simulate network delay so concurrent tasks pile up
2304                        crate::rt::time::sleep(std::time::Duration::from_millis(50)).await;
2305                        FetchResult::found(vec!["wss://test.example.com".to_string()], true)
2306                    })
2307                    .await
2308                });
2309                handles.push(handle);
2310            }
2311
2312            // Wait for all tasks to complete
2313            let results = futures_util::future::join_all(handles).await;
2314
2315            // All tasks should succeed and get the same result
2316            for result in &results {
2317                assert!(result.is_ok());
2318                let relays = &result.as_ref().unwrap().relays;
2319                assert_eq!(relays, &vec!["wss://test.example.com".to_string()]);
2320            }
2321
2322            // CRITICAL: Only ONE fetch should have executed (others waited on lock + hit cache)
2323            assert_eq!(
2324                fetch_counter.load(Ordering::SeqCst),
2325                1,
2326                "Expected exactly 1 fetch for 10 concurrent requests to same pubkey"
2327            );
2328
2329            let locks_after = {
2330                let locks = FETCH_LOCKS.lock().unwrap();
2331                locks.len()
2332            };
2333            assert_eq!(locks_after, 0, "Lock entry should be removed after all waiters complete");
2334        })
2335        .await;
2336    }
2337
2338    #[tokio::test]
2339    async fn fetch_locks_do_not_accumulate_after_calls_complete() {
2340        let _guard = TEST_GLOBALS_LOCK.lock().await;
2341        isolated(async {
2342
2343            // Verify that lock entries are removed eagerly when the last in-flight
2344            // caller for a key exits (true bounded growth, no idle-after-burst leak).
2345
2346            let pk1 = test_pubkey();
2347            let pk2 = test_pubkey();
2348            let pk3 = test_pubkey();
2349
2350            // Clear both cache and locks to avoid interference from other tests
2351            {
2352                let owner = inbox_relay_cache();
2353                let mut cache = owner.lock().unwrap();
2354                cache.clear();
2355            }
2356            {
2357                let mut locks = FETCH_LOCKS.lock().unwrap();
2358                locks.clear();
2359            }
2360
2361            // Step 1: Fetch for pk1 (cache miss -> creates lock entry)
2362            get_or_fetch_with_lock(&pk1, || async {
2363                FetchResult::found(vec!["wss://relay1.example.com".to_string()], true)
2364            })
2365            .await;
2366
2367            // Single-call path: no waiters, so eager cleanup should remove key immediately.
2368
2369            let locks_after_pk1 = {
2370                let locks = FETCH_LOCKS.lock().unwrap();
2371                locks.len()
2372            };
2373            assert_eq!(locks_after_pk1, 0, "No lock entries should remain after pk1 call");
2374
2375            // Step 2: repeat with pk2
2376            get_or_fetch_with_lock(&pk2, || async {
2377                FetchResult::found(vec!["wss://relay2.example.com".to_string()], true)
2378            })
2379            .await;
2380
2381            let locks_after_pk2 = {
2382                let locks = FETCH_LOCKS.lock().unwrap();
2383                locks.len()
2384            };
2385            assert_eq!(locks_after_pk2, 0, "No lock entries should remain after pk2 call");
2386
2387            // Step 3: repeat with pk3
2388            get_or_fetch_with_lock(&pk3, || async {
2389                FetchResult::found(vec!["wss://relay3.example.com".to_string()], true)
2390            })
2391            .await;
2392
2393            let locks_after_pk3 = {
2394                let locks = FETCH_LOCKS.lock().unwrap();
2395                locks.len()
2396            };
2397            assert_eq!(locks_after_pk3, 0, "No lock entries should remain after pk3 call");
2398        })
2399        .await;
2400    }
2401
2402    #[tokio::test]
2403    async fn a_blind_lookup_is_never_cached() {
2404        let _guard = TEST_GLOBALS_LOCK.lock().await;
2405        isolated(async {
2406            let pk = test_pubkey();
2407            let runs = Arc::new(AtomicU64::new(0));
2408            for _ in 0..2 {
2409                let runs = runs.clone();
2410                let r = get_or_fetch_with_lock(&pk, || async move {
2411                    runs.fetch_add(1, Ordering::SeqCst);
2412                    FetchResult { relays: Vec::new(), fetch_ok: true, blind: Some(Blind::Policy(crate::transport::Refusal::ExitOff)), cached_at: None, event_at: None }
2413                })
2414                .await;
2415                assert_eq!(r.blind, Some(Blind::Policy(crate::transport::Refusal::ExitOff)));
2416            }
2417            assert_eq!(runs.load(Ordering::SeqCst), 2, "asked again, not answered from the cache");
2418            assert!(!is_cached_for_test(&pk));
2419            let r = get_or_fetch_with_lock(&pk, || async { FetchResult::found(Vec::new(), true) }).await;
2420            assert!(r.blind.is_none() && is_cached_for_test(&pk), "a real answer is cached as before");
2421        })
2422        .await;
2423    }
2424
2425    #[tokio::test]
2426    async fn cancelled_fetch_cleans_up_lock_entry() {
2427        let _guard = TEST_GLOBALS_LOCK.lock().await;
2428        isolated(async {
2429            let pk = test_pubkey();
2430
2431            {
2432                let owner = inbox_relay_cache();
2433                let mut cache = owner.lock().unwrap();
2434                cache.clear();
2435            }
2436            {
2437                let mut locks = FETCH_LOCKS.lock().unwrap();
2438                locks.clear();
2439            }
2440
2441            let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
2442            let task_pk = pk;
2443            let handle = crate::db::spawn_bound(async move {
2444                get_or_fetch_with_lock(&task_pk, || async move {
2445                    let _ = started_tx.send(());
2446                    crate::rt::time::sleep(std::time::Duration::from_secs(30)).await;
2447                    FetchResult::found(Vec::new(), false)
2448                })
2449                .await
2450            });
2451
2452            started_rx.await.expect("fetch closure should start before abort");
2453            handle.abort();
2454            let _ = handle.await;
2455            crate::rt::yield_now().await;
2456
2457            let locks_after = {
2458                let locks = FETCH_LOCKS.lock().unwrap();
2459                locks.len()
2460            };
2461            assert_eq!(
2462                locks_after, 0,
2463                "Lock entry should be removed even if fetch task is cancelled"
2464            );
2465        })
2466        .await;
2467    }
2468
2469    // ---- Debounce ----
2470
2471    // `start_paused`: drive the 800ms debounce window on tokio's VIRTUAL clock, which auto-advances when
2472    // all tasks are parked. The spawned timers then resolve deterministically — no dependence on wall-clock
2473    // timing, so heavy parallel CPU load (e.g. the serialized vault stress tests) can't make the gate fire
2474    // after the test's wait and spuriously fail. (Was a real 1000ms sleep with only a 200ms margin.)
2475    #[tokio::test(start_paused = true)]
2476    async fn debounce_coalesces_rapid_calls_into_one() {
2477        // Another test installing a session mid-wait makes the debounced task stand down before
2478        // it counts; the database tests all take this lock.
2479        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
2480        // Snapshot counters before the burst.
2481        let gen_before = REPUBLISH_GEN.load(Ordering::SeqCst);
2482        let pass_before = DEBOUNCE_PASS_COUNT.load(Ordering::SeqCst);
2483
2484        // Three rapid calls — only the last should survive the debounce gate.
2485        republish_inbox_relays_debounced();
2486        republish_inbox_relays_debounced();
2487        republish_inbox_relays_debounced();
2488
2489        let gen_after = REPUBLISH_GEN.load(Ordering::SeqCst);
2490        assert_eq!(gen_after, gen_before + 3);
2491
2492        // Past the 800ms window on the virtual clock (auto-advanced) so all spawned tasks resolve.
2493        crate::rt::time::sleep(std::time::Duration::from_millis(1000)).await;
2494
2495        let pass_after = DEBOUNCE_PASS_COUNT.load(Ordering::SeqCst);
2496        // Exactly one task should have passed the generation gate.
2497        // (It then exits at nostr_client() since the client isn't
2498        // initialised in tests, but the coalescing behaviour is proven.)
2499        assert_eq!(pass_after - pass_before, 1);
2500    }
2501}