JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
7.75 kB
"""JSON file-backed database for isolated ticketing runtime data."""
from __future__ import annotations
import json
import os
from typing import Any, Callable, Dict, List, Optional
from mcp_servers.utils import generate_id, safe_copy
ENTITY_FILES = {
"operator": ("operators.json", "operator_id"),
"venue": ("venues.json", "venue_id"),
"venue_section": ("venue_sections.json", "venue_section_id"),
"seat": ("seats.json", "seat_id"),
"event": ("events.json", "event_id"),
"performance": ("performances.json", "performance_id"),
"price_tier": ("price_tiers.json", "price_tier_id"),
"ticket_type": ("ticket_types.json", "ticket_type_id"),
"discount_campaign": ("discount_campaigns.json", "discount_campaign_id"),
"customer": ("customers.json", "customer_id"),
"order": ("orders.json", "order_id"),
"order_line": ("order_lines.json", "order_line_id"),
"ticket": ("tickets.json", "ticket_id"),
"refund_request": ("refund_requests.json", "refund_request_id"),
"checkpoint": ("checkpoints.json", "checkpoint_id"),
"entry_scan": ("entry_scans.json", "entry_scan_id"),
"inventory_hold": ("inventory_holds.json", "inventory_hold_id"),
"entry_summary": ("entry_summaries.json", "entry_summary_id"),
"audit_log": ("audit_logs.json", "audit_log_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 _info(self, entity_type: str) -> tuple[str, str]:
return ENTITY_FILES.get(entity_type, (f"{entity_type}s.json", f"{entity_type}_id"))
def _file(self, entity_type: str) -> str:
return os.path.join(self.db_dir, self._info(entity_type)[0])
def _pk_field(self, entity_type: str) -> str:
return self._info(entity_type)[1]
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:
rows = json.load(handle)
self._data[entity_type] = rows if isinstance(rows, list) else []
else:
self._data[entity_type] = []
self._id_counters.setdefault(entity_type, len(self._data[entity_type]))
def _flush(self, entity_type: str) -> None:
os.makedirs(self.db_dir, exist_ok=True)
path = self._file(entity_type)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as handle:
json.dump(self._data.get(entity_type, []), handle, indent=2, ensure_ascii=False)
try:
os.unlink(path)
except FileNotFoundError:
pass
os.replace(tmp, path)
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_ref(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]:
self._ensure_loaded(entity_type)
pk = self._pk_field(entity_type)
for row in self._data[entity_type]:
if row.get(pk) == entity_id or row.get("id") == entity_id:
return row
return None
def get_by_id(self, entity_type: str, entity_id: str) -> Optional[Dict[str, Any]]:
ref = self.get_ref(entity_type, entity_id)
return safe_copy(ref) if ref is not None else None
def get_one(self, entity_type: str, id_field: str, entity_id: str) -> Optional[Dict[str, Any]]:
self._ensure_loaded(entity_type)
pk = self._pk_field(entity_type)
if id_field in {"id", pk}:
return self.get_by_id(entity_type, entity_id)
for row in self._data[entity_type]:
if row.get(id_field) == entity_id:
return safe_copy(row)
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([row for row in self._data[entity_type] if predicate(row)])
def add(self, entity_type: str, record: Dict[str, Any]) -> Dict[str, Any]:
self._ensure_loaded(entity_type)
stored = safe_copy(record)
pk = self._pk_field(entity_type)
if not stored.get(pk):
self._id_counters[entity_type] = self._id_counters.get(entity_type, 0) + 1
stored[pk] = generate_id(entity_type, self._id_counters[entity_type])
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]:
if isinstance(arg1, dict):
record = safe_copy(arg1)
id_field = arg2 if isinstance(arg2, str) and arg2 else self._pk_field(entity_type)
entity_id = str(record.get(id_field) or record.get(self._pk_field(entity_type)) or record.get("id") or "")
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:
return self.add(entity_type, record)
self._ensure_loaded(entity_type)
pk = self._pk_field(entity_type)
for row in self._data[entity_type]:
if row.get(pk) == entity_id or row.get(id_field) == entity_id or row.get("id") == entity_id:
row.update(record)
if pk not in row:
row[pk] = entity_id
self._flush(entity_type)
return safe_copy(row)
if pk not in record:
record[pk] = entity_id
self._data[entity_type].append(record)
self._flush(entity_type)
return safe_copy(record)
def update(self, entity_type: str, entity_id: str, patch: Dict[str, Any]) -> Optional[Dict[str, Any]]:
self._ensure_loaded(entity_type)
pk = self._pk_field(entity_type)
for row in self._data[entity_type]:
if row.get(pk) == entity_id or row.get("id") == entity_id:
row.update(safe_copy(patch))
self._flush(entity_type)
return safe_copy(row)
return None
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)
value = str(arg1)
else:
id_field = str(arg1)
value = str(arg2)
before = len(self._data[entity_type])
self._data[entity_type] = [row for row in self._data[entity_type] if str(row.get(id_field) or row.get(self._pk_field(entity_type)) or row.get("id")) != value]
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] = [row for row in self._data[entity_type] if not predicate(row)]
removed = before - len(self._data[entity_type])
if removed:
self._flush(entity_type)
return removed
def snapshot(self, *, loaded_only: bool = True) -> Dict[str, List[Dict[str, Any]]]:
if not loaded_only:
for entity_type in ENTITY_FILES:
self._ensure_loaded(entity_type)
return safe_copy(self._data)
def reset(self) -> None:
self._data.clear()
self._id_counters.clear()