|
| 1 | +"""File system-based execution store implementation.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import contextlib |
| 6 | +import json |
| 7 | +import logging |
| 8 | +import threading |
| 9 | +from datetime import UTC, datetime |
| 10 | +from pathlib import Path |
| 11 | +from typing import TYPE_CHECKING |
| 12 | + |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + from aws_durable_execution_sdk_python_testing.execution import Execution |
| 16 | + |
| 17 | + |
| 18 | +class DateTimeEncoder(json.JSONEncoder): |
| 19 | + """Custom JSON encoder that handles datetime objects.""" |
| 20 | + |
| 21 | + def default(self, obj): |
| 22 | + if isinstance(obj, datetime): |
| 23 | + return obj.timestamp() |
| 24 | + return super().default(obj) |
| 25 | + |
| 26 | + |
| 27 | +def datetime_object_hook(obj): |
| 28 | + """JSON object hook to convert unix timestamps back to datetime objects.""" |
| 29 | + if isinstance(obj, dict): |
| 30 | + for key, value in obj.items(): |
| 31 | + if isinstance(value, int | float) and key.endswith(("_timestamp", "_time")): |
| 32 | + with contextlib.suppress(ValueError, OSError): |
| 33 | + obj[key] = datetime.fromtimestamp(value, tz=UTC) |
| 34 | + return obj |
| 35 | + |
| 36 | + |
| 37 | +class FileSystemExecutionStore: |
| 38 | + """File system-based execution store for persistence.""" |
| 39 | + |
| 40 | + def __init__(self, storage_dir: str | Path = ".durable_executions") -> None: |
| 41 | + self._storage_dir = Path(storage_dir) |
| 42 | + self._storage_dir.mkdir(exist_ok=True) |
| 43 | + self._lock = threading.RLock() |
| 44 | + |
| 45 | + def _get_file_path(self, execution_arn: str) -> Path: |
| 46 | + """Get file path for execution ARN.""" |
| 47 | + # Use ARN as filename with .json extension, replacing unsafe characters |
| 48 | + safe_filename = execution_arn.replace(":", "_").replace("/", "_") |
| 49 | + return self._storage_dir / f"{safe_filename}.json" |
| 50 | + |
| 51 | + def save(self, execution: Execution) -> None: |
| 52 | + """Save execution to file system.""" |
| 53 | + with self._lock: |
| 54 | + file_path = self._get_file_path(execution.durable_execution_arn) |
| 55 | + data = execution.to_dict() |
| 56 | + |
| 57 | + # Write atomically using temporary file |
| 58 | + temp_path = file_path.with_suffix(".tmp") |
| 59 | + try: |
| 60 | + with open(temp_path, "w", encoding="utf-8") as f: |
| 61 | + json.dump(data, f, indent=2, cls=DateTimeEncoder) |
| 62 | + temp_path.replace(file_path) |
| 63 | + except Exception: |
| 64 | + if temp_path.exists(): |
| 65 | + temp_path.unlink() |
| 66 | + raise |
| 67 | + |
| 68 | + def load(self, execution_arn: str) -> Execution: |
| 69 | + """Load execution from file system.""" |
| 70 | + from aws_durable_execution_sdk_python_testing.execution import Execution |
| 71 | + |
| 72 | + with self._lock: |
| 73 | + file_path = self._get_file_path(execution_arn) |
| 74 | + if not file_path.exists(): |
| 75 | + msg = f"Execution {execution_arn} not found" |
| 76 | + raise KeyError(msg) |
| 77 | + |
| 78 | + with open(file_path, encoding="utf-8") as f: |
| 79 | + data = json.load(f, object_hook=datetime_object_hook) |
| 80 | + |
| 81 | + return Execution.from_dict(data) |
| 82 | + |
| 83 | + def update(self, execution: Execution) -> None: |
| 84 | + """Update execution in file system (same as save).""" |
| 85 | + self.save(execution) |
| 86 | + |
| 87 | + def list_all(self) -> list[Execution]: |
| 88 | + """List all executions from file system.""" |
| 89 | + from aws_durable_execution_sdk_python_testing.execution import Execution |
| 90 | + |
| 91 | + with self._lock: |
| 92 | + executions = [] |
| 93 | + for file_path in self._storage_dir.glob("*.json"): |
| 94 | + try: |
| 95 | + with open(file_path, encoding="utf-8") as f: |
| 96 | + data = json.load(f, object_hook=datetime_object_hook) |
| 97 | + executions.append(Execution.from_dict(data)) |
| 98 | + except (json.JSONDecodeError, KeyError, OSError) as e: |
| 99 | + logging.warning("Skipping corrupted file %s: %s", file_path, e) |
| 100 | + continue |
| 101 | + return executions |
0 commit comments