Skip to main content

vector_core/community/
transport.rs

1//! Transport abstraction for Community events.
2//!
3//! The protocol's send/sync logic is written against this trait, not against the
4//! live Nostr client, so it can be exercised end-to-end by multiple emulated
5//! clients sharing an in-memory relay (no network, fully deterministic). Production
6//! provides an adapter over `NOSTR_CLIENT`; tests use `MemoryRelay`.
7
8use nostr_sdk::prelude::*;
9use crate::ClientRelayExt;
10
11/// How much relay coverage a fetch waits to witness before returning.
12///
13/// The community planes distinguish POSITIVE DATA (signed events, hash-chained
14/// editions — safe to act on from any relay; refuse-downgrade floors make stale
15/// or replayed data harmless) from NEGATIVE VERDICTS (conclusions from absence:
16/// "no rotation happened", "history ends here", "coverage complete"). A partial
17/// relay view can only ever STALL consensus — and every stall heals via the
18/// straggler sink, the live subscription, or the next sync — but a written
19/// negative verdict has no healer. Pick the tier by what the caller CONCLUDES
20/// from the result, not by how fast it wants to be.
21#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
22pub enum Evidence {
23    /// Return at the FIRST successful relay EOSE (+ the residual merge window).
24    /// For positive-data consumers only: never conclude absence from a Fast
25    /// result.
26    Fast,
27    /// Wait for a MAJORITY of attempted relays — time-bounded to
28    /// [`QUORUM_GRACE_MS`] past the first success, so one dead relay can't
29    /// gate a degraded set. A single fast-lying relay can't force an early
30    /// return while its honest peers answer within the window. Note: for a
31    /// 2-relay set the majority is BOTH, so a degraded pair always rides the
32    /// grace bound (first success + 2s), never a dead relay's full timeout.
33    #[default]
34    Quorum,
35    /// Wait for EVERY relay to resolve (EOSE or its per-relay timeout). For
36    /// presence-latches and coverage gates whose correctness depends on the
37    /// union being as complete as the reachable set allows. Forced whenever
38    /// `Query::until` is set (back-page verdicts).
39    Full,
40}
41
42/// A plane fetch plus how much of the relay set actually answered it.
43///
44/// One honest relay is enough to RUN Concord: a valid, sealed, signed event is
45/// proof on its own, and no amount of corroboration adds to it. So coverage never
46/// gates accepting data — a single relay's answer is taken whole.
47///
48/// It gates exactly one thing: concluding that something is **absent**. An empty
49/// result from four relays where three timed out says nothing; the same empty
50/// result where all four answered is real evidence. Both used to be a bare
51/// `Vec<Event>`, indistinguishable, so every "it's gone" decision in the protocol
52/// was really "nobody who happened to reply mentioned it".
53///
54/// Coverage is always relative to the REACHABLE set, never an absolute quorum: a
55/// one-relay community reports 1/1 and its absences are as confirmed as they can
56/// ever be. Nothing halts for want of relays.
57#[derive(Debug, Clone)]
58pub struct PlaneFetch {
59    pub events: Vec<Event>,
60    /// Relays that resolved successfully (an empty EOSE counts — that is a real answer).
61    pub answered: usize,
62    /// Relays attempted.
63    pub attempted: usize,
64}
65
66impl PlaneFetch {
67    /// Every relay we could reach answered, so an empty `events` IS absence.
68    pub fn is_complete(&self) -> bool {
69        self.answered > 0 && self.answered == self.attempted
70    }
71
72    /// For transports with no relay set of their own (the in-memory test relays and
73    /// stubs): one authoritative source, fully answered.
74    pub fn whole(events: Vec<Event>) -> Self {
75        PlaneFetch { events, answered: 1, attempted: 1 }
76    }
77}
78
79/// The slice of a relay query the Community protocol needs: event kinds, the `z`
80/// pseudonym tag values, and an optional `since` floor. Production translates
81/// this into a Nostr `Filter`; the in-memory relay matches it directly.
82#[derive(Clone, Debug, Default)]
83pub struct Query {
84    pub kinds: Vec<u16>,
85    /// `z` tag values to match (OR). Empty = match any (no `z` constraint).
86    pub z_tags: Vec<String>,
87    /// `d` tag (identifier) values to match (OR). Empty = no `d` constraint. Used to
88    /// locate addressable events (e.g. a public-invite bundle by its token locator).
89    pub d_tags: Vec<String>,
90    /// `p` tag (recipient pubkey hex) values to match (OR). Empty = no `p` constraint.
91    /// Used to fetch person-addressed giftwraps (direct invites) by recipient.
92    pub p_tags: Vec<String>,
93    /// `k` tag (wrapped-kind) values to match (OR). Empty = no `k` constraint. Narrows
94    /// giftwrap fetches to the inner kind advertised on the wrap.
95    pub k_tags: Vec<String>,
96    /// Author pubkeys (hex) to match (OR). Empty = any author.
97    pub authors: Vec<String>,
98    /// Event ids (hex) to match (OR). Empty = any id. Used to recover a known
99    /// wrap verbatim (e.g. re-opening a message's seal to build a pin proof).
100    pub ids: Vec<String>,
101    /// Lower bound on `created_at` (seconds), inclusive.
102    pub since: Option<u64>,
103    /// Upper bound on `created_at` (seconds), inclusive — pages OLDER history (events
104    /// strictly/inclusively before a scroll cursor).
105    pub until: Option<u64>,
106    /// Max events to return (newest-first), the relay-side page cap. `None` = no limit.
107    pub limit: Option<usize>,
108    /// Relay-coverage requirement before the fetch may return. Defaults to
109    /// [`Evidence::Quorum`]; opt into [`Evidence::Fast`] only for positive-data
110    /// reads. Ignored by the in-memory test relay (inherently full-coverage).
111    pub evidence: Evidence,
112    /// One page of a newest-first walk, whose caller goes on from the oldest event it is given:
113    /// the answer is cut where the shallowest relay's page ended (`PageFloor`).
114    pub paged: bool,
115}
116
117/// Where a page read from several relays stops being whole.
118///
119/// Each relay answers with its own newest `limit` events, so their pages end at different
120/// depths. Below the shallowest of those ends, a relay that filled its page holds events nobody
121/// has asked it for yet, and a walk stepping to the oldest event any relay returned would pass
122/// them by. Cut there, the oldest event left is where every relay has been read down to.
123///
124/// A short answer is the end of that relay's plane, as each walk's own end check reads it.
125pub(crate) struct PageFloor {
126    limit: usize,
127    until: Option<u64>,
128    floor: Option<u64>,
129}
130
131impl PageFloor {
132    pub(crate) fn of(query: &Query) -> Option<PageFloor> {
133        let limit = query.limit.filter(|l| query.paged && *l > 0)?;
134        Some(PageFloor { limit, until: query.until, floor: None })
135    }
136
137    /// One relay's answer.
138    pub(crate) fn note(&mut self, events: &[Event]) {
139        if events.len() < self.limit {
140            return;
141        }
142        let Some(bottom) = events.iter().map(|e| e.created_at.as_secs()).min() else { return };
143        // A full page no deeper than where it was asked from is a same-second wall, the walk's to judge.
144        if self.until.is_some_and(|until| bottom >= until) {
145            return;
146        }
147        self.floor = self.floor.max(Some(bottom));
148    }
149
150    pub(crate) fn cut(&self, events: &mut Vec<Event>) {
151        if let Some(floor) = self.floor {
152            events.retain(|e| e.created_at.as_secs() >= floor);
153        }
154    }
155}
156
157impl Query {
158    /// Does `event` satisfy this query?
159    pub fn matches(&self, event: &Event) -> bool {
160        // Compare via `Kind` (not raw u16) so this matches `to_filter`'s
161        // `Kind::Custom` normalization exactly — the live and in-memory paths must
162        // agree even at kind values that nostr maps to named variants.
163        if !self.kinds.is_empty() && !self.kinds.iter().any(|k| Kind::Custom(*k) == event.kind) {
164            return false;
165        }
166        if let Some(since) = self.since {
167            if event.created_at.as_secs() < since {
168                return false;
169            }
170        }
171        if let Some(until) = self.until {
172            if event.created_at.as_secs() > until {
173                return false;
174            }
175        }
176        if !self.authors.is_empty() && !self.authors.iter().any(|a| *a == event.pubkey.to_hex()) {
177            return false;
178        }
179        if !self.ids.is_empty() && !self.ids.iter().any(|i| *i == event.id.to_hex()) {
180            return false;
181        }
182        if !self.z_tags.is_empty() && !self.matches_single_letter("z", &self.z_tags, event) {
183            return false;
184        }
185        if !self.d_tags.is_empty() && !self.matches_single_letter("d", &self.d_tags, event) {
186            return false;
187        }
188        if !self.p_tags.is_empty() && !self.matches_single_letter("p", &self.p_tags, event) {
189            return false;
190        }
191        if !self.k_tags.is_empty() && !self.matches_single_letter("k", &self.k_tags, event) {
192            return false;
193        }
194        true
195    }
196
197    fn matches_single_letter(&self, name: &str, wanted: &[String], event: &Event) -> bool {
198        // ANY occurrence may satisfy the OR-set (an event can carry several `p` tags);
199        // relays match every tag instance, and matches() must agree with to_filter.
200        event.tags.iter().any(|t| {
201            let s = t.as_slice();
202            s.len() >= 2 && s[0] == name && wanted.iter().any(|w| *w == s[1])
203        })
204    }
205
206    /// Translate to a Nostr relay `Filter` for the live client.
207    pub fn to_filter(&self) -> Filter {
208        let mut filter = Filter::new();
209        if !self.kinds.is_empty() {
210            filter = filter.kinds(self.kinds.iter().map(|k| Kind::Custom(*k)));
211        }
212        if !self.z_tags.is_empty() {
213            filter = filter
214                .custom_tags(SingleLetterTag::LOWERCASE_Z, self.z_tags.clone());
215        }
216        if !self.d_tags.is_empty() {
217            filter = filter.identifiers(self.d_tags.clone());
218        }
219        if !self.p_tags.is_empty() {
220            filter = filter
221                .custom_tags(SingleLetterTag::LOWERCASE_P, self.p_tags.clone());
222        }
223        if !self.k_tags.is_empty() {
224            filter = filter
225                .custom_tags(SingleLetterTag::LOWERCASE_K, self.k_tags.clone());
226        }
227        if !self.authors.is_empty() {
228            let authors: Vec<PublicKey> =
229                self.authors.iter().filter_map(|a| PublicKey::from_hex(a).ok()).collect();
230            if !authors.is_empty() {
231                filter = filter.authors(authors);
232            }
233        }
234        if !self.ids.is_empty() {
235            let ids: Vec<EventId> =
236                self.ids.iter().filter_map(|i| EventId::from_hex(i).ok()).collect();
237            if !ids.is_empty() {
238                filter = filter.ids(ids);
239            }
240        }
241        if let Some(since) = self.since {
242            filter = filter.since(Timestamp::from_secs(since));
243        }
244        if let Some(until) = self.until {
245            filter = filter.until(Timestamp::from_secs(until));
246        }
247        if let Some(limit) = self.limit {
248            filter = filter.limit(limit);
249        }
250        filter
251    }
252}
253
254/// What one relay holds of a query, against what the asker holds.
255#[derive(Debug, Default, Clone, PartialEq, Eq)]
256pub struct Diff {
257    /// Held by the relay, not by the asker.
258    pub need: Vec<EventId>,
259    /// Held by the asker, not by the relay.
260    pub lack: Vec<EventId>,
261    /// Both sets were compared to the end; `false` when the budget of named ids came first.
262    pub complete: bool,
263}
264
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub enum ReconcileFail {
267    /// The relay does not reconcile sets (no NIP-77).
268    Unsupported,
269    /// It wants an identity this connection has not shown.
270    Gated,
271    /// No answer.
272    Unreached,
273    /// It answered, and the exchange broke.
274    Failed(String),
275}
276
277/// Set reconciliation with one relay (NIP-77): which of the events matching `query` each side
278/// lacks, without either sending the events. `held` is every matching event the asker holds, by
279/// id and `created_at`; naming stops at `budget` ids the asker lacks.
280#[async_trait::async_trait]
281pub trait Reconcile: Send + Sync {
282    async fn reconcile(&self, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail>;
283
284    /// [`Self::reconcile`] for a plane a relay may serve only to a connection authed as it.
285    async fn reconcile_plane(&self, _plane: &Keys, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail> {
286        self.reconcile(query, held, relay, budget).await
287    }
288}
289
290/// Publish + fetch over a set of relays. Async to match the live Nostr client (the
291/// whole app is tokio-based and network I/O is async); `async-trait` boxes the
292/// futures as `Send` so impls work inside spawned tasks.
293#[async_trait::async_trait]
294pub trait Transport {
295    /// Publish `event` to every relay in `relays`. Single-attempt: Ok if ≥1 relay ACKs.
296    async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String>;
297    /// Fetch events matching `query` across `relays`, unioned and deduped by id.
298    async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String>;
299
300    /// Fetch a group PLANE (events authored by `plane`'s pubkey), authenticating
301    /// to AUTH-gating relays AS that plane key. On a relay that requires "the
302    /// author you query must be authenticated" (Ditto), the shared client — authed
303    /// as the USER — can't fetch a plane, so its catch-up REQ is CLOSED and the
304    /// rotation/control is never folded (an offline member wedges at the old
305    /// epoch). This fetches over a connection authed as the plane itself. Required
306    /// (not defaulted — a default async-trait method forces a Sync bound on every
307    /// generic caller); the in-memory test relay just fetches (no auth).
308    async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String>;
309
310    /// DURABLE publish for security-critical control events (rekeys, bans, the invite registry, deletes):
311    /// retry **each relay independently** until it ACKs, up to [`MAX_PUBLISH_ATTEMPTS`] times, re-sending
312    /// only the relays that have NOT yet accepted. The already-signed `event` is broadcast as-is — the
313    /// crypto (e.g. a rekey's fresh root) is minted ONCE by the caller; this only hardens the broadcast,
314    /// so a relay blip or a brief local connectivity drop can't leave a rekey/ban under-propagated.
315    /// (Required, not defaulted — a default async-trait method would force a `Sync` bound on every
316    /// generic `T: Transport` caller. The in-memory test relay implements it as a single publish.)
317    async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String>;
318
319    /// Set reconciliation, where this transport can do it. Without it a plane is read by pages.
320    fn reconciler(&self) -> Option<&dyn Reconcile> {
321        None
322    }
323
324    /// A transport of its own for work that outlives the call. Without one, that work is done
325    /// before the call returns.
326    fn detached(&self) -> Option<std::sync::Arc<dyn Transport + Send + Sync>> {
327        None
328    }
329
330    /// Dial `relays` for plane reads ahead of the first one, in the background.
331    fn prewarm_planes(&self, _relays: &[String]) {}
332}
333
334/// Per-relay broadcast cap: retry each relay up to this many times before giving up on it (matching the
335/// NIP-17 deletable-DM durability). High enough to ride out a transient relay/local-network blip.
336pub const MAX_PUBLISH_ATTEMPTS: usize = 30;
337
338/// Residual union window past the moment a fetch's evidence requirement is met:
339/// relays finishing within it still merge synchronously; slower ones background-
340/// merge via the straggler sink.
341pub const RESIDUAL_GRACE_MS: u64 = 400;
342
343/// Time-bound on the Quorum majority wait, measured from the FIRST successful
344/// EOSE. Without it a 2-relay set with one dead relay would ride the dead
345/// relay's full timeout on every fetch; with it a degraded set costs
346/// first-success + this bound, and a healthy set returns at majority
347/// (typically far sooner).
348pub const QUORUM_GRACE_MS: u64 = 2000;
349
350/// Consecutive FULL-BUDGET failures before a relay trips.
351const BREAKER_TRIP_THRESHOLD: u8 = 2;
352
353/// How long a tripped relay stays demoted/skipped before its next fetch becomes
354/// the full-budget half-open probe.
355const BREAKER_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(30);
356
357/// Demoted per-relay timeout for tripped relays on Full drains (N ≥ 2, non-Tor
358/// only) — halves a Full drain's dead-relay tail without shrinking the evidence
359/// denominator.
360const TRIPPED_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(6);
361
362/// Hard ceiling on the initial confirmation: at least one relay must ACK within this window or the publish
363/// is a failure (we throw rather than spin on a dead/unreachable relay set forever). Once ONE relay accepts,
364/// the slow/ratelimited stragglers are threaded in the background (capped at MAX_PUBLISH_ATTEMPTS).
365pub const CONFIRM_WINDOW: std::time::Duration = std::time::Duration::from_secs(30);
366
367/// The retry engine behind a durable broadcast, factored out so it is unit-testable without a live
368/// client. `send_round(pending)` performs ONE broadcast attempt to the given still-pending relays and
369/// returns the subset that ACKed; this retries the rest (with `backoff` between rounds) until every relay
370/// has ACKed or `max_attempts` is reached. Returns `Ok` if at least one relay ever accepted (the event is
371/// durably out there; the fetch-union self-heals the stragglers), `Err` only if ZERO relays accepted
372/// after exhausting the retries. Dedups `relays` first so a duplicated url isn't double-counted.
373pub async fn durable_broadcast<'a, F>(
374    relays: &[String],
375    max_attempts: usize,
376    backoff: std::time::Duration,
377    mut send_round: F,
378) -> Result<(), String>
379where
380    F: FnMut(Vec<String>) -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send + 'a>>,
381{
382    let mut pending: Vec<String> = Vec::new();
383    for r in relays {
384        if !pending.contains(r) {
385            pending.push(r.clone());
386        }
387    }
388    let total = pending.len();
389    if total == 0 {
390        return Err("no relays to broadcast to".to_string());
391    }
392    for attempt in 0..max_attempts {
393        if pending.is_empty() {
394            break;
395        }
396        let acked = send_round(pending.clone()).await;
397        pending.retain(|r| !acked.contains(r));
398        if pending.is_empty() || attempt + 1 == max_attempts {
399            break;
400        }
401        if !backoff.is_zero() {
402            crate::rt::time::sleep(backoff).await;
403        }
404    }
405    if pending.len() < total {
406        Ok(()) // at least one relay accepted; the rest were retried to the cap
407    } else {
408        Err(format!("no relay accepted the event after {max_attempts} attempts each"))
409    }
410}
411
412/// Sink for "straggler" events — ones a SLOWER relay returns after a racing [`LiveTransport::fetch`]
413/// has already handed the caller the first relay's batch. The integrator (src-tauri) registers a
414/// handler that feeds them back through the normal Concord ingest path (`process_incoming` for
415/// content, control/rekey re-fold for authority). The transport stays DUMB: it dedups only by event
416/// id (identical bytes) and forwards everything else. Two relays disagreeing on the latest control
417/// commit are two editions with DIFFERENT ids, so BOTH reach the ingester, where the deterministic
418/// convergence engine (version floors + same-version tiebreakers) decides the winner. The transport
419/// never resolves conflicts itself.
420pub trait CommunityIngestSink: Send + Sync + 'static {
421    fn ingest_stragglers(&self, events: Vec<Event>);
422}
423
424static INGEST_SINK: std::sync::OnceLock<Box<dyn CommunityIngestSink>> = std::sync::OnceLock::new();
425
426/// Register the straggler ingest sink. Call once during app startup (mirrors `set_event_emitter`).
427pub fn set_community_ingest_sink(sink: Box<dyn CommunityIngestSink>) {
428    let _ = INGEST_SINK.set(sink);
429}
430
431fn submit_stragglers(events: Vec<Event>) {
432    if events.is_empty() {
433        return;
434    }
435    if let Some(sink) = INGEST_SINK.get() {
436        sink.ingest_stragglers(events);
437    }
438}
439
440/// Relay urls already added + connected into the shared pool this session, so `warm_client` can
441/// skip the per-call `add_relay` bookkeeping + whole-pool `connect()` sweep once a community's
442/// relays are established (relays auto-reconnect on drop, so the re-kick is redundant once warm).
443/// Keyed by session generation: an account swap bumps the generation, invalidating every entry
444/// (the pool is rebuilt for the new account).
445static WARMED_RELAYS: std::sync::LazyLock<std::sync::Mutex<(u64, std::collections::HashSet<String>)>> =
446    std::sync::LazyLock::new(|| std::sync::Mutex::new((0, std::collections::HashSet::new())));
447
448/// Forget a relay from the warm set — call when a relay is REMOVED from the pool (e.g. pruned after
449/// leaving a community), so a later `warm_client` for another community that shares it doesn't
450/// fast-path-skip the re-add and target a relay the pool no longer holds. Poison-tolerant: the set
451/// is pure optimization state, so a poisoned lock is recovered rather than propagated.
452pub fn forget_warmed_relay(url: &str) {
453    WARMED_RELAYS.lock().unwrap_or_else(|e| e.into_inner()).1.remove(url);
454}
455
456/// A network switch: every warm socket and breaker verdict belonged to the old route.
457pub fn on_transport_switch() {
458    // Replaced, not cleared: a cleared table keeps its peak allocation.
459    WARMED_RELAYS.lock().unwrap_or_else(|e| e.into_inner()).1 = Default::default();
460    RELAY_BREAKER.lock().unwrap_or_else(|e| e.into_inner()).1 = Default::default();
461}
462
463/// Per-relay failure tracker behind the fetch circuit breaker. Generation-keyed
464/// like [`WARMED_RELAYS`] (an account swap invalidates every entry). A trip is
465/// driven ONLY by consecutive failures at the relay's FULL timeout budget:
466/// failures at a demoted budget never count (a slow-but-honest relay must be
467/// able to recover via the post-cooldown full-budget probe), and a late EOSE
468/// surfacing in the background drain resets the entry (slow ≠ dead).
469#[derive(Default)]
470struct BreakerEntry {
471    consecutive_failures: u8,
472    tripped_until: Option<web_time::Instant>,
473}
474
475static RELAY_BREAKER: std::sync::LazyLock<
476    std::sync::Mutex<(u64, std::collections::HashMap<String, BreakerEntry>)>,
477> = std::sync::LazyLock::new(|| std::sync::Mutex::new((0, std::collections::HashMap::new())));
478
479/// Run `f` over the breaker map for `generation`, resetting the map if the
480/// generation advanced (pure optimization state — poison-tolerant). Generation
481/// is injected so tests pin a fixed one — other tests bump the REAL session
482/// generation concurrently, and a mid-test bump would wipe the map under us.
483fn with_breaker_at<R>(
484    generation: u64,
485    f: impl FnOnce(&mut std::collections::HashMap<String, BreakerEntry>) -> R,
486) -> R {
487    let mut guard = RELAY_BREAKER.lock().unwrap_or_else(|e| e.into_inner());
488    if guard.0 != generation {
489        guard.0 = generation;
490        guard.1 = Default::default();
491    }
492    f(&mut guard.1)
493}
494
495/// Is `url` inside a trip cooldown right now?
496/// Drop targets whose socket cannot progress without external intervention.
497///
498/// With pool auto-reconnect OFF (Vector owns reconnects), a relay sitting in
499/// `Terminated`/`Shutdown`/`Banned` will not move until the reconcile loop
500/// revives it — it is physically incapable of answering THIS call, so waiting
501/// out its per-relay budget yields the same nothing as skipping it. This is not
502/// the breaker's job: the breaker judges relays that ANSWER badly and must not
503/// shrink a Quorum/Full evidence denominator; a dead socket was never part of
504/// the reachable denominator to begin with. `Connecting`/`Pending`/unknown stay
505/// eligible (a just-added relay may finish its handshake mid-fetch), and an
506/// all-dead set falls back to the full list so the honest-timeout error paths
507/// still run.
508fn drop_unrevivable(targets: Vec<String>, is_unrevivable: impl Fn(&str) -> bool) -> Vec<String> {
509    let alive: Vec<String> = targets.iter().filter(|r| !is_unrevivable(r)).cloned().collect();
510    if alive.is_empty() {
511        targets
512    } else {
513        alive
514    }
515}
516
517/// [`drop_unrevivable`] against a live pool's current statuses.
518async fn drop_unrevivable_targets(client: &Client, targets: Vec<String>) -> Vec<String> {
519    let pool = client.relays().all().await;
520    drop_unrevivable(targets, |r| socket_dead(&pool, r))
521}
522
523/// Every target whose socket can still answer, with no fallback.
524async fn reachable_targets(client: &Client, targets: Vec<String>) -> Vec<String> {
525    let pool = client.relays().all().await;
526    targets.into_iter().filter(|r| !socket_dead(&pool, r)).collect()
527}
528
529fn socket_dead(pool: &std::collections::HashMap<RelayUrl, Relay>, url: &str) -> bool {
530    use nostr_sdk::prelude::RelayStatus;
531    RelayUrl::parse(url)
532        .ok()
533        .and_then(|u| pool.get(&u).map(|rl| matches!(rl.status(), RelayStatus::Terminated | RelayStatus::Shutdown | RelayStatus::Banned)))
534        .unwrap_or(false)
535}
536
537fn breaker_tripped(url: &str) -> bool {
538    breaker_tripped_at(crate::db::current_session_id(), url)
539}
540
541fn breaker_tripped_at(generation: u64, url: &str) -> bool {
542    with_breaker_at(generation, |map| {
543        map.get(url)
544            .and_then(|e| e.tripped_until)
545            .is_some_and(|t| web_time::Instant::now() < t)
546    })
547}
548
549/// Record a per-relay fetch outcome. Success resets the entry; a failure counts
550/// toward a trip only when the relay had its full timeout budget.
551fn breaker_record(url: &str, success: bool, full_budget: bool) {
552    breaker_record_at(crate::db::current_session_id(), url, success, full_budget)
553}
554
555fn breaker_record_at(generation: u64, url: &str, success: bool, full_budget: bool) {
556    with_breaker_at(generation, |map| {
557        if success {
558            map.remove(url);
559            return;
560        }
561        if !full_budget {
562            return;
563        }
564        let e = map.entry(url.to_string()).or_default();
565        e.consecutive_failures = e.consecutive_failures.saturating_add(1);
566        if e.consecutive_failures >= BREAKER_TRIP_THRESHOLD {
567            e.tripped_until = Some(web_time::Instant::now() + BREAKER_COOLDOWN);
568        }
569    })
570}
571
572/// The relays a plane read asks. A tripped relay is skipped to spare its dead
573/// timeout, unless that would leave nobody to ask — but it stays in the reachable
574/// set, unanswered, so a read that skipped one never claims full coverage.
575struct PlaneTargets {
576    ask: Vec<String>,
577    skipped: usize,
578}
579
580fn plane_targets(relays: Vec<String>, tripped: impl Fn(&str) -> bool) -> PlaneTargets {
581    let ask: Vec<String> = relays.iter().filter(|r| !tripped(r)).cloned().collect();
582    if ask.is_empty() {
583        return PlaneTargets { ask: relays, skipped: 0 };
584    }
585    let skipped = relays.len() - ask.len();
586    PlaneTargets { ask, skipped }
587}
588
589impl PlaneTargets {
590    /// The read's coverage, over the `asked` relays still standing after dead sockets left.
591    fn fetched(&self, events: Vec<Event>, answered: usize, asked: usize) -> PlaneFetch {
592        PlaneFetch { events, answered, attempted: asked + self.skipped }
593    }
594}
595
596/// Callers own their evidence tier. The chat plane is flat, linear data — an
597/// event exists or it doesn't — so no transport floor promotes its reads.
598/// Every site that draws a completeness-sensitive conclusion from an `until`
599/// walk (join-verify's genesis anchor, refound compaction, guestbook folds)
600/// REQUESTS Full explicitly at its own Query.
601fn effective_evidence(query: &Query) -> Evidence {
602    query.evidence
603}
604
605// ── Plane connection pool (fetch_plane) ─────────────────────────────────────
606// A plane fetch on an AUTH-gating relay needs a connection authed AS the plane
607// key. Re-connecting + re-NIP-42-authing on EVERY page/epoch dominates TTFB on
608// slow relays, so keep the authed connection warm and reuse it. Keyed by (plane
609// pubkey, relay set). Generation-scoped: an account swap holds account A's plane
610// SECRET keys, so the pool MUST clear (also freed by `clear_plane_pool`).
611//
612// A relay that never challenges needs no identity on the socket, so its plane
613// reads share one unauthenticated connection (`OPEN_PLANES`, keyed by relay).
614// Never the account client: the user's own subscriptions stay off that socket.
615
616struct PooledPlane {
617    client: Client,
618    last_used: web_time::Instant,
619    /// Tells a replacement apart from the entry a caller found dead.
620    id: u64,
621    /// Reads dialling or reading on it: neither the idle sweep nor the LRU closes it under them.
622    in_use: std::sync::Arc<std::sync::atomic::AtomicUsize>,
623}
624
625impl PooledPlane {
626    fn new(client: Client) -> Self {
627        PooledPlane { client, last_used: web_time::Instant::now(), id: next_pooled_id(), in_use: Default::default() }
628    }
629
630    fn idle(&self) -> bool {
631        self.in_use.load(std::sync::atomic::Ordering::Acquire) == 0
632    }
633}
634
635/// A read's hold on an open pool entry, released (and the idle clock restarted) on drop.
636struct InUse {
637    pool: &'static PlanePool,
638    generation: u64,
639    key: String,
640    id: u64,
641    count: std::sync::Arc<std::sync::atomic::AtomicUsize>,
642}
643
644impl Drop for InUse {
645    fn drop(&mut self) {
646        self.pool.touch(self.generation, &self.key, self.id);
647        self.count.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
648    }
649}
650
651fn next_pooled_id() -> u64 {
652    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
653    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
654}
655
656type PlaneSlots = (u64, std::collections::HashMap<String, PooledPlane>);
657
658#[derive(Default)]
659struct PlanePool {
660    /// The session generation the entries belong to, and the entries by key.
661    slots: std::sync::Mutex<PlaneSlots>,
662    /// Whether a sweep is waiting on the pool's next expiry: one at a time, none for an empty pool.
663    sweep_armed: std::sync::atomic::AtomicBool,
664}
665
666static PLANE_POOL: std::sync::LazyLock<PlanePool> = std::sync::LazyLock::new(PlanePool::default);
667static OPEN_PLANES: std::sync::LazyLock<PlanePool> = std::sync::LazyLock::new(PlanePool::default);
668
669/// A pooled connection unused for this long is closed — long enough to span a
670/// community's whole backfill, short enough not to hoard sockets.
671const PLANE_POOL_IDLE_TTL: std::time::Duration = if cfg!(test) {
672    std::time::Duration::from_millis(200)
673} else {
674    std::time::Duration::from_secs(90)
675};
676/// Hard cap on simultaneously-pooled plane connections (LRU-evicted).
677const PLANE_POOL_MAX: usize = 24;
678
679/// Remove the entries idle past the TTL, returning their clients to disconnect.
680fn take_expired(pool: &mut std::collections::HashMap<String, PooledPlane>, now: web_time::Instant) -> Vec<Client> {
681    let expired: Vec<String> = pool.iter()
682        .filter(|(_, p)| p.idle() && now.duration_since(p.last_used) >= PLANE_POOL_IDLE_TTL)
683        .map(|(k, _)| k.clone())
684        .collect();
685    expired.into_iter().filter_map(|k| pool.remove(&k)).map(|p| p.client).collect()
686}
687
688impl PlanePool {
689    fn lock(&self) -> std::sync::MutexGuard<'_, PlaneSlots> {
690        self.slots.lock().unwrap_or_else(|e| e.into_inner())
691    }
692
693    /// Close pooled connections as they pass the idle TTL, without waiting for another fetch to
694    /// notice: after a catch-up nothing fetches, and every connection would stay open all session.
695    fn arm_sweep(&'static self) {
696        if self.sweep_armed.swap(true, std::sync::atomic::Ordering::AcqRel) {
697            return;
698        }
699        // spawn-detached: drains the process-wide pool; touches no account state.
700        crate::rt::spawn(async move {
701            loop {
702                let (held, next) = {
703                    let g = self.lock();
704                    (!g.1.is_empty(), g.1.values().filter(|p| p.idle()).map(|p| p.last_used).min())
705                };
706                if !held {
707                    break;
708                }
709                // Only entries in use: look again a TTL on, as releasing one restarts its clock.
710                let due = next.map_or(PLANE_POOL_IDLE_TTL, |oldest| {
711                    PLANE_POOL_IDLE_TTL.saturating_sub(web_time::Instant::now().duration_since(oldest))
712                });
713                crate::rt::time::sleep(due).await;
714                let expired = take_expired(&mut self.lock().1, web_time::Instant::now());
715                disconnect_clients(expired);
716            }
717            self.sweep_armed.store(false, std::sync::atomic::Ordering::Release);
718            // An insert that saw the sweep still armed, just before it stood down.
719            if !self.lock().1.is_empty() {
720                self.arm_sweep();
721            }
722        });
723    }
724
725    /// Take a warm pooled client for `key` if one is fresh; also drops entries whose
726    /// idle TTL expired and resets the whole pool if the session generation advanced
727    /// (a swap). Returns `(Some(client_if_hit), clients_to_disconnect)`.
728    fn take(&self, generation: u64, key: &str) -> (Option<Client>, Vec<Client>) {
729        let (hit, evicted) = take_locked(&mut self.lock(), generation, key);
730        (hit.map(|(client, _)| client), evicted)
731    }
732
733    /// [`take`](Self::take) held for a read, pooling `make()` in the same step on a miss so
734    /// callers racing for one key share one client. `None` for a previous session's caller.
735    fn take_or_insert(&'static self, generation: u64, key: &str, make: impl FnOnce() -> Client) -> Option<(Client, InUse, Vec<Client>)> {
736        let mut g = self.lock();
737        if generation < g.0 {
738            return None;
739        }
740        let (_, mut evicted) = take_locked(&mut g, generation, key);
741        if !g.1.contains_key(key) {
742            evicted.extend(make_room(&mut g.1));
743            g.1.insert(key.to_string(), PooledPlane::new(make()));
744        }
745        let entry = &g.1[key];
746        entry.in_use.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
747        let hold = InUse { pool: self, generation, key: key.to_string(), id: entry.id, count: entry.in_use.clone() };
748        let client = entry.client.clone();
749        drop(g);
750        self.arm_sweep();
751        Some((client, hold, evicted))
752    }
753
754    /// Insert a freshly-built client for `key`, LRU-evicting if over the cap. Returns
755    /// ONLY the displaced LRU victim(s) to disconnect — NEVER the just-built `client`.
756    /// If we don't pool it (swapped mid-build, or a concurrent miss already pooled
757    /// this key), we return nothing: the caller still uses the client for this one
758    /// fetch and it closes on drop, so we must not disconnect the connection it's
759    /// about to run on.
760    fn insert(&'static self, generation: u64, key: String, client: Client) -> Vec<Client> {
761        let mut g = self.lock();
762        // Swapped mid-build, or a concurrent miss already pooled this key — don't pool
763        // ours (the caller uses it once, then it drops).
764        if g.0 != generation || g.1.contains_key(&key) {
765            return Vec::new();
766        }
767        let evicted = make_room(&mut g.1);
768        g.1.insert(key, PooledPlane::new(client));
769        drop(g);
770        self.arm_sweep();
771        evicted.into_iter().collect()
772    }
773
774    /// Restart `key`'s idle clock, if it is still entry `id`.
775    fn touch(&self, generation: u64, key: &str, id: u64) {
776        let mut g = self.lock();
777        if g.0 == generation {
778            if let Some(p) = g.1.get_mut(key).filter(|p| p.id == id) {
779                p.last_used = web_time::Instant::now();
780            }
781        }
782    }
783
784    /// Remove `key` if it is still entry `id`.
785    fn remove(&self, generation: u64, key: &str, id: u64) -> Option<Client> {
786        let mut g = self.lock();
787        if g.0 != generation || g.1.get(key).is_none_or(|p| p.id != id) {
788            return None;
789        }
790        g.1.remove(key).map(|p| p.client)
791    }
792
793    /// Empty the pool, stamped with the live generation so an insert still in flight from the
794    /// prior one is refused rather than pooled.
795    fn clear(&self) -> Vec<Client> {
796        let mut g = self.lock();
797        g.0 = crate::db::current_session_id();
798        g.1.drain().map(|(_, p)| p.client).collect()
799    }
800}
801
802/// Drops entries idle past the TTL, and every entry if the session generation advanced (a
803/// swap); a previous session's caller finds nothing and resets nothing. Returns the hit and
804/// the clients to disconnect.
805fn take_locked(g: &mut PlaneSlots, generation: u64, key: &str) -> (Option<(Client, u64)>, Vec<Client>) {
806    if generation < g.0 {
807        return (None, Vec::new());
808    }
809    let mut evicted: Vec<Client> = Vec::new();
810    if g.0 != generation {
811        evicted.extend(g.1.drain().map(|(_, p)| p.client));
812        g.0 = generation;
813    }
814    let now = web_time::Instant::now();
815    evicted.extend(take_expired(&mut g.1, now));
816    let hit = g.1.get_mut(key).map(|p| {
817        p.last_used = now;
818        (p.client.clone(), p.id)
819    });
820    (hit, evicted)
821}
822
823/// The least recently used entry no read holds, removed when the pool is full.
824fn make_room(pool: &mut std::collections::HashMap<String, PooledPlane>) -> Option<Client> {
825    if pool.len() < PLANE_POOL_MAX {
826        return None;
827    }
828    let lru_key = pool.iter().filter(|(_, p)| p.idle()).min_by_key(|(_, p)| p.last_used).map(|(k, _)| k.clone())?;
829    pool.remove(&lru_key).map(|p| p.client)
830}
831
832fn plane_pool_key(plane_pk: &str, relays: &[String]) -> String {
833    let mut rs: Vec<&str> = relays.iter().map(|s| s.as_str()).collect();
834    rs.sort_unstable();
835    let mut k = String::with_capacity(plane_pk.len() + 1 + rs.iter().map(|r| r.len() + 1).sum::<usize>());
836    k.push_str(plane_pk);
837    k.push('|');
838    k.push_str(&rs.join(","));
839    k
840}
841
842/// Disconnect the given clients off the hot path (never awaited under the lock).
843/// Runtime-guarded: `clear_plane_pool` is public and a bot author may call it from
844/// a non-tokio thread — `disconnect` off a live handle if there is one, else drop
845/// the client (its background task ends on drop).
846fn disconnect_clients(clients: Vec<Client>) {
847    if clients.is_empty() {
848        return;
849    }
850    match tokio::runtime::Handle::try_current() {
851        Ok(handle) => {
852            for c in clients {
853                handle.spawn(async move {
854                    c.disconnect().await;
855                });
856            }
857        }
858        Err(_) => drop(clients),
859    }
860}
861
862/// Close + drop every pooled plane connection. Call on account swap — the pooled
863/// clients are authenticated as the swapped-out account's community plane keys, and
864/// the open ones carry its plane reads. A network switch calls it too: a dial that
865/// failed on the old route is no reason to wait before the new one.
866pub fn clear_plane_pool() {
867    let mut drained = PLANE_POOL.clear();
868    drained.extend(OPEN_PLANES.clear());
869    disconnect_clients(drained);
870    GREETINGS.lock().unwrap_or_else(|e| e.into_inner()).clear();
871    for relay in PLANE_RELAYS.lock().unwrap_or_else(|e| e.into_inner()).1.values_mut() {
872        relay.dial_failed = None;
873    }
874}
875
876/// What a relay has shown of NIP-42 to the plane reads: `Auth` once it challenged or answered
877/// "auth-required:", `Open` once it served a read without either. `Auth` holds for the session.
878#[derive(Clone, Copy, PartialEq, Eq, Debug)]
879enum RelayGate {
880    Open,
881    Auth,
882}
883
884#[derive(Clone, Copy, Default)]
885struct PlaneRelay {
886    gate: Option<RelayGate>,
887    /// When its open connection last failed to dial: not redialled until `PLANE_REDIAL_GAP` passes,
888    /// or a dead relay would charge its connect wait to every page of a backfill.
889    dial_failed: Option<web_time::Instant>,
890}
891
892const PLANE_REDIAL_GAP: std::time::Duration = std::time::Duration::from_secs(30);
893
894/// Plane reads in flight on one open connection: relays cap the subscriptions a connection holds.
895const OPEN_READS_PER_RELAY: usize = 8;
896
897/// Keyed by [`normalize_relay_url`](crate::inbox_relays::normalize_relay_url), as `auth_gate:` is.
898static PLANE_RELAYS: std::sync::LazyLock<std::sync::Mutex<(u64, std::collections::HashMap<String, PlaneRelay>)>> =
899    std::sync::LazyLock::new(Default::default);
900
901fn with_plane_relay<R>(generation: u64, key: &str, f: impl FnOnce(&mut PlaneRelay) -> R) -> R {
902    let mut g = PLANE_RELAYS.lock().unwrap_or_else(|e| e.into_inner());
903    if generation < g.0 {
904        // A previous session's read neither reads nor resets this one's.
905        return f(&mut PlaneRelay::default());
906    }
907    if g.0 != generation {
908        *g = (generation, Default::default());
909    }
910    f(g.1.entry(key.to_string()).or_default())
911}
912
913/// How long a relay's AUTH challenge stands: one that stops asking (new software, a changed
914/// config) is read openly again within this.
915const AUTH_GATE_TTL_SECS: u64 = 3 * 24 * 60 * 60;
916/// A relay that challenges every connection rewrites its record at most this often.
917const AUTH_GATE_REFRESH_SECS: u64 = 24 * 60 * 60;
918
919fn auth_gate_setting(url: &str) -> String {
920    format!("auth_gate:{}", crate::inbox_relays::normalize_relay_url(url))
921}
922
923/// When this account last recorded the relay's AUTH challenge (unix secs). A record without a
924/// time reads as none.
925fn auth_gate_at(url: &str) -> Option<u64> {
926    crate::db::get_sql_setting(auth_gate_setting(url)).ok().flatten()?.parse().ok()
927}
928
929fn now_secs() -> u64 {
930    crate::clock::now_secs()
931}
932
933/// Whether the relay has challenged this account within [`AUTH_GATE_TTL_SECS`].
934pub(crate) fn auth_gate_live(url: &str) -> bool {
935    auth_gate_at(url).is_some_and(|at| now_secs().saturating_sub(at) < AUTH_GATE_TTL_SECS)
936}
937
938/// Record a challenge from the relay now, unless one was recorded within a day.
939pub(crate) fn note_auth_gate(url: &str) {
940    let now = now_secs();
941    if auth_gate_at(url).is_some_and(|at| now.saturating_sub(at) < AUTH_GATE_REFRESH_SECS) {
942        return;
943    }
944    let _ = crate::db::set_sql_setting(auth_gate_setting(url), now.to_string());
945}
946
947/// The relay's gate, seeded from the challenges this account has recorded (`auth_gate:`).
948fn plane_gate(generation: u64, url: &str) -> Option<RelayGate> {
949    let key = crate::inbox_relays::normalize_relay_url(url);
950    if let Some(gate) = with_plane_relay(generation, &key, |r| r.gate) {
951        return Some(gate);
952    }
953    auth_gate_live(&key).then(|| {
954        mark_auth(generation, &key);
955        RelayGate::Auth
956    })
957}
958
959fn mark_auth(generation: u64, key: &str) {
960    with_plane_relay(generation, key, |r| r.gate = Some(RelayGate::Auth));
961}
962
963/// [`mark_auth`], recorded for the account too (the volley routes by it), unless the account
964/// changed since the read began.
965fn learn_auth(generation: u64, key: &str) {
966    mark_auth(generation, key);
967    if crate::db::current_session_id() != generation {
968        return;
969    }
970    note_auth_gate(key);
971}
972
973fn redial_waits(generation: u64, key: &str) -> bool {
974    with_plane_relay(generation, key, |r| r.dial_failed).is_some_and(|at| at.elapsed() < PLANE_REDIAL_GAP)
975}
976
977/// Plane reconciliations open at once on one relay: relays cap NIP-77 sessions per connection
978/// (Magnitude at 8), and DM catch-up shares the connection.
979const NEG_SESSIONS_PER_RELAY: usize = 4;
980
981fn neg_permits(url: &str) -> std::sync::Arc<tokio::sync::Semaphore> {
982    type Permits = std::collections::HashMap<String, std::sync::Arc<tokio::sync::Semaphore>>;
983    static PERMITS: std::sync::LazyLock<std::sync::Mutex<Permits>> = std::sync::LazyLock::new(Default::default);
984    let mut permits = PERMITS.lock().unwrap_or_else(|e| e.into_inner());
985    permits.entry(crate::inbox_relays::normalize_relay_url(url)).or_insert_with(|| std::sync::Arc::new(tokio::sync::Semaphore::new(NEG_SESSIONS_PER_RELAY))).clone()
986}
987
988fn open_read_permits(key: &str) -> std::sync::Arc<tokio::sync::Semaphore> {
989    type Permits = std::collections::HashMap<String, std::sync::Arc<tokio::sync::Semaphore>>;
990    static PERMITS: std::sync::LazyLock<std::sync::Mutex<Permits>> = std::sync::LazyLock::new(Default::default);
991    let mut permits = PERMITS.lock().unwrap_or_else(|e| e.into_inner());
992    permits.entry(key.to_string()).or_insert_with(|| std::sync::Arc::new(tokio::sync::Semaphore::new(OPEN_READS_PER_RELAY))).clone()
993}
994
995/// The pooled open client for `key`, built on a miss with the per-plane connections' lane and
996/// relay options, so it routes as they do.
997fn open_entry(generation: u64, key: &str) -> Option<(Client, InUse)> {
998    let (client, hold, evicted) = OPEN_PLANES.take_or_insert(generation, key, || {
999        crate::apply_transport(
1000            nostr_sdk::prelude::Client::builder().notification_channel_size(std::num::NonZeroUsize::MIN),
1001            crate::transport::Lane::Shared,
1002        )
1003        .build()
1004    })?;
1005    disconnect_clients(evicted);
1006    Some((client, hold))
1007}
1008
1009async fn open_relay(client: &Client, url: &str) -> Option<Relay> {
1010    if let Ok(Some(relay)) = client.relay(url).await {
1011        return Some(relay);
1012    }
1013    client.add_managed_relay(url).capabilities(crate::community_relay_capabilities()).await.ok()?;
1014    client.relay(url).await.ok().flatten()
1015}
1016
1017/// The relay's open plane connection, held for the read, dialled when it has none. `None` when
1018/// the dial failed: the relay was never reached.
1019async fn open_plane_client(generation: u64, url: &str, key: &str, timeout: std::time::Duration) -> Option<(Client, InUse)> {
1020    use RelayStatus::{Banned, Connected, Connecting, Initialized, Pending, Shutdown, Sleeping, Terminated};
1021    let (mut client, mut hold) = open_entry(generation, key)?;
1022    let mut relay = open_relay(&client, url).await?;
1023    if !matches!(relay.status(), Initialized | Pending | Connecting | Connected | Sleeping) {
1024        if redial_waits(generation, key) {
1025            return None;
1026        }
1027        // A dropped socket is replaced, never redialled: reconnecting the relay it ran on can
1028        // leave it Pending with no connection task behind it.
1029        disconnect_clients(OPEN_PLANES.remove(generation, key, hold.id).into_iter().collect());
1030        (client, hold) = open_entry(generation, key)?;
1031        relay = open_relay(&client, url).await?;
1032    }
1033    if matches!(relay.status(), Initialized | Sleeping) {
1034        if redial_waits(generation, key) {
1035            return None;
1036        }
1037        watch_for_challenge(generation, key, &relay);
1038        GREETINGS.lock().unwrap_or_else(|e| e.into_inner()).insert((generation, key.to_string()), (hold.id, relay.notifications()));
1039        relay.connect();
1040    }
1041    relay.wait_for_connection(crate::relay_connect_timeout(timeout)).await;
1042    match relay.status() {
1043        Connected => {
1044            with_plane_relay(generation, key, |r| r.dial_failed = None);
1045            Some((client, hold))
1046        }
1047        Terminated | Banned | Shutdown => {
1048            with_plane_relay(generation, key, |r| r.dial_failed = Some(web_time::Instant::now()));
1049            None
1050        }
1051        // Still connecting: the REQ queues on the socket and the read counts against the relay.
1052        _ => Some((client, hold)),
1053    }
1054}
1055
1056/// Marks the relay `Auth` when it challenges on this socket outside any read: on connect, before
1057/// the first REQ.
1058fn watch_for_challenge(generation: u64, key: &str, relay: &Relay) {
1059    #[cfg(test)]
1060    if UNWATCHED.lock().unwrap().contains(key) {
1061        return;
1062    }
1063    let mut notifications = relay.notifications();
1064    let key = key.to_string();
1065    // spawn-detached: one socket's frames into the generation-keyed gate map; no account state.
1066    crate::rt::spawn(async move {
1067        while let Some(n) = notifications.next().await {
1068            match n {
1069                RelayNotification::Message { message } if matches!(*message, RelayMessage::Auth { .. }) => {
1070                    return mark_auth(generation, &key);
1071                }
1072                RelayNotification::RelayStatus { status: RelayStatus::Terminated | RelayStatus::Shutdown | RelayStatus::Banned } => return,
1073                _ => {}
1074            }
1075        }
1076    });
1077}
1078
1079type Frames = std::pin::Pin<Box<dyn futures_util::Stream<Item = RelayNotification> + Send>>;
1080
1081/// Each fresh open socket's frames from before it connected, by pool entry, until a read settles
1082/// its gate. The watcher above marks a challenge whenever it runs, which can be after a read has
1083/// already reached EOSE.
1084static GREETINGS: std::sync::LazyLock<std::sync::Mutex<Greetings>> = std::sync::LazyLock::new(Default::default);
1085
1086/// `(generation, relay key)` to the pool entry the frames belong to, and the frames.
1087type Greetings = std::collections::HashMap<(u64, String), (u64, Frames)>;
1088
1089#[cfg(test)]
1090static UNWATCHED: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());
1091
1092/// The relay's gate once a read on pool entry `id` has its EOSE. A relay challenges on connect
1093/// before it answers any REQ, so that challenge is already among the socket's frames by now.
1094fn settle_gate(generation: u64, key: &str, id: u64) -> RelayGate {
1095    use futures_util::{FutureExt, StreamExt};
1096    let mut greetings = GREETINGS.lock().unwrap_or_else(|e| e.into_inner());
1097    let slot = (generation, key.to_string());
1098    if greetings.get(&slot).is_some_and(|(held, _)| *held == id) {
1099        let (_, mut frames) = greetings.remove(&slot).expect("held above");
1100        while let Some(Some(frame)) = frames.next().now_or_never() {
1101            if matches!(frame, RelayNotification::Message { ref message } if matches!(**message, RelayMessage::Auth { .. })) {
1102                mark_auth(generation, key);
1103                break;
1104            }
1105        }
1106    }
1107    // Still holding the greetings: a read settling after this one sees what this one learned.
1108    with_plane_relay(generation, key, |r| *r.gate.get_or_insert(RelayGate::Open))
1109}
1110
1111/// Returns once a relay that challenged on `frames` has had its AUTH answered, accepted or not,
1112/// or `budget` has passed; at once for one that never challenged.
1113async fn authenticated(mut frames: Frames, budget: std::time::Duration) {
1114    use futures_util::{FutureExt, StreamExt};
1115    let deadline = crate::rt::time::Instant::now() + budget;
1116    let mut challenged = false;
1117    loop {
1118        let frame = if challenged {
1119            match crate::rt::time::timeout_at(deadline, frames.next()).await {
1120                Ok(Some(frame)) => frame,
1121                _ => return,
1122            }
1123        } else {
1124            match frames.next().now_or_never() {
1125                Some(Some(frame)) => frame,
1126                _ => return,
1127            }
1128        };
1129        match frame {
1130            RelayNotification::Authenticated | RelayNotification::AuthenticationFailed => return,
1131            RelayNotification::Message { ref message } if matches!(**message, RelayMessage::Auth { .. }) => challenged = true,
1132            _ => {}
1133        }
1134    }
1135}
1136
1137enum OpenRead {
1138    Read(Vec<Event>),
1139    /// It asks for AUTH: read it over a connection authed as the plane instead.
1140    Gated,
1141    Failed,
1142    /// Never reached, so out of the denominator like a dead socket.
1143    Unreachable,
1144}
1145
1146async fn read_open_plane(generation: u64, url: &str, filter: Filter, timeout: std::time::Duration) -> OpenRead {
1147    let key = crate::inbox_relays::normalize_relay_url(url);
1148    let Some((client, hold)) = open_plane_client(generation, url, &key, timeout).await else { return OpenRead::Unreachable };
1149    let permits = open_read_permits(&key);
1150    let _permit = permits.acquire().await;
1151    let (gate, events) = match read_relay_eose(&client, url, vec![filter], timeout, true).await {
1152        Ok(events) => (settle_gate(generation, &key, hold.id), events),
1153        Err(ReadFail::Gated) => (RelayGate::Auth, Vec::new()),
1154        Err(ReadFail::Eose(_)) => return OpenRead::Failed,
1155    };
1156    match gate {
1157        RelayGate::Open => OpenRead::Read(events),
1158        RelayGate::Auth => {
1159            learn_auth(generation, &key);
1160            // Out of the pool but left open: other reads may still be on it, and it closes
1161            // when the last of them drops it.
1162            drop(OPEN_PLANES.remove(generation, &key, hold.id));
1163            OpenRead::Gated
1164        }
1165    }
1166}
1167
1168/// Whether Full-drain timeout demotion may apply. Over an anonymity network EVERY relay is
1169/// legitimately slow — a first congested pass must not cascade into pool-wide starvation, so
1170/// demotion applies on Clearnet only.
1171fn demotion_allowed() -> bool {
1172    crate::transport::preference() == Some(crate::transport::Kind::Clearnet)
1173}
1174
1175/// Dial every held community's relay set on the shared warm client, ahead of
1176/// first use — the volley otherwise pays the TLS/WS dial (and the gating
1177/// relay's NIP-42 challenge round) inside its own wall time. Fire-and-forget.
1178/// Session-gated between the per-account DB reads and the shared-client
1179/// mutation: a swap mid-read must not warm account A's relays under B.
1180pub async fn prewarm_held_communities() {
1181    crate::db::scoped(async move {
1182        let mut relays: Vec<String> =
1183            crate::db::community::held_community_relays().unwrap_or_default().into_iter().collect();
1184        relays.sort();
1185        if relays.is_empty() {
1186            return;
1187        }
1188        let Ok(client) = LiveTransport::warm_client(&relays, std::time::Duration::from_secs(4)).await
1189        else {
1190            return;
1191        };
1192        // Elicit each relay's NIP-42 challenge NOW: a gating relay challenges on
1193        // the first gated REQ (never on connect), and challenges are
1194        // per-connection — without this the volley's priming pays the full
1195        // challenge round inside its own wall time every boot. The responder
1196        // remembers the challenge; the volley's prime then replays it instantly.
1197        crate::community::v2::streamauth::ensure_responder(&client);
1198        let probe = Keys::generate();
1199        let filter = Query {
1200            kinds: vec![crate::community::v2::stream::KIND_WRAP],
1201            authors: vec![probe.public_key().to_hex()],
1202            limit: Some(1),
1203            ..Default::default()
1204        }
1205        .to_filter();
1206        let mut elicits = futures_util::stream::FuturesUnordered::new();
1207        for r in &relays {
1208            let c = client.clone();
1209            let f = filter.clone();
1210            let r = r.clone();
1211            elicits.push(async move {
1212                let _ = fetch_relay_eose_filters(&c, &r, vec![f], std::time::Duration::from_secs(3)).await;
1213            });
1214        }
1215        use futures_util::StreamExt;
1216        while elicits.next().await.is_some() {}
1217    })
1218    .await
1219}
1220
1221/// Why a genuine-EOSE read failed — callers that retry must not treat a
1222/// burned deadline like an AUTH-gate CLOSED (the retry exists for the
1223/// latter; repeating the former doubles a dead relay's cost).
1224#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1225pub enum EoseFail {
1226    /// The relay CLOSED the REQ (includes auth-required).
1227    Closed,
1228    /// The deadline elapsed without an EOSE.
1229    Deadline,
1230    /// No usable connection (lookup/send failure, shutdown, stream end).
1231    Gone,
1232}
1233
1234/// Fetch one relay to GENUINE EOSE, or fail. `Client::fetch_events_from` (and
1235/// the whole nostr-sdk 0.44 fetch stack) returns `Ok(collected)` on timeout,
1236/// disconnect, and relay-CLOSED alike — success does NOT mean EOSE, which would
1237/// let a dead relay count as quorum evidence and return confident empties. So
1238/// the verdict is read from the relay's own notification stream instead: EOSE =
1239/// success (empty included — a quiet coordinate is a legitimate answer);
1240/// CLOSED / shutdown / deadline = failure.
1241///
1242/// Public for diagnostics (the v2 plane probe); production fetches go through
1243/// [`Transport::fetch`], which layers the evidence tiers on top.
1244pub async fn fetch_relay_eose(
1245    client: &Client,
1246    url: &str,
1247    filter: Filter,
1248    timeout: std::time::Duration,
1249) -> Result<Vec<Event>, ()> {
1250    fetch_relay_eose_filters(client, url, vec![filter], timeout).await.map_err(|_| ())
1251}
1252
1253/// [`fetch_relay_eose`] for a multi-filter REQ (one frame, many filters — the
1254/// batched-volley shape). Raw REQ/CLOSE frames: the subscribe builder takes a
1255/// single filter, and the auto-close bookkeeping is unnecessary for a one-shot
1256/// read we close ourselves on every exit.
1257pub async fn fetch_relay_eose_filters(
1258    client: &Client,
1259    url: &str,
1260    filters: Vec<Filter>,
1261    timeout: std::time::Duration,
1262) -> Result<Vec<Event>, EoseFail> {
1263    read_relay_eose(client, url, filters, timeout, false).await.map_err(|fail| match fail {
1264        ReadFail::Gated => EoseFail::Closed,
1265        ReadFail::Eose(fail) => fail,
1266    })
1267}
1268
1269enum ReadFail {
1270    /// CLOSED "auth-required:", or on an open plane socket any challenge.
1271    Gated,
1272    Eose(EoseFail),
1273}
1274
1275/// On an open plane socket (`open_socket`) a challenge is a gate, since a relay may challenge and
1276/// then serve an unauthenticated REQ less than it holds, and a socket that closed ends the read.
1277async fn read_relay_eose(
1278    client: &Client,
1279    url: &str,
1280    filters: Vec<Filter>,
1281    timeout: std::time::Duration,
1282    open_socket: bool,
1283) -> Result<Vec<Event>, ReadFail> {
1284    use EoseFail::{Closed, Deadline, Gone};
1285    let relay = client.relay(url).await.map_err(|_| ReadFail::Eose(Gone))?.ok_or(ReadFail::Eose(Gone))?;
1286    // Subscribe to notifications BEFORE the REQ so the EOSE can't slip past.
1287    let mut notifications = relay.notifications();
1288    let sub_id = SubscriptionId::generate();
1289    // Close on every exit — this REQ bypasses the pool's subscription map.
1290    // Constructed BEFORE the send: cancellation during the send await must
1291    // not leave a queued REQ unguarded (a CLOSE for a never-sent REQ is
1292    // harmless). Drop can't await, so the CLOSE rides a detached task; all
1293    // callers drop on runtime threads (a JNI-thread drop would silently skip
1294    // the CLOSE, not panic).
1295    struct CloseGuard(Relay, SubscriptionId);
1296    impl Drop for CloseGuard {
1297        fn drop(&mut self) {
1298            let relay = self.0.clone();
1299            let id = self.1.clone();
1300            // spawn-detached: sends a relay CLOSE, touches no account state.
1301            crate::rt::spawn(async move {
1302                let _ = relay
1303                    .send_msg(nostr_sdk::prelude::ClientMessage::Close(std::borrow::Cow::Owned(id)))
1304                    .await;
1305            });
1306        }
1307    }
1308    let _close = CloseGuard(relay.clone(), sub_id.clone());
1309    relay
1310        .send_msg(nostr_sdk::prelude::ClientMessage::Req {
1311            subscription_id: std::borrow::Cow::Borrowed(&sub_id),
1312            filters: filters.into_iter().map(std::borrow::Cow::Owned).collect(),
1313        })
1314        .await
1315        .map_err(|_| ReadFail::Eose(Gone))?;
1316    let deadline = crate::rt::time::Instant::now() + timeout;
1317    let mut events: Vec<Event> = Vec::new();
1318    let mut seen: std::collections::HashSet<EventId> = std::collections::HashSet::new();
1319    loop {
1320        // 0.45 hands back a Stream, so there's no broadcast-lag case to drain:
1321        // the stream ending is the closed case, and the deadline is still a
1322        // failure rather than a false EOSE.
1323        let notification = match crate::rt::time::timeout_at(deadline, notifications.next()).await {
1324            Ok(Some(n)) => n,
1325            Ok(None) => return Err(ReadFail::Eose(Gone)),
1326            Err(_) => return Err(ReadFail::Eose(Deadline)), // timeout is NOT EOSE
1327        };
1328        match notification {
1329            RelayNotification::Event { subscription_id, event }
1330                if subscription_id == sub_id && seen.insert(event.id) =>
1331            {
1332                events.push(*event);
1333            }
1334            RelayNotification::Message { message } => match *message {
1335                RelayMessage::Event { subscription_id, event }
1336                    if *subscription_id == sub_id && seen.insert(event.id) =>
1337                {
1338                    events.push(event.into_owned());
1339                }
1340                RelayMessage::EndOfStoredEvents(id) if *id == sub_id => return Ok(events),
1341                RelayMessage::Closed { subscription_id, message } if *subscription_id == sub_id => {
1342                    return Err(match MachineReadablePrefix::parse(&message) {
1343                        Some(MachineReadablePrefix::AuthRequired) => ReadFail::Gated,
1344                        _ => ReadFail::Eose(Closed),
1345                    });
1346                }
1347                RelayMessage::Auth { .. } if open_socket => return Err(ReadFail::Gated),
1348                _ => {}
1349            },
1350            RelayNotification::RelayStatus { status: nostr_sdk::prelude::RelayStatus::Shutdown } => {
1351                return Err(ReadFail::Eose(Gone));
1352            }
1353            RelayNotification::RelayStatus { status: RelayStatus::Terminated | RelayStatus::Banned } if open_socket => {
1354                return Err(ReadFail::Eose(Gone));
1355            }
1356            _ => {}
1357        }
1358    }
1359}
1360
1361/// Return-timing state machine for a multi-relay fetch: feed it per-relay
1362/// outcomes and ask whether the query's [`Evidence`] requirement is met. Pure
1363/// sync logic so the quorum math is unit-testable without a client.
1364pub(crate) struct UnionPlan {
1365    attempted: usize,
1366    successes: usize,
1367    resolved: usize,
1368    evidence: Evidence,
1369}
1370
1371impl UnionPlan {
1372    pub(crate) fn new(evidence: Evidence, attempted: usize) -> Self {
1373        Self { attempted, successes: 0, resolved: 0, evidence }
1374    }
1375
1376    pub(crate) fn record(&mut self, success: bool) {
1377        self.resolved += 1;
1378        if success {
1379            self.successes += 1;
1380        }
1381    }
1382
1383    /// The tier's coverage requirement is met — the fetch may return after the
1384    /// residual merge window. Note Full's requirement is all-RESOLVED (a dead
1385    /// relay's timeout is a resolution); the zero-success case errors at the
1386    /// call site regardless of tier.
1387    pub(crate) fn satisfied(&self) -> bool {
1388        match self.evidence {
1389            Evidence::Fast => self.successes >= 1,
1390            Evidence::Quorum => self.successes > (self.attempted / 2),
1391            Evidence::Full => self.resolved >= self.attempted,
1392        }
1393    }
1394
1395    /// Every relay resolved — nothing left to wait for.
1396    pub(crate) fn exhausted(&self) -> bool {
1397        self.resolved >= self.attempted
1398    }
1399
1400    pub(crate) fn successes(&self) -> usize {
1401        self.successes
1402    }
1403
1404    pub(crate) fn attempted(&self) -> usize {
1405        self.attempted
1406    }
1407}
1408
1409/// Hold a community network op while the chosen network is still connecting, bounded by its
1410/// ready-wait budget: a refused send would otherwise read as "no relay accepted the event".
1411async fn wait_transport_ready() -> Result<(), String> {
1412    let budget = crate::transport::budget(crate::transport::Op::ReadyWait, std::time::Duration::ZERO);
1413    crate::transport::wait_ready(budget).await.map_err(|why| {
1414        // A block only the user can lift says so; waiting longer would not help.
1415        if crate::transport::status::waits_for_user() {
1416            return why;
1417        }
1418        let label = crate::transport::preference().map_or("Vector", crate::transport::Kind::label);
1419        format!("{label} is still connecting. Wait a moment and try again.")
1420    })
1421}
1422
1423/// Targets the account's network can never reach (another network's names, I2P-Only) leave the
1424/// set, like a dead socket: they were never part of the reachable denominator. An all-refused
1425/// set fails with the reason.
1426fn drop_refused(targets: Vec<String>) -> Result<Vec<String>, String> {
1427    if targets.is_empty() {
1428        return Ok(targets);
1429    }
1430    let reachable: Vec<String> = targets.iter().filter(|r| crate::transport::refuses(r).is_none()).cloned().collect();
1431    if reachable.is_empty() {
1432        let label = crate::transport::preference().map_or("this network", crate::transport::Kind::label);
1433        return Err(format!("None of this community's relays are reachable on {label}."));
1434    }
1435    Ok(reachable)
1436}
1437
1438/// Shed pooled Community relays from `candidates` that no JOINED community still needs. Used by both
1439/// the leave path (relays of a community we left) and the invite-preload TTL cleanup (relays an
1440/// unsolicited/declined invite warmed but never became a join, #297). A relay is kept if a held
1441/// community lists it or still listens on it after a move, if it is a Discovery Relay, or if it
1442/// carries the READ or WRITE flag (the user's own relays). A pruned relay re-warms automatically if
1443/// its invite is later accepted (the join's subscription re-adds it), so pruning a still-pending
1444/// invite's relay is safe.
1445pub async fn prune_unneeded_community_relays(candidates: &[String]) {
1446    if candidates.is_empty() {
1447        return;
1448    }
1449    let Some(client) = crate::state::nostr_client() else { return };
1450    prune_relays(&client, candidates, &still_needed_relays()).await;
1451}
1452
1453/// Normalised urls of every relay a held community lists or still listens on.
1454fn still_needed_relays() -> std::collections::HashSet<String> {
1455    use crate::inbox_relays::normalize_relay_url;
1456    let mut needed: std::collections::HashSet<String> =
1457        crate::db::community::held_community_relays().unwrap_or_default().iter().map(|r| normalize_relay_url(r)).collect();
1458    for id in crate::db::community::list_community_ids().unwrap_or_default() {
1459        let retired = crate::community::v2::service::retired_relays(&crate::simd::hex::bytes_to_hex_32(&id.0));
1460        needed.extend(retired.iter().map(|r| normalize_relay_url(r)));
1461    }
1462    needed
1463}
1464
1465async fn prune_relays(pool: &Client, candidates: &[String], still_needed: &std::collections::HashSet<String>) {
1466    use crate::inbox_relays::normalize_relay_url;
1467    // all(): community relays carry GOSSIP, so they're absent from `relays()` (READ/WRITE only).
1468    let pooled = pool.relays().all().await;
1469    for url in candidates {
1470        let norm = normalize_relay_url(url);
1471        if still_needed.contains(&norm) || crate::state::discovery_relay_iter().any(|d| normalize_relay_url(d) == norm) {
1472            continue;
1473        }
1474        let Ok(parsed) = nostr_sdk::prelude::RelayUrl::parse(url) else { continue };
1475        if let Some(relay) = pooled.get(&parsed) {
1476            // The flags themselves: can_read()/can_write() also count the GOSSIP every community relay has.
1477            if relay.capabilities().load().has_any(RelayCapabilities::READ | RelayCapabilities::WRITE) {
1478                continue;
1479            }
1480        }
1481        let _ = pool.remove_relay(parsed).force().await; // plain remove refuses GOSSIP
1482        forget_warmed_relay(url);
1483    }
1484}
1485
1486/// Production [`Transport`] over the live Nostr network.
1487///
1488/// Reuses the app's persistent client (`state::nostr_client`) — already connected to the user's relays,
1489/// which ARE the Community's relays — and targets sends/fetches at the Community relay set explicitly. No
1490/// per-call cold handshake (a throwaway client paid ~4s of TLS + relay handshake on every op). Any Community
1491/// relay the pool doesn't already hold is added idempotently, mirroring the realtime subscription.
1492pub struct LiveTransport {
1493    timeout: std::time::Duration,
1494}
1495
1496impl Default for LiveTransport {
1497    fn default() -> Self {
1498        Self::with_timeout(std::time::Duration::from_secs(10))
1499    }
1500}
1501
1502impl LiveTransport {
1503    pub fn new() -> Self {
1504        Self::default()
1505    }
1506
1507    /// Tor-aware: every caller's budget is sized for clearnet, and a community fetch
1508    /// that expires returns the same "no relay answered" as a genuinely dead relay —
1509    /// so under Tor the control plane reads as unreachable and rekey/catch-up silently
1510    /// stop. Raised to a floor here rather than at ~65 call sites; `max()` keeps any
1511    /// caller that already asked for longer.
1512    pub fn with_timeout(timeout: std::time::Duration) -> Self {
1513        Self { timeout: crate::relay_request_timeout(timeout) }
1514    }
1515
1516    /// Grab the app's persistent client and make sure it's connected to `relays` — the Community's relays
1517    /// are the user's own relays, so this is almost always a pure no-op (already in the warm pool). A relay
1518    /// the pool doesn't hold yet is added idempotently (mirrors what the realtime subscription does), then
1519    /// `connect()` kicks it without disturbing the already-connected majority. Never shut this client down:
1520    /// it is shared. Errors only if there is no client yet or every relay url was invalid.
1521    pub(crate) async fn warm_client(relays: &[String], connect_timeout: std::time::Duration) -> Result<Client, String> {
1522        if relays.is_empty() {
1523            return Err("community has no relays configured".to_string());
1524        }
1525        // Before the warmed-cache fast path, so a relay warmed before a switch still waits:
1526        // while the chosen network is connecting every relay connect is refused at once.
1527        wait_transport_ready().await?;
1528        let client = crate::state::nostr_client().ok_or_else(|| "nostr client not initialized".to_string())?;
1529
1530        // Fast path: every one of these relays was already warmed this session → the pool holds and
1531        // (auto-)maintains them, so skip the redundant add_relay + connect churn that otherwise runs on
1532        // EVERY fetch/publish. Account swaps bump the generation, dropping the cache.
1533        let generation = crate::db::current_session_id();
1534        {
1535            let warmed = WARMED_RELAYS.lock().unwrap_or_else(|e| e.into_inner());
1536            if warmed.0 == generation && relays.iter().all(|r| warmed.1.contains(r)) {
1537                return Ok(client);
1538            }
1539        }
1540
1541        // `add_relay` returns Ok(true) if NEWLY added, Ok(false) if the pool already held it.
1542        // Community relays join GOSSIP-only (see `community_relay_capabilities`) so they stay warm
1543        // without pulling the user's DM/profile traffic onto relays they don't own — omitting the
1544        // capabilities would default them to READ|WRITE and leak the user's own traffic there. An
1545        // overlap relay already in the pool as a user relay keeps its READ+WRITE (add_relay no-ops).
1546        let mut added: Vec<&String> = Vec::new();
1547        let mut succeeded: Vec<&String> = Vec::new();
1548        for url in relays {
1549            match client
1550                .add_managed_relay(url.as_str())
1551                .capabilities(crate::community_relay_capabilities())
1552                .await
1553            {
1554                Ok(true) => { added.push(url); succeeded.push(url); }
1555                Ok(false) => { succeeded.push(url); }
1556                Err(_) => {}
1557            }
1558        }
1559        if succeeded.is_empty() {
1560            return Err("no valid community relays could be added".to_string());
1561        }
1562        if !added.is_empty() {
1563            // A relay we weren't already connected to (a Community on non-default relays): wait up to
1564            // the caller's cap for its socket, or the immediate fetch/send reaches zero relays. Only the
1565            // new relays connect, each on the transport's own budget: a pool-wide `try_connect` that
1566            // runs out terminates every relay still mid-handshake, and over Tor that is most of them.
1567            let budget = crate::relay_connect_timeout(connect_timeout);
1568            let mut fresh = Vec::new();
1569            for url in &added {
1570                if let Ok(Some(relay)) = client.relay(url.as_str()).await {
1571                    let connecting = relay.clone();
1572                    // spawn-detached: one relay's handshake, socket work only; it outlives the wait.
1573                    crate::rt::spawn(async move { let _ = connecting.try_connect().timeout(budget).await; });
1574                    fresh.push(relay);
1575                }
1576            }
1577            futures_util::future::join_all(
1578                fresh.iter().map(|r| crate::negentropy::wait_connected(r, connect_timeout)),
1579            ).await;
1580        } else {
1581            // Every relay already warm in the pool — cheap re-kick of any dropped connection, no wait.
1582            client.connect().await;
1583        }
1584
1585        // Record the now-connected relays as warmed for this generation so subsequent calls fast-path
1586        // (reset the set if the generation advanced under us — a swap mid-warm).
1587        {
1588            let mut warmed = WARMED_RELAYS.lock().unwrap_or_else(|e| e.into_inner());
1589            if warmed.0 != generation {
1590                warmed.0 = generation;
1591                warmed.1 = Default::default();
1592            }
1593            for url in succeeded {
1594                warmed.1.insert(url.clone());
1595            }
1596        }
1597        Ok(client)
1598    }
1599
1600    /// A plane read over a connection authed as the plane, for the relays that ask for AUTH:
1601    /// the events, how many relays answered, and how many could be asked.
1602    /// A connection authed AS `plane` to `targets`, pooled so the NIP-42 handshake happens once.
1603    async fn plane_client(&self, plane: &Keys, filter: &Filter, targets: &[String], generation: u64) -> nostr_sdk::prelude::Client {
1604        let key = plane_pool_key(&plane.public_key().to_hex(), targets);
1605
1606        // Reuse a warm, already-authed pooled connection if one exists — this is
1607        // the win: the NIP-42 handshake happens ONCE, not per page/epoch.
1608        let (hit, evicted) = PLANE_POOL.take(generation, &key);
1609        disconnect_clients(evicted);
1610        if let Some(c) = hit {
1611            c
1612        } else {
1613            let opened = web_time::Instant::now();
1614            // Cold: a dedicated connection authed AS the plane key (a NIP-42
1615            // connection holds ONE identity; the shared client's is the user's).
1616            // Authenticates as the PLANE key, not the user — hence its own
1617            // authenticator rather than `nostr_client_builder()`, which resolves the
1618            // session identity.
1619            let auth = nostr_sdk::prelude::SignerAuthenticator::new(plane.clone());
1620            #[cfg(test)]
1621            let auth = tests::SlowAuth(auth);
1622            let client = crate::apply_transport(
1623                nostr_sdk::prelude::Client::builder()
1624                    .authenticator(auth)
1625                    // Nothing reads a plane client's pool notifications; the default
1626                    // channel allocates 4096 of them up front.
1627                    .notification_channel_size(std::num::NonZeroUsize::MIN),
1628                crate::transport::Lane::Shared,
1629            )
1630            .build();
1631            // Community relay options (GOSSIP|PING + Tor-aware ConnectionMode): a
1632            // bare add_relay leaves ConnectionMode::Direct, so under active Tor the
1633            // plane fetch — and the NIP-42 auth AS the plane key — would connect
1634            // direct and tie the user's IP to community membership.
1635            for r in targets {
1636                let _ = client.add_managed_relay(r.clone()).capabilities(crate::community_relay_capabilities()).await;
1637            }
1638            let mut frames = Vec::with_capacity(targets.len());
1639            for r in targets {
1640                if let Ok(Some(relay)) = client.relay(r).await {
1641                    frames.push(relay.notifications());
1642                }
1643            }
1644            client.connect().await;
1645            // Warmup with the gated filter shape triggers each relay's NIP-42
1646            // challenge so auto-auth completes ONCE here; pooled reuses skip it.
1647            // Every relay at once: one that never answers costs its budget once, not
1648            // once ahead of each relay after it.
1649            futures_util::future::join_all(targets.iter().map(|r| {
1650                let (client, filter) = (&client, filter.clone());
1651                async move {
1652                    let _ = client
1653                        .fetch_events(nostr_sdk::prelude::ReqTarget::single(r.clone(), [filter]))
1654                        // Tor-aware: this warmup carries a NIP-42 challenge round trip, so a
1655                        // clearnet 5s budget expires mid-auth and every relay ends up
1656                        // unauthenticated — which surfaces as `0/N attempted` below.
1657                        .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(5)))
1658                        .await;
1659                }
1660            }))
1661            .await;
1662            // The warmup ends at its EOSE while nostr-sdk answers the challenge on a task of its
1663            // own, and a relay may answer a REQ that reaches it before the AUTH with nothing.
1664            let budget = crate::relay_request_timeout(std::time::Duration::from_secs(5));
1665            futures_util::future::join_all(frames.into_iter().map(|f| authenticated(f, budget))).await;
1666            let ev = PLANE_POOL.insert(generation, key, client.clone());
1667            disconnect_clients(ev);
1668            crate::log_debug!("[v2:plane] a connection as {} to {} relay(s) opened in {:?}", &plane.public_key().to_hex()[..8], targets.len(), opened.elapsed());
1669            client
1670        }
1671    }
1672
1673    async fn read_authed_plane(&self, plane: &Keys, filter: &Filter, targets: Vec<String>, generation: u64, floor: &mut Option<PageFloor>) -> (Vec<Event>, usize, usize) {
1674        let client = self.plane_client(plane, filter, &targets, generation).await;
1675
1676        // This walk is SERIAL, so a dead socket taxes every page its full budget;
1677        // judged against the PLANE pool's statuses (a separate client — nothing
1678        // revives its members, so an unrevivable one here is dead for good). No
1679        // all-dead fallback: the open relays may have answered, and with none
1680        // reached at all the fetch errs anyway.
1681        let targets = reachable_targets(&client, targets).await;
1682
1683        let mut result: Vec<Event> = Vec::new();
1684        let mut seen: std::collections::HashSet<EventId> = std::collections::HashSet::new();
1685        let mut successes = 0usize;
1686        // CONCURRENTLY. Serially, one dead relay cost its entire timeout before the
1687        // next was even tried, and the whole plane read paid that on every page of
1688        // every epoch of a catch-up. The union is order-independent, so there is
1689        // nothing to serialize for.
1690        {
1691            use futures_util::stream::{FuturesUnordered, StreamExt};
1692            let mut inflight: FuturesUnordered<_> = targets
1693                .iter()
1694                .map(|r| {
1695                    let client = client.clone();
1696                    let filter = filter.clone();
1697                    let timeout = self.timeout;
1698                    async move { (r.clone(), fetch_relay_eose(&client, r, filter, timeout).await) }
1699                })
1700                .collect();
1701            while let Some((r, res)) = inflight.next().await {
1702                // Feed the shared breaker so this auth path both benefits from AND
1703                // contributes to the pool-wide dead-relay knowledge.
1704                breaker_record(&r, res.is_ok(), true);
1705                if let Ok(events) = res {
1706                    successes += 1;
1707                    if let Some(floor) = floor.as_mut() {
1708                        floor.note(&events);
1709                    }
1710                    for e in events {
1711                        if seen.insert(e.id) {
1712                            result.push(e);
1713                        }
1714                    }
1715                }
1716            }
1717        }
1718        // The client stays POOLED (not disconnected) for the next page/epoch/community.
1719        let asked = targets.len();
1720        (result, successes, asked)
1721    }
1722
1723    /// Coverage-reporting fetch — same engine as [`Transport::fetch`], returning
1724    /// `(events, relays_that_EOSEd, relays_attempted)`. The boot control probe
1725    /// reads the counts to decide whether its cursor may advance (full coverage
1726    /// only — a majority return must not skip a down relay's pending editions).
1727    pub async fn fetch_counted(&self, query: &Query, relays: &[String]) -> Result<(Vec<Event>, usize, usize), String> {
1728        let client = Self::warm_client(relays, self.timeout).await?;
1729        let base_timeout = self.timeout;
1730        let filter = query.to_filter();
1731
1732        let evidence = effective_evidence(query);
1733
1734        let mut targets: Vec<String> = Vec::new();
1735        for r in relays {
1736            if !targets.contains(r) {
1737                targets.push(r.clone());
1738            }
1739        }
1740        let mut targets = drop_refused(targets)?;
1741        // Even a Full drain skips a DEAD socket: with pool auto-reconnect off, a
1742        // Terminated relay cannot answer this call no matter how long we wait, so
1743        // its timeout buys byte-identical evidence to skipping it — and paid per
1744        // PAGE, it is what stretched one dead relay into a minute-long rotation.
1745        targets = drop_unrevivable_targets(&client, targets).await;
1746
1747        // Fast tier: skip tripped relays outright (pure bandwidth save — the
1748        // evidence bar is ≥1 success either way, and the union self-heals).
1749        // Never skip down to an empty set. Quorum/Full always attempt every
1750        // relay so a trip can't shrink their evidence denominator.
1751        if evidence == Evidence::Fast && targets.len() >= 2 {
1752            let alive: Vec<String> =
1753                targets.iter().filter(|r| !breaker_tripped(r)).cloned().collect();
1754            if !alive.is_empty() {
1755                targets = alive;
1756            }
1757        }
1758
1759        // One relay → nothing to race; the sole relay always gets the full
1760        // budget (there is nothing to union around).
1761        if targets.len() <= 1 {
1762            let Some(url) = targets.first() else {
1763                return Err("no valid relay to fetch from".to_string());
1764            };
1765            let res = fetch_relay_eose(&client, url, filter, base_timeout)
1766                .await
1767                .map_err(|_| format!("relay did not answer the fetch: {url}"));
1768            breaker_record(url, res.is_ok(), true);
1769            return res.map(|evs| (evs, 1, 1));
1770        }
1771
1772        /// One relay's answer into the union.
1773        fn merge_events(
1774            evs: Vec<Event>,
1775            result: &mut Vec<Event>,
1776            seen: &mut std::collections::HashSet<EventId>,
1777            floor: &mut Option<PageFloor>,
1778        ) {
1779            if let Some(floor) = floor {
1780                floor.note(&evs);
1781            }
1782            for e in evs {
1783                if seen.insert(e.id) {
1784                    result.push(e);
1785                }
1786            }
1787        }
1788
1789        // RACE per-relay (mirrors the publish first-ACK race) and union per the
1790        // evidence tier. Every relay's outcome is tracked — genuine EOSE vs
1791        // error/timeout — so an all-dead pool surfaces as Err, never as a
1792        // confident empty answer. Tripped relays keep their place in the
1793        // denominator; on Full drains (non-Tor) they run on a demoted budget so
1794        // a dead relay's tail shrinks without weakening the union.
1795        let demote = evidence == Evidence::Full && demotion_allowed();
1796        use futures_util::stream::{FuturesUnordered, StreamExt};
1797        let mut fetches: FuturesUnordered<_> = targets
1798            .iter()
1799            .map(|r| {
1800                let client = client.clone();
1801                let filter = filter.clone();
1802                let r = r.clone();
1803                let timeout = if demote && breaker_tripped(&r) {
1804                    TRIPPED_TIMEOUT.min(base_timeout)
1805                } else {
1806                    base_timeout
1807                };
1808                let full_budget = timeout >= base_timeout;
1809                // spawn-detached: relay I/O only — no account storage is touched.
1810                crate::rt::spawn(async move {
1811                    let out = fetch_relay_eose(&client, &r, filter, timeout).await;
1812                    (r, full_budget, out)
1813                })
1814            })
1815            .collect();
1816
1817        let mut plan = UnionPlan::new(evidence, targets.len());
1818        let mut result: Vec<Event> = Vec::new();
1819        let mut union_ids: std::collections::HashSet<EventId> = std::collections::HashSet::new();
1820        let mut floor = PageFloor::of(query);
1821
1822        // Phase 1 — wait for the tier's coverage requirement. Quorum's majority
1823        // wait is TIME-BOUNDED from the first success so a dead relay can't
1824        // gate a degraded set (a 2-relay community with one relay down must not
1825        // ride that relay's timeout on every fetch).
1826        let mut quorum_deadline: Option<crate::rt::time::Instant> = None;
1827        let mut quorum_window_closed = false;
1828        while !plan.satisfied() && !plan.exhausted() {
1829            let next = match quorum_deadline {
1830                Some(deadline) => match crate::rt::time::timeout_at(deadline, fetches.next()).await {
1831                    Ok(n) => n,
1832                    Err(_) => {
1833                        quorum_window_closed = true;
1834                        break; // window closed — return with what we hold (≥1 success)
1835                    }
1836                },
1837                None => fetches.next().await,
1838            };
1839            let Some(joined) = next else { break };
1840            match joined {
1841                Ok((url, full_budget, Ok(evs))) => {
1842                    breaker_record(&url, true, full_budget);
1843                    merge_events(evs, &mut result, &mut union_ids, &mut floor);
1844                    plan.record(true);
1845                    if evidence == Evidence::Quorum && quorum_deadline.is_none() {
1846                        quorum_deadline = Some(
1847                            crate::rt::time::Instant::now()
1848                                + std::time::Duration::from_millis(QUORUM_GRACE_MS),
1849                        );
1850                    }
1851                }
1852                Ok((url, full_budget, Err(()))) => {
1853                    breaker_record(&url, false, full_budget);
1854                    plan.record(false);
1855                }
1856                Err(_) => plan.record(false), // task join error — a resolved failure
1857            }
1858        }
1859
1860        if plan.successes() == 0 {
1861            return Err(format!(
1862                "no relay answered the fetch (0/{} attempted)",
1863                plan.attempted()
1864            ));
1865        }
1866
1867        // Phase 2 — residual union window: relays finishing just behind the
1868        // requirement still merge synchronously. Skipped when the quorum window
1869        // already expired (that wait subsumes this one).
1870        if !fetches.is_empty() && !quorum_window_closed {
1871            let grace = crate::rt::time::sleep(std::time::Duration::from_millis(RESIDUAL_GRACE_MS));
1872            tokio::pin!(grace);
1873            loop {
1874                tokio::select! {
1875                    _ = &mut grace => break,
1876                    next = fetches.next() => match next {
1877                        Some(Ok((url, full_budget, Ok(evs)))) => {
1878                            breaker_record(&url, true, full_budget);
1879                            merge_events(evs, &mut result, &mut union_ids, &mut floor);
1880                        }
1881                        Some(Ok((url, full_budget, Err(())))) => {
1882                            breaker_record(&url, false, full_budget);
1883                        }
1884                        Some(Err(_)) => continue,
1885                        None => break,
1886                    }
1887                }
1888            }
1889        }
1890
1891        if let Some(floor) = &floor {
1892            floor.cut(&mut result);
1893        }
1894
1895        // Background-merge the relays that haven't finished: dedup by event id ONLY (identical bytes)
1896        // against what we returned, then hand the rest to the ingester. Conflicting editions carry
1897        // distinct ids, so the protocol's convergence engine resolves them — not the transport.
1898        if !fetches.is_empty() {
1899            let seen: std::collections::HashSet<EventId> = result.iter().map(|e| e.id).collect();
1900            // Captured BEFORE the drain spawn: the drain can outlive an account swap, and
1901            // stragglers fetched under the prior session must not feed the new one's ingest.
1902            crate::db::spawn_bound(async move {
1903                let mut extra: Vec<Event> = Vec::new();
1904                let mut extra_ids: std::collections::HashSet<EventId> = std::collections::HashSet::new();
1905                while let Some(joined) = fetches.next().await {
1906                    if let Ok((url, full_budget, out)) = joined {
1907                        // A late EOSE is still a SUCCESS — slow ≠ dead; without
1908                        // this a relay slower than the residual window could
1909                        // never un-trip.
1910                        breaker_record(&url, out.is_ok(), full_budget);
1911                        if let Ok(evs) = out {
1912                            for e in evs {
1913                                if !seen.contains(&e.id) && extra_ids.insert(e.id) {
1914                                    extra.push(e);
1915                                }
1916                            }
1917                        }
1918                    }
1919                }
1920                submit_stragglers(extra);
1921            });
1922        }
1923
1924        Ok((result, plan.successes(), plan.attempted()))
1925    }
1926}
1927
1928/// Send to one pooled relay, true on its ACK. Callers verify the event and mark it as ours
1929/// once; `Client::send_event` would redo both for every relay, every round.
1930async fn send_to_relay(client: &Client, event: &Event, url: &str) -> bool {
1931    send_to_relay_why(client, event, url).await.is_ok()
1932}
1933
1934/// [`send_to_relay`], with the relay's own reason when it refuses.
1935async fn send_to_relay_why(client: &Client, event: &Event, url: &str) -> Result<(), String> {
1936    let Ok(Some(relay)) = client.relay(url).await else { return Err("not connected".to_string()) };
1937    let wait = crate::relay_request_timeout(std::time::Duration::from_secs(10));
1938    relay.send_event(event).ok_timeout(wait).authentication_timeout(wait).await.map(|_| ()).map_err(|e| e.to_string())
1939}
1940
1941/// Mark our own event as seen before it goes out, so the relays' echoes of it are dropped
1942/// before any work. The mark only silences echoes; it never stands for delivery, which is
1943/// each relay's OK. Returns whether the mark is ours: an id seen before stays seen.
1944pub(crate) async fn mark_own(client: &Client, event: &Event) -> bool {
1945    let fresh = matches!(
1946        client.database().check_id(&event.id).await,
1947        Ok(nostr_sdk::prelude::DatabaseEventStatus::NotExistent)
1948    );
1949    let _ = client.database().save_event(event).await;
1950    fresh
1951}
1952
1953/// Undo a mark [`mark_own`] made once no relay took the event, so a copy that turns up later
1954/// is handled like anyone else's.
1955pub(crate) async fn unmark_own(client: &Client, event: &Event) {
1956    let _ = client.database().delete(nostr_sdk::prelude::Filter::new().id(event.id)).await;
1957}
1958
1959#[async_trait::async_trait]
1960impl Transport for LiveTransport {
1961    async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
1962        event.verify().map_err(|e| e.to_string())?;
1963        crate::event_size::check(event)?;
1964        let client = Self::warm_client(relays, self.timeout).await?;
1965        let timeout = self.timeout;
1966        let mut targets: Vec<String> = Vec::new();
1967        for r in relays { if !targets.contains(r) { targets.push(r.clone()); } }
1968        targets = drop_refused(targets)?;
1969        // A dead socket can't ACK and won't be revived mid-send — don't spawn at it.
1970        targets = drop_unrevivable_targets(&client, targets).await;
1971        // Fan out one send per relay and RETURN on the first ACK — never wait for the slowest relay (a
1972        // distant/ratelimited one must not gate a reaction/edit/message). Each send is SPAWNED, so the rest
1973        // keep delivering to every relay after we return (dropping a JoinHandle detaches, it doesn't abort).
1974        // Single attempt — durable retry is publish_durable's job.
1975        use futures_util::stream::{FuturesUnordered, StreamExt};
1976        let marked = mark_own(&client, event).await;
1977        let mut sends: FuturesUnordered<_> = targets
1978            .into_iter()
1979            .map(|r| {
1980                let client = client.clone();
1981                let event = event.clone();
1982                // spawn-detached: relay I/O only — no account storage is touched.
1983                crate::rt::spawn(async move {
1984                    match crate::rt::time::timeout(timeout, send_to_relay_why(&client, &event, &r)).await {
1985                        Ok(sent) => sent,
1986                        Err(_) => Err("timed out".to_string()),
1987                    }
1988                })
1989            })
1990            .collect();
1991        let mut why = None;
1992        while let Some(joined) = sends.next().await {
1993            match joined {
1994                Ok(Ok(())) => return Ok(()), // first relay ACKed; the others keep delivering in the background
1995                Ok(Err(e)) => why = Some(e),
1996                Err(_) => {}
1997            }
1998        }
1999        // Every send has finished without an ACK.
2000        if marked {
2001            unmark_own(&client, event).await;
2002        }
2003        Err(match why {
2004            Some(why) => format!("no relay accepted the event: {why}"),
2005            None => "no relay accepted the event".to_string(),
2006        })
2007    }
2008
2009    async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
2010        self.fetch_counted(query, relays).await.map(|(events, _successes, _attempted)| events)
2011    }
2012
2013    async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String> {
2014        if relays.is_empty() {
2015            return Ok(PlaneFetch { events: Vec::new(), answered: 0, attempted: 0 });
2016        }
2017        wait_transport_ready().await?;
2018        // Skip relays the shared breaker already knows are dead — don't even pay
2019        // their connect handshake + warmup + timeout (DM negentropy and other sweeps
2020        // trip them early, so by the time a v2 backfill runs they're usually
2021        // marked). Keep all if that would leave none — a slow fetch beats no fetch.
2022        let relays = drop_refused(relays.to_vec())?;
2023        let selected = plane_targets(relays, breaker_tripped);
2024        let filter = query.to_filter();
2025        let generation = crate::db::current_session_id();
2026        let (gated, open): (Vec<String>, Vec<String>) =
2027            selected.ask.iter().cloned().partition(|r| plane_gate(generation, r) == Some(RelayGate::Auth));
2028
2029        let mut result: Vec<Event> = Vec::new();
2030        let mut seen: std::collections::HashSet<EventId> = std::collections::HashSet::new();
2031        let mut keep = |events: Vec<Event>| result.extend(events.into_iter().filter(|e| seen.insert(e.id)));
2032        let (mut successes, mut asked) = (0usize, 0usize);
2033        let mut floor = PageFloor::of(query);
2034        let open_reads = futures_util::future::join_all(open.iter().map(|r| {
2035            let filter = filter.clone();
2036            async move { (r, read_open_plane(generation, r, filter, self.timeout).await) }
2037        }));
2038        // Relays already known to gate read alongside, not after a slow open relay's dial.
2039        let known_gated = async {
2040            if gated.is_empty() {
2041                (Vec::new(), 0, 0)
2042            } else {
2043                self.read_authed_plane(plane, &filter, gated.clone(), generation, &mut floor).await
2044            }
2045        };
2046        let (reads, (events, answered, reached)) = futures_util::future::join(open_reads, known_gated).await;
2047        successes += answered;
2048        asked += reached;
2049        keep(events);
2050        let mut newly_gated: Vec<String> = Vec::new();
2051        for (r, read) in reads {
2052            match read {
2053                OpenRead::Read(events) => {
2054                    breaker_record(r, true, true);
2055                    successes += 1;
2056                    asked += 1;
2057                    if let Some(floor) = floor.as_mut() {
2058                        floor.note(&events);
2059                    }
2060                    keep(events);
2061                }
2062                OpenRead::Failed => {
2063                    breaker_record(r, false, true);
2064                    asked += 1;
2065                }
2066                OpenRead::Unreachable => {}
2067                OpenRead::Gated => newly_gated.push(r.clone()),
2068            }
2069        }
2070        if !newly_gated.is_empty() {
2071            let (events, answered, reached) = self.read_authed_plane(plane, &filter, newly_gated, generation, &mut floor).await;
2072            successes += answered;
2073            asked += reached;
2074            keep(events);
2075        }
2076        if let Some(floor) = &floor {
2077            floor.cut(&mut result);
2078        }
2079        // Zero EOSE = every relay refused/timed out — an honest transient failure,
2080        // NOT a "the plane is empty" verdict (a genuine empty plane EOSEs with no
2081        // events, which counts as a success). A confident-empty here could mask a
2082        // rotation from a caller that concludes absence.
2083        if successes == 0 {
2084            return Err(format!("no relay answered the plane fetch (0/{} attempted)", selected.ask.len()));
2085        }
2086        Ok(selected.fetched(result, successes, asked))
2087    }
2088
2089    async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2090        // "Durable" = confirm the network has it (≥1 relay ACKs within CONFIRM_WINDOW), then keep bugging the
2091        // SLOW/ratelimited stragglers (Damus-style 1-event/min) in the BACKGROUND. If NOTHING ACKs in the
2092        // window we throw — a dead relay set is a failure, not an endless wait. Uses the shared warm client
2093        // (NEVER shut down here) and targets the community relay set across rounds.
2094        event.verify().map_err(|e| e.to_string())?;
2095        crate::event_size::check(event)?;
2096        let client = Self::warm_client(relays, self.timeout).await?;
2097        let timeout = self.timeout;
2098        let event = event.clone();
2099        let backoff = std::time::Duration::from_millis(750);
2100        let mut pending: Vec<String> = Vec::new();
2101        for r in relays { if !pending.contains(r) { pending.push(r.clone()); } }
2102        if pending.is_empty() {
2103            return Err("no relays to broadcast to".to_string());
2104        }
2105        let mut pending = drop_refused(pending)?;
2106
2107        // Phase 1 — CONFIRM: RACE the relays and return the instant ANY one ACKs — never wait for the
2108        // slowest. `send_event_to(all)` blocks on the slowest relay (a distant/ratelimited one dominates the
2109        // latency), so we fan out one send per relay and take the first winner; the losers are cancelled and
2110        // re-sent in the background. Retry rounds within CONFIRM_WINDOW; zero ACKs in the window = failure.
2111        let mut acked_any = false;
2112        let marked = mark_own(&client, &event).await;
2113        // Over Tor one round alone can take the 30 s request floor: the 60 s connect floor leaves
2114        // room for a retry. Clearnet keeps 30 s.
2115        let confirm_window = crate::relay_connect_timeout(CONFIRM_WINDOW);
2116        let _ = crate::rt::time::timeout(confirm_window, async {
2117            loop {
2118                // Per ROUND, not from `pending`: a dead socket stays pending (the
2119                // reconcile loop may revive it before the stragglers give up) but a
2120                // confirm round must not spend its budget on a relay that cannot ACK.
2121                let round = drop_unrevivable_targets(&client, pending.clone()).await;
2122                let sends = round.iter().cloned().map(|r| {
2123                    let client = &client;
2124                    let event = &event;
2125                    Box::pin(async move {
2126                        match crate::rt::time::timeout(timeout, send_to_relay(client, event, &r)).await {
2127                            Ok(true) => Ok(r),
2128                            _ => Err(()),
2129                        }
2130                    })
2131                });
2132                if let Ok((winner, _losers)) = futures_util::future::select_ok(sends).await {
2133                    acked_any = true;
2134                    pending.retain(|r| r != &winner);
2135                    break;
2136                }
2137                crate::rt::time::sleep(backoff).await;
2138            }
2139        })
2140        .await;
2141
2142        if !acked_any {
2143            if marked {
2144                unmark_own(&client, &event).await;
2145            }
2146            return Err(format!("no relay accepted the event within {}s", confirm_window.as_secs()));
2147        }
2148        if pending.is_empty() {
2149            return Ok(()); // every relay ACKed during the confirm phase
2150        }
2151
2152        // Phase 2 — BACKGROUND: thread the laggards through a durable publisher (retries each up to
2153        // MAX_PUBLISH_ATTEMPTS at a 750ms backoff, so it can't run forever). The caller returns NOW with its
2154        // confirmed ACK; 's fetch-union heals anything that never lands. The client is shared — not torn
2155        // down — so the spawned task just drops its handle when finished.
2156        // spawn-detached: relay I/O only — no account storage is touched.
2157        crate::rt::spawn(async move {
2158            let client_ref = &client;
2159            let event_ref = &event;
2160            let _ = durable_broadcast(&pending, MAX_PUBLISH_ATTEMPTS, backoff, move |round| {
2161                Box::pin(async move {
2162                    match crate::rt::time::timeout(timeout, crate::transport_aware(client_ref.send_event(event_ref)).to(round.clone())).await {
2163                        Ok(Ok(output)) => round.into_iter().filter(|p| RelayUrl::parse(p).map(|u| output.success.contains_key(&u)).unwrap_or(false)).collect(),
2164                        _ => Vec::new(),
2165                    }
2166                })
2167            })
2168            .await;
2169        });
2170        Ok(())
2171    }
2172
2173    fn reconciler(&self) -> Option<&dyn Reconcile> {
2174        Some(self)
2175    }
2176
2177    fn detached(&self) -> Option<std::sync::Arc<dyn Transport + Send + Sync>> {
2178        Some(std::sync::Arc::new(LiveTransport { timeout: self.timeout }))
2179    }
2180
2181    fn prewarm_planes(&self, relays: &[String]) {
2182        let (relays, timeout) = (relays.to_vec(), self.timeout);
2183        crate::db::spawn_bound(async move {
2184            if wait_transport_ready().await.is_err() {
2185                return;
2186            }
2187            let Ok(relays) = drop_refused(relays) else { return };
2188            let generation = crate::db::current_session_id();
2189            // A relay known to gate reads is dialled as each plane, with its key.
2190            let open = relays.iter().filter(|r| !breaker_tripped(r) && plane_gate(generation, r) != Some(RelayGate::Auth));
2191            futures_util::future::join_all(open.map(|r| async move {
2192                let key = crate::inbox_relays::normalize_relay_url(r);
2193                drop(open_plane_client(generation, r, &key, timeout).await);
2194            }))
2195            .await;
2196        });
2197    }
2198}
2199
2200/// How long a relay's "no NIP-77" stands before it is asked again: relays gain it with an upgrade.
2201const PLANE_NEG_TTL_SECS: u64 = 24 * 60 * 60;
2202
2203/// Apart from the DM reads' `neg_cap2:` record: a relay's answer for a plane's `authors` filter
2204/// says nothing of its answer for our own `p` filter, nor the other way.
2205fn plane_neg_setting(url: &str) -> String {
2206    format!("neg_plane2:{}", crate::inbox_relays::normalize_relay_url(url))
2207}
2208
2209/// Whether `url` reconciled a plane when last asked, and when.
2210fn plane_neg(url: &str) -> Option<(bool, u64)> {
2211    let raw = crate::db::get_sql_setting(plane_neg_setting(url)).ok().flatten()?;
2212    let (flag, at) = raw.split_once(':')?;
2213    Some((flag == "1", at.parse().ok()?))
2214}
2215
2216/// What `url` is on record as doing with a plane reconciliation: nothing until it was asked.
2217#[cfg(test)]
2218pub(crate) fn plane_reconciles(url: &str) -> Option<bool> {
2219    plane_neg(url).map(|(reconciles, _)| reconciles)
2220}
2221
2222fn note_plane_neg(url: &str, reconciles: bool) {
2223    // A standing yes is rewritten once a day, not on every pass.
2224    if reconciles && plane_neg(url).is_some_and(|(ok, at)| ok && now_secs().saturating_sub(at) < PLANE_NEG_TTL_SECS) {
2225        return;
2226    }
2227    let _ = crate::db::set_sql_setting(plane_neg_setting(url), format!("{}:{}", u8::from(reconciles), now_secs()));
2228}
2229
2230#[async_trait::async_trait]
2231impl Reconcile for LiveTransport {
2232    async fn reconcile(&self, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail> {
2233        let seen = plane_neg(relay);
2234        if seen.is_some_and(|(ok, at)| !ok && now_secs().saturating_sub(at) < PLANE_NEG_TTL_SECS) {
2235            return Err(ReconcileFail::Unsupported);
2236        }
2237        let client = Self::warm_client(std::slice::from_ref(&relay.to_string()), self.timeout).await.map_err(|_| ReconcileFail::Unreached)?;
2238        let handle = client.relay(relay).await.ok().flatten().ok_or(ReconcileFail::Unreached)?;
2239        if !crate::negentropy::wait_connected(&handle, crate::relay_connect_timeout(std::time::Duration::from_secs(3)).min(self.timeout)).await {
2240            breaker_record(relay, false, true);
2241            return Err(ReconcileFail::Unreached);
2242        }
2243        let first = crate::relay_request_timeout(std::time::Duration::from_secs(5)).min(self.timeout);
2244        let permits = neg_permits(relay);
2245        let _permit = permits.acquire().await;
2246        match super::plane_neg::reconcile(&handle, query.to_filter(), held, budget, first, self.timeout).await {
2247            Ok(diff) => {
2248                breaker_record(relay, true, true);
2249                note_plane_neg(relay, true);
2250                Ok(diff)
2251            }
2252            Err(super::plane_neg::Ended::Fail(fail)) => {
2253                if fail == ReconcileFail::Unsupported {
2254                    note_plane_neg(relay, false);
2255                }
2256                Err(fail)
2257            }
2258            // A relay that has reconciled before is slow, not unable.
2259            Err(super::plane_neg::Ended::Silent) if seen.is_some_and(|(ok, _)| ok) => Err(ReconcileFail::Failed("no answer".to_string())),
2260            // Silence says nothing by itself. A relay that answers a plain read and not this has
2261            // no NIP-77; one that answers neither was not reached.
2262            Err(super::plane_neg::Ended::Silent) => match fetch_relay_eose(&client, relay, query.to_filter().limit(0), first).await {
2263                Ok(_) => {
2264                    note_plane_neg(relay, false);
2265                    Err(ReconcileFail::Unsupported)
2266                }
2267                Err(()) => Err(ReconcileFail::Unreached),
2268            },
2269        }
2270    }
2271
2272    async fn reconcile_plane(&self, plane: &Keys, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail> {
2273        let generation = crate::db::current_session_id();
2274        if plane_gate(generation, relay) != Some(RelayGate::Auth) {
2275            match self.reconcile(query, held, relay, budget).await {
2276                Err(ReconcileFail::Gated) => {}
2277                answered => return answered,
2278            }
2279        }
2280        let filter = query.to_filter();
2281        let client = self.plane_client(plane, &filter, std::slice::from_ref(&relay.to_string()), generation).await;
2282        let handle = client.relay(relay).await.ok().flatten().ok_or(ReconcileFail::Unreached)?;
2283        if !crate::negentropy::wait_connected(&handle, crate::relay_connect_timeout(std::time::Duration::from_secs(3)).min(self.timeout)).await {
2284            return Err(ReconcileFail::Unreached);
2285        }
2286        let first = crate::relay_request_timeout(std::time::Duration::from_secs(5)).min(self.timeout);
2287        let permits = neg_permits(relay);
2288        let _permit = permits.acquire().await;
2289        match super::plane_neg::reconcile(&handle, filter, held, budget, first, self.timeout).await {
2290            Ok(diff) => Ok(diff),
2291            Err(super::plane_neg::Ended::Fail(fail)) => Err(fail),
2292            Err(super::plane_neg::Ended::Silent) => Err(ReconcileFail::Failed("no answer".to_string())),
2293        }
2294    }
2295
2296}
2297
2298#[cfg(any(test, feature = "bench"))]
2299pub(crate) mod memory {
2300    use super::*;
2301    use std::collections::{HashMap, HashSet};
2302    use std::sync::Mutex;
2303
2304    /// An in-memory stand-in for the Community's relay set. Stores events per relay
2305    /// url so tests can model partial propagation (a relay that missed an event) and
2306    /// verify the redundancy/self-heal property: a fetch across the set unions +
2307    /// dedups, so a gap on one relay is covered by its siblings.
2308    pub struct MemoryRelay {
2309        per_relay: Mutex<HashMap<String, Vec<Event>>>,
2310        subscribers: Mutex<Vec<(Query, tokio::sync::mpsc::UnboundedSender<Event>)>>,
2311        /// Relays that judge a wrap's deletion by its `p`-tagged owner, as CORD-01 asks.
2312        owner_rule: Mutex<HashSet<String>>,
2313        /// Relays without NIP-77.
2314        no_reconcile: Mutex<HashSet<String>>,
2315        /// Reconciliations answered, by anyone asking.
2316        reconciled: std::sync::atomic::AtomicU64,
2317    }
2318
2319    /// NIP-01 ephemeral range: relays stream these to live subscriptions but never store
2320    /// them, so a fetch on a real relay can never return one.
2321    fn is_ephemeral(kind: u16) -> bool {
2322        (20000..30000).contains(&kind)
2323    }
2324
2325    impl MemoryRelay {
2326        pub fn new() -> Self {
2327            MemoryRelay {
2328                per_relay: Mutex::new(HashMap::new()),
2329                subscribers: Mutex::new(Vec::new()),
2330                owner_rule: Mutex::new(HashSet::new()),
2331                no_reconcile: Mutex::new(HashSet::new()),
2332                reconciled: Default::default(),
2333            }
2334        }
2335
2336        /// Have `relays` answer a reconciliation as a relay without NIP-77 does.
2337        #[cfg(test)]
2338        pub fn without_reconcile(&self, relays: &[String]) {
2339            self.no_reconcile.lock().unwrap().extend(relays.iter().cloned());
2340        }
2341
2342        /// Reconciliations answered since the last ask.
2343        #[cfg(test)]
2344        pub fn reconciled(&self) -> u64 {
2345            self.reconciled.swap(0, std::sync::atomic::Ordering::Relaxed)
2346        }
2347
2348        /// Have `relays` follow CORD-01 §Deletions: a wrap goes only by its `p`-tagged owner's
2349        /// deletion, never its author's.
2350        #[cfg(test)]
2351        pub fn follow_cord01(&self, relays: &[String]) {
2352            self.owner_rule.lock().unwrap().extend(relays.iter().cloned());
2353        }
2354
2355        /// Total stored events across every relay url — lets a test assert that a
2356        /// code path published NOTHING, which an absence-of-effect check can't
2357        /// express by fetching (an empty result also means "never published").
2358        #[cfg(test)]
2359        pub fn stored_count(&self) -> usize {
2360            self.per_relay.lock().unwrap().values().map(|v| v.len()).sum()
2361        }
2362
2363        /// Open a live subscription: every subsequent publish/inject matching `query` is
2364        /// delivered — ephemerals included, which stream but are never stored.
2365        #[cfg(test)]
2366        pub fn subscribe(&self, query: Query) -> tokio::sync::mpsc::UnboundedReceiver<Event> {
2367            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
2368            self.subscribers.lock().unwrap().push((query, tx));
2369            rx
2370        }
2371
2372        /// Push `event` to every live matching subscriber, pruning closed ones.
2373        fn deliver(&self, event: &Event) {
2374            self.subscribers.lock().unwrap().retain(|(q, tx)| {
2375                if q.matches(event) {
2376                    tx.send(event.clone()).is_ok()
2377                } else {
2378                    !tx.is_closed()
2379                }
2380            });
2381        }
2382
2383        /// Publish to ONLY a subset of relays — used to simulate a relay missing an
2384        /// event (e.g. a dropped rekey) for redundancy tests.
2385        pub fn inject(&self, event: &Event, relays: &[String]) {
2386            self.deliver(event);
2387            if is_ephemeral(event.kind.as_u16()) {
2388                return; // live-delivered above, never stored
2389            }
2390            // Replaceable kinds: parameterized (30000-39999, keyed by (kind, pubkey, d-tag)) AND
2391            // standard (10000-19999, plus 0/3, keyed by (kind, pubkey) — the d-tag is "") — a relay keeps
2392            // only the latest at that coordinate, so a new event REPLACES the old (NIP-01). This is what
2393            // makes a revocation tombstone overwrite a bundle, and a fresh Community List supersede the last one,
2394            // even on relays that ignore deletions — model it so tests match real relay behavior.
2395            let d_tag = |e: &Event| e.tags.iter().find_map(|t| {
2396                let s = t.as_slice();
2397                (s.len() >= 2 && s[0] == "d").then(|| s[1].clone())
2398            }).unwrap_or_default();
2399            let k = event.kind.as_u16();
2400            let replaceable = (30000..40000).contains(&k) || (10000..20000).contains(&k) || k == 0 || k == 3;
2401            let coord = (event.kind.as_u16(), event.pubkey, d_tag(event));
2402            let mut map = self.per_relay.lock().unwrap();
2403            for r in relays {
2404                let v = map.entry(r.clone()).or_default();
2405                if replaceable {
2406                    v.retain(|e| (e.kind.as_u16(), e.pubkey, d_tag(e)) != coord);
2407                }
2408                v.push(event.clone());
2409            }
2410        }
2411
2412        /// How many events a given relay holds (test introspection).
2413        #[cfg(test)]
2414        pub fn count_on(&self, relay: &str) -> usize {
2415            self.per_relay.lock().unwrap().get(relay).map_or(0, |v| v.len())
2416        }
2417
2418        /// Apply a NIP-09 deletion: drop any stored event matched by the deletion's `e`
2419        /// tags (by id) OR `a` tags (addressable coordinate `kind:pubkey:d`), AND whose
2420        /// author matches the deletion's author (a deleter can only delete their own
2421        /// events — same rule strfry enforces). A relay following CORD-01 takes a wrap's
2422        /// `p`-tagged owner in place of its author.
2423        fn apply_deletion(&self, deletion: &Event, relays: &[String]) {
2424            let owner_rule = self.owner_rule.lock().unwrap().clone();
2425            let mut id_targets: HashSet<String> = HashSet::new();
2426            let mut coord_targets: HashSet<String> = HashSet::new();
2427            for t in deletion.tags.iter() {
2428                let s = t.as_slice();
2429                if s.len() >= 2 && s[0] == "e" {
2430                    id_targets.insert(s[1].clone());
2431                } else if s.len() >= 2 && s[0] == "a" {
2432                    coord_targets.insert(s[1].clone());
2433                }
2434            }
2435            let mut map = self.per_relay.lock().unwrap();
2436            for r in relays {
2437                let by_owner = owner_rule.contains(r);
2438                if let Some(events) = map.get_mut(r) {
2439                    events.retain(|e| {
2440                        let deleter = if by_owner && e.kind.as_u16() == 1059 {
2441                            crate::community::v2::stream::wrap_owner(e)
2442                        } else {
2443                            Some(e.pubkey)
2444                        };
2445                        if deleter != Some(deletion.pubkey) {
2446                            return true;
2447                        }
2448                        if id_targets.contains(&e.id.to_hex()) {
2449                            return false;
2450                        }
2451                        // Addressable coordinate "kind:pubkey:d-identifier".
2452                        let d = e.tags.iter().find_map(|t| {
2453                            let s = t.as_slice();
2454                            (s.len() >= 2 && s[0] == "d").then(|| s[1].clone())
2455                        }).unwrap_or_default();
2456                        let coord = format!("{}:{}:{}", e.kind.as_u16(), e.pubkey.to_hex(), d);
2457                        !coord_targets.contains(&coord)
2458                    });
2459                }
2460            }
2461        }
2462    }
2463
2464    #[async_trait::async_trait]
2465    impl Transport for MemoryRelay {
2466        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2467            // Refuse what a real relay would, so every test publish is a size test too.
2468            crate::event_size::check(event)?;
2469            // Honor NIP-09 so the delete→gone cycle is testable offline.
2470            if event.kind == Kind::EventDeletion {
2471                self.apply_deletion(event, relays);
2472                self.deliver(event);
2473            } else {
2474                self.inject(event, relays);
2475            }
2476            Ok(())
2477        }
2478
2479        // The in-memory relay always accepts, so a "durable" publish is just a publish (the retry
2480        // engine itself is unit-tested separately via `durable_broadcast`).
2481        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2482            self.publish(event, relays).await
2483        }
2484
2485        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
2486            let map = self.per_relay.lock().unwrap();
2487            let newest_first = |a: &&Event, b: &&Event| b.created_at.cmp(&a.created_at).then_with(|| b.id.cmp(&a.id));
2488            let mut seen = HashSet::new();
2489            let mut out = Vec::new();
2490            let mut floor = PageFloor::of(query);
2491            for r in relays {
2492                let Some(events) = map.get(r) else { continue };
2493                // Never stored, but guard the read path too: a real relay never
2494                // serves an ephemeral from a fetch, whatever got in.
2495                let mut page: Vec<&Event> = events.iter().filter(|ev| !is_ephemeral(ev.kind.as_u16()) && query.matches(ev)).collect();
2496                // The page cap is each relay's own, newest first: the union of several runs past it.
2497                if let Some(limit) = query.limit {
2498                    page.sort_by(newest_first);
2499                    page.truncate(limit);
2500                }
2501                let page: Vec<Event> = page.into_iter().cloned().collect();
2502                if let Some(floor) = floor.as_mut() {
2503                    floor.note(&page);
2504                }
2505                out.extend(page.into_iter().filter(|e| seen.insert(e.id)));
2506            }
2507            if let Some(floor) = &floor {
2508                floor.cut(&mut out);
2509            }
2510            if query.limit.is_some() {
2511                out.sort_by(|a, b| newest_first(&a, &b));
2512            }
2513            Ok(out)
2514        }
2515
2516        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String> {
2517            // No auth in the in-memory relay — a plane fetch is just a fetch.
2518            Ok(PlaneFetch::whole(self.fetch(query, relays).await?))
2519        }
2520
2521        fn reconciler(&self) -> Option<&dyn Reconcile> {
2522            Some(self)
2523        }
2524    }
2525
2526    #[async_trait::async_trait]
2527    impl Reconcile for MemoryRelay {
2528        async fn reconcile(&self, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail> {
2529            if self.no_reconcile.lock().unwrap().contains(relay) {
2530                return Err(ReconcileFail::Unsupported);
2531            }
2532            self.reconciled.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2533            let map = self.per_relay.lock().unwrap();
2534            let theirs: HashSet<EventId> =
2535                map.get(relay).into_iter().flatten().filter(|e| !is_ephemeral(e.kind.as_u16()) && query.matches(e)).map(|e| e.id).collect();
2536            let ours: HashSet<EventId> = held.iter().map(|(id, _)| *id).collect();
2537            let mut need: Vec<EventId> = theirs.difference(&ours).copied().collect();
2538            need.sort_unstable();
2539            let complete = need.len() <= budget;
2540            need.truncate(budget);
2541            let mut lack: Vec<EventId> = ours.difference(&theirs).copied().collect();
2542            lack.sort_unstable();
2543            Ok(Diff { need, lack, complete })
2544        }
2545    }
2546}
2547
2548/// A relay on a real loopback socket, for what only a socket shows: how many connections a
2549/// client opens, and how it answers a NIP-42 gate.
2550#[cfg(test)]
2551pub(crate) mod wire {
2552    use futures_util::{SinkExt, StreamExt};
2553    use nostr_sdk::prelude::*;
2554    use std::collections::HashSet;
2555    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2556    use std::sync::{Arc, Mutex};
2557    use tokio_tungstenite::tungstenite::Message as Ws;
2558
2559    /// Answers REQs from what it holds. Gated, it serves a REQ only to a connection authed as
2560    /// every author it names, as Ditto does: otherwise one AUTH challenge per connection and a
2561    /// CLOSED "auth-required:", or with `quiet` an EOSE with nothing. Greeting, it challenges on
2562    /// connect and serves reads anyway. Refusing, it CLOSEs every REQ with an error.
2563    pub struct WireRelay {
2564        pub port: u16,
2565        opened: Arc<AtomicUsize>,
2566        modes: Arc<Modes>,
2567        held: Arc<Mutex<Vec<Event>>>,
2568    }
2569
2570    #[derive(Default)]
2571    struct Modes {
2572        gated: AtomicBool,
2573        quiet: AtomicBool,
2574        greets: AtomicBool,
2575        refuses: AtomicBool,
2576        /// Milliseconds a new connection waits before its WebSocket handshake.
2577        stall_ms: std::sync::atomic::AtomicU64,
2578        /// Subscriptions one connection may hold open; 0 for no limit.
2579        sub_cap: AtomicUsize,
2580        /// Close the connection on the first REQ, unanswered.
2581        hangs_up: AtomicBool,
2582        /// Gate without ever sending a challenge.
2583        mute: AtomicBool,
2584        /// Challenge once a connection has been served a read.
2585        challenges_after: AtomicBool,
2586        /// How a NEG-OPEN is met: 0 reconciled, 1 a notice as from a relay without NIP-77, 2 silence.
2587        neg: std::sync::atomic::AtomicU8,
2588        /// NEG-OPENs received.
2589        neg_opens: AtomicUsize,
2590        /// NIP-77 sessions one connection may hold open, as Magnitude caps them. 0 for none.
2591        neg_cap: AtomicUsize,
2592    }
2593
2594    impl WireRelay {
2595        pub async fn start() -> Self {
2596            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2597            let port = listener.local_addr().unwrap().port();
2598            let relay = WireRelay { port, opened: Arc::default(), modes: Arc::default(), held: Arc::default() };
2599            let (opened, modes, held) = (relay.opened.clone(), relay.modes.clone(), relay.held.clone());
2600            let url = RelayUrl::parse(&relay.url()).unwrap();
2601            tokio::spawn(async move {
2602                while let Ok((tcp, _)) = listener.accept().await {
2603                    opened.fetch_add(1, Ordering::SeqCst);
2604                    tokio::spawn(serve(tcp, url.clone(), modes.clone(), held.clone()));
2605                }
2606            });
2607            relay
2608        }
2609
2610        pub fn url(&self) -> String {
2611            format!("ws://127.0.0.1:{}", self.port)
2612        }
2613
2614        /// Connections accepted so far.
2615        pub fn opened(&self) -> usize {
2616            self.opened.load(Ordering::SeqCst)
2617        }
2618
2619        pub fn gate(&self, on: bool) {
2620            self.modes.gated.store(on, Ordering::SeqCst);
2621        }
2622
2623        pub fn quiet(&self, on: bool) {
2624            self.modes.quiet.store(on, Ordering::SeqCst);
2625        }
2626
2627        pub fn greet(&self, on: bool) {
2628            self.modes.greets.store(on, Ordering::SeqCst);
2629        }
2630
2631        pub fn refuse(&self, on: bool) {
2632            self.modes.refuses.store(on, Ordering::SeqCst);
2633        }
2634
2635        pub fn stall(&self, by: std::time::Duration) {
2636            self.modes.stall_ms.store(by.as_millis() as u64, Ordering::SeqCst);
2637        }
2638
2639        pub fn cap_subs(&self, n: usize) {
2640            self.modes.sub_cap.store(n, Ordering::SeqCst);
2641        }
2642
2643        pub fn hang_up(&self, on: bool) {
2644            self.modes.hangs_up.store(on, Ordering::SeqCst);
2645        }
2646
2647        pub fn mute(&self, on: bool) {
2648            self.modes.mute.store(on, Ordering::SeqCst);
2649        }
2650
2651        pub fn challenge_after_a_read(&self, on: bool) {
2652            self.modes.challenges_after.store(on, Ordering::SeqCst);
2653        }
2654
2655        pub fn hold(&self, events: impl IntoIterator<Item = Event>) {
2656            self.held.lock().unwrap().extend(events);
2657        }
2658
2659        /// Meet a NEG-OPEN as a relay without NIP-77 does: with a notice, or with `silent` nothing.
2660        pub fn no_nip77(&self, silent: bool) {
2661            self.modes.neg.store(if silent { 2 } else { 1 }, Ordering::SeqCst);
2662        }
2663
2664        /// Reconcile again.
2665        pub fn nip77(&self) {
2666            self.modes.neg.store(0, Ordering::SeqCst);
2667        }
2668
2669        /// NEG-OPENs received so far.
2670        pub fn neg_opens(&self) -> usize {
2671            self.modes.neg_opens.load(Ordering::SeqCst)
2672        }
2673
2674        /// Refuse a NIP-77 session past `cap` open on one connection, as Magnitude does.
2675        pub fn cap_neg_sessions(&self, cap: usize) {
2676            self.modes.neg_cap.store(cap, Ordering::SeqCst);
2677        }
2678    }
2679
2680    async fn serve(tcp: tokio::net::TcpStream, url: RelayUrl, modes: Arc<Modes>, held: Arc<Mutex<Vec<Event>>>) {
2681        tokio::time::sleep(std::time::Duration::from_millis(modes.stall_ms.load(Ordering::SeqCst))).await;
2682        let greet = modes.greets.load(Ordering::SeqCst);
2683        let Ok(ws) = tokio_tungstenite::accept_async(tcp).await else { return };
2684        let (mut sink, mut stream) = ws.split();
2685        static CONNECTION: AtomicUsize = AtomicUsize::new(0);
2686        let challenge = format!("challenge-{}", CONNECTION.fetch_add(1, Ordering::SeqCst));
2687        let (mut challenged, mut authed) = (greet, HashSet::<PublicKey>::new());
2688        let mut open = HashSet::<SubscriptionId>::new();
2689        let mut reconciling = std::collections::HashMap::<SubscriptionId, negentropy::Negentropy<'static, negentropy::NegentropyStorageVector>>::new();
2690        if greet && sink.send(Ws::Text(RelayMessage::auth(challenge.clone()).as_json().into())).await.is_err() {
2691            return;
2692        }
2693        while let Some(Ok(frame)) = stream.next().await {
2694            let Ws::Text(text) = frame else { continue };
2695            let mut out: Vec<RelayMessage> = Vec::new();
2696            match ClientMessage::from_json(text.as_str()) {
2697                Ok(ClientMessage::Req { .. }) if modes.hangs_up.load(Ordering::SeqCst) => return,
2698                Ok(ClientMessage::Req { subscription_id, filters }) => {
2699                    let id = subscription_id.into_owned();
2700                    let named = filters.iter().flat_map(|f| f.authors.iter().flatten().copied());
2701                    let cap = modes.sub_cap.load(Ordering::SeqCst);
2702                    if modes.refuses.load(Ordering::SeqCst) {
2703                        out.push(RelayMessage::closed(id, "error: refused"));
2704                    } else if cap > 0 && open.len() >= cap {
2705                        out.push(RelayMessage::closed(id, "error: too many subscriptions"));
2706                    } else if modes.gated.load(Ordering::SeqCst) && !named.into_iter().all(|a| authed.contains(&a)) {
2707                        if !challenged && !modes.mute.load(Ordering::SeqCst) {
2708                            challenged = true;
2709                            out.push(RelayMessage::auth(challenge.clone()));
2710                        }
2711                        out.push(match modes.quiet.load(Ordering::SeqCst) {
2712                            true => RelayMessage::eose(id),
2713                            false => RelayMessage::closed(id, "auth-required: all authors must be authenticated"),
2714                        });
2715                    } else {
2716                        open.insert(id.clone());
2717                        let held = held.lock().unwrap();
2718                        let mut matched: Vec<&Event> = held.iter().filter(|e| filters.iter().any(|f| f.match_event(e, MatchEventOptions::new()))).collect();
2719                        // The newest `limit`, as a relay pages.
2720                        if let Some(limit) = filters.iter().filter_map(|f| f.limit).max() {
2721                            matched.sort_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| b.id.cmp(&a.id)));
2722                            matched.truncate(limit);
2723                        }
2724                        for e in matched {
2725                            out.push(RelayMessage::event(id.clone(), e.clone()));
2726                        }
2727                        out.push(RelayMessage::eose(id));
2728                        if !challenged && modes.challenges_after.load(Ordering::SeqCst) {
2729                            challenged = true;
2730                            out.push(RelayMessage::auth(challenge.clone()));
2731                        }
2732                    }
2733                }
2734                Ok(ClientMessage::Close(id)) => {
2735                    open.remove(id.as_ref());
2736                }
2737                Ok(ClientMessage::NegOpen { subscription_id, filter, initial_message }) => {
2738                    modes.neg_opens.fetch_add(1, Ordering::SeqCst);
2739                    let id = subscription_id.into_owned();
2740                    let named = filter.authors.iter().flatten().copied();
2741                    match modes.neg.load(Ordering::SeqCst) {
2742                        1 => out.push(RelayMessage::notice("ERROR: bad msg: unknown cmd")),
2743                        2 => {}
2744                        _ if modes.neg_cap.load(Ordering::SeqCst) > 0 && reconciling.len() >= modes.neg_cap.load(Ordering::SeqCst) => {
2745                            out.push(RelayMessage::NegErr { subscription_id: std::borrow::Cow::Owned(id), message: "blocked: too many open negentropy sessions".into() });
2746                        }
2747                        _ if modes.gated.load(Ordering::SeqCst) && !named.into_iter().all(|a| authed.contains(&a)) => {
2748                            out.push(RelayMessage::NegErr { subscription_id: std::borrow::Cow::Owned(id), message: "auth-required: all authors must be authenticated".into() });
2749                        }
2750                        _ => {
2751                            let mut storage = negentropy::NegentropyStorageVector::new();
2752                            for e in held.lock().unwrap().iter().filter(|e| filter.match_event(e, MatchEventOptions::new())) {
2753                                storage.insert(e.created_at.as_secs(), negentropy::Id::from_byte_array(e.id.to_bytes())).unwrap();
2754                            }
2755                            storage.seal().unwrap();
2756                            let mut neg = negentropy::Negentropy::owned(storage, 60_000).unwrap();
2757                            let answer = neg.reconcile(&crate::simd::hex::hex_string_to_bytes(&initial_message)).unwrap();
2758                            out.push(RelayMessage::NegMsg { subscription_id: std::borrow::Cow::Owned(id.clone()), message: crate::simd::hex::bytes_to_hex_string(&answer).into() });
2759                            reconciling.insert(id, neg);
2760                        }
2761                    }
2762                }
2763                Ok(ClientMessage::NegMsg { subscription_id, message }) => {
2764                    if let Some(neg) = reconciling.get_mut(subscription_id.as_ref()) {
2765                        let answer = neg.reconcile(&crate::simd::hex::hex_string_to_bytes(&message)).unwrap();
2766                        out.push(RelayMessage::NegMsg { subscription_id, message: crate::simd::hex::bytes_to_hex_string(&answer).into() });
2767                    }
2768                }
2769                Ok(ClientMessage::NegClose { subscription_id }) => {
2770                    reconciling.remove(subscription_id.as_ref());
2771                }
2772                Ok(ClientMessage::Auth(event)) => {
2773                    let ok = nostr::nips::nip42::is_valid_auth_event(&event, &url, &challenge);
2774                    if ok {
2775                        authed.insert(event.pubkey);
2776                    }
2777                    out.push(RelayMessage::ok(event.id, ok, if ok { "" } else { "invalid: auth" }));
2778                }
2779                Ok(ClientMessage::Event(event)) => {
2780                    out.push(RelayMessage::ok(event.id, true, ""));
2781                    held.lock().unwrap().push(event.into_owned());
2782                }
2783                _ => {}
2784            }
2785            for m in out {
2786                if sink.send(Ws::Text(m.as_json().into())).await.is_err() {
2787                    return;
2788                }
2789            }
2790        }
2791    }
2792}
2793
2794/// A [`Transport`] that fails on purpose.
2795///
2796/// `MemoryRelay` always succeeds: no failed fetch, no short page, no reordering,
2797/// no relay that serves a different subset than its siblings. Every strand and
2798/// fork this codebase has shipped lives in exactly the space it cannot express,
2799/// which is a large part of why none of them were caught by a test. This wraps it
2800/// and injects the failures a real relay set produces.
2801///
2802/// Deterministic by construction — the only randomness is a seeded counter, so a
2803/// failing scenario reproduces exactly from its seed.
2804#[cfg(test)]
2805pub(crate) mod adversarial {
2806    // A fault-injection toolkit: each scenario uses the rules it needs, and the rest
2807    // of the surface waits for the next scenario rather than being trimmed to fit.
2808    #![allow(dead_code)]
2809
2810    use super::memory::MemoryRelay;
2811    use super::*;
2812    use std::sync::atomic::{AtomicU64, Ordering};
2813    use std::sync::Mutex;
2814
2815    /// What a fetch should do instead of succeeding.
2816    #[derive(Clone, Debug)]
2817    pub enum Fault {
2818        /// Return `Err` — a dead relay, an AUTH gate, a timeout.
2819        FailFetch(String),
2820        /// Succeed, but serve at most `n` events — the "short page reads as the end
2821        /// of the plane" hazard.
2822        ShortPage(usize),
2823        /// Succeed, but serve nothing at all — a relay silently withholding.
2824        Empty,
2825        /// Serve at most `n` events from the relays that answered, while another
2826        /// stayed silent: a short page that is NOT the end of the plane.
2827        ShortUnconfirmed(usize),
2828    }
2829
2830    /// Which fetches a rule applies to. Matched against the query, so a plan can
2831    /// target one plane (an author) without knowing call order.
2832    #[derive(Clone, Debug, Default)]
2833    pub struct Match {
2834        /// Any of these authors appears in the query.
2835        pub author: Option<String>,
2836        /// Only the Nth matching call (1-based); `None` = every one.
2837        pub nth: Option<u64>,
2838        /// Only from this call onward (1-based).
2839        pub from_nth: Option<u64>,
2840    }
2841
2842    impl Match {
2843        pub fn author(hex: &str) -> Self {
2844            Match { author: Some(hex.to_string()), ..Default::default() }
2845        }
2846        pub fn any() -> Self {
2847            Match::default()
2848        }
2849        pub fn nth(mut self, n: u64) -> Self {
2850            self.nth = Some(n);
2851            self
2852        }
2853        pub fn from_nth(mut self, n: u64) -> Self {
2854            self.from_nth = Some(n);
2855            self
2856        }
2857    }
2858
2859    struct Rule {
2860        m: Match,
2861        fault: Fault,
2862        hits: AtomicU64,
2863    }
2864
2865    pub struct AdversarialRelay {
2866        inner: MemoryRelay,
2867        rules: Mutex<Vec<Rule>>,
2868        /// Every fetch, whether or not a rule matched — the round-trip counter a
2869        /// scale test asserts on ("~2 per hop, not ~97").
2870        fetches: AtomicU64,
2871    }
2872
2873    impl AdversarialRelay {
2874        pub fn new() -> Self {
2875            AdversarialRelay { inner: MemoryRelay::new(), rules: Mutex::new(Vec::new()), fetches: AtomicU64::new(0) }
2876        }
2877
2878        /// The underlying honest relay — publish fixtures through this so a fault
2879        /// plan governs only what the client can READ back.
2880        pub fn relay(&self) -> &MemoryRelay {
2881            &self.inner
2882        }
2883
2884        pub fn on(&self, m: Match, fault: Fault) -> &Self {
2885            self.rules.lock().unwrap_or_else(|e| e.into_inner()).push(Rule { m, fault, hits: AtomicU64::new(0) });
2886            self
2887        }
2888
2889        /// Drop every rule — "the faults cease", the precondition of the
2890        /// convergence property every scenario asserts.
2891        pub fn heal(&self) {
2892            self.rules.lock().unwrap_or_else(|e| e.into_inner()).clear();
2893        }
2894
2895        pub fn fetch_count(&self) -> u64 {
2896            self.fetches.load(Ordering::Relaxed)
2897        }
2898
2899        pub fn reset_fetch_count(&self) {
2900            self.fetches.store(0, Ordering::Relaxed);
2901        }
2902
2903        fn verdict(&self, query: &Query) -> Option<Fault> {
2904            let rules = self.rules.lock().unwrap_or_else(|e| e.into_inner());
2905            for r in rules.iter() {
2906                if let Some(a) = &r.m.author {
2907                    if !query.authors.iter().any(|q| q == a) {
2908                        continue;
2909                    }
2910                }
2911                let n = r.hits.fetch_add(1, Ordering::Relaxed) + 1;
2912                if r.m.nth.is_some_and(|want| want != n) {
2913                    continue;
2914                }
2915                if r.m.from_nth.is_some_and(|first| n < first) {
2916                    continue;
2917                }
2918                return Some(r.fault.clone());
2919            }
2920            None
2921        }
2922
2923        /// The served events, and whether every relay answered.
2924        async fn governed(&self, query: &Query, relays: &[String], plane: Option<&Keys>) -> Result<(Vec<Event>, bool), String> {
2925            self.fetches.fetch_add(1, Ordering::Relaxed);
2926            let short = match self.verdict(query) {
2927                Some(Fault::FailFetch(why)) => return Err(why),
2928                Some(Fault::Empty) => return Ok((Vec::new(), true)),
2929                Some(Fault::ShortPage(n)) => Some((n, true)),
2930                Some(Fault::ShortUnconfirmed(n)) => Some((n, false)),
2931                None => None,
2932            };
2933            let mut out = match plane {
2934                Some(p) => self.inner.fetch_plane(p, query, relays).await?.events,
2935                None => self.inner.fetch(query, relays).await?,
2936            };
2937            let Some((n, complete)) = short else { return Ok((out, true)) };
2938            out.truncate(n);
2939            Ok((out, complete))
2940        }
2941    }
2942
2943    #[async_trait::async_trait]
2944    impl Transport for AdversarialRelay {
2945        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2946            self.inner.publish(event, relays).await
2947        }
2948        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2949            self.inner.publish_durable(event, relays).await
2950        }
2951        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
2952            self.governed(query, relays, None).await.map(|(events, _)| events)
2953        }
2954        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String> {
2955            // `Empty` answers with nothing (coverage intact, so absence is real)
2956            // while `FailFetch` propagates an Err (nobody answered, so absence is
2957            // unproven) — the exact distinction the coverage field carries.
2958            let (events, complete) = self.governed(query, relays, Some(plane)).await?;
2959            Ok(if complete { PlaneFetch::whole(events) } else { PlaneFetch { events, answered: 1, attempted: 2 } })
2960        }
2961    }
2962}
2963
2964#[cfg(test)]
2965mod tests {
2966    use super::*;
2967
2968    /// Relays whose plane AUTH answers [`SlowAuth`] holds back.
2969    static SLOW_AUTH: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());
2970
2971    /// The plane authenticator, slowed for the relays in [`SLOW_AUTH`].
2972    #[derive(Debug)]
2973    pub(super) struct SlowAuth<T: nostr_sdk::prelude::Authenticator>(pub(super) T);
2974
2975    impl<T: nostr_sdk::prelude::Authenticator> nostr_sdk::prelude::Authenticator for SlowAuth<T> {
2976        fn make_auth_event<'a>(&'a self, relay_url: &'a RelayUrl, challenge: &'a str) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Event, nostr_sdk::prelude::Error>> + Send + 'a>> {
2977            Box::pin(async move {
2978                if SLOW_AUTH.lock().unwrap().contains(&crate::inbox_relays::normalize_relay_url(relay_url.as_str())) {
2979                    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
2980                }
2981                self.0.make_auth_event(relay_url, challenge).await
2982            })
2983        }
2984    }
2985
2986    // ── Plane read coverage ───────────────────────────────────────────────────
2987
2988    fn urls(n: usize) -> Vec<String> {
2989        (0..n).map(|i| format!("wss://r{i}")).collect()
2990    }
2991
2992    #[test]
2993    fn a_plane_read_that_skipped_a_tripped_relay_does_not_claim_full_coverage() {
2994        // A skipped relay was never asked, so whatever it holds is unseen: the read
2995        // may RETURN early, but it must not report every relay as having answered.
2996        let sel = plane_targets(urls(3), |r| r == "wss://r1");
2997        assert_eq!(sel.ask, vec!["wss://r0".to_string(), "wss://r2".to_string()], "the tripped relay is spared");
2998        let read = sel.fetched(Vec::new(), 2, sel.ask.len());
2999        assert_eq!((read.answered, read.attempted), (2, 3), "the skipped relay stays in the denominator");
3000        assert!(!read.is_complete(), "an empty answer from the asked relays is not proof of absence");
3001    }
3002
3003    #[test]
3004    fn a_plane_read_with_nothing_tripped_or_everything_tripped_asks_everyone() {
3005        let none = plane_targets(urls(3), |_| false);
3006        assert_eq!((none.ask.len(), none.skipped), (3, 0));
3007        assert!(none.fetched(Vec::new(), 3, 3).is_complete(), "every relay asked and answered IS full coverage");
3008        // Skipping every relay would ask nobody: ask them all rather than return nothing.
3009        let all = plane_targets(urls(3), |_| true);
3010        assert_eq!((all.ask.len(), all.skipped), (3, 0));
3011        assert!(all.fetched(Vec::new(), 3, 3).is_complete());
3012    }
3013
3014    #[test]
3015    fn a_dead_socket_leaves_the_denominator_but_a_tripped_relay_does_not() {
3016        // A dead socket can't answer this call at all, so it was never reachable;
3017        // a tripped relay merely answered badly lately and may hold the event.
3018        let sel = plane_targets(urls(4), |r| r == "wss://r3");
3019        let after_dead_sockets = sel.ask.len() - 1;
3020        let read = sel.fetched(Vec::new(), after_dead_sockets, after_dead_sockets);
3021        assert_eq!(read.attempted, 3, "asked minus the dead socket, plus the tripped relay");
3022        assert!(!read.is_complete());
3023    }
3024
3025    // ── Plane pool ────────────────────────────────────────────────────────────
3026
3027    /// Polls until `cond` holds: the sweep runs on real time, so wait for it rather than guess.
3028    async fn eventually(cond: impl Fn() -> bool) -> bool {
3029        for _ in 0..100 {
3030            if cond() {
3031                return true;
3032            }
3033            tokio::time::sleep(PLANE_POOL_IDLE_TTL / 4).await;
3034        }
3035        cond()
3036    }
3037
3038    #[tokio::test]
3039    async fn an_idle_plane_connection_closes_without_another_fetch() {
3040        // Its own pool: the global one is drained by any swap elsewhere in the suite.
3041        let pool: &'static PlanePool = Box::leak(Box::default());
3042        let in_pool = |key: &str| pool.lock().1.contains_key(key);
3043        let (kept, idle) = ("plane-kept|wss://a", "plane-idle|wss://a");
3044        pool.insert(0, idle.into(), crate::nostr_client_builder().build());
3045        pool.insert(0, kept.into(), crate::nostr_client_builder().build());
3046        assert!(in_pool(idle) && in_pool(kept));
3047
3048        // One stays in use (stamped ahead, so no sleep can let it lapse): only the idle one
3049        // goes, and nothing fetched to notice it.
3050        pool.lock().1.get_mut(kept).unwrap().last_used = web_time::Instant::now() + std::time::Duration::from_secs(60);
3051        assert!(eventually(|| !in_pool(idle)).await, "the idle connection was swept");
3052        assert!(in_pool(kept), "the one in use stays warm");
3053
3054        pool.lock().1.get_mut(kept).unwrap().last_used = web_time::Instant::now();
3055        assert!(eventually(|| !in_pool(kept)).await, "and goes once it idles too");
3056        let disarmed = || !pool.sweep_armed.load(std::sync::atomic::Ordering::Acquire);
3057        assert!(eventually(disarmed).await, "an empty pool runs no sweep");
3058    }
3059
3060    // ── Plane connections by relay gate ───────────────────────────────────────
3061
3062    /// A plane key and the one wrap it authored, held by `relay`.
3063    fn plane_on(relay: &wire::WireRelay) -> (Keys, Event) {
3064        use nostr_sdk::prelude::FinalizeEvent;
3065        let plane = Keys::generate();
3066        let wrap = EventBuilder::new(Kind::Custom(crate::community::v2::stream::KIND_WRAP), "sealed").finalize(&plane).unwrap();
3067        relay.hold([wrap.clone()]);
3068        (plane, wrap)
3069    }
3070
3071    async fn read_plane(relay: &wire::WireRelay, plane: &Keys) -> PlaneFetch {
3072        read_plane_at(relay.url(), plane.clone()).await
3073    }
3074
3075    async fn read_plane_at(url: String, plane: Keys) -> PlaneFetch {
3076        let query = Query {
3077            kinds: vec![crate::community::v2::stream::KIND_WRAP],
3078            authors: vec![plane.public_key().to_hex()],
3079            ..Default::default()
3080        };
3081        LiveTransport::with_timeout(std::time::Duration::from_secs(5)).fetch_plane(&plane, &query, &[url]).await.unwrap()
3082    }
3083
3084    fn gate_of(relay: &wire::WireRelay) -> Option<RelayGate> {
3085        with_plane_relay(crate::db::current_session_id(), &relay.url(), |r| r.gate)
3086    }
3087
3088    fn authed_pooled(plane: &Keys) -> bool {
3089        let pk = plane.public_key().to_hex();
3090        PLANE_POOL.lock().1.keys().any(|k| k.starts_with(&pk))
3091    }
3092
3093    fn open_pooled(relay: &wire::WireRelay) -> bool {
3094        OPEN_PLANES.lock().1.contains_key(&relay.url())
3095    }
3096
3097    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3098    #[allow(clippy::await_holding_lock)]
3099    async fn a_relay_that_never_challenges_serves_every_plane_over_one_connection() {
3100        let _s = GateScene::new();
3101        let relay = wire::WireRelay::start().await;
3102        let planes: Vec<(Keys, Event)> = (0..5).map(|_| plane_on(&relay)).collect();
3103        for (plane, wrap) in &planes {
3104            let read = read_plane(&relay, plane).await;
3105            assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3106            assert!(read.is_complete());
3107            assert!(!authed_pooled(plane), "no connection of its own");
3108        }
3109        assert_eq!(relay.opened(), 1, "five planes, one connection");
3110        assert_eq!(gate_of(&relay), Some(RelayGate::Open));
3111        assert!(open_pooled(&relay));
3112        clear_plane_pool();
3113        assert!(!open_pooled(&relay), "a swap closes it with the authed ones");
3114    }
3115
3116    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3117    #[allow(clippy::await_holding_lock)]
3118    async fn reads_that_reach_a_new_relay_together_dial_it_once() {
3119        let _s = GateScene::new();
3120        let relay = wire::WireRelay::start().await;
3121        let planes: Vec<(Keys, Event)> = (0..8).map(|_| plane_on(&relay)).collect();
3122        let reads = planes.iter().map(|(plane, _)| tokio::spawn(read_plane_at(relay.url(), plane.clone())));
3123        for read in futures_util::future::join_all(reads).await {
3124            assert_eq!(read.unwrap().events.len(), 1);
3125        }
3126        assert_eq!(relay.opened(), 1);
3127    }
3128
3129    #[tokio::test]
3130    #[allow(clippy::await_holding_lock)]
3131    async fn on_one_thread_a_challenge_inside_a_read_is_seen_by_that_read() {
3132        let _s = GateScene::new();
3133        let relay = wire::WireRelay::start().await;
3134        relay.gate(true);
3135        relay.quiet(true);
3136        let (plane, wrap) = plane_on(&relay);
3137        let read = read_plane(&relay, &plane).await;
3138        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3139        assert!(authed_pooled(&plane) && !open_pooled(&relay));
3140    }
3141
3142    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3143    #[allow(clippy::await_holding_lock)]
3144    async fn auth_required_without_a_challenge_is_still_a_gate() {
3145        let _s = GateScene::new();
3146        let relay = wire::WireRelay::start().await;
3147        relay.gate(true);
3148        relay.mute(true);
3149        let (plane, _) = plane_on(&relay);
3150        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3151        let read = LiveTransport::with_timeout(std::time::Duration::from_secs(2)).fetch_plane(&plane, &query, &[relay.url()]).await;
3152        assert!(read.is_err(), "nothing to authenticate against, so nothing served");
3153        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3154    }
3155
3156    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3157    #[allow(clippy::await_holding_lock)]
3158    async fn a_challenge_between_reads_moves_the_next_read_to_an_authed_connection() {
3159        let _s = GateScene::new();
3160        let relay = wire::WireRelay::start().await;
3161        relay.challenge_after_a_read(true);
3162        let (first, _) = plane_on(&relay);
3163        read_plane(&relay, &first).await;
3164        assert!(eventually(|| gate_of(&relay) == Some(RelayGate::Auth)).await, "the socket's watcher saw it");
3165        let (second, _) = plane_on(&relay);
3166        read_plane(&relay, &second).await;
3167        assert!(authed_pooled(&second));
3168    }
3169
3170    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3171    #[allow(clippy::await_holding_lock)]
3172    async fn a_socket_that_closes_under_a_read_ends_it_at_once() {
3173        let _s = GateScene::new();
3174        let relay = wire::WireRelay::start().await;
3175        relay.hang_up(true);
3176        let plane = Keys::generate();
3177        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3178        let started = web_time::Instant::now();
3179        let read = LiveTransport::with_timeout(std::time::Duration::from_secs(5)).fetch_plane(&plane, &query, &[relay.url()]).await;
3180        assert!(read.is_err(), "nothing answered");
3181        assert!(started.elapsed() < std::time::Duration::from_secs(2), "not left to its deadline: {:?}", started.elapsed());
3182    }
3183
3184    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3185    #[allow(clippy::await_holding_lock)]
3186    async fn reads_sharing_one_connection_stay_under_its_subscription_cap() {
3187        let _s = GateScene::new();
3188        let relay = wire::WireRelay::start().await;
3189        relay.cap_subs(16);
3190        let planes: Vec<(Keys, Event)> = (0..40).map(|_| plane_on(&relay)).collect();
3191        let reads = planes.iter().map(|(plane, _)| tokio::spawn(read_plane_at(relay.url(), plane.clone())));
3192        for read in futures_util::future::join_all(reads).await {
3193            assert_eq!(read.unwrap().events.len(), 1);
3194        }
3195        assert_eq!(relay.opened(), 1);
3196    }
3197
3198    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3199    #[allow(clippy::await_holding_lock)]
3200    async fn a_relay_that_cannot_be_reached_is_not_redialled_for_every_read() {
3201        use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
3202        let _s = GateScene::new();
3203        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3204        let url = format!("ws://127.0.0.1:{}", listener.local_addr().unwrap().port());
3205        let dials = std::sync::Arc::new(AtomicUsize::new(0));
3206        let counted = dials.clone();
3207        tokio::spawn(async move {
3208            while let Ok((tcp, _)) = listener.accept().await {
3209                counted.fetch_add(1, SeqCst);
3210                drop(tcp);
3211            }
3212        });
3213        let plane = Keys::generate();
3214        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3215        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(2));
3216        for _ in 0..3 {
3217            assert!(live.fetch_plane(&plane, &query, std::slice::from_ref(&url)).await.is_err(), "nothing answered");
3218        }
3219        assert_eq!(dials.load(SeqCst), 1, "one dial inside the redial gap");
3220        clear_plane_pool();
3221        assert!(live.fetch_plane(&plane, &query, std::slice::from_ref(&url)).await.is_err());
3222        assert_eq!(dials.load(SeqCst), 2, "a new network dials at once");
3223    }
3224
3225    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3226    #[allow(clippy::await_holding_lock)]
3227    async fn a_relay_that_asks_for_auth_reads_each_plane_on_a_connection_authed_as_it() {
3228        let _s = GateScene::new();
3229        let relay = wire::WireRelay::start().await;
3230        relay.gate(true);
3231        let planes: Vec<(Keys, Event)> = (0..3).map(|_| plane_on(&relay)).collect();
3232        for (plane, wrap) in &planes {
3233            let read = read_plane(&relay, plane).await;
3234            assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "served once authed as the plane");
3235            assert!(authed_pooled(plane));
3236        }
3237        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3238        assert!(!open_pooled(&relay), "the open connection closed at the first challenge");
3239        assert_eq!(relay.opened(), 1 + planes.len(), "the read that met the gate, then one per plane");
3240    }
3241
3242    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3243    #[allow(clippy::await_holding_lock)]
3244    async fn a_relay_that_starts_challenging_moves_its_planes_to_authed_connections() {
3245        let _s = GateScene::new();
3246        let relay = wire::WireRelay::start().await;
3247        let (first, _) = plane_on(&relay);
3248        read_plane(&relay, &first).await;
3249        assert_eq!((gate_of(&relay), relay.opened()), (Some(RelayGate::Open), 1));
3250
3251        relay.gate(true);
3252        let (second, wrap) = plane_on(&relay);
3253        let read = read_plane(&relay, &second).await;
3254        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "the same read, from an authed connection");
3255        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3256        assert!(authed_pooled(&second) && !open_pooled(&relay));
3257
3258        let (third, _) = plane_on(&relay);
3259        read_plane(&relay, &third).await;
3260        assert_eq!(relay.opened(), 3, "no read goes back to the open connection");
3261    }
3262
3263    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3264    #[allow(clippy::await_holding_lock)]
3265    async fn a_relay_that_challenges_then_answers_with_silence_still_serves_the_plane_once_authed() {
3266        let _s = GateScene::new();
3267        let relay = wire::WireRelay::start().await;
3268        relay.gate(true);
3269        relay.quiet(true);
3270        let (plane, wrap) = plane_on(&relay);
3271        let read = read_plane(&relay, &plane).await;
3272        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "the silence was no answer");
3273        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3274        assert!(authed_pooled(&plane));
3275    }
3276
3277    /// A port that refuses every connection.
3278    async fn refusing_url() -> String {
3279        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3280        let port = listener.local_addr().unwrap().port();
3281        drop(listener);
3282        format!("ws://127.0.0.1:{port}")
3283    }
3284
3285    async fn read_across(urls: &[String], plane: &Keys, timeout: std::time::Duration) -> PlaneFetch {
3286        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3287        LiveTransport::with_timeout(timeout).fetch_plane(plane, &query, urls).await.unwrap()
3288    }
3289
3290    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3291    #[allow(clippy::await_holding_lock)]
3292    async fn a_relay_never_reached_leaves_the_read_of_the_others_complete() {
3293        let _s = GateScene::new();
3294        let relay = wire::WireRelay::start().await;
3295        let (plane, _) = plane_on(&relay);
3296        let read = read_across(&[relay.url(), refusing_url().await], &plane, std::time::Duration::from_secs(2)).await;
3297        assert_eq!((read.answered, read.attempted), (1, 1));
3298        assert!(read.is_complete());
3299    }
3300
3301    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3302    #[allow(clippy::await_holding_lock)]
3303    async fn a_relay_that_refuses_the_read_keeps_it_incomplete() {
3304        let _s = GateScene::new();
3305        let (answers, refuses) = (wire::WireRelay::start().await, wire::WireRelay::start().await);
3306        refuses.refuse(true);
3307        let (plane, _) = plane_on(&answers);
3308        let read = read_across(&[answers.url(), refuses.url()], &plane, std::time::Duration::from_secs(2)).await;
3309        assert_eq!((read.answered, read.attempted), (1, 2));
3310        assert!(!read.is_complete());
3311        assert_eq!(gate_of(&refuses), None, "a refusal is no gate");
3312    }
3313
3314    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3315    #[allow(clippy::await_holding_lock)]
3316    async fn a_relay_still_connecting_is_read_not_dropped() {
3317        let _s = GateScene::new();
3318        let (quick, slow) = (wire::WireRelay::start().await, wire::WireRelay::start().await);
3319        slow.stall(std::time::Duration::from_millis(1500));
3320        let (plane, wrap) = plane_on(&slow);
3321        let read = read_across(&[quick.url(), slow.url()], &plane, std::time::Duration::from_secs(1)).await;
3322        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "the slow relay held it");
3323        assert_eq!((read.answered, read.attempted), (2, 2));
3324    }
3325
3326    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3327    #[allow(clippy::await_holding_lock)]
3328    async fn a_gating_relay_that_is_down_leaves_the_denominator_when_an_open_one_answered() {
3329        let _s = GateScene::new();
3330        let relay = wire::WireRelay::start().await;
3331        let down = refusing_url().await;
3332        mark_auth(crate::db::current_session_id(), &crate::inbox_relays::normalize_relay_url(&down));
3333        let (plane, wrap) = plane_on(&relay);
3334        let read = read_across(&[relay.url(), down], &plane, std::time::Duration::from_secs(2)).await;
3335        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3336        assert_eq!((read.answered, read.attempted), (1, 1));
3337    }
3338
3339    #[tokio::test]
3340    async fn a_previous_sessions_caller_leaves_the_pool_alone() {
3341        let pool: &'static PlanePool = Box::leak(Box::default());
3342        let build = || crate::nostr_client_builder().build();
3343        let (_, hold, _) = pool.take_or_insert(7, "wss://a", build).unwrap();
3344        let id = hold.id;
3345        assert!(pool.take_or_insert(6, "wss://a", build).is_none(), "an earlier session builds nothing");
3346        assert_eq!(pool.take(6, "wss://a").0.map(|_| ()), None);
3347        assert_eq!(pool.lock().0, 7);
3348        assert_eq!(pool.lock().1.get("wss://a").map(|p| p.id), Some(id), "and wipes nothing");
3349        assert!(pool.remove(7, "wss://a", id + 1).is_none(), "a replacement is not removed for its predecessor");
3350    }
3351
3352    #[tokio::test]
3353    async fn a_held_open_connection_outlives_the_idle_clock_and_goes_once_released() {
3354        let pool: &'static PlanePool = Box::leak(Box::default());
3355        let (_, hold, _) = pool.take_or_insert(1, "wss://a", || crate::nostr_client_builder().build()).unwrap();
3356        tokio::time::sleep(PLANE_POOL_IDLE_TTL * 3).await;
3357        assert!(pool.lock().1.contains_key("wss://a"), "a dial or read in flight keeps it");
3358        drop(hold);
3359        assert!(eventually(|| !pool.lock().1.contains_key("wss://a")).await, "and it idles out after");
3360    }
3361
3362    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3363    #[allow(clippy::await_holding_lock)]
3364    async fn a_challenge_on_connect_gates_the_first_read_however_late_its_watcher_runs() {
3365        let _s = GateScene::new();
3366        let relay = wire::WireRelay::start().await;
3367        let key = crate::inbox_relays::normalize_relay_url(&relay.url());
3368        UNWATCHED.lock().unwrap().insert(key.clone());
3369        relay.greet(true);
3370        let (plane, wrap) = plane_on(&relay);
3371        // Every read slot held until the greeting has long landed, so the read subscribes after it.
3372        let held = open_read_permits(&key).acquire_many_owned(OPEN_READS_PER_RELAY as u32).await.unwrap();
3373        let read = tokio::spawn({
3374            let (url, plane) = (relay.url(), plane.clone());
3375            async move { read_plane_at(url, plane).await }
3376        });
3377        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3378        drop(held);
3379        let read = read.await.unwrap();
3380        UNWATCHED.lock().unwrap().remove(&key);
3381        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3382        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3383        assert!(authed_pooled(&plane) && !open_pooled(&relay), "read again on a connection authed as the plane");
3384    }
3385
3386    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3387    #[allow(clippy::await_holding_lock)]
3388    async fn an_authed_read_asks_only_once_its_auth_has_landed() {
3389        let _s = GateScene::new();
3390        let relay = wire::WireRelay::start().await;
3391        relay.gate(true);
3392        relay.quiet(true);
3393        let key = crate::inbox_relays::normalize_relay_url(&relay.url());
3394        SLOW_AUTH.lock().unwrap().insert(key.clone());
3395        let (plane, wrap) = plane_on(&relay);
3396        let read = read_plane(&relay, &plane).await;
3397        SLOW_AUTH.lock().unwrap().remove(&key);
3398        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "an answer ahead of the AUTH is no answer");
3399        assert!(authed_pooled(&plane));
3400    }
3401
3402    #[tokio::test]
3403    async fn waiting_for_auth_ends_on_its_answer_and_never_starts_without_a_challenge() {
3404        let auth = || RelayNotification::Message { message: Box::new(RelayMessage::auth("c")) };
3405        let budget = std::time::Duration::from_secs(5);
3406        let started = tokio::time::Instant::now();
3407        authenticated(Box::pin(futures_util::stream::iter(vec![RelayNotification::Authenticated])), budget).await;
3408        authenticated(Box::pin(futures_util::stream::pending()), budget).await;
3409        assert!(started.elapsed() < std::time::Duration::from_secs(1), "no challenge, nothing to wait for");
3410        let answered = futures_util::stream::iter(vec![auth()]).chain(futures_util::stream::once(async {
3411            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
3412            RelayNotification::AuthenticationFailed
3413        }));
3414        let started = tokio::time::Instant::now();
3415        authenticated(Box::pin(answered.chain(futures_util::stream::pending())), budget).await;
3416        let waited = started.elapsed();
3417        assert!(waited >= std::time::Duration::from_millis(200) && waited < std::time::Duration::from_secs(2), "waited for the answer, refused or not: {waited:?}");
3418        let started = tokio::time::Instant::now();
3419        authenticated(Box::pin(futures_util::stream::iter(vec![auth()]).chain(futures_util::stream::pending())), std::time::Duration::from_millis(300)).await;
3420        assert!(started.elapsed() >= std::time::Duration::from_millis(300), "a challenge unanswered waits out the budget");
3421    }
3422
3423    #[test]
3424    fn a_settled_gate_reads_only_its_own_sockets_greeting() {
3425        let _s = GateScene::new();
3426        let generation = crate::db::current_session_id();
3427        let auth = || RelayNotification::Message { message: Box::new(RelayMessage::auth("c")) };
3428        let greet = |key: &str, id: u64, frames: Vec<RelayNotification>| {
3429            GREETINGS.lock().unwrap().insert((generation, key.to_string()), (id, Box::pin(futures_util::stream::iter(frames))));
3430        };
3431        greet("wss://greets", 1, vec![auth()]);
3432        assert_eq!(settle_gate(generation, "wss://greets", 1), RelayGate::Auth);
3433        greet("wss://quiet", 1, vec![]);
3434        assert_eq!(settle_gate(generation, "wss://quiet", 1), RelayGate::Open);
3435        greet("wss://replaced", 2, vec![auth()]);
3436        assert_eq!(settle_gate(generation, "wss://replaced", 1), RelayGate::Open, "another socket's greeting is not this one's");
3437        assert!(GREETINGS.lock().unwrap().contains_key(&(generation, "wss://replaced".to_string())), "and stays for its own socket");
3438        assert!(!GREETINGS.lock().unwrap().contains_key(&(generation, "wss://greets".to_string())), "a settled socket's frames are let go");
3439    }
3440
3441    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3442    #[allow(clippy::await_holding_lock)]
3443    async fn a_challenge_on_connect_is_a_gate_even_when_reads_are_served() {
3444        let _s = GateScene::new();
3445        let relay = wire::WireRelay::start().await;
3446        relay.greet(true);
3447        let (plane, wrap) = plane_on(&relay);
3448        let read = read_plane(&relay, &plane).await;
3449        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3450        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3451        assert!(authed_pooled(&plane) && !open_pooled(&relay));
3452    }
3453
3454    // ── Dead-socket target filtering ──────────────────────────────────────────
3455
3456    #[test]
3457    fn a_dead_socket_is_skipped_but_a_connecting_or_unknown_one_is_not() {
3458        let targets: Vec<String> = ["wss://dead", "wss://connecting", "wss://unknown"].map(String::from).into();
3459        let out = drop_unrevivable(targets, |r| r == "wss://dead");
3460        assert_eq!(out, ["wss://connecting", "wss://unknown"].map(String::from).to_vec());
3461    }
3462
3463    #[test]
3464    fn an_all_dead_set_falls_back_to_the_full_list() {
3465        // Offline (or a status race) must keep the honest-timeout error paths —
3466        // an instant empty-target "success" would read as a confident empty.
3467        let targets: Vec<String> = ["wss://a", "wss://b"].map(String::from).into();
3468        let out = drop_unrevivable(targets.clone(), |_| true);
3469        assert_eq!(out, targets);
3470    }
3471
3472    #[tokio::test]
3473    async fn pruning_severs_a_lone_community_relay_and_keeps_every_shared_one() {
3474        let client = crate::nostr_client_builder().build();
3475        let gossip = crate::community_relay_capabilities();
3476        for (url, caps) in [
3477            ("wss://left.example", gossip),
3478            ("wss://other.example", gossip),
3479            ("wss://nos.lol", crate::discovery_relay_capabilities()),
3480            ("wss://own-read.example", RelayCapabilities::READ),
3481            ("wss://own-write.example", RelayCapabilities::WRITE),
3482        ] {
3483            client.add_managed_relay(url).capabilities(caps).await.unwrap();
3484        }
3485        let candidates: Vec<String> = ["wss://left.example/", "wss://OTHER.example", "wss://nos.lol", "wss://own-read.example", "wss://own-write.example"]
3486            .map(String::from)
3487            .into();
3488        let needed = ["wss://other.example".to_string()].into_iter().collect();
3489        prune_relays(&client, &candidates, &needed).await;
3490
3491        let mut left: Vec<String> = client.relays().all().await.keys().map(|u| u.to_string().trim_end_matches('/').to_string()).collect();
3492        left.sort();
3493        assert_eq!(left, ["wss://nos.lol", "wss://other.example", "wss://own-read.example", "wss://own-write.example"]);
3494    }
3495
3496    // ── Ready gate (community publish while the chosen network still connects) ──
3497    // The live gate, `wait_transport_ready`, over the real transport state: a network installed
3498    // by hand stands in for Tor, so no live Tor is needed.
3499
3500    /// A network that is up or not as the test says, and dials nothing.
3501    struct Gate(std::sync::atomic::AtomicBool);
3502
3503    #[async_trait::async_trait]
3504    impl crate::transport::Transport for Gate {
3505        fn kind(&self) -> crate::transport::Kind {
3506            crate::transport::Kind::Tor
3507        }
3508        fn route(&self, dest: &crate::transport::Dest, port: u16, ctx: &crate::transport::RouteCtx) -> crate::transport::Route {
3509            crate::transport::route::route_tor(dest, port, ctx)
3510        }
3511        async fn dial(
3512            &self,
3513            _: &crate::transport::Route,
3514            _: crate::transport::Lane,
3515        ) -> Result<(crate::transport::BoxedStream, crate::transport::Dialed), crate::transport::ConnectError> {
3516            Err(crate::transport::ConnectError::Unreachable("gate".into()))
3517        }
3518        fn ready(&self) -> bool {
3519            self.0.load(std::sync::atomic::Ordering::SeqCst)
3520        }
3521        fn kind_status(&self) -> crate::transport::status::KindStatus {
3522            crate::transport::status::KindStatus::ready(serde_json::Value::Null)
3523        }
3524        async fn new_identity(&self) {}
3525        async fn shutdown(&self) {}
3526        fn into_any(self: std::sync::Arc<Self>) -> std::sync::Arc<dyn std::any::Any + Send + Sync> {
3527            self
3528        }
3529    }
3530
3531    #[test]
3532    fn an_auth_record_stands_three_days_is_refreshed_daily_and_one_without_a_time_never_counts() {
3533        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3534        crate::db::close_database();
3535        crate::db::clear_id_caches();
3536        use nostr_sdk::prelude::ToBech32;
3537        let tmp = tempfile::tempdir().unwrap();
3538        let account = Keys::generate().public_key().to_bech32().unwrap();
3539        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
3540        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
3541        crate::db::set_current_account(account.clone()).unwrap();
3542        crate::db::init_database(&account).unwrap();
3543
3544        let url = "wss://gate.example/nostr";
3545        let set = |at: String| crate::db::set_sql_setting(super::auth_gate_setting(url), at).unwrap();
3546        let ago = |secs: u64| (super::now_secs() - secs).to_string();
3547        assert!(!super::auth_gate_live(url));
3548        set("1".into());
3549        assert!(!super::auth_gate_live(url), "a record from before the TTL says nothing of today");
3550        super::note_auth_gate(url);
3551        assert!(super::auth_gate_live(url));
3552        set(ago(super::AUTH_GATE_TTL_SECS - 60));
3553        assert!(super::auth_gate_live(url));
3554        set(ago(super::AUTH_GATE_TTL_SECS + 1));
3555        assert!(!super::auth_gate_live(url), "a relay that stopped asking is read openly again");
3556
3557        set(ago(3600));
3558        super::note_auth_gate(url);
3559        assert_eq!(super::auth_gate_at(url), Some(super::now_secs() - 3600), "no rewrite within a day");
3560        set(ago(super::AUTH_GATE_REFRESH_SECS + 1));
3561        super::note_auth_gate(url);
3562        assert!(super::auth_gate_at(url).is_some_and(|at| super::now_secs() - at < 5), "a day on, a challenge refreshes it");
3563    }
3564
3565    /// Holds the process-wide network for one test and puts Clearnet back however it ends.
3566    struct GateScene(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);
3567
3568    impl GateScene {
3569        fn new() -> Self {
3570            let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3571            drop(crate::transport::host::uninstall());
3572            GateScene(guard)
3573        }
3574    }
3575
3576    impl Drop for GateScene {
3577        fn drop(&mut self) {
3578            drop(crate::transport::host::uninstall());
3579            crate::transport::budget::clear_overrides_for_test();
3580            crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
3581        }
3582    }
3583
3584    #[tokio::test]
3585    #[allow(clippy::await_holding_lock)]
3586    async fn ready_gate_passes_at_once_when_nothing_holds_traffic() {
3587        let _s = GateScene::new();
3588        crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
3589        let start = web_time::Instant::now();
3590        assert!(wait_transport_ready().await.is_ok());
3591        crate::transport::set_preference(Some(crate::transport::Kind::Tor));
3592        let gate = std::sync::Arc::new(Gate(std::sync::atomic::AtomicBool::new(true)));
3593        crate::transport::host::activate(gate, crate::db::live_session_id(), false).unwrap();
3594        assert!(wait_transport_ready().await.is_ok());
3595        assert!(start.elapsed() < std::time::Duration::from_millis(500), "must not wait while ready");
3596    }
3597
3598    #[tokio::test]
3599    #[allow(clippy::await_holding_lock)]
3600    async fn ready_gate_errors_honestly_after_its_window() {
3601        // Without the gate a send failed at once with a misleading "no relay accepted"; with
3602        // it, it waits the window and then names the cause.
3603        let _s = GateScene::new();
3604        crate::transport::budget::override_for_test(crate::transport::Op::ReadyWait, Some(std::time::Duration::from_millis(300)));
3605        crate::transport::set_preference(Some(crate::transport::Kind::Tor));
3606        let gate = std::sync::Arc::new(Gate(std::sync::atomic::AtomicBool::new(false)));
3607        crate::transport::host::activate(gate, crate::db::live_session_id(), false).unwrap();
3608        let start = web_time::Instant::now();
3609        let err = wait_transport_ready().await.expect_err("Tor never comes up");
3610        assert_eq!(err, "Tor is still connecting. Wait a moment and try again.");
3611        let took = start.elapsed();
3612        assert!(took >= std::time::Duration::from_millis(300) && took < std::time::Duration::from_millis(1500), "{took:?}");
3613
3614        // A network this build lacks never comes: no wait, and its own words.
3615        if !crate::transport::Kind::Tor.compiled() {
3616            drop(crate::transport::host::uninstall());
3617            let start = web_time::Instant::now();
3618            assert_eq!(wait_transport_ready().await.unwrap_err(), "This build doesn't include Tor.");
3619            assert!(start.elapsed() < std::time::Duration::from_millis(100));
3620        }
3621    }
3622
3623    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3624    #[allow(clippy::await_holding_lock)]
3625    async fn ready_gate_passes_once_the_network_comes_up_mid_wait() {
3626        let _s = GateScene::new();
3627        crate::transport::budget::override_for_test(crate::transport::Op::ReadyWait, Some(std::time::Duration::from_secs(10)));
3628        crate::transport::set_preference(Some(crate::transport::Kind::Tor));
3629        let gate = std::sync::Arc::new(Gate(std::sync::atomic::AtomicBool::new(false)));
3630        let inst = crate::transport::host::activate(gate.clone(), crate::db::live_session_id(), false).unwrap();
3631        let id = inst.id();
3632        let up = tokio::spawn(async move {
3633            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
3634            gate.0.store(true, std::sync::atomic::Ordering::SeqCst);
3635            crate::transport::host::notify(crate::transport::host::TransportEvent::Ready {
3636                kind: crate::transport::Kind::Tor,
3637                instance: id,
3638                owner: crate::db::live_session_id(),
3639                recovered: false,
3640            });
3641        });
3642        let start = web_time::Instant::now();
3643        assert!(wait_transport_ready().await.is_ok(), "passes once the network is up");
3644        assert!(start.elapsed() < std::time::Duration::from_secs(2), "woken by the change, not the window");
3645        up.await.unwrap();
3646    }
3647
3648    fn evt(kind: u16, z: &str) -> Event {
3649        EventBuilder::new(Kind::Custom(kind), "x")
3650            .tags([Tag::custom(
3651                "z",
3652                [z.to_string()],
3653            )])
3654            .finalize(&Keys::generate())
3655            .unwrap()
3656    }
3657
3658    #[test]
3659    fn query_matches_kind_and_z() {
3660        let e = evt(3300, "abc");
3661        assert!(Query { kinds: vec![3300], z_tags: vec!["abc".into()], since: None, ..Default::default() }.matches(&e));
3662        assert!(!Query { kinds: vec![3301], ..Default::default() }.matches(&e));
3663        assert!(!Query { kinds: vec![], z_tags: vec!["xyz".into()], since: None, ..Default::default() }.matches(&e));
3664        assert!(Query::default().matches(&e), "empty query matches anything");
3665    }
3666
3667    fn evt_at(kind: u16, secs: u64) -> Event {
3668        EventBuilder::new(Kind::Custom(kind), "x")
3669            .custom_created_at(Timestamp::from(secs))
3670            .finalize(&Keys::generate())
3671            .unwrap()
3672    }
3673
3674    /// Build a z-tagged event at a controlled created_at (for deterministic paging tests —
3675    /// the real outer events carry wall-clock send time).
3676    fn evt_z_at(kind: u16, z: &str, secs: u64) -> Event {
3677        EventBuilder::new(Kind::Custom(kind), "x")
3678            .custom_created_at(Timestamp::from(secs))
3679            .tags([Tag::custom(
3680                "z",
3681                [z.to_string()],
3682            )])
3683            .finalize(&Keys::generate())
3684            .unwrap()
3685    }
3686
3687    #[tokio::test]
3688    async fn fetch_pages_with_until_and_limit_newest_first() {
3689        // The Discord-style paging mechanism: `limit` caps newest-first; `until` walks older.
3690        let relay = super::memory::MemoryRelay::new();
3691        let relays = vec!["r1".to_string()];
3692        for s in 1..=5u64 {
3693            relay.inject(&evt_z_at(3300, "pg", s), &relays);
3694        }
3695        let secs = |evs: &[Event]| evs.iter().map(|e| e.created_at.as_secs()).collect::<Vec<_>>();
3696
3697        // Latest page: the two newest (secs 5, 4), newest-first.
3698        let latest = relay
3699            .fetch(&Query { kinds: vec![3300], z_tags: vec!["pg".into()], limit: Some(2), ..Default::default() }, &relays)
3700            .await
3701            .unwrap();
3702        assert_eq!(secs(&latest), vec![5, 4]);
3703
3704        // Older page before the cursor (until=3, inclusive): secs 3, 2.
3705        let older = relay
3706            .fetch(&Query { kinds: vec![3300], z_tags: vec!["pg".into()], until: Some(3), limit: Some(2), ..Default::default() }, &relays)
3707            .await
3708            .unwrap();
3709        assert_eq!(secs(&older), vec![3, 2]);
3710
3711        // Start of history: until=1 returns only the single oldest event — the signal the
3712        // caller uses to mark "no more older" and stop hitting the network.
3713        let start = relay
3714            .fetch(&Query { kinds: vec![3300], z_tags: vec!["pg".into()], until: Some(1), limit: Some(2), ..Default::default() }, &relays)
3715            .await
3716            .unwrap();
3717        assert_eq!(secs(&start), vec![1]);
3718    }
3719
3720    // ── A page read from several relays ───────────────────────────────────────
3721
3722    fn page_of(secs: &[u64]) -> Vec<Event> {
3723        secs.iter().map(|s| evt_at(3300, *s)).collect()
3724    }
3725
3726    fn paged(limit: usize, until: Option<u64>) -> Query {
3727        Query { kinds: vec![3300], limit: Some(limit), until, paged: true, ..Default::default() }
3728    }
3729
3730    fn secs_of(events: &[Event]) -> Vec<u64> {
3731        let mut secs: Vec<u64> = events.iter().map(|e| e.created_at.as_secs()).collect();
3732        secs.sort_unstable_by(|a, b| b.cmp(a));
3733        secs
3734    }
3735
3736    #[test]
3737    fn a_page_is_cut_where_the_shallowest_full_answer_ended() {
3738        let mut floor = PageFloor::of(&paged(3, None)).unwrap();
3739        floor.note(&page_of(&[10, 9, 8]));
3740        floor.note(&page_of(&[10, 9, 3]));
3741        let mut union = page_of(&[10, 9, 8, 3]);
3742        floor.cut(&mut union);
3743        assert_eq!(secs_of(&union), vec![10, 9, 8], "below 8 the first relay hasn't been asked");
3744    }
3745
3746    #[test]
3747    fn a_short_answer_cuts_nothing() {
3748        let mut floor = PageFloor::of(&paged(3, None)).unwrap();
3749        floor.note(&page_of(&[10, 9]));
3750        let mut union = page_of(&[10, 9]);
3751        floor.cut(&mut union);
3752        assert_eq!(secs_of(&union), vec![10, 9]);
3753        floor.note(&page_of(&[10, 7, 5]));
3754        let mut union = page_of(&[10, 9, 7, 5]);
3755        floor.cut(&mut union);
3756        assert_eq!(secs_of(&union), vec![10, 9, 7, 5], "a relay at the end of its plane holds nothing further down for a deeper page to wait on");
3757    }
3758
3759    #[test]
3760    fn a_full_answer_no_deeper_than_it_was_asked_from_cuts_nothing() {
3761        let mut floor = PageFloor::of(&paged(3, Some(8))).unwrap();
3762        floor.note(&page_of(&[8, 8, 8]));
3763        floor.note(&page_of(&[8, 5, 4]));
3764        let mut union = page_of(&[8, 8, 8, 8, 5, 4]);
3765        floor.cut(&mut union);
3766        assert_eq!(secs_of(&union), vec![8, 8, 8, 8, 5, 4], "a relay stuck on one second leaves the walk to the others, as before");
3767    }
3768
3769    #[test]
3770    fn only_a_paged_query_with_a_limit_is_cut() {
3771        assert!(PageFloor::of(&Query { limit: Some(3), ..Default::default() }).is_none());
3772        assert!(PageFloor::of(&Query { paged: true, ..Default::default() }).is_none());
3773        assert!(PageFloor::of(&Query { paged: true, limit: Some(0), ..Default::default() }).is_none());
3774    }
3775
3776    /// A plane walked to its end as the pagers walk one: inclusive `until`, on from the oldest
3777    /// event the page gave.
3778    async fn walk<T: Transport>(transport: &T, relays: &[String], mut query: Query) -> Vec<u64> {
3779        let mut seen = std::collections::HashSet::new();
3780        let mut read = Vec::new();
3781        let mut oldest: Option<u64> = None;
3782        for _ in 0..64 {
3783            query.until = oldest;
3784            let page = transport.fetch(&query, relays).await.unwrap();
3785            let fresh: Vec<u64> = page.iter().filter(|e| seen.insert(e.id)).map(|e| e.created_at.as_secs()).collect();
3786            if fresh.is_empty() {
3787                break;
3788            }
3789            oldest = oldest.into_iter().chain(fresh.iter().copied()).min();
3790            read.extend(fresh);
3791        }
3792        read.sort_unstable();
3793        read
3794    }
3795
3796    /// Events at seconds 1 to 10 on `full`, and on `sparse` all but 4 to 8.
3797    fn differing(mut hold: impl FnMut(&Event, bool)) {
3798        for s in 1..=10u64 {
3799            hold(&evt_at(3300, s), !(4..=8).contains(&s));
3800        }
3801    }
3802
3803    #[tokio::test]
3804    async fn a_walk_over_relays_that_hold_different_amounts_reads_every_event() {
3805        let relay = super::memory::MemoryRelay::new();
3806        let both = ["wss://full".to_string(), "wss://sparse".to_string()];
3807        differing(|e, on_sparse| {
3808            relay.inject(e, &both[..1]);
3809            if on_sparse {
3810                relay.inject(e, &both[1..]);
3811            }
3812        });
3813        assert_eq!(walk(&relay, &both, paged(3, None)).await, (1..=10).collect::<Vec<_>>());
3814        // Unpaged, every relay's newest page comes back whole: the sparse one's reaches down to
3815        // 3, and a walk going on from there never asks the full one for 4 to 7.
3816        let unpaged = Query { paged: false, ..paged(3, None) };
3817        assert_eq!(walk(&relay, &both, unpaged).await, vec![1, 2, 3, 8, 9, 10]);
3818    }
3819
3820    fn plane_wraps(plane: &Keys, secs: impl IntoIterator<Item = u64>) -> Vec<Event> {
3821        use nostr_sdk::prelude::FinalizeEvent;
3822        secs.into_iter()
3823            .map(|s| EventBuilder::new(Kind::Custom(crate::community::v2::stream::KIND_WRAP), "sealed").custom_created_at(Timestamp::from(s)).finalize(plane).unwrap())
3824            .collect()
3825    }
3826
3827    /// A plane's wraps at seconds 1 to 10 on one relay, and all but 4 to 8 on another.
3828    async fn differing_wire(plane: &Keys) -> (wire::WireRelay, wire::WireRelay) {
3829        let (full, sparse) = (wire::WireRelay::start().await, wire::WireRelay::start().await);
3830        let wraps = plane_wraps(plane, 1..=10);
3831        sparse.hold(wraps.iter().filter(|w| !(4..=8).contains(&w.created_at.as_secs())).cloned());
3832        full.hold(wraps);
3833        (full, sparse)
3834    }
3835
3836    fn plane_page(plane: &Keys) -> Query {
3837        Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], limit: Some(3), paged: true, ..Default::default() }
3838    }
3839
3840    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3841    #[allow(clippy::await_holding_lock)]
3842    async fn a_paged_plane_read_stops_where_the_shallowest_relay_did() {
3843        let _s = GateScene::new();
3844        let plane = Keys::generate();
3845        let (full, sparse) = differing_wire(&plane).await;
3846        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(5));
3847        let read = live.fetch_plane(&plane, &plane_page(&plane), &[full.url(), sparse.url()]).await.unwrap();
3848        assert_eq!(secs_of(&read.events), vec![10, 9, 8]);
3849        assert!(read.is_complete());
3850    }
3851
3852    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3853    #[allow(clippy::await_holding_lock)]
3854    async fn a_paged_plane_read_over_authed_connections_stops_there_too() {
3855        let _s = GateScene::new();
3856        let plane = Keys::generate();
3857        let (full, sparse) = differing_wire(&plane).await;
3858        full.gate(true);
3859        sparse.gate(true);
3860        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(5));
3861        let urls = [full.url(), sparse.url()];
3862        let learning = live.fetch_plane(&plane, &plane_page(&plane), &urls).await.unwrap();
3863        assert_eq!(secs_of(&learning.events), vec![10, 9, 8], "the read that learns both relays gate");
3864        assert_eq!((gate_of(&full), gate_of(&sparse)), (Some(RelayGate::Auth), Some(RelayGate::Auth)));
3865        let knowing = live.fetch_plane(&plane, &plane_page(&plane), &urls).await.unwrap();
3866        assert_eq!(secs_of(&knowing.events), vec![10, 9, 8], "and the next, which knows");
3867    }
3868
3869    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3870    #[allow(clippy::await_holding_lock)]
3871    async fn a_paged_fetch_stops_where_the_shallowest_relay_did() {
3872        let _s = GateScene::new();
3873        let plane = Keys::generate();
3874        let (full, sparse) = differing_wire(&plane).await;
3875        crate::state::set_nostr_client(crate::nostr_client_builder().build());
3876        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(5));
3877        let urls = [full.url(), sparse.url()];
3878        let read = live.fetch(&Query { evidence: Evidence::Full, ..plane_page(&plane) }, &urls).await;
3879        let walked = walk(&live, &urls, Query { evidence: Evidence::Full, ..plane_page(&plane) }).await;
3880        let _ = crate::state::take_nostr_client();
3881        assert_eq!(secs_of(&read.unwrap()), vec![10, 9, 8]);
3882        assert_eq!(walked, (1..=10).collect::<Vec<_>>());
3883    }
3884
3885    #[test]
3886    fn to_filter_translates_kinds_z_and_since() {
3887        // The live/test-parity claim rests on to_filter matching matches(); assert
3888        // the Filter directly. An event the Query matches must also pass the Filter.
3889        let q = Query { kinds: vec![3300], z_tags: vec!["abc".into()], since: Some(100), ..Default::default() };
3890        let filter = q.to_filter();
3891        let matching = EventBuilder::new(Kind::Custom(3300), "x")
3892            .custom_created_at(Timestamp::from(150))
3893            .tags([Tag::custom(
3894                "z",
3895                ["abc".to_string()],
3896            )])
3897            .finalize(&Keys::generate())
3898            .unwrap();
3899        assert!(filter.match_event(&matching, MatchEventOptions::new()), "to_filter must accept what matches() accepts");
3900        assert!(q.matches(&matching));
3901
3902        // Wrong kind, wrong z, and too-early all rejected by the same Filter.
3903        let wrong_kind = EventBuilder::new(Kind::Custom(3301), "x")
3904            .custom_created_at(Timestamp::from(150))
3905            .tags([Tag::custom(
3906                "z",
3907                ["abc".to_string()],
3908            )])
3909            .finalize(&Keys::generate())
3910            .unwrap();
3911        assert!(!filter.match_event(&wrong_kind, MatchEventOptions::new()));
3912    }
3913
3914    /// Build an event carrying one arbitrary single-letter tag (recipient `p`, wrapped-kind `k`).
3915    fn evt_sl(kind: u16, letter: SingleLetterTag, value: &str) -> Event {
3916        EventBuilder::new(Kind::Custom(kind), "x")
3917            .tags([Tag::custom(
3918                letter.as_char().to_string(),
3919                [value.to_string()],
3920            )])
3921            .finalize(&Keys::generate())
3922            .unwrap()
3923    }
3924
3925    #[test]
3926    fn to_filter_and_matches_agree_on_authors() {
3927        let keys = Keys::generate();
3928        let e = EventBuilder::new(Kind::Custom(1059), "x").finalize(&keys).unwrap();
3929        let q = Query { kinds: vec![1059], authors: vec![keys.public_key().to_hex()], ..Default::default() };
3930        assert!(q.matches(&e));
3931        assert!(q.to_filter().match_event(&e, MatchEventOptions::new()));
3932        let miss = Query { kinds: vec![1059], authors: vec![Keys::generate().public_key().to_hex()], ..Default::default() };
3933        assert!(!miss.matches(&e));
3934        assert!(!miss.to_filter().match_event(&e, MatchEventOptions::new()));
3935    }
3936
3937    #[test]
3938    fn to_filter_and_matches_agree_on_p_tags() {
3939        let recipient = Keys::generate().public_key().to_hex();
3940        let e = evt_sl(1059, SingleLetterTag::LOWERCASE_P, &recipient);
3941        let q = Query { kinds: vec![1059], p_tags: vec![recipient], ..Default::default() };
3942        assert!(q.matches(&e));
3943        assert!(q.to_filter().match_event(&e, MatchEventOptions::new()));
3944        let miss = Query { kinds: vec![1059], p_tags: vec![Keys::generate().public_key().to_hex()], ..Default::default() };
3945        assert!(!miss.matches(&e));
3946        assert!(!miss.to_filter().match_event(&e, MatchEventOptions::new()));
3947    }
3948
3949    #[test]
3950    fn to_filter_and_matches_agree_on_k_tags() {
3951        let e = evt_sl(1059, SingleLetterTag::LOWERCASE_K, "3311");
3952        let q = Query { kinds: vec![1059], k_tags: vec!["3311".into()], ..Default::default() };
3953        assert!(q.matches(&e));
3954        assert!(q.to_filter().match_event(&e, MatchEventOptions::new()));
3955        let miss = Query { kinds: vec![1059], k_tags: vec!["3300".into()], ..Default::default() };
3956        assert!(!miss.matches(&e));
3957        assert!(!miss.to_filter().match_event(&e, MatchEventOptions::new()));
3958    }
3959
3960    #[test]
3961    fn to_filter_empty_kinds_only_constrains_z_and_since() {
3962        // Empty kinds = no kind constraint, matching matches()' behavior.
3963        let q = Query { kinds: vec![], z_tags: vec!["p".into()], since: None, ..Default::default() };
3964        let filter = q.to_filter();
3965        let e = evt(3300, "p");
3966        assert!(filter.match_event(&e, MatchEventOptions::new()));
3967        assert!(q.matches(&e));
3968    }
3969
3970    #[test]
3971    fn since_is_an_inclusive_lower_bound() {
3972        let below = evt_at(3300, 99);
3973        let exact = evt_at(3300, 100);
3974        let above = evt_at(3300, 101);
3975        let q = Query { kinds: vec![3300], z_tags: vec![], since: Some(100), ..Default::default() };
3976        assert!(!q.matches(&below), "below the floor is excluded");
3977        assert!(q.matches(&exact), "exactly the floor is included");
3978        assert!(q.matches(&above), "above the floor is included");
3979    }
3980
3981    #[test]
3982    fn z_tags_match_as_or_set() {
3983        // The whole-channel fetch lists multiple epoch pseudonyms; an event
3984        // tagged with any one of them must match.
3985        let e = evt(3300, "p2");
3986        let q = Query { kinds: vec![3300], z_tags: vec!["p1".into(), "p2".into()], since: None, ..Default::default() };
3987        assert!(q.matches(&e));
3988        let miss = Query { kinds: vec![3300], z_tags: vec!["p1".into(), "p3".into()], since: None, ..Default::default() };
3989        assert!(!miss.matches(&e));
3990    }
3991
3992    #[tokio::test]
3993    async fn fetch_unions_and_dedups_across_relays() {
3994        use super::memory::MemoryRelay;
3995        let relay = MemoryRelay::new();
3996        let relays = vec!["r1".to_string(), "r2".to_string(), "r3".to_string()];
3997        let e = evt(3300, "p");
3998        relay.publish(&e, &relays).await.unwrap();
3999        let got = relay
4000            .fetch(&Query { kinds: vec![3300], z_tags: vec!["p".into()], since: None, ..Default::default() }, &relays)
4001            .await
4002            .unwrap();
4003        assert_eq!(got.len(), 1, "same event on 3 relays dedups to 1");
4004    }
4005
4006    #[tokio::test]
4007    async fn durable_broadcast_retries_only_the_failing_relays_until_they_ack() {
4008        // r1/r3 ACK on round 1; r2 fails the first 4 rounds then ACKs. The engine must keep re-sending
4009        // ONLY r2 (not the already-ACKed r1/r3) until it lands, and succeed.
4010        use std::cell::Cell;
4011        let relays = vec!["r1".to_string(), "r2".to_string(), "r3".to_string()];
4012        let round = Cell::new(0usize);
4013        let r2_round_seen = Cell::new(0usize);
4014        let res = durable_broadcast(&relays, 30, std::time::Duration::ZERO, |pending| {
4015            let n = round.get();
4016            round.set(n + 1);
4017            // r2 is only ever retried alone after round 1 — assert we never re-send a relay that ACKed.
4018            if n >= 1 {
4019                assert_eq!(pending, vec!["r2".to_string()], "only the failing relay is retried");
4020                r2_round_seen.set(r2_round_seen.get() + 1);
4021            }
4022            Box::pin(async move {
4023                pending.into_iter().filter(|r| r != "r2" || n >= 4).collect()
4024            })
4025        })
4026        .await;
4027        assert!(res.is_ok(), "all relays eventually ACK → Ok");
4028        assert!(round.get() >= 5, "kept retrying r2 across rounds");
4029    }
4030
4031    #[tokio::test]
4032    async fn durable_broadcast_is_ok_if_some_ack_even_when_one_never_does() {
4033        // r1 ACKs; r2 never does. After exhausting r2's retries, the event is still durably out (r1 has
4034        // it, fetch-union covers r2), so the result is Ok — durability is best-effort per relay.
4035        let relays = vec!["r1".to_string(), "r2".to_string()];
4036        let res = durable_broadcast(&relays, 5, std::time::Duration::ZERO, |pending| {
4037            Box::pin(async move { pending.into_iter().filter(|r| r == "r1").collect() })
4038        })
4039        .await;
4040        assert!(res.is_ok(), "≥1 relay accepted → Ok despite a permanently-failing relay");
4041    }
4042
4043    #[tokio::test]
4044    async fn durable_broadcast_errs_only_if_zero_relays_ever_accept() {
4045        let relays = vec!["r1".to_string(), "r2".to_string()];
4046        let res = durable_broadcast(&relays, 5, std::time::Duration::ZERO, |_pending| {
4047            Box::pin(async move { Vec::new() }) // nobody ever ACKs
4048        })
4049        .await;
4050        assert!(res.is_err(), "zero acceptances after the retry cap → Err");
4051    }
4052
4053    #[tokio::test]
4054    async fn redundancy_self_heals_a_missing_relay() {
4055        use super::memory::MemoryRelay;
4056        let relay = MemoryRelay::new();
4057        let all = vec!["r1".to_string(), "r2".to_string(), "r3".to_string()];
4058        let e = evt(3300, "p");
4059        // Event lands on ONLY r2 (the others "missed" it).
4060        relay.inject(&e, &["r2".to_string()]);
4061        assert_eq!(relay.count_on("r1"), 0);
4062        assert_eq!(relay.count_on("r2"), 1);
4063        // A fetch across the full set still finds it (redundancy).
4064        let got = relay.fetch(&Query { kinds: vec![3300], ..Default::default() }, &all).await.unwrap();
4065        assert_eq!(got.len(), 1);
4066    }
4067
4068    #[tokio::test]
4069    async fn ephemeral_kind_streams_live_but_is_never_stored_or_fetched() {
4070        use super::memory::MemoryRelay;
4071        let relay = MemoryRelay::new();
4072        let relays = vec!["r1".to_string()];
4073        let mut sub = relay.subscribe(Query { kinds: vec![21059], ..Default::default() });
4074        let e = evt(21059, "p");
4075        relay.publish(&e, &relays).await.unwrap();
4076        assert_eq!(relay.count_on("r1"), 0, "ephemeral is never stored");
4077        let got = relay
4078            .fetch(&Query { kinds: vec![21059], ..Default::default() }, &relays)
4079            .await
4080            .unwrap();
4081        assert!(got.is_empty(), "a real relay never serves an ephemeral from a fetch");
4082        assert_eq!(sub.try_recv().unwrap().id, e.id, "but a live subscriber receives it");
4083    }
4084
4085    #[tokio::test]
4086    async fn stored_kind_is_fetchable_and_delivered_live() {
4087        use super::memory::MemoryRelay;
4088        let relay = MemoryRelay::new();
4089        let relays = vec!["r1".to_string()];
4090        let mut sub = relay.subscribe(Query { kinds: vec![1059], ..Default::default() });
4091        let e = evt(1059, "p");
4092        relay.publish(&e, &relays).await.unwrap();
4093        let got = relay
4094            .fetch(&Query { kinds: vec![1059], ..Default::default() }, &relays)
4095            .await
4096            .unwrap();
4097        assert_eq!(got.len(), 1, "stored kind is fetchable");
4098        assert_eq!(sub.try_recv().unwrap().id, e.id, "and delivered to the live subscriber");
4099    }
4100
4101    #[tokio::test]
4102    async fn p_tags_route_a_giftwrap_to_the_matching_subscriber() {
4103        use super::memory::MemoryRelay;
4104        let relay = MemoryRelay::new();
4105        let relays = vec!["r1".to_string()];
4106        let alice = Keys::generate().public_key().to_hex();
4107        let bob = Keys::generate().public_key().to_hex();
4108        let mut sub_alice =
4109            relay.subscribe(Query { kinds: vec![1059], p_tags: vec![alice.clone()], ..Default::default() });
4110        let mut sub_bob =
4111            relay.subscribe(Query { kinds: vec![1059], p_tags: vec![bob.clone()], ..Default::default() });
4112        let wrap = evt_sl(1059, SingleLetterTag::LOWERCASE_P, &alice);
4113        relay.publish(&wrap, &relays).await.unwrap();
4114        assert_eq!(sub_alice.try_recv().unwrap().id, wrap.id, "addressed recipient gets it live");
4115        assert!(sub_bob.try_recv().is_err(), "a differently-addressed subscriber does not");
4116        // Fetch agrees with the live routing.
4117        let for_alice = relay
4118            .fetch(&Query { kinds: vec![1059], p_tags: vec![alice], ..Default::default() }, &relays)
4119            .await
4120            .unwrap();
4121        assert_eq!(for_alice.len(), 1);
4122        let for_bob = relay
4123            .fetch(&Query { kinds: vec![1059], p_tags: vec![bob], ..Default::default() }, &relays)
4124            .await
4125            .unwrap();
4126        assert!(for_bob.is_empty());
4127    }
4128
4129    // ── UnionPlan: the evidence tiers' return-timing math ────────────────────
4130
4131    #[test]
4132    fn union_plan_fast_satisfied_on_first_success() {
4133        let mut p = UnionPlan::new(Evidence::Fast, 4);
4134        p.record(false);
4135        assert!(!p.satisfied(), "a failure is not evidence");
4136        p.record(true);
4137        assert!(p.satisfied(), "one genuine EOSE satisfies Fast");
4138        assert!(!p.exhausted());
4139    }
4140
4141    #[test]
4142    fn union_plan_quorum_majority_math() {
4143        // (attempted, successes needed): majority = attempted/2 + 1
4144        for (n, need) in [(2usize, 2usize), (3, 2), (4, 3), (5, 3)] {
4145            let mut p = UnionPlan::new(Evidence::Quorum, n);
4146            for _ in 0..need - 1 {
4147                p.record(true);
4148            }
4149            assert!(!p.satisfied(), "{}/{} must not satisfy quorum", need - 1, n);
4150            p.record(true);
4151            assert!(p.satisfied(), "{}/{} satisfies quorum", need, n);
4152        }
4153    }
4154
4155    #[test]
4156    fn union_plan_quorum_failures_never_substitute_for_successes() {
4157        let mut p = UnionPlan::new(Evidence::Quorum, 3);
4158        p.record(true);
4159        p.record(false);
4160        p.record(false);
4161        assert!(!p.satisfied(), "1 success + 2 failures is not a majority");
4162        assert!(p.exhausted(), "all resolved — the degraded path returns best-effort");
4163        assert_eq!(p.successes(), 1);
4164    }
4165
4166    #[test]
4167    fn union_plan_full_requires_every_relay_resolved() {
4168        let mut p = UnionPlan::new(Evidence::Full, 3);
4169        p.record(true);
4170        p.record(true);
4171        assert!(!p.satisfied(), "Full waits for the last relay even after 2 EOSEs");
4172        p.record(false);
4173        assert!(p.satisfied(), "a timeout is a resolution — Full is done");
4174        assert!(p.exhausted());
4175    }
4176
4177    #[test]
4178    fn union_plan_all_dead_is_reportable_not_a_confident_empty() {
4179        let mut p = UnionPlan::new(Evidence::Quorum, 2);
4180        p.record(false);
4181        p.record(false);
4182        assert!(p.exhausted());
4183        assert_eq!(p.successes(), 0, "the caller must map this to Err, never Ok(vec![])");
4184    }
4185
4186    // ── Circuit breaker: trip/reset rules ────────────────────────────────────
4187    // Pinned generation + unique urls per test: the breaker is one global map,
4188    // and other tests bump the REAL session generation concurrently (which
4189    // would wipe it mid-assertion via the production accessors).
4190
4191    const BREAKER_TEST_GEN: u64 = u64::MAX;
4192
4193    #[test]
4194    fn breaker_trips_only_after_consecutive_full_budget_failures() {
4195        let url = "wss://breaker-test-full-budget.example";
4196        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4197        assert!(!breaker_tripped_at(BREAKER_TEST_GEN, url), "one failure is below the threshold");
4198        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4199        assert!(breaker_tripped_at(BREAKER_TEST_GEN, url), "two consecutive full-budget failures trip");
4200    }
4201
4202    #[test]
4203    fn breaker_demoted_budget_failures_never_count() {
4204        let url = "wss://breaker-test-demoted.example";
4205        breaker_record_at(BREAKER_TEST_GEN, url, false, false);
4206        breaker_record_at(BREAKER_TEST_GEN, url, false, false);
4207        breaker_record_at(BREAKER_TEST_GEN, url, false, false);
4208        assert!(
4209            !breaker_tripped_at(BREAKER_TEST_GEN, url),
4210            "demoted-budget failures must not trip (anti-starvation: the post-cooldown probe must stay reachable)"
4211        );
4212    }
4213
4214    #[test]
4215    fn breaker_success_resets_the_entry() {
4216        let url = "wss://breaker-test-reset.example";
4217        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4218        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4219        assert!(breaker_tripped_at(BREAKER_TEST_GEN, url));
4220        // A late EOSE (e.g. via the background drain) proves slow ≠ dead.
4221        breaker_record_at(BREAKER_TEST_GEN, url, true, false);
4222        assert!(!breaker_tripped_at(BREAKER_TEST_GEN, url), "any success unconditionally resets");
4223        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4224        assert!(!breaker_tripped_at(BREAKER_TEST_GEN, url), "and the failure count restarted from zero");
4225    }
4226
4227    // ── The evidence floor ───────────────────────────────────────────────────
4228
4229    #[test]
4230    fn declared_evidence_stands_and_default_is_quorum() {
4231        assert_eq!(Query::default().evidence, Evidence::Quorum, "unclassified sites get Quorum");
4232        assert_eq!(
4233            effective_evidence(&Query { until: Some(1), evidence: Evidence::Fast, ..Default::default() }),
4234            Evidence::Fast,
4235            "chat pagination rides its declared tier — absence verdicts request Full themselves"
4236        );
4237        assert_eq!(
4238            effective_evidence(&Query { evidence: Evidence::Fast, ..Default::default() }),
4239            Evidence::Fast,
4240            "without `until` the declared tier stands"
4241        );
4242    }
4243}