onetaskgraph_github_projects/lib.rs
1//! A stateless onetaskgraph source over one GitHub Projects v2 board.
2//!
3//! **A board is a container of projects, not a project.** Its own `title`,
4//! `shortDescription` and `readme` are never read as an item's fields and are never
5//! written: nothing in this source can rename the board a user configured.
6//!
7//! **A project is an issue and its tasks are that issue's sub-issues.** GitHub's schema
8//! decides that: `Issue` exposes `parent`, `subIssues` and `subIssuesSummary`, and
9//! `DraftIssue` exposes none of them. Creating an issue needs a `repositoryId`, and a
10//! board has none, so a write without [`GitHubProjectsConfig::repository`] is refused
11//! naming the field — but that repository is the *fallback*, not the home of every item.
12//!
13//! <!-- llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] The rule's one
14//! executable source is `GitHubProjectsSource::creation_target`; this is where a reader of
15//! the module meets it, and `tests/plugin.rs` drives every arm below against the loopback
16//! board and asserts on `createIssue`'s own `repositoryId`, so the prose cannot outlive a
17//! change to the rule. -->
18//! **Which repository an issue is created in is decided by the item's own `repositories`
19//! field, under one rule.** Exactly one entry names the repository the issue is created in:
20//! a task issue is where a person finds the work from the repository it changes, and one
21//! filed in a board's nominated repository is invisible from every other. Zero entries, or
22//! two or more, name none, so a task's or a document's issue is created in the repository
23//! its parent project's issue lives in — read from the board, or from this process's own
24//! record of a project it created earlier in the same command — and a project's issue, or
25//! a task or document written with no parent, is created in the configured `repository:`.
26//! What that rule refuses, it refuses before `createIssue`, so no issue is half-created. An
27//! existing issue is never moved: the update path leaves the issue where it is and records
28//! the list in the metadata slot when it differs, so the read side's derivation and the
29//! creation rule agree by construction.
30//! <!-- llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate] -->
31//!
32//! **A document is an ordinary issue whose title begins [`DESIGN_TITLE_PREFIX`].** A
33//! board has no document type and nothing but issues to hold one in, so the title is the
34//! discriminator and it is the whole of it. The title this source *reports* is the one a
35//! person wrote, with the prefix taken off — the same way the metadata slot is taken off
36//! the body so `content` is what the person wrote — and writing a document puts the prefix
37//! back, so a round trip returns the title that went in.
38//!
39//! **Telling a document from a project from a task.** The design prefix is read **first**:
40//! a document is never a project and never a task, whatever sub-issues it has or does not
41//! have. Only then does the rest apply — a board issue is a project when *either* it has
42//! sub-issues *or* it carries [`ItemKind::METADATA_KEY`]; otherwise it is a task. A
43//! sub-issue is always a task, whatever it carries. The marker is sufficient and never
44//! necessary: it is what makes an *empty* project — the state a project copy passes
45//! through between creating the project and filing its first task — readable as a
46//! project, while the sub-issue arm lets a person author a project on the board by hand
47//! with no knowledge of this product's metadata at all. Reading the prefix later than the
48//! sub-issue rule would make a design issue with no sub-issues an empty project, which is
49//! exactly the state that rule exists to catch. Pull requests are neither a project nor a
50//! task nor a document and are ignored.
51//!
52//! **A task's comments are its issue's comments.** They are read off `Issue.comments` and
53//! written with `addComment`, `updateIssueComment` and `deleteIssueComment`, and a comment's
54//! id is GitHub's own node id for the `IssueComment`. Two things GitHub decides are refused
55//! rather than papered over: a board **draft** is not an issue and has no comments at all, so
56//! a comment call on one is refused rather than answered with an empty page; and GitHub signs
57//! every comment as the account the token belongs to, so a comment handed an author of its
58//! own is refused rather than posted under another name. GitHub's comment mutations take the
59//! comment's id and nothing else, so an edit or a delete first reads which issue that comment
60//! is on, and a comment on some other issue is one this task does not have.
61//!
62//! **Where an entity is, is a link.** Every project, task and document this source reports
63//! carries a [`Location::Url`] naming the issue's own web address — the same address the
64//! `url` field already reports, in the shape that says a reader can open it. That is the
65//! contrast the location contract exists for: a reader holding an entity from this source
66//! is handed something to link to and one holding an entity from a folder of Markdown is
67//! handed a path, and neither has to know which plugin answered. It does not replace or
68//! derive from `url`; that field goes on reporting what it always reported.
69//!
70//! **Where metadata lives.** Short typed things go to typed fields and native relations:
71//! status to the board's `Status` single-select and the issue's own state, the copy
72//! origin to a source-owned `onetaskgraph.origin` text field, and dependencies to
73//! `blockedBy` and to sub-issue links. Unbounded caller JSON goes in a trailing
74//! `<!-- onetaskgraph.metadata ... -->` comment at the end of the issue body — the same
75//! encoding `docs/metadata.md` settles for Linear, not a second one. A ProjectV2 text
76//! field is length-bounded and `shortDescription` is capped at 300 characters, which is
77//! why neither can hold a caller's own prose. Setting one caller key on its own — on a task,
78//! a project or a document alike — is one update of the issue body that changes that slot
79//! and not one byte outside it, and it is not sent at all when the key already holds the
80//! value. The link a copy records on an item it copied, `onetaskgraph.copies`, is small and
81//! is kept in that same slot, written by that same update.
82//!
83//! **A caller's value can also be projected onto a board text field**, so the board can filter
84//! on it: each [`GitHubProjectsConfig::metadata_fields`] entry names a text field, a top-level
85//! metadata key and a path inside its value. The slot stays the value's one home — every read
86//! reports metadata from it alone — and the field follows it on every write of an item, a
87//! create, an update and a copy alike: a string is written, and not sent again while the field
88//! holds it — an empty string included, which is written as itself; nothing there or `null`
89//! clears a field holding a value; any other
90//! JSON type is refused before any mutation. It rides the ordered [`graphql::UPDATE_FIELDS`]
91//! write beside `Status`, `Priority` and the origin, so it adds no request; a key set on its
92//! own moves its field first and the body last, as every write of an existing item does. A
93//! board without the field, or with a non-text field of that name, is refused before any
94//! mutation pointing at `sources fields`, whose [`GitHubProjectsSource::fields`] creates it as
95//! a text field and never changes a field that is there.
96//!
97// llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] This public module documentation is a required user-facing description; the loopback plugin tests and shared live journey drive StatusMapping resolution, both mutations, and observed read-back together.
98//! **Status.** `status_mapping` is per-instance configuration, in the shared grammar
99//! [`onetaskgraph_plugin_api::StatusMapping`] documents, from a status category to an
100//! option of the board's one `Status` field for a task and for a project: a bare name is
101//! the option for both kinds, `null` disables the category for both, and `{task, project}`
102//! names it per kind. A category the mapping does not mention keeps its shipped default for
103//! both kinds; one it mentions is exactly what it configures, so a per-kind object no longer
104//! gets the shipped default for the kind it leaves out. Two categories one kind would read
105//! back from one option are refused as the configuration is read, ignoring case, while one
106//! option may stand for different categories of the two kinds. Writes go by the kind of the
107//! item written: a status that kind has no option for, or whose option the board lacks, is
108//! refused before any mutation, naming the source, the kind, the category and the key
109//! `status_mapping.<category>.<kind>` — there is no fallback. `done` selects its mapped
110//! option and closes the issue as `COMPLETED`; `cancelled` selects its mapped option and
111//! closes it as `NOT_PLANNED`, for either kind. Every open category reopens a closed issue
112//! before selecting its option. Reads give a closed issue's reason precedence over its
113//! option, while an open issue's option decides its category through its own kind's
114//! mapping, and an option that mapping does not name reads as `unknown` under its own name.
115//! The guarded [`GitHubProjectsSource::status_options`] and
116//! [`GitHubProjectsSource::fields`] operations are the one path here that calls
117//! `updateProjectV2Field`: GitHub replaces the whole option list, so they preserve every
118//! existing option id and verify the field and item assignments immediately afterwards.
119//! They ask for both kinds' options, counting a terminal category's mapped option as
120//! configured because a terminal write refuses without it. No ordinary source read or
121//! write calls that mutation, whose
122//! `singleSelectOptions` *overwrites* a field's option set, so no addition is additive
123//! and a mistake destroys every item's status. A status this board cannot represent is a
124//! refusal naming the status and the instance instead.
125//!
126//! `unknown` has no shipped option because this source cannot preserve an open-ended
127//! status word: it writes an existing board option and never
128//! creates an option. An operator may map `unknown` to one existing option, in which case
129//! every unknown word lands on that option and reads back as `unknown` under the option's
130//! name. This differs from `local-md`, which writes and reads the original word itself.
131//!
132//! The shipped terminal options are exactly `done: Done` and `cancelled: Cancelled`.
133//! `done` also closes the issue because GitHub derives `subIssuesSummary.completed`
134//! and the board's own `Sub-issues progress` field from closed sub-issues: a plan whose
135//! finished tasks were only moved to a "Done" column would read 0% complete forever.
136// llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
137//!
138//! # What this source declares, field by field
139//!
140//! One verdict per field of [`Capabilities`], and what `Native` means when this source
141//! says it. *Proven* means a shared journey drives it against the real
142//! binary over this source's own row in `crates/onetaskgraph-e2e-support/src/fixtures.rs`, and
143//! `every_row_declares_exactly_what_its_plugin_reports` is what keeps this list and
144//! [`capabilities`](TaskSource::capabilities) from parting.
145//!
146//! | Field | Verdict |
147//! | --- | --- |
148//! | `projects` | **Supported and proven,** and the one predicate here that is pushed down rather than applied in process: a task's project is the issue it is a sub-issue of, so a listing scoped to one *asks that issue* for its own sub-issues. This is the field that was declared and then not applied, which silently returned another project's tasks. |
149//! | `documents` | **Supported and proven.** A board holds issues, so a document is one: the issue whose title begins [`DESIGN_TITLE_PREFIX`]. Reads, filters and paging answer on exactly the terms a task read does, and a write puts the prefix back. |
150//! | `comments` | **Supported and proven,** over the task issue's own comment connection, oldest first and paged by GitHub's own cursor; added, edited and removed through GitHub's comment mutations, paced as every other mutation is. A draft item has no comments on GitHub and is refused, and so is an author, because GitHub records the signed-in account as every comment's author. |
151//! | `assets` | **Supported and native.** Image references travel as GitHub user attachments in the repository the task or document issue lives in. Uploads are authenticated and verified before the issue body is written. |
152//! | `priority` | **Supported and proven** by an instance configured with `priority_mapping`, and declared unsupported by one without it, which reports every task's priority as `none` and sends exactly the requests it sent before priorities existed. The priority is the board's single-select `Priority` field: no value is `none`, a mapped option is its level, matched case-insensitively, and an option the mapping does not name fails the read of that task, naming the option. A write selects the mapped option, or clears the value for `none`; a board without the field or the option is refused, pointing at `sources fields`, which is the one thing that creates either. |
153//! | `filter_by_priority` | **Supported and proven,** over the priority each task reads as — `none` for every task of an instance without `priority_mapping`. |
154//! | `filter_by_comment_activity` | **Supported, and exact** for comments created and for comments edited at or after `commented_since`, in every repository — of any owner — the board's items live in. Applied by asking a narrower question rather than by reading the board: GitHub's issue search scoped by `project:<owner>/<number>` alone, with an `updated:>=` qualifier, names the candidates, and each candidate's own comments confirm it, so `ProjectV2.items` is never read. That rests on GitHub moving an issue's `updatedAt` when a comment on it is added **or edited**, which the credentialed journey `an_edited_comment_moves_its_issue_and_is_selected_since` re-takes on every run of this lane. The search is an index that lags a write — the credentialed lane has watched it miss a newly commented issue for thirty seconds — so an issue this process itself commented on in the same command is a candidate whatever the search says, read by its own node if the search did not name it, and has its comments read rather than being ruled out by an `updatedAt` from before the comment. A comment another process wrote is found only once the index has it, so a caller asking again from its last instant should overlap the two generously. |
155//! | `orphan_tasks` | **Supported and proven.** A task issue with no `parent` is in no project. |
156//! | `filter_by_label` | **Supported and proven,** over the issue's own labels. |
157//! | `filter_by_status` | **Supported and proven,** over the board's `Status` option and the issue's open or closed state, through this instance's own `status_mapping` for the item's kind — a task query by the task half, a project query by the project half, `unknown` included. |
158//! | `filter_by_metadata` | **Supported, and asked of GitHub** — through the body and never through a projected `metadata_fields` text field, which is the board's to filter on and not this source's to read. A query naming metadata values is one board-scoped issue search with each value a quoted phrase `in:body` — GitHub's index covers the metadata comment at the end of the body, which is where caller metadata lives — and every candidate is confirmed against its own parsed metadata comment, so only an item holding that string at that key and path is returned. **A value with no letter or digit is refused** — the empty string, whitespace or punctuation alone — before any request, as a `SourceError::Refused` (wire kind `refused`) naming the value: GitHub's index holds words, so no bounded query can find such a value, and this source neither reads the whole board for it nor answers it as empty. |
159//! | `filter_by_origin` | **Supported, and asked of GitHub without enumerating the board.** The union of three reads, each confirmed by an exact match against the item's own origin field: the board's field filter over the `onetaskgraph.origin` text field, the issue search for the id as a phrase in the body where a write of this release mirrors it, and this process's own writes. See *Where a read-after-write guarantee comes from* for the window the three leave. |
160//! | `reconcile_status` | **Supported,** and proven by `onetaskgraph-github-projects-e2e`'s `status_reconcile.rs`: the board's own `ProjectV2.items(query:)` filter, `is:closed`, read page by page and never the unfiltered items, each candidate confirmed from its own item node — a closed task whose card is not at the option the mapping gives its closure's category. |
161//! | `complete_by_issue` | **Supported,** and proven by `status_complete.rs` there and in the engine's suite: each issue a reference names read in one aliased request per fifty — its repository, its number, its first page of board memberships with each card's `Status` read by name — and nothing else of the board. |
162//! | `search_title` | **Supported, and asked of GitHub for a task,** over `Issue.title`: a task query's text is one board-scoped issue search for it as a phrase `in:title`, every candidate confirmed by the case-insensitive substring rule. GitHub matches whole words, so a task holding the text only inside a longer word is not returned — a narrowing this source declares rather than hides. **A text with no letter or digit that is not blank is refused** — `--` for one — before any request, as the same `refused` error naming the text, for the reason a metadata value like it is; a blank text is not refused, and keeps the board read it always had, confirmed by the same substring rule. A project query's text, and a document query's text when the query is scoped to no project, is that same board-scoped search for the same phrase in the same fields, refused on the same terms, every candidate confirmed by its kind and by the same substring rule, so it narrows exactly as a task's does; a document query scoped to one project sends no search, reads that project's sub-issues and confirms its text over them by the substring rule alone, so it is neither narrowed to whole words nor refused for a text with no letter or digit. A board draft is not an issue, so no text search lists one, a draft titled as a document included. |
163//! | `search_content` | **Supported,** on the same terms, `in:body`, over the visible body — the trailing metadata comment is not part of what the substring rule confirms. |
164//! | `task_dependencies` | **Supported and proven,** in both directions: `blockedBy` and `blocking`. |
165//! | `project_dependencies` | **Supported and proven,** in both directions, over the same two connections, because a project here is an issue. |
166//! | `max_page_size` | **Supported and proven.** [`MAX_PAGE_SIZE`], GitHub's own connection maximum. |
167//!
168//! Image writes use `POST https://uploads.github.com/user-attachments/assets` with `name`,
169//! `content_type` and the issue repository's numeric `repository_id` as query parameters,
170//! the source token as `Authorization: Bearer`, the image content type as `Content-Type`,
171//! and the raw bytes as the request body. The numeric repository id is read at most once
172//! per repository per source instance. A loopback API endpoint also selects the loopback
173//! uploads host; production needs no assets repository, commits or extra configuration.
174//! Every returned JSON `url` is read with the same token before a body is written: only
175//! a 2xx verification succeeds. A refusal names the asset, URL and HTTP status; an
176//! anonymous 404 does not invalidate an authenticated 200. An upload refusal names the
177//! asset and HTTP status and says the token type may not be accepted by the upload
178//! endpoint. A classic PAT was measured accepted; no acceptance claim is made about
179//! fine-grained PATs or OAuth tokens.
180//! The body keeps the authored alt text while `./<name>` becomes the attachment URL,
181//! and `onetaskgraph.assets` records `{sha256, url}` by name. A matching destination
182//! SHA-256 reuses its URL without an upload or verifying read; changed bytes are uploaded
183//! and verified afresh, in the repository the issue already lives in on an update.
184//! An uploaded image renders for the viewers GitHub lets read it, like the issue text beside it.
185//! Uploads take the same mutation spacing as content writes. Both uploads and verification
186//! reads wait out classified rate limits within the configured per-call retry budget,
187//! on the supplied clock; verifying reads take no mutation slot.
188//!
189//! Nothing here is unsupported. `documents` and `comments` are not predicates — they say this
190//! source has documents and that its tasks have comments, both of which hold — and the three
191//! facts behind the uniform `Native` on the
192//! predicates beside it are recorded below rather than re-derived, because a reader who
193//! takes `Native` to mean *the remote service filters* will read that uniformity as a
194//! lie.
195//!
196//! First, the plugin contract defines `Support::Native` as *the source applies this
197//! predicate itself*, and says nothing about where it applies it. What the declaration
198//! promises the engine is capability rule 1 — a predicate declared `Native` **is** applied
199//! — so that the engine may push it down and apply nothing of its own.
200//!
201//! Second, this source can keep that promise for every predicate at no additional API
202//! cost, because whichever of the reads below answers a query has already read every
203//! candidate that query will return before it filters anything. Filtering those items is
204//! in-process work over data already in hand.
205//!
206//! Third, six task predicates are asked of GitHub as a narrower question and the rest are
207//! applied in process over what that question returned. A project filter has a relationship — a
208//! project's tasks are that issue's sub-issues, and asking the issue for them is both cheaper
209//! and exact. Comment activity is the issue search's `updated:` qualifier. A text search, and
210//! a search for metadata values, is the board-scoped issue search carrying the text and each
211//! value as quoted phrases; an origin is the board's own field filter over its origin field
212//! beside the same search for the id. **The text search narrows, and that is this source's
213//! declared semantics:** GitHub matches whole words where the substring rule this source and
214//! the local Markdown source confirm with would match inside one, so an item holding the text
215//! only inside a longer word is never a candidate. Every item returned does contain the text.
216//! A project query's text, and a document query's scoped to no project, is that same search
217//! and narrows on the same terms, its candidates confirmed by their kind as well.
218//! GitHub's issue search offers no qualifier for a label set, a status column or a priority,
219//! so those three are applied in process over the candidates, and a query carrying none of
220//! the six narrowing predicates reads the board. Declaring one `Unsupported` would make the
221//! engine compensate for work this source has already done, and declaring `projects` native
222//! while ignoring the filter (which this source once did) silently returns another project's
223//! tasks, because the engine trusts the declaration and applies nothing locally.
224//!
225//! # The three ways this source reaches an item, and what each costs
226//!
227//! A board read is charged for what its *nested* connections could return rather than for
228//! what was asked, so one whole-board read costs the same whether the question was about
229//! one project or about all of them. That is why a question about one project is never
230//! answered by reading the board:
231//!
232//! | The question | What is sent | What it costs |
233//! | --- | --- | --- |
234//! | one item, by its own id | [`graphql::ISSUE`] — `node(id:)`, carrying the field definitions of the boards it sits on and the far ends of its `blockedBy`, which is what a write of it needs — and, when that node is a board draft, [`graphql::DRAFT`] — the draft and the one board item it is | the item |
235//! | one task with its first page of comments, for `task show` and a comment listing | [`graphql::ISSUE_DETAIL`] — the same `node(id:)` read with the issue's `comments` | the item and a page of its comments |
236//! | several tasks with their comments, for `task show-many` | [`graphql::ISSUE_DETAILS`] — [`DETAIL_BATCH`] aliased `node(id:)` fields per request | each item and a page of its comments |
237//! | the board's own id and field definitions, for a write whose item does not carry them | [`graphql::BOARD_FIELDS`] — the board's `id` and `fields`, and no `items` — or, for a create that needs the repository's id too, [`graphql::CREATION_CONTEXT`], both in one request | the board's fields |
238//! | one project's tasks or documents | [`graphql::SUB_ISSUES`] — that issue's own `subIssues` | that project |
239//! | which projects this board holds | [`graphql::SEARCH_ISSUES`] — an issue search scoped to the board | the board's issues, without their board items |
240//! | which projects hold a text, or which documents do when no project narrows the question | [`graphql::SEARCH_ISSUES`] — the board-scoped search with the text as one quoted phrase, `in:title`, `in:body` or both, as a task's text is sent — walked to its end in pages of twenty | the issues that match |
241//! | which tasks were commented on since an instant | [`graphql::SEARCH_ISSUES`] — the same board-scoped search with an `updated:>=` qualifier — then [`graphql::ISSUE_COMMENTS`] for each candidate it names | the issues updated since, and their comments |
242//! | which tasks hold a text, or a metadata value | [`graphql::SEARCH_ISSUES`] — the board-scoped search with the text and each value as quoted phrases, `in:title`, `in:body` or both, and an `updated:>=` qualifier too when comment activity is asked for — in pages of twenty, only as many as the caller's rows need | the issues that match |
243//! | which tasks were copied from one origin | [`graphql::ORIGIN_LOOKUP`] — the board's own `items` under its field filter on the origin field, and the same board-scoped search for the id `in:body`, in one request, each paged at three | the carriers of that origin, which is one item |
244//! | every task, every document, every label, when nothing above narrows the question | [`graphql::BOARD`] — the board's own `items` — **and** [`graphql::SEARCH_ISSUES`], because neither enumeration of a board is complete alone; see [`GitHubProjectsSource::board`] | the board, twice over |
245//! | which board item one issue is, past the page that came with it | [`graphql::ISSUE_BOARD_ITEMS`] — that issue's own `projectItems` | one issue's memberships |
246//!
247//! The following standalone-ticket requests are pinned by the real CLI fixture journeys
248//! `follow_up_writes_resolve_each_item_once_and_batch_the_copy_fields` and
249//! `a_batched_detail_read_costs_one_request_and_one_point_per_detail_batch`, as request count
250//! equal to declared points equal to the row. They include the origin lookup and the
251//! field/repository discovery a create needs. A bound re-copy changes status, priority,
252//! content and metadata; comment recount means a subsequent detail read. Each request here
253//! costs one declared point. A membership beyond the embedded page can additionally require
254//! the one-point membership recovery described above. A bound re-copy of a task filed under a
255//! project adds one read, the engine confirming that project's link by its own id once per
256//! command; and the same-source far ends a write newly names — those that do not already block
257//! the item, whose own read answered for them — are read together by their own ids,
258//! [`DETAIL_BATCH`] to one [`graphql::ISSUE_DETAILS`] request, each new edge then one
259//! [`graphql::ADD_BLOCKED_BY`]. Both additions are rows of the table below, pinned by
260//! `a_bound_recopy_adds_one_project_read_and_batches_the_dependencies_it_newly_names`.
261//!
262//! **[`DETAIL_BATCH`] is 24**: the largest batch of [`graphql::ISSUE_DETAILS`] the node-count
263//! model prices at one point. Each aliased item is six of GitHub's aggregate, so 24 are 144,
264//! which rounds to one point, and 25 are 150, which rounds to two; `tests/point_cost.rs`
265//! holds both halves.
266//!
267//! **An existing item is written body last.** A bound re-copy and a `task update` send its
268//! board fields first — the `Status` option and the `Priority` together, in one request — then
269//! its parent and its `blockedBy`, and its title, body and state in one `updateIssue` last.
270//! GitHub runs no two requests as one, and runs a document's mutation fields in order without
271//! undoing an earlier field when a later one fails, so that order is what makes a write
272//! refused part-way leave the item's body, and every metadata key in it, exactly as it stood;
273//! the one piece of metadata written before the body, an origin a copy re-points, is put back
274//! when a later write is refused — and when putting it back is refused too, the write's own
275//! refusal names that key, what it now holds and what it held. `crates/onetaskgraph-github-projects-e2e/tests/e2e/write_order.rs` refuses each
276//! of those writes in turn, whole and as one aliased field failing after the one before it.
277//!
278//! **Two facts about GitHub the write rows rest on, each read off GitHub's published schema
279//! artifact <https://docs.github.com/public/fpt/schema.docs.graphql> on 2026-10-01 and pinned
280//! in `tests/fixtures/schema.graphql`, and the first then put to GitHub itself:**
281//!
282//! - **A board is accepted at creation but its item is not answered, so a create still files
283//! the issue itself: a new copy is 5 requests, and 4 with `--create`.**
284//! `CreateIssueInput.projectV2Ids: [ID!]` is declared there — "An array of Node IDs for
285//! Projects V2 associated with this issue", `@possibleTypes(concreteTypes: ["ProjectV2"])`.
286//! The credentialed journey `real_projects_v2_contract_writes_and_leaves_no_residue` was run
287//! against a real board on 2026-10-01 with a create sending the board there and reading the
288//! item off the payload's `Issue.projectItems`: every one of its four creates answered with
289//! no item on the board, so each went on to [`graphql::ADD_TO_BOARD`], and the fourth was
290//! refused "Content already exists in this project" — GitHub had filed the issue after
291//! answering, and refuses a second filing rather than answering with the item it holds. A
292//! create therefore sends no `projectV2Ids` and files the issue with
293//! `addProjectV2ItemById`, the one call whose answer names the board item. The saving that is
294//! real is the read before it: the board's fields and the repository's id together, in
295//! [`graphql::CREATION_CONTEXT`], at the point the repository is known.
296//! - **A comment still reads its target first, so a comment is 2 requests.**
297//! `AddCommentInput.subjectId: ID!` is declared there with
298//! `@possibleTypes(concreteTypes: ["Issue", "PullRequest"], abstractType:
299//! "IssueOrPullRequest")`. A board draft is no such subject and would be refused, but a
300//! project's issue, a document's issue, an issue on no board of this source and a pull
301//! request all are: GitHub writes the comment, so there is no refusal to map into "that is
302//! not a task of this board". [`graphql::ISSUE`] before [`graphql::ADD_COMMENT`] is what
303//! refuses those by name.
304//!
305//! | Verb | Requests / points | Documents |
306//! | --- | --- | --- |
307//! | new copy | 5 | ORIGIN_LOOKUP, CREATION_CONTEXT (the board's fields and the repository's id together), CREATE_ISSUE, ADD_TO_BOARD, UPDATE_FIELDS |
308//! | copy --create | 4 | CREATION_CONTEXT, CREATE_ISSUE, ADD_TO_BOARD, UPDATE_FIELDS: the new copy without its ORIGIN_LOOKUP |
309//! | bound copy | 3 | ISSUE (with the board's fields and the issue's `blockedBy`, so no BOARD_FIELDS or ISSUE_DEPENDENCIES), UPDATE_FIELDS, then UPDATE_ISSUE last |
310//! | bound copy, filed under a project | 4 | the bound copy's three, and one ISSUE of the destination project its link names, read once per command |
311//! | bound copy, newly naming n dependencies | + ceil(n / DETAIL_BATCH) + n | ISSUE_DETAILS for the far ends that do not already block the item, DETAIL_BATCH (24) to a request (one alone is ISSUE), then one ADD_BLOCKED_BY each; a far end already blocking it is answered by its own read and costs nothing |
312//! | comment | 2 | ISSUE, ADD_COMMENT: the target is read first, because GitHub accepts a comment on any issue or pull request (see below) |
313//! | detail | 1 | ISSUE_DETAIL: the item and its first page of comments, for `task show` and `task comment list`; `--no-comments` is ISSUE alone |
314//! | batched detail | ceil(n / DETAIL_BATCH) | ISSUE_DETAILS: `task show-many` of `n` items, DETAIL_BATCH (24) at a time, comments included or not |
315//! | copy --comments, n changed tasks | ceil(n / COPY_DETAIL_BATCH) | ISSUE_COPY_DETAILS: each task with its first page of comments and its `blockedBy`, COPY_DETAIL_BATCH (21) at a time; a task whose comments run past that page adds one ISSUE_DETAIL per further page, and a task skipped from its listing costs nothing beyond it |
316//! | recount | 1 | ISSUE_DETAIL |
317//! | status | 2 | ISSUE, UPDATE_FIELD; a terminal status additionally updates issue state |
318//! | priority | 2 | ISSUE, UPDATE_FIELD or CLEAR_FIELD, with stored priority in the mutation response |
319//! | content | 2 | ISSUE, UPDATE_ISSUE |
320//! | metadata | 2 | ISSUE, UPDATE_ISSUE |
321//! | update | 3 | `task update` naming any of title, body, metadata, status and priority — all five included: ISSUE, UPDATE_FIELDS (the status option and the priority together), UPDATE_ISSUE (title, body with its metadata slot, and state) last |
322//! | record only | 1 | ISSUE |
323//!
324//! <!-- github-search-paging:start -->
325//! Board-scoped text, metadata, project-name and comment-activity searches send every
326//! page at `first = 20` (SEARCH_PAGE_SIZE), the SEARCH_ISSUES document's one-point
327//! ceiling. A later page is sent only when `hasNextPage` is true and the caller still
328//! needs rows. A page is never resized to the rows still needed: GitHub orders one
329//! search differently at different page sizes, so one fixed size makes a paged walk
330//! send exactly the requests one whole read sends, and the answer's order is the order
331//! those pages arrive in. A page below twenty would cost the same one point, and GitHub
332//! prices this document by rows, so twenty-row pages cost per row what 100-row pages do.
333//! Project-name lookup continues until an exact match or exhaustion. A task limit bounds
334//! returned and fetched pages: a limit is sliced from the pages it needs, and local
335//! confirmation can require more candidates than matching rows. Walking all pages
336//! returns the whole answer. The opaque version-4 source cursor carries GitHub's page
337//! cursor and how far into that page the last answer stopped, and resumes in the same
338//! process or a new one, without duplicates or gaps. It carries no rows: one process
339//! sends each page's search once, and a new process re-reads only the page it resumes
340//! in, then sends a further page once, never as a re-read, only when its limit still
341//! needs rows. Every request either walk sends is the one a whole read sends for that page. Own writes replace stale index
342//! copies and complete missing rows at exhaustion. Cache entries are whole GitHub pages,
343//! so a small answer cannot truncate a wider question. Origin pages remain three; whole-board sizing is unchanged.
344//! Read-after-write is a per-process guarantee. A cursor resumed in a new process is
345//! not required to include the original process's writes still omitted by the index.
346//! <!-- github-search-paging:end -->
347//!
348//! The board half of an issue — its board item's id, its `Status` option and this
349//! source's origin text field — rides along on `Issue.projectItems` in the first three, so
350//! an item reached any of those ways resolves through the same
351//! [`GitHubProjectsSource::resolve`] the board walk uses and reports the same title, the
352//! same status, the same labels and the same qualified id. That connection comes back a
353//! *page* at a time, at `BOARD_ITEMS_PAGE_SIZE`, so the entry for this board is looked for
354//! on the page in hand and — only if that page reports more of the connection — in the
355//! last row's read of that one issue's memberships, resumed from the page's own cursor and
356//! walked to exhaustion. An issue with no entry for *this* board is not this source's to
357//! report, which is what keeps an id naming another repository's issue from being answered
358//! as an item of this board; and because the page is where the search starts rather than
359//! where it ends, that answer is one about a connection read to exhaustion and never about
360//! an unread page. Nothing costs the extra read but an issue on more boards than a page
361//! holds: an issue this board really does not hold reports no next page, so its
362//! memberships are already exhausted where they arrived.
363//!
364//! **No document here selects the board's own `Labels` field, and nothing is lost by
365//! that.** An item's labels are read from its content alone, wherever that content is
366//! reached: the three documents above select `Issue.labels` on the fragment, and
367//! [`graphql::BOARD`] selects the same connection on the `... on Issue` arm of its
368//! `content`. A board's `Labels` field is not one anybody fills in: it is a built-in
369//! `ProjectV2FieldType`, it is absent from `ProjectV2CustomFieldType` so no project can
370//! create one, and `ProjectV2FieldValue` — the whole of what
371//! `updateProjectV2ItemFieldValue` accepts — offers no way to write one. So GitHub derives
372//! it from the content, for every content type it exists on, and there is nothing it can
373//! hold that the content does not already say: for an `Issue` it *is* that issue's own
374//! labels, so selecting it beside them unions a set with itself.
375//!
376//! **A draft loses nothing by that either**, which is the reasoning this paragraph once had
377//! backwards. `DraftIssue` exposes no `labels` field, and by the three schema facts above
378//! it cannot carry a board `Labels` value to be derived from one — so a draft has nothing
379//! to select *and nothing to lose*, and reports no labels at all. A `PullRequest` item is
380//! discarded by [`GitHubProjectsSource::resolve`] before labels are read. Both halves are
381//! held to that by tests in `tests/plugin.rs`: the four ways an item is reached report one
382//! label set, and that set is the fixture issue's own, by
383//! `an_item_reports_the_same_labels_title_status_and_id_however_it_is_reached`; and a board
384//! item whose content is a draft reports an empty set, by
385//! `a_board_item_whose_content_is_a_draft_reports_no_labels_at_all`. The absence of the
386//! selection is held over [`graphql::DOCUMENTS`] by
387//! `no_document_selects_the_boards_own_labels_field`.
388//!
389//! The whole-board row is still the board's own item connection, and deliberately: a
390//! **draft** board item is not an issue, so no search can list one, and the reads that have
391//! to answer for the whole board are the ones whose cost is the board's size anyway.
392//!
393//! **A question about one item this source already names by id never lists the board.**
394//! Whether that item is on this board, and what its board fields are, is answered by reading
395//! that item — its own `Issue.projectItems`, walked to exhaustion by
396//! [`GitHubProjectsSource::resolve_issue`], or a draft's own board item — and never by
397//! looking for it in [`graphql::BOARD`]'s `items` or in a listing this command already
398//! holds. That covers a write's destination, the project a new item is filed under, a
399//! same-source far end a dependency names, a status write, the dependency slot a draft keeps,
400//! and the delete that takes back an item a copy made. What such a write needs of the board
401//! and the item does not carry — the board's id, the `Status` and origin field definitions —
402//! comes from [`graphql::BOARD_FIELDS`], which reads no item at all. The reason is evidence,
403//! not economy alone: `ProjectV2.items` is a projection that lags the membership GitHub
404//! itself reports — an issue added with `addProjectV2ItemById` can be missing from it for
405//! minutes. Scanning this host's 842-item board has refused a document copy and an update
406//! even though the items' own reads named that board. A scan there gives the wrong answer
407//! as well as paying for every page. So a `board.items` lookup does not belong on any of
408//! those paths.
409//!
410//! **What a read may return is capped too, and that cap is on the document rather than on
411//! the board.** GitHub limits the number of nodes **one query may return** to
412//! [`NODE_COUNT_LIMIT`] and refuses a query above that before executing it: the answer is
413//! an error naming the connection the count crossed at, not a slow or a partial result.
414//! Every board this source reads is refused the same way, so no board is too big for these
415//! documents and none is small enough to save one that is over.
416//!
417//! The count is arithmetic over the document's own text: each connection contributes the
418//! `first:` it asks for, counts **multiply** down a nested path and **sum** across sibling
419//! paths. Those are [GitHub's published rules][node-limits] and this workspace does not
420//! restate them — `github-graphql-node-count` implements them, and
421//! [`worst_case_node_count`] under [`largest_page_sizes`] is where every node count here
422//! comes from. `every_document_this_source_sends_stays_under_githubs_node_limit`, in
423//! `tests/node_count.rs`, recomputes every document in [`graphql::DOCUMENTS`] from that
424//! same text on every run and fails naming any that reaches the limit — so a connection
425//! added to a shared fragment is caught there rather than by GitHub.
426//!
427//! What decides those counts is the page sizes: [`MAX_PAGE_SIZE`] on the outer page,
428//! `NESTED_PAGE_SIZE` on the connections hanging off one item, and
429//! `BOARD_ITEMS_PAGE_SIZE` on the page of an issue's board memberships a read carries.
430//! `$nestedFirst` is spent twice down one path of a board read, so that constant is
431//! effectively squared there, which is why it is the one the limit is most sensitive to.
432//! `BOARD_ITEMS_PAGE_SIZE` is small for a reason of its own, recorded beside it: what a
433//! page of memberships misses is recovered by one further read rather than refused, so it
434//! buys a bound every read pays for at the price of a request only a multi-board issue
435//! pays.
436//!
437//! **`nodeCount` and `cost` are two numbers against two limits, and both are computed
438//! offline here — per document, one document at a time.** `nodeCount` is the one above: the
439//! most nodes one query may return, checked per query and bounded by [`NODE_COUNT_LIMIT`].
440//! `cost` is rate-limit points, metered per hour across everything one credential does; it
441//! is what the two limiters [`Limiter`] tells apart meter, and a document under
442//! [`NODE_COUNT_LIMIT`] still says nothing about its price. [`worst_case_point_cost`] is
443//! that second number, and `tests/point_cost.rs` pins every document in
444//! [`graphql::DOCUMENTS`] at what it costs — there being no per-call point ceiling to hold
445//! one under, the pin itself is the check. The credentialed lane reconciles both figures
446//! against GitHub's own, off a probe it already sends.
447//!
448//! **What is pinned that way is a per-document price and never a session's.** The record in
449//! `session-cost.md` measures the two quantities a whole session can be counted in offline —
450//! **requests** and **worst-case nodes** — and neither is points. What one whole session
451//! consumes of the hourly point allowance is observable only from a credentialed run's own
452//! `x-ratelimit-*` headers, which is what [`accounting`] fills its per-budget figures from
453//! and what `tests/live.rs` prints at the end of every run.
454//!
455//! [node-limits]: https://docs.github.com/en/graphql/overview/rate-limits-and-node-limits-for-the-graphql-api
456//!
457//! **Where a read-after-write guarantee comes from, since neither of GitHub's two
458//! enumerations of a board can supply one alone.** Resolving a node id is strongly
459//! consistent, so a read by id and a project's own sub-issues are already current. The
460//! other two are not, and they are behind by different amounts and in different directions:
461//!
462//! - GitHub's **issue search** is an index and answers a write made moments ago with the
463//! value from before it — usually for a second or two.
464//! - **`ProjectV2.items`** is a projection GitHub rebuilds behind the write, and an item put
465//! on a board with `addProjectV2ItemById` can be **absent** from it — not present with its
466//! content withheld, absent, with the connection walked to its own `hasNextPage: false` —
467//! for *minutes*, while `Issue.projectItems` names the same membership at once.
468//!
469//! That second one is a measurement rather than a caution. This repository's own
470//! credentialed journey writes a project and waits for the board to report it, then writes a
471//! task and waits for the same thing seconds later on the same board: the project wait is
472//! answered through the search and converged in two or three attempts in each of three runs,
473//! and the task wait is answered through `ProjectV2.items` and converged in none of them
474//! inside thirty. Separately, an item added to a second and larger board was read back by
475//! `Issue.projectItems` on that board's own id while every one of that connection's nine
476//! pages, walked to exhaustion nine minutes after the add, did not name it. Reading a board
477//! through the lagging one alone is what had a board read deny an issue that had certainly
478//! landed on it.
479//!
480//! So [`GitHubProjectsSource::board`] is the **union** of both — each search result still
481//! admitted only on this board's own strongly-consistent `Issue.projectItems`, and neither
482//! enumeration dropped, because only `ProjectV2.items` lists a board draft and only the
483//! search reports what the projection is behind on. What closes the last
484//! gap, the one where both are behind, is [`GitHubProjectsSource::created`]: every read this
485//! source answers is completed with what this process itself wrote, so an item created
486//! seconds ago is reported whether or not GitHub has caught up. Nothing else is remembered,
487//! nothing is written down, and the record dies with the process. **A wait that has to
488//! observe GitHub's own data cannot be answered from that record** — which is why the
489//! credentialed journey asks through a source built afresh, and why the union above rather
490//! than a longer wait is what makes such a wait converge.
491//!
492//! **A narrowed read is the same bargain, stated for each of the three predicates it
493//! answers.** A read carrying a text, metadata or origin predicate asks GitHub's index rather
494//! than walking the board, and every such answer is completed with what this process wrote —
495//! its [`created`](GitHubProjectsSource::created) record and every existing item it wrote,
496//! each filtered by the same predicates as the rest — so an item this command wrote a moment
497//! ago is returned by a query that matches it whether or not the index has caught up. An item
498//! a caller holds the id of is read by that id, with `node(id:)`, which is strongly
499//! consistent. What is left is stated rather than papered over:
500//!
501//! | Read | Finds | Behind by |
502//! | --- | --- | --- |
503//! | text, metadata | the issue search for the phrases | what another process wrote in the last second or two, until GitHub indexes it |
504//! | origin, first read | the board's field filter over the origin field — every carrier, whichever release wrote it | what `ProjectV2.items` is behind on, which the measurements above put in minutes |
505//! | origin, second read | the issue search for the id in the body, where a write of this release mirrors it | a second or two, as any search |
506//! | origin, third read | this process's own writes | nothing |
507//!
508//! So an origin carrier another process added within the last second or two, before either
509//! index has it, can be missing from an origin query, and one written by the release before
510//! this one — its origin in the field alone — can be missing for as long as the board's own
511//! item connection is behind on it. A copy that must not duplicate its own earlier write
512//! relies on the link it records, not on either index. **A board draft is not an issue**, so
513//! a draft is never returned by a text, metadata or origin query, whatever it holds: no search
514//! lists one, the origin lookup drops any the board's own field filter names, and one this
515//! process wrote is not added back either.
516//!
517//! **The origin lives in the board field, and the body holds a mirror of it.** A write that
518//! carries an origin writes it to the `onetaskgraph.origin` text field and also into the
519//! body's metadata slot, so the issue search can find it in seconds. The field is
520//! authoritative: this source reads an item's origin from the field alone, so a slot that
521//! disagrees with it, or holds one where the field holds none, is never read as a second
522//! origin — and the release before this one reads the slot, drops that key's copy for the
523//! field's, and sees the same one origin.
524//!
525//! Filtering happens before paging, so a page of a filtered result is a page of the
526//! survivors rather than the survivors of a page. Label matching and the substring rule a
527//! text candidate is confirmed by answer the same question the same way the local Markdown
528//! source's do; which candidates a text search has to confirm is GitHub's word match, which
529//! is the one place the two sources can answer the same text differently.
530//!
531//! <!-- llmlint: ignore[contracts_have_one_source_or_a_drift_gate] The declaration itself
532//! has one source, `capabilities`, and the note above is the reasoning behind it rather
533//! than a second copy of it: without the three facts recorded here a reader takes the
534//! uniform `Native` for a lie and reverts it. The drift gate on the declaration is this
535//! crate's own capabilities test, which pins every field of it against a fully spelled-out
536//! `Capabilities` literal — a struct with no `Default`, so a field added to the contract
537//! fails to compile there rather than going unasserted. -->
538//! The fixture-server tests above run wherever this crate is selected; the credentialed
539//! lane runs in the same required check, beside them, and can fail it — it verifies the
540//! current schema, then drives every field of the table above against the real board. It builds its own fixture there — two projects, one task filed under each,
541//! one filed under neither, a label on one of the three and a closed status on another —
542//! because that shape is what tells an honoured predicate from an ignored one: a board
543//! holding a single project answers a project filter the same way whether or not this
544//! source applies it, which is exactly how the defect above went unseen.
545//!
546//! That lane writes only to the board `GH_PROJECTS_OWNER` and `GH_PROJECTS_NUMBER` name,
547//! and the scratch repository `GH_PROJECTS_REPOSITORY` names:
548//! `nickderobertis/onetaskgraph-live-scratch`. It refuses the core repository before any
549//! session or request, independently of the live demand. Fix that variable in the machine's
550//! onetaskgraph `secrets.env` or the environment it pushes from, such as ai-orchestrator's
551//! `.env`. The targets are declared once in `onetaskgraph_github_live`, the lane's own
552//! policy crate; absent credentials or nominations otherwise skip.
553//!
554//! GitHub Actions artifacts carry `ci-<run id>-<attempt>-<micros>`, naming their writing
555//! run and attempt; invalid Actions identity refuses before writing. Other runs retain
556//! `<host>-<process>-<micros>`. Own cleanup matches the whole stamp. Machine residue stays
557//! the owning machine's lock sweep's; Linear always keeps that form and is unaffected.
558//! The hourly janitor is cleanup, never a test lane: scratch CI residue is removed only
559//! after its run reads back as `completed`, immediately before the listed-artifact batch.
560//! Failed or incomplete ownership reads preserve residue. A 24-hour waiting period
561//! is a margin, never the ownership authorisation. Cleanup leaves machine stamps
562//! and the board's `onetaskgraph.origin` field untouched.
563//!
564//! # What a session of requests costs, and where the report is
565//!
566//! This source records **every** request it sends into [`accounting::Accounting`], at
567//! `send_once` — the one place a request leaves this crate, which is why a read path added
568//! later is counted without anybody remembering to count it. That is the whole of what this
569//! crate adds to the arrangement; [`accounting`] is where what a record carries, how a
570//! session's spend is arrived at, and what it deliberately does not know are set out.
571//!
572//! What one whole session of the live journey costs, counted that way against this crate's
573//! loopback fixture board, is written down in `session-cost.md` beside this crate — with the
574//! reduction it came out of, and with what it does and does not say about rate-limit points.
575//!
576//! [`GitHubProjectsSource::accounting`] is the read: a snapshot to hold and compare, which
577//! [`accounting::Session::report`] renders the session report from. It is on the ordinary
578//! code path — no environment variable, no feature, no build configuration — because an
579//! instrument nobody switches on measures nothing, and
580//! [`Plugin::build_recording_into`] is how a caller making its own calls beside this
581//! source's counts the whole session rather than this source's share. The credentialed lane
582//! in `tests/live.rs` does exactly that, and prints the report at the end of every run,
583//! passed or failed.
584//!
585//! **A live session refuses to start unless the account can afford it.** Before it does any
586//! of the work it exists to do, the journey makes one request — `GET /rate_limit`, which
587//! GitHub documents as not counting against the REST rate limit and which answers both of
588//! its budgets at once — and starts only if, for each of them, what remains minus this
589//! session's estimated cost is still at least
590//! `onetaskgraph_live::RETAINED_BUFFER` — twenty per cent — of that budget's whole
591//! allowance. A session that cannot **declines**: it did not run, so it is
592//! neither a pass nor a failing assertion, and it says which budget was short, that budget's
593//! limit, what remained, the estimate, the buffer and when it resets — then stops, without
594//! waiting for the budget to come back. The estimate is derived offline from
595//! `tests/fixtures/session-cost.txt` and a cost model stated in `tests/journey/budget.rs`,
596//! which is also where the published rule that model rests on is cited; the accounting
597//! above records the gate's own read like any other request, and
598//! [`accounting::Session::report`] prints the estimate beside what the session really spent.
599//!
600//! **GitHub is the authority on both of its own numbers, and the credentialed lane goes and
601//! asks it.** Everything above computes `nodeCount` and `cost` offline from a document's own
602//! text, which is what lets it run on every platform and on a pull request from a fork with
603//! no credential — and that is what actually stops a regression merging. But an offline
604//! arithmetic can only ever agree with itself: if GitHub changes its rules, this workspace
605//! goes on computing the old answer and nothing notices. So `tests/live.rs` reconciles them.
606//! GitHub's schema exposes `rateLimit(dryRun: true)`, whose `nodeCount` is *"the maximum
607//! number of nodes this query may return"* and whose `cost` is what that document would
608//! spend, both for a document **without executing it**, and the lane asks it for every query
609//! document this source sends, under the largest bindings this source sends, and fails when
610//! GitHub's figure and [`worst_case_node_count`] or [`worst_case_point_cost`] disagree. A
611//! mutation is skipped, because `rateLimit` is a field of `Query` and cannot be asked about
612//! one; the offline pins still cover it. It records what those calls reported about the
613//! account's own allowance, because whether asking is free is a thing to observe rather than
614//! to assume. Two quantities, not one: [`NODE_COUNT_LIMIT`] bounds `nodeCount` per query,
615//! and `cost` is metered against an hourly allowance the accounting above reads off a
616//! credentialed run's own response headers.
617//!
618//! **GitHub has two rate limiters and this source is refused by both, so nothing here
619//! treats them as one thing.** The primary budget is the hourly allowance `gh api
620//! rate_limit` reports; the secondary limiter is a burst limiter over content-generating
621//! requests, and *nothing* reports it. Which one refused decides the operator's next step,
622//! so [`Limiter`] is a type rather than a detail, and it is what [`MIN_MUTATION_INTERVAL_MS`],
623//! [`GitHubProjectsSource::board_cache`] and [`GitHubProjectsSource::graphql`] each answer
624//! one part of.
625#![deny(missing_docs)]
626
627use std::collections::BTreeMap;
628use std::sync::{Arc, Mutex};
629use std::time::Duration;
630
631use chrono::{DateTime, Utc};
632use onetaskgraph_plugin_api::{
633 Capabilities, Classification, ClosedAs, Comment, CommentBody, CommentOrigin, Completion,
634 Coverage, Cursor, DependencyEdge, DependencyEndpoint, DependencyKind, DependencySupport,
635 Direction, Document, DocumentQuery, DocumentVersionCoverage, Health, HeldTask, IssueHolding,
636 IssueRef, ItemKind, ItemWrite, Label, LabelFilter, Location, MetadataKey, Metering, NativeId,
637 NewComment, Page, PageRequest, Priority, Project, ProjectFilter, ProjectQuery,
638 ProjectVersionCoverage, Repository, SecretResolver, SharedClock, SourceError, SourceName,
639 SourcePlugin, Status, StatusCategory, StatusContradiction, StatusMapping, Support, Task,
640 TaskDetailRead, TaskQuery, TaskRef, TaskSource, TaskUpdate, TaskUpdateOutcome, TextFields,
641 TextQuery, UnmappedStatus, UpdatedField, VersionCoverage, WriteJournal, WriteSupport,
642 system_clock,
643};
644use reqwest::{Client, StatusCode, Url};
645use schemars::{Schema, schema_for};
646use secrecy::{ExposeSecret, SecretString};
647use serde::{Deserialize, Serialize};
648use serde_json::{Value, json};
649
650pub mod accounting;
651mod assets;
652pub mod change_token;
653mod expected;
654pub use expected::{CONTEXT_VERSION, WHOLE_MEMBERS, context_shapes};
655mod visibility;
656
657use accounting::Accounting;
658
659/// The registry name for this plugin.
660pub const KIND: &str = "github-projects";
661/// GitHub's maximum connection page size.
662pub const MAX_PAGE_SIZE: u32 = 100;
663/// Every page of a board-scoped narrowing search: 20 rows, one point of SEARCH_ISSUES, the
664/// most one point buys. GitHub prices that document by rows, so pages of 20 cost what pages
665/// of 100 cost per row, and a page of fewer than 20 costs the same one point.
666pub const SEARCH_PAGE_SIZE: u32 = 20;
667/// How many items one [`graphql::ISSUE_DETAILS`] request reads, each with the first page of
668/// its comments: the largest batch the node-count model prices at one point.
669///
670/// Each aliased item is resolved once, and what GitHub charges for it is the connections
671/// under it — its labels, its page of board memberships, the field values of each of those
672/// three memberships, and its comments: six requests' worth of the aggregate GitHub divides
673/// by a hundred and rounds. Twenty-four items come to 144, which rounds to one point;
674/// twenty-five come to 150, which rounds to two. `tests/point_cost.rs` prices the document at
675/// one point and fails if one item more would still be priced at one.
676pub const DETAIL_BATCH: usize = 24;
677/// How many issue references one [`graphql::ISSUES_BY_REFERENCE`] request reads.
678///
679/// Each reference asks GitHub for one connection — a page of its board memberships, each with
680/// its `Status` value read by name rather than through a connection of field values — so fifty
681/// come to fifty requests' worth of the aggregate GitHub divides by a hundred, which is its
682/// one-point minimum, and the batch a landing's closures are read in costs one point per fifty
683/// issues per source. `tests/point_cost.rs` prices the document at one point.
684pub const REFERENCE_BATCH: usize = 50;
685/// How many items one [`graphql::ISSUE_COPY_DETAILS`] request reads: each with the first page
686/// of its comments and its `blockedBy`, the largest batch the node-count model prices at one
687/// point.
688///
689/// The six requests' worth an item of [`DETAIL_BATCH`] costs, and its `blockedBy` connection
690/// besides: seven. Twenty-one items come to 147, which rounds to one point; twenty-two come to
691/// 154, which rounds to two. `tests/point_cost.rs` prices the document at one point and fails
692/// if one item more would still be priced at one.
693pub const COPY_DETAIL_BATCH: usize = 21;
694
695/// The most nodes any one document this source sends may be asked to return.
696///
697/// GitHub's own published per-query ceiling, taken from
698/// [`github_graphql_node_count::NODE_LIMIT`] rather than written out again here, so this
699/// workspace cannot hold a stale copy of somebody else's number. A query above it is
700/// **refused before it is executed**, whoever is asking and whatever board they are
701/// asking about — so this is a bound on the documents rather than a budget that runs out.
702///
703/// This is `nodeCount`, the maximum number of nodes *one query may return*. It is not
704/// `cost`, the rate-limit points a call spends against an hourly allowance shared by
705/// everything the credential does — two numbers against two limits, and this constant
706/// bounds only the first. The second is computed offline too, per document:
707/// [`worst_case_point_cost`], pinned for every document in [`graphql::DOCUMENTS`] by
708/// `tests/point_cost.rs`, and reconciled against GitHub's own `cost` by the credentialed
709/// lane. There is no constant like this one to hold a price under, because points are an
710/// hourly allowance rather than a per-call bound.
711///
712/// Neither is a session's price. What `session-cost.md` records of a whole session is its
713/// **requests** and its **worst-case nodes**; what a whole session spends in points is
714/// reported only by a credentialed run's own `x-ratelimit-*` headers, through
715/// [`accounting`]. The module section on the three ways this source reaches an item says how
716/// the count is arrived at, and which of the page sizes below decide it.
717pub const NODE_COUNT_LIMIT: u64 = github_graphql_node_count::NODE_LIMIT;
718
719/// Nested connection size for the connections that hang off one item.
720///
721/// It multiplies through every document that reaches an item under a page — the count
722/// rules multiply down a nested path — so it is the constant [`NODE_COUNT_LIMIT`] is most
723/// sensitive to. `tests/node_count.rs` is what holds the pair together: it recomputes
724/// every document under these constants and fails naming any that reaches the limit, so
725/// raising this is caught there rather than by GitHub.
726const NESTED_PAGE_SIZE: u32 = 50;
727/// How many of one issue's board memberships are read when an issue is reached directly.
728///
729/// An issue reached through a search or through its own node id carries its board half in
730/// `Issue.projectItems`, and only the entry for *this* board is read. This connection sits
731/// under a page of issues, so every point of it multiplies through the whole document and
732/// is paid for whether or not any issue is on a second board — which is why it is
733/// deliberately far smaller than [`NESTED_PAGE_SIZE`].
734///
735/// **Three, because what a page misses is now recovered rather than refused**, and the
736/// recovery is what the value is chosen against. An issue whose entry for this board sits
737/// past this page costs one further request — [`graphql::ISSUE_BOARD_ITEMS`], resumed from
738/// that page's own cursor — so the value trades a bound every read pays for a request only
739/// a multi-board issue pays. At one, a deployment whose issues commonly sit on two or more
740/// boards would pay that request *per issue*, which is order N against the one page per
741/// hundred issues a read costs today. At three it is only reached by an issue on four or
742/// more boards at once, which keeps the recovery path exceptional rather than routine for
743/// a plausible deployment.
744const BOARD_ITEMS_PAGE_SIZE: u32 = 3;
745/// How many carriers of one copy origin one page of [`graphql::ORIGIN_LOOKUP`] asks each of
746/// its two connections for.
747///
748/// An origin names one item, so the answer an origin lookup expects is one carrier, and a
749/// second is a duplicate a copy already takes the first of. Both connections are walked to
750/// exhaustion whatever this is, so it decides how many requests an unusual answer costs and
751/// never what the answer is. It is small because every point of it is paid on every lookup,
752/// and a copy makes one lookup per item it has no link for: at three, ten lookups cost fewer
753/// worst-case nodes than the one whole-board read they replaced.
754const ORIGIN_PAGE_SIZE: u32 = 3;
755
756pub use github_graphql_node_count::{NodeCountError, Variables};
757
758/// The largest value this source can bind to each page-size variable its documents name.
759///
760/// Every `first:` in [`graphql`] reads one of these four, and each is capped at the
761/// constant above it wherever a caller's own limit could reach it — `$first` at
762/// [`MAX_PAGE_SIZE`], `$nestedFirst` at `NESTED_PAGE_SIZE`, `$boardItems` at
763/// `BOARD_ITEMS_PAGE_SIZE`, `$originFirst` at `ORIGIN_PAGE_SIZE`. So this is the worst case a caller can drive this source to,
764/// not one configuration of it, which is what makes a bound computed under it a bound on
765/// every read.
766pub fn largest_page_sizes() -> Variables {
767 Variables::from([
768 ("first".to_owned(), MAX_PAGE_SIZE),
769 ("nestedFirst".to_owned(), NESTED_PAGE_SIZE),
770 ("boardItems".to_owned(), BOARD_ITEMS_PAGE_SIZE),
771 ("originFirst".to_owned(), ORIGIN_PAGE_SIZE),
772 ])
773}
774
775/// The most nodes `document` could be asked to return, by GitHub's published rules.
776///
777/// Computed offline from the document's own text under [`largest_page_sizes`] — no
778/// network, no credential and no schema — by
779/// [`github_graphql_node_count::node_count`], which is where the rules themselves live.
780/// A document at or above [`NODE_COUNT_LIMIT`] is one GitHub refuses before executing, so
781/// this is what a check holds every document in [`graphql::DOCUMENTS`] below.
782///
783/// # Errors
784///
785/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
786/// no single operation, or binds a page size this source does not name — each of which is
787/// a defect in the document rather than a number.
788pub fn worst_case_node_count(document: &str) -> Result<u64, NodeCountError> {
789 node_count(document, &largest_page_sizes())
790}
791
792/// The most rate-limit points one call of `document` could spend, by GitHub's published
793/// rules.
794///
795/// Computed offline from the document's own text under [`largest_page_sizes`] — no
796/// network, no credential and no schema — by
797/// [`github_graphql_node_count::point_cost`], which is where the rules themselves live.
798/// This is `cost`, metered **per hour** against the allowance one credential shares across
799/// everything it does; it is not `nodeCount`, which is [`worst_case_node_count`] and is
800/// bounded per query by [`NODE_COUNT_LIMIT`]. There is no per-call ceiling to hold this
801/// under, so what `tests/point_cost.rs` does with it is pin every document in
802/// [`graphql::DOCUMENTS`] at what it costs, and the credentialed lane reconciles those
803/// figures against GitHub's own reported `cost`.
804///
805/// # Errors
806///
807/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
808/// no single operation, or binds a page size this source does not name — each of which is
809/// a defect in the document rather than a number.
810pub fn worst_case_point_cost(document: &str) -> Result<u64, NodeCountError> {
811 github_graphql_node_count::point_cost(document, &largest_page_sizes())
812}
813
814/// The most nodes `document` could be asked to return under `variables`.
815///
816/// [`worst_case_node_count`] is this under [`largest_page_sizes`], and the accounting in
817/// [`accounting`] is this under the bindings one request really sent — one spelling of the
818/// calculation, so a bound checked offline and a cost recorded at run time cannot come to
819/// disagree. The rules themselves live in [`github_graphql_node_count::node_count`].
820///
821/// # Errors
822///
823/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
824/// no single operation, or binds a page size `variables` does not name.
825pub fn node_count(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
826 github_graphql_node_count::node_count(document, variables)
827}
828
829/// The issue-title prefix that makes a board issue a document.
830///
831/// A GitHub Projects board has no document type — it holds issues — so the discriminator
832/// is the title, and this is the whole of it: an issue whose title begins with these bytes
833/// is a document and every other issue is the task or project the sub-issue rule makes it.
834///
835/// It is spelled **once**, here, and read rather than restated everywhere else — including
836/// by the shared journeys, which take it from this constant so a board fixture cannot
837/// drift from what this source reads. `docs/metadata.md` records the two consequences that
838/// are not obvious from the bytes: the reported title has this prefix taken off, exactly
839/// as the body's metadata slot is taken off `content`, and this prefix is read *before*
840/// the sub-issue rule, so a design issue with no sub-issues is never an empty project.
841pub const DESIGN_TITLE_PREFIX: &str = "DESIGN: ";
842
843/// Exact GraphQL query documents issued by this plugin.
844///
845/// Keeping the production documents here lets the pinned-schema test validate the same
846/// bytes that are sent to GitHub, rather than a test-only copy which could drift
847/// independently. [`STATUS_OPTIONS_UPDATE`] is the sole document that may rewrite a board
848/// field, and its guarded caller always supplies the complete existing option set with ids.
849pub mod graphql {
850 /// The board half of one item: the field values every document here reads it from.
851 ///
852 /// A macro for the same reason [`board_issue!`] below is one, a level further in. This
853 /// selection is needed by that fragment, by [`BOARD`] under the board's own `items`,
854 /// and by [`ISSUE_BOARD_ITEMS`] under a membership walk — and all three have to produce
855 /// *the same value*, because
856 /// [`GitHubProjectsSource::resolve`](super::GitHubProjectsSource) reads them through
857 /// one path. Three spellings of it is what would drift, so there is one.
858 ///
859 /// The `Status` option and this source's own origin text field are the whole of it. It
860 /// selects no `ProjectV2ItemFieldLabelValue`: GitHub derives that field from the item's
861 /// content, so it holds nothing the content's own `labels` do not already say, and it
862 /// would sit a label connection two page sizes deep.
863 macro_rules! board_item_values {
864 () => {
865 r#"fieldValues(first:$nestedFirst){nodes{
866 ... on ProjectV2ItemFieldSingleSelectValue{name field{
867 ... on ProjectV2SingleSelectField{id name options{id name}}
868 }}
869 ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{id name}}}
870 }pageInfo{hasNextPage}}"#
871 };
872 }
873
874 /// The variable every document reading an issue declares for the relationship events its
875 /// change token counts, with its value as the default, so no caller binds it.
876 ///
877 /// A variable rather than a literal list because every argument a production document
878 /// passes is a declared variable, which `tests/schema.rs` holds them to, and every member of
879 /// its default to the pinned enum. Its default is the six event types GitHub records a
880 /// relationship added or removed with: a dependency on either end, as `blockedBy` and
881 /// `blocking`, so one a person makes from the far end moves this end's count too; and a
882 /// project membership on the task, as its parent, which GitHub records there whichever
883 /// issue the move was made from. A sub-issue's events on its parent are not counted: a
884 /// project carries no task token, and a copy writes nothing of a task its own sub-issues
885 /// decide. [`super::change_token`] says why the count is in the token.
886 macro_rules! relationship_events_variable {
887 () => {
888 ",$relationshipEvents:[IssueTimelineItemsItemType!]=[BLOCKED_BY_ADDED_EVENT,BLOCKED_BY_REMOVED_EVENT,BLOCKING_ADDED_EVENT,BLOCKING_REMOVED_EVENT,PARENT_ISSUE_ADDED_EVENT,PARENT_ISSUE_REMOVED_EVENT]"
889 };
890 }
891
892 /// Everything this source reads about one issue, wherever it reaches that issue.
893 ///
894 /// A macro rather than a constant so the three documents below can `concat!` it: one
895 /// spelling of these fields is what makes an issue read through the board-scoped
896 /// search, through its own node id, and through its project's sub-issue relationship
897 /// resolve to *the same* item, which is the whole of what
898 /// [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource) relies on.
899 ///
900 /// `projectItems` is what carries the board half of an issue: the board item's own id
901 /// and the [`board_item_values!`] above — the `Status` option and this source's origin
902 /// text field — that a `ProjectV2.items` read used to carry. It is asked for on the
903 /// issue rather than on the board, which is what makes the cost of a read proportional
904 /// to what was asked for instead of to the board's size.
905 ///
906 /// It carries a *page* of that connection, at `BOARD_ITEMS_PAGE_SIZE`, and its
907 /// `endCursor` is what [`ISSUE_BOARD_ITEMS`] resumes from when this board's entry is
908 /// not on that page: a page here is where the search for the entry starts rather than
909 /// where it ends.
910 ///
911 /// It does **not** select the board's `Labels` field value, and that is the whole of
912 /// what keeps the three documents below under [`NODE_COUNT_LIMIT`](super::NODE_COUNT_LIMIT):
913 /// a label connection there sits under `fieldValues` under `projectItems` under a page
914 /// of issues, spending `$nestedFirst` twice down one path, and took
915 /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] to 2,556,100 nodes against a limit of 500,000.
916 /// No label is lost — this is a fragment `on Issue`, whose own `labels` are selected
917 /// above, and that connection is where every label this source reports comes from. No
918 /// document in this module selects the board field any longer, [`BOARD`] included; the
919 /// module documentation records why nothing it could have held is lost.
920 macro_rules! board_issue {
921 () => {
922 concat!(
923 r#" fragment BoardIssue on Issue{__typename id number title body url createdAt updatedAt state stateReason(enableDuplicate:$duplicates) repository{nameWithOwner} parent{id} subIssuesSummary{total} commentCount:comments{totalCount} relationshipEvents:timelineItems(itemTypes:$relationshipEvents){totalCount}
924 labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}
925 projectItems(first:$boardItems){nodes{id updatedAt project{id number}
926 "#,
927 board_item_values!(),
928 r#"}pageInfo{hasNextPage endCursor}}}"#
929 )
930 };
931 }
932
933 /// Every issue of one board, found by a search scoped to that board.
934 ///
935 /// This is how the projects a board holds are listed, and it selects no `items`
936 /// connection on `ProjectV2`: the board is a *qualifier of the search* rather than a
937 /// container walked page by page, so nothing nested inside a board item is paid for.
938 /// Which of the issues it returns is a project is then read off `parent` — GitHub
939 /// accepts `-has:parent` as a search qualifier and silently ignores it, so the
940 /// discriminator has to be applied to the field, which is a scalar on the issue and
941 /// costs nothing.
942 pub const SEARCH_ISSUES: &str = concat!(
943 r#"query($search:String!,$type:SearchType!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
944 relationship_events_variable!(),
945 r#"){
946 search(query:$search,type:$type,first:$first,after:$after){
947 pageInfo{hasNextPage endCursor}
948 nodes{__typename ...BoardIssue}
949 }
950 }"#,
951 board_issue!()
952 );
953
954 /// What a dependency read selects of each far end: enough to say which kind of item it
955 /// is, its body included for the kind marker.
956 macro_rules! related_issue {
957 () => {
958 " fragment Related on Issue{id title body parent{id} subIssuesSummary{total}}"
959 };
960 }
961
962 /// One issue by its own node id, which is what a qualified id names here — with what a
963 /// write of it needs and the issue does not carry in `board_issue!`: the field
964 /// definitions of the boards it sits on, and the far ends of its `blockedBy`.
965 ///
966 /// Strongly consistent, unlike the search above: GitHub's issue search is an index and
967 /// answers a write made moments ago with the value from before it, and resolving a node
968 /// id does not.
969 ///
970 /// **Why those two ride here and not on the fragment.** A copy or an update of an item
971 /// reads it by its own id, and with them that one read answers everything the write
972 /// needs: which option ids the board's `Status` and `Priority` fields hold — so no
973 /// [`BOARD_FIELDS`] — and which issues block it, with each one's kind — so no
974 /// [`ISSUE_DEPENDENCIES`]. On `board_issue!` they would sit under the hundred-issue
975 /// pages of [`SEARCH_ISSUES`] and [`SUB_ISSUES`], multiplying both documents' price. Here
976 /// they sit under one item, and this read is still one point.
977 pub const ISSUE: &str = concat!(
978 r#"query($id:ID!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
979 relationship_events_variable!(),
980 r#"){
981 node(id:$id){__typename ...BoardIssue ... on Issue{
982 boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
983 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
984 ... on ProjectV2Field{__typename id name dataType}
985 }pageInfo{hasNextPage}}}}}
986 blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
987 }}
988 }"#,
989 board_issue!(),
990 related_issue!()
991 );
992
993 /// One project's tasks: the sub-issues of the issue that project is, each with a page of
994 /// what blocks it.
995 ///
996 /// The work this costs is the project's own size. Nothing about it grows as the board
997 /// gains projects, or as those projects gain tasks.
998 ///
999 /// **Why `blockedBy` rides here and on no other page of issues.** What reads a project's
1000 /// tasks reads their edges next — `project graph` draws them, a copy carries them — and
1001 /// without them here that is one [`ISSUE_DEPENDENCIES`] per task, so the requests a graph
1002 /// costs grow with its tasks rather than with the pages of them. Carried here, a task
1003 /// blocked by no more than `$nestedFirst` issues answers its forward edges from this read,
1004 /// exactly as an [`ISSUE`] read of it does, and only one blocked by more is asked again.
1005 /// It adds a connection under each issue of the page — one rate-limit point per page,
1006 /// and `$nestedFirst` nodes per issue — and is kept off [`SEARCH_ISSUES`], whose pages
1007 /// answer questions that never read an edge.
1008 pub const SUB_ISSUES: &str = concat!(
1009 r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1010 relationship_events_variable!(),
1011 r#"){
1012 node(id:$id){__typename
1013 ... on Issue{subIssues(first:$first,after:$after){
1014 pageInfo{hasNextPage endCursor}
1015 nodes{__typename ...BoardIssue ... on Issue{
1016 blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1017 }}
1018 }}}
1019 }"#,
1020 board_issue!(),
1021 related_issue!()
1022 );
1023
1024 /// What a read of the board's own `items` selects of each item's content.
1025 ///
1026 /// A macro for the reason [`board_item_values!`] is one: [`BOARD`] and [`ORIGIN_LOOKUP`]
1027 /// both walk `ProjectV2.items` and hand each item to one resolver, so they select its
1028 /// content by one spelling.
1029 macro_rules! board_item_content {
1030 () => {
1031 r#" content{
1032 ... on Issue{__typename id number title body url createdAt updatedAt state stateReason(enableDuplicate:$duplicates) repository{nameWithOwner} parent{id} subIssuesSummary{total} commentCount:comments{totalCount} relationshipEvents:timelineItems(itemTypes:$relationshipEvents){totalCount} labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}}
1033 ... on PullRequest{__typename id}
1034 ... on DraftIssue{__typename id title body createdAt updatedAt}
1035 }"#
1036 };
1037 }
1038
1039 /// Reads the board's fields and one page of its items.
1040 pub const BOARD: &str = concat!(
1041 r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!,$duplicates:Boolean!"#,
1042 relationship_events_variable!(),
1043 r#"){
1044 owner:repositoryOwner(login:$owner){
1045 ... on ProjectV2Owner{projectV2(number:$number){...Board}}
1046 }
1047 } fragment Board on ProjectV2 { id title
1048 fields(first:$nestedFirst){nodes{
1049 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1050 ... on ProjectV2Field{__typename id name dataType}
1051 }pageInfo{hasNextPage}}
1052 items(first:$first,after:$after){nodes{id updatedAt "#,
1053 board_item_values!(),
1054 board_item_content!(),
1055 r#"} pageInfo{hasNextPage endCursor}}
1056 }"#
1057 );
1058
1059 /// Every carrier of one copy origin, by two reads in one request, and nothing else of
1060 /// the board.
1061 ///
1062 /// **`originItems`** is the board's own items narrowed by its own field filter —
1063 /// `ProjectV2.items(query:)`, which GitHub's schema declares as "Search query for
1064 /// filtering items" — to those whose `onetaskgraph.origin` text field holds the
1065 /// qualified id, quoted. It reads the field every carrier already holds, whichever release
1066 /// wrote it, and matches it exactly: measured on 2026-09-29 against a 394-item board,
1067 /// the quoted, the unquoted and the bare-value spellings each returned exactly the one
1068 /// carrier and a prefix of the value returned none. It is `ProjectV2.items`, so it lags a
1069 /// fresh `addProjectV2ItemById` the way that connection does.
1070 ///
1071 /// **`search`** is the board-scoped issue search for the same id as a quoted phrase in
1072 /// the body, which is where this source mirrors the origin into its metadata slot. GitHub
1073 /// indexes that comment, and the index catches up with a write in a second or two rather
1074 /// than in minutes, so it finds a carrier another process wrote that the first read is
1075 /// still behind on.
1076 ///
1077 /// Each connection pages at `$originFirst`, its own small size — see `ORIGIN_PAGE_SIZE`
1078 /// — and resumes from its own cursor; a connection already walked to its end is resumed
1079 /// from its last cursor, which answers an empty page. Every candidate either read returns
1080 /// is confirmed against its own origin field before it is reported, so a token match of
1081 /// the search or anything else the filter admits never is.
1082 ///
1083 /// The root is aliased `originItems` rather than `owner`, so nothing counting the board's
1084 /// own whole reads counts this one among them.
1085 pub const ORIGIN_LOOKUP: &str = concat!(
1086 r#"query($owner:String!,$number:Int!,$filter:String!,$search:String!,$type:SearchType!,$originFirst:Int!,$itemsAfter:String,$searchAfter:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1087 relationship_events_variable!(),
1088 r#"){
1089 originItems:repositoryOwner(login:$owner){
1090 ... on ProjectV2Owner{projectV2(number:$number){
1091 items(first:$originFirst,after:$itemsAfter,query:$filter){nodes{id updatedAt "#,
1092 board_item_values!(),
1093 board_item_content!(),
1094 r#"} pageInfo{hasNextPage endCursor}}
1095 }}
1096 }
1097 search(query:$search,type:$type,first:$originFirst,after:$searchAfter){
1098 pageInfo{hasNextPage endCursor}
1099 nodes{__typename ...BoardIssue}
1100 }
1101 }"#,
1102 board_issue!()
1103 );
1104
1105 /// Every closed item of the board, by the board's own field filter — what
1106 /// `task status reconcile` reads, and nothing else of the board.
1107 ///
1108 /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1109 /// `is:closed` alone, so a board whose open items are most of it is not read whole to find
1110 /// the closed ones. It is narrowed rather than trusted: every item it answers is confirmed
1111 /// closed, with a reason and a card that contradict each other, from the item node it
1112 /// already carries, so a filter that also let open items through would cost reads and
1113 /// write nothing wrong.
1114 ///
1115 /// The board's own id and field definitions ride along, as [`BOARD`] carries them, so the
1116 /// option writes that follow need no read of the board. The root is aliased `closedItems`
1117 /// rather than `owner`, so nothing counting the board's own whole reads counts this one
1118 /// among them.
1119 pub const CLOSED_ITEMS: &str = concat!(
1120 r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1121 relationship_events_variable!(),
1122 r#"){
1123 closedItems:repositoryOwner(login:$owner){
1124 ... on ProjectV2Owner{projectV2(number:$number){id
1125 fields(first:$nestedFirst){nodes{
1126 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1127 ... on ProjectV2Field{__typename id name dataType}
1128 }pageInfo{hasNextPage}}
1129 items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1130 board_item_values!(),
1131 board_item_content!(),
1132 r#"} pageInfo{hasNextPage endCursor}}
1133 }}
1134 }
1135 }"#
1136 );
1137
1138 /// One alias of [`ISSUES_BY_REFERENCE`]: the issue `$owner<n>/$name<n>#$number<n>` names.
1139 macro_rules! reference_alias {
1140 ($n:literal) => {
1141 concat!(
1142 "\n r",
1143 stringify!($n),
1144 ":repository(owner:$owner",
1145 stringify!($n),
1146 ",name:$name",
1147 stringify!($n),
1148 "){issue(number:$number",
1149 stringify!($n),
1150 "){...HeldIssue}}"
1151 )
1152 };
1153 }
1154
1155 /// [`REFERENCE_BATCH`](super::REFERENCE_BATCH) issues at once, each by its repository and
1156 /// number — the one read `task status complete` makes of a source, and nothing else of
1157 /// the board: no `items`, no search and no project read.
1158 ///
1159 /// **Its own fragment, lighter than `board_issue!`, and that is what makes fifty
1160 /// references one point.** It selects no labels, and of each board membership only the
1161 /// `Status` value, by name, with `fieldValueByName` — so each alias asks GitHub for one
1162 /// connection, its page of memberships, where the whole fragment asks for five. What a
1163 /// completion writes is a card and, at most, the issue's state, so the labels and the other
1164 /// field values it leaves out are never what it needs; an item read this way is held for
1165 /// that write alone and never answers another read. An issue whose entry for this board is
1166 /// past its first page of memberships is walked with [`ISSUE_BOARD_ITEMS`], exactly as
1167 /// every other read of an issue recovers one.
1168 ///
1169 /// Fixed-size, as [`ISSUE_DETAILS`] is, so there is one document to price: a batch of
1170 /// fewer references binds the slots it has none for to its last one.
1171 pub const ISSUES_BY_REFERENCE: &str = concat!(
1172 r#"query($owner0:String!,$name0:String!,$number0:Int!,$owner1:String!,$name1:String!,$number1:Int!,$owner2:String!,$name2:String!,$number2:Int!,$owner3:String!,$name3:String!,$number3:Int!,$owner4:String!,$name4:String!,$number4:Int!,$owner5:String!,$name5:String!,$number5:Int!,$owner6:String!,$name6:String!,$number6:Int!,$owner7:String!,$name7:String!,$number7:Int!,$owner8:String!,$name8:String!,$number8:Int!,$owner9:String!,$name9:String!,$number9:Int!,$owner10:String!,$name10:String!,$number10:Int!,$owner11:String!,$name11:String!,$number11:Int!,$owner12:String!,$name12:String!,$number12:Int!,$owner13:String!,$name13:String!,$number13:Int!,$owner14:String!,$name14:String!,$number14:Int!,$owner15:String!,$name15:String!,$number15:Int!,$owner16:String!,$name16:String!,$number16:Int!,$owner17:String!,$name17:String!,$number17:Int!,$owner18:String!,$name18:String!,$number18:Int!,$owner19:String!,$name19:String!,$number19:Int!,$owner20:String!,$name20:String!,$number20:Int!,$owner21:String!,$name21:String!,$number21:Int!,$owner22:String!,$name22:String!,$number22:Int!,$owner23:String!,$name23:String!,$number23:Int!,$owner24:String!,$name24:String!,$number24:Int!,$owner25:String!,$name25:String!,$number25:Int!,$owner26:String!,$name26:String!,$number26:Int!,$owner27:String!,$name27:String!,$number27:Int!,$owner28:String!,$name28:String!,$number28:Int!,$owner29:String!,$name29:String!,$number29:Int!,$owner30:String!,$name30:String!,$number30:Int!,$owner31:String!,$name31:String!,$number31:Int!,$owner32:String!,$name32:String!,$number32:Int!,$owner33:String!,$name33:String!,$number33:Int!,$owner34:String!,$name34:String!,$number34:Int!,$owner35:String!,$name35:String!,$number35:Int!,$owner36:String!,$name36:String!,$number36:Int!,$owner37:String!,$name37:String!,$number37:Int!,$owner38:String!,$name38:String!,$number38:Int!,$owner39:String!,$name39:String!,$number39:Int!,$owner40:String!,$name40:String!,$number40:Int!,$owner41:String!,$name41:String!,$number41:Int!,$owner42:String!,$name42:String!,$number42:Int!,$owner43:String!,$name43:String!,$number43:Int!,$owner44:String!,$name44:String!,$number44:Int!,$owner45:String!,$name45:String!,$number45:Int!,$owner46:String!,$name46:String!,$number46:Int!,$owner47:String!,$name47:String!,$number47:Int!,$owner48:String!,$name48:String!,$number48:Int!,$owner49:String!,$name49:String!,$number49:Int!,$boardItems:Int!,$statusField:String!,$duplicates:Boolean!"#,
1173 relationship_events_variable!(),
1174 r#"){"#,
1175 reference_alias!(0),
1176 reference_alias!(1),
1177 reference_alias!(2),
1178 reference_alias!(3),
1179 reference_alias!(4),
1180 reference_alias!(5),
1181 reference_alias!(6),
1182 reference_alias!(7),
1183 reference_alias!(8),
1184 reference_alias!(9),
1185 reference_alias!(10),
1186 reference_alias!(11),
1187 reference_alias!(12),
1188 reference_alias!(13),
1189 reference_alias!(14),
1190 reference_alias!(15),
1191 reference_alias!(16),
1192 reference_alias!(17),
1193 reference_alias!(18),
1194 reference_alias!(19),
1195 reference_alias!(20),
1196 reference_alias!(21),
1197 reference_alias!(22),
1198 reference_alias!(23),
1199 reference_alias!(24),
1200 reference_alias!(25),
1201 reference_alias!(26),
1202 reference_alias!(27),
1203 reference_alias!(28),
1204 reference_alias!(29),
1205 reference_alias!(30),
1206 reference_alias!(31),
1207 reference_alias!(32),
1208 reference_alias!(33),
1209 reference_alias!(34),
1210 reference_alias!(35),
1211 reference_alias!(36),
1212 reference_alias!(37),
1213 reference_alias!(38),
1214 reference_alias!(39),
1215 reference_alias!(40),
1216 reference_alias!(41),
1217 reference_alias!(42),
1218 reference_alias!(43),
1219 reference_alias!(44),
1220 reference_alias!(45),
1221 reference_alias!(46),
1222 reference_alias!(47),
1223 reference_alias!(48),
1224 reference_alias!(49),
1225 "\n }",
1226 r#" fragment HeldIssue on Issue{__typename id number title body url createdAt updatedAt state stateReason(enableDuplicate:$duplicates) repository{nameWithOwner} parent{id} subIssuesSummary{total} commentCount:comments{totalCount} relationshipEvents:timelineItems(itemTypes:$relationshipEvents){totalCount}
1227 projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1228 status:fieldValueByName(name:$statusField){... on ProjectV2ItemFieldSingleSelectValue{name field{
1229 ... on ProjectV2SingleSelectField{id name options{id name}}
1230 }}}
1231 }pageInfo{hasNextPage endCursor}}}"#
1232 );
1233
1234 /// The board's own id and field definitions, and not one of its items.
1235 ///
1236 /// What a write needs of the board when the item it writes does not say: the id a field
1237 /// write and `addProjectV2ItemById` address, and the definitions of the `Status` and
1238 /// origin fields. It selects no `items`, so what it costs is the board's field list
1239 /// however many items the board holds — and it decides nothing about which items those
1240 /// are, which is the question a read of one item by its own id answers instead.
1241 ///
1242 /// The root is aliased `boardFields` rather than `owner`, so nothing counting the
1243 /// board's item reads by their root counts this one among them.
1244 pub const BOARD_FIELDS: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!){
1245 boardFields:repositoryOwner(login:$owner){
1246 ... on ProjectV2Owner{projectV2(number:$number){id
1247 fields(first:$nestedFirst){nodes{
1248 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1249 ... on ProjectV2Field{__typename id name dataType}
1250 }pageInfo{hasNextPage}}
1251 }}
1252 }
1253 }"#;
1254
1255 /// One board draft by its own node id, with the board item it sits in.
1256 ///
1257 /// A draft is not an issue, so [`ISSUE`] reaches it and reads nothing of it; this is the
1258 /// second read that answers it. `DraftIssue.projectV2Items` names the board item a draft
1259 /// is — GitHub links a draft to one item — with the same [`board_item_values!`] the
1260 /// issue fragment reads, so a draft reached by id resolves through the same resolver a
1261 /// board listing hands it to, and nothing has to list the board to find one.
1262 pub const DRAFT: &str = concat!(
1263 r#"query($id:ID!,$nestedFirst:Int!,$boardItems:Int!){
1264 node(id:$id){__typename ... on DraftIssue{id title body createdAt updatedAt
1265 projectV2Items(first:$boardItems){nodes{id project{id number}
1266 "#,
1267 board_item_values!(),
1268 r#"}pageInfo{hasNextPage endCursor}}}}
1269 }"#
1270 );
1271
1272 /// One issue's board memberships alone, walked past the page a read of it carried.
1273 ///
1274 /// The recovery read behind [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource):
1275 /// every document above carries a *page* of `Issue.projectItems`, and an issue on more
1276 /// boards than that page holds may have this board's entry past its end. This asks that
1277 /// one issue for its memberships and nothing else — the caller already holds the issue —
1278 /// so an answer of "this board does not hold it" is only ever given about a connection
1279 /// read to exhaustion.
1280 ///
1281 /// It selects the board item's id, its project number and the same
1282 /// [`board_item_values!`] the fragment does, because what it produces is handed to the
1283 /// very same resolver: an issue recovered this way reports the same title, the same
1284 /// status, the same labels and the same qualified id as one whose entry was on the
1285 /// page.
1286 ///
1287 /// `$first` rather than `$boardItems`: this document reads one issue, so nothing
1288 /// multiplies through it and the membership connection can be walked at
1289 /// [`MAX_PAGE_SIZE`](super::MAX_PAGE_SIZE) — which is what keeps the recovery to one
1290 /// further request for any issue a person really keeps.
1291 pub const ISSUE_BOARD_ITEMS: &str = concat!(
1292 r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!){
1293 node(id:$id){
1294 ... on Issue{projectItems(first:$first,after:$after){
1295 nodes{id updatedAt project{id number}
1296 "#,
1297 board_item_values!(),
1298 r#"}
1299 pageInfo{hasNextPage endCursor}}}
1300 }
1301 }"#
1302 );
1303 /// Whether the board's Project is public — half of what decides whether a write here can
1304 /// be read by anybody. Needs the `read:project` scope.
1305 pub const PROJECT_VISIBILITY: &str = r#"query($owner:String!,$number:Int!){visibility:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){public}}}}"#;
1306 /// Resolves the configured repository's node id, which creating an issue requires.
1307 pub const REPOSITORY: &str = r#"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){id nameWithOwner}}"#;
1308 /// What creating an issue needs and has not read yet: the board's own id and field
1309 /// definitions, as [`BOARD_FIELDS`] reads them, and the node id of the repository the
1310 /// issue is created in, as [`REPOSITORY`] reads it — in one request.
1311 ///
1312 /// Sent at the point a create knows which repository it is for, when neither half is
1313 /// already known to this process; a create needing only one of them sends that one's own
1314 /// document. Neither half is kept past the process: a field's option ids are re-minted by
1315 /// `sources fields --apply`, so a copy of them held between runs would write the wrong
1316 /// status.
1317 pub const CREATION_CONTEXT: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!,$repositoryOwner:String!,$repositoryName:String!){
1318 boardFields:repositoryOwner(login:$owner){
1319 ... on ProjectV2Owner{projectV2(number:$number){id
1320 fields(first:$nestedFirst){nodes{
1321 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1322 ... on ProjectV2Field{__typename id name dataType}
1323 }pageInfo{hasNextPage}}
1324 }}
1325 }
1326 repository(owner:$repositoryOwner,name:$repositoryName){id nameWithOwner}
1327 }"#;
1328 /// Reads both dependency directions for one issue, with each far end's own kind — and
1329 /// the issue's own body, which is where an edge to another source is recorded, so that
1330 /// half of a dependency read needs no second read of the issue or of the board.
1331 pub const ISSUE_DEPENDENCIES: &str = concat!(
1332 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1333 ... on Issue{body
1334 blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1335 blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1336 }}}"#,
1337 related_issue!()
1338 );
1339 /// Creates one issue in the configured repository, on no board: [`ADD_TO_BOARD`] files
1340 /// it. `CreateIssueInput.projectV2Ids` is not sent — see the crate's notes on what GitHub
1341 /// answered when it was.
1342 pub const CREATE_ISSUE: &str =
1343 r#"mutation($input:CreateIssueInput!){createIssue(input:$input){issue{id number url}}}"#;
1344 /// Puts an existing issue on the configured board.
1345 pub const ADD_TO_BOARD: &str = r#"mutation($input:AddProjectV2ItemByIdInput!){addProjectV2ItemById(input:$input){item{id}}}"#;
1346 /// Updates an issue's visible fields and its open or closed state in one call.
1347 pub const UPDATE_ISSUE: &str =
1348 r#"mutation($input:UpdateIssueInput!){updateIssue(input:$input){issue{id}}}"#;
1349 /// Updates an existing draft's user-visible fields.
1350 pub const UPDATE_DRAFT: &str = r#"mutation($input:UpdateProjectV2DraftIssueInput!){updateProjectV2DraftIssue(input:$input){draftIssue{id}}}"#;
1351 /// Updates a text or single-select value on one project item.
1352 pub const UPDATE_FIELD: &str = r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}}}}}"#;
1353 /// Writes up to six board fields and clears up to three in one ordered mutation: every
1354 /// aliased field is included by its own boolean, as [`FIELD_WRITE_SLOTS`](super::FIELD_WRITE_SLOTS)
1355 /// and [`FIELD_CLEAR_SLOTS`](super::FIELD_CLEAR_SLOTS) name them, writes before clears.
1356 pub const UPDATE_FIELDS: &str = r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$second:UpdateProjectV2ItemFieldValueInput!,$third:UpdateProjectV2ItemFieldValueInput!,$fourth:UpdateProjectV2ItemFieldValueInput!,$fifth:UpdateProjectV2ItemFieldValueInput!,$sixth:UpdateProjectV2ItemFieldValueInput!,$clear:ClearProjectV2ItemFieldValueInput!,$clearSecond:ClearProjectV2ItemFieldValueInput!,$clearThird:ClearProjectV2ItemFieldValueInput!,$writeFirst:Boolean!,$writeSecond:Boolean!,$writeThird:Boolean!,$writeFourth:Boolean!,$writeFifth:Boolean!,$writeSixth:Boolean!,$writeClear:Boolean!,$writeClearSecond:Boolean!,$writeClearThird:Boolean!){updateProjectV2ItemFieldValue(input:$input) @include(if:$writeFirst){projectV2Item{id}} second:updateProjectV2ItemFieldValue(input:$second) @include(if:$writeSecond){projectV2Item{id}} third:updateProjectV2ItemFieldValue(input:$third) @include(if:$writeThird){projectV2Item{id}} fourth:updateProjectV2ItemFieldValue(input:$fourth) @include(if:$writeFourth){projectV2Item{id}} fifth:updateProjectV2ItemFieldValue(input:$fifth) @include(if:$writeFifth){projectV2Item{id}} sixth:updateProjectV2ItemFieldValue(input:$sixth) @include(if:$writeSixth){projectV2Item{id}} cleared:clearProjectV2ItemFieldValue(input:$clear) @include(if:$writeClear){projectV2Item{id}} clearedSecond:clearProjectV2ItemFieldValue(input:$clearSecond) @include(if:$writeClearSecond){projectV2Item{id}} clearedThird:clearProjectV2ItemFieldValue(input:$clearThird) @include(if:$writeClearThird){projectV2Item{id}}}"#;
1357 /// Clears one project item's value of one field, which is what a `none` priority is.
1358 pub const CLEAR_FIELD: &str = r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}}}}}"#;
1359 /// Creates one field: a single-select one with its options, or a text one for a projected
1360 /// metadata value. Only the guarded field setup may use this document, and only for a
1361 /// field the board lacks.
1362 pub const CREATE_FIELD: &str = r#"mutation($input:CreateProjectV2FieldInput!){createProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id name options{id name color description}}}}}"#;
1363 /// Replaces a single-select field's options. Only the guarded field setup — the
1364 /// `status-options` and `fields` operations — may use this document, because GitHub
1365 /// treats the input as the complete option list.
1366 pub const STATUS_OPTIONS_UPDATE: &str = r#"mutation($input:UpdateProjectV2FieldInput!){updateProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id options{id name color description}}}}}"#;
1367 /// A fresh snapshot of the Status field and every board item's assignment.
1368 pub const STATUS_OPTIONS_SNAPSHOT: &str = r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!){owner:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){id fields(first:$nestedFirst){nodes{... on ProjectV2SingleSelectField{id name options{id name color description}}}pageInfo{hasNextPage}} items(first:$first,after:$after){nodes{id fieldValues(first:$nestedFirst){nodes{... on ProjectV2ItemFieldSingleSelectValue{name optionId field{... on ProjectV2SingleSelectField{id name}}}}pageInfo{hasNextPage}}}pageInfo{hasNextPage endCursor}}}}}}"#;
1369 /// Files one issue under another as a sub-issue, which is what project membership is.
1370 pub const ADD_SUB_ISSUE: &str =
1371 r#"mutation($input:AddSubIssueInput!){addSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1372 /// Takes one issue back out of its parent.
1373 pub const REMOVE_SUB_ISSUE: &str = r#"mutation($input:RemoveSubIssueInput!){removeSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1374 /// Adds GitHub's native issue blocked-by relationship.
1375 pub const ADD_BLOCKED_BY: &str = r#"mutation($input:AddBlockedByInput!){addBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
1376 /// Removes one native issue blocked-by relationship.
1377 pub const REMOVE_BLOCKED_BY: &str = r#"mutation($input:RemoveBlockedByInput!){removeBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
1378 /// Deletes one issue, which takes its board item with it.
1379 ///
1380 /// The engine sends this in one situation only: undoing a copy that could not finish,
1381 /// over the items that same copy created. Deleting the issue removes the board item
1382 /// too, so there is no second `deleteProjectV2Item` to keep in step with it.
1383 pub const DELETE_ISSUE: &str =
1384 r#"mutation($input:DeleteIssueInput!){deleteIssue(input:$input){repository{id}}}"#;
1385
1386 /// Everything this source reads about one issue comment, wherever it reaches one.
1387 ///
1388 /// A macro for the reason [`board_issue!`] is one: a comment listed, a comment just added
1389 /// and a comment just edited are handed to one mapper, so they are selected by one
1390 /// spelling. `author` is `Actor`, which GitHub answers `null` for an account that no
1391 /// longer exists, and `login` is the one member every kind of actor carries.
1392 macro_rules! issue_comment {
1393 () => {
1394 "id author{login} createdAt updatedAt body url"
1395 };
1396 }
1397
1398 /// One task's comments: a page of its issue's own `comments` connection.
1399 ///
1400 /// **No `orderBy`, and that is what makes the page oldest first.** GitHub's only
1401 /// `IssueCommentOrder` field is `UPDATED_AT`, which would move a comment to the end of the
1402 /// list every time somebody edited it; left unordered the connection answers in the order
1403 /// the comments were written, which is the order GitHub documents for the same collection
1404 /// over REST — ascending id. Nothing multiplies through it, so `$first` is the whole of its
1405 /// node count and the caller's own page size is pushed straight down.
1406 pub const ISSUE_COMMENTS: &str = concat!(
1407 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename ... on Issue{comments(first:$first,after:$after){nodes{"#,
1408 issue_comment!(),
1409 r#"}pageInfo{hasNextPage endCursor}}}}}"#
1410 );
1411 /// One issue by its own node id, with a page of its comments: what `task show` and a
1412 /// comment listing read, in one request.
1413 ///
1414 /// [`ISSUE`] and [`ISSUE_COMMENTS`] in one document, rather than one then the other. The
1415 /// comments are selected here and **not** on the shared `board_issue!` fragment, which
1416 /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] nest under a page of a hundred issues: a comment
1417 /// connection there would multiply through both of those documents' price, and neither
1418 /// needs one.
1419 pub const ISSUE_DETAIL: &str = concat!(
1420 r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1421 relationship_events_variable!(),
1422 r#"){
1423 node(id:$id){__typename ...BoardIssue ... on Issue{comments(first:$first,after:$after){nodes{"#,
1424 issue_comment!(),
1425 r#"}pageInfo{hasNextPage endCursor}}}}
1426 }"#,
1427 board_issue!()
1428 );
1429
1430 /// One alias of [`ISSUE_DETAILS`]: the item a batch's `$id<n>` names, with the first
1431 /// page of its comments when `$comments` asks for them.
1432 macro_rules! issue_details_alias {
1433 ($n:literal) => {
1434 concat!(
1435 "\n i",
1436 stringify!($n),
1437 ":node(id:$id",
1438 stringify!($n),
1439 "){__typename ...BoardIssue ... on Issue{comments(first:$first) @include(if:$comments){nodes{",
1440 issue_comment!(),
1441 "}pageInfo{hasNextPage endCursor}}}}"
1442 )
1443 };
1444 }
1445
1446 /// [`ISSUE_DETAIL`] for [`DETAIL_BATCH`](super::DETAIL_BATCH) items at once, each by its
1447 /// own node id, as one fixed-size document of aliased `node(id:)` fields.
1448 ///
1449 /// **Aliased `node(id:)` rather than `nodes(ids:)`, and that is what keeps its price
1450 /// honest.** The `github-graphql-node-count` model this workspace prices with treats a
1451 /// field that supplies neither `first` nor `last` as free, and `nodes(ids:)` supplies
1452 /// neither — so every connection under it would be priced at nothing and the pin in
1453 /// `tests/point_cost.rs` would understate what GitHub charges. Each alias here is the
1454 /// one-item read the model already prices, so the batch costs what its aliases cost.
1455 ///
1456 /// **Fixed-size, so there is one document to price.** A batch of fewer items binds the
1457 /// slots it has no item for to the last item it does, and reads that item again; the
1458 /// price is the document's, whatever its variables, so a short batch costs what a full
1459 /// one does and nothing more.
1460 pub const ISSUE_DETAILS: &str = concat!(
1461 r#"query($id0:ID!,$id1:ID!,$id2:ID!,$id3:ID!,$id4:ID!,$id5:ID!,$id6:ID!,$id7:ID!,$id8:ID!,$id9:ID!,$id10:ID!,$id11:ID!,$id12:ID!,$id13:ID!,$id14:ID!,$id15:ID!,$id16:ID!,$id17:ID!,$id18:ID!,$id19:ID!,$id20:ID!,$id21:ID!,$id22:ID!,$id23:ID!,$first:Int!,$comments:Boolean!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1462 relationship_events_variable!(),
1463 r#"){"#,
1464 issue_details_alias!(0),
1465 issue_details_alias!(1),
1466 issue_details_alias!(2),
1467 issue_details_alias!(3),
1468 issue_details_alias!(4),
1469 issue_details_alias!(5),
1470 issue_details_alias!(6),
1471 issue_details_alias!(7),
1472 issue_details_alias!(8),
1473 issue_details_alias!(9),
1474 issue_details_alias!(10),
1475 issue_details_alias!(11),
1476 issue_details_alias!(12),
1477 issue_details_alias!(13),
1478 issue_details_alias!(14),
1479 issue_details_alias!(15),
1480 issue_details_alias!(16),
1481 issue_details_alias!(17),
1482 issue_details_alias!(18),
1483 issue_details_alias!(19),
1484 issue_details_alias!(20),
1485 issue_details_alias!(21),
1486 issue_details_alias!(22),
1487 issue_details_alias!(23),
1488 "\n }",
1489 board_issue!()
1490 );
1491
1492 /// One alias of [`ISSUE_COPY_DETAILS`]: the item a batch's `$id<n>` names, with the first
1493 /// page of its comments and the issues it is blocked by.
1494 macro_rules! issue_copy_details_alias {
1495 ($n:literal) => {
1496 concat!(
1497 "\n i",
1498 stringify!($n),
1499 ":node(id:$id",
1500 stringify!($n),
1501 "){__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{",
1502 issue_comment!(),
1503 "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}}}"
1504 )
1505 };
1506 }
1507
1508 /// [`ISSUE_DETAILS`] as a copy reads the tasks it carries: each item with the first page of
1509 /// its comments and its `blockedBy` — the edges a copy reads of every task next, which
1510 /// [`ISSUE`] carries and [`ISSUE_DETAILS`] does not — [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH)
1511 /// at a time, so a copy of a changed task costs this read and nothing else.
1512 ///
1513 /// A document of its own rather than a widening of [`ISSUE_DETAILS`], whose batch size is
1514 /// what `task show-many` is priced by and which reads no edge.
1515 pub const ISSUE_COPY_DETAILS: &str = concat!(
1516 r#"query($id0:ID!,$id1:ID!,$id2:ID!,$id3:ID!,$id4:ID!,$id5:ID!,$id6:ID!,$id7:ID!,$id8:ID!,$id9:ID!,$id10:ID!,$id11:ID!,$id12:ID!,$id13:ID!,$id14:ID!,$id15:ID!,$id16:ID!,$id17:ID!,$id18:ID!,$id19:ID!,$id20:ID!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1517 relationship_events_variable!(),
1518 r#"){"#,
1519 issue_copy_details_alias!(0),
1520 issue_copy_details_alias!(1),
1521 issue_copy_details_alias!(2),
1522 issue_copy_details_alias!(3),
1523 issue_copy_details_alias!(4),
1524 issue_copy_details_alias!(5),
1525 issue_copy_details_alias!(6),
1526 issue_copy_details_alias!(7),
1527 issue_copy_details_alias!(8),
1528 issue_copy_details_alias!(9),
1529 issue_copy_details_alias!(10),
1530 issue_copy_details_alias!(11),
1531 issue_copy_details_alias!(12),
1532 issue_copy_details_alias!(13),
1533 issue_copy_details_alias!(14),
1534 issue_copy_details_alias!(15),
1535 issue_copy_details_alias!(16),
1536 issue_copy_details_alias!(17),
1537 issue_copy_details_alias!(18),
1538 issue_copy_details_alias!(19),
1539 issue_copy_details_alias!(20),
1540 "\n }",
1541 board_issue!(),
1542 related_issue!()
1543 );
1544
1545 /// Which issue one comment is on, read before that comment is edited or removed.
1546 ///
1547 /// GitHub's comment mutations take the comment's id and nothing else, so without this a
1548 /// comment id given against the wrong task would change a comment on another issue.
1549 pub const COMMENT_ISSUE: &str =
1550 r#"query($id:ID!){node(id:$id){__typename ... on IssueComment{id body issue{id}}}}"#;
1551 /// Adds one comment to an issue, signed as the account the token belongs to.
1552 pub const ADD_COMMENT: &str = concat!(
1553 r#"mutation($input:AddCommentInput!){addComment(input:$input){subject{id} commentEdge{node{"#,
1554 issue_comment!(),
1555 r#"}}}}"#
1556 );
1557 /// Replaces the body of one issue comment.
1558 pub const UPDATE_COMMENT: &str = concat!(
1559 r#"mutation($input:UpdateIssueCommentInput!){updateIssueComment(input:$input){issueComment{"#,
1560 issue_comment!(),
1561 r#"}}}"#
1562 );
1563 /// Removes one issue comment. Its payload carries nothing about the comment it removed.
1564 pub const DELETE_COMMENT: &str = r#"mutation($input:DeleteIssueCommentInput!){deleteIssueComment(input:$input){clientMutationId}}"#;
1565
1566 /// What a mutation of a write the store's cache expects selects of the issue it wrote:
1567 /// everything [`ISSUE_DETAIL`] reads of it, so its response shows the task whole — its
1568 /// change token's every part and the first page of its comments.
1569 ///
1570 /// Sent **only** while that write runs, in place of the document named beside each
1571 /// below, so every other write's documents, prices and request counts are what they
1572 /// were. GitHub's token waits for a task to settle (`change_token::SETTLED`), and a
1573 /// mutation's response is stamped seconds after the change it made, so against GitHub
1574 /// itself a response rarely determines a version; the cache is then left unserveable
1575 /// for the task, and its next read refreshes it.
1576 macro_rules! whole_issue {
1577 () => {
1578 concat!(
1579 r#"__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{"#,
1580 issue_comment!(),
1581 r#"}pageInfo{hasNextPage endCursor}}}"#
1582 )
1583 };
1584 }
1585
1586 /// The variables every document of `whole_issue!` declares beside its own.
1587 macro_rules! whole_variables {
1588 () => {
1589 concat!(
1590 r#",$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1591 relationship_events_variable!()
1592 )
1593 };
1594 }
1595
1596 /// [`ADD_COMMENT`], selecting the whole issue commented on.
1597 pub const ADD_COMMENT_WHOLE: &str = concat!(
1598 r#"mutation($input:AddCommentInput!"#,
1599 whole_variables!(),
1600 r#"){addComment(input:$input){subject{id "#,
1601 whole_issue!(),
1602 r#"} commentEdge{node{"#,
1603 issue_comment!(),
1604 r#"}}}}"#,
1605 board_issue!()
1606 );
1607 /// [`UPDATE_COMMENT`], selecting the whole issue the comment is on.
1608 pub const UPDATE_COMMENT_WHOLE: &str = concat!(
1609 r#"mutation($input:UpdateIssueCommentInput!"#,
1610 whole_variables!(),
1611 r#"){updateIssueComment(input:$input){issueComment{"#,
1612 issue_comment!(),
1613 r#" issue{"#,
1614 whole_issue!(),
1615 r#"}}}}"#,
1616 board_issue!()
1617 );
1618 /// [`UPDATE_ISSUE`], selecting the whole issue updated.
1619 pub const UPDATE_ISSUE_WHOLE: &str = concat!(
1620 r#"mutation($input:UpdateIssueInput!"#,
1621 whole_variables!(),
1622 r#"){updateIssue(input:$input){issue{id "#,
1623 whole_issue!(),
1624 r#"}}}"#,
1625 board_issue!()
1626 );
1627 /// [`UPDATE_FIELD`], selecting the whole issue behind the board item written.
1628 pub const UPDATE_FIELD_WHOLE: &str = concat!(
1629 r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
1630 whole_variables!(),
1631 r#"){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
1632 whole_issue!(),
1633 r#"}}}}"#,
1634 board_issue!()
1635 );
1636 /// [`CLEAR_FIELD`], selecting the whole issue behind the board item cleared.
1637 pub const CLEAR_FIELD_WHOLE: &str = concat!(
1638 r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
1639 whole_variables!(),
1640 r#"){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
1641 whole_issue!(),
1642 r#"}}}}"#,
1643 board_issue!()
1644 );
1645
1646 /// The document sent in `document`'s place while a write the store's cache expects runs,
1647 /// when it has one.
1648 #[must_use]
1649 pub fn whole_twin(document: &str) -> Option<&'static str> {
1650 [
1651 (ADD_COMMENT, ADD_COMMENT_WHOLE),
1652 (UPDATE_COMMENT, UPDATE_COMMENT_WHOLE),
1653 (UPDATE_ISSUE, UPDATE_ISSUE_WHOLE),
1654 (UPDATE_FIELD, UPDATE_FIELD_WHOLE),
1655 (CLEAR_FIELD, CLEAR_FIELD_WHOLE),
1656 ]
1657 .into_iter()
1658 .find(|(plain, _)| *plain == document)
1659 .map(|(_, whole)| whole)
1660 }
1661
1662 /// Every document above, with what this source is doing when it sends one.
1663 ///
1664 /// One list rather than a `match` beside the constants: a rate-limit diagnostic has to
1665 /// name the call that was refused, and a `match` with a catch-all arm would answer a
1666 /// document added later with "talking to GitHub" and never say so.
1667 ///
1668 /// `documents_are_all_inventoried` reads this file back and fails naming any `pub
1669 /// const` here that this list omits, so the two cannot part — which is the same guard
1670 /// `CATEGORIES` carries, in the one shape available to a set of `&str` constants.
1671 pub const DOCUMENTS: [(&str, &str); 42] = [
1672 (SEARCH_ISSUES, "searching this board's issues"),
1673 (ISSUE, "reading one issue"),
1674 (
1675 ISSUE_BOARD_ITEMS,
1676 "reading one issue's board memberships past the page it came with",
1677 ),
1678 (SUB_ISSUES, "reading a project's tasks"),
1679 (BOARD, "reading the board"),
1680 (ORIGIN_LOOKUP, "looking up the items copied from one origin"),
1681 (CLOSED_ITEMS, "reading the board's closed items"),
1682 (
1683 ISSUES_BY_REFERENCE,
1684 "reading a batch of issues by their references",
1685 ),
1686 (BOARD_FIELDS, "reading the board's fields"),
1687 (DRAFT, "reading one draft"),
1688 (REPOSITORY, "reading the destination repository"),
1689 (
1690 PROJECT_VISIBILITY,
1691 "reading whether the board's project is public",
1692 ),
1693 (
1694 CREATION_CONTEXT,
1695 "reading the board's fields and the destination repository",
1696 ),
1697 (ISSUE_DEPENDENCIES, "reading an issue's dependencies"),
1698 (CREATE_ISSUE, "creating an issue"),
1699 (ADD_TO_BOARD, "adding an issue to the board"),
1700 (UPDATE_ISSUE, "updating an issue"),
1701 (UPDATE_DRAFT, "updating a draft item"),
1702 (UPDATE_FIELD, "writing a board field"),
1703 (UPDATE_FIELDS, "writing board fields together"),
1704 (CLEAR_FIELD, "clearing a board field"),
1705 (
1706 CREATE_FIELD,
1707 "creating a board single-select field with its options",
1708 ),
1709 (
1710 STATUS_OPTIONS_SNAPSHOT,
1711 "snapshotting board Status options and assignments",
1712 ),
1713 (
1714 STATUS_OPTIONS_UPDATE,
1715 "safely replacing the board Status option list",
1716 ),
1717 (ADD_SUB_ISSUE, "filing an issue under its project"),
1718 (REMOVE_SUB_ISSUE, "taking an issue out of its project"),
1719 (ADD_BLOCKED_BY, "recording a dependency"),
1720 (REMOVE_BLOCKED_BY, "removing a dependency"),
1721 (DELETE_ISSUE, "deleting an issue"),
1722 (ISSUE_COMMENTS, "reading a task's comments"),
1723 (ISSUE_DETAIL, "reading one issue with its comments"),
1724 (
1725 ISSUE_DETAILS,
1726 "reading a batch of issues with their comments",
1727 ),
1728 (
1729 ISSUE_COPY_DETAILS,
1730 "reading a batch of issues with their comments and dependencies for a copy",
1731 ),
1732 (COMMENT_ISSUE, "reading which issue a comment is on"),
1733 (ADD_COMMENT, "adding a comment"),
1734 (UPDATE_COMMENT, "editing a comment"),
1735 (DELETE_COMMENT, "deleting a comment"),
1736 (
1737 ADD_COMMENT_WHOLE,
1738 "adding a comment, answered with the whole issue",
1739 ),
1740 (
1741 UPDATE_COMMENT_WHOLE,
1742 "editing a comment, answered with the whole issue",
1743 ),
1744 (
1745 UPDATE_ISSUE_WHOLE,
1746 "updating an issue, answered with it whole",
1747 ),
1748 (
1749 UPDATE_FIELD_WHOLE,
1750 "writing a board field, answered with the whole issue",
1751 ),
1752 (
1753 CLEAR_FIELD_WHOLE,
1754 "clearing a board field, answered with the whole issue",
1755 ),
1756 ];
1757}
1758
1759/// One aliased mutation field of [`graphql::UPDATE_FIELDS`]: the key its answer comes back
1760/// under, the variable carrying its input, and the boolean variable that includes it.
1761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1762pub struct FieldSlot {
1763 /// The key of the answer's `data` this field's payload is under.
1764 pub alias: &'static str,
1765 /// The variable carrying this field's input.
1766 pub variable: &'static str,
1767 /// The boolean variable whose `true` sends this field.
1768 pub include: &'static str,
1769}
1770
1771/// The value writes [`graphql::UPDATE_FIELDS`] carries, in the order GitHub runs them.
1772pub const FIELD_WRITE_SLOTS: [FieldSlot; 6] = [
1773 FieldSlot {
1774 alias: "updateProjectV2ItemFieldValue",
1775 variable: "input",
1776 include: "writeFirst",
1777 },
1778 FieldSlot {
1779 alias: "second",
1780 variable: "second",
1781 include: "writeSecond",
1782 },
1783 FieldSlot {
1784 alias: "third",
1785 variable: "third",
1786 include: "writeThird",
1787 },
1788 FieldSlot {
1789 alias: "fourth",
1790 variable: "fourth",
1791 include: "writeFourth",
1792 },
1793 FieldSlot {
1794 alias: "fifth",
1795 variable: "fifth",
1796 include: "writeFifth",
1797 },
1798 FieldSlot {
1799 alias: "sixth",
1800 variable: "sixth",
1801 include: "writeSixth",
1802 },
1803];
1804
1805/// The clears [`graphql::UPDATE_FIELDS`] carries, run after every write of the same request.
1806pub const FIELD_CLEAR_SLOTS: [FieldSlot; 3] = [
1807 FieldSlot {
1808 alias: "cleared",
1809 variable: "clear",
1810 include: "writeClear",
1811 },
1812 FieldSlot {
1813 alias: "clearedSecond",
1814 variable: "clearSecond",
1815 include: "writeClearSecond",
1816 },
1817 FieldSlot {
1818 alias: "clearedThird",
1819 variable: "clearThird",
1820 include: "writeClearThird",
1821 },
1822];
1823
1824/// Which of GitHub's two rate limiters refused a request.
1825///
1826/// Waiting is the whole answer to the primary budget, and polling is what *extends* the
1827/// secondary one — so an operator told the wrong one takes the wrong next step, which is
1828/// the whole reason this is carried rather than collapsed into "rate limited".
1829#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1830enum Limiter {
1831 /// The hourly API budget, which `gh api rate_limit` reports and a wait answers.
1832 Primary,
1833 /// The burst limiter over content-generating requests, which nothing reports.
1834 Secondary,
1835}
1836
1837/// The wordings GitHub answers a secondary rate limit with.
1838///
1839/// It sends them under a forbidden status, under a too-many-requests status, and inside
1840/// the `errors` of a *successful* response, which is why the text is what this matches on
1841/// rather than the status. `abuse detection` is the wording GitHub used before the
1842/// limiter was renamed and still returns from some endpoints; `submitted too quickly` is
1843/// what a burst of content creation is refused with.
1844///
1845/// This is GitHub's vocabulary rather than this source's, so it is pinned rather than
1846/// remembered: `tests/fixtures/rate-limits.json` records where each wording was read and
1847/// when, and the drift gate reconciles the two lists both ways. Public for that gate
1848/// alone — a caller has no use for it, and matching on a refusal is this source's job.
1849pub const SECONDARY_WORDINGS: [&str; 5] = [
1850 "secondary rate limit",
1851 "temporarily blocked from content creation",
1852 "abuse detection",
1853 "submitted too quickly",
1854 "exceeded a secondary",
1855];
1856
1857/// The wordings GitHub answers an exhausted primary budget with.
1858///
1859/// `rate_limited` is the `type` its GraphQL error carries, which is read as a field rather
1860/// than looked for in the response text. `api rate limit already exceeded` is what GraphQL
1861/// answers a request made once the hour's budget is spent — "API rate limit already exceeded
1862/// for user ID …" in the `errors` of an HTTP 200, with no `type` — and neither of the other
1863/// two phrases is a substring of it, so without it that answer read as a refusal that will
1864/// never lift. Pinned and gated exactly as [`SECONDARY_WORDINGS`] is, and public for the same
1865/// one reason.
1866pub const PRIMARY_WORDINGS: [&str; 4] = [
1867 "api rate limit exceeded",
1868 "api rate limit already exceeded",
1869 "rate limit exceeded",
1870 "rate_limited",
1871];
1872
1873/// What a response *says about itself*, which is the only place a refusal can be read.
1874///
1875/// Deliberately not the whole response body. A board is a place people write about their
1876/// own work, and a task on it titled "the secondary rate limit" would, matched across the
1877/// raw text, turn a perfectly good answer into a refusal this source then waited out and
1878/// reported. So the item data is never read: what is read is GitHub's own REST-style
1879/// `message` envelope, which is what a forbidden status carries, and the `message` and
1880/// `type` of each GraphQL error, which is where a *successful* response says it.
1881///
1882/// A body that is not JSON at all has nothing structured to read, so only a failing
1883/// response's own text is taken — a successful response that is not JSON is malformed
1884/// rather than refused, and [`GitHubProjectsSource::answer`] says so.
1885fn refusal_wording(status: StatusCode, body: &str) -> String {
1886 let Ok(parsed) = serde_json::from_str::<Value>(body) else {
1887 return if status.is_success() {
1888 String::new()
1889 } else {
1890 body.to_owned()
1891 };
1892 };
1893 let mut said: Vec<&str> = parsed
1894 .get("message")
1895 .and_then(Value::as_str)
1896 .into_iter()
1897 .collect();
1898 if let Some(errors) = parsed.get("errors").and_then(Value::as_array) {
1899 for error in errors {
1900 said.extend(
1901 ["message", "type"]
1902 .into_iter()
1903 .filter_map(|key| error.get(key).and_then(Value::as_str)),
1904 );
1905 }
1906 }
1907 said.join("; ")
1908}
1909
1910impl Limiter {
1911 /// Which limiter refused this response, or `None` when none of them did.
1912 ///
1913 /// The wording is read first and the status only decides what carries none of it,
1914 /// because GitHub answers a secondary limit with a forbidden status far more often
1915 /// than with too-many-requests — while a forbidden status saying nothing about a limit
1916 /// really is a credential this token lacks.
1917 ///
1918 /// A response is a refusal because of its status or its own wording. A spent budget
1919 /// only ever explains one; it never turns an answer into a refusal.
1920 fn classify(status: StatusCode, budget_exhausted: bool, body: &str) -> Option<Self> {
1921 let normalized = refusal_wording(status, body).to_ascii_lowercase();
1922 if SECONDARY_WORDINGS
1923 .iter()
1924 .any(|wording| normalized.contains(wording))
1925 {
1926 return Some(Self::Secondary);
1927 }
1928 if status == StatusCode::TOO_MANY_REQUESTS {
1929 return Some(Self::Primary);
1930 }
1931 // An exhausted budget *explains* a response that failed; it does not make one that
1932 // succeeded into a failure. GitHub sets `x-ratelimit-remaining: 0` on the last
1933 // request the budget allowed as well as on the ones it then refuses, so reading
1934 // the header alone threw away a good answer — and, once refusals were retried,
1935 // replayed a request that had already taken effect.
1936 if !status.is_success() && budget_exhausted {
1937 return Some(Self::Primary);
1938 }
1939 // A successful response saying it: GitHub reports a GraphQL rate limit in the
1940 // `errors` of an HTTP 200, where nothing about the status says so at all.
1941 if status.is_success()
1942 && PRIMARY_WORDINGS
1943 .iter()
1944 .any(|wording| normalized.contains(wording))
1945 {
1946 return Some(Self::Primary);
1947 }
1948 None
1949 }
1950
1951 /// What this limiter is called where an operator can look it up.
1952 const fn name(self) -> &'static str {
1953 match self {
1954 Self::Primary => "GitHub's primary API rate limit",
1955 Self::Secondary => "GitHub's secondary rate limit",
1956 }
1957 }
1958
1959 /// What the endpoint an operator would go and check says about this limiter.
1960 const fn where_to_look(self) -> &'static str {
1961 match self {
1962 Self::Primary => {
1963 "That is the budget `gh api rate_limit` reports, so that endpoint says when it \
1964 comes back."
1965 }
1966 Self::Secondary => {
1967 "That limiter is not the primary API budget: `gh api rate_limit` reports the \
1968 primary budget and does not report this one, so budget showing there says \
1969 nothing about this refusal, and every further attempt extends it."
1970 }
1971 }
1972 }
1973
1974 /// The next step this limiter actually calls for.
1975 const fn what_to_do(self) -> &'static str {
1976 match self {
1977 Self::Primary => {
1978 "wait for the reset `gh api rate_limit` reports, then run the command again."
1979 }
1980 Self::Secondary => {
1981 "leave this board alone for a few minutes, then run the command again — or \
1982 raise pacing.min_mutation_interval_ms on this source so it writes more slowly."
1983 }
1984 }
1985 }
1986}
1987
1988/// One rate-limit refusal, and the wait GitHub asked for if it asked for one.
1989#[derive(Debug, Clone, Copy)]
1990struct Limited {
1991 limiter: Limiter,
1992 hint: Option<u64>,
1993}
1994
1995impl Limited {
1996 /// What the caller is told once this source has waited as long as it may.
1997 ///
1998 /// Both limiters report as [`SourceError::RateLimited`], because that is what
1999 /// happened: the kind a caller matches on says a rate limit refused this, and nothing
2000 /// about *which* limiter it was makes it a different kind of failure. What differs is
2001 /// the operator's next step, and that is what the message carries — a secondary
2002 /// refusal read as a primary one sends an operator to `gh api rate_limit`, where the
2003 /// budget looks fine, and then back to retry the very burst that was refused.
2004 fn exhausted(
2005 self,
2006 doing: &str,
2007 waits: u32,
2008 waited: Duration,
2009 needed: Duration,
2010 budget: Duration,
2011 ) -> SourceError {
2012 SourceError::RateLimited {
2013 retry_after_seconds: self.hint,
2014 message: Some(format!(
2015 "{} refused this source while {doing}; it waited {} out over {} and was refused \
2016 again, and the next wait of {} would take it past the {} one call may spend \
2017 waiting. {} next: {}",
2018 self.limiter.name(),
2019 plural(waits, "refusal"),
2020 seconds(waited),
2021 seconds(needed),
2022 seconds(budget),
2023 self.limiter.where_to_look(),
2024 self.limiter.what_to_do(),
2025 )),
2026 }
2027 }
2028}
2029
2030/// One HTTP attempt's result, with what its response said about the rate limit.
2031///
2032/// The two travel together so the record and the outcome are written from the same place:
2033/// what a response said about the budget is only readable while that response is in hand,
2034/// and what the attempt *meant* is only decidable once its body has been read.
2035struct Attempted {
2036 result: Result<Value, Attempt>,
2037 limits: accounting::RateLimit,
2038 /// GitHub's own reported cost for this call, for a document that asked for it.
2039 reported_cost: Option<u64>,
2040 response_outcome: accounting::ResponseOutcome,
2041}
2042
2043/// One attempt's outcome: an error to report, or a rate limit to wait out.
2044enum Attempt {
2045 Failed(SourceError),
2046 Limited(Limited),
2047}
2048
2049fn plural(count: u32, thing: &str) -> String {
2050 if count == 1 {
2051 format!("{count} {thing}")
2052 } else {
2053 format!("{count} {thing}s")
2054 }
2055}
2056
2057fn seconds(duration: Duration) -> String {
2058 format!("{:.1}s", duration.as_secs_f64())
2059}
2060
2061/// The member [`stamp_served`] writes onto every node of a response that says when it last
2062/// changed: the `Date` that response was served at. No GitHub type has a field of this name.
2063const SERVED_AT: &str = "onetaskgraphServedAt";
2064
2065/// Write `served` onto every object of `data` carrying an `updatedAt`, so whatever reads a
2066/// node's time later knows the server's clock on the response that read it — which is what
2067/// decides whether that node's change token is given (see [`change_token::SETTLED`]).
2068fn stamp_served(data: &mut Value, served: &str) {
2069 match data {
2070 Value::Object(members) => {
2071 if members.contains_key("updatedAt") {
2072 members.insert(SERVED_AT.to_owned(), Value::String(served.to_owned()));
2073 }
2074 for member in members.values_mut() {
2075 stamp_served(member, served);
2076 }
2077 }
2078 Value::Array(items) => {
2079 for item in items {
2080 stamp_served(item, served);
2081 }
2082 }
2083 _ => {}
2084 }
2085}
2086
2087/// A header GitHub spells as a whole number of seconds, or `None` when this one is not.
2088///
2089/// A value that is present and unreadable is deliberately *not* an error. `retry-after` is
2090/// allowed by HTTP to be a date rather than a count, an intermediary can rewrite either
2091/// header, and neither is what makes a response a refusal — so the whole cost of one this
2092/// cannot read is that the refusal carries no hint and the backing-off schedule answers it
2093/// instead. Refusing the response over the header would turn a readable refusal into an
2094/// unreadable one, and refusing to *wait* would be the one wrong direction to fail in.
2095fn whole_seconds(value: Option<&reqwest::header::HeaderValue>) -> Option<u64> {
2096 value
2097 .and_then(|value| value.to_str().ok())
2098 .and_then(|value| value.trim().parse::<u64>().ok())
2099}
2100
2101/// Every mutation this source sends creates content — an issue, a board item, a field of
2102/// one, a sub-issue link, a dependency, a comment — or edits or removes content of that
2103/// kind, and no query in [`graphql::DOCUMENTS`] does, so what the secondary limiter counts
2104/// and what the keyword says are the same set. That is what makes the keyword a sound test
2105/// rather than a convenient one: pacing an edit or a removal the limiter might not have
2106/// counted costs a wait, and not pacing one it did count costs the next fifty minutes.
2107fn is_mutation(query: &str) -> bool {
2108 query.trim_start().starts_with("mutation")
2109}
2110
2111/// What this source was doing, for a diagnostic that has to say so.
2112///
2113/// Read out of [`graphql::DOCUMENTS`], which is the inventory rather than a copy of it, so
2114/// a document added without a description is caught by that list's own gate instead of
2115/// falling through to the vague arm below.
2116fn operation_description(query: &str) -> &'static str {
2117 graphql::DOCUMENTS
2118 .iter()
2119 .find(|(document, _)| *document == query)
2120 .map_or("talking to GitHub", |(_, doing)| *doing)
2121}
2122
2123/// GitHub's published ceiling on content-generating requests, per minute.
2124///
2125/// Pinned in `tests/fixtures/rate-limits.json` and gated against it, because it is
2126/// GitHub's number rather than this source's: [`MIN_MUTATION_INTERVAL_MS`] is *derived*
2127/// from it, so a pacing value checked only against itself cannot go stale here.
2128pub const CONTENT_CREATION_PER_MINUTE: u64 = 80;
2129/// The same ceiling as GitHub publishes it per hour, which this source does **not** pace
2130/// at. See [`MIN_MUTATION_INTERVAL_MS`] for why the per-minute bound is the one that
2131/// governs; it is pinned beside its sibling so the gate would notice either one moving.
2132pub const CONTENT_CREATION_PER_HOUR: u64 = 500;
2133/// Shortest interval between two content-creating mutations, in milliseconds.
2134///
2135/// GitHub documents two secondary limits on content-generating requests:
2136/// [`CONTENT_CREATION_PER_MINUTE`] and [`CONTENT_CREATION_PER_HOUR`]. 60000/80 is 750, so
2137/// a mutation every 750 ms is the fastest rate that cannot exceed the per-minute bound,
2138/// and that is the bound a copy actually trips: a copy of one plan-sized project is a
2139/// burst of a few dozen mutations inside a few seconds. The hourly bound works out at one
2140/// every 7.2 seconds sustained, which no single copy reaches and which, used as the
2141/// spacing here, would turn an ordinary copy into an hour of waiting — so it is
2142/// deliberately *not* what this paces at. An installation that wants the hourly bound
2143/// honoured for a long sequence of copies says so through
2144/// `pacing.min_mutation_interval_ms`.
2145pub const MIN_MUTATION_INTERVAL_MS: u64 = 60_000 / CONTENT_CREATION_PER_MINUTE;
2146/// First wait when a rate-limit refusal carries no hint; each further wait doubles it.
2147///
2148/// A doubling schedule from one second reaches a minute in six waits, which is GitHub's
2149/// own advice for a secondary limit — wait, and wait longer each time — without spending
2150/// the first minute of a transient refusal doing nothing.
2151pub const RETRY_BACKOFF_MS: u64 = 1_000;
2152/// Total time one call may spend waiting out rate limits before it reports a failure.
2153///
2154/// Two minutes is long enough to ride out the refusals a paced copy still collects and
2155/// short enough that a command an operator is watching returns. The bound is what makes
2156/// the wait a wait rather than a hang: a call refused past it ends in a diagnostic naming
2157/// the limiter, not in a process nobody can tell from a wedged one.
2158pub const RETRY_BUDGET_MS: u64 = 120_000;
2159
2160fn default_token_env() -> String {
2161 "GH_PROJECTS_TOKEN".to_owned()
2162}
2163fn default_endpoint() -> String {
2164 "https://api.github.com/graphql".to_owned()
2165}
2166
2167/// The name of a `Status` single-select option on the board.
2168///
2169/// Validated on the way in rather than checked later, so a blank option name — which
2170/// nothing on a board can be — is a state this type cannot hold.
2171#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2172#[serde(try_from = "String")]
2173#[schemars(extend("minLength" = 1))]
2174pub struct ColumnName(String);
2175
2176impl ColumnName {
2177 /// The option name, as the board spells it.
2178 fn as_str(&self) -> &str {
2179 &self.0
2180 }
2181}
2182
2183impl TryFrom<String> for ColumnName {
2184 type Error = String;
2185
2186 fn try_from(name: String) -> Result<Self, Self::Error> {
2187 if name.trim().is_empty() {
2188 return Err("a status_mapping option name cannot be blank".to_owned());
2189 }
2190 Ok(Self(name))
2191 }
2192}
2193
2194/// The two closed states this product can mean.
2195///
2196/// GitHub's `IssueClosedStateReason` also spells `DUPLICATE`, which nothing here ever writes:
2197/// an issue closed as one *reads* `cancelled`, because its work is another issue's, but this
2198/// product never decides on a person's behalf that two issues are the same work.
2199#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, schemars::JsonSchema)]
2200#[serde(rename_all = "kebab-case")]
2201pub enum ClosedState {
2202 /// `COMPLETED` — precisely done.
2203 Completed,
2204 /// `NOT_PLANNED` — precisely cancelled.
2205 NotPlanned,
2206}
2207
2208impl ClosedState {
2209 const fn reason(self) -> &'static str {
2210 match self {
2211 Self::Completed => "COMPLETED",
2212 Self::NotPlanned => "NOT_PLANNED",
2213 }
2214 }
2215}
2216
2217/// Configuration for one GitHub Projects v2 board.
2218///
2219/// It serializes to a document this same type reads back as itself, so a caller writing a
2220/// configuration — a consumer filing onto a board it configures — can build one here rather
2221/// than spell the shape again; an empty `metadata_fields` is left out, as one never set.
2222#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2223#[serde(default, deny_unknown_fields)]
2224pub struct GitHubProjectsConfig {
2225 /// Login of the user or organization which owns the board.
2226 pub owner: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates GitHub's owner grammar before private construction.
2227 /// The project number shown in the board's GitHub URL.
2228 pub project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` bounds this to a positive GraphQL Int.
2229 // llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] This doc is the field's schema description, which is what a person configuring the source reads, so it has to say when the field decides an issue's repository and when the item's own field does; the rule's one executable source is `GitHubProjectsSource::creation_target`, and `tests/plugin.rs` drives each case named here against the loopback board.
2230 /// `owner/name` of the repository this source creates an issue in when the item's own
2231 /// `repositories` field does not decide it.
2232 ///
2233 /// An item naming exactly one repository is created there; a task or a document naming
2234 /// none or several is created in its parent project's repository; and a project, or a
2235 /// task or document with no parent, naming none or several is created here. A board
2236 /// has no repository of its own and `createIssue` requires one, so a write without
2237 /// this is refused naming the field. Reads never need it.
2238 pub repository: Option<String>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the `owner/name` grammar before private construction.
2239 // llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
2240 /// Environment variable containing a fine-grained token with Projects and Issues
2241 /// read/write plus Pull requests read-only access for every repository represented on
2242 /// the board.
2243 #[serde(default = "default_token_env")]
2244 pub token_env: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the environment-variable grammar.
2245 /// GraphQL endpoint. GitHub Enterprise installations may override it.
2246 #[serde(default = "default_endpoint")]
2247 pub endpoint: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` converts it to the private validated `Url`.
2248 /// Per-instance mapping from a status category to the option of the board's one
2249 /// `Status` field it lands on, for a task and for a project.
2250 ///
2251 /// The shared `StatusMapping` grammar: each value is one option name for both kinds,
2252 /// `null` to disable the category for both, or `{task, project}` naming it per kind,
2253 /// where a kind left out leaves the category unmapped for that kind. A category this
2254 /// does not mention keeps its shipped default for both kinds: `backlog` to "Backlog",
2255 /// `todo` to "Todo", `queued` to "Queued", `in-progress` to "In Progress", `done` to
2256 /// "Done" plus closed as completed, `cancelled` to "Cancelled" plus closed as not
2257 /// planned, and `draft` and `unknown` unmapped. A category it does mention gets no
2258 /// shipped default for a kind it leaves out. `done` and `cancelled` close the issue for
2259 /// either kind. No two categories may name one option for the same kind, ignoring case.
2260 /// `unknown` may name one existing option; every unknown word then lands on it and
2261 /// reads back as `unknown` under its name. Unlike `local-md`, this source cannot keep
2262 /// each unknown word because it never creates board options.
2263 #[serde(default)]
2264 pub status_mapping: StatusMapping,
2265 /// Per-instance mapping from a task's priority to an option of this board's
2266 /// single-select field named `Priority`.
2267 ///
2268 /// Absent, this source holds no priority: every task reads as `none`, and a write of any
2269 /// other priority is refused before it reaches this board. Present, each of `urgent`,
2270 /// `high`, `medium` and `low` it does not mention keeps its shipped default — `Urgent`,
2271 /// `High`, `Medium` and `Low` — and an item with no value in the `Priority` field reads
2272 /// as `none`, so writing `none` clears the value. Option names match case-insensitively;
2273 /// no two levels may name one option. Reads and writes never create the field or an
2274 /// option: `onetaskgraph sources fields <source> --apply` does, and a write naming one
2275 /// the board lacks is refused pointing there.
2276 #[serde(default)]
2277 pub priority_mapping: Option<PriorityMappingConfig>,
2278 /// Caller metadata values this source also writes to board text fields, so the board can
2279 /// filter on them.
2280 ///
2281 /// Absent or empty, nothing is projected. Each entry names a board text `field`, a
2282 /// top-level metadata `key` and an optional `path` of object keys walked inside that key's
2283 /// value. On every item write — create, update and copy, of a task, a project or a
2284 /// document — a string found there is written to the field, and nothing is sent when the
2285 /// field already holds it; nothing there, or `null`, clears the field when it holds a
2286 /// value; any other JSON type is refused before any mutation. The metadata comment in the
2287 /// issue body stays the one home of the value, and every read reports metadata from it.
2288 /// Reads and writes never create the field: `onetaskgraph sources fields <source>
2289 /// --apply` does, as a text field, and a write to a board lacking it, or holding a
2290 /// non-text field of that name, is refused pointing there.
2291 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2292 // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
2293 // list out, so both SDKs model an absent list as an empty one rather than as `null`.
2294 #[schemars(!skip_serializing_if)]
2295 pub metadata_fields: Vec<MetadataFieldConfig>,
2296 /// How fast this source writes, and how long it waits out a rate-limit refusal.
2297 ///
2298 /// Every field keeps its shipped default when it is absent, and the defaults are
2299 /// GitHub's own published limits rather than taste. See [`Pacing`].
2300 #[serde(default)]
2301 pub pacing: PacingConfig,
2302}
2303
2304/// Which option of the board's `Priority` field each priority lands on.
2305///
2306/// One member per level rather than a map, so a key that is not a level is refused where
2307/// the configuration is read, naming the levels there are. `none` is not a member: it is no
2308/// value in the field, not an option of it.
2309#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2310#[serde(default, deny_unknown_fields)]
2311pub struct PriorityMappingConfig {
2312 /// The option `urgent` lands on; `Urgent` when absent.
2313 pub urgent: Option<PriorityOptionName>,
2314 /// The option `high` lands on; `High` when absent.
2315 pub high: Option<PriorityOptionName>,
2316 /// The option `medium` lands on; `Medium` when absent.
2317 pub medium: Option<PriorityOptionName>,
2318 /// The option `low` lands on; `Low` when absent.
2319 pub low: Option<PriorityOptionName>,
2320}
2321
2322/// The name of an option of the board's `Priority` single-select field.
2323///
2324/// Validated on the way in, for the reason [`ColumnName`] is: nothing on a board can have a
2325/// blank name.
2326#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2327#[serde(try_from = "String")]
2328#[schemars(extend("minLength" = 1))]
2329pub struct PriorityOptionName(String);
2330
2331impl PriorityOptionName {
2332 /// The option name, as the board spells it.
2333 fn as_str(&self) -> &str {
2334 &self.0
2335 }
2336}
2337
2338impl TryFrom<String> for PriorityOptionName {
2339 type Error = String;
2340
2341 fn try_from(name: String) -> Result<Self, Self::Error> {
2342 if name.trim().is_empty() {
2343 return Err("a priority_mapping option name cannot be blank".to_owned());
2344 }
2345 Ok(Self(name))
2346 }
2347}
2348
2349/// The name of the board field a priority is held in.
2350pub const PRIORITY_FIELD: &str = "Priority";
2351
2352/// The four priorities a board option can hold, in the order a new `Priority` field lists
2353/// them. `none` is not among them: it is the field holding no value.
2354///
2355/// This list mirrors `Priority`, so it carries its own drift gate, in the shape [`CATEGORIES`]
2356/// does: [`level_position`] is a wildcard-free match, so a priority added to the shared
2357/// vocabulary fails to compile until it is placed there, and this crate's suite reconciles
2358/// this list and [`PriorityMappingConfig`]'s members against that enum's own derived schema.
2359pub const PRIORITY_LEVELS: [Priority; 4] = [
2360 Priority::Urgent,
2361 Priority::High,
2362 Priority::Medium,
2363 Priority::Low,
2364];
2365
2366/// Where one priority sits in [`PRIORITY_LEVELS`], or `None` for `none`, which is no option;
2367/// see that list for what this pins.
2368#[must_use]
2369pub const fn level_position(priority: Priority) -> Option<usize> {
2370 match priority {
2371 Priority::None => None,
2372 Priority::Urgent => Some(0),
2373 Priority::High => Some(1),
2374 Priority::Medium => Some(2),
2375 Priority::Low => Some(3),
2376 }
2377}
2378
2379/// This instance's complete priority-to-option mapping, read in both directions.
2380///
2381/// One option per level, held in [`PRIORITY_LEVELS`] order, once it is established that no
2382/// two levels name one option.
2383#[derive(Debug, Clone)]
2384struct PriorityMapping {
2385 options: [PriorityOptionName; 4],
2386}
2387
2388impl PriorityMapping {
2389 fn resolve(config: PriorityMappingConfig, instance: &SourceName) -> Result<Self, SourceError> {
2390 let shipped = |name: &str| PriorityOptionName(name.to_owned());
2391 let mapping = Self {
2392 options: [
2393 config.urgent.unwrap_or_else(|| shipped("Urgent")),
2394 config.high.unwrap_or_else(|| shipped("High")),
2395 config.medium.unwrap_or_else(|| shipped("Medium")),
2396 config.low.unwrap_or_else(|| shipped("Low")),
2397 ],
2398 };
2399 for (index, option) in mapping.options.iter().enumerate() {
2400 if let Some(earlier) = mapping.options[..index]
2401 .iter()
2402 .position(|other| other.as_str().eq_ignore_ascii_case(option.as_str()))
2403 {
2404 return Err(SourceError::Config {
2405 message: format!(
2406 "priority_mapping of source {instance} sends both {} and {} to the board \
2407 option {:?}; one option cannot read back as two priorities",
2408 PRIORITY_LEVELS[earlier],
2409 PRIORITY_LEVELS[index],
2410 option.as_str()
2411 ),
2412 });
2413 }
2414 }
2415 Ok(mapping)
2416 }
2417
2418 /// The option `priority` lands on, or `None` for `none`, which is no option at all.
2419 fn option(&self, priority: Priority) -> Option<&str> {
2420 level_position(priority).map(|index| self.options[index].as_str())
2421 }
2422
2423 /// The priority a board option name reports, or `None` when nothing maps to it.
2424 fn priority_of(&self, option: &str) -> Option<Priority> {
2425 self.options
2426 .iter()
2427 .position(|name| name.as_str().eq_ignore_ascii_case(option))
2428 .map(|index| PRIORITY_LEVELS[index])
2429 }
2430
2431 /// Every mapped option name, in the order a new `Priority` field lists them.
2432 fn names(&self) -> impl Iterator<Item = &str> {
2433 self.options.iter().map(PriorityOptionName::as_str)
2434 }
2435}
2436
2437/// One metadata value this source projects onto a board text field.
2438#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2439#[serde(deny_unknown_fields)]
2440pub struct MetadataFieldConfig {
2441 /// The name of the board text field the value is written to.
2442 pub field: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `MetadataField::resolve` refuses a blank, reserved, GitHub-owned or repeated name before the private validated entry is built.
2443 /// The top-level metadata key the value is read from. A key under the reserved
2444 /// `onetaskgraph.` prefix is refused.
2445 pub key: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `MetadataField::resolve` refuses a blank or reserved key before the private validated entry is built.
2446 /// Object keys walked inside that key's value, outermost first. Absent or empty, the
2447 /// key's own value is the one projected. Left out of a serialized entry when empty.
2448 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2449 // Kept in the schema as `"default": []`, for the reason `metadata_fields`' is.
2450 #[schemars(!skip_serializing_if)]
2451 pub path: Vec<String>,
2452}
2453
2454/// The board fields no metadata value may be projected onto, compared ignoring case: the
2455/// three this source writes itself, and those GitHub owns on every board.
2456// llmlint: ignore[contracts_have_one_source_or_a_drift_gate] This list is the configuration contract `metadata_fields`' consumers agreed, refused at read so a mistaken entry is named early — not a mirror GitHub's field set has to stay in step with. What keeps a write off a field GitHub owns is the write's own check, `projection_field`, which refuses any field whose `dataType` is not `TEXT`: every built-in board field reports its own type (TITLE, ASSIGNEES, LABELS, …), and the live contract introspection holds GitHub to `ProjectV2Field.dataType`. So a built-in field GitHub adds later and this list lacks is still never written.
2457const UNPROJECTABLE_FIELDS: [&str; 13] = [
2458 STATUS_FIELD,
2459 PRIORITY_FIELD,
2460 ORIGIN_FIELD,
2461 "Title",
2462 "Assignees",
2463 "Labels",
2464 "Linked pull requests",
2465 "Milestone",
2466 "Repository",
2467 "Reviewers",
2468 "Parent issue",
2469 "Sub-issues progress",
2470 "Type",
2471];
2472
2473/// One validated [`MetadataFieldConfig`] entry.
2474#[derive(Debug, Clone)]
2475struct MetadataField {
2476 field: ProjectedField,
2477 key: ProjectedKey,
2478 path: Vec<String>,
2479}
2480
2481/// The name of a board text field a metadata value is projected onto: never blank, never one
2482/// this source or GitHub writes, and never one another entry of the same source names.
2483#[derive(Debug, Clone, PartialEq, Eq)]
2484struct ProjectedField(String);
2485
2486/// The top-level metadata key a projected value is read from: never blank, and never under
2487/// the namespace this product reserves.
2488#[derive(Debug, Clone, PartialEq, Eq)]
2489struct ProjectedKey(String);
2490
2491impl std::ops::Deref for ProjectedField {
2492 type Target = str;
2493 fn deref(&self) -> &str {
2494 &self.0
2495 }
2496}
2497
2498impl std::ops::Deref for ProjectedKey {
2499 type Target = str;
2500 fn deref(&self) -> &str {
2501 &self.0
2502 }
2503}
2504
2505/// What one item's metadata says one projected field should hold.
2506#[derive(Debug, Clone, PartialEq, Eq)]
2507enum Projected {
2508 /// A string to hold.
2509 Text(String),
2510 /// Nothing: the key or a step of the path is absent, or the value is `null`.
2511 Nothing,
2512}
2513
2514impl MetadataField {
2515 /// Validate every entry of one instance's `metadata_fields`, refusing the first that
2516 /// cannot stand, naming the source and the entry.
2517 fn resolve(
2518 configured: Vec<MetadataFieldConfig>,
2519 instance: &SourceName,
2520 ) -> Result<Vec<Self>, SourceError> {
2521 let mut resolved: Vec<Self> = Vec::with_capacity(configured.len());
2522 for (index, entry) in configured.into_iter().enumerate() {
2523 let refuse = |why: String| SourceError::Config {
2524 message: format!(
2525 "metadata_fields[{index}] of source {instance} (field {:?}, key {:?}) {why}",
2526 entry.field, entry.key
2527 ),
2528 };
2529 if entry.field.trim().is_empty() {
2530 return Err(refuse("names a blank field".to_owned()));
2531 }
2532 if entry.key.trim().is_empty() {
2533 return Err(refuse("names a blank key".to_owned()));
2534 }
2535 if entry.key.split('.').next() == Some(MetadataKey::RESERVED_NAMESPACE) {
2536 return Err(refuse(format!(
2537 "names a key under the reserved \"{}.\" prefix, which this product keeps \
2538 for its own keys; next: project a caller key instead",
2539 MetadataKey::RESERVED_NAMESPACE
2540 )));
2541 }
2542 if let Some(owned) = UNPROJECTABLE_FIELDS
2543 .iter()
2544 .find(|owned| owned.eq_ignore_ascii_case(&entry.field))
2545 {
2546 return Err(refuse(format!(
2547 "names the board field {owned:?}, which this source or GitHub already \
2548 writes; next: name a text field of your own"
2549 )));
2550 }
2551 if let Some(earlier) = resolved
2552 .iter()
2553 .position(|other| other.field.eq_ignore_ascii_case(&entry.field))
2554 {
2555 return Err(refuse(format!(
2556 "names the same board field as metadata_fields[{earlier}]; one field \
2557 cannot hold two values"
2558 )));
2559 }
2560 resolved.push(Self {
2561 field: ProjectedField(entry.field),
2562 key: ProjectedKey(entry.key),
2563 path: entry.path,
2564 });
2565 }
2566 Ok(resolved)
2567 }
2568
2569 /// The path as a refusal spells it: `[]` for the key's own value.
2570 fn spelled_path(&self) -> String {
2571 serde_json::to_string(&self.path).unwrap_or_else(|_| format!("{:?}", self.path))
2572 }
2573
2574 /// What `metadata` says this field should hold, or the refusal for a value no text field
2575 /// can hold.
2576 fn projected(
2577 &self,
2578 metadata: &BTreeMap<String, Value>,
2579 instance: &SourceName,
2580 ) -> Result<Projected, SourceError> {
2581 let mut value = metadata.get(&*self.key);
2582 for step in &self.path {
2583 value = value.and_then(|held| held.get(step.as_str()));
2584 }
2585 let found = match value {
2586 None | Some(Value::Null) => return Ok(Projected::Nothing),
2587 Some(Value::String(text)) => return Ok(Projected::Text(text.clone())),
2588 Some(Value::Bool(_)) => "a boolean",
2589 Some(Value::Number(_)) => "a number",
2590 Some(Value::Array(_)) => "an array",
2591 Some(Value::Object(_)) => "an object",
2592 };
2593 Err(SourceError::Refused {
2594 message: format!(
2595 "source {instance} projects metadata key {:?} at path {} onto its board text \
2596 field {:?}, and this item holds {found} there; only a string, null or nothing \
2597 can be written to a text field; next: store a string there, or remove the \
2598 value",
2599 &*self.key,
2600 self.spelled_path(),
2601 &*self.field
2602 ),
2603 })
2604 }
2605}
2606
2607/// What one item's `Priority` field says, read through this instance's mapping.
2608#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
2609enum HeldPriority {
2610 /// A priority this source reports: an option the mapping names, or no value (`none`).
2611 Read(Priority),
2612 /// An option the mapping does not name, which is never read as a level or as `none`.
2613 Unmapped(String),
2614}
2615
2616/// How fast this source writes, and how long it waits out a rate-limit refusal.
2617///
2618/// Configurable because a GitHub Enterprise installation sets its own limits and an
2619/// operator who has already been refused may want to go slower still — not because the
2620/// defaults are guesses.
2621#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2622#[serde(default, deny_unknown_fields)]
2623pub struct PacingConfig {
2624 /// Shortest interval between two content-creating mutations, in milliseconds.
2625 ///
2626 /// Zero sends them as fast as they are asked for, which is what a fixture server on
2627 /// loopback wants and what no board on github.com does. At most [`MAX_PACING_MS`].
2628 pub min_mutation_interval_ms: Option<u64>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `Pacing::resolve` bounds it to `MAX_PACING_MS` before the private validated `Pacing` is built.
2629 /// First wait when a rate-limit refusal carries no hint, in milliseconds. Each
2630 /// further wait of the same call doubles it. At most [`MAX_PACING_MS`], and never
2631 /// zero while there is a budget to spend, because a schedule of zero-length waits
2632 /// consumes none of it and so never ends.
2633 pub retry_backoff_ms: Option<u64>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `Pacing::resolve` refuses a non-progressing zero and bounds the rest before the private validated `Pacing` is built.
2634 /// Total time one call may spend waiting out rate limits, in milliseconds.
2635 ///
2636 /// Zero reports the refusal rather than waiting at all. At most [`MAX_PACING_MS`]:
2637 /// the bound is what makes this a wait rather than a hang.
2638 pub retry_budget_ms: Option<u64>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `Pacing::resolve` bounds it to `MAX_PACING_MS` before the private validated `Pacing` is built.
2639}
2640
2641/// The largest any pacing setting may be, in milliseconds.
2642///
2643/// One hour. GitHub's own harshest published bound on content-generating requests works
2644/// out at one every 7.2 seconds, so an hour is already three orders of magnitude past
2645/// anything a real limit asks for, and past it the settings stop describing pacing at all:
2646/// a wait budget beyond it is the unbounded wait this whole mechanism exists to replace,
2647/// and an interval beyond it is a command that never sends its second mutation. It also
2648/// keeps the clock arithmetic in [`GitHubProjectsSource::reserve_mutation_slot`] inside
2649/// what a `Duration` can hold on every platform.
2650pub const MAX_PACING_MS: u64 = 3_600_000;
2651
2652/// [`PacingConfig`] with every default resolved and every value checked, which is what the
2653/// source holds.
2654#[derive(Debug, Clone, Copy)]
2655struct Pacing {
2656 min_mutation_interval: Duration,
2657 retry_backoff: Duration,
2658 retry_budget: Duration,
2659}
2660
2661impl Pacing {
2662 /// Resolve one instance's pacing, refusing a configuration that would not pace at all.
2663 fn resolve(config: PacingConfig, instance: &SourceName) -> Result<Self, SourceError> {
2664 let bounded = |value: Option<u64>, default: u64, field: &str| match value {
2665 Some(value) if value > MAX_PACING_MS => Err(SourceError::Config {
2666 message: format!(
2667 "pacing.{field} of source {instance} is {value} ms, and the most any pacing \
2668 setting may be is {MAX_PACING_MS} ms — an hour, which is already far past \
2669 GitHub's own harshest published limit"
2670 ),
2671 }),
2672 Some(value) => Ok(Duration::from_millis(value)),
2673 None => Ok(Duration::from_millis(default)),
2674 };
2675 let retry_backoff = bounded(
2676 config.retry_backoff_ms,
2677 RETRY_BACKOFF_MS,
2678 "retry_backoff_ms",
2679 )?;
2680 let retry_budget = bounded(config.retry_budget_ms, RETRY_BUDGET_MS, "retry_budget_ms")?;
2681 if retry_backoff.is_zero() && !retry_budget.is_zero() {
2682 return Err(SourceError::Config {
2683 message: format!(
2684 "pacing.retry_backoff_ms of source {instance} is 0 while \
2685 pacing.retry_budget_ms is {} ms; a schedule of zero-length waits spends \
2686 none of that budget, so it would retry a refusal forever. Set a backoff of \
2687 at least 1 ms, or set retry_budget_ms to 0 to report a refusal without \
2688 waiting at all",
2689 retry_budget.as_millis()
2690 ),
2691 });
2692 }
2693 Ok(Self {
2694 min_mutation_interval: bounded(
2695 config.min_mutation_interval_ms,
2696 MIN_MUTATION_INTERVAL_MS,
2697 "min_mutation_interval_ms",
2698 )?,
2699 retry_backoff,
2700 retry_budget,
2701 })
2702 }
2703}
2704
2705/// Factory for [`GitHubProjectsSource`].
2706#[derive(Debug, Clone, Copy, Default)]
2707pub struct Plugin;
2708
2709impl SourcePlugin for Plugin {
2710 fn kind(&self) -> &'static str {
2711 KIND
2712 }
2713 /// The endpoint, the owner and the board's number: what names one board.
2714 fn remote_identity(&self, config: &Value) -> Option<String> {
2715 let config: GitHubProjectsConfig = serde_json::from_value(config.clone()).ok()?;
2716 Some(format!(
2717 "{}\n{}\n{}",
2718 config.endpoint, config.owner, config.project_number
2719 ))
2720 }
2721 fn config_schema(&self) -> Schema {
2722 schema_for!(GitHubProjectsConfig)
2723 }
2724 fn build(
2725 &self,
2726 name: &SourceName,
2727 config: &Value,
2728 secrets: &dyn SecretResolver,
2729 ) -> Result<Box<dyn TaskSource>, SourceError> {
2730 self.build_recording_into(name, config, secrets, Arc::new(Accounting::new()))
2731 }
2732
2733 fn build_with_clock(
2734 &self,
2735 name: &SourceName,
2736 config: &Value,
2737 secrets: &dyn SecretResolver,
2738 clock: SharedClock,
2739 ) -> Result<Box<dyn TaskSource>, SourceError> {
2740 self.build_recording_with_clock(name, config, secrets, Arc::new(Accounting::new()), clock)
2741 }
2742}
2743
2744impl Plugin {
2745 /// Build a source recording every request it sends into an accounting the caller holds.
2746 ///
2747 /// [`SourcePlugin::build`] is this with an accounting of its own, which is what the
2748 /// registry gets. This is for a caller that is also calling GitHub itself and wants one
2749 /// session total rather than two — see [`accounting`] and
2750 /// [`GitHubProjectsSource::recording_into`].
2751 ///
2752 /// # Errors
2753 ///
2754 /// Exactly [`SourcePlugin::build`]'s, with the same source name in front of each:
2755 /// [`SourceError::Config`] for configuration this plugin cannot use and
2756 /// [`SourceError::Auth`] for a credential it cannot find.
2757 pub fn build_recording_into(
2758 &self,
2759 name: &SourceName,
2760 config: &Value,
2761 secrets: &dyn SecretResolver,
2762 ledger: Arc<Accounting>,
2763 ) -> Result<Box<dyn TaskSource>, SourceError> {
2764 self.build_recording_with_clock(name, config, secrets, ledger, system_clock())
2765 }
2766
2767 fn build_recording_with_clock(
2768 &self,
2769 name: &SourceName,
2770 config: &Value,
2771 secrets: &dyn SecretResolver,
2772 ledger: Arc<Accounting>,
2773 clock: SharedClock,
2774 ) -> Result<Box<dyn TaskSource>, SourceError> {
2775 let config: GitHubProjectsConfig =
2776 serde_json::from_value(config.clone()).map_err(|e| SourceError::Config {
2777 message: format!("source {name}: {e}"),
2778 })?;
2779 let prefix = format!("source {name}: ");
2780 let mut source = GitHubProjectsSource::recording_into(name, config, secrets, ledger)
2781 .map_err(|error| match error {
2782 // The shared `StatusMapping::distinct` names the source itself.
2783 SourceError::Config { message } if message.starts_with(&prefix) => {
2784 SourceError::Config { message }
2785 }
2786 SourceError::Config { message } => SourceError::Config {
2787 message: format!("{prefix}{message}"),
2788 },
2789 SourceError::Auth { message } => SourceError::Auth {
2790 message: format!("source {name}: {message}"),
2791 },
2792 other => other,
2793 })?;
2794 source.clock = clock;
2795 Ok(Box::new(source))
2796 }
2797}
2798
2799/// Where a status category lands on this board, once configuration is resolved.
2800#[derive(Debug, Clone, PartialEq, Eq)]
2801enum StatusTarget {
2802 /// Not usable against this instance for this kind, and why.
2803 Disabled(UnmappedStatus),
2804 /// The board's `Status` option of this name.
2805 Column(ColumnName),
2806 /// A closed issue, with both its board option and the reason that says which closed it means.
2807 // llmlint: ignore[invalid_states_unrepresentable] The reason is fixed by the category — `done` closes as completed, `cancelled` as not planned — and this private enum is built in one place, `BoardStatuses::resolve`, which pairs each from the category's own slot. Carrying the reason on the target is what lets every write site that holds only a target derive its `stateInput` from that one resolved model rather than re-deriving it from a category and risking a disagreement with the mapping.
2808 Terminal(ColumnName, ClosedState),
2809}
2810
2811/// Every status category, in the order the vocabulary declares them.
2812///
2813/// This list mirrors `StatusCategory`, so it carries its own drift gate rather than a
2814/// reviewer's attention: [`category_position`] is a wildcard-free match, so a variant
2815/// added to the shared vocabulary fails to compile until it is named there, and this
2816/// crate's suite reconciles this list against that enum's own derived schema, which is
2817/// generated from the variants rather than written beside them. The schema is what
2818/// catches a list left one short — a list checking only the positions it already holds
2819/// would pass while every mapping indexed by the new position panicked.
2820pub const CATEGORIES: [StatusCategory; 8] = [
2821 StatusCategory::Draft,
2822 StatusCategory::Backlog,
2823 StatusCategory::Todo,
2824 StatusCategory::Queued,
2825 StatusCategory::InProgress,
2826 StatusCategory::Done,
2827 StatusCategory::Cancelled,
2828 StatusCategory::Unknown,
2829];
2830
2831/// Where one category sits in [`CATEGORIES`]; see that list for what this pins.
2832#[must_use]
2833pub const fn category_position(category: StatusCategory) -> usize {
2834 match category {
2835 StatusCategory::Draft => 0,
2836 StatusCategory::Backlog => 1,
2837 StatusCategory::Todo => 2,
2838 StatusCategory::Queued => 3,
2839 StatusCategory::InProgress => 4,
2840 StatusCategory::Done => 5,
2841 StatusCategory::Cancelled => 6,
2842 StatusCategory::Unknown => 7,
2843 }
2844}
2845
2846/// The spelling a status category is configured and reported under.
2847fn category_name(category: StatusCategory) -> &'static str {
2848 match category {
2849 StatusCategory::Draft => "draft",
2850 StatusCategory::Backlog => "backlog",
2851 StatusCategory::Todo => "todo",
2852 StatusCategory::Queued => "queued",
2853 StatusCategory::InProgress => "in-progress",
2854 StatusCategory::Done => "done",
2855 StatusCategory::Cancelled => "cancelled",
2856 StatusCategory::Unknown => "unknown",
2857 }
2858}
2859
2860/// A shipped default's option name.
2861///
2862/// The literals below are this file's own and non-blank, and they are validated by the
2863/// one constructor a configured name goes through rather than beside it.
2864fn shipped_column(name: &'static str) -> ColumnName {
2865 ColumnName::try_from(name.to_owned()).expect("a shipped default names a board option")
2866}
2867
2868/// The shipped default for one category this instance's `status_mapping` does not mention,
2869/// for either kind.
2870fn shipped_default(category: StatusCategory) -> StatusTarget {
2871 match category {
2872 StatusCategory::Backlog => StatusTarget::Column(shipped_column("Backlog")),
2873 StatusCategory::Todo => StatusTarget::Column(shipped_column("Todo")),
2874 StatusCategory::Queued => StatusTarget::Column(shipped_column("Queued")),
2875 StatusCategory::InProgress => StatusTarget::Column(shipped_column("In Progress")),
2876 StatusCategory::Done => {
2877 StatusTarget::Terminal(shipped_column("Done"), ClosedState::Completed)
2878 }
2879 StatusCategory::Cancelled => {
2880 StatusTarget::Terminal(shipped_column("Cancelled"), ClosedState::NotPlanned)
2881 }
2882 StatusCategory::Draft | StatusCategory::Unknown => {
2883 StatusTarget::Disabled(UnmappedStatus::Unconfigured)
2884 }
2885 }
2886}
2887
2888/// The two kinds a status is written and read for, each with its own half of the mapping.
2889const STATUS_KINDS: [ItemKind; 2] = [ItemKind::Task, ItemKind::Project];
2890
2891/// This instance's complete category-to-target mapping for each kind, read in both
2892/// directions.
2893///
2894/// One target per category per kind, held at that category's own [`category_position`], so
2895/// a category missing from the mapping, named twice in it, or filed out of order is a state
2896/// this type cannot hold rather than one [`Self::target`] has to defend against. Both kinds'
2897/// targets are options of the board's one `Status` field.
2898#[derive(Debug, Clone)]
2899struct BoardStatuses {
2900 tasks: [StatusTarget; CATEGORIES.len()],
2901 projects: [StatusTarget; CATEGORIES.len()],
2902}
2903
2904impl BoardStatuses {
2905 /// Resolve `configured` against the shipped defaults, refusing two categories one kind
2906 /// would read back from one option.
2907 ///
2908 /// A category the mapping does not mention keeps its shipped default for both kinds; one
2909 /// it does mention is exactly what it configures, so a per-kind object leaves the kind it
2910 /// omits unmapped rather than defaulted.
2911 fn resolve(configured: &StatusMapping, instance: &SourceName) -> Result<Self, SourceError> {
2912 let resolve_kind =
2913 |kind: ItemKind| -> Result<[StatusTarget; CATEGORIES.len()], SourceError> {
2914 // `CATEGORIES[position] == category` for every category — the crate's suite
2915 // asserts it — so mapping the list in order fills each category's own slot.
2916 let mut targets = CATEGORIES.map(shipped_default);
2917 for (slot, category) in targets.iter_mut().zip(CATEGORIES) {
2918 if !configured.mentions(category) {
2919 continue;
2920 }
2921 *slot = match configured.name_for(category, kind) {
2922 Err(why) => StatusTarget::Disabled(why),
2923 Ok(name) => {
2924 let option = ColumnName::try_from(name.as_str().to_owned())
2925 .map_err(|message| SourceError::Config { message })?;
2926 match category {
2927 StatusCategory::Done => {
2928 StatusTarget::Terminal(option, ClosedState::Completed)
2929 }
2930 StatusCategory::Cancelled => {
2931 StatusTarget::Terminal(option, ClosedState::NotPlanned)
2932 }
2933 _ => StatusTarget::Column(option),
2934 }
2935 }
2936 };
2937 }
2938 StatusMapping::distinct(
2939 instance,
2940 kind,
2941 CATEGORIES
2942 .iter()
2943 .zip(&targets)
2944 .filter_map(|(category, target)| target.option().map(|o| (*category, o))),
2945 )?;
2946 Ok(targets)
2947 };
2948 Ok(Self {
2949 tasks: resolve_kind(ItemKind::Task)?,
2950 projects: resolve_kind(ItemKind::Project)?,
2951 })
2952 }
2953
2954 /// Every category's target for `kind`, in category order.
2955 const fn targets(&self, kind: ItemKind) -> &[StatusTarget; CATEGORIES.len()] {
2956 match kind {
2957 ItemKind::Task => &self.tasks,
2958 ItemKind::Project => &self.projects,
2959 }
2960 }
2961
2962 fn target(&self, kind: ItemKind, category: StatusCategory) -> &StatusTarget {
2963 &self.targets(kind)[category_position(category)]
2964 }
2965
2966 /// The category a board option name reports for `kind`, or `None` when nothing of that
2967 /// kind maps to it.
2968 fn category_of(&self, kind: ItemKind, option: &str) -> Option<StatusCategory> {
2969 CATEGORIES.into_iter().find(|category| {
2970 self.target(kind, *category)
2971 .option()
2972 .is_some_and(|name| name.eq_ignore_ascii_case(option))
2973 })
2974 }
2975
2976 /// Every option name either kind maps a category to, each once ignoring case, in
2977 /// category order with a task's name before a project's — what the guarded setup asks
2978 /// the `Status` field to hold.
2979 fn wanted(&self) -> Vec<String> {
2980 let mut wanted: Vec<String> = Vec::new();
2981 for category in CATEGORIES {
2982 for kind in STATUS_KINDS {
2983 if let Some(name) = self.target(kind, category).option()
2984 && !wanted.iter().any(|held| held.eq_ignore_ascii_case(name))
2985 {
2986 wanted.push(name.to_owned());
2987 }
2988 }
2989 }
2990 wanted
2991 }
2992
2993 /// The status an item of `kind` reports, from the three things a read of it says: its
2994 /// board `Status` option, whether its issue is closed, and the reason it was closed with.
2995 ///
2996 /// **A closed issue's category follows its closure**, by [`closed_category`]: completed
2997 /// or no reason reads `done`, not planned and duplicate read `cancelled`, and any other
2998 /// reason reads `unknown`. `REOPENED`-while-closed is a state this source can never
2999 /// produce, so it is read permissively rather than refused — reads are faithful, and
3000 /// refusals belong on writes.
3001 ///
3002 /// **Its name follows the closure too, unless the option agrees with it.** The option's
3003 /// own name is kept when this kind's mapping reads that option as the same category, or
3004 /// does not name it at all — so a closed issue in a "Shipped" column reports `done`
3005 /// named `Shipped`. An option the mapping reads as another category contradicts the
3006 /// closure, and so does no option at all: the name is then the option the mapping gives
3007 /// the closure's category, so an issue closed as completed at `Todo` reads `done` named
3008 /// by the board's `done` option, and a destination reading `Todo` as todo is never handed
3009 /// it. An `unknown` closure keeps the option, or `Closed` without one.
3010 ///
3011 /// An open item's option reads through its own kind's mapping, and an option that mapping
3012 /// does not name reads as `Unknown` under its own name.
3013 ///
3014 /// One function of those three rather than of a response, so a narrow status write can
3015 /// answer what a re-read would report by applying it to the state it has just written.
3016 fn status(
3017 &self,
3018 kind: ItemKind,
3019 option: Option<&str>,
3020 closed: bool,
3021 reason: Option<&str>,
3022 ) -> Status {
3023 if closed {
3024 let category = closed_category(reason);
3025 let agrees = option.filter(|option| {
3026 category == StatusCategory::Unknown
3027 || self
3028 .category_of(kind, option)
3029 .is_none_or(|read| read == category)
3030 });
3031 let name = agrees.or_else(|| self.target(kind, category).option());
3032 let fallback = match category {
3033 StatusCategory::Done => "Done",
3034 StatusCategory::Cancelled => "Cancelled",
3035 _ => "Closed",
3036 };
3037 return Status {
3038 category,
3039 name: name.or(option).unwrap_or(fallback).to_owned(),
3040 };
3041 }
3042 let name = option.unwrap_or("Open").to_owned();
3043 Status {
3044 category: self
3045 .category_of(kind, &name)
3046 .unwrap_or(StatusCategory::Unknown),
3047 name,
3048 }
3049 }
3050
3051 /// The option a closed item's `Status` has to hold for its card to agree with its
3052 /// closure, and the category that closure reads as — or `None` when the item is open,
3053 /// its closure reads `unknown`, or its option already agrees.
3054 ///
3055 /// What `task status reconcile` writes: only `done` and `cancelled` closures are brought
3056 /// in line, each to the one option the mapping gives its category — an item with no
3057 /// option, or at one the mapping does not name, included.
3058 fn contradicted(
3059 &self,
3060 kind: ItemKind,
3061 option: Option<&str>,
3062 closed: bool,
3063 reason: Option<&str>,
3064 ) -> Option<(ClosedAs, &str)> {
3065 if !closed {
3066 return None;
3067 }
3068 let closed_as = match closed_category(reason) {
3069 StatusCategory::Done => ClosedAs::Done,
3070 StatusCategory::Cancelled => ClosedAs::Cancelled,
3071 _ => return None,
3072 };
3073 let wanted = self.target(kind, closed_as.category()).option()?;
3074 if option.is_some_and(|option| option.eq_ignore_ascii_case(wanted)) {
3075 return None;
3076 }
3077 Some((closed_as, wanted))
3078 }
3079}
3080
3081/// The category a closed issue reads as, from the reason it was closed with.
3082///
3083/// `COMPLETED`, and no reason at all, is finished work; `NOT_PLANNED` and `DUPLICATE` are both
3084/// work nobody will do here — a duplicate's work is the other issue's — and any other reason
3085/// is one this source cannot read a category from.
3086fn closed_category(reason: Option<&str>) -> StatusCategory {
3087 match reason {
3088 None | Some("COMPLETED") => StatusCategory::Done,
3089 Some("NOT_PLANNED" | "DUPLICATE") => StatusCategory::Cancelled,
3090 Some(_) => StatusCategory::Unknown,
3091 }
3092}
3093
3094impl BoardStatuses {
3095 /// For each kind, the option names it maps a category to that `existing` lacks, ignoring
3096 /// case; a kind lacking none is left out.
3097 fn missing_by_kind(&self, existing: &[StatusOption]) -> Vec<KindMissing> {
3098 STATUS_KINDS
3099 .into_iter()
3100 .filter_map(|kind| {
3101 let missing: Vec<String> = self
3102 .targets(kind)
3103 .iter()
3104 .filter_map(StatusTarget::option)
3105 .filter(|wanted| {
3106 !existing
3107 .iter()
3108 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
3109 })
3110 .map(str::to_owned)
3111 .collect();
3112 (!missing.is_empty()).then_some(KindMissing { kind, missing })
3113 })
3114 .collect()
3115 }
3116}
3117
3118impl StatusTarget {
3119 /// The board option this target selects, or `None` for an unmapped one.
3120 fn option(&self) -> Option<&str> {
3121 match self {
3122 Self::Column(name) | Self::Terminal(name, _) => Some(name.as_str()),
3123 Self::Disabled(_) => None,
3124 }
3125 }
3126}
3127
3128// llmlint: ignore-block[comments_earn_their_place, contracts_have_one_source_or_a_drift_gate] Every `createIssue` names one of these, and which one is the rule — a reader who reaches the type from `create_and_file_issue` gets the rule in one sentence here without the method's refusals, which stay on `creation_target`, the rule's one executable source; `tests/plugin.rs` drives every arm of it against the loopback board.
3129/// One repository this source can create an issue in, as `owner/name`.
3130///
3131/// Every `createIssue` this source sends names one of these: the item's own single
3132/// `repositories` entry, else its parent project issue's repository, else the configured
3133/// [`GitHubProjectsConfig::repository`]. [`GitHubProjectsSource::creation_target`] makes
3134/// that choice and says what it refuses before `createIssue`.
3135// llmlint: ignore-end[comments_earn_their_place, contracts_have_one_source_or_a_drift_gate]
3136#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
3137struct RepositoryTarget {
3138 owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
3139 name: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
3140}
3141
3142impl RepositoryTarget {
3143 fn parse(value: &str) -> Result<Self, SourceError> {
3144 let (owner, name) = value.split_once('/').ok_or_else(|| SourceError::Config {
3145 message: format!(
3146 "repository must be spelled owner/name; {value:?} names no repository"
3147 ),
3148 })?;
3149 if !valid_github_owner(owner) || !valid_github_repository_name(name) {
3150 return Err(SourceError::Config {
3151 message: format!(
3152 "repository must be spelled owner/name with a GitHub login and one \
3153 repository name; {value:?} is not"
3154 ),
3155 });
3156 }
3157 Ok(Self {
3158 owner: owner.to_owned(),
3159 name: name.to_owned(),
3160 })
3161 }
3162
3163 /// The one host whose repositories this source creates issues in, spelled once: it is
3164 /// what [`Self::origin`] renders and what [`Self::from_origin`] accepts.
3165 const HOST: &str = "github.com";
3166
3167 fn origin(&self) -> String {
3168 format!("{}/{}/{}", Self::HOST, self.owner, self.name)
3169 }
3170
3171 /// The repository a normalized origin names, or why it is none this source can create
3172 /// an issue in: another host, or more or fewer than `owner/name` under this one.
3173 fn from_origin(origin: &Repository) -> Result<Self, String> {
3174 let not_here = || {
3175 format!(
3176 "{} is not a {}/owner/name repository",
3177 origin.as_str(),
3178 Self::HOST
3179 )
3180 };
3181 let (host, rest) = origin.as_str().split_once('/').ok_or_else(not_here)?;
3182 if host != Self::HOST {
3183 return Err(not_here());
3184 }
3185 Self::parse(rest).map_err(|_| not_here())
3186 }
3187
3188 fn slug(&self) -> String {
3189 format!("{}/{}", self.owner, self.name)
3190 }
3191}
3192
3193/// A source which reads GitHub afresh for every operation.
3194pub struct GitHubProjectsSource {
3195 /// This source's configured name, used both to tell a far end naming this source
3196 /// from one naming a system it knows nothing about, and to name the instance a
3197 /// status refusal is about.
3198 name: SourceName,
3199 owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after full GitHub-owner validation.
3200 project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after GraphQL-Int validation.
3201 repository: Option<RepositoryTarget>,
3202 endpoint: Url,
3203 token: SecretString,
3204 credential_name: String, // llmlint: ignore[invalid_states_unrepresentable] Private diagnostic value constructed only after environment-name validation.
3205 statuses: BoardStatuses,
3206 /// Where each priority lands on this board, or `None` when this instance holds none.
3207 priorities: Option<PriorityMapping>,
3208 /// The metadata values this instance projects onto board text fields, in configured order.
3209 metadata_fields: Vec<MetadataField>,
3210 client: Client,
3211 asset_client: Client,
3212 /// Every item this source has created in this command, in the order it created them —
3213 /// dropped by [`TaskSource::end_command`].
3214 ///
3215 /// GitHub's `projectV2.items` is eventually consistent: an issue added to a board with
3216 /// `addProjectV2ItemById` is routinely absent from the very next read of that board, so
3217 /// a copy resolving a dependency on an item it had just created refused it as not
3218 /// found. A board read is completed from this — an item remembered here and absent from
3219 /// the read is added back, because the board really does hold it and only the read is
3220 /// behind.
3221 ///
3222 /// It is not a cache of a user's work: nothing is remembered that this process did not
3223 /// itself just write, it lives and dies with the process, and it is never consulted for
3224 /// an item this source did not create.
3225 created: Mutex<Vec<Resolved>>,
3226 /// Every item that already existed and that this source has written in this command, as
3227 /// it wrote it — dropped by [`TaskSource::end_command`].
3228 ///
3229 /// The other half of [`Self::created`], held on the same terms and for the reason a
3230 /// narrowed read needs it: an answer from GitHub's search or from the board's own field
3231 /// filter is an index behind a write this process made moments ago, so a query matching
3232 /// what this process just wrote onto an existing item would otherwise miss it. Nothing
3233 /// is remembered that this process did not itself just write.
3234 updated: Mutex<Vec<Resolved>>,
3235 /// Every issue this source has added a comment to or edited a comment of in this command
3236 /// — dropped by [`TaskSource::end_command`].
3237 ///
3238 /// A comment-activity read is narrowed by GitHub's issue search, whose `updated:` index
3239 /// lags the write that moved an issue's `updatedAt`, and neither [`Self::created`] nor
3240 /// [`Self::updated`] is moved by a comment, so an issue this process had just commented
3241 /// on was missing from such a read — or ruled out by the `updatedAt` its own record held
3242 /// from before — until the index caught up. Each id here is a candidate of every such
3243 /// search-narrowed read, and wherever it is a candidate its comments are read rather than
3244 /// it being ruled out by a stale `updatedAt`; that read is of the issue's own node, so it
3245 /// is current. It holds ids alone: nothing of a comment is remembered. A comment another
3246 /// process wrote is still found only once the index has it.
3247 commented: Mutex<Vec<NativeId>>,
3248 /// How fast this source writes, and how long it waits out a refusal.
3249 pacing: Pacing,
3250 /// When the last content-creating mutation finished, or the moment the furthest-out
3251 /// reserved slot releases the next one, whichever is later — so the one after it can be
3252 /// spaced from that. See [`MIN_MUTATION_INTERVAL_MS`] for the interval and
3253 /// [`GitHubProjectsSource::finish_mutation`] for why completion rather than release is
3254 /// what it is measured from.
3255 last_mutation: Mutex<Option<Duration>>,
3256 clock: SharedClock,
3257 numeric_repositories: tokio::sync::Mutex<BTreeMap<RepositoryTarget, std::num::NonZeroU64>>,
3258 /// The board as this process last read it, for the length of one command — dropped by
3259 /// [`TaskSource::end_command`].
3260 ///
3261 /// A copy of a project used to re-read the whole board, paged, before writing each of
3262 /// its items, which is by far the largest part of a copy's request count and none of
3263 /// its work. Nothing else changes this board while a command runs — this source's own
3264 /// writes are the only writer — so one read answers them all.
3265 ///
3266 /// It is not a store of a user's work and it is not the cache the no-persistence
3267 /// invariant forbids: it lives and dies with the process exactly as `created` does,
3268 /// nothing is written down, and [`Self::board`] still completes it from `created`, so
3269 /// an item this command created and then depends on resolves whether or not GitHub's
3270 /// own eventually-consistent read has caught up. A write to an item already on the
3271 /// board updates the entry here too, so what this holds is the last read plus this
3272 /// process's own writes rather than a snapshot taken before them.
3273 board_cache: Mutex<Option<Board>>,
3274 /// Every issue this board's own search reported, for the length of one command — dropped
3275 /// by [`TaskSource::end_command`].
3276 ///
3277 /// The second half of a board read, and cached for the same reason and on the same
3278 /// terms as the first: it lives and dies with the process, nothing is written down, and
3279 /// a write this process makes updates the entry here exactly as it updates the one in
3280 /// [`Self::board_cache`]. One read answers every question a command asks, so a command
3281 /// that lists this board's projects and its tasks pays for one search rather than two.
3282 search_cache: Mutex<Option<Vec<Resolved>>>,
3283 /// What each narrowed question GitHub was asked answered, keyed by that question, for
3284 /// the length of one command — dropped by [`TaskSource::end_command`].
3285 ///
3286 /// The narrowed counterpart of [`Self::search_cache`], held on the same terms: it lives
3287 /// and dies with the process, nothing is written down, a write this process makes
3288 /// updates the entry here as it updates the other two, and every answer is completed
3289 /// with this process's own writes each time it is given. A command that asks the same
3290 /// narrowed question twice — a wait polling for its own items, a listing repeated after a
3291 /// write — pays for it once, which is what the whole-board read it replaced gave it.
3292 narrowed_cache: Mutex<BTreeMap<String, Vec<Resolved>>>,
3293 search_next: Mutex<BTreeMap<String, Option<String>>>,
3294 /// Records already resolved in this command, reused by writes and for comment identity.
3295 /// Explicit item reads still reach GitHub. Nothing is persisted, and
3296 /// [`TaskSource::end_command`] drops every record, so a write in the next command reads
3297 /// its item as a person has since left it.
3298 resolved_cache: Mutex<BTreeMap<NativeId, Resolved>>,
3299 /// Items an issue read by reference reached, held for the one status write each was read
3300 /// for and taken out by it alone — see [`Self::take_held`] — because that read selects only
3301 /// what such a write needs. Dropped by [`TaskSource::end_command`].
3302 held_cache: Mutex<BTreeMap<NativeId, Resolved>>,
3303 /// Each project's sub-issues as GitHub answered them, keyed by the selector they were
3304 /// asked for under, with the project that selector named — for the length of one command,
3305 /// dropped by [`TaskSource::end_command`].
3306 ///
3307 /// A caller pages through a project's tasks one engine page at a time, and every page
3308 /// is cut from the whole list of them, so without this each page walked every
3309 /// [`graphql::SUB_ISSUES`] page again and a project of `n` listing pages cost `n²`
3310 /// requests to read once. Held on the terms [`Self::narrowed_cache`] is: it lives and
3311 /// dies with the process, nothing is written down, a write this process makes updates or
3312 /// removes the entry here as it does there, and every answer is completed with this
3313 /// process's own writes each time it is given.
3314 children_cache: Mutex<ProjectChildren>,
3315 /// The board's own id and field definitions as this process last read them on their
3316 /// own, for the length of one command — dropped by [`TaskSource::end_command`].
3317 ///
3318 /// What a write needs of the board and its item does not say, read once per command
3319 /// rather than once per item written, on the terms [`Self::board_cache`] is held on: it
3320 /// lives and dies with the process and nothing is written down. It holds no item and so
3321 /// can answer no question about one — see [`Self::board_fields`].
3322 fields_cache: Mutex<Option<BoardFields>>,
3323 /// Each destination repository's node id, resolved once per repository
3324 /// rather than per issue created.
3325 ///
3326 /// A repository's node id does not change, and re-reading it for every issue of a copy
3327 /// spent one request per item on an answer this source already had. It is a map rather
3328 /// than one entry because a copy files each item in the repository its own
3329 /// `repositories` field names, so a plan across five repositories asks GitHub five
3330 /// times and not once per item.
3331 repository_cache: Mutex<BTreeMap<RepositoryTarget, String>>,
3332 /// What every request this source sends is recorded into.
3333 ///
3334 /// Ordinary code path, not a mode: [`Self::send_once`] records into it at the one place
3335 /// a request leaves this crate, so nothing has to be switched on for a session to be
3336 /// counted. It is shared rather than owned so a caller accounting for a whole session —
3337 /// its own schema verification, board lookups, residue sweep and cleanup beside this
3338 /// source's reads and writes — adds up one accounting instead of two. See
3339 /// [`accounting`] for what a record carries and what a session's spend is and is not.
3340 ledger: Arc<Accounting>,
3341 /// What [`expected`] holds for a write the store's cache expects: the journal while one is
3342 /// open, the issues primed from the cache, and the comments known on each.
3343 expected: expected::Held,
3344}
3345
3346/// GitHub's closed single-select color vocabulary.
3347#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3348#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
3349pub enum StatusOptionColor {
3350 /// Gray.
3351 Gray,
3352 /// Blue.
3353 Blue,
3354 /// Green.
3355 Green,
3356 /// Yellow.
3357 Yellow,
3358 /// Purple.
3359 Purple,
3360 /// Red.
3361 Red,
3362 /// Orange.
3363 Orange,
3364 /// Pink.
3365 Pink,
3366}
3367
3368/// Whether a guarded board setup — of the fields, or of the Status options alone — plans or
3369/// applies its additions.
3370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3371pub enum SetupMode {
3372 /// Read without mutation.
3373 Plan,
3374 /// Apply and verify.
3375 Apply,
3376}
3377
3378/// The name [`SetupMode`] had when Status was the one field set up, kept so a caller written
3379/// against it goes on compiling.
3380pub type StatusOptionsMode = SetupMode;
3381
3382/// The explicit result of the requested operation.
3383#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3384#[serde(rename_all = "kebab-case")]
3385pub enum StatusOptionsOutcome {
3386 /// A read-only plan.
3387 Planned,
3388 /// Apply found nothing missing.
3389 Unchanged,
3390 /// Additions were applied and verified.
3391 Applied,
3392}
3393
3394/// A GitHub single-select option's opaque GraphQL node identifier.
3395#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3396#[serde(transparent)]
3397pub struct StatusOptionId(#[schemars(length(min = 1))] String);
3398
3399impl TryFrom<String> for StatusOptionId {
3400 type Error = String;
3401
3402 fn try_from(id: String) -> Result<Self, Self::Error> {
3403 if id.trim().is_empty() {
3404 return Err("a GitHub Status option id cannot be blank".to_owned());
3405 }
3406 Ok(Self(id))
3407 }
3408}
3409
3410/// One existing or proposed option in a guarded Status-field update.
3411#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3412pub struct StatusOption {
3413 /// GitHub's stable id.
3414 pub id: StatusOptionId,
3415 /// The visible option name.
3416 pub name: ColumnName,
3417 /// GitHub's single-select color token.
3418 pub color: StatusOptionColor,
3419 /// The option description, including an empty one.
3420 pub description: String,
3421}
3422
3423/// One board item's Status assignment, retained as recovery data.
3424#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3425pub struct StatusAssignment {
3426 /// The project item id whose assignment this is.
3427 // llmlint: ignore[invalid_states_unrepresentable] This opaque GraphQL node ID is
3428 // carried verbatim as operator recovery data; introducing a semantic type would claim
3429 // validation rules GitHub does not publish and no operation here interprets.
3430 pub item_id: String,
3431 /// The selected option, absent when the item has no status.
3432 #[serde(skip_serializing_if = "Option::is_none")]
3433 pub option: Option<AssignedStatusOption>,
3434}
3435
3436/// The inseparable id and name of an assigned option.
3437#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3438pub struct AssignedStatusOption {
3439 /// GitHub's stable id.
3440 pub id: StatusOptionId,
3441 /// The visible name.
3442 pub name: ColumnName,
3443}
3444
3445/// The plan and verified outcome of reconciling configured Status options.
3446#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3447pub struct StatusOptionsReport {
3448 /// The configured source name.
3449 pub source: SourceName,
3450 /// Configured option names absent before the operation.
3451 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a
3452 // `ColumnName` and has therefore already passed its nonblank validation; retaining the
3453 // serialized string here preserves the report's intentionally simple public contract.
3454 pub missing: Vec<String>,
3455 /// What the requested operation did.
3456 pub outcome: StatusOptionsOutcome,
3457 /// The complete option list observed before any mutation.
3458 pub existing: Vec<StatusOption>,
3459}
3460
3461#[derive(Debug, Clone, PartialEq, Eq)]
3462struct StatusSnapshot {
3463 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
3464 // passed back as the mutation's project identity; a newtype could enforce no stronger
3465 // invariant because GitHub publishes no grammar for it.
3466 board_id: String,
3467 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
3468 // passed back as the mutation's field identity; a newtype could enforce no stronger
3469 // invariant because GitHub publishes no grammar for it.
3470 field_id: String,
3471 options: Vec<StatusOption>,
3472 assignments: Vec<StatusAssignment>,
3473}
3474
3475/// The name of the board field a status is held in.
3476const STATUS_FIELD: &str = "Status";
3477
3478/// Every item's value of each field `report` names, as it stood before the setup wrote
3479/// anything — what a person puts back when the setup is refused part way.
3480fn recovery(report: &FieldsReport, before: &BoardSnapshot) -> Result<String, SourceError> {
3481 let assignments: BTreeMap<&str, Vec<StatusAssignment>> = report
3482 .fields
3483 .iter()
3484 .map(|field| (field.field.name(), before.assignments(field.field)))
3485 .collect();
3486 serde_json::to_string_pretty(&assignments).map_err(|error| SourceError::Malformed {
3487 message: format!("cannot render the pre-write field recovery snapshot: {error}"),
3488 })
3489}
3490
3491/// One board field the guarded setup reads and writes — every one it reads, and the only
3492/// ones it writes.
3493#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, schemars::JsonSchema)]
3494pub enum BoardField {
3495 /// The single-select `Status` field every instance's `status_mapping` resolves into.
3496 Status,
3497 /// The single-select `Priority` field an instance's `priority_mapping` resolves into.
3498 Priority,
3499}
3500
3501impl BoardField {
3502 /// The field's name on the board.
3503 #[must_use]
3504 pub const fn name(self) -> &'static str {
3505 match self {
3506 Self::Status => STATUS_FIELD,
3507 Self::Priority => PRIORITY_FIELD,
3508 }
3509 }
3510
3511 /// The field a board calls `name`, or `None` for one this setup does not own.
3512 fn named(name: &str) -> Option<Self> {
3513 [Self::Status, Self::Priority]
3514 .into_iter()
3515 .find(|field| field.name() == name)
3516 }
3517}
3518
3519/// What the guarded setup did to one field.
3520#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3521#[serde(rename_all = "kebab-case")]
3522pub enum FieldOutcome {
3523 /// A read-only plan.
3524 Planned,
3525 /// Apply found the field there with every configured option.
3526 Unchanged,
3527 /// Missing options were added to the field that was there, and verified.
3528 Applied,
3529 /// The field was not there; it was created holding the configured options, and verified.
3530 Created,
3531}
3532
3533/// One field's plan, or its verified outcome.
3534#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3535pub struct FieldReport {
3536 /// Which field.
3537 pub field: BoardField,
3538 /// Whether the board had the field before the operation.
3539 // llmlint: ignore[invalid_states_unrepresentable] `exists` beside `outcome` is the report's
3540 // wire shape as its consumer's contract fixes it — `{"field", "exists", "missing",
3541 // "outcome", "existing"}` — so folding one into the other would change a published JSON
3542 // shape. The contradictory pairings cannot be built: `GitHubProjectsSource::fields` is the
3543 // one constructor, and it derives `outcome` from `exists` in one match.
3544 pub exists: bool,
3545 /// Configured option names the field lacked before the operation — every one of them,
3546 /// in the order a new field lists them, when the field was not there at all.
3547 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
3548 // mapping name and has therefore already passed its nonblank validation; the serialized
3549 // string is the report's intentionally simple public contract, as `StatusOptionsReport`'s is.
3550 pub missing: Vec<String>,
3551 /// For the `Status` field, which item kind each missing name is configured for: one
3552 /// entry per kind `status_mapping` names a missing option for, task before project, each
3553 /// listing that kind's missing names in category order. A name both kinds use is in
3554 /// both. Empty — and left out of the JSON — when nothing is missing, and always for
3555 /// `Priority`, which only a task holds.
3556 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3557 // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
3558 // both SDKs model an absent `kinds` as an empty list rather than as `null`.
3559 #[schemars(!skip_serializing_if)]
3560 pub kinds: Vec<KindMissing>,
3561 /// What the requested operation did.
3562 pub outcome: FieldOutcome,
3563 /// The field's complete option list observed before any mutation; empty when the field
3564 /// was not there.
3565 pub existing: Vec<StatusOption>,
3566}
3567
3568/// The `Status` option names one item kind's `status_mapping` names that the field lacked.
3569#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3570pub struct KindMissing {
3571 /// The kind these names are configured for.
3572 pub kind: ItemKind,
3573 /// The names that kind maps a category to and the field lacked, in category order.
3574 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
3575 // mapping name, as `FieldReport::missing`'s do, and the serialized string is the report's
3576 // intentionally simple public contract.
3577 pub missing: Vec<String>,
3578}
3579
3580/// The plan and verified outcome of setting up every field a source's configuration names.
3581#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3582pub struct FieldsReport {
3583 /// The configured source name.
3584 pub source: SourceName,
3585 /// `Status`, always, and `Priority` when the source sets `priority_mapping`.
3586 // llmlint: ignore[invalid_states_unrepresentable] A list is the report's wire shape as its
3587 // consumer's contract fixes it — `{"source", "fields": [...]}` — so a struct with one member
3588 // per field would change a published JSON shape. The states the list could hold and the
3589 // contract forbids cannot be built: `GitHubProjectsSource::fields` is the one constructor,
3590 // and it pushes `Status` first and exactly once, then `Priority` exactly when configured.
3591 pub fields: Vec<FieldReport>,
3592 /// Each board text field the source's `metadata_fields` projects a value onto, in
3593 /// configured order. Empty — and left out of the JSON — when it projects none.
3594 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3595 // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
3596 // both SDKs model an absent list as an empty one rather than as `null`.
3597 #[schemars(!skip_serializing_if)]
3598 pub metadata_fields: Vec<MetadataFieldReport>,
3599}
3600
3601/// The type of a board field that is not a text field, as GitHub names it — its `dataType`, or
3602/// its GraphQL type when it has none — which is what a projected field's conflict reports.
3603///
3604/// Never empty, never beginning with whitespace, and never `TEXT`: a text field of that name is
3605/// no conflict.
3606// The schema states that rule as `NON_TEXT_FIELD_TYPE_PATTERN`, so a generated SDK model
3607// refuses exactly what `try_from` below does.
3608#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3609#[serde(transparent)]
3610pub struct NonTextFieldType(#[schemars(regex(pattern = NON_TEXT_FIELD_TYPE_PATTERN))] String);
3611
3612/// What a [`NonTextFieldType`] may be, as the emitted schema states it: a first character that
3613/// is not whitespace, and anything but exactly `TEXT` — spelled without a lookahead, which
3614/// neither SDK's validator can be relied on to support.
3615const NON_TEXT_FIELD_TYPE_PATTERN: &str =
3616 r"^(?:[^T\s]|T(?:[^E]|$)|TE(?:[^X]|$)|TEX(?:[^T]|$)|TEXT[\s\S])";
3617
3618impl TryFrom<String> for NonTextFieldType {
3619 type Error = String;
3620
3621 fn try_from(kind: String) -> Result<Self, Self::Error> {
3622 if kind.is_empty() || kind.starts_with(char::is_whitespace) {
3623 return Err("a board field's type cannot be blank or begin with whitespace".to_owned());
3624 }
3625 if kind == "TEXT" {
3626 return Err("a TEXT field is no conflict for a projected text field".to_owned());
3627 }
3628 Ok(Self(kind))
3629 }
3630}
3631
3632impl std::fmt::Display for NonTextFieldType {
3633 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3634 formatter.write_str(&self.0)
3635 }
3636}
3637
3638/// One projected metadata text field's plan, or its verified outcome.
3639///
3640/// The setup creates a missing one as a text field and never alters a field that is there:
3641/// a same-named field of another type is reported in `conflict` and left as it is.
3642#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3643pub struct MetadataFieldReport {
3644 /// The board field's name.
3645 pub field: String, // llmlint: ignore[invalid_states_unrepresentable] Copied from a configuration entry `MetadataField::resolve` already validated; the serialized string is the report's intentionally simple public contract, as `FieldReport::missing`'s names are.
3646 /// The metadata key the value is read from.
3647 pub key: String, // llmlint: ignore[invalid_states_unrepresentable] As `field`: a validated configuration value reported back as written.
3648 /// The object keys walked inside that key's value; empty for the key's own value.
3649 pub path: Vec<String>,
3650 /// Whether the board had a text field of that name before the operation.
3651 // llmlint: ignore[invalid_states_unrepresentable] `exists` beside `outcome` mirrors `FieldReport`'s published shape; `GitHubProjectsSource::fields` is the one constructor and derives `outcome` from `exists` and `conflict` in one match.
3652 pub exists: bool,
3653 /// The type of a field of that name that is not a text field, which the setup leaves as
3654 /// it is; absent — and left out of the JSON — when there is none.
3655 #[serde(default, skip_serializing_if = "Option::is_none")]
3656 pub conflict: Option<NonTextFieldType>,
3657 /// What the requested operation did: `planned`; `created` for a field that was not
3658 /// there; `unchanged` for one that was, and for a conflict, which is never changed.
3659 pub outcome: FieldOutcome,
3660}
3661
3662/// Which options one field is configured with, in the order a new field would list them.
3663struct FieldPlan {
3664 field: BoardField,
3665 wanted: Vec<String>,
3666}
3667
3668/// One single-select field as the guarded setup snapshots it.
3669#[derive(Debug, Clone, PartialEq, Eq)]
3670struct SnapshotField {
3671 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
3672 // passed back as the mutation's field identity; a newtype could enforce no stronger
3673 // invariant because GitHub publishes no grammar for it.
3674 field_id: String,
3675 options: Vec<StatusOption>,
3676}
3677
3678/// Every single-select field of a board and every item's value of each.
3679#[derive(Debug, Clone, PartialEq, Eq)]
3680struct BoardSnapshot {
3681 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
3682 // passed back as the mutation's project identity; a newtype could enforce no stronger
3683 // invariant because GitHub publishes no grammar for it.
3684 board_id: String,
3685 fields: BTreeMap<BoardField, SnapshotField>,
3686 /// Each board item's id, and its value of each field this setup owns that it holds one of.
3687 items: Vec<(String, BTreeMap<BoardField, AssignedStatusOption>)>,
3688}
3689
3690impl BoardSnapshot {
3691 /// Every item's value of `field`, in board order — the recovery data a drift refusal
3692 /// carries.
3693 fn assignments(&self, field: BoardField) -> Vec<StatusAssignment> {
3694 self.items
3695 .iter()
3696 .map(|(item_id, values)| StatusAssignment {
3697 item_id: item_id.clone(),
3698 option: values.get(&field).cloned(),
3699 })
3700 .collect()
3701 }
3702}
3703
3704impl GitHubProjectsSource {
3705 /// Report missing configured Status options and, when `apply` is true, add them with
3706 /// a whole-list mutation that preserves every existing id and verifies the result.
3707 ///
3708 /// # Errors
3709 ///
3710 /// Refuses a board without a single-select `Status` field. A post-write difference in
3711 /// any pre-existing option id or item assignment is refused with the complete pre-write
3712 /// assignment snapshot in the diagnostic for recovery.
3713 // llmlint: ignore[changed_behavior_has_e2e] The CLI journeys cover plan, no-op apply,
3714 // successful mutation, both drift refusals, source selection, missing Status, casing,
3715 // and paging. Transport errors remain the shared `graphql` boundary's behavior rather
3716 // than a new status-options behavior, and the pinned-schema test prevents valid GitHub
3717 // responses from entering the defensive malformed-response branches below.
3718 pub async fn status_options(
3719 &self,
3720 mode: StatusOptionsMode,
3721 ) -> Result<StatusOptionsReport, SourceError> {
3722 let before = self.status_snapshot().await?;
3723 // A terminal category's option is as configured as an open one's: a terminal
3724 // write validates it before closing and refuses when the board lacks it. Both
3725 // kinds' names are options of the one field, so both are asked for.
3726 let missing = self
3727 .statuses
3728 .wanted()
3729 .into_iter()
3730 .filter(|wanted| {
3731 !before
3732 .options
3733 .iter()
3734 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
3735 })
3736 .collect::<Vec<_>>();
3737 let report = StatusOptionsReport {
3738 source: self.name.clone(),
3739 missing: missing.clone(),
3740 outcome: match (mode, missing.is_empty()) {
3741 (StatusOptionsMode::Plan, _) => StatusOptionsOutcome::Planned,
3742 (StatusOptionsMode::Apply, true) => StatusOptionsOutcome::Unchanged,
3743 (StatusOptionsMode::Apply, false) => StatusOptionsOutcome::Applied,
3744 },
3745 existing: before.options.clone(),
3746 };
3747 if mode == StatusOptionsMode::Plan || missing.is_empty() {
3748 return Ok(report);
3749 }
3750 let mut options = before
3751 .options
3752 .iter()
3753 .map(|option| {
3754 json!({
3755 "id": option.id, "name": option.name, "color": option.color,
3756 "description": option.description,
3757 })
3758 })
3759 .collect::<Vec<_>>();
3760 options.extend(missing.iter().map(|name| {
3761 json!({
3762 "name": name, "color": "GRAY", "description": ""
3763 })
3764 }));
3765 self.graphql(
3766 graphql::STATUS_OPTIONS_UPDATE,
3767 json!({"input": {
3768 "projectId": before.board_id, "fieldId": before.field_id,
3769 "singleSelectOptions": options,
3770 }}),
3771 )
3772 .await?;
3773 let after = self.status_snapshot().await?;
3774 let options_preserved = before
3775 .options
3776 .iter()
3777 .all(|old| after.options.iter().any(|new| new == old));
3778 let additions_present = missing.iter().all(|wanted| {
3779 after
3780 .options
3781 .iter()
3782 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
3783 });
3784 if !options_preserved || !additions_present || after.assignments != before.assignments {
3785 let recovery = serde_json::to_string_pretty(&before.assignments).map_err(|error| {
3786 SourceError::Malformed {
3787 message: format!("cannot render pre-write Status recovery snapshot: {error}"),
3788 }
3789 })?;
3790 return Err(SourceError::Refused {
3791 message: format!(
3792 "GitHub changed a pre-existing Status option id, name, color or description, or an item assignment after the guarded update; the pre-write item assignment snapshot is:\n{recovery}"
3793 ),
3794 });
3795 }
3796 Ok(report)
3797 }
3798
3799 /// A fresh snapshot of the Status field and every board item's assignment of it.
3800 ///
3801 /// # Errors
3802 ///
3803 /// Refuses a board without a single-select `Status` field, and one the token cannot see.
3804 async fn status_snapshot(&self) -> Result<StatusSnapshot, SourceError> {
3805 // Status alone, as this operation has always read it: a `Priority` field is another
3806 // operation's, so nothing about it can refuse this one.
3807 let mut board = self.board_snapshot(&[BoardField::Status]).await?;
3808 let field = board
3809 .fields
3810 .remove(&BoardField::Status)
3811 .ok_or_else(|| self.no_status_field())?;
3812 Ok(StatusSnapshot {
3813 assignments: board.assignments(BoardField::Status),
3814 board_id: board.board_id,
3815 field_id: field.field_id,
3816 options: field.options,
3817 })
3818 }
3819
3820 /// The refusal a board with no `Status` field is answered with by the guarded setup.
3821 fn no_status_field(&self) -> SourceError {
3822 SourceError::Refused {
3823 message: format!("source {} board has no Status field", self.name),
3824 }
3825 }
3826
3827 // llmlint: ignore-block[changed_behavior_has_e2e] Valid snapshot shapes are exercised through
3828 // the real CLI loopback journey, including pagination. The individual malformed guards
3829 // are defensive validation of a schema-pinned third-party response, not separate user
3830 // journeys; drift and missing-field failures cover the operation's recovery behavior.
3831 /// A fresh snapshot of each of the `owned` fields on the board, with its options, and of
3832 /// every board item's value of each, walked to the end of the board's items. A field not
3833 /// in `owned` is read past whatever it holds.
3834 async fn board_snapshot(&self, owned: &[BoardField]) -> Result<BoardSnapshot, SourceError> {
3835 let mut after: Option<String> = None;
3836 let mut snapshot: Option<BoardSnapshot> = None;
3837 loop {
3838 let data = self
3839 .graphql(
3840 graphql::STATUS_OPTIONS_SNAPSHOT,
3841 json!({
3842 "owner": self.owner, "number": self.project_number,
3843 "first": MAX_PAGE_SIZE, "after": after, "nestedFirst": MAX_PAGE_SIZE,
3844 }),
3845 )
3846 .await?;
3847 let board = data
3848 .pointer("/owner/projectV2")
3849 .filter(|board| board.is_object())
3850 .ok_or_else(|| SourceError::Refused {
3851 message: format!(
3852 "source {} has no accessible GitHub Projects board",
3853 self.name
3854 ),
3855 })?;
3856 if board
3857 .pointer("/fields/pageInfo/hasNextPage")
3858 .and_then(Value::as_bool)
3859 != Some(false)
3860 {
3861 return Err(SourceError::Malformed {
3862 message:
3863 "GitHub project fields is incomplete or has malformed pageInfo.hasNextPage"
3864 .into(),
3865 });
3866 }
3867 let mut fields = BTreeMap::new();
3868 // Only the fields this setup owns, by name: a node the single-select fragment did not
3869 // match carries no name, and a person's own single-select field — a `Size`, a
3870 // `Team` — is none of this setup's business, so nothing about it can refuse one. A
3871 // `Status` or `Priority` field without its options is malformed, not absent.
3872 // llmlint: ignore[boundary_inputs_validated] The field page this loop reads is validated as complete immediately above: any `fields.pageInfo.hasNextPage` other than `false` is refused as malformed before a node is read, so an incomplete page is never taken for the board's whole field set.
3873 for (owned, field) in board
3874 .pointer("/fields/nodes")
3875 .and_then(Value::as_array)
3876 .ok_or_else(|| SourceError::Malformed {
3877 message: "GitHub project fields.nodes is not an array".into(),
3878 })?
3879 .iter()
3880 .filter_map(|field| {
3881 let named = BoardField::named(field.get("name")?.as_str()?)?;
3882 owned.contains(&named).then_some((named, field))
3883 })
3884 {
3885 let options = field
3886 .get("options")
3887 .and_then(Value::as_array)
3888 .ok_or_else(|| SourceError::Malformed {
3889 message: "GitHub single-select field options is not an array".into(),
3890 })?
3891 .iter()
3892 .map(|option| {
3893 Ok(StatusOption {
3894 id: StatusOptionId::try_from(required_str(option, "id")?.to_owned())
3895 .map_err(|message| SourceError::Malformed { message })?,
3896 name: ColumnName::try_from(required_str(option, "name")?.to_owned())
3897 .map_err(|message| SourceError::Malformed {
3898 message: format!(
3899 "GitHub single-select option name is invalid: {message}"
3900 ),
3901 })?,
3902 color: serde_json::from_value(
3903 option.get("color").cloned().unwrap_or(Value::Null),
3904 )
3905 .map_err(|error| {
3906 SourceError::Malformed {
3907 message: format!(
3908 "GitHub single-select option color is invalid: {error}"
3909 ),
3910 }
3911 })?,
3912 description: optional_str(option, "description")?
3913 .unwrap_or_default()
3914 .to_owned(),
3915 })
3916 })
3917 .collect::<Result<Vec<_>, SourceError>>()?;
3918 let snapshot = SnapshotField {
3919 field_id: required_nonblank_str(field, "id")?.to_owned(),
3920 options,
3921 };
3922 // A board's field names are unique, so a second one is an answer that cannot
3923 // say which field the setup would act on — refused rather than one chosen.
3924 if fields.insert(owned, snapshot).is_some() {
3925 return Err(SourceError::Malformed {
3926 message: format!(
3927 "GitHub answered two {} fields for this board",
3928 owned.name()
3929 ),
3930 });
3931 }
3932 }
3933 let board_id = required_nonblank_str(board, "id")?.to_owned();
3934 let current = snapshot.get_or_insert_with(|| BoardSnapshot {
3935 board_id,
3936 fields,
3937 items: Vec::new(),
3938 });
3939 let items = board
3940 .pointer("/items/nodes")
3941 .and_then(Value::as_array)
3942 .ok_or_else(|| SourceError::Malformed {
3943 message: "GitHub project items.nodes is not an array".into(),
3944 })?;
3945 for item in items {
3946 let field_values =
3947 item.get("fieldValues")
3948 .ok_or_else(|| SourceError::Malformed {
3949 message: "GitHub project item is missing fieldValues".into(),
3950 })?;
3951 if field_values
3952 .pointer("/pageInfo/hasNextPage")
3953 .and_then(Value::as_bool)
3954 != Some(false)
3955 {
3956 return Err(SourceError::Malformed {
3957 message: "GitHub project item fieldValues is incomplete or has malformed pageInfo.hasNextPage".into(),
3958 });
3959 }
3960 let values = item
3961 .pointer("/fieldValues/nodes")
3962 .and_then(Value::as_array)
3963 .ok_or_else(|| SourceError::Malformed {
3964 message: "GitHub project item fieldValues.nodes is not an array".into(),
3965 })?;
3966 let item_id = required_nonblank_str(item, "id")?;
3967 let mut assigned = BTreeMap::new();
3968 for value in values {
3969 let Some(field) = value
3970 .pointer("/field/name")
3971 .and_then(Value::as_str)
3972 .and_then(BoardField::named)
3973 .filter(|field| owned.contains(field))
3974 else {
3975 continue;
3976 };
3977 let held = assigned.insert(
3978 field,
3979 AssignedStatusOption {
3980 id: StatusOptionId::try_from(
3981 required_str(value, "optionId")?.to_owned(),
3982 )
3983 .map_err(|message| SourceError::Malformed { message })?,
3984 name: ColumnName::try_from(required_str(value, "name")?.to_owned())
3985 .map_err(|message| SourceError::Malformed {
3986 message: format!(
3987 "GitHub assigned {} name is invalid: {message}",
3988 field.name()
3989 ),
3990 })?,
3991 },
3992 );
3993 // An item holds one value of a field, so a second one leaves no way to
3994 // tell which it holds — and a verification or recovery built on either
3995 // could restore the wrong one.
3996 if held.is_some() {
3997 return Err(SourceError::Malformed {
3998 message: format!(
3999 "GitHub answered two {} values for board item {item_id}",
4000 field.name()
4001 ),
4002 });
4003 }
4004 }
4005 current.items.push((item_id.to_owned(), assigned));
4006 }
4007 let page = board.get("items").ok_or_else(|| SourceError::Malformed {
4008 message: "GitHub project is missing items".into(),
4009 })?;
4010 let has_next = page
4011 .pointer("/pageInfo/hasNextPage")
4012 .and_then(Value::as_bool)
4013 .ok_or_else(|| SourceError::Malformed {
4014 message: "GitHub project items.pageInfo.hasNextPage is not a boolean".into(),
4015 })?;
4016 if !has_next {
4017 break;
4018 }
4019 let next =
4020 required_nonblank_str(page.get("pageInfo").unwrap_or(&Value::Null), "endCursor")?;
4021 validate_cursor_progress(after.as_deref(), next)?;
4022 after = Some(next.to_owned());
4023 }
4024 snapshot.ok_or_else(|| SourceError::Malformed {
4025 message: "GitHub returned no board field snapshot".into(),
4026 })
4027 }
4028 // llmlint: ignore-end[changed_behavior_has_e2e]
4029
4030 /// Report every board field this source's configuration names and, with
4031 /// [`SetupMode::Apply`], set each up: add the options a field lacks, and create
4032 /// the `Priority` field when the board has none.
4033 ///
4034 /// The fields are `Status`, always, with the options `status_mapping` resolves to; and
4035 /// `Priority`, when `priority_mapping` is set, with its four mapped options — created in
4036 /// the order urgent, high, medium, low. An option a field already has keeps its id, name,
4037 /// color and description: the whole option list goes back with every existing id, because
4038 /// a re-minted id clears every item's value.
4039 ///
4040 /// # Errors
4041 ///
4042 /// Refuses a board without a single-select `Status` field. After an apply the board is
4043 /// read again, and a pre-existing option or any item's value of either field that moved is
4044 /// refused with the complete pre-write assignments in the diagnostic, for recovery.
4045 // llmlint: ignore[changed_behavior_has_e2e] The `sources fields` journeys drive plan,
4046 // unchanged apply, a created field, an added option to each field, drift refusal, a board
4047 // with no Status field and a non-github-projects source through the compiled CLI against
4048 // the loopback board. Transport errors are the shared `graphql` boundary's behavior.
4049 pub async fn fields(&self, mode: SetupMode) -> Result<FieldsReport, SourceError> {
4050 let owned: Vec<BoardField> = if self.priorities.is_some() {
4051 vec![BoardField::Status, BoardField::Priority]
4052 } else {
4053 vec![BoardField::Status]
4054 };
4055 let before = self.board_snapshot(&owned).await?;
4056 let mut plans = vec![FieldPlan {
4057 field: BoardField::Status,
4058 wanted: self.statuses.wanted(),
4059 }];
4060 if !before.fields.contains_key(&BoardField::Status) {
4061 return Err(self.no_status_field());
4062 }
4063 if let Some(mapping) = &self.priorities {
4064 plans.push(FieldPlan {
4065 field: BoardField::Priority,
4066 wanted: mapping.names().map(str::to_owned).collect(),
4067 });
4068 }
4069 // The snapshot reads single-select fields alone, so a field it did not find may still
4070 // be on the board under the name, of another type: creating one beside it would fail
4071 // part way, or leave two fields of one name. Asked of the board's own field list, and
4072 // only when a field is missing.
4073 if plans
4074 .iter()
4075 .any(|plan| !before.fields.contains_key(&plan.field))
4076 {
4077 let board = self.board_fields().await?;
4078 for plan in plans
4079 .iter()
4080 .filter(|plan| !before.fields.contains_key(&plan.field))
4081 {
4082 if let Some(field) = Board::field(&board.fields, plan.field.name())? {
4083 return Err(SourceError::Refused {
4084 message: format!(
4085 "source {}'s board has a {} field that is not a single-select field \
4086 (it is a {}), so it cannot hold this source's options; next: rename \
4087 or remove that field, then run this again",
4088 self.name,
4089 plan.field.name(),
4090 optional_str(field, "__typename")?.unwrap_or("field of another type")
4091 ),
4092 });
4093 }
4094 }
4095 }
4096 let mut reports = Vec::new();
4097 for plan in &plans {
4098 let held = before.fields.get(&plan.field);
4099 let existing = held.map(|field| field.options.clone()).unwrap_or_default();
4100 let mut missing: Vec<String> = Vec::new();
4101 for wanted in &plan.wanted {
4102 let present = existing
4103 .iter()
4104 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4105 || missing
4106 .iter()
4107 .any(|named| named.eq_ignore_ascii_case(wanted));
4108 if !present {
4109 missing.push(wanted.clone());
4110 }
4111 }
4112 let kinds = match plan.field {
4113 BoardField::Status => self.statuses.missing_by_kind(&existing),
4114 BoardField::Priority => Vec::new(),
4115 };
4116 reports.push(FieldReport {
4117 field: plan.field,
4118 exists: held.is_some(),
4119 kinds,
4120 outcome: match (mode, held.is_some(), missing.is_empty()) {
4121 (SetupMode::Plan, _, _) => FieldOutcome::Planned,
4122 (SetupMode::Apply, true, true) => FieldOutcome::Unchanged,
4123 (SetupMode::Apply, true, false) => FieldOutcome::Applied,
4124 (SetupMode::Apply, false, _) => FieldOutcome::Created,
4125 },
4126 missing,
4127 existing,
4128 });
4129 }
4130 // A projected field is a text field, which the single-select snapshot cannot see, so
4131 // it is asked of the board's own field list — and only when one is configured.
4132 let mut metadata_fields = Vec::new();
4133 if !self.metadata_fields.is_empty() {
4134 let board = self.board_fields().await?;
4135 for projection in &self.metadata_fields {
4136 let conflict = match Board::field(&board.fields, &projection.field)? {
4137 None => None,
4138 Some(field) => {
4139 let typename = optional_str(field, "__typename")?;
4140 let data_type = optional_str(field, "dataType")?;
4141 if typename == Some("ProjectV2Field") && data_type == Some("TEXT") {
4142 None
4143 } else {
4144 let named = data_type
4145 .filter(|kind| *kind != "TEXT")
4146 .or(typename)
4147 .unwrap_or("field of another type");
4148 Some(NonTextFieldType::try_from(named.to_owned()).map_err(
4149 |message| SourceError::Malformed {
4150 message: format!(
4151 "GitHub answered the board's {} field with a type this \
4152 setup cannot read: {message}",
4153 &*projection.field
4154 ),
4155 },
4156 )?)
4157 }
4158 }
4159 };
4160 let exists =
4161 conflict.is_none() && Board::field(&board.fields, &projection.field)?.is_some();
4162 metadata_fields.push(MetadataFieldReport {
4163 field: projection.field.to_string(),
4164 key: projection.key.to_string(),
4165 path: projection.path.clone(),
4166 exists,
4167 outcome: match (mode, exists || conflict.is_some()) {
4168 (SetupMode::Plan, _) => FieldOutcome::Planned,
4169 (SetupMode::Apply, true) => FieldOutcome::Unchanged,
4170 (SetupMode::Apply, false) => FieldOutcome::Created,
4171 },
4172 conflict,
4173 });
4174 }
4175 }
4176 let report = FieldsReport {
4177 source: self.name.clone(),
4178 fields: reports,
4179 metadata_fields,
4180 };
4181 let writes: Vec<&FieldReport> = report
4182 .fields
4183 .iter()
4184 .filter(|field| !field.missing.is_empty() || !field.exists)
4185 .collect();
4186 let creates: Vec<&MetadataFieldReport> = report
4187 .metadata_fields
4188 .iter()
4189 .filter(|field| field.outcome == FieldOutcome::Created)
4190 .collect();
4191 if mode == SetupMode::Plan || (writes.is_empty() && creates.is_empty()) {
4192 return Ok(report);
4193 }
4194 let mut landed: Vec<&str> = Vec::new();
4195 for field in &writes {
4196 let added = field
4197 .missing
4198 .iter()
4199 .map(|name| json!({"name": name, "color": "GRAY", "description": ""}));
4200 let sent = match before.fields.get(&field.field) {
4201 Some(held) => {
4202 let mut options = held
4203 .options
4204 .iter()
4205 .map(|option| {
4206 json!({
4207 "id": option.id, "name": option.name, "color": option.color,
4208 "description": option.description,
4209 })
4210 })
4211 .collect::<Vec<_>>();
4212 options.extend(added);
4213 self.graphql(
4214 graphql::STATUS_OPTIONS_UPDATE,
4215 json!({"input": {
4216 "projectId": before.board_id, "fieldId": held.field_id,
4217 "singleSelectOptions": options,
4218 }}),
4219 )
4220 .await
4221 }
4222 None => {
4223 self.graphql(
4224 graphql::CREATE_FIELD,
4225 json!({"input": {
4226 "projectId": before.board_id, "dataType": "SINGLE_SELECT",
4227 "name": field.field.name(),
4228 "singleSelectOptions": added.collect::<Vec<_>>(),
4229 }}),
4230 )
4231 .await
4232 }
4233 };
4234 // A mutation that failed does not establish that GitHub left its field as it was,
4235 // so every failure from here on carries the recovery data a drift refusal does.
4236 match sent {
4237 Ok(_) => landed.push(field.field.name()),
4238 Err(error) => {
4239 let changed = if landed.is_empty() {
4240 String::new()
4241 } else {
4242 format!("changed the {} field and then ", landed.join(" and "))
4243 };
4244 return Err(SourceError::Refused {
4245 message: format!(
4246 "the guarded field setup {changed}failed on the {} field, which it may \
4247 have changed part way: {error}; the pre-write item assignments \
4248 are:\n{}",
4249 field.field.name(),
4250 recovery(&report, &before)?
4251 ),
4252 });
4253 }
4254 }
4255 }
4256 for field in &creates {
4257 let sent = self
4258 .graphql(
4259 graphql::CREATE_FIELD,
4260 json!({"input": {
4261 "projectId": before.board_id, "dataType": "TEXT", "name": field.field,
4262 }}),
4263 )
4264 .await;
4265 if let Err(error) = sent {
4266 let changed = if landed.is_empty() {
4267 String::new()
4268 } else {
4269 format!("changed the {} field and then ", landed.join(" and "))
4270 };
4271 return Err(SourceError::Refused {
4272 message: format!(
4273 "the guarded field setup {changed}failed creating the {} text field: \
4274 {error}; run it again to create what is still missing",
4275 field.field
4276 ),
4277 });
4278 }
4279 landed.push(&field.field);
4280 }
4281 // The board has been written, so a verification read that fails leaves it unverified
4282 // rather than unchanged, and says what to put back.
4283 let after = match self.board_snapshot(&owned).await {
4284 Ok(after) => after,
4285 Err(error) => {
4286 return Err(SourceError::Refused {
4287 message: format!(
4288 "the guarded field setup changed the {} field and then could not read the \
4289 board back to verify it: {error}; the pre-write item assignments are:\n{}",
4290 landed.join(" and "),
4291 recovery(&report, &before)?
4292 ),
4293 });
4294 }
4295 };
4296 let mut moved = Vec::new();
4297 for field in &report.fields {
4298 let name = field.field.name();
4299 let now = after
4300 .fields
4301 .get(&field.field)
4302 .map(|held| held.options.as_slice())
4303 .unwrap_or_default();
4304 if !field.existing.iter().all(|old| now.contains(old)) {
4305 moved.push(format!(
4306 "a pre-existing {name} option id, name, color or description"
4307 ));
4308 }
4309 if !field.missing.iter().all(|wanted| {
4310 now.iter()
4311 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4312 }) {
4313 moved.push(format!("an added {name} option"));
4314 }
4315 if after.assignments(field.field) != before.assignments(field.field) {
4316 moved.push(format!("an item's {name} value"));
4317 }
4318 }
4319 if !creates.is_empty() {
4320 // Read afresh: the view held for this command is the one from before the creates.
4321 *self.fields_cache()? = None;
4322 let board = match self.board_fields().await {
4323 Ok(board) => board,
4324 Err(error) => {
4325 return Err(SourceError::Refused {
4326 message: format!(
4327 "the guarded field setup changed the {} field and then could not \
4328 read the board back to verify it: {error}; run it again to verify \
4329 it, which creates nothing a second time",
4330 landed.join(" and ")
4331 ),
4332 });
4333 }
4334 };
4335 for field in &creates {
4336 let text = Board::field(&board.fields, &field.field)?.is_some_and(|held| {
4337 held.get("__typename").and_then(Value::as_str) == Some("ProjectV2Field")
4338 && held.get("dataType").and_then(Value::as_str) == Some("TEXT")
4339 });
4340 if !text {
4341 moved.push(format!("the created {} text field", field.field));
4342 }
4343 }
4344 }
4345 if !moved.is_empty() {
4346 return Err(SourceError::Refused {
4347 message: format!(
4348 "GitHub changed {} after the guarded field setup; the pre-write item \
4349 assignments are:\n{}",
4350 moved.join(", "),
4351 recovery(&report, &before)?
4352 ),
4353 });
4354 }
4355 Ok(report)
4356 }
4357
4358 /// Validate configuration and capture the named credential without exposing it.
4359 ///
4360 /// # Errors
4361 ///
4362 /// Returns [`SourceError::Config`] for a configuration this instance cannot use and
4363 /// [`SourceError::Auth`] when the named credential is missing or empty.
4364 pub fn new(
4365 name: &SourceName,
4366 config: GitHubProjectsConfig,
4367 secrets: &dyn SecretResolver,
4368 ) -> Result<Self, SourceError> {
4369 Self::recording_into(name, config, secrets, Arc::new(Accounting::new()))
4370 }
4371
4372 /// The same, recording every request it sends into an accounting the caller holds too.
4373 ///
4374 /// [`Self::new`] is this with an accounting of its own. A caller that is also making
4375 /// its own calls to GitHub — a lane verifying a schema, sweeping residue or cleaning
4376 /// up — passes the one it records those into, so the session total accounts for the
4377 /// whole session rather than for this source's share of it.
4378 ///
4379 /// # Errors
4380 ///
4381 /// Exactly [`Self::new`]'s: [`SourceError::Config`] for a configuration this instance
4382 /// cannot use and [`SourceError::Auth`] when the named credential is missing or empty.
4383 pub fn recording_into(
4384 name: &SourceName,
4385 config: GitHubProjectsConfig,
4386 secrets: &dyn SecretResolver,
4387 ledger: Arc<Accounting>,
4388 ) -> Result<Self, SourceError> {
4389 if !valid_github_owner(&config.owner) {
4390 return Err(SourceError::Config {
4391 message: "owner must be 1-39 ASCII letters, digits, or single hyphens, and cannot start or end with a hyphen".into(),
4392 });
4393 }
4394 if config.project_number == 0 || config.project_number > i32::MAX as u32 {
4395 return Err(SourceError::Config {
4396 message: format!("project_number must be between 1 and {}", i32::MAX),
4397 });
4398 }
4399 if !valid_environment_name(&config.token_env) {
4400 return Err(SourceError::Config {
4401 message: "token_env must be a valid environment-variable name".into(),
4402 });
4403 }
4404 let repository = config
4405 .repository
4406 .as_deref()
4407 .map(RepositoryTarget::parse)
4408 .transpose()?;
4409 let endpoint = Url::parse(&config.endpoint).map_err(|e| SourceError::Config {
4410 message: format!("endpoint is not a valid URL: {e}"),
4411 })?;
4412 if endpoint.scheme() != "https"
4413 && !(endpoint.scheme() == "http"
4414 && endpoint
4415 .host_str()
4416 .is_some_and(|h| h == "127.0.0.1" || h == "localhost" || h == "::1"))
4417 {
4418 return Err(SourceError::Config {
4419 message:
4420 "endpoint must use HTTPS (HTTP is accepted only for a loopback test server)"
4421 .into(),
4422 });
4423 }
4424 let token = secrets.get(&config.token_env).filter(|token| !token.expose_secret().trim().is_empty()).ok_or_else(|| SourceError::Auth {
4425 message: format!("environment variable {} is missing or empty; set it to a fine-grained GitHub token granting Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board", config.token_env),
4426 })?;
4427 Ok(Self {
4428 name: name.clone(),
4429 owner: config.owner,
4430 project_number: config.project_number,
4431 repository,
4432 asset_client: assets::client(&endpoint)?,
4433 endpoint,
4434 token,
4435 credential_name: config.token_env,
4436 statuses: BoardStatuses::resolve(&config.status_mapping, name)?,
4437 priorities: config
4438 .priority_mapping
4439 .map(|mapping| PriorityMapping::resolve(mapping, name))
4440 .transpose()?,
4441 metadata_fields: MetadataField::resolve(config.metadata_fields, name)?,
4442 client: Client::builder()
4443 .user_agent("onetaskgraph")
4444 .build()
4445 .map_err(|e| SourceError::Config {
4446 message: format!("cannot build HTTP client: {e}"),
4447 })?,
4448 created: Mutex::new(Vec::new()),
4449 updated: Mutex::new(Vec::new()),
4450 commented: Mutex::new(Vec::new()),
4451 pacing: Pacing::resolve(config.pacing, name)?,
4452 last_mutation: Mutex::new(None),
4453 clock: system_clock(),
4454 numeric_repositories: tokio::sync::Mutex::new(BTreeMap::new()),
4455 board_cache: Mutex::new(None),
4456 search_cache: Mutex::new(None),
4457 narrowed_cache: Mutex::new(BTreeMap::new()),
4458 resolved_cache: Mutex::new(BTreeMap::new()),
4459 held_cache: Mutex::new(BTreeMap::new()),
4460 children_cache: Mutex::new(BTreeMap::new()),
4461 search_next: Mutex::new(BTreeMap::new()),
4462 fields_cache: Mutex::new(None),
4463 repository_cache: Mutex::new(BTreeMap::new()),
4464 ledger,
4465 expected: expected::Held::default(),
4466 })
4467 }
4468
4469 /// A snapshot of every request this source has sent, and what each cost.
4470 ///
4471 /// A value to hold and compare rather than a borrow of the accounting itself, so two
4472 /// of them can sit side by side. When this source was built with
4473 /// [`Self::recording_into`] the snapshot is the whole shared session, which is the
4474 /// point of building it that way.
4475 #[must_use]
4476 pub fn accounting(&self) -> accounting::Session {
4477 self.ledger.snapshot()
4478 }
4479
4480 /// Send one GraphQL document, pacing this source's own mutations and waiting out a
4481 /// rate limit rather than handing it straight back as an error.
4482 ///
4483 /// Retrying is safe for every document here, including the mutations, and the reason
4484 /// is that only a *refusal* is retried: [`Limiter::classify`] rules on a response
4485 /// GitHub sent, and a request GitHub refused for a rate limit did not run, so nothing
4486 /// this replays has already taken effect. An outcome this source cannot know — the
4487 /// send failed, or the body could not be read, so the mutation may well have landed —
4488 /// is [`Attempt::Failed`] in [`send_once`] and leaves this loop without a second
4489 /// attempt. A duplicate write would come from replaying one of those, and none is
4490 /// replayed.
4491 async fn graphql(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
4492 if !self.expected.journaling() {
4493 return self.graphql_sent(query, variables).await;
4494 }
4495 // While a write the store's cache expects runs, its mutations select the whole issue
4496 // they leave behind, so the response vouches for what the cache keeps — and every
4497 // request is recorded, so the write's parts are reported from their own responses.
4498 let (query, variables) = match graphql::whole_twin(query) {
4499 Some(twin) => (twin, expected::whole_variables(variables)),
4500 None => (query, variables),
4501 };
4502 let sent = self.graphql_sent(query, variables.clone()).await;
4503 self.journal(query, &variables, &sent).await;
4504 sent
4505 }
4506
4507 /// One document sent, retried while GitHub asks for a wait, exactly as asked.
4508 async fn graphql_sent(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
4509 if is_mutation(query)
4510 && ![
4511 graphql::ADD_COMMENT,
4512 graphql::UPDATE_COMMENT,
4513 graphql::DELETE_COMMENT,
4514 graphql::ADD_COMMENT_WHOLE,
4515 graphql::UPDATE_COMMENT_WHOLE,
4516 ]
4517 .contains(&query)
4518 {
4519 let mut cache = self.resolved_cache()?;
4520 for argument in ["input", "second", "third", "clear"] {
4521 if let Some(input) = variables.get(argument) {
4522 cache.retain(|id, item| {
4523 !["id", "issueId", "subjectId", "itemId"].iter().any(|key| {
4524 input
4525 .get(key)
4526 .and_then(Value::as_str)
4527 .is_some_and(|value| value == id.0 || value == item.item_id)
4528 })
4529 });
4530 }
4531 }
4532 }
4533 let doing = operation_description(query);
4534 let mut waited = Duration::ZERO;
4535 let mut waits = 0_u32;
4536 let mut backoff = self.pacing.retry_backoff;
4537 loop {
4538 if is_mutation(query) {
4539 let spacing = self.reserve_mutation_slot();
4540 if !spacing.is_zero() {
4541 self.clock.sleep(spacing).await;
4542 }
4543 }
4544 let attempt = self.send_once(query, &variables, waits + 1).await;
4545 if is_mutation(query) {
4546 self.finish_mutation();
4547 }
4548 let limited = match attempt {
4549 Ok(data) => return Ok(data),
4550 Err(Attempt::Failed(error)) => return Err(error),
4551 Err(Attempt::Limited(limited)) => limited,
4552 };
4553 // GitHub really does send `retry-after: 0`, and retrying at once is the one
4554 // move that extends a secondary limit, so a hint below the schedule's own next
4555 // wait is raised to it.
4556 let wait = match limited.hint {
4557 Some(hint) => Duration::from_secs(hint).max(backoff),
4558 None => backoff,
4559 };
4560 let remaining = self.pacing.retry_budget.saturating_sub(waited);
4561 // A wait of nothing spends none of the budget, so it is exhaustion rather
4562 // than a retry. `Pacing::resolve` rules out every way of configuring one
4563 // except a budget of zero, where reporting the first refusal is the ask.
4564 if wait.is_zero() || wait > remaining {
4565 return Err(limited.exhausted(
4566 doing,
4567 waits,
4568 waited,
4569 wait,
4570 self.pacing.retry_budget,
4571 ));
4572 }
4573 self.clock.sleep(wait).await;
4574 waited += wait;
4575 waits += 1;
4576 backoff = backoff.saturating_mul(2);
4577 }
4578 }
4579
4580 /// The next moment a content-creating mutation may leave this source, as a wait from
4581 /// now.
4582 ///
4583 /// The slot is reserved under the lock and the waiting happens outside it, so two
4584 /// callers take two slots rather than the same one — and no lock is held across an
4585 /// await.
4586 ///
4587 /// The moment it is spaced from is the previous mutation's *completion*, which
4588 /// [`Self::finish_mutation`] records. See that method for why the release moment on its
4589 /// own is the wrong thing to measure from.
4590 fn reserve_mutation_slot(&self) -> Duration {
4591 if self.pacing.min_mutation_interval.is_zero() {
4592 return Duration::ZERO;
4593 }
4594 // A poisoned lock here costs pacing, not correctness, and refusing the write over
4595 // it would turn an earlier failure into a second one for no gain.
4596 let mut last = self
4597 .last_mutation
4598 .lock()
4599 .unwrap_or_else(std::sync::PoisonError::into_inner);
4600 let now = self.clock.now();
4601 // `checked_add` rather than `+`: adding durations can panic on overflow, and
4602 // pacing is not worth a panic even at a bound `MAX_PACING_MS` already rules out.
4603 let at = last.map_or(now, |previous| {
4604 previous
4605 .checked_add(self.pacing.min_mutation_interval)
4606 .map_or(now, |earliest| earliest.max(now))
4607 });
4608 *last = Some(at);
4609 at.saturating_sub(now)
4610 }
4611
4612 /// Record that a content-creating mutation has finished, so the next one is spaced
4613 /// from here rather than from the moment this one was released.
4614 ///
4615 /// This source can only choose when a request *departs*; the limiter counts when it
4616 /// *arrives*, and the two differ by whatever the request spent in transit. Spacing one
4617 /// departure from the last therefore hands the limiter a gap of the interval less that
4618 /// transit, so a source pacing at 750 ms can still be seen arriving faster — which is
4619 /// exactly how a copy paced well inside a board's threshold was refused by it on a
4620 /// slower machine while passing on a quick one.
4621 ///
4622 /// Spacing from completion removes the subtraction rather than budgeting for it. The
4623 /// previous request had already arrived before its response came back, so its arrival
4624 /// is no later than this moment, and the next mutation is released at least the
4625 /// interval after this moment and arrives no earlier than it is released: the gap the
4626 /// limiter measures is therefore at least the interval, whatever transit costs and on
4627 /// whatever platform. The price is that a mutation's own round trip no longer counts
4628 /// towards its spacing, which makes this source slightly slower than the configured
4629 /// rate rather than slightly faster — the safe side of a limit that punishes being
4630 /// wrong by refusing reads for the next fifty minutes.
4631 ///
4632 /// A failed attempt is recorded too: a request refused by the limiter still arrived,
4633 /// and one that never left costs only a wait nobody needed.
4634 fn finish_mutation(&self) {
4635 if self.pacing.min_mutation_interval.is_zero() {
4636 return;
4637 }
4638 // A poisoned lock here costs pacing, not correctness, exactly as in the reservation.
4639 let mut last = self
4640 .last_mutation
4641 .lock()
4642 .unwrap_or_else(std::sync::PoisonError::into_inner);
4643 let now = self.clock.now();
4644 // `max` rather than an assignment: a concurrent caller may already have reserved a
4645 // slot further out, and completing this request must never pull that slot back in.
4646 *last = Some(last.map_or(now, |reserved| reserved.max(now)));
4647 }
4648
4649 /// One HTTP attempt, classified into an answer, a rate limit to wait out, or a
4650 /// failure that waiting cannot help — and recorded, whichever of the three it was.
4651 ///
4652 /// This is the one place a request leaves this crate, which is why the accounting is
4653 /// here rather than at each of the callers: a read path added later is counted without
4654 /// anybody remembering to count it, and
4655 /// `the_session_report_counts_every_request_the_board_served_and_what_each_cost` fails
4656 /// when one is not.
4657 async fn send_once(
4658 &self,
4659 query: &str,
4660 variables: &Value,
4661 number: u32,
4662 ) -> Result<Value, Attempt> {
4663 let executed = self.ledger.priced_document(query);
4664 let Attempted {
4665 result,
4666 limits,
4667 reported_cost,
4668 response_outcome,
4669 } = self.attempt(executed.as_ref(), variables).await;
4670 // No `otherwise` name: every document this source sends is one of its own, and the
4671 // inventory gate on `graphql::DOCUMENTS` is what keeps that true.
4672 let sending = accounting::Request::graphql(query, variables, None, reported_cost);
4673 let outcome = match &result {
4674 Ok(_) => accounting::Outcome::Answered,
4675 Err(Attempt::Limited(_)) => accounting::Outcome::RateLimited,
4676 Err(Attempt::Failed(_)) => accounting::Outcome::Refused,
4677 };
4678 self.ledger
4679 .record(sending.finished(outcome, limits).with_execution(
4680 Some(executed.into_owned()),
4681 response_outcome,
4682 number,
4683 ));
4684 result
4685 }
4686
4687 /// The attempt itself, with what its response said about the rate limit alongside.
4688 ///
4689 /// The two are returned together rather than recorded here because every one of the
4690 /// early exits below is a different outcome, and a record written at each of them is a
4691 /// record one of them can be added without.
4692 async fn attempt(&self, query: &str, variables: &Value) -> Attempted {
4693 let mut limits = accounting::RateLimit::default();
4694 let mut reported_cost = None;
4695 let mut response_outcome = accounting::ResponseOutcome::TransportError;
4696 let result = self
4697 .attempted(
4698 query,
4699 variables,
4700 &mut limits,
4701 &mut reported_cost,
4702 &mut response_outcome,
4703 )
4704 .await;
4705 Attempted {
4706 result,
4707 limits,
4708 reported_cost,
4709 response_outcome,
4710 }
4711 }
4712
4713 /// One HTTP attempt, filling in what its response said about the rate limit as it goes.
4714 async fn attempted(
4715 &self,
4716 query: &str,
4717 variables: &Value,
4718 limits: &mut accounting::RateLimit,
4719 reported_cost: &mut Option<u64>,
4720 response_outcome: &mut accounting::ResponseOutcome,
4721 ) -> Result<Value, Attempt> {
4722 let response = self
4723 .client
4724 .post(self.endpoint.clone())
4725 .bearer_auth(self.token.expose_secret())
4726 .json(&json!({"query": query, "variables": variables}))
4727 .send()
4728 .await
4729 .map_err(|e| {
4730 Attempt::Failed(SourceError::Unavailable {
4731 message: format!("GitHub GraphQL request failed: {e}"),
4732 })
4733 })?;
4734 let status = response.status();
4735 if !status.is_success() {
4736 *response_outcome = accounting::ResponseOutcome::HttpError;
4737 }
4738 let header = |name: &str| whole_seconds(response.headers().get(name));
4739 let served = response
4740 .headers()
4741 .get(reqwest::header::DATE)
4742 .and_then(|value| value.to_str().ok())
4743 .and_then(|value| DateTime::parse_from_rfc2822(value).ok())
4744 .map(|at| at.with_timezone(&Utc));
4745 *limits = accounting::RateLimit::read(|name| {
4746 response
4747 .headers()
4748 .get(name)
4749 .and_then(|value| value.to_str().ok())
4750 .map(str::to_owned)
4751 });
4752 // Exactly `0` is exhaustion and everything else — a count, an empty value, bytes
4753 // that are not text at all — is "not known to be exhausted". This never makes a
4754 // response a refusal on its own: it says which limiter a refusal is attributed to
4755 // and where its hint comes from, so a value this cannot read costs a hint rather
4756 // than an answer.
4757 let exhausted = response
4758 .headers()
4759 .get("x-ratelimit-remaining")
4760 .and_then(|value| value.to_str().ok())
4761 == Some("0");
4762 // `retry-after` is what GitHub asks for when it asks; when it does not and the
4763 // primary budget is spent, `x-ratelimit-reset` says when that budget comes back,
4764 // which is the same question answered as an absolute time. Nothing else here is a
4765 // hint, and a schedule is what answers a refusal that carries none.
4766 let hint = header("retry-after").or_else(|| {
4767 exhausted
4768 .then(|| header("x-ratelimit-reset"))
4769 .flatten()
4770 .map(|reset| reset.saturating_sub(Utc::now().timestamp().max(0).unsigned_abs()))
4771 });
4772 // Read before it is parsed, because the evidence which tells a secondary rate
4773 // limit from a rejected credential is in the body of a response whose status says
4774 // only "forbidden" — and a non-success response was never parsed at all.
4775 let body = response.text().await.map_err(|e| {
4776 Attempt::Failed(SourceError::Unavailable {
4777 message: format!("GitHub GraphQL response could not be read: {e}"),
4778 })
4779 })?;
4780 *reported_cost = serde_json::from_str::<Value>(&body)
4781 .ok()
4782 .as_ref()
4783 .and_then(|body| body.pointer("/data/rateLimit/cost"))
4784 .and_then(Value::as_u64);
4785 let parsed = serde_json::from_str::<Value>(&body).ok();
4786 *response_outcome = accounting::ResponseOutcome::of_graphql_reply(status, parsed.as_ref());
4787 if let Some(limiter) = Limiter::classify(status, exhausted, &body) {
4788 return Err(Attempt::Limited(Limited { limiter, hint }));
4789 }
4790 if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
4791 return Err(Attempt::Failed(SourceError::Auth {
4792 message: format!(
4793 "GitHub rejected the configured credential with HTTP {status}; grant it Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board"
4794 ),
4795 }));
4796 }
4797 if !status.is_success() {
4798 return Err(Attempt::Failed(SourceError::Unavailable {
4799 message: format!("GitHub GraphQL returned HTTP {status}"),
4800 }));
4801 }
4802 let answered = if query == graphql::ISSUES_BY_REFERENCE {
4803 self.answer_unresolved(&body)
4804 } else {
4805 self.answer(&body)
4806 };
4807 let mut data = answered.map_err(Attempt::Failed)?;
4808 if let Some(served) = served {
4809 stamp_served(&mut data, &served.to_rfc3339());
4810 }
4811 Ok(data)
4812 }
4813
4814 /// What one successful HTTP response says, once its GraphQL errors are read.
4815 /// [`Self::answer`], for a read of issues by reference: a reference GitHub cannot resolve
4816 /// for this credential — a repository it cannot see, an issue number it does not hold —
4817 /// is answered `null` beside a `NOT_FOUND` error naming it, and that is an answer about
4818 /// that reference rather than a failure of the others. Any other error refuses the read,
4819 /// as there.
4820 fn answer_unresolved(&self, body: &str) -> Result<Value, SourceError> {
4821 let parsed: Option<Value> = serde_json::from_str(body).ok();
4822 // Each error is a `NOT_FOUND` whose path names one slot of the batch, `r<n>` or its
4823 // `issue`, and the answer holds `null` at exactly that path: anything else — another
4824 // kind of error, one naming no slot, or one beside a value it says is not there — is a
4825 // refusal of the whole read.
4826 let unresolved = |data: &Value, error: &Value| {
4827 error.get("type").and_then(Value::as_str) == Some("NOT_FOUND")
4828 && error
4829 .get("path")
4830 .and_then(Value::as_array)
4831 .is_some_and(|path| {
4832 let alias = path.first().and_then(Value::as_str).and_then(|alias| {
4833 alias
4834 .strip_prefix('r')
4835 .and_then(|slot| slot.parse::<usize>().ok())
4836 .filter(|slot| *slot < REFERENCE_BATCH)
4837 .map(|_| alias)
4838 });
4839 match (alias, path.get(1).and_then(Value::as_str), path.len()) {
4840 (Some(alias), None, 1) => data.get(alias).is_some_and(Value::is_null),
4841 (Some(alias), Some("issue"), 2) => data
4842 .get(alias)
4843 .and_then(|repository| repository.get("issue"))
4844 .is_some_and(Value::is_null),
4845 _ => false,
4846 }
4847 })
4848 };
4849 let unresolved_only = parsed.as_ref().is_some_and(|parsed| {
4850 parsed.get("data").is_some_and(|data| {
4851 data.is_object()
4852 && parsed
4853 .get("errors")
4854 .and_then(Value::as_array)
4855 .is_some_and(|errors| errors.iter().all(|error| unresolved(data, error)))
4856 })
4857 });
4858 match parsed {
4859 Some(parsed) if unresolved_only => Ok(parsed["data"].clone()),
4860 _ => self.answer(body),
4861 }
4862 }
4863
4864 fn answer(&self, body: &str) -> Result<Value, SourceError> {
4865 let body: Value = serde_json::from_str(body).map_err(|e| SourceError::Malformed {
4866 message: format!("GitHub returned invalid JSON: {e}"),
4867 })?;
4868 let errors = body
4869 .get("errors")
4870 .map(|value| {
4871 value.as_array().ok_or_else(|| SourceError::Malformed {
4872 message: "GitHub response errors is not an array".into(),
4873 })
4874 })
4875 .transpose()?;
4876 if let Some(errors) = errors.filter(|errors| !errors.is_empty()) {
4877 let messages = errors
4878 .iter()
4879 .filter_map(|e| e.get("message").and_then(Value::as_str))
4880 .collect::<Vec<_>>()
4881 .join("; ");
4882 let message = if messages.is_empty() {
4883 "GitHub returned GraphQL errors".into()
4884 } else {
4885 messages
4886 };
4887 let normalized = message.to_ascii_lowercase();
4888 if normalized.contains("resource not accessible") || normalized.contains("scope") {
4889 return Err(SourceError::Auth {
4890 message: format!(
4891 "{message}; grant {} Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board",
4892 self.credential_name
4893 ),
4894 });
4895 }
4896 return Err(SourceError::Refused { message });
4897 }
4898 body.get("data")
4899 .filter(|data| data.is_object())
4900 .cloned()
4901 .ok_or_else(|| SourceError::Malformed {
4902 message: "GitHub response has no data object".into(),
4903 })
4904 }
4905
4906 // llmlint: ignore[boundary_inputs_validated] GitHub caps nested connections at 100 and
4907 // GraphQL cannot independently page them inside the outer item page. This source page is
4908 // deliberately bounded at that published maximum; the live drift journey exercises it.
4909 async fn board_page(
4910 &self,
4911 items_after: Option<&str>,
4912 items_first: u32,
4913 ) -> Result<Value, SourceError> {
4914 let data = self
4915 .graphql(
4916 graphql::BOARD,
4917 json!({"owner":self.owner,"number":self.project_number,
4918 "first":items_first.min(MAX_PAGE_SIZE),"after":items_after,
4919 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
4920 )
4921 .await?;
4922 data.pointer("/owner/projectV2")
4923 .filter(|v| !v.is_null())
4924 .cloned()
4925 .ok_or_else(|| SourceError::Refused {
4926 message: format!(
4927 "GitHub project {}/{} was not found or is not visible to the token",
4928 self.owner, self.project_number
4929 ),
4930 })
4931 }
4932
4933 /// The search that finds the issues of this board, narrowed by `also` when it is
4934 /// given.
4935 ///
4936 /// `project:owner/number` is what scopes a search to one board, and `is:issue` is what
4937 /// keeps pull requests out of it: GitHub's `ISSUE` search type covers both, and a pull
4938 /// request is somebody's change rather than a unit of plan. `-has:parent` is *not*
4939 /// here on purpose — GitHub accepts it and silently ignores it, so a project is told
4940 /// from a task by the `parent` field each issue carries rather than by the search.
4941 fn board_search(&self, also: Option<&str>) -> String {
4942 let scope = format!("project:{}/{} is:issue", self.owner, self.project_number);
4943 match also {
4944 Some(also) => format!("{scope} {also}"),
4945 None => scope,
4946 }
4947 }
4948
4949 /// One issue this source reached directly, as the board item a read of the board would
4950 /// have produced — or `None` when this board does not hold it.
4951 ///
4952 /// The board half of an issue rides along on `Issue.projectItems`, so the value handed
4953 /// to [`Self::resolve`] is the very shape a `ProjectV2.items` read gives it: the board
4954 /// item's own id, that item's field values, and the issue as its content. One resolver
4955 /// for both routes is what makes an issue read through a search, through its own node
4956 /// id, or through its project's sub-issues report the same title, the same status, the
4957 /// same labels and the same qualified id.
4958 ///
4959 /// An issue with no entry for *this* board is not this source's to report, which is
4960 /// what keeps an id naming some other repository's issue from being answered as an item
4961 /// of this board. That answer is given about an **exhausted** connection and never
4962 /// about an unread page: the entry is looked for on the page in hand, and only if that
4963 /// page reports more of the connection, in [`Self::board_membership`]'s walk of the
4964 /// rest of it.
4965 async fn resolve_issue(&self, issue: &Value) -> Result<Option<Resolved>, SourceError> {
4966 self.resolve_issue_as(issue, true).await
4967 }
4968
4969 /// [`Self::resolve_issue`], remembering what it resolves for this command's later reads
4970 /// and writes only when `remember` says to.
4971 async fn resolve_issue_as(
4972 &self,
4973 issue: &Value,
4974 remember: bool,
4975 ) -> Result<Option<Resolved>, SourceError> {
4976 if optional_str(issue, "__typename")? != Some("Issue") {
4977 return Ok(None);
4978 }
4979 let memberships = issue
4980 .get("projectItems")
4981 .ok_or_else(|| SourceError::Malformed {
4982 message: "GitHub issue is missing projectItems".into(),
4983 })?;
4984 let nodes = memberships
4985 .get("nodes")
4986 .and_then(Value::as_array)
4987 .ok_or_else(|| SourceError::Malformed {
4988 message: "GitHub issue projectItems.nodes is not an array".into(),
4989 })?;
4990 let held = match self.board_entry(nodes) {
4991 Some(held) => held.clone(),
4992 None => {
4993 let info = memberships
4994 .get("pageInfo")
4995 .ok_or_else(|| SourceError::Malformed {
4996 message: "GitHub issue projectItems has no pageInfo".into(),
4997 })?;
4998 // The page held no entry for this board. Whether that means the issue is
4999 // not on it is a question about the rest of the connection, and only a
5000 // connection with no rest answers it here.
5001 if !required_bool(info, "hasNextPage")? {
5002 return Ok(None);
5003 }
5004 let cursor = required_str(info, "endCursor")?;
5005 validate_cursor_progress(None, cursor)?;
5006 let issue_id = required_str(issue, "id")?;
5007 match self.board_membership(issue_id, cursor).await? {
5008 Some(held) => held,
5009 None => return Ok(None),
5010 }
5011 }
5012 };
5013 // The membership's own `updatedAt` rides along: it is the board half of the item's change
5014 // token, which a field change moves where the issue's own time does not.
5015 let item = json!({
5016 "id": required_str(&held, "id")?,
5017 "updatedAt": held.get("updatedAt"),
5018 "project": held.get("project"),
5019 "fieldValues": held.get("fieldValues"),
5020 "content": issue,
5021 });
5022 if remember {
5023 self.resolve(&item)
5024 } else {
5025 self.resolve_unremembered(&item)
5026 }
5027 }
5028
5029 /// This board's own entry among one page of an issue's `Issue.projectItems`.
5030 ///
5031 /// One spelling of *which membership is this board's*, so the page a read carries and
5032 /// the pages [`Self::board_membership`] walks are searched by the same rule.
5033 fn board_entry<'a>(&self, nodes: &'a [Value]) -> Option<&'a Value> {
5034 nodes.iter().find(|node| {
5035 node.pointer("/project/number").and_then(Value::as_u64)
5036 == Some(u64::from(self.project_number))
5037 })
5038 }
5039
5040 /// The rest of one issue's board memberships, from `after`, for this board's entry.
5041 ///
5042 /// The recovery read: a page of memberships that holds no entry for this board says
5043 /// nothing about the memberships past it, so the connection is walked to exhaustion
5044 /// before an issue is reported as one this board does not hold. `Ok(None)` is that
5045 /// positive answer — the whole connection was read and no entry named this board —
5046 /// rather than a failure, and the walk is held to
5047 /// [`validate_cursor_progress`] like every other page walk here, so a source answering
5048 /// with a cursor that does not advance is refused instead of spun on.
5049 async fn board_membership(
5050 &self,
5051 issue: &str,
5052 after: &str,
5053 ) -> Result<Option<Value>, SourceError> {
5054 let mut after = after.to_owned();
5055 loop {
5056 let data = self
5057 .graphql(
5058 graphql::ISSUE_BOARD_ITEMS,
5059 json!({"id":issue,"first":MAX_PAGE_SIZE,"after":after,
5060 "nestedFirst":NESTED_PAGE_SIZE}),
5061 )
5062 .await?;
5063 let Some(connection) = data
5064 .pointer("/node/projectItems")
5065 .filter(|value| !value.is_null())
5066 else {
5067 // The id resolved to nothing, or to something with no memberships to walk —
5068 // which is the same answer as a connection holding no entry for this board.
5069 return Ok(None);
5070 };
5071 let nodes = connection
5072 .get("nodes")
5073 .and_then(Value::as_array)
5074 .ok_or_else(|| SourceError::Malformed {
5075 message: "GitHub issue projectItems.nodes is not an array".into(),
5076 })?;
5077 if let Some(held) = self.board_entry(nodes) {
5078 return Ok(Some(held.clone()));
5079 }
5080 let info = connection
5081 .get("pageInfo")
5082 .ok_or_else(|| SourceError::Malformed {
5083 message: "GitHub issue projectItems has no pageInfo".into(),
5084 })?;
5085 let next = required_bool(info, "hasNextPage")?
5086 .then(|| required_str(info, "endCursor"))
5087 .transpose()?;
5088 match next {
5089 Some(next) => {
5090 validate_cursor_progress(Some(&after), next)?;
5091 after = next.to_owned();
5092 }
5093 None => return Ok(None),
5094 }
5095 }
5096 }
5097
5098 /// One page of a board-scoped issue search, and where the next page resumes.
5099 async fn search_page(
5100 &self,
5101 search: &str,
5102 first: u32,
5103 after: Option<&str>,
5104 ) -> Result<(Vec<Resolved>, Option<String>), SourceError> {
5105 let data = self
5106 .graphql(
5107 graphql::SEARCH_ISSUES,
5108 json!({"search":search,"type":"ISSUE","first":first.min(MAX_PAGE_SIZE),
5109 "after":after,"nestedFirst":NESTED_PAGE_SIZE,
5110 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
5111 )
5112 .await?;
5113 let connection = data.get("search").ok_or_else(|| SourceError::Malformed {
5114 message: "GitHub search response has no search connection".into(),
5115 })?;
5116 let mut found = Vec::new();
5117 for node in connection
5118 .get("nodes")
5119 .and_then(Value::as_array)
5120 .ok_or_else(|| SourceError::Malformed {
5121 message: "GitHub search nodes is not an array".into(),
5122 })?
5123 {
5124 if let Some(resolved) = self.resolve_issue(node).await? {
5125 found.push(resolved);
5126 }
5127 }
5128 let info = connection
5129 .get("pageInfo")
5130 .ok_or_else(|| SourceError::Malformed {
5131 message: "GitHub search connection has no pageInfo".into(),
5132 })?;
5133 let next = required_bool(info, "hasNextPage")?
5134 .then(|| required_str(info, "endCursor"))
5135 .transpose()?
5136 .map(str::to_owned);
5137 if let Some(next) = &next {
5138 validate_cursor_progress(after, next)?;
5139 }
5140 Ok((found, next))
5141 }
5142
5143 /// Every issue this board holds, completed with what this run wrote.
5144 ///
5145 /// The completion is not an optimisation and it is not a cache: GitHub's issue search
5146 /// is an index and is eventually consistent, so an issue this run created seconds ago
5147 /// can be absent from it, and a project listed straight after being written would
5148 /// otherwise be missing from its own board. What is added back is only what this
5149 /// process itself wrote, out of [`Self::created`], which lives and dies with the
5150 /// process.
5151 async fn board_issues(&self) -> Result<Vec<Resolved>, SourceError> {
5152 let found = self.searched_issues().await?;
5153 self.completed_with_written(found, |_| true)
5154 }
5155
5156 /// Every issue this board's own search reports, walked to exhaustion, read once per
5157 /// source.
5158 ///
5159 /// The uncompleted half of [`Self::board_issues`], separated because [`Self::board`]
5160 /// needs it too and the two would otherwise walk the same search twice in one command.
5161 /// See [`Self::search_cache`] for why holding it is the same bargain holding the board
5162 /// is.
5163 async fn searched_issues(&self) -> Result<Vec<Resolved>, SourceError> {
5164 let cached = self.search_cache()?.clone();
5165 if let Some(held) = cached {
5166 return Ok(held);
5167 }
5168 let mut after: Option<String> = None;
5169 let mut found = Vec::new();
5170 let search = self.board_search(None);
5171 loop {
5172 let (page, next) = self
5173 .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
5174 .await?;
5175 found.extend(page);
5176 match next {
5177 Some(next) => after = Some(next),
5178 None => break,
5179 }
5180 }
5181 *self.search_cache()? = Some(found.clone());
5182 Ok(found)
5183 }
5184
5185 /// Every issue this board's own search reports with `also` beside its scope, walked to
5186 /// exhaustion — held for no later read, which may not be narrowed alike.
5187 async fn searched_narrowly(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
5188 let mut after: Option<String> = None;
5189 let mut found = Vec::new();
5190 let search = self.board_search(Some(also));
5191 loop {
5192 let (page, next) = self
5193 .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
5194 .await?;
5195 found.extend(page);
5196 match next {
5197 Some(next) => after = Some(next),
5198 None => return Ok(found),
5199 }
5200 }
5201 }
5202
5203 /// This process's own view of the board's issues, or the refusal a poisoned lock is.
5204 fn search_cache(
5205 &self,
5206 ) -> Result<std::sync::MutexGuard<'_, Option<Vec<Resolved>>>, SourceError> {
5207 self.search_cache
5208 .lock()
5209 .map_err(|_| SourceError::Unavailable {
5210 message: "this source's view of the board's issues was left inconsistent by an \
5211 earlier failure; next: run the command again"
5212 .into(),
5213 })
5214 }
5215
5216 /// `found`, with everything this run wrote that `keep` accepts and the read did not
5217 /// report.
5218 ///
5219 /// See [`Self::created`] and [`Self::board_issues`] for why a read has to be completed
5220 /// at all: the search index is behind, and a node read of an item filed moments ago can
5221 /// be too.
5222 fn completed_with_written(
5223 &self,
5224 mut found: Vec<Resolved>,
5225 keep: impl Fn(&Resolved) -> bool,
5226 ) -> Result<Vec<Resolved>, SourceError> {
5227 for own in self.created()?.iter().filter(|own| keep(own)) {
5228 if !found.iter().any(|item| item.id == own.id) {
5229 found.push(own.clone());
5230 }
5231 }
5232 Ok(found)
5233 }
5234
5235 /// What resolving one node id reached.
5236 ///
5237 /// Three answers rather than an `Option`, because a board *draft* is none of the other
5238 /// two: it is not an issue, so the issue fragment reads nothing of it, and a read of one
5239 /// is completed by a read of the draft itself rather than reported as nothing.
5240 async fn reach(&self, id: &NativeId) -> Result<Reached, SourceError> {
5241 let asked = self
5242 .graphql(
5243 graphql::ISSUE,
5244 json!({"id":id.0,"first":MAX_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
5245 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
5246 )
5247 .await;
5248 let data = match asked {
5249 Ok(data) => data,
5250 // A string that is not a node id at all is not a failure to report: it is an id
5251 // this board does not hold, which is what every read of one already answers.
5252 Err(error) if unresolvable_node(&error) => return Ok(Reached::Nothing),
5253 Err(error) => return Err(error),
5254 };
5255 let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
5256 return Ok(Reached::Nothing);
5257 };
5258 if optional_str(node, "__typename")? == Some("DraftIssue") {
5259 return Ok(Reached::Draft);
5260 }
5261 Ok(match self.resolve_issue(node).await? {
5262 Some(item) => Reached::Held(Box::new(item)),
5263 None => Reached::Nothing,
5264 })
5265 }
5266
5267 /// One item of this board by its own id, whatever kind it is.
5268 ///
5269 /// Resolved from the identifier alone: no search, board-wide or otherwise. What this
5270 /// run wrote is read first, because a node read of an item created moments ago can
5271 /// still be behind the board field values written onto it — see [`Self::created`].
5272 async fn item_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5273 if let Some(own) = self.created()?.iter().find(|own| own.id == *id) {
5274 return Ok(Some(own.clone()));
5275 }
5276 match self.reach(id).await? {
5277 Reached::Held(item) => Ok(Some(*item)),
5278 Reached::Nothing => Ok(None),
5279 Reached::Draft => self.draft_by_id(id).await,
5280 }
5281 }
5282
5283 /// Several items of this board, each by its own id, in order — what [`Self::item_by_id`]
5284 /// answers for each, read [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] rather
5285 /// than one request per id.
5286 ///
5287 /// What this run wrote answers first, as it does there, and only the rest is read. One id
5288 /// left to read is read by [`Self::item_by_id`] itself, which costs what a batch does. A
5289 /// batch GitHub refuses because one of its ids resolves to no node at all is read again one
5290 /// id at a time, so that id is answered as not held and the others as themselves; a draft
5291 /// is completed by a read of the draft, exactly as there.
5292 async fn items_by_ids(&self, ids: &[NativeId]) -> Result<Vec<Option<Resolved>>, SourceError> {
5293 let mut found: Vec<Option<Option<Resolved>>> = {
5294 let created = self.created()?;
5295 ids.iter()
5296 .map(|id| {
5297 created
5298 .iter()
5299 .find(|own| own.id == *id)
5300 .map(|own| Some(own.clone()))
5301 })
5302 .collect()
5303 };
5304 let unread: Vec<NativeId> = ids
5305 .iter()
5306 .zip(&found)
5307 .filter(|(_, found)| found.is_none())
5308 .map(|(id, _)| id.clone())
5309 .collect();
5310 let mut read = Vec::with_capacity(unread.len());
5311 if let [one] = unread.as_slice() {
5312 read.push(self.item_by_id(one).await?);
5313 } else {
5314 for batch in unread.chunks(DETAIL_BATCH) {
5315 let data = match self
5316 .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, None))
5317 .await
5318 {
5319 Ok(data) => data,
5320 Err(error) if unresolvable_node(&error) => {
5321 for id in batch {
5322 read.push(self.item_by_id(id).await?);
5323 }
5324 continue;
5325 }
5326 Err(error) => return Err(error),
5327 };
5328 for (slot, id) in batch.iter().enumerate() {
5329 let node =
5330 data.get(format!("i{slot}"))
5331 .ok_or_else(|| SourceError::Malformed {
5332 message: format!(
5333 "GitHub answered a batch read with no item for {}",
5334 id.0
5335 ),
5336 })?;
5337 read.push(if node.is_null() {
5338 None
5339 } else if optional_str(node, "__typename")? == Some("DraftIssue") {
5340 self.draft_by_id(id).await?
5341 } else {
5342 if optional_str(node, "__typename")? == Some("Issue")
5343 && required_str(node, "id")? != id.0
5344 {
5345 return Err(SourceError::Malformed {
5346 message: format!(
5347 "GitHub answered the read of {} with issue {}",
5348 id.0,
5349 required_str(node, "id")?
5350 ),
5351 });
5352 }
5353 self.resolve_issue(node).await?
5354 });
5355 }
5356 }
5357 }
5358 let mut read = read.into_iter();
5359 Ok(found
5360 .iter_mut()
5361 .map(|slot| slot.take().unwrap_or_else(|| read.next().flatten()))
5362 .collect())
5363 }
5364
5365 fn resolved_cache(
5366 &self,
5367 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
5368 self.resolved_cache
5369 .lock()
5370 .map_err(|_| SourceError::Unavailable {
5371 message: "resolved item records were left inconsistent; run the command again"
5372 .into(),
5373 })
5374 }
5375
5376 /// Reuse a record this invocation already resolved. The mutation sender invalidates
5377 /// it before writing, so a partial failure cannot leave a pre-write binding behind.
5378 async fn bound_item(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5379 let cached = self.resolved_cache()?.get(id).cloned();
5380 if let Some(item) = cached {
5381 return Ok(Some(item));
5382 }
5383 self.item_by_id(id).await
5384 }
5385
5386 /// Take out the item an issue read by reference reached for `id`, when one is held: the
5387 /// status write it was read for is the one caller, so no other read or write is ever
5388 /// answered from a read that selected only what that write needs.
5389 fn take_held(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5390 Ok(self
5391 .held_cache
5392 .lock()
5393 .map_err(|_| SourceError::Unavailable {
5394 message: "items read by issue reference were left inconsistent; run the \
5395 command again"
5396 .into(),
5397 })?
5398 .remove(id))
5399 }
5400
5401 /// One board draft by its own id, with the board item it sits in — or `None` when no
5402 /// item of this board is that draft's.
5403 ///
5404 /// The same decision [`Self::resolve_issue`] makes for an issue, over the draft's own
5405 /// `projectV2Items`: an entry naming this board is what makes it this board's. GitHub
5406 /// links a draft to one board item, so the page this read carries is the whole of that
5407 /// connection, and a page that reports more than it holds is refused rather than read
5408 /// as an answer about memberships nobody read.
5409 async fn draft_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5410 let data = self
5411 .graphql(
5412 graphql::DRAFT,
5413 json!({"id":id.0,"nestedFirst":NESTED_PAGE_SIZE,
5414 "boardItems":BOARD_ITEMS_PAGE_SIZE}),
5415 )
5416 .await?;
5417 // Gone between the two reads is an answer — the draft is no longer there. Anything
5418 // else than the draft [`Self::reach`] was just told this id is, is not one.
5419 let Some(draft) = data.get("node").filter(|node| !node.is_null()) else {
5420 return Ok(None);
5421 };
5422 if optional_str(draft, "__typename")? != Some("DraftIssue") {
5423 return Err(SourceError::Malformed {
5424 message: format!(
5425 "GitHub answered {} as a draft and then as something else",
5426 id.0
5427 ),
5428 });
5429 }
5430 if required_str(draft, "id")? != id.0 {
5431 return Err(SourceError::Malformed {
5432 message: format!("GitHub answered a different draft for {}", id.0),
5433 });
5434 }
5435 let memberships = draft
5436 .get("projectV2Items")
5437 .ok_or_else(|| SourceError::Malformed {
5438 message: format!("GitHub draft {} is missing projectV2Items", id.0),
5439 })?;
5440 let nodes = memberships
5441 .get("nodes")
5442 .and_then(Value::as_array)
5443 .ok_or_else(|| SourceError::Malformed {
5444 message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
5445 })?;
5446 let info = memberships
5447 .get("pageInfo")
5448 .ok_or_else(|| SourceError::Malformed {
5449 message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
5450 })?;
5451 // Read whether or not this board's entry is on the page: a page claiming more than
5452 // the one item GitHub links a draft to is a malformed answer either way.
5453 if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
5454 return Err(SourceError::Malformed {
5455 message: format!(
5456 "GitHub draft {} reports more board items than the one GitHub links a draft \
5457 to",
5458 id.0
5459 ),
5460 });
5461 }
5462 if let Some(node) = nodes.first()
5463 && node
5464 .pointer("/project/number")
5465 .and_then(Value::as_u64)
5466 .is_none()
5467 {
5468 return Err(SourceError::Malformed {
5469 message: format!(
5470 "GitHub draft {} board item has no numeric project number",
5471 id.0
5472 ),
5473 });
5474 }
5475 let Some(held) = self.board_entry(nodes) else {
5476 return Ok(None);
5477 };
5478 if required_str(
5479 held.get("project").ok_or_else(|| SourceError::Malformed {
5480 message: format!("GitHub draft {} board item has no project", id.0),
5481 })?,
5482 "id",
5483 )? != self.board_fields().await?.id.as_str()
5484 {
5485 return Ok(None);
5486 }
5487 let item = json!({
5488 "id": required_str(held, "id")?,
5489 "project": held.get("project"),
5490 "fieldValues": held.get("fieldValues"),
5491 "content": draft,
5492 });
5493 self.resolve(&item)
5494 }
5495
5496 /// The board's own id and field definitions, for a write whose item does not carry
5497 /// them — never its items.
5498 ///
5499 /// A board this command has already listed supplies them, since it read them beside its
5500 /// items; otherwise they come from [`graphql::BOARD_FIELDS`], once per command. Neither
5501 /// is consulted about which items the board holds: see the module documentation for
5502 /// why a question about one known item is answered by reading that item.
5503 async fn board_fields(&self) -> Result<BoardFields, SourceError> {
5504 if let Some(board) = self.board_cache()?.as_ref() {
5505 return Ok(BoardFields {
5506 id: BoardId::parse(&board.id)?,
5507 fields: board.fields.clone(),
5508 });
5509 }
5510 if let Some(held) = self.fields_cache()?.clone() {
5511 return Ok(held);
5512 }
5513 let data = self
5514 .graphql(
5515 graphql::BOARD_FIELDS,
5516 json!({"owner":self.owner,"number":self.project_number,
5517 "nestedFirst":NESTED_PAGE_SIZE}),
5518 )
5519 .await?;
5520 self.fields_read(&data)
5521 }
5522
5523 /// The board's id and fields out of an answer carrying the `boardFields` root, held for
5524 /// the rest of this command.
5525 fn fields_read(&self, data: &Value) -> Result<BoardFields, SourceError> {
5526 let board = data
5527 .pointer("/boardFields/projectV2")
5528 .filter(|value| !value.is_null())
5529 .ok_or_else(|| SourceError::Refused {
5530 message: format!(
5531 "GitHub project {}/{} was not found or is not visible to the token",
5532 self.owner, self.project_number
5533 ),
5534 })?;
5535 let read = BoardFields {
5536 id: BoardId::parse(required_str(board, "id")?)?,
5537 fields: board.get("fields").cloned().unwrap_or(Value::Null),
5538 };
5539 *self.fields_cache()? = Some(read.clone());
5540 Ok(read)
5541 }
5542
5543 /// Read what creating an issue in `repository` needs and this command has not read yet —
5544 /// the board's fields and the repository's node id — in one request when it needs both.
5545 ///
5546 /// When either is already known this sends nothing, and the other is read by its own
5547 /// document where it is asked for, so no create reads anything twice.
5548 async fn creation_context(
5549 &self,
5550 repository: &RepositoryTarget,
5551 incoming: &Incoming<'_>,
5552 ) -> Result<(), SourceError> {
5553 let fields_known = self.board_cache()?.is_some() || self.fields_cache()?.is_some();
5554 if fields_known || self.repository_cache()?.contains_key(repository) {
5555 return Ok(());
5556 }
5557 let data = self
5558 .graphql(
5559 graphql::CREATION_CONTEXT,
5560 json!({"owner":self.owner,"number":self.project_number,
5561 "nestedFirst":NESTED_PAGE_SIZE,"repositoryOwner":repository.owner,
5562 "repositoryName":repository.name}),
5563 )
5564 .await?;
5565 self.fields_read(&data)?;
5566 self.repository_read(&data, repository, incoming)?;
5567 Ok(())
5568 }
5569
5570 /// This process's own view of the board's fields, or the refusal a poisoned lock is.
5571 fn fields_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<BoardFields>>, SourceError> {
5572 self.fields_cache
5573 .lock()
5574 .map_err(|_| SourceError::Unavailable {
5575 message: "this source's view of the board's fields was left inconsistent by an \
5576 earlier failure; next: run the command again"
5577 .into(),
5578 })
5579 }
5580
5581 /// What a write to `item` needs of the board, read off that item when it says enough and
5582 /// off [`Self::board_fields`] when it does not.
5583 ///
5584 /// A node read of an item names its board and carries the definition of every field it
5585 /// holds a value of — so an item naming its board, holding a value of the origin field,
5586 /// and, when the write carries a status, holding a `Status` value, needs no read of the
5587 /// board at all. **Nothing the item does not say is guessed:** a field it holds no value
5588 /// of may still be on the board, and a view reading it as absent would refuse a write the
5589 /// board can take or skip a field write the board needs, so such an item — and a create,
5590 /// which has no item yet — takes the board's fields from their own read instead.
5591 async fn fields_for(
5592 &self,
5593 item: Option<&Resolved>,
5594 writes_status: bool,
5595 selects_priority: bool,
5596 ) -> Result<BoardFields, SourceError> {
5597 if let Some(board) = item.and_then(Resolved::carried_board) {
5598 return Ok(board);
5599 }
5600 if let Some(item) = item
5601 && let Some(board_id) = item.named_board()
5602 && item.defines(ORIGIN_FIELD)
5603 && (!writes_status || item.defines("Status"))
5604 && (!selects_priority || item.defines(PRIORITY_FIELD))
5605 && self
5606 .metadata_fields
5607 .iter()
5608 .all(|projection| item.defines(&projection.field))
5609 {
5610 return Ok(BoardFields {
5611 id: board_id,
5612 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
5613 });
5614 }
5615 self.board_fields().await
5616 }
5617
5618 /// Everything filed under one issue of this board, walked to exhaustion — or `None`
5619 /// when that id names nothing here with a sub-issue relationship to walk.
5620 ///
5621 /// `None` and an empty answer are different: `None` is *this is not an issue of this
5622 /// GitHub*, which is what sends a project selector on to be read as a name, and an
5623 /// empty vector is a project that holds nothing.
5624 async fn sub_issues(&self, id: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
5625 let mut after: Option<String> = None;
5626 let mut children = Vec::new();
5627 loop {
5628 let asked = self
5629 .graphql(
5630 graphql::SUB_ISSUES,
5631 json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after,
5632 "nestedFirst":NESTED_PAGE_SIZE,
5633 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
5634 )
5635 .await;
5636 let data = match asked {
5637 Ok(data) => data,
5638 // A string that is not a node id at all is not a failure to report: it is
5639 // the ordinary answer to a selector naming a project by its name.
5640 Err(error) if unresolvable_node(&error) => return Ok(None),
5641 Err(error) => return Err(error),
5642 };
5643 let Some(connection) = data
5644 .pointer("/node/subIssues")
5645 .filter(|value| !value.is_null())
5646 else {
5647 // No such node, or one with no sub-issue relationship — a board draft is
5648 // the one this board can really hold.
5649 return Ok(None);
5650 };
5651 for node in connection
5652 .get("nodes")
5653 .and_then(Value::as_array)
5654 .ok_or_else(|| SourceError::Malformed {
5655 message: "GitHub subIssues.nodes is not an array".into(),
5656 })?
5657 {
5658 if let Some(resolved) = self.resolve_issue(node).await? {
5659 children.push(resolved);
5660 }
5661 }
5662 let info = connection
5663 .get("pageInfo")
5664 .ok_or_else(|| SourceError::Malformed {
5665 message: "GitHub subIssues connection has no pageInfo".into(),
5666 })?;
5667 let next = required_bool(info, "hasNextPage")?
5668 .then(|| required_str(info, "endCursor"))
5669 .transpose()?;
5670 match next {
5671 Some(next) => {
5672 validate_cursor_progress(after.as_deref(), next)?;
5673 after = Some(next.to_owned());
5674 }
5675 None => return Ok(Some(children)),
5676 }
5677 }
5678 }
5679
5680 /// Which issue of this board a project *name* is, or `None` when none is.
5681 ///
5682 /// One bounded query which filters on that name at the server, rather than a walk of
5683 /// every issue the board holds. The name is compared again here: the qualifier narrows
5684 /// what GitHub sends, and this source decides what it names.
5685 async fn project_by_name(&self, name: &str) -> Result<Option<NativeId>, SourceError> {
5686 let search = self.board_search(Some(&title_qualifier(name)));
5687 let mut after = None;
5688 loop {
5689 let (candidates, next) = self
5690 .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
5691 .await?;
5692 if let Some(item) = candidates.into_iter().find(|item| {
5693 item.kind == BoardKind::Work(ItemKind::Project)
5694 && item.title.eq_ignore_ascii_case(name)
5695 }) {
5696 return Ok(Some(item.id));
5697 }
5698 match next {
5699 Some(next) => after = Some(next),
5700 None => return Ok(None),
5701 }
5702 }
5703 }
5704
5705 /// Everything filed under one project of this board: the sub-issues of the issue that
5706 /// project is.
5707 ///
5708 /// Tasks *and* documents, because a document filed under a project is a sub-issue of it
5709 /// too — the caller keeps the kind it asked for. Nothing about this grows as the board
5710 /// gains projects, or as another project gains tasks.
5711 ///
5712 /// A qualified id names the issue and is asked for its sub-issues directly: one
5713 /// request, no search of any kind. Only a selector GitHub cannot resolve that way is
5714 /// read as a project *name*, which costs the one bounded search
5715 /// [`Self::project_by_name`] makes.
5716 ///
5717 /// What GitHub answered is held for the rest of the command — see [`Self::children_cache`]
5718 /// — and each answer is still cut to the items whose parent is this project, so one this
5719 /// process has since filed elsewhere is not reported here, and completed with what this
5720 /// process filed under it.
5721 async fn project_children(&self, selector: &NativeId) -> Result<Vec<Resolved>, SourceError> {
5722 let held = self.children_cache()?.get(selector).cloned();
5723 let (project, children) = match held {
5724 Some(held) => held,
5725 None => {
5726 let answered = match self.sub_issues(selector).await? {
5727 Some(children) => (selector.clone(), children),
5728 None => match self.project_by_name(&selector.0).await? {
5729 Some(project) => {
5730 let children = self.sub_issues(&project).await?.unwrap_or_default();
5731 (project, children)
5732 }
5733 None => return Ok(Vec::new()),
5734 },
5735 };
5736 self.children_cache()?
5737 .insert(selector.clone(), answered.clone());
5738 answered
5739 }
5740 };
5741 let mut children: Vec<Resolved> = children
5742 .into_iter()
5743 .filter(|child| child.parent.as_ref() == Some(&project))
5744 .collect();
5745 for own in self.updated()?.iter() {
5746 if own.parent.as_ref() == Some(&project) && !children.iter().any(|c| c.id == own.id) {
5747 children.push(own.clone());
5748 }
5749 }
5750 self.completed_with_written(children, |own| own.parent.as_ref() == Some(&project))
5751 }
5752
5753 /// Every issue of this board GitHub's issue search reports updated at or after `since`,
5754 /// completed with what this run wrote — the candidates a comment-activity read confirms.
5755 ///
5756 /// Scoped by the board and by nothing else: `project:<owner>/<number>` reaches every issue
5757 /// on the board whatever repository, and whatever owner, it lives in, so no repository or
5758 /// owner qualifier is added and none is needed. What makes the `updated:` qualifier
5759 /// sufficient is a fact about GitHub rather than about this source: a comment written on an
5760 /// issue **and a comment edited on it** both move that issue's `updatedAt`. The credentialed
5761 /// journey `an_edited_comment_moves_its_issue_and_is_selected_since` in `tests/journey`
5762 /// re-takes that fact on every run of the lane, so a change on GitHub's side fails there
5763 /// rather than silently narrowing a caller's answer.
5764 ///
5765 /// The instant is written to the second, rounded down, which can only widen what the
5766 /// search returns; confirmation against each candidate's own comments is what makes the
5767 /// answer exact. The search is an index that lags a write by a second or two — the module
5768 /// documentation records it — so a caller that asks again from its last instant should
5769 /// overlap the two by more than that.
5770 async fn updated_since(&self, since: DateTime<Utc>) -> Result<Vec<Resolved>, SourceError> {
5771 let found = self.searched(&updated_qualifier(since)).await?;
5772 self.completed_with_written(found, |_| true)
5773 }
5774
5775 /// Every issue of this board GitHub's issue search reports for the board-scoped search
5776 /// narrowed by `also`, in pages of [`SEARCH_PAGE_SIZE`].
5777 ///
5778 /// Uncompleted: what this process wrote is added by the caller, which knows whether its
5779 /// own record is the fresher of the two.
5780 async fn searched(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
5781 let search = self.board_search(Some(also));
5782 let mut after: Option<String> = None;
5783 let mut found = Vec::new();
5784 loop {
5785 let (page, next) = self
5786 .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
5787 .await?;
5788 found.extend(page);
5789 match next {
5790 Some(next) => after = Some(next),
5791 None => return Ok(found),
5792 }
5793 }
5794 }
5795
5796 /// A bounded task answer; the versioned cursor carries the connection position, how
5797 /// many rows of the page starting there were already handed out, and the own-write ids
5798 /// already observed, including across a new source instance.
5799 ///
5800 /// Every page is sent at [`SEARCH_PAGE_SIZE`] whatever the caller's limit, and a limit is
5801 /// sliced from the pages it needs; why is the module documentation's paging contract.
5802 async fn search_tasks(
5803 &self,
5804 query: &TaskQuery,
5805 page: &PageRequest,
5806 also: &str,
5807 ) -> Result<Page<Task>, SourceError> {
5808 let mut position = match &page.cursor {
5809 None => SearchPosition::default(),
5810 Some(cursor) => serde_json::from_str::<SearchPosition>(&cursor.0)
5811 .ok()
5812 .filter(|position| {
5813 position.version == SEARCH_CURSOR_VERSION
5814 && position.connection.valid_resume(position.offset)
5815 })
5816 .ok_or_else(|| SourceError::Config {
5817 message: "page cursor is invalid".into(),
5818 })?,
5819 };
5820 let search = self.board_search(Some(also));
5821 let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
5822 let own = self.with_own_writes(Vec::new())?;
5823 // An issue this process commented on is a candidate of a comment-activity read
5824 // whether or not the search has caught up with the comment; see `Self::commented`.
5825 let commented = match query.commented_since {
5826 Some(_) => self.commented()?.clone(),
5827 None => Vec::new(),
5828 };
5829 for id in own.iter().map(|item| &item.id).chain(&commented) {
5830 if !position.own.contains(id) {
5831 position.own.push(id.clone());
5832 }
5833 }
5834 let mut tasks = Vec::new();
5835 while !position.connection.exhausted() && tasks.len() < limit {
5836 let first = SEARCH_PAGE_SIZE;
5837 // Page size is part of the key: a short cached answer cannot answer a wider ask.
5838 let key =
5839 serde_json::to_string(&("page", &search, &position.connection.after(), first))
5840 .expect("search page key is serializable");
5841 let cached = if query.commented_since.is_none() {
5842 self.narrowed_cache()?.get(&key).cloned()
5843 } else {
5844 None
5845 };
5846 let (found, next) = match cached {
5847 Some(found) => {
5848 let next = self
5849 .search_next
5850 .lock()
5851 .map_err(|_| SourceError::Unavailable {
5852 message:
5853 "search pagination was left inconsistent; run the command again"
5854 .into(),
5855 })?
5856 .get(&key)
5857 .cloned()
5858 .flatten();
5859 (found, next)
5860 }
5861 None => {
5862 let (found, next) = self
5863 .search_page(&search, first, position.connection.after())
5864 .await?;
5865 if query.commented_since.is_none() {
5866 self.search_next
5867 .lock()
5868 .map_err(|_| SourceError::Unavailable {
5869 message:
5870 "search pagination was left inconsistent; run the command again"
5871 .into(),
5872 })?
5873 .insert(key.clone(), next.clone());
5874 self.narrowed_cache()?.insert(key, found.clone());
5875 }
5876 (found, next)
5877 }
5878 };
5879 let rows = found.len();
5880 for mut item in found.into_iter().skip(position.offset) {
5881 if tasks.len() == limit {
5882 break;
5883 }
5884 position.offset += 1;
5885 if position.own.contains(&item.id) {
5886 if position.seen.contains(&item.id) {
5887 continue;
5888 }
5889 position.seen.push(item.id.clone());
5890 // The search's own copy of an issue this process only commented on is as
5891 // good as a node read of it, since its comments are read either way.
5892 let only_commented = commented.contains(&item.id)
5893 && !own.iter().any(|written| written.id == item.id);
5894 if !only_commented {
5895 let updated_at = item.updated_at;
5896 let Some(written) = self.search_written(&own, &item.id).await? else {
5897 continue;
5898 };
5899 item = written;
5900 item.updated_at = item.updated_at.max(updated_at);
5901 self.resolved_cache()?.insert(item.id.clone(), item.clone());
5902 }
5903 }
5904 if item.kind == BoardKind::Work(ItemKind::Task) {
5905 let task = item.task()?;
5906 if task_matches(&task, query, &query.project)
5907 && self.commented_since(&item, query.commented_since).await?
5908 {
5909 tasks.push(task);
5910 }
5911 }
5912 }
5913 if position.offset < rows {
5914 continue;
5915 }
5916 position.offset = 0;
5917 position.connection = match next {
5918 Some(after) => SearchConnection::Continuing {
5919 after: Cursor(after),
5920 },
5921 None => SearchConnection::Exhausted {},
5922 };
5923 }
5924 if position.connection.exhausted() {
5925 for id in position.own.clone() {
5926 if position.seen.contains(&id) {
5927 continue;
5928 }
5929 if tasks.len() == limit {
5930 break;
5931 }
5932 position.seen.push(id.clone());
5933 let Some(item) = self.search_written(&own, &id).await? else {
5934 continue;
5935 };
5936 if item.kind == BoardKind::Work(ItemKind::Task) {
5937 let task = item.task()?;
5938 if task_matches(&task, query, &query.project)
5939 && self.commented_since(&item, query.commented_since).await?
5940 {
5941 tasks.push(task);
5942 }
5943 }
5944 }
5945 }
5946 let more = !position.connection.exhausted()
5947 || position.own.iter().any(|id| !position.seen.contains(id));
5948 Ok(Page {
5949 items: tasks,
5950 next: more.then(|| {
5951 Cursor(serde_json::to_string(&position).expect("search position is serializable"))
5952 }),
5953 })
5954 }
5955
5956 /// A resumed process has the ids but no write records; resolve only a record the
5957 /// current page needs, by its uncached node read rather than the lagging search index.
5958 async fn search_written(
5959 &self,
5960 own: &[Resolved],
5961 id: &NativeId,
5962 ) -> Result<Option<Resolved>, SourceError> {
5963 match own.iter().find(|item| item.id == *id) {
5964 Some(item) => Ok(Some(item.clone())),
5965 None => self.item_by_id(id).await,
5966 }
5967 }
5968
5969 /// The candidates for a task query carrying a text, metadata or origin predicate, read
5970 /// without enumerating the board — or `None` for a query carrying none of the three, which
5971 /// keeps the reads it always had.
5972 ///
5973 /// An origin is answered by [`Self::origin_candidates`], whatever else the query carries,
5974 /// because it names at most a handful of items. Text and metadata are answered by one
5975 /// board-scoped issue search carrying every term — see [`narrowing_qualifiers`] — narrowed
5976 /// further by `updated:>=` when the query also asks for comment activity, since both
5977 /// qualifiers must hold of an issue the answer keeps. Every candidate is confirmed in
5978 /// process afterwards by the same predicates [`task_matches`] applies to every read.
5979 ///
5980 /// Completed with what this process wrote, its own record winning over the index's copy
5981 /// of the same item: see [`Self::with_own_writes`].
5982 async fn narrowed(&self, query: &TaskQuery) -> Result<Option<Vec<Resolved>>, SourceError> {
5983 let asked = match (&query.origin, narrowing_qualifiers(query)) {
5984 (Some(origin), _) => Narrowing::Origin(origin.clone()),
5985 (None, Some(qualifiers)) => Narrowing::Search(match query.commented_since {
5986 Some(since) => format!("{} {qualifiers}", updated_qualifier(since)),
5987 None => qualifiers,
5988 }),
5989 (None, None) => return Ok(None),
5990 };
5991 // A question about comment activity is asked afresh every time, as it always was: it
5992 // is the one a caller polls from one source while waiting for the index, and an
5993 // answer held from the first poll would be the answer to every later one.
5994 let key = query.commented_since.is_none().then(|| asked.key());
5995 let cached = match &key {
5996 Some(key) => self.narrowed_cache()?.get(key).cloned(),
5997 None => None,
5998 };
5999 let found = match cached {
6000 Some(found) => found,
6001 None => {
6002 let found = match &asked {
6003 Narrowing::Origin(origin) => self.origin_candidates(origin).await?,
6004 Narrowing::Search(also) => self.searched(also).await?,
6005 };
6006 if let Some(key) = key {
6007 self.narrowed_cache()?.insert(key, found.clone());
6008 }
6009 found
6010 }
6011 };
6012 self.with_own_writes(found).map(Some)
6013 }
6014
6015 /// The candidates for a project or unscoped document query carrying a searchable text,
6016 /// read without enumerating the board — or `None` for a query with no text or a blank one,
6017 /// which keeps the read it always had.
6018 ///
6019 /// The text is sent as the very phrase a task query's text is — see [`text_qualifiers`] —
6020 /// in one board-scoped issue search walked to its end at [`SEARCH_PAGE_SIZE`], so what it
6021 /// costs is the issues that match and never the board. Its answer is held for the command
6022 /// under the same key [`Self::narrowed`] holds that search under, so a walk of the caller's
6023 /// pages asks GitHub once. Every candidate is confirmed afterwards by its kind and by the
6024 /// substring rule, exactly as an item of the wider read was, and is completed with what this
6025 /// process wrote: see [`Self::with_own_writes`].
6026 async fn text_searched(
6027 &self,
6028 text: Option<&TextQuery>,
6029 ) -> Result<Option<Vec<Resolved>>, SourceError> {
6030 let Some(also) = text_qualifiers(text) else {
6031 return Ok(None);
6032 };
6033 let key = Narrowing::Search(also.clone()).key();
6034 let cached = self.narrowed_cache()?.get(&key).cloned();
6035 let found = match cached {
6036 Some(found) => found,
6037 None => {
6038 let found = self.searched(&also).await?;
6039 self.narrowed_cache()?.insert(key, found.clone());
6040 found
6041 }
6042 };
6043 self.with_own_writes(found).map(Some)
6044 }
6045
6046 /// Every item of this board that may carry `origin` — a superset of those that do — found
6047 /// by [`graphql::ORIGIN_LOOKUP`] and never by enumerating the board.
6048 ///
6049 /// The union of the board's own field filter over the `onetaskgraph.origin` text field —
6050 /// which reads the field every carrier holds, whichever release wrote it — and the
6051 /// board-scoped issue search for the same id as a phrase in the body, where this source
6052 /// mirrors it. The caller adds the third read, this process's own writes. Candidates are
6053 /// returned unconfirmed; [`task_matches`] compares each one's own origin field with the
6054 /// query's, exactly.
6055 ///
6056 /// Both connections are walked to exhaustion, each from its own cursor. One that has
6057 /// already ended is sent its last cursor again, which answers an empty page, so the one
6058 /// document serves every page of either. What the two leave is stated in the module
6059 /// documentation: a carrier another process added within the last second or two, before
6060 /// either index has it.
6061 async fn origin_candidates(&self, origin: &str) -> Result<Vec<Resolved>, SourceError> {
6062 let filter = format!("{ORIGIN_FIELD}:{}", quoted(origin));
6063 let search = self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))));
6064 let mut items_after: Option<String> = None;
6065 let mut search_after: Option<String> = None;
6066 let mut found: Vec<Resolved> = Vec::new();
6067 let keep = |resolved: Resolved, found: &mut Vec<Resolved>| {
6068 if !found.iter().any(|held| held.id == resolved.id) {
6069 found.push(resolved);
6070 }
6071 };
6072 loop {
6073 let data = self
6074 .graphql(
6075 graphql::ORIGIN_LOOKUP,
6076 json!({"owner":self.owner,"number":self.project_number,"filter":filter,
6077 "search":search,"type":"ISSUE","originFirst":ORIGIN_PAGE_SIZE,
6078 "itemsAfter":items_after,"searchAfter":search_after,
6079 "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
6080 "duplicates":true}),
6081 )
6082 .await?;
6083 let items = data
6084 .pointer("/originItems/projectV2/items")
6085 .filter(|value| !value.is_null())
6086 .ok_or_else(|| SourceError::Refused {
6087 message: format!(
6088 "GitHub project {}/{} was not found or is not visible to the token",
6089 self.owner, self.project_number
6090 ),
6091 })?;
6092 for item in optional_nodes(Some(items), "project items")?
6093 .into_iter()
6094 .flatten()
6095 {
6096 // The board's own items list its drafts too, and a draft is not an issue: no
6097 // narrowed read answers with one, whatever its origin field holds.
6098 if let Some(resolved) = self.resolve(item)?
6099 && resolved.content_kind == ContentKind::Issue
6100 {
6101 keep(resolved, &mut found);
6102 }
6103 }
6104 let searched = data.get("search").ok_or_else(|| SourceError::Malformed {
6105 message: "GitHub search response has no search connection".into(),
6106 })?;
6107 for node in optional_nodes(Some(searched), "search")?
6108 .into_iter()
6109 .flatten()
6110 {
6111 if let Some(resolved) = self.resolve_issue(node).await? {
6112 keep(resolved, &mut found);
6113 }
6114 }
6115 let items_next = resumed(items, items_after.as_deref())?;
6116 let search_next = resumed(searched, search_after.as_deref())?;
6117 if !items_next.has_more() && !search_next.has_more() {
6118 return Ok(found);
6119 }
6120 items_after = items_next.cursor();
6121 search_after = search_next.cursor();
6122 }
6123 }
6124
6125 /// `found`, with every item this process created or wrote in its place, and every one of
6126 /// them the read did not report added.
6127 ///
6128 /// This process's own record wins over the read's copy of the same item, because a read
6129 /// of an item written moments ago can still be behind what was written onto it — the
6130 /// origin field included, which is the one a narrowed read is confirmed against — and a
6131 /// read that still names an item under a predicate this process's write moved it out of
6132 /// must not return it. The one thing the read knows that the record cannot is when GitHub
6133 /// last saw the item change, which is what a comment-activity read rules a candidate out
6134 /// by, so the read's `updatedAt` is kept when the record has none of its own. See
6135 /// [`Self::created`] and [`Self::updated`](GitHubProjectsSource::updated).
6136 fn with_own_writes(&self, mut found: Vec<Resolved>) -> Result<Vec<Resolved>, SourceError> {
6137 // A board draft is not an issue, so no narrowed read returns one, and this process
6138 // having written one does not make it an answer either.
6139 let own: Vec<Resolved> = self
6140 .created()?
6141 .iter()
6142 .chain(self.updated()?.iter())
6143 .filter(|own| own.content_kind == ContentKind::Issue)
6144 .cloned()
6145 .collect();
6146 for mut own in own {
6147 self.resolved_cache()?.insert(own.id.clone(), own.clone());
6148 match found.iter_mut().find(|read| read.id == own.id) {
6149 Some(read) => {
6150 own.updated_at = own.updated_at.max(read.updated_at);
6151 *read = own;
6152 }
6153 None => found.push(own),
6154 }
6155 }
6156 Ok(found)
6157 }
6158
6159 /// Whether `item` has a comment created or last edited at or after `since` — always, when
6160 /// there is no instant to hold it to.
6161 ///
6162 /// The candidate's own `updatedAt` is read first, because a comment written or edited at
6163 /// or after the instant moved it there: an issue not updated since holds no such comment,
6164 /// and its comments are never asked for — unless this process commented on it in this
6165 /// command, when the `updatedAt` held may predate that comment; see [`Self::commented`]. Otherwise its comments are walked, oldest first,
6166 /// only as far as the first that matches. A board draft is not an issue and has no
6167 /// comments, so it never matches.
6168 async fn commented_since(
6169 &self,
6170 item: &Resolved,
6171 since: Option<DateTime<Utc>>,
6172 ) -> Result<bool, SourceError> {
6173 let Some(since) = since else {
6174 return Ok(true);
6175 };
6176 if item.content_kind == ContentKind::DraftIssue {
6177 return Ok(false);
6178 }
6179 // An `updatedAt` this process's own record or a lagging index holds can predate a
6180 // comment this process wrote since, so only an issue it did not comment on is ruled
6181 // out by one.
6182 if item.updated_at.is_some_and(|updated| updated < since)
6183 && !self.commented()?.contains(&item.id)
6184 {
6185 return Ok(false);
6186 }
6187 let query = TaskQuery {
6188 commented_since: Some(since),
6189 ..TaskQuery::default()
6190 };
6191 let mut after: Option<String> = None;
6192 loop {
6193 let data = self
6194 .graphql(
6195 graphql::ISSUE_COMMENTS,
6196 json!({"id":item.id.0,"first":MAX_PAGE_SIZE,"after":after}),
6197 )
6198 .await?;
6199 let Some(connection) = data
6200 .get("node")
6201 .filter(|value| !value.is_null())
6202 .and_then(|node| node.get("comments"))
6203 .filter(|value| !value.is_null())
6204 else {
6205 // Removed since the search reported it: no longer an issue with comments.
6206 return Ok(false);
6207 };
6208 let comments = optional_nodes(Some(connection), "issue comments")?
6209 .into_iter()
6210 .flatten()
6211 .map(comment_from)
6212 .collect::<Result<Vec<_>, _>>()?;
6213 if query.comments_match(&comments) {
6214 return Ok(true);
6215 }
6216 match next_cursor(connection)? {
6217 Some(next) => {
6218 validate_cursor_progress(after.as_deref(), &next.0)?;
6219 after = Some(next.0);
6220 }
6221 None => return Ok(false),
6222 }
6223 }
6224 }
6225
6226 /// Every item on the board: the union of both enumerations GitHub offers of one.
6227 ///
6228 /// Neither contains the other, so neither is dropped — only `ProjectV2.items` lists a
6229 /// board **draft** and reads the board's own fields beside its items, and only the search
6230 /// reports an item that connection is behind on. The module documentation is where the lag and the
6231 /// measurements behind it are written down.
6232 ///
6233 /// A search result is admitted on the same terms as any other issue this source reaches
6234 /// directly — [`Self::resolve_issue`] keeps it only if that issue's own `projectItems`
6235 /// names *this* board — so an issue the index still believes is here after it was taken
6236 /// off is refused rather than reported.
6237 ///
6238 /// See [`Self::board_cache`]. Both completions happen on every call rather than once,
6239 /// which is what the cache could otherwise have broken.
6240 async fn board(&self) -> Result<Board, SourceError> {
6241 self.board_completed_by(None).await
6242 }
6243
6244 /// [`Self::board`], its search half narrowed by `also` when it is given — which an issue
6245 /// that half could add is then answered only if it holds.
6246 async fn board_completed_by(&self, also: Option<&str>) -> Result<Board, SourceError> {
6247 let cached = self.board_cache()?.clone();
6248 let mut board = match cached {
6249 Some(board) => board,
6250 None => {
6251 let read = self.read_board().await?;
6252 *self.board_cache()? = Some(read.clone());
6253 read
6254 }
6255 };
6256 let searched = match also {
6257 None => self.searched_issues().await?,
6258 Some(also) => self.searched_narrowly(also).await?,
6259 };
6260 for held in searched {
6261 if !board.items.iter().any(|item| item.id == held.id) {
6262 board.items.push(held);
6263 }
6264 }
6265 for own in self.created()?.iter() {
6266 if !board.items.iter().any(|item| item.id == own.id) {
6267 board.items.push(own.clone());
6268 }
6269 }
6270 Ok(board)
6271 }
6272
6273 /// This process's own view of the board, or the refusal a poisoned lock is.
6274 fn board_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<Board>>, SourceError> {
6275 self.board_cache
6276 .lock()
6277 .map_err(|_| SourceError::Unavailable {
6278 message: "this source's view of the board was left inconsistent by an earlier \
6279 failure; next: run the command again"
6280 .into(),
6281 })
6282 }
6283
6284 /// Bring this process's own view of the board up to an item it has just written.
6285 ///
6286 /// A created item goes to `created`, which is what completes a board read GitHub's own
6287 /// eventual consistency has left behind. An item that was already there is replaced
6288 /// where it sits, so a second write of it in the same command reads its real parent
6289 /// rather than the one it had before the first write.
6290 ///
6291 /// "Where it sits" is three places, and missing an earlier one leaves a stale record
6292 /// that wins: an item this same run created is held in `created` and not in the cached
6293 /// board, and `board` completes the cached board *from* `created`, so replacing only
6294 /// the cached copy of such an item replaces nothing and the read still reports the
6295 /// title it was created with. The search is the third, and it is the one an item the
6296 /// board's own projection is behind on sits in *alone* — which is exactly the item this
6297 /// source is least able to re-read, so leaving it out would put the stale title back on
6298 /// the only items the completion in [`Self::board`] exists for.
6299 fn remember_written(&self, item: Resolved, created: bool) -> Result<(), SourceError> {
6300 self.resolved_cache()?.insert(item.id.clone(), item.clone());
6301 if created {
6302 self.created()?.push(item);
6303 return Ok(());
6304 }
6305 {
6306 let mut own = self.created()?;
6307 if let Some(held) = own.iter_mut().find(|held| held.id == item.id) {
6308 *held = item;
6309 return Ok(());
6310 }
6311 }
6312 {
6313 let mut own = self.updated()?;
6314 match own.iter_mut().find(|held| held.id == item.id) {
6315 Some(held) => *held = item.clone(),
6316 None => own.push(item.clone()),
6317 }
6318 }
6319 if let Some(board) = self.board_cache()?.as_mut()
6320 && let Some(held) = board.items.iter_mut().find(|held| held.id == item.id)
6321 {
6322 *held = item.clone();
6323 }
6324 if let Some(found) = self.search_cache()?.as_mut()
6325 && let Some(held) = found.iter_mut().find(|held| held.id == item.id)
6326 {
6327 *held = item.clone();
6328 }
6329 for found in self.narrowed_cache()?.values_mut() {
6330 if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
6331 *held = item.clone();
6332 }
6333 }
6334 for (_, found) in self.children_cache()?.values_mut() {
6335 if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
6336 *held = item.clone();
6337 }
6338 }
6339 Ok(())
6340 }
6341
6342 /// Forget one item this process has just deleted, from every half of its own view.
6343 fn forget(&self, id: &NativeId) -> Result<(), SourceError> {
6344 self.resolved_cache()?.remove(id);
6345 self.created()?.retain(|own| own.id != *id);
6346 self.updated()?.retain(|own| own.id != *id);
6347 self.commented()?.retain(|own| own != id);
6348 if let Some(board) = self.board_cache()?.as_mut() {
6349 board.items.retain(|item| item.id != *id);
6350 }
6351 if let Some(found) = self.search_cache()?.as_mut() {
6352 found.retain(|item| item.id != *id);
6353 }
6354 for found in self.narrowed_cache()?.values_mut() {
6355 found.retain(|item| item.id != *id);
6356 }
6357 for (_, found) in self.children_cache()?.values_mut() {
6358 found.retain(|item| item.id != *id);
6359 }
6360 Ok(())
6361 }
6362
6363 /// This process's own record of each narrowed answer, or the refusal a poisoned lock is.
6364 fn narrowed_cache(
6365 &self,
6366 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<String, Vec<Resolved>>>, SourceError> {
6367 self.narrowed_cache
6368 .lock()
6369 .map_err(|_| SourceError::Unavailable {
6370 message: "this source's view of a narrowed read was left inconsistent by an \
6371 earlier failure; next: run the command again"
6372 .into(),
6373 })
6374 }
6375
6376 /// This process's own record of each project's sub-issues, or the refusal a poisoned lock
6377 /// is.
6378 fn children_cache(&self) -> Result<std::sync::MutexGuard<'_, ProjectChildren>, SourceError> {
6379 self.children_cache
6380 .lock()
6381 .map_err(|_| SourceError::Unavailable {
6382 message: "this source's view of a project's tasks was left inconsistent by an \
6383 earlier failure; next: run the command again"
6384 .into(),
6385 })
6386 }
6387
6388 /// Every page of the board, read from GitHub.
6389 async fn read_board(&self) -> Result<Board, SourceError> {
6390 let mut after: Option<String> = None;
6391 let mut items = Vec::new();
6392 let mut board;
6393 loop {
6394 let page = self.board_page(after.as_deref(), MAX_PAGE_SIZE).await?;
6395 for item in page
6396 .pointer("/items/nodes")
6397 .and_then(Value::as_array)
6398 .ok_or_else(|| SourceError::Malformed {
6399 message: "GitHub project items.nodes is not an array".into(),
6400 })?
6401 {
6402 if let Some(resolved) = self.resolve(item)? {
6403 items.push(resolved);
6404 }
6405 }
6406 let info = page
6407 .pointer("/items/pageInfo")
6408 .ok_or_else(|| SourceError::Malformed {
6409 message: "GitHub project items have no pageInfo".into(),
6410 })?;
6411 let has_next = required_bool(info, "hasNextPage")?;
6412 let next = has_next
6413 .then(|| required_str(info, "endCursor"))
6414 .transpose()?;
6415 board = page.clone();
6416 match next {
6417 Some(next) => {
6418 validate_cursor_progress(after.as_deref(), next)?;
6419 after = Some(next.to_owned());
6420 }
6421 None => break,
6422 }
6423 }
6424 Ok(Board {
6425 id: required_str(&board, "id")?.to_owned(),
6426 fields: board.get("fields").cloned().unwrap_or(Value::Null),
6427 items,
6428 })
6429 }
6430
6431 /// The existing items this source has written, for completing a narrowed read that is
6432 /// behind; see [`Self::updated`](GitHubProjectsSource::updated).
6433 fn updated(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
6434 self.updated.lock().map_err(|_| SourceError::Unavailable {
6435 message: "this source's record of what it wrote in this run was left inconsistent \
6436 by an earlier failure; next: run the command again"
6437 .into(),
6438 })
6439 }
6440
6441 /// The issues this source has commented on in this command; see
6442 /// [`Self::commented`](GitHubProjectsSource::commented).
6443 fn commented(&self) -> Result<std::sync::MutexGuard<'_, Vec<NativeId>>, SourceError> {
6444 self.commented.lock().map_err(|_| SourceError::Unavailable {
6445 message: "this source's record of what it commented on in this run was left \
6446 inconsistent by an earlier failure; next: run the command again"
6447 .into(),
6448 })
6449 }
6450
6451 /// Called only once GitHub has answered the comment write, so an issue whose comment
6452 /// failed is never made a candidate a later read would pay a node read for.
6453 fn remember_commented(&self, issue: &NativeId) -> Result<(), SourceError> {
6454 let mut commented = self.commented()?;
6455 if !commented.contains(issue) {
6456 commented.push(issue.clone());
6457 }
6458 Ok(())
6459 }
6460
6461 /// The items this source has created, for completing a board read that is behind.
6462 fn created(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
6463 self.created.lock().map_err(|_| SourceError::Unavailable {
6464 message: "this source's record of what it created in this run was left \
6465 inconsistent by an earlier failure; next: run the command again"
6466 .into(),
6467 })
6468 }
6469
6470 /// One board item as this source reports it, or `None` for content it ignores.
6471 ///
6472 /// A pull request is neither a project nor a task — it is somebody's change, not a
6473 /// unit of plan — and an item whose content the token cannot see has nothing to
6474 /// report at all.
6475 fn resolve(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
6476 let resolved = self.resolve_unremembered(item)?;
6477 if let Some(resolved) = &resolved {
6478 self.resolved_cache()?
6479 .insert(resolved.id.clone(), resolved.clone());
6480 }
6481 Ok(resolved)
6482 }
6483
6484 /// [`Self::resolve`], without remembering the item it resolves: what reading a token off a
6485 /// write's own response needs, which says nothing this process should answer a later read
6486 /// with.
6487 fn resolve_unremembered(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
6488 let content = item.get("content").ok_or_else(|| SourceError::Malformed {
6489 message: "GitHub project item is missing content".into(),
6490 })?;
6491 if content.is_null() {
6492 return Ok(None);
6493 }
6494 let content_kind = match required_str(content, "__typename")? {
6495 "Issue" => ContentKind::Issue,
6496 "DraftIssue" => ContentKind::DraftIssue,
6497 _ => return Ok(None),
6498 };
6499 let field_values = item
6500 .get("fieldValues")
6501 .ok_or_else(|| SourceError::Malformed {
6502 message: "GitHub project item is missing fieldValues".into(),
6503 })?;
6504 complete_connection(field_values, "project item field values", NESTED_PAGE_SIZE)?;
6505 let nodes = field_values
6506 .get("nodes")
6507 .and_then(Value::as_array)
6508 .ok_or_else(|| SourceError::Malformed {
6509 message: "GitHub project item fieldValues.nodes is not an array".into(),
6510 })?;
6511 if let Some(labels) = content.get("labels") {
6512 complete_connection(labels, "content labels", NESTED_PAGE_SIZE)?;
6513 }
6514 let raw_body = optional_str(content, "body")?.map(str::to_owned);
6515 let (body, slot) = metadata_body(raw_body.clone())?;
6516 let parent = optional_str(content.get("parent").unwrap_or(&Value::Null), "id")?
6517 .map(|id| NativeId(id.to_owned()));
6518 // A draft has no sub-issues to summarise, and GitHub's schema gives it no field
6519 // to read one from; it is a task, and never a project.
6520 let sub_issues = match content_kind {
6521 ContentKind::Issue => sub_issue_total(content)?,
6522 ContentKind::DraftIssue => 0,
6523 };
6524 let content_id = required_str(content, "id")?;
6525 let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
6526 message: format!("GitHub issue {content_id}: {message}"),
6527 })?;
6528 let raw_title = required_str(content, "title")?;
6529 let kind = BoardKind::of(raw_title, parent.is_some(), sub_issues, marked);
6530 // The title a person wrote, which for a document is the one without the prefix —
6531 // the same way `content` above is the body without this source's metadata slot.
6532 let title = match kind {
6533 BoardKind::Document => raw_title[DESIGN_TITLE_PREFIX.len()..].to_owned(),
6534 BoardKind::Work(_) => raw_title.to_owned(),
6535 };
6536 let own_repository = content
6537 .pointer("/repository/nameWithOwner")
6538 .and_then(Value::as_str)
6539 .map(|origin| Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST)))
6540 .transpose()
6541 .map_err(|message| SourceError::Malformed { message })?;
6542 let repositories = if slot.contains_key(Repository::METADATA_KEY) {
6543 Repository::from_metadata(&slot)
6544 .map_err(|message| SourceError::Malformed { message })?
6545 } else {
6546 own_repository.clone().into_iter().collect()
6547 };
6548 let classification = Classification::from_metadata(&slot)
6549 .map_err(|message| SourceError::Malformed { message })?;
6550 let id = NativeId(content_id.to_owned());
6551 // Read only for a task, because only a task has either list: a project or a
6552 // document holding one of these keys holds nothing this source reports, and the
6553 // keys are left out of its caller-visible metadata all the same.
6554 let (delivers, delivered_by) = if kind == BoardKind::Work(ItemKind::Task) {
6555 let listed = |key: &str| {
6556 TaskRef::from_value(key, &id, Some(&self.name), slot.get(key))
6557 .map_err(|message| SourceError::Malformed { message })
6558 };
6559 (
6560 listed(TaskRef::DELIVERS_KEY)?,
6561 listed(TaskRef::DELIVERED_BY_KEY)?,
6562 )
6563 } else {
6564 (Vec::new(), Vec::new())
6565 };
6566 let (option, closed, reason) = Self::status_parts(nodes, content)?;
6567 let priority = self.held_priority(nodes)?;
6568 let item_labels = labels(content)?;
6569 // Present when the item was reached through its own issue, whose board entry
6570 // names the board; a read of the board's own items has the board already. An
6571 // empty id names nothing a field write could address, so it is read as absent and
6572 // the write goes back to reading the board.
6573 let board_id = item
6574 .pointer("/project/id")
6575 .and_then(Value::as_str)
6576 .filter(|id| !id.is_empty());
6577 let resolved = Resolved {
6578 item_id: required_str(item, "id")?.to_owned(),
6579 id,
6580 content_kind,
6581 kind,
6582 title,
6583 body: body.filter(|value| !value.is_empty()),
6584 raw_body,
6585 status: self
6586 .statuses
6587 .status(kind.status_kind(), option, closed, reason),
6588 option: option.map(str::to_owned),
6589 priority,
6590 closed,
6591 reason: closed.then(|| reason.map(str::to_owned)).flatten(),
6592 delivers,
6593 delivered_by,
6594 labels: item_labels.clone(),
6595 parent,
6596 origin: text_field(nodes, ORIGIN_FIELD)?.filter(|value| !value.is_empty()),
6597 projected: self.held_projections(nodes)?,
6598 number: match content_kind {
6599 ContentKind::Issue => Some(issue_number(content)?),
6600 // A draft is filed in no repository, so nothing ever numbered it:
6601 // `DraftIssue` declares no `number` at all, exactly as it declares no
6602 // `subIssuesSummary` the branch above reads.
6603 ContentKind::DraftIssue => None,
6604 },
6605 url: optional_str(content, "url")?.map(str::to_owned),
6606 created_at: optional_time(content, "createdAt")?,
6607 updated_at: optional_time(content, "updatedAt")?,
6608 item_updated_at: optional_time(item, "updatedAt")?,
6609 comment_count: content
6610 .pointer("/commentCount/totalCount")
6611 .and_then(Value::as_u64),
6612 relationship_events: content
6613 .pointer("/relationshipEvents/totalCount")
6614 .and_then(Value::as_u64),
6615 // The issue node is stamped wherever it was read; a board item a read of the issue
6616 // put together from its memberships is not.
6617 served_at: match optional_time(content, SERVED_AT)? {
6618 Some(served) => Some(served),
6619 None => optional_time(item, SERVED_AT)?,
6620 },
6621 // Both connections were read to their end above — one reporting a further page is
6622 // refused — so these are every field value and every label the item holds. A
6623 // response that did not select the labels at all says nothing of them, and gives
6624 // no facets.
6625 facets: content.get("labels").is_some().then(|| {
6626 change_token::Facets::new(kind.facet(), facet_fields(nodes), &item_labels).digest()
6627 }),
6628 own_repository,
6629 repositories,
6630 classification,
6631 slot,
6632 board_id: board_id.map(str::to_owned),
6633 fields: field_definitions(nodes),
6634 board_fields: Self::carried_board_fields(content, board_id)?,
6635 blocked_by: carried_blocked_by(content)?,
6636 };
6637 Ok(Some(resolved))
6638 }
6639
6640 /// The field definitions of the board `board_id` names — the project this issue's own
6641 /// board item is on — off the `boards` page a read of an issue by its own id carries, or
6642 /// `None` when the read carried none, carried no entry for that board, or the board item
6643 /// named no board, which a write then answers by reading the board's fields itself.
6644 ///
6645 /// Matched by the board's node id and never by its number alone: a project number is
6646 /// unique only within its owner, so another owner's board numbered alike can sit on the
6647 /// same page, and its field and option ids address nothing on this one.
6648 fn carried_board_fields(
6649 content: &Value,
6650 board_id: Option<&str>,
6651 ) -> Result<Option<Value>, SourceError> {
6652 let (Some(nodes), Some(board_id)) = (
6653 content.pointer("/boards/nodes").and_then(Value::as_array),
6654 board_id,
6655 ) else {
6656 return Ok(None);
6657 };
6658 let Some(board) = nodes.iter().find_map(|node| {
6659 let project = node.get("project")?;
6660 (project.get("id").and_then(Value::as_str) == Some(board_id)).then_some(project)
6661 }) else {
6662 return Ok(None);
6663 };
6664 let Some(fields) = board.get("fields").filter(|fields| !fields.is_null()) else {
6665 return Ok(None);
6666 };
6667 complete_connection(fields, "board fields", NESTED_PAGE_SIZE)?;
6668 Ok(Some(fields.clone()))
6669 }
6670
6671 /// What one board item's `Priority` field says, through this instance's mapping.
6672 ///
6673 /// An instance with no mapping holds no priority, so every item reads as `none` whatever
6674 /// its board holds. With one, no value is `none`, a mapped option is its level, and an
6675 /// option the mapping does not name is kept as itself — never read as a level or as
6676 /// `none` — for a read of the task to report by name.
6677 fn held_priority(&self, field_values: &[Value]) -> Result<HeldPriority, SourceError> {
6678 let Some(mapping) = &self.priorities else {
6679 return Ok(HeldPriority::Read(Priority::None));
6680 };
6681 // A value of the field that names no option — a text field someone called `Priority` —
6682 // is malformed rather than `none`: reading it as no priority would let the next copy
6683 // clear one a person set.
6684 let Some(option) = field_values
6685 .iter()
6686 .find(|value| {
6687 value.pointer("/field/name").and_then(Value::as_str) == Some(PRIORITY_FIELD)
6688 })
6689 .map(|value| required_str(value, "name"))
6690 .transpose()?
6691 else {
6692 return Ok(HeldPriority::Read(Priority::None));
6693 };
6694 Ok(mapping.priority_of(option).map_or_else(
6695 || HeldPriority::Unmapped(option.to_owned()),
6696 HeldPriority::Read,
6697 ))
6698 }
6699
6700 /// What each projected metadata field holds for one board item, by field name — every text
6701 /// value GitHub answers, an empty one included.
6702 fn held_projections(
6703 &self,
6704 field_values: &[Value],
6705 ) -> Result<BTreeMap<String, String>, SourceError> {
6706 let mut held = BTreeMap::new();
6707 for projection in &self.metadata_fields {
6708 if let Some(text) = text_field(field_values, &projection.field)? {
6709 held.insert(projection.field.to_string(), text);
6710 }
6711 }
6712 Ok(held)
6713 }
6714
6715 /// What one board item's status is read from: its `Status` option, whether its issue
6716 /// is closed, and the reason it was closed with. [`BoardStatuses::status`] turns the
6717 /// three into the status it reports.
6718 fn status_parts<'a>(
6719 field_values: &'a [Value],
6720 content: &'a Value,
6721 ) -> Result<(Option<&'a str>, bool, Option<&'a str>), SourceError> {
6722 let option = field_values
6723 .iter()
6724 .find(|value| value.pointer("/field/name").and_then(Value::as_str) == Some("Status"))
6725 .map(|value| required_str(value, "name"))
6726 .transpose()?;
6727 let closed = optional_str(content, "state")? == Some("CLOSED");
6728 Ok((option, closed, optional_str(content, "stateReason")?))
6729 }
6730
6731 /// The board Status option this write selects, or the refusal that says why not.
6732 ///
6733 /// The mapped option is required for both open and terminal targets. A terminal write
6734 /// validates it before changing either representation, so it can never fall back to
6735 /// closing an issue whose board cannot display the matching status.
6736 ///
6737 /// Answers the field's id, the option's id, and the option's name as the board spells
6738 /// it — which is the name a read of the item reports once it sits there.
6739 fn column_for(
6740 &self,
6741 fields: &Value,
6742 kind: ItemKind,
6743 category: StatusCategory,
6744 target: &StatusTarget,
6745 ) -> Result<Option<(String, String, String)>, SourceError> {
6746 let Some(wanted) = target.option() else {
6747 return Ok(None);
6748 };
6749 let missing = |detail: &str| SourceError::Refused {
6750 message: format!(
6751 "{} status {} of source {} needs the board Status option {wanted:?}, and \
6752 {detail}; next: add that option to the board, which `onetaskgraph sources \
6753 fields {} --apply` does, or point status_mapping.{}.{} of this source at one \
6754 it has",
6755 kind.marker(),
6756 category_name(category),
6757 self.name,
6758 self.name,
6759 category_name(category),
6760 kind.marker()
6761 ),
6762 };
6763 let Some(field) = Board::field(fields, "Status")? else {
6764 return Err(missing("this board has no Status field"));
6765 };
6766 if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
6767 return Err(missing(
6768 "this board's Status field is not a single-select field",
6769 ));
6770 }
6771 let option = field
6772 .get("options")
6773 .and_then(Value::as_array)
6774 .and_then(|options| {
6775 options.iter().find(|option| {
6776 option
6777 .get("name")
6778 .and_then(Value::as_str)
6779 .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
6780 })
6781 });
6782 match option {
6783 None => Err(missing("this board does not have it")),
6784 Some(option) => Ok(Some((
6785 required_str(field, "id")?.to_owned(),
6786 required_str(option, "id")?.to_owned(),
6787 required_str(option, "name")?.to_owned(),
6788 ))),
6789 }
6790 }
6791
6792 /// The refusal a status that closes an issue is answered with over a board draft.
6793 fn closes_a_draft(&self, category: StatusCategory) -> SourceError {
6794 SourceError::Refused {
6795 message: format!(
6796 "status {} of source {} closes the item's issue, and GitHub draft items have \
6797 no open or closed state",
6798 category_name(category),
6799 self.name
6800 ),
6801 }
6802 }
6803
6804 /// What a status write to one item needs of the board: the board's id and the
6805 /// definition of its `Status` field, read off the item when the item says both.
6806 ///
6807 /// The same reasoning as [`Self::fields_for`]: a node read of the item names its board,
6808 /// and its `Status` value carries that field's definition, options and all. An item that
6809 /// does not say — no board id, or no `Status` value to read the field off — takes them
6810 /// from [`Self::board_fields`], which reads no item.
6811 async fn status_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
6812 if let Some(board) = item.carried_board() {
6813 return Ok(board);
6814 }
6815 if item.defines("Status")
6816 && let Some(board_id) = item.named_board()
6817 {
6818 return Ok(BoardFields {
6819 id: board_id,
6820 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
6821 });
6822 }
6823 self.board_fields().await
6824 }
6825
6826 /// Set one task's status and nothing else; see [`TaskSource::set_task_status`].
6827 async fn set_status(
6828 &self,
6829 id: &NativeId,
6830 category: StatusCategory,
6831 ) -> Result<Option<Status>, SourceError> {
6832 // Refused before anything is read, in the words a write of the same status is.
6833 let target = self.resolved_target(ItemKind::Task, category)?;
6834 // An item read by issue reference carries only what this write needs, so what it
6835 // becomes is never remembered for a later read to be answered from.
6836 let held = self.take_held(id)?;
6837 let by_reference = held.is_some();
6838 let bound = match held {
6839 Some(item) => Some(item),
6840 None => self.bound_item(id).await?,
6841 };
6842 let Some(mut item) = bound.filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
6843 else {
6844 return Ok(None);
6845 };
6846 let board = self.status_board(&item).await?;
6847 let (field, option, name) = self
6848 .column_for(&board.fields, ItemKind::Task, category, &target)?
6849 .ok_or_else(|| SourceError::Malformed {
6850 message: format!(
6851 "status {} of source {} names no board Status option",
6852 category_name(category),
6853 self.name
6854 ),
6855 })?;
6856 if item.status.category == category && item.option.as_deref() == Some(&name) {
6857 return Ok(Some(item.status));
6858 }
6859 match &target {
6860 StatusTarget::Terminal(_, reason) => {
6861 if item.content_kind == ContentKind::DraftIssue {
6862 return Err(self.closes_a_draft(category));
6863 }
6864 // The option first, so a refused selection leaves an open issue open rather
6865 // than closed behind a card that still reads open.
6866 self.set_item_field(
6867 board.id.as_str(),
6868 &item.item_id,
6869 &field,
6870 json!({"singleSelectOptionId": option}),
6871 )
6872 .await?;
6873 // An issue already closed in a way that reads as this category keeps its state
6874 // and its reason: only its card was out of line, and closing it again would
6875 // overwrite a reason — a duplicate's — that says more than this write does.
6876 let already = item.closed && item.status.category == category;
6877 if !already {
6878 self.update_content(
6879 ContentKind::Issue,
6880 &item.id,
6881 json!({"stateInput": state_input(Some(&target))}),
6882 )
6883 .await?;
6884 }
6885 let reason = if already {
6886 item.reason.clone()
6887 } else {
6888 Some(reason.reason().to_owned())
6889 };
6890 item.closed = true;
6891 item.status =
6892 self.statuses
6893 .status(ItemKind::Task, Some(&name), true, reason.as_deref());
6894 item.option = Some(name);
6895 item.reason = reason;
6896 }
6897 StatusTarget::Column(_) => {
6898 // An option is what an open item's status is, so a closed issue is reopened
6899 // first — sitting closed in the column, it would read back as closed. A draft has
6900 // no state to reopen.
6901 if item.content_kind == ContentKind::Issue && item.closed {
6902 self.update_content(
6903 ContentKind::Issue,
6904 &item.id,
6905 json!({"stateInput": state_input(Some(&target))}),
6906 )
6907 .await?;
6908 item.closed = false;
6909 }
6910 self.set_item_field(
6911 board.id.as_str(),
6912 &item.item_id,
6913 &field,
6914 json!({"singleSelectOptionId": option}),
6915 )
6916 .await?;
6917 item.status = self
6918 .statuses
6919 .status(ItemKind::Task, Some(&name), false, None);
6920 item.option = Some(name);
6921 }
6922 StatusTarget::Disabled(_) => {
6923 unreachable!("resolved_target refused a disabled status")
6924 }
6925 }
6926 let status = item.status.clone();
6927 if !by_reference {
6928 self.remember_written(item, false)?;
6929 }
6930 Ok(Some(status))
6931 }
6932
6933 /// Replace one task's `delivered_by` and nothing else; see
6934 /// [`TaskSource::set_delivered_by`].
6935 ///
6936 /// One update of the body, which differs from the body GitHub holds only inside the
6937 /// metadata slot — see [`with_slot`]. A body that would not change is not sent at all.
6938 async fn replace_delivered_by(
6939 &self,
6940 id: &NativeId,
6941 delivered_by: &[TaskRef],
6942 ) -> Result<Option<()>, SourceError> {
6943 let entries = TaskRef::listed(
6944 TaskRef::DELIVERED_BY_KEY,
6945 id,
6946 Some(&self.name),
6947 delivered_by.to_vec(),
6948 )
6949 .map_err(|message| SourceError::Refused { message })?;
6950 let Some(mut item) = self
6951 .bound_item(id)
6952 .await?
6953 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
6954 else {
6955 return Ok(None);
6956 };
6957 let mut slot = item.slot.clone();
6958 set_task_list(&mut slot, TaskRef::DELIVERED_BY_KEY, &entries);
6959 self.write_slot(&mut item, &slot).await?;
6960 item.delivered_by = entries;
6961 self.remember_written(item, false)?;
6962 Ok(Some(()))
6963 }
6964
6965 /// Set one caller key of the metadata slot of one issue of `kind`, and nothing else;
6966 /// see [`TaskSource::set_task_metadata`].
6967 ///
6968 /// `None` when this board holds no item by that id, or holds one of another kind. The
6969 /// answer is the item as this source now reads it, so what a caller is told the key
6970 /// holds is what the slot holds.
6971 ///
6972 /// A key already holding the value is answered without a write, compared as JSON rather
6973 /// than as the body's bytes: a slot a person spelled with other whitespace would
6974 /// otherwise be re-encoded, which is a write that changes nothing the caller asked for.
6975 async fn set_slot_key(
6976 &self,
6977 id: &NativeId,
6978 kind: BoardKind,
6979 key: &MetadataKey,
6980 value: &Value,
6981 ) -> Result<Option<Resolved>, SourceError> {
6982 let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
6983 return Ok(None);
6984 };
6985 if item.slot.get(key.as_str()) == Some(value) {
6986 return Ok(Some(item));
6987 }
6988 let mut slot = item.slot.clone();
6989 slot.insert(key.as_str().to_owned(), value.clone());
6990 // A key a board text field projects moves that field first, so the body — the value's
6991 // one authoritative home — is written last, as every write of an existing item is.
6992 if self
6993 .metadata_fields
6994 .iter()
6995 .any(|projection| &*projection.key == key.as_str())
6996 {
6997 let board = self.projection_board(&item).await?;
6998 let (writes, projected) = self.projection_writes(
6999 &board.fields,
7000 Some(&item.projected),
7001 &slot,
7002 Some(&[key.as_str()]),
7003 )?;
7004 let (mut values, mut clears) = (Vec::new(), Vec::new());
7005 for write in &writes {
7006 write.join(&mut values, &mut clears);
7007 }
7008 self.set_item_fields(board.id.as_str(), &item.item_id, &values, &clears)
7009 .await?;
7010 item.projected = projected;
7011 }
7012 self.write_slot(&mut item, &slot).await?;
7013 self.remember_written(item.clone(), false)?;
7014 Ok(Some(item))
7015 }
7016
7017 /// What a projection write to `item` needs of the board, read off the item when it says
7018 /// enough, as [`Self::fields_for`] reads it.
7019 async fn projection_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
7020 if let Some(board) = item.carried_board() {
7021 return Ok(board);
7022 }
7023 if let Some(board_id) = item.named_board()
7024 && self
7025 .metadata_fields
7026 .iter()
7027 .all(|projection| item.defines(&projection.field))
7028 {
7029 return Ok(BoardFields {
7030 id: board_id,
7031 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7032 });
7033 }
7034 self.board_fields().await
7035 }
7036
7037 /// Put `slot` in one item's metadata slot with a single update of its body, and bring
7038 /// `item` up to what that write left.
7039 ///
7040 /// The body sent differs from the body GitHub holds only inside the slot — see
7041 /// [`with_slot`] — and a body that would not change is not sent at all. It goes through
7042 /// the mutation the item's content takes, so a board draft's body is written with
7043 /// `updateProjectV2DraftIssue` exactly as an issue's is with `updateIssue`.
7044 async fn write_slot(
7045 &self,
7046 item: &mut Resolved,
7047 slot: &BTreeMap<String, Value>,
7048 ) -> Result<(), SourceError> {
7049 let held = item.raw_body.clone().unwrap_or_default();
7050 let body = with_slot(&held, slot)?;
7051 if body != held {
7052 self.update_content(item.content_kind, &item.id, json!({"body": body}))
7053 .await?;
7054 }
7055 let (visible, slot) = metadata_body(Some(body.clone()))?;
7056 item.body = visible.filter(|value| !value.is_empty());
7057 item.raw_body = Some(body);
7058 item.slot = slot;
7059 Ok(())
7060 }
7061
7062 /// This instance's target for a category written to an item of `kind`, refusing one
7063 /// that kind has no option for — before anything is read or written.
7064 ///
7065 /// Nothing here mutates the board's option set to make room for a status. GitHub
7066 /// documents `UpdateProjectV2FieldInput.singleSelectOptions` as *"provided values
7067 /// overwrite existing options"*, so no addition is additive and a mistake destroys the
7068 /// field and every item's status.
7069 fn resolved_target(
7070 &self,
7071 kind: ItemKind,
7072 category: StatusCategory,
7073 ) -> Result<StatusTarget, SourceError> {
7074 let target = self.statuses.target(kind, category).clone();
7075 let StatusTarget::Disabled(why) = target else {
7076 return Ok(target);
7077 };
7078 let refusal = why.refusal(&self.name, category, kind);
7079 // Why there is no shipped default, which is the question a person meeting this
7080 // refusal on a source that never mentioned the category asks.
7081 let shipped_none = match category {
7082 StatusCategory::Draft => Some(
7083 "draft has no shipped default because GitHub draft issues cannot have \
7084 sub-issues, and this source stores a project's tasks as its issue's sub-issues",
7085 ),
7086 StatusCategory::Unknown => Some(
7087 "unknown has no shipped default because this board keeps no open-ended status \
7088 word: every word classified unknown is written to the one board Status option \
7089 status_mapping.unknown names",
7090 ),
7091 _ => None,
7092 };
7093 Err(match (refusal, shipped_none, why) {
7094 (SourceError::Refused { message }, Some(note), UnmappedStatus::Unconfigured) => {
7095 SourceError::Refused {
7096 message: format!("{message}; {note}"),
7097 }
7098 }
7099 (refusal, _, _) => refusal,
7100 })
7101 }
7102
7103 /// What writing `priority` does to one item's `Priority` field on this board, or the
7104 /// refusal naming what the board lacks.
7105 ///
7106 /// `none` is no value, so it clears the field — and asks nothing of an item that holds
7107 /// none already, or of an item not created yet. Every other priority selects the option
7108 /// the mapping names, matched case-insensitively; a board with no `Priority` field, or
7109 /// without that option, is refused rather than given one: reads and writes never create
7110 /// a field or an option.
7111 fn priority_write(
7112 &self,
7113 fields: &Value,
7114 existing: Option<&Resolved>,
7115 priority: Priority,
7116 ) -> Result<Option<PriorityWrite>, SourceError> {
7117 let Some(mapping) = &self.priorities else {
7118 return Err(self.holds_no_priority());
7119 };
7120 let Some(wanted) = mapping.option(priority) else {
7121 if !existing.is_some_and(Resolved::holds_priority) {
7122 return Ok(None);
7123 }
7124 let field =
7125 Board::field(fields, PRIORITY_FIELD)?.ok_or_else(|| SourceError::Malformed {
7126 message: format!(
7127 "an item holding a {PRIORITY_FIELD} value was read without that field"
7128 ),
7129 })?;
7130 return Ok(Some(PriorityWrite::Clear {
7131 field: required_str(field, "id")?.to_owned(),
7132 }));
7133 };
7134 let missing = |detail: &str| SourceError::Refused {
7135 message: format!(
7136 "priority {priority} of source {} needs the board {PRIORITY_FIELD} option \
7137 {wanted:?}, and {detail}; run `onetaskgraph sources fields {} --apply` to add \
7138 it, or point priority_mapping.{priority} of this source at an option the board \
7139 has",
7140 self.name, self.name
7141 ),
7142 };
7143 let Some(field) = Board::field(fields, PRIORITY_FIELD)? else {
7144 return Err(missing(&format!(
7145 "this board has no {PRIORITY_FIELD} field"
7146 )));
7147 };
7148 if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
7149 return Err(missing(&format!(
7150 "this board's {PRIORITY_FIELD} field is not a single-select field"
7151 )));
7152 }
7153 // An options list that is absent or not a list is an answer this source cannot read,
7154 // not a board lacking the option: `sources fields --apply` is no remedy for it.
7155 let option = field
7156 .get("options")
7157 .and_then(Value::as_array)
7158 .ok_or_else(|| SourceError::Malformed {
7159 message: format!("GitHub {PRIORITY_FIELD} field options is not an array"),
7160 })?
7161 .iter()
7162 .find(|option| {
7163 option
7164 .get("name")
7165 .and_then(Value::as_str)
7166 .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
7167 })
7168 .ok_or_else(|| missing("this board does not have it"))?;
7169 Ok(Some(PriorityWrite::Select {
7170 field: required_str(field, "id")?.to_owned(),
7171 option: required_str(option, "id")?.to_owned(),
7172 }))
7173 }
7174
7175 /// What writing `metadata` does to each projected text field of one item, and what those
7176 /// fields hold after it — or the refusal, before anything is sent.
7177 ///
7178 /// `held` is what the item's fields hold now, `None` for an item not created yet. `keys`
7179 /// narrows the work to the entries projecting one of those metadata keys, for a write that
7180 /// touches only them; `None` is every entry. A string the field already holds, and nothing
7181 /// for a field holding nothing, sends nothing. A value no text field can hold is refused,
7182 /// and so is a board without the field, or with a field of that name that is not a text
7183 /// field: reads and writes never create a field.
7184 fn projection_writes(
7185 &self,
7186 fields: &Value,
7187 held: Option<&BTreeMap<String, String>>,
7188 metadata: &BTreeMap<String, Value>,
7189 keys: Option<&[&str]>,
7190 ) -> Result<(Vec<ProjectionWrite>, BTreeMap<String, String>), SourceError> {
7191 let mut projected = held.cloned().unwrap_or_default();
7192 let mut writes = Vec::new();
7193 for projection in self
7194 .metadata_fields
7195 .iter()
7196 .filter(|projection| keys.is_none_or(|keys| keys.contains(&&*projection.key)))
7197 {
7198 let wanted = projection.projected(metadata, &self.name)?;
7199 let field = self.projection_field(fields, projection)?;
7200 let holding = projected.get(&*projection.field);
7201 match wanted {
7202 Projected::Text(text) if holding != Some(&text) => {
7203 writes.push(ProjectionWrite::Set {
7204 field,
7205 text: text.clone(),
7206 });
7207 projected.insert(projection.field.to_string(), text);
7208 }
7209 Projected::Nothing if holding.is_some() => {
7210 writes.push(ProjectionWrite::Clear { field });
7211 projected.remove(&*projection.field);
7212 }
7213 Projected::Text(_) | Projected::Nothing => {}
7214 }
7215 }
7216 Ok((writes, projected))
7217 }
7218
7219 /// The id of the board text field one projection writes, or the refusal naming what the
7220 /// board has instead.
7221 fn projection_field(
7222 &self,
7223 fields: &Value,
7224 projection: &MetadataField,
7225 ) -> Result<String, SourceError> {
7226 let refuse = |detail: String| SourceError::Refused {
7227 message: format!(
7228 "source {} projects metadata key {:?} onto the board text field {:?}, and \
7229 {detail}; next: run `onetaskgraph sources fields {} --apply` to create it as a \
7230 text field, or name another field in metadata_fields",
7231 self.name, &*projection.key, &*projection.field, self.name
7232 ),
7233 };
7234 let Some(field) = Board::field(fields, &projection.field)? else {
7235 return Err(refuse("this board has no field of that name".to_owned()));
7236 };
7237 let typename = optional_str(field, "__typename")?.unwrap_or("field of another type");
7238 let data_type = optional_str(field, "dataType")?;
7239 if typename != "ProjectV2Field" || data_type != Some("TEXT") {
7240 return Err(refuse(format!(
7241 "this board's field of that name is not a text field (it is a {}), so it is \
7242 left as it is; rename or remove that field first",
7243 data_type.unwrap_or(typename)
7244 )));
7245 }
7246 Ok(required_str(field, "id")?.to_owned())
7247 }
7248
7249 /// Apply one priority write to one board item.
7250 async fn write_priority(
7251 &self,
7252 board_id: &str,
7253 item_id: &str,
7254 write: &PriorityWrite,
7255 ) -> Result<(), SourceError> {
7256 match write {
7257 PriorityWrite::Select { field, option } => {
7258 self.set_item_field(
7259 board_id,
7260 item_id,
7261 field,
7262 json!({"singleSelectOptionId": option}),
7263 )
7264 .await
7265 }
7266 PriorityWrite::Clear { field } => {
7267 let data = self
7268 .graphql(
7269 graphql::CLEAR_FIELD,
7270 json!({"input":{"projectId":board_id,"itemId":item_id,"fieldId":field},
7271 "readPriority":false,"priorityName":PRIORITY_FIELD}),
7272 )
7273 .await?;
7274 let returned = data
7275 .pointer("/clearProjectV2ItemFieldValue/projectV2Item")
7276 .ok_or_else(|| SourceError::Malformed {
7277 message: "GitHub field clear returned no project item".into(),
7278 })?;
7279 if required_str(returned, "id")? != item_id {
7280 return Err(SourceError::Malformed {
7281 message: "GitHub field clear returned the wrong project item".into(),
7282 });
7283 }
7284 Ok(())
7285 }
7286 }
7287 }
7288
7289 /// The refusal a priority is answered with by an instance configured with no
7290 /// `priority_mapping`, which holds none.
7291 fn holds_no_priority(&self) -> SourceError {
7292 SourceError::Refused {
7293 message: format!(
7294 "source {} holds no task priority: its configuration sets no priority_mapping; \
7295 next: set priority_mapping on this source, then run `onetaskgraph sources \
7296 fields {} --apply` to set its board up",
7297 self.name, self.name
7298 ),
7299 }
7300 }
7301
7302 /// Set one task's priority and nothing else; see [`TaskSource::set_task_priority`].
7303 ///
7304 /// One field write — a select, or a clear for `none` — and no title, body, label, state
7305 /// or `Status` request. Clearing a priority an item does not hold sends nothing.
7306 async fn set_priority(
7307 &self,
7308 id: &NativeId,
7309 priority: Priority,
7310 ) -> Result<Option<Priority>, SourceError> {
7311 if self.priorities.is_none() {
7312 return Err(self.holds_no_priority());
7313 }
7314 let Some(mut item) = self
7315 .bound_item(id)
7316 .await?
7317 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
7318 else {
7319 return Ok(None);
7320 };
7321 if priority == Priority::None && !item.holds_priority() {
7322 return Ok(Some(priority));
7323 }
7324 // The item's own read carries the field's definition whenever it holds a value of
7325 // it, which a clear always does; a select onto an item holding none reads the board.
7326 let board = match (item.carried_board(), item.named_board()) {
7327 (Some(board), _) => board,
7328 (None, Some(id)) if item.defines(PRIORITY_FIELD) => BoardFields {
7329 id,
7330 fields: json!({"nodes": item.fields.clone(), "pageInfo": {"hasNextPage": false}}),
7331 },
7332 _ => self.board_fields().await?,
7333 };
7334 let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? else {
7335 return Ok(Some(priority));
7336 };
7337 let (document, root, input) = match write {
7338 PriorityWrite::Select { field, option } => (
7339 graphql::UPDATE_FIELD,
7340 "updateProjectV2ItemFieldValue",
7341 json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field,"value":{"singleSelectOptionId":option}}),
7342 ),
7343 PriorityWrite::Clear { field } => (
7344 graphql::CLEAR_FIELD,
7345 "clearProjectV2ItemFieldValue",
7346 json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field}),
7347 ),
7348 };
7349 let data = self
7350 .graphql(
7351 document,
7352 json!({"input":input,"readPriority":true,"priorityName":PRIORITY_FIELD}),
7353 )
7354 .await?;
7355 let returned = data
7356 .get(root)
7357 .and_then(|value| value.get("projectV2Item"))
7358 .ok_or_else(|| SourceError::Malformed {
7359 message: "GitHub priority write returned no project item".into(),
7360 })?;
7361 if required_str(returned, "id")? != item.item_id {
7362 return Err(SourceError::Malformed {
7363 message: "GitHub priority write returned the wrong project item".into(),
7364 });
7365 }
7366 let value = returned
7367 .get("fieldValueByName")
7368 .ok_or_else(|| SourceError::Malformed {
7369 message: "GitHub priority write returned no priority read-back".into(),
7370 })?;
7371 if !value.is_null()
7372 && value.pointer("/field/name").and_then(Value::as_str) != Some(PRIORITY_FIELD)
7373 {
7374 return Err(SourceError::Malformed {
7375 message: "GitHub priority read-back is not a Priority field value".into(),
7376 });
7377 }
7378 let values = if value.is_null() {
7379 Vec::new()
7380 } else {
7381 vec![value.clone()]
7382 };
7383 item.priority = self.held_priority(&values)?;
7384 let answer = item.task()?.priority;
7385 self.remember_written(item, false)?;
7386 Ok(Some(answer))
7387 }
7388
7389 /// Replace one task's visible body and nothing else; see
7390 /// [`TaskSource::set_task_content`].
7391 ///
7392 /// One update of the body, which differs from the body GitHub holds only outside the
7393 /// metadata slot — the slot is kept byte for byte, so every caller key and every list
7394 /// this source keeps there reads back as it was. A body that would not change is not
7395 /// sent at all.
7396 async fn replace_content(
7397 &self,
7398 id: &NativeId,
7399 content: &str,
7400 ) -> Result<Option<()>, SourceError> {
7401 let Some(mut item) = self
7402 .bound_item(id)
7403 .await?
7404 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
7405 else {
7406 return Ok(None);
7407 };
7408 let held = item.raw_body.clone().unwrap_or_default();
7409 let body = with_content(&held, content)?;
7410 // Checked before anything is sent: content ending in what this source reads as its own
7411 // metadata slot would read back as metadata rather than as the content it was.
7412 let (visible, slot) = metadata_body(Some(body.clone()))?;
7413 if visible.as_deref().unwrap_or_default() != content || slot != item.slot {
7414 return Err(SourceError::Refused {
7415 message: format!(
7416 "this content ends in what source {} reads as its own metadata slot \
7417 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
7418 as content; next: remove that trailing block from the content",
7419 self.name
7420 ),
7421 });
7422 }
7423 if body != held {
7424 self.update_content(item.content_kind, &item.id, json!({"body": body}))
7425 .await?;
7426 }
7427 item.body = visible.filter(|value| !value.is_empty());
7428 item.raw_body = Some(body);
7429 item.slot = slot;
7430 self.remember_written(item, false)?;
7431 Ok(Some(()))
7432 }
7433
7434 /// Apply one targeted update to one task; see [`TaskSource::update_task`].
7435 ///
7436 /// One read of the item — which carries the board's field definitions and the issue's
7437 /// `blockedBy`, so neither is read again — and then only what differs from it: the
7438 /// `Status` option and the `Priority` field together in one request, the `blockedBy`
7439 /// additions and removals the named edges differ by, and last one `updateIssue` carrying
7440 /// the title, the body — visible content and metadata slot together — and a state change.
7441 /// So an update naming any of title, body, metadata, status and priority is one read and
7442 /// at most two writes. The body goes last so that a write refused part-way leaves it, and
7443 /// the metadata in it, as it stood. A terminal status selects its option and then closes,
7444 /// as a whole write does; an open one selects its option and then reopens. The origin
7445 /// field is never written: an update is of an item that already exists, whose origin is
7446 /// what it is.
7447 ///
7448 /// The task answered is the item as those writes left it, built from the read and what was
7449 /// sent rather than read again — the same record a later read in this run answers from.
7450 async fn targeted_update(
7451 &self,
7452 id: &NativeId,
7453 update: &TaskUpdate,
7454 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
7455 // Everything this source can refuse without reading the item is refused first, in the
7456 // words a whole write of the same fields is refused with.
7457 update.consistent()?;
7458 if update
7459 .title
7460 .as_deref()
7461 .is_some_and(|title| title.starts_with(DESIGN_TITLE_PREFIX))
7462 {
7463 return Err(SourceError::Refused {
7464 message: format!(
7465 "the title of this task begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
7466 spells a document, so it would read back as one rather than as a task; \
7467 retitle it",
7468 self.name
7469 ),
7470 });
7471 }
7472 if let Some(delivers) = &update.delivers {
7473 TaskRef::listed(
7474 TaskRef::DELIVERS_KEY,
7475 id,
7476 Some(&self.name),
7477 delivers.clone(),
7478 )
7479 .map_err(|message| SourceError::Refused { message })?;
7480 }
7481 if self.priorities.is_none()
7482 && update
7483 .priority
7484 .is_some_and(|priority| priority != Priority::None)
7485 {
7486 return Err(self.holds_no_priority());
7487 }
7488 let target = update
7489 .status
7490 .as_ref()
7491 .map(|status| self.resolved_target(ItemKind::Task, status.category))
7492 .transpose()?;
7493 let Some(mut item) = self
7494 .bound_item(id)
7495 .await?
7496 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
7497 else {
7498 return Ok(None);
7499 };
7500 let before = item.task()?;
7501
7502 let mut status_move = None;
7503 if let (Some(status), Some(target)) = (&update.status, target) {
7504 let board = self.status_board(&item).await?;
7505 let (field, option, name) = self
7506 .column_for(&board.fields, ItemKind::Task, status.category, &target)?
7507 .ok_or_else(|| SourceError::Malformed {
7508 message: format!(
7509 "status {} of source {} names no board Status option",
7510 category_name(status.category),
7511 self.name
7512 ),
7513 })?;
7514 let terminal = matches!(target, StatusTarget::Terminal(_, _));
7515 if terminal && item.content_kind == ContentKind::DraftIssue {
7516 return Err(self.closes_a_draft(status.category));
7517 }
7518 let landed = match &target {
7519 StatusTarget::Terminal(_, reason) => {
7520 self.statuses
7521 .status(ItemKind::Task, Some(&name), true, Some(reason.reason()))
7522 }
7523 _ => self
7524 .statuses
7525 .status(ItemKind::Task, Some(&name), false, None),
7526 };
7527 let option_moves = item
7528 .option
7529 .as_deref()
7530 .is_none_or(|held| !held.eq_ignore_ascii_case(&name));
7531 let state_moves = item.content_kind == ContentKind::Issue
7532 && (item.closed != terminal || (terminal && item.status != landed));
7533 if let Some(moves) = Moves::of(option_moves, state_moves) {
7534 status_move = Some(StatusMove {
7535 board: board.id,
7536 field,
7537 option,
7538 name,
7539 target,
7540 landed,
7541 moves,
7542 });
7543 }
7544 }
7545
7546 let mut priority_move = None;
7547 if let Some(priority) = update.priority
7548 && self.priorities.is_some()
7549 && item.priority != HeldPriority::Read(priority)
7550 {
7551 let board = match (item.carried_board(), item.named_board()) {
7552 (Some(board), _) => board,
7553 (None, Some(board)) if item.defines(PRIORITY_FIELD) => BoardFields {
7554 id: board,
7555 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7556 },
7557 _ => self.board_fields().await?,
7558 };
7559 if let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? {
7560 priority_move = Some((board.id, write, priority));
7561 }
7562 }
7563
7564 // The metadata keys this update names that a board text field projects, and what
7565 // that does to those fields — refused, as a whole write refuses it, before anything
7566 // is sent.
7567 let touched: Vec<&str> = update
7568 .metadata_set
7569 .keys()
7570 .chain(update.metadata_remove.iter())
7571 .map(MetadataKey::as_str)
7572 .collect();
7573 let mut projection_move = None;
7574 if self
7575 .metadata_fields
7576 .iter()
7577 .any(|projection| touched.contains(&&*projection.key))
7578 {
7579 let mut metadata = item.slot.clone();
7580 for (key, value) in &update.metadata_set {
7581 metadata.insert(key.as_str().to_owned(), value.clone());
7582 }
7583 for key in &update.metadata_remove {
7584 metadata.remove(key.as_str());
7585 }
7586 let board = self.projection_board(&item).await?;
7587 let (writes, projected) = self.projection_writes(
7588 &board.fields,
7589 Some(&item.projected),
7590 &metadata,
7591 Some(&touched),
7592 )?;
7593 projection_move = Some((board.id, writes, projected));
7594 }
7595
7596 // Resolved before the body is composed, because a far end `blockedBy` cannot name is
7597 // recorded in the slot, and the slot travels in the one body update below.
7598 let edges = match &update.depends_on {
7599 Some(edges) => Some(
7600 self.partition_edges(
7601 BoardKind::Work(ItemKind::Task),
7602 item.content_kind,
7603 item.blocked_by.as_deref(),
7604 edges,
7605 )
7606 .await?,
7607 ),
7608 None => None,
7609 };
7610
7611 let mut slot = item.slot.clone();
7612 for (key, value) in &update.metadata_set {
7613 slot.insert(key.as_str().to_owned(), value.clone());
7614 }
7615 for key in &update.metadata_remove {
7616 slot.remove(key.as_str());
7617 }
7618 if let Some(delivers) = &update.delivers {
7619 set_task_list(&mut slot, TaskRef::DELIVERS_KEY, delivers);
7620 }
7621 if let Some((_, recorded)) = &edges {
7622 record_edges(&mut slot, recorded);
7623 }
7624 let held = item.raw_body.clone().unwrap_or_default();
7625 let content = match &update.content {
7626 Some(content) => with_content(&held, content)?,
7627 None => held.clone(),
7628 };
7629 // A slot holding what it held is kept byte for byte, compared as JSON rather than as
7630 // the body's bytes, as a metadata write compares it: a slot a person spelled with
7631 // other whitespace would otherwise be re-encoded, which is a write nobody asked for.
7632 let body = if slot == item.slot {
7633 content
7634 } else {
7635 with_slot(&content, &slot)?
7636 };
7637 // Checked before anything is sent, as a content write checks it: content ending in
7638 // what this source reads as its own slot would read back as metadata.
7639 let (visible, read) = metadata_body(Some(body.clone()))?;
7640 let wanted = update.content.as_deref().or(item.body.as_deref());
7641 if visible.as_deref().unwrap_or_default() != wanted.unwrap_or_default() || read != slot {
7642 return Err(SourceError::Refused {
7643 message: format!(
7644 "this content ends in what source {} reads as its own metadata slot \
7645 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
7646 as content; next: remove that trailing block from the content",
7647 self.name
7648 ),
7649 });
7650 }
7651 let recorded_moves =
7652 slot.get(DependencyEdge::RECORDED_KEY) != item.slot.get(DependencyEdge::RECORDED_KEY);
7653
7654 // One `updateIssue` carries all three, because every mutation spends the secondary
7655 // limiter and the title, body and state are one mutation's inputs.
7656 let mut fields = serde_json::Map::new();
7657 if let Some(title) = update.title.as_ref().filter(|title| **title != item.title) {
7658 fields.insert("title".to_owned(), json!(title));
7659 }
7660 if body != held {
7661 fields.insert("body".to_owned(), json!(body));
7662 }
7663 if let Some(moving) = status_move.as_ref().filter(|moving| moving.moves.state()) {
7664 fields.insert("stateInput".to_owned(), state_input(Some(&moving.target)));
7665 }
7666 // **The body is written last, and that is the guarantee a refusal part-way keeps.**
7667 // GitHub runs no two requests as one, and runs one document's mutation fields in order
7668 // without undoing an earlier field when a later one fails — so a body written before a
7669 // board field the board then refused would be left changed. Written after every other
7670 // write has landed, a refusal anywhere leaves the item's body, and every metadata key
7671 // it carries, exactly as they stood. So the `Status` option and the `Priority` field go
7672 // first, together in one request — a terminal option selected before the issue
7673 // closes, as a whole write does — then the `blockedBy` difference, then the body.
7674 let mut board_writes: Vec<(&BoardId, (String, Value))> = Vec::new();
7675 let mut clears: Vec<(&BoardId, &str)> = Vec::new();
7676 if let Some(moving) = status_move.as_ref().filter(|moving| moving.moves.option()) {
7677 board_writes.push((
7678 &moving.board,
7679 (
7680 moving.field.clone(),
7681 json!({"singleSelectOptionId": moving.option}),
7682 ),
7683 ));
7684 }
7685 match &priority_move {
7686 Some((board, PriorityWrite::Select { field, option }, _)) => board_writes.push((
7687 board,
7688 (field.clone(), json!({"singleSelectOptionId": option})),
7689 )),
7690 Some((board, PriorityWrite::Clear { field }, _)) => clears.push((board, field)),
7691 None => {}
7692 }
7693 if let Some((board, writes, _)) = &projection_move {
7694 for write in writes {
7695 let (mut values, mut cleared) = (Vec::new(), Vec::new());
7696 write.join(&mut values, &mut cleared);
7697 board_writes.extend(values.into_iter().map(|value| (board, value)));
7698 clears.extend(cleared.into_iter().map(|field| (board, field)));
7699 }
7700 }
7701 let mut boards: Vec<&BoardId> = board_writes.iter().map(|(board, _)| *board).collect();
7702 boards.extend(clears.iter().map(|(board, _)| *board));
7703 boards.dedup_by(|one, other| one.as_str() == other.as_str());
7704 for board in boards {
7705 let writes = board_writes
7706 .iter()
7707 .filter(|(on, _)| on.as_str() == board.as_str())
7708 .map(|(_, write)| write.clone())
7709 .collect::<Vec<_>>();
7710 let cleared = clears
7711 .iter()
7712 .filter(|(on, _)| on.as_str() == board.as_str())
7713 .map(|(_, field)| *field)
7714 .collect::<Vec<_>>();
7715 self.set_item_fields(board.as_str(), &item.item_id, &writes, &cleared)
7716 .await?;
7717 }
7718 let mut blocked_by_moved = false;
7719 if let Some((native, _)) = &edges
7720 && item.content_kind == ContentKind::Issue
7721 {
7722 blocked_by_moved = self
7723 .reconcile_blocked_by(
7724 &item.id,
7725 native,
7726 Issue::Existing(item.blocked_by.as_deref()),
7727 )
7728 .await?;
7729 }
7730 if !fields.is_empty() {
7731 self.update_content(item.content_kind, &item.id, Value::Object(fields))
7732 .await?;
7733 }
7734
7735 // The `blockedBy` this item was read with is what the write just changed, so it is no
7736 // answer any more: a later write in this command would reconcile against it — re-adding
7737 // what it kept and never removing what it dropped — and a forward-edge read would
7738 // answer with it. Left unknown, each asks GitHub instead.
7739 if blocked_by_moved {
7740 item.blocked_by = None;
7741 }
7742 if let Some(title) = &update.title {
7743 item.title.clone_from(title);
7744 }
7745 item.body = visible.filter(|value| !value.is_empty());
7746 item.raw_body = (!body.is_empty() || item.raw_body.is_some()).then_some(body);
7747 item.slot = slot;
7748 if let Some(delivers) = &update.delivers {
7749 item.delivers.clone_from(delivers);
7750 }
7751 if let Some(moving) = status_move {
7752 item.closed = matches!(moving.target, StatusTarget::Terminal(_, _))
7753 && item.content_kind == ContentKind::Issue;
7754 item.status = moving.landed;
7755 item.option = Some(moving.name);
7756 }
7757 if let Some((_, _, priority)) = priority_move {
7758 item.priority = HeldPriority::Read(priority);
7759 }
7760 if let Some((_, _, projected)) = projection_move {
7761 item.projected = projected;
7762 }
7763 let task = item.task()?;
7764 let mut written = update.changed(&before, &task);
7765 if blocked_by_moved || recorded_moves {
7766 written.insert(UpdatedField::DependsOn);
7767 }
7768 self.remember_written(item, false)?;
7769 Ok(Some(TaskUpdateOutcome {
7770 task,
7771 written,
7772 delivers_before: before.delivers,
7773 }))
7774 }
7775
7776 /// Replace one issue's visible body and its [`MetadataKey::TEMPLATE_KEY`] slot entry
7777 /// together, and nothing else; see [`TaskSource::set_task_rendering`].
7778 ///
7779 /// One update of the body: the content outside the slot, and inside it that one entry,
7780 /// every other entry kept as it was. This source keeps no template answers — an issue has
7781 /// no room beside itself that is not its body, and answers written there would duplicate
7782 /// what the content already says and count against GitHub's body limit — so `answers`
7783 /// reaches nothing here. A body that would not change is not sent at all.
7784 async fn replace_rendering(
7785 &self,
7786 id: &NativeId,
7787 kind: BoardKind,
7788 content: &str,
7789 provenance: &Value,
7790 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
7791 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
7792 let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
7793 return Ok(None);
7794 };
7795 let held = item.raw_body.clone().unwrap_or_default();
7796 let mut slot = item.slot.clone();
7797 slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
7798 let rewritten;
7799 let content = if let Some(assets) = assets {
7800 let uploads = self
7801 .upload_assets(item.own_repository.as_ref(), assets)
7802 .await?;
7803 rewritten =
7804 onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads);
7805 rewritten.as_str()
7806 } else {
7807 content
7808 };
7809 let body = with_slot(&with_content(&held, content)?, &slot)?;
7810 // Checked before anything is sent, as a content write checks it.
7811 let (visible, read) = metadata_body(Some(body.clone()))?;
7812 if visible.as_deref().unwrap_or_default() != content || read != slot {
7813 return Err(SourceError::Refused {
7814 message: format!(
7815 "this content ends in what source {} reads as its own metadata slot \
7816 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
7817 as content; next: remove that trailing block from the template",
7818 self.name
7819 ),
7820 });
7821 }
7822 if body != held {
7823 self.update_content(item.content_kind, &item.id, json!({"body": body}))
7824 .await?;
7825 }
7826 item.body = visible.filter(|value| !value.is_empty());
7827 item.raw_body = Some(body);
7828 item.slot = read;
7829 self.remember_written(item, false)?;
7830 Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
7831 id: id.clone(),
7832 content: Some(content.to_owned()),
7833 }))
7834 }
7835
7836 async fn set_item_field(
7837 &self,
7838 board_id: &str,
7839 item_id: &str,
7840 field_id: &str,
7841 value: Value,
7842 ) -> Result<(), SourceError> {
7843 let data = self
7844 .graphql(
7845 graphql::UPDATE_FIELD,
7846 json!({"input":{
7847 "projectId":board_id,"itemId":item_id,"fieldId":field_id,"value":value
7848 },"readPriority":false,"priorityName":PRIORITY_FIELD}),
7849 )
7850 .await?;
7851 let returned = data
7852 .pointer("/updateProjectV2ItemFieldValue/projectV2Item")
7853 .ok_or_else(|| SourceError::Malformed {
7854 message: "GitHub field update returned no project item".into(),
7855 })?;
7856 if required_str(returned, "id")? != item_id {
7857 return Err(SourceError::Malformed {
7858 message: "GitHub field update returned the wrong project item".into(),
7859 });
7860 }
7861 Ok(())
7862 }
7863
7864 /// GitHub accepts one value per field mutation; aliases combine those mutations in
7865 /// one request — writes in the order given, then clears. A lone write is
7866 /// [`graphql::UPDATE_FIELD`] and a lone clear [`graphql::CLEAR_FIELD`]; more than one
7867 /// request's slots hold go in further requests of the same document, in order. Every
7868 /// returned item id is checked, including optional aliases.
7869 async fn set_item_fields(
7870 &self,
7871 board: &str,
7872 item: &str,
7873 fields: &[(String, Value)],
7874 clears: &[&str],
7875 ) -> Result<(), SourceError> {
7876 match (fields, clears) {
7877 ([], []) => return Ok(()),
7878 ([(field, value)], []) => {
7879 return self.set_item_field(board, item, field, value.clone()).await;
7880 }
7881 ([], [field]) => {
7882 return self
7883 .write_priority(
7884 board,
7885 item,
7886 &PriorityWrite::Clear {
7887 field: (*field).to_owned(),
7888 },
7889 )
7890 .await;
7891 }
7892 _ => {}
7893 }
7894 // Any field of the request stands in for an input a slot leaves out, which GitHub
7895 // still requires to be well formed although it never runs it.
7896 let filler = fields
7897 .first()
7898 .map_or_else(|| clears[0], |(field, _)| field.as_str());
7899 let mut writes = fields.iter();
7900 let mut cleared = clears.iter();
7901 loop {
7902 let batch: Vec<&(String, Value)> =
7903 writes.by_ref().take(FIELD_WRITE_SLOTS.len()).collect();
7904 let batch_clears: Vec<&&str> = cleared.by_ref().take(FIELD_CLEAR_SLOTS.len()).collect();
7905 if batch.is_empty() && batch_clears.is_empty() {
7906 return Ok(());
7907 }
7908 let mut variables = serde_json::Map::new();
7909 for (index, slot) in FIELD_WRITE_SLOTS.iter().enumerate() {
7910 let input = match batch.get(index) {
7911 Some((field, value)) => {
7912 json!({"projectId":board,"itemId":item,"fieldId":field,"value":value})
7913 }
7914 None => json!({"projectId":board,"itemId":item,"fieldId":filler,
7915 "value":{"text":""}}),
7916 };
7917 variables.insert(slot.variable.to_owned(), input);
7918 variables.insert(slot.include.to_owned(), json!(index < batch.len()));
7919 }
7920 for (index, slot) in FIELD_CLEAR_SLOTS.iter().enumerate() {
7921 let field = batch_clears.get(index).map_or(filler, |field| **field);
7922 variables.insert(
7923 slot.variable.to_owned(),
7924 json!({"projectId":board,"itemId":item,"fieldId":field}),
7925 );
7926 variables.insert(slot.include.to_owned(), json!(index < batch_clears.len()));
7927 }
7928 let data = self
7929 .graphql(graphql::UPDATE_FIELDS, Value::Object(variables))
7930 .await?;
7931 let sent = FIELD_WRITE_SLOTS[..batch.len()]
7932 .iter()
7933 .chain(&FIELD_CLEAR_SLOTS[..batch_clears.len()]);
7934 for slot in sent {
7935 let alias = slot.alias;
7936 let returned = data
7937 .get(alias)
7938 .and_then(|value| value.get("projectV2Item"))
7939 .ok_or_else(|| SourceError::Malformed {
7940 message: format!("GitHub field update {alias} returned no project item"),
7941 })?;
7942 if required_str(returned, "id")? != item {
7943 return Err(SourceError::Malformed {
7944 message: format!(
7945 "GitHub field update {alias} returned the wrong project item"
7946 ),
7947 });
7948 }
7949 }
7950 }
7951 }
7952
7953 async fn native_dependency_ids(&self, id: &NativeId) -> Result<Vec<String>, SourceError> {
7954 let mut after: Option<String> = None;
7955 let mut ids = Vec::new();
7956 loop {
7957 let data = self
7958 .graphql(
7959 graphql::ISSUE_DEPENDENCIES,
7960 json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after}),
7961 )
7962 .await?;
7963 let connection =
7964 data.pointer("/node/blockedBy")
7965 .ok_or_else(|| SourceError::Malformed {
7966 message: "GitHub dependency response has no blockedBy connection".into(),
7967 })?;
7968 ids.extend(
7969 connection
7970 .get("nodes")
7971 .and_then(Value::as_array)
7972 .ok_or_else(|| SourceError::Malformed {
7973 message: "GitHub dependency response nodes is not an array".into(),
7974 })?
7975 .iter()
7976 .map(|value| required_str(value, "id").map(str::to_owned))
7977 .collect::<Result<Vec<_>, _>>()?,
7978 );
7979 let next = next_cursor(connection)?;
7980 if let Some(next) = &next {
7981 validate_cursor_progress(after.as_deref(), &next.0)?;
7982 }
7983 after = next.map(|cursor| cursor.0);
7984 if after.is_none() {
7985 return Ok(ids);
7986 }
7987 }
7988 }
7989
7990 async fn dependencies(
7991 &self,
7992 id: &NativeId,
7993 near_kind: ItemKind,
7994 direction: Direction,
7995 page: &PageRequest,
7996 ) -> Result<Page<DependencyEdge>, SourceError> {
7997 validate_page(page)?;
7998 let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
7999 let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
8000 let recorded = recorded_offset(cursor, direction)?;
8001 // What this issue is blocked by, when a read of it by its own id in this command
8002 // already carried the whole connection — a copy reads the item it writes before it
8003 // reads its edges — and the page asked for is the whole of it, or the recorded tail
8004 // after it. Answered from that read, in the shape the dependency read answers in;
8005 // anything else is asked of GitHub.
8006 let carried = match direction {
8007 Direction::DependsOn => self
8008 .resolved_cache()?
8009 .get(id)
8010 .filter(|item| item.content_kind == ContentKind::Issue)
8011 .and_then(|item| Some((item.blocked_by.clone()?, item.raw_body.clone()))),
8012 Direction::DependedOnBy => None,
8013 }
8014 .filter(|(nodes, _)| recorded.is_some() || (cursor.is_none() && nodes.len() <= limit));
8015 // Asked for even in the recorded phase, whose page reads nothing from the
8016 // connection: `__typename` is what says whether this item has a native
8017 // relationship at all, and that is what decides which far ends the reserved key is
8018 // allowed to hold.
8019 let data = match carried {
8020 Some((nodes, body)) => json!({"node":{"__typename":"Issue","body":body,
8021 "blockedBy":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}}),
8022 None => {
8023 self.graphql(
8024 graphql::ISSUE_DEPENDENCIES,
8025 json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),
8026 "after":if recorded.is_some() {None} else {cursor}}),
8027 )
8028 .await?
8029 }
8030 };
8031 let node =
8032 data.get("node")
8033 .filter(|v| !v.is_null())
8034 .ok_or_else(|| SourceError::Refused {
8035 message: format!(
8036 "GitHub item {} was not found or does not support dependencies",
8037 id.0
8038 ),
8039 })?;
8040 let connection_name = match direction {
8041 Direction::DependsOn => "blockedBy",
8042 Direction::DependedOnBy => "blocking",
8043 };
8044 // A draft has neither `blockedBy` nor `blocking`, so nothing it depends on can be
8045 // named natively and the reserved key may hold any far end. An issue's connections
8046 // hold issues, and this source reads them at the near item's own level.
8047 let natively_names = (required_str(node, "__typename")? == "Issue").then_some(near_kind);
8048 if let Some(offset) = recorded {
8049 return Ok(recorded_page(
8050 self.recorded_edges(id, near_kind, direction, natively_names, node)
8051 .await?,
8052 offset,
8053 limit,
8054 ));
8055 }
8056 if natively_names.is_none() {
8057 return Ok(recorded_page(
8058 self.recorded_edges(id, near_kind, direction, natively_names, node)
8059 .await?,
8060 0,
8061 limit,
8062 ));
8063 }
8064 let connection = node
8065 .get(connection_name)
8066 .ok_or_else(|| SourceError::Malformed {
8067 message: "GitHub dependency response is missing its connection".into(),
8068 })?;
8069 let nodes = connection
8070 .get("nodes")
8071 .and_then(Value::as_array)
8072 .ok_or_else(|| SourceError::Malformed {
8073 message: "GitHub dependency response nodes is not an array".into(),
8074 })?;
8075 // `from` depends on `to`, always. GitHub spells the same relationship from either
8076 // end — `blockedBy` lists what this item waits on, `blocking` lists what waits on
8077 // it — so the near item is `from` in one direction and `to` in the other.
8078 let items = nodes
8079 .iter()
8080 .map(|value| {
8081 let related = NativeId(required_str(value, "id")?.into());
8082 let related_kind = related_kind(value)?;
8083 let (from, to) = match direction {
8084 Direction::DependsOn => (
8085 DependencyEndpoint::from_native(id.clone(), near_kind),
8086 DependencyEndpoint::from_native(related, related_kind),
8087 ),
8088 Direction::DependedOnBy => (
8089 DependencyEndpoint::from_native(related, related_kind),
8090 DependencyEndpoint::from_native(id.clone(), near_kind),
8091 ),
8092 };
8093 Ok(DependencyEdge {
8094 from,
8095 to,
8096 kind: DependencyKind::Blocks,
8097 })
8098 })
8099 .collect::<Result<Vec<_>, SourceError>>()?;
8100 let mut next = next_cursor(connection)?;
8101 if let Some(next) = &next {
8102 validate_cursor_progress(cursor, &next.0)?;
8103 }
8104 if next.is_none()
8105 && !self
8106 .recorded_edges(id, near_kind, direction, natively_names, node)
8107 .await?
8108 .is_empty()
8109 {
8110 next = Some(Cursor(format!("{RECORDED_CURSOR}0")));
8111 }
8112 Ok(Page { items, next })
8113 }
8114
8115 /// The edges this item records under [`DependencyEdge::RECORDED_KEY`], which is where
8116 /// a far end in another source has to live: no GitHub issue relationship can name one.
8117 ///
8118 /// Only forwards. The reverse of a recorded edge is derived from the far end, and this
8119 /// source never writes one down.
8120 ///
8121 /// The metadata lives in the item's own body slot, and `node` is the dependency read's
8122 /// own answer, which carries an issue's body — so an issue's recorded edges cost no
8123 /// request beyond the read already made, and reading the board for them would be a
8124 /// walk of every item for one field of one. A draft has no body in that answer, because
8125 /// a draft is not an issue, so a draft's are read off its own read by id — never off a
8126 /// listing of the board, which can be behind on the very item asked about.
8127 async fn recorded_edges(
8128 &self,
8129 id: &NativeId,
8130 near_kind: ItemKind,
8131 direction: Direction,
8132 natively_names: Option<ItemKind>,
8133 node: &Value,
8134 ) -> Result<Vec<DependencyEdge>, SourceError> {
8135 if direction != Direction::DependsOn {
8136 return Ok(Vec::new());
8137 }
8138 let slot = match node.get("body") {
8139 Some(body) if natively_names.is_some() => {
8140 metadata_body(body.as_str().map(str::to_owned))?.1
8141 }
8142 _ => {
8143 let Some(item) = self.bound_item(id).await? else {
8144 return Ok(Vec::new());
8145 };
8146 item.slot
8147 }
8148 };
8149 DependencyEdge::recorded(&slot, id, near_kind, &self.name, natively_names)
8150 .map_err(|message| SourceError::Malformed { message })
8151 }
8152
8153 fn configured_repository(&self) -> Result<&RepositoryTarget, SourceError> {
8154 self.repository
8155 .as_ref()
8156 .ok_or_else(|| SourceError::Refused {
8157 message: format!(
8158 "source {} has no repository configured, and a GitHub Projects board has no \
8159 repository of its own to create an issue in; set repository: owner/name on \
8160 this source",
8161 self.name
8162 ),
8163 })
8164 }
8165
8166 /// The repository one new issue is created in, under the rule [`RepositoryTarget`]
8167 /// states.
8168 ///
8169 /// The fallback is demanded first, whichever arm answers: a write without a configured
8170 /// repository is refused naming the field exactly as it was before the rule existed,
8171 /// so a source that could not write before cannot write now, rather than writing for
8172 /// the one item whose own field happens to decide it.
8173 ///
8174 /// Everything this refuses is refused before `createIssue`, so a refusal leaves no
8175 /// issue behind: an entry that is not a repository on [`RepositoryTarget::HOST`], an
8176 /// entry owned by someone other than the owner of the parent issue's repository —
8177 /// GitHub accepts a sub-issue from another repository of the same owner and from no
8178 /// other, so `addSubIssue` would refuse it after the issue existed — a parent the
8179 /// board does not hold, and a parent that is a draft, which GitHub gives no sub-issues,
8180 /// both of which `addSubIssue` would likewise refuse too late. Whether the entry exists
8181 /// and is visible to the token is checked where its node id is resolved, still before
8182 /// `createIssue`. The parent is read by its own id through [`Self::item_by_id`] — never
8183 /// looked up in a listing of the board, which can be minutes behind an issue its own
8184 /// `projectItems` already places on it — and that read answers first from this process's
8185 /// own record, so a project created moments ago in this command answers though GitHub
8186 /// has not caught up.
8187 async fn creation_target(
8188 &self,
8189 incoming: &Incoming<'_>,
8190 ) -> Result<RepositoryTarget, SourceError> {
8191 let fallback = self.configured_repository()?;
8192 let what = |incoming: &Incoming<'_>| {
8193 format!(
8194 "{} {:?}",
8195 incoming.written.kind().describes(),
8196 incoming.title
8197 )
8198 };
8199 let parent = match incoming.parent {
8200 Some(parent) => Some(self.bound_item(parent).await?.ok_or_else(|| {
8201 SourceError::Refused {
8202 message: format!(
8203 "GitHub project issue {} was not found on the board of source {}, so {} \
8204 cannot be filed under it",
8205 parent.0,
8206 self.name,
8207 what(incoming)
8208 ),
8209 }
8210 })?),
8211 None => None,
8212 };
8213 let parents_repository = parent
8214 .as_ref()
8215 .map(|parent| {
8216 // A draft is on the board and so is found, but it has no repository to
8217 // place a task in and GitHub gives it no sub-issues, so `addSubIssue`
8218 // would refuse the task only once `createIssue` had made it.
8219 if parent.content_kind == ContentKind::DraftIssue {
8220 return Err(SourceError::Refused {
8221 message: format!(
8222 "GitHub project item {} on the board of source {} is a draft, \
8223 which cannot have sub-issues, so {} cannot be filed under it",
8224 parent.id.0,
8225 self.name,
8226 what(incoming)
8227 ),
8228 });
8229 }
8230 // An issue's repository is where a sub-issue is placed and whose owner it
8231 // is compared against, so a parent whose repository this source cannot
8232 // spell as `owner/name` — GitHub's login grammar is wider than this
8233 // source's floor — is one nothing can be filed under.
8234 parent
8235 .own_repository
8236 .as_ref()
8237 .and_then(|origin| RepositoryTarget::from_origin(origin).ok())
8238 .ok_or_else(|| SourceError::Malformed {
8239 message: format!(
8240 "GitHub project issue {} on the board of source {} is in {}, which \
8241 is not a {}/owner/name repository this source can place {} in",
8242 parent.id.0,
8243 self.name,
8244 parent
8245 .own_repository
8246 .as_ref()
8247 .map_or("no repository", Repository::as_str),
8248 RepositoryTarget::HOST,
8249 what(incoming)
8250 ),
8251 })
8252 })
8253 .transpose()?;
8254 match incoming.repositories {
8255 [named] => {
8256 let target =
8257 RepositoryTarget::from_origin(named).map_err(|_| SourceError::Refused {
8258 message: format!(
8259 "{} names repository {}, which is not a {}/owner/name repository \
8260 source {} can create an issue in; name one that is, or name none",
8261 what(incoming),
8262 named.as_str(),
8263 RepositoryTarget::HOST,
8264 self.name
8265 ),
8266 })?;
8267 if let Some(parents) = &parents_repository
8268 && parents.owner != target.owner
8269 {
8270 return Err(SourceError::Refused {
8271 message: format!(
8272 "{} names repository {}, owned by {}, but its project's issue is in \
8273 {}, owned by {}, and GitHub files a sub-issue only in a repository \
8274 of the same owner as its parent issue; name a repository of {}, or \
8275 name none",
8276 what(incoming),
8277 target.slug(),
8278 target.owner,
8279 parents.slug(),
8280 parents.owner,
8281 parents.owner
8282 ),
8283 });
8284 }
8285 Ok(target)
8286 }
8287 _ => Ok(parents_repository.unwrap_or_else(|| fallback.clone())),
8288 }
8289 }
8290
8291 /// The node id of the repository `incoming` is being created in, or the refusal naming
8292 /// the item and the repository the token cannot see.
8293 ///
8294 /// Resolved once per command per repository; see [`Self::repository_cache`].
8295 async fn repository_id(
8296 &self,
8297 repository: &RepositoryTarget,
8298 incoming: &Incoming<'_>,
8299 ) -> Result<String, SourceError> {
8300 if let Some(id) = self.repository_cache()?.get(repository).cloned() {
8301 return Ok(id);
8302 }
8303 let data = self
8304 .graphql(
8305 graphql::REPOSITORY,
8306 json!({"owner":repository.owner,"name":repository.name}),
8307 )
8308 .await?;
8309 self.repository_read(&data, repository, incoming)
8310 }
8311
8312 /// The repository's node id out of an answer carrying the `repository` root, held for
8313 /// the rest of this command, or the refusal naming the item that cannot be created in it.
8314 fn repository_read(
8315 &self,
8316 data: &Value,
8317 repository: &RepositoryTarget,
8318 incoming: &Incoming<'_>,
8319 ) -> Result<String, SourceError> {
8320 let node = data
8321 .get("repository")
8322 .filter(|value| !value.is_null())
8323 .ok_or_else(|| SourceError::Refused {
8324 message: format!(
8325 "GitHub repository {} was not found or is not visible to the token, so {} \
8326 {:?} cannot be created in it",
8327 repository.slug(),
8328 incoming.written.kind().describes(),
8329 incoming.title
8330 ),
8331 })?;
8332 let id = required_str(node, "id")?.to_owned();
8333 self.repository_cache()?
8334 .insert(repository.clone(), id.clone());
8335 Ok(id)
8336 }
8337
8338 fn repository_cache(
8339 &self,
8340 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<RepositoryTarget, String>>, SourceError> {
8341 self.repository_cache
8342 .lock()
8343 .map_err(|_| SourceError::Unavailable {
8344 message: "this source's record of the destination repository was left \
8345 inconsistent by an earlier failure; next: run the command again"
8346 .into(),
8347 })
8348 }
8349
8350 /// Create or update one board item, whichever kind it is.
8351 async fn write_item(
8352 &self,
8353 incoming: &Incoming<'_>,
8354 target: Option<&NativeId>,
8355 depends_on: &[DependencyEdge],
8356 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
8357 // Refused before anything is read or written: a task or a project titled the way
8358 // this board spells a document would land as an issue this same source reads back
8359 // as a document, so the field this destination cannot carry is named rather than
8360 // written and silently reclassified.
8361 if let Written::Work(kind, _) = incoming.written
8362 && incoming.title.starts_with(DESIGN_TITLE_PREFIX)
8363 {
8364 return Err(SourceError::Refused {
8365 message: format!(
8366 "the title of this {} begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
8367 spells a document, so it would read back as one rather than as a {}; \
8368 retitle it, or copy it as a document",
8369 kind.marker(),
8370 self.name,
8371 kind.marker()
8372 ),
8373 });
8374 }
8375 // The destination is read by its own id, and whether this board holds it is decided
8376 // by that read — its own `projectItems` — rather than by whether a listing of the
8377 // board happens to include it yet. See the module documentation.
8378 let existing = match target {
8379 Some(target) => {
8380 Some(
8381 self.bound_item(target)
8382 .await?
8383 .ok_or_else(|| SourceError::Refused {
8384 message: format!("GitHub destination item {} was not found", target.0),
8385 })?,
8386 )
8387 }
8388 None => None,
8389 };
8390 let existing = existing.as_ref();
8391 // An existing issue is never moved; a new one is created where the rule says — and
8392 // knowing where is what lets the board's fields and that repository's id be read
8393 // together, before anything below needs either.
8394 let creation_target = match existing {
8395 Some(_) => None,
8396 None => {
8397 let target = self.creation_target(incoming).await?;
8398 self.creation_context(&target, incoming).await?;
8399 Some(target)
8400 }
8401 };
8402 let board = self
8403 .fields_for(
8404 existing,
8405 incoming.written.status().is_some(),
8406 incoming
8407 .priority
8408 .is_some_and(|priority| priority != Priority::None),
8409 )
8410 .await?;
8411 let status_target = incoming
8412 .written
8413 .work_status()
8414 .map(|(kind, status)| self.resolved_target(kind, status.category))
8415 .transpose()?;
8416 let column = match (incoming.written.work_status(), status_target.as_ref()) {
8417 (Some((kind, status)), Some(target)) => {
8418 self.column_for(&board.fields, kind, status.category, target)?
8419 }
8420 _ => None,
8421 };
8422 // Resolved before anything is created, for the reason the column above is: a
8423 // priority this board has no option for is refused while nothing has been written.
8424 let priority_write = match incoming.priority {
8425 Some(priority) => self.priority_write(&board.fields, existing, priority)?,
8426 None => None,
8427 };
8428 // And for the reason the priority is: a value no projected field can hold, or a board
8429 // that cannot hold the field, is refused while nothing has been written.
8430 let (projections, projected) = self.projection_writes(
8431 &board.fields,
8432 existing.map(|item| &item.projected),
8433 incoming.metadata,
8434 None,
8435 )?;
8436 let content_kind = existing.map_or(ContentKind::Issue, |item| item.content_kind);
8437 if content_kind == ContentKind::DraftIssue {
8438 if let (Some(StatusTarget::Terminal(_, _)), Some(status)) =
8439 (status_target.as_ref(), incoming.written.status())
8440 {
8441 return Err(self.closes_a_draft(status.category));
8442 }
8443 if incoming.parent.is_some() {
8444 return Err(SourceError::Refused {
8445 message: "GitHub draft items cannot be a project's sub-issue".into(),
8446 });
8447 }
8448 }
8449 match existing {
8450 Some(item) if content_kind == ContentKind::Issue => {
8451 if item.labels != incoming.labels {
8452 return Err(SourceError::Refused {
8453 message: "GitHub issue labels differ from the labels being written".into(),
8454 });
8455 }
8456 }
8457 _ => {
8458 if !incoming.labels.is_empty() {
8459 return Err(SourceError::Refused {
8460 message: "GitHub items created by this destination carry no labels".into(),
8461 });
8462 }
8463 }
8464 }
8465
8466 // The repository the issue really lives in is what the slot below is written against,
8467 // so a single entry that is where the issue is created travels as no key at all, and
8468 // the read side derives it back from the issue.
8469 let own_repository = match (existing, &creation_target) {
8470 (Some(item), _) => item.own_repository.clone(),
8471 (None, Some(target)) => Some(
8472 Repository::try_from(target.origin())
8473 .map_err(|message| SourceError::Config { message })?,
8474 ),
8475 (None, None) => None,
8476 };
8477 let (native, fallback) = self
8478 .partition_edges(
8479 incoming.written.kind(),
8480 content_kind,
8481 existing.and_then(|item| item.blocked_by.as_deref()),
8482 depends_on,
8483 )
8484 .await?;
8485 let mut slot = slot_metadata(incoming, own_repository.as_ref(), &fallback);
8486 let content = match incoming.assets {
8487 Some(assets) => {
8488 let uploads = self.upload_assets(own_repository.as_ref(), assets).await?;
8489 let rewritten = onetaskgraph_plugin_api::serve_asset_references(
8490 incoming.content.unwrap_or_default(),
8491 &mut slot,
8492 &uploads,
8493 );
8494 incoming.content.map(|_| rewritten)
8495 }
8496 None => incoming.content.map(str::to_owned),
8497 };
8498 let body = compose_body(content.as_deref(), &slot)?;
8499 // Read before anything is created, for the reason the field below is: a value
8500 // this destination cannot store has to refuse, and refusing after `createIssue`
8501 // would leave an issue behind that nothing asked for. The engine writes a
8502 // qualified id here; a caller handing this key anything else is told so rather
8503 // than having it silently stored as no origin at all.
8504 // llmlint: ignore[boundary_inputs_validated, changed_behavior_has_e2e] The qualified id's syntax is the engine's and not this plugin's to police: `GlobalId` is deliberately absent from the contract crate because a plugin never sees a qualified id (AGENTS.md), no plugin crate may depend on the engine to parse one, and `docs/metadata.md` says the contents of this key are what no plugin constructs or interprets. What this boundary owns is whether the value is a string its text field can hold, and that is what it checks.
8505 let origin = match incoming.metadata.get(ORIGIN_KEY) {
8506 None => "",
8507 Some(Value::String(origin)) => origin.as_str(),
8508 Some(other) => {
8509 return Err(SourceError::Refused {
8510 message: format!(
8511 "{ORIGIN_KEY} holds a qualified id spelled as a string, and this item's \
8512 is {other}"
8513 ),
8514 });
8515 }
8516 };
8517 // Resolved before anything is created: a board that cannot carry the copy origin
8518 // has to refuse the write, and refusing it after `createIssue` would leave an
8519 // issue behind that nothing asked for.
8520 let origin_field = match Board::field(&board.fields, ORIGIN_FIELD)? {
8521 Some(field) => {
8522 if required_str(field, "__typename")? != "ProjectV2Field" {
8523 return Err(SourceError::Refused {
8524 message: format!(
8525 "GitHub board source-owned {ORIGIN_FIELD} field is not a text field"
8526 ),
8527 });
8528 }
8529 Some(required_str(field, "id")?.to_owned())
8530 }
8531 None if incoming.metadata.contains_key(ORIGIN_KEY) => {
8532 return Err(SourceError::Refused {
8533 message: format!(
8534 "GitHub board has no source-owned {ORIGIN_FIELD} text field, and the \
8535 item carries {ORIGIN_KEY}; add a text field named {ORIGIN_FIELD} to \
8536 the board"
8537 ),
8538 });
8539 }
8540 None => None,
8541 };
8542
8543 let Landed {
8544 content_id,
8545 item_id,
8546 url,
8547 number,
8548 } = match existing {
8549 // Its content is written last, below, once everything else has landed.
8550 Some(item) => Landed {
8551 content_id: item.id.clone(),
8552 item_id: item.item_id.clone(),
8553 url: item.url.clone(),
8554 number: item.number,
8555 },
8556 None => {
8557 let target = creation_target
8558 .as_ref()
8559 .ok_or_else(|| SourceError::Malformed {
8560 message: "a new item was decided without a repository to create it in"
8561 .into(),
8562 })?;
8563 self.create_and_file_issue(board.id.as_str(), target, incoming, &body)
8564 .await?
8565 }
8566 };
8567
8568 // A write the store's cache expects sends only what differs from the version it expects:
8569 // a priority the item already holds there is not sent, so a person's edit of it since is
8570 // left alone. Every other write sends it, as its pinned cost says.
8571 let priority_write = priority_write.filter(|_| {
8572 !existing.is_some_and(|item| {
8573 self.expected.is_primed(&item.id)
8574 && incoming.priority.map(HeldPriority::Read) == Some(item.priority.clone())
8575 })
8576 });
8577 let written_option = column.as_ref().map(|(_, _, name)| name.clone());
8578 let column = column
8579 .filter(|(_, _, name)| existing.is_none_or(|item| item.option.as_ref() != Some(name)))
8580 .map(|(field, option, _)| (field, option));
8581 // Creating an item here is several calls — `createIssue`, which files it on the
8582 // board, then its board fields, the parent and the dependencies — and GitHub can fail
8583 // at any of them. Everything this source can refuse *before* the first of those is
8584 // already checked above, so what is left is GitHub itself failing part way. When it
8585 // does over an item this call created, the issue is taken back: a write that
8586 // refused must not leave an item behind that nobody asked for, and one that does
8587 // makes the retry create a second.
8588 // Whether the board-field write carrying a moved origin was answered as landing whole.
8589 // When it was refused, GitHub does not say which of its fields ran before the one that
8590 // failed, so the origin may or may not have moved.
8591 let mut origin_landed = false;
8592 let landed = self
8593 .finish_write(
8594 board.id.as_str(),
8595 incoming,
8596 &content_id,
8597 &item_id,
8598 content_kind,
8599 existing,
8600 origin_field.as_deref(),
8601 origin,
8602 column,
8603 status_target.as_ref(),
8604 priority_write.as_ref(),
8605 &projections,
8606 &native,
8607 &mut origin_landed,
8608 )
8609 .await;
8610 // An existing item's title, body and state go last, in one `updateIssue`, once its board
8611 // fields and its relationships have landed: a refusal of any of those then leaves its
8612 // body — and the metadata slot inside it — exactly as it stood.
8613 let landed = match (landed, existing) {
8614 (Ok(()), Some(item)) => {
8615 self.update_existing(item, incoming, &body, status_target.as_ref())
8616 .await
8617 }
8618 (landed, _) => landed,
8619 };
8620 if let Err(error) = landed {
8621 match existing {
8622 // Best effort, and the write's own failure is what the caller is told: a
8623 // refusal naming the tidy-up would hide why the write failed at all.
8624 None => {
8625 let _ = self.delete_issue(&content_id).await;
8626 }
8627 // The origin field is the one piece of an existing item's metadata written
8628 // before its body, so a write refused after it puts it back as it was. When
8629 // that is refused too, the write's own failure is still what the caller is
8630 // told — with what it left behind added, because the item's metadata is then
8631 // not as it stood and a caller retrying has to know which key moved.
8632 Some(item) => {
8633 let before = item.origin.as_deref().unwrap_or("");
8634 if let Some(field) = origin_field.as_deref()
8635 && before != origin
8636 && let Err(restore) = self
8637 .set_item_field(
8638 board.id.as_str(),
8639 &item.item_id,
8640 field,
8641 json!({"text": before}),
8642 )
8643 .await
8644 {
8645 let left = if origin_landed {
8646 format!(
8647 "its {ORIGIN_KEY} was moved to {origin:?} before that and could \
8648 not be put back to {before:?} ({restore}), so item {} still \
8649 holds {origin:?} there",
8650 item.id.0
8651 )
8652 } else {
8653 format!(
8654 "the refused write carried its {ORIGIN_KEY} from {before:?} to \
8655 {origin:?}, GitHub does not say whether that part of it ran, \
8656 and putting it back to {before:?} was refused ({restore}), so \
8657 item {} holds {origin:?} or {before:?} there",
8658 item.id.0
8659 )
8660 };
8661 return Err(noting(
8662 error,
8663 &format!(
8664 "; {left}; next: set {ORIGIN_KEY} on it back to {before:?}, or \
8665 run the write again"
8666 ),
8667 ));
8668 }
8669 }
8670 }
8671 return Err(error);
8672 }
8673
8674 let written_status = match (incoming.written.work_status(), status_target.as_ref()) {
8675 (Some((kind, _)), Some(StatusTarget::Terminal(_, reason))) => {
8676 self.statuses
8677 .status(kind, written_option.as_deref(), true, Some(reason.reason()))
8678 }
8679 (Some((kind, _)), Some(StatusTarget::Column(_))) => {
8680 self.statuses
8681 .status(kind, written_option.as_deref(), false, None)
8682 }
8683 (Some((_, status)), _) => status.clone(),
8684 (None, _) => Status {
8685 category: StatusCategory::Unknown,
8686 name: "Open".to_owned(),
8687 },
8688 };
8689
8690 // So the rest of this command reads what it just did rather than what the board
8691 // said before it. See `remember_written` for which half takes it.
8692 let remembered = Resolved {
8693 item_id,
8694 id: content_id.clone(),
8695 content_kind,
8696 kind: incoming.written.kind(),
8697 title: incoming.title.to_owned(),
8698 // The visible half of the body this write composed, split back off it the
8699 // way a read splits it — so what this record reports is what a read of the
8700 // same issue reports, rather than the person's text with the metadata slot
8701 // still on the end of it.
8702 body: metadata_body(body.clone())?.0,
8703 raw_body: body.clone(),
8704 // A document has no status of its own; what it reads back as is whatever
8705 // the issue's own state says, which is what a re-read reports.
8706 status: written_status,
8707 option: written_option.or_else(|| existing.and_then(|item| item.option.clone())),
8708 priority: match incoming.priority {
8709 Some(priority) => HeldPriority::Read(priority),
8710 None => existing.map_or(HeldPriority::Read(Priority::None), |item| {
8711 item.priority.clone()
8712 }),
8713 },
8714 // What `state_input` asked for: closed for a terminal target, open for any other
8715 // status, and the issue's own state left as it was by a document write.
8716 closed: content_kind == ContentKind::Issue
8717 && match status_target.as_ref() {
8718 Some(StatusTarget::Terminal(_, _)) => true,
8719 Some(_) => false,
8720 None => existing.is_some_and(|item| item.closed),
8721 },
8722 reason: match status_target.as_ref() {
8723 Some(StatusTarget::Terminal(_, reason)) if content_kind == ContentKind::Issue => {
8724 Some(reason.reason().to_owned())
8725 }
8726 Some(_) => None,
8727 None => existing.and_then(|item| item.reason.clone()),
8728 },
8729 delivers: incoming.delivers.to_vec(),
8730 delivered_by: incoming.delivered_by.to_vec(),
8731 labels: incoming.labels.to_vec(),
8732 parent: incoming.parent.cloned(),
8733 origin: (!origin.is_empty()).then(|| origin.to_owned()),
8734 projected,
8735 number,
8736 // In the update path this is the item's own url, read off `existing` where the
8737 // record above was bound, so one expression serves both halves.
8738 url,
8739 created_at: existing.and_then(|item| item.created_at),
8740 updated_at: existing.and_then(|item| item.updated_at),
8741 // What this write moved is GitHub's to say, so a record of it gives no token until
8742 // it is read again.
8743 item_updated_at: None,
8744 comment_count: None,
8745 relationship_events: None,
8746 served_at: None,
8747 facets: None,
8748 own_repository,
8749 repositories: incoming.repositories.to_vec(),
8750 classification: incoming.classification,
8751 slot,
8752 board_id: Some(board.id.as_str().to_owned()),
8753 fields: board
8754 .fields
8755 .get("nodes")
8756 .and_then(Value::as_array)
8757 .cloned()
8758 .unwrap_or_default(),
8759 board_fields: Some(board.fields.clone()),
8760 // What this write left the relationship holding is known by id alone, and a
8761 // later read of its edges needs each far end's kind, so it reads them again.
8762 blocked_by: None,
8763 };
8764 self.remember_written(remembered, existing.is_none())?;
8765 Ok(onetaskgraph_plugin_api::AssetsWritten {
8766 id: content_id,
8767 content,
8768 })
8769 }
8770
8771 /// Everything a write does after the item exists: its board fields, its parent, and
8772 /// its dependencies.
8773 ///
8774 /// Split out of `write_item` so there is one place a failure past the point of no
8775 /// return is caught, rather than a tidy-up repeated at each `?` above.
8776 // llmlint: ignore[suppressions_justified] This is the tail of `write_item` lifted out
8777 // so there is one place a failure past the point of no return is caught, and its
8778 // arguments are exactly the values that tail already had in scope. Bundling them into a
8779 // struct would describe no concept — it would be "the arguments of this function" — and
8780 // would put the whole of `write_item`'s locals behind one more indirection.
8781 #[allow(clippy::too_many_arguments)]
8782 async fn finish_write(
8783 &self,
8784 board_id: &str,
8785 incoming: &Incoming<'_>,
8786 content_id: &NativeId,
8787 item_id: &str,
8788 content_kind: ContentKind,
8789 existing: Option<&Resolved>,
8790 origin_field: Option<&str>,
8791 origin: &str,
8792 column: Option<(String, String)>,
8793 status_target: Option<&StatusTarget>,
8794 priority: Option<&PriorityWrite>,
8795 projections: &[ProjectionWrite],
8796 native: &[String],
8797 origin_landed: &mut bool,
8798 ) -> Result<(), SourceError> {
8799 let mut fields = Vec::new();
8800 if let Some(field_id) = origin_field
8801 && existing.map_or(!origin.is_empty(), |item| {
8802 item.origin.as_deref().unwrap_or("") != origin
8803 })
8804 {
8805 fields.push((field_id.to_owned(), json!({"text":origin})));
8806 }
8807 if let Some((field_id, option_id)) = column {
8808 fields.push((field_id, json!({"singleSelectOptionId":option_id})));
8809 }
8810 let mut clears = Vec::new();
8811 match priority {
8812 Some(PriorityWrite::Select { field, option }) => {
8813 fields.push((field.clone(), json!({"singleSelectOptionId":option})));
8814 }
8815 Some(PriorityWrite::Clear { field }) => clears.push(field.as_str()),
8816 None => {}
8817 }
8818 for projection in projections {
8819 projection.join(&mut fields, &mut clears);
8820 }
8821 self.set_item_fields(board_id, item_id, &fields, &clears)
8822 .await?;
8823 *origin_landed = true;
8824
8825 // An existing issue closes in the `updateIssue` its write ends with; one created just
8826 // now closes here, once its option is selected.
8827 if existing.is_none()
8828 && content_kind == ContentKind::Issue
8829 && matches!(status_target, Some(StatusTarget::Terminal(_, _)))
8830 {
8831 self.update_content(
8832 ContentKind::Issue,
8833 content_id,
8834 json!({"stateInput":state_input(status_target)}),
8835 )
8836 .await?;
8837 }
8838
8839 if content_kind == ContentKind::Issue {
8840 self.reparent(
8841 existing.and_then(|item| item.parent.clone()),
8842 content_id,
8843 incoming.parent,
8844 )
8845 .await?;
8846 // A document takes part in no dependency graph, so writing one neither reads
8847 // nor changes the issue's own `blockedBy` relationships. Reconciling them
8848 // against the empty list a document write carries would *delete* whatever
8849 // relationships a person had made on that issue, which is a write nobody
8850 // asked for.
8851 if incoming.written.kind() != BoardKind::Document {
8852 let issue = match existing {
8853 Some(item) => Issue::Existing(item.blocked_by.as_deref()),
8854 None => Issue::Created,
8855 };
8856 self.reconcile_blocked_by(content_id, native, issue).await?;
8857 }
8858 }
8859 Ok(())
8860 }
8861
8862 /// Delete one issue, which takes its board item with it.
8863 async fn delete_issue(&self, id: &NativeId) -> Result<(), SourceError> {
8864 let data = self
8865 .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
8866 .await?;
8867 data.pointer("/deleteIssue/repository")
8868 .filter(|value| !value.is_null())
8869 .ok_or_else(|| SourceError::Malformed {
8870 message: "GitHub issue deletion returned no repository".into(),
8871 })?;
8872 self.forget(id)?;
8873 Ok(())
8874 }
8875
8876 /// Remove one item this copy created, so a copy that could not finish leaves the board
8877 /// as it found it.
8878 ///
8879 /// Deleting the issue takes its board item with it, so there is no second mutation to
8880 /// keep in step. An id the board does not hold is not an error: the item is already
8881 /// gone, which is the state this asks for. Which that is, is decided by reading the item
8882 /// by its own id — a listing of the board can still be missing an item it holds, and
8883 /// reading that as *already gone* would leave behind the very item this was asked to
8884 /// take back.
8885 async fn delete_item(&self, id: &NativeId) -> Result<(), SourceError> {
8886 let Some(item) = self.bound_item(id).await? else {
8887 return Ok(());
8888 };
8889 if item.content_kind == ContentKind::DraftIssue {
8890 return Err(SourceError::Refused {
8891 message: format!(
8892 "GitHub item {} is a draft, and this source removes an item by deleting \
8893 its issue; next: remove it from the board by hand",
8894 id.0
8895 ),
8896 });
8897 }
8898 let data = self
8899 .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
8900 .await?;
8901 data.pointer("/deleteIssue/repository")
8902 .filter(|value| !value.is_null())
8903 .ok_or_else(|| SourceError::Malformed {
8904 message: "GitHub issue deletion returned no repository".into(),
8905 })?;
8906 self.forget(id)?;
8907 Ok(())
8908 }
8909
8910 /// The issue a comment call on `task` is about, or `None` when this board holds no such
8911 /// task.
8912 ///
8913 /// Resolved exactly as [`TaskSource::get_task`] resolves it, so the comment verbs and a
8914 /// read of the task cannot disagree about which ids name one: a project or a document of
8915 /// this board is not a task here either.
8916 ///
8917 /// A **draft** is a task with nowhere to keep a comment, because GitHub keeps comments on
8918 /// issues and a draft is not one. It is refused rather than answered with an empty page,
8919 /// which would read as a task nobody has commented on yet.
8920 async fn commented_issue(&self, task: &NativeId) -> Result<Option<NativeId>, SourceError> {
8921 let cached = self.resolved_cache()?.get(task).cloned();
8922 let Some(item) = (match cached {
8923 Some(item) => Some(item),
8924 None => self.item_by_id(task).await?,
8925 })
8926 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
8927 return Ok(None);
8928 };
8929 if item.content_kind == ContentKind::DraftIssue {
8930 return Err(self.draft_has_no_comments(task));
8931 }
8932 Ok(Some(item.id))
8933 }
8934
8935 /// The refusal a comment call on a board draft is answered with: GitHub keeps comments on
8936 /// issues, and a draft is not one.
8937 fn draft_has_no_comments(&self, task: &NativeId) -> SourceError {
8938 SourceError::Refused {
8939 message: format!(
8940 "task {} of source {} is a draft item on the board, and GitHub keeps \
8941 comments on issues alone, so a draft has none to read or write; next: \
8942 convert the draft to an issue on the board, then comment on the issue it \
8943 becomes",
8944 task.0, self.name
8945 ),
8946 }
8947 }
8948
8949 /// One task and a page of its comments, read with [`graphql::ISSUE_DETAIL`] in one
8950 /// request — or `None` when this board holds no task by that id.
8951 ///
8952 /// What `task show` and a comment listing read. A draft is a task with no comments, so it
8953 /// is answered with the draft and the refusal, at the price of the draft's own read.
8954 async fn issue_detail(
8955 &self,
8956 id: &NativeId,
8957 page: &PageRequest,
8958 ) -> Result<Option<TaskDetailRead>, SourceError> {
8959 let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
8960 let asked = self
8961 .graphql(
8962 graphql::ISSUE_DETAIL,
8963 json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),"after":after,
8964 "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
8965 "duplicates":true}),
8966 )
8967 .await;
8968 let data = match asked {
8969 Ok(data) => data,
8970 Err(error) if unresolvable_node(&error) => return Ok(None),
8971 Err(error) => return Err(error),
8972 };
8973 // `node` is null for an id that names nothing, and absent only from an answer this
8974 // source cannot read — never the same thing.
8975 let node = data.get("node").ok_or_else(|| SourceError::Malformed {
8976 message: format!("GitHub answered the read of {} with no node", id.0),
8977 })?;
8978 self.detail_of(id, node, true, after).await
8979 }
8980
8981 /// Several tasks, each with the first page of its comments when `comments` is set, read
8982 /// [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] — one answer per id, in
8983 /// order.
8984 ///
8985 /// A batch GitHub refuses because one of its ids resolves to no node at all is read again
8986 /// one item at a time, so that id is answered as missing and the others as themselves; any
8987 /// other refusal is every id of that batch's answer.
8988 async fn issue_details(
8989 &self,
8990 ids: &[NativeId],
8991 comments: Option<&PageRequest>,
8992 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
8993 let mut read = Vec::with_capacity(ids.len());
8994 for batch in ids.chunks(DETAIL_BATCH) {
8995 match self
8996 .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, comments))
8997 .await
8998 {
8999 Ok(data) => {
9000 for (slot, id) in batch.iter().enumerate() {
9001 // Every alias asked for is answered, null for an id naming nothing;
9002 // one missing is an answer this source cannot read.
9003 let read_one = match data.get(format!("i{slot}")) {
9004 Some(node) => self.detail_of(id, node, comments.is_some(), None).await,
9005 None => Err(SourceError::Malformed {
9006 message: format!(
9007 "GitHub answered a batch read with no item for {}",
9008 id.0
9009 ),
9010 }),
9011 };
9012 read.push(read_one);
9013 }
9014 }
9015 Err(error) if unresolvable_node(&error) => {
9016 for id in batch {
9017 read.push(match comments {
9018 Some(page) => self.issue_detail(id, page).await,
9019 None => self.task_read(id).await,
9020 });
9021 }
9022 }
9023 Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
9024 }
9025 }
9026 read
9027 }
9028
9029 /// One task and nothing of its comments, as [`TaskSource::get_task`] reads it.
9030 async fn task_read(&self, id: &NativeId) -> Result<Option<TaskDetailRead>, SourceError> {
9031 Ok(self.get_task(id).await?.map(|task| TaskDetailRead {
9032 task,
9033 comments: None,
9034 }))
9035 }
9036
9037 /// What one node a detail read reached says: the task this board holds by `id`, with the
9038 /// page of comments the node carries when `commented` — or `None` for a node that is no
9039 /// task of this board.
9040 ///
9041 /// Resolved as [`Self::item_by_id`] resolves an item: a draft is read again as a draft,
9042 /// and an item this process created answers from this process's own record, which a node
9043 /// read taken moments after the write can still be behind.
9044 async fn detail_of(
9045 &self,
9046 id: &NativeId,
9047 node: &Value,
9048 commented: bool,
9049 after: Option<&str>,
9050 ) -> Result<Option<TaskDetailRead>, SourceError> {
9051 if node.is_null() {
9052 return Ok(None);
9053 }
9054 let draft = optional_str(node, "__typename")? == Some("DraftIssue");
9055 // An issue answered under one id is that id's, or the answer is not one this source
9056 // can report: reporting another issue's task and comments under the qualified id asked
9057 // for would be the one wrong answer here. A draft's own read checks the same.
9058 if !draft
9059 && optional_str(node, "__typename")? == Some("Issue")
9060 && required_str(node, "id")? != id.0
9061 {
9062 return Err(SourceError::Malformed {
9063 message: format!(
9064 "GitHub answered the read of {} with issue {}",
9065 id.0,
9066 required_str(node, "id")?
9067 ),
9068 });
9069 }
9070 let item = if draft {
9071 self.draft_by_id(id).await?
9072 } else {
9073 self.resolve_issue(node).await?
9074 };
9075 // A read that carried the whole of what the issue is blocked by — a copy's — is kept
9076 // for this command, so the dependency read the copy makes next is answered from it.
9077 if let Some(read) = item.as_ref().filter(|item| item.blocked_by.is_some()) {
9078 self.resolved_cache()?.insert(read.id.clone(), read.clone());
9079 }
9080 let Some(item) = item.filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
9081 return Ok(None);
9082 };
9083 let own = self.created()?.iter().find(|own| own.id == *id).cloned();
9084 let task = own.unwrap_or(item).task()?;
9085 let comments = match (commented, draft) {
9086 (false, _) => None,
9087 (true, true) => Some(Err(self.draft_has_no_comments(id))),
9088 (true, false) => Some(comment_page(node, &id.0, after).map(Some)),
9089 };
9090 if commented && !draft && after.is_none() {
9091 self.expected.learn_comments(id, node);
9092 }
9093 Ok(Some(TaskDetailRead { task, comments }))
9094 }
9095
9096 /// Whether the comment `comment` is one of `issue`'s own.
9097 ///
9098 /// Read before an edit or a removal is sent, because GitHub's comment mutations take the
9099 /// comment's id and nothing else: a comment id given against the wrong task would
9100 /// otherwise change a comment on some other issue entirely. An id that names nothing, or
9101 /// names something that is not an issue comment, is a comment this task does not have —
9102 /// which is what GitHub refusing to resolve it means too.
9103 async fn comment_is_on(
9104 &self,
9105 issue: &NativeId,
9106 comment: &NativeId,
9107 ) -> Result<bool, SourceError> {
9108 Ok(self.comment_on(issue, comment).await?.is_some())
9109 }
9110
9111 /// The body the comment `comment` holds, exactly as GitHub holds it, when it is one of
9112 /// `issue`'s own — the read [`Self::comment_is_on`] makes, answering with what it selected.
9113 async fn comment_on(
9114 &self,
9115 issue: &NativeId,
9116 comment: &NativeId,
9117 ) -> Result<Option<String>, SourceError> {
9118 // A write the store's cache expects knows which comments its issue held, and their
9119 // bodies, at the version it expects: what this read would answer.
9120 if let Some(primed) = self.expected.primed_comment(issue, comment) {
9121 return Ok(primed);
9122 }
9123 let asked = self
9124 .graphql(graphql::COMMENT_ISSUE, json!({"id":comment.0}))
9125 .await;
9126 let data = match asked {
9127 Ok(data) => data,
9128 Err(error) if unresolvable_node(&error) => return Ok(None),
9129 Err(error) => return Err(error),
9130 };
9131 let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
9132 return Ok(None);
9133 };
9134 if optional_str(node, "__typename")? != Some("IssueComment") {
9135 return Ok(None);
9136 }
9137 let on = node.get("issue").ok_or_else(|| SourceError::Malformed {
9138 message: format!("GitHub issue comment {} names no issue", comment.0),
9139 })?;
9140 if required_str(on, "id")? != issue.0 {
9141 return Ok(None);
9142 }
9143 Ok(Some(required_str(node, "body")?.to_owned()))
9144 }
9145
9146 /// Which far ends this item's own `blockedBy` relationship holds, and which it cannot.
9147 async fn partition_edges(
9148 &self,
9149 near_kind: BoardKind,
9150 near_content: ContentKind,
9151 carried: Option<&[Value]>,
9152 depends_on: &[DependencyEdge],
9153 ) -> Result<(Vec<String>, Vec<DependencyEdge>), SourceError> {
9154 let mut native = Vec::new();
9155 let mut fallback = Vec::new();
9156 let far_ends: Vec<(&DependencyEdge, &str, bool, Option<&Value>)> = depends_on
9157 .iter()
9158 .map(|edge| {
9159 let same_source = edge
9160 .to
9161 .source()
9162 .is_none_or(|source| source == self.name.as_str());
9163 // A qualified id's source segment runs to its *first* colon — `GlobalId` and
9164 // `DependencyEndpoint::source` both read it that way — and a native id may hold
9165 // colons of its own, so the far end is everything after that one separator.
9166 // Splitting at the last would truncate `work:urn:task:7` to `7`.
9167 let far_id = if edge.to.is_qualified() {
9168 edge.to
9169 .id()
9170 .split_once(':')
9171 .map_or(edge.to.id(), |(_, native)| native)
9172 } else {
9173 edge.to.id()
9174 };
9175 // One that already blocks the near issue was answered by that issue's own
9176 // read, which carried each of its blockers' kinds — an issue every one — so it
9177 // is not read again.
9178 let blocking = carried.and_then(|nodes| {
9179 nodes
9180 .iter()
9181 .find(|node| node.get("id").and_then(Value::as_str) == Some(far_id))
9182 });
9183 (edge, far_id, same_source, blocking)
9184 })
9185 .collect();
9186 // Every other same-source far end is read by its own id, exactly as the item it is a
9187 // far end of is: whether this board holds it is that read's answer, never a listing's.
9188 // They are read together, [`DETAIL_BATCH`] to a request, rather than one each.
9189 let mut unread: Vec<NativeId> = Vec::new();
9190 for (_, far_id, same_source, blocking) in &far_ends {
9191 let id = NativeId((*far_id).to_owned());
9192 if *same_source && blocking.is_none() && !unread.contains(&id) {
9193 unread.push(id);
9194 }
9195 }
9196 let read: BTreeMap<NativeId, Option<Resolved>> = unread
9197 .iter()
9198 .cloned()
9199 .zip(self.items_by_ids(&unread).await?)
9200 .collect();
9201 for (edge, far_id, same_source, blocking) in far_ends {
9202 let far = match (same_source, blocking) {
9203 (false, _) => None,
9204 (true, Some(node)) => Some(FarEnd {
9205 kind: if required_str(node, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
9206 BoardKind::Document
9207 } else {
9208 BoardKind::Work(related_kind(node)?)
9209 },
9210 content_kind: ContentKind::Issue,
9211 }),
9212 (true, None) => {
9213 let read = read
9214 .get(&NativeId(far_id.to_owned()))
9215 .cloned()
9216 .flatten()
9217 .ok_or_else(|| SourceError::Refused {
9218 message: format!("GitHub dependency item {far_id} was not found"),
9219 })?;
9220 Some(FarEnd {
9221 kind: read.kind,
9222 content_kind: read.content_kind,
9223 })
9224 }
9225 };
9226 let far = far.as_ref();
9227 // The caller says which kind the far end is, and this board holds the far end
9228 // itself, so a disagreement is settled here rather than stored: recorded, the
9229 // wrong kind would read back as a cross-level edge that never existed; written
9230 // natively, it would name a relationship of a different level than the caller
9231 // asked for.
9232 //
9233 // A far end this board holds as a *document* fails the same comparison and is
9234 // refused by the same sentence: `ItemKind` has no document variant because
9235 // nothing may point at one, so no caller can name it correctly and the refusal
9236 // is the only honest answer.
9237 if let Some(disagreeing) = far.filter(|far| far.kind != BoardKind::Work(edge.to.kind)) {
9238 return Err(SourceError::Refused {
9239 message: format!(
9240 "GitHub dependency item {far_id} is a {} of this board, and this item \
9241 names it as a {}; record the kind it is",
9242 disagreeing.kind.describes(),
9243 edge.to.kind.marker()
9244 ),
9245 });
9246 }
9247 // A draft has neither `blockedBy` nor `blocking`, so no edge of one is native
9248 // however the far end is spelled — and one classified native here would be
9249 // written nowhere at all, because a draft's native reconciliation never runs.
9250 let native_here = near_content == ContentKind::Issue
9251 && far.is_some_and(|far| {
9252 far.content_kind == ContentKind::Issue
9253 && BoardKind::Work(edge.to.kind) == near_kind
9254 });
9255 if native_here {
9256 native.push(far_id.to_owned());
9257 } else {
9258 fallback.push(edge.clone());
9259 }
9260 }
9261 Ok((native, fallback))
9262 }
9263
9264 async fn update_existing(
9265 &self,
9266 item: &Resolved,
9267 incoming: &Incoming<'_>,
9268 body: &Option<String>,
9269 status_target: Option<&StatusTarget>,
9270 ) -> Result<(), SourceError> {
9271 let title = incoming.written_title();
9272 // A terminal status closes the issue here, in the same mutation as its body: its board
9273 // option was selected before this, so a close never lands on an item whose board cannot
9274 // show it.
9275 let mut fields = match item.content_kind {
9276 ContentKind::DraftIssue => json!({"title":title,"body":body}),
9277 ContentKind::Issue => json!({"title":title,"body":body,
9278 "stateInput":state_input(status_target)}),
9279 };
9280 // A write the store's cache expects sends only the members whose value differs from the
9281 // version it expects, and nothing at all when none does.
9282 if self.expected.is_primed(&item.id)
9283 && let Some(members) = fields.as_object_mut()
9284 {
9285 if members.get("title").and_then(Value::as_str) == Some(item.title.as_str()) {
9286 members.remove("title");
9287 }
9288 if members.get("body").and_then(Value::as_str)
9289 == Some(item.raw_body.as_deref().unwrap_or_default())
9290 {
9291 members.remove("body");
9292 }
9293 let terminal = matches!(status_target, Some(StatusTarget::Terminal(_, _)));
9294 if members.contains_key("stateInput") && terminal == item.closed {
9295 members.remove("stateInput");
9296 }
9297 if members.is_empty() {
9298 return Ok(());
9299 }
9300 }
9301 self.update_content(item.content_kind, &item.id, fields)
9302 .await
9303 }
9304
9305 /// Update one board item's content with exactly `fields` beside its id, through the
9306 /// mutation its kind takes: `updateIssue` for an issue, `updateProjectV2DraftIssue` for
9307 /// a draft.
9308 ///
9309 /// Every input field either mutation leaves out is a field GitHub leaves as it is, which
9310 /// is what lets a narrow write carry the one thing it changes and nothing else.
9311 async fn update_content(
9312 &self,
9313 kind: ContentKind,
9314 id: &NativeId,
9315 fields: Value,
9316 ) -> Result<(), SourceError> {
9317 let (operation, id_key, pointer) = match kind {
9318 ContentKind::DraftIssue => (
9319 graphql::UPDATE_DRAFT,
9320 "draftIssueId",
9321 "/updateProjectV2DraftIssue/draftIssue",
9322 ),
9323 ContentKind::Issue => (graphql::UPDATE_ISSUE, "id", "/updateIssue/issue"),
9324 };
9325 let mut input = fields;
9326 input[id_key] = json!(id.0);
9327 let data = self.graphql(operation, json!({"input":input})).await?;
9328 let returned = data
9329 .pointer(pointer)
9330 .ok_or_else(|| SourceError::Malformed {
9331 message: "GitHub item update returned no item".into(),
9332 })?;
9333 if required_str(returned, "id")? != id.0 {
9334 return Err(SourceError::Malformed {
9335 message: "GitHub item update returned the wrong item".into(),
9336 });
9337 }
9338 Ok(())
9339 }
9340
9341 /// Creates one issue, files it on the board, and reports what a read of it would say:
9342 /// its content id, its board item id, and the web address GitHub gave it.
9343 ///
9344 /// Two calls rather than one: `createIssue` answers with an issue that is on no board,
9345 /// and `addProjectV2ItemById` is what puts it there. Filing it at creation through
9346 /// `CreateIssueInput.projectV2Ids` was tried and is not done: GitHub answered with no
9347 /// board item, and the `addProjectV2ItemById` that then had to follow was refused
9348 /// "Content already exists in this project". A terminal status is not written here:
9349 /// `finish_write` selects its option first and closes the issue after, so a close never
9350 /// lands on an item whose board cannot show it.
9351 ///
9352 /// The address and the number come back here because this is the only place either is
9353 /// known before GitHub's own board read catches up — an item this run created answers
9354 /// the reads that follow it out of the record below, and one remembered without them
9355 /// would report no location and no key for the rest of the run.
9356 async fn create_and_file_issue(
9357 &self,
9358 board_id: &str,
9359 repository: &RepositoryTarget,
9360 incoming: &Incoming<'_>,
9361 body: &Option<String>,
9362 ) -> Result<Landed, SourceError> {
9363 let repository_id = self.repository_id(repository, incoming).await?;
9364 let data = self
9365 .graphql(
9366 graphql::CREATE_ISSUE,
9367 json!({"input":{
9368 "repositoryId":repository_id,"title":incoming.written_title(),"body":body
9369 }}),
9370 )
9371 .await?;
9372 let created = data
9373 .pointer("/createIssue/issue")
9374 .filter(|value| !value.is_null())
9375 .ok_or_else(|| SourceError::Malformed {
9376 message: "GitHub issue creation returned no issue".into(),
9377 })?;
9378 let content_id = NativeId(required_str(created, "id")?.to_owned());
9379 // Optional although GitHub's schema makes it non-null: the issue exists by now, so
9380 // a response without it is not worth failing a landed write over — the item simply
9381 // reports no location until the board read catches up, which is what it did before.
9382 let url = optional_str(created, "url")?.map(str::to_owned);
9383 // The issue exists from here on, so an unreadable number and a refused board
9384 // filing below each try, best effort, to take it back: an issue in the repository
9385 // that is on no board is an item nobody asked for and nothing here would find again.
9386 //
9387 // Its number is optional on the same terms its address is — a landed write is not
9388 // worth failing over a member that came back missing, and such an item reports no
9389 // handle until a board read catches up. A number that is *present* and is not an
9390 // unsigned integer is still a response this source cannot read.
9391 let number = match created_issue_number(created) {
9392 Ok(number) => number,
9393 Err(error) => {
9394 let _ = self.delete_issue(&content_id).await;
9395 return Err(error);
9396 }
9397 };
9398 let added = match self
9399 .graphql(
9400 graphql::ADD_TO_BOARD,
9401 json!({"input":{"projectId":board_id,"contentId":content_id.0}}),
9402 )
9403 .await
9404 {
9405 Ok(added) => added,
9406 Err(error) => {
9407 let _ = self.delete_issue(&content_id).await;
9408 return Err(error);
9409 }
9410 };
9411 let item = added
9412 .pointer("/addProjectV2ItemById/item")
9413 .filter(|value| !value.is_null())
9414 .ok_or_else(|| SourceError::Malformed {
9415 message: "GitHub board addition returned no project item".into(),
9416 })?;
9417 Ok(Landed {
9418 content_id,
9419 item_id: required_str(item, "id")?.to_owned(),
9420 url,
9421 number,
9422 })
9423 }
9424
9425 /// Move one issue under the project it now belongs to, or out of the one it left.
9426 async fn reparent(
9427 &self,
9428 held: Option<NativeId>,
9429 child: &NativeId,
9430 wanted: Option<&NativeId>,
9431 ) -> Result<(), SourceError> {
9432 if held.as_ref() == wanted {
9433 return Ok(());
9434 }
9435 if let Some(held) = &held {
9436 self.sub_issue(graphql::REMOVE_SUB_ISSUE, held, child, "removeSubIssue")
9437 .await?;
9438 }
9439 if let Some(wanted) = wanted {
9440 self.sub_issue(graphql::ADD_SUB_ISSUE, wanted, child, "addSubIssue")
9441 .await?;
9442 }
9443 Ok(())
9444 }
9445
9446 async fn sub_issue(
9447 &self,
9448 operation: &str,
9449 parent: &NativeId,
9450 child: &NativeId,
9451 root: &str,
9452 ) -> Result<(), SourceError> {
9453 let data = self
9454 .graphql(
9455 operation,
9456 json!({"input":{"issueId":parent.0,"subIssueId":child.0}}),
9457 )
9458 .await?;
9459 let issue =
9460 data.pointer(&format!("/{root}/issue"))
9461 .ok_or_else(|| SourceError::Malformed {
9462 message: "GitHub sub-issue update returned no issue".into(),
9463 })?;
9464 let sub =
9465 data.pointer(&format!("/{root}/subIssue"))
9466 .ok_or_else(|| SourceError::Malformed {
9467 message: "GitHub sub-issue update returned no sub-issue".into(),
9468 })?;
9469 if required_str(issue, "id")? != parent.0 || required_str(sub, "id")? != child.0 {
9470 return Err(SourceError::Malformed {
9471 message: "GitHub sub-issue update returned the wrong issues".into(),
9472 });
9473 }
9474 Ok(())
9475 }
9476
9477 /// Bring one issue's `blockedBy` to exactly `native`, sending only the difference, and say
9478 /// whether there was one.
9479 ///
9480 /// An issue [`Issue::Created`] by this very write is blocked by nothing yet, so its
9481 /// relationships are not read: there is nothing a read of them could find.
9482 async fn reconcile_blocked_by(
9483 &self,
9484 content_id: &NativeId,
9485 native: &[String],
9486 issue: Issue<'_>,
9487 ) -> Result<bool, SourceError> {
9488 let current = match issue {
9489 Issue::Created => Vec::new(),
9490 Issue::Existing(Some(held)) => held
9491 .iter()
9492 .map(|far| required_str(far, "id").map(str::to_owned))
9493 .collect::<Result<Vec<_>, _>>()?,
9494 Issue::Existing(None) => self.native_dependency_ids(content_id).await?,
9495 };
9496 let mut changed = false;
9497 for (operation, far_id) in current
9498 .iter()
9499 .filter(|id| !native.contains(id))
9500 .map(|id| (graphql::REMOVE_BLOCKED_BY, id))
9501 .chain(
9502 native
9503 .iter()
9504 .filter(|id| !current.contains(id))
9505 .map(|id| (graphql::ADD_BLOCKED_BY, id)),
9506 )
9507 {
9508 let data = self
9509 .graphql(
9510 operation,
9511 json!({"input":{"issueId":content_id.0,"blockingIssueId":far_id}}),
9512 )
9513 .await?;
9514 let root = if operation == graphql::ADD_BLOCKED_BY {
9515 "addBlockedBy"
9516 } else {
9517 "removeBlockedBy"
9518 };
9519 let issue =
9520 data.pointer(&format!("/{root}/issue"))
9521 .ok_or_else(|| SourceError::Malformed {
9522 message: "GitHub dependency update returned no issue".into(),
9523 })?;
9524 let blocker = data
9525 .pointer(&format!("/{root}/blockingIssue"))
9526 .ok_or_else(|| SourceError::Malformed {
9527 message: "GitHub dependency update returned no blocking issue".into(),
9528 })?;
9529 if required_str(issue, "id")? != content_id.0 || required_str(blocker, "id")? != far_id
9530 {
9531 return Err(SourceError::Malformed {
9532 message: "GitHub dependency update returned the wrong issues".into(),
9533 });
9534 }
9535 changed = true;
9536 }
9537 Ok(changed)
9538 }
9539}
9540
9541/// What a write needs to know of one far end it names: which kind of item it is, and whether
9542/// it is an issue a native relationship can name.
9543struct FarEnd {
9544 kind: BoardKind,
9545 content_kind: ContentKind,
9546}
9547
9548/// Whether the issue one write reconciles was created by that write or was already there.
9549#[derive(Clone, Copy, PartialEq, Eq)]
9550enum Issue<'a> {
9551 /// Created by this write, so it holds no relationships yet.
9552 Created,
9553 /// On the board before this write, holding whatever relationships it holds — the far
9554 /// ends of its whole `blockedBy`, when the read that reached it carried them.
9555 Existing(Option<&'a [Value]>),
9556}
9557
9558/// What resolving one node id reached; see [`GitHubProjectsSource::reach`].
9559enum Reached {
9560 /// An issue this board holds, resolved into everything this source reports about it.
9561 Held(Box<Resolved>),
9562 /// Nothing this board holds: no such node, or a node on some other board.
9563 Nothing,
9564 /// A board draft, which [`graphql::ISSUE`] reaches and reads nothing of, so it is read
9565 /// again by [`GitHubProjectsSource::draft_by_id`].
9566 Draft,
9567}
9568
9569/// What GitHub says when a string is not a node id it can resolve.
9570///
9571/// Matched because it is the ordinary answer to a project selector naming a project by its
9572/// *name*, and reporting that as a failure would make naming one impossible. It is read
9573/// off the refusal GitHub sent, never guessed from the shape of the string: this source
9574/// does not define the syntax of a GitHub node id and would be wrong about it.
9575const UNRESOLVABLE_NODE: &str = "could not resolve to a node";
9576
9577/// `error` with `note` added to the end of what it says, its kind and every other member
9578/// unchanged — so a caller still branches on the failure that happened, and reads beside it
9579/// what that failure left behind.
9580fn noting(error: SourceError, note: &str) -> SourceError {
9581 match error {
9582 SourceError::Config { message } => SourceError::Config {
9583 message: message + note,
9584 },
9585 SourceError::Auth { message } => SourceError::Auth {
9586 message: message + note,
9587 },
9588 SourceError::Refused { message } => SourceError::Refused {
9589 message: message + note,
9590 },
9591 SourceError::RateLimited {
9592 retry_after_seconds,
9593 message,
9594 } => SourceError::RateLimited {
9595 retry_after_seconds,
9596 message: Some(message.unwrap_or_default() + note),
9597 },
9598 SourceError::Unavailable { message } => SourceError::Unavailable {
9599 message: message + note,
9600 },
9601 SourceError::Malformed { message } => SourceError::Malformed {
9602 message: message + note,
9603 },
9604 }
9605}
9606
9607/// The variables of one [`graphql::ISSUE_COPY_DETAILS`] request, as [`detail_batch`] binds its
9608/// own: a slot `batch` has no id for is bound to its last id, read again at no added price.
9609fn copy_detail_batch(batch: &[NativeId], comments: &PageRequest) -> Value {
9610 let mut variables = serde_json::Map::new();
9611 for slot in 0..COPY_DETAIL_BATCH {
9612 let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
9613 variables.insert(format!("id{slot}"), json!(id));
9614 }
9615 variables.insert("first".to_owned(), json!(comments.limit.min(MAX_PAGE_SIZE)));
9616 variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
9617 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
9618 variables.insert("duplicates".to_owned(), json!(true));
9619 Value::Object(variables)
9620}
9621
9622/// The variables of one [`graphql::ISSUE_DETAILS`] request over `batch` — at most
9623/// [`DETAIL_BATCH`] ids — each item with the first page of its comments when `comments` asks
9624/// for them.
9625///
9626/// The document is fixed-size, so a slot `batch` has no id for is bound to its last id, which
9627/// is read again at no added price.
9628fn detail_batch(batch: &[NativeId], comments: Option<&PageRequest>) -> Value {
9629 let mut variables = serde_json::Map::new();
9630 for slot in 0..DETAIL_BATCH {
9631 let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
9632 variables.insert(format!("id{slot}"), json!(id));
9633 }
9634 variables.insert(
9635 "first".to_owned(),
9636 json!(comments.map_or(MAX_PAGE_SIZE, |page| page.limit.min(MAX_PAGE_SIZE))),
9637 );
9638 variables.insert("comments".to_owned(), json!(comments.is_some()));
9639 variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
9640 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
9641 variables.insert("duplicates".to_owned(), json!(true));
9642 Value::Object(variables)
9643}
9644
9645/// Whether this refusal is GitHub saying the id names no node at all.
9646fn unresolvable_node(error: &SourceError) -> bool {
9647 matches!(error, SourceError::Refused { message }
9648 if message.to_ascii_lowercase().contains(UNRESOLVABLE_NODE))
9649}
9650
9651/// One project name, as a search qualifier which filters on it at the server.
9652///
9653/// Quoted so the whole title is one phrase rather than a bag of words, with the two
9654/// characters GitHub's own quoting grammar gives a meaning inside a quoted phrase escaped
9655/// the way it documents. A title matched here is still compared for equality afterwards:
9656/// the qualifier narrows what the server sends, and this source decides what it names.
9657fn title_qualifier(name: &str) -> String {
9658 format!("in:title {}", quoted(name))
9659}
9660
9661/// `value` as one quoted phrase of a GitHub search or a board filter, with the two
9662/// characters GitHub's quoting grammar gives a meaning inside a quoted phrase escaped the way
9663/// it documents — so a value holding a qualifier's spelling is searched for rather than
9664/// obeyed.
9665fn quoted(value: &str) -> String {
9666 let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
9667 format!("\"{escaped}\"")
9668}
9669
9670/// The search qualifier for the issues updated at or after `since`.
9671///
9672/// Written to the second, rounded down, which can only widen what the search returns.
9673fn updated_qualifier(since: DateTime<Utc>) -> String {
9674 format!("updated:>={}", since.format("%Y-%m-%dT%H:%M:%S+00:00"))
9675}
9676
9677/// The search terms that narrow a board-scoped issue search to a task query's text and
9678/// metadata predicates, or `None` when it carries neither.
9679///
9680/// The text is one quoted phrase, searched `in:title`, `in:body` or both as its fields say,
9681/// and each metadata value is one more quoted phrase, which GitHub finds in the body because
9682/// its index covers the metadata comment the value is stored in. GitHub ANDs the phrases and
9683/// matches each in any field the `in:` qualifier names, so a query naming a title search and
9684/// a metadata value searches both fields for both — wider than asked, never narrower, and
9685/// every candidate is confirmed in process afterwards.
9686///
9687/// **This narrows a text search, and that is this source's declared semantics.** GitHub
9688/// matches whole tokens where a substring rule would match inside a word, so an item holding
9689/// the text only inside a longer word is not returned. A text of nothing but whitespace
9690/// matches every item, so it narrows nothing and is not sent.
9691fn narrowing_qualifiers(query: &TaskQuery) -> Option<String> {
9692 let text = query
9693 .text
9694 .as_ref()
9695 .filter(|text| !text.terms.trim().is_empty());
9696 if text.is_none() && query.metadata.is_empty() {
9697 return None;
9698 }
9699 let (title, body) = match text.map(|text| text.fields) {
9700 None => (false, true),
9701 Some(TextFields::Title) => (true, !query.metadata.is_empty()),
9702 Some(TextFields::Content) => (false, true),
9703 Some(TextFields::TitleOrContent) => (true, true),
9704 };
9705 let fields = match (title, body) {
9706 (true, true) => "in:title,body",
9707 (true, false) => "in:title",
9708 _ => "in:body",
9709 };
9710 let phrases = text
9711 .map(|text| text.terms.clone())
9712 .into_iter()
9713 .chain(
9714 query
9715 .metadata
9716 .iter()
9717 .map(|wanted| as_stored(wanted.value())),
9718 )
9719 .map(|phrase| quoted(&phrase))
9720 .collect::<Vec<_>>();
9721 Some(format!("{fields} {}", phrases.join(" ")))
9722}
9723
9724/// The search terms that narrow a board-scoped issue search to a project or document query's
9725/// text, or `None` when it has none or a blank one: the phrase, in the fields, a task query
9726/// carrying that text alone is sent as by [`narrowing_qualifiers`].
9727fn text_qualifiers(text: Option<&TextQuery>) -> Option<String> {
9728 narrowing_qualifiers(&TaskQuery {
9729 text: text.cloned(),
9730 ..TaskQuery::default()
9731 })
9732}
9733
9734/// Refuses a project or document query's text GitHub's issue search cannot find, before
9735/// anything is asked of GitHub, on exactly the terms [`refuse_unsearchable`] refuses a task
9736/// query's.
9737fn refuse_unsearchable_text(text: Option<&TextQuery>) -> Result<(), SourceError> {
9738 refuse_unsearchable(&TaskQuery {
9739 text: text.cloned(),
9740 ..TaskQuery::default()
9741 })
9742}
9743
9744/// Refuses a task query naming a text or a metadata value GitHub's issue search cannot find,
9745/// before anything is asked of GitHub.
9746///
9747/// GitHub's index holds words, so a phrase with no letter or digit names none to find, and no
9748/// bounded query answers it: sent, GitHub's answer to it is nothing this source may rely on;
9749/// left out, the search is every issue of the board. So this source says it cannot answer
9750/// rather than reading the board or answering nothing. A blank text is not refused: it narrows
9751/// nothing GitHub could search for, and keeps the board read it always had.
9752fn refuse_unsearchable(query: &TaskQuery) -> Result<(), SourceError> {
9753 const WHY: &str = "GitHub's issue search indexes words, so it cannot answer a value with no \
9754 letter or digit with a bounded query";
9755 if let Some(text) = &query.text
9756 && !text.terms.trim().is_empty()
9757 && !has_words(&text.terms)
9758 {
9759 return Err(SourceError::Refused {
9760 message: format!(
9761 "cannot search for the text {:?}: {WHY}; search for a text holding a letter or a digit",
9762 text.terms
9763 ),
9764 });
9765 }
9766 if let Some(wanted) = query
9767 .metadata
9768 .iter()
9769 .find(|wanted| !has_words(wanted.value()))
9770 {
9771 return Err(SourceError::Refused {
9772 message: format!(
9773 "cannot filter by the metadata value {:?} at {:?}: {WHY}; filter by a value holding a letter or a digit",
9774 wanted.value(),
9775 std::iter::once(wanted.key())
9776 .chain(wanted.path().iter().map(String::as_str))
9777 .collect::<Vec<_>>()
9778 .join("/"),
9779 ),
9780 });
9781 }
9782 Ok(())
9783}
9784
9785/// Whether GitHub's index could hold a word of `phrase`: whether it has a letter or a digit.
9786fn has_words(phrase: &str) -> bool {
9787 phrase.chars().any(char::is_alphanumeric)
9788}
9789
9790/// `value` spelled the way the metadata slot stores it: as the inside of its JSON string.
9791///
9792/// What GitHub indexes is the slot's JSON text, so a value holding a character JSON escapes —
9793/// a newline, a tab, a quote — is found by the escape the body holds and not by the character,
9794/// which GitHub's word match would read as different words.
9795fn as_stored(value: &str) -> String {
9796 let encoded = Value::String(value.to_owned()).to_string();
9797 encoded[1..encoded.len() - 1].to_owned()
9798}
9799
9800/// The one narrower question a task query carrying a text, metadata or origin predicate is
9801/// sent as.
9802enum Narrowing {
9803 /// Every carrier of this origin: [`graphql::ORIGIN_LOOKUP`].
9804 Origin(String),
9805 /// The board-scoped issue search narrowed by these qualifiers.
9806 Search(String),
9807}
9808
9809impl Narrowing {
9810 /// What this question is remembered under for the length of one command.
9811 fn key(&self) -> String {
9812 match self {
9813 Self::Origin(origin) => format!("origin {origin}"),
9814 Self::Search(also) => format!("search {also}"),
9815 }
9816 }
9817}
9818
9819/// Where one connection of [`graphql::ORIGIN_LOOKUP`] resumes.
9820enum Resumed {
9821 /// It reported another page, which starts after this cursor.
9822 More(String),
9823 /// It has ended. Sending this cursor again — the page's own end when it had one, and
9824 /// otherwise the cursor it was reached from — answers an empty page, so the one document
9825 /// can go on walking the other connection.
9826 Ended(Option<String>),
9827}
9828
9829impl Resumed {
9830 /// Whether the connection has another page.
9831 const fn has_more(&self) -> bool {
9832 matches!(self, Self::More(_))
9833 }
9834
9835 /// The cursor to send this connection next.
9836 fn cursor(self) -> Option<String> {
9837 match self {
9838 Self::More(next) => Some(next),
9839 Self::Ended(last) => last,
9840 }
9841 }
9842}
9843
9844/// Where `connection`, reached from `after`, resumes — refused when it reports another page
9845/// with no cursor to it, or from a cursor that does not advance.
9846fn resumed(connection: &Value, after: Option<&str>) -> Result<Resumed, SourceError> {
9847 let info = connection
9848 .get("pageInfo")
9849 .ok_or_else(|| SourceError::Malformed {
9850 message: "GitHub connection has no pageInfo".into(),
9851 })?;
9852 let end = optional_str(info, "endCursor")?;
9853 if required_bool(info, "hasNextPage")? {
9854 let next = end.ok_or_else(|| SourceError::Malformed {
9855 message: "GitHub connection reports another page and no endCursor".into(),
9856 })?;
9857 validate_cursor_progress(after, next)?;
9858 return Ok(Resumed::More(next.to_owned()));
9859 }
9860 Ok(Resumed::Ended(
9861 end.map(str::to_owned).or_else(|| after.map(str::to_owned)),
9862 ))
9863}
9864
9865/// The board, and every item on it this source reports.
9866#[derive(Clone)]
9867struct Board {
9868 id: String,
9869 fields: Value,
9870 items: Vec<Resolved>,
9871}
9872
9873/// What a write needs of the board and nothing more: its node id and its field
9874/// definitions, in the shape a read of the board's own `fields` gives them.
9875///
9876/// Deliberately no items. A write decides which item it writes, which parent it files
9877/// under and which far ends it names by reading each of them by its own id; this is the
9878/// half of the board those reads cannot carry, and holding no item is what keeps it from
9879/// ever being asked whether an item is there.
9880#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
9881struct BoardFields {
9882 id: BoardId,
9883 fields: Value,
9884}
9885
9886/// A board's node id: what a field write and `addProjectV2ItemById` address.
9887///
9888/// Never blank, because a blank one addresses no board — so an id GitHub answers blank is
9889/// refused where it is read, and one an item names blank is read as not named at all.
9890#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
9891#[serde(try_from = "String")]
9892struct BoardId(String);
9893
9894impl TryFrom<String> for BoardId {
9895 type Error = String;
9896
9897 /// The same refusal [`BoardId::parse`] makes, for an id read back from a kept context.
9898 fn try_from(id: String) -> Result<Self, Self::Error> {
9899 Self::parse(&id).map_err(|error| error.to_string())
9900 }
9901}
9902
9903/// Where one write left its item, for the record the rest of the command reads it out of.
9904///
9905/// A named record rather than a tuple because the update arm and the create arm each fill
9906/// all four, and two `Option`s of different meaning side by side in a tuple are two
9907/// positions a reader has to count.
9908struct Landed {
9909 /// The issue's own node id, which is the [`NativeId`] this source reports.
9910 content_id: NativeId,
9911 /// The board item's id, which is what a field write addresses.
9912 // llmlint: ignore[invalid_states_unrepresentable] This field and the one below are `Resolved::item_id` and `Resolved::url` carried out of one call: the update arm assigns them from an existing `Resolved` and the whole record is assigned straight back into one. A newtype introduced here alone would be wrapped at both of those boundaries and unwrapped at every use, and would make this private record disagree with the type the same values have on the struct they come from and return to. Where the board item id gets a newtype is on `Resolved`, which is the contract's own shape and not this change's to move.
9913 item_id: String,
9914 /// The web address GitHub gave the issue, when it gave one.
9915 // llmlint: ignore[invalid_states_unrepresentable] The answer `Resolved::url` and the contract's `Task::url` already record: a web address this source never parses, resolves or compares — it reads GitHub's string and hands it back, and `Location::Url` is where the contract gives it a shape. Validating it here would have this plugin decide what GitHub may call an address.
9916 url: Option<String>,
9917 /// The issue's number on its repository, when GitHub reported one.
9918 number: Option<u64>,
9919}
9920
9921impl BoardId {
9922 fn parse(id: &str) -> Result<Self, SourceError> {
9923 if id.trim().is_empty() {
9924 return Err(SourceError::Malformed {
9925 message: "GitHub named a board with a blank node id".into(),
9926 });
9927 }
9928 Ok(Self(id.to_owned()))
9929 }
9930
9931 fn as_str(&self) -> &str {
9932 &self.0
9933 }
9934}
9935
9936impl Board {
9937 fn field<'a>(fields: &'a Value, name: &str) -> Result<Option<&'a Value>, SourceError> {
9938 complete_connection(fields, "project fields", NESTED_PAGE_SIZE)?;
9939 let nodes = fields
9940 .get("nodes")
9941 .and_then(Value::as_array)
9942 .ok_or_else(|| SourceError::Malformed {
9943 message: "GitHub project fields.nodes is not an array".into(),
9944 })?;
9945 Ok(nodes
9946 .iter()
9947 .find(|field| field.get("name").and_then(Value::as_str) == Some(name)))
9948 }
9949}
9950
9951/// One board item, resolved into everything this source reports about it.
9952///
9953/// Serializable because it is what [`TaskSource::write_context`] hands the store's cache and
9954/// [`TaskSource::prime_write`] takes back — see [`expected`].
9955#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
9956struct Resolved {
9957 item_id: String,
9958 id: NativeId,
9959 content_kind: ContentKind,
9960 kind: BoardKind,
9961 title: String,
9962 body: Option<String>,
9963 /// The body exactly as GitHub holds it, metadata slot and all, which is what a write
9964 /// that changes the slot alone has to keep byte for byte outside it.
9965 raw_body: Option<String>,
9966 status: Status,
9967 /// The name of the board `Status` option this item sits in, as the board spells it.
9968 option: Option<String>,
9969 /// What its `Priority` field says, read through this instance's mapping.
9970 priority: HeldPriority,
9971 /// Whether this item's issue is closed. A draft has no such state and is never closed.
9972 closed: bool,
9973 /// GitHub's reason for a closed issue's closure, as it spells it — `None` for an open
9974 /// issue, a draft, and an issue closed before GitHub recorded reasons.
9975 #[serde(default)]
9976 reason: Option<String>,
9977 /// The tasks this one delivers, read out of its slot. Empty for anything not a task.
9978 delivers: Vec<TaskRef>,
9979 /// Every task that delivers this one, read out of its slot. Empty for anything not a
9980 /// task.
9981 delivered_by: Vec<TaskRef>,
9982 labels: Vec<Label>,
9983 parent: Option<NativeId>,
9984 // llmlint: ignore[invalid_states_unrepresentable] The write side's reason, read back: this is the engine's qualified id, taken out of a board text field and handed on untouched. A newtype here would have this plugin define the syntax of an id `docs/metadata.md` says no plugin ever constructs or interprets.
9985 origin: Option<String>,
9986 /// What each board text field this instance projects metadata onto holds for this item,
9987 /// by field name — only the fields holding a value, an empty text included. What a write compares the
9988 /// item's metadata against, so a field already holding its value is not written again;
9989 /// never read back as metadata, which the slot alone reports.
9990 projected: BTreeMap<String, String>,
9991 /// The issue's own number on its repository, as GitHub reports it.
9992 ///
9993 /// `None` in exactly two cases: a draft, which has no number at all — `DraftIssue`
9994 /// declares none, and a draft is not filed in a repository to be numbered by one — and
9995 /// an issue this run created whose creating mutation answered without one, which is a
9996 /// response GitHub's own schema says cannot happen and which a landed write is not
9997 /// worth failing over. An `Issue` read off the board always has one.
9998 number: Option<u64>,
9999 url: Option<String>,
10000 created_at: Option<DateTime<Utc>>,
10001 updated_at: Option<DateTime<Utc>>,
10002 /// When the board item itself last changed — what a board field write moves — when the
10003 /// read that reached it said.
10004 item_updated_at: Option<DateTime<Utc>>,
10005 /// How many comments the issue holds, when the read that reached it said.
10006 comment_count: Option<u64>,
10007 /// How many relationship events the issue's timeline holds — every dependency, as
10008 /// `blockedBy` or `blocking`, and every project membership, as its parent, added or
10009 /// removed — when the read that reached it said.
10010 relationship_events: Option<u64>,
10011 /// The server's clock on the response that read it — its `Date` header — when the
10012 /// response carried one.
10013 served_at: Option<DateTime<Utc>>,
10014 /// The digest of its [`change_token::Facets`] — its own kind, its board field values and
10015 /// its labels — when the read that reached it carried all three whole.
10016 #[serde(default)]
10017 facets: Option<change_token::FacetsDigest>,
10018 own_repository: Option<Repository>,
10019 repositories: Vec<Repository>,
10020 classification: Classification,
10021 slot: BTreeMap<String, Value>,
10022 /// The node id of the board this item sits on, when the read that reached it said.
10023 board_id: Option<String>,
10024 /// The definition of every board field this item holds a value of, in the shape a read
10025 /// of the board's own `fields` gives one.
10026 ///
10027 /// Only the fields this item has a value in: a field it holds nothing of is not here,
10028 /// which says nothing about whether the board has it.
10029 fields: Vec<Value>,
10030 /// Every field the board this item sits on defines, as its own read of the board's
10031 /// `fields` gives them — when the read that reached the item carried them, which a read
10032 /// of it by its own id does. What a write of it needs of the board, then, needs no read
10033 /// of the board.
10034 board_fields: Option<Value>,
10035 /// The far ends of this issue's whole `blockedBy` connection, each as a dependency read
10036 /// selects one — when the read that reached it carried the connection to its end, which a
10037 /// read of it by its own id does for any issue blocked by no more than a page. What a
10038 /// write reconciles that relationship against, and what a read of its forward edges in
10039 /// the same command answers with.
10040 blocked_by: Option<Vec<Value>>,
10041}
10042
10043impl Resolved {
10044 /// The board this item's own read names it on, when that read named one this source can
10045 /// address.
10046 fn named_board(&self) -> Option<BoardId> {
10047 self.board_id
10048 .as_deref()
10049 .and_then(|id| BoardId::parse(id).ok())
10050 }
10051
10052 /// The board's id and every field it defines, when the read that reached this item
10053 /// carried both — which a read of it by its own id does.
10054 fn carried_board(&self) -> Option<BoardFields> {
10055 Some(BoardFields {
10056 id: self.named_board()?,
10057 fields: self.board_fields.clone()?,
10058 })
10059 }
10060
10061 /// Whether this item holds a value of the board field called `name`, and so carries
10062 /// that field's definition. `false` says nothing about whether the board has the field.
10063 fn defines(&self, name: &str) -> bool {
10064 self.fields
10065 .iter()
10066 .any(|field| field.get("name").and_then(Value::as_str) == Some(name))
10067 }
10068
10069 /// The metadata a caller sees: their own keys, plus the copy origin this source keeps
10070 /// in a field of its own, and none of the five keys that are only an encoding.
10071 ///
10072 /// The two delivery keys are left out for every kind, not only for a task: they are
10073 /// the encoding of [`Task::delivers`] and [`Task::delivered_by`], and a project or a
10074 /// document carrying one holds nothing a caller's own metadata could mean by it.
10075 fn metadata(&self) -> BTreeMap<String, Value> {
10076 let mut metadata = self.slot.clone();
10077 metadata.remove(Repository::METADATA_KEY);
10078 metadata.remove(DependencyEdge::RECORDED_KEY);
10079 metadata.remove(ItemKind::METADATA_KEY);
10080 metadata.remove(TaskRef::DELIVERS_KEY);
10081 metadata.remove(TaskRef::DELIVERED_BY_KEY);
10082 metadata.remove(Classification::METADATA_KEY);
10083 // The board field is the origin, and the body's copy of it is only a mirror for the
10084 // issue search to find: an item whose field holds none has none, whatever its body
10085 // says, so no reader ever sees two answers.
10086 metadata.remove(ORIGIN_KEY);
10087 if let Some(origin) = &self.origin {
10088 metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin.clone()));
10089 }
10090 metadata
10091 }
10092
10093 /// Where this item is, as a link a reader can open.
10094 ///
10095 /// A board is a hosted place and every issue on it has a web address, so that address
10096 /// is what "where is this?" means here — and [`Location::Url`] is what says which kind
10097 /// of place it is, so a reader knows to open it rather than to read a file out. It
10098 /// does not replace or derive from `url`: the field goes on reporting exactly what it
10099 /// reported before, and this says what that address *is*.
10100 ///
10101 /// An item GitHub gave no `url` for — a draft has none — reports no location at all
10102 /// rather than a third variant, which is the contract's "the source did not say". An
10103 /// issue this run created is not one of those: its address comes back from the
10104 /// creating mutation, so it is somewhere a reader can open from the moment it exists
10105 /// rather than from whenever the board read catches up.
10106 fn location(&self) -> Option<Location> {
10107 self.url.clone().map(Location::Url)
10108 }
10109
10110 /// The short handle this board's backend shows people for a task: the issue's number
10111 /// alone, as a decimal string.
10112 ///
10113 /// The number alone rather than `owner/repo#1043`, because that is the contract's
10114 /// value for this backend. A draft has no number and so no handle, which is the
10115 /// contract's *absent* rather than a handle of some other shape — and the native
10116 /// [`Task::id`] here is the issue's GraphQL node id, which this neither replaces nor
10117 /// derives from.
10118 fn key(&self) -> Option<String> {
10119 self.number.map(|number| number.to_string())
10120 }
10121
10122 /// This item's change token — see [`change_token`] — or `None` when the read that
10123 /// reached it did not carry all six of its parts, which a draft never does, did not say
10124 /// when GitHub served it, or found it changed too recently to have settled.
10125 fn version(&self) -> Option<String> {
10126 match self.content_kind {
10127 ContentKind::Issue => {
10128 let (issue, item) = (self.updated_at?, self.item_updated_at?);
10129 let parts = change_token::Parts {
10130 issue,
10131 item,
10132 comments: self.comment_count?,
10133 relationships: self.relationship_events?,
10134 facets: self.facets.clone()?,
10135 repository: self.own_repository.clone()?,
10136 };
10137 change_token::settled(issue, item, self.served_at?)
10138 .then(|| change_token::spell(&parts))
10139 }
10140 ContentKind::DraftIssue => None,
10141 }
10142 }
10143
10144 /// Whether its `Priority` field holds a value at all, mapped or not.
10145 fn holds_priority(&self) -> bool {
10146 self.priority != HeldPriority::Read(Priority::None)
10147 }
10148
10149 /// The task this item is.
10150 ///
10151 /// Fails for an item whose `Priority` field holds an option the mapping does not name:
10152 /// reading that as a level would be a guess, and reading it as `none` would let the next
10153 /// copy clear a priority a person set.
10154 fn task(&self) -> Result<Task, SourceError> {
10155 let priority = match &self.priority {
10156 HeldPriority::Read(priority) => *priority,
10157 HeldPriority::Unmapped(option) => {
10158 return Err(SourceError::Malformed {
10159 message: format!(
10160 "task {}{} sits in the board {PRIORITY_FIELD} option {option:?}, which \
10161 this source's priority_mapping does not name, so its priority cannot be \
10162 read; next: name {option:?} under priority_mapping, or move the item to \
10163 a mapped option",
10164 self.id,
10165 self.number
10166 .map(|number| format!(" (#{number})"))
10167 .unwrap_or_default()
10168 ),
10169 });
10170 }
10171 };
10172 Ok(Task {
10173 version: self.version(),
10174 id: self.id.clone(),
10175 key: self.key(),
10176 title: self.title.clone(),
10177 content: self.body.clone(),
10178 status: self.status.clone(),
10179 priority,
10180 labels: self.labels.clone(),
10181 project: self.parent.clone(),
10182 url: self.url.clone(),
10183 location: self.location(),
10184 created_at: self.created_at,
10185 updated_at: self.updated_at,
10186 metadata: self.metadata(),
10187 repositories: self.repositories.clone(),
10188 delivers: self.delivers.clone(),
10189 delivered_by: self.delivered_by.clone(),
10190 classification: self.classification,
10191 })
10192 }
10193
10194 fn project(&self) -> Project {
10195 Project {
10196 version: self.version(),
10197 id: self.id.clone(),
10198 title: self.title.clone(),
10199 content: self.body.clone(),
10200 status: self.status.clone(),
10201 labels: self.labels.clone(),
10202 url: self.url.clone(),
10203 location: self.location(),
10204 created_at: self.created_at,
10205 updated_at: self.updated_at,
10206 metadata: self.metadata(),
10207 repositories: self.repositories.clone(),
10208 classification: self.classification,
10209 }
10210 }
10211
10212 /// The same issue as a document: the project it is filed under, and no status and no
10213 /// dependencies, because a document is not work.
10214 fn document(&self) -> Document {
10215 Document {
10216 version: self.version(),
10217 id: self.id.clone(),
10218 title: self.title.clone(),
10219 content: self.body.clone(),
10220 project: self.parent.clone(),
10221 labels: self.labels.clone(),
10222 url: self.url.clone(),
10223 location: self.location(),
10224 created_at: self.created_at,
10225 updated_at: self.updated_at,
10226 metadata: self.metadata(),
10227 repositories: self.repositories.clone(),
10228 classification: self.classification,
10229 }
10230 }
10231}
10232
10233/// Where one targeted update moves an item's status, and which of its two halves move.
10234struct StatusMove {
10235 /// The board the item's `Status` field is on.
10236 board: BoardId,
10237 /// The `Status` field's id.
10238 field: String,
10239 /// The option's id.
10240 option: String,
10241 /// The option's name, as the board spells it.
10242 name: String,
10243 /// What the status asks of the issue's state.
10244 target: StatusTarget,
10245 /// The status the item reads as once it is there.
10246 landed: Status,
10247 /// Which of the status's two halves differ from what the item holds.
10248 moves: Moves,
10249}
10250
10251/// Which halves of an item's status one targeted update moves: its `Status` option, the open or
10252/// closed state of its issue, or both. A status neither half of which differs is no move at all,
10253/// and is not a value of this type.
10254#[derive(Clone, Copy, PartialEq, Eq)]
10255enum Moves {
10256 /// The option alone.
10257 Option,
10258 /// The issue's state alone: open, closed, or closed with another reason.
10259 State,
10260 /// Both.
10261 Both,
10262}
10263
10264impl Moves {
10265 /// What differs, or `None` when nothing does.
10266 const fn of(option: bool, state: bool) -> Option<Self> {
10267 match (option, state) {
10268 (true, true) => Some(Self::Both),
10269 (true, false) => Some(Self::Option),
10270 (false, true) => Some(Self::State),
10271 (false, false) => None,
10272 }
10273 }
10274
10275 /// Whether the option moves.
10276 const fn option(self) -> bool {
10277 matches!(self, Self::Option | Self::Both)
10278 }
10279
10280 /// Whether the issue's state moves.
10281 const fn state(self) -> bool {
10282 matches!(self, Self::State | Self::Both)
10283 }
10284}
10285
10286/// What one write is, and the status that comes with being it.
10287///
10288/// One value rather than a [`BoardKind`] beside an `Option<Status>`: a document has no
10289/// status and a task or a project always has one, so "a document carrying a status" and
10290/// "a task carrying none" are states a write cannot be in rather than states every use
10291/// site below has to defend against.
10292enum Written<'a> {
10293 /// A document, which is not work and so has no status at all.
10294 Document,
10295 /// A task or a project, and the status it is being written with.
10296 Work(ItemKind, &'a Status),
10297}
10298
10299impl Written<'_> {
10300 /// Which of the board's three kinds this write is.
10301 const fn kind(&self) -> BoardKind {
10302 match self {
10303 Self::Document => BoardKind::Document,
10304 Self::Work(kind, _) => BoardKind::Work(*kind),
10305 }
10306 }
10307
10308 /// The status this write carries. A document carries none, so a write of one says
10309 /// nothing about the issue's open or closed state and selects no board `Status`
10310 /// option.
10311 const fn status(&self) -> Option<&Status> {
10312 match self {
10313 Self::Document => None,
10314 Self::Work(_, status) => Some(status),
10315 }
10316 }
10317
10318 /// The status this write carries with the kind whose half of `status_mapping` it is
10319 /// written through.
10320 const fn work_status(&self) -> Option<(ItemKind, &Status)> {
10321 match self {
10322 Self::Document => None,
10323 Self::Work(kind, status) => Some((*kind, status)),
10324 }
10325 }
10326}
10327
10328/// The item being written, in the one shape all three write methods reach.
10329struct Incoming<'a> {
10330 written: Written<'a>,
10331 /// The title a person wrote. A document's goes onto the issue with
10332 /// [`DESIGN_TITLE_PREFIX`] put back, so a round trip returns the title that went in.
10333 title: &'a str,
10334 content: Option<&'a str>,
10335 assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
10336 labels: &'a [Label],
10337 metadata: &'a BTreeMap<String, Value>,
10338 repositories: &'a [Repository],
10339 /// Recorded in the slot while private, and nowhere while public.
10340 classification: Classification,
10341 parent: Option<&'a NativeId>,
10342 /// [`Task::delivers`], already checked. Empty for a project or a document, which is
10343 /// what keeps either key out of their slot.
10344 delivers: &'a [TaskRef],
10345 /// [`Task::delivered_by`], already checked. Empty for a project or a document.
10346 delivered_by: &'a [TaskRef],
10347 /// [`Task::priority`], for a task written to an instance that holds one; `None` for a
10348 /// project, a document, and every write to an instance with no `priority_mapping` —
10349 /// which is what keeps such a write's requests exactly what they were before.
10350 priority: Option<Priority>,
10351}
10352
10353/// What one write does to one projected metadata text field, by the field's id.
10354#[derive(Debug, Clone)]
10355enum ProjectionWrite {
10356 /// Write this text.
10357 Set {
10358 field: String, // llmlint: ignore[invalid_states_unrepresentable] A private opaque GraphQL field id passed straight back to GitHub, as `PriorityWrite`'s are; GitHub publishes no grammar for it.
10359 text: String,
10360 },
10361 /// Clear the field's value.
10362 Clear { field: String }, // llmlint: ignore[invalid_states_unrepresentable] As above.
10363}
10364
10365impl ProjectionWrite {
10366 /// Add this write to a field write's list of values and list of clears.
10367 fn join<'a>(&'a self, values: &mut Vec<(String, Value)>, clears: &mut Vec<&'a str>) {
10368 match self {
10369 Self::Set { field, text } => values.push((field.clone(), json!({"text": text}))),
10370 Self::Clear { field } => clears.push(field),
10371 }
10372 }
10373}
10374
10375/// What one write does to an item's `Priority` field.
10376enum PriorityWrite {
10377 /// Select this option of this field.
10378 Select {
10379 /// The `Priority` field's id.
10380 field: String,
10381 /// The mapped option's id.
10382 option: String,
10383 },
10384 /// Clear the field's value, which is what `none` is.
10385 Clear {
10386 /// The `Priority` field's id.
10387 field: String,
10388 },
10389}
10390
10391impl Incoming<'_> {
10392 /// The title this write puts on the issue.
10393 fn written_title(&self) -> String {
10394 match self.written {
10395 Written::Document => format!("{DESIGN_TITLE_PREFIX}{}", self.title),
10396 Written::Work(..) => self.title.to_owned(),
10397 }
10398 }
10399}
10400
10401#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
10402enum ContentKind {
10403 DraftIssue,
10404 Issue,
10405}
10406
10407/// What one board issue is: a document, or the work an [`ItemKind`] names.
10408///
10409/// A type of this source's own rather than an `ItemKind` with a third variant, because
10410/// `ItemKind` names what a dependency endpoint points at and nothing may point at a
10411/// document — the contract keeps a document out of that enum deliberately. Holding the
10412/// board's three answers in one value is what makes every place that asks "which is this?"
10413/// answer all three, rather than a `document: bool` beside a `kind` that means nothing for
10414/// two thirds of the board.
10415#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
10416enum BoardKind {
10417 /// An issue whose title begins [`DESIGN_TITLE_PREFIX`].
10418 Document,
10419 /// Every other issue, and every draft.
10420 Work(ItemKind),
10421}
10422
10423impl BoardKind {
10424 /// The kind of an item titled `title`, filed under a project or not, holding `sub_issues`
10425 /// sub-issues and carrying the kind marker `marked` in its slot.
10426 ///
10427 /// The design prefix is read *first*, before either of the two rules that separate a
10428 /// project from a task. A document is not work whatever sub-issues it has and whatever
10429 /// marker it carries, and reading the prefix later would make a design issue with none of
10430 /// either an empty project. Being a sub-issue wins outright over the rest, and no marker
10431 /// overrides it: an issue filed under a project is that project's task even when it has
10432 /// sub-issues of its own.
10433 fn of(title: &str, filed: bool, sub_issues: u64, marked: Option<ItemKind>) -> Self {
10434 if title.starts_with(DESIGN_TITLE_PREFIX) {
10435 Self::Document
10436 } else if filed {
10437 Self::Work(ItemKind::Task)
10438 } else if sub_issues > 0 || marked == Some(ItemKind::Project) {
10439 Self::Work(ItemKind::Project)
10440 } else {
10441 Self::Work(ItemKind::Task)
10442 }
10443 }
10444
10445 /// What the change token's facets call this kind.
10446 const fn facet(self) -> change_token::FacetKind {
10447 match self {
10448 Self::Document => change_token::FacetKind::Document,
10449 Self::Work(ItemKind::Project) => change_token::FacetKind::Project,
10450 Self::Work(ItemKind::Task) => change_token::FacetKind::Task,
10451 }
10452 }
10453
10454 /// Whose half of `status_mapping` an item of this kind reads its status through. A
10455 /// document has no status of its own, so the task half stands in for whatever the issue
10456 /// holds; nothing reports it.
10457 const fn status_kind(self) -> ItemKind {
10458 match self {
10459 Self::Document => ItemKind::Task,
10460 Self::Work(kind) => kind,
10461 }
10462 }
10463
10464 /// How a refusal names this kind to the person reading it.
10465 const fn describes(self) -> &'static str {
10466 match self {
10467 Self::Document => "document",
10468 Self::Work(kind) => kind.marker(),
10469 }
10470 }
10471}
10472
10473/// Whether `labels` satisfies `filter`, matching by name, case-insensitively.
10474///
10475/// This is the local Markdown source's `labels_match`, spelled the same way on purpose:
10476/// the shared cross-source journeys assert one answer to one question, so two sources
10477/// that disagree about what "carries the label bug" means fail them.
10478fn labels_match(labels: &[Label], filter: &LabelFilter) -> bool {
10479 let holds = |name: &String| {
10480 labels
10481 .iter()
10482 .any(|label| label.name.eq_ignore_ascii_case(name))
10483 };
10484 (filter.any_of.is_empty() || filter.any_of.iter().any(holds))
10485 && filter.all_of.iter().all(holds)
10486 && !filter.none_of.iter().any(holds)
10487}
10488
10489/// Whether `category` is one of `statuses`. An empty list is unfiltered rather than
10490/// "keeps nothing", which is what lets a `Vec<StatusCategory>` spell no filter at all.
10491fn status_matches(category: StatusCategory, statuses: &[StatusCategory]) -> bool {
10492 statuses.is_empty() || statuses.contains(&category)
10493}
10494
10495/// Whether `title`/`content` satisfies `query`, matching case-insensitively.
10496///
10497/// `content` is the item's own prose — the body with this source's trailing metadata
10498/// comment already taken off — so a search never matches an encoding the author of the
10499/// issue never wrote.
10500fn text_matches(title: &str, content: Option<&str>, query: &TextQuery) -> bool {
10501 let terms = query.terms.to_lowercase();
10502 let in_title = title.to_lowercase().contains(&terms);
10503 let in_content = content.is_some_and(|body| body.to_lowercase().contains(&terms));
10504 match query.fields {
10505 TextFields::Title => in_title,
10506 TextFields::Content => in_content,
10507 TextFields::TitleOrContent => in_title || in_content,
10508 }
10509}
10510
10511/// Whether `task` satisfies `query`, with `project` deciding the project predicate.
10512///
10513/// The project predicate is passed separately because a read narrowed to one project has
10514/// already answered it by asking *that project* for its own items — and re-applying it
10515/// there would compare the caller's selector, which may be a project's **name**, against
10516/// the id of the project that name resolved to, and keep nothing. Every other read passes
10517/// `query.project` and applies it here, which is what keeps `projects` a predicate this
10518/// source really does apply.
10519fn task_matches(task: &Task, query: &TaskQuery, project: &ProjectFilter) -> bool {
10520 labels_match(&task.labels, &query.labels)
10521 && status_matches(task.status.category, &query.statuses)
10522 && (query.priorities.is_empty() || query.priorities.contains(&task.priority))
10523 && match project {
10524 ProjectFilter::Any => true,
10525 ProjectFilter::Orphans => task.project.is_none(),
10526 ProjectFilter::Is(id) => task.project.as_ref() == Some(id),
10527 }
10528 && query
10529 .text
10530 .as_ref()
10531 .is_none_or(|text| text_matches(&task.title, task.content.as_deref(), text))
10532 // Against the parsed metadata slot, and against the origin field, which is where
10533 // `Resolved::metadata` reads each of them from.
10534 && query.metadata_matches(&task.metadata)
10535 && query.origin_matches(&task.metadata)
10536}
10537
10538fn project_matches(project: &Project, query: &ProjectQuery) -> bool {
10539 labels_match(&project.labels, &query.labels)
10540 && status_matches(project.status.category, &query.statuses)
10541 && query
10542 .text
10543 .as_ref()
10544 .is_none_or(|text| text_matches(&project.title, project.content.as_deref(), text))
10545}
10546
10547/// The same three predicates a task query carries, minus the status filter.
10548///
10549/// A document is not work, so it has no status for one to compare against and the query
10550/// type carries none. The project predicate is the same one — a design issue filed under a
10551/// project issue is in that project, and one filed under nothing is in none — so it is
10552/// spelled the same way here rather than answered differently.
10553fn document_matches(document: &Document, query: &DocumentQuery, project: &ProjectFilter) -> bool {
10554 labels_match(&document.labels, &query.labels)
10555 && match project {
10556 ProjectFilter::Any => true,
10557 ProjectFilter::Orphans => document.project.is_none(),
10558 ProjectFilter::Is(id) => document.project.as_ref() == Some(id),
10559 }
10560 && query
10561 .text
10562 .as_ref()
10563 .is_none_or(|text| text_matches(&document.title, document.content.as_deref(), text))
10564}
10565
10566/// Why a GitHub item's change token does not vouch for its forward edges.
10567///
10568/// A forward edge names its far end and that far end's kind, and the near item's token moves
10569/// with the edges it holds but says nothing of the far ends themselves: a far end turning from a
10570/// task into a project when it gains a sub-issue, retitled into a document, or deleted moves
10571/// nothing the near token reads, so an edge kept at the near version could name a far end that
10572/// is no longer what it said.
10573const FAR_ENDS_UNCOVERED: &str = "a github item's change token does not attest a far end's kind, \
10574 whether it became a document, or its deletion, so its forward edges are always read from \
10575 github";
10576
10577/// The issue-search qualifier that keeps open issues alone, which a status filter naming only
10578/// categories an open issue reads as narrows a board-scoped search with.
10579const OPEN_QUALIFIER: &str = "is:open";
10580
10581/// The board filter `task status reconcile` reads the board through: closed items alone.
10582const CLOSED_FILTER: &str = "is:closed";
10583
10584/// The variables of one [`graphql::ISSUES_BY_REFERENCE`] request for `batch`: each slot names
10585/// one reference, and a slot the batch has none for names its last one again.
10586fn reference_batch(batch: &[IssueRef]) -> Value {
10587 let mut variables = serde_json::Map::new();
10588 for slot in 0..REFERENCE_BATCH {
10589 let issue = batch.get(slot).or(batch.last());
10590 variables.insert(format!("owner{slot}"), json!(issue.map(|i| &i.owner)));
10591 variables.insert(format!("name{slot}"), json!(issue.map(|i| &i.name)));
10592 variables.insert(format!("number{slot}"), json!(issue.map(|i| i.number)));
10593 }
10594 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
10595 variables.insert("statusField".to_owned(), json!(STATUS_FIELD));
10596 variables.insert("duplicates".to_owned(), json!(true));
10597 Value::Object(variables)
10598}
10599
10600/// One issue an issue read by reference answered, in the shape every other read of an issue
10601/// hands its resolver: each board membership's `Status` value, read by name, as the one field
10602/// value that membership carries.
10603///
10604/// A membership's `status` is `null` when its card sits at no option — or on a board with no
10605/// field of that name — and otherwise an option value naming its option; anything else is not
10606/// an answer to this read, and is refused rather than read as a card at no option.
10607fn held_issue(issue: &Value) -> Result<Value, SourceError> {
10608 let malformed = |what: &str| SourceError::Malformed {
10609 message: format!("GitHub answered an issue read by reference with {what}"),
10610 };
10611 let mut issue = issue.clone();
10612 let nodes = issue
10613 .pointer_mut("/projectItems/nodes")
10614 .and_then(Value::as_array_mut)
10615 .ok_or_else(|| malformed("no list of board memberships"))?;
10616 for node in nodes {
10617 let node = node
10618 .as_object_mut()
10619 .ok_or_else(|| malformed("a board membership that is not an object"))?;
10620 let status = match node.get("status") {
10621 None => return Err(malformed("a board membership with no status member")),
10622 Some(Value::Null) => None,
10623 Some(status) if status.get("name").is_some_and(Value::is_string) => {
10624 Some(status.clone())
10625 }
10626 // A single-select value of another field type answers `{}`; only an option value
10627 // carries a name.
10628 Some(status) if status.as_object().is_some_and(serde_json::Map::is_empty) => None,
10629 Some(_) => return Err(malformed("a membership status that names no option")),
10630 };
10631 node.insert(
10632 "fieldValues".to_owned(),
10633 json!({"nodes": status.into_iter().collect::<Vec<_>>(),
10634 "pageInfo": {"hasNextPage": false}}),
10635 );
10636 }
10637 Ok(issue)
10638}
10639
10640/// The issue one slot of a read by reference answered, `None` when GitHub answered that
10641/// slot's repository or issue `null` — which [`GitHubProjectsSource::answer_unresolved`]
10642/// admitted only beside a `NOT_FOUND` naming that very slot — and a refusal when the answer
10643/// leaves the slot, or its `issue` member, out: an answer missing a member is malformed rather
10644/// than a reference nothing holds.
10645fn referenced_issue(data: &Value, slot: usize) -> Result<Option<&Value>, SourceError> {
10646 let alias = format!("r{slot}");
10647 let repository = data.get(&alias).ok_or_else(|| SourceError::Malformed {
10648 message: format!("GitHub answered a read by reference with no {alias}"),
10649 })?;
10650 if repository.is_null() {
10651 return Ok(None);
10652 }
10653 let issue = repository
10654 .get("issue")
10655 .ok_or_else(|| SourceError::Malformed {
10656 message: format!("GitHub answered {alias} of a read by reference with no issue"),
10657 })?;
10658 if issue.is_null() {
10659 return Ok(None);
10660 }
10661 // `Repository.issue` is typed `Issue`, so anything else is not an answer to this read.
10662 if optional_str(issue, "__typename")? != Some("Issue") {
10663 return Err(SourceError::Malformed {
10664 message: format!(
10665 "GitHub answered {alias} of a read by reference with an issue whose __typename \
10666 is not Issue"
10667 ),
10668 });
10669 }
10670 Ok(Some(issue))
10671}
10672
10673/// A closure reason as a person reads it: `NOT_PLANNED` as `not planned`.
10674fn spoken_reason(reason: &str) -> String {
10675 reason.to_ascii_lowercase().replace('_', " ")
10676}
10677
10678impl GitHubProjectsSource {
10679 /// Every task of this board whose card contradicts its issue's closure, read through the
10680 /// board's own `is:closed` filter, page by page — never the board's unfiltered `items`.
10681 ///
10682 /// Each item the filter answers is confirmed from its own node: an open one, one whose
10683 /// closure reads `unknown`, and one whose card is already in line are left out whatever
10684 /// the filter let through. The board's fields ride along and are held for the option
10685 /// writes that follow, so those need no read of the board.
10686 async fn contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
10687 let mut after: Option<String> = None;
10688 let mut found = Vec::new();
10689 loop {
10690 let data = self
10691 .graphql(
10692 graphql::CLOSED_ITEMS,
10693 json!({"owner":self.owner,"number":self.project_number,
10694 "first":MAX_PAGE_SIZE,"after":after,"filter":CLOSED_FILTER,
10695 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
10696 )
10697 .await?;
10698 let board = data
10699 .pointer("/closedItems/projectV2")
10700 .filter(|value| !value.is_null())
10701 .ok_or_else(|| SourceError::Refused {
10702 message: format!(
10703 "GitHub project {}/{} was not found or is not visible to the token",
10704 self.owner, self.project_number
10705 ),
10706 })?;
10707 *self.fields_cache()? = Some(BoardFields {
10708 id: BoardId::parse(required_str(board, "id")?)?,
10709 fields: board.get("fields").cloned().unwrap_or(Value::Null),
10710 });
10711 let items = board.get("items").ok_or_else(|| SourceError::Malformed {
10712 message: "GitHub project closed items are missing".into(),
10713 })?;
10714 for item in items
10715 .get("nodes")
10716 .and_then(Value::as_array)
10717 .ok_or_else(|| SourceError::Malformed {
10718 message: "GitHub project items.nodes is not an array".into(),
10719 })?
10720 {
10721 let Some(resolved) = self.resolve(item)? else {
10722 continue;
10723 };
10724 if resolved.kind != BoardKind::Work(ItemKind::Task) {
10725 continue;
10726 }
10727 let Some((closed_as, name)) = self.statuses.contradicted(
10728 ItemKind::Task,
10729 resolved.option.as_deref(),
10730 resolved.closed,
10731 resolved.reason.as_deref(),
10732 ) else {
10733 continue;
10734 };
10735 found.push(StatusContradiction {
10736 closed_as,
10737 to: name.to_owned(),
10738 option: resolved.option.clone(),
10739 task: resolved.task()?,
10740 });
10741 }
10742 let info = items
10743 .get("pageInfo")
10744 .ok_or_else(|| SourceError::Malformed {
10745 message: "GitHub project items have no pageInfo".into(),
10746 })?;
10747 if !required_bool(info, "hasNextPage")? {
10748 return Ok(found);
10749 }
10750 let next = required_str(info, "endCursor")?;
10751 validate_cursor_progress(after.as_deref(), next)?;
10752 after = Some(next.to_owned());
10753 }
10754 }
10755
10756 /// What this board holds for each issue in `issues`, once each in the order given, read
10757 /// [`REFERENCE_BATCH`] references at a time — and nothing else of the board.
10758 ///
10759 /// An issue GitHub cannot find for this source's credential, and one with no item on this
10760 /// board, are both absent. A closure that already says the work will not be done here —
10761 /// not planned, duplicate — is skipped: a landing does not overrule it. A task closed as
10762 /// completed whose card sits at the `done` option is unchanged, and every other task is
10763 /// due a `done` write.
10764 async fn holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
10765 let mut distinct: Vec<IssueRef> = Vec::with_capacity(issues.len());
10766 for issue in issues {
10767 if !distinct.contains(issue) {
10768 distinct.push(issue.clone());
10769 }
10770 }
10771 let done = self
10772 .statuses
10773 .target(ItemKind::Task, StatusCategory::Done)
10774 .option()
10775 .unwrap_or("Done")
10776 .to_owned();
10777 // GitHub numbers an issue with a GraphQL `Int`, a signed 32-bit value, so a reference past
10778 // its range names no issue any repository can hold: it is answered absent and never sent,
10779 // where binding it would have GitHub refuse the whole batch.
10780 let readable: Vec<IssueRef> = distinct
10781 .iter()
10782 .filter(|issue| i32::try_from(issue.number).is_ok())
10783 .cloned()
10784 .collect();
10785 let mut holdings = Vec::with_capacity(readable.len());
10786 for batch in readable.chunks(REFERENCE_BATCH) {
10787 let data = self
10788 .graphql(graphql::ISSUES_BY_REFERENCE, reference_batch(batch))
10789 .await?;
10790 for (slot, issue) in batch.iter().enumerate() {
10791 let node = referenced_issue(&data, slot)?;
10792 let resolved = match node {
10793 Some(node) => self
10794 .resolve_issue_as(&held_issue(node)?, false)
10795 .await?
10796 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task)),
10797 None => None,
10798 };
10799 let Some(item) = resolved else {
10800 holdings.push(IssueHolding {
10801 issue: issue.clone(),
10802 completion: Completion::Absent,
10803 });
10804 continue;
10805 };
10806 let held = item.task()?;
10807 let task = HeldTask {
10808 id: held.id,
10809 option: item.option.clone(),
10810 classification: held.classification,
10811 repositories: held.repositories,
10812 delivers: held.delivers,
10813 };
10814 let completion = match (item.closed, item.reason.as_deref()) {
10815 (true, Some(reason @ ("NOT_PLANNED" | "DUPLICATE"))) => Completion::Skipped {
10816 task,
10817 reason: format!("closed as {}", spoken_reason(reason)),
10818 },
10819 (true, None | Some("COMPLETED"))
10820 if item
10821 .option
10822 .as_deref()
10823 .is_some_and(|option| option.eq_ignore_ascii_case(&done)) =>
10824 {
10825 Completion::Unchanged { task }
10826 }
10827 _ => {
10828 let kept = item.clone();
10829 self.held_cache
10830 .lock()
10831 .map_err(|_| SourceError::Unavailable {
10832 message: "items read by issue reference were left \
10833 inconsistent; run the command again"
10834 .into(),
10835 })?
10836 .insert(kept.id.clone(), kept);
10837 Completion::Due {
10838 task,
10839 to: done.clone(),
10840 }
10841 }
10842 };
10843 holdings.push(IssueHolding {
10844 issue: issue.clone(),
10845 completion,
10846 });
10847 }
10848 }
10849 let mut read = holdings.into_iter();
10850 let mut answered = Vec::with_capacity(distinct.len());
10851 for issue in distinct {
10852 if i32::try_from(issue.number).is_ok() {
10853 answered.push(read.next().ok_or_else(|| SourceError::Malformed {
10854 message: format!("no holding was read for {issue}"),
10855 })?);
10856 } else {
10857 answered.push(IssueHolding {
10858 issue,
10859 completion: Completion::Absent,
10860 });
10861 }
10862 }
10863 Ok(answered)
10864 }
10865}
10866
10867#[async_trait::async_trait]
10868impl TaskSource for GitHubProjectsSource {
10869 fn kind(&self) -> &'static str {
10870 KIND
10871 }
10872 fn order_versions(&self, a: &str, b: &str) -> Option<std::cmp::Ordering> {
10873 change_token::order(a, b)
10874 }
10875 /// A task's fields and comments: §4.13d of `docs/plugin-protocol.md` states, member by
10876 /// member, the change each part of the token moves for. Not its forward edges — see
10877 /// [`FAR_ENDS_UNCOVERED`].
10878 fn version_coverage(&self) -> VersionCoverage {
10879 VersionCoverage {
10880 forward_edges: Coverage::Uncovered {
10881 reason: FAR_ENDS_UNCOVERED.to_owned(),
10882 },
10883 ..VersionCoverage::whole()
10884 }
10885 }
10886 /// Every part, for a copy's skip: the relationship count moves for an edge added or removed
10887 /// and for a far end deleted, so the token sees every change to a task's edges but one — a
10888 /// far end's own kind flipping, by gaining a sub-issue or being retitled into a document,
10889 /// which `spike-coverage` measured stale 1 of 1. A skipping recopy does not carry that, and
10890 /// the next copy that reads the task does (`docs/plugin-protocol.md` §4.13d).
10891 // llmlint: ignore[names_match_behavior] The manager's ruling (c-d7838f2c) keeps 0.6.0's GitHub skip and has this plugin state that bounded claim through the coverage it reports, with the bound documented here, in §4.13d and by the copy_skip journey; a separate bounded representation would be a contract change beyond a defaulted addition, which the ruling reserves for the contract's owner, and a follow-up is drafted for a far-end-aware skip.
10892 fn copy_version_coverage(&self) -> VersionCoverage {
10893 VersionCoverage::whole()
10894 }
10895 /// A project's fields, and not its forward edges, for the same reason a task's are not.
10896 fn project_version_coverage(&self) -> ProjectVersionCoverage {
10897 ProjectVersionCoverage {
10898 fields: Coverage::Covered,
10899 forward_edges: Coverage::Uncovered {
10900 reason: FAR_ENDS_UNCOVERED.to_owned(),
10901 },
10902 }
10903 }
10904 /// A document's fields and the manifest of its image assets, which its metadata slot
10905 /// records: both are the issue's body, whose every edit moves the token's issue time.
10906 fn document_version_coverage(&self) -> DocumentVersionCoverage {
10907 DocumentVersionCoverage::whole()
10908 }
10909 fn write_context(&self, id: &NativeId) -> Option<Value> {
10910 self.context_of(id)
10911 }
10912 fn board_context(&self) -> Option<Value> {
10913 self.board_context_held()
10914 }
10915 fn prime_write(&self, id: &NativeId, context: &Value, board: Option<&Value>) -> bool {
10916 self.prime(id, context, board)
10917 }
10918 fn unprime(&self, id: &NativeId) {
10919 self.unprime_held(id);
10920 }
10921 fn begin_journal(&self) {
10922 self.expected.begin();
10923 }
10924 fn end_journal(&self) -> Option<WriteJournal> {
10925 Some(self.expected.end())
10926 }
10927 fn capabilities(&self) -> Capabilities {
10928 Capabilities {
10929 projects: Support::Native,
10930 documents: Support::Native,
10931 comments: Support::Native,
10932 assets: Support::Native,
10933 priority: if self.priorities.is_some() {
10934 Support::Native
10935 } else {
10936 Support::Unsupported
10937 },
10938 filter_by_priority: Support::Native,
10939 filter_by_comment_activity: Support::Native,
10940 filter_by_metadata: Support::Native,
10941 filter_by_origin: Support::Native,
10942 reconcile_status: Support::Native,
10943 complete_by_issue: Support::Native,
10944 orphan_tasks: Support::Native,
10945 filter_by_label: Support::Native,
10946 filter_by_status: Support::Native,
10947 search_title: Support::Native,
10948 search_content: Support::Native,
10949 task_dependencies: DependencySupport::BothDirections,
10950 project_dependencies: DependencySupport::BothDirections,
10951 max_page_size: MAX_PAGE_SIZE,
10952 }
10953 }
10954 async fn visibility(
10955 &self,
10956 target: &onetaskgraph_plugin_api::WriteTarget<'_>,
10957 ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
10958 self.write_visibility(target).await
10959 }
10960 async fn health(&self) -> Result<Health, SourceError> {
10961 let board = self.board_page(None, 1).await?;
10962 Ok(Health {
10963 reachable: true,
10964 detail: Some(format!(
10965 "reading GitHub project {}/{} ({})",
10966 self.owner,
10967 self.project_number,
10968 required_str(&board, "title")?
10969 )),
10970 })
10971 }
10972 async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
10973 self.item_by_id(id)
10974 .await?
10975 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
10976 .map(|item| item.task())
10977 .transpose()
10978 }
10979 async fn task_assets(
10980 &self,
10981 id: &NativeId,
10982 ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
10983 self.held_assets(id, BoardKind::Work(ItemKind::Task)).await
10984 }
10985 async fn task_asset(
10986 &self,
10987 id: &NativeId,
10988 name: &onetaskgraph_plugin_api::AssetName,
10989 ) -> Result<Option<Vec<u8>>, SourceError> {
10990 self.held_asset(id, BoardKind::Work(ItemKind::Task), name)
10991 .await
10992 }
10993 async fn set_task_rendering_with_assets(
10994 &self,
10995 id: &NativeId,
10996 content: &str,
10997 provenance: &Value,
10998 _answers: &BTreeMap<String, Value>,
10999 assets: &onetaskgraph_plugin_api::AssetWrite,
11000 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
11001 self.replace_rendering(
11002 id,
11003 BoardKind::Work(ItemKind::Task),
11004 content,
11005 provenance,
11006 Some(assets),
11007 )
11008 .await
11009 }
11010 async fn document_assets(
11011 &self,
11012 id: &NativeId,
11013 ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
11014 self.held_assets(id, BoardKind::Document).await
11015 }
11016 async fn document_asset(
11017 &self,
11018 id: &NativeId,
11019 name: &onetaskgraph_plugin_api::AssetName,
11020 ) -> Result<Option<Vec<u8>>, SourceError> {
11021 self.held_asset(id, BoardKind::Document, name).await
11022 }
11023 async fn set_document_rendering_with_assets(
11024 &self,
11025 id: &NativeId,
11026 content: &str,
11027 provenance: &Value,
11028 _answers: &BTreeMap<String, Value>,
11029 assets: &onetaskgraph_plugin_api::AssetWrite,
11030 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
11031 self.replace_rendering(id, BoardKind::Document, content, provenance, Some(assets))
11032 .await
11033 }
11034 async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
11035 Ok(self
11036 .item_by_id(id)
11037 .await?
11038 .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
11039 .map(|item| item.project()))
11040 }
11041 async fn query_tasks(
11042 &self,
11043 query: &TaskQuery,
11044 page: &PageRequest,
11045 ) -> Result<Page<Task>, SourceError> {
11046 validate_page(page)?;
11047 refuse_unsearchable(query)?;
11048 // A closed issue reads `done`, `cancelled` or — closed for a reason that implies no
11049 // category — `unknown`; every other category reads only off an open issue or a draft. So
11050 // a status filter naming none of those three asks every issue search it sends for open
11051 // issues alone; each candidate's category is still confirmed from its own item below.
11052 let open_only = !query.statuses.is_empty()
11053 && query.statuses.iter().all(|category| {
11054 !matches!(
11055 category,
11056 StatusCategory::Done | StatusCategory::Cancelled | StatusCategory::Unknown
11057 )
11058 });
11059 if query.origin.is_none() && !matches!(query.project, ProjectFilter::Is(_)) {
11060 let mut qualifiers: Vec<String> = [
11061 query.commented_since.map(updated_qualifier),
11062 narrowing_qualifiers(query),
11063 ]
11064 .into_iter()
11065 .flatten()
11066 .collect();
11067 // A narrowed search never answers a draft, which is no issue, so narrowing it to
11068 // open issues too leaves out nothing such a search could have answered.
11069 if !qualifiers.is_empty() {
11070 if open_only {
11071 qualifiers.push(OPEN_QUALIFIER.to_owned());
11072 }
11073 return self.search_tasks(query, page, &qualifiers.join(" ")).await;
11074 }
11075 }
11076
11077 // A read narrowed to one project asks that project for its own tasks, so nothing
11078 // about it costs what the rest of the board holds. A read carrying a text, metadata
11079 // or origin predicate asks GitHub the narrower question those predicates are, and a
11080 // read narrowed to comment activity alone asks the board's own issue search for the
11081 // issues updated since, which is every issue a comment could have been written or
11082 // edited on since. Every other task read is a question about the whole board and is
11083 // answered by reading it.
11084 let (held, membership) = match (&query.project, query.commented_since) {
11085 (ProjectFilter::Is(project), _) => (
11086 self.project_children(project).await?,
11087 // Answered by where these items came from; see `task_matches`.
11088 &ProjectFilter::Any,
11089 ),
11090 (ProjectFilter::Any | ProjectFilter::Orphans, since) => {
11091 match (self.narrowed(query).await?, since) {
11092 (Some(narrowed), _) => (narrowed, &query.project),
11093 (None, Some(since)) => (self.updated_since(since).await?, &query.project),
11094 // The board's own items list every draft; only the search half, which
11095 // completes them with issues they lag behind on, is narrowed — a closed
11096 // issue that half leaves out is at no category the filter keeps.
11097 (None, None) if open_only => (
11098 self.board_completed_by(Some(OPEN_QUALIFIER)).await?.items,
11099 &query.project,
11100 ),
11101 (None, None) => (self.board().await?.items, &query.project),
11102 }
11103 }
11104 };
11105 // Filtered before paged: a page of a filtered result is a page of the survivors,
11106 // never the survivors of a page.
11107 let mut tasks = Vec::new();
11108 for item in held
11109 .iter()
11110 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
11111 {
11112 let task = item.task()?;
11113 if task_matches(&task, query, membership)
11114 && self.commented_since(item, query.commented_since).await?
11115 {
11116 tasks.push(task);
11117 }
11118 }
11119 Ok(offset_page(
11120 tasks,
11121 numeric_cursor(page.cursor.as_ref())?,
11122 page.limit.min(MAX_PAGE_SIZE) as usize,
11123 ))
11124 }
11125 async fn query_projects(
11126 &self,
11127 query: &ProjectQuery,
11128 page: &PageRequest,
11129 ) -> Result<Page<Project>, SourceError> {
11130 validate_page(page)?;
11131 refuse_unsearchable_text(query.text.as_ref())?;
11132 // The projects a board holds are found by an issue search scoped to that board,
11133 // never by walking the board's own item connection: what tells a project from a
11134 // task is the `parent` each issue carries, which costs nothing to read. A query
11135 // carrying a text asks that search for the text too, so it reads the issues that
11136 // hold it rather than every issue of the board.
11137 let held = match self.text_searched(query.text.as_ref()).await? {
11138 Some(searched) => searched,
11139 None => self.board_issues().await?,
11140 };
11141 let projects = held
11142 .iter()
11143 .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
11144 .map(Resolved::project)
11145 .filter(|project| project_matches(project, query))
11146 .collect();
11147 Ok(offset_page(
11148 projects,
11149 numeric_cursor(page.cursor.as_ref())?,
11150 page.limit.min(MAX_PAGE_SIZE) as usize,
11151 ))
11152 }
11153 async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
11154 Ok(self
11155 .item_by_id(id)
11156 .await?
11157 .filter(|item| item.kind == BoardKind::Document)
11158 .map(|item| item.document()))
11159 }
11160 async fn query_documents(
11161 &self,
11162 query: &DocumentQuery,
11163 page: &PageRequest,
11164 ) -> Result<Page<Document>, SourceError> {
11165 validate_page(page)?;
11166 // Narrowed to one project, this is the same sub-issue read a task list scoped to
11167 // that project makes — a document filed under a project is a sub-issue of it too,
11168 // and which of them come back is the kind this caller asked for. Unscoped, a query
11169 // carrying a text asks the board-scoped issue search for it, as a task query does,
11170 // and only one carrying none reads the board.
11171 let (held, membership) = match &query.project {
11172 ProjectFilter::Is(project) => (
11173 self.project_children(project).await?,
11174 // Answered by where these items came from; see `task_matches`.
11175 &ProjectFilter::Any,
11176 ),
11177 ProjectFilter::Any | ProjectFilter::Orphans => {
11178 refuse_unsearchable_text(query.text.as_ref())?;
11179 match self.text_searched(query.text.as_ref()).await? {
11180 Some(searched) => (searched, &query.project),
11181 None => (self.board().await?.items, &query.project),
11182 }
11183 }
11184 };
11185 // Filtered before paged, exactly as a task read is: a page of a filtered result is
11186 // a page of the survivors, never the survivors of a page.
11187 let documents = held
11188 .iter()
11189 .filter(|item| item.kind == BoardKind::Document)
11190 .map(Resolved::document)
11191 .filter(|document| document_matches(document, query, membership))
11192 .collect();
11193 Ok(offset_page(
11194 documents,
11195 numeric_cursor(page.cursor.as_ref())?,
11196 page.limit.min(MAX_PAGE_SIZE) as usize,
11197 ))
11198 }
11199 async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
11200 validate_page(page)?;
11201 let offset = numeric_cursor(page.cursor.as_ref())?;
11202 let mut labels = self
11203 .board()
11204 .await?
11205 .items
11206 .into_iter()
11207 .flat_map(|item| item.labels)
11208 .fold(Vec::new(), |mut all, label| {
11209 if !all.iter().any(|x: &Label| x.id == label.id) {
11210 all.push(label);
11211 }
11212 all
11213 });
11214 labels.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.0.cmp(&b.id.0)));
11215 Ok(offset_page(
11216 labels,
11217 offset,
11218 page.limit.min(MAX_PAGE_SIZE) as usize,
11219 ))
11220 }
11221 async fn task_dependencies(
11222 &self,
11223 id: &NativeId,
11224 direction: Direction,
11225 page: &PageRequest,
11226 ) -> Result<Page<DependencyEdge>, SourceError> {
11227 self.dependencies(id, ItemKind::Task, direction, page).await
11228 }
11229 async fn project_dependencies(
11230 &self,
11231 id: &NativeId,
11232 direction: Direction,
11233 page: &PageRequest,
11234 ) -> Result<Page<DependencyEdge>, SourceError> {
11235 self.dependencies(id, ItemKind::Project, direction, page)
11236 .await
11237 }
11238
11239 fn writes(&self) -> WriteSupport {
11240 WriteSupport::Supported
11241 }
11242
11243 /// Create or update one task.
11244 ///
11245 /// Its `delivers` and `delivered_by` are checked before anything is read or written —
11246 /// neither may name the task itself or name one task twice — and land in the body's
11247 /// metadata slot under their reserved keys, in place of any caller metadata of those
11248 /// names.
11249 async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
11250 self.write_task_assets(write, None)
11251 .await
11252 .map(|written| written.id)
11253 }
11254
11255 async fn write_task_with_assets(
11256 &self,
11257 write: &ItemWrite<Task>,
11258 _answers: Option<&BTreeMap<String, Value>>,
11259 assets: &onetaskgraph_plugin_api::AssetWrite,
11260 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11261 self.write_task_assets(write, Some(assets)).await
11262 }
11263
11264 async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
11265 self.write_item(
11266 &Incoming {
11267 written: Written::Work(ItemKind::Project, &write.item.status),
11268 title: &write.item.title,
11269 content: write.item.content.as_deref(),
11270 assets: None,
11271 labels: &write.item.labels,
11272 metadata: &write.item.metadata,
11273 repositories: &write.item.repositories,
11274 classification: write.item.classification,
11275 parent: None,
11276 delivers: &[],
11277 delivered_by: &[],
11278 priority: None,
11279 },
11280 write.target.as_ref(),
11281 &write.depends_on,
11282 )
11283 .await
11284 .map(|written| written.id)
11285 }
11286
11287 /// Create or update one document, which is one issue titled the way this board spells
11288 /// a document.
11289 ///
11290 /// Everything else is exactly a task write: caller metadata goes to the same canonical
11291 /// JSON slot at the end of the body and comes back with its JSON types intact, a key
11292 /// or a field this board cannot carry is refused by name rather than dropped, a target
11293 /// naming an issue this board does not hold is refused rather than created, and an
11294 /// issue this call created is taken back when the rest of the write fails.
11295 async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
11296 self.write_document_assets(write, None)
11297 .await
11298 .map(|written| written.id)
11299 }
11300
11301 async fn write_document_with_assets(
11302 &self,
11303 write: &ItemWrite<Document>,
11304 _answers: Option<&BTreeMap<String, Value>>,
11305 assets: &onetaskgraph_plugin_api::AssetWrite,
11306 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11307 self.write_document_assets(write, Some(assets)).await
11308 }
11309
11310 /// Refused exactly as the write refuses it, from what the write reads: the mapping first,
11311 /// which reads nothing; then the board's `Status` option. Over an existing item that is
11312 /// read off the item, as the write reads it, and the item is held among this command's
11313 /// resolved records so the write that follows reuses that read rather than repeating it;
11314 /// an item that does not carry the field takes the board's fields, which are held once
11315 /// read. A create is checked against the board's fields only when this command already
11316 /// holds them, because a create reads them together with its repository, in one request,
11317 /// and refuses a missing option before it writes anything.
11318 async fn check_status_write(
11319 &self,
11320 kind: ItemKind,
11321 category: StatusCategory,
11322 target: Option<&NativeId>,
11323 ) -> Result<(), SourceError> {
11324 let status = self.resolved_target(kind, category)?;
11325 if status.option().is_none() {
11326 return Ok(());
11327 }
11328 let fields = match target {
11329 Some(target) => {
11330 // A target this board does not hold is the write's own refusal to make.
11331 let Some(item) = self.bound_item(target).await? else {
11332 return Ok(());
11333 };
11334 self.resolved_cache()?.insert(target.clone(), item.clone());
11335 self.fields_for(Some(&item), true, false).await?.fields
11336 }
11337 None => {
11338 let held = self
11339 .board_cache()?
11340 .as_ref()
11341 .map(|board| board.fields.clone());
11342 match held.or_else(|| {
11343 self.fields_cache()
11344 .ok()
11345 .and_then(|cache| cache.as_ref().map(|board| board.fields.clone()))
11346 }) {
11347 Some(fields) => fields,
11348 None => return Ok(()),
11349 }
11350 }
11351 };
11352 self.column_for(&fields, kind, category, &status)
11353 .map(|_| ())
11354 }
11355
11356 /// Set one task's status alone.
11357 ///
11358 /// An open target reopens a closed issue with an `updateIssue` carrying only its
11359 /// `stateInput`, then selects the board option with `updateProjectV2ItemFieldValue`; a
11360 /// terminal target selects its mapped option, then closes with its fixed reason. No
11361 /// request carries a title, a body or a label. The status
11362 /// answered is what [`BoardStatuses::status`] reads off the state just written, which is
11363 /// what a re-read reports.
11364 async fn set_task_status(
11365 &self,
11366 id: &NativeId,
11367 category: StatusCategory,
11368 ) -> Result<Option<Status>, SourceError> {
11369 self.set_status(id, category).await
11370 }
11371
11372 /// Every task whose card contradicts its issue's closure, read through the board's own
11373 /// `is:closed` filter; see [`TaskSource::status_contradictions`].
11374 async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
11375 self.contradictions().await
11376 }
11377
11378 /// What this board holds for each issue reference, one request per fifty of them; see
11379 /// [`TaskSource::issue_holdings`].
11380 async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
11381 self.holdings(issues).await
11382 }
11383
11384 /// Set one task's priority alone: one `updateProjectV2ItemFieldValue` selecting the
11385 /// mapped option of the board's `Priority` field, or one `clearProjectV2ItemFieldValue`
11386 /// for `none`. Refused by an instance with no `priority_mapping`.
11387 async fn set_task_priority(
11388 &self,
11389 id: &NativeId,
11390 priority: Priority,
11391 ) -> Result<Option<Priority>, SourceError> {
11392 self.set_priority(id, priority).await
11393 }
11394
11395 /// Replace one task's content with a single body update that keeps the metadata slot
11396 /// byte for byte.
11397 async fn set_task_content(
11398 &self,
11399 id: &NativeId,
11400 content: &str,
11401 ) -> Result<Option<()>, SourceError> {
11402 self.replace_content(id, content).await
11403 }
11404
11405 /// Replace one task issue's content and its provenance slot entry with a single body
11406 /// update. The answers are not kept: see `replace_rendering`.
11407 async fn set_task_rendering(
11408 &self,
11409 id: &NativeId,
11410 content: &str,
11411 provenance: &Value,
11412 _answers: &BTreeMap<String, Value>,
11413 ) -> Result<Option<()>, SourceError> {
11414 self.replace_rendering(
11415 id,
11416 BoardKind::Work(ItemKind::Task),
11417 content,
11418 provenance,
11419 None,
11420 )
11421 .await
11422 .map(|written| written.map(|_| ()))
11423 }
11424
11425 /// Replace one design-document issue's content and its provenance slot entry, on exactly
11426 /// the terms of [`set_task_rendering`](TaskSource::set_task_rendering).
11427 async fn set_document_rendering(
11428 &self,
11429 id: &NativeId,
11430 content: &str,
11431 provenance: &Value,
11432 _answers: &BTreeMap<String, Value>,
11433 ) -> Result<Option<()>, SourceError> {
11434 self.replace_rendering(id, BoardKind::Document, content, provenance, None)
11435 .await
11436 .map(|written| written.map(|_| ()))
11437 }
11438
11439 /// Replace one project issue's content and its provenance slot entry, on exactly the
11440 /// terms of [`set_task_rendering`](TaskSource::set_task_rendering).
11441 async fn set_project_rendering(
11442 &self,
11443 id: &NativeId,
11444 content: &str,
11445 provenance: &Value,
11446 _answers: &BTreeMap<String, Value>,
11447 ) -> Result<Option<()>, SourceError> {
11448 self.replace_rendering(
11449 id,
11450 BoardKind::Work(ItemKind::Project),
11451 content,
11452 provenance,
11453 None,
11454 )
11455 .await
11456 .map(|written| written.map(|_| ()))
11457 }
11458
11459 /// Apply a targeted update with one read of the item and a write only for what differs:
11460 /// the `Status` and `Priority` field writes in one request, the `blockedBy` difference,
11461 /// and last one `updateIssue` for title, body and state. See `targeted_update`.
11462 async fn update_task(
11463 &self,
11464 id: &NativeId,
11465 update: &TaskUpdate,
11466 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
11467 self.targeted_update(id, update).await
11468 }
11469
11470 /// Replace one task's `delivered_by` with a single body update that changes the
11471 /// metadata slot and nothing outside it.
11472 async fn set_delivered_by(
11473 &self,
11474 id: &NativeId,
11475 delivered_by: &[TaskRef],
11476 ) -> Result<Option<()>, SourceError> {
11477 self.replace_delivered_by(id, delivered_by).await
11478 }
11479
11480 /// Set one key of one task issue's metadata with a single body update that changes the
11481 /// metadata slot and nothing outside it — no title, label, state or board field request —
11482 /// and sends nothing when the task already holds that value under the key.
11483 async fn set_task_metadata(
11484 &self,
11485 id: &NativeId,
11486 key: &MetadataKey,
11487 value: &Value,
11488 ) -> Result<Option<Task>, SourceError> {
11489 Ok(self
11490 .set_slot_key(id, BoardKind::Work(ItemKind::Task), key, value)
11491 .await?
11492 .map(|item| item.task())
11493 .transpose()?)
11494 }
11495
11496 /// Set one key of one project issue's metadata, on exactly the terms of
11497 /// [`set_task_metadata`](TaskSource::set_task_metadata).
11498 async fn set_project_metadata(
11499 &self,
11500 id: &NativeId,
11501 key: &MetadataKey,
11502 value: &Value,
11503 ) -> Result<Option<Project>, SourceError> {
11504 Ok(self
11505 .set_slot_key(id, BoardKind::Work(ItemKind::Project), key, value)
11506 .await?
11507 .map(|item| item.project()))
11508 }
11509
11510 /// Set one key of one design-document issue's metadata, on exactly the terms of
11511 /// [`set_task_metadata`](TaskSource::set_task_metadata).
11512 async fn set_document_metadata(
11513 &self,
11514 id: &NativeId,
11515 key: &MetadataKey,
11516 value: &Value,
11517 ) -> Result<Option<Document>, SourceError> {
11518 Ok(self
11519 .set_slot_key(id, BoardKind::Document, key, value)
11520 .await?
11521 .map(|item| item.document()))
11522 }
11523
11524 async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
11525 self.delete_item(id).await
11526 }
11527
11528 async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
11529 self.delete_item(id).await
11530 }
11531
11532 async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
11533 self.delete_item(id).await
11534 }
11535
11536 /// One page of the task issue's own comments, walked by GitHub's own cursor.
11537 ///
11538 /// Nothing here filters, so nothing has to be read ahead of the page: the caller's limit is
11539 /// the page GitHub is asked for and GitHub's `endCursor` is the cursor handed back.
11540 ///
11541 /// One request, [`graphql::ISSUE_DETAIL`]: the read that says the id names a task of this
11542 /// board is the read of its comments. A draft this process already resolved is refused
11543 /// without one.
11544 async fn task_comments(
11545 &self,
11546 task: &NativeId,
11547 page: &PageRequest,
11548 ) -> Result<Option<Page<Comment>>, SourceError> {
11549 validate_page(page)?;
11550 let cached = self.resolved_cache()?.get(task).cloned();
11551 if let Some(item) = cached {
11552 if item.kind != BoardKind::Work(ItemKind::Task) {
11553 return Ok(None);
11554 }
11555 if item.content_kind == ContentKind::DraftIssue {
11556 return Err(self.draft_has_no_comments(task));
11557 }
11558 }
11559 match self.issue_detail(task, page).await? {
11560 Some(TaskDetailRead {
11561 comments: Some(comments),
11562 ..
11563 }) => comments,
11564 _ => Ok(None),
11565 }
11566 }
11567
11568 /// Every id's task, with the first page of its comments when `comments` names it:
11569 /// [`DETAIL_BATCH`] items per [`graphql::ISSUE_DETAILS`] request, and one item with its
11570 /// comments in one [`graphql::ISSUE_DETAIL`] request.
11571 async fn get_task_details(
11572 &self,
11573 ids: &[NativeId],
11574 comments: Option<&PageRequest>,
11575 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
11576 if let Some(page) = comments
11577 && let Err(error) = validate_page(page)
11578 {
11579 return ids.iter().map(|_| Err(error.clone())).collect();
11580 }
11581 match (ids, comments) {
11582 ([id], Some(page)) => vec![self.issue_detail(id, page).await],
11583 ([id], None) => vec![self.task_read(id).await],
11584 _ => self.issue_details(ids, comments).await,
11585 }
11586 }
11587
11588 /// Every id's task with the first page of its comments and its `blockedBy`, as a copy reads
11589 /// the tasks it carries: [`COPY_DETAIL_BATCH`] items per [`graphql::ISSUE_COPY_DETAILS`]
11590 /// request, so the dependency read a copy makes of each next is answered from this one.
11591 async fn get_task_details_for_copy(
11592 &self,
11593 ids: &[NativeId],
11594 comments: &PageRequest,
11595 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
11596 // A page past the first is a page of one task's comments, which the detail read of it
11597 // alone answers.
11598 if comments.cursor.is_some() {
11599 return self.get_task_details(ids, Some(comments)).await;
11600 }
11601 if let Err(error) = validate_page(comments) {
11602 return ids.iter().map(|_| Err(error.clone())).collect();
11603 }
11604 let mut read = Vec::with_capacity(ids.len());
11605 for batch in ids.chunks(COPY_DETAIL_BATCH) {
11606 match self
11607 .graphql(
11608 graphql::ISSUE_COPY_DETAILS,
11609 copy_detail_batch(batch, comments),
11610 )
11611 .await
11612 {
11613 Ok(data) => {
11614 for (slot, id) in batch.iter().enumerate() {
11615 let read_one = match data.get(format!("i{slot}")) {
11616 Some(node) => self.detail_of(id, node, true, None).await,
11617 None => Err(SourceError::Malformed {
11618 message: format!(
11619 "GitHub answered a batch read with no item for {}",
11620 id.0
11621 ),
11622 }),
11623 };
11624 read.push(read_one);
11625 }
11626 }
11627 Err(error) if unresolvable_node(&error) => {
11628 for id in batch {
11629 read.push(self.issue_detail(id, comments).await);
11630 }
11631 }
11632 Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
11633 }
11634 }
11635 read
11636 }
11637
11638 /// Add one comment to the task's issue, as the account the token belongs to.
11639 ///
11640 /// The author is refused before anything is sent — not even the task is read — because
11641 /// no answer GitHub could give would make posting under another name than the one asked
11642 /// for the right outcome.
11643 async fn add_comment(
11644 &self,
11645 task: &NativeId,
11646 comment: &NewComment,
11647 ) -> Result<Option<Comment>, SourceError> {
11648 if let Some(author) = &comment.author {
11649 return Err(SourceError::Refused {
11650 message: format!(
11651 "source {} cannot post a comment as {author:?}: GitHub records the account \
11652 the token signs in as the author of every comment; next: leave --author \
11653 out, and the comment is posted as that account",
11654 self.name
11655 ),
11656 });
11657 }
11658 let Some(issue) = self.commented_issue(task).await? else {
11659 return Ok(None);
11660 };
11661 let data = self
11662 .graphql(
11663 graphql::ADD_COMMENT,
11664 json!({"input":{"subjectId":issue.0,"body":comment.body.as_str()}}),
11665 )
11666 .await?;
11667 let subject = data
11668 .pointer("/addComment/subject")
11669 .filter(|value| !value.is_null())
11670 .ok_or_else(|| SourceError::Malformed {
11671 message: "GitHub comment addition returned no subject".into(),
11672 })?;
11673 if required_str(subject, "id")? != issue.0 {
11674 return Err(SourceError::Malformed {
11675 message: "GitHub comment addition answered about another issue".into(),
11676 });
11677 }
11678 let added = data
11679 .pointer("/addComment/commentEdge/node")
11680 .filter(|value| !value.is_null())
11681 .ok_or_else(|| SourceError::Malformed {
11682 message: "GitHub comment addition returned no comment".into(),
11683 })?;
11684 let added = comment_from(added)?;
11685 self.remember_commented(&issue)?;
11686 Ok(Some(added))
11687 }
11688
11689 async fn edit_comment(
11690 &self,
11691 task: &NativeId,
11692 comment: &NativeId,
11693 body: &CommentBody,
11694 ) -> Result<Option<Comment>, SourceError> {
11695 let Some(issue) = self.commented_issue(task).await? else {
11696 return Ok(None);
11697 };
11698 let Some(held) = self.comment_on(&issue, comment).await? else {
11699 return Ok(None);
11700 };
11701 // A comment a copy wrote keeps its origin through an edit: its marker is carried over.
11702 let body = CommentOrigin::kept(&held, body)?;
11703 let data = self
11704 .graphql(
11705 graphql::UPDATE_COMMENT,
11706 json!({"input":{"id":comment.0,"body":body.as_str()}}),
11707 )
11708 .await?;
11709 let edited = data
11710 .pointer("/updateIssueComment/issueComment")
11711 .filter(|value| !value.is_null())
11712 .ok_or_else(|| SourceError::Malformed {
11713 message: "GitHub comment update returned no comment".into(),
11714 })?;
11715 let edited = comment_from(edited)?;
11716 if edited.id != *comment {
11717 return Err(SourceError::Malformed {
11718 message: "GitHub comment update returned the wrong comment".into(),
11719 });
11720 }
11721 self.remember_commented(&issue)?;
11722 Ok(Some(edited))
11723 }
11724
11725 async fn delete_comment(
11726 &self,
11727 task: &NativeId,
11728 comment: &NativeId,
11729 ) -> Result<Option<NativeId>, SourceError> {
11730 let Some(issue) = self.commented_issue(task).await? else {
11731 return Ok(None);
11732 };
11733 if !self.comment_is_on(&issue, comment).await? {
11734 return Ok(None);
11735 }
11736 let data = self
11737 .graphql(graphql::DELETE_COMMENT, json!({"input":{"id":comment.0}}))
11738 .await?;
11739 // The payload says nothing about the comment it removed, so what is checked is that
11740 // GitHub answered the mutation at all rather than leaving it unanswered.
11741 data.get("deleteIssueComment")
11742 .filter(|value| !value.is_null())
11743 .ok_or_else(|| SourceError::Malformed {
11744 message: "GitHub comment deletion returned no payload".into(),
11745 })?;
11746 Ok(Some(comment.clone()))
11747 }
11748
11749 /// Every request this source has recorded, and what each of GitHub's two budgets was
11750 /// attributed — read off the same accounting the session report is rendered from, so
11751 /// the two cannot count one request two ways.
11752 async fn metering(&self) -> Result<Option<Metering>, SourceError> {
11753 Ok(Some(self.ledger.snapshot().metering()))
11754 }
11755
11756 /// Drop every item, search answer and board read this source holds, so the next command
11757 /// reads the board as a person has since left it.
11758 ///
11759 /// Every one of those is held on the assumption that nothing but this source writes the
11760 /// board while a command runs, which stops being true the moment the command is over: a
11761 /// body a person edited would be overwritten from the record held here, and a card they
11762 /// moved would be read as still where this source left it. The board's own field
11763 /// definitions go too, because a person can add or delete a `Status` option and a write
11764 /// resolved against the held list would not re-read on a miss. What stays is what stays
11765 /// valid in normal use: each repository's node id, which a miss re-reads, the pacing of
11766 /// mutations, which is about GitHub's limiter rather than anybody's work, and the running
11767 /// accounting [`metering`](TaskSource::metering) answers from.
11768 ///
11769 /// Infallible in practice: a lock an earlier failure poisoned is cleared rather than
11770 /// refused, because clearing it is what puts it right.
11771 async fn end_command(&self) -> Result<(), SourceError> {
11772 fn clear<T: Default>(held: &Mutex<T>) {
11773 *held
11774 .lock()
11775 .unwrap_or_else(std::sync::PoisonError::into_inner) = T::default();
11776 held.clear_poison();
11777 }
11778 clear(&self.created);
11779 clear(&self.updated);
11780 clear(&self.commented);
11781 clear(&self.board_cache);
11782 clear(&self.search_cache);
11783 clear(&self.narrowed_cache);
11784 clear(&self.search_next);
11785 clear(&self.resolved_cache);
11786 clear(&self.held_cache);
11787 clear(&self.children_cache);
11788 clear(&self.fields_cache);
11789 self.expected.end_command();
11790 Ok(())
11791 }
11792}
11793
11794/// Each project's sub-issues as one command read them, keyed by the selector they were asked
11795/// for under, beside the project that selector named; see `children_cache`.
11796type ProjectChildren = BTreeMap<NativeId, (NativeId, Vec<Resolved>)>;
11797
11798/// One issue comment as the contract carries it.
11799///
11800/// `author` is absent both when GitHub answers `null` for an account that no longer exists
11801/// and when it answers an actor with no login, because either way the source did not say who
11802/// wrote it — which is what an absent author means, rather than an author called nothing.
11803///
11804/// A comment a copy wrote here carries its origin as the hidden marker at the end of its body
11805/// — GitHub sets every comment's author and times itself, so there is nowhere else to keep it —
11806/// and is read back with the marker taken out and reported as its origin.
11807fn comment_from(value: &Value) -> Result<Comment, SourceError> {
11808 Ok(Comment {
11809 origin: None,
11810 id: NativeId(required_str(value, "id")?.to_owned()),
11811 author: optional_str(value.get("author").unwrap_or(&Value::Null), "login")?
11812 .map(str::to_owned),
11813 created_at: optional_time(value, "createdAt")?,
11814 updated_at: optional_time(value, "updatedAt")?,
11815 body: required_str(value, "body")?.to_owned(),
11816 url: optional_str(value, "url")?.map(str::to_owned),
11817 }
11818 .unmarked())
11819}
11820
11821/// The page of comments one issue node carries, resumed from `after`.
11822fn comment_page(
11823 node: &Value,
11824 issue: &str,
11825 after: Option<&str>,
11826) -> Result<Page<Comment>, SourceError> {
11827 let connection = node
11828 .get("comments")
11829 .filter(|value| !value.is_null())
11830 .ok_or_else(|| SourceError::Malformed {
11831 message: format!("GitHub issue {issue} answered with no comments connection"),
11832 })?;
11833 let items = optional_nodes(Some(connection), "issue comments")?
11834 .into_iter()
11835 .flatten()
11836 .map(comment_from)
11837 .collect::<Result<Vec<_>, _>>()?;
11838 let next = next_cursor(connection)?;
11839 if let Some(next) = &next {
11840 validate_cursor_progress(after, &next.0)?;
11841 }
11842 Ok(Page { items, next })
11843}
11844
11845/// The far ends of an issue's whole `blockedBy` connection, when the read carried it to its
11846/// end — `None` when it carried none, or a page with more past it.
11847fn carried_blocked_by(content: &Value) -> Result<Option<Vec<Value>>, SourceError> {
11848 let Some(connection) = content.get("blockedBy").filter(|value| !value.is_null()) else {
11849 return Ok(None);
11850 };
11851 if next_cursor(connection)?.is_some() {
11852 return Ok(None);
11853 }
11854 Ok(Some(
11855 optional_nodes(Some(connection), "blocked-by issues")?
11856 .into_iter()
11857 .flatten()
11858 .cloned()
11859 .collect(),
11860 ))
11861}
11862
11863/// Where the recorded tail of a dependency walk resumes; see
11864/// [`GitHubProjectsSource::recorded_edges`].
11865const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";
11866
11867/// The board text field this source keeps a copy's origin in.
11868///
11869/// Named after the key it holds, and held to that name by the guard below rather than by
11870/// a reader noticing.
11871const ORIGIN_FIELD: &str = "onetaskgraph.origin";
11872
11873/// The metadata key that field holds.
11874///
11875/// The engine owns this key and spells it once as `GlobalId::ORIGIN_KEY`; a plugin never
11876/// constructs or interprets the qualified id it carries. This source names it only to
11877/// route it — a short, typed value belongs in a typed field rather than in the body slot
11878/// a caller's own prose shares.
11879///
11880/// Restated rather than imported, because no plugin crate may depend on the engine. What
11881/// keeps the two spellings one contract is `scripts/check-origin-key-spelling.sh`, a
11882/// target in `check`: it reads the engine's own literal and fails naming the file and the
11883/// line when a plugin's parts from it either way. Drift here has one symptom — a copy
11884/// that creates a second item every run instead of finding the one it wrote — and that is
11885/// too late to learn it.
11886const ORIGIN_KEY: &str = "onetaskgraph.origin";
11887
11888/// Where a recorded tail resumes, refusing a cursor no walk in `direction` reported.
11889///
11890/// The reserved key holds forward edges and nothing else — the reverse of a recorded edge
11891/// is derived from the far end, never written down on the near item — so only a forward
11892/// walk ever reports one of these cursors. A reverse read carrying one is resuming a walk
11893/// it did not come from, and it is told so rather than answered with an empty page that
11894/// reads as a walk which ended.
11895fn recorded_offset(
11896 cursor: Option<&str>,
11897 direction: Direction,
11898) -> Result<Option<usize>, SourceError> {
11899 cursor
11900 .and_then(|cursor| cursor.strip_prefix(RECORDED_CURSOR))
11901 .map(|offset| {
11902 if direction != Direction::DependsOn {
11903 return Err(SourceError::Config {
11904 message: format!(
11905 "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a \
11906 reverse dependency read never issues; resume it in the direction \
11907 that reported it"
11908 ),
11909 });
11910 }
11911 offset.parse().map_err(|_| SourceError::Config {
11912 message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
11913 })
11914 })
11915 .transpose()
11916}
11917
11918fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
11919 let mut page = offset_page(edges, offset, limit.max(1));
11920 page.next = page
11921 .next
11922 .map(|cursor| Cursor(format!("{RECORDED_CURSOR}{}", cursor.0)));
11923 page
11924}
11925
11926/// The kind of one issue reached through a dependency connection.
11927///
11928/// The same questions the board scan asks, over the fields the dependency document
11929/// selects, and in the same order: the design prefix first, then a sub-issue is a task,
11930/// then anything with sub-issues or the marker is a project.
11931///
11932/// # Errors
11933///
11934/// A far end this board holds as a document is refused rather than reported. The two
11935/// answers that are not refusals would both be wrong: reporting it as a task names an id
11936/// no task read of this source can find, and reporting it as a project names one no
11937/// project read can. There is no third value to return — `ItemKind` has no document
11938/// variant, because nothing may point at a document — so the relationship itself is what
11939/// the person is told about.
11940fn related_kind(value: &Value) -> Result<ItemKind, SourceError> {
11941 let id = required_str(value, "id")?;
11942 if required_str(value, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
11943 return Err(SourceError::Refused {
11944 message: format!(
11945 "GitHub issue {id} is a document of this board — its title begins \
11946 {DESIGN_TITLE_PREFIX:?} — and nothing may depend on a document or be depended \
11947 on by one; next: remove that issue's blocking relationship on this board"
11948 ),
11949 });
11950 }
11951 let parent = optional_str(value.get("parent").unwrap_or(&Value::Null), "id")?;
11952 if parent.is_some() {
11953 return Ok(ItemKind::Task);
11954 }
11955 let (_, slot) = metadata_body(optional_str(value, "body")?.map(str::to_owned))?;
11956 let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
11957 message: format!("GitHub issue {id}: {message}"),
11958 })?;
11959 let sub_issues = sub_issue_total(value)?;
11960 Ok(if sub_issues > 0 || marked == Some(ItemKind::Project) {
11961 ItemKind::Project
11962 } else {
11963 ItemKind::Task
11964 })
11965}
11966
11967/// The `IssueStateUpdateInput` one status target asks for.
11968///
11969/// `stateInput` and `state` are mutually exclusive on `UpdateIssueInput`, and only this
11970/// one is ever sent. A non-terminal status always asks for `OPEN`, which is what reopens
11971/// a currently-closed issue: without that the item would read back `Unknown` and a copy
11972/// would report a change forever. A document has no status at all, and asks for neither.
11973fn state_input(target: Option<&StatusTarget>) -> Value {
11974 match target {
11975 Some(StatusTarget::Terminal(_, reason)) => {
11976 json!({"value":"CLOSED","stateReason":reason.reason()})
11977 }
11978 Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => json!({"value":"OPEN"}),
11979 // A document has no status, so a write of one says nothing about the issue's open
11980 // or closed state rather than forcing it open: `stateInput` is what carries that
11981 // instruction, and an explicit null asks for no change to it.
11982 None => Value::Null,
11983 }
11984}
11985
11986/// The metadata one write stores in the item's body slot.
11987///
11988/// The typed fields travel as themselves, so the three reserved keys are rebuilt here
11989/// rather than carried: the kind marker so an empty project stays readable, the
11990/// repository list only when it is not exactly the issue's own repository, and the far
11991/// ends no relationship here can name.
11992///
11993/// The copy origin is the one typed field that is also mirrored here, and only as a
11994/// mirror: it lands in the board's origin field as well, which stays the one every reader
11995/// takes it from, and it is here so that GitHub's issue search — which indexes this comment
11996/// and catches up with a write in seconds rather than minutes — can find the item by it.
11997/// A reader of the release before this one drops the slot's copy and reads the field, so an
11998/// item written here still reads with exactly one origin there.
11999fn slot_metadata(
12000 incoming: &Incoming<'_>,
12001 own_repository: Option<&Repository>,
12002 fallback: &[DependencyEdge],
12003) -> BTreeMap<String, Value> {
12004 let mut metadata = incoming.metadata.clone();
12005 match metadata.remove(ORIGIN_KEY) {
12006 Some(Value::String(origin)) if !origin.is_empty() => {
12007 metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin));
12008 }
12009 _ => {}
12010 }
12011 match incoming.written.kind() {
12012 BoardKind::Work(kind) => metadata.insert(
12013 ItemKind::METADATA_KEY.to_owned(),
12014 Value::String(kind.marker().to_owned()),
12015 ),
12016 // A document is told by its title, so it carries no kind marker: that key names
12017 // what a dependency endpoint points at, and nothing may point at a document.
12018 BoardKind::Document => metadata.remove(ItemKind::METADATA_KEY),
12019 };
12020 incoming.classification.record(&mut metadata);
12021 let derivable = own_repository
12022 .map(|own| incoming.repositories == [own.clone()])
12023 .unwrap_or(incoming.repositories.is_empty());
12024 if derivable {
12025 metadata.remove(Repository::METADATA_KEY);
12026 } else {
12027 metadata.insert(
12028 Repository::METADATA_KEY.to_owned(),
12029 Value::Array(
12030 incoming
12031 .repositories
12032 .iter()
12033 .map(|repository| Value::String(repository.as_str().to_owned()))
12034 .collect(),
12035 ),
12036 );
12037 }
12038 // The typed lists are what land, whatever the caller's own metadata held under their
12039 // keys: a key of either name travelling beside the field would otherwise be a second
12040 // answer to the same question, and the field is the one the contract names.
12041 for (key, entries) in [
12042 (TaskRef::DELIVERS_KEY, incoming.delivers),
12043 (TaskRef::DELIVERED_BY_KEY, incoming.delivered_by),
12044 ] {
12045 set_task_list(&mut metadata, key, entries);
12046 }
12047 record_edges(&mut metadata, fallback);
12048 metadata
12049}
12050
12051/// Hold the far ends no relationship here can name under [`DependencyEdge::RECORDED_KEY`] in
12052/// one slot's metadata, or no such key when there are none.
12053fn record_edges(metadata: &mut BTreeMap<String, Value>, fallback: &[DependencyEdge]) {
12054 if fallback.is_empty() {
12055 metadata.remove(DependencyEdge::RECORDED_KEY);
12056 } else {
12057 metadata.insert(
12058 DependencyEdge::RECORDED_KEY.to_owned(),
12059 Value::Array(
12060 fallback
12061 .iter()
12062 .map(|edge| json!({"id":edge.to.id(),"kind":edge.to.kind}))
12063 .collect(),
12064 ),
12065 );
12066 }
12067}
12068
12069/// Every label one item carries, from its content's own connection and nowhere else.
12070///
12071/// There is no second place to read one from: no document this source sends selects the
12072/// board's built-in `Labels` field, because GitHub derives it from the content and a draft
12073/// cannot carry one at all. The module documentation records the three schema facts that
12074/// settle it.
12075fn labels(content: &Value) -> Result<Vec<Label>, SourceError> {
12076 optional_nodes(content.get("labels"), "content labels")?
12077 .into_iter()
12078 .flatten()
12079 .map(|v| {
12080 Ok(Label {
12081 id: NativeId(required_str(v, "id")?.to_owned()),
12082 name: required_str(v, "name")?.to_owned(),
12083 color: optional_str(v, "color")?.map(str::to_owned),
12084 })
12085 })
12086 .collect()
12087}
12088
12089/// Each board field value one item holds, as the change token's facets name it: the field's
12090/// name, with the single-select option's name or the text. A value of a type no read here
12091/// selects, and one naming no field, says nothing a person can rename and is left out.
12092fn facet_fields(field_values: &[Value]) -> Vec<(String, String)> {
12093 field_values
12094 .iter()
12095 .filter_map(|value| {
12096 let field = value.pointer("/field/name")?.as_str()?;
12097 let held = value.get("name").or_else(|| value.get("text"))?.as_str()?;
12098 Some((field.to_owned(), held.to_owned()))
12099 })
12100 .collect()
12101}
12102
12103/// The digest of the facets of the issue `content`, whose board item's values are
12104/// `field_values` — or `None` when the response did not carry, whole, every member they are read
12105/// from: the title, the parent, the sub-issue summary and the body its kind is read from, every
12106/// label, and every field value.
12107///
12108/// What a write's own response spells its token from, by exactly the rules a read takes them by.
12109fn facets_of(content: &Value, field_values: &Value) -> Option<change_token::FacetsDigest> {
12110 let ended = |connection: &Value| {
12111 connection.pointer("/pageInfo/hasNextPage") == Some(&Value::Bool(false))
12112 };
12113 let labels = content.get("labels").filter(|labels| ended(labels))?;
12114 if !ended(field_values) {
12115 return None;
12116 }
12117 let parent = content.get("parent")?;
12118 let (_, slot) = metadata_body(content.get("body")?.as_str().map(str::to_owned)).ok()?;
12119 let kind = BoardKind::of(
12120 content.get("title")?.as_str()?,
12121 !parent.is_null(),
12122 sub_issue_total(content).ok()?,
12123 ItemKind::from_metadata(&slot).ok()?,
12124 );
12125 let labels = self::labels(&json!({"labels": labels})).ok()?;
12126 let nodes = field_values.get("nodes")?.as_array()?;
12127 Some(change_token::Facets::new(kind.facet(), facet_fields(nodes), &labels).digest())
12128}
12129
12130/// The definition of each board field one item's values are values of, in the shape a read
12131/// of the board's own `fields` gives one.
12132///
12133/// A value names its field through a fragment on that field's own type, so the type is
12134/// known from which kind of value it is: a single-select value's field is a
12135/// `ProjectV2SingleSelectField`, options and all, and a text value's is a `ProjectV2Field`.
12136/// A value whose field carried no id, or an empty one, says nothing usable and is left out.
12137fn field_definitions(field_values: &[Value]) -> Vec<Value> {
12138 field_values
12139 .iter()
12140 .filter_map(|value| {
12141 let field = value.get("field")?.as_object()?;
12142 field.get("id")?.as_str().filter(|id| !id.is_empty())?;
12143 let typename = if value.get("text").is_some() {
12144 "ProjectV2Field"
12145 } else if value.get("name").is_some() {
12146 "ProjectV2SingleSelectField"
12147 } else {
12148 return None;
12149 };
12150 let mut defined = field.clone();
12151 defined.insert("__typename".to_owned(), json!(typename));
12152 // Only a text field holds a text value, so the value says the field's type too.
12153 if typename == "ProjectV2Field" {
12154 defined.insert("dataType".to_owned(), json!("TEXT"));
12155 }
12156 Some(Value::Object(defined))
12157 })
12158 .collect()
12159}
12160
12161fn text_field(field_values: &[Value], name: &str) -> Result<Option<String>, SourceError> {
12162 let Some(node) = field_values
12163 .iter()
12164 .find(|node| node.pointer("/field/name").and_then(Value::as_str) == Some(name))
12165 else {
12166 return Ok(None);
12167 };
12168 Ok(optional_str(node, "text")?.map(str::to_owned))
12169}
12170
12171fn valid_github_owner(owner: &str) -> bool {
12172 !owner.is_empty()
12173 && owner.len() <= 39
12174 && !owner.starts_with('-')
12175 && !owner.ends_with('-')
12176 && !owner.contains("--")
12177 && owner
12178 .bytes()
12179 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
12180}
12181
12182/// GitHub's repository-name grammar: 1-100 ASCII letters, digits, `-`, `_` or `.`, and
12183/// neither of the two names a path segment already means.
12184fn valid_github_repository_name(name: &str) -> bool {
12185 !name.is_empty()
12186 && name.len() <= 100
12187 && name != "."
12188 && name != ".."
12189 && name
12190 .bytes()
12191 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
12192}
12193
12194fn valid_environment_name(name: &str) -> bool {
12195 let mut bytes = name.bytes();
12196 bytes
12197 .next()
12198 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
12199 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
12200}
12201
12202/// How many sub-issues one issue has.
12203///
12204/// `Issue.subIssuesSummary` is `SubIssuesSummary!` and its `total` is `Int!`, so an
12205/// absent or non-integer one is a response this source cannot read — and reading it as
12206/// zero would classify a project as a task, which is exactly the mistake the marker
12207/// exists to keep from happening quietly.
12208fn sub_issue_total(issue: &Value) -> Result<u64, SourceError> {
12209 let summary = issue
12210 .get("subIssuesSummary")
12211 .ok_or_else(|| SourceError::Malformed {
12212 message: "GitHub issue is missing subIssuesSummary".into(),
12213 })?;
12214 summary
12215 .get("total")
12216 .and_then(Value::as_u64)
12217 .ok_or_else(|| SourceError::Malformed {
12218 message: "GitHub issue subIssuesSummary.total is not an unsigned integer".into(),
12219 })
12220}
12221
12222/// One issue's own `number`.
12223///
12224/// An issue always has one: GitHub declares `Issue.number` as `Int!` and every selection of
12225/// an issue in this module asks for it. So a read of one that comes back without it, or
12226/// with something that is not an unsigned integer, is a response this source cannot read —
12227/// absence here is **not** "this issue has no number". A draft is the content that has
12228/// none, and a draft never reaches this: the caller decides on `__typename` first, the way
12229/// it does for `subIssuesSummary`, which `DraftIssue` equally declares nothing for.
12230fn issue_number(issue: &Value) -> Result<u64, SourceError> {
12231 issue
12232 .get("number")
12233 .and_then(Value::as_u64)
12234 .ok_or_else(|| SourceError::Malformed {
12235 message: "GitHub issue number is missing or is not an unsigned integer".into(),
12236 })
12237}
12238
12239/// The `number` a creating mutation answered with, and `None` when it answered without one;
12240/// why a missing one is tolerated is at the call in `create_and_file_issue`.
12241fn created_issue_number(created: &Value) -> Result<Option<u64>, SourceError> {
12242 match created.get("number") {
12243 None | Some(Value::Null) => Ok(None),
12244 Some(value) => value
12245 .as_u64()
12246 .map(Some)
12247 .ok_or_else(|| SourceError::Malformed {
12248 message: "GitHub created issue number is not an unsigned integer".into(),
12249 }),
12250 }
12251}
12252
12253fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
12254 value
12255 .get(field)
12256 .and_then(Value::as_str)
12257 .ok_or_else(|| SourceError::Malformed {
12258 message: format!("GitHub response is missing string field {field}"),
12259 })
12260}
12261
12262fn required_nonblank_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
12263 let found = required_str(value, field)?;
12264 if found.trim().is_empty() {
12265 return Err(SourceError::Malformed {
12266 message: format!("GitHub response has blank string field {field}"),
12267 });
12268 }
12269 Ok(found)
12270}
12271
12272/// The slot's delimiters, which `docs/metadata.md` settles once for every source that
12273/// needs one — Linear spells them too, in its own description field.
12274///
12275/// Restated rather than shared, because a plugin crate depends on the contract crate and
12276/// nothing else of this workspace. `scripts/check-metadata-slot-encoding.sh`, a target in
12277/// `check`, is what keeps the two one encoding: drift is otherwise quiet, since each
12278/// source round-trips its own writes perfectly well under its own spelling.
12279const METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
12280const METADATA_CLOSE: &str = "\n-->";
12281
12282/// What the composer puts between a non-empty visible body and the slot, and the one thing
12283/// the parser takes off the visible body when it takes the slot off — exactly once, so every
12284/// other trailing byte of the body comes back as it was written.
12285// llmlint: ignore[contracts_have_one_source_or_a_drift_gate] How a composer lays the slot after prose is this source's own; `docs/metadata.md` and its gate settle only the delimiters, and no other source declares a separator to reconcile against.
12286const METADATA_SEPARATOR: &str = "\n\n";
12287
12288/// The visible body and the metadata slot at the end of it.
12289///
12290/// The encoding is the one `docs/metadata.md` settles for Linear, which is where its
12291/// reasons are. Only a comment at the very end is a slot; one in the middle is a person's
12292/// own content and is left alone. The visible body is everything before the slot less the
12293/// one [`METADATA_SEPARATOR`] the composer put there, byte for byte.
12294fn metadata_body(
12295 body: Option<String>,
12296) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
12297 let Some(body) = body else {
12298 return Ok((None, BTreeMap::new()));
12299 };
12300 let Some(slot) = slot_span(&body)? else {
12301 return Ok((Some(body), BTreeMap::new()));
12302 };
12303 let metadata =
12304 serde_json::from_str(&body[slot.encoded_start..slot.encoded_end]).map_err(|error| {
12305 SourceError::Malformed {
12306 message: format!(
12307 "invalid canonical JSON in GitHub issue onetaskgraph metadata slot: {error}"
12308 ),
12309 }
12310 })?;
12311 let before = &body[..slot.start];
12312 let visible = before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before);
12313 Ok(((!visible.is_empty()).then(|| visible.to_owned()), metadata))
12314}
12315
12316/// Where the metadata slot sits in one body, as byte offsets into it.
12317struct SlotSpan {
12318 /// Where [`METADATA_OPEN`] begins.
12319 start: usize,
12320 /// Where the encoded JSON begins, just past [`METADATA_OPEN`].
12321 encoded_start: usize,
12322 /// Where the encoded JSON ends, at the start of [`METADATA_CLOSE`].
12323 encoded_end: usize,
12324 /// Just past [`METADATA_CLOSE`].
12325 end: usize,
12326}
12327
12328/// The slot at the very end of `body`, or `None` when it has none.
12329///
12330/// The one reading of *where the slot is*, shared by [`metadata_body`], which reads it, and
12331/// [`with_slot`], which rewrites it — so the two cannot disagree about which comment is the
12332/// slot.
12333fn slot_span(body: &str) -> Result<Option<SlotSpan>, SourceError> {
12334 let Some(start) = body.rfind(METADATA_OPEN) else {
12335 return Ok(None);
12336 };
12337 let encoded_start = start + METADATA_OPEN.len();
12338 let Some(relative_end) = body[encoded_start..].find(METADATA_CLOSE) else {
12339 return Err(SourceError::Malformed {
12340 message: "unterminated onetaskgraph metadata slot in GitHub issue body".into(),
12341 });
12342 };
12343 let encoded_end = encoded_start + relative_end;
12344 let end = encoded_end + METADATA_CLOSE.len();
12345 if !body[end..].trim().is_empty() {
12346 return Ok(None);
12347 }
12348 Ok(Some(SlotSpan {
12349 start,
12350 encoded_start,
12351 encoded_end,
12352 end,
12353 }))
12354}
12355
12356/// `body` with its metadata slot holding exactly `metadata`, and every byte outside the
12357/// slot as it was.
12358///
12359/// A slot that is there has its JSON replaced in place; one that becomes empty is removed
12360/// together with the one [`METADATA_SEPARATOR`] separating it from the prose before it. A
12361/// body with no slot gains one the way [`compose_body`] writes it — after that separator,
12362/// or alone in an empty body — and a body with no slot that is given no metadata is
12363/// returned as it is.
12364fn with_slot(body: &str, metadata: &BTreeMap<String, Value>) -> Result<String, SourceError> {
12365 let encoded = if metadata.is_empty() {
12366 None
12367 } else {
12368 Some(
12369 serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
12370 message: error.to_string(),
12371 })?,
12372 )
12373 };
12374 Ok(match (slot_span(body)?, encoded) {
12375 (Some(slot), Some(encoded)) => format!(
12376 "{}{encoded}{}",
12377 &body[..slot.encoded_start],
12378 &body[slot.encoded_end..]
12379 ),
12380 (Some(slot), None) => {
12381 let before = &body[..slot.start];
12382 format!(
12383 "{}{}",
12384 before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before),
12385 &body[slot.end..]
12386 )
12387 }
12388 (None, None) => body.to_owned(),
12389 (None, Some(encoded)) if body.is_empty() => {
12390 format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
12391 }
12392 (None, Some(encoded)) => {
12393 format!("{body}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
12394 }
12395 })
12396}
12397
12398/// `body` with everything before its metadata slot replaced by `content`, and the slot
12399/// itself kept byte for byte.
12400///
12401/// The inverse of how [`metadata_body`] splits a body: the slot, when there is one, follows
12402/// `content` after the one [`METADATA_SEPARATOR`] the composer puts there — or alone, when
12403/// `content` is empty — so a read of the result reports `content` as the visible body and
12404/// the slot's metadata exactly as it was.
12405fn with_content(body: &str, content: &str) -> Result<String, SourceError> {
12406 let Some(slot) = slot_span(body)? else {
12407 return Ok(content.to_owned());
12408 };
12409 let kept = &body[slot.start..];
12410 Ok(if content.is_empty() {
12411 kept.to_owned()
12412 } else {
12413 format!("{content}{METADATA_SEPARATOR}{kept}")
12414 })
12415}
12416
12417/// Hold `entries` under `key` in one slot's metadata, or no such key when there are none.
12418fn set_task_list(metadata: &mut BTreeMap<String, Value>, key: &str, entries: &[TaskRef]) {
12419 if entries.is_empty() {
12420 metadata.remove(key);
12421 } else {
12422 metadata.insert(
12423 key.to_owned(),
12424 Value::Array(
12425 entries
12426 .iter()
12427 .map(|entry| Value::String(entry.as_str().to_owned()))
12428 .collect(),
12429 ),
12430 );
12431 }
12432}
12433
12434fn compose_body(
12435 content: Option<&str>,
12436 metadata: &BTreeMap<String, Value>,
12437) -> Result<Option<String>, SourceError> {
12438 let visible = content.unwrap_or_default();
12439 if metadata.is_empty() {
12440 return Ok((!visible.is_empty()).then(|| visible.to_owned()));
12441 }
12442 let encoded = serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
12443 message: error.to_string(),
12444 })?;
12445 Ok(Some(if visible.is_empty() {
12446 format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
12447 } else {
12448 format!("{visible}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
12449 }))
12450}
12451
12452fn required_bool(value: &Value, field: &str) -> Result<bool, SourceError> {
12453 value
12454 .get(field)
12455 .and_then(Value::as_bool)
12456 .ok_or_else(|| SourceError::Malformed {
12457 message: format!("GitHub response is missing boolean field {field}"),
12458 })
12459}
12460fn optional_str<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, SourceError> {
12461 match value.get(field) {
12462 None | Some(Value::Null) => Ok(None),
12463 Some(value) => value
12464 .as_str()
12465 .map(Some)
12466 .ok_or_else(|| SourceError::Malformed {
12467 message: format!("GitHub response field {field} is not a string or null"),
12468 }),
12469 }
12470}
12471fn optional_nodes<'a>(
12472 connection: Option<&'a Value>,
12473 name: &str,
12474) -> Result<Option<&'a Vec<Value>>, SourceError> {
12475 match connection {
12476 None | Some(Value::Null) => Ok(None),
12477 Some(value) => value
12478 .get("nodes")
12479 .and_then(Value::as_array)
12480 .map(Some)
12481 .ok_or_else(|| SourceError::Malformed {
12482 message: format!("GitHub {name}.nodes is not an array"),
12483 }),
12484 }
12485}
12486fn complete_connection(connection: &Value, name: &str, size: u32) -> Result<(), SourceError> {
12487 let page_info = connection
12488 .get("pageInfo")
12489 .ok_or_else(|| SourceError::Malformed {
12490 message: format!("GitHub {name} has no pageInfo"),
12491 })?;
12492 if required_bool(page_info, "hasNextPage")? {
12493 return Err(SourceError::Malformed {
12494 message: format!(
12495 "GitHub {name} exceeds the supported nested connection size of {size}"
12496 ),
12497 });
12498 }
12499 Ok(())
12500}
12501fn optional_time(value: &Value, field: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
12502 optional_str(value, field)?
12503 .map(|timestamp| {
12504 timestamp.parse().map_err(|error| SourceError::Malformed {
12505 message: format!("GitHub response field {field} is not a timestamp: {error}"),
12506 })
12507 })
12508 .transpose()
12509}
12510fn validate_page(page: &PageRequest) -> Result<(), SourceError> {
12511 if page.limit == 0 {
12512 Err(SourceError::Config {
12513 message: "page limit must be at least 1".into(),
12514 })
12515 } else {
12516 Ok(())
12517 }
12518}
12519fn next_cursor(connection: &Value) -> Result<Option<Cursor>, SourceError> {
12520 let page = connection
12521 .get("pageInfo")
12522 .filter(|value| value.is_object())
12523 .ok_or_else(|| SourceError::Malformed {
12524 message: "GitHub connection is missing pageInfo".into(),
12525 })?;
12526 if required_bool(page, "hasNextPage")? {
12527 let cursor = required_str(page, "endCursor")?;
12528 validate_cursor_progress(None, cursor)?;
12529 Ok(Some(Cursor(cursor.into())))
12530 } else {
12531 Ok(None)
12532 }
12533}
12534fn validate_cursor_progress(previous: Option<&str>, next: &str) -> Result<(), SourceError> {
12535 if next.is_empty() || previous == Some(next) {
12536 Err(SourceError::Malformed {
12537 message: "GitHub pagination cursor is empty or did not advance".into(),
12538 })
12539 } else {
12540 Ok(())
12541 }
12542}
12543/// The version of this plugin's opaque narrowing-search cursor.
12544pub const SEARCH_CURSOR_VERSION: u32 = 4;
12545
12546#[derive(Serialize, Deserialize)]
12547#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
12548enum SearchConnection {
12549 Initial {},
12550 Continuing { after: Cursor },
12551 Exhausted {},
12552}
12553impl SearchConnection {
12554 fn after(&self) -> Option<&str> {
12555 match self {
12556 Self::Continuing { after } => Some(&after.0),
12557 _ => None,
12558 }
12559 }
12560 fn exhausted(&self) -> bool {
12561 matches!(self, Self::Exhausted { .. })
12562 }
12563 /// Whether a cursor naming this position, `offset` rows into its page, is one this
12564 /// plugin could have handed out: a page is resumed only part of the way through it — an
12565 /// offset of a whole page or more would skip rows nobody was given — an initial page
12566 /// only once some of it was handed out, and an exhausted connection has no page to be
12567 /// part of the way through.
12568 fn valid_resume(&self, offset: usize) -> bool {
12569 let within = offset < SEARCH_PAGE_SIZE as usize;
12570 match self {
12571 Self::Initial { .. } => offset > 0 && within,
12572 Self::Continuing { after } => !after.0.is_empty() && within,
12573 Self::Exhausted { .. } => offset == 0,
12574 }
12575 }
12576}
12577
12578/// Versioned source cursor. A zero offset and empty own-write ids are omitted.
12579#[derive(Serialize, Deserialize)]
12580#[serde(deny_unknown_fields)]
12581struct SearchPosition {
12582 version: u32,
12583 connection: SearchConnection,
12584 /// How many rows of the page `connection` starts were already handed out.
12585 #[serde(default, skip_serializing_if = "is_zero")]
12586 offset: usize,
12587 #[serde(default, skip_serializing_if = "Vec::is_empty")]
12588 seen: Vec<NativeId>,
12589 #[serde(default, skip_serializing_if = "Vec::is_empty")]
12590 own: Vec<NativeId>,
12591}
12592impl Default for SearchPosition {
12593 fn default() -> Self {
12594 Self {
12595 version: SEARCH_CURSOR_VERSION,
12596 connection: SearchConnection::Initial {},
12597 offset: 0,
12598 seen: Vec::new(),
12599 own: Vec::new(),
12600 }
12601 }
12602}
12603
12604fn is_zero(offset: &usize) -> bool {
12605 *offset == 0
12606}
12607
12608fn numeric_cursor(cursor: Option<&Cursor>) -> Result<usize, SourceError> {
12609 cursor.map_or(Ok(0), |c| {
12610 c.0.parse().map_err(|_| SourceError::Config {
12611 message: "page cursor is invalid".into(),
12612 })
12613 })
12614}
12615fn offset_page<T>(mut items: Vec<T>, offset: usize, limit: usize) -> Page<T> {
12616 if offset > items.len() {
12617 return Page::last(vec![]);
12618 }
12619 let tail = items.split_off(offset);
12620 let mut selected = tail;
12621 let next = (selected.len() > limit).then(|| Cursor((offset + limit).to_string()));
12622 selected.truncate(limit);
12623 Page {
12624 items: selected,
12625 next,
12626 }
12627}
12628
12629impl GitHubProjectsSource {
12630 async fn write_task_assets(
12631 &self,
12632 write: &ItemWrite<Task>,
12633 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
12634 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
12635 let near = write.target.as_ref().unwrap_or(&write.item.id);
12636 for (key, entries) in [
12637 (TaskRef::DELIVERS_KEY, &write.item.delivers),
12638 (TaskRef::DELIVERED_BY_KEY, &write.item.delivered_by),
12639 ] {
12640 TaskRef::listed(key, near, Some(&self.name), entries.clone())
12641 .map_err(|message| SourceError::Refused { message })?;
12642 }
12643 if self.priorities.is_none() && write.item.priority != Priority::None {
12644 return Err(self.holds_no_priority());
12645 }
12646 self.write_item(
12647 &Incoming {
12648 written: Written::Work(ItemKind::Task, &write.item.status),
12649 title: &write.item.title,
12650 content: write.item.content.as_deref(),
12651 assets,
12652 labels: &write.item.labels,
12653 metadata: &write.item.metadata,
12654 repositories: &write.item.repositories,
12655 classification: write.item.classification,
12656 parent: write.item.project.as_ref(),
12657 delivers: &write.item.delivers,
12658 delivered_by: &write.item.delivered_by,
12659 priority: self.priorities.as_ref().map(|_| write.item.priority),
12660 },
12661 write.target.as_ref(),
12662 &write.depends_on,
12663 )
12664 .await
12665 }
12666 async fn write_document_assets(
12667 &self,
12668 write: &ItemWrite<Document>,
12669 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
12670 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
12671 // A document takes part in no dependency graph, so there is no far end to write
12672 // natively and none to record: a caller naming one is told so rather than having it
12673 // stored under the reserved key, where a later read would report an edge the
12674 // contract says cannot exist.
12675 if !write.depends_on.is_empty() {
12676 return Err(SourceError::Refused {
12677 message: format!(
12678 "this write names {} dependencies for a document, and a document takes \
12679 part in no dependency graph; next: put the dependency on the task or \
12680 project the document is about",
12681 write.depends_on.len()
12682 ),
12683 });
12684 }
12685 self.write_item(
12686 &Incoming {
12687 written: Written::Document,
12688 title: &write.item.title,
12689 content: write.item.content.as_deref(),
12690 assets,
12691 labels: &write.item.labels,
12692 metadata: &write.item.metadata,
12693 repositories: &write.item.repositories,
12694 classification: write.item.classification,
12695 parent: write.item.project.as_ref(),
12696 delivers: &[],
12697 delivered_by: &[],
12698 priority: None,
12699 },
12700 write.target.as_ref(),
12701 &[],
12702 )
12703 .await
12704 }
12705}
12706
12707/// What [`TaskSource::end_command`] leaves of this source's held state, asserted on the state
12708/// itself, for the two things no journey can observe.
12709///
12710/// The journeys in `crates/onetaskgraph-e2e/tests/e2e/end_command.rs` prove through the engine,
12711/// with and without the call, that a settlement, a board listing and a metadata search each
12712/// read afresh after it — the resolved records, the written-item overlay, the board and its
12713/// search, and the narrowed searches. What they cannot reach is the held field definitions,
12714/// because a status write naming an option a person deleted is refused the same whether or
12715/// not the list is held, and a poisoned lock, because nothing outside the source can panic
12716/// while one of its locks is held. So these assert those directly, and every other holder
12717/// beside them so a holder added later without a clear in the call fails here.
12718#[cfg(test)]
12719mod end_command_tests {
12720 use super::*;
12721
12722 struct Token;
12723
12724 impl SecretResolver for Token {
12725 fn get(&self, var: &str) -> Option<SecretString> {
12726 (var == "GH_PROJECTS_TOKEN").then(|| "test-token".into())
12727 }
12728 }
12729
12730 fn source() -> GitHubProjectsSource {
12731 let config = serde_json::from_value(json!({
12732 "owner": "octo-org", "project_number": 7, "repository": "acme/work",
12733 // Nothing here is sent: the source is only built and its state inspected.
12734 "endpoint": "http://127.0.0.1:9/graphql",
12735 }))
12736 .expect("a usable configuration");
12737 GitHubProjectsSource::new(&SourceName::new("work").unwrap(), config, &Token)
12738 .expect("the source builds")
12739 }
12740
12741 /// One issue as a board read answers it.
12742 fn resolved(source: &GitHubProjectsSource) -> Resolved {
12743 source
12744 .resolve(&json!({
12745 "id": "ITEM-1",
12746 "content": {"__typename": "Issue", "id": "I_1", "title": "Held",
12747 "body": "what a person may since have edited", "state": "OPEN",
12748 "stateReason": null, "url": null, "number": 1,
12749 "subIssuesSummary": {"total": 0},
12750 "labels": {"nodes": [], "pageInfo": {"hasNextPage": false}}},
12751 "fieldValues": {"nodes": [], "pageInfo": {"hasNextPage": false}},
12752 }))
12753 .expect("the item reads")
12754 .expect("an issue")
12755 }
12756
12757 /// Hold something in every holder the call clears, and the repository id it keeps.
12758 fn fill(source: &GitHubProjectsSource) {
12759 let item = resolved(source);
12760 source.created.lock().unwrap().push(item.clone());
12761 source.updated.lock().unwrap().push(item.clone());
12762 *source.board_cache.lock().unwrap() = Some(Board {
12763 id: "PVT-board".into(),
12764 fields: json!({"nodes": []}),
12765 items: vec![item.clone()],
12766 });
12767 *source.search_cache.lock().unwrap() = Some(vec![item.clone()]);
12768 source
12769 .narrowed_cache
12770 .lock()
12771 .unwrap()
12772 .insert("status:todo".into(), vec![item.clone()]);
12773 source.children_cache.lock().unwrap().insert(
12774 NativeId("P-1".into()),
12775 (NativeId("P-1".into()), vec![item.clone()]),
12776 );
12777 source
12778 .search_next
12779 .lock()
12780 .unwrap()
12781 .insert("status:todo".into(), Some("cursor".into()));
12782 source
12783 .resolved_cache
12784 .lock()
12785 .unwrap()
12786 .insert(item.id.clone(), item);
12787 *source.fields_cache.lock().unwrap() = Some(BoardFields {
12788 id: BoardId::parse("PVT-board").unwrap(),
12789 fields: json!({"nodes": []}),
12790 });
12791 source
12792 .repository_cache
12793 .lock()
12794 .unwrap()
12795 .insert(RepositoryTarget::parse("acme/work").unwrap(), "R_1".into());
12796 }
12797
12798 fn assert_dropped(source: &GitHubProjectsSource) {
12799 assert!(source.created().unwrap().is_empty(), "created");
12800 assert!(source.updated().unwrap().is_empty(), "updated");
12801 assert!(source.board_cache().unwrap().is_none(), "board");
12802 assert!(source.search_cache.lock().unwrap().is_none(), "search");
12803 assert!(source.narrowed_cache.lock().unwrap().is_empty(), "narrowed");
12804 assert!(
12805 source.children_cache.lock().unwrap().is_empty(),
12806 "project children"
12807 );
12808 assert!(
12809 source.search_next.lock().unwrap().is_empty(),
12810 "search paging"
12811 );
12812 assert!(
12813 source.resolved_cache().unwrap().is_empty(),
12814 "resolved records"
12815 );
12816 assert!(source.fields_cache().unwrap().is_none(), "board fields");
12817 assert_eq!(
12818 source.repository_cache().unwrap().len(),
12819 1,
12820 "a repository's node id stays valid and is kept"
12821 );
12822 }
12823
12824 fn end(source: &GitHubProjectsSource) {
12825 tokio::runtime::Builder::new_current_thread()
12826 .build()
12827 .unwrap()
12828 .block_on(source.end_command())
12829 .expect("the command ends");
12830 }
12831
12832 #[test]
12833 fn the_call_drops_every_item_search_and_board_read_and_keeps_repository_ids() {
12834 let source = source();
12835 fill(&source);
12836 end(&source);
12837 assert_dropped(&source);
12838 }
12839
12840 #[test]
12841 fn the_call_clears_a_lock_an_earlier_failure_poisoned() {
12842 fn poison<T: Send>(held: &Mutex<T>) {
12843 std::thread::scope(|scope| {
12844 let _ = scope
12845 .spawn(|| {
12846 let _guard = held.lock().unwrap();
12847 panic!("a failure while the lock is held");
12848 })
12849 .join();
12850 });
12851 assert!(held.is_poisoned());
12852 }
12853 let source = source();
12854 fill(&source);
12855 poison(&source.created);
12856 poison(&source.updated);
12857 poison(&source.board_cache);
12858 poison(&source.search_cache);
12859 poison(&source.narrowed_cache);
12860 poison(&source.search_next);
12861 poison(&source.resolved_cache);
12862 poison(&source.fields_cache);
12863 assert!(
12864 source.resolved_cache().is_err(),
12865 "a poisoned lock is refused before the call"
12866 );
12867 end(&source);
12868 assert_dropped(&source);
12869 }
12870}
12871
12872#[cfg(test)]
12873mod unprojectable_fields_tests {
12874 use super::*;
12875
12876 /// The field names `docs/metadata.md` says a `metadata_fields` entry may not name.
12877 fn documented() -> std::collections::BTreeSet<String> {
12878 let document = std::fs::read_to_string(
12879 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
12880 )
12881 .expect("docs/metadata.md is readable");
12882 let document = document.split_whitespace().collect::<Vec<_>>().join(" ");
12883 let lead = "a `field` equal, ignoring case, to ";
12884 let start = document.find(lead).expect("the refused-field sentence") + lead.len();
12885 let sentence = &document[start..];
12886 let sentence = &sentence[..sentence
12887 .find("; and two entries naming one field")
12888 .expect("the refused-field sentence ends at the duplicate rule")];
12889 let (own, github) = sentence
12890 .split_once(" or a field GitHub owns on every board (")
12891 .expect("the sentence names GitHub's own fields");
12892 own.split('`')
12893 .skip(1)
12894 .step_by(2)
12895 .chain(
12896 github
12897 .strip_suffix(')')
12898 .expect("GitHub's own fields close the sentence")
12899 .split(", "),
12900 )
12901 .map(str::to_owned)
12902 .collect()
12903 }
12904
12905 #[test]
12906 fn the_documented_refused_fields_are_exactly_the_ones_the_configuration_refuses() {
12907 let refused: std::collections::BTreeSet<String> = UNPROJECTABLE_FIELDS
12908 .iter()
12909 .map(|&name| name.to_owned())
12910 .collect();
12911 assert_eq!(documented(), refused, "the fields docs/metadata.md lists");
12912 let instance = SourceName::new("work").unwrap();
12913 for name in UNPROJECTABLE_FIELDS {
12914 for spelled in [name.to_owned(), name.to_uppercase()] {
12915 let entry = MetadataFieldConfig {
12916 field: spelled.clone(),
12917 key: "team.machine".to_owned(),
12918 path: Vec::new(),
12919 };
12920 let refused = MetadataField::resolve(vec![entry], &instance)
12921 .expect_err("an unprojectable field is refused");
12922 assert!(
12923 refused.to_string().contains(&format!("{name:?}")),
12924 "{spelled}: {refused}"
12925 );
12926 }
12927 }
12928 }
12929}