Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/daemon-adopt-read-buffers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
## Changed

- The desktop daemon uses smaller read buffers when turning on sync for a folder of existing notes.
43 changes: 40 additions & 3 deletions runtime/crates/daemon/examples/adopt_rehearsal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,18 @@
//! can kill -9 the adopter at any point and check that a rerun converges.
//!
//! ```text
//! logsvc --listen 127.0.0.1:7741 --testkit-cp conformance --insecure-test-keys &
//! mdbn-log-server --listen 127.0.0.1:7741 --testkit-cp conformance --insecure-test-keys &
//! export MDBASE_ENV=test MDBASE_SECRET_BACKEND=insecure-test-file
//! adopt_rehearsal setup --log http://127.0.0.1:7741 --dir <run> --docs 3000 [--cloud]
//! adopt_rehearsal read --dir <run> # time the inventory and bucket read passes
//! adopt_rehearsal adopt --dir <run> [--exit-when-done] # kill -9 it, run again
//! adopt_rehearsal verify --dir <run>
//! ```
//!
//! Secrets live in the insecure test file store under `<run>`; the example refuses
//! to run without both test variables (never the OS keychain).
//! to use the OS keychain. For optimized measurements, build the example with
//! `--release --config 'profile.release.package.mdbn-daemon.debug-assertions=true'`
//! so its test secret backend is available.
#![allow(clippy::disallowed_methods, clippy::disallowed_types)]

use std::collections::BTreeMap;
Expand Down Expand Up @@ -95,6 +98,40 @@ async fn main() {
p.private
);
}
"read" => {
use mdbn_daemon::adopt::FolderSource;
use mdbn_platform_native::{NativePlatform, OpenOptions};
use mdbn_replica::AdoptSource;
use mdbn_replica::replica::gen0::{Gen0Writer, bucket_bits};
use mdbn_wire::common::B16;
let p = plan(&dir);
let platform = NativePlatform::open(dir.join("a"), &OpenOptions::default()).unwrap();
let mut source = FolderSource::new(std::rc::Rc::new(platform), Default::default());
let start = Instant::now();
let mut read = |path: &str| source.read(path).unwrap().expect("seeded Markdown file");
let bytes = p
.records
.iter()
.map(|(_, path)| read(path).len() as u64)
.sum();
let inventory_ms = ms(start);
let writer = Gen0Writer::new(B16(p.collection), bucket_bits(bytes), false, false);
let mut records = p.adopt().records;
records.sort_unstable_by_key(|(id, _)| (writer.bucket_of(id), *id));
let start = Instant::now();
let mut max_capacity = 0u64;
for bucket in records.chunk_by(|a, b| writer.bucket_of(&a.0) == writer.bucket_of(&b.0))
{
let docs: Vec<_> = bucket.iter().map(|(_, path)| read(path)).collect();
let capacity = docs.iter().map(|doc| doc.capacity() as u64).sum();
max_capacity = max_capacity.max(capacity);
}
println!(
"READ inventory_ms={inventory_ms} buckets_ms={} records={} bytes={bytes} max_bucket_capacity={max_capacity}",
ms(start),
p.records.len()
);
}
"adopt" => {
let p = plan(&dir);
let rt = scenario::open(
Expand Down Expand Up @@ -198,6 +235,6 @@ async fn main() {
assert_eq!((st.holds, st.unresolved), (0, 0));
rt.stop().await;
}
_ => panic!("usage: adopt_rehearsal setup|adopt|verify --dir <run> ..."),
_ => panic!("usage: adopt_rehearsal setup|read|adopt|verify --dir <run> ..."),
}
}
57 changes: 47 additions & 10 deletions runtime/crates/daemon/src/adopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ pub const SCHEMA_VERSION: u32 = 1;
/// Larger files are left to ordinary ingest after the base (the replica's own
/// record-size admission is far below this).
const MAX_READ: u32 = 16 * 1024 * 1024;
const FIRST_READ: u32 = 16 * 1024;

/// The mode adopt creates the log in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
Expand Down Expand Up @@ -155,17 +156,26 @@ impl<P: FilePlatform> AdoptSource for FolderSource<P> {
if rel.is_root() {
return Ok(None);
}
// One bounded read of the opened regular file: a file larger than the
// cap is refused by what was read, not by an earlier stat.
match now(self.platform.read_range(&rel, 0, MAX_READ + 1)) {
Ok(b) if b.len() as u64 <= u64::from(MAX_READ) => Ok(String::from_utf8(b).ok()),
Ok(_) => Ok(None),
Err(e) if e.kind == FsErrorKind::Other || e.kind == FsErrorKind::Busy => {
Err(format!("read: {:?}", e.kind))
// A range reader can reserve the entire requested length. Start small;
// a short read proves EOF on that one confined file handle. Each retry
// rereads from zero so replacements cannot splice two files together.
// 16 KiB, 256 KiB, 4 MiB, then the admission limit plus its EOF probe.
let mut limit = FIRST_READ;
loop {
match now(self.platform.read_range(&rel, 0, limit)) {
Ok(mut bytes) if bytes.len() < limit as usize => {
// The sealer retains a bucket of documents at once.
bytes.shrink_to_fit();
return Ok(String::from_utf8(bytes).ok());
}
Ok(_) if limit < MAX_READ + 1 => limit = (limit * 16).min(MAX_READ + 1),
Ok(_) => return Ok(None),
Err(e) if e.kind == FsErrorKind::Other || e.kind == FsErrorKind::Busy => {
return Err(format!("read: {:?}", e.kind));
}
// Gone, a link or unreadable: left to ordinary ingest after the base.
Err(_) => return Ok(None),
}
// Gone, not a regular file, a link, or not ours to read: left to
// ordinary ingest after the base.
Err(_) => Ok(None),
}
}
}
Expand Down Expand Up @@ -221,6 +231,33 @@ mod tests {
assert!(p.fs.log().iter().any(|l| l.contains("read_range n/a.md")));
}

#[test]
fn filled_ranges_reread_the_current_file_from_zero_and_enforce_the_cap() {
use mdbn_store_file::platform::{CaseSensitivity, ReplaceStrategy};
use mdbn_store_file::testing::MemPlatform;
for size in [1, FIRST_READ, FIRST_READ + 1, MAX_READ, MAX_READ + 1] {
let p = Rc::new(MemPlatform::new(
ReplaceStrategy::Exchange,
CaseSensitivity::Sensitive,
));
p.fs.write_in_place("note.md", &vec![b'x'; FIRST_READ as usize])
.unwrap();
p.fs.before_op(1, move |fs| {
fs.write_in_place("note.md", &vec![b'y'; size as usize])
.unwrap();
});
let mut source = FolderSource::new(p, AdoptRecords::default());
let doc = source.read("note.md").unwrap();
if size <= MAX_READ {
let doc = doc.unwrap();
assert_eq!(doc.len(), size as usize);
assert!(doc.bytes().all(|b| b == b'y'));
} else {
assert_eq!(doc, None);
}
}
}

#[cfg(unix)]
#[test]
fn folder_source_never_follows_a_link_out_of_the_folder() {
Expand Down
Loading