use super::*;
use crate::community::roles::Permissions;
use crate::community::v2::seal::{self, SealPage};
use crate::community::v2::writers::SealRef;
const SEAL_READ_PAGE: usize = 200;
const SEAL_WALL_LIMIT: usize = 5_000;
const IDS_PER_FETCH: usize = 200;
const PAGE_CACHE_MAX: usize = 4096;
fn hex(b: &[u8; 32]) -> String {
crate::simd::hex::bytes_to_hex_32(b)
}
pub(super) fn reads_whole_history(community: &CommunityV2, ch: &ChannelV2, planes: &[(ReadPlane, Epoch)]) -> bool {
let has = |e: u64, public: bool| planes.iter().any(|(p, ep)| ep.0 == e && p.group().is_some() && matches!(p, ReadPlane::Public(..)) == public);
let roots = |public: bool| (0..=community.root_epoch.0).all(|e| has(e, public));
if ch.private {
(1..=ch.epoch.0).all(|e| has(e, false)) && (ch.public_until().is_none() || roots(true))
} else {
roots(false)
}
}
pub(crate) async fn seal_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, ch: &ChannelV2) -> Result<Option<usize>, String> {
seal_history_at(transport, community, ch, now_ms()).await
}
pub(crate) async fn seal_history_at<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, ch: &ChannelV2, now: u64) -> Result<Option<usize>, String> {
let ledger = ch.writers.clone().ok_or("this channel keeps no writer ledger")?;
let (Some(until), Some(run)) = (ledger.seal_target(now), ledger.seal_run()) else { return Ok(None) };
let planes = read_planes(community, ch);
if !reads_whole_history(community, ch, &planes) {
crate::log_debug!("[v2:writers {}] can't read all of its history, so not sealing it", &hex(&ch.id.0)[..8]);
return Ok(None);
}
writing::read_whole(transport, community).await?;
let cid_hex = hex(&community.id().0);
let held = crate::db::community::load_community_v2(community.id())?.ok_or("this community is gone")?;
let judge = writing::Judge::of(&held, ch);
let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
let owner = community.owner()?.to_hex();
let prev = ledger.seal.clone();
let mut ids: Vec<([u8; 32], u64, usize)> = Vec::new();
let mut top = until.saturating_sub(1);
while let Some((floor, range_top)) = ledger.read_range(top) {
for (i, (plane, epoch)) in planes.iter().enumerate() {
read_whole_range(transport, community, plane, floor, range_top, |wrap| {
let Some(event) = plane.open(&wrap, &ch.id, *epoch) else { return };
let o = event.opened();
let (at, author, kind) = (o.at_ms, o.author.to_hex(), o.rumor.kind.as_u16());
if at < floor || at > range_top {
return;
}
if kind == super::super::kind::REACTION && !roster.channel_permissions(Some(&owner), &author, &hex(&ch.id.0), ch.private).contains(Permissions::ADD_REACTIONS) {
return;
}
if matches!(writing::sort_arrival(judge.as_ref(), event, None), writing::Arrival::Stands(_)) {
ids.push((wrap.id.to_bytes(), at, i));
}
})
.await?;
}
let Some(below) = floor.checked_sub(1) else { break };
top = below;
}
let mut pages = seal::paginate(ids);
let added: usize = pages.iter().map(|(p, _)| p.ids.len()).sum();
let dated = until.saturating_sub(1);
let mut next: Option<([u8; 32], Epoch)> = prev.as_ref().and_then(|s| s.page.map(|p| (p, s.read)));
let mut wraps = Vec::with_capacity(pages.len());
for (page, i) in pages.iter_mut().rev() {
let (plane, epoch) = &planes[*i];
let group = plane.group().ok_or("a page's read plane has no key here")?;
page.next = next;
let wrap = seal::page_wrap(page, &ch.id, *epoch, group, dated)?;
next = Some((wrap.id.to_bytes(), *epoch));
wraps.push(wrap);
}
for wrap in &wraps {
transport.publish_durable(wrap, &community.relays).await?;
}
if !crate::db::current_session().is_live() {
return Err("account changed while sealing a channel".to_string());
}
let fresh = crate::db::community::load_community_v2(community.id())?.ok_or("this community is gone")?;
let ch = fresh.channel(&ch.id).cloned().ok_or("no such channel")?;
let base = ch.writers.clone().ok_or("this channel keeps no writer ledger")?;
if base.seal_target(now) != Some(until) || writing::ledger_moved_since(transport, &fresh, &ch).await? {
return Err("this channel's writer ledger moved; nothing sealed".to_string());
}
let sealed = SealRef {
page: next.map(|(p, _)| p),
read: next.map_or(Epoch(0), |(_, r)| r),
until,
run,
count: prev.map_or(0, |s| s.count) + added as u64,
extra: Default::default(),
};
writing::publish_seal(transport, &fresh, &ch, &base, sealed).await?;
Ok(Some(added))
}
async fn read_whole_range<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, plane: &ReadPlane, floor: u64, top: u64, mut each: impl FnMut(Event)) -> Result<(), String> {
let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
let mut cursor = top / 1000;
let read = |q: Query| async move {
match plane.group() {
Some(group) => {
let page = transport.fetch_plane(group.keys(), &q, &community.relays).await?;
if !page.is_complete() {
return Err("a relay didn't answer the whole read; nothing sealed".to_string());
}
Ok(page.events)
}
None => transport.fetch(&q, &community.relays).await,
}
};
loop {
let q = Query { since: Some(floor / 1000), evidence: crate::community::transport::Evidence::Full, ..plane_page(plane.address().to_hex(), SEAL_READ_PAGE, Some(cursor)) };
let evs = read(q.clone()).await?;
let full = evs.len() >= SEAL_READ_PAGE;
let oldest = evs.iter().map(|e| e.created_at.as_secs()).min();
let mut fresh = false;
for e in evs {
if seen.insert(e.id) {
fresh = true;
each(e);
}
}
let Some(oldest) = oldest else { break };
let next = if oldest == cursor && (full || !fresh) {
for e in read(Query { since: Some(oldest), limit: Some(SEAL_WALL_LIMIT), ..q }).await? {
if seen.insert(e.id) {
each(e);
}
}
oldest.saturating_sub(1)
} else if fresh {
oldest
} else {
break;
};
if next < floor / 1000 || oldest == 0 {
break;
}
cursor = next;
}
Ok(())
}
struct SealPages;
type PageCache = std::sync::Mutex<std::collections::HashMap<[u8; 32], (SealPage, PublicKey)>>;
async fn load_page<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, ch: &ChannelV2, link: ([u8; 32], Epoch)) -> Result<Option<(SealPage, PublicKey)>, String> {
let cache = crate::db::current_session().scoped::<SealPages, PageCache>();
if let Some(p) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&link.0) {
return Ok(Some(p.clone()));
}
let q = Query { ids: vec![hex(&link.0)], evidence: crate::community::transport::Evidence::Quorum, ..Default::default() };
for (plane, _) in read_planes(community, ch).into_iter().filter(|(_, e)| *e == link.1) {
let fetched = match plane.group() {
Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await?.events,
None => transport.fetch(&q, &community.relays).await?,
};
if let Some(page) = fetched.iter().find_map(|w| seal::open_page(w, &link.0, &ch.id, link.1, &plane.address(), plane.conv())) {
let mut cache = cache.lock().unwrap_or_else(|e| e.into_inner());
if cache.len() >= PAGE_CACHE_MAX {
cache.clear();
}
cache.insert(link.0, (page.clone(), plane.address()));
return Ok(Some((page, plane.address())));
}
}
Ok(None)
}
pub(crate) struct SealWalk {
next: Option<([u8; 32], Epoch)>,
page: Option<(SealPage, PublicKey)>,
given: usize,
until_ms: u64,
broken: bool,
}
pub(crate) struct SealStep {
pub ids: Vec<([u8; 32], PublicKey)>,
pub bottom_ms: Option<u64>,
}
impl SealWalk {
pub(crate) fn new(seal: &SealRef, until_ms: u64) -> Self {
SealWalk { next: seal.page.map(|p| (p, seal.read)), page: None, given: 0, until_ms, broken: false }
}
pub(crate) fn done(&self) -> bool {
self.next.is_none() && self.page.as_ref().is_none_or(|(p, _)| self.given >= p.ids.len())
}
pub(crate) fn broken(&self) -> bool {
self.broken
}
pub(crate) async fn next<T: Transport + ?Sized>(&mut self, transport: &T, community: &CommunityV2, ch: &ChannelV2, n: usize) -> Result<SealStep, String> {
let mut step = SealStep { ids: Vec::with_capacity(n), bottom_ms: None };
while step.ids.len() < n {
if let Some((page, address)) = &self.page {
if self.given < page.ids.len() {
let take = (n - step.ids.len()).min(page.ids.len() - self.given);
step.ids.extend(page.ids[self.given..self.given + take].iter().map(|id| (*id, *address)));
self.given += take;
step.bottom_ms = Some(page.oldest);
continue;
}
}
let Some(link) = self.next else { break };
let Some((page, address)) = load_page(transport, community, ch, link).await? else {
self.next = None;
self.broken = true;
break;
};
self.next = page.next;
self.given = if page.oldest > self.until_ms { page.ids.len() } else { 0 };
self.page = Some((page, address));
}
Ok(step)
}
}
pub(crate) async fn fetch_ids<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, plane: Option<&GroupKey>, ids: &[[u8; 32]], evidence: crate::community::transport::Evidence) -> Result<Vec<Event>, String> {
let mut out = Vec::with_capacity(ids.len());
for batch in ids.chunks(IDS_PER_FETCH) {
let q = Query { ids: batch.iter().map(hex).collect(), evidence, ..Default::default() };
out.extend(match plane {
Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await?.events,
None => transport.fetch(&q, &community.relays).await?,
});
}
Ok(out)
}