Skip to main content

vector_core/community/v2/
volley.rs

1//! Chat-plane volley — the boot paint pass (CONCORD_CHAT_PLANE_VOLLEY_DESIGN.md).
2//!
3//! Paints every channel's CURRENT-epoch chat plane from stored state in a few
4//! batched multi-filter REQs on the shared warm community client. No per-plane
5//! clients, no NIP-42 warmups, no dial storms: a cold `fetch_plane` per plane
6//! pays a connect + per-relay warmup gauntlet, which is how a 47-channel boot
7//! became a 36s crawl. Auth-gating relays contribute nothing to a batch (they
8//! CLOSE REQs whose authors aren't the connection's authed key); the planes
9//! also live on the non-gating relays, and anything held ONLY by a gating
10//! relay still arrives via the verification sweep behind this.
11//!
12//! Non-authoritative by design: chat planes carry nothing that needs verifying
13//! before display. The control plane folds AFTER paint and enforces
14//! retroactively (retro-hide revokes a banned member's painted rows). Epochs
15//! rotated while offline make these filters return silence — never lies — and
16//! the rekey walk behind this repaints the channel under its new epoch.
17
18use std::collections::{HashMap, HashSet};
19
20use futures_util::stream::{FuturesUnordered, StreamExt};
21use nostr_sdk::prelude::*;
22
23use crate::community::transport::{Evidence, LiveTransport, Query, Transport};
24use crate::community::v2::derive::{channel_group_key, GroupKey};
25use crate::community::v2::service::FetchedEvent;
26use crate::community::v2::{chat, stream};
27use crate::community::{ChannelId, CommunityId, Epoch};
28use crate::state::{self};
29
30/// One channel to paint. `since` = the chat's last held message (seconds,
31/// minus the caller's slack) so the page carries only genuinely-new wraps.
32pub struct PaintTarget {
33    pub community_id: CommunityId,
34    pub channel_hex: String,
35    pub since: Option<u64>,
36}
37
38/// Filters per REQ — comfortably under every relay's max_filters cap.
39const BATCH_FILTERS: usize = 20;
40
41struct Job {
42    community: CommunityId,
43    channel_hex: String,
44    channel_id: ChannelId,
45    /// The read epoch's group: its conversation key opens every plane of the channel.
46    group: GroupKey,
47    epoch: Epoch,
48    since: Option<u64>,
49    relay_set: usize,
50    /// The address fetched: the read plane's, or a restricted Channel's live writer.
51    address: PublicKey,
52    /// A writer address's epoch, and its keys when this device is a writer.
53    writer: Option<(Epoch, Option<Keys>)>,
54    /// How the Channel's writers' rules judge what it reads, when it keeps a ledger.
55    judge: Option<std::sync::Arc<crate::community::v2::service::Judge>>,
56}
57
58impl Job {
59    /// Open one wrap fetched for this job, holding what its Channel's rules don't stand behind.
60    fn open(&self, wrap: &Event) -> Option<chat::ChatEvent> {
61        if wrap.pubkey != self.address {
62            return None;
63        }
64        let wepoch = self.writer.as_ref().map(|(w, _)| *w);
65        let opened = match wepoch {
66            Some(w) => chat::open_writer_chat_event(wrap, &self.address, w, self.group.conv_key(), &self.channel_id, self.epoch),
67            None => chat::open_chat_event(wrap, &self.group, &self.channel_id, self.epoch),
68        };
69        crate::community::v2::service::judge_arrival(self.judge.as_deref(), &self.community.0, &self.channel_id, wrap, opened.ok()?, wepoch)
70    }
71
72    /// The keys a relay that gates reads must see this connection authenticated as.
73    fn auth_keys(&self) -> Option<Keys> {
74        match &self.writer {
75            Some((_, keys)) => keys.clone(),
76            None => Some(self.group.keys().clone()),
77        }
78    }
79}
80
81/// Learned from live NIP-42 challenges (streamauth records the KV): a gating
82/// relay answers batch REQs with silence no matter what it holds.
83fn relay_auth_gating(url: &str) -> bool {
84    crate::community::transport::auth_gate_live(url)
85}
86
87/// The subset of `relays` currently CONNECTED on the shared client, waiting up
88/// to `allowance` for the first one — cold boots dial these sockets moments
89/// before the volley needs them.
90async fn connected_targets(
91    client: &Client,
92    relays: &[String],
93    allowance: std::time::Duration,
94) -> Vec<String> {
95    let deadline = crate::rt::time::Instant::now() + allowance;
96    loop {
97        let pool = client.relays().await;
98        let up: Vec<String> = relays
99            .iter()
100            .filter(|r| {
101                RelayUrl::parse(r)
102                    .ok()
103                    .and_then(|u| pool.get(&u).map(|rl| rl.status() == RelayStatus::Connected))
104                    .unwrap_or(false)
105            })
106            .cloned()
107            .collect();
108        if !up.is_empty() || crate::rt::time::Instant::now() >= deadline {
109            return up;
110        }
111        crate::rt::time::sleep(std::time::Duration::from_millis(150)).await;
112    }
113}
114
115/// Stage timing + hit counts for the boot log — the volley is a performance
116/// feature, and every regression so far was found by reading these.
117#[derive(Default)]
118pub struct VolleyStats {
119    pub batch_ms: u128,
120    pub fallback_ms: u128,
121    pub batch_events: usize,
122    pub fallback_events: usize,
123}
124
125/// Paint every target's latest page. Returns `(channel_hex, new)` per channel
126/// that gained messages (callers own the logging) plus stage stats.
127pub async fn paint_all(targets: Vec<PaintTarget>) -> (Vec<(String, usize)>, VolleyStats) {
128    crate::db::scoped(async move {
129        let session = crate::db::current_session();
130        let mut stats = VolleyStats::default();
131        let Some(my_pk) = state::my_public_key() else {
132            return (Vec::new(), stats);
133        };
134
135        // Group targets per community: one DB load each, current-epoch planes only.
136        let mut by_community: Vec<(CommunityId, Vec<PaintTarget>)> = Vec::new();
137        for t in targets {
138            match by_community.iter_mut().find(|(id, _)| *id == t.community_id) {
139                Some((_, v)) => v.push(t),
140                None => by_community.push((t.community_id, vec![t])),
141            }
142        }
143
144        let mut relay_sets: Vec<Vec<String>> = Vec::new();
145        let mut jobs: Vec<Job> = Vec::new();
146        let mut plane_index: HashMap<PublicKey, usize> = HashMap::new();
147        for (cid, ts) in by_community {
148            let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
149            if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
150                continue;
151            }
152            let Ok(Some(community)) = crate::db::community::load_community_v2(&cid) else {
153                continue;
154            };
155            let mut sorted = community.relays.clone();
156            sorted.sort();
157            let relay_set = match relay_sets.iter().position(|r| {
158                let mut s = r.clone();
159                s.sort();
160                s == sorted
161            }) {
162                Some(i) => i,
163                None => {
164                    relay_sets.push(community.relays.clone());
165                    relay_sets.len() - 1
166                }
167            };
168            for t in ts {
169                let ch_id = ChannelId(crate::simd::hex::hex_to_bytes_32(&t.channel_hex));
170                let Some(ch) = community.channel(&ch_id) else { continue };
171                // ONE plane per channel, at the MAX HELD epoch: the community
172                // row's epoch fields can lag a rotation the rekey walk already
173                // archived, so "current" means the freshest key the DB holds.
174                // Older epochs stay the history-pagination system's job.
175                let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
176                let (group, epoch) = if ch.private {
177                    let mut best: Option<(crate::community::Epoch, [u8; 32])> =
178                        ch.key.map(|k| (ch.epoch, k));
179                    for (ep, k) in
180                        crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default()
181                    {
182                        // A private plane is never derived from the root value.
183                        if k == community.community_root {
184                            continue;
185                        }
186                        if best.is_none_or(|(be, _)| ep.0 > be.0) {
187                            best = Some((ep, k));
188                        }
189                    }
190                    let Some((ep, key)) = best else { continue };
191                    (channel_group_key(&key, &ch_id, ep), ep)
192                } else {
193                    let mut best = (community.root_epoch, community.community_root);
194                    for (ep, k) in crate::db::community::held_epoch_keys(
195                        &cid_hex,
196                        crate::community::SERVER_ROOT_SCOPE_HEX,
197                    )
198                    .unwrap_or_default()
199                    {
200                        if ep.0 > best.0 .0 {
201                            best = (ep, k);
202                        }
203                    }
204                    (channel_group_key(&best.1, &ch_id, best.0), best.0)
205                };
206                // A duplicated target would orphan the first job (unroutable) and
207                // burn a fallback dial — first derivation wins.
208                if plane_index.contains_key(&group.pk()) {
209                    continue;
210                }
211                let judge = crate::community::v2::service::Judge::of(&community, ch).map(std::sync::Arc::new);
212                let writer = ch.writers.as_ref().and_then(|l| l.current_writer()).and_then(|(we, pk)| PublicKey::from_slice(&pk).ok().map(|a| (we, a)));
213                if let Some((wepoch, address)) = writer.filter(|(_, a)| !plane_index.contains_key(a)) {
214                    let keys = crate::community::v2::service::live_writer_of(&community, ch).filter(|(e, ..)| *e == wepoch).map(|(_, _, g)| g.keys().clone());
215                    plane_index.insert(address, jobs.len());
216                    jobs.push(Job {
217                        community: t.community_id,
218                        channel_hex: t.channel_hex.clone(),
219                        channel_id: ch_id,
220                        group: group.clone(),
221                        epoch,
222                        since: t.since,
223                        relay_set,
224                        address,
225                        writer: Some((wepoch, keys)),
226                        judge: judge.clone(),
227                    });
228                }
229                plane_index.insert(group.pk(), jobs.len());
230                jobs.push(Job {
231                    community: t.community_id,
232                    channel_hex: t.channel_hex,
233                    channel_id: ch_id,
234                    address: group.pk(),
235                    group,
236                    epoch,
237                    since: t.since,
238                    relay_set,
239                    writer: None,
240                    judge,
241                });
242            }
243        }
244        if jobs.is_empty() {
245            return (Vec::new(), stats);
246        }
247
248        // One multi-filter REQ per ≤BATCH_FILTERS jobs per relay, all concurrent,
249        // all on the shared warm client. Callers pass targets recency-first and
250        // job order preserves it, so the hottest channels ride the first batches.
251        let mut by_set: HashMap<usize, Vec<usize>> = HashMap::new();
252        for (i, j) in jobs.iter().enumerate() {
253            by_set.entry(j.relay_set).or_default().push(i);
254        }
255        let batch_start = web_time::Instant::now();
256        // Register every job's plane key BEFORE any relay contact: gating relays
257        // serve a multi-author REQ only when EVERY author is authed on the
258        // connection (proven live: all-authed → EOSE; partial → CLOSED), and the
259        // responder auths exactly the registered set.
260        crate::community::v2::streamauth::register(jobs.iter().filter_map(Job::auth_keys));
261        let shared = LiveTransport::warm_client(
262            relay_sets.iter().flat_map(|r| r.iter().cloned()).collect::<Vec<_>>().as_slice(),
263            std::time::Duration::from_secs(4),
264        )
265        .await
266        .ok();
267
268        // Per-set pipelines: each set gates on its own first live socket, then
269        // fires its filter chunks — independent, so a dead-only set's allowance
270        // never holds another set's filters hostage.
271        let fetch_budget = crate::relay_request_timeout(std::time::Duration::from_secs(4));
272        let mut fetches = FuturesUnordered::new();
273        for (set, idxs) in by_set {
274            // A reader holds no key to authenticate as a writer address, and a gating relay fails
275            // a whole filter set over one plane it can't: those ride their own chunks.
276            let (authed, keyless): (Vec<usize>, Vec<usize>) = idxs.into_iter().partition(|&i| jobs[i].auth_keys().is_some());
277            let chunks: Vec<Vec<Filter>> = authed
278                .chunks(BATCH_FILTERS)
279                .chain(keyless.chunks(BATCH_FILTERS))
280                .map(|chunk| {
281                    chunk
282                        .iter()
283                        .map(|&i| {
284                            let j = &jobs[i];
285                            Query {
286                                kinds: vec![stream::KIND_WRAP],
287                                authors: vec![j.address.to_hex()],
288                                since: j.since,
289                                limit: Some(50),
290                                ..Default::default()
291                            }
292                            .to_filter()
293                        })
294                        .collect()
295                })
296                .collect();
297            let relays = relay_sets[set].clone();
298            let client = shared.clone();
299            fetches.push(async move {
300                let Some(client) = client else {
301                    return (set, Vec::new(), Vec::new(), false);
302                };
303                let live =
304                    connected_targets(&client, &relays, std::time::Duration::from_millis(2500)).await;
305                if live.is_empty() {
306                    return (set, live, Vec::new(), false);
307                }
308                // Prime the AUTH gate on live gating relays so the mass batch is
309                // served there too — priming must be COMPLETE before the REQ (one
310                // unauthenticated plane fails the whole filter set).
311                let gating_live: Vec<String> = live
312                    .iter()
313                    .filter(|r| relay_auth_gating(r))
314                    .cloned()
315                    .collect();
316                if !gating_live.is_empty() {
317                    crate::community::v2::streamauth::prime_auth(&client, &gating_live).await;
318                }
319                let mut evs: Vec<Event> = Vec::new();
320                // Bounded width: chunk×relay all-at-once can blow past a relay's
321                // subscription cap (strfry default 20) alongside the DM walk,
322                // realtime subs, and the hot lane — overflow CLOSEs read as
323                // coverage failure and trigger the very fallback this avoids.
324                let client_ref = &client;
325                let mut per = futures_util::stream::iter(chunks.iter().flat_map(|chunk| {
326                    live.iter().map(move |r| {
327                        let c = client_ref.clone();
328                        let f = chunk.clone();
329                        let r = r.clone();
330                        async move {
331                            let res = crate::community::transport::fetch_relay_eose_filters(
332                                &c, &r, f, fetch_budget,
333                            )
334                            .await;
335                            (r, res)
336                        }
337                    })
338                }).collect::<Vec<_>>())
339                .buffer_unordered(6);
340                // The set is COVERED only when EVERY live relay EOSE'd every
341                // chunk — then batch silence is authoritative everywhere. One
342                // open relay's EOSE must not mask a gating relay whose priming
343                // failed (its CLOSED hides events only it holds); any shortfall
344                // keeps the per-plane fallback in play for this set.
345                let mut ok_chunks: HashMap<String, usize> = HashMap::new();
346                while let Some((r, res)) = per.next().await {
347                    if let Ok(batch) = res {
348                        *ok_chunks.entry(r).or_insert(0) += 1;
349                        evs.extend(batch);
350                    }
351                }
352                let covered = !live.is_empty()
353                    && live
354                        .iter()
355                        .all(|r| ok_chunks.get(r).copied().unwrap_or(0) == chunks.len());
356                (set, live, evs, covered)
357            });
358        }
359
360        // Route each wrap to its job by plane author as sets complete, and
361        // INGEST each set's pages immediately — the hottest channels paint the
362        // moment their batch lands instead of waiting out the slowest set and
363        // the fallback stage.
364        let mut live_by_set: HashMap<usize, Vec<String>> = HashMap::new();
365        let mut covered_sets: HashSet<usize> = HashSet::new();
366        let mut seen_wraps: HashSet<EventId> = HashSet::new();
367        let mut ingested: HashSet<usize> = HashSet::new();
368        let mut painted: Vec<(String, usize)> = Vec::new();
369        while let Some((set, live, evs, covered)) = fetches.next().await {
370            // Each set is a page to open and persist. Once the user has moved
371            // on there is nobody to paint for, so stop rather than decrypt the
372            // rest of the boot for a screen that is gone.
373            if session.stopped() {
374                break;
375            }
376            live_by_set.insert(set, live);
377            if covered {
378                covered_sets.insert(set);
379            }
380            let mut pages: HashMap<usize, Vec<FetchedEvent>> = HashMap::new();
381            for wrap in evs {
382                if !seen_wraps.insert(wrap.id) {
383                    continue;
384                }
385                let Some(&job_idx) = plane_index.get(&wrap.pubkey) else { continue };
386                let j = &jobs[job_idx];
387                if let Some(event) = j.open(&wrap) {
388                    stats.batch_events += 1;
389                    pages.entry(job_idx).or_default().push(FetchedEvent { event, epoch: j.epoch, wrap: Some(wrap.clone()) });
390                }
391            }
392            for (job_idx, mut page) in pages {
393                page.sort_by_key(|f| f.event.opened().at_ms);
394                let new = crate::VectorCore::v2_ingest_chat_page(
395                    &jobs[job_idx].channel_hex,
396                    my_pk,
397                    session.clone(),
398                    page,
399                )
400                .await;
401                ingested.insert(job_idx);
402                if new > 0 {
403                    painted.push((jobs[job_idx].channel_hex.clone(), new));
404                }
405            }
406        }
407        stats.batch_ms = batch_start.elapsed().as_millis();
408        let fallback_start = web_time::Instant::now();
409
410        // Second barrel: jobs the batch couldn't see. When the only LIVE relay in
411        // a set is auth-gating (Ditto serves plane reads solely to a connection
412        // authed AS the plane), batches get protocol-correct silence — fetch_plane
413        // pays the per-plane authed connection through its pool instead. Quiet
414        // channels cost one pooled round trip; the breaker keeps dead relays from
415        // taxing the warmups.
416        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(4));
417        // One KV read per relay, not three per missed job.
418        let gating: HashSet<String> = live_by_set
419            .values()
420            .flat_map(|v| v.iter())
421            .filter(|r| relay_auth_gating(r))
422            .cloned()
423            .collect();
424        let missed: Vec<(usize, nostr_sdk::prelude::Keys, Query, Vec<String>)> = jobs
425            .iter()
426            .enumerate()
427            .filter(|(idx, j)| {
428                if ingested.contains(idx) {
429                    return false;
430                }
431                // A covered set's batch silence IS the answer (a relay we authed
432                // against EOSE'd every chunk): quiet channel, nothing to confirm.
433                if covered_sets.contains(&j.relay_set) {
434                    return false;
435                }
436                // NO live relay: nothing can answer at any price — the reconnect
437                // catch-up owns the channel when its relays return.
438                let live = live_by_set.get(&j.relay_set).map(Vec::as_slice).unwrap_or(&[]);
439                if live.is_empty() {
440                    return false;
441                }
442                // Every live relay gates: batch silence proved nothing.
443                if live.iter().all(|r| gating.contains(r.as_str())) {
444                    return true;
445                }
446                // A live OPEN relay answered with silence — usually a quiet
447                // channel, but a flaky relay can hold HOLES (missed publishes),
448                // so recently-active channels still confirm against a live gating
449                // relay. Dormant ones trust the batch.
450                const RECENT_SECS: u64 = 7 * 24 * 3600;
451                let now = crate::clock::now_secs();
452                j.since.is_some_and(|s| now.saturating_sub(s) < RECENT_SECS)
453                    && live.iter().any(|r| gating.contains(r.as_str()))
454            })
455            .filter_map(|(idx, j)| {
456                // The fallback authenticates as the plane; a reader holds no writer key.
457                let keys = j.auth_keys()?;
458                let q = Query {
459                    kinds: vec![stream::KIND_WRAP],
460                    authors: vec![j.address.to_hex()],
461                    since: j.since,
462                    limit: Some(50),
463                    // Declared intent — fetch_plane does not consult evidence
464                    // yet (#370); its 4s transport bound is the effective limit.
465                    evidence: Evidence::Fast,
466                    ..Default::default()
467                };
468                // Confirmations go to the gating relays only — the open ones
469                // already answered this job in the batch.
470                let live = live_by_set.get(&j.relay_set).map(Vec::as_slice).unwrap_or(&[]);
471                let gate_targets: Vec<String> =
472                    live.iter().filter(|r| gating.contains(r.as_str())).cloned().collect();
473                let targets = if gate_targets.is_empty() { live.to_vec() } else { gate_targets };
474                Some((idx, keys, q, targets))
475            })
476            .collect();
477        let fallback_pages: Vec<(usize, Vec<Event>)> = futures_util::stream::iter(missed)
478            .map(|(idx, keys, q, relays)| {
479                let t = &transport;
480                async move { (idx, t.fetch_plane(&keys, &q, &relays).await.map(|p| p.events).unwrap_or_default()) }
481            })
482            .buffer_unordered(24)
483            .collect()
484            .await;
485        let mut fb_pages: HashMap<usize, Vec<FetchedEvent>> = HashMap::new();
486        for (job_idx, evs) in fallback_pages {
487            if session.stopped() {
488                break;
489            }
490            let j = &jobs[job_idx];
491            for wrap in evs {
492                if !seen_wraps.insert(wrap.id) {
493                    continue;
494                }
495                if let Some(event) = j.open(&wrap) {
496                    stats.fallback_events += 1;
497                    fb_pages.entry(job_idx).or_default().push(FetchedEvent { event, epoch: j.epoch, wrap: Some(wrap.clone()) });
498                }
499            }
500        }
501        for (job_idx, mut page) in fb_pages {
502            page.sort_by_key(|f| f.event.opened().at_ms);
503            let new = crate::VectorCore::v2_ingest_chat_page(
504                &jobs[job_idx].channel_hex,
505                my_pk,
506                session.clone(),
507                page,
508            )
509            .await;
510            if new > 0 {
511                painted.push((jobs[job_idx].channel_hex.clone(), new));
512            }
513        }
514        stats.fallback_ms = fallback_start.elapsed().as_millis();
515        (painted, stats)
516    })
517    .await
518}