Python functions as REST objects, with clustering, load balancing and state replication; no containers or orchestration.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-primitive.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-primitive.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Q Consolidate duplicate QUICKSTARTs on the top-level file 503f830 7 months ago History
version_manager.py · 7.8 KB · 289 lines
1"""
2Version Manager
3
4Manages versions of objects (endpoints, data, code).
5
6Every change is versioned:
7- Before modification, save current version
8- Store metadata in TSV (timestamp, author, message, hash)
9- Store content in separate file (v1.txt, v2.txt, etc.)
10- Can retrieve any historical version
11- Can rollback to previous version
12
13Design:
14- versions/{object_id}/metadata.tsv - Version metadata
15- versions/{object_id}/v1.txt - Version 1 content
16- versions/{object_id}/v2.txt - Version 2 content
17- etc.
18"""
19
20import hashlib
21from pathlib import Path
22from datetime import datetime
23from typing import Optional, List, Dict, Any
24import csv
25
26
27class VersionError(Exception):
28 """Base exception for version-related errors"""
29 pass
30
31
32class VersionNotFoundError(VersionError):
33 """Raised when version doesn't exist"""
34 pass
35
36
37class VersionManager:
38 """
39 Manages versions of objects.
40
41 Each object has its own version history stored in:
42 - versions/{object_id}/metadata.tsv
43 - versions/{object_id}/v{N}.txt
44 """
45
46 def __init__(self, base_dir: Path | str):
47 """
48 Initialize version manager.
49
50 Args:
51 base_dir: Base directory for version storage
52 """
53 self.base_dir = Path(base_dir)
54 self.versions_dir = self.base_dir / 'versions'
55 self.versions_dir.mkdir(parents=True, exist_ok=True)
56
57 def save_version(
58 self,
59 object_id: str,
60 content: str,
61 author: str,
62 message: str,
63 ) -> int:
64 """
65 Save a new version of an object.
66
67 Args:
68 object_id: ID of the object (e.g., 'hello', 'calculator')
69 content: The content to version
70 author: Who made this change
71 message: Commit message
72
73 Returns:
74 The version ID (1, 2, 3, etc.)
75 """
76 # Create object's version directory
77 obj_dir = self.versions_dir / object_id
78 obj_dir.mkdir(parents=True, exist_ok=True)
79
80 # Compute hash of content
81 content_hash = self._compute_hash(content)
82
83 # Get next version ID
84 version_id = self._get_next_version_id(object_id)
85
86 # Get timestamp
87 timestamp = datetime.now().isoformat()
88
89 # Save content to file
90 content_file = obj_dir / f'v{version_id}.txt'
91 content_file.write_text(content)
92
93 # Save metadata to TSV
94 metadata_file = obj_dir / 'metadata.tsv'
95 is_new_file = not metadata_file.exists()
96
97 with open(metadata_file, 'a', newline='') as f:
98 writer = csv.DictWriter(
99 f,
100 fieldnames=['version_id', 'timestamp', 'author', 'message', 'hash'],
101 delimiter='\t',
102 )
103
104 if is_new_file:
105 writer.writeheader()
106
107 writer.writerow({
108 'version_id': version_id,
109 'timestamp': timestamp,
110 'author': author,
111 'message': message,
112 'hash': content_hash,
113 })
114
115 return version_id
116
117 def get_version(self, object_id: str, version_id: Optional[int] = None) -> Optional[Dict[str, Any]]:
118 """
119 Get a specific version of an object.
120
121 Args:
122 object_id: ID of the object
123 version_id: Version ID to retrieve (None = latest)
124
125 Returns:
126 Dictionary with version data, or None if not found
127 """
128 obj_dir = self.versions_dir / object_id
129
130 if not obj_dir.exists():
131 return None
132
133 # Get metadata
134 metadata_file = obj_dir / 'metadata.tsv'
135 if not metadata_file.exists():
136 return None
137
138 # Read all versions
139 versions = []
140 with open(metadata_file, 'r', newline='') as f:
141 reader = csv.DictReader(f, delimiter='\t')
142 for row in reader:
143 row['version_id'] = int(row['version_id'])
144 versions.append(row)
145
146 if not versions:
147 return None
148
149 # Find the version
150 if version_id is None:
151 # Get latest
152 target_version = versions[-1]
153 else:
154 # Find specific version
155 target_version = None
156 for v in versions:
157 if v['version_id'] == version_id:
158 target_version = v
159 break
160
161 if target_version is None:
162 return None
163
164 # Read content
165 content_file = obj_dir / f"v{target_version['version_id']}.txt"
166 if not content_file.exists():
167 return None
168
169 content = content_file.read_text()
170
171 # Return version with content
172 return {
173 **target_version,
174 'content': content,
175 }
176
177 def get_history(
178 self,
179 object_id: str,
180 limit: Optional[int] = None,
181 offset: int = 0,
182 ) -> List[Dict[str, Any]]:
183 """
184 Get version history for an object.
185
186 Args:
187 object_id: ID of the object
188 limit: Maximum number of versions to return
189 offset: Number of versions to skip (from most recent)
190
191 Returns:
192 List of version metadata (WITHOUT content)
193 """
194 obj_dir = self.versions_dir / object_id
195
196 if not obj_dir.exists():
197 return []
198
199 metadata_file = obj_dir / 'metadata.tsv'
200 if not metadata_file.exists():
201 return []
202
203 # Read all versions
204 versions = []
205 with open(metadata_file, 'r', newline='') as f:
206 reader = csv.DictReader(f, delimiter='\t')
207 for row in reader:
208 row['version_id'] = int(row['version_id'])
209 versions.append(row)
210
211 if not versions:
212 return []
213
214 # Reverse (most recent first)
215 versions.reverse()
216
217 # Apply offset and limit
218 if offset > 0:
219 versions = versions[offset:]
220
221 if limit is not None:
222 versions = versions[:limit]
223
224 return versions
225
226 def rollback(
227 self,
228 object_id: str,
229 to_version: int,
230 author: str,
231 message: str,
232 ) -> int:
233 """
234 Rollback to a previous version.
235
236 This creates a NEW version with the content from the old version.
237 History is preserved (not deleted).
238
239 Args:
240 object_id: ID of the object
241 to_version: Version ID to rollback to
242 author: Who is performing the rollback
243 message: Rollback message
244
245 Returns:
246 The new version ID
247
248 Raises:
249 VersionNotFoundError: If to_version doesn't exist
250 """
251 # Get the version to rollback to
252 old_version = self.get_version(object_id, to_version)
253
254 if old_version is None:
255 raise VersionNotFoundError(f"Version {to_version} not found for object {object_id}")
256
257 # Save a new version with the old content
258 new_version_id = self.save_version(
259 object_id=object_id,
260 content=old_version['content'],
261 author=author,
262 message=message,
263 )
264
265 return new_version_id
266
267 def _get_next_version_id(self, object_id: str) -> int:
268 """Get the next version ID for an object"""
269 obj_dir = self.versions_dir / object_id
270 metadata_file = obj_dir / 'metadata.tsv'
271
272 if not metadata_file.exists():
273 return 1
274
275 # Read existing versions
276 with open(metadata_file, 'r', newline='') as f:
277 reader = csv.DictReader(f, delimiter='\t')
278 versions = list(reader)
279
280 if not versions:
281 return 1
282
283 # Get max version ID and add 1
284 max_id = max(int(v['version_id']) for v in versions)
285 return max_id + 1
286
287 def _compute_hash(self, content: str) -> str:
288 """Compute SHA-256 hash of content"""
289 return hashlib.sha256(content.encode()).hexdigest()