Download cases/filesystem/raw/mcp_servers/state/database.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 7.6 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/filesystem/raw/mcp_servers/state/database.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/filesystem/raw/mcp_servers/state/database.py
-
curl -L -o database.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/filesystem/raw/mcp_servers/state/database.py
7.6 kB
| """Generic JSON file-backed database for isolated runtime state.""" | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import shutil | |
| from typing import Any, Callable, Dict, List, Optional | |
| from mcp_servers.utils import extract_id_sequence, generate_id, safe_copy | |
| ID_FIELDS = { | |
| "workspace": "workspace_id", | |
| "user": "user_id", | |
| "team": "team_id", | |
| "node": "node_id", | |
| "file_content": "content_id", | |
| "operation": "operation_id", | |
| "snapshot": "snapshot_id", | |
| "manifest": "manifest_id", | |
| } | |
| class Database: | |
| def __init__(self, db_dir: str) -> None: | |
| self.db_dir = os.path.abspath(db_dir) | |
| self._data: Dict[str, List[Dict[str, Any]]] = {} | |
| self._id_counters: Dict[str, int] = {} | |
| def copy_database(src_dir: str, dst_dir: str) -> None: | |
| if os.path.isdir(dst_dir): | |
| shutil.rmtree(dst_dir) | |
| if os.path.isdir(src_dir): | |
| shutil.copytree(src_dir, dst_dir) | |
| else: | |
| os.makedirs(dst_dir, exist_ok=True) | |
| def _file(self, entity_type: str) -> str: | |
| return os.path.join(self.db_dir, f"{entity_type}s.json") | |
| def _pk_field(self, entity_type: str) -> str: | |
| return ID_FIELDS.get(entity_type, f"{entity_type}_id") | |
| def _ensure_loaded(self, entity_type: str) -> None: | |
| if entity_type in self._data: | |
| return | |
| path = self._file(entity_type) | |
| if os.path.exists(path): | |
| with open(path, "r", encoding="utf-8") as handle: | |
| raw = json.load(handle) | |
| self._data[entity_type] = raw if isinstance(raw, list) else [] | |
| else: | |
| self._data[entity_type] = [] | |
| pk_field = self._pk_field(entity_type) | |
| max_seq = 0 | |
| for record in self._data[entity_type]: | |
| seq = extract_id_sequence(record.get(pk_field) or record.get("id"), entity_type) | |
| if seq is not None: | |
| max_seq = max(max_seq, seq) | |
| self._id_counters.setdefault(entity_type, max_seq) | |
| def _flush(self, entity_type: str) -> None: | |
| os.makedirs(self.db_dir, exist_ok=True) | |
| path = self._file(entity_type) | |
| tmp_path = path + ".tmp" | |
| with open(tmp_path, "w", encoding="utf-8") as handle: | |
| json.dump(self._data.get(entity_type, []), handle, indent=2, ensure_ascii=False) | |
| os.replace(tmp_path, path) | |
| def _ref(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]: | |
| self._ensure_loaded(entity_type) | |
| pk_field = self._pk_field(entity_type) | |
| for record in self._data[entity_type]: | |
| if record.get(pk_field) == entity_id or record.get("id") == entity_id: | |
| return record | |
| return None | |
| def next_id(self, entity_type: str) -> str: | |
| self._ensure_loaded(entity_type) | |
| self._id_counters[entity_type] = self._id_counters.get(entity_type, 0) + 1 | |
| return generate_id(entity_type, self._id_counters[entity_type]) | |
| def get_all(self, entity_type: str) -> List[Dict[str, Any]]: | |
| self._ensure_loaded(entity_type) | |
| return safe_copy(self._data[entity_type]) | |
| def get_by_id(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]: | |
| ref = self._ref(entity_type, entity_id) | |
| return safe_copy(ref) if ref is not None else None | |
| def get_ref(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]: | |
| return self._ref(entity_type, entity_id) | |
| def get_one(self, entity_type: str, id_field: str, entity_id: str) -> Optional[Dict[str, Any]]: | |
| self._ensure_loaded(entity_type) | |
| for record in self._data[entity_type]: | |
| if record.get(id_field) == entity_id: | |
| return safe_copy(record) | |
| return None | |
| def query(self, entity_type: str, predicate: Callable[[Dict[str, Any]], bool]) -> List[Dict[str, Any]]: | |
| self._ensure_loaded(entity_type) | |
| return safe_copy([record for record in self._data[entity_type] if predicate(record)]) | |
| def insert(self, entity_type: str, record: Dict[str, Any]) -> Dict[str, Any]: | |
| self._ensure_loaded(entity_type) | |
| stored = safe_copy(record) | |
| self._data[entity_type].append(stored) | |
| self._flush(entity_type) | |
| return safe_copy(stored) | |
| def upsert(self, entity_type: str, arg1: Any, arg2: Any = None) -> Dict[str, Any]: | |
| self._ensure_loaded(entity_type) | |
| if isinstance(arg1, dict): | |
| record = safe_copy(arg1) | |
| id_field = str(arg2 or self._pk_field(entity_type)) | |
| entity_id = record.get(id_field) or record.get(self._pk_field(entity_type)) or record.get("id") | |
| else: | |
| entity_id = str(arg1) | |
| record = safe_copy(arg2 if isinstance(arg2, dict) else {}) | |
| id_field = self._pk_field(entity_type) | |
| if not entity_id: | |
| entity_id = self.next_id(entity_type) | |
| record[id_field] = entity_id | |
| pk_field = self._pk_field(entity_type) | |
| if pk_field not in record and id_field != pk_field: | |
| record[pk_field] = entity_id | |
| for index, current in enumerate(self._data[entity_type]): | |
| if current.get(id_field) == entity_id or current.get(pk_field) == entity_id or current.get("id") == entity_id: | |
| merged = safe_copy(current) | |
| merged.update(record) | |
| self._data[entity_type][index] = merged | |
| self._flush(entity_type) | |
| return safe_copy(merged) | |
| self._data[entity_type].append(record) | |
| self._flush(entity_type) | |
| return safe_copy(record) | |
| def update(self, entity_type: str, entity_id: str, updates: Dict[str, Any]) -> Optional[Dict[str, Any]]: | |
| ref = self._ref(entity_type, entity_id) | |
| if ref is None: | |
| return None | |
| ref.update(updates) | |
| self._flush(entity_type) | |
| return safe_copy(ref) | |
| def delete(self, entity_type: str, arg1: Any, arg2: Any = None) -> bool: | |
| self._ensure_loaded(entity_type) | |
| if arg2 is None: | |
| id_field = self._pk_field(entity_type) | |
| entity_id = str(arg1) | |
| else: | |
| id_field = str(arg1) | |
| entity_id = str(arg2) | |
| before = len(self._data[entity_type]) | |
| self._data[entity_type] = [record for record in self._data[entity_type] if record.get(id_field) != entity_id] | |
| if len(self._data[entity_type]) != before: | |
| self._flush(entity_type) | |
| return True | |
| return False | |
| def delete_many(self, entity_type: str, predicate: Callable[[Dict[str, Any]], bool]) -> int: | |
| self._ensure_loaded(entity_type) | |
| before = len(self._data[entity_type]) | |
| self._data[entity_type] = [record for record in self._data[entity_type] if not predicate(record)] | |
| removed = before - len(self._data[entity_type]) | |
| if removed: | |
| self._flush(entity_type) | |
| return removed | |
| def save_entity(self, entity_type: str) -> None: | |
| self._ensure_loaded(entity_type) | |
| self._flush(entity_type) | |
| def snapshot(self) -> Dict[str, List[Dict[str, Any]]]: | |
| if os.path.isdir(self.db_dir): | |
| for name in sorted(os.listdir(self.db_dir)): | |
| if not name.endswith(".json"): | |
| continue | |
| entity_type = name[:-5] | |
| if entity_type.endswith("s"): | |
| entity_type = entity_type[:-1] | |
| self._ensure_loaded(entity_type) | |
| return safe_copy(self._data) | |
| def reset(self) -> None: | |
| self._data.clear() | |
| self._id_counters.clear() | |