caelum0x 6801c08af9
Some checks failed
ci / cargo test (abacus) (push) Has been cancelled
ci / cargo test (agent-runtime) (push) Has been cancelled
ci / cargo test (context-passport) (push) Has been cancelled
ci / cargo test (game-economy) (push) Has been cancelled
ci / cargo test (ledgerline) (push) Has been cancelled
ci / cargo test (mint) (push) Has been cancelled
ci / cargo test (rago) (push) Has been cancelled
ci / cargo test (relay) (push) Has been cancelled
ci / node suites (push) Has been cancelled
ci / cargo test (toolgate) (push) Has been cancelled
ci / cargo test (turnstile) (push) Has been cancelled
ci / cargo test (vend) (push) Has been cancelled
feat(RIT-OPS,RIT-BRD): rename gitea -> rit everywhere we control, deployed + live-verified
apps/gitea -> apps/rithub-server; compose services/containers renamed
(rithub-server-app/postgres/act-runner) with explicit project name and
volume names pinned to the exact existing Docker volumes (no data loss);
our own GITEA_* compose/env var names -> RIT_*; new rit-admin CLI wrapper
on railyard-box; giteaSession.mjs/giteaOAuth.mjs/giteaInfo.mjs ->
ritSession/ritOAuth/ritInfo across 6 apps; GiteaForgeAdapter -> RitForgeAdapter
+ giteaSyncService/importGiteaRepos/syncGiteaRepos -> rit* in ritgram
(tsc clean); apps/console/lib/gitea.ts -> lib/ritProvision.ts; Go
internal/giteaclient -> internal/ritclient in rithub-async-import (go
build/test clean); new /auth/rit + /forges/rit/connect routes with
/gitea back-compat aliases; locale/swagger/footer/captcha template text
scrubbed of remaining "Gitea" strings.

Deployed to railyard-box: old containers stopped/removed, /srv/railyard-gitea
renamed to /srv/rithub-server with a symlink kept, docker compose up -d from
the new path, act_runner network-alias fix for its persisted instance URL.
Live-verified: docker compose config diff showed zero unintended value
changes, DB row counts unchanged (19 users, 635 repos), full route
regression 200/expected, 0 "gitea" in headers/bodies on every checked page,
real git clone+push over HTTPS and SSH with a disposable account (deleted
after). Deferred on purpose (documented in plans/railyard.md): the forge
discriminator / DB column names / Postgres role+volume names (data
migrations, not a naming change) and the upstream GITEA__ env-to-ini keys
and X-Gitea-* wire headers (hardcoded in the vendored engine binary).

See plans/railyard.md RIT-OPS/RIT-BRD entry for the full old->new map and
live evidence.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-12-01 16:34:39 +03:00

121 lines
4.2 KiB
Python
Executable File

#!/usr/bin/env python3
"""Count ?ref=<value> visits to rithub.dev from Caddy's own JSON access
logs, so the share loops (plans/growth-loops-2026-11-19.md Rithub row
#4) have a real "who brings whom" number without a new engine route or a
third-party analytics event we'd have to trust to fire correctly.
Reads /var/log/caddy/rithub-dev.log and rithub-dev-www.log (one JSON
object per line, Caddy's `format json` access log -- see /etc/caddy/
Caddyfile's (common) snippet). For each line whose `request.uri` query
string has a `ref` param, increments a per-ref counter in
/srv/rithub-server/ref-counts.json.
Tracks a byte offset per log file (keyed by inode, so a Caddy
roll_size rotation that starts a fresh file with the same name is
detected and read from byte 0 again) in
/srv/rithub-server/.ref-count-state.json, so re-running this on a
cron tick only processes new lines -- cheap enough to run every few
minutes, never re-counts the same request twice in the normal case.
Intentionally simple (the task spec's own wording): a rotated-away
`.log.gz` is not back-processed, so a visit landing in the last few KB
before a rotation could in theory be missed once -- acceptable for a
"who brings whom" trend counter, not a billing-grade metric.
Must run as root (the caddy access logs are 0600 caddy:caddy) -- see
scripts/ref-count.sh, which is what actually gets cron'd and invokes
this via sudo.
"""
import json
import os
import re
import sys
from datetime import datetime, timezone
from typing import Any
from urllib.parse import parse_qs, urlsplit
LOG_FILES: list[str] = [
"/var/log/caddy/rithub-dev.log",
"/var/log/caddy/rithub-dev-www.log",
]
STATE_FILE = "/srv/rithub-server/.ref-count-state.json"
COUNTS_FILE = "/srv/rithub-server/ref-counts.json"
# Keep ref values sane -- usernames/short codes only, never let a hostile
# query string balloon the counts file or get echoed back unescaped
# anywhere downstream.
REF_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,64}$")
def load_json(path: str, default: dict[str, Any]) -> dict[str, Any]:
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return default
def save_json(path: str, data: dict[str, Any]) -> None:
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, sort_keys=True)
os.replace(tmp, path)
def extract_ref(uri: str) -> str | None:
try:
qs = parse_qs(urlsplit(uri).query)
except ValueError:
return None
vals = qs.get("ref")
if not vals:
return None
ref = vals[0].strip()
return ref if REF_RE.match(ref) else None
def process_file(path: str, state: dict[str, Any], counts: dict[str, Any]) -> None:
try:
st = os.stat(path)
except FileNotFoundError:
return
entry = state.get(path, {})
offset = entry.get("offset", 0)
if entry.get("inode") != st.st_ino or offset > st.st_size:
# Rotated (new inode) or truncated -- start over from byte 0.
offset = 0
now = datetime.now(timezone.utc).isoformat()
with open(path, encoding="utf-8", errors="replace") as f:
f.seek(offset)
for raw_line in f:
line = raw_line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
uri = rec.get("request", {}).get("uri", "")
ref = extract_ref(uri)
if not ref:
continue
bucket = counts.setdefault(ref, {"visits": 0, "first_seen": now, "last_seen": now})
bucket["visits"] += 1
bucket["last_seen"] = now
new_offset = f.tell()
state[path] = {"inode": st.st_ino, "offset": new_offset}
def main() -> int:
state = load_json(STATE_FILE, {})
counts = load_json(COUNTS_FILE, {})
for path in LOG_FILES:
process_file(path, state, counts)
save_json(STATE_FILE, state)
save_json(COUNTS_FILE, counts)
total = sum(v["visits"] for v in counts.values())
print(f"ref-count: {len(counts)} distinct ref value(s), {total} total ?ref visit(s) tracked")
return 0
if __name__ == "__main__":
sys.exit(main())