use std::path::{Path, PathBuf};
use super::{NOTE_MAX_LEN, admit_by_create_rules, classify_invalid_mem_name};
use crate::FullEngineError;
use crate::workspace::{Mount, MountCapability, MountLifecycle, MountStorage};
use crate::workspace_store::WorkspaceStoreAdapter;
#[derive(Debug, Clone)]
pub enum MountSource {
Branch {
branch: String,
gitdir: Option<PathBuf>,
},
Remote { remote: String },
}
#[derive(Debug, Clone)]
pub struct MemMountParams {
pub name: String,
pub source: MountSource,
pub capability: MountCapability,
pub schema: Option<memstead_schema::SchemaRef>,
pub note: Option<String>,
pub operator_mode: bool,
pub actor: crate::vcs::Actor,
pub client: Option<crate::vcs::ClientId>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct MemMountResponse {
pub name: String,
pub gitdir: String,
pub branch: String,
pub capability: &'static str,
pub schema_ref: String,
pub head: String,
pub fetched: bool,
pub config_written: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub warnings: Vec<crate::ops::WarningHint>,
}
const REGISTRY_REF: &str = "refs/heads/__MEMSTEAD";
pub fn mount_mem(
engine: &mut crate::Engine,
params: MemMountParams,
) -> Result<MemMountResponse, FullEngineError> {
if let Some(note) = params.note.as_deref()
&& note.chars().count() > NOTE_MAX_LEN
{
return Err(crate::EngineError::InvalidInput(format!(
"note exceeds {NOTE_MAX_LEN} characters"
))
.into());
}
if let Some(reason) = classify_invalid_mem_name(¶ms.name) {
return Err(FullEngineError::InvalidMemName {
name: params.name.clone(),
reason,
});
}
if crate::entity::id::validate_mem_name_grammar(¶ms.name).is_err() {
return Err(FullEngineError::InvalidMemName {
name: params.name.clone(),
reason: "invalid_char",
});
}
let root = engine
.workspace_root()
.map(Path::to_path_buf)
.ok_or_else(|| {
crate::EngineError::InvalidInput(
"mem mount requires a workspace root to write its roster".to_string(),
)
})?;
let ops = engine.git_branch_ops().ok_or_else(|| {
crate::EngineError::InvalidInput(
"mem mount requires the git-branch ops bundle (full boot only)".to_string(),
)
})?;
let ctx = engine.commit_context(
Some("memstead_mem_mount"),
params.actor,
params.client.clone(),
params.note.clone(),
);
engine
.reconcile_roster_forced()
.map_err(FullEngineError::from)?;
if let Some(existing) = engine.mem_router().origin_for_mem(¶ms.name) {
return Err(crate::EngineError::MemNameCollision {
name: params.name,
source_origin: existing.render_source(),
}
.into());
}
if engine
.mem_router()
.archive_path_for_mem(¶ms.name)
.is_some()
|| engine.mount(¶ms.name).is_some()
{
return Err(crate::EngineError::MemNameCollision {
name: params.name,
source_origin: "attached read mem".to_string(),
}
.into());
}
if let Some(q) = engine.quarantine_reason(¶ms.name) {
return Err(crate::EngineError::MemNameCollision {
name: params.name.clone(),
source_origin: format!("a quarantined mount ({})", q.reason_code),
}
.into());
}
let own_gitdir = root.join("mem-repo").join(".git");
let own_gitdir = own_gitdir.canonicalize().unwrap_or(own_gitdir);
let (gitdir, branch_ref, fetched) = match ¶ms.source {
MountSource::Branch { branch, gitdir } => {
let gitdir = match gitdir {
Some(path) => {
let path = if path.is_absolute() {
path.clone()
} else {
root.join(path)
};
path.canonicalize().unwrap_or(path)
}
None => own_gitdir.clone(),
};
require_mem_repo(&ops, &gitdir)?;
let branch_ref = crate::workspace::branch_full_ref(branch);
(gitdir, branch_ref, false)
}
MountSource::Remote { remote } => {
require_mem_repo_dir(&own_gitdir)?;
let branch_ref = format!("refs/heads/{}", params.name);
fetch_mem_branch(&ops, &own_gitdir, remote, ¶ms.name)?;
(own_gitdir.clone(), branch_ref, true)
}
};
let in_own_mem_repo = gitdir == own_gitdir;
let tracking_ref = match ¶ms.source {
MountSource::Remote { remote } => Some(format!("refs/remotes/{remote}/{}", params.name)),
MountSource::Branch { .. } => None,
};
let existing_tip =
(ops.resolve_ref)(&gitdir, &branch_ref).map_err(crate::EngineError::Backend)?;
let (head, adopt) = match (&tracking_ref, existing_tip) {
(None, Some(tip)) => (tip, false),
(None, None) => {
return Err(crate::EngineError::UnknownRef(format!(
"{branch_ref} does not exist in {}: a mount serves a branch that is already \
there (`memstead mem init` creates a mem, `--remote` fetches one first)",
gitdir.display()
))
.into());
}
(Some(tracking), existing) => {
let fetched_tip = (ops.resolve_ref)(&gitdir, tracking)
.map_err(crate::EngineError::Backend)?
.ok_or_else(|| crate::EngineError::UnknownRef(tracking.clone()))?;
match existing {
Some(tip) if tip == fetched_tip => (tip, false),
Some(tip) => {
return Err(crate::EngineError::InvalidInput(format!(
"{branch_ref} already exists locally at {tip} and the remote's branch \
is at {fetched_tip}: mount the local branch with `--branch {}` and \
bring it up to date with `memstead pull`",
params.name
))
.into());
}
None => (fetched_tip, true),
}
}
};
let entry_name = crate::workspace::branch_short_name(&branch_ref).to_string();
let own_entry = (ops.read_config_at_ref)(&gitdir, REGISTRY_REF, &entry_name)
.map_err(crate::EngineError::Backend)?;
let remote_entry = match (¶ms.source, &own_entry) {
(MountSource::Remote { remote }, None) => {
let tracking_registry = format!("refs/remotes/{remote}/__MEMSTEAD");
match (ops.resolve_ref)(&gitdir, &tracking_registry) {
Ok(Some(_)) => (ops.read_config_at_ref)(&gitdir, &tracking_registry, &entry_name)
.map_err(crate::EngineError::Backend)?,
_ => None,
}
}
_ => None,
};
let entry_pin = |bytes: &[u8]| -> Option<memstead_schema::SchemaRef> {
let value: serde_json::Value = serde_json::from_slice(bytes).ok()?;
memstead_schema::config::parse_mem_config(&value)
.ok()?
.schema
};
let recorded_pin = own_entry
.as_deref()
.and_then(entry_pin)
.or_else(|| remote_entry.as_deref().and_then(entry_pin));
let pin = match (recorded_pin, params.schema.clone()) {
(Some(recorded), Some(asked)) if recorded != asked => {
return Err(crate::EngineError::InvalidInput(format!(
"mem {:?} is pinned to {recorded} in its registry entry and the mount names \
{asked}: a mount never re-pins (omit `--schema`, or change the pin with \
`memstead mem set-schema` once the mem is mounted writable)",
params.name
))
.into());
}
(Some(recorded), _) => recorded,
(None, Some(asked)) => asked,
(None, None) => {
return Err(crate::EngineError::InvalidInput(format!(
"mem {:?} has no schema pin: no registry this mount reads has an entry for \
it, so the pin must be named. Pass `--schema <name>@<version>`, the schema \
the mem was written under; a mount never guesses one",
params.name
))
.into());
}
};
if !params.operator_mode {
let mut catalogue: Vec<std::sync::Arc<memstead_schema::Schema>> =
engine.workspace_schemas().to_vec();
catalogue.extend_from_slice(engine.builtin_schemas());
admit_by_create_rules(
engine,
¶ms.name,
&root.join(¶ms.name),
&pin,
&catalogue,
)?;
}
let mount = Mount {
mem: params.name.clone(),
schema: Some(pin.clone()),
storage: MountStorage::GitBranch {
gitdir: gitdir.clone(),
branch: branch_ref.clone(),
},
capability: params.capability,
lifecycle: MountLifecycle::Eager,
cross_linkable: true,
migration_target: None,
};
let mut schema_report = crate::ops::FullRefreshReport::default();
engine.refresh_schema_sources_for(&mut schema_report, std::slice::from_ref(&mount));
let resolves = engine
.workspace_schemas()
.iter()
.chain(engine.builtin_schemas())
.any(|schema| {
let (name, version) = schema.id();
memstead_schema::SchemaRef::new(name, version) == pin
});
if !resolves {
return Err(crate::EngineError::InvalidInput(format!(
"mem {:?} is pinned to {pin}, a schema this workspace cannot resolve \
(SCHEMA_NOT_FOUND): it is neither built in nor installed here or in the git \
directory that holds the branch. Install it (`memstead schema install`, or \
`memstead pull --all` where the remote's registry carries it) and mount again; \
nothing was mounted",
params.name
))
.into());
}
let created_branch = adopt;
if adopt {
(ops.create_branch_at)(&gitdir, ¶ms.name, &head)
.map_err(crate::EngineError::Backend)?;
}
let entry_stood = own_entry.is_some();
let undo_storage = |engine: &crate::Engine, config_written: bool| {
if let Some(ops) = engine.git_branch_ops() {
if created_branch && !entry_stood {
let _ = (ops.prune_residue)(&gitdir, ¶ms.name, &ctx);
} else if config_written {
let _ = (ops.prune_config_blob)(&gitdir, &entry_name, &ctx);
}
}
};
let mut config_written = false;
if in_own_mem_repo && own_entry.is_none() {
let bytes = match remote_entry {
Some(bytes) => bytes,
None => {
let mut bytes = serde_json::to_vec_pretty(&serde_json::json!({
"version": "0.1.0",
"schema": pin.to_string(),
}))
.map_err(|e| {
crate::EngineError::InvalidInput(format!("could not serialize mem config: {e}"))
})?;
bytes.push(b'\n');
bytes
}
};
let written = engine
.instantiate_backend(&mount)
.map_err(|e| crate::EngineError::Mem(e.to_string()))
.and_then(|backend| {
backend
.write_mem_config(&bytes, &ctx)
.map_err(crate::EngineError::Backend)
});
if let Err(e) = written {
undo_storage(engine, false);
return Err(e.into());
}
config_written = true;
}
if let Err(e) = write_roster_row(&root, Some(&mount), ¶ms.name) {
undo_storage(engine, config_written);
return Err(e.into());
}
let attached = engine.reconcile_roster_forced();
let serving = engine.mount(¶ms.name).is_some();
if !serving {
let reason = engine
.quarantine_reason(¶ms.name)
.map(|q| (q.reason_code.clone(), q.reason_message.clone()));
let _ = write_roster_row(&root, None, ¶ms.name);
let _ = engine.reconcile_roster_forced();
undo_storage(engine, config_written);
return Err(match (attached, reason) {
(Err(e), _) => e.into(),
(Ok(_), Some((code, message))) => crate::EngineError::InvalidInput(format!(
"mem {:?} did not mount ({code}): {message}",
params.name
))
.into(),
(Ok(_), None) => crate::EngineError::InvalidInput(format!(
"mem {:?} did not mount: the roster row was not attached",
params.name
))
.into(),
});
}
let mut warnings: Vec<crate::ops::WarningHint> = Vec::new();
if engine.settings().mutations.require_notes.unwrap_or(false)
&& params.note.as_deref().is_none_or(|n| n.trim().is_empty())
{
warnings.push(crate::ops::WarningHint::NoteMissing {
tool: "memstead_mem_mount".to_string(),
});
}
Ok(MemMountResponse {
name: params.name,
gitdir: gitdir.display().to_string(),
branch: branch_ref,
capability: match params.capability {
MountCapability::Write => "write",
MountCapability::ReadOnly => "read-only",
},
schema_ref: pin.to_string(),
head,
fetched,
config_written,
warnings,
})
}
fn require_mem_repo(
ops: &crate::engine::GitBranchOps,
gitdir: &Path,
) -> Result<(), FullEngineError> {
require_mem_repo_dir(gitdir)?;
let registry = (ops.resolve_ref)(gitdir, REGISTRY_REF).unwrap_or(None);
if registry.is_none() {
return Err(crate::EngineError::InvalidInput(format!(
"{} is not a mem-repo: it carries no {REGISTRY_REF} (a mount serves a mem of a \
mem-repo; name the mem-repo's git directory, usually `<workspace>/mem-repo/.git`)",
gitdir.display()
))
.into());
}
Ok(())
}
fn require_mem_repo_dir(gitdir: &Path) -> Result<(), FullEngineError> {
if !gitdir.is_dir() {
return Err(crate::EngineError::InvalidInput(format!(
"{} is not a git directory: a mount serves a branch of a mem-repo (pass \
`--gitdir <path>` for a mem that lives in another workspace's mem-repo, or run \
`memstead mem-repo init` to give this workspace its own)",
gitdir.display()
))
.into());
}
Ok(())
}
fn fetch_mem_branch(
ops: &crate::engine::GitBranchOps,
gitdir: &Path,
remote: &str,
mem: &str,
) -> Result<(), FullEngineError> {
let lift = |e: crate::backend::BackendError| -> FullEngineError {
if crate::EngineError::is_remote_marker(&e) {
crate::EngineError::from_transport(e).into()
} else {
crate::EngineError::Backend(e).into()
}
};
let heads = (ops.ls_remote)(gitdir, remote).map_err(lift)?;
let branch_ref = format!("refs/heads/{mem}");
if !heads.iter().any(|(name, _)| name == &branch_ref) {
return Err(crate::EngineError::UnknownRef(format!(
"remote {remote:?} has no branch {branch_ref}: the mem {mem:?} is not on that remote"
))
.into());
}
let mut refspecs = vec![format!("+{branch_ref}:refs/remotes/{remote}/{mem}")];
if heads.iter().any(|(name, _)| name == REGISTRY_REF) {
refspecs.push(format!("+{REGISTRY_REF}:refs/remotes/{remote}/__MEMSTEAD"));
}
(ops.fetch)(gitdir, remote, &refspecs).map_err(lift)?;
Ok(())
}
fn write_roster_row(
root: &Path,
row: Option<&Mount>,
name: &str,
) -> Result<(), crate::EngineError> {
let store = crate::FileWorkspaceStore::new();
let failed = |e: crate::workspace_store::StoreError| {
crate::EngineError::Mem(format!("mount roster: {e}"))
};
for _ in 0..8 {
let before = store.read_state_bytes(root).map_err(failed)?;
let mut workspace = store.load(root).map_err(failed)?;
workspace.mounts.retain(|m| m.mem != name);
if let Some(row) = row {
workspace.mounts.push(row.clone());
}
if store
.save_state_cas(root, &workspace, before.as_deref())
.map_err(failed)?
{
return Ok(());
}
}
Err(crate::EngineError::Mem(
"mount roster: the file kept changing under the write; nothing was mounted".to_string(),
))
}