File size: 7,603 Bytes
f726fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""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] = {}

    @staticmethod
    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()