Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,45 @@ except `GET /health` needs the pairing token when `PLUGIN_TOKEN` is set.
| `GET /template?platform=` | example `.monkeytester/build-<platform>.sh` |
| `GET /repos/<owner>/<repo>[?branch=]` | check a repo (and branch) |
| `GET /repos/<owner>/<repo>/branches` | the repo's branches |
| `GET /repos/<owner>/<repo>/cases?ref=` | test cases on a ref |
| `GET /repos/<owner>/<repo>/cases?ref=` | test cases on a ref, the build scripts present, and each case's `DEVICE` lines (`devices`, see below) |
| `POST /builds` | queue a build; `GET /builds/<ref>` its status |
| `GET /builds/<ref>/log?offset=` | the build log from `offset` |
| `POST /builds/<ref>/cancel` | stop a queued or running build |

### Cases and their DEVICE lines

`GET /repos/<owner>/<repo>/cases?ref=<branch>` answers:

```json
{
"repo": "owner/App",
"ref": "master",
"cases": ["login", "onboarding"],
"recipes": {"android": true, "ios": true},
"devices": {
"login": ["ios, physical", "android, virtual = MT_Pixel"],
"onboarding": []
}
}
```

A case is a folder `mt-tests/<case>/` holding `INSTRUCTION.txt`. `devices` maps
each case to the raw text after `DEVICE:` on every `DEVICE` line in that file's
header, in file order, trimmed. A case without a `DEVICE` line maps to `[]`. The
header is the run of `KEY: value` lines at the top of the file (`MODE`,
`CLEAR_DATA`, `REINSTALL_APP`, `DEVICE`; the key is case-insensitive; blank
lines and `#` lines are allowed) and ends at the first other line, the same way
the MonkeyTester runner reads it. The plugin passes the values through without
interpreting them; the viewer parses them.

The plugin reads every `INSTRUCTION.txt` as a git blob named by the branch's
tree, in parallel, and caches the result by blob sha, so a later listing only
reads files that changed. On GitHub, when the recursive tree is truncated, the
contents-API answers it already makes carry the files, so no extra request is
needed. If any file can't be read, `devices` is left out of the answer, which
the contract reads as "unknown" (the cases list still comes back).
`POST /builds` does not read these files.

`/docs` reads `README.md` next to `build_plugin.py` at request time. The
launchd/systemd units run from the checkout and the Nix flake copies every
git-tracked file, so README.md is present in all three; an install without it
Expand Down
2 changes: 1 addition & 1 deletion build_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,7 @@ def start_build(self, data):
raise PluginError(f"this host can't build {', '.join(cant)} (it builds: {builds})")
cfg = self.configured(need_viewer=True)
src = self.source(cfg)
info = source_call(src.list_cases, cfg, repo, branch)
info = source_call(src.list_cases, cfg, repo, branch, False) # no devices: recipes only
missing = [p for p in platforms if (info.get("recipes") or {}).get(p) is False]
if missing:
raise PluginError(f"{branch} has no {', '.join(RECIPES[p] for p in missing)} "
Expand Down
117 changes: 116 additions & 1 deletion sources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
check_token(forge_url, token) -> the token's user login
check_repo(cfg, repo, branch) -> contract GET /repos/<o>/<r> body
list_branches(cfg, repo) -> contract GET /repos/<o>/<r>/branches body
list_cases(cfg, repo, ref) -> contract GET /repos/<o>/<r>/cases body
list_cases(cfg, repo, ref, devices=True)
-> contract GET /repos/<o>/<r>/cases body;
devices=False skips reading the cases'
INSTRUCTION.txt (no `devices` key)
clone_url(cfg, repo) -> the git URL to fetch from
git_auth_config(cfg, repo) -> [(git config key, value)] carrying the token,
passed per command via GIT_CONFIG_* env,
Expand All @@ -20,7 +23,11 @@
"""
from __future__ import annotations

import base64
import binascii
import re
import threading
from concurrent.futures import ThreadPoolExecutor

PLATFORMS = ("android", "ios")
RECIPES = {"android": ".monkeytester/build-android.sh", "ios": ".monkeytester/build-ios.sh"}
Expand Down Expand Up @@ -57,6 +64,114 @@ def cases_from_tree(entries):
return sorted(cases)


# Header keys of INSTRUCTION.txt (MonkeyTester's test runner,
# _parse_instruction_header_keys). The header ends at the first line that is
# not blank, not a # comment and not `<known key>: value`.
INSTRUCTION_HEADER_KEYS = ("mode", "clear_data", "reinstall_app", "device")
DEVICE_FETCH_WORKERS = 8
_DEVICE_CACHE_MAX = 4096
_device_cache = {} # blob sha -> [DEVICE values]; blobs are content-addressed
_device_cache_lock = threading.Lock()


def device_lines(content):
"""The raw values after `DEVICE:` in an INSTRUCTION.txt header, in file
order, whitespace-trimmed. Not interpreted: the viewer parses them.

Mirrors the runner's header parser: the key is case-insensitive and the
header stops at the first line that isn't blank, a # comment or a known
`KEY: value` line."""
values = []
for line in content.strip().split("\n"):
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
key, sep, value = stripped.partition(":")
key = key.strip().lower()
if not sep or key not in INSTRUCTION_HEADER_KEYS:
break
if key == "device":
values.append(value.strip())
return values


def decode_text(raw):
"""File bytes -> text the way the runner reads them (UTF-8; bad bytes replaced)."""
return raw.decode("utf-8", "replace")


def instruction_blobs(entries):
"""{case: blob sha} for mt-tests/<case>/INSTRUCTION.txt in a git tree listing."""
blobs = {}
for entry in entries or []:
if not isinstance(entry, dict):
continue
parts = (entry.get("path") or "").split("/")
if len(parts) == 3 and parts[0] == CASES_DIR and parts[2] == "INSTRUCTION.txt" \
and entry.get("type") == "blob" and CASE_RE.match(parts[1]) and entry.get("sha"):
blobs[parts[1]] = entry["sha"]
return blobs


def _cached_devices(sha):
with _device_cache_lock:
return _device_cache.get(sha)


def _cache_devices(sha, values):
with _device_cache_lock:
if len(_device_cache) >= _DEVICE_CACHE_MAX:
_device_cache.clear()
_device_cache[sha] = values


def case_devices(blobs, fetch_blob):
"""{case: [DEVICE values]} for {case: blob sha}, or None when any
INSTRUCTION.txt couldn't be read (the response then leaves `devices` out,
which the contract reads as "unknown").

