use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::Path;
use nibkeep_base::{EntityId, Hash, SpaceId, StatementId};
use nibkeep_crypto::rand_core::CryptoRng;
use nibkeep_log::list::{is_position, position_between};
use nibkeep_model::storage::Statements;
use nibkeep_model::{
FieldDef, FieldName, Name, Operation, Resolution, State, Statement, TypeDef, TypeName, Value,
ValueKind, fields,
};
use nibkeep_std::{
CAMERA_MAKE, CONTENT, FILE, FOUND_ON, MEDIA_TYPE, MODIFIED, ORIGIN, ORIGIN_OF, PATH, SIZE,
};
use super::Library;
use super::accounts::Copies;
use super::entities::{PART, by_parts};
use super::files::{moment, resolved_path};
use crate::NodeError;
pub const STORAGE_POLICY: TypeName = TypeName::from_static("org.nibkeep.storage-policy");
pub const STORAGE_RULE: TypeName = TypeName::from_static("org.nibkeep.storage-rule");
pub const POLICY: FieldName = FieldName::from_static("org.nibkeep.policy");
pub(crate) const POLICY_COPIES: FieldName = FieldName::from_static("org.nibkeep.policy-copies");
pub(crate) const POLICY_AWAY: FieldName = FieldName::from_static("org.nibkeep.policy-away");
pub(crate) const POLICY_ARCHIVED: FieldName = FieldName::from_static("org.nibkeep.policy-archived");
pub(crate) const POLICY_KEPT: FieldName = FieldName::from_static("org.nibkeep.policy-kept");
pub(crate) const RULE_POLICY: FieldName = FieldName::from_static("org.nibkeep.rule-policy");
pub(crate) const RULE_TYPE: FieldName = FieldName::from_static("org.nibkeep.rule-type");
pub(crate) const RULE_HAS: FieldName = FieldName::from_static("org.nibkeep.rule-has");
pub(crate) const RULE_FOLDER: FieldName = FieldName::from_static("org.nibkeep.rule-folder");
pub(crate) const RULE_DEVICE: FieldName = FieldName::from_static("org.nibkeep.rule-device");
pub(crate) const RULE_MEDIA_TYPE: FieldName = FieldName::from_static("org.nibkeep.rule-media-type");
pub(crate) const RULE_LARGER_THAN: FieldName =
FieldName::from_static("org.nibkeep.rule-larger-than");
pub(crate) const RULE_ASKS_ABOVE: FieldName = FieldName::from_static("org.nibkeep.rule-asks-above");
const OWN_FIELDS: [FieldName; 13] = [
POLICY,
POLICY_COPIES,
POLICY_AWAY,
POLICY_ARCHIVED,
POLICY_KEPT,
RULE_POLICY,
RULE_TYPE,
RULE_HAS,
RULE_FOLDER,
RULE_DEVICE,
RULE_MEDIA_TYPE,
RULE_LARGER_THAN,
RULE_ASKS_ABOVE,
];
pub(crate) fn is_own_field(field: &FieldName) -> bool {
OWN_FIELDS.contains(field) || super::backups::is_own_field(field)
}
pub(crate) fn is_own_type(name: &TypeName) -> bool {
*name == STORAGE_POLICY || *name == STORAGE_RULE || *name == super::backups::BACKUP
}
pub(crate) fn types() -> [TypeDef; 2] {
let integer = || FieldDef::new(ValueKind::Integer);
let text = || FieldDef::new(ValueKind::Text);
[
TypeDef::new(STORAGE_POLICY, 1)
.with_field(fields::NAME, FieldDef::new(ValueKind::Name))
.with_field(POLICY_COPIES, integer())
.with_field(POLICY_AWAY, integer())
.with_field(POLICY_ARCHIVED, integer())
.with_field(POLICY_KEPT, text()),
TypeDef::new(STORAGE_RULE, 1)
.with_field(fields::POSITION, text().last_writer_wins())
.with_field(RULE_POLICY, FieldDef::new(ValueKind::Reference))
.with_field(RULE_TYPE, text())
.with_field(RULE_HAS, text())
.with_field(RULE_FOLDER, text())
.with_field(RULE_DEVICE, FieldDef::new(ValueKind::Reference))
.with_field(RULE_MEDIA_TYPE, text())
.with_field(RULE_LARGER_THAN, integer())
.with_field(RULE_ASKS_ABOVE, integer()),
]
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Kept {
InPlace,
Store,
}
impl Kept {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::InPlace => "in-place",
Self::Store => "store",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Needs {
pub copies: u32,
pub away: u32,
pub archived: u32,
pub kept: Kept,
}
impl Needs {
pub const CRITICAL: Self = Self {
copies: 3,
away: 1,
archived: 0,
kept: Kept::Store,
};
pub const ONE: Self = Self {
copies: 1,
away: 0,
archived: 0,
kept: Kept::Store,
};
pub const FALLBACK: Self = Self {
copies: 2,
away: 0,
archived: 1,
kept: Kept::Store,
};
#[must_use]
pub fn lacks(&self, disks: usize, away: usize, archived: usize) -> Lacks {
let needs = |wanted: u32| usize::try_from(wanted).unwrap_or(usize::MAX);
Lacks {
copies: disks < needs(self.copies.max(1)),
away: away < needs(self.away),
archived: archived < needs(self.archived),
}
}
#[must_use]
pub fn lacks_of(&self, copies: &[super::accounts::FileCopy]) -> Lacks {
let counting = || copies.iter().filter(|copy| copy.counts);
self.lacks(
counting().count(),
counting().filter(|copy| copy.disk.away).count(),
counting().filter(|copy| copy.disk.archive).count(),
)
}
#[must_use]
pub fn strictest(self, other: Self) -> Self {
Self {
copies: self.copies.max(other.copies),
away: self.away.max(other.away),
archived: self.archived.max(other.archived),
kept: self.kept.max(other.kept),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Lacks {
pub copies: bool,
pub away: bool,
pub archived: bool,
}
impl Lacks {
#[must_use]
pub fn any(self) -> bool {
self.copies || self.away || self.archived
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Policy {
pub id: EntityId,
pub name: Option<String>,
pub needs: Needs,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Folder {
pub path: String,
pub device: EntityId,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Conditions {
pub of_type: Option<TypeName>,
pub has: Option<FieldName>,
pub folder: Option<Folder>,
pub media_type: Option<String>,
pub larger_than: Option<u64>,
}
impl Conditions {
#[must_use]
pub fn is_empty(&self) -> bool {
*self == Self::default()
}
fn hold(&self, facts: &Facts) -> bool {
self.of_type
.as_ref()
.is_none_or(|name| facts.types.contains(name))
&& self
.has
.as_ref()
.is_none_or(|field| facts.fields.contains(field))
&& self.folder.as_ref().is_none_or(|folder| {
!facts.places.is_empty()
&& facts.places.iter().all(|(device, path)| {
*device == folder.device && Path::new(path).starts_with(&folder.path)
})
})
&& self.media_type.as_ref().is_none_or(|prefix| {
facts
.media_type
.as_ref()
.is_some_and(|media_type| media_type.starts_with(prefix.as_str()))
})
&& self
.larger_than
.is_none_or(|bytes| facts.size.is_some_and(|size| size > bytes))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rule {
pub id: EntityId,
pub policy: Option<EntityId>,
pub conditions: Conditions,
pub asks_above: Option<u64>,
position: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NewRule {
pub policy: EntityId,
pub of_type: Option<TypeName>,
pub has: Option<FieldName>,
pub folder: Option<std::path::PathBuf>,
pub media_type: Option<String>,
pub larger_than: Option<u64>,
pub asks_above: Option<u64>,
}
impl NewRule {
#[must_use]
pub const fn new(policy: EntityId) -> Self {
Self {
policy,
of_type: None,
has: None,
folder: None,
media_type: None,
larger_than: None,
asks_above: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Place {
First,
Last,
Before(EntityId),
After(EntityId),
BeforeTheRest,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChosenBy {
Own,
Rule(EntityId),
Fallback,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Choice {
pub policy: Option<EntityId>,
pub needs: Needs,
pub by: ChosenBy,
pub asks_above: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PolicyCount {
pub policy: Option<EntityId>,
pub name: Option<String>,
pub needs: Needs,
pub files: usize,
pub short: usize,
pub lacking: Vec<EntityId>,
pub few_copies: usize,
pub few_away: usize,
pub few_archived: usize,
pub unchecked: usize,
pub none_here: Vec<EntityId>,
pub not_stored: Vec<EntityId>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PolicyCheck {
pub policies: Vec<PolicyCount>,
pub disks: Vec<super::accounts::Disk>,
pub changes: super::accounts::ChangeCopies,
pub files: Vec<CheckedFile>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CheckedFile {
pub file: EntityId,
pub policy: Option<EntityId>,
pub size: Option<u64>,
pub disks: usize,
pub away: usize,
pub archived: usize,
pub lacks: Lacks,
pub unchecked: bool,
}
#[derive(Clone, Debug, Default)]
pub(crate) struct Facts {
pub(crate) types: BTreeSet<TypeName>,
pub(crate) fields: BTreeSet<FieldName>,
pub(crate) media_type: Option<String>,
pub(crate) size: Option<u64>,
pub(crate) places: Vec<(EntityId, String)>,
}
pub(crate) struct Policies {
policies: BTreeMap<EntityId, Policy>,
rules: Vec<Rule>,
}
impl Policies {
pub(crate) fn read<S: Statements>(
state: &State<S>,
policies: impl IntoIterator<Item = EntityId>,
rules: impl IntoIterator<Item = EntityId>,
) -> Result<Self, NodeError>
where
NodeError: From<S::Error>,
{
let mut read = BTreeMap::new();
for entity in policies {
let entity = state.canonical(entity)?;
if state.is_deleted(entity)? || !state.types(entity)?.contains(&STORAGE_POLICY) {
continue;
}
read.insert(entity, read_policy(state, entity)?);
}
let mut found = Vec::new();
for entity in rules {
let entity = state.canonical(entity)?;
if state.is_deleted(entity)? || !state.types(entity)?.contains(&STORAGE_RULE) {
continue;
}
found.push(read_rule(state, entity, &read)?);
}
found.sort_by(|a, b| {
(a.position.is_none(), &a.position, a.id).cmp(&(
b.position.is_none(),
&b.position,
b.id,
))
});
found.dedup_by_key(|rule| rule.id);
Ok(Self {
policies: read,
rules: found,
})
}
pub(crate) fn choose(&self, own: &[EntityId], facts: &Facts) -> Choice {
if let Some(policy) = self.strictest(own) {
return Choice {
policy: Some(policy.id),
needs: policy.needs,
by: ChosenBy::Own,
asks_above: None,
};
}
for rule in &self.rules {
if let Some(policy) = rule.policy.and_then(|id| self.policies.get(&id))
&& rule.conditions.hold(facts)
{
return Choice {
policy: Some(policy.id),
needs: policy.needs,
by: ChosenBy::Rule(rule.id),
asks_above: rule.asks_above,
};
}
}
Choice {
policy: None,
needs: Needs::FALLBACK,
by: ChosenBy::Fallback,
asks_above: None,
}
}
pub(crate) fn asks_about(&self, size: u64) -> bool {
self.rules
.iter()
.any(|rule| rule.asks_above.is_some_and(|limit| size > limit))
}
pub(crate) fn has_policy(&self, id: EntityId) -> bool {
self.policies.contains_key(&id)
}
pub(crate) fn has_rule(&self, id: EntityId) -> bool {
self.rules.iter().any(|rule| rule.id == id)
}
fn strictest(&self, ids: &[EntityId]) -> Option<&Policy> {
ids.iter()
.filter_map(|id| self.policies.get(id))
.max_by_key(|policy| (policy.needs, std::cmp::Reverse(policy.id)))
}
pub(crate) fn fields_asked(&self) -> BTreeSet<FieldName> {
self.rules
.iter()
.filter_map(|rule| rule.conditions.has.clone())
.collect()
}
}
fn read_policy<S: Statements>(state: &State<S>, entity: EntityId) -> Result<Policy, NodeError>
where
NodeError: From<S::Error>,
{
let most = |field: &FieldName| -> Result<u32, NodeError> {
Ok(state
.current(entity, field)?
.iter()
.filter_map(|statement| match statement.value {
Value::Integer(n) => u32::try_from(n).ok(),
_ => None,
})
.max()
.unwrap_or(0))
};
let kept: Vec<String> = state
.current(entity, &POLICY_KEPT)?
.iter()
.filter_map(|statement| statement.value.as_text().map(str::to_owned))
.collect();
let kept = if kept.is_empty() || kept.iter().any(|kept| kept != Kept::InPlace.as_str()) {
Kept::Store
} else {
Kept::InPlace
};
Ok(Policy {
id: entity,
name: first_name(state, entity)?,
needs: Needs {
copies: most(&POLICY_COPIES)?.max(1),
away: most(&POLICY_AWAY)?,
archived: most(&POLICY_ARCHIVED)?,
kept,
},
})
}
fn read_rule<S: Statements>(
state: &State<S>,
entity: EntityId,
policies: &BTreeMap<EntityId, Policy>,
) -> Result<Rule, NodeError>
where
NodeError: From<S::Error>,
{
let first = |field: &FieldName| -> Result<Option<Value>, NodeError> {
Ok(state
.current(entity, field)?
.iter()
.min_by_key(|statement| statement.id)
.map(|statement| statement.value.clone()))
};
let text = |field: &FieldName| -> Result<Option<String>, NodeError> {
Ok(first(field)?.and_then(|value| value.as_text().map(str::to_owned)))
};
let bytes = |field: &FieldName| -> Result<Option<u64>, NodeError> {
Ok(match first(field)? {
Some(Value::Integer(n)) => u64::try_from(n).ok(),
_ => None,
})
};
let mut named = Vec::new();
for statement in state.current(entity, &RULE_POLICY)? {
if let Some(policy) = statement.value.as_reference() {
named.push(state.canonical(policy)?);
}
}
let policy = named
.iter()
.filter_map(|id| policies.get(id))
.max_by_key(|policy| (policy.needs, std::cmp::Reverse(policy.id)))
.map(|policy| policy.id);
let device = match first(&RULE_DEVICE)? {
Some(Value::Reference(device)) => Some(state.canonical(device)?),
_ => None,
};
let folder = match (text(&RULE_FOLDER)?, device) {
(Some(path), Some(device)) => Some(Folder { path, device }),
_ => None,
};
let conditions = Conditions {
of_type: text(&RULE_TYPE)?.and_then(|name| name.parse().ok()),
has: text(&RULE_HAS)?.and_then(|name| name.parse().ok()),
folder,
media_type: text(&RULE_MEDIA_TYPE)?,
larger_than: bytes(&RULE_LARGER_THAN)?,
};
let readable = [
(RULE_TYPE, conditions.of_type.is_some()),
(RULE_HAS, conditions.has.is_some()),
(RULE_FOLDER, conditions.folder.is_some()),
(RULE_DEVICE, conditions.folder.is_some()),
(RULE_MEDIA_TYPE, conditions.media_type.is_some()),
(RULE_LARGER_THAN, conditions.larger_than.is_some()),
]
.into_iter()
.try_fold(true, |readable, (field, read)| {
Ok::<_, NodeError>(readable && (read || first(&field)?.is_none()))
})?;
Ok(Rule {
id: entity,
policy: policy.filter(|_| readable),
conditions,
asks_above: bytes(&RULE_ASKS_ABOVE)?,
position: last_position(state, entity)?,
})
}
fn last_position<S: Statements>(
state: &State<S>,
entity: EntityId,
) -> Result<Option<String>, NodeError>
where
NodeError: From<S::Error>,
{
let definition = FieldDef::new(ValueKind::Text).last_writer_wins();
Ok(
match state.resolve(entity, &fields::POSITION, Some(&definition))? {
Resolution::Values(values) | Resolution::Competing(values) => values
.first()
.and_then(|statement| statement.value.as_text())
.filter(|key| is_position(key))
.map(str::to_owned),
},
)
}
pub(crate) fn first_name<S: Statements>(
state: &State<S>,
entity: EntityId,
) -> Result<Option<String>, NodeError>
where
NodeError: From<S::Error>,
{
Ok(state
.current(entity, &fields::NAME)?
.iter()
.min_by_key(|statement| statement.id)
.and_then(|statement| statement.value.as_name_text().map(str::to_owned)))
}
pub(crate) fn facts_of<S: Statements>(state: &State<S>, file: EntityId) -> Result<Facts, NodeError>
where
NodeError: From<S::Error>,
{
let mut facts = facts_but_places(state, file)?;
facts.places = origins_of(state, file)?
.into_iter()
.map(|(_, device, path)| (device, path))
.collect();
Ok(facts)
}
fn facts_but_places<S: Statements>(state: &State<S>, file: EntityId) -> Result<Facts, NodeError>
where
NodeError: From<S::Error>,
{
let media_type = state
.current(file, &MEDIA_TYPE)?
.iter()
.min_by_key(|statement| statement.id)
.and_then(|statement| statement.value.as_text().map(str::to_owned));
Ok(Facts {
types: state.types(file)?,
fields: state.fields(file)?,
media_type,
size: size_of(state, file)?,
places: Vec::new(),
})
}
pub(crate) fn size_of<S: Statements>(
state: &State<S>,
file: EntityId,
) -> Result<Option<u64>, NodeError>
where
NodeError: From<S::Error>,
{
Ok(state
.current(file, &SIZE)?
.iter()
.find_map(|statement| match statement.value {
Value::Integer(n) => u64::try_from(n).ok(),
_ => None,
}))
}
pub(crate) fn stands_here<S: Statements>(
state: &State<S>,
record: EntityId,
) -> Result<bool, NodeError>
where
NodeError: From<S::Error>,
{
Ok(!state.is_deleted(record)? && state.current(record, &fields::MOVED_INTO)?.is_empty())
}
pub(crate) fn origins_of<S: Statements>(
state: &State<S>,
file: EntityId,
) -> Result<Vec<(EntityId, EntityId, String)>, NodeError>
where
NodeError: From<S::Error>,
{
let mut found = Vec::new();
let mut seen = BTreeSet::new();
for statement in state.referrers_in(file, &ORIGIN_OF)? {
let origin = state.canonical(statement.entity)?;
if !seen.insert(origin)
|| !stands_here(state, origin)?
|| !state.types(origin)?.contains(&ORIGIN)
{
continue;
}
let devices: Vec<EntityId> = state
.current(origin, &FOUND_ON)?
.iter()
.filter_map(|statement| statement.value.as_reference())
.collect();
for path in state.current(origin, &PATH)? {
if let Some(path) = path.value.as_text() {
for device in &devices {
found.push((origin, state.canonical(*device)?, path.to_owned()));
}
}
}
}
Ok(found)
}
fn derived(space: SpaceId, label: &str) -> EntityId {
let material = [space.as_bytes().as_slice(), label.as_bytes()].concat();
EntityId::derived("nibkeep 2026-10 storage policies", &material)
}
const CRITICAL: &str = "critical";
const STANDARD: &str = "standard";
const REPLACEABLE: &str = "replaceable";
const FROM_A_CAMERA: &str = "from a camera";
const ANY_OTHER: &str = "any other file";
const DOWNLOADS: &str = "downloads";
const ASKS_ABOVE: u64 = 1 << 30;
pub(crate) fn default_policies(space: SpaceId) -> [EntityId; 3] {
[CRITICAL, STANDARD, REPLACEABLE].map(|label| derived(space, label))
}
pub(crate) fn answer_policy(space: SpaceId, again: bool) -> EntityId {
derived(space, if again { REPLACEABLE } else { STANDARD })
}
pub(crate) fn assert(
entity: EntityId,
field: FieldName,
value: Value,
rng: &mut impl CryptoRng,
) -> Operation {
Operation::assert(Statement::new(
StatementId::random(rng),
entity,
field,
value,
))
}
fn make_policy(
entity: EntityId,
name: &str,
needs: Needs,
rng: &mut impl CryptoRng,
) -> Vec<Operation> {
vec![
assert(
entity,
fields::TYPE,
Value::Text(STORAGE_POLICY.to_string()),
rng,
),
assert(entity, fields::NAME, Value::Name(Name::new(name)), rng),
assert(
entity,
POLICY_COPIES,
Value::Integer(i64::from(needs.copies)),
rng,
),
assert(
entity,
POLICY_AWAY,
Value::Integer(i64::from(needs.away)),
rng,
),
assert(
entity,
POLICY_ARCHIVED,
Value::Integer(i64::from(needs.archived)),
rng,
),
assert(
entity,
POLICY_KEPT,
Value::Text(needs.kept.as_str().to_owned()),
rng,
),
]
}
fn make_rule(
entity: EntityId,
rule: &NewRule,
folder: Option<(&str, EntityId)>,
position: String,
rng: &mut impl CryptoRng,
) -> Vec<Operation> {
let mut operations = vec![
assert(
entity,
fields::TYPE,
Value::Text(STORAGE_RULE.to_string()),
rng,
),
assert(entity, fields::POSITION, Value::Text(position), rng),
assert(entity, RULE_POLICY, Value::Reference(rule.policy), rng),
];
if let Some(name) = &rule.of_type {
operations.push(assert(
entity,
RULE_TYPE,
Value::Text(name.to_string()),
rng,
));
}
if let Some(field) = &rule.has {
operations.push(assert(
entity,
RULE_HAS,
Value::Text(field.to_string()),
rng,
));
}
if let Some((path, device)) = folder {
operations.push(assert(
entity,
RULE_FOLDER,
Value::Text(path.to_owned()),
rng,
));
operations.push(assert(entity, RULE_DEVICE, Value::Reference(device), rng));
}
if let Some(media_type) = &rule.media_type {
operations.push(assert(
entity,
RULE_MEDIA_TYPE,
Value::Text(media_type.clone()),
rng,
));
}
for (field, bytes) in [
(RULE_LARGER_THAN, rule.larger_than),
(RULE_ASKS_ABOVE, rule.asks_above),
] {
if let Some(bytes) = bytes {
operations.push(assert(
entity,
field,
Value::Integer(i64::try_from(bytes).unwrap_or(i64::MAX)),
rng,
));
}
}
operations
}
fn resolved_folder(folder: &Path) -> Result<String, NodeError> {
let resolved = resolved_path(folder).map_err(|error| NodeError::Unreadable {
path: folder.display().to_string(),
reason: error.to_string(),
})?;
if !resolved.is_dir() {
return Err(NodeError::Unreadable {
path: folder.display().to_string(),
reason: "not a folder".to_owned(),
});
}
Ok(resolved.to_string_lossy().into_owned())
}
impl Library {
pub fn install_policies(
&mut self,
space: SpaceId,
downloads: Option<&Path>,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<(), NodeError> {
let critical = derived(space, CRITICAL);
let standard = derived(space, STANDARD);
let replaceable = derived(space, REPLACEABLE);
let any_other = derived(space, ANY_OTHER);
let device = self.info.device;
let downloads_rule = derived(space, &format!("{DOWNLOADS} {device}"));
let (installed, has_downloads) = {
let open = self.space(space)?;
let storage = open.stored.log().state().storage();
let policies = open
.stored
.find(&fields::TYPE, &Value::Text(STORAGE_POLICY.to_string()))?;
(
!storage.of_entity(critical)?.is_empty() || !policies.is_empty(),
!storage.of_entity(downloads_rule)?.is_empty(),
)
};
let downloads = match downloads {
Some(folder) if !has_downloads => resolved_folder(folder).ok(),
_ => None,
};
let mut operations = Vec::new();
if !installed {
for (entity, name, needs) in [
(critical, "Critical", Needs::CRITICAL),
(standard, "Standard", Needs::FALLBACK),
(
replaceable,
"Replaceable",
Needs {
copies: 1,
away: 0,
archived: 0,
kept: Kept::InPlace,
},
),
] {
operations.extend(make_policy(entity, name, needs, rng));
}
let first = position_between(None, None).unwrap_or_else(|| "V".to_owned());
let last = position_between(Some(&first), None).unwrap_or_else(|| "k".to_owned());
let camera = NewRule {
has: Some(CAMERA_MAKE),
..NewRule::new(standard)
};
operations.extend(make_rule(
derived(space, FROM_A_CAMERA),
&camera,
None,
first,
rng,
));
let rest = NewRule {
asks_above: Some(ASKS_ABOVE),
..NewRule::new(standard)
};
operations.extend(make_rule(any_other, &rest, None, last, rng));
}
if let Some(folder) = downloads {
let rule = NewRule::new(replaceable);
let position = if installed {
let (position, renumbered) = self.placing(space, Place::BeforeTheRest, None)?;
operations.extend(self.renumbering(space, renumbered, rng)?);
position
} else {
let first = position_between(None, None).unwrap_or_else(|| "V".to_owned());
let last = position_between(Some(&first), None).unwrap_or_else(|| "k".to_owned());
position_between(Some(&first), Some(&last)).unwrap_or(last)
};
operations.extend(make_rule(
downloads_rule,
&rule,
Some((&folder, device)),
position,
rng,
));
}
if operations.is_empty() {
return Ok(());
}
self.commit(space, operations, wall_millis, rng)
}
pub(crate) fn read_policies(&self, space: SpaceId) -> Result<Policies, NodeError> {
let open = self.space(space)?;
let state = open.stored.log().state();
let of_type = |name: &TypeName| {
open.stored
.find(&fields::TYPE, &Value::Text(name.to_string()))
};
Policies::read(state, of_type(&STORAGE_POLICY)?, of_type(&STORAGE_RULE)?)
}
pub fn policies(&self, space: SpaceId) -> Result<Vec<Policy>, NodeError> {
let mut policies: Vec<Policy> = self.read_policies(space)?.policies.into_values().collect();
policies.sort_by_cached_key(|policy| {
(
policy.name.as_ref().map(|name| name.to_lowercase()),
policy.id,
)
});
Ok(policies)
}
pub fn rules(&self, space: SpaceId) -> Result<Vec<Rule>, NodeError> {
Ok(self.read_policies(space)?.rules)
}
pub fn find_policy(&self, space: SpaceId, reference: &str) -> Result<EntityId, NodeError> {
let policies = self.policies(space)?;
let lowered = reference.to_lowercase();
let by_name: Vec<EntityId> = policies
.iter()
.filter(|policy| {
policy
.name
.as_ref()
.is_some_and(|name| name.to_lowercase() == lowered)
})
.map(|policy| policy.id)
.collect();
let found = if by_name.is_empty() {
policies
.iter()
.filter(|policy| {
let id = policy.id.to_string();
id == lowered || (lowered.len() >= 6 && id.starts_with(&lowered))
})
.map(|policy| policy.id)
.collect()
} else {
by_name
};
match found.as_slice() {
[] => Err(NodeError::NoEntity(reference.to_owned())),
[one] => Ok(*one),
_ => Err(NodeError::Ambiguous {
reference: reference.to_owned(),
candidates: found,
}),
}
}
pub fn add_policy(
&mut self,
space: SpaceId,
name: &str,
needs: Needs,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<EntityId, NodeError> {
if name.trim().is_empty() {
return Err(NodeError::EmptyName);
}
self.space(space)?;
let entity = EntityId::random(rng);
let operations = make_policy(
entity,
name.trim(),
Needs {
copies: needs.copies.max(1),
..needs
},
rng,
);
self.commit(space, operations, wall_millis, rng)?;
Ok(entity)
}
pub fn edit_policy(
&mut self,
space: SpaceId,
policy: EntityId,
edit: &PolicyEdit,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<(), NodeError> {
if edit
.name
.as_ref()
.is_some_and(|name| name.trim().is_empty())
{
return Err(NodeError::EmptyName);
}
self.check_policy(space, policy)?;
let mut values = Vec::new();
if let Some(name) = &edit.name {
values.push((fields::NAME, Value::Name(Name::new(name.trim()))));
}
for (field, number) in [
(POLICY_COPIES, edit.copies.map(|copies| copies.max(1))),
(POLICY_AWAY, edit.away),
(POLICY_ARCHIVED, edit.archived),
] {
if let Some(number) = number {
values.push((field, Value::Integer(i64::from(number))));
}
}
if let Some(kept) = edit.kept {
values.push((POLICY_KEPT, Value::Text(kept.as_str().to_owned())));
}
let operations = self.replacing(space, policy, values, rng)?;
if operations.is_empty() {
return Ok(());
}
self.commit(space, operations, wall_millis, rng)
}
pub fn add_rule(
&mut self,
space: SpaceId,
rule: &NewRule,
place: Place,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<EntityId, NodeError> {
self.check_policy(space, rule.policy)?;
let folder = rule.folder.as_deref().map(resolved_folder).transpose()?;
let (position, renumbered) = self.placing(space, place, None)?;
let entity = EntityId::random(rng);
let device = self.info.device;
let mut operations = self.renumbering(space, renumbered, rng)?;
operations.extend(make_rule(
entity,
rule,
folder.as_deref().map(|folder| (folder, device)),
position,
rng,
));
self.commit(space, operations, wall_millis, rng)?;
Ok(entity)
}
pub fn remove_rule(
&mut self,
space: SpaceId,
rule: EntityId,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<(), NodeError> {
self.check_rule(space, rule)?;
let operations = vec![assert(rule, fields::DELETED, Value::Boolean(true), rng)];
self.commit(space, operations, wall_millis, rng)
}
pub fn remove_policy(
&mut self,
space: SpaceId,
policy: EntityId,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<(), NodeError> {
self.check_policy(space, policy)?;
let operations = vec![assert(policy, fields::DELETED, Value::Boolean(true), rng)];
self.commit(space, operations, wall_millis, rng)
}
pub fn move_rule(
&mut self,
space: SpaceId,
rule: EntityId,
place: Place,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<(), NodeError> {
self.check_rule(space, rule)?;
if place == Place::Before(rule) || place == Place::After(rule) {
return Ok(());
}
let (position, mut renumbered) = self.placing(space, place, Some(rule))?;
renumbered.push((rule, position));
let operations = self.renumbering(space, renumbered, rng)?;
self.commit(space, operations, wall_millis, rng)
}
pub fn set_policy(
&mut self,
space: SpaceId,
entity: EntityId,
policy: Option<EntityId>,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<(), NodeError> {
if let Some(policy) = policy {
self.check_policy(space, policy)?;
}
let operations = if let Some(policy) = policy {
self.replacing(space, entity, vec![(POLICY, Value::Reference(policy))], rng)?
} else {
let state = self.space(space)?.stored.log().state();
let current: Vec<StatementId> = state
.current(entity, &POLICY)?
.iter()
.map(|statement| statement.id)
.collect();
if current.is_empty() {
Vec::new()
} else {
vec![Operation::retract(entity, current)]
}
};
if operations.is_empty() {
return Ok(());
}
self.commit(space, operations, wall_millis, rng)
}
pub fn policy_of(&self, space: SpaceId, entity: EntityId) -> Result<Choice, NodeError> {
let policies = self.read_policies(space)?;
let open = self.space(space)?;
let state = open.stored.log().state();
let entity = state.canonical(entity)?;
let own = own_choices(state, entity)?;
Ok(policies.choose(&own, &facts_of(state, entity)?))
}
pub fn check_policies(
&self,
space: SpaceId,
wall_millis: u64,
) -> Result<PolicyCheck, NodeError> {
self.check_policies_in_parts(space, (PART, false), wall_millis)
}
pub(crate) fn policies_without_this_disk(
&self,
space: SpaceId,
wall_millis: u64,
) -> Result<Vec<PolicyCount>, NodeError> {
Ok(self
.check_policies_in_parts(space, (PART, true), wall_millis)?
.policies)
}
pub(crate) fn critical_needs(&self, space: SpaceId) -> Result<Needs, NodeError> {
Ok(self
.read_policies(space)?
.policies
.get(&derived(space, CRITICAL))
.map_or(Needs::CRITICAL, |policy| policy.needs))
}
fn check_policies_in_parts(
&self,
space: SpaceId,
(part, without_own): (usize, bool),
wall_millis: u64,
) -> Result<PolicyCheck, NodeError> {
let policies = self.read_policies(space)?;
let copies = self.copies_by_disk(space, wall_millis)?;
let open = self.space(space)?;
let state = open.stored.log().state();
let of_type = |name: &TypeName| -> Result<Vec<EntityId>, NodeError> {
Ok(open
.stored
.find(&fields::TYPE, &Value::Text(name.to_string()))?)
};
let device = self.info.device;
let mut devices_needed: BTreeSet<EntityId> = policies
.rules
.iter()
.filter_map(|rule| rule.conditions.folder.as_ref().map(|folder| folder.device))
.collect();
devices_needed.insert(device);
let places = places_by_file(state, &of_type(&ORIGIN)?, (&devices_needed, part))?;
let mut asked: Vec<FieldName> = vec![
fields::TYPE,
fields::DELETED,
fields::MERGED_INTO,
POLICY,
CONTENT,
SIZE,
MEDIA_TYPE,
];
for field in policies.fields_asked() {
if !asked.contains(&field) {
asked.push(field);
}
}
let mut seen = BTreeSet::new();
let mut counts: BTreeMap<Option<EntityId>, PolicyCount> = BTreeMap::new();
let mut checked_files = Vec::new();
by_parts(
state,
&of_type(&FILE)?,
(&asked, part),
&mut |files, ids| {
for &file in ids {
let file = files.canonical(file)?;
if !seen.insert(file)
|| files.is_deleted(file)?
|| !files.types(file)?.contains(&FILE)
{
continue;
}
let mut found: Vec<&FoundAt> = Vec::new();
for member in files.merged(file)? {
found.extend(places.get(&member).into_iter().flatten());
}
let mut facts = facts_of_part(files, file)?;
facts.places = found
.iter()
.map(|place| (place.device, place.path.clone()))
.collect();
let choice = policies.choose(&own_choices(files, file)?, &facts);
let content =
files
.current(file, &CONTENT)?
.iter()
.find_map(|statement| match statement.value {
Value::Blob(hash) => Some(hash),
_ => None,
});
let stored = content.is_some_and(|hash| open.stored.holds_ordinary_blob(&hash));
let members: Vec<EntityId> = files.merged(file)?.into_iter().collect();
let in_place = copies.plain_here(&members, content);
let sealed = self.ordinary_sealed(space, content)?;
let (mut disks, old) = copies.holding(&sealed, (&members, content));
if without_own && !disks.remove(&Copies::OWN) {
continue;
}
let (away, archived) = copies.marked(&disks);
checked_files.push(tally(
&mut counts,
&policies,
(&choice, file, facts.size),
(
(stored, in_place),
(disks.len(), away, archived, !old.is_empty()),
),
));
}
Ok(())
},
)?;
let critical = policies
.policies
.get(&derived(space, CRITICAL))
.map_or(Needs::CRITICAL, |policy| policy.needs);
let mut check = checked(counts, checked_files);
if without_own {
check.disks = copies.disks;
return Ok(check);
}
check.changes = self.change_copies(space, &copies, critical)?;
check.disks = copies.disks;
Ok(check)
}
pub(crate) fn origin_places_here(
&self,
space: SpaceId,
) -> Result<Vec<super::checking::PlainPlace>, NodeError> {
let open = self.space(space)?;
let state = open.stored.log().state();
let mut origins = Vec::new();
for origin in open
.stored
.find(&fields::TYPE, &Value::Text(ORIGIN.to_string()))?
{
if stands_here(state, state.canonical(origin)?)? {
origins.push(origin);
}
}
let device = self.info.device;
let mut found = Vec::new();
for (file, places) in places_by_file(state, &origins, (&BTreeSet::from([device]), PART))? {
for place in places.iter().filter(|place| place.device == device) {
let (Some(content), Some(size)) = (place.content, place.size) else {
continue;
};
let untouched = place.holds(Some(content));
found.push(super::checking::PlainPlace {
file,
path: place.path.clone(),
content,
untouched,
size,
seen: super::checking::seen_at(&place.path).filter(|_| untouched),
});
}
}
Ok(found)
}
fn check_policy(&self, space: SpaceId, policy: EntityId) -> Result<(), NodeError> {
if self.read_policies(space)?.policies.contains_key(&policy) {
Ok(())
} else {
Err(NodeError::NoEntity(policy.to_string()))
}
}
fn check_rule(&self, space: SpaceId, rule: EntityId) -> Result<(), NodeError> {
if self
.read_policies(space)?
.rules
.iter()
.any(|known| known.id == rule)
{
Ok(())
} else {
Err(NodeError::NoEntity(rule.to_string()))
}
}
fn placing(
&self,
space: SpaceId,
place: Place,
moving: Option<EntityId>,
) -> Result<(String, Vec<(EntityId, String)>), NodeError> {
let rules: Vec<Rule> = self
.read_policies(space)?
.rules
.into_iter()
.filter(|rule| Some(rule.id) != moving)
.collect();
let index_of = |id: EntityId| {
rules
.iter()
.position(|rule| rule.id == id)
.ok_or_else(|| NodeError::NoEntity(id.to_string()))
};
let at = match place {
Place::First => 0,
Place::Last => rules.len(),
Place::Before(id) => index_of(id)?,
Place::After(id) => index_of(id)? + 1,
Place::BeforeTheRest => match rules.last() {
Some(last) if last.conditions.is_empty() => rules.len() - 1,
_ => rules.len(),
},
};
let neighbour = |index: Option<usize>| match index {
None => Some(None),
Some(index) => rules
.get(index)
.map_or(Some(None), |rule| rule.position.as_deref().map(Some)),
};
if let (Some(before), Some(after)) = (neighbour(at.checked_sub(1)), neighbour(Some(at)))
&& let Some(key) = position_between(before, after)
{
return Ok((key, Vec::new()));
}
let mut keys = Vec::with_capacity(rules.len() + 1);
for _ in 0..=rules.len() {
let key = position_between(keys.last().map(String::as_str), None)
.unwrap_or_else(|| "V".to_owned());
keys.push(key);
}
let key = keys.remove(at);
let renumbered = rules
.iter()
.zip(keys)
.filter(|(rule, key)| rule.position.as_ref() != Some(key))
.map(|(rule, key)| (rule.id, key))
.collect();
Ok((key, renumbered))
}
fn renumbering(
&self,
space: SpaceId,
renumbered: Vec<(EntityId, String)>,
rng: &mut impl CryptoRng,
) -> Result<Vec<Operation>, NodeError> {
let mut operations = Vec::new();
for (rule, key) in renumbered {
operations.extend(self.replacing(
space,
rule,
vec![(fields::POSITION, Value::Text(key))],
rng,
)?);
}
Ok(operations)
}
pub(crate) fn replacing(
&self,
space: SpaceId,
entity: EntityId,
values: Vec<(FieldName, Value)>,
rng: &mut impl CryptoRng,
) -> Result<Vec<Operation>, NodeError> {
let state = self.space(space)?.stored.log().state();
let mut operations = Vec::new();
for (field, value) in values {
let current: Vec<StatementId> = state
.current(entity, &field)?
.iter()
.map(|statement| statement.id)
.collect();
let statement = Statement::new(StatementId::random(rng), entity, field, value);
operations.push(Operation::replace(statement, current));
}
Ok(operations)
}
}
fn checked(
counts: BTreeMap<Option<EntityId>, PolicyCount>,
files: Vec<CheckedFile>,
) -> PolicyCheck {
let mut checked: Vec<PolicyCount> = counts.into_values().collect();
checked.sort_by_cached_key(|count| {
(
count.policy.is_none(),
count.name.as_ref().map(|name| name.to_lowercase()),
count.policy,
)
});
PolicyCheck {
policies: checked,
files,
..PolicyCheck::default()
}
}
fn tally(
counts: &mut BTreeMap<Option<EntityId>, PolicyCount>,
policies: &Policies,
(choice, file, size): (&Choice, EntityId, Option<u64>),
((stored, in_place), (disks, away, archived, unchecked)): (
(bool, bool),
(usize, usize, usize, bool),
),
) -> CheckedFile {
let count = counts.entry(choice.policy).or_insert_with(|| PolicyCount {
policy: choice.policy,
name: choice
.policy
.and_then(|id| policies.policies.get(&id))
.and_then(|policy| policy.name.clone()),
needs: choice.needs,
files: 0,
short: 0,
lacking: Vec::new(),
few_copies: 0,
few_away: 0,
few_archived: 0,
unchecked: 0,
none_here: Vec::new(),
not_stored: Vec::new(),
});
count.files += 1;
let lacks = choice.needs.lacks(disks, away, archived);
count.few_copies += usize::from(lacks.copies);
count.few_away += usize::from(lacks.away);
count.few_archived += usize::from(lacks.archived);
count.unchecked += usize::from(unchecked);
if lacks.any() {
count.short += 1;
count.lacking.push(file);
}
if !stored && !in_place {
count.none_here.push(file);
} else if choice.needs.kept == Kept::Store && !stored {
count.not_stored.push(file);
}
CheckedFile {
file,
policy: choice.policy,
size,
disks,
away,
archived,
lacks,
unchecked,
}
}
#[derive(Clone, Debug)]
struct FoundAt {
device: EntityId,
path: String,
modified: Option<Value>,
content: Option<Hash>,
size: Option<u64>,
}
impl FoundAt {
fn holds(&self, content: Option<Hash>) -> bool {
if self.content.is_none() || self.content != content {
return false;
}
let Ok(metadata) = fs::metadata(&self.path) else {
return false;
};
let modified = metadata.modified().ok().and_then(moment).map(Value::Date);
metadata.is_file()
&& self.size == Some(metadata.len())
&& modified.is_some()
&& modified == self.modified
}
}
fn places_by_file<S: Statements>(
state: &State<S>,
origins: &[EntityId],
(devices_needed, part): (&BTreeSet<EntityId>, usize),
) -> Result<BTreeMap<EntityId, Vec<FoundAt>>, NodeError>
where
NodeError: From<S::Error>,
{
let mut canonical_devices: BTreeMap<EntityId, EntityId> = BTreeMap::new();
let asked = [
fields::TYPE,
fields::DELETED,
fields::MERGED_INTO,
ORIGIN_OF,
FOUND_ON,
PATH,
MODIFIED,
CONTENT,
SIZE,
];
let mut seen = BTreeSet::new();
let mut places: BTreeMap<EntityId, Vec<FoundAt>> = BTreeMap::new();
by_parts(state, origins, (&asked, part), &mut |part, origins| {
for &origin in origins {
let origin = part.canonical(origin)?;
if !seen.insert(origin)
|| part.is_deleted(origin)?
|| !part.types(origin)?.contains(&ORIGIN)
{
continue;
}
let values = |field: &FieldName| -> Result<Vec<Value>, NodeError> {
Ok(part
.current(origin, field)?
.iter()
.map(|statement| statement.value.clone())
.collect())
};
let modified = values(&MODIFIED)?.into_iter().next();
let content = values(&CONTENT)?.into_iter().find_map(|value| match value {
Value::Blob(content) => Some(content),
_ => None,
});
let size = values(&SIZE)?.into_iter().find_map(|value| match value {
Value::Integer(size) => u64::try_from(size).ok(),
_ => None,
});
let mut devices = Vec::new();
for device in values(&FOUND_ON)?.iter().filter_map(Value::as_reference) {
let device = if let Some(canonical) = canonical_devices.get(&device) {
*canonical
} else {
let canonical = canonical_device(state, device)?;
canonical_devices.insert(device, canonical);
canonical
};
devices.push(device);
}
let paths: Vec<String> = values(&PATH)?
.iter()
.filter_map(|path| path.as_text().map(str::to_owned))
.collect();
for file in values(&ORIGIN_OF)?.iter().filter_map(Value::as_reference) {
let found = places.entry(file).or_default();
for device in &devices {
if !devices_needed.contains(device) {
found.push(FoundAt {
device: *device,
path: String::new(),
modified: None,
content: None,
size: None,
});
continue;
}
for path in &paths {
found.push(FoundAt {
device: *device,
path: path.clone(),
modified: modified.clone(),
content,
size,
});
}
}
}
}
Ok(())
})?;
Ok(places)
}
fn canonical_device<S: Statements>(
state: &State<S>,
device: EntityId,
) -> Result<EntityId, NodeError>
where
NodeError: From<S::Error>,
{
Ok(state.canonical(device)?)
}
fn facts_of_part(part: &State, file: EntityId) -> Result<Facts, NodeError> {
facts_but_places(part, file)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PolicyEdit {
pub name: Option<String>,
pub copies: Option<u32>,
pub away: Option<u32>,
pub archived: Option<u32>,
pub kept: Option<Kept>,
}
pub(crate) fn own_choices<S: Statements>(
state: &State<S>,
entity: EntityId,
) -> Result<Vec<EntityId>, NodeError>
where
NodeError: From<S::Error>,
{
let mut own = Vec::new();
for statement in state.current(entity, &POLICY)? {
if let Some(policy) = statement.value.as_reference() {
own.push(state.canonical(policy)?);
}
}
Ok(own)
}
#[cfg(test)]
mod tests {
use nibkeep_model::storage::Memory;
use nibkeep_std::{CAMERA_MODEL, PHOTO};
use nibkeep_testkit::TestRng;
use nibkeep_time::Timestamp;
use super::*;
#[test]
fn the_strictest_of_competing_values_counts() {
let mut rng = TestRng::new("strictest");
let policy = rng.entity_id();
let text = |text: &str| Value::Text(text.to_owned());
let operations = [
assert(
policy,
fields::TYPE,
text(STORAGE_POLICY.as_str()),
&mut rng,
),
assert(policy, POLICY_COPIES, Value::Integer(2), &mut rng),
assert(policy, POLICY_COPIES, Value::Integer(3), &mut rng),
assert(policy, POLICY_ARCHIVED, Value::Integer(1), &mut rng),
assert(policy, POLICY_KEPT, text("in-place"), &mut rng),
assert(policy, POLICY_KEPT, text("store"), &mut rng),
];
let mut state = State::in_storage(Memory::default());
for (at, operation) in (1_000..).zip(&operations) {
let Ok(()) = state.apply(operation, Timestamp::new(at, 0));
}
let policies = Policies::read(&state, [policy], []).expect("reads");
assert_eq!(
policies.policies[&policy].needs,
Needs {
copies: 3,
away: 0,
archived: 1,
kept: Kept::Store,
}
);
}
#[test]
fn every_condition_must_hold() {
let mut rng = TestRng::new("conditions");
let (device, other) = (rng.entity_id(), rng.entity_id());
let facts = Facts {
types: [FILE].into_iter().collect(),
fields: [CAMERA_MAKE].into_iter().collect(),
media_type: Some("video/mp4".to_owned()),
size: Some(100),
places: vec![(device, "/home/ada/Downloads/film.mp4".to_owned())],
};
let folder = |path: &str, device: EntityId| Conditions {
folder: Some(Folder {
path: path.to_owned(),
device,
}),
..Conditions::default()
};
assert!(Conditions::default().hold(&facts), "no conditions");
assert!(folder("/home/ada/Downloads", device).hold(&facts));
assert!(folder("/home/ada", device).hold(&facts), "below the folder");
assert!(
!folder("/home/ada/Down", device).hold(&facts),
"a folder is named whole"
);
assert!(
!folder("/home/ada/Downloads", other).hold(&facts),
"on another device"
);
let mut elsewhere = facts.clone();
elsewhere
.places
.push((device, "/home/ada/Films/film.mp4".to_owned()));
assert!(
!folder("/home/ada/Downloads", device).hold(&elsewhere),
"found elsewhere too"
);
let media = |prefix: &str| Conditions {
media_type: Some(prefix.to_owned()),
..Conditions::default()
};
assert!(media("video/").hold(&facts));
assert!(media("video/mp4").hold(&facts));
assert!(!media("image/").hold(&facts));
let larger = |bytes| Conditions {
larger_than: Some(bytes),
..Conditions::default()
};
assert!(larger(99).hold(&facts));
assert!(!larger(100).hold(&facts));
let of_type = |name| Conditions {
of_type: Some(name),
..Conditions::default()
};
assert!(of_type(FILE).hold(&facts));
assert!(!of_type(PHOTO).hold(&facts));
let has = |field| Conditions {
has: Some(field),
..Conditions::default()
};
assert!(has(CAMERA_MAKE).hold(&facts));
assert!(!has(CAMERA_MODEL).hold(&facts));
let all = Conditions {
of_type: Some(FILE),
has: Some(CAMERA_MAKE),
..media("video/")
};
assert!(all.hold(&facts));
assert!(
!Conditions {
larger_than: Some(100),
..all
}
.hold(&facts)
);
}
#[test]
fn a_rule_with_a_condition_it_cannot_read_chooses_nothing() {
let mut rng = TestRng::new("unreadable");
let (policy, rule) = (rng.entity_id(), rng.entity_id());
let text = |text: &str| Value::Text(text.to_owned());
let operations = [
assert(
policy,
fields::TYPE,
text(STORAGE_POLICY.as_str()),
&mut rng,
),
assert(rule, fields::TYPE, text(STORAGE_RULE.as_str()), &mut rng),
assert(rule, RULE_POLICY, Value::Reference(policy), &mut rng),
assert(rule, RULE_TYPE, text("not a type name"), &mut rng),
];
let mut state = State::in_storage(Memory::default());
for (at, operation) in (1_000..).zip(&operations) {
let Ok(()) = state.apply(operation, Timestamp::new(at, 0));
}
let policies = Policies::read(&state, [policy], [rule]).expect("reads");
assert_eq!(policies.rules[0].policy, None);
let choice = policies.choose(&[], &Facts::default());
assert_eq!(choice.by, ChosenBy::Fallback);
}
fn library(name: &str, rng: &mut TestRng) -> (std::path::PathBuf, Library) {
let directory = nibkeep_testkit::empty_directory(
std::env::temp_dir(),
&format!("nibkeep-policies-{name}-{}", std::process::id()),
);
let protection = nibkeep_keys::NewProtection::Passphrase(
"correct horse",
nibkeep_crypto::PassphraseParams::new(64, 1, 1).expect("valid"),
);
let library = Library::create(
&directory,
&crate::NewLibrary::new("Ada", "laptop", "nib"),
&protection,
NOW,
rng,
)
.expect("creates");
(directory, library)
}
const NOW: u64 = 1_790_000_000_000;
fn set_position(library: &mut Library, rule: EntityId, key: &str, rng: &mut TestRng) {
let space = library.personal_space();
let operations = library
.replacing(
space,
rule,
vec![(fields::POSITION, Value::Text(key.to_owned()))],
rng,
)
.expect("reads");
library
.commit(space, operations, NOW, rng)
.expect("commits");
}
#[test]
fn a_rule_goes_where_it_is_put_when_keys_are_shared_or_bad() {
let mut rng = TestRng::new("placing");
let (directory, mut library) = library("placing", &mut rng);
let space = library.personal_space();
library
.install_policies(space, None, NOW, &mut rng)
.expect("installs");
let rules = library.rules(space).expect("reads");
let (camera, rest) = (rules[0].id, rules[1].id);
let standard = derived(space, STANDARD);
let key = rules[0].position.clone().expect("a key");
set_position(&mut library, rest, &key, &mut rng);
let order = |library: &Library| -> Vec<EntityId> {
library
.rules(space)
.expect("reads")
.iter()
.map(|rule| rule.id)
.collect()
};
let first_two = order(&library);
let new = library
.add_rule(
space,
&NewRule::new(standard),
Place::After(first_two[0]),
NOW,
&mut rng,
)
.expect("adds");
assert_eq!(order(&library), [first_two[0], new, first_two[1]]);
set_position(&mut library, camera, "not a key!", &mut rng);
assert_eq!(order(&library).last(), Some(&camera));
let last = library
.add_rule(space, &NewRule::new(standard), Place::Last, NOW, &mut rng)
.expect("adds");
assert_eq!(order(&library).last(), Some(&last));
assert_eq!(order(&library).len(), 4);
drop(library);
let _ = std::fs::remove_dir_all(directory);
}
#[test]
fn the_position_written_last_counts() {
for (earlier, later) in [("a", "b"), ("b", "a")] {
let mut rng = TestRng::new(&format!("last position {earlier}"));
let (rule, policy) = (rng.entity_id(), rng.entity_id());
let text = |text: &str| Value::Text(text.to_owned());
let operations = [
assert(
policy,
fields::TYPE,
text(STORAGE_POLICY.as_str()),
&mut rng,
),
assert(rule, fields::TYPE, text(STORAGE_RULE.as_str()), &mut rng),
assert(rule, RULE_POLICY, Value::Reference(policy), &mut rng),
assert(rule, fields::POSITION, text(earlier), &mut rng),
assert(rule, fields::POSITION, text(later), &mut rng),
];
let mut state = State::in_storage(Memory::default());
for (at, operation) in (1_000..).zip(&operations) {
let Ok(()) = state.apply(operation, Timestamp::new(at, 0));
}
let policies = Policies::read(&state, [policy], [rule]).expect("reads");
assert_eq!(policies.rules[0].position.as_deref(), Some(later));
}
}
#[test]
fn policies_checked_in_parts_are_checked_as_at_once() {
let mut rng = TestRng::new("checked in parts");
let (directory, mut library) = library("checked-in-parts", &mut rng);
let space = library.personal_space();
let downloads = directory.join("downloads");
let elsewhere = directory.join("elsewhere");
std::fs::create_dir_all(&downloads).expect("makes a folder");
std::fs::create_dir_all(&elsewhere).expect("makes a folder");
library
.install_policies(space, Some(&downloads), NOW, &mut rng)
.expect("installs");
let mut added = Vec::new();
for n in 0..12 {
let folder = if n % 2 == 0 { &downloads } else { &elsewhere };
let path = folder.join(format!("file {n}"));
std::fs::write(&path, format!("the content of file {n}")).expect("writes");
added.push((
path.clone(),
library.add_file(space, &path, NOW, &mut rng).expect("adds"),
));
}
std::fs::write(&added[0].0, b"changed by another app").expect("writes");
library
.merge_entities(space, added[2].1.file, added[3].1.file, NOW, &mut rng)
.expect("merges");
let critical = derived(space, CRITICAL);
library
.set_policy(space, added[4].1.file, Some(critical), NOW, &mut rng)
.expect("sets");
let in_parts = library
.check_policies_in_parts(space, (2, false), NOW)
.expect("checks");
let at_once = library
.check_policies_in_parts(space, (100_000, false), NOW)
.expect("checks");
assert_eq!(in_parts, at_once);
let open = library.space(space).expect("a space");
let state = open.stored.log().state();
let policies = library.read_policies(space).expect("reads");
let mut counts = BTreeMap::new();
let files: BTreeSet<EntityId> = added
.iter()
.map(|(_, added)| state.canonical(added.file).expect("reads"))
.collect();
for file in files {
let choice = library.policy_of(space, file).expect("chooses");
let content = state
.current(file, &CONTENT)
.expect("reads")
.iter()
.find_map(|statement| match statement.value {
Value::Blob(hash) => Some(hash),
_ => None,
});
let stored = content.is_some_and(|content| open.stored.holds_ordinary_blob(&content));
let mut in_place = false;
for (origin, device, path) in origins_of(state, file).expect("reads") {
let first = |field: &FieldName| {
state
.current(origin, field)
.expect("reads")
.first()
.map(|statement| statement.value.clone())
};
let place = FoundAt {
device,
path,
modified: first(&MODIFIED),
content: match first(&CONTENT) {
Some(Value::Blob(content)) => Some(content),
_ => None,
},
size: match first(&SIZE) {
Some(Value::Integer(size)) => u64::try_from(size).ok(),
_ => None,
},
};
in_place |= device == library.info.device && place.holds(content);
}
let disks = (usize::from(stored || in_place), 0, 0, false);
tally(
&mut counts,
&policies,
(&choice, file, None),
((stored, in_place), disks),
);
}
assert_eq!(in_parts.policies, checked(counts, Vec::new()).policies);
let files: usize = at_once.policies.iter().map(|count| count.files).sum();
assert_eq!(files, 11, "twelve files, two of them merged");
assert!(
at_once
.policies
.iter()
.any(|count| count.none_here.contains(&added[0].1.file)),
"the changed one has no copy here"
);
drop(library);
let _ = std::fs::remove_dir_all(directory);
}
}