~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

An account's space repos are read from its table as they are needed

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:store/account-table
.cargo/config.toml+6−2
@@ -2,6 +2,10 @@
# give memory back to the system as soon as it is freed: freed pages are kept
# for no time at all. The server's resident memory is what spec/STORE.md's
# bounds count, and a default build keeps what a large write freed for ten
# seconds. `_RJEM_MALLOC_CONF` in the server's environment still overrides it.
# seconds. It is built with 8 arenas, not the default four for each core:
# each arena keeps slabs of its own for every size of allocation, part full,
# and a thread's allocations go to its arena, so what is resident and not in
# use grows with the arenas, by megabytes each, whatever the server holds.
# `_RJEM_MALLOC_CONF` in the server's environment still overrides both.
[env]
JEMALLOC_SYS_WITH_MALLOC_CONF = "dirty_decay_ms:0,muzzy_decay_ms:0"
JEMALLOC_SYS_WITH_MALLOC_CONF = "dirty_decay_ms:0,muzzy_decay_ms:0,narenas:8"
crates/pds/src/main.rs+10−8
@@ -4,10 +4,11 @@
#![forbid(unsafe_code)]
/// jemalloc rather than the system's allocator, built to keep freed pages
/// for no time at all (`.cargo/config.toml`): the server's resident memory
/// is what `spec/STORE.md`'s "Scale" bounds, and the system's allocators
/// keep what a large write freed resident, each in its own way. So memory
/// follows what is in use, the same on Linux and macOS.
/// for no time at all, in a few arenas whatever the machine's cores
/// (`.cargo/config.toml`): the server's resident memory is what
/// `spec/STORE.md`'s "Scale" bounds, and the system's allocators keep what
/// a large write freed resident, each in its own way. So memory follows
/// what is in use, the same on Linux and macOS.
#[global_allocator]
static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
@@ -92,13 +93,14 @@ mod tests {
/// The build is given the allocator's options, as `.cargo/config.toml`
/// sets them for jemalloc's build and this crate's alike: a build
/// without them keeps freed pages resident for seconds, past
/// `spec/STORE.md`'s memory bound. What the allocator then does with
/// them is the scale run's to hold (`harness/compare.mjs --scale`).
/// without them keeps freed pages resident for seconds, and slabs part
/// full in four arenas for each core, past `spec/STORE.md`'s memory
/// bound. What the allocator then does with them is the scale run's to
/// hold (`harness/compare.mjs --scale`).
#[test]
fn the_allocator_keeps_no_freed_pages() {
let built = option_env!("JEMALLOC_SYS_WITH_MALLOC_CONF").unwrap_or("");
for option in ["dirty_decay_ms:0", "muzzy_decay_ms:0"] {
for option in ["dirty_decay_ms:0", "muzzy_decay_ms:0", "narenas:8"] {
assert!(
built.split(',').any(|o| o == option),
"jemalloc built with {built:?}, without {option}"
crates/pds-server/src/checkpoint/before.rsnew+280−0
@@ -0,0 +1,280 @@
//! A table of the version before, which the last release wrote: it has no
//! `H`, its `S` says version 2 and holds the table's generation, the last
//! `seq` and the greatest seq let go, and each space repo whole: its
//! space's URI, its rev and `data`, its records, `[path, DRISL bytes]`,
//! the rev that last wrote each, `[path, rev]`, and its operation log,
//! each operation's rev, collection, rkey, and CID after and before it.
//! The rest of its `S`, and its other sections, are as this version's.
//!
//! It is read whole, once, by the fold that makes a table of this version
//! of it (`load`): its space repos become the entries of their sections,
//! each checked as a load of the version before checked it.
use super::spaces::{self, Entries, Meta, op_key, op_value, ref_key, space_key};
use super::{
Small, VERSION, as_bytes, as_link, as_list, as_pair, as_text, as_uint, fields, int, key, map,
or_none, text,
};
use crate::blobs::cids_in;
use crate::space_repo::Op;
use pds_repo::data::{V, cid_of, cid_string, decode};
use pds_repo::valid_tid;
use pds_space::LtHash;
use pds_space::lthash::element;
use std::collections::BTreeMap;
/// The version a table of the version before says it is.
const BEFORE: i64 = 2;
/// Take the value of `k` out of a map.
fn take(m: &mut Vec<(String, V)>, k: &str) -> Result<V, String> {
m.iter()
.position(|(n, _)| n == k)
.map(|i| m.swap_remove(i).1)
.ok_or_else(|| format!("a checkpoint of the version before with no {k}"))
}
/// An `S` value of the version before, decoded, less its version.
fn state(bytes: &[u8]) -> Result<Vec<(String, V)>, String> {
let V::Map(mut m) = decode(bytes).map_err(|e| format!("the state: {e}"))? else {
return Err("the state is not a map".into());
};
let version = take(&mut m, "version")?;
if version != V::Int(BEFORE) {
return Err(format!(
"a checkpoint of version {version:?}, which this server does not know"
));
}
Ok(m)
}
/// The generation of the table whose `S` value this is.
pub(super) fn generation(bytes: &[u8]) -> Result<u64, String> {
as_uint(take(&mut state(bytes)?, "generation")?, "generation")
}
/// Read an `S` value of the version before, of the account `did`: the
/// state, and the entries of the space repos' sections, by key.
pub(super) fn read(bytes: &[u8], did: &str) -> Result<(Small, Entries), String> {
let mut m = state(bytes)?;
let mut number = |k: &str| as_uint(take(&mut m, k)?, k);
let header = (number("generation")?, number("lastSeq")?, number("letGo")?);
let mut rows = BTreeMap::new();
let mut counted: BTreeMap<String, u64> = BTreeMap::new();
let mut kept = Vec::new();
for x in as_list(take(&mut m, "spaces")?, "spaces")? {
kept.push(space(x, &mut rows, &mut counted)?);
}
let counted = counted
.into_iter()
.map(|(cid, n)| V::Arr(vec![text(&cid), int(n)]));
m.push(("version".into(), V::Int(VERSION)));
m.push(("spaces".into(), V::Arr(kept)));
m.push(("spaceRefs".into(), V::Arr(counted.collect())));
Ok((Small::of(V::Map(m), header, did)?, rows))
}
/// A space repo as the version before kept it: its entries of this
/// version's sections go into `rows`, each of its records' blob references
/// is counted in `counted`, and what this version's `S` keeps of it is
/// answered. Its records must make its `data`, each have one rev, no later
/// than the repo's, and its operations be in order.
fn space(v: V, rows: &mut Entries, counted: &mut BTreeMap<String, u64>) -> Result<V, String> {
let [space, rev, data, records, written, ops] = fields(
v,
["space", "rev", "data", "records", "written", "ops"],
"a space",
)?;
let space = as_text(space, "a space's space")?;
let what = |x: &str| format!("space {space}'s {x}");
let rev = as_text(rev, &what("rev"))?;
let mut revs: BTreeMap<String, String> = BTreeMap::new();
for x in as_list(written, &what("written"))? {
let (path, r) = as_pair(x, &what("written"))?;
let (path, r) = (
as_text(path, &what("written's path"))?,
as_text(r, &what("written's rev"))?,
);
if revs.last_key_value().is_some_and(|(l, _)| *l >= path) || !valid_tid(&r) || r > rev {
return Err(what("written out of order, or of a bad rev"));
}
revs.insert(path, r);
}
let mut hash = LtHash::new();
let mut held = 0u64;
let mut last: Option<String> = None;
for x in as_list(records, &what("records"))? {
let (path, bytes) = as_pair(x, &what("record"))?;
let (path, bytes) = (
as_text(path, &what("record's path"))?,
as_bytes(bytes, &what("record's bytes"))?,
);
if last.as_ref().is_some_and(|l| *l >= path) {
return Err(what("records out of order"));
}
let value = decode(&bytes).map_err(|e| what(&format!("record {path}: {e}")))?;
let Some(written) = revs.remove(&path) else {
return Err(what("records, not one rev for each"));
};
let meta = Meta {
cid: cid_of(0x71, &bytes),
rev: written,
refs: cids_in(&value),
};
hash.add(&element(&path, &cid_string(&meta.cid)));
for cid in &meta.refs {
*counted.entry(cid.clone()).or_default() += 1;
rows.insert(
key(spaces::REFS, &ref_key(&space, cid, &path)),
meta.rev.clone().into_bytes(),
);
}
let k = space_key(&space, path.as_bytes());
rows.insert(key(spaces::RECORDS, &k), meta.encode());
rows.insert(key(spaces::VALUES, &k), bytes);
held += 1;
last = Some(path);
}
if !revs.is_empty() {
return Err(what("written, not one record for each"));
}
let data = as_bytes(data, &what("data"))?;
if hash.digest()[..] != data[..] {
return Err(what("records, which do not make its data"));
}
let mut logged = 0u64;
let mut before: Option<(String, usize)> = None;
for x in as_list(ops, &what("ops"))? {
let [op_rev, collection, rkey, cid, prev] = fields(
x,
["rev", "collection", "rkey", "cid", "prev"],
&what("operation"),
)?;
let op_rev = as_text(op_rev, &what("operation's rev"))?;
if !valid_tid(&op_rev) || op_rev > rev || before.as_ref().is_some_and(|(r, _)| *r > op_rev)
{
return Err(what("operations out of order, or of a bad rev"));
}
let index = match &before {
Some((r, i)) if *r == op_rev => i + 1,
_ => 0,
};
let link = |v: V| or_none(v, |l| as_link(l, &what("operation's cid")));
let o = Op {
path: format!(
"{}/{}",
as_text(collection, &what("operation's collection"))?,
as_text(rkey, &what("operation's rkey"))?
),
cid: link(cid)?,
prev: link(prev)?,
rev: op_rev.clone(),
index,
};
rows.insert(
key(spaces::OPS, &op_key(&space, &o.rev, o.index)),
op_value(&o),
);
before = Some((op_rev, index));
logged += 1;
}
Ok(map([
("space", text(&space)),
("rev", text(&rev)),
("data", V::Bytes(data)),
("hash", V::Bytes(hash.state().to_vec())),
("records", int(held)),
("ops", int(logged)),
]))
}
#[cfg(test)]
pub(crate) mod tests {
use super::super::{header_value, read_header};
use super::*;
use pds_repo::data::encode;
use pds_store::table::{BlockCache, Table, TableWriter};
use std::path::Path;
/// Make the table at `path`, of this version, one of the version
/// before holding the same: its space repos whole in its `S`, with its
/// generation, last `seq` and greatest seq let go, and no `H` nor any
/// of the space repos' sections.
pub(crate) fn downgrade(path: &Path) {
let cache = BlockCache::new(1 << 20);
let all: Vec<(Vec<u8>, Vec<u8>)> = Table::open(path)
.unwrap()
.iter(b"", None, &cache)
.map(Result::unwrap)
.collect();
let get = |k: &[u8]| all.iter().find(|(x, _)| x == k).unwrap().1.clone();
let (generation, last_seq, let_go) = read_header(&get(b"H")).unwrap();
let V::Map(mut m) = decode(&get(b"S")).unwrap() else {
panic!("a state that is no map")
};
assert_eq!(take(&mut m, "version"), Ok(V::Int(VERSION)));
take(&mut m, "spaceRefs").unwrap();
let whole = |s: V| {
let [space, rev, data, _, _, _] = fields(
s,
["space", "rev", "data", "hash", "records", "ops"],
"a space",
)
.unwrap();
let uri = as_text(space.clone(), "a space").unwrap();
let of = |section: u8| {
let prefix = key(section, &space_key(&uri, b""));
all.iter()
.filter(move |(k, _)| k.starts_with(&prefix))
.map(|(k, v)| (&k[uri.len() + 2..], v))
};
let path = |k: &[u8]| text(std::str::from_utf8(k).unwrap());
let records =
of(spaces::VALUES).map(|(k, v)| V::Arr(vec![path(k), V::Bytes(v.clone())]));
let written = of(spaces::RECORDS)
.map(|(k, v)| V::Arr(vec![path(k), text(&Meta::decode(v).unwrap().rev)]));
let ops = of(spaces::OPS).map(|(k, v)| {
let o = spaces::read_op(k, v).unwrap();
let (collection, rkey) = o.path.split_once('/').unwrap();
let link = |c: Option<Vec<u8>>| c.map_or(V::Null, V::Link);
map([
("rev", text(&o.rev)),
("collection", text(collection)),
("rkey", text(rkey)),
("cid", link(o.cid)),
("prev", link(o.prev)),
])
});
map([
("space", space),
("rev", rev),
("data", data),
("records", V::Arr(records.collect())),
("written", V::Arr(written.collect())),
("ops", V::Arr(ops.collect())),
])
};
let V::Arr(kept) = take(&mut m, "spaces").unwrap() else {
panic!("spaces that are no list")
};
m.push((
"spaces".into(),
V::Arr(kept.into_iter().map(whole).collect()),
));
m.push(("version".into(), V::Int(BEFORE)));
m.push(("generation".into(), int(generation)));
m.push(("lastSeq".into(), int(last_seq)));
m.push(("letGo".into(), int(let_go)));
assert_eq!(header_value(generation, last_seq, let_go), get(b"H"));
let out = std::io::BufWriter::new(std::fs::File::create(path).unwrap());
let mut w = TableWriter::new(out, all.len() as u64);
for (k, v) in &all {
match k[0] {
b'B' | b'D' | b'E' | b'P' => w.add(k, v).unwrap(),
b'S' => w.add(k, &encode(&V::Map(m.clone()))).unwrap(),
_ => {}
}
}
w.finish().unwrap();
}
}
crates/pds-server/src/checkpoint/spaces.rsnew+1167−0
1167 lines changed: not loaded until asked for.
crates/pds-server/src/blobs.rs+55−19
@@ -119,6 +119,11 @@ pub(crate) struct Held {
/// CIDs it references, each once, in order.
type RecordRefs = (String, Vec<String>);
/// The bytes a record with blob refs, at `path`, is counted as in the cache.
fn record_cost(path: &str, (rev, cids): &RecordRefs) -> usize {
path.len() + rev.len() + cids.iter().map(|c| c.len() + 24).sum::<usize>() + 96
}
/// What a commit changed of an account's blobs, as they were before it.
#[derive(Default)]
struct Undo {
@@ -144,6 +149,8 @@ pub(crate) struct Blobs {
space_refs: HashMap<String, u32>,
/// Each record with blob refs, by path.
records: HashMap<String, RecordRefs>,
/// The bytes `records` is counted as in the cache.
record_bytes: usize,
/// The blobs held that no record references, by when they were last uploaded.
unreferenced: BTreeSet<(u64, String)>,
/// The bytes of the blobs held.
@@ -290,21 +297,23 @@ impl Blobs {
self.placing.is_empty() && self.doomed.is_empty()
}
/// About the bytes it holds in memory.
/// About the bytes it holds in memory: each a count kept as it changes.
pub(crate) fn cost(&self) -> u64 {
let refs: usize = self
.records
.iter()
.map(|(p, (r, c))| {
p.len() + r.len() + c.iter().map(|x| x.len() + 24).sum::<usize>() + 96
})
.sum();
let undo = self
.undo
.as_ref()
.map_or(0, |u| u.records.len() + u.refs.len() + u.held.len());
(self.held.len() * 160
+ self.refs.len() * 96
+ self.space_refs.len() * 96
+ self.takedowns.len() * 128
+ self.kept.len() * 96
+ refs) as u64
+ self.unreferenced.len() * 112
+ self.unsynced.len() * 256
+ self.placing.len() * 96
+ self.doomed.len() * 96
+ undo * 160
+ self.record_bytes) as u64
}
/// The CIDs whose objects a bucket may keep that it does not hold, and
@@ -607,6 +616,9 @@ impl Blobs {
for path in c.puts.iter().map(|(p, _)| p).chain(&c.dels) {
let now = written.get(path).cloned().unwrap_or_default();
let before = self.records.remove(path);
if let Some(b) = &before {
self.record_bytes -= record_cost(path, b);
}
undo.records.push((path.clone(), before.clone()));
let before = before.map(|(_, cids)| cids).unwrap_or_default();
for cid in before.iter().filter(|x| !now.contains(x)) {
@@ -616,7 +628,9 @@ impl Blobs {
*delta.entry(cid.clone()).or_default() += 1;
}
if !now.is_empty() {
self.records.insert(path.clone(), (c.rev.clone(), now));
let refs = (c.rev.clone(), now);
self.record_bytes += record_cost(path, &refs);
self.records.insert(path.clone(), refs);
}
}
for (cid, d) in delta {
@@ -679,10 +693,13 @@ impl Blobs {
pub(crate) fn undo(&mut self) {
let Some(u) = self.undo.take() else { return };
for (path, before) in u.records {
match before {
Some(r) => self.records.insert(path, r),
None => self.records.remove(&path),
};
if let Some(now) = self.records.remove(&path) {
self.record_bytes -= record_cost(&path, &now);
}
if let Some(r) = before {
self.record_bytes += record_cost(&path, &r);
self.records.insert(path, r);
}
}
for (cid, n) in u.refs {
match n {
@@ -901,18 +918,35 @@ impl Blobs {
out
}
/// How many records of the account's space repos reference each CID,
/// for those some such record does, in ascending order of CID: what a
/// checkpoint keeps of them, as the records are not read to count them.
pub(crate) fn space_ref_list(&self) -> Vec<(&str, u32)> {
let mut out: Vec<(&str, u32)> = self
.space_refs
.iter()
.map(|(cid, n)| (cid.as_str(), *n))
.collect();
out.sort_unstable();
out
}
/// The blobs a checkpoint keeps, as replaying the log would leave them:
/// those held, each with its takedown, the records with blob refs, each
/// with the rev that last wrote it and what it references, and with
/// blobs in a bucket, the objects it may keep of those not held
/// (`objects_list`). The space repos' references are counted as each is
/// restored (`space_repo`).
/// (`objects_list`), and how many records of the account's space repos
/// reference each CID (`space_ref_list`).
pub(crate) fn restore(
records: Vec<(String, String, Vec<String>)>,
held: Vec<(String, Held, Option<String>)>,
objects: Option<Vec<String>>,
space_refs: Vec<(String, u32)>,
) -> Result<Blobs, String> {
let mut b = Blobs::default();
let mut b = Blobs {
space_refs: space_refs.into_iter().collect(),
..Default::default()
};
for (path, rev, cids) in records {
if cids.is_empty() {
return Err(format!("record {path} kept with no blob refs"));
@@ -920,10 +954,12 @@ impl Blobs {
for cid in &cids {
*b.refs.entry(cid.clone()).or_default() += 1;
}
b.records.insert(path, (rev, cids));
let refs = (rev, cids);
b.record_bytes += record_cost(&path, &refs);
b.records.insert(path, refs);
}
for (cid, h, takedown) in held {
if !b.refs.contains_key(&cid) {
if !b.referenced(&cid) {
b.unreferenced.insert((h.at, cid.clone()));
}
if let Some(t) = takedown {
crates/pds-server/src/cache.rs+314−13
@@ -9,7 +9,21 @@
//! checkpoint and log on its first use, a read or a write (`Slot`), and let
//! go when it has not been used for `IDLE`, or when the stores held count
//! more than the cache's share of `PDS_CACHE_BYTES`, least recently used
//! first. A store is let go only with nothing of it in flight: no write
//! first. A store counts what it holds in memory (`Store::cost`): its
//! table's index, where in the log each entry the log changed is, its
//! blobs, and of each space repo its commit and hash, not its records, which
//! are read from the table and the log as they are asked for.
//!
//! **A store being written** holds where each entry of its log after its
//! table is (its memtable), which grows with the log. Past an eighth of
//! the stores' share of the cache (`Cache::memtable`), its log is
//! compacted, whatever the log's size, and what the table then holds is
//! let go; past twice that while the compaction runs, a writer waits for
//! it (`Slot::write_lock`): written faster than its log can be compacted,
//! a store holds no more for it. The compaction holds as much again of
//! the logs it folds, with the account's state and a few blocks
//! (`Cache::fold_blocks`), counted with the store while it runs
//! (`Slot::folding`). A store is let go only with nothing of it in flight: no write
//! waiting for its log to be on disk, no compaction of its log, no upload
//! moving into place. Everything it holds is on disk by then, so letting it
//! go is dropping it.
@@ -42,6 +56,10 @@ pub(crate) const IDLE: Duration = Duration::from_secs(120);
/// The service log's entry of an account's mark and handle.
pub(crate) const DIR: &str = "dir";
/// The bytes a record taken down is counted as in the cache: its path and
/// its takedown's reference.
const TAKEDOWN_COST: u64 = 192;
/// What every account's slot shares: where the files are, and what loading
/// a store needs.
pub(crate) struct Ctx {
@@ -171,9 +189,21 @@ impl Store {
}
/// The bytes it is counted as in the cache: what it holds in memory,
/// not the blocks it reads, which the block cache counts.
fn cost(&self) -> u64 {
4096 + self.repo.head_bytes().len() as u64 + self.disk.cost() + self.blobs.cost()
/// not the blocks it reads, which the block cache counts, nor what a
/// compaction of its log holds, which its slot counts with it. Its table's
/// index and what the memtable keeps of the log after it, its blobs,
/// each space repo's commit and hash, the spaces it is the authority
/// of, its write notifications and its records taken down: each a
/// total kept as it changes, but the records' blob refs, which are
/// walked.
pub(crate) fn cost(&self) -> u64 {
4096 + self.repo.head_bytes().len() as u64
+ self.disk.cost()
+ self.blobs.cost()
+ self.spaces.cost()
+ self.authority.cost()
+ self.notify.cost()
+ self.takedowns.len() as u64 * TAKEDOWN_COST
}
}
@@ -185,6 +215,10 @@ pub(crate) struct Cache {
held: Mutex<Held>,
}
/// The least a store's memtable may count before its log is compacted for
/// what it counts, however small the cache.
const MEMTABLE_FLOOR: u64 = 256 << 10;
#[derive(Default)]
struct Held {
slots: HashMap<String, Weak<Account>>,
@@ -199,6 +233,32 @@ impl Cache {
}
}
/// What one store's memtable may count before its log is compacted,
/// whatever the log's size: an eighth of the stores' share of the cache.
/// A store being written holds where each entry of its log after its
/// table is, and its log grows to its table's size before it is
/// compacted for that (`store::policy`): past this, it is compacted
/// for what it holds in memory.
pub fn memtable(&self) -> u64 {
(self.budget / 8).max(MEMTABLE_FLOOR)
}
/// What one store's memtable may count while its log is compacted
/// before a writer waits for the compaction: twice `memtable`. So a
/// store written faster than its log is compacted holds no more than
/// this and one write of its log, and the compaction as much again of
/// the logs it folds: half the stores' share in all.
pub fn memtable_most(&self) -> u64 {
self.memtable() * 2
}
/// The bytes a fold of an account's log may keep of what it reads to
/// read it again: the places of its frames' items, and the table's
/// blocks it looks records up in.
pub fn fold_blocks(&self) -> u64 {
(self.budget / 8).clamp(1 << 20, 4 << 20)
}
/// The bytes the stores held count.
#[cfg(test)]
pub fn bytes(&self) -> u64 {
@@ -326,6 +386,9 @@ pub(crate) struct Slot {
used: AtomicU64,
/// The bytes the store held counts, `0` if none is.
cost: AtomicU64,
/// The bytes a compaction of its log under way holds, counted with its
/// store's: `0` with none.
folding: AtomicU64,
}
/// An account's store, read.
@@ -366,7 +429,14 @@ impl DerefMut for StoreWrite<'_> {
impl Drop for StoreWrite<'_> {
fn drop(&mut self) {
let Some(g) = self.guard.take() else { return };
let cost = g.as_ref().map_or(0, |st| st.cost());
let cost = g.as_ref().map_or(0, |st| {
// More of its log held in memory than its share of the cache:
// compacted now, whatever the log's size.
if st.disk.mem.cost() > self.slot.ctx.cache.memtable() {
st.wal.compact_soon();
}
st.cost()
});
drop(g);
self.slot.recount(cost);
}
@@ -391,6 +461,7 @@ impl Slot {
store: RwLock::new(None),
used: AtomicU64::new(clock()),
cost: AtomicU64::new(0),
folding: AtomicU64::new(0),
};
if let Some(st) = store {
slot.compacted(&st);
@@ -405,11 +476,18 @@ impl Slot {
did: st.repo.did.clone(),
key: self.key.get().clone(),
window: self.ctx.window,
blocks: self.ctx.cache.fold_blocks(),
account: self.account.clone(),
};
st.wal.set_fold(Arc::new(fold));
}
/// A compaction of its log holds `bytes` in memory now: counted with
/// its store's when that is next counted.
pub fn folding(&self, bytes: u64) {
self.folding.store(bytes, Ordering::Relaxed);
}
/// Count a store made with the account in the cache, once the account is in its `Arc`.
pub fn counted(&self) {
let cost = crate::read(&self.store).as_ref().map_or(0, |st| st.cost());
@@ -532,8 +610,13 @@ impl Slot {
}
}
/// The store's cost now `cost`: counted in the cache.
/// The store's cost now `cost`: counted in the cache, with what a
/// compaction of its log holds.
fn recount(&self, cost: u64) {
let cost = match cost {
0 => 0,
held => held + self.folding.load(Ordering::Relaxed),
};
let before = self.cost.swap(cost, Ordering::Relaxed);
if before == cost {
return;
@@ -595,22 +678,50 @@ impl Locked for Slot {
}
}
/// A writer of a store whose memtable counts more than
/// `Cache::memtable_most` while its log is compacted waits for the
/// compaction, which lets go of what it folded: what a store being
/// written holds does not follow how fast the writes come
/// (`spec/STORE.md`, "Bounds"). The wait gives up its place among the
/// runtime's workers, so that other requests go on meanwhile.
fn write_lock(&self) -> StoreWrite<'_> {
let most = self.ctx.cache.memtable_most();
loop {
self.used.store(clock(), Ordering::Relaxed);
let g = crate::write(&self.store);
if g.is_some() {
return StoreWrite {
guard: Some(g),
slot: self,
};
match g.as_deref() {
Some(st) if st.disk.mem.cost() > most && st.wal.compacting() => {
let wal = st.wal.clone();
drop(g);
off_worker(|| wal.wait_compacted());
}
Some(_) => {
return StoreWrite {
guard: Some(g),
slot: self,
};
}
None => {
drop(g);
self.ensure();
}
}
drop(g);
self.ensure();
}
}
}
/// Run `wait`, which may block for long, without holding one of a
/// multi-threaded runtime's workers through it.
fn off_worker(wait: impl FnOnce()) {
use tokio::runtime::{Handle, RuntimeFlavor};
match Handle::try_current() {
Ok(h) if h.runtime_flavor() == RuntimeFlavor::MultiThread => {
tokio::task::block_in_place(wait)
}
_ => wait(),
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -1024,4 +1135,194 @@ mod tests {
);
let _ = std::fs::remove_dir_all(&dir);
}
/// The memtable of `did`'s store: what it counts, and whether its log
/// is being compacted.
fn memtable(s: &crate::Service, did: &str) -> (u64, bool) {
store_of(s, did, |st| (st.disk.mem.cost(), st.wal.compacting()))
}
/// A batch of space records written to `did`'s repo in a space of
/// another's, each of a key no other has.
async fn space_batch(s: &crate::Shared, did: &str, token: &str, batch: usize) {
let space = "at://did:plc:ewvi7nxzyoun6zhxrhs64oiz/space/com.example.forum/main";
let writes: Vec<Json> = (0..50)
.map(|i| json!({ "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": format!("b{batch:04}r{i:02}"), "value": record(i) }))
.collect();
let body = json!({ "space": space, "repo": did, "writes": writes });
call(s, "com.atproto.space.applyWrites", Some(token), body)
.await
.unwrap();
}
/// A batch of records written to `did`'s repository, each of a key no
/// other has.
async fn repo_batch(s: &crate::Shared, did: &str, token: &str, batch: usize) {
let writes: Vec<Json> = (0..50)
.map(|i| json!({ "$type": "com.atproto.repo.applyWrites#create", "collection": "a.b.c", "rkey": format!("b{batch:04}r{i:02}"), "value": record(i) }))
.collect();
let body = json!({ "repo": did, "writes": writes });
call(s, "com.atproto.repo.applyWrites", Some(token), body)
.await
.unwrap();
}
/// A store's log is compacted for what its memtable counts, whatever
/// the log's size: written without a pause, the memtable never counts
/// more than `memtable_most` and one write, the store with a
/// compaction's share no more than the cache gives a store being
/// written, and every record is read back, after a start too.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_store_being_written_stays_within_its_share() {
let plc = plc().await;
let dir = scratch("memtable-share");
// Never compacted for its log's size.
let opened = || {
open_with(&dir, &plc, |c| {
(c.load_all, c.cache_bytes, c.log_floor) = (false, 2 << 20, 1 << 30)
})
};
let s = opened();
let (did, token) = create(&s, "alice").await;
let (soft, most) = (s.ctx.cache.memtable(), s.ctx.cache.memtable_most());
assert_eq!((soft, most), (256 << 10, 512 << 10));
space_batch(&s, &did, &token, 0).await;
let one = memtable(&s, &did).0;
let (mut peak, mut compactions, mut last) = (0, 0, 0);
for batch in 1..120 {
space_batch(&s, &did, &token, batch).await;
let (cost, _) = memtable(&s, &did);
peak = peak.max(cost);
assert!(cost <= most + one, "batch {batch}: {cost}");
let generation = store_of(&s, &did, |st| st.wal.checkpoint_generation());
compactions += u64::from(generation != last);
last = generation;
}
assert!(peak > soft, "{peak}");
assert!(compactions >= 4, "{compactions}");
let wal = store_of(&s, &did, |st| st.wal.clone());
wal.wait_compacted();
assert!(wal.log_bytes() < 1 << 30);
drop(wal);
let listed = |s: &crate::Shared| {
let (s, did, token) = (s.clone(), did.clone(), token.clone());
async move {
let space = "at://did:plc:ewvi7nxzyoun6zhxrhs64oiz/space/com.example.forum/main";
let mut n = 0;
let mut cursor: Option<String> = None;
loop {
let mut p = vec![
("space".to_string(), space.to_string()),
("repo".to_string(), did.clone()),
("limit".to_string(), "1000".to_string()),
];
p.extend(cursor.take().map(|c| ("cursor".to_string(), c)));
let got = call_with(
&s,
"com.atproto.space.listRecords",
Some(&token),
&p,
Json::Null,
)
.await
.unwrap();
n += got["records"].as_array().unwrap().len();
match got["cursor"].as_str() {
Some(c) => cursor = Some(c.to_string()),
None => return n,
}
}
}
};
assert_eq!(listed(&s).await, 120 * 50);
crate::space_notify::tests::idle(&s).await;
drop(s);
assert_eq!(listed(&opened()).await, 120 * 50);
let _ = std::fs::remove_dir_all(&dir);
}
/// An account's fold that waits for word before it folds, the first
/// time; then folds as the account's does.
struct Waits {
fold: crate::checkpoint::AccountFold,
word: Mutex<std::sync::mpsc::Receiver<()>>,
}
impl pds_store::Fold for Waits {
fn fold_files(
&self,
checkpoint: Option<&std::path::Path>,
logs: &[PathBuf],
generation: u64,
out: &mut dyn std::io::Write,
) -> Result<(), String> {
let _ = lock(&self.word).recv();
self.fold.fold_files(checkpoint, logs, generation, out)
}
fn install(
&self,
generation: u64,
rename: &mut dyn FnMut() -> Result<(), String>,
) -> Result<(), String> {
self.fold.install(generation, rename)
}
}
/// A compaction that cannot keep up: while it runs, writes go on until
/// the memtable counts more than `memtable_most`; the next writer waits
/// for the compaction, and writes once it has let go of what it folded.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_writer_waits_for_a_compaction_that_cannot_keep_up() {
let plc = plc().await;
let dir = scratch("memtable-waits");
let s = open_with(&dir, &plc, |c| {
(c.load_all, c.cache_bytes, c.log_floor) = (false, 2 << 20, 1 << 30)
});
let (did, token) = create(&s, "alice").await;
let a = s.account(&did).unwrap();
let (go, word) = std::sync::mpsc::channel();
store_of(&s, &did, |st| {
let fold = crate::checkpoint::AccountFold {
did: did.clone(),
key: a.store.key.get().clone(),
window: s.ctx.window,
blocks: s.ctx.cache.fold_blocks(),
account: Arc::downgrade(&a),
};
st.wal.set_fold(Arc::new(Waits {
fold,
word: Mutex::new(word),
}));
});
let most = s.ctx.cache.memtable_most();
// Past its share, a compaction starts, and waits; writes go on.
let mut batch = 0;
while memtable(&s, &did).0 <= most {
repo_batch(&s, &did, &token, batch).await;
batch += 1;
}
assert!(memtable(&s, &did).1, "no compaction started");
let held = memtable(&s, &did).0;
// The next writer waits.
let writing = {
let (s, did, token) = (s.clone(), did.clone(), token.clone());
tokio::spawn(async move { repo_batch(&s, &did, &token, batch).await })
};
tokio::time::sleep(Duration::from_millis(300)).await;
assert!(!writing.is_finished(), "a writer did not wait");
assert_eq!(memtable(&s, &did), (held, true));
// A read does not.
let p = [("did".to_string(), did.clone())];
call_with(&s, "com.atproto.sync.getLatestCommit", None, &p, Json::Null)
.await
.unwrap();
go.send(()).unwrap();
drop(go);
writing.await.unwrap();
// What the compaction folded is let go, and the write is there.
assert!(memtable(&s, &did).0 < held);
assert!(store_of(&s, &did, |st| st.wal.checkpoint_generation()) > 0);
let _ = std::fs::remove_dir_all(&dir);
}
}
crates/pds-server/src/checkpoint.rs+545−312
857 lines changed: not loaded until asked for.
crates/pds-server/src/federation.rs+1−1
@@ -227,7 +227,7 @@ mod tests {
Ok(Resp::Nothing) => panic!("{nsid} answered nothing"),
Ok(Resp::Blob(_)) => panic!("{nsid} answered a blob"),
Ok(Resp::Upstream(_)) => panic!("{nsid} was forwarded"),
Ok(Resp::Octets(_) | Resp::HeadedOctets(..)) => panic!("{nsid} answered an archive"),
Ok(Resp::Octets(_) | Resp::Archive(..)) => panic!("{nsid} answered an archive"),
Err(e) => Err(e.name.to_string()),
}
}
crates/pds-server/src/lib.rs+5−13
@@ -512,9 +512,9 @@ enum Resp {
Headed(Json, Vec<(&'static str, String)>),
/// Bytes as `application/octet-stream`, as a space meta archive.
Octets(Vec<u8>),
/// Bytes as `application/octet-stream`, with headers of their own, as a
/// space repo's archive with its MAC.
HeadedOctets(Vec<u8>, Vec<(&'static str, String)>),
/// A space repo's archive, read as it is sent (`space_repo::Archive`),
/// with headers of its own, as its commit's MAC.
Archive(space_repo::Archive, Vec<(&'static str, String)>),
}
/// An error as XRPC answers it: an HTTP status, a name and a message.
@@ -908,15 +908,7 @@ fn respond(answer: Result<Resp, XrpcError>, charged: Option<&limits::Charged>) -
b,
)
.into_response(),
Ok(Resp::HeadedOctets(b, headers)) => with_headers(
(
StatusCode::OK,
[(header::CONTENT_TYPE, "application/octet-stream")],
b,
)
.into_response(),
headers,
),
Ok(Resp::Archive(a, headers)) => with_headers(a.response(), headers),
Err(e) => (
StatusCode::from_u16(e.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
[(header::CONTENT_TYPE, "application/json")],
@@ -1484,7 +1476,7 @@ mod testing {
match answer(s, &call).await {
Ok(Resp::Json(j) | Resp::Headed(j, _)) => Ok(j),
Ok(Resp::Car(_) | Resp::CarStream(_)) => Err("a CAR file".into()),
Ok(Resp::Octets(_) | Resp::HeadedOctets(..)) => Err("bytes".into()),
Ok(Resp::Octets(_) | Resp::Archive(..)) => Err("bytes".into()),
Ok(Resp::Nothing) => Ok(Json::Null),
Ok(Resp::Blob(_)) => Err("a blob".into()),
// A service's answer: its JSON, or for an error, its name.
crates/pds-server/src/log.rs+331−9
@@ -2899,7 +2899,7 @@ mod tests {
did.clone(),
format!(
"{:?}",
crate::space_repo::tests::snapshot(&crate::read(&a.store).spaces)
crate::space_repo::tests::snapshot(&crate::read(&a.store))
),
)
})
@@ -2916,10 +2916,22 @@ mod tests {
/// keep it in the retry queue (`space_notify`), which this does not cut.
#[tokio::test]
async fn torn_space_writes_recover_to_before_or_after() {
torn_space_writes("log", false).await;
}
/// The same of an account's log after a table that holds space repos:
/// each commit replayed reads the records it replaces from the table,
/// and a `clearRecords` and an import void what the table holds.
#[tokio::test]
async fn torn_space_writes_after_a_table() {
torn_space_writes("table", true).await;
}
async fn torn_space_writes(name: &str, table: bool) {
use crate::space_notify::tests::idle;
use crate::space_repo::tests::{SPACE, w};
let plc = plc().await;
let dir = scratch("torn-space-src");
let dir = scratch(&format!("torn-space-src-{name}"));
let s = open(&dir, &plc);
let (a, ta) = create(&s, "alice").await;
let (b, tb) = create(&s, "bob").await;
@@ -2932,8 +2944,19 @@ mod tests {
got
}
};
let mut steps = vec![snap(&s)];
let rec = |did: &str, rkey: &str, n: i64| json!({ "space": SPACE, "repo": did, "collection": "a.b.c", "rkey": rkey, "record": record(n) });
if table {
for (did, token, rkey) in [(&a, &ta, "zero"), (&b, &tb, "zero"), (&b, &tb, "one")] {
w(&s, "putRecord", token, rec(did, rkey, 0)).await.unwrap();
}
for did in [&a, &b] {
let wal = crate::read(&s.account(did).unwrap().store).wal.clone();
wal.compact().unwrap();
let layout = crate::store::account_layout(&dir, did);
assert!(layout.checkpoint().exists());
}
}
let mut steps = vec![snap(&s)];
w(&s, "createRecord", &ta, rec(&a, "one", 1)).await.unwrap();
steps.push(snap(&s));
w(&s, "putRecord", &tb, rec(&b, "one", 2)).await.unwrap();
@@ -2988,10 +3011,10 @@ mod tests {
charged: Default::default(),
http: None,
};
let Ok(crate::Resp::HeadedOctets(archive, _)) = crate::answer(&s, &get).await else {
let Ok(crate::Resp::Archive(archive, _)) = crate::answer(&s, &get).await else {
panic!("getRepo answered no archive")
};
archive
archive.bytes().unwrap()
};
let mut headers = axum::http::HeaderMap::new();
headers.insert(
@@ -3026,7 +3049,7 @@ mod tests {
.unwrap();
assert_eq!(files(&dir), steps.last().unwrap().0);
drop(s);
let work = scratch("torn-space-work");
let work = scratch(&format!("torn-space-work-{name}"));
let mut cuts = 0;
for (i, win) in steps.windows(2).enumerate() {
let ((before_files, before), (after_files, after)) = (&win[0], &win[1]);
@@ -3088,7 +3111,7 @@ mod tests {
}
assert!(cuts > 500, "{cuts}");
// A space commit whose records do not make its data is refused.
let alice = repo_log(Path::new(""), &a);
let alice = changed_logs(&steps[0].0, &steps[1].0)[0].clone();
let last = &steps.last().unwrap().0;
let mut frames = store::scan(&last[&alice]).0;
let entry = frames
@@ -3326,15 +3349,47 @@ mod tests {
/// A compaction killed at each step of `spec/STORE.md`'s crash table,
/// with the writes of every file it had not made durable lost: an
/// account's log, then the service log, each with a write after its seal.
/// Every start recovers the state before the compaction, or with that
/// write too where all of it is in the new log.
/// The account's table and its log hold space repos, which the fold
/// merges with what the log voids of them. Every start recovers the
/// state before the compaction, or with that write too where all of it
/// is in the new log.
#[tokio::test]
async fn compaction_killed_at_every_step() {
let plc = plc().await;
let dir = scratch("compact-killed");
let (_, accounts) = script(&dir, &plc).await;
let (a, ta) = &accounts[0];
// The account's space repos: in its table, and in its log after it,
// which writes over the table's records, deletes one and clears a repo.
{
use crate::space_notify::tests::idle;
use crate::space_repo::tests::{SPACE, w};
let other = "at://did:web:example.com/space/com.example.chat/room";
let s = open(&dir, &plc);
let rec = |space: &str, rkey: &str, n: i64| json!({ "space": space, "repo": a, "collection": "a.b.c", "rkey": rkey, "record": record(n) });
for (space, rkey, n) in [(SPACE, "one", 1), (SPACE, "two", 2), (other, "one", 3)] {
w(&s, "putRecord", ta, rec(space, rkey, n)).await.unwrap();
}
idle(&s).await;
let wal = crate::read(&s.account(a).unwrap().store).wal.clone();
wal.compact().unwrap();
drop(wal);
w(&s, "putRecord", ta, rec(SPACE, "two", 22)).await.unwrap();
w(&s, "putRecord", ta, rec(SPACE, "three", 3))
.await
.unwrap();
let gone = json!({ "space": SPACE, "repo": a, "collection": "a.b.c", "rkey": "one" });
w(&s, "deleteRecord", ta, gone).await.unwrap();
w(&s, "clearRecords", ta, json!({ "space": other, "repo": a }))
.await
.unwrap();
w(&s, "putRecord", ta, rec(other, "after", 4))
.await
.unwrap();
idle(&s).await;
}
let work = scratch("compact-killed-work");
let state = with_spaces;
for which in ["account", "service"] {
let s = open(&dir, &plc);
let before = (files(&dir), state(&s));
@@ -3387,6 +3442,10 @@ mod tests {
.collect();
let with = |logs: &[(&PathBuf, &[u8])]| {
let mut f = base.clone();
// The table before, if it had one.
if let Some(table) = before.0.get(&ckpt) {
f.insert(ckpt.clone(), table.clone());
}
for (p, b) in logs {
f.insert((*p).clone(), b.to_vec());
}
@@ -3455,6 +3514,269 @@ mod tests {
let _ = std::fs::remove_dir_all(&work);
}
/// Everything a restart must carry over of the accounts, with each
/// one's space repos, the spaces it is the authority of, and its write
/// notifications.
fn with_all(s: &Service) -> (State, BTreeMap<String, String>, BTreeMap<String, String>) {
let kept = crate::read(&s.directory)
.by_did
.iter()
.map(|(did, a)| {
let st = crate::read(&a.store);
(did.clone(), format!("{:?}", (&st.authority, &st.notify)))
})
.collect();
let (state, spaces) = with_spaces(s);
(state, spaces, kept)
}
/// Account tables of the version before, with space repos, blobs, the
/// spaces an account is the authority of and write notifications in
/// their `S`, and logs after them as that version wrote them: the first
/// load of each folds it into a table of this version, once, and serves
/// all of it, the same wherever the fold was cut short, when the server
/// is started again, and when each account is loaded as it is first
/// asked for; and takes writes after.
#[tokio::test]
async fn a_table_of_the_version_before_is_folded_once() {
use crate::space_notify::tests::idle;
use crate::space_repo::tests::{SPACE, w};
let plc = plc().await;
let dir = scratch("before-src");
let s = open(&dir, &plc);
let (a, ta) = create(&s, "alice").await;
let (b, tb) = create(&s, "bob").await;
// An account no start loads: nothing of its is waiting to be sent.
let (c, tc) = create(&s, "carol").await;
let (one, two) = (
b"spec-pds before one".to_vec(),
b"spec-pds before two".to_vec(),
);
let mut refs = Vec::new();
for body in [&one, &two] {
let up =
crate::blobs::test_upload(&s, Some(&ta), Some("text/plain"), body.clone(), false)
.await
.unwrap();
refs.push(up["blob"].clone());
}
let made = call(&s, "com.atproto.space.createSpace", Some(&ta), json!({ "spaceType": "com.example.forum", "skey": "mine", "policy": { "$type": crate::space_authority::MEMBER, "publishPolicy": true, "publishMembers": true } }))
.await
.unwrap();
let mine = made["uri"].as_str().unwrap().to_string();
let member = |did: &str, write: bool| json!({ "space": mine, "did": did, "read": true, "write": write });
call(
&s,
"com.atproto.memberspace.putMember",
Some(&ta),
member(&b, true),
)
.await
.unwrap();
let rec = |space: &str, did: &str, rkey: &str, record: Json| json!({ "space": space, "repo": did, "collection": "a.b.c", "rkey": rkey, "record": record });
let public = |rkey: &str, record: Json| json!({ "repo": a, "collection": "a.b.c", "rkey": rkey, "record": record });
call(
&s,
"com.atproto.repo.putRecord",
Some(&ta),
public("pic", json!({ "img": refs[0] })),
)
.await
.unwrap();
for (space, rkey, record) in [
(SPACE, "one", record(1)),
(SPACE, "two", json!({ "img": refs[1] })),
(mine.as_str(), "one", record(3)),
(mine.as_str(), "two", record(4)),
] {
w(&s, "putRecord", &ta, rec(space, &a, rkey, record))
.await
.unwrap();
}
w(
&s,
"deleteRecord",
&ta,
json!({ "space": mine, "repo": a, "collection": "a.b.c", "rkey": "two" }),
)
.await
.unwrap();
for rkey in ["one", "zero"] {
w(&s, "putRecord", &tb, rec(SPACE, &b, rkey, record(5)))
.await
.unwrap();
}
let carols =
json!({ "repo": c, "collection": "a.b.c", "rkey": "one", "record": record(1) });
call(&s, "com.atproto.repo.putRecord", Some(&tc), carols)
.await
.unwrap();
idle(&s).await;
// The tables, then the logs after them.
for did in [&a, &b, &c] {
let wal = crate::read(&s.account(did).unwrap().store).wal.clone();
wal.compact().unwrap();
}
w(&s, "putRecord", &ta, rec(SPACE, &a, "one", record(11)))
.await
.unwrap();
w(
&s,
"putRecord",
&ta,
rec(SPACE, &a, "three", json!({ "img": refs[1] })),
)
.await
.unwrap();
w(
&s,
"deleteRecord",
&ta,
json!({ "space": SPACE, "repo": a, "collection": "a.b.c", "rkey": "two" }),
)
.await
.unwrap();
w(&s, "putRecord", &ta, rec(&mine, &a, "five", record(5)))
.await
.unwrap();
call(
&s,
"com.atproto.memberspace.putMember",
Some(&ta),
member("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", false),
)
.await
.unwrap();
call(
&s,
"com.atproto.repo.putRecord",
Some(&ta),
public("after", record(2)),
)
.await
.unwrap();
w(&s, "putRecord", &tb, rec(SPACE, &b, "one", record(6)))
.await
.unwrap();
w(
&s,
"clearRecords",
&tb,
json!({ "space": SPACE, "repo": b }),
)
.await
.unwrap();
w(&s, "putRecord", &tb, rec(SPACE, &b, "after", record(7)))
.await
.unwrap();
idle(&s).await;
let want = with_all(&s);
let g = crate::read(&s.account(&a).unwrap().store).wal.generation();
drop(s);
// As the version before left them: its tables, and a `clearRecords`
// that names each record it deletes.
for did in [&a, &b, &c] {
let layout = crate::store::account_layout(&dir, did);
crate::checkpoint::downgrade(&layout.checkpoint());
let log = layout.log(g);
let mut frames = store::scan(&std::fs::read(&log).unwrap()).0;
for e in frames.iter_mut().flatten() {
if e.get("kept") == Some(&json!([])) {
e.as_object_mut().unwrap().remove("kept");
e["dels"] = json!(["a.b.c/one", "a.b.c/zero"]);
}
}
let bytes: Vec<u8> = frames.iter().flat_map(|f| store::frame(f)).collect();
std::fs::write(&log, bytes).unwrap();
}
let before = files(&dir);
let layout = crate::store::account_layout(Path::new(""), &a);
let (old, new, ckpt) = (layout.log(g), layout.log(g + 1), layout.checkpoint());
assert!(!store::scan(&before[&old]).0.is_empty());
// Folded on its first load, and served.
let work = scratch("before-work");
put_files(&work, &before);
let s = open(&work, &plc);
assert!(with_all(&s) == want, "folded");
drop(s);
let folded = files(&work);
assert!(!folded.contains_key(&old) && folded.contains_key(&new));
assert!(folded[&ckpt] != before[&ckpt]);
// Once: a start after it reads the table it made, and writes go on.
let s = open(&work, &plc);
assert!(with_all(&s) == want, "started again");
assert!(files(&work)[&ckpt] == folded[&ckpt]);
w(&s, "putRecord", &ta, rec(SPACE, &a, "later", record(8)))
.await
.unwrap();
w(&s, "putRecord", &tb, rec(SPACE, &b, "zero", record(9)))
.await
.unwrap();
idle(&s).await;
let later = with_all(&s);
assert!(later != want);
drop(s);
assert!(with_all(&open(&work, &plc)) == later, "written after");
// An account not loaded at the start: its table has no header to
// find its events by, so it is loaded for them, and folded then.
put_files(&work, &before);
let s = open_with(&work, &plc, |c| c.load_all = false);
assert!(!s.account(&c).is_some_and(|a| a.store.is_loaded()));
assert!(crate::checkpoint::events_on_disk(&s.ctx, &c).is_err());
s.events.find_old(&s);
for did in [&a, &b, &c] {
assert!(s.by_did(did).is_some());
}
assert!(with_all(&s) == want, "loaded as first asked for");
drop(s);
// The fold cut at every step: the seal at every byte, the next log
// made or not, the table written in part, put in place, and the log
// it covers deleted or not.
let check = |files: BTreeMap<PathBuf, Vec<u8>>, why: String| {
put_files(&work, &files);
let s = open(&work, &plc);
assert!(with_all(&s) == want, "{why}");
drop(s);
assert!(with_all(&open(&work, &plc)) == want, "{why}, started twice");
};
let with = |logs: &[(&PathBuf, &[u8])]| {
let mut f = before.clone();
for (p, b) in logs {
f.insert((*p).clone(), b.to_vec());
}
f
};
let mut sealed = before[&old].clone();
sealed.extend(seal());
for cut in 0..seal().len() {
check(
with(&[(&old, &sealed[..before[&old].len() + cut])]),
format!("the seal cut at {cut}"),
);
}
check(with(&[(&old, &sealed)]), "sealed, no next log".into());
check(
with(&[(&old, &sealed), (&new, &[])]),
"sealed, the next log made".into(),
);
let bytes = &folded[&ckpt];
for at in (0..bytes.len())
.step_by((bytes.len() / 9).max(1))
.chain([bytes.len()])
{
let mut f = with(&[(&old, &sealed), (&new, &[])]);
f.insert(layout.tmp(), bytes[..at].to_vec());
check(f, format!("the .tmp cut at {at}"));
}
let mut f = with(&[(&old, &sealed), (&new, &[])]);
f.insert(ckpt.clone(), bytes.clone());
check(f.clone(), "put in place".into());
f.remove(&old);
check(f, "the log it covers deleted".into());
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&work);
}
/// The state of a server that loads each account when it is first
/// asked for, once every account `want` holds is: none is loaded
/// before.
crates/pds-server/src/mcp.rs+1−1
@@ -750,7 +750,7 @@ async fn call_tool(
| Resp::Blob(_)
| Resp::Nothing
| Resp::Octets(_)
| Resp::HeadedOctets(..),
| Resp::Archive(..),
) => (
json!({ "error": "InternalServerError", "message": "a tool's method answered no JSON" }),
true,
crates/pds-server/src/space_authority.rs+60−25
@@ -248,6 +248,8 @@ enum Held {
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Authority {
spaces: BTreeMap<String, Held>,
/// The bytes all of it is counted as in the cache.
cost: u64,
}
impl Authority {
@@ -286,6 +288,32 @@ impl Authority {
self.apply(e).map_err(|why| format!("{why}: {e}"))
}
/// About the bytes it holds in memory: a total kept as its spaces change.
pub(crate) fn cost(&self) -> u64 {
self.cost
}
/// About the bytes the space `uri` takes in memory, by how many
/// members, writers and allowed apps it has: `0` if it holds none of it.
fn cost_of(&self, uri: &str) -> u64 {
let held = match self.spaces.get(uri) {
None => return 0,
Some(Held::Deleted) => 0,
Some(Held::Live(s)) => {
let policy = match &s.policy {
Policy::Member {
allowed_apps: Some(apps),
..
} => apps.len() * 96,
Policy::Managed { managing_app, .. } => managing_app.len(),
_ => 0,
};
160 + policy + s.members.len() * 144 + s.writers.len() * 256
}
};
(uri.len() + 96 + held) as u64
}
/// Each space as a checkpoint keeps it, in ascending order of URI: a
/// live one's archive, as `exportSpaceMeta` answers it, or None for one deleted.
pub(crate) fn saved(&self) -> impl Iterator<Item = (&str, Option<Vec<u8>>)> {
@@ -334,12 +362,22 @@ impl Authority {
}
};
self.spaces.insert(uri.to_string(), held);
self.cost += self.cost_of(uri);
Ok(())
}
/// Make the change an entry records. A change is checked before it is
/// logged, so one logged applies as it did.
/// Make the change an entry records, and count what it leaves of its
/// space. A change is checked before it is logged, so one logged
/// applies as it did.
fn apply(&mut self, e: &Json) -> Result<(), String> {
let uri = e["space"].as_str().unwrap_or_default();
let before = self.cost_of(uri);
let done = self.change(e);
self.cost = self.cost - before + self.cost_of(uri);
done
}
fn change(&mut self, e: &Json) -> Result<(), String> {
let text = |k: &str| e[k].as_str().ok_or_else(|| format!("no {k}"));
let flag = |k: &str| e[k].as_bool().ok_or_else(|| format!("no {k}"));
let policy =
@@ -506,6 +544,9 @@ pub(crate) enum Publication {
pub(crate) trait Publisher {
/// The record keys of `collection` in the authority's repo in `space`.
fn rkeys(&self, st: &Store, space: &SpaceRef, collection: &str) -> Vec<String>;
/// Whether the authority's repo in `space` holds a record of
/// `collection` at `rkey`.
fn holds(&self, st: &Store, space: &SpaceRef, collection: &str, rkey: &str) -> bool;
/// One commit of the authority's repo in `space`, making these changes
/// in order, as any write of that repo is made: its log entry, and the
/// commit. Never called with none.
@@ -694,24 +735,27 @@ async fn change<T>(
let mut st = write(&a.store);
let out = f(&mut st, &mut frame)?;
if !frame.entries.is_empty() {
if let Err(e) =
crate::blobstore::mark_for(&st).and_then(|()| st.wal.append(&frame.entries))
let pos = match crate::blobstore::mark_for(&st)
.and_then(|()| crate::space_repo::append(&st, &frame.entries))
{
crate::ops::failed_for(
crate::ops::Level::Error,
"a change to spaces failed",
&a.did,
e,
);
return crate::internal();
}
Ok(pos) => pos,
Err(e) => {
crate::ops::failed_for(
crate::ops::Level::Error,
"a change to spaces failed",
&a.did,
e,
);
return crate::internal();
}
};
for c in &frame.changes {
st.authority
.apply(c)
.expect("a change checked before it is logged");
}
for s in std::mem::take(&mut frame.staged) {
s.apply(&mut st);
s.apply(&mut st, pos);
}
for e in &frame.notices {
st.notify
@@ -860,11 +904,7 @@ async fn update_space(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp,
let mut ops = Vec::new();
if policy.publishes_policy() {
ops.push(put_policy(&policy));
} else if publisher
.rkeys(st, &sr, POLICY_RECORD)
.iter()
.any(|k| k == "self")
{
} else if publisher.holds(st, &sr, POLICY_RECORD, "self") {
ops.push(Publication::Delete {
collection: POLICY_RECORD,
rkey: "self".into(),
@@ -1000,8 +1040,7 @@ async fn remove_member(svc: &Shared, call: &Call<'_>, m: &Method) -> Result<Resp
if svc
.space_authority
.publisher
.rkeys(st, &sr, MEMBER_RECORD)
.contains(&rkey)
.holds(st, &sr, MEMBER_RECORD, &rkey)
{
publish(
svc,
@@ -2191,11 +2230,7 @@ mod tests {
let records = |space: &str| {
let a = s.account(&alice).unwrap();
let st = crate::read(&a.store);
st.spaces.get(space).map(|r| {
r.records()
.map(|(p, rec)| (p.to_string(), data::to_json(&rec.value)))
.collect::<BTreeMap<_, _>>()
})
st.space_values(space)
};
let web = "did:web:localhost%3A2583";
let record = |read: bool, write: bool| json!({ "$type": MEMBER_RECORD, "read": read, "write": write });
crates/pds-server/src/space_notify.rs+29−9
crates/pds-server/src/space_repo.rs+1901−511
A large diff, not shown.
crates/pds-server/src/store.rs+17−8
crates/pds-server/src/sync.rs+3−3
crates/pds-space/src/lthash.rs+14−0
crates/pds-store/src/generations.rs+73−6
docs/guide/comparing.md+3−1
harness/checks/scale.mjs+87−0
spec/STORE.md+20−4