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_attention.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, 8 minutes ago History
object_attention.py · 34.7 KB · 735 lines
1"""A declared attention count: `collection` + `where`, counted for a viewer.
2
3An attention source (object_packages' `attention` manifest section, the
4`attention_sources` registry) used to have exactly one form: an
5`object_id` naming a provider with a `COUNT` method. Sixteen packages
6shipped one, and ten of them were the same fifteen lines -- read one
7collection, keep the rows whose status is the waiting room, return
8`len()` and a sentence. This module is that fifteen lines, once, so a
9package can say it instead of writing it::
10
11 {"id": "expenses_to_approve", "label": "Expenses to approve",
12 "path": "/expenses", "nav_id": "expenses", "group": "Money",
13 "collection": "expenses",
14 "where": {"status": "submitted"},
15 "detail": {"op": "sum", "field": "amount_cents", "format": "cents",
16 "text": "{value} awaiting approval"}}
17
18**`where` is the permission row-filter language, not a new one.** Every
19value is what a rule's `row_filter` accepts and
20`object_permissions.record_matches_filter` decides: a literal (implicit
21`eq`), a `$`-variable (`$user_id` is the viewer -- "my own rows" is
22`{"owner_id": "$user_id"}`, so there is no separate `scope` switch), one
23`{"op", "value"}` condition with an op from `FILTER_OPERATORS`, or a list
24of such conditions ANDed. A bare JSON list is NOT membership there (it is
25compared as one string), so it is refused here rather than given a second
26meaning; membership is `{"op": "in", "value": [...]}`. One operator is
27added, and only here: `older_than_days` (see `_age_days`), because "the
28oldest of these" and "how many are over a week old" were the sentence in
29half of the providers this replaced, and no row filter has a clock. Its
30threshold may name an app_settings key with a default
31(`{"setting": "carrier.stuck_days", "default": 10}`, `_setting_days`):
32the stuck-parcel provider read its threshold that way, and a number of
33days read by key is configuration, not an expression.
34
35What the second round (invoices, parcels, mailboxes) did NOT need, and so
36did not get: a case-insensitive operator (the write path stores a boolean
37as exactly `true`/`false`, so `"ok": "false"` is exact), a `not_in` (a
38list of `ne`, or -- where the condition must also serve the index -- the
39enum's complement written out as an `in`, pinned by a test against the
40schema), and a "before today" (`older_than_days` 1 on a date). What it
41refused: a field that falls back to another field, a distinct count over
42such a fallback, arithmetic between fields, minutes against a naive local
43clock. Those stay code (docs/package-authoring.md lists the five
44providers and why), and their numbers are gated, below.
45
46**Counted for the viewer, through the permission engine.** The old
47providers ran in the daemon with no identity and their numbers were shown
48to every signed-in user: "Expenses to approve: 3, 1,240.00 awaiting
49approval" reached a member who may read none of those expenses. A
50declared count is the number of rows the VIEWER may read
51(`object_access.Access.visible`, the same engine call the record API makes
52per row), so an admin sees what the provider used to say, a manager the
53rows a manager may read, a member their own, and someone with no grant
54nothing at all. Fail closed in every direction Access already fails
55closed: no identity is anonymous (no counts), an unreadable policy refuses
56every row. Project and share grants count, as they do for the record API.
57
58**And from the fields the viewer may read**, when permissions are enforced
59(`object_access.enforcement_enabled`). The row decision alone let a
60declaration whose `where`, sum or age named a field a rule or the schema
61hides from the viewer produce a count, a total or a sentence derived from
62it: "Band A tickets: 2" to someone who cannot read the band. Each row is
63now judged as `Access.readable` returns it (the record API's redaction): a
64condition on a field hidden in that row is false, a sum or age over one
65adds nothing, and a detail part every row of which is blind is left out
66(`count`, `_detail`). Off or audit-only, nothing is redacted anywhere and
67the count is the row-level one; a mode that cannot be read counts nothing.
68The price is one redaction per matched row (about 10 microseconds, measured
692026-12-03: a 1,000-row queue went from ~5 ms to ~14 ms for a non-admin and
70from ~1.4 ms to ~11.5 ms for an admin, who used to skip the engine).
71
72**Why counting at read time does not repeat the 675MB incident.** The
73attention rollup exists because folding a dozen collections on every home
74render is how a box once started swapping. A declared count does not fold
75its collection: `where` must carry at least one literal equality, and the
76rows are fetched through the records cache's field index
77(`object_records.read_collection_records_for_plan`, the index the record
78API uses for row-filtered lists), so the cost is the queue, not the
79collection. The index is per cache entry and rebuilt lazily after a
80write; a collection over DBBASIC_RECORDS_CACHE_MAX_ROWS has no index and
81is read whole, exactly as every API list of it already is. A per-viewer
82count could not be a rollup anyway without a row per viewer per queue.
83Code providers (`object_id`) are still rolled up by
84object_daemon.process_attention -- folding four collections per render is
85the thing the rollup exists to prevent -- and so still produce one number
86over everybody's rows. That number is shown only to a viewer who may read
87every row of each collection the entry's `reads` names
88(`provider_shown_to`), and to nobody but an admin when it names none: the
89only honest way to show an aggregate is to someone the rows themselves
90could reach. A per-viewer provider was rejected for the same reason the
91rollup exists.
92
93**The detail** is the second sentence ("3 over a week old"). A part, or a
94list of parts joined with ", ", each one of:
95
96- `{"op": "count", "where"?: ..., "text": "{value} over a week old"}` --
97 the counted rows, or the subset of them matching a further `where`;
98- `{"op": "sum", "field": ..., "format"?: ..., "text": ...}` -- an integer
99 field summed (an unparseable cell contributes 0, as every provider did);
100- `{"op": "max_age_days", "field": ..., "text": ...}` -- the oldest row's
101 age, from rows whose date parses and is not in the future.
102
103A part whose value is 0 is left out unless it says `"show_zero": true`,
104and a max_age part with no dated rows is always left out. A `text`
105without `{value}` is a fixed sentence, shown when the part would be. `format` is
106`integer` (the default), `cents` ("1,234.56"), `dollars` ("$1234.56") or
107`hours` (seconds as hours, one decimal) -- the formats the replaced
108providers printed, kept so the sentences did not change. All integer
109arithmetic: no float touches money (doctrine #10); `hours` is not money.
110
111What was rejected: a generic "counter" object every declaration pointed at
112(the daemon calls COUNT with an empty payload, so it could not have known
113which queue or which viewer); counting the stored state in the daemon and
114hiding it from non-admins (a manager who works the expense queue would
115have lost the number); and new filter keys (`not_in`, `older_than` at the
116top level) where the row-filter language already had the condition.
117"""
118
119from __future__ import annotations
120
121import json
122import re
123from datetime import date, datetime, timezone
124from pathlib import Path
125from typing import Any, Iterable, Mapping
126
127import object_access
128import object_collections
129import object_field_permissions
130import object_permissions
131import object_records
132
133SOURCES_COLLECTION = "attention_sources"
134COUNTS_COLLECTION = "attention_counts"
135
136OLDER_THAN_DAYS = "older_than_days"
137DETAIL_OPS = ("count", "sum", "max_age_days")
138FORMATS = ("integer", "cents", "dollars", "hours")
139DETAIL_LIMIT = 200
140_FIELD_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
141# object_packages' attention collection pattern.
142_COLLECTION_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")
143_DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
144# app_settings' own key pattern (its schema's validation), so a declaration
145# cannot name a key no setting could ever have.
146_SETTING_KEY_RE = re.compile(r"^[a-z0-9_]+(\.[a-z0-9_]+)+$")
147SETTINGS_COLLECTION = "app_settings"
148_TRUE = ("true", "1", "yes", "on")
149
150
151class InvalidDeclarationError(ValueError):
152 """A `collection`/`where`/`detail` declaration that could not work."""
153
154
155# --- parsing (install time, and again on every read of the registry) -------
156
157def parse_where(where: Any, *, require_equality: bool = True) -> dict[str, Any]:
158 """The `where` mapping, validated against the row-filter vocabulary.
159
160 Raises InvalidDeclarationError naming the field. `require_equality`
161 is the cost rule (module docstring): the top-level `where` of a count
162 must name at least one literal `eq`/`in`, so the rows can always be
163 fetched through the field index. A detail part's sub-`where` filters
164 rows already fetched and does not need one.
165 """
166 if not isinstance(where, Mapping) or not where:
167 raise InvalidDeclarationError("where must be a non-empty object")
168 clean: dict[str, Any] = {}
169 for field, expected in where.items():
170 if not isinstance(field, str) or not _FIELD_RE.fullmatch(field):
171 raise InvalidDeclarationError(f"where names an invalid field: {field!r}")
172 clean[field] = _parse_conditions(field, expected)
173 if require_equality and not _equality_lookups(clean):
174 raise InvalidDeclarationError(
175 "where needs at least one literal equality (a value, or op eq/in), "
176 "so the count reads its queue through the index and not the whole collection")
177 return clean
178
179
180def _parse_conditions(field: str, expected: Any) -> Any:
181 if isinstance(expected, str):
182 return expected
183 if isinstance(expected, Mapping):
184 return _parse_condition(field, expected)
185 if isinstance(expected, list) and expected and all(isinstance(item, Mapping) for item in expected):
186 return [_parse_condition(field, item) for item in expected]
187 raise InvalidDeclarationError(
188 f"where.{field} must be a string, an {{op, value}} condition or a list of them "
189 "(membership is {\"op\": \"in\", \"value\": [...]})")
190
191
192def _parse_condition(field: str, condition: Mapping[str, Any]) -> dict[str, Any]:
193 if set(condition) - {"op", "value"}:
194 raise InvalidDeclarationError(f"where.{field} condition takes only op and value")
195 op = str(condition.get("op") or "eq").strip().lower()
196 value = condition.get("value")
197 if op == OLDER_THAN_DAYS:
198 if isinstance(value, Mapping):
199 return {"op": op, "value": _parse_setting_value(field, value)}
200 if not _whole_days(value):
201 raise InvalidDeclarationError(
202 f"where.{field} {OLDER_THAN_DAYS} needs a whole number of days "
203 "or {\"setting\": key, \"default\": days}")
204 return {"op": op, "value": value}
205 if op not in object_permissions.FILTER_OPERATORS:
206 raise InvalidDeclarationError(f"where.{field} has an unknown op: {op}")
207 if op == "in":
208 if not isinstance(value, list) or not value or not all(isinstance(item, str) for item in value):
209 raise InvalidDeclarationError(f"where.{field} in needs a list of strings")
210 return {"op": op, "value": list(value)}
211 if isinstance(value, bool) or not isinstance(value, (str, int)):
212 raise InvalidDeclarationError(f"where.{field} {op} needs a string or number value")
213 return {"op": op, "value": str(value)}
214
215
216def _whole_days(value: Any) -> bool:
217 return not isinstance(value, bool) and isinstance(value, int) and value >= 0
218
219
220def _parse_setting_value(field: str, value: Mapping[str, Any]) -> dict[str, Any]:
221 """`{"setting": "carrier.stuck_days", "default": 10}`: a threshold the
222 operator tunes in app_settings, with the default the package documents.
223
224 The only thing a declaration may read from settings is a whole number
225 of days, and only by naming the key: no expression, no other type."""
226 if set(value) != {"setting", "default"}:
227 raise InvalidDeclarationError(
228 f"where.{field} {OLDER_THAN_DAYS} setting takes exactly setting and default")
229 key = value.get("setting")
230 if not isinstance(key, str) or not _SETTING_KEY_RE.fullmatch(key):
231 raise InvalidDeclarationError(
232 f"where.{field} {OLDER_THAN_DAYS} names an invalid setting key: {key!r}")
233 if not _whole_days(value.get("default")):
234 raise InvalidDeclarationError(
235 f"where.{field} {OLDER_THAN_DAYS} setting needs a whole number of days as its default")
236 return {"setting": key, "default": value["default"]}
237
238
239def _iter_field_conditions(expected: Any) -> list[tuple[str, Any]]:
240 items = expected if isinstance(expected, list) else [expected]
241 out = []
242 for item in items:
243 if isinstance(item, Mapping):
244 out.append((item["op"], item["value"]))
245 else:
246 out.append(("eq", item))
247 return out
248
249
250def _equality_lookups(where: Mapping[str, Any]) -> list[tuple[str, frozenset[str]]]:
251 """(field, values) for every literal eq/in -- each, alone, a superset of
252 the rows `where` matches, which is what makes it an index option."""
253 lookups = []
254 for field, expected in where.items():
255 for op, value in _iter_field_conditions(expected):
256 if op == "eq" and isinstance(value, str) and not value.startswith("$"):
257 lookups.append((field, frozenset({value})))
258 elif op == "in" and all(not item.startswith("$") for item in value):
259 lookups.append((field, frozenset(value)))
260 return lookups
261
262
263def parse_detail(detail: Any) -> list[dict[str, Any]]:
264 """The detail parts, validated. None/empty is no detail."""
265 if detail in (None, "", [], {}):
266 return []
267 parts = detail if isinstance(detail, list) else [detail]
268 clean = []
269 for index, part in enumerate(parts):
270 label = f"detail[{index}]"
271 if not isinstance(part, Mapping):
272 raise InvalidDeclarationError(f"{label} must be an object")
273 unknown = set(part) - {"op", "field", "where", "format", "text", "show_zero"}
274 if unknown:
275 raise InvalidDeclarationError(f"{label} has unknown keys: {', '.join(sorted(unknown))}")
276 op = str(part.get("op") or "")
277 if op not in DETAIL_OPS:
278 raise InvalidDeclarationError(f"{label}.op must be one of {', '.join(DETAIL_OPS)}")
279 text = part.get("text")
280 # `{value}` is optional: a part without it is a fixed sentence,
281 # shown exactly when the part's value would have been ("failed 3 or
282 # more syncs in a row" -- the threshold is the where, not a number
283 # worth repeating).
284 if not isinstance(text, str) or not text.strip() or len(text) > DETAIL_LIMIT:
285 raise InvalidDeclarationError(f"{label}.text must be a short sentence")
286 if text.replace("{value}", "").count("{") or text.replace("{value}", "").count("}"):
287 raise InvalidDeclarationError(f"{label}.text may hold no placeholder but {{value}}")
288 item: dict[str, Any] = {"op": op, "text": text}
289 if op == "count":
290 if "field" in part:
291 raise InvalidDeclarationError(f"{label}: count takes no field")
292 else:
293 field = part.get("field")
294 if not isinstance(field, str) or not _FIELD_RE.fullmatch(field):
295 raise InvalidDeclarationError(f"{label}.field must name a field")
296 item["field"] = field
297 if "where" in part:
298 item["where"] = parse_where(part["where"], require_equality=False)
299 fmt = str(part.get("format") or "integer")
300 if fmt not in FORMATS or (fmt != "integer" and op != "sum"):
301 raise InvalidDeclarationError(f"{label}.format must be one of {', '.join(FORMATS)} "
302 "(and only a sum takes a format other than integer)")
303 if fmt != "integer":
304 item["format"] = fmt
305 show_zero = part.get("show_zero", False)
306 if not isinstance(show_zero, bool):
307 raise InvalidDeclarationError(f"{label}.show_zero must be true or false")
308 if show_zero:
309 item["show_zero"] = True
310 clean.append(item)
311 return clean
312
313
314def canonical_json(value: Any) -> str:
315 """How a declaration is stored in an attention_sources cell, and compared
316 on reinstall: one spelling, so "unchanged" means unchanged."""
317 if value in (None, "", [], {}):
318 return ""
319 return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
320
321
322def declaration_from_source(source: Mapping[str, Any]) -> dict[str, Any] | None:
323 """The parsed declaration of a registry row, or None for a code provider.
324
325 Raises InvalidDeclarationError for a row whose stored JSON no longer
326 parses (a hand edit): the caller decides how loudly to refuse.
327 """
328 collection = str(source.get("collection") or "").strip()
329 if not collection:
330 return None
331 try:
332 where = json.loads(str(source.get("where") or ""))
333 detail_text = str(source.get("detail") or "")
334 detail = json.loads(detail_text) if detail_text else None
335 except ValueError as exc:
336 raise InvalidDeclarationError(f"stored declaration is not JSON: {exc}") from exc
337 return {"collection": collection, "where": parse_where(where), "detail": parse_detail(detail)}
338
339
340# --- evaluation --------------------------------------------------------------
341
342def _text(value: Any) -> str:
343 return str(value if value is not None else "").strip()
344
345
346def _age_days(value: Any, *, now: datetime, today: date) -> int | None:
347 """Whole days since a stored date or datetime, or None.
348
349 A date-only value (`YYYY-MM-DD`, the `date` field type) is aged in
350 calendar days against the server's local date; anything else is parsed
351 as an ISO datetime (`Z` accepted, naive read as UTC) and aged in
352 elapsed whole days against UTC now. Those are exactly the two rules the
353 providers this replaced used (bank lines and backorders by posting /
354 request date, scans, returns and disputes by `created_at`). An empty or
355 unparseable value has no age: it is never "older than", and it adds
356 nothing to an oldest-age detail -- an unreadable date must not become
357 evidence of anything.
358 """
359 text = _text(value)
360 if not text:
361 return None
362 if _DATE_ONLY_RE.fullmatch(text):
363 try:
364 return (today - date.fromisoformat(text)).days
365 except ValueError:
366 return None
367 try:
368 stamp = datetime.fromisoformat(text.replace("Z", "+00:00"))
369 except ValueError:
370 return None
371 if stamp.tzinfo is None:
372 stamp = stamp.replace(tzinfo=timezone.utc)
373 return (now - stamp).days
374
375
376def _setting_days(key: str, default: int, *, base_dir: Path | str) -> int:
377 """A whole-days threshold from app_settings, or `default`.
378
379 The rule every provider that read a setting used: the first row whose
380 key is exactly `key` and whose value is not blank, parsed as an integer.
381 A value that is not a whole number of days (`"soon"`, `"7.5"`, `"-3"`)
382 reads as the default, as does a box without app-settings: a typo in a
383 setting must not turn into "every parcel is stuck" or "none ever is".
384 The settings are read through the key index, not folded.
385 """
386 groups = (((("key", frozenset({key})),),),)
387 try:
388 rows, _narrowed = object_records.read_collection_records_for_plan(
389 SETTINGS_COLLECTION, groups, base_dir=base_dir)
390 except (object_collections.CollectionNotFoundError,
391 object_collections.InvalidCollectionNameError):
392 return default
393 for row in rows:
394 if row.get("key") == key and _text(row.get("value")):
395 try:
396 days = int(_text(row.get("value")))
397 except ValueError:
398 return default
399 return days if days >= 0 else default
400 return default
401
402
403def _resolve_settings(where: Mapping[str, Any], *, base_dir: Path | str,
404 cache: dict[str, int]) -> dict[str, Any]:
405 """`where` with every `{"setting", "default"}` threshold replaced by the
406 number it reads now -- once per count, so every row and every detail
407 part is judged against the same threshold."""
408 def resolve(item):
409 if (isinstance(item, Mapping) and item.get("op") == OLDER_THAN_DAYS
410 and isinstance(item.get("value"), Mapping)):
411 key, default = item["value"]["setting"], item["value"]["default"]
412 if key not in cache:
413 cache[key] = _setting_days(key, default, base_dir=base_dir)
414 return {"op": OLDER_THAN_DAYS, "value": cache[key]}
415 return item
416
417 return {field: ([resolve(item) for item in expected] if isinstance(expected, list)
418 else resolve(expected))
419 for field, expected in where.items()}
420
421
422def _split_where(where: Mapping[str, Any]) -> tuple[dict[str, Any], list[tuple[str, int]]]:
423 """(the row filter for record_matches_filter, the older_than_days checks).
424
425 `where` has had its settings resolved (`_resolve_settings`)."""
426 row_filter: dict[str, Any] = {}
427 ages: list[tuple[str, int]] = []
428 for field, expected in where.items():
429 kept = []
430 for item in (expected if isinstance(expected, list) else [expected]):
431 if isinstance(item, Mapping) and item.get("op") == OLDER_THAN_DAYS:
432 ages.append((field, int(item["value"])))
433 else:
434 kept.append(item)
435 if kept:
436 row_filter[field] = kept if isinstance(expected, list) and len(kept) > 1 else kept[0]
437 return row_filter, ages
438
439
440def _matches(row: Mapping[str, Any], compiled, subject, *, now, today) -> bool:
441 row_filter, ages = compiled
442 if row_filter and not object_permissions.record_matches_filter(row, row_filter, subject):
443 return False
444 for field, days in ages:
445 age = _age_days(row.get(field), now=now, today=today)
446 if age is None or age < days:
447 return False
448 return True
449
450
451def _int(value: Any) -> int:
452 try:
453 return int(_text(value) or 0)
454 except ValueError:
455 return 0
456
457
458def _format(value: int, fmt: str) -> str:
459 if fmt == "cents":
460 sign = "-" if value < 0 else ""
461 whole, minor = divmod(abs(value), 100)
462 return f"{sign}{whole:,}.{minor:02d}"
463 if fmt == "dollars":
464 sign = "-" if value < 0 else ""
465 whole, minor = divmod(abs(value), 100)
466 return f"{sign}${whole}.{minor:02d}"
467 if fmt == "hours":
468 return f"{value / 3600.0:.1f}"
469 return str(value)
470
471
472def _detail(parts: Iterable[Mapping[str, Any]], rows: list[Mapping[str, Any]], subject,
473 *, now: datetime, today: date,
474 hidden: list[frozenset[str]] | None = None) -> str:
475 """The detail sentence over the counted rows.
476
477 `hidden`, given when permissions are enforced, is aligned with `rows`:
478 the fields of each row its viewer may not read (`rows` are then the
479 readable views, without them). A row contributes to a part only when
480 the viewer reads every field the part depends on in it -- the part's
481 `field` and each field its `where` names -- so a hidden amount adds
482 nothing to a sum, a hidden date no age, and a condition on a hidden
483 field matches nothing. A part none of whose rows can contribute is left
484 out even with `show_zero`: "0.00 awaiting approval" would be a claim
485 about a field the viewer cannot read.
486 """
487 sentences = []
488 for part in parts:
489 subset = rows
490 if hidden is not None:
491 needs = set(part.get("where") or ())
492 if "field" in part:
493 needs.add(part["field"])
494 subset = [row for row, unread in zip(rows, hidden) if not (needs & unread)]
495 if rows and not subset:
496 continue
497 if part.get("where"):
498 compiled = _split_where(part["where"])
499 subset = [row for row in subset if _matches(row, compiled, subject, now=now, today=today)]
500 if part["op"] == "count":
501 value: int | None = len(subset)
502 elif part["op"] == "sum":
503 value = sum(_int(row.get(part["field"])) for row in subset)
504 else:
505 ages = [age for age in (_age_days(row.get(part["field"]), now=now, today=today)
506 for row in subset) if age is not None and age >= 0]
507 value = max(ages) if ages else None
508 if value is None or (value == 0 and not part.get("show_zero")):
509 continue
510 rendered = _format(value, part.get("format", "integer"))
511 sentences.append(part["text"].replace("{value}", rendered))
512 return ", ".join(sentences)[:DETAIL_LIMIT]
513
514
515def count(declaration: Mapping[str, Any], access: object_access.Access, *,
516 base_dir: Path | str, now: datetime | None = None) -> dict[str, Any]:
517 """`{"count", "detail"}` for one declaration, as `access`'s subject sees it.
518
519 THE platform function: every declared queue is counted here and only
520 here. Rows come through the field index (superset of `where`), are kept
521 when `where` matches and the subject may read them, then counted.
522
523 With permissions enforced (`object_access.enforcement_enabled`), each
524 row is judged as the subject may read it (`Access.readable`, the record
525 API's row decision and field redaction): a row they may not read is not
526 counted, a `where` condition on a field they may not read in that row is
527 false, and the detail is computed from the readable fields only
528 (`_detail`). So the count is "rows where this field, which you can see,
529 matches", never a number derived from a field the record API would not
530 show them. With enforcement off or audit-only the record API serves
531 every field, and the count is the row-level one it always was. If the
532 mode cannot be determined, nothing is counted.
533
534 A collection that is not installed counts zero, the posture every
535 provider took (a deployment without the app has no such queue). Any
536 other storage error propagates: an unreadable collection is not an
537 empty queue.
538 """
539 try:
540 enforcing = object_access.enforcement_enabled()
541 except Exception: # noqa: BLE001 - mode unknown: count nothing
542 return {"count": 0, "detail": ""}
543 now = now or datetime.now(timezone.utc)
544 today = now.astimezone().date() if now.tzinfo else now.date()
545 collection = declaration["collection"]
546 settings: dict[str, int] = {}
547 where = _resolve_settings(declaration["where"], base_dir=base_dir, cache=settings)
548 parts = [{**part, "where": _resolve_settings(part["where"], base_dir=base_dir, cache=settings)}
549 if part.get("where") else part
550 for part in declaration.get("detail") or ()]
551 lookups = _equality_lookups(where)
552 groups = (tuple(((field, values),) for field, values in lookups),) if lookups else None
553 try:
554 rows, _narrowed = object_records.read_collection_records_for_plan(
555 collection, groups, base_dir=base_dir)
556 except (object_collections.CollectionNotFoundError,
557 object_collections.InvalidCollectionNameError):
558 return {"count": 0, "detail": ""}
559 subject = access.subject
560 compiled = _split_where(where)
561 matched = [row for row in rows if _matches(row, compiled, subject, now=now, today=today)]
562 if not enforcing:
563 visible = access.visible(collection, matched)
564 if not visible:
565 return {"count": 0, "detail": ""}
566 return {"count": len(visible),
567 "detail": _detail(parts, visible, subject, now=now, today=today)}
568 # Enforced. A row that matches as stored and whose `where` fields are all
569 # readable matches as read too (the values are the same ones), so the
570 # stored match above is only a cheaper first cut: the decision is the
571 # readable view's.
572 views: list[Mapping[str, Any]] = []
573 hidden: list[frozenset[str]] = []
574 for row in matched:
575 view = access.readable(collection, row)
576 if view is None:
577 continue
578 unread = frozenset(field for field in row if field not in view)
579 if any(field in unread for field in where):
580 continue
581 views.append(view)
582 hidden.append(unread)
583 if not views:
584 return {"count": 0, "detail": ""}
585 return {"count": len(views),
586 "detail": _detail(parts, views, subject, now=now, today=today, hidden=hidden)}
587
588
589def parse_reads(reads: Any) -> list[str]:
590 """A code provider's `reads`, validated: the collections its number is
591 folded from, in the order given, without repeats. None/empty is none."""
592 if reads in (None, "", []):
593 return []
594 if not isinstance(reads, list) or not all(
595 isinstance(name, str) and _COLLECTION_RE.fullmatch(name) for name in reads):
596 raise InvalidDeclarationError("reads must be a list of collection names")
597 return list(dict.fromkeys(reads))
598
599
600def _installed(collection: str, base_dir: Path | str) -> bool:
601 return (object_records.collection_has_records(collection, base_dir=base_dir)
602 or (Path(base_dir) / "schemas" / f"{collection}.json").is_file())
603
604
605def provider_shown_to(access: object_access.Access, source: Mapping[str, Any] | None, *,
606 base_dir: Path | str) -> bool:
607 """May this viewer be shown a code provider's stored number?
608
609 That number was folded by the daemon with no viewer, over every row of
610 the collections the provider reads, so it may only reach someone those
611 rows could reach whole: every collection in the source's `reads` that
612 this box has must be one the viewer reads every row of
613 (`Access.reads_every_row`). Fail closed: an admin always may (they read
614 everything anyway); otherwise a source with no `reads` -- a package
615 from before the key, or one that never said -- a `reads` that does not
616 parse, or an orphaned count with no source at all is shown to nobody
617 but an admin. A collection the box does not have holds no rows, so it
618 is skipped; a source all of whose collections are absent is hidden.
619
620 "Whole" includes the schema's field permissions, which
621 `reads_every_row` (rules only) does not look at. With permissions
622 enforced, a listed collection whose schema could hide any field from
623 this viewer in some row (`_schema_may_hide`) hides the number from them:
624 the provider does not say which fields it folds, so any hidden field
625 might be one it counted or described. That holds for an admin too -- the
626 record API redacts a schema-hidden field for an admin like anyone else
627 -- for the collections `reads` names; a source with no `reads` names
628 nothing to check and stays admin-only. With enforcement off no field is
629 redacted anywhere and this check is skipped; if the mode cannot be
630 determined, nobody is shown the number.
631 """
632 try:
633 enforcing = object_access.enforcement_enabled()
634 except Exception: # noqa: BLE001 - mode unknown: show nothing
635 return False
636 reads: list[str] | None = None
637 if source is not None:
638 try:
639 reads = parse_reads(json.loads(_text(source.get("reads")) or "[]"))
640 except (ValueError, InvalidDeclarationError):
641 reads = None
642 present = [name for name in reads or () if _installed(name, base_dir)]
643 if enforcing and any(_schema_may_hide(access, name) for name in present):
644 return False
645 if access.is_admin:
646 return True
647 if source is None or reads is None or not access.signed_in:
648 return False
649 return bool(present) and all(access.reads_every_row(name) for name in present)
650
651
652def _schema_may_hide(access: object_access.Access, collection: str) -> bool:
653 """Could a schema field permission hide a field of ``collection`` from
654 this viewer in some row (object_field_permissions.may_hide_a_field)?
655 True when it cannot be ruled out, an unreadable policy included."""
656 if access.policy is None:
657 return True
658 return object_field_permissions.may_hide_a_field(
659 collection, subject=access.subject, policy=access.policy, base_dir=access.base_dir)
660
661
662def _read(collection: str, base_dir: Path | str) -> list[dict[str, Any]] | None:
663 try:
664 return object_records.read_collection_records(collection, base_dir=base_dir)
665 except (object_collections.CollectionNotFoundError,
666 object_collections.InvalidCollectionNameError):
667 return None
668
669
670def rows_for(identity: Mapping[str, Any] | None, *, base_dir: Path | str,
671 now: datetime | None = None) -> list[dict[str, Any]]:
672 """Every attention row this viewer is shown, before sorting and zeros.
673
674 Code providers: their stored `attention_counts` row, only to a viewer
675 `provider_shown_to` allows (it used to reach every signed-in user).
676 Declared sources: counted now, for this viewer (`count`), and any stored
677 row for them ignored -- one written by a provider this declaration
678 replaced, before the upgrade, is a global number this viewer may not be
679 entitled to. A muted declared source is not counted. A declared row
680 whose stored JSON no longer parses, or whose collection cannot be read,
681 is left out: it is refused rather than shown as a number nobody
682 computed (the daemon reports a provider's failures; a hand-broken
683 declaration is visible in the registry it was broken in).
684
685 Anonymous viewers get nothing: these are internal work queues.
686 """
687 if not _text((identity or {}).get("user_id")):
688 return []
689 sources = _read(SOURCES_COLLECTION, base_dir) or []
690 stored = _read(COUNTS_COLLECTION, base_dir) or []
691 now = now or datetime.now(timezone.utc)
692
693 declared: dict[str, tuple[Mapping[str, Any], dict[str, Any] | None]] = {}
694 providers: dict[str, Mapping[str, Any]] = {}
695 for source in sources:
696 source_id = _text(source.get("id"))
697 if not source_id:
698 continue
699 if not _text(source.get("collection")):
700 providers[source_id] = source
701 continue
702 try:
703 declared[source_id] = (source, declaration_from_source(source))
704 except InvalidDeclarationError:
705 declared[source_id] = (source, None)
706
707 access = object_access.Access(identity, base_dir=base_dir)
708 rows = [dict(row) for row in stored
709 if _text(row.get("id")) not in declared
710 and provider_shown_to(access, providers.get(_text(row.get("id"))), base_dir=base_dir)]
711 if not declared:
712 return rows
713
714 computed_at = now.isoformat()
715 for source_id, (source, declaration) in declared.items():
716 if declaration is None or _text(source.get("operator_muted")).lower() in _TRUE:
717 continue
718 try:
719 answer = count(declaration, access, base_dir=base_dir, now=now)
720 except (OSError, ValueError, LookupError):
721 continue
722 rows.append({
723 "id": source_id,
724 "source_id": source_id,
725 "label": _text(source.get("label")),
726 "path": _text(source.get("path")),
727 "nav_id": _text(source.get("nav_id")),
728 "group": _text(source.get("group")) or "Apps",
729 "severity": _text(source.get("severity")) or "normal",
730 "count": str(answer["count"]),
731 "detail": answer["detail"],
732 "computed_at": computed_at,
733 "error": "",
734 })
735 return rows