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
flow.py · 10.5 KB · 227 lines
1"""site_flow -- the workflow, viewable: /flow and /flow/{collection}.
2
3Dan's observation, which most web software never answered: apps forgot
4help, and frameworks forgot docs. The reason was structural -- their
5workflow existed only as the union of whatever every callback did, so any
6documentation was hand-written and rotting from the moment it was saved.
7Here the workflow is COMPILED (object_governance.py): transitions and
8guards from the schema, the gate the schema names, reactions from HANDLES
9declarations, notify rules and schedules from data. This page renders that
10compilation live, so the docs cannot disagree with the system -- they are
11the system, read back.
12
13Per collection: the state machine drawn as SVG (server-side, zero JS
14dependencies -- a diagram that needs a CDN is a diagram that breaks),
15every transition with its guard, what gates writes, what the record layer
16refuses inside the write lock (`unique` keys, `locked_when` freezes), what reacts, what gets
17composed, who gets notified, when the clock touches it, and where it
18renders. Plus the Mermaid source in a copy block, because the same text
19pastes into GitHub, docs, or a whiteboard tool.
20
21Signed-in users only: the picture of how money moves through a system is
22itself information about the system. No per-collection secrets are shown
23beyond what the schema API already exposes, but the assembled map deserves
24the same courtesy as the data it describes.
25"""
26
27import html
28import math
29import os
30
31import object_governance
32import object_schemas
33
34_PAGE_ROOTS = None # objects run from the server's roots; governance reads the same
35
36
37def _base_dir():
38 return os.environ.get("DBBASIC_DATA_DIR", "data")
39
40
41def _esc(value):
42 return html.escape(str(value or ""))
43
44
45def _state_svg(transitions):
46 """The state machine as a self-contained SVG.
47
48 Hand-laid layout: states ring-positioned, edges as straight lines with
49 small labels. Deliberately simple -- a six-state machine reads fine on
50 a ring, and a machine too tangled for this picture is feedback about
51 the machine, not the renderer.
52 """
53 if not transitions:
54 return ""
55 field, moves = next(iter(transitions.items()))
56 states = sorted({s for s in moves} |
57 {t["to"] for targets in moves.values() for t in targets if t["to"]})
58 n = len(states)
59 if not n:
60 return ""
61 width, height = 640, max(300, 90 * n // 2 + 160)
62 cx, cy = width / 2, height / 2
63 radius = min(cx, cy) - 70
64 pos = {}
65 for i, state in enumerate(states):
66 angle = (2 * math.pi * i / n) - math.pi / 2
67 pos[state] = (cx + radius * math.cos(angle), cy + radius * math.sin(angle))
68
69 parts = [f'<svg viewBox="0 0 {width} {height}" role="img" '
70 f'style="max-width:100%;height:auto;background:var(--panel,#1a1a22);'
71 f'border:1px solid var(--line,#333);border-radius:8px">']
72 parts.append('<defs><marker id="arr" markerWidth="8" markerHeight="8" refX="7" refY="3" '
73 'orient="auto"><path d="M0,0 L7,3 L0,6 z" fill="currentColor"/></marker></defs>')
74 for state, targets in moves.items():
75 x1, y1 = pos[state]
76 for target in targets:
77 if not target["to"] or target["to"] not in pos:
78 continue
79 x2, y2 = pos[target["to"]]
80 dx, dy = x2 - x1, y2 - y1
81 dist = math.hypot(dx, dy) or 1
82 # stop the line at the node's edge so the arrowhead is visible
83 sx, sy = x1 + dx / dist * 34, y1 + dy / dist * 34
84 ex, ey = x2 - dx / dist * 38, y2 - dy / dist * 38
85 parts.append(f'<line x1="{sx:.0f}" y1="{sy:.0f}" x2="{ex:.0f}" y2="{ey:.0f}" '
86 f'stroke="currentColor" stroke-opacity="0.55" marker-end="url(#arr)"/>')
87 for state in states:
88 x, y = pos[state]
89 parts.append(f'<g><circle cx="{x:.0f}" cy="{y:.0f}" r="32" fill="none" '
90 f'stroke="currentColor" stroke-opacity="0.9"/>'
91 f'<text x="{x:.0f}" y="{y:.0f}" text-anchor="middle" dominant-baseline="middle" '
92 f'fill="currentColor" font-size="12">{_esc(state)}</text></g>')
93 parts.append(f'<text x="{width - 10}" y="{height - 10}" text-anchor="end" fill="currentColor" '
94 f'fill-opacity="0.5" font-size="11">{_esc(field)}</text>')
95 parts.append("</svg>")
96 return "".join(parts)
97
98
99def _rows(items, render, empty="none"):
100 return "".join(render(item) for item in items) or \
101 f'<tr><td colspan="9" class="muted">{_esc(empty)}</td></tr>'
102
103
104def _codes(names):
105 return ", ".join(f"<code>{_esc(name)}</code>" for name in names)
106
107
108def _unique_row(rule):
109 """One schema `unique` constraint, in the words a refused writer meets."""
110 key = _codes(rule.get("fields") or [])
111 if rule.get("scope"):
112 key += f" per {_codes(rule['scope'])}"
113 if rule.get("ignore_case"):
114 key += " <span class='muted'>(ignoring case)</span>"
115 return (f"<tr><td>Unique</td><td>{key}</td>"
116 f"<td class='muted'>{_esc(rule.get('message'))}</td></tr>")
117
118
119def _locked_row(rule):
120 """One schema `locked_when` rule: when a record is settled, and what
121 may still change on it."""
122 when = " and ".join(
123 f"<code>{_esc(name)}</code> is {_esc(' or '.join(values) or 'blank')}"
124 for name, values in (rule.get("when") or {}).items())
125 allowed = rule.get("except") or []
126 rest = (f"may still change: {_codes(allowed)}" if allowed
127 else "nothing may change")
128 rest += "; can be deleted" if rule.get("allow_delete") else "; cannot be deleted"
129 return (f"<tr><td>Frozen when {when}</td><td>{rest}</td>"
130 f"<td class='muted'>{_esc(rule.get('message'))}</td></tr>")
131
132
133def _collection_page(collection, base):
134 info = object_governance.governs(collection, base_dir=base)
135 mermaid = object_governance.workflow_mermaid(collection, base_dir=base)
136 decl = info["declarations"]
137
138 transitions_rows = []
139 for field, moves in decl["transitions"].items():
140 for state, targets in moves.items():
141 for target in targets:
142 guard = ", ".join(f"{k} = {v}" for k, v in (target["when"] or {}).items()) or "anyone with write access"
143 transitions_rows.append(
144 f"<tr><td><code>{_esc(state)}</code> &rarr; <code>{_esc(target['to'])}</code></td>"
145 f"<td>{_esc(guard)}</td></tr>")
146 body = f"""
147<div class="breadcrumb"><a href="/">Home</a> / <a href="/flow">Flow</a> / {_esc(collection)}</div>
148<h1>How <code>{_esc(collection)}</code> works</h1>
149<p class="muted">Compiled from the schema, hooks, handlers and rules the server actually
150enforces &mdash; this page cannot disagree with the system, because it is the system, read back.</p>
151{_state_svg(decl["transitions"])}
152<h2>Transitions &amp; who may make them</h2>
153<table><thead><tr><th>Move</th><th>Guard</th></tr></thead>
154<tbody>{''.join(transitions_rows) or '<tr><td colspan="2" class="muted">no state machine — plain records</td></tr>'}</tbody></table>
155<h2>Gates (before the write, fail closed)</h2>
156<table><tbody>{_rows(info["gates"], lambda g: f"<tr><td><code>{_esc(g['object_id'])}</code></td><td>{_esc(g['note'])}</td></tr>")}</tbody></table>
157<h2>Inside the write lock (every writer, nobody exempt)</h2>
158<table><tbody>{_rows(decl.get("unique") or [], _unique_row, "no unique keys")}{_rows(decl.get("locked_when") or [], _locked_row, "nothing frozen")}</tbody></table>
159<h2>Reactions (after the write, never block it)</h2>
160<table><tbody>{_rows(info["reactions"], lambda r: f"<tr><td><code>{_esc(r['object_id'])}</code></td><td>on {_esc(r['on'])}</td></tr>")}</tbody></table>
161<h2>Composes into</h2>
162<table><tbody>{_rows(info["feeds"], lambda f: f"<tr><td><code>{_esc(f)}</code> <span class='muted'>(stamped generated_from)</span></td></tr>")}</tbody></table>
163<h2>Notifications</h2>
164<table><tbody>{_rows(info["notifications"], lambda n: f"<tr><td>{_esc(n['event'])}</td><td>{_esc(n['recipients'])}</td></tr>")}</tbody></table>
165<h2>Derived fields</h2>
166<table><tbody>{_rows(list(decl["formulas"].items()) + list(decl["rollups"].items()), lambda kv: f"<tr><td><code>{_esc(kv[0])}</code></td><td><code>{_esc(kv[1])}</code></td></tr>")}</tbody></table>
167<h2>Rendered at</h2>
168<table><tbody>{_rows(info["views"], lambda v: f"<tr><td><a href='{_esc(v['route'] or '')}'>{_esc(v['route'] or v['view'])}</a></td></tr>")}</tbody></table>
169<h2>Mermaid source</h2>
170<p class="muted">The same diagram as text &mdash; paste it into GitHub, docs, or any tool that speaks Mermaid.</p>
171<pre style="overflow-x:auto">{_esc(mermaid)}</pre>
172"""
173 return body
174
175
176def _index_page(base):
177 items = []
178 for summary in object_schemas.list_schemas(base_dir=base):
179 name = summary.get("name") or summary.get("collection")
180 if not name:
181 continue
182 items.append(f'<li><a href="/flow/{_esc(name)}"><code>{_esc(name)}</code></a></li>')
183 return f"""
184<div class="breadcrumb"><a href="/">Home</a> / Flow</div>
185<h1>How things work</h1>
186<p class="muted">One page per collection: its state machine, who may move it, what gates
187writes, what reacts, what gets composed, and where it renders &mdash; compiled live from
188the declarations the server enforces. The docs most systems forgot, generated so they
189cannot rot.</p>
190<ul class="accountlist">{''.join(sorted(items))}</ul>
191"""
192
193
194def GET(request):
195 identity = request.get("_identity") or {}
196 if not identity.get("user_id"):
197 body = ('<p class="hint"><a href="/login?next=/flow">Sign in</a> to see how the '
198 "system's collections work &mdash; their state machines, gates, and reactions.</p>")
199 else:
200 base = _base_dir()
201 collection = str(request.get("collection") or "").strip()
202 if collection and object_schemas.validate_schema_name(collection):
203 body = _collection_page(collection, base)
204 else:
205 body = _index_page(base)
206
207 return {"content_type": "text/html; charset=utf-8", "body": f"""<!doctype html>
208<html lang="en">
209<head>
210<meta charset="utf-8">
211<meta name="viewport" content="width=device-width, initial-scale=1">
212<title>Flow</title>
213<link rel="stylesheet" href="/style">
214<style>
215.wrap {{ max-width: 900px; margin: 0 auto; padding: 1.25rem; }}
216table {{ width: 100%; border-collapse: collapse; margin: 0.25rem 0 1rem; }}
217td, th {{ text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line, #333); }}
218h2 {{ font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted, #999); margin: 1.25rem 0 0.25rem; }}
219.muted {{ color: var(--muted, #999); }}
220svg {{ margin: 0.75rem 0; color: var(--text, #eee); }}
221</style>
222</head>
223<body>
224<script src="/nav"></script>
225<div class="wrap">{body}</div>
226</body>
227</html>"""}