use std::path::PathBuf;
use std::sync::Arc;
use memstead_schema::Schema;
use crate::backend::MemBackend;
use crate::storage::ArchiveBackend;
use crate::validator::ValidatorLimits;
use crate::validator::archive::{ArchiveEntries, SchemaFile, extract_entries};
use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
use super::{Engine, EngineError};
#[allow(clippy::large_enum_variant)]
#[derive(Debug, thiserror::Error)]
pub enum FromArchiveBytesError {
#[error("archive validation: {0}")]
Validation(#[from] crate::validator::ValidationError),
#[error("invalid published config: {0}")]
InvalidConfig(String),
#[error(
"unsupported archive format {declared} — this engine accepts formats {accepted:?}; \
re-export the mem with a current engine or upgrade this one"
)]
UnsupportedFormat {
declared: u32,
accepted: &'static [u32],
},
#[error("embedded schema failed to load: {0}")]
EmbeddedSchemaInvalid(String),
#[error(transparent)]
Engine(#[from] EngineError),
}
impl Engine {
pub fn from_archive_bytes(bytes: Vec<u8>) -> Result<Self, FromArchiveBytesError> {
Self::from_archive_bytes_with_limits(bytes, &ValidatorLimits::DEFAULT)
}
pub fn from_archive_bytes_with_limits(
bytes: Vec<u8>,
limits: &ValidatorLimits,
) -> Result<Self, FromArchiveBytesError> {
let entries = extract_entries(&bytes, limits)?;
let ArchiveEntries {
config_bytes,
schema_files,
..
} = &entries;
let published: memstead_schema::PublishedMemConfig =
serde_json::from_slice(config_bytes)
.map_err(|e| FromArchiveBytesError::InvalidConfig(e.to_string()))?;
if !memstead_schema::published_format_accepted(published.format) {
return Err(FromArchiveBytesError::UnsupportedFormat {
declared: published.format,
accepted: memstead_schema::PUBLISHED_MEM_FORMATS_ACCEPTED,
});
}
let extra_schemas = load_embedded_schemas(schema_files)?;
let mount = Mount {
mem: published.name.clone(),
schema: Some(published.schema.clone()),
storage: MountStorage::Archive {
path: PathBuf::new(),
},
capability: MountCapability::ReadOnly,
lifecycle: MountLifecycle::Eager,
cross_linkable: false,
migration_target: None,
};
let backend: Box<dyn MemBackend> = Box::new(ArchiveBackend::from_bytes(bytes));
let engine = Self::from_mounts_inner(vec![(mount, backend)], extra_schemas, Vec::new())?;
Ok(engine)
}
pub fn export_mem_to_bytes(&self, mem_name: &str) -> Result<Vec<u8>, EngineError> {
self.export_mem_bytes_report(mem_name).map(|out| out.bytes)
}
pub fn export_mem_bytes_report(
&self,
mem_name: &str,
) -> Result<crate::ops::export::MemExportBytes, EngineError> {
let mount = self
.mounts
.iter()
.find(|m| m.mount.mem == mem_name)
.ok_or_else(|| self.unknown_mem_error(mem_name))?;
let config = self.mem_config_for(mem_name).ok_or_else(|| {
EngineError::InvalidInput(format!(
"mem '{mem_name}' has no loaded MemConfig — cannot export"
))
})?;
if config.version.is_none() {
return Err(EngineError::MemConfigIncomplete {
mem: mem_name.to_string(),
missing_fields: vec!["version".to_string()],
});
}
let workspace_root = self.workspace_root.as_deref();
let fixed_schemas_dir = workspace_root.map(|r| r.join(".memstead").join("schemas"));
let workspace_schemas_dir = fixed_schemas_dir.as_deref();
match &mount.mount.storage {
MountStorage::Folder { path } => crate::ops::export::export_mem_to_bytes(
path,
config,
workspace_root,
workspace_schemas_dir,
mem_name,
self.ref_schema_source_for(config),
Some(&self.sealed_row_reader(mem_name)),
)
.map_err(|e| {
EngineError::Backend(crate::backend::BackendError::Other(format!(
"export_mem_to_bytes: {e}"
)))
}),
MountStorage::Archive { .. } => {
Err(EngineError::Backend(crate::backend::BackendError::Sealed))
}
MountStorage::GitBranch { gitdir, branch } => {
let hook = self.git_branch_ops.as_ref().ok_or_else(|| {
EngineError::Backend(crate::backend::BackendError::Other(
"git-branch export hook not installed (git-branch ops not wired)"
.to_string(),
))
})?;
let entity_paths = crate::ops::export::entity_paths_of(
&mount
.backend
.list_entities()
.map_err(EngineError::Backend)?,
);
let records = mount.backend.read_provenance(None).unwrap_or_default();
let (provenance, redactions) =
crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
let provenance_bytes = provenance.to_archive_bytes().ok();
let anchors_bytes = mount.backend.read_anchors_sidecar().ok().flatten();
let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
workspace_root,
mem_name,
&entity_paths,
Some(&self.sealed_row_reader(mem_name)),
);
(hook.export_to_bytes)(
gitdir,
branch,
mem_name,
config,
workspace_root,
workspace_schemas_dir,
provenance_bytes.as_deref(),
anchors_bytes.as_deref(),
checks_bytes.as_deref(),
)
.map(|mut out| {
out.redactions =
crate::ops::export::merge_redactions(redactions, check_redactions);
out
})
.map_err(EngineError::Backend)
}
MountStorage::InMemory => {
let backend = mount.backend.as_ref();
let rels = backend.list_entities().map_err(EngineError::Backend)?;
let entity_paths = crate::ops::export::entity_paths_of(&rels);
let mut md_entries: Vec<(std::path::PathBuf, Vec<u8>)> =
Vec::with_capacity(rels.len());
for rel in rels {
if let Some(bytes) = backend.read_entity(&rel).map_err(EngineError::Backend)? {
md_entries.push((rel, bytes));
}
}
let records = backend.read_provenance(None).unwrap_or_default();
let (provenance, redactions) =
crate::ops::export::build_redacted_archive_provenance(&records, &entity_paths);
let anchors_bytes = backend
.read_anchors_sidecar()
.map_err(EngineError::Backend)?;
let (checks_bytes, check_redactions) = crate::ops::export::sealed_checks_bytes_for(
workspace_root,
mem_name,
&entity_paths,
Some(&self.sealed_row_reader(mem_name)),
);
crate::ops::export::export_entries_to_bytes(
config,
workspace_root,
workspace_schemas_dir,
mem_name,
md_entries,
Some(&provenance),
anchors_bytes.as_deref(),
checks_bytes.as_deref(),
self.ref_schema_source_for(config),
)
.map(|mut out| {
out.redactions =
crate::ops::export::merge_redactions(redactions, check_redactions);
out
})
.map_err(|e| {
EngineError::Backend(crate::backend::BackendError::Other(format!(
"export_mem_to_bytes: {e}"
)))
})
}
}
}
}
pub(crate) fn load_embedded_schemas(
schema_files: &[SchemaFile],
) -> Result<Vec<Arc<Schema>>, FromArchiveBytesError> {
if schema_files.is_empty() {
return Ok(Vec::new());
}
let mut manifest: Option<&str> = None;
let mut types: Vec<(String, String)> = Vec::new();
for sf in schema_files {
if sf.archive_path == ".memstead/schema/schema.yaml" {
manifest = Some(&sf.content);
} else if let Some(rest) = sf.archive_path.strip_prefix(".memstead/schema/types/")
&& let Some(stem) = rest.strip_suffix(".yaml")
{
types.push((stem.to_string(), sf.content.clone()));
}
}
let Some(manifest_yaml) = manifest else {
return Err(FromArchiveBytesError::EmbeddedSchemaInvalid(
"embedded schema package present but `.memstead/schema/schema.yaml` missing"
.to_string(),
));
};
let marker_path = format!(
".memstead/schema/{}",
memstead_schema::loader::SCHEMA_FORMAT_MARKER_FILE
);
let format = if schema_files.iter().any(|sf| sf.archive_path == marker_path) {
memstead_schema::MetadataPolarityFormat::RequiredOptIn
} else {
memstead_schema::MetadataPolarityFormat::Legacy
};
let schema =
memstead_schema::load_schema_from_memory_with_format(manifest_yaml, &types, format)
.map_err(|e| FromArchiveBytesError::EmbeddedSchemaInvalid(e.to_string()))?;
Ok(vec![Arc::new(schema)])
}
#[cfg(test)]
mod tests;