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

9 downloads

dbbasic-object-server/object_collections.py
Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_collections.py · 14.5 KB · 417 lines
1"""Read-only collection summaries for object sources.
2
3Collections are a server-side view over object source files and permission
4policy. They let tools such as Scroll show business/app groupings without
5turning collection membership into a separate database table too early.
6"""
7
8from __future__ import annotations
9
10import os
11from collections import Counter, defaultdict
12from dataclasses import dataclass
13from pathlib import Path
14from typing import Any, Iterable
15
16import object_files
17import object_logs
18import object_permission_store
19import object_permissions
20import object_state
21from object_namespace import (
22 ObjectSource,
23 iter_object_sources,
24 parse_user_object_id,
25 validate_object_id,
26)
27from object_versions import DEFAULT_DATA_DIR
28
29COLLECTIONS_DIR = "collections"
30RECORDS_FILE = "records.tsv"
31
32
33class InvalidCollectionNameError(ValueError):
34 """Raised when a collection name is not safe for routes or storage."""
35
36
37class CollectionNotFoundError(LookupError):
38 """Raised when a collection has no objects or permission rules."""
39
40
41@dataclass(frozen=True)
42class CollectionObjectSummary:
43 object_id: str
44 path: str
45 owner: str
46 kind: str
47 state_count: int
48 has_logs: bool
49 file_count: int
50
51 def to_dict(self) -> dict[str, Any]:
52 return {
53 "object_id": self.object_id,
54 "path": self.path,
55 "owner": self.owner,
56 "kind": self.kind,
57 "state_count": self.state_count,
58 "has_logs": self.has_logs,
59 "file_count": self.file_count,
60 }
61
62
63def validate_collection_name(collection: str) -> bool:
64 """Return True when a collection name is safe to use in a route."""
65 return validate_object_id(collection)
66
67
68def collection_for_object_id(object_id: str) -> str | None:
69 """Infer the collection NAME an object id stands for.
70
71 This decides which names are collections (collection_names,
72 is_known_collection), and there a user object `u_<id>_<name>` still
73 counts under whatever `<name>` starts with: record and schema routes
74 for that name answer because of it, and that is left alone.
75
76 It does not decide membership. A user object is no member of the
77 collection its name spells: see _summaries_by_collection.
78 """
79 parsed = parse_user_object_id(object_id)
80 if parsed is not None:
81 _, name = parsed
82 return name.split("_", 1)[0] if name else None
83
84 return object_id.split("_", 1)[0] if object_id else None
85
86
87def list_collections(
88 *,
89 base_dir: Path | str = DEFAULT_DATA_DIR,
90 roots: Iterable[Path] | None = None,
91) -> list[dict[str, Any]]:
92 """Return summaries for all known source and permission collections."""
93 sources = iter_object_sources(roots)
94 policy = object_permission_store.load_policy(base_dir)
95 summaries = _summaries_by_collection(sources, policy, base_dir=base_dir)
96 return [summaries[name] for name in sorted(summaries)]
97
98
99def list_user_object_groups(
100 *,
101 base_dir: Path | str = DEFAULT_DATA_DIR,
102 roots: Iterable[Path] | None = None,
103) -> list[dict[str, Any]]:
104 """Return user objects summarised per owner, in owner-id order.
105
106 `owner` is the user id as a string, as in GET /objects. There is no
107 `permission` block: a user object answers to its owner (and to rules
108 naming its object_id), not to any collection's rules.
109 """
110 groups: dict[int, list[CollectionObjectSummary]] = defaultdict(list)
111 for source in iter_object_sources(roots):
112 parsed = parse_user_object_id(source.object_id)
113 if parsed is None:
114 continue
115 groups[parsed[0]].append(_object_summary(source, base_dir=base_dir))
116
117 summaries = []
118 for user_id in sorted(groups):
119 objects = sorted(groups[user_id], key=lambda item: item.object_id)
120 summaries.append({
121 "owner": str(user_id),
122 "object_count": len(objects),
123 "file_count": sum(item.file_count for item in objects),
124 "state_object_count": sum(1 for item in objects if item.state_count > 0),
125 "log_object_count": sum(1 for item in objects if item.has_logs),
126 "objects": [item.to_dict() for item in objects],
127 })
128 return summaries
129
130
131def collection_names(
132 *,
133 base_dir: Path | str = DEFAULT_DATA_DIR,
134 roots: Iterable[Path] | None = None,
135) -> set[str]:
136 """Return exactly the names list_collections() would summarise.
137
138 The same four sources in the same way (object ids, permission rules,
139 records files, schema files), without building a summary per object.
140 A summary reads every object's state file, lists its files and probes
141 its logs, so asking list_collections() "which names exist" cost about
142 36 ms on a 57-package install (160 objects) and the answer was thrown
143 away. Nothing is cached here: every call reads the disk.
144 """
145 sources = iter_object_sources(roots)
146 policy = object_permission_store.load_policy(base_dir)
147 names = {
148 collection
149 for collection in (collection_for_object_id(source.object_id) for source in sources)
150 if collection is not None
151 }
152 names.update(
153 rule.collection
154 for rule in policy.rules
155 if rule.collection is not None and validate_collection_name(rule.collection)
156 )
157 names.update(_iter_record_collections(base_dir))
158 names.update(_iter_schema_collections(base_dir))
159 return names
160
161
162def is_known_collection(
163 collection: str,
164 *,
165 base_dir: Path | str = DEFAULT_DATA_DIR,
166 roots: Iterable[Path] | None = None,
167) -> bool:
168 """Return True exactly when `collection in collection_names(...)`.
169
170 The membership question object_schemas.get_schema asks for every name
171 that has no schema file, which the server asks on every site-route
172 request (`site_hosts`), so it is answered by looking for this one name
173 rather than by listing every name:
174
175 - the policy is always loaded, first, so a policy file that cannot be
176 parsed raises here exactly as it did when list_collections() answered;
177 - a records file or a schema file is one lexists() each. The listing
178 globs, and a glob reports any directory entry (a dangling symlink
179 included), which is what lexists() answers. On a case-insensitive
180 filesystem lexists() also answers yes for a differently-cased name
181 the glob would have spelled the other way, so a hit is confirmed
182 against the real directory entry;
183 - object sources are scanned only for a name with no underscore: an
184 object id contributes its first `_`-separated segment (see
185 collection_for_object_id), which cannot contain one.
186
187 No cache, so nothing to invalidate: a package installed or removed, a
188 rule added, a records file created or deleted is seen by the next call.
189 """
190 if not validate_collection_name(collection):
191 return False
192
193 policy = object_permission_store.load_policy(base_dir)
194 if any(rule.collection == collection for rule in policy.rules):
195 return True
196
197 base = Path(base_dir)
198 if _entry_exists(base / COLLECTIONS_DIR / collection / RECORDS_FILE, collection, depth=2):
199 return True
200 if _entry_exists(base / "schemas" / f"{collection}.json", f"{collection}.json", depth=1):
201 return True
202
203 if "_" in collection:
204 return False
205 return any(
206 collection_for_object_id(source.object_id) == collection
207 for source in iter_object_sources(roots)
208 )
209
210
211def _entry_exists(path: Path, exact_name: str, *, depth: int) -> bool:
212 """lexists(path), confirmed against the real spelling of the entry
213 `depth` levels up from the end of the path (1 = the file itself, 2 =
214 its directory). The confirmation only runs on a hit."""
215 if not os.path.lexists(path):
216 return False
217 listed_in = path.parents[depth - 1]
218 try:
219 return exact_name in os.listdir(listed_in)
220 except OSError:
221 return False
222
223
224def get_collection(
225 collection: str,
226 *,
227 base_dir: Path | str = DEFAULT_DATA_DIR,
228 roots: Iterable[Path] | None = None,
229) -> dict[str, Any]:
230 """Return one collection summary including object details."""
231 if not validate_collection_name(collection):
232 raise InvalidCollectionNameError(f"Invalid collection name: {collection}")
233
234 sources = iter_object_sources(roots)
235 policy = object_permission_store.load_policy(base_dir)
236 summaries = _summaries_by_collection(
237 sources,
238 policy,
239 base_dir=base_dir,
240 include_objects=True,
241 )
242 try:
243 return summaries[collection]
244 except KeyError as exc:
245 raise CollectionNotFoundError(f"Collection not found: {collection}") from exc
246
247
248def _summaries_by_collection(
249 sources: list[ObjectSource],
250 policy: object_permissions.PermissionPolicy,
251 *,
252 base_dir: Path | str,
253 include_objects: bool = False,
254) -> dict[str, dict[str, Any]]:
255 object_groups: dict[str, list[CollectionObjectSummary]] = defaultdict(list)
256 for source in sources:
257 collection = collection_for_object_id(source.object_id)
258 if collection is None:
259 continue
260 if parse_user_object_id(source.object_id) is not None:
261 # The name stays a collection; the object is not one of its
262 # members. `u_1_tools_cli` used to be listed inside the system
263 # collection `tools` (owners ["1", "system"]) beside that
264 # collection's permission rules, which do not grant on it
265 # (object_server._object_permission_decision). User objects are
266 # summarised per owner by list_user_object_groups().
267 object_groups.setdefault(collection, [])
268 continue
269 object_groups[collection].append(_object_summary(source, base_dir=base_dir))
270
271 policy_collections = {
272 rule.collection
273 for rule in policy.rules
274 if rule.collection is not None and validate_collection_name(rule.collection)
275 }
276 record_collections = set(_iter_record_collections(base_dir))
277 schema_collections = set(_iter_schema_collections(base_dir))
278
279 collection_names = (
280 set(object_groups) | policy_collections | record_collections | schema_collections
281 )
282 summaries: dict[str, dict[str, Any]] = {}
283 for collection in collection_names:
284 objects = sorted(object_groups.get(collection, []), key=lambda item: item.object_id)
285 summaries[collection] = _collection_summary(
286 collection,
287 objects,
288 policy,
289 has_records=collection in record_collections,
290 has_schema=collection in schema_collections,
291 include_objects=include_objects,
292 )
293
294 return summaries
295
296
297def _object_summary(
298 source: ObjectSource,
299 *,
300 base_dir: Path | str,
301) -> CollectionObjectSummary:
302 state = object_state.get_object_state(source.object_id, base_dir=base_dir)
303 files = object_files.list_object_files(source.object_id, base_dir=base_dir)
304
305 return CollectionObjectSummary(
306 object_id=source.object_id,
307 path=source.relative_path.as_posix(),
308 owner=_object_owner(source.object_id),
309 kind=source.kind,
310 state_count=len(state),
311 has_logs=_has_logs(source.object_id, base_dir=base_dir),
312 file_count=len(files),
313 )
314
315
316def _collection_summary(
317 collection: str,
318 objects: list[CollectionObjectSummary],
319 policy: object_permissions.PermissionPolicy,
320 *,
321 has_records: bool,
322 has_schema: bool = False,
323 include_objects: bool,
324) -> dict[str, Any]:
325 owners = sorted({item.owner for item in objects})
326 kinds = Counter(item.kind for item in objects)
327 summary = {
328 "name": collection,
329 "object_count": len(objects),
330 "file_count": sum(item.file_count for item in objects),
331 "state_object_count": sum(1 for item in objects if item.state_count > 0),
332 "log_object_count": sum(1 for item in objects if item.has_logs),
333 "has_records": has_records,
334 "has_schema": has_schema,
335 "owners": owners,
336 "kinds": dict(sorted(kinds.items())),
337 "permission": _permission_summary(collection, policy),
338 }
339 if include_objects:
340 summary["objects"] = [item.to_dict() for item in objects]
341 return summary
342
343
344def _permission_summary(
345 collection: str,
346 policy: object_permissions.PermissionPolicy,
347) -> dict[str, Any]:
348 rules = [rule for rule in policy.rules if rule.collection == collection]
349 actions = sorted({action for rule in rules for action in rule.actions})
350 principals = sorted({rule.principal for rule in rules})
351 return {
352 "access_mode": policy.access_mode,
353 "rule_count": len(rules),
354 "allow_count": sum(1 for rule in rules if rule.effect == "allow"),
355 "deny_count": sum(1 for rule in rules if rule.effect == "deny"),
356 "actions": actions,
357 "principals": principals,
358 }
359
360
361def _object_owner(object_id: str) -> str:
362 parsed = parse_user_object_id(object_id)
363 if parsed is None:
364 return "system"
365 user_id, _ = parsed
366 return str(user_id)
367
368
369def _has_logs(object_id: str, *, base_dir: Path | str) -> bool:
370 log_dir = object_logs.object_log_dir(object_id, base_dir)
371 if not log_dir.exists() or not log_dir.is_dir():
372 return False
373
374 if (log_dir / object_logs.LOG_FILE).is_file():
375 return True
376
377 return any(path.is_file() for path in log_dir.glob("log-*.tsv*"))
378
379
380def _iter_schema_collections(base_dir: Path | str) -> list[str]:
381 root = Path(base_dir) / "schemas"
382 if not root.exists() or not root.is_dir():
383 return []
384
385 names = []
386 for path in sorted(root.glob("*.json"), key=lambda item: item.as_posix()):
387 name = path.stem
388 if validate_collection_name(name):
389 names.append(name)
390 return names
391
392
393def _iter_record_collections(base_dir: Path | str) -> list[str]:
394 root = Path(base_dir) / COLLECTIONS_DIR
395 if not root.exists() or not root.is_dir():
396 return []
397
398 # Not `root.glob(f"*/{RECORDS_FILE}")`: a glob whose last part is a plain
399 # name answers exists() on Python 3.10-3.11 (a dangling records.tsv
400 # symlink is missed) and lexists() on 3.12+ (it is listed). This is
401 # lexists() on every version, which is what is_known_collection asks.
402 try:
403 with os.scandir(root) as entries:
404 found = [
405 root / entry.name / RECORDS_FILE
406 for entry in entries
407 if entry.is_dir() and os.path.lexists(os.path.join(entry.path, RECORDS_FILE))
408 ]
409 except OSError:
410 return []
411
412 names = []
413 for path in sorted(found, key=lambda item: item.as_posix()):
414 name = path.parent.name
415 if validate_collection_name(name):
416 names.append(name)
417 return names