ReMe/reme/steps/index/init_changes.py
jinliyl 54fa3381d7
Some checks failed
CI and Release / Docker / Build and test / amd64 (push) Has been cancelled
CI and Release / Docker / Build and test / arm64 (push) Has been cancelled
Security / CodeQL / Analyze python (push) Has been cancelled
CI / Python quality / Pre-commit (push) Has been cancelled
CI / Python tests / Unit Tests - py3.12 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.13 (push) Has been cancelled
CI / Python tests / Unit Tests - py3.14 (push) Has been cancelled
CI / Python packages / Build and verify distributions (push) Has been cancelled
CI / Python quality / GitHub Actions (push) Has been cancelled
CI / Python tests / Hermes embedded - ubuntu-latest (push) Has been cancelled
CI / Python tests / Hermes embedded - windows-latest (push) Has been cancelled
CI / Python tests / Unit Tests - py3.11 (push) Has been cancelled
CI / ReMe Studio / Studio checks (push) Has been cancelled
Deploy / Documentation / Build documentation (push) Has been cancelled
CI / Windows / CLI smoke - py3.11 (push) Has been cancelled
Security / CodeQL / Analyze javascript-typescript (push) Has been cancelled
CI and Release / Docker / Publish multi-platform tags (push) Has been cancelled
Deploy / Documentation / deploy (push) Has been cancelled
refactor(core): reorganize the ReMe runtime and shared helpers (#769)
* refactor(core): reorganize the ReMe runtime and shared helpers

* test(status): import the base component from its canonical module

* test: remove redundant unit checks

* refactor(core): use canonical runtime imports and shared CLI discovery

Restore evolve behavior to the base branch and update its imports. Use Application as the runtime entry point and encode SSE in the HTTP service.

* fix(cli): honor caller config when service replay is incomplete

Use partial startup overrides for port probes and resolve named configs before requesting the service process working directory.
2026-11-20 22:06:46 +08:00

82 lines
3.4 KiB
Python

"""One-shot change producer: diff watched files against file_store/file_catalog."""
from pathlib import Path
from typing import Iterable
from ._change_batch import coalesce_changes
from ._watch_rules import build_context_watch_rules
from ..base_step import BaseStep
from ...core.registry import R
from ...schema import FileNode
from ...utils.files.file_watch import WatchRule, collect_existing, diff_files
@R.register("init_changes_step")
class InitChangesStep(BaseStep):
"""Scan once, write ``context["changes"]``, then dispatch change handlers."""
def __init__(
self,
monitor_type: str | None = None,
monitor_name: str = "default",
store: str | None = None,
recursive: bool = True,
**kwargs,
):
super().__init__(**kwargs)
self.monitor_type = monitor_type or store
self.monitor_name = monitor_name
self.recursive = recursive
if self.monitor_type in {"file_store", "file_catalog"}:
self.kwargs.setdefault(self.monitor_type, monitor_name)
def _get_watch_rules(self) -> list[WatchRule]:
assert self.context is not None
app_config = self.app_context.app_config if self.app_context else None
return build_context_watch_rules(app_config, self.workspace_path, self.context, self.file_catalog)
async def _load_indexed_nodes(self) -> Iterable[FileNode]:
if self.monitor_type == "file_store":
return await self.file_store.get_nodes()
if self.monitor_type == "file_catalog":
if self.file_catalog is None:
raise RuntimeError("file_catalog is not initialized!")
return await self.file_catalog.get_nodes()
raise ValueError("init_changes_step.monitor_type must be 'file_store' or 'file_catalog'")
@staticmethod
def diff(existing: dict[str, float], nodes: Iterable[FileNode], workspace_path: Path) -> tuple[
list[dict],
dict[str, int],
]:
"""Compute added/modified/deleted vs ``nodes`` and return (changes, counts)."""
indexed: dict[str, float] = {
str(Path(n.path) if Path(n.path).is_absolute() else workspace_path / n.path): n.st_mtime for n in nodes
}
return diff_files(existing, indexed)
async def execute(self):
assert self.context is not None
rules = self._get_watch_rules()
existing = collect_existing(rules, recursive=self.recursive)
nodes = await self._load_indexed_nodes()
changes, counts = self.diff(existing, nodes, self.workspace_path)
changes = coalesce_changes(changes)
self.context["changes"] = changes
if changes:
self.logger.info(f"[{self.name}] scan {self.monitor_type}:{self.monitor_name}: {counts}")
retry_key = "retry_source_changes_before_watch"
had_retry_value = retry_key in self.context
previous_retry_value = self.context.get(retry_key)
self.context[retry_key] = True
try:
await self.dispatch_steps(self.dispatch_step_specs, changes=changes)
finally:
if had_retry_value:
self.context[retry_key] = previous_retry_value
else:
del self.context[retry_key]
else:
self.logger.info(f"[{self.name}] {self.monitor_type}:{self.monitor_name} is up to date")
self.context.response.metadata["counts"] = counts
return self.context.response