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

9 downloads

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, 49 minutes ago History
nav_entries.py · 10.6 KB · 266 lines
1"""action_nav_entries -- the doors this caller may be shown, grouped.
2
3POST/GET {} -> {ok, groups: [{group, entries: [...]}], attention: [...], count}
4
5Every navigation surface on this server is meant to be a FOLD over one
6registry rather than a list somebody maintains: the app switcher in
7site_nav, the tile grid on site_home, and anything built next. This is
8that fold, and it lives in an object rather than in each surface because
9the visibility rule -- who is allowed to SEE a door -- is a rule, and a
10rule copied into two renderers is a rule that will be enforced two
11different ways within a year.
12
13Three tiers, decided here once:
14
15- `public` entries are returned to anyone, signed in or not.
16- `member` entries need a signed-in identity.
17- `operator` entries need an admin role, the same check system_scheduler
18 makes before it will draw the task board.
19
20Two kinds of row are never returned at all: `surface: hidden` (the
21package registered a door it does not want rendered) and
22`operator_hidden` (the operator took it off this deployment's menu). The
23second is the reason they are separate columns -- the package says what
24the app IS, the operator says what they want to SEE, and an install
25restates the first without ever touching the second.
26
27This is a MENU, not a gate. Permissions decide who may actually open a
28page; leaving a door off the menu hides nothing that was not already
29protected, and putting one on it grants nothing.
30
31It also carries the ATTENTION counts, because they are the cheapest half
32of a home screen and belong on a list people already look at: an entry
33whose queue is non-empty comes back with `count`, `detail` and
34`severity`, so the app list reads "Invoices - 5 overdue" with no second
35surface to maintain. A code provider's number is read from
36`attention_counts`, the small table the daemon's rollup writes, and
37returned only to a caller who may read every row it was folded from
38(object_attention.provider_shown_to: it is everybody's number); a
39declared count (`collection` + `where`) is counted for this caller by
40object_attention, through the field index and the permission engine, so
41it reads the queue and never folds the collection -- which is the rule
42that keeps this object's cost flat as packages are installed.
43
44**Zero contributes nothing.** A row whose count is zero is dropped
45entirely rather than returned as a zero, because an empty queue is not
46news, and a surface that is handed zeros will eventually render them.
47"""
48
49import os
50
51import object_attention
52import object_records
53
54ACTOR = "action_nav_entries"
55
56_DEFAULT_GROUP = "Apps"
57_DEFAULT_ORDER = 100
58_TRUE = ("true", "1", "yes", "on")
59
60# Loudest first on every surface that sorts by it. Three steps, because a
61# scale with more is a scale nobody calibrates.
62_SEVERITY_RANK = {"urgent": 0, "warning": 1, "normal": 2}
63_DEFAULT_SEVERITY = "normal"
64
65
66def _base_dir():
67 return os.environ.get("DBBASIC_DATA_DIR", "data")
68
69
70def _text(value):
71 return str(value if value is not None else "").strip()
72
73
74def _order(row):
75 try:
76 return int(_text(row.get("order")) or _DEFAULT_ORDER)
77 except (TypeError, ValueError):
78 # A hand-edited order that will not parse sorts to the back
79 # rather than taking the whole menu down with it.
80 return _DEFAULT_ORDER
81
82
83def _visible_surfaces(identity):
84 """Which tiers this caller may be shown.
85
86 An anonymous visitor sees the public web; any signed-in user is a
87 member; an admin role additionally sees the operator surfaces. The
88 admin test is `"admin" in identity["roles"]`, copied from
89 system_scheduler rather than reinvented, so there is one answer on
90 this server to "is this an operator?".
91 """
92 identity = identity or {}
93 surfaces = {"public"}
94 if _text(identity.get("user_id")):
95 surfaces.add("member")
96 if "admin" in (identity.get("roles") or []):
97 surfaces.add("operator")
98 return surfaces
99
100
101def _count(row):
102 try:
103 return int(_text(row.get("count")) or 0)
104 except (TypeError, ValueError):
105 # A hand-edited count that will not parse is not a queue of
106 # unknown size, it is a broken cell: it contributes nothing rather
107 # than taking the whole menu down with it.
108 return 0
109
110
111def _attention_rows(identity):
112 """Every non-zero attention count this caller is entitled to see.
113
114 Sorted loudest first: severity, then size, then label. That order is
115 decided here rather than in each renderer for the same reason the
116 visibility tiers are -- a rule copied into two surfaces is a rule that
117 will be enforced two different ways within a year.
118
119 Anonymous visitors get nothing at all. These are internal work
120 queues, and how many receipts are unconfirmed is a fact about how a
121 business is running, not part of the public web. Rows that name a
122 nav entry are additionally held to that entry's own tier, so an
123 operator-only door does not leak a count to a member.
124 """
125 if not _text((identity or {}).get("user_id")):
126 return []
127 try:
128 # The rolled-up rows of code providers, plus every declared count
129 # (`collection` + `where`) counted for THIS caller over the rows
130 # the permission engine lets them read -- object_attention says
131 # why those are not rolled up.
132 rows = object_attention.rows_for(identity, base_dir=_base_dir())
133 except Exception:
134 # The rollup is not installed, or has never run. No counts is a
135 # real answer and exactly what "nothing needs you" looks like.
136 return []
137
138 attention = []
139 for row in rows:
140 count = _count(row)
141 if count <= 0:
142 continue # an empty queue is not news
143 severity = _text(row.get("severity")).lower() or _DEFAULT_SEVERITY
144 attention.append({
145 "id": _text(row.get("id")),
146 "label": _text(row.get("label")),
147 "path": _text(row.get("path")),
148 "nav_id": _text(row.get("nav_id")),
149 "group": _text(row.get("group")) or _DEFAULT_GROUP,
150 "severity": severity,
151 "count": count,
152 "detail": _text(row.get("detail")),
153 "computed_at": _text(row.get("computed_at")),
154 "error": _text(row.get("error")),
155 })
156 attention.sort(key=lambda row: (_SEVERITY_RANK.get(row["severity"], 9),
157 -row["count"], row["label"]))
158 return attention
159
160
161def _decorate(entries, attention):
162 """Hang each entry's queue total on it, in place.
163
164 One badge per door, and it is the SUM of every queue that names the
165 door: a user with one owned and one assigned item, as two sources on
166 one `nav_id`, is shown 2, not whichever queue sorted first. Until
167 2026-11 the louder source won and the other was silently dropped,
168 which made a door under-report exactly when it had two reasons to be
169 opened. The badge takes the loudest severity among its queues and
170 their `detail` sentences joined in that same loudest-first order
171 (`attention` arrives sorted that way); the separate rows, with their
172 own counts, are still all in `attention` for the home band.
173 """
174 by_nav = {}
175 for row in attention:
176 if row["nav_id"]:
177 by_nav.setdefault(row["nav_id"], []).append(row)
178 for entry in entries:
179 rows = by_nav.get(entry["id"])
180 if not rows:
181 continue
182 entry["count"] = sum(row["count"] for row in rows)
183 entry["detail"] = "; ".join(row["detail"] for row in rows if row["detail"])
184 entry["severity"] = rows[0]["severity"]
185
186
187def _entries(request):
188 identity = request.get("_identity") or {}
189 surfaces = _visible_surfaces(identity)
190 try:
191 # access: menu entries filtered by the surfaces the caller's identity may see
192 rows = object_records.read_collection_records("nav_entries", base_dir=_base_dir())
193 except Exception:
194 # The registry is not installed yet. An empty menu is a real
195 # answer; the callers fall back to their own shipped list.
196 return []
197
198 visible = []
199 for row in rows:
200 if _text(row.get("operator_hidden")).lower() in _TRUE:
201 continue
202 surface = _text(row.get("surface")).lower() or "member"
203 if surface not in surfaces:
204 continue
205 path = _text(row.get("path"))
206 if not path:
207 continue
208 visible.append({
209 "id": _text(row.get("id")),
210 "label": _text(row.get("label")) or path,
211 "path": path,
212 "blurb": _text(row.get("blurb")),
213 "group": _text(row.get("group")) or _DEFAULT_GROUP,
214 "surface": surface,
215 "order": _order(row),
216 "package": _text(row.get("package")),
217 })
218
219 # A group sorts where its earliest entry sorts. Packages band their
220 # `order` values (Work in the 0s, Publishing the 200s, Money the
221 # 300s, and so on), so the reading order of the menu falls out of the
222 # same number that orders entries within a group -- rather than out
223 # of the alphabet, which would put System before Work, or out of a
224 # hardcoded group table, which would be a fourth list to maintain.
225 rank = {}
226 for entry in visible:
227 group = entry["group"]
228 rank[group] = min(rank.get(group, entry["order"]), entry["order"])
229 visible.sort(key=lambda entry: (rank[entry["group"]], entry["group"],
230 entry["order"], entry["label"]))
231 return visible
232
233
234def _grouped(entries):
235 """Group-preserving fold over an already-sorted list.
236
237 The sort put every group together, so grouping is one pass and the
238 group order is the sort's order -- no second sort key to disagree
239 with the first one.
240 """
241 groups = []
242 for entry in entries:
243 if not groups or groups[-1]["group"] != entry["group"]:
244 groups.append({"group": entry["group"], "entries": []})
245 groups[-1]["entries"].append(entry)
246 return groups
247
248
249def POST(request):
250 entries = _entries(request)
251 attention = _attention_rows(request.get("_identity") or {})
252 # A count attached to a door nobody may see would leak the door. The
253 # visible set is already decided above, so the filter is a membership
254 # test rather than a second copy of the tier rule.
255 visible_ids = {entry["id"] for entry in entries}
256 attention = [row for row in attention
257 if not row["nav_id"] or row["nav_id"] in visible_ids]
258 _decorate(entries, attention)
259 return {"ok": True, "groups": _grouped(entries), "entries": entries,
260 "attention": attention, "count": len(entries)}
261
262
263def GET(request):
264 # Same answer either way: reading the menu is a read. GET is what the
265 # nav script fetches; POST is what a sibling object calls in-process.
266 return POST(request)