diff --git a/.github/verify-pr-spike/spike.py b/.github/verify-pr-spike/spike.py index 2b415bb8f2..0cb12a582b 100644 --- a/.github/verify-pr-spike/spike.py +++ b/.github/verify-pr-spike/spike.py @@ -1,10 +1,12 @@ #!/usr/bin/env python3 """Test workflow script for #7127: the verify-pr Android steps on a Linux runner. -Builds the sample without the PR (its SDK change reverse-applied from its merge -commit) and with it, runs the skill's example flow on each build with the run -ids the workflow passes in, and records each side's crash event id from the -device log, with timings, disk usage and stale-bundle checks. +Runs from a checkout of main, against the `ref` checkout in $VERIFY_REF_DIR. +Builds the sample without the PR (its `packages/core` diff from $BASE_SHA +reverse-applied) and with it, rebuilding `packages/core` in between so each APK +bundles its own JavaScript, then runs the flow in $VERIFY_FLOW on each build +with the run ids the workflow passes in. Records timings, disk usage and bundle +checks. The fetch job finds the events by run id; no event id leaves this job. Each subcommand is one workflow step. Results go to $RUNNER_TEMP/verify-pr-spike, which the workflow uploads. @@ -14,7 +16,6 @@ import hashlib import json import os -import re import shutil import subprocess import sys @@ -22,33 +23,48 @@ import zipfile from pathlib import Path -REPO = Path(__file__).resolve().parents[2] +# The `ref` checkout: the code under test. This script comes from main. +REPO = Path(os.environ["VERIFY_REF_DIR"]).resolve() SAMPLE = REPO / "samples" / "react-native" -FLOW = REPO / ".agents/skills/verify-pr/flows/examples/turbo-module-calls-then-native-crash.yml" +FLOWS = REPO / ".agents/skills/verify-pr/flows" +# Validated by the workflow against a fixed pattern under FLOWS. +FLOW = REPO / os.environ["VERIFY_FLOW"] APP_ID = "io.sentry.reactnative.sample" OUT = Path(os.environ["RUNNER_TEMP"]) / "verify-pr-spike" RESULTS = OUT / "results.json" PATCH = OUT / f"pr{os.environ['VERIFY_PR']}.patch" SIDES = ("without", "with") +CORE = "packages/core" +CORE_SRC = f"{CORE}/src/" +# Same exclusions as the skill's patch (SKILL.md step 2). +PATCH_PATHS = ( + CORE, + f":!{CORE}/test", + f":!{CORE}/RNSentryAndroidTester", + f":!{CORE}/RNSentryCocoaTester", +) +# Fetch depths to try until the merge base of $BASE_SHA and HEAD is present. +MERGE_BASE_DEPTHS = (50, 500, 5000) +# Gradle doesn't see packages/core/dist as an input of the JS bundle task, so it +# keeps the previous side's bundle unless these go (references/android.md). +REACT_OUTPUTS = ( + "generated/assets/react/release", + "generated/res/react/release", + "generated/sourcemaps/react/release", + "intermediates/sourcemaps/react/release", +) # A string literal from samples/react-native/src/verifyRun.ts, so it is in both # bundles; the check is whether the skill's command reads the Hermes bundle on # Linux at all. BUNDLE_STRING = "verify.run_id" # Time for queued envelopes to be sent after the flow, before the next install. SEND_WAIT_SECONDS = 30 -# `adb logcat -d` prints the threadtime format: date, time, pid, tid, level, -# tag, message. -LOGCAT_LINE = re.compile( - r"^\S+\s+\S+\s+(?P\d+)\s+(?P\d+)\s+[VDIWEF]\s+(?P\S+)\s*: (?P.*)$" -) -UNCAUGHT = "Uncaught exception received." -CAPTURING = re.compile(r"Capturing event: ([0-9a-f]{32})") def load(): if RESULTS.exists(): return json.loads(RESULTS.read_text()) - return {"timings": {}, "marks": {}, "disk": {}, "bundle": {}, "runs": {}} + return {"timings": {}, "marks": {}, "disk": {}, "patch": {}, "bundle": {}, "runs": {}} def save(results): @@ -65,9 +81,12 @@ def git(*args, **kwargs): return run(["git", "-C", str(REPO), *args], **kwargs) +def git_out(*args): + return git(*args, capture_output=True, text=True).stdout.strip() + + def short_head(): - out = git("rev-parse", "--short", "HEAD", capture_output=True, text=True) - return out.stdout.strip() + return git_out("rev-parse", "--short", "HEAD") def sha256(path): @@ -100,19 +119,47 @@ def cmd_kvm(_args): run(["sudo", "udevadm", "trigger", "--name-match=kvm"]) +def cmd_flow(_args): + # Before any build: the flow must be a file on the ref branch, under FLOWS. + flow = FLOW.resolve() + if not flow.is_relative_to(FLOWS.resolve()) or not flow.is_file(): + sys.exit(f"the flow is not a file under {FLOWS.relative_to(REPO)} on the ref branch") + print(f"flow: {FLOW.relative_to(REPO)}") + + +def fetch_merge_base(base, head): + """Deepens the shallow checkout until `base...head` has a merge base.""" + for depth in MERGE_BASE_DEPTHS: + git("fetch", "--no-tags", f"--depth={depth}", "origin", base, head) + found = subprocess.run( + ["git", "-C", str(REPO), "merge-base", base, head], + capture_output=True, text=True, check=False, + ) + if found.returncode == 0: + return found.stdout.strip() + sys.exit(f"no merge base of the base sha and HEAD within {MERGE_BASE_DEPTHS[-1]} commits") + + def cmd_revert(_args): - merge_sha = os.environ["MERGE_SHA"].lower() - # The checkout is shallow; `git show` needs the merge commit and its parent. - git("fetch", "--no-tags", "--depth=2", "origin", merge_sha) + base = os.environ["BASE_SHA"].lower() + head = git_out("rev-parse", "HEAD") + merge_base = fetch_merge_base(base, head) + diff_range = f"{base}...HEAD" OUT.mkdir(parents=True, exist_ok=True) with PATCH.open("w") as patch: - git( - "show", "--format=", merge_sha, "--", "packages/core", - ":!packages/core/test", - ":!packages/core/RNSentryAndroidTester", - ":!packages/core/RNSentryCocoaTester", - stdout=patch, - ) + git("diff", diff_range, "--", *PATCH_PATHS, stdout=patch) + files = git_out("diff", "--name-only", diff_range, "--", *PATCH_PATHS).splitlines() + if not files: + sys.exit(f"git diff {diff_range} changes nothing under {CORE}") + results = load() + results["patch"] = { + "base_sha": base, + "merge_base": merge_base, + "head": head, + "files": files, + "changes_core_src": any(f.startswith(CORE_SRC) for f in files), + } + save(results) git("apply", "-R", "--check", str(PATCH)) git("apply", "-R", str(PATCH)) @@ -125,6 +172,9 @@ def cmd_build(args): side = args.side env = dict(os.environ, RN_ARCHITECTURE="new", CONFIG="release") start = time.time() + # Re-bundle from the packages/core/dist that the previous step just built. + for output in REACT_OUTPUTS: + shutil.rmtree(SAMPLE / "android/app/build" / output, ignore_errors=True) # `yarn build-android-release` drops extra arguments, so call the script it # wraps. x86_64 only: the emulator's ABI, instead of all four. run( @@ -164,30 +214,14 @@ def cmd_build(args): save(results) -def crash_event_ids(logcat): - """Ids of the crash events in a device log. - - A crash event is one the Android SDK logs as `Capturing event: ` in the - next `Sentry` line from the same process and thread as `Uncaught exception - received.`. The other ids in the log, such as envelope files, transactions - and the session, are not on such a line. - """ - ids = [] - crashed = set() - for line in logcat.splitlines(): - match = LOGCAT_LINE.match(line) - if not match or match["tag"] != "Sentry": - continue - thread = (match["pid"], match["tid"]) - message = match["msg"].strip() - if message == UNCAUGHT: - crashed.add(thread) - elif thread in crashed: - crashed.discard(thread) - capturing = CAPTURING.fullmatch(message) - if capturing: - ids.append(capturing[1]) - return ids +def cmd_check_bundles(_args): + results = load() + identical = results["bundle"]["without"]["bundle_sha256"] == results["bundle"]["with"]["bundle_sha256"] + results["bundle"]["identical"] = identical + save(results) + print(f"the two JavaScript bundles are {'identical' if identical else 'different'}") + if identical and results["patch"]["changes_core_src"]: + sys.exit(f"the PR changes files under {CORE_SRC} but both APKs bundle the same JavaScript") def adb(*args, **kwargs): @@ -200,7 +234,8 @@ def run_side(side, results): run_id = os.environ[f"RUN_ID_{side.upper()}"] commit = short_head() if side == "without": - commit = f"{commit}-{os.environ['MERGE_SHA'].lower()[:7]}" + # HEAD with its diff from the base sha reversed. + commit = f"{commit}-{os.environ['BASE_SHA'].lower()[:7]}" run_dir = OUT / run_id run_dir.mkdir(parents=True, exist_ok=True) record = {"run_id": run_id, "commit": commit} @@ -236,10 +271,6 @@ def run_side(side, results): (run_dir / f"{run_id}.logcat").write_text(logcat, encoding="utf-8") record["logcat_run_id_lines"] = logcat.count(run_id) record["logcat_envelopes_sent"] = logcat.count("Envelope sent successfully") - ids = crash_event_ids(logcat) - record["crash_event_ids"] = ids - if len(ids) == 1: - record["crash_event_id"] = ids[0] with (run_dir / "screencap.png").open("wb") as png: adb("exec-out", "screencap", "-p", stdout=png) # An all-black screenshot compresses to a few KB; a real one is much larger. @@ -257,22 +288,11 @@ def cmd_run(_args): for side in SIDES: if run_side(side, results) != 0: failures.append(f"the Maestro flow failed for {side}") - found = len(results["runs"][side]["crash_event_ids"]) - if found != 1: - failures.append(f"{found} crash event ids in the {side} device log, expected 1") save(results) if failures: sys.exit("; ".join(failures)) -def cmd_outputs(_args): - # The only values the fetch job gets from this job. - runs = load()["runs"] - with open(os.environ["GITHUB_OUTPUT"], "a") as fh: - for side in SIDES: - fh.write(f"{side}_event_id={runs[side]['crash_event_id']}\n") - - def cmd_summary(_args): results = load() marks = results["marks"] @@ -294,9 +314,9 @@ def main(): sub.add_parser("disk").add_argument("label") sub.add_parser("build").add_argument("side", choices=SIDES) commands = { - "mark": cmd_mark, "disk": cmd_disk, "kvm": cmd_kvm, "revert": cmd_revert, - "restore": cmd_restore, "build": cmd_build, "run": cmd_run, "outputs": cmd_outputs, - "summary": cmd_summary, + "mark": cmd_mark, "disk": cmd_disk, "kvm": cmd_kvm, "flow": cmd_flow, + "revert": cmd_revert, "restore": cmd_restore, "build": cmd_build, + "check-bundles": cmd_check_bundles, "run": cmd_run, "summary": cmd_summary, } for name, handler in commands.items(): (sub.choices.get(name) or sub.add_parser(name)).set_defaults(handler=handler) diff --git a/.github/workflows/verify-pr-spike.yml b/.github/workflows/verify-pr-spike.yml index 3d3e06b5b5..276b9372a7 100644 --- a/.github/workflows/verify-pr-spike.yml +++ b/.github/workflows/verify-pr-spike.yml @@ -3,16 +3,17 @@ name: verify-pr spike # Test workflow for #7127, to be replaced by the real verify-pr workflow. Started # by hand on main; the workflow file always comes from main, whatever `ref` is. # -# The build job checks out `ref`, builds the sample without the PR (its merge -# commit reverse-applied) and with it, runs the skill's example flow on each, and -# reads each side's crash event id from the device log. It holds no secrets. Its -# step logic is in .github/verify-pr-spike/spike.py, from the `ref` checkout. It -# hands the fetch job only the two crash event ids. +# The build job checks out `ref` in ref/ and main in main/. It builds the sample +# without the PR (its packages/core diff from `base_sha` reverse-applied) and +# with it, rebuilding packages/core before each side so each APK bundles its own +# JavaScript, and runs the `flow` from the ref branch on each. It holds no +# secrets. Its step logic is in .github/verify-pr-spike/spike.py, from the main +# checkout. It hands the fetch job nothing. # # The fetch job checks out nothing and runs no repository code: its logic is # inline below. It is the only job that gets SENTRY_AUTH_TOKEN. It builds the -# expected run ids itself from github.run_id and refuses any event whose -# verify.run_id differs. +# run ids itself from github.run_id, finds each side's error events by their +# verify.run_id tag, and refuses any event whose verify.run_id differs. on: workflow_dispatch: @@ -25,8 +26,12 @@ on: description: Number of the PR under test required: true type: string - merge_sha: - description: The PR's merge commit, which the build reverse-applies (40 hex characters) + base_sha: + description: The PR's base commit; the build reverse-applies the diff from it to `ref` (40 hex characters) + required: true + type: string + flow: + description: Maestro flow on `ref` to run, matching .agents/skills/verify-pr/flows/.yml required: true type: string @@ -51,14 +56,14 @@ jobs: permissions: contents: read env: - SPIKE: .github/verify-pr-spike/spike.py + # The script and the local action come from main, the code under test from ref. + SPIKE: ${{ github.workspace }}/main/.github/verify-pr-spike/spike.py + VERIFY_REF_DIR: ${{ github.workspace }}/ref VERIFY_PR: ${{ inputs.pr }} - MERGE_SHA: ${{ inputs.merge_sha }} + VERIFY_FLOW: ${{ inputs.flow }} + BASE_SHA: ${{ inputs.base_sha }} RUN_ID_WITHOUT: gh${{ github.run_id }}-without RUN_ID_WITH: gh${{ github.run_id }}-with - outputs: - without_event_id: ${{ steps.ids.outputs.without_event_id }} - with_event_id: ${{ steps.ids.outputs.with_event_id }} steps: - name: Validate the inputs id: validate @@ -66,7 +71,8 @@ jobs: env: INPUT_REF: ${{ inputs.ref }} INPUT_PR: ${{ inputs.pr }} - INPUT_MERGE_SHA: ${{ inputs.merge_sha }} + INPUT_BASE_SHA: ${{ inputs.base_sha }} + INPUT_FLOW: ${{ inputs.flow }} run: | import os import re @@ -75,7 +81,13 @@ jobs: PATTERNS = { "ref": ("INPUT_REF", r"verify/[A-Za-z0-9._-]+"), "pr": ("INPUT_PR", r"[0-9]+"), - "merge_sha": ("INPUT_MERGE_SHA", r"[0-9a-fA-F]{40}"), + "base_sha": ("INPUT_BASE_SHA", r"[0-9a-fA-F]{40}"), + # No segment starts with a dot, so no "..". + "flow": ( + "INPUT_FLOW", + r"\.agents/skills/verify-pr/flows/(?:[A-Za-z0-9_-][A-Za-z0-9._-]*/)*" + r"[A-Za-z0-9_-][A-Za-z0-9._-]*\.ya?ml", + ), } # Names only: an input's value is never printed. invalid = [ @@ -90,15 +102,27 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ inputs.ref }} + path: ref + persist-credentials: false + + # Only .github: the script and the disk-cleanup action. + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + path: main + sparse-checkout: .github persist-credentials: false + - name: Check the flow is on the ref branch + run: python3 "$SPIKE" flow + - name: Mark job start run: python3 "$SPIKE" mark job_start - name: Disk at start run: python3 "$SPIKE" disk start - - uses: ./.github/actions/disk-cleanup + - uses: ./main/.github/actions/disk-cleanup - name: Disk after cleanup run: python3 "$SPIKE" disk after_cleanup @@ -139,23 +163,36 @@ jobs: print("SENTRY_AUTH_TOKEN is not set") - name: Install SDK Dependencies + working-directory: ref run: yarn install - name: Build SDK + working-directory: ref run: yarn build - name: Reverse-apply the PR run: python3 "$SPIKE" revert + - name: Build packages/core without the PR + working-directory: ref/packages/core + run: yarn build + - name: Build without the PR (clean) run: python3 "$SPIKE" build without - name: Restore the PR run: python3 "$SPIKE" restore + - name: Build packages/core with the PR + working-directory: ref/packages/core + run: yarn build + - name: Build with the PR (incremental) run: python3 "$SPIKE" build with + - name: Check each APK bundles its own JavaScript + run: python3 "$SPIKE" check-bundles + - name: Disk after builds run: python3 "$SPIKE" disk after_builds @@ -186,10 +223,6 @@ jobs: -camera-front none script: python3 "$SPIKE" run - - name: Hand the event ids to the fetch job - id: ids - run: python3 "$SPIKE" outputs - - name: Disk at end if: ${{ always() && steps.validate.outcome == 'success' }} run: python3 "$SPIKE" disk end @@ -210,7 +243,7 @@ jobs: retention-days: 14 fetch: - name: Fetch the crash events from Sentry + name: Fetch the error events from Sentry needs: build runs-on: ubuntu-latest timeout-minutes: 20 @@ -218,22 +251,21 @@ jobs: contents: read steps: # No checkout: everything this job runs is in this file. - - name: Fetch the two crash events + - name: Find and fetch each side's error events shell: python env: SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} - WITHOUT_EVENT_ID: ${{ needs.build.outputs.without_event_id }} - WITH_EVENT_ID: ${{ needs.build.outputs.with_event_id }} EXPECTED_RUN_ID_WITHOUT: gh${{ github.run_id }}-without EXPECTED_RUN_ID_WITH: gh${{ github.run_id }}-with FETCH_OUT: ${{ runner.temp }}/verify-pr-spike-events run: | - """Fetches each side's crash event and keeps only the fields the check needs. + """Finds each side's error events by run id and keeps only the fields the check needs. - Same auth as dev-packages/e2e-tests/maestro/utils/sentryApi.js. Reads each event - from two endpoints: /json/ (the raw event, which drops null-valued tags) and the - event detail endpoint (which keeps them). Prints only URLs, status codes and the - small files it writes: never the token, the request headers or a response body. + Same auth as dev-packages/e2e-tests/maestro/utils/sentryApi.js. Searches the org's + error events for each side's verify.run_id, then reads each event it finds from + two endpoints: /json/ (the raw event, which drops null-valued tags) and the event + detail endpoint (which keeps them). Prints only URLs, status codes and the small + files it writes: never the token, the request headers or a response body. """ import json @@ -242,20 +274,32 @@ jobs: import sys import time import urllib.error + import urllib.parse import urllib.request from pathlib import Path - BASE_URL = "https://sentry.io/api/0/projects/sentry-sdks/sentry-react-native" + API_URL = "https://sentry.io/api/0" + ORG = "sentry-sdks" + PROJECT = "sentry-react-native" + PROJECT_URL = f"{API_URL}/projects/{ORG}/{PROJECT}" + SEARCH_ENDPOINT = f"/organizations/{ORG}/events/" JSON_ENDPOINT = "/events//json/" DETAIL_ENDPOINT = "/events//" SIDES = ("without", "with") - # Per request, including the request itself. Four requests at most take 12 of - # the job's 20 minutes. + # Per request, including the request itself, and for the search until it finds + # an event. A search and then each event's two requests normally answer at once. DEADLINE_SECONDS = 180 RETRY_SECONDS = 5 REQUEST_TIMEOUT_SECONDS = 30 - # The detail endpoint may refuse a token that /json/ accepts; fall back then. - DETAIL_REFUSALS = (401, 403) + # Wider than the build job's 120 minutes; the run id is unique to this run. + SEARCH_PERIOD = "24h" + # Events read per side, earliest first. + MAX_EVENTS = 5 + # Statuses no retry can change. A 404 is retried: the event may not be stored yet. + FINAL_STATUSES = (400, 401, 403) + # The token may be refused on the search or the detail endpoint; /json/ has + # accepted it so far. + REFUSALS = (401, 403) EVENT_ID = re.compile(r"[0-9a-f]{32}") KEPT_TAG_PREFIXES = ("verify.", "turbo_module.") OUT = Path(os.environ["FETCH_OUT"]) @@ -270,12 +314,11 @@ jobs: OPENER = urllib.request.build_opener(NoRedirect) - def fetch(endpoint, event_id, token, refusals=()): - """(status, JSON) for an endpoint, retried until it exists or the deadline passes. + def fetch(url, token, refusals=(), ready=lambda body: True): + """(status, JSON) for a URL, retried until `ready(JSON)` or the deadline passes. A status in `refusals` is returned with no JSON instead of failing. """ - url = BASE_URL + endpoint.replace("", event_id) request = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) deadline = time.monotonic() + DEADLINE_SECONDS attempt = 0 @@ -285,18 +328,19 @@ jobs: remaining = max(1, deadline - time.monotonic()) timeout = min(REQUEST_TIMEOUT_SECONDS, remaining) with OPENER.open(request, timeout=timeout) as response: - body = response.read() - print(f"{url}: HTTP 200 on attempt {attempt}", flush=True) - return 200, json.loads(body) + body = json.loads(response.read()) + if ready(body): + print(f"{url}: HTTP 200 on attempt {attempt}", flush=True) + return 200, body + status = "HTTP 200, not ready" except urllib.error.HTTPError as error: status = f"HTTP {error.code}" error.close() if error.code in refusals: - print(f"{url}: {status}, falling back to {JSON_ENDPOINT}", flush=True) return error.code, None - # sentryApi.js gives up on 403 only; 401 and redirects cannot + # sentryApi.js gives up on 403 only; 400, 401 and redirects cannot # succeed on a retry either. - if error.code in (401, 403) or 300 <= error.code < 400: + if error.code in FINAL_STATUSES or 300 <= error.code < 400: raise RuntimeError(f"{url}: {status}, not retrying") from None except OSError as error: status = type(error).__name__ @@ -309,6 +353,36 @@ jobs: time.sleep(RETRY_SECONDS) + def search(run_id, token): + """Ids of the run's error events, waiting until there is at least one.""" + params = urllib.parse.urlencode( + [ + ("dataset", "errors"), + ("projectSlug", PROJECT), + ("statsPeriod", SEARCH_PERIOD), + ("field", "id"), + ("field", "timestamp"), + ("query", f'verify.run_id:"{run_id}" event.type:error'), + ("sort", "timestamp"), + ("per_page", str(MAX_EVENTS)), + ] + ) + url = f"{API_URL}{SEARCH_ENDPOINT}?{params}" + status, body = fetch(url, token, REFUSALS, ready=lambda body: bool(body.get("data"))) + if body is None: + raise RuntimeError( + f"the token was refused on the search endpoint {SEARCH_ENDPOINT}: HTTP {status}" + ) + ids = [] + for row in body["data"]: + event_id = row.get("id") + if not isinstance(event_id, str) or not EVENT_ID.fullmatch(event_id): + raise RuntimeError(f"{SEARCH_ENDPOINT}: malformed event id in the results") + if event_id not in ids: + ids.append(event_id) + return ids + + def kept(tags): keys = sorted(k for k in tags if isinstance(k, str) and k.startswith(KEPT_TAG_PREFIXES)) return {key: tags[key] for key in keys} @@ -356,6 +430,28 @@ jobs: return codes + def exception_frames(exceptions): + """Each exception's type and frames, as Sentry stored them, oldest frame first. + + Only filename, function and in_app: in_app is the stored value, after + Sentry's own in-app rules ran. + """ + return [ + { + "type": exception.get("type"), + "frames": [ + { + "filename": frame.get("filename"), + "function": frame.get("function"), + "in_app": frame.get("in_app"), + } + for frame in (exception.get("stacktrace") or {}).get("frames") or [] + ], + } + for exception in exceptions + ] + + def check_run_id(tags, event_id, run_id, endpoint): if tags.get("verify.run_id") != run_id: raise RuntimeError(f"{event_id}: refused, verify.run_id from {endpoint} is not {run_id}") @@ -375,11 +471,13 @@ jobs: # Sentry lists chained exceptions innermost first; the last is the # one the issue is titled after. "exception_type": exceptions[-1].get("type") if exceptions else None, + "exceptions": exception_frames(exceptions), } source = { "event_id": JSON_ENDPOINT, "platform": JSON_ENDPOINT, "exception_type": JSON_ENDPOINT, + "exceptions": JSON_ENDPOINT, } if detail is not None: if detail.get("eventID") != event_id: @@ -401,6 +499,16 @@ jobs: return summary + def read_event(event_id, run_id, token): + url = PROJECT_URL + JSON_ENDPOINT.replace("", event_id) + _, raw = fetch(url, token) + url = PROJECT_URL + DETAIL_ENDPOINT.replace("", event_id) + detail_status, detail = fetch(url, token, REFUSALS) + if detail is None: + print(f"{url}: HTTP {detail_status}, falling back to {JSON_ENDPOINT}", flush=True) + return summarize(event_id, run_id, raw, detail_status, detail) + + def main(): token = os.environ.get("SENTRY_AUTH_TOKEN", "") if not token: @@ -408,21 +516,17 @@ jobs: OUT.mkdir(parents=True, exist_ok=True) failures = [] for side in SIDES: - event_id = os.environ[f"{side.upper()}_EVENT_ID"] - # Built in this job from github.run_id, not taken from the build job. + # Built in this job from github.run_id; nothing comes from the build job. run_id = os.environ[f"EXPECTED_RUN_ID_{side.upper()}"] - if not EVENT_ID.fullmatch(event_id): - failures.append(f"{side}: malformed event id from the build job") - continue try: - _, raw = fetch(JSON_ENDPOINT, event_id, token) - detail_status, detail = fetch(DETAIL_ENDPOINT, event_id, token, DETAIL_REFUSALS) - summary = summarize(event_id, run_id, raw, detail_status, detail) + ids = search(run_id, token) + events = [read_event(event_id, run_id, token) for event_id in ids] except (RuntimeError, ValueError, AttributeError, TypeError) as error: # None of these messages carries a response body. failures.append(f"{side}: {type(error).__name__}: {error}") continue - text = json.dumps(summary, indent=2) + "\n" + result = {"run_id": run_id, "search_endpoint": SEARCH_ENDPOINT, "events": events} + text = json.dumps(result, indent=2) + "\n" (OUT / f"{side}.json").write_text(text) print(f"{side}.json:\n{text}", flush=True) if failures: