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