fix: persist runtime memory across Docker restarts #3
@@ -22,12 +22,7 @@ class MemoryItem:
|
||||
|
||||
|
||||
class GlobalMemory:
|
||||
"""Persistent global memory store shared across all forum topics.
|
||||
|
||||
The target file is replaced only after a complete JSON document has been
|
||||
written and flushed. This prevents a restart during a write from leaving
|
||||
a truncated ``global_memory.json``.
|
||||
"""
|
||||
"""Persistent global memory store shared across all forum topics."""
|
||||
|
||||
def __init__(self, storage_path: Path):
|
||||
self.storage_path = Path(storage_path).expanduser().resolve()
|
||||
@@ -40,6 +35,8 @@ class GlobalMemory:
|
||||
try:
|
||||
with self.storage_path.open("r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if not isinstance(data, list):
|
||||
raise ValueError("memory file must contain a JSON list")
|
||||
for item_data in data:
|
||||
item = MemoryItem(**item_data)
|
||||
self._items[item.id] = item
|
||||
@@ -49,15 +46,9 @@ class GlobalMemory:
|
||||
|
||||
def _save(self) -> None:
|
||||
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = json.dumps(
|
||||
[asdict(item) for item in self._items.values()],
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
payload = json.dumps([asdict(item) for item in self._items.values()], ensure_ascii=False, indent=2)
|
||||
fd, temporary_path = tempfile.mkstemp(
|
||||
prefix=f".{self.storage_path.name}.",
|
||||
suffix=".tmp",
|
||||
dir=self.storage_path.parent,
|
||||
prefix=f".{self.storage_path.name}.", suffix=".tmp", dir=self.storage_path.parent
|
||||
)
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
@@ -73,11 +64,10 @@ class GlobalMemory:
|
||||
raise
|
||||
|
||||
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
||||
item_id = str(uuid.uuid4())[:8]
|
||||
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
||||
self._items[item_id] = item
|
||||
item = MemoryItem(id=str(uuid.uuid4())[:8], fact=fact.strip(), category=category.strip().lower())
|
||||
self._items[item.id] = item
|
||||
self._save()
|
||||
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
|
||||
logger.info("Added fact [%s] in category '%s': %s", item.id, item.category, item.fact)
|
||||
return item
|
||||
|
||||
def remove_fact(self, fact_id: str) -> bool:
|
||||
@@ -95,10 +85,7 @@ class GlobalMemory:
|
||||
|
||||
def search(self, query: str) -> list[MemoryItem]:
|
||||
q = query.lower()
|
||||
return [
|
||||
item for item in self._items.values()
|
||||
if q in item.fact.lower() or q in item.category.lower()
|
||||
]
|
||||
return [item for item in self._items.values() if q in item.fact.lower() or q in item.category.lower()]
|
||||
|
||||
def clear(self) -> None:
|
||||
self._items.clear()
|
||||
@@ -113,13 +100,18 @@ class GlobalMemory:
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
_global_memory_instance: Optional[GlobalMemory] = None
|
||||
_global_memory_instances: dict[Path, GlobalMemory] = {}
|
||||
|
||||
|
||||
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
||||
global _global_memory_instance
|
||||
if _global_memory_instance is None:
|
||||
"""Get the memory store keyed by its absolute path.
|
||||
|
||||
DATA_DIR is used in Docker and keeps this store aligned with the mounted
|
||||
application directory even when the process working directory changes.
|
||||
"""
|
||||
if storage_path is None:
|
||||
storage_path = Path("data") / "global_memory.json"
|
||||
_global_memory_instance = GlobalMemory(storage_path)
|
||||
return _global_memory_instance
|
||||
storage_path = Path(os.environ.get("DATA_DIR", "data")) / "global_memory.json"
|
||||
path = Path(storage_path).expanduser().resolve()
|
||||
if path not in _global_memory_instances:
|
||||
_global_memory_instances[path] = GlobalMemory(path)
|
||||
return _global_memory_instances[path]
|
||||
Reference in new issue
Block a user