use super::*;
impl Engine {
pub fn get_entity(&self, id: &EntityId) -> Option<&Entity> {
self.store.get(id)
}
pub fn mem_anchor_holders(&self, mem: &str) -> std::collections::BTreeSet<String> {
let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
return Default::default();
};
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
return Default::default();
};
let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
return Default::default();
};
sc.entities
.iter()
.filter(|(_, rows)| !rows.is_empty())
.map(|(eid, _)| eid.clone())
.collect()
}
pub fn anchors_sidecar_error(&self, mem: &str) -> Option<String> {
let mount = self.mounts.iter().find(|m| m.mount.mem == mem)?;
let bytes = match mount.backend.read_anchors_sidecar() {
Err(e) => return Some(format!("could not read the sidecar: {e}")),
Ok(None) => return None,
Ok(Some(b)) => b,
};
if bytes.iter().all(|b| b.is_ascii_whitespace()) {
return Some(
"the sidecar file is empty — an interrupted write leaves this state, and it is not the same as having no anchors; remove the file if the mem genuinely has none"
.to_string(),
);
}
match crate::anchor::AnchorSidecar::from_bytes(&bytes) {
Ok(_) => None,
Err(e) => Some(e.to_string()),
}
}
pub fn entity_anchors(&self, id: &EntityId) -> Vec<crate::anchor::Anchor> {
let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == id.mem()) else {
return Vec::new();
};
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
return Vec::new();
};
match crate::anchor::AnchorSidecar::from_bytes(&bytes) {
Ok(sc) => sc.get(id.as_ref()).to_vec(),
Err(_) => Vec::new(),
}
}
pub fn entity_anchors_resolved(&self, id: &EntityId) -> Vec<ResolvedAnchor> {
let anchors = self.entity_anchors(id);
let source_roots = self.anchor_source_roots(id.mem());
let none = SuppliedObservations::new();
anchors
.into_iter()
.map(|anchor| self.resolve_one(anchor, &source_roots, &none))
.collect()
}
fn resolve_one(
&self,
anchor: crate::anchor::Anchor,
source_roots: &std::collections::BTreeMap<String, AnchorSourceJoin>,
supplied: &SuppliedObservations,
) -> ResolvedAnchor {
let observed = self.observe_anchor(&anchor, source_roots, supplied);
let (state, observed_hash, observed_at) = match observed {
Some(o) => (Some(o.state), o.hash, o.at),
None => (None, None, None),
};
ResolvedAnchor {
anchor,
state,
observed_hash,
observed_at,
}
}
fn observe_anchor(
&self,
anchor: &crate::anchor::Anchor,
source_roots: &std::collections::BTreeMap<String, AnchorSourceJoin>,
supplied: &SuppliedObservations,
) -> Option<Observed> {
if anchor.grain == crate::anchor::AnchorGrain::Url {
if let Some(obs) = supplied
.get(&anchor.artifact)
.filter(|obs| observation_adjudicates(obs, anchor))
{
return Some(match &obs.outcome {
crate::anchor::SuppliedOutcome::Absent => Observed {
state: crate::anchor::AnchorState::Recheck,
hash: None,
at: Some(obs.at.clone()),
},
crate::anchor::SuppliedOutcome::Present {
hash,
content: Some(text),
} if anchor.span.is_some() => Observed {
state: crate::anchor::resolve_span_anchor(anchor, text),
hash: Some(hash.clone()),
at: Some(obs.at.clone()),
},
crate::anchor::SuppliedOutcome::Present { hash, content } => {
let preparation = anchor
.source
.as_deref()
.and_then(|name| source_roots.get(name))
.and_then(|j| j.preparation.as_deref());
let current = match (preparation, content) {
(Some(_), Some(text)) => crate::preparation::path_prepared_hash(
preparation,
&anchor.artifact,
anchor.grain,
text.as_bytes(),
),
_ => crate::preparation::PathPrepared::NoHash,
};
match current {
crate::preparation::PathPrepared::UnitAbsent => Observed {
state: crate::anchor::resolve_anchor(
anchor,
&crate::anchor::ArtifactObservation::Absent,
),
hash: None,
at: Some(obs.at.clone()),
},
crate::preparation::PathPrepared::Hash(h) => Observed {
state: crate::anchor::resolve_anchor(
anchor,
&crate::anchor::ArtifactObservation::Present {
current_hash: Some(h.clone()),
},
),
hash: Some(h),
at: Some(obs.at.clone()),
},
crate::preparation::PathPrepared::NoHash => Observed {
state: crate::anchor::resolve_anchor(
anchor,
&crate::anchor::ArtifactObservation::Present {
current_hash: Some(hash.clone()),
},
),
hash: Some(hash.clone()),
at: Some(obs.at.clone()),
},
}
}
});
}
return anchor.last_observed.as_ref().map(|rec| Observed {
state: rec.state,
hash: rec.hash.clone(),
at: Some(rec.at.clone()),
});
}
let join = anchor
.source
.as_deref()
.and_then(|name| source_roots.get(name));
if anchor.grain == crate::anchor::AnchorGrain::Entity {
return self
.observe_entity_anchor(anchor, join.and_then(|j| j.preparation.as_deref()))
.map(Observed::live);
}
let root = self.workspace_root.as_deref()?;
observe_path_anchor(root, anchor, join).map(Observed::live)
}
pub(crate) fn entity_anchor_target_hash(
&self,
artifact: &str,
preparation: Option<&str>,
) -> Option<String> {
let (id_part, locator) = crate::preparation::split_unit_id(artifact);
let id = EntityId::canonical(id_part);
if !self.mounts.iter().any(|m| m.mount.mem == id.mem()) {
return None;
}
let entity = self.store.get(&id).filter(|e| !e.stub)?;
let type_def = self
.schema_for(id.mem())
.and_then(|schema| schema.get_type(&entity.entity_type));
match crate::preparation::entity_prepared(entity, type_def.as_deref(), preparation, locator)
{
crate::preparation::PathPrepared::Hash(h) => Some(h),
crate::preparation::PathPrepared::UnitAbsent
| crate::preparation::PathPrepared::NoHash => None,
}
}
fn observe_entity_anchor(
&self,
anchor: &crate::anchor::Anchor,
preparation: Option<&str>,
) -> Option<(crate::anchor::AnchorState, Option<String>)> {
let (id_part, locator) = crate::preparation::split_unit_id(&anchor.artifact);
let id = EntityId::canonical(id_part);
if !self.mounts.iter().any(|m| m.mount.mem == id.mem()) {
return None;
}
let entity = self.store.get(&id).filter(|e| !e.stub);
let Some(entity) = entity else {
return Some((
crate::anchor::resolve_anchor(anchor, &crate::anchor::ArtifactObservation::Absent),
None,
));
};
let current_hash = if anchor.class.is_hash_bearing() {
let type_def = self
.schema_for(id.mem())
.and_then(|schema| schema.get_type(&entity.entity_type));
match crate::preparation::entity_prepared(
entity,
type_def.as_deref(),
preparation,
locator,
) {
crate::preparation::PathPrepared::Hash(h) => Some(h),
crate::preparation::PathPrepared::UnitAbsent => {
return Some((
crate::anchor::resolve_anchor(
anchor,
&crate::anchor::ArtifactObservation::Absent,
),
None,
));
}
crate::preparation::PathPrepared::NoHash => return None,
}
} else {
None
};
let observation = crate::anchor::ArtifactObservation::Present {
current_hash: current_hash.clone(),
};
Some((
crate::anchor::resolve_anchor(anchor, &observation),
current_hash,
))
}
pub(crate) fn anchor_source_roots(
&self,
mem: &str,
) -> std::collections::BTreeMap<String, AnchorSourceJoin> {
let mut roots = std::collections::BTreeMap::new();
let Some(root) = self.workspace_root.as_deref() else {
return roots;
};
let Ok(configs) = crate::pipeline_store::load_pipeline_configs(root) else {
return roots;
};
for record in configs.bindings.iter().filter(|r| r.mem == mem) {
for source in &record.config.sources {
roots
.entry(source.name.clone())
.or_insert_with(|| AnchorSourceJoin {
pointer: source.pointer.clone(),
preparation: source.preparation.clone(),
source: source.clone(),
deny_paths: record.config.deny_paths.clone(),
});
}
}
roots
}
pub fn anchors_referencing_artifact(
&self,
artifact_path: &str,
) -> Vec<(EntityId, crate::anchor::Anchor)> {
let mut out = Vec::new();
for mount in &self.mounts {
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
continue;
};
let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
continue;
};
let source_roots = self.anchor_source_roots(&mount.mount.mem);
for (eid, anchors) in &sc.entities {
for a in anchors {
let joined = a
.source
.as_deref()
.and_then(|name| source_roots.get(name))
.map(|join| {
artifact_candidates(&join.pointer, anchor_base_path(&a.artifact))
})
.and_then(|mut c| (c.len() > 1).then(|| c.remove(0)));
if anchor_references_path(a, artifact_path)
|| joined.is_some_and(|j| {
path_references(
&j,
a.grain == crate::anchor::AnchorGrain::Tree,
artifact_path,
)
})
{
out.push((EntityId(eid.clone()), a.clone()));
}
}
}
}
out
}
pub fn mem_has_anchors(&self, mem: &str) -> bool {
let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
return false;
};
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
return false;
};
let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
return false;
};
sc.entities.values().any(|anchors| !anchors.is_empty())
}
pub fn mem_anchors_resolved(&self, mem: &str) -> Vec<(EntityId, ResolvedAnchor)> {
self.mem_anchors_resolved_with(mem, &SuppliedObservations::new())
}
pub fn mem_anchors_resolved_with(
&self,
mem: &str,
supplied: &SuppliedObservations,
) -> Vec<(EntityId, ResolvedAnchor)> {
let Some(mount) = self.mounts.iter().find(|m| m.mount.mem == mem) else {
return Vec::new();
};
let Ok(Some(bytes)) = mount.backend.read_anchors_sidecar() else {
return Vec::new();
};
let Ok(sc) = crate::anchor::AnchorSidecar::from_bytes(&bytes) else {
return Vec::new();
};
let mut out = Vec::new();
let source_roots = self.anchor_source_roots(mem);
for (eid, anchors) in &sc.entities {
for anchor in anchors {
out.push((
EntityId(eid.clone()),
self.resolve_one(anchor.clone(), &source_roots, supplied),
));
}
}
out
}
pub fn verify_mem_anchors(&self, mem: &str) -> Result<MemAnchorVerification, EngineError> {
self.verify_mem_anchors_with(mem, &SuppliedObservations::new())
}
pub(super) fn apply_anchor_clock(
&self,
summary: &mut crate::ops::HealthSummary,
mem: Option<&str>,
) {
use std::collections::HashMap;
fn rank(state: &str) -> Option<u8> {
match state {
"drifted" | "span_absent" => Some(3),
"recheck" => Some(2),
"resolves" => Some(1),
_ => None,
}
}
let mut by_entity: HashMap<String, (u8, String)> = HashMap::new();
let mut mems: Vec<String> = self.mem_names().iter().map(|s| s.to_string()).collect();
mems.retain(|m| mem.is_none_or(|scope| scope == m));
for m in mems {
let Ok(report) = self.verify_mem_anchors(&m) else {
continue;
};
for row in &report.anchors {
let Some(r) = rank(&row.state) else { continue };
let entry = by_entity
.entry(row.entity_id.clone())
.or_insert((0, String::new()));
if r > entry.0 {
*entry = (r, row.state.clone());
}
}
}
if by_entity.is_empty() {
return;
}
let today = crate::ops::health::days_since_epoch();
let mut stale = std::mem::take(&mut summary.stale_entities);
let mut fresh = Vec::new();
stale.retain(|row| match by_entity.get(row.id.0.as_str()) {
None => true,
Some((_, state)) => {
if state == "resolves" {
fresh.push(crate::ops::StaleEntity {
id: row.id.clone(),
title: row.title.clone(),
days_since_modified: row.days_since_modified,
anchor_state: Some(state.clone()),
});
}
false
}
});
let mut by_anchor: Vec<crate::ops::StaleEntity> = by_entity
.iter()
.filter(|(_, (_, state))| state != "resolves")
.filter_map(|(id, (_, state))| {
let entity = self.store.get(&crate::EntityId(id.clone()))?;
if entity.stub || mem.is_some_and(|scope| entity.mem != scope) {
return None;
}
let days = entity
.metadata
.get("last_modified")
.and_then(|v| crate::ops::health::parse_iso_to_days(&v.to_frontmatter_string()))
.map(|d| today.saturating_sub(d))
.unwrap_or(0);
Some(crate::ops::StaleEntity {
id: entity.id.clone(),
title: entity.title.clone(),
days_since_modified: days,
anchor_state: Some(state.clone()),
})
})
.collect();
stale.append(&mut by_anchor);
stale.sort_by(|a, b| a.id.0.cmp(&b.id.0));
fresh.sort_by(|a, b| a.id.0.cmp(&b.id.0));
summary.stale_entities = stale;
summary.anchor_fresh = fresh;
}
pub fn verify_mem_anchors_with(
&self,
mem: &str,
supplied: &SuppliedObservations,
) -> Result<MemAnchorVerification, EngineError> {
if !self.mem_router.is_visible(mem) {
return Err(self.unknown_mem_error(mem));
}
let now = self.now_iso();
if let Some(why) = self.anchors_sidecar_error(mem) {
let mut report = MemAnchorVerification {
mem: mem.to_string(),
sidecar_error: Some(why),
..Default::default()
};
report.figure = report.figure_over(0);
return Ok(report);
}
let mut report = MemAnchorVerification {
mem: mem.to_string(),
unreconciled: self
.entity_set_is_reconcilable(mem)
.err()
.map(str::to_string),
..Default::default()
};
let reconciled = report.unreconciled.is_none();
let mut resolves = 0usize;
let mut matched: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
for (eid, resolved) in self.mem_anchors_resolved_with(mem, supplied) {
let is_url = resolved.anchor.grain == crate::anchor::AnchorGrain::Url;
let supplied_here = is_url
&& supplied
.get(&resolved.anchor.artifact)
.is_some_and(|obs| observation_adjudicates(obs, &resolved.anchor));
if supplied_here {
matched.insert(resolved.anchor.artifact.clone());
}
let observed_at = resolved.observed_at.clone();
let unobserved_for_days = observed_at
.as_deref()
.and_then(|at| crate::anchor::days_between(at, &now));
if let (true, Some(state), Some(at)) = (supplied_here, resolved.state, &observed_at) {
report.recordable_observations.push(RecordedObservation {
entity: eid.to_string(),
artifact: resolved.anchor.artifact.clone(),
span: resolved.anchor.span.clone(),
observation: crate::anchor::AnchorObservation {
at: at.clone(),
hash: resolved.observed_hash.clone(),
state,
},
});
}
if reconciled && self.entity_is_absent(&eid) {
report.dangling += 1;
report.anchors.push(VerifiedAnchor {
entity_id: eid.to_string(),
artifact: resolved.anchor.artifact.clone(),
grain: resolved.anchor.grain.as_wire().to_string(),
class: resolved.anchor.class.as_wire().to_string(),
span: resolved.anchor.span.clone(),
state: "dangling".to_string(),
observed_hash: resolved.observed_hash,
observed_at,
unobserved_for_days,
observation_supplied: supplied_here,
});
continue;
}
let state = match resolved.state {
Some(crate::anchor::AnchorState::Resolves) => {
resolves += 1;
crate::anchor::AnchorState::Resolves.as_wire()
}
Some(crate::anchor::AnchorState::Drifted) => {
report.drifted += 1;
crate::anchor::AnchorState::Drifted.as_wire()
}
Some(crate::anchor::AnchorState::Recheck) => {
report.recheck += 1;
crate::anchor::AnchorState::Recheck.as_wire()
}
Some(crate::anchor::AnchorState::Orphaned) => {
report.unresolvable += 1;
crate::anchor::AnchorState::Orphaned.as_wire()
}
Some(crate::anchor::AnchorState::SpanAbsent) => {
report.span_absent += 1;
crate::anchor::AnchorState::SpanAbsent.as_wire()
}
None => {
report.unobserved += 1;
"unobserved"
}
};
report.anchors.push(VerifiedAnchor {
entity_id: eid.to_string(),
artifact: resolved.anchor.artifact.clone(),
grain: resolved.anchor.grain.as_wire().to_string(),
class: resolved.anchor.class.as_wire().to_string(),
span: resolved.anchor.span.clone(),
state: state.to_string(),
observed_hash: resolved.observed_hash,
observed_at,
unobserved_for_days,
observation_supplied: supplied_here,
});
}
report.unmatched_observations = supplied
.keys()
.filter(|artifact| !matched.contains(*artifact))
.cloned()
.collect();
report.figure = report.figure_over(resolves);
Ok(report)
}
}
pub fn anchor_base_path(artifact: &str) -> &str {
let cut = artifact.find(['@', '#']).unwrap_or(artifact.len());
&artifact[..cut]
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct MemAnchorVerification {
pub mem: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub sidecar_error: Option<String>,
#[serde(flatten)]
pub figure: crate::anchor::AnchorResolutionFigure,
pub drifted: usize,
pub recheck: usize,
pub unresolvable: usize,
pub span_absent: usize,
pub unobserved: usize,
pub dangling: usize,
pub unreconciled: Option<String>,
pub anchors: Vec<VerifiedAnchor>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub unmatched_observations: Vec<String>,
#[serde(skip)]
pub recordable_observations: Vec<RecordedObservation>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecordedObservation {
pub entity: String,
pub artifact: String,
pub span: Option<String>,
pub observation: crate::anchor::AnchorObservation,
}
pub type SuppliedObservations =
std::collections::BTreeMap<String, crate::anchor::SuppliedObservation>;
fn observation_adjudicates(
obs: &crate::anchor::SuppliedObservation,
anchor: &crate::anchor::Anchor,
) -> bool {
anchor.span.is_none()
|| !matches!(
obs.outcome,
crate::anchor::SuppliedOutcome::Present { content: None, .. }
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Observed {
state: crate::anchor::AnchorState,
hash: Option<String>,
at: Option<String>,
}
impl Observed {
fn live((state, hash): (crate::anchor::AnchorState, Option<String>)) -> Self {
Observed {
state,
hash,
at: None,
}
}
}
impl MemAnchorVerification {
fn figure_over(&self, resolves: usize) -> crate::anchor::AnchorResolutionFigure {
if let Some(why) = &self.sidecar_error {
return crate::anchor::AnchorResolutionFigure::uncounted(format!(
"population unknown: the anchors sidecar could not be read ({why}); no row was \
counted, and zero counts here are not a clean mem"
));
}
let adjudicated = resolves + self.drifted + self.unresolvable + self.span_absent;
let unadjudicated = self.recheck + self.unobserved;
let mut s = format!(
"over {} counted row(s): {adjudicated} adjudicated, {unadjudicated} not (recheck {}, unobserved {})",
adjudicated + unadjudicated,
self.recheck,
self.unobserved
);
if self.dangling > 0 {
s.push_str(&format!(
"; {} row(s) excluded, naming an entity the mem no longer holds",
self.dangling
));
}
if let Some(why) = &self.unreconciled {
s.push_str(&format!(
"; the entity end was NOT reconciled ({why}), so dangling rows would not have been detected"
));
}
let fully_adjudicated =
self.recheck == 0 && self.unobserved == 0 && self.unreconciled.is_none();
crate::anchor::AnchorResolutionFigure::new(resolves, s, fully_adjudicated)
.expect("the population statement is never empty")
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct VerifiedAnchor {
pub entity_id: String,
pub artifact: String,
pub grain: String,
pub class: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<String>,
pub state: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub observed_hash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub observed_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub unobserved_for_days: Option<u64>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub observation_supplied: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct ResolvedAnchor {
#[serde(flatten)]
pub anchor: crate::anchor::Anchor,
#[serde(skip_serializing_if = "Option::is_none")]
pub state: Option<crate::anchor::AnchorState>,
#[serde(skip)]
pub observed_hash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub observed_at: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct AnchorSourceJoin {
pub(crate) pointer: String,
pub(crate) preparation: Option<String>,
pub(crate) source: crate::pipeline::Source,
pub(crate) deny_paths: Vec<String>,
}
fn observe_path_anchor(
root: &Path,
anchor: &crate::anchor::Anchor,
join: Option<&AnchorSourceJoin>,
) -> Option<(crate::anchor::AnchorState, Option<String>)> {
use crate::anchor::AnchorGrain;
match anchor.grain {
AnchorGrain::Span | AnchorGrain::File | AnchorGrain::Tree => {}
AnchorGrain::Url | AnchorGrain::Entity => return None,
}
let source_pointer = join.map(|j| j.pointer.as_str());
let preparation = join.and_then(|j| j.preparation.as_deref());
let base = anchor_base_path(&anchor.artifact);
let path = {
let candidates = artifact_candidates(source_pointer.unwrap_or(""), base);
candidates
.iter()
.map(|c| root.join(c))
.find(|p| p.exists())
.unwrap_or_else(|| root.join(base))
};
if !path.exists() {
return Some((
crate::anchor::resolve_anchor(anchor, &crate::anchor::ArtifactObservation::Absent),
None,
));
}
if anchor.span.is_some() && matches!(anchor.grain, AnchorGrain::File | AnchorGrain::Span) {
let Some(bytes) = (path.is_file())
.then(|| std::fs::read(&path).ok())
.flatten()
else {
return Some((crate::anchor::AnchorState::Recheck, None));
};
let text = String::from_utf8_lossy(&bytes);
let state = crate::anchor::resolve_span_anchor(anchor, &text);
let hash = match crate::preparation::path_prepared_hash(
preparation,
&anchor.artifact,
anchor.grain,
&bytes,
) {
crate::preparation::PathPrepared::Hash(h) => Some(h),
_ => None,
};
return Some((state, hash));
}
let current_hash = if !anchor.class.is_hash_bearing() {
None
} else if matches!(anchor.grain, AnchorGrain::File | AnchorGrain::Span) && path.is_file() {
match std::fs::read(&path).ok().map(|bytes| {
crate::preparation::path_prepared_hash(
preparation,
&anchor.artifact,
anchor.grain,
&bytes,
)
}) {
Some(crate::preparation::PathPrepared::Hash(h)) => Some(h),
Some(crate::preparation::PathPrepared::UnitAbsent) => {
return Some((
crate::anchor::resolve_anchor(
anchor,
&crate::anchor::ArtifactObservation::Absent,
),
None,
));
}
Some(crate::preparation::PathPrepared::NoHash) | None => None,
}
} else if anchor.grain == AnchorGrain::Tree
&& path.is_dir()
&& let Some(join) = join
{
let enumeration = crate::source_scope::enumerate_facet_files_reported(
&join.source,
&join.deny_paths,
root,
);
if enumeration.is_partial() {
None
} else if preparation == Some(crate::preparation::CODE_MAP) {
let files: Vec<(String, String)> = enumeration
.files
.into_iter()
.filter(|f| root.join(f).starts_with(&path))
.filter_map(|f| {
std::fs::read(root.join(&f))
.ok()
.map(|bytes| (f, String::from_utf8_lossy(&bytes).into_owned()))
})
.collect();
Some(crate::anchor::prepared_content_hash(
crate::preparation::code_map_tree_digest(&files).as_bytes(),
))
} else {
let files: Vec<(String, Vec<u8>)> = enumeration
.files
.into_iter()
.filter(|f| root.join(f).starts_with(&path))
.filter_map(|f| std::fs::read(root.join(&f)).ok().map(|bytes| (f, bytes)))
.collect();
Some(crate::anchor::prepared_content_hash(
crate::preparation::plain_tree_digest(&files).as_bytes(),
))
}
} else {
None
};
let observation = crate::anchor::ArtifactObservation::Present {
current_hash: current_hash.clone(),
};
Some((
crate::anchor::resolve_anchor(anchor, &observation),
current_hash,
))
}
pub(super) fn schema_parsed_fingerprint(schema: &memstead_schema::Schema) -> String {
let mut keys: Vec<&String> = schema.types.keys().collect();
keys.sort();
let types: Vec<String> = keys
.iter()
.map(|k| format!("{k}={:?}", schema.types[k.as_str()]))
.collect();
format!(
"{:?}|{}|{}",
schema.manifest,
schema.version,
types.join(";")
)
}
fn anchor_references_path(anchor: &crate::anchor::Anchor, path: &str) -> bool {
let base = anchor_base_path(&anchor.artifact);
path_references(base, anchor.grain == crate::anchor::AnchorGrain::Tree, path)
}
fn path_references(base: &str, is_tree: bool, path: &str) -> bool {
if base == path {
return true;
}
if is_tree {
let prefix = base.strip_suffix('/').unwrap_or(base);
return path.starts_with(&format!("{prefix}/"));
}
false
}
pub fn join_pointer(pointer: &str, base: &str) -> String {
let pointer = pointer.trim_end_matches('/');
if pointer.is_empty() || pointer == "." {
base.to_string()
} else {
format!("{pointer}/{base}")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CrossSourceArtifact {
Unresolved,
Unique(String),
Ambiguous(Vec<String>),
}
pub fn resolve_across_sources<'a, I, F>(
bases: I,
requested: &str,
canonical_for: F,
) -> CrossSourceArtifact
where
I: IntoIterator<Item = &'a std::path::PathBuf>,
F: Fn(&std::path::PathBuf, &str) -> Option<String>,
{
let mut hits: Vec<String> = bases
.into_iter()
.filter_map(|base| canonical_for(base, requested))
.collect();
hits.sort();
hits.dedup();
match hits.len() {
0 => CrossSourceArtifact::Unresolved,
1 => CrossSourceArtifact::Unique(hits.remove(0)),
_ => CrossSourceArtifact::Ambiguous(hits),
}
}
pub fn artifact_candidates(pointer: &str, base: &str) -> Vec<String> {
let pointer = pointer.trim_end_matches('/');
if pointer.is_empty() || pointer == "." {
return vec![base.to_string()];
}
if base.starts_with("../") || base == ".." {
return vec![base.to_string()];
}
vec![format!("{pointer}/{base}"), base.to_string()]
}