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