chore: import upstream snapshot with attribution
Integ / changes (push) Has been skipped
Pre-commit / pre-commit (push) Failing after 1s
CLI exit codes / changes (push) Has been skipped
Test (Install) / changes (push) Has been skipped
Test (Python) / changes (push) Has been skipped
Test (TypeScript) / changes (push) Has been skipped
CLI exit codes / cli-gate (push) Has been cancelled
Test (Install) / test-install-gate (push) Has been cancelled
Integ / integ-gate (push) Has been cancelled
Test (Python) / test-python-gate (push) Has been cancelled
Test (TypeScript) / test-typescript-gate (push) Has been cancelled
Test (Install) / python-minimal (3.12) (push) Has been cancelled
Test (Install) / python-minimal (3.11) (push) Has been cancelled
Test (Install) / python-extra (agno, mirage.agents.agno) (push) Has been cancelled
Test (Install) / python-extra (chroma, mirage.resource.chroma) (push) Has been cancelled
Test (Install) / python-extra (pdf, mirage.core.filetype.pdf) (push) Has been cancelled
Integ / integ (push) Has been cancelled
Integ / integ-database (push) Has been cancelled
Integ / integ-database-ts (push) Has been cancelled
Integ / integ-data (push) Has been cancelled
Integ / integ-ssh (push) Has been cancelled
Integ / integ-ssh-ts (push) Has been cancelled
Test (Python) / audit (push) Has been cancelled
Test (TypeScript) / test (push) Has been cancelled
Test (TypeScript) / python-fs-shim (push) Has been cancelled
CLI exit codes / Python CLI (push) Has been cancelled
CLI exit codes / TypeScript CLI (push) Has been cancelled
CLI exit codes / Cross-language snapshot interop (push) Has been cancelled
Test (Python) / test (push) Has been cancelled
Test (Python) / import-isolation (deepagents, openai, mirage.agents.openai_agents) (push) Has been cancelled
Test (Python) / import-isolation (deepagents, pydantic-ai, mirage.agents.pydantic_ai) (push) Has been cancelled
Integ / integ-ts (push) Has been cancelled
Integ / integ-fuse (push) Has been cancelled
Test (Install) / python-extra (databricks, mirage.resource.databricks_volume) (push) Has been cancelled
Test (Install) / python-extra (deepagents, mirage.agents.langchain) (push) Has been cancelled
Test (Install) / python-extra (email, mirage.resource.email) (push) Has been cancelled
Test (Install) / python-extra (fuse, mirage.fuse.mount) (push) Has been cancelled
Test (Install) / python-extra (hdf5, mirage.core.filetype.hdf5) (push) Has been cancelled
Test (Install) / python-extra (hf, mirage.resource.hf_buckets) (push) Has been cancelled
Test (Install) / python-extra (lancedb, mirage.resource.lancedb) (push) Has been cancelled
Test (Install) / python-extra (langfuse, mirage.resource.langfuse) (push) Has been cancelled
Test (Install) / python-extra (mongodb, mirage.resource.mongodb) (push) Has been cancelled
Test (Install) / python-extra (nextcloud, mirage.resource.nextcloud) (push) Has been cancelled
Test (Install) / python-extra (openai, mirage.agents.openai_agents) (push) Has been cancelled
Test (Install) / python-extra (openhands, mirage.agents.openhands, 3.12) (push) Has been cancelled
Test (Install) / python-extra (parquet, mirage.core.filetype.parquet) (push) Has been cancelled
Test (Install) / python-extra (postgres, mirage.resource.postgres) (push) Has been cancelled
Test (Install) / python-extra (pydantic-ai, mirage.agents.pydantic_ai) (push) Has been cancelled
Test (Install) / python-extra (qdrant, mirage.resource.qdrant) (push) Has been cancelled
Test (Install) / python-extra (redis, mirage.resource.redis) (push) Has been cancelled
Test (Install) / python-extra (s3, mirage.resource.s3) (push) Has been cancelled
Test (Install) / python-extra (ssh, mirage.resource.ssh) (push) Has been cancelled
Test (Install) / ts-minimal (push) Has been cancelled
Integ / changes (push) Has been skipped
Pre-commit / pre-commit (push) Failing after 1s
CLI exit codes / changes (push) Has been skipped
Test (Install) / changes (push) Has been skipped
Test (Python) / changes (push) Has been skipped
Test (TypeScript) / changes (push) Has been skipped
CLI exit codes / cli-gate (push) Has been cancelled
Test (Install) / test-install-gate (push) Has been cancelled
Integ / integ-gate (push) Has been cancelled
Test (Python) / test-python-gate (push) Has been cancelled
Test (TypeScript) / test-typescript-gate (push) Has been cancelled
Test (Install) / python-minimal (3.12) (push) Has been cancelled
Test (Install) / python-minimal (3.11) (push) Has been cancelled
Test (Install) / python-extra (agno, mirage.agents.agno) (push) Has been cancelled
Test (Install) / python-extra (chroma, mirage.resource.chroma) (push) Has been cancelled
Test (Install) / python-extra (pdf, mirage.core.filetype.pdf) (push) Has been cancelled
Integ / integ (push) Has been cancelled
Integ / integ-database (push) Has been cancelled
Integ / integ-database-ts (push) Has been cancelled
Integ / integ-data (push) Has been cancelled
Integ / integ-ssh (push) Has been cancelled
Integ / integ-ssh-ts (push) Has been cancelled
Test (Python) / audit (push) Has been cancelled
Test (TypeScript) / test (push) Has been cancelled
Test (TypeScript) / python-fs-shim (push) Has been cancelled
CLI exit codes / Python CLI (push) Has been cancelled
CLI exit codes / TypeScript CLI (push) Has been cancelled
CLI exit codes / Cross-language snapshot interop (push) Has been cancelled
Test (Python) / test (push) Has been cancelled
Test (Python) / import-isolation (deepagents, openai, mirage.agents.openai_agents) (push) Has been cancelled
Test (Python) / import-isolation (deepagents, pydantic-ai, mirage.agents.pydantic_ai) (push) Has been cancelled
Integ / integ-ts (push) Has been cancelled
Integ / integ-fuse (push) Has been cancelled
Test (Install) / python-extra (databricks, mirage.resource.databricks_volume) (push) Has been cancelled
Test (Install) / python-extra (deepagents, mirage.agents.langchain) (push) Has been cancelled
Test (Install) / python-extra (email, mirage.resource.email) (push) Has been cancelled
Test (Install) / python-extra (fuse, mirage.fuse.mount) (push) Has been cancelled
Test (Install) / python-extra (hdf5, mirage.core.filetype.hdf5) (push) Has been cancelled
Test (Install) / python-extra (hf, mirage.resource.hf_buckets) (push) Has been cancelled
Test (Install) / python-extra (lancedb, mirage.resource.lancedb) (push) Has been cancelled
Test (Install) / python-extra (langfuse, mirage.resource.langfuse) (push) Has been cancelled
Test (Install) / python-extra (mongodb, mirage.resource.mongodb) (push) Has been cancelled
Test (Install) / python-extra (nextcloud, mirage.resource.nextcloud) (push) Has been cancelled
Test (Install) / python-extra (openai, mirage.agents.openai_agents) (push) Has been cancelled
Test (Install) / python-extra (openhands, mirage.agents.openhands, 3.12) (push) Has been cancelled
Test (Install) / python-extra (parquet, mirage.core.filetype.parquet) (push) Has been cancelled
Test (Install) / python-extra (postgres, mirage.resource.postgres) (push) Has been cancelled
Test (Install) / python-extra (pydantic-ai, mirage.agents.pydantic_ai) (push) Has been cancelled
Test (Install) / python-extra (qdrant, mirage.resource.qdrant) (push) Has been cancelled
Test (Install) / python-extra (redis, mirage.resource.redis) (push) Has been cancelled
Test (Install) / python-extra (s3, mirage.resource.s3) (push) Has been cancelled
Test (Install) / python-extra (ssh, mirage.resource.ssh) (push) Has been cancelled
Test (Install) / ts-minimal (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
|
||||
from mirage.workspace.mount.mount import MountEntry
|
||||
from mirage.workspace.mount.registry import (MountCommandUnsupported,
|
||||
MountRegistry)
|
||||
from mirage.workspace.mount.spec import Mount
|
||||
|
||||
__all__ = ["Mount", "MountCommandUnsupported", "MountEntry", "MountRegistry"]
|
||||
@@ -0,0 +1,535 @@
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
|
||||
import dataclasses
|
||||
import inspect
|
||||
from typing import Any, Callable
|
||||
|
||||
from mirage.cache.context import push_cache_manager
|
||||
from mirage.cache.manager import CacheManager
|
||||
from mirage.commands.builtin.utils.safeguard import (apply_op_safeguard,
|
||||
run_with_timeout)
|
||||
from mirage.commands.config import RegisteredCommand
|
||||
from mirage.commands.resolve import get_extension
|
||||
from mirage.commands.safeguard import CommandSafeguard, resolve_safeguard
|
||||
from mirage.commands.spec import CommandSpec
|
||||
from mirage.io.types import ByteSource, IOResult
|
||||
from mirage.observe.context import (push_mount_prefix, push_revisions,
|
||||
reset_revisions, with_mount_prefix,
|
||||
with_revisions)
|
||||
from mirage.ops.registry import RegisteredOp
|
||||
from mirage.resource.base import BaseResource
|
||||
from mirage.types import ConsistencyPolicy, MountMode, PathSpec
|
||||
from mirage.utils.key_prefix import mount_key
|
||||
|
||||
|
||||
def _wrap_cmd_streams(
|
||||
result: tuple[ByteSource | None, IOResult],
|
||||
mount_prefix: str,
|
||||
revisions: dict[str, str] | None,
|
||||
) -> tuple[ByteSource | None, IOResult]:
|
||||
"""Wrap any async-iterator streams in ``result`` with the mount
|
||||
prefix and active revisions, so ``record_stream`` and
|
||||
``revision_for`` calls inside the lazy backend body see the right
|
||||
context when consumed after this frame exits.
|
||||
|
||||
Mirrors the ``exit_on_empty`` pattern: thin async-gen wrapper that
|
||||
side-effects the recorder state as bytes flow through. Same object
|
||||
appearing in both the primary stream and IOResult.reads/writes is
|
||||
wrapped once (dedup by identity).
|
||||
|
||||
Args:
|
||||
result: ``(stream, io)`` as returned by a command handler.
|
||||
mount_prefix: prefix to push during stream consumption.
|
||||
revisions: revisions map to push during stream consumption
|
||||
(None when the mount has no pins installed).
|
||||
"""
|
||||
stream, io = result
|
||||
seen: dict[int, ByteSource] = {}
|
||||
|
||||
def _wrap(obj: ByteSource | None) -> ByteSource | None:
|
||||
if obj is None or isinstance(obj, (bytes, bytearray)):
|
||||
return obj
|
||||
oid = id(obj)
|
||||
if oid in seen:
|
||||
return seen[oid]
|
||||
wrapped = with_mount_prefix(mount_prefix, obj)
|
||||
if revisions:
|
||||
wrapped = with_revisions(revisions, wrapped)
|
||||
seen[oid] = wrapped
|
||||
return wrapped
|
||||
|
||||
stream = _wrap(stream)
|
||||
for k, v in list(io.reads.items()):
|
||||
io.reads[k] = _wrap(v)
|
||||
for k, v in list(io.writes.items()):
|
||||
io.writes[k] = _wrap(v)
|
||||
return stream, io
|
||||
|
||||
|
||||
class MountEntry:
|
||||
"""A mounted resource with command and op dispatch.
|
||||
|
||||
Each mount has its own lookup tables for commands and ops.
|
||||
Different mounts of the same resource type can have
|
||||
different registered commands/ops.
|
||||
|
||||
Resolution hierarchy (same for commands and ops):
|
||||
1. (name, extension) -- filetype-specific
|
||||
2. (name, None) -- resource-specific
|
||||
3. general[name] -- general fallback
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
prefix: str,
|
||||
resource: BaseResource,
|
||||
mode: MountMode = MountMode.READ,
|
||||
consistency: ConsistencyPolicy = ConsistencyPolicy.LAZY,
|
||||
) -> None:
|
||||
if not prefix.startswith("/"):
|
||||
raise ValueError(f"prefix must start with /: {prefix!r}")
|
||||
if not prefix.endswith("/"):
|
||||
raise ValueError(f"prefix must end with /: {prefix!r}")
|
||||
if "//" in prefix:
|
||||
raise ValueError(f"prefix must not contain //: {prefix!r}")
|
||||
self.prefix = prefix
|
||||
self.resource = resource
|
||||
self.mode = mode
|
||||
self.consistency = consistency
|
||||
self.cache_manager: CacheManager | None = None
|
||||
# Per-path revision pins installed at Workspace.load time. Read
|
||||
# functions consult these via the ``revision_for`` contextvar
|
||||
# lookup; on a hit, the backend GET pins to the recorded
|
||||
# revision so replay serves the exact bytes the agent saw.
|
||||
# Empty during normal runs; populated only by the snapshot
|
||||
# loader.
|
||||
self.revisions: dict[str, str] = {}
|
||||
self._cmds: dict[tuple, RegisteredCommand] = {}
|
||||
self._general_cmds: dict[str, RegisteredCommand] = {}
|
||||
self._cmd_specs: dict[str, CommandSpec] = {}
|
||||
self.command_safeguards: dict[str, CommandSafeguard] = {}
|
||||
self._ops: dict[tuple, RegisteredOp] = {}
|
||||
self._general_ops: dict[str, RegisteredOp] = {}
|
||||
# key: (cmd_name, target_resource_type)
|
||||
self._cross_cmds: dict[tuple, RegisteredCommand] = {}
|
||||
|
||||
# ── command registration ──────────────────────────
|
||||
|
||||
def register(self, cmd: RegisteredCommand) -> None:
|
||||
"""Register a resource-specific command."""
|
||||
key = (cmd.name, cmd.filetype)
|
||||
self._cmds[key] = cmd
|
||||
if cmd.spec is not None:
|
||||
self._cmd_specs[cmd.name] = cmd.spec
|
||||
|
||||
def register_general(
|
||||
self,
|
||||
cmd: RegisteredCommand,
|
||||
) -> None:
|
||||
"""Register a general command (resource=None).
|
||||
|
||||
General commands work on any resource (e.g. echo, pwd).
|
||||
They are the last fallback in resolve_command().
|
||||
"""
|
||||
self._general_cmds[cmd.name] = cmd
|
||||
if cmd.spec is not None:
|
||||
self._cmd_specs[cmd.name] = cmd.spec
|
||||
|
||||
def resolve_command(
|
||||
self,
|
||||
cmd_name: str,
|
||||
extension: str | None = None,
|
||||
) -> RegisteredCommand | None:
|
||||
"""Resolve command with fallback hierarchy.
|
||||
|
||||
Lookup order:
|
||||
1. (cmd_name, extension) -- filetype-specific
|
||||
2. (cmd_name, None) -- resource-specific
|
||||
3. general_cmds[cmd_name] -- general fallback
|
||||
"""
|
||||
if extension:
|
||||
cmd = self._cmds.get((cmd_name, extension))
|
||||
if cmd is not None:
|
||||
return cmd
|
||||
cmd = self._cmds.get((cmd_name, None))
|
||||
if cmd is not None:
|
||||
return cmd
|
||||
return self._general_cmds.get(cmd_name)
|
||||
|
||||
def spec_for(
|
||||
self,
|
||||
cmd_name: str,
|
||||
) -> CommandSpec | None:
|
||||
"""Get the spec for a command name."""
|
||||
return self._cmd_specs.get(cmd_name)
|
||||
|
||||
def is_general_command(self, cmd_name: str) -> bool:
|
||||
"""Whether `cmd_name` is registered as a general command here."""
|
||||
return cmd_name in self._general_cmds
|
||||
|
||||
def all_commands(self) -> list[RegisteredCommand]:
|
||||
"""All registered commands (per-mount + general), deduped by name."""
|
||||
seen: set[str] = set()
|
||||
out: list[RegisteredCommand] = []
|
||||
for rc in self._cmds.values():
|
||||
if rc.name in seen:
|
||||
continue
|
||||
seen.add(rc.name)
|
||||
out.append(rc)
|
||||
for rc in self._general_cmds.values():
|
||||
if rc.name in seen:
|
||||
continue
|
||||
seen.add(rc.name)
|
||||
out.append(rc)
|
||||
return out
|
||||
|
||||
def filetype_handlers(
|
||||
self,
|
||||
cmd_name: str,
|
||||
) -> dict[str, Callable]:
|
||||
"""Get filetype-specific command handlers.
|
||||
|
||||
Example::
|
||||
|
||||
mount.register(generic_cat) # ("cat", None)
|
||||
mount.register(parquet_cat) # ("cat", ".parquet")
|
||||
|
||||
mount.filetype_handlers("cat")
|
||||
# -> {".parquet": parquet_cat_fn}
|
||||
|
||||
Args:
|
||||
cmd_name (str): command name, e.g. "cat".
|
||||
"""
|
||||
fns: dict[str, Callable] = {}
|
||||
for (name, ft), rc in self._cmds.items():
|
||||
if name == cmd_name and ft is not None:
|
||||
if ft not in fns:
|
||||
fns[ft] = rc.fn
|
||||
return fns
|
||||
|
||||
def register_fns(self, fns: list) -> None:
|
||||
"""Register commands and ops from decorated functions.
|
||||
|
||||
Args:
|
||||
fns (list): Functions decorated with @command and/or @op.
|
||||
|
||||
Raises:
|
||||
ValueError: If a command/op's resource doesn't match
|
||||
this mount's resource.
|
||||
"""
|
||||
pname = self.resource.name
|
||||
for fn in fns:
|
||||
if hasattr(fn, "_registered_commands"):
|
||||
rcs = fn._registered_commands
|
||||
matching = [
|
||||
rc for rc in rcs
|
||||
if rc.resource is None or rc.resource == pname
|
||||
]
|
||||
if rcs and not matching:
|
||||
resources = sorted({rc.resource for rc in rcs})
|
||||
raise ValueError(
|
||||
f"command {rcs[0].name!r} is for resource(s) "
|
||||
f"{resources!r}, not {pname!r}")
|
||||
for rc in matching:
|
||||
self.register(rc)
|
||||
if hasattr(fn, "_registered_ops"):
|
||||
ros = fn._registered_ops
|
||||
matching_ops = [
|
||||
ro for ro in ros
|
||||
if ro.resource is None or ro.resource == pname
|
||||
]
|
||||
if ros and not matching_ops:
|
||||
resources = sorted({ro.resource for ro in ros})
|
||||
raise ValueError(f"op {ros[0].name!r} is for resource(s) "
|
||||
f"{resources!r}, not {pname!r}")
|
||||
for ro in matching_ops:
|
||||
self.register_op(ro)
|
||||
|
||||
def unregister(self, names: list[str]) -> None:
|
||||
"""Remove all commands and ops with the given names.
|
||||
|
||||
Args:
|
||||
names (list[str]): Command/op names to remove.
|
||||
"""
|
||||
for name in names:
|
||||
keys = [k for k in self._cmds if k[0] == name]
|
||||
for k in keys:
|
||||
del self._cmds[k]
|
||||
self._general_cmds.pop(name, None)
|
||||
self._cmd_specs.pop(name, None)
|
||||
op_keys = [k for k in self._ops if k[0] == name]
|
||||
for k in op_keys:
|
||||
del self._ops[k]
|
||||
self._general_ops.pop(name, None)
|
||||
|
||||
def commands(self) -> dict[str, list[str | None]]:
|
||||
"""List registered commands grouped by filetype variants.
|
||||
|
||||
Returns:
|
||||
dict[str, list[str | None]]: Command name to filetype list.
|
||||
"""
|
||||
result: dict[str, list[str | None]] = {}
|
||||
for (name, filetype) in self._cmds:
|
||||
result.setdefault(name, []).append(filetype)
|
||||
for name in self._general_cmds:
|
||||
result.setdefault(name, [])
|
||||
for name in result:
|
||||
result[name] = sorted(result[name],
|
||||
key=lambda x: (x is not None, x or ""))
|
||||
return dict(sorted(result.items()))
|
||||
|
||||
def registered_ops(self) -> dict[str, list[str | None]]:
|
||||
"""List registered ops grouped by filetype variants.
|
||||
|
||||
Returns:
|
||||
dict[str, list[str | None]]: Op name to filetype list.
|
||||
"""
|
||||
result: dict[str, list[str | None]] = {}
|
||||
for (name, filetype) in self._ops:
|
||||
result.setdefault(name, []).append(filetype)
|
||||
for name in self._general_ops:
|
||||
result.setdefault(name, [])
|
||||
for name in result:
|
||||
result[name] = sorted(result[name],
|
||||
key=lambda x: (x is not None, x or ""))
|
||||
return dict(sorted(result.items()))
|
||||
|
||||
# ── cross-mount registration ─────────────────────
|
||||
|
||||
def register_cross(
|
||||
self,
|
||||
cmd: RegisteredCommand,
|
||||
target_resource_type: str,
|
||||
) -> None:
|
||||
"""Register a cross-mount command for a target.
|
||||
|
||||
Example::
|
||||
|
||||
mount.register_cross(cp_cmd, "ram")
|
||||
# This mount can now cp to ram mounts
|
||||
|
||||
Args:
|
||||
cmd: the cross-mount command.
|
||||
target_resource_type: e.g. "ram", "s3".
|
||||
"""
|
||||
key = (cmd.name, target_resource_type)
|
||||
self._cross_cmds[key] = cmd
|
||||
|
||||
def resolve_cross(
|
||||
self,
|
||||
cmd_name: str,
|
||||
target_resource_type: str,
|
||||
) -> RegisteredCommand | None:
|
||||
"""Find a cross-mount command for a target."""
|
||||
return self._cross_cmds.get((cmd_name, target_resource_type))
|
||||
|
||||
# ── op registration ───────────────────────────────
|
||||
|
||||
def register_op(self, op: RegisteredOp) -> None:
|
||||
"""Register a resource-specific VFS op."""
|
||||
key = (op.name, op.filetype)
|
||||
self._ops[key] = op
|
||||
|
||||
def _resolve_cascade(
|
||||
self,
|
||||
name: str,
|
||||
extension: str | None,
|
||||
table: dict,
|
||||
general: dict,
|
||||
) -> list:
|
||||
"""Resolve with cascade: try filetype, resource, general.
|
||||
|
||||
Returns list of matching entries to try in order.
|
||||
First non-None result wins.
|
||||
"""
|
||||
levels = []
|
||||
if extension:
|
||||
entry = table.get((name, extension))
|
||||
if entry is not None:
|
||||
levels.append(entry)
|
||||
entry = table.get((name, None))
|
||||
if entry is not None:
|
||||
levels.append(entry)
|
||||
entry = general.get(name)
|
||||
if entry is not None:
|
||||
levels.append(entry)
|
||||
return levels
|
||||
|
||||
# ── execution ─────────────────────────────────────
|
||||
|
||||
async def execute_cmd(
|
||||
self,
|
||||
cmd_name: str,
|
||||
paths: list[PathSpec],
|
||||
texts: list[str],
|
||||
flag_kwargs: dict,
|
||||
*,
|
||||
stdin: ByteSource | None = None,
|
||||
cwd: str = "/",
|
||||
dispatch: Callable | None = None,
|
||||
session_id: str | None = None,
|
||||
env: dict[str, str] | None = None,
|
||||
exec_allowed: bool = True,
|
||||
) -> tuple[ByteSource | None, IOResult]:
|
||||
"""Execute a command on this mount's resource.
|
||||
|
||||
Pure dispatch — flag parsing is done upstream in
|
||||
executor/command.py. This method just resolves the
|
||||
command handler and calls it.
|
||||
|
||||
Args:
|
||||
cmd_name (str): command name.
|
||||
paths (list[PathSpec]): positional path args.
|
||||
texts (list[str]): positional text args.
|
||||
flag_kwargs (dict): parsed flags from upstream.
|
||||
stdin (ByteSource | None): stdin data.
|
||||
cwd (str): virtual cwd from session.
|
||||
"""
|
||||
extension = get_extension(paths[0].virtual) if paths else None
|
||||
|
||||
handlers = self._resolve_cascade(cmd_name, extension, self._cmds,
|
||||
self._general_cmds)
|
||||
if not handlers:
|
||||
return None, IOResult(
|
||||
exit_code=127,
|
||||
stderr=(f"{cmd_name}: command not found".encode()))
|
||||
|
||||
mount_prefix = self.prefix.rstrip("/")
|
||||
filetype_fns = self.filetype_handlers(cmd_name)
|
||||
is_filetype_cmd = extension is not None and (cmd_name,
|
||||
extension) in self._cmds
|
||||
|
||||
paths = [
|
||||
dataclasses.replace(
|
||||
p, resource_path=mount_key(p.virtual, mount_prefix))
|
||||
if isinstance(p, PathSpec) else p for p in paths
|
||||
]
|
||||
|
||||
# Stamp this mount's backend key onto path-shaped flag values so
|
||||
# backend reads can address them: a single PathSpec (e.g. awk -f,
|
||||
# single grep -f) or a list of PathSpec (repeatable grep -f).
|
||||
# Everything else (bools, strings, list[str] like repeated -e) is
|
||||
# not a path and passes through unchanged.
|
||||
kw = {}
|
||||
for k, v in flag_kwargs.items():
|
||||
if isinstance(v, PathSpec):
|
||||
kw[k] = dataclasses.replace(v,
|
||||
resource_path=mount_key(
|
||||
v.virtual, mount_prefix))
|
||||
elif isinstance(v, list) and v and all(
|
||||
isinstance(item, PathSpec) for item in v):
|
||||
kw[k] = [
|
||||
dataclasses.replace(item,
|
||||
resource_path=mount_key(
|
||||
item.virtual, mount_prefix))
|
||||
for item in v
|
||||
]
|
||||
else:
|
||||
kw[k] = v
|
||||
kw["index"] = self.resource.index
|
||||
kw["cwd"] = PathSpec(
|
||||
virtual=cwd,
|
||||
directory=cwd,
|
||||
resolved=False,
|
||||
resource_path=mount_key(cwd, mount_prefix),
|
||||
)
|
||||
kw["filetype_fns"] = (filetype_fns if not is_filetype_cmd else None)
|
||||
if stdin is not None:
|
||||
kw["stdin"] = stdin
|
||||
if dispatch is not None:
|
||||
kw["dispatch"] = dispatch
|
||||
if session_id is not None:
|
||||
kw["session_id"] = session_id
|
||||
if env is not None:
|
||||
kw["env"] = env
|
||||
kw["exec_allowed"] = exec_allowed
|
||||
|
||||
prev_prefix = push_mount_prefix(mount_prefix)
|
||||
revs_token = push_revisions(self.revisions or None)
|
||||
prev_manager = push_cache_manager(self.cache_manager)
|
||||
try:
|
||||
for cmd in handlers:
|
||||
if cmd.write and self.mode == MountMode.READ:
|
||||
return None, IOResult(
|
||||
exit_code=1,
|
||||
stderr=(f"{cmd_name}: read-only mount "
|
||||
f"at {self.prefix}".encode()))
|
||||
result = await cmd.fn(self.resource.accessor, paths, *texts,
|
||||
**kw)
|
||||
if result is not None:
|
||||
stream, io = _wrap_cmd_streams(result, mount_prefix,
|
||||
self.revisions or None)
|
||||
# TODO: hand back a finalization context separately
|
||||
# instead of stamping policy onto io.safeguard.
|
||||
io.safeguard = resolve_safeguard(
|
||||
cmd_name, cmd.safeguard,
|
||||
self.command_safeguards.get(cmd_name))
|
||||
return stream, io
|
||||
return None, IOResult()
|
||||
finally:
|
||||
reset_revisions(revs_token)
|
||||
push_mount_prefix(prev_prefix)
|
||||
push_cache_manager(prev_manager)
|
||||
|
||||
async def execute_op(
|
||||
self,
|
||||
op_name: str,
|
||||
path: str,
|
||||
*args,
|
||||
**kwargs,
|
||||
) -> Any:
|
||||
"""Execute a VFS op on this mount's resource.
|
||||
|
||||
Tries filetype-specific first, then resource-specific.
|
||||
First non-None result wins.
|
||||
|
||||
Args:
|
||||
op_name (str): operation name (e.g. "read", "stat").
|
||||
path (str): virtual path.
|
||||
"""
|
||||
filetype = get_extension(path)
|
||||
levels = self._resolve_cascade(op_name, filetype, self._ops,
|
||||
self._general_ops)
|
||||
if not levels:
|
||||
raise AttributeError(f"{self.resource.name}: "
|
||||
f"no op {op_name!r}")
|
||||
|
||||
if self.mode == MountMode.READ and any(o.write for o in levels):
|
||||
raise PermissionError(f"mount {self.prefix!r} is read-only")
|
||||
|
||||
mount_prefix = self.prefix.rstrip("/")
|
||||
scope = PathSpec(
|
||||
virtual=path,
|
||||
directory=path.rsplit("/", 1)[0] or "/",
|
||||
resource_path=mount_key(path, mount_prefix),
|
||||
)
|
||||
kwargs.setdefault("index", self.resource.index)
|
||||
op_override = self.command_safeguards.get(op_name)
|
||||
op_timeout = (op_override.timeout_seconds
|
||||
if op_override is not None else None)
|
||||
prev_prefix = push_mount_prefix(mount_prefix)
|
||||
revs_token = push_revisions(self.revisions or None)
|
||||
try:
|
||||
for op in levels:
|
||||
result = op.fn(self.resource.accessor, scope, *args, **kwargs)
|
||||
if inspect.isawaitable(result):
|
||||
result = await run_with_timeout(result, op_timeout,
|
||||
op_name)
|
||||
if result is not None:
|
||||
return await apply_op_safeguard(result, op_override)
|
||||
return None
|
||||
finally:
|
||||
reset_revisions(revs_token)
|
||||
push_mount_prefix(prev_prefix)
|
||||
@@ -0,0 +1,154 @@
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from mirage.resource.base import BaseResource
|
||||
from mirage.types import MountMode
|
||||
from mirage.utils.path import resolve_symlinks
|
||||
from mirage.workspace.mount.mount import MountEntry
|
||||
from mirage.workspace.mount.registry import MountRegistry
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class LinkEntry:
|
||||
target: str
|
||||
mtime: float
|
||||
|
||||
|
||||
class Namespace:
|
||||
"""Addressing authority: maps virtual paths to their mounts.
|
||||
|
||||
Owns the mount registry and the symlink table (and, in a later phase, the
|
||||
attribute overlay). Pure addressing: it resolves a virtual path to its
|
||||
mount and backend-relative path, following symlinks and crossing mounts.
|
||||
It holds no cache and performs no backend I/O. Op execution and caching
|
||||
live in the Dispatcher, which calls this layer to locate the mount.
|
||||
|
||||
Symlinks are stored verbatim as typed: the target string is kept exactly as
|
||||
the user wrote it (relative targets are resolved lazily against the link's
|
||||
own parent at resolution time), so ``readlink`` is GNU-faithful.
|
||||
"""
|
||||
|
||||
def __init__(self, registry: MountRegistry) -> None:
|
||||
self._registry = registry
|
||||
self._symlinks: dict[str, LinkEntry] = {}
|
||||
|
||||
@property
|
||||
def registry(self) -> MountRegistry:
|
||||
return self._registry
|
||||
|
||||
@property
|
||||
def symlinks(self) -> dict[str, LinkEntry]:
|
||||
return self._symlinks
|
||||
|
||||
def replace_symlinks(self, entries: dict[str, LinkEntry]) -> None:
|
||||
self._symlinks = dict(entries)
|
||||
|
||||
def symlink_targets(self) -> dict[str, str]:
|
||||
return {link: entry.target for link, entry in self._symlinks.items()}
|
||||
|
||||
def is_link(self, path: str) -> bool:
|
||||
return path in self._symlinks
|
||||
|
||||
def readlink(self, path: str) -> str | None:
|
||||
entry = self._symlinks.get(path)
|
||||
return entry.target if entry is not None else None
|
||||
|
||||
def symlink(self, link: str, target: str, mtime: float) -> None:
|
||||
self._symlinks[link] = LinkEntry(target=target, mtime=mtime)
|
||||
|
||||
def unlink(self, path: str) -> bool:
|
||||
if path in self._symlinks:
|
||||
del self._symlinks[path]
|
||||
return True
|
||||
return False
|
||||
|
||||
def rename(self, src: str, dst: str) -> bool:
|
||||
entry = self._symlinks.pop(src, None)
|
||||
if entry is None:
|
||||
return False
|
||||
self._symlinks[dst] = entry
|
||||
return True
|
||||
|
||||
def follow(self, path: str) -> str:
|
||||
"""Return ``path`` with all symlink prefixes resolved.
|
||||
|
||||
Identity when the table is empty or nothing matches.
|
||||
|
||||
Args:
|
||||
path (str): absolute virtual path.
|
||||
|
||||
Raises:
|
||||
CycleError: when resolution exceeds the hop limit (ELOOP).
|
||||
"""
|
||||
if not self._symlinks:
|
||||
return path
|
||||
return resolve_symlinks(path, self.symlink_targets())
|
||||
|
||||
def links_under(self, directory: str) -> dict[str, str]:
|
||||
"""Links living directly under a directory.
|
||||
|
||||
Args:
|
||||
directory (str): absolute virtual directory path.
|
||||
|
||||
Returns:
|
||||
dict[str, str]: link basename to target, for entries whose
|
||||
parent is exactly ``directory``.
|
||||
"""
|
||||
base = directory.rstrip("/") + "/"
|
||||
out: dict[str, str] = {}
|
||||
for link, entry in self._symlinks.items():
|
||||
if link.startswith(base) and "/" not in link[len(base):]:
|
||||
out[link[len(base):]] = entry.target
|
||||
return out
|
||||
|
||||
def purge_under(self, directory: str) -> int:
|
||||
"""Drop every link entry under a directory (``rm -r`` semantics).
|
||||
|
||||
Args:
|
||||
directory (str): absolute virtual directory path being removed.
|
||||
|
||||
Returns:
|
||||
int: number of entries dropped.
|
||||
"""
|
||||
base = directory.rstrip("/") + "/"
|
||||
doomed = [link for link in self._symlinks if link.startswith(base)]
|
||||
for link in doomed:
|
||||
del self._symlinks[link]
|
||||
return len(doomed)
|
||||
|
||||
def resolve(self,
|
||||
path: str,
|
||||
*,
|
||||
follow: bool = True) -> tuple[BaseResource, str, MountMode]:
|
||||
"""Map a virtual path to ``(resource, resource_path, mode)``.
|
||||
|
||||
Args:
|
||||
path (str): virtual path to resolve.
|
||||
follow (bool): follow symlinks (the symlink table) before mapping
|
||||
the path to its mount.
|
||||
|
||||
Raises:
|
||||
CycleError: when symlink resolution exceeds the hop limit (ELOOP).
|
||||
"""
|
||||
if follow and self._symlinks:
|
||||
path = resolve_symlinks(path, self.symlink_targets())
|
||||
return self._registry.resolve(path)
|
||||
|
||||
def mount_for(self, path: str) -> MountEntry:
|
||||
return self._registry.mount_for(path)
|
||||
|
||||
def is_mount_root(self, path: str) -> bool:
|
||||
return self._registry.is_mount_root(path)
|
||||
@@ -0,0 +1,388 @@
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
|
||||
from mirage.cache.file.mixin import FileCacheMixin
|
||||
from mirage.cache.manager import CacheManager
|
||||
from mirage.commands.builtin.general import COMMANDS as GENERAL_COMMANDS
|
||||
from mirage.ops.config import OpsMount
|
||||
from mirage.resource.base import BaseResource
|
||||
from mirage.resource.dev import DevResource
|
||||
from mirage.types import ConsistencyPolicy, MountMode, PathSpec
|
||||
from mirage.workspace.mount.mount import MountEntry
|
||||
|
||||
DEV_PREFIX = "/dev/"
|
||||
|
||||
|
||||
class MountCommandUnsupported(Exception):
|
||||
"""Raised when a path-bound command is unsupported by its backend.
|
||||
|
||||
Rendered in the GNU shape ``<cmd>: <operand>: <reason>`` with the
|
||||
EOPNOTSUPP strerror, naming the offending path like coreutils does;
|
||||
the backend name stays on the exception for programmatic use (#394).
|
||||
"""
|
||||
|
||||
def __init__(self, cmd_name: str, backend: str, operand: str) -> None:
|
||||
self.cmd_name = cmd_name
|
||||
self.backend = backend
|
||||
self.operand = operand
|
||||
super().__init__(f"{cmd_name}: {operand}: Operation not supported")
|
||||
|
||||
|
||||
class MountRegistry:
|
||||
"""Longest-prefix-match router.
|
||||
|
||||
Given a virtual path like "/s3-prod/data/file.json",
|
||||
resolves to the mount at "/s3-prod/" and returns the
|
||||
stripped resource path "/data/file.json".
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._mounts: list[MountEntry] = []
|
||||
self._root: MountEntry | None = None
|
||||
self._consistency: ConsistencyPolicy = ConsistencyPolicy.LAZY
|
||||
self._file_cache: FileCacheMixin | None = None
|
||||
self.mount(DEV_PREFIX, DevResource(), MountMode.WRITE)
|
||||
|
||||
def set_consistency(self, consistency: ConsistencyPolicy) -> None:
|
||||
self._consistency = consistency
|
||||
|
||||
def attach_file_cache(self, cache: FileCacheMixin | None) -> None:
|
||||
"""Attach the workspace file cache and build per-mount
|
||||
CacheManagers.
|
||||
|
||||
Called once by Workspace after the cache store exists. Mounts
|
||||
added later get their manager in ``mount()``.
|
||||
|
||||
Args:
|
||||
cache (FileCacheMixin | None): Workspace file cache store.
|
||||
"""
|
||||
self._file_cache = cache
|
||||
for m in self._mounts:
|
||||
self._attach_manager(m)
|
||||
|
||||
def _attach_manager(self, m: MountEntry) -> None:
|
||||
m.cache_manager = CacheManager(self._file_cache, m.resource.index,
|
||||
m.prefix, m.resource.caches_reads)
|
||||
|
||||
def mount(
|
||||
self,
|
||||
prefix: str,
|
||||
resource: BaseResource,
|
||||
mode: MountMode = MountMode.READ,
|
||||
consistency: ConsistencyPolicy = ConsistencyPolicy.LAZY,
|
||||
) -> MountEntry:
|
||||
"""Mount a resource and return the Mount object."""
|
||||
stripped = prefix.strip("/")
|
||||
norm_prefix = ("/" + stripped + "/" if stripped else "/")
|
||||
for existing in self._mounts:
|
||||
if existing.prefix == norm_prefix:
|
||||
raise ValueError(f"duplicate mount prefix: "
|
||||
f"{norm_prefix!r}")
|
||||
m = MountEntry(norm_prefix, resource, mode, consistency)
|
||||
for cmd in resource.commands():
|
||||
m.register(cmd)
|
||||
for cmd in GENERAL_COMMANDS:
|
||||
m.register_general(cmd)
|
||||
for ro in resource.ops_list():
|
||||
m.register_op(ro)
|
||||
if self._file_cache is not None:
|
||||
self._attach_manager(m)
|
||||
self._mounts.append(m)
|
||||
self._mounts.sort(key=lambda x: len(x.prefix), reverse=True)
|
||||
if norm_prefix == "/":
|
||||
self._root = m
|
||||
return m
|
||||
|
||||
def unmount(self, prefix: str) -> MountEntry:
|
||||
"""Remove a mount by exact prefix and return it.
|
||||
|
||||
Per-mount commands and ops live on the Mount instance and die with
|
||||
it. The /dev/ mount is reserved and cannot be removed.
|
||||
|
||||
Args:
|
||||
prefix (str): mount prefix.
|
||||
"""
|
||||
stripped = prefix.strip("/")
|
||||
norm_prefix = ("/" + stripped + "/" if stripped else "/")
|
||||
if norm_prefix == DEV_PREFIX:
|
||||
raise ValueError(f"cannot unmount reserved prefix: "
|
||||
f"{norm_prefix!r}")
|
||||
for i, m in enumerate(self._mounts):
|
||||
if m.prefix == norm_prefix:
|
||||
del self._mounts[i]
|
||||
if m is self._root:
|
||||
self._root = None
|
||||
return m
|
||||
raise ValueError(f"no mount at prefix: {norm_prefix!r}")
|
||||
|
||||
def resolve(
|
||||
self,
|
||||
path: str,
|
||||
) -> tuple[BaseResource, str, MountMode]:
|
||||
"""Returns (resource, resource_path, mode)."""
|
||||
had_trailing = path.endswith("/")
|
||||
norm = "/" + path.strip("/")
|
||||
for m in self._mounts:
|
||||
if (norm == m.prefix.rstrip("/") or norm.startswith(m.prefix)):
|
||||
resource_path = "/" + norm[len(m.prefix):]
|
||||
if (had_trailing and not resource_path.endswith("/")):
|
||||
resource_path += "/"
|
||||
return m.resource, resource_path, m.mode
|
||||
raise ValueError(f"no mount matches path: {path!r}")
|
||||
|
||||
def mount_for_prefix(self, prefix: str) -> MountEntry:
|
||||
for m in self._mounts:
|
||||
if m.prefix == prefix:
|
||||
return m
|
||||
raise ValueError(f"no mount with prefix {prefix!r}")
|
||||
|
||||
def is_mount_root(self, path: str) -> bool:
|
||||
stripped = path.strip("/")
|
||||
norm = "/" + stripped + "/" if stripped else "/"
|
||||
return any(m.prefix == norm for m in self._mounts)
|
||||
|
||||
def descendant_mounts(self, path: str) -> list[MountEntry]:
|
||||
"""Mounts whose prefix is strictly under `path`.
|
||||
|
||||
Used by traversal commands (find, tree, du, grep -r) to fan out
|
||||
across nested mounts. Excludes the mount that contains `path`
|
||||
itself; callers should add that mount via `mount_for(path)`.
|
||||
|
||||
Args:
|
||||
path (str): parent path to scan beneath.
|
||||
"""
|
||||
stripped = path.strip("/")
|
||||
norm = "/" + stripped + "/" if stripped else "/"
|
||||
out: list[MountEntry] = []
|
||||
for m in self._mounts:
|
||||
if m.prefix == norm:
|
||||
continue
|
||||
if not m.prefix.startswith(norm):
|
||||
continue
|
||||
out.append(m)
|
||||
out.sort(key=lambda m: m.prefix)
|
||||
return out
|
||||
|
||||
def child_mount_names(
|
||||
self,
|
||||
parent_path: str,
|
||||
include_hidden: bool = False,
|
||||
) -> list[str]:
|
||||
"""Names of immediate child mounts under parent_path.
|
||||
|
||||
Args:
|
||||
parent_path (str): directory whose child mounts to enumerate.
|
||||
include_hidden (bool): include names starting with '.'.
|
||||
"""
|
||||
stripped = parent_path.strip("/")
|
||||
norm = "/" + stripped + "/" if stripped else "/"
|
||||
seen: set[str] = set()
|
||||
out: list[str] = []
|
||||
for m in self._mounts:
|
||||
if m.prefix == norm:
|
||||
continue
|
||||
if not m.prefix.startswith(norm):
|
||||
continue
|
||||
rest = m.prefix[len(norm):]
|
||||
slash = rest.find("/")
|
||||
name = rest if slash == -1 else rest[:slash]
|
||||
if name == "":
|
||||
continue
|
||||
if not include_hidden and name.startswith("."):
|
||||
continue
|
||||
if name in seen:
|
||||
continue
|
||||
seen.add(name)
|
||||
out.append(name)
|
||||
out.sort()
|
||||
return out
|
||||
|
||||
def mount_for(self, path: str) -> MountEntry:
|
||||
"""Find the mount that handles this path."""
|
||||
norm = "/" + path.strip("/")
|
||||
for m in self._mounts:
|
||||
if (norm == m.prefix.rstrip("/") or norm.startswith(m.prefix)):
|
||||
return m
|
||||
raise ValueError(f"no mount matches path: {path!r}")
|
||||
|
||||
def is_exec_allowed(self) -> bool:
|
||||
for m in self._mounts:
|
||||
if m.prefix == DEV_PREFIX:
|
||||
continue
|
||||
if m.mode == MountMode.EXEC:
|
||||
return True
|
||||
return False
|
||||
|
||||
def mount_for_command(self, cmd_name: str) -> MountEntry | None:
|
||||
"""Find a mount that has this command registered.
|
||||
|
||||
Prefers the virtual root mount, then searches other mounts.
|
||||
"""
|
||||
if (self._root is not None
|
||||
and self._root.resolve_command(cmd_name) is not None):
|
||||
return self._root
|
||||
for m in self._mounts:
|
||||
if m.resolve_command(cmd_name) is not None:
|
||||
return m
|
||||
return None
|
||||
|
||||
async def resolve_mount(
|
||||
self,
|
||||
cmd_name: str,
|
||||
path_scopes: list[PathSpec],
|
||||
cwd: str,
|
||||
) -> MountEntry | None:
|
||||
"""Resolve which mount should handle a command.
|
||||
|
||||
Resolution order:
|
||||
1. First PathSpec path (or cwd) → mount_for(path)
|
||||
2. If mount lacks the command → mount_for_command(cmd_name)
|
||||
3. For a read-only command on a caching backend under ALWAYS
|
||||
consistency, evict stale entries from the hidden file cache so
|
||||
the in-place read-through serves fresh bytes. The command always
|
||||
stays on its real mount; the cache is never a mount.
|
||||
|
||||
Args:
|
||||
cmd_name (str): command name.
|
||||
path_scopes (list[PathSpec]): path arguments.
|
||||
cwd (str): current working directory.
|
||||
"""
|
||||
if path_scopes:
|
||||
mount_path = path_scopes[0].virtual
|
||||
else:
|
||||
mount_path = cwd
|
||||
|
||||
try:
|
||||
mount = self.mount_for(mount_path)
|
||||
except ValueError:
|
||||
mount = None
|
||||
|
||||
if mount is not None and mount.resolve_command(cmd_name) is None:
|
||||
if path_scopes:
|
||||
raise MountCommandUnsupported(cmd_name, mount.resource.name,
|
||||
path_scopes[0].raw_path)
|
||||
mount = self.mount_for_command(cmd_name)
|
||||
elif mount is None:
|
||||
mount = self.mount_for_command(cmd_name)
|
||||
|
||||
if mount is None:
|
||||
return None
|
||||
|
||||
resolved = mount.resolve_command(cmd_name)
|
||||
# Warm reads are served in place by with_read_cache, so a read-only
|
||||
# command stays on its real mount. The cache is a hidden store (not a
|
||||
# mount); under ALWAYS we evict stale entries from it here so the
|
||||
# read-through serves fresh bytes.
|
||||
if (self._file_cache is not None and path_scopes
|
||||
and resolved is not None and not resolved.write
|
||||
and mount.resource.caches_reads
|
||||
and self._consistency == ConsistencyPolicy.ALWAYS):
|
||||
await self._evict_stale(mount, self._file_cache, path_scopes)
|
||||
|
||||
return mount
|
||||
|
||||
async def _evict_stale(
|
||||
self,
|
||||
real_mount: MountEntry,
|
||||
cache: FileCacheMixin,
|
||||
path_scopes: list[PathSpec],
|
||||
) -> None:
|
||||
"""Evict cached entries whose remote fingerprint has changed.
|
||||
|
||||
Only used when ConsistencyPolicy.ALWAYS is active. Backends that
|
||||
return stat.fingerprint=None silently fall back to LAZY behavior
|
||||
(no eviction, cache serves whatever it has).
|
||||
"""
|
||||
for scope in path_scopes:
|
||||
key = scope.virtual
|
||||
if not await cache.exists(key):
|
||||
continue
|
||||
try:
|
||||
remote_stat = await real_mount.execute_op("stat", key)
|
||||
except FileNotFoundError:
|
||||
await cache.remove(key)
|
||||
continue
|
||||
except Exception:
|
||||
continue
|
||||
if remote_stat is None or remote_stat.fingerprint is None:
|
||||
continue
|
||||
if not await cache.is_fresh(key, remote_stat.fingerprint):
|
||||
await cache.remove(key)
|
||||
|
||||
@property
|
||||
def root_mount(self) -> MountEntry | None:
|
||||
return self._root
|
||||
|
||||
@property
|
||||
def file_cache(self) -> FileCacheMixin | None:
|
||||
return self._file_cache
|
||||
|
||||
def mounts(self) -> list[MountEntry]:
|
||||
return list(self._mounts)
|
||||
|
||||
def ops_mounts(self) -> list[OpsMount]:
|
||||
"""Build OpsMount list from registered mounts for Ops layer."""
|
||||
return [
|
||||
OpsMount(
|
||||
prefix=m.prefix,
|
||||
resource_type=m.resource.name,
|
||||
accessor=m.resource.accessor,
|
||||
index=m.resource.index,
|
||||
mode=m.mode,
|
||||
ops=m.resource.ops_list(),
|
||||
) for m in self._mounts
|
||||
]
|
||||
|
||||
def find_resource_by_name(
|
||||
self,
|
||||
resource_name: str | None,
|
||||
) -> BaseResource | None:
|
||||
"""Find a resource by its type name."""
|
||||
if resource_name is None:
|
||||
return None
|
||||
for mount in self._mounts:
|
||||
if mount.resource.name == resource_name:
|
||||
return mount.resource
|
||||
return None
|
||||
|
||||
def get_resource_type(
|
||||
self,
|
||||
path: str | None,
|
||||
) -> str | None:
|
||||
"""Get the resource type for a virtual path."""
|
||||
if path is None:
|
||||
return None
|
||||
try:
|
||||
resource, _, _ = self.resolve(path)
|
||||
return resource.name
|
||||
except (ValueError, KeyError):
|
||||
return None
|
||||
|
||||
def group_by_mount(
|
||||
self,
|
||||
paths: list[str],
|
||||
) -> list[tuple[MountEntry, list[str]]]:
|
||||
"""Group virtual paths by their mount.
|
||||
|
||||
Returns list of (mount, resource_paths).
|
||||
"""
|
||||
groups: dict[int, tuple[MountEntry, list[str]]] = {}
|
||||
for path in paths:
|
||||
mount = self.mount_for(path)
|
||||
_, resource_path, _ = self.resolve(path)
|
||||
key = id(mount)
|
||||
if key not in groups:
|
||||
groups[key] = (mount, [])
|
||||
groups[key][1].append(resource_path)
|
||||
return list(groups.values())
|
||||
@@ -0,0 +1,28 @@
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
# ========= Copyright 2026 @ Strukto.AI All Rights Reserved. =========
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from mirage.commands.safeguard import CommandSafeguard
|
||||
from mirage.resource.base import BaseResource
|
||||
from mirage.types import MountMode
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Mount:
|
||||
resource: BaseResource
|
||||
mode: MountMode | None = None
|
||||
fuse: bool | str = False
|
||||
command_safeguards: dict[str,
|
||||
CommandSafeguard] = field(default_factory=dict)
|
||||
Reference in New Issue
Block a user