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_site_routes.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_site_routes.py · 6.4 KB · 186 lines
1"""Site routing: clean public URLs resolved to DBBASIC objects.
2
3Design (see docs/site-routing.md for the full rationale):
4
5- Convention first: `/about` maps to object `site_about`, `/docs/install` to
6 `site_docs_install`, and `/` to `site_home`. Creating a page object creates
7 its URL, like filesystem routing, with hyphens translated to underscores.
8- Data overrides second: a `site_routes` records collection maps URL patterns
9 to objects for what conventions cannot express — parameterized routes like
10 `/articles/{article_id:uuid}` — with schema validation, change history, and
11 rollback from the existing records machinery.
12- Routing only maps URLs. Authorization stays in the permission policy: the
13 resolved object runs through the normal execution path, so enforcement,
14 audit, timeouts, and correlation ids all apply.
15
16Pattern segments: literal text, `{name}` (any single segment), or
17`{name:uuid}` (segment must be UUID-shaped). Captured params are merged into
18the object's request payload.
19"""
20
21from __future__ import annotations
22
23import re
24from typing import Any, Iterable, Mapping
25
26SITE_ROUTES_COLLECTION = "site_routes"
27SITE_HOSTS_COLLECTION = "site_hosts"
28DEFAULT_PREFIX = "site"
29ROOT_OBJECT_ID = "site_home"
30NOT_FOUND_OBJECT_ID = "site_404"
31SITE_OBJECT_PREFIX = "site_"
32
33_SEGMENT_RE = re.compile(r"^[A-Za-z0-9_-]+$")
34_PREFIX_RE = re.compile(r"^[a-z0-9][a-z0-9_]{0,63}$")
35_PARAM_RE = re.compile(r"^\{([A-Za-z_][A-Za-z0-9_]*)(?::(uuid))?\}$")
36_UUID_RE = re.compile(
37 r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
38)
39
40
41def normalize_host(value: str | None) -> str:
42 """Lowercase one Host header value and strip any port."""
43 host = (value or "").strip().lower()
44 if host.startswith("["):
45 return host.partition("]")[0].lstrip("[")
46 return host.partition(":")[0]
47
48
49def resolve_host(
50 host: str | None,
51 records: Iterable[Mapping[str, Any]],
52) -> dict[str, str]:
53 """Return the site config for one request host.
54
55 `site_hosts` records carry `host`, `prefix`, and optional `home_object`
56 and `not_found_object`. Hosts without a record keep the default `site_*`
57 behavior, so a single-site deployment needs no configuration.
58 """
59 normalized = normalize_host(host)
60 for record in records:
61 record_host = normalize_host(str(record.get("host") or ""))
62 prefix = str(record.get("prefix") or "").strip()
63 if not record_host or record_host != normalized:
64 continue
65 if not _PREFIX_RE.fullmatch(prefix):
66 continue
67 home = str(record.get("home_object") or "").strip() or f"{prefix}_home"
68 not_found = str(record.get("not_found_object") or "").strip() or f"{prefix}_404"
69 return {"host": record_host, "prefix": prefix, "home": home, "not_found": not_found}
70
71 return {
72 "host": normalized,
73 "prefix": DEFAULT_PREFIX,
74 "home": ROOT_OBJECT_ID,
75 "not_found": NOT_FOUND_OBJECT_ID,
76 }
77
78
79def convention_object_id(path: str, *, prefix: str = DEFAULT_PREFIX, home: str | None = None) -> str | None:
80 """Map one URL path to its conventional site object id, or None."""
81 if path == "/":
82 return home or f"{prefix}_home"
83
84 segments = _path_segments(path)
85 if segments is None or not segments:
86 return None
87
88 parts = []
89 for segment in segments:
90 if not _SEGMENT_RE.fullmatch(segment):
91 return None
92 parts.append(segment.replace("-", "_"))
93 return f"{prefix}_" + "_".join(parts)
94
95
96def match_records(
97 path: str,
98 records: Iterable[Mapping[str, Any]],
99 *,
100 host: str | None = None,
101) -> tuple[str, dict[str, str]] | None:
102 """Match one path against site_routes records; most specific pattern wins.
103
104 Records with a `host` value only match that host; records without one
105 match every host. Host-specific matches beat host-agnostic ones.
106 """
107 segments = _path_segments(path)
108 if segments is None:
109 return None
110
111 normalized_host = normalize_host(host)
112 candidates = []
113 for record in records:
114 pattern = record.get("pattern")
115 object_id = record.get("object_id")
116 if not isinstance(pattern, str) or not isinstance(object_id, str):
117 continue
118 if not pattern.startswith("/") or not object_id.strip():
119 continue
120 record_host = normalize_host(str(record.get("host") or ""))
121 if record_host and record_host != normalized_host:
122 continue
123 parsed = _parse_pattern(pattern)
124 if parsed is None:
125 continue
126 params = _match_segments(parsed, segments)
127 if params is None:
128 continue
129 literal_count = sum(1 for kind, _, _ in parsed if kind == "literal")
130 priority = record.get("priority")
131 try:
132 priority_value = int(priority) if priority not in (None, "") else 100
133 except (TypeError, ValueError):
134 priority_value = 100
135 host_rank = 0 if record_host else 1
136 candidates.append((host_rank, priority_value, -literal_count, object_id.strip(), params))
137
138 if not candidates:
139 return None
140
141 candidates.sort(key=lambda item: (item[0], item[1], item[2]))
142 _, _, _, object_id, params = candidates[0]
143 return object_id, params
144
145
146def _path_segments(path: str) -> list[str] | None:
147 if not path.startswith("/") or "\\" in path or "\x00" in path:
148 return None
149 segments = [segment for segment in path.split("/") if segment]
150 if any(segment in {".", ".."} for segment in segments):
151 return None
152 return segments
153
154
155def _parse_pattern(pattern: str) -> list[tuple[str, str, str]] | None:
156 parsed: list[tuple[str, str, str]] = []
157 for raw in pattern.split("/"):
158 if not raw:
159 continue
160 param = _PARAM_RE.fullmatch(raw)
161 if param is not None:
162 parsed.append(("param", param.group(1), param.group(2) or ""))
163 else:
164 parsed.append(("literal", raw, ""))
165 if not parsed:
166 return None
167 return parsed
168
169
170def _match_segments(
171 parsed: list[tuple[str, str, str]],
172 segments: list[str],
173) -> dict[str, str] | None:
174 if len(parsed) != len(segments):
175 return None
176
177 params: dict[str, str] = {}
178 for (kind, value, constraint), segment in zip(parsed, segments):
179 if kind == "literal":
180 if value != segment:
181 return None
182 continue
183 if constraint == "uuid" and not _UUID_RE.fullmatch(segment):
184 return None
185 params[value] = segment
186 return params