fetch_blob(sha) -> file bytes, or None on failure. Blobs not cached yet
are fetched in parallel; results are cached by blob sha (a sha always
names the same content, so a cached answer can't go stale)."""
out, missing = {}, {}
for case, sha in blobs.items():
cached = _cached_devices(sha)
if cached is not None:
out[case] = list(cached)
else:
missing.setdefault(sha, []).append(case)

def read(sha):
try:
raw = fetch_blob(sha)
except SourceError:
return sha, None
return sha, None if raw is None else device_lines(decode_text(raw))

if missing:
workers = min(DEVICE_FETCH_WORKERS, len(missing))
with ThreadPoolExecutor(max_workers=workers) as pool:
for sha, values in pool.map(read, list(missing)):
if values is None:
return None
_cache_devices(sha, values)
for case in missing[sha]:
out[case] = list(values)
return dict(sorted(out.items()))


def decode_base64_content(payload):
"""File bytes from a contents/blobs API answer ({"content", "encoding":
"base64"}), or None when it carries no base64 content."""
if not isinstance(payload, dict) or payload.get("encoding") != "base64" \
or not isinstance(payload.get("content"), str):
return None
try:
return base64.b64decode(payload["content"])
except (ValueError, binascii.Error):
return None


def recipes_from_tree(entries):
"""{platform: bool}: which build scripts a git tree listing holds."""
blobs = {e.get("path") for e in entries or [] if isinstance(e, dict) and e.get("type") == "blob"}
Expand Down
29 changes: 25 additions & 4 deletions sources/gitea.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
import urllib.parse
import urllib.request

from sources import PLATFORMS, RECIPES, SourceError, cases_from_tree, override_url, recipes_from_tree, require_http
from sources import (PLATFORMS, RECIPES, SourceError, case_devices, cases_from_tree, decode_base64_content,
instruction_blobs, override_url, recipes_from_tree, require_http)

KIND = "gitea"
LABEL = "Gitea"
Expand Down Expand Up @@ -188,8 +189,20 @@ def list_branches(cfg, repo):
return {"repo": repo, "default": default, "branches": names}


def list_cases(cfg, repo, ref):
"""{repo, ref, cases, recipes} for that branch. Unknown branch -> not_found."""
def _read_blob(cfg, repo, sha):
"""A blob's bytes (GET /repos/{o}/{r}/git/blobs/{sha}), or None on failure."""
status, payload = _get(cfg, f"{_repo_path(repo)}/git/blobs/{_ref(sha)}")
if status != 200:
return None
return decode_base64_content(payload)


def list_cases(cfg, repo, ref, devices=True):
"""{repo, ref, cases, recipes[, devices]} for that branch. Unknown branch -> not_found.

devices: {case: [raw DEVICE values]} from each case's INSTRUCTION.txt
header, read in parallel as blobs named by the tree (cached by blob sha).
Left out when devices=False or when a file couldn't be read."""
entries = []
for page in range(1, TREE_MAX_PAGES + 1):
status, payload = _get(cfg, f"{_repo_path(repo)}/git/trees/{_ref(ref)}",
Expand All @@ -203,4 +216,12 @@ def list_cases(cfg, repo, ref):
entries += payload.get("tree") or []
if not payload.get("truncated"):
break
return {"repo": repo, "ref": ref, "cases": cases_from_tree(entries), "recipes": recipes_from_tree(entries)}
cases = cases_from_tree(entries)
out = {"repo": repo, "ref": ref, "cases": cases, "recipes": recipes_from_tree(entries)}
if devices:
blobs = instruction_blobs(entries)
found = case_devices({case: blobs[case] for case in cases if case in blobs},
lambda sha: _read_blob(cfg, repo, sha))
if found is not None and set(found) == set(cases):
out["devices"] = found
return out
47 changes: 37 additions & 10 deletions sources/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@
import urllib.parse
import urllib.request

from sources import (CASE_RE, CASES_DIR, PLATFORMS, RECIPES, SourceError, cases_from_tree, override_url,
recipes_from_tree, require_http)
from sources import (CASE_RE, CASES_DIR, PLATFORMS, RECIPES, SourceError, case_devices, cases_from_tree,
decode_base64_content, instruction_blobs, override_url, recipes_from_tree, require_http)

KIND = "github"
LABEL = "GitHub"
Expand Down Expand Up @@ -229,35 +229,62 @@ def _branch_commit(cfg, repo, ref):

def _cases_from_contents(cfg, repo, sha):
"""Fallback when the recursive tree is truncated: list mt-tests/ and check
each folder for INSTRUCTION.txt through the contents API."""
each folder for INSTRUCTION.txt through the contents API.

Returns (cases, {case: (blob sha, file bytes or None)}): the contents API
answer already carries the file, so `devices` costs no extra request here."""
status, payload = _call(cfg, "GET", f"/repos/{repo}/contents/{CASES_DIR}", params={"ref": sha})
if status == 404:
return []
return [], {}
if status != 200 or not isinstance(payload, list):
raise _refused(f"Listing {CASES_DIR}/ failed", status, payload)
dirs = sorted(e["name"] for e in payload
if isinstance(e, dict) and e.get("type") == "dir" and CASE_RE.match(e.get("name") or ""))
cases = []
cases, files = [], {}
for name in dirs[:MAX_FALLBACK_CASES]:
status, entry = _call(cfg, "GET", f"/repos/{repo}/contents/{CASES_DIR}/{_q(name)}/INSTRUCTION.txt",
params={"ref": sha})
if status == 200 and isinstance(entry, dict) and entry.get("type") == "file":
cases.append(name)
return cases
files[name] = (entry.get("sha") or "", decode_base64_content(entry))
return cases, files


def _read_blob(cfg, repo, blob_sha):
"""A blob's bytes (GET /repos/{o}/{r}/git/blobs/{sha}), or None on failure."""
status, payload = _call(cfg, "GET", f"/repos/{repo}/git/blobs/{_q(blob_sha)}")
if status != 200:
return None
return decode_base64_content(payload)


def list_cases(cfg, repo, ref, devices=True):
"""{repo, ref, cases, recipes[, devices]} for one branch. Unknown branch -> not_found.

def list_cases(cfg, repo, ref):
"""{repo, ref, cases, recipes} for one branch. Unknown branch -> not_found."""
devices: {case: [raw DEVICE values]} from each case's INSTRUCTION.txt
header, read in parallel as blobs named by the tree (cached by blob sha).
Left out when devices=False or when a file couldn't be read."""
sha, tree_sha = _branch_commit(cfg, repo, ref)
status, payload = _call(cfg, "GET", f"/repos/{repo}/git/trees/{_q(tree_sha or sha)}",
params={"recursive": "1"})
if status != 200 or not isinstance(payload, dict):
raise _refused(f"Reading the tree of {ref} failed", status, payload)
entries = payload.get("tree") or []
if payload.get("truncated"):
cases = _cases_from_contents(cfg, repo, sha or ref)
cases, files = _cases_from_contents(cfg, repo, sha or ref)
recipes = {p: has_file(cfg, repo, RECIPES[p], sha or ref) for p in PLATFORMS}
blobs = {case: blob for case, (blob, _) in files.items()}
inline = {blob: raw for blob, raw in files.values() if blob and raw is not None}
else:
cases = cases_from_tree(entries)
recipes = recipes_from_tree(entries)
return {"repo": repo, "ref": ref, "cases": cases, "recipes": recipes}
blobs, inline = instruction_blobs(entries), {}
out = {"repo": repo, "ref": ref, "cases": cases, "recipes": recipes}
if devices:
found = None
if all(blobs.get(case) for case in cases):
found = case_devices({case: blobs[case] for case in cases},
lambda blob: inline[blob] if blob in inline else _read_blob(cfg, repo, blob))
if found is not None:
out["devices"] = found
return out
27 changes: 23 additions & 4 deletions tests/fake_gitea.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
(/<owner>/<repo>.git/info/refs) so tests can see the credentials git sent, and
answers it 404. No network access beyond 127.0.0.1.
"""
import base64
import hashlib
import json
import threading
import urllib.parse
Expand All @@ -27,21 +29,30 @@ def __init__(self):
self.repos = {}
self.tree_page_size = 1000
self.fail_user = None # HTTP status for GET /user
self.fail_blobs = False # answer GET .../git/blobs/<sha> with 500
self.blobs = {} # blob sha -> file text (files given with content)
branches = [f"feat/b{i:02d}" for i in range(60)] + ["master", "develop"]
self.add_repo(REPO, {b: list(DEFAULT_FILES) for b in branches})

def add_repo(self, repo, branches, default="master"):
"""branches: {name: [file paths]}."""
"""branches: {name: [file paths]} or {name: {file path: text}}."""
self.repos[repo] = {"default": default, "branches": branches}


def tree_entries(files):
def tree_entries(files, blobs=None):
"""Tree entries; with file texts (a dict) blob shas are content-addressed
like git and the texts are registered in `blobs`."""
dirs, out = set(), []
for path in files:
parts = path.split("/")
for i in range(1, len(parts)):
dirs.add("/".join(parts[:i]))
out.append({"path": path, "mode": "100644", "type": "blob", "sha": "b" * 40, "size": 10})
blob = "b" * 40
if isinstance(files, dict):
blob = hashlib.sha1(("blob:" + files[path]).encode()).hexdigest()
if blobs is not None:
blobs[blob] = files[path]
out.append({"path": path, "mode": "100644", "type": "blob", "sha": blob, "size": 10})
out += [{"path": d, "mode": "040000", "type": "tree", "sha": "t" * 40} for d in dirs]
return sorted(out, key=lambda e: e["path"])

Expand Down Expand Up @@ -112,12 +123,20 @@ def do_GET(self):
if any(f.startswith(fpath + "/") for f in branches[ref]):
return self.reply(200, [{"type": "dir", "name": "x"}])
return self.reply(404, {"message": "GetContentsOrList", "errors": []})
if rest[:2] == ["git", "blobs"] and len(rest) == 3:
if st.fail_blobs:
return self.reply(500, {"message": "boom"})
if rest[2] not in st.blobs:
return self.reply(404, {"message": "object does not exist"})
raw = st.blobs[rest[2]].encode()
return self.reply(200, {"sha": rest[2], "size": len(raw), "encoding": "base64",
"content": base64.b64encode(raw).decode(), "url": "http://gitea/blob"})
if rest[:2] == ["git", "trees"]:
ref = "/".join(rest[2:])
if ref not in branches:
# Gitea 1.27: GetTreeBySHA -> 400 "sha not found [<ref>]"
return self.reply(400, {"message": f"sha not found [{ref}]", "url": "http://gitea/api/swagger"})
tree = tree_entries(branches[ref])
tree = tree_entries(branches[ref], st.blobs)
page = int(query.get("page", ["1"])[0])
per = min(int(query.get("per_page", ["1000"])[0]), st.tree_page_size)
start, end = per * (page - 1), per * page
Expand Down
Loading
Loading