Skip to main content

nibkeep_store/
stored.rs

1//! A space's log and sealed blobs, kept on disk.
2
3use std::cell::Cell;
4use std::collections::{BTreeMap, BTreeSet};
5use std::fs::{self, File};
6use std::io::{self, BufWriter, Read};
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10
11use getrandom::SysRng;
12use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
13use nibkeep_crypto::rand_core::{CryptoRng, UnwrapErr};
14use nibkeep_crypto::{BlobReader, Key, SigningKey, seal_blob};
15use nibkeep_log::{
16	ChangeId, History, Kept, Kind, Log, LogError, Parcel, Payload, Received, SealedPayload,
17	SpaceKeys, WrappedBlobKey, WrappedChangeKey, WrappedKey,
18};
19use nibkeep_model::{FieldName, Operation, Value, fields};
20use nibkeep_time::Clock;
21
22use crate::blobs::BlobFiles;
23use crate::file::{KeptRow, LogFile, PlaceCheck, StoredPage, StoredPageId, Writes};
24use crate::index::{self, Fields, Postings};
25use crate::lock::SpaceLock;
26use crate::state_file::{Savepoint, SpecialFields};
27use crate::{Found, StateFile, StoreError};
28
29/// The context of the key that seals the state file's own key, derived from the replica's
30/// storage key.
31const STATE_CONTEXT: &str = "nibkeep 2026-10 state file";
32
33/// A change that begins within this time of the last change saved belongs to a burst, such
34/// as an import that saves them one at a time: the state file takes in the changes of a
35/// burst in one transaction, which commits when a change comes later than that, when it
36/// holds [`PENDING_CHANGES`], when the space is used again more than [`PENDING_FOR`] after
37/// the first of them, before a batch begins, and when the space closes ([technical design:
38/// the state file]). A change made on its own commits the state file at once, as before, and so does
39/// each change while another program has the space open, which would wait meanwhile.
40///
41/// [technical design: the state file]: ../../../docs/Technical-design.md#75-the-state-file
42const BURST_GAP: Duration = Duration::from_millis(100);
43const PENDING_CHANGES: usize = 1_000;
44const PENDING_FOR: Duration = Duration::from_secs(1);
45
46/// The file in a space's folder that says that a program waits to make the state file anew
47/// alone, after a purge, until the other programs that have the space open close it
48/// ([technical design: several programs on one replica]): they see it at their next change, and close the space, which
49/// opens again once the state file is made anew.
50///
51/// [technical design: several programs on one replica]: ../../../docs/Technical-design.md#78-several-programs-on-one-replica
52const REMAKE: &str = "remake";
53
54/// How long a purge waits for the other programs that have the space open to close it.
55const PURGE_WAIT: Duration = Duration::from_secs(10);
56
57/// How often a purge looks whether the others closed the space.
58const PURGE_LOOK: Duration = Duration::from_millis(50);
59
60/// How many times a change catches up with what others wrote before it gives up, as when
61/// another program writes all the while.
62const CATCH_UP_TRIES: usize = 10;
63
64/// Where a stored log reads the time that tells the changes of a burst from changes made one
65/// by one: the system's monotonic clock, unless a test sets another, so that the same
66/// changes form the same bursts on every machine, however fast.
67#[derive(Clone)]
68pub struct Ticks(Arc<dyn Fn() -> Instant + Send + Sync>);
69
70impl Ticks {
71	/// The system's monotonic clock.
72	#[must_use]
73	pub fn system() -> Self {
74		Self(Arc::new(Instant::now))
75	}
76
77	/// A clock that `now` reads.
78	#[must_use]
79	pub fn from_fn(now: impl Fn() -> Instant + Send + Sync + 'static) -> Self {
80		Self(Arc::new(now))
81	}
82
83	/// The time now.
84	fn now(&self) -> Instant {
85		(self.0)()
86	}
87}
88
89impl std::fmt::Debug for Ticks {
90	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91		formatter.write_str("Ticks")
92	}
93}
94
95/// Randomness for the state file: its key, and the nonces of what is written to it.
96fn state_rng() -> UnwrapErr<SysRng> {
97	UnwrapErr(SysRng)
98}
99
100/// The path of a space's log file in a replica's data directory.
101#[must_use]
102pub fn log_path(root: &Path, space: SpaceId) -> PathBuf {
103	root.join("spaces")
104		.join(space.to_string())
105		.join("log.sqlite")
106}
107
108/// A space's log, kept on disk: what changes the log is saved before the call returns,
109/// and opening the file builds the log again. The space's sealed blobs are kept in the
110/// replica's directory `blobs`, which its spaces share, and written through the directory
111/// `tmp` beside the log file.
112pub struct StoredLog {
113	blobs: BlobFiles,
114	/// The log, whose history is the log file, and whose state is kept in the state file
115	/// beside it.
116	log: Log<StateFile, LogFile>,
117	/// The key that seals the state file's own key, to make the file again.
118	state_key: Key,
119	/// The fields the indexes in the state file were built with, as they were last read or
120	/// written, if they were built.
121	index_built_with: Option<SpecialFields>,
122	max_drift_millis: u64,
123	secret_fields: BTreeSet<FieldName>,
124	/// The fields whose last writer wins, of which search finds only the value written
125	/// last.
126	last_writer_wins: BTreeSet<FieldName>,
127	/// Whether the person locked the secrets, so that building the log again must not open
128	/// them.
129	locked: bool,
130	/// Whether a purge still waits for the write-ahead log to be truncated.
131	unshredded: bool,
132	/// Whether the log can be used, or is behind or broken.
133	standing: Standing,
134	/// How many times the log was built again from the files since the space was opened.
135	reloads: u64,
136	/// The sealed hashes of the blobs some of whose stored wrapped keys turned out to be
137	/// bad when the space was opened, and left the disk.
138	dropped_at_open: Vec<Hash>,
139	/// The batch of changes that is open, if one is.
140	batch: Option<Batch>,
141	/// The changes of a burst that the state file's transaction holds, saved to the log file
142	/// and not committed to the state file yet, if any. Reading the log commits them once
143	/// they have waited long enough, so they are kept where reading can change them.
144	pending: Cell<Option<Pending>>,
145	/// Whether a read is in progress, in which no burst commits: the read sees one state.
146	reading: Cell<bool>,
147	/// When a change was last saved, which tells a burst from changes made one by one.
148	last_saved: Option<Instant>,
149	/// When the change being made began, if one is: within [`BURST_GAP`] of the last change
150	/// saved, it belongs to a burst.
151	change_began: Option<Instant>,
152	/// Where the times of bursts are read.
153	ticks: Ticks,
154	/// The file that says that a program waits to make the state file anew.
155	remake: PathBuf,
156	/// The two files' counts of what other connections committed, as this stored log last
157	/// caught up with them: when either moves, another program, or another stored log of
158	/// the space, wrote to it.
159	seen: (i64, i64),
160	/// What the replica keeps apart of what purges destroy, if it waits before purging.
161	waiting: Waiting,
162	/// The lock on the space, held shared while the space is open here, and alone while
163	/// this stored log must run alone. It is the last field, so that it is released after
164	/// everything else is dropped, such as a damaged state file that is deleted then.
165	lock: SpaceLock,
166}
167
168/// How a stored log keeps apart what purges destroy, on a replica that waits before purging
169/// ([technical design: copies that wait]).
170///
171/// [technical design: copies that wait]: ../../../docs/Technical-design.md#911-copies-that-wait
172#[derive(Clone, Copy, Debug, Default)]
173struct Waiting {
174	/// Whether the replica waits, so keeps it apart.
175	keeping: bool,
176	/// The wall clock time that the call under way gave, if it took one, in milliseconds
177	/// since 1970: when a purge that it takes in is received. Saving what it destroyed
178	/// takes it.
179	last_wall: Option<u64>,
180	/// Whether a change that restores came to count since what this replica keeps apart was
181	/// last given back, so that [`StoredLog::take_back_kept`] has something to do.
182	restored: bool,
183}
184
185/// Whether a stored log can be used.
186#[derive(Clone, Copy, Debug, PartialEq, Eq)]
187enum Standing {
188	/// It can.
189	Usable,
190	/// The log could not be built again, as the state file must be made anew, which only a
191	/// program that has the space alone may do: the log is empty, and the space is to be
192	/// closed, and opened again once the others close it too. The next change tries again.
193	Behind,
194	/// Saving failed and building the log again from the file failed too: the log is empty
195	/// until the space is opened again.
196	Broken,
197}
198
199/// Changes of a burst that the state file holds and has not committed yet.
200#[derive(Clone, Copy)]
201struct Pending {
202	/// How many changes.
203	changes: usize,
204	/// When the first was saved.
205	since: Instant,
206	/// Whether the change being made has a savepoint in the transaction.
207	savepoint: bool,
208	/// Whether the transaction that held the changes ended already, in an error of the
209	/// state file that was not damage: the log file holds the changes, and the state file
210	/// takes them in when the log is built again from the files, before the next change.
211	lost: bool,
212}
213
214impl Drop for StoredLog {
215	fn drop(&mut self) {
216		self.commit_pending();
217		// A damaged state file is deleted as it goes, but only by a program that has the
218		// space alone.
219		if self.postings().is_damaged() && !self.lock.alone() {
220			self.postings().keep();
221		}
222	}
223}
224
225/// A batch of changes that is open ([technical design: saving in batches]): one transaction of each file
226/// spans it, and each change in it has a savepoint of its own.
227///
228/// [technical design: saving in batches]: ../../../docs/Technical-design.md#77-saving-in-batches
229struct Batch {
230	/// The keys to build the log again with, if the files fail.
231	keys: SpaceKeys,
232	/// Whether the files failed, which left out every change of the batch.
233	lost: bool,
234	/// Whether a change received in the batch purged: once the batch is saved, the
235	/// write-ahead log is truncated, and the state file written anew if the purge took away
236	/// what it holds.
237	purged: bool,
238	/// The sealed hashes of the blobs whose files are to go once the batch is saved, as its
239	/// purges destroyed their keys.
240	released: Vec<Hash>,
241}
242
243/// What reading a sealed blob's file in full against its sealed hash found.
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
245pub enum SealedCheck {
246	/// It holds its sealed hash; its size in bytes.
247	Intact(u64),
248	/// It holds other bytes, read twice.
249	Damaged,
250	/// The replica does not hold it, as when a purge deleted it meanwhile.
251	Gone,
252	/// The check stopped before the end, as asked.
253	Stopped,
254}
255
256/// The files in a replica's blob directory, by what a space's log knows of them.
257#[derive(Clone, Debug, Default, PartialEq, Eq)]
258pub struct BlobInventory {
259	/// The content hashes of the space's blobs that the replica holds a copy of and can
260	/// read.
261	pub held: Vec<Hash>,
262	/// How many of the space's sealed files have keys that the replica cannot open yet,
263	/// such as keys of a space key it has not received.
264	pub waiting: usize,
265	/// The sealed hashes of the files that no key of the space or of the replica's other
266	/// spaces opens, and no purge explains: unless a key arrives, their content is lost.
267	pub keyless: Vec<Hash>,
268	/// Files that are not sealed blobs at all.
269	pub unknown: Vec<PathBuf>,
270}
271
272impl StoredLog {
273	/// Opens a space's log file, creating it and its directory if needed, as the log's
274	/// history, which the log reads as it needs it, checking each change it reads against
275	/// the tag that `storage`, the replica's storage key, makes. The state is in the state
276	/// file beside the log file, which takes in the changes it does not cover yet, and is
277	/// made again if it cannot be used, as the storage specification says in section 5. The
278	/// fields that the state file's indexes were built with, secret and whose last writer
279	/// wins, are the space's special fields until [`StoredLog::set_fields`] says otherwise,
280	/// unless `secret_fields` holds a field that they do not: the space's types made them
281	/// special when it was last open. Holds a shared lock on the space until the stored log
282	/// is dropped, so that several programs, and several stored logs in one, have it open at
283	/// once, each catching up with what the others write before it writes
284	/// ([technical design: several programs on one replica]). Unless another has the space open, finishes what a crash
285	/// interrupted: puts blobs whose keys were saved in place, and deletes the other files
286	/// that were being written; and deletes the files of purged blobs that no other space of
287	/// the replica keeps a key for ([technical design: blobs]).
288	///
289	/// [technical design: several programs on one replica]: ../../../docs/Technical-design.md#78-several-programs-on-one-replica
290	/// [technical design: blobs]: ../../../docs/Technical-design.md#79-blobs
291	///
292	/// # Errors
293	///
294	/// Returns [`StoreError::InUse`] if another program has the space to itself for a moment,
295	/// or waits to, or the state file must be made anew while another has the space open;
296	/// and an error if the file cannot be opened, is not a log file of this version, or is
297	/// damaged.
298	pub fn open(
299		path: &Path,
300		space: SpaceId,
301		keys: &SpaceKeys,
302		storage: &Key,
303		max_drift_millis: u64,
304		secret_fields: impl IntoIterator<Item = FieldName>,
305	) -> Result<Self, StoreError> {
306		if let Some(directory) = path.parent() {
307			fs::create_dir_all(directory)?;
308		}
309		let lock = SpaceLock::shared(&path.with_file_name("lock"))?;
310		// Alone, a stored log puts the space in order after a crash, and may make the state
311		// file anew; while others have the space open, it takes the space as they keep it.
312		let alone = lock.alone();
313		let remake = path.with_file_name(REMAKE);
314		if !alone && remake.exists() {
315			return Err(StoreError::InUse);
316		}
317		let file = LogFile::open(path, storage)?;
318		let blobs = BlobFiles::of_log(path, space);
319		let secret_fields: BTreeSet<FieldName> = secret_fields.into_iter().collect();
320		let state_key = storage.derive(STATE_CONTEXT);
321		let state = open_state(&path.with_file_name("state.sqlite"), &state_key, alone)?;
322		// Before the log is built, so that what others write meanwhile is caught up with
323		// later.
324		let seen = (file.data_version()?, state.data_version()?);
325		// The fields the indexes were built with, which the space's types made special last
326		// time, count until the space says otherwise, unless more fields are secret now.
327		let (secret_fields, last_writer_wins) = match state.indexed_fields() {
328			Ok(Some((secret, last))) if secret_fields.is_subset(&secret) => (secret, last),
329			_ => (secret_fields, BTreeSet::new()),
330		};
331		let mut log = Log::with_history(space, Clock::new(max_drift_millis), state, file);
332		log.set_secret_fields(secret_fields.iter().cloned());
333		let fields = Fields {
334			secret: &secret_fields,
335			last_writer_wins: &last_writer_wins,
336		};
337		let dropped = build(
338			&mut log,
339			keys,
340			max_drift_millis,
341			&state_key,
342			fields,
343			&|| alone,
344		)?;
345		let mut stored = Self {
346			remake,
347			seen,
348			lock,
349			blobs,
350			log,
351			state_key,
352			index_built_with: None,
353			max_drift_millis,
354			secret_fields,
355			last_writer_wins,
356			locked: false,
357			unshredded: false,
358			standing: Standing::Usable,
359			reloads: 0,
360			dropped_at_open: dropped.clone(),
361			batch: None,
362			pending: Cell::new(None),
363			reading: Cell::new(false),
364			last_saved: None,
365			change_began: None,
366			ticks: Ticks::system(),
367			waiting: Waiting::default(),
368		};
369		stored.note_index();
370		stored.recover_blobs(dropped)?;
371		if stored.lock.is_alone() {
372			// Alone, nothing was missed, and the state file may have been made anew, with a
373			// count of its own.
374			stored.seen = stored.versions()?;
375			let _ = fs::remove_file(&stored.remake);
376		}
377		stored.lock.share();
378		Ok(stored)
379	}
380
381	/// Catches up with what other programs, or other stored logs of the space in this one,
382	/// wrote to the space since this one last read it, if they did: builds the log again
383	/// from the files, which takes in what they wrote. Returns whether it did. A change
384	/// catches up by itself before it writes; a caller that keeps what it read of the space,
385	/// such as its types, catches up first to read them again.
386	///
387	/// # Errors
388	///
389	/// Returns [`StoreError::InUse`] if the state file must be made anew while another
390	/// program has the space open, and an error if the files cannot be read.
391	pub fn catch_up(&mut self, keys: &SpaceKeys) -> Result<bool, StoreError> {
392		// A batch holds both files' write locks: nobody else wrote.
393		if self.batch.is_some() {
394			return Ok(false);
395		}
396		if self.standing != Standing::Behind {
397			self.check_usable()?;
398			if self.versions()? == self.seen {
399				return Ok(false);
400			}
401		}
402		self.commit_pending();
403		self.reload(keys);
404		self.check_usable()?;
405		Ok(true)
406	}
407
408	/// How many times the log was built again from the files since the space was opened,
409	/// as after another program wrote to it, or saving failed.
410	#[must_use]
411	pub const fn reloads(&self) -> u64 {
412		self.reloads
413	}
414
415	/// The two files' counts of what other connections committed.
416	fn versions(&self) -> Result<(i64, i64), StoreError> {
417		Ok((self.file().data_version()?, self.postings().data_version()?))
418	}
419
420	/// Has the space's first change govern it, as [`Log::expect_governed`] says: a change
421	/// without parents that does not is rejected.
422	pub fn expect_governed(&mut self) {
423		self.log.expect_governed();
424	}
425
426	/// Takes as the space's first change only one of `roots`, as [`Log::expect_roots`] says.
427	pub fn expect_roots(&mut self, roots: impl IntoIterator<Item = ChangeId>) {
428		self.log.expect_roots(roots);
429	}
430
431	/// Takes as the space's first change one of `roots` too, as [`Log::expect_roots_too`]
432	/// says.
433	pub fn expect_roots_too(&mut self, roots: impl IntoIterator<Item = ChangeId>) {
434		self.log.expect_roots_too(roots);
435	}
436
437	/// Reads the times of bursts of changes from `ticks` from now on, instead of the
438	/// system's monotonic clock: tests give a clock of their own, so that the same changes
439	/// form the same bursts on every machine. Times read from the clock before are not
440	/// compared with those of the new one: the next change begins anew, and commits a burst
441	/// pending from before, whose second is counted again from now.
442	pub fn set_ticks(&mut self, ticks: Ticks) {
443		self.last_saved = None;
444		if let Some(mut pending) = self.pending.get() {
445			pending.since = ticks.now();
446			self.pending.set(Some(pending));
447		}
448		self.ticks = ticks;
449	}
450
451	/// How many changes saved to the log file the state file holds in a transaction that
452	/// has not committed yet: those of a burst, which commit together.
453	#[must_use]
454	pub fn pending_changes(&self) -> usize {
455		self.pending.get().map_or(0, |pending| pending.changes)
456	}
457
458	/// Commits the changes of a burst that the state file holds, if any, as closing the
459	/// space does: for a program that made a few changes at once and stays open, so that
460	/// another program can open the space at once. Nothing is committed during a batch, a
461	/// change or a read, which sees one state. A failure leaves the state file behind the log
462	/// file, which the next change, or opening the space again, takes in.
463	pub fn end_burst(&mut self) {
464		if self.change_began.is_none() && !self.reading.get() {
465			self.commit_pending();
466		}
467	}
468
469	/// Commits the changes of a burst that the state file holds, if any, when the space
470	/// closes. A change half made, which the log file never got, such as one a panic cut
471	/// short, is left out first. A failure leaves the state file behind the log file, which
472	/// opening the space again takes in.
473	fn commit_pending(&mut self) {
474		let Some(pending) = self.pending.take() else {
475			return;
476		};
477		if self.batch.is_some() || pending.lost || !self.postings().in_transaction() {
478			return;
479		}
480		if pending.savepoint {
481			let _ = self
482				.log
483				.storage_mut()
484				.rollback_to_savepoint(Savepoint::Change);
485		}
486		let _ = self.log.storage_mut().commit();
487	}
488
489	/// The log. After a failure that left the log file unreadable, it is empty. On the way,
490	/// the changes of a burst that have waited a second commit to the state file, so that a
491	/// burst that stopped does not hold them long once the space is used again.
492	#[must_use]
493	pub fn log(&self) -> &Log<StateFile, LogFile> {
494		self.settle();
495		&self.log
496	}
497
498	/// Commits the changes of a burst that have waited [`PENDING_FOR`], unless a change is
499	/// being made. If that fails, the log file holds them, and the next change has the log
500	/// built again from the files, which takes them in.
501	fn settle(&self) {
502		if let Some(mut pending) = self.pending.get()
503			&& !pending.savepoint
504			&& !pending.lost
505			&& !self.reading.get()
506			&& self.change_began.is_none()
507			&& self.batch.is_none()
508			&& self.ticks.now().duration_since(pending.since) >= PENDING_FOR
509			&& self.postings().in_transaction()
510		{
511			if self.postings().commit().is_ok() {
512				self.pending.set(None);
513			} else {
514				pending.lost = true;
515				self.pending.set(Some(pending));
516			}
517		}
518	}
519
520	/// Commits a change, as [`Log::commit`] does, and saves it.
521	///
522	/// # Errors
523	///
524	/// Returns the errors of [`Log::commit`], or an error if saving fails, in which case
525	/// the change is not committed.
526	pub fn commit(
527		&mut self,
528		author: &SigningKey,
529		keys: &SpaceKeys,
530		operations: Vec<Operation>,
531		wall_millis: u64,
532		rng: &mut impl CryptoRng,
533	) -> Result<Parcel, StoreError> {
534		// A change that governs may set aside or bring back purges, which delete files at
535		// once, so it is made outside a batch.
536		if self.batch.is_some() {
537			for operation in &operations {
538				if self.log.governs(operation)? {
539					return Err(StoreError::InBatch);
540				}
541			}
542		}
543		// A copy for a second try, if the first finds the state file damaged.
544		let again = operations.clone();
545		let mut first = Some(operations);
546		self.changing(keys, |stored| {
547			let operations = first.take().unwrap_or_else(|| again.clone());
548			stored.waiting.last_wall = Some(wall_millis);
549			let parcel = stored
550				.log
551				.commit(author, keys, operations, wall_millis, rng)?;
552			let applied = stored.log.take_applied();
553			let sealed: Vec<StatementId> = parcel.change.sealed().keys().copied().collect();
554			let mut writes = Writes {
555				wrapped_keys: stored.key_sets(sealed),
556				changes: vec![parcel.clone()],
557				..Writes::default()
558			};
559			// A change that governs may have set aside purges, or brought one back.
560			let purged_blobs = stored.save_destroyed(&mut writes, &applied, keys)?;
561			stored.remove_blob_files(&purged_blobs);
562			Ok(parcel)
563		})
564	}
565
566	/// Begins a batch of changes, which [`StoredLog::end_batch`] saves together
567	/// ([technical design: saving in batches]): until then, the changes that [`StoredLog::commit`] makes are
568	/// read here, but not saved, and so are the changes and record keys that
569	/// [`StoredLog::receive`] and [`StoredLog::receive_wrapped_key`] receive. A change that
570	/// is refused leaves the others of the batch. If the files fail, the log is built again
571	/// from them with `keys`, and every change of the batch is left out. Nothing else that
572	/// writes, such as a purge, a change that governs, or receiving a blob or its key, is
573	/// done while a batch is open.
574	///
575	/// [technical design: saving in batches]: ../../../docs/Technical-design.md#77-saving-in-batches
576	///
577	/// # Errors
578	///
579	/// Returns [`StoreError::InBatch`] if a batch is open already, or an error if the files
580	/// fail.
581	pub fn begin_batch(&mut self, keys: &SpaceKeys) -> Result<(), StoreError> {
582		self.check_not_in_batch()?;
583		if self.standing == Standing::Behind || self.postings().is_damaged() || self.pending_lost()
584		{
585			self.reload(keys);
586		}
587		self.check_usable()?;
588		self.build_index()?;
589		// The changes of a burst commit before the batch, which commits as a whole.
590		if self.pending.get().is_some() {
591			self.commit_state(keys)?;
592		}
593		self.begin_writing(keys)?;
594		if let Err(error) = self.log.storage_mut().begin() {
595			let _ = self.file_mut().rollback();
596			return Err(error);
597		}
598		self.batch = Some(Batch {
599			keys: keys.clone(),
600			lost: false,
601			purged: false,
602			released: Vec::new(),
603		});
604		Ok(())
605	}
606
607	/// Whether a batch of changes is open.
608	#[must_use]
609	pub const fn in_batch(&self) -> bool {
610		self.batch.is_some()
611	}
612
613	/// Whether a change received in the open batch purged. What it destroyed leaves the
614	/// disk once the batch ends, so a caller ends the batch soon.
615	#[must_use]
616	pub fn batch_purged(&self) -> bool {
617		self.batch.as_ref().is_some_and(|batch| batch.purged)
618	}
619
620	/// Whether another stored log, here or in another program, has the space open now: it
621	/// would wait for the write locks while a batch holds them.
622	#[must_use]
623	pub fn shared_with_others(&self) -> bool {
624		self.lock.shared_with_others()
625	}
626
627	/// Ends the batch of changes, and saves them: commits the log file, which is then
628	/// synchronized, then the state file. If only the state file fails, the changes are
629	/// saved, and the state file takes them in from the log file. Once saved, what the
630	/// batch's purges destroyed leaves the disk: the files of their blobs go, the
631	/// write-ahead log is truncated, and the state file is written anew if they took away
632	/// what it holds, as after a single change that purges.
633	///
634	/// # Errors
635	///
636	/// Returns [`StoreError::NoBatch`] if no batch is open, [`StoreError::BatchLost`] if the
637	/// files failed while it was, or an error if saving fails, in which case none of its
638	/// changes is saved.
639	pub fn end_batch(&mut self) -> Result<(), StoreError> {
640		let batch = self.batch.take().ok_or(StoreError::NoBatch)?;
641		if batch.lost {
642			return Err(StoreError::BatchLost);
643		}
644		if !self.both_in_transaction() {
645			// A read found a file failing, which ended its transaction.
646			self.reload(&batch.keys);
647			return Err(StoreError::BatchLost);
648		}
649		if let Err(error) = self.file_mut().commit() {
650			self.reload(&batch.keys);
651			return Err(error);
652		}
653		// The log file holds the batch from here on: a state file that fails is built again
654		// from it, as after a single change.
655		self.pending.set(None);
656		self.release_blob_files(&batch.released);
657		let saved = if self.log.take_stale() {
658			self.remake_state(&batch.keys);
659			if self.standing == Standing::Broken {
660				Err(StoreError::Broken)
661			} else {
662				Ok(())
663			}
664		} else if self.mark_state().is_err() || self.log.storage_mut().commit().is_err() {
665			self.reload(&batch.keys);
666			self.check_usable()
667		} else {
668			Ok(())
669		};
670		if batch.purged || self.unshredded {
671			self.unshredded = !self.file().truncate_wal().unwrap_or(false);
672		}
673		saved
674	}
675
676	/// Leaves out every change of the batch that is open, if one is, and builds the log
677	/// again from the files: for a batch that cannot end, such as when the program that
678	/// made it panicked.
679	pub fn abandon_batch(&mut self) {
680		if let Some(batch) = self.batch.take()
681			&& !batch.lost
682		{
683			self.reload(&batch.keys);
684		}
685	}
686
687	/// Receives a change with what came of its payload and key, as [`Log::receive`] does,
688	/// and saves what the log keeps. Waiting changes that are rejected for good on the way
689	/// leave the file. In a batch, it is saved with the batch, and what a purge destroys
690	/// leaves the disk once the batch is saved, as [`StoredLog::end_batch`] says; a change
691	/// that governs is received outside a batch, as [`StoredLog::commit`] makes one, and so
692	/// is a change that waiting changes wait for, which may govern.
693	///
694	/// # Errors
695	///
696	/// Returns [`StoreError::InBatch`] for a change that governs, or that waiting changes
697	/// wait for, while a batch is open; the errors of [`Log::receive`]; or an error if saving
698	/// fails, in which case the change is not kept.
699	pub fn receive(
700		&mut self,
701		parcel: &Parcel,
702		keys: &SpaceKeys,
703		wall_millis: u64,
704	) -> Result<Received, StoreError> {
705		if self.batch.is_some()
706			&& (parcel.change.kind() == Kind::Governing || self.log.is_awaited(parcel.id()))
707		{
708			return Err(StoreError::InBatch);
709		}
710		let received = self.changing(keys, |stored| {
711			stored.receive_saving(parcel, keys, wall_millis)
712		})?;
713		Ok(received?)
714	}
715
716	/// Receives the sealed payload of a change, as [`Log::receive_payload`] does, and saves
717	/// it if the log keeps it.
718	///
719	/// # Errors
720	///
721	/// Returns the errors of [`Log::receive_payload`], or an error if saving fails, in
722	/// which case the payload is not kept.
723	pub fn receive_payload(
724		&mut self,
725		id: ChangeId,
726		payload: &SealedPayload,
727		keys: &SpaceKeys,
728	) -> Result<(), StoreError> {
729		self.check_not_in_batch()?;
730		self.changing(keys, |stored| {
731			let kept = stored.log.receive_payload(id, payload.clone(), keys);
732			stored.save_part(id, kept, keys)
733		})
734	}
735
736	/// Receives a wrapped key of a change, as [`Log::receive_change_key`] does, and saves it
737	/// if the log keeps it.
738	///
739	/// # Errors
740	///
741	/// Returns the errors of [`Log::receive_change_key`], or an error if saving fails, in
742	/// which case the key is not kept.
743	pub fn receive_change_key(
744		&mut self,
745		id: ChangeId,
746		key: &WrappedChangeKey,
747		keys: &SpaceKeys,
748	) -> Result<(), StoreError> {
749		self.check_not_in_batch()?;
750		self.changing(keys, |stored| {
751			let kept = stored.log.receive_change_key(id, key.clone(), keys);
752			stored.save_part(id, kept, keys)
753		})
754	}
755
756	/// Applies the changes that `keys` let the log read now, as [`Log::open_changes`] does,
757	/// for example after the replica received an older space key, and saves what they
758	/// changed.
759	///
760	/// # Errors
761	///
762	/// Returns an error if the state file cannot be written.
763	pub fn open_changes(&mut self, keys: &SpaceKeys) -> Result<(), StoreError> {
764		self.check_not_in_batch()?;
765		self.changing(keys, |stored| {
766			let opened = stored.log.open_changes(keys);
767			let applied = stored.log.take_applied();
768			opened?;
769			// The log file records them applied, and the state file takes them in, with
770			// what the governing changes read now set aside or brought back.
771			let purged_blobs = stored.save_destroyed(&mut Writes::default(), &applied, keys)?;
772			stored.remove_blob_files(&purged_blobs);
773			Ok(())
774		})
775	}
776
777	/// Follows the groups in this space, as the replica's copies of their logs say, as
778	/// [`Log::follow`] does, and saves what deciding again changed. A program follows them
779	/// each time it opens the space, before it takes or makes changes there.
780	///
781	/// # Errors
782	///
783	/// Returns the errors of [`Log::follow`], or an error if saving fails.
784	pub fn follow(
785		&mut self,
786		groups: &[nibkeep_governance::Followed],
787		keys: &SpaceKeys,
788	) -> Result<(), StoreError> {
789		self.check_not_in_batch()?;
790		self.changing(keys, |stored| {
791			let followed = stored.log.follow(groups.to_vec(), keys);
792			let applied = stored.log.take_applied();
793			followed?;
794			let purged_blobs = stored.save_destroyed(&mut Writes::default(), &applied, keys)?;
795			stored.remove_blob_files(&purged_blobs);
796			Ok(())
797		})
798	}
799
800	/// Saves a change whose payload or key the log kept, and what applying it changed, in a
801	/// transaction of the state file.
802	fn save_part(
803		&mut self,
804		id: ChangeId,
805		kept: Result<bool, LogError>,
806		keys: &SpaceKeys,
807	) -> Result<(), StoreError> {
808		let applied = self.log.take_applied();
809		if !kept? {
810			return Ok(());
811		}
812		let mut writes = Writes {
813			completed: self.waiting_parcel(id)?.into_iter().collect(),
814			..Writes::default()
815		};
816		let purged_blobs = self.save_destroyed(&mut writes, &applied, keys)?;
817		self.remove_blob_files(&purged_blobs);
818		Ok(())
819	}
820
821	/// Receives a change and saves what changed, in a transaction of the state file. The
822	/// log's refusal is returned once what it changed is saved, such as waiting changes that
823	/// it rejected for good on the way.
824	fn receive_saving(
825		&mut self,
826		parcel: &Parcel,
827		keys: &SpaceKeys,
828		wall_millis: u64,
829	) -> Result<Result<Received, LogError>, StoreError> {
830		let rejected_before: BTreeSet<ChangeId> = self.log.rejected().keys().copied().collect();
831		let id = parcel.id();
832		self.waiting.last_wall = Some(wall_millis);
833		let received = self.log.receive(parcel.clone(), keys, wall_millis);
834		let applied = self.log.take_applied();
835		if received == Err(LogError::Storage) {
836			// Nothing is saved: the log no longer matches the state file.
837			return Err(LogError::Storage.into());
838		}
839		let rejected: Vec<ChangeId> = self
840			.log
841			.rejected()
842			.keys()
843			.filter(|id| !rejected_before.contains(id))
844			.copied()
845			.collect();
846		let mut writes = Writes {
847			rejected,
848			..Writes::default()
849		};
850		match &received {
851			Err(_) | Ok(Received::Duplicate) => {}
852			Ok(Received::Completed) => writes.completed.extend(self.waiting_parcel(id)?),
853			Ok(Received::Waiting | Received::Accepted(_)) => {
854				writes.changes.extend(self.log.parcel(id)?);
855			}
856		}
857		let purged_blobs = self.save_destroyed(&mut writes, &applied, keys)?;
858		self.remove_blob_files(&purged_blobs);
859		Ok(received)
860	}
861
862	/// Saves `writes`, what applying changes did, and the deletion of what purges destroyed
863	/// in the last call to the log: only purges of changes that count, which the log says,
864	/// and not those it set aside. Returns the sealed hashes of the blobs whose files are to
865	/// go, once saved.
866	fn save_destroyed(
867		&mut self,
868		writes: &mut Writes,
869		applied: &[(ChangeId, Payload)],
870		keys: &SpaceKeys,
871	) -> Result<Vec<Hash>, StoreError> {
872		let destroyed = self.log.take_destroyed();
873		let purges = !destroyed.is_empty();
874		// What a replica that waits keeps apart is saved with the purge that destroyed it, and
875		// when it came: the time that the call which brought it gave, or else now.
876		let received = self.waiting.last_wall.take().unwrap_or_else(wall_now);
877		for (purge, part) in destroyed.kept {
878			writes.kept.push(KeptRow {
879				purge,
880				part,
881				received,
882			});
883		}
884		self.waiting.restored |= !destroyed.restored.is_empty();
885		for statement in &destroyed.statements {
886			writes.wrapped_keys.push((*statement, Vec::new()));
887		}
888		for sealed in &destroyed.blobs {
889			writes.blob_keys.push((*sealed, Vec::new()));
890			writes.unheld.push(*sealed);
891		}
892		self.take_in(applied, keys)?;
893		self.save(writes, purges, keys)?;
894		Ok(destroyed.blobs)
895	}
896
897	/// What SQLite's own check of the log file finds wrong: nothing if it is sound.
898	///
899	/// # Errors
900	///
901	/// Returns an error if the database fails.
902	pub fn integrity_problems(&self) -> Result<Vec<String>, StoreError> {
903		self.file().integrity_problems()
904	}
905
906	/// The sealed hashes of the blobs some of whose stored wrapped keys turned out to be
907	/// bad when the space was opened. Opening removed them from the disk, since no key can
908	/// be read from them; another replica may still hold good ones.
909	#[must_use]
910	pub fn blob_keys_dropped_at_open(&self) -> &[Hash] {
911		&self.dropped_at_open
912	}
913
914	/// The files in the replica's blob directory, by what the space's log knows of them, and
915	/// `elsewhere`, the sealed hashes that the replica's other spaces keep keys for or
916	/// purged, as [`StoredLog::known_blobs`] gives them: a file that neither explains is
917	/// keyless.
918	///
919	/// # Errors
920	///
921	/// Returns an error if the directory cannot be read.
922	pub fn blob_inventory(&self, elsewhere: &BTreeSet<Hash>) -> Result<BlobInventory, StoreError> {
923		let mut readable: BTreeMap<Hash, Hash> = BTreeMap::new();
924		for content in self.log.blobs() {
925			for (sealed, _) in self.log.blob_keys(content) {
926				readable.insert(*sealed, *content);
927			}
928		}
929		let wrapped: BTreeSet<Hash> = self
930			.log
931			.wrapped_blob_keys()
932			.map(|(sealed, _)| *sealed)
933			.collect();
934		let purged: BTreeSet<Hash> = self.log.purged_blobs()?.into_iter().collect();
935		let mut inventory = BlobInventory::default();
936		let mut held = BTreeSet::new();
937		for file in self.blobs.files()? {
938			match file {
939				Ok(sealed) => match readable.get(&sealed) {
940					Some(content) => {
941						held.insert(*content);
942					}
943					None if wrapped.contains(&sealed) => inventory.waiting += 1,
944					None if purged.contains(&sealed) || elsewhere.contains(&sealed) => {}
945					None => inventory.keyless.push(sealed),
946				},
947				Err(path) => inventory.unknown.push(path),
948			}
949		}
950		inventory.held = held.into_iter().collect();
951		Ok(inventory)
952	}
953
954	/// The sealed hashes that the space keeps wrapped keys for, or purged: those of the files
955	/// in the replica's blob directory that the space explains.
956	///
957	/// # Errors
958	///
959	/// Returns an error if the log file cannot be read.
960	pub fn known_blobs(&self) -> Result<BTreeSet<Hash>, StoreError> {
961		let mut known: BTreeSet<Hash> = self
962			.log
963			.wrapped_blob_keys()
964			.map(|(sealed, _)| *sealed)
965			.collect();
966		known.extend(self.log.purged_blobs()?);
967		Ok(known)
968	}
969
970	/// Finds the entities whose current values hold every word of `query`, compared without
971	/// regard to case or accents. The last word also matches the start of a longer word, so
972	/// that results appear while typing. Entities with more matching values come first.
973	/// Secret fields are never searched.
974	///
975	/// # Errors
976	///
977	/// Returns an error if the state file cannot be read.
978	pub fn search(&self, query: &str) -> Result<Vec<Found>, StoreError> {
979		if self.standing == Standing::Broken {
980			return Ok(Vec::new());
981		}
982		self.check_index()?;
983		index::search(self.postings(), query)
984	}
985
986	/// The entities, deleted ones included, that a current statement of a field that can
987	/// name them names `name`, compared lowercased; of entities merged together, the one
988	/// they were merged into. Which of its names an entity shows is for the caller to check.
989	/// `None` if the indexes cannot tell: if a field that can name entities is secret on
990	/// this replica, or the state file or its indexes cannot be used.
991	///
992	/// # Errors
993	///
994	/// Returns an error if the state file or the log file cannot be read.
995	pub fn named(&self, name: &str) -> Result<Option<Vec<EntityId>>, StoreError> {
996		if self.standing == Standing::Broken
997			|| self.secret_fields.iter().any(fields::can_name)
998			|| self.check_index().is_err()
999		{
1000			return Ok(None);
1001		}
1002		let lowered = name.to_lowercase();
1003		let mut named: BTreeSet<EntityId> =
1004			self.postings().with_name(&lowered)?.into_iter().collect();
1005		// Sealed statements are not indexed: of them, those that this replica opened, kept in
1006		// memory, can name an entity.
1007		let state = self.log.state();
1008		for statement in state.storage().opened() {
1009			if fields::name_key(&statement.field, &statement.value).as_deref() == Some(&lowered)
1010				&& state.is_current(statement.id)?
1011			{
1012				named.insert(state.canonical(statement.entity)?);
1013			}
1014		}
1015		Ok(Some(named.into_iter().collect()))
1016	}
1017
1018	/// Runs `read`, which reads the space, with the state file read in one transaction:
1019	/// many small reads, such as those of listing entities, then cost less, and all see the
1020	/// state as it was when the first began.
1021	///
1022	/// # Errors
1023	///
1024	/// Returns the error of `read`, or an error if the state file fails.
1025	pub fn reading<T, E: From<StoreError>>(
1026		&self,
1027		read: impl FnOnce(&Self) -> Result<T, E>,
1028	) -> Result<T, E> {
1029		if self.standing == Standing::Broken {
1030			return read(self);
1031		}
1032		// A burst that stopped commits before the read, not in it; one whose transaction an
1033		// error ended is noted as lost, so that nothing takes the read's transaction for it.
1034		self.settle();
1035		if let Some(mut pending) = self.pending.get()
1036			&& !self.postings().in_transaction()
1037		{
1038			pending.lost = true;
1039			self.pending.set(Some(pending));
1040		}
1041		// A read within a read leaves the outer one reading.
1042		let was_reading = self.reading.replace(true);
1043		let result = self.postings().reading(|| read(self));
1044		self.reading.set(was_reading);
1045		result
1046	}
1047
1048	/// The entities whose field `field` has the current value `value`, exactly, ordered by
1049	/// ID. Secret fields are never searched.
1050	///
1051	/// # Errors
1052	///
1053	/// Returns an error if the state file cannot be read.
1054	pub fn find(&self, field: &FieldName, value: &Value) -> Result<Vec<EntityId>, StoreError> {
1055		if self.standing == Standing::Broken {
1056			return Ok(Vec::new());
1057		}
1058		self.check_index()?;
1059		index::find(self.postings(), field, value)
1060	}
1061
1062	/// Receives a wrapped record key, as [`Log::receive_wrapped_key`] does, and saves the
1063	/// statement's keys if they changed; in a batch, with the batch.
1064	///
1065	/// # Errors
1066	///
1067	/// Returns an error if saving fails, in which case the key is not kept.
1068	pub fn receive_wrapped_key(
1069		&mut self,
1070		statement: StatementId,
1071		wrapped: WrappedKey,
1072		keys: &SpaceKeys,
1073	) -> Result<(), StoreError> {
1074		let receive = |stored: &mut Self| {
1075			let before = stored.log.wrapped_keys_of(statement).to_vec();
1076			let received = stored.log.receive_wrapped_key(statement, wrapped, keys);
1077			if stored.batch.is_some() {
1078				// A failure of the storage loses the batch.
1079				received?;
1080			} else {
1081				logged(&mut stored.log, received)?;
1082			}
1083			if stored.log.wrapped_keys_of(statement) != before.as_slice() {
1084				let writes = Writes {
1085					wrapped_keys: stored.key_sets([statement]),
1086					..Writes::default()
1087				};
1088				stored.save(&writes, false, keys)?;
1089			}
1090			Ok(())
1091		};
1092		if self.batch.is_some() {
1093			return self.change_in_batch(receive);
1094		}
1095		self.apart(keys, receive)
1096	}
1097
1098	/// Purges values, as [`Log::purge`] does: deletes from the disk the wrapped keys of the
1099	/// secret ones, and the sealed payloads and wrapped keys of the changes that asserted
1100	/// the others, and writes the state file anew under a new key, without what was purged.
1101	/// [`StoredLog::is_shredded`] tells whether no copy of the keys and payloads is left in
1102	/// the log file.
1103	///
1104	/// # Errors
1105	///
1106	/// Returns the errors of [`Log::purge`], or an error if saving fails, in which case
1107	/// nothing is purged.
1108	pub fn purge(
1109		&mut self,
1110		author: &SigningKey,
1111		keys: &SpaceKeys,
1112		statements: &[StatementId],
1113		wall_millis: u64,
1114		rng: &mut impl CryptoRng,
1115	) -> Result<Parcel, StoreError> {
1116		self.purge_with_blobs(author, keys, statements, (&[], false), wall_millis, rng)
1117	}
1118
1119	/// Purges values as [`StoredLog::purge`] does, and in the same change the blobs with
1120	/// the content hashes `contents`, as [`Log::purge_with_blobs`] does: deletes their
1121	/// wrapped keys from the disk, then the files of their sealed copies.
1122	///
1123	/// # Errors
1124	///
1125	/// As [`StoredLog::purge`].
1126	pub fn purge_with_blobs(
1127		&mut self,
1128		author: &SigningKey,
1129		keys: &SpaceKeys,
1130		statements: &[StatementId],
1131		contents: (&[Hash], bool),
1132		wall_millis: u64,
1133		rng: &mut impl CryptoRng,
1134	) -> Result<Parcel, StoreError> {
1135		self.check_not_in_batch()?;
1136		self.changing(keys, |stored| {
1137			stored.waiting.last_wall = Some(wall_millis);
1138			let parcel = stored.log.purge_with_blobs(
1139				author,
1140				keys,
1141				statements.iter().copied(),
1142				contents,
1143				wall_millis,
1144				rng,
1145			)?;
1146			let applied = stored.log.take_applied();
1147			let mut writes = Writes {
1148				changes: vec![parcel.clone()],
1149				..Writes::default()
1150			};
1151			let purged_blobs = stored.save_destroyed(&mut writes, &applied, keys)?;
1152			stored.remove_blob_files(&purged_blobs);
1153			Ok(parcel)
1154		})
1155	}
1156
1157	/// Whether every purged key is gone from the database files. If another program held
1158	/// the database while purging, copies may remain until the next save or
1159	/// [`StoredLog::finish_shredding`].
1160	#[must_use]
1161	pub const fn is_shredded(&self) -> bool {
1162		!self.unshredded
1163	}
1164
1165	/// Tries again to remove the copies of purged keys from the database files. Returns
1166	/// whether none is left.
1167	///
1168	/// # Errors
1169	///
1170	/// Returns an error if the database fails.
1171	pub fn finish_shredding(&mut self) -> Result<bool, StoreError> {
1172		self.check_not_in_batch()?;
1173		if self.unshredded {
1174			self.unshredded = !self.file().truncate_wal()?;
1175		}
1176		Ok(!self.unshredded)
1177	}
1178
1179	/// Keeps apart what purges destroy, as a replica that waits before purging does, or no
1180	/// longer: the sealed payloads and wrapped keys of the changes they purge, the wrapped
1181	/// keys of their statements and blobs, in the log file, with when the purge was taken in,
1182	/// and the files of sealed blobs that no other space keeps a key for, in `kept/` in the
1183	/// replica's folder ([technical design: copies that wait]). What is kept apart is purged
1184	/// as far as everything else goes: never sent, proved, nor counted as a copy.
1185	///
1186	/// [technical design: copies that wait]: ../../../docs/Technical-design.md#911-copies-that-wait
1187	pub fn keep_destroyed(&mut self, keeping: bool) {
1188		self.waiting.keeping = keeping;
1189		self.log.keep_destroyed(keeping);
1190	}
1191
1192	/// Whether this stored log keeps apart what purges destroy, as
1193	/// [`StoredLog::keep_destroyed`] set it.
1194	#[must_use]
1195	pub const fn keeps_destroyed(&self) -> bool {
1196		self.waiting.keeping
1197	}
1198
1199	/// What this replica keeps apart of what purges destroyed, by the purge that destroyed
1200	/// each part, with when it took the purge in.
1201	///
1202	/// # Errors
1203	///
1204	/// Returns an error if the log file cannot be read.
1205	pub fn kept(&self) -> Result<Vec<KeptRow>, StoreError> {
1206		self.file().kept()
1207	}
1208
1209	/// Whether this replica keeps anything apart of what purges destroyed.
1210	///
1211	/// # Errors
1212	///
1213	/// Returns an error if the log file cannot be read.
1214	pub fn keeps_any(&self) -> Result<bool, StoreError> {
1215		self.file().keeps_any()
1216	}
1217
1218	/// The size of the file of a sealed blob kept apart, if it is.
1219	#[must_use]
1220	pub fn kept_blob_size(&self, sealed: &Hash) -> Option<u64> {
1221		self.blobs.kept_size(sealed)
1222	}
1223
1224	/// Stops a purge whose destruction this replica keeps apart, or another copy that waits,
1225	/// such as a backup, holds: makes a change, signed by `author`, that restores what it
1226	/// keeps of what the purge destroyed, and `also`, as [`Log::restore_purged`] does, and
1227	/// gives back what it kept, as [`StoredLog::take_back_kept`] does; what `also` names comes
1228	/// from that copy. Returns the change, or `None` if nothing of the purge is kept.
1229	///
1230	/// # Errors
1231	///
1232	/// Returns the errors of [`Log::restore_purged`], or an error if saving fails.
1233	pub fn restore_kept(
1234		&mut self,
1235		author: &SigningKey,
1236		keys: &SpaceKeys,
1237		(purge, also): (ChangeId, &nibkeep_log::Restores),
1238		wall_millis: u64,
1239		rng: &mut impl CryptoRng,
1240	) -> Result<Option<Parcel>, StoreError> {
1241		self.check_not_in_batch()?;
1242		let mut restores = also.clone();
1243		for row in self.kept()? {
1244			if row.purge != purge {
1245				continue;
1246			}
1247			match row.part {
1248				Kept::Change(parcel) => {
1249					restores.changes.insert(parcel.id());
1250				}
1251				Kept::RecordKeys(statement, _) => {
1252					restores.statements.insert(statement);
1253				}
1254				Kept::BlobKeys(sealed, _) => {
1255					restores.blobs.insert(sealed);
1256				}
1257			}
1258		}
1259		if restores.is_empty() {
1260			return Ok(None);
1261		}
1262		let parcel = self.changing(keys, |stored| {
1263			stored.waiting.last_wall = Some(wall_millis);
1264			let parcel =
1265				stored
1266					.log
1267					.restore_purged(author, keys, restores.clone(), wall_millis, rng)?;
1268			let applied = stored.log.take_applied();
1269			let mut writes = Writes {
1270				changes: vec![parcel.clone()],
1271				..Writes::default()
1272			};
1273			let purged = stored.save_destroyed(&mut writes, &applied, keys)?;
1274			stored.remove_blob_files(&purged);
1275			Ok(parcel)
1276		})?;
1277		self.take_back_kept(keys, wall_millis)?;
1278		Ok(Some(parcel))
1279	}
1280
1281	/// Gives back what this replica keeps apart of what purges destroyed, where a change that
1282	/// restores it came to count, so that it is no longer purged: a change's sealed payload
1283	/// and wrapped keys, which apply its operations again, a statement's or a blob's wrapped
1284	/// keys, and a sealed blob's file, back in place. What is given back is no longer kept
1285	/// apart. Returns how many parts were given back.
1286	///
1287	/// # Errors
1288	///
1289	/// Returns an error if the files cannot be read or written.
1290	pub fn take_back_kept(
1291		&mut self,
1292		keys: &SpaceKeys,
1293		wall_millis: u64,
1294	) -> Result<usize, StoreError> {
1295		if !self.keeps_any()? {
1296			self.waiting.restored = false;
1297			return Ok(0);
1298		}
1299		let mut given = Vec::new();
1300		for row in self.kept()? {
1301			let log = &self.log;
1302			let purged = match &row.part {
1303				Kept::Change(parcel) => log.is_change_purged(parcel.id())?,
1304				Kept::RecordKeys(statement, _) => log.history().is_statement_purged(*statement)?,
1305				Kept::BlobKeys(sealed, _) => log.is_blob_purged(sealed)?,
1306			};
1307			if purged {
1308				continue;
1309			}
1310			match &row.part {
1311				Kept::Change(parcel) => {
1312					match self.receive(parcel, keys, wall_millis) {
1313						Ok(_) | Err(StoreError::Log(_)) => {}
1314						Err(error) => return Err(error),
1315					}
1316					// Kept still, unless the log holds its payload again.
1317					if self.log.sealed_payload(parcel.id())?.is_none() {
1318						continue;
1319					}
1320				}
1321				Kept::RecordKeys(statement, wrapped) => {
1322					for wrapped in wrapped {
1323						self.receive_wrapped_key(*statement, wrapped.clone(), keys)?;
1324					}
1325				}
1326				Kept::BlobKeys(sealed, wrapped) => {
1327					for wrapped in wrapped {
1328						self.receive_blob_key(*sealed, wrapped.clone(), keys)?;
1329					}
1330					self.blobs.take_back(sealed)?;
1331				}
1332			}
1333			given.push(row.part);
1334		}
1335		let count = given.len();
1336		if count > 0 {
1337			self.apart(keys, |stored| {
1338				let writes = Writes {
1339					unkept: given,
1340					..Writes::default()
1341				};
1342				stored.save(&writes, false, keys)
1343			})?;
1344		}
1345		// Only once all went well: else the next sync tries again.
1346		self.waiting.restored = false;
1347		Ok(count)
1348	}
1349
1350	/// How long this device waits before purging, from each time on, in milliseconds, in the
1351	/// order of those times, as the personal space's log file keeps it: the device's own, which
1352	/// never syncs.
1353	///
1354	/// # Errors
1355	///
1356	/// Returns an error if the log file cannot be read.
1357	pub fn waits(&self) -> Result<Vec<(u64, u64)>, StoreError> {
1358		self.file().waits()
1359	}
1360
1361	/// Replaces how long this device waits before purging, from each time on.
1362	///
1363	/// # Errors
1364	///
1365	/// Returns an error if the log file cannot be written.
1366	pub fn save_waits(
1367		&mut self,
1368		waits: Vec<(u64, u64)>,
1369		keys: &SpaceKeys,
1370	) -> Result<(), StoreError> {
1371		self.apart(keys, |stored| {
1372			let writes = Writes {
1373				waits: Some(waits),
1374				..Writes::default()
1375			};
1376			stored.save(&writes, false, keys)
1377		})
1378	}
1379
1380	/// Whether a change that restores came to count since what this replica keeps apart was
1381	/// last given back.
1382	#[must_use]
1383	pub const fn restored_since(&self) -> bool {
1384		self.waiting.restored
1385	}
1386
1387	/// Destroys what this replica keeps apart of what these purges destroyed, as their wait
1388	/// ended or its owner ended it: deletes it from the log file, which then holds no copy
1389	/// of it, and the files of their sealed blobs kept apart, but those that another space
1390	/// keeps apart too; and the files kept apart that no purge of this space or another
1391	/// keeps. Returns how many parts went.
1392	///
1393	/// # Errors
1394	///
1395	/// Returns an error if the files cannot be read or written.
1396	pub fn destroy_kept(
1397		&mut self,
1398		purges: &BTreeSet<ChangeId>,
1399		keys: &SpaceKeys,
1400	) -> Result<usize, StoreError> {
1401		self.check_not_in_batch()?;
1402		let rows = self.kept()?;
1403		let mut ending = Vec::new();
1404		let mut staying = BTreeSet::new();
1405		for row in rows {
1406			let blob = match &row.part {
1407				Kept::BlobKeys(sealed, _) => Some(*sealed),
1408				_ => None,
1409			};
1410			if purges.contains(&row.purge) {
1411				ending.push(row.part);
1412			} else if let Some(sealed) = blob {
1413				staying.insert(sealed);
1414			}
1415		}
1416		let count = ending.len();
1417		if !ending.is_empty() {
1418			self.apart(keys, |stored| {
1419				let writes = Writes {
1420					unkept: ending,
1421					..Writes::default()
1422				};
1423				stored.save(&writes, true, keys)
1424			})?;
1425		}
1426		let gone: Vec<Hash> = self
1427			.blobs
1428			.kept_files()
1429			.into_iter()
1430			.filter(|sealed| !staying.contains(sealed))
1431			.collect();
1432		self.blobs.destroy_kept(&gone)?;
1433		Ok(count)
1434	}
1435
1436	/// Opens the secret values that `keys` allow, as [`Log::unlock_secrets`] does, and
1437	/// removes from the disk the wrapped keys that turned out to be bad.
1438	///
1439	/// # Errors
1440	///
1441	/// Returns an error if saving fails.
1442	pub fn unlock_secrets(&mut self, keys: &SpaceKeys) -> Result<(), StoreError> {
1443		self.apart(keys, |stored| {
1444			let before = stored.all_key_sets();
1445			// Only the keys of secret blobs change as the secrets unlock.
1446			let blob_keys_before =
1447				stored.blob_key_counts(stored.log.sealed_with_secret_keys().copied());
1448			let unlocked = stored.log.unlock_secrets(keys);
1449			logged(&mut stored.log, unlocked)?;
1450			stored.locked = false;
1451			let changed: Vec<StatementId> = before
1452				.into_iter()
1453				.filter(|(statement, keys)| {
1454					stored.log.wrapped_keys_of(*statement) != keys.as_slice()
1455				})
1456				.map(|(statement, _)| statement)
1457				.collect();
1458			let writes = Writes {
1459				wrapped_keys: stored.key_sets(changed),
1460				blob_keys: stored.blob_key_sets(stored.dropped_blob_keys(blob_keys_before)),
1461				..Writes::default()
1462			};
1463			stored.save(&writes, false, keys)
1464		})
1465	}
1466
1467	/// The fields whose values are secret.
1468	#[must_use]
1469	pub const fn secret_fields(&self) -> &BTreeSet<FieldName> {
1470		&self.secret_fields
1471	}
1472
1473	/// Changes which fields are secret, for example after a type of the space marked
1474	/// another field secret: values of them committed from now on are sealed, and search
1475	/// leaves them out.
1476	///
1477	/// # Errors
1478	///
1479	/// Returns an error if the state file cannot be read to build the indexes again.
1480	pub fn set_secret_fields(
1481		&mut self,
1482		secret_fields: impl IntoIterator<Item = FieldName>,
1483	) -> Result<(), StoreError> {
1484		self.secret_fields = secret_fields.into_iter().collect();
1485		self.log
1486			.set_secret_fields(self.secret_fields.iter().cloned());
1487		self.build_index()
1488	}
1489
1490	/// The fields whose last writer wins, of which search finds only the value written last.
1491	#[must_use]
1492	pub const fn last_writer_wins_fields(&self) -> &BTreeSet<FieldName> {
1493		&self.last_writer_wins
1494	}
1495
1496	/// Changes which fields are secret, as [`StoredLog::set_secret_fields`] does, and which
1497	/// show only the value written last, of which search finds only that value; for example
1498	/// after a type of the space defined such fields. Builds the indexes again once.
1499	///
1500	/// # Errors
1501	///
1502	/// Returns an error if the state file cannot be read to build the indexes again.
1503	pub fn set_fields(
1504		&mut self,
1505		secret: impl IntoIterator<Item = FieldName>,
1506		last_writer_wins: impl IntoIterator<Item = FieldName>,
1507	) -> Result<(), StoreError> {
1508		self.secret_fields = secret.into_iter().collect();
1509		self.log
1510			.set_secret_fields(self.secret_fields.iter().cloned());
1511		self.last_writer_wins = last_writer_wins.into_iter().collect();
1512		self.build_index()
1513	}
1514
1515	/// Brings the indexes up to date, if the fields that are secret or show the value written
1516	/// last are not those they were built with: the fields that changed are indexed again,
1517	/// or everything, if the indexes were never built. If that fails, they are not searched
1518	/// until they are brought up to date, before the next change, as they may hold values of
1519	/// fields that became secret.
1520	fn build_index(&mut self) -> Result<(), StoreError> {
1521		if self.index_matches() {
1522			return Ok(());
1523		}
1524		let special = (self.secret_fields.clone(), self.last_writer_wins.clone());
1525		let in_transaction = self.postings().in_transaction();
1526		let was = self.index_built_with.clone();
1527		let built = ensure_index(&mut self.log, was.as_ref(), special, in_transaction);
1528		self.note_index();
1529		built
1530	}
1531
1532	/// Notes the fields the indexes in the state file were built with.
1533	fn note_index(&mut self) {
1534		self.index_built_with = self.postings().indexed_fields().ok().flatten();
1535	}
1536
1537	/// Whether the indexes were built with the fields that are special now.
1538	fn index_matches(&self) -> bool {
1539		matches!(
1540			&self.index_built_with,
1541			Some((secret, last)) if *secret == self.secret_fields && *last == self.last_writer_wins
1542		)
1543	}
1544
1545	/// Returns an error if the indexes must not be searched, as they were built with other
1546	/// fields than those that are special now.
1547	fn check_index(&self) -> Result<(), StoreError> {
1548		if self.index_matches() {
1549			Ok(())
1550		} else {
1551			Err(StoreError::State(
1552				"the search index could not be built again".to_owned(),
1553			))
1554		}
1555	}
1556
1557	/// The postings of the indexes, in the state file.
1558	fn postings(&self) -> &StateFile {
1559		self.log.state().storage().ordinary()
1560	}
1561
1562	/// Which fields the space treats specially.
1563	fn fields(&self) -> Fields<'_> {
1564		Fields {
1565			secret: &self.secret_fields,
1566			last_writer_wins: &self.last_writer_wins,
1567		}
1568	}
1569
1570	/// Forgets the opened secret values, as [`Log::lock_secrets`] does.
1571	pub fn lock_secrets(&mut self) {
1572		self.log.lock_secrets();
1573		self.locked = true;
1574	}
1575
1576	/// Seals content as a blob of the space, unless the replica holds it already with an
1577	/// ordinary key, and returns its content hash. Reads `content` to its end and seals it
1578	/// with a new blob key into a new file. Saves the key, wrapped with the newest space key,
1579	/// before the file takes its place, so that every blob in place has its key. Records
1580	/// `wall_millis` as the time the blob was last checked.
1581	///
1582	/// # Errors
1583	///
1584	/// Returns an error if reading the content or writing fails, in which case no blob is
1585	/// added.
1586	pub fn import_blob(
1587		&mut self,
1588		keys: &SpaceKeys,
1589		content: impl Read,
1590		wall_millis: u64,
1591		rng: &mut impl CryptoRng,
1592	) -> Result<Hash, StoreError> {
1593		self.import(keys, (content, false), &|_| Vec::new(), wall_millis, rng)
1594	}
1595
1596	/// Seals content as a blob of the space, as [`StoredLog::import_blob`] does, with a
1597	/// secret key if `secret` says so, as [`StoredLog::import_secret_blob`] does, unless the
1598	/// replica holds it already for another of its spaces: `elsewhere` gives the sealed
1599	/// copies of a content that the replica's other spaces hold, with their keys, smallest
1600	/// sealed hash first, as [`StoredLog::held_copies`] gives them. The first that
1601	/// [`StoredLog::share_blob`] takes up is the space's copy too, and the content is not
1602	/// sealed anew ([technical design: blobs]).
1603	///
1604	/// [technical design: blobs]: ../../../docs/Technical-design.md#79-blobs
1605	///
1606	/// # Errors
1607	///
1608	/// As [`StoredLog::import_blob`] and [`StoredLog::import_secret_blob`].
1609	pub fn import_blob_sharing(
1610		&mut self,
1611		keys: &SpaceKeys,
1612		(content, secret): (impl Read, bool),
1613		elsewhere: &dyn Fn(&Hash) -> Vec<(Hash, Key)>,
1614		wall_millis: u64,
1615		rng: &mut impl CryptoRng,
1616	) -> Result<Hash, StoreError> {
1617		if secret && keys.newest_secrets().is_none() {
1618			return Err(StoreError::Log(LogError::SecretsLocked));
1619		}
1620		self.import(keys, (content, secret), elsewhere, wall_millis, rng)
1621	}
1622
1623	/// The sealed copies of a content that the replica holds and can read in the space,
1624	/// with keys of the kind given, secret or ordinary, smallest sealed hash first, for its
1625	/// other spaces to take up.
1626	#[must_use]
1627	pub fn held_copies(&self, content: &Hash, secret: bool) -> Vec<(Hash, Key)> {
1628		self.held(content)
1629			.filter(|(sealed, _)| self.log.is_secret_blob(sealed) == secret)
1630			.map(|(sealed, key)| (*sealed, key.clone()))
1631			.collect()
1632	}
1633
1634	/// Takes up, for the space, a sealed copy of `content` that the replica holds for
1635	/// another of its spaces, `copy`, with its key: reads it whole first, as the content
1636	/// hash a key claims is only a claim, then wraps its key for the space, secret if
1637	/// `secret` says so, and records `wall_millis` as the time the copy was last checked.
1638	/// Returns whether the space holds the content now with a key of that kind, which it
1639	/// may have already. A copy whose sealed hash the space purged is never taken up, nor
1640	/// one that does not hold the content: the content is then to be sealed anew
1641	/// ([technical design: blobs]).
1642	///
1643	/// [technical design: blobs]: ../../../docs/Technical-design.md#79-blobs
1644	///
1645	/// # Errors
1646	///
1647	/// Returns [`StoreError::Log`] with [`LogError::SecretsLocked`] if `secret` and `keys`
1648	/// hold no secrets key, and another error if the blob lock cannot be taken, or saving
1649	/// fails.
1650	pub fn share_blob(
1651		&mut self,
1652		keys: &SpaceKeys,
1653		content: &Hash,
1654		(sealed, key): (Hash, &Key),
1655		secret: bool,
1656		wall_millis: u64,
1657		rng: &mut impl CryptoRng,
1658	) -> Result<bool, StoreError> {
1659		self.check_usable()?;
1660		self.check_not_in_batch()?;
1661		if secret && keys.newest_secrets().is_none() {
1662			return Err(StoreError::Log(LogError::SecretsLocked));
1663		}
1664		if self.held_as(content, secret) {
1665			return Ok(true);
1666		}
1667		if self.log.is_blob_purged(&sealed)? {
1668			return Ok(false);
1669		}
1670		// A copy that cannot be read whole, or does not hold the content, is not taken up.
1671		let checked = self.blobs.open(&sealed).and_then(|file| {
1672			BlobReader::new(key, *content, file)
1673				.and_then(|mut reader| io::copy(&mut reader, &mut io::sink()))
1674		});
1675		if checked.is_err() {
1676			return Ok(false);
1677		}
1678		// Under the blob lock, so that no other space deletes the file in between, as it
1679		// would if it saw no key of this space for it; and once the log has caught up, so
1680		// that the keys saved replace none that another program saved meanwhile.
1681		let _lock = self.blobs.lock()?;
1682		if !self.blobs.holds(&sealed) {
1683			return Ok(false);
1684		}
1685		self.apart(keys, |stored| {
1686			let added = if secret {
1687				stored
1688					.log
1689					.add_secret_blob_key(*content, sealed, key.clone(), keys, rng)
1690			} else {
1691				stored
1692					.log
1693					.add_blob_key(*content, sealed, key.clone(), keys, rng)
1694			};
1695			logged(&mut stored.log, added)?;
1696			if !stored.held_as(content, secret) {
1697				return Ok(false);
1698			}
1699			let writes = Writes {
1700				blob_keys: stored.blob_key_sets([sealed]),
1701				verified: vec![(sealed, wall_millis)],
1702				..Writes::default()
1703			};
1704			stored.save(&writes, false, keys)?;
1705			Ok(true)
1706		})
1707	}
1708
1709	/// Seals the content of a secret field as a blob of the space, as
1710	/// [`StoredLog::import_blob`] seals other content, unless the replica holds it already
1711	/// with a secret key: its key is wrapped with the newest secrets key inside the newest
1712	/// space key, so that only a replica that holds the secrets reads it. Content that the
1713	/// replica holds with an ordinary key only is sealed anew.
1714	///
1715	/// # Errors
1716	///
1717	/// Returns [`StoreError::Log`] with [`LogError::SecretsLocked`] if `keys` hold no
1718	/// secrets key, and another error if reading the content or writing fails, in which case
1719	/// no blob is added.
1720	pub fn import_secret_blob(
1721		&mut self,
1722		keys: &SpaceKeys,
1723		content: impl Read,
1724		wall_millis: u64,
1725		rng: &mut impl CryptoRng,
1726	) -> Result<Hash, StoreError> {
1727		if keys.newest_secrets().is_none() {
1728			return Err(StoreError::Log(LogError::SecretsLocked));
1729		}
1730		self.import(keys, (content, true), &|_| Vec::new(), wall_millis, rng)
1731	}
1732
1733	/// Seals content as a blob of the space, with a secret key or an ordinary one, unless it
1734	/// takes up a copy that `elsewhere` gives.
1735	fn import(
1736		&mut self,
1737		keys: &SpaceKeys,
1738		content: (impl Read, bool),
1739		elsewhere: &dyn Fn(&Hash) -> Vec<(Hash, Key)>,
1740		wall_millis: u64,
1741		rng: &mut impl CryptoRng,
1742	) -> Result<Hash, StoreError> {
1743		self.check_usable()?;
1744		self.check_not_in_batch()?;
1745		let (temporary, file) = self.blobs.temporary()?;
1746		let imported = self.import_from(
1747			&temporary,
1748			file,
1749			keys,
1750			content,
1751			elsewhere,
1752			(wall_millis, rng),
1753		);
1754		// After a success the file is in place, or was not needed.
1755		let _ = fs::remove_file(&temporary);
1756		imported
1757	}
1758
1759	/// Whether the replica holds a sealed copy of the content with the hash `content` that it
1760	/// can read now: with an ordinary key, or with a secret one while the secrets are
1761	/// unlocked. Whether the content is stored for every replica,
1762	/// [`StoredLog::holds_ordinary_blob`] tells.
1763	#[must_use]
1764	pub fn holds_blob(&self, content: &Hash) -> bool {
1765		self.held(content).next().is_some()
1766	}
1767
1768	/// Whether the replica holds a sealed copy of the content with the hash `content` with
1769	/// an ordinary key, which every replica of the space can read.
1770	#[must_use]
1771	pub fn holds_ordinary_blob(&self, content: &Hash) -> bool {
1772		self.held_as(content, false)
1773	}
1774
1775	/// Whether the replica has opened a secret blob key for the content with the hash
1776	/// `content`, whether or not it holds the sealed copy yet: whether the content is sealed
1777	/// for the secrets, as far as this replica knows while its secrets are unlocked.
1778	#[must_use]
1779	pub fn has_secret_blob_key(&self, content: &Hash) -> bool {
1780		self.log
1781			.blob_keys(content)
1782			.any(|(sealed, _)| self.log.is_secret_blob(sealed))
1783	}
1784
1785	/// Whether the replica holds a sealed copy of the content with a key of the kind given.
1786	fn held_as(&self, content: &Hash, secret: bool) -> bool {
1787		self.held(content)
1788			.any(|(sealed, _)| self.log.is_secret_blob(sealed) == secret)
1789	}
1790
1791	/// Opens the content with the hash `content` for reading, from a sealed copy that the
1792	/// replica holds. The reader can start anywhere, and checks the content hash when it
1793	/// reads all of the content in order.
1794	///
1795	/// # Errors
1796	///
1797	/// Returns an error if the replica holds no copy, or the copy is damaged.
1798	pub fn open_blob(&self, content: &Hash) -> Result<BlobReader<File>, StoreError> {
1799		let copy = self.checked_last(content)?.ok_or(StoreError::MissingBlob)?;
1800		BlobReader::new(copy.key, *content, self.blobs.open(copy.sealed)?).map_err(blob_error)
1801	}
1802
1803	/// Reads every sealed copy of the content that the replica holds in full, checking the
1804	/// content hash, and records `wall_millis` as the time each intact copy was last
1805	/// checked. A replica normally holds one copy of a content, and more only when replicas
1806	/// sealed it before they learned of each other's keys.
1807	///
1808	/// # Errors
1809	///
1810	/// Returns an error if the replica holds no copy, a copy is damaged, which is reported
1811	/// after the intact ones are recorded, or saving fails.
1812	pub fn verify_blob(&mut self, content: &Hash, wall_millis: u64) -> Result<(), StoreError> {
1813		self.check_usable()?;
1814		self.check_not_in_batch()?;
1815		let mut held = false;
1816		let mut damaged = false;
1817		let mut verified = Vec::new();
1818		for (sealed, key) in self.held(content) {
1819			held = true;
1820			let checked = BlobReader::new(key, *content, self.blobs.open(sealed)?)
1821				.and_then(|mut reader| io::copy(&mut reader, &mut io::sink()));
1822			match checked {
1823				Ok(_) => verified.push((*sealed, wall_millis)),
1824				Err(error) if error.kind() == io::ErrorKind::InvalidData => damaged = true,
1825				Err(error) => return Err(error.into()),
1826			}
1827		}
1828		if !held {
1829			return Err(StoreError::MissingBlob);
1830		}
1831		self.save_records(&Writes {
1832			verified,
1833			..Writes::default()
1834		})?;
1835		if damaged {
1836			return Err(StoreError::DamagedBlob);
1837		}
1838		Ok(())
1839	}
1840
1841	/// When the replica last found a copy of the content intact, in milliseconds since 1970,
1842	/// or `None` if it holds no copy.
1843	///
1844	/// # Errors
1845	///
1846	/// Returns an error if the database fails.
1847	pub fn blob_verified(&self, content: &Hash) -> Result<Option<u64>, StoreError> {
1848		Ok(self.checked_last(content)?.and_then(|copy| copy.verified))
1849	}
1850
1851	/// When the replica last read each sealed blob of the space in full and found it intact,
1852	/// by sealed hash, in milliseconds since 1970.
1853	///
1854	/// # Errors
1855	///
1856	/// Returns an error if the database fails.
1857	pub fn checks(&self) -> Result<BTreeMap<Hash, u64>, StoreError> {
1858		self.file().checks()
1859	}
1860
1861	/// The pages of the replicas' accounts of what they hold in the space that the log file
1862	/// keeps: the latest of each page of each replica ([technical design: where the copies
1863	/// are]).
1864	///
1865	/// [technical design: where the copies are]: ../../../docs/Technical-design.md#96-where-the-copies-are
1866	///
1867	/// # Errors
1868	///
1869	/// Returns an error if the database fails, or a page's row is damaged.
1870	pub fn account_pages(&self) -> Result<Vec<StoredPage>, StoreError> {
1871		self.file().account_pages()
1872	}
1873
1874	/// The pages of the replicas' accounts that the log file keeps, as
1875	/// [`StoredLog::account_pages`] lists them, without their encodings.
1876	///
1877	/// # Errors
1878	///
1879	/// Returns an error if the database fails, or a page's row is damaged.
1880	pub fn account_page_ids(&self) -> Result<Vec<StoredPageId>, StoreError> {
1881		self.file().account_page_ids()
1882	}
1883
1884	/// The pages of the accounts of backups that the log file keeps: the latest of each page
1885	/// of each backup that each replica issued
1886	/// ([technical design](../../../docs/Technical-design.md#910-backups)).
1887	///
1888	/// # Errors
1889	///
1890	/// Returns an error if the database fails, or a page's row is damaged.
1891	pub fn backup_account_pages(&self) -> Result<Vec<StoredPage>, StoreError> {
1892		self.file().backup_account_pages()
1893	}
1894
1895	/// The same, without their encodings.
1896	///
1897	/// # Errors
1898	///
1899	/// Returns an error if the database fails, or a page's row is damaged.
1900	pub fn backup_account_page_ids(&self) -> Result<Vec<StoredPageId>, StoreError> {
1901		self.file().backup_account_page_ids()
1902	}
1903
1904	/// The encoding of the page of an account whose hash is `id`, if the log file keeps it.
1905	///
1906	/// # Errors
1907	///
1908	/// Returns an error if the database fails.
1909	pub fn account_page(&self, id: &Hash) -> Result<Option<Vec<u8>>, StoreError> {
1910		self.file().account_page(id)
1911	}
1912
1913	/// Keeps each of these pages of accounts that is later than the one of its replica and
1914	/// number that the log file keeps, if it keeps one: issued later, or at the same time
1915	/// with a larger hash. Checking the pages is the caller's. Returns how many it kept.
1916	///
1917	/// # Errors
1918	///
1919	/// Returns an error if a batch is open, or the database fails, in which case none is
1920	/// kept.
1921	pub fn save_account_pages(&mut self, pages: &[StoredPage]) -> Result<usize, StoreError> {
1922		self.check_usable()?;
1923		self.check_not_in_batch()?;
1924		if pages.is_empty() {
1925			return Ok(0);
1926		}
1927		// A burst that holds the state file's write lock commits first, so that this program
1928		// never holds it while it waits for the log file's, which another program may hold
1929		// while it waits for the state file's.
1930		self.commit_pending();
1931		self.file_mut().save_account_pages(pages)
1932	}
1933
1934	/// Deletes the replica's ordinary sealed copies of the content, and keeps the keys: for
1935	/// when the replica no longer needs a copy. A secret file's copy, which no storage policy
1936	/// chooses for, stays, and so does a copy that another space of the replica keeps a key
1937	/// for.
1938	///
1939	/// # Errors
1940	///
1941	/// Returns an error if a file or the record of its checks cannot be deleted.
1942	pub fn remove_blob(&mut self, content: &Hash) -> Result<(), StoreError> {
1943		self.check_usable()?;
1944		self.check_not_in_batch()?;
1945		let held: Vec<Hash> = self
1946			.held(content)
1947			.map(|(sealed, _)| *sealed)
1948			.filter(|sealed| !self.log.is_secret_blob(sealed))
1949			.collect();
1950		self.blobs.release(&held)?;
1951		self.save_records(&Writes {
1952			unheld: held,
1953			..Writes::default()
1954		})
1955	}
1956
1957	/// The sealed hashes of the sealed blobs of the space that the replica holds, whether or
1958	/// not it can read them yet, for other replicas: those it keeps a wrapped key for in the
1959	/// space, as the replica's other spaces keep theirs in the same directory.
1960	///
1961	/// # Errors
1962	///
1963	/// Returns an error if the blob directory cannot be read: none now, as each file is
1964	/// looked up.
1965	pub fn sealed_blobs(&self) -> Result<Vec<Hash>, StoreError> {
1966		Ok(self
1967			.log
1968			.wrapped_blob_keys()
1969			.map(|(sealed, _)| *sealed)
1970			.collect::<BTreeSet<Hash>>()
1971			.into_iter()
1972			.filter(|sealed| self.blobs.holds(sealed))
1973			.collect())
1974	}
1975
1976	/// Opens a sealed blob of the space that the replica holds as it is stored, for another
1977	/// replica, with its size in bytes; `None` if it holds none with that sealed hash, or
1978	/// keeps no key for it in the space.
1979	///
1980	/// # Errors
1981	///
1982	/// Returns an error if the file cannot be opened.
1983	pub fn open_sealed_blob(&self, sealed: &Hash) -> Result<Option<(u64, File)>, StoreError> {
1984		if self.log.wrapped_blob_keys_of(sealed).is_empty() {
1985			return Ok(None);
1986		}
1987		let file = match self.blobs.open(sealed) {
1988			Ok(file) => file,
1989			Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
1990			Err(error) => return Err(error.into()),
1991		};
1992		let size = file.metadata()?.len();
1993		Ok(Some((size, file)))
1994	}
1995
1996	/// Receives a sealed blob of `size` bytes from another replica, and keeps it if its
1997	/// bytes have the sealed hash, and the replica neither holds it nor purged it. Its key
1998	/// comes on its own, before or after: the sealed hash is checked without it, and until
1999	/// it comes, the space does not pass the blob on. A blob kept replaces a damaged copy of
2000	/// it kept aside. Returns whether the blob was kept: it was read whole then, which counts
2001	/// as a check that the caller records ([`StoredLog::record_checks`]).
2002	///
2003	/// # Errors
2004	///
2005	/// Returns an error if reading `bytes` or writing the file fails, in which case no blob
2006	/// is added.
2007	pub fn receive_sealed_blob(
2008		&mut self,
2009		sealed: Hash,
2010		size: u64,
2011		bytes: impl Read,
2012	) -> Result<bool, StoreError> {
2013		self.check_usable()?;
2014		self.check_not_in_batch()?;
2015		if self.blobs.holds(&sealed) || self.log.is_blob_purged(&sealed)? {
2016			return Ok(false);
2017		}
2018		let (temporary, file) = self.blobs.temporary()?;
2019		let received = self.receive_into(&temporary, file, &sealed, size, bytes);
2020		// After a success the file is in place.
2021		let _ = fs::remove_file(&temporary);
2022		received
2023	}
2024
2025	/// Reads the replica's copy of a sealed blob in full against its sealed hash, as a
2026	/// regular check does, without a key: again if its bytes differ, so that one bad read is
2027	/// not taken for damage. `stop` is asked between chunks.
2028	///
2029	/// # Errors
2030	///
2031	/// Returns an error if the file cannot be read, which is no sign of damage.
2032	pub fn check_sealed_blob(
2033		&self,
2034		sealed: &Hash,
2035		stop: &dyn Fn() -> bool,
2036	) -> Result<SealedCheck, StoreError> {
2037		for _ in 0..2 {
2038			match self.blobs.hash_file(sealed, stop) {
2039				Ok(None) => return Ok(SealedCheck::Stopped),
2040				Ok(Some((found, size))) if found == *sealed => {
2041					return Ok(SealedCheck::Intact(size));
2042				}
2043				Ok(Some(_)) => {}
2044				Err(error) if error.kind() == io::ErrorKind::NotFound => {
2045					return Ok(SealedCheck::Gone);
2046				}
2047				Err(error) => return Err(error.into()),
2048			}
2049		}
2050		Ok(SealedCheck::Damaged)
2051	}
2052
2053	/// Moves the replica's damaged copy of a sealed blob aside, out of the blob directory, so
2054	/// that the replica no longer holds it and a sync brings it again, which then replaces
2055	/// it ([technical design: checking and repair]). Returns whether it did: not if the
2056	/// replica no longer holds it.
2057	///
2058	/// [technical design: checking and repair]: ../../../docs/Technical-design.md#97-checking-and-repair
2059	///
2060	/// # Errors
2061	///
2062	/// Returns an error if the file cannot be moved.
2063	pub fn set_aside_blob(&self, sealed: &Hash) -> Result<bool, StoreError> {
2064		Ok(self.blobs.set_aside(sealed)?)
2065	}
2066
2067	/// Removes the replica's copies of sealed blobs of the space that it no longer keeps,
2068	/// though the space keeps their keys, as the planner does once other disks proved their
2069	/// copies ([technical design: the planner]). A blob that another space of the replica
2070	/// keeps a key for stays. Returns those removed.
2071	///
2072	/// [technical design: the planner]: ../../../docs/Technical-design.md#99-the-planner
2073	///
2074	/// # Errors
2075	///
2076	/// Returns an error if a file cannot be removed; those removed before it are gone.
2077	pub fn remove_sealed_blobs(&self, sealed: &[Hash]) -> Result<Vec<Hash>, StoreError> {
2078		let keyed: Vec<Hash> = sealed
2079			.iter()
2080			.copied()
2081			.filter(|sealed| !self.log.wrapped_blob_keys_of(sealed).is_empty())
2082			.collect();
2083		Ok(self.blobs.remove(&keyed)?)
2084	}
2085
2086	/// Deletes the files of every sealed blob that the space keeps a key for, and their
2087	/// damaged copies kept aside, but those that another space of the replica keeps a key
2088	/// for, under the blob lock: as the space leaves the replica, when its device drops it
2089	/// ([technical design: devices that choose their spaces]).
2090	///
2091	/// [technical design: devices that choose their spaces]: ../../../docs/Technical-design.md#1310-devices-that-choose-their-spaces
2092	///
2093	/// # Errors
2094	///
2095	/// Returns an error if a file cannot be deleted; the others are deleted all the same.
2096	pub fn release_all_blobs(&self) -> Result<(), StoreError> {
2097		let sealed: Vec<Hash> = self
2098			.log
2099			.wrapped_blob_keys()
2100			.map(|(sealed, _)| *sealed)
2101			.collect::<BTreeSet<Hash>>()
2102			.into_iter()
2103			.collect();
2104		Ok(self.blobs.release(&sealed)?)
2105	}
2106
2107	/// Holds the space's lock alone, if no other stored log, here or in another program,
2108	/// has the space open: whether it does. It is held alone until this stored log goes, as
2109	/// when the space leaves the replica.
2110	#[must_use]
2111	pub fn hold_alone(&self) -> bool {
2112		self.lock.alone()
2113	}
2114
2115	/// Shares the space's lock again, held alone before, so that other programs open the
2116	/// space again.
2117	pub fn share_again(&self) {
2118		self.lock.share();
2119	}
2120
2121	/// Of these sealed blobs, those that another space of the replica keeps a key for, as
2122	/// its log file says now: all of them if one cannot be read.
2123	#[must_use]
2124	pub fn keyed_elsewhere(&self, sealed: &[Hash]) -> BTreeSet<Hash> {
2125		self.blobs.kept_elsewhere(sealed)
2126	}
2127
2128	/// Whether the replica holds a sealed blob, in its blob directory.
2129	#[must_use]
2130	pub fn holds_sealed(&self, sealed: &Hash) -> bool {
2131		self.blobs.holds(sealed)
2132	}
2133
2134	/// Whether a damaged copy of a sealed blob is kept aside, waiting for an intact one.
2135	#[must_use]
2136	pub fn is_blob_aside(&self, sealed: &Hash) -> bool {
2137		self.blobs.is_aside(sealed)
2138	}
2139
2140	/// The sealed blobs of the space, whose keys it keeps, that the replica no longer holds
2141	/// as a damaged copy of each is kept aside.
2142	#[must_use]
2143	pub fn aside_blobs(&self) -> Vec<Hash> {
2144		self.blobs
2145			.aside_files()
2146			.into_iter()
2147			.filter(|sealed| {
2148				!self.log.wrapped_blob_keys_of(sealed).is_empty() && !self.blobs.holds(sealed)
2149			})
2150			.collect()
2151	}
2152
2153	/// Reads the copy of a sealed blob kept aside in full against its sealed hash, as
2154	/// [`StoredLog::check_sealed_blob`] reads one in place, and puts it back in place if it
2155	/// is intact after all, as when the damage was a bad read, unless the replica holds the
2156	/// blob again. Returns what the read found: [`SealedCheck::Intact`] once it is back.
2157	///
2158	/// # Errors
2159	///
2160	/// Returns an error if the file cannot be read or moved.
2161	pub fn recheck_aside_blob(
2162		&self,
2163		sealed: &Hash,
2164		stop: &dyn Fn() -> bool,
2165	) -> Result<SealedCheck, StoreError> {
2166		match self.blobs.hash_aside(sealed, stop) {
2167			Ok(None) => Ok(SealedCheck::Stopped),
2168			Ok(Some((found, size))) if found == *sealed => {
2169				if self.blobs.restore(sealed)? {
2170					Ok(SealedCheck::Intact(size))
2171				} else {
2172					Ok(SealedCheck::Gone)
2173				}
2174			}
2175			Ok(Some(_)) => Ok(SealedCheck::Damaged),
2176			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(SealedCheck::Gone),
2177			Err(error) => Err(error.into()),
2178		}
2179	}
2180
2181	/// Records what checks found: sealed blobs found intact and found damaged, each with
2182	/// when, and checks of plain copies on this device.
2183	///
2184	/// # Errors
2185	///
2186	/// Returns an error if a batch is open, or saving fails.
2187	pub fn record_checks(
2188		&mut self,
2189		intact: Vec<(Hash, u64)>,
2190		damaged: Vec<(Hash, u64)>,
2191		places: Vec<PlaceCheck>,
2192	) -> Result<(), StoreError> {
2193		self.check_usable()?;
2194		self.check_not_in_batch()?;
2195		if intact.is_empty() && damaged.is_empty() && places.is_empty() {
2196			return Ok(());
2197		}
2198		// A burst that holds the state file's write lock commits first, as for pages of
2199		// accounts.
2200		self.commit_pending();
2201		self.save_records(&Writes {
2202			verified: intact,
2203			damaged,
2204			places,
2205			..Writes::default()
2206		})
2207	}
2208
2209	/// The sealed blobs of the space that checks found damaged, with when each was last found
2210	/// so, in milliseconds since 1970; those that came again since are held once more.
2211	///
2212	/// # Errors
2213	///
2214	/// Returns an error if the database fails.
2215	pub fn damaged_blobs(&self) -> Result<BTreeMap<Hash, u64>, StoreError> {
2216		self.file().damaged_blobs()
2217	}
2218
2219	/// The latest check of each plain copy on this device.
2220	///
2221	/// # Errors
2222	///
2223	/// Returns an error if the database fails.
2224	pub fn place_checks(&self) -> Result<Vec<PlaceCheck>, StoreError> {
2225		self.file().place_checks()
2226	}
2227
2228	/// Records that a file was opened on this device at `at`, in milliseconds since 1970,
2229	/// outside the history: it decides which files an everyday device keeps, and is never
2230	/// synced.
2231	///
2232	/// # Errors
2233	///
2234	/// Returns an error if a batch is open, or saving fails.
2235	pub fn record_opened(&mut self, file: EntityId, at: u64) -> Result<(), StoreError> {
2236		self.check_usable()?;
2237		self.check_not_in_batch()?;
2238		self.commit_pending();
2239		self.save_records(&Writes {
2240			opened: vec![(file, at)],
2241			..Writes::default()
2242		})
2243	}
2244
2245	/// When each file was last opened on this device, by its ID, in milliseconds since 1970.
2246	///
2247	/// # Errors
2248	///
2249	/// Returns an error if the database fails.
2250	pub fn opened(&self) -> Result<BTreeMap<EntityId, u64>, StoreError> {
2251		self.file().opened()
2252	}
2253
2254	/// Writes a received sealed blob into a temporary file, and puts it in place if it has
2255	/// its sealed hash.
2256	fn receive_into(
2257		&self,
2258		temporary: &Path,
2259		file: File,
2260		sealed: &Hash,
2261		size: u64,
2262		bytes: impl Read,
2263	) -> Result<bool, StoreError> {
2264		let mut hasher = nibkeep_base::Hasher::new();
2265		let mut output = BufWriter::new(file);
2266		let mut buffer = vec![0; 64 * 1024];
2267		let mut bytes = bytes.take(size);
2268		let mut written = 0_u64;
2269		loop {
2270			let count = bytes.read(&mut buffer)?;
2271			if count == 0 {
2272				break;
2273			}
2274			hasher.update(&buffer[..count]);
2275			io::Write::write_all(&mut output, &buffer[..count])?;
2276			written += count as u64;
2277		}
2278		if written != size || hasher.finalize() != *sealed {
2279			return Ok(false);
2280		}
2281		output
2282			.into_inner()
2283			.map_err(io::IntoInnerError::into_error)?
2284			.sync_all()?;
2285		let staged = self.blobs.stage(temporary, sealed)?;
2286		self.blobs.place(&staged, sealed)?;
2287		Ok(true)
2288	}
2289
2290	/// Opens the wrapped blob keys that `keys` allow, as [`Log::open_blob_keys`] does, for
2291	/// example after the replica received an older space key, and removes from the disk
2292	/// those that turned out to be bad.
2293	///
2294	/// # Errors
2295	///
2296	/// Returns an error if saving fails.
2297	pub fn open_blob_keys(&mut self, keys: &SpaceKeys) -> Result<(), StoreError> {
2298		self.check_usable()?;
2299		self.check_not_in_batch()?;
2300		let all: Vec<Hash> = self
2301			.log
2302			.wrapped_blob_keys()
2303			.map(|(sealed, _)| *sealed)
2304			.collect();
2305		let before = self.blob_key_counts(all);
2306		self.log.open_blob_keys(keys);
2307		self.save_records(&Writes {
2308			blob_keys: self.blob_key_sets(self.dropped_blob_keys(before)),
2309			..Writes::default()
2310		})
2311	}
2312
2313	/// How many wrapped keys the log has for each of these sealed blobs.
2314	fn blob_key_counts(&self, sealed: impl IntoIterator<Item = Hash>) -> BTreeMap<Hash, usize> {
2315		sealed
2316			.into_iter()
2317			.map(|sealed| (sealed, self.log.wrapped_blob_keys_of(&sealed).len()))
2318			.collect()
2319	}
2320
2321	/// The sealed blobs that the log has fewer wrapped keys for than `before` counted, as it
2322	/// dropped those that turned out to be bad.
2323	fn dropped_blob_keys(&self, before: BTreeMap<Hash, usize>) -> Vec<Hash> {
2324		before
2325			.into_iter()
2326			.filter(|(sealed, count)| self.log.wrapped_blob_keys_of(sealed).len() < *count)
2327			.map(|(sealed, _)| sealed)
2328			.collect()
2329	}
2330
2331	/// Receives a wrapped blob key, as [`Log::receive_blob_key`] does, and saves the blob's
2332	/// keys if they changed.
2333	///
2334	/// # Errors
2335	///
2336	/// Returns an error if the replica's blob lock cannot be taken, or saving fails, in which
2337	/// case the key is not kept.
2338	pub fn receive_blob_key(
2339		&mut self,
2340		sealed: Hash,
2341		wrapped: WrappedBlobKey,
2342		keys: &SpaceKeys,
2343	) -> Result<(), StoreError> {
2344		// Under the blob lock, so that another space that purges the blob either sees this
2345		// key, or deletes the file before it, which the sealed blob that comes after the key
2346		// then brings back.
2347		let _lock = self.blobs.lock()?;
2348		self.apart(keys, |stored| {
2349			let before = stored.log.wrapped_blob_keys_of(&sealed).to_vec();
2350			let received = stored.log.receive_blob_key(sealed, wrapped, keys);
2351			logged(&mut stored.log, received)?;
2352			if stored.log.wrapped_blob_keys_of(&sealed) != before.as_slice() {
2353				let writes = Writes {
2354					blob_keys: stored.blob_key_sets([sealed]),
2355					..Writes::default()
2356				};
2357				stored.save(&writes, false, keys)?;
2358			}
2359			Ok(())
2360		})
2361	}
2362
2363	/// Purges a blob, as [`Log::purge_blob`] does: deletes its wrapped keys from the disk,
2364	/// then the files of its sealed copies. [`StoredLog::is_shredded`] tells whether no copy
2365	/// of the keys is left. Without its keys a sealed copy is unreadable, so a file that
2366	/// cannot be deleted now is deleted when the space is opened again.
2367	///
2368	/// # Errors
2369	///
2370	/// Returns the errors of [`Log::purge_blob`], or an error if saving fails, in which
2371	/// case nothing is purged.
2372	pub fn purge_blob(
2373		&mut self,
2374		author: &SigningKey,
2375		keys: &SpaceKeys,
2376		content: &Hash,
2377		wall_millis: u64,
2378		rng: &mut impl CryptoRng,
2379	) -> Result<Parcel, StoreError> {
2380		self.check_not_in_batch()?;
2381		self.changing(keys, |stored| {
2382			stored.waiting.last_wall = Some(wall_millis);
2383			let parcel = stored
2384				.log
2385				.purge_blob(author, keys, content, wall_millis, rng)?;
2386			let applied = stored.log.take_applied();
2387			let mut writes = Writes {
2388				changes: vec![parcel.clone()],
2389				..Writes::default()
2390			};
2391			let purged = stored.save_destroyed(&mut writes, &applied, keys)?;
2392			stored.remove_blob_files(&purged);
2393			Ok(parcel)
2394		})
2395	}
2396
2397	/// Seals content into a temporary file, and puts it in place unless the space holds the
2398	/// content already, or takes up a copy that another of the replica's spaces holds.
2399	fn import_from(
2400		&mut self,
2401		temporary: &Path,
2402		file: File,
2403		keys: &SpaceKeys,
2404		(content, secret): (impl Read, bool),
2405		elsewhere: &dyn Fn(&Hash) -> Vec<(Hash, Key)>,
2406		(wall_millis, rng): (u64, &mut impl CryptoRng),
2407	) -> Result<Hash, StoreError> {
2408		// A new key for every sealing: a key that another replica sent may not belong to the
2409		// content it claims.
2410		let key = Key::generate(rng);
2411		let mut output = BufWriter::new(file);
2412		let sealed = seal_blob(&key, content, &mut output, rng)?;
2413		if self.held_as(&sealed.content, secret) {
2414			return Ok(sealed.content);
2415		}
2416		for (copy, copy_key) in elsewhere(&sealed.content) {
2417			let shared = self.share_blob(
2418				keys,
2419				&sealed.content,
2420				(copy, &copy_key),
2421				secret,
2422				wall_millis,
2423				rng,
2424			)?;
2425			if shared {
2426				return Ok(sealed.content);
2427			}
2428		}
2429		output
2430			.into_inner()
2431			.map_err(io::IntoInnerError::into_error)?
2432			.sync_all()?;
2433		// Named after its sealed hash, the file is put in place when the space is opened
2434		// again if a crash comes after its key is saved.
2435		let staged = self.blobs.stage(temporary, &sealed.sealed)?;
2436		let added = if secret {
2437			self.log
2438				.add_secret_blob_key(sealed.content, sealed.sealed, key, keys, rng)
2439		} else {
2440			self.log
2441				.add_blob_key(sealed.content, sealed.sealed, key, keys, rng)
2442		};
2443		if let Err(error) = logged(&mut self.log, added) {
2444			let _ = fs::remove_file(&staged);
2445			return Err(error);
2446		}
2447		let writes = Writes {
2448			blob_keys: self.blob_key_sets([sealed.sealed]),
2449			verified: vec![(sealed.sealed, wall_millis)],
2450			..Writes::default()
2451		};
2452		if let Err(error) = self.save(&writes, false, keys) {
2453			let _ = fs::remove_file(&staged);
2454			return Err(error);
2455		}
2456		self.blobs.place(&staged, &sealed.sealed)?;
2457		Ok(sealed.content)
2458	}
2459
2460	/// The sealed copy of some content that the replica found intact most recently, or else
2461	/// the first one it holds.
2462	fn checked_last(&self, content: &Hash) -> Result<Option<HeldCopy<'_>>, StoreError> {
2463		let mut last: Option<HeldCopy<'_>> = None;
2464		for (sealed, key) in self.held(content) {
2465			let verified = self.file().verified(sealed)?;
2466			if last.as_ref().is_none_or(|last| verified > last.verified) {
2467				last = Some(HeldCopy {
2468					sealed,
2469					key,
2470					verified,
2471				});
2472			}
2473		}
2474		Ok(last)
2475	}
2476
2477	/// The sealed copies of some content that the replica holds, with their keys.
2478	fn held<'a>(&'a self, content: &Hash) -> impl Iterator<Item = (&'a Hash, &'a Key)> {
2479		self.log
2480			.blob_keys(content)
2481			.filter(|(sealed, _)| self.blobs.holds(sealed))
2482	}
2483
2484	/// Deletes the files of purged blobs that no other space of the replica keeps a key for,
2485	/// or in a batch, once the batch is saved. Without their keys they are unreadable, so one
2486	/// that cannot be deleted now is deleted when the space is opened again.
2487	fn remove_blob_files(&mut self, purged: &[Hash]) {
2488		match &mut self.batch {
2489			Some(batch) => batch.released.extend_from_slice(purged),
2490			None => self.release_blob_files(purged),
2491		}
2492	}
2493
2494	/// Deletes the files of sealed blobs whose keys purges destroyed, as far as no other space
2495	/// keeps a key for them; or, if the replica waits, keeps them apart.
2496	fn release_blob_files(&self, purged: &[Hash]) {
2497		if self.waiting.keeping {
2498			// A file that cannot be moved goes, as it would have.
2499			if self.blobs.keep_apart(purged).is_err() {
2500				let _ = self.blobs.release(purged);
2501			}
2502		} else {
2503			let _ = self.blobs.release(purged);
2504		}
2505	}
2506
2507	/// Finishes what a crash interrupted, with the space alone. A blob being written whose
2508	/// key was saved goes in place, and the other files being written go, but while another
2509	/// program has the space open, as it may be writing them. The files of purged blobs, which are unreadable without their keys, go as far as no other space
2510	/// keeps a key for them and they can be deleted now. The wrapped blob keys that turned
2511	/// out to be bad when the log was built leave the disk.
2512	fn recover_blobs(&mut self, dropped: Vec<Hash>) -> Result<(), StoreError> {
2513		let temporary = if self.lock.is_alone() {
2514			self.blobs.temporary_files()?
2515		} else {
2516			Vec::new()
2517		};
2518		for (path, staged) in temporary {
2519			match staged {
2520				Some(sealed) if !self.log.wrapped_blob_keys_of(&sealed).is_empty() => {
2521					let _ = self.blobs.place(&path, &sealed);
2522				}
2523				_ => {
2524					let _ = fs::remove_file(&path);
2525				}
2526			}
2527		}
2528		// Files of purged blobs whose keys a device that waits keeps apart are kept apart too,
2529		// as a crash between the two left them.
2530		let kept = self.file().kept_blobs()?;
2531		let (apart, purged): (Vec<Hash>, Vec<Hash>) = self
2532			.log
2533			.purged_blobs()?
2534			.into_iter()
2535			.partition(|sealed| kept.contains(sealed));
2536		let _ = self.blobs.keep_apart(&apart);
2537		let _ = self.blobs.release(&purged);
2538		self.save_records(&Writes {
2539			blob_keys: self.blob_key_sets(dropped),
2540			..Writes::default()
2541		})
2542	}
2543
2544	/// Saves records that do not change the log, such as checks of blobs and the removal
2545	/// of bad keys, and retries an unfinished truncation of the write-ahead log.
2546	fn save_records(&mut self, writes: &Writes) -> Result<(), StoreError> {
2547		self.file_mut().save(writes)?;
2548		if self.unshredded {
2549			self.unshredded = !self.file().truncate_wal().unwrap_or(false);
2550		}
2551		Ok(())
2552	}
2553
2554	/// Takes the operations of applied changes into the indexes, and notes that the state
2555	/// file holds them, in the transaction that takes them into the state. If that fails,
2556	/// the log, which accepted them already, is built again from the files, which do not
2557	/// hold them.
2558	fn take_in(
2559		&mut self,
2560		applied: &[(ChangeId, Payload)],
2561		keys: &SpaceKeys,
2562	) -> Result<(), StoreError> {
2563		// A state that a purge left stale is built again from the files, indexes and all.
2564		if self.log.is_stale() {
2565			return Ok(());
2566		}
2567		let taken = applied.iter().try_for_each(|(id, payload)| {
2568			index::apply(
2569				&self.log,
2570				self.postings(),
2571				self.fields(),
2572				payload.all_operations(),
2573			)?;
2574			self.postings().note_applied(id.hash())
2575		});
2576		if let Err(error) = taken {
2577			self.reload(keys);
2578			return Err(error);
2579		}
2580		Ok(())
2581	}
2582
2583	/// Runs `change`, which changes the log and saves it, in a transaction of the state
2584	/// file, which saving commits together with how far into the log file it now goes, or
2585	/// leaves open for the next change of a burst, as [`StoredLog::end_state_change`] says.
2586	/// If `change` fails before saving, what it wrote to the state file is left out; if the
2587	/// state file failed, the log is built again from the files. A change that finds the
2588	/// state file damaged is made once more, after the state file is made again. In a batch,
2589	/// `change` runs in the batch's transactions instead, as [`StoredLog::change_in_batch`]
2590	/// says.
2591	fn changing<T>(
2592		&mut self,
2593		keys: &SpaceKeys,
2594		mut change: impl FnMut(&mut Self) -> Result<T, StoreError>,
2595	) -> Result<T, StoreError> {
2596		if self.batch.is_some() {
2597			return self.change_in_batch(change);
2598		}
2599		let mut tries = 0;
2600		loop {
2601			tries += 1;
2602			match self.change_once(keys, &mut change) {
2603				Err(StoreError::State(_)) if tries == 1 => {
2604					if self.log.state().storage().ordinary().is_damaged() {
2605						self.reload(keys);
2606					}
2607				}
2608				result => return result,
2609			}
2610		}
2611	}
2612
2613	/// Runs `change` once, as [`StoredLog::changing`] says.
2614	fn change_once<T>(
2615		&mut self,
2616		keys: &SpaceKeys,
2617		change: &mut impl FnMut(&mut Self) -> Result<T, StoreError>,
2618	) -> Result<T, StoreError> {
2619		if self.standing == Standing::Behind
2620			|| self.log.state().storage().ordinary().is_damaged()
2621			|| self.pending_lost()
2622		{
2623			self.reload(keys);
2624		}
2625		self.check_usable()?;
2626		self.build_index()?;
2627		self.begin_writing(keys)?;
2628		if let Err(error) = self.begin_state_change() {
2629			let _ = self.file_mut().rollback();
2630			return Err(error);
2631		}
2632		let result = change(self);
2633		// The log's own account of a storage failure, taken before anything builds the log
2634		// again, which forgets it.
2635		let storage_failed = matches!(result, Err(StoreError::Log(LogError::Storage)));
2636		let result = result.map_err(|error| match error {
2637			StoreError::Log(LogError::Storage) => {
2638				self.log.storage_error().unwrap_or(StoreError::Broken)
2639			}
2640			error => error,
2641		});
2642		if storage_failed {
2643			self.reload(keys);
2644		} else if result.is_err() || self.file().in_transaction() {
2645			// A change that saved left no transaction of the log file open; what else is open
2646			// is left out, and the state file's transaction of the burst, if any, stays.
2647			self.roll_back_change(keys);
2648		}
2649		self.change_began = None;
2650		result
2651	}
2652
2653	/// Begins the log file's transaction, for a change or a batch, once the log has caught up
2654	/// with what others wrote, under that transaction's write lock, so that it never writes
2655	/// on a state it has not seen ([technical design: several programs on one replica]). The log file's write lock is taken
2656	/// before the state file's: the changes of a burst, which hold the state file's, commit
2657	/// first if another program holds the log file's, so that the two never wait for each
2658	/// other. A program that waits to make the state file anew, after a purge, is told so:
2659	/// the space is to be closed.
2660	///
2661	/// [technical design: several programs on one replica]: ../../../docs/Technical-design.md#78-several-programs-on-one-replica
2662	fn begin_writing(&mut self, keys: &SpaceKeys) -> Result<(), StoreError> {
2663		for _ in 0..CATCH_UP_TRIES {
2664			let began = self.postings().in_transaction() && self.file_mut().begin_now()?;
2665			if !began {
2666				self.commit_pending();
2667				self.file_mut().begin()?;
2668			}
2669			if self.remake.exists() {
2670				// Built again at the next change, which makes the state file anew, or lets go
2671				// of the mark, once no other program has the space open.
2672				let _ = self.file_mut().rollback();
2673				self.standing = Standing::Behind;
2674				return Err(StoreError::InUse);
2675			}
2676			let versions = self.versions();
2677			if versions
2678				.as_ref()
2679				.is_ok_and(|versions| *versions == self.seen)
2680			{
2681				return Ok(());
2682			}
2683			let _ = self.file_mut().rollback();
2684			versions?;
2685			self.commit_pending();
2686			self.reload(keys);
2687			self.check_usable()?;
2688			self.build_index()?;
2689		}
2690		Err(StoreError::InUse)
2691	}
2692
2693	/// Changes the log in memory, and saves what changes apart from a change, such as a key
2694	/// received, once the log has caught up with what others wrote, under the log file's
2695	/// write lock, as [`StoredLog::begin_writing`] says: what it saves of a statement or a
2696	/// blob replaces what the files hold of it.
2697	fn apart<T>(
2698		&mut self,
2699		keys: &SpaceKeys,
2700		change: impl FnOnce(&mut Self) -> Result<T, StoreError>,
2701	) -> Result<T, StoreError> {
2702		self.check_not_in_batch()?;
2703		if self.standing == Standing::Behind {
2704			self.reload(keys);
2705		}
2706		self.check_usable()?;
2707		self.begin_writing(keys)?;
2708		let result = change(self);
2709		// Nothing was saved, or saving failed, which builds the log again.
2710		if self.file().in_transaction() {
2711			let _ = self.file_mut().rollback();
2712		}
2713		result
2714	}
2715
2716	/// Begins the state file's part of a change: its transaction, or, while the transaction
2717	/// of a burst holds changes saved before, a savepoint in it, so that this change alone
2718	/// can be left out.
2719	fn begin_state_change(&mut self) -> Result<(), StoreError> {
2720		self.change_began = Some(self.ticks.now());
2721		if self.postings().in_transaction()
2722			&& let Some(mut pending) = self.pending.get()
2723		{
2724			self.log.storage_mut().savepoint(Savepoint::Change)?;
2725			pending.savepoint = true;
2726			self.pending.set(Some(pending));
2727			return Ok(());
2728		}
2729		self.pending.set(None);
2730		self.log.storage_mut().begin()
2731	}
2732
2733	/// Whether an error ended the state file's transaction with the changes of a burst in
2734	/// it: the log file holds them, and the state file lacks them until the log is built
2735	/// again from the files, which takes them in.
2736	fn pending_lost(&self) -> bool {
2737		self.pending
2738			.get()
2739			.is_some_and(|pending| pending.lost || !self.postings().in_transaction())
2740	}
2741
2742	/// Ends the state file's part of a change saved to the log file: keeps what it wrote,
2743	/// notes how far into the log file the state file goes now, and commits the transaction,
2744	/// unless the change began within [`BURST_GAP`] of the last change saved: the changes of
2745	/// a burst commit together, when a change comes later than that, when they are
2746	/// [`PENDING_CHANGES`], when a change comes more than [`PENDING_FOR`] after the first of
2747	/// them, and when the space closes. What is saved apart from a change while a burst is
2748	/// pending, such as a blob or a key, waits with the burst, and does not count as a
2749	/// change. If the state file fails, the log file holds what it lacks, which building
2750	/// the log again takes in.
2751	fn end_state_change(&mut self, keys: &SpaceKeys) -> Result<(), StoreError> {
2752		if self.change_began.is_none()
2753			&& let Some(pending) = self.pending.get()
2754		{
2755			if self.mark_state().is_err() {
2756				self.reload(keys);
2757				return self.check_usable();
2758			}
2759			// Saving is using the space, which commits a burst that has waited long enough.
2760			if self.ticks.now().duration_since(pending.since) >= PENDING_FOR {
2761				self.commit_state(keys)?;
2762			}
2763			return Ok(());
2764		}
2765		let burst = match (self.last_saved, self.change_began.take()) {
2766			(Some(last), Some(began)) => began.duration_since(last) < BURST_GAP,
2767			_ => false,
2768		};
2769		let kept = match self.pending.get() {
2770			Some(pending) if pending.savepoint => {
2771				self.pending.set(Some(Pending {
2772					savepoint: false,
2773					..pending
2774				}));
2775				self.log.storage_mut().release(Savepoint::Change)
2776			}
2777			_ => Ok(()),
2778		};
2779		if kept.and_then(|()| self.mark_state()).is_err() {
2780			self.reload(keys);
2781			return self.check_usable();
2782		}
2783		let now = self.ticks.now();
2784		let mut pending = self.pending.get().unwrap_or(Pending {
2785			changes: 0,
2786			since: now,
2787			savepoint: false,
2788			lost: false,
2789		});
2790		pending.changes += 1;
2791		self.pending.set(Some(pending));
2792		// Another program that has the space open would wait for the state file's write lock
2793		// while a burst holds it: changes commit one by one then.
2794		let due = !burst
2795			|| pending.changes >= PENDING_CHANGES
2796			|| now.duration_since(pending.since) >= PENDING_FOR
2797			|| (pending.changes == 1 && self.lock.shared_with_others());
2798		if due {
2799			self.commit_state(keys)?;
2800		}
2801		self.last_saved = Some(self.ticks.now());
2802		Ok(())
2803	}
2804
2805	/// Leaves out what the change being made wrote to both files: the log file's
2806	/// transaction, and in the state file the change's savepoint, or its transaction where
2807	/// no change of a burst is pending in it. If an error ended the state file's transaction
2808	/// already, with the changes of a burst in it, the log is built again from the files,
2809	/// which takes them in.
2810	fn roll_back_change(&mut self, keys: &SpaceKeys) {
2811		self.change_began = None;
2812		if self.postings().in_transaction() {
2813			match self.pending.get() {
2814				Some(pending) if pending.savepoint => {
2815					self.pending.set(Some(Pending {
2816						savepoint: false,
2817						..pending
2818					}));
2819					let _ = self
2820						.log
2821						.storage_mut()
2822						.rollback_to_savepoint(Savepoint::Change);
2823				}
2824				Some(_) => {}
2825				None => {
2826					let _ = self.log.storage_mut().rollback();
2827				}
2828			}
2829		} else if self.pending.take().is_some() {
2830			self.reload(keys);
2831			return;
2832		}
2833		if self.file().in_transaction() {
2834			let _ = self.file_mut().rollback();
2835		}
2836	}
2837
2838	/// Runs `change` in the open batch, after a savepoint of each file. A change that is
2839	/// refused goes back to its savepoints, and the batch goes on. If the files fail, the
2840	/// whole batch is left out, and the log is built again from the files; the batch's
2841	/// later changes are then refused. A change that finds the state file damaged is not
2842	/// made again, which would leave out the changes before it.
2843	fn change_in_batch<T>(
2844		&mut self,
2845		change: impl FnOnce(&mut Self) -> Result<T, StoreError>,
2846	) -> Result<T, StoreError> {
2847		if self.batch.as_ref().is_some_and(|batch| batch.lost) {
2848			return Err(StoreError::BatchLost);
2849		}
2850		if !self.both_in_transaction() {
2851			// A read found a file failing, which ended its transaction.
2852			self.lose_batch(false);
2853			return Err(StoreError::BatchLost);
2854		}
2855		let reloads = self.reloads;
2856		// What the batch's purges destroyed so far, kept if this change goes back to its
2857		// savepoints.
2858		let destroyed = self
2859			.batch
2860			.as_ref()
2861			.map(|batch| (batch.purged, batch.released.len()));
2862		let began = self.build_index().and_then(|()| {
2863			self.file_mut().savepoint()?;
2864			self.log.storage_mut().savepoint(Savepoint::Change)
2865		});
2866		if let Err(error) = began {
2867			self.lose_batch(self.reloads > reloads);
2868			return Err(error);
2869		}
2870		let result = change(self);
2871		let failed = match &result {
2872			Ok(_) => !self.both_in_transaction(),
2873			Err(error) => {
2874				matches!(error, StoreError::Log(LogError::Storage)) || !self.both_in_transaction()
2875			}
2876		};
2877		if failed {
2878			let error = match result {
2879				Err(StoreError::Log(LogError::Storage)) => {
2880					self.log.storage_error().unwrap_or(StoreError::Broken)
2881				}
2882				Err(error) => error,
2883				Ok(_) => StoreError::BatchLost,
2884			};
2885			self.lose_batch(self.reloads > reloads);
2886			return Err(error);
2887		}
2888		let ended = if result.is_ok() {
2889			self.file_mut()
2890				.release()
2891				.and_then(|()| self.log.storage_mut().release(Savepoint::Change))
2892		} else {
2893			if let (Some(batch), Some((purged, released))) = (&mut self.batch, destroyed) {
2894				batch.purged = purged;
2895				batch.released.truncate(released);
2896			}
2897			self.file_mut().rollback_to_savepoint().and_then(|()| {
2898				self.log
2899					.storage_mut()
2900					.rollback_to_savepoint(Savepoint::Change)
2901			})
2902		};
2903		if let Err(error) = ended {
2904			self.lose_batch(false);
2905			return Err(error);
2906		}
2907		result
2908	}
2909
2910	/// Leaves out every change of the open batch, after the files failed, and builds the
2911	/// log again from them, unless the failure did already. The batch stays open, lost,
2912	/// until it ends.
2913	fn lose_batch(&mut self, rebuilt: bool) {
2914		if let Some(mut batch) = self.batch.take() {
2915			if !batch.lost {
2916				if !rebuilt {
2917					self.reload(&batch.keys);
2918				}
2919				batch.lost = true;
2920			}
2921			self.batch = Some(batch);
2922		}
2923	}
2924
2925	/// Whether both files have a transaction open, as a batch has.
2926	fn both_in_transaction(&self) -> bool {
2927		self.file().in_transaction() && self.postings().in_transaction()
2928	}
2929
2930	/// Returns [`StoreError::InBatch`] if a batch of changes is open.
2931	const fn check_not_in_batch(&self) -> Result<(), StoreError> {
2932		if self.batch.is_some() {
2933			return Err(StoreError::InBatch);
2934		}
2935		Ok(())
2936	}
2937
2938	/// Leaves out what was written to both files since their transactions began, if they
2939	/// have not ended, the changes of a burst that the state file holds included: the log
2940	/// file holds them, and building the log again takes them in.
2941	fn roll_back(&mut self) {
2942		self.pending.set(None);
2943		self.change_began = None;
2944		if self.log.storage_mut().in_transaction() {
2945			let _ = self.log.storage_mut().rollback();
2946		}
2947		if self.file().in_transaction() {
2948			let _ = self.file_mut().rollback();
2949		}
2950	}
2951
2952	/// A waiting change with its parts, which the log file holds apart from the history:
2953	/// what the log has of an accepted change, it saves itself.
2954	fn waiting_parcel(&self, id: ChangeId) -> Result<Option<Parcel>, StoreError> {
2955		if self.file().contains(id)? {
2956			return Ok(None);
2957		}
2958		self.log.parcel(id)
2959	}
2960
2961	/// The log file.
2962	const fn file(&self) -> &LogFile {
2963		self.log.history()
2964	}
2965
2966	/// The log file, to write.
2967	fn file_mut(&mut self) -> &mut LogFile {
2968		self.log.history_mut()
2969	}
2970
2971	fn check_usable(&self) -> Result<(), StoreError> {
2972		if self.standing == Standing::Broken {
2973			return Err(StoreError::Broken);
2974		}
2975		if self.standing == Standing::Behind {
2976			return Err(StoreError::InUse);
2977		}
2978		Ok(())
2979	}
2980
2981	/// The wrapped keys that the log has for some statements.
2982	fn key_sets(
2983		&self,
2984		statements: impl IntoIterator<Item = StatementId>,
2985	) -> Vec<(StatementId, Vec<WrappedKey>)> {
2986		statements
2987			.into_iter()
2988			.map(|statement| (statement, self.log.wrapped_keys_of(statement).to_vec()))
2989			.collect()
2990	}
2991
2992	/// The wrapped keys that the log has for some sealed blobs.
2993	fn blob_key_sets(
2994		&self,
2995		sealed: impl IntoIterator<Item = Hash>,
2996	) -> Vec<(Hash, Vec<WrappedBlobKey>)> {
2997		sealed
2998			.into_iter()
2999			.map(|sealed| {
3000				let keys = self.log.wrapped_blob_keys_of(&sealed).to_vec();
3001				(sealed, keys)
3002			})
3003			.collect()
3004	}
3005
3006	fn all_key_sets(&self) -> BTreeMap<StatementId, Vec<WrappedKey>> {
3007		let mut sets: BTreeMap<StatementId, Vec<WrappedKey>> = BTreeMap::new();
3008		for (statement, wrapped) in self.log.wrapped_keys() {
3009			sets.entry(statement).or_default().push(wrapped.clone());
3010		}
3011		sets
3012	}
3013
3014	/// Saves to the log file, with what the log wrote to it as its history, and then ends
3015	/// the state file's part of the change, if its transaction has begun, as
3016	/// [`StoredLog::end_state_change`] says; truncates the write-ahead log after purges. If
3017	/// saving fails, builds the log again from the files, so that the log never holds what
3018	/// the file does not; if that fails too, the stored log is unusable and its log empty.
3019	/// If only the state file fails, the change is saved, and the state file takes it in
3020	/// from the log file. In a batch, both transactions stay open, for the batch's end to
3021	/// commit, and to act on purges, which only changes received in it make.
3022	fn save(&mut self, writes: &Writes, purges: bool, keys: &SpaceKeys) -> Result<(), StoreError> {
3023		let batch = self.batch.is_some();
3024		if purges && let Some(batch) = &mut self.batch {
3025			batch.purged = true;
3026		}
3027		if writes.is_empty() && !self.file().wrote() && !self.log.is_stale() {
3028			// Nothing changed, such as for a change received twice: neither file is written.
3029			if !batch {
3030				self.roll_back_change(keys);
3031			}
3032			return Ok(());
3033		}
3034		let saved = self.file_mut().save(writes).and_then(|()| {
3035			if !batch && self.file().in_transaction() {
3036				self.file_mut().commit()
3037			} else {
3038				Ok(())
3039			}
3040		});
3041		if let Err(error) = saved {
3042			self.reload(keys);
3043			return Err(error);
3044		}
3045		if batch {
3046			return Ok(());
3047		}
3048		if self.log.take_stale() {
3049			// A purge took away what the state file holds: it is written anew, under a new
3050			// key, from the log file, which no longer holds what was purged. The change is
3051			// saved, even if that waits for others to close the space.
3052			self.remake_state(keys);
3053			if self.standing == Standing::Broken {
3054				return Err(StoreError::Broken);
3055			}
3056		} else if self.log.storage_mut().in_transaction() {
3057			self.end_state_change(keys)?;
3058		}
3059		if purges || self.unshredded {
3060			// The purge is saved; if another program holds the database, the old copies are
3061			// removed on a later save.
3062			self.unshredded = !self.file().truncate_wal().unwrap_or(false);
3063		}
3064		Ok(())
3065	}
3066
3067	/// Notes in the state file's transaction how far into the log file it goes now: to its
3068	/// last row, after the log file committed.
3069	fn mark_state(&mut self) -> Result<(), StoreError> {
3070		if let Some(mark) = self.file().last()? {
3071			self.log.storage_mut().set_mark(&mark)?;
3072		}
3073		Ok(())
3074	}
3075
3076	/// Commits the transaction of the state file, with the changes it holds and how far
3077	/// into the log file it goes. If that fails, the log file holds what the state file
3078	/// lacks, which building the log again takes in.
3079	fn commit_state(&mut self, keys: &SpaceKeys) -> Result<(), StoreError> {
3080		self.pending.set(None);
3081		if self.log.storage_mut().commit().is_err() {
3082			self.reload(keys);
3083			self.check_usable()?;
3084		}
3085		Ok(())
3086	}
3087
3088	/// Makes the state file anew, under a new key, and builds the log and the indexes again
3089	/// from the files, alone: other programs that have the space open are waited for, for a
3090	/// while, as [`StoredLog::wait_alone`] says. If they keep it, the stored log is behind,
3091	/// and the state file is made anew by the first that opens the space alone. If making it
3092	/// fails, the stored log is unusable and its log empty.
3093	fn remake_state(&mut self, keys: &SpaceKeys) {
3094		self.roll_back();
3095		if !self.wait_alone() {
3096			self.log.reset(Clock::new(self.max_drift_millis));
3097			self.standing = Standing::Behind;
3098			return;
3099		}
3100		if self
3101			.log
3102			.storage_mut()
3103			.remake(&self.state_key, state_rng())
3104			.is_ok()
3105		{
3106			self.reload(keys);
3107		} else {
3108			self.log.reset(Clock::new(self.max_drift_millis));
3109			self.standing = Standing::Broken;
3110		}
3111		let _ = fs::remove_file(&self.remake);
3112		self.lock.share();
3113	}
3114
3115	/// Takes the space's lock alone, waiting up to [`PURGE_WAIT`] for the other programs that
3116	/// have the space open to close it: the mark that says so tells them to at their next
3117	/// change. Returns whether it has the lock alone. The mark stays if it does not, until a
3118	/// program opens the space alone, which makes the state file anew.
3119	fn wait_alone(&self) -> bool {
3120		if self.lock.alone() {
3121			return true;
3122		}
3123		let _ = File::create(&self.remake);
3124		let waited = Instant::now();
3125		while waited.elapsed() < PURGE_WAIT {
3126			std::thread::sleep(PURGE_LOOK);
3127			if self.lock.alone() {
3128				return true;
3129			}
3130		}
3131		false
3132	}
3133
3134	/// Builds the log and the indexes again from the files: after another program wrote to
3135	/// the space, or after a failure left the log out of step with them. A state file that
3136	/// must be made anew is made so only alone: while others have the space open, the stored
3137	/// log is behind. If building fails otherwise, the stored log is unusable and its log
3138	/// empty.
3139	fn reload(&mut self, keys: &SpaceKeys) {
3140		self.reloads += 1;
3141		let mut keys = keys.clone();
3142		if self.locked {
3143			keys.forget_secrets();
3144		}
3145		self.roll_back();
3146		self.log.reset(Clock::new(self.max_drift_millis));
3147		self.adopt_indexed_fields();
3148		let was_alone = self.lock.is_alone();
3149		let lock = &self.lock;
3150		// Damage found since opening may be where building again does not read.
3151		let remade = if !self.log.state().storage().ordinary().is_damaged() {
3152			Ok(())
3153		} else if lock.alone() {
3154			self.log.storage_mut().remake(&self.state_key, state_rng())
3155		} else {
3156			Err(StoreError::InUse)
3157		};
3158		// Before the log is built, so that what others write meanwhile is caught up with
3159		// later.
3160		let seen = remade.and_then(|()| {
3161			Ok((
3162				self.log.history().data_version()?,
3163				self.log.state().storage().ordinary().data_version()?,
3164			))
3165		});
3166		let fields = Fields {
3167			secret: &self.secret_fields,
3168			last_writer_wins: &self.last_writer_wins,
3169		};
3170		let built = seen.and_then(|seen| {
3171			build(
3172				&mut self.log,
3173				&keys,
3174				self.max_drift_millis,
3175				&self.state_key,
3176				fields,
3177				&|| lock.alone(),
3178			)?;
3179			Ok(seen)
3180		});
3181		match built {
3182			Ok(seen) => {
3183				if self.standing == Standing::Behind {
3184					self.standing = Standing::Usable;
3185				}
3186				// The state file is in step with the log file now: a mark that waits for it to
3187				// be made anew goes, once no other program has the space open.
3188				if self.remake.exists() && self.lock.alone() {
3189					let _ = fs::remove_file(&self.remake);
3190				}
3191				self.seen = seen;
3192				// Alone, nothing was missed, and the state file may have been made anew.
3193				if self.lock.is_alone()
3194					&& let Ok(versions) = self.versions()
3195				{
3196					self.seen = versions;
3197				}
3198			}
3199			// Another program has the space alone, or holds a write lock longer than SQLite
3200			// waits: building again is tried at the next change.
3201			Err(error) if matches!(error, StoreError::InUse) || error.busy() => {
3202				self.log.reset(Clock::new(self.max_drift_millis));
3203				self.standing = Standing::Behind;
3204			}
3205			Err(_) => {
3206				// The state goes too, so that it shows nothing, as the log does.
3207				self.log.reset(Clock::new(self.max_drift_millis));
3208				if self.lock.alone() {
3209					let _ = self.log.storage_mut().remake(&self.state_key, state_rng());
3210				}
3211				self.standing = Standing::Broken;
3212			}
3213		}
3214		if !was_alone {
3215			self.lock.share();
3216		}
3217		self.note_index();
3218	}
3219
3220	/// Takes the fields that the state file's indexes were built with as the special ones,
3221	/// unless fewer of them are secret than here, as opening does: another program that has
3222	/// the space open may have made more fields secret, whose values are sealed from then on
3223	/// here too.
3224	fn adopt_indexed_fields(&mut self) {
3225		if let Ok(Some((secret, last_writer_wins))) = self.postings().indexed_fields()
3226			&& self.secret_fields.is_subset(&secret)
3227		{
3228			self.log.set_secret_fields(secret.iter().cloned());
3229			self.secret_fields = secret;
3230			self.last_writer_wins = last_writer_wins;
3231		}
3232	}
3233}
3234
3235/// A sealed copy of some content that the replica holds.
3236struct HeldCopy<'a> {
3237	sealed: &'a Hash,
3238	key: &'a Key,
3239	/// When the replica last found it intact.
3240	verified: Option<u64>,
3241}
3242
3243/// Builds a space's log from its file into `log`, which keeps its history in the log file
3244/// and its state in the state file, as [`load`] does, and the indexes, unless they were
3245/// built with the fields that are special now. A state file that does not match the log
3246/// file, or turns out damaged on the way, is made again and takes in every change, if
3247/// `may_remake` says that the program has the space alone; otherwise the build fails with
3248/// [`StoreError::InUse`]. Returns the sealed hashes of the blobs some of whose stored
3249/// wrapped keys turned out to be bad.
3250fn build(
3251	log: &mut Log<StateFile, LogFile>,
3252	keys: &SpaceKeys,
3253	max_drift_millis: u64,
3254	state_key: &Key,
3255	fields: Fields<'_>,
3256	may_remake: &dyn Fn() -> bool,
3257) -> Result<Vec<Hash>, StoreError> {
3258	let attempt = |log: &mut Log<StateFile, LogFile>| -> Result<Vec<Hash>, StoreError> {
3259		let dropped = load(log, keys, fields)?;
3260		if !indexed_with(log, fields)? {
3261			let was = log.state().storage().ordinary().indexed_fields()?;
3262			ensure_index(
3263				log,
3264				was.as_ref(),
3265				(fields.secret.clone(), fields.last_writer_wins.clone()),
3266				false,
3267			)?;
3268		}
3269		Ok(dropped)
3270	};
3271	match attempt(log) {
3272		Err(StoreError::State(_)) if may_remake() => {
3273			log.reset(Clock::new(max_drift_millis));
3274			log.storage_mut().remake(state_key, state_rng())?;
3275			attempt(log)
3276		}
3277		// Only a program that has the space alone may make the state file anew.
3278		Err(StoreError::State(_)) => Err(StoreError::InUse),
3279		built => built,
3280	}
3281}
3282
3283/// Opens a space's state file, or makes it anew if it cannot be used, as
3284/// [`StateFile::open_or_make`] does, but only `alone`: while others have the space open, it
3285/// is made anew by the first that opens the space alone.
3286fn open_state(path: &Path, key: &Key, alone: bool) -> Result<StateFile, StoreError> {
3287	if alone {
3288		return StateFile::open_or_make(path, key, state_rng);
3289	}
3290	match StateFile::open(path, key, state_rng()) {
3291		Err(StoreError::State(_)) => Err(StoreError::InUse),
3292		opened => opened,
3293	}
3294}
3295
3296/// Whether the indexes of a log's state were built with the fields that are special now.
3297fn indexed_with(log: &Log<StateFile, LogFile>, fields: Fields<'_>) -> Result<bool, StoreError> {
3298	Ok(matches!(
3299		log.state().storage().ordinary().indexed_fields()?,
3300		Some((secret, last)) if secret == *fields.secret && last == *fields.last_writer_wins
3301	))
3302}
3303
3304/// Brings the indexes of a log's state to the fields that are special, secret and whose
3305/// last writer wins: from the fields they were built with, `was`, indexing again the fields
3306/// that changed, or anew, if they were not built. It runs in a transaction of its own, which
3307/// only the indexes are written in, so that a failure leaves the state file readable, or
3308/// else, in a transaction that has begun, of a batch or of a burst of changes, in a
3309/// savepoint of it, which commits with its changes.
3310fn ensure_index(
3311	log: &mut Log<StateFile, LogFile>,
3312	was: Option<&SpecialFields>,
3313	(secret, last_writer_wins): SpecialFields,
3314	in_transaction: bool,
3315) -> Result<(), StoreError> {
3316	let own = !in_transaction;
3317	if own {
3318		log.storage_mut().begin_derived()?;
3319	} else {
3320		log.storage_mut().savepoint(Savepoint::Indexes)?;
3321	}
3322	let fields = Fields {
3323		secret: &secret,
3324		last_writer_wins: &last_writer_wins,
3325	};
3326	let postings = log.state().storage().ordinary();
3327	let brought = match was {
3328		Some((was_secret, was_last)) => index::rebuild_fields(
3329			log,
3330			postings,
3331			Fields {
3332				secret: was_secret,
3333				last_writer_wins: was_last,
3334			},
3335			fields,
3336		),
3337		None => index::build(log, postings, fields),
3338	};
3339	let built = brought.and_then(|()| postings.set_indexed_fields(&secret, &last_writer_wins));
3340	match built {
3341		Ok(()) if own => log.storage_mut().commit(),
3342		Ok(()) => log.storage_mut().release(Savepoint::Indexes),
3343		Err(error) => {
3344			if log.storage_mut().in_transaction() {
3345				let _ = if own {
3346					log.storage_mut().rollback()
3347				} else {
3348					log.storage_mut().rollback_to_savepoint(Savepoint::Indexes)
3349				};
3350			}
3351			Err(error)
3352		}
3353	}
3354}
3355
3356/// Opens a space's log, whose history is the log file: takes the waiting changes and the
3357/// wrapped keys into memory, resumes the clock, and has the state file catch up with the
3358/// log file, in one transaction of each. Returns the sealed hashes of the blobs some of
3359/// whose stored wrapped keys turned out to be bad.
3360fn load(
3361	log: &mut Log<StateFile, LogFile>,
3362	keys: &SpaceKeys,
3363	fields: Fields<'_>,
3364) -> Result<Vec<Hash>, StoreError> {
3365	if let Some(latest) = log.history().latest()? {
3366		log.resume_clock(latest);
3367	}
3368	log.history_mut().begin()?;
3369	let caught_up = log
3370		.storage_mut()
3371		.begin()
3372		.and_then(|()| catch_up(log, keys, fields));
3373	let committed = match caught_up {
3374		Ok(true) => log
3375			.history_mut()
3376			.commit()
3377			.and_then(|()| log.storage_mut().commit()),
3378		Ok(false) => Ok(()),
3379		Err(error) => Err(error),
3380	};
3381	// Whatever happened, no transaction is left open.
3382	if log.storage_mut().in_transaction() {
3383		let _ = log.storage_mut().rollback();
3384	}
3385	if log.history().in_transaction() {
3386		let _ = log.history_mut().rollback();
3387	}
3388	committed?;
3389	for (statement, wrapped) in log.history().wrapped_keys()? {
3390		let received = log.receive_wrapped_key(statement, wrapped, keys);
3391		logged(log, received)?;
3392	}
3393	let mut stored: BTreeMap<Hash, usize> = BTreeMap::new();
3394	for (sealed, wrapped) in log.history().blob_keys()? {
3395		*stored.entry(sealed).or_default() += 1;
3396		let received = log.receive_blob_key(sealed, wrapped, keys);
3397		logged(log, received)?;
3398	}
3399	Ok(stored
3400		.into_iter()
3401		.filter(|(sealed, count)| log.wrapped_blob_keys_of(sealed).len() < *count)
3402		.map(|(sealed, _)| sealed)
3403		.collect())
3404}
3405
3406/// Has the state file catch up with the log file, in transactions of both that have
3407/// begun: takes the waiting changes back, applies the changes after the state file's mark
3408/// that the log file says are applied and the state file lacks, and those that `keys` let
3409/// the log read now, takes them into the indexes, and moves the mark. Returns whether it
3410/// wrote anything. Returns [`StoreError::State`] if the mark's tag is no change's in the log
3411/// file at the mark's sequence or later, or the state file holds a change that was purged:
3412/// the state file is then ahead of the log file, does not belong to it, or holds what a
3413/// purge took away, such as when a crash kept it from being written anew.
3414fn catch_up(
3415	log: &mut Log<StateFile, LogFile>,
3416	keys: &SpaceKeys,
3417	fields: Fields<'_>,
3418) -> Result<bool, StoreError> {
3419	let mark = log.state().storage().ordinary().mark()?;
3420	if let Some(mark) = &mark {
3421		// A row moves only to the end, so one before the mark's sequence is from an older
3422		// log file.
3423		let at = log.history().sequence_of(&mark.tag)?;
3424		if at.is_none_or(|at| at < mark.sequence) {
3425			return Err(StoreError::State(
3426				"it is ahead of the log file, or does not match it".to_owned(),
3427			));
3428		}
3429	}
3430	for purged in log.purged_changes()? {
3431		if log
3432			.state()
3433			.storage()
3434			.ordinary()
3435			.has_applied(purged.hash())?
3436		{
3437			return Err(StoreError::State(
3438				"it holds what a purge took away".to_owned(),
3439			));
3440		}
3441	}
3442	for set_aside in log.set_aside_changes()? {
3443		if log
3444			.state()
3445			.storage()
3446			.ordinary()
3447			.has_applied(set_aside.hash())?
3448		{
3449			return Err(StoreError::State(
3450				"it holds a change that was set aside".to_owned(),
3451			));
3452		}
3453	}
3454	// The changes the state file takes in go into the indexes too, in the same transaction,
3455	// unless the indexes are to be built anew, with other fields.
3456	let indexed = indexed_with(log, fields)?;
3457	// Each change goes into the indexes right after it goes into the state, as the indexes
3458	// follow the state change by change.
3459	let mut wrote = false;
3460	for parcel in log.history().waiting()? {
3461		let restored = log.restore(parcel, keys, false);
3462		logged(log, restored)?;
3463		wrote |= take_in_indexes(log, fields, indexed)?;
3464	}
3465	let since = mark.as_ref().map_or(0, |mark| mark.sequence);
3466	for id in log.history().applied_since(since)? {
3467		if !log.state().storage().ordinary().has_applied(id.hash())? {
3468			let reapplied = log.reapply(id, keys);
3469			logged(log, reapplied)?;
3470			wrote |= take_in_indexes(log, fields, indexed)?;
3471		}
3472	}
3473	// Pending changes that changed since may be readable now; the others were not when
3474	// the state file last caught up, and [`StoredLog::open_changes`] tries them again when
3475	// keys arrive.
3476	let pending = log.history().pending_since(since)?;
3477	let opened = log.open_changes_of(pending, keys);
3478	logged(log, opened)?;
3479	wrote |= take_in_indexes(log, fields, indexed)?;
3480	let last = log.history().last()?;
3481	if !wrote && last == mark {
3482		return Ok(false);
3483	}
3484	// The indexes, which do not take these changes in, are to be built again.
3485	if !indexed {
3486		log.state().storage().ordinary().forget_indexed_fields()?;
3487	}
3488	if let Some(last) = last {
3489		log.storage_mut().set_mark(&last)?;
3490	}
3491	Ok(true)
3492}
3493
3494/// Takes the changes whose operations the log just applied into the indexes, unless they
3495/// are to be built anew, and notes that the state file holds them. Returns whether there
3496/// were any.
3497fn take_in_indexes(
3498	log: &mut Log<StateFile, LogFile>,
3499	fields: Fields<'_>,
3500	indexed: bool,
3501) -> Result<bool, StoreError> {
3502	let applied = log.take_applied();
3503	for (id, payload) in &applied {
3504		if indexed {
3505			index::apply(
3506				log,
3507				log.state().storage().ordinary(),
3508				fields,
3509				payload.all_operations(),
3510			)?;
3511		}
3512		log.state().storage().ordinary().note_applied(id.hash())?;
3513	}
3514	Ok(!applied.is_empty())
3515}
3516
3517/// What the log did, with its failure to read or write the storage told as the storage's
3518/// error.
3519fn logged<T>(
3520	log: &mut Log<StateFile, LogFile>,
3521	result: Result<T, LogError>,
3522) -> Result<T, StoreError> {
3523	result.map_err(|error| match error {
3524		LogError::Storage => log.storage_error().unwrap_or(StoreError::Broken),
3525		error => StoreError::Log(error),
3526	})
3527}
3528
3529/// The error for a sealed copy that does not read back.
3530fn blob_error(error: io::Error) -> StoreError {
3531	if error.kind() == io::ErrorKind::InvalidData {
3532		StoreError::DamagedBlob
3533	} else {
3534		StoreError::Io(error)
3535	}
3536}
3537
3538/// The wall clock time now, in milliseconds since 1970.
3539fn wall_now() -> u64 {
3540	std::time::SystemTime::now()
3541		.duration_since(std::time::UNIX_EPOCH)
3542		.map_or(0, |since| {
3543			u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
3544		})
3545}