Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

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

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

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_source.py · 6.2 KB · 195 lines
1"""Source file operations for DBBASIC objects.
2
3This module connects object ID resolution with source version storage. It does
4not reload runtime objects or enforce HTTP permissions; those belong in the
5server/runtime layers that call this code.
6"""
7
8from __future__ import annotations
9
10import ast
11from pathlib import Path
12from typing import Iterable
13
14HTTP_METHOD_NAMES = ("GET", "POST", "PUT", "DELETE")
15
16from object_namespace import (
17 get_object_roots,
18 object_id_from_path,
19 parse_user_object_id,
20 resolve_object_id,
21 validate_object_id,
22)
23from object_versions import InvalidObjectIdError, VersionManager, VersionNotFoundError
24
25
26class ObjectSourceError(Exception):
27 """Base exception for object source operations."""
28
29
30class ObjectSourceNotFoundError(ObjectSourceError):
31 """Raised when an object ID does not resolve to a source file."""
32
33
34class ObjectSourceExistsError(ObjectSourceError):
35 """Raised when an object source already exists."""
36
37
38def get_object_source(object_id: str, roots: Iterable[Path] | None = None) -> str:
39 """Read source text for an existing object."""
40 source_path = _resolve_existing_source(object_id, roots)
41 return source_path.read_text()
42
43
44def source_method_report(code: str) -> tuple[list[str], list[str]]:
45 """Return (executable HTTP methods, authoring warnings) for object source.
46
47 Detection is static (AST), so it runs safely at write time and lets the
48 create/update responses tell authors — human or AI — that a saved object
49 cannot execute, instead of leaving that discovery to the first request.
50 """
51 try:
52 tree = ast.parse(code)
53 except SyntaxError as exc:
54 return [], [f"Source has a Python syntax error: {exc.msg} (line {exc.lineno})"]
55
56 methods = sorted(
57 {
58 node.name
59 for node in tree.body
60 if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
61 and node.name in HTTP_METHOD_NAMES
62 }
63 )
64 if not methods:
65 return [], [
66 "Source defines no HTTP methods; the object cannot execute. "
67 "Define GET(request), POST(request), PUT(request), or DELETE(request) "
68 "at module top level (see docs/object-authoring.md)."
69 ]
70 return methods, []
71
72
73def create_object_source(
74 object_id: str,
75 code: str,
76 author: str,
77 message: str,
78 roots: Iterable[Path] | None = None,
79 version_manager: VersionManager | None = None,
80 correlation_id: str | None = None,
81) -> int:
82 """Create a new source file, save its first version, and return its version ID."""
83 source_path = _resolve_new_source_path(object_id, roots)
84 manager = version_manager or VersionManager()
85
86 version_id = manager.save_version(
87 object_id=object_id,
88 content=code,
89 author=author,
90 message=message,
91 correlation_id=correlation_id,
92 )
93 source_path.parent.mkdir(parents=True, exist_ok=True)
94 _write_source(source_path, code)
95 return version_id
96
97
98def update_object_source(
99 object_id: str,
100 new_code: str,
101 author: str,
102 message: str,
103 roots: Iterable[Path] | None = None,
104 version_manager: VersionManager | None = None,
105 correlation_id: str | None = None,
106) -> int:
107 """Save a new source version and write it to the object file."""
108 source_path = _resolve_existing_source(object_id, roots)
109 manager = version_manager or VersionManager()
110
111 version_id = manager.save_version(
112 object_id=object_id,
113 content=new_code,
114 author=author,
115 message=message,
116 correlation_id=correlation_id,
117 )
118 _write_source(source_path, new_code)
119 return version_id
120
121
122def rollback_object_source(
123 object_id: str,
124 to_version: int,
125 author: str,
126 message: str,
127 roots: Iterable[Path] | None = None,
128 version_manager: VersionManager | None = None,
129 correlation_id: str | None = None,
130) -> int:
131 """Rollback source by creating a new version and writing its content."""
132 source_path = _resolve_existing_source(object_id, roots)
133 manager = version_manager or VersionManager()
134
135 new_version_id = manager.rollback(
136 object_id=object_id,
137 to_version=to_version,
138 author=author,
139 message=message,
140 correlation_id=correlation_id,
141 )
142 new_version = manager.get_version(object_id, new_version_id)
143 if new_version is None:
144 raise VersionNotFoundError(f"Version {new_version_id} not found for object {object_id}")
145
146 _write_source(source_path, new_version["content"])
147 return new_version_id
148
149
150def _resolve_existing_source(object_id: str, roots: Iterable[Path] | None) -> Path:
151 if not validate_object_id(object_id):
152 raise InvalidObjectIdError(f"Invalid object ID: {object_id}")
153
154 source_path = resolve_object_id(object_id, roots=roots)
155 if source_path is None:
156 raise ObjectSourceNotFoundError(f"Object source not found: {object_id}")
157 return source_path
158
159
160def _resolve_new_source_path(object_id: str, roots: Iterable[Path] | None) -> Path:
161 if not validate_object_id(object_id):
162 raise InvalidObjectIdError(f"Invalid object ID: {object_id}")
163
164 search_roots = list(roots) if roots is not None else get_object_roots()
165 if not search_roots:
166 raise InvalidObjectIdError("No object source root configured")
167
168 if resolve_object_id(object_id, roots=search_roots) is not None:
169 raise ObjectSourceExistsError(f"Object source already exists: {object_id}")
170
171 root = search_roots[0]
172 parsed_user = parse_user_object_id(object_id)
173 if parsed_user:
174 user_id, name = parsed_user
175 source_path = root / "users" / str(user_id) / f"{name}.py"
176 elif "_" in object_id:
177 category, name = object_id.split("_", 1)
178 source_path = root / category / f"{name}.py"
179 else:
180 source_path = root / f"{object_id}.py"
181
182 try:
183 derived_object_id = object_id_from_path(source_path, root)
184 except ValueError as exc:
185 raise InvalidObjectIdError(f"Invalid object ID: {object_id}")
186 if derived_object_id != object_id:
187 raise InvalidObjectIdError(f"Invalid object ID: {object_id}")
188
189 return source_path
190
191
192def _write_source(source_path: Path, content: str) -> None:
193 temp_path = source_path.with_name(f".{source_path.name}.tmp")
194 temp_path.write_text(content)
195 temp_path.replace(source_path)