use crate::catalog::{Chunk, Tree};
use crate::error::Error;
use crate::hash::FastMap;
use crate::trace;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
#[derive(Debug)]
pub(crate) enum Origin {
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
Path(std::path::PathBuf),
Bytes(Arc<[u8]>),
Remote,
}
#[derive(Debug)]
pub(crate) struct LazyFile {
pub(crate) path: Box<str>,
pub(crate) shown: Box<str>,
pub(crate) origin: Origin,
pub(crate) under: bool,
}
impl LazyFile {
pub(crate) fn is_remote(&self) -> bool {
matches!(self.origin, Origin::Remote)
}
fn read(&self) -> Option<Result<(Tree, usize), Error>> {
let parse = |bytes: &[u8]| Tree::parse(bytes, &self.shown).map(|t| (t, bytes.len()));
match &self.origin {
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
Origin::Path(full) => Some(
std::fs::read(full)
.map_err(|source| Error::Io {
path: String::from(&*self.shown),
source,
})
.and_then(|b| parse(&b)),
),
Origin::Bytes(b) => Some(parse(b)),
Origin::Remote => None,
}
}
}
pub(crate) fn apply(acc: &mut Tree, tree: Tree, under: bool) {
if under {
let above = std::mem::replace(acc, tree);
acc.merge(above);
} else {
acc.merge(tree);
}
}
static TICK: AtomicU64 = AtomicU64::new(1);
pub(crate) type Pair = (Arc<str>, Option<Arc<str>>);
pub(crate) type PagePair = (Arc<str>, Arc<str>);
pub(crate) struct LazyCtl {
pub(crate) limit: Option<usize>,
pub(crate) loads: AtomicU64,
pub(crate) owner: OnceLock<Weak<crate::i18n::Inner>>,
pub(crate) flights: Mutex<FastMap<Box<str>, Arc<crate::remote::Flight>>>,
pub(crate) loaded: Mutex<FastMap<PagePair, ()>>,
}
impl LazyCtl {
pub(crate) fn new(limit: Option<usize>) -> LazyCtl {
LazyCtl {
limit,
loads: AtomicU64::new(0),
owner: OnceLock::new(),
flights: Mutex::new(FastMap::default()),
loaded: Mutex::new(FastMap::default()),
}
}
}
pub(crate) fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) struct LazyChunk {
pub(crate) pair: Pair,
pub(crate) files: Arc<[LazyFile]>,
pub(crate) base: Option<Arc<Tree>>,
pub(crate) over: Arc<[Arc<Tree>]>,
pub(crate) added: Arc<[Arc<Tree>]>,
pub(crate) arrived: Mutex<Vec<Option<Arc<Tree>>>>,
pub(crate) remote: bool,
partial: OnceLock<Option<Arc<Tree>>>,
cell: OnceLock<Tree>,
stamp: AtomicU64,
pub(crate) evictable: bool,
pub(crate) ctl: Arc<LazyCtl>,
miss: fn(&LazyChunk) -> Option<&Tree>,
pub(crate) linked: OnceLock<Arc<LinkCtx>>,
}
pub(crate) struct LinkCtx {
pub(crate) layers: Vec<Pair>,
pub(crate) tag: Arc<str>,
pub(crate) resolve: fn(&mut Tree, &[&Chunk], &str),
}
thread_local! {
#[allow(
clippy::missing_const_for_thread_local,
reason = "already `const`: clippy misreads the expansion on targets without native TLS (Android)"
)]
static LOADING: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
}
struct Loading(usize);
impl Loading {
fn has(cell: &LazyChunk) -> bool {
let at = std::ptr::from_ref(cell) as usize;
LOADING
.try_with(|l| l.try_borrow().is_ok_and(|l| l.contains(&at)))
.unwrap_or(false)
}
fn push(cell: &LazyChunk) -> Loading {
let at = std::ptr::from_ref(cell) as usize;
let _ = LOADING.try_with(|l| {
if let Ok(mut l) = l.try_borrow_mut() {
l.push(at);
}
});
Loading(at)
}
}
impl Drop for Loading {
fn drop(&mut self) {
let _ = LOADING.try_with(|l| {
if let Ok(mut l) = l.try_borrow_mut()
&& let Some(i) = l.iter().rposition(|x| *x == self.0)
{
l.remove(i);
}
});
}
}
impl LinkCtx {
fn deps(&self, ctl: &LazyCtl) -> Vec<Layer> {
let Some(inner) = ctl.owner.get().and_then(Weak::upgrade) else {
return Vec::new();
};
let snap = inner.current();
self.layers
.iter()
.filter_map(|(l, p)| snap.data.get(l)?.layer(p.as_deref()).cloned())
.collect()
}
fn apply(&self, tree: &mut Tree, deps: &[Layer]) {
let layers: Vec<&Chunk> = deps
.iter()
.filter_map(|l| match l {
Layer::Ready(c) => Some(&**c),
Layer::Lazy(c) => c
.loaded()
.or_else(|| c.partial.get().and_then(|p| p.as_deref())),
})
.collect();
(self.resolve)(tree, &layers, &self.tag);
}
}
impl std::fmt::Debug for LazyChunk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LazyChunk")
.field("files", &self.files.len())
.field("loaded", &self.cell.get().is_some())
.finish_non_exhaustive()
}
}
impl LazyChunk {
pub(crate) fn new(
pair: Pair,
files: Arc<[LazyFile]>,
base: Option<Arc<Tree>>,
over: Arc<[Arc<Tree>]>,
evictable: bool,
ctl: Arc<LazyCtl>,
) -> LazyChunk {
LazyChunk::parts(
pair,
files,
base,
over,
Arc::new([]),
evictable,
ctl,
LazyChunk::load,
)
}
#[allow(clippy::too_many_arguments, reason = "the fields of one cell")]
fn parts(
pair: Pair,
files: Arc<[LazyFile]>,
base: Option<Arc<Tree>>,
over: Arc<[Arc<Tree>]>,
added: Arc<[Arc<Tree>]>,
evictable: bool,
ctl: Arc<LazyCtl>,
miss: fn(&LazyChunk) -> Option<&Tree>,
) -> LazyChunk {
LazyChunk {
pair,
remote: files.iter().any(LazyFile::is_remote),
partial: OnceLock::new(),
arrived: Mutex::new(files.iter().map(|_| None).collect()),
files,
base,
over,
added,
cell: OnceLock::new(),
stamp: AtomicU64::new(0),
evictable,
ctl,
miss,
linked: OnceLock::new(),
}
}
fn again(&self, added: Arc<[Arc<Tree>]>, evictable: bool) -> LazyChunk {
let next = LazyChunk::parts(
self.pair.clone(),
self.files.clone(),
self.base.clone(),
self.over.clone(),
added,
evictable,
self.ctl.clone(),
self.miss,
);
if let Some(ctx) = self.linked.get() {
let _ = next.linked.set(ctx.clone());
}
next
}
pub(crate) fn fresh(&self) -> LazyChunk {
self.again(self.added.clone(), self.evictable)
}
pub(crate) fn respawn(&self) -> LazyChunk {
let next = self.again(self.added.clone(), self.evictable);
*lock(&next.arrived) = lock(&self.arrived).clone();
next
}
pub(crate) fn has_partial(&self) -> bool {
self.partial.get().is_some()
}
pub(crate) fn with_over(&self, tree: Tree) -> LazyChunk {
let added: Arc<[Arc<Tree>]> = self
.added
.iter()
.cloned()
.chain(std::iter::once(Arc::new(tree)))
.collect();
let next = self.again(added, false);
*lock(&next.arrived) = lock(&self.arrived).clone();
next
}
pub(crate) fn loaded(&self) -> Option<&Tree> {
self.cell.get()
}
pub(crate) fn stamp(&self) -> u64 {
self.stamp.load(Ordering::Relaxed)
}
#[inline]
pub(crate) fn get(&self) -> Option<&Tree> {
match self.cell.get() {
Some(t) => {
if self.evictable {
let now = TICK.load(Ordering::Relaxed);
if self.stamp.load(Ordering::Relaxed) != now {
self.stamp.store(now, Ordering::Relaxed);
}
}
Some(t)
}
None => (self.miss)(self),
}
}
fn prepare(&self) -> Vec<Layer> {
let Some(ctx) = self.linked.get() else {
return Vec::new();
};
let deps = ctx.deps(&self.ctl);
let _me = Loading::push(self);
for d in &deps {
if let Layer::Lazy(c) = d
&& !Loading::has(c)
{
let _ = c.get();
}
}
deps
}
#[cold]
#[inline(never)]
fn load(&self) -> Option<&Tree> {
if self.remote {
return self.partial();
}
let deps = self.prepare();
let mut fresh = None;
let tree = self.cell.get_or_init(|| {
let (tree, ok) = self.build(Vec::new(), &deps);
fresh = Some(ok);
tree
});
if let Some(ok) = fresh
&& self.mark_loaded(ok)
{
if let Some(inner) = self.ctl.owner.get().and_then(Weak::upgrade) {
inner.try_evict();
}
}
Some(tree)
}
fn partial(&self) -> Option<&Tree> {
if let Some(p) = self.partial.get() {
return p.as_deref();
}
let deps = self.prepare();
self.partial
.get_or_init(|| {
let ctx = self.linked.get();
if ctx.is_none() && self.over.is_empty() && self.added.is_empty() {
return self.base.clone();
}
let mut t = self.base.as_deref().cloned().unwrap_or_default();
for o in self.over.iter() {
t.merge(Tree::clone(o));
}
if let Some(ctx) = ctx {
ctx.apply(&mut t, &deps);
}
for a in self.added.iter() {
t.merge(Tree::clone(a));
}
Some(Arc::new(t))
})
.as_deref()
}
fn mark_loaded(&self, ok: bool) -> bool {
if ok {
self.ctl.loads.fetch_add(1, Ordering::Relaxed);
}
let now = TICK.fetch_add(2, Ordering::Relaxed) + 1;
self.stamp.store(now, Ordering::Relaxed);
if self.evictable
&& let (l, Some(p)) = &self.pair
{
lock(&self.ctl.loaded).insert((l.clone(), p.clone()), ());
}
self.evictable
}
pub(crate) fn complete(&self) -> bool {
self.cell.get().is_none()
&& self
.files
.iter()
.zip(lock(&self.arrived).iter())
.all(|(f, t)| !f.is_remote() || t.is_some())
}
pub(crate) fn fill(&self) -> Option<bool> {
if !self.complete() {
return None;
}
let arrived = std::mem::take(&mut *lock(&self.arrived));
let deps = self.prepare();
let mut fresh = None;
self.cell.get_or_init(|| {
let (tree, ok) = self.build(arrived, &deps);
fresh = Some(ok);
tree
});
fresh.map(|ok| self.mark_loaded(ok))
}
fn build(&self, mut arrived: Vec<Option<Arc<Tree>>>, deps: &[Layer]) -> (Tree, bool) {
let mut ok = true;
let mut files = Tree::default();
for (i, f) in self.files.iter().enumerate() {
let timer = trace::Timer::start();
let tree = match f.read() {
Some(Ok((tree, bytes))) => {
timer.done("load", &f.shown, bytes);
tree
}
Some(Err(e)) => {
trace::broken(&e);
ok = false;
continue;
}
None => match arrived.get_mut(i).and_then(Option::take) {
Some(t) => Arc::unwrap_or_clone(t),
None => continue,
},
};
apply(&mut files, tree, f.under);
}
let mut tree = self.base.as_deref().cloned().unwrap_or_default();
tree.merge(files);
for o in self.over.iter() {
tree.merge(Tree::clone(o));
}
if let Some(ctx) = self.linked.get() {
ctx.apply(&mut tree, deps);
}
for a in self.added.iter() {
tree.merge(Tree::clone(a));
}
(tree, ok)
}
}
#[derive(Debug, Clone)]
pub(crate) enum Layer {
Ready(Arc<Chunk>),
Lazy(Arc<LazyChunk>),
}
impl Layer {
#[inline]
pub(crate) fn chunk(&self) -> Option<&Chunk> {
match self {
Layer::Ready(c) => Some(c),
Layer::Lazy(l) => l.get(),
}
}
}