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 | 4 / 5 | ORIGIN_LOOKUPS (the origin, the board's fields and the repository's node and numeric ids together; two points), CREATE_ISSUE filing the issue on the board and under its project, CREATED_BOARD_ITEMS once GitHub has added it, WRITE_FIELD_VALUES |
308//! | copy --create | 4 | CREATION_CONTEXT, CREATE_ISSUE, CREATED_BOARD_ITEMS, WRITE_FIELD_VALUES: the new copy with no origin to ask about |
309//! | bound copy | 3 | ISSUE (with the board's fields and the issue's `blockedBy`, so no BOARD_FIELDS or ISSUE_DEPENDENCIES), UPDATE_FIELDS when a board field differs, then UPDATE_ISSUE last carrying only the title, body or state that differs — none, when nothing does |
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//! | document metadata, `--expect` a version | 2 | ISSUE, then UPDATE_ISSUE only when the issue is still at that version — the precondition GitHub's own update cannot take — primed with what the read answered |
322//! | 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 |
323//! | record only | 1 | ISSUE |
324//!
325//! <!-- github-search-paging:start -->
326//! Board-scoped text, metadata, project-name and comment-activity searches send every
327//! page at `first = 20` (SEARCH_PAGE_SIZE), the SEARCH_ISSUES document's one-point
328//! ceiling. A later page is sent only when `hasNextPage` is true and the caller still
329//! needs rows. A page is never resized to the rows still needed: GitHub orders one
330//! search differently at different page sizes, so one fixed size makes a paged walk
331//! send exactly the requests one whole read sends, and the answer's order is the order
332//! those pages arrive in. A page below twenty would cost the same one point, and GitHub
333//! prices this document by rows, so twenty-row pages cost per row what 100-row pages do.
334//! Project-name lookup continues until an exact match or exhaustion. A task limit bounds
335//! returned and fetched pages: a limit is sliced from the pages it needs, and local
336//! confirmation can require more candidates than matching rows. Walking all pages
337//! returns the whole answer. The opaque version-4 source cursor carries GitHub's page
338//! cursor and how far into that page the last answer stopped, and resumes in the same
339//! process or a new one, without duplicates or gaps. It carries no rows: one process
340//! sends each page's search once, and a new process re-reads only the page it resumes
341//! in, then sends a further page once, never as a re-read, only when its limit still
342//! needs rows. Every request either walk sends is the one a whole read sends for that page. Own writes replace stale index
343//! copies and complete missing rows at exhaustion. Cache entries are whole GitHub pages,
344//! so a small answer cannot truncate a wider question. Origin pages remain three; whole-board sizing is unchanged.
345//! Read-after-write is a per-process guarantee. A cursor resumed in a new process is
346//! not required to include the original process's writes still omitted by the index.
347//! <!-- github-search-paging:end -->
348//!
349//! The board half of an issue — its board item's id, its `Status` option and this
350//! source's origin text field — rides along on `Issue.projectItems` in the first three, so
351//! an item reached any of those ways resolves through the same
352//! [`GitHubProjectsSource::resolve`] the board walk uses and reports the same title, the
353//! same status, the same labels and the same qualified id. That connection comes back a
354//! *page* at a time, at `BOARD_ITEMS_PAGE_SIZE`, so the entry for this board is looked for
355//! on the page in hand and — only if that page reports more of the connection — in the
356//! last row's read of that one issue's memberships, resumed from the page's own cursor and
357//! walked to exhaustion. An issue with no entry for *this* board is not this source's to
358//! report, which is what keeps an id naming another repository's issue from being answered
359//! as an item of this board; and because the page is where the search starts rather than
360//! where it ends, that answer is one about a connection read to exhaustion and never about
361//! an unread page. Nothing costs the extra read but an issue on more boards than a page
362//! holds: an issue this board really does not hold reports no next page, so its
363//! memberships are already exhausted where they arrived.
364//!
365//! **No document here selects the board's own `Labels` field, and nothing is lost by
366//! that.** An item's labels are read from its content alone, wherever that content is
367//! reached: the three documents above select `Issue.labels` on the fragment, and
368//! [`graphql::BOARD`] selects the same connection on the `... on Issue` arm of its
369//! `content`. A board's `Labels` field is not one anybody fills in: it is a built-in
370//! `ProjectV2FieldType`, it is absent from `ProjectV2CustomFieldType` so no project can
371//! create one, and `ProjectV2FieldValue` — the whole of what
372//! `updateProjectV2ItemFieldValue` accepts — offers no way to write one. So GitHub derives
373//! it from the content, for every content type it exists on, and there is nothing it can
374//! hold that the content does not already say: for an `Issue` it *is* that issue's own
375//! labels, so selecting it beside them unions a set with itself.
376//!
377//! **A draft loses nothing by that either**, which is the reasoning this paragraph once had
378//! backwards. `DraftIssue` exposes no `labels` field, and by the three schema facts above
379//! it cannot carry a board `Labels` value to be derived from one — so a draft has nothing
380//! to select *and nothing to lose*, and reports no labels at all. A `PullRequest` item is
381//! discarded by [`GitHubProjectsSource::resolve`] before labels are read. Both halves are
382//! held to that by tests in `tests/plugin.rs`: the four ways an item is reached report one
383//! label set, and that set is the fixture issue's own, by
384//! `an_item_reports_the_same_labels_title_status_and_id_however_it_is_reached`; and a board
385//! item whose content is a draft reports an empty set, by
386//! `a_board_item_whose_content_is_a_draft_reports_no_labels_at_all`. The absence of the
387//! selection is held over [`graphql::DOCUMENTS`] by
388//! `no_document_selects_the_boards_own_labels_field`.
389//!
390//! The whole-board row is still the board's own item connection, and deliberately: a
391//! **draft** board item is not an issue, so no search can list one, and the reads that have
392//! to answer for the whole board are the ones whose cost is the board's size anyway.
393//!
394//! **A question about one item this source already names by id never lists the board.**
395//! Whether that item is on this board, and what its board fields are, is answered by reading
396//! that item — its own `Issue.projectItems`, walked to exhaustion by
397//! [`GitHubProjectsSource::resolve_issue`], or a draft's own board item — and never by
398//! looking for it in [`graphql::BOARD`]'s `items` or in a listing this command already
399//! holds. That covers a write's destination, the project a new item is filed under, a
400//! same-source far end a dependency names, a status write, the dependency slot a draft keeps,
401//! and the delete that takes back an item a copy made. What such a write needs of the board
402//! and the item does not carry — the board's id, the `Status` and origin field definitions —
403//! comes from [`graphql::BOARD_FIELDS`], which reads no item at all. The reason is evidence,
404//! not economy alone: `ProjectV2.items` is a projection that lags the membership GitHub
405//! itself reports — an issue added with `addProjectV2ItemById` can be missing from it for
406//! minutes. Scanning this host's 842-item board has refused a document copy and an update
407//! even though the items' own reads named that board. A scan there gives the wrong answer
408//! as well as paying for every page. So a `board.items` lookup does not belong on any of
409//! those paths.
410//!
411//! **What a read may return is capped too, and that cap is on the document rather than on
412//! the board.** GitHub limits the number of nodes **one query may return** to
413//! [`NODE_COUNT_LIMIT`] and refuses a query above that before executing it: the answer is
414//! an error naming the connection the count crossed at, not a slow or a partial result.
415//! Every board this source reads is refused the same way, so no board is too big for these
416//! documents and none is small enough to save one that is over.
417//!
418//! The count is arithmetic over the document's own text: each connection contributes the
419//! `first:` it asks for, counts **multiply** down a nested path and **sum** across sibling
420//! paths. Those are [GitHub's published rules][node-limits] and this workspace does not
421//! restate them — `github-graphql-node-count` implements them, and
422//! [`worst_case_node_count`] under [`largest_page_sizes`] is where every node count here
423//! comes from. `every_document_this_source_sends_stays_under_githubs_node_limit`, in
424//! `tests/node_count.rs`, recomputes every document in [`graphql::DOCUMENTS`] from that
425//! same text on every run and fails naming any that reaches the limit — so a connection
426//! added to a shared fragment is caught there rather than by GitHub.
427//!
428//! What decides those counts is the page sizes: [`MAX_PAGE_SIZE`] on the outer page,
429//! `NESTED_PAGE_SIZE` on the connections hanging off one item, and
430//! `BOARD_ITEMS_PAGE_SIZE` on the page of an issue's board memberships a read carries.
431//! `$nestedFirst` is spent twice down one path of a board read, so that constant is
432//! effectively squared there, which is why it is the one the limit is most sensitive to.
433//! `BOARD_ITEMS_PAGE_SIZE` is small for a reason of its own, recorded beside it: what a
434//! page of memberships misses is recovered by one further read rather than refused, so it
435//! buys a bound every read pays for at the price of a request only a multi-board issue
436//! pays.
437//!
438//! **`nodeCount` and `cost` are two numbers against two limits, and both are computed
439//! offline here — per document, one document at a time.** `nodeCount` is the one above: the
440//! most nodes one query may return, checked per query and bounded by [`NODE_COUNT_LIMIT`].
441//! `cost` is rate-limit points, metered per hour across everything one credential does; it
442//! is what the two limiters [`Limiter`] tells apart meter, and a document under
443//! [`NODE_COUNT_LIMIT`] still says nothing about its price. [`worst_case_point_cost`] is
444//! that second number, and `tests/point_cost.rs` pins every document in
445//! [`graphql::DOCUMENTS`] at what it costs — there being no per-call point ceiling to hold
446//! one under, the pin itself is the check. The credentialed lane reconciles both figures
447//! against GitHub's own, off a probe it already sends.
448//!
449//! **What is pinned that way is a per-document price and never a session's.** The record in
450//! `session-cost.md` measures the two quantities a whole session can be counted in offline —
451//! **requests** and **worst-case nodes** — and neither is points. What one whole session
452//! consumes of the hourly point allowance is observable only from a credentialed run's own
453//! `x-ratelimit-*` headers, which is what [`accounting`] fills its per-budget figures from
454//! and what `tests/live.rs` prints at the end of every run.
455//!
456//! [node-limits]: https://docs.github.com/en/graphql/overview/rate-limits-and-node-limits-for-the-graphql-api
457//!
458//! **Where a read-after-write guarantee comes from, since neither of GitHub's two
459//! enumerations of a board can supply one alone.** Resolving a node id is strongly
460//! consistent, so a read by id and a project's own sub-issues are already current. The
461//! other two are not, and they are behind by different amounts and in different directions:
462//!
463//! - GitHub's **issue search** is an index and answers a write made moments ago with the
464//! value from before it — usually for a second or two.
465//! - **`ProjectV2.items`** is a projection GitHub rebuilds behind the write, and an item put
466//! on a board with `addProjectV2ItemById` can be **absent** from it — not present with its
467//! content withheld, absent, with the connection walked to its own `hasNextPage: false` —
468//! for *minutes*, while `Issue.projectItems` names the same membership at once.
469//!
470//! That second one is a measurement rather than a caution. This repository's own
471//! credentialed journey writes a project and waits for the board to report it, then writes a
472//! task and waits for the same thing seconds later on the same board: the project wait is
473//! answered through the search and converged in two or three attempts in each of three runs,
474//! and the task wait is answered through `ProjectV2.items` and converged in none of them
475//! inside thirty. Separately, an item added to a second and larger board was read back by
476//! `Issue.projectItems` on that board's own id while every one of that connection's nine
477//! pages, walked to exhaustion nine minutes after the add, did not name it. Reading a board
478//! through the lagging one alone is what had a board read deny an issue that had certainly
479//! landed on it.
480//!
481//! So [`GitHubProjectsSource::board`] is the **union** of both — each search result still
482//! admitted only on this board's own strongly-consistent `Issue.projectItems`, and neither
483//! enumeration dropped, because only `ProjectV2.items` lists a board draft and only the
484//! search reports what the projection is behind on. What closes the last
485//! gap, the one where both are behind, is [`GitHubProjectsSource::created`]: every read this
486//! source answers is completed with what this process itself wrote, so an item created
487//! seconds ago is reported whether or not GitHub has caught up. Nothing else is remembered,
488//! nothing is written down, and the record dies with the process. **A wait that has to
489//! observe GitHub's own data cannot be answered from that record** — which is why the
490//! credentialed journey asks through a source built afresh, and why the union above rather
491//! than a longer wait is what makes such a wait converge.
492//!
493//! **A narrowed read is the same bargain, stated for each of the three predicates it
494//! answers.** A read carrying a text, metadata or origin predicate asks GitHub's index rather
495//! than walking the board, and every such answer is completed with what this process wrote —
496//! its [`created`](GitHubProjectsSource::created) record and every existing item it wrote,
497//! each filtered by the same predicates as the rest — so an item this command wrote a moment
498//! ago is returned by a query that matches it whether or not the index has caught up. An item
499//! a caller holds the id of is read by that id, with `node(id:)`, which is strongly
500//! consistent. What is left is stated rather than papered over:
501//!
502//! | Read | Finds | Behind by |
503//! | --- | --- | --- |
504//! | text, metadata | the issue search for the phrases | what another process wrote in the last second or two, until GitHub indexes it |
505//! | 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 |
506//! | 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 |
507//! | origin, third read | this process's own writes | nothing |
508//!
509//! So an origin carrier another process added within the last second or two, before either
510//! index has it, can be missing from an origin query, and one written by the release before
511//! this one — its origin in the field alone — can be missing for as long as the board's own
512//! item connection is behind on it. A copy that must not duplicate its own earlier write
513//! relies on the link it records, not on either index. **A board draft is not an issue**, so
514//! a draft is never returned by a text, metadata or origin query, whatever it holds: no search
515//! lists one, the origin lookup drops any the board's own field filter names, and one this
516//! process wrote is not added back either.
517//!
518//! **The origin lives in the board field, and the body holds a mirror of it.** A write that
519//! carries an origin writes it to the `onetaskgraph.origin` text field and also into the
520//! body's metadata slot, so the issue search can find it in seconds. The field is
521//! authoritative: this source reads an item's origin from the field alone, so a slot that
522//! disagrees with it, or holds one where the field holds none, is never read as a second
523//! origin — and the release before this one reads the slot, drops that key's copy for the
524//! field's, and sees the same one origin.
525//!
526//! Filtering happens before paging, so a page of a filtered result is a page of the
527//! survivors rather than the survivors of a page. Label matching and the substring rule a
528//! text candidate is confirmed by answer the same question the same way the local Markdown
529//! source's do; which candidates a text search has to confirm is GitHub's word match, which
530//! is the one place the two sources can answer the same text differently.
531//!
532//! <!-- llmlint: ignore[contracts_have_one_source_or_a_drift_gate] The declaration itself
533//! has one source, `capabilities`, and the note above is the reasoning behind it rather
534//! than a second copy of it: without the three facts recorded here a reader takes the
535//! uniform `Native` for a lie and reverts it. The drift gate on the declaration is this
536//! crate's own capabilities test, which pins every field of it against a fully spelled-out
537//! `Capabilities` literal — a struct with no `Default`, so a field added to the contract
538//! fails to compile there rather than going unasserted. -->
539//! The fixture-server tests above run wherever this crate is selected; the credentialed
540//! lane runs in the same required check, beside them, and can fail it — it verifies the
541//! 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,
542//! one filed under neither, a label on one of the three and a closed status on another —
543//! because that shape is what tells an honoured predicate from an ignored one: a board
544//! holding a single project answers a project filter the same way whether or not this
545//! source applies it, which is exactly how the defect above went unseen.
546//!
547//! That lane writes only to the board `GH_PROJECTS_OWNER` and `GH_PROJECTS_NUMBER` name,
548//! and the scratch repository `GH_PROJECTS_REPOSITORY` names:
549//! `nickderobertis/onetaskgraph-live-scratch`. It refuses the core repository before any
550//! session or request, independently of the live demand. Fix that variable in the machine's
551//! onetaskgraph `secrets.env` or the environment it pushes from, such as ai-orchestrator's
552//! `.env`. The targets are declared once in `onetaskgraph_github_live`, the lane's own
553//! policy crate; absent credentials or nominations otherwise skip.
554//!
555//! GitHub Actions artifacts carry `ci-<run id>-<attempt>-<micros>`, naming their writing
556//! run and attempt; invalid Actions identity refuses before writing. Other runs retain
557//! `<host>-<process>-<micros>`. Own cleanup matches the whole stamp. Machine residue stays
558//! the owning machine's lock sweep's; Linear always keeps that form and is unaffected.
559//! The hourly janitor is cleanup, never a test lane: scratch CI residue is removed only
560//! after its run reads back as `completed`, immediately before the listed-artifact batch.
561//! Failed or incomplete ownership reads preserve residue. A 24-hour waiting period
562//! is a margin, never the ownership authorisation. Cleanup leaves machine stamps
563//! and the board's `onetaskgraph.origin` field untouched.
564//!
565//! # What a session of requests costs, and where the report is
566//!
567//! This source records **every** request it sends into [`accounting::Accounting`], at
568//! `send_once` — the one place a request leaves this crate, which is why a read path added
569//! later is counted without anybody remembering to count it. That is the whole of what this
570//! crate adds to the arrangement; [`accounting`] is where what a record carries, how a
571//! session's spend is arrived at, and what it deliberately does not know are set out.
572//!
573//! What one whole session of the live journey costs, counted that way against this crate's
574//! loopback fixture board, is written down in `session-cost.md` beside this crate — with the
575//! reduction it came out of, and with what it does and does not say about rate-limit points.
576//!
577//! [`GitHubProjectsSource::accounting`] is the read: a snapshot to hold and compare, which
578//! [`accounting::Session::report`] renders the session report from. It is on the ordinary
579//! code path — no environment variable, no feature, no build configuration — because an
580//! instrument nobody switches on measures nothing, and
581//! [`Plugin::build_recording_into`] is how a caller making its own calls beside this
582//! source's counts the whole session rather than this source's share. The credentialed lane
583//! in `tests/live.rs` does exactly that, and prints the report at the end of every run,
584//! passed or failed.
585//!
586//! **A live session refuses to start unless the account can afford it.** Before it does any
587//! of the work it exists to do, the journey makes one request — `GET /rate_limit`, which
588//! GitHub documents as not counting against the REST rate limit and which answers both of
589//! its budgets at once — and starts only if, for each of them, what remains minus this
590//! session's estimated cost is still at least
591//! `onetaskgraph_live::RETAINED_BUFFER` — twenty per cent — of that budget's whole
592//! allowance. A session that cannot **declines**: it did not run, so it is
593//! neither a pass nor a failing assertion, and it says which budget was short, that budget's
594//! limit, what remained, the estimate, the buffer and when it resets — then stops, without
595//! waiting for the budget to come back. The estimate is derived offline from
596//! `tests/fixtures/session-cost.txt` and a cost model stated in `tests/journey/budget.rs`,
597//! which is also where the published rule that model rests on is cited; the accounting
598//! above records the gate's own read like any other request, and
599//! [`accounting::Session::report`] prints the estimate beside what the session really spent.
600//!
601//! **GitHub is the authority on both of its own numbers, and the credentialed lane goes and
602//! asks it.** Everything above computes `nodeCount` and `cost` offline from a document's own
603//! text, which is what lets it run on every platform and on a pull request from a fork with
604//! no credential — and that is what actually stops a regression merging. But an offline
605//! arithmetic can only ever agree with itself: if GitHub changes its rules, this workspace
606//! goes on computing the old answer and nothing notices. So `tests/live.rs` reconciles them.
607//! GitHub's schema exposes `rateLimit(dryRun: true)`, whose `nodeCount` is *"the maximum
608//! number of nodes this query may return"* and whose `cost` is what that document would
609//! spend, both for a document **without executing it**, and the lane asks it for every query
610//! document this source sends, under the largest bindings this source sends, and fails when
611//! GitHub's figure and [`worst_case_node_count`] or [`worst_case_point_cost`] disagree. A
612//! mutation is skipped, because `rateLimit` is a field of `Query` and cannot be asked about
613//! one; the offline pins still cover it. It records what those calls reported about the
614//! account's own allowance, because whether asking is free is a thing to observe rather than
615//! to assume. Two quantities, not one: [`NODE_COUNT_LIMIT`] bounds `nodeCount` per query,
616//! and `cost` is metered against an hourly allowance the accounting above reads off a
617//! credentialed run's own response headers.
618//!
619//! **GitHub has two rate limiters and this source is refused by both, so nothing here
620//! treats them as one thing.** The primary budget is the hourly allowance `gh api
621//! rate_limit` reports; the secondary limiter is a burst limiter over content-generating
622//! requests, and *nothing* reports it. Which one refused decides the operator's next step,
623//! so [`Limiter`] is a type rather than a detail, and it is what [`MIN_MUTATION_INTERVAL_MS`],
624//! [`GitHubProjectsSource::board_cache`] and [`GitHubProjectsSource::graphql`] each answer
625//! one part of.
626#![deny(missing_docs)]
627
628use std::collections::BTreeMap;
629use std::sync::{Arc, Mutex};
630use std::time::Duration;
631
632use chrono::{DateTime, Utc};
633use onetaskgraph_plugin_api::{
634 Capabilities, Classification, ClosedAs, Comment, CommentBody, CommentOrigin, Completion,
635 ContradictedItem, Coverage, Cursor, DependencyEdge, DependencyEndpoint, DependencyKind,
636 DependencySupport, Designator, Direction, Document, DocumentQuery, DocumentVersionCoverage,
637 Health, HeldTask, IssueHolding, IssueRef, ItemKind, ItemWrite, Label, LabelFilter, Location,
638 MetadataKey, Metering, NativeId, NewComment, Page, PageRequest, Priority, Project,
639 ProjectFilter, ProjectQuery, ProjectVersionCoverage, Repository, SecretResolver, SharedClock,
640 SourceError, SourceName, SourcePlugin, Status, StatusCategory, StatusContradiction,
641 StatusMapping, Support, Task, TaskDetailRead, TaskQuery, TaskRef, TaskSource, TaskUpdate,
642 TaskUpdateOutcome, TextFields, TextQuery, UnmappedStatus, UpdatedField, VersionCoverage,
643 WaitCause, WriteJournal, WriteSupport, system_clock,
644};
645use reqwest::{Client, StatusCode, Url};
646use schemars::{Schema, schema_for};
647use secrecy::{ExposeSecret, SecretString};
648use serde::{Deserialize, Serialize};
649use serde_json::{Value, json};
650
651pub mod accounting;
652mod assets;
653pub mod change_token;
654mod expected;
655pub use expected::{CONTEXT_VERSION, WHOLE_MEMBERS, context_shapes};
656mod pacing;
657mod visibility;
658
659use accounting::Accounting;
660
661/// The registry name for this plugin.
662pub const KIND: &str = "github-projects";
663/// GitHub's maximum connection page size.
664pub const MAX_PAGE_SIZE: u32 = 100;
665/// Every page of a board-scoped narrowing search: 20 rows, one point of SEARCH_ISSUES, the
666/// most one point buys. GitHub prices that document by rows, so pages of 20 cost what pages
667/// of 100 cost per row, and a page of fewer than 20 costs the same one point.
668pub const SEARCH_PAGE_SIZE: u32 = 20;
669/// How many items one [`graphql::ISSUE_DETAILS`] request reads, each with the first page of
670/// its comments: the largest batch the node-count model prices at one point.
671///
672/// Each aliased item is resolved once, and what GitHub charges for it is the connections
673/// under it — its labels, its page of board memberships, the field values of each of those
674/// three memberships, and its comments: six requests' worth of the aggregate GitHub divides
675/// by a hundred and rounds. Twenty-four items come to 144, which rounds to one point;
676/// twenty-five come to 150, which rounds to two. `tests/point_cost.rs` prices the document at
677/// one point and fails if one item more would still be priced at one.
678pub const DETAIL_BATCH: usize = 24;
679/// How many issue references one [`graphql::ISSUES_BY_REFERENCE`] request reads.
680///
681/// Each reference asks GitHub for one connection — a page of its board memberships, each with
682/// its `Status` value read by name rather than through a connection of field values — so fifty
683/// come to fifty requests' worth of the aggregate GitHub divides by a hundred, which is its
684/// one-point minimum, and the batch a landing's closures are read in costs one point per fifty
685/// issues per source. `tests/point_cost.rs` prices the document at one point.
686pub const REFERENCE_BATCH: usize = 50;
687/// How many items one [`graphql::ISSUE_COPY_DETAILS`] request reads: each with the first page
688/// of its comments and its `blockedBy`, the largest batch the node-count model prices at one
689/// point.
690///
691/// The six requests' worth an item of [`DETAIL_BATCH`] costs, and its `blockedBy` connection
692/// besides: seven. Twenty-one items come to 147, which rounds to one point; twenty-two come to
693/// 154, which rounds to two. `tests/point_cost.rs` prices the document at one point and fails
694/// if one item more would still be priced at one.
695pub const COPY_DETAIL_BATCH: usize = 21;
696/// How many mutations one aliased request of a copy's writes carries: [`graphql::CREATE_ISSUES`],
697/// [`graphql::WRITE_FIELD_VALUES`], [`graphql::CLOSE_ISSUES`] and [`graphql::ADD_BLOCKED_BYS`].
698///
699/// Eleven is what GitHub was seen to accept in one request — the timing spike
700/// (`board-copy-speed-2026-10-18-spike-copy-timing-report`) sent eleven aliased mutations of four
701/// kinds, three `createIssue`, three `addProjectV2ItemById`, three field updates, an
702/// `addSubIssue` and an `addBlockedBy`, and every one ran — and no more was established.
703pub const MUTATION_BATCH: usize = 11;
704/// How many origins one [`graphql::ORIGIN_LOOKUPS`] request asks about: the nine records of a
705/// plan and the project's document, and no more, since each carries a page of the board's field
706/// filter and one of the issue search.
707pub const ORIGIN_BATCH: usize = 10;
708
709/// The most nodes any one document this source sends may be asked to return.
710///
711/// GitHub's own published per-query ceiling, taken from
712/// [`github_graphql_node_count::NODE_LIMIT`] rather than written out again here, so this
713/// workspace cannot hold a stale copy of somebody else's number. A query above it is
714/// **refused before it is executed**, whoever is asking and whatever board they are
715/// asking about — so this is a bound on the documents rather than a budget that runs out.
716///
717/// This is `nodeCount`, the maximum number of nodes *one query may return*. It is not
718/// `cost`, the rate-limit points a call spends against an hourly allowance shared by
719/// everything the credential does — two numbers against two limits, and this constant
720/// bounds only the first. The second is computed offline too, per document:
721/// [`worst_case_point_cost`], pinned for every document in [`graphql::DOCUMENTS`] by
722/// `tests/point_cost.rs`, and reconciled against GitHub's own `cost` by the credentialed
723/// lane. There is no constant like this one to hold a price under, because points are an
724/// hourly allowance rather than a per-call bound.
725///
726/// Neither is a session's price. What `session-cost.md` records of a whole session is its
727/// **requests** and its **worst-case nodes**; what a whole session spends in points is
728/// reported only by a credentialed run's own `x-ratelimit-*` headers, through
729/// [`accounting`]. The module section on the three ways this source reaches an item says how
730/// the count is arrived at, and which of the page sizes below decide it.
731pub const NODE_COUNT_LIMIT: u64 = github_graphql_node_count::NODE_LIMIT;
732
733/// Nested connection size for the connections that hang off one item.
734///
735/// It multiplies through every document that reaches an item under a page — the count
736/// rules multiply down a nested path — so it is the constant [`NODE_COUNT_LIMIT`] is most
737/// sensitive to. `tests/node_count.rs` is what holds the pair together: it recomputes
738/// every document under these constants and fails naming any that reaches the limit, so
739/// raising this is caught there rather than by GitHub.
740const NESTED_PAGE_SIZE: u32 = 50;
741/// How many of one issue's board memberships are read when an issue is reached directly.
742///
743/// An issue reached through a search or through its own node id carries its board half in
744/// `Issue.projectItems`, and only the entry for *this* board is read. This connection sits
745/// under a page of issues, so every point of it multiplies through the whole document and
746/// is paid for whether or not any issue is on a second board — which is why it is
747/// deliberately far smaller than [`NESTED_PAGE_SIZE`].
748///
749/// **Three, because what a page misses is now recovered rather than refused**, and the
750/// recovery is what the value is chosen against. An issue whose entry for this board sits
751/// past this page costs one further request — [`graphql::ISSUE_BOARD_ITEMS`], resumed from
752/// that page's own cursor — so the value trades a bound every read pays for a request only
753/// a multi-board issue pays. At one, a deployment whose issues commonly sit on two or more
754/// boards would pay that request *per issue*, which is order N against the one page per
755/// hundred issues a read costs today. At three it is only reached by an issue on four or
756/// more boards at once, which keeps the recovery path exceptional rather than routine for
757/// a plausible deployment.
758const BOARD_ITEMS_PAGE_SIZE: u32 = 3;
759/// How many carriers of one copy origin one page of [`graphql::ORIGIN_LOOKUP`] asks each of
760/// its two connections for.
761///
762/// An origin names one item, so the answer an origin lookup expects is one carrier, and a
763/// second is a duplicate a copy already takes the first of. Both connections are walked to
764/// exhaustion whatever this is, so it decides how many requests an unusual answer costs and
765/// never what the answer is. It is small because every point of it is paid on every lookup,
766/// and a copy makes one lookup per item it has no link for: at three, ten lookups cost fewer
767/// worst-case nodes than the one whole-board read they replaced.
768const ORIGIN_PAGE_SIZE: u32 = 3;
769
770/// How many of one project's sub-issues one [`graphql::SUB_ISSUES`] page asks for: the most
771/// one point buys, since every row carries six connections GitHub charges for once per row.
772/// `session-cost.md` derives it; `tests/point_cost.rs` prices the document at one point and
773/// fails if one row more would still be priced at one.
774pub const MEMBER_PAGE_SIZE: u32 = 23;
775
776pub use github_graphql_node_count::{NodeCountError, Variables};
777
778/// The largest value this source can bind to each page-size variable its documents name.
779///
780/// Every `first:` in [`graphql`] reads one of these five, and each is capped at the
781/// constant above it wherever a caller's own limit could reach it — `$first` at
782/// [`MAX_PAGE_SIZE`], `$nestedFirst` at `NESTED_PAGE_SIZE`, `$boardItems` at
783/// `BOARD_ITEMS_PAGE_SIZE`, `$originFirst` at `ORIGIN_PAGE_SIZE`, `$memberFirst` at
784/// [`MEMBER_PAGE_SIZE`]. So this is the worst case a caller can drive this source to,
785/// not one configuration of it, which is what makes a bound computed under it a bound on
786/// every read.
787pub fn largest_page_sizes() -> Variables {
788 Variables::from([
789 ("first".to_owned(), MAX_PAGE_SIZE),
790 ("nestedFirst".to_owned(), NESTED_PAGE_SIZE),
791 ("boardItems".to_owned(), BOARD_ITEMS_PAGE_SIZE),
792 ("originFirst".to_owned(), ORIGIN_PAGE_SIZE),
793 ("memberFirst".to_owned(), MEMBER_PAGE_SIZE),
794 ])
795}
796
797/// The most nodes `document` could be asked to return, by GitHub's published rules.
798///
799/// Computed offline from the document's own text under [`largest_page_sizes`] — no
800/// network, no credential and no schema — by
801/// [`github_graphql_node_count::node_count`], which is where the rules themselves live.
802/// A document at or above [`NODE_COUNT_LIMIT`] is one GitHub refuses before executing, so
803/// this is what a check holds every document in [`graphql::DOCUMENTS`] below.
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_node_count(document: &str) -> Result<u64, NodeCountError> {
811 node_count(document, &largest_page_sizes())
812}
813
814/// The most rate-limit points one call of `document` could spend, by GitHub's published
815/// rules.
816///
817/// Computed offline from the document's own text under [`largest_page_sizes`] — no
818/// network, no credential and no schema — by
819/// [`github_graphql_node_count::point_cost`], which is where the rules themselves live.
820/// This is `cost`, metered **per hour** against the allowance one credential shares across
821/// everything it does; it is not `nodeCount`, which is [`worst_case_node_count`] and is
822/// bounded per query by [`NODE_COUNT_LIMIT`]. There is no per-call ceiling to hold this
823/// under, so what `tests/point_cost.rs` does with it is pin every document in
824/// [`graphql::DOCUMENTS`] at what it costs, and the credentialed lane reconciles those
825/// figures against GitHub's own reported `cost`.
826///
827/// # Errors
828///
829/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
830/// no single operation, or binds a page size this source does not name — each of which is
831/// a defect in the document rather than a number.
832pub fn worst_case_point_cost(document: &str) -> Result<u64, NodeCountError> {
833 github_graphql_node_count::point_cost(document, &largest_page_sizes())
834}
835
836/// The most nodes `document` could be asked to return under `variables`.
837///
838/// [`worst_case_node_count`] is this under [`largest_page_sizes`], and the accounting in
839/// [`accounting`] is this under the bindings one request really sent — one spelling of the
840/// calculation, so a bound checked offline and a cost recorded at run time cannot come to
841/// disagree. The rules themselves live in [`github_graphql_node_count::node_count`].
842///
843/// # Errors
844///
845/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
846/// no single operation, or binds a page size `variables` does not name.
847pub fn node_count(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
848 github_graphql_node_count::node_count(document, variables)
849}
850
851/// The issue-title prefix that makes a board issue a document.
852///
853/// A GitHub Projects board has no document type — it holds issues — so the discriminator
854/// is the title, and this is the whole of it: an issue whose title begins with these bytes
855/// is a document and every other issue is the task or project the sub-issue rule makes it.
856///
857/// It is spelled **once**, here, and read rather than restated everywhere else — including
858/// by the shared journeys, which take it from this constant so a board fixture cannot
859/// drift from what this source reads. `docs/metadata.md` records the two consequences that
860/// are not obvious from the bytes: the reported title has this prefix taken off, exactly
861/// as the body's metadata slot is taken off `content`, and this prefix is read *before*
862/// the sub-issue rule, so a design issue with no sub-issues is never an empty project.
863pub const DESIGN_TITLE_PREFIX: &str = "DESIGN: ";
864
865/// Exact GraphQL query documents issued by this plugin.
866///
867/// Keeping the production documents here lets the pinned-schema test validate the same
868/// bytes that are sent to GitHub, rather than a test-only copy which could drift
869/// independently. [`STATUS_OPTIONS_UPDATE`] is the sole document that may rewrite a board
870/// field, and its guarded caller always supplies the complete existing option set with ids.
871pub mod graphql {
872 /// The board half of one item: the field values every document here reads it from.
873 ///
874 /// A macro for the same reason [`board_issue!`] below is one, a level further in. This
875 /// selection is needed by that fragment, by [`BOARD`] under the board's own `items`,
876 /// and by [`ISSUE_BOARD_ITEMS`] under a membership walk — and all three have to produce
877 /// *the same value*, because
878 /// [`GitHubProjectsSource::resolve`](super::GitHubProjectsSource) reads them through
879 /// one path. Three spellings of it is what would drift, so there is one.
880 ///
881 /// The `Status` option and this source's own origin text field are the whole of it. It
882 /// selects no `ProjectV2ItemFieldLabelValue`: GitHub derives that field from the item's
883 /// content, so it holds nothing the content's own `labels` do not already say, and it
884 /// would sit a label connection two page sizes deep.
885 macro_rules! board_item_values {
886 () => {
887 r#"fieldValues(first:$nestedFirst){nodes{
888 ... on ProjectV2ItemFieldSingleSelectValue{name field{
889 ... on ProjectV2SingleSelectField{id name options{id name}}
890 }}
891 ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{id name}}}
892 }pageInfo{hasNextPage}}"#
893 };
894 }
895
896 /// The variable every document reading an issue declares for the relationship events its
897 /// change token counts, with its value as the default, so no caller binds it.
898 ///
899 /// A variable rather than a literal list because every argument a production document
900 /// passes is a declared variable, which `tests/schema.rs` holds them to, and every member of
901 /// its default to the pinned enum. Its default is the six event types GitHub records a
902 /// relationship added or removed with: a dependency on either end, as `blockedBy` and
903 /// `blocking`, so one a person makes from the far end moves this end's count too; and a
904 /// project membership on the task, as its parent, which GitHub records there whichever
905 /// issue the move was made from. A sub-issue's events on its parent are not counted: a
906 /// project carries no task token, and a copy writes nothing of a task its own sub-issues
907 /// decide. [`super::change_token`] says why the count is in the token.
908 macro_rules! relationship_events_variable {
909 () => {
910 ",$relationshipEvents:[IssueTimelineItemsItemType!]=[BLOCKED_BY_ADDED_EVENT,BLOCKED_BY_REMOVED_EVENT,BLOCKING_ADDED_EVENT,BLOCKING_REMOVED_EVENT,PARENT_ISSUE_ADDED_EVENT,PARENT_ISSUE_REMOVED_EVENT]"
911 };
912 }
913
914 /// Everything this source reads about one issue, wherever it reaches that issue.
915 ///
916 /// A macro rather than a constant so the three documents below can `concat!` it: one
917 /// spelling of these fields is what makes an issue read through the board-scoped
918 /// search, through its own node id, and through its project's sub-issue relationship
919 /// resolve to *the same* item, which is the whole of what
920 /// [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource) relies on.
921 ///
922 /// `projectItems` is what carries the board half of an issue: the board item's own id
923 /// and the [`board_item_values!`] above — the `Status` option and this source's origin
924 /// text field — that a `ProjectV2.items` read used to carry. It is asked for on the
925 /// issue rather than on the board, which is what makes the cost of a read proportional
926 /// to what was asked for instead of to the board's size.
927 ///
928 /// It carries a *page* of that connection, at `BOARD_ITEMS_PAGE_SIZE`, and its
929 /// `endCursor` is what [`ISSUE_BOARD_ITEMS`] resumes from when this board's entry is
930 /// not on that page: a page here is where the search for the entry starts rather than
931 /// where it ends.
932 ///
933 /// It does **not** select the board's `Labels` field value, and that is the whole of
934 /// what keeps the three documents below under [`NODE_COUNT_LIMIT`](super::NODE_COUNT_LIMIT):
935 /// a label connection there sits under `fieldValues` under `projectItems` under a page
936 /// of issues, spending `$nestedFirst` twice down one path, and took
937 /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] to 2,556,100 nodes against a limit of 500,000.
938 /// No label is lost — this is a fragment `on Issue`, whose own `labels` are selected
939 /// above, and that connection is where every label this source reports comes from. No
940 /// document in this module selects the board field any longer, [`BOARD`] included; the
941 /// module documentation records why nothing it could have held is lost.
942 macro_rules! board_issue {
943 () => {
944 concat!(
945 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}
946 labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}
947 projectItems(first:$boardItems){nodes{id updatedAt project{id number}
948 "#,
949 board_item_values!(),
950 r#"}pageInfo{hasNextPage endCursor}}}"#
951 )
952 };
953 }
954
955 /// Every issue of one board, found by a search scoped to that board.
956 ///
957 /// This is how the projects a board holds are listed, and it selects no `items`
958 /// connection on `ProjectV2`: the board is a *qualifier of the search* rather than a
959 /// container walked page by page, so nothing nested inside a board item is paid for.
960 /// Which of the issues it returns is a project is then read off `parent` — GitHub
961 /// accepts `-has:parent` as a search qualifier and silently ignores it, so the
962 /// discriminator has to be applied to the field, which is a scalar on the issue and
963 /// costs nothing.
964 pub const SEARCH_ISSUES: &str = concat!(
965 r#"query($search:String!,$type:SearchType!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
966 relationship_events_variable!(),
967 r#"){
968 search(query:$search,type:$type,first:$first,after:$after){
969 pageInfo{hasNextPage endCursor}
970 nodes{__typename ...BoardIssue}
971 }
972 }"#,
973 board_issue!()
974 );
975
976 /// What a dependency read selects of each far end: enough to say which kind of item it
977 /// is, its body included for the kind marker.
978 macro_rules! related_issue {
979 () => {
980 " fragment Related on Issue{id title body parent{id} subIssuesSummary{total}}"
981 };
982 }
983
984 /// One issue by its own node id, which is what a qualified id names here — with what a
985 /// write of it needs and the issue does not carry in `board_issue!`: the field
986 /// definitions of the boards it sits on, and the far ends of its `blockedBy`.
987 ///
988 /// Strongly consistent, unlike the search above: GitHub's issue search is an index and
989 /// answers a write made moments ago with the value from before it, and resolving a node
990 /// id does not.
991 ///
992 /// **Why those two ride here and not on the fragment.** A copy or an update of an item
993 /// reads it by its own id, and with them that one read answers everything the write
994 /// needs: which option ids the board's `Status` and `Priority` fields hold — so no
995 /// [`BOARD_FIELDS`] — and which issues block it, with each one's kind — so no
996 /// [`ISSUE_DEPENDENCIES`]. On `board_issue!` they would sit under the hundred-issue
997 /// pages of [`SEARCH_ISSUES`] and [`SUB_ISSUES`], multiplying both documents' price. Here
998 /// they sit under one item, and this read is still one point.
999 pub const ISSUE: &str = concat!(
1000 r#"query($id:ID!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1001 relationship_events_variable!(),
1002 r#"){
1003 node(id:$id){__typename ...BoardIssue ... on Issue{
1004 boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
1005 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1006 ... on ProjectV2Field{__typename id name dataType}
1007 }pageInfo{hasNextPage}}}}}
1008 blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
1009 }}
1010 }"#,
1011 board_issue!(),
1012 related_issue!()
1013 );
1014
1015 /// One project's tasks: the sub-issues of the issue that project is, each with a page of
1016 /// what blocks it.
1017 ///
1018 /// Paged at `$memberFirst` — [`MEMBER_PAGE_SIZE`](super::MEMBER_PAGE_SIZE), the most rows
1019 /// one point buys — rather than at `$first`, because every row carries six connections and
1020 /// a hundred-row page cost six points to list a project of ten.
1021 ///
1022 /// The work this costs is the project's own size. Nothing about it grows as the board
1023 /// gains projects, or as those projects gain tasks.
1024 ///
1025 /// **Why `blockedBy` rides here and on no other page of issues.** What reads a project's
1026 /// tasks reads their edges next — `project graph` draws them, a copy carries them — and
1027 /// without them here that is one [`ISSUE_DEPENDENCIES`] per task, so the requests a graph
1028 /// costs grow with its tasks rather than with the pages of them. Carried here, a task
1029 /// blocked by no more than `$nestedFirst` issues answers its forward edges from this read,
1030 /// exactly as an [`ISSUE`] read of it does, and only one blocked by more is asked again.
1031 /// It adds a connection under each issue of the page — one rate-limit point per page,
1032 /// and `$nestedFirst` nodes per issue — and is kept off [`SEARCH_ISSUES`], whose pages
1033 /// answer questions that never read an edge.
1034 ///
1035 /// **The project issue itself rides here too**, with the page of what blocks it, because
1036 /// the reader of a project's tasks reads the project next: a copy writing the project reads
1037 /// it and its edges before it writes them. Carried on the request that already names the
1038 /// project, the first page answers that read and the dependency read after it, at the
1039 /// state GitHub answered in this command, rather than spending one more read on an item
1040 /// the cache's token cannot vouch for whole. Each sub-issue is kept the same way, so a
1041 /// copy's read of a task this listing carried is answered by it rather than sent again.
1042 /// Only a copy's read-before-write takes them; every other read by id reads GitHub.
1043 pub const SUB_ISSUES: &str = concat!(
1044 r#"query($id:ID!,$memberFirst:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1045 relationship_events_variable!(),
1046 r#"){
1047 node(id:$id){__typename ...BoardIssue
1048 ... on Issue{blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1049 subIssues(first:$memberFirst,after:$after){
1050 pageInfo{hasNextPage endCursor}
1051 nodes{__typename ...BoardIssue ... on Issue{
1052 blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1053 }}
1054 }}}
1055 }"#,
1056 board_issue!(),
1057 related_issue!()
1058 );
1059
1060 /// What a read of the board's own `items` selects of each item's content.
1061 ///
1062 /// A macro for the reason [`board_item_values!`] is one: [`BOARD`] and [`ORIGIN_LOOKUP`]
1063 /// both walk `ProjectV2.items` and hand each item to one resolver, so they select its
1064 /// content by one spelling.
1065 macro_rules! board_item_content {
1066 () => {
1067 r#" content{
1068 ... 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}}}
1069 ... on PullRequest{__typename id}
1070 ... on DraftIssue{__typename id title body createdAt updatedAt}
1071 }"#
1072 };
1073 }
1074
1075 /// Reads the board's fields and one page of its items.
1076 pub const BOARD: &str = concat!(
1077 r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!,$duplicates:Boolean!"#,
1078 relationship_events_variable!(),
1079 r#"){
1080 owner:repositoryOwner(login:$owner){
1081 ... on ProjectV2Owner{projectV2(number:$number){...Board}}
1082 }
1083 } fragment Board on ProjectV2 { id title
1084 fields(first:$nestedFirst){nodes{
1085 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1086 ... on ProjectV2Field{__typename id name dataType}
1087 }pageInfo{hasNextPage}}
1088 items(first:$first,after:$after){nodes{id updatedAt "#,
1089 board_item_values!(),
1090 board_item_content!(),
1091 r#"} pageInfo{hasNextPage endCursor}}
1092 }"#
1093 );
1094
1095 /// Every carrier of one copy origin, by two reads in one request, and nothing else of
1096 /// the board.
1097 ///
1098 /// **`originItems`** is the board's own items narrowed by its own field filter —
1099 /// `ProjectV2.items(query:)`, which GitHub's schema declares as "Search query for
1100 /// filtering items" — to those whose `onetaskgraph.origin` text field holds the
1101 /// qualified id, quoted. It reads the field every carrier already holds, whichever release
1102 /// wrote it, and matches it exactly: measured on 2026-09-29 against a 394-item board,
1103 /// the quoted, the unquoted and the bare-value spellings each returned exactly the one
1104 /// carrier and a prefix of the value returned none. It is `ProjectV2.items`, so it lags a
1105 /// fresh `addProjectV2ItemById` the way that connection does.
1106 ///
1107 /// **`search`** is the board-scoped issue search for the same id as a quoted phrase in
1108 /// the body, which is where this source mirrors the origin into its metadata slot. GitHub
1109 /// indexes that comment, and the index catches up with a write in a second or two rather
1110 /// than in minutes, so it finds a carrier another process wrote that the first read is
1111 /// still behind on.
1112 ///
1113 /// Each connection pages at `$originFirst`, its own small size — see `ORIGIN_PAGE_SIZE`
1114 /// — and resumes from its own cursor; a connection already walked to its end is resumed
1115 /// from its last cursor, which answers an empty page. Every candidate either read returns
1116 /// is confirmed against its own origin field before it is reported, so a token match of
1117 /// the search or anything else the filter admits never is.
1118 ///
1119 /// The root is aliased `originItems` rather than `owner`, so nothing counting the board's
1120 /// own whole reads counts this one among them.
1121 pub const ORIGIN_LOOKUP: &str = concat!(
1122 r#"query($owner:String!,$number:Int!,$filter:String!,$search:String!,$type:SearchType!,$originFirst:Int!,$itemsAfter:String,$searchAfter:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1123 relationship_events_variable!(),
1124 r#"){
1125 originItems:repositoryOwner(login:$owner){
1126 ... on ProjectV2Owner{projectV2(number:$number){
1127 items(first:$originFirst,after:$itemsAfter,query:$filter){nodes{id updatedAt "#,
1128 board_item_values!(),
1129 board_item_content!(),
1130 r#"} pageInfo{hasNextPage endCursor}}
1131 }}
1132 }
1133 search(query:$search,type:$type,first:$originFirst,after:$searchAfter){
1134 pageInfo{hasNextPage endCursor}
1135 nodes{__typename ...BoardIssue}
1136 }
1137 }"#,
1138 board_issue!()
1139 );
1140
1141 /// Every closed item of the board, by the board's own field filter — what
1142 /// `task status reconcile` reads, and nothing else of the board.
1143 ///
1144 /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1145 /// `is:closed` alone, so a board whose open items are most of it is not read whole to find
1146 /// the closed ones. It is narrowed rather than trusted: every item it answers is confirmed
1147 /// closed, with a reason and a card that contradict each other, from the item node it
1148 /// already carries, so a filter that also let open items through would cost reads and
1149 /// write nothing wrong.
1150 ///
1151 /// The board's own id and field definitions ride along, as [`BOARD`] carries them, so the
1152 /// option writes that follow need no read of the board. The root is aliased `closedItems`
1153 /// rather than `owner`, so nothing counting the board's own whole reads counts this one
1154 /// among them.
1155 pub const CLOSED_ITEMS: &str = concat!(
1156 r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1157 relationship_events_variable!(),
1158 r#"){
1159 closedItems:repositoryOwner(login:$owner){
1160 ... on ProjectV2Owner{projectV2(number:$number){id
1161 fields(first:$nestedFirst){nodes{
1162 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1163 ... on ProjectV2Field{__typename id name dataType}
1164 }pageInfo{hasNextPage}}
1165 items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1166 board_item_values!(),
1167 board_item_content!(),
1168 r#"} pageInfo{hasNextPage endCursor}}
1169 }}
1170 }
1171 }"#
1172 );
1173
1174 /// One alias of [`ISSUES_BY_REFERENCE`]: the issue `$owner<n>/$name<n>#$number<n>` names.
1175 macro_rules! reference_alias {
1176 ($n:literal) => {
1177 concat!(
1178 "\n r",
1179 stringify!($n),
1180 ":repository(owner:$owner",
1181 stringify!($n),
1182 ",name:$name",
1183 stringify!($n),
1184 "){issue(number:$number",
1185 stringify!($n),
1186 "){...HeldIssue}}"
1187 )
1188 };
1189 }
1190
1191 /// [`REFERENCE_BATCH`](super::REFERENCE_BATCH) issues at once, each by its repository and
1192 /// number — the one read `task status complete` makes of a source, and nothing else of
1193 /// the board: no `items`, no search and no project read.
1194 ///
1195 /// **Its own fragment, lighter than `board_issue!`, and that is what makes fifty
1196 /// references one point.** It selects no labels, and of each board membership only the
1197 /// `Status` value, by name, with `fieldValueByName` — so each alias asks GitHub for one
1198 /// connection, its page of memberships, where the whole fragment asks for five. What a
1199 /// completion writes is a card and, at most, the issue's state, so the labels and the other
1200 /// field values it leaves out are never what it needs; an item read this way is held for
1201 /// that write alone and never answers another read. An issue whose entry for this board is
1202 /// past its first page of memberships is walked with [`ISSUE_BOARD_ITEMS`], exactly as
1203 /// every other read of an issue recovers one.
1204 ///
1205 /// Fixed-size, as [`ISSUE_DETAILS`] is, so there is one document to price: a batch of
1206 /// fewer references binds the slots it has none for to its last one.
1207 pub const ISSUES_BY_REFERENCE: &str = concat!(
1208 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!"#,
1209 relationship_events_variable!(),
1210 r#"){"#,
1211 reference_alias!(0),
1212 reference_alias!(1),
1213 reference_alias!(2),
1214 reference_alias!(3),
1215 reference_alias!(4),
1216 reference_alias!(5),
1217 reference_alias!(6),
1218 reference_alias!(7),
1219 reference_alias!(8),
1220 reference_alias!(9),
1221 reference_alias!(10),
1222 reference_alias!(11),
1223 reference_alias!(12),
1224 reference_alias!(13),
1225 reference_alias!(14),
1226 reference_alias!(15),
1227 reference_alias!(16),
1228 reference_alias!(17),
1229 reference_alias!(18),
1230 reference_alias!(19),
1231 reference_alias!(20),
1232 reference_alias!(21),
1233 reference_alias!(22),
1234 reference_alias!(23),
1235 reference_alias!(24),
1236 reference_alias!(25),
1237 reference_alias!(26),
1238 reference_alias!(27),
1239 reference_alias!(28),
1240 reference_alias!(29),
1241 reference_alias!(30),
1242 reference_alias!(31),
1243 reference_alias!(32),
1244 reference_alias!(33),
1245 reference_alias!(34),
1246 reference_alias!(35),
1247 reference_alias!(36),
1248 reference_alias!(37),
1249 reference_alias!(38),
1250 reference_alias!(39),
1251 reference_alias!(40),
1252 reference_alias!(41),
1253 reference_alias!(42),
1254 reference_alias!(43),
1255 reference_alias!(44),
1256 reference_alias!(45),
1257 reference_alias!(46),
1258 reference_alias!(47),
1259 reference_alias!(48),
1260 reference_alias!(49),
1261 "\n }",
1262 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}
1263 projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1264 status:fieldValueByName(name:$statusField){... on ProjectV2ItemFieldSingleSelectValue{name field{
1265 ... on ProjectV2SingleSelectField{id name options{id name}}
1266 }}}
1267 }pageInfo{hasNextPage endCursor}}}"#
1268 );
1269
1270 /// The board's own id and field definitions, and not one of its items.
1271 ///
1272 /// What a write needs of the board when the item it writes does not say: the id a field
1273 /// write and `addProjectV2ItemById` address, and the definitions of the `Status` and
1274 /// origin fields. It selects no `items`, so what it costs is the board's field list
1275 /// however many items the board holds — and it decides nothing about which items those
1276 /// are, which is the question a read of one item by its own id answers instead.
1277 ///
1278 /// The root is aliased `boardFields` rather than `owner`, so nothing counting the
1279 /// board's item reads by their root counts this one among them.
1280 pub const BOARD_FIELDS: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!){
1281 boardFields:repositoryOwner(login:$owner){
1282 ... on ProjectV2Owner{projectV2(number:$number){id
1283 fields(first:$nestedFirst){nodes{
1284 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1285 ... on ProjectV2Field{__typename id name dataType}
1286 }pageInfo{hasNextPage}}
1287 }}
1288 }
1289 }"#;
1290
1291 /// One board draft by its own node id, with the board item it sits in.
1292 ///
1293 /// A draft is not an issue, so [`ISSUE`] reaches it and reads nothing of it; this is the
1294 /// second read that answers it. `DraftIssue.projectV2Items` names the board item a draft
1295 /// is — GitHub links a draft to one item — with the same [`board_item_values!`] the
1296 /// issue fragment reads, so a draft reached by id resolves through the same resolver a
1297 /// board listing hands it to, and nothing has to list the board to find one.
1298 pub const DRAFT: &str = concat!(
1299 r#"query($id:ID!,$nestedFirst:Int!,$boardItems:Int!){
1300 node(id:$id){__typename ... on DraftIssue{id title body createdAt updatedAt
1301 projectV2Items(first:$boardItems){nodes{id project{id number}
1302 "#,
1303 board_item_values!(),
1304 r#"}pageInfo{hasNextPage endCursor}}}}
1305 }"#
1306 );
1307
1308 /// One issue's board memberships alone, walked past the page a read of it carried.
1309 ///
1310 /// The recovery read behind [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource):
1311 /// every document above carries a *page* of `Issue.projectItems`, and an issue on more
1312 /// boards than that page holds may have this board's entry past its end. This asks that
1313 /// one issue for its memberships and nothing else — the caller already holds the issue —
1314 /// so an answer of "this board does not hold it" is only ever given about a connection
1315 /// read to exhaustion.
1316 ///
1317 /// It selects the board item's id, its project number and the same
1318 /// [`board_item_values!`] the fragment does, because what it produces is handed to the
1319 /// very same resolver: an issue recovered this way reports the same title, the same
1320 /// status, the same labels and the same qualified id as one whose entry was on the
1321 /// page.
1322 ///
1323 /// `$first` rather than `$boardItems`: this document reads one issue, so nothing
1324 /// multiplies through it and the membership connection can be walked at
1325 /// [`MAX_PAGE_SIZE`](super::MAX_PAGE_SIZE) — which is what keeps the recovery to one
1326 /// further request for any issue a person really keeps.
1327 pub const ISSUE_BOARD_ITEMS: &str = concat!(
1328 r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!){
1329 node(id:$id){
1330 ... on Issue{projectItems(first:$first,after:$after){
1331 nodes{id updatedAt project{id number}
1332 "#,
1333 board_item_values!(),
1334 r#"}
1335 pageInfo{hasNextPage endCursor}}}
1336 }
1337 }"#
1338 );
1339 /// Whether the board's Project is public — half of what decides whether a write here can
1340 /// be read by anybody. Needs the `read:project` scope.
1341 pub const PROJECT_VISIBILITY: &str = r#"query($owner:String!,$number:Int!){visibility:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){public}}}}"#;
1342 /// Resolves the configured repository's node id, which creating an issue requires.
1343 pub const REPOSITORY: &str = r#"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){id nameWithOwner}}"#;
1344 /// What creating an issue needs and has not read yet: the board's own id and field
1345 /// definitions, as [`BOARD_FIELDS`] reads them, and the node id of the repository the
1346 /// issue is created in, as [`REPOSITORY`] reads it — in one request.
1347 ///
1348 /// Sent at the point a create knows which repository it is for, when neither half is
1349 /// already known to this process; a create needing only one of them sends that one's own
1350 /// document. Neither half is kept past the process: a field's option ids are re-minted by
1351 /// `sources fields --apply`, so a copy of them held between runs would write the wrong
1352 /// status.
1353 pub const CREATION_CONTEXT: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!,$repositoryOwner:String!,$repositoryName:String!){
1354 boardFields:repositoryOwner(login:$owner){
1355 ... on ProjectV2Owner{projectV2(number:$number){id
1356 fields(first:$nestedFirst){nodes{
1357 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1358 ... on ProjectV2Field{__typename id name dataType}
1359 }pageInfo{hasNextPage}}
1360 }}
1361 }
1362 repository(owner:$repositoryOwner,name:$repositoryName){id nameWithOwner}
1363 }"#;
1364 /// Reads both dependency directions for one issue, with each far end's own kind — and
1365 /// the issue's own body, which is where an edge to another source is recorded, so that
1366 /// half of a dependency read needs no second read of the issue or of the board.
1367 pub const ISSUE_DEPENDENCIES: &str = concat!(
1368 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1369 ... on Issue{body
1370 blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1371 blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1372 }}}"#,
1373 related_issue!()
1374 );
1375 /// What one item depends on: [`ISSUE_DEPENDENCIES`] narrowed to `blockedBy`, so a
1376 /// dependency read asks GitHub for the one direction it answers. The issue's `body` rides
1377 /// along because its metadata slot is where an edge to another source is recorded — and a
1378 /// board draft's `body` too, with the one board item GitHub links a draft to and, aliased
1379 /// `board`, this board's own id, so a draft's recorded edges are read off this same answer
1380 /// and only when that item is this board's: no draft read and no board read follow it.
1381 ///
1382 /// The draft's board item is asked for under a root of its own, aliased `draft`, rather
1383 /// than beside its `body` under `node`. GitHub counts the type-conditional fragments of
1384 /// one selection as the largest of them — `blockedBy`'s 100 alone, where this workspace's
1385 /// calculation adds the draft's 3 — while separate roots are summed by both, so this is
1386 /// the spelling whose node count GitHub and the calculation agree on. Both price it at
1387 /// one point; the credentialed lane's reconciliation is what holds the two to that.
1388 pub const ISSUE_DEPENDS_ON: &str = concat!(
1389 r#"query($id:ID!,$first:Int!,$after:String,$owner:String!,$number:Int!,$boardItems:Int!){
1390 node(id:$id){__typename
1391 ... on Issue{body
1392 blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1393 }
1394 ... on DraftIssue{id body}}
1395 draft:node(id:$id){... on DraftIssue{projectV2Items(first:$boardItems){nodes{project{id number}}pageInfo{hasNextPage}}}}
1396 board:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){id}}}}"#,
1397 related_issue!()
1398 );
1399 /// What depends on one issue: [`ISSUE_DEPENDENCIES`] with its `blocking` alone. No `body`:
1400 /// the reverse of a recorded edge is derived from the far end, never written down here.
1401 pub const ISSUE_DEPENDED_ON_BY: &str = concat!(
1402 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1403 ... on Issue{
1404 blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1405 }}}"#,
1406 related_issue!()
1407 );
1408 /// Creates one issue. Outside a copy it is created on no board, and [`ADD_TO_BOARD`] files
1409 /// it; inside one, its input names the board in `projectV2Ids` and its project in
1410 /// `parentIssueId`, so this one request files it under both — see
1411 /// [`GitHubProjectsSource::create_filed_issue`](super::GitHubProjectsSource).
1412 pub const CREATE_ISSUE: &str =
1413 r#"mutation($input:CreateIssueInput!){createIssue(input:$input){issue{id number url}}}"#;
1414 /// Puts an existing issue on the configured board.
1415 pub const ADD_TO_BOARD: &str = r#"mutation($input:AddProjectV2ItemByIdInput!){addProjectV2ItemById(input:$input){item{id}}}"#;
1416 /// Updates an issue's visible fields and its open or closed state in one call.
1417 pub const UPDATE_ISSUE: &str =
1418 r#"mutation($input:UpdateIssueInput!){updateIssue(input:$input){issue{id}}}"#;
1419 /// Updates an existing draft's user-visible fields.
1420 pub const UPDATE_DRAFT: &str = r#"mutation($input:UpdateProjectV2DraftIssueInput!){updateProjectV2DraftIssue(input:$input){draftIssue{id}}}"#;
1421 /// Updates a text or single-select value on one project item.
1422 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}}}}}}}}"#;
1423 /// Writes up to six board fields and clears up to three in one ordered mutation: every
1424 /// aliased field is included by its own boolean, as [`FIELD_WRITE_SLOTS`](super::FIELD_WRITE_SLOTS)
1425 /// and [`FIELD_CLEAR_SLOTS`](super::FIELD_CLEAR_SLOTS) name them, writes before clears.
1426 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}}}"#;
1427 /// Clears one project item's value of one field, which is what a `none` priority is.
1428 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}}}}}}}}"#;
1429 /// Creates one field: a single-select one with its options, or a text one for a projected
1430 /// metadata value. Only the guarded field setup may use this document, and only for a
1431 /// field the board lacks.
1432 pub const CREATE_FIELD: &str = r#"mutation($input:CreateProjectV2FieldInput!){createProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id name options{id name color description}}}}}"#;
1433 /// Replaces a single-select field's options. Only the guarded field setup — the
1434 /// `status-options` and `fields` operations — may use this document, because GitHub
1435 /// treats the input as the complete option list.
1436 pub const STATUS_OPTIONS_UPDATE: &str = r#"mutation($input:UpdateProjectV2FieldInput!){updateProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id options{id name color description}}}}}"#;
1437 /// A fresh snapshot of the Status field and every board item's assignment.
1438 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}}}}}}"#;
1439 /// Files one issue under another as a sub-issue, which is what project membership is.
1440 pub const ADD_SUB_ISSUE: &str =
1441 r#"mutation($input:AddSubIssueInput!){addSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1442 /// Takes one issue back out of its parent.
1443 pub const REMOVE_SUB_ISSUE: &str = r#"mutation($input:RemoveSubIssueInput!){removeSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1444 /// Adds GitHub's native issue blocked-by relationship.
1445 pub const ADD_BLOCKED_BY: &str = r#"mutation($input:AddBlockedByInput!){addBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
1446 /// One origin of [`ORIGIN_LOOKUPS`]: [`ORIGIN_LOOKUP`]'s two connections for the origin the
1447 /// `$filter<n>` and `$search<n>` of slot `<n>` name, sent only while `$ask<n>` holds.
1448 macro_rules! origin_lookup_alias {
1449 ($n:literal) => {
1450 concat!(
1451 "\n o",
1452 stringify!($n),
1453 ":repositoryOwner(login:$owner) @include(if:$ask",
1454 stringify!($n),
1455 "){... on ProjectV2Owner{projectV2(number:$number){items(first:$originFirst,query:$filter",
1456 stringify!($n),
1457 "){nodes{id updatedAt ",
1458 board_item_values!(),
1459 board_item_content!(),
1460 "} pageInfo{hasNextPage endCursor}}}}}\n s",
1461 stringify!($n),
1462 ":search(query:$search",
1463 stringify!($n),
1464 ",type:$type,first:$originFirst) @include(if:$ask",
1465 stringify!($n),
1466 "){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}"
1467 )
1468 };
1469 }
1470
1471 /// The first page of [`ORIGIN_LOOKUP`] for up to [`ORIGIN_BATCH`](super::ORIGIN_BATCH)
1472 /// origins a copy is about to look for, and everything creating an item then reads —
1473 /// the board's own id and field definitions, as [`CREATION_CONTEXT`] reads them, and the node
1474 /// id and the numeric id of the repository an issue is created in — in one request.
1475 ///
1476 /// What a copy reads before it writes anything, so that finding none of its records on the
1477 /// board and creating every one costs this read and the writes. An origin whose page says
1478 /// there is more is left to its own [`ORIGIN_LOOKUP`]. The repository's numeric id is what an
1479 /// image upload names, so a copy carrying assets needs no `GET /repos/{owner}/{repo}` either.
1480 pub const ORIGIN_LOOKUPS: &str = concat!(
1481 r#"query($owner:String!,$number:Int!,$type:SearchType!,$originFirst:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!,$repositoryOwner:String!,$repositoryName:String!,$filter0:String!,$filter1:String!,$filter2:String!,$filter3:String!,$filter4:String!,$filter5:String!,$filter6:String!,$filter7:String!,$filter8:String!,$filter9:String!,$search0:String!,$search1:String!,$search2:String!,$search3:String!,$search4:String!,$search5:String!,$search6:String!,$search7:String!,$search8:String!,$search9:String!,$ask0:Boolean!,$ask1:Boolean!,$ask2:Boolean!,$ask3:Boolean!,$ask4:Boolean!,$ask5:Boolean!,$ask6:Boolean!,$ask7:Boolean!,$ask8:Boolean!,$ask9:Boolean!"#,
1482 relationship_events_variable!(),
1483 r#"){
1484 boardFields:repositoryOwner(login:$owner){
1485 ... on ProjectV2Owner{projectV2(number:$number){id
1486 fields(first:$nestedFirst){nodes{
1487 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1488 ... on ProjectV2Field{__typename id name dataType}
1489 }pageInfo{hasNextPage}}
1490 }}
1491 }
1492 repository(owner:$repositoryOwner,name:$repositoryName){id databaseId nameWithOwner}"#,
1493 origin_lookup_alias!(0),
1494 origin_lookup_alias!(1),
1495 origin_lookup_alias!(2),
1496 origin_lookup_alias!(3),
1497 origin_lookup_alias!(4),
1498 origin_lookup_alias!(5),
1499 origin_lookup_alias!(6),
1500 origin_lookup_alias!(7),
1501 origin_lookup_alias!(8),
1502 origin_lookup_alias!(9),
1503 "\n }",
1504 board_issue!()
1505 );
1506
1507 /// One slot `<n>` of a copy's aliased writes: `$<prefix><n>` is its input and `$send<n>`
1508 /// whether it is sent.
1509 macro_rules! write_slot {
1510 ($prefix:literal, $field:literal, $selection:literal, $n:literal) => {
1511 concat!(
1512 " ",
1513 $prefix,
1514 stringify!($n),
1515 ":",
1516 $field,
1517 "(input:$",
1518 $prefix,
1519 stringify!($n),
1520 ") @include(if:$send",
1521 stringify!($n),
1522 "){",
1523 $selection,
1524 "}"
1525 )
1526 };
1527 }
1528
1529 /// The variables of a copy's aliased writes: eleven inputs of `$type` named `$<prefix><n>`,
1530 /// and eleven `$send<n>`.
1531 macro_rules! write_variables {
1532 ($prefix:literal, $type:literal) => {
1533 concat!(
1534 "mutation(",
1535 "$",
1536 $prefix,
1537 "0:",
1538 $type,
1539 "!,$",
1540 $prefix,
1541 "1:",
1542 $type,
1543 "!,$",
1544 $prefix,
1545 "2:",
1546 $type,
1547 "!,$",
1548 $prefix,
1549 "3:",
1550 $type,
1551 "!,$",
1552 $prefix,
1553 "4:",
1554 $type,
1555 "!,$",
1556 $prefix,
1557 "5:",
1558 $type,
1559 "!,$",
1560 $prefix,
1561 "6:",
1562 $type,
1563 "!,$",
1564 $prefix,
1565 "7:",
1566 $type,
1567 "!,$",
1568 $prefix,
1569 "8:",
1570 $type,
1571 "!,$",
1572 $prefix,
1573 "9:",
1574 $type,
1575 "!,$",
1576 $prefix,
1577 "10:",
1578 $type,
1579 "!,",
1580 "$send0:Boolean!,$send1:Boolean!,$send2:Boolean!,$send3:Boolean!,$send4:Boolean!,",
1581 "$send5:Boolean!,$send6:Boolean!,$send7:Boolean!,$send8:Boolean!,$send9:Boolean!,",
1582 "$send10:Boolean!){"
1583 )
1584 };
1585 }
1586
1587 /// A copy's aliased writes of one kind: [`MUTATION_BATCH`](super::MUTATION_BATCH) slots of
1588 /// `$field`, each sent only while its `$send<n>` holds.
1589 macro_rules! write_batch {
1590 ($prefix:literal, $type:literal, $field:literal, $selection:literal) => {
1591 concat!(
1592 write_variables!($prefix, $type),
1593 write_slot!($prefix, $field, $selection, 0),
1594 write_slot!($prefix, $field, $selection, 1),
1595 write_slot!($prefix, $field, $selection, 2),
1596 write_slot!($prefix, $field, $selection, 3),
1597 write_slot!($prefix, $field, $selection, 4),
1598 write_slot!($prefix, $field, $selection, 5),
1599 write_slot!($prefix, $field, $selection, 6),
1600 write_slot!($prefix, $field, $selection, 7),
1601 write_slot!($prefix, $field, $selection, 8),
1602 write_slot!($prefix, $field, $selection, 9),
1603 write_slot!($prefix, $field, $selection, 10),
1604 "}"
1605 )
1606 };
1607 }
1608
1609 /// Creates up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues in one request, each filed on
1610 /// the board and under its project by the same `createIssue` — its `projectV2Ids` and
1611 /// `parentIssueId` — as [`CREATE_ISSUE`] creates one.
1612 pub const CREATE_ISSUES: &str = write_batch!(
1613 "create",
1614 "CreateIssueInput",
1615 "createIssue",
1616 "issue{id number url}"
1617 );
1618
1619 /// One issue of [`CREATED_BOARD_ITEMS`]: the board items the issue `$id<n>` names is on, with
1620 /// the `Status` value of each, read only while `$read<n>` holds.
1621 macro_rules! created_item_alias {
1622 ($n:literal) => {
1623 concat!(
1624 "\n i",
1625 stringify!($n),
1626 ":node(id:$id",
1627 stringify!($n),
1628 ") @include(if:$read",
1629 stringify!($n),
1630 "){... on Issue{id projectItems(first:$boardItems){nodes{id project{id} status:fieldValueByName(name:$statusName){... on ProjectV2ItemFieldSingleSelectValue{name}}}}}}"
1631 )
1632 };
1633 }
1634
1635 /// The board item of each issue a copy created, up to
1636 /// [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH) at a time, with its `Status` as the board
1637 /// set it: what `createIssue`'s `projectV2Ids` files the issue as, which GitHub adds after
1638 /// answering the create, so its id comes from a read made once every create has been sent.
1639 pub const CREATED_BOARD_ITEMS: &str = concat!(
1640 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!,$read0:Boolean!,$read1:Boolean!,$read2:Boolean!,$read3:Boolean!,$read4:Boolean!,$read5:Boolean!,$read6:Boolean!,$read7:Boolean!,$read8:Boolean!,$read9:Boolean!,$read10:Boolean!,$read11:Boolean!,$read12:Boolean!,$read13:Boolean!,$read14:Boolean!,$read15:Boolean!,$read16:Boolean!,$read17:Boolean!,$read18:Boolean!,$read19:Boolean!,$read20:Boolean!,$boardItems:Int!,$statusName:String!){"#,
1641 created_item_alias!(0),
1642 created_item_alias!(1),
1643 created_item_alias!(2),
1644 created_item_alias!(3),
1645 created_item_alias!(4),
1646 created_item_alias!(5),
1647 created_item_alias!(6),
1648 created_item_alias!(7),
1649 created_item_alias!(8),
1650 created_item_alias!(9),
1651 created_item_alias!(10),
1652 created_item_alias!(11),
1653 created_item_alias!(12),
1654 created_item_alias!(13),
1655 created_item_alias!(14),
1656 created_item_alias!(15),
1657 created_item_alias!(16),
1658 created_item_alias!(17),
1659 created_item_alias!(18),
1660 created_item_alias!(19),
1661 created_item_alias!(20),
1662 "\n }"
1663 );
1664
1665 /// Up to [`MUTATION_BATCH`](super::MUTATION_BATCH) board field values a copy writes on the
1666 /// items it created, each on its own item, in one ordered request.
1667 pub const WRITE_FIELD_VALUES: &str = write_batch!(
1668 "field",
1669 "UpdateProjectV2ItemFieldValueInput",
1670 "updateProjectV2ItemFieldValue",
1671 "projectV2Item{id}"
1672 );
1673
1674 /// Closes up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues a copy created at a closing
1675 /// status, each with its own `stateInput` and nothing else, once its option is selected.
1676 pub const CLOSE_ISSUES: &str =
1677 write_batch!("close", "UpdateIssueInput", "updateIssue", "issue{id}");
1678
1679 /// Up to [`MUTATION_BATCH`](super::MUTATION_BATCH) native blocked-by relationships a copy adds
1680 /// to the issues it created, in one request.
1681 pub const ADD_BLOCKED_BYS: &str = write_batch!(
1682 "block",
1683 "AddBlockedByInput",
1684 "addBlockedBy",
1685 "issue{id} blockingIssue{id}"
1686 );
1687
1688 /// Removes one native issue blocked-by relationship.
1689 pub const REMOVE_BLOCKED_BY: &str = r#"mutation($input:RemoveBlockedByInput!){removeBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
1690 /// Deletes one issue, which takes its board item with it.
1691 ///
1692 /// The engine sends this in one situation only: undoing a copy that could not finish,
1693 /// over the items that same copy created. Deleting the issue removes the board item
1694 /// too, so there is no second `deleteProjectV2Item` to keep in step with it.
1695 pub const DELETE_ISSUE: &str =
1696 r#"mutation($input:DeleteIssueInput!){deleteIssue(input:$input){repository{id}}}"#;
1697
1698 /// Everything this source reads about one issue comment, wherever it reaches one.
1699 ///
1700 /// A macro for the reason [`board_issue!`] is one: a comment listed, a comment just added
1701 /// and a comment just edited are handed to one mapper, so they are selected by one
1702 /// spelling. `author` is `Actor`, which GitHub answers `null` for an account that no
1703 /// longer exists, and `login` is the one member every kind of actor carries.
1704 macro_rules! issue_comment {
1705 () => {
1706 "id author{login} createdAt updatedAt body url"
1707 };
1708 }
1709
1710 /// One task's comments: a page of its issue's own `comments` connection.
1711 ///
1712 /// **No `orderBy`, and that is what makes the page oldest first.** GitHub's only
1713 /// `IssueCommentOrder` field is `UPDATED_AT`, which would move a comment to the end of the
1714 /// list every time somebody edited it; left unordered the connection answers in the order
1715 /// the comments were written, which is the order GitHub documents for the same collection
1716 /// over REST — ascending id. Nothing multiplies through it, so `$first` is the whole of its
1717 /// node count and the caller's own page size is pushed straight down.
1718 pub const ISSUE_COMMENTS: &str = concat!(
1719 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename ... on Issue{comments(first:$first,after:$after){nodes{"#,
1720 issue_comment!(),
1721 r#"}pageInfo{hasNextPage endCursor}}}}}"#
1722 );
1723 /// One issue by its own node id, with a page of its comments: what `task show` and a
1724 /// comment listing read, in one request.
1725 ///
1726 /// [`ISSUE`] and [`ISSUE_COMMENTS`] in one document, rather than one then the other. The
1727 /// comments are selected here and **not** on the shared `board_issue!` fragment, which
1728 /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] nest under a page of a hundred issues: a comment
1729 /// connection there would multiply through both of those documents' price, and neither
1730 /// needs one.
1731 pub const ISSUE_DETAIL: &str = concat!(
1732 r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1733 relationship_events_variable!(),
1734 r#"){
1735 node(id:$id){__typename ...BoardIssue ... on Issue{comments(first:$first,after:$after){nodes{"#,
1736 issue_comment!(),
1737 r#"}pageInfo{hasNextPage endCursor}}}}
1738 }"#,
1739 board_issue!()
1740 );
1741
1742 /// One alias of [`ISSUE_DETAILS`]: the item a batch's `$id<n>` names, with the first
1743 /// page of its comments when `$comments` asks for them.
1744 macro_rules! issue_details_alias {
1745 ($n:literal) => {
1746 concat!(
1747 "\n i",
1748 stringify!($n),
1749 ":node(id:$id",
1750 stringify!($n),
1751 "){__typename ...BoardIssue ... on Issue{comments(first:$first) @include(if:$comments){nodes{",
1752 issue_comment!(),
1753 "}pageInfo{hasNextPage endCursor}}}}"
1754 )
1755 };
1756 }
1757
1758 /// [`ISSUE_DETAIL`] for [`DETAIL_BATCH`](super::DETAIL_BATCH) items at once, each by its
1759 /// own node id, as one fixed-size document of aliased `node(id:)` fields.
1760 ///
1761 /// **Aliased `node(id:)` rather than `nodes(ids:)`, and that is what keeps its price
1762 /// honest.** The `github-graphql-node-count` model this workspace prices with treats a
1763 /// field that supplies neither `first` nor `last` as free, and `nodes(ids:)` supplies
1764 /// neither — so every connection under it would be priced at nothing and the pin in
1765 /// `tests/point_cost.rs` would understate what GitHub charges. Each alias here is the
1766 /// one-item read the model already prices, so the batch costs what its aliases cost.
1767 ///
1768 /// **Fixed-size, so there is one document to price.** A batch of fewer items binds the
1769 /// slots it has no item for to the last item it does, and reads that item again; the
1770 /// price is the document's, whatever its variables, so a short batch costs what a full
1771 /// one does and nothing more.
1772 pub const ISSUE_DETAILS: &str = concat!(
1773 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!"#,
1774 relationship_events_variable!(),
1775 r#"){"#,
1776 issue_details_alias!(0),
1777 issue_details_alias!(1),
1778 issue_details_alias!(2),
1779 issue_details_alias!(3),
1780 issue_details_alias!(4),
1781 issue_details_alias!(5),
1782 issue_details_alias!(6),
1783 issue_details_alias!(7),
1784 issue_details_alias!(8),
1785 issue_details_alias!(9),
1786 issue_details_alias!(10),
1787 issue_details_alias!(11),
1788 issue_details_alias!(12),
1789 issue_details_alias!(13),
1790 issue_details_alias!(14),
1791 issue_details_alias!(15),
1792 issue_details_alias!(16),
1793 issue_details_alias!(17),
1794 issue_details_alias!(18),
1795 issue_details_alias!(19),
1796 issue_details_alias!(20),
1797 issue_details_alias!(21),
1798 issue_details_alias!(22),
1799 issue_details_alias!(23),
1800 "\n }",
1801 board_issue!()
1802 );
1803
1804 /// One alias of [`ISSUE_COPY_DETAILS`]: the item a batch's `$id<n>` names, with the first
1805 /// page of its comments and the issues it is blocked by.
1806 macro_rules! issue_copy_details_alias {
1807 ($n:literal) => {
1808 concat!(
1809 "\n i",
1810 stringify!($n),
1811 ":node(id:$id",
1812 stringify!($n),
1813 "){__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{",
1814 issue_comment!(),
1815 "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}}}"
1816 )
1817 };
1818 }
1819
1820 /// [`ISSUE_DETAILS`] as a copy reads the tasks it carries: each item with the first page of
1821 /// its comments and its `blockedBy` — the edges a copy reads of every task next, which
1822 /// [`ISSUE`] carries and [`ISSUE_DETAILS`] does not — [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH)
1823 /// at a time, so a copy of a changed task costs this read and nothing else.
1824 ///
1825 /// A document of its own rather than a widening of [`ISSUE_DETAILS`], whose batch size is
1826 /// what `task show-many` is priced by and which reads no edge.
1827 ///
1828 /// `children`, read only while `$children` holds, is which issues the issue `$project` has
1829 /// as sub-issues — each one's id and title, the page `$nestedFirst` allows — so that a
1830 /// project copy, which reads its project and every task at once, knows from this same read
1831 /// which tasks the project holds at the destination, and its orphan check is answered by it
1832 /// rather than by a listing of the project.
1833 pub const ISSUE_COPY_DETAILS: &str = concat!(
1834 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!,$project:ID!,$children:Boolean!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1835 relationship_events_variable!(),
1836 r#"){"#,
1837 issue_copy_details_alias!(0),
1838 issue_copy_details_alias!(1),
1839 issue_copy_details_alias!(2),
1840 issue_copy_details_alias!(3),
1841 issue_copy_details_alias!(4),
1842 issue_copy_details_alias!(5),
1843 issue_copy_details_alias!(6),
1844 issue_copy_details_alias!(7),
1845 issue_copy_details_alias!(8),
1846 issue_copy_details_alias!(9),
1847 issue_copy_details_alias!(10),
1848 issue_copy_details_alias!(11),
1849 issue_copy_details_alias!(12),
1850 issue_copy_details_alias!(13),
1851 issue_copy_details_alias!(14),
1852 issue_copy_details_alias!(15),
1853 issue_copy_details_alias!(16),
1854 issue_copy_details_alias!(17),
1855 issue_copy_details_alias!(18),
1856 issue_copy_details_alias!(19),
1857 issue_copy_details_alias!(20),
1858 "\n children:node(id:$project) @include(if:$children){... on Issue{id subIssues(first:$nestedFirst){nodes{id title} pageInfo{hasNextPage}}}}",
1859 "\n }",
1860 board_issue!(),
1861 related_issue!()
1862 );
1863
1864 /// Which issue one comment is on, read before that comment is edited or removed.
1865 ///
1866 /// GitHub's comment mutations take the comment's id and nothing else, so without this a
1867 /// comment id given against the wrong task would change a comment on another issue.
1868 pub const COMMENT_ISSUE: &str =
1869 r#"query($id:ID!){node(id:$id){__typename ... on IssueComment{id body issue{id}}}}"#;
1870 /// Adds one comment to an issue, signed as the account the token belongs to.
1871 pub const ADD_COMMENT: &str = concat!(
1872 r#"mutation($input:AddCommentInput!){addComment(input:$input){subject{id} commentEdge{node{"#,
1873 issue_comment!(),
1874 r#"}}}}"#
1875 );
1876 /// Replaces the body of one issue comment.
1877 pub const UPDATE_COMMENT: &str = concat!(
1878 r#"mutation($input:UpdateIssueCommentInput!){updateIssueComment(input:$input){issueComment{"#,
1879 issue_comment!(),
1880 r#"}}}"#
1881 );
1882 /// Removes one issue comment. Its payload carries nothing about the comment it removed.
1883 pub const DELETE_COMMENT: &str = r#"mutation($input:DeleteIssueCommentInput!){deleteIssueComment(input:$input){clientMutationId}}"#;
1884
1885 /// What a mutation of a write the store's cache expects selects of the issue it wrote:
1886 /// everything [`ISSUE_DETAIL`] reads of it, so its response shows the task whole — its
1887 /// change token's every part and the first page of its comments.
1888 ///
1889 /// Sent **only** while that write runs, in place of the document named beside each
1890 /// below, so every other write's documents, prices and request counts are what they
1891 /// were. GitHub's token waits for a task to settle (`change_token::SETTLED`), and a
1892 /// mutation's response is stamped seconds after the change it made, so against GitHub
1893 /// itself a response rarely determines a version; the cache is then left unserveable
1894 /// for the task, and its next read refreshes it.
1895 macro_rules! whole_issue {
1896 () => {
1897 concat!(
1898 r#"__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{"#,
1899 issue_comment!(),
1900 r#"}pageInfo{hasNextPage endCursor}}}"#
1901 )
1902 };
1903 }
1904
1905 /// The variables every document of `whole_issue!` declares beside its own.
1906 macro_rules! whole_variables {
1907 () => {
1908 concat!(
1909 r#",$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1910 relationship_events_variable!()
1911 )
1912 };
1913 }
1914
1915 /// [`ADD_COMMENT`], selecting the whole issue commented on.
1916 pub const ADD_COMMENT_WHOLE: &str = concat!(
1917 r#"mutation($input:AddCommentInput!"#,
1918 whole_variables!(),
1919 r#"){addComment(input:$input){subject{id "#,
1920 whole_issue!(),
1921 r#"} commentEdge{node{"#,
1922 issue_comment!(),
1923 r#"}}}}"#,
1924 board_issue!()
1925 );
1926 /// [`UPDATE_COMMENT`], selecting the whole issue the comment is on.
1927 pub const UPDATE_COMMENT_WHOLE: &str = concat!(
1928 r#"mutation($input:UpdateIssueCommentInput!"#,
1929 whole_variables!(),
1930 r#"){updateIssueComment(input:$input){issueComment{"#,
1931 issue_comment!(),
1932 r#" issue{"#,
1933 whole_issue!(),
1934 r#"}}}}"#,
1935 board_issue!()
1936 );
1937 /// [`UPDATE_ISSUE`], selecting the whole issue updated.
1938 pub const UPDATE_ISSUE_WHOLE: &str = concat!(
1939 r#"mutation($input:UpdateIssueInput!"#,
1940 whole_variables!(),
1941 r#"){updateIssue(input:$input){issue{id "#,
1942 whole_issue!(),
1943 r#"}}}"#,
1944 board_issue!()
1945 );
1946 /// [`UPDATE_FIELD`], selecting the whole issue behind the board item written.
1947 pub const UPDATE_FIELD_WHOLE: &str = concat!(
1948 r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
1949 whole_variables!(),
1950 r#"){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
1951 whole_issue!(),
1952 r#"}}}}"#,
1953 board_issue!()
1954 );
1955 /// [`CLEAR_FIELD`], selecting the whole issue behind the board item cleared.
1956 pub const CLEAR_FIELD_WHOLE: &str = concat!(
1957 r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
1958 whole_variables!(),
1959 r#"){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
1960 whole_issue!(),
1961 r#"}}}}"#,
1962 board_issue!()
1963 );
1964
1965 /// The document sent in `document`'s place while a write the store's cache expects runs,
1966 /// when it has one.
1967 #[must_use]
1968 pub fn whole_twin(document: &str) -> Option<&'static str> {
1969 [
1970 (ADD_COMMENT, ADD_COMMENT_WHOLE),
1971 (UPDATE_COMMENT, UPDATE_COMMENT_WHOLE),
1972 (UPDATE_ISSUE, UPDATE_ISSUE_WHOLE),
1973 (UPDATE_FIELD, UPDATE_FIELD_WHOLE),
1974 (CLEAR_FIELD, CLEAR_FIELD_WHOLE),
1975 ]
1976 .into_iter()
1977 .find(|(plain, _)| *plain == document)
1978 .map(|(_, whole)| whole)
1979 }
1980
1981 /// Every document above, with what this source is doing when it sends one.
1982 ///
1983 /// One list rather than a `match` beside the constants: a rate-limit diagnostic has to
1984 /// name the call that was refused, and a `match` with a catch-all arm would answer a
1985 /// document added later with "talking to GitHub" and never say so.
1986 ///
1987 /// `documents_are_all_inventoried` reads this file back and fails naming any `pub
1988 /// const` here that this list omits, so the two cannot part — which is the same guard
1989 /// `CATEGORIES` carries, in the one shape available to a set of `&str` constants.
1990 pub const DOCUMENTS: [(&str, &str); 50] = [
1991 (SEARCH_ISSUES, "searching this board's issues"),
1992 (ISSUE, "reading one issue"),
1993 (
1994 ISSUE_BOARD_ITEMS,
1995 "reading one issue's board memberships past the page it came with",
1996 ),
1997 (SUB_ISSUES, "reading a project's tasks"),
1998 (BOARD, "reading the board"),
1999 (ORIGIN_LOOKUP, "looking up the items copied from one origin"),
2000 (CLOSED_ITEMS, "reading the board's closed items"),
2001 (
2002 ISSUES_BY_REFERENCE,
2003 "reading a batch of issues by their references",
2004 ),
2005 (BOARD_FIELDS, "reading the board's fields"),
2006 (DRAFT, "reading one draft"),
2007 (REPOSITORY, "reading the destination repository"),
2008 (
2009 PROJECT_VISIBILITY,
2010 "reading whether the board's project is public",
2011 ),
2012 (
2013 CREATION_CONTEXT,
2014 "reading the board's fields and the destination repository",
2015 ),
2016 (ISSUE_DEPENDENCIES, "reading an issue's dependencies"),
2017 (ISSUE_DEPENDS_ON, "reading what an item depends on"),
2018 (ISSUE_DEPENDED_ON_BY, "reading what depends on an issue"),
2019 (CREATE_ISSUE, "creating an issue"),
2020 (
2021 ORIGIN_LOOKUPS,
2022 "looking up the items copied from several origins, and what creating one reads",
2023 ),
2024 (CREATE_ISSUES, "creating several issues together"),
2025 (
2026 CREATED_BOARD_ITEMS,
2027 "reading the board items of the issues a copy created",
2028 ),
2029 (
2030 WRITE_FIELD_VALUES,
2031 "writing board fields of the items a copy created",
2032 ),
2033 (CLOSE_ISSUES, "closing the issues a copy created"),
2034 (ADD_BLOCKED_BYS, "recording several dependencies together"),
2035 (ADD_TO_BOARD, "adding an issue to the board"),
2036 (UPDATE_ISSUE, "updating an issue"),
2037 (UPDATE_DRAFT, "updating a draft item"),
2038 (UPDATE_FIELD, "writing a board field"),
2039 (UPDATE_FIELDS, "writing board fields together"),
2040 (CLEAR_FIELD, "clearing a board field"),
2041 (
2042 CREATE_FIELD,
2043 "creating a board single-select field with its options",
2044 ),
2045 (
2046 STATUS_OPTIONS_SNAPSHOT,
2047 "snapshotting board Status options and assignments",
2048 ),
2049 (
2050 STATUS_OPTIONS_UPDATE,
2051 "safely replacing the board Status option list",
2052 ),
2053 (ADD_SUB_ISSUE, "filing an issue under its project"),
2054 (REMOVE_SUB_ISSUE, "taking an issue out of its project"),
2055 (ADD_BLOCKED_BY, "recording a dependency"),
2056 (REMOVE_BLOCKED_BY, "removing a dependency"),
2057 (DELETE_ISSUE, "deleting an issue"),
2058 (ISSUE_COMMENTS, "reading a task's comments"),
2059 (ISSUE_DETAIL, "reading one issue with its comments"),
2060 (
2061 ISSUE_DETAILS,
2062 "reading a batch of issues with their comments",
2063 ),
2064 (
2065 ISSUE_COPY_DETAILS,
2066 "reading a batch of issues with their comments and dependencies for a copy",
2067 ),
2068 (COMMENT_ISSUE, "reading which issue a comment is on"),
2069 (ADD_COMMENT, "adding a comment"),
2070 (UPDATE_COMMENT, "editing a comment"),
2071 (DELETE_COMMENT, "deleting a comment"),
2072 (
2073 ADD_COMMENT_WHOLE,
2074 "adding a comment, answered with the whole issue",
2075 ),
2076 (
2077 UPDATE_COMMENT_WHOLE,
2078 "editing a comment, answered with the whole issue",
2079 ),
2080 (
2081 UPDATE_ISSUE_WHOLE,
2082 "updating an issue, answered with it whole",
2083 ),
2084 (
2085 UPDATE_FIELD_WHOLE,
2086 "writing a board field, answered with the whole issue",
2087 ),
2088 (
2089 CLEAR_FIELD_WHOLE,
2090 "clearing a board field, answered with the whole issue",
2091 ),
2092 ];
2093}
2094
2095/// One aliased mutation field of [`graphql::UPDATE_FIELDS`]: the key its answer comes back
2096/// under, the variable carrying its input, and the boolean variable that includes it.
2097#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2098pub struct FieldSlot {
2099 /// The key of the answer's `data` this field's payload is under.
2100 pub alias: &'static str,
2101 /// The variable carrying this field's input.
2102 pub variable: &'static str,
2103 /// The boolean variable whose `true` sends this field.
2104 pub include: &'static str,
2105}
2106
2107/// The value writes [`graphql::UPDATE_FIELDS`] carries, in the order GitHub runs them.
2108pub const FIELD_WRITE_SLOTS: [FieldSlot; 6] = [
2109 FieldSlot {
2110 alias: "updateProjectV2ItemFieldValue",
2111 variable: "input",
2112 include: "writeFirst",
2113 },
2114 FieldSlot {
2115 alias: "second",
2116 variable: "second",
2117 include: "writeSecond",
2118 },
2119 FieldSlot {
2120 alias: "third",
2121 variable: "third",
2122 include: "writeThird",
2123 },
2124 FieldSlot {
2125 alias: "fourth",
2126 variable: "fourth",
2127 include: "writeFourth",
2128 },
2129 FieldSlot {
2130 alias: "fifth",
2131 variable: "fifth",
2132 include: "writeFifth",
2133 },
2134 FieldSlot {
2135 alias: "sixth",
2136 variable: "sixth",
2137 include: "writeSixth",
2138 },
2139];
2140
2141/// The clears [`graphql::UPDATE_FIELDS`] carries, run after every write of the same request.
2142pub const FIELD_CLEAR_SLOTS: [FieldSlot; 3] = [
2143 FieldSlot {
2144 alias: "cleared",
2145 variable: "clear",
2146 include: "writeClear",
2147 },
2148 FieldSlot {
2149 alias: "clearedSecond",
2150 variable: "clearSecond",
2151 include: "writeClearSecond",
2152 },
2153 FieldSlot {
2154 alias: "clearedThird",
2155 variable: "clearThird",
2156 include: "writeClearThird",
2157 },
2158];
2159
2160/// Which of GitHub's two rate limiters refused a request.
2161///
2162/// Waiting is the whole answer to the primary budget, and polling is what *extends* the
2163/// secondary one — so an operator told the wrong one takes the wrong next step, which is
2164/// the whole reason this is carried rather than collapsed into "rate limited".
2165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2166enum Limiter {
2167 /// The hourly API budget, which `gh api rate_limit` reports and a wait answers.
2168 Primary,
2169 /// The burst limiter over content-generating requests, which nothing reports.
2170 Secondary,
2171}
2172
2173/// The wordings GitHub answers a secondary rate limit with.
2174///
2175/// It sends them under a forbidden status, under a too-many-requests status, and inside
2176/// the `errors` of a *successful* response, which is why the text is what this matches on
2177/// rather than the status. `abuse detection` is the wording GitHub used before the
2178/// limiter was renamed and still returns from some endpoints; `submitted too quickly` is
2179/// what a burst of content creation is refused with.
2180///
2181/// This is GitHub's vocabulary rather than this source's, so it is pinned rather than
2182/// remembered: `tests/fixtures/rate-limits.json` records where each wording was read and
2183/// when, and the drift gate reconciles the two lists both ways. Public for that gate
2184/// alone — a caller has no use for it, and matching on a refusal is this source's job.
2185pub const SECONDARY_WORDINGS: [&str; 5] = [
2186 "secondary rate limit",
2187 "temporarily blocked from content creation",
2188 "abuse detection",
2189 "submitted too quickly",
2190 "exceeded a secondary",
2191];
2192
2193/// The wordings GitHub answers an exhausted primary budget with.
2194///
2195/// `rate_limited` is the `type` its GraphQL error carries, which is read as a field rather
2196/// than looked for in the response text. `api rate limit already exceeded` is what GraphQL
2197/// answers a request made once the hour's budget is spent — "API rate limit already exceeded
2198/// for user ID …" in the `errors` of an HTTP 200, with no `type` — and neither of the other
2199/// two phrases is a substring of it, so without it that answer read as a refusal that will
2200/// never lift. Pinned and gated exactly as [`SECONDARY_WORDINGS`] is, and public for the same
2201/// one reason.
2202pub const PRIMARY_WORDINGS: [&str; 4] = [
2203 "api rate limit exceeded",
2204 "api rate limit already exceeded",
2205 "rate limit exceeded",
2206 "rate_limited",
2207];
2208
2209/// What a response *says about itself*, which is the only place a refusal can be read.
2210///
2211/// Deliberately not the whole response body. A board is a place people write about their
2212/// own work, and a task on it titled "the secondary rate limit" would, matched across the
2213/// raw text, turn a perfectly good answer into a refusal this source then waited out and
2214/// reported. So the item data is never read: what is read is GitHub's own REST-style
2215/// `message` envelope, which is what a forbidden status carries, and the `message` and
2216/// `type` of each GraphQL error, which is where a *successful* response says it.
2217///
2218/// A body that is not JSON at all has nothing structured to read, so only a failing
2219/// response's own text is taken — a successful response that is not JSON is malformed
2220/// rather than refused, and [`GitHubProjectsSource::answer`] says so.
2221fn refusal_wording(status: StatusCode, body: &str) -> String {
2222 let Ok(parsed) = serde_json::from_str::<Value>(body) else {
2223 return if status.is_success() {
2224 String::new()
2225 } else {
2226 body.to_owned()
2227 };
2228 };
2229 let mut said: Vec<&str> = parsed
2230 .get("message")
2231 .and_then(Value::as_str)
2232 .into_iter()
2233 .collect();
2234 if let Some(errors) = parsed.get("errors").and_then(Value::as_array) {
2235 for error in errors {
2236 said.extend(
2237 ["message", "type"]
2238 .into_iter()
2239 .filter_map(|key| error.get(key).and_then(Value::as_str)),
2240 );
2241 }
2242 }
2243 said.join("; ")
2244}
2245
2246impl Limiter {
2247 /// Which limiter refused this response, or `None` when none of them did.
2248 ///
2249 /// The wording is read first and the status only decides what carries none of it,
2250 /// because GitHub answers a secondary limit with a forbidden status far more often
2251 /// than with too-many-requests — while a forbidden status saying nothing about a limit
2252 /// really is a credential this token lacks.
2253 ///
2254 /// A response is a refusal because of its status or its own wording. A spent budget
2255 /// only ever explains one; it never turns an answer into a refusal.
2256 fn classify(status: StatusCode, budget_exhausted: bool, body: &str) -> Option<Self> {
2257 let normalized = refusal_wording(status, body).to_ascii_lowercase();
2258 if SECONDARY_WORDINGS
2259 .iter()
2260 .any(|wording| normalized.contains(wording))
2261 {
2262 return Some(Self::Secondary);
2263 }
2264 if status == StatusCode::TOO_MANY_REQUESTS {
2265 return Some(Self::Primary);
2266 }
2267 // An exhausted budget *explains* a response that failed; it does not make one that
2268 // succeeded into a failure. GitHub sets `x-ratelimit-remaining: 0` on the last
2269 // request the budget allowed as well as on the ones it then refuses, so reading
2270 // the header alone threw away a good answer — and, once refusals were retried,
2271 // replayed a request that had already taken effect.
2272 if !status.is_success() && budget_exhausted {
2273 return Some(Self::Primary);
2274 }
2275 // A successful response saying it: GitHub reports a GraphQL rate limit in the
2276 // `errors` of an HTTP 200, where nothing about the status says so at all.
2277 if status.is_success()
2278 && PRIMARY_WORDINGS
2279 .iter()
2280 .any(|wording| normalized.contains(wording))
2281 {
2282 return Some(Self::Primary);
2283 }
2284 None
2285 }
2286
2287 /// What this limiter is called where an operator can look it up.
2288 const fn name(self) -> &'static str {
2289 match self {
2290 Self::Primary => "GitHub's primary API rate limit",
2291 Self::Secondary => "GitHub's secondary rate limit",
2292 }
2293 }
2294
2295 /// What the endpoint an operator would go and check says about this limiter.
2296 const fn where_to_look(self) -> &'static str {
2297 match self {
2298 Self::Primary => {
2299 "That is the budget `gh api rate_limit` reports, so that endpoint says when it \
2300 comes back."
2301 }
2302 Self::Secondary => {
2303 "That limiter is not the primary API budget: `gh api rate_limit` reports the \
2304 primary budget and does not report this one, so budget showing there says \
2305 nothing about this refusal, and every further attempt extends it."
2306 }
2307 }
2308 }
2309
2310 /// The next step this limiter actually calls for.
2311 const fn what_to_do(self) -> &'static str {
2312 match self {
2313 Self::Primary => {
2314 "wait for the reset `gh api rate_limit` reports, then run the command again."
2315 }
2316 Self::Secondary => {
2317 "leave this board alone for a few minutes, then run the command again — or \
2318 raise pacing.min_mutation_interval_ms on this source so it writes more slowly."
2319 }
2320 }
2321 }
2322}
2323
2324/// One rate-limit refusal, and the wait GitHub asked for if it asked for one.
2325#[derive(Debug, Clone, Copy)]
2326struct Limited {
2327 limiter: Limiter,
2328 hint: Option<u64>,
2329 /// Which header the hint came from: `retry-after`, or an exhausted primary budget's
2330 /// `x-ratelimit-reset`.
2331 hinted_by: Hint,
2332}
2333
2334/// Where a refusal's hint came from, which is what its wait is named after.
2335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2336enum Hint {
2337 /// `retry-after`, or no hint at all.
2338 RetryAfter,
2339 /// An exhausted primary budget's `x-ratelimit-reset`.
2340 PrimaryReset,
2341}
2342
2343impl Limited {
2344 /// The wait this refusal is answered with, when the backing-off schedule is at `backoff`,
2345 /// and the cause it is named by: the hint, raised to the schedule's own next wait —
2346 /// GitHub really does send `retry-after: 0`, and retrying at once is the one move that
2347 /// extends a secondary limit — or the schedule alone when there is none.
2348 fn wait(self, backoff: Duration) -> (Duration, WaitCause) {
2349 match (self.hint, self.hinted_by) {
2350 (Some(hint), Hint::RetryAfter) => (
2351 Duration::from_secs(hint).max(backoff),
2352 pacing::cause::RETRY_AFTER,
2353 ),
2354 (Some(hint), Hint::PrimaryReset) => (
2355 Duration::from_secs(hint).max(backoff),
2356 pacing::cause::PRIMARY_RESET,
2357 ),
2358 (None, _) => (backoff, pacing::cause::BACKOFF),
2359 }
2360 }
2361
2362 /// What the caller is told once this source has waited as long as it may.
2363 ///
2364 /// Both limiters report as [`SourceError::RateLimited`], because that is what
2365 /// happened: the kind a caller matches on says a rate limit refused this, and nothing
2366 /// about *which* limiter it was makes it a different kind of failure. What differs is
2367 /// the operator's next step, and that is what the message carries — a secondary
2368 /// refusal read as a primary one sends an operator to `gh api rate_limit`, where the
2369 /// budget looks fine, and then back to retry the very burst that was refused.
2370 fn exhausted(
2371 self,
2372 doing: &str,
2373 waits: u32,
2374 waited: Duration,
2375 needed: Duration,
2376 budget: Duration,
2377 ) -> SourceError {
2378 SourceError::RateLimited {
2379 retry_after_seconds: self.hint,
2380 message: Some(format!(
2381 "{} refused this source while {doing}; it waited {} out over {} and was refused \
2382 again, and the next wait of {} would take it past the {} one call may spend \
2383 waiting. {} next: {}",
2384 self.limiter.name(),
2385 plural(waits, "refusal"),
2386 seconds(waited),
2387 seconds(needed),
2388 seconds(budget),
2389 self.limiter.where_to_look(),
2390 self.limiter.what_to_do(),
2391 )),
2392 }
2393 }
2394}
2395
2396/// One HTTP attempt's result, with what its response said about the rate limit.
2397///
2398/// The two travel together so the record and the outcome are written from the same place:
2399/// what a response said about the budget is only readable while that response is in hand,
2400/// and what the attempt *meant* is only decidable once its body has been read.
2401struct Attempted {
2402 result: Result<Value, Attempt>,
2403 limits: accounting::RateLimit,
2404 /// GitHub's own reported cost for this call, for a document that asked for it.
2405 reported_cost: Option<u64>,
2406 response_outcome: accounting::ResponseOutcome,
2407}
2408
2409/// One attempt's outcome: an error to report, or a rate limit to wait out.
2410enum Attempt {
2411 Failed(SourceError),
2412 Limited(Limited),
2413}
2414
2415fn plural(count: u32, thing: &str) -> String {
2416 if count == 1 {
2417 format!("{count} {thing}")
2418 } else {
2419 format!("{count} {thing}s")
2420 }
2421}
2422
2423fn seconds(duration: Duration) -> String {
2424 format!("{:.1}s", duration.as_secs_f64())
2425}
2426
2427/// The member [`stamp_served`] writes onto every node of a response that says when it last
2428/// changed: the `Date` that response was served at. No GitHub type has a field of this name.
2429const SERVED_AT: &str = "onetaskgraphServedAt";
2430
2431/// Write `served` onto every object of `data` carrying an `updatedAt`, so whatever reads a
2432/// node's time later knows the server's clock on the response that read it — which is what
2433/// decides whether that node's change token is given (see [`change_token::SETTLED`]).
2434fn stamp_served(data: &mut Value, served: &str) {
2435 match data {
2436 Value::Object(members) => {
2437 if members.contains_key("updatedAt") {
2438 members.insert(SERVED_AT.to_owned(), Value::String(served.to_owned()));
2439 }
2440 for member in members.values_mut() {
2441 stamp_served(member, served);
2442 }
2443 }
2444 Value::Array(items) => {
2445 for item in items {
2446 stamp_served(item, served);
2447 }
2448 }
2449 _ => {}
2450 }
2451}
2452
2453/// A header GitHub spells as a whole number of seconds, or `None` when this one is not.
2454///
2455/// A value that is present and unreadable is deliberately *not* an error. `retry-after` is
2456/// allowed by HTTP to be a date rather than a count, an intermediary can rewrite either
2457/// header, and neither is what makes a response a refusal — so the whole cost of one this
2458/// cannot read is that the refusal carries no hint and the backing-off schedule answers it
2459/// instead. Refusing the response over the header would turn a readable refusal into an
2460/// unreadable one, and refusing to *wait* would be the one wrong direction to fail in.
2461fn whole_seconds(value: Option<&reqwest::header::HeaderValue>) -> Option<u64> {
2462 value
2463 .and_then(|value| value.to_str().ok())
2464 .and_then(|value| value.trim().parse::<u64>().ok())
2465}
2466
2467/// A transport failure with every cause beneath it, outermost first.
2468///
2469/// The client's own text for a request it could not complete is `error sending request for
2470/// url (…)`, and the socket error that says why — a refused or reset connection, an exhausted
2471/// port range, a connection closed before its answer — is only in the chain of sources below
2472/// it. Those differ in what to do next, so all of them are kept.
2473pub(crate) fn transport_error(error: &(dyn std::error::Error + 'static)) -> String {
2474 let mut text = error.to_string();
2475 let mut cause = error.source();
2476 while let Some(next) = cause {
2477 let said = next.to_string();
2478 if !text.ends_with(&said) {
2479 text = format!("{text}: {said}");
2480 }
2481 cause = next.source();
2482 }
2483 text
2484}
2485
2486/// Every mutation this source sends creates content — an issue, a board item, a field of
2487/// one, a sub-issue link, a dependency, a comment — or edits or removes content of that
2488/// kind, and no query in [`graphql::DOCUMENTS`] does, so what the secondary limiter counts
2489/// and what the keyword says are the same set. That is what makes the keyword a sound test
2490/// rather than a convenient one: counting an edit or a removal the limiter might not have
2491/// counted costs a wait, and not counting one it did count costs the next fifty minutes.
2492pub(crate) fn is_mutation(query: &str) -> bool {
2493 query.trim_start().starts_with("mutation")
2494}
2495
2496/// What this source was doing, for a diagnostic that has to say so.
2497///
2498/// Read out of [`graphql::DOCUMENTS`], which is the inventory rather than a copy of it, so
2499/// a document added without a description is caught by that list's own gate instead of
2500/// falling through to the vague arm below.
2501fn operation_description(query: &str) -> &'static str {
2502 graphql::DOCUMENTS
2503 .iter()
2504 .find(|(document, _)| *document == query)
2505 .map_or("talking to GitHub", |(_, doing)| *doing)
2506}
2507
2508/// GitHub's published ceiling on content-generating requests in any one minute.
2509///
2510/// Pinned in `tests/fixtures/rate-limits.json` and gated against it, because it is
2511/// GitHub's number rather than this source's. This source paces at it over its window: a
2512/// content-creating request goes out at once while the minute's creations leave room for it,
2513/// and waits until they do otherwise — see the `pacing` module.
2514pub const CONTENT_CREATION_PER_MINUTE: u64 = 80;
2515/// The same ceiling as GitHub publishes it for any one hour, paced over its window as the
2516/// per-minute one is. Pinned beside its sibling so the gate would notice either one moving.
2517pub const CONTENT_CREATION_PER_HOUR: u64 = 500;
2518/// GitHub's published ceiling on secondary points in any one minute: what every GraphQL
2519/// request is charged against, a mutation [`SECONDARY_POINTS_PER_MUTATION`] and a query
2520/// [`SECONDARY_POINTS_PER_QUERY`]. Pinned and paced as [`CONTENT_CREATION_PER_MINUTE`] is.
2521pub const SECONDARY_POINTS_PER_MINUTE: u64 = 2_000;
2522/// The secondary points one GraphQL request carrying a mutation is charged.
2523pub const SECONDARY_POINTS_PER_MUTATION: u64 = 5;
2524/// The secondary points one GraphQL request carrying no mutation is charged.
2525pub const SECONDARY_POINTS_PER_QUERY: u64 = 1;
2526/// The fastest *steady* spacing of content-creating mutations that cannot exceed
2527/// [`CONTENT_CREATION_PER_MINUTE`], in milliseconds: 60000/80 is 750.
2528///
2529/// It is no longer the default. This source paces by GitHub's windows instead, so a copy's
2530/// few dozen writes go out as fast as GitHub answers them while the minute has room, rather
2531/// than 750 ms apart — which was most of a plan copy's wall time. An installation that wants
2532/// mutations spaced as well says so through `pacing.min_mutation_interval_ms`, and this is the
2533/// value that holds a long sustained burst under the per-minute bound by spacing alone.
2534pub const MIN_MUTATION_INTERVAL_MS: u64 = 60_000 / CONTENT_CREATION_PER_MINUTE;
2535/// First wait when a rate-limit refusal carries no hint; each further wait doubles it.
2536///
2537/// A doubling schedule from one second reaches a minute in six waits, which is GitHub's
2538/// own advice for a secondary limit — wait, and wait longer each time — without spending
2539/// the first minute of a transient refusal doing nothing.
2540pub const RETRY_BACKOFF_MS: u64 = 1_000;
2541/// Total time one call may spend waiting out rate limits before it reports a failure.
2542///
2543/// Two minutes is long enough to ride out the refusals a paced copy still collects and
2544/// short enough that a command an operator is watching returns. The bound is what makes
2545/// the wait a wait rather than a hang: a call refused past it ends in a diagnostic naming
2546/// the limiter, not in a process nobody can tell from a wedged one.
2547pub const RETRY_BUDGET_MS: u64 = 120_000;
2548
2549fn default_token_env() -> String {
2550 "GH_PROJECTS_TOKEN".to_owned()
2551}
2552fn default_endpoint() -> String {
2553 "https://api.github.com/graphql".to_owned()
2554}
2555
2556/// The name of a `Status` single-select option on the board.
2557///
2558/// Validated on the way in rather than checked later, so a blank option name — which
2559/// nothing on a board can be — is a state this type cannot hold.
2560#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2561#[serde(try_from = "String")]
2562#[schemars(extend("minLength" = 1))]
2563pub struct ColumnName(String);
2564
2565impl ColumnName {
2566 /// The option name, as the board spells it.
2567 fn as_str(&self) -> &str {
2568 &self.0
2569 }
2570}
2571
2572impl TryFrom<String> for ColumnName {
2573 type Error = String;
2574
2575 fn try_from(name: String) -> Result<Self, Self::Error> {
2576 if name.trim().is_empty() {
2577 return Err("a status_mapping option name cannot be blank".to_owned());
2578 }
2579 Ok(Self(name))
2580 }
2581}
2582
2583/// The two closed states this product can mean.
2584///
2585/// GitHub's `IssueClosedStateReason` also spells `DUPLICATE`, which nothing here ever writes:
2586/// an issue closed as one *reads* `cancelled`, because its work is another issue's, but this
2587/// product never decides on a person's behalf that two issues are the same work.
2588#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, schemars::JsonSchema)]
2589#[serde(rename_all = "kebab-case")]
2590pub enum ClosedState {
2591 /// `COMPLETED` — precisely done.
2592 Completed,
2593 /// `NOT_PLANNED` — precisely cancelled.
2594 NotPlanned,
2595}
2596
2597impl ClosedState {
2598 const fn reason(self) -> &'static str {
2599 match self {
2600 Self::Completed => "COMPLETED",
2601 Self::NotPlanned => "NOT_PLANNED",
2602 }
2603 }
2604}
2605
2606/// Configuration for one GitHub Projects v2 board.
2607///
2608/// It serializes to a document this same type reads back as itself, so a caller writing a
2609/// configuration — a consumer filing onto a board it configures — can build one here rather
2610/// than spell the shape again; an empty `metadata_fields` is left out, as one never set.
2611#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2612#[serde(default, deny_unknown_fields)]
2613pub struct GitHubProjectsConfig {
2614 /// Login of the user or organization which owns the board.
2615 pub owner: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates GitHub's owner grammar before private construction.
2616 /// The project number shown in the board's GitHub URL.
2617 pub project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` bounds this to a positive GraphQL Int.
2618 // 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.
2619 /// `owner/name` of the repository this source creates an issue in when the item's own
2620 /// `repositories` field does not decide it.
2621 ///
2622 /// An item naming exactly one repository is created there; a task or a document naming
2623 /// none or several is created in its parent project's repository; and a project, or a
2624 /// task or document with no parent, naming none or several is created here. A board
2625 /// has no repository of its own and `createIssue` requires one, so a write without
2626 /// this is refused naming the field. Reads never need it.
2627 pub repository: Option<String>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the `owner/name` grammar before private construction.
2628 // llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
2629 /// Environment variable containing a fine-grained token with Projects and Issues
2630 /// read/write plus Pull requests read-only access for every repository represented on
2631 /// the board.
2632 #[serde(default = "default_token_env")]
2633 pub token_env: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the environment-variable grammar.
2634 /// GraphQL endpoint. GitHub Enterprise installations may override it.
2635 #[serde(default = "default_endpoint")]
2636 pub endpoint: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` converts it to the private validated `Url`.
2637 /// Per-instance mapping from a status category to the option of the board's one
2638 /// `Status` field it lands on, for a task and for a project.
2639 ///
2640 /// The shared `StatusMapping` grammar: each value is one option name for both kinds,
2641 /// `null` to disable the category for both, or `{task, project}` naming it per kind,
2642 /// where a kind left out leaves the category unmapped for that kind. A category this
2643 /// does not mention keeps its shipped default for both kinds: `backlog` to "Backlog",
2644 /// `todo` to "Todo", `queued` to "Queued", `in-progress` to "In Progress", `done` to
2645 /// "Done" plus closed as completed, `cancelled` to "Cancelled" plus closed as not
2646 /// planned, and `draft` and `unknown` unmapped. A category it does mention gets no
2647 /// shipped default for a kind it leaves out. `done` and `cancelled` close the issue for
2648 /// either kind. No two categories may name one option for the same kind, ignoring case.
2649 /// `unknown` may name one existing option; every unknown word then lands on it and
2650 /// reads back as `unknown` under its name. Unlike `local-md`, this source cannot keep
2651 /// each unknown word because it never creates board options.
2652 #[serde(default)]
2653 pub status_mapping: StatusMapping,
2654 /// Per-instance mapping from a task's priority to an option of this board's
2655 /// single-select field named `Priority`.
2656 ///
2657 /// Absent, this source holds no priority: every task reads as `none`, and a write of any
2658 /// other priority is refused before it reaches this board. Present, each of `urgent`,
2659 /// `high`, `medium` and `low` it does not mention keeps its shipped default — `Urgent`,
2660 /// `High`, `Medium` and `Low` — and an item with no value in the `Priority` field reads
2661 /// as `none`, so writing `none` clears the value. Option names match case-insensitively;
2662 /// no two levels may name one option. Reads and writes never create the field or an
2663 /// option: `onetaskgraph sources fields <source> --apply` does, and a write naming one
2664 /// the board lacks is refused pointing there.
2665 #[serde(default)]
2666 pub priority_mapping: Option<PriorityMappingConfig>,
2667 /// Caller metadata values this source also writes to board text fields, so the board can
2668 /// filter on them.
2669 ///
2670 /// Absent or empty, nothing is projected. Each entry names a board text `field`, a
2671 /// top-level metadata `key` and an optional `path` of object keys walked inside that key's
2672 /// value. On every item write — create, update and copy, of a task, a project or a
2673 /// document — a string found there is written to the field, and nothing is sent when the
2674 /// field already holds it; nothing there, or `null`, clears the field when it holds a
2675 /// value; any other JSON type is refused before any mutation. The metadata comment in the
2676 /// issue body stays the one home of the value, and every read reports metadata from it.
2677 /// Reads and writes never create the field: `onetaskgraph sources fields <source>
2678 /// --apply` does, as a text field, and a write to a board lacking it, or holding a
2679 /// non-text field of that name, is refused pointing there.
2680 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2681 // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
2682 // list out, so both SDKs model an absent list as an empty one rather than as `null`.
2683 #[schemars(!skip_serializing_if)]
2684 pub metadata_fields: Vec<MetadataFieldConfig>,
2685 /// How fast this source writes, and how long it waits out a rate-limit refusal.
2686 ///
2687 /// Every field keeps its shipped default when it is absent, and the defaults are
2688 /// GitHub's own published limits rather than taste. See [`Pacing`].
2689 #[serde(default)]
2690 pub pacing: PacingConfig,
2691}
2692
2693/// Which option of the board's `Priority` field each priority lands on.
2694///
2695/// One member per level rather than a map, so a key that is not a level is refused where
2696/// the configuration is read, naming the levels there are. `none` is not a member: it is no
2697/// value in the field, not an option of it.
2698#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2699#[serde(default, deny_unknown_fields)]
2700pub struct PriorityMappingConfig {
2701 /// The option `urgent` lands on; `Urgent` when absent.
2702 pub urgent: Option<PriorityOptionName>,
2703 /// The option `high` lands on; `High` when absent.
2704 pub high: Option<PriorityOptionName>,
2705 /// The option `medium` lands on; `Medium` when absent.
2706 pub medium: Option<PriorityOptionName>,
2707 /// The option `low` lands on; `Low` when absent.
2708 pub low: Option<PriorityOptionName>,
2709}
2710
2711/// The name of an option of the board's `Priority` single-select field.
2712///
2713/// Validated on the way in, for the reason [`ColumnName`] is: nothing on a board can have a
2714/// blank name.
2715#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2716#[serde(try_from = "String")]
2717#[schemars(extend("minLength" = 1))]
2718pub struct PriorityOptionName(String);
2719
2720impl PriorityOptionName {
2721 /// The option name, as the board spells it.
2722 fn as_str(&self) -> &str {
2723 &self.0
2724 }
2725}
2726
2727impl TryFrom<String> for PriorityOptionName {
2728 type Error = String;
2729
2730 fn try_from(name: String) -> Result<Self, Self::Error> {
2731 if name.trim().is_empty() {
2732 return Err("a priority_mapping option name cannot be blank".to_owned());
2733 }
2734 Ok(Self(name))
2735 }
2736}
2737
2738/// The name of the board field a priority is held in.
2739pub const PRIORITY_FIELD: &str = "Priority";
2740
2741/// The four priorities a board option can hold, in the order a new `Priority` field lists
2742/// them. `none` is not among them: it is the field holding no value.
2743///
2744/// This list mirrors `Priority`, so it carries its own drift gate, in the shape [`CATEGORIES`]
2745/// does: [`level_position`] is a wildcard-free match, so a priority added to the shared
2746/// vocabulary fails to compile until it is placed there, and this crate's suite reconciles
2747/// this list and [`PriorityMappingConfig`]'s members against that enum's own derived schema.
2748pub const PRIORITY_LEVELS: [Priority; 4] = [
2749 Priority::Urgent,
2750 Priority::High,
2751 Priority::Medium,
2752 Priority::Low,
2753];
2754
2755/// Where one priority sits in [`PRIORITY_LEVELS`], or `None` for `none`, which is no option;
2756/// see that list for what this pins.
2757#[must_use]
2758pub const fn level_position(priority: Priority) -> Option<usize> {
2759 match priority {
2760 Priority::None => None,
2761 Priority::Urgent => Some(0),
2762 Priority::High => Some(1),
2763 Priority::Medium => Some(2),
2764 Priority::Low => Some(3),
2765 }
2766}
2767
2768/// This instance's complete priority-to-option mapping, read in both directions.
2769///
2770/// One option per level, held in [`PRIORITY_LEVELS`] order, once it is established that no
2771/// two levels name one option.
2772#[derive(Debug, Clone)]
2773struct PriorityMapping {
2774 options: [PriorityOptionName; 4],
2775}
2776
2777impl PriorityMapping {
2778 fn resolve(config: PriorityMappingConfig, instance: &SourceName) -> Result<Self, SourceError> {
2779 let shipped = |name: &str| PriorityOptionName(name.to_owned());
2780 let mapping = Self {
2781 options: [
2782 config.urgent.unwrap_or_else(|| shipped("Urgent")),
2783 config.high.unwrap_or_else(|| shipped("High")),
2784 config.medium.unwrap_or_else(|| shipped("Medium")),
2785 config.low.unwrap_or_else(|| shipped("Low")),
2786 ],
2787 };
2788 for (index, option) in mapping.options.iter().enumerate() {
2789 if let Some(earlier) = mapping.options[..index]
2790 .iter()
2791 .position(|other| other.as_str().eq_ignore_ascii_case(option.as_str()))
2792 {
2793 return Err(SourceError::Config {
2794 message: format!(
2795 "priority_mapping of source {instance} sends both {} and {} to the board \
2796 option {:?}; one option cannot read back as two priorities",
2797 PRIORITY_LEVELS[earlier],
2798 PRIORITY_LEVELS[index],
2799 option.as_str()
2800 ),
2801 });
2802 }
2803 }
2804 Ok(mapping)
2805 }
2806
2807 /// The option `priority` lands on, or `None` for `none`, which is no option at all.
2808 fn option(&self, priority: Priority) -> Option<&str> {
2809 level_position(priority).map(|index| self.options[index].as_str())
2810 }
2811
2812 /// The priority a board option name reports, or `None` when nothing maps to it.
2813 fn priority_of(&self, option: &str) -> Option<Priority> {
2814 self.options
2815 .iter()
2816 .position(|name| name.as_str().eq_ignore_ascii_case(option))
2817 .map(|index| PRIORITY_LEVELS[index])
2818 }
2819
2820 /// Every mapped option name, in the order a new `Priority` field lists them.
2821 fn names(&self) -> impl Iterator<Item = &str> {
2822 self.options.iter().map(PriorityOptionName::as_str)
2823 }
2824}
2825
2826/// One metadata value this source projects onto a board text field.
2827#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
2828#[serde(deny_unknown_fields)]
2829pub struct MetadataFieldConfig {
2830 /// The name of the board text field the value is written to.
2831 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.
2832 /// The top-level metadata key the value is read from. A key under the reserved
2833 /// `onetaskgraph.` prefix is refused.
2834 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.
2835 /// Object keys walked inside that key's value, outermost first. Absent or empty, the
2836 /// key's own value is the one projected. Left out of a serialized entry when empty.
2837 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2838 // Kept in the schema as `"default": []`, for the reason `metadata_fields`' is.
2839 #[schemars(!skip_serializing_if)]
2840 pub path: Vec<String>,
2841}
2842
2843/// The board fields no metadata value may be projected onto, compared ignoring case: the
2844/// three this source writes itself, and those GitHub owns on every board.
2845// 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.
2846const UNPROJECTABLE_FIELDS: [&str; 13] = [
2847 STATUS_FIELD,
2848 PRIORITY_FIELD,
2849 ORIGIN_FIELD,
2850 "Title",
2851 "Assignees",
2852 "Labels",
2853 "Linked pull requests",
2854 "Milestone",
2855 "Repository",
2856 "Reviewers",
2857 "Parent issue",
2858 "Sub-issues progress",
2859 "Type",
2860];
2861
2862/// One validated [`MetadataFieldConfig`] entry.
2863#[derive(Debug, Clone)]
2864struct MetadataField {
2865 field: ProjectedField,
2866 key: ProjectedKey,
2867 path: Vec<String>,
2868}
2869
2870/// The name of a board text field a metadata value is projected onto: never blank, never one
2871/// this source or GitHub writes, and never one another entry of the same source names.
2872#[derive(Debug, Clone, PartialEq, Eq)]
2873struct ProjectedField(String);
2874
2875/// The top-level metadata key a projected value is read from: never blank, and never under
2876/// the namespace this product reserves.
2877#[derive(Debug, Clone, PartialEq, Eq)]
2878struct ProjectedKey(String);
2879
2880impl std::ops::Deref for ProjectedField {
2881 type Target = str;
2882 fn deref(&self) -> &str {
2883 &self.0
2884 }
2885}
2886
2887impl std::ops::Deref for ProjectedKey {
2888 type Target = str;
2889 fn deref(&self) -> &str {
2890 &self.0
2891 }
2892}
2893
2894/// What one item's metadata says one projected field should hold.
2895#[derive(Debug, Clone, PartialEq, Eq)]
2896enum Projected {
2897 /// A string to hold.
2898 Text(String),
2899 /// Nothing: the key or a step of the path is absent, or the value is `null`.
2900 Nothing,
2901}
2902
2903impl MetadataField {
2904 /// Validate every entry of one instance's `metadata_fields`, refusing the first that
2905 /// cannot stand, naming the source and the entry.
2906 fn resolve(
2907 configured: Vec<MetadataFieldConfig>,
2908 instance: &SourceName,
2909 ) -> Result<Vec<Self>, SourceError> {
2910 let mut resolved: Vec<Self> = Vec::with_capacity(configured.len());
2911 for (index, entry) in configured.into_iter().enumerate() {
2912 let refuse = |why: String| SourceError::Config {
2913 message: format!(
2914 "metadata_fields[{index}] of source {instance} (field {:?}, key {:?}) {why}",
2915 entry.field, entry.key
2916 ),
2917 };
2918 if entry.field.trim().is_empty() {
2919 return Err(refuse("names a blank field".to_owned()));
2920 }
2921 if entry.key.trim().is_empty() {
2922 return Err(refuse("names a blank key".to_owned()));
2923 }
2924 if entry.key.split('.').next() == Some(MetadataKey::RESERVED_NAMESPACE) {
2925 return Err(refuse(format!(
2926 "names a key under the reserved \"{}.\" prefix, which this product keeps \
2927 for its own keys; next: project a caller key instead",
2928 MetadataKey::RESERVED_NAMESPACE
2929 )));
2930 }
2931 if let Some(owned) = UNPROJECTABLE_FIELDS
2932 .iter()
2933 .find(|owned| owned.eq_ignore_ascii_case(&entry.field))
2934 {
2935 return Err(refuse(format!(
2936 "names the board field {owned:?}, which this source or GitHub already \
2937 writes; next: name a text field of your own"
2938 )));
2939 }
2940 if let Some(earlier) = resolved
2941 .iter()
2942 .position(|other| other.field.eq_ignore_ascii_case(&entry.field))
2943 {
2944 return Err(refuse(format!(
2945 "names the same board field as metadata_fields[{earlier}]; one field \
2946 cannot hold two values"
2947 )));
2948 }
2949 resolved.push(Self {
2950 field: ProjectedField(entry.field),
2951 key: ProjectedKey(entry.key),
2952 path: entry.path,
2953 });
2954 }
2955 Ok(resolved)
2956 }
2957
2958 /// The path as a refusal spells it: `[]` for the key's own value.
2959 fn spelled_path(&self) -> String {
2960 serde_json::to_string(&self.path).unwrap_or_else(|_| format!("{:?}", self.path))
2961 }
2962
2963 /// What `metadata` says this field should hold, or the refusal for a value no text field
2964 /// can hold.
2965 fn projected(
2966 &self,
2967 metadata: &BTreeMap<String, Value>,
2968 instance: &SourceName,
2969 ) -> Result<Projected, SourceError> {
2970 let mut value = metadata.get(&*self.key);
2971 for step in &self.path {
2972 value = value.and_then(|held| held.get(step.as_str()));
2973 }
2974 let found = match value {
2975 None | Some(Value::Null) => return Ok(Projected::Nothing),
2976 Some(Value::String(text)) => return Ok(Projected::Text(text.clone())),
2977 Some(Value::Bool(_)) => "a boolean",
2978 Some(Value::Number(_)) => "a number",
2979 Some(Value::Array(_)) => "an array",
2980 Some(Value::Object(_)) => "an object",
2981 };
2982 Err(SourceError::Refused {
2983 message: format!(
2984 "source {instance} projects metadata key {:?} at path {} onto its board text \
2985 field {:?}, and this item holds {found} there; only a string, null or nothing \
2986 can be written to a text field; next: store a string there, or remove the \
2987 value",
2988 &*self.key,
2989 self.spelled_path(),
2990 &*self.field
2991 ),
2992 })
2993 }
2994}
2995
2996/// What one item's `Priority` field says, read through this instance's mapping.
2997#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
2998enum HeldPriority {
2999 /// A priority this source reports: an option the mapping names, or no value (`none`).
3000 Read(Priority),
3001 /// An option the mapping does not name, which is never read as a level or as `none`.
3002 Unmapped(String),
3003}
3004
3005/// How fast this source writes, and how long it waits out a rate-limit refusal.
3006///
3007/// Configurable because a GitHub Enterprise installation sets its own limits and an
3008/// operator who has already been refused may want to go slower still — not because the
3009/// defaults are guesses.
3010#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3011#[serde(default, deny_unknown_fields)]
3012pub struct PacingConfig {
3013 /// Shortest interval between two content-creating mutations, in milliseconds.
3014 ///
3015 /// Zero sends them as fast as they are asked for, which is what a fixture server on
3016 /// loopback wants and what no board on github.com does. At most [`MAX_PACING_MS`].
3017 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.
3018 /// First wait when a rate-limit refusal carries no hint, in milliseconds. Each
3019 /// further wait of the same call doubles it. At most [`MAX_PACING_MS`], and never
3020 /// zero while there is a budget to spend, because a schedule of zero-length waits
3021 /// consumes none of it and so never ends.
3022 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.
3023 /// Total time one call may spend waiting out rate limits, in milliseconds.
3024 ///
3025 /// Zero reports the refusal rather than waiting at all. At most [`MAX_PACING_MS`]:
3026 /// the bound is what makes this a wait rather than a hang.
3027 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.
3028}
3029
3030/// The largest any pacing setting may be, in milliseconds.
3031///
3032/// One hour. GitHub's own harshest published bound on content-generating requests works
3033/// out at one every 7.2 seconds, so an hour is already three orders of magnitude past
3034/// anything a real limit asks for, and past it the settings stop describing pacing at all:
3035/// a wait budget beyond it is the unbounded wait this whole mechanism exists to replace,
3036/// and an interval beyond it is a command that never sends its second mutation. It also
3037/// keeps the clock arithmetic in [`GitHubProjectsSource::reserve_mutation_slot`] inside
3038/// what a `Duration` can hold on every platform.
3039pub const MAX_PACING_MS: u64 = 3_600_000;
3040
3041/// [`PacingConfig`] with every default resolved and every value checked, which is what the
3042/// source holds.
3043///
3044/// Unset, `min_mutation_interval_ms` spaces nothing, and every request is paced by GitHub's
3045/// secondary windows alone — see the `pacing` module; set, it spaces content-creating mutations
3046/// on top of those windows, [`MIN_MUTATION_INTERVAL_MS`] being the spacing that holds a sustained
3047/// burst under the per-minute bound by spacing alone; and zero sends every request as fast as it
3048/// is asked for, windows included.
3049#[derive(Debug, Clone, Copy)]
3050struct Pacing {
3051 /// Whether requests are held for GitHub's secondary windows: always, unless
3052 /// `min_mutation_interval_ms` is set to exactly zero, which has always asked for no
3053 /// pacing at all — what a fixture server on loopback wants and no board on github.com does.
3054 windows: bool,
3055 min_mutation_interval: Duration,
3056 retry_backoff: Duration,
3057 retry_budget: Duration,
3058}
3059
3060impl Pacing {
3061 /// Resolve one instance's pacing, refusing a configuration that would not pace at all.
3062 fn resolve(config: PacingConfig, instance: &SourceName) -> Result<Self, SourceError> {
3063 let bounded = |value: Option<u64>, default: u64, field: &str| match value {
3064 Some(value) if value > MAX_PACING_MS => Err(SourceError::Config {
3065 message: format!(
3066 "pacing.{field} of source {instance} is {value} ms, and the most any pacing \
3067 setting may be is {MAX_PACING_MS} ms — an hour, which is already far past \
3068 GitHub's own harshest published limit"
3069 ),
3070 }),
3071 Some(value) => Ok(Duration::from_millis(value)),
3072 None => Ok(Duration::from_millis(default)),
3073 };
3074 let retry_backoff = bounded(
3075 config.retry_backoff_ms,
3076 RETRY_BACKOFF_MS,
3077 "retry_backoff_ms",
3078 )?;
3079 let retry_budget = bounded(config.retry_budget_ms, RETRY_BUDGET_MS, "retry_budget_ms")?;
3080 if retry_backoff.is_zero() && !retry_budget.is_zero() {
3081 return Err(SourceError::Config {
3082 message: format!(
3083 "pacing.retry_backoff_ms of source {instance} is 0 while \
3084 pacing.retry_budget_ms is {} ms; a schedule of zero-length waits spends \
3085 none of that budget, so it would retry a refusal forever. Set a backoff of \
3086 at least 1 ms, or set retry_budget_ms to 0 to report a refusal without \
3087 waiting at all",
3088 retry_budget.as_millis()
3089 ),
3090 });
3091 }
3092 Ok(Self {
3093 windows: config.min_mutation_interval_ms != Some(0),
3094 min_mutation_interval: bounded(
3095 config.min_mutation_interval_ms,
3096 0,
3097 "min_mutation_interval_ms",
3098 )?,
3099 retry_backoff,
3100 retry_budget,
3101 })
3102 }
3103}
3104
3105/// Factory for [`GitHubProjectsSource`].
3106#[derive(Debug, Clone, Copy, Default)]
3107pub struct Plugin;
3108
3109impl SourcePlugin for Plugin {
3110 fn kind(&self) -> &'static str {
3111 KIND
3112 }
3113 /// The endpoint, the owner and the board's number: what names one board.
3114 fn remote_identity(&self, config: &Value) -> Option<String> {
3115 let config: GitHubProjectsConfig = serde_json::from_value(config.clone()).ok()?;
3116 Some(format!(
3117 "{}\n{}\n{}",
3118 config.endpoint, config.owner, config.project_number
3119 ))
3120 }
3121 fn config_schema(&self) -> Schema {
3122 schema_for!(GitHubProjectsConfig)
3123 }
3124 fn build(
3125 &self,
3126 name: &SourceName,
3127 config: &Value,
3128 secrets: &dyn SecretResolver,
3129 ) -> Result<Box<dyn TaskSource>, SourceError> {
3130 self.build_recording_into(name, config, secrets, Arc::new(Accounting::new()))
3131 }
3132
3133 fn build_with_clock(
3134 &self,
3135 name: &SourceName,
3136 config: &Value,
3137 secrets: &dyn SecretResolver,
3138 clock: SharedClock,
3139 ) -> Result<Box<dyn TaskSource>, SourceError> {
3140 self.build_recording_with_clock(name, config, secrets, Arc::new(Accounting::new()), clock)
3141 }
3142}
3143
3144impl Plugin {
3145 /// Build a source recording every request it sends into an accounting the caller holds.
3146 ///
3147 /// [`SourcePlugin::build`] is this with an accounting of its own, which is what the
3148 /// registry gets. This is for a caller that is also calling GitHub itself and wants one
3149 /// session total rather than two — see [`accounting`] and
3150 /// [`GitHubProjectsSource::recording_into`].
3151 ///
3152 /// # Errors
3153 ///
3154 /// Exactly [`SourcePlugin::build`]'s, with the same source name in front of each:
3155 /// [`SourceError::Config`] for configuration this plugin cannot use and
3156 /// [`SourceError::Auth`] for a credential it cannot find.
3157 pub fn build_recording_into(
3158 &self,
3159 name: &SourceName,
3160 config: &Value,
3161 secrets: &dyn SecretResolver,
3162 ledger: Arc<Accounting>,
3163 ) -> Result<Box<dyn TaskSource>, SourceError> {
3164 self.build_recording_with_clock(name, config, secrets, ledger, system_clock())
3165 }
3166
3167 fn build_recording_with_clock(
3168 &self,
3169 name: &SourceName,
3170 config: &Value,
3171 secrets: &dyn SecretResolver,
3172 ledger: Arc<Accounting>,
3173 clock: SharedClock,
3174 ) -> Result<Box<dyn TaskSource>, SourceError> {
3175 let config: GitHubProjectsConfig =
3176 serde_json::from_value(config.clone()).map_err(|e| SourceError::Config {
3177 message: format!("source {name}: {e}"),
3178 })?;
3179 let prefix = format!("source {name}: ");
3180 let mut source = GitHubProjectsSource::recording_into(name, config, secrets, ledger)
3181 .map_err(|error| match error {
3182 // The shared `StatusMapping::distinct` names the source itself.
3183 SourceError::Config { message } if message.starts_with(&prefix) => {
3184 SourceError::Config { message }
3185 }
3186 SourceError::Config { message } => SourceError::Config {
3187 message: format!("{prefix}{message}"),
3188 },
3189 SourceError::Auth { message } => SourceError::Auth {
3190 message: format!("source {name}: {message}"),
3191 },
3192 other => other,
3193 })?;
3194 source.clock = clock;
3195 Ok(Box::new(source))
3196 }
3197}
3198
3199/// Where a status category lands on this board, once configuration is resolved.
3200#[derive(Debug, Clone, PartialEq, Eq)]
3201enum StatusTarget {
3202 /// Not usable against this instance for this kind, and why.
3203 Disabled(UnmappedStatus),
3204 /// The board's `Status` option of this name.
3205 Column(ColumnName),
3206 /// A closed issue, with both its board option and the reason that says which closed it means.
3207 // 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.
3208 Terminal(ColumnName, ClosedState),
3209}
3210
3211/// Every status category, in the order the vocabulary declares them.
3212///
3213/// This list mirrors `StatusCategory`, so it carries its own drift gate rather than a
3214/// reviewer's attention: [`category_position`] is a wildcard-free match, so a variant
3215/// added to the shared vocabulary fails to compile until it is named there, and this
3216/// crate's suite reconciles this list against that enum's own derived schema, which is
3217/// generated from the variants rather than written beside them. The schema is what
3218/// catches a list left one short — a list checking only the positions it already holds
3219/// would pass while every mapping indexed by the new position panicked.
3220pub const CATEGORIES: [StatusCategory; 8] = [
3221 StatusCategory::Draft,
3222 StatusCategory::Backlog,
3223 StatusCategory::Todo,
3224 StatusCategory::Queued,
3225 StatusCategory::InProgress,
3226 StatusCategory::Done,
3227 StatusCategory::Cancelled,
3228 StatusCategory::Unknown,
3229];
3230
3231/// Where one category sits in [`CATEGORIES`]; see that list for what this pins.
3232#[must_use]
3233pub const fn category_position(category: StatusCategory) -> usize {
3234 match category {
3235 StatusCategory::Draft => 0,
3236 StatusCategory::Backlog => 1,
3237 StatusCategory::Todo => 2,
3238 StatusCategory::Queued => 3,
3239 StatusCategory::InProgress => 4,
3240 StatusCategory::Done => 5,
3241 StatusCategory::Cancelled => 6,
3242 StatusCategory::Unknown => 7,
3243 }
3244}
3245
3246/// The spelling a status category is configured and reported under.
3247fn category_name(category: StatusCategory) -> &'static str {
3248 match category {
3249 StatusCategory::Draft => "draft",
3250 StatusCategory::Backlog => "backlog",
3251 StatusCategory::Todo => "todo",
3252 StatusCategory::Queued => "queued",
3253 StatusCategory::InProgress => "in-progress",
3254 StatusCategory::Done => "done",
3255 StatusCategory::Cancelled => "cancelled",
3256 StatusCategory::Unknown => "unknown",
3257 }
3258}
3259
3260/// A shipped default's option name.
3261///
3262/// The literals below are this file's own and non-blank, and they are validated by the
3263/// one constructor a configured name goes through rather than beside it.
3264fn shipped_column(name: &'static str) -> ColumnName {
3265 ColumnName::try_from(name.to_owned()).expect("a shipped default names a board option")
3266}
3267
3268/// The shipped default for one category this instance's `status_mapping` does not mention,
3269/// for either kind.
3270fn shipped_default(category: StatusCategory) -> StatusTarget {
3271 match category {
3272 StatusCategory::Backlog => StatusTarget::Column(shipped_column("Backlog")),
3273 StatusCategory::Todo => StatusTarget::Column(shipped_column("Todo")),
3274 StatusCategory::Queued => StatusTarget::Column(shipped_column("Queued")),
3275 StatusCategory::InProgress => StatusTarget::Column(shipped_column("In Progress")),
3276 StatusCategory::Done => {
3277 StatusTarget::Terminal(shipped_column("Done"), ClosedState::Completed)
3278 }
3279 StatusCategory::Cancelled => {
3280 StatusTarget::Terminal(shipped_column("Cancelled"), ClosedState::NotPlanned)
3281 }
3282 StatusCategory::Draft | StatusCategory::Unknown => {
3283 StatusTarget::Disabled(UnmappedStatus::Unconfigured)
3284 }
3285 }
3286}
3287
3288/// The two kinds a status is written and read for, each with its own half of the mapping.
3289const STATUS_KINDS: [ItemKind; 2] = [ItemKind::Task, ItemKind::Project];
3290
3291/// This instance's complete category-to-target mapping for each kind, read in both
3292/// directions.
3293///
3294/// One target per category per kind, held at that category's own [`category_position`], so
3295/// a category missing from the mapping, named twice in it, or filed out of order is a state
3296/// this type cannot hold rather than one [`Self::target`] has to defend against. Both kinds'
3297/// targets are options of the board's one `Status` field.
3298#[derive(Debug, Clone)]
3299struct BoardStatuses {
3300 tasks: [StatusTarget; CATEGORIES.len()],
3301 projects: [StatusTarget; CATEGORIES.len()],
3302}
3303
3304impl BoardStatuses {
3305 /// Resolve `configured` against the shipped defaults, refusing two categories one kind
3306 /// would read back from one option.
3307 ///
3308 /// A category the mapping does not mention keeps its shipped default for both kinds; one
3309 /// it does mention is exactly what it configures, so a per-kind object leaves the kind it
3310 /// omits unmapped rather than defaulted.
3311 fn resolve(configured: &StatusMapping, instance: &SourceName) -> Result<Self, SourceError> {
3312 let resolve_kind =
3313 |kind: ItemKind| -> Result<[StatusTarget; CATEGORIES.len()], SourceError> {
3314 // `CATEGORIES[position] == category` for every category — the crate's suite
3315 // asserts it — so mapping the list in order fills each category's own slot.
3316 let mut targets = CATEGORIES.map(shipped_default);
3317 for (slot, category) in targets.iter_mut().zip(CATEGORIES) {
3318 if !configured.mentions(category) {
3319 continue;
3320 }
3321 *slot = match configured.name_for(category, kind) {
3322 Err(why) => StatusTarget::Disabled(why),
3323 Ok(name) => {
3324 let option = ColumnName::try_from(name.as_str().to_owned())
3325 .map_err(|message| SourceError::Config { message })?;
3326 match category {
3327 StatusCategory::Done => {
3328 StatusTarget::Terminal(option, ClosedState::Completed)
3329 }
3330 StatusCategory::Cancelled => {
3331 StatusTarget::Terminal(option, ClosedState::NotPlanned)
3332 }
3333 _ => StatusTarget::Column(option),
3334 }
3335 }
3336 };
3337 }
3338 StatusMapping::distinct(
3339 instance,
3340 kind,
3341 CATEGORIES
3342 .iter()
3343 .zip(&targets)
3344 .filter_map(|(category, target)| target.option().map(|o| (*category, o))),
3345 )?;
3346 Ok(targets)
3347 };
3348 Ok(Self {
3349 tasks: resolve_kind(ItemKind::Task)?,
3350 projects: resolve_kind(ItemKind::Project)?,
3351 })
3352 }
3353
3354 /// Every category's target for `kind`, in category order.
3355 const fn targets(&self, kind: ItemKind) -> &[StatusTarget; CATEGORIES.len()] {
3356 match kind {
3357 ItemKind::Task => &self.tasks,
3358 ItemKind::Project => &self.projects,
3359 }
3360 }
3361
3362 fn target(&self, kind: ItemKind, category: StatusCategory) -> &StatusTarget {
3363 &self.targets(kind)[category_position(category)]
3364 }
3365
3366 /// The category a board option name reports for `kind`, or `None` when nothing of that
3367 /// kind maps to it.
3368 fn category_of(&self, kind: ItemKind, option: &str) -> Option<StatusCategory> {
3369 CATEGORIES.into_iter().find(|category| {
3370 self.target(kind, *category)
3371 .option()
3372 .is_some_and(|name| name.eq_ignore_ascii_case(option))
3373 })
3374 }
3375
3376 /// Every option name either kind maps a category to, each once ignoring case, in
3377 /// category order with a task's name before a project's — what the guarded setup asks
3378 /// the `Status` field to hold.
3379 fn wanted(&self) -> Vec<String> {
3380 let mut wanted: Vec<String> = Vec::new();
3381 for category in CATEGORIES {
3382 for kind in STATUS_KINDS {
3383 if let Some(name) = self.target(kind, category).option()
3384 && !wanted.iter().any(|held| held.eq_ignore_ascii_case(name))
3385 {
3386 wanted.push(name.to_owned());
3387 }
3388 }
3389 }
3390 wanted
3391 }
3392
3393 /// The status an item of `kind` reports, from the three things a read of it says: its
3394 /// board `Status` option, whether its issue is closed, and the reason it was closed with.
3395 ///
3396 /// **A closed issue's category follows its closure**, by [`closed_category`]: completed
3397 /// or no reason reads `done`, not planned and duplicate read `cancelled`, and any other
3398 /// reason reads `unknown`. `REOPENED`-while-closed is a state this source can never
3399 /// produce, so it is read permissively rather than refused — reads are faithful, and
3400 /// refusals belong on writes.
3401 ///
3402 /// **Its name follows the closure too, unless the option agrees with it.** The option's
3403 /// own name is kept when this kind's mapping reads that option as the same category, or
3404 /// does not name it at all — so a closed issue in a "Shipped" column reports `done`
3405 /// named `Shipped`. An option the mapping reads as another category contradicts the
3406 /// closure, and so does no option at all: the name is then the option the mapping gives
3407 /// the closure's category, so an issue closed as completed at `Todo` reads `done` named
3408 /// by the board's `done` option, and a destination reading `Todo` as todo is never handed
3409 /// it. An `unknown` closure keeps the option, or `Closed` without one.
3410 ///
3411 /// An open item's option reads through its own kind's mapping, and an option that mapping
3412 /// does not name reads as `Unknown` under its own name.
3413 ///
3414 /// One function of those three rather than of a response, so a narrow status write can
3415 /// answer what a re-read would report by applying it to the state it has just written.
3416 fn status(
3417 &self,
3418 kind: ItemKind,
3419 option: Option<&str>,
3420 closed: bool,
3421 reason: Option<&str>,
3422 ) -> Status {
3423 if closed {
3424 let category = closed_category(reason);
3425 let agrees = option.filter(|option| {
3426 category == StatusCategory::Unknown
3427 || self
3428 .category_of(kind, option)
3429 .is_none_or(|read| read == category)
3430 });
3431 let name = agrees.or_else(|| self.target(kind, category).option());
3432 let fallback = match category {
3433 StatusCategory::Done => "Done",
3434 StatusCategory::Cancelled => "Cancelled",
3435 _ => "Closed",
3436 };
3437 return Status {
3438 category,
3439 name: name.or(option).unwrap_or(fallback).to_owned(),
3440 };
3441 }
3442 let name = option.unwrap_or("Open").to_owned();
3443 Status {
3444 category: self
3445 .category_of(kind, &name)
3446 .unwrap_or(StatusCategory::Unknown),
3447 name,
3448 }
3449 }
3450
3451 /// The option a closed item's `Status` has to hold for its card to agree with its
3452 /// closure, and the category that closure reads as — or `None` when the item is open,
3453 /// its closure reads `unknown`, or its option already agrees.
3454 ///
3455 /// What `task status reconcile` writes: only `done` and `cancelled` closures are brought
3456 /// in line, each to the one option the mapping gives its category — an item with no
3457 /// option, or at one the mapping does not name, included.
3458 fn contradicted(
3459 &self,
3460 kind: ItemKind,
3461 option: Option<&str>,
3462 closed: bool,
3463 reason: Option<&str>,
3464 ) -> Option<(ClosedAs, &str)> {
3465 if !closed {
3466 return None;
3467 }
3468 let closed_as = match closed_category(reason) {
3469 StatusCategory::Done => ClosedAs::Done,
3470 StatusCategory::Cancelled => ClosedAs::Cancelled,
3471 _ => return None,
3472 };
3473 let wanted = self.target(kind, closed_as.category()).option()?;
3474 if option.is_some_and(|option| option.eq_ignore_ascii_case(wanted)) {
3475 return None;
3476 }
3477 Some((closed_as, wanted))
3478 }
3479}
3480
3481/// The category a closed issue reads as, from the reason it was closed with.
3482///
3483/// `COMPLETED`, and no reason at all, is finished work; `NOT_PLANNED` and `DUPLICATE` are both
3484/// work nobody will do here — a duplicate's work is the other issue's — and any other reason
3485/// is one this source cannot read a category from.
3486fn closed_category(reason: Option<&str>) -> StatusCategory {
3487 match reason {
3488 None | Some("COMPLETED") => StatusCategory::Done,
3489 Some("NOT_PLANNED" | "DUPLICATE") => StatusCategory::Cancelled,
3490 Some(_) => StatusCategory::Unknown,
3491 }
3492}
3493
3494impl BoardStatuses {
3495 /// For each kind, the option names it maps a category to that `existing` lacks, ignoring
3496 /// case; a kind lacking none is left out.
3497 fn missing_by_kind(&self, existing: &[StatusOption]) -> Vec<KindMissing> {
3498 STATUS_KINDS
3499 .into_iter()
3500 .filter_map(|kind| {
3501 let missing: Vec<String> = self
3502 .targets(kind)
3503 .iter()
3504 .filter_map(StatusTarget::option)
3505 .filter(|wanted| {
3506 !existing
3507 .iter()
3508 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
3509 })
3510 .map(str::to_owned)
3511 .collect();
3512 (!missing.is_empty()).then_some(KindMissing { kind, missing })
3513 })
3514 .collect()
3515 }
3516}
3517
3518impl StatusTarget {
3519 /// The board option this target selects, or `None` for an unmapped one.
3520 fn option(&self) -> Option<&str> {
3521 match self {
3522 Self::Column(name) | Self::Terminal(name, _) => Some(name.as_str()),
3523 Self::Disabled(_) => None,
3524 }
3525 }
3526}
3527
3528// 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.
3529/// One repository this source can create an issue in, as `owner/name`.
3530///
3531/// Every `createIssue` this source sends names one of these: the item's own single
3532/// `repositories` entry, else its parent project issue's repository, else the configured
3533/// [`GitHubProjectsConfig::repository`]. [`GitHubProjectsSource::creation_target`] makes
3534/// that choice and says what it refuses before `createIssue`.
3535// llmlint: ignore-end[comments_earn_their_place, contracts_have_one_source_or_a_drift_gate]
3536#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
3537struct RepositoryTarget {
3538 owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
3539 name: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
3540}
3541
3542impl RepositoryTarget {
3543 fn parse(value: &str) -> Result<Self, SourceError> {
3544 let (owner, name) = value.split_once('/').ok_or_else(|| SourceError::Config {
3545 message: format!(
3546 "repository must be spelled owner/name; {value:?} names no repository"
3547 ),
3548 })?;
3549 if !valid_github_owner(owner) || !valid_github_repository_name(name) {
3550 return Err(SourceError::Config {
3551 message: format!(
3552 "repository must be spelled owner/name with a GitHub login and one \
3553 repository name; {value:?} is not"
3554 ),
3555 });
3556 }
3557 Ok(Self {
3558 owner: owner.to_owned(),
3559 name: name.to_owned(),
3560 })
3561 }
3562
3563 /// The one host whose repositories this source creates issues in, spelled once: it is
3564 /// what [`Self::origin`] renders and what [`Self::from_origin`] accepts.
3565 const HOST: &str = "github.com";
3566
3567 fn origin(&self) -> String {
3568 format!("{}/{}/{}", Self::HOST, self.owner, self.name)
3569 }
3570
3571 /// The repository a normalized origin names, or why it is none this source can create
3572 /// an issue in: another host, or more or fewer than `owner/name` under this one.
3573 fn from_origin(origin: &Repository) -> Result<Self, String> {
3574 let not_here = || {
3575 format!(
3576 "{} is not a {}/owner/name repository",
3577 origin.as_str(),
3578 Self::HOST
3579 )
3580 };
3581 let (host, rest) = origin.as_str().split_once('/').ok_or_else(not_here)?;
3582 if host != Self::HOST {
3583 return Err(not_here());
3584 }
3585 Self::parse(rest).map_err(|_| not_here())
3586 }
3587
3588 fn slug(&self) -> String {
3589 format!("{}/{}", self.owner, self.name)
3590 }
3591}
3592
3593/// A source which reads GitHub afresh for every operation.
3594pub struct GitHubProjectsSource {
3595 /// This source's configured name, used both to tell a far end naming this source
3596 /// from one naming a system it knows nothing about, and to name the instance a
3597 /// status refusal is about.
3598 name: SourceName,
3599 owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after full GitHub-owner validation.
3600 project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after GraphQL-Int validation.
3601 repository: Option<RepositoryTarget>,
3602 endpoint: Url,
3603 token: SecretString,
3604 credential_name: String, // llmlint: ignore[invalid_states_unrepresentable] Private diagnostic value constructed only after environment-name validation.
3605 statuses: BoardStatuses,
3606 /// Where each priority lands on this board, or `None` when this instance holds none.
3607 priorities: Option<PriorityMapping>,
3608 /// The metadata values this instance projects onto board text fields, in configured order.
3609 metadata_fields: Vec<MetadataField>,
3610 client: Client,
3611 asset_client: Client,
3612 /// Every item this source has created in this command, in the order it created them —
3613 /// dropped by [`TaskSource::end_command`].
3614 ///
3615 /// GitHub's `projectV2.items` is eventually consistent: an issue added to a board with
3616 /// `addProjectV2ItemById` is routinely absent from the very next read of that board, so
3617 /// a copy resolving a dependency on an item it had just created refused it as not
3618 /// found. A board read is completed from this — an item remembered here and absent from
3619 /// the read is added back, because the board really does hold it and only the read is
3620 /// behind.
3621 ///
3622 /// It is not a cache of a user's work: nothing is remembered that this process did not
3623 /// itself just write, it lives and dies with the process, and it is never consulted for
3624 /// an item this source did not create.
3625 created: Mutex<Vec<Resolved>>,
3626 /// Every item that already existed and that this source has written in this command, as
3627 /// it wrote it — dropped by [`TaskSource::end_command`].
3628 ///
3629 /// The other half of [`Self::created`], held on the same terms and for the reason a
3630 /// narrowed read needs it: an answer from GitHub's search or from the board's own field
3631 /// filter is an index behind a write this process made moments ago, so a query matching
3632 /// what this process just wrote onto an existing item would otherwise miss it. Nothing
3633 /// is remembered that this process did not itself just write.
3634 updated: Mutex<Vec<Resolved>>,
3635 /// Every issue this source has added a comment to or edited a comment of in this command
3636 /// — dropped by [`TaskSource::end_command`].
3637 ///
3638 /// A comment-activity read is narrowed by GitHub's issue search, whose `updated:` index
3639 /// lags the write that moved an issue's `updatedAt`, and neither [`Self::created`] nor
3640 /// [`Self::updated`] is moved by a comment, so an issue this process had just commented
3641 /// on was missing from such a read — or ruled out by the `updatedAt` its own record held
3642 /// from before — until the index caught up. Each id here is a candidate of every such
3643 /// search-narrowed read, and wherever it is a candidate its comments are read rather than
3644 /// it being ruled out by a stale `updatedAt`; that read is of the issue's own node, so it
3645 /// is current. It holds ids alone: nothing of a comment is remembered. A comment another
3646 /// process wrote is still found only once the index has it.
3647 commented: Mutex<Vec<NativeId>>,
3648 /// How fast this source writes, and how long it waits out a refusal.
3649 pacing: Pacing,
3650 /// When the last content-creating mutation finished, or the moment the furthest-out
3651 /// reserved slot releases the next one, whichever is later — so the one after it can be
3652 /// spaced from that, when `pacing.min_mutation_interval_ms` asks for a spacing. See
3653 /// [`GitHubProjectsSource::paced`] for why completion rather than release is what it is
3654 /// measured from.
3655 last_mutation: Mutex<Option<Duration>>,
3656 /// GitHub's secondary windows as this source has charged them; see the `pacing` module.
3657 windows: Mutex<pacing::Windows>,
3658 /// The tasks a project holds, as a copy's batched read of the project and every one of them
3659 /// found them — see [`TaskSource::read_ahead_for_copy`] — for the length of one command, so
3660 /// a listing of that project's tasks is answered without a read of its own.
3661 task_children: Mutex<BTreeMap<NativeId, Vec<Resolved>>>,
3662 /// The web address of each issue this source created in the current command, as its
3663 /// `createIssue` answered it — what [`TaskSource::written_location`] answers, without a
3664 /// request.
3665 written: Mutex<BTreeMap<NativeId, String>>,
3666 /// What a copy has held back of the items it created, between
3667 /// [`TaskSource::begin_deferred_writes`] and [`TaskSource::finish_writes`] — `None` while
3668 /// nothing is being held back, when every write lands whole as it is made.
3669 deferred: Mutex<Option<Deferred>>,
3670 clock: SharedClock,
3671 numeric_repositories: tokio::sync::Mutex<BTreeMap<RepositoryTarget, std::num::NonZeroU64>>,
3672 /// The board as this process last read it, for the length of one command — dropped by
3673 /// [`TaskSource::end_command`].
3674 ///
3675 /// A copy of a project used to re-read the whole board, paged, before writing each of
3676 /// its items, which is by far the largest part of a copy's request count and none of
3677 /// its work. Nothing else changes this board while a command runs — this source's own
3678 /// writes are the only writer — so one read answers them all.
3679 ///
3680 /// It is not a store of a user's work and it is not the cache the no-persistence
3681 /// invariant forbids: it lives and dies with the process exactly as `created` does,
3682 /// nothing is written down, and [`Self::board`] still completes it from `created`, so
3683 /// an item this command created and then depends on resolves whether or not GitHub's
3684 /// own eventually-consistent read has caught up. A write to an item already on the
3685 /// board updates the entry here too, so what this holds is the last read plus this
3686 /// process's own writes rather than a snapshot taken before them.
3687 board_cache: Mutex<Option<Board>>,
3688 /// Every issue this board's own search reported, for the length of one command — dropped
3689 /// by [`TaskSource::end_command`].
3690 ///
3691 /// The second half of a board read, and cached for the same reason and on the same
3692 /// terms as the first: it lives and dies with the process, nothing is written down, and
3693 /// a write this process makes updates the entry here exactly as it updates the one in
3694 /// [`Self::board_cache`]. One read answers every question a command asks, so a command
3695 /// that lists this board's projects and its tasks pays for one search rather than two.
3696 search_cache: Mutex<Option<Vec<Resolved>>>,
3697 /// What each narrowed question GitHub was asked answered, keyed by that question, for
3698 /// the length of one command — dropped by [`TaskSource::end_command`].
3699 ///
3700 /// The narrowed counterpart of [`Self::search_cache`], held on the same terms: it lives
3701 /// and dies with the process, nothing is written down, a write this process makes
3702 /// updates the entry here as it updates the other two, and every answer is completed
3703 /// with this process's own writes each time it is given. A command that asks the same
3704 /// narrowed question twice — a wait polling for its own items, a listing repeated after a
3705 /// write — pays for it once, which is what the whole-board read it replaced gave it.
3706 narrowed_cache: Mutex<BTreeMap<String, Vec<Resolved>>>,
3707 search_next: Mutex<BTreeMap<String, Option<String>>>,
3708 /// Records already resolved in this command, reused by writes and for comment identity.
3709 /// Explicit item reads still reach GitHub. Nothing is persisted, and
3710 /// [`TaskSource::end_command`] drops every record, so a write in the next command reads
3711 /// its item as a person has since left it.
3712 resolved_cache: Mutex<BTreeMap<NativeId, Resolved>>,
3713 /// What [`TaskSource::read_ahead_for_copy`] read, by id — `None` for an id that read
3714 /// answered as holding nothing — each taken by the next read of that item by id and by
3715 /// nothing else, dropped by any mutation naming it, and cleared by
3716 /// [`TaskSource::end_command`]. So a read answered from it is the copy's own
3717 /// read-before-write, made in the same request as the others' rather than on its own.
3718 read_ahead: Mutex<BTreeMap<NativeId, Option<Resolved>>>,
3719 /// Every item a listing of one project's members carried whole in this command — the
3720 /// project issue and each of its sub-issues — kept for [`TaskSource::read_ahead_for_copy`]
3721 /// alone, which takes each one it is asked for into [`Self::read_ahead`] instead of reading
3722 /// it again. No other read is answered from it, so a read by id outside a copy's
3723 /// read-before-write reads GitHub as it always did. Dropped by any mutation naming an
3724 /// item, and cleared by [`TaskSource::end_command`].
3725 carried: Mutex<BTreeMap<NativeId, Resolved>>,
3726 /// Items an issue read by reference reached, held for the one status write each was read
3727 /// for and taken out by it alone — see [`Self::take_held`] — because that read selects only
3728 /// what such a write needs. Dropped by [`TaskSource::end_command`].
3729 held_cache: Mutex<BTreeMap<NativeId, Resolved>>,
3730 /// Each project's sub-issues as GitHub answered them, keyed by the selector they were
3731 /// asked for under, with the project that selector named — for the length of one command,
3732 /// dropped by [`TaskSource::end_command`].
3733 ///
3734 /// A caller pages through a project's tasks one engine page at a time, and every page
3735 /// is cut from the whole list of them, so without this each page walked every
3736 /// [`graphql::SUB_ISSUES`] page again and a project of `n` listing pages cost `n²`
3737 /// requests to read once. Held on the terms [`Self::narrowed_cache`] is: it lives and
3738 /// dies with the process, nothing is written down, a write this process makes updates or
3739 /// removes the entry here as it does there, and every answer is completed with this
3740 /// process's own writes each time it is given.
3741 children_cache: Mutex<ProjectChildren>,
3742 /// The board's own id and field definitions as this process last read them on their
3743 /// own, for the length of one command — dropped by [`TaskSource::end_command`].
3744 ///
3745 /// What a write needs of the board and its item does not say, read once per command
3746 /// rather than once per item written, on the terms [`Self::board_cache`] is held on: it
3747 /// lives and dies with the process and nothing is written down. It holds no item and so
3748 /// can answer no question about one — see [`Self::board_fields`].
3749 fields_cache: Mutex<Option<BoardFields>>,
3750 /// Each destination repository's node id, resolved once per repository
3751 /// rather than per issue created.
3752 ///
3753 /// A repository's node id does not change, and re-reading it for every issue of a copy
3754 /// spent one request per item on an answer this source already had. It is a map rather
3755 /// than one entry because a copy files each item in the repository its own
3756 /// `repositories` field names, so a plan across five repositories asks GitHub five
3757 /// times and not once per item.
3758 repository_cache: Mutex<BTreeMap<RepositoryTarget, String>>,
3759 /// What every request this source sends is recorded into.
3760 ///
3761 /// Ordinary code path, not a mode: [`Self::send_once`] records into it at the one place
3762 /// a request leaves this crate, so nothing has to be switched on for a session to be
3763 /// counted. It is shared rather than owned so a caller accounting for a whole session —
3764 /// its own schema verification, board lookups, residue sweep and cleanup beside this
3765 /// source's reads and writes — adds up one accounting instead of two. See
3766 /// [`accounting`] for what a record carries and what a session's spend is and is not.
3767 ledger: Arc<Accounting>,
3768 /// What [`expected`] holds for a write the store's cache expects: the journal while one is
3769 /// open, the issues primed from the cache, and the comments known on each.
3770 expected: expected::Held,
3771}
3772
3773/// GitHub's closed single-select color vocabulary.
3774#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3775#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
3776pub enum StatusOptionColor {
3777 /// Gray.
3778 Gray,
3779 /// Blue.
3780 Blue,
3781 /// Green.
3782 Green,
3783 /// Yellow.
3784 Yellow,
3785 /// Purple.
3786 Purple,
3787 /// Red.
3788 Red,
3789 /// Orange.
3790 Orange,
3791 /// Pink.
3792 Pink,
3793}
3794
3795/// Whether a guarded board setup — of the fields, or of the Status options alone — plans or
3796/// applies its additions.
3797#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3798pub enum SetupMode {
3799 /// Read without mutation.
3800 Plan,
3801 /// Apply and verify.
3802 Apply,
3803}
3804
3805/// The name [`SetupMode`] had when Status was the one field set up, kept so a caller written
3806/// against it goes on compiling.
3807pub type StatusOptionsMode = SetupMode;
3808
3809/// The explicit result of the requested operation.
3810#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3811#[serde(rename_all = "kebab-case")]
3812pub enum StatusOptionsOutcome {
3813 /// A read-only plan.
3814 Planned,
3815 /// Apply found nothing missing.
3816 Unchanged,
3817 /// Additions were applied and verified.
3818 Applied,
3819}
3820
3821/// A GitHub single-select option's opaque GraphQL node identifier.
3822#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3823#[serde(transparent)]
3824pub struct StatusOptionId(#[schemars(length(min = 1))] String);
3825
3826impl TryFrom<String> for StatusOptionId {
3827 type Error = String;
3828
3829 fn try_from(id: String) -> Result<Self, Self::Error> {
3830 if id.trim().is_empty() {
3831 return Err("a GitHub Status option id cannot be blank".to_owned());
3832 }
3833 Ok(Self(id))
3834 }
3835}
3836
3837/// One existing or proposed option in a guarded Status-field update.
3838#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3839pub struct StatusOption {
3840 /// GitHub's stable id.
3841 pub id: StatusOptionId,
3842 /// The visible option name.
3843 pub name: ColumnName,
3844 /// GitHub's single-select color token.
3845 pub color: StatusOptionColor,
3846 /// The option description, including an empty one.
3847 pub description: String,
3848}
3849
3850/// One board item's Status assignment, retained as recovery data.
3851#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3852pub struct StatusAssignment {
3853 /// The project item id whose assignment this is.
3854 // llmlint: ignore[invalid_states_unrepresentable] This opaque GraphQL node ID is
3855 // carried verbatim as operator recovery data; introducing a semantic type would claim
3856 // validation rules GitHub does not publish and no operation here interprets.
3857 pub item_id: String,
3858 /// The selected option, absent when the item has no status.
3859 #[serde(skip_serializing_if = "Option::is_none")]
3860 pub option: Option<AssignedStatusOption>,
3861}
3862
3863/// The inseparable id and name of an assigned option.
3864#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3865pub struct AssignedStatusOption {
3866 /// GitHub's stable id.
3867 pub id: StatusOptionId,
3868 /// The visible name.
3869 pub name: ColumnName,
3870}
3871
3872/// The plan and verified outcome of reconciling configured Status options.
3873#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3874pub struct StatusOptionsReport {
3875 /// The configured source name.
3876 pub source: SourceName,
3877 /// Configured option names absent before the operation.
3878 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a
3879 // `ColumnName` and has therefore already passed its nonblank validation; retaining the
3880 // serialized string here preserves the report's intentionally simple public contract.
3881 pub missing: Vec<String>,
3882 /// What the requested operation did.
3883 pub outcome: StatusOptionsOutcome,
3884 /// The complete option list observed before any mutation.
3885 pub existing: Vec<StatusOption>,
3886}
3887
3888#[derive(Debug, Clone, PartialEq, Eq)]
3889struct StatusSnapshot {
3890 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
3891 // passed back as the mutation's project identity; a newtype could enforce no stronger
3892 // invariant because GitHub publishes no grammar for it.
3893 board_id: String,
3894 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
3895 // passed back as the mutation's field identity; a newtype could enforce no stronger
3896 // invariant because GitHub publishes no grammar for it.
3897 field_id: String,
3898 options: Vec<StatusOption>,
3899 assignments: Vec<StatusAssignment>,
3900}
3901
3902/// The name of the board field a status is held in.
3903const STATUS_FIELD: &str = "Status";
3904
3905/// Every item's value of each field `report` names, as it stood before the setup wrote
3906/// anything — what a person puts back when the setup is refused part way.
3907fn recovery(report: &FieldsReport, before: &BoardSnapshot) -> Result<String, SourceError> {
3908 let assignments: BTreeMap<&str, Vec<StatusAssignment>> = report
3909 .fields
3910 .iter()
3911 .map(|field| (field.field.name(), before.assignments(field.field)))
3912 .collect();
3913 serde_json::to_string_pretty(&assignments).map_err(|error| SourceError::Malformed {
3914 message: format!("cannot render the pre-write field recovery snapshot: {error}"),
3915 })
3916}
3917
3918/// One board field the guarded setup reads and writes — every one it reads, and the only
3919/// ones it writes.
3920#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, schemars::JsonSchema)]
3921pub enum BoardField {
3922 /// The single-select `Status` field every instance's `status_mapping` resolves into.
3923 Status,
3924 /// The single-select `Priority` field an instance's `priority_mapping` resolves into.
3925 Priority,
3926}
3927
3928impl BoardField {
3929 /// The field's name on the board.
3930 #[must_use]
3931 pub const fn name(self) -> &'static str {
3932 match self {
3933 Self::Status => STATUS_FIELD,
3934 Self::Priority => PRIORITY_FIELD,
3935 }
3936 }
3937
3938 /// The field a board calls `name`, or `None` for one this setup does not own.
3939 fn named(name: &str) -> Option<Self> {
3940 [Self::Status, Self::Priority]
3941 .into_iter()
3942 .find(|field| field.name() == name)
3943 }
3944}
3945
3946/// What the guarded setup did to one field.
3947#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3948#[serde(rename_all = "kebab-case")]
3949pub enum FieldOutcome {
3950 /// A read-only plan.
3951 Planned,
3952 /// Apply found the field there with every configured option.
3953 Unchanged,
3954 /// Missing options were added to the field that was there, and verified.
3955 Applied,
3956 /// The field was not there; it was created holding the configured options, and verified.
3957 Created,
3958}
3959
3960/// One field's plan, or its verified outcome.
3961#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3962pub struct FieldReport {
3963 /// Which field.
3964 pub field: BoardField,
3965 /// Whether the board had the field before the operation.
3966 // llmlint: ignore[invalid_states_unrepresentable] `exists` beside `outcome` is the report's
3967 // wire shape as its consumer's contract fixes it — `{"field", "exists", "missing",
3968 // "outcome", "existing"}` — so folding one into the other would change a published JSON
3969 // shape. The contradictory pairings cannot be built: `GitHubProjectsSource::fields` is the
3970 // one constructor, and it derives `outcome` from `exists` in one match.
3971 pub exists: bool,
3972 /// Configured option names the field lacked before the operation — every one of them,
3973 /// in the order a new field lists them, when the field was not there at all.
3974 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
3975 // mapping name and has therefore already passed its nonblank validation; the serialized
3976 // string is the report's intentionally simple public contract, as `StatusOptionsReport`'s is.
3977 pub missing: Vec<String>,
3978 /// For the `Status` field, which item kind each missing name is configured for: one
3979 /// entry per kind `status_mapping` names a missing option for, task before project, each
3980 /// listing that kind's missing names in category order. A name both kinds use is in
3981 /// both. Empty — and left out of the JSON — when nothing is missing, and always for
3982 /// `Priority`, which only a task holds.
3983 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3984 // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
3985 // both SDKs model an absent `kinds` as an empty list rather than as `null`.
3986 #[schemars(!skip_serializing_if)]
3987 pub kinds: Vec<KindMissing>,
3988 /// What the requested operation did.
3989 pub outcome: FieldOutcome,
3990 /// The field's complete option list observed before any mutation; empty when the field
3991 /// was not there.
3992 pub existing: Vec<StatusOption>,
3993}
3994
3995/// The `Status` option names one item kind's `status_mapping` names that the field lacked.
3996#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
3997pub struct KindMissing {
3998 /// The kind these names are configured for.
3999 pub kind: ItemKind,
4000 /// The names that kind maps a category to and the field lacked, in category order.
4001 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
4002 // mapping name, as `FieldReport::missing`'s do, and the serialized string is the report's
4003 // intentionally simple public contract.
4004 pub missing: Vec<String>,
4005}
4006
4007/// The plan and verified outcome of setting up every field a source's configuration names.
4008#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
4009pub struct FieldsReport {
4010 /// The configured source name.
4011 pub source: SourceName,
4012 /// `Status`, always, and `Priority` when the source sets `priority_mapping`.
4013 // llmlint: ignore[invalid_states_unrepresentable] A list is the report's wire shape as its
4014 // consumer's contract fixes it — `{"source", "fields": [...]}` — so a struct with one member
4015 // per field would change a published JSON shape. The states the list could hold and the
4016 // contract forbids cannot be built: `GitHubProjectsSource::fields` is the one constructor,
4017 // and it pushes `Status` first and exactly once, then `Priority` exactly when configured.
4018 pub fields: Vec<FieldReport>,
4019 /// Each board text field the source's `metadata_fields` projects a value onto, in
4020 /// configured order. Empty — and left out of the JSON — when it projects none.
4021 #[serde(default, skip_serializing_if = "Vec::is_empty")]
4022 // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
4023 // both SDKs model an absent list as an empty one rather than as `null`.
4024 #[schemars(!skip_serializing_if)]
4025 pub metadata_fields: Vec<MetadataFieldReport>,
4026}
4027
4028/// The type of a board field that is not a text field, as GitHub names it — its `dataType`, or
4029/// its GraphQL type when it has none — which is what a projected field's conflict reports.
4030///
4031/// Never empty, never beginning with whitespace, and never `TEXT`: a text field of that name is
4032/// no conflict.
4033// The schema states that rule as `NON_TEXT_FIELD_TYPE_PATTERN`, so a generated SDK model
4034// refuses exactly what `try_from` below does.
4035#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
4036#[serde(transparent)]
4037pub struct NonTextFieldType(#[schemars(regex(pattern = NON_TEXT_FIELD_TYPE_PATTERN))] String);
4038
4039/// What a [`NonTextFieldType`] may be, as the emitted schema states it: a first character that
4040/// is not whitespace, and anything but exactly `TEXT` — spelled without a lookahead, which
4041/// neither SDK's validator can be relied on to support.
4042const NON_TEXT_FIELD_TYPE_PATTERN: &str =
4043 r"^(?:[^T\s]|T(?:[^E]|$)|TE(?:[^X]|$)|TEX(?:[^T]|$)|TEXT[\s\S])";
4044
4045impl TryFrom<String> for NonTextFieldType {
4046 type Error = String;
4047
4048 fn try_from(kind: String) -> Result<Self, Self::Error> {
4049 if kind.is_empty() || kind.starts_with(char::is_whitespace) {
4050 return Err("a board field's type cannot be blank or begin with whitespace".to_owned());
4051 }
4052 if kind == "TEXT" {
4053 return Err("a TEXT field is no conflict for a projected text field".to_owned());
4054 }
4055 Ok(Self(kind))
4056 }
4057}
4058
4059impl std::fmt::Display for NonTextFieldType {
4060 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4061 formatter.write_str(&self.0)
4062 }
4063}
4064
4065/// One projected metadata text field's plan, or its verified outcome.
4066///
4067/// The setup creates a missing one as a text field and never alters a field that is there:
4068/// a same-named field of another type is reported in `conflict` and left as it is.
4069#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
4070pub struct MetadataFieldReport {
4071 /// The board field's name.
4072 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.
4073 /// The metadata key the value is read from.
4074 pub key: String, // llmlint: ignore[invalid_states_unrepresentable] As `field`: a validated configuration value reported back as written.
4075 /// The object keys walked inside that key's value; empty for the key's own value.
4076 pub path: Vec<String>,
4077 /// Whether the board had a text field of that name before the operation.
4078 // 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.
4079 pub exists: bool,
4080 /// The type of a field of that name that is not a text field, which the setup leaves as
4081 /// it is; absent — and left out of the JSON — when there is none.
4082 #[serde(default, skip_serializing_if = "Option::is_none")]
4083 pub conflict: Option<NonTextFieldType>,
4084 /// What the requested operation did: `planned`; `created` for a field that was not
4085 /// there; `unchanged` for one that was, and for a conflict, which is never changed.
4086 pub outcome: FieldOutcome,
4087}
4088
4089/// Which options one field is configured with, in the order a new field would list them.
4090struct FieldPlan {
4091 field: BoardField,
4092 wanted: Vec<String>,
4093}
4094
4095/// One single-select field as the guarded setup snapshots it.
4096#[derive(Debug, Clone, PartialEq, Eq)]
4097struct SnapshotField {
4098 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
4099 // passed back as the mutation's field identity; a newtype could enforce no stronger
4100 // invariant because GitHub publishes no grammar for it.
4101 field_id: String,
4102 options: Vec<StatusOption>,
4103}
4104
4105/// Every single-select field of a board and every item's value of each.
4106#[derive(Debug, Clone, PartialEq, Eq)]
4107struct BoardSnapshot {
4108 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
4109 // passed back as the mutation's project identity; a newtype could enforce no stronger
4110 // invariant because GitHub publishes no grammar for it.
4111 board_id: String,
4112 fields: BTreeMap<BoardField, SnapshotField>,
4113 /// Each board item's id, and its value of each field this setup owns that it holds one of.
4114 items: Vec<(String, BTreeMap<BoardField, AssignedStatusOption>)>,
4115}
4116
4117impl BoardSnapshot {
4118 /// Every item's value of `field`, in board order — the recovery data a drift refusal
4119 /// carries.
4120 fn assignments(&self, field: BoardField) -> Vec<StatusAssignment> {
4121 self.items
4122 .iter()
4123 .map(|(item_id, values)| StatusAssignment {
4124 item_id: item_id.clone(),
4125 option: values.get(&field).cloned(),
4126 })
4127 .collect()
4128 }
4129}
4130
4131impl GitHubProjectsSource {
4132 /// Report missing configured Status options and, when `apply` is true, add them with
4133 /// a whole-list mutation that preserves every existing id and verifies the result.
4134 ///
4135 /// # Errors
4136 ///
4137 /// Refuses a board without a single-select `Status` field. A post-write difference in
4138 /// any pre-existing option id or item assignment is refused with the complete pre-write
4139 /// assignment snapshot in the diagnostic for recovery.
4140 // llmlint: ignore[changed_behavior_has_e2e] The CLI journeys cover plan, no-op apply,
4141 // successful mutation, both drift refusals, source selection, missing Status, casing,
4142 // and paging. Transport errors remain the shared `graphql` boundary's behavior rather
4143 // than a new status-options behavior, and the pinned-schema test prevents valid GitHub
4144 // responses from entering the defensive malformed-response branches below.
4145 pub async fn status_options(
4146 &self,
4147 mode: StatusOptionsMode,
4148 ) -> Result<StatusOptionsReport, SourceError> {
4149 let before = self.status_snapshot().await?;
4150 // A terminal category's option is as configured as an open one's: a terminal
4151 // write validates it before closing and refuses when the board lacks it. Both
4152 // kinds' names are options of the one field, so both are asked for.
4153 let missing = self
4154 .statuses
4155 .wanted()
4156 .into_iter()
4157 .filter(|wanted| {
4158 !before
4159 .options
4160 .iter()
4161 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4162 })
4163 .collect::<Vec<_>>();
4164 let report = StatusOptionsReport {
4165 source: self.name.clone(),
4166 missing: missing.clone(),
4167 outcome: match (mode, missing.is_empty()) {
4168 (StatusOptionsMode::Plan, _) => StatusOptionsOutcome::Planned,
4169 (StatusOptionsMode::Apply, true) => StatusOptionsOutcome::Unchanged,
4170 (StatusOptionsMode::Apply, false) => StatusOptionsOutcome::Applied,
4171 },
4172 existing: before.options.clone(),
4173 };
4174 if mode == StatusOptionsMode::Plan || missing.is_empty() {
4175 return Ok(report);
4176 }
4177 let mut options = before
4178 .options
4179 .iter()
4180 .map(|option| {
4181 json!({
4182 "id": option.id, "name": option.name, "color": option.color,
4183 "description": option.description,
4184 })
4185 })
4186 .collect::<Vec<_>>();
4187 options.extend(missing.iter().map(|name| {
4188 json!({
4189 "name": name, "color": "GRAY", "description": ""
4190 })
4191 }));
4192 self.graphql(
4193 graphql::STATUS_OPTIONS_UPDATE,
4194 json!({"input": {
4195 "projectId": before.board_id, "fieldId": before.field_id,
4196 "singleSelectOptions": options,
4197 }}),
4198 )
4199 .await?;
4200 let after = self.status_snapshot().await?;
4201 let options_preserved = before
4202 .options
4203 .iter()
4204 .all(|old| after.options.iter().any(|new| new == old));
4205 let additions_present = missing.iter().all(|wanted| {
4206 after
4207 .options
4208 .iter()
4209 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4210 });
4211 if !options_preserved || !additions_present || after.assignments != before.assignments {
4212 let recovery = serde_json::to_string_pretty(&before.assignments).map_err(|error| {
4213 SourceError::Malformed {
4214 message: format!("cannot render pre-write Status recovery snapshot: {error}"),
4215 }
4216 })?;
4217 return Err(SourceError::Refused {
4218 message: format!(
4219 "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}"
4220 ),
4221 });
4222 }
4223 Ok(report)
4224 }
4225
4226 /// A fresh snapshot of the Status field and every board item's assignment of it.
4227 ///
4228 /// # Errors
4229 ///
4230 /// Refuses a board without a single-select `Status` field, and one the token cannot see.
4231 async fn status_snapshot(&self) -> Result<StatusSnapshot, SourceError> {
4232 // Status alone, as this operation has always read it: a `Priority` field is another
4233 // operation's, so nothing about it can refuse this one.
4234 let mut board = self.board_snapshot(&[BoardField::Status]).await?;
4235 let field = board
4236 .fields
4237 .remove(&BoardField::Status)
4238 .ok_or_else(|| self.no_status_field())?;
4239 Ok(StatusSnapshot {
4240 assignments: board.assignments(BoardField::Status),
4241 board_id: board.board_id,
4242 field_id: field.field_id,
4243 options: field.options,
4244 })
4245 }
4246
4247 /// The refusal a board with no `Status` field is answered with by the guarded setup.
4248 fn no_status_field(&self) -> SourceError {
4249 SourceError::Refused {
4250 message: format!("source {} board has no Status field", self.name),
4251 }
4252 }
4253
4254 // llmlint: ignore-block[changed_behavior_has_e2e] Valid snapshot shapes are exercised through
4255 // the real CLI loopback journey, including pagination. The individual malformed guards
4256 // are defensive validation of a schema-pinned third-party response, not separate user
4257 // journeys; drift and missing-field failures cover the operation's recovery behavior.
4258 /// A fresh snapshot of each of the `owned` fields on the board, with its options, and of
4259 /// every board item's value of each, walked to the end of the board's items. A field not
4260 /// in `owned` is read past whatever it holds.
4261 async fn board_snapshot(&self, owned: &[BoardField]) -> Result<BoardSnapshot, SourceError> {
4262 let mut after: Option<String> = None;
4263 let mut snapshot: Option<BoardSnapshot> = None;
4264 loop {
4265 let data = self
4266 .graphql(
4267 graphql::STATUS_OPTIONS_SNAPSHOT,
4268 json!({
4269 "owner": self.owner, "number": self.project_number,
4270 "first": MAX_PAGE_SIZE, "after": after, "nestedFirst": MAX_PAGE_SIZE,
4271 }),
4272 )
4273 .await?;
4274 let board = data
4275 .pointer("/owner/projectV2")
4276 .filter(|board| board.is_object())
4277 .ok_or_else(|| SourceError::Refused {
4278 message: format!(
4279 "source {} has no accessible GitHub Projects board",
4280 self.name
4281 ),
4282 })?;
4283 if board
4284 .pointer("/fields/pageInfo/hasNextPage")
4285 .and_then(Value::as_bool)
4286 != Some(false)
4287 {
4288 return Err(SourceError::Malformed {
4289 message:
4290 "GitHub project fields is incomplete or has malformed pageInfo.hasNextPage"
4291 .into(),
4292 });
4293 }
4294 let mut fields = BTreeMap::new();
4295 // Only the fields this setup owns, by name: a node the single-select fragment did not
4296 // match carries no name, and a person's own single-select field — a `Size`, a
4297 // `Team` — is none of this setup's business, so nothing about it can refuse one. A
4298 // `Status` or `Priority` field without its options is malformed, not absent.
4299 // 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.
4300 for (owned, field) in board
4301 .pointer("/fields/nodes")
4302 .and_then(Value::as_array)
4303 .ok_or_else(|| SourceError::Malformed {
4304 message: "GitHub project fields.nodes is not an array".into(),
4305 })?
4306 .iter()
4307 .filter_map(|field| {
4308 let named = BoardField::named(field.get("name")?.as_str()?)?;
4309 owned.contains(&named).then_some((named, field))
4310 })
4311 {
4312 let options = field
4313 .get("options")
4314 .and_then(Value::as_array)
4315 .ok_or_else(|| SourceError::Malformed {
4316 message: "GitHub single-select field options is not an array".into(),
4317 })?
4318 .iter()
4319 .map(|option| {
4320 Ok(StatusOption {
4321 id: StatusOptionId::try_from(required_str(option, "id")?.to_owned())
4322 .map_err(|message| SourceError::Malformed { message })?,
4323 name: ColumnName::try_from(required_str(option, "name")?.to_owned())
4324 .map_err(|message| SourceError::Malformed {
4325 message: format!(
4326 "GitHub single-select option name is invalid: {message}"
4327 ),
4328 })?,
4329 color: serde_json::from_value(
4330 option.get("color").cloned().unwrap_or(Value::Null),
4331 )
4332 .map_err(|error| {
4333 SourceError::Malformed {
4334 message: format!(
4335 "GitHub single-select option color is invalid: {error}"
4336 ),
4337 }
4338 })?,
4339 description: optional_str(option, "description")?
4340 .unwrap_or_default()
4341 .to_owned(),
4342 })
4343 })
4344 .collect::<Result<Vec<_>, SourceError>>()?;
4345 let snapshot = SnapshotField {
4346 field_id: required_nonblank_str(field, "id")?.to_owned(),
4347 options,
4348 };
4349 // A board's field names are unique, so a second one is an answer that cannot
4350 // say which field the setup would act on — refused rather than one chosen.
4351 if fields.insert(owned, snapshot).is_some() {
4352 return Err(SourceError::Malformed {
4353 message: format!(
4354 "GitHub answered two {} fields for this board",
4355 owned.name()
4356 ),
4357 });
4358 }
4359 }
4360 let board_id = required_nonblank_str(board, "id")?.to_owned();
4361 let current = snapshot.get_or_insert_with(|| BoardSnapshot {
4362 board_id,
4363 fields,
4364 items: Vec::new(),
4365 });
4366 let items = board
4367 .pointer("/items/nodes")
4368 .and_then(Value::as_array)
4369 .ok_or_else(|| SourceError::Malformed {
4370 message: "GitHub project items.nodes is not an array".into(),
4371 })?;
4372 for item in items {
4373 let field_values =
4374 item.get("fieldValues")
4375 .ok_or_else(|| SourceError::Malformed {
4376 message: "GitHub project item is missing fieldValues".into(),
4377 })?;
4378 if field_values
4379 .pointer("/pageInfo/hasNextPage")
4380 .and_then(Value::as_bool)
4381 != Some(false)
4382 {
4383 return Err(SourceError::Malformed {
4384 message: "GitHub project item fieldValues is incomplete or has malformed pageInfo.hasNextPage".into(),
4385 });
4386 }
4387 let values = item
4388 .pointer("/fieldValues/nodes")
4389 .and_then(Value::as_array)
4390 .ok_or_else(|| SourceError::Malformed {
4391 message: "GitHub project item fieldValues.nodes is not an array".into(),
4392 })?;
4393 let item_id = required_nonblank_str(item, "id")?;
4394 let mut assigned = BTreeMap::new();
4395 for value in values {
4396 let Some(field) = value
4397 .pointer("/field/name")
4398 .and_then(Value::as_str)
4399 .and_then(BoardField::named)
4400 .filter(|field| owned.contains(field))
4401 else {
4402 continue;
4403 };
4404 let held = assigned.insert(
4405 field,
4406 AssignedStatusOption {
4407 id: StatusOptionId::try_from(
4408 required_str(value, "optionId")?.to_owned(),
4409 )
4410 .map_err(|message| SourceError::Malformed { message })?,
4411 name: ColumnName::try_from(required_str(value, "name")?.to_owned())
4412 .map_err(|message| SourceError::Malformed {
4413 message: format!(
4414 "GitHub assigned {} name is invalid: {message}",
4415 field.name()
4416 ),
4417 })?,
4418 },
4419 );
4420 // An item holds one value of a field, so a second one leaves no way to
4421 // tell which it holds — and a verification or recovery built on either
4422 // could restore the wrong one.
4423 if held.is_some() {
4424 return Err(SourceError::Malformed {
4425 message: format!(
4426 "GitHub answered two {} values for board item {item_id}",
4427 field.name()
4428 ),
4429 });
4430 }
4431 }
4432 current.items.push((item_id.to_owned(), assigned));
4433 }
4434 let page = board.get("items").ok_or_else(|| SourceError::Malformed {
4435 message: "GitHub project is missing items".into(),
4436 })?;
4437 let has_next = page
4438 .pointer("/pageInfo/hasNextPage")
4439 .and_then(Value::as_bool)
4440 .ok_or_else(|| SourceError::Malformed {
4441 message: "GitHub project items.pageInfo.hasNextPage is not a boolean".into(),
4442 })?;
4443 if !has_next {
4444 break;
4445 }
4446 let next =
4447 required_nonblank_str(page.get("pageInfo").unwrap_or(&Value::Null), "endCursor")?;
4448 validate_cursor_progress(after.as_deref(), next)?;
4449 after = Some(next.to_owned());
4450 }
4451 snapshot.ok_or_else(|| SourceError::Malformed {
4452 message: "GitHub returned no board field snapshot".into(),
4453 })
4454 }
4455 // llmlint: ignore-end[changed_behavior_has_e2e]
4456
4457 /// Report every board field this source's configuration names and, with
4458 /// [`SetupMode::Apply`], set each up: add the options a field lacks, and create
4459 /// the `Priority` field when the board has none.
4460 ///
4461 /// The fields are `Status`, always, with the options `status_mapping` resolves to; and
4462 /// `Priority`, when `priority_mapping` is set, with its four mapped options — created in
4463 /// the order urgent, high, medium, low. An option a field already has keeps its id, name,
4464 /// color and description: the whole option list goes back with every existing id, because
4465 /// a re-minted id clears every item's value.
4466 ///
4467 /// # Errors
4468 ///
4469 /// Refuses a board without a single-select `Status` field. After an apply the board is
4470 /// read again, and a pre-existing option or any item's value of either field that moved is
4471 /// refused with the complete pre-write assignments in the diagnostic, for recovery.
4472 // llmlint: ignore[changed_behavior_has_e2e] The `sources fields` journeys drive plan,
4473 // unchanged apply, a created field, an added option to each field, drift refusal, a board
4474 // with no Status field and a non-github-projects source through the compiled CLI against
4475 // the loopback board. Transport errors are the shared `graphql` boundary's behavior.
4476 pub async fn fields(&self, mode: SetupMode) -> Result<FieldsReport, SourceError> {
4477 let owned: Vec<BoardField> = if self.priorities.is_some() {
4478 vec![BoardField::Status, BoardField::Priority]
4479 } else {
4480 vec![BoardField::Status]
4481 };
4482 let before = self.board_snapshot(&owned).await?;
4483 let mut plans = vec![FieldPlan {
4484 field: BoardField::Status,
4485 wanted: self.statuses.wanted(),
4486 }];
4487 if !before.fields.contains_key(&BoardField::Status) {
4488 return Err(self.no_status_field());
4489 }
4490 if let Some(mapping) = &self.priorities {
4491 plans.push(FieldPlan {
4492 field: BoardField::Priority,
4493 wanted: mapping.names().map(str::to_owned).collect(),
4494 });
4495 }
4496 // The snapshot reads single-select fields alone, so a field it did not find may still
4497 // be on the board under the name, of another type: creating one beside it would fail
4498 // part way, or leave two fields of one name. Asked of the board's own field list, and
4499 // only when a field is missing.
4500 if plans
4501 .iter()
4502 .any(|plan| !before.fields.contains_key(&plan.field))
4503 {
4504 let board = self.board_fields().await?;
4505 for plan in plans
4506 .iter()
4507 .filter(|plan| !before.fields.contains_key(&plan.field))
4508 {
4509 if let Some(field) = Board::field(&board.fields, plan.field.name())? {
4510 return Err(SourceError::Refused {
4511 message: format!(
4512 "source {}'s board has a {} field that is not a single-select field \
4513 (it is a {}), so it cannot hold this source's options; next: rename \
4514 or remove that field, then run this again",
4515 self.name,
4516 plan.field.name(),
4517 optional_str(field, "__typename")?.unwrap_or("field of another type")
4518 ),
4519 });
4520 }
4521 }
4522 }
4523 let mut reports = Vec::new();
4524 for plan in &plans {
4525 let held = before.fields.get(&plan.field);
4526 let existing = held.map(|field| field.options.clone()).unwrap_or_default();
4527 let mut missing: Vec<String> = Vec::new();
4528 for wanted in &plan.wanted {
4529 let present = existing
4530 .iter()
4531 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4532 || missing
4533 .iter()
4534 .any(|named| named.eq_ignore_ascii_case(wanted));
4535 if !present {
4536 missing.push(wanted.clone());
4537 }
4538 }
4539 let kinds = match plan.field {
4540 BoardField::Status => self.statuses.missing_by_kind(&existing),
4541 BoardField::Priority => Vec::new(),
4542 };
4543 reports.push(FieldReport {
4544 field: plan.field,
4545 exists: held.is_some(),
4546 kinds,
4547 outcome: match (mode, held.is_some(), missing.is_empty()) {
4548 (SetupMode::Plan, _, _) => FieldOutcome::Planned,
4549 (SetupMode::Apply, true, true) => FieldOutcome::Unchanged,
4550 (SetupMode::Apply, true, false) => FieldOutcome::Applied,
4551 (SetupMode::Apply, false, _) => FieldOutcome::Created,
4552 },
4553 missing,
4554 existing,
4555 });
4556 }
4557 // A projected field is a text field, which the single-select snapshot cannot see, so
4558 // it is asked of the board's own field list — and only when one is configured.
4559 let mut metadata_fields = Vec::new();
4560 if !self.metadata_fields.is_empty() {
4561 let board = self.board_fields().await?;
4562 for projection in &self.metadata_fields {
4563 let conflict = match Board::field(&board.fields, &projection.field)? {
4564 None => None,
4565 Some(field) => {
4566 let typename = optional_str(field, "__typename")?;
4567 let data_type = optional_str(field, "dataType")?;
4568 if typename == Some("ProjectV2Field") && data_type == Some("TEXT") {
4569 None
4570 } else {
4571 let named = data_type
4572 .filter(|kind| *kind != "TEXT")
4573 .or(typename)
4574 .unwrap_or("field of another type");
4575 Some(NonTextFieldType::try_from(named.to_owned()).map_err(
4576 |message| SourceError::Malformed {
4577 message: format!(
4578 "GitHub answered the board's {} field with a type this \
4579 setup cannot read: {message}",
4580 &*projection.field
4581 ),
4582 },
4583 )?)
4584 }
4585 }
4586 };
4587 let exists =
4588 conflict.is_none() && Board::field(&board.fields, &projection.field)?.is_some();
4589 metadata_fields.push(MetadataFieldReport {
4590 field: projection.field.to_string(),
4591 key: projection.key.to_string(),
4592 path: projection.path.clone(),
4593 exists,
4594 outcome: match (mode, exists || conflict.is_some()) {
4595 (SetupMode::Plan, _) => FieldOutcome::Planned,
4596 (SetupMode::Apply, true) => FieldOutcome::Unchanged,
4597 (SetupMode::Apply, false) => FieldOutcome::Created,
4598 },
4599 conflict,
4600 });
4601 }
4602 }
4603 let report = FieldsReport {
4604 source: self.name.clone(),
4605 fields: reports,
4606 metadata_fields,
4607 };
4608 let writes: Vec<&FieldReport> = report
4609 .fields
4610 .iter()
4611 .filter(|field| !field.missing.is_empty() || !field.exists)
4612 .collect();
4613 let creates: Vec<&MetadataFieldReport> = report
4614 .metadata_fields
4615 .iter()
4616 .filter(|field| field.outcome == FieldOutcome::Created)
4617 .collect();
4618 if mode == SetupMode::Plan || (writes.is_empty() && creates.is_empty()) {
4619 return Ok(report);
4620 }
4621 let mut landed: Vec<&str> = Vec::new();
4622 for field in &writes {
4623 let added = field
4624 .missing
4625 .iter()
4626 .map(|name| json!({"name": name, "color": "GRAY", "description": ""}));
4627 let sent = match before.fields.get(&field.field) {
4628 Some(held) => {
4629 let mut options = held
4630 .options
4631 .iter()
4632 .map(|option| {
4633 json!({
4634 "id": option.id, "name": option.name, "color": option.color,
4635 "description": option.description,
4636 })
4637 })
4638 .collect::<Vec<_>>();
4639 options.extend(added);
4640 self.graphql(
4641 graphql::STATUS_OPTIONS_UPDATE,
4642 json!({"input": {
4643 "projectId": before.board_id, "fieldId": held.field_id,
4644 "singleSelectOptions": options,
4645 }}),
4646 )
4647 .await
4648 }
4649 None => {
4650 self.graphql(
4651 graphql::CREATE_FIELD,
4652 json!({"input": {
4653 "projectId": before.board_id, "dataType": "SINGLE_SELECT",
4654 "name": field.field.name(),
4655 "singleSelectOptions": added.collect::<Vec<_>>(),
4656 }}),
4657 )
4658 .await
4659 }
4660 };
4661 // A mutation that failed does not establish that GitHub left its field as it was,
4662 // so every failure from here on carries the recovery data a drift refusal does.
4663 match sent {
4664 Ok(_) => landed.push(field.field.name()),
4665 Err(error) => {
4666 let changed = if landed.is_empty() {
4667 String::new()
4668 } else {
4669 format!("changed the {} field and then ", landed.join(" and "))
4670 };
4671 return Err(SourceError::Refused {
4672 message: format!(
4673 "the guarded field setup {changed}failed on the {} field, which it may \
4674 have changed part way: {error}; the pre-write item assignments \
4675 are:\n{}",
4676 field.field.name(),
4677 recovery(&report, &before)?
4678 ),
4679 });
4680 }
4681 }
4682 }
4683 for field in &creates {
4684 let sent = self
4685 .graphql(
4686 graphql::CREATE_FIELD,
4687 json!({"input": {
4688 "projectId": before.board_id, "dataType": "TEXT", "name": field.field,
4689 }}),
4690 )
4691 .await;
4692 if let Err(error) = sent {
4693 let changed = if landed.is_empty() {
4694 String::new()
4695 } else {
4696 format!("changed the {} field and then ", landed.join(" and "))
4697 };
4698 return Err(SourceError::Refused {
4699 message: format!(
4700 "the guarded field setup {changed}failed creating the {} text field: \
4701 {error}; run it again to create what is still missing",
4702 field.field
4703 ),
4704 });
4705 }
4706 landed.push(&field.field);
4707 }
4708 // The board has been written, so a verification read that fails leaves it unverified
4709 // rather than unchanged, and says what to put back.
4710 let after = match self.board_snapshot(&owned).await {
4711 Ok(after) => after,
4712 Err(error) => {
4713 return Err(SourceError::Refused {
4714 message: format!(
4715 "the guarded field setup changed the {} field and then could not read the \
4716 board back to verify it: {error}; the pre-write item assignments are:\n{}",
4717 landed.join(" and "),
4718 recovery(&report, &before)?
4719 ),
4720 });
4721 }
4722 };
4723 let mut moved = Vec::new();
4724 for field in &report.fields {
4725 let name = field.field.name();
4726 let now = after
4727 .fields
4728 .get(&field.field)
4729 .map(|held| held.options.as_slice())
4730 .unwrap_or_default();
4731 if !field.existing.iter().all(|old| now.contains(old)) {
4732 moved.push(format!(
4733 "a pre-existing {name} option id, name, color or description"
4734 ));
4735 }
4736 if !field.missing.iter().all(|wanted| {
4737 now.iter()
4738 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4739 }) {
4740 moved.push(format!("an added {name} option"));
4741 }
4742 if after.assignments(field.field) != before.assignments(field.field) {
4743 moved.push(format!("an item's {name} value"));
4744 }
4745 }
4746 if !creates.is_empty() {
4747 // Read afresh: the view held for this command is the one from before the creates.
4748 *self.fields_cache()? = None;
4749 let board = match self.board_fields().await {
4750 Ok(board) => board,
4751 Err(error) => {
4752 return Err(SourceError::Refused {
4753 message: format!(
4754 "the guarded field setup changed the {} field and then could not \
4755 read the board back to verify it: {error}; run it again to verify \
4756 it, which creates nothing a second time",
4757 landed.join(" and ")
4758 ),
4759 });
4760 }
4761 };
4762 for field in &creates {
4763 let text = Board::field(&board.fields, &field.field)?.is_some_and(|held| {
4764 held.get("__typename").and_then(Value::as_str) == Some("ProjectV2Field")
4765 && held.get("dataType").and_then(Value::as_str) == Some("TEXT")
4766 });
4767 if !text {
4768 moved.push(format!("the created {} text field", field.field));
4769 }
4770 }
4771 }
4772 if !moved.is_empty() {
4773 return Err(SourceError::Refused {
4774 message: format!(
4775 "GitHub changed {} after the guarded field setup; the pre-write item \
4776 assignments are:\n{}",
4777 moved.join(", "),
4778 recovery(&report, &before)?
4779 ),
4780 });
4781 }
4782 Ok(report)
4783 }
4784
4785 /// Validate configuration and capture the named credential without exposing it.
4786 ///
4787 /// # Errors
4788 ///
4789 /// Returns [`SourceError::Config`] for a configuration this instance cannot use and
4790 /// [`SourceError::Auth`] when the named credential is missing or empty.
4791 pub fn new(
4792 name: &SourceName,
4793 config: GitHubProjectsConfig,
4794 secrets: &dyn SecretResolver,
4795 ) -> Result<Self, SourceError> {
4796 Self::recording_into(name, config, secrets, Arc::new(Accounting::new()))
4797 }
4798
4799 /// The same, recording every request it sends into an accounting the caller holds too.
4800 ///
4801 /// [`Self::new`] is this with an accounting of its own. A caller that is also making
4802 /// its own calls to GitHub — a lane verifying a schema, sweeping residue or cleaning
4803 /// up — passes the one it records those into, so the session total accounts for the
4804 /// whole session rather than for this source's share of it.
4805 ///
4806 /// # Errors
4807 ///
4808 /// Exactly [`Self::new`]'s: [`SourceError::Config`] for a configuration this instance
4809 /// cannot use and [`SourceError::Auth`] when the named credential is missing or empty.
4810 pub fn recording_into(
4811 name: &SourceName,
4812 config: GitHubProjectsConfig,
4813 secrets: &dyn SecretResolver,
4814 ledger: Arc<Accounting>,
4815 ) -> Result<Self, SourceError> {
4816 if !valid_github_owner(&config.owner) {
4817 return Err(SourceError::Config {
4818 message: "owner must be 1-39 ASCII letters, digits, or single hyphens, and cannot start or end with a hyphen".into(),
4819 });
4820 }
4821 if config.project_number == 0 || config.project_number > i32::MAX as u32 {
4822 return Err(SourceError::Config {
4823 message: format!("project_number must be between 1 and {}", i32::MAX),
4824 });
4825 }
4826 if !valid_environment_name(&config.token_env) {
4827 return Err(SourceError::Config {
4828 message: "token_env must be a valid environment-variable name".into(),
4829 });
4830 }
4831 let repository = config
4832 .repository
4833 .as_deref()
4834 .map(RepositoryTarget::parse)
4835 .transpose()?;
4836 let endpoint = Url::parse(&config.endpoint).map_err(|e| SourceError::Config {
4837 message: format!("endpoint is not a valid URL: {e}"),
4838 })?;
4839 if endpoint.scheme() != "https"
4840 && !(endpoint.scheme() == "http"
4841 && endpoint
4842 .host_str()
4843 .is_some_and(|h| h == "127.0.0.1" || h == "localhost" || h == "::1"))
4844 {
4845 return Err(SourceError::Config {
4846 message:
4847 "endpoint must use HTTPS (HTTP is accepted only for a loopback test server)"
4848 .into(),
4849 });
4850 }
4851 let token = secrets.get(&config.token_env).filter(|token| !token.expose_secret().trim().is_empty()).ok_or_else(|| SourceError::Auth {
4852 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),
4853 })?;
4854 Ok(Self {
4855 name: name.clone(),
4856 owner: config.owner,
4857 project_number: config.project_number,
4858 repository,
4859 asset_client: assets::client(&endpoint)?,
4860 endpoint,
4861 token,
4862 credential_name: config.token_env,
4863 statuses: BoardStatuses::resolve(&config.status_mapping, name)?,
4864 priorities: config
4865 .priority_mapping
4866 .map(|mapping| PriorityMapping::resolve(mapping, name))
4867 .transpose()?,
4868 metadata_fields: MetadataField::resolve(config.metadata_fields, name)?,
4869 client: Client::builder()
4870 .user_agent("onetaskgraph")
4871 .build()
4872 .map_err(|e| SourceError::Config {
4873 message: format!("cannot build HTTP client: {e}"),
4874 })?,
4875 created: Mutex::new(Vec::new()),
4876 updated: Mutex::new(Vec::new()),
4877 commented: Mutex::new(Vec::new()),
4878 pacing: Pacing::resolve(config.pacing, name)?,
4879 last_mutation: Mutex::new(None),
4880 windows: Mutex::new(pacing::Windows::default()),
4881 task_children: Mutex::new(BTreeMap::new()),
4882 written: Mutex::new(BTreeMap::new()),
4883 deferred: Mutex::new(None),
4884 clock: system_clock(),
4885 numeric_repositories: tokio::sync::Mutex::new(BTreeMap::new()),
4886 board_cache: Mutex::new(None),
4887 search_cache: Mutex::new(None),
4888 narrowed_cache: Mutex::new(BTreeMap::new()),
4889 resolved_cache: Mutex::new(BTreeMap::new()),
4890 read_ahead: Mutex::new(BTreeMap::new()),
4891 carried: Mutex::new(BTreeMap::new()),
4892 held_cache: Mutex::new(BTreeMap::new()),
4893 children_cache: Mutex::new(BTreeMap::new()),
4894 search_next: Mutex::new(BTreeMap::new()),
4895 fields_cache: Mutex::new(None),
4896 repository_cache: Mutex::new(BTreeMap::new()),
4897 ledger,
4898 expected: expected::Held::default(),
4899 })
4900 }
4901
4902 /// A snapshot of every request this source has sent, and what each cost.
4903 ///
4904 /// A value to hold and compare rather than a borrow of the accounting itself, so two
4905 /// of them can sit side by side. When this source was built with
4906 /// [`Self::recording_into`] the snapshot is the whole shared session, which is the
4907 /// point of building it that way.
4908 #[must_use]
4909 pub fn accounting(&self) -> accounting::Session {
4910 self.ledger.snapshot()
4911 }
4912
4913 /// Send one GraphQL document, pacing this source's own mutations and waiting out a
4914 /// rate limit rather than handing it straight back as an error.
4915 ///
4916 /// Retrying is safe for every document here, including the mutations, and the reason
4917 /// is that only a *refusal* is retried: [`Limiter::classify`] rules on a response
4918 /// GitHub sent, and a request GitHub refused for a rate limit did not run, so nothing
4919 /// this replays has already taken effect. An outcome this source cannot know — the
4920 /// send failed, or the body could not be read, so the mutation may well have landed —
4921 /// is [`Attempt::Failed`] in [`send_once`] and leaves this loop without a second
4922 /// attempt. A duplicate write would come from replaying one of those, and none is
4923 /// replayed.
4924 async fn graphql(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
4925 if !self.expected.journaling() {
4926 return self.graphql_sent(query, variables).await;
4927 }
4928 // While a write the store's cache expects runs, its mutations select the whole issue
4929 // they leave behind, so the response vouches for what the cache keeps — and every
4930 // request is recorded, so the write's parts are reported from their own responses.
4931 let (query, variables) = match graphql::whole_twin(query) {
4932 Some(twin) => (twin, expected::whole_variables(variables)),
4933 None => (query, variables),
4934 };
4935 let sent = self.graphql_sent(query, variables.clone()).await;
4936 self.journal(query, &variables, &sent).await;
4937 sent
4938 }
4939
4940 /// One document sent, retried while GitHub asks for a wait, exactly as asked.
4941 async fn graphql_sent(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
4942 if is_mutation(query)
4943 && ![
4944 graphql::ADD_COMMENT,
4945 graphql::UPDATE_COMMENT,
4946 graphql::DELETE_COMMENT,
4947 graphql::ADD_COMMENT_WHOLE,
4948 graphql::UPDATE_COMMENT_WHOLE,
4949 ]
4950 .contains(&query)
4951 {
4952 let mut cache = self.resolved_cache()?;
4953 let mut ahead = self.read_ahead()?;
4954 let mut carried = self.carried()?;
4955 for argument in ["input", "second", "third", "clear"] {
4956 if let Some(input) = variables.get(argument) {
4957 let names = |id: &NativeId, item_id: Option<&str>| {
4958 ["id", "issueId", "subjectId", "itemId"].iter().any(|key| {
4959 input
4960 .get(key)
4961 .and_then(Value::as_str)
4962 .is_some_and(|value| value == id.0 || Some(value) == item_id)
4963 })
4964 };
4965 cache.retain(|id, item| !names(id, Some(&item.item_id)));
4966 ahead.retain(|id, item| {
4967 !names(id, item.as_ref().map(|item| item.item_id.as_str()))
4968 });
4969 carried.retain(|id, item| !names(id, Some(&item.item_id)));
4970 }
4971 }
4972 }
4973 let doing = operation_description(query);
4974 let mutation = is_mutation(query);
4975 let charge = pacing::Charge::graphql(query, &variables);
4976 let mut waited = Duration::ZERO;
4977 let mut waits = 0_u32;
4978 let mut backoff = self.pacing.retry_backoff;
4979 loop {
4980 let ticket = self.pace(charge, mutation).await;
4981 let attempt = self.send_once(query, &variables, waits + 1).await;
4982 self.paced(ticket, mutation);
4983 let limited = match attempt {
4984 Ok(data) => return Ok(data),
4985 Err(Attempt::Failed(error)) => return Err(error),
4986 Err(Attempt::Limited(limited)) => limited,
4987 };
4988 let (wait, cause) = limited.wait(backoff);
4989 let remaining = self.pacing.retry_budget.saturating_sub(waited);
4990 // A wait of nothing spends none of the budget, so it is exhaustion rather
4991 // than a retry. `Pacing::resolve` rules out every way of configuring one
4992 // except a budget of zero, where reporting the first refusal is the ask.
4993 if wait.is_zero() || wait > remaining {
4994 return Err(limited.exhausted(
4995 doing,
4996 waits,
4997 waited,
4998 wait,
4999 self.pacing.retry_budget,
5000 ));
5001 }
5002 self.clock.sleep_because(wait, cause).await;
5003 waited += wait;
5004 waits += 1;
5005 backoff = backoff.saturating_mul(2);
5006 }
5007 }
5008
5009 /// Hold one request charging `charge` until every secondary window it charges has room for
5010 /// the whole of it — and, for a mutation of an instance configured with
5011 /// `pacing.min_mutation_interval_ms`, until that interval has passed since the last one
5012 /// finished — then count it, answering the ticket [`Self::paced`] finishes it with.
5013 ///
5014 /// The moment is decided and counted under the lock and waited out outside it, so two
5015 /// callers take two places rather than the same one, and no lock is held across an await.
5016 /// A request with room goes out at once: nothing here waits that a window does not ask for.
5017 async fn pace(&self, charge: pacing::Charge, mutation: bool) -> pacing::Ticket {
5018 let (wait, cause, ticket) = {
5019 // A poisoned lock here costs pacing, not correctness, and refusing the write over
5020 // it would turn an earlier failure into a second one for no gain.
5021 let mut windows = self
5022 .windows
5023 .lock()
5024 .unwrap_or_else(std::sync::PoisonError::into_inner);
5025 let now = self.clock.now();
5026 let (mut at, mut cause) = if self.pacing.windows {
5027 windows.room(now, charge)
5028 } else {
5029 (now, None)
5030 };
5031 if mutation && !self.pacing.min_mutation_interval.is_zero() {
5032 let mut last = self
5033 .last_mutation
5034 .lock()
5035 .unwrap_or_else(std::sync::PoisonError::into_inner);
5036 // `checked_add` rather than `+`: adding durations can panic on overflow, and
5037 // pacing is not worth a panic even at a bound `MAX_PACING_MS` already rules out.
5038 if let Some(earliest) = last
5039 .and_then(|previous| previous.checked_add(self.pacing.min_mutation_interval))
5040 && earliest > at
5041 {
5042 at = earliest;
5043 cause = Some(pacing::cause::MIN_INTERVAL);
5044 }
5045 *last = Some(at);
5046 }
5047 let ticket = windows.charge(at, charge);
5048 (at.saturating_sub(now), cause, ticket)
5049 };
5050 if let (false, Some(cause)) = (wait.is_zero(), cause) {
5051 self.clock.sleep_because(wait, cause).await;
5052 }
5053 ticket
5054 }
5055
5056 /// Record that the request `ticket` was charged for has finished, so each window — and
5057 /// the configured spacing — counts it from here rather than from the moment it left.
5058 ///
5059 /// This source can only choose when a request *departs*; GitHub's limiter counts when it
5060 /// *arrives*, and the two differ by whatever the request spent in transit. Counting from
5061 /// departure would hand the limiter a window that looked roomier than it is, so a source
5062 /// pacing exactly at a limit could still be seen arriving over it — which is how a copy
5063 /// paced well inside a board's threshold was once refused by it on a slower machine while
5064 /// passing on a quick one. The previous request had arrived before its response came back,
5065 /// so counting from here is never earlier than the limiter does, whatever transit costs
5066 /// and on whatever platform: the safe side of a limit that punishes being wrong by refusing
5067 /// reads for the next fifty minutes.
5068 ///
5069 /// A failed attempt is finished too: a request refused by the limiter still arrived, and
5070 /// one that never left costs only room nobody needed.
5071 fn paced(&self, ticket: pacing::Ticket, mutation: bool) {
5072 let now = self.clock.now();
5073 self.windows
5074 .lock()
5075 .unwrap_or_else(std::sync::PoisonError::into_inner)
5076 .finish(ticket, now);
5077 if mutation && !self.pacing.min_mutation_interval.is_zero() {
5078 let mut last = self
5079 .last_mutation
5080 .lock()
5081 .unwrap_or_else(std::sync::PoisonError::into_inner);
5082 // `max` rather than an assignment: a concurrent caller may already have reserved a
5083 // slot further out, and completing this request must never pull that slot back in.
5084 *last = Some(last.map_or(now, |reserved| reserved.max(now)));
5085 }
5086 }
5087
5088 /// One HTTP attempt, classified into an answer, a rate limit to wait out, or a
5089 /// failure that waiting cannot help — and recorded, whichever of the three it was.
5090 ///
5091 /// This is the one place a request leaves this crate, which is why the accounting is
5092 /// here rather than at each of the callers: a read path added later is counted without
5093 /// anybody remembering to count it, and
5094 /// `the_session_report_counts_every_request_the_board_served_and_what_each_cost` fails
5095 /// when one is not.
5096 async fn send_once(
5097 &self,
5098 query: &str,
5099 variables: &Value,
5100 number: u32,
5101 ) -> Result<Value, Attempt> {
5102 let executed = self.ledger.priced_document(query);
5103 let Attempted {
5104 result,
5105 limits,
5106 reported_cost,
5107 response_outcome,
5108 } = self.attempt(executed.as_ref(), variables).await;
5109 // No `otherwise` name: every document this source sends is one of its own, and the
5110 // inventory gate on `graphql::DOCUMENTS` is what keeps that true.
5111 let sending = accounting::Request::graphql(query, variables, None, reported_cost);
5112 let outcome = match &result {
5113 Ok(_) => accounting::Outcome::Answered,
5114 Err(Attempt::Limited(_)) => accounting::Outcome::RateLimited,
5115 Err(Attempt::Failed(_)) => accounting::Outcome::Refused,
5116 };
5117 self.ledger
5118 .record(sending.finished(outcome, limits).with_execution(
5119 Some(executed.into_owned()),
5120 response_outcome,
5121 number,
5122 ));
5123 result
5124 }
5125
5126 /// The attempt itself, with what its response said about the rate limit alongside.
5127 ///
5128 /// The two are returned together rather than recorded here because every one of the
5129 /// early exits below is a different outcome, and a record written at each of them is a
5130 /// record one of them can be added without.
5131 async fn attempt(&self, query: &str, variables: &Value) -> Attempted {
5132 let mut limits = accounting::RateLimit::default();
5133 let mut reported_cost = None;
5134 let mut response_outcome = accounting::ResponseOutcome::TransportError;
5135 let result = self
5136 .attempted(
5137 query,
5138 variables,
5139 &mut limits,
5140 &mut reported_cost,
5141 &mut response_outcome,
5142 )
5143 .await;
5144 Attempted {
5145 result,
5146 limits,
5147 reported_cost,
5148 response_outcome,
5149 }
5150 }
5151
5152 /// One HTTP attempt, filling in what its response said about the rate limit as it goes.
5153 async fn attempted(
5154 &self,
5155 query: &str,
5156 variables: &Value,
5157 limits: &mut accounting::RateLimit,
5158 reported_cost: &mut Option<u64>,
5159 response_outcome: &mut accounting::ResponseOutcome,
5160 ) -> Result<Value, Attempt> {
5161 let response = self
5162 .client
5163 .post(self.endpoint.clone())
5164 .bearer_auth(self.token.expose_secret())
5165 .json(&json!({"query": query, "variables": variables}))
5166 .send()
5167 .await
5168 .map_err(|e| {
5169 Attempt::Failed(SourceError::Unavailable {
5170 message: format!("GitHub GraphQL request failed: {}", transport_error(&e)),
5171 })
5172 })?;
5173 let status = response.status();
5174 if !status.is_success() {
5175 *response_outcome = accounting::ResponseOutcome::HttpError;
5176 }
5177 let header = |name: &str| whole_seconds(response.headers().get(name));
5178 let served = response
5179 .headers()
5180 .get(reqwest::header::DATE)
5181 .and_then(|value| value.to_str().ok())
5182 .and_then(|value| DateTime::parse_from_rfc2822(value).ok())
5183 .map(|at| at.with_timezone(&Utc));
5184 *limits = accounting::RateLimit::read(|name| {
5185 response
5186 .headers()
5187 .get(name)
5188 .and_then(|value| value.to_str().ok())
5189 .map(str::to_owned)
5190 });
5191 // Exactly `0` is exhaustion and everything else — a count, an empty value, bytes
5192 // that are not text at all — is "not known to be exhausted". This never makes a
5193 // response a refusal on its own: it says which limiter a refusal is attributed to
5194 // and where its hint comes from, so a value this cannot read costs a hint rather
5195 // than an answer.
5196 let exhausted = response
5197 .headers()
5198 .get("x-ratelimit-remaining")
5199 .and_then(|value| value.to_str().ok())
5200 == Some("0");
5201 // `retry-after` is what GitHub asks for when it asks; when it does not and the
5202 // primary budget is spent, `x-ratelimit-reset` says when that budget comes back,
5203 // which is the same question answered as an absolute time. Nothing else here is a
5204 // hint, and a schedule is what answers a refusal that carries none.
5205 let retry_after = header("retry-after");
5206 let hinted_by = if retry_after.is_some() || !exhausted {
5207 Hint::RetryAfter
5208 } else {
5209 Hint::PrimaryReset
5210 };
5211 let hint = retry_after.or_else(|| {
5212 exhausted
5213 .then(|| header("x-ratelimit-reset"))
5214 .flatten()
5215 .map(|reset| reset.saturating_sub(Utc::now().timestamp().max(0).unsigned_abs()))
5216 });
5217 // Read before it is parsed, because the evidence which tells a secondary rate
5218 // limit from a rejected credential is in the body of a response whose status says
5219 // only "forbidden" — and a non-success response was never parsed at all.
5220 let body = response.text().await.map_err(|e| {
5221 Attempt::Failed(SourceError::Unavailable {
5222 message: format!(
5223 "GitHub GraphQL response could not be read: {}",
5224 transport_error(&e)
5225 ),
5226 })
5227 })?;
5228 *reported_cost = serde_json::from_str::<Value>(&body)
5229 .ok()
5230 .as_ref()
5231 .and_then(|body| body.pointer("/data/rateLimit/cost"))
5232 .and_then(Value::as_u64);
5233 let parsed = serde_json::from_str::<Value>(&body).ok();
5234 *response_outcome = accounting::ResponseOutcome::of_graphql_reply(status, parsed.as_ref());
5235 if let Some(limiter) = Limiter::classify(status, exhausted, &body) {
5236 return Err(Attempt::Limited(Limited {
5237 limiter,
5238 hint,
5239 hinted_by,
5240 }));
5241 }
5242 if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
5243 return Err(Attempt::Failed(SourceError::Auth {
5244 message: format!(
5245 "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"
5246 ),
5247 }));
5248 }
5249 if !status.is_success() {
5250 return Err(Attempt::Failed(SourceError::Unavailable {
5251 message: format!("GitHub GraphQL returned HTTP {status}"),
5252 }));
5253 }
5254 let answered = if query == graphql::ISSUES_BY_REFERENCE {
5255 self.answer_unresolved(&body)
5256 } else if query == graphql::CREATE_ISSUES {
5257 answer_with_errors(&body).map_or_else(|| self.answer(&body), Ok)
5258 } else {
5259 self.answer(&body)
5260 };
5261 let mut data = answered.map_err(Attempt::Failed)?;
5262 if let Some(served) = served {
5263 stamp_served(&mut data, &served.to_rfc3339());
5264 }
5265 Ok(data)
5266 }
5267
5268 /// What one successful HTTP response says, once its GraphQL errors are read.
5269 /// [`Self::answer`], for a read of issues by reference: a reference GitHub cannot resolve
5270 /// for this credential — a repository it cannot see, an issue number it does not hold —
5271 /// is answered `null` beside a `NOT_FOUND` error naming it, and that is an answer about
5272 /// that reference rather than a failure of the others. Any other error refuses the read,
5273 /// as there.
5274 fn answer_unresolved(&self, body: &str) -> Result<Value, SourceError> {
5275 let parsed: Option<Value> = serde_json::from_str(body).ok();
5276 // Each error is a `NOT_FOUND` whose path names one slot of the batch, `r<n>` or its
5277 // `issue`, and the answer holds `null` at exactly that path: anything else — another
5278 // kind of error, one naming no slot, or one beside a value it says is not there — is a
5279 // refusal of the whole read.
5280 let unresolved = |data: &Value, error: &Value| {
5281 error.get("type").and_then(Value::as_str) == Some("NOT_FOUND")
5282 && error
5283 .get("path")
5284 .and_then(Value::as_array)
5285 .is_some_and(|path| {
5286 let alias = path.first().and_then(Value::as_str).and_then(|alias| {
5287 alias
5288 .strip_prefix('r')
5289 .and_then(|slot| slot.parse::<usize>().ok())
5290 .filter(|slot| *slot < REFERENCE_BATCH)
5291 .map(|_| alias)
5292 });
5293 match (alias, path.get(1).and_then(Value::as_str), path.len()) {
5294 (Some(alias), None, 1) => data.get(alias).is_some_and(Value::is_null),
5295 (Some(alias), Some("issue"), 2) => data
5296 .get(alias)
5297 .and_then(|repository| repository.get("issue"))
5298 .is_some_and(Value::is_null),
5299 _ => false,
5300 }
5301 })
5302 };
5303 let unresolved_only = parsed.as_ref().is_some_and(|parsed| {
5304 parsed.get("data").is_some_and(|data| {
5305 data.is_object()
5306 && parsed
5307 .get("errors")
5308 .and_then(Value::as_array)
5309 .is_some_and(|errors| errors.iter().all(|error| unresolved(data, error)))
5310 })
5311 });
5312 match parsed {
5313 Some(parsed) if unresolved_only => Ok(parsed["data"].clone()),
5314 _ => self.answer(body),
5315 }
5316 }
5317
5318 fn answer(&self, body: &str) -> Result<Value, SourceError> {
5319 let body: Value = serde_json::from_str(body).map_err(|e| SourceError::Malformed {
5320 message: format!("GitHub returned invalid JSON: {e}"),
5321 })?;
5322 let errors = body
5323 .get("errors")
5324 .map(|value| {
5325 value.as_array().ok_or_else(|| SourceError::Malformed {
5326 message: "GitHub response errors is not an array".into(),
5327 })
5328 })
5329 .transpose()?;
5330 if let Some(errors) = errors.filter(|errors| !errors.is_empty()) {
5331 let messages = errors
5332 .iter()
5333 .filter_map(|e| e.get("message").and_then(Value::as_str))
5334 .collect::<Vec<_>>()
5335 .join("; ");
5336 let message = if messages.is_empty() {
5337 "GitHub returned GraphQL errors".into()
5338 } else {
5339 messages
5340 };
5341 let normalized = message.to_ascii_lowercase();
5342 if normalized.contains("resource not accessible") || normalized.contains("scope") {
5343 return Err(SourceError::Auth {
5344 message: format!(
5345 "{message}; grant {} Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board",
5346 self.credential_name
5347 ),
5348 });
5349 }
5350 return Err(SourceError::Refused { message });
5351 }
5352 body.get("data")
5353 .filter(|data| data.is_object())
5354 .cloned()
5355 .ok_or_else(|| SourceError::Malformed {
5356 message: "GitHub response has no data object".into(),
5357 })
5358 }
5359
5360 // llmlint: ignore[boundary_inputs_validated] GitHub caps nested connections at 100 and
5361 // GraphQL cannot independently page them inside the outer item page. This source page is
5362 // deliberately bounded at that published maximum; the live drift journey exercises it.
5363 async fn board_page(
5364 &self,
5365 items_after: Option<&str>,
5366 items_first: u32,
5367 ) -> Result<Value, SourceError> {
5368 let data = self
5369 .graphql(
5370 graphql::BOARD,
5371 json!({"owner":self.owner,"number":self.project_number,
5372 "first":items_first.min(MAX_PAGE_SIZE),"after":items_after,
5373 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
5374 )
5375 .await?;
5376 data.pointer("/owner/projectV2")
5377 .filter(|v| !v.is_null())
5378 .cloned()
5379 .ok_or_else(|| SourceError::Refused {
5380 message: format!(
5381 "GitHub project {}/{} was not found or is not visible to the token",
5382 self.owner, self.project_number
5383 ),
5384 })
5385 }
5386
5387 /// The search that finds the issues of this board, narrowed by `also` when it is
5388 /// given.
5389 ///
5390 /// `project:owner/number` is what scopes a search to one board, and `is:issue` is what
5391 /// keeps pull requests out of it: GitHub's `ISSUE` search type covers both, and a pull
5392 /// request is somebody's change rather than a unit of plan. `-has:parent` is *not*
5393 /// here on purpose — GitHub accepts it and silently ignores it, so a project is told
5394 /// from a task by the `parent` field each issue carries rather than by the search.
5395 fn board_search(&self, also: Option<&str>) -> String {
5396 let scope = format!("project:{}/{} is:issue", self.owner, self.project_number);
5397 match also {
5398 Some(also) => format!("{scope} {also}"),
5399 None => scope,
5400 }
5401 }
5402
5403 /// One issue this source reached directly, as the board item a read of the board would
5404 /// have produced — or `None` when this board does not hold it.
5405 ///
5406 /// The board half of an issue rides along on `Issue.projectItems`, so the value handed
5407 /// to [`Self::resolve`] is the very shape a `ProjectV2.items` read gives it: the board
5408 /// item's own id, that item's field values, and the issue as its content. One resolver
5409 /// for both routes is what makes an issue read through a search, through its own node
5410 /// id, or through its project's sub-issues report the same title, the same status, the
5411 /// same labels and the same qualified id.
5412 ///
5413 /// An issue with no entry for *this* board is not this source's to report, which is
5414 /// what keeps an id naming some other repository's issue from being answered as an item
5415 /// of this board. That answer is given about an **exhausted** connection and never
5416 /// about an unread page: the entry is looked for on the page in hand, and only if that
5417 /// page reports more of the connection, in [`Self::board_membership`]'s walk of the
5418 /// rest of it.
5419 async fn resolve_issue(&self, issue: &Value) -> Result<Option<Resolved>, SourceError> {
5420 self.resolve_issue_as(issue, true).await
5421 }
5422
5423 /// [`Self::resolve_issue`], remembering what it resolves for this command's later reads
5424 /// and writes only when `remember` says to.
5425 async fn resolve_issue_as(
5426 &self,
5427 issue: &Value,
5428 remember: bool,
5429 ) -> Result<Option<Resolved>, SourceError> {
5430 if optional_str(issue, "__typename")? != Some("Issue") {
5431 return Ok(None);
5432 }
5433 let memberships = issue
5434 .get("projectItems")
5435 .ok_or_else(|| SourceError::Malformed {
5436 message: "GitHub issue is missing projectItems".into(),
5437 })?;
5438 let nodes = memberships
5439 .get("nodes")
5440 .and_then(Value::as_array)
5441 .ok_or_else(|| SourceError::Malformed {
5442 message: "GitHub issue projectItems.nodes is not an array".into(),
5443 })?;
5444 let held = match self.board_entry(nodes) {
5445 Some(held) => held.clone(),
5446 None => {
5447 let info = memberships
5448 .get("pageInfo")
5449 .ok_or_else(|| SourceError::Malformed {
5450 message: "GitHub issue projectItems has no pageInfo".into(),
5451 })?;
5452 // The page held no entry for this board. Whether that means the issue is
5453 // not on it is a question about the rest of the connection, and only a
5454 // connection with no rest answers it here.
5455 if !required_bool(info, "hasNextPage")? {
5456 return Ok(None);
5457 }
5458 let cursor = required_str(info, "endCursor")?;
5459 validate_cursor_progress(None, cursor)?;
5460 let issue_id = required_str(issue, "id")?;
5461 match self.board_membership(issue_id, cursor).await? {
5462 Some(held) => held,
5463 None => return Ok(None),
5464 }
5465 }
5466 };
5467 // The membership's own `updatedAt` rides along: it is the board half of the item's change
5468 // token, which a field change moves where the issue's own time does not.
5469 let item = json!({
5470 "id": required_str(&held, "id")?,
5471 "updatedAt": held.get("updatedAt"),
5472 "project": held.get("project"),
5473 "fieldValues": held.get("fieldValues"),
5474 "content": issue,
5475 });
5476 if remember {
5477 self.resolve(&item)
5478 } else {
5479 self.resolve_unremembered(&item)
5480 }
5481 }
5482
5483 /// This board's own entry among one page of an issue's `Issue.projectItems`.
5484 ///
5485 /// One spelling of *which membership is this board's*, so the page a read carries and
5486 /// the pages [`Self::board_membership`] walks are searched by the same rule.
5487 fn board_entry<'a>(&self, nodes: &'a [Value]) -> Option<&'a Value> {
5488 nodes.iter().find(|node| {
5489 node.pointer("/project/number").and_then(Value::as_u64)
5490 == Some(u64::from(self.project_number))
5491 })
5492 }
5493
5494 /// The rest of one issue's board memberships, from `after`, for this board's entry.
5495 ///
5496 /// The recovery read: a page of memberships that holds no entry for this board says
5497 /// nothing about the memberships past it, so the connection is walked to exhaustion
5498 /// before an issue is reported as one this board does not hold. `Ok(None)` is that
5499 /// positive answer — the whole connection was read and no entry named this board —
5500 /// rather than a failure, and the walk is held to
5501 /// [`validate_cursor_progress`] like every other page walk here, so a source answering
5502 /// with a cursor that does not advance is refused instead of spun on.
5503 async fn board_membership(
5504 &self,
5505 issue: &str,
5506 after: &str,
5507 ) -> Result<Option<Value>, SourceError> {
5508 let mut after = after.to_owned();
5509 loop {
5510 let data = self
5511 .graphql(
5512 graphql::ISSUE_BOARD_ITEMS,
5513 json!({"id":issue,"first":MAX_PAGE_SIZE,"after":after,
5514 "nestedFirst":NESTED_PAGE_SIZE}),
5515 )
5516 .await?;
5517 let Some(connection) = data
5518 .pointer("/node/projectItems")
5519 .filter(|value| !value.is_null())
5520 else {
5521 // The id resolved to nothing, or to something with no memberships to walk —
5522 // which is the same answer as a connection holding no entry for this board.
5523 return Ok(None);
5524 };
5525 let nodes = connection
5526 .get("nodes")
5527 .and_then(Value::as_array)
5528 .ok_or_else(|| SourceError::Malformed {
5529 message: "GitHub issue projectItems.nodes is not an array".into(),
5530 })?;
5531 if let Some(held) = self.board_entry(nodes) {
5532 return Ok(Some(held.clone()));
5533 }
5534 let info = connection
5535 .get("pageInfo")
5536 .ok_or_else(|| SourceError::Malformed {
5537 message: "GitHub issue projectItems has no pageInfo".into(),
5538 })?;
5539 let next = required_bool(info, "hasNextPage")?
5540 .then(|| required_str(info, "endCursor"))
5541 .transpose()?;
5542 match next {
5543 Some(next) => {
5544 validate_cursor_progress(Some(&after), next)?;
5545 after = next.to_owned();
5546 }
5547 None => return Ok(None),
5548 }
5549 }
5550 }
5551
5552 /// One page of a board-scoped issue search, and where the next page resumes.
5553 async fn search_page(
5554 &self,
5555 search: &str,
5556 first: u32,
5557 after: Option<&str>,
5558 ) -> Result<(Vec<Resolved>, Option<String>), SourceError> {
5559 let data = self
5560 .graphql(
5561 graphql::SEARCH_ISSUES,
5562 json!({"search":search,"type":"ISSUE","first":first.min(MAX_PAGE_SIZE),
5563 "after":after,"nestedFirst":NESTED_PAGE_SIZE,
5564 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
5565 )
5566 .await?;
5567 let connection = data.get("search").ok_or_else(|| SourceError::Malformed {
5568 message: "GitHub search response has no search connection".into(),
5569 })?;
5570 let mut found = Vec::new();
5571 for node in connection
5572 .get("nodes")
5573 .and_then(Value::as_array)
5574 .ok_or_else(|| SourceError::Malformed {
5575 message: "GitHub search nodes is not an array".into(),
5576 })?
5577 {
5578 if let Some(resolved) = self.resolve_issue(node).await? {
5579 found.push(resolved);
5580 }
5581 }
5582 let info = connection
5583 .get("pageInfo")
5584 .ok_or_else(|| SourceError::Malformed {
5585 message: "GitHub search connection has no pageInfo".into(),
5586 })?;
5587 let next = required_bool(info, "hasNextPage")?
5588 .then(|| required_str(info, "endCursor"))
5589 .transpose()?
5590 .map(str::to_owned);
5591 if let Some(next) = &next {
5592 validate_cursor_progress(after, next)?;
5593 }
5594 Ok((found, next))
5595 }
5596
5597 /// Every issue this board holds, completed with what this run wrote.
5598 ///
5599 /// The completion is not an optimisation and it is not a cache: GitHub's issue search
5600 /// is an index and is eventually consistent, so an issue this run created seconds ago
5601 /// can be absent from it, and a project listed straight after being written would
5602 /// otherwise be missing from its own board. What is added back is only what this
5603 /// process itself wrote, out of [`Self::created`], which lives and dies with the
5604 /// process.
5605 async fn board_issues(&self) -> Result<Vec<Resolved>, SourceError> {
5606 let found = self.searched_issues().await?;
5607 self.completed_with_written(found, |_| true)
5608 }
5609
5610 /// Every issue this board's own search reports, walked to exhaustion, read once per
5611 /// source.
5612 ///
5613 /// The uncompleted half of [`Self::board_issues`], separated because [`Self::board`]
5614 /// needs it too and the two would otherwise walk the same search twice in one command.
5615 /// See [`Self::search_cache`] for why holding it is the same bargain holding the board
5616 /// is.
5617 async fn searched_issues(&self) -> Result<Vec<Resolved>, SourceError> {
5618 let cached = self.search_cache()?.clone();
5619 if let Some(held) = cached {
5620 return Ok(held);
5621 }
5622 let mut after: Option<String> = None;
5623 let mut found = Vec::new();
5624 let search = self.board_search(None);
5625 loop {
5626 let (page, next) = self
5627 .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
5628 .await?;
5629 found.extend(page);
5630 match next {
5631 Some(next) => after = Some(next),
5632 None => break,
5633 }
5634 }
5635 *self.search_cache()? = Some(found.clone());
5636 Ok(found)
5637 }
5638
5639 /// Every issue this board's own search reports with `also` beside its scope, walked to
5640 /// exhaustion — held for no later read, which may not be narrowed alike.
5641 async fn searched_narrowly(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
5642 let mut after: Option<String> = None;
5643 let mut found = Vec::new();
5644 let search = self.board_search(Some(also));
5645 loop {
5646 let (page, next) = self
5647 .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
5648 .await?;
5649 found.extend(page);
5650 match next {
5651 Some(next) => after = Some(next),
5652 None => return Ok(found),
5653 }
5654 }
5655 }
5656
5657 /// This process's own view of the board's issues, or the refusal a poisoned lock is.
5658 fn search_cache(
5659 &self,
5660 ) -> Result<std::sync::MutexGuard<'_, Option<Vec<Resolved>>>, SourceError> {
5661 self.search_cache
5662 .lock()
5663 .map_err(|_| SourceError::Unavailable {
5664 message: "this source's view of the board's issues was left inconsistent by an \
5665 earlier failure; next: run the command again"
5666 .into(),
5667 })
5668 }
5669
5670 /// `found`, with everything this run wrote that `keep` accepts and the read did not
5671 /// report.
5672 ///
5673 /// See [`Self::created`] and [`Self::board_issues`] for why a read has to be completed
5674 /// at all: the search index is behind, and a node read of an item filed moments ago can
5675 /// be too.
5676 fn completed_with_written(
5677 &self,
5678 mut found: Vec<Resolved>,
5679 keep: impl Fn(&Resolved) -> bool,
5680 ) -> Result<Vec<Resolved>, SourceError> {
5681 for own in self.created()?.iter().filter(|own| keep(own)) {
5682 if !found.iter().any(|item| item.id == own.id) {
5683 found.push(own.clone());
5684 }
5685 }
5686 Ok(found)
5687 }
5688
5689 /// What resolving one node id reached.
5690 ///
5691 /// Three answers rather than an `Option`, because a board *draft* is none of the other
5692 /// two: it is not an issue, so the issue fragment reads nothing of it, and a read of one
5693 /// is completed by a read of the draft itself rather than reported as nothing.
5694 async fn reach(&self, id: &NativeId) -> Result<Reached, SourceError> {
5695 let asked = self
5696 .graphql(
5697 graphql::ISSUE,
5698 json!({"id":id.0,"first":MAX_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
5699 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
5700 )
5701 .await;
5702 let data = match asked {
5703 Ok(data) => data,
5704 // A string that is not a node id at all is not a failure to report: it is an id
5705 // this board does not hold, which is what every read of one already answers.
5706 Err(error) if unresolvable_node(&error) => return Ok(Reached::Nothing),
5707 Err(error) => return Err(error),
5708 };
5709 let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
5710 return Ok(Reached::Nothing);
5711 };
5712 if optional_str(node, "__typename")? == Some("DraftIssue") {
5713 return Ok(Reached::Draft);
5714 }
5715 Ok(match self.resolve_issue(node).await? {
5716 Some(item) => Reached::Held(Box::new(item)),
5717 None => Reached::Nothing,
5718 })
5719 }
5720
5721 /// One item of this board by its own id, whatever kind it is.
5722 ///
5723 /// Resolved from the identifier alone: no search, board-wide or otherwise. What this
5724 /// run wrote is read first, because a node read of an item created moments ago can
5725 /// still be behind the board field values written onto it — see [`Self::created`].
5726 async fn item_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5727 if let Some(own) = self.created()?.iter().find(|own| own.id == *id) {
5728 return Ok(Some(own.clone()));
5729 }
5730 if let Some(held) = self.read_ahead()?.remove(id) {
5731 return Ok(held);
5732 }
5733 match self.reach(id).await? {
5734 Reached::Held(item) => Ok(Some(*item)),
5735 Reached::Nothing => Ok(None),
5736 Reached::Draft => self.draft_by_id(id).await,
5737 }
5738 }
5739
5740 /// Several items of this board, each by its own id, in order — what [`Self::item_by_id`]
5741 /// answers for each, read [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] rather
5742 /// than one request per id.
5743 ///
5744 /// What this run wrote answers first, as it does there, and only the rest is read. One id
5745 /// left to read is read by [`Self::item_by_id`] itself, which costs what a batch does. A
5746 /// batch GitHub refuses because one of its ids resolves to no node at all is read again one
5747 /// id at a time, so that id is answered as not held and the others as themselves; a draft
5748 /// is completed by a read of the draft, exactly as there.
5749 async fn items_by_ids(&self, ids: &[NativeId]) -> Result<Vec<Option<Resolved>>, SourceError> {
5750 let mut found: Vec<Option<Option<Resolved>>> = {
5751 let created = self.created()?;
5752 ids.iter()
5753 .map(|id| {
5754 created
5755 .iter()
5756 .find(|own| own.id == *id)
5757 .map(|own| Some(own.clone()))
5758 })
5759 .collect()
5760 };
5761 let unread: Vec<NativeId> = ids
5762 .iter()
5763 .zip(&found)
5764 .filter(|(_, found)| found.is_none())
5765 .map(|(id, _)| id.clone())
5766 .collect();
5767 let mut read = Vec::with_capacity(unread.len());
5768 if let [one] = unread.as_slice() {
5769 read.push(self.item_by_id(one).await?);
5770 } else {
5771 for batch in unread.chunks(DETAIL_BATCH) {
5772 let data = match self
5773 .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, None))
5774 .await
5775 {
5776 Ok(data) => data,
5777 Err(error) if unresolvable_node(&error) => {
5778 for id in batch {
5779 read.push(self.item_by_id(id).await?);
5780 }
5781 continue;
5782 }
5783 Err(error) => return Err(error),
5784 };
5785 for (slot, id) in batch.iter().enumerate() {
5786 let node =
5787 data.get(format!("i{slot}"))
5788 .ok_or_else(|| SourceError::Malformed {
5789 message: format!(
5790 "GitHub answered a batch read with no item for {}",
5791 id.0
5792 ),
5793 })?;
5794 read.push(if node.is_null() {
5795 None
5796 } else if optional_str(node, "__typename")? == Some("DraftIssue") {
5797 self.draft_by_id(id).await?
5798 } else {
5799 if optional_str(node, "__typename")? == Some("Issue")
5800 && required_str(node, "id")? != id.0
5801 {
5802 return Err(SourceError::Malformed {
5803 message: format!(
5804 "GitHub answered the read of {} with issue {}",
5805 id.0,
5806 required_str(node, "id")?
5807 ),
5808 });
5809 }
5810 self.resolve_issue(node).await?
5811 });
5812 }
5813 }
5814 }
5815 let mut read = read.into_iter();
5816 Ok(found
5817 .iter_mut()
5818 .map(|slot| slot.take().unwrap_or_else(|| read.next().flatten()))
5819 .collect())
5820 }
5821
5822 fn read_ahead(
5823 &self,
5824 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Option<Resolved>>>, SourceError> {
5825 self.read_ahead
5826 .lock()
5827 .map_err(|_| SourceError::Unavailable {
5828 message:
5829 "items read ahead for a copy were left inconsistent; run the command again"
5830 .into(),
5831 })
5832 }
5833
5834 fn resolved_cache(
5835 &self,
5836 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
5837 self.resolved_cache
5838 .lock()
5839 .map_err(|_| SourceError::Unavailable {
5840 message: "resolved item records were left inconsistent; run the command again"
5841 .into(),
5842 })
5843 }
5844
5845 /// Reuse a record this invocation already resolved. The mutation sender invalidates
5846 /// it before writing, so a partial failure cannot leave a pre-write binding behind.
5847 async fn bound_item(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5848 let cached = self.resolved_cache()?.get(id).cloned();
5849 if let Some(item) = cached {
5850 return Ok(Some(item));
5851 }
5852 self.item_by_id(id).await
5853 }
5854
5855 /// Take out the item an issue read by reference reached for `id`, when one is held: the
5856 /// status write it was read for is the one caller, so no other read or write is ever
5857 /// answered from a read that selected only what that write needs.
5858 fn take_held(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5859 Ok(self
5860 .held_cache
5861 .lock()
5862 .map_err(|_| SourceError::Unavailable {
5863 message: "items read by issue reference were left inconsistent; run the \
5864 command again"
5865 .into(),
5866 })?
5867 .remove(id))
5868 }
5869
5870 /// One board draft by its own id, with the board item it sits in — or `None` when no
5871 /// item of this board is that draft's.
5872 ///
5873 /// The same decision [`Self::resolve_issue`] makes for an issue, over the draft's own
5874 /// `projectV2Items`: an entry naming this board is what makes it this board's. GitHub
5875 /// links a draft to one board item, so the page this read carries is the whole of that
5876 /// connection, and a page that reports more than it holds is refused rather than read
5877 /// as an answer about memberships nobody read.
5878 async fn draft_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
5879 let data = self
5880 .graphql(
5881 graphql::DRAFT,
5882 json!({"id":id.0,"nestedFirst":NESTED_PAGE_SIZE,
5883 "boardItems":BOARD_ITEMS_PAGE_SIZE}),
5884 )
5885 .await?;
5886 // Gone between the two reads is an answer — the draft is no longer there. Anything
5887 // else than the draft [`Self::reach`] was just told this id is, is not one.
5888 let Some(draft) = data.get("node").filter(|node| !node.is_null()) else {
5889 return Ok(None);
5890 };
5891 if optional_str(draft, "__typename")? != Some("DraftIssue") {
5892 return Err(SourceError::Malformed {
5893 message: format!(
5894 "GitHub answered {} as a draft and then as something else",
5895 id.0
5896 ),
5897 });
5898 }
5899 if required_str(draft, "id")? != id.0 {
5900 return Err(SourceError::Malformed {
5901 message: format!("GitHub answered a different draft for {}", id.0),
5902 });
5903 }
5904 let memberships = draft
5905 .get("projectV2Items")
5906 .ok_or_else(|| SourceError::Malformed {
5907 message: format!("GitHub draft {} is missing projectV2Items", id.0),
5908 })?;
5909 let nodes = memberships
5910 .get("nodes")
5911 .and_then(Value::as_array)
5912 .ok_or_else(|| SourceError::Malformed {
5913 message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
5914 })?;
5915 let info = memberships
5916 .get("pageInfo")
5917 .ok_or_else(|| SourceError::Malformed {
5918 message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
5919 })?;
5920 // Read whether or not this board's entry is on the page: a page claiming more than
5921 // the one item GitHub links a draft to is a malformed answer either way.
5922 if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
5923 return Err(SourceError::Malformed {
5924 message: format!(
5925 "GitHub draft {} reports more board items than the one GitHub links a draft \
5926 to",
5927 id.0
5928 ),
5929 });
5930 }
5931 if let Some(node) = nodes.first()
5932 && node
5933 .pointer("/project/number")
5934 .and_then(Value::as_u64)
5935 .is_none()
5936 {
5937 return Err(SourceError::Malformed {
5938 message: format!(
5939 "GitHub draft {} board item has no numeric project number",
5940 id.0
5941 ),
5942 });
5943 }
5944 let Some(held) = self.board_entry(nodes) else {
5945 return Ok(None);
5946 };
5947 if required_str(
5948 held.get("project").ok_or_else(|| SourceError::Malformed {
5949 message: format!("GitHub draft {} board item has no project", id.0),
5950 })?,
5951 "id",
5952 )? != self.board_fields().await?.id.as_str()
5953 {
5954 return Ok(None);
5955 }
5956 let item = json!({
5957 "id": required_str(held, "id")?,
5958 "project": held.get("project"),
5959 "fieldValues": held.get("fieldValues"),
5960 "content": draft,
5961 });
5962 self.resolve(&item)
5963 }
5964
5965 /// The board's own id and field definitions, for a write whose item does not carry
5966 /// them — never its items.
5967 ///
5968 /// A board this command has already listed supplies them, since it read them beside its
5969 /// items; otherwise they come from [`graphql::BOARD_FIELDS`], once per command. Neither
5970 /// is consulted about which items the board holds: see the module documentation for
5971 /// why a question about one known item is answered by reading that item.
5972 async fn board_fields(&self) -> Result<BoardFields, SourceError> {
5973 if let Some(board) = self.board_cache()?.as_ref() {
5974 return Ok(BoardFields {
5975 id: BoardId::parse(&board.id)?,
5976 fields: board.fields.clone(),
5977 });
5978 }
5979 if let Some(held) = self.fields_cache()?.clone() {
5980 return Ok(held);
5981 }
5982 let data = self
5983 .graphql(
5984 graphql::BOARD_FIELDS,
5985 json!({"owner":self.owner,"number":self.project_number,
5986 "nestedFirst":NESTED_PAGE_SIZE}),
5987 )
5988 .await?;
5989 self.fields_read(&data)
5990 }
5991
5992 /// The board's id and fields out of an answer carrying the `boardFields` root, held for
5993 /// the rest of this command.
5994 fn fields_read(&self, data: &Value) -> Result<BoardFields, SourceError> {
5995 let board = data
5996 .pointer("/boardFields/projectV2")
5997 .filter(|value| !value.is_null())
5998 .ok_or_else(|| SourceError::Refused {
5999 message: format!(
6000 "GitHub project {}/{} was not found or is not visible to the token",
6001 self.owner, self.project_number
6002 ),
6003 })?;
6004 let read = BoardFields {
6005 id: BoardId::parse(required_str(board, "id")?)?,
6006 fields: board.get("fields").cloned().unwrap_or(Value::Null),
6007 };
6008 *self.fields_cache()? = Some(read.clone());
6009 Ok(read)
6010 }
6011
6012 /// Read what creating an issue in `repository` needs and this command has not read yet —
6013 /// the board's fields and the repository's node id — in one request when it needs both.
6014 ///
6015 /// When either is already known this sends nothing, and the other is read by its own
6016 /// document where it is asked for, so no create reads anything twice.
6017 async fn creation_context(
6018 &self,
6019 repository: &RepositoryTarget,
6020 incoming: &Incoming<'_>,
6021 ) -> Result<(), SourceError> {
6022 let fields_known = self.board_cache()?.is_some() || self.fields_cache()?.is_some();
6023 if fields_known || self.repository_cache()?.contains_key(repository) {
6024 return Ok(());
6025 }
6026 let data = self
6027 .graphql(
6028 graphql::CREATION_CONTEXT,
6029 json!({"owner":self.owner,"number":self.project_number,
6030 "nestedFirst":NESTED_PAGE_SIZE,"repositoryOwner":repository.owner,
6031 "repositoryName":repository.name}),
6032 )
6033 .await?;
6034 self.fields_read(&data)?;
6035 self.repository_read(&data, repository, incoming)?;
6036 Ok(())
6037 }
6038
6039 /// This process's own view of the board's fields, or the refusal a poisoned lock is.
6040 fn fields_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<BoardFields>>, SourceError> {
6041 self.fields_cache
6042 .lock()
6043 .map_err(|_| SourceError::Unavailable {
6044 message: "this source's view of the board's fields was left inconsistent by an \
6045 earlier failure; next: run the command again"
6046 .into(),
6047 })
6048 }
6049
6050 /// What a write to `item` needs of the board, read off that item when it says enough and
6051 /// off [`Self::board_fields`] when it does not.
6052 ///
6053 /// A node read of an item names its board and carries the definition of every field it
6054 /// holds a value of — so an item naming its board, holding a value of the origin field,
6055 /// and, when the write carries a status, holding a `Status` value, needs no read of the
6056 /// board at all. **Nothing the item does not say is guessed:** a field it holds no value
6057 /// of may still be on the board, and a view reading it as absent would refuse a write the
6058 /// board can take or skip a field write the board needs, so such an item — and a create,
6059 /// which has no item yet — takes the board's fields from their own read instead.
6060 async fn fields_for(
6061 &self,
6062 item: Option<&Resolved>,
6063 writes_status: bool,
6064 selects_priority: bool,
6065 ) -> Result<BoardFields, SourceError> {
6066 if let Some(board) = item.and_then(Resolved::carried_board) {
6067 return Ok(board);
6068 }
6069 if let Some(item) = item
6070 && let Some(board_id) = item.named_board()
6071 && item.defines(ORIGIN_FIELD)
6072 && (!writes_status || item.defines("Status"))
6073 && (!selects_priority || item.defines(PRIORITY_FIELD))
6074 && self
6075 .metadata_fields
6076 .iter()
6077 .all(|projection| item.defines(&projection.field))
6078 {
6079 return Ok(BoardFields {
6080 id: board_id,
6081 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
6082 });
6083 }
6084 self.board_fields().await
6085 }
6086
6087 /// Everything filed under one issue of this board, walked to exhaustion — or `None`
6088 /// when that id names nothing here with a sub-issue relationship to walk.
6089 ///
6090 /// `None` and an empty answer are different: `None` is *this is not an issue of this
6091 /// GitHub*, which is what sends a project selector on to be read as a name, and an
6092 /// empty vector is a project that holds nothing.
6093 async fn sub_issues(&self, id: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
6094 let mut after: Option<String> = None;
6095 let mut children = Vec::new();
6096 // The project issue as the first page carried it, held once the walk has ended.
6097 let mut parent: Option<Resolved> = None;
6098 loop {
6099 let asked = self
6100 .graphql(
6101 graphql::SUB_ISSUES,
6102 json!({"id":id.0,"memberFirst":MEMBER_PAGE_SIZE,"after":after,
6103 "nestedFirst":NESTED_PAGE_SIZE,
6104 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
6105 )
6106 .await;
6107 let data = match asked {
6108 Ok(data) => data,
6109 // A string that is not a node id at all is not a failure to report: it is
6110 // the ordinary answer to a selector naming a project by its name.
6111 Err(error) if unresolvable_node(&error) => return Ok(None),
6112 Err(error) => return Err(error),
6113 };
6114 let Some(connection) = data
6115 .pointer("/node/subIssues")
6116 .filter(|value| !value.is_null())
6117 else {
6118 // No such node, or one with no sub-issue relationship — a board draft is
6119 // the one this board can really hold.
6120 return Ok(None);
6121 };
6122 if after.is_none()
6123 && let Some(node) = data.get("node").filter(|node| node.get("id").is_some())
6124 {
6125 parent = self
6126 .resolve_issue(node)
6127 .await?
6128 .filter(|resolved| resolved.id == *id);
6129 }
6130 for node in connection
6131 .get("nodes")
6132 .and_then(Value::as_array)
6133 .ok_or_else(|| SourceError::Malformed {
6134 message: "GitHub subIssues.nodes is not an array".into(),
6135 })?
6136 {
6137 if let Some(resolved) = self.resolve_issue(node).await? {
6138 children.push(resolved);
6139 }
6140 }
6141 let info = connection
6142 .get("pageInfo")
6143 .ok_or_else(|| SourceError::Malformed {
6144 message: "GitHub subIssues connection has no pageInfo".into(),
6145 })?;
6146 let next = required_bool(info, "hasNextPage")?
6147 .then(|| required_str(info, "endCursor"))
6148 .transpose()?;
6149 match next {
6150 Some(next) => {
6151 validate_cursor_progress(after.as_deref(), next)?;
6152 after = Some(next.to_owned());
6153 }
6154 None => {
6155 // Held only once the walk has ended, so one failing part way holds
6156 // nothing and every read it would have answered is made.
6157 let mut carried = self.carried()?;
6158 for item in parent.into_iter().chain(children.iter().cloned()) {
6159 carried.insert(item.id.clone(), item);
6160 }
6161 return Ok(Some(children));
6162 }
6163 }
6164 }
6165 }
6166
6167 fn carried(
6168 &self,
6169 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
6170 self.carried.lock().map_err(|_| SourceError::Unavailable {
6171 message: "items a project's listing carried were left inconsistent; run the \
6172 command again"
6173 .into(),
6174 })
6175 }
6176
6177 /// Which issue of this board a project *name* is, or `None` when none is.
6178 ///
6179 /// One bounded query which filters on that name at the server, rather than a walk of
6180 /// every issue the board holds. The name is compared again here: the qualifier narrows
6181 /// what GitHub sends, and this source decides what it names.
6182 async fn project_by_name(&self, name: &str) -> Result<Option<NativeId>, SourceError> {
6183 let search = self.board_search(Some(&title_qualifier(name)));
6184 let mut after = None;
6185 loop {
6186 let (candidates, next) = self
6187 .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
6188 .await?;
6189 if let Some(item) = candidates.into_iter().find(|item| {
6190 item.kind == BoardKind::Work(ItemKind::Project)
6191 && item.title.eq_ignore_ascii_case(name)
6192 }) {
6193 return Ok(Some(item.id));
6194 }
6195 match next {
6196 Some(next) => after = Some(next),
6197 None => return Ok(None),
6198 }
6199 }
6200 }
6201
6202 /// Everything filed under one project of this board: the sub-issues of the issue that
6203 /// project is.
6204 ///
6205 /// Tasks *and* documents, because a document filed under a project is a sub-issue of it
6206 /// too — the caller keeps the kind it asked for. Nothing about this grows as the board
6207 /// gains projects, or as another project gains tasks.
6208 ///
6209 /// A qualified id names the issue and is asked for its sub-issues directly: one
6210 /// request, no search of any kind. Only a selector GitHub cannot resolve that way is
6211 /// read as a project *name*, which costs the one bounded search
6212 /// [`Self::project_by_name`] makes.
6213 ///
6214 /// What GitHub answered is held for the rest of the command — see [`Self::children_cache`]
6215 /// — and each answer is still cut to the items whose parent is this project, so one this
6216 /// process has since filed elsewhere is not reported here, and completed with what this
6217 /// process filed under it.
6218 async fn project_children(&self, selector: &NativeId) -> Result<Vec<Resolved>, SourceError> {
6219 let held = self.children_cache()?.get(selector).cloned();
6220 let (project, children) = match held {
6221 Some(held) => held,
6222 None => {
6223 let answered = match self.sub_issues(selector).await? {
6224 Some(children) => (selector.clone(), children),
6225 None => match self.project_by_name(&selector.0).await? {
6226 Some(project) => {
6227 let children = self.sub_issues(&project).await?.unwrap_or_default();
6228 (project, children)
6229 }
6230 None => return Ok(Vec::new()),
6231 },
6232 };
6233 self.children_cache()?
6234 .insert(selector.clone(), answered.clone());
6235 answered
6236 }
6237 };
6238 let mut children: Vec<Resolved> = children
6239 .into_iter()
6240 .filter(|child| child.parent.as_ref() == Some(&project))
6241 .collect();
6242 for own in self.updated()?.iter() {
6243 if own.parent.as_ref() == Some(&project) && !children.iter().any(|c| c.id == own.id) {
6244 children.push(own.clone());
6245 }
6246 }
6247 self.completed_with_written(children, |own| own.parent.as_ref() == Some(&project))
6248 }
6249
6250 /// Every issue of this board GitHub's issue search reports updated at or after `since`,
6251 /// completed with what this run wrote — the candidates a comment-activity read confirms.
6252 ///
6253 /// Scoped by the board and by nothing else: `project:<owner>/<number>` reaches every issue
6254 /// on the board whatever repository, and whatever owner, it lives in, so no repository or
6255 /// owner qualifier is added and none is needed. What makes the `updated:` qualifier
6256 /// sufficient is a fact about GitHub rather than about this source: a comment written on an
6257 /// issue **and a comment edited on it** both move that issue's `updatedAt`. The credentialed
6258 /// journey `an_edited_comment_moves_its_issue_and_is_selected_since` in `tests/journey`
6259 /// re-takes that fact on every run of the lane, so a change on GitHub's side fails there
6260 /// rather than silently narrowing a caller's answer.
6261 ///
6262 /// The instant is written to the second, rounded down, which can only widen what the
6263 /// search returns; confirmation against each candidate's own comments is what makes the
6264 /// answer exact. The search is an index that lags a write by a second or two — the module
6265 /// documentation records it — so a caller that asks again from its last instant should
6266 /// overlap the two by more than that.
6267 async fn updated_since(&self, since: DateTime<Utc>) -> Result<Vec<Resolved>, SourceError> {
6268 let found = self.searched(&updated_qualifier(since)).await?;
6269 self.completed_with_written(found, |_| true)
6270 }
6271
6272 /// Every issue of this board GitHub's issue search reports for the board-scoped search
6273 /// narrowed by `also`, in pages of [`SEARCH_PAGE_SIZE`].
6274 ///
6275 /// Uncompleted: what this process wrote is added by the caller, which knows whether its
6276 /// own record is the fresher of the two.
6277 async fn searched(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
6278 let search = self.board_search(Some(also));
6279 let mut after: Option<String> = None;
6280 let mut found = Vec::new();
6281 loop {
6282 let (page, next) = self
6283 .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
6284 .await?;
6285 found.extend(page);
6286 match next {
6287 Some(next) => after = Some(next),
6288 None => return Ok(found),
6289 }
6290 }
6291 }
6292
6293 /// A bounded task answer; the versioned cursor carries the connection position, how
6294 /// many rows of the page starting there were already handed out, and the own-write ids
6295 /// already observed, including across a new source instance.
6296 ///
6297 /// Every page is sent at [`SEARCH_PAGE_SIZE`] whatever the caller's limit, and a limit is
6298 /// sliced from the pages it needs; why is the module documentation's paging contract.
6299 async fn search_tasks(
6300 &self,
6301 query: &TaskQuery,
6302 page: &PageRequest,
6303 also: &str,
6304 ) -> Result<Page<Task>, SourceError> {
6305 let mut position = match &page.cursor {
6306 None => SearchPosition::default(),
6307 Some(cursor) => serde_json::from_str::<SearchPosition>(&cursor.0)
6308 .ok()
6309 .filter(|position| {
6310 position.version == SEARCH_CURSOR_VERSION
6311 && position.connection.valid_resume(position.offset)
6312 })
6313 .ok_or_else(|| SourceError::Config {
6314 message: "page cursor is invalid".into(),
6315 })?,
6316 };
6317 let search = self.board_search(Some(also));
6318 let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
6319 let own = self.with_own_writes(Vec::new())?;
6320 // An issue this process commented on is a candidate of a comment-activity read
6321 // whether or not the search has caught up with the comment; see `Self::commented`.
6322 let commented = match query.commented_since {
6323 Some(_) => self.commented()?.clone(),
6324 None => Vec::new(),
6325 };
6326 for id in own.iter().map(|item| &item.id).chain(&commented) {
6327 if !position.own.contains(id) {
6328 position.own.push(id.clone());
6329 }
6330 }
6331 let mut tasks = Vec::new();
6332 while !position.connection.exhausted() && tasks.len() < limit {
6333 let first = SEARCH_PAGE_SIZE;
6334 // Page size is part of the key: a short cached answer cannot answer a wider ask.
6335 let key =
6336 serde_json::to_string(&("page", &search, &position.connection.after(), first))
6337 .expect("search page key is serializable");
6338 let cached = if query.commented_since.is_none() {
6339 self.narrowed_cache()?.get(&key).cloned()
6340 } else {
6341 None
6342 };
6343 let (found, next) = match cached {
6344 Some(found) => {
6345 let next = self
6346 .search_next
6347 .lock()
6348 .map_err(|_| SourceError::Unavailable {
6349 message:
6350 "search pagination was left inconsistent; run the command again"
6351 .into(),
6352 })?
6353 .get(&key)
6354 .cloned()
6355 .flatten();
6356 (found, next)
6357 }
6358 None => {
6359 let (found, next) = self
6360 .search_page(&search, first, position.connection.after())
6361 .await?;
6362 if query.commented_since.is_none() {
6363 self.search_next
6364 .lock()
6365 .map_err(|_| SourceError::Unavailable {
6366 message:
6367 "search pagination was left inconsistent; run the command again"
6368 .into(),
6369 })?
6370 .insert(key.clone(), next.clone());
6371 self.narrowed_cache()?.insert(key, found.clone());
6372 }
6373 (found, next)
6374 }
6375 };
6376 let rows = found.len();
6377 for mut item in found.into_iter().skip(position.offset) {
6378 if tasks.len() == limit {
6379 break;
6380 }
6381 position.offset += 1;
6382 if position.own.contains(&item.id) {
6383 if position.seen.contains(&item.id) {
6384 continue;
6385 }
6386 position.seen.push(item.id.clone());
6387 // The search's own copy of an issue this process only commented on is as
6388 // good as a node read of it, since its comments are read either way.
6389 let only_commented = commented.contains(&item.id)
6390 && !own.iter().any(|written| written.id == item.id);
6391 if !only_commented {
6392 let updated_at = item.updated_at;
6393 let Some(written) = self.search_written(&own, &item.id).await? else {
6394 continue;
6395 };
6396 item = written;
6397 item.updated_at = item.updated_at.max(updated_at);
6398 self.resolved_cache()?.insert(item.id.clone(), item.clone());
6399 }
6400 }
6401 if item.kind == BoardKind::Work(ItemKind::Task) {
6402 let task = item.task()?;
6403 if task_matches(&task, query, &query.project)
6404 && self.commented_since(&item, query.commented_since).await?
6405 {
6406 tasks.push(task);
6407 }
6408 }
6409 }
6410 if position.offset < rows {
6411 continue;
6412 }
6413 position.offset = 0;
6414 position.connection = match next {
6415 Some(after) => SearchConnection::Continuing {
6416 after: Cursor(after),
6417 },
6418 None => SearchConnection::Exhausted {},
6419 };
6420 }
6421 if position.connection.exhausted() {
6422 for id in position.own.clone() {
6423 if position.seen.contains(&id) {
6424 continue;
6425 }
6426 if tasks.len() == limit {
6427 break;
6428 }
6429 position.seen.push(id.clone());
6430 let Some(item) = self.search_written(&own, &id).await? else {
6431 continue;
6432 };
6433 if item.kind == BoardKind::Work(ItemKind::Task) {
6434 let task = item.task()?;
6435 if task_matches(&task, query, &query.project)
6436 && self.commented_since(&item, query.commented_since).await?
6437 {
6438 tasks.push(task);
6439 }
6440 }
6441 }
6442 }
6443 let more = !position.connection.exhausted()
6444 || position.own.iter().any(|id| !position.seen.contains(id));
6445 Ok(Page {
6446 items: tasks,
6447 next: more.then(|| {
6448 Cursor(serde_json::to_string(&position).expect("search position is serializable"))
6449 }),
6450 })
6451 }
6452
6453 /// A resumed process has the ids but no write records; resolve only a record the
6454 /// current page needs, by its uncached node read rather than the lagging search index.
6455 async fn search_written(
6456 &self,
6457 own: &[Resolved],
6458 id: &NativeId,
6459 ) -> Result<Option<Resolved>, SourceError> {
6460 match own.iter().find(|item| item.id == *id) {
6461 Some(item) => Ok(Some(item.clone())),
6462 None => self.item_by_id(id).await,
6463 }
6464 }
6465
6466 /// The candidates for a task query carrying a text, metadata or origin predicate, read
6467 /// without enumerating the board — or `None` for a query carrying none of the three, which
6468 /// keeps the reads it always had.
6469 ///
6470 /// An origin is answered by [`Self::origin_candidates`], whatever else the query carries,
6471 /// because it names at most a handful of items. Text and metadata are answered by one
6472 /// board-scoped issue search carrying every term — see [`narrowing_qualifiers`] — narrowed
6473 /// further by `updated:>=` when the query also asks for comment activity, since both
6474 /// qualifiers must hold of an issue the answer keeps. Every candidate is confirmed in
6475 /// process afterwards by the same predicates [`task_matches`] applies to every read.
6476 ///
6477 /// Completed with what this process wrote, its own record winning over the index's copy
6478 /// of the same item: see [`Self::with_own_writes`].
6479 async fn narrowed(&self, query: &TaskQuery) -> Result<Option<Vec<Resolved>>, SourceError> {
6480 let asked = match (&query.origin, narrowing_qualifiers(query)) {
6481 (Some(origin), _) => Narrowing::Origin(origin.clone()),
6482 (None, Some(qualifiers)) => Narrowing::Search(match query.commented_since {
6483 Some(since) => format!("{} {qualifiers}", updated_qualifier(since)),
6484 None => qualifiers,
6485 }),
6486 (None, None) => return Ok(None),
6487 };
6488 // A question about comment activity is asked afresh every time, as it always was: it
6489 // is the one a caller polls from one source while waiting for the index, and an
6490 // answer held from the first poll would be the answer to every later one.
6491 let key = query.commented_since.is_none().then(|| asked.key());
6492 let cached = match &key {
6493 Some(key) => self.narrowed_cache()?.get(key).cloned(),
6494 None => None,
6495 };
6496 let found = match cached {
6497 Some(found) => found,
6498 None => {
6499 let found = match &asked {
6500 Narrowing::Origin(origin) => self.origin_candidates(origin).await?,
6501 Narrowing::Search(also) => self.searched(also).await?,
6502 };
6503 if let Some(key) = key {
6504 self.narrowed_cache()?.insert(key, found.clone());
6505 }
6506 found
6507 }
6508 };
6509 self.with_own_writes(found).map(Some)
6510 }
6511
6512 /// The candidates for a project or unscoped document query carrying a searchable text,
6513 /// read without enumerating the board — or `None` for a query with no text or a blank one,
6514 /// which keeps the read it always had.
6515 ///
6516 /// The text is sent as the very phrase a task query's text is — see [`text_qualifiers`] —
6517 /// in one board-scoped issue search walked to its end at [`SEARCH_PAGE_SIZE`], so what it
6518 /// costs is the issues that match and never the board. Its answer is held for the command
6519 /// under the same key [`Self::narrowed`] holds that search under, so a walk of the caller's
6520 /// pages asks GitHub once. Every candidate is confirmed afterwards by its kind and by the
6521 /// substring rule, exactly as an item of the wider read was, and is completed with what this
6522 /// process wrote: see [`Self::with_own_writes`].
6523 async fn text_searched(
6524 &self,
6525 text: Option<&TextQuery>,
6526 ) -> Result<Option<Vec<Resolved>>, SourceError> {
6527 let Some(also) = text_qualifiers(text) else {
6528 return Ok(None);
6529 };
6530 let key = Narrowing::Search(also.clone()).key();
6531 let cached = self.narrowed_cache()?.get(&key).cloned();
6532 let found = match cached {
6533 Some(found) => found,
6534 None => {
6535 let found = self.searched(&also).await?;
6536 self.narrowed_cache()?.insert(key, found.clone());
6537 found
6538 }
6539 };
6540 self.with_own_writes(found).map(Some)
6541 }
6542
6543 /// Every `kind` item of this board whose own origin is exactly `origin`: the candidates
6544 /// [`Self::narrowed`] reads for a task query carrying that origin — one
6545 /// [`graphql::ORIGIN_LOOKUP`] walk, held for the command under the same key, completed with
6546 /// what this process wrote — each confirmed against its own origin entry.
6547 ///
6548 /// What answers a project or document listing by origin, so finding every copy of one plan
6549 /// costs the items that carry its origin and never a page of the board.
6550 async fn copied_from(
6551 &self,
6552 origin: &str,
6553 kind: BoardKind,
6554 ) -> Result<Vec<Resolved>, SourceError> {
6555 let wanted = TaskQuery {
6556 origin: Some(origin.to_owned()),
6557 ..TaskQuery::default()
6558 };
6559 Ok(self
6560 .narrowed(&wanted)
6561 .await?
6562 .unwrap_or_default()
6563 .into_iter()
6564 .filter(|item| item.kind == kind && wanted.origin_matches(&item.metadata()))
6565 .collect())
6566 }
6567
6568 /// Every item of this board that may carry `origin` — a superset of those that do — found
6569 /// by [`graphql::ORIGIN_LOOKUP`] and never by enumerating the board.
6570 ///
6571 /// The union of the board's own field filter over the `onetaskgraph.origin` text field —
6572 /// which reads the field every carrier holds, whichever release wrote it — and the
6573 /// board-scoped issue search for the same id as a phrase in the body, where this source
6574 /// mirrors it. The caller adds the third read, this process's own writes. Candidates are
6575 /// returned unconfirmed; [`task_matches`] compares each one's own origin field with the
6576 /// query's, exactly.
6577 ///
6578 /// Both connections are walked to exhaustion, each from its own cursor. One that has
6579 /// already ended is sent its last cursor again, which answers an empty page, so the one
6580 /// document serves every page of either. What the two leave is stated in the module
6581 /// documentation: a carrier another process added within the last second or two, before
6582 /// either index has it.
6583 async fn origin_candidates(&self, origin: &str) -> Result<Vec<Resolved>, SourceError> {
6584 let filter = format!("{ORIGIN_FIELD}:{}", quoted(origin));
6585 let search = self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))));
6586 let mut items_after: Option<String> = None;
6587 let mut search_after: Option<String> = None;
6588 let mut found: Vec<Resolved> = Vec::new();
6589 let keep = |resolved: Resolved, found: &mut Vec<Resolved>| {
6590 if !found.iter().any(|held| held.id == resolved.id) {
6591 found.push(resolved);
6592 }
6593 };
6594 loop {
6595 let data = self
6596 .graphql(
6597 graphql::ORIGIN_LOOKUP,
6598 json!({"owner":self.owner,"number":self.project_number,"filter":filter,
6599 "search":search,"type":"ISSUE","originFirst":ORIGIN_PAGE_SIZE,
6600 "itemsAfter":items_after,"searchAfter":search_after,
6601 "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
6602 "duplicates":true}),
6603 )
6604 .await?;
6605 let items = data
6606 .pointer("/originItems/projectV2/items")
6607 .filter(|value| !value.is_null())
6608 .ok_or_else(|| SourceError::Refused {
6609 message: format!(
6610 "GitHub project {}/{} was not found or is not visible to the token",
6611 self.owner, self.project_number
6612 ),
6613 })?;
6614 for item in optional_nodes(Some(items), "project items")?
6615 .into_iter()
6616 .flatten()
6617 {
6618 // The board's own items list its drafts too, and a draft is not an issue: no
6619 // narrowed read answers with one, whatever its origin field holds.
6620 if let Some(resolved) = self.resolve(item)?
6621 && resolved.content_kind == ContentKind::Issue
6622 {
6623 keep(resolved, &mut found);
6624 }
6625 }
6626 let searched = data.get("search").ok_or_else(|| SourceError::Malformed {
6627 message: "GitHub search response has no search connection".into(),
6628 })?;
6629 for node in optional_nodes(Some(searched), "search")?
6630 .into_iter()
6631 .flatten()
6632 {
6633 if let Some(resolved) = self.resolve_issue(node).await? {
6634 keep(resolved, &mut found);
6635 }
6636 }
6637 let items_next = resumed(items, items_after.as_deref())?;
6638 let search_next = resumed(searched, search_after.as_deref())?;
6639 if !items_next.has_more() && !search_next.has_more() {
6640 return Ok(found);
6641 }
6642 items_after = items_next.cursor();
6643 search_after = search_next.cursor();
6644 }
6645 }
6646
6647 /// `found`, with every item this process created or wrote in its place, and every one of
6648 /// them the read did not report added.
6649 ///
6650 /// This process's own record wins over the read's copy of the same item, because a read
6651 /// of an item written moments ago can still be behind what was written onto it — the
6652 /// origin field included, which is the one a narrowed read is confirmed against — and a
6653 /// read that still names an item under a predicate this process's write moved it out of
6654 /// must not return it. The one thing the read knows that the record cannot is when GitHub
6655 /// last saw the item change, which is what a comment-activity read rules a candidate out
6656 /// by, so the read's `updatedAt` is kept when the record has none of its own. See
6657 /// [`Self::created`] and [`Self::updated`](GitHubProjectsSource::updated).
6658 fn with_own_writes(&self, mut found: Vec<Resolved>) -> Result<Vec<Resolved>, SourceError> {
6659 // A board draft is not an issue, so no narrowed read returns one, and this process
6660 // having written one does not make it an answer either.
6661 let own: Vec<Resolved> = self
6662 .created()?
6663 .iter()
6664 .chain(self.updated()?.iter())
6665 .filter(|own| own.content_kind == ContentKind::Issue)
6666 .cloned()
6667 .collect();
6668 for mut own in own {
6669 self.resolved_cache()?.insert(own.id.clone(), own.clone());
6670 match found.iter_mut().find(|read| read.id == own.id) {
6671 Some(read) => {
6672 own.updated_at = own.updated_at.max(read.updated_at);
6673 *read = own;
6674 }
6675 None => found.push(own),
6676 }
6677 }
6678 Ok(found)
6679 }
6680
6681 /// Whether `item` has a comment created or last edited at or after `since` — always, when
6682 /// there is no instant to hold it to.
6683 ///
6684 /// The candidate's own `updatedAt` is read first, because a comment written or edited at
6685 /// or after the instant moved it there: an issue not updated since holds no such comment,
6686 /// and its comments are never asked for — unless this process commented on it in this
6687 /// command, when the `updatedAt` held may predate that comment; see [`Self::commented`]. Otherwise its comments are walked, oldest first,
6688 /// only as far as the first that matches. A board draft is not an issue and has no
6689 /// comments, so it never matches.
6690 async fn commented_since(
6691 &self,
6692 item: &Resolved,
6693 since: Option<DateTime<Utc>>,
6694 ) -> Result<bool, SourceError> {
6695 let Some(since) = since else {
6696 return Ok(true);
6697 };
6698 if item.content_kind == ContentKind::DraftIssue {
6699 return Ok(false);
6700 }
6701 // An `updatedAt` this process's own record or a lagging index holds can predate a
6702 // comment this process wrote since, so only an issue it did not comment on is ruled
6703 // out by one.
6704 if item.updated_at.is_some_and(|updated| updated < since)
6705 && !self.commented()?.contains(&item.id)
6706 {
6707 return Ok(false);
6708 }
6709 let query = TaskQuery {
6710 commented_since: Some(since),
6711 ..TaskQuery::default()
6712 };
6713 let mut after: Option<String> = None;
6714 loop {
6715 let data = self
6716 .graphql(
6717 graphql::ISSUE_COMMENTS,
6718 json!({"id":item.id.0,"first":MAX_PAGE_SIZE,"after":after}),
6719 )
6720 .await?;
6721 let Some(connection) = data
6722 .get("node")
6723 .filter(|value| !value.is_null())
6724 .and_then(|node| node.get("comments"))
6725 .filter(|value| !value.is_null())
6726 else {
6727 // Removed since the search reported it: no longer an issue with comments.
6728 return Ok(false);
6729 };
6730 let comments = optional_nodes(Some(connection), "issue comments")?
6731 .into_iter()
6732 .flatten()
6733 .map(comment_from)
6734 .collect::<Result<Vec<_>, _>>()?;
6735 if query.comments_match(&comments) {
6736 return Ok(true);
6737 }
6738 match next_cursor(connection)? {
6739 Some(next) => {
6740 validate_cursor_progress(after.as_deref(), &next.0)?;
6741 after = Some(next.0);
6742 }
6743 None => return Ok(false),
6744 }
6745 }
6746 }
6747
6748 /// Every item on the board: the union of both enumerations GitHub offers of one.
6749 ///
6750 /// Neither contains the other, so neither is dropped — only `ProjectV2.items` lists a
6751 /// board **draft** and reads the board's own fields beside its items, and only the search
6752 /// reports an item that connection is behind on. The module documentation is where the lag and the
6753 /// measurements behind it are written down.
6754 ///
6755 /// A search result is admitted on the same terms as any other issue this source reaches
6756 /// directly — [`Self::resolve_issue`] keeps it only if that issue's own `projectItems`
6757 /// names *this* board — so an issue the index still believes is here after it was taken
6758 /// off is refused rather than reported.
6759 ///
6760 /// See [`Self::board_cache`]. Both completions happen on every call rather than once,
6761 /// which is what the cache could otherwise have broken.
6762 async fn board(&self) -> Result<Board, SourceError> {
6763 self.board_completed_by(None).await
6764 }
6765
6766 /// [`Self::board`], its search half narrowed by `also` when it is given — which an issue
6767 /// that half could add is then answered only if it holds.
6768 async fn board_completed_by(&self, also: Option<&str>) -> Result<Board, SourceError> {
6769 let cached = self.board_cache()?.clone();
6770 let mut board = match cached {
6771 Some(board) => board,
6772 None => {
6773 let read = self.read_board().await?;
6774 *self.board_cache()? = Some(read.clone());
6775 read
6776 }
6777 };
6778 let searched = match also {
6779 None => self.searched_issues().await?,
6780 Some(also) => self.searched_narrowly(also).await?,
6781 };
6782 for held in searched {
6783 if !board.items.iter().any(|item| item.id == held.id) {
6784 board.items.push(held);
6785 }
6786 }
6787 for own in self.created()?.iter() {
6788 if !board.items.iter().any(|item| item.id == own.id) {
6789 board.items.push(own.clone());
6790 }
6791 }
6792 Ok(board)
6793 }
6794
6795 /// This process's own view of the board, or the refusal a poisoned lock is.
6796 fn board_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<Board>>, SourceError> {
6797 self.board_cache
6798 .lock()
6799 .map_err(|_| SourceError::Unavailable {
6800 message: "this source's view of the board was left inconsistent by an earlier \
6801 failure; next: run the command again"
6802 .into(),
6803 })
6804 }
6805
6806 /// Bring this process's own view of the board up to an item it has just written.
6807 ///
6808 /// A created item goes to `created`, which is what completes a board read GitHub's own
6809 /// eventual consistency has left behind. An item that was already there is replaced
6810 /// where it sits, so a second write of it in the same command reads its real parent
6811 /// rather than the one it had before the first write.
6812 ///
6813 /// "Where it sits" is three places, and missing an earlier one leaves a stale record
6814 /// that wins: an item this same run created is held in `created` and not in the cached
6815 /// board, and `board` completes the cached board *from* `created`, so replacing only
6816 /// the cached copy of such an item replaces nothing and the read still reports the
6817 /// title it was created with. The search is the third, and it is the one an item the
6818 /// board's own projection is behind on sits in *alone* — which is exactly the item this
6819 /// source is least able to re-read, so leaving it out would put the stale title back on
6820 /// the only items the completion in [`Self::board`] exists for.
6821 fn remember_written(&self, item: Resolved, created: bool) -> Result<(), SourceError> {
6822 self.resolved_cache()?.insert(item.id.clone(), item.clone());
6823 if created {
6824 self.created()?.push(item);
6825 return Ok(());
6826 }
6827 {
6828 let mut own = self.created()?;
6829 if let Some(held) = own.iter_mut().find(|held| held.id == item.id) {
6830 *held = item;
6831 return Ok(());
6832 }
6833 }
6834 {
6835 let mut own = self.updated()?;
6836 match own.iter_mut().find(|held| held.id == item.id) {
6837 Some(held) => *held = item.clone(),
6838 None => own.push(item.clone()),
6839 }
6840 }
6841 if let Some(board) = self.board_cache()?.as_mut()
6842 && let Some(held) = board.items.iter_mut().find(|held| held.id == item.id)
6843 {
6844 *held = item.clone();
6845 }
6846 if let Some(found) = self.search_cache()?.as_mut()
6847 && let Some(held) = found.iter_mut().find(|held| held.id == item.id)
6848 {
6849 *held = item.clone();
6850 }
6851 for found in self.narrowed_cache()?.values_mut() {
6852 if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
6853 *held = item.clone();
6854 }
6855 }
6856 for (_, found) in self.children_cache()?.values_mut() {
6857 if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
6858 *held = item.clone();
6859 }
6860 }
6861 Ok(())
6862 }
6863
6864 /// Forget one item this process has just deleted, from every half of its own view.
6865 fn forget(&self, id: &NativeId) -> Result<(), SourceError> {
6866 if let Some(Deferred::Held { created, .. }) = self.deferred()?.as_mut() {
6867 created.retain(|held| held.content != *id);
6868 }
6869 self.resolved_cache()?.remove(id);
6870 self.read_ahead()?.remove(id);
6871 self.carried()?.remove(id);
6872 self.created()?.retain(|own| own.id != *id);
6873 self.updated()?.retain(|own| own.id != *id);
6874 self.commented()?.retain(|own| own != id);
6875 if let Some(board) = self.board_cache()?.as_mut() {
6876 board.items.retain(|item| item.id != *id);
6877 }
6878 if let Some(found) = self.search_cache()?.as_mut() {
6879 found.retain(|item| item.id != *id);
6880 }
6881 for found in self.narrowed_cache()?.values_mut() {
6882 found.retain(|item| item.id != *id);
6883 }
6884 for (_, found) in self.children_cache()?.values_mut() {
6885 found.retain(|item| item.id != *id);
6886 }
6887 Ok(())
6888 }
6889
6890 /// This process's own record of each narrowed answer, or the refusal a poisoned lock is.
6891 fn narrowed_cache(
6892 &self,
6893 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<String, Vec<Resolved>>>, SourceError> {
6894 self.narrowed_cache
6895 .lock()
6896 .map_err(|_| SourceError::Unavailable {
6897 message: "this source's view of a narrowed read was left inconsistent by an \
6898 earlier failure; next: run the command again"
6899 .into(),
6900 })
6901 }
6902
6903 /// This process's own record of each project's sub-issues, or the refusal a poisoned lock
6904 /// is.
6905 /// The tasks `project` holds, as a copy's batched read found them this command, when it did.
6906 fn held_task_children(&self, project: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
6907 Ok(self.task_children()?.get(project).cloned())
6908 }
6909
6910 fn task_children(
6911 &self,
6912 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Vec<Resolved>>>, SourceError> {
6913 self.task_children
6914 .lock()
6915 .map_err(|_| SourceError::Unavailable {
6916 message: "this source's record of a project's tasks was left inconsistent by an \
6917 earlier failure; next: run the command again"
6918 .into(),
6919 })
6920 }
6921
6922 fn children_cache(&self) -> Result<std::sync::MutexGuard<'_, ProjectChildren>, SourceError> {
6923 self.children_cache
6924 .lock()
6925 .map_err(|_| SourceError::Unavailable {
6926 message: "this source's view of a project's tasks was left inconsistent by an \
6927 earlier failure; next: run the command again"
6928 .into(),
6929 })
6930 }
6931
6932 /// Every page of the board, read from GitHub.
6933 async fn read_board(&self) -> Result<Board, SourceError> {
6934 let mut after: Option<String> = None;
6935 let mut items = Vec::new();
6936 let mut board;
6937 loop {
6938 let page = self.board_page(after.as_deref(), MAX_PAGE_SIZE).await?;
6939 for item in page
6940 .pointer("/items/nodes")
6941 .and_then(Value::as_array)
6942 .ok_or_else(|| SourceError::Malformed {
6943 message: "GitHub project items.nodes is not an array".into(),
6944 })?
6945 {
6946 if let Some(resolved) = self.resolve(item)? {
6947 items.push(resolved);
6948 }
6949 }
6950 let info = page
6951 .pointer("/items/pageInfo")
6952 .ok_or_else(|| SourceError::Malformed {
6953 message: "GitHub project items have no pageInfo".into(),
6954 })?;
6955 let has_next = required_bool(info, "hasNextPage")?;
6956 let next = has_next
6957 .then(|| required_str(info, "endCursor"))
6958 .transpose()?;
6959 board = page.clone();
6960 match next {
6961 Some(next) => {
6962 validate_cursor_progress(after.as_deref(), next)?;
6963 after = Some(next.to_owned());
6964 }
6965 None => break,
6966 }
6967 }
6968 Ok(Board {
6969 id: required_str(&board, "id")?.to_owned(),
6970 fields: board.get("fields").cloned().unwrap_or(Value::Null),
6971 items,
6972 })
6973 }
6974
6975 /// The existing items this source has written, for completing a narrowed read that is
6976 /// behind; see [`Self::updated`](GitHubProjectsSource::updated).
6977 fn updated(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
6978 self.updated.lock().map_err(|_| SourceError::Unavailable {
6979 message: "this source's record of what it wrote in this run was left inconsistent \
6980 by an earlier failure; next: run the command again"
6981 .into(),
6982 })
6983 }
6984
6985 /// The issues this source has commented on in this command; see
6986 /// [`Self::commented`](GitHubProjectsSource::commented).
6987 fn commented(&self) -> Result<std::sync::MutexGuard<'_, Vec<NativeId>>, SourceError> {
6988 self.commented.lock().map_err(|_| SourceError::Unavailable {
6989 message: "this source's record of what it commented on in this run was left \
6990 inconsistent by an earlier failure; next: run the command again"
6991 .into(),
6992 })
6993 }
6994
6995 /// Called only once GitHub has answered the comment write, so an issue whose comment
6996 /// failed is never made a candidate a later read would pay a node read for.
6997 fn remember_commented(&self, issue: &NativeId) -> Result<(), SourceError> {
6998 let mut commented = self.commented()?;
6999 if !commented.contains(issue) {
7000 commented.push(issue.clone());
7001 }
7002 Ok(())
7003 }
7004
7005 /// The items this source has created, for completing a board read that is behind.
7006 fn created(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
7007 self.created.lock().map_err(|_| SourceError::Unavailable {
7008 message: "this source's record of what it created in this run was left \
7009 inconsistent by an earlier failure; next: run the command again"
7010 .into(),
7011 })
7012 }
7013
7014 /// One board item as this source reports it, or `None` for content it ignores.
7015 ///
7016 /// A pull request is neither a project nor a task — it is somebody's change, not a
7017 /// unit of plan — and an item whose content the token cannot see has nothing to
7018 /// report at all.
7019 fn resolve(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
7020 let resolved = self.resolve_unremembered(item)?;
7021 if let Some(resolved) = &resolved {
7022 self.resolved_cache()?
7023 .insert(resolved.id.clone(), resolved.clone());
7024 }
7025 Ok(resolved)
7026 }
7027
7028 /// [`Self::resolve`], without remembering the item it resolves: what reading a token off a
7029 /// write's own response needs, which says nothing this process should answer a later read
7030 /// with.
7031 fn resolve_unremembered(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
7032 let content = item.get("content").ok_or_else(|| SourceError::Malformed {
7033 message: "GitHub project item is missing content".into(),
7034 })?;
7035 if content.is_null() {
7036 return Ok(None);
7037 }
7038 let content_kind = match required_str(content, "__typename")? {
7039 "Issue" => ContentKind::Issue,
7040 "DraftIssue" => ContentKind::DraftIssue,
7041 _ => return Ok(None),
7042 };
7043 let field_values = item
7044 .get("fieldValues")
7045 .ok_or_else(|| SourceError::Malformed {
7046 message: "GitHub project item is missing fieldValues".into(),
7047 })?;
7048 complete_connection(field_values, "project item field values", NESTED_PAGE_SIZE)?;
7049 let nodes = field_values
7050 .get("nodes")
7051 .and_then(Value::as_array)
7052 .ok_or_else(|| SourceError::Malformed {
7053 message: "GitHub project item fieldValues.nodes is not an array".into(),
7054 })?;
7055 if let Some(labels) = content.get("labels") {
7056 complete_connection(labels, "content labels", NESTED_PAGE_SIZE)?;
7057 }
7058 let raw_body = optional_str(content, "body")?.map(str::to_owned);
7059 let (body, slot) = metadata_body(raw_body.clone())?;
7060 let parent = optional_str(content.get("parent").unwrap_or(&Value::Null), "id")?
7061 .map(|id| NativeId(id.to_owned()));
7062 // A draft has no sub-issues to summarise, and GitHub's schema gives it no field
7063 // to read one from; it is a task, and never a project.
7064 let sub_issues = match content_kind {
7065 ContentKind::Issue => sub_issue_total(content)?,
7066 ContentKind::DraftIssue => 0,
7067 };
7068 let content_id = required_str(content, "id")?;
7069 let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
7070 message: format!("GitHub issue {content_id}: {message}"),
7071 })?;
7072 let raw_title = required_str(content, "title")?;
7073 let kind = BoardKind::of(raw_title, parent.is_some(), sub_issues, marked);
7074 // The title a person wrote, which for a document is the one without the prefix —
7075 // the same way `content` above is the body without this source's metadata slot.
7076 let title = match kind {
7077 BoardKind::Document => raw_title[DESIGN_TITLE_PREFIX.len()..].to_owned(),
7078 BoardKind::Work(_) => raw_title.to_owned(),
7079 };
7080 let own_repository = content
7081 .pointer("/repository/nameWithOwner")
7082 .and_then(Value::as_str)
7083 .map(|origin| Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST)))
7084 .transpose()
7085 .map_err(|message| SourceError::Malformed { message })?;
7086 let repositories = if slot.contains_key(Repository::METADATA_KEY) {
7087 Repository::from_metadata(&slot)
7088 .map_err(|message| SourceError::Malformed { message })?
7089 } else {
7090 own_repository.clone().into_iter().collect()
7091 };
7092 let classification = Classification::from_metadata(&slot)
7093 .map_err(|message| SourceError::Malformed { message })?;
7094 let id = NativeId(content_id.to_owned());
7095 // Read only for a task, because only a task has either list: a project or a
7096 // document holding one of these keys holds nothing this source reports, and the
7097 // keys are left out of its caller-visible metadata all the same.
7098 let (delivers, delivered_by) = if kind == BoardKind::Work(ItemKind::Task) {
7099 let listed = |key: &str| {
7100 TaskRef::from_value(key, &id, Some(&self.name), slot.get(key))
7101 .map_err(|message| SourceError::Malformed { message })
7102 };
7103 (
7104 listed(TaskRef::DELIVERS_KEY)?,
7105 listed(TaskRef::DELIVERED_BY_KEY)?,
7106 )
7107 } else {
7108 (Vec::new(), Vec::new())
7109 };
7110 let (option, closed, reason) = Self::status_parts(nodes, content)?;
7111 let priority = self.held_priority(nodes)?;
7112 let item_labels = labels(content)?;
7113 // Present when the item was reached through its own issue, whose board entry
7114 // names the board; a read of the board's own items has the board already. An
7115 // empty id names nothing a field write could address, so it is read as absent and
7116 // the write goes back to reading the board.
7117 let board_id = item
7118 .pointer("/project/id")
7119 .and_then(Value::as_str)
7120 .filter(|id| !id.is_empty());
7121 let resolved = Resolved {
7122 item_id: required_str(item, "id")?.to_owned(),
7123 id,
7124 content_kind,
7125 kind,
7126 title,
7127 body: body.filter(|value| !value.is_empty()),
7128 raw_body,
7129 status: self
7130 .statuses
7131 .status(kind.status_kind(), option, closed, reason),
7132 option: option.map(str::to_owned),
7133 priority,
7134 closed,
7135 reason: closed.then(|| reason.map(str::to_owned)).flatten(),
7136 delivers,
7137 delivered_by,
7138 labels: item_labels.clone(),
7139 parent,
7140 origin: text_field(nodes, ORIGIN_FIELD)?.filter(|value| !value.is_empty()),
7141 projected: self.held_projections(nodes)?,
7142 number: match content_kind {
7143 ContentKind::Issue => Some(issue_number(content)?),
7144 // A draft is filed in no repository, so nothing ever numbered it:
7145 // `DraftIssue` declares no `number` at all, exactly as it declares no
7146 // `subIssuesSummary` the branch above reads.
7147 ContentKind::DraftIssue => None,
7148 },
7149 url: optional_str(content, "url")?.map(str::to_owned),
7150 created_at: optional_time(content, "createdAt")?,
7151 updated_at: optional_time(content, "updatedAt")?,
7152 item_updated_at: optional_time(item, "updatedAt")?,
7153 comment_count: content
7154 .pointer("/commentCount/totalCount")
7155 .and_then(Value::as_u64),
7156 relationship_events: content
7157 .pointer("/relationshipEvents/totalCount")
7158 .and_then(Value::as_u64),
7159 // The issue node is stamped wherever it was read; a board item a read of the issue
7160 // put together from its memberships is not.
7161 served_at: match optional_time(content, SERVED_AT)? {
7162 Some(served) => Some(served),
7163 None => optional_time(item, SERVED_AT)?,
7164 },
7165 // Both connections were read to their end above — one reporting a further page is
7166 // refused — so these are every field value and every label the item holds. A
7167 // response that did not select the labels at all says nothing of them, and gives
7168 // no facets.
7169 facets: content.get("labels").is_some().then(|| {
7170 change_token::Facets::new(kind.facet(), facet_fields(nodes), &item_labels).digest()
7171 }),
7172 own_repository,
7173 repositories,
7174 classification,
7175 slot,
7176 board_id: board_id.map(str::to_owned),
7177 fields: field_definitions(nodes),
7178 board_fields: Self::carried_board_fields(content, board_id)?,
7179 blocked_by: carried_blocked_by(content)?,
7180 };
7181 Ok(Some(resolved))
7182 }
7183
7184 /// The field definitions of the board `board_id` names — the project this issue's own
7185 /// board item is on — off the `boards` page a read of an issue by its own id carries, or
7186 /// `None` when the read carried none, carried no entry for that board, or the board item
7187 /// named no board, which a write then answers by reading the board's fields itself.
7188 ///
7189 /// Matched by the board's node id and never by its number alone: a project number is
7190 /// unique only within its owner, so another owner's board numbered alike can sit on the
7191 /// same page, and its field and option ids address nothing on this one.
7192 fn carried_board_fields(
7193 content: &Value,
7194 board_id: Option<&str>,
7195 ) -> Result<Option<Value>, SourceError> {
7196 let (Some(nodes), Some(board_id)) = (
7197 content.pointer("/boards/nodes").and_then(Value::as_array),
7198 board_id,
7199 ) else {
7200 return Ok(None);
7201 };
7202 let Some(board) = nodes.iter().find_map(|node| {
7203 let project = node.get("project")?;
7204 (project.get("id").and_then(Value::as_str) == Some(board_id)).then_some(project)
7205 }) else {
7206 return Ok(None);
7207 };
7208 let Some(fields) = board.get("fields").filter(|fields| !fields.is_null()) else {
7209 return Ok(None);
7210 };
7211 complete_connection(fields, "board fields", NESTED_PAGE_SIZE)?;
7212 Ok(Some(fields.clone()))
7213 }
7214
7215 /// What one board item's `Priority` field says, through this instance's mapping.
7216 ///
7217 /// An instance with no mapping holds no priority, so every item reads as `none` whatever
7218 /// its board holds. With one, no value is `none`, a mapped option is its level, and an
7219 /// option the mapping does not name is kept as itself — never read as a level or as
7220 /// `none` — for a read of the task to report by name.
7221 fn held_priority(&self, field_values: &[Value]) -> Result<HeldPriority, SourceError> {
7222 let Some(mapping) = &self.priorities else {
7223 return Ok(HeldPriority::Read(Priority::None));
7224 };
7225 // A value of the field that names no option — a text field someone called `Priority` —
7226 // is malformed rather than `none`: reading it as no priority would let the next copy
7227 // clear one a person set.
7228 let Some(option) = field_values
7229 .iter()
7230 .find(|value| {
7231 value.pointer("/field/name").and_then(Value::as_str) == Some(PRIORITY_FIELD)
7232 })
7233 .map(|value| required_str(value, "name"))
7234 .transpose()?
7235 else {
7236 return Ok(HeldPriority::Read(Priority::None));
7237 };
7238 Ok(mapping.priority_of(option).map_or_else(
7239 || HeldPriority::Unmapped(option.to_owned()),
7240 HeldPriority::Read,
7241 ))
7242 }
7243
7244 /// What each projected metadata field holds for one board item, by field name — every text
7245 /// value GitHub answers, an empty one included.
7246 fn held_projections(
7247 &self,
7248 field_values: &[Value],
7249 ) -> Result<BTreeMap<String, String>, SourceError> {
7250 let mut held = BTreeMap::new();
7251 for projection in &self.metadata_fields {
7252 if let Some(text) = text_field(field_values, &projection.field)? {
7253 held.insert(projection.field.to_string(), text);
7254 }
7255 }
7256 Ok(held)
7257 }
7258
7259 /// What one board item's status is read from: its `Status` option, whether its issue
7260 /// is closed, and the reason it was closed with. [`BoardStatuses::status`] turns the
7261 /// three into the status it reports.
7262 fn status_parts<'a>(
7263 field_values: &'a [Value],
7264 content: &'a Value,
7265 ) -> Result<(Option<&'a str>, bool, Option<&'a str>), SourceError> {
7266 let option = field_values
7267 .iter()
7268 .find(|value| value.pointer("/field/name").and_then(Value::as_str) == Some("Status"))
7269 .map(|value| required_str(value, "name"))
7270 .transpose()?;
7271 let closed = optional_str(content, "state")? == Some("CLOSED");
7272 Ok((option, closed, optional_str(content, "stateReason")?))
7273 }
7274
7275 /// The board Status option this write selects, or the refusal that says why not.
7276 ///
7277 /// The mapped option is required for both open and terminal targets. A terminal write
7278 /// validates it before changing either representation, so it can never fall back to
7279 /// closing an issue whose board cannot display the matching status.
7280 ///
7281 /// Answers the field's id, the option's id, and the option's name as the board spells
7282 /// it — which is the name a read of the item reports once it sits there.
7283 fn column_for(
7284 &self,
7285 fields: &Value,
7286 kind: ItemKind,
7287 category: StatusCategory,
7288 target: &StatusTarget,
7289 ) -> Result<Option<(String, String, String)>, SourceError> {
7290 let Some(wanted) = target.option() else {
7291 return Ok(None);
7292 };
7293 let missing = |detail: &str| SourceError::Refused {
7294 message: format!(
7295 "{} status {} of source {} needs the board Status option {wanted:?}, and \
7296 {detail}; next: add that option to the board, which `onetaskgraph sources \
7297 fields {} --apply` does, or point status_mapping.{}.{} of this source at one \
7298 it has",
7299 kind.marker(),
7300 category_name(category),
7301 self.name,
7302 self.name,
7303 category_name(category),
7304 kind.marker()
7305 ),
7306 };
7307 let Some(field) = Board::field(fields, "Status")? else {
7308 return Err(missing("this board has no Status field"));
7309 };
7310 if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
7311 return Err(missing(
7312 "this board's Status field is not a single-select field",
7313 ));
7314 }
7315 let option = field
7316 .get("options")
7317 .and_then(Value::as_array)
7318 .and_then(|options| {
7319 options.iter().find(|option| {
7320 option
7321 .get("name")
7322 .and_then(Value::as_str)
7323 .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
7324 })
7325 });
7326 match option {
7327 None => Err(missing("this board does not have it")),
7328 Some(option) => Ok(Some((
7329 required_str(field, "id")?.to_owned(),
7330 required_str(option, "id")?.to_owned(),
7331 required_str(option, "name")?.to_owned(),
7332 ))),
7333 }
7334 }
7335
7336 /// The refusal a status that closes an issue is answered with over a board draft.
7337 fn closes_a_draft(&self, category: StatusCategory) -> SourceError {
7338 SourceError::Refused {
7339 message: format!(
7340 "status {} of source {} closes the item's issue, and GitHub draft items have \
7341 no open or closed state",
7342 category_name(category),
7343 self.name
7344 ),
7345 }
7346 }
7347
7348 /// What a status write to one item needs of the board: the board's id and the
7349 /// definition of its `Status` field, read off the item when the item says both.
7350 ///
7351 /// The same reasoning as [`Self::fields_for`]: a node read of the item names its board,
7352 /// and its `Status` value carries that field's definition, options and all. An item that
7353 /// does not say — no board id, or no `Status` value to read the field off — takes them
7354 /// from [`Self::board_fields`], which reads no item.
7355 async fn status_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
7356 if let Some(board) = item.carried_board() {
7357 return Ok(board);
7358 }
7359 if item.defines("Status")
7360 && let Some(board_id) = item.named_board()
7361 {
7362 return Ok(BoardFields {
7363 id: board_id,
7364 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7365 });
7366 }
7367 self.board_fields().await
7368 }
7369
7370 /// Set one task's or one project's status and nothing else; see
7371 /// [`TaskSource::set_task_status`] and [`TaskSource::set_project_status`].
7372 async fn set_status(
7373 &self,
7374 id: &NativeId,
7375 kind: ItemKind,
7376 category: StatusCategory,
7377 ) -> Result<Option<Status>, SourceError> {
7378 // Refused before anything is read, in the words a write of the same status is.
7379 let target = self.resolved_target(kind, category)?;
7380 // An item read by issue reference carries only what this write needs, so what it
7381 // becomes is never remembered for a later read to be answered from.
7382 let held = self.take_held(id)?;
7383 let by_reference = held.is_some();
7384 let bound = match held {
7385 Some(item) => Some(item),
7386 None => self.bound_item(id).await?,
7387 };
7388 let Some(mut item) = bound.filter(|item| item.kind == BoardKind::Work(kind)) else {
7389 return Ok(None);
7390 };
7391 let board = self.status_board(&item).await?;
7392 let (field, option, name) = self
7393 .column_for(&board.fields, kind, category, &target)?
7394 .ok_or_else(|| SourceError::Malformed {
7395 message: format!(
7396 "status {} of source {} names no board Status option",
7397 category_name(category),
7398 self.name
7399 ),
7400 })?;
7401 if item.status.category == category && item.option.as_deref() == Some(&name) {
7402 return Ok(Some(item.status));
7403 }
7404 match &target {
7405 StatusTarget::Terminal(_, reason) => {
7406 if item.content_kind == ContentKind::DraftIssue {
7407 return Err(self.closes_a_draft(category));
7408 }
7409 // The option first, so a refused selection leaves an open issue open rather
7410 // than closed behind a card that still reads open.
7411 self.set_item_field(
7412 board.id.as_str(),
7413 &item.item_id,
7414 &field,
7415 json!({"singleSelectOptionId": option}),
7416 )
7417 .await?;
7418 // An issue already closed in a way that reads as this category keeps its state
7419 // and its reason: only its card was out of line, and closing it again would
7420 // overwrite a reason — a duplicate's — that says more than this write does.
7421 let already = item.closed && item.status.category == category;
7422 if !already {
7423 self.update_content(
7424 ContentKind::Issue,
7425 &item.id,
7426 json!({"stateInput": state_input(Some(&target))}),
7427 )
7428 .await?;
7429 }
7430 let reason = if already {
7431 item.reason.clone()
7432 } else {
7433 Some(reason.reason().to_owned())
7434 };
7435 item.closed = true;
7436 item.status = self
7437 .statuses
7438 .status(kind, Some(&name), true, reason.as_deref());
7439 item.option = Some(name);
7440 item.reason = reason;
7441 }
7442 StatusTarget::Column(_) => {
7443 // An option is what an open item's status is, so a closed issue is reopened
7444 // first — sitting closed in the column, it would read back as closed. A draft has
7445 // no state to reopen.
7446 if item.content_kind == ContentKind::Issue && item.closed {
7447 self.update_content(
7448 ContentKind::Issue,
7449 &item.id,
7450 json!({"stateInput": state_input(Some(&target))}),
7451 )
7452 .await?;
7453 item.closed = false;
7454 }
7455 self.set_item_field(
7456 board.id.as_str(),
7457 &item.item_id,
7458 &field,
7459 json!({"singleSelectOptionId": option}),
7460 )
7461 .await?;
7462 item.status = self.statuses.status(kind, Some(&name), false, None);
7463 item.option = Some(name);
7464 }
7465 StatusTarget::Disabled(_) => {
7466 unreachable!("resolved_target refused a disabled status")
7467 }
7468 }
7469 let status = item.status.clone();
7470 if !by_reference {
7471 self.remember_written(item, false)?;
7472 }
7473 Ok(Some(status))
7474 }
7475
7476 /// Replace one task's `delivered_by` and nothing else; see
7477 /// [`TaskSource::set_delivered_by`].
7478 ///
7479 /// One update of the body, which differs from the body GitHub holds only inside the
7480 /// metadata slot — see [`with_slot`]. A body that would not change is not sent at all.
7481 async fn replace_delivered_by(
7482 &self,
7483 id: &NativeId,
7484 delivered_by: &[TaskRef],
7485 ) -> Result<Option<()>, SourceError> {
7486 let entries = TaskRef::listed(
7487 TaskRef::DELIVERED_BY_KEY,
7488 id,
7489 Some(&self.name),
7490 delivered_by.to_vec(),
7491 )
7492 .map_err(|message| SourceError::Refused { message })?;
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 mut slot = item.slot.clone();
7501 set_task_list(&mut slot, TaskRef::DELIVERED_BY_KEY, &entries);
7502 self.write_slot(&mut item, &slot).await?;
7503 item.delivered_by = entries;
7504 self.remember_written(item, false)?;
7505 Ok(Some(()))
7506 }
7507
7508 /// Set one caller key of the metadata slot of one issue of `kind`, and nothing else;
7509 /// see [`TaskSource::set_task_metadata`].
7510 ///
7511 /// `None` when this board holds no item by that id, or holds one of another kind. The
7512 /// answer is the item as this source now reads it, so what a caller is told the key
7513 /// holds is what the slot holds.
7514 ///
7515 /// A key already holding the value is answered without a write, compared as JSON rather
7516 /// than as the body's bytes: a slot a person spelled with other whitespace would
7517 /// otherwise be re-encoded, which is a write that changes nothing the caller asked for.
7518 async fn set_slot_key(
7519 &self,
7520 id: &NativeId,
7521 kind: BoardKind,
7522 key: &MetadataKey,
7523 value: &Value,
7524 ) -> Result<Option<Resolved>, SourceError> {
7525 let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
7526 return Ok(None);
7527 };
7528 if item.slot.get(key.as_str()) == Some(value) {
7529 return Ok(Some(item));
7530 }
7531 let mut slot = item.slot.clone();
7532 slot.insert(key.as_str().to_owned(), value.clone());
7533 // A key a board text field projects moves that field first, so the body — the value's
7534 // one authoritative home — is written last, as every write of an existing item is.
7535 if self
7536 .metadata_fields
7537 .iter()
7538 .any(|projection| &*projection.key == key.as_str())
7539 {
7540 let board = self.projection_board(&item).await?;
7541 let (writes, projected) = self.projection_writes(
7542 &board.fields,
7543 Some(&item.projected),
7544 &slot,
7545 Some(&[key.as_str()]),
7546 )?;
7547 let (mut values, mut clears) = (Vec::new(), Vec::new());
7548 for write in &writes {
7549 write.join(&mut values, &mut clears);
7550 }
7551 self.set_item_fields(board.id.as_str(), &item.item_id, &values, &clears)
7552 .await?;
7553 item.projected = projected;
7554 }
7555 self.write_slot(&mut item, &slot).await?;
7556 self.remember_written(item.clone(), false)?;
7557 Ok(Some(item))
7558 }
7559
7560 /// What a projection write to `item` needs of the board, read off the item when it says
7561 /// enough, as [`Self::fields_for`] reads it.
7562 async fn projection_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
7563 if let Some(board) = item.carried_board() {
7564 return Ok(board);
7565 }
7566 if let Some(board_id) = item.named_board()
7567 && self
7568 .metadata_fields
7569 .iter()
7570 .all(|projection| item.defines(&projection.field))
7571 {
7572 return Ok(BoardFields {
7573 id: board_id,
7574 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7575 });
7576 }
7577 self.board_fields().await
7578 }
7579
7580 /// Put `slot` in one item's metadata slot with a single update of its body, and bring
7581 /// `item` up to what that write left.
7582 ///
7583 /// The body sent differs from the body GitHub holds only inside the slot — see
7584 /// [`with_slot`] — and a body that would not change is not sent at all. It goes through
7585 /// the mutation the item's content takes, so a board draft's body is written with
7586 /// `updateProjectV2DraftIssue` exactly as an issue's is with `updateIssue`.
7587 async fn write_slot(
7588 &self,
7589 item: &mut Resolved,
7590 slot: &BTreeMap<String, Value>,
7591 ) -> Result<(), SourceError> {
7592 let held = item.raw_body.clone().unwrap_or_default();
7593 let body = with_slot(&held, slot)?;
7594 if body != held {
7595 self.update_content(item.content_kind, &item.id, json!({"body": body}))
7596 .await?;
7597 }
7598 let (visible, slot) = metadata_body(Some(body.clone()))?;
7599 item.body = visible.filter(|value| !value.is_empty());
7600 item.raw_body = Some(body);
7601 item.slot = slot;
7602 Ok(())
7603 }
7604
7605 /// This instance's target for a category written to an item of `kind`, refusing one
7606 /// that kind has no option for — before anything is read or written.
7607 ///
7608 /// Nothing here mutates the board's option set to make room for a status. GitHub
7609 /// documents `UpdateProjectV2FieldInput.singleSelectOptions` as *"provided values
7610 /// overwrite existing options"*, so no addition is additive and a mistake destroys the
7611 /// field and every item's status.
7612 fn resolved_target(
7613 &self,
7614 kind: ItemKind,
7615 category: StatusCategory,
7616 ) -> Result<StatusTarget, SourceError> {
7617 let target = self.statuses.target(kind, category).clone();
7618 let StatusTarget::Disabled(why) = target else {
7619 return Ok(target);
7620 };
7621 let refusal = why.refusal(&self.name, category, kind);
7622 // Why there is no shipped default, which is the question a person meeting this
7623 // refusal on a source that never mentioned the category asks.
7624 let shipped_none = match category {
7625 StatusCategory::Draft => Some(
7626 "draft has no shipped default because GitHub draft issues cannot have \
7627 sub-issues, and this source stores a project's tasks as its issue's sub-issues",
7628 ),
7629 StatusCategory::Unknown => Some(
7630 "unknown has no shipped default because this board keeps no open-ended status \
7631 word: every word classified unknown is written to the one board Status option \
7632 status_mapping.unknown names",
7633 ),
7634 _ => None,
7635 };
7636 Err(match (refusal, shipped_none, why) {
7637 (SourceError::Refused { message }, Some(note), UnmappedStatus::Unconfigured) => {
7638 SourceError::Refused {
7639 message: format!("{message}; {note}"),
7640 }
7641 }
7642 (refusal, _, _) => refusal,
7643 })
7644 }
7645
7646 /// What writing `priority` does to one item's `Priority` field on this board, or the
7647 /// refusal naming what the board lacks.
7648 ///
7649 /// `none` is no value, so it clears the field — and asks nothing of an item that holds
7650 /// none already, or of an item not created yet. Every other priority selects the option
7651 /// the mapping names, matched case-insensitively; a board with no `Priority` field, or
7652 /// without that option, is refused rather than given one: reads and writes never create
7653 /// a field or an option.
7654 fn priority_write(
7655 &self,
7656 fields: &Value,
7657 existing: Option<&Resolved>,
7658 priority: Priority,
7659 ) -> Result<Option<PriorityWrite>, SourceError> {
7660 let Some(mapping) = &self.priorities else {
7661 return Err(self.holds_no_priority());
7662 };
7663 let Some(wanted) = mapping.option(priority) else {
7664 if !existing.is_some_and(Resolved::holds_priority) {
7665 return Ok(None);
7666 }
7667 let field =
7668 Board::field(fields, PRIORITY_FIELD)?.ok_or_else(|| SourceError::Malformed {
7669 message: format!(
7670 "an item holding a {PRIORITY_FIELD} value was read without that field"
7671 ),
7672 })?;
7673 return Ok(Some(PriorityWrite::Clear {
7674 field: required_str(field, "id")?.to_owned(),
7675 }));
7676 };
7677 let missing = |detail: &str| SourceError::Refused {
7678 message: format!(
7679 "priority {priority} of source {} needs the board {PRIORITY_FIELD} option \
7680 {wanted:?}, and {detail}; run `onetaskgraph sources fields {} --apply` to add \
7681 it, or point priority_mapping.{priority} of this source at an option the board \
7682 has",
7683 self.name, self.name
7684 ),
7685 };
7686 let Some(field) = Board::field(fields, PRIORITY_FIELD)? else {
7687 return Err(missing(&format!(
7688 "this board has no {PRIORITY_FIELD} field"
7689 )));
7690 };
7691 if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
7692 return Err(missing(&format!(
7693 "this board's {PRIORITY_FIELD} field is not a single-select field"
7694 )));
7695 }
7696 // An options list that is absent or not a list is an answer this source cannot read,
7697 // not a board lacking the option: `sources fields --apply` is no remedy for it.
7698 let option = field
7699 .get("options")
7700 .and_then(Value::as_array)
7701 .ok_or_else(|| SourceError::Malformed {
7702 message: format!("GitHub {PRIORITY_FIELD} field options is not an array"),
7703 })?
7704 .iter()
7705 .find(|option| {
7706 option
7707 .get("name")
7708 .and_then(Value::as_str)
7709 .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
7710 })
7711 .ok_or_else(|| missing("this board does not have it"))?;
7712 Ok(Some(PriorityWrite::Select {
7713 field: required_str(field, "id")?.to_owned(),
7714 option: required_str(option, "id")?.to_owned(),
7715 }))
7716 }
7717
7718 /// What writing `metadata` does to each projected text field of one item, and what those
7719 /// fields hold after it — or the refusal, before anything is sent.
7720 ///
7721 /// `held` is what the item's fields hold now, `None` for an item not created yet. `keys`
7722 /// narrows the work to the entries projecting one of those metadata keys, for a write that
7723 /// touches only them; `None` is every entry. A string the field already holds, and nothing
7724 /// for a field holding nothing, sends nothing. A value no text field can hold is refused,
7725 /// and so is a board without the field, or with a field of that name that is not a text
7726 /// field: reads and writes never create a field.
7727 fn projection_writes(
7728 &self,
7729 fields: &Value,
7730 held: Option<&BTreeMap<String, String>>,
7731 metadata: &BTreeMap<String, Value>,
7732 keys: Option<&[&str]>,
7733 ) -> Result<(Vec<ProjectionWrite>, BTreeMap<String, String>), SourceError> {
7734 let mut projected = held.cloned().unwrap_or_default();
7735 let mut writes = Vec::new();
7736 for projection in self
7737 .metadata_fields
7738 .iter()
7739 .filter(|projection| keys.is_none_or(|keys| keys.contains(&&*projection.key)))
7740 {
7741 let wanted = projection.projected(metadata, &self.name)?;
7742 let field = self.projection_field(fields, projection)?;
7743 let holding = projected.get(&*projection.field);
7744 match wanted {
7745 Projected::Text(text) if holding != Some(&text) => {
7746 writes.push(ProjectionWrite::Set {
7747 field,
7748 text: text.clone(),
7749 });
7750 projected.insert(projection.field.to_string(), text);
7751 }
7752 Projected::Nothing if holding.is_some() => {
7753 writes.push(ProjectionWrite::Clear { field });
7754 projected.remove(&*projection.field);
7755 }
7756 Projected::Text(_) | Projected::Nothing => {}
7757 }
7758 }
7759 Ok((writes, projected))
7760 }
7761
7762 /// The id of the board text field one projection writes, or the refusal naming what the
7763 /// board has instead.
7764 fn projection_field(
7765 &self,
7766 fields: &Value,
7767 projection: &MetadataField,
7768 ) -> Result<String, SourceError> {
7769 let refuse = |detail: String| SourceError::Refused {
7770 message: format!(
7771 "source {} projects metadata key {:?} onto the board text field {:?}, and \
7772 {detail}; next: run `onetaskgraph sources fields {} --apply` to create it as a \
7773 text field, or name another field in metadata_fields",
7774 self.name, &*projection.key, &*projection.field, self.name
7775 ),
7776 };
7777 let Some(field) = Board::field(fields, &projection.field)? else {
7778 return Err(refuse("this board has no field of that name".to_owned()));
7779 };
7780 let typename = optional_str(field, "__typename")?.unwrap_or("field of another type");
7781 let data_type = optional_str(field, "dataType")?;
7782 if typename != "ProjectV2Field" || data_type != Some("TEXT") {
7783 return Err(refuse(format!(
7784 "this board's field of that name is not a text field (it is a {}), so it is \
7785 left as it is; rename or remove that field first",
7786 data_type.unwrap_or(typename)
7787 )));
7788 }
7789 Ok(required_str(field, "id")?.to_owned())
7790 }
7791
7792 /// Apply one priority write to one board item.
7793 async fn write_priority(
7794 &self,
7795 board_id: &str,
7796 item_id: &str,
7797 write: &PriorityWrite,
7798 ) -> Result<(), SourceError> {
7799 match write {
7800 PriorityWrite::Select { field, option } => {
7801 self.set_item_field(
7802 board_id,
7803 item_id,
7804 field,
7805 json!({"singleSelectOptionId": option}),
7806 )
7807 .await
7808 }
7809 PriorityWrite::Clear { field } => {
7810 let data = self
7811 .graphql(
7812 graphql::CLEAR_FIELD,
7813 json!({"input":{"projectId":board_id,"itemId":item_id,"fieldId":field},
7814 "readPriority":false,"priorityName":PRIORITY_FIELD}),
7815 )
7816 .await?;
7817 let returned = data
7818 .pointer("/clearProjectV2ItemFieldValue/projectV2Item")
7819 .ok_or_else(|| SourceError::Malformed {
7820 message: "GitHub field clear returned no project item".into(),
7821 })?;
7822 if required_str(returned, "id")? != item_id {
7823 return Err(SourceError::Malformed {
7824 message: "GitHub field clear returned the wrong project item".into(),
7825 });
7826 }
7827 Ok(())
7828 }
7829 }
7830 }
7831
7832 /// The refusal a priority is answered with by an instance configured with no
7833 /// `priority_mapping`, which holds none.
7834 fn holds_no_priority(&self) -> SourceError {
7835 SourceError::Refused {
7836 message: format!(
7837 "source {} holds no task priority: its configuration sets no priority_mapping; \
7838 next: set priority_mapping on this source, then run `onetaskgraph sources \
7839 fields {} --apply` to set its board up",
7840 self.name, self.name
7841 ),
7842 }
7843 }
7844
7845 /// Set one task's priority and nothing else; see [`TaskSource::set_task_priority`].
7846 ///
7847 /// One field write — a select, or a clear for `none` — and no title, body, label, state
7848 /// or `Status` request. Clearing a priority an item does not hold sends nothing.
7849 async fn set_priority(
7850 &self,
7851 id: &NativeId,
7852 priority: Priority,
7853 ) -> Result<Option<Priority>, SourceError> {
7854 if self.priorities.is_none() {
7855 return Err(self.holds_no_priority());
7856 }
7857 let Some(mut item) = self
7858 .bound_item(id)
7859 .await?
7860 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
7861 else {
7862 return Ok(None);
7863 };
7864 if priority == Priority::None && !item.holds_priority() {
7865 return Ok(Some(priority));
7866 }
7867 // The item's own read carries the field's definition whenever it holds a value of
7868 // it, which a clear always does; a select onto an item holding none reads the board.
7869 let board = match (item.carried_board(), item.named_board()) {
7870 (Some(board), _) => board,
7871 (None, Some(id)) if item.defines(PRIORITY_FIELD) => BoardFields {
7872 id,
7873 fields: json!({"nodes": item.fields.clone(), "pageInfo": {"hasNextPage": false}}),
7874 },
7875 _ => self.board_fields().await?,
7876 };
7877 let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? else {
7878 return Ok(Some(priority));
7879 };
7880 let (document, root, input) = match write {
7881 PriorityWrite::Select { field, option } => (
7882 graphql::UPDATE_FIELD,
7883 "updateProjectV2ItemFieldValue",
7884 json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field,"value":{"singleSelectOptionId":option}}),
7885 ),
7886 PriorityWrite::Clear { field } => (
7887 graphql::CLEAR_FIELD,
7888 "clearProjectV2ItemFieldValue",
7889 json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field}),
7890 ),
7891 };
7892 let data = self
7893 .graphql(
7894 document,
7895 json!({"input":input,"readPriority":true,"priorityName":PRIORITY_FIELD}),
7896 )
7897 .await?;
7898 let returned = data
7899 .get(root)
7900 .and_then(|value| value.get("projectV2Item"))
7901 .ok_or_else(|| SourceError::Malformed {
7902 message: "GitHub priority write returned no project item".into(),
7903 })?;
7904 if required_str(returned, "id")? != item.item_id {
7905 return Err(SourceError::Malformed {
7906 message: "GitHub priority write returned the wrong project item".into(),
7907 });
7908 }
7909 let value = returned
7910 .get("fieldValueByName")
7911 .ok_or_else(|| SourceError::Malformed {
7912 message: "GitHub priority write returned no priority read-back".into(),
7913 })?;
7914 if !value.is_null()
7915 && value.pointer("/field/name").and_then(Value::as_str) != Some(PRIORITY_FIELD)
7916 {
7917 return Err(SourceError::Malformed {
7918 message: "GitHub priority read-back is not a Priority field value".into(),
7919 });
7920 }
7921 let values = if value.is_null() {
7922 Vec::new()
7923 } else {
7924 vec![value.clone()]
7925 };
7926 item.priority = self.held_priority(&values)?;
7927 let answer = item.task()?.priority;
7928 self.remember_written(item, false)?;
7929 Ok(Some(answer))
7930 }
7931
7932 /// Replace one task's visible body and nothing else; see
7933 /// [`TaskSource::set_task_content`].
7934 ///
7935 /// One update of the body, which differs from the body GitHub holds only outside the
7936 /// metadata slot — the slot is kept byte for byte, so every caller key and every list
7937 /// this source keeps there reads back as it was. A body that would not change is not
7938 /// sent at all.
7939 async fn replace_content(
7940 &self,
7941 id: &NativeId,
7942 content: &str,
7943 ) -> Result<Option<()>, SourceError> {
7944 let Some(mut item) = self
7945 .bound_item(id)
7946 .await?
7947 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
7948 else {
7949 return Ok(None);
7950 };
7951 let held = item.raw_body.clone().unwrap_or_default();
7952 let body = with_content(&held, content)?;
7953 // Checked before anything is sent: content ending in what this source reads as its own
7954 // metadata slot would read back as metadata rather than as the content it was.
7955 let (visible, slot) = metadata_body(Some(body.clone()))?;
7956 if visible.as_deref().unwrap_or_default() != content || slot != item.slot {
7957 return Err(SourceError::Refused {
7958 message: format!(
7959 "this content ends in what source {} reads as its own metadata slot \
7960 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
7961 as content; next: remove that trailing block from the content",
7962 self.name
7963 ),
7964 });
7965 }
7966 if body != held {
7967 self.update_content(item.content_kind, &item.id, json!({"body": body}))
7968 .await?;
7969 }
7970 item.body = visible.filter(|value| !value.is_empty());
7971 item.raw_body = Some(body);
7972 item.slot = slot;
7973 self.remember_written(item, false)?;
7974 Ok(Some(()))
7975 }
7976
7977 /// Apply one targeted update to one task; see [`TaskSource::update_task`].
7978 ///
7979 /// One read of the item — which carries the board's field definitions and the issue's
7980 /// `blockedBy`, so neither is read again — and then only what differs from it: the
7981 /// `Status` option and the `Priority` field together in one request, the `blockedBy`
7982 /// additions and removals the named edges differ by, and last one `updateIssue` carrying
7983 /// the title, the body — visible content and metadata slot together — and a state change.
7984 /// So an update naming any of title, body, metadata, status and priority is one read and
7985 /// at most two writes. The body goes last so that a write refused part-way leaves it, and
7986 /// the metadata in it, as it stood. A terminal status selects its option and then closes,
7987 /// as a whole write does; an open one selects its option and then reopens. The origin
7988 /// field is never written: an update is of an item that already exists, whose origin is
7989 /// what it is.
7990 ///
7991 /// The task answered is the item as those writes left it, built from the read and what was
7992 /// sent rather than read again — the same record a later read in this run answers from.
7993 async fn targeted_update(
7994 &self,
7995 id: &NativeId,
7996 update: &TaskUpdate,
7997 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
7998 // Everything this source can refuse without reading the item is refused first, in the
7999 // words a whole write of the same fields is refused with.
8000 update.consistent()?;
8001 if update
8002 .title
8003 .as_deref()
8004 .is_some_and(|title| title.starts_with(DESIGN_TITLE_PREFIX))
8005 {
8006 return Err(SourceError::Refused {
8007 message: format!(
8008 "the title of this task begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
8009 spells a document, so it would read back as one rather than as a task; \
8010 retitle it",
8011 self.name
8012 ),
8013 });
8014 }
8015 if let Some(delivers) = &update.delivers {
8016 TaskRef::listed(
8017 TaskRef::DELIVERS_KEY,
8018 id,
8019 Some(&self.name),
8020 delivers.clone(),
8021 )
8022 .map_err(|message| SourceError::Refused { message })?;
8023 }
8024 if self.priorities.is_none()
8025 && update
8026 .priority
8027 .is_some_and(|priority| priority != Priority::None)
8028 {
8029 return Err(self.holds_no_priority());
8030 }
8031 let target = update
8032 .status
8033 .as_ref()
8034 .map(|status| self.resolved_target(ItemKind::Task, status.category))
8035 .transpose()?;
8036 let Some(mut item) = self
8037 .bound_item(id)
8038 .await?
8039 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
8040 else {
8041 return Ok(None);
8042 };
8043 let before = item.task()?;
8044
8045 let mut status_move = None;
8046 if let (Some(status), Some(target)) = (&update.status, target) {
8047 let board = self.status_board(&item).await?;
8048 let (field, option, name) = self
8049 .column_for(&board.fields, ItemKind::Task, status.category, &target)?
8050 .ok_or_else(|| SourceError::Malformed {
8051 message: format!(
8052 "status {} of source {} names no board Status option",
8053 category_name(status.category),
8054 self.name
8055 ),
8056 })?;
8057 let terminal = matches!(target, StatusTarget::Terminal(_, _));
8058 if terminal && item.content_kind == ContentKind::DraftIssue {
8059 return Err(self.closes_a_draft(status.category));
8060 }
8061 let landed = match &target {
8062 StatusTarget::Terminal(_, reason) => {
8063 self.statuses
8064 .status(ItemKind::Task, Some(&name), true, Some(reason.reason()))
8065 }
8066 _ => self
8067 .statuses
8068 .status(ItemKind::Task, Some(&name), false, None),
8069 };
8070 let option_moves = item
8071 .option
8072 .as_deref()
8073 .is_none_or(|held| !held.eq_ignore_ascii_case(&name));
8074 let state_moves = item.content_kind == ContentKind::Issue
8075 && (item.closed != terminal || (terminal && item.status != landed));
8076 if let Some(moves) = Moves::of(option_moves, state_moves) {
8077 status_move = Some(StatusMove {
8078 board: board.id,
8079 field,
8080 option,
8081 name,
8082 target,
8083 landed,
8084 moves,
8085 });
8086 }
8087 }
8088
8089 let mut priority_move = None;
8090 if let Some(priority) = update.priority
8091 && self.priorities.is_some()
8092 && item.priority != HeldPriority::Read(priority)
8093 {
8094 let board = match (item.carried_board(), item.named_board()) {
8095 (Some(board), _) => board,
8096 (None, Some(board)) if item.defines(PRIORITY_FIELD) => BoardFields {
8097 id: board,
8098 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
8099 },
8100 _ => self.board_fields().await?,
8101 };
8102 if let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? {
8103 priority_move = Some((board.id, write, priority));
8104 }
8105 }
8106
8107 // The metadata keys this update names that a board text field projects, and what
8108 // that does to those fields — refused, as a whole write refuses it, before anything
8109 // is sent.
8110 let touched: Vec<&str> = update
8111 .metadata_set
8112 .keys()
8113 .chain(update.metadata_remove.iter())
8114 .map(MetadataKey::as_str)
8115 .collect();
8116 let mut projection_move = None;
8117 if self
8118 .metadata_fields
8119 .iter()
8120 .any(|projection| touched.contains(&&*projection.key))
8121 {
8122 let mut metadata = item.slot.clone();
8123 for (key, value) in &update.metadata_set {
8124 metadata.insert(key.as_str().to_owned(), value.clone());
8125 }
8126 for key in &update.metadata_remove {
8127 metadata.remove(key.as_str());
8128 }
8129 let board = self.projection_board(&item).await?;
8130 let (writes, projected) = self.projection_writes(
8131 &board.fields,
8132 Some(&item.projected),
8133 &metadata,
8134 Some(&touched),
8135 )?;
8136 projection_move = Some((board.id, writes, projected));
8137 }
8138
8139 // Resolved before the body is composed, because a far end `blockedBy` cannot name is
8140 // recorded in the slot, and the slot travels in the one body update below.
8141 let edges = match &update.depends_on {
8142 Some(edges) => Some(
8143 self.partition_edges(
8144 BoardKind::Work(ItemKind::Task),
8145 item.content_kind,
8146 item.blocked_by.as_deref(),
8147 edges,
8148 )
8149 .await?,
8150 ),
8151 None => None,
8152 };
8153
8154 let mut slot = item.slot.clone();
8155 for (key, value) in &update.metadata_set {
8156 slot.insert(key.as_str().to_owned(), value.clone());
8157 }
8158 for key in &update.metadata_remove {
8159 slot.remove(key.as_str());
8160 }
8161 if let Some(delivers) = &update.delivers {
8162 set_task_list(&mut slot, TaskRef::DELIVERS_KEY, delivers);
8163 }
8164 if let Some((_, recorded)) = &edges {
8165 record_edges(&mut slot, recorded);
8166 }
8167 let held = item.raw_body.clone().unwrap_or_default();
8168 let content = match &update.content {
8169 Some(content) => with_content(&held, content)?,
8170 None => held.clone(),
8171 };
8172 // A slot holding what it held is kept byte for byte, compared as JSON rather than as
8173 // the body's bytes, as a metadata write compares it: a slot a person spelled with
8174 // other whitespace would otherwise be re-encoded, which is a write nobody asked for.
8175 let body = if slot == item.slot {
8176 content
8177 } else {
8178 with_slot(&content, &slot)?
8179 };
8180 // Checked before anything is sent, as a content write checks it: content ending in
8181 // what this source reads as its own slot would read back as metadata.
8182 let (visible, read) = metadata_body(Some(body.clone()))?;
8183 let wanted = update.content.as_deref().or(item.body.as_deref());
8184 if visible.as_deref().unwrap_or_default() != wanted.unwrap_or_default() || read != slot {
8185 return Err(SourceError::Refused {
8186 message: format!(
8187 "this content ends in what source {} reads as its own metadata slot \
8188 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
8189 as content; next: remove that trailing block from the content",
8190 self.name
8191 ),
8192 });
8193 }
8194 let recorded_moves =
8195 slot.get(DependencyEdge::RECORDED_KEY) != item.slot.get(DependencyEdge::RECORDED_KEY);
8196
8197 // One `updateIssue` carries all three, because every mutation spends the secondary
8198 // limiter and the title, body and state are one mutation's inputs.
8199 let mut fields = serde_json::Map::new();
8200 if let Some(title) = update.title.as_ref().filter(|title| **title != item.title) {
8201 fields.insert("title".to_owned(), json!(title));
8202 }
8203 if body != held {
8204 fields.insert("body".to_owned(), json!(body));
8205 }
8206 if let Some(moving) = status_move.as_ref().filter(|moving| moving.moves.state()) {
8207 fields.insert("stateInput".to_owned(), state_input(Some(&moving.target)));
8208 }
8209 // **The body is written last, and that is the guarantee a refusal part-way keeps.**
8210 // GitHub runs no two requests as one, and runs one document's mutation fields in order
8211 // without undoing an earlier field when a later one fails — so a body written before a
8212 // board field the board then refused would be left changed. Written after every other
8213 // write has landed, a refusal anywhere leaves the item's body, and every metadata key
8214 // it carries, exactly as they stood. So the `Status` option and the `Priority` field go
8215 // first, together in one request — a terminal option selected before the issue
8216 // closes, as a whole write does — then the `blockedBy` difference, then the body.
8217 let mut board_writes: Vec<(&BoardId, (String, Value))> = Vec::new();
8218 let mut clears: Vec<(&BoardId, &str)> = Vec::new();
8219 if let Some(moving) = status_move.as_ref().filter(|moving| moving.moves.option()) {
8220 board_writes.push((
8221 &moving.board,
8222 (
8223 moving.field.clone(),
8224 json!({"singleSelectOptionId": moving.option}),
8225 ),
8226 ));
8227 }
8228 match &priority_move {
8229 Some((board, PriorityWrite::Select { field, option }, _)) => board_writes.push((
8230 board,
8231 (field.clone(), json!({"singleSelectOptionId": option})),
8232 )),
8233 Some((board, PriorityWrite::Clear { field }, _)) => clears.push((board, field)),
8234 None => {}
8235 }
8236 if let Some((board, writes, _)) = &projection_move {
8237 for write in writes {
8238 let (mut values, mut cleared) = (Vec::new(), Vec::new());
8239 write.join(&mut values, &mut cleared);
8240 board_writes.extend(values.into_iter().map(|value| (board, value)));
8241 clears.extend(cleared.into_iter().map(|field| (board, field)));
8242 }
8243 }
8244 let mut boards: Vec<&BoardId> = board_writes.iter().map(|(board, _)| *board).collect();
8245 boards.extend(clears.iter().map(|(board, _)| *board));
8246 boards.dedup_by(|one, other| one.as_str() == other.as_str());
8247 for board in boards {
8248 let writes = board_writes
8249 .iter()
8250 .filter(|(on, _)| on.as_str() == board.as_str())
8251 .map(|(_, write)| write.clone())
8252 .collect::<Vec<_>>();
8253 let cleared = clears
8254 .iter()
8255 .filter(|(on, _)| on.as_str() == board.as_str())
8256 .map(|(_, field)| *field)
8257 .collect::<Vec<_>>();
8258 self.set_item_fields(board.as_str(), &item.item_id, &writes, &cleared)
8259 .await?;
8260 }
8261 let mut blocked_by_moved = false;
8262 if let Some((native, _)) = &edges
8263 && item.content_kind == ContentKind::Issue
8264 {
8265 blocked_by_moved = self
8266 .reconcile_blocked_by(
8267 &item.id,
8268 native,
8269 Issue::Existing(item.blocked_by.as_deref()),
8270 )
8271 .await?;
8272 }
8273 if !fields.is_empty() {
8274 self.update_content(item.content_kind, &item.id, Value::Object(fields))
8275 .await?;
8276 }
8277
8278 // The `blockedBy` this item was read with is what the write just changed, so it is no
8279 // answer any more: a later write in this command would reconcile against it — re-adding
8280 // what it kept and never removing what it dropped — and a forward-edge read would
8281 // answer with it. Left unknown, each asks GitHub instead.
8282 if blocked_by_moved {
8283 item.blocked_by = None;
8284 }
8285 if let Some(title) = &update.title {
8286 item.title.clone_from(title);
8287 }
8288 item.body = visible.filter(|value| !value.is_empty());
8289 item.raw_body = (!body.is_empty() || item.raw_body.is_some()).then_some(body);
8290 item.slot = slot;
8291 if let Some(delivers) = &update.delivers {
8292 item.delivers.clone_from(delivers);
8293 }
8294 if let Some(moving) = status_move {
8295 item.closed = matches!(moving.target, StatusTarget::Terminal(_, _))
8296 && item.content_kind == ContentKind::Issue;
8297 item.status = moving.landed;
8298 item.option = Some(moving.name);
8299 }
8300 if let Some((_, _, priority)) = priority_move {
8301 item.priority = HeldPriority::Read(priority);
8302 }
8303 if let Some((_, _, projected)) = projection_move {
8304 item.projected = projected;
8305 }
8306 let task = item.task()?;
8307 let mut written = update.changed(&before, &task);
8308 if blocked_by_moved || recorded_moves {
8309 written.insert(UpdatedField::DependsOn);
8310 }
8311 self.remember_written(item, false)?;
8312 Ok(Some(TaskUpdateOutcome {
8313 task,
8314 written,
8315 delivers_before: before.delivers,
8316 }))
8317 }
8318
8319 /// Replace one issue's visible body and its [`MetadataKey::TEMPLATE_KEY`] slot entry
8320 /// together, and nothing else; see [`TaskSource::set_task_rendering`].
8321 ///
8322 /// One update of the body: the content outside the slot, and inside it that one entry,
8323 /// every other entry kept as it was. This source keeps no template answers — an issue has
8324 /// no room beside itself that is not its body, and answers written there would duplicate
8325 /// what the content already says and count against GitHub's body limit — so `answers`
8326 /// reaches nothing here. A body that would not change is not sent at all.
8327 async fn replace_rendering(
8328 &self,
8329 id: &NativeId,
8330 kind: BoardKind,
8331 content: &str,
8332 provenance: &Value,
8333 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
8334 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
8335 let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
8336 return Ok(None);
8337 };
8338 let held = item.raw_body.clone().unwrap_or_default();
8339 let mut slot = item.slot.clone();
8340 slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
8341 let rewritten;
8342 let content = if let Some(assets) = assets {
8343 let uploads = self
8344 .upload_assets(item.own_repository.as_ref(), assets)
8345 .await?;
8346 rewritten =
8347 onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads);
8348 rewritten.as_str()
8349 } else {
8350 content
8351 };
8352 let body = with_slot(&with_content(&held, content)?, &slot)?;
8353 // Checked before anything is sent, as a content write checks it.
8354 let (visible, read) = metadata_body(Some(body.clone()))?;
8355 if visible.as_deref().unwrap_or_default() != content || read != slot {
8356 return Err(SourceError::Refused {
8357 message: format!(
8358 "this content ends in what source {} reads as its own metadata slot \
8359 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
8360 as content; next: remove that trailing block from the template",
8361 self.name
8362 ),
8363 });
8364 }
8365 if body != held {
8366 self.update_content(item.content_kind, &item.id, json!({"body": body}))
8367 .await?;
8368 }
8369 item.body = visible.filter(|value| !value.is_empty());
8370 item.raw_body = Some(body);
8371 item.slot = read;
8372 self.remember_written(item, false)?;
8373 Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
8374 id: id.clone(),
8375 content: Some(content.to_owned()),
8376 }))
8377 }
8378
8379 async fn set_item_field(
8380 &self,
8381 board_id: &str,
8382 item_id: &str,
8383 field_id: &str,
8384 value: Value,
8385 ) -> Result<(), SourceError> {
8386 let data = self
8387 .graphql(
8388 graphql::UPDATE_FIELD,
8389 json!({"input":{
8390 "projectId":board_id,"itemId":item_id,"fieldId":field_id,"value":value
8391 },"readPriority":false,"priorityName":PRIORITY_FIELD}),
8392 )
8393 .await?;
8394 let returned = data
8395 .pointer("/updateProjectV2ItemFieldValue/projectV2Item")
8396 .ok_or_else(|| SourceError::Malformed {
8397 message: "GitHub field update returned no project item".into(),
8398 })?;
8399 if required_str(returned, "id")? != item_id {
8400 return Err(SourceError::Malformed {
8401 message: "GitHub field update returned the wrong project item".into(),
8402 });
8403 }
8404 Ok(())
8405 }
8406
8407 /// GitHub accepts one value per field mutation; aliases combine those mutations in
8408 /// one request — writes in the order given, then clears. A lone write is
8409 /// [`graphql::UPDATE_FIELD`] and a lone clear [`graphql::CLEAR_FIELD`]; more than one
8410 /// request's slots hold go in further requests of the same document, in order. Every
8411 /// returned item id is checked, including optional aliases.
8412 async fn set_item_fields(
8413 &self,
8414 board: &str,
8415 item: &str,
8416 fields: &[(String, Value)],
8417 clears: &[&str],
8418 ) -> Result<(), SourceError> {
8419 match (fields, clears) {
8420 ([], []) => return Ok(()),
8421 ([(field, value)], []) => {
8422 return self.set_item_field(board, item, field, value.clone()).await;
8423 }
8424 ([], [field]) => {
8425 return self
8426 .write_priority(
8427 board,
8428 item,
8429 &PriorityWrite::Clear {
8430 field: (*field).to_owned(),
8431 },
8432 )
8433 .await;
8434 }
8435 _ => {}
8436 }
8437 // Any field of the request stands in for an input a slot leaves out, which GitHub
8438 // still requires to be well formed although it never runs it.
8439 let filler = fields
8440 .first()
8441 .map_or_else(|| clears[0], |(field, _)| field.as_str());
8442 let mut writes = fields.iter();
8443 let mut cleared = clears.iter();
8444 loop {
8445 let batch: Vec<&(String, Value)> =
8446 writes.by_ref().take(FIELD_WRITE_SLOTS.len()).collect();
8447 let batch_clears: Vec<&&str> = cleared.by_ref().take(FIELD_CLEAR_SLOTS.len()).collect();
8448 if batch.is_empty() && batch_clears.is_empty() {
8449 return Ok(());
8450 }
8451 let mut variables = serde_json::Map::new();
8452 for (index, slot) in FIELD_WRITE_SLOTS.iter().enumerate() {
8453 let input = match batch.get(index) {
8454 Some((field, value)) => {
8455 json!({"projectId":board,"itemId":item,"fieldId":field,"value":value})
8456 }
8457 None => json!({"projectId":board,"itemId":item,"fieldId":filler,
8458 "value":{"text":""}}),
8459 };
8460 variables.insert(slot.variable.to_owned(), input);
8461 variables.insert(slot.include.to_owned(), json!(index < batch.len()));
8462 }
8463 for (index, slot) in FIELD_CLEAR_SLOTS.iter().enumerate() {
8464 let field = batch_clears.get(index).map_or(filler, |field| **field);
8465 variables.insert(
8466 slot.variable.to_owned(),
8467 json!({"projectId":board,"itemId":item,"fieldId":field}),
8468 );
8469 variables.insert(slot.include.to_owned(), json!(index < batch_clears.len()));
8470 }
8471 let data = self
8472 .graphql(graphql::UPDATE_FIELDS, Value::Object(variables))
8473 .await?;
8474 let sent = FIELD_WRITE_SLOTS[..batch.len()]
8475 .iter()
8476 .chain(&FIELD_CLEAR_SLOTS[..batch_clears.len()]);
8477 for slot in sent {
8478 let alias = slot.alias;
8479 let returned = data
8480 .get(alias)
8481 .and_then(|value| value.get("projectV2Item"))
8482 .ok_or_else(|| SourceError::Malformed {
8483 message: format!("GitHub field update {alias} returned no project item"),
8484 })?;
8485 if required_str(returned, "id")? != item {
8486 return Err(SourceError::Malformed {
8487 message: format!(
8488 "GitHub field update {alias} returned the wrong project item"
8489 ),
8490 });
8491 }
8492 }
8493 }
8494 }
8495
8496 async fn native_dependency_ids(&self, id: &NativeId) -> Result<Vec<String>, SourceError> {
8497 let mut after: Option<String> = None;
8498 let mut ids = Vec::new();
8499 loop {
8500 let data = self
8501 .graphql(
8502 graphql::ISSUE_DEPENDENCIES,
8503 json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after}),
8504 )
8505 .await?;
8506 let connection =
8507 data.pointer("/node/blockedBy")
8508 .ok_or_else(|| SourceError::Malformed {
8509 message: "GitHub dependency response has no blockedBy connection".into(),
8510 })?;
8511 ids.extend(
8512 connection
8513 .get("nodes")
8514 .and_then(Value::as_array)
8515 .ok_or_else(|| SourceError::Malformed {
8516 message: "GitHub dependency response nodes is not an array".into(),
8517 })?
8518 .iter()
8519 .map(|value| required_str(value, "id").map(str::to_owned))
8520 .collect::<Result<Vec<_>, _>>()?,
8521 );
8522 let next = next_cursor(connection)?;
8523 if let Some(next) = &next {
8524 validate_cursor_progress(after.as_deref(), &next.0)?;
8525 }
8526 after = next.map(|cursor| cursor.0);
8527 if after.is_none() {
8528 return Ok(ids);
8529 }
8530 }
8531 }
8532
8533 async fn dependencies(
8534 &self,
8535 id: &NativeId,
8536 near_kind: ItemKind,
8537 direction: Direction,
8538 page: &PageRequest,
8539 ) -> Result<Page<DependencyEdge>, SourceError> {
8540 validate_page(page)?;
8541 let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
8542 let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
8543 let recorded = recorded_offset(cursor, direction)?;
8544 // What this issue is blocked by, when a read of it by its own id in this command
8545 // already carried the whole connection — a copy reads the item it writes before it
8546 // reads its edges — and the page asked for is the whole of it, or the recorded tail
8547 // after it. Answered from that read, in the shape the dependency read answers in;
8548 // anything else is asked of GitHub.
8549 let carried = match direction {
8550 Direction::DependsOn => self
8551 .resolved_cache()?
8552 .get(id)
8553 .filter(|item| item.content_kind == ContentKind::Issue)
8554 .and_then(|item| Some((item.blocked_by.clone()?, item.raw_body.clone()))),
8555 Direction::DependedOnBy => None,
8556 }
8557 .filter(|(nodes, _)| recorded.is_some() || (cursor.is_none() && nodes.len() <= limit));
8558 // Asked for even in the recorded phase, whose page reads nothing from the
8559 // connection: `__typename` is what says whether this item has a native
8560 // relationship at all, and that is what decides which far ends the reserved key is
8561 // allowed to hold.
8562 let data = match carried {
8563 Some((nodes, body)) => json!({"node":{"__typename":"Issue","body":body,
8564 "blockedBy":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}}),
8565 None => {
8566 let after = if recorded.is_some() { None } else { cursor };
8567 let first = page.limit.min(MAX_PAGE_SIZE);
8568 match direction {
8569 Direction::DependsOn => {
8570 self.graphql(
8571 graphql::ISSUE_DEPENDS_ON,
8572 json!({"id":id.0,"first":first,"after":after,"owner":self.owner,
8573 "number":self.project_number,
8574 "boardItems":BOARD_ITEMS_PAGE_SIZE}),
8575 )
8576 .await?
8577 }
8578 Direction::DependedOnBy => {
8579 self.graphql(
8580 graphql::ISSUE_DEPENDED_ON_BY,
8581 json!({"id":id.0,"first":first,"after":after}),
8582 )
8583 .await?
8584 }
8585 }
8586 }
8587 };
8588 let draft_slot = draft_slot(&data, id, self.project_number)?;
8589 let node =
8590 data.get("node")
8591 .filter(|v| !v.is_null())
8592 .ok_or_else(|| SourceError::Refused {
8593 message: format!(
8594 "GitHub item {} was not found or does not support dependencies",
8595 id.0
8596 ),
8597 })?;
8598 let connection_name = match direction {
8599 Direction::DependsOn => "blockedBy",
8600 Direction::DependedOnBy => "blocking",
8601 };
8602 // A draft has neither `blockedBy` nor `blocking`, so nothing it depends on can be
8603 // named natively and the reserved key may hold any far end. An issue's connections
8604 // hold issues, and this source reads them at the near item's own level.
8605 let natively_names = (required_str(node, "__typename")? == "Issue").then_some(near_kind);
8606 if let Some(offset) = recorded {
8607 return Ok(recorded_page(
8608 self.recorded_edges(
8609 id,
8610 near_kind,
8611 direction,
8612 natively_names,
8613 node,
8614 draft_slot.as_ref(),
8615 )
8616 .await?,
8617 offset,
8618 limit,
8619 ));
8620 }
8621 if natively_names.is_none() {
8622 return Ok(recorded_page(
8623 self.recorded_edges(
8624 id,
8625 near_kind,
8626 direction,
8627 natively_names,
8628 node,
8629 draft_slot.as_ref(),
8630 )
8631 .await?,
8632 0,
8633 limit,
8634 ));
8635 }
8636 let connection = node
8637 .get(connection_name)
8638 .ok_or_else(|| SourceError::Malformed {
8639 message: "GitHub dependency response is missing its connection".into(),
8640 })?;
8641 let nodes = connection
8642 .get("nodes")
8643 .and_then(Value::as_array)
8644 .ok_or_else(|| SourceError::Malformed {
8645 message: "GitHub dependency response nodes is not an array".into(),
8646 })?;
8647 // `from` depends on `to`, always. GitHub spells the same relationship from either
8648 // end — `blockedBy` lists what this item waits on, `blocking` lists what waits on
8649 // it — so the near item is `from` in one direction and `to` in the other.
8650 let items = nodes
8651 .iter()
8652 .map(|value| {
8653 let related = NativeId(required_str(value, "id")?.into());
8654 let related_kind = related_kind(value)?;
8655 let (from, to) = match direction {
8656 Direction::DependsOn => (
8657 DependencyEndpoint::from_native(id.clone(), near_kind),
8658 DependencyEndpoint::from_native(related, related_kind),
8659 ),
8660 Direction::DependedOnBy => (
8661 DependencyEndpoint::from_native(related, related_kind),
8662 DependencyEndpoint::from_native(id.clone(), near_kind),
8663 ),
8664 };
8665 Ok(DependencyEdge {
8666 from,
8667 to,
8668 kind: DependencyKind::Blocks,
8669 })
8670 })
8671 .collect::<Result<Vec<_>, SourceError>>()?;
8672 let mut next = next_cursor(connection)?;
8673 if let Some(next) = &next {
8674 validate_cursor_progress(cursor, &next.0)?;
8675 }
8676 // The recorded far ends ride on the last page of `blockedBy`, whose answer carried the
8677 // body they are recorded in, as far as the page has room — so they cost no request of
8678 // their own — and only what does not fit is resumed by a cursor.
8679 let mut items = items;
8680 if next.is_none() {
8681 let recorded = self
8682 .recorded_edges(
8683 id,
8684 near_kind,
8685 direction,
8686 natively_names,
8687 node,
8688 draft_slot.as_ref(),
8689 )
8690 .await?;
8691 let room = limit.saturating_sub(items.len());
8692 let total = recorded.len();
8693 items.extend(recorded.into_iter().take(room));
8694 if total > room {
8695 next = Some(Cursor(format!("{RECORDED_CURSOR}{room}")));
8696 }
8697 }
8698 Ok(Page { items, next })
8699 }
8700
8701 /// The edges this item records under [`DependencyEdge::RECORDED_KEY`], which is where
8702 /// a far end in another source has to live: no GitHub issue relationship can name one.
8703 ///
8704 /// Only forwards. The reverse of a recorded edge is derived from the far end, and this
8705 /// source never writes one down.
8706 ///
8707 /// The metadata lives in the item's own body slot, and `node` is the dependency read's
8708 /// own answer, which carries an issue's body — so an issue's recorded edges cost no
8709 /// request beyond the read already made, and reading the board for them would be a
8710 /// walk of every item for one field of one. A draft has no body in that answer, because
8711 /// a draft is not an issue, so a draft's are read off its own read by id — never off a
8712 /// listing of the board, which can be behind on the very item asked about.
8713 async fn recorded_edges(
8714 &self,
8715 id: &NativeId,
8716 near_kind: ItemKind,
8717 direction: Direction,
8718 natively_names: Option<ItemKind>,
8719 node: &Value,
8720 draft_slot: Option<&Option<BTreeMap<String, Value>>>,
8721 ) -> Result<Vec<DependencyEdge>, SourceError> {
8722 if direction != Direction::DependsOn {
8723 return Ok(Vec::new());
8724 }
8725 let slot = match (node.get("body"), draft_slot) {
8726 (Some(body), _) if natively_names.is_some() => {
8727 metadata_body(body.as_str().map(str::to_owned))?.1
8728 }
8729 // A draft the dependency read itself answered: this board's, or none of its.
8730 (_, Some(Some(slot))) => slot.clone(),
8731 (_, Some(None)) => return Ok(Vec::new()),
8732 _ => {
8733 let Some(item) = self.bound_item(id).await? else {
8734 return Ok(Vec::new());
8735 };
8736 item.slot
8737 }
8738 };
8739 DependencyEdge::recorded(&slot, id, near_kind, &self.name, natively_names)
8740 .map_err(|message| SourceError::Malformed { message })
8741 }
8742
8743 fn configured_repository(&self) -> Result<&RepositoryTarget, SourceError> {
8744 self.repository
8745 .as_ref()
8746 .ok_or_else(|| SourceError::Refused {
8747 message: format!(
8748 "source {} has no repository configured, and a GitHub Projects board has no \
8749 repository of its own to create an issue in; set repository: owner/name on \
8750 this source",
8751 self.name
8752 ),
8753 })
8754 }
8755
8756 /// The repository one new issue is created in, under the rule [`RepositoryTarget`]
8757 /// states.
8758 ///
8759 /// The fallback is demanded first, whichever arm answers: a write without a configured
8760 /// repository is refused naming the field exactly as it was before the rule existed,
8761 /// so a source that could not write before cannot write now, rather than writing for
8762 /// the one item whose own field happens to decide it.
8763 ///
8764 /// Everything this refuses is refused before `createIssue`, so a refusal leaves no
8765 /// issue behind: an entry that is not a repository on [`RepositoryTarget::HOST`], an
8766 /// entry owned by someone other than the owner of the parent issue's repository —
8767 /// GitHub accepts a sub-issue from another repository of the same owner and from no
8768 /// other, so `addSubIssue` would refuse it after the issue existed — a parent the
8769 /// board does not hold, and a parent that is a draft, which GitHub gives no sub-issues,
8770 /// both of which `addSubIssue` would likewise refuse too late. Whether the entry exists
8771 /// and is visible to the token is checked where its node id is resolved, still before
8772 /// `createIssue`. The parent is read by its own id through [`Self::item_by_id`] — never
8773 /// looked up in a listing of the board, which can be minutes behind an issue its own
8774 /// `projectItems` already places on it — and that read answers first from this process's
8775 /// own record, so a project created moments ago in this command answers though GitHub
8776 /// has not caught up.
8777 async fn creation_target(
8778 &self,
8779 incoming: &Incoming<'_>,
8780 ) -> Result<RepositoryTarget, SourceError> {
8781 let fallback = self.configured_repository()?;
8782 let what = |incoming: &Incoming<'_>| {
8783 format!(
8784 "{} {:?}",
8785 incoming.written.kind().describes(),
8786 incoming.title
8787 )
8788 };
8789 let parent = match incoming.parent {
8790 Some(parent) => Some(self.bound_item(parent).await?.ok_or_else(|| {
8791 SourceError::Refused {
8792 message: format!(
8793 "GitHub project issue {} was not found on the board of source {}, so {} \
8794 cannot be filed under it",
8795 parent.0,
8796 self.name,
8797 what(incoming)
8798 ),
8799 }
8800 })?),
8801 None => None,
8802 };
8803 let parents_repository = parent
8804 .as_ref()
8805 .map(|parent| {
8806 // A draft is on the board and so is found, but it has no repository to
8807 // place a task in and GitHub gives it no sub-issues, so `addSubIssue`
8808 // would refuse the task only once `createIssue` had made it.
8809 if parent.content_kind == ContentKind::DraftIssue {
8810 return Err(SourceError::Refused {
8811 message: format!(
8812 "GitHub project item {} on the board of source {} is a draft, \
8813 which cannot have sub-issues, so {} cannot be filed under it",
8814 parent.id.0,
8815 self.name,
8816 what(incoming)
8817 ),
8818 });
8819 }
8820 // An issue's repository is where a sub-issue is placed and whose owner it
8821 // is compared against, so a parent whose repository this source cannot
8822 // spell as `owner/name` — GitHub's login grammar is wider than this
8823 // source's floor — is one nothing can be filed under.
8824 parent
8825 .own_repository
8826 .as_ref()
8827 .and_then(|origin| RepositoryTarget::from_origin(origin).ok())
8828 .ok_or_else(|| SourceError::Malformed {
8829 message: format!(
8830 "GitHub project issue {} on the board of source {} is in {}, which \
8831 is not a {}/owner/name repository this source can place {} in",
8832 parent.id.0,
8833 self.name,
8834 parent
8835 .own_repository
8836 .as_ref()
8837 .map_or("no repository", Repository::as_str),
8838 RepositoryTarget::HOST,
8839 what(incoming)
8840 ),
8841 })
8842 })
8843 .transpose()?;
8844 match incoming.repositories {
8845 [named] => {
8846 let target =
8847 RepositoryTarget::from_origin(named).map_err(|_| SourceError::Refused {
8848 message: format!(
8849 "{} names repository {}, which is not a {}/owner/name repository \
8850 source {} can create an issue in; name one that is, or name none",
8851 what(incoming),
8852 named.as_str(),
8853 RepositoryTarget::HOST,
8854 self.name
8855 ),
8856 })?;
8857 if let Some(parents) = &parents_repository
8858 && parents.owner != target.owner
8859 {
8860 return Err(SourceError::Refused {
8861 message: format!(
8862 "{} names repository {}, owned by {}, but its project's issue is in \
8863 {}, owned by {}, and GitHub files a sub-issue only in a repository \
8864 of the same owner as its parent issue; name a repository of {}, or \
8865 name none",
8866 what(incoming),
8867 target.slug(),
8868 target.owner,
8869 parents.slug(),
8870 parents.owner,
8871 parents.owner
8872 ),
8873 });
8874 }
8875 Ok(target)
8876 }
8877 _ => Ok(parents_repository.unwrap_or_else(|| fallback.clone())),
8878 }
8879 }
8880
8881 /// The node id of the repository `incoming` is being created in, or the refusal naming
8882 /// the item and the repository the token cannot see.
8883 ///
8884 /// Resolved once per command per repository; see [`Self::repository_cache`].
8885 async fn repository_id(
8886 &self,
8887 repository: &RepositoryTarget,
8888 incoming: &Incoming<'_>,
8889 ) -> Result<String, SourceError> {
8890 if let Some(id) = self.repository_cache()?.get(repository).cloned() {
8891 return Ok(id);
8892 }
8893 let data = self
8894 .graphql(
8895 graphql::REPOSITORY,
8896 json!({"owner":repository.owner,"name":repository.name}),
8897 )
8898 .await?;
8899 self.repository_read(&data, repository, incoming)
8900 }
8901
8902 /// The repository's node id out of an answer carrying the `repository` root, held for
8903 /// the rest of this command, or the refusal naming the item that cannot be created in it.
8904 fn repository_read(
8905 &self,
8906 data: &Value,
8907 repository: &RepositoryTarget,
8908 incoming: &Incoming<'_>,
8909 ) -> Result<String, SourceError> {
8910 let node = data
8911 .get("repository")
8912 .filter(|value| !value.is_null())
8913 .ok_or_else(|| SourceError::Refused {
8914 message: format!(
8915 "GitHub repository {} was not found or is not visible to the token, so {} \
8916 {:?} cannot be created in it",
8917 repository.slug(),
8918 incoming.written.kind().describes(),
8919 incoming.title
8920 ),
8921 })?;
8922 let id = required_str(node, "id")?.to_owned();
8923 self.repository_cache()?
8924 .insert(repository.clone(), id.clone());
8925 Ok(id)
8926 }
8927
8928 fn repository_cache(
8929 &self,
8930 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<RepositoryTarget, String>>, SourceError> {
8931 self.repository_cache
8932 .lock()
8933 .map_err(|_| SourceError::Unavailable {
8934 message: "this source's record of the destination repository was left \
8935 inconsistent by an earlier failure; next: run the command again"
8936 .into(),
8937 })
8938 }
8939
8940 /// Create or update one board item, whichever kind it is.
8941 async fn write_item(
8942 &self,
8943 incoming: &Incoming<'_>,
8944 target: Option<&NativeId>,
8945 depends_on: &[DependencyEdge],
8946 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
8947 let prepared = self.prepare_write(incoming, target, depends_on).await?;
8948 let landed = match &prepared.destination {
8949 // Its content is written last, by `complete_write`, once everything else has landed.
8950 WriteDestination::Existing(item) => Landed {
8951 content_id: item.id.clone(),
8952 item_id: Some(item.item_id.clone()),
8953 url: item.url.clone(),
8954 number: item.number,
8955 },
8956 WriteDestination::New(target) => {
8957 if self.deferring()? {
8958 self.create_filed_issue(
8959 prepared.board.id.as_str(),
8960 target,
8961 incoming,
8962 &prepared.body,
8963 )
8964 .await?
8965 } else {
8966 self.create_and_file_issue(
8967 prepared.board.id.as_str(),
8968 target,
8969 incoming,
8970 &prepared.body,
8971 )
8972 .await?
8973 }
8974 }
8975 };
8976 self.complete_write(incoming, prepared, landed).await
8977 }
8978
8979 /// Everything one write of `incoming` reads and decides before it sends anything: what is
8980 /// there now, where a new item is created, the board's fields, and every value refused while
8981 /// nothing has been written — the item's body included.
8982 async fn prepare_write(
8983 &self,
8984 incoming: &Incoming<'_>,
8985 target: Option<&NativeId>,
8986 depends_on: &[DependencyEdge],
8987 ) -> Result<Prepared, SourceError> {
8988 // Refused before anything is read or written: a task or a project titled the way
8989 // this board spells a document would land as an issue this same source reads back
8990 // as a document, so the field this destination cannot carry is named rather than
8991 // written and silently reclassified.
8992 if let Written::Work(kind, _) = incoming.written
8993 && incoming.title.starts_with(DESIGN_TITLE_PREFIX)
8994 {
8995 return Err(SourceError::Refused {
8996 message: format!(
8997 "the title of this {} begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
8998 spells a document, so it would read back as one rather than as a {}; \
8999 retitle it, or copy it as a document",
9000 kind.marker(),
9001 self.name,
9002 kind.marker()
9003 ),
9004 });
9005 }
9006 // The destination is read by its own id, and whether this board holds it is decided
9007 // by that read — its own `projectItems` — rather than by whether a listing of the
9008 // board happens to include it yet. See the module documentation.
9009 // An existing issue is never moved; a new one is created where the rule says — and
9010 // knowing where is what lets the board's fields and that repository's id be read
9011 // together, before anything below needs either.
9012 let destination = match target {
9013 Some(target) => {
9014 WriteDestination::Existing(Box::new(self.bound_item(target).await?.ok_or_else(
9015 || SourceError::Refused {
9016 message: format!("GitHub destination item {} was not found", target.0),
9017 },
9018 )?))
9019 }
9020 None => {
9021 let target = self.creation_target(incoming).await?;
9022 self.creation_context(&target, incoming).await?;
9023 WriteDestination::New(target)
9024 }
9025 };
9026 let existing = destination.existing();
9027 let board = self
9028 .fields_for(
9029 existing,
9030 incoming.written.status().is_some(),
9031 incoming
9032 .priority
9033 .is_some_and(|priority| priority != Priority::None),
9034 )
9035 .await?;
9036 let status_target = incoming
9037 .written
9038 .work_status()
9039 .map(|(kind, status)| self.resolved_target(kind, status.category))
9040 .transpose()?;
9041 let column = match (incoming.written.work_status(), status_target.as_ref()) {
9042 (Some((kind, status)), Some(target)) => {
9043 self.column_for(&board.fields, kind, status.category, target)?
9044 }
9045 _ => None,
9046 };
9047 // Resolved before anything is created, for the reason the column above is: a
9048 // priority this board has no option for is refused while nothing has been written.
9049 let priority_write = match incoming.priority {
9050 Some(priority) => self.priority_write(&board.fields, existing, priority)?,
9051 None => None,
9052 };
9053 // And for the reason the priority is: a value no projected field can hold, or a board
9054 // that cannot hold the field, is refused while nothing has been written.
9055 let (projections, projected) = self.projection_writes(
9056 &board.fields,
9057 existing.map(|item| &item.projected),
9058 incoming.metadata,
9059 None,
9060 )?;
9061 let content_kind = existing.map_or(ContentKind::Issue, |item| item.content_kind);
9062 if content_kind == ContentKind::DraftIssue {
9063 if let (Some(StatusTarget::Terminal(_, _)), Some(status)) =
9064 (status_target.as_ref(), incoming.written.status())
9065 {
9066 return Err(self.closes_a_draft(status.category));
9067 }
9068 if incoming.parent.is_some() {
9069 return Err(SourceError::Refused {
9070 message: "GitHub draft items cannot be a project's sub-issue".into(),
9071 });
9072 }
9073 }
9074 match existing {
9075 Some(item) if content_kind == ContentKind::Issue => {
9076 if item.labels != incoming.labels {
9077 return Err(SourceError::Refused {
9078 message: "GitHub issue labels differ from the labels being written".into(),
9079 });
9080 }
9081 }
9082 _ => {
9083 if !incoming.labels.is_empty() {
9084 return Err(SourceError::Refused {
9085 message: "GitHub items created by this destination carry no labels".into(),
9086 });
9087 }
9088 }
9089 }
9090
9091 // The repository the issue really lives in is what the slot below is written against,
9092 // so a single entry that is where the issue is created travels as no key at all, and
9093 // the read side derives it back from the issue.
9094 let own_repository = match &destination {
9095 WriteDestination::Existing(item) => item.own_repository.clone(),
9096 WriteDestination::New(target) => Some(
9097 Repository::try_from(target.origin())
9098 .map_err(|message| SourceError::Config { message })?,
9099 ),
9100 };
9101 let (native, fallback) = self
9102 .partition_edges(
9103 incoming.written.kind(),
9104 content_kind,
9105 existing.and_then(|item| item.blocked_by.as_deref()),
9106 depends_on,
9107 )
9108 .await?;
9109 let mut slot = slot_metadata(incoming, own_repository.as_ref(), &fallback);
9110 let content = match incoming.assets {
9111 Some(assets) => {
9112 let uploads = self.upload_assets(own_repository.as_ref(), assets).await?;
9113 let rewritten = onetaskgraph_plugin_api::serve_asset_references(
9114 incoming.content.unwrap_or_default(),
9115 &mut slot,
9116 &uploads,
9117 );
9118 incoming.content.map(|_| rewritten)
9119 }
9120 None => incoming.content.map(str::to_owned),
9121 };
9122 let body = compose_body(content.as_deref(), &slot)?;
9123 // Read before anything is created, for the reason the field below is: a value
9124 // this destination cannot store has to refuse, and refusing after `createIssue`
9125 // would leave an issue behind that nothing asked for. The engine writes a
9126 // qualified id here; a caller handing this key anything else is told so rather
9127 // than having it silently stored as no origin at all.
9128 // 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.
9129 let origin = match incoming.metadata.get(ORIGIN_KEY) {
9130 None => "",
9131 Some(Value::String(origin)) => origin.as_str(),
9132 Some(other) => {
9133 return Err(SourceError::Refused {
9134 message: format!(
9135 "{ORIGIN_KEY} holds a qualified id spelled as a string, and this item's \
9136 is {other}"
9137 ),
9138 });
9139 }
9140 };
9141 // Resolved before anything is created: a board that cannot carry the copy origin
9142 // has to refuse the write, and refusing it after `createIssue` would leave an
9143 // issue behind that nothing asked for.
9144 let origin_field = match Board::field(&board.fields, ORIGIN_FIELD)? {
9145 Some(field) => {
9146 if required_str(field, "__typename")? != "ProjectV2Field" {
9147 return Err(SourceError::Refused {
9148 message: format!(
9149 "GitHub board source-owned {ORIGIN_FIELD} field is not a text field"
9150 ),
9151 });
9152 }
9153 Some(required_str(field, "id")?.to_owned())
9154 }
9155 None if incoming.metadata.contains_key(ORIGIN_KEY) => {
9156 return Err(SourceError::Refused {
9157 message: format!(
9158 "GitHub board has no source-owned {ORIGIN_FIELD} text field, and the \
9159 item carries {ORIGIN_KEY}; add a text field named {ORIGIN_FIELD} to \
9160 the board"
9161 ),
9162 });
9163 }
9164 None => None,
9165 };
9166
9167 Ok(Prepared {
9168 origin: origin.to_owned(),
9169 destination,
9170 board,
9171 status_target,
9172 column,
9173 priority_write,
9174 projections,
9175 projected,
9176 content_kind,
9177 own_repository,
9178 native,
9179 slot,
9180 content,
9181 body,
9182 origin_field,
9183 })
9184 }
9185
9186 /// Everything one write does once the item it writes exists: its board fields, its
9187 /// relationships and — for an item that was already there — its content last, then what this
9188 /// process remembers of it.
9189 ///
9190 /// While this source is holding writes back — see [`TaskSource::begin_deferred_writes`] — an
9191 /// item this command created has its fields, its closing and its edges held for
9192 /// [`TaskSource::finish_writes`] rather than sent here.
9193 async fn complete_write(
9194 &self,
9195 incoming: &Incoming<'_>,
9196 prepared: Prepared,
9197 landed: Landed,
9198 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
9199 let Prepared {
9200 destination,
9201 board,
9202 status_target,
9203 column,
9204 priority_write,
9205 projections,
9206 projected,
9207 content_kind,
9208 own_repository,
9209 native,
9210 slot,
9211 content,
9212 body,
9213 origin,
9214 origin_field,
9215 } = prepared;
9216 let existing = destination.existing();
9217 let origin = origin.as_str();
9218 let Landed {
9219 content_id,
9220 item_id,
9221 url,
9222 number,
9223 } = landed;
9224
9225 // Only what differs from the item as this write read it is sent: a priority the item
9226 // already holds is not, so an unchanged re-copy writes no field and a person's edit of
9227 // it since that read is left alone.
9228 let priority_write = priority_write.filter(|_| {
9229 !existing.is_some_and(|item| {
9230 incoming.priority.map(HeldPriority::Read) == Some(item.priority.clone())
9231 })
9232 });
9233 let written_option = column.as_ref().map(|(_, _, name)| name.clone());
9234 let column = column
9235 .filter(|(_, _, name)| existing.is_none_or(|item| item.option.as_ref() != Some(name)))
9236 .map(|(field, option, _)| (field, option));
9237 // Creating an item here is several calls — `createIssue`, which files it on the
9238 // board, then its board fields, the parent and the dependencies — and GitHub can fail
9239 // at any of them. Everything this source can refuse *before* the first of those is
9240 // already checked above, so what is left is GitHub itself failing part way. When it
9241 // does over an item this call created, the issue is taken back: a write that
9242 // refused must not leave an item behind that nobody asked for, and one that does
9243 // makes the retry create a second.
9244 // Whether the board-field write carrying a moved origin was answered as landing whole.
9245 // When it was refused, GitHub does not say which of its fields ran before the one that
9246 // failed, so the origin may or may not have moved.
9247 let mut origin_landed = false;
9248 // An item this command created while writes are held back has every part that can land
9249 // later held for `finish_writes` — its own create filed it on the board and under its
9250 // project already — and so does a later write of it in the same command.
9251 let holding = (existing.is_none() && self.deferring()?) || self.holds_back(&content_id)?;
9252 let landed = if holding {
9253 self.hold_back(
9254 &board.id,
9255 &content_id,
9256 existing,
9257 origin_field.as_deref(),
9258 origin,
9259 column,
9260 status_target.as_ref(),
9261 priority_write.as_ref(),
9262 &projections,
9263 &native,
9264 )
9265 } else if let Some(item_id) = item_id.as_deref() {
9266 self.finish_write(
9267 board.id.as_str(),
9268 incoming,
9269 &content_id,
9270 item_id,
9271 content_kind,
9272 existing,
9273 origin_field.as_deref(),
9274 origin,
9275 column,
9276 status_target.as_ref(),
9277 priority_write.as_ref(),
9278 &projections,
9279 &native,
9280 &mut origin_landed,
9281 )
9282 .await
9283 } else {
9284 // An issue a create filed on the board itself has no board item this process
9285 // knows until `finish_writes` reads it, so nothing but a held-back write may land
9286 // on it before then.
9287 Err(SourceError::Malformed {
9288 message: format!(
9289 "issue {} was written before the board item GitHub filed it as was read",
9290 content_id.0
9291 ),
9292 })
9293 };
9294 // An existing item's title, body and state go last, in one `updateIssue`, once its board
9295 // fields and its relationships have landed: a refusal of any of those then leaves its
9296 // body — and the metadata slot inside it — exactly as it stood.
9297 let landed = match (landed, existing) {
9298 (Ok(()), Some(item)) => {
9299 self.update_existing(item, incoming, &body, status_target.as_ref())
9300 .await
9301 }
9302 (landed, _) => landed,
9303 };
9304 if let Err(error) = landed {
9305 match existing {
9306 // Best effort, and the write's own failure is what the caller is told: a
9307 // refusal naming the tidy-up would hide why the write failed at all.
9308 None => {
9309 let _ = self.delete_issue(&content_id).await;
9310 }
9311 // The origin field is the one piece of an existing item's metadata written
9312 // before its body, so a write refused after it puts it back as it was. When
9313 // that is refused too, the write's own failure is still what the caller is
9314 // told — with what it left behind added, because the item's metadata is then
9315 // not as it stood and a caller retrying has to know which key moved.
9316 Some(item) => {
9317 let before = item.origin.as_deref().unwrap_or("");
9318 if let Some(field) = origin_field.as_deref()
9319 && before != origin
9320 && let Err(restore) = self
9321 .set_item_field(
9322 board.id.as_str(),
9323 &item.item_id,
9324 field,
9325 json!({"text": before}),
9326 )
9327 .await
9328 {
9329 let left = if origin_landed {
9330 format!(
9331 "its {ORIGIN_KEY} was moved to {origin:?} before that and could \
9332 not be put back to {before:?} ({restore}), so item {} still \
9333 holds {origin:?} there",
9334 item.id.0
9335 )
9336 } else {
9337 format!(
9338 "the refused write carried its {ORIGIN_KEY} from {before:?} to \
9339 {origin:?}, GitHub does not say whether that part of it ran, \
9340 and putting it back to {before:?} was refused ({restore}), so \
9341 item {} holds {origin:?} or {before:?} there",
9342 item.id.0
9343 )
9344 };
9345 return Err(noting(
9346 error,
9347 &format!(
9348 "; {left}; next: set {ORIGIN_KEY} on it back to {before:?}, or \
9349 run the write again"
9350 ),
9351 ));
9352 }
9353 }
9354 }
9355 return Err(error);
9356 }
9357
9358 let written_status = match (incoming.written.work_status(), status_target.as_ref()) {
9359 (Some((kind, _)), Some(StatusTarget::Terminal(_, reason))) => {
9360 self.statuses
9361 .status(kind, written_option.as_deref(), true, Some(reason.reason()))
9362 }
9363 (Some((kind, _)), Some(StatusTarget::Column(_))) => {
9364 self.statuses
9365 .status(kind, written_option.as_deref(), false, None)
9366 }
9367 (Some((_, status)), _) => status.clone(),
9368 (None, _) => Status {
9369 category: StatusCategory::Unknown,
9370 name: "Open".to_owned(),
9371 },
9372 };
9373
9374 // So the rest of this command reads what it just did rather than what the board
9375 // said before it. See `remember_written` for which half takes it.
9376 let remembered = Resolved {
9377 // Empty for an issue whose board item is not read yet: `finish_writes` reads it
9378 // and `learn_item` puts it here.
9379 // llmlint: ignore[invalid_states_unrepresentable] `Resolved` is serialised into the cache's stored write context, so its field type is a stored shape this change may not move; the empty id lives only until `finish_writes` reads the board item in this same command, and nothing addresses it before then — `complete_write` refuses any write naming no board item.
9380 item_id: item_id.unwrap_or_default(),
9381 id: content_id.clone(),
9382 content_kind,
9383 kind: incoming.written.kind(),
9384 title: incoming.title.to_owned(),
9385 // The visible half of the body this write composed, split back off it the
9386 // way a read splits it — so what this record reports is what a read of the
9387 // same issue reports, rather than the person's text with the metadata slot
9388 // still on the end of it.
9389 body: metadata_body(body.clone())?.0,
9390 raw_body: body.clone(),
9391 // A document has no status of its own; what it reads back as is whatever
9392 // the issue's own state says, which is what a re-read reports.
9393 status: written_status,
9394 option: written_option.or_else(|| existing.and_then(|item| item.option.clone())),
9395 priority: match incoming.priority {
9396 Some(priority) => HeldPriority::Read(priority),
9397 None => existing.map_or(HeldPriority::Read(Priority::None), |item| {
9398 item.priority.clone()
9399 }),
9400 },
9401 // What `state_input` asked for: closed for a terminal target, open for any other
9402 // status, and the issue's own state left as it was by a document write.
9403 closed: content_kind == ContentKind::Issue
9404 && match status_target.as_ref() {
9405 Some(StatusTarget::Terminal(_, _)) => true,
9406 Some(_) => false,
9407 None => existing.is_some_and(|item| item.closed),
9408 },
9409 reason: match status_target.as_ref() {
9410 Some(StatusTarget::Terminal(_, reason)) if content_kind == ContentKind::Issue => {
9411 Some(reason.reason().to_owned())
9412 }
9413 Some(_) => None,
9414 None => existing.and_then(|item| item.reason.clone()),
9415 },
9416 delivers: incoming.delivers.to_vec(),
9417 delivered_by: incoming.delivered_by.to_vec(),
9418 labels: incoming.labels.to_vec(),
9419 parent: incoming.parent.cloned(),
9420 origin: (!origin.is_empty()).then(|| origin.to_owned()),
9421 projected,
9422 number,
9423 // In the update path this is the item's own url, read off `existing` where the
9424 // record above was bound, so one expression serves both halves.
9425 url,
9426 created_at: existing.and_then(|item| item.created_at),
9427 updated_at: existing.and_then(|item| item.updated_at),
9428 // What this write moved is GitHub's to say, so a record of it gives no token until
9429 // it is read again.
9430 item_updated_at: None,
9431 comment_count: None,
9432 relationship_events: None,
9433 served_at: None,
9434 facets: None,
9435 own_repository,
9436 repositories: incoming.repositories.to_vec(),
9437 classification: incoming.classification,
9438 slot,
9439 board_id: Some(board.id.as_str().to_owned()),
9440 fields: board
9441 .fields
9442 .get("nodes")
9443 .and_then(Value::as_array)
9444 .cloned()
9445 .unwrap_or_default(),
9446 board_fields: Some(board.fields.clone()),
9447 // What this write left the relationship holding is known by id alone, and a
9448 // later read of its edges needs each far end's kind, so it reads them again.
9449 blocked_by: None,
9450 };
9451 self.remember_written(remembered, existing.is_none())?;
9452 Ok(onetaskgraph_plugin_api::AssetsWritten {
9453 id: content_id,
9454 content,
9455 })
9456 }
9457
9458 /// Everything a write does after the item exists: its board fields, its parent, and
9459 /// its dependencies.
9460 ///
9461 /// Split out of `write_item` so there is one place a failure past the point of no
9462 /// return is caught, rather than a tidy-up repeated at each `?` above.
9463 // llmlint: ignore[suppressions_justified] This is the tail of `write_item` lifted out
9464 // so there is one place a failure past the point of no return is caught, and its
9465 // arguments are exactly the values that tail already had in scope. Bundling them into a
9466 // struct would describe no concept — it would be "the arguments of this function" — and
9467 // would put the whole of `write_item`'s locals behind one more indirection.
9468 #[allow(clippy::too_many_arguments)]
9469 async fn finish_write(
9470 &self,
9471 board_id: &str,
9472 incoming: &Incoming<'_>,
9473 content_id: &NativeId,
9474 item_id: &str,
9475 content_kind: ContentKind,
9476 existing: Option<&Resolved>,
9477 origin_field: Option<&str>,
9478 origin: &str,
9479 column: Option<(String, String)>,
9480 status_target: Option<&StatusTarget>,
9481 priority: Option<&PriorityWrite>,
9482 projections: &[ProjectionWrite],
9483 native: &[String],
9484 origin_landed: &mut bool,
9485 ) -> Result<(), SourceError> {
9486 let (fields, clears) = field_writes(
9487 existing,
9488 origin_field,
9489 origin,
9490 column,
9491 priority,
9492 projections,
9493 );
9494 self.set_item_fields(board_id, item_id, &fields, &clears)
9495 .await?;
9496 *origin_landed = true;
9497
9498 // An existing issue closes in the `updateIssue` its write ends with; one created just
9499 // now closes here, once its option is selected.
9500 if existing.is_none()
9501 && content_kind == ContentKind::Issue
9502 && matches!(status_target, Some(StatusTarget::Terminal(_, _)))
9503 {
9504 self.update_content(
9505 ContentKind::Issue,
9506 content_id,
9507 json!({"stateInput":state_input(status_target)}),
9508 )
9509 .await?;
9510 }
9511
9512 if content_kind == ContentKind::Issue {
9513 self.reparent(
9514 existing.and_then(|item| item.parent.clone()),
9515 content_id,
9516 incoming.parent,
9517 )
9518 .await?;
9519 // A document takes part in no dependency graph, so writing one neither reads
9520 // nor changes the issue's own `blockedBy` relationships. Reconciling them
9521 // against the empty list a document write carries would *delete* whatever
9522 // relationships a person had made on that issue, which is a write nobody
9523 // asked for.
9524 if incoming.written.kind() != BoardKind::Document {
9525 let issue = match existing {
9526 Some(item) => Issue::Existing(item.blocked_by.as_deref()),
9527 None => Issue::Created,
9528 };
9529 self.reconcile_blocked_by(content_id, native, issue).await?;
9530 }
9531 }
9532 Ok(())
9533 }
9534
9535 /// Whether this source is holding writes back — see [`TaskSource::begin_deferred_writes`].
9536 fn deferring(&self) -> Result<bool, SourceError> {
9537 Ok(self.deferred()?.is_some())
9538 }
9539
9540 /// Whether `content` is an item this command created whose parts are held back.
9541 fn holds_back(&self, content: &NativeId) -> Result<bool, SourceError> {
9542 Ok(self
9543 .deferred()?
9544 .as_ref()
9545 .is_some_and(|deferred| deferred.holds(content)))
9546 }
9547
9548 fn deferred(&self) -> Result<std::sync::MutexGuard<'_, Option<Deferred>>, SourceError> {
9549 self.deferred.lock().map_err(|_| SourceError::Unavailable {
9550 message: "this source's record of the writes it is holding back was left \
9551 inconsistent by an earlier failure; next: run the command again"
9552 .into(),
9553 })
9554 }
9555
9556 /// Creates one issue filed on the board and under its project by the `createIssue` itself —
9557 /// `projectV2Ids` naming the board and `parentIssueId` the project — which is what a copy
9558 /// creates with: one request where adding it to the board and filing it under its project
9559 /// were two more. GitHub adds the board item after answering, so its id is not known here;
9560 /// [`TaskSource::finish_writes`] reads it.
9561 async fn create_filed_issue(
9562 &self,
9563 board_id: &str,
9564 repository: &RepositoryTarget,
9565 incoming: &Incoming<'_>,
9566 body: &Option<String>,
9567 ) -> Result<Landed, SourceError> {
9568 let repository_id = self.repository_id(repository, incoming).await?;
9569 let data = self
9570 .graphql(
9571 graphql::CREATE_ISSUE,
9572 json!({"input": filed_input(&repository_id, board_id, incoming, body)}),
9573 )
9574 .await?;
9575 let created = data
9576 .pointer("/createIssue/issue")
9577 .filter(|value| !value.is_null())
9578 .ok_or_else(|| SourceError::Malformed {
9579 message: "GitHub issue creation returned no issue".into(),
9580 })?;
9581 self.created_landed(created).await
9582 }
9583
9584 /// Keep the address `createIssue` answered for the issue `content`, for
9585 /// [`TaskSource::written_location`].
9586 fn note_written(&self, content: &NativeId, url: Option<&str>) {
9587 if let Some(url) = url {
9588 self.written
9589 .lock()
9590 .unwrap_or_else(std::sync::PoisonError::into_inner)
9591 .insert(content.clone(), url.to_owned());
9592 }
9593 }
9594
9595 /// What one `createIssue` answered, as the item it created — or, when its number cannot be
9596 /// read, the refusal, after taking the issue back.
9597 async fn created_landed(&self, created: &Value) -> Result<Landed, SourceError> {
9598 let content_id = NativeId(required_nonblank_str(created, "id")?.to_owned());
9599 let url = optional_str(created, "url")?.map(str::to_owned);
9600 let number = match created_issue_number(created) {
9601 Ok(number) => number,
9602 Err(error) => {
9603 let _ = self.delete_issue(&content_id).await;
9604 return Err(error);
9605 }
9606 };
9607 self.note_written(&content_id, url.as_deref());
9608 Ok(Landed {
9609 content_id,
9610 item_id: None,
9611 url,
9612 number,
9613 })
9614 }
9615
9616 /// Hold back everything a write of the created item `content` would send after creating it,
9617 /// for [`TaskSource::finish_writes`]: the same field values, closing and edges
9618 /// `finish_write` sends, the parent excepted, which its create already named. A later write
9619 /// of the same item replaces what it changes.
9620 // llmlint: ignore[suppressions_justified] The arguments are `finish_write`'s, which this holds back instead of sending, and they are exactly the values `complete_write` has in scope; bundling them would describe no concept.
9621 #[allow(clippy::too_many_arguments)]
9622 fn hold_back(
9623 &self,
9624 board_id: &BoardId,
9625 content: &NativeId,
9626 existing: Option<&Resolved>,
9627 origin_field: Option<&str>,
9628 origin: &str,
9629 column: Option<(String, String)>,
9630 status_target: Option<&StatusTarget>,
9631 priority: Option<&PriorityWrite>,
9632 projections: &[ProjectionWrite],
9633 native: &[String],
9634 ) -> Result<(), SourceError> {
9635 let status = column.map(|(field, option)| {
9636 let name = self
9637 .fields_cache()
9638 .ok()
9639 .and_then(|fields| {
9640 fields.as_ref().and_then(|board| {
9641 option_name(&board.fields, &field, &option).map(str::to_owned)
9642 })
9643 })
9644 .unwrap_or_default();
9645 (field, option, name)
9646 });
9647 let (fields, clears) =
9648 field_writes(existing, origin_field, origin, None, priority, projections);
9649 let close = match status_target {
9650 Some(StatusTarget::Terminal(_, reason)) => Some(*reason),
9651 _ => None,
9652 };
9653 let mut deferred = self.deferred()?;
9654 let deferred = deferred.get_or_insert_with(Deferred::default);
9655 if let Deferred::Nothing = deferred {
9656 *deferred = Deferred::Held {
9657 board: board_id.clone(),
9658 created: Vec::new(),
9659 };
9660 }
9661 let Deferred::Held { created, .. } = deferred else {
9662 unreachable!("held back on the line above");
9663 };
9664 let held = match created.iter().position(|held| held.content == *content) {
9665 Some(at) => &mut created[at],
9666 None => {
9667 created.push(HeldBack {
9668 content: content.clone(),
9669 fields: Vec::new(),
9670 status: None,
9671 clears: Vec::new(),
9672 close: None,
9673 edges: Vec::new(),
9674 });
9675 created.last_mut().expect("just held")
9676 }
9677 };
9678 for (field, value) in fields {
9679 held.fields.retain(|(held, _)| *held != field);
9680 held.clears.retain(|held| *held != field);
9681 held.fields.push((field, value));
9682 }
9683 for field in clears {
9684 held.fields.retain(|(held, _)| held != field);
9685 if !held.clears.iter().any(|held| held == field) {
9686 held.clears.push(field.to_owned());
9687 }
9688 }
9689 if status.is_some() {
9690 held.status = status;
9691 }
9692 if close.is_some() {
9693 held.close = close;
9694 }
9695 // Nothing of an item created in this command has been sent but its create, so the edges
9696 // it is to have are exactly the ones its latest write names.
9697 held.edges = native.iter().map(|far| NativeId(far.clone())).collect();
9698 Ok(())
9699 }
9700
9701 /// Create every task of `writes`, together, filed on the board and under each one's
9702 /// project: [`graphql::CREATE_ISSUES`], [`MUTATION_BATCH`] to a request.
9703 ///
9704 /// Each is prepared as [`Self::write_item`] prepares one — every refusal a write owes made
9705 /// before the first request — then created, then completed with its parts held back. A
9706 /// request refused part way leaves the issues it did create, which are taken back, with the
9707 /// rest of this call's, before the refusal is answered.
9708 async fn create_together(
9709 &self,
9710 writes: &[ItemWrite<Task>],
9711 ) -> Result<Vec<NativeId>, SourceError> {
9712 let incomings: Vec<Incoming<'_>> = writes
9713 .iter()
9714 .map(|write| self.task_incoming(write, None))
9715 .collect::<Result<_, _>>()?;
9716 let mut prepared = Vec::with_capacity(writes.len());
9717 for (incoming, write) in incomings.iter().zip(writes) {
9718 if write.target.is_some() {
9719 return Err(SourceError::Malformed {
9720 message: "a write naming its target was handed to a batch of creates".into(),
9721 });
9722 }
9723 prepared.push(
9724 self.prepare_write(incoming, None, &write.depends_on)
9725 .await?,
9726 );
9727 }
9728 let mut inputs = Vec::with_capacity(prepared.len());
9729 for (incoming, prepared) in incomings.iter().zip(&prepared) {
9730 let WriteDestination::New(target) = &prepared.destination else {
9731 return Err(SourceError::Malformed {
9732 message: "an update was decided for a write handed to a batch of creates"
9733 .into(),
9734 });
9735 };
9736 let repository_id = self.repository_id(target, incoming).await?;
9737 inputs.push(filed_input(
9738 &repository_id,
9739 prepared.board.id.as_str(),
9740 incoming,
9741 &prepared.body,
9742 ));
9743 }
9744 let mut landed: Vec<Landed> = Vec::with_capacity(inputs.len());
9745 let refused = 'create: {
9746 for chunk in inputs.chunks(MUTATION_BATCH) {
9747 let mut variables = serde_json::Map::new();
9748 for slot in 0..MUTATION_BATCH {
9749 variables.insert(
9750 format!("create{slot}"),
9751 chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
9752 );
9753 variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
9754 }
9755 let data = match self
9756 .graphql(graphql::CREATE_ISSUES, Value::Object(variables))
9757 .await
9758 {
9759 Ok(data) => data,
9760 Err(error) => break 'create Some(error),
9761 };
9762 let mut refusal = data.get(ANSWER_ERRORS).map(|errors| {
9763 let said: Vec<&str> = errors
9764 .as_array()
9765 .into_iter()
9766 .flatten()
9767 .filter_map(|error| error.get("message").and_then(Value::as_str))
9768 .collect();
9769 SourceError::Refused {
9770 message: if said.is_empty() {
9771 "GitHub returned GraphQL errors".to_owned()
9772 } else {
9773 said.join("; ")
9774 },
9775 }
9776 });
9777 for slot in 0..chunk.len() {
9778 match data
9779 .pointer(&format!("/create{slot}/issue"))
9780 .filter(|value| !value.is_null())
9781 {
9782 Some(created) => match self.created_landed(created).await {
9783 Ok(created) => landed.push(created),
9784 Err(error) => {
9785 refusal.get_or_insert(error);
9786 }
9787 },
9788 // An alias GitHub refused answers nothing, and the refusal says why.
9789 None => {
9790 refusal.get_or_insert(SourceError::Malformed {
9791 message: "GitHub issue creation returned no issue".into(),
9792 });
9793 }
9794 }
9795 }
9796 if let Some(error) = refusal {
9797 break 'create Some(error);
9798 }
9799 }
9800 None
9801 };
9802 if let Some(error) = refused {
9803 // None of these ids reaches the caller, so an issue GitHub will not take back is
9804 // named here or by nobody.
9805 let mut left: Vec<&str> = Vec::new();
9806 for created in &landed {
9807 if self.delete_issue(&created.content_id).await.is_err() {
9808 left.push(created.content_id.0.as_str());
9809 }
9810 }
9811 return Err(left_behind(error, &left));
9812 }
9813 let created: Vec<NativeId> = landed
9814 .iter()
9815 .map(|landed| landed.content_id.clone())
9816 .collect();
9817 let mut ids = Vec::with_capacity(landed.len());
9818 for ((incoming, prepared), landed) in incomings.iter().zip(prepared).zip(landed) {
9819 match self.complete_write(incoming, prepared, landed).await {
9820 Ok(written) => ids.push(written.id),
9821 // llmlint: ignore[changed_behavior_has_e2e] While writes are held back, which is the only time a batch is created, completing a created item only holds its parts back, and that fails on nothing but a poisoned lock, which no journey can cause; the issues are taken back regardless, because the caller is never handed their ids.
9822 Err(error) => {
9823 let mut left: Vec<&str> = Vec::new();
9824 for id in &created {
9825 if self.delete_issue(id).await.is_err() {
9826 left.push(id.0.as_str());
9827 }
9828 }
9829 return Err(left_behind(error, &left));
9830 }
9831 }
9832 }
9833 Ok(ids)
9834 }
9835
9836 /// Send everything held back since [`TaskSource::begin_deferred_writes`]: one read of the
9837 /// created items' board items, then their field values, closes and edges, each kind in
9838 /// requests of [`MUTATION_BATCH`]. Anything refused takes back every issue held, and
9839 /// answers the refusal.
9840 async fn send_held_back(&self) -> Result<(), SourceError> {
9841 let Some(Deferred::Held { board, created }) = self.deferred()?.take() else {
9842 return Ok(());
9843 };
9844 if created.is_empty() {
9845 return Ok(());
9846 }
9847 let sent = self.send_deferred(board.as_str(), &created).await;
9848 if let Err(error) = sent {
9849 // Best effort, and the failure is what the caller is told, as a write of one item
9850 // that fails part way takes back what it created: the copy that held these back
9851 // journalled every one, so one this cannot take back its undo tries again, and says
9852 // so when it cannot either.
9853 for held in &created {
9854 let _ = self.delete_issue(&held.content).await;
9855 }
9856 return Err(error);
9857 }
9858 Ok(())
9859 }
9860
9861 /// The requests [`Self::send_held_back`] makes.
9862 async fn send_deferred(&self, board: &str, created: &[HeldBack]) -> Result<(), SourceError> {
9863 let items = self.created_board_items(board, created).await?;
9864 let mut fields: Vec<Value> = Vec::new();
9865 let mut closes: Vec<Value> = Vec::new();
9866 let mut edges: Vec<Value> = Vec::new();
9867 for held in created {
9868 let (item, status) = &items[&held.content];
9869 let mut values = held.fields.clone();
9870 // A status the board already shows — set by a workflow a person turned on to file
9871 // new items at it — is not written again.
9872 if let Some((field, option, name)) = &held.status
9873 && status.as_deref() != Some(name.as_str())
9874 {
9875 values.insert(0, (field.clone(), json!({"singleSelectOptionId": option})));
9876 }
9877 for (field, value) in values {
9878 fields.push(json!({"projectId":board,"itemId":item,"fieldId":field,"value":value}));
9879 }
9880 if let Some(reason) = held.close {
9881 closes.push(json!({"id": held.content.0, "stateInput": closed_input(reason)}));
9882 }
9883 for far in &held.edges {
9884 edges.push(json!({"issueId": held.content.0, "blockingIssueId": far.0}));
9885 }
9886 if !held.clears.is_empty() {
9887 let clears: Vec<&str> = held.clears.iter().map(String::as_str).collect();
9888 self.set_item_fields(board, item, &[], &clears).await?;
9889 }
9890 }
9891 // Each alias answers with what it wrote, which is what its input named: the board item a
9892 // field value is set on, the issue closed, the issue blocked and the one blocking it.
9893 let field_answer: &[(&str, &str)] = &[("projectV2Item", "itemId")];
9894 let close_answer: &[(&str, &str)] = &[("issue", "id")];
9895 let block_answer: &[(&str, &str)] =
9896 &[("issue", "issueId"), ("blockingIssue", "blockingIssueId")];
9897 for (document, prefix, inputs, answers) in [
9898 (graphql::WRITE_FIELD_VALUES, "field", &fields, field_answer),
9899 (graphql::CLOSE_ISSUES, "close", &closes, close_answer),
9900 (graphql::ADD_BLOCKED_BYS, "block", &edges, block_answer),
9901 ] {
9902 for chunk in inputs.chunks(MUTATION_BATCH) {
9903 let mut variables = serde_json::Map::new();
9904 for slot in 0..MUTATION_BATCH {
9905 variables.insert(
9906 format!("{prefix}{slot}"),
9907 chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
9908 );
9909 variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
9910 }
9911 let data = self.graphql(document, Value::Object(variables)).await?;
9912 for (slot, input) in chunk.iter().enumerate() {
9913 for (root, named) in answers {
9914 let answered = data
9915 .pointer(&format!("/{prefix}{slot}/{root}/id"))
9916 .and_then(Value::as_str)
9917 .ok_or_else(|| SourceError::Malformed {
9918 message: format!(
9919 "GitHub answered {} with nothing at {prefix}{slot}",
9920 operation_description(document)
9921 ),
9922 })?;
9923 let asked = input.get(named).and_then(Value::as_str).unwrap_or_default();
9924 if answered != asked {
9925 return Err(SourceError::Malformed {
9926 message: format!(
9927 "GitHub answered {} at {prefix}{slot} with {answered}, which \
9928 is not {asked}, the item it was asked to write",
9929 operation_description(document)
9930 ),
9931 });
9932 }
9933 }
9934 }
9935 }
9936 }
9937 for held in created {
9938 self.learn_item(&held.content, &items[&held.content].0)?;
9939 }
9940 Ok(())
9941 }
9942
9943 /// The board item each of `created` is on this board, with its `Status` as the board set it:
9944 /// [`graphql::CREATED_BOARD_ITEMS`], read again — after a wait of a second, then two, four,
9945 /// eight and sixteen — while GitHub has not filed one yet.
9946 async fn created_board_items(
9947 &self,
9948 board: &str,
9949 created: &[HeldBack],
9950 ) -> Result<BTreeMap<NativeId, (String, Option<String>)>, SourceError> {
9951 let mut found: BTreeMap<NativeId, (String, Option<String>)> = BTreeMap::new();
9952 let mut wait = Duration::from_secs(1);
9953 for attempt in 0..6 {
9954 let unfiled: Vec<&NativeId> = created
9955 .iter()
9956 .map(|held| &held.content)
9957 .filter(|id| !found.contains_key(*id))
9958 .collect();
9959 if unfiled.is_empty() {
9960 return Ok(found);
9961 }
9962 if attempt > 0 {
9963 self.clock
9964 .sleep_because(wait, pacing::cause::BOARD_FILING)
9965 .await;
9966 wait = wait.saturating_mul(2);
9967 }
9968 for chunk in unfiled.chunks(COPY_DETAIL_BATCH) {
9969 let mut variables = serde_json::Map::new();
9970 for slot in 0..COPY_DETAIL_BATCH {
9971 variables.insert(
9972 format!("id{slot}"),
9973 json!(chunk.get(slot).unwrap_or(&chunk[0]).0),
9974 );
9975 variables.insert(format!("read{slot}"), json!(slot < chunk.len()));
9976 }
9977 variables.insert("boardItems".into(), json!(BOARD_ITEMS_PAGE_SIZE));
9978 variables.insert("statusName".into(), json!(STATUS_FIELD));
9979 let data = self
9980 .graphql(graphql::CREATED_BOARD_ITEMS, Value::Object(variables))
9981 .await?;
9982 for (slot, id) in chunk.iter().enumerate() {
9983 // An answer for another issue than the one asked about says nothing of
9984 // where that one is filed, and its board item is not this one's.
9985 let node = data.get(format!("i{slot}")).filter(|node| !node.is_null());
9986 let named = node.map(|node| node.get("id").and_then(Value::as_str));
9987 if let Some(named) = named
9988 && named != Some(id.0.as_str())
9989 {
9990 return Err(SourceError::Malformed {
9991 message: format!(
9992 "GitHub answered the board items of {} when asked for those of \
9993 {}",
9994 named.unwrap_or("an issue it did not name"),
9995 id.0
9996 ),
9997 });
9998 }
9999 // An issue GitHub does not answer yet is not filed yet; one it answers is
10000 // read whole, its connection, each board item's board and its status, and
10001 // any of them unreadable is refused rather than read as not filed.
10002 let Some(node) = node else { continue };
10003 let malformed = |what: &str| SourceError::Malformed {
10004 message: format!("GitHub answered the board items of {} with {what}", id.0),
10005 };
10006 let nodes = node
10007 .pointer("/projectItems/nodes")
10008 .and_then(Value::as_array)
10009 .ok_or_else(|| malformed("no list of board items"))?;
10010 let mut item = None;
10011 for node in nodes {
10012 let on = node
10013 .pointer("/project/id")
10014 .and_then(Value::as_str)
10015 .ok_or_else(|| malformed("a board item naming no board"))?;
10016 if on == board {
10017 item = Some(node);
10018 }
10019 }
10020 if let Some(item) = item {
10021 let status = match item.get("status") {
10022 None | Some(Value::Null) => None,
10023 Some(status) => Some(
10024 status
10025 .get("name")
10026 .and_then(Value::as_str)
10027 .ok_or_else(|| malformed("a status that names no option"))?
10028 .to_owned(),
10029 ),
10030 };
10031 found.insert(
10032 (*id).clone(),
10033 (required_nonblank_str(item, "id")?.to_owned(), status),
10034 );
10035 }
10036 }
10037 }
10038 }
10039 let unfiled: Vec<&str> = created
10040 .iter()
10041 .map(|held| held.content.0.as_str())
10042 .filter(|id| !found.keys().any(|found| found.0 == *id))
10043 .collect();
10044 // The last read may be the one that finds the rest.
10045 if unfiled.is_empty() {
10046 return Ok(found);
10047 }
10048 Err(SourceError::Unavailable {
10049 message: format!(
10050 "GitHub created {} filed on board {board} and has not added {} to it after 31 \
10051 seconds: {}; next: run the copy again once GitHub has caught up",
10052 if unfiled.len() == 1 {
10053 "an issue"
10054 } else {
10055 "issues"
10056 },
10057 if unfiled.len() == 1 { "it" } else { "them" },
10058 unfiled.join(", ")
10059 ),
10060 })
10061 }
10062
10063 /// The board item id of `content`, which this process created and remembered without one,
10064 /// in every half of its own view.
10065 fn learn_item(&self, content: &NativeId, item: &str) -> Result<(), SourceError> {
10066 if let Some(held) = self.resolved_cache()?.get_mut(content) {
10067 held.item_id = item.to_owned();
10068 }
10069 if let Some(held) = self.created()?.iter_mut().find(|held| held.id == *content) {
10070 held.item_id = item.to_owned();
10071 }
10072 Ok(())
10073 }
10074
10075 /// Ask together which items each of `origins` names, and what creating an item reads; see
10076 /// [`TaskSource::read_ahead_origins_for_copy`]. An origin whose answer runs past its first
10077 /// page is left to its own lookup.
10078 async fn origins_ahead(&self, origins: &[String]) -> Result<(), SourceError> {
10079 let Some(repository) = self.repository.clone() else {
10080 return Ok(());
10081 };
10082 let unasked: Vec<&String> = {
10083 let held = self.narrowed_cache()?;
10084 let mut unasked: Vec<&String> = Vec::new();
10085 for origin in origins {
10086 if !held.contains_key(&Narrowing::Origin(origin.clone()).key())
10087 && !unasked.contains(&origin)
10088 {
10089 unasked.push(origin);
10090 }
10091 }
10092 unasked
10093 };
10094 if unasked.is_empty() {
10095 return Ok(());
10096 }
10097 for chunk in unasked.chunks(ORIGIN_BATCH) {
10098 let mut variables = json!({"owner":self.owner,"number":self.project_number,
10099 "type":"ISSUE","originFirst":ORIGIN_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
10100 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true,
10101 "repositoryOwner":repository.owner,"repositoryName":repository.name});
10102 for slot in 0..ORIGIN_BATCH {
10103 let origin = chunk.get(slot).unwrap_or(&chunk[0]);
10104 variables[format!("filter{slot}")] =
10105 json!(format!("{ORIGIN_FIELD}:{}", quoted(origin)));
10106 variables[format!("search{slot}")] = json!(
10107 self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))))
10108 );
10109 variables[format!("ask{slot}")] = json!(slot < chunk.len());
10110 }
10111 let data = self.graphql(graphql::ORIGIN_LOOKUPS, variables).await?;
10112 self.fields_read(&data)?;
10113 if let Some(node) = data.get("repository").filter(|value| !value.is_null()) {
10114 let id = required_nonblank_str(node, "id")?.to_owned();
10115 self.repository_cache()?.insert(repository.clone(), id);
10116 if let Some(numeric) = node
10117 .get("databaseId")
10118 .and_then(Value::as_u64)
10119 .and_then(std::num::NonZeroU64::new)
10120 {
10121 self.numeric_repositories
10122 .lock()
10123 .await
10124 .insert(repository.clone(), numeric);
10125 }
10126 }
10127 for (slot, origin) in chunk.iter().enumerate() {
10128 let items = data
10129 .pointer(&format!("/o{slot}/projectV2/items"))
10130 .filter(|value| !value.is_null())
10131 .ok_or_else(|| SourceError::Refused {
10132 message: format!(
10133 "GitHub project {}/{} was not found or is not visible to the token",
10134 self.owner, self.project_number
10135 ),
10136 })?;
10137 let searched =
10138 data.get(format!("s{slot}"))
10139 .ok_or_else(|| SourceError::Malformed {
10140 message: "GitHub search response has no search connection".into(),
10141 })?;
10142 if resumed(items, None)?.has_more() || resumed(searched, None)?.has_more() {
10143 continue;
10144 }
10145 let mut found: Vec<Resolved> = Vec::new();
10146 for item in optional_nodes(Some(items), "project items")?
10147 .into_iter()
10148 .flatten()
10149 {
10150 if let Some(resolved) = self.resolve(item)?
10151 && resolved.content_kind == ContentKind::Issue
10152 && !found.iter().any(|held| held.id == resolved.id)
10153 {
10154 found.push(resolved);
10155 }
10156 }
10157 for node in optional_nodes(Some(searched), "search")?
10158 .into_iter()
10159 .flatten()
10160 {
10161 if let Some(resolved) = self.resolve_issue(node).await?
10162 && !found.iter().any(|held| held.id == resolved.id)
10163 {
10164 found.push(resolved);
10165 }
10166 }
10167 self.narrowed_cache()?
10168 .insert(Narrowing::Origin((*origin).clone()).key(), found);
10169 }
10170 }
10171 Ok(())
10172 }
10173
10174 /// Delete one issue, which takes its board item with it.
10175 async fn delete_issue(&self, id: &NativeId) -> Result<(), SourceError> {
10176 let data = self
10177 .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
10178 .await?;
10179 data.pointer("/deleteIssue/repository")
10180 .filter(|value| !value.is_null())
10181 .ok_or_else(|| SourceError::Malformed {
10182 message: "GitHub issue deletion returned no repository".into(),
10183 })?;
10184 self.forget(id)?;
10185 Ok(())
10186 }
10187
10188 /// Remove one item this copy created, so a copy that could not finish leaves the board
10189 /// as it found it.
10190 ///
10191 /// Deleting the issue takes its board item with it, so there is no second mutation to
10192 /// keep in step. An id the board does not hold is not an error: the item is already
10193 /// gone, which is the state this asks for. Which that is, is decided by reading the item
10194 /// by its own id — a listing of the board can still be missing an item it holds, and
10195 /// reading that as *already gone* would leave behind the very item this was asked to
10196 /// take back.
10197 async fn delete_item(&self, id: &NativeId) -> Result<(), SourceError> {
10198 let Some(item) = self.bound_item(id).await? else {
10199 return Ok(());
10200 };
10201 if item.content_kind == ContentKind::DraftIssue {
10202 return Err(SourceError::Refused {
10203 message: format!(
10204 "GitHub item {} is a draft, and this source removes an item by deleting \
10205 its issue; next: remove it from the board by hand",
10206 id.0
10207 ),
10208 });
10209 }
10210 let data = self
10211 .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
10212 .await?;
10213 data.pointer("/deleteIssue/repository")
10214 .filter(|value| !value.is_null())
10215 .ok_or_else(|| SourceError::Malformed {
10216 message: "GitHub issue deletion returned no repository".into(),
10217 })?;
10218 self.forget(id)?;
10219 Ok(())
10220 }
10221
10222 /// The issue a comment call on `task` is about, or `None` when this board holds no such
10223 /// task.
10224 ///
10225 /// Resolved exactly as [`TaskSource::get_task`] resolves it, so the comment verbs and a
10226 /// read of the task cannot disagree about which ids name one: a project or a document of
10227 /// this board is not a task here either.
10228 ///
10229 /// A **draft** is a task with nowhere to keep a comment, because GitHub keeps comments on
10230 /// issues and a draft is not one. It is refused rather than answered with an empty page,
10231 /// which would read as a task nobody has commented on yet.
10232 async fn commented_issue(&self, task: &NativeId) -> Result<Option<NativeId>, SourceError> {
10233 let cached = self.resolved_cache()?.get(task).cloned();
10234 let Some(item) = (match cached {
10235 Some(item) => Some(item),
10236 None => self.item_by_id(task).await?,
10237 })
10238 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
10239 return Ok(None);
10240 };
10241 if item.content_kind == ContentKind::DraftIssue {
10242 return Err(self.draft_has_no_comments(task));
10243 }
10244 Ok(Some(item.id))
10245 }
10246
10247 /// The refusal a comment call on a board draft is answered with: GitHub keeps comments on
10248 /// issues, and a draft is not one.
10249 fn draft_has_no_comments(&self, task: &NativeId) -> SourceError {
10250 SourceError::Refused {
10251 message: format!(
10252 "task {} of source {} is a draft item on the board, and GitHub keeps \
10253 comments on issues alone, so a draft has none to read or write; next: \
10254 convert the draft to an issue on the board, then comment on the issue it \
10255 becomes",
10256 task.0, self.name
10257 ),
10258 }
10259 }
10260
10261 /// One task and a page of its comments, read with [`graphql::ISSUE_DETAIL`] in one
10262 /// request — or `None` when this board holds no task by that id.
10263 ///
10264 /// What `task show` and a comment listing read. A draft is a task with no comments, so it
10265 /// is answered with the draft and the refusal, at the price of the draft's own read.
10266 async fn issue_detail(
10267 &self,
10268 id: &NativeId,
10269 page: &PageRequest,
10270 ) -> Result<Option<TaskDetailRead>, SourceError> {
10271 let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
10272 let asked = self
10273 .graphql(
10274 graphql::ISSUE_DETAIL,
10275 json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),"after":after,
10276 "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
10277 "duplicates":true}),
10278 )
10279 .await;
10280 let data = match asked {
10281 Ok(data) => data,
10282 Err(error) if unresolvable_node(&error) => return Ok(None),
10283 Err(error) => return Err(error),
10284 };
10285 // `node` is null for an id that names nothing, and absent only from an answer this
10286 // source cannot read — never the same thing.
10287 let node = data.get("node").ok_or_else(|| SourceError::Malformed {
10288 message: format!("GitHub answered the read of {} with no node", id.0),
10289 })?;
10290 self.detail_of(id, node, true, after).await
10291 }
10292
10293 /// Several tasks, each with the first page of its comments when `comments` is set, read
10294 /// [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] — one answer per id, in
10295 /// order.
10296 ///
10297 /// A batch GitHub refuses because one of its ids resolves to no node at all is read again
10298 /// one item at a time, so that id is answered as missing and the others as themselves; any
10299 /// other refusal is every id of that batch's answer.
10300 async fn issue_details(
10301 &self,
10302 ids: &[NativeId],
10303 comments: Option<&PageRequest>,
10304 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
10305 let mut read = Vec::with_capacity(ids.len());
10306 for batch in ids.chunks(DETAIL_BATCH) {
10307 match self
10308 .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, comments))
10309 .await
10310 {
10311 Ok(data) => {
10312 for (slot, id) in batch.iter().enumerate() {
10313 // Every alias asked for is answered, null for an id naming nothing;
10314 // one missing is an answer this source cannot read.
10315 let read_one = match data.get(format!("i{slot}")) {
10316 Some(node) => self.detail_of(id, node, comments.is_some(), None).await,
10317 None => Err(SourceError::Malformed {
10318 message: format!(
10319 "GitHub answered a batch read with no item for {}",
10320 id.0
10321 ),
10322 }),
10323 };
10324 read.push(read_one);
10325 }
10326 }
10327 Err(error) if unresolvable_node(&error) => {
10328 for id in batch {
10329 read.push(match comments {
10330 Some(page) => self.issue_detail(id, page).await,
10331 None => self.task_read(id).await,
10332 });
10333 }
10334 }
10335 Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
10336 }
10337 }
10338 read
10339 }
10340
10341 /// One task and nothing of its comments, as [`TaskSource::get_task`] reads it.
10342 async fn task_read(&self, id: &NativeId) -> Result<Option<TaskDetailRead>, SourceError> {
10343 Ok(self.get_task(id).await?.map(|task| TaskDetailRead {
10344 task,
10345 comments: None,
10346 }))
10347 }
10348
10349 /// What one node a detail read reached says: the task this board holds by `id`, with the
10350 /// page of comments the node carries when `commented` — or `None` for a node that is no
10351 /// task of this board.
10352 ///
10353 /// Resolved as [`Self::item_by_id`] resolves an item: a draft is read again as a draft,
10354 /// and an item this process created answers from this process's own record, which a node
10355 /// read taken moments after the write can still be behind.
10356 async fn detail_of(
10357 &self,
10358 id: &NativeId,
10359 node: &Value,
10360 commented: bool,
10361 after: Option<&str>,
10362 ) -> Result<Option<TaskDetailRead>, SourceError> {
10363 if node.is_null() {
10364 return Ok(None);
10365 }
10366 let draft = optional_str(node, "__typename")? == Some("DraftIssue");
10367 // An issue answered under one id is that id's, or the answer is not one this source
10368 // can report: reporting another issue's task and comments under the qualified id asked
10369 // for would be the one wrong answer here. A draft's own read checks the same.
10370 if !draft
10371 && optional_str(node, "__typename")? == Some("Issue")
10372 && required_str(node, "id")? != id.0
10373 {
10374 return Err(SourceError::Malformed {
10375 message: format!(
10376 "GitHub answered the read of {} with issue {}",
10377 id.0,
10378 required_str(node, "id")?
10379 ),
10380 });
10381 }
10382 let item = if draft {
10383 self.draft_by_id(id).await?
10384 } else {
10385 self.resolve_issue(node).await?
10386 };
10387 // A read that carried the whole of what the issue is blocked by — a copy's — is kept
10388 // for this command, so the dependency read the copy makes next is answered from it.
10389 if let Some(read) = item.as_ref().filter(|item| item.blocked_by.is_some()) {
10390 self.resolved_cache()?.insert(read.id.clone(), read.clone());
10391 }
10392 let Some(item) = item.filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
10393 return Ok(None);
10394 };
10395 let own = self.created()?.iter().find(|own| own.id == *id).cloned();
10396 let task = own.unwrap_or(item).task()?;
10397 let comments = match (commented, draft) {
10398 (false, _) => None,
10399 (true, true) => Some(Err(self.draft_has_no_comments(id))),
10400 (true, false) => Some(comment_page(node, &id.0, after).map(Some)),
10401 };
10402 if commented && !draft && after.is_none() {
10403 self.expected.learn_comments(id, node);
10404 }
10405 Ok(Some(TaskDetailRead { task, comments }))
10406 }
10407
10408 /// Whether the comment `comment` is one of `issue`'s own.
10409 ///
10410 /// Read before an edit or a removal is sent, because GitHub's comment mutations take the
10411 /// comment's id and nothing else: a comment id given against the wrong task would
10412 /// otherwise change a comment on some other issue entirely. An id that names nothing, or
10413 /// names something that is not an issue comment, is a comment this task does not have —
10414 /// which is what GitHub refusing to resolve it means too.
10415 async fn comment_is_on(
10416 &self,
10417 issue: &NativeId,
10418 comment: &NativeId,
10419 ) -> Result<bool, SourceError> {
10420 Ok(self.comment_on(issue, comment).await?.is_some())
10421 }
10422
10423 /// The body the comment `comment` holds, exactly as GitHub holds it, when it is one of
10424 /// `issue`'s own — the read [`Self::comment_is_on`] makes, answering with what it selected.
10425 async fn comment_on(
10426 &self,
10427 issue: &NativeId,
10428 comment: &NativeId,
10429 ) -> Result<Option<String>, SourceError> {
10430 // A write the store's cache expects knows which comments its issue held, and their
10431 // bodies, at the version it expects: what this read would answer.
10432 if let Some(primed) = self.expected.primed_comment(issue, comment) {
10433 return Ok(primed);
10434 }
10435 let asked = self
10436 .graphql(graphql::COMMENT_ISSUE, json!({"id":comment.0}))
10437 .await;
10438 let data = match asked {
10439 Ok(data) => data,
10440 Err(error) if unresolvable_node(&error) => return Ok(None),
10441 Err(error) => return Err(error),
10442 };
10443 let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
10444 return Ok(None);
10445 };
10446 if optional_str(node, "__typename")? != Some("IssueComment") {
10447 return Ok(None);
10448 }
10449 let on = node.get("issue").ok_or_else(|| SourceError::Malformed {
10450 message: format!("GitHub issue comment {} names no issue", comment.0),
10451 })?;
10452 if required_str(on, "id")? != issue.0 {
10453 return Ok(None);
10454 }
10455 Ok(Some(required_str(node, "body")?.to_owned()))
10456 }
10457
10458 /// Which far ends this item's own `blockedBy` relationship holds, and which it cannot.
10459 async fn partition_edges(
10460 &self,
10461 near_kind: BoardKind,
10462 near_content: ContentKind,
10463 carried: Option<&[Value]>,
10464 depends_on: &[DependencyEdge],
10465 ) -> Result<(Vec<String>, Vec<DependencyEdge>), SourceError> {
10466 let mut native = Vec::new();
10467 let mut fallback = Vec::new();
10468 let far_ends: Vec<(&DependencyEdge, &str, bool, Option<&Value>)> = depends_on
10469 .iter()
10470 .map(|edge| {
10471 // An opaque far end names another tracker, so it is never this board's own.
10472 let same_source = edge.to.designator().is_none()
10473 && edge
10474 .to
10475 .source()
10476 .is_none_or(|source| source == self.name.as_str());
10477 // A qualified id's source segment runs to its *first* colon — `GlobalId` and
10478 // `DependencyEndpoint::source` both read it that way — and a native id may hold
10479 // colons of its own, so the far end is everything after that one separator.
10480 // Splitting at the last would truncate `work:urn:task:7` to `7`.
10481 let far_id = if edge.to.is_qualified() {
10482 edge.to
10483 .id()
10484 .split_once(':')
10485 .map_or(edge.to.id(), |(_, native)| native)
10486 } else {
10487 edge.to.id()
10488 };
10489 // One that already blocks the near issue was answered by that issue's own
10490 // read, which carried each of its blockers' kinds — an issue every one — so it
10491 // is not read again.
10492 let blocking = carried.and_then(|nodes| {
10493 nodes
10494 .iter()
10495 .find(|node| node.get("id").and_then(Value::as_str) == Some(far_id))
10496 });
10497 (edge, far_id, same_source, blocking)
10498 })
10499 .collect();
10500 // Every other same-source far end is read by its own id, exactly as the item it is a
10501 // far end of is: whether this board holds it is that read's answer, never a listing's.
10502 // They are read together, [`DETAIL_BATCH`] to a request, rather than one each.
10503 let mut unread: Vec<NativeId> = Vec::new();
10504 for (_, far_id, same_source, blocking) in &far_ends {
10505 let id = NativeId((*far_id).to_owned());
10506 if *same_source && blocking.is_none() && !unread.contains(&id) {
10507 unread.push(id);
10508 }
10509 }
10510 let read: BTreeMap<NativeId, Option<Resolved>> = unread
10511 .iter()
10512 .cloned()
10513 .zip(self.items_by_ids(&unread).await?)
10514 .collect();
10515 for (edge, far_id, same_source, blocking) in far_ends {
10516 let far = match (same_source, blocking) {
10517 (false, _) => None,
10518 (true, Some(node)) => Some(FarEnd {
10519 kind: if required_str(node, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
10520 BoardKind::Document
10521 } else {
10522 BoardKind::Work(related_kind(node)?)
10523 },
10524 content_kind: ContentKind::Issue,
10525 }),
10526 (true, None) => {
10527 let read = read
10528 .get(&NativeId(far_id.to_owned()))
10529 .cloned()
10530 .flatten()
10531 .ok_or_else(|| SourceError::Refused {
10532 message: format!("GitHub dependency item {far_id} was not found"),
10533 })?;
10534 Some(FarEnd {
10535 kind: read.kind,
10536 content_kind: read.content_kind,
10537 })
10538 }
10539 };
10540 let far = far.as_ref();
10541 // The caller says which kind the far end is, and this board holds the far end
10542 // itself, so a disagreement is settled here rather than stored: recorded, the
10543 // wrong kind would read back as a cross-level edge that never existed; written
10544 // natively, it would name a relationship of a different level than the caller
10545 // asked for.
10546 //
10547 // A far end this board holds as a *document* fails the same comparison and is
10548 // refused by the same sentence: `ItemKind` has no document variant because
10549 // nothing may point at one, so no caller can name it correctly and the refusal
10550 // is the only honest answer.
10551 if let Some(disagreeing) = far.filter(|far| far.kind != BoardKind::Work(edge.to.kind)) {
10552 return Err(SourceError::Refused {
10553 message: format!(
10554 "GitHub dependency item {far_id} is a {} of this board, and this item \
10555 names it as a {}; record the kind it is",
10556 disagreeing.kind.describes(),
10557 edge.to.kind.marker()
10558 ),
10559 });
10560 }
10561 // A draft has neither `blockedBy` nor `blocking`, so no edge of one is native
10562 // however the far end is spelled — and one classified native here would be
10563 // written nowhere at all, because a draft's native reconciliation never runs.
10564 let native_here = near_content == ContentKind::Issue
10565 && far.is_some_and(|far| {
10566 far.content_kind == ContentKind::Issue
10567 && BoardKind::Work(edge.to.kind) == near_kind
10568 });
10569 if native_here {
10570 native.push(far_id.to_owned());
10571 } else {
10572 fallback.push(edge.clone());
10573 }
10574 }
10575 Ok((native, fallback))
10576 }
10577
10578 async fn update_existing(
10579 &self,
10580 item: &Resolved,
10581 incoming: &Incoming<'_>,
10582 body: &Option<String>,
10583 status_target: Option<&StatusTarget>,
10584 ) -> Result<(), SourceError> {
10585 let title = incoming.written_title();
10586 // A terminal status closes the issue here, in the same mutation as its body: its board
10587 // option was selected before this, so a close never lands on an item whose board cannot
10588 // show it.
10589 let mut fields = match item.content_kind {
10590 ContentKind::DraftIssue => json!({"title":title,"body":body}),
10591 ContentKind::Issue => json!({"title":title,"body":body,
10592 "stateInput":state_input(status_target)}),
10593 };
10594 // Only the members whose value differs from the item as this write read it are sent,
10595 // and nothing at all when none does — whether or not the store's cache expects a
10596 // version of it. A member left out is one GitHub leaves as it is, so a person's edit
10597 // of it since that read is kept rather than overwritten with what it already held,
10598 // and a re-copy of an unchanged item costs no mutation.
10599 if let Some(members) = fields.as_object_mut() {
10600 if members.get("title").and_then(Value::as_str) == Some(item.title.as_str()) {
10601 members.remove("title");
10602 }
10603 let body_unchanged = match (members.get("body"), item.raw_body.as_deref()) {
10604 (Some(Value::String(sent)), Some(held)) => sent == held,
10605 (Some(Value::Null), held) => held.is_none_or(str::is_empty),
10606 _ => false,
10607 };
10608 if body_unchanged {
10609 members.remove("body");
10610 }
10611 // An issue already in the state the target asks for keeps it: an open one stays
10612 // open, and a closed one whose closure reads as the target's category keeps its
10613 // reason — a duplicate's says more than this write would.
10614 let unchanged_state = match status_target {
10615 Some(StatusTarget::Terminal(_, reason)) => {
10616 item.closed
10617 && closed_category(item.reason.as_deref())
10618 == closed_category(Some(reason.reason()))
10619 }
10620 Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => !item.closed,
10621 None => true,
10622 };
10623 if unchanged_state {
10624 members.remove("stateInput");
10625 }
10626 if members.is_empty() {
10627 return Ok(());
10628 }
10629 }
10630 self.update_content(item.content_kind, &item.id, fields)
10631 .await
10632 }
10633
10634 /// Update one board item's content with exactly `fields` beside its id, through the
10635 /// mutation its kind takes: `updateIssue` for an issue, `updateProjectV2DraftIssue` for
10636 /// a draft.
10637 ///
10638 /// Every input field either mutation leaves out is a field GitHub leaves as it is, which
10639 /// is what lets a narrow write carry the one thing it changes and nothing else.
10640 async fn update_content(
10641 &self,
10642 kind: ContentKind,
10643 id: &NativeId,
10644 fields: Value,
10645 ) -> Result<(), SourceError> {
10646 let (operation, id_key, pointer) = match kind {
10647 ContentKind::DraftIssue => (
10648 graphql::UPDATE_DRAFT,
10649 "draftIssueId",
10650 "/updateProjectV2DraftIssue/draftIssue",
10651 ),
10652 ContentKind::Issue => (graphql::UPDATE_ISSUE, "id", "/updateIssue/issue"),
10653 };
10654 let mut input = fields;
10655 input[id_key] = json!(id.0);
10656 let data = self.graphql(operation, json!({"input":input})).await?;
10657 let returned = data
10658 .pointer(pointer)
10659 .ok_or_else(|| SourceError::Malformed {
10660 message: "GitHub item update returned no item".into(),
10661 })?;
10662 if required_str(returned, "id")? != id.0 {
10663 return Err(SourceError::Malformed {
10664 message: "GitHub item update returned the wrong item".into(),
10665 });
10666 }
10667 Ok(())
10668 }
10669
10670 /// Creates one issue, files it on the board, and reports what a read of it would say:
10671 /// its content id, its board item id, and the web address GitHub gave it.
10672 ///
10673 /// Two calls rather than one: `createIssue` answers with an issue that is on no board,
10674 /// and `addProjectV2ItemById` is what puts it there. Filing it at creation through
10675 /// `CreateIssueInput.projectV2Ids` was tried and is not done: GitHub answered with no
10676 /// board item, and the `addProjectV2ItemById` that then had to follow was refused
10677 /// "Content already exists in this project". A terminal status is not written here:
10678 /// `finish_write` selects its option first and closes the issue after, so a close never
10679 /// lands on an item whose board cannot show it.
10680 ///
10681 /// The address and the number come back here because this is the only place either is
10682 /// known before GitHub's own board read catches up — an item this run created answers
10683 /// the reads that follow it out of the record below, and one remembered without them
10684 /// would report no location and no key for the rest of the run.
10685 async fn create_and_file_issue(
10686 &self,
10687 board_id: &str,
10688 repository: &RepositoryTarget,
10689 incoming: &Incoming<'_>,
10690 body: &Option<String>,
10691 ) -> Result<Landed, SourceError> {
10692 let repository_id = self.repository_id(repository, incoming).await?;
10693 let data = self
10694 .graphql(
10695 graphql::CREATE_ISSUE,
10696 json!({"input":{
10697 "repositoryId":repository_id,"title":incoming.written_title(),"body":body
10698 }}),
10699 )
10700 .await?;
10701 let created = data
10702 .pointer("/createIssue/issue")
10703 .filter(|value| !value.is_null())
10704 .ok_or_else(|| SourceError::Malformed {
10705 message: "GitHub issue creation returned no issue".into(),
10706 })?;
10707 let content_id = NativeId(required_str(created, "id")?.to_owned());
10708 // Optional although GitHub's schema makes it non-null: the issue exists by now, so
10709 // a response without it is not worth failing a landed write over — the item simply
10710 // reports no location until the board read catches up, which is what it did before.
10711 let url = optional_str(created, "url")?.map(str::to_owned);
10712 // The issue exists from here on, so an unreadable number and a refused board
10713 // filing below each try, best effort, to take it back: an issue in the repository
10714 // that is on no board is an item nobody asked for and nothing here would find again.
10715 //
10716 // Its number is optional on the same terms its address is — a landed write is not
10717 // worth failing over a member that came back missing, and such an item reports no
10718 // handle until a board read catches up. A number that is *present* and is not an
10719 // unsigned integer is still a response this source cannot read.
10720 let number = match created_issue_number(created) {
10721 Ok(number) => number,
10722 Err(error) => {
10723 let _ = self.delete_issue(&content_id).await;
10724 return Err(error);
10725 }
10726 };
10727 let added = match self
10728 .graphql(
10729 graphql::ADD_TO_BOARD,
10730 json!({"input":{"projectId":board_id,"contentId":content_id.0}}),
10731 )
10732 .await
10733 {
10734 Ok(added) => added,
10735 Err(error) => {
10736 let _ = self.delete_issue(&content_id).await;
10737 return Err(error);
10738 }
10739 };
10740 let item = added
10741 .pointer("/addProjectV2ItemById/item")
10742 .filter(|value| !value.is_null())
10743 .ok_or_else(|| SourceError::Malformed {
10744 message: "GitHub board addition returned no project item".into(),
10745 })?;
10746 self.note_written(&content_id, url.as_deref());
10747 Ok(Landed {
10748 content_id,
10749 item_id: Some(required_str(item, "id")?.to_owned()),
10750 url,
10751 number,
10752 })
10753 }
10754
10755 /// Move one issue under the project it now belongs to, or out of the one it left.
10756 async fn reparent(
10757 &self,
10758 held: Option<NativeId>,
10759 child: &NativeId,
10760 wanted: Option<&NativeId>,
10761 ) -> Result<(), SourceError> {
10762 if held.as_ref() == wanted {
10763 return Ok(());
10764 }
10765 if let Some(held) = &held {
10766 self.sub_issue(graphql::REMOVE_SUB_ISSUE, held, child, "removeSubIssue")
10767 .await?;
10768 }
10769 if let Some(wanted) = wanted {
10770 self.sub_issue(graphql::ADD_SUB_ISSUE, wanted, child, "addSubIssue")
10771 .await?;
10772 }
10773 Ok(())
10774 }
10775
10776 async fn sub_issue(
10777 &self,
10778 operation: &str,
10779 parent: &NativeId,
10780 child: &NativeId,
10781 root: &str,
10782 ) -> Result<(), SourceError> {
10783 let data = self
10784 .graphql(
10785 operation,
10786 json!({"input":{"issueId":parent.0,"subIssueId":child.0}}),
10787 )
10788 .await?;
10789 let issue =
10790 data.pointer(&format!("/{root}/issue"))
10791 .ok_or_else(|| SourceError::Malformed {
10792 message: "GitHub sub-issue update returned no issue".into(),
10793 })?;
10794 let sub =
10795 data.pointer(&format!("/{root}/subIssue"))
10796 .ok_or_else(|| SourceError::Malformed {
10797 message: "GitHub sub-issue update returned no sub-issue".into(),
10798 })?;
10799 if required_str(issue, "id")? != parent.0 || required_str(sub, "id")? != child.0 {
10800 return Err(SourceError::Malformed {
10801 message: "GitHub sub-issue update returned the wrong issues".into(),
10802 });
10803 }
10804 Ok(())
10805 }
10806
10807 /// Bring one issue's `blockedBy` to exactly `native`, sending only the difference, and say
10808 /// whether there was one.
10809 ///
10810 /// An issue [`Issue::Created`] by this very write is blocked by nothing yet, so its
10811 /// relationships are not read: there is nothing a read of them could find.
10812 async fn reconcile_blocked_by(
10813 &self,
10814 content_id: &NativeId,
10815 native: &[String],
10816 issue: Issue<'_>,
10817 ) -> Result<bool, SourceError> {
10818 let current = match issue {
10819 Issue::Created => Vec::new(),
10820 Issue::Existing(Some(held)) => held
10821 .iter()
10822 .map(|far| required_str(far, "id").map(str::to_owned))
10823 .collect::<Result<Vec<_>, _>>()?,
10824 Issue::Existing(None) => self.native_dependency_ids(content_id).await?,
10825 };
10826 let mut changed = false;
10827 for (operation, far_id) in current
10828 .iter()
10829 .filter(|id| !native.contains(id))
10830 .map(|id| (graphql::REMOVE_BLOCKED_BY, id))
10831 .chain(
10832 native
10833 .iter()
10834 .filter(|id| !current.contains(id))
10835 .map(|id| (graphql::ADD_BLOCKED_BY, id)),
10836 )
10837 {
10838 let data = self
10839 .graphql(
10840 operation,
10841 json!({"input":{"issueId":content_id.0,"blockingIssueId":far_id}}),
10842 )
10843 .await?;
10844 let root = if operation == graphql::ADD_BLOCKED_BY {
10845 "addBlockedBy"
10846 } else {
10847 "removeBlockedBy"
10848 };
10849 let issue =
10850 data.pointer(&format!("/{root}/issue"))
10851 .ok_or_else(|| SourceError::Malformed {
10852 message: "GitHub dependency update returned no issue".into(),
10853 })?;
10854 let blocker = data
10855 .pointer(&format!("/{root}/blockingIssue"))
10856 .ok_or_else(|| SourceError::Malformed {
10857 message: "GitHub dependency update returned no blocking issue".into(),
10858 })?;
10859 if required_str(issue, "id")? != content_id.0 || required_str(blocker, "id")? != far_id
10860 {
10861 return Err(SourceError::Malformed {
10862 message: "GitHub dependency update returned the wrong issues".into(),
10863 });
10864 }
10865 changed = true;
10866 }
10867 Ok(changed)
10868 }
10869}
10870
10871/// The board field values one write sends, in the order GitHub runs them, and the fields it
10872/// clears after them: the origin field when it moves, the `Status` option `column` names, the
10873/// priority, then each projected field.
10874fn field_writes<'a>(
10875 existing: Option<&Resolved>,
10876 origin_field: Option<&str>,
10877 origin: &str,
10878 column: Option<(String, String)>,
10879 priority: Option<&'a PriorityWrite>,
10880 projections: &'a [ProjectionWrite],
10881) -> (Vec<(String, Value)>, Vec<&'a str>) {
10882 let mut fields = Vec::new();
10883 if let Some(field_id) = origin_field
10884 && existing.map_or(!origin.is_empty(), |item| {
10885 item.origin.as_deref().unwrap_or("") != origin
10886 })
10887 {
10888 fields.push((field_id.to_owned(), json!({"text":origin})));
10889 }
10890 if let Some((field_id, option_id)) = column {
10891 fields.push((field_id, json!({"singleSelectOptionId":option_id})));
10892 }
10893 let mut clears = Vec::new();
10894 match priority {
10895 Some(PriorityWrite::Select { field, option }) => {
10896 fields.push((field.clone(), json!({"singleSelectOptionId":option})));
10897 }
10898 Some(PriorityWrite::Clear { field }) => clears.push(field.as_str()),
10899 None => {}
10900 }
10901 for projection in projections {
10902 projection.join(&mut fields, &mut clears);
10903 }
10904 (fields, clears)
10905}
10906
10907/// Everything one write decided before sending anything: see
10908/// [`GitHubProjectsSource::prepare_write`].
10909struct Prepared {
10910 /// What the write lands on.
10911 destination: WriteDestination,
10912 board: BoardFields,
10913 status_target: Option<StatusTarget>,
10914 /// The `Status` field, the option and the option's name the status lands on.
10915 // llmlint: ignore[invalid_states_unrepresentable] Exactly what `column_for` returns, which predates this change and four callers share; this record only carries it from `prepare_write` to `complete_write`, which a retyping of that return would reach and this change does not need.
10916 column: Option<(String, String, String)>,
10917 priority_write: Option<PriorityWrite>,
10918 projections: Vec<ProjectionWrite>,
10919 projected: BTreeMap<String, String>,
10920 content_kind: ContentKind,
10921 own_repository: Option<Repository>,
10922 /// The far ends of the item's native blocked-by relationships.
10923 // llmlint: ignore[invalid_states_unrepresentable] What `partition_edges` answers and `finish_write` takes as `&[String]`, both of which predate this change; this record only carries the value between them.
10924 native: Vec<String>,
10925 slot: BTreeMap<String, Value>,
10926 content: Option<String>,
10927 body: Option<String>,
10928 /// The copy origin the item records, empty for none.
10929 // llmlint: ignore[invalid_states_unrepresentable] `finish_write` and `field_writes` take the origin as `&str`, empty for none, as they did before this change; this record only carries it to them.
10930 origin: String,
10931 origin_field: Option<String>,
10932}
10933
10934/// `error`, which stopped a batch of creates, and — when GitHub refused to take any of them
10935/// back — each issue of `left` it created that is still in the repository, which its caller,
10936/// never handed their ids, could not name.
10937fn left_behind(error: SourceError, left: &[&str]) -> SourceError {
10938 if left.is_empty() {
10939 return error;
10940 }
10941 SourceError::Refused {
10942 message: format!(
10943 "{error}; GitHub then refused to take back {}, which this write created and which \
10944 are still in the repository; next: delete {} before writing again",
10945 left.join(", "),
10946 if left.len() == 1 { "it" } else { "them" }
10947 ),
10948 }
10949}
10950
10951/// What one write lands on: the item it updates, as it stood, or where it creates a new one.
10952enum WriteDestination {
10953 /// The item as it stood, for an update.
10954 Existing(Box<Resolved>),
10955 /// Where a new item is created.
10956 New(RepositoryTarget),
10957}
10958
10959impl WriteDestination {
10960 /// The item an update writes over, as it stood; `None` for a create.
10961 fn existing(&self) -> Option<&Resolved> {
10962 match self {
10963 Self::Existing(item) => Some(item),
10964 Self::New(_) => None,
10965 }
10966 }
10967}
10968
10969/// What a copy has held back of the items it created; see
10970/// [`GitHubProjectsSource::hold_back`].
10971#[derive(Debug, Default)]
10972enum Deferred {
10973 /// Writes are being held back, and nothing has been held yet.
10974 #[default]
10975 Nothing,
10976 /// The items held back, every one of them on `board`.
10977 Held {
10978 /// The board every one of them is on.
10979 board: BoardId,
10980 /// Each created item, in the order it was created.
10981 created: Vec<HeldBack>,
10982 },
10983}
10984
10985impl Deferred {
10986 /// Whether `content` is one of the items held back.
10987 fn holds(&self, content: &NativeId) -> bool {
10988 match self {
10989 Self::Nothing => false,
10990 Self::Held { created, .. } => created.iter().any(|held| held.content == *content),
10991 }
10992 }
10993}
10994
10995/// One created item's parts that land once [`TaskSource::finish_writes`] is called.
10996#[derive(Debug)]
10997struct HeldBack {
10998 /// The issue.
10999 content: NativeId,
11000 /// Its board field values other than its `Status`, in the order they are written.
11001 fields: Vec<(String, Value)>,
11002 /// The `Status` field, and the option and its name that the item's status lands on.
11003 // llmlint: ignore[invalid_states_unrepresentable] The same triple `column_for` returns and `Prepared::column` carries, held back unchanged until it is sent.
11004 status: Option<(String, String, String)>,
11005 /// The fields it clears after those are written.
11006 clears: Vec<String>,
11007 /// The reason it is closed for, once its option is selected; `None` leaves it open.
11008 close: Option<ClosedState>,
11009 /// The issues it is blocked by.
11010 edges: Vec<NativeId>,
11011}
11012
11013/// The member [`answer_with_errors`] carries a response's GraphQL errors under, beside its data:
11014/// no GitHub type has a field of this name.
11015const ANSWER_ERRORS: &str = "onetaskgraphErrors";
11016
11017/// A response's `data` with its GraphQL errors beside it under [`ANSWER_ERRORS`], when it has
11018/// both — or `None`, for an answer [`GitHubProjectsSource::answer`] reads as it always has.
11019///
11020/// What [`graphql::CREATE_ISSUES`] is answered with: GitHub runs a document's mutation fields in
11021/// order and answers each one that ran, so a refusal of one alias leaves the issues the others
11022/// created named in the data beside it — the ids a copy needs to take them back.
11023fn answer_with_errors(body: &str) -> Option<Value> {
11024 let parsed: Value = serde_json::from_str(body).ok()?;
11025 let errors = parsed
11026 .get("errors")?
11027 .as_array()
11028 .filter(|errors| !errors.is_empty())?;
11029 let mut data = parsed.get("data").filter(|data| data.is_object())?.clone();
11030 data[ANSWER_ERRORS] = Value::Array(errors.clone());
11031 Some(data)
11032}
11033
11034/// The `createIssue` input that files the new issue on `board` and, when `incoming` names one,
11035/// under its project — see [`GitHubProjectsSource::create_filed_issue`].
11036fn filed_input(
11037 repository: &str,
11038 board: &str,
11039 incoming: &Incoming<'_>,
11040 body: &Option<String>,
11041) -> Value {
11042 let mut input = json!({"repositoryId":repository,"title":incoming.written_title(),
11043 "body":body,"projectV2Ids":[board]});
11044 if let Some(parent) = incoming.parent {
11045 input["parentIssueId"] = json!(parent.0);
11046 }
11047 input
11048}
11049
11050/// The name of option `option` of field `field` among a board's `fields`.
11051fn option_name<'a>(fields: &'a Value, field: &str, option: &str) -> Option<&'a str> {
11052 fields
11053 .get("nodes")?
11054 .as_array()?
11055 .iter()
11056 .find(|node| node.get("id").and_then(Value::as_str) == Some(field))?
11057 .get("options")?
11058 .as_array()?
11059 .iter()
11060 .find(|candidate| candidate.get("id").and_then(Value::as_str) == Some(option))?
11061 .get("name")?
11062 .as_str()
11063}
11064
11065/// What a write needs to know of one far end it names: which kind of item it is, and whether
11066/// it is an issue a native relationship can name.
11067struct FarEnd {
11068 kind: BoardKind,
11069 content_kind: ContentKind,
11070}
11071
11072/// Whether the issue one write reconciles was created by that write or was already there.
11073#[derive(Clone, Copy, PartialEq, Eq)]
11074enum Issue<'a> {
11075 /// Created by this write, so it holds no relationships yet.
11076 Created,
11077 /// On the board before this write, holding whatever relationships it holds — the far
11078 /// ends of its whole `blockedBy`, when the read that reached it carried them.
11079 Existing(Option<&'a [Value]>),
11080}
11081
11082/// What resolving one node id reached; see [`GitHubProjectsSource::reach`].
11083enum Reached {
11084 /// An issue this board holds, resolved into everything this source reports about it.
11085 Held(Box<Resolved>),
11086 /// Nothing this board holds: no such node, or a node on some other board.
11087 Nothing,
11088 /// A board draft, which [`graphql::ISSUE`] reaches and reads nothing of, so it is read
11089 /// again by [`GitHubProjectsSource::draft_by_id`].
11090 Draft,
11091}
11092
11093/// What GitHub says when a string is not a node id it can resolve.
11094///
11095/// Matched because it is the ordinary answer to a project selector naming a project by its
11096/// *name*, and reporting that as a failure would make naming one impossible. It is read
11097/// off the refusal GitHub sent, never guessed from the shape of the string: this source
11098/// does not define the syntax of a GitHub node id and would be wrong about it.
11099const UNRESOLVABLE_NODE: &str = "could not resolve to a node";
11100
11101/// `error` with `note` added to the end of what it says, its kind and every other member
11102/// unchanged — so a caller still branches on the failure that happened, and reads beside it
11103/// what that failure left behind.
11104fn noting(error: SourceError, note: &str) -> SourceError {
11105 match error {
11106 SourceError::Config { message } => SourceError::Config {
11107 message: message + note,
11108 },
11109 SourceError::Auth { message } => SourceError::Auth {
11110 message: message + note,
11111 },
11112 SourceError::Refused { message } => SourceError::Refused {
11113 message: message + note,
11114 },
11115 SourceError::RateLimited {
11116 retry_after_seconds,
11117 message,
11118 } => SourceError::RateLimited {
11119 retry_after_seconds,
11120 message: Some(message.unwrap_or_default() + note),
11121 },
11122 SourceError::Unavailable { message } => SourceError::Unavailable {
11123 message: message + note,
11124 },
11125 SourceError::Malformed { message } => SourceError::Malformed {
11126 message: message + note,
11127 },
11128 }
11129}
11130
11131/// The variables of one [`graphql::ISSUE_COPY_DETAILS`] request, as [`detail_batch`] binds its
11132/// own: a slot `batch` has no id for is bound to its last id, read again at no added price.
11133fn copy_detail_batch(batch: &[NativeId], comments: &PageRequest, children: bool) -> Value {
11134 let mut variables = serde_json::Map::new();
11135 for slot in 0..COPY_DETAIL_BATCH {
11136 let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
11137 variables.insert(format!("id{slot}"), json!(id));
11138 }
11139 variables.insert("project".to_owned(), json!(batch.first().map(|id| &id.0)));
11140 variables.insert("children".to_owned(), json!(children));
11141 variables.insert("first".to_owned(), json!(comments.limit.min(MAX_PAGE_SIZE)));
11142 variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
11143 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
11144 variables.insert("duplicates".to_owned(), json!(true));
11145 Value::Object(variables)
11146}
11147
11148/// The variables of one [`graphql::ISSUE_DETAILS`] request over `batch` — at most
11149/// [`DETAIL_BATCH`] ids — each item with the first page of its comments when `comments` asks
11150/// for them.
11151///
11152/// The document is fixed-size, so a slot `batch` has no id for is bound to its last id, which
11153/// is read again at no added price.
11154fn detail_batch(batch: &[NativeId], comments: Option<&PageRequest>) -> Value {
11155 let mut variables = serde_json::Map::new();
11156 for slot in 0..DETAIL_BATCH {
11157 let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
11158 variables.insert(format!("id{slot}"), json!(id));
11159 }
11160 variables.insert(
11161 "first".to_owned(),
11162 json!(comments.map_or(MAX_PAGE_SIZE, |page| page.limit.min(MAX_PAGE_SIZE))),
11163 );
11164 variables.insert("comments".to_owned(), json!(comments.is_some()));
11165 variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
11166 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
11167 variables.insert("duplicates".to_owned(), json!(true));
11168 Value::Object(variables)
11169}
11170
11171/// Whether this refusal is GitHub saying the id names no node at all.
11172fn unresolvable_node(error: &SourceError) -> bool {
11173 matches!(error, SourceError::Refused { message }
11174 if message.to_ascii_lowercase().contains(UNRESOLVABLE_NODE))
11175}
11176
11177/// One project name, as a search qualifier which filters on it at the server.
11178///
11179/// Quoted so the whole title is one phrase rather than a bag of words, with the two
11180/// characters GitHub's own quoting grammar gives a meaning inside a quoted phrase escaped
11181/// the way it documents. A title matched here is still compared for equality afterwards:
11182/// the qualifier narrows what the server sends, and this source decides what it names.
11183fn title_qualifier(name: &str) -> String {
11184 format!("in:title {}", quoted(name))
11185}
11186
11187/// `value` as one quoted phrase of a GitHub search or a board filter, with the two
11188/// characters GitHub's quoting grammar gives a meaning inside a quoted phrase escaped the way
11189/// it documents — so a value holding a qualifier's spelling is searched for rather than
11190/// obeyed.
11191fn quoted(value: &str) -> String {
11192 let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
11193 format!("\"{escaped}\"")
11194}
11195
11196/// The search qualifier for the issues updated at or after `since`.
11197///
11198/// Written to the second, rounded down, which can only widen what the search returns.
11199fn updated_qualifier(since: DateTime<Utc>) -> String {
11200 format!("updated:>={}", since.format("%Y-%m-%dT%H:%M:%S+00:00"))
11201}
11202
11203/// The search terms that narrow a board-scoped issue search to a task query's text and
11204/// metadata predicates, or `None` when it carries neither.
11205///
11206/// The text is one quoted phrase, searched `in:title`, `in:body` or both as its fields say,
11207/// and each metadata value is one more quoted phrase, which GitHub finds in the body because
11208/// its index covers the metadata comment the value is stored in. GitHub ANDs the phrases and
11209/// matches each in any field the `in:` qualifier names, so a query naming a title search and
11210/// a metadata value searches both fields for both — wider than asked, never narrower, and
11211/// every candidate is confirmed in process afterwards.
11212///
11213/// **This narrows a text search, and that is this source's declared semantics.** GitHub
11214/// matches whole tokens where a substring rule would match inside a word, so an item holding
11215/// the text only inside a longer word is not returned. A text of nothing but whitespace
11216/// matches every item, so it narrows nothing and is not sent.
11217fn narrowing_qualifiers(query: &TaskQuery) -> Option<String> {
11218 let text = query
11219 .text
11220 .as_ref()
11221 .filter(|text| !text.terms.trim().is_empty());
11222 if text.is_none() && query.metadata.is_empty() {
11223 return None;
11224 }
11225 let (title, body) = match text.map(|text| text.fields) {
11226 None => (false, true),
11227 Some(TextFields::Title) => (true, !query.metadata.is_empty()),
11228 Some(TextFields::Content) => (false, true),
11229 Some(TextFields::TitleOrContent) => (true, true),
11230 };
11231 let fields = match (title, body) {
11232 (true, true) => "in:title,body",
11233 (true, false) => "in:title",
11234 _ => "in:body",
11235 };
11236 let phrases = text
11237 .map(|text| text.terms.clone())
11238 .into_iter()
11239 .chain(
11240 query
11241 .metadata
11242 .iter()
11243 .map(|wanted| as_stored(wanted.value())),
11244 )
11245 .map(|phrase| quoted(&phrase))
11246 .collect::<Vec<_>>();
11247 Some(format!("{fields} {}", phrases.join(" ")))
11248}
11249
11250/// The search terms that narrow a board-scoped issue search to a project or document query's
11251/// text, or `None` when it has none or a blank one: the phrase, in the fields, a task query
11252/// carrying that text alone is sent as by [`narrowing_qualifiers`].
11253fn text_qualifiers(text: Option<&TextQuery>) -> Option<String> {
11254 narrowing_qualifiers(&TaskQuery {
11255 text: text.cloned(),
11256 ..TaskQuery::default()
11257 })
11258}
11259
11260/// Refuses a project or document query's text GitHub's issue search cannot find, before
11261/// anything is asked of GitHub, on exactly the terms [`refuse_unsearchable`] refuses a task
11262/// query's.
11263fn refuse_unsearchable_text(text: Option<&TextQuery>) -> Result<(), SourceError> {
11264 refuse_unsearchable(&TaskQuery {
11265 text: text.cloned(),
11266 ..TaskQuery::default()
11267 })
11268}
11269
11270/// Refuses a task query naming a text or a metadata value GitHub's issue search cannot find,
11271/// before anything is asked of GitHub.
11272///
11273/// GitHub's index holds words, so a phrase with no letter or digit names none to find, and no
11274/// bounded query answers it: sent, GitHub's answer to it is nothing this source may rely on;
11275/// left out, the search is every issue of the board. So this source says it cannot answer
11276/// rather than reading the board or answering nothing. A blank text is not refused: it narrows
11277/// nothing GitHub could search for, and keeps the board read it always had.
11278fn refuse_unsearchable(query: &TaskQuery) -> Result<(), SourceError> {
11279 const WHY: &str = "GitHub's issue search indexes words, so it cannot answer a value with no \
11280 letter or digit with a bounded query";
11281 if let Some(text) = &query.text
11282 && !text.terms.trim().is_empty()
11283 && !has_words(&text.terms)
11284 {
11285 return Err(SourceError::Refused {
11286 message: format!(
11287 "cannot search for the text {:?}: {WHY}; search for a text holding a letter or a digit",
11288 text.terms
11289 ),
11290 });
11291 }
11292 if let Some(wanted) = query
11293 .metadata
11294 .iter()
11295 .find(|wanted| !has_words(wanted.value()))
11296 {
11297 return Err(SourceError::Refused {
11298 message: format!(
11299 "cannot filter by the metadata value {:?} at {:?}: {WHY}; filter by a value holding a letter or a digit",
11300 wanted.value(),
11301 std::iter::once(wanted.key())
11302 .chain(wanted.path().iter().map(String::as_str))
11303 .collect::<Vec<_>>()
11304 .join("/"),
11305 ),
11306 });
11307 }
11308 Ok(())
11309}
11310
11311/// Whether GitHub's index could hold a word of `phrase`: whether it has a letter or a digit.
11312fn has_words(phrase: &str) -> bool {
11313 phrase.chars().any(char::is_alphanumeric)
11314}
11315
11316/// `value` spelled the way the metadata slot stores it: as the inside of its JSON string.
11317///
11318/// What GitHub indexes is the slot's JSON text, so a value holding a character JSON escapes —
11319/// a newline, a tab, a quote — is found by the escape the body holds and not by the character,
11320/// which GitHub's word match would read as different words.
11321fn as_stored(value: &str) -> String {
11322 let encoded = Value::String(value.to_owned()).to_string();
11323 encoded[1..encoded.len() - 1].to_owned()
11324}
11325
11326/// The one narrower question a task query carrying a text, metadata or origin predicate is
11327/// sent as.
11328enum Narrowing {
11329 /// Every carrier of this origin: [`graphql::ORIGIN_LOOKUP`].
11330 Origin(String),
11331 /// The board-scoped issue search narrowed by these qualifiers.
11332 Search(String),
11333}
11334
11335impl Narrowing {
11336 /// What this question is remembered under for the length of one command.
11337 fn key(&self) -> String {
11338 match self {
11339 Self::Origin(origin) => format!("origin {origin}"),
11340 Self::Search(also) => format!("search {also}"),
11341 }
11342 }
11343}
11344
11345/// Where one connection of [`graphql::ORIGIN_LOOKUP`] resumes.
11346enum Resumed {
11347 /// It reported another page, which starts after this cursor.
11348 More(String),
11349 /// It has ended. Sending this cursor again — the page's own end when it had one, and
11350 /// otherwise the cursor it was reached from — answers an empty page, so the one document
11351 /// can go on walking the other connection.
11352 Ended(Option<String>),
11353}
11354
11355impl Resumed {
11356 /// Whether the connection has another page.
11357 const fn has_more(&self) -> bool {
11358 matches!(self, Self::More(_))
11359 }
11360
11361 /// The cursor to send this connection next.
11362 fn cursor(self) -> Option<String> {
11363 match self {
11364 Self::More(next) => Some(next),
11365 Self::Ended(last) => last,
11366 }
11367 }
11368}
11369
11370/// Where `connection`, reached from `after`, resumes — refused when it reports another page
11371/// with no cursor to it, or from a cursor that does not advance.
11372fn resumed(connection: &Value, after: Option<&str>) -> Result<Resumed, SourceError> {
11373 let info = connection
11374 .get("pageInfo")
11375 .ok_or_else(|| SourceError::Malformed {
11376 message: "GitHub connection has no pageInfo".into(),
11377 })?;
11378 let end = optional_str(info, "endCursor")?;
11379 if required_bool(info, "hasNextPage")? {
11380 let next = end.ok_or_else(|| SourceError::Malformed {
11381 message: "GitHub connection reports another page and no endCursor".into(),
11382 })?;
11383 validate_cursor_progress(after, next)?;
11384 return Ok(Resumed::More(next.to_owned()));
11385 }
11386 Ok(Resumed::Ended(
11387 end.map(str::to_owned).or_else(|| after.map(str::to_owned)),
11388 ))
11389}
11390
11391/// The board, and every item on it this source reports.
11392#[derive(Clone)]
11393struct Board {
11394 id: String,
11395 fields: Value,
11396 items: Vec<Resolved>,
11397}
11398
11399/// What a write needs of the board and nothing more: its node id and its field
11400/// definitions, in the shape a read of the board's own `fields` gives them.
11401///
11402/// Deliberately no items. A write decides which item it writes, which parent it files
11403/// under and which far ends it names by reading each of them by its own id; this is the
11404/// half of the board those reads cannot carry, and holding no item is what keeps it from
11405/// ever being asked whether an item is there.
11406#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
11407struct BoardFields {
11408 id: BoardId,
11409 fields: Value,
11410}
11411
11412/// A board's node id: what a field write and `addProjectV2ItemById` address.
11413///
11414/// Never blank, because a blank one addresses no board — so an id GitHub answers blank is
11415/// refused where it is read, and one an item names blank is read as not named at all.
11416#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
11417#[serde(try_from = "String")]
11418struct BoardId(String);
11419
11420impl TryFrom<String> for BoardId {
11421 type Error = String;
11422
11423 /// The same refusal [`BoardId::parse`] makes, for an id read back from a kept context.
11424 fn try_from(id: String) -> Result<Self, Self::Error> {
11425 Self::parse(&id).map_err(|error| error.to_string())
11426 }
11427}
11428
11429/// Where one write left its item, for the record the rest of the command reads it out of.
11430///
11431/// A named record rather than a tuple because the update arm and the create arm each fill
11432/// all four, and two `Option`s of different meaning side by side in a tuple are two
11433/// positions a reader has to count.
11434struct Landed {
11435 /// The issue's own node id, which is the [`NativeId`] this source reports.
11436 content_id: NativeId,
11437 /// The board item's id, which is what a field write addresses — `None` for an issue its
11438 /// create filed on the board itself, whose board item GitHub adds after answering and
11439 /// [`TaskSource::finish_writes`] reads.
11440 // 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.
11441 item_id: Option<String>,
11442 /// The web address GitHub gave the issue, when it gave one.
11443 // 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.
11444 url: Option<String>,
11445 /// The issue's number on its repository, when GitHub reported one.
11446 number: Option<u64>,
11447}
11448
11449impl BoardId {
11450 fn parse(id: &str) -> Result<Self, SourceError> {
11451 if id.trim().is_empty() {
11452 return Err(SourceError::Malformed {
11453 message: "GitHub named a board with a blank node id".into(),
11454 });
11455 }
11456 Ok(Self(id.to_owned()))
11457 }
11458
11459 fn as_str(&self) -> &str {
11460 &self.0
11461 }
11462}
11463
11464impl Board {
11465 fn field<'a>(fields: &'a Value, name: &str) -> Result<Option<&'a Value>, SourceError> {
11466 complete_connection(fields, "project fields", NESTED_PAGE_SIZE)?;
11467 let nodes = fields
11468 .get("nodes")
11469 .and_then(Value::as_array)
11470 .ok_or_else(|| SourceError::Malformed {
11471 message: "GitHub project fields.nodes is not an array".into(),
11472 })?;
11473 Ok(nodes
11474 .iter()
11475 .find(|field| field.get("name").and_then(Value::as_str) == Some(name)))
11476 }
11477}
11478
11479/// One board item, resolved into everything this source reports about it.
11480///
11481/// Serializable because it is what [`TaskSource::write_context`] hands the store's cache and
11482/// [`TaskSource::prime_write`] takes back — see [`expected`].
11483#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
11484struct Resolved {
11485 item_id: String,
11486 id: NativeId,
11487 content_kind: ContentKind,
11488 kind: BoardKind,
11489 title: String,
11490 body: Option<String>,
11491 /// The body exactly as GitHub holds it, metadata slot and all, which is what a write
11492 /// that changes the slot alone has to keep byte for byte outside it.
11493 raw_body: Option<String>,
11494 status: Status,
11495 /// The name of the board `Status` option this item sits in, as the board spells it.
11496 option: Option<String>,
11497 /// What its `Priority` field says, read through this instance's mapping.
11498 priority: HeldPriority,
11499 /// Whether this item's issue is closed. A draft has no such state and is never closed.
11500 closed: bool,
11501 /// GitHub's reason for a closed issue's closure, as it spells it — `None` for an open
11502 /// issue, a draft, and an issue closed before GitHub recorded reasons.
11503 #[serde(default)]
11504 reason: Option<String>,
11505 /// The tasks this one delivers, read out of its slot. Empty for anything not a task.
11506 delivers: Vec<TaskRef>,
11507 /// Every task that delivers this one, read out of its slot. Empty for anything not a
11508 /// task.
11509 delivered_by: Vec<TaskRef>,
11510 labels: Vec<Label>,
11511 parent: Option<NativeId>,
11512 // 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.
11513 origin: Option<String>,
11514 /// What each board text field this instance projects metadata onto holds for this item,
11515 /// by field name — only the fields holding a value, an empty text included. What a write compares the
11516 /// item's metadata against, so a field already holding its value is not written again;
11517 /// never read back as metadata, which the slot alone reports.
11518 projected: BTreeMap<String, String>,
11519 /// The issue's own number on its repository, as GitHub reports it.
11520 ///
11521 /// `None` in exactly two cases: a draft, which has no number at all — `DraftIssue`
11522 /// declares none, and a draft is not filed in a repository to be numbered by one — and
11523 /// an issue this run created whose creating mutation answered without one, which is a
11524 /// response GitHub's own schema says cannot happen and which a landed write is not
11525 /// worth failing over. An `Issue` read off the board always has one.
11526 number: Option<u64>,
11527 url: Option<String>,
11528 created_at: Option<DateTime<Utc>>,
11529 updated_at: Option<DateTime<Utc>>,
11530 /// When the board item itself last changed — what a board field write moves — when the
11531 /// read that reached it said.
11532 item_updated_at: Option<DateTime<Utc>>,
11533 /// How many comments the issue holds, when the read that reached it said.
11534 comment_count: Option<u64>,
11535 /// How many relationship events the issue's timeline holds — every dependency, as
11536 /// `blockedBy` or `blocking`, and every project membership, as its parent, added or
11537 /// removed — when the read that reached it said.
11538 relationship_events: Option<u64>,
11539 /// The server's clock on the response that read it — its `Date` header — when the
11540 /// response carried one.
11541 served_at: Option<DateTime<Utc>>,
11542 /// The digest of its [`change_token::Facets`] — its own kind, its board field values and
11543 /// its labels — when the read that reached it carried all three whole.
11544 #[serde(default)]
11545 facets: Option<change_token::FacetsDigest>,
11546 own_repository: Option<Repository>,
11547 repositories: Vec<Repository>,
11548 classification: Classification,
11549 slot: BTreeMap<String, Value>,
11550 /// The node id of the board this item sits on, when the read that reached it said.
11551 board_id: Option<String>,
11552 /// The definition of every board field this item holds a value of, in the shape a read
11553 /// of the board's own `fields` gives one.
11554 ///
11555 /// Only the fields this item has a value in: a field it holds nothing of is not here,
11556 /// which says nothing about whether the board has it.
11557 fields: Vec<Value>,
11558 /// Every field the board this item sits on defines, as its own read of the board's
11559 /// `fields` gives them — when the read that reached the item carried them, which a read
11560 /// of it by its own id does. What a write of it needs of the board, then, needs no read
11561 /// of the board.
11562 board_fields: Option<Value>,
11563 /// The far ends of this issue's whole `blockedBy` connection, each as a dependency read
11564 /// selects one — when the read that reached it carried the connection to its end, which a
11565 /// read of it by its own id does for any issue blocked by no more than a page. What a
11566 /// write reconciles that relationship against, and what a read of its forward edges in
11567 /// the same command answers with.
11568 blocked_by: Option<Vec<Value>>,
11569}
11570
11571impl Resolved {
11572 /// The board this item's own read names it on, when that read named one this source can
11573 /// address.
11574 fn named_board(&self) -> Option<BoardId> {
11575 self.board_id
11576 .as_deref()
11577 .and_then(|id| BoardId::parse(id).ok())
11578 }
11579
11580 /// The board's id and every field it defines, when the read that reached this item
11581 /// carried both — which a read of it by its own id does.
11582 fn carried_board(&self) -> Option<BoardFields> {
11583 Some(BoardFields {
11584 id: self.named_board()?,
11585 fields: self.board_fields.clone()?,
11586 })
11587 }
11588
11589 /// Whether this item holds a value of the board field called `name`, and so carries
11590 /// that field's definition. `false` says nothing about whether the board has the field.
11591 fn defines(&self, name: &str) -> bool {
11592 self.fields
11593 .iter()
11594 .any(|field| field.get("name").and_then(Value::as_str) == Some(name))
11595 }
11596
11597 /// The metadata a caller sees: their own keys, plus the copy origin this source keeps
11598 /// in a field of its own, and none of the five keys that are only an encoding.
11599 ///
11600 /// The two delivery keys are left out for every kind, not only for a task: they are
11601 /// the encoding of [`Task::delivers`] and [`Task::delivered_by`], and a project or a
11602 /// document carrying one holds nothing a caller's own metadata could mean by it.
11603 fn metadata(&self) -> BTreeMap<String, Value> {
11604 let mut metadata = self.slot.clone();
11605 metadata.remove(Repository::METADATA_KEY);
11606 metadata.remove(DependencyEdge::RECORDED_KEY);
11607 metadata.remove(ItemKind::METADATA_KEY);
11608 metadata.remove(TaskRef::DELIVERS_KEY);
11609 metadata.remove(TaskRef::DELIVERED_BY_KEY);
11610 metadata.remove(Classification::METADATA_KEY);
11611 // The board field is the origin, and the body's copy of it is only a mirror for the
11612 // issue search to find: an item whose field holds none has none, whatever its body
11613 // says, so no reader ever sees two answers.
11614 metadata.remove(ORIGIN_KEY);
11615 if let Some(origin) = &self.origin {
11616 metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin.clone()));
11617 }
11618 metadata
11619 }
11620
11621 /// Where this item is, as a link a reader can open.
11622 ///
11623 /// A board is a hosted place and every issue on it has a web address, so that address
11624 /// is what "where is this?" means here — and [`Location::Url`] is what says which kind
11625 /// of place it is, so a reader knows to open it rather than to read a file out. It
11626 /// does not replace or derive from `url`: the field goes on reporting exactly what it
11627 /// reported before, and this says what that address *is*.
11628 ///
11629 /// An item GitHub gave no `url` for — a draft has none — reports no location at all
11630 /// rather than a third variant, which is the contract's "the source did not say". An
11631 /// issue this run created is not one of those: its address comes back from the
11632 /// creating mutation, so it is somewhere a reader can open from the moment it exists
11633 /// rather than from whenever the board read catches up.
11634 fn location(&self) -> Option<Location> {
11635 self.url.clone().map(Location::Url)
11636 }
11637
11638 /// The short handle this board's backend shows people for a task: the issue's number
11639 /// alone, as a decimal string.
11640 ///
11641 /// The number alone rather than `owner/repo#1043`, because that is the contract's
11642 /// value for this backend. A draft has no number and so no handle, which is the
11643 /// contract's *absent* rather than a handle of some other shape — and the native
11644 /// [`Task::id`] here is the issue's GraphQL node id, which this neither replaces nor
11645 /// derives from.
11646 fn key(&self) -> Option<String> {
11647 self.number.map(|number| number.to_string())
11648 }
11649
11650 /// This item's change token — see [`change_token`] — or `None` when the read that
11651 /// reached it did not carry all six of its parts, which a draft never does, did not say
11652 /// when GitHub served it, or found it changed too recently to have settled.
11653 fn version(&self) -> Option<String> {
11654 match self.content_kind {
11655 ContentKind::Issue => {
11656 let (issue, item) = (self.updated_at?, self.item_updated_at?);
11657 let parts = change_token::Parts {
11658 issue,
11659 item,
11660 comments: self.comment_count?,
11661 relationships: self.relationship_events?,
11662 facets: self.facets.clone()?,
11663 repository: self.own_repository.clone()?,
11664 };
11665 change_token::settled(issue, item, self.served_at?)
11666 .then(|| change_token::spell(&parts))
11667 }
11668 ContentKind::DraftIssue => None,
11669 }
11670 }
11671
11672 /// Whether its `Priority` field holds a value at all, mapped or not.
11673 fn holds_priority(&self) -> bool {
11674 self.priority != HeldPriority::Read(Priority::None)
11675 }
11676
11677 /// The task this item is.
11678 ///
11679 /// Fails for an item whose `Priority` field holds an option the mapping does not name:
11680 /// reading that as a level would be a guess, and reading it as `none` would let the next
11681 /// copy clear a priority a person set.
11682 fn task(&self) -> Result<Task, SourceError> {
11683 let priority = match &self.priority {
11684 HeldPriority::Read(priority) => *priority,
11685 HeldPriority::Unmapped(option) => {
11686 return Err(SourceError::Malformed {
11687 message: format!(
11688 "task {}{} sits in the board {PRIORITY_FIELD} option {option:?}, which \
11689 this source's priority_mapping does not name, so its priority cannot be \
11690 read; next: name {option:?} under priority_mapping, or move the item to \
11691 a mapped option",
11692 self.id,
11693 self.number
11694 .map(|number| format!(" (#{number})"))
11695 .unwrap_or_default()
11696 ),
11697 });
11698 }
11699 };
11700 Ok(Task {
11701 version: self.version(),
11702 id: self.id.clone(),
11703 key: self.key(),
11704 title: self.title.clone(),
11705 content: self.body.clone(),
11706 status: self.status.clone(),
11707 priority,
11708 labels: self.labels.clone(),
11709 project: self.parent.clone(),
11710 url: self.url.clone(),
11711 location: self.location(),
11712 created_at: self.created_at,
11713 updated_at: self.updated_at,
11714 metadata: self.metadata(),
11715 repositories: self.repositories.clone(),
11716 delivers: self.delivers.clone(),
11717 delivered_by: self.delivered_by.clone(),
11718 classification: self.classification,
11719 })
11720 }
11721
11722 fn project(&self) -> Project {
11723 Project {
11724 version: self.version(),
11725 id: self.id.clone(),
11726 title: self.title.clone(),
11727 content: self.body.clone(),
11728 status: self.status.clone(),
11729 labels: self.labels.clone(),
11730 url: self.url.clone(),
11731 location: self.location(),
11732 created_at: self.created_at,
11733 updated_at: self.updated_at,
11734 metadata: self.metadata(),
11735 repositories: self.repositories.clone(),
11736 classification: self.classification,
11737 }
11738 }
11739
11740 /// The same issue as a document: the project it is filed under, and no status and no
11741 /// dependencies, because a document is not work.
11742 fn document(&self) -> Document {
11743 Document {
11744 version: self.version(),
11745 id: self.id.clone(),
11746 title: self.title.clone(),
11747 content: self.body.clone(),
11748 project: self.parent.clone(),
11749 labels: self.labels.clone(),
11750 url: self.url.clone(),
11751 location: self.location(),
11752 created_at: self.created_at,
11753 updated_at: self.updated_at,
11754 metadata: self.metadata(),
11755 repositories: self.repositories.clone(),
11756 classification: self.classification,
11757 }
11758 }
11759}
11760
11761/// Where one targeted update moves an item's status, and which of its two halves move.
11762struct StatusMove {
11763 /// The board the item's `Status` field is on.
11764 board: BoardId,
11765 /// The `Status` field's id.
11766 field: String,
11767 /// The option's id.
11768 option: String,
11769 /// The option's name, as the board spells it.
11770 name: String,
11771 /// What the status asks of the issue's state.
11772 target: StatusTarget,
11773 /// The status the item reads as once it is there.
11774 landed: Status,
11775 /// Which of the status's two halves differ from what the item holds.
11776 moves: Moves,
11777}
11778
11779/// Which halves of an item's status one targeted update moves: its `Status` option, the open or
11780/// closed state of its issue, or both. A status neither half of which differs is no move at all,
11781/// and is not a value of this type.
11782#[derive(Clone, Copy, PartialEq, Eq)]
11783enum Moves {
11784 /// The option alone.
11785 Option,
11786 /// The issue's state alone: open, closed, or closed with another reason.
11787 State,
11788 /// Both.
11789 Both,
11790}
11791
11792impl Moves {
11793 /// What differs, or `None` when nothing does.
11794 const fn of(option: bool, state: bool) -> Option<Self> {
11795 match (option, state) {
11796 (true, true) => Some(Self::Both),
11797 (true, false) => Some(Self::Option),
11798 (false, true) => Some(Self::State),
11799 (false, false) => None,
11800 }
11801 }
11802
11803 /// Whether the option moves.
11804 const fn option(self) -> bool {
11805 matches!(self, Self::Option | Self::Both)
11806 }
11807
11808 /// Whether the issue's state moves.
11809 const fn state(self) -> bool {
11810 matches!(self, Self::State | Self::Both)
11811 }
11812}
11813
11814/// What one write is, and the status that comes with being it.
11815///
11816/// One value rather than a [`BoardKind`] beside an `Option<Status>`: a document has no
11817/// status and a task or a project always has one, so "a document carrying a status" and
11818/// "a task carrying none" are states a write cannot be in rather than states every use
11819/// site below has to defend against.
11820enum Written<'a> {
11821 /// A document, which is not work and so has no status at all.
11822 Document,
11823 /// A task or a project, and the status it is being written with.
11824 Work(ItemKind, &'a Status),
11825}
11826
11827impl Written<'_> {
11828 /// Which of the board's three kinds this write is.
11829 const fn kind(&self) -> BoardKind {
11830 match self {
11831 Self::Document => BoardKind::Document,
11832 Self::Work(kind, _) => BoardKind::Work(*kind),
11833 }
11834 }
11835
11836 /// The status this write carries. A document carries none, so a write of one says
11837 /// nothing about the issue's open or closed state and selects no board `Status`
11838 /// option.
11839 const fn status(&self) -> Option<&Status> {
11840 match self {
11841 Self::Document => None,
11842 Self::Work(_, status) => Some(status),
11843 }
11844 }
11845
11846 /// The status this write carries with the kind whose half of `status_mapping` it is
11847 /// written through.
11848 const fn work_status(&self) -> Option<(ItemKind, &Status)> {
11849 match self {
11850 Self::Document => None,
11851 Self::Work(kind, status) => Some((*kind, status)),
11852 }
11853 }
11854}
11855
11856/// The item being written, in the one shape all three write methods reach.
11857struct Incoming<'a> {
11858 written: Written<'a>,
11859 /// The title a person wrote. A document's goes onto the issue with
11860 /// [`DESIGN_TITLE_PREFIX`] put back, so a round trip returns the title that went in.
11861 title: &'a str,
11862 content: Option<&'a str>,
11863 assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
11864 labels: &'a [Label],
11865 metadata: &'a BTreeMap<String, Value>,
11866 repositories: &'a [Repository],
11867 /// Recorded in the slot while private, and nowhere while public.
11868 classification: Classification,
11869 parent: Option<&'a NativeId>,
11870 /// [`Task::delivers`], already checked. Empty for a project or a document, which is
11871 /// what keeps either key out of their slot.
11872 delivers: &'a [TaskRef],
11873 /// [`Task::delivered_by`], already checked. Empty for a project or a document.
11874 delivered_by: &'a [TaskRef],
11875 /// [`Task::priority`], for a task written to an instance that holds one; `None` for a
11876 /// project, a document, and every write to an instance with no `priority_mapping` —
11877 /// which is what keeps such a write's requests exactly what they were before.
11878 priority: Option<Priority>,
11879}
11880
11881/// What one write does to one projected metadata text field, by the field's id.
11882#[derive(Debug, Clone)]
11883enum ProjectionWrite {
11884 /// Write this text.
11885 Set {
11886 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.
11887 text: String,
11888 },
11889 /// Clear the field's value.
11890 Clear { field: String }, // llmlint: ignore[invalid_states_unrepresentable] As above.
11891}
11892
11893impl ProjectionWrite {
11894 /// Add this write to a field write's list of values and list of clears.
11895 fn join<'a>(&'a self, values: &mut Vec<(String, Value)>, clears: &mut Vec<&'a str>) {
11896 match self {
11897 Self::Set { field, text } => values.push((field.clone(), json!({"text": text}))),
11898 Self::Clear { field } => clears.push(field),
11899 }
11900 }
11901}
11902
11903/// What one write does to an item's `Priority` field.
11904enum PriorityWrite {
11905 /// Select this option of this field.
11906 Select {
11907 /// The `Priority` field's id.
11908 field: String,
11909 /// The mapped option's id.
11910 option: String,
11911 },
11912 /// Clear the field's value, which is what `none` is.
11913 Clear {
11914 /// The `Priority` field's id.
11915 field: String,
11916 },
11917}
11918
11919impl Incoming<'_> {
11920 /// The title this write puts on the issue.
11921 fn written_title(&self) -> String {
11922 match self.written {
11923 Written::Document => format!("{DESIGN_TITLE_PREFIX}{}", self.title),
11924 Written::Work(..) => self.title.to_owned(),
11925 }
11926 }
11927}
11928
11929#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
11930enum ContentKind {
11931 DraftIssue,
11932 Issue,
11933}
11934
11935/// What one board issue is: a document, or the work an [`ItemKind`] names.
11936///
11937/// A type of this source's own rather than an `ItemKind` with a third variant, because
11938/// `ItemKind` names what a dependency endpoint points at and nothing may point at a
11939/// document — the contract keeps a document out of that enum deliberately. Holding the
11940/// board's three answers in one value is what makes every place that asks "which is this?"
11941/// answer all three, rather than a `document: bool` beside a `kind` that means nothing for
11942/// two thirds of the board.
11943#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
11944enum BoardKind {
11945 /// An issue whose title begins [`DESIGN_TITLE_PREFIX`].
11946 Document,
11947 /// Every other issue, and every draft.
11948 Work(ItemKind),
11949}
11950
11951impl BoardKind {
11952 /// The kind of an item titled `title`, filed under a project or not, holding `sub_issues`
11953 /// sub-issues and carrying the kind marker `marked` in its slot.
11954 ///
11955 /// The design prefix is read *first*, before either of the two rules that separate a
11956 /// project from a task. A document is not work whatever sub-issues it has and whatever
11957 /// marker it carries, and reading the prefix later would make a design issue with none of
11958 /// either an empty project. Being a sub-issue wins outright over the rest, and no marker
11959 /// overrides it: an issue filed under a project is that project's task even when it has
11960 /// sub-issues of its own.
11961 fn of(title: &str, filed: bool, sub_issues: u64, marked: Option<ItemKind>) -> Self {
11962 if title.starts_with(DESIGN_TITLE_PREFIX) {
11963 Self::Document
11964 } else if filed {
11965 Self::Work(ItemKind::Task)
11966 } else if sub_issues > 0 || marked == Some(ItemKind::Project) {
11967 Self::Work(ItemKind::Project)
11968 } else {
11969 Self::Work(ItemKind::Task)
11970 }
11971 }
11972
11973 /// What the change token's facets call this kind.
11974 const fn facet(self) -> change_token::FacetKind {
11975 match self {
11976 Self::Document => change_token::FacetKind::Document,
11977 Self::Work(ItemKind::Project) => change_token::FacetKind::Project,
11978 Self::Work(ItemKind::Task) => change_token::FacetKind::Task,
11979 }
11980 }
11981
11982 /// Whose half of `status_mapping` an item of this kind reads its status through. A
11983 /// document has no status of its own, so the task half stands in for whatever the issue
11984 /// holds; nothing reports it.
11985 const fn status_kind(self) -> ItemKind {
11986 match self {
11987 Self::Document => ItemKind::Task,
11988 Self::Work(kind) => kind,
11989 }
11990 }
11991
11992 /// How a refusal names this kind to the person reading it.
11993 const fn describes(self) -> &'static str {
11994 match self {
11995 Self::Document => "document",
11996 Self::Work(kind) => kind.marker(),
11997 }
11998 }
11999}
12000
12001/// Whether `labels` satisfies `filter`, matching by name, case-insensitively.
12002///
12003/// This is the local Markdown source's `labels_match`, spelled the same way on purpose:
12004/// the shared cross-source journeys assert one answer to one question, so two sources
12005/// that disagree about what "carries the label bug" means fail them.
12006fn labels_match(labels: &[Label], filter: &LabelFilter) -> bool {
12007 let holds = |name: &String| {
12008 labels
12009 .iter()
12010 .any(|label| label.name.eq_ignore_ascii_case(name))
12011 };
12012 (filter.any_of.is_empty() || filter.any_of.iter().any(holds))
12013 && filter.all_of.iter().all(holds)
12014 && !filter.none_of.iter().any(holds)
12015}
12016
12017/// Whether `category` is one of `statuses`. An empty list is unfiltered rather than
12018/// "keeps nothing", which is what lets a `Vec<StatusCategory>` spell no filter at all.
12019fn status_matches(category: StatusCategory, statuses: &[StatusCategory]) -> bool {
12020 statuses.is_empty() || statuses.contains(&category)
12021}
12022
12023/// Whether `title`/`content` satisfies `query`, matching case-insensitively.
12024///
12025/// `content` is the item's own prose — the body with this source's trailing metadata
12026/// comment already taken off — so a search never matches an encoding the author of the
12027/// issue never wrote.
12028fn text_matches(title: &str, content: Option<&str>, query: &TextQuery) -> bool {
12029 let terms = query.terms.to_lowercase();
12030 let in_title = title.to_lowercase().contains(&terms);
12031 let in_content = content.is_some_and(|body| body.to_lowercase().contains(&terms));
12032 match query.fields {
12033 TextFields::Title => in_title,
12034 TextFields::Content => in_content,
12035 TextFields::TitleOrContent => in_title || in_content,
12036 }
12037}
12038
12039/// Whether `task` satisfies `query`, with `project` deciding the project predicate.
12040///
12041/// The project predicate is passed separately because a read narrowed to one project has
12042/// already answered it by asking *that project* for its own items — and re-applying it
12043/// there would compare the caller's selector, which may be a project's **name**, against
12044/// the id of the project that name resolved to, and keep nothing. Every other read passes
12045/// `query.project` and applies it here, which is what keeps `projects` a predicate this
12046/// source really does apply.
12047fn task_matches(task: &Task, query: &TaskQuery, project: &ProjectFilter) -> bool {
12048 labels_match(&task.labels, &query.labels)
12049 && status_matches(task.status.category, &query.statuses)
12050 && (query.priorities.is_empty() || query.priorities.contains(&task.priority))
12051 && match project {
12052 ProjectFilter::Any => true,
12053 ProjectFilter::Orphans => task.project.is_none(),
12054 ProjectFilter::Is(id) => task.project.as_ref() == Some(id),
12055 }
12056 && query
12057 .text
12058 .as_ref()
12059 .is_none_or(|text| text_matches(&task.title, task.content.as_deref(), text))
12060 // Against the parsed metadata slot, and against the origin field, which is where
12061 // `Resolved::metadata` reads each of them from.
12062 && query.metadata_matches(&task.metadata)
12063 && query.origin_matches(&task.metadata)
12064}
12065
12066fn project_matches(project: &Project, query: &ProjectQuery) -> bool {
12067 labels_match(&project.labels, &query.labels)
12068 && status_matches(project.status.category, &query.statuses)
12069 && query
12070 .text
12071 .as_ref()
12072 .is_none_or(|text| text_matches(&project.title, project.content.as_deref(), text))
12073}
12074
12075/// The same three predicates a task query carries, minus the status filter.
12076///
12077/// A document is not work, so it has no status for one to compare against and the query
12078/// type carries none. The project predicate is the same one — a design issue filed under a
12079/// project issue is in that project, and one filed under nothing is in none — so it is
12080/// spelled the same way here rather than answered differently.
12081fn document_matches(document: &Document, query: &DocumentQuery, project: &ProjectFilter) -> bool {
12082 labels_match(&document.labels, &query.labels)
12083 && match project {
12084 ProjectFilter::Any => true,
12085 ProjectFilter::Orphans => document.project.is_none(),
12086 ProjectFilter::Is(id) => document.project.as_ref() == Some(id),
12087 }
12088 && query
12089 .text
12090 .as_ref()
12091 .is_none_or(|text| text_matches(&document.title, document.content.as_deref(), text))
12092}
12093
12094/// Why a GitHub item's change token does not vouch for its forward edges.
12095///
12096/// A forward edge names its far end and that far end's kind, and the near item's token moves
12097/// with the edges it holds but says nothing of the far ends themselves: a far end turning from a
12098/// task into a project when it gains a sub-issue, retitled into a document, or deleted moves
12099/// nothing the near token reads, so an edge kept at the near version could name a far end that
12100/// is no longer what it said.
12101const FAR_ENDS_UNCOVERED: &str = "a github item's change token does not attest a far end's kind, \
12102 whether it became a document, or its deletion, so its forward edges are always read from \
12103 github";
12104
12105/// The issue-search qualifier that keeps open issues alone, which a status filter naming only
12106/// categories an open issue reads as narrows a board-scoped search with.
12107const OPEN_QUALIFIER: &str = "is:open";
12108
12109/// The board filter `task status reconcile` reads the board through: closed items alone.
12110const CLOSED_FILTER: &str = "is:closed";
12111
12112/// The variables of one [`graphql::ISSUES_BY_REFERENCE`] request for `batch`: each slot names
12113/// one reference, and a slot the batch has none for names its last one again.
12114fn reference_batch(batch: &[IssueRef]) -> Value {
12115 let mut variables = serde_json::Map::new();
12116 for slot in 0..REFERENCE_BATCH {
12117 let issue = batch.get(slot).or(batch.last());
12118 variables.insert(format!("owner{slot}"), json!(issue.map(|i| &i.owner)));
12119 variables.insert(format!("name{slot}"), json!(issue.map(|i| &i.name)));
12120 variables.insert(format!("number{slot}"), json!(issue.map(|i| i.number)));
12121 }
12122 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
12123 variables.insert("statusField".to_owned(), json!(STATUS_FIELD));
12124 variables.insert("duplicates".to_owned(), json!(true));
12125 Value::Object(variables)
12126}
12127
12128/// One issue an issue read by reference answered, in the shape every other read of an issue
12129/// hands its resolver: each board membership's `Status` value, read by name, as the one field
12130/// value that membership carries.
12131///
12132/// A membership's `status` is `null` when its card sits at no option — or on a board with no
12133/// field of that name — and otherwise an option value naming its option; anything else is not
12134/// an answer to this read, and is refused rather than read as a card at no option.
12135fn held_issue(issue: &Value) -> Result<Value, SourceError> {
12136 let malformed = |what: &str| SourceError::Malformed {
12137 message: format!("GitHub answered an issue read by reference with {what}"),
12138 };
12139 let mut issue = issue.clone();
12140 let nodes = issue
12141 .pointer_mut("/projectItems/nodes")
12142 .and_then(Value::as_array_mut)
12143 .ok_or_else(|| malformed("no list of board memberships"))?;
12144 for node in nodes {
12145 let node = node
12146 .as_object_mut()
12147 .ok_or_else(|| malformed("a board membership that is not an object"))?;
12148 let status = match node.get("status") {
12149 None => return Err(malformed("a board membership with no status member")),
12150 Some(Value::Null) => None,
12151 Some(status) if status.get("name").is_some_and(Value::is_string) => {
12152 Some(status.clone())
12153 }
12154 // A single-select value of another field type answers `{}`; only an option value
12155 // carries a name.
12156 Some(status) if status.as_object().is_some_and(serde_json::Map::is_empty) => None,
12157 Some(_) => return Err(malformed("a membership status that names no option")),
12158 };
12159 node.insert(
12160 "fieldValues".to_owned(),
12161 json!({"nodes": status.into_iter().collect::<Vec<_>>(),
12162 "pageInfo": {"hasNextPage": false}}),
12163 );
12164 }
12165 Ok(issue)
12166}
12167
12168/// The issue one slot of a read by reference answered, `None` when GitHub answered that
12169/// slot's repository or issue `null` — which [`GitHubProjectsSource::answer_unresolved`]
12170/// admitted only beside a `NOT_FOUND` naming that very slot — and a refusal when the answer
12171/// leaves the slot, or its `issue` member, out: an answer missing a member is malformed rather
12172/// than a reference nothing holds.
12173fn referenced_issue(data: &Value, slot: usize) -> Result<Option<&Value>, SourceError> {
12174 let alias = format!("r{slot}");
12175 let repository = data.get(&alias).ok_or_else(|| SourceError::Malformed {
12176 message: format!("GitHub answered a read by reference with no {alias}"),
12177 })?;
12178 if repository.is_null() {
12179 return Ok(None);
12180 }
12181 let issue = repository
12182 .get("issue")
12183 .ok_or_else(|| SourceError::Malformed {
12184 message: format!("GitHub answered {alias} of a read by reference with no issue"),
12185 })?;
12186 if issue.is_null() {
12187 return Ok(None);
12188 }
12189 // `Repository.issue` is typed `Issue`, so anything else is not an answer to this read.
12190 if optional_str(issue, "__typename")? != Some("Issue") {
12191 return Err(SourceError::Malformed {
12192 message: format!(
12193 "GitHub answered {alias} of a read by reference with an issue whose __typename \
12194 is not Issue"
12195 ),
12196 });
12197 }
12198 Ok(Some(issue))
12199}
12200
12201/// A closure reason as a person reads it: `NOT_PLANNED` as `not planned`.
12202fn spoken_reason(reason: &str) -> String {
12203 reason.to_ascii_lowercase().replace('_', " ")
12204}
12205
12206impl GitHubProjectsSource {
12207 /// Every task and project of this board whose card contradicts its issue's closure, each
12208 /// judged against its own kind's half of `status_mapping`, read through the board's own
12209 /// `is:closed` filter, page by page — never the board's unfiltered `items`.
12210 ///
12211 /// Each item the filter answers is confirmed from its own node: an open one, one whose
12212 /// closure reads `unknown`, and one whose card is already in line are left out whatever
12213 /// the filter let through. The board's fields ride along and are held for the option
12214 /// writes that follow, so those need no read of the board.
12215 async fn contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
12216 let mut after: Option<String> = None;
12217 let mut found = Vec::new();
12218 loop {
12219 let data = self
12220 .graphql(
12221 graphql::CLOSED_ITEMS,
12222 json!({"owner":self.owner,"number":self.project_number,
12223 "first":MAX_PAGE_SIZE,"after":after,"filter":CLOSED_FILTER,
12224 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
12225 )
12226 .await?;
12227 let board = data
12228 .pointer("/closedItems/projectV2")
12229 .filter(|value| !value.is_null())
12230 .ok_or_else(|| SourceError::Refused {
12231 message: format!(
12232 "GitHub project {}/{} was not found or is not visible to the token",
12233 self.owner, self.project_number
12234 ),
12235 })?;
12236 *self.fields_cache()? = Some(BoardFields {
12237 id: BoardId::parse(required_str(board, "id")?)?,
12238 fields: board.get("fields").cloned().unwrap_or(Value::Null),
12239 });
12240 let items = board.get("items").ok_or_else(|| SourceError::Malformed {
12241 message: "GitHub project closed items are missing".into(),
12242 })?;
12243 for item in items
12244 .get("nodes")
12245 .and_then(Value::as_array)
12246 .ok_or_else(|| SourceError::Malformed {
12247 message: "GitHub project items.nodes is not an array".into(),
12248 })?
12249 {
12250 let Some(resolved) = self.resolve(item)? else {
12251 continue;
12252 };
12253 let BoardKind::Work(kind) = resolved.kind else {
12254 continue;
12255 };
12256 let Some((closed_as, name)) = self.statuses.contradicted(
12257 kind,
12258 resolved.option.as_deref(),
12259 resolved.closed,
12260 resolved.reason.as_deref(),
12261 ) else {
12262 continue;
12263 };
12264 found.push(StatusContradiction {
12265 closed_as,
12266 to: name.to_owned(),
12267 option: resolved.option.clone(),
12268 item: match kind {
12269 ItemKind::Task => ContradictedItem::Task(resolved.task()?),
12270 ItemKind::Project => ContradictedItem::Project(resolved.project()),
12271 },
12272 });
12273 }
12274 let info = items
12275 .get("pageInfo")
12276 .ok_or_else(|| SourceError::Malformed {
12277 message: "GitHub project items have no pageInfo".into(),
12278 })?;
12279 if !required_bool(info, "hasNextPage")? {
12280 return Ok(found);
12281 }
12282 let next = required_str(info, "endCursor")?;
12283 validate_cursor_progress(after.as_deref(), next)?;
12284 after = Some(next.to_owned());
12285 }
12286 }
12287
12288 /// What this board holds for each issue in `issues`, once each in the order given, read
12289 /// [`REFERENCE_BATCH`] references at a time — and nothing else of the board.
12290 ///
12291 /// An issue GitHub cannot find for this source's credential, and one with no item on this
12292 /// board, are both absent. A closure that already says the work will not be done here —
12293 /// not planned, duplicate — is skipped: a landing does not overrule it. An item closed as
12294 /// completed whose card sits at its kind's `done` option is unchanged, and every other item
12295 /// is due a `done` write. A project item — a plan's home card, its issue holding the plan's
12296 /// tasks as sub-issues — is held under exactly these rules, judged against the project
12297 /// kind's half of `status_mapping`.
12298 async fn holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
12299 let mut distinct: Vec<IssueRef> = Vec::with_capacity(issues.len());
12300 for issue in issues {
12301 if !distinct.contains(issue) {
12302 distinct.push(issue.clone());
12303 }
12304 }
12305 let done = |kind: ItemKind| {
12306 self.statuses
12307 .target(kind, StatusCategory::Done)
12308 .option()
12309 .unwrap_or("Done")
12310 .to_owned()
12311 };
12312 // GitHub numbers an issue with a GraphQL `Int`, a signed 32-bit value, so a reference past
12313 // its range names no issue any repository can hold: it is answered absent and never sent,
12314 // where binding it would have GitHub refuse the whole batch.
12315 let readable: Vec<IssueRef> = distinct
12316 .iter()
12317 .filter(|issue| i32::try_from(issue.number).is_ok())
12318 .cloned()
12319 .collect();
12320 let mut holdings = Vec::with_capacity(readable.len());
12321 for batch in readable.chunks(REFERENCE_BATCH) {
12322 let data = self
12323 .graphql(graphql::ISSUES_BY_REFERENCE, reference_batch(batch))
12324 .await?;
12325 for (slot, issue) in batch.iter().enumerate() {
12326 let node = referenced_issue(&data, slot)?;
12327 let resolved = match node {
12328 Some(node) => self.resolve_issue_as(&held_issue(node)?, false).await?,
12329 None => None,
12330 };
12331 // A task and a project are both held; a document is not work, so nothing is.
12332 let Some((item, kind)) = resolved.and_then(|item| match item.kind {
12333 BoardKind::Work(kind) => Some((item, kind)),
12334 BoardKind::Document => None,
12335 }) else {
12336 holdings.push(IssueHolding {
12337 issue: issue.clone(),
12338 completion: Completion::Absent,
12339 });
12340 continue;
12341 };
12342 let task = match kind {
12343 ItemKind::Task => {
12344 let held = item.task()?;
12345 HeldTask {
12346 id: held.id,
12347 kind,
12348 option: item.option.clone(),
12349 classification: held.classification,
12350 repositories: held.repositories,
12351 delivers: held.delivers,
12352 }
12353 }
12354 // A project delivers no task, so what its write keeps in step is nothing.
12355 ItemKind::Project => {
12356 let held = item.project();
12357 HeldTask {
12358 id: held.id,
12359 kind,
12360 option: item.option.clone(),
12361 classification: held.classification,
12362 repositories: held.repositories,
12363 delivers: Vec::new(),
12364 }
12365 }
12366 };
12367 let done = done(kind);
12368 let completion = match (item.closed, item.reason.as_deref()) {
12369 (true, Some(reason @ ("NOT_PLANNED" | "DUPLICATE"))) => Completion::Skipped {
12370 task,
12371 reason: format!("closed as {}", spoken_reason(reason)),
12372 },
12373 (true, None | Some("COMPLETED"))
12374 if item
12375 .option
12376 .as_deref()
12377 .is_some_and(|option| option.eq_ignore_ascii_case(&done)) =>
12378 {
12379 Completion::Unchanged { task }
12380 }
12381 _ => {
12382 let kept = item.clone();
12383 self.held_cache
12384 .lock()
12385 .map_err(|_| SourceError::Unavailable {
12386 message: "items read by issue reference were left \
12387 inconsistent; run the command again"
12388 .into(),
12389 })?
12390 .insert(kept.id.clone(), kept);
12391 Completion::Due {
12392 task,
12393 to: done.clone(),
12394 }
12395 }
12396 };
12397 holdings.push(IssueHolding {
12398 issue: issue.clone(),
12399 completion,
12400 });
12401 }
12402 }
12403 let mut read = holdings.into_iter();
12404 let mut answered = Vec::with_capacity(distinct.len());
12405 for issue in distinct {
12406 if i32::try_from(issue.number).is_ok() {
12407 answered.push(read.next().ok_or_else(|| SourceError::Malformed {
12408 message: format!("no holding was read for {issue}"),
12409 })?);
12410 } else {
12411 answered.push(IssueHolding {
12412 issue,
12413 completion: Completion::Absent,
12414 });
12415 }
12416 }
12417 Ok(answered)
12418 }
12419}
12420
12421#[async_trait::async_trait]
12422impl TaskSource for GitHubProjectsSource {
12423 fn kind(&self) -> &'static str {
12424 KIND
12425 }
12426 fn order_versions(&self, a: &str, b: &str) -> Option<std::cmp::Ordering> {
12427 change_token::order(a, b)
12428 }
12429 /// A task's fields and comments: §4.13d of `docs/plugin-protocol.md` states, member by
12430 /// member, the change each part of the token moves for. Not its forward edges — see
12431 /// [`FAR_ENDS_UNCOVERED`].
12432 fn version_coverage(&self) -> VersionCoverage {
12433 VersionCoverage {
12434 forward_edges: Coverage::Uncovered {
12435 reason: FAR_ENDS_UNCOVERED.to_owned(),
12436 },
12437 ..VersionCoverage::whole()
12438 }
12439 }
12440 /// Every part, for a copy's skip: the relationship count moves for an edge added or removed
12441 /// and for a far end deleted, so the token sees every change to a task's edges but one — a
12442 /// far end's own kind flipping, by gaining a sub-issue or being retitled into a document,
12443 /// which `spike-coverage` measured stale 1 of 1. A skipping recopy does not carry that, and
12444 /// the next copy that reads the task does (`docs/plugin-protocol.md` §4.13d).
12445 // 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.
12446 fn copy_version_coverage(&self) -> VersionCoverage {
12447 VersionCoverage::whole()
12448 }
12449 /// A project's fields, and not its forward edges, for the same reason a task's are not.
12450 fn project_version_coverage(&self) -> ProjectVersionCoverage {
12451 ProjectVersionCoverage {
12452 fields: Coverage::Covered,
12453 forward_edges: Coverage::Uncovered {
12454 reason: FAR_ENDS_UNCOVERED.to_owned(),
12455 },
12456 }
12457 }
12458 /// A document's fields and the manifest of its image assets, which its metadata slot
12459 /// records: both are the issue's body, whose every edit moves the token's issue time.
12460 fn document_version_coverage(&self) -> DocumentVersionCoverage {
12461 DocumentVersionCoverage::whole()
12462 }
12463 fn write_context(&self, id: &NativeId) -> Option<Value> {
12464 self.context_of(id)
12465 }
12466 fn board_context(&self) -> Option<Value> {
12467 self.board_context_held()
12468 }
12469 fn prime_write(&self, id: &NativeId, context: &Value, board: Option<&Value>) -> bool {
12470 self.prime(id, context, board)
12471 }
12472 fn unprime(&self, id: &NativeId) {
12473 self.unprime_held(id);
12474 }
12475 fn begin_journal(&self) {
12476 self.expected.begin();
12477 }
12478 fn end_journal(&self) -> Option<WriteJournal> {
12479 Some(self.expected.end())
12480 }
12481 fn capabilities(&self) -> Capabilities {
12482 Capabilities {
12483 projects: Support::Native,
12484 documents: Support::Native,
12485 comments: Support::Native,
12486 assets: Support::Native,
12487 priority: if self.priorities.is_some() {
12488 Support::Native
12489 } else {
12490 Support::Unsupported
12491 },
12492 filter_by_priority: Support::Native,
12493 filter_by_comment_activity: Support::Native,
12494 filter_by_metadata: Support::Native,
12495 filter_by_origin: Support::Native,
12496 reconcile_status: Support::Native,
12497 complete_by_issue: Support::Native,
12498 orphan_tasks: Support::Native,
12499 filter_by_label: Support::Native,
12500 filter_by_status: Support::Native,
12501 search_title: Support::Native,
12502 search_content: Support::Native,
12503 task_dependencies: DependencySupport::BothDirections,
12504 project_dependencies: DependencySupport::BothDirections,
12505 max_page_size: MAX_PAGE_SIZE,
12506 }
12507 }
12508 async fn visibility(
12509 &self,
12510 target: &onetaskgraph_plugin_api::WriteTarget<'_>,
12511 ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
12512 self.write_visibility(target).await
12513 }
12514 async fn health(&self) -> Result<Health, SourceError> {
12515 let board = self.board_page(None, 1).await?;
12516 Ok(Health {
12517 reachable: true,
12518 detail: Some(format!(
12519 "reading GitHub project {}/{} ({})",
12520 self.owner,
12521 self.project_number,
12522 required_str(&board, "title")?
12523 )),
12524 })
12525 }
12526 /// The board's own node id, digested: the one request reading its fields, or none when
12527 /// this command has read them already.
12528 async fn designator(&self) -> Result<Option<Designator>, SourceError> {
12529 let board = self.board_fields().await?;
12530 Designator::of_backend(KIND, board.id.as_str())
12531 .map(Some)
12532 .map_err(|message| SourceError::Malformed { message })
12533 }
12534 async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
12535 self.item_by_id(id)
12536 .await?
12537 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
12538 .map(|item| item.task())
12539 .transpose()
12540 }
12541 async fn task_assets(
12542 &self,
12543 id: &NativeId,
12544 ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
12545 self.held_assets(id, BoardKind::Work(ItemKind::Task)).await
12546 }
12547 async fn task_asset(
12548 &self,
12549 id: &NativeId,
12550 name: &onetaskgraph_plugin_api::AssetName,
12551 ) -> Result<Option<Vec<u8>>, SourceError> {
12552 self.held_asset(id, BoardKind::Work(ItemKind::Task), name)
12553 .await
12554 }
12555 async fn set_task_rendering_with_assets(
12556 &self,
12557 id: &NativeId,
12558 content: &str,
12559 provenance: &Value,
12560 _answers: &BTreeMap<String, Value>,
12561 assets: &onetaskgraph_plugin_api::AssetWrite,
12562 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
12563 self.replace_rendering(
12564 id,
12565 BoardKind::Work(ItemKind::Task),
12566 content,
12567 provenance,
12568 Some(assets),
12569 )
12570 .await
12571 }
12572 async fn document_assets(
12573 &self,
12574 id: &NativeId,
12575 ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
12576 self.held_assets(id, BoardKind::Document).await
12577 }
12578 async fn document_asset(
12579 &self,
12580 id: &NativeId,
12581 name: &onetaskgraph_plugin_api::AssetName,
12582 ) -> Result<Option<Vec<u8>>, SourceError> {
12583 self.held_asset(id, BoardKind::Document, name).await
12584 }
12585 async fn set_document_rendering_with_assets(
12586 &self,
12587 id: &NativeId,
12588 content: &str,
12589 provenance: &Value,
12590 _answers: &BTreeMap<String, Value>,
12591 assets: &onetaskgraph_plugin_api::AssetWrite,
12592 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
12593 self.replace_rendering(id, BoardKind::Document, content, provenance, Some(assets))
12594 .await
12595 }
12596 async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
12597 Ok(self
12598 .item_by_id(id)
12599 .await?
12600 .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
12601 .map(|item| item.project()))
12602 }
12603 async fn query_tasks(
12604 &self,
12605 query: &TaskQuery,
12606 page: &PageRequest,
12607 ) -> Result<Page<Task>, SourceError> {
12608 validate_page(page)?;
12609 refuse_unsearchable(query)?;
12610 // A closed issue reads `done`, `cancelled` or — closed for a reason that implies no
12611 // category — `unknown`; every other category reads only off an open issue or a draft. So
12612 // a status filter naming none of those three asks every issue search it sends for open
12613 // issues alone; each candidate's category is still confirmed from its own item below.
12614 let open_only = !query.statuses.is_empty()
12615 && query.statuses.iter().all(|category| {
12616 !matches!(
12617 category,
12618 StatusCategory::Done | StatusCategory::Cancelled | StatusCategory::Unknown
12619 )
12620 });
12621 if query.origin.is_none() && !matches!(query.project, ProjectFilter::Is(_)) {
12622 let mut qualifiers: Vec<String> = [
12623 query.commented_since.map(updated_qualifier),
12624 narrowing_qualifiers(query),
12625 ]
12626 .into_iter()
12627 .flatten()
12628 .collect();
12629 // A narrowed search never answers a draft, which is no issue, so narrowing it to
12630 // open issues too leaves out nothing such a search could have answered.
12631 if !qualifiers.is_empty() {
12632 if open_only {
12633 qualifiers.push(OPEN_QUALIFIER.to_owned());
12634 }
12635 return self.search_tasks(query, page, &qualifiers.join(" ")).await;
12636 }
12637 }
12638
12639 // A read narrowed to one project asks that project for its own tasks, so nothing
12640 // about it costs what the rest of the board holds. A read carrying a text, metadata
12641 // or origin predicate asks GitHub the narrower question those predicates are, and a
12642 // read narrowed to comment activity alone asks the board's own issue search for the
12643 // issues updated since, which is every issue a comment could have been written or
12644 // edited on since. Every other task read is a question about the whole board and is
12645 // answered by reading it.
12646 let (held, membership) = match (&query.project, query.commented_since) {
12647 (ProjectFilter::Is(project), _) => (
12648 match self.held_task_children(project)? {
12649 // Taken as `project_children` takes the project's own sub-issue read: with
12650 // every item this process wrote under it since, and none it moved away.
12651 Some(held) => self.completed_with_written(
12652 held.into_iter()
12653 .filter(|child| child.parent.as_ref() == Some(project))
12654 .collect(),
12655 |own| own.parent.as_ref() == Some(project),
12656 )?,
12657 None => self.project_children(project).await?,
12658 },
12659 // Answered by where these items came from; see `task_matches`.
12660 &ProjectFilter::Any,
12661 ),
12662 (ProjectFilter::Any | ProjectFilter::Orphans, since) => {
12663 match (self.narrowed(query).await?, since) {
12664 (Some(narrowed), _) => (narrowed, &query.project),
12665 (None, Some(since)) => (self.updated_since(since).await?, &query.project),
12666 // The board's own items list every draft; only the search half, which
12667 // completes them with issues they lag behind on, is narrowed — a closed
12668 // issue that half leaves out is at no category the filter keeps.
12669 (None, None) if open_only => (
12670 self.board_completed_by(Some(OPEN_QUALIFIER)).await?.items,
12671 &query.project,
12672 ),
12673 (None, None) => (self.board().await?.items, &query.project),
12674 }
12675 }
12676 };
12677 // Filtered before paged: a page of a filtered result is a page of the survivors,
12678 // never the survivors of a page.
12679 let mut tasks = Vec::new();
12680 for item in held
12681 .iter()
12682 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
12683 {
12684 let task = item.task()?;
12685 if task_matches(&task, query, membership)
12686 && self.commented_since(item, query.commented_since).await?
12687 {
12688 tasks.push(task);
12689 }
12690 }
12691 Ok(offset_page(
12692 tasks,
12693 numeric_cursor(page.cursor.as_ref())?,
12694 page.limit.min(MAX_PAGE_SIZE) as usize,
12695 ))
12696 }
12697 async fn query_projects(
12698 &self,
12699 query: &ProjectQuery,
12700 page: &PageRequest,
12701 ) -> Result<Page<Project>, SourceError> {
12702 validate_page(page)?;
12703 refuse_unsearchable_text(query.text.as_ref())?;
12704 // The projects a board holds are found by an issue search scoped to that board,
12705 // never by walking the board's own item connection: what tells a project from a
12706 // task is the `parent` each issue carries, which costs nothing to read. A query
12707 // carrying a text asks that search for the text too, so it reads the issues that
12708 // hold it rather than every issue of the board.
12709 let held = match self.text_searched(query.text.as_ref()).await? {
12710 Some(searched) => searched,
12711 None => self.board_issues().await?,
12712 };
12713 let projects = held
12714 .iter()
12715 .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
12716 .map(Resolved::project)
12717 .filter(|project| project_matches(project, query))
12718 .collect();
12719 Ok(offset_page(
12720 projects,
12721 numeric_cursor(page.cursor.as_ref())?,
12722 page.limit.min(MAX_PAGE_SIZE) as usize,
12723 ))
12724 }
12725 async fn query_projects_by_origin(
12726 &self,
12727 origin: &str,
12728 page: &PageRequest,
12729 ) -> Result<Page<Project>, SourceError> {
12730 validate_page(page)?;
12731 let projects = self
12732 .copied_from(origin, BoardKind::Work(ItemKind::Project))
12733 .await?
12734 .iter()
12735 .map(Resolved::project)
12736 .collect();
12737 Ok(offset_page(
12738 projects,
12739 numeric_cursor(page.cursor.as_ref())?,
12740 page.limit.min(MAX_PAGE_SIZE) as usize,
12741 ))
12742 }
12743 async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
12744 let Some(item) = self
12745 .item_by_id(id)
12746 .await?
12747 .filter(|item| item.kind == BoardKind::Document)
12748 else {
12749 return Ok(None);
12750 };
12751 self.expected.read_document(&item);
12752 Ok(Some(item.document()))
12753 }
12754 async fn query_documents_by_origin(
12755 &self,
12756 origin: &str,
12757 page: &PageRequest,
12758 ) -> Result<Page<Document>, SourceError> {
12759 validate_page(page)?;
12760 let documents = self
12761 .copied_from(origin, BoardKind::Document)
12762 .await?
12763 .iter()
12764 .map(Resolved::document)
12765 .collect();
12766 Ok(offset_page(
12767 documents,
12768 numeric_cursor(page.cursor.as_ref())?,
12769 page.limit.min(MAX_PAGE_SIZE) as usize,
12770 ))
12771 }
12772 async fn query_documents(
12773 &self,
12774 query: &DocumentQuery,
12775 page: &PageRequest,
12776 ) -> Result<Page<Document>, SourceError> {
12777 validate_page(page)?;
12778 // Narrowed to one project, this is the same sub-issue read a task list scoped to
12779 // that project makes — a document filed under a project is a sub-issue of it too,
12780 // and which of them come back is the kind this caller asked for. Unscoped, a query
12781 // carrying a text asks the board-scoped issue search for it, as a task query does,
12782 // and only one carrying none reads the board.
12783 let (held, membership) = match &query.project {
12784 ProjectFilter::Is(project) => (
12785 self.project_children(project).await?,
12786 // Answered by where these items came from; see `task_matches`.
12787 &ProjectFilter::Any,
12788 ),
12789 ProjectFilter::Any | ProjectFilter::Orphans => {
12790 refuse_unsearchable_text(query.text.as_ref())?;
12791 match self.text_searched(query.text.as_ref()).await? {
12792 Some(searched) => (searched, &query.project),
12793 None => (self.board().await?.items, &query.project),
12794 }
12795 }
12796 };
12797 // Filtered before paged, exactly as a task read is: a page of a filtered result is
12798 // a page of the survivors, never the survivors of a page.
12799 let documents = held
12800 .iter()
12801 .filter(|item| item.kind == BoardKind::Document)
12802 .map(Resolved::document)
12803 .filter(|document| document_matches(document, query, membership))
12804 .collect();
12805 Ok(offset_page(
12806 documents,
12807 numeric_cursor(page.cursor.as_ref())?,
12808 page.limit.min(MAX_PAGE_SIZE) as usize,
12809 ))
12810 }
12811 async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
12812 validate_page(page)?;
12813 let offset = numeric_cursor(page.cursor.as_ref())?;
12814 let mut labels = self
12815 .board()
12816 .await?
12817 .items
12818 .into_iter()
12819 .flat_map(|item| item.labels)
12820 .fold(Vec::new(), |mut all, label| {
12821 if !all.iter().any(|x: &Label| x.id == label.id) {
12822 all.push(label);
12823 }
12824 all
12825 });
12826 labels.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.0.cmp(&b.id.0)));
12827 Ok(offset_page(
12828 labels,
12829 offset,
12830 page.limit.min(MAX_PAGE_SIZE) as usize,
12831 ))
12832 }
12833 async fn task_dependencies(
12834 &self,
12835 id: &NativeId,
12836 direction: Direction,
12837 page: &PageRequest,
12838 ) -> Result<Page<DependencyEdge>, SourceError> {
12839 self.dependencies(id, ItemKind::Task, direction, page).await
12840 }
12841 async fn project_dependencies(
12842 &self,
12843 id: &NativeId,
12844 direction: Direction,
12845 page: &PageRequest,
12846 ) -> Result<Page<DependencyEdge>, SourceError> {
12847 self.dependencies(id, ItemKind::Project, direction, page)
12848 .await
12849 }
12850
12851 fn writes(&self) -> WriteSupport {
12852 WriteSupport::Supported
12853 }
12854
12855 /// Create or update one task.
12856 ///
12857 /// Its `delivers` and `delivered_by` are checked before anything is read or written —
12858 /// neither may name the task itself or name one task twice — and land in the body's
12859 /// metadata slot under their reserved keys, in place of any caller metadata of those
12860 /// names.
12861 async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
12862 self.write_task_assets(write, None)
12863 .await
12864 .map(|written| written.id)
12865 }
12866
12867 async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
12868 self.origins_ahead(origins).await
12869 }
12870
12871 /// The issue's own web address, as the `createIssue` that made it in this command answered
12872 /// it: a task, a project and a document are each an issue here.
12873 fn written_location(
12874 &self,
12875 _record: onetaskgraph_plugin_api::MetadataRecord,
12876 id: &NativeId,
12877 ) -> Option<Location> {
12878 self.written
12879 .lock()
12880 .unwrap_or_else(std::sync::PoisonError::into_inner)
12881 .get(id)
12882 .cloned()
12883 .map(Location::Url)
12884 }
12885
12886 /// [`MUTATION_BATCH`], while writes are held back: [`graphql::CREATE_ISSUES`] creates that many
12887 /// in one request, and a copy's tasks are created together only then, since their fields
12888 /// and edges are what is held back.
12889 fn create_batch_limit(&self) -> usize {
12890 if self.deferring().unwrap_or(false) {
12891 MUTATION_BATCH
12892 } else {
12893 1
12894 }
12895 }
12896
12897 // llmlint: ignore[invalid_states_unrepresentable] The signature is the plugin contract's additive `TaskSource::write_tasks`, which the manager approved taking `ItemWrite<Task>` as `write_task` does; a create-only input type would be a new contract type. A write naming an existing target is refused below before anything is sent.
12898 async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
12899 if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
12900 return Err(SourceError::Refused {
12901 message: format!(
12902 "write_tasks creates tasks, and the write of {} names the existing task {}; \
12903 next: update it with write_task",
12904 write.item.id,
12905 write.target.as_ref().map_or("", |target| target.0.as_str())
12906 ),
12907 });
12908 }
12909 if !self.deferring()? {
12910 let mut created = Vec::with_capacity(writes.len());
12911 for write in writes {
12912 match self.write_task(write).await {
12913 Ok(id) => created.push(id),
12914 Err(error) => {
12915 let mut left: Vec<&str> = Vec::new();
12916 for id in &created {
12917 if self.delete_issue(id).await.is_err() {
12918 left.push(id.0.as_str());
12919 }
12920 }
12921 return Err(left_behind(error, &left));
12922 }
12923 }
12924 }
12925 return Ok(created);
12926 }
12927 self.create_together(writes).await
12928 }
12929
12930 fn begin_deferred_writes(&self) {
12931 if let Ok(mut deferred) = self.deferred.lock() {
12932 deferred.get_or_insert_with(Deferred::default);
12933 }
12934 }
12935
12936 async fn finish_writes(&self) -> Result<(), SourceError> {
12937 self.send_held_back().await
12938 }
12939
12940 async fn write_task_with_assets(
12941 &self,
12942 write: &ItemWrite<Task>,
12943 _answers: Option<&BTreeMap<String, Value>>,
12944 assets: &onetaskgraph_plugin_api::AssetWrite,
12945 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
12946 self.write_task_assets(write, Some(assets)).await
12947 }
12948
12949 async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
12950 self.write_item(
12951 &Incoming {
12952 written: Written::Work(ItemKind::Project, &write.item.status),
12953 title: &write.item.title,
12954 content: write.item.content.as_deref(),
12955 assets: None,
12956 labels: &write.item.labels,
12957 metadata: &write.item.metadata,
12958 repositories: &write.item.repositories,
12959 classification: write.item.classification,
12960 parent: None,
12961 delivers: &[],
12962 delivered_by: &[],
12963 priority: None,
12964 },
12965 write.target.as_ref(),
12966 &write.depends_on,
12967 )
12968 .await
12969 .map(|written| written.id)
12970 }
12971
12972 /// Create or update one document, which is one issue titled the way this board spells
12973 /// a document.
12974 ///
12975 /// Everything else is exactly a task write: caller metadata goes to the same canonical
12976 /// JSON slot at the end of the body and comes back with its JSON types intact, a key
12977 /// or a field this board cannot carry is refused by name rather than dropped, a target
12978 /// naming an issue this board does not hold is refused rather than created, and an
12979 /// issue this call created is taken back when the rest of the write fails.
12980 async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
12981 self.write_document_assets(write, None)
12982 .await
12983 .map(|written| written.id)
12984 }
12985
12986 async fn write_document_with_assets(
12987 &self,
12988 write: &ItemWrite<Document>,
12989 _answers: Option<&BTreeMap<String, Value>>,
12990 assets: &onetaskgraph_plugin_api::AssetWrite,
12991 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
12992 self.write_document_assets(write, Some(assets)).await
12993 }
12994
12995 /// Refused exactly as the write refuses it, from what the write reads: the mapping first,
12996 /// which reads nothing; then the board's `Status` option. Over an existing item that is
12997 /// read off the item, as the write reads it, and the item is held among this command's
12998 /// resolved records so the write that follows reuses that read rather than repeating it;
12999 /// an item that does not carry the field takes the board's fields, which are held once
13000 /// read. A create is checked against the board's fields only when this command already
13001 /// holds them, because a create reads them together with its repository, in one request,
13002 /// and refuses a missing option before it writes anything.
13003 async fn check_status_write(
13004 &self,
13005 kind: ItemKind,
13006 category: StatusCategory,
13007 target: Option<&NativeId>,
13008 ) -> Result<(), SourceError> {
13009 let status = self.resolved_target(kind, category)?;
13010 if status.option().is_none() {
13011 return Ok(());
13012 }
13013 let fields = match target {
13014 Some(target) => {
13015 // A target this board does not hold is the write's own refusal to make.
13016 let Some(item) = self.bound_item(target).await? else {
13017 return Ok(());
13018 };
13019 self.resolved_cache()?.insert(target.clone(), item.clone());
13020 self.fields_for(Some(&item), true, false).await?.fields
13021 }
13022 None => {
13023 let held = self
13024 .board_cache()?
13025 .as_ref()
13026 .map(|board| board.fields.clone());
13027 match held.or_else(|| {
13028 self.fields_cache()
13029 .ok()
13030 .and_then(|cache| cache.as_ref().map(|board| board.fields.clone()))
13031 }) {
13032 Some(fields) => fields,
13033 None => return Ok(()),
13034 }
13035 }
13036 };
13037 self.column_for(&fields, kind, category, &status)
13038 .map(|_| ())
13039 }
13040
13041 /// What a write of `status` reads back as: the `Status` option its category maps to for
13042 /// `kind`, and for a closing category the closure that option and its fixed reason read
13043 /// as — exactly what [`BoardStatuses::status`] reports of the item once written. A category
13044 /// this instance has no option for is answered as given, since writing it is refused.
13045 fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
13046 match self.statuses.target(kind, status.category) {
13047 StatusTarget::Column(name) => {
13048 self.statuses.status(kind, Some(name.as_str()), false, None)
13049 }
13050 StatusTarget::Terminal(name, reason) => {
13051 self.statuses
13052 .status(kind, Some(name.as_str()), true, Some(reason.reason()))
13053 }
13054 StatusTarget::Disabled(_) => status.clone(),
13055 }
13056 }
13057
13058 /// Set one task's status alone.
13059 ///
13060 /// An open target reopens a closed issue with an `updateIssue` carrying only its
13061 /// `stateInput`, then selects the board option with `updateProjectV2ItemFieldValue`; a
13062 /// terminal target selects its mapped option, then closes with its fixed reason. No
13063 /// request carries a title, a body or a label. The status
13064 /// answered is what [`BoardStatuses::status`] reads off the state just written, which is
13065 /// what a re-read reports.
13066 async fn set_task_status(
13067 &self,
13068 id: &NativeId,
13069 category: StatusCategory,
13070 ) -> Result<Option<Status>, SourceError> {
13071 self.set_status(id, ItemKind::Task, category).await
13072 }
13073
13074 /// Set one task's status and answer the task with it, reading the item once: the read the
13075 /// task is answered from is handed to the status write, which would otherwise read the
13076 /// same issue again — two requests on a fresh process, the read and the field write,
13077 /// where the default's `get_task` before `set_task_status` sent three.
13078 async fn set_task_status_reading(
13079 &self,
13080 id: &NativeId,
13081 category: StatusCategory,
13082 ) -> Result<Option<Task>, SourceError> {
13083 // Refused before anything is read, in the words the write itself refuses it.
13084 self.resolved_target(ItemKind::Task, category)?;
13085 let Some(item) = self
13086 .bound_item(id)
13087 .await?
13088 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
13089 else {
13090 return Ok(None);
13091 };
13092 let mut task = item.task()?;
13093 self.held_cache
13094 .lock()
13095 .map_err(|_| SourceError::Unavailable {
13096 message: "items read by issue reference were left inconsistent; run the \
13097 command again"
13098 .into(),
13099 })?
13100 .insert(id.clone(), item);
13101 let Some(status) = self.set_status(id, ItemKind::Task, category).await? else {
13102 return Ok(None);
13103 };
13104 task.status = status;
13105 Ok(Some(task))
13106 }
13107
13108 /// Set one project's status alone, by exactly the paired write a task's status takes, for
13109 /// the project kind: a terminal category selects the project kind's mapped option and then
13110 /// closes the issue with the category's fixed reason — an issue already closed with a
13111 /// reason that reads that category is left as it is — and an open category reopens a closed
13112 /// issue and then selects its option. A board draft is refused a terminal category as a
13113 /// task's is.
13114 async fn set_project_status(
13115 &self,
13116 id: &NativeId,
13117 category: StatusCategory,
13118 ) -> Result<Option<Status>, SourceError> {
13119 self.set_status(id, ItemKind::Project, category).await
13120 }
13121
13122 /// Every task and project whose card contradicts its issue's closure, read through the
13123 /// board's own `is:closed` filter; see [`TaskSource::status_contradictions`].
13124 async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
13125 self.contradictions().await
13126 }
13127
13128 /// What this board holds for each issue reference, one request per fifty of them; see
13129 /// [`TaskSource::issue_holdings`].
13130 async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
13131 self.holdings(issues).await
13132 }
13133
13134 /// Set one task's priority alone: one `updateProjectV2ItemFieldValue` selecting the
13135 /// mapped option of the board's `Priority` field, or one `clearProjectV2ItemFieldValue`
13136 /// for `none`. Refused by an instance with no `priority_mapping`.
13137 async fn set_task_priority(
13138 &self,
13139 id: &NativeId,
13140 priority: Priority,
13141 ) -> Result<Option<Priority>, SourceError> {
13142 self.set_priority(id, priority).await
13143 }
13144
13145 /// Replace one task's content with a single body update that keeps the metadata slot
13146 /// byte for byte.
13147 async fn set_task_content(
13148 &self,
13149 id: &NativeId,
13150 content: &str,
13151 ) -> Result<Option<()>, SourceError> {
13152 self.replace_content(id, content).await
13153 }
13154
13155 /// Replace one task issue's content and its provenance slot entry with a single body
13156 /// update. The answers are not kept: see `replace_rendering`.
13157 async fn set_task_rendering(
13158 &self,
13159 id: &NativeId,
13160 content: &str,
13161 provenance: &Value,
13162 _answers: &BTreeMap<String, Value>,
13163 ) -> Result<Option<()>, SourceError> {
13164 self.replace_rendering(
13165 id,
13166 BoardKind::Work(ItemKind::Task),
13167 content,
13168 provenance,
13169 None,
13170 )
13171 .await
13172 .map(|written| written.map(|_| ()))
13173 }
13174
13175 /// Replace one design-document issue's content and its provenance slot entry, on exactly
13176 /// the terms of [`set_task_rendering`](TaskSource::set_task_rendering).
13177 async fn set_document_rendering(
13178 &self,
13179 id: &NativeId,
13180 content: &str,
13181 provenance: &Value,
13182 _answers: &BTreeMap<String, Value>,
13183 ) -> Result<Option<()>, SourceError> {
13184 self.replace_rendering(id, BoardKind::Document, content, provenance, None)
13185 .await
13186 .map(|written| written.map(|_| ()))
13187 }
13188
13189 /// Replace one project issue's content and its provenance slot entry, on exactly the
13190 /// terms of [`set_task_rendering`](TaskSource::set_task_rendering).
13191 async fn set_project_rendering(
13192 &self,
13193 id: &NativeId,
13194 content: &str,
13195 provenance: &Value,
13196 _answers: &BTreeMap<String, Value>,
13197 ) -> Result<Option<()>, SourceError> {
13198 self.replace_rendering(
13199 id,
13200 BoardKind::Work(ItemKind::Project),
13201 content,
13202 provenance,
13203 None,
13204 )
13205 .await
13206 .map(|written| written.map(|_| ()))
13207 }
13208
13209 /// Apply a targeted update with one read of the item and a write only for what differs:
13210 /// the `Status` and `Priority` field writes in one request, the `blockedBy` difference,
13211 /// and last one `updateIssue` for title, body and state. See `targeted_update`.
13212 async fn update_task(
13213 &self,
13214 id: &NativeId,
13215 update: &TaskUpdate,
13216 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
13217 self.targeted_update(id, update).await
13218 }
13219
13220 /// Replace one task's `delivered_by` with a single body update that changes the
13221 /// metadata slot and nothing outside it.
13222 async fn set_delivered_by(
13223 &self,
13224 id: &NativeId,
13225 delivered_by: &[TaskRef],
13226 ) -> Result<Option<()>, SourceError> {
13227 self.replace_delivered_by(id, delivered_by).await
13228 }
13229
13230 /// Set one key of one task issue's metadata with a single body update that changes the
13231 /// metadata slot and nothing outside it — no title, label, state or board field request —
13232 /// and sends nothing when the task already holds that value under the key.
13233 async fn set_task_metadata(
13234 &self,
13235 id: &NativeId,
13236 key: &MetadataKey,
13237 value: &Value,
13238 ) -> Result<Option<Task>, SourceError> {
13239 Ok(self
13240 .set_slot_key(id, BoardKind::Work(ItemKind::Task), key, value)
13241 .await?
13242 .map(|item| item.task())
13243 .transpose()?)
13244 }
13245
13246 /// Set one key of one project issue's metadata, on exactly the terms of
13247 /// [`set_task_metadata`](TaskSource::set_task_metadata).
13248 async fn set_project_metadata(
13249 &self,
13250 id: &NativeId,
13251 key: &MetadataKey,
13252 value: &Value,
13253 ) -> Result<Option<Project>, SourceError> {
13254 Ok(self
13255 .set_slot_key(id, BoardKind::Work(ItemKind::Project), key, value)
13256 .await?
13257 .map(|item| item.project()))
13258 }
13259
13260 /// Set one key of one design-document issue's metadata, on exactly the terms of
13261 /// [`set_task_metadata`](TaskSource::set_task_metadata).
13262 async fn set_document_metadata(
13263 &self,
13264 id: &NativeId,
13265 key: &MetadataKey,
13266 value: &Value,
13267 ) -> Result<Option<Document>, SourceError> {
13268 Ok(self
13269 .set_slot_key(id, BoardKind::Document, key, value)
13270 .await?
13271 .map(|item| item.document()))
13272 }
13273
13274 async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
13275 self.delete_item(id).await
13276 }
13277
13278 async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
13279 self.delete_item(id).await
13280 }
13281
13282 async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
13283 self.delete_item(id).await
13284 }
13285
13286 /// One page of the task issue's own comments, walked by GitHub's own cursor.
13287 ///
13288 /// Nothing here filters, so nothing has to be read ahead of the page: the caller's limit is
13289 /// the page GitHub is asked for and GitHub's `endCursor` is the cursor handed back.
13290 ///
13291 /// One request, [`graphql::ISSUE_DETAIL`]: the read that says the id names a task of this
13292 /// board is the read of its comments. A draft this process already resolved is refused
13293 /// without one.
13294 async fn task_comments(
13295 &self,
13296 task: &NativeId,
13297 page: &PageRequest,
13298 ) -> Result<Option<Page<Comment>>, SourceError> {
13299 validate_page(page)?;
13300 let cached = self.resolved_cache()?.get(task).cloned();
13301 if let Some(item) = cached {
13302 if item.kind != BoardKind::Work(ItemKind::Task) {
13303 return Ok(None);
13304 }
13305 if item.content_kind == ContentKind::DraftIssue {
13306 return Err(self.draft_has_no_comments(task));
13307 }
13308 }
13309 match self.issue_detail(task, page).await? {
13310 Some(TaskDetailRead {
13311 comments: Some(comments),
13312 ..
13313 }) => comments,
13314 _ => Ok(None),
13315 }
13316 }
13317
13318 /// Every id's task, with the first page of its comments when `comments` names it:
13319 /// [`DETAIL_BATCH`] items per [`graphql::ISSUE_DETAILS`] request, and one item with its
13320 /// comments in one [`graphql::ISSUE_DETAIL`] request.
13321 async fn get_task_details(
13322 &self,
13323 ids: &[NativeId],
13324 comments: Option<&PageRequest>,
13325 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
13326 if let Some(page) = comments
13327 && let Err(error) = validate_page(page)
13328 {
13329 return ids.iter().map(|_| Err(error.clone())).collect();
13330 }
13331 match (ids, comments) {
13332 ([id], Some(page)) => vec![self.issue_detail(id, page).await],
13333 ([id], None) => vec![self.task_read(id).await],
13334 _ => self.issue_details(ids, comments).await,
13335 }
13336 }
13337
13338 /// Every id's task with the first page of its comments and its `blockedBy`, as a copy reads
13339 /// the tasks it carries: [`COPY_DETAIL_BATCH`] items per [`graphql::ISSUE_COPY_DETAILS`]
13340 /// request, so the dependency read a copy makes of each next is answered from this one.
13341 async fn get_task_details_for_copy(
13342 &self,
13343 ids: &[NativeId],
13344 comments: &PageRequest,
13345 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
13346 // A page past the first is a page of one task's comments, which the detail read of it
13347 // alone answers.
13348 if comments.cursor.is_some() {
13349 return self.get_task_details(ids, Some(comments)).await;
13350 }
13351 if let Err(error) = validate_page(comments) {
13352 return ids.iter().map(|_| Err(error.clone())).collect();
13353 }
13354 let mut read = Vec::with_capacity(ids.len());
13355 for batch in ids.chunks(COPY_DETAIL_BATCH) {
13356 match self
13357 .graphql(
13358 graphql::ISSUE_COPY_DETAILS,
13359 copy_detail_batch(batch, comments, false),
13360 )
13361 .await
13362 {
13363 Ok(data) => {
13364 for (slot, id) in batch.iter().enumerate() {
13365 let read_one = match data.get(format!("i{slot}")) {
13366 Some(node) => self.detail_of(id, node, true, None).await,
13367 None => Err(SourceError::Malformed {
13368 message: format!(
13369 "GitHub answered a batch read with no item for {}",
13370 id.0
13371 ),
13372 }),
13373 };
13374 read.push(read_one);
13375 }
13376 }
13377 Err(error) if unresolvable_node(&error) => {
13378 for id in batch {
13379 read.push(self.issue_detail(id, comments).await);
13380 }
13381 }
13382 Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
13383 }
13384 }
13385 read
13386 }
13387
13388 /// Every id's item, whatever kind it is, read [`COPY_DETAIL_BATCH`] at a time with
13389 /// [`graphql::ISSUE_COPY_DETAILS`] — the document a copy reads the tasks it carries with —
13390 /// and held for the next read of each by id; see `read_ahead`.
13391 ///
13392 /// What this run wrote is never read: its own record answers, as it does for a read by id.
13393 /// Nor is an item a listing of its project carried whole earlier in this command — see
13394 /// `carried` — which is held in place of reading it.
13395 /// A batch GitHub refuses because one of its ids resolves to no node at all holds nothing,
13396 /// so each of its ids is read on its own and answered as that read answers; a draft, and an
13397 /// answer naming another issue than the one asked for, are left to their own reads too.
13398 async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
13399 let mut unread: Vec<NativeId> = Vec::new();
13400 // Read whole by a listing of its project in this command, which a mutation naming it
13401 // would have dropped: held as a batch would have held it, once every batch is answered.
13402 let mut listed: Vec<NativeId> = Vec::new();
13403 {
13404 let created = self.created()?;
13405 let held = self.read_ahead()?;
13406 let carried = self.carried()?;
13407 for id in ids {
13408 if unread.contains(id)
13409 || listed.contains(id)
13410 || held.contains_key(id)
13411 || created.iter().any(|own| own.id == *id)
13412 {
13413 continue;
13414 }
13415 if carried.contains_key(id) {
13416 listed.push(id.clone());
13417 } else {
13418 unread.push(id.clone());
13419 }
13420 }
13421 }
13422 // Nothing of an item's comments is wanted here: the smallest page keeps the read to
13423 // what the item itself costs.
13424 let comments = PageRequest {
13425 cursor: None,
13426 limit: 1,
13427 };
13428 // Held only once every batch has been answered, so a read-ahead that fails part way
13429 // holds nothing — what a listing carried included, which stays carried — and every
13430 // item is read on its own, as the method promises.
13431 let mut read: Vec<(NativeId, Option<Resolved>)> = Vec::new();
13432 // The issues the first id names as sub-issues, as `ISSUE_COPY_DETAILS`'s `children`
13433 // answered them: what a project copy's orphan check asks, when that first id is its
13434 // project.
13435 let mut children: Option<(NativeId, Vec<(String, String)>)> = None;
13436 for (index, batch) in unread.chunks(COPY_DETAIL_BATCH).enumerate() {
13437 let data = match self
13438 .graphql(
13439 graphql::ISSUE_COPY_DETAILS,
13440 copy_detail_batch(batch, &comments, index == 0),
13441 )
13442 .await
13443 {
13444 Ok(data) => data,
13445 Err(error) if unresolvable_node(&error) => continue,
13446 Err(error) => return Err(error),
13447 };
13448 for (slot, id) in batch.iter().enumerate() {
13449 let Some(node) = data.get(format!("i{slot}")) else {
13450 continue;
13451 };
13452 let held = if node.is_null() {
13453 None
13454 } else {
13455 match optional_str(node, "__typename")? {
13456 Some("DraftIssue") => continue,
13457 Some("Issue") if required_str(node, "id")? != id.0 => continue,
13458 _ => {}
13459 }
13460 // Remembered below with the rest, so a later batch refused leaves no
13461 // dependency read answered from this one either.
13462 self.resolve_issue_as(node, false).await?
13463 };
13464 read.push((id.clone(), held));
13465 }
13466 if index == 0
13467 && let Some(node) = data.get("children").filter(|node| !node.is_null())
13468 && node.get("id").and_then(Value::as_str) == batch.first().map(|id| id.0.as_str())
13469 && node.pointer("/subIssues/pageInfo/hasNextPage") == Some(&Value::Bool(false))
13470 {
13471 // A list GitHub did not answer is not an empty one: it would answer the project's
13472 // task listing with nothing, and the orphan check with no orphans.
13473 let listed = node
13474 .pointer("/subIssues/nodes")
13475 .and_then(Value::as_array)
13476 .ok_or_else(|| SourceError::Malformed {
13477 message: format!(
13478 "GitHub answered the sub-issues of project {} with no list of them",
13479 batch[0].0
13480 ),
13481 })?
13482 .iter()
13483 .map(|child| {
13484 Ok((
13485 required_str(child, "id")?.to_owned(),
13486 required_str(child, "title")?.to_owned(),
13487 ))
13488 })
13489 .collect::<Result<Vec<_>, SourceError>>()?;
13490 children = Some((batch[0].clone(), listed));
13491 }
13492 }
13493 // The project's tasks are known from this read alone when every child it named is held
13494 // from it, but for a document, which its title says is one and which a task listing
13495 // never answers: then a listing of the project's tasks is answered from them.
13496 if let Some((project, listed)) = children
13497 && read.iter().any(|(id, held)| {
13498 *id == project
13499 && held
13500 .as_ref()
13501 .is_some_and(|held| held.kind == BoardKind::Work(ItemKind::Project))
13502 })
13503 {
13504 let mut tasks = Vec::new();
13505 let mut whole = true;
13506 for (child, title) in &listed {
13507 match read.iter().find(|(id, _)| id.0 == *child) {
13508 Some((_, Some(held))) if held.parent.as_ref() == Some(&project) => {
13509 if held.kind == BoardKind::Work(ItemKind::Task) {
13510 tasks.push(held.clone());
13511 }
13512 }
13513 _ if title.starts_with(DESIGN_TITLE_PREFIX) => {}
13514 _ => whole = false,
13515 }
13516 }
13517 if whole {
13518 self.task_children()?.insert(project, tasks);
13519 }
13520 }
13521 let mut resolved = self.resolved_cache()?;
13522 let mut ahead = self.read_ahead()?;
13523 let mut carried = self.carried()?;
13524 for item in read.iter().filter_map(|(_, held)| held.as_ref()) {
13525 resolved.insert(item.id.clone(), item.clone());
13526 }
13527 // Taken only if still carried: a mutation naming it while the batches ran dropped it,
13528 // and its next read is then its own.
13529 for id in &listed {
13530 let Some(item) = carried.remove(id) else {
13531 continue;
13532 };
13533 // The whole of what it is blocked by came with it, so the dependency read a copy
13534 // makes next is answered from this one, as a copy's detail read is.
13535 if item.blocked_by.is_some() {
13536 resolved.insert(item.id.clone(), item.clone());
13537 }
13538 read.push((id.clone(), Some(item)));
13539 }
13540 for (id, held) in read {
13541 ahead.insert(id, held);
13542 }
13543 Ok(())
13544 }
13545
13546 /// Add one comment to the task's issue, as the account the token belongs to.
13547 ///
13548 /// The author is refused before anything is sent — not even the task is read — because
13549 /// no answer GitHub could give would make posting under another name than the one asked
13550 /// for the right outcome.
13551 async fn add_comment(
13552 &self,
13553 task: &NativeId,
13554 comment: &NewComment,
13555 ) -> Result<Option<Comment>, SourceError> {
13556 if let Some(author) = &comment.author {
13557 return Err(SourceError::Refused {
13558 message: format!(
13559 "source {} cannot post a comment as {author:?}: GitHub records the account \
13560 the token signs in as the author of every comment; next: leave --author \
13561 out, and the comment is posted as that account",
13562 self.name
13563 ),
13564 });
13565 }
13566 let Some(issue) = self.commented_issue(task).await? else {
13567 return Ok(None);
13568 };
13569 let data = self
13570 .graphql(
13571 graphql::ADD_COMMENT,
13572 json!({"input":{"subjectId":issue.0,"body":comment.body.as_str()}}),
13573 )
13574 .await?;
13575 let subject = data
13576 .pointer("/addComment/subject")
13577 .filter(|value| !value.is_null())
13578 .ok_or_else(|| SourceError::Malformed {
13579 message: "GitHub comment addition returned no subject".into(),
13580 })?;
13581 if required_str(subject, "id")? != issue.0 {
13582 return Err(SourceError::Malformed {
13583 message: "GitHub comment addition answered about another issue".into(),
13584 });
13585 }
13586 let added = data
13587 .pointer("/addComment/commentEdge/node")
13588 .filter(|value| !value.is_null())
13589 .ok_or_else(|| SourceError::Malformed {
13590 message: "GitHub comment addition returned no comment".into(),
13591 })?;
13592 let added = comment_from(added)?;
13593 self.remember_commented(&issue)?;
13594 Ok(Some(added))
13595 }
13596
13597 async fn edit_comment(
13598 &self,
13599 task: &NativeId,
13600 comment: &NativeId,
13601 body: &CommentBody,
13602 ) -> Result<Option<Comment>, SourceError> {
13603 let Some(issue) = self.commented_issue(task).await? else {
13604 return Ok(None);
13605 };
13606 let Some(held) = self.comment_on(&issue, comment).await? else {
13607 return Ok(None);
13608 };
13609 // A comment a copy wrote keeps its origin through an edit: its marker is carried over.
13610 let body = CommentOrigin::kept(&held, body)?;
13611 let data = self
13612 .graphql(
13613 graphql::UPDATE_COMMENT,
13614 json!({"input":{"id":comment.0,"body":body.as_str()}}),
13615 )
13616 .await?;
13617 let edited = data
13618 .pointer("/updateIssueComment/issueComment")
13619 .filter(|value| !value.is_null())
13620 .ok_or_else(|| SourceError::Malformed {
13621 message: "GitHub comment update returned no comment".into(),
13622 })?;
13623 let edited = comment_from(edited)?;
13624 if edited.id != *comment {
13625 return Err(SourceError::Malformed {
13626 message: "GitHub comment update returned the wrong comment".into(),
13627 });
13628 }
13629 self.remember_commented(&issue)?;
13630 Ok(Some(edited))
13631 }
13632
13633 async fn delete_comment(
13634 &self,
13635 task: &NativeId,
13636 comment: &NativeId,
13637 ) -> Result<Option<NativeId>, SourceError> {
13638 let Some(issue) = self.commented_issue(task).await? else {
13639 return Ok(None);
13640 };
13641 if !self.comment_is_on(&issue, comment).await? {
13642 return Ok(None);
13643 }
13644 let data = self
13645 .graphql(graphql::DELETE_COMMENT, json!({"input":{"id":comment.0}}))
13646 .await?;
13647 // The payload says nothing about the comment it removed, so what is checked is that
13648 // GitHub answered the mutation at all rather than leaving it unanswered.
13649 data.get("deleteIssueComment")
13650 .filter(|value| !value.is_null())
13651 .ok_or_else(|| SourceError::Malformed {
13652 message: "GitHub comment deletion returned no payload".into(),
13653 })?;
13654 Ok(Some(comment.clone()))
13655 }
13656
13657 /// Every request this source has recorded, and what each of GitHub's two budgets was
13658 /// attributed — read off the same accounting the session report is rendered from, so
13659 /// the two cannot count one request two ways.
13660 async fn metering(&self) -> Result<Option<Metering>, SourceError> {
13661 Ok(Some(self.ledger.snapshot().metering()))
13662 }
13663
13664 /// Drop every item, search answer and board read this source holds, so the next command
13665 /// reads the board as a person has since left it.
13666 ///
13667 /// Every one of those is held on the assumption that nothing but this source writes the
13668 /// board while a command runs, which stops being true the moment the command is over: a
13669 /// body a person edited would be overwritten from the record held here, and a card they
13670 /// moved would be read as still where this source left it. The board's own field
13671 /// definitions go too, because a person can add or delete a `Status` option and a write
13672 /// resolved against the held list would not re-read on a miss. What stays is what stays
13673 /// valid in normal use: each repository's node id, which a miss re-reads, the pacing of
13674 /// mutations, which is about GitHub's limiter rather than anybody's work, and the running
13675 /// accounting [`metering`](TaskSource::metering) answers from.
13676 ///
13677 /// Infallible in practice: a lock an earlier failure poisoned is cleared rather than
13678 /// refused, because clearing it is what puts it right.
13679 async fn end_command(&self) -> Result<(), SourceError> {
13680 fn clear<T: Default>(held: &Mutex<T>) {
13681 *held
13682 .lock()
13683 .unwrap_or_else(std::sync::PoisonError::into_inner) = T::default();
13684 held.clear_poison();
13685 }
13686 clear(&self.created);
13687 clear(&self.updated);
13688 clear(&self.commented);
13689 clear(&self.board_cache);
13690 clear(&self.search_cache);
13691 clear(&self.narrowed_cache);
13692 clear(&self.search_next);
13693 clear(&self.resolved_cache);
13694 clear(&self.read_ahead);
13695 clear(&self.carried);
13696 clear(&self.held_cache);
13697 clear(&self.children_cache);
13698 clear(&self.task_children);
13699 clear(&self.written);
13700 clear(&self.fields_cache);
13701 self.expected.end_command();
13702 Ok(())
13703 }
13704}
13705
13706/// Each project's sub-issues as one command read them, keyed by the selector they were asked
13707/// for under, beside the project that selector named; see `children_cache`.
13708type ProjectChildren = BTreeMap<NativeId, (NativeId, Vec<Resolved>)>;
13709
13710/// One issue comment as the contract carries it.
13711///
13712/// `author` is absent both when GitHub answers `null` for an account that no longer exists
13713/// and when it answers an actor with no login, because either way the source did not say who
13714/// wrote it — which is what an absent author means, rather than an author called nothing.
13715///
13716/// A comment a copy wrote here carries its origin as the hidden marker at the end of its body
13717/// — GitHub sets every comment's author and times itself, so there is nowhere else to keep it —
13718/// and is read back with the marker taken out and reported as its origin.
13719fn comment_from(value: &Value) -> Result<Comment, SourceError> {
13720 Ok(Comment {
13721 origin: None,
13722 id: NativeId(required_str(value, "id")?.to_owned()),
13723 author: optional_str(value.get("author").unwrap_or(&Value::Null), "login")?
13724 .map(str::to_owned),
13725 created_at: optional_time(value, "createdAt")?,
13726 updated_at: optional_time(value, "updatedAt")?,
13727 body: required_str(value, "body")?.to_owned(),
13728 url: optional_str(value, "url")?.map(str::to_owned),
13729 }
13730 .unmarked())
13731}
13732
13733/// The page of comments one issue node carries, resumed from `after`.
13734fn comment_page(
13735 node: &Value,
13736 issue: &str,
13737 after: Option<&str>,
13738) -> Result<Page<Comment>, SourceError> {
13739 let connection = node
13740 .get("comments")
13741 .filter(|value| !value.is_null())
13742 .ok_or_else(|| SourceError::Malformed {
13743 message: format!("GitHub issue {issue} answered with no comments connection"),
13744 })?;
13745 let items = optional_nodes(Some(connection), "issue comments")?
13746 .into_iter()
13747 .flatten()
13748 .map(comment_from)
13749 .collect::<Result<Vec<_>, _>>()?;
13750 let next = next_cursor(connection)?;
13751 if let Some(next) = &next {
13752 validate_cursor_progress(after, &next.0)?;
13753 }
13754 Ok(Page { items, next })
13755}
13756
13757/// The far ends of an issue's whole `blockedBy` connection, when the read carried it to its
13758/// end — `None` when it carried none, or a page with more past it.
13759fn carried_blocked_by(content: &Value) -> Result<Option<Vec<Value>>, SourceError> {
13760 let Some(connection) = content.get("blockedBy").filter(|value| !value.is_null()) else {
13761 return Ok(None);
13762 };
13763 if next_cursor(connection)?.is_some() {
13764 return Ok(None);
13765 }
13766 Ok(Some(
13767 optional_nodes(Some(connection), "blocked-by issues")?
13768 .into_iter()
13769 .flatten()
13770 .cloned()
13771 .collect(),
13772 ))
13773}
13774
13775/// Where the recorded tail of a dependency walk resumes; see
13776/// [`GitHubProjectsSource::recorded_edges`].
13777const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";
13778
13779/// The board text field this source keeps a copy's origin in.
13780///
13781/// Named after the key it holds, and held to that name by the guard below rather than by
13782/// a reader noticing.
13783const ORIGIN_FIELD: &str = "onetaskgraph.origin";
13784
13785/// The metadata key that field holds.
13786///
13787/// The engine owns this key and spells it once as `GlobalId::ORIGIN_KEY`; a plugin never
13788/// constructs or interprets the qualified id it carries. This source names it only to
13789/// route it — a short, typed value belongs in a typed field rather than in the body slot
13790/// a caller's own prose shares.
13791///
13792/// Restated rather than imported, because no plugin crate may depend on the engine. What
13793/// keeps the two spellings one contract is `scripts/check-origin-key-spelling.sh`, a
13794/// target in `check`: it reads the engine's own literal and fails naming the file and the
13795/// line when a plugin's parts from it either way. Drift here has one symptom — a copy
13796/// that creates a second item every run instead of finding the one it wrote — and that is
13797/// too late to learn it.
13798const ORIGIN_KEY: &str = "onetaskgraph.origin";
13799
13800/// Where a recorded tail resumes, refusing a cursor no walk in `direction` reported.
13801///
13802/// The reserved key holds forward edges and nothing else — the reverse of a recorded edge
13803/// is derived from the far end, never written down on the near item — so only a forward
13804/// walk ever reports one of these cursors. A reverse read carrying one is resuming a walk
13805/// it did not come from, and it is told so rather than answered with an empty page that
13806/// reads as a walk which ended.
13807fn recorded_offset(
13808 cursor: Option<&str>,
13809 direction: Direction,
13810) -> Result<Option<usize>, SourceError> {
13811 cursor
13812 .and_then(|cursor| cursor.strip_prefix(RECORDED_CURSOR))
13813 .map(|offset| {
13814 if direction != Direction::DependsOn {
13815 return Err(SourceError::Config {
13816 message: format!(
13817 "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a \
13818 reverse dependency read never issues; resume it in the direction \
13819 that reported it"
13820 ),
13821 });
13822 }
13823 offset.parse().map_err(|_| SourceError::Config {
13824 message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
13825 })
13826 })
13827 .transpose()
13828}
13829
13830/// What a dependency read's own answer says of a board draft: `None` when the item is not a
13831/// draft, or the answer did not carry its board item; `Some(None)` for a draft whose one board
13832/// item is not on this board, which this source does not hold; and `Some(Some(slot))`, the
13833/// draft's metadata, for one it does — its board item naming this board by its number and by
13834/// the id the same answer read of the board, as [`GitHubProjectsSource::draft_by_id`] decides.
13835fn draft_slot(
13836 data: &Value,
13837 id: &NativeId,
13838 project_number: u32,
13839) -> Result<Option<Option<BTreeMap<String, Value>>>, SourceError> {
13840 let Some(draft) = data
13841 .get("node")
13842 .filter(|node| node.get("__typename").and_then(Value::as_str) == Some("DraftIssue"))
13843 else {
13844 return Ok(None);
13845 };
13846 let Some(items) = data.pointer("/draft/projectV2Items") else {
13847 return Ok(None);
13848 };
13849 if required_str(draft, "id")? != id.0 {
13850 return Err(SourceError::Malformed {
13851 message: format!("GitHub answered a different draft for {}", id.0),
13852 });
13853 }
13854 let nodes = items
13855 .get("nodes")
13856 .and_then(Value::as_array)
13857 .ok_or_else(|| SourceError::Malformed {
13858 message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
13859 })?;
13860 let info = items
13861 .get("pageInfo")
13862 .ok_or_else(|| SourceError::Malformed {
13863 message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
13864 })?;
13865 if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
13866 return Err(SourceError::Malformed {
13867 message: format!(
13868 "GitHub draft {} reports more board items than the one GitHub links a draft to",
13869 id.0
13870 ),
13871 });
13872 }
13873 let board = data
13874 .pointer("/board/projectV2/id")
13875 .and_then(Value::as_str)
13876 .ok_or_else(|| SourceError::Malformed {
13877 message: format!(
13878 "GitHub answered draft {} without this board's own id beside it",
13879 id.0
13880 ),
13881 })?;
13882 let mut held = false;
13883 for node in nodes {
13884 let project = node.get("project").ok_or_else(|| SourceError::Malformed {
13885 message: format!("GitHub draft {} board item has no project", id.0),
13886 })?;
13887 let number = project
13888 .get("number")
13889 .and_then(Value::as_u64)
13890 .ok_or_else(|| SourceError::Malformed {
13891 message: format!(
13892 "GitHub draft {} board item has no numeric project number",
13893 id.0
13894 ),
13895 })?;
13896 let project_id = required_str(project, "id")?;
13897 held |= number == u64::from(project_number) && project_id == board;
13898 }
13899 if !held {
13900 return Ok(Some(None));
13901 }
13902 Ok(Some(Some(
13903 metadata_body(optional_str(draft, "body")?.map(str::to_owned))?.1,
13904 )))
13905}
13906
13907fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
13908 let mut page = offset_page(edges, offset, limit.max(1));
13909 page.next = page
13910 .next
13911 .map(|cursor| Cursor(format!("{RECORDED_CURSOR}{}", cursor.0)));
13912 page
13913}
13914
13915/// The kind of one issue reached through a dependency connection.
13916///
13917/// The same questions the board scan asks, over the fields the dependency document
13918/// selects, and in the same order: the design prefix first, then a sub-issue is a task,
13919/// then anything with sub-issues or the marker is a project.
13920///
13921/// # Errors
13922///
13923/// A far end this board holds as a document is refused rather than reported. The two
13924/// answers that are not refusals would both be wrong: reporting it as a task names an id
13925/// no task read of this source can find, and reporting it as a project names one no
13926/// project read can. There is no third value to return — `ItemKind` has no document
13927/// variant, because nothing may point at a document — so the relationship itself is what
13928/// the person is told about.
13929fn related_kind(value: &Value) -> Result<ItemKind, SourceError> {
13930 let id = required_str(value, "id")?;
13931 if required_str(value, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
13932 return Err(SourceError::Refused {
13933 message: format!(
13934 "GitHub issue {id} is a document of this board — its title begins \
13935 {DESIGN_TITLE_PREFIX:?} — and nothing may depend on a document or be depended \
13936 on by one; next: remove that issue's blocking relationship on this board"
13937 ),
13938 });
13939 }
13940 let parent = optional_str(value.get("parent").unwrap_or(&Value::Null), "id")?;
13941 if parent.is_some() {
13942 return Ok(ItemKind::Task);
13943 }
13944 let (_, slot) = metadata_body(optional_str(value, "body")?.map(str::to_owned))?;
13945 let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
13946 message: format!("GitHub issue {id}: {message}"),
13947 })?;
13948 let sub_issues = sub_issue_total(value)?;
13949 Ok(if sub_issues > 0 || marked == Some(ItemKind::Project) {
13950 ItemKind::Project
13951 } else {
13952 ItemKind::Task
13953 })
13954}
13955
13956/// The `stateInput` that closes an issue for `reason`.
13957fn closed_input(reason: ClosedState) -> Value {
13958 json!({"value":"CLOSED","stateReason":reason.reason()})
13959}
13960
13961/// The `IssueStateUpdateInput` one status target asks for.
13962///
13963/// `stateInput` and `state` are mutually exclusive on `UpdateIssueInput`, and only this
13964/// one is ever sent. A non-terminal status always asks for `OPEN`, which is what reopens
13965/// a currently-closed issue: without that the item would read back `Unknown` and a copy
13966/// would report a change forever. A document has no status at all, and asks for neither.
13967fn state_input(target: Option<&StatusTarget>) -> Value {
13968 match target {
13969 Some(StatusTarget::Terminal(_, reason)) => closed_input(*reason),
13970 Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => json!({"value":"OPEN"}),
13971 // A document has no status, so a write of one says nothing about the issue's open
13972 // or closed state rather than forcing it open: `stateInput` is what carries that
13973 // instruction, and an explicit null asks for no change to it.
13974 None => Value::Null,
13975 }
13976}
13977
13978/// The metadata one write stores in the item's body slot.
13979///
13980/// The typed fields travel as themselves, so the three reserved keys are rebuilt here
13981/// rather than carried: the kind marker so an empty project stays readable, the
13982/// repository list only when it is not exactly the issue's own repository, and the far
13983/// ends no relationship here can name.
13984///
13985/// The copy origin is the one typed field that is also mirrored here, and only as a
13986/// mirror: it lands in the board's origin field as well, which stays the one every reader
13987/// takes it from, and it is here so that GitHub's issue search — which indexes this comment
13988/// and catches up with a write in seconds rather than minutes — can find the item by it.
13989/// A reader of the release before this one drops the slot's copy and reads the field, so an
13990/// item written here still reads with exactly one origin there.
13991fn slot_metadata(
13992 incoming: &Incoming<'_>,
13993 own_repository: Option<&Repository>,
13994 fallback: &[DependencyEdge],
13995) -> BTreeMap<String, Value> {
13996 let mut metadata = incoming.metadata.clone();
13997 match metadata.remove(ORIGIN_KEY) {
13998 Some(Value::String(origin)) if !origin.is_empty() => {
13999 metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin));
14000 }
14001 _ => {}
14002 }
14003 match incoming.written.kind() {
14004 BoardKind::Work(kind) => metadata.insert(
14005 ItemKind::METADATA_KEY.to_owned(),
14006 Value::String(kind.marker().to_owned()),
14007 ),
14008 // A document is told by its title, so it carries no kind marker: that key names
14009 // what a dependency endpoint points at, and nothing may point at a document.
14010 BoardKind::Document => metadata.remove(ItemKind::METADATA_KEY),
14011 };
14012 incoming.classification.record(&mut metadata);
14013 let derivable = own_repository
14014 .map(|own| incoming.repositories == [own.clone()])
14015 .unwrap_or(incoming.repositories.is_empty());
14016 if derivable {
14017 metadata.remove(Repository::METADATA_KEY);
14018 } else {
14019 metadata.insert(
14020 Repository::METADATA_KEY.to_owned(),
14021 Value::Array(
14022 incoming
14023 .repositories
14024 .iter()
14025 .map(|repository| Value::String(repository.as_str().to_owned()))
14026 .collect(),
14027 ),
14028 );
14029 }
14030 // The typed lists are what land, whatever the caller's own metadata held under their
14031 // keys: a key of either name travelling beside the field would otherwise be a second
14032 // answer to the same question, and the field is the one the contract names.
14033 for (key, entries) in [
14034 (TaskRef::DELIVERS_KEY, incoming.delivers),
14035 (TaskRef::DELIVERED_BY_KEY, incoming.delivered_by),
14036 ] {
14037 set_task_list(&mut metadata, key, entries);
14038 }
14039 record_edges(&mut metadata, fallback);
14040 metadata
14041}
14042
14043/// Hold the far ends no relationship here can name under [`DependencyEdge::RECORDED_KEY`] in
14044/// one slot's metadata, or no such key when there are none.
14045fn record_edges(metadata: &mut BTreeMap<String, Value>, fallback: &[DependencyEdge]) {
14046 if fallback.is_empty() {
14047 metadata.remove(DependencyEdge::RECORDED_KEY);
14048 } else {
14049 metadata.insert(
14050 DependencyEdge::RECORDED_KEY.to_owned(),
14051 Value::Array(
14052 fallback
14053 .iter()
14054 .map(|edge| {
14055 serde_json::to_value(&edge.to).expect("an endpoint renders as JSON")
14056 })
14057 .collect(),
14058 ),
14059 );
14060 }
14061}
14062
14063/// Every label one item carries, from its content's own connection and nowhere else.
14064///
14065/// There is no second place to read one from: no document this source sends selects the
14066/// board's built-in `Labels` field, because GitHub derives it from the content and a draft
14067/// cannot carry one at all. The module documentation records the three schema facts that
14068/// settle it.
14069fn labels(content: &Value) -> Result<Vec<Label>, SourceError> {
14070 optional_nodes(content.get("labels"), "content labels")?
14071 .into_iter()
14072 .flatten()
14073 .map(|v| {
14074 Ok(Label {
14075 id: NativeId(required_str(v, "id")?.to_owned()),
14076 name: required_str(v, "name")?.to_owned(),
14077 color: optional_str(v, "color")?.map(str::to_owned),
14078 })
14079 })
14080 .collect()
14081}
14082
14083/// Each board field value one item holds, as the change token's facets name it: the field's
14084/// name, with the single-select option's name or the text. A value of a type no read here
14085/// selects, and one naming no field, says nothing a person can rename and is left out.
14086fn facet_fields(field_values: &[Value]) -> Vec<(String, String)> {
14087 field_values
14088 .iter()
14089 .filter_map(|value| {
14090 let field = value.pointer("/field/name")?.as_str()?;
14091 let held = value.get("name").or_else(|| value.get("text"))?.as_str()?;
14092 Some((field.to_owned(), held.to_owned()))
14093 })
14094 .collect()
14095}
14096
14097/// The digest of the facets of the issue `content`, whose board item's values are
14098/// `field_values` — or `None` when the response did not carry, whole, every member they are read
14099/// from: the title, the parent, the sub-issue summary and the body its kind is read from, every
14100/// label, and every field value.
14101///
14102/// What a write's own response spells its token from, by exactly the rules a read takes them by.
14103fn facets_of(content: &Value, field_values: &Value) -> Option<change_token::FacetsDigest> {
14104 let ended = |connection: &Value| {
14105 connection.pointer("/pageInfo/hasNextPage") == Some(&Value::Bool(false))
14106 };
14107 let labels = content.get("labels").filter(|labels| ended(labels))?;
14108 if !ended(field_values) {
14109 return None;
14110 }
14111 let parent = content.get("parent")?;
14112 let (_, slot) = metadata_body(content.get("body")?.as_str().map(str::to_owned)).ok()?;
14113 let kind = BoardKind::of(
14114 content.get("title")?.as_str()?,
14115 !parent.is_null(),
14116 sub_issue_total(content).ok()?,
14117 ItemKind::from_metadata(&slot).ok()?,
14118 );
14119 let labels = self::labels(&json!({"labels": labels})).ok()?;
14120 let nodes = field_values.get("nodes")?.as_array()?;
14121 Some(change_token::Facets::new(kind.facet(), facet_fields(nodes), &labels).digest())
14122}
14123
14124/// The definition of each board field one item's values are values of, in the shape a read
14125/// of the board's own `fields` gives one.
14126///
14127/// A value names its field through a fragment on that field's own type, so the type is
14128/// known from which kind of value it is: a single-select value's field is a
14129/// `ProjectV2SingleSelectField`, options and all, and a text value's is a `ProjectV2Field`.
14130/// A value whose field carried no id, or an empty one, says nothing usable and is left out.
14131fn field_definitions(field_values: &[Value]) -> Vec<Value> {
14132 field_values
14133 .iter()
14134 .filter_map(|value| {
14135 let field = value.get("field")?.as_object()?;
14136 field.get("id")?.as_str().filter(|id| !id.is_empty())?;
14137 let typename = if value.get("text").is_some() {
14138 "ProjectV2Field"
14139 } else if value.get("name").is_some() {
14140 "ProjectV2SingleSelectField"
14141 } else {
14142 return None;
14143 };
14144 let mut defined = field.clone();
14145 defined.insert("__typename".to_owned(), json!(typename));
14146 // Only a text field holds a text value, so the value says the field's type too.
14147 if typename == "ProjectV2Field" {
14148 defined.insert("dataType".to_owned(), json!("TEXT"));
14149 }
14150 Some(Value::Object(defined))
14151 })
14152 .collect()
14153}
14154
14155fn text_field(field_values: &[Value], name: &str) -> Result<Option<String>, SourceError> {
14156 let Some(node) = field_values
14157 .iter()
14158 .find(|node| node.pointer("/field/name").and_then(Value::as_str) == Some(name))
14159 else {
14160 return Ok(None);
14161 };
14162 Ok(optional_str(node, "text")?.map(str::to_owned))
14163}
14164
14165fn valid_github_owner(owner: &str) -> bool {
14166 !owner.is_empty()
14167 && owner.len() <= 39
14168 && !owner.starts_with('-')
14169 && !owner.ends_with('-')
14170 && !owner.contains("--")
14171 && owner
14172 .bytes()
14173 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
14174}
14175
14176/// GitHub's repository-name grammar: 1-100 ASCII letters, digits, `-`, `_` or `.`, and
14177/// neither of the two names a path segment already means.
14178fn valid_github_repository_name(name: &str) -> bool {
14179 !name.is_empty()
14180 && name.len() <= 100
14181 && name != "."
14182 && name != ".."
14183 && name
14184 .bytes()
14185 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
14186}
14187
14188fn valid_environment_name(name: &str) -> bool {
14189 let mut bytes = name.bytes();
14190 bytes
14191 .next()
14192 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
14193 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
14194}
14195
14196/// How many sub-issues one issue has.
14197///
14198/// `Issue.subIssuesSummary` is `SubIssuesSummary!` and its `total` is `Int!`, so an
14199/// absent or non-integer one is a response this source cannot read — and reading it as
14200/// zero would classify a project as a task, which is exactly the mistake the marker
14201/// exists to keep from happening quietly.
14202fn sub_issue_total(issue: &Value) -> Result<u64, SourceError> {
14203 let summary = issue
14204 .get("subIssuesSummary")
14205 .ok_or_else(|| SourceError::Malformed {
14206 message: "GitHub issue is missing subIssuesSummary".into(),
14207 })?;
14208 summary
14209 .get("total")
14210 .and_then(Value::as_u64)
14211 .ok_or_else(|| SourceError::Malformed {
14212 message: "GitHub issue subIssuesSummary.total is not an unsigned integer".into(),
14213 })
14214}
14215
14216/// One issue's own `number`.
14217///
14218/// An issue always has one: GitHub declares `Issue.number` as `Int!` and every selection of
14219/// an issue in this module asks for it. So a read of one that comes back without it, or
14220/// with something that is not an unsigned integer, is a response this source cannot read —
14221/// absence here is **not** "this issue has no number". A draft is the content that has
14222/// none, and a draft never reaches this: the caller decides on `__typename` first, the way
14223/// it does for `subIssuesSummary`, which `DraftIssue` equally declares nothing for.
14224fn issue_number(issue: &Value) -> Result<u64, SourceError> {
14225 issue
14226 .get("number")
14227 .and_then(Value::as_u64)
14228 .ok_or_else(|| SourceError::Malformed {
14229 message: "GitHub issue number is missing or is not an unsigned integer".into(),
14230 })
14231}
14232
14233/// The `number` a creating mutation answered with, and `None` when it answered without one;
14234/// why a missing one is tolerated is at the call in `create_and_file_issue`.
14235fn created_issue_number(created: &Value) -> Result<Option<u64>, SourceError> {
14236 match created.get("number") {
14237 None | Some(Value::Null) => Ok(None),
14238 Some(value) => value
14239 .as_u64()
14240 .map(Some)
14241 .ok_or_else(|| SourceError::Malformed {
14242 message: "GitHub created issue number is not an unsigned integer".into(),
14243 }),
14244 }
14245}
14246
14247fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
14248 value
14249 .get(field)
14250 .and_then(Value::as_str)
14251 .ok_or_else(|| SourceError::Malformed {
14252 message: format!("GitHub response is missing string field {field}"),
14253 })
14254}
14255
14256fn required_nonblank_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
14257 let found = required_str(value, field)?;
14258 if found.trim().is_empty() {
14259 return Err(SourceError::Malformed {
14260 message: format!("GitHub response has blank string field {field}"),
14261 });
14262 }
14263 Ok(found)
14264}
14265
14266/// The slot's delimiters, which `docs/metadata.md` settles once for every source that
14267/// needs one — Linear spells them too, in its own description field.
14268///
14269/// Restated rather than shared, because a plugin crate depends on the contract crate and
14270/// nothing else of this workspace. `scripts/check-metadata-slot-encoding.sh`, a target in
14271/// `check`, is what keeps the two one encoding: drift is otherwise quiet, since each
14272/// source round-trips its own writes perfectly well under its own spelling.
14273const METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
14274const METADATA_CLOSE: &str = "\n-->";
14275
14276/// What the composer puts between a non-empty visible body and the slot, and the one thing
14277/// the parser takes off the visible body when it takes the slot off — exactly once, so every
14278/// other trailing byte of the body comes back as it was written.
14279// 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.
14280const METADATA_SEPARATOR: &str = "\n\n";
14281
14282/// The visible body and the metadata slot at the end of it.
14283///
14284/// The encoding is the one `docs/metadata.md` settles for Linear, which is where its
14285/// reasons are. Only a comment at the very end is a slot; one in the middle is a person's
14286/// own content and is left alone. The visible body is everything before the slot less the
14287/// one [`METADATA_SEPARATOR`] the composer put there, byte for byte.
14288fn metadata_body(
14289 body: Option<String>,
14290) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
14291 let Some(body) = body else {
14292 return Ok((None, BTreeMap::new()));
14293 };
14294 let Some(slot) = slot_span(&body)? else {
14295 return Ok((Some(body), BTreeMap::new()));
14296 };
14297 let metadata =
14298 serde_json::from_str(&body[slot.encoded_start..slot.encoded_end]).map_err(|error| {
14299 SourceError::Malformed {
14300 message: format!(
14301 "invalid canonical JSON in GitHub issue onetaskgraph metadata slot: {error}"
14302 ),
14303 }
14304 })?;
14305 let before = &body[..slot.start];
14306 let visible = before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before);
14307 Ok(((!visible.is_empty()).then(|| visible.to_owned()), metadata))
14308}
14309
14310/// Where the metadata slot sits in one body, as byte offsets into it.
14311struct SlotSpan {
14312 /// Where [`METADATA_OPEN`] begins.
14313 start: usize,
14314 /// Where the encoded JSON begins, just past [`METADATA_OPEN`].
14315 encoded_start: usize,
14316 /// Where the encoded JSON ends, at the start of [`METADATA_CLOSE`].
14317 encoded_end: usize,
14318 /// Just past [`METADATA_CLOSE`].
14319 end: usize,
14320}
14321
14322/// The slot at the very end of `body`, or `None` when it has none.
14323///
14324/// The one reading of *where the slot is*, shared by [`metadata_body`], which reads it, and
14325/// [`with_slot`], which rewrites it — so the two cannot disagree about which comment is the
14326/// slot.
14327fn slot_span(body: &str) -> Result<Option<SlotSpan>, SourceError> {
14328 let Some(start) = body.rfind(METADATA_OPEN) else {
14329 return Ok(None);
14330 };
14331 let encoded_start = start + METADATA_OPEN.len();
14332 let Some(relative_end) = body[encoded_start..].find(METADATA_CLOSE) else {
14333 return Err(SourceError::Malformed {
14334 message: "unterminated onetaskgraph metadata slot in GitHub issue body".into(),
14335 });
14336 };
14337 let encoded_end = encoded_start + relative_end;
14338 let end = encoded_end + METADATA_CLOSE.len();
14339 if !body[end..].trim().is_empty() {
14340 return Ok(None);
14341 }
14342 Ok(Some(SlotSpan {
14343 start,
14344 encoded_start,
14345 encoded_end,
14346 end,
14347 }))
14348}
14349
14350/// `body` with its metadata slot holding exactly `metadata`, and every byte outside the
14351/// slot as it was.
14352///
14353/// A slot that is there has its JSON replaced in place; one that becomes empty is removed
14354/// together with the one [`METADATA_SEPARATOR`] separating it from the prose before it. A
14355/// body with no slot gains one the way [`compose_body`] writes it — after that separator,
14356/// or alone in an empty body — and a body with no slot that is given no metadata is
14357/// returned as it is.
14358fn with_slot(body: &str, metadata: &BTreeMap<String, Value>) -> Result<String, SourceError> {
14359 let encoded = if metadata.is_empty() {
14360 None
14361 } else {
14362 Some(
14363 serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
14364 message: error.to_string(),
14365 })?,
14366 )
14367 };
14368 Ok(match (slot_span(body)?, encoded) {
14369 (Some(slot), Some(encoded)) => format!(
14370 "{}{encoded}{}",
14371 &body[..slot.encoded_start],
14372 &body[slot.encoded_end..]
14373 ),
14374 (Some(slot), None) => {
14375 let before = &body[..slot.start];
14376 format!(
14377 "{}{}",
14378 before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before),
14379 &body[slot.end..]
14380 )
14381 }
14382 (None, None) => body.to_owned(),
14383 (None, Some(encoded)) if body.is_empty() => {
14384 format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
14385 }
14386 (None, Some(encoded)) => {
14387 format!("{body}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
14388 }
14389 })
14390}
14391
14392/// `body` with everything before its metadata slot replaced by `content`, and the slot
14393/// itself kept byte for byte.
14394///
14395/// The inverse of how [`metadata_body`] splits a body: the slot, when there is one, follows
14396/// `content` after the one [`METADATA_SEPARATOR`] the composer puts there — or alone, when
14397/// `content` is empty — so a read of the result reports `content` as the visible body and
14398/// the slot's metadata exactly as it was.
14399fn with_content(body: &str, content: &str) -> Result<String, SourceError> {
14400 let Some(slot) = slot_span(body)? else {
14401 return Ok(content.to_owned());
14402 };
14403 let kept = &body[slot.start..];
14404 Ok(if content.is_empty() {
14405 kept.to_owned()
14406 } else {
14407 format!("{content}{METADATA_SEPARATOR}{kept}")
14408 })
14409}
14410
14411/// Hold `entries` under `key` in one slot's metadata, or no such key when there are none.
14412fn set_task_list(metadata: &mut BTreeMap<String, Value>, key: &str, entries: &[TaskRef]) {
14413 if entries.is_empty() {
14414 metadata.remove(key);
14415 } else {
14416 metadata.insert(
14417 key.to_owned(),
14418 Value::Array(
14419 entries
14420 .iter()
14421 .map(|entry| Value::String(entry.as_str().to_owned()))
14422 .collect(),
14423 ),
14424 );
14425 }
14426}
14427
14428fn compose_body(
14429 content: Option<&str>,
14430 metadata: &BTreeMap<String, Value>,
14431) -> Result<Option<String>, SourceError> {
14432 let visible = content.unwrap_or_default();
14433 if metadata.is_empty() {
14434 return Ok((!visible.is_empty()).then(|| visible.to_owned()));
14435 }
14436 let encoded = serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
14437 message: error.to_string(),
14438 })?;
14439 Ok(Some(if visible.is_empty() {
14440 format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
14441 } else {
14442 format!("{visible}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
14443 }))
14444}
14445
14446fn required_bool(value: &Value, field: &str) -> Result<bool, SourceError> {
14447 value
14448 .get(field)
14449 .and_then(Value::as_bool)
14450 .ok_or_else(|| SourceError::Malformed {
14451 message: format!("GitHub response is missing boolean field {field}"),
14452 })
14453}
14454fn optional_str<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, SourceError> {
14455 match value.get(field) {
14456 None | Some(Value::Null) => Ok(None),
14457 Some(value) => value
14458 .as_str()
14459 .map(Some)
14460 .ok_or_else(|| SourceError::Malformed {
14461 message: format!("GitHub response field {field} is not a string or null"),
14462 }),
14463 }
14464}
14465fn optional_nodes<'a>(
14466 connection: Option<&'a Value>,
14467 name: &str,
14468) -> Result<Option<&'a Vec<Value>>, SourceError> {
14469 match connection {
14470 None | Some(Value::Null) => Ok(None),
14471 Some(value) => value
14472 .get("nodes")
14473 .and_then(Value::as_array)
14474 .map(Some)
14475 .ok_or_else(|| SourceError::Malformed {
14476 message: format!("GitHub {name}.nodes is not an array"),
14477 }),
14478 }
14479}
14480fn complete_connection(connection: &Value, name: &str, size: u32) -> Result<(), SourceError> {
14481 let page_info = connection
14482 .get("pageInfo")
14483 .ok_or_else(|| SourceError::Malformed {
14484 message: format!("GitHub {name} has no pageInfo"),
14485 })?;
14486 if required_bool(page_info, "hasNextPage")? {
14487 return Err(SourceError::Malformed {
14488 message: format!(
14489 "GitHub {name} exceeds the supported nested connection size of {size}"
14490 ),
14491 });
14492 }
14493 Ok(())
14494}
14495fn optional_time(value: &Value, field: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
14496 optional_str(value, field)?
14497 .map(|timestamp| {
14498 timestamp.parse().map_err(|error| SourceError::Malformed {
14499 message: format!("GitHub response field {field} is not a timestamp: {error}"),
14500 })
14501 })
14502 .transpose()
14503}
14504fn validate_page(page: &PageRequest) -> Result<(), SourceError> {
14505 if page.limit == 0 {
14506 Err(SourceError::Config {
14507 message: "page limit must be at least 1".into(),
14508 })
14509 } else {
14510 Ok(())
14511 }
14512}
14513fn next_cursor(connection: &Value) -> Result<Option<Cursor>, SourceError> {
14514 let page = connection
14515 .get("pageInfo")
14516 .filter(|value| value.is_object())
14517 .ok_or_else(|| SourceError::Malformed {
14518 message: "GitHub connection is missing pageInfo".into(),
14519 })?;
14520 if required_bool(page, "hasNextPage")? {
14521 let cursor = required_str(page, "endCursor")?;
14522 validate_cursor_progress(None, cursor)?;
14523 Ok(Some(Cursor(cursor.into())))
14524 } else {
14525 Ok(None)
14526 }
14527}
14528fn validate_cursor_progress(previous: Option<&str>, next: &str) -> Result<(), SourceError> {
14529 if next.is_empty() || previous == Some(next) {
14530 Err(SourceError::Malformed {
14531 message: "GitHub pagination cursor is empty or did not advance".into(),
14532 })
14533 } else {
14534 Ok(())
14535 }
14536}
14537/// The version of this plugin's opaque narrowing-search cursor.
14538pub const SEARCH_CURSOR_VERSION: u32 = 4;
14539
14540#[derive(Serialize, Deserialize)]
14541#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
14542enum SearchConnection {
14543 Initial {},
14544 Continuing { after: Cursor },
14545 Exhausted {},
14546}
14547impl SearchConnection {
14548 fn after(&self) -> Option<&str> {
14549 match self {
14550 Self::Continuing { after } => Some(&after.0),
14551 _ => None,
14552 }
14553 }
14554 fn exhausted(&self) -> bool {
14555 matches!(self, Self::Exhausted { .. })
14556 }
14557 /// Whether a cursor naming this position, `offset` rows into its page, is one this
14558 /// plugin could have handed out: a page is resumed only part of the way through it — an
14559 /// offset of a whole page or more would skip rows nobody was given — an initial page
14560 /// only once some of it was handed out, and an exhausted connection has no page to be
14561 /// part of the way through.
14562 fn valid_resume(&self, offset: usize) -> bool {
14563 let within = offset < SEARCH_PAGE_SIZE as usize;
14564 match self {
14565 Self::Initial { .. } => offset > 0 && within,
14566 Self::Continuing { after } => !after.0.is_empty() && within,
14567 Self::Exhausted { .. } => offset == 0,
14568 }
14569 }
14570}
14571
14572/// Versioned source cursor. A zero offset and empty own-write ids are omitted.
14573#[derive(Serialize, Deserialize)]
14574#[serde(deny_unknown_fields)]
14575struct SearchPosition {
14576 version: u32,
14577 connection: SearchConnection,
14578 /// How many rows of the page `connection` starts were already handed out.
14579 #[serde(default, skip_serializing_if = "is_zero")]
14580 offset: usize,
14581 #[serde(default, skip_serializing_if = "Vec::is_empty")]
14582 seen: Vec<NativeId>,
14583 #[serde(default, skip_serializing_if = "Vec::is_empty")]
14584 own: Vec<NativeId>,
14585}
14586impl Default for SearchPosition {
14587 fn default() -> Self {
14588 Self {
14589 version: SEARCH_CURSOR_VERSION,
14590 connection: SearchConnection::Initial {},
14591 offset: 0,
14592 seen: Vec::new(),
14593 own: Vec::new(),
14594 }
14595 }
14596}
14597
14598fn is_zero(offset: &usize) -> bool {
14599 *offset == 0
14600}
14601
14602fn numeric_cursor(cursor: Option<&Cursor>) -> Result<usize, SourceError> {
14603 cursor.map_or(Ok(0), |c| {
14604 c.0.parse().map_err(|_| SourceError::Config {
14605 message: "page cursor is invalid".into(),
14606 })
14607 })
14608}
14609fn offset_page<T>(mut items: Vec<T>, offset: usize, limit: usize) -> Page<T> {
14610 if offset > items.len() {
14611 return Page::last(vec![]);
14612 }
14613 let tail = items.split_off(offset);
14614 let mut selected = tail;
14615 let next = (selected.len() > limit).then(|| Cursor((offset + limit).to_string()));
14616 selected.truncate(limit);
14617 Page {
14618 items: selected,
14619 next,
14620 }
14621}
14622
14623impl GitHubProjectsSource {
14624 async fn write_task_assets(
14625 &self,
14626 write: &ItemWrite<Task>,
14627 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
14628 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
14629 self.write_item(
14630 &self.task_incoming(write, assets)?,
14631 write.target.as_ref(),
14632 &write.depends_on,
14633 )
14634 .await
14635 }
14636
14637 /// One task write as [`Self::write_item`] takes it, once what it delivers and its priority
14638 /// are known to be ones this source can write.
14639 fn task_incoming<'a>(
14640 &self,
14641 write: &'a ItemWrite<Task>,
14642 assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
14643 ) -> Result<Incoming<'a>, SourceError> {
14644 let near = write.target.as_ref().unwrap_or(&write.item.id);
14645 for (key, entries) in [
14646 (TaskRef::DELIVERS_KEY, &write.item.delivers),
14647 (TaskRef::DELIVERED_BY_KEY, &write.item.delivered_by),
14648 ] {
14649 TaskRef::listed(key, near, Some(&self.name), entries.clone())
14650 .map_err(|message| SourceError::Refused { message })?;
14651 }
14652 if self.priorities.is_none() && write.item.priority != Priority::None {
14653 return Err(self.holds_no_priority());
14654 }
14655 Ok(Incoming {
14656 written: Written::Work(ItemKind::Task, &write.item.status),
14657 title: &write.item.title,
14658 content: write.item.content.as_deref(),
14659 assets,
14660 labels: &write.item.labels,
14661 metadata: &write.item.metadata,
14662 repositories: &write.item.repositories,
14663 classification: write.item.classification,
14664 parent: write.item.project.as_ref(),
14665 delivers: &write.item.delivers,
14666 delivered_by: &write.item.delivered_by,
14667 priority: self.priorities.as_ref().map(|_| write.item.priority),
14668 })
14669 }
14670 async fn write_document_assets(
14671 &self,
14672 write: &ItemWrite<Document>,
14673 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
14674 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
14675 // A document takes part in no dependency graph, so there is no far end to write
14676 // natively and none to record: a caller naming one is told so rather than having it
14677 // stored under the reserved key, where a later read would report an edge the
14678 // contract says cannot exist.
14679 if !write.depends_on.is_empty() {
14680 return Err(SourceError::Refused {
14681 message: format!(
14682 "this write names {} dependencies for a document, and a document takes \
14683 part in no dependency graph; next: put the dependency on the task or \
14684 project the document is about",
14685 write.depends_on.len()
14686 ),
14687 });
14688 }
14689 self.write_item(
14690 &Incoming {
14691 written: Written::Document,
14692 title: &write.item.title,
14693 content: write.item.content.as_deref(),
14694 assets,
14695 labels: &write.item.labels,
14696 metadata: &write.item.metadata,
14697 repositories: &write.item.repositories,
14698 classification: write.item.classification,
14699 parent: write.item.project.as_ref(),
14700 delivers: &[],
14701 delivered_by: &[],
14702 priority: None,
14703 },
14704 write.target.as_ref(),
14705 &[],
14706 )
14707 .await
14708 }
14709}
14710
14711/// What [`TaskSource::end_command`] leaves of this source's held state, asserted on the state
14712/// itself, for the two things no journey can observe.
14713///
14714/// The journeys in `crates/onetaskgraph-e2e/tests/e2e/end_command.rs` prove through the engine,
14715/// with and without the call, that a settlement, a board listing and a metadata search each
14716/// read afresh after it — the resolved records, the written-item overlay, the board and its
14717/// search, and the narrowed searches. What they cannot reach is the held field definitions,
14718/// because a status write naming an option a person deleted is refused the same whether or
14719/// not the list is held, and a poisoned lock, because nothing outside the source can panic
14720/// while one of its locks is held. So these assert those directly, and every other holder
14721/// beside them so a holder added later without a clear in the call fails here.
14722#[cfg(test)]
14723mod end_command_tests {
14724 use super::*;
14725
14726 struct Token;
14727
14728 impl SecretResolver for Token {
14729 fn get(&self, var: &str) -> Option<SecretString> {
14730 (var == "GH_PROJECTS_TOKEN").then(|| "test-token".into())
14731 }
14732 }
14733
14734 fn source() -> GitHubProjectsSource {
14735 let config = serde_json::from_value(json!({
14736 "owner": "octo-org", "project_number": 7, "repository": "acme/work",
14737 // Nothing here is sent: the source is only built and its state inspected.
14738 "endpoint": "http://127.0.0.1:9/graphql",
14739 }))
14740 .expect("a usable configuration");
14741 GitHubProjectsSource::new(&SourceName::new("work").unwrap(), config, &Token)
14742 .expect("the source builds")
14743 }
14744
14745 /// One issue as a board read answers it.
14746 fn resolved(source: &GitHubProjectsSource) -> Resolved {
14747 source
14748 .resolve(&json!({
14749 "id": "ITEM-1",
14750 "content": {"__typename": "Issue", "id": "I_1", "title": "Held",
14751 "body": "what a person may since have edited", "state": "OPEN",
14752 "stateReason": null, "url": null, "number": 1,
14753 "subIssuesSummary": {"total": 0},
14754 "labels": {"nodes": [], "pageInfo": {"hasNextPage": false}}},
14755 "fieldValues": {"nodes": [], "pageInfo": {"hasNextPage": false}},
14756 }))
14757 .expect("the item reads")
14758 .expect("an issue")
14759 }
14760
14761 /// Hold something in every holder the call clears, and the repository id it keeps.
14762 fn fill(source: &GitHubProjectsSource) {
14763 let item = resolved(source);
14764 source.created.lock().unwrap().push(item.clone());
14765 source.updated.lock().unwrap().push(item.clone());
14766 *source.board_cache.lock().unwrap() = Some(Board {
14767 id: "PVT-board".into(),
14768 fields: json!({"nodes": []}),
14769 items: vec![item.clone()],
14770 });
14771 *source.search_cache.lock().unwrap() = Some(vec![item.clone()]);
14772 source
14773 .narrowed_cache
14774 .lock()
14775 .unwrap()
14776 .insert("status:todo".into(), vec![item.clone()]);
14777 source.children_cache.lock().unwrap().insert(
14778 NativeId("P-1".into()),
14779 (NativeId("P-1".into()), vec![item.clone()]),
14780 );
14781 source
14782 .search_next
14783 .lock()
14784 .unwrap()
14785 .insert("status:todo".into(), Some("cursor".into()));
14786 source
14787 .resolved_cache
14788 .lock()
14789 .unwrap()
14790 .insert(item.id.clone(), item);
14791 *source.fields_cache.lock().unwrap() = Some(BoardFields {
14792 id: BoardId::parse("PVT-board").unwrap(),
14793 fields: json!({"nodes": []}),
14794 });
14795 source
14796 .repository_cache
14797 .lock()
14798 .unwrap()
14799 .insert(RepositoryTarget::parse("acme/work").unwrap(), "R_1".into());
14800 }
14801
14802 fn assert_dropped(source: &GitHubProjectsSource) {
14803 assert!(source.created().unwrap().is_empty(), "created");
14804 assert!(source.updated().unwrap().is_empty(), "updated");
14805 assert!(source.board_cache().unwrap().is_none(), "board");
14806 assert!(source.search_cache.lock().unwrap().is_none(), "search");
14807 assert!(source.narrowed_cache.lock().unwrap().is_empty(), "narrowed");
14808 assert!(
14809 source.children_cache.lock().unwrap().is_empty(),
14810 "project children"
14811 );
14812 assert!(
14813 source.search_next.lock().unwrap().is_empty(),
14814 "search paging"
14815 );
14816 assert!(
14817 source.resolved_cache().unwrap().is_empty(),
14818 "resolved records"
14819 );
14820 assert!(source.fields_cache().unwrap().is_none(), "board fields");
14821 assert_eq!(
14822 source.repository_cache().unwrap().len(),
14823 1,
14824 "a repository's node id stays valid and is kept"
14825 );
14826 }
14827
14828 fn end(source: &GitHubProjectsSource) {
14829 tokio::runtime::Builder::new_current_thread()
14830 .build()
14831 .unwrap()
14832 .block_on(source.end_command())
14833 .expect("the command ends");
14834 }
14835
14836 #[test]
14837 fn the_call_drops_every_item_search_and_board_read_and_keeps_repository_ids() {
14838 let source = source();
14839 fill(&source);
14840 end(&source);
14841 assert_dropped(&source);
14842 }
14843
14844 #[test]
14845 fn the_call_clears_a_lock_an_earlier_failure_poisoned() {
14846 fn poison<T: Send>(held: &Mutex<T>) {
14847 std::thread::scope(|scope| {
14848 let _ = scope
14849 .spawn(|| {
14850 let _guard = held.lock().unwrap();
14851 panic!("a failure while the lock is held");
14852 })
14853 .join();
14854 });
14855 assert!(held.is_poisoned());
14856 }
14857 let source = source();
14858 fill(&source);
14859 poison(&source.created);
14860 poison(&source.updated);
14861 poison(&source.board_cache);
14862 poison(&source.search_cache);
14863 poison(&source.narrowed_cache);
14864 poison(&source.search_next);
14865 poison(&source.resolved_cache);
14866 poison(&source.fields_cache);
14867 assert!(
14868 source.resolved_cache().is_err(),
14869 "a poisoned lock is refused before the call"
14870 );
14871 end(&source);
14872 assert_dropped(&source);
14873 }
14874}
14875
14876#[cfg(test)]
14877mod unprojectable_fields_tests {
14878 use super::*;
14879
14880 /// The field names `docs/metadata.md` says a `metadata_fields` entry may not name.
14881 fn documented() -> std::collections::BTreeSet<String> {
14882 let document = std::fs::read_to_string(
14883 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
14884 )
14885 .expect("docs/metadata.md is readable");
14886 let document = document.split_whitespace().collect::<Vec<_>>().join(" ");
14887 let lead = "a `field` equal, ignoring case, to ";
14888 let start = document.find(lead).expect("the refused-field sentence") + lead.len();
14889 let sentence = &document[start..];
14890 let sentence = &sentence[..sentence
14891 .find("; and two entries naming one field")
14892 .expect("the refused-field sentence ends at the duplicate rule")];
14893 let (own, github) = sentence
14894 .split_once(" or a field GitHub owns on every board (")
14895 .expect("the sentence names GitHub's own fields");
14896 own.split('`')
14897 .skip(1)
14898 .step_by(2)
14899 .chain(
14900 github
14901 .strip_suffix(')')
14902 .expect("GitHub's own fields close the sentence")
14903 .split(", "),
14904 )
14905 .map(str::to_owned)
14906 .collect()
14907 }
14908
14909 #[test]
14910 fn the_documented_refused_fields_are_exactly_the_ones_the_configuration_refuses() {
14911 let refused: std::collections::BTreeSet<String> = UNPROJECTABLE_FIELDS
14912 .iter()
14913 .map(|&name| name.to_owned())
14914 .collect();
14915 assert_eq!(documented(), refused, "the fields docs/metadata.md lists");
14916 let instance = SourceName::new("work").unwrap();
14917 for name in UNPROJECTABLE_FIELDS {
14918 for spelled in [name.to_owned(), name.to_uppercase()] {
14919 let entry = MetadataFieldConfig {
14920 field: spelled.clone(),
14921 key: "team.machine".to_owned(),
14922 path: Vec::new(),
14923 };
14924 let refused = MetadataField::resolve(vec![entry], &instance)
14925 .expect_err("an unprojectable field is refused");
14926 assert!(
14927 refused.to_string().contains(&format!("{name:?}")),
14928 "{spelled}: {refused}"
14929 );
14930 }
14931 }
14932 }
14933}