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
6 changes: 3 additions & 3 deletions design/workstreams/provider-github/LLD/github-provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ Untrusted text (issue/PR bodies, comments) is stored as **content refs** (`githu

- Issue: state, labels, sub-issues, linked PRs, comments count.
- Deploy: for work items with merged PRs, the latest `github-pages` deployment of the default branch → `item.deploy{state, sha, url, containsMerge}` (`containsMerge`: every merge commit of the item's PRs is an ancestor of `sha`, via the compare API). docs' Pages workflow cancels in-progress deploys, so only the latest one matters.
- PR: `isDraft`, `headRefOid`, `baseRefName`, labels, `reviews(last:20){author, state, commit{oid}}` → `approvedBy[]{identity, commit}`, `reviewThreads(first:100){isResolved}` → `unresolvedThreads`, `commits(last:1){checkSuites(first:100){status, conclusion, checkRuns{totalCount}}}` → `checks{state, settled}`, merged/mergedAt/mergeCommit, author (factory or not).
- PR: `isDraft`, `headRefOid`, `baseRefName`, labels, `reviews(last:20){author, state, commit{oid}}` → `approvedBy[]{identity, commit}`, `reviewThreads(first:100){isResolved}` → `unresolvedThreads`, `commits(last:1){checkSuites(first:100){databaseId, createdAt, status, conclusion, app{databaseId}, workflowRun{runNumber, event, workflow{databaseId}}, checkRuns{totalCount}}}` → `checks{state, settled}` (only the latest suite per workflow and event counts: see the roll-up below), merged/mergedAt/mergeCommit, author (factory or not).

There is no `List`, and `Observe` doesn't read the markers back: the work-item rebuild that used them is gone (P3 §No rebuild from markers), and the store is the authority. The markers and labels are for people to read. Only `Project` reads the App's own markers, to find the one it updates and which labels other work items own.

Expand Down Expand Up @@ -160,12 +160,12 @@ Implemented in GH-S1-T04; the details are in [§Decisions taken in GH-S1-T04](#d
- **GraphQL by hand, no new dependency.** The queries are constants in `observe.go`, posted by the new `tokens.Minter.GraphQL(ctx, token, op, query, vars, out)` and decoded with `encoding/json`, rather than through `githubv4`: errors then map like every other call (HTTP errors as in T01; a response with `errors` is a `*tokens.GraphQLError`, `NOT_FOUND` → `ErrNotFound`, `FORBIDDEN` → `tokens.ErrForbidden` and `provider.ErrForbidden`, a permission problem callers can tell from a transient one, `RATE_LIMITED` → `*provider.RetryableError`), the recorded responses under `testdata/graphql` are plain JSON, and `githubtest` answers by operation name. **A response with errors fails even with partial data**: an observation missing a field could make a rule merge. The endpoint is `<api>/graphql`, or `https://<host>/api/graphql` for a GHE REST base `…/api/v3` (`tokens.GraphQLURL`). `tokens` also gained `Do` (any method with an installation token, optional body and decoding), `NextPage` (the Link `rel="next"` query), and 410 (a deleted issue) now maps to `ErrNotFound`.
- **`Observe(ref)`** is one `Observe` query on `repository.issueOrPullRequest(number)`, so a ref of the other kind (an issue ref naming a PR) is `ErrNotFound`, as the fake does, and an empty kind is filled in. Follow-up queries (`ObserveComments`, `ObserveThreads`, by node ID and cursor) read comments and review threads past the first 100, up to 10 more pages each (`ObserveComments` went with the markers' read-back: [§P3](#decisions-taken-with-p3-no-list-no-marker-read-back)). Labels (first 100), sub-issues (GitHub caps them at 100) and reviews (`last: 100`, not the LLD's 20, so an old approval isn't cut off by a chatty review) are one page.
- Issue: state, labels, author, `subIssues` → `SubIssues`, `closedByPullRequestsReferences` (open and closed) → `LinkedPRs`, `comments.totalCount` → `Comments`.
- PR: `isDraft`, `headRefOid`, `baseRefName`, labels, author, `mergedAt`, `mergeCommit` (only once merged). `checks` rolls up the last commit's check suites that have check runs: `failure` once one concluded failing (failure, timed out, cancelled, action required, startup failure, stale), else `pending` while one runs, else `success` (success, neutral, skipped); `settled` for `success` and `failure`; no such suite leaves `checks` empty. **Not `statusCheckRollup`** (fx/gh-observe-perms): it also covers commit statuses (`statuses: read`), which the Apps aren't granted, and check suites are what `pr.checks.completed` reports, so commit statuses don't count. `approvedBy` is each reviewer's **latest opinion** (`APPROVED`, `CHANGES_REQUESTED`, `DISMISSED`; comments and pending reviews don't change it) when it is an approval, at that review's commit, sorted. The factory's Apps map to their identity (`ccf-factory-reviewer[bot]` → `reviewer`, `ccf-factory[bot]` → `author`, from the slugs T02 learns), anyone else to their login; a deleted account counts for nobody. `unresolvedThreads` counts `isResolved: false` across all pages.
- PR: `isDraft`, `headRefOid`, `baseRefName`, labels, author, `mergedAt`, `mergeCommit` (only once merged). `checks` rolls up the last commit's check suites that have check runs, **keeping only the latest suite of each workflow** (fx/checks-latest-suite): a GitHub Actions suite's kind is its App, workflow and event (`app{databaseId}`, `workflowRun{workflow{databaseId}, event}`); the latest is the highest workflow run number, then the newest `createdAt`, then the highest `databaseId`, and a suite with runs isn't superseded by a later one without. A suite whose workflow can't be told (no App, a null `workflowRun`: another App's suite such as CodeRabbit's, or an Actions suite whose run was deleted; a null `workflow`) is **never superseded and supersedes nothing**, so a failing suite can't hide behind an unrelated green one. So a run cancelled by its concurrency group, or a failed run re-triggered by a later green one, no longer turns a green PR into `failure` (compliance-framework/api#584: a cancelled `preview` run beside its green successor). A re-run (`rerun-failed-jobs`, re-run all jobs) is a new attempt of the same workflow run and GitHub keeps it in the same check suite, whose status and conclusion are the latest attempt's (checked on GitHub: a run's `check_suite_id` is unchanged by a re-run, and that suite went from failure to success), so attempts need no handling. The event is part of the kind because a `push` and a `pull_request` run of one workflow are separate checks (separate concurrency groups in practice): a failing `push` run isn't hidden by a green `pull_request` one. Of the kept suites: `failure` once one concluded failing (failure, timed out, cancelled, action required, startup failure, stale), else `pending` while one runs, else `success` (success, neutral, skipped); `settled` for `success` and `failure`; no such suite leaves `checks` empty. **Not `statusCheckRollup`** (fx/gh-observe-perms): it also covers commit statuses (`statuses: read`), which the Apps aren't granted, and check suites are what `pr.checks.completed` reports, so commit statuses don't count. `approvedBy` is each reviewer's **latest opinion** (`APPROVED`, `CHANGES_REQUESTED`, `DISMISSED`; comments and pending reviews don't change it) when it is an approval, at that review's commit, sorted. The factory's Apps map to their identity (`ccf-factory-reviewer[bot]` → `reviewer`, `ccf-factory[bot]` → `author`, from the slugs T02 learns), anyone else to their login; a deleted account counts for nobody. `unresolvedThreads` counts `isResolved: false` across all pages.
- Author: `<provider>:<login>` with REST's spelling (GraphQL's Bot `ccf-factory` is `ccf-factory[bot]`, as in webhooks), `isBot`, and `isFactory`/`identity` for the factory's Apps; nil for a deleted account.
- Projections (removed with P3: [§P3](#decisions-taken-with-p3-no-list-no-marker-read-back)): the v1 markers among the comments **written by the projecting App** (the author identity); a look-alike by anyone else, or a marker of another version, is ignored (the latter with a warning). Of two markers for one work item the oldest comment wins. Comment bodies are read only for that and never returned.
- **Other kinds**, because the work-item view and the rule controller's probe treat any error but `ErrNotFound` as fatal: a `repo` link (an event without an object) is open, or closed once archived (`ObserveRepo`, `metadata: read`); releases and deployments are immutable records, `closed` with no call. Any other kind is `ErrInvalid`.
- **Deploy** is set on **merged PRs only**: the latest deployment (REST `GET …/deployments?environment=<env>&ref=<default branch>&per_page=1`) to `Options.DeployEnvironment` (default `github-pages`), its latest status's `state` (`pending` when it has none) and `environment_url` (else `target_url`), its `sha`, and `containsMerge` when this PR's merge commit is ahead-or-identical by the compare API (shared with T02's deployment linking). Observe is per object, so "every merge commit of the item's PRs" can't be computed here. **Gap for RT:** `buildView` takes `item.deploy` from the primary link, else the first link with one, so for a stack it reflects one PR; `announce-ptbr-live` should see `containsMerge` ANDed over the item's merged PRs (the controller can combine the PRs' `Deploy`).
- **Tokens and identities.** Everything is the author identity (`readIdentity`, as in T02). Observe and List read with `{issues, pull_requests, contents, checks: read}` on the object's repo (`contents` for the Commit objects the query reaches: head, merge commit, reviews' commits; `checks` for the head's check suites) (one cache key, so List's token serves the Observes that follow); the deployment with `{contents, deployments: read}`. Project reads the issue and its comments with the read token (a `pull_requests`-only token can't tell an issue from a missing one) and writes with **`issues: write` on an issue, `pull_requests: write` on a PR**, nothing else.
- **Tokens and identities.** Everything is the author identity (`readIdentity`, as in T02). Observe and List read with `{issues, pull_requests, contents, checks, actions: read}` on the object's repo (`contents` for the Commit objects the query reaches: head, merge commit, reviews' commits; `checks` for the head's check suites; `actions` for each suite's `workflowRun`, which the App's **actions: read** grant covers, fx/checks-latest-suite) (one cache key, so List's token serves the Observes that follow); the deployment with `{contents, deployments: read}`. Project reads the issue and its comments with the read token (a `pull_requests`-only token can't tell an issue from a missing one) and writes with **`issues: write` on an issue, `pull_requests: write` on a PR**, nothing else.
- **Marker format v1** (`marker.go`), as the LLD's, with what round-tripping needed: `links` are `provider:ref[:kind[:primary]]`, so the rebuild gets kinds and the primary back; a new **`labels=`** field records the factory-owned labels this work item put on the object; every key and value is percent-encoded (only `A-Z a-z 0-9 . _ ~ -` stay), so no value can hold a space, comma, colon, `>` or `-->`; non-string state values (numbers, bools, maps, lists) are `b64:` base64url JSON, and parse back as a JSON round trip gives them (`float64`, `[]any`), as the controller's state already is. Unknown fields are ignored, so v1 can grow. The visible line links to `<Options.UIBaseURL>/workitems/<id>` when the new `Options.UIBaseURL` is set (`serve` wiring is GH-S1-T04), else it has no link. Over 60 KB the marker is written without `state` and a warning is logged; still over is `ErrInvalid`.
- **`Project(ref, p)`**: (1) labels, then (2) the marker, so a failed marker write is retried with the old ownership still on record. Labels: add the projection's labels the object lacks; remove those the work item's **previous marker** owned that the projection dropped, unless another work item's marker on the object owns them too. Nothing else is ever removed, a human's `factory:stop` included. Names compare case-insensitively, as GitHub does; a 404 on removal is success. Marker: the oldest marker the author App wrote for the work item is edited (`PATCH …/issues/comments/{id}`) when its body differs, else one is created. The same projection again makes no write. Releases, deployments and repos carry no marker: projecting onto them is a no-op (the controller would otherwise fail the reconcile).
- **`List(scope)`** (removed with P3: [§P3](#decisions-taken-with-p3-no-list-no-marker-read-back)): per repo, two searches (`GET /search/issues`, 100 per page, at most 10 pages: GitHub's 1000-result cap, with a warning): `repo:<r> is:open updated:>=<now−90d>` and `repo:<r> "Tracked by CCF Factory" in:comments updated:>=<now−90d>` (the marker's visible text, rather than the hidden header, which search may not index). **The marker search is bounded by the same 90 days**, unlike the LLD: an item older than that is past the work items' retention, so rebuilding it would only retire it again. The kind comes from the result's `pull_request` key; refs are unique and sorted.
Expand Down
34 changes: 29 additions & 5 deletions internal/provider/github/githubtest/objects.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,21 @@ type Object struct {
}

// CheckSuite is one check suite of a commit: Status (QUEUED, IN_PROGRESS, COMPLETED, …),
// Conclusion once completed (SUCCESS, FAILURE, …) and how many check runs it has.
// Conclusion once completed (SUCCESS, FAILURE, …) and how many check runs it has. ID, Created
// and App are the suite's databaseId, createdAt and App (zero: null, an App not read); a
// workflow run's suite (GitHub Actions) also has Workflow (the workflow's databaseId),
// RunNumber and Event; without both Workflow and RunNumber its workflowRun is null, and with a
// RunNumber but no Workflow the run's workflow is null.
type CheckSuite struct {
Status string
Conclusion string
Runs int
ID int64
Created time.Time
App int64
Workflow int64
RunNumber int
Event string
}

// Merge blocks (Object.MergeBlock).
Expand Down Expand Up @@ -665,15 +675,17 @@ func (s *Server) handleGraphQL(w http.ResponseWriter, r *http.Request) {

// fieldPerms are the permissions an installation token needs for GraphQL fields, as GitHub
// checks them: Commit objects (a PR's commits, its merge commit, a review's commit) need
// contents, a commit's check suites checks, its status rollup and status statuses. The server
// matches the query text, so it is stricter than GitHub, which checks only the fields it
// resolves (an issue's observation doesn't reach the PR fragment's commits).
// contents, a commit's check suites checks, a check suite's workflow run actions, its status
// rollup and status statuses. The server matches the query text, so it is stricter than
// GitHub, which checks only the fields it resolves (an issue's observation doesn't reach the
// PR fragment's commits).
var fieldPerms = []struct {
field *regexp.Regexp
perm string
}{
{regexp.MustCompile(`\b(?:commit|mergeCommit)\s*\{`), "contents"},
{regexp.MustCompile(`\b(?:checkSuites|checkRuns)\b`), "checks"},
{regexp.MustCompile(`\bworkflowRun\s*\{`), "actions"},
{regexp.MustCompile(`\b(?:statusCheckRollup|status)\s*\{`), "statuses"},
}

Expand Down Expand Up @@ -751,7 +763,19 @@ func (s *Server) gqlObserve(repo string, n int) map[string]any {
if cs.Conclusion != "" {
conclusion = cs.Conclusion
}
suites[i] = map[string]any{"status": cs.Status, "conclusion": conclusion, "checkRuns": map[string]any{"totalCount": cs.Runs}}
suite := map[string]any{"databaseId": cs.ID, "createdAt": cs.Created.UTC().Format(time.RFC3339), "status": cs.Status, "conclusion": conclusion,
"app": nil, "workflowRun": nil, "checkRuns": map[string]any{"totalCount": cs.Runs}}
if cs.App != 0 {
suite["app"] = map[string]any{"databaseId": cs.App}
}
if cs.Workflow != 0 || cs.RunNumber != 0 {
var workflow any // null: a run without its workflow
if cs.Workflow != 0 {
workflow = map[string]any{"databaseId": cs.Workflow}
}
suite["workflowRun"] = map[string]any{"runNumber": cs.RunNumber, "event": cs.Event, "workflow": workflow}
}
suites[i] = suite
}
obj["commits"] = map[string]any{"nodes": []any{map[string]any{"commit": map[string]any{"oid": o.Head, "checkSuites": map[string]any{"nodes": suites}}}}}
} else {
Expand Down
Loading