interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / scripts / allen / pusher / omega_projects_pusher.py

744 lines · 33613 bytes Raw Blame History
1#!/usr/bin/python3
2"""omega-projects-pusher: files visitor-confirmed Allen spool items on aien-dev/omega-projects.
3
4The public gateway (allen-chat) holds no credential; it only drops validated items into
5spool-in. This program, a separate system user (omega-pusher), is the only holder of
6GitHub write ability. For every spool-in/<id>.json it re-validates the item, checks the
7id, scrubs emails and phone numbers, enforces daily caps, dedupes, then acts once: an
8issue; a save (one commit on u/<handle>); a publish (one commit on p/<handle>/<project>
9and one pull request to main, reused while open); a decline from Drake's console (comment
10and close that pull request); or a refresh. Files land only under
11projects/<handle>/<project>/ (allen_build.py). It never writes main and never merges.
12After build items it rewrites spool-status/index.json (open publish requests, gallery).
13The result goes to spool-status/<id>.json (atomic, 0640); the spool file is then deleted.
14
15Credential: a fine-grained token (github_pat_...) scoped to aien-dev/omega-projects, given
16by systemd as the encrypted credential "omega-projects-token". Without it, or with any
17other kind of token (a gh login is gho_/ghp_), nothing is filed: valid items stay in the
18spool with status queued, reason "awaiting activation".
19
20Python stdlib only. allen_spool.py and allen_build.py are imported from this file's
21directory (installed copy) or from --spool-module-dir (tests).
22"""
23
24import argparse
25import base64
26import datetime
27import fcntl
28import json
29import os
30import re
31import socket
32import stat
33import sys
34import time
35import urllib.error
36import urllib.parse
37import urllib.request
38
39REPO = "aien-dev/omega-projects"
40API = "https://api.github.com"
41# Tests may point the client at a local stub; nothing else is accepted.
42STUB_API = re.compile(r"^http://127\.0\.0\.1:[0-9]{1,5}$")
43FINE_GRAINED = re.compile(r"^github_pat_[A-Za-z0-9_]{20,250}$")
44AWAITING = "awaiting activation"
45REPO_PREFIX = "/repos/" + REPO + "/"
46BACKOFF = (10.0, 20.0, 40.0, 80.0) # seconds before attempts 2..5; attempts = len + 1
47REQUEST_TIMEOUT = 10
48RUN_BUDGET = 100.0 # seconds per run; the unit has TimeoutStartSec=120
49MAX_ITEM_BYTES = 512 * 1024
50FOOTER = "Filed by Aien from aienos.com/aien/ after the visitor confirmed this exact text."
51TITLE_PREFIX = {"feature": "[feature] ", "question": "[question] ", "bug": "[bug] "}
52# Daily caps: kind -> (state key, cap). Decline and refresh come only from Drake's console.
53CAPS = {"issue": ("issues", 40), "publish": ("prs", 20), "save": ("saves", 200)}
54ID_FILE = re.compile(r"^([0-9a-f]{20})\.json$")
55
56spool = None # allen_spool module, bound in main()
57build = None # allen_build module, bound in main()
58
59
60class Refused(Exception):
61 """The content broke a rule: status rejected, never retried."""
62
63
64class GitHubError(Exception):
65 """GitHub did not take a request. `cause` is the honest text shown to the visitor.
66 Retried with backoff; after the last attempt the item's status becomes failed."""
67
68 def __init__(self, cause, status=None):
69 super().__init__(cause)
70 self.cause = cause
71 self.status = status
72
73
74class HTTPRefused(GitHubError):
75 def __init__(self, status, msg=""):
76 if status == 401:
77 cause = "GitHub refused the credential (HTTP 401)"
78 elif status == 429 or (status == 403 and "rate limit" in msg.lower()):
79 cause = "GitHub rate limit (HTTP %d)" % status
80 elif status >= 500:
81 cause = "GitHub server error (HTTP %d)" % status
82 else:
83 cause = "GitHub refused the request (HTTP %d)" % status
84 super().__init__(cause, status)
85
86
87def log(msg):
88 print(msg, file=sys.stderr, flush=True)
89
90
91# ---------------------------------------------------------------- GitHub client
92
93class _NoRedirect(urllib.request.HTTPRedirectHandler):
94 """A redirect would carry the token to another URL; treat it as an error instead."""
95
96 def redirect_request(self, req, fp, code, msg, headers, newurl):
97 return None
98
99
100class GitHub:
101 """Talks to api.github.com for aien-dev/omega-projects only."""
102
103 def __init__(self, token, api=API):
104 if not FINE_GRAINED.match(token or ""):
105 raise ValueError("not a fine-grained token")
106 if api != API and not STUB_API.match(api):
107 raise ValueError("refusing API base %r" % api)
108 self._token = token
109 self._api = api
110 self._open = urllib.request.build_opener(_NoRedirect())
111
112 def call(self, method, path, body=None):
113 _check_request(method, path, body)
114 data = None if body is None else json.dumps(body).encode()
115 req = urllib.request.Request(self._api + path, data=data, method=method)
116 req.add_header("Authorization", "Bearer " + self._token)
117 req.add_header("Accept", "application/vnd.github+json")
118 req.add_header("X-GitHub-Api-Version", "2022-11-28")
119 req.add_header("User-Agent", "omega-projects-pusher")
120 if data is not None:
121 req.add_header("Content-Type", "application/json")
122 try:
123 with self._open.open(req, timeout=REQUEST_TIMEOUT) as r:
124 status, raw = r.status, r.read()
125 except urllib.error.HTTPError as e:
126 status, raw = e.code, e.read()
127 except (TimeoutError, socket.timeout):
128 raise GitHubError("GitHub did not answer within %d s" % REQUEST_TIMEOUT)
129 except urllib.error.URLError as e:
130 if isinstance(e.reason, (TimeoutError, socket.timeout)):
131 raise GitHubError("GitHub did not answer within %d s" % REQUEST_TIMEOUT)
132 raise GitHubError("GitHub could not be reached")
133 except OSError:
134 raise GitHubError("GitHub could not be reached")
135 if status in (200, 201):
136 try:
137 return json.loads(raw) if raw else None
138 except ValueError:
139 raise GitHubError("GitHub sent an unreadable answer")
140 msg = ""
141 try:
142 msg = str(json.loads(raw).get("message", ""))[:200]
143 except (ValueError, AttributeError):
144 pass
145 raise HTTPRefused(status, msg)
146
147
148class GuardRefused(PermissionError):
149 """The request guard refused a call outside the allowed shape."""
150
151
152SAFE_PATH = re.compile(r"^[A-Za-z0-9/_.:%?&=,+-]*$")
153
154
155BUILD_REF = r"(?:u/[a-z0-9-]+|p/[a-z0-9-]+/[a-z0-9-]+)"
156TREE_PATH = re.compile(r"^projects/[a-z0-9-]+/[a-z0-9-]+/[A-Za-z0-9_.-]+$")
157
158
159def _check_request(method, path, body):
160 """Refuse anything outside the one repository and the handful of calls the pusher needs.
161 No call can write main: refs are created or moved only under u/ and p/, never forced, and
162 trees only carry files under projects/<handle>/<project>/."""
163 if not path.startswith(REPO_PREFIX) or ".." in path or "//" in path or not SAFE_PATH.match(path):
164 raise GuardRefused("refusing request outside %s: %s" % (REPO, path))
165 rest = path[len(REPO_PREFIX):].split("?", 1)[0]
166 allowed = {
167 "GET": (r"git/ref/heads/main", r"git/ref/heads/" + BUILD_REF, r"git/commits/[0-9a-f]{40}",
168 r"git/trees/[0-9a-f]{40}", r"git/blobs/[0-9a-f]{40}", r"pulls", r"pulls/[0-9]+", r"issues",
169 r"labels/[A-Za-z0-9:._%-]+"),
170 "POST": (r"issues", r"issues/[0-9]+/labels", r"issues/[0-9]+/comments", r"pulls", r"labels",
171 r"git/blobs", r"git/trees", r"git/commits", r"git/refs"),
172 "PATCH": (r"git/refs/heads/" + BUILD_REF, r"pulls/[0-9]+"),
173 }.get(method, ())
174 if not any(re.fullmatch(p, rest) for p in allowed):
175 raise GuardRefused("refusing %s %s" % (method, rest))
176 body = body or {}
177 if method == "POST" and rest == "git/refs":
178 if not re.fullmatch(r"refs/heads/" + BUILD_REF, body.get("ref", "")):
179 raise GuardRefused("refusing to create ref %r" % body.get("ref"))
180 if method == "PATCH" and rest.startswith("git/refs/") and body.get("force") is not False:
181 raise GuardRefused("refusing a forced ref update")
182 if method == "PATCH" and rest.startswith("pulls/") and body != {"state": "closed"}:
183 raise GuardRefused("refusing pull request change %r" % sorted(body))
184 if method == "POST" and rest == "git/trees":
185 if not all(isinstance(e, dict) and TREE_PATH.match(str(e.get("path", ""))) for e in body.get("tree", [])):
186 raise GuardRefused("refusing a tree entry outside projects/<handle>/<project>/")
187 if method == "POST" and rest == "pulls":
188 if body.get("base") != "main" or not re.fullmatch(r"p/[a-z0-9-]+/[a-z0-9-]+", str(body.get("head", ""))):
189 raise GuardRefused("refusing pull request shape")
190
191
192# ---------------------------------------------------------------- state
193
194class State:
195 """Persisted counters, ledger of filed ids, in-flight markers and attempt counts."""
196
197 def __init__(self, path):
198 self.path = path
199 self.file = os.path.join(path, "state.json")
200 try:
201 with open(self.file, encoding="utf-8") as f:
202 self.d = json.load(f)
203 except FileNotFoundError:
204 self.d = {}
205 for k in ("filed", "pending", "attempts"):
206 self.d.setdefault(k, {})
207 self.d.setdefault("day", "")
208 for k in CAPS.values():
209 self.d.setdefault(k[0], 0)
210
211 def save(self):
212 atomic_write(self.file, self.d)
213
214 def take(self, kind, now=None):
215 """One slot of today's cap for kind; decline and refresh have none."""
216 if kind not in CAPS:
217 return True
218 day = (now or datetime.datetime.now(datetime.timezone.utc)).strftime("%Y-%m-%d")
219 if self.d["day"] != day:
220 self.d.update({"day": day}, **{k: 0 for k, _ in CAPS.values()})
221 key, cap = CAPS[kind]
222 if self.d[key] >= cap:
223 return False
224 self.d[key] += 1
225 self.save()
226 return True
227
228 def give(self, kind):
229 """Return a slot taken by an item that was never filed."""
230 if kind in CAPS and self.d[CAPS[kind][0]] > 0:
231 self.d[CAPS[kind][0]] -= 1
232
233
234def atomic_write(path, obj, mode=0o600):
235 tmp = "%s.tmp-%d" % (path, os.getpid())
236 fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
237 os.fchmod(fd, mode)
238 with os.fdopen(fd, "w", encoding="utf-8") as f:
239 json.dump(obj, f, ensure_ascii=False, sort_keys=True)
240 f.flush()
241 os.fsync(f.fileno())
242 os.rename(tmp, path)
243
244
245def write_status(status_dir, iid, state, url=None, reason=None):
246 # 0640: the gateway reads status through the allen-spool group.
247 atomic_write(os.path.join(status_dir, iid + ".json"),
248 {"id": iid, "state": state, "url": url, "reason": reason}, mode=0o640)
249
250
251def read_status_file(status_dir, iid):
252 try:
253 with open(os.path.join(status_dir, iid + ".json"), encoding="utf-8") as f:
254 return json.load(f)
255 except (OSError, ValueError):
256 return None
257
258
259# ---------------------------------------------------------------- item checks
260
261def load_areas(path):
262 """Known public repository names. Without the file every area becomes 'unknown'."""
263 try:
264 with open(path, encoding="utf-8") as f:
265 return {ln.strip() for ln in f if ln.strip()}
266 except FileNotFoundError:
267 return set()
268
269
270def read_item(path):
271 try:
272 fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
273 except OSError:
274 raise Refused("the item is not a regular file")
275 with os.fdopen(fd, "rb") as f:
276 info = os.fstat(f.fileno())
277 if not stat.S_ISREG(info.st_mode):
278 raise Refused("the item is not a regular file")
279 if info.st_size > MAX_ITEM_BYTES:
280 raise Refused("the item is too large")
281 raw = f.read(MAX_ITEM_BYTES + 1)
282 if len(raw) > MAX_ITEM_BYTES:
283 raise Refused("the item is too large")
284 try:
285 return json.loads(raw.decode("utf-8", errors="strict"))
286 except (UnicodeDecodeError, ValueError):
287 raise Refused("the item is not valid UTF-8 JSON")
288
289
290def check_item(raw, iid, areas):
291 """Return the canonical, scrubbed item or raise Refused."""
292 if spool.item_id(raw) != iid:
293 raise Refused("the item id does not match its content")
294 try:
295 if isinstance(raw, dict) and raw.get("kind") == "issue":
296 item = spool.validate(raw, areas=areas)
297 item["title"] = spool.scrub(item["title"])
298 item["body"] = issue_markdown(spool.scrub(item["body"]))
299 return item
300 item = build.validate(raw)
301 except spool.Invalid as e:
302 raise Refused(str(e))
303 # Prose is scrubbed; code files carrying an email were refused by validate, and Drake
304 # reviews every publish request before anything goes live.
305 return build.scrubbed(item) if item["kind"] in ("save", "publish") else item
306
307
308# ---------------------------------------------------------------- filing
309
310def issue_markdown(text):
311 """Visitor text made inert as GitHub markdown before it is filed under the org: '<' is
312 escaped, so no raw HTML, HTML comment (no planted item marker) or <img>; '![' is escaped, so
313 no markdown image (no tracking pixel); '@' before a name gets a zero-width space, so no
314 mention notifies anyone. Plain links stay, as the security survey F3 allows."""
315 text = text.replace("<", "&lt;").replace("![", "!\\[")
316 return re.sub(r"@(?=[A-Za-z0-9])", "@\u200b", text)
317
318
319def marker(iid):
320 return "<!-- allen-item: %s -->" % iid
321
322
323def ensure_label(gh, name, cache):
324 if name in cache:
325 return
326 try:
327 gh.call("GET", REPO_PREFIX + "labels/" + urllib.parse.quote(name, safe=""))
328 except HTTPRefused as e:
329 if e.status != 404:
330 raise
331 try:
332 gh.call("POST", REPO_PREFIX + "labels",
333 {"name": name, "color": "c5def5",
334 "description": ("Concerns aien-dev/" + name[5:]) if name.startswith("area:") else "Aien"})
335 except HTTPRefused as e2:
336 if e2.status != 422: # 422: created meanwhile
337 raise
338 cache.add(name)
339
340
341def find_issue(gh, iid):
342 """Recover an issue filed before a crash: search recent issues for the id marker. Issues
343 filed before the Aien rename carry from-allen, so a crash across the switch is found too.
344 Only labelled issues (labels need triage rights, so the pusher or a maintainer set them)
345 whose body ENDS with the marker count: file_issue writes it last, and visitor text can no
346 longer carry one (issue_markdown), nor could an older planted one sit at the end."""
347 for label in ("from-aien", "from-allen"):
348 found = gh.call("GET", REPO_PREFIX + "issues?labels=%s&state=all&per_page=100&sort=created&direction=desc"
349 % label)
350 for it in found or []:
351 if (it.get("body") or "").rstrip().endswith(marker(iid)) and "pull_request" not in it:
352 return it["html_url"]
353 return None
354
355
356def file_issue(gh, item, iid, extra_labels, label_cache):
357 area_label = "area:" + item["area"]
358 labels = ["from-aien", area_label] + list(extra_labels)
359 for name in labels:
360 ensure_label(gh, name, label_cache)
361 body = "%s\n\n---\n%s\n%s\n" % (item["body"].rstrip(), FOOTER, marker(iid))
362 r = gh.call("POST", REPO_PREFIX + "issues",
363 {"title": TITLE_PREFIX[item["template"]] + item["title"], "body": body, "labels": labels})
364 return r["html_url"]
365
366
367def _ref(gh, branch):
368 """The branch head sha, or None when the branch does not exist."""
369 try:
370 return gh.call("GET", REPO_PREFIX + "git/ref/heads/" + branch)["object"]["sha"]
371 except HTTPRefused as e:
372 if e.status != 404:
373 raise
374 return None
375
376
377def _dir_blobs(gh, tree_sha, prefix):
378 """{path: blob sha} of every file under prefix/ in a tree (recursive listing)."""
379 t = gh.call("GET", REPO_PREFIX + "git/trees/%s?recursive=1" % tree_sha)
380 if t.get("truncated"):
381 raise GitHubError("the repository tree is too large to list")
382 return {e["path"]: e["sha"] for e in t.get("tree", [])
383 if e.get("type") == "blob" and e["path"].startswith(prefix + "/")}
384
385
386def _project_tree(gh, item, iid, today, base_tree):
387 """A new tree: base_tree with projects/<handle>/<project>/ replaced by exactly the item's files
388 plus meta.json. Every path is built from the validated handle and project name."""
389 d = build.project_dir(item)
390 files = [(f["name"], f["content"]) for f in item["files"]]
391 files.append(("meta.json", json.dumps(build.meta(item, iid, today), ensure_ascii=False, indent=2,
392 sort_keys=True) + "\n"))
393 entries, keep = [], set()
394 for name, content in files:
395 blob = gh.call("POST", REPO_PREFIX + "git/blobs",
396 {"content": base64.b64encode(content.encode()).decode(), "encoding": "base64"})
397 keep.add(d + "/" + name)
398 entries.append({"path": d + "/" + name, "mode": "100644", "type": "blob", "sha": blob["sha"]})
399 for path in sorted(set(_dir_blobs(gh, base_tree, d)) - keep):
400 entries.append({"path": path, "mode": "100644", "type": "blob", "sha": None}) # removed file
401 for e in entries:
402 if not e["path"].startswith(d + "/") or "/" in e["path"][len(d) + 1:]:
403 raise GuardRefused("path outside the project home: %r" % e["path"])
404 return gh.call("POST", REPO_PREFIX + "git/trees", {"base_tree": base_tree, "tree": entries})["sha"]
405
406
407def _commit_to(gh, branch, item, iid, today, verb, merge_main):
408 """One commit on branch with the item's project. Returns the branch head sha afterwards.
409 A head whose message names this item means an earlier attempt already committed it."""
410 head = _ref(gh, branch)
411 main = gh.call("GET", REPO_PREFIX + "git/ref/heads/main")["object"]["sha"]
412 head_commit = None
413 if head:
414 head_commit = gh.call("GET", REPO_PREFIX + "git/commits/" + head)
415 if ("Allen item " + iid) in (head_commit.get("message") or ""):
416 return head
417 base_commit = main if (merge_main or head is None) else head
418 base_tree = gh.call("GET", REPO_PREFIX + "git/commits/" + base_commit)["tree"]["sha"]
419 tree = _project_tree(gh, item, iid, today, base_tree)
420 if head and head_commit["tree"]["sha"] == tree:
421 return head # nothing changed
422 parents = [head] if head else [main]
423 if merge_main and head:
424 # A publish branch merges main in when main moved since its last commit (recorded as
425 # "Main <sha>"), so the pull request always shows only the project.
426 seen = re.search(r"^Main ([0-9a-f]{40})$", head_commit.get("message") or "", re.M)
427 if not seen or seen.group(1) != main:
428 parents = [head, main]
429 c = gh.call("POST", REPO_PREFIX + "git/commits",
430 {"message": "%s %s/%s from Allen\n\nAllen item %s\nMain %s" % (
431 verb, item["handle"], item["project"], iid, main),
432 "tree": tree, "parents": parents})
433 if head:
434 gh.call("PATCH", REPO_PREFIX + "git/refs/heads/" + branch, {"sha": c["sha"], "force": False})
435 else:
436 gh.call("POST", REPO_PREFIX + "git/refs", {"ref": "refs/heads/" + branch, "sha": c["sha"]})
437 return c["sha"]
438
439
440def save_project(gh, item, iid, today):
441 """Save: one commit on u/<handle>; the URL is that commit's page."""
442 sha = _commit_to(gh, "u/" + item["handle"], item, iid, today, "Save", merge_main=False)
443 return "https://github.com/%s/commit/%s" % (REPO, sha)
444
445
446def find_open_pull(gh, branch):
447 found = gh.call("GET", REPO_PREFIX + "pulls?state=open&per_page=10&head=" +
448 urllib.parse.quote("aien-dev:" + branch, safe=""))
449 return found[0]["html_url"] if found else None
450
451
452def publish_project(gh, item, iid, today, extra_labels, label_cache):
453 """Publish: p/<handle>/<project> carries the project on top of main; one open pull request
454 to main per branch, reused on republish. Drake approves and merges; the pusher never does."""
455 branch = "p/%s/%s" % (item["handle"], item["project"])
456 _commit_to(gh, branch, item, iid, today, "Publish", merge_main=True)
457 existing = find_open_pull(gh, branch)
458 if existing:
459 return existing
460 d = build.project_dir(item)
461 names = "\n".join("- `%s/%s`" % (d, f["name"]) for f in item["files"])
462 body = ("%s\n\n%s\n\nBuilt with Aien by `%s`. Files:\n%s\n- `%s/meta.json`\n\n"
463 "Drake reviews this project before it goes live; merging publishes it at %s/%s/\n\n---\n%s\n%s\n") % (
464 item["title"], item["description"].rstrip(), item["handle"], names, d, build.PAGES_URL, d, FOOTER,
465 marker(iid))
466 pr = gh.call("POST", REPO_PREFIX + "pulls",
467 {"title": "Project: " + item["title"], "head": branch, "base": "main", "body": body,
468 "maintainer_can_modify": True})
469 labels = ["from-aien", "built-with-aien"] + list(extra_labels)
470 for name in labels:
471 ensure_label(gh, name, label_cache)
472 gh.call("POST", REPO_PREFIX + "issues/%d/labels" % pr["number"], {"labels": labels})
473 return pr["html_url"]
474
475
476def decline_pull(gh, item):
477 """Drake declined in his console: comment and close. Only open publish pull requests."""
478 pr = gh.call("GET", REPO_PREFIX + "pulls/%d" % item["pr"])
479 head = (pr.get("head") or {}).get("ref", "")
480 if not re.fullmatch(r"p/[a-z0-9-]+/[a-z0-9-]+", head) or (pr.get("base") or {}).get("ref") != "main":
481 raise Refused("pull request %d is not a project publish request" % item["pr"])
482 if pr.get("state") == "open":
483 reason = spool.scrub(item["reason"]).strip()
484 gh.call("POST", REPO_PREFIX + "issues/%d/comments" % item["pr"],
485 {"body": "Declined by Drake%s\n\n---\n%s" % ((": " + reason) if reason else ".", FOOTER)})
486 gh.call("PATCH", REPO_PREFIX + "pulls/%d" % item["pr"], {"state": "closed"})
487 return pr["html_url"]
488
489
490def write_index(gh, status_dir):
491 """spool-status/index.json: open publish requests (Drake's console) and merged projects
492 (the Built with Aien gallery), read from main's meta.json files."""
493 open_prs = []
494 for pr in gh.call("GET", REPO_PREFIX + "pulls?state=open&per_page=100&base=main") or []:
495 m = re.fullmatch(r"p/([a-z0-9-]+)/([a-z0-9-]+)", (pr.get("head") or {}).get("ref", ""))
496 if m:
497 open_prs.append({"number": pr["number"], "url": pr["html_url"], "title": str(pr.get("title", ""))[:120],
498 "handle": m.group(1), "project": m.group(2)})
499 main = gh.call("GET", REPO_PREFIX + "git/ref/heads/main")["object"]["sha"]
500 tree = gh.call("GET", REPO_PREFIX + "git/commits/" + main)["tree"]["sha"]
501 gallery = []
502 metas = sorted(p for p in _dir_blobs(gh, tree, "projects").items()
503 if re.fullmatch(r"projects/[a-z0-9-]+/[a-z0-9-]+/meta\.json", p[0]))
504 for path, sha in metas[:200]:
505 try:
506 blob = gh.call("GET", REPO_PREFIX + "git/blobs/" + sha)
507 m = json.loads(base64.b64decode(blob["content"]).decode("utf-8"))
508 handle, project = path.split("/")[1:3]
509 gallery.append({"handle": handle, "project": project, "title": str(m.get("title", ""))[:80],
510 "description": str(m.get("description", ""))[:400],
511 "url": "%s/tree/main/projects/%s/%s" % (build.REPO_URL, handle, project),
512 "page": "%s/projects/%s/%s/" % (build.PAGES_URL, handle, project)})
513 except (ValueError, KeyError, TypeError, AttributeError):
514 log("index: skipping unreadable %s" % path)
515 atomic_write(os.path.join(status_dir, build.INDEX),
516 {"v": 1, "updated": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
517 "open": open_prs, "gallery": gallery}, mode=0o640)
518 log("index: %d open, %d in the gallery" % (len(open_prs), len(gallery)))
519
520
521# ---------------------------------------------------------------- driver
522
523class Run:
524 """Result of one pass over the spool."""
525
526 def __init__(self):
527 self.next_due = None # epoch seconds of the earliest retry not yet due
528 self.waiting = 0 # items kept because the pusher is not activated
529 self.more = False # stopped early for time; the next run continues
530 self.index = False # a build item ran: rewrite spool-status/index.json
531
532 def due(self, when):
533 self.next_due = when if self.next_due is None else min(self.next_due, when)
534
535
536def process(args, gh, deadline=None):
537 """One pass over spool-in. `deadline` is a time.monotonic() value; no new item starts
538 within 30 s of it, so a run never ends mid-item."""
539 spool_in, status_dir = args.spool_in, args.spool_status
540 backoff = tuple(getattr(args, "backoff", BACKOFF))
541 attempts_max = len(backoff) + 1
542 st = State(args.state_dir)
543 areas = load_areas(args.areas)
544 label_cache = set()
545 extra = ["test"] if args.test_label else []
546 today = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")
547 run = Run()
548 for name in sorted(os.listdir(spool_in)):
549 if name.startswith(".tmp-"):
550 continue
551 path = os.path.join(spool_in, name)
552 m = ID_FILE.match(name)
553 if not m:
554 log("removing unexpected spool entry %r" % name)
555 _remove(path)
556 continue
557 iid = m.group(1)
558 prior = read_status_file(status_dir, iid)
559 if iid in st.d["filed"] or (prior and prior.get("state") == "filed"):
560 url = st.d["filed"].get(iid) or prior.get("url")
561 write_status(status_dir, iid, "filed", url=url)
562 _remove(path)
563 log("%s: already filed (%s); nothing filed" % (iid, url))
564 continue
565 try:
566 item = check_item(read_item(path), iid, areas)
567 except Refused as e:
568 _finish(st, status_dir, path, iid, "rejected", str(e))
569 continue
570 kind = item["kind"]
571 if gh is None:
572 # Not activated: keep the item, tell the visitor it is queued.
573 if not (prior and prior.get("state") == "queued" and prior.get("reason") == AWAITING):
574 write_status(status_dir, iid, "queued", reason=AWAITING)
575 log("%s: queued (%s)" % (iid, AWAITING))
576 run.waiting += 1
577 continue
578 rec = st.d["attempts"].get(iid)
579 if rec and rec["next"] > time.time():
580 run.due(rec["next"])
581 continue
582 if deadline is not None and time.monotonic() > deadline - 30:
583 run.more = True
584 log("run time used; remaining items go to the next run")
585 break
586 try:
587 url = None
588 if st.d["pending"].get(iid) == "issue":
589 url = find_issue(gh, iid) # an earlier attempt may have created it
590 if url is None:
591 if iid not in st.d["pending"]:
592 if not st.take(kind):
593 _finish(st, status_dir, path, iid, "failed",
594 "today's limit for %s on GitHub is reached"
595 % {"issue": "issues", "save": "saves"}.get(kind, "publish requests"))
596 continue
597 st.d["pending"][iid] = kind
598 st.save()
599 if kind == "issue":
600 url = file_issue(gh, item, iid, extra, label_cache)
601 elif kind == "save":
602 url = save_project(gh, item, iid, today)
603 elif kind == "publish":
604 url = publish_project(gh, item, iid, today, extra, label_cache)
605 elif kind == "decline":
606 url = decline_pull(gh, item)
607 else: # refresh: the index below is the whole action
608 url = None
609 run.index = run.index or kind != "issue"
610 st.d["filed"][iid] = url
611 st.d["pending"].pop(iid, None)
612 st.d["attempts"].pop(iid, None)
613 st.save()
614 write_status(status_dir, iid, "filed", url=url)
615 _remove(path)
616 log("%s: filed %s" % (iid, url))
617 continue
618 except Refused as e:
619 _finish(st, status_dir, path, iid, "rejected", str(e))
620 continue
621 except GitHubError as e:
622 cause = e.cause
623 except GuardRefused as e:
624 # The request guard stopped a call the code should never make: not retried.
625 log("%s: guard: %s" % (iid, e))
626 _finish(st, status_dir, path, iid, "failed", "an internal safety check stopped the request")
627 continue
628 except Exception as e: # noqa: BLE001 - an unknown error must not lose the item
629 cause = "an internal error (%s)" % type(e).__name__
630 log("%s: %s: %s" % (iid, type(e).__name__, str(e)[:200]))
631 n = (rec["n"] if rec else 0) + 1
632 if n >= attempts_max:
633 _finish(st, status_dir, path, iid, "failed", "%s after %d attempts" % (cause, n))
634 continue
635 when = time.time() + backoff[n - 1]
636 st.d["attempts"][iid] = {"n": n, "next": when, "cause": cause}
637 st.save()
638 write_status(status_dir, iid, "queued",
639 reason="retrying: %s (attempt %d of %d)" % (cause, n, attempts_max))
640 log("%s: attempt %d of %d failed: %s; next in %.0f s" % (iid, n, attempts_max, cause, backoff[n - 1]))
641 run.due(when)
642 if gh is not None and run.index:
643 try:
644 write_index(gh, status_dir)
645 except (GitHubError, GuardRefused, OSError, KeyError, TypeError) as e:
646 log("index: not rewritten: %s" % e)
647 return run
648
649
650def _finish(st, status_dir, path, iid, state, reason):
651 """rejected: the content broke a rule. failed: GitHub did not take it."""
652 kind = st.d["pending"].pop(iid, None)
653 if state == "failed" and kind:
654 st.give(kind)
655 st.d["attempts"].pop(iid, None)
656 st.save()
657 write_status(status_dir, iid, state, reason=reason)
658 _remove(path)
659 log("%s: %s: %s" % (iid, state, reason))
660
661
662def _remove(path):
663 try:
664 os.unlink(path)
665 except FileNotFoundError:
666 pass
667
668
669def load_token(path):
670 """The fine-grained token, or None. Never falls back to any other credential."""
671 if not path:
672 return None
673 try:
674 with open(path, encoding="ascii") as f:
675 token = f.read().strip()
676 except (OSError, UnicodeDecodeError):
677 return None
678 if not FINE_GRAINED.match(token):
679 log("credential is not a fine-grained github_pat_ token; refusing it")
680 return None
681 return token
682
683
684def _seconds_list(text):
685 vals = tuple(float(x) for x in text.split(","))
686 if not vals or any(v < 0 for v in vals):
687 raise argparse.ArgumentTypeError("comma-separated non-negative seconds")
688 return vals
689
690
691def main(argv=None):
692 creds = os.environ.get("CREDENTIALS_DIRECTORY")
693 p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
694 p.add_argument("--spool-in", default="/var/lib/allen-chat/spool-in")
695 p.add_argument("--spool-status", default="/var/lib/allen-chat/spool-status")
696 p.add_argument("--state-dir", default="/var/lib/omega-pusher")
697 p.add_argument("--areas", default="/var/lib/allen-catalog/areas.txt")
698 p.add_argument("--token-file", default=os.path.join(creds, "omega-projects-token") if creds else None)
699 p.add_argument("--api-base", default=API, help="tests only: http://127.0.0.1:PORT stub")
700 p.add_argument("--spool-module-dir", default=os.path.dirname(os.path.abspath(__file__)))
701 p.add_argument("--test-label", action="store_true", help="add the 'test' label (tests only)")
702 p.add_argument("--backoff", type=_seconds_list, default=BACKOFF,
703 help="seconds before each retry; attempts = entries + 1 (default 10,20,40,80)")
704 p.add_argument("--run-budget", type=float, default=RUN_BUDGET,
705 help="seconds one run may take, retries included (unit TimeoutStartSec is 120)")
706 p.add_argument("--idle-delay", type=float, default=90.0,
707 help="seconds to wait before exiting when items wait for activation")
708 args = p.parse_args(argv)
709 global spool, build
710 sys.path.insert(0, args.spool_module_dir)
711 import allen_spool
712 import allen_build
713 spool, build = allen_spool, allen_build
714 os.makedirs(args.state_dir, mode=0o700, exist_ok=True)
715 lock = open(os.path.join(args.state_dir, "lock"), "w")
716 fcntl.flock(lock, fcntl.LOCK_EX)
717 token = load_token(args.token_file)
718 gh = GitHub(token, api=args.api_base) if token else None
719 if gh is None:
720 log("not activated: no omega-projects-token credential; items stay queued")
721 deadline = time.monotonic() + args.run_budget
722 # The path unit starts a new run as soon as this one exits while spool-in holds
723 # items, so every exit with items left waits first: until a retry is due (looping
724 # inside this run while time is left) or for idle-delay when not activated.
725 while True:
726 run = process(args, gh, deadline)
727 left = deadline - time.monotonic()
728 if run.more:
729 break
730 if run.waiting:
731 time.sleep(max(0.0, min(args.idle_delay, left)))
732 break
733 if run.next_due is None:
734 break
735 delay = max(0.0, run.next_due - time.time())
736 if delay > left:
737 time.sleep(max(0.0, left))
738 break
739 time.sleep(delay)
740 return 0
741
742
743if __name__ == "__main__":
744 sys.exit(main())