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            // Cold: a dedicated connection authed AS the plane key (a NIP-42
1611            // connection holds ONE identity; the shared client's is the user's).
1612            // Authenticates as the PLANE key, not the user — hence its own
1613            // authenticator rather than `nostr_client_builder()`, which resolves the
1614            // session identity.
1615            let auth = nostr_sdk::prelude::SignerAuthenticator::new(plane.clone());
1616            #[cfg(test)]
1617            let auth = tests::SlowAuth(auth);
1618            let client = crate::apply_transport(
1619                nostr_sdk::prelude::Client::builder()
1620                    .authenticator(auth)
1621                    // Nothing reads a plane client's pool notifications; the default
1622                    // channel allocates 4096 of them up front.
1623                    .notification_channel_size(std::num::NonZeroUsize::MIN),
1624                crate::transport::Lane::Shared,
1625            )
1626            .build();
1627            // Community relay options (GOSSIP|PING + Tor-aware ConnectionMode): a
1628            // bare add_relay leaves ConnectionMode::Direct, so under active Tor the
1629            // plane fetch — and the NIP-42 auth AS the plane key — would connect
1630            // direct and tie the user's IP to community membership.
1631            for r in targets {
1632                let _ = client.add_managed_relay(r.clone()).capabilities(crate::community_relay_capabilities()).await;
1633            }
1634            let mut frames = Vec::with_capacity(targets.len());
1635            for r in targets {
1636                if let Ok(Some(relay)) = client.relay(r).await {
1637                    frames.push(relay.notifications());
1638                }
1639            }
1640            client.connect().await;
1641            // Warmup with the gated filter shape triggers each relay's NIP-42
1642            // challenge so auto-auth completes ONCE here; pooled reuses skip it.
1643            for r in targets {
1644                let _ = client
1645                    .fetch_events(nostr_sdk::prelude::ReqTarget::single(r.clone(), [filter.clone()]))
1646                    // Tor-aware: this warmup carries a NIP-42 challenge round trip, so a
1647                    // clearnet 5s budget expires mid-auth and every relay ends up
1648                    // unauthenticated — which surfaces as `0/N attempted` below.
1649                    .timeout(crate::relay_request_timeout(std::time::Duration::from_secs(5)))
1650                    .await;
1651            }
1652            // The warmup ends at its EOSE while nostr-sdk answers the challenge on a task of its
1653            // own, and a relay may answer a REQ that reaches it before the AUTH with nothing.
1654            let budget = crate::relay_request_timeout(std::time::Duration::from_secs(5));
1655            futures_util::future::join_all(frames.into_iter().map(|f| authenticated(f, budget))).await;
1656            let ev = PLANE_POOL.insert(generation, key, client.clone());
1657            disconnect_clients(ev);
1658            client
1659        }
1660    }
1661
1662    async fn read_authed_plane(&self, plane: &Keys, filter: &Filter, targets: Vec<String>, generation: u64, floor: &mut Option<PageFloor>) -> (Vec<Event>, usize, usize) {
1663        let client = self.plane_client(plane, filter, &targets, generation).await;
1664
1665        // This walk is SERIAL, so a dead socket taxes every page its full budget;
1666        // judged against the PLANE pool's statuses (a separate client — nothing
1667        // revives its members, so an unrevivable one here is dead for good). No
1668        // all-dead fallback: the open relays may have answered, and with none
1669        // reached at all the fetch errs anyway.
1670        let targets = reachable_targets(&client, targets).await;
1671
1672        let mut result: Vec<Event> = Vec::new();
1673        let mut seen: std::collections::HashSet<EventId> = std::collections::HashSet::new();
1674        let mut successes = 0usize;
1675        // CONCURRENTLY. Serially, one dead relay cost its entire timeout before the
1676        // next was even tried, and the whole plane read paid that on every page of
1677        // every epoch of a catch-up. The union is order-independent, so there is
1678        // nothing to serialize for.
1679        {
1680            use futures_util::stream::{FuturesUnordered, StreamExt};
1681            let mut inflight: FuturesUnordered<_> = targets
1682                .iter()
1683                .map(|r| {
1684                    let client = client.clone();
1685                    let filter = filter.clone();
1686                    let timeout = self.timeout;
1687                    async move { (r.clone(), fetch_relay_eose(&client, r, filter, timeout).await) }
1688                })
1689                .collect();
1690            while let Some((r, res)) = inflight.next().await {
1691                // Feed the shared breaker so this auth path both benefits from AND
1692                // contributes to the pool-wide dead-relay knowledge.
1693                breaker_record(&r, res.is_ok(), true);
1694                if let Ok(events) = res {
1695                    successes += 1;
1696                    if let Some(floor) = floor.as_mut() {
1697                        floor.note(&events);
1698                    }
1699                    for e in events {
1700                        if seen.insert(e.id) {
1701                            result.push(e);
1702                        }
1703                    }
1704                }
1705            }
1706        }
1707        // The client stays POOLED (not disconnected) for the next page/epoch/community.
1708        let asked = targets.len();
1709        (result, successes, asked)
1710    }
1711
1712    /// Coverage-reporting fetch — same engine as [`Transport::fetch`], returning
1713    /// `(events, relays_that_EOSEd, relays_attempted)`. The boot control probe
1714    /// reads the counts to decide whether its cursor may advance (full coverage
1715    /// only — a majority return must not skip a down relay's pending editions).
1716    pub async fn fetch_counted(&self, query: &Query, relays: &[String]) -> Result<(Vec<Event>, usize, usize), String> {
1717        let client = Self::warm_client(relays, self.timeout).await?;
1718        let base_timeout = self.timeout;
1719        let filter = query.to_filter();
1720
1721        let evidence = effective_evidence(query);
1722
1723        let mut targets: Vec<String> = Vec::new();
1724        for r in relays {
1725            if !targets.contains(r) {
1726                targets.push(r.clone());
1727            }
1728        }
1729        let mut targets = drop_refused(targets)?;
1730        // Even a Full drain skips a DEAD socket: with pool auto-reconnect off, a
1731        // Terminated relay cannot answer this call no matter how long we wait, so
1732        // its timeout buys byte-identical evidence to skipping it — and paid per
1733        // PAGE, it is what stretched one dead relay into a minute-long rotation.
1734        targets = drop_unrevivable_targets(&client, targets).await;
1735
1736        // Fast tier: skip tripped relays outright (pure bandwidth save — the
1737        // evidence bar is ≥1 success either way, and the union self-heals).
1738        // Never skip down to an empty set. Quorum/Full always attempt every
1739        // relay so a trip can't shrink their evidence denominator.
1740        if evidence == Evidence::Fast && targets.len() >= 2 {
1741            let alive: Vec<String> =
1742                targets.iter().filter(|r| !breaker_tripped(r)).cloned().collect();
1743            if !alive.is_empty() {
1744                targets = alive;
1745            }
1746        }
1747
1748        // One relay → nothing to race; the sole relay always gets the full
1749        // budget (there is nothing to union around).
1750        if targets.len() <= 1 {
1751            let Some(url) = targets.first() else {
1752                return Err("no valid relay to fetch from".to_string());
1753            };
1754            let res = fetch_relay_eose(&client, url, filter, base_timeout)
1755                .await
1756                .map_err(|_| format!("relay did not answer the fetch: {url}"));
1757            breaker_record(url, res.is_ok(), true);
1758            return res.map(|evs| (evs, 1, 1));
1759        }
1760
1761        /// One relay's answer into the union.
1762        fn merge_events(
1763            evs: Vec<Event>,
1764            result: &mut Vec<Event>,
1765            seen: &mut std::collections::HashSet<EventId>,
1766            floor: &mut Option<PageFloor>,
1767        ) {
1768            if let Some(floor) = floor {
1769                floor.note(&evs);
1770            }
1771            for e in evs {
1772                if seen.insert(e.id) {
1773                    result.push(e);
1774                }
1775            }
1776        }
1777
1778        // RACE per-relay (mirrors the publish first-ACK race) and union per the
1779        // evidence tier. Every relay's outcome is tracked — genuine EOSE vs
1780        // error/timeout — so an all-dead pool surfaces as Err, never as a
1781        // confident empty answer. Tripped relays keep their place in the
1782        // denominator; on Full drains (non-Tor) they run on a demoted budget so
1783        // a dead relay's tail shrinks without weakening the union.
1784        let demote = evidence == Evidence::Full && demotion_allowed();
1785        use futures_util::stream::{FuturesUnordered, StreamExt};
1786        let mut fetches: FuturesUnordered<_> = targets
1787            .iter()
1788            .map(|r| {
1789                let client = client.clone();
1790                let filter = filter.clone();
1791                let r = r.clone();
1792                let timeout = if demote && breaker_tripped(&r) {
1793                    TRIPPED_TIMEOUT.min(base_timeout)
1794                } else {
1795                    base_timeout
1796                };
1797                let full_budget = timeout >= base_timeout;
1798                // spawn-detached: relay I/O only — no account storage is touched.
1799                crate::rt::spawn(async move {
1800                    let out = fetch_relay_eose(&client, &r, filter, timeout).await;
1801                    (r, full_budget, out)
1802                })
1803            })
1804            .collect();
1805
1806        let mut plan = UnionPlan::new(evidence, targets.len());
1807        let mut result: Vec<Event> = Vec::new();
1808        let mut union_ids: std::collections::HashSet<EventId> = std::collections::HashSet::new();
1809        let mut floor = PageFloor::of(query);
1810
1811        // Phase 1 — wait for the tier's coverage requirement. Quorum's majority
1812        // wait is TIME-BOUNDED from the first success so a dead relay can't
1813        // gate a degraded set (a 2-relay community with one relay down must not
1814        // ride that relay's timeout on every fetch).
1815        let mut quorum_deadline: Option<crate::rt::time::Instant> = None;
1816        let mut quorum_window_closed = false;
1817        while !plan.satisfied() && !plan.exhausted() {
1818            let next = match quorum_deadline {
1819                Some(deadline) => match crate::rt::time::timeout_at(deadline, fetches.next()).await {
1820                    Ok(n) => n,
1821                    Err(_) => {
1822                        quorum_window_closed = true;
1823                        break; // window closed — return with what we hold (≥1 success)
1824                    }
1825                },
1826                None => fetches.next().await,
1827            };
1828            let Some(joined) = next else { break };
1829            match joined {
1830                Ok((url, full_budget, Ok(evs))) => {
1831                    breaker_record(&url, true, full_budget);
1832                    merge_events(evs, &mut result, &mut union_ids, &mut floor);
1833                    plan.record(true);
1834                    if evidence == Evidence::Quorum && quorum_deadline.is_none() {
1835                        quorum_deadline = Some(
1836                            crate::rt::time::Instant::now()
1837                                + std::time::Duration::from_millis(QUORUM_GRACE_MS),
1838                        );
1839                    }
1840                }
1841                Ok((url, full_budget, Err(()))) => {
1842                    breaker_record(&url, false, full_budget);
1843                    plan.record(false);
1844                }
1845                Err(_) => plan.record(false), // task join error — a resolved failure
1846            }
1847        }
1848
1849        if plan.successes() == 0 {
1850            return Err(format!(
1851                "no relay answered the fetch (0/{} attempted)",
1852                plan.attempted()
1853            ));
1854        }
1855
1856        // Phase 2 — residual union window: relays finishing just behind the
1857        // requirement still merge synchronously. Skipped when the quorum window
1858        // already expired (that wait subsumes this one).
1859        if !fetches.is_empty() && !quorum_window_closed {
1860            let grace = crate::rt::time::sleep(std::time::Duration::from_millis(RESIDUAL_GRACE_MS));
1861            tokio::pin!(grace);
1862            loop {
1863                tokio::select! {
1864                    _ = &mut grace => break,
1865                    next = fetches.next() => match next {
1866                        Some(Ok((url, full_budget, Ok(evs)))) => {
1867                            breaker_record(&url, true, full_budget);
1868                            merge_events(evs, &mut result, &mut union_ids, &mut floor);
1869                        }
1870                        Some(Ok((url, full_budget, Err(())))) => {
1871                            breaker_record(&url, false, full_budget);
1872                        }
1873                        Some(Err(_)) => continue,
1874                        None => break,
1875                    }
1876                }
1877            }
1878        }
1879
1880        if let Some(floor) = &floor {
1881            floor.cut(&mut result);
1882        }
1883
1884        // Background-merge the relays that haven't finished: dedup by event id ONLY (identical bytes)
1885        // against what we returned, then hand the rest to the ingester. Conflicting editions carry
1886        // distinct ids, so the protocol's convergence engine resolves them — not the transport.
1887        if !fetches.is_empty() {
1888            let seen: std::collections::HashSet<EventId> = result.iter().map(|e| e.id).collect();
1889            // Captured BEFORE the drain spawn: the drain can outlive an account swap, and
1890            // stragglers fetched under the prior session must not feed the new one's ingest.
1891            crate::db::spawn_bound(async move {
1892                let mut extra: Vec<Event> = Vec::new();
1893                let mut extra_ids: std::collections::HashSet<EventId> = std::collections::HashSet::new();
1894                while let Some(joined) = fetches.next().await {
1895                    if let Ok((url, full_budget, out)) = joined {
1896                        // A late EOSE is still a SUCCESS — slow ≠ dead; without
1897                        // this a relay slower than the residual window could
1898                        // never un-trip.
1899                        breaker_record(&url, out.is_ok(), full_budget);
1900                        if let Ok(evs) = out {
1901                            for e in evs {
1902                                if !seen.contains(&e.id) && extra_ids.insert(e.id) {
1903                                    extra.push(e);
1904                                }
1905                            }
1906                        }
1907                    }
1908                }
1909                submit_stragglers(extra);
1910            });
1911        }
1912
1913        Ok((result, plan.successes(), plan.attempted()))
1914    }
1915}
1916
1917/// Send to one pooled relay, true on its ACK. Callers verify the event and mark it as ours
1918/// once; `Client::send_event` would redo both for every relay, every round.
1919async fn send_to_relay(client: &Client, event: &Event, url: &str) -> bool {
1920    send_to_relay_why(client, event, url).await.is_ok()
1921}
1922
1923/// [`send_to_relay`], with the relay's own reason when it refuses.
1924async fn send_to_relay_why(client: &Client, event: &Event, url: &str) -> Result<(), String> {
1925    let Ok(Some(relay)) = client.relay(url).await else { return Err("not connected".to_string()) };
1926    let wait = crate::relay_request_timeout(std::time::Duration::from_secs(10));
1927    relay.send_event(event).ok_timeout(wait).authentication_timeout(wait).await.map(|_| ()).map_err(|e| e.to_string())
1928}
1929
1930/// Mark our own event as seen before it goes out, so the relays' echoes of it are dropped
1931/// before any work. The mark only silences echoes; it never stands for delivery, which is
1932/// each relay's OK. Returns whether the mark is ours: an id seen before stays seen.
1933pub(crate) async fn mark_own(client: &Client, event: &Event) -> bool {
1934    let fresh = matches!(
1935        client.database().check_id(&event.id).await,
1936        Ok(nostr_sdk::prelude::DatabaseEventStatus::NotExistent)
1937    );
1938    let _ = client.database().save_event(event).await;
1939    fresh
1940}
1941
1942/// Undo a mark [`mark_own`] made once no relay took the event, so a copy that turns up later
1943/// is handled like anyone else's.
1944pub(crate) async fn unmark_own(client: &Client, event: &Event) {
1945    let _ = client.database().delete(nostr_sdk::prelude::Filter::new().id(event.id)).await;
1946}
1947
1948#[async_trait::async_trait]
1949impl Transport for LiveTransport {
1950    async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
1951        event.verify().map_err(|e| e.to_string())?;
1952        crate::event_size::check(event)?;
1953        let client = Self::warm_client(relays, self.timeout).await?;
1954        let timeout = self.timeout;
1955        let mut targets: Vec<String> = Vec::new();
1956        for r in relays { if !targets.contains(r) { targets.push(r.clone()); } }
1957        targets = drop_refused(targets)?;
1958        // A dead socket can't ACK and won't be revived mid-send — don't spawn at it.
1959        targets = drop_unrevivable_targets(&client, targets).await;
1960        // Fan out one send per relay and RETURN on the first ACK — never wait for the slowest relay (a
1961        // distant/ratelimited one must not gate a reaction/edit/message). Each send is SPAWNED, so the rest
1962        // keep delivering to every relay after we return (dropping a JoinHandle detaches, it doesn't abort).
1963        // Single attempt — durable retry is publish_durable's job.
1964        use futures_util::stream::{FuturesUnordered, StreamExt};
1965        let marked = mark_own(&client, event).await;
1966        let mut sends: FuturesUnordered<_> = targets
1967            .into_iter()
1968            .map(|r| {
1969                let client = client.clone();
1970                let event = event.clone();
1971                // spawn-detached: relay I/O only — no account storage is touched.
1972                crate::rt::spawn(async move {
1973                    match crate::rt::time::timeout(timeout, send_to_relay_why(&client, &event, &r)).await {
1974                        Ok(sent) => sent,
1975                        Err(_) => Err("timed out".to_string()),
1976                    }
1977                })
1978            })
1979            .collect();
1980        let mut why = None;
1981        while let Some(joined) = sends.next().await {
1982            match joined {
1983                Ok(Ok(())) => return Ok(()), // first relay ACKed; the others keep delivering in the background
1984                Ok(Err(e)) => why = Some(e),
1985                Err(_) => {}
1986            }
1987        }
1988        // Every send has finished without an ACK.
1989        if marked {
1990            unmark_own(&client, event).await;
1991        }
1992        Err(match why {
1993            Some(why) => format!("no relay accepted the event: {why}"),
1994            None => "no relay accepted the event".to_string(),
1995        })
1996    }
1997
1998    async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
1999        self.fetch_counted(query, relays).await.map(|(events, _successes, _attempted)| events)
2000    }
2001
2002    async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String> {
2003        if relays.is_empty() {
2004            return Ok(PlaneFetch { events: Vec::new(), answered: 0, attempted: 0 });
2005        }
2006        wait_transport_ready().await?;
2007        // Skip relays the shared breaker already knows are dead — don't even pay
2008        // their connect handshake + warmup + timeout (DM negentropy and other sweeps
2009        // trip them early, so by the time a v2 backfill runs they're usually
2010        // marked). Keep all if that would leave none — a slow fetch beats no fetch.
2011        let relays = drop_refused(relays.to_vec())?;
2012        let selected = plane_targets(relays, breaker_tripped);
2013        let filter = query.to_filter();
2014        let generation = crate::db::current_session_id();
2015        let (gated, open): (Vec<String>, Vec<String>) =
2016            selected.ask.iter().cloned().partition(|r| plane_gate(generation, r) == Some(RelayGate::Auth));
2017
2018        let mut result: Vec<Event> = Vec::new();
2019        let mut seen: std::collections::HashSet<EventId> = std::collections::HashSet::new();
2020        let mut keep = |events: Vec<Event>| result.extend(events.into_iter().filter(|e| seen.insert(e.id)));
2021        let (mut successes, mut asked) = (0usize, 0usize);
2022        let mut floor = PageFloor::of(query);
2023        let open_reads = futures_util::future::join_all(open.iter().map(|r| {
2024            let filter = filter.clone();
2025            async move { (r, read_open_plane(generation, r, filter, self.timeout).await) }
2026        }));
2027        // Relays already known to gate read alongside, not after a slow open relay's dial.
2028        let known_gated = async {
2029            if gated.is_empty() {
2030                (Vec::new(), 0, 0)
2031            } else {
2032                self.read_authed_plane(plane, &filter, gated.clone(), generation, &mut floor).await
2033            }
2034        };
2035        let (reads, (events, answered, reached)) = futures_util::future::join(open_reads, known_gated).await;
2036        successes += answered;
2037        asked += reached;
2038        keep(events);
2039        let mut newly_gated: Vec<String> = Vec::new();
2040        for (r, read) in reads {
2041            match read {
2042                OpenRead::Read(events) => {
2043                    breaker_record(r, true, true);
2044                    successes += 1;
2045                    asked += 1;
2046                    if let Some(floor) = floor.as_mut() {
2047                        floor.note(&events);
2048                    }
2049                    keep(events);
2050                }
2051                OpenRead::Failed => {
2052                    breaker_record(r, false, true);
2053                    asked += 1;
2054                }
2055                OpenRead::Unreachable => {}
2056                OpenRead::Gated => newly_gated.push(r.clone()),
2057            }
2058        }
2059        if !newly_gated.is_empty() {
2060            let (events, answered, reached) = self.read_authed_plane(plane, &filter, newly_gated, generation, &mut floor).await;
2061            successes += answered;
2062            asked += reached;
2063            keep(events);
2064        }
2065        if let Some(floor) = &floor {
2066            floor.cut(&mut result);
2067        }
2068        // Zero EOSE = every relay refused/timed out — an honest transient failure,
2069        // NOT a "the plane is empty" verdict (a genuine empty plane EOSEs with no
2070        // events, which counts as a success). A confident-empty here could mask a
2071        // rotation from a caller that concludes absence.
2072        if successes == 0 {
2073            return Err(format!("no relay answered the plane fetch (0/{} attempted)", selected.ask.len()));
2074        }
2075        Ok(selected.fetched(result, successes, asked))
2076    }
2077
2078    async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2079        // "Durable" = confirm the network has it (≥1 relay ACKs within CONFIRM_WINDOW), then keep bugging the
2080        // SLOW/ratelimited stragglers (Damus-style 1-event/min) in the BACKGROUND. If NOTHING ACKs in the
2081        // window we throw — a dead relay set is a failure, not an endless wait. Uses the shared warm client
2082        // (NEVER shut down here) and targets the community relay set across rounds.
2083        event.verify().map_err(|e| e.to_string())?;
2084        crate::event_size::check(event)?;
2085        let client = Self::warm_client(relays, self.timeout).await?;
2086        let timeout = self.timeout;
2087        let event = event.clone();
2088        let backoff = std::time::Duration::from_millis(750);
2089        let mut pending: Vec<String> = Vec::new();
2090        for r in relays { if !pending.contains(r) { pending.push(r.clone()); } }
2091        if pending.is_empty() {
2092            return Err("no relays to broadcast to".to_string());
2093        }
2094        let mut pending = drop_refused(pending)?;
2095
2096        // Phase 1 — CONFIRM: RACE the relays and return the instant ANY one ACKs — never wait for the
2097        // slowest. `send_event_to(all)` blocks on the slowest relay (a distant/ratelimited one dominates the
2098        // latency), so we fan out one send per relay and take the first winner; the losers are cancelled and
2099        // re-sent in the background. Retry rounds within CONFIRM_WINDOW; zero ACKs in the window = failure.
2100        let mut acked_any = false;
2101        let marked = mark_own(&client, &event).await;
2102        // Over Tor one round alone can take the 30 s request floor: the 60 s connect floor leaves
2103        // room for a retry. Clearnet keeps 30 s.
2104        let confirm_window = crate::relay_connect_timeout(CONFIRM_WINDOW);
2105        let _ = crate::rt::time::timeout(confirm_window, async {
2106            loop {
2107                // Per ROUND, not from `pending`: a dead socket stays pending (the
2108                // reconcile loop may revive it before the stragglers give up) but a
2109                // confirm round must not spend its budget on a relay that cannot ACK.
2110                let round = drop_unrevivable_targets(&client, pending.clone()).await;
2111                let sends = round.iter().cloned().map(|r| {
2112                    let client = &client;
2113                    let event = &event;
2114                    Box::pin(async move {
2115                        match crate::rt::time::timeout(timeout, send_to_relay(client, event, &r)).await {
2116                            Ok(true) => Ok(r),
2117                            _ => Err(()),
2118                        }
2119                    })
2120                });
2121                if let Ok((winner, _losers)) = futures_util::future::select_ok(sends).await {
2122                    acked_any = true;
2123                    pending.retain(|r| r != &winner);
2124                    break;
2125                }
2126                crate::rt::time::sleep(backoff).await;
2127            }
2128        })
2129        .await;
2130
2131        if !acked_any {
2132            if marked {
2133                unmark_own(&client, &event).await;
2134            }
2135            return Err(format!("no relay accepted the event within {}s", confirm_window.as_secs()));
2136        }
2137        if pending.is_empty() {
2138            return Ok(()); // every relay ACKed during the confirm phase
2139        }
2140
2141        // Phase 2 — BACKGROUND: thread the laggards through a durable publisher (retries each up to
2142        // MAX_PUBLISH_ATTEMPTS at a 750ms backoff, so it can't run forever). The caller returns NOW with its
2143        // confirmed ACK; 's fetch-union heals anything that never lands. The client is shared — not torn
2144        // down — so the spawned task just drops its handle when finished.
2145        // spawn-detached: relay I/O only — no account storage is touched.
2146        crate::rt::spawn(async move {
2147            let client_ref = &client;
2148            let event_ref = &event;
2149            let _ = durable_broadcast(&pending, MAX_PUBLISH_ATTEMPTS, backoff, move |round| {
2150                Box::pin(async move {
2151                    match crate::rt::time::timeout(timeout, crate::transport_aware(client_ref.send_event(event_ref)).to(round.clone())).await {
2152                        Ok(Ok(output)) => round.into_iter().filter(|p| RelayUrl::parse(p).map(|u| output.success.contains_key(&u)).unwrap_or(false)).collect(),
2153                        _ => Vec::new(),
2154                    }
2155                })
2156            })
2157            .await;
2158        });
2159        Ok(())
2160    }
2161
2162    fn reconciler(&self) -> Option<&dyn Reconcile> {
2163        Some(self)
2164    }
2165
2166    fn detached(&self) -> Option<std::sync::Arc<dyn Transport + Send + Sync>> {
2167        Some(std::sync::Arc::new(LiveTransport { timeout: self.timeout }))
2168    }
2169}
2170
2171/// How long a relay's "no NIP-77" stands before it is asked again: relays gain it with an upgrade.
2172const PLANE_NEG_TTL_SECS: u64 = 24 * 60 * 60;
2173
2174/// Apart from the DM reads' `neg_cap2:` record: a relay's answer for a plane's `authors` filter
2175/// says nothing of its answer for our own `p` filter, nor the other way.
2176fn plane_neg_setting(url: &str) -> String {
2177    format!("neg_plane2:{}", crate::inbox_relays::normalize_relay_url(url))
2178}
2179
2180/// Whether `url` reconciled a plane when last asked, and when.
2181fn plane_neg(url: &str) -> Option<(bool, u64)> {
2182    let raw = crate::db::get_sql_setting(plane_neg_setting(url)).ok().flatten()?;
2183    let (flag, at) = raw.split_once(':')?;
2184    Some((flag == "1", at.parse().ok()?))
2185}
2186
2187/// What `url` is on record as doing with a plane reconciliation: nothing until it was asked.
2188#[cfg(test)]
2189pub(crate) fn plane_reconciles(url: &str) -> Option<bool> {
2190    plane_neg(url).map(|(reconciles, _)| reconciles)
2191}
2192
2193fn note_plane_neg(url: &str, reconciles: bool) {
2194    // A standing yes is rewritten once a day, not on every pass.
2195    if reconciles && plane_neg(url).is_some_and(|(ok, at)| ok && now_secs().saturating_sub(at) < PLANE_NEG_TTL_SECS) {
2196        return;
2197    }
2198    let _ = crate::db::set_sql_setting(plane_neg_setting(url), format!("{}:{}", u8::from(reconciles), now_secs()));
2199}
2200
2201#[async_trait::async_trait]
2202impl Reconcile for LiveTransport {
2203    async fn reconcile(&self, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail> {
2204        let seen = plane_neg(relay);
2205        if seen.is_some_and(|(ok, at)| !ok && now_secs().saturating_sub(at) < PLANE_NEG_TTL_SECS) {
2206            return Err(ReconcileFail::Unsupported);
2207        }
2208        let client = Self::warm_client(std::slice::from_ref(&relay.to_string()), self.timeout).await.map_err(|_| ReconcileFail::Unreached)?;
2209        let handle = client.relay(relay).await.ok().flatten().ok_or(ReconcileFail::Unreached)?;
2210        if !crate::negentropy::wait_connected(&handle, crate::relay_connect_timeout(std::time::Duration::from_secs(3)).min(self.timeout)).await {
2211            breaker_record(relay, false, true);
2212            return Err(ReconcileFail::Unreached);
2213        }
2214        let first = crate::relay_request_timeout(std::time::Duration::from_secs(5)).min(self.timeout);
2215        let permits = neg_permits(relay);
2216        let _permit = permits.acquire().await;
2217        match super::plane_neg::reconcile(&handle, query.to_filter(), held, budget, first, self.timeout).await {
2218            Ok(diff) => {
2219                breaker_record(relay, true, true);
2220                note_plane_neg(relay, true);
2221                Ok(diff)
2222            }
2223            Err(super::plane_neg::Ended::Fail(fail)) => {
2224                if fail == ReconcileFail::Unsupported {
2225                    note_plane_neg(relay, false);
2226                }
2227                Err(fail)
2228            }
2229            // A relay that has reconciled before is slow, not unable.
2230            Err(super::plane_neg::Ended::Silent) if seen.is_some_and(|(ok, _)| ok) => Err(ReconcileFail::Failed("no answer".to_string())),
2231            // Silence says nothing by itself. A relay that answers a plain read and not this has
2232            // no NIP-77; one that answers neither was not reached.
2233            Err(super::plane_neg::Ended::Silent) => match fetch_relay_eose(&client, relay, query.to_filter().limit(0), first).await {
2234                Ok(_) => {
2235                    note_plane_neg(relay, false);
2236                    Err(ReconcileFail::Unsupported)
2237                }
2238                Err(()) => Err(ReconcileFail::Unreached),
2239            },
2240        }
2241    }
2242
2243    async fn reconcile_plane(&self, plane: &Keys, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail> {
2244        let generation = crate::db::current_session_id();
2245        if plane_gate(generation, relay) != Some(RelayGate::Auth) {
2246            match self.reconcile(query, held, relay, budget).await {
2247                Err(ReconcileFail::Gated) => {}
2248                answered => return answered,
2249            }
2250        }
2251        let filter = query.to_filter();
2252        let client = self.plane_client(plane, &filter, std::slice::from_ref(&relay.to_string()), generation).await;
2253        let handle = client.relay(relay).await.ok().flatten().ok_or(ReconcileFail::Unreached)?;
2254        if !crate::negentropy::wait_connected(&handle, crate::relay_connect_timeout(std::time::Duration::from_secs(3)).min(self.timeout)).await {
2255            return Err(ReconcileFail::Unreached);
2256        }
2257        let first = crate::relay_request_timeout(std::time::Duration::from_secs(5)).min(self.timeout);
2258        let permits = neg_permits(relay);
2259        let _permit = permits.acquire().await;
2260        match super::plane_neg::reconcile(&handle, filter, held, budget, first, self.timeout).await {
2261            Ok(diff) => Ok(diff),
2262            Err(super::plane_neg::Ended::Fail(fail)) => Err(fail),
2263            Err(super::plane_neg::Ended::Silent) => Err(ReconcileFail::Failed("no answer".to_string())),
2264        }
2265    }
2266
2267}
2268
2269#[cfg(any(test, feature = "bench"))]
2270pub(crate) mod memory {
2271    use super::*;
2272    use std::collections::{HashMap, HashSet};
2273    use std::sync::Mutex;
2274
2275    /// An in-memory stand-in for the Community's relay set. Stores events per relay
2276    /// url so tests can model partial propagation (a relay that missed an event) and
2277    /// verify the redundancy/self-heal property: a fetch across the set unions +
2278    /// dedups, so a gap on one relay is covered by its siblings.
2279    pub struct MemoryRelay {
2280        per_relay: Mutex<HashMap<String, Vec<Event>>>,
2281        subscribers: Mutex<Vec<(Query, tokio::sync::mpsc::UnboundedSender<Event>)>>,
2282        /// Relays that judge a wrap's deletion by its `p`-tagged owner, as CORD-01 asks.
2283        owner_rule: Mutex<HashSet<String>>,
2284        /// Relays without NIP-77.
2285        no_reconcile: Mutex<HashSet<String>>,
2286        /// Reconciliations answered, by anyone asking.
2287        reconciled: std::sync::atomic::AtomicU64,
2288    }
2289
2290    /// NIP-01 ephemeral range: relays stream these to live subscriptions but never store
2291    /// them, so a fetch on a real relay can never return one.
2292    fn is_ephemeral(kind: u16) -> bool {
2293        (20000..30000).contains(&kind)
2294    }
2295
2296    impl MemoryRelay {
2297        pub fn new() -> Self {
2298            MemoryRelay {
2299                per_relay: Mutex::new(HashMap::new()),
2300                subscribers: Mutex::new(Vec::new()),
2301                owner_rule: Mutex::new(HashSet::new()),
2302                no_reconcile: Mutex::new(HashSet::new()),
2303                reconciled: Default::default(),
2304            }
2305        }
2306
2307        /// Have `relays` answer a reconciliation as a relay without NIP-77 does.
2308        #[cfg(test)]
2309        pub fn without_reconcile(&self, relays: &[String]) {
2310            self.no_reconcile.lock().unwrap().extend(relays.iter().cloned());
2311        }
2312
2313        /// Reconciliations answered since the last ask.
2314        #[cfg(test)]
2315        pub fn reconciled(&self) -> u64 {
2316            self.reconciled.swap(0, std::sync::atomic::Ordering::Relaxed)
2317        }
2318
2319        /// Have `relays` follow CORD-01 §Deletions: a wrap goes only by its `p`-tagged owner's
2320        /// deletion, never its author's.
2321        #[cfg(test)]
2322        pub fn follow_cord01(&self, relays: &[String]) {
2323            self.owner_rule.lock().unwrap().extend(relays.iter().cloned());
2324        }
2325
2326        /// Total stored events across every relay url — lets a test assert that a
2327        /// code path published NOTHING, which an absence-of-effect check can't
2328        /// express by fetching (an empty result also means "never published").
2329        #[cfg(test)]
2330        pub fn stored_count(&self) -> usize {
2331            self.per_relay.lock().unwrap().values().map(|v| v.len()).sum()
2332        }
2333
2334        /// Open a live subscription: every subsequent publish/inject matching `query` is
2335        /// delivered — ephemerals included, which stream but are never stored.
2336        #[cfg(test)]
2337        pub fn subscribe(&self, query: Query) -> tokio::sync::mpsc::UnboundedReceiver<Event> {
2338            let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
2339            self.subscribers.lock().unwrap().push((query, tx));
2340            rx
2341        }
2342
2343        /// Push `event` to every live matching subscriber, pruning closed ones.
2344        fn deliver(&self, event: &Event) {
2345            self.subscribers.lock().unwrap().retain(|(q, tx)| {
2346                if q.matches(event) {
2347                    tx.send(event.clone()).is_ok()
2348                } else {
2349                    !tx.is_closed()
2350                }
2351            });
2352        }
2353
2354        /// Publish to ONLY a subset of relays — used to simulate a relay missing an
2355        /// event (e.g. a dropped rekey) for redundancy tests.
2356        pub fn inject(&self, event: &Event, relays: &[String]) {
2357            self.deliver(event);
2358            if is_ephemeral(event.kind.as_u16()) {
2359                return; // live-delivered above, never stored
2360            }
2361            // Replaceable kinds: parameterized (30000-39999, keyed by (kind, pubkey, d-tag)) AND
2362            // standard (10000-19999, plus 0/3, keyed by (kind, pubkey) — the d-tag is "") — a relay keeps
2363            // only the latest at that coordinate, so a new event REPLACES the old (NIP-01). This is what
2364            // makes a revocation tombstone overwrite a bundle, and a fresh Community List supersede the last one,
2365            // even on relays that ignore deletions — model it so tests match real relay behavior.
2366            let d_tag = |e: &Event| e.tags.iter().find_map(|t| {
2367                let s = t.as_slice();
2368                (s.len() >= 2 && s[0] == "d").then(|| s[1].clone())
2369            }).unwrap_or_default();
2370            let k = event.kind.as_u16();
2371            let replaceable = (30000..40000).contains(&k) || (10000..20000).contains(&k) || k == 0 || k == 3;
2372            let coord = (event.kind.as_u16(), event.pubkey, d_tag(event));
2373            let mut map = self.per_relay.lock().unwrap();
2374            for r in relays {
2375                let v = map.entry(r.clone()).or_default();
2376                if replaceable {
2377                    v.retain(|e| (e.kind.as_u16(), e.pubkey, d_tag(e)) != coord);
2378                }
2379                v.push(event.clone());
2380            }
2381        }
2382
2383        /// How many events a given relay holds (test introspection).
2384        #[cfg(test)]
2385        pub fn count_on(&self, relay: &str) -> usize {
2386            self.per_relay.lock().unwrap().get(relay).map_or(0, |v| v.len())
2387        }
2388
2389        /// Apply a NIP-09 deletion: drop any stored event matched by the deletion's `e`
2390        /// tags (by id) OR `a` tags (addressable coordinate `kind:pubkey:d`), AND whose
2391        /// author matches the deletion's author (a deleter can only delete their own
2392        /// events — same rule strfry enforces). A relay following CORD-01 takes a wrap's
2393        /// `p`-tagged owner in place of its author.
2394        fn apply_deletion(&self, deletion: &Event, relays: &[String]) {
2395            let owner_rule = self.owner_rule.lock().unwrap().clone();
2396            let mut id_targets: HashSet<String> = HashSet::new();
2397            let mut coord_targets: HashSet<String> = HashSet::new();
2398            for t in deletion.tags.iter() {
2399                let s = t.as_slice();
2400                if s.len() >= 2 && s[0] == "e" {
2401                    id_targets.insert(s[1].clone());
2402                } else if s.len() >= 2 && s[0] == "a" {
2403                    coord_targets.insert(s[1].clone());
2404                }
2405            }
2406            let mut map = self.per_relay.lock().unwrap();
2407            for r in relays {
2408                let by_owner = owner_rule.contains(r);
2409                if let Some(events) = map.get_mut(r) {
2410                    events.retain(|e| {
2411                        let deleter = if by_owner && e.kind.as_u16() == 1059 {
2412                            crate::community::v2::stream::wrap_owner(e)
2413                        } else {
2414                            Some(e.pubkey)
2415                        };
2416                        if deleter != Some(deletion.pubkey) {
2417                            return true;
2418                        }
2419                        if id_targets.contains(&e.id.to_hex()) {
2420                            return false;
2421                        }
2422                        // Addressable coordinate "kind:pubkey:d-identifier".
2423                        let d = e.tags.iter().find_map(|t| {
2424                            let s = t.as_slice();
2425                            (s.len() >= 2 && s[0] == "d").then(|| s[1].clone())
2426                        }).unwrap_or_default();
2427                        let coord = format!("{}:{}:{}", e.kind.as_u16(), e.pubkey.to_hex(), d);
2428                        !coord_targets.contains(&coord)
2429                    });
2430                }
2431            }
2432        }
2433    }
2434
2435    #[async_trait::async_trait]
2436    impl Transport for MemoryRelay {
2437        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2438            // Refuse what a real relay would, so every test publish is a size test too.
2439            crate::event_size::check(event)?;
2440            // Honor NIP-09 so the delete→gone cycle is testable offline.
2441            if event.kind == Kind::EventDeletion {
2442                self.apply_deletion(event, relays);
2443                self.deliver(event);
2444            } else {
2445                self.inject(event, relays);
2446            }
2447            Ok(())
2448        }
2449
2450        // The in-memory relay always accepts, so a "durable" publish is just a publish (the retry
2451        // engine itself is unit-tested separately via `durable_broadcast`).
2452        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2453            self.publish(event, relays).await
2454        }
2455
2456        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
2457            let map = self.per_relay.lock().unwrap();
2458            let newest_first = |a: &&Event, b: &&Event| b.created_at.cmp(&a.created_at).then_with(|| b.id.cmp(&a.id));
2459            let mut seen = HashSet::new();
2460            let mut out = Vec::new();
2461            let mut floor = PageFloor::of(query);
2462            for r in relays {
2463                let Some(events) = map.get(r) else { continue };
2464                // Never stored, but guard the read path too: a real relay never
2465                // serves an ephemeral from a fetch, whatever got in.
2466                let mut page: Vec<&Event> = events.iter().filter(|ev| !is_ephemeral(ev.kind.as_u16()) && query.matches(ev)).collect();
2467                // The page cap is each relay's own, newest first: the union of several runs past it.
2468                if let Some(limit) = query.limit {
2469                    page.sort_by(newest_first);
2470                    page.truncate(limit);
2471                }
2472                let page: Vec<Event> = page.into_iter().cloned().collect();
2473                if let Some(floor) = floor.as_mut() {
2474                    floor.note(&page);
2475                }
2476                out.extend(page.into_iter().filter(|e| seen.insert(e.id)));
2477            }
2478            if let Some(floor) = &floor {
2479                floor.cut(&mut out);
2480            }
2481            if query.limit.is_some() {
2482                out.sort_by(|a, b| newest_first(&a, &b));
2483            }
2484            Ok(out)
2485        }
2486
2487        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String> {
2488            // No auth in the in-memory relay — a plane fetch is just a fetch.
2489            Ok(PlaneFetch::whole(self.fetch(query, relays).await?))
2490        }
2491
2492        fn reconciler(&self) -> Option<&dyn Reconcile> {
2493            Some(self)
2494        }
2495    }
2496
2497    #[async_trait::async_trait]
2498    impl Reconcile for MemoryRelay {
2499        async fn reconcile(&self, query: &Query, held: &[(EventId, u64)], relay: &str, budget: usize) -> Result<Diff, ReconcileFail> {
2500            if self.no_reconcile.lock().unwrap().contains(relay) {
2501                return Err(ReconcileFail::Unsupported);
2502            }
2503            self.reconciled.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2504            let map = self.per_relay.lock().unwrap();
2505            let theirs: HashSet<EventId> =
2506                map.get(relay).into_iter().flatten().filter(|e| !is_ephemeral(e.kind.as_u16()) && query.matches(e)).map(|e| e.id).collect();
2507            let ours: HashSet<EventId> = held.iter().map(|(id, _)| *id).collect();
2508            let mut need: Vec<EventId> = theirs.difference(&ours).copied().collect();
2509            need.sort_unstable();
2510            let complete = need.len() <= budget;
2511            need.truncate(budget);
2512            let mut lack: Vec<EventId> = ours.difference(&theirs).copied().collect();
2513            lack.sort_unstable();
2514            Ok(Diff { need, lack, complete })
2515        }
2516    }
2517}
2518
2519/// A relay on a real loopback socket, for what only a socket shows: how many connections a
2520/// client opens, and how it answers a NIP-42 gate.
2521#[cfg(test)]
2522pub(crate) mod wire {
2523    use futures_util::{SinkExt, StreamExt};
2524    use nostr_sdk::prelude::*;
2525    use std::collections::HashSet;
2526    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
2527    use std::sync::{Arc, Mutex};
2528    use tokio_tungstenite::tungstenite::Message as Ws;
2529
2530    /// Answers REQs from what it holds. Gated, it serves a REQ only to a connection authed as
2531    /// every author it names, as Ditto does: otherwise one AUTH challenge per connection and a
2532    /// CLOSED "auth-required:", or with `quiet` an EOSE with nothing. Greeting, it challenges on
2533    /// connect and serves reads anyway. Refusing, it CLOSEs every REQ with an error.
2534    pub struct WireRelay {
2535        pub port: u16,
2536        opened: Arc<AtomicUsize>,
2537        modes: Arc<Modes>,
2538        held: Arc<Mutex<Vec<Event>>>,
2539    }
2540
2541    #[derive(Default)]
2542    struct Modes {
2543        gated: AtomicBool,
2544        quiet: AtomicBool,
2545        greets: AtomicBool,
2546        refuses: AtomicBool,
2547        /// Milliseconds a new connection waits before its WebSocket handshake.
2548        stall_ms: std::sync::atomic::AtomicU64,
2549        /// Subscriptions one connection may hold open; 0 for no limit.
2550        sub_cap: AtomicUsize,
2551        /// Close the connection on the first REQ, unanswered.
2552        hangs_up: AtomicBool,
2553        /// Gate without ever sending a challenge.
2554        mute: AtomicBool,
2555        /// Challenge once a connection has been served a read.
2556        challenges_after: AtomicBool,
2557        /// How a NEG-OPEN is met: 0 reconciled, 1 a notice as from a relay without NIP-77, 2 silence.
2558        neg: std::sync::atomic::AtomicU8,
2559        /// NEG-OPENs received.
2560        neg_opens: AtomicUsize,
2561        /// NIP-77 sessions one connection may hold open, as Magnitude caps them. 0 for none.
2562        neg_cap: AtomicUsize,
2563    }
2564
2565    impl WireRelay {
2566        pub async fn start() -> Self {
2567            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2568            let port = listener.local_addr().unwrap().port();
2569            let relay = WireRelay { port, opened: Arc::default(), modes: Arc::default(), held: Arc::default() };
2570            let (opened, modes, held) = (relay.opened.clone(), relay.modes.clone(), relay.held.clone());
2571            let url = RelayUrl::parse(&relay.url()).unwrap();
2572            tokio::spawn(async move {
2573                while let Ok((tcp, _)) = listener.accept().await {
2574                    opened.fetch_add(1, Ordering::SeqCst);
2575                    tokio::spawn(serve(tcp, url.clone(), modes.clone(), held.clone()));
2576                }
2577            });
2578            relay
2579        }
2580
2581        pub fn url(&self) -> String {
2582            format!("ws://127.0.0.1:{}", self.port)
2583        }
2584
2585        /// Connections accepted so far.
2586        pub fn opened(&self) -> usize {
2587            self.opened.load(Ordering::SeqCst)
2588        }
2589
2590        pub fn gate(&self, on: bool) {
2591            self.modes.gated.store(on, Ordering::SeqCst);
2592        }
2593
2594        pub fn quiet(&self, on: bool) {
2595            self.modes.quiet.store(on, Ordering::SeqCst);
2596        }
2597
2598        pub fn greet(&self, on: bool) {
2599            self.modes.greets.store(on, Ordering::SeqCst);
2600        }
2601
2602        pub fn refuse(&self, on: bool) {
2603            self.modes.refuses.store(on, Ordering::SeqCst);
2604        }
2605
2606        pub fn stall(&self, by: std::time::Duration) {
2607            self.modes.stall_ms.store(by.as_millis() as u64, Ordering::SeqCst);
2608        }
2609
2610        pub fn cap_subs(&self, n: usize) {
2611            self.modes.sub_cap.store(n, Ordering::SeqCst);
2612        }
2613
2614        pub fn hang_up(&self, on: bool) {
2615            self.modes.hangs_up.store(on, Ordering::SeqCst);
2616        }
2617
2618        pub fn mute(&self, on: bool) {
2619            self.modes.mute.store(on, Ordering::SeqCst);
2620        }
2621
2622        pub fn challenge_after_a_read(&self, on: bool) {
2623            self.modes.challenges_after.store(on, Ordering::SeqCst);
2624        }
2625
2626        pub fn hold(&self, events: impl IntoIterator<Item = Event>) {
2627            self.held.lock().unwrap().extend(events);
2628        }
2629
2630        /// Meet a NEG-OPEN as a relay without NIP-77 does: with a notice, or with `silent` nothing.
2631        pub fn no_nip77(&self, silent: bool) {
2632            self.modes.neg.store(if silent { 2 } else { 1 }, Ordering::SeqCst);
2633        }
2634
2635        /// Reconcile again.
2636        pub fn nip77(&self) {
2637            self.modes.neg.store(0, Ordering::SeqCst);
2638        }
2639
2640        /// NEG-OPENs received so far.
2641        pub fn neg_opens(&self) -> usize {
2642            self.modes.neg_opens.load(Ordering::SeqCst)
2643        }
2644
2645        /// Refuse a NIP-77 session past `cap` open on one connection, as Magnitude does.
2646        pub fn cap_neg_sessions(&self, cap: usize) {
2647            self.modes.neg_cap.store(cap, Ordering::SeqCst);
2648        }
2649    }
2650
2651    async fn serve(tcp: tokio::net::TcpStream, url: RelayUrl, modes: Arc<Modes>, held: Arc<Mutex<Vec<Event>>>) {
2652        tokio::time::sleep(std::time::Duration::from_millis(modes.stall_ms.load(Ordering::SeqCst))).await;
2653        let greet = modes.greets.load(Ordering::SeqCst);
2654        let Ok(ws) = tokio_tungstenite::accept_async(tcp).await else { return };
2655        let (mut sink, mut stream) = ws.split();
2656        static CONNECTION: AtomicUsize = AtomicUsize::new(0);
2657        let challenge = format!("challenge-{}", CONNECTION.fetch_add(1, Ordering::SeqCst));
2658        let (mut challenged, mut authed) = (greet, HashSet::<PublicKey>::new());
2659        let mut open = HashSet::<SubscriptionId>::new();
2660        let mut reconciling = std::collections::HashMap::<SubscriptionId, negentropy::Negentropy<'static, negentropy::NegentropyStorageVector>>::new();
2661        if greet && sink.send(Ws::Text(RelayMessage::auth(challenge.clone()).as_json().into())).await.is_err() {
2662            return;
2663        }
2664        while let Some(Ok(frame)) = stream.next().await {
2665            let Ws::Text(text) = frame else { continue };
2666            let mut out: Vec<RelayMessage> = Vec::new();
2667            match ClientMessage::from_json(text.as_str()) {
2668                Ok(ClientMessage::Req { .. }) if modes.hangs_up.load(Ordering::SeqCst) => return,
2669                Ok(ClientMessage::Req { subscription_id, filters }) => {
2670                    let id = subscription_id.into_owned();
2671                    let named = filters.iter().flat_map(|f| f.authors.iter().flatten().copied());
2672                    let cap = modes.sub_cap.load(Ordering::SeqCst);
2673                    if modes.refuses.load(Ordering::SeqCst) {
2674                        out.push(RelayMessage::closed(id, "error: refused"));
2675                    } else if cap > 0 && open.len() >= cap {
2676                        out.push(RelayMessage::closed(id, "error: too many subscriptions"));
2677                    } else if modes.gated.load(Ordering::SeqCst) && !named.into_iter().all(|a| authed.contains(&a)) {
2678                        if !challenged && !modes.mute.load(Ordering::SeqCst) {
2679                            challenged = true;
2680                            out.push(RelayMessage::auth(challenge.clone()));
2681                        }
2682                        out.push(match modes.quiet.load(Ordering::SeqCst) {
2683                            true => RelayMessage::eose(id),
2684                            false => RelayMessage::closed(id, "auth-required: all authors must be authenticated"),
2685                        });
2686                    } else {
2687                        open.insert(id.clone());
2688                        let held = held.lock().unwrap();
2689                        let mut matched: Vec<&Event> = held.iter().filter(|e| filters.iter().any(|f| f.match_event(e, MatchEventOptions::new()))).collect();
2690                        // The newest `limit`, as a relay pages.
2691                        if let Some(limit) = filters.iter().filter_map(|f| f.limit).max() {
2692                            matched.sort_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| b.id.cmp(&a.id)));
2693                            matched.truncate(limit);
2694                        }
2695                        for e in matched {
2696                            out.push(RelayMessage::event(id.clone(), e.clone()));
2697                        }
2698                        out.push(RelayMessage::eose(id));
2699                        if !challenged && modes.challenges_after.load(Ordering::SeqCst) {
2700                            challenged = true;
2701                            out.push(RelayMessage::auth(challenge.clone()));
2702                        }
2703                    }
2704                }
2705                Ok(ClientMessage::Close(id)) => {
2706                    open.remove(id.as_ref());
2707                }
2708                Ok(ClientMessage::NegOpen { subscription_id, filter, initial_message }) => {
2709                    modes.neg_opens.fetch_add(1, Ordering::SeqCst);
2710                    let id = subscription_id.into_owned();
2711                    let named = filter.authors.iter().flatten().copied();
2712                    match modes.neg.load(Ordering::SeqCst) {
2713                        1 => out.push(RelayMessage::notice("ERROR: bad msg: unknown cmd")),
2714                        2 => {}
2715                        _ if modes.neg_cap.load(Ordering::SeqCst) > 0 && reconciling.len() >= modes.neg_cap.load(Ordering::SeqCst) => {
2716                            out.push(RelayMessage::NegErr { subscription_id: std::borrow::Cow::Owned(id), message: "blocked: too many open negentropy sessions".into() });
2717                        }
2718                        _ if modes.gated.load(Ordering::SeqCst) && !named.into_iter().all(|a| authed.contains(&a)) => {
2719                            out.push(RelayMessage::NegErr { subscription_id: std::borrow::Cow::Owned(id), message: "auth-required: all authors must be authenticated".into() });
2720                        }
2721                        _ => {
2722                            let mut storage = negentropy::NegentropyStorageVector::new();
2723                            for e in held.lock().unwrap().iter().filter(|e| filter.match_event(e, MatchEventOptions::new())) {
2724                                storage.insert(e.created_at.as_secs(), negentropy::Id::from_byte_array(e.id.to_bytes())).unwrap();
2725                            }
2726                            storage.seal().unwrap();
2727                            let mut neg = negentropy::Negentropy::owned(storage, 60_000).unwrap();
2728                            let answer = neg.reconcile(&crate::simd::hex::hex_string_to_bytes(&initial_message)).unwrap();
2729                            out.push(RelayMessage::NegMsg { subscription_id: std::borrow::Cow::Owned(id.clone()), message: crate::simd::hex::bytes_to_hex_string(&answer).into() });
2730                            reconciling.insert(id, neg);
2731                        }
2732                    }
2733                }
2734                Ok(ClientMessage::NegMsg { subscription_id, message }) => {
2735                    if let Some(neg) = reconciling.get_mut(subscription_id.as_ref()) {
2736                        let answer = neg.reconcile(&crate::simd::hex::hex_string_to_bytes(&message)).unwrap();
2737                        out.push(RelayMessage::NegMsg { subscription_id, message: crate::simd::hex::bytes_to_hex_string(&answer).into() });
2738                    }
2739                }
2740                Ok(ClientMessage::NegClose { subscription_id }) => {
2741                    reconciling.remove(subscription_id.as_ref());
2742                }
2743                Ok(ClientMessage::Auth(event)) => {
2744                    let ok = nostr::nips::nip42::is_valid_auth_event(&event, &url, &challenge);
2745                    if ok {
2746                        authed.insert(event.pubkey);
2747                    }
2748                    out.push(RelayMessage::ok(event.id, ok, if ok { "" } else { "invalid: auth" }));
2749                }
2750                Ok(ClientMessage::Event(event)) => {
2751                    out.push(RelayMessage::ok(event.id, true, ""));
2752                    held.lock().unwrap().push(event.into_owned());
2753                }
2754                _ => {}
2755            }
2756            for m in out {
2757                if sink.send(Ws::Text(m.as_json().into())).await.is_err() {
2758                    return;
2759                }
2760            }
2761        }
2762    }
2763}
2764
2765/// A [`Transport`] that fails on purpose.
2766///
2767/// `MemoryRelay` always succeeds: no failed fetch, no short page, no reordering,
2768/// no relay that serves a different subset than its siblings. Every strand and
2769/// fork this codebase has shipped lives in exactly the space it cannot express,
2770/// which is a large part of why none of them were caught by a test. This wraps it
2771/// and injects the failures a real relay set produces.
2772///
2773/// Deterministic by construction — the only randomness is a seeded counter, so a
2774/// failing scenario reproduces exactly from its seed.
2775#[cfg(test)]
2776pub(crate) mod adversarial {
2777    // A fault-injection toolkit: each scenario uses the rules it needs, and the rest
2778    // of the surface waits for the next scenario rather than being trimmed to fit.
2779    #![allow(dead_code)]
2780
2781    use super::memory::MemoryRelay;
2782    use super::*;
2783    use std::sync::atomic::{AtomicU64, Ordering};
2784    use std::sync::Mutex;
2785
2786    /// What a fetch should do instead of succeeding.
2787    #[derive(Clone, Debug)]
2788    pub enum Fault {
2789        /// Return `Err` — a dead relay, an AUTH gate, a timeout.
2790        FailFetch(String),
2791        /// Succeed, but serve at most `n` events — the "short page reads as the end
2792        /// of the plane" hazard.
2793        ShortPage(usize),
2794        /// Succeed, but serve nothing at all — a relay silently withholding.
2795        Empty,
2796        /// Serve at most `n` events from the relays that answered, while another
2797        /// stayed silent: a short page that is NOT the end of the plane.
2798        ShortUnconfirmed(usize),
2799    }
2800
2801    /// Which fetches a rule applies to. Matched against the query, so a plan can
2802    /// target one plane (an author) without knowing call order.
2803    #[derive(Clone, Debug, Default)]
2804    pub struct Match {
2805        /// Any of these authors appears in the query.
2806        pub author: Option<String>,
2807        /// Only the Nth matching call (1-based); `None` = every one.
2808        pub nth: Option<u64>,
2809        /// Only from this call onward (1-based).
2810        pub from_nth: Option<u64>,
2811    }
2812
2813    impl Match {
2814        pub fn author(hex: &str) -> Self {
2815            Match { author: Some(hex.to_string()), ..Default::default() }
2816        }
2817        pub fn any() -> Self {
2818            Match::default()
2819        }
2820        pub fn nth(mut self, n: u64) -> Self {
2821            self.nth = Some(n);
2822            self
2823        }
2824        pub fn from_nth(mut self, n: u64) -> Self {
2825            self.from_nth = Some(n);
2826            self
2827        }
2828    }
2829
2830    struct Rule {
2831        m: Match,
2832        fault: Fault,
2833        hits: AtomicU64,
2834    }
2835
2836    pub struct AdversarialRelay {
2837        inner: MemoryRelay,
2838        rules: Mutex<Vec<Rule>>,
2839        /// Every fetch, whether or not a rule matched — the round-trip counter a
2840        /// scale test asserts on ("~2 per hop, not ~97").
2841        fetches: AtomicU64,
2842    }
2843
2844    impl AdversarialRelay {
2845        pub fn new() -> Self {
2846            AdversarialRelay { inner: MemoryRelay::new(), rules: Mutex::new(Vec::new()), fetches: AtomicU64::new(0) }
2847        }
2848
2849        /// The underlying honest relay — publish fixtures through this so a fault
2850        /// plan governs only what the client can READ back.
2851        pub fn relay(&self) -> &MemoryRelay {
2852            &self.inner
2853        }
2854
2855        pub fn on(&self, m: Match, fault: Fault) -> &Self {
2856            self.rules.lock().unwrap_or_else(|e| e.into_inner()).push(Rule { m, fault, hits: AtomicU64::new(0) });
2857            self
2858        }
2859
2860        /// Drop every rule — "the faults cease", the precondition of the
2861        /// convergence property every scenario asserts.
2862        pub fn heal(&self) {
2863            self.rules.lock().unwrap_or_else(|e| e.into_inner()).clear();
2864        }
2865
2866        pub fn fetch_count(&self) -> u64 {
2867            self.fetches.load(Ordering::Relaxed)
2868        }
2869
2870        pub fn reset_fetch_count(&self) {
2871            self.fetches.store(0, Ordering::Relaxed);
2872        }
2873
2874        fn verdict(&self, query: &Query) -> Option<Fault> {
2875            let rules = self.rules.lock().unwrap_or_else(|e| e.into_inner());
2876            for r in rules.iter() {
2877                if let Some(a) = &r.m.author {
2878                    if !query.authors.iter().any(|q| q == a) {
2879                        continue;
2880                    }
2881                }
2882                let n = r.hits.fetch_add(1, Ordering::Relaxed) + 1;
2883                if r.m.nth.is_some_and(|want| want != n) {
2884                    continue;
2885                }
2886                if r.m.from_nth.is_some_and(|first| n < first) {
2887                    continue;
2888                }
2889                return Some(r.fault.clone());
2890            }
2891            None
2892        }
2893
2894        /// The served events, and whether every relay answered.
2895        async fn governed(&self, query: &Query, relays: &[String], plane: Option<&Keys>) -> Result<(Vec<Event>, bool), String> {
2896            self.fetches.fetch_add(1, Ordering::Relaxed);
2897            let short = match self.verdict(query) {
2898                Some(Fault::FailFetch(why)) => return Err(why),
2899                Some(Fault::Empty) => return Ok((Vec::new(), true)),
2900                Some(Fault::ShortPage(n)) => Some((n, true)),
2901                Some(Fault::ShortUnconfirmed(n)) => Some((n, false)),
2902                None => None,
2903            };
2904            let mut out = match plane {
2905                Some(p) => self.inner.fetch_plane(p, query, relays).await?.events,
2906                None => self.inner.fetch(query, relays).await?,
2907            };
2908            let Some((n, complete)) = short else { return Ok((out, true)) };
2909            out.truncate(n);
2910            Ok((out, complete))
2911        }
2912    }
2913
2914    #[async_trait::async_trait]
2915    impl Transport for AdversarialRelay {
2916        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2917            self.inner.publish(event, relays).await
2918        }
2919        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
2920            self.inner.publish_durable(event, relays).await
2921        }
2922        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
2923            self.governed(query, relays, None).await.map(|(events, _)| events)
2924        }
2925        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<PlaneFetch, String> {
2926            // `Empty` answers with nothing (coverage intact, so absence is real)
2927            // while `FailFetch` propagates an Err (nobody answered, so absence is
2928            // unproven) — the exact distinction the coverage field carries.
2929            let (events, complete) = self.governed(query, relays, Some(plane)).await?;
2930            Ok(if complete { PlaneFetch::whole(events) } else { PlaneFetch { events, answered: 1, attempted: 2 } })
2931        }
2932    }
2933}
2934
2935#[cfg(test)]
2936mod tests {
2937    use super::*;
2938
2939    /// Relays whose plane AUTH answers [`SlowAuth`] holds back.
2940    static SLOW_AUTH: std::sync::Mutex<std::collections::BTreeSet<String>> = std::sync::Mutex::new(std::collections::BTreeSet::new());
2941
2942    /// The plane authenticator, slowed for the relays in [`SLOW_AUTH`].
2943    #[derive(Debug)]
2944    pub(super) struct SlowAuth<T: nostr_sdk::prelude::Authenticator>(pub(super) T);
2945
2946    impl<T: nostr_sdk::prelude::Authenticator> nostr_sdk::prelude::Authenticator for SlowAuth<T> {
2947        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>> {
2948            Box::pin(async move {
2949                if SLOW_AUTH.lock().unwrap().contains(&crate::inbox_relays::normalize_relay_url(relay_url.as_str())) {
2950                    tokio::time::sleep(std::time::Duration::from_millis(400)).await;
2951                }
2952                self.0.make_auth_event(relay_url, challenge).await
2953            })
2954        }
2955    }
2956
2957    // ── Plane read coverage ───────────────────────────────────────────────────
2958
2959    fn urls(n: usize) -> Vec<String> {
2960        (0..n).map(|i| format!("wss://r{i}")).collect()
2961    }
2962
2963    #[test]
2964    fn a_plane_read_that_skipped_a_tripped_relay_does_not_claim_full_coverage() {
2965        // A skipped relay was never asked, so whatever it holds is unseen: the read
2966        // may RETURN early, but it must not report every relay as having answered.
2967        let sel = plane_targets(urls(3), |r| r == "wss://r1");
2968        assert_eq!(sel.ask, vec!["wss://r0".to_string(), "wss://r2".to_string()], "the tripped relay is spared");
2969        let read = sel.fetched(Vec::new(), 2, sel.ask.len());
2970        assert_eq!((read.answered, read.attempted), (2, 3), "the skipped relay stays in the denominator");
2971        assert!(!read.is_complete(), "an empty answer from the asked relays is not proof of absence");
2972    }
2973
2974    #[test]
2975    fn a_plane_read_with_nothing_tripped_or_everything_tripped_asks_everyone() {
2976        let none = plane_targets(urls(3), |_| false);
2977        assert_eq!((none.ask.len(), none.skipped), (3, 0));
2978        assert!(none.fetched(Vec::new(), 3, 3).is_complete(), "every relay asked and answered IS full coverage");
2979        // Skipping every relay would ask nobody: ask them all rather than return nothing.
2980        let all = plane_targets(urls(3), |_| true);
2981        assert_eq!((all.ask.len(), all.skipped), (3, 0));
2982        assert!(all.fetched(Vec::new(), 3, 3).is_complete());
2983    }
2984
2985    #[test]
2986    fn a_dead_socket_leaves_the_denominator_but_a_tripped_relay_does_not() {
2987        // A dead socket can't answer this call at all, so it was never reachable;
2988        // a tripped relay merely answered badly lately and may hold the event.
2989        let sel = plane_targets(urls(4), |r| r == "wss://r3");
2990        let after_dead_sockets = sel.ask.len() - 1;
2991        let read = sel.fetched(Vec::new(), after_dead_sockets, after_dead_sockets);
2992        assert_eq!(read.attempted, 3, "asked minus the dead socket, plus the tripped relay");
2993        assert!(!read.is_complete());
2994    }
2995
2996    // ── Plane pool ────────────────────────────────────────────────────────────
2997
2998    /// Polls until `cond` holds: the sweep runs on real time, so wait for it rather than guess.
2999    async fn eventually(cond: impl Fn() -> bool) -> bool {
3000        for _ in 0..100 {
3001            if cond() {
3002                return true;
3003            }
3004            tokio::time::sleep(PLANE_POOL_IDLE_TTL / 4).await;
3005        }
3006        cond()
3007    }
3008
3009    #[tokio::test]
3010    async fn an_idle_plane_connection_closes_without_another_fetch() {
3011        // Its own pool: the global one is drained by any swap elsewhere in the suite.
3012        let pool: &'static PlanePool = Box::leak(Box::default());
3013        let in_pool = |key: &str| pool.lock().1.contains_key(key);
3014        let (kept, idle) = ("plane-kept|wss://a", "plane-idle|wss://a");
3015        pool.insert(0, idle.into(), crate::nostr_client_builder().build());
3016        pool.insert(0, kept.into(), crate::nostr_client_builder().build());
3017        assert!(in_pool(idle) && in_pool(kept));
3018
3019        // One stays in use (stamped ahead, so no sleep can let it lapse): only the idle one
3020        // goes, and nothing fetched to notice it.
3021        pool.lock().1.get_mut(kept).unwrap().last_used = web_time::Instant::now() + std::time::Duration::from_secs(60);
3022        assert!(eventually(|| !in_pool(idle)).await, "the idle connection was swept");
3023        assert!(in_pool(kept), "the one in use stays warm");
3024
3025        pool.lock().1.get_mut(kept).unwrap().last_used = web_time::Instant::now();
3026        assert!(eventually(|| !in_pool(kept)).await, "and goes once it idles too");
3027        let disarmed = || !pool.sweep_armed.load(std::sync::atomic::Ordering::Acquire);
3028        assert!(eventually(disarmed).await, "an empty pool runs no sweep");
3029    }
3030
3031    // ── Plane connections by relay gate ───────────────────────────────────────
3032
3033    /// A plane key and the one wrap it authored, held by `relay`.
3034    fn plane_on(relay: &wire::WireRelay) -> (Keys, Event) {
3035        use nostr_sdk::prelude::FinalizeEvent;
3036        let plane = Keys::generate();
3037        let wrap = EventBuilder::new(Kind::Custom(crate::community::v2::stream::KIND_WRAP), "sealed").finalize(&plane).unwrap();
3038        relay.hold([wrap.clone()]);
3039        (plane, wrap)
3040    }
3041
3042    async fn read_plane(relay: &wire::WireRelay, plane: &Keys) -> PlaneFetch {
3043        read_plane_at(relay.url(), plane.clone()).await
3044    }
3045
3046    async fn read_plane_at(url: String, plane: Keys) -> PlaneFetch {
3047        let query = Query {
3048            kinds: vec![crate::community::v2::stream::KIND_WRAP],
3049            authors: vec![plane.public_key().to_hex()],
3050            ..Default::default()
3051        };
3052        LiveTransport::with_timeout(std::time::Duration::from_secs(5)).fetch_plane(&plane, &query, &[url]).await.unwrap()
3053    }
3054
3055    fn gate_of(relay: &wire::WireRelay) -> Option<RelayGate> {
3056        with_plane_relay(crate::db::current_session_id(), &relay.url(), |r| r.gate)
3057    }
3058
3059    fn authed_pooled(plane: &Keys) -> bool {
3060        let pk = plane.public_key().to_hex();
3061        PLANE_POOL.lock().1.keys().any(|k| k.starts_with(&pk))
3062    }
3063
3064    fn open_pooled(relay: &wire::WireRelay) -> bool {
3065        OPEN_PLANES.lock().1.contains_key(&relay.url())
3066    }
3067
3068    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3069    #[allow(clippy::await_holding_lock)]
3070    async fn a_relay_that_never_challenges_serves_every_plane_over_one_connection() {
3071        let _s = GateScene::new();
3072        let relay = wire::WireRelay::start().await;
3073        let planes: Vec<(Keys, Event)> = (0..5).map(|_| plane_on(&relay)).collect();
3074        for (plane, wrap) in &planes {
3075            let read = read_plane(&relay, plane).await;
3076            assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3077            assert!(read.is_complete());
3078            assert!(!authed_pooled(plane), "no connection of its own");
3079        }
3080        assert_eq!(relay.opened(), 1, "five planes, one connection");
3081        assert_eq!(gate_of(&relay), Some(RelayGate::Open));
3082        assert!(open_pooled(&relay));
3083        clear_plane_pool();
3084        assert!(!open_pooled(&relay), "a swap closes it with the authed ones");
3085    }
3086
3087    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3088    #[allow(clippy::await_holding_lock)]
3089    async fn reads_that_reach_a_new_relay_together_dial_it_once() {
3090        let _s = GateScene::new();
3091        let relay = wire::WireRelay::start().await;
3092        let planes: Vec<(Keys, Event)> = (0..8).map(|_| plane_on(&relay)).collect();
3093        let reads = planes.iter().map(|(plane, _)| tokio::spawn(read_plane_at(relay.url(), plane.clone())));
3094        for read in futures_util::future::join_all(reads).await {
3095            assert_eq!(read.unwrap().events.len(), 1);
3096        }
3097        assert_eq!(relay.opened(), 1);
3098    }
3099
3100    #[tokio::test]
3101    #[allow(clippy::await_holding_lock)]
3102    async fn on_one_thread_a_challenge_inside_a_read_is_seen_by_that_read() {
3103        let _s = GateScene::new();
3104        let relay = wire::WireRelay::start().await;
3105        relay.gate(true);
3106        relay.quiet(true);
3107        let (plane, wrap) = plane_on(&relay);
3108        let read = read_plane(&relay, &plane).await;
3109        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3110        assert!(authed_pooled(&plane) && !open_pooled(&relay));
3111    }
3112
3113    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3114    #[allow(clippy::await_holding_lock)]
3115    async fn auth_required_without_a_challenge_is_still_a_gate() {
3116        let _s = GateScene::new();
3117        let relay = wire::WireRelay::start().await;
3118        relay.gate(true);
3119        relay.mute(true);
3120        let (plane, _) = plane_on(&relay);
3121        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3122        let read = LiveTransport::with_timeout(std::time::Duration::from_secs(2)).fetch_plane(&plane, &query, &[relay.url()]).await;
3123        assert!(read.is_err(), "nothing to authenticate against, so nothing served");
3124        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3125    }
3126
3127    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3128    #[allow(clippy::await_holding_lock)]
3129    async fn a_challenge_between_reads_moves_the_next_read_to_an_authed_connection() {
3130        let _s = GateScene::new();
3131        let relay = wire::WireRelay::start().await;
3132        relay.challenge_after_a_read(true);
3133        let (first, _) = plane_on(&relay);
3134        read_plane(&relay, &first).await;
3135        assert!(eventually(|| gate_of(&relay) == Some(RelayGate::Auth)).await, "the socket's watcher saw it");
3136        let (second, _) = plane_on(&relay);
3137        read_plane(&relay, &second).await;
3138        assert!(authed_pooled(&second));
3139    }
3140
3141    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3142    #[allow(clippy::await_holding_lock)]
3143    async fn a_socket_that_closes_under_a_read_ends_it_at_once() {
3144        let _s = GateScene::new();
3145        let relay = wire::WireRelay::start().await;
3146        relay.hang_up(true);
3147        let plane = Keys::generate();
3148        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3149        let started = web_time::Instant::now();
3150        let read = LiveTransport::with_timeout(std::time::Duration::from_secs(5)).fetch_plane(&plane, &query, &[relay.url()]).await;
3151        assert!(read.is_err(), "nothing answered");
3152        assert!(started.elapsed() < std::time::Duration::from_secs(2), "not left to its deadline: {:?}", started.elapsed());
3153    }
3154
3155    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3156    #[allow(clippy::await_holding_lock)]
3157    async fn reads_sharing_one_connection_stay_under_its_subscription_cap() {
3158        let _s = GateScene::new();
3159        let relay = wire::WireRelay::start().await;
3160        relay.cap_subs(16);
3161        let planes: Vec<(Keys, Event)> = (0..40).map(|_| plane_on(&relay)).collect();
3162        let reads = planes.iter().map(|(plane, _)| tokio::spawn(read_plane_at(relay.url(), plane.clone())));
3163        for read in futures_util::future::join_all(reads).await {
3164            assert_eq!(read.unwrap().events.len(), 1);
3165        }
3166        assert_eq!(relay.opened(), 1);
3167    }
3168
3169    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3170    #[allow(clippy::await_holding_lock)]
3171    async fn a_relay_that_cannot_be_reached_is_not_redialled_for_every_read() {
3172        use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
3173        let _s = GateScene::new();
3174        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3175        let url = format!("ws://127.0.0.1:{}", listener.local_addr().unwrap().port());
3176        let dials = std::sync::Arc::new(AtomicUsize::new(0));
3177        let counted = dials.clone();
3178        tokio::spawn(async move {
3179            while let Ok((tcp, _)) = listener.accept().await {
3180                counted.fetch_add(1, SeqCst);
3181                drop(tcp);
3182            }
3183        });
3184        let plane = Keys::generate();
3185        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3186        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(2));
3187        for _ in 0..3 {
3188            assert!(live.fetch_plane(&plane, &query, std::slice::from_ref(&url)).await.is_err(), "nothing answered");
3189        }
3190        assert_eq!(dials.load(SeqCst), 1, "one dial inside the redial gap");
3191        clear_plane_pool();
3192        assert!(live.fetch_plane(&plane, &query, std::slice::from_ref(&url)).await.is_err());
3193        assert_eq!(dials.load(SeqCst), 2, "a new network dials at once");
3194    }
3195
3196    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3197    #[allow(clippy::await_holding_lock)]
3198    async fn a_relay_that_asks_for_auth_reads_each_plane_on_a_connection_authed_as_it() {
3199        let _s = GateScene::new();
3200        let relay = wire::WireRelay::start().await;
3201        relay.gate(true);
3202        let planes: Vec<(Keys, Event)> = (0..3).map(|_| plane_on(&relay)).collect();
3203        for (plane, wrap) in &planes {
3204            let read = read_plane(&relay, plane).await;
3205            assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "served once authed as the plane");
3206            assert!(authed_pooled(plane));
3207        }
3208        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3209        assert!(!open_pooled(&relay), "the open connection closed at the first challenge");
3210        assert_eq!(relay.opened(), 1 + planes.len(), "the read that met the gate, then one per plane");
3211    }
3212
3213    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3214    #[allow(clippy::await_holding_lock)]
3215    async fn a_relay_that_starts_challenging_moves_its_planes_to_authed_connections() {
3216        let _s = GateScene::new();
3217        let relay = wire::WireRelay::start().await;
3218        let (first, _) = plane_on(&relay);
3219        read_plane(&relay, &first).await;
3220        assert_eq!((gate_of(&relay), relay.opened()), (Some(RelayGate::Open), 1));
3221
3222        relay.gate(true);
3223        let (second, wrap) = plane_on(&relay);
3224        let read = read_plane(&relay, &second).await;
3225        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "the same read, from an authed connection");
3226        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3227        assert!(authed_pooled(&second) && !open_pooled(&relay));
3228
3229        let (third, _) = plane_on(&relay);
3230        read_plane(&relay, &third).await;
3231        assert_eq!(relay.opened(), 3, "no read goes back to the open connection");
3232    }
3233
3234    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3235    #[allow(clippy::await_holding_lock)]
3236    async fn a_relay_that_challenges_then_answers_with_silence_still_serves_the_plane_once_authed() {
3237        let _s = GateScene::new();
3238        let relay = wire::WireRelay::start().await;
3239        relay.gate(true);
3240        relay.quiet(true);
3241        let (plane, wrap) = plane_on(&relay);
3242        let read = read_plane(&relay, &plane).await;
3243        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "the silence was no answer");
3244        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3245        assert!(authed_pooled(&plane));
3246    }
3247
3248    /// A port that refuses every connection.
3249    async fn refusing_url() -> String {
3250        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
3251        let port = listener.local_addr().unwrap().port();
3252        drop(listener);
3253        format!("ws://127.0.0.1:{port}")
3254    }
3255
3256    async fn read_across(urls: &[String], plane: &Keys, timeout: std::time::Duration) -> PlaneFetch {
3257        let query = Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
3258        LiveTransport::with_timeout(timeout).fetch_plane(plane, &query, urls).await.unwrap()
3259    }
3260
3261    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3262    #[allow(clippy::await_holding_lock)]
3263    async fn a_relay_never_reached_leaves_the_read_of_the_others_complete() {
3264        let _s = GateScene::new();
3265        let relay = wire::WireRelay::start().await;
3266        let (plane, _) = plane_on(&relay);
3267        let read = read_across(&[relay.url(), refusing_url().await], &plane, std::time::Duration::from_secs(2)).await;
3268        assert_eq!((read.answered, read.attempted), (1, 1));
3269        assert!(read.is_complete());
3270    }
3271
3272    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3273    #[allow(clippy::await_holding_lock)]
3274    async fn a_relay_that_refuses_the_read_keeps_it_incomplete() {
3275        let _s = GateScene::new();
3276        let (answers, refuses) = (wire::WireRelay::start().await, wire::WireRelay::start().await);
3277        refuses.refuse(true);
3278        let (plane, _) = plane_on(&answers);
3279        let read = read_across(&[answers.url(), refuses.url()], &plane, std::time::Duration::from_secs(2)).await;
3280        assert_eq!((read.answered, read.attempted), (1, 2));
3281        assert!(!read.is_complete());
3282        assert_eq!(gate_of(&refuses), None, "a refusal is no gate");
3283    }
3284
3285    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3286    #[allow(clippy::await_holding_lock)]
3287    async fn a_relay_still_connecting_is_read_not_dropped() {
3288        let _s = GateScene::new();
3289        let (quick, slow) = (wire::WireRelay::start().await, wire::WireRelay::start().await);
3290        slow.stall(std::time::Duration::from_millis(1500));
3291        let (plane, wrap) = plane_on(&slow);
3292        let read = read_across(&[quick.url(), slow.url()], &plane, std::time::Duration::from_secs(1)).await;
3293        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "the slow relay held it");
3294        assert_eq!((read.answered, read.attempted), (2, 2));
3295    }
3296
3297    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3298    #[allow(clippy::await_holding_lock)]
3299    async fn a_gating_relay_that_is_down_leaves_the_denominator_when_an_open_one_answered() {
3300        let _s = GateScene::new();
3301        let relay = wire::WireRelay::start().await;
3302        let down = refusing_url().await;
3303        mark_auth(crate::db::current_session_id(), &crate::inbox_relays::normalize_relay_url(&down));
3304        let (plane, wrap) = plane_on(&relay);
3305        let read = read_across(&[relay.url(), down], &plane, std::time::Duration::from_secs(2)).await;
3306        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3307        assert_eq!((read.answered, read.attempted), (1, 1));
3308    }
3309
3310    #[tokio::test]
3311    async fn a_previous_sessions_caller_leaves_the_pool_alone() {
3312        let pool: &'static PlanePool = Box::leak(Box::default());
3313        let build = || crate::nostr_client_builder().build();
3314        let (_, hold, _) = pool.take_or_insert(7, "wss://a", build).unwrap();
3315        let id = hold.id;
3316        assert!(pool.take_or_insert(6, "wss://a", build).is_none(), "an earlier session builds nothing");
3317        assert_eq!(pool.take(6, "wss://a").0.map(|_| ()), None);
3318        assert_eq!(pool.lock().0, 7);
3319        assert_eq!(pool.lock().1.get("wss://a").map(|p| p.id), Some(id), "and wipes nothing");
3320        assert!(pool.remove(7, "wss://a", id + 1).is_none(), "a replacement is not removed for its predecessor");
3321    }
3322
3323    #[tokio::test]
3324    async fn a_held_open_connection_outlives_the_idle_clock_and_goes_once_released() {
3325        let pool: &'static PlanePool = Box::leak(Box::default());
3326        let (_, hold, _) = pool.take_or_insert(1, "wss://a", || crate::nostr_client_builder().build()).unwrap();
3327        tokio::time::sleep(PLANE_POOL_IDLE_TTL * 3).await;
3328        assert!(pool.lock().1.contains_key("wss://a"), "a dial or read in flight keeps it");
3329        drop(hold);
3330        assert!(eventually(|| !pool.lock().1.contains_key("wss://a")).await, "and it idles out after");
3331    }
3332
3333    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3334    #[allow(clippy::await_holding_lock)]
3335    async fn a_challenge_on_connect_gates_the_first_read_however_late_its_watcher_runs() {
3336        let _s = GateScene::new();
3337        let relay = wire::WireRelay::start().await;
3338        let key = crate::inbox_relays::normalize_relay_url(&relay.url());
3339        UNWATCHED.lock().unwrap().insert(key.clone());
3340        relay.greet(true);
3341        let (plane, wrap) = plane_on(&relay);
3342        // Every read slot held until the greeting has long landed, so the read subscribes after it.
3343        let held = open_read_permits(&key).acquire_many_owned(OPEN_READS_PER_RELAY as u32).await.unwrap();
3344        let read = tokio::spawn({
3345            let (url, plane) = (relay.url(), plane.clone());
3346            async move { read_plane_at(url, plane).await }
3347        });
3348        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3349        drop(held);
3350        let read = read.await.unwrap();
3351        UNWATCHED.lock().unwrap().remove(&key);
3352        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3353        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3354        assert!(authed_pooled(&plane) && !open_pooled(&relay), "read again on a connection authed as the plane");
3355    }
3356
3357    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3358    #[allow(clippy::await_holding_lock)]
3359    async fn an_authed_read_asks_only_once_its_auth_has_landed() {
3360        let _s = GateScene::new();
3361        let relay = wire::WireRelay::start().await;
3362        relay.gate(true);
3363        relay.quiet(true);
3364        let key = crate::inbox_relays::normalize_relay_url(&relay.url());
3365        SLOW_AUTH.lock().unwrap().insert(key.clone());
3366        let (plane, wrap) = plane_on(&relay);
3367        let read = read_plane(&relay, &plane).await;
3368        SLOW_AUTH.lock().unwrap().remove(&key);
3369        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id], "an answer ahead of the AUTH is no answer");
3370        assert!(authed_pooled(&plane));
3371    }
3372
3373    #[tokio::test]
3374    async fn waiting_for_auth_ends_on_its_answer_and_never_starts_without_a_challenge() {
3375        let auth = || RelayNotification::Message { message: Box::new(RelayMessage::auth("c")) };
3376        let budget = std::time::Duration::from_secs(5);
3377        let started = tokio::time::Instant::now();
3378        authenticated(Box::pin(futures_util::stream::iter(vec![RelayNotification::Authenticated])), budget).await;
3379        authenticated(Box::pin(futures_util::stream::pending()), budget).await;
3380        assert!(started.elapsed() < std::time::Duration::from_secs(1), "no challenge, nothing to wait for");
3381        let answered = futures_util::stream::iter(vec![auth()]).chain(futures_util::stream::once(async {
3382            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
3383            RelayNotification::AuthenticationFailed
3384        }));
3385        let started = tokio::time::Instant::now();
3386        authenticated(Box::pin(answered.chain(futures_util::stream::pending())), budget).await;
3387        let waited = started.elapsed();
3388        assert!(waited >= std::time::Duration::from_millis(200) && waited < std::time::Duration::from_secs(2), "waited for the answer, refused or not: {waited:?}");
3389        let started = tokio::time::Instant::now();
3390        authenticated(Box::pin(futures_util::stream::iter(vec![auth()]).chain(futures_util::stream::pending())), std::time::Duration::from_millis(300)).await;
3391        assert!(started.elapsed() >= std::time::Duration::from_millis(300), "a challenge unanswered waits out the budget");
3392    }
3393
3394    #[test]
3395    fn a_settled_gate_reads_only_its_own_sockets_greeting() {
3396        let _s = GateScene::new();
3397        let generation = crate::db::current_session_id();
3398        let auth = || RelayNotification::Message { message: Box::new(RelayMessage::auth("c")) };
3399        let greet = |key: &str, id: u64, frames: Vec<RelayNotification>| {
3400            GREETINGS.lock().unwrap().insert((generation, key.to_string()), (id, Box::pin(futures_util::stream::iter(frames))));
3401        };
3402        greet("wss://greets", 1, vec![auth()]);
3403        assert_eq!(settle_gate(generation, "wss://greets", 1), RelayGate::Auth);
3404        greet("wss://quiet", 1, vec![]);
3405        assert_eq!(settle_gate(generation, "wss://quiet", 1), RelayGate::Open);
3406        greet("wss://replaced", 2, vec![auth()]);
3407        assert_eq!(settle_gate(generation, "wss://replaced", 1), RelayGate::Open, "another socket's greeting is not this one's");
3408        assert!(GREETINGS.lock().unwrap().contains_key(&(generation, "wss://replaced".to_string())), "and stays for its own socket");
3409        assert!(!GREETINGS.lock().unwrap().contains_key(&(generation, "wss://greets".to_string())), "a settled socket's frames are let go");
3410    }
3411
3412    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3413    #[allow(clippy::await_holding_lock)]
3414    async fn a_challenge_on_connect_is_a_gate_even_when_reads_are_served() {
3415        let _s = GateScene::new();
3416        let relay = wire::WireRelay::start().await;
3417        relay.greet(true);
3418        let (plane, wrap) = plane_on(&relay);
3419        let read = read_plane(&relay, &plane).await;
3420        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
3421        assert_eq!(gate_of(&relay), Some(RelayGate::Auth));
3422        assert!(authed_pooled(&plane) && !open_pooled(&relay));
3423    }
3424
3425    // ── Dead-socket target filtering ──────────────────────────────────────────
3426
3427    #[test]
3428    fn a_dead_socket_is_skipped_but_a_connecting_or_unknown_one_is_not() {
3429        let targets: Vec<String> = ["wss://dead", "wss://connecting", "wss://unknown"].map(String::from).into();
3430        let out = drop_unrevivable(targets, |r| r == "wss://dead");
3431        assert_eq!(out, ["wss://connecting", "wss://unknown"].map(String::from).to_vec());
3432    }
3433
3434    #[test]
3435    fn an_all_dead_set_falls_back_to_the_full_list() {
3436        // Offline (or a status race) must keep the honest-timeout error paths —
3437        // an instant empty-target "success" would read as a confident empty.
3438        let targets: Vec<String> = ["wss://a", "wss://b"].map(String::from).into();
3439        let out = drop_unrevivable(targets.clone(), |_| true);
3440        assert_eq!(out, targets);
3441    }
3442
3443    #[tokio::test]
3444    async fn pruning_severs_a_lone_community_relay_and_keeps_every_shared_one() {
3445        let client = crate::nostr_client_builder().build();
3446        let gossip = crate::community_relay_capabilities();
3447        for (url, caps) in [
3448            ("wss://left.example", gossip),
3449            ("wss://other.example", gossip),
3450            ("wss://nos.lol", crate::discovery_relay_capabilities()),
3451            ("wss://own-read.example", RelayCapabilities::READ),
3452            ("wss://own-write.example", RelayCapabilities::WRITE),
3453        ] {
3454            client.add_managed_relay(url).capabilities(caps).await.unwrap();
3455        }
3456        let candidates: Vec<String> = ["wss://left.example/", "wss://OTHER.example", "wss://nos.lol", "wss://own-read.example", "wss://own-write.example"]
3457            .map(String::from)
3458            .into();
3459        let needed = ["wss://other.example".to_string()].into_iter().collect();
3460        prune_relays(&client, &candidates, &needed).await;
3461
3462        let mut left: Vec<String> = client.relays().all().await.keys().map(|u| u.to_string().trim_end_matches('/').to_string()).collect();
3463        left.sort();
3464        assert_eq!(left, ["wss://nos.lol", "wss://other.example", "wss://own-read.example", "wss://own-write.example"]);
3465    }
3466
3467    // ── Ready gate (community publish while the chosen network still connects) ──
3468    // The live gate, `wait_transport_ready`, over the real transport state: a network installed
3469    // by hand stands in for Tor, so no live Tor is needed.
3470
3471    /// A network that is up or not as the test says, and dials nothing.
3472    struct Gate(std::sync::atomic::AtomicBool);
3473
3474    #[async_trait::async_trait]
3475    impl crate::transport::Transport for Gate {
3476        fn kind(&self) -> crate::transport::Kind {
3477            crate::transport::Kind::Tor
3478        }
3479        fn route(&self, dest: &crate::transport::Dest, port: u16, ctx: &crate::transport::RouteCtx) -> crate::transport::Route {
3480            crate::transport::route::route_tor(dest, port, ctx)
3481        }
3482        async fn dial(
3483            &self,
3484            _: &crate::transport::Route,
3485            _: crate::transport::Lane,
3486        ) -> Result<(crate::transport::BoxedStream, crate::transport::Dialed), crate::transport::ConnectError> {
3487            Err(crate::transport::ConnectError::Unreachable("gate".into()))
3488        }
3489        fn ready(&self) -> bool {
3490            self.0.load(std::sync::atomic::Ordering::SeqCst)
3491        }
3492        fn kind_status(&self) -> crate::transport::status::KindStatus {
3493            crate::transport::status::KindStatus::ready(serde_json::Value::Null)
3494        }
3495        async fn new_identity(&self) {}
3496        async fn shutdown(&self) {}
3497        fn into_any(self: std::sync::Arc<Self>) -> std::sync::Arc<dyn std::any::Any + Send + Sync> {
3498            self
3499        }
3500    }
3501
3502    #[test]
3503    fn an_auth_record_stands_three_days_is_refreshed_daily_and_one_without_a_time_never_counts() {
3504        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3505        crate::db::close_database();
3506        crate::db::clear_id_caches();
3507        use nostr_sdk::prelude::ToBech32;
3508        let tmp = tempfile::tempdir().unwrap();
3509        let account = Keys::generate().public_key().to_bech32().unwrap();
3510        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
3511        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
3512        crate::db::set_current_account(account.clone()).unwrap();
3513        crate::db::init_database(&account).unwrap();
3514
3515        let url = "wss://gate.example/nostr";
3516        let set = |at: String| crate::db::set_sql_setting(super::auth_gate_setting(url), at).unwrap();
3517        let ago = |secs: u64| (super::now_secs() - secs).to_string();
3518        assert!(!super::auth_gate_live(url));
3519        set("1".into());
3520        assert!(!super::auth_gate_live(url), "a record from before the TTL says nothing of today");
3521        super::note_auth_gate(url);
3522        assert!(super::auth_gate_live(url));
3523        set(ago(super::AUTH_GATE_TTL_SECS - 60));
3524        assert!(super::auth_gate_live(url));
3525        set(ago(super::AUTH_GATE_TTL_SECS + 1));
3526        assert!(!super::auth_gate_live(url), "a relay that stopped asking is read openly again");
3527
3528        set(ago(3600));
3529        super::note_auth_gate(url);
3530        assert_eq!(super::auth_gate_at(url), Some(super::now_secs() - 3600), "no rewrite within a day");
3531        set(ago(super::AUTH_GATE_REFRESH_SECS + 1));
3532        super::note_auth_gate(url);
3533        assert!(super::auth_gate_at(url).is_some_and(|at| super::now_secs() - at < 5), "a day on, a challenge refreshes it");
3534    }
3535
3536    /// Holds the process-wide network for one test and puts Clearnet back however it ends.
3537    struct GateScene(#[allow(dead_code)] std::sync::MutexGuard<'static, ()>);
3538
3539    impl GateScene {
3540        fn new() -> Self {
3541            let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
3542            drop(crate::transport::host::uninstall());
3543            GateScene(guard)
3544        }
3545    }
3546
3547    impl Drop for GateScene {
3548        fn drop(&mut self) {
3549            drop(crate::transport::host::uninstall());
3550            crate::transport::budget::clear_overrides_for_test();
3551            crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
3552        }
3553    }
3554
3555    #[tokio::test]
3556    #[allow(clippy::await_holding_lock)]
3557    async fn ready_gate_passes_at_once_when_nothing_holds_traffic() {
3558        let _s = GateScene::new();
3559        crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
3560        let start = web_time::Instant::now();
3561        assert!(wait_transport_ready().await.is_ok());
3562        crate::transport::set_preference(Some(crate::transport::Kind::Tor));
3563        let gate = std::sync::Arc::new(Gate(std::sync::atomic::AtomicBool::new(true)));
3564        crate::transport::host::activate(gate, crate::db::live_session_id(), false).unwrap();
3565        assert!(wait_transport_ready().await.is_ok());
3566        assert!(start.elapsed() < std::time::Duration::from_millis(500), "must not wait while ready");
3567    }
3568
3569    #[tokio::test]
3570    #[allow(clippy::await_holding_lock)]
3571    async fn ready_gate_errors_honestly_after_its_window() {
3572        // Without the gate a send failed at once with a misleading "no relay accepted"; with
3573        // it, it waits the window and then names the cause.
3574        let _s = GateScene::new();
3575        crate::transport::budget::override_for_test(crate::transport::Op::ReadyWait, Some(std::time::Duration::from_millis(300)));
3576        crate::transport::set_preference(Some(crate::transport::Kind::Tor));
3577        let gate = std::sync::Arc::new(Gate(std::sync::atomic::AtomicBool::new(false)));
3578        crate::transport::host::activate(gate, crate::db::live_session_id(), false).unwrap();
3579        let start = web_time::Instant::now();
3580        let err = wait_transport_ready().await.expect_err("Tor never comes up");
3581        assert_eq!(err, "Tor is still connecting. Wait a moment and try again.");
3582        let took = start.elapsed();
3583        assert!(took >= std::time::Duration::from_millis(300) && took < std::time::Duration::from_millis(1500), "{took:?}");
3584
3585        // A network this build lacks never comes: no wait, and its own words.
3586        if !crate::transport::Kind::Tor.compiled() {
3587            drop(crate::transport::host::uninstall());
3588            let start = web_time::Instant::now();
3589            assert_eq!(wait_transport_ready().await.unwrap_err(), "This build doesn't include Tor.");
3590            assert!(start.elapsed() < std::time::Duration::from_millis(100));
3591        }
3592    }
3593
3594    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3595    #[allow(clippy::await_holding_lock)]
3596    async fn ready_gate_passes_once_the_network_comes_up_mid_wait() {
3597        let _s = GateScene::new();
3598        crate::transport::budget::override_for_test(crate::transport::Op::ReadyWait, Some(std::time::Duration::from_secs(10)));
3599        crate::transport::set_preference(Some(crate::transport::Kind::Tor));
3600        let gate = std::sync::Arc::new(Gate(std::sync::atomic::AtomicBool::new(false)));
3601        let inst = crate::transport::host::activate(gate.clone(), crate::db::live_session_id(), false).unwrap();
3602        let id = inst.id();
3603        let up = tokio::spawn(async move {
3604            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
3605            gate.0.store(true, std::sync::atomic::Ordering::SeqCst);
3606            crate::transport::host::notify(crate::transport::host::TransportEvent::Ready {
3607                kind: crate::transport::Kind::Tor,
3608                instance: id,
3609                owner: crate::db::live_session_id(),
3610                recovered: false,
3611            });
3612        });
3613        let start = web_time::Instant::now();
3614        assert!(wait_transport_ready().await.is_ok(), "passes once the network is up");
3615        assert!(start.elapsed() < std::time::Duration::from_secs(2), "woken by the change, not the window");
3616        up.await.unwrap();
3617    }
3618
3619    fn evt(kind: u16, z: &str) -> Event {
3620        EventBuilder::new(Kind::Custom(kind), "x")
3621            .tags([Tag::custom(
3622                "z",
3623                [z.to_string()],
3624            )])
3625            .finalize(&Keys::generate())
3626            .unwrap()
3627    }
3628
3629    #[test]
3630    fn query_matches_kind_and_z() {
3631        let e = evt(3300, "abc");
3632        assert!(Query { kinds: vec![3300], z_tags: vec!["abc".into()], since: None, ..Default::default() }.matches(&e));
3633        assert!(!Query { kinds: vec![3301], ..Default::default() }.matches(&e));
3634        assert!(!Query { kinds: vec![], z_tags: vec!["xyz".into()], since: None, ..Default::default() }.matches(&e));
3635        assert!(Query::default().matches(&e), "empty query matches anything");
3636    }
3637
3638    fn evt_at(kind: u16, secs: u64) -> Event {
3639        EventBuilder::new(Kind::Custom(kind), "x")
3640            .custom_created_at(Timestamp::from(secs))
3641            .finalize(&Keys::generate())
3642            .unwrap()
3643    }
3644
3645    /// Build a z-tagged event at a controlled created_at (for deterministic paging tests —
3646    /// the real outer events carry wall-clock send time).
3647    fn evt_z_at(kind: u16, z: &str, secs: u64) -> Event {
3648        EventBuilder::new(Kind::Custom(kind), "x")
3649            .custom_created_at(Timestamp::from(secs))
3650            .tags([Tag::custom(
3651                "z",
3652                [z.to_string()],
3653            )])
3654            .finalize(&Keys::generate())
3655            .unwrap()
3656    }
3657
3658    #[tokio::test]
3659    async fn fetch_pages_with_until_and_limit_newest_first() {
3660        // The Discord-style paging mechanism: `limit` caps newest-first; `until` walks older.
3661        let relay = super::memory::MemoryRelay::new();
3662        let relays = vec!["r1".to_string()];
3663        for s in 1..=5u64 {
3664            relay.inject(&evt_z_at(3300, "pg", s), &relays);
3665        }
3666        let secs = |evs: &[Event]| evs.iter().map(|e| e.created_at.as_secs()).collect::<Vec<_>>();
3667
3668        // Latest page: the two newest (secs 5, 4), newest-first.
3669        let latest = relay
3670            .fetch(&Query { kinds: vec![3300], z_tags: vec!["pg".into()], limit: Some(2), ..Default::default() }, &relays)
3671            .await
3672            .unwrap();
3673        assert_eq!(secs(&latest), vec![5, 4]);
3674
3675        // Older page before the cursor (until=3, inclusive): secs 3, 2.
3676        let older = relay
3677            .fetch(&Query { kinds: vec![3300], z_tags: vec!["pg".into()], until: Some(3), limit: Some(2), ..Default::default() }, &relays)
3678            .await
3679            .unwrap();
3680        assert_eq!(secs(&older), vec![3, 2]);
3681
3682        // Start of history: until=1 returns only the single oldest event — the signal the
3683        // caller uses to mark "no more older" and stop hitting the network.
3684        let start = relay
3685            .fetch(&Query { kinds: vec![3300], z_tags: vec!["pg".into()], until: Some(1), limit: Some(2), ..Default::default() }, &relays)
3686            .await
3687            .unwrap();
3688        assert_eq!(secs(&start), vec![1]);
3689    }
3690
3691    // ── A page read from several relays ───────────────────────────────────────
3692
3693    fn page_of(secs: &[u64]) -> Vec<Event> {
3694        secs.iter().map(|s| evt_at(3300, *s)).collect()
3695    }
3696
3697    fn paged(limit: usize, until: Option<u64>) -> Query {
3698        Query { kinds: vec![3300], limit: Some(limit), until, paged: true, ..Default::default() }
3699    }
3700
3701    fn secs_of(events: &[Event]) -> Vec<u64> {
3702        let mut secs: Vec<u64> = events.iter().map(|e| e.created_at.as_secs()).collect();
3703        secs.sort_unstable_by(|a, b| b.cmp(a));
3704        secs
3705    }
3706
3707    #[test]
3708    fn a_page_is_cut_where_the_shallowest_full_answer_ended() {
3709        let mut floor = PageFloor::of(&paged(3, None)).unwrap();
3710        floor.note(&page_of(&[10, 9, 8]));
3711        floor.note(&page_of(&[10, 9, 3]));
3712        let mut union = page_of(&[10, 9, 8, 3]);
3713        floor.cut(&mut union);
3714        assert_eq!(secs_of(&union), vec![10, 9, 8], "below 8 the first relay hasn't been asked");
3715    }
3716
3717    #[test]
3718    fn a_short_answer_cuts_nothing() {
3719        let mut floor = PageFloor::of(&paged(3, None)).unwrap();
3720        floor.note(&page_of(&[10, 9]));
3721        let mut union = page_of(&[10, 9]);
3722        floor.cut(&mut union);
3723        assert_eq!(secs_of(&union), vec![10, 9]);
3724        floor.note(&page_of(&[10, 7, 5]));
3725        let mut union = page_of(&[10, 9, 7, 5]);
3726        floor.cut(&mut union);
3727        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");
3728    }
3729
3730    #[test]
3731    fn a_full_answer_no_deeper_than_it_was_asked_from_cuts_nothing() {
3732        let mut floor = PageFloor::of(&paged(3, Some(8))).unwrap();
3733        floor.note(&page_of(&[8, 8, 8]));
3734        floor.note(&page_of(&[8, 5, 4]));
3735        let mut union = page_of(&[8, 8, 8, 8, 5, 4]);
3736        floor.cut(&mut union);
3737        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");
3738    }
3739
3740    #[test]
3741    fn only_a_paged_query_with_a_limit_is_cut() {
3742        assert!(PageFloor::of(&Query { limit: Some(3), ..Default::default() }).is_none());
3743        assert!(PageFloor::of(&Query { paged: true, ..Default::default() }).is_none());
3744        assert!(PageFloor::of(&Query { paged: true, limit: Some(0), ..Default::default() }).is_none());
3745    }
3746
3747    /// A plane walked to its end as the pagers walk one: inclusive `until`, on from the oldest
3748    /// event the page gave.
3749    async fn walk<T: Transport>(transport: &T, relays: &[String], mut query: Query) -> Vec<u64> {
3750        let mut seen = std::collections::HashSet::new();
3751        let mut read = Vec::new();
3752        let mut oldest: Option<u64> = None;
3753        for _ in 0..64 {
3754            query.until = oldest;
3755            let page = transport.fetch(&query, relays).await.unwrap();
3756            let fresh: Vec<u64> = page.iter().filter(|e| seen.insert(e.id)).map(|e| e.created_at.as_secs()).collect();
3757            if fresh.is_empty() {
3758                break;
3759            }
3760            oldest = oldest.into_iter().chain(fresh.iter().copied()).min();
3761            read.extend(fresh);
3762        }
3763        read.sort_unstable();
3764        read
3765    }
3766
3767    /// Events at seconds 1 to 10 on `full`, and on `sparse` all but 4 to 8.
3768    fn differing(mut hold: impl FnMut(&Event, bool)) {
3769        for s in 1..=10u64 {
3770            hold(&evt_at(3300, s), !(4..=8).contains(&s));
3771        }
3772    }
3773
3774    #[tokio::test]
3775    async fn a_walk_over_relays_that_hold_different_amounts_reads_every_event() {
3776        let relay = super::memory::MemoryRelay::new();
3777        let both = ["wss://full".to_string(), "wss://sparse".to_string()];
3778        differing(|e, on_sparse| {
3779            relay.inject(e, &both[..1]);
3780            if on_sparse {
3781                relay.inject(e, &both[1..]);
3782            }
3783        });
3784        assert_eq!(walk(&relay, &both, paged(3, None)).await, (1..=10).collect::<Vec<_>>());
3785        // Unpaged, every relay's newest page comes back whole: the sparse one's reaches down to
3786        // 3, and a walk going on from there never asks the full one for 4 to 7.
3787        let unpaged = Query { paged: false, ..paged(3, None) };
3788        assert_eq!(walk(&relay, &both, unpaged).await, vec![1, 2, 3, 8, 9, 10]);
3789    }
3790
3791    fn plane_wraps(plane: &Keys, secs: impl IntoIterator<Item = u64>) -> Vec<Event> {
3792        use nostr_sdk::prelude::FinalizeEvent;
3793        secs.into_iter()
3794            .map(|s| EventBuilder::new(Kind::Custom(crate::community::v2::stream::KIND_WRAP), "sealed").custom_created_at(Timestamp::from(s)).finalize(plane).unwrap())
3795            .collect()
3796    }
3797
3798    /// A plane's wraps at seconds 1 to 10 on one relay, and all but 4 to 8 on another.
3799    async fn differing_wire(plane: &Keys) -> (wire::WireRelay, wire::WireRelay) {
3800        let (full, sparse) = (wire::WireRelay::start().await, wire::WireRelay::start().await);
3801        let wraps = plane_wraps(plane, 1..=10);
3802        sparse.hold(wraps.iter().filter(|w| !(4..=8).contains(&w.created_at.as_secs())).cloned());
3803        full.hold(wraps);
3804        (full, sparse)
3805    }
3806
3807    fn plane_page(plane: &Keys) -> Query {
3808        Query { kinds: vec![crate::community::v2::stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], limit: Some(3), paged: true, ..Default::default() }
3809    }
3810
3811    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3812    #[allow(clippy::await_holding_lock)]
3813    async fn a_paged_plane_read_stops_where_the_shallowest_relay_did() {
3814        let _s = GateScene::new();
3815        let plane = Keys::generate();
3816        let (full, sparse) = differing_wire(&plane).await;
3817        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(5));
3818        let read = live.fetch_plane(&plane, &plane_page(&plane), &[full.url(), sparse.url()]).await.unwrap();
3819        assert_eq!(secs_of(&read.events), vec![10, 9, 8]);
3820        assert!(read.is_complete());
3821    }
3822
3823    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3824    #[allow(clippy::await_holding_lock)]
3825    async fn a_paged_plane_read_over_authed_connections_stops_there_too() {
3826        let _s = GateScene::new();
3827        let plane = Keys::generate();
3828        let (full, sparse) = differing_wire(&plane).await;
3829        full.gate(true);
3830        sparse.gate(true);
3831        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(5));
3832        let urls = [full.url(), sparse.url()];
3833        let learning = live.fetch_plane(&plane, &plane_page(&plane), &urls).await.unwrap();
3834        assert_eq!(secs_of(&learning.events), vec![10, 9, 8], "the read that learns both relays gate");
3835        assert_eq!((gate_of(&full), gate_of(&sparse)), (Some(RelayGate::Auth), Some(RelayGate::Auth)));
3836        let knowing = live.fetch_plane(&plane, &plane_page(&plane), &urls).await.unwrap();
3837        assert_eq!(secs_of(&knowing.events), vec![10, 9, 8], "and the next, which knows");
3838    }
3839
3840    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
3841    #[allow(clippy::await_holding_lock)]
3842    async fn a_paged_fetch_stops_where_the_shallowest_relay_did() {
3843        let _s = GateScene::new();
3844        let plane = Keys::generate();
3845        let (full, sparse) = differing_wire(&plane).await;
3846        crate::state::set_nostr_client(crate::nostr_client_builder().build());
3847        let live = LiveTransport::with_timeout(std::time::Duration::from_secs(5));
3848        let urls = [full.url(), sparse.url()];
3849        let read = live.fetch(&Query { evidence: Evidence::Full, ..plane_page(&plane) }, &urls).await;
3850        let walked = walk(&live, &urls, Query { evidence: Evidence::Full, ..plane_page(&plane) }).await;
3851        let _ = crate::state::take_nostr_client();
3852        assert_eq!(secs_of(&read.unwrap()), vec![10, 9, 8]);
3853        assert_eq!(walked, (1..=10).collect::<Vec<_>>());
3854    }
3855
3856    #[test]
3857    fn to_filter_translates_kinds_z_and_since() {
3858        // The live/test-parity claim rests on to_filter matching matches(); assert
3859        // the Filter directly. An event the Query matches must also pass the Filter.
3860        let q = Query { kinds: vec![3300], z_tags: vec!["abc".into()], since: Some(100), ..Default::default() };
3861        let filter = q.to_filter();
3862        let matching = EventBuilder::new(Kind::Custom(3300), "x")
3863            .custom_created_at(Timestamp::from(150))
3864            .tags([Tag::custom(
3865                "z",
3866                ["abc".to_string()],
3867            )])
3868            .finalize(&Keys::generate())
3869            .unwrap();
3870        assert!(filter.match_event(&matching, MatchEventOptions::new()), "to_filter must accept what matches() accepts");
3871        assert!(q.matches(&matching));
3872
3873        // Wrong kind, wrong z, and too-early all rejected by the same Filter.
3874        let wrong_kind = EventBuilder::new(Kind::Custom(3301), "x")
3875            .custom_created_at(Timestamp::from(150))
3876            .tags([Tag::custom(
3877                "z",
3878                ["abc".to_string()],
3879            )])
3880            .finalize(&Keys::generate())
3881            .unwrap();
3882        assert!(!filter.match_event(&wrong_kind, MatchEventOptions::new()));
3883    }
3884
3885    /// Build an event carrying one arbitrary single-letter tag (recipient `p`, wrapped-kind `k`).
3886    fn evt_sl(kind: u16, letter: SingleLetterTag, value: &str) -> Event {
3887        EventBuilder::new(Kind::Custom(kind), "x")
3888            .tags([Tag::custom(
3889                letter.as_char().to_string(),
3890                [value.to_string()],
3891            )])
3892            .finalize(&Keys::generate())
3893            .unwrap()
3894    }
3895
3896    #[test]
3897    fn to_filter_and_matches_agree_on_authors() {
3898        let keys = Keys::generate();
3899        let e = EventBuilder::new(Kind::Custom(1059), "x").finalize(&keys).unwrap();
3900        let q = Query { kinds: vec![1059], authors: vec![keys.public_key().to_hex()], ..Default::default() };
3901        assert!(q.matches(&e));
3902        assert!(q.to_filter().match_event(&e, MatchEventOptions::new()));
3903        let miss = Query { kinds: vec![1059], authors: vec![Keys::generate().public_key().to_hex()], ..Default::default() };
3904        assert!(!miss.matches(&e));
3905        assert!(!miss.to_filter().match_event(&e, MatchEventOptions::new()));
3906    }
3907
3908    #[test]
3909    fn to_filter_and_matches_agree_on_p_tags() {
3910        let recipient = Keys::generate().public_key().to_hex();
3911        let e = evt_sl(1059, SingleLetterTag::LOWERCASE_P, &recipient);
3912        let q = Query { kinds: vec![1059], p_tags: vec![recipient], ..Default::default() };
3913        assert!(q.matches(&e));
3914        assert!(q.to_filter().match_event(&e, MatchEventOptions::new()));
3915        let miss = Query { kinds: vec![1059], p_tags: vec![Keys::generate().public_key().to_hex()], ..Default::default() };
3916        assert!(!miss.matches(&e));
3917        assert!(!miss.to_filter().match_event(&e, MatchEventOptions::new()));
3918    }
3919
3920    #[test]
3921    fn to_filter_and_matches_agree_on_k_tags() {
3922        let e = evt_sl(1059, SingleLetterTag::LOWERCASE_K, "3311");
3923        let q = Query { kinds: vec![1059], k_tags: vec!["3311".into()], ..Default::default() };
3924        assert!(q.matches(&e));
3925        assert!(q.to_filter().match_event(&e, MatchEventOptions::new()));
3926        let miss = Query { kinds: vec![1059], k_tags: vec!["3300".into()], ..Default::default() };
3927        assert!(!miss.matches(&e));
3928        assert!(!miss.to_filter().match_event(&e, MatchEventOptions::new()));
3929    }
3930
3931    #[test]
3932    fn to_filter_empty_kinds_only_constrains_z_and_since() {
3933        // Empty kinds = no kind constraint, matching matches()' behavior.
3934        let q = Query { kinds: vec![], z_tags: vec!["p".into()], since: None, ..Default::default() };
3935        let filter = q.to_filter();
3936        let e = evt(3300, "p");
3937        assert!(filter.match_event(&e, MatchEventOptions::new()));
3938        assert!(q.matches(&e));
3939    }
3940
3941    #[test]
3942    fn since_is_an_inclusive_lower_bound() {
3943        let below = evt_at(3300, 99);
3944        let exact = evt_at(3300, 100);
3945        let above = evt_at(3300, 101);
3946        let q = Query { kinds: vec![3300], z_tags: vec![], since: Some(100), ..Default::default() };
3947        assert!(!q.matches(&below), "below the floor is excluded");
3948        assert!(q.matches(&exact), "exactly the floor is included");
3949        assert!(q.matches(&above), "above the floor is included");
3950    }
3951
3952    #[test]
3953    fn z_tags_match_as_or_set() {
3954        // The whole-channel fetch lists multiple epoch pseudonyms; an event
3955        // tagged with any one of them must match.
3956        let e = evt(3300, "p2");
3957        let q = Query { kinds: vec![3300], z_tags: vec!["p1".into(), "p2".into()], since: None, ..Default::default() };
3958        assert!(q.matches(&e));
3959        let miss = Query { kinds: vec![3300], z_tags: vec!["p1".into(), "p3".into()], since: None, ..Default::default() };
3960        assert!(!miss.matches(&e));
3961    }
3962
3963    #[tokio::test]
3964    async fn fetch_unions_and_dedups_across_relays() {
3965        use super::memory::MemoryRelay;
3966        let relay = MemoryRelay::new();
3967        let relays = vec!["r1".to_string(), "r2".to_string(), "r3".to_string()];
3968        let e = evt(3300, "p");
3969        relay.publish(&e, &relays).await.unwrap();
3970        let got = relay
3971            .fetch(&Query { kinds: vec![3300], z_tags: vec!["p".into()], since: None, ..Default::default() }, &relays)
3972            .await
3973            .unwrap();
3974        assert_eq!(got.len(), 1, "same event on 3 relays dedups to 1");
3975    }
3976
3977    #[tokio::test]
3978    async fn durable_broadcast_retries_only_the_failing_relays_until_they_ack() {
3979        // r1/r3 ACK on round 1; r2 fails the first 4 rounds then ACKs. The engine must keep re-sending
3980        // ONLY r2 (not the already-ACKed r1/r3) until it lands, and succeed.
3981        use std::cell::Cell;
3982        let relays = vec!["r1".to_string(), "r2".to_string(), "r3".to_string()];
3983        let round = Cell::new(0usize);
3984        let r2_round_seen = Cell::new(0usize);
3985        let res = durable_broadcast(&relays, 30, std::time::Duration::ZERO, |pending| {
3986            let n = round.get();
3987            round.set(n + 1);
3988            // r2 is only ever retried alone after round 1 — assert we never re-send a relay that ACKed.
3989            if n >= 1 {
3990                assert_eq!(pending, vec!["r2".to_string()], "only the failing relay is retried");
3991                r2_round_seen.set(r2_round_seen.get() + 1);
3992            }
3993            Box::pin(async move {
3994                pending.into_iter().filter(|r| r != "r2" || n >= 4).collect()
3995            })
3996        })
3997        .await;
3998        assert!(res.is_ok(), "all relays eventually ACK → Ok");
3999        assert!(round.get() >= 5, "kept retrying r2 across rounds");
4000    }
4001
4002    #[tokio::test]
4003    async fn durable_broadcast_is_ok_if_some_ack_even_when_one_never_does() {
4004        // r1 ACKs; r2 never does. After exhausting r2's retries, the event is still durably out (r1 has
4005        // it, fetch-union covers r2), so the result is Ok — durability is best-effort per relay.
4006        let relays = vec!["r1".to_string(), "r2".to_string()];
4007        let res = durable_broadcast(&relays, 5, std::time::Duration::ZERO, |pending| {
4008            Box::pin(async move { pending.into_iter().filter(|r| r == "r1").collect() })
4009        })
4010        .await;
4011        assert!(res.is_ok(), "≥1 relay accepted → Ok despite a permanently-failing relay");
4012    }
4013
4014    #[tokio::test]
4015    async fn durable_broadcast_errs_only_if_zero_relays_ever_accept() {
4016        let relays = vec!["r1".to_string(), "r2".to_string()];
4017        let res = durable_broadcast(&relays, 5, std::time::Duration::ZERO, |_pending| {
4018            Box::pin(async move { Vec::new() }) // nobody ever ACKs
4019        })
4020        .await;
4021        assert!(res.is_err(), "zero acceptances after the retry cap → Err");
4022    }
4023
4024    #[tokio::test]
4025    async fn redundancy_self_heals_a_missing_relay() {
4026        use super::memory::MemoryRelay;
4027        let relay = MemoryRelay::new();
4028        let all = vec!["r1".to_string(), "r2".to_string(), "r3".to_string()];
4029        let e = evt(3300, "p");
4030        // Event lands on ONLY r2 (the others "missed" it).
4031        relay.inject(&e, &["r2".to_string()]);
4032        assert_eq!(relay.count_on("r1"), 0);
4033        assert_eq!(relay.count_on("r2"), 1);
4034        // A fetch across the full set still finds it (redundancy).
4035        let got = relay.fetch(&Query { kinds: vec![3300], ..Default::default() }, &all).await.unwrap();
4036        assert_eq!(got.len(), 1);
4037    }
4038
4039    #[tokio::test]
4040    async fn ephemeral_kind_streams_live_but_is_never_stored_or_fetched() {
4041        use super::memory::MemoryRelay;
4042        let relay = MemoryRelay::new();
4043        let relays = vec!["r1".to_string()];
4044        let mut sub = relay.subscribe(Query { kinds: vec![21059], ..Default::default() });
4045        let e = evt(21059, "p");
4046        relay.publish(&e, &relays).await.unwrap();
4047        assert_eq!(relay.count_on("r1"), 0, "ephemeral is never stored");
4048        let got = relay
4049            .fetch(&Query { kinds: vec![21059], ..Default::default() }, &relays)
4050            .await
4051            .unwrap();
4052        assert!(got.is_empty(), "a real relay never serves an ephemeral from a fetch");
4053        assert_eq!(sub.try_recv().unwrap().id, e.id, "but a live subscriber receives it");
4054    }
4055
4056    #[tokio::test]
4057    async fn stored_kind_is_fetchable_and_delivered_live() {
4058        use super::memory::MemoryRelay;
4059        let relay = MemoryRelay::new();
4060        let relays = vec!["r1".to_string()];
4061        let mut sub = relay.subscribe(Query { kinds: vec![1059], ..Default::default() });
4062        let e = evt(1059, "p");
4063        relay.publish(&e, &relays).await.unwrap();
4064        let got = relay
4065            .fetch(&Query { kinds: vec![1059], ..Default::default() }, &relays)
4066            .await
4067            .unwrap();
4068        assert_eq!(got.len(), 1, "stored kind is fetchable");
4069        assert_eq!(sub.try_recv().unwrap().id, e.id, "and delivered to the live subscriber");
4070    }
4071
4072    #[tokio::test]
4073    async fn p_tags_route_a_giftwrap_to_the_matching_subscriber() {
4074        use super::memory::MemoryRelay;
4075        let relay = MemoryRelay::new();
4076        let relays = vec!["r1".to_string()];
4077        let alice = Keys::generate().public_key().to_hex();
4078        let bob = Keys::generate().public_key().to_hex();
4079        let mut sub_alice =
4080            relay.subscribe(Query { kinds: vec![1059], p_tags: vec![alice.clone()], ..Default::default() });
4081        let mut sub_bob =
4082            relay.subscribe(Query { kinds: vec![1059], p_tags: vec![bob.clone()], ..Default::default() });
4083        let wrap = evt_sl(1059, SingleLetterTag::LOWERCASE_P, &alice);
4084        relay.publish(&wrap, &relays).await.unwrap();
4085        assert_eq!(sub_alice.try_recv().unwrap().id, wrap.id, "addressed recipient gets it live");
4086        assert!(sub_bob.try_recv().is_err(), "a differently-addressed subscriber does not");
4087        // Fetch agrees with the live routing.
4088        let for_alice = relay
4089            .fetch(&Query { kinds: vec![1059], p_tags: vec![alice], ..Default::default() }, &relays)
4090            .await
4091            .unwrap();
4092        assert_eq!(for_alice.len(), 1);
4093        let for_bob = relay
4094            .fetch(&Query { kinds: vec![1059], p_tags: vec![bob], ..Default::default() }, &relays)
4095            .await
4096            .unwrap();
4097        assert!(for_bob.is_empty());
4098    }
4099
4100    // ── UnionPlan: the evidence tiers' return-timing math ────────────────────
4101
4102    #[test]
4103    fn union_plan_fast_satisfied_on_first_success() {
4104        let mut p = UnionPlan::new(Evidence::Fast, 4);
4105        p.record(false);
4106        assert!(!p.satisfied(), "a failure is not evidence");
4107        p.record(true);
4108        assert!(p.satisfied(), "one genuine EOSE satisfies Fast");
4109        assert!(!p.exhausted());
4110    }
4111
4112    #[test]
4113    fn union_plan_quorum_majority_math() {
4114        // (attempted, successes needed): majority = attempted/2 + 1
4115        for (n, need) in [(2usize, 2usize), (3, 2), (4, 3), (5, 3)] {
4116            let mut p = UnionPlan::new(Evidence::Quorum, n);
4117            for _ in 0..need - 1 {
4118                p.record(true);
4119            }
4120            assert!(!p.satisfied(), "{}/{} must not satisfy quorum", need - 1, n);
4121            p.record(true);
4122            assert!(p.satisfied(), "{}/{} satisfies quorum", need, n);
4123        }
4124    }
4125
4126    #[test]
4127    fn union_plan_quorum_failures_never_substitute_for_successes() {
4128        let mut p = UnionPlan::new(Evidence::Quorum, 3);
4129        p.record(true);
4130        p.record(false);
4131        p.record(false);
4132        assert!(!p.satisfied(), "1 success + 2 failures is not a majority");
4133        assert!(p.exhausted(), "all resolved — the degraded path returns best-effort");
4134        assert_eq!(p.successes(), 1);
4135    }
4136
4137    #[test]
4138    fn union_plan_full_requires_every_relay_resolved() {
4139        let mut p = UnionPlan::new(Evidence::Full, 3);
4140        p.record(true);
4141        p.record(true);
4142        assert!(!p.satisfied(), "Full waits for the last relay even after 2 EOSEs");
4143        p.record(false);
4144        assert!(p.satisfied(), "a timeout is a resolution — Full is done");
4145        assert!(p.exhausted());
4146    }
4147
4148    #[test]
4149    fn union_plan_all_dead_is_reportable_not_a_confident_empty() {
4150        let mut p = UnionPlan::new(Evidence::Quorum, 2);
4151        p.record(false);
4152        p.record(false);
4153        assert!(p.exhausted());
4154        assert_eq!(p.successes(), 0, "the caller must map this to Err, never Ok(vec![])");
4155    }
4156
4157    // ── Circuit breaker: trip/reset rules ────────────────────────────────────
4158    // Pinned generation + unique urls per test: the breaker is one global map,
4159    // and other tests bump the REAL session generation concurrently (which
4160    // would wipe it mid-assertion via the production accessors).
4161
4162    const BREAKER_TEST_GEN: u64 = u64::MAX;
4163
4164    #[test]
4165    fn breaker_trips_only_after_consecutive_full_budget_failures() {
4166        let url = "wss://breaker-test-full-budget.example";
4167        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4168        assert!(!breaker_tripped_at(BREAKER_TEST_GEN, url), "one failure is below the threshold");
4169        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4170        assert!(breaker_tripped_at(BREAKER_TEST_GEN, url), "two consecutive full-budget failures trip");
4171    }
4172
4173    #[test]
4174    fn breaker_demoted_budget_failures_never_count() {
4175        let url = "wss://breaker-test-demoted.example";
4176        breaker_record_at(BREAKER_TEST_GEN, url, false, false);
4177        breaker_record_at(BREAKER_TEST_GEN, url, false, false);
4178        breaker_record_at(BREAKER_TEST_GEN, url, false, false);
4179        assert!(
4180            !breaker_tripped_at(BREAKER_TEST_GEN, url),
4181            "demoted-budget failures must not trip (anti-starvation: the post-cooldown probe must stay reachable)"
4182        );
4183    }
4184
4185    #[test]
4186    fn breaker_success_resets_the_entry() {
4187        let url = "wss://breaker-test-reset.example";
4188        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4189        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4190        assert!(breaker_tripped_at(BREAKER_TEST_GEN, url));
4191        // A late EOSE (e.g. via the background drain) proves slow ≠ dead.
4192        breaker_record_at(BREAKER_TEST_GEN, url, true, false);
4193        assert!(!breaker_tripped_at(BREAKER_TEST_GEN, url), "any success unconditionally resets");
4194        breaker_record_at(BREAKER_TEST_GEN, url, false, true);
4195        assert!(!breaker_tripped_at(BREAKER_TEST_GEN, url), "and the failure count restarted from zero");
4196    }
4197
4198    // ── The evidence floor ───────────────────────────────────────────────────
4199
4200    #[test]
4201    fn declared_evidence_stands_and_default_is_quorum() {
4202        assert_eq!(Query::default().evidence, Evidence::Quorum, "unclassified sites get Quorum");
4203        assert_eq!(
4204            effective_evidence(&Query { until: Some(1), evidence: Evidence::Fast, ..Default::default() }),
4205            Evidence::Fast,
4206            "chat pagination rides its declared tier — absence verdicts request Full themselves"
4207        );
4208        assert_eq!(
4209            effective_evidence(&Query { evidence: Evidence::Fast, ..Default::default() }),
4210            Evidence::Fast,
4211            "without `until` the declared tier stands"
4212        );
4213    }
4214}