askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_versions.py · 6.7 KB · 205 lines
| 1 | """Object source version storage. |
| 2 | |
| 3 | This keeps the versioning contract from the working prototype: |
| 4 | |
| 5 | - data/versions/{object_id}/metadata.tsv |
| 6 | - data/versions/{object_id}/v1.txt |
| 7 | - data/versions/{object_id}/v2.txt |
| 8 | |
| 9 | Rollback is non-destructive. It creates a new version containing the older |
| 10 | content, preserving the full history. |
| 11 | """ |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import csv |
| 15 | import hashlib |
| 16 | from datetime import datetime |
| 17 | from pathlib import Path |
| 18 | from typing import Any |
| 19 | |
| 20 | from object_namespace import validate_object_id |
| 21 | |
| 22 | |
| 23 | DEFAULT_DATA_DIR = "data" |
| 24 | METADATA_FILE = "metadata.tsv" |
| 25 | BASE_METADATA_FIELDS = ["version_id", "timestamp", "author", "message", "hash"] |
| 26 | METADATA_FIELDS = [*BASE_METADATA_FIELDS, "correlation_id"] |
| 27 | |
| 28 | |
| 29 | class VersionError(Exception): |
| 30 | """Base exception for version-related errors.""" |
| 31 | |
| 32 | |
| 33 | class InvalidObjectIdError(VersionError): |
| 34 | """Raised when an object ID is not safe for version storage.""" |
| 35 | |
| 36 | |
| 37 | class VersionNotFoundError(VersionError): |
| 38 | """Raised when a requested version does not exist.""" |
| 39 | |
| 40 | |
| 41 | class VersionManager: |
| 42 | """Manage per-object source versions stored as TSV metadata and text files.""" |
| 43 | |
| 44 | def __init__(self, base_dir: Path | str = DEFAULT_DATA_DIR): |
| 45 | self.base_dir = Path(base_dir) |
| 46 | self.versions_dir = self.base_dir / "versions" |
| 47 | self.versions_dir.mkdir(parents=True, exist_ok=True) |
| 48 | |
| 49 | def save_version( |
| 50 | self, |
| 51 | object_id: str, |
| 52 | content: str, |
| 53 | author: str, |
| 54 | message: str, |
| 55 | correlation_id: str | None = None, |
| 56 | ) -> int: |
| 57 | """Save a new version and return its integer version ID.""" |
| 58 | obj_dir = self._object_dir(object_id, create=True) |
| 59 | version_id = self._get_next_version_id(object_id) |
| 60 | content_hash = self._compute_hash(content) |
| 61 | timestamp = datetime.now().isoformat() |
| 62 | |
| 63 | content_file = obj_dir / f"v{version_id}.txt" |
| 64 | content_file.write_text(content) |
| 65 | |
| 66 | metadata_file = obj_dir / METADATA_FILE |
| 67 | is_new_file = not metadata_file.exists() |
| 68 | with metadata_file.open("a", newline="") as f: |
| 69 | writer = csv.DictWriter(f, fieldnames=METADATA_FIELDS, delimiter="\t") |
| 70 | if is_new_file: |
| 71 | writer.writeheader() |
| 72 | writer.writerow( |
| 73 | { |
| 74 | "version_id": version_id, |
| 75 | "timestamp": timestamp, |
| 76 | "author": author, |
| 77 | "message": message, |
| 78 | "hash": content_hash, |
| 79 | "correlation_id": correlation_id or "", |
| 80 | } |
| 81 | ) |
| 82 | |
| 83 | return version_id |
| 84 | |
| 85 | def get_version(self, object_id: str, version_id: int | None = None) -> dict[str, Any] | None: |
| 86 | """Get one version with content. `version_id=None` returns the latest.""" |
| 87 | versions = self._read_metadata(object_id) |
| 88 | if not versions: |
| 89 | return None |
| 90 | |
| 91 | if version_id is None: |
| 92 | target_version = versions[-1] |
| 93 | else: |
| 94 | target_version = next((v for v in versions if v["version_id"] == version_id), None) |
| 95 | if target_version is None: |
| 96 | return None |
| 97 | |
| 98 | content_file = self._object_dir(object_id) / f"v{target_version['version_id']}.txt" |
| 99 | if not content_file.exists() or not content_file.is_file(): |
| 100 | return None |
| 101 | |
| 102 | return { |
| 103 | **target_version, |
| 104 | "content": content_file.read_text(), |
| 105 | } |
| 106 | |
| 107 | def get_history( |
| 108 | self, |
| 109 | object_id: str, |
| 110 | limit: int | None = None, |
| 111 | offset: int = 0, |
| 112 | ) -> list[dict[str, Any]]: |
| 113 | """Return metadata history, newest first, without version content.""" |
| 114 | versions = list(reversed(self._read_metadata(object_id))) |
| 115 | |
| 116 | if offset > 0: |
| 117 | versions = versions[offset:] |
| 118 | |
| 119 | if limit is not None: |
| 120 | versions = versions[:limit] |
| 121 | |
| 122 | return versions |
| 123 | |
| 124 | def rollback( |
| 125 | self, |
| 126 | object_id: str, |
| 127 | to_version: int, |
| 128 | author: str, |
| 129 | message: str, |
| 130 | correlation_id: str | None = None, |
| 131 | ) -> int: |
| 132 | """Create a new version containing content from an older version.""" |
| 133 | old_version = self.get_version(object_id, to_version) |
| 134 | if old_version is None: |
| 135 | raise VersionNotFoundError(f"Version {to_version} not found for object {object_id}") |
| 136 | |
| 137 | return self.save_version( |
| 138 | object_id=object_id, |
| 139 | content=old_version["content"], |
| 140 | author=author, |
| 141 | message=message, |
| 142 | correlation_id=correlation_id, |
| 143 | ) |
| 144 | |
| 145 | def _object_dir(self, object_id: str, *, create: bool = False) -> Path: |
| 146 | if not validate_object_id(object_id): |
| 147 | raise InvalidObjectIdError(f"Invalid object ID: {object_id}") |
| 148 | |
| 149 | obj_dir = self.versions_dir / object_id |
| 150 | versions_root = self.versions_dir.resolve(strict=False) |
| 151 | resolved_obj_dir = obj_dir.resolve(strict=False) |
| 152 | |
| 153 | try: |
| 154 | resolved_obj_dir.relative_to(versions_root) |
| 155 | except ValueError as exc: |
| 156 | raise InvalidObjectIdError(f"Object ID escapes versions directory: {object_id}") from exc |
| 157 | |
| 158 | if create: |
| 159 | obj_dir.mkdir(parents=True, exist_ok=True) |
| 160 | return obj_dir |
| 161 | |
| 162 | def _read_metadata(self, object_id: str) -> list[dict[str, Any]]: |
| 163 | metadata_file = self._object_dir(object_id) / METADATA_FILE |
| 164 | if not metadata_file.exists() or not metadata_file.is_file(): |
| 165 | return [] |
| 166 | |
| 167 | versions: list[dict[str, Any]] = [] |
| 168 | with metadata_file.open("r", newline="") as f: |
| 169 | reader = csv.DictReader(f, delimiter="\t") |
| 170 | for row in reader: |
| 171 | normalized = self._normalize_metadata_row(row) |
| 172 | if normalized is not None: |
| 173 | versions.append(normalized) |
| 174 | |
| 175 | return versions |
| 176 | |
| 177 | def _normalize_metadata_row(self, row: dict[str, str | None]) -> dict[str, Any] | None: |
| 178 | if any(row.get(field) is None for field in BASE_METADATA_FIELDS): |
| 179 | return None |
| 180 | |
| 181 | try: |
| 182 | version_id = int(row["version_id"] or "") |
| 183 | except ValueError: |
| 184 | return None |
| 185 | |
| 186 | normalized = { |
| 187 | "version_id": version_id, |
| 188 | "timestamp": row["timestamp"] or "", |
| 189 | "author": row["author"] or "", |
| 190 | "message": row["message"] or "", |
| 191 | "hash": row["hash"] or "", |
| 192 | } |
| 193 | correlation_id = row.get("correlation_id") or "" |
| 194 | if correlation_id: |
| 195 | normalized["correlation_id"] = correlation_id |
| 196 | return normalized |
| 197 | |
| 198 | def _get_next_version_id(self, object_id: str) -> int: |
| 199 | versions = self._read_metadata(object_id) |
| 200 | if not versions: |
| 201 | return 1 |
| 202 | return max(version["version_id"] for version in versions) + 1 |
| 203 | |
| 204 | def _compute_hash(self, content: str) -> str: |
| 205 | return hashlib.sha256(content.encode()).hexdigest() |