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