interplane.Get Omega
Read in your language

interplane-forge

INTERPLANE Forge

Brought by drakestapleton

branch main Branches Tags History

interplane-forge / growth / tests / oracle.py

232 lines · 8244 bytes Raw Blame History
1# ORACLE
2# Independent recount of the fixture logs. Not forged code.
3# Same rules as server/counts.om: visitor git fetches, upload-pack POSTs,
4# visitor archive and release downloads. Window is [start, end] inclusive.
5import json
6import re
7import sys
8
9HOME = "198.51.100.7"
10
11
12def own(ip):
13 if ip in ("", "-", HOME):
14 return True
15 if ip.startswith(("127.", "10.", "192.168.", "::1", "fe80:", "fd")):
16 return True
17 if ip.startswith("100."):
18 parts = ip.split(".")
19 if len(parts) >= 2 and parts[1].isdigit():
20 n = int(parts[1])
21 if 64 <= n <= 127:
22 return True
23 return False
24
25
26def bot(ua):
27 u = ua.lower()
28 return "bot" in u or "crawl" in u or "spider" in u
29
30
31def recount(dl, access, forged, repos, start, end):
32 # repos: name -> rid
33 out = {n: {"fetches": 0, "win_fetches": 0, "posts": 0, "win_posts": 0,
34 "archives": 0, "releases": 0, "win_dl": 0} for n in repos}
35 by_rid = {r: n for n, r in repos.items()}
36 q = re.compile(r'^/rad/([^/]+)\.git(?:/z6Mk[^/]*)?/info/refs\?service=git-upload-pack$')
37 code = re.compile(r'^/code/git/([^/]+)\.git/info/refs\?service=git-upload-pack$')
38 with open(dl, encoding="utf-8", errors="replace") as f:
39 for line in f:
40 parts = line.split(" ", 3)
41 if len(parts) < 4:
42 continue
43 ep = parts[0].split(".", 1)[0]
44 if not ep.isdigit():
45 continue
46 epoch = int(ep)
47 ip, status, rest = parts[1], parts[2], parts[3]
48 if status != "200" or own(ip):
49 continue
50 try:
51 uri, ua = rest.split('" "', 1)
52 except ValueError:
53 continue
54 uri = uri[1:] if uri.startswith('"') else uri
55 if bot(ua):
56 continue
57 name = None
58 m = q.match(uri)
59 if m and m.group(1) in by_rid:
60 name = by_rid[m.group(1)]
61 m = code.match(uri)
62 if m and m.group(1) in repos:
63 name = m.group(1)
64 if name is None:
65 continue
66 out[name]["fetches"] += 1
67 if start <= epoch <= end:
68 out[name]["win_fetches"] += 1
69 post = re.compile(r'"POST /rad/([^/ ]+)\.git(?:/z6Mk[^/ ]*)?/git-upload-pack HTTP/[0-9.]+" 200 ')
70 with open(access, encoding="utf-8", errors="replace") as f:
71 for line in f:
72 m = post.search(line)
73 if not m or m.group(1) not in by_rid:
74 continue
75 name = by_rid[m.group(1)]
76 out[name]["posts"] += 1
77 tm = re.search(r'\[(\d{2})/([A-Za-z]{3})/(\d{4}):(\d{2}):(\d{2}):(\d{2}) ([+-]\d{4})\]', line)
78 if not tm:
79 continue
80 # epoch is checked by the shell driver; the page's upload-pack window uses forged's parse.
81 # The driver passes precomputed epochs in a sidecar when needed. Here we only total posts.
82 _ = tm
83 arch = "/archive/"
84 rel = "/releases/download/"
85 with open(forged, encoding="utf-8", errors="replace") as f:
86 for line in f:
87 p = line.split()
88 if len(p) < 5 or not p[0].isdigit() or p[2] != "1" or p[4] != "200" or own(p[1]):
89 continue
90 epoch = int(p[0])
91 path = p[3]
92 for name in repos:
93 prefix = "/drakestapleton/" + name
94 if path.startswith(prefix + arch):
95 out[name]["archives"] += 1
96 if start <= epoch <= end:
97 out[name]["win_dl"] += 1
98 elif path.startswith(prefix + rel):
99 out[name]["releases"] += 1
100 if start <= epoch <= end:
101 out[name]["win_dl"] += 1
102 return out
103
104
105def social(path, start, end):
106 # Replay the social log the same way the store does: a star adds a key,
107 # an unstar removes it. Window net is events inside [start, end], not the set.
108 import hashlib
109 current = {}
110 window = {}
111 follows = {}
112 first = None
113 prev = "0" * 64
114 seq = 0
115 with open(path, encoding="utf-8") as f:
116 for raw in f:
117 line = raw[:-1] if raw.endswith("\n") else raw
118 if not line:
119 continue
120 seq += 1
121 got = hashlib.sha256(line.encode()).hexdigest()
122 row = json.loads(line)
123 if row["seq"] != seq or row["prev"] != prev:
124 raise SystemExit("social chain broken")
125 prev = got
126 ts = int(row["ts"])
127 if first is None:
128 first = ts
129 act = row["action"]
130 target = row["target"]
131 did = row["did"]
132 if act in ("star", "unstar"):
133 bag = current.setdefault(target, set())
134 if act == "star":
135 bag.add(did)
136 else:
137 bag.discard(did)
138 if start <= ts <= end:
139 window[target] = window.get(target, 0) + (1 if act == "star" else -1)
140 elif act == "follow":
141 follows.setdefault(target, set()).add(did)
142 elif act == "unfollow":
143 follows.setdefault(target, set()).discard(did)
144 net = {k: max(v, 0) for k, v in window.items()}
145 now = {k: len(v) for k, v in current.items()}
146 fol = {k: len(v) for k, v in follows.items()}
147 return {"first": first, "stars": now, "window": net, "follows": fol}
148
149
150def authors(gitdir):
151 import subprocess
152 ref = "refs/heads/main"
153 p = subprocess.run(["git", "--git-dir", gitdir, "rev-parse", "--verify", ref],
154 capture_output=True)
155 if p.returncode != 0:
156 ref = "refs/namespaces/z6MkfZDue1TbaNFi3ZzcD9uiTeduPLC52ucdFVuLKZwexxhK/refs/heads/main"
157 p = subprocess.run(["git", "--git-dir", gitdir, "log", "--format=%aN", ref],
158 capture_output=True, text=True, check=True)
159 names = []
160 seen = set()
161 for line in p.stdout.splitlines():
162 name = line[:48]
163 if name in seen:
164 continue
165 seen.add(name)
166 names.append(name)
167 if len(names) == 64:
168 break
169 return names
170
171
172def patches(gitdir):
173 import subprocess
174 p = subprocess.run(
175 ["git", "--git-dir", gitdir, "for-each-ref",
176 "--format=%(objectname) %(refname:lstrip=-1)",
177 "refs/namespaces/*/refs/cobs/xyz.radicle.patch/*"],
178 capture_output=True, text=True, check=True)
179 ids = []
180 seen = set()
181 tips = {}
182 for line in p.stdout.splitlines():
183 parts = line.split()
184 if len(parts) != 2 or len(parts[1]) != 40:
185 continue
186 tips.setdefault(parts[1], []).append(parts[0])
187 if parts[1] in seen:
188 continue
189 seen.add(parts[1])
190 ids.append(parts[1])
191 merged = 0
192 for pid in ids:
193 if _merged(gitdir, pid, tips[pid]):
194 merged += 1
195 return {"opened": len(ids), "merged": merged}
196
197
198def _merged(gitdir, pid, tips):
199 import subprocess
200 cmd = ["git", "--git-dir", gitdir, "log", "--ancestry-path", "--topo-order",
201 "--format=%H", *tips, "^" + pid]
202 log = subprocess.run(cmd, capture_output=True, text=True)
203 commits = log.stdout.splitlines() if log.returncode == 0 else []
204 commits.append(pid)
205 for commit in commits:
206 n = 0
207 while n < 64:
208 blob = subprocess.run(
209 ["git", "--git-dir", gitdir, "cat-file", "blob", "%s:%d" % (commit, n)],
210 capture_output=True)
211 if blob.returncode != 0:
212 break
213 try:
214 row = json.loads(blob.stdout.decode("utf-8", "replace"))
215 except json.JSONDecodeError:
216 n += 1
217 continue
218 if isinstance(row, dict) and row.get("type") == "merge":
219 return True
220 n += 1
221 return False
222
223
224def main():
225 spec = json.load(sys.stdin)
226 rows = recount(spec["dl"], spec["access"], spec["forged"], spec["repos"], spec["start"], spec["end"])
227 json.dump(rows, sys.stdout)
228 sys.stdout.write("\n")
229
230
231if __name__ == "__main__":
232 main()