onetaskgraph_github_projects/lib.rs
1//! A stateless onetaskgraph source over one GitHub Projects v2 board.
2//!
3//! **A write held to a version** (`--if-version`) is checked immediately before its first
4//! mutation and not as one step with it: GitHub takes no conditional write, so the engine reads
5//! the task through this source just before writing it, and a change landing between that read
6//! and the mutation — the time one request takes — is GitHub's residual race.
7//!
8//! **A board is a container of projects, not a project.** Its own `title`,
9//! `shortDescription` and `readme` are never read as an item's fields and are never
10//! written: nothing in this source can rename the board a user configured.
11//!
12//! **A project is an issue and its tasks are that issue's sub-issues.** GitHub's schema
13//! decides that: `Issue` exposes `parent`, `subIssues` and `subIssuesSummary`, and
14//! `DraftIssue` exposes none of them. Creating an issue needs a `repositoryId`, and a
15//! board has none, so a write without [`GitHubProjectsConfig::repository`] is refused
16//! naming the field — but that repository is the *fallback*, not the home of every item.
17//!
18//! <!-- llmlint: ignore-block[contracts_have_one_source_or_a_drift_gate] The rule's one
19//! executable source is `GitHubProjectsSource::creation_target`; this is where a reader of
20//! the module meets it, and `tests/plugin.rs` drives every arm below against the loopback
21//! board and asserts on `createIssue`'s own `repositoryId`, so the prose cannot outlive a
22//! change to the rule. -->
23//! **Which repository an issue is created in is decided by the item's own `repositories`
24//! field, under one rule.** Exactly one entry names the repository the issue is created in:
25//! a task issue is where a person finds the work from the repository it changes, and one
26//! filed in a board's nominated repository is invisible from every other. Zero entries, or
27//! two or more, name none, so a task's or a document's issue is created in the repository
28//! its parent project's issue lives in — read from the board, or from this process's own
29//! record of a project it created earlier in the same command — and a project's issue, or
30//! a task or document written with no parent, is created in the configured `repository:`.
31//! What that rule refuses, it refuses before `createIssue`, so no issue is half-created. An
32//! existing issue is never moved: the update path leaves the issue where it is and records
33//! the list in the metadata slot when it differs, so the read side's derivation and the
34//! creation rule agree by construction.
35//! <!-- llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate] -->
36//!
37//! **A document is an ordinary issue whose title begins [`DESIGN_TITLE_PREFIX`].** A
38//! board has no document type and nothing but issues to hold one in, so the title is the
39//! discriminator and it is the whole of it. The title this source *reports* is the one a
40//! person wrote, with the prefix taken off — the same way the metadata slot is taken off
41//! the body so `content` is what the person wrote — and writing a document puts the prefix
42//! back, so a round trip returns the title that went in.
43//!
44//! **Telling a document from a project from a task.** The design prefix is read **first**:
45//! a document is never a project and never a task, whatever sub-issues it has or does not
46//! have. Only then does the rest apply — a board issue is a project when *either* it has
47//! sub-issues *or* it carries [`ItemKind::METADATA_KEY`]; otherwise it is a task. A
48//! sub-issue is always a task, whatever it carries. The marker is sufficient and never
49//! necessary: it is what makes an *empty* project — the state a project copy passes
50//! through between creating the project and filing its first task — readable as a
51//! project, while the sub-issue arm lets a person author a project on the board by hand
52//! with no knowledge of this product's metadata at all. Reading the prefix later than the
53//! sub-issue rule would make a design issue with no sub-issues an empty project, which is
54//! exactly the state that rule exists to catch. Pull requests are neither a project nor a
55//! task nor a document and are ignored.
56//!
57//! **A task's comments are its issue's comments.** They are read off `Issue.comments` and
58//! written with `addComment`, `updateIssueComment` and `deleteIssueComment`, and a comment's
59//! id is GitHub's own node id for the `IssueComment`. Two things GitHub decides are refused
60//! rather than papered over: a board **draft** is not an issue and has no comments at all, so
61//! a comment call on one is refused rather than answered with an empty page; and GitHub signs
62//! every comment as the account the token belongs to, so a comment handed an author of its
63//! own is refused rather than posted under another name. GitHub's comment mutations take the
64//! comment's id and nothing else, so an edit or a delete first reads which issue that comment
65//! is on, and a comment on some other issue is one this task does not have.
66//!
67//! **Where an entity is, is a link.** Every project, task and document this source reports
68//! carries a [`Location::Url`] naming the issue's own web address — the same address the
69//! `url` field already reports, in the shape that says a reader can open it. That is the
70//! contrast the location contract exists for: a reader holding an entity from this source
71//! is handed something to link to and one holding an entity from a folder of Markdown is
72//! handed a path, and neither has to know which plugin answered. It does not replace or
73//! derive from `url`; that field goes on reporting what it always reported.
74//!
75//! **Where metadata lives.** Short typed things go to typed fields and native relations:
76//! status to the board's `Status` single-select and the issue's own state, the copy
77//! origin to a source-owned `onetaskgraph.origin` text field, and dependencies to
78//! `blockedBy` and to sub-issue links. Unbounded caller JSON goes in a trailing
79//! `<!-- onetaskgraph.metadata ... -->` comment at the end of the issue body — the same
80//! encoding `docs/metadata.md` settles for Linear, not a second one. A ProjectV2 text
81//! field is length-bounded and `shortDescription` is capped at 300 characters, which is
82//! why neither can hold a caller's own prose. Setting one caller key on its own — on a task,
83//! a project or a document alike — is one update of the issue body that changes that slot
84//! and not one byte outside it, and it is not sent at all when the key already holds the
85//! value. The link a copy records on an item it copied, `onetaskgraph.copies`, is small and
86//! is kept in that same slot, written by that same update.
87//!
88//! **A caller's value can also be projected onto a board text field**, so the board can filter
89//! on it: each [`GitHubProjectsConfig::metadata_fields`] entry names a text field, a top-level
90//! metadata key and a path inside its value. The slot stays the value's one home — every read
91//! reports metadata from it alone — and the field follows it on every write of an item, a
92//! create, an update and a copy alike: a string is written, an array of strings as one line per
93//! element and an object of string values as one `KEY: VALUE` line per entry in byte order of
94//! the keys, shortened past [`TEXT_FIELD_LIMIT`] to its leading whole lines and a line counting
95//! the rest, and none of them sent again while the field holds that text — an empty string,
96//! array or object included, which writes the empty string; nothing there or `null` clears a
97//! field holding a value; any other JSON type is refused before any mutation, the shared rule
98//! [`ProjectedValue`] decides. It rides the ordered [`graphql::UPDATE_FIELDS`]
99//! write beside `Status`, `Priority` and the origin, so it adds no request; a key set on its
100//! own moves its field first and the body last, as every write of an existing item does. A
101//! board without the field, or with a non-text field of that name, is refused before any
102//! mutation pointing at `sources fields`, whose [`GitHubProjectsSource::fields`] creates it as
103//! a text field and never changes a field that is there.
104//!
105// 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.
106//! **Status.** `status_mapping` is per-instance configuration, in the shared grammar
107//! [`onetaskgraph_plugin_api::StatusMapping`] documents, from a status category to an
108//! option of the board's one `Status` field for a task and for a project: a bare name is
109//! the option for both kinds, `null` disables the category for both, and `{task, project}`
110//! names it per kind. A category the mapping does not mention keeps its shipped default for
111//! both kinds; one it mentions is exactly what it configures, so a per-kind object no longer
112//! gets the shipped default for the kind it leaves out. Two categories one kind would read
113//! back from one option are refused as the configuration is read, ignoring case, while one
114//! option may stand for different categories of the two kinds. Writes go by the kind of the
115//! item written: a status that kind has no option for, or whose option the board lacks, is
116//! refused before any mutation, naming the source, the kind, the category and the key
117//! `status_mapping.<category>.<kind>` — there is no fallback. `done` selects its mapped
118//! option and closes the issue as `COMPLETED`; `cancelled` selects its mapped option and
119//! closes it as `NOT_PLANNED`, for either kind. Every open category reopens a closed issue
120//! before selecting its option. Reads give a closed issue's reason precedence over its
121//! option, while an open issue's option decides its category through its own kind's
122//! mapping, and an option that mapping does not name reads as `unknown` under its own name.
123//! The guarded [`GitHubProjectsSource::status_options`] and
124//! [`GitHubProjectsSource::fields`] operations are the one path here that calls
125//! `updateProjectV2Field`: GitHub replaces the whole option list, so they preserve every
126//! existing option id and verify the field and item assignments immediately afterwards.
127//! They ask for both kinds' options, counting a terminal category's mapped option as
128//! configured because a terminal write refuses without it. No ordinary source read or
129//! write calls that mutation, whose
130//! `singleSelectOptions` *overwrites* a field's option set, so no addition is additive
131//! and a mistake destroys every item's status. A status this board cannot represent is a
132//! refusal naming the status and the instance instead.
133//!
134//! `unknown` has no shipped option because this source cannot preserve an open-ended
135//! status word: it writes an existing board option and never
136//! creates an option. An operator may map `unknown` to one existing option, in which case
137//! every unknown word lands on that option and reads back as `unknown` under the option's
138//! name. This differs from `local-md`, which writes and reads the original word itself.
139//!
140//! The shipped terminal options are exactly `done: Done` and `cancelled: Cancelled`.
141//! `done` also closes the issue because GitHub derives `subIssuesSummary.completed`
142//! and the board's own `Sub-issues progress` field from closed sub-issues: a plan whose
143//! finished tasks were only moved to a "Done" column would read 0% complete forever.
144// llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
145//!
146//! # What this source declares, field by field
147//!
148//! One verdict per field of [`Capabilities`], and what `Native` means when this source
149//! says it. *Proven* means a shared journey drives it against the real
150//! binary over this source's own row in `crates/onetaskgraph-e2e-support/src/fixtures.rs`, and
151//! `every_row_declares_exactly_what_its_plugin_reports` is what keeps this list and
152//! [`capabilities`](TaskSource::capabilities) from parting.
153//!
154//! | Field | Verdict |
155//! | --- | --- |
156//! | `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. |
157//! | `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. |
158//! | `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. |
159//! | `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. |
160//! | `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. |
161//! | `assignees` | **Supported and proven when `config.assignees: true`,** unsupported otherwise, which reads no issue's assignees and sends exactly the requests it sent before assignees existed. An issue's `assignees` by login, every one it holds, selected on the reads the source already makes; a write replaces them with one login or none as one more aliased field of the document the write already sends, and a login GitHub refuses, or answers leaving off the issue, is refused for that item naming it. See [`assignees`] for the login lookup. Proven by `onetaskgraph-github-projects-e2e`'s `assignees` journeys. |
162//! | `filter_by_priority` | **Supported and proven,** over the priority each task reads as — `none` for every task of an instance without `priority_mapping`. |
163//! | `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. |
164//! | `orphan_tasks` | **Supported and proven.** A task issue with no `parent` is in no project. |
165//! | `filter_by_label` | **Supported and proven,** over the issue's own labels. |
166//! | `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. |
167//! | `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. |
168//! | `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. |
169//! | `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. |
170//! | `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. |
171//! | `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. |
172//! | `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. |
173//! | `task_dependencies` | **Supported and proven,** in both directions: `blockedBy` and `blocking`. |
174//! | `project_dependencies` | **Supported and proven,** in both directions, over the same two connections, because a project here is an issue. |
175//! | `max_page_size` | **Supported and proven.** [`MAX_PAGE_SIZE`], GitHub's own connection maximum. |
176//!
177//! Image writes use `POST https://uploads.github.com/user-attachments/assets` with `name`,
178//! `content_type` and the issue repository's numeric `repository_id` as query parameters,
179//! the source token as `Authorization: Bearer`, the image content type as `Content-Type`,
180//! and the raw bytes as the request body. The numeric repository id is read at most once
181//! per repository per source instance. A loopback API endpoint also selects the loopback
182//! uploads host; production needs no assets repository, commits or extra configuration.
183//! Every returned JSON `url` is read with the same token before a body is written: only
184//! a 2xx verification succeeds. A refusal names the asset, URL and HTTP status; an
185//! anonymous 404 does not invalidate an authenticated 200. An upload refusal names the
186//! asset and HTTP status and says the token type may not be accepted by the upload
187//! endpoint. A classic PAT was measured accepted; no acceptance claim is made about
188//! fine-grained PATs or OAuth tokens.
189//! The body keeps the authored alt text while `./<name>` becomes the attachment URL,
190//! and `onetaskgraph.assets` records `{sha256, url}` by name. A matching destination
191//! SHA-256 reuses its URL without an upload or verifying read; changed bytes are uploaded
192//! and verified afresh, in the repository the issue already lives in on an update.
193//! An uploaded image renders for the viewers GitHub lets read it, like the issue text beside it.
194//! Uploads take the same mutation spacing as content writes. Both uploads and verification
195//! reads wait out classified rate limits within the configured per-call retry budget,
196//! on the supplied clock; verifying reads take no mutation slot.
197//!
198//! Nothing here is unsupported. `documents` and `comments` are not predicates — they say this
199//! source has documents and that its tasks have comments, both of which hold — and the three
200//! facts behind the uniform `Native` on the
201//! predicates beside it are recorded below rather than re-derived, because a reader who
202//! takes `Native` to mean *the remote service filters* will read that uniformity as a
203//! lie.
204//!
205//! First, the plugin contract defines `Support::Native` as *the source applies this
206//! predicate itself*, and says nothing about where it applies it. What the declaration
207//! promises the engine is capability rule 1 — a predicate declared `Native` **is** applied
208//! — so that the engine may push it down and apply nothing of its own.
209//!
210//! Second, this source can keep that promise for every predicate at no additional API
211//! cost, because whichever of the reads below answers a query has already read every
212//! candidate that query will return before it filters anything. Filtering those items is
213//! in-process work over data already in hand.
214//!
215//! Third, six task predicates are asked of GitHub as a narrower question and the rest are
216//! applied in process over what that question returned. A project filter has a relationship — a
217//! project's tasks are that issue's sub-issues, and asking the issue for them is both cheaper
218//! and exact. Comment activity is the issue search's `updated:` qualifier. A text search, and
219//! a search for metadata values, is the board-scoped issue search carrying the text and each
220//! value as quoted phrases; an origin is the board's own field filter over its origin field
221//! beside the same search for the id. **The text search narrows, and that is this source's
222//! declared semantics:** GitHub matches whole words where the substring rule this source and
223//! the local Markdown source confirm with would match inside one, so an item holding the text
224//! only inside a longer word is never a candidate. Every item returned does contain the text.
225//! A project query's text, and a document query's scoped to no project, is that same search
226//! and narrows on the same terms, its candidates confirmed by their kind as well.
227//! GitHub's issue search offers no qualifier for a label set, a status column or a priority,
228//! so those three are applied in process over the candidates, and a query carrying none of
229//! the six narrowing predicates reads the board. Declaring one `Unsupported` would make the
230//! engine compensate for work this source has already done, and declaring `projects` native
231//! while ignoring the filter (which this source once did) silently returns another project's
232//! tasks, because the engine trusts the declaration and applies nothing locally.
233//!
234//! # The three ways this source reaches an item, and what each costs
235//!
236//! A board read is charged for what its *nested* connections could return rather than for
237//! what was asked, so one whole-board read costs the same whether the question was about
238//! one project or about all of them. That is why a question about one project is never
239//! answered by reading the board:
240//!
241//! | The question | What is sent | What it costs |
242//! | --- | --- | --- |
243//! | 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 |
244//! | 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 |
245//! | one board page with each task's first comments, for `TaskSource::query_task_details` | [`graphql::BOARD_WITH_COMMENTS`] — the board's own `items`, without search completion | tasks and first comment pages in one request; board consistency, with comment-activity filtering refused |
246//! | 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 |
247//! | 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 |
248//! | one project's tasks or documents | [`graphql::SUB_ISSUES`] — that issue's own `subIssues` | that project |
249//! | which projects this board holds | [`graphql::SEARCH_ISSUES`] — an issue search scoped to the board | the board's issues, without their board items |
250//! | 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 |
251//! | 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 |
252//! | 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 |
253//! | 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 |
254//! | 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 |
255//! | 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 |
256//!
257//! The following standalone-ticket requests are pinned by the real CLI fixture journeys
258//! `follow_up_writes_resolve_each_item_once_and_batch_the_copy_fields` and
259//! `a_batched_detail_read_costs_one_request_and_one_point_per_detail_batch`, as request count
260//! equal to declared points equal to the row. They include the origin lookup and the
261//! field/repository discovery a create needs. A bound re-copy changes status, priority,
262//! content and metadata; comment recount means a subsequent detail read. Each request here
263//! costs one declared point. A membership beyond the embedded page can additionally require
264//! the one-point membership recovery described above. A bound re-copy of a task filed under a
265//! project adds one read, the engine confirming that project's link by its own id once per
266//! command; and the same-source far ends a write newly names — those that do not already block
267//! the item, whose own read answered for them — are read together by their own ids,
268//! [`DETAIL_BATCH`] to one [`graphql::ISSUE_DETAILS`] request, each new edge then one
269//! [`graphql::ADD_BLOCKED_BY`]. Both additions are rows of the table below, pinned by
270//! `a_bound_recopy_adds_one_project_read_and_batches_the_dependencies_it_newly_names`.
271//!
272//! **[`DETAIL_BATCH`] is 24**: the largest batch of [`graphql::ISSUE_DETAILS`] the node-count
273//! model prices at one point. Each aliased item is six of GitHub's aggregate, so 24 are 144,
274//! which rounds to one point, and 25 are 150, which rounds to two; `tests/point_cost.rs`
275//! holds both halves.
276//!
277//! **An existing item is written body last.** A bound re-copy and a `task update` send its
278//! board fields first — the `Status` option and the `Priority` together, in one request — then
279//! its parent and its `blockedBy`, and its title, body and state in one `updateIssue` last.
280//! GitHub runs no two requests as one, and runs a document's mutation fields in order without
281//! undoing an earlier field when a later one fails, so that order is what makes a write
282//! refused part-way leave the item's body, and every metadata key in it, exactly as it stood;
283//! the one piece of metadata written before the body, an origin a copy re-points, is put back
284//! when a later write is refused — and when putting it back is refused too, the write's own
285//! refusal names that key, what it now holds and what it held. `crates/onetaskgraph-github-projects-e2e/tests/e2e/write_order.rs` refuses each
286//! of those writes in turn, whole and as one aliased field failing after the one before it.
287//!
288//! **Two facts about GitHub the write rows rest on, each read off GitHub's published schema
289//! artifact <https://docs.github.com/public/fpt/schema.docs.graphql> on 2026-10-01 and pinned
290//! in `tests/fixtures/schema.graphql`, and the first then put to GitHub itself:**
291//!
292//! - **A board is accepted at creation but its item is not answered, so a create still files
293//! the issue itself: a new copy is 5 requests, and 4 with `--create`.**
294//! `CreateIssueInput.projectV2Ids: [ID!]` is declared there — "An array of Node IDs for
295//! Projects V2 associated with this issue", `@possibleTypes(concreteTypes: ["ProjectV2"])`.
296//! The credentialed journey `real_projects_v2_contract_writes_and_leaves_no_residue` was run
297//! against a real board on 2026-10-01 with a create sending the board there and reading the
298//! item off the payload's `Issue.projectItems`: every one of its four creates answered with
299//! no item on the board, so each went on to [`graphql::ADD_TO_BOARD`], and the fourth was
300//! refused "Content already exists in this project" — GitHub had filed the issue after
301//! answering, and refuses a second filing rather than answering with the item it holds. A
302//! create therefore sends no `projectV2Ids` and files the issue with
303//! `addProjectV2ItemById`, the one call whose answer names the board item. The saving that is
304//! real is the read before it: the board's fields and the repository's id together, in
305//! [`graphql::CREATION_CONTEXT`], at the point the repository is known.
306//! - **A comment still reads its target first, so a comment is 2 requests.**
307//! `AddCommentInput.subjectId: ID!` is declared there with
308//! `@possibleTypes(concreteTypes: ["Issue", "PullRequest"], abstractType:
309//! "IssueOrPullRequest")`. A board draft is no such subject and would be refused, but a
310//! project's issue, a document's issue, an issue on no board of this source and a pull
311//! request all are: GitHub writes the comment, so there is no refusal to map into "that is
312//! not a task of this board". [`graphql::ISSUE`] before [`graphql::ADD_COMMENT`] is what
313//! refuses those by name.
314//!
315//! | Verb | Requests / points | Documents |
316//! | --- | --- | --- |
317//! | new copy | 4 | ORIGIN_LOOKUPS (the origin, the board's fields and the repository's node and numeric ids together, a page of one carrier for each origin), CREATE_ISSUE filing the issue on the board and under its project, CREATED_BOARD_ITEMS once GitHub has added it, WRITE_FIELD_VALUES |
318//! | copy --create | 4 | CREATION_CONTEXT, CREATE_ISSUE, CREATED_BOARD_ITEMS, WRITE_FIELD_VALUES: the new copy with no origin to ask about |
319//! | 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 |
320//! | 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 |
321//! | 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 |
322//! | comment | 2 | ISSUE, ADD_COMMENT: the target is read first, because GitHub accepts a comment on any issue or pull request (see below) |
323//! | detail | 1 | ISSUE_DETAIL: the item and its first page of comments, for `task show` and `task comment list`; `--no-comments` is ISSUE alone |
324//! | batched detail | ceil(n / DETAIL_BATCH) | ISSUE_DETAILS: `task show-many` of `n` items, DETAIL_BATCH (24) at a time, comments included or not |
325//! | 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 |
326//! | recount | 1 | ISSUE_DETAIL |
327//! | status | 2 | ISSUE, UPDATE_FIELD; a terminal status additionally updates issue state |
328//! | priority | 2 | ISSUE, UPDATE_FIELD or CLEAR_FIELD, with stored priority in the mutation response |
329//! | content | 2 | ISSUE, UPDATE_ISSUE |
330//! | metadata | 2 | ISSUE, UPDATE_ISSUE |
331//! | 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 |
332//! | 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 |
333//! | record only | 1 | ISSUE |
334//!
335//! <!-- github-search-paging:start -->
336//! Board-scoped text, metadata, project-name and comment-activity searches send every
337//! page at `first = 20` (SEARCH_PAGE_SIZE), the SEARCH_ISSUES document's one-point
338//! ceiling. A later page is sent only when `hasNextPage` is true and the caller still
339//! needs rows. A page is never resized to the rows still needed: GitHub orders one
340//! search differently at different page sizes, so one fixed size makes a paged walk
341//! send exactly the requests one whole read sends, and the answer's order is the order
342//! those pages arrive in. A page below twenty would cost the same one point, and GitHub
343//! prices this document by rows, so twenty-row pages cost per row what 100-row pages do.
344//! Project-name lookup continues until an exact match or exhaustion. A task limit bounds
345//! returned and fetched pages: a limit is sliced from the pages it needs, and local
346//! confirmation can require more candidates than matching rows. Walking all pages
347//! returns the whole answer. The opaque version-4 source cursor carries GitHub's page
348//! cursor and how far into that page the last answer stopped, and resumes in the same
349//! process or a new one, without duplicates or gaps. It carries no rows: one process
350//! sends each page's search once, and a new process re-reads only the page it resumes
351//! in, then sends a further page once, never as a re-read, only when its limit still
352//! needs rows. Every request either walk sends is the one a whole read sends for that page. Own writes replace stale index
353//! copies and complete missing rows at exhaustion. Cache entries are whole GitHub pages,
354//! so a small answer cannot truncate a wider question. Origin pages remain three; whole-board sizing is unchanged.
355//! Read-after-write is a per-process guarantee. A cursor resumed in a new process is
356//! not required to include the original process's writes still omitted by the index.
357//! <!-- github-search-paging:end -->
358//!
359//! The board half of an issue — its board item's id, its `Status` option and this
360//! source's origin text field — rides along on `Issue.projectItems` in the first three, so
361//! an item reached any of those ways resolves through the same
362//! [`GitHubProjectsSource::resolve`] the board walk uses and reports the same title, the
363//! same status, the same labels and the same qualified id. That connection comes back a
364//! *page* at a time, at `BOARD_ITEMS_PAGE_SIZE`, so the entry for this board is looked for
365//! on the page in hand and — only if that page reports more of the connection — in the
366//! last row's read of that one issue's memberships, resumed from the page's own cursor and
367//! walked to exhaustion. An issue with no entry for *this* board is not this source's to
368//! report, which is what keeps an id naming another repository's issue from being answered
369//! as an item of this board; and because the page is where the search starts rather than
370//! where it ends, that answer is one about a connection read to exhaustion and never about
371//! an unread page. Nothing costs the extra read but an issue on more boards than a page
372//! holds: an issue this board really does not hold reports no next page, so its
373//! memberships are already exhausted where they arrived.
374//!
375//! **No document here selects the board's own `Labels` field, and nothing is lost by
376//! that.** An item's labels are read from its content alone, wherever that content is
377//! reached: the three documents above select `Issue.labels` on the fragment, and
378//! [`graphql::BOARD`] selects the same connection on the `... on Issue` arm of its
379//! `content`. A board's `Labels` field is not one anybody fills in: it is a built-in
380//! `ProjectV2FieldType`, it is absent from `ProjectV2CustomFieldType` so no project can
381//! create one, and `ProjectV2FieldValue` — the whole of what
382//! `updateProjectV2ItemFieldValue` accepts — offers no way to write one. So GitHub derives
383//! it from the content, for every content type it exists on, and there is nothing it can
384//! hold that the content does not already say: for an `Issue` it *is* that issue's own
385//! labels, so selecting it beside them unions a set with itself.
386//!
387//! **A draft loses nothing by that either**, which is the reasoning this paragraph once had
388//! backwards. `DraftIssue` exposes no `labels` field, and by the three schema facts above
389//! it cannot carry a board `Labels` value to be derived from one — so a draft has nothing
390//! to select *and nothing to lose*, and reports no labels at all. A `PullRequest` item is
391//! discarded by [`GitHubProjectsSource::resolve`] before labels are read. Both halves are
392//! held to that by tests in `tests/plugin.rs`: the four ways an item is reached report one
393//! label set, and that set is the fixture issue's own, by
394//! `an_item_reports_the_same_labels_title_status_and_id_however_it_is_reached`; and a board
395//! item whose content is a draft reports an empty set, by
396//! `a_board_item_whose_content_is_a_draft_reports_no_labels_at_all`. The absence of the
397//! selection is held over [`graphql::DOCUMENTS`] by
398//! `no_document_selects_the_boards_own_labels_field`.
399//!
400//! The whole-board row is still the board's own item connection, and deliberately: a
401//! **draft** board item is not an issue, so no search can list one, and the reads that have
402//! to answer for the whole board are the ones whose cost is the board's size anyway.
403//!
404//! **A question about one item this source already names by id never lists the board.**
405//! Whether that item is on this board, and what its board fields are, is answered by reading
406//! that item — its own `Issue.projectItems`, walked to exhaustion by
407//! [`GitHubProjectsSource::resolve_issue`], or a draft's own board item — and never by
408//! looking for it in [`graphql::BOARD`]'s `items` or in a listing this command already
409//! holds. That covers a write's destination, the project a new item is filed under, a
410//! same-source far end a dependency names, a status write, the dependency slot a draft keeps,
411//! and the delete that takes back an item a copy made. What such a write needs of the board
412//! and the item does not carry — the board's id, the `Status` and origin field definitions —
413//! comes from [`graphql::BOARD_FIELDS`], which reads no item at all. The reason is evidence,
414//! not economy alone: `ProjectV2.items` is a projection that lags the membership GitHub
415//! itself reports — an issue added with `addProjectV2ItemById` can be missing from it for
416//! minutes. Scanning this host's 842-item board has refused a document copy and an update
417//! even though the items' own reads named that board. A scan there gives the wrong answer
418//! as well as paying for every page. So a `board.items` lookup does not belong on any of
419//! those paths.
420//!
421//! **What a read may return is capped too, and that cap is on the document rather than on
422//! the board.** GitHub limits the number of nodes **one query may return** to
423//! [`NODE_COUNT_LIMIT`] and refuses a query above that before executing it: the answer is
424//! an error naming the connection the count crossed at, not a slow or a partial result.
425//! Every board this source reads is refused the same way, so no board is too big for these
426//! documents and none is small enough to save one that is over.
427//!
428//! The count is arithmetic over the document's own text: each connection contributes the
429//! `first:` it asks for, counts **multiply** down a nested path and **sum** across sibling
430//! paths. Those are [GitHub's published rules][node-limits] and this workspace does not
431//! restate them — `github-graphql-node-count` implements them, and
432//! [`worst_case_node_count`] under [`largest_page_sizes`] is where every node count here
433//! comes from. `every_document_this_source_sends_stays_under_githubs_node_limit`, in
434//! `tests/node_count.rs`, recomputes every document in [`graphql::DOCUMENTS`] from that
435//! same text on every run and fails naming any that reaches the limit — so a connection
436//! added to a shared fragment is caught there rather than by GitHub.
437//!
438//! What decides those counts is the page sizes: [`MAX_PAGE_SIZE`] on the outer page,
439//! `NESTED_PAGE_SIZE` on the connections hanging off one item, and
440//! `BOARD_ITEMS_PAGE_SIZE` on the page of an issue's board memberships a read carries.
441//! `$nestedFirst` is spent twice down one path of a board read, so that constant is
442//! effectively squared there, which is why it is the one the limit is most sensitive to.
443//! `BOARD_ITEMS_PAGE_SIZE` is small for a reason of its own, recorded beside it: what a
444//! page of memberships misses is recovered by one further read rather than refused, so it
445//! buys a bound every read pays for at the price of a request only a multi-board issue
446//! pays.
447//!
448//! **`nodeCount` and `cost` are two numbers against two limits, and both are computed
449//! offline here — per document, one document at a time.** `nodeCount` is the one above: the
450//! most nodes one query may return, checked per query and bounded by [`NODE_COUNT_LIMIT`].
451//! `cost` is rate-limit points, metered per hour across everything one credential does; it
452//! is what the two limiters [`Limiter`] tells apart meter, and a document under
453//! [`NODE_COUNT_LIMIT`] still says nothing about its price. [`worst_case_point_cost`] is
454//! that second number, and `tests/point_cost.rs` pins every document in
455//! [`graphql::DOCUMENTS`] at what it costs — there being no per-call point ceiling to hold
456//! one under, the pin itself is the check. The credentialed lane reconciles both figures
457//! against GitHub's own, off a probe it already sends.
458//!
459//! **What is pinned that way is a per-document price and never a session's.** The record in
460//! `session-cost.md` measures the two quantities a whole session can be counted in offline —
461//! **requests** and **worst-case nodes** — and neither is points. What one whole session
462//! consumes of the hourly point allowance is observable only from a credentialed run's own
463//! `x-ratelimit-*` headers, which is what [`accounting`] fills its per-budget figures from
464//! and what `tests/live.rs` prints at the end of every run.
465//!
466//! [node-limits]: https://docs.github.com/en/graphql/overview/rate-limits-and-node-limits-for-the-graphql-api
467//!
468//! **Where a read-after-write guarantee comes from, since neither of GitHub's two
469//! enumerations of a board can supply one alone.** Resolving a node id is strongly
470//! consistent, so a read by id and a project's own sub-issues are already current. The
471//! other two are not, and they are behind by different amounts and in different directions:
472//!
473//! - GitHub's **issue search** is an index and answers a write made moments ago with the
474//! value from before it — usually for a second or two.
475//! - **`ProjectV2.items`** is a projection GitHub rebuilds behind the write, and an item put
476//! on a board with `addProjectV2ItemById` can be **absent** from it — not present with its
477//! content withheld, absent, with the connection walked to its own `hasNextPage: false` —
478//! for *minutes*, while `Issue.projectItems` names the same membership at once.
479//!
480//! That second one is a measurement rather than a caution. This repository's own
481//! credentialed journey writes a project and waits for the board to report it, then writes a
482//! task and waits for the same thing seconds later on the same board: the project wait is
483//! answered through the search and converged in two or three attempts in each of three runs,
484//! and the task wait is answered through `ProjectV2.items` and converged in none of them
485//! inside thirty. Separately, an item added to a second and larger board was read back by
486//! `Issue.projectItems` on that board's own id while every one of that connection's nine
487//! pages, walked to exhaustion nine minutes after the add, did not name it. Reading a board
488//! through the lagging one alone is what had a board read deny an issue that had certainly
489//! landed on it.
490//!
491//! So [`GitHubProjectsSource::board`] is the **union** of both — each search result still
492//! admitted only on this board's own strongly-consistent `Issue.projectItems`, and neither
493//! enumeration dropped, because only `ProjectV2.items` lists a board draft and only the
494//! search reports what the projection is behind on. What closes the last
495//! gap, the one where both are behind, is [`GitHubProjectsSource::created`]: every read this
496//! source answers is completed with what this process itself wrote, so an item created
497//! seconds ago is reported whether or not GitHub has caught up. Nothing else is remembered,
498//! nothing is written down, and the record dies with the process. **A wait that has to
499//! observe GitHub's own data cannot be answered from that record** — which is why the
500//! credentialed journey asks through a source built afresh, and why the union above rather
501//! than a longer wait is what makes such a wait converge.
502//!
503//! **A narrowed read is the same bargain, stated for each of the three predicates it
504//! answers.** A read carrying a text, metadata or origin predicate asks GitHub's index rather
505//! than walking the board, and every such answer is completed with what this process wrote —
506//! its [`created`](GitHubProjectsSource::created) record and every existing item it wrote,
507//! each filtered by the same predicates as the rest — so an item this command wrote a moment
508//! ago is returned by a query that matches it whether or not the index has caught up. An item
509//! a caller holds the id of is read by that id, with `node(id:)`, which is strongly
510//! consistent. What is left is stated rather than papered over:
511//!
512//! | Read | Finds | Behind by |
513//! | --- | --- | --- |
514//! | text, metadata | the issue search for the phrases | what another process wrote in the last second or two, until GitHub indexes it |
515//! | 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 |
516//! | 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 |
517//! | origin, third read | this process's own writes | nothing |
518//!
519//! So an origin carrier another process added within the last second or two, before either
520//! index has it, can be missing from an origin query, and one written by the release before
521//! this one — its origin in the field alone — can be missing for as long as the board's own
522//! item connection is behind on it. A copy that must not duplicate its own earlier write
523//! relies on the link it records, not on either index. **A board draft is not an issue**, so
524//! a draft is never returned by a text, metadata or origin query, whatever it holds: no search
525//! lists one, the origin lookup drops any the board's own field filter names, and one this
526//! process wrote is not added back either.
527//!
528//! **The origin lives in the board field, and the body holds a mirror of it.** A write that
529//! carries an origin writes it to the `onetaskgraph.origin` text field and also into the
530//! body's metadata slot, so the issue search can find it in seconds. The field is
531//! authoritative: this source reads an item's origin from the field alone, so a slot that
532//! disagrees with it, or holds one where the field holds none, is never read as a second
533//! origin — and the release before this one reads the slot, drops that key's copy for the
534//! field's, and sees the same one origin.
535//!
536//! Filtering happens before paging, so a page of a filtered result is a page of the
537//! survivors rather than the survivors of a page. Label matching and the substring rule a
538//! text candidate is confirmed by answer the same question the same way the local Markdown
539//! source's do; which candidates a text search has to confirm is GitHub's word match, which
540//! is the one place the two sources can answer the same text differently.
541//!
542//! <!-- llmlint: ignore[contracts_have_one_source_or_a_drift_gate] The declaration itself
543//! has one source, `capabilities`, and the note above is the reasoning behind it rather
544//! than a second copy of it: without the three facts recorded here a reader takes the
545//! uniform `Native` for a lie and reverts it. The drift gate on the declaration is this
546//! crate's own capabilities test, which pins every field of it against a fully spelled-out
547//! `Capabilities` literal — a struct with no `Default`, so a field added to the contract
548//! fails to compile there rather than going unasserted. -->
549//! The fixture-server tests above run wherever this crate is selected; the credentialed
550//! lane runs in the same required check, beside them, and can fail it — it verifies the
551//! 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,
552//! one filed under neither, a label on one of the three and a closed status on another —
553//! because that shape is what tells an honoured predicate from an ignored one: a board
554//! holding a single project answers a project filter the same way whether or not this
555//! source applies it, which is exactly how the defect above went unseen.
556//!
557//! That lane writes only to the board `GH_PROJECTS_OWNER` and `GH_PROJECTS_NUMBER` name,
558//! and the scratch repository `GH_PROJECTS_REPOSITORY` names:
559//! `nickderobertis/onetaskgraph-live-scratch`. It refuses the core repository before any
560//! session or request, independently of the live demand. Fix that variable in the machine's
561//! onetaskgraph `secrets.env` or the environment it pushes from, such as ai-orchestrator's
562//! `.env`. The targets are declared once in `onetaskgraph_github_live`, the lane's own
563//! policy crate; absent credentials or nominations otherwise skip.
564//!
565//! GitHub Actions artifacts carry `ci-<run id>-<attempt>-<micros>`, naming their writing
566//! run and attempt; invalid Actions identity refuses before writing. Other runs retain
567//! `<host>-<process>-<micros>`. Own cleanup matches the whole stamp. Machine residue stays
568//! the owning machine's lock sweep's; Linear always keeps that form and is unaffected.
569//! The hourly janitor is cleanup, never a test lane: scratch CI residue is removed only
570//! after its run reads back as `completed`, immediately before the listed-artifact batch.
571//! Failed or incomplete ownership reads preserve residue. A 24-hour waiting period
572//! is a margin, never the ownership authorisation. Cleanup leaves machine stamps
573//! and the board's `onetaskgraph.origin` field untouched.
574//!
575//! # What a session of requests costs, and where the report is
576//!
577//! This source records **every** request it sends into [`accounting::Accounting`], at
578//! `send_once` — the one place a request leaves this crate, which is why a read path added
579//! later is counted without anybody remembering to count it. That is the whole of what this
580//! crate adds to the arrangement; [`accounting`] is where what a record carries, how a
581//! session's spend is arrived at, and what it deliberately does not know are set out.
582//!
583//! What one whole session of the live journey costs, counted that way against this crate's
584//! loopback fixture board, is written down in `session-cost.md` beside this crate — with the
585//! reduction it came out of, and with what it does and does not say about rate-limit points.
586//!
587//! [`GitHubProjectsSource::accounting`] is the read: a snapshot to hold and compare, which
588//! [`accounting::Session::report`] renders the session report from. It is on the ordinary
589//! code path — no environment variable, no feature, no build configuration — because an
590//! instrument nobody switches on measures nothing, and
591//! [`Plugin::build_recording_into`] is how a caller making its own calls beside this
592//! source's counts the whole session rather than this source's share. The credentialed lane
593//! in `tests/live.rs` does exactly that, and prints the report at the end of every run,
594//! passed or failed.
595//!
596//! **A live session refuses to start unless the account can afford it.** Before it does any
597//! of the work it exists to do, the journey makes one request — `GET /rate_limit`, which
598//! GitHub documents as not counting against the REST rate limit and which answers both of
599//! its budgets at once — and starts only if, for each of them, what remains minus this
600//! session's estimated cost is still at least
601//! `onetaskgraph_live::RETAINED_BUFFER` — twenty per cent — of that budget's whole
602//! allowance. A session that cannot **declines**: it did not run, so it is
603//! neither a pass nor a failing assertion, and it says which budget was short, that budget's
604//! limit, what remained, the estimate, the buffer and when it resets — then stops, without
605//! waiting for the budget to come back. The estimate is derived offline from
606//! `tests/fixtures/session-cost.txt` and a cost model stated in `tests/journey/budget.rs`,
607//! which is also where the published rule that model rests on is cited; the accounting
608//! above records the gate's own read like any other request, and
609//! [`accounting::Session::report`] prints the estimate beside what the session really spent.
610//!
611//! **GitHub is the authority on both of its own numbers, and the credentialed lane goes and
612//! asks it.** Everything above computes `nodeCount` and `cost` offline from a document's own
613//! text, which is what lets it run on every platform and on a pull request from a fork with
614//! no credential — and that is what actually stops a regression merging. But an offline
615//! arithmetic can only ever agree with itself: if GitHub changes its rules, this workspace
616//! goes on computing the old answer and nothing notices. So `tests/live.rs` reconciles them.
617//! GitHub's schema exposes `rateLimit(dryRun: true)`, whose `nodeCount` is *"the maximum
618//! number of nodes this query may return"* and whose `cost` is what that document would
619//! spend, both for a document **without executing it**, and the lane asks it for every query
620//! document this source sends, under the largest bindings this source sends, and fails when
621//! GitHub's figure and [`worst_case_node_count`] or [`worst_case_point_cost`] disagree. A
622//! mutation is skipped, because `rateLimit` is a field of `Query` and cannot be asked about
623//! one; the offline pins still cover it. It records what those calls reported about the
624//! account's own allowance, because whether asking is free is a thing to observe rather than
625//! to assume. Two quantities, not one: [`NODE_COUNT_LIMIT`] bounds `nodeCount` per query,
626//! and `cost` is metered against an hourly allowance the accounting above reads off a
627//! credentialed run's own response headers.
628//!
629//! **GitHub has two rate limiters and this source is refused by both, so nothing here
630//! treats them as one thing.** The primary budget is the hourly allowance `gh api
631//! rate_limit` reports; the secondary limiter is a burst limiter over content-generating
632//! requests, and *nothing* reports it. Which one refused decides the operator's next step,
633//! so [`Limiter`] is a type rather than a detail, and it is what [`MIN_MUTATION_INTERVAL_MS`],
634//! [`GitHubProjectsSource::board_cache`] and [`GitHubProjectsSource::graphql`] each answer
635//! one part of.
636#![deny(missing_docs)]
637
638use std::collections::BTreeMap;
639use std::sync::{Arc, Mutex};
640use std::time::Duration;
641
642use chrono::{DateTime, Utc};
643use onetaskgraph_plugin_api::ProjectedValue;
644use onetaskgraph_plugin_api::{
645 Capabilities, Classification, ClosedAs, Comment, CommentBody, CommentOrigin, Completion,
646 ContradictedItem, Coverage, Cursor, DependencyEdge, DependencyEndpoint, DependencyKind,
647 DependencySupport, Designator, Direction, Document, DocumentQuery, DocumentVersionCoverage,
648 Health, HeldTask, IssueHolding, IssueRef, ItemKind, ItemWrite, Label, LabelFilter, Location,
649 MetadataKey, Metering, NativeId, NewComment, Page, PageRequest, Priority, Project,
650 ProjectFilter, ProjectQuery, ProjectVersionCoverage, Repository, SecretResolver, SharedClock,
651 SourceError, SourceName, SourcePlugin, Status, StatusCategory, StatusContradiction,
652 StatusMapping, Support, Task, TaskDetailRead, TaskQuery, TaskRef, TaskSource, TaskUpdate,
653 TaskUpdateOutcome, TextFields, TextQuery, UnmappedStatus, UpdatedField, VersionCoverage,
654 WaitCause, WriteJournal, WriteSupport, system_clock,
655};
656use reqwest::{Client, StatusCode, Url};
657use schemars::{Schema, schema_for};
658use secrecy::{ExposeSecret, SecretString};
659use serde::{Deserialize, Serialize};
660use serde_json::{Value, json};
661
662pub mod accounting;
663mod assets;
664mod assignees;
665mod batch;
666pub mod change_token;
667mod expected;
668pub use expected::{CONTEXT_VERSION, WHOLE_MEMBERS, context_shapes};
669mod pacing;
670mod projection;
671mod quota;
672mod relations;
673mod visibility;
674
675use accounting::Accounting;
676
677/// The registry name for this plugin.
678pub const KIND: &str = "github-projects";
679/// GitHub's maximum connection page size.
680pub const MAX_PAGE_SIZE: u32 = 100;
681/// Every page of a board-scoped narrowing search: 20 rows, one point of SEARCH_ISSUES, the
682/// most one point buys. GitHub prices that document by rows, so pages of 20 cost what pages
683/// of 100 cost per row, and a page of fewer than 20 costs the same one point.
684pub const SEARCH_PAGE_SIZE: u32 = 20;
685/// How many items one [`graphql::ISSUE_DETAILS`] request reads, each with the first page of
686/// its comments: the largest batch the node-count model prices at one point.
687///
688/// Each aliased item is resolved once, and what GitHub charges for it is the connections
689/// under it — its labels, its page of board memberships, the field values of each of those
690/// three memberships, and its comments: six requests' worth of the aggregate GitHub divides
691/// by a hundred and rounds. Twenty-four items come to 144, which rounds to one point;
692/// twenty-five come to 150, which rounds to two. `tests/point_cost.rs` prices the document at
693/// one point and fails if one item more would still be priced at one.
694pub const DETAIL_BATCH: usize = 24;
695/// How many issue references one [`graphql::ISSUES_BY_REFERENCE`] request reads.
696///
697/// Each reference asks GitHub for one connection — a page of its board memberships, each with
698/// its `Status` value read by name rather than through a connection of field values — so fifty
699/// come to fifty requests' worth of the aggregate GitHub divides by a hundred, which is its
700/// one-point minimum, and the batch a landing's closures are read in costs one point per fifty
701/// issues per source. `tests/point_cost.rs` prices the document at one point.
702pub const REFERENCE_BATCH: usize = 50;
703/// How many items one [`graphql::ISSUE_COPY_DETAILS`] request reads: each with the first page
704/// of its comments and its `blockedBy`, the largest batch the node-count model prices at one
705/// point.
706///
707/// The six requests' worth an item of [`DETAIL_BATCH`] costs, and its `blockedBy` connection
708/// besides: seven. Twenty-one items come to 147, which rounds to one point; twenty-two come to
709/// 154, which rounds to two. `tests/point_cost.rs` prices the document at one point and fails
710/// if one item more would still be priced at one.
711pub const COPY_DETAIL_BATCH: usize = 21;
712/// How many mutations one aliased request of a copy's creates, closes and updates carries:
713/// [`graphql::CREATE_ISSUES`], [`graphql::CLOSE_ISSUES`] and [`graphql::UPDATE_ISSUES`].
714///
715/// Eleven is what GitHub was seen to accept in one request — the timing spike
716/// (`board-copy-speed-2026-10-18-spike-copy-timing-report`) sent eleven aliased mutations of four
717/// kinds, three `createIssue`, three `addProjectV2ItemById`, three field updates, an
718/// `addSubIssue` and an `addBlockedBy`, and every one ran — and no more was established.
719pub const MUTATION_BATCH: usize = 11;
720
721/// The most people one lookup ([`graphql::user_ids`]) asks for: GitHub's documented limit of
722/// [`NODE_COUNT_LIMIT`] nodes a request, each `user(login:)` field being one. Every person a
723/// call names that this process has not resolved is looked up in one request below it — so a
724/// call is split only past it.
725#[expect(
726 clippy::cast_possible_truncation,
727 reason = "500,000 fits every target's usize"
728)]
729pub const PEOPLE_PER_LOOKUP: usize = NODE_COUNT_LIMIT as usize;
730
731/// The most relation writes — `addSubIssue`, `removeSubIssue`, `addRelatesTo`,
732/// `removeRelatesTo` — one request carries: a 60-alias `addRelatesTo` answered HTTP 504 after
733/// landing 58 of its 60 (`spike-relations`), and 30 were accepted every time.
734pub const RELATION_BATCH: usize = 30;
735/// How many aliased writes one request of a copy's board field values and blocked-by edges
736/// carries: [`graphql::WRITE_FIELD_VALUES`], [`graphql::ADD_BLOCKED_BYS`] and, for a request
737/// holding both kinds, [`graphql::WRITE_FIELDS_AND_EDGES`].
738///
739/// Nineteen is the most aliases the feasibility spike
740/// (`board-copy-gaps-2026-10-24-spike-feasibility-report`) sent in one mutation request and
741/// saw GitHub price at the one point every mutation request costs; no larger request was
742/// established, so a copy holding more is split.
743pub const WRITE_BATCH: usize = 19;
744/// How many issues one [`graphql::DELETE_ISSUES`] request deletes: one request of eleven
745/// aliased `deleteIssue` met `RESOURCE_LIMITS_EXCEEDED` from the eighth alias on, and batches
746/// of five succeeded (the feasibility spike's undo-batching run).
747pub const DELETE_BATCH: usize = 5;
748/// How many origins one [`graphql::ORIGIN_LOOKUPS`] request asks about: the nine records of a
749/// plan and the project's document, and no more, since each carries a page of the board's field
750/// filter and one of the issue search.
751pub const ORIGIN_BATCH: usize = 10;
752/// How many searches one [`graphql::SEARCH_BATCH`] request asks: what `task find` asks of a
753/// board in one call, each search an aliased `search` field of its own.
754pub const SEARCH_BATCH: usize = 20;
755/// How many origins one [`graphql::SEARCH_BATCH`] request looks up beside its searches, each by
756/// the board's own field filter in an aliased `items` field of its own and by one of the
757/// request's searches.
758pub const SEARCH_BATCH_ORIGINS: usize = 5;
759/// The rows each search of a [`graphql::SEARCH_BATCH`] request asks for on its first page.
760///
761/// A batched find asks narrowed questions that each expect a handful of answers, and every
762/// search slot is priced at its page size: three rows a slot keep a first round of
763/// [`SEARCH_BATCH`] searches at three points, where a page of [`SEARCH_PAGE_SIZE`] each would
764/// cost twenty. A search with more to answer is walked on at [`SEARCH_PAGE_SIZE`] rows a page.
765pub const SEARCH_BATCH_FIRST_PAGE: u32 = 3;
766
767/// The rows each resumed page of one [`graphql::SEARCH_BATCH`] round asks for, when `resumed`
768/// of its slots — searches and origin item listings alike — resume from a cursor.
769///
770/// Every resumed page of a round shares one [`SEARCH_PAGE_SIZE`] of rows, rather than each
771/// asking that many: a round in which all twenty searches walked on at twenty rows a slot cost
772/// 22 points in one request, while sharing holds every round to what its first pages cost and
773/// one page more. A search with more to answer is walked on over more rounds, each page still
774/// read, so what a walk answers is unchanged; a round of one resumed search asks the page a
775/// search alone asks.
776#[must_use]
777pub fn search_batch_resumed_page(resumed: usize) -> u32 {
778 let resumed = u32::try_from(resumed.max(1)).unwrap_or(u32::MAX);
779 (SEARCH_PAGE_SIZE / resumed).max(1)
780}
781
782/// The page sizes of the most expensive [`graphql::SEARCH_BATCH`] round this source sends:
783/// every slot on its first page, at [`SEARCH_BATCH_FIRST_PAGE`] rows, but one resumed slot
784/// asking all of [`search_batch_resumed_page`]'s shared rows.
785///
786/// `tests/point_cost.rs` holds every round shape [`search_batch_resumed_page`] allows to cost
787/// no more than this, and the credentialed lane reconciles GitHub's own price of the document
788/// under it. [`largest_page_sizes`] still binds every slot at [`SEARCH_PAGE_SIZE`], an upper
789/// bound on this, so the offline worst case covers more than any round sends.
790#[must_use]
791pub fn search_batch_largest_round() -> Variables {
792 let mut sizes = largest_page_sizes();
793 for slot in 0..SEARCH_BATCH {
794 sizes.insert(format!("first{slot}"), SEARCH_BATCH_FIRST_PAGE);
795 }
796 for slot in 0..SEARCH_BATCH_ORIGINS {
797 sizes.insert(format!("itemsFirst{slot}"), SEARCH_BATCH_FIRST_PAGE);
798 }
799 sizes.insert("first0".to_owned(), search_batch_resumed_page(1));
800 sizes
801}
802/// How many comments one [`graphql::ADD_COMMENTS`] request adds, and how many issue updates one
803/// [`graphql::WRITE_TASKS`] request carries: [`MUTATION_BATCH`], the most aliased mutations
804/// GitHub was seen to accept in one request.
805pub const COMMENT_BATCH: usize = MUTATION_BATCH;
806/// How many board field values one [`graphql::WRITE_TASKS`] request carries, beside
807/// [`MUTATION_BATCH`] field clears: [`WRITE_BATCH`].
808pub const TASK_FIELD_BATCH: usize = WRITE_BATCH;
809
810/// The most nodes any one document this source sends may be asked to return.
811///
812/// GitHub's own published per-query ceiling, taken from
813/// [`github_graphql_node_count::NODE_LIMIT`] rather than written out again here, so this
814/// workspace cannot hold a stale copy of somebody else's number. A query above it is
815/// **refused before it is executed**, whoever is asking and whatever board they are
816/// asking about — so this is a bound on the documents rather than a budget that runs out.
817///
818/// This is `nodeCount`, the maximum number of nodes *one query may return*. It is not
819/// `cost`, the rate-limit points a call spends against an hourly allowance shared by
820/// everything the credential does — two numbers against two limits, and this constant
821/// bounds only the first. The second is computed offline too, per document:
822/// [`worst_case_point_cost`], pinned for every document in [`graphql::DOCUMENTS`] by
823/// `tests/point_cost.rs`, and reconciled against GitHub's own `cost` by the credentialed
824/// lane. There is no constant like this one to hold a price under, because points are an
825/// hourly allowance rather than a per-call bound.
826///
827/// Neither is a session's price. What `session-cost.md` records of a whole session is its
828/// **requests** and its **worst-case nodes**; what a whole session spends in points is
829/// reported only by a credentialed run's own `x-ratelimit-*` headers, through
830/// [`accounting`]. The module section on the three ways this source reaches an item says how
831/// the count is arrived at, and which of the page sizes below decide it.
832pub const NODE_COUNT_LIMIT: u64 = github_graphql_node_count::NODE_LIMIT;
833
834/// Nested connection size for the connections that hang off one item.
835///
836/// It multiplies through every document that reaches an item under a page — the count
837/// rules multiply down a nested path — so it is the constant [`NODE_COUNT_LIMIT`] is most
838/// sensitive to. `tests/node_count.rs` is what holds the pair together: it recomputes
839/// every document under these constants and fails naming any that reaches the limit, so
840/// raising this is caught there rather than by GitHub.
841const NESTED_PAGE_SIZE: u32 = 50;
842/// How many of one issue's board memberships are read when an issue is reached directly.
843///
844/// An issue reached through a search or through its own node id carries its board half in
845/// `Issue.projectItems`, and only the entry for *this* board is read. This connection sits
846/// under a page of issues, so every point of it multiplies through the whole document and
847/// is paid for whether or not any issue is on a second board — which is why it is
848/// deliberately far smaller than [`NESTED_PAGE_SIZE`].
849///
850/// **Three, because what a page misses is now recovered rather than refused**, and the
851/// recovery is what the value is chosen against. An issue whose entry for this board sits
852/// past this page costs one further request — [`graphql::ISSUE_BOARD_ITEMS`], resumed from
853/// that page's own cursor — so the value trades a bound every read pays for a request only
854/// a multi-board issue pays. At one, a deployment whose issues commonly sit on two or more
855/// boards would pay that request *per issue*, which is order N against the one page per
856/// hundred issues a read costs today. At three it is only reached by an issue on four or
857/// more boards at once, which keeps the recovery path exceptional rather than routine for
858/// a plausible deployment.
859const BOARD_ITEMS_PAGE_SIZE: u32 = 3;
860/// How many carriers of one copy origin one page of [`graphql::ORIGIN_LOOKUP`] asks each of
861/// its two connections for.
862///
863/// An origin names one item, so the answer an origin lookup expects is one carrier, and a
864/// second is a duplicate a copy already takes the first of. Both connections are walked to
865/// exhaustion whatever this is, so it decides how many requests an unusual answer costs and
866/// never what the answer is. It is small because every point of it is paid on every lookup,
867/// and a copy makes one lookup per item it has no link for: at three, ten lookups cost fewer
868/// worst-case nodes than the one whole-board read they replaced.
869const ORIGIN_PAGE_SIZE: u32 = 3;
870/// How many carriers of each origin the batched [`graphql::ORIGIN_LOOKUPS`] asks each of its two
871/// connections for: one, the one carrier an origin names.
872///
873/// A second carrier still shows: the page then says there is more, and that origin is left to
874/// its own [`graphql::ORIGIN_LOOKUP`], which walks every page at `ORIGIN_PAGE_SIZE` — so a
875/// duplicate is found exactly as before, by the lookup that reads all of them. The feasibility
876/// spike (`board-copy-gaps-2026-10-24-spike-feasibility-report`) priced the batch of ten
877/// origins at two points with a first page of three and at one with a first page of one.
878const ORIGIN_LOOKUPS_PAGE_SIZE: u32 = 1;
879
880/// How many of one project's sub-issues one [`graphql::SUB_ISSUES`] page asks for: the most
881/// one point buys, since every row carries six connections GitHub charges for once per row.
882/// `session-cost.md` derives it; `tests/point_cost.rs` prices the document at one point and
883/// fails if one row more would still be priced at one.
884pub const MEMBER_PAGE_SIZE: u32 = 23;
885
886pub use github_graphql_node_count::{NodeCountError, Variables};
887
888/// The largest value this source can bind to each page-size variable its documents name.
889///
890/// Every `first:` in [`graphql`] reads one of these seven, and each is capped at the
891/// constant above it wherever a caller's own limit could reach it — `$first` at
892/// [`MAX_PAGE_SIZE`], `$commentFirst` at [`MAX_PAGE_SIZE`], `$nestedFirst` at `NESTED_PAGE_SIZE`, `$boardItems` at
893/// `BOARD_ITEMS_PAGE_SIZE`, `$originFirst` at `ORIGIN_PAGE_SIZE`, `$lookupFirst` at
894/// `ORIGIN_LOOKUPS_PAGE_SIZE`, `$memberFirst` at [`MEMBER_PAGE_SIZE`]. So this is the worst case a caller can drive this source to,
895/// not one configuration of it, which is what makes a bound computed under it a bound on
896/// every read.
897pub fn largest_page_sizes() -> Variables {
898 let mut sizes = Variables::from([
899 ("first".to_owned(), MAX_PAGE_SIZE),
900 ("commentFirst".to_owned(), MAX_PAGE_SIZE),
901 ("nestedFirst".to_owned(), NESTED_PAGE_SIZE),
902 ("boardItems".to_owned(), BOARD_ITEMS_PAGE_SIZE),
903 ("originFirst".to_owned(), ORIGIN_PAGE_SIZE),
904 ("lookupFirst".to_owned(), ORIGIN_LOOKUPS_PAGE_SIZE),
905 ("memberFirst".to_owned(), MEMBER_PAGE_SIZE),
906 ]);
907 // Each slot of the batched search pages at most what one search does.
908 for slot in 0..SEARCH_BATCH {
909 sizes.insert(format!("first{slot}"), SEARCH_PAGE_SIZE);
910 }
911 for slot in 0..SEARCH_BATCH_ORIGINS {
912 sizes.insert(format!("itemsFirst{slot}"), SEARCH_PAGE_SIZE);
913 }
914 sizes
915}
916
917/// The most nodes `document` could be asked to return, by GitHub's published rules.
918///
919/// Computed offline from the document's own text under [`largest_page_sizes`] — no
920/// network, no credential and no schema — by
921/// [`github_graphql_node_count::node_count`], which is where the rules themselves live.
922/// A document at or above [`NODE_COUNT_LIMIT`] is one GitHub refuses before executing, so
923/// this is what a check holds every document in [`graphql::DOCUMENTS`] below.
924///
925/// # Errors
926///
927/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
928/// no single operation, or binds a page size this source does not name — each of which is
929/// a defect in the document rather than a number.
930pub fn worst_case_node_count(document: &str) -> Result<u64, NodeCountError> {
931 node_count(document, &largest_page_sizes())
932}
933
934/// The most rate-limit points one call of `document` could spend, by GitHub's published
935/// rules.
936///
937/// Computed offline from the document's own text under [`largest_page_sizes`] — no
938/// network, no credential and no schema — by
939/// [`github_graphql_node_count::point_cost`], which is where the rules themselves live.
940/// This is `cost`, metered **per hour** against the allowance one credential shares across
941/// everything it does; it is not `nodeCount`, which is [`worst_case_node_count`] and is
942/// bounded per query by [`NODE_COUNT_LIMIT`]. There is no per-call ceiling to hold this
943/// under, so what `tests/point_cost.rs` does with it is pin every document in
944/// [`graphql::DOCUMENTS`] at what it costs, and the credentialed lane reconciles those
945/// figures against GitHub's own reported `cost`.
946///
947/// # Errors
948///
949/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
950/// no single operation, or binds a page size this source does not name — each of which is
951/// a defect in the document rather than a number.
952pub fn worst_case_point_cost(document: &str) -> Result<u64, NodeCountError> {
953 github_graphql_node_count::point_cost(document, &largest_page_sizes())
954}
955
956/// The rate-limit points one call of `document` spends under `variables`, by GitHub's published
957/// rules: [`worst_case_point_cost`] is this under [`largest_page_sizes`], and a request this
958/// source sent is priced by it under the page sizes that request really bound — what GitHub
959/// charges the request, since it charges every connection at the page size asked for.
960///
961/// # Errors
962///
963/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
964/// no single operation, or binds a page size `variables` does not name.
965pub fn point_cost(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
966 github_graphql_node_count::point_cost(document, variables)
967}
968
969/// The most nodes `document` could be asked to return under `variables`.
970///
971/// [`worst_case_node_count`] is this under [`largest_page_sizes`], and the accounting in
972/// [`accounting`] is this under the bindings one request really sent — one spelling of the
973/// calculation, so a bound checked offline and a cost recorded at run time cannot come to
974/// disagree. The rules themselves live in [`github_graphql_node_count::node_count`].
975///
976/// # Errors
977///
978/// Returns the calculation's own [`NodeCountError`] when `document` does not parse, holds
979/// no single operation, or binds a page size `variables` does not name.
980pub fn node_count(document: &str, variables: &Variables) -> Result<u64, NodeCountError> {
981 github_graphql_node_count::node_count(document, variables)
982}
983
984/// `variables` with the page sizes and flags a token twin's inline issue selection binds,
985/// at a read's page sizes.
986fn token_variables(mut variables: Value) -> Value {
987 if let Some(object) = variables.as_object_mut() {
988 object.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
989 object.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
990 object.insert("duplicates".to_owned(), json!(true));
991 }
992 variables
993}
994
995/// What a caller's request gate is told of one GraphQL request: it draws on GitHub's `graphql`
996/// resource, it creates content exactly when it creates an issue or a comment,
997/// and it costs what GitHub's published rules price it at under the page sizes it binds.
998fn gated_graphql(document: &str, variables: &Value) -> onetaskgraph_plugin_api::GatedRequest {
999 onetaskgraph_plugin_api::GatedRequest {
1000 resource: "graphql".to_owned(),
1001 content_creating: creates_content(document),
1002 cost_hint: point_cost(document, &accounting::bindings(variables)).ok(),
1003 }
1004}
1005
1006/// Whether `document` creates content GitHub's secondary limits meter as such: an issue or a
1007/// comment. `creates_content_tests` classifies every mutation root `graphql::DOCUMENTS` sends,
1008/// so a root added later fails there until it is said whether it creates content.
1009fn creates_content(document: &str) -> bool {
1010 is_mutation(document)
1011 && ["createIssue(", "addComment("]
1012 .iter()
1013 .any(|root| document.contains(root))
1014}
1015
1016#[cfg(test)]
1017mod creates_content_tests {
1018 use super::{creates_content, graphql};
1019 use std::collections::BTreeMap;
1020
1021 /// Every root field a mutation document selects at its top level, aliases resolved.
1022 fn roots(document: &str) -> Vec<String> {
1023 let body = &document[document.find('{').expect("a selection set") + 1..];
1024 let (mut braces, mut parens, mut roots) = (0_usize, 0_usize, Vec::new());
1025 let mut chars = body.char_indices().peekable();
1026 while let Some((at, c)) = chars.next() {
1027 match c {
1028 '{' => braces += 1,
1029 '}' if braces == 0 => break,
1030 '}' => braces -= 1,
1031 '(' => parens += 1,
1032 ')' => parens -= 1,
1033 // A directive's name is no field.
1034 '@' => {
1035 while chars
1036 .peek()
1037 .is_some_and(|&(_, n)| n.is_ascii_alphanumeric() || n == '_')
1038 {
1039 chars.next();
1040 }
1041 }
1042 c if braces == 0 && parens == 0 && (c.is_ascii_alphabetic() || c == '_') => {
1043 let mut end = at + c.len_utf8();
1044 while let Some(&(next, n)) = chars.peek() {
1045 if !(n.is_ascii_alphanumeric() || n == '_') {
1046 break;
1047 }
1048 end = next + n.len_utf8();
1049 chars.next();
1050 }
1051 let rest = body[end..].trim_start();
1052 // An alias names the root after its colon, which this loop reads next.
1053 if !rest.starts_with(':') {
1054 roots.push(body[at..end].to_owned());
1055 }
1056 }
1057 _ => {}
1058 }
1059 }
1060 roots
1061 }
1062
1063 #[test]
1064 fn every_mutation_root_sent_is_classified_and_creates_content_agrees() {
1065 // Whether each root creates an issue or a comment: what GitHub's
1066 // secondary limits meter as content creation.
1067 let classified = BTreeMap::from([
1068 ("addBlockedBy", false),
1069 ("addComment", true),
1070 ("addProjectV2ItemById", false),
1071 ("addRelatesTo", false),
1072 ("addSubIssue", false),
1073 ("clearProjectV2ItemFieldValue", false),
1074 ("closeIssue", false),
1075 ("createIssue", true),
1076 ("createProjectV2Field", false),
1077 ("deleteIssue", false),
1078 ("deleteIssueComment", false),
1079 ("removeBlockedBy", false),
1080 ("removeRelatesTo", false),
1081 ("removeSubIssue", false),
1082 ("updateIssue", false),
1083 ("updateIssueComment", false),
1084 ("updateProjectV2DraftIssue", false),
1085 ("updateProjectV2Field", false),
1086 ("updateProjectV2ItemFieldValue", false),
1087 ]);
1088 let (mut seen, mut unclassified) = (BTreeMap::new(), std::collections::BTreeSet::new());
1089 for (document, _) in graphql::DOCUMENTS {
1090 if !super::is_mutation(document) {
1091 assert!(!creates_content(document), "a query: {document}");
1092 continue;
1093 }
1094 let roots = roots(document);
1095 assert!(!roots.is_empty(), "no root read: {document}");
1096 for root in &roots {
1097 match classified.get(root.as_str()) {
1098 Some(&creates) => _ = seen.insert(root.clone(), creates),
1099 None => _ = unclassified.insert(root.clone()),
1100 }
1101 }
1102 let expected = roots
1103 .iter()
1104 .any(|root| classified.get(root.as_str()) == Some(&true));
1105 assert_eq!(creates_content(document), expected, "{document}");
1106 }
1107 assert!(
1108 unclassified.is_empty(),
1109 "say whether each of these mutation roots creates content: {unclassified:?}"
1110 );
1111 let unsent: Vec<_> = classified
1112 .keys()
1113 .filter(|root| !seen.contains_key(**root))
1114 .collect();
1115 assert!(unsent.is_empty(), "classified but never sent: {unsent:?}");
1116 }
1117}
1118
1119/// The input members a mutation names the issue or board item it writes by.
1120const WRITTEN_NAMES: [&str; 4] = ["id", "issueId", "subjectId", "itemId"];
1121
1122tokio::task_local! {
1123 /// The source a targeted update is running on, by its address, while it runs: what has its
1124 /// mutations sent as the twins selecting the whole issue, so the update answers the version
1125 /// its own last response shows (see `GitHubProjectsSource::written_tokens`).
1126 static SPELLING: usize;
1127}
1128
1129/// The issue-title prefix that makes a board issue a document.
1130///
1131/// A GitHub Projects board has no document type — it holds issues — so the discriminator
1132/// is the title, and this is the whole of it: an issue whose title begins with these bytes
1133/// is a document and every other issue is the task or project the sub-issue rule makes it.
1134///
1135/// It is spelled **once**, here, and read rather than restated everywhere else — including
1136/// by the shared journeys, which take it from this constant so a board fixture cannot
1137/// drift from what this source reads. `docs/metadata.md` records the two consequences that
1138/// are not obvious from the bytes: the reported title has this prefix taken off, exactly
1139/// as the body's metadata slot is taken off `content`, and this prefix is read *before*
1140/// the sub-issue rule, so a design issue with no sub-issues is never an empty project.
1141pub const DESIGN_TITLE_PREFIX: &str = "DESIGN: ";
1142
1143/// The most characters GitHub stores in one issue's body: a longer one is refused as
1144/// `body is too long (maximum is 65536 characters)`.
1145pub const BODY_LIMIT: u64 = 65_536;
1146
1147/// The address a new upload's URL is spelled at, as GitHub serves a user attachment: what the
1148/// size of a body is measured with before an asset of it is uploaded, a UUID long.
1149const PREDICTED_ATTACHMENT_URL: &str =
1150 "https://github.com/user-attachments/assets/00000000-0000-0000-0000-000000000000";
1151
1152/// Exact GraphQL query documents issued by this plugin.
1153///
1154/// Keeping the production documents here lets the pinned-schema test validate the same
1155/// bytes that are sent to GitHub, rather than a test-only copy which could drift
1156/// independently. [`STATUS_OPTIONS_UPDATE`] is the sole document that may rewrite a board
1157/// field, and its guarded caller always supplies the complete existing option set with ids.
1158pub mod graphql {
1159 /// The board half of one item: the field values every document here reads it from.
1160 ///
1161 /// A macro for the same reason [`board_issue!`] below is one, a level further in. This
1162 /// selection is needed by that fragment, by [`BOARD`] under the board's own `items`,
1163 /// and by [`ISSUE_BOARD_ITEMS`] under a membership walk — and all three have to produce
1164 /// *the same value*, because
1165 /// [`GitHubProjectsSource::resolve`](super::GitHubProjectsSource) reads them through
1166 /// one path. Three spellings of it is what would drift, so there is one.
1167 ///
1168 /// The `Status` option and this source's own origin text field are the whole of it. It
1169 /// selects no `ProjectV2ItemFieldLabelValue`: GitHub derives that field from the item's
1170 /// content, so it holds nothing the content's own `labels` do not already say, and it
1171 /// would sit a label connection two page sizes deep.
1172 macro_rules! board_item_values {
1173 () => {
1174 r#"fieldValues(first:$nestedFirst){nodes{
1175 ... on ProjectV2ItemFieldSingleSelectValue{name field{
1176 ... on ProjectV2SingleSelectField{id name options{id name}}
1177 }}
1178 ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{id name}}}
1179 }pageInfo{hasNextPage}}"#
1180 };
1181 }
1182
1183 /// The variable every document reading an issue declares for the relationship events its
1184 /// change token counts, with its value as the default, so no caller binds it.
1185 ///
1186 /// A variable rather than a literal list because every argument a production document
1187 /// passes is a declared variable, which `tests/schema.rs` holds them to, and every member of
1188 /// its default to the pinned enum. Its default is the six event types GitHub records a
1189 /// relationship added or removed with: a dependency on either end, as `blockedBy` and
1190 /// `blocking`, so one a person makes from the far end moves this end's count too; and a
1191 /// project membership on the task, as its parent, which GitHub records there whichever
1192 /// issue the move was made from. A sub-issue's events on its parent are not counted: a
1193 /// project carries no task token, and a copy writes nothing of a task its own sub-issues
1194 /// decide. [`super::change_token`] says why the count is in the token.
1195 macro_rules! relationship_events_variable {
1196 () => {
1197 ",$relationshipEvents:[IssueTimelineItemsItemType!]=[BLOCKED_BY_ADDED_EVENT,BLOCKED_BY_REMOVED_EVENT,BLOCKING_ADDED_EVENT,BLOCKING_REMOVED_EVENT,PARENT_ISSUE_ADDED_EVENT,PARENT_ISSUE_REMOVED_EVENT]"
1198 };
1199 }
1200
1201 /// Everything this source reads about one issue, wherever it reaches that issue.
1202 ///
1203 /// A macro rather than a constant so the three documents below can `concat!` it: one
1204 /// spelling of these fields is what makes an issue read through the board-scoped
1205 /// search, through its own node id, and through its project's sub-issue relationship
1206 /// resolve to *the same* item, which is the whole of what
1207 /// [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource) relies on.
1208 ///
1209 /// `projectItems` is what carries the board half of an issue: the board item's own id
1210 /// and the [`board_item_values!`] above — the `Status` option and this source's origin
1211 /// text field — that a `ProjectV2.items` read used to carry. It is asked for on the
1212 /// issue rather than on the board, which is what makes the cost of a read proportional
1213 /// to what was asked for instead of to the board's size.
1214 ///
1215 /// It carries a *page* of that connection, at `BOARD_ITEMS_PAGE_SIZE`, and its
1216 /// `endCursor` is what [`ISSUE_BOARD_ITEMS`] resumes from when this board's entry is
1217 /// not on that page: a page here is where the search for the entry starts rather than
1218 /// where it ends.
1219 ///
1220 /// It does **not** select the board's `Labels` field value, and that is the whole of
1221 /// what keeps the three documents below under [`NODE_COUNT_LIMIT`](super::NODE_COUNT_LIMIT):
1222 /// a label connection there sits under `fieldValues` under `projectItems` under a page
1223 /// of issues, spending `$nestedFirst` twice down one path, and took
1224 /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] to 2,556,100 nodes against a limit of 500,000.
1225 /// No label is lost — this is a fragment `on Issue`, whose own `labels` are selected
1226 /// above, and that connection is where every label this source reports comes from. No
1227 /// document in this module selects the board field any longer, [`BOARD`] included; the
1228 /// module documentation records why nothing it could have held is lost.
1229 macro_rules! board_issue {
1230 () => {
1231 concat!(
1232 r#" fragment BoardIssue on Issue{"#,
1233 board_issue_fields!(),
1234 "}"
1235 )
1236 };
1237 }
1238
1239 /// What [`board_issue!`] selects of an issue, written out where a document selects it
1240 /// inline rather than through the fragment.
1241 macro_rules! board_issue_fields {
1242 () => {
1243 concat!(
1244 r#"__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}
1245 labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}
1246 projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1247 "#,
1248 board_item_values!(),
1249 r#"}pageInfo{hasNextPage endCursor}}"#
1250 )
1251 };
1252 }
1253
1254 /// One page of a repository's issues, newest first, each with when it was created and its
1255 /// body: what a retried copy reads to find the issue its earlier attempt created, by the
1256 /// create key in that body's metadata slot — never through search, whose index lags.
1257 pub const ISSUES_BY_CREATION: &str = "query($owner:String!,$name:String!,$first:Int!,$after:String){repository(owner:$owner,name:$name){issues(first:$first,after:$after,orderBy:{field:CREATED_AT,direction:DESC}){nodes{id createdAt body}pageInfo{hasNextPage endCursor}}}}";
1258 /// Every issue of one board, found by a search scoped to that board.
1259 ///
1260 /// This is how the projects a board holds are listed, and it selects no `items`
1261 /// connection on `ProjectV2`: the board is a *qualifier of the search* rather than a
1262 /// container walked page by page, so nothing nested inside a board item is paid for.
1263 /// Which of the issues it returns is a project is then read off `parent` — GitHub
1264 /// accepts `-has:parent` as a search qualifier and silently ignores it, so the
1265 /// discriminator has to be applied to the field, which is a scalar on the issue and
1266 /// costs nothing.
1267 pub const SEARCH_ISSUES: &str = concat!(
1268 r#"query($search:String!,$type:SearchType!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1269 relationship_events_variable!(),
1270 r#"){
1271 search(query:$search,type:$type,first:$first,after:$after){
1272 pageInfo{hasNextPage endCursor}
1273 nodes{__typename ...BoardIssue}
1274 }
1275 }"#,
1276 board_issue!()
1277 );
1278
1279 /// What a dependency read selects of each far end: enough to say which kind of item it
1280 /// is, its body included for the kind marker.
1281 macro_rules! related_issue {
1282 () => {
1283 " fragment Related on Issue{id title body parent{id} subIssuesSummary{total}}"
1284 };
1285 }
1286
1287 /// One issue by its own node id, which is what a qualified id names here — with what a
1288 /// write of it needs and the issue does not carry in `board_issue!`: the field
1289 /// definitions of the boards it sits on, and the far ends of its `blockedBy`.
1290 ///
1291 /// Strongly consistent, unlike the search above: GitHub's issue search is an index and
1292 /// answers a write made moments ago with the value from before it, and resolving a node
1293 /// id does not.
1294 ///
1295 /// **Why those two ride here and not on the fragment.** A copy or an update of an item
1296 /// reads it by its own id, and with them that one read answers everything the write
1297 /// needs: which option ids the board's `Status` and `Priority` fields hold — so no
1298 /// [`BOARD_FIELDS`] — and which issues block it, with each one's kind — so no
1299 /// [`ISSUE_DEPENDENCIES`]. On `board_issue!` they would sit under the hundred-issue
1300 /// pages of [`SEARCH_ISSUES`] and [`SUB_ISSUES`], multiplying both documents' price. Here
1301 /// they sit under one item, and this read is still one point.
1302 pub const ISSUE: &str = concat!(
1303 r#"query($id:ID!,$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1304 relationship_events_variable!(),
1305 r#"){
1306 node(id:$id){__typename ...BoardIssue ... on Issue{
1307 boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
1308 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1309 ... on ProjectV2Field{__typename id name dataType}
1310 }pageInfo{hasNextPage}}}}}
1311 blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
1312 }}
1313 }"#,
1314 board_issue!(),
1315 related_issue!()
1316 );
1317
1318 /// One document by its own node id, as [`ISSUE`] reads one, with the project it is filed
1319 /// under and that project's members beside it: the project issue whole, and a page of its
1320 /// sub-issues, each as [`SUB_ISSUES`] carries one but with no page of what blocks it.
1321 ///
1322 /// What a guarded write of a document's metadata reads, and what reading a document by its
1323 /// id is: a write to a board the boundary screens is held to who may read the document,
1324 /// which is the project's and every member's classification as much as its own, and here
1325 /// the one request that holds the version the write is compared against answers all of it.
1326 /// Its members carry no edges, which nothing classifying them reads.
1327 pub const DOCUMENT_IN_PROJECT: &str = concat!(
1328 r#"query($id:ID!,$first:Int!,$memberFirst:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1329 relationship_events_variable!(),
1330 r#"){
1331 node(id:$id){__typename ...BoardIssue ... on Issue{
1332 boards:projectItems(first:$boardItems){nodes{project{id number fields(first:$nestedFirst){nodes{
1333 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1334 ... on ProjectV2Field{__typename id name dataType}
1335 }pageInfo{hasNextPage}}}}}
1336 blockedBy(first:$first){nodes{...Related}pageInfo{hasNextPage endCursor}}
1337 project:parent{__typename ...BoardIssue
1338 subIssues(first:$memberFirst){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}
1339 }
1340 }}
1341 }"#,
1342 board_issue!(),
1343 related_issue!()
1344 );
1345
1346 /// One project's tasks: the sub-issues of the issue that project is, each with a page of
1347 /// what blocks it.
1348 ///
1349 /// Paged at `$memberFirst` — [`MEMBER_PAGE_SIZE`](super::MEMBER_PAGE_SIZE), the most rows
1350 /// one point buys — rather than at `$first`, because every row carries six connections and
1351 /// a hundred-row page cost six points to list a project of ten.
1352 ///
1353 /// The work this costs is the project's own size. Nothing about it grows as the board
1354 /// gains projects, or as those projects gain tasks.
1355 ///
1356 /// **Why `blockedBy` rides here and on no other page of issues.** What reads a project's
1357 /// tasks reads their edges next — `project graph` draws them, a copy carries them — and
1358 /// without them here that is one [`ISSUE_DEPENDENCIES`] per task, so the requests a graph
1359 /// costs grow with its tasks rather than with the pages of them. Carried here, a task
1360 /// blocked by no more than `$nestedFirst` issues answers its forward edges from this read,
1361 /// exactly as an [`ISSUE`] read of it does, and only one blocked by more is asked again.
1362 /// It adds a connection under each issue of the page — one rate-limit point per page,
1363 /// and `$nestedFirst` nodes per issue — and is kept off [`SEARCH_ISSUES`], whose pages
1364 /// answer questions that never read an edge.
1365 ///
1366 /// **The project issue itself rides here too**, with the page of what blocks it, because
1367 /// the reader of a project's tasks reads the project next: a copy writing the project reads
1368 /// it and its edges before it writes them. Carried on the request that already names the
1369 /// project, the first page answers that read and the dependency read after it, at the
1370 /// state GitHub answered in this command, rather than spending one more read on an item
1371 /// the cache's token cannot vouch for whole. Each sub-issue is kept the same way, so a
1372 /// copy's read of a task this listing carried is answered by it rather than sent again.
1373 /// Only a copy's read-before-write takes them; every other read by id reads GitHub.
1374 pub const SUB_ISSUES: &str = concat!(
1375 r#"query($id:ID!,$memberFirst:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1376 relationship_events_variable!(),
1377 r#"){
1378 node(id:$id){__typename ...BoardIssue
1379 ... on Issue{blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1380 subIssues(first:$memberFirst,after:$after){
1381 pageInfo{hasNextPage endCursor}
1382 nodes{__typename ...BoardIssue ... on Issue{
1383 blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}
1384 }}
1385 }}}
1386 }"#,
1387 board_issue!(),
1388 related_issue!()
1389 );
1390
1391 /// Everything this source reads about one issue comment, wherever it reaches one.
1392 ///
1393 /// A macro for the reason [`board_issue!`] is one: a comment listed, a comment just added
1394 /// and a comment just edited are handed to one mapper, so they are selected by one
1395 /// spelling. `author` is `Actor`, which GitHub answers `null` for an account that no
1396 /// longer exists, and `login` is the one member every kind of actor carries; `__typename`
1397 /// says whether it is a `Bot`, whose `login` GitHub's own pages spell with `[bot]` after it.
1398 macro_rules! issue_comment {
1399 () => {
1400 "id author{__typename login} createdAt updatedAt body url"
1401 };
1402 }
1403
1404 /// What a read of the board's own `items` selects of each item's content.
1405 ///
1406 /// A macro for the reason [`board_item_values!`] is one: [`BOARD`] and [`ORIGIN_LOOKUP`]
1407 /// both walk `ProjectV2.items` and hand each item to one resolver, so they select its
1408 /// content by one spelling.
1409 macro_rules! board_item_content {
1410 () => { board_item_content!("") };
1411 ($comments:expr) => {
1412 concat!(r#" content{
1413 ... 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}}"#, $comments, r#"}
1414 ... on PullRequest{__typename id}
1415 ... on DraftIssue{__typename id title body createdAt updatedAt}
1416 }"#)
1417 };
1418 }
1419
1420 macro_rules! board_listing {
1421 ($variables:expr, $comments:expr) => { concat!(
1422 r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!,$duplicates:Boolean!"#,
1423 relationship_events_variable!(), $variables,
1424 r#"){
1425 owner:repositoryOwner(login:$owner){
1426 ... on ProjectV2Owner{projectV2(number:$number){...Board}}
1427 }
1428 } fragment Board on ProjectV2 { id title
1429 fields(first:$nestedFirst){nodes{
1430 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1431 ... on ProjectV2Field{__typename id name dataType}
1432 }pageInfo{hasNextPage}}
1433 items(first:$first,after:$after){nodes{id updatedAt "#,
1434 board_item_values!(),
1435 board_item_content!($comments),
1436 r#"} pageInfo{hasNextPage endCursor}}
1437 }"#
1438 ) };
1439 }
1440
1441 /// Reads the board's fields and one page of its items.
1442 pub const BOARD: &str = board_listing!("", "");
1443
1444 /// A board page carrying each issue's first comment page in the same request.
1445 pub const BOARD_WITH_COMMENTS: &str = concat!(
1446 board_listing!(
1447 ",$commentFirst:Int!",
1448 concat!(
1449 "comments(first:$commentFirst){nodes{",
1450 issue_comment!(),
1451 "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}"
1452 )
1453 ),
1454 related_issue!()
1455 );
1456
1457 /// Every carrier of one copy origin, by two reads in one request, and nothing else of
1458 /// the board.
1459 ///
1460 /// **`originItems`** is the board's own items narrowed by its own field filter —
1461 /// `ProjectV2.items(query:)`, which GitHub's schema declares as "Search query for
1462 /// filtering items" — to those whose `onetaskgraph.origin` text field holds the
1463 /// qualified id, quoted. It reads the field every carrier already holds, whichever release
1464 /// wrote it, and matches it exactly: measured on 2026-09-29 against a 394-item board,
1465 /// the quoted, the unquoted and the bare-value spellings each returned exactly the one
1466 /// carrier and a prefix of the value returned none. It is `ProjectV2.items`, so it lags a
1467 /// fresh `addProjectV2ItemById` the way that connection does.
1468 ///
1469 /// **`search`** is the board-scoped issue search for the same id as a quoted phrase in
1470 /// the body, which is where this source mirrors the origin into its metadata slot. GitHub
1471 /// indexes that comment, and the index catches up with a write in a second or two rather
1472 /// than in minutes, so it finds a carrier another process wrote that the first read is
1473 /// still behind on.
1474 ///
1475 /// Each connection pages at `$originFirst`, its own small size — see `ORIGIN_PAGE_SIZE`
1476 /// — and resumes from its own cursor; a connection already walked to its end is resumed
1477 /// from its last cursor, which answers an empty page. Every candidate either read returns
1478 /// is confirmed against its own origin field before it is reported, so a token match of
1479 /// the search or anything else the filter admits never is.
1480 ///
1481 /// The root is aliased `originItems` rather than `owner`, so nothing counting the board's
1482 /// own whole reads counts this one among them.
1483 pub const ORIGIN_LOOKUP: &str = concat!(
1484 r#"query($owner:String!,$number:Int!,$filter:String!,$search:String!,$type:SearchType!,$originFirst:Int!,$itemsAfter:String,$searchAfter:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
1485 relationship_events_variable!(),
1486 r#"){
1487 originItems:repositoryOwner(login:$owner){
1488 ... on ProjectV2Owner{projectV2(number:$number){
1489 items(first:$originFirst,after:$itemsAfter,query:$filter){nodes{id updatedAt "#,
1490 board_item_values!(),
1491 board_item_content!(),
1492 r#"} pageInfo{hasNextPage endCursor}}
1493 }}
1494 }
1495 search(query:$search,type:$type,first:$originFirst,after:$searchAfter){
1496 pageInfo{hasNextPage endCursor}
1497 nodes{__typename ...BoardIssue}
1498 }
1499 }"#,
1500 board_issue!()
1501 );
1502
1503 /// Every closed item of the board, by the board's own field filter — what
1504 /// `task status reconcile` reads, and nothing else of the board.
1505 ///
1506 /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1507 /// `is:closed` alone, so a board whose open items are most of it is not read whole to find
1508 /// the closed ones. It is narrowed rather than trusted: every item it answers is confirmed
1509 /// closed, with a reason and a card that contradict each other, from the item node it
1510 /// already carries, so a filter that also let open items through would cost reads and
1511 /// write nothing wrong.
1512 ///
1513 /// The board's own id and field definitions ride along, as [`BOARD`] carries them, so the
1514 /// option writes that follow need no read of the board. The root is aliased `closedItems`
1515 /// rather than `owner`, so nothing counting the board's own whole reads counts this one
1516 /// among them.
1517 pub const CLOSED_ITEMS: &str = concat!(
1518 r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1519 relationship_events_variable!(),
1520 r#"){
1521 closedItems:repositoryOwner(login:$owner){
1522 ... on ProjectV2Owner{projectV2(number:$number){id
1523 fields(first:$nestedFirst){nodes{
1524 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1525 ... on ProjectV2Field{__typename id name dataType}
1526 }pageInfo{hasNextPage}}
1527 items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1528 board_item_values!(),
1529 board_item_content!(),
1530 r#"} pageInfo{hasNextPage endCursor}}
1531 }}
1532 }
1533 }"#
1534 );
1535
1536 /// Every open item of the board, drafts included, by the board's own field filter — what a
1537 /// task listing whose every status category is open reads, and nothing else of the board.
1538 ///
1539 /// **`ProjectV2.items(query:)` narrowed by `$filter`**, which this source binds to
1540 /// `is:open` alone. GitHub's filter reads the issue's state, not its card, so it answers
1541 /// every open issue whatever column its card sits in — an open issue under a terminal card,
1542 /// and one under an option no mapping names, among them — and every draft, which has no
1543 /// state and is never closed; measured on the real board by `spike-store-defects`, it read
1544 /// 466 open items in five requests where the whole board's walk and its issue search took
1545 /// thirty-one. Each item's category is still confirmed in process from its own node, so a
1546 /// filter that let a closed item through would cost a read and keep nothing it should not.
1547 ///
1548 /// The board's own id and field definitions ride along, as [`CLOSED_ITEMS`] carries them,
1549 /// so a status write after it needs no read of the board's fields. The root is aliased
1550 /// `openItems`, so nothing counting the board's whole reads counts this one among them.
1551 pub const OPEN_ITEMS: &str = concat!(
1552 r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$filter:String!,$nestedFirst:Int!,$duplicates:Boolean!"#,
1553 relationship_events_variable!(),
1554 r#"){
1555 openItems:repositoryOwner(login:$owner){
1556 ... on ProjectV2Owner{projectV2(number:$number){id
1557 fields(first:$nestedFirst){nodes{
1558 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1559 ... on ProjectV2Field{__typename id name dataType}
1560 }pageInfo{hasNextPage}}
1561 items(first:$first,after:$after,query:$filter){nodes{id updatedAt "#,
1562 board_item_values!(),
1563 board_item_content!(),
1564 r#"} pageInfo{hasNextPage endCursor}}
1565 }}
1566 }
1567 }"#
1568 );
1569
1570 /// One alias of [`ISSUES_BY_REFERENCE`]: the issue `$owner<n>/$name<n>#$number<n>` names.
1571 macro_rules! reference_alias {
1572 ($n:literal) => {
1573 concat!(
1574 "\n r",
1575 stringify!($n),
1576 ":repository(owner:$owner",
1577 stringify!($n),
1578 ",name:$name",
1579 stringify!($n),
1580 "){issue(number:$number",
1581 stringify!($n),
1582 "){...HeldIssue}}"
1583 )
1584 };
1585 }
1586
1587 /// [`REFERENCE_BATCH`](super::REFERENCE_BATCH) issues at once, each by its repository and
1588 /// number — the one read `task status complete` makes of a source, and nothing else of
1589 /// the board: no `items`, no search and no project read.
1590 ///
1591 /// **Its own fragment, lighter than `board_issue!`, and that is what makes fifty
1592 /// references one point.** It selects no labels, and of each board membership only the
1593 /// `Status` value, by name, with `fieldValueByName` — so each alias asks GitHub for one
1594 /// connection, its page of memberships, where the whole fragment asks for five. What a
1595 /// completion writes is a card and, at most, the issue's state, so the labels and the other
1596 /// field values it leaves out are never what it needs; an item read this way is held for
1597 /// that write alone and never answers another read. An issue whose entry for this board is
1598 /// past its first page of memberships is walked with [`ISSUE_BOARD_ITEMS`], exactly as
1599 /// every other read of an issue recovers one.
1600 ///
1601 /// Fixed-size, as [`ISSUE_DETAILS`] is, so there is one document to price: a batch of
1602 /// fewer references binds the slots it has none for to its last one.
1603 pub const ISSUES_BY_REFERENCE: &str = concat!(
1604 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!"#,
1605 relationship_events_variable!(),
1606 r#"){"#,
1607 reference_alias!(0),
1608 reference_alias!(1),
1609 reference_alias!(2),
1610 reference_alias!(3),
1611 reference_alias!(4),
1612 reference_alias!(5),
1613 reference_alias!(6),
1614 reference_alias!(7),
1615 reference_alias!(8),
1616 reference_alias!(9),
1617 reference_alias!(10),
1618 reference_alias!(11),
1619 reference_alias!(12),
1620 reference_alias!(13),
1621 reference_alias!(14),
1622 reference_alias!(15),
1623 reference_alias!(16),
1624 reference_alias!(17),
1625 reference_alias!(18),
1626 reference_alias!(19),
1627 reference_alias!(20),
1628 reference_alias!(21),
1629 reference_alias!(22),
1630 reference_alias!(23),
1631 reference_alias!(24),
1632 reference_alias!(25),
1633 reference_alias!(26),
1634 reference_alias!(27),
1635 reference_alias!(28),
1636 reference_alias!(29),
1637 reference_alias!(30),
1638 reference_alias!(31),
1639 reference_alias!(32),
1640 reference_alias!(33),
1641 reference_alias!(34),
1642 reference_alias!(35),
1643 reference_alias!(36),
1644 reference_alias!(37),
1645 reference_alias!(38),
1646 reference_alias!(39),
1647 reference_alias!(40),
1648 reference_alias!(41),
1649 reference_alias!(42),
1650 reference_alias!(43),
1651 reference_alias!(44),
1652 reference_alias!(45),
1653 reference_alias!(46),
1654 reference_alias!(47),
1655 reference_alias!(48),
1656 reference_alias!(49),
1657 "\n }",
1658 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}
1659 projectItems(first:$boardItems){nodes{id updatedAt project{id number}
1660 status:fieldValueByName(name:$statusField){... on ProjectV2ItemFieldSingleSelectValue{name field{
1661 ... on ProjectV2SingleSelectField{id name options{id name}}
1662 }}}
1663 }pageInfo{hasNextPage endCursor}}}"#
1664 );
1665
1666 /// The board's own id and field definitions, and not one of its items.
1667 ///
1668 /// What a write needs of the board when the item it writes does not say: the id a field
1669 /// write and `addProjectV2ItemById` address, and the definitions of the `Status` and
1670 /// origin fields. It selects no `items`, so what it costs is the board's field list
1671 /// however many items the board holds — and it decides nothing about which items those
1672 /// are, which is the question a read of one item by its own id answers instead.
1673 ///
1674 /// The root is aliased `boardFields` rather than `owner`, so nothing counting the
1675 /// board's item reads by their root counts this one among them.
1676 pub const BOARD_FIELDS: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!){
1677 boardFields:repositoryOwner(login:$owner){
1678 ... on ProjectV2Owner{projectV2(number:$number){id
1679 fields(first:$nestedFirst){nodes{
1680 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1681 ... on ProjectV2Field{__typename id name dataType}
1682 }pageInfo{hasNextPage}}
1683 }}
1684 }
1685 }"#;
1686
1687 /// One board draft by its own node id, with the board item it sits in.
1688 ///
1689 /// A draft is not an issue, so [`ISSUE`] reaches it and reads nothing of it; this is the
1690 /// second read that answers it. `DraftIssue.projectV2Items` names the board item a draft
1691 /// is — GitHub links a draft to one item — with the same [`board_item_values!`] the
1692 /// issue fragment reads, so a draft reached by id resolves through the same resolver a
1693 /// board listing hands it to, and nothing has to list the board to find one.
1694 pub const DRAFT: &str = concat!(
1695 r#"query($id:ID!,$nestedFirst:Int!,$boardItems:Int!){
1696 node(id:$id){__typename ... on DraftIssue{id title body createdAt updatedAt
1697 projectV2Items(first:$boardItems){nodes{id project{id number}
1698 "#,
1699 board_item_values!(),
1700 r#"}pageInfo{hasNextPage endCursor}}}}
1701 }"#
1702 );
1703
1704 /// One issue's board memberships alone, walked past the page a read of it carried.
1705 ///
1706 /// The recovery read behind [`GitHubProjectsSource::resolve_issue`](super::GitHubProjectsSource):
1707 /// every document above carries a *page* of `Issue.projectItems`, and an issue on more
1708 /// boards than that page holds may have this board's entry past its end. This asks that
1709 /// one issue for its memberships and nothing else — the caller already holds the issue —
1710 /// so an answer of "this board does not hold it" is only ever given about a connection
1711 /// read to exhaustion.
1712 ///
1713 /// It selects the board item's id, its project number and the same
1714 /// [`board_item_values!`] the fragment does, because what it produces is handed to the
1715 /// very same resolver: an issue recovered this way reports the same title, the same
1716 /// status, the same labels and the same qualified id as one whose entry was on the
1717 /// page.
1718 ///
1719 /// `$first` rather than `$boardItems`: this document reads one issue, so nothing
1720 /// multiplies through it and the membership connection can be walked at
1721 /// [`MAX_PAGE_SIZE`](super::MAX_PAGE_SIZE) — which is what keeps the recovery to one
1722 /// further request for any issue a person really keeps.
1723 pub const ISSUE_BOARD_ITEMS: &str = concat!(
1724 r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!){
1725 node(id:$id){
1726 ... on Issue{projectItems(first:$first,after:$after){
1727 nodes{id updatedAt project{id number}
1728 "#,
1729 board_item_values!(),
1730 r#"}
1731 pageInfo{hasNextPage endCursor}}}
1732 }
1733 }"#
1734 );
1735 /// Whether the board's Project is public — half of what decides whether a write here can
1736 /// be read by anybody. Needs the `read:project` scope.
1737 pub const PROJECT_VISIBILITY: &str = r#"query($owner:String!,$number:Int!){visibility:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){public}}}}"#;
1738 /// Resolves the configured repository's node id, which creating an issue requires.
1739 pub const REPOSITORY: &str = r#"query($owner:String!,$name:String!){repository(owner:$owner,name:$name){id nameWithOwner}}"#;
1740 /// What creating an issue needs and has not read yet: the board's own id and field
1741 /// definitions, as [`BOARD_FIELDS`] reads them, and the node id of the repository the
1742 /// issue is created in, as [`REPOSITORY`] reads it — in one request.
1743 ///
1744 /// Sent at the point a create knows which repository it is for, when neither half is
1745 /// already known to this process; a create needing only one of them sends that one's own
1746 /// document. Neither half is kept past the process: a field's option ids are re-minted by
1747 /// `sources fields --apply`, so a copy of them held between runs would write the wrong
1748 /// status.
1749 pub const CREATION_CONTEXT: &str = r#"query($owner:String!,$number:Int!,$nestedFirst:Int!,$repositoryOwner:String!,$repositoryName:String!){
1750 boardFields:repositoryOwner(login:$owner){
1751 ... on ProjectV2Owner{projectV2(number:$number){id
1752 fields(first:$nestedFirst){nodes{
1753 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1754 ... on ProjectV2Field{__typename id name dataType}
1755 }pageInfo{hasNextPage}}
1756 }}
1757 }
1758 repository(owner:$repositoryOwner,name:$repositoryName){id nameWithOwner}
1759 }"#;
1760 /// Reads both dependency directions for one issue, with each far end's own kind — and
1761 /// the issue's own body, which is where an edge to another source is recorded, so that
1762 /// half of a dependency read needs no second read of the issue or of the board.
1763 pub const ISSUE_DEPENDENCIES: &str = concat!(
1764 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1765 ... on Issue{body
1766 blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1767 blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1768 }}}"#,
1769 related_issue!()
1770 );
1771 /// What one item depends on: [`ISSUE_DEPENDENCIES`] narrowed to `blockedBy`, so a
1772 /// dependency read asks GitHub for the one direction it answers. The issue's `body` rides
1773 /// along because its metadata slot is where an edge to another source is recorded — and a
1774 /// board draft's `body` too, with the one board item GitHub links a draft to and, aliased
1775 /// `board`, this board's own id, so a draft's recorded edges are read off this same answer
1776 /// and only when that item is this board's: no draft read and no board read follow it.
1777 ///
1778 /// The draft's board item is asked for under a root of its own, aliased `draft`, rather
1779 /// than beside its `body` under `node`. GitHub counts the type-conditional fragments of
1780 /// one selection as the largest of them — `blockedBy`'s 100 alone, where this workspace's
1781 /// calculation adds the draft's 3 — while separate roots are summed by both, so this is
1782 /// the spelling whose node count GitHub and the calculation agree on. Both price it at
1783 /// one point; the credentialed lane's reconciliation is what holds the two to that.
1784 pub const ISSUE_DEPENDS_ON: &str = concat!(
1785 r#"query($id:ID!,$first:Int!,$after:String,$owner:String!,$number:Int!,$boardItems:Int!){
1786 node(id:$id){__typename
1787 ... on Issue{body
1788 blockedBy(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1789 }
1790 ... on DraftIssue{id body}}
1791 draft:node(id:$id){... on DraftIssue{projectV2Items(first:$boardItems){nodes{project{id number}}pageInfo{hasNextPage}}}}
1792 board:repositoryOwner(login:$owner){... on ProjectV2Owner{projectV2(number:$number){id}}}}"#,
1793 related_issue!()
1794 );
1795 /// What depends on one issue: [`ISSUE_DEPENDENCIES`] with its `blocking` alone. No `body`:
1796 /// the reverse of a recorded edge is derived from the far end, never written down here.
1797 pub const ISSUE_DEPENDED_ON_BY: &str = concat!(
1798 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename
1799 ... on Issue{
1800 blocking(first:$first,after:$after){nodes{...Related}pageInfo{hasNextPage endCursor}}
1801 }}}"#,
1802 related_issue!()
1803 );
1804 /// Creates one issue. Outside a copy it is created on no board, and [`ADD_TO_BOARD`] files
1805 /// it; inside one, its input names the board in `projectV2Ids` and its project in
1806 /// `parentIssueId`, so this one request files it under both — see
1807 /// [`GitHubProjectsSource::create_filed_issue`](super::GitHubProjectsSource).
1808 pub const CREATE_ISSUE: &str =
1809 r#"mutation($input:CreateIssueInput!){createIssue(input:$input){issue{id number url}}}"#;
1810 /// Puts an existing issue on the configured board.
1811 pub const ADD_TO_BOARD: &str = r#"mutation($input:AddProjectV2ItemByIdInput!){addProjectV2ItemById(input:$input){item{id}}}"#;
1812 /// Updates an issue's visible fields and its open or closed state in one call.
1813 pub const UPDATE_ISSUE: &str =
1814 r#"mutation($input:UpdateIssueInput!){updateIssue(input:$input){issue{id}}}"#;
1815 /// Closes one issue for a reason, the survivor it is a duplicate of included — the one way
1816 /// GitHub records a duplicate's link: `updateIssue`'s `stateInput` carries no survivor, and
1817 /// the REST `state_reason=duplicate` is accepted and records none, both measured by
1818 /// `spike-store-defects`.
1819 pub const CLOSE_ISSUE: &str =
1820 r#"mutation($input:CloseIssueInput!){closeIssue(input:$input){issue{id}}}"#;
1821 /// Updates an existing draft's user-visible fields.
1822 pub const UPDATE_DRAFT: &str = r#"mutation($input:UpdateProjectV2DraftIssueInput!){updateProjectV2DraftIssue(input:$input){draftIssue{id}}}"#;
1823 /// Updates a text or single-select value on one project item.
1824 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}}}}}}}}"#;
1825 /// Writes up to six board fields and clears up to three in one ordered mutation: every
1826 /// aliased field is included by its own boolean, as [`FIELD_WRITE_SLOTS`](super::FIELD_WRITE_SLOTS)
1827 /// and [`FIELD_CLEAR_SLOTS`](super::FIELD_CLEAR_SLOTS) name them, writes before clears.
1828 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}}}"#;
1829 /// Clears one project item's value of one field, which is what a `none` priority is.
1830 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}}}}}}}}"#;
1831 /// Creates one field: a single-select one with its options, or a text one for a projected
1832 /// metadata value. Only the guarded field setup may use this document, and only for a
1833 /// field the board lacks.
1834 pub const CREATE_FIELD: &str = r#"mutation($input:CreateProjectV2FieldInput!){createProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id name options{id name color description}}}}}"#;
1835 /// Replaces a single-select field's options. Only the guarded field setup — the
1836 /// `status-options` and `fields` operations — may use this document, because GitHub
1837 /// treats the input as the complete option list.
1838 pub const STATUS_OPTIONS_UPDATE: &str = r#"mutation($input:UpdateProjectV2FieldInput!){updateProjectV2Field(input:$input){projectV2Field{... on ProjectV2SingleSelectField{id options{id name color description}}}}}"#;
1839 /// A fresh snapshot of the Status field and every board item's assignment.
1840 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}}}}}}"#;
1841 /// Files one issue under another as a sub-issue, which is what project membership is.
1842 pub const ADD_SUB_ISSUE: &str =
1843 r#"mutation($input:AddSubIssueInput!){addSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1844 /// Takes one issue back out of its parent.
1845 pub const REMOVE_SUB_ISSUE: &str = r#"mutation($input:RemoveSubIssueInput!){removeSubIssue(input:$input){issue{id} subIssue{id}}}"#;
1846 /// Adds GitHub's native issue blocked-by relationship.
1847 pub const ADD_BLOCKED_BY: &str = r#"mutation($input:AddBlockedByInput!){addBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
1848 /// One origin of [`ORIGIN_LOOKUPS`]: [`ORIGIN_LOOKUP`]'s two connections for the origin the
1849 /// `$filter<n>` and `$search<n>` of slot `<n>` name, sent only while `$ask<n>` holds.
1850 macro_rules! origin_lookup_alias {
1851 ($n:literal) => {
1852 concat!(
1853 "\n o",
1854 stringify!($n),
1855 ":repositoryOwner(login:$owner) @include(if:$ask",
1856 stringify!($n),
1857 "){... on ProjectV2Owner{projectV2(number:$number){items(first:$lookupFirst,query:$filter",
1858 stringify!($n),
1859 "){nodes{id updatedAt ",
1860 board_item_values!(),
1861 board_item_content!(),
1862 "} pageInfo{hasNextPage endCursor}}}}}\n s",
1863 stringify!($n),
1864 ":search(query:$search",
1865 stringify!($n),
1866 ",type:$type,first:$lookupFirst) @include(if:$ask",
1867 stringify!($n),
1868 "){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}"
1869 )
1870 };
1871 }
1872
1873 /// [`ORIGIN_LOOKUPS`], with `$extra_variables` declared after its own and `$extra_fields`
1874 /// selected beside them: one spelling of the batched lookup for the documents that send it.
1875 macro_rules! origin_lookups {
1876 ($extra_variables:literal, $extra_fields:literal) => {
1877 concat!(
1878 r#"query($owner:String!,$number:Int!,$type:SearchType!,$lookupFirst: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!"#,
1879 relationship_events_variable!(),
1880 $extra_variables,
1881 r#"){
1882 boardFields:repositoryOwner(login:$owner){
1883 ... on ProjectV2Owner{projectV2(number:$number){id
1884 fields(first:$nestedFirst){nodes{
1885 ... on ProjectV2SingleSelectField{__typename id name options{id name}}
1886 ... on ProjectV2Field{__typename id name dataType}
1887 }pageInfo{hasNextPage}}
1888 }}
1889 }
1890 repository(owner:$repositoryOwner,name:$repositoryName){id databaseId nameWithOwner}"#,
1891 $extra_fields,
1892 origin_lookup_alias!(0),
1893 origin_lookup_alias!(1),
1894 origin_lookup_alias!(2),
1895 origin_lookup_alias!(3),
1896 origin_lookup_alias!(4),
1897 origin_lookup_alias!(5),
1898 origin_lookup_alias!(6),
1899 origin_lookup_alias!(7),
1900 origin_lookup_alias!(8),
1901 origin_lookup_alias!(9),
1902 "\n }",
1903 board_issue!()
1904 )
1905 };
1906 }
1907
1908 /// The first page of [`ORIGIN_LOOKUP`] for up to [`ORIGIN_BATCH`](super::ORIGIN_BATCH)
1909 /// origins a copy is about to look for, and everything creating an item then reads —
1910 /// the board's own id and field definitions, as [`CREATION_CONTEXT`] reads them, and the node
1911 /// id and the numeric id of the repository an issue is created in — in one request.
1912 ///
1913 /// What a copy reads before it writes anything, so that finding none of its records on the
1914 /// board and creating every one costs this read and the writes. An origin whose page says
1915 /// there is more is left to its own [`ORIGIN_LOOKUP`]. The repository's numeric id is what an
1916 /// image upload names, so a copy carrying assets needs no `GET /repos/{owner}/{repo}` either.
1917 pub const ORIGIN_LOOKUPS: &str = origin_lookups!("", "");
1918
1919 /// [`ORIGIN_LOOKUPS`], with a page of the members of the project `$project` beside it, each
1920 /// trimmed to what classifying it reads — its id, its parent, its body and its repository,
1921 /// and no connection under it.
1922 ///
1923 /// What a document copy sends where the public boundary screens its write: the document is
1924 /// held to who may read its project, which is its members' classification as much as the
1925 /// project's own, and this request carries both the project — among the origins it asks —
1926 /// and its members. GitHub's own dry run prices it at the one point [`ORIGIN_LOOKUPS`]
1927 /// costs alone (`docs/measurements/board-copy-gaps-2026-10-24/coalesced-members-dry-run`).
1928 pub const ORIGIN_LOOKUPS_WITH_MEMBERS: &str = origin_lookups!(
1929 ",$project:ID!,$memberFirst:Int!",
1930 "\n members:node(id:$project){... on Issue{subIssues(first:$memberFirst){pageInfo{hasNextPage endCursor} nodes{id body parent{id} repository{nameWithOwner}}}}}"
1931 );
1932
1933 /// One slot `<n>` of a copy's aliased writes: `$<prefix><n>` is its input and `$send<n>`
1934 /// whether it is sent.
1935 macro_rules! write_slot {
1936 ($prefix:literal, $field:literal, $selection:literal, $n:literal) => {
1937 concat!(
1938 " ",
1939 $prefix,
1940 stringify!($n),
1941 ":",
1942 $field,
1943 "(input:$",
1944 $prefix,
1945 stringify!($n),
1946 ") @include(if:$send",
1947 stringify!($n),
1948 "){",
1949 $selection,
1950 "}"
1951 )
1952 };
1953 }
1954
1955 /// The variables of a copy's aliased writes: eleven inputs of `$type` named `$<prefix><n>`,
1956 /// and eleven `$send<n>`.
1957 macro_rules! write_variables {
1958 ($prefix:literal, $type:literal) => {
1959 concat!(
1960 "mutation(",
1961 "$",
1962 $prefix,
1963 "0:",
1964 $type,
1965 "!,$",
1966 $prefix,
1967 "1:",
1968 $type,
1969 "!,$",
1970 $prefix,
1971 "2:",
1972 $type,
1973 "!,$",
1974 $prefix,
1975 "3:",
1976 $type,
1977 "!,$",
1978 $prefix,
1979 "4:",
1980 $type,
1981 "!,$",
1982 $prefix,
1983 "5:",
1984 $type,
1985 "!,$",
1986 $prefix,
1987 "6:",
1988 $type,
1989 "!,$",
1990 $prefix,
1991 "7:",
1992 $type,
1993 "!,$",
1994 $prefix,
1995 "8:",
1996 $type,
1997 "!,$",
1998 $prefix,
1999 "9:",
2000 $type,
2001 "!,$",
2002 $prefix,
2003 "10:",
2004 $type,
2005 "!,",
2006 "$send0:Boolean!,$send1:Boolean!,$send2:Boolean!,$send3:Boolean!,$send4:Boolean!,",
2007 "$send5:Boolean!,$send6:Boolean!,$send7:Boolean!,$send8:Boolean!,$send9:Boolean!,",
2008 "$send10:Boolean!){"
2009 )
2010 };
2011 }
2012
2013 /// A copy's aliased writes of one kind: [`MUTATION_BATCH`](super::MUTATION_BATCH) slots of
2014 /// `$field`, each sent only while its `$send<n>` holds.
2015 macro_rules! write_batch {
2016 ($prefix:literal, $type:literal, $field:literal, $selection:literal) => {
2017 concat!(
2018 write_variables!($prefix, $type),
2019 write_slot!($prefix, $field, $selection, 0),
2020 write_slot!($prefix, $field, $selection, 1),
2021 write_slot!($prefix, $field, $selection, 2),
2022 write_slot!($prefix, $field, $selection, 3),
2023 write_slot!($prefix, $field, $selection, 4),
2024 write_slot!($prefix, $field, $selection, 5),
2025 write_slot!($prefix, $field, $selection, 6),
2026 write_slot!($prefix, $field, $selection, 7),
2027 write_slot!($prefix, $field, $selection, 8),
2028 write_slot!($prefix, $field, $selection, 9),
2029 write_slot!($prefix, $field, $selection, 10),
2030 "}"
2031 )
2032 };
2033 }
2034
2035 /// Creates up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues in one request, each filed on
2036 /// the board and under its project by the same `createIssue` — its `projectV2Ids` and
2037 /// `parentIssueId` — as [`CREATE_ISSUE`] creates one.
2038 pub const CREATE_ISSUES: &str = write_batch!(
2039 "create",
2040 "CreateIssueInput",
2041 "createIssue",
2042 "issue{id number url}"
2043 );
2044
2045 /// One issue of [`CREATED_BOARD_ITEMS`]: the board items the issue `$id<n>` names is on, with
2046 /// the `Status` value of each, read only while `$read<n>` holds.
2047 macro_rules! created_item_alias {
2048 ($n:literal) => {
2049 concat!(
2050 "\n i",
2051 stringify!($n),
2052 ":node(id:$id",
2053 stringify!($n),
2054 ") @include(if:$read",
2055 stringify!($n),
2056 "){... on Issue{id projectItems(first:$boardItems){nodes{id project{id} status:fieldValueByName(name:$statusName){... on ProjectV2ItemFieldSingleSelectValue{name}}}}}}"
2057 )
2058 };
2059 }
2060
2061 /// The board item of each issue a copy created, up to
2062 /// [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH) at a time, with its `Status` as the board
2063 /// set it: what `createIssue`'s `projectV2Ids` files the issue as, which GitHub adds after
2064 /// answering the create, so its id comes from a read made once every create has been sent.
2065 pub const CREATED_BOARD_ITEMS: &str = concat!(
2066 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!){"#,
2067 created_item_alias!(0),
2068 created_item_alias!(1),
2069 created_item_alias!(2),
2070 created_item_alias!(3),
2071 created_item_alias!(4),
2072 created_item_alias!(5),
2073 created_item_alias!(6),
2074 created_item_alias!(7),
2075 created_item_alias!(8),
2076 created_item_alias!(9),
2077 created_item_alias!(10),
2078 created_item_alias!(11),
2079 created_item_alias!(12),
2080 created_item_alias!(13),
2081 created_item_alias!(14),
2082 created_item_alias!(15),
2083 created_item_alias!(16),
2084 created_item_alias!(17),
2085 created_item_alias!(18),
2086 created_item_alias!(19),
2087 created_item_alias!(20),
2088 "\n }"
2089 );
2090
2091 /// The variables and the aliases of [`WRITE_BATCH`](super::WRITE_BATCH) slots: `$<prefix><n>`
2092 /// is a slot's input and `$<send><n>` whether it is sent, for the slot numbers given.
2093 macro_rules! wide_variables {
2094 ($prefix:literal, $type:literal, $send:literal; $($n:literal)+) => {
2095 concat!($("$", $prefix, stringify!($n), ":", $type, "!,$", $send, stringify!($n), ":Boolean!,",)+)
2096 };
2097 }
2098 macro_rules! wide_slots {
2099 ($prefix:literal, $field:literal, $selection:literal, $send:literal; $($n:literal)+) => {
2100 concat!($(
2101 " ", $prefix, stringify!($n), ":", $field, "(input:$", $prefix, stringify!($n),
2102 ") @include(if:$", $send, stringify!($n), "){", $selection, "}",
2103 )+)
2104 };
2105 }
2106
2107 /// Up to [`WRITE_BATCH`](super::WRITE_BATCH) board field values a copy writes on the items it
2108 /// created, each on its own item, in one ordered request.
2109 pub const WRITE_FIELD_VALUES: &str = concat!(
2110 "mutation(",
2111 wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2112 "){",
2113 wide_slots!("field", "updateProjectV2ItemFieldValue", "projectV2Item{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2114 "}"
2115 );
2116
2117 /// A copy's board field values and its blocked-by edges together, up to
2118 /// [`WRITE_BATCH`](super::WRITE_BATCH) of the two kinds between them, in one ordered request:
2119 /// every field value its `$sendField<n>` sends, then every edge its `$sendBlock<n>` sends.
2120 /// What a copy sends when one request of its writes holds both kinds; one holding a single
2121 /// kind is [`WRITE_FIELD_VALUES`] or [`ADD_BLOCKED_BYS`].
2122 pub const WRITE_FIELDS_AND_EDGES: &str = concat!(
2123 "mutation(",
2124 wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2125 wide_variables!("block", "AddBlockedByInput", "sendBlock"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2126 "){",
2127 wide_slots!("field", "updateProjectV2ItemFieldValue", "projectV2Item{id}", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2128 wide_slots!("block", "addBlockedBy", "issue{id} blockingIssue{id}", "sendBlock"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2129 "}"
2130 );
2131
2132 /// Closes up to [`MUTATION_BATCH`](super::MUTATION_BATCH) issues a copy created at a closing
2133 /// status, each with its own `stateInput` and nothing else, once its option is selected.
2134 pub const CLOSE_ISSUES: &str =
2135 write_batch!("close", "UpdateIssueInput", "updateIssue", "issue{id}");
2136
2137 /// Updates up to [`MUTATION_BATCH`](super::MUTATION_BATCH) existing issues a copy rewrites,
2138 /// each with the members its own [`UPDATE_ISSUE`] would have sent, in one request.
2139 pub const UPDATE_ISSUES: &str =
2140 write_batch!("update", "UpdateIssueInput", "updateIssue", "issue{id}");
2141
2142 /// Up to [`WRITE_BATCH`](super::WRITE_BATCH) native blocked-by relationships a copy adds to the
2143 /// issues it created, in one request.
2144 pub const ADD_BLOCKED_BYS: &str = concat!(
2145 "mutation(",
2146 wide_variables!("block", "AddBlockedByInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2147 "){",
2148 wide_slots!("block", "addBlockedBy", "issue{id} blockingIssue{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2149 "}"
2150 );
2151
2152 /// Removes one native issue blocked-by relationship.
2153 pub const REMOVE_BLOCKED_BY: &str = r#"mutation($input:RemoveBlockedByInput!){removeBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
2154 /// Deletes one issue, which takes its board item with it.
2155 ///
2156 /// The engine sends this in one situation only: undoing a copy that could not finish,
2157 /// over the items that same copy created. Deleting the issue removes the board item
2158 /// too, so there is no second `deleteProjectV2Item` to keep in step with it.
2159 pub const DELETE_ISSUE: &str =
2160 r#"mutation($input:DeleteIssueInput!){deleteIssue(input:$input){repository{id}}}"#;
2161 /// Deletes up to [`DELETE_BATCH`](super::DELETE_BATCH) issues in one request, each as
2162 /// [`DELETE_ISSUE`] deletes one: what a write that created several issues and was refused
2163 /// part way sends to take them back.
2164 pub const DELETE_ISSUES: &str = concat!(
2165 "mutation(",
2166 wide_variables!("delete", "DeleteIssueInput", "send"; 0 1 2 3 4),
2167 "){",
2168 wide_slots!("delete", "deleteIssue", "repository{id}", "send"; 0 1 2 3 4),
2169 "}"
2170 );
2171
2172 /// One task's comments: a page of its issue's own `comments` connection.
2173 ///
2174 /// **No `orderBy`, and that is what makes the page oldest first.** GitHub's only
2175 /// `IssueCommentOrder` field is `UPDATED_AT`, which would move a comment to the end of the
2176 /// list every time somebody edited it; left unordered the connection answers in the order
2177 /// the comments were written, which is the order GitHub documents for the same collection
2178 /// over REST — ascending id. Nothing multiplies through it, so `$first` is the whole of its
2179 /// node count and the caller's own page size is pushed straight down.
2180 pub const ISSUE_COMMENTS: &str = concat!(
2181 r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename ... on Issue{comments(first:$first,after:$after){nodes{"#,
2182 issue_comment!(),
2183 r#"}pageInfo{hasNextPage endCursor}}}}}"#
2184 );
2185 /// One issue by its own node id, with a page of its comments: what `task show` and a
2186 /// comment listing read, in one request.
2187 ///
2188 /// [`ISSUE`] and [`ISSUE_COMMENTS`] in one document, rather than one then the other. The
2189 /// comments are selected here and **not** on the shared `board_issue!` fragment, which
2190 /// [`SEARCH_ISSUES`] and [`SUB_ISSUES`] nest under a page of a hundred issues: a comment
2191 /// connection there would multiply through both of those documents' price, and neither
2192 /// needs one.
2193 pub const ISSUE_DETAIL: &str = concat!(
2194 r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2195 relationship_events_variable!(),
2196 r#"){
2197 node(id:$id){__typename ...BoardIssue ... on Issue{comments(first:$first,after:$after){nodes{"#,
2198 issue_comment!(),
2199 r#"}pageInfo{hasNextPage endCursor}}}}
2200 }"#,
2201 board_issue!()
2202 );
2203
2204 /// One alias of [`ISSUE_DETAILS`]: the item a batch's `$id<n>` names, with the first
2205 /// page of its comments when `$comments` asks for them.
2206 macro_rules! issue_details_alias {
2207 ($n:literal) => {
2208 concat!(
2209 "\n i",
2210 stringify!($n),
2211 ":node(id:$id",
2212 stringify!($n),
2213 "){__typename ...BoardIssue ... on Issue{comments(first:$first) @include(if:$comments){nodes{",
2214 issue_comment!(),
2215 "}pageInfo{hasNextPage endCursor}}}}"
2216 )
2217 };
2218 }
2219
2220 /// [`ISSUE_DETAIL`] for [`DETAIL_BATCH`](super::DETAIL_BATCH) items at once, each by its
2221 /// own node id, as one fixed-size document of aliased `node(id:)` fields.
2222 ///
2223 /// **Aliased `node(id:)` rather than `nodes(ids:)`, and that is what keeps its price
2224 /// honest.** The `github-graphql-node-count` model this workspace prices with treats a
2225 /// field that supplies neither `first` nor `last` as free, and `nodes(ids:)` supplies
2226 /// neither — so every connection under it would be priced at nothing and the pin in
2227 /// `tests/point_cost.rs` would understate what GitHub charges. Each alias here is the
2228 /// one-item read the model already prices, so the batch costs what its aliases cost.
2229 ///
2230 /// **Fixed-size, so there is one document to price.** A batch of fewer items binds the
2231 /// slots it has no item for to the last item it does, and reads that item again; the
2232 /// price is the document's, whatever its variables, so a short batch costs what a full
2233 /// one does and nothing more.
2234 pub const ISSUE_DETAILS: &str = concat!(
2235 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!"#,
2236 relationship_events_variable!(),
2237 r#"){"#,
2238 issue_details_alias!(0),
2239 issue_details_alias!(1),
2240 issue_details_alias!(2),
2241 issue_details_alias!(3),
2242 issue_details_alias!(4),
2243 issue_details_alias!(5),
2244 issue_details_alias!(6),
2245 issue_details_alias!(7),
2246 issue_details_alias!(8),
2247 issue_details_alias!(9),
2248 issue_details_alias!(10),
2249 issue_details_alias!(11),
2250 issue_details_alias!(12),
2251 issue_details_alias!(13),
2252 issue_details_alias!(14),
2253 issue_details_alias!(15),
2254 issue_details_alias!(16),
2255 issue_details_alias!(17),
2256 issue_details_alias!(18),
2257 issue_details_alias!(19),
2258 issue_details_alias!(20),
2259 issue_details_alias!(21),
2260 issue_details_alias!(22),
2261 issue_details_alias!(23),
2262 "\n }",
2263 board_issue!()
2264 );
2265
2266 /// One alias of [`ISSUE_COPY_DETAILS`]: the item a batch's `$id<n>` names, with the first
2267 /// page of its comments and the issues it is blocked by.
2268 macro_rules! issue_copy_details_alias {
2269 ($n:literal) => {
2270 concat!(
2271 "\n i",
2272 stringify!($n),
2273 ":node(id:$id",
2274 stringify!($n),
2275 "){__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{",
2276 issue_comment!(),
2277 "}pageInfo{hasNextPage endCursor}} blockedBy(first:$nestedFirst){nodes{...Related}pageInfo{hasNextPage endCursor}}}}"
2278 )
2279 };
2280 }
2281
2282 /// [`ISSUE_DETAILS`] as a copy reads the tasks it carries: each item with the first page of
2283 /// its comments and its `blockedBy` — the edges a copy reads of every task next, which
2284 /// [`ISSUE`] carries and [`ISSUE_DETAILS`] does not — [`COPY_DETAIL_BATCH`](super::COPY_DETAIL_BATCH)
2285 /// at a time, so a copy of a changed task costs this read and nothing else.
2286 ///
2287 /// A document of its own rather than a widening of [`ISSUE_DETAILS`], whose batch size is
2288 /// what `task show-many` is priced by and which reads no edge.
2289 ///
2290 /// `children`, read only while `$children` holds, is which issues the issue `$project` has
2291 /// as sub-issues — each one's id and title, the page `$nestedFirst` allows — so that a
2292 /// project copy, which reads its project and every task at once, knows from this same read
2293 /// which tasks the project holds at the destination, and its orphan check is answered by it
2294 /// rather than by a listing of the project.
2295 pub const ISSUE_COPY_DETAILS: &str = concat!(
2296 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!"#,
2297 relationship_events_variable!(),
2298 r#"){"#,
2299 issue_copy_details_alias!(0),
2300 issue_copy_details_alias!(1),
2301 issue_copy_details_alias!(2),
2302 issue_copy_details_alias!(3),
2303 issue_copy_details_alias!(4),
2304 issue_copy_details_alias!(5),
2305 issue_copy_details_alias!(6),
2306 issue_copy_details_alias!(7),
2307 issue_copy_details_alias!(8),
2308 issue_copy_details_alias!(9),
2309 issue_copy_details_alias!(10),
2310 issue_copy_details_alias!(11),
2311 issue_copy_details_alias!(12),
2312 issue_copy_details_alias!(13),
2313 issue_copy_details_alias!(14),
2314 issue_copy_details_alias!(15),
2315 issue_copy_details_alias!(16),
2316 issue_copy_details_alias!(17),
2317 issue_copy_details_alias!(18),
2318 issue_copy_details_alias!(19),
2319 issue_copy_details_alias!(20),
2320 "\n children:node(id:$project) @include(if:$children){... on Issue{id subIssues(first:$nestedFirst){nodes{id title} pageInfo{hasNextPage}}}}",
2321 "\n }",
2322 board_issue!(),
2323 related_issue!()
2324 );
2325
2326 /// Which issue one comment is on, read before that comment is edited or removed.
2327 ///
2328 /// GitHub's comment mutations take the comment's id and nothing else, so without this a
2329 /// comment id given against the wrong task would change a comment on another issue.
2330 pub const COMMENT_ISSUE: &str =
2331 r#"query($id:ID!){node(id:$id){__typename ... on IssueComment{id body issue{id}}}}"#;
2332 /// Adds one comment to an issue, signed as the account the token belongs to.
2333 pub const ADD_COMMENT: &str = concat!(
2334 r#"mutation($input:AddCommentInput!){addComment(input:$input){subject{id} commentEdge{node{"#,
2335 issue_comment!(),
2336 r#"}}}}"#
2337 );
2338 /// Replaces the body of one issue comment.
2339 pub const UPDATE_COMMENT: &str = concat!(
2340 r#"mutation($input:UpdateIssueCommentInput!){updateIssueComment(input:$input){issueComment{"#,
2341 issue_comment!(),
2342 r#"}}}"#
2343 );
2344 /// Removes one issue comment. Its payload carries nothing about the comment it removed.
2345 pub const DELETE_COMMENT: &str = r#"mutation($input:DeleteIssueCommentInput!){deleteIssueComment(input:$input){clientMutationId}}"#;
2346
2347 /// The variables of the search slots `<n>` of [`SEARCH_BATCH`]: its search, where it
2348 /// resumes, its page size and whether it is asked.
2349 macro_rules! search_batch_variables {
2350 ($($n:literal)+) => {
2351 concat!($(
2352 ",$search", stringify!($n), ":String!,$after", stringify!($n),
2353 ":String,$first", stringify!($n), ":Int!,$ask", stringify!($n), ":Boolean!",
2354 )+)
2355 };
2356 }
2357 /// The search slots `<n>` of [`SEARCH_BATCH`]: [`SEARCH_ISSUES`]'s one connection, aliased
2358 /// `s<n>`, sent only while `$ask<n>` holds.
2359 macro_rules! search_batch_slots {
2360 ($($n:literal)+) => {
2361 concat!($(
2362 "\n s", stringify!($n), ":search(query:$search", stringify!($n),
2363 ",type:$type,first:$first", stringify!($n), ",after:$after", stringify!($n),
2364 ") @include(if:$ask", stringify!($n),
2365 "){pageInfo{hasNextPage endCursor} nodes{__typename ...BoardIssue}}",
2366 )+)
2367 };
2368 }
2369 /// The variables of the origin slots `<n>` of [`SEARCH_BATCH`]: the board's field filter
2370 /// naming the origin, where its items resume, their page size and whether it is asked.
2371 macro_rules! origin_batch_variables {
2372 ($($n:literal)+) => {
2373 concat!($(
2374 ",$filter", stringify!($n), ":String!,$itemsAfter", stringify!($n),
2375 ":String,$itemsFirst", stringify!($n), ":Int!,$origin", stringify!($n),
2376 ":Boolean!",
2377 )+)
2378 };
2379 }
2380 /// The origin slots `<n>` of [`SEARCH_BATCH`]: [`ORIGIN_LOOKUP`]'s board half, the board's
2381 /// own items through its field filter, aliased `o<n>`, sent only while `$origin<n>` holds.
2382 macro_rules! origin_batch_slots {
2383 ($($n:literal)+) => {
2384 concat!($(
2385 "\n o", stringify!($n), ":repositoryOwner(login:$owner) @include(if:$origin",
2386 stringify!($n),
2387 "){... on ProjectV2Owner{projectV2(number:$number){items(first:$itemsFirst",
2388 stringify!($n), ",after:$itemsAfter", stringify!($n), ",query:$filter",
2389 stringify!($n), "){nodes{id updatedAt ", board_item_values!(),
2390 board_item_content!(), "} pageInfo{hasNextPage endCursor}}}}}",
2391 )+)
2392 };
2393 }
2394
2395 /// Up to [`SEARCH_BATCH`](super::SEARCH_BATCH) board-scoped issue searches in one request,
2396 /// each [`SEARCH_ISSUES`]'s connection in an aliased `s<n>` field with its own query, page
2397 /// size and cursor, and beside them up to
2398 /// [`SEARCH_BATCH_ORIGINS`](super::SEARCH_BATCH_ORIGINS) origin lookups' board halves —
2399 /// [`ORIGIN_LOOKUP`]'s `items` filtered by the origin field — in aliased `o<n>` fields, each
2400 /// origin's issue search in a search slot of its own.
2401 ///
2402 /// What `task find` asks a board, every search a page at a time: one request a round,
2403 /// rather than one per search. A slot not asked is left out by `@include`, its page size
2404 /// bound to one; GitHub answers an error about one slot at that slot's path, and the other
2405 /// slots are answered beside it.
2406 pub const SEARCH_BATCH: &str = concat!(
2407 r#"query($owner:String!,$number:Int!,$type:SearchType!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2408 relationship_events_variable!(),
2409 search_batch_variables!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19),
2410 origin_batch_variables!(0 1 2 3 4),
2411 "){",
2412 search_batch_slots!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19),
2413 origin_batch_slots!(0 1 2 3 4),
2414 "\n }",
2415 board_issue!()
2416 );
2417
2418 /// The comment slots `<n>` of [`ADD_COMMENTS`]: [`ADD_COMMENT`]'s mutation, aliased
2419 /// `comment<n>`, sent only while `$send<n>` holds.
2420 macro_rules! comment_slots {
2421 ($($n:literal)+) => {
2422 concat!($(
2423 " comment", stringify!($n), ":addComment(input:$comment", stringify!($n),
2424 ") @include(if:$send", stringify!($n), "){subject{id} commentEdge{node{",
2425 issue_comment!(), "}}}",
2426 )+)
2427 };
2428 }
2429
2430 /// Adds up to [`COMMENT_BATCH`](super::COMMENT_BATCH) comments in one request, each as
2431 /// [`ADD_COMMENT`] adds one, in order: what `task comment add-many` sends. GitHub runs each
2432 /// alias on its own and answers one it refused at its own path, beside the others.
2433 pub const ADD_COMMENTS: &str = concat!(
2434 "mutation(",
2435 wide_variables!("comment", "AddCommentInput", "send"; 0 1 2 3 4 5 6 7 8 9 10),
2436 "){",
2437 comment_slots!(0 1 2 3 4 5 6 7 8 9 10),
2438 "}"
2439 );
2440
2441 /// Many tasks' targeted updates, each as [`UPDATE_FIELDS`] and [`UPDATE_ISSUE`] write one:
2442 /// up to [`TASK_FIELD_BATCH`](super::TASK_FIELD_BATCH) board field values in `field<n>`,
2443 /// [`MUTATION_BATCH`](super::MUTATION_BATCH) field clears in `clear<n>`, and as many
2444 /// `updateIssue`s in `update<n>`, each sent only while its own `send…<n>` holds.
2445 ///
2446 /// What `task update-many` sends, in two requests at most: every item's field values and
2447 /// clears first, then every issue update of an item whose fields all landed — the order one
2448 /// item's update keeps, so a refusal part way leaves an item's body as it stood.
2449 ///
2450 /// Each `update<n>` selects the issue it updated as a read of it does, so its response spells
2451 /// the change token the task holds after its batch's writes — the version `update-many`
2452 /// answers — with no read after them. Its page sizes are bound by `$nestedFirst` and
2453 /// `$boardItems`, as every read's are.
2454 pub const WRITE_TASKS: &str = concat!(
2455 "mutation(",
2456 wide_variables!("field", "UpdateProjectV2ItemFieldValueInput", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2457 wide_variables!("clear", "ClearProjectV2ItemFieldValueInput", "sendClear"; 0 1 2 3 4 5 6 7 8 9 10),
2458 wide_variables!("update", "UpdateIssueInput", "sendUpdate"; 0 1 2 3 4 5 6 7 8 9 10),
2459 r#"$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2460 relationship_events_variable!(),
2461 "){",
2462 wide_slots!("field", "updateProjectV2ItemFieldValue", "projectV2Item{id}", "sendField"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18),
2463 wide_slots!("clear", "clearProjectV2ItemFieldValue", "projectV2Item{id}", "sendClear"; 0 1 2 3 4 5 6 7 8 9 10),
2464 wide_slots!("update", "updateIssue", "issue{id ...BoardIssue}", "sendUpdate"; 0 1 2 3 4 5 6 7 8 9 10),
2465 "}",
2466 board_issue!()
2467 );
2468
2469 /// One alias of [`ISSUE_RELATIONS`]: the item a batch's `$id<n>` names, as a read of it by
2470 /// its own id reads it, with a page of its sub-issues' ids.
2471 macro_rules! issue_relations_alias {
2472 ($n:literal) => {
2473 concat!(
2474 "\n i",
2475 stringify!($n),
2476 ":node(id:$id",
2477 stringify!($n),
2478 "){__typename ...BoardIssue ... on Issue{subIssues(first:$first){nodes{id}pageInfo{hasNextPage}}}}"
2479 )
2480 };
2481 }
2482
2483 /// [`ISSUE_DETAILS`] with each issue's sub-issues in place of its comments: what `task
2484 /// relations` and a link write read of [`DETAIL_BATCH`](super::DETAIL_BATCH) tasks at once
2485 /// on a source reading sub-issues as children — each task whole, its parent and the ids of up
2486 /// to `$first` of its children.
2487 pub const ISSUE_RELATIONS: &str = concat!(
2488 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!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2489 relationship_events_variable!(),
2490 r#"){"#,
2491 issue_relations_alias!(0),
2492 issue_relations_alias!(1),
2493 issue_relations_alias!(2),
2494 issue_relations_alias!(3),
2495 issue_relations_alias!(4),
2496 issue_relations_alias!(5),
2497 issue_relations_alias!(6),
2498 issue_relations_alias!(7),
2499 issue_relations_alias!(8),
2500 issue_relations_alias!(9),
2501 issue_relations_alias!(10),
2502 issue_relations_alias!(11),
2503 issue_relations_alias!(12),
2504 issue_relations_alias!(13),
2505 issue_relations_alias!(14),
2506 issue_relations_alias!(15),
2507 issue_relations_alias!(16),
2508 issue_relations_alias!(17),
2509 issue_relations_alias!(18),
2510 issue_relations_alias!(19),
2511 issue_relations_alias!(20),
2512 issue_relations_alias!(21),
2513 issue_relations_alias!(22),
2514 issue_relations_alias!(23),
2515 "\n }",
2516 board_issue!()
2517 );
2518
2519 /// Up to [`RELATION_BATCH`](super::RELATION_BATCH) parent writes in one request:
2520 /// `parent<n>` an `addSubIssue` (a re-parent carrying `replaceParent: true`) and `unparent<n>`
2521 /// a `removeSubIssue`, each sent only while its own `send…<n>` holds. GitHub runs each alias
2522 /// on its own and answers one it refused — a cycle, a depth or children limit — at its own
2523 /// path, beside the others.
2524 pub const SET_PARENTS: &str = concat!(
2525 "mutation(",
2526 wide_variables!("parent", "AddSubIssueInput", "sendParent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2527 wide_variables!("unparent", "RemoveSubIssueInput", "sendUnparent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2528 "){",
2529 wide_slots!("parent", "addSubIssue", "issue{id} subIssue{id}", "sendParent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2530 wide_slots!("unparent", "removeSubIssue", "issue{id} subIssue{id}", "sendUnparent"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2531 "}"
2532 );
2533
2534 /// Up to [`RELATION_BATCH`](super::RELATION_BATCH) `relates-to` relations added in one
2535 /// request, each `relate<n>` sent only while `$send<n>` holds: what a link of a type a
2536 /// source mirrors natively writes beside its metadata.
2537 pub const ADD_RELATES_TO: &str = concat!(
2538 "mutation(",
2539 wide_variables!("relate", "AddRelatesToInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2540 "){",
2541 wide_slots!("relate", "addRelatesTo", "issue{id} relatedIssue{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2542 "}"
2543 );
2544
2545 /// [`ADD_RELATES_TO`]'s removal: up to [`RELATION_BATCH`](super::RELATION_BATCH)
2546 /// `relates-to` relations removed in one request.
2547 pub const REMOVE_RELATES_TO: &str = concat!(
2548 "mutation(",
2549 wide_variables!("unrelate", "RemoveRelatesToInput", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2550 "){",
2551 wide_slots!("unrelate", "removeRelatesTo", "issue{id} relatedIssue{id}", "send"; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29),
2552 "}"
2553 );
2554
2555 /// One alias of [`RELATES_TO_READS`]: the issue `$id<n>` names and the ids of up to
2556 /// `$first` of the issues it relates to.
2557 macro_rules! relates_to_alias {
2558 ($n:literal) => {
2559 concat!(
2560 "\n r",
2561 stringify!($n),
2562 ":node(id:$id",
2563 stringify!($n),
2564 "){... on Issue{id relatesTo(first:$first){nodes{id}pageInfo{hasNextPage}}}}"
2565 )
2566 };
2567 }
2568
2569 /// What [`DETAIL_BATCH`](super::DETAIL_BATCH) issues relate to, one alias each: read
2570 /// after a relation write whose answer never arrived, so each relation is answered from what
2571 /// GitHub holds rather than sent again blindly.
2572 pub const RELATES_TO_READS: &str = concat!(
2573 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!){"#,
2574 relates_to_alias!(0),
2575 relates_to_alias!(1),
2576 relates_to_alias!(2),
2577 relates_to_alias!(3),
2578 relates_to_alias!(4),
2579 relates_to_alias!(5),
2580 relates_to_alias!(6),
2581 relates_to_alias!(7),
2582 relates_to_alias!(8),
2583 relates_to_alias!(9),
2584 relates_to_alias!(10),
2585 relates_to_alias!(11),
2586 relates_to_alias!(12),
2587 relates_to_alias!(13),
2588 relates_to_alias!(14),
2589 relates_to_alias!(15),
2590 relates_to_alias!(16),
2591 relates_to_alias!(17),
2592 relates_to_alias!(18),
2593 relates_to_alias!(19),
2594 relates_to_alias!(20),
2595 relates_to_alias!(21),
2596 relates_to_alias!(22),
2597 relates_to_alias!(23),
2598 "\n }"
2599 );
2600
2601 /// What a mutation of a write the store's cache expects selects of the issue it wrote:
2602 /// everything [`ISSUE_DETAIL`] reads of it, so its response shows the task whole — its
2603 /// change token's every part and the first page of its comments.
2604 ///
2605 /// Sent **only** while that write runs, in place of the document named beside each
2606 /// below, so every other write's documents, prices and request counts are what they
2607 /// were. GitHub's token waits for a task to settle (`change_token::SETTLED`), and a
2608 /// mutation's response is stamped seconds after the change it made, so against GitHub
2609 /// itself a response rarely determines a version; the cache is then left unserveable
2610 /// for the task, and its next read refreshes it.
2611 macro_rules! whole_issue {
2612 () => {
2613 concat!(
2614 r#"__typename ...BoardIssue ... on Issue{comments(first:$first){nodes{"#,
2615 issue_comment!(),
2616 r#"}pageInfo{hasNextPage endCursor}}}"#
2617 )
2618 };
2619 }
2620
2621 /// The variables every document of `whole_issue!` declares beside its own.
2622 macro_rules! whole_variables {
2623 () => {
2624 concat!(
2625 r#",$first:Int!,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2626 relationship_events_variable!()
2627 )
2628 };
2629 }
2630
2631 /// [`ADD_COMMENT`], selecting the whole issue commented on.
2632 pub const ADD_COMMENT_WHOLE: &str = concat!(
2633 r#"mutation($input:AddCommentInput!"#,
2634 whole_variables!(),
2635 r#"){addComment(input:$input){subject{id "#,
2636 whole_issue!(),
2637 r#"} commentEdge{node{"#,
2638 issue_comment!(),
2639 r#"}}}}"#,
2640 board_issue!()
2641 );
2642 /// [`UPDATE_COMMENT`], selecting the whole issue the comment is on.
2643 pub const UPDATE_COMMENT_WHOLE: &str = concat!(
2644 r#"mutation($input:UpdateIssueCommentInput!"#,
2645 whole_variables!(),
2646 r#"){updateIssueComment(input:$input){issueComment{"#,
2647 issue_comment!(),
2648 r#" issue{"#,
2649 whole_issue!(),
2650 r#"}}}}"#,
2651 board_issue!()
2652 );
2653 /// [`UPDATE_ISSUE`], selecting the whole issue updated.
2654 pub const UPDATE_ISSUE_WHOLE: &str = concat!(
2655 r#"mutation($input:UpdateIssueInput!"#,
2656 whole_variables!(),
2657 r#"){updateIssue(input:$input){issue{id "#,
2658 whole_issue!(),
2659 r#"}}}"#,
2660 board_issue!()
2661 );
2662 /// [`UPDATE_FIELD`], selecting the whole issue behind the board item written.
2663 pub const UPDATE_FIELD_WHOLE: &str = concat!(
2664 r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2665 whole_variables!(),
2666 r#"){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
2667 whole_issue!(),
2668 r#"}}}}"#,
2669 board_issue!()
2670 );
2671 /// [`CLEAR_FIELD`], selecting the whole issue behind the board item cleared.
2672 pub const CLEAR_FIELD_WHOLE: &str = concat!(
2673 r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2674 whole_variables!(),
2675 r#"){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{"#,
2676 whole_issue!(),
2677 r#"}}}}"#,
2678 board_issue!()
2679 );
2680
2681 /// The variables every document selecting [`board_issue_fields!`] inline declares beside
2682 /// its own.
2683 macro_rules! token_variables {
2684 () => {
2685 concat!(
2686 r#",$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!"#,
2687 relationship_events_variable!()
2688 )
2689 };
2690 }
2691
2692 /// [`UPDATE_ISSUE`], selecting what a read of the issue updated selects — every part of its
2693 /// change token, and no comment — inline, so its root fields are the plain document's.
2694 ///
2695 /// What a targeted update sends in the plain document's place, so the version it answers
2696 /// is the one its own last response spells (`GitHubProjectsSource::written_tokens`). It
2697 /// costs the one point the plain document does.
2698 pub const UPDATE_ISSUE_TOKEN: &str = concat!(
2699 r#"mutation($input:UpdateIssueInput!"#,
2700 token_variables!(),
2701 r#"){updateIssue(input:$input){issue{"#,
2702 board_issue_fields!(),
2703 r#"}}}"#
2704 );
2705 /// [`UPDATE_FIELD`], selecting the issue behind the board item written as
2706 /// [`UPDATE_ISSUE_TOKEN`] selects the issue it updates.
2707 pub const UPDATE_FIELD_TOKEN: &str = concat!(
2708 r#"mutation($input:UpdateProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2709 token_variables!(),
2710 r#"){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{... on Issue{"#,
2711 board_issue_fields!(),
2712 r#"}}}}}"#
2713 );
2714 /// [`CLEAR_FIELD`], selecting the issue behind the board item cleared as
2715 /// [`UPDATE_ISSUE_TOKEN`] selects the issue it updates.
2716 pub const CLEAR_FIELD_TOKEN: &str = concat!(
2717 r#"mutation($input:ClearProjectV2ItemFieldValueInput!,$readPriority:Boolean!,$priorityName:String!"#,
2718 token_variables!(),
2719 r#"){clearProjectV2ItemFieldValue(input:$input){projectV2Item{id fieldValueByName(name:$priorityName) @include(if:$readPriority){... on ProjectV2ItemFieldSingleSelectValue{name field{... on ProjectV2SingleSelectField{id name options{id name}}}}} content{... on Issue{"#,
2720 board_issue_fields!(),
2721 r#"}}}}}"#
2722 );
2723
2724 /// The document a targeted update sends in `document`'s place, when it has one: the twin
2725 /// whose answer spells the change token of the issue written.
2726 #[must_use]
2727 pub fn token_twin(document: &str) -> Option<&'static str> {
2728 [
2729 (UPDATE_ISSUE, UPDATE_ISSUE_TOKEN),
2730 (UPDATE_FIELD, UPDATE_FIELD_TOKEN),
2731 (CLEAR_FIELD, CLEAR_FIELD_TOKEN),
2732 ]
2733 .into_iter()
2734 .find(|(plain, _)| *plain == document)
2735 .map(|(_, token)| token)
2736 }
2737
2738 /// The document sent in `document`'s place while a write the store's cache expects runs,
2739 /// when it has one.
2740 #[must_use]
2741 pub fn whole_twin(document: &str) -> Option<&'static str> {
2742 [
2743 (ADD_COMMENT, ADD_COMMENT_WHOLE),
2744 (UPDATE_COMMENT, UPDATE_COMMENT_WHOLE),
2745 (UPDATE_ISSUE, UPDATE_ISSUE_WHOLE),
2746 (UPDATE_FIELD, UPDATE_FIELD_WHOLE),
2747 (CLEAR_FIELD, CLEAR_FIELD_WHOLE),
2748 ]
2749 .into_iter()
2750 .find(|(plain, _)| *plain == document)
2751 .map(|(_, whole)| whole)
2752 }
2753
2754 /// The node id of one person by their login, as the aliased field `u0` answering `$login0`:
2755 /// what an assignee write names a person by, since `assigneeIds` takes node ids and a person
2756 /// is named by login.
2757 ///
2758 /// The inventoried form of the lookup. What is sent is this document sized to the call
2759 /// ([`user_ids`]): one `u<n>:user(login:$login<n>)` field per person the call names that
2760 /// this process has not resolved, so one request answers every one of them. GitHub answers a
2761 /// login it does not know with `null` at that alias beside a `NOT_FOUND` error naming it,
2762 /// and the others' ids beside them.
2763 pub const USER_IDS: &str = "query($login0:String!){ u0:user(login:$login0){id login}}";
2764
2765 /// [`USER_IDS`] for `people` logins — `$login0` to `$login<people - 1>`, each answered at
2766 /// its own alias — and [`USER_IDS`] itself for one.
2767 #[must_use]
2768 pub fn user_ids(people: usize) -> String {
2769 let people = people.max(1);
2770 let declared: Vec<String> = (0..people)
2771 .map(|slot| format!("$login{slot}:String!"))
2772 .collect();
2773 let fields: Vec<String> = (0..people)
2774 .map(|slot| format!("u{slot}:user(login:$login{slot}){{id login}}"))
2775 .collect();
2776 format!("query({}){{ {}}}", declared.join(","), fields.join(" "))
2777 }
2778
2779 /// The document a request sending `document` with `variables` really sends: [`USER_IDS`]
2780 /// sized to the logins `variables` binds, and every other document as it is.
2781 #[must_use]
2782 pub fn sized<'a>(
2783 document: &'a str,
2784 variables: &serde_json::Value,
2785 ) -> std::borrow::Cow<'a, str> {
2786 if document != USER_IDS {
2787 return std::borrow::Cow::Borrowed(document);
2788 }
2789 let people = (0..)
2790 .take_while(|slot| variables.get(format!("login{slot}")).is_some())
2791 .count();
2792 std::borrow::Cow::Owned(user_ids(people))
2793 }
2794
2795 /// The inventoried document `document` is an instance of: [`USER_IDS`] for any lookup
2796 /// [`user_ids`] sized, and `document` itself otherwise.
2797 #[must_use]
2798 pub fn inventoried(document: &str) -> &str {
2799 let people = document.matches(":user(login:$login").count();
2800 if people > 0 && user_ids(people) == document {
2801 USER_IDS
2802 } else {
2803 document
2804 }
2805 }
2806
2807 /// The selection of an issue's — or a draft's — assignees, as a source opted in to them
2808 /// (`config.assignees: true`) adds it to every document that reads one; see
2809 /// [`with_assignees`].
2810 const ASSIGNEES: &str = " assignees(first:$assigneeFirst){nodes{id login}}";
2811 /// The variable [`ASSIGNEES`] pages by, declared with its value as its default — the most
2812 /// people GitHub assigns one issue — so no caller binds it, and inserted first among a
2813 /// document's variables.
2814 const ASSIGNEE_VARIABLE: &str = "$assigneeFirst:Int!=10 ";
2815 /// [`ASSIGNEE_VARIABLE`] for a document declaring no variables of its own.
2816 const ASSIGNEE_VARIABLES: &str = "($assigneeFirst:Int!=10)";
2817 /// Where [`ASSIGNEES`] goes: straight after each of these, wherever an issue or a draft is
2818 /// read — what every read of an issue selects of it — and inside the answer of each
2819 /// `createIssue` and `updateIssue`, so a write's own answer says whom GitHub assigned.
2820 const ASSIGNEE_MARKERS: [&str; 2] = [
2821 "commentCount:comments{totalCount}",
2822 "title body createdAt updatedAt",
2823 ];
2824
2825 /// `document` as a source opted in to assignees sends it: [`ASSIGNEES`] selected wherever
2826 /// it reads an issue or a draft and in every `createIssue` and `updateIssue` answer, with the
2827 /// variable it pages by declared — or `None` when it reads and writes neither, and is sent
2828 /// as written.
2829 ///
2830 /// A rewrite of the one text sent rather than a second set of documents, so a source that
2831 /// has not opted in sends every document byte for byte as it did, and an opted-in one rides
2832 /// its assignees on the very reads and writes it already makes. [`without_assignees`] is its
2833 /// exact inverse, which the loopback board answers a document by.
2834 #[must_use]
2835 pub fn with_assignees(document: &str) -> Option<String> {
2836 let mut spelled = String::with_capacity(document.len() + 256);
2837 let mut inserted = false;
2838 let mut rest = document;
2839 while !rest.is_empty() {
2840 // The earliest place one is due, of every kind.
2841 let next = ASSIGNEE_MARKERS
2842 .iter()
2843 .filter_map(|marker| rest.find(marker).map(|at| (at + marker.len(), true)))
2844 .chain(["createIssue(", "updateIssue("].iter().filter_map(|write| {
2845 let at = rest.find(write)?;
2846 let open = at + rest[at..].find('{')?;
2847 rest[open..]
2848 .starts_with("{issue{id")
2849 .then_some((open + "{issue{id".len(), true))
2850 .or(Some((open, false)))
2851 }))
2852 .min_by_key(|(at, _)| *at);
2853 let Some((at, insert)) = next else {
2854 spelled.push_str(rest);
2855 break;
2856 };
2857 spelled.push_str(&rest[..at]);
2858 if insert {
2859 spelled.push_str(ASSIGNEES);
2860 inserted = true;
2861 }
2862 rest = &rest[at..];
2863 if !insert {
2864 // A write whose answer reads no issue's id first: past its opening brace.
2865 spelled.push('{');
2866 rest = &rest[1..];
2867 }
2868 }
2869 if !inserted {
2870 return None;
2871 }
2872 let open = spelled.find('(');
2873 let body = spelled.find('{');
2874 Some(match (open, body) {
2875 (Some(open), Some(body)) if open < body => {
2876 format!(
2877 "{}{ASSIGNEE_VARIABLE}{}",
2878 &spelled[..=open],
2879 &spelled[open + 1..]
2880 )
2881 }
2882 (_, Some(body)) => format!(
2883 "{}{ASSIGNEE_VARIABLES}{}",
2884 &spelled[..body],
2885 &spelled[body..]
2886 ),
2887 _ => return None,
2888 })
2889 }
2890
2891 /// `document` as [`with_assignees`] spelled it, back as the document it was written as — or
2892 /// `None` for a document it did not rewrite.
2893 #[must_use]
2894 pub fn without_assignees(document: &str) -> Option<String> {
2895 if !document.contains(ASSIGNEES) {
2896 return None;
2897 }
2898 let plain = document.replace(ASSIGNEES, "");
2899 Some(if plain.contains(ASSIGNEE_VARIABLES) {
2900 plain.replacen(ASSIGNEE_VARIABLES, "", 1)
2901 } else {
2902 plain.replacen(ASSIGNEE_VARIABLE, "", 1)
2903 })
2904 }
2905
2906 /// Every document above, with what this source is doing when it sends one.
2907 ///
2908 /// One list rather than a `match` beside the constants: a rate-limit diagnostic has to
2909 /// name the call that was refused, and a `match` with a catch-all arm would answer a
2910 /// document added later with "talking to GitHub" and never say so.
2911 ///
2912 /// `documents_are_all_inventoried` reads this file back and fails naming any `pub
2913 /// const` here that this list omits, so the two cannot part — which is the same guard
2914 /// `CATEGORIES` carries, in the one shape available to a set of `&str` constants.
2915 pub const DOCUMENTS: [(&str, &str); 71] = [
2916 (USER_IDS, "looking up the people an assignee write names"),
2917 (
2918 ISSUE_RELATIONS,
2919 "reading several issues with their parents and sub-issues",
2920 ),
2921 (SET_PARENTS, "writing several issues' parents"),
2922 (ADD_RELATES_TO, "adding several relates-to relations"),
2923 (REMOVE_RELATES_TO, "removing several relates-to relations"),
2924 (
2925 RELATES_TO_READS,
2926 "reading what several issues relate to after a relation write went unanswered",
2927 ),
2928 (
2929 ISSUES_BY_CREATION,
2930 "listing a repository's issues newest first for a create key",
2931 ),
2932 (SEARCH_ISSUES, "searching this board's issues"),
2933 (ISSUE, "reading one issue"),
2934 (
2935 DOCUMENT_IN_PROJECT,
2936 "reading one document with its project and the project's members",
2937 ),
2938 (
2939 ISSUE_BOARD_ITEMS,
2940 "reading one issue's board memberships past the page it came with",
2941 ),
2942 (SUB_ISSUES, "reading a project's tasks"),
2943 (BOARD, "reading the board"),
2944 (
2945 BOARD_WITH_COMMENTS,
2946 "reading a board page with first comments",
2947 ),
2948 (ORIGIN_LOOKUP, "looking up the items copied from one origin"),
2949 (CLOSED_ITEMS, "reading the board's closed items"),
2950 (OPEN_ITEMS, "reading the board's open items"),
2951 (CLOSE_ISSUE, "closing an issue as a duplicate"),
2952 (
2953 ISSUES_BY_REFERENCE,
2954 "reading a batch of issues by their references",
2955 ),
2956 (BOARD_FIELDS, "reading the board's fields"),
2957 (DRAFT, "reading one draft"),
2958 (REPOSITORY, "reading the destination repository"),
2959 (
2960 PROJECT_VISIBILITY,
2961 "reading whether the board's project is public",
2962 ),
2963 (
2964 CREATION_CONTEXT,
2965 "reading the board's fields and the destination repository",
2966 ),
2967 (ISSUE_DEPENDENCIES, "reading an issue's dependencies"),
2968 (ISSUE_DEPENDS_ON, "reading what an item depends on"),
2969 (ISSUE_DEPENDED_ON_BY, "reading what depends on an issue"),
2970 (CREATE_ISSUE, "creating an issue"),
2971 (
2972 ORIGIN_LOOKUPS,
2973 "looking up the items copied from several origins, and what creating one reads",
2974 ),
2975 (
2976 ORIGIN_LOOKUPS_WITH_MEMBERS,
2977 "looking up the items copied from several origins, with a project's members",
2978 ),
2979 (CREATE_ISSUES, "creating several issues together"),
2980 (
2981 CREATED_BOARD_ITEMS,
2982 "reading the board items of the issues a copy created",
2983 ),
2984 (
2985 WRITE_FIELD_VALUES,
2986 "writing board fields of the items a copy created",
2987 ),
2988 (
2989 WRITE_FIELDS_AND_EDGES,
2990 "writing board fields and dependencies of the items a copy created",
2991 ),
2992 (CLOSE_ISSUES, "closing the issues a copy created"),
2993 (UPDATE_ISSUES, "updating several issues together"),
2994 (ADD_BLOCKED_BYS, "recording several dependencies together"),
2995 (ADD_TO_BOARD, "adding an issue to the board"),
2996 (UPDATE_ISSUE, "updating an issue"),
2997 (UPDATE_DRAFT, "updating a draft item"),
2998 (UPDATE_FIELD, "writing a board field"),
2999 (UPDATE_FIELDS, "writing board fields together"),
3000 (CLEAR_FIELD, "clearing a board field"),
3001 (
3002 CREATE_FIELD,
3003 "creating a board single-select field with its options",
3004 ),
3005 (
3006 STATUS_OPTIONS_SNAPSHOT,
3007 "snapshotting board Status options and assignments",
3008 ),
3009 (
3010 STATUS_OPTIONS_UPDATE,
3011 "safely replacing the board Status option list",
3012 ),
3013 (ADD_SUB_ISSUE, "filing an issue under its project"),
3014 (REMOVE_SUB_ISSUE, "taking an issue out of its project"),
3015 (ADD_BLOCKED_BY, "recording a dependency"),
3016 (REMOVE_BLOCKED_BY, "removing a dependency"),
3017 (DELETE_ISSUE, "deleting an issue"),
3018 (DELETE_ISSUES, "deleting several issues together"),
3019 (ISSUE_COMMENTS, "reading a task's comments"),
3020 (ISSUE_DETAIL, "reading one issue with its comments"),
3021 (
3022 ISSUE_DETAILS,
3023 "reading a batch of issues with their comments",
3024 ),
3025 (
3026 ISSUE_COPY_DETAILS,
3027 "reading a batch of issues with their comments and dependencies for a copy",
3028 ),
3029 (COMMENT_ISSUE, "reading which issue a comment is on"),
3030 (ADD_COMMENT, "adding a comment"),
3031 (UPDATE_COMMENT, "editing a comment"),
3032 (DELETE_COMMENT, "deleting a comment"),
3033 (
3034 SEARCH_BATCH,
3035 "searching this board's issues several ways at once",
3036 ),
3037 (ADD_COMMENTS, "adding several comments together"),
3038 (WRITE_TASKS, "updating several tasks together"),
3039 (
3040 ADD_COMMENT_WHOLE,
3041 "adding a comment, answered with the whole issue",
3042 ),
3043 (
3044 UPDATE_COMMENT_WHOLE,
3045 "editing a comment, answered with the whole issue",
3046 ),
3047 (
3048 UPDATE_ISSUE_WHOLE,
3049 "updating an issue, answered with it whole",
3050 ),
3051 (
3052 UPDATE_FIELD_WHOLE,
3053 "writing a board field, answered with the whole issue",
3054 ),
3055 (
3056 CLEAR_FIELD_WHOLE,
3057 "clearing a board field, answered with the whole issue",
3058 ),
3059 (
3060 UPDATE_ISSUE_TOKEN,
3061 "updating an issue, answered with its version",
3062 ),
3063 (
3064 UPDATE_FIELD_TOKEN,
3065 "writing a board field, answered with the issue's version",
3066 ),
3067 (
3068 CLEAR_FIELD_TOKEN,
3069 "clearing a board field, answered with the issue's version",
3070 ),
3071 ];
3072}
3073
3074/// One aliased mutation field of [`graphql::UPDATE_FIELDS`]: the key its answer comes back
3075/// under, the variable carrying its input, and the boolean variable that includes it.
3076#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3077pub struct FieldSlot {
3078 /// The key of the answer's `data` this field's payload is under.
3079 pub alias: &'static str,
3080 /// The variable carrying this field's input.
3081 pub variable: &'static str,
3082 /// The boolean variable whose `true` sends this field.
3083 pub include: &'static str,
3084}
3085
3086/// The value writes [`graphql::UPDATE_FIELDS`] carries, in the order GitHub runs them.
3087pub const FIELD_WRITE_SLOTS: [FieldSlot; 6] = [
3088 FieldSlot {
3089 alias: "updateProjectV2ItemFieldValue",
3090 variable: "input",
3091 include: "writeFirst",
3092 },
3093 FieldSlot {
3094 alias: "second",
3095 variable: "second",
3096 include: "writeSecond",
3097 },
3098 FieldSlot {
3099 alias: "third",
3100 variable: "third",
3101 include: "writeThird",
3102 },
3103 FieldSlot {
3104 alias: "fourth",
3105 variable: "fourth",
3106 include: "writeFourth",
3107 },
3108 FieldSlot {
3109 alias: "fifth",
3110 variable: "fifth",
3111 include: "writeFifth",
3112 },
3113 FieldSlot {
3114 alias: "sixth",
3115 variable: "sixth",
3116 include: "writeSixth",
3117 },
3118];
3119
3120/// The clears [`graphql::UPDATE_FIELDS`] carries, run after every write of the same request.
3121pub const FIELD_CLEAR_SLOTS: [FieldSlot; 3] = [
3122 FieldSlot {
3123 alias: "cleared",
3124 variable: "clear",
3125 include: "writeClear",
3126 },
3127 FieldSlot {
3128 alias: "clearedSecond",
3129 variable: "clearSecond",
3130 include: "writeClearSecond",
3131 },
3132 FieldSlot {
3133 alias: "clearedThird",
3134 variable: "clearThird",
3135 include: "writeClearThird",
3136 },
3137];
3138
3139/// Which of GitHub's two rate limiters refused a request.
3140///
3141/// Waiting is the whole answer to the primary budget, and polling is what *extends* the
3142/// secondary one — so an operator told the wrong one takes the wrong next step, which is
3143/// the whole reason this is carried rather than collapsed into "rate limited".
3144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3145enum Limiter {
3146 /// The hourly API budget, which `gh api rate_limit` reports and a wait answers.
3147 Primary,
3148 /// The burst limiter over content-generating requests, which nothing reports.
3149 Secondary,
3150}
3151
3152/// The wordings GitHub answers a secondary rate limit with.
3153///
3154/// It sends them under a forbidden status, under a too-many-requests status, and inside
3155/// the `errors` of a *successful* response, which is why the text is what this matches on
3156/// rather than the status. `abuse detection` is the wording GitHub used before the
3157/// limiter was renamed and still returns from some endpoints; `submitted too quickly` is
3158/// what a burst of content creation is refused with.
3159///
3160/// This is GitHub's vocabulary rather than this source's, so it is pinned rather than
3161/// remembered: `tests/fixtures/rate-limits.json` records where each wording was read and
3162/// when, and the drift gate reconciles the two lists both ways. Public for that gate
3163/// alone — a caller has no use for it, and matching on a refusal is this source's job.
3164pub const SECONDARY_WORDINGS: [&str; 5] = [
3165 "secondary rate limit",
3166 "temporarily blocked from content creation",
3167 "abuse detection",
3168 "submitted too quickly",
3169 "exceeded a secondary",
3170];
3171
3172/// The wordings GitHub answers an exhausted primary budget with.
3173///
3174/// `rate_limited` is the `type` its GraphQL error carries, which is read as a field rather
3175/// than looked for in the response text. `api rate limit already exceeded` is what GraphQL
3176/// answers a request made once the hour's budget is spent — "API rate limit already exceeded
3177/// for user ID …" in the `errors` of an HTTP 200, with no `type` — and neither of the other
3178/// two phrases is a substring of it, so without it that answer read as a refusal that will
3179/// never lift. Pinned and gated exactly as [`SECONDARY_WORDINGS`] is, and public for the same
3180/// one reason.
3181pub const PRIMARY_WORDINGS: [&str; 4] = [
3182 "api rate limit exceeded",
3183 "api rate limit already exceeded",
3184 "rate limit exceeded",
3185 "rate_limited",
3186];
3187
3188/// The wordings GitHub answers a write that collided with another change to the same
3189/// ordering with, in the `errors` of an HTTP 200: "Your attempt to move this item created a
3190/// temporary conflict. Please try again." The write did not take effect and GitHub asks for it
3191/// again, so it is retried on the same growing schedule a rate limit without a hint is, within
3192/// the same retry budget — except a `createIssue`, whose answer cannot say the issue was not
3193/// made, and which is therefore reported rather than replayed into a duplicate.
3194///
3195/// Observed rather than documented, so it is pinned exactly as [`SECONDARY_WORDINGS`] is:
3196/// `tests/fixtures/rate-limits.json` records where it was read under `conflict.observed`, and
3197/// the same drift gate reconciles the two both ways. Public for that gate alone.
3198pub const CONFLICT_WORDINGS: [&str; 1] = ["created a temporary conflict"];
3199
3200/// What a response *says about itself*, which is the only place a refusal can be read.
3201///
3202/// Deliberately not the whole response body. A board is a place people write about their
3203/// own work, and a task on it titled "the secondary rate limit" would, matched across the
3204/// raw text, turn a perfectly good answer into a refusal this source then waited out and
3205/// reported. So the item data is never read: what is read is GitHub's own REST-style
3206/// `message` envelope, which is what a forbidden status carries, and the `message` and
3207/// `type` of each GraphQL error, which is where a *successful* response says it.
3208///
3209/// A body that is not JSON at all has nothing structured to read, so only a failing
3210/// response's own text is taken — a successful response that is not JSON is malformed
3211/// rather than refused, and [`GitHubProjectsSource::answer`] says so.
3212fn refusal_wording(status: StatusCode, body: &str) -> String {
3213 let Ok(parsed) = serde_json::from_str::<Value>(body) else {
3214 return if status.is_success() {
3215 String::new()
3216 } else {
3217 body.to_owned()
3218 };
3219 };
3220 let mut said: Vec<&str> = parsed
3221 .get("message")
3222 .and_then(Value::as_str)
3223 .into_iter()
3224 .collect();
3225 if let Some(errors) = parsed.get("errors").and_then(Value::as_array) {
3226 for error in errors {
3227 said.extend(
3228 ["message", "type"]
3229 .into_iter()
3230 .filter_map(|key| error.get(key).and_then(Value::as_str)),
3231 );
3232 }
3233 }
3234 said.join("; ")
3235}
3236
3237impl Limiter {
3238 /// Which limiter refused this response, or `None` when none of them did.
3239 ///
3240 /// The wording is read first and the status only decides what carries none of it,
3241 /// because GitHub answers a secondary limit with a forbidden status far more often
3242 /// than with too-many-requests — while a forbidden status saying nothing about a limit
3243 /// really is a credential this token lacks.
3244 ///
3245 /// A response is a refusal because of its status or its own wording. A spent budget
3246 /// only ever explains one; it never turns an answer into a refusal.
3247 fn classify(status: StatusCode, budget_exhausted: bool, body: &str) -> Option<Self> {
3248 let normalized = refusal_wording(status, body).to_ascii_lowercase();
3249 if SECONDARY_WORDINGS
3250 .iter()
3251 .any(|wording| normalized.contains(wording))
3252 {
3253 return Some(Self::Secondary);
3254 }
3255 if status == StatusCode::TOO_MANY_REQUESTS {
3256 return Some(Self::Primary);
3257 }
3258 // An exhausted budget *explains* a response that failed; it does not make one that
3259 // succeeded into a failure. GitHub sets `x-ratelimit-remaining: 0` on the last
3260 // request the budget allowed as well as on the ones it then refuses, so reading
3261 // the header alone threw away a good answer — and, once refusals were retried,
3262 // replayed a request that had already taken effect.
3263 if !status.is_success() && budget_exhausted {
3264 return Some(Self::Primary);
3265 }
3266 // A successful response saying it: GitHub reports a GraphQL rate limit in the
3267 // `errors` of an HTTP 200, where nothing about the status says so at all.
3268 if status.is_success()
3269 && PRIMARY_WORDINGS
3270 .iter()
3271 .any(|wording| normalized.contains(wording))
3272 {
3273 return Some(Self::Primary);
3274 }
3275 None
3276 }
3277
3278 /// What this limiter is called where an operator can look it up.
3279 const fn name(self) -> &'static str {
3280 match self {
3281 Self::Primary => "GitHub's primary API rate limit",
3282 Self::Secondary => "GitHub's secondary rate limit",
3283 }
3284 }
3285
3286 /// What the endpoint an operator would go and check says about this limiter.
3287 const fn where_to_look(self) -> &'static str {
3288 match self {
3289 Self::Primary => {
3290 "That is the budget `gh api rate_limit` reports, so that endpoint says when it \
3291 comes back."
3292 }
3293 Self::Secondary => {
3294 "That limiter is not the primary API budget: `gh api rate_limit` reports the \
3295 primary budget and does not report this one, so budget showing there says \
3296 nothing about this refusal, and every further attempt extends it."
3297 }
3298 }
3299 }
3300
3301 /// The next step this limiter actually calls for.
3302 const fn what_to_do(self) -> &'static str {
3303 match self {
3304 Self::Primary => {
3305 "wait for the reset `gh api rate_limit` reports, then run the command again."
3306 }
3307 Self::Secondary => {
3308 "leave this board alone for a few minutes, then run the command again — or \
3309 raise pacing.min_mutation_interval_ms on this source so it writes more slowly."
3310 }
3311 }
3312 }
3313}
3314
3315/// One rate-limit refusal, and the wait GitHub asked for if it asked for one.
3316#[derive(Debug, Clone, Copy)]
3317struct Limited {
3318 limiter: Limiter,
3319 hint: Option<u64>,
3320 /// Which header the hint came from: `retry-after`, or an exhausted primary budget's
3321 /// `x-ratelimit-reset`.
3322 hinted_by: Hint,
3323}
3324
3325/// Where a refusal's hint came from, which is what its wait is named after.
3326#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3327enum Hint {
3328 /// `retry-after`, or no hint at all.
3329 RetryAfter,
3330 /// An exhausted primary budget's `x-ratelimit-reset`.
3331 PrimaryReset,
3332}
3333
3334impl Limited {
3335 /// The wait this refusal is answered with, when the backing-off schedule is at `backoff`,
3336 /// and the cause it is named by: the hint, raised to the schedule's own next wait —
3337 /// GitHub really does send `retry-after: 0`, and retrying at once is the one move that
3338 /// extends a secondary limit — or the schedule alone when there is none.
3339 fn wait(self, backoff: Duration) -> (Duration, WaitCause) {
3340 match (self.hint, self.hinted_by) {
3341 (Some(hint), Hint::RetryAfter) => (
3342 Duration::from_secs(hint).max(backoff),
3343 pacing::cause::RETRY_AFTER,
3344 ),
3345 (Some(hint), Hint::PrimaryReset) => (
3346 Duration::from_secs(hint).max(backoff),
3347 pacing::cause::PRIMARY_RESET,
3348 ),
3349 (None, _) => (backoff, pacing::cause::BACKOFF),
3350 }
3351 }
3352
3353 /// What the caller is told once this source has waited as long as it may.
3354 ///
3355 /// Both limiters report as [`SourceError::RateLimited`], because that is what
3356 /// happened: the kind a caller matches on says a rate limit refused this, and nothing
3357 /// about *which* limiter it was makes it a different kind of failure. What differs is
3358 /// the operator's next step, and that is what the message carries — a secondary
3359 /// refusal read as a primary one sends an operator to `gh api rate_limit`, where the
3360 /// budget looks fine, and then back to retry the very burst that was refused.
3361 fn exhausted(
3362 self,
3363 doing: &str,
3364 waits: u32,
3365 waited: Duration,
3366 needed: Duration,
3367 budget: Duration,
3368 ) -> SourceError {
3369 SourceError::RateLimited {
3370 retry_after_seconds: self.hint,
3371 message: Some(format!(
3372 "{} refused this source while {doing}; it waited {} out over {} and was refused \
3373 again, and the next wait of {} would take it past the {} one call may spend \
3374 waiting. {} next: {}",
3375 self.limiter.name(),
3376 plural(waits, "refusal"),
3377 seconds(waited),
3378 seconds(needed),
3379 seconds(budget),
3380 self.limiter.where_to_look(),
3381 self.limiter.what_to_do(),
3382 )),
3383 }
3384 }
3385}
3386
3387/// One HTTP attempt's result, with what its response said about the rate limit.
3388///
3389/// The two travel together so the record and the outcome are written from the same place:
3390/// what a response said about the budget is only readable while that response is in hand,
3391/// and what the attempt *meant* is only decidable once its body has been read.
3392struct Attempted {
3393 result: Result<Value, Attempt>,
3394 limits: accounting::RateLimit,
3395 /// GitHub's own reported cost for this call, for a document that asked for it.
3396 reported_cost: Option<u64>,
3397 response_outcome: accounting::ResponseOutcome,
3398}
3399
3400/// One attempt's outcome: an error to report, or a rate limit to wait out.
3401enum Attempt {
3402 Failed(SourceError),
3403 Limited(Limited),
3404 /// GitHub refused a write as a temporary conflict and asked for it again — see
3405 /// [`CONFLICT_WORDINGS`]. Carries what GitHub said, for the diagnostic once retrying ends.
3406 Conflicted(String),
3407}
3408
3409fn plural(count: u32, thing: &str) -> String {
3410 if count == 1 {
3411 format!("{count} {thing}")
3412 } else {
3413 format!("{count} {thing}s")
3414 }
3415}
3416
3417fn seconds(duration: Duration) -> String {
3418 format!("{:.1}s", duration.as_secs_f64())
3419}
3420
3421/// The member [`stamp_served`] writes onto every node of a response that says when it last
3422/// changed: the `Date` that response was served at. No GitHub type has a field of this name.
3423const SERVED_AT: &str = "onetaskgraphServedAt";
3424
3425/// Write `served` onto every object of `data` carrying an `updatedAt`, so whatever reads a
3426/// node's time later knows the server's clock on the response that read it — which is what
3427/// decides whether that node's change token is given (see [`change_token::SETTLED`]).
3428fn stamp_served(data: &mut Value, served: &str) {
3429 match data {
3430 Value::Object(members) => {
3431 if members.contains_key("updatedAt") {
3432 members.insert(SERVED_AT.to_owned(), Value::String(served.to_owned()));
3433 }
3434 for member in members.values_mut() {
3435 stamp_served(member, served);
3436 }
3437 }
3438 Value::Array(items) => {
3439 for item in items {
3440 stamp_served(item, served);
3441 }
3442 }
3443 _ => {}
3444 }
3445}
3446
3447/// A header GitHub spells as a whole number of seconds, or `None` when this one is not.
3448///
3449/// A value that is present and unreadable is deliberately *not* an error. `retry-after` is
3450/// allowed by HTTP to be a date rather than a count, an intermediary can rewrite either
3451/// header, and neither is what makes a response a refusal — so the whole cost of one this
3452/// cannot read is that the refusal carries no hint and the backing-off schedule answers it
3453/// instead. Refusing the response over the header would turn a readable refusal into an
3454/// unreadable one, and refusing to *wait* would be the one wrong direction to fail in.
3455fn whole_seconds(value: Option<&reqwest::header::HeaderValue>) -> Option<u64> {
3456 value
3457 .and_then(|value| value.to_str().ok())
3458 .and_then(|value| value.trim().parse::<u64>().ok())
3459}
3460
3461/// A transport failure with every cause beneath it, outermost first.
3462///
3463/// The client's own text for a request it could not complete is `error sending request for
3464/// url (…)`, and the socket error that says why — a refused or reset connection, an exhausted
3465/// port range, a connection closed before its answer — is only in the chain of sources below
3466/// it. Those differ in what to do next, so all of them are kept.
3467pub(crate) fn transport_error(error: &(dyn std::error::Error + 'static)) -> String {
3468 let mut text = error.to_string();
3469 let mut cause = error.source();
3470 while let Some(next) = cause {
3471 let said = next.to_string();
3472 if !text.ends_with(&said) {
3473 text = format!("{text}: {said}");
3474 }
3475 cause = next.source();
3476 }
3477 text
3478}
3479
3480/// Every mutation this source sends creates content — an issue, a board item, a field of
3481/// one, a sub-issue link, a dependency, a comment — or edits or removes content of that
3482/// kind, and no query in [`graphql::DOCUMENTS`] does, so what the secondary limiter counts
3483/// and what the keyword says are the same set. That is what makes the keyword a sound test
3484/// rather than a convenient one: counting an edit or a removal the limiter might not have
3485/// counted costs a wait, and not counting one it did count costs the next fifty minutes.
3486pub(crate) fn is_mutation(query: &str) -> bool {
3487 query.trim_start().starts_with("mutation")
3488}
3489
3490/// What this source was doing, for a diagnostic that has to say so.
3491///
3492/// Read out of [`graphql::DOCUMENTS`], which is the inventory rather than a copy of it, so
3493/// a document added without a description is caught by that list's own gate instead of
3494/// falling through to the vague arm below.
3495fn operation_description(query: &str) -> &'static str {
3496 let query = graphql::inventoried(query);
3497 graphql::DOCUMENTS
3498 .iter()
3499 .find(|(document, _)| *document == query)
3500 .map_or("talking to GitHub", |(_, doing)| *doing)
3501}
3502
3503/// GitHub's published ceiling on content-generating requests in any one minute.
3504///
3505/// Pinned in `tests/fixtures/rate-limits.json` and gated against it, because it is
3506/// GitHub's number rather than this source's. This source paces at it over its window: a
3507/// content-creating request goes out at once while the minute's creations leave room for it,
3508/// and waits until they do otherwise — see the `pacing` module.
3509pub const CONTENT_CREATION_PER_MINUTE: u64 = 80;
3510/// The same ceiling as GitHub publishes it for any one hour, paced over its window as the
3511/// per-minute one is. Pinned beside its sibling so the gate would notice either one moving.
3512pub const CONTENT_CREATION_PER_HOUR: u64 = 500;
3513/// GitHub's published ceiling on secondary points in any one minute: what every GraphQL
3514/// request is charged against, a mutation [`SECONDARY_POINTS_PER_MUTATION`] and a query
3515/// [`SECONDARY_POINTS_PER_QUERY`]. Pinned and paced as [`CONTENT_CREATION_PER_MINUTE`] is.
3516pub const SECONDARY_POINTS_PER_MINUTE: u64 = 2_000;
3517/// The secondary points one GraphQL request carrying a mutation is charged.
3518pub const SECONDARY_POINTS_PER_MUTATION: u64 = 5;
3519/// The secondary points one GraphQL request carrying no mutation is charged.
3520pub const SECONDARY_POINTS_PER_QUERY: u64 = 1;
3521/// The fastest *steady* spacing of content-creating mutations that cannot exceed
3522/// [`CONTENT_CREATION_PER_MINUTE`], in milliseconds: 60000/80 is 750.
3523///
3524/// It is no longer the default. This source paces by GitHub's windows instead, so a copy's
3525/// few dozen writes go out as fast as GitHub answers them while the minute has room, rather
3526/// than 750 ms apart — which was most of a plan copy's wall time. An installation that wants
3527/// mutations spaced as well says so through `pacing.min_mutation_interval_ms`, and this is the
3528/// value that holds a long sustained burst under the per-minute bound by spacing alone.
3529pub const MIN_MUTATION_INTERVAL_MS: u64 = 60_000 / CONTENT_CREATION_PER_MINUTE;
3530/// First wait when a rate-limit refusal carries no hint; each further wait doubles it.
3531///
3532/// A doubling schedule from one second reaches a minute in six waits, which is GitHub's
3533/// own advice for a secondary limit — wait, and wait longer each time — without spending
3534/// the first minute of a transient refusal doing nothing.
3535pub const RETRY_BACKOFF_MS: u64 = 1_000;
3536/// Total time one call may spend waiting out rate limits before it reports a failure.
3537///
3538/// Two minutes is long enough to ride out the refusals a paced copy still collects and
3539/// short enough that a command an operator is watching returns. The bound is what makes
3540/// the wait a wait rather than a hang: a call refused past it ends in a diagnostic naming
3541/// the limiter, not in a process nobody can tell from a wedged one.
3542pub const RETRY_BUDGET_MS: u64 = 120_000;
3543
3544fn default_token_env() -> String {
3545 "GH_PROJECTS_TOKEN".to_owned()
3546}
3547fn default_endpoint() -> String {
3548 "https://api.github.com/graphql".to_owned()
3549}
3550
3551/// The name of a `Status` single-select option on the board.
3552///
3553/// Validated on the way in rather than checked later, so a blank option name — which
3554/// nothing on a board can be — is a state this type cannot hold.
3555#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3556#[serde(try_from = "String")]
3557#[schemars(extend("minLength" = 1))]
3558pub struct ColumnName(String);
3559
3560impl ColumnName {
3561 /// The option name, as the board spells it.
3562 fn as_str(&self) -> &str {
3563 &self.0
3564 }
3565}
3566
3567impl TryFrom<String> for ColumnName {
3568 type Error = String;
3569
3570 fn try_from(name: String) -> Result<Self, Self::Error> {
3571 if name.trim().is_empty() {
3572 return Err("a status_mapping option name cannot be blank".to_owned());
3573 }
3574 Ok(Self(name))
3575 }
3576}
3577
3578/// The two closed states this product can mean.
3579///
3580/// GitHub's `IssueClosedStateReason` also spells `DUPLICATE`, which nothing here ever writes:
3581/// an issue closed as one *reads* `cancelled`, because its work is another issue's, but this
3582/// product never decides on a person's behalf that two issues are the same work.
3583#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, schemars::JsonSchema)]
3584#[serde(rename_all = "kebab-case")]
3585pub enum ClosedState {
3586 /// `COMPLETED` — precisely done.
3587 Completed,
3588 /// `NOT_PLANNED` — precisely cancelled.
3589 NotPlanned,
3590}
3591
3592impl ClosedState {
3593 const fn reason(self) -> &'static str {
3594 match self {
3595 Self::Completed => "COMPLETED",
3596 Self::NotPlanned => "NOT_PLANNED",
3597 }
3598 }
3599}
3600
3601/// Configuration for one GitHub Projects v2 board.
3602///
3603/// It serializes to a document this same type reads back as itself, so a caller writing a
3604/// configuration — a consumer filing onto a board it configures — can build one here rather
3605/// than spell the shape again; an empty `metadata_fields` is left out, as one never set.
3606#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3607#[serde(default, deny_unknown_fields)]
3608pub struct GitHubProjectsConfig {
3609 /// Login of the user or organization which owns the board.
3610 pub owner: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates GitHub's owner grammar before private construction.
3611 /// The project number shown in the board's GitHub URL.
3612 pub project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` bounds this to a positive GraphQL Int.
3613 // 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.
3614 /// `owner/name` of the repository this source creates an issue in when the item's own
3615 /// `repositories` field does not decide it.
3616 ///
3617 /// An item naming exactly one repository is created there — on a source declared
3618 /// `visibility: private`, only when that repository reads private, and otherwise as an
3619 /// item naming none is; a task or a document naming none or several is created in its
3620 /// parent project's repository; and a project, or a task or document with no parent,
3621 /// naming none or several is created here. A board
3622 /// has no repository of its own and `createIssue` requires one, so a write without
3623 /// this is refused naming the field. Reads never need it.
3624 pub repository: Option<String>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the `owner/name` grammar before private construction.
3625 // llmlint: ignore-end[contracts_have_one_source_or_a_drift_gate]
3626 /// GitHub logins whose repositories this source may create an issue in.
3627 ///
3628 /// Absent or empty, the default, restricts nothing. Otherwise a create whose issue the
3629 /// rule `repository` describes would file in a repository owned by anyone else is refused
3630 /// before anything of it is written — by `task copy`, `task copy --create`, a member
3631 /// create of a project copy and a dry run of each — with the error kind `creation-owner`,
3632 /// naming the repository and these owners. Logins compare case-insensitively, as GitHub
3633 /// compares them. An update of an issue that already exists is never refused by it.
3634 /// `task locate` reports such a refusal as `creates_in.refused` rather than failing.
3635 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3636 // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
3637 // list out, so both SDKs model an absent list as an empty one rather than as `null`.
3638 #[schemars(!skip_serializing_if)]
3639 pub creation_owners: Vec<String>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates each entry against GitHub's login grammar, naming the one it refuses.
3640 /// Environment variable containing a fine-grained token with Projects and Issues
3641 /// read/write plus Pull requests read-only access for every repository represented on
3642 /// the board.
3643 #[serde(default = "default_token_env")]
3644 pub token_env: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the environment-variable grammar.
3645 /// GraphQL endpoint. GitHub Enterprise installations may override it.
3646 #[serde(default = "default_endpoint")]
3647 pub endpoint: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` converts it to the private validated `Url`.
3648 /// Per-instance mapping from a status category to the option of the board's one
3649 /// `Status` field it lands on, for a task and for a project.
3650 ///
3651 /// The shared `StatusMapping` grammar: each value is one option name for both kinds,
3652 /// `null` to disable the category for both, or `{task, project}` naming it per kind,
3653 /// where a kind left out leaves the category unmapped for that kind. A category this
3654 /// does not mention keeps its shipped default for both kinds: `backlog` to "Backlog",
3655 /// `todo` to "Todo", `queued` to "Queued", `in-progress` to "In Progress", `done` to
3656 /// "Done" plus closed as completed, `cancelled` to "Cancelled" plus closed as not
3657 /// planned, and `draft`, `in-review` and `unknown` unmapped. A category it does mention
3658 /// gets no shipped default for a kind it leaves out. `done` and `cancelled` close the issue for
3659 /// either kind. No two categories may name one option for the same kind, ignoring case.
3660 /// `unknown` may name one existing option; every unknown word then lands on it and
3661 /// reads back as `unknown` under its name. Unlike `local-md`, this source cannot keep
3662 /// each unknown word because it never creates board options.
3663 #[serde(default)]
3664 pub status_mapping: StatusMapping,
3665 /// Per-instance mapping from a task's priority to an option of this board's
3666 /// single-select field named `Priority`.
3667 ///
3668 /// Absent, this source holds no priority: every task reads as `none`, and a write of any
3669 /// other priority is refused before it reaches this board. Present, each of `urgent`,
3670 /// `high`, `medium` and `low` it does not mention keeps its shipped default — `Urgent`,
3671 /// `High`, `Medium` and `Low` — and an item with no value in the `Priority` field reads
3672 /// as `none`, so writing `none` clears the value. Option names match case-insensitively;
3673 /// no two levels may name one option. Reads and writes never create the field or an
3674 /// option: `onetaskgraph sources fields <source> --apply` does, and a write naming one
3675 /// the board lacks is refused pointing there.
3676 #[serde(default)]
3677 pub priority_mapping: Option<PriorityMappingConfig>,
3678 /// Caller metadata values this source also writes to board text fields, so the board can
3679 /// filter on them.
3680 ///
3681 /// Absent or empty, nothing is projected. Each entry names a board text `field`, a
3682 /// top-level metadata `key` and an optional `path` of object keys walked inside that key's
3683 /// value. On every item write — create, update and copy, of a task, a project or a
3684 /// document — a string found there is written to the field, an array of strings as one
3685 /// line per element and an object of string values as one `KEY: VALUE` line per entry in
3686 /// byte order of the keys, shortened to whole lines and a count of the rest past the
3687 /// field's 1,024-byte limit; nothing is sent when the field already holds that text;
3688 /// nothing there, or `null`, clears the field when it holds a value; any other JSON type
3689 /// is refused before any mutation. `docs/metadata.md` states the rule. The metadata comment in the
3690 /// issue body stays the one home of the value, and every read reports metadata from it.
3691 /// Reads and writes never create the field: `onetaskgraph sources fields <source>
3692 /// --apply` does, as a text field, and a write to a board lacking it, or holding a
3693 /// non-text field of that name, is refused pointing there.
3694 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3695 // Kept in the schema as `"default": []` although a serialized configuration leaves an empty
3696 // list out, so both SDKs model an absent list as an empty one rather than as `null`.
3697 #[schemars(!skip_serializing_if)]
3698 pub metadata_fields: Vec<MetadataFieldConfig>,
3699 /// How fast this source writes, and how long it waits out a rate-limit refusal.
3700 ///
3701 /// Every field keeps its shipped default when it is absent, and the defaults are
3702 /// GitHub's own published limits rather than taste. See [`Pacing`].
3703 #[serde(default)]
3704 pub pacing: PacingConfig,
3705 /// What an issue's sub-issues mean on this board.
3706 ///
3707 /// `project`, the default, is this source's meaning since it was first written: an issue
3708 /// with sub-issues reads as a project and its sub-issues as that project's tasks. `parent`
3709 /// reads every issue as a task and a sub-issue as a child under the parent relation, which
3710 /// `task parent set-many` writes and `task relations` reads; a project write to such a
3711 /// source is refused naming this setting. The two meanings answer differently for the same
3712 /// issues, so a `parent` source needs a board of its own: two sources naming one board with
3713 /// different `sub_issues` are refused when the configuration is read.
3714 #[serde(default, skip_serializing_if = "SubIssues::is_project")]
3715 pub sub_issues: SubIssues,
3716 /// The link types this source also writes as GitHub's own `relates-to` relation, beside the
3717 /// store's metadata, so they show in the issue's Relationships panel: each type name mapped
3718 /// to `{"native": "relates-to"}`. A type not named here is kept in metadata alone. Any other
3719 /// word — `blocks`, `blocked-by`, `duplicate`, `similar` among them — is refused when the
3720 /// source is built.
3721 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
3722 // Kept in the schema as `"default": {}` although a serialized configuration leaves an empty
3723 // map out, so both SDKs model an absent map as an empty one rather than as `null`.
3724 #[schemars(!skip_serializing_if)]
3725 pub link_types: BTreeMap<String, onetaskgraph_plugin_api::LinkTypeConfig>,
3726 /// Whether this source's tasks carry the GitHub users each issue is assigned to, and
3727 /// take an assignee write. `false`, the default, reads no issue's assignees and writes
3728 /// none: every request this source sends is then exactly what it was before assignees
3729 /// existed. `true` reads each issue's assignees on the reads it already makes, and writes
3730 /// one person or none — by login — in the `createIssue` or `updateIssue` the write already
3731 /// sends, refusing a person GitHub does not know or leaves off the issue.
3732 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3733 // Kept in the schema as `"default": false` although a serialized configuration leaves a
3734 // `false` out, so both SDKs model an absent setting as `false` rather than as `null`.
3735 #[schemars(!skip_serializing_if)]
3736 pub assignees: bool,
3737}
3738
3739/// What an issue's sub-issues mean on a GitHub Projects board: see
3740/// [`GitHubProjectsConfig::sub_issues`].
3741#[derive(
3742 Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema,
3743)]
3744#[serde(rename_all = "kebab-case")]
3745pub enum SubIssues {
3746 /// An issue with sub-issues is a project, and its sub-issues are its tasks.
3747 #[default]
3748 Project,
3749 /// Every issue is a task, and a sub-issue is a child under the parent relation.
3750 Parent,
3751}
3752
3753impl SubIssues {
3754 /// Whether this is the default meaning, which a serialized configuration leaves out.
3755 #[must_use]
3756 pub const fn is_project(&self) -> bool {
3757 matches!(self, Self::Project)
3758 }
3759}
3760
3761/// Which option of the board's `Priority` field each priority lands on.
3762///
3763/// One member per level rather than a map, so a key that is not a level is refused where
3764/// the configuration is read, naming the levels there are. `none` is not a member: it is no
3765/// value in the field, not an option of it.
3766#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3767#[serde(default, deny_unknown_fields)]
3768pub struct PriorityMappingConfig {
3769 /// The option `urgent` lands on; `Urgent` when absent.
3770 pub urgent: Option<PriorityOptionName>,
3771 /// The option `high` lands on; `High` when absent.
3772 pub high: Option<PriorityOptionName>,
3773 /// The option `medium` lands on; `Medium` when absent.
3774 pub medium: Option<PriorityOptionName>,
3775 /// The option `low` lands on; `Low` when absent.
3776 pub low: Option<PriorityOptionName>,
3777}
3778
3779/// The name of an option of the board's `Priority` single-select field.
3780///
3781/// Validated on the way in, for the reason [`ColumnName`] is: nothing on a board can have a
3782/// blank name.
3783#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3784#[serde(try_from = "String")]
3785#[schemars(extend("minLength" = 1))]
3786pub struct PriorityOptionName(String);
3787
3788impl PriorityOptionName {
3789 /// The option name, as the board spells it.
3790 fn as_str(&self) -> &str {
3791 &self.0
3792 }
3793}
3794
3795impl TryFrom<String> for PriorityOptionName {
3796 type Error = String;
3797
3798 fn try_from(name: String) -> Result<Self, Self::Error> {
3799 if name.trim().is_empty() {
3800 return Err("a priority_mapping option name cannot be blank".to_owned());
3801 }
3802 Ok(Self(name))
3803 }
3804}
3805
3806/// The name of the board field a priority is held in.
3807pub const PRIORITY_FIELD: &str = "Priority";
3808
3809/// The four priorities a board option can hold, in the order a new `Priority` field lists
3810/// them. `none` is not among them: it is the field holding no value.
3811///
3812/// This list mirrors `Priority`, so it carries its own drift gate, in the shape [`CATEGORIES`]
3813/// does: [`level_position`] is a wildcard-free match, so a priority added to the shared
3814/// vocabulary fails to compile until it is placed there, and this crate's suite reconciles
3815/// this list and [`PriorityMappingConfig`]'s members against that enum's own derived schema.
3816pub const PRIORITY_LEVELS: [Priority; 4] = [
3817 Priority::Urgent,
3818 Priority::High,
3819 Priority::Medium,
3820 Priority::Low,
3821];
3822
3823/// Where one priority sits in [`PRIORITY_LEVELS`], or `None` for `none`, which is no option;
3824/// see that list for what this pins.
3825#[must_use]
3826pub const fn level_position(priority: Priority) -> Option<usize> {
3827 match priority {
3828 Priority::None => None,
3829 Priority::Urgent => Some(0),
3830 Priority::High => Some(1),
3831 Priority::Medium => Some(2),
3832 Priority::Low => Some(3),
3833 }
3834}
3835
3836/// This instance's complete priority-to-option mapping, read in both directions.
3837///
3838/// One option per level, held in [`PRIORITY_LEVELS`] order, once it is established that no
3839/// two levels name one option.
3840#[derive(Debug, Clone)]
3841struct PriorityMapping {
3842 options: [PriorityOptionName; 4],
3843}
3844
3845impl PriorityMapping {
3846 fn resolve(config: PriorityMappingConfig, instance: &SourceName) -> Result<Self, SourceError> {
3847 let shipped = |name: &str| PriorityOptionName(name.to_owned());
3848 let mapping = Self {
3849 options: [
3850 config.urgent.unwrap_or_else(|| shipped("Urgent")),
3851 config.high.unwrap_or_else(|| shipped("High")),
3852 config.medium.unwrap_or_else(|| shipped("Medium")),
3853 config.low.unwrap_or_else(|| shipped("Low")),
3854 ],
3855 };
3856 for (index, option) in mapping.options.iter().enumerate() {
3857 if let Some(earlier) = mapping.options[..index]
3858 .iter()
3859 .position(|other| other.as_str().eq_ignore_ascii_case(option.as_str()))
3860 {
3861 return Err(SourceError::Config {
3862 message: format!(
3863 "priority_mapping of source {instance} sends both {} and {} to the board \
3864 option {:?}; one option cannot read back as two priorities",
3865 PRIORITY_LEVELS[earlier],
3866 PRIORITY_LEVELS[index],
3867 option.as_str()
3868 ),
3869 });
3870 }
3871 }
3872 Ok(mapping)
3873 }
3874
3875 /// The option `priority` lands on, or `None` for `none`, which is no option at all.
3876 fn option(&self, priority: Priority) -> Option<&str> {
3877 level_position(priority).map(|index| self.options[index].as_str())
3878 }
3879
3880 /// The priority a board option name reports, or `None` when nothing maps to it.
3881 fn priority_of(&self, option: &str) -> Option<Priority> {
3882 self.options
3883 .iter()
3884 .position(|name| name.as_str().eq_ignore_ascii_case(option))
3885 .map(|index| PRIORITY_LEVELS[index])
3886 }
3887
3888 /// Every mapped option name, in the order a new `Priority` field lists them.
3889 fn names(&self) -> impl Iterator<Item = &str> {
3890 self.options.iter().map(PriorityOptionName::as_str)
3891 }
3892}
3893
3894/// One metadata value this source projects onto a board text field.
3895#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
3896#[serde(deny_unknown_fields)]
3897pub struct MetadataFieldConfig {
3898 /// The name of the board text field the value is written to.
3899 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.
3900 /// The top-level metadata key the value is read from. A key under the reserved
3901 /// `onetaskgraph.` prefix is refused.
3902 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.
3903 /// Object keys walked inside that key's value, outermost first. Absent or empty, the
3904 /// key's own value is the one projected. Left out of a serialized entry when empty.
3905 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3906 // Kept in the schema as `"default": []`, for the reason `metadata_fields`' is.
3907 #[schemars(!skip_serializing_if)]
3908 pub path: Vec<String>,
3909}
3910
3911/// The board fields no metadata value may be projected onto, compared ignoring case: the
3912/// three this source writes itself, and those GitHub owns on every board.
3913// 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.
3914const UNPROJECTABLE_FIELDS: [&str; 13] = [
3915 STATUS_FIELD,
3916 PRIORITY_FIELD,
3917 ORIGIN_FIELD,
3918 "Title",
3919 "Assignees",
3920 "Labels",
3921 "Linked pull requests",
3922 "Milestone",
3923 "Repository",
3924 "Reviewers",
3925 "Parent issue",
3926 "Sub-issues progress",
3927 "Type",
3928];
3929
3930/// One validated [`MetadataFieldConfig`] entry.
3931#[derive(Debug, Clone)]
3932struct MetadataField {
3933 field: ProjectedField,
3934 key: ProjectedKey,
3935 path: Vec<String>,
3936}
3937
3938/// The name of a board text field a metadata value is projected onto: never blank, never one
3939/// this source or GitHub writes, and never one another entry of the same source names.
3940#[derive(Debug, Clone, PartialEq, Eq)]
3941struct ProjectedField(String);
3942
3943/// The top-level metadata key a projected value is read from: never blank, and never under
3944/// the namespace this product reserves.
3945#[derive(Debug, Clone, PartialEq, Eq)]
3946struct ProjectedKey(String);
3947
3948impl std::ops::Deref for ProjectedField {
3949 type Target = str;
3950 fn deref(&self) -> &str {
3951 &self.0
3952 }
3953}
3954
3955impl std::ops::Deref for ProjectedKey {
3956 type Target = str;
3957 fn deref(&self) -> &str {
3958 &self.0
3959 }
3960}
3961
3962/// What one item's metadata says one projected field should hold.
3963#[derive(Debug, Clone, PartialEq, Eq)]
3964enum Projected {
3965 /// A string to hold.
3966 Text(String),
3967 /// Nothing: the key or a step of the path is absent, or the value is `null`.
3968 Nothing,
3969}
3970
3971impl MetadataField {
3972 /// Validate every entry of one instance's `metadata_fields`, refusing the first that
3973 /// cannot stand, naming the source and the entry.
3974 fn resolve(
3975 configured: Vec<MetadataFieldConfig>,
3976 instance: &SourceName,
3977 ) -> Result<Vec<Self>, SourceError> {
3978 let mut resolved: Vec<Self> = Vec::with_capacity(configured.len());
3979 for (index, entry) in configured.into_iter().enumerate() {
3980 let refuse = |why: String| SourceError::Config {
3981 message: format!(
3982 "metadata_fields[{index}] of source {instance} (field {:?}, key {:?}) {why}",
3983 entry.field, entry.key
3984 ),
3985 };
3986 if let Some(why) = ProjectedValue::entry_refusal(
3987 &entry.field,
3988 &entry.key,
3989 resolved.iter().map(|other| &*other.field),
3990 "board field",
3991 ) {
3992 return Err(refuse(why));
3993 }
3994 if let Some(owned) = UNPROJECTABLE_FIELDS
3995 .iter()
3996 .find(|owned| owned.eq_ignore_ascii_case(&entry.field))
3997 {
3998 return Err(refuse(format!(
3999 "names the board field {owned:?}, which this source or GitHub already \
4000 writes; next: name a text field of your own"
4001 )));
4002 }
4003 resolved.push(Self {
4004 field: ProjectedField(entry.field),
4005 key: ProjectedKey(entry.key),
4006 path: entry.path,
4007 });
4008 }
4009 Ok(resolved)
4010 }
4011
4012 /// The path as a refusal spells it: `[]` for the key's own value.
4013 fn spelled_path(&self) -> String {
4014 serde_json::to_string(&self.path).unwrap_or_else(|_| format!("{:?}", self.path))
4015 }
4016
4017 /// What `metadata` says this field should hold, or the refusal for a value no text field
4018 /// can hold.
4019 fn projected(
4020 &self,
4021 metadata: &BTreeMap<String, Value>,
4022 instance: &SourceName,
4023 ) -> Result<Projected, SourceError> {
4024 let found = match ProjectedValue::read(metadata, &self.key, &self.path) {
4025 Ok(None) => return Ok(Projected::Nothing),
4026 Ok(Some(value)) => return Ok(Projected::Text(field_text(&value))),
4027 Err(found) => found,
4028 };
4029 Err(SourceError::Refused {
4030 message: format!(
4031 "source {instance} projects metadata key {:?} at path {} onto its board text \
4032 field {:?}, and this item holds {found} there; only a string, an array of \
4033 strings, an object of string values, null or nothing can be written to a text \
4034 field; next: store one of those there, or remove the value",
4035 &*self.key,
4036 self.spelled_path(),
4037 &*self.field
4038 ),
4039 })
4040 }
4041}
4042
4043/// The most a ProjectV2 text field holds, in UTF-8 bytes.
4044///
4045/// Spike `spike-sample-ticket` measured it on a live board through this store with ASCII
4046/// values: 1,024 accepted, 1,025 refused whole with `Column value must be a valid value for
4047/// text column`, and nothing on the item changed. GitHub documents neither the limit nor its
4048/// unit, so this source counts UTF-8 bytes — at least as many as characters or UTF-16 units —
4049/// which can only shorten a non-ASCII value earlier than GitHub would, never send one it
4050/// refuses.
4051// llmlint: ignore[contracts_have_one_source_or_a_drift_gate] GitHub publishes no machine-readable statement of this limit — neither its documentation nor its GraphQL schema (`ProjectV2FieldValue.text: String`) names one — so the only source is the measurement above, and a live probe would spend the credentialed lane's budget, which is a decision outside this change. Drift cannot pass silently either way: a raised limit only shortens a value earlier than needed, and a lowered one makes GitHub refuse the write, which fails the command naming the field.
4052pub const TEXT_FIELD_LIMIT: usize = 1024;
4053
4054/// The text a board text field holds for `value`, as `docs/metadata.md` states it: a string as
4055/// itself, an array's elements and an object's `KEY: VALUE` entries — in byte order of the
4056/// keys — one per line, joined by one line feed; and, over [`TEXT_FIELD_LIMIT`], the longest
4057/// prefix of whole lines that fits beside one line feed and the line counting the rest.
4058fn field_text(value: &ProjectedValue) -> String {
4059 let rendered = match value {
4060 ProjectedValue::Text(text) => text.clone(),
4061 ProjectedValue::List(list) => list.join("\n"),
4062 ProjectedValue::Map(map) => map
4063 .iter()
4064 .map(|(key, value)| format!("{key}: {value}"))
4065 .collect::<Vec<_>>()
4066 .join("\n"),
4067 };
4068 if rendered.len() <= TEXT_FIELD_LIMIT {
4069 return rendered;
4070 }
4071 let lines: Vec<&str> = rendered.split('\n').collect();
4072 let elided = |left_out: usize| {
4073 let noun = if left_out == 1 { "line" } else { "lines" };
4074 format!("\u{2026} {left_out} more {noun} in this item's metadata")
4075 };
4076 // The bytes the first `kept` lines take with the line feeds between them.
4077 let mut prefix = 0;
4078 let mut fits = 0;
4079 for (kept, line) in lines.iter().enumerate().map(|(at, line)| (at + 1, line)) {
4080 prefix += line.len() + usize::from(kept > 1);
4081 if kept == lines.len() || prefix + 1 + elided(lines.len() - kept).len() > TEXT_FIELD_LIMIT {
4082 break;
4083 }
4084 fits = kept;
4085 }
4086 if fits == 0 {
4087 return elided(lines.len());
4088 }
4089 format!(
4090 "{}\n{}",
4091 lines[..fits].join("\n"),
4092 elided(lines.len() - fits)
4093 )
4094}
4095
4096/// What one item's `Priority` field says, read through this instance's mapping.
4097#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
4098enum HeldPriority {
4099 /// A priority this source reports: an option the mapping names, or no value (`none`).
4100 Read(Priority),
4101 /// An option the mapping does not name, which is never read as a level or as `none`.
4102 Unmapped(String),
4103}
4104
4105/// How fast this source writes, and how long it waits out a rate-limit refusal.
4106///
4107/// Configurable because a GitHub Enterprise installation sets its own limits and an
4108/// operator who has already been refused may want to go slower still — not because the
4109/// defaults are guesses.
4110#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
4111#[serde(default, deny_unknown_fields)]
4112pub struct PacingConfig {
4113 /// Shortest interval between two content-creating mutations, in milliseconds.
4114 ///
4115 /// Zero sends them as fast as they are asked for, which is what a fixture server on
4116 /// loopback wants and what no board on github.com does. At most [`MAX_PACING_MS`].
4117 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.
4118 /// First wait when a rate-limit refusal carries no hint, in milliseconds. Each
4119 /// further wait of the same call doubles it. At most [`MAX_PACING_MS`], and never
4120 /// zero while there is a budget to spend, because a schedule of zero-length waits
4121 /// consumes none of it and so never ends.
4122 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.
4123 /// Total time one call may spend waiting out rate limits, in milliseconds.
4124 ///
4125 /// Zero reports the refusal rather than waiting at all. At most [`MAX_PACING_MS`]:
4126 /// the bound is what makes this a wait rather than a hang.
4127 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.
4128}
4129
4130/// The largest any pacing setting may be, in milliseconds.
4131///
4132/// One hour. GitHub's own harshest published bound on content-generating requests works
4133/// out at one every 7.2 seconds, so an hour is already three orders of magnitude past
4134/// anything a real limit asks for, and past it the settings stop describing pacing at all:
4135/// a wait budget beyond it is the unbounded wait this whole mechanism exists to replace,
4136/// and an interval beyond it is a command that never sends its second mutation. It also
4137/// keeps the clock arithmetic in [`GitHubProjectsSource::reserve_mutation_slot`] inside
4138/// what a `Duration` can hold on every platform.
4139pub const MAX_PACING_MS: u64 = 3_600_000;
4140
4141/// [`PacingConfig`] with every default resolved and every value checked, which is what the
4142/// source holds.
4143///
4144/// Unset, `min_mutation_interval_ms` spaces nothing, and every request is paced by GitHub's
4145/// secondary windows alone — see the `pacing` module; set, it spaces content-creating mutations
4146/// on top of those windows, [`MIN_MUTATION_INTERVAL_MS`] being the spacing that holds a sustained
4147/// burst under the per-minute bound by spacing alone; and zero sends every request as fast as it
4148/// is asked for, windows included.
4149#[derive(Debug, Clone, Copy)]
4150struct Pacing {
4151 /// Whether requests are held for GitHub's secondary windows: always, unless
4152 /// `min_mutation_interval_ms` is set to exactly zero, which has always asked for no
4153 /// pacing at all — what a fixture server on loopback wants and no board on github.com does.
4154 windows: bool,
4155 min_mutation_interval: Duration,
4156 retry_backoff: Duration,
4157 retry_budget: Duration,
4158}
4159
4160impl Pacing {
4161 /// Resolve one instance's pacing, refusing a configuration that would not pace at all.
4162 fn resolve(config: PacingConfig, instance: &SourceName) -> Result<Self, SourceError> {
4163 let bounded = |value: Option<u64>, default: u64, field: &str| match value {
4164 Some(value) if value > MAX_PACING_MS => Err(SourceError::Config {
4165 message: format!(
4166 "pacing.{field} of source {instance} is {value} ms, and the most any pacing \
4167 setting may be is {MAX_PACING_MS} ms — an hour, which is already far past \
4168 GitHub's own harshest published limit"
4169 ),
4170 }),
4171 Some(value) => Ok(Duration::from_millis(value)),
4172 None => Ok(Duration::from_millis(default)),
4173 };
4174 let retry_backoff = bounded(
4175 config.retry_backoff_ms,
4176 RETRY_BACKOFF_MS,
4177 "retry_backoff_ms",
4178 )?;
4179 let retry_budget = bounded(config.retry_budget_ms, RETRY_BUDGET_MS, "retry_budget_ms")?;
4180 if retry_backoff.is_zero() && !retry_budget.is_zero() {
4181 return Err(SourceError::Config {
4182 message: format!(
4183 "pacing.retry_backoff_ms of source {instance} is 0 while \
4184 pacing.retry_budget_ms is {} ms; a schedule of zero-length waits spends \
4185 none of that budget, so it would retry a refusal forever. Set a backoff of \
4186 at least 1 ms, or set retry_budget_ms to 0 to report a refusal without \
4187 waiting at all",
4188 retry_budget.as_millis()
4189 ),
4190 });
4191 }
4192 Ok(Self {
4193 windows: config.min_mutation_interval_ms != Some(0),
4194 min_mutation_interval: bounded(
4195 config.min_mutation_interval_ms,
4196 0,
4197 "min_mutation_interval_ms",
4198 )?,
4199 retry_backoff,
4200 retry_budget,
4201 })
4202 }
4203}
4204
4205/// Factory for [`GitHubProjectsSource`].
4206#[derive(Debug, Clone, Copy, Default)]
4207pub struct Plugin;
4208
4209impl SourcePlugin for Plugin {
4210 fn kind(&self) -> &'static str {
4211 KIND
4212 }
4213 /// The endpoint, the owner and the board's number: what names one board.
4214 fn remote_identity(&self, config: &Value) -> Option<String> {
4215 let config: GitHubProjectsConfig = serde_json::from_value(config.clone()).ok()?;
4216 Some(format!(
4217 "{}\n{}\n{}",
4218 config.endpoint, config.owner, config.project_number
4219 ))
4220 }
4221 fn config_schema(&self) -> Schema {
4222 schema_for!(GitHubProjectsConfig)
4223 }
4224 fn build(
4225 &self,
4226 name: &SourceName,
4227 config: &Value,
4228 secrets: &dyn SecretResolver,
4229 ) -> Result<Box<dyn TaskSource>, SourceError> {
4230 self.build_recording_into(name, config, secrets, Arc::new(Accounting::new()))
4231 }
4232
4233 fn build_with_clock(
4234 &self,
4235 name: &SourceName,
4236 config: &Value,
4237 secrets: &dyn SecretResolver,
4238 clock: SharedClock,
4239 ) -> Result<Box<dyn TaskSource>, SourceError> {
4240 self.build_recording_with_clock(name, config, secrets, Arc::new(Accounting::new()), clock)
4241 }
4242}
4243
4244/// The client `cell` holds, building it with `build` the first time it is asked for.
4245///
4246/// A failed build is the request's failure, with the message the source's construction gave it
4247/// before clients were deferred.
4248// llmlint: ignore[changed_behavior_has_e2e] A client build fails only when the TLS backend cannot initialise, which nothing outside the process can induce: a certificate bundle of garbage still builds one. That the build is deferred is proven end to end by `store_startup::a_command_builds_no_client_for_a_source_it_sends_nothing`.
4249fn built(
4250 cell: &std::sync::OnceLock<Client>,
4251 build: impl FnOnce() -> Result<Client, SourceError>,
4252) -> Result<&Client, SourceError> {
4253 if let Some(client) = cell.get() {
4254 return Ok(client);
4255 }
4256 let client = build()?;
4257 Ok(cell.get_or_init(|| client))
4258}
4259
4260impl Plugin {
4261 /// Build a source recording every request it sends into an accounting the caller holds.
4262 ///
4263 /// [`SourcePlugin::build`] is this with an accounting of its own, which is what the
4264 /// registry gets. This is for a caller that is also calling GitHub itself and wants one
4265 /// session total rather than two — see [`accounting`] and
4266 /// [`GitHubProjectsSource::recording_into`].
4267 ///
4268 /// # Errors
4269 ///
4270 /// Exactly [`SourcePlugin::build`]'s, with the same source name in front of each:
4271 /// [`SourceError::Config`] for configuration this plugin cannot use and
4272 /// [`SourceError::Auth`] for a credential it cannot find.
4273 pub fn build_recording_into(
4274 &self,
4275 name: &SourceName,
4276 config: &Value,
4277 secrets: &dyn SecretResolver,
4278 ledger: Arc<Accounting>,
4279 ) -> Result<Box<dyn TaskSource>, SourceError> {
4280 self.build_recording_with_clock(name, config, secrets, ledger, system_clock())
4281 }
4282
4283 fn build_recording_with_clock(
4284 &self,
4285 name: &SourceName,
4286 config: &Value,
4287 secrets: &dyn SecretResolver,
4288 ledger: Arc<Accounting>,
4289 clock: SharedClock,
4290 ) -> Result<Box<dyn TaskSource>, SourceError> {
4291 let config: GitHubProjectsConfig =
4292 serde_json::from_value(config.clone()).map_err(|e| SourceError::Config {
4293 message: format!("source {name}: {e}"),
4294 })?;
4295 let prefix = format!("source {name}: ");
4296 let mut source = GitHubProjectsSource::recording_into(name, config, secrets, ledger)
4297 .map_err(|error| match error {
4298 // The shared `StatusMapping::distinct` names the source itself.
4299 SourceError::Config { message } if message.starts_with(&prefix) => {
4300 SourceError::Config { message }
4301 }
4302 SourceError::Config { message } => SourceError::Config {
4303 message: format!("{prefix}{message}"),
4304 },
4305 SourceError::Auth { message } => SourceError::Auth {
4306 message: format!("source {name}: {message}"),
4307 },
4308 other => other,
4309 })?;
4310 source.clock = clock;
4311 Ok(Box::new(source))
4312 }
4313}
4314
4315/// Where a status category lands on this board, once configuration is resolved.
4316#[derive(Debug, Clone, PartialEq, Eq)]
4317enum StatusTarget {
4318 /// Not usable against this instance for this kind, and why.
4319 Disabled(UnmappedStatus),
4320 /// The board's `Status` option of this name.
4321 Column(ColumnName),
4322 /// A closed issue, with both its board option and the reason that says which closed it means.
4323 // 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.
4324 Terminal(ColumnName, ClosedState),
4325}
4326
4327/// Every status category, in the order the vocabulary declares them.
4328///
4329/// This list mirrors `StatusCategory`, so it carries its own drift gate rather than a
4330/// reviewer's attention: [`category_position`] is a wildcard-free match, so a variant
4331/// added to the shared vocabulary fails to compile until it is named there, and this
4332/// crate's suite reconciles this list against that enum's own derived schema, which is
4333/// generated from the variants rather than written beside them. The schema is what
4334/// catches a list left one short — a list checking only the positions it already holds
4335/// would pass while every mapping indexed by the new position panicked.
4336pub const CATEGORIES: [StatusCategory; 9] = [
4337 StatusCategory::Draft,
4338 StatusCategory::Backlog,
4339 StatusCategory::Todo,
4340 StatusCategory::Queued,
4341 StatusCategory::InProgress,
4342 StatusCategory::InReview,
4343 StatusCategory::Done,
4344 StatusCategory::Cancelled,
4345 StatusCategory::Unknown,
4346];
4347
4348/// Where one category sits in [`CATEGORIES`]; see that list for what this pins.
4349#[must_use]
4350pub const fn category_position(category: StatusCategory) -> usize {
4351 match category {
4352 StatusCategory::Draft => 0,
4353 StatusCategory::Backlog => 1,
4354 StatusCategory::Todo => 2,
4355 StatusCategory::Queued => 3,
4356 StatusCategory::InProgress => 4,
4357 StatusCategory::InReview => 5,
4358 StatusCategory::Done => 6,
4359 StatusCategory::Cancelled => 7,
4360 StatusCategory::Unknown => 8,
4361 }
4362}
4363
4364/// The spelling a status category is configured and reported under.
4365fn category_name(category: StatusCategory) -> &'static str {
4366 match category {
4367 StatusCategory::Draft => "draft",
4368 StatusCategory::Backlog => "backlog",
4369 StatusCategory::Todo => "todo",
4370 StatusCategory::Queued => "queued",
4371 StatusCategory::InProgress => "in-progress",
4372 StatusCategory::InReview => "in-review",
4373 StatusCategory::Done => "done",
4374 StatusCategory::Cancelled => "cancelled",
4375 StatusCategory::Unknown => "unknown",
4376 }
4377}
4378
4379/// A shipped default's option name.
4380///
4381/// The literals below are this file's own and non-blank, and they are validated by the
4382/// one constructor a configured name goes through rather than beside it.
4383fn shipped_column(name: &'static str) -> ColumnName {
4384 ColumnName::try_from(name.to_owned()).expect("a shipped default names a board option")
4385}
4386
4387/// The shipped default for one category this instance's `status_mapping` does not mention,
4388/// for either kind.
4389fn shipped_default(category: StatusCategory) -> StatusTarget {
4390 match category {
4391 StatusCategory::Backlog => StatusTarget::Column(shipped_column("Backlog")),
4392 StatusCategory::Todo => StatusTarget::Column(shipped_column("Todo")),
4393 StatusCategory::Queued => StatusTarget::Column(shipped_column("Queued")),
4394 StatusCategory::InProgress => StatusTarget::Column(shipped_column("In Progress")),
4395 StatusCategory::Done => {
4396 StatusTarget::Terminal(shipped_column("Done"), ClosedState::Completed)
4397 }
4398 StatusCategory::Cancelled => {
4399 StatusTarget::Terminal(shipped_column("Cancelled"), ClosedState::NotPlanned)
4400 }
4401 // No board ships a review column, so `in-review` is written and read only where a
4402 // mapping names one, and a board without it reads exactly as before.
4403 StatusCategory::Draft | StatusCategory::InReview | StatusCategory::Unknown => {
4404 StatusTarget::Disabled(UnmappedStatus::Unconfigured)
4405 }
4406 }
4407}
4408
4409/// The two kinds a status is written and read for, each with its own half of the mapping.
4410const STATUS_KINDS: [ItemKind; 2] = [ItemKind::Task, ItemKind::Project];
4411
4412/// This instance's complete category-to-target mapping for each kind, read in both
4413/// directions.
4414///
4415/// One target per category per kind, held at that category's own [`category_position`], so
4416/// a category missing from the mapping, named twice in it, or filed out of order is a state
4417/// this type cannot hold rather than one [`Self::target`] has to defend against. Both kinds'
4418/// targets are options of the board's one `Status` field.
4419#[derive(Debug, Clone)]
4420struct BoardStatuses {
4421 tasks: [StatusTarget; CATEGORIES.len()],
4422 projects: [StatusTarget; CATEGORIES.len()],
4423}
4424
4425impl BoardStatuses {
4426 /// Resolve `configured` against the shipped defaults, refusing two categories one kind
4427 /// would read back from one option.
4428 ///
4429 /// A category the mapping does not mention keeps its shipped default for both kinds; one
4430 /// it does mention is exactly what it configures, so a per-kind object leaves the kind it
4431 /// omits unmapped rather than defaulted.
4432 fn resolve(configured: &StatusMapping, instance: &SourceName) -> Result<Self, SourceError> {
4433 let resolve_kind =
4434 |kind: ItemKind| -> Result<[StatusTarget; CATEGORIES.len()], SourceError> {
4435 // `CATEGORIES[position] == category` for every category — the crate's suite
4436 // asserts it — so mapping the list in order fills each category's own slot.
4437 let mut targets = CATEGORIES.map(shipped_default);
4438 for (slot, category) in targets.iter_mut().zip(CATEGORIES) {
4439 if !configured.mentions(category) {
4440 continue;
4441 }
4442 *slot = match configured.name_for(category, kind) {
4443 Err(why) => StatusTarget::Disabled(why),
4444 Ok(name) => {
4445 let option = ColumnName::try_from(name.as_str().to_owned())
4446 .map_err(|message| SourceError::Config { message })?;
4447 match category {
4448 StatusCategory::Done => {
4449 StatusTarget::Terminal(option, ClosedState::Completed)
4450 }
4451 StatusCategory::Cancelled => {
4452 StatusTarget::Terminal(option, ClosedState::NotPlanned)
4453 }
4454 _ => StatusTarget::Column(option),
4455 }
4456 }
4457 };
4458 }
4459 StatusMapping::distinct(
4460 instance,
4461 kind,
4462 CATEGORIES
4463 .iter()
4464 .zip(&targets)
4465 .filter_map(|(category, target)| target.option().map(|o| (*category, o))),
4466 )?;
4467 Ok(targets)
4468 };
4469 Ok(Self {
4470 tasks: resolve_kind(ItemKind::Task)?,
4471 projects: resolve_kind(ItemKind::Project)?,
4472 })
4473 }
4474
4475 /// Every category's target for `kind`, in category order.
4476 const fn targets(&self, kind: ItemKind) -> &[StatusTarget; CATEGORIES.len()] {
4477 match kind {
4478 ItemKind::Task => &self.tasks,
4479 ItemKind::Project => &self.projects,
4480 }
4481 }
4482
4483 fn target(&self, kind: ItemKind, category: StatusCategory) -> &StatusTarget {
4484 &self.targets(kind)[category_position(category)]
4485 }
4486
4487 /// The category a board option name reports for `kind`, or `None` when nothing of that
4488 /// kind maps to it.
4489 fn category_of(&self, kind: ItemKind, option: &str) -> Option<StatusCategory> {
4490 CATEGORIES.into_iter().find(|category| {
4491 self.target(kind, *category)
4492 .option()
4493 .is_some_and(|name| name.eq_ignore_ascii_case(option))
4494 })
4495 }
4496
4497 /// Every option name either kind maps a category to, each once ignoring case, in
4498 /// category order with a task's name before a project's — what the guarded setup asks
4499 /// the `Status` field to hold.
4500 fn wanted(&self) -> Vec<String> {
4501 let mut wanted: Vec<String> = Vec::new();
4502 for category in CATEGORIES {
4503 for kind in STATUS_KINDS {
4504 if let Some(name) = self.target(kind, category).option()
4505 && !wanted.iter().any(|held| held.eq_ignore_ascii_case(name))
4506 {
4507 wanted.push(name.to_owned());
4508 }
4509 }
4510 }
4511 wanted
4512 }
4513
4514 /// The status an item of `kind` reports, from the three things a read of it says: its
4515 /// board `Status` option, whether its issue is closed, and the reason it was closed with.
4516 ///
4517 /// **A closed issue's category follows its closure**, by [`closed_category`]: completed
4518 /// or no reason reads `done`, not planned and duplicate read `cancelled`, and any other
4519 /// reason reads `unknown`. `REOPENED`-while-closed is a state this source can never
4520 /// produce, so it is read permissively rather than refused — reads are faithful, and
4521 /// refusals belong on writes.
4522 ///
4523 /// **Its name follows the closure too, unless the option agrees with it.** The option's
4524 /// own name is kept when this kind's mapping reads that option as the same category, or
4525 /// does not name it at all — so a closed issue in a "Shipped" column reports `done`
4526 /// named `Shipped`. An option the mapping reads as another category contradicts the
4527 /// closure, and so does no option at all: the name is then the option the mapping gives
4528 /// the closure's category, so an issue closed as completed at `Todo` reads `done` named
4529 /// by the board's `done` option, and a destination reading `Todo` as todo is never handed
4530 /// it. An `unknown` closure keeps the option, or `Closed` without one.
4531 ///
4532 /// An open item's option reads through its own kind's mapping, and an option that mapping
4533 /// does not name reads as `Unknown` under its own name.
4534 ///
4535 /// One function of those three rather than of a response, so a narrow status write can
4536 /// answer what a re-read would report by applying it to the state it has just written.
4537 fn status(
4538 &self,
4539 kind: ItemKind,
4540 option: Option<&str>,
4541 closed: bool,
4542 reason: Option<&str>,
4543 ) -> Status {
4544 if closed {
4545 let category = closed_category(reason);
4546 let agrees = option.filter(|option| {
4547 category == StatusCategory::Unknown
4548 || self
4549 .category_of(kind, option)
4550 .is_none_or(|read| read == category)
4551 });
4552 let name = agrees.or_else(|| self.target(kind, category).option());
4553 let fallback = match category {
4554 StatusCategory::Done => "Done",
4555 StatusCategory::Cancelled => "Cancelled",
4556 _ => "Closed",
4557 };
4558 return Status {
4559 category,
4560 name: name.or(option).unwrap_or(fallback).to_owned(),
4561 };
4562 }
4563 let name = option.unwrap_or("Open").to_owned();
4564 Status {
4565 category: self
4566 .category_of(kind, &name)
4567 .unwrap_or(StatusCategory::Unknown),
4568 name,
4569 }
4570 }
4571
4572 /// The option a closed item's `Status` has to hold for its card to agree with its
4573 /// closure, and the category that closure reads as — or `None` when the item is open,
4574 /// its closure reads `unknown`, or its option already agrees.
4575 ///
4576 /// What `task status reconcile` writes: only `done` and `cancelled` closures are brought
4577 /// in line, each to the one option the mapping gives its category — an item with no
4578 /// option, or at one the mapping does not name, included.
4579 fn contradicted(
4580 &self,
4581 kind: ItemKind,
4582 option: Option<&str>,
4583 closed: bool,
4584 reason: Option<&str>,
4585 ) -> Option<(ClosedAs, &str)> {
4586 if !closed {
4587 return None;
4588 }
4589 let closed_as = match closed_category(reason) {
4590 StatusCategory::Done => ClosedAs::Done,
4591 StatusCategory::Cancelled => ClosedAs::Cancelled,
4592 _ => return None,
4593 };
4594 let wanted = self.target(kind, closed_as.category()).option()?;
4595 if option.is_some_and(|option| option.eq_ignore_ascii_case(wanted)) {
4596 return None;
4597 }
4598 Some((closed_as, wanted))
4599 }
4600}
4601
4602/// The category a closed issue reads as, from the reason it was closed with.
4603///
4604/// `COMPLETED`, and no reason at all, is finished work; `NOT_PLANNED` and `DUPLICATE` are both
4605/// work nobody will do here — a duplicate's work is the other issue's — and any other reason
4606/// is one this source cannot read a category from.
4607fn closed_category(reason: Option<&str>) -> StatusCategory {
4608 match reason {
4609 None | Some("COMPLETED") => StatusCategory::Done,
4610 Some("NOT_PLANNED" | "DUPLICATE") => StatusCategory::Cancelled,
4611 Some(_) => StatusCategory::Unknown,
4612 }
4613}
4614
4615impl BoardStatuses {
4616 /// For each kind, the option names it maps a category to that `existing` lacks, ignoring
4617 /// case; a kind lacking none is left out.
4618 fn missing_by_kind(&self, existing: &[StatusOption]) -> Vec<KindMissing> {
4619 STATUS_KINDS
4620 .into_iter()
4621 .filter_map(|kind| {
4622 let missing: Vec<String> = self
4623 .targets(kind)
4624 .iter()
4625 .filter_map(StatusTarget::option)
4626 .filter(|wanted| {
4627 !existing
4628 .iter()
4629 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
4630 })
4631 .map(str::to_owned)
4632 .collect();
4633 (!missing.is_empty()).then_some(KindMissing { kind, missing })
4634 })
4635 .collect()
4636 }
4637}
4638
4639impl StatusTarget {
4640 /// The board option this target selects, or `None` for an unmapped one.
4641 fn option(&self) -> Option<&str> {
4642 match self {
4643 Self::Column(name) | Self::Terminal(name, _) => Some(name.as_str()),
4644 Self::Disabled(_) => None,
4645 }
4646 }
4647}
4648
4649// 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.
4650/// One repository this source can create an issue in, as `owner/name`.
4651///
4652/// Every `createIssue` this source sends names one of these: the item's own single
4653/// `repositories` entry — on a source declared private, only when it reads private — else
4654/// its parent project issue's repository, else the configured
4655/// [`GitHubProjectsConfig::repository`]. [`GitHubProjectsSource::creation_target`] makes
4656/// that choice and says what it refuses before `createIssue`.
4657// llmlint: ignore-end[comments_earn_their_place, contracts_have_one_source_or_a_drift_gate]
4658#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
4659#[serde(try_from = "String", into = "String")]
4660struct RepositoryTarget {
4661 owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
4662 name: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only after `owner/name` validation in `new`.
4663}
4664
4665impl RepositoryTarget {
4666 fn parse(value: &str) -> Result<Self, SourceError> {
4667 let (owner, name) = value.split_once('/').ok_or_else(|| SourceError::Config {
4668 message: format!(
4669 "repository must be spelled owner/name; {value:?} names no repository"
4670 ),
4671 })?;
4672 if !valid_github_owner(owner) || !valid_github_repository_name(name) {
4673 return Err(SourceError::Config {
4674 message: format!(
4675 "repository must be spelled owner/name with a GitHub login and one \
4676 repository name; {value:?} is not"
4677 ),
4678 });
4679 }
4680 Ok(Self {
4681 owner: owner.to_owned(),
4682 name: name.to_owned(),
4683 })
4684 }
4685
4686 /// The one host whose repositories this source creates issues in, spelled once: it is
4687 /// what [`Self::origin`] renders and what [`Self::from_origin`] accepts.
4688 const HOST: &str = "github.com";
4689
4690 fn origin(&self) -> String {
4691 format!("{}/{}/{}", Self::HOST, self.owner, self.name)
4692 }
4693
4694 /// The repository a normalized origin names, or why it is none this source can create
4695 /// an issue in: another host, or more or fewer than `owner/name` under this one.
4696 fn from_origin(origin: &Repository) -> Result<Self, String> {
4697 let not_here = || {
4698 format!(
4699 "{} is not a {}/owner/name repository",
4700 origin.as_str(),
4701 Self::HOST
4702 )
4703 };
4704 let (host, rest) = origin.as_str().split_once('/').ok_or_else(not_here)?;
4705 if host != Self::HOST {
4706 return Err(not_here());
4707 }
4708 Self::parse(rest).map_err(|_| not_here())
4709 }
4710
4711 fn slug(&self) -> String {
4712 format!("{}/{}", self.owner, self.name)
4713 }
4714}
4715
4716/// Read back from a kept context as the `owner/name` it was written as, refused unless
4717/// [`RepositoryTarget::parse`] takes it.
4718impl TryFrom<String> for RepositoryTarget {
4719 type Error = String;
4720
4721 fn try_from(slug: String) -> Result<Self, Self::Error> {
4722 Self::parse(&slug).map_err(|error| error.to_string())
4723 }
4724}
4725
4726impl From<RepositoryTarget> for String {
4727 fn from(target: RepositoryTarget) -> Self {
4728 target.slug()
4729 }
4730}
4731
4732/// How long GitHub's issue search may go on missing a comment after it was made or edited,
4733/// which a read of the comments made since an instant sets its watermark back by: four times the
4734/// thirty seconds the credentialed lane has watched it lag.
4735pub const COMMENT_SEARCH_LAG: std::time::Duration = std::time::Duration::from_secs(120);
4736
4737/// A source which reads GitHub afresh for every operation.
4738pub struct GitHubProjectsSource {
4739 /// This source's configured name, used both to tell a far end naming this source
4740 /// from one naming a system it knows nothing about, and to name the instance a
4741 /// status refusal is about.
4742 name: SourceName,
4743 owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after full GitHub-owner validation.
4744 project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after GraphQL-Int validation.
4745 repository: Option<RepositoryTarget>,
4746 /// The logins whose repositories a create may file in; empty restricts nothing.
4747 creation_owners: Vec<String>, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after each entry passes GitHub's login grammar.
4748 endpoint: Url,
4749 token: SecretString,
4750 credential_name: String, // llmlint: ignore[invalid_states_unrepresentable] Private diagnostic value constructed only after environment-name validation.
4751 statuses: BoardStatuses,
4752 /// Where each priority lands on this board, or `None` when this instance holds none.
4753 priorities: Option<PriorityMapping>,
4754 /// The metadata values this instance projects onto board text fields, in configured order.
4755 metadata_fields: Vec<MetadataField>,
4756 /// What this board's sub-issues mean.
4757 sub_issues: SubIssues,
4758 /// The link types this source mirrors as `relates-to`.
4759 link_types: onetaskgraph_plugin_api::LinkTypes,
4760 /// Whether this source's configuration opted in to assignees: every document it sends is
4761 /// then spelled by [`graphql::with_assignees`], and every task it reads carries them.
4762 assignees: bool,
4763 /// The GitHub node id of each person an assignee write of this process has named, by
4764 /// lowercased login — `None` for a login GitHub said it does not know — so a later call
4765 /// naming one sends no lookup. A write that fails, or is answered with other people, has the
4766 /// people it named forgotten when its call ends ([`Self::forgotten`]), so the next call
4767 /// naming them asks GitHub again while the rest of its own call does not.
4768 people: Mutex<BTreeMap<String, Option<String>>>,
4769 /// The node ids of the people a failed or mismatched assignee write of this call named,
4770 /// forgotten from [`Self::people`] when the call ends.
4771 forgotten: Mutex<Vec<String>>,
4772 /// GitHub's own spelling of each login this process looked up, by lowercased login: what a
4773 /// write that assigned a person reports them as, however the caller spelled them.
4774 spellings: Mutex<BTreeMap<String, String>>,
4775 /// Built on the first request rather than with the source, as [`Self::client`] says.
4776 client: std::sync::OnceLock<Client>,
4777 /// Built on the first attachment request, as [`Self::asset_client`] says.
4778 asset_client: std::sync::OnceLock<Client>,
4779 /// The markup the engine handed this source for its bodies' headings, applied to every
4780 /// visible body it composes and stripped from every one it reads back: see
4781 /// [`TaskSource::attach_body_markup`].
4782 body_markup: std::sync::OnceLock<onetaskgraph_plugin_api::SharedBodyMarkup>,
4783 /// Every item this source has created in this command, in the order it created them —
4784 /// dropped by [`TaskSource::end_command`].
4785 ///
4786 /// GitHub's `projectV2.items` is eventually consistent: an issue added to a board with
4787 /// `addProjectV2ItemById` is routinely absent from the very next read of that board, so
4788 /// a copy resolving a dependency on an item it had just created refused it as not
4789 /// found. A board read is completed from this — an item remembered here and absent from
4790 /// the read is added back, because the board really does hold it and only the read is
4791 /// behind.
4792 ///
4793 /// It is not a cache of a user's work: nothing is remembered that this process did not
4794 /// itself just write, it lives and dies with the process, and it is never consulted for
4795 /// an item this source did not create.
4796 created: Mutex<Vec<Resolved>>,
4797 /// Every item that already existed and that this source has written in this command, as
4798 /// it wrote it — dropped by [`TaskSource::end_command`].
4799 ///
4800 /// The other half of [`Self::created`], held on the same terms and for the reason a
4801 /// narrowed read needs it: an answer from GitHub's search or from the board's own field
4802 /// filter is an index behind a write this process made moments ago, so a query matching
4803 /// what this process just wrote onto an existing item would otherwise miss it. Nothing
4804 /// is remembered that this process did not itself just write.
4805 updated: Mutex<Vec<Resolved>>,
4806 /// Every issue this source has added a comment to or edited a comment of in this command
4807 /// — dropped by [`TaskSource::end_command`].
4808 ///
4809 /// A comment-activity read is narrowed by GitHub's issue search, whose `updated:` index
4810 /// lags the write that moved an issue's `updatedAt`, and neither [`Self::created`] nor
4811 /// [`Self::updated`] is moved by a comment, so an issue this process had just commented
4812 /// on was missing from such a read — or ruled out by the `updatedAt` its own record held
4813 /// from before — until the index caught up. Each id here is a candidate of every such
4814 /// search-narrowed read, and wherever it is a candidate its comments are read rather than
4815 /// it being ruled out by a stale `updatedAt`; that read is of the issue's own node, so it
4816 /// is current. It holds ids alone: nothing of a comment is remembered. A comment another
4817 /// process wrote is still found only once the index has it.
4818 commented: Mutex<Vec<NativeId>>,
4819 /// How fast this source writes, and how long it waits out a refusal.
4820 pacing: Pacing,
4821 /// When the last content-creating mutation finished, or the moment the furthest-out
4822 /// reserved slot releases the next one, whichever is later — so the one after it can be
4823 /// spaced from that, when `pacing.min_mutation_interval_ms` asks for a spacing. See
4824 /// [`GitHubProjectsSource::paced`] for why completion rather than release is what it is
4825 /// measured from.
4826 last_mutation: Mutex<Option<Duration>>,
4827 /// The `Date` GitHub stated on the last answer this source read: its own time, which the
4828 /// watermark of a comment read is set back from. See [`TaskSource::served_at`].
4829 last_served: Mutex<Option<DateTime<Utc>>>,
4830 /// GitHub's secondary windows as this source has charged them; see the `pacing` module.
4831 windows: Mutex<pacing::Windows>,
4832 /// The tasks a project holds, as a copy's batched read of the project and every one of them
4833 /// found them — see [`TaskSource::read_ahead_for_copy`] — for the length of one command, so
4834 /// a listing of that project's tasks is answered without a read of its own.
4835 task_children: Mutex<BTreeMap<NativeId, Vec<Resolved>>>,
4836 /// The web address of each issue this source created in the current command, as its
4837 /// `createIssue` answered it — what [`TaskSource::written_location`] answers, without a
4838 /// request.
4839 written: Mutex<BTreeMap<NativeId, String>>,
4840 /// What a copy has held back of the items it created, between
4841 /// [`TaskSource::begin_deferred_writes`] and [`TaskSource::finish_writes`] — `None` while
4842 /// nothing is being held back, when every write lands whole as it is made.
4843 deferred: Mutex<Option<Deferred>>,
4844 /// Each existing issue's update held back while writes are, in the order it was made: sent
4845 /// together by [`Self::send_held_updates`] before any other request goes out, so nothing
4846 /// this source sends or reads ever sees the board without them.
4847 held_updates: Mutex<Vec<HeldUpdate>>,
4848 /// The first page of comments a comment-activity read read of each candidate it confirmed,
4849 /// held for the one comment listing of that task that follows in this command — see
4850 /// `batch::hold_comment_pages`.
4851 held_comments: Mutex<BTreeMap<NativeId, Page<Comment>>>,
4852 /// The board field writes and issue updates a batch of targeted updates is holding back,
4853 /// while one runs — see `batch::TaskWrites`.
4854 task_writes: Mutex<Option<batch::TaskWrites>>,
4855 /// The change token each task a targeted update wrote in the current command holds after
4856 /// that write, by the task's id with its board item's id — spelled from the write's own
4857 /// last response, or from the read made right after it where no response showed the whole
4858 /// issue: what [`TaskSource::written_task`] answers as its `version`. Any later mutation
4859 /// naming the task or its board item drops its entry before it is sent, so an entry is
4860 /// never one write behind.
4861 /// A response that showed the issue whole but not every part of its token — a draft, or a
4862 /// page of labels or field values that did not end — records `None`, which a read would
4863 /// not improve on.
4864 written_tokens: Mutex<BTreeMap<NativeId, (String, Option<String>)>>,
4865 clock: SharedClock,
4866 /// Whether the configuration declares this source private, as
4867 /// [`TaskSource::declare_visibility`] told it: what decides where a new issue whose one
4868 /// named repository reads public is created — see [`Self::creation_rule`].
4869 declared_private: std::sync::atomic::AtomicBool,
4870 numeric_repositories: tokio::sync::Mutex<BTreeMap<RepositoryTarget, std::num::NonZeroU64>>,
4871 /// The board as this process last read it, for the length of one command — dropped by
4872 /// [`TaskSource::end_command`].
4873 ///
4874 /// A copy of a project used to re-read the whole board, paged, before writing each of
4875 /// its items, which is by far the largest part of a copy's request count and none of
4876 /// its work. Nothing else changes this board while a command runs — this source's own
4877 /// writes are the only writer — so one read answers them all.
4878 ///
4879 /// It is not a store of a user's work and it is not the cache the no-persistence
4880 /// invariant forbids: it lives and dies with the process exactly as `created` does,
4881 /// nothing is written down, and [`Self::board`] still completes it from `created`, so
4882 /// an item this command created and then depends on resolves whether or not GitHub's
4883 /// own eventually-consistent read has caught up. A write to an item already on the
4884 /// board updates the entry here too, so what this holds is the last read plus this
4885 /// process's own writes rather than a snapshot taken before them.
4886 board_cache: Mutex<Option<Board>>,
4887 /// Every issue this board's own search reported, for the length of one command — dropped
4888 /// by [`TaskSource::end_command`].
4889 ///
4890 /// The second half of a board read, and cached for the same reason and on the same
4891 /// terms as the first: it lives and dies with the process, nothing is written down, and
4892 /// a write this process makes updates the entry here exactly as it updates the one in
4893 /// [`Self::board_cache`]. One read answers every question a command asks, so a command
4894 /// that lists this board's projects and its tasks pays for one search rather than two.
4895 search_cache: Mutex<Option<Vec<Resolved>>>,
4896 /// What each narrowed question GitHub was asked answered, keyed by that question, for
4897 /// the length of one command — dropped by [`TaskSource::end_command`].
4898 ///
4899 /// The narrowed counterpart of [`Self::search_cache`], held on the same terms: it lives
4900 /// and dies with the process, nothing is written down, a write this process makes
4901 /// updates the entry here as it updates the other two, and every answer is completed
4902 /// with this process's own writes each time it is given. A command that asks the same
4903 /// narrowed question twice — a wait polling for its own items, a listing repeated after a
4904 /// write — pays for it once, which is what the whole-board read it replaced gave it.
4905 narrowed_cache: Mutex<BTreeMap<String, Vec<Resolved>>>,
4906 search_next: Mutex<BTreeMap<String, Option<String>>>,
4907 /// Records already resolved in this command, reused by writes and for comment identity.
4908 /// Explicit item reads still reach GitHub. Nothing is persisted, and
4909 /// [`TaskSource::end_command`] drops every record, so a write in the next command reads
4910 /// its item as a person has since left it.
4911 resolved_cache: Mutex<BTreeMap<NativeId, Resolved>>,
4912 /// What [`TaskSource::read_ahead_for_copy`] read, by id — `None` for an id that read
4913 /// answered as holding nothing — each taken by the next read of that item by id and by
4914 /// nothing else, dropped by any mutation naming it, and cleared by
4915 /// [`TaskSource::end_command`]. So a read answered from it is the copy's own
4916 /// read-before-write, made in the same request as the others' rather than on its own.
4917 read_ahead: Mutex<BTreeMap<NativeId, Option<Resolved>>>,
4918 /// The origins [`TaskSource::read_ahead_origins_for_copy`] was asked about and has not sent
4919 /// yet: held for the [`TaskSource::read_ahead_for_copy`] that follows it, which sends them —
4920 /// beside the members of the one project it names, when it names one — or for the next
4921 /// request this source makes, whichever comes first.
4922 pending_origins: Mutex<Vec<String>>,
4923 /// Each project's members as a lookup carrying them read them in this command, trimmed to
4924 /// their classification and repositories, taken by [`TaskSource::member_classifications`]
4925 /// of that project and by nothing else, and cleared by [`TaskSource::end_command`].
4926 member_classes: Mutex<BTreeMap<NativeId, Vec<MemberClass>>>,
4927 /// Every item a listing of one project's members carried whole in this command — the
4928 /// project issue and each of its sub-issues — kept for [`TaskSource::read_ahead_for_copy`]
4929 /// alone, which takes each one it is asked for into [`Self::read_ahead`] instead of reading
4930 /// it again. No other read is answered from it, so a read by id outside a copy's
4931 /// read-before-write reads GitHub as it always did. Dropped by any mutation naming an
4932 /// item, and cleared by [`TaskSource::end_command`].
4933 carried: Mutex<BTreeMap<NativeId, Resolved>>,
4934 /// Items an issue read by reference reached, held for the one status write each was read
4935 /// for and taken out by it alone — see [`Self::take_held`] — because that read selects only
4936 /// what such a write needs. Dropped by [`TaskSource::end_command`].
4937 held_cache: Mutex<BTreeMap<NativeId, Resolved>>,
4938 /// Each project's sub-issues as GitHub answered them, keyed by the selector they were
4939 /// asked for under, with the project that selector named — for the length of one command,
4940 /// dropped by [`TaskSource::end_command`].
4941 ///
4942 /// A caller pages through a project's tasks one engine page at a time, and every page
4943 /// is cut from the whole list of them, so without this each page walked every
4944 /// [`graphql::SUB_ISSUES`] page again and a project of `n` listing pages cost `n²`
4945 /// requests to read once. Held on the terms [`Self::narrowed_cache`] is: it lives and
4946 /// dies with the process, nothing is written down, a write this process makes updates or
4947 /// removes the entry here as it does there, and every answer is completed with this
4948 /// process's own writes each time it is given.
4949 children_cache: Mutex<ProjectChildren>,
4950 /// The board's own id and field definitions as this process last read them on their
4951 /// own, for the length of one command — dropped by [`TaskSource::end_command`].
4952 ///
4953 /// What a write needs of the board and its item does not say, read once per command
4954 /// rather than once per item written, on the terms [`Self::board_cache`] is held on: it
4955 /// lives and dies with the process and nothing is written down. It holds no item and so
4956 /// can answer no question about one — see [`Self::board_fields`].
4957 fields_cache: Mutex<Option<BoardFields>>,
4958 /// Each destination repository's node id, resolved once per repository
4959 /// rather than per issue created.
4960 ///
4961 /// A repository's node id does not change, and re-reading it for every issue of a copy
4962 /// spent one request per item on an answer this source already had. It is a map rather
4963 /// than one entry because a copy files each item in the repository its own
4964 /// `repositories` field names, so a plan across five repositories asks GitHub five
4965 /// times and not once per item.
4966 repository_cache: Mutex<BTreeMap<RepositoryTarget, String>>,
4967 /// What every request this source sends is recorded into.
4968 ///
4969 /// Ordinary code path, not a mode: [`Self::send_once`] records into it at the one place
4970 /// a request leaves this crate, so nothing has to be switched on for a session to be
4971 /// counted. It is shared rather than owned so a caller accounting for a whole session —
4972 /// its own schema verification, board lookups, residue sweep and cleanup beside this
4973 /// source's reads and writes — adds up one accounting instead of two. See
4974 /// [`accounting`] for what a record carries and what a session's spend is and is not.
4975 ledger: Arc<Accounting>,
4976 /// What [`expected`] holds for a write the store's cache expects: the journal while one is
4977 /// open, the issues primed from the cache, and the comments known on each.
4978 expected: expected::Held,
4979 /// What [`projection`] holds for a producer's projection: a kept placement awaiting its
4980 /// setup-context token, and where the last create was placed.
4981 projection: projection::Held,
4982}
4983
4984/// The board item a single field update's answer names, refused unless it is `item_id`.
4985fn field_update_item<'a>(data: &'a Value, item_id: &str) -> Result<&'a Value, SourceError> {
4986 let returned = data
4987 .pointer("/updateProjectV2ItemFieldValue/projectV2Item")
4988 .ok_or_else(|| SourceError::Malformed {
4989 message: "GitHub field update returned no project item".into(),
4990 })?;
4991 if required_str(returned, "id")? != item_id {
4992 return Err(SourceError::Malformed {
4993 message: "GitHub field update returned the wrong project item".into(),
4994 });
4995 }
4996 Ok(returned)
4997}
4998
4999/// GitHub's closed single-select color vocabulary.
5000#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, schemars::JsonSchema)]
5001#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
5002pub enum StatusOptionColor {
5003 /// Gray.
5004 Gray,
5005 /// Blue.
5006 Blue,
5007 /// Green.
5008 Green,
5009 /// Yellow.
5010 Yellow,
5011 /// Purple.
5012 Purple,
5013 /// Red.
5014 Red,
5015 /// Orange.
5016 Orange,
5017 /// Pink.
5018 Pink,
5019}
5020
5021/// Whether a guarded board setup — of the fields, or of the Status options alone — plans or
5022/// applies its additions.
5023#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5024pub enum SetupMode {
5025 /// Read without mutation.
5026 Plan,
5027 /// Apply and verify.
5028 Apply,
5029}
5030
5031/// The name [`SetupMode`] had when Status was the one field set up, kept so a caller written
5032/// against it goes on compiling.
5033pub type StatusOptionsMode = SetupMode;
5034
5035/// The explicit result of the requested operation.
5036#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5037#[serde(rename_all = "kebab-case")]
5038pub enum StatusOptionsOutcome {
5039 /// A read-only plan.
5040 Planned,
5041 /// Apply found nothing missing.
5042 Unchanged,
5043 /// Additions were applied and verified.
5044 Applied,
5045}
5046
5047/// A GitHub single-select option's opaque GraphQL node identifier.
5048#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5049#[serde(transparent)]
5050pub struct StatusOptionId(#[schemars(length(min = 1))] String);
5051
5052impl TryFrom<String> for StatusOptionId {
5053 type Error = String;
5054
5055 fn try_from(id: String) -> Result<Self, Self::Error> {
5056 if id.trim().is_empty() {
5057 return Err("a GitHub Status option id cannot be blank".to_owned());
5058 }
5059 Ok(Self(id))
5060 }
5061}
5062
5063/// One existing or proposed option in a guarded Status-field update.
5064#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5065pub struct StatusOption {
5066 /// GitHub's stable id.
5067 pub id: StatusOptionId,
5068 /// The visible option name.
5069 pub name: ColumnName,
5070 /// GitHub's single-select color token.
5071 pub color: StatusOptionColor,
5072 /// The option description, including an empty one.
5073 pub description: String,
5074}
5075
5076/// One board item's Status assignment, retained as recovery data.
5077#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5078pub struct StatusAssignment {
5079 /// The project item id whose assignment this is.
5080 // llmlint: ignore[invalid_states_unrepresentable] This opaque GraphQL node ID is
5081 // carried verbatim as operator recovery data; introducing a semantic type would claim
5082 // validation rules GitHub does not publish and no operation here interprets.
5083 pub item_id: String,
5084 /// The selected option, absent when the item has no status.
5085 #[serde(skip_serializing_if = "Option::is_none")]
5086 pub option: Option<AssignedStatusOption>,
5087}
5088
5089/// The inseparable id and name of an assigned option.
5090#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5091pub struct AssignedStatusOption {
5092 /// GitHub's stable id.
5093 pub id: StatusOptionId,
5094 /// The visible name.
5095 pub name: ColumnName,
5096}
5097
5098/// The plan and verified outcome of reconciling configured Status options.
5099#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5100pub struct StatusOptionsReport {
5101 /// The configured source name.
5102 pub source: SourceName,
5103 /// Configured option names absent before the operation.
5104 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a
5105 // `ColumnName` and has therefore already passed its nonblank validation; retaining the
5106 // serialized string here preserves the report's intentionally simple public contract.
5107 pub missing: Vec<String>,
5108 /// What the requested operation did.
5109 pub outcome: StatusOptionsOutcome,
5110 /// The complete option list observed before any mutation.
5111 pub existing: Vec<StatusOption>,
5112}
5113
5114#[derive(Debug, Clone, PartialEq, Eq)]
5115struct StatusSnapshot {
5116 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5117 // passed back as the mutation's project identity; a newtype could enforce no stronger
5118 // invariant because GitHub publishes no grammar for it.
5119 board_id: String,
5120 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5121 // passed back as the mutation's field identity; a newtype could enforce no stronger
5122 // invariant because GitHub publishes no grammar for it.
5123 field_id: String,
5124 options: Vec<StatusOption>,
5125 assignments: Vec<StatusAssignment>,
5126}
5127
5128/// The name of the board field a status is held in.
5129const STATUS_FIELD: &str = "Status";
5130
5131/// Every item's value of each field `report` names, as it stood before the setup wrote
5132/// anything — what a person puts back when the setup is refused part way.
5133fn recovery(report: &FieldsReport, before: &BoardSnapshot) -> Result<String, SourceError> {
5134 let assignments: BTreeMap<&str, Vec<StatusAssignment>> = report
5135 .fields
5136 .iter()
5137 .map(|field| (field.field.name(), before.assignments(field.field)))
5138 .collect();
5139 serde_json::to_string_pretty(&assignments).map_err(|error| SourceError::Malformed {
5140 message: format!("cannot render the pre-write field recovery snapshot: {error}"),
5141 })
5142}
5143
5144/// One board field the guarded setup reads and writes — every one it reads, and the only
5145/// ones it writes.
5146#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, schemars::JsonSchema)]
5147pub enum BoardField {
5148 /// The single-select `Status` field every instance's `status_mapping` resolves into.
5149 Status,
5150 /// The single-select `Priority` field an instance's `priority_mapping` resolves into.
5151 Priority,
5152}
5153
5154impl BoardField {
5155 /// The field's name on the board.
5156 #[must_use]
5157 pub const fn name(self) -> &'static str {
5158 match self {
5159 Self::Status => STATUS_FIELD,
5160 Self::Priority => PRIORITY_FIELD,
5161 }
5162 }
5163
5164 /// The field a board calls `name`, or `None` for one this setup does not own.
5165 fn named(name: &str) -> Option<Self> {
5166 [Self::Status, Self::Priority]
5167 .into_iter()
5168 .find(|field| field.name() == name)
5169 }
5170}
5171
5172/// What the guarded setup did to one field.
5173#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5174#[serde(rename_all = "kebab-case")]
5175pub enum FieldOutcome {
5176 /// A read-only plan.
5177 Planned,
5178 /// Apply found the field there with every configured option.
5179 Unchanged,
5180 /// Missing options were added to the field that was there, and verified.
5181 Applied,
5182 /// The field was not there; it was created holding the configured options, and verified.
5183 Created,
5184}
5185
5186/// One field's plan, or its verified outcome.
5187#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5188pub struct FieldReport {
5189 /// Which field.
5190 pub field: BoardField,
5191 /// Whether the board had the field before the operation.
5192 // llmlint: ignore[invalid_states_unrepresentable] `exists` beside `outcome` is the report's
5193 // wire shape as its consumer's contract fixes it — `{"field", "exists", "missing",
5194 // "outcome", "existing"}` — so folding one into the other would change a published JSON
5195 // shape. The contradictory pairings cannot be built: `GitHubProjectsSource::fields` is the
5196 // one constructor, and it derives `outcome` from `exists` in one match.
5197 pub exists: bool,
5198 /// Configured option names the field lacked before the operation — every one of them,
5199 /// in the order a new field lists them, when the field was not there at all.
5200 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
5201 // mapping name and has therefore already passed its nonblank validation; the serialized
5202 // string is the report's intentionally simple public contract, as `StatusOptionsReport`'s is.
5203 pub missing: Vec<String>,
5204 /// For the `Status` field, which item kind each missing name is configured for: one
5205 /// entry per kind `status_mapping` names a missing option for, task before project, each
5206 /// listing that kind's missing names in category order. A name both kinds use is in
5207 /// both. Empty — and left out of the JSON — when nothing is missing, and always for
5208 /// `Priority`, which only a task holds.
5209 #[serde(default, skip_serializing_if = "Vec::is_empty")]
5210 // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
5211 // both SDKs model an absent `kinds` as an empty list rather than as `null`.
5212 #[schemars(!skip_serializing_if)]
5213 pub kinds: Vec<KindMissing>,
5214 /// What the requested operation did.
5215 pub outcome: FieldOutcome,
5216 /// The field's complete option list observed before any mutation; empty when the field
5217 /// was not there.
5218 pub existing: Vec<StatusOption>,
5219}
5220
5221/// The `Status` option names one item kind's `status_mapping` names that the field lacked.
5222#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5223pub struct KindMissing {
5224 /// The kind these names are configured for.
5225 pub kind: ItemKind,
5226 /// The names that kind maps a category to and the field lacked, in category order.
5227 // llmlint: ignore[invalid_states_unrepresentable] Each value originates from a validated
5228 // mapping name, as `FieldReport::missing`'s do, and the serialized string is the report's
5229 // intentionally simple public contract.
5230 pub missing: Vec<String>,
5231}
5232
5233/// The plan and verified outcome of setting up every field a source's configuration names.
5234#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5235pub struct FieldsReport {
5236 /// The configured source name.
5237 pub source: SourceName,
5238 /// `Status`, always, and `Priority` when the source sets `priority_mapping`.
5239 // llmlint: ignore[invalid_states_unrepresentable] A list is the report's wire shape as its
5240 // consumer's contract fixes it — `{"source", "fields": [...]}` — so a struct with one member
5241 // per field would change a published JSON shape. The states the list could hold and the
5242 // contract forbids cannot be built: `GitHubProjectsSource::fields` is the one constructor,
5243 // and it pushes `Status` first and exactly once, then `Priority` exactly when configured.
5244 pub fields: Vec<FieldReport>,
5245 /// Each board text field the source's `metadata_fields` projects a value onto, in
5246 /// configured order. Empty — and left out of the JSON — when it projects none.
5247 #[serde(default, skip_serializing_if = "Vec::is_empty")]
5248 // Kept in the schema as `"default": []` although the JSON leaves an empty list out, so
5249 // both SDKs model an absent list as an empty one rather than as `null`.
5250 #[schemars(!skip_serializing_if)]
5251 pub metadata_fields: Vec<MetadataFieldReport>,
5252}
5253
5254/// The type of a board field that is not a text field, as GitHub names it — its `dataType`, or
5255/// its GraphQL type when it has none — which is what a projected field's conflict reports.
5256///
5257/// Never empty, never beginning with whitespace, and never `TEXT`: a text field of that name is
5258/// no conflict.
5259// The schema states that rule as `NON_TEXT_FIELD_TYPE_PATTERN`, so a generated SDK model
5260// refuses exactly what `try_from` below does.
5261#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5262#[serde(transparent)]
5263pub struct NonTextFieldType(#[schemars(regex(pattern = NON_TEXT_FIELD_TYPE_PATTERN))] String);
5264
5265/// What a [`NonTextFieldType`] may be, as the emitted schema states it: a first character that
5266/// is not whitespace, and anything but exactly `TEXT` — spelled without a lookahead, which
5267/// neither SDK's validator can be relied on to support.
5268const NON_TEXT_FIELD_TYPE_PATTERN: &str =
5269 r"^(?:[^T\s]|T(?:[^E]|$)|TE(?:[^X]|$)|TEX(?:[^T]|$)|TEXT[\s\S])";
5270
5271impl TryFrom<String> for NonTextFieldType {
5272 type Error = String;
5273
5274 fn try_from(kind: String) -> Result<Self, Self::Error> {
5275 if kind.is_empty() || kind.starts_with(char::is_whitespace) {
5276 return Err("a board field's type cannot be blank or begin with whitespace".to_owned());
5277 }
5278 if kind == "TEXT" {
5279 return Err("a TEXT field is no conflict for a projected text field".to_owned());
5280 }
5281 Ok(Self(kind))
5282 }
5283}
5284
5285impl std::fmt::Display for NonTextFieldType {
5286 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5287 formatter.write_str(&self.0)
5288 }
5289}
5290
5291/// One projected metadata text field's plan, or its verified outcome.
5292///
5293/// The setup creates a missing one as a text field and never alters a field that is there:
5294/// a same-named field of another type is reported in `conflict` and left as it is.
5295#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
5296pub struct MetadataFieldReport {
5297 /// The board field's name.
5298 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.
5299 /// The metadata key the value is read from.
5300 pub key: String, // llmlint: ignore[invalid_states_unrepresentable] As `field`: a validated configuration value reported back as written.
5301 /// The object keys walked inside that key's value; empty for the key's own value.
5302 pub path: Vec<String>,
5303 /// Whether the board had a text field of that name before the operation.
5304 // 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.
5305 pub exists: bool,
5306 /// The type of a field of that name that is not a text field, which the setup leaves as
5307 /// it is; absent — and left out of the JSON — when there is none.
5308 #[serde(default, skip_serializing_if = "Option::is_none")]
5309 pub conflict: Option<NonTextFieldType>,
5310 /// What the requested operation did: `planned`; `created` for a field that was not
5311 /// there; `unchanged` for one that was, and for a conflict, which is never changed.
5312 pub outcome: FieldOutcome,
5313}
5314
5315/// Which options one field is configured with, in the order a new field would list them.
5316struct FieldPlan {
5317 field: BoardField,
5318 wanted: Vec<String>,
5319}
5320
5321/// One single-select field as the guarded setup snapshots it.
5322#[derive(Debug, Clone, PartialEq, Eq)]
5323struct SnapshotField {
5324 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5325 // passed back as the mutation's field identity; a newtype could enforce no stronger
5326 // invariant because GitHub publishes no grammar for it.
5327 field_id: String,
5328 options: Vec<StatusOption>,
5329}
5330
5331/// Every single-select field of a board and every item's value of each.
5332#[derive(Debug, Clone, PartialEq, Eq)]
5333struct BoardSnapshot {
5334 // llmlint: ignore[invalid_states_unrepresentable] This private opaque GraphQL ID is
5335 // passed back as the mutation's project identity; a newtype could enforce no stronger
5336 // invariant because GitHub publishes no grammar for it.
5337 board_id: String,
5338 fields: BTreeMap<BoardField, SnapshotField>,
5339 /// Each board item's id, and its value of each field this setup owns that it holds one of.
5340 items: Vec<(String, BTreeMap<BoardField, AssignedStatusOption>)>,
5341}
5342
5343impl BoardSnapshot {
5344 /// Every item's value of `field`, in board order — the recovery data a drift refusal
5345 /// carries.
5346 fn assignments(&self, field: BoardField) -> Vec<StatusAssignment> {
5347 self.items
5348 .iter()
5349 .map(|(item_id, values)| StatusAssignment {
5350 item_id: item_id.clone(),
5351 option: values.get(&field).cloned(),
5352 })
5353 .collect()
5354 }
5355}
5356
5357impl GitHubProjectsSource {
5358 /// `content` as this source sends it, with the markup the engine handed it applied.
5359 fn marked(&self, content: &str) -> String {
5360 match self.body_markup.get() {
5361 Some(markup) if !content.is_empty() => markup.written(content),
5362 _ => content.to_owned(),
5363 }
5364 }
5365
5366 /// The visible body and the metadata slot of `body` as [`metadata_body`] splits them,
5367 /// the visible body without the markup [`Self::marked`] applies.
5368 fn visible(
5369 &self,
5370 body: Option<String>,
5371 ) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
5372 let (visible, slot) = metadata_body(body)?;
5373 Ok((
5374 match (visible, self.body_markup.get()) {
5375 (Some(visible), Some(markup)) => {
5376 Some(markup.read(&visible)).filter(|read| !read.is_empty())
5377 }
5378 (visible, _) => visible,
5379 },
5380 slot,
5381 ))
5382 }
5383
5384 /// Report missing configured Status options and, when `apply` is true, add them with
5385 /// a whole-list mutation that preserves every existing id and verifies the result.
5386 ///
5387 /// # Errors
5388 ///
5389 /// Refuses a board without a single-select `Status` field. A post-write difference in
5390 /// any pre-existing option id or item assignment is refused with the complete pre-write
5391 /// assignment snapshot in the diagnostic for recovery.
5392 // llmlint: ignore[changed_behavior_has_e2e] The CLI journeys cover plan, no-op apply,
5393 // successful mutation, both drift refusals, source selection, missing Status, casing,
5394 // and paging. Transport errors remain the shared `graphql` boundary's behavior rather
5395 // than a new status-options behavior, and the pinned-schema test prevents valid GitHub
5396 // responses from entering the defensive malformed-response branches below.
5397 pub async fn status_options(
5398 &self,
5399 mode: StatusOptionsMode,
5400 ) -> Result<StatusOptionsReport, SourceError> {
5401 let before = self.status_snapshot().await?;
5402 // A terminal category's option is as configured as an open one's: a terminal
5403 // write validates it before closing and refuses when the board lacks it. Both
5404 // kinds' names are options of the one field, so both are asked for.
5405 let missing = self
5406 .statuses
5407 .wanted()
5408 .into_iter()
5409 .filter(|wanted| {
5410 !before
5411 .options
5412 .iter()
5413 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5414 })
5415 .collect::<Vec<_>>();
5416 let report = StatusOptionsReport {
5417 source: self.name.clone(),
5418 missing: missing.clone(),
5419 outcome: match (mode, missing.is_empty()) {
5420 (StatusOptionsMode::Plan, _) => StatusOptionsOutcome::Planned,
5421 (StatusOptionsMode::Apply, true) => StatusOptionsOutcome::Unchanged,
5422 (StatusOptionsMode::Apply, false) => StatusOptionsOutcome::Applied,
5423 },
5424 existing: before.options.clone(),
5425 };
5426 if mode == StatusOptionsMode::Plan || missing.is_empty() {
5427 return Ok(report);
5428 }
5429 let mut options = before
5430 .options
5431 .iter()
5432 .map(|option| {
5433 json!({
5434 "id": option.id, "name": option.name, "color": option.color,
5435 "description": option.description,
5436 })
5437 })
5438 .collect::<Vec<_>>();
5439 options.extend(missing.iter().map(|name| {
5440 json!({
5441 "name": name, "color": "GRAY", "description": ""
5442 })
5443 }));
5444 self.graphql(
5445 graphql::STATUS_OPTIONS_UPDATE,
5446 json!({"input": {
5447 "fieldId": before.field_id,
5448 "singleSelectOptions": options,
5449 }}),
5450 )
5451 .await?;
5452 let after = self.status_snapshot().await?;
5453 let options_preserved = before
5454 .options
5455 .iter()
5456 .all(|old| after.options.iter().any(|new| new == old));
5457 let additions_present = missing.iter().all(|wanted| {
5458 after
5459 .options
5460 .iter()
5461 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5462 });
5463 if !options_preserved || !additions_present || after.assignments != before.assignments {
5464 let recovery = serde_json::to_string_pretty(&before.assignments).map_err(|error| {
5465 SourceError::Malformed {
5466 message: format!("cannot render pre-write Status recovery snapshot: {error}"),
5467 }
5468 })?;
5469 return Err(SourceError::Refused {
5470 message: format!(
5471 "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}"
5472 ),
5473 });
5474 }
5475 Ok(report)
5476 }
5477
5478 /// A fresh snapshot of the Status field and every board item's assignment of it.
5479 ///
5480 /// # Errors
5481 ///
5482 /// Refuses a board without a single-select `Status` field, and one the token cannot see.
5483 async fn status_snapshot(&self) -> Result<StatusSnapshot, SourceError> {
5484 // Status alone, as this operation has always read it: a `Priority` field is another
5485 // operation's, so nothing about it can refuse this one.
5486 let mut board = self.board_snapshot(&[BoardField::Status]).await?;
5487 let field = board
5488 .fields
5489 .remove(&BoardField::Status)
5490 .ok_or_else(|| self.no_status_field())?;
5491 Ok(StatusSnapshot {
5492 assignments: board.assignments(BoardField::Status),
5493 board_id: board.board_id,
5494 field_id: field.field_id,
5495 options: field.options,
5496 })
5497 }
5498
5499 /// The refusal a board with no `Status` field is answered with by the guarded setup.
5500 fn no_status_field(&self) -> SourceError {
5501 SourceError::Refused {
5502 message: format!("source {} board has no Status field", self.name),
5503 }
5504 }
5505
5506 // llmlint: ignore-block[changed_behavior_has_e2e] Valid snapshot shapes are exercised through
5507 // the real CLI loopback journey, including pagination. The individual malformed guards
5508 // are defensive validation of a schema-pinned third-party response, not separate user
5509 // journeys; drift and missing-field failures cover the operation's recovery behavior.
5510 /// A fresh snapshot of each of the `owned` fields on the board, with its options, and of
5511 /// every board item's value of each, walked to the end of the board's items. A field not
5512 /// in `owned` is read past whatever it holds.
5513 async fn board_snapshot(&self, owned: &[BoardField]) -> Result<BoardSnapshot, SourceError> {
5514 let mut after: Option<String> = None;
5515 let mut snapshot: Option<BoardSnapshot> = None;
5516 loop {
5517 let data = self
5518 .graphql(
5519 graphql::STATUS_OPTIONS_SNAPSHOT,
5520 json!({
5521 "owner": self.owner, "number": self.project_number,
5522 "first": MAX_PAGE_SIZE, "after": after, "nestedFirst": MAX_PAGE_SIZE,
5523 }),
5524 )
5525 .await?;
5526 let board = data
5527 .pointer("/owner/projectV2")
5528 .filter(|board| board.is_object())
5529 .ok_or_else(|| SourceError::Refused {
5530 message: format!(
5531 "source {} has no accessible GitHub Projects board",
5532 self.name
5533 ),
5534 })?;
5535 if board
5536 .pointer("/fields/pageInfo/hasNextPage")
5537 .and_then(Value::as_bool)
5538 != Some(false)
5539 {
5540 return Err(SourceError::Malformed {
5541 message:
5542 "GitHub project fields is incomplete or has malformed pageInfo.hasNextPage"
5543 .into(),
5544 });
5545 }
5546 let mut fields = BTreeMap::new();
5547 // Only the fields this setup owns, by name: a node the single-select fragment did not
5548 // match carries no name, and a person's own single-select field — a `Size`, a
5549 // `Team` — is none of this setup's business, so nothing about it can refuse one. A
5550 // `Status` or `Priority` field without its options is malformed, not absent.
5551 // 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.
5552 for (owned, field) in board
5553 .pointer("/fields/nodes")
5554 .and_then(Value::as_array)
5555 .ok_or_else(|| SourceError::Malformed {
5556 message: "GitHub project fields.nodes is not an array".into(),
5557 })?
5558 .iter()
5559 .filter_map(|field| {
5560 let named = BoardField::named(field.get("name")?.as_str()?)?;
5561 owned.contains(&named).then_some((named, field))
5562 })
5563 {
5564 let options = field
5565 .get("options")
5566 .and_then(Value::as_array)
5567 .ok_or_else(|| SourceError::Malformed {
5568 message: "GitHub single-select field options is not an array".into(),
5569 })?
5570 .iter()
5571 .map(|option| {
5572 Ok(StatusOption {
5573 id: StatusOptionId::try_from(required_str(option, "id")?.to_owned())
5574 .map_err(|message| SourceError::Malformed { message })?,
5575 name: ColumnName::try_from(required_str(option, "name")?.to_owned())
5576 .map_err(|message| SourceError::Malformed {
5577 message: format!(
5578 "GitHub single-select option name is invalid: {message}"
5579 ),
5580 })?,
5581 color: serde_json::from_value(
5582 option.get("color").cloned().unwrap_or(Value::Null),
5583 )
5584 .map_err(|error| {
5585 SourceError::Malformed {
5586 message: format!(
5587 "GitHub single-select option color is invalid: {error}"
5588 ),
5589 }
5590 })?,
5591 description: optional_str(option, "description")?
5592 .unwrap_or_default()
5593 .to_owned(),
5594 })
5595 })
5596 .collect::<Result<Vec<_>, SourceError>>()?;
5597 let snapshot = SnapshotField {
5598 field_id: required_nonblank_str(field, "id")?.to_owned(),
5599 options,
5600 };
5601 // A board's field names are unique, so a second one is an answer that cannot
5602 // say which field the setup would act on — refused rather than one chosen.
5603 if fields.insert(owned, snapshot).is_some() {
5604 return Err(SourceError::Malformed {
5605 message: format!(
5606 "GitHub answered two {} fields for this board",
5607 owned.name()
5608 ),
5609 });
5610 }
5611 }
5612 let board_id = required_nonblank_str(board, "id")?.to_owned();
5613 let current = snapshot.get_or_insert_with(|| BoardSnapshot {
5614 board_id,
5615 fields,
5616 items: Vec::new(),
5617 });
5618 let items = board
5619 .pointer("/items/nodes")
5620 .and_then(Value::as_array)
5621 .ok_or_else(|| SourceError::Malformed {
5622 message: "GitHub project items.nodes is not an array".into(),
5623 })?;
5624 for item in items {
5625 let field_values =
5626 item.get("fieldValues")
5627 .ok_or_else(|| SourceError::Malformed {
5628 message: "GitHub project item is missing fieldValues".into(),
5629 })?;
5630 if field_values
5631 .pointer("/pageInfo/hasNextPage")
5632 .and_then(Value::as_bool)
5633 != Some(false)
5634 {
5635 return Err(SourceError::Malformed {
5636 message: "GitHub project item fieldValues is incomplete or has malformed pageInfo.hasNextPage".into(),
5637 });
5638 }
5639 let values = item
5640 .pointer("/fieldValues/nodes")
5641 .and_then(Value::as_array)
5642 .ok_or_else(|| SourceError::Malformed {
5643 message: "GitHub project item fieldValues.nodes is not an array".into(),
5644 })?;
5645 let item_id = required_nonblank_str(item, "id")?;
5646 let mut assigned = BTreeMap::new();
5647 for value in values {
5648 let Some(field) = value
5649 .pointer("/field/name")
5650 .and_then(Value::as_str)
5651 .and_then(BoardField::named)
5652 .filter(|field| owned.contains(field))
5653 else {
5654 continue;
5655 };
5656 let held = assigned.insert(
5657 field,
5658 AssignedStatusOption {
5659 id: StatusOptionId::try_from(
5660 required_str(value, "optionId")?.to_owned(),
5661 )
5662 .map_err(|message| SourceError::Malformed { message })?,
5663 name: ColumnName::try_from(required_str(value, "name")?.to_owned())
5664 .map_err(|message| SourceError::Malformed {
5665 message: format!(
5666 "GitHub assigned {} name is invalid: {message}",
5667 field.name()
5668 ),
5669 })?,
5670 },
5671 );
5672 // An item holds one value of a field, so a second one leaves no way to
5673 // tell which it holds — and a verification or recovery built on either
5674 // could restore the wrong one.
5675 if held.is_some() {
5676 return Err(SourceError::Malformed {
5677 message: format!(
5678 "GitHub answered two {} values for board item {item_id}",
5679 field.name()
5680 ),
5681 });
5682 }
5683 }
5684 current.items.push((item_id.to_owned(), assigned));
5685 }
5686 let page = board.get("items").ok_or_else(|| SourceError::Malformed {
5687 message: "GitHub project is missing items".into(),
5688 })?;
5689 let has_next = page
5690 .pointer("/pageInfo/hasNextPage")
5691 .and_then(Value::as_bool)
5692 .ok_or_else(|| SourceError::Malformed {
5693 message: "GitHub project items.pageInfo.hasNextPage is not a boolean".into(),
5694 })?;
5695 if !has_next {
5696 break;
5697 }
5698 let next =
5699 required_nonblank_str(page.get("pageInfo").unwrap_or(&Value::Null), "endCursor")?;
5700 validate_cursor_progress(after.as_deref(), next)?;
5701 after = Some(next.to_owned());
5702 }
5703 snapshot.ok_or_else(|| SourceError::Malformed {
5704 message: "GitHub returned no board field snapshot".into(),
5705 })
5706 }
5707 // llmlint: ignore-end[changed_behavior_has_e2e]
5708
5709 /// Report every board field this source's configuration names and, with
5710 /// [`SetupMode::Apply`], set each up: add the options a field lacks, and create
5711 /// the `Priority` field when the board has none.
5712 ///
5713 /// The fields are `Status`, always, with the options `status_mapping` resolves to; and
5714 /// `Priority`, when `priority_mapping` is set, with its four mapped options — created in
5715 /// the order urgent, high, medium, low. An option a field already has keeps its id, name,
5716 /// color and description: the whole option list goes back with every existing id, because
5717 /// a re-minted id clears every item's value.
5718 ///
5719 /// # Errors
5720 ///
5721 /// Refuses a board without a single-select `Status` field. After an apply the board is
5722 /// read again, and a pre-existing option or any item's value of either field that moved is
5723 /// refused with the complete pre-write assignments in the diagnostic, for recovery.
5724 // llmlint: ignore[changed_behavior_has_e2e] The `sources fields` journeys drive plan,
5725 // unchanged apply, a created field, an added option to each field, drift refusal, a board
5726 // with no Status field and a non-github-projects source through the compiled CLI against
5727 // the loopback board. Transport errors are the shared `graphql` boundary's behavior.
5728 pub async fn fields(&self, mode: SetupMode) -> Result<FieldsReport, SourceError> {
5729 let owned: Vec<BoardField> = if self.priorities.is_some() {
5730 vec![BoardField::Status, BoardField::Priority]
5731 } else {
5732 vec![BoardField::Status]
5733 };
5734 let before = self.board_snapshot(&owned).await?;
5735 let mut plans = vec![FieldPlan {
5736 field: BoardField::Status,
5737 wanted: self.statuses.wanted(),
5738 }];
5739 if !before.fields.contains_key(&BoardField::Status) {
5740 return Err(self.no_status_field());
5741 }
5742 if let Some(mapping) = &self.priorities {
5743 plans.push(FieldPlan {
5744 field: BoardField::Priority,
5745 wanted: mapping.names().map(str::to_owned).collect(),
5746 });
5747 }
5748 // The snapshot reads single-select fields alone, so a field it did not find may still
5749 // be on the board under the name, of another type: creating one beside it would fail
5750 // part way, or leave two fields of one name. Asked of the board's own field list, and
5751 // only when a field is missing.
5752 if plans
5753 .iter()
5754 .any(|plan| !before.fields.contains_key(&plan.field))
5755 {
5756 let board = self.board_fields().await?;
5757 for plan in plans
5758 .iter()
5759 .filter(|plan| !before.fields.contains_key(&plan.field))
5760 {
5761 if let Some(field) = Board::field(&board.fields, plan.field.name())? {
5762 return Err(SourceError::Refused {
5763 message: format!(
5764 "source {}'s board has a {} field that is not a single-select field \
5765 (it is a {}), so it cannot hold this source's options; next: rename \
5766 or remove that field, then run this again",
5767 self.name,
5768 plan.field.name(),
5769 optional_str(field, "__typename")?.unwrap_or("field of another type")
5770 ),
5771 });
5772 }
5773 }
5774 }
5775 let mut reports = Vec::new();
5776 for plan in &plans {
5777 let held = before.fields.get(&plan.field);
5778 let existing = held.map(|field| field.options.clone()).unwrap_or_default();
5779 let mut missing: Vec<String> = Vec::new();
5780 for wanted in &plan.wanted {
5781 let present = existing
5782 .iter()
5783 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5784 || missing
5785 .iter()
5786 .any(|named| named.eq_ignore_ascii_case(wanted));
5787 if !present {
5788 missing.push(wanted.clone());
5789 }
5790 }
5791 let kinds = match plan.field {
5792 BoardField::Status => self.statuses.missing_by_kind(&existing),
5793 BoardField::Priority => Vec::new(),
5794 };
5795 reports.push(FieldReport {
5796 field: plan.field,
5797 exists: held.is_some(),
5798 kinds,
5799 outcome: match (mode, held.is_some(), missing.is_empty()) {
5800 (SetupMode::Plan, _, _) => FieldOutcome::Planned,
5801 (SetupMode::Apply, true, true) => FieldOutcome::Unchanged,
5802 (SetupMode::Apply, true, false) => FieldOutcome::Applied,
5803 (SetupMode::Apply, false, _) => FieldOutcome::Created,
5804 },
5805 missing,
5806 existing,
5807 });
5808 }
5809 // A projected field is a text field, which the single-select snapshot cannot see, so
5810 // it is asked of the board's own field list — and only when one is configured.
5811 let mut metadata_fields = Vec::new();
5812 if !self.metadata_fields.is_empty() {
5813 let board = self.board_fields().await?;
5814 for projection in &self.metadata_fields {
5815 let conflict = match Board::field(&board.fields, &projection.field)? {
5816 None => None,
5817 Some(field) => {
5818 let typename = optional_str(field, "__typename")?;
5819 let data_type = optional_str(field, "dataType")?;
5820 if typename == Some("ProjectV2Field") && data_type == Some("TEXT") {
5821 None
5822 } else {
5823 let named = data_type
5824 .filter(|kind| *kind != "TEXT")
5825 .or(typename)
5826 .unwrap_or("field of another type");
5827 Some(NonTextFieldType::try_from(named.to_owned()).map_err(
5828 |message| SourceError::Malformed {
5829 message: format!(
5830 "GitHub answered the board's {} field with a type this \
5831 setup cannot read: {message}",
5832 &*projection.field
5833 ),
5834 },
5835 )?)
5836 }
5837 }
5838 };
5839 let exists =
5840 conflict.is_none() && Board::field(&board.fields, &projection.field)?.is_some();
5841 metadata_fields.push(MetadataFieldReport {
5842 field: projection.field.to_string(),
5843 key: projection.key.to_string(),
5844 path: projection.path.clone(),
5845 exists,
5846 outcome: match (mode, exists || conflict.is_some()) {
5847 (SetupMode::Plan, _) => FieldOutcome::Planned,
5848 (SetupMode::Apply, true) => FieldOutcome::Unchanged,
5849 (SetupMode::Apply, false) => FieldOutcome::Created,
5850 },
5851 conflict,
5852 });
5853 }
5854 }
5855 let report = FieldsReport {
5856 source: self.name.clone(),
5857 fields: reports,
5858 metadata_fields,
5859 };
5860 let writes: Vec<&FieldReport> = report
5861 .fields
5862 .iter()
5863 .filter(|field| !field.missing.is_empty() || !field.exists)
5864 .collect();
5865 let creates: Vec<&MetadataFieldReport> = report
5866 .metadata_fields
5867 .iter()
5868 .filter(|field| field.outcome == FieldOutcome::Created)
5869 .collect();
5870 if mode == SetupMode::Plan || (writes.is_empty() && creates.is_empty()) {
5871 return Ok(report);
5872 }
5873 let mut landed: Vec<&str> = Vec::new();
5874 for field in &writes {
5875 let added = field
5876 .missing
5877 .iter()
5878 .map(|name| json!({"name": name, "color": "GRAY", "description": ""}));
5879 let sent = match before.fields.get(&field.field) {
5880 Some(held) => {
5881 let mut options = held
5882 .options
5883 .iter()
5884 .map(|option| {
5885 json!({
5886 "id": option.id, "name": option.name, "color": option.color,
5887 "description": option.description,
5888 })
5889 })
5890 .collect::<Vec<_>>();
5891 options.extend(added);
5892 self.graphql(
5893 graphql::STATUS_OPTIONS_UPDATE,
5894 json!({"input": {
5895 "fieldId": held.field_id,
5896 "singleSelectOptions": options,
5897 }}),
5898 )
5899 .await
5900 }
5901 None => {
5902 self.graphql(
5903 graphql::CREATE_FIELD,
5904 json!({"input": {
5905 "projectId": before.board_id, "dataType": "SINGLE_SELECT",
5906 "name": field.field.name(),
5907 "singleSelectOptions": added.collect::<Vec<_>>(),
5908 }}),
5909 )
5910 .await
5911 }
5912 };
5913 // A mutation that failed does not establish that GitHub left its field as it was,
5914 // so every failure from here on carries the recovery data a drift refusal does.
5915 match sent {
5916 Ok(_) => landed.push(field.field.name()),
5917 Err(error) => {
5918 let changed = if landed.is_empty() {
5919 String::new()
5920 } else {
5921 format!("changed the {} field and then ", landed.join(" and "))
5922 };
5923 return Err(SourceError::Refused {
5924 message: format!(
5925 "the guarded field setup {changed}failed on the {} field, which it may \
5926 have changed part way: {error}; the pre-write item assignments \
5927 are:\n{}",
5928 field.field.name(),
5929 recovery(&report, &before)?
5930 ),
5931 });
5932 }
5933 }
5934 }
5935 for field in &creates {
5936 let sent = self
5937 .graphql(
5938 graphql::CREATE_FIELD,
5939 json!({"input": {
5940 "projectId": before.board_id, "dataType": "TEXT", "name": field.field,
5941 }}),
5942 )
5943 .await;
5944 if let Err(error) = sent {
5945 let changed = if landed.is_empty() {
5946 String::new()
5947 } else {
5948 format!("changed the {} field and then ", landed.join(" and "))
5949 };
5950 return Err(SourceError::Refused {
5951 message: format!(
5952 "the guarded field setup {changed}failed creating the {} text field: \
5953 {error}; run it again to create what is still missing",
5954 field.field
5955 ),
5956 });
5957 }
5958 landed.push(&field.field);
5959 }
5960 // The board has been written, so a verification read that fails leaves it unverified
5961 // rather than unchanged, and says what to put back.
5962 let after = match self.board_snapshot(&owned).await {
5963 Ok(after) => after,
5964 Err(error) => {
5965 return Err(SourceError::Refused {
5966 message: format!(
5967 "the guarded field setup changed the {} field and then could not read the \
5968 board back to verify it: {error}; the pre-write item assignments are:\n{}",
5969 landed.join(" and "),
5970 recovery(&report, &before)?
5971 ),
5972 });
5973 }
5974 };
5975 let mut moved = Vec::new();
5976 for field in &report.fields {
5977 let name = field.field.name();
5978 let now = after
5979 .fields
5980 .get(&field.field)
5981 .map(|held| held.options.as_slice())
5982 .unwrap_or_default();
5983 if !field.existing.iter().all(|old| now.contains(old)) {
5984 moved.push(format!(
5985 "a pre-existing {name} option id, name, color or description"
5986 ));
5987 }
5988 if !field.missing.iter().all(|wanted| {
5989 now.iter()
5990 .any(|option| option.name.as_str().eq_ignore_ascii_case(wanted))
5991 }) {
5992 moved.push(format!("an added {name} option"));
5993 }
5994 if after.assignments(field.field) != before.assignments(field.field) {
5995 moved.push(format!("an item's {name} value"));
5996 }
5997 }
5998 if !creates.is_empty() {
5999 // Read afresh: the view held for this command is the one from before the creates.
6000 *self.fields_cache()? = None;
6001 let board = match self.board_fields().await {
6002 Ok(board) => board,
6003 Err(error) => {
6004 return Err(SourceError::Refused {
6005 message: format!(
6006 "the guarded field setup changed the {} field and then could not \
6007 read the board back to verify it: {error}; run it again to verify \
6008 it, which creates nothing a second time",
6009 landed.join(" and ")
6010 ),
6011 });
6012 }
6013 };
6014 for field in &creates {
6015 let text = Board::field(&board.fields, &field.field)?.is_some_and(|held| {
6016 held.get("__typename").and_then(Value::as_str) == Some("ProjectV2Field")
6017 && held.get("dataType").and_then(Value::as_str) == Some("TEXT")
6018 });
6019 if !text {
6020 moved.push(format!("the created {} text field", field.field));
6021 }
6022 }
6023 }
6024 if !moved.is_empty() {
6025 return Err(SourceError::Refused {
6026 message: format!(
6027 "GitHub changed {} after the guarded field setup; the pre-write item \
6028 assignments are:\n{}",
6029 moved.join(", "),
6030 recovery(&report, &before)?
6031 ),
6032 });
6033 }
6034 Ok(report)
6035 }
6036
6037 /// Validate configuration and capture the named credential without exposing it.
6038 ///
6039 /// # Errors
6040 ///
6041 /// Returns [`SourceError::Config`] for a configuration this instance cannot use and
6042 /// [`SourceError::Auth`] when the named credential is missing or empty.
6043 pub fn new(
6044 name: &SourceName,
6045 config: GitHubProjectsConfig,
6046 secrets: &dyn SecretResolver,
6047 ) -> Result<Self, SourceError> {
6048 Self::recording_into(name, config, secrets, Arc::new(Accounting::new()))
6049 }
6050
6051 /// The same, recording every request it sends into an accounting the caller holds too.
6052 ///
6053 /// [`Self::new`] is this with an accounting of its own. A caller that is also making
6054 /// its own calls to GitHub — a lane verifying a schema, sweeping residue or cleaning
6055 /// up — passes the one it records those into, so the session total accounts for the
6056 /// whole session rather than for this source's share of it.
6057 ///
6058 /// # Errors
6059 ///
6060 /// Exactly [`Self::new`]'s: [`SourceError::Config`] for a configuration this instance
6061 /// cannot use and [`SourceError::Auth`] when the named credential is missing or empty.
6062 pub fn recording_into(
6063 name: &SourceName,
6064 config: GitHubProjectsConfig,
6065 secrets: &dyn SecretResolver,
6066 ledger: Arc<Accounting>,
6067 ) -> Result<Self, SourceError> {
6068 if !valid_github_owner(&config.owner) {
6069 return Err(SourceError::Config {
6070 message: "owner must be 1-39 ASCII letters, digits, or single hyphens, and cannot start or end with a hyphen".into(),
6071 });
6072 }
6073 if config.project_number == 0 || config.project_number > i32::MAX as u32 {
6074 return Err(SourceError::Config {
6075 message: format!("project_number must be between 1 and {}", i32::MAX),
6076 });
6077 }
6078 if !valid_environment_name(&config.token_env) {
6079 return Err(SourceError::Config {
6080 message: "token_env must be a valid environment-variable name".into(),
6081 });
6082 }
6083 let repository = config
6084 .repository
6085 .as_deref()
6086 .map(RepositoryTarget::parse)
6087 .transpose()?;
6088 if let Some(entry) = config
6089 .creation_owners
6090 .iter()
6091 .find(|entry| !valid_github_owner(entry))
6092 {
6093 return Err(SourceError::Config {
6094 message: format!(
6095 "creation_owners entry {entry:?} is not a GitHub login: a login is 1-39 ASCII \
6096 letters, digits, or single hyphens, and cannot start or end with a hyphen"
6097 ),
6098 });
6099 }
6100 let endpoint = Url::parse(&config.endpoint).map_err(|e| SourceError::Config {
6101 message: format!("endpoint is not a valid URL: {e}"),
6102 })?;
6103 if endpoint.scheme() != "https"
6104 && !(endpoint.scheme() == "http"
6105 && endpoint
6106 .host_str()
6107 .is_some_and(|h| h == "127.0.0.1" || h == "localhost" || h == "::1"))
6108 {
6109 return Err(SourceError::Config {
6110 message:
6111 "endpoint must use HTTPS (HTTP is accepted only for a loopback test server)"
6112 .into(),
6113 });
6114 }
6115 let token = secrets.get(&config.token_env).filter(|token| !token.expose_secret().trim().is_empty()).ok_or_else(|| SourceError::Auth {
6116 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),
6117 })?;
6118 Ok(Self {
6119 name: name.clone(),
6120 owner: config.owner,
6121 project_number: config.project_number,
6122 repository,
6123 creation_owners: config.creation_owners,
6124 asset_client: std::sync::OnceLock::new(),
6125 body_markup: std::sync::OnceLock::new(),
6126 endpoint,
6127 token,
6128 credential_name: config.token_env,
6129 statuses: BoardStatuses::resolve(&config.status_mapping, name)?,
6130 priorities: config
6131 .priority_mapping
6132 .map(|mapping| PriorityMapping::resolve(mapping, name))
6133 .transpose()?,
6134 metadata_fields: MetadataField::resolve(config.metadata_fields, name)?,
6135 sub_issues: config.sub_issues,
6136 assignees: config.assignees,
6137 people: Mutex::new(BTreeMap::new()),
6138 forgotten: Mutex::new(Vec::new()),
6139 spellings: Mutex::new(BTreeMap::new()),
6140 link_types: onetaskgraph_plugin_api::LinkTypes::checked(
6141 KIND,
6142 &config.link_types,
6143 &[relations::RELATES_TO],
6144 relations::REFUSED_WORDS,
6145 )
6146 .map_err(|error| match error {
6147 SourceError::Config { message } => SourceError::Config {
6148 message: format!("source {name}: {message}"),
6149 },
6150 other => other,
6151 })?,
6152 client: std::sync::OnceLock::new(),
6153 created: Mutex::new(Vec::new()),
6154 updated: Mutex::new(Vec::new()),
6155 commented: Mutex::new(Vec::new()),
6156 pacing: Pacing::resolve(config.pacing, name)?,
6157 last_mutation: Mutex::new(None),
6158 last_served: Mutex::new(None),
6159 windows: Mutex::new(pacing::Windows::default()),
6160 task_children: Mutex::new(BTreeMap::new()),
6161 written: Mutex::new(BTreeMap::new()),
6162 deferred: Mutex::new(None),
6163 held_updates: Mutex::new(Vec::new()),
6164 held_comments: Mutex::new(BTreeMap::new()),
6165 task_writes: Mutex::new(None),
6166 written_tokens: Mutex::new(BTreeMap::new()),
6167 clock: system_clock(),
6168 declared_private: std::sync::atomic::AtomicBool::new(false),
6169 numeric_repositories: tokio::sync::Mutex::new(BTreeMap::new()),
6170 board_cache: Mutex::new(None),
6171 search_cache: Mutex::new(None),
6172 narrowed_cache: Mutex::new(BTreeMap::new()),
6173 resolved_cache: Mutex::new(BTreeMap::new()),
6174 read_ahead: Mutex::new(BTreeMap::new()),
6175 pending_origins: Mutex::new(Vec::new()),
6176 member_classes: Mutex::new(BTreeMap::new()),
6177 carried: Mutex::new(BTreeMap::new()),
6178 held_cache: Mutex::new(BTreeMap::new()),
6179 children_cache: Mutex::new(BTreeMap::new()),
6180 search_next: Mutex::new(BTreeMap::new()),
6181 fields_cache: Mutex::new(None),
6182 repository_cache: Mutex::new(BTreeMap::new()),
6183 ledger,
6184 expected: expected::Held::default(),
6185 projection: projection::Held::default(),
6186 })
6187 }
6188
6189 /// The client every API request goes through, built on the first one.
6190 ///
6191 /// Not with the source: building a client loads the system's certificate store, which
6192 /// costs tens of milliseconds, and a command that configures this board but never sends to
6193 /// it — a read of another source — should not pay that in its process.
6194 fn client(&self) -> Result<&Client, SourceError> {
6195 built(&self.client, || {
6196 Client::builder()
6197 .user_agent("onetaskgraph")
6198 .build()
6199 .map_err(|e| SourceError::Config {
6200 message: format!("cannot build HTTP client: {e}"),
6201 })
6202 })
6203 }
6204
6205 /// The client attachment requests go through, with its own redirect policy, built on the
6206 /// first one for the reason [`Self::client`] gives.
6207 fn asset_client(&self) -> Result<&Client, SourceError> {
6208 built(&self.asset_client, || assets::client(&self.endpoint))
6209 }
6210
6211 /// A snapshot of every request this source has sent, and what each cost.
6212 ///
6213 /// A value to hold and compare rather than a borrow of the accounting itself, so two
6214 /// of them can sit side by side. When this source was built with
6215 /// [`Self::recording_into`] the snapshot is the whole shared session, which is the
6216 /// point of building it that way.
6217 #[must_use]
6218 pub fn accounting(&self) -> accounting::Session {
6219 self.ledger.snapshot()
6220 }
6221
6222 /// Send one GraphQL document, pacing this source's own mutations and waiting out a
6223 /// rate limit rather than handing it straight back as an error.
6224 ///
6225 /// Retrying is safe for every document here, including the mutations, and the reason
6226 /// is that only a *refusal* is retried: [`Limiter::classify`] rules on a response
6227 /// GitHub sent, and a request GitHub refused for a rate limit did not run, so nothing
6228 /// this replays has already taken effect. An outcome this source cannot know — the
6229 /// send failed, or the body could not be read, so the mutation may well have landed —
6230 /// is [`Attempt::Failed`] in [`send_once`] and leaves this loop without a second
6231 /// attempt. A duplicate write would come from replaying one of those, and none is
6232 /// replayed.
6233 async fn graphql(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
6234 // Updates held back go out before any other request, so whatever it reads or writes
6235 // sees the board as though each had been sent when it was made.
6236 Box::pin(self.send_held_updates()).await?;
6237 // Origins held back for a read ahead that never came are sent before anything else.
6238 if query != graphql::ORIGIN_LOOKUPS && query != graphql::ORIGIN_LOOKUPS_WITH_MEMBERS {
6239 Box::pin(self.send_pending_origins(None)).await?;
6240 }
6241 let journaling = self.expected.journaling();
6242 let spelling = self.spelling();
6243 if !journaling && !spelling {
6244 return self.graphql_sent(query, variables).await;
6245 }
6246 // While a write the store's cache expects runs, its mutations select the whole issue
6247 // they leave behind, so the response vouches for what the cache keeps — and every
6248 // request is recorded, so the write's parts are reported from their own responses.
6249 // A targeted update sends a twin of each selecting the issue's token parts inline, at
6250 // the same price, so the version it answers is the one its own last response spells.
6251 let (query, variables) = match (journaling, graphql::whole_twin(query)) {
6252 (true, Some(twin)) => (twin, expected::whole_variables(variables)),
6253 _ => match graphql::token_twin(query).filter(|_| spelling) {
6254 Some(twin) => (twin, token_variables(variables)),
6255 None => (query, variables),
6256 },
6257 };
6258 let sent = self.graphql_sent(query, variables.clone()).await;
6259 if spelling && let Ok(data) = &sent {
6260 self.record_written_token(query, &variables, data);
6261 }
6262 if journaling {
6263 self.journal(query, &variables, &sent).await;
6264 }
6265 sent
6266 }
6267
6268 /// Whether a targeted update of this source is running, whose mutations are each sent as
6269 /// the twin selecting the whole issue (see [`Self::written_tokens`]).
6270 fn spelling(&self) -> bool {
6271 SPELLING
6272 .try_with(|source| *source == std::ptr::from_ref(self) as usize)
6273 .unwrap_or(false)
6274 }
6275
6276 /// Record the change token the issue a mutation's response shows whole holds now, as
6277 /// [`TaskSource::written_task`] answers it; a response showing no whole issue records
6278 /// nothing.
6279 fn record_written_token(&self, document: &str, variables: &Value, data: &Value) {
6280 let (issue, _) = expected::read_back(document, variables, data);
6281 if let Some(issue) = issue {
6282 self.record_written_issue(issue);
6283 }
6284 }
6285
6286 /// Record the change token `issue`, as a write's own answer shows it whole, holds now — or,
6287 /// where that answer lacks a part of one, that it was shown and spells none.
6288 fn record_written_issue(&self, issue: &Value) {
6289 // An answer naming the issue by its id alone did not show it, so it says nothing.
6290 if issue.get("updatedAt").is_none() {
6291 return;
6292 }
6293 let Some(id) = issue.get("id").and_then(Value::as_str) else {
6294 return;
6295 };
6296 let (item, token) = match self.written_token_of(issue) {
6297 Some((item, token)) => (item, Some(token)),
6298 None => {
6299 // Answered whole, but without every part of a token: its board item's id, where
6300 // it says one, so a later write naming that item still drops the entry.
6301 let item = issue
6302 .pointer("/projectItems/nodes")
6303 .and_then(Value::as_array)
6304 .and_then(|nodes| self.board_entry(nodes))
6305 .and_then(|entry| entry.get("id"))
6306 .and_then(Value::as_str)
6307 .unwrap_or_default()
6308 .to_owned();
6309 (item, None)
6310 }
6311 };
6312 if let Ok(mut tokens) = self.written_tokens.lock() {
6313 tokens.insert(NativeId(id.to_owned()), (item, token));
6314 }
6315 }
6316
6317 /// Record `token` as the change token the task `item` holds after this command's write.
6318 fn remember_written_token(&self, item: &Resolved, token: String) {
6319 if let Ok(mut tokens) = self.written_tokens.lock() {
6320 tokens.insert(item.id.clone(), (item.item_id.clone(), Some(token)));
6321 }
6322 }
6323
6324 /// The change token the task `id` holds after this command's latest write of it, when that
6325 /// write's own response — or the read made right after it — showed one.
6326 fn written_token(&self, id: &NativeId) -> Option<String> {
6327 self.written_answer(id).flatten()
6328 }
6329
6330 /// What this command's latest write of the task `id` showed of it: `Some` once a response
6331 /// showed the issue whole — its token, or `None` where that response could not spell one —
6332 /// and `None` where no response did.
6333 fn written_answer(&self, id: &NativeId) -> Option<Option<String>> {
6334 self.written_tokens
6335 .lock()
6336 .ok()?
6337 .get(id)
6338 .map(|(_, token)| token.clone())
6339 }
6340
6341 /// Drop the written token of every task `variables` names, by its id or its board item's,
6342 /// before a mutation that may move it is sent.
6343 fn forget_written_tokens(&self, variables: &Value) {
6344 let Ok(mut tokens) = self.written_tokens.lock() else {
6345 return;
6346 };
6347 if tokens.is_empty() {
6348 return;
6349 }
6350 let named: Vec<&str> = variables
6351 .as_object()
6352 .into_iter()
6353 .flat_map(|arguments| arguments.values())
6354 .flat_map(|input| {
6355 WRITTEN_NAMES
6356 .iter()
6357 .filter_map(|key| input.get(key).and_then(Value::as_str))
6358 })
6359 .collect();
6360 tokens.retain(|id, (item, _)| {
6361 !named
6362 .iter()
6363 .any(|name| *name == id.0 || *name == item.as_str())
6364 });
6365 }
6366
6367 /// One document sent, retried while GitHub asks for a wait, exactly as asked.
6368 async fn graphql_sent(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
6369 if is_mutation(query) {
6370 self.forget_written_tokens(&variables);
6371 }
6372 if is_mutation(query)
6373 && ![
6374 graphql::ADD_COMMENT,
6375 graphql::UPDATE_COMMENT,
6376 graphql::DELETE_COMMENT,
6377 graphql::ADD_COMMENT_WHOLE,
6378 graphql::UPDATE_COMMENT_WHOLE,
6379 ]
6380 .contains(&query)
6381 {
6382 let mut cache = self.resolved_cache()?;
6383 let mut ahead = self.read_ahead()?;
6384 let mut carried = self.carried()?;
6385 for argument in ["input", "second", "third", "clear"] {
6386 if let Some(input) = variables.get(argument) {
6387 let names = |id: &NativeId, item_id: Option<&str>| {
6388 ["id", "issueId", "subjectId", "itemId"].iter().any(|key| {
6389 input
6390 .get(key)
6391 .and_then(Value::as_str)
6392 .is_some_and(|value| value == id.0 || Some(value) == item_id)
6393 })
6394 };
6395 cache.retain(|id, item| !names(id, Some(&item.item_id)));
6396 ahead.retain(|id, item| {
6397 !names(id, item.as_ref().map(|item| item.item_id.as_str()))
6398 });
6399 carried.retain(|id, item| !names(id, Some(&item.item_id)));
6400 }
6401 }
6402 }
6403 let doing = operation_description(query);
6404 let mutation = is_mutation(query);
6405 let charge = pacing::Charge::graphql(query, &variables);
6406 let mut waited = Duration::ZERO;
6407 let mut waits = 0_u32;
6408 let mut backoff = self.pacing.retry_backoff;
6409 loop {
6410 let ticket = self.pace(charge, mutation).await;
6411 // Every write but a create is asked for immediately before it is sent — a create's
6412 // fields, its relationships, its content and the delete that takes it back included
6413 // — so a copy that owns the create renews its hold first, and one that has lost it
6414 // sends nothing more. Asked again before a retry, which is sent later.
6415 if mutation
6416 && !query.contains("createIssue(")
6417 && let Err(refused) = <dyn onetaskgraph_plugin_api::WriteGuard>::check().await
6418 {
6419 self.paced(ticket, mutation);
6420 return Err(refused);
6421 }
6422 // And of a caller's request gate, before every request this source sends — a retry
6423 // as its own — so a caller pacing its own floor inside one call waits or stops here.
6424 let admitted = match <dyn onetaskgraph_plugin_api::RequestGate>::before(&gated_graphql(
6425 query, &variables,
6426 ))
6427 .await
6428 {
6429 Ok(admitted) => admitted,
6430 Err(refused) => {
6431 self.paced(ticket, mutation);
6432 return Err(refused);
6433 }
6434 };
6435 let attempt = self.send_once(query, &variables, waits + 1).await;
6436 // Over however it ended — answered, refused or failed before any header — and
6437 // ended before any wait for a retry, which is asked for as a request of its own.
6438 admitted.end();
6439 self.paced(ticket, mutation);
6440 let remaining = self.pacing.retry_budget.saturating_sub(waited);
6441 let (wait, cause) = match attempt {
6442 Ok(data) => return Ok(data),
6443 Err(Attempt::Failed(error)) => return Err(error),
6444 Err(Attempt::Conflicted(said)) => {
6445 // A create is never replayed: see `CONFLICT_WORDINGS`.
6446 if query.contains("createIssue(") || backoff.is_zero() || backoff > remaining {
6447 return Err(SourceError::Unavailable {
6448 message: format!(
6449 "GitHub refused this source while {doing} as a temporary \
6450 conflict ({said}); it retried {} over {} and the conflict \
6451 did not clear within the {} one call may spend waiting. \
6452 next: run the command again once nothing else is writing to \
6453 the same items",
6454 plural(waits, "time"),
6455 seconds(waited),
6456 seconds(self.pacing.retry_budget),
6457 ),
6458 });
6459 }
6460 (backoff, pacing::cause::BACKOFF)
6461 }
6462 Err(Attempt::Limited(limited)) => {
6463 let (wait, cause) = limited.wait(backoff);
6464 // A wait of nothing spends none of the budget, so it is exhaustion rather
6465 // than a retry. `Pacing::resolve` rules out every way of configuring one
6466 // except a budget of zero, where reporting the first refusal is the ask.
6467 if wait.is_zero() || wait > remaining {
6468 return Err(limited.exhausted(
6469 doing,
6470 waits,
6471 waited,
6472 wait,
6473 self.pacing.retry_budget,
6474 ));
6475 }
6476 (wait, cause)
6477 }
6478 };
6479 self.clock.sleep_because(wait, cause).await;
6480 waited += wait;
6481 waits += 1;
6482 backoff = backoff.saturating_mul(2);
6483 }
6484 }
6485
6486 /// Hold one request charging `charge` until every secondary window it charges has room for
6487 /// the whole of it — and, for a mutation of an instance configured with
6488 /// `pacing.min_mutation_interval_ms`, until that interval has passed since the last one
6489 /// finished — then count it, answering the ticket [`Self::paced`] finishes it with.
6490 ///
6491 /// The moment is decided and counted under the lock and waited out outside it, so two
6492 /// callers take two places rather than the same one, and no lock is held across an await.
6493 /// A request with room goes out at once: nothing here waits that a window does not ask for.
6494 async fn pace(&self, charge: pacing::Charge, mutation: bool) -> pacing::Ticket {
6495 let (wait, cause, ticket) = {
6496 // A poisoned lock here costs pacing, not correctness, and refusing the write over
6497 // it would turn an earlier failure into a second one for no gain.
6498 let mut windows = self
6499 .windows
6500 .lock()
6501 .unwrap_or_else(std::sync::PoisonError::into_inner);
6502 let now = self.clock.now();
6503 let (mut at, mut cause) = if self.pacing.windows {
6504 windows.room(now, charge)
6505 } else {
6506 (now, None)
6507 };
6508 if mutation && !self.pacing.min_mutation_interval.is_zero() {
6509 let mut last = self
6510 .last_mutation
6511 .lock()
6512 .unwrap_or_else(std::sync::PoisonError::into_inner);
6513 // `checked_add` rather than `+`: adding durations can panic on overflow, and
6514 // pacing is not worth a panic even at a bound `MAX_PACING_MS` already rules out.
6515 if let Some(earliest) = last
6516 .and_then(|previous| previous.checked_add(self.pacing.min_mutation_interval))
6517 && earliest > at
6518 {
6519 at = earliest;
6520 cause = Some(pacing::cause::MIN_INTERVAL);
6521 }
6522 *last = Some(at);
6523 }
6524 let ticket = windows.charge(at, charge);
6525 (at.saturating_sub(now), cause, ticket)
6526 };
6527 if let (false, Some(cause)) = (wait.is_zero(), cause) {
6528 self.clock.sleep_because(wait, cause).await;
6529 }
6530 ticket
6531 }
6532
6533 /// Record that the request `ticket` was charged for has finished, so each window — and
6534 /// the configured spacing — counts it from here rather than from the moment it left.
6535 ///
6536 /// This source can only choose when a request *departs*; GitHub's limiter counts when it
6537 /// *arrives*, and the two differ by whatever the request spent in transit. Counting from
6538 /// departure would hand the limiter a window that looked roomier than it is, so a source
6539 /// pacing exactly at a limit could still be seen arriving over it — which is how a copy
6540 /// paced well inside a board's threshold was once refused by it on a slower machine while
6541 /// passing on a quick one. The previous request had arrived before its response came back,
6542 /// so counting from here is never earlier than the limiter does, whatever transit costs
6543 /// and on whatever platform: the safe side of a limit that punishes being wrong by refusing
6544 /// reads for the next fifty minutes.
6545 ///
6546 /// A failed attempt is finished too: a request refused by the limiter still arrived, and
6547 /// one that never left costs only room nobody needed.
6548 fn paced(&self, ticket: pacing::Ticket, mutation: bool) {
6549 let now = self.clock.now();
6550 self.windows
6551 .lock()
6552 .unwrap_or_else(std::sync::PoisonError::into_inner)
6553 .finish(ticket, now);
6554 if mutation && !self.pacing.min_mutation_interval.is_zero() {
6555 let mut last = self
6556 .last_mutation
6557 .lock()
6558 .unwrap_or_else(std::sync::PoisonError::into_inner);
6559 // `max` rather than an assignment: a concurrent caller may already have reserved a
6560 // slot further out, and completing this request must never pull that slot back in.
6561 *last = Some(last.map_or(now, |reserved| reserved.max(now)));
6562 }
6563 }
6564
6565 /// One HTTP attempt, classified into an answer, a rate limit to wait out, or a
6566 /// failure that waiting cannot help — and recorded, whichever of the three it was.
6567 ///
6568 /// This is the one place a request leaves this crate, which is why the accounting is
6569 /// here rather than at each of the callers: a read path added later is counted without
6570 /// anybody remembering to count it, and
6571 /// `the_session_report_counts_every_request_the_board_served_and_what_each_cost` fails
6572 /// when one is not.
6573 async fn send_once(
6574 &self,
6575 query: &str,
6576 variables: &Value,
6577 number: u32,
6578 ) -> Result<Value, Attempt> {
6579 // A lookup goes out sized to the people it names, and the record names and counts it as
6580 // what it is; everything that decides how it is retried or read compares `query`, the
6581 // constant it was written as.
6582 let sized = graphql::sized(query, variables);
6583 let executed = self.ledger.priced_document(sized.as_ref());
6584 let Attempted {
6585 result,
6586 limits,
6587 reported_cost,
6588 response_outcome,
6589 } = self.attempt(executed.as_ref(), variables).await;
6590 // No `otherwise` name: every document this source sends is one of its own, and the
6591 // inventory gate on `graphql::DOCUMENTS` is what keeps that true.
6592 let sending = accounting::Request::graphql(sized.as_ref(), variables, None, reported_cost);
6593 let outcome = match &result {
6594 Ok(_) => accounting::Outcome::Answered,
6595 Err(Attempt::Limited(_)) => accounting::Outcome::RateLimited,
6596 Err(Attempt::Failed(_) | Attempt::Conflicted(_)) => accounting::Outcome::Refused,
6597 };
6598 self.ledger
6599 .record(sending.finished(outcome, limits).with_execution(
6600 Some(executed.into_owned()),
6601 response_outcome,
6602 number,
6603 ));
6604 result
6605 }
6606
6607 /// The attempt itself, with what its response said about the rate limit alongside.
6608 ///
6609 /// The two are returned together rather than recorded here because every one of the
6610 /// early exits below is a different outcome, and a record written at each of them is a
6611 /// record one of them can be added without.
6612 async fn attempt(&self, query: &str, variables: &Value) -> Attempted {
6613 let mut limits = accounting::RateLimit::default();
6614 let mut reported_cost = None;
6615 let mut response_outcome = accounting::ResponseOutcome::TransportError;
6616 // Spelled here, at the one place a document leaves for GitHub, and nowhere earlier:
6617 // everything that decides how a document is retried or how its answer is read compares
6618 // it with the constant it was written as.
6619 let spelled = self
6620 .assignees
6621 .then(|| graphql::with_assignees(query))
6622 .flatten();
6623 let result = self
6624 .attempted(
6625 query,
6626 spelled.as_deref().unwrap_or(query),
6627 variables,
6628 &mut limits,
6629 &mut reported_cost,
6630 &mut response_outcome,
6631 )
6632 .await;
6633 Attempted {
6634 result,
6635 limits,
6636 reported_cost,
6637 response_outcome,
6638 }
6639 }
6640
6641 /// One HTTP attempt, filling in what its response said about the rate limit as it goes.
6642 async fn attempted(
6643 &self,
6644 query: &str,
6645 sent: &str,
6646 variables: &Value,
6647 limits: &mut accounting::RateLimit,
6648 reported_cost: &mut Option<u64>,
6649 response_outcome: &mut accounting::ResponseOutcome,
6650 ) -> Result<Value, Attempt> {
6651 let response = self
6652 .client()
6653 .map_err(Attempt::Failed)?
6654 .post(self.endpoint.clone())
6655 .bearer_auth(self.token.expose_secret())
6656 .json(&json!({"query": sent, "variables": variables}))
6657 .send()
6658 .await
6659 .map_err(|e| {
6660 Attempt::Failed(SourceError::Unavailable {
6661 message: format!("GitHub GraphQL request failed: {}", transport_error(&e)),
6662 })
6663 })?;
6664 let status = response.status();
6665 if !status.is_success() {
6666 *response_outcome = accounting::ResponseOutcome::HttpError;
6667 }
6668 let header = |name: &str| whole_seconds(response.headers().get(name));
6669 let served = response
6670 .headers()
6671 .get(reqwest::header::DATE)
6672 .and_then(|value| value.to_str().ok())
6673 .and_then(|value| DateTime::parse_from_rfc2822(value).ok())
6674 .map(|at| at.with_timezone(&Utc));
6675 *limits = accounting::RateLimit::read(|name| {
6676 response
6677 .headers()
6678 .get(name)
6679 .and_then(|value| value.to_str().ok())
6680 .map(str::to_owned)
6681 });
6682 // Each response's own reading, as it gave it: never merged with another window's.
6683 <dyn onetaskgraph_plugin_api::RequestGate>::after("a::header_readings(limits));
6684 // Exactly `0` is exhaustion and everything else — a count, an empty value, bytes
6685 // that are not text at all — is "not known to be exhausted". This never makes a
6686 // response a refusal on its own: it says which limiter a refusal is attributed to
6687 // and where its hint comes from, so a value this cannot read costs a hint rather
6688 // than an answer.
6689 let exhausted = response
6690 .headers()
6691 .get("x-ratelimit-remaining")
6692 .and_then(|value| value.to_str().ok())
6693 == Some("0");
6694 // `retry-after` is what GitHub asks for when it asks; when it does not and the
6695 // primary budget is spent, `x-ratelimit-reset` says when that budget comes back,
6696 // which is the same question answered as an absolute time. Nothing else here is a
6697 // hint, and a schedule is what answers a refusal that carries none.
6698 let retry_after = header("retry-after");
6699 let hinted_by = if retry_after.is_some() || !exhausted {
6700 Hint::RetryAfter
6701 } else {
6702 Hint::PrimaryReset
6703 };
6704 let hint = retry_after.or_else(|| {
6705 exhausted
6706 .then(|| header("x-ratelimit-reset"))
6707 .flatten()
6708 .map(|reset| reset.saturating_sub(Utc::now().timestamp().max(0).unsigned_abs()))
6709 });
6710 // Read before it is parsed, because the evidence which tells a secondary rate
6711 // limit from a rejected credential is in the body of a response whose status says
6712 // only "forbidden" — and a non-success response was never parsed at all.
6713 let body = response.text().await.map_err(|e| {
6714 Attempt::Failed(SourceError::Unavailable {
6715 message: format!(
6716 "GitHub GraphQL response could not be read: {}",
6717 transport_error(&e)
6718 ),
6719 })
6720 })?;
6721 *reported_cost = serde_json::from_str::<Value>(&body)
6722 .ok()
6723 .as_ref()
6724 .and_then(|body| body.pointer("/data/rateLimit/cost"))
6725 .and_then(Value::as_u64);
6726 let parsed = serde_json::from_str::<Value>(&body).ok();
6727 *response_outcome = accounting::ResponseOutcome::of_graphql_reply(status, parsed.as_ref());
6728 if let Some(limiter) = Limiter::classify(status, exhausted, &body) {
6729 return Err(Attempt::Limited(Limited {
6730 limiter,
6731 hint,
6732 hinted_by,
6733 }));
6734 }
6735 if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
6736 return Err(Attempt::Failed(SourceError::Auth {
6737 message: format!(
6738 "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"
6739 ),
6740 }));
6741 }
6742 if !status.is_success() {
6743 return Err(Attempt::Failed(SourceError::Unavailable {
6744 message: format!("GitHub GraphQL returned HTTP {status}"),
6745 }));
6746 }
6747 let said = refusal_wording(status, &body);
6748 let normalized = said.to_ascii_lowercase();
6749 if CONFLICT_WORDINGS
6750 .iter()
6751 .any(|wording| normalized.contains(wording))
6752 {
6753 return Err(Attempt::Conflicted(said));
6754 }
6755 // A lookup is read as the inventoried document it was sized from.
6756 let query = graphql::inventoried(query);
6757 let answered = if query == graphql::ISSUES_BY_REFERENCE {
6758 self.answer_unresolved(&body)
6759 } else if [
6760 graphql::CREATE_ISSUES,
6761 graphql::SEARCH_BATCH,
6762 graphql::USER_IDS,
6763 graphql::ADD_COMMENTS,
6764 graphql::WRITE_TASKS,
6765 graphql::SET_PARENTS,
6766 graphql::ADD_RELATES_TO,
6767 graphql::REMOVE_RELATES_TO,
6768 ]
6769 .contains(&query)
6770 {
6771 answer_with_errors(&body).map_or_else(|| self.answer(&body), Ok)
6772 } else {
6773 self.answer(&body)
6774 };
6775 let mut data = answered.map_err(Attempt::Failed)?;
6776 if let Some(served) = served {
6777 *self
6778 .last_served
6779 .lock()
6780 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(served);
6781 stamp_served(&mut data, &served.to_rfc3339());
6782 }
6783 Ok(data)
6784 }
6785
6786 /// What one successful HTTP response says, once its GraphQL errors are read.
6787 /// [`Self::answer`], for a read of issues by reference: a reference GitHub cannot resolve
6788 /// for this credential — a repository it cannot see, an issue number it does not hold —
6789 /// is answered `null` beside a `NOT_FOUND` error naming it, and that is an answer about
6790 /// that reference rather than a failure of the others. Any other error refuses the read,
6791 /// as there.
6792 fn answer_unresolved(&self, body: &str) -> Result<Value, SourceError> {
6793 let parsed: Option<Value> = serde_json::from_str(body).ok();
6794 // Each error is a `NOT_FOUND` whose path names one slot of the batch, `r<n>` or its
6795 // `issue`, and the answer holds `null` at exactly that path: anything else — another
6796 // kind of error, one naming no slot, or one beside a value it says is not there — is a
6797 // refusal of the whole read.
6798 let unresolved = |data: &Value, error: &Value| {
6799 error.get("type").and_then(Value::as_str) == Some("NOT_FOUND")
6800 && error
6801 .get("path")
6802 .and_then(Value::as_array)
6803 .is_some_and(|path| {
6804 let alias = path.first().and_then(Value::as_str).and_then(|alias| {
6805 alias
6806 .strip_prefix('r')
6807 .and_then(|slot| slot.parse::<usize>().ok())
6808 .filter(|slot| *slot < REFERENCE_BATCH)
6809 .map(|_| alias)
6810 });
6811 match (alias, path.get(1).and_then(Value::as_str), path.len()) {
6812 (Some(alias), None, 1) => data.get(alias).is_some_and(Value::is_null),
6813 (Some(alias), Some("issue"), 2) => data
6814 .get(alias)
6815 .and_then(|repository| repository.get("issue"))
6816 .is_some_and(Value::is_null),
6817 _ => false,
6818 }
6819 })
6820 };
6821 let unresolved_only = parsed.as_ref().is_some_and(|parsed| {
6822 parsed.get("data").is_some_and(|data| {
6823 data.is_object()
6824 && parsed
6825 .get("errors")
6826 .and_then(Value::as_array)
6827 .is_some_and(|errors| errors.iter().all(|error| unresolved(data, error)))
6828 })
6829 });
6830 match parsed {
6831 Some(parsed) if unresolved_only => Ok(parsed["data"].clone()),
6832 _ => self.answer(body),
6833 }
6834 }
6835
6836 fn answer(&self, body: &str) -> Result<Value, SourceError> {
6837 let body: Value = serde_json::from_str(body).map_err(|e| SourceError::Malformed {
6838 message: format!("GitHub returned invalid JSON: {e}"),
6839 })?;
6840 let errors = body
6841 .get("errors")
6842 .map(|value| {
6843 value.as_array().ok_or_else(|| SourceError::Malformed {
6844 message: "GitHub response errors is not an array".into(),
6845 })
6846 })
6847 .transpose()?;
6848 if let Some(errors) = errors.filter(|errors| !errors.is_empty()) {
6849 let messages = errors
6850 .iter()
6851 .filter_map(|e| e.get("message").and_then(Value::as_str))
6852 .collect::<Vec<_>>()
6853 .join("; ");
6854 let message = if messages.is_empty() {
6855 "GitHub returned GraphQL errors".into()
6856 } else {
6857 messages
6858 };
6859 let normalized = message.to_ascii_lowercase();
6860 if normalized.contains("resource not accessible") || normalized.contains("scope") {
6861 return Err(SourceError::Auth {
6862 message: format!(
6863 "{message}; grant {} Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board",
6864 self.credential_name
6865 ),
6866 });
6867 }
6868 return Err(SourceError::Refused { message });
6869 }
6870 body.get("data")
6871 .filter(|data| data.is_object())
6872 .cloned()
6873 .ok_or_else(|| SourceError::Malformed {
6874 message: "GitHub response has no data object".into(),
6875 })
6876 }
6877
6878 // llmlint: ignore[boundary_inputs_validated] GitHub caps nested connections at 100 and
6879 // GraphQL cannot independently page them inside the outer item page. This source page is
6880 // deliberately bounded at that published maximum; the live drift journey exercises it.
6881 async fn board_page(
6882 &self,
6883 items_after: Option<&str>,
6884 items_first: u32,
6885 ) -> Result<Value, SourceError> {
6886 let data = self
6887 .graphql(
6888 graphql::BOARD,
6889 json!({"owner":self.owner,"number":self.project_number,
6890 "first":items_first.min(MAX_PAGE_SIZE),"after":items_after,
6891 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
6892 )
6893 .await?;
6894 data.pointer("/owner/projectV2")
6895 .filter(|v| !v.is_null())
6896 .cloned()
6897 .ok_or_else(|| SourceError::Refused {
6898 message: format!(
6899 "GitHub project {}/{} was not found or is not visible to the token",
6900 self.owner, self.project_number
6901 ),
6902 })
6903 }
6904
6905 /// The search that finds the issues of this board, narrowed by `also` when it is
6906 /// given.
6907 ///
6908 /// `project:owner/number` is what scopes a search to one board, and `is:issue` is what
6909 /// keeps pull requests out of it: GitHub's `ISSUE` search type covers both, and a pull
6910 /// request is somebody's change rather than a unit of plan. `-has:parent` is *not*
6911 /// here on purpose — GitHub accepts it and silently ignores it, so a project is told
6912 /// from a task by the `parent` field each issue carries rather than by the search.
6913 fn board_search(&self, also: Option<&str>) -> String {
6914 let scope = format!("project:{}/{} is:issue", self.owner, self.project_number);
6915 match also {
6916 Some(also) => format!("{scope} {also}"),
6917 None => scope,
6918 }
6919 }
6920
6921 /// One issue this source reached directly, as the board item a read of the board would
6922 /// have produced — or `None` when this board does not hold it.
6923 ///
6924 /// The board half of an issue rides along on `Issue.projectItems`, so the value handed
6925 /// to [`Self::resolve`] is the very shape a `ProjectV2.items` read gives it: the board
6926 /// item's own id, that item's field values, and the issue as its content. One resolver
6927 /// for both routes is what makes an issue read through a search, through its own node
6928 /// id, or through its project's sub-issues report the same title, the same status, the
6929 /// same labels and the same qualified id.
6930 ///
6931 /// An issue with no entry for *this* board is not this source's to report, which is
6932 /// what keeps an id naming some other repository's issue from being answered as an item
6933 /// of this board. That answer is given about an **exhausted** connection and never
6934 /// about an unread page: the entry is looked for on the page in hand, and only if that
6935 /// page reports more of the connection, in [`Self::board_membership`]'s walk of the
6936 /// rest of it.
6937 async fn resolve_issue(&self, issue: &Value) -> Result<Option<Resolved>, SourceError> {
6938 self.resolve_issue_as(issue, true).await
6939 }
6940
6941 /// [`Self::resolve_issue`], remembering what it resolves for this command's later reads
6942 /// and writes only when `remember` says to.
6943 async fn resolve_issue_as(
6944 &self,
6945 issue: &Value,
6946 remember: bool,
6947 ) -> Result<Option<Resolved>, SourceError> {
6948 if optional_str(issue, "__typename")? != Some("Issue") {
6949 return Ok(None);
6950 }
6951 let memberships = issue
6952 .get("projectItems")
6953 .ok_or_else(|| SourceError::Malformed {
6954 message: "GitHub issue is missing projectItems".into(),
6955 })?;
6956 let nodes = memberships
6957 .get("nodes")
6958 .and_then(Value::as_array)
6959 .ok_or_else(|| SourceError::Malformed {
6960 message: "GitHub issue projectItems.nodes is not an array".into(),
6961 })?;
6962 let held = match self.board_entry(nodes) {
6963 Some(held) => held.clone(),
6964 None => {
6965 let info = memberships
6966 .get("pageInfo")
6967 .ok_or_else(|| SourceError::Malformed {
6968 message: "GitHub issue projectItems has no pageInfo".into(),
6969 })?;
6970 // The page held no entry for this board. Whether that means the issue is
6971 // not on it is a question about the rest of the connection, and only a
6972 // connection with no rest answers it here.
6973 if !required_bool(info, "hasNextPage")? {
6974 return Ok(None);
6975 }
6976 let cursor = required_str(info, "endCursor")?;
6977 validate_cursor_progress(None, cursor)?;
6978 let issue_id = required_str(issue, "id")?;
6979 match self.board_membership(issue_id, cursor).await? {
6980 Some(held) => held,
6981 None => return Ok(None),
6982 }
6983 }
6984 };
6985 // The membership's own `updatedAt` rides along: it is the board half of the item's change
6986 // token, which a field change moves where the issue's own time does not.
6987 let item = json!({
6988 "id": required_str(&held, "id")?,
6989 "updatedAt": held.get("updatedAt"),
6990 "project": held.get("project"),
6991 "fieldValues": held.get("fieldValues"),
6992 "content": issue,
6993 });
6994 if remember {
6995 self.resolve(&item)
6996 } else {
6997 self.resolve_unremembered(&item)
6998 }
6999 }
7000
7001 /// This board's own entry among one page of an issue's `Issue.projectItems`.
7002 ///
7003 /// One spelling of *which membership is this board's*, so the page a read carries and
7004 /// the pages [`Self::board_membership`] walks are searched by the same rule.
7005 fn board_entry<'a>(&self, nodes: &'a [Value]) -> Option<&'a Value> {
7006 nodes.iter().find(|node| {
7007 node.pointer("/project/number").and_then(Value::as_u64)
7008 == Some(u64::from(self.project_number))
7009 })
7010 }
7011
7012 /// The rest of one issue's board memberships, from `after`, for this board's entry.
7013 ///
7014 /// The recovery read: a page of memberships that holds no entry for this board says
7015 /// nothing about the memberships past it, so the connection is walked to exhaustion
7016 /// before an issue is reported as one this board does not hold. `Ok(None)` is that
7017 /// positive answer — the whole connection was read and no entry named this board —
7018 /// rather than a failure, and the walk is held to
7019 /// [`validate_cursor_progress`] like every other page walk here, so a source answering
7020 /// with a cursor that does not advance is refused instead of spun on.
7021 async fn board_membership(
7022 &self,
7023 issue: &str,
7024 after: &str,
7025 ) -> Result<Option<Value>, SourceError> {
7026 let mut after = after.to_owned();
7027 loop {
7028 let data = self
7029 .graphql(
7030 graphql::ISSUE_BOARD_ITEMS,
7031 json!({"id":issue,"first":MAX_PAGE_SIZE,"after":after,
7032 "nestedFirst":NESTED_PAGE_SIZE}),
7033 )
7034 .await?;
7035 let Some(connection) = data
7036 .pointer("/node/projectItems")
7037 .filter(|value| !value.is_null())
7038 else {
7039 // The id resolved to nothing, or to something with no memberships to walk —
7040 // which is the same answer as a connection holding no entry for this board.
7041 return Ok(None);
7042 };
7043 let nodes = connection
7044 .get("nodes")
7045 .and_then(Value::as_array)
7046 .ok_or_else(|| SourceError::Malformed {
7047 message: "GitHub issue projectItems.nodes is not an array".into(),
7048 })?;
7049 if let Some(held) = self.board_entry(nodes) {
7050 return Ok(Some(held.clone()));
7051 }
7052 let info = connection
7053 .get("pageInfo")
7054 .ok_or_else(|| SourceError::Malformed {
7055 message: "GitHub issue projectItems has no pageInfo".into(),
7056 })?;
7057 let next = required_bool(info, "hasNextPage")?
7058 .then(|| required_str(info, "endCursor"))
7059 .transpose()?;
7060 match next {
7061 Some(next) => {
7062 validate_cursor_progress(Some(&after), next)?;
7063 after = next.to_owned();
7064 }
7065 None => return Ok(None),
7066 }
7067 }
7068 }
7069
7070 /// One page of a board-scoped issue search, and where the next page resumes.
7071 async fn search_page(
7072 &self,
7073 search: &str,
7074 first: u32,
7075 after: Option<&str>,
7076 ) -> Result<(Vec<Resolved>, Option<String>), SourceError> {
7077 let data = self
7078 .graphql(
7079 graphql::SEARCH_ISSUES,
7080 json!({"search":search,"type":"ISSUE","first":first.min(MAX_PAGE_SIZE),
7081 "after":after,"nestedFirst":NESTED_PAGE_SIZE,
7082 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7083 )
7084 .await?;
7085 let connection = data.get("search").ok_or_else(|| SourceError::Malformed {
7086 message: "GitHub search response has no search connection".into(),
7087 })?;
7088 let mut found = Vec::new();
7089 for node in connection
7090 .get("nodes")
7091 .and_then(Value::as_array)
7092 .ok_or_else(|| SourceError::Malformed {
7093 message: "GitHub search nodes is not an array".into(),
7094 })?
7095 {
7096 if let Some(resolved) = self.resolve_issue(node).await? {
7097 found.push(resolved);
7098 }
7099 }
7100 let info = connection
7101 .get("pageInfo")
7102 .ok_or_else(|| SourceError::Malformed {
7103 message: "GitHub search connection has no pageInfo".into(),
7104 })?;
7105 let next = required_bool(info, "hasNextPage")?
7106 .then(|| required_str(info, "endCursor"))
7107 .transpose()?
7108 .map(str::to_owned);
7109 if let Some(next) = &next {
7110 validate_cursor_progress(after, next)?;
7111 }
7112 Ok((found, next))
7113 }
7114
7115 /// Every issue this board holds, completed with what this run wrote.
7116 ///
7117 /// The completion is not an optimisation and it is not a cache: GitHub's issue search
7118 /// is an index and is eventually consistent, so an issue this run created seconds ago
7119 /// can be absent from it, and a project listed straight after being written would
7120 /// otherwise be missing from its own board. What is added back is only what this
7121 /// process itself wrote, out of [`Self::created`], which lives and dies with the
7122 /// process.
7123 async fn board_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7124 let found = self.searched_issues().await?;
7125 self.completed_with_written(found, |_| true)
7126 }
7127
7128 /// Every issue this board's own search reports, walked to exhaustion, read once per
7129 /// source.
7130 ///
7131 /// The uncompleted half of [`Self::board_issues`], separated because [`Self::board`]
7132 /// needs it too and the two would otherwise walk the same search twice in one command.
7133 /// See [`Self::search_cache`] for why holding it is the same bargain holding the board
7134 /// is.
7135 async fn searched_issues(&self) -> Result<Vec<Resolved>, SourceError> {
7136 let cached = self.search_cache()?.clone();
7137 if let Some(held) = cached {
7138 return Ok(held);
7139 }
7140 let mut after: Option<String> = None;
7141 let mut found = Vec::new();
7142 let search = self.board_search(None);
7143 loop {
7144 let (page, next) = self
7145 .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7146 .await?;
7147 found.extend(page);
7148 match next {
7149 Some(next) => after = Some(next),
7150 None => break,
7151 }
7152 }
7153 *self.search_cache()? = Some(found.clone());
7154 Ok(found)
7155 }
7156
7157 /// Every issue this board's own search reports with `also` beside its scope, walked to
7158 /// exhaustion — held for no later read, which may not be narrowed alike.
7159 async fn searched_narrowly(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
7160 let mut after: Option<String> = None;
7161 let mut found = Vec::new();
7162 let search = self.board_search(Some(also));
7163 loop {
7164 let (page, next) = self
7165 .search_page(&search, MAX_PAGE_SIZE, after.as_deref())
7166 .await?;
7167 found.extend(page);
7168 match next {
7169 Some(next) => after = Some(next),
7170 None => return Ok(found),
7171 }
7172 }
7173 }
7174
7175 /// This process's own view of the board's issues, or the refusal a poisoned lock is.
7176 fn search_cache(
7177 &self,
7178 ) -> Result<std::sync::MutexGuard<'_, Option<Vec<Resolved>>>, SourceError> {
7179 self.search_cache
7180 .lock()
7181 .map_err(|_| SourceError::Unavailable {
7182 message: "this source's view of the board's issues was left inconsistent by an \
7183 earlier failure; next: run the command again"
7184 .into(),
7185 })
7186 }
7187
7188 /// `found`, with everything this run wrote that `keep` accepts and the read did not
7189 /// report.
7190 ///
7191 /// See [`Self::created`] and [`Self::board_issues`] for why a read has to be completed
7192 /// at all: the search index is behind, and a node read of an item filed moments ago can
7193 /// be too.
7194 fn completed_with_written(
7195 &self,
7196 mut found: Vec<Resolved>,
7197 keep: impl Fn(&Resolved) -> bool,
7198 ) -> Result<Vec<Resolved>, SourceError> {
7199 for own in self.created()?.iter().filter(|own| keep(own)) {
7200 if !found.iter().any(|item| item.id == own.id) {
7201 found.push(own.clone());
7202 }
7203 }
7204 Ok(found)
7205 }
7206
7207 /// What resolving one node id reached.
7208 ///
7209 /// Three answers rather than an `Option`, because a board *draft* is none of the other
7210 /// two: it is not an issue, so the issue fragment reads nothing of it, and a read of one
7211 /// is completed by a read of the draft itself rather than reported as nothing.
7212 async fn reach(&self, id: &NativeId) -> Result<Reached, SourceError> {
7213 let asked = self
7214 .graphql(
7215 graphql::ISSUE,
7216 json!({"id":id.0,"first":MAX_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
7217 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7218 )
7219 .await;
7220 let data = match asked {
7221 Ok(data) => data,
7222 // A string that is not a node id at all is not a failure to report: it is an id
7223 // this board does not hold, which is what every read of one already answers.
7224 Err(error) if unresolvable_node(&error) => return Ok(Reached::Nothing),
7225 Err(error) => return Err(error),
7226 };
7227 let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7228 return Ok(Reached::Nothing);
7229 };
7230 if optional_str(node, "__typename")? == Some("DraftIssue") {
7231 return Ok(Reached::Draft);
7232 }
7233 Ok(match self.resolve_issue(node).await? {
7234 Some(item) => Reached::Held(Box::new(item)),
7235 None => Reached::Nothing,
7236 })
7237 }
7238
7239 /// One item of this board by its own id, whatever kind it is.
7240 ///
7241 /// Resolved from the identifier alone: no search, board-wide or otherwise. What this
7242 /// run wrote is read first, because a node read of an item created moments ago can
7243 /// still be behind the board field values written onto it — see [`Self::created`].
7244 async fn item_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7245 if let Some(own) = self.created()?.iter().find(|own| own.id == *id) {
7246 return Ok(Some(own.clone()));
7247 }
7248 if let Some(held) = self.read_ahead()?.remove(id) {
7249 return Ok(held);
7250 }
7251 match self.reach(id).await? {
7252 Reached::Held(item) => Ok(Some(*item)),
7253 Reached::Nothing => Ok(None),
7254 Reached::Draft => self.draft_by_id(id).await,
7255 }
7256 }
7257
7258 /// [`Self::item_by_id`] for a document: one [`graphql::DOCUMENT_IN_PROJECT`] read, which
7259 /// answers the project it is filed under and that project's members beside it.
7260 ///
7261 /// Each is held for this command as a read of it would have been: the project for the
7262 /// next read of it by its id, and — when its page of members is the whole of them — the
7263 /// members for the next listing of that project. So a write held to who may read the
7264 /// document, which reads all three, is answered by this one request.
7265 async fn document_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7266 if self.created()?.iter().any(|own| own.id == *id) || self.read_ahead()?.contains_key(id) {
7267 return self.item_by_id(id).await;
7268 }
7269 let asked = self
7270 .graphql(
7271 graphql::DOCUMENT_IN_PROJECT,
7272 json!({"id":id.0,"first":MAX_PAGE_SIZE,"memberFirst":MEMBER_PAGE_SIZE,
7273 "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
7274 "duplicates":true}),
7275 )
7276 .await;
7277 let data = match asked {
7278 Ok(data) => data,
7279 Err(error) if unresolvable_node(&error) => return Ok(None),
7280 Err(error) => return Err(error),
7281 };
7282 let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
7283 return Ok(None);
7284 };
7285 if optional_str(node, "__typename")? == Some("DraftIssue") {
7286 return self.draft_by_id(id).await;
7287 }
7288 let Some(item) = self.resolve_issue(node).await? else {
7289 return Ok(None);
7290 };
7291 // An answer for another issue than the one asked about says nothing of that one.
7292 if item.id != *id {
7293 return Err(SourceError::Malformed {
7294 message: format!(
7295 "GitHub answered issue {} when asked for document {}",
7296 item.id.0, id.0
7297 ),
7298 });
7299 }
7300 if let Some(project) = node.get("project").filter(|value| !value.is_null())
7301 && let Some(parent) = self
7302 .resolve_issue(project)
7303 .await?
7304 .filter(|parent| Some(&parent.id) == item.parent.as_ref())
7305 {
7306 let members = project.get("subIssues").filter(|value| !value.is_null());
7307 let whole = members
7308 .and_then(|members| members.pointer("/pageInfo/hasNextPage"))
7309 .and_then(Value::as_bool)
7310 == Some(false);
7311 if whole {
7312 let nodes = members
7313 .and_then(|members| members.get("nodes"))
7314 .and_then(Value::as_array)
7315 .ok_or_else(|| SourceError::Malformed {
7316 message: "GitHub subIssues.nodes is not an array".into(),
7317 })?;
7318 let mut children = Vec::new();
7319 for member in nodes {
7320 if let Some(resolved) = self.resolve_issue(member).await? {
7321 children.push(resolved);
7322 }
7323 }
7324 // Held as the project's members only when every one resolved and says it is
7325 // filed under it: a page with any other answers nothing of all the members.
7326 if children.len() == nodes.len()
7327 && children
7328 .iter()
7329 .all(|child| child.parent.as_ref() == Some(&parent.id))
7330 {
7331 self.children_cache()?
7332 .insert(parent.id.clone(), (parent.id.clone(), children));
7333 }
7334 }
7335 self.read_ahead()?.insert(parent.id.clone(), Some(parent));
7336 }
7337 Ok(Some(item))
7338 }
7339
7340 /// Several items of this board, each by its own id, in order — what [`Self::item_by_id`]
7341 /// answers for each, read [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] rather
7342 /// than one request per id.
7343 ///
7344 /// What this run wrote answers first, as it does there, and only the rest is read. One id
7345 /// left to read is read by [`Self::item_by_id`] itself, which costs what a batch does. A
7346 /// batch GitHub refuses because one of its ids resolves to no node at all is read again one
7347 /// id at a time, so that id is answered as not held and the others as themselves; a draft
7348 /// is completed by a read of the draft, exactly as there.
7349 async fn items_by_ids(&self, ids: &[NativeId]) -> Result<Vec<Option<Resolved>>, SourceError> {
7350 let mut found: Vec<Option<Option<Resolved>>> = {
7351 let created = self.created()?;
7352 ids.iter()
7353 .map(|id| {
7354 created
7355 .iter()
7356 .find(|own| own.id == *id)
7357 .map(|own| Some(own.clone()))
7358 })
7359 .collect()
7360 };
7361 let unread: Vec<NativeId> = ids
7362 .iter()
7363 .zip(&found)
7364 .filter(|(_, found)| found.is_none())
7365 .map(|(id, _)| id.clone())
7366 .collect();
7367 let mut read = Vec::with_capacity(unread.len());
7368 if let [one] = unread.as_slice() {
7369 read.push(self.item_by_id(one).await?);
7370 } else {
7371 for batch in unread.chunks(DETAIL_BATCH) {
7372 let data = match self
7373 .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, None))
7374 .await
7375 {
7376 Ok(data) => data,
7377 Err(error) if unresolvable_node(&error) => {
7378 for id in batch {
7379 read.push(self.item_by_id(id).await?);
7380 }
7381 continue;
7382 }
7383 Err(error) => return Err(error),
7384 };
7385 for (slot, id) in batch.iter().enumerate() {
7386 let node =
7387 data.get(format!("i{slot}"))
7388 .ok_or_else(|| SourceError::Malformed {
7389 message: format!(
7390 "GitHub answered a batch read with no item for {}",
7391 id.0
7392 ),
7393 })?;
7394 read.push(if node.is_null() {
7395 None
7396 } else if optional_str(node, "__typename")? == Some("DraftIssue") {
7397 self.draft_by_id(id).await?
7398 } else {
7399 if optional_str(node, "__typename")? == Some("Issue")
7400 && required_str(node, "id")? != id.0
7401 {
7402 return Err(SourceError::Malformed {
7403 message: format!(
7404 "GitHub answered the read of {} with issue {}",
7405 id.0,
7406 required_str(node, "id")?
7407 ),
7408 });
7409 }
7410 self.resolve_issue(node).await?
7411 });
7412 }
7413 }
7414 }
7415 let mut read = read.into_iter();
7416 Ok(found
7417 .iter_mut()
7418 .map(|slot| slot.take().unwrap_or_else(|| read.next().flatten()))
7419 .collect())
7420 }
7421
7422 fn read_ahead(
7423 &self,
7424 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Option<Resolved>>>, SourceError> {
7425 self.read_ahead
7426 .lock()
7427 .map_err(|_| SourceError::Unavailable {
7428 message:
7429 "items read ahead for a copy were left inconsistent; run the command again"
7430 .into(),
7431 })
7432 }
7433
7434 fn resolved_cache(
7435 &self,
7436 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7437 self.resolved_cache
7438 .lock()
7439 .map_err(|_| SourceError::Unavailable {
7440 message: "resolved item records were left inconsistent; run the command again"
7441 .into(),
7442 })
7443 }
7444
7445 /// Reuse a record this invocation already resolved. The mutation sender invalidates
7446 /// it before writing, so a partial failure cannot leave a pre-write binding behind.
7447 async fn bound_item(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7448 let cached = self.resolved_cache()?.get(id).cloned();
7449 if let Some(item) = cached {
7450 return Ok(Some(item));
7451 }
7452 self.item_by_id(id).await
7453 }
7454
7455 /// Take out the item an issue read by reference reached for `id`, when one is held: the
7456 /// status write it was read for is the one caller, so no other read or write is ever
7457 /// answered from a read that selected only what that write needs.
7458 fn take_held(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7459 Ok(self
7460 .held_cache
7461 .lock()
7462 .map_err(|_| SourceError::Unavailable {
7463 message: "items read by issue reference were left inconsistent; run the \
7464 command again"
7465 .into(),
7466 })?
7467 .remove(id))
7468 }
7469
7470 /// One board draft by its own id, with the board item it sits in — or `None` when no
7471 /// item of this board is that draft's.
7472 ///
7473 /// The same decision [`Self::resolve_issue`] makes for an issue, over the draft's own
7474 /// `projectV2Items`: an entry naming this board is what makes it this board's. GitHub
7475 /// links a draft to one board item, so the page this read carries is the whole of that
7476 /// connection, and a page that reports more than it holds is refused rather than read
7477 /// as an answer about memberships nobody read.
7478 async fn draft_by_id(&self, id: &NativeId) -> Result<Option<Resolved>, SourceError> {
7479 let data = self
7480 .graphql(
7481 graphql::DRAFT,
7482 json!({"id":id.0,"nestedFirst":NESTED_PAGE_SIZE,
7483 "boardItems":BOARD_ITEMS_PAGE_SIZE}),
7484 )
7485 .await?;
7486 // Gone between the two reads is an answer — the draft is no longer there. Anything
7487 // else than the draft [`Self::reach`] was just told this id is, is not one.
7488 let Some(draft) = data.get("node").filter(|node| !node.is_null()) else {
7489 return Ok(None);
7490 };
7491 if optional_str(draft, "__typename")? != Some("DraftIssue") {
7492 return Err(SourceError::Malformed {
7493 message: format!(
7494 "GitHub answered {} as a draft and then as something else",
7495 id.0
7496 ),
7497 });
7498 }
7499 if required_str(draft, "id")? != id.0 {
7500 return Err(SourceError::Malformed {
7501 message: format!("GitHub answered a different draft for {}", id.0),
7502 });
7503 }
7504 let memberships = draft
7505 .get("projectV2Items")
7506 .ok_or_else(|| SourceError::Malformed {
7507 message: format!("GitHub draft {} is missing projectV2Items", id.0),
7508 })?;
7509 let nodes = memberships
7510 .get("nodes")
7511 .and_then(Value::as_array)
7512 .ok_or_else(|| SourceError::Malformed {
7513 message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
7514 })?;
7515 let info = memberships
7516 .get("pageInfo")
7517 .ok_or_else(|| SourceError::Malformed {
7518 message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
7519 })?;
7520 // Read whether or not this board's entry is on the page: a page claiming more than
7521 // the one item GitHub links a draft to is a malformed answer either way.
7522 if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
7523 return Err(SourceError::Malformed {
7524 message: format!(
7525 "GitHub draft {} reports more board items than the one GitHub links a draft \
7526 to",
7527 id.0
7528 ),
7529 });
7530 }
7531 if let Some(node) = nodes.first()
7532 && node
7533 .pointer("/project/number")
7534 .and_then(Value::as_u64)
7535 .is_none()
7536 {
7537 return Err(SourceError::Malformed {
7538 message: format!(
7539 "GitHub draft {} board item has no numeric project number",
7540 id.0
7541 ),
7542 });
7543 }
7544 let Some(held) = self.board_entry(nodes) else {
7545 return Ok(None);
7546 };
7547 if required_str(
7548 held.get("project").ok_or_else(|| SourceError::Malformed {
7549 message: format!("GitHub draft {} board item has no project", id.0),
7550 })?,
7551 "id",
7552 )? != self.board_fields().await?.id.as_str()
7553 {
7554 return Ok(None);
7555 }
7556 let item = json!({
7557 "id": required_str(held, "id")?,
7558 "project": held.get("project"),
7559 "fieldValues": held.get("fieldValues"),
7560 "content": draft,
7561 });
7562 self.resolve(&item)
7563 }
7564
7565 /// The board's own id and field definitions, for a write whose item does not carry
7566 /// them — never its items.
7567 ///
7568 /// A board this command has already listed supplies them, since it read them beside its
7569 /// items; otherwise they come from [`graphql::BOARD_FIELDS`], once per command. Neither
7570 /// is consulted about which items the board holds: see the module documentation for
7571 /// why a question about one known item is answered by reading that item.
7572 async fn board_fields(&self) -> Result<BoardFields, SourceError> {
7573 if let Some(board) = self.board_cache()?.as_ref() {
7574 return Ok(BoardFields {
7575 id: BoardId::parse(&board.id)?,
7576 fields: board.fields.clone(),
7577 });
7578 }
7579 if let Some(held) = self.fields_cache()?.clone() {
7580 return Ok(held);
7581 }
7582 let data = self
7583 .graphql(
7584 graphql::BOARD_FIELDS,
7585 json!({"owner":self.owner,"number":self.project_number,
7586 "nestedFirst":NESTED_PAGE_SIZE}),
7587 )
7588 .await?;
7589 self.fields_read(&data)
7590 }
7591
7592 /// The board's id and fields out of an answer carrying the `boardFields` root, held for
7593 /// the rest of this command.
7594 fn fields_read(&self, data: &Value) -> Result<BoardFields, SourceError> {
7595 let board = data
7596 .pointer("/boardFields/projectV2")
7597 .filter(|value| !value.is_null())
7598 .ok_or_else(|| SourceError::Refused {
7599 message: format!(
7600 "GitHub project {}/{} was not found or is not visible to the token",
7601 self.owner, self.project_number
7602 ),
7603 })?;
7604 let read = BoardFields {
7605 id: BoardId::parse(required_str(board, "id")?)?,
7606 fields: board.get("fields").cloned().unwrap_or(Value::Null),
7607 };
7608 *self.fields_cache()? = Some(read.clone());
7609 Ok(read)
7610 }
7611
7612 /// Read what creating an issue in `repository` needs and this command has not read yet —
7613 /// the board's fields and the repository's node id — in one request when it needs both.
7614 ///
7615 /// When either is already known this sends nothing, and the other is read by its own
7616 /// document where it is asked for, so no create reads anything twice.
7617 async fn creation_context(
7618 &self,
7619 repository: &RepositoryTarget,
7620 incoming: &Incoming<'_>,
7621 ) -> Result<(), SourceError> {
7622 let fields_known = self.board_cache()?.is_some() || self.fields_cache()?.is_some();
7623 if fields_known || self.repository_cache()?.contains_key(repository) {
7624 return Ok(());
7625 }
7626 // A placement an earlier process kept is taken only while the project issue this create
7627 // has just read shows its setup-context token unchanged; see `projection`.
7628 if self.placed_by_kept(repository, incoming.parent) {
7629 return Ok(());
7630 }
7631 let data = self
7632 .graphql(
7633 graphql::CREATION_CONTEXT,
7634 json!({"owner":self.owner,"number":self.project_number,
7635 "nestedFirst":NESTED_PAGE_SIZE,"repositoryOwner":repository.owner,
7636 "repositoryName":repository.name}),
7637 )
7638 .await?;
7639 self.fields_read(&data)?;
7640 self.repository_read(&data, repository, incoming)?;
7641 Ok(())
7642 }
7643
7644 /// This process's own view of the board's fields, or the refusal a poisoned lock is.
7645 fn fields_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<BoardFields>>, SourceError> {
7646 self.fields_cache
7647 .lock()
7648 .map_err(|_| SourceError::Unavailable {
7649 message: "this source's view of the board's fields was left inconsistent by an \
7650 earlier failure; next: run the command again"
7651 .into(),
7652 })
7653 }
7654
7655 /// What a write to `item` needs of the board, read off that item when it says enough and
7656 /// off [`Self::board_fields`] when it does not.
7657 ///
7658 /// A node read of an item names its board and carries the definition of every field it
7659 /// holds a value of — so an item naming its board, holding a value of the origin field
7660 /// when the write carries an origin, and, when the write carries a status, holding a
7661 /// `Status` value, needs no read of the board at all. **Nothing the item does not say is
7662 /// guessed:** a field it holds no value of may still be on the board, and a view reading it
7663 /// as absent would refuse a write the board can take or skip a field write the board
7664 /// needs, so such an item — and a create, which has no item yet — takes the board's fields
7665 /// from their own read instead. A write carrying no origin to an item holding none — every
7666 /// write out of a source declared private — writes no origin whatever the board defines,
7667 /// so it needs no definition of that field.
7668 async fn fields_for(
7669 &self,
7670 item: Option<&Resolved>,
7671 writes_origin: bool,
7672 writes_status: bool,
7673 selects_priority: bool,
7674 ) -> Result<BoardFields, SourceError> {
7675 if let Some(board) = item.and_then(Resolved::carried_board) {
7676 return Ok(board);
7677 }
7678 if let Some(item) = item
7679 && let Some(board_id) = item.named_board()
7680 && (!writes_origin || item.defines(ORIGIN_FIELD))
7681 && (!writes_status || item.defines("Status"))
7682 && (!selects_priority || item.defines(PRIORITY_FIELD))
7683 && self
7684 .metadata_fields
7685 .iter()
7686 .all(|projection| item.defines(&projection.field))
7687 {
7688 return Ok(BoardFields {
7689 id: board_id,
7690 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
7691 });
7692 }
7693 self.board_fields().await
7694 }
7695
7696 /// Everything filed under one issue of this board, walked to exhaustion — or `None`
7697 /// when that id names nothing here with a sub-issue relationship to walk.
7698 ///
7699 /// `None` and an empty answer are different: `None` is *this is not an issue of this
7700 /// GitHub*, which is what sends a project selector on to be read as a name, and an
7701 /// empty vector is a project that holds nothing.
7702 async fn sub_issues(&self, id: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
7703 let mut after: Option<String> = None;
7704 let mut children = Vec::new();
7705 // The project issue as the first page carried it, held once the walk has ended.
7706 let mut parent: Option<Resolved> = None;
7707 loop {
7708 let asked = self
7709 .graphql(
7710 graphql::SUB_ISSUES,
7711 json!({"id":id.0,"memberFirst":MEMBER_PAGE_SIZE,"after":after,
7712 "nestedFirst":NESTED_PAGE_SIZE,
7713 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true}),
7714 )
7715 .await;
7716 let data = match asked {
7717 Ok(data) => data,
7718 // A string that is not a node id at all is not a failure to report: it is
7719 // the ordinary answer to a selector naming a project by its name.
7720 Err(error) if unresolvable_node(&error) => return Ok(None),
7721 Err(error) => return Err(error),
7722 };
7723 let Some(connection) = data
7724 .pointer("/node/subIssues")
7725 .filter(|value| !value.is_null())
7726 else {
7727 // No such node, or one with no sub-issue relationship — a board draft is
7728 // the one this board can really hold.
7729 return Ok(None);
7730 };
7731 if after.is_none()
7732 && let Some(node) = data.get("node").filter(|node| node.get("id").is_some())
7733 {
7734 parent = self
7735 .resolve_issue(node)
7736 .await?
7737 .filter(|resolved| resolved.id == *id);
7738 }
7739 for node in connection
7740 .get("nodes")
7741 .and_then(Value::as_array)
7742 .ok_or_else(|| SourceError::Malformed {
7743 message: "GitHub subIssues.nodes is not an array".into(),
7744 })?
7745 {
7746 if let Some(resolved) = self.resolve_issue(node).await? {
7747 children.push(resolved);
7748 }
7749 }
7750 let info = connection
7751 .get("pageInfo")
7752 .ok_or_else(|| SourceError::Malformed {
7753 message: "GitHub subIssues connection has no pageInfo".into(),
7754 })?;
7755 let next = required_bool(info, "hasNextPage")?
7756 .then(|| required_str(info, "endCursor"))
7757 .transpose()?;
7758 match next {
7759 Some(next) => {
7760 validate_cursor_progress(after.as_deref(), next)?;
7761 after = Some(next.to_owned());
7762 }
7763 None => {
7764 // Held only once the walk has ended, so one failing part way holds
7765 // nothing and every read it would have answered is made.
7766 // The project issue the first page carried answers the next read of the
7767 // project by its id in this command, as a read of it made now would: what
7768 // classifying a project for a write reads straight after its members.
7769 if let Some(parent) = &parent {
7770 self.read_ahead()?
7771 .entry(parent.id.clone())
7772 .or_insert_with(|| Some(parent.clone()));
7773 }
7774 let mut carried = self.carried()?;
7775 for item in parent.into_iter().chain(children.iter().cloned()) {
7776 carried.insert(item.id.clone(), item);
7777 }
7778 return Ok(Some(children));
7779 }
7780 }
7781 }
7782 }
7783
7784 fn carried(
7785 &self,
7786 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Resolved>>, SourceError> {
7787 self.carried.lock().map_err(|_| SourceError::Unavailable {
7788 message: "items a project's listing carried were left inconsistent; run the \
7789 command again"
7790 .into(),
7791 })
7792 }
7793
7794 /// Which issue of this board a project *name* is, or `None` when none is.
7795 ///
7796 /// One bounded query which filters on that name at the server, rather than a walk of
7797 /// every issue the board holds. The name is compared again here: the qualifier narrows
7798 /// what GitHub sends, and this source decides what it names.
7799 async fn project_by_name(&self, name: &str) -> Result<Option<NativeId>, SourceError> {
7800 let search = self.board_search(Some(&title_qualifier(name)));
7801 let mut after = None;
7802 loop {
7803 let (candidates, next) = self
7804 .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
7805 .await?;
7806 if let Some(item) = candidates.into_iter().find(|item| {
7807 item.kind == BoardKind::Work(ItemKind::Project)
7808 && item.title.eq_ignore_ascii_case(name)
7809 }) {
7810 return Ok(Some(item.id));
7811 }
7812 match next {
7813 Some(next) => after = Some(next),
7814 None => return Ok(None),
7815 }
7816 }
7817 }
7818
7819 /// Everything filed under one project of this board: the sub-issues of the issue that
7820 /// project is.
7821 ///
7822 /// Tasks *and* documents, because a document filed under a project is a sub-issue of it
7823 /// too — the caller keeps the kind it asked for. Nothing about this grows as the board
7824 /// gains projects, or as another project gains tasks.
7825 ///
7826 /// A qualified id names the issue and is asked for its sub-issues directly: one
7827 /// request, no search of any kind. Only a selector GitHub cannot resolve that way is
7828 /// read as a project *name*, which costs the one bounded search
7829 /// [`Self::project_by_name`] makes.
7830 ///
7831 /// What GitHub answered is held for the rest of the command — see [`Self::children_cache`]
7832 /// — and each answer is still cut to the items whose parent is this project, so one this
7833 /// process has since filed elsewhere is not reported here, and completed with what this
7834 /// process filed under it.
7835 async fn project_children(&self, selector: &NativeId) -> Result<Vec<Resolved>, SourceError> {
7836 let held = self.children_cache()?.get(selector).cloned();
7837 let (project, children) = match held {
7838 Some(held) => held,
7839 None => {
7840 let answered = match self.sub_issues(selector).await? {
7841 Some(children) => (selector.clone(), children),
7842 None => match self.project_by_name(&selector.0).await? {
7843 Some(project) => {
7844 let children = self.sub_issues(&project).await?.unwrap_or_default();
7845 (project, children)
7846 }
7847 None => return Ok(Vec::new()),
7848 },
7849 };
7850 self.children_cache()?
7851 .insert(selector.clone(), answered.clone());
7852 answered
7853 }
7854 };
7855 let mut children: Vec<Resolved> = children
7856 .into_iter()
7857 .filter(|child| child.parent.as_ref() == Some(&project))
7858 .collect();
7859 for own in self.updated()?.iter() {
7860 if own.parent.as_ref() == Some(&project) && !children.iter().any(|c| c.id == own.id) {
7861 children.push(own.clone());
7862 }
7863 }
7864 self.completed_with_written(children, |own| own.parent.as_ref() == Some(&project))
7865 }
7866
7867 /// Every issue of this board GitHub's issue search reports updated at or after `since`,
7868 /// completed with what this run wrote — the candidates a comment-activity read confirms.
7869 ///
7870 /// Scoped by the board and by nothing else: `project:<owner>/<number>` reaches every issue
7871 /// on the board whatever repository, and whatever owner, it lives in, so no repository or
7872 /// owner qualifier is added and none is needed. What makes the `updated:` qualifier
7873 /// sufficient is a fact about GitHub rather than about this source: a comment written on an
7874 /// issue **and a comment edited on it** both move that issue's `updatedAt`. The credentialed
7875 /// journey `an_edited_comment_moves_its_issue_and_is_selected_since` in `tests/journey`
7876 /// re-takes that fact on every run of the lane, so a change on GitHub's side fails there
7877 /// rather than silently narrowing a caller's answer.
7878 ///
7879 /// The instant is written to the second, rounded down, which can only widen what the
7880 /// search returns; confirmation against each candidate's own comments is what makes the
7881 /// answer exact. The search is an index that lags a write by a second or two — the module
7882 /// documentation records it — so a caller that asks again from its last instant should
7883 /// overlap the two by more than that.
7884 async fn updated_since(&self, since: DateTime<Utc>) -> Result<Vec<Resolved>, SourceError> {
7885 let found = self.searched(&updated_qualifier(since)).await?;
7886 self.completed_with_written(found, |_| true)
7887 }
7888
7889 /// Every issue of this board GitHub's issue search reports for the board-scoped search
7890 /// narrowed by `also`, in pages of [`SEARCH_PAGE_SIZE`].
7891 ///
7892 /// Uncompleted: what this process wrote is added by the caller, which knows whether its
7893 /// own record is the fresher of the two.
7894 async fn searched(&self, also: &str) -> Result<Vec<Resolved>, SourceError> {
7895 let search = self.board_search(Some(also));
7896 let mut after: Option<String> = None;
7897 let mut found = Vec::new();
7898 loop {
7899 let (page, next) = self
7900 .search_page(&search, SEARCH_PAGE_SIZE, after.as_deref())
7901 .await?;
7902 found.extend(page);
7903 match next {
7904 Some(next) => after = Some(next),
7905 None => return Ok(found),
7906 }
7907 }
7908 }
7909
7910 /// A bounded task answer; the versioned cursor carries the connection position, how
7911 /// many rows of the page starting there were already handed out, and the own-write ids
7912 /// already observed, including across a new source instance.
7913 ///
7914 /// Every page is sent at [`SEARCH_PAGE_SIZE`] whatever the caller's limit, and a limit is
7915 /// sliced from the pages it needs; why is the module documentation's paging contract.
7916 async fn search_tasks(
7917 &self,
7918 query: &TaskQuery,
7919 page: &PageRequest,
7920 also: &str,
7921 ) -> Result<Page<Task>, SourceError> {
7922 let mut position = match &page.cursor {
7923 None => SearchPosition::default(),
7924 Some(cursor) => serde_json::from_str::<SearchPosition>(&cursor.0)
7925 .ok()
7926 .filter(|position| {
7927 position.version == SEARCH_CURSOR_VERSION
7928 && position.connection.valid_resume(position.offset)
7929 })
7930 .ok_or_else(|| SourceError::Config {
7931 message: "page cursor is invalid".into(),
7932 })?,
7933 };
7934 let search = self.board_search(Some(also));
7935 let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
7936 let own = self.with_own_writes(Vec::new())?;
7937 // An issue this process commented on is a candidate of a comment-activity read
7938 // whether or not the search has caught up with the comment; see `Self::commented`.
7939 let commented = match query.commented_since {
7940 Some(_) => self.commented()?.clone(),
7941 None => Vec::new(),
7942 };
7943 for id in own.iter().map(|item| &item.id).chain(&commented) {
7944 if !position.own.contains(id) {
7945 position.own.push(id.clone());
7946 }
7947 }
7948 let mut tasks = Vec::new();
7949 while !position.connection.exhausted() && tasks.len() < limit {
7950 let first = SEARCH_PAGE_SIZE;
7951 // Page size is part of the key: a short cached answer cannot answer a wider ask.
7952 let key =
7953 serde_json::to_string(&("page", &search, &position.connection.after(), first))
7954 .expect("search page key is serializable");
7955 let cached = if query.commented_since.is_none() {
7956 self.narrowed_cache()?.get(&key).cloned()
7957 } else {
7958 None
7959 };
7960 let (found, next) = match cached {
7961 Some(found) => {
7962 let next = self
7963 .search_next
7964 .lock()
7965 .map_err(|_| SourceError::Unavailable {
7966 message:
7967 "search pagination was left inconsistent; run the command again"
7968 .into(),
7969 })?
7970 .get(&key)
7971 .cloned()
7972 .flatten();
7973 (found, next)
7974 }
7975 None => {
7976 let (found, next) = self
7977 .search_page(&search, first, position.connection.after())
7978 .await?;
7979 if query.commented_since.is_none() {
7980 self.search_next
7981 .lock()
7982 .map_err(|_| SourceError::Unavailable {
7983 message:
7984 "search pagination was left inconsistent; run the command again"
7985 .into(),
7986 })?
7987 .insert(key.clone(), next.clone());
7988 self.narrowed_cache()?.insert(key, found.clone());
7989 }
7990 (found, next)
7991 }
7992 };
7993 let rows = found.len();
7994 // Every candidate of the page this read confirms by its comments is read together.
7995 let candidates =
7996 self.comment_candidates(found.iter().skip(position.offset), query, &query.project)?;
7997 self.hold_comment_pages(&candidates).await?;
7998 for mut item in found.into_iter().skip(position.offset) {
7999 if tasks.len() == limit {
8000 break;
8001 }
8002 position.offset += 1;
8003 if position.own.contains(&item.id) {
8004 if position.seen.contains(&item.id) {
8005 continue;
8006 }
8007 position.seen.push(item.id.clone());
8008 // The search's own copy of an issue this process only commented on is as
8009 // good as a node read of it, since its comments are read either way.
8010 let only_commented = commented.contains(&item.id)
8011 && !own.iter().any(|written| written.id == item.id);
8012 if !only_commented {
8013 let updated_at = item.updated_at;
8014 let Some(written) = self.search_written(&own, &item.id).await? else {
8015 continue;
8016 };
8017 item = written;
8018 item.updated_at = item.updated_at.max(updated_at);
8019 self.resolved_cache()?.insert(item.id.clone(), item.clone());
8020 }
8021 }
8022 if item.kind == BoardKind::Work(ItemKind::Task) {
8023 let task = item.task()?;
8024 if task_matches(&task, query, &query.project)
8025 && self.commented_since(&item, query.commented_since).await?
8026 {
8027 tasks.push(task);
8028 }
8029 }
8030 }
8031 if position.offset < rows {
8032 continue;
8033 }
8034 position.offset = 0;
8035 position.connection = match next {
8036 Some(after) => SearchConnection::Continuing {
8037 after: Cursor(after),
8038 },
8039 None => SearchConnection::Exhausted {},
8040 };
8041 }
8042 if position.connection.exhausted() {
8043 for id in position.own.clone() {
8044 if position.seen.contains(&id) {
8045 continue;
8046 }
8047 if tasks.len() == limit {
8048 break;
8049 }
8050 position.seen.push(id.clone());
8051 let Some(item) = self.search_written(&own, &id).await? else {
8052 continue;
8053 };
8054 if item.kind == BoardKind::Work(ItemKind::Task) {
8055 let task = item.task()?;
8056 if task_matches(&task, query, &query.project)
8057 && self.commented_since(&item, query.commented_since).await?
8058 {
8059 tasks.push(task);
8060 }
8061 }
8062 }
8063 }
8064 let more = !position.connection.exhausted()
8065 || position.own.iter().any(|id| !position.seen.contains(id));
8066 Ok(Page {
8067 items: tasks,
8068 next: more.then(|| {
8069 Cursor(serde_json::to_string(&position).expect("search position is serializable"))
8070 }),
8071 })
8072 }
8073
8074 /// A resumed process has the ids but no write records; resolve only a record the
8075 /// current page needs, by its uncached node read rather than the lagging search index.
8076 async fn search_written(
8077 &self,
8078 own: &[Resolved],
8079 id: &NativeId,
8080 ) -> Result<Option<Resolved>, SourceError> {
8081 match own.iter().find(|item| item.id == *id) {
8082 Some(item) => Ok(Some(item.clone())),
8083 None => self.item_by_id(id).await,
8084 }
8085 }
8086
8087 /// The candidates for a task query carrying a text, metadata or origin predicate, read
8088 /// without enumerating the board — or `None` for a query carrying none of the three, which
8089 /// keeps the reads it always had.
8090 ///
8091 /// An origin is answered by [`Self::origin_candidates`], whatever else the query carries,
8092 /// because it names at most a handful of items. Text and metadata are answered by one
8093 /// board-scoped issue search carrying every term — see [`narrowing_qualifiers`] — narrowed
8094 /// further by `updated:>=` when the query also asks for comment activity, since both
8095 /// qualifiers must hold of an issue the answer keeps. Every candidate is confirmed in
8096 /// process afterwards by the same predicates [`task_matches`] applies to every read.
8097 ///
8098 /// Completed with what this process wrote, its own record winning over the index's copy
8099 /// of the same item: see [`Self::with_own_writes`].
8100 async fn narrowed(&self, query: &TaskQuery) -> Result<Option<Vec<Resolved>>, SourceError> {
8101 self.send_pending_origins(None).await?;
8102 let asked = match (&query.origin, narrowing_qualifiers(query)) {
8103 (Some(origin), _) => Narrowing::Origin(origin.clone()),
8104 (None, Some(qualifiers)) => Narrowing::Search(match query.commented_since {
8105 Some(since) => format!("{} {qualifiers}", updated_qualifier(since)),
8106 None => qualifiers,
8107 }),
8108 (None, None) => return Ok(None),
8109 };
8110 // A question about comment activity is asked afresh every time, as it always was: it
8111 // is the one a caller polls from one source while waiting for the index, and an
8112 // answer held from the first poll would be the answer to every later one.
8113 let key = query.commented_since.is_none().then(|| asked.key());
8114 let cached = match &key {
8115 Some(key) => self.narrowed_cache()?.get(key).cloned(),
8116 None => None,
8117 };
8118 let found = match cached {
8119 Some(found) => found,
8120 None => {
8121 let found = match &asked {
8122 Narrowing::Origin(origin) => self.origin_candidates(origin).await?,
8123 Narrowing::Search(also) => self.searched(also).await?,
8124 };
8125 if let Some(key) = key {
8126 self.narrowed_cache()?.insert(key, found.clone());
8127 }
8128 found
8129 }
8130 };
8131 self.with_own_writes(found).map(Some)
8132 }
8133
8134 /// The candidates for a project or unscoped document query carrying a searchable text,
8135 /// read without enumerating the board — or `None` for a query with no text or a blank one,
8136 /// which keeps the read it always had.
8137 ///
8138 /// The text is sent as the very phrase a task query's text is — see [`text_qualifiers`] —
8139 /// in one board-scoped issue search walked to its end at [`SEARCH_PAGE_SIZE`], so what it
8140 /// costs is the issues that match and never the board. Its answer is held for the command
8141 /// under the same key [`Self::narrowed`] holds that search under, so a walk of the caller's
8142 /// pages asks GitHub once. Every candidate is confirmed afterwards by its kind and by the
8143 /// substring rule, exactly as an item of the wider read was, and is completed with what this
8144 /// process wrote: see [`Self::with_own_writes`].
8145 async fn text_searched(
8146 &self,
8147 text: Option<&TextQuery>,
8148 ) -> Result<Option<Vec<Resolved>>, SourceError> {
8149 let Some(also) = text_qualifiers(text) else {
8150 return Ok(None);
8151 };
8152 let key = Narrowing::Search(also.clone()).key();
8153 let cached = self.narrowed_cache()?.get(&key).cloned();
8154 let found = match cached {
8155 Some(found) => found,
8156 None => {
8157 let found = self.searched(&also).await?;
8158 self.narrowed_cache()?.insert(key, found.clone());
8159 found
8160 }
8161 };
8162 self.with_own_writes(found).map(Some)
8163 }
8164
8165 /// Every `kind` item of this board whose own origin is exactly `origin`: the candidates
8166 /// [`Self::narrowed`] reads for a task query carrying that origin — one
8167 /// [`graphql::ORIGIN_LOOKUP`] walk, held for the command under the same key, completed with
8168 /// what this process wrote — each confirmed against its own origin entry.
8169 ///
8170 /// What answers a project or document listing by origin, so finding every copy of one plan
8171 /// costs the items that carry its origin and never a page of the board.
8172 async fn copied_from(
8173 &self,
8174 origin: &str,
8175 kind: BoardKind,
8176 ) -> Result<Vec<Resolved>, SourceError> {
8177 let wanted = TaskQuery {
8178 origin: Some(origin.to_owned()),
8179 ..TaskQuery::default()
8180 };
8181 Ok(self
8182 .narrowed(&wanted)
8183 .await?
8184 .unwrap_or_default()
8185 .into_iter()
8186 .filter(|item| item.kind == kind && wanted.origin_matches(&item.metadata()))
8187 .collect())
8188 }
8189
8190 /// Every item of this board that may carry `origin` — a superset of those that do — found
8191 /// by [`graphql::ORIGIN_LOOKUP`] and never by enumerating the board.
8192 ///
8193 /// The union of the board's own field filter over the `onetaskgraph.origin` text field —
8194 /// which reads the field every carrier holds, whichever release wrote it — and the
8195 /// board-scoped issue search for the same id as a phrase in the body, where this source
8196 /// mirrors it. The caller adds the third read, this process's own writes. Candidates are
8197 /// returned unconfirmed; [`task_matches`] compares each one's own origin field with the
8198 /// query's, exactly.
8199 ///
8200 /// Both connections are walked to exhaustion, each from its own cursor. One that has
8201 /// already ended is sent its last cursor again, which answers an empty page, so the one
8202 /// document serves every page of either. What the two leave is stated in the module
8203 /// documentation: a carrier another process added within the last second or two, before
8204 /// either index has it.
8205 async fn origin_candidates(&self, origin: &str) -> Result<Vec<Resolved>, SourceError> {
8206 let filter = format!("{ORIGIN_FIELD}:{}", quoted(origin));
8207 let search = self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))));
8208 let mut items_after: Option<String> = None;
8209 let mut search_after: Option<String> = None;
8210 let mut found: Vec<Resolved> = Vec::new();
8211 let keep = |resolved: Resolved, found: &mut Vec<Resolved>| {
8212 if !found.iter().any(|held| held.id == resolved.id) {
8213 found.push(resolved);
8214 }
8215 };
8216 loop {
8217 let data = self
8218 .graphql(
8219 graphql::ORIGIN_LOOKUP,
8220 json!({"owner":self.owner,"number":self.project_number,"filter":filter,
8221 "search":search,"type":"ISSUE","originFirst":ORIGIN_PAGE_SIZE,
8222 "itemsAfter":items_after,"searchAfter":search_after,
8223 "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
8224 "duplicates":true}),
8225 )
8226 .await?;
8227 let items = data
8228 .pointer("/originItems/projectV2/items")
8229 .filter(|value| !value.is_null())
8230 .ok_or_else(|| SourceError::Refused {
8231 message: format!(
8232 "GitHub project {}/{} was not found or is not visible to the token",
8233 self.owner, self.project_number
8234 ),
8235 })?;
8236 for item in optional_nodes(Some(items), "project items")?
8237 .into_iter()
8238 .flatten()
8239 {
8240 // The board's own items list its drafts too, and a draft is not an issue: no
8241 // narrowed read answers with one, whatever its origin field holds.
8242 if let Some(resolved) = self.resolve(item)?
8243 && resolved.content_kind == ContentKind::Issue
8244 {
8245 keep(resolved, &mut found);
8246 }
8247 }
8248 let searched = data.get("search").ok_or_else(|| SourceError::Malformed {
8249 message: "GitHub search response has no search connection".into(),
8250 })?;
8251 for node in optional_nodes(Some(searched), "search")?
8252 .into_iter()
8253 .flatten()
8254 {
8255 if let Some(resolved) = self.resolve_issue(node).await? {
8256 keep(resolved, &mut found);
8257 }
8258 }
8259 let items_next = resumed(items, items_after.as_deref())?;
8260 let search_next = resumed(searched, search_after.as_deref())?;
8261 if !items_next.has_more() && !search_next.has_more() {
8262 return Ok(found);
8263 }
8264 items_after = items_next.cursor();
8265 search_after = search_next.cursor();
8266 }
8267 }
8268
8269 /// `found`, with every item this process created or wrote in its place, and every one of
8270 /// them the read did not report added.
8271 ///
8272 /// This process's own record wins over the read's copy of the same item, because a read
8273 /// of an item written moments ago can still be behind what was written onto it — the
8274 /// origin field included, which is the one a narrowed read is confirmed against — and a
8275 /// read that still names an item under a predicate this process's write moved it out of
8276 /// must not return it. The one thing the read knows that the record cannot is when GitHub
8277 /// last saw the item change, which is what a comment-activity read rules a candidate out
8278 /// by, so the read's `updatedAt` is kept when the record has none of its own. See
8279 /// [`Self::created`] and [`Self::updated`](GitHubProjectsSource::updated).
8280 fn with_own_writes(&self, mut found: Vec<Resolved>) -> Result<Vec<Resolved>, SourceError> {
8281 // A board draft is not an issue, so no narrowed read returns one, and this process
8282 // having written one does not make it an answer either.
8283 let own: Vec<Resolved> = self
8284 .created()?
8285 .iter()
8286 .chain(self.updated()?.iter())
8287 .filter(|own| own.content_kind == ContentKind::Issue)
8288 .cloned()
8289 .collect();
8290 for mut own in own {
8291 self.resolved_cache()?.insert(own.id.clone(), own.clone());
8292 match found.iter_mut().find(|read| read.id == own.id) {
8293 Some(read) => {
8294 own.updated_at = own.updated_at.max(read.updated_at);
8295 *read = own;
8296 }
8297 None => found.push(own),
8298 }
8299 }
8300 Ok(found)
8301 }
8302
8303 /// Whether `item` has a comment created or last edited at or after `since` — always, when
8304 /// there is no instant to hold it to.
8305 ///
8306 /// The candidate's own `updatedAt` is read first, because a comment written or edited at
8307 /// or after the instant moved it there: an issue not updated since holds no such comment,
8308 /// and its comments are never asked for — unless this process commented on it in this
8309 /// command, when the `updatedAt` held may predate that comment; see [`Self::commented`]. Otherwise its comments are walked, oldest first,
8310 /// only as far as the first that matches. A board draft is not an issue and has no
8311 /// comments, so it never matches.
8312 async fn commented_since(
8313 &self,
8314 item: &Resolved,
8315 since: Option<DateTime<Utc>>,
8316 ) -> Result<bool, SourceError> {
8317 let Some(since) = since else {
8318 return Ok(true);
8319 };
8320 if item.content_kind == ContentKind::DraftIssue {
8321 return Ok(false);
8322 }
8323 // An `updatedAt` this process's own record or a lagging index holds can predate a
8324 // comment this process wrote since, so only an issue it did not comment on is ruled
8325 // out by one.
8326 if item.updated_at.is_some_and(|updated| updated < since)
8327 && !self.commented()?.contains(&item.id)
8328 {
8329 return Ok(false);
8330 }
8331 let query = TaskQuery {
8332 commented_since: Some(since),
8333 ..TaskQuery::default()
8334 };
8335 let mut after: Option<String> = None;
8336 // A first page read beside its fellow candidates answers as this read's own would.
8337 let held = self.held_comments()?.get(&item.id).cloned();
8338 if let Some(first) = held {
8339 if query.comments_match(&first.items) {
8340 return Ok(true);
8341 }
8342 match first.next {
8343 Some(next) => after = Some(next.0),
8344 None => return Ok(false),
8345 }
8346 }
8347 loop {
8348 let data = self
8349 .graphql(
8350 graphql::ISSUE_COMMENTS,
8351 json!({"id":item.id.0,"first":MAX_PAGE_SIZE,"after":after}),
8352 )
8353 .await?;
8354 let Some(connection) = data
8355 .get("node")
8356 .filter(|value| !value.is_null())
8357 .and_then(|node| node.get("comments"))
8358 .filter(|value| !value.is_null())
8359 else {
8360 // Removed since the search reported it: no longer an issue with comments.
8361 return Ok(false);
8362 };
8363 let comments = optional_nodes(Some(connection), "issue comments")?
8364 .into_iter()
8365 .flatten()
8366 .map(comment_from)
8367 .collect::<Result<Vec<_>, _>>()?;
8368 if query.comments_match(&comments) {
8369 return Ok(true);
8370 }
8371 match next_cursor(connection)? {
8372 Some(next) => {
8373 validate_cursor_progress(after.as_deref(), &next.0)?;
8374 after = Some(next.0);
8375 }
8376 None => return Ok(false),
8377 }
8378 }
8379 }
8380
8381 /// Every item on the board: the union of both enumerations GitHub offers of one.
8382 ///
8383 /// Neither contains the other, so neither is dropped — only `ProjectV2.items` lists a
8384 /// board **draft** and reads the board's own fields beside its items, and only the search
8385 /// reports an item that connection is behind on. The module documentation is where the lag and the
8386 /// measurements behind it are written down.
8387 ///
8388 /// A search result is admitted on the same terms as any other issue this source reaches
8389 /// directly — [`Self::resolve_issue`] keeps it only if that issue's own `projectItems`
8390 /// names *this* board — so an issue the index still believes is here after it was taken
8391 /// off is refused rather than reported.
8392 ///
8393 /// See [`Self::board_cache`]. Both completions happen on every call rather than once,
8394 /// which is what the cache could otherwise have broken.
8395 async fn board(&self) -> Result<Board, SourceError> {
8396 self.board_completed_by(None).await
8397 }
8398
8399 /// [`Self::board`], its search half narrowed by `also` when it is given — which an issue
8400 /// that half could add is then answered only if it holds.
8401 async fn board_completed_by(&self, also: Option<&str>) -> Result<Board, SourceError> {
8402 let cached = self.board_cache()?.clone();
8403 let mut board = match cached {
8404 Some(board) => board,
8405 None => {
8406 let read = self.read_board().await?;
8407 *self.board_cache()? = Some(read.clone());
8408 read
8409 }
8410 };
8411 let searched = match also {
8412 None => self.searched_issues().await?,
8413 Some(also) => self.searched_narrowly(also).await?,
8414 };
8415 // A complete sweep asks for every page of this view. Reconcile ids once per
8416 // view, rather than scanning the board for every search result on every page.
8417 let mut ids: std::collections::HashSet<_> =
8418 board.items.iter().map(|item| item.id.clone()).collect();
8419 for held in searched {
8420 if ids.insert(held.id.clone()) {
8421 board.items.push(held);
8422 }
8423 }
8424 for own in self.created()?.iter() {
8425 if ids.insert(own.id.clone()) {
8426 board.items.push(own.clone());
8427 }
8428 }
8429 Ok(board)
8430 }
8431
8432 /// Every open item of this board, drafts included, read through the board's own `is:open`
8433 /// filter page by page — never its unfiltered `items`, and with no issue search beside it —
8434 /// held for the command under [`OPEN_ITEMS_KEY`] on the terms every narrowed answer is
8435 /// held on, and completed with this process's own writes each time it is given.
8436 ///
8437 /// What a task listing whose every status category is open reads: an item is open exactly
8438 /// when GitHub's filter answers it, so the categories are still confirmed in process from
8439 /// each item's own node, and the answer is the whole board's filtered to the same
8440 /// categories — an open issue under a terminal card read as its card, a draft and an item
8441 /// under an option no mapping names included.
8442 async fn open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8443 let key = OPEN_ITEMS_KEY.to_owned();
8444 let cached = self.narrowed_cache()?.get(&key).cloned();
8445 let mut found = match cached {
8446 Some(found) => found,
8447 None => {
8448 let found = self.read_open_items().await?;
8449 self.narrowed_cache()?.insert(key, found.clone());
8450 found
8451 }
8452 };
8453 // Every item this process wrote, drafts included: the filter answers drafts, so an
8454 // own draft is as much an answer as an own issue. Its category is confirmed below like
8455 // any other's, so one this process closed is left out there.
8456 let own: Vec<Resolved> = self
8457 .created()?
8458 .iter()
8459 .chain(self.updated()?.iter())
8460 .cloned()
8461 .collect();
8462 for own in own {
8463 match found.iter_mut().find(|read| read.id == own.id) {
8464 Some(read) => *read = own,
8465 None => found.push(own),
8466 }
8467 }
8468 Ok(found)
8469 }
8470
8471 /// Every page of [`graphql::OPEN_ITEMS`], resolved; the board's own fields are held for
8472 /// the writes that follow, as a reconcile holds them.
8473 async fn read_open_items(&self) -> Result<Vec<Resolved>, SourceError> {
8474 let mut after: Option<String> = None;
8475 let mut found = Vec::new();
8476 loop {
8477 let data = self
8478 .graphql(
8479 graphql::OPEN_ITEMS,
8480 json!({"owner":self.owner,"number":self.project_number,
8481 "first":MAX_PAGE_SIZE,"after":after,"filter":OPEN_QUALIFIER,
8482 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
8483 )
8484 .await?;
8485 let board = data
8486 .pointer("/openItems/projectV2")
8487 .filter(|value| !value.is_null())
8488 .ok_or_else(|| SourceError::Refused {
8489 message: format!(
8490 "GitHub project {}/{} was not found or is not visible to the token",
8491 self.owner, self.project_number
8492 ),
8493 })?;
8494 *self.fields_cache()? = Some(BoardFields {
8495 id: BoardId::parse(required_str(board, "id")?)?,
8496 fields: board.get("fields").cloned().unwrap_or(Value::Null),
8497 });
8498 let items = board.get("items").ok_or_else(|| SourceError::Malformed {
8499 message: "GitHub project open items are missing".into(),
8500 })?;
8501 for item in items
8502 .get("nodes")
8503 .and_then(Value::as_array)
8504 .ok_or_else(|| SourceError::Malformed {
8505 message: "GitHub project items.nodes is not an array".into(),
8506 })?
8507 {
8508 if let Some(resolved) = self.resolve(item)? {
8509 found.push(resolved);
8510 }
8511 }
8512 let info = items
8513 .get("pageInfo")
8514 .ok_or_else(|| SourceError::Malformed {
8515 message: "GitHub project items have no pageInfo".into(),
8516 })?;
8517 if !required_bool(info, "hasNextPage")? {
8518 return Ok(found);
8519 }
8520 let next = required_str(info, "endCursor")?;
8521 validate_cursor_progress(after.as_deref(), next)?;
8522 after = Some(next.to_owned());
8523 }
8524 }
8525
8526 /// This process's own view of the board, or the refusal a poisoned lock is.
8527 fn board_cache(&self) -> Result<std::sync::MutexGuard<'_, Option<Board>>, SourceError> {
8528 self.board_cache
8529 .lock()
8530 .map_err(|_| SourceError::Unavailable {
8531 message: "this source's view of the board was left inconsistent by an earlier \
8532 failure; next: run the command again"
8533 .into(),
8534 })
8535 }
8536
8537 /// Bring this process's own view of the board up to an item it has just written.
8538 ///
8539 /// A created item goes to `created`, which is what completes a board read GitHub's own
8540 /// eventual consistency has left behind. An item that was already there is replaced
8541 /// where it sits, so a second write of it in the same command reads its real parent
8542 /// rather than the one it had before the first write.
8543 ///
8544 /// "Where it sits" is three places, and missing an earlier one leaves a stale record
8545 /// that wins: an item this same run created is held in `created` and not in the cached
8546 /// board, and `board` completes the cached board *from* `created`, so replacing only
8547 /// the cached copy of such an item replaces nothing and the read still reports the
8548 /// title it was created with. The search is the third, and it is the one an item the
8549 /// board's own projection is behind on sits in *alone* — which is exactly the item this
8550 /// source is least able to re-read, so leaving it out would put the stale title back on
8551 /// the only items the completion in [`Self::board`] exists for.
8552 fn remember_written(&self, item: Resolved, created: bool) -> Result<(), SourceError> {
8553 self.resolved_cache()?.insert(item.id.clone(), item.clone());
8554 if created {
8555 self.created()?.push(item);
8556 return Ok(());
8557 }
8558 {
8559 let mut own = self.created()?;
8560 if let Some(held) = own.iter_mut().find(|held| held.id == item.id) {
8561 *held = item;
8562 return Ok(());
8563 }
8564 }
8565 {
8566 let mut own = self.updated()?;
8567 match own.iter_mut().find(|held| held.id == item.id) {
8568 Some(held) => *held = item.clone(),
8569 None => own.push(item.clone()),
8570 }
8571 }
8572 if let Some(board) = self.board_cache()?.as_mut()
8573 && let Some(held) = board.items.iter_mut().find(|held| held.id == item.id)
8574 {
8575 *held = item.clone();
8576 }
8577 if let Some(found) = self.search_cache()?.as_mut()
8578 && let Some(held) = found.iter_mut().find(|held| held.id == item.id)
8579 {
8580 *held = item.clone();
8581 }
8582 for found in self.narrowed_cache()?.values_mut() {
8583 if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8584 *held = item.clone();
8585 }
8586 }
8587 for (_, found) in self.children_cache()?.values_mut() {
8588 if let Some(held) = found.iter_mut().find(|held| held.id == item.id) {
8589 *held = item.clone();
8590 }
8591 }
8592 Ok(())
8593 }
8594
8595 /// Forget one item this process has just deleted, from every half of its own view.
8596 fn forget(&self, id: &NativeId) -> Result<(), SourceError> {
8597 if let Some(Deferred::Held { created, .. }) = self.deferred()?.as_mut() {
8598 created.retain(|held| held.content != *id);
8599 }
8600 self.resolved_cache()?.remove(id);
8601 self.read_ahead()?.remove(id);
8602 self.carried()?.remove(id);
8603 self.created()?.retain(|own| own.id != *id);
8604 self.updated()?.retain(|own| own.id != *id);
8605 self.commented()?.retain(|own| own != id);
8606 if let Some(board) = self.board_cache()?.as_mut() {
8607 board.items.retain(|item| item.id != *id);
8608 }
8609 if let Some(found) = self.search_cache()?.as_mut() {
8610 found.retain(|item| item.id != *id);
8611 }
8612 for found in self.narrowed_cache()?.values_mut() {
8613 found.retain(|item| item.id != *id);
8614 }
8615 for (_, found) in self.children_cache()?.values_mut() {
8616 found.retain(|item| item.id != *id);
8617 }
8618 Ok(())
8619 }
8620
8621 /// This process's own record of each narrowed answer, or the refusal a poisoned lock is.
8622 fn narrowed_cache(
8623 &self,
8624 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<String, Vec<Resolved>>>, SourceError> {
8625 self.narrowed_cache
8626 .lock()
8627 .map_err(|_| SourceError::Unavailable {
8628 message: "this source's view of a narrowed read was left inconsistent by an \
8629 earlier failure; next: run the command again"
8630 .into(),
8631 })
8632 }
8633
8634 /// This process's own record of each project's sub-issues, or the refusal a poisoned lock
8635 /// is.
8636 /// The tasks `project` holds, as a copy's batched read found them this command, when it did.
8637 fn held_task_children(&self, project: &NativeId) -> Result<Option<Vec<Resolved>>, SourceError> {
8638 Ok(self.task_children()?.get(project).cloned())
8639 }
8640
8641 fn task_children(
8642 &self,
8643 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<NativeId, Vec<Resolved>>>, SourceError> {
8644 self.task_children
8645 .lock()
8646 .map_err(|_| SourceError::Unavailable {
8647 message: "this source's record of a project's tasks was left inconsistent by an \
8648 earlier failure; next: run the command again"
8649 .into(),
8650 })
8651 }
8652
8653 fn children_cache(&self) -> Result<std::sync::MutexGuard<'_, ProjectChildren>, SourceError> {
8654 self.children_cache
8655 .lock()
8656 .map_err(|_| SourceError::Unavailable {
8657 message: "this source's view of a project's tasks was left inconsistent by an \
8658 earlier failure; next: run the command again"
8659 .into(),
8660 })
8661 }
8662
8663 /// Every page of the board, read from GitHub.
8664 async fn read_board(&self) -> Result<Board, SourceError> {
8665 let mut after: Option<String> = None;
8666 let mut items = Vec::new();
8667 let mut board;
8668 loop {
8669 let page = self.board_page(after.as_deref(), MAX_PAGE_SIZE).await?;
8670 for item in page
8671 .pointer("/items/nodes")
8672 .and_then(Value::as_array)
8673 .ok_or_else(|| SourceError::Malformed {
8674 message: "GitHub project items.nodes is not an array".into(),
8675 })?
8676 {
8677 if let Some(resolved) = self.resolve(item)? {
8678 items.push(resolved);
8679 }
8680 }
8681 let info = page
8682 .pointer("/items/pageInfo")
8683 .ok_or_else(|| SourceError::Malformed {
8684 message: "GitHub project items have no pageInfo".into(),
8685 })?;
8686 let has_next = required_bool(info, "hasNextPage")?;
8687 let next = has_next
8688 .then(|| required_str(info, "endCursor"))
8689 .transpose()?;
8690 board = page.clone();
8691 match next {
8692 Some(next) => {
8693 validate_cursor_progress(after.as_deref(), next)?;
8694 after = Some(next.to_owned());
8695 }
8696 None => break,
8697 }
8698 }
8699 Ok(Board {
8700 id: required_str(&board, "id")?.to_owned(),
8701 fields: board.get("fields").cloned().unwrap_or(Value::Null),
8702 items,
8703 })
8704 }
8705
8706 /// The existing items this source has written, for completing a narrowed read that is
8707 /// behind; see [`Self::updated`](GitHubProjectsSource::updated).
8708 fn updated(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8709 self.updated.lock().map_err(|_| SourceError::Unavailable {
8710 message: "this source's record of what it wrote in this run was left inconsistent \
8711 by an earlier failure; next: run the command again"
8712 .into(),
8713 })
8714 }
8715
8716 /// The issues this source has commented on in this command; see
8717 /// [`Self::commented`](GitHubProjectsSource::commented).
8718 fn commented(&self) -> Result<std::sync::MutexGuard<'_, Vec<NativeId>>, SourceError> {
8719 self.commented.lock().map_err(|_| SourceError::Unavailable {
8720 message: "this source's record of what it commented on in this run was left \
8721 inconsistent by an earlier failure; next: run the command again"
8722 .into(),
8723 })
8724 }
8725
8726 /// Called only once GitHub has answered the comment write, so an issue whose comment
8727 /// failed is never made a candidate a later read would pay a node read for.
8728 fn remember_commented(&self, issue: &NativeId) -> Result<(), SourceError> {
8729 // A comment page held for this command is no longer what the issue holds.
8730 self.held_comments()?.remove(issue);
8731 let mut commented = self.commented()?;
8732 if !commented.contains(issue) {
8733 commented.push(issue.clone());
8734 }
8735 Ok(())
8736 }
8737
8738 /// The items this source has created, for completing a board read that is behind.
8739 fn created(&self) -> Result<std::sync::MutexGuard<'_, Vec<Resolved>>, SourceError> {
8740 self.created.lock().map_err(|_| SourceError::Unavailable {
8741 message: "this source's record of what it created in this run was left \
8742 inconsistent by an earlier failure; next: run the command again"
8743 .into(),
8744 })
8745 }
8746
8747 /// One board item as this source reports it, or `None` for content it ignores.
8748 ///
8749 /// A pull request is neither a project nor a task — it is somebody's change, not a
8750 /// unit of plan — and an item whose content the token cannot see has nothing to
8751 /// report at all.
8752 fn resolve(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8753 let resolved = self.resolve_unremembered(item)?;
8754 if let Some(resolved) = &resolved {
8755 self.resolved_cache()?
8756 .insert(resolved.id.clone(), resolved.clone());
8757 }
8758 Ok(resolved)
8759 }
8760
8761 /// [`Self::resolve`], without remembering the item it resolves: what reading a token off a
8762 /// write's own response needs, which says nothing this process should answer a later read
8763 /// with.
8764 fn resolve_unremembered(&self, item: &Value) -> Result<Option<Resolved>, SourceError> {
8765 let content = item.get("content").ok_or_else(|| SourceError::Malformed {
8766 message: "GitHub project item is missing content".into(),
8767 })?;
8768 if content.is_null() {
8769 return Ok(None);
8770 }
8771 let content_kind = match required_str(content, "__typename")? {
8772 "Issue" => ContentKind::Issue,
8773 "DraftIssue" => ContentKind::DraftIssue,
8774 _ => return Ok(None),
8775 };
8776 let field_values = item
8777 .get("fieldValues")
8778 .ok_or_else(|| SourceError::Malformed {
8779 message: "GitHub project item is missing fieldValues".into(),
8780 })?;
8781 complete_connection(field_values, "project item field values", NESTED_PAGE_SIZE)?;
8782 let nodes = field_values
8783 .get("nodes")
8784 .and_then(Value::as_array)
8785 .ok_or_else(|| SourceError::Malformed {
8786 message: "GitHub project item fieldValues.nodes is not an array".into(),
8787 })?;
8788 if let Some(labels) = content.get("labels") {
8789 complete_connection(labels, "content labels", NESTED_PAGE_SIZE)?;
8790 }
8791 let raw_body = optional_str(content, "body")?.map(str::to_owned);
8792 let (body, slot) = self.visible(raw_body.clone())?;
8793 let parent = optional_str(content.get("parent").unwrap_or(&Value::Null), "id")?
8794 .map(|id| NativeId(id.to_owned()));
8795 // A draft has no sub-issues to summarise, and GitHub's schema gives it no field
8796 // to read one from; it is a task, and never a project.
8797 let sub_issues = match content_kind {
8798 ContentKind::Issue => sub_issue_total(content)?,
8799 ContentKind::DraftIssue => 0,
8800 };
8801 let content_id = required_str(content, "id")?;
8802 let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
8803 message: format!("GitHub issue {content_id}: {message}"),
8804 })?;
8805 let raw_title = required_str(content, "title")?;
8806 // Read as children, a sub-issue is filed under no project and nothing is a project: the
8807 // GitHub parent is the parent relation instead.
8808 let (kind, parent, issue_parent) = match self.sub_issues {
8809 SubIssues::Project => (
8810 BoardKind::of(raw_title, parent.is_some(), sub_issues, marked),
8811 parent,
8812 None,
8813 ),
8814 SubIssues::Parent => (
8815 if raw_title.starts_with(DESIGN_TITLE_PREFIX) {
8816 BoardKind::Document
8817 } else {
8818 BoardKind::Work(ItemKind::Task)
8819 },
8820 None,
8821 parent,
8822 ),
8823 };
8824 // The title a person wrote, which for a document is the one without the prefix —
8825 // the same way `content` above is the body without this source's metadata slot.
8826 let title = match kind {
8827 BoardKind::Document => raw_title[DESIGN_TITLE_PREFIX.len()..].to_owned(),
8828 BoardKind::Work(_) => raw_title.to_owned(),
8829 };
8830 let own_repository = content
8831 .pointer("/repository/nameWithOwner")
8832 .and_then(Value::as_str)
8833 .map(|origin| Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST)))
8834 .transpose()
8835 .map_err(|message| SourceError::Malformed { message })?;
8836 let repositories = if slot.contains_key(Repository::METADATA_KEY) {
8837 Repository::from_metadata(&slot)
8838 .map_err(|message| SourceError::Malformed { message })?
8839 } else {
8840 own_repository.clone().into_iter().collect()
8841 };
8842 let classification = Classification::from_metadata(&slot)
8843 .map_err(|message| SourceError::Malformed { message })?;
8844 let id = NativeId(content_id.to_owned());
8845 // Read only for a task, because only a task has either list: a project or a
8846 // document holding one of these keys holds nothing this source reports, and the
8847 // keys are left out of its caller-visible metadata all the same.
8848 let (delivers, delivered_by) = if kind == BoardKind::Work(ItemKind::Task) {
8849 let listed = |key: &str| {
8850 TaskRef::from_value(key, &id, Some(&self.name), slot.get(key))
8851 .map_err(|message| SourceError::Malformed { message })
8852 };
8853 (
8854 listed(TaskRef::DELIVERS_KEY)?,
8855 listed(TaskRef::DELIVERED_BY_KEY)?,
8856 )
8857 } else {
8858 (Vec::new(), Vec::new())
8859 };
8860 let (option, closed, reason) = Self::status_parts(nodes, content)?;
8861 let priority = self.held_priority(nodes)?;
8862 let item_labels = labels(content)?;
8863 // Present when the item was reached through its own issue, whose board entry
8864 // names the board; a read of the board's own items has the board already. An
8865 // empty id names nothing a field write could address, so it is read as absent and
8866 // the write goes back to reading the board.
8867 let board_id = item
8868 .pointer("/project/id")
8869 .and_then(Value::as_str)
8870 .filter(|id| !id.is_empty());
8871 let resolved = Resolved {
8872 item_id: required_str(item, "id")?.to_owned(),
8873 id,
8874 content_kind,
8875 kind,
8876 title,
8877 body: body.filter(|value| !value.is_empty()),
8878 raw_body,
8879 status: self
8880 .statuses
8881 .status(kind.status_kind(), option, closed, reason),
8882 option: option.map(str::to_owned),
8883 priority,
8884 closed,
8885 reason: closed.then(|| reason.map(str::to_owned)).flatten(),
8886 delivers,
8887 delivered_by,
8888 labels: item_labels.clone(),
8889 parent,
8890 issue_parent,
8891 origin: text_field(nodes, ORIGIN_FIELD)?.filter(|value| !value.is_empty()),
8892 projected: self.held_projections(nodes)?,
8893 number: match content_kind {
8894 ContentKind::Issue => Some(issue_number(content)?),
8895 // A draft is filed in no repository, so nothing ever numbered it:
8896 // `DraftIssue` declares no `number` at all, exactly as it declares no
8897 // `subIssuesSummary` the branch above reads.
8898 ContentKind::DraftIssue => None,
8899 },
8900 url: optional_str(content, "url")?.map(str::to_owned),
8901 created_at: optional_time(content, "createdAt")?,
8902 updated_at: optional_time(content, "updatedAt")?,
8903 item_updated_at: optional_time(item, "updatedAt")?,
8904 comment_count: content
8905 .pointer("/commentCount/totalCount")
8906 .and_then(Value::as_u64),
8907 relationship_events: content
8908 .pointer("/relationshipEvents/totalCount")
8909 .and_then(Value::as_u64),
8910 // The issue node is stamped wherever it was read; a board item a read of the issue
8911 // put together from its memberships is not.
8912 served_at: match optional_time(content, SERVED_AT)? {
8913 Some(served) => Some(served),
8914 None => optional_time(item, SERVED_AT)?,
8915 },
8916 // Both connections were read to their end above — one reporting a further page is
8917 // refused — so these are every field value and every label the item holds. A
8918 // response that did not select the labels at all says nothing of them, and gives
8919 // no facets.
8920 facets: content.get("labels").is_some().then(|| {
8921 change_token::Facets::new(kind.facet(), facet_fields(nodes), &item_labels).digest()
8922 }),
8923 own_repository,
8924 repositories,
8925 classification,
8926 slot,
8927 board_id: board_id.map(str::to_owned),
8928 fields: field_definitions(nodes),
8929 board_fields: Self::carried_board_fields(content, board_id)?,
8930 blocked_by: carried_blocked_by(content)?,
8931 assignees: if self.assignees {
8932 Some(assignees::assignee_logins(content)?)
8933 } else {
8934 None
8935 },
8936 };
8937 Ok(Some(resolved))
8938 }
8939
8940 /// The field definitions of the board `board_id` names — the project this issue's own
8941 /// board item is on — off the `boards` page a read of an issue by its own id carries, or
8942 /// `None` when the read carried none, carried no entry for that board, or the board item
8943 /// named no board, which a write then answers by reading the board's fields itself.
8944 ///
8945 /// Matched by the board's node id and never by its number alone: a project number is
8946 /// unique only within its owner, so another owner's board numbered alike can sit on the
8947 /// same page, and its field and option ids address nothing on this one.
8948 fn carried_board_fields(
8949 content: &Value,
8950 board_id: Option<&str>,
8951 ) -> Result<Option<Value>, SourceError> {
8952 let (Some(nodes), Some(board_id)) = (
8953 content.pointer("/boards/nodes").and_then(Value::as_array),
8954 board_id,
8955 ) else {
8956 return Ok(None);
8957 };
8958 let Some(board) = nodes.iter().find_map(|node| {
8959 let project = node.get("project")?;
8960 (project.get("id").and_then(Value::as_str) == Some(board_id)).then_some(project)
8961 }) else {
8962 return Ok(None);
8963 };
8964 let Some(fields) = board.get("fields").filter(|fields| !fields.is_null()) else {
8965 return Ok(None);
8966 };
8967 complete_connection(fields, "board fields", NESTED_PAGE_SIZE)?;
8968 Ok(Some(fields.clone()))
8969 }
8970
8971 /// What one board item's `Priority` field says, through this instance's mapping.
8972 ///
8973 /// An instance with no mapping holds no priority, so every item reads as `none` whatever
8974 /// its board holds. With one, no value is `none`, a mapped option is its level, and an
8975 /// option the mapping does not name is kept as itself — never read as a level or as
8976 /// `none` — for a read of the task to report by name.
8977 fn held_priority(&self, field_values: &[Value]) -> Result<HeldPriority, SourceError> {
8978 let Some(mapping) = &self.priorities else {
8979 return Ok(HeldPriority::Read(Priority::None));
8980 };
8981 // A value of the field that names no option — a text field someone called `Priority` —
8982 // is malformed rather than `none`: reading it as no priority would let the next copy
8983 // clear one a person set.
8984 let Some(option) = field_values
8985 .iter()
8986 .find(|value| {
8987 value.pointer("/field/name").and_then(Value::as_str) == Some(PRIORITY_FIELD)
8988 })
8989 .map(|value| required_str(value, "name"))
8990 .transpose()?
8991 else {
8992 return Ok(HeldPriority::Read(Priority::None));
8993 };
8994 Ok(mapping.priority_of(option).map_or_else(
8995 || HeldPriority::Unmapped(option.to_owned()),
8996 HeldPriority::Read,
8997 ))
8998 }
8999
9000 /// What each projected metadata field holds for one board item, by field name — every text
9001 /// value GitHub answers, an empty one included.
9002 fn held_projections(
9003 &self,
9004 field_values: &[Value],
9005 ) -> Result<BTreeMap<String, String>, SourceError> {
9006 let mut held = BTreeMap::new();
9007 for projection in &self.metadata_fields {
9008 if let Some(text) = text_field(field_values, &projection.field)? {
9009 held.insert(projection.field.to_string(), text);
9010 }
9011 }
9012 Ok(held)
9013 }
9014
9015 /// What one board item's status is read from: its `Status` option, whether its issue
9016 /// is closed, and the reason it was closed with. [`BoardStatuses::status`] turns the
9017 /// three into the status it reports.
9018 fn status_parts<'a>(
9019 field_values: &'a [Value],
9020 content: &'a Value,
9021 ) -> Result<(Option<&'a str>, bool, Option<&'a str>), SourceError> {
9022 let option = field_values
9023 .iter()
9024 .find(|value| value.pointer("/field/name").and_then(Value::as_str) == Some("Status"))
9025 .map(|value| required_str(value, "name"))
9026 .transpose()?;
9027 let closed = optional_str(content, "state")? == Some("CLOSED");
9028 Ok((option, closed, optional_str(content, "stateReason")?))
9029 }
9030
9031 /// The board Status option this write selects, or the refusal that says why not.
9032 ///
9033 /// The mapped option is required for both open and terminal targets. A terminal write
9034 /// validates it before changing either representation, so it can never fall back to
9035 /// closing an issue whose board cannot display the matching status.
9036 ///
9037 /// Answers the field's id, the option's id, and the option's name as the board spells
9038 /// it — which is the name a read of the item reports once it sits there.
9039 fn column_for(
9040 &self,
9041 fields: &Value,
9042 kind: ItemKind,
9043 category: StatusCategory,
9044 target: &StatusTarget,
9045 ) -> Result<Option<(String, String, String)>, SourceError> {
9046 let Some(wanted) = target.option() else {
9047 return Ok(None);
9048 };
9049 let missing = |detail: &str| SourceError::Refused {
9050 message: format!(
9051 "{} status {} of source {} needs the board Status option {wanted:?}, and \
9052 {detail}; next: add that option to the board, which `onetaskgraph sources \
9053 fields {} --apply` does, or point status_mapping.{}.{} of this source at one \
9054 it has",
9055 kind.marker(),
9056 category_name(category),
9057 self.name,
9058 self.name,
9059 category_name(category),
9060 kind.marker()
9061 ),
9062 };
9063 let Some(field) = Board::field(fields, "Status")? else {
9064 return Err(missing("this board has no Status field"));
9065 };
9066 if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9067 return Err(missing(
9068 "this board's Status field is not a single-select field",
9069 ));
9070 }
9071 let option = field
9072 .get("options")
9073 .and_then(Value::as_array)
9074 .and_then(|options| {
9075 options.iter().find(|option| {
9076 option
9077 .get("name")
9078 .and_then(Value::as_str)
9079 .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9080 })
9081 });
9082 match option {
9083 None => Err(missing("this board does not have it")),
9084 Some(option) => Ok(Some((
9085 required_str(field, "id")?.to_owned(),
9086 required_str(option, "id")?.to_owned(),
9087 required_str(option, "name")?.to_owned(),
9088 ))),
9089 }
9090 }
9091
9092 /// The refusal a status that closes an issue is answered with over a board draft.
9093 fn closes_a_draft(&self, category: StatusCategory) -> SourceError {
9094 SourceError::Refused {
9095 message: format!(
9096 "status {} of source {} closes the item's issue, and GitHub draft items have \
9097 no open or closed state",
9098 category_name(category),
9099 self.name
9100 ),
9101 }
9102 }
9103
9104 /// What a status write to one item needs of the board: the board's id and the
9105 /// definition of its `Status` field, read off the item when the item says both.
9106 ///
9107 /// The same reasoning as [`Self::fields_for`]: a node read of the item names its board,
9108 /// and its `Status` value carries that field's definition, options and all. An item that
9109 /// does not say — no board id, or no `Status` value to read the field off — takes them
9110 /// from [`Self::board_fields`], which reads no item.
9111 async fn status_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9112 if let Some(board) = item.carried_board() {
9113 return Ok(board);
9114 }
9115 if item.defines("Status")
9116 && let Some(board_id) = item.named_board()
9117 {
9118 return Ok(BoardFields {
9119 id: board_id,
9120 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9121 });
9122 }
9123 self.board_fields().await
9124 }
9125
9126 /// Set one task's or one project's status and nothing else; see
9127 /// [`TaskSource::set_task_status`] and [`TaskSource::set_project_status`].
9128 async fn set_status(
9129 &self,
9130 id: &NativeId,
9131 kind: ItemKind,
9132 category: StatusCategory,
9133 ) -> Result<Option<Status>, SourceError> {
9134 // Refused before anything is read, in the words a write of the same status is.
9135 let target = self.resolved_target(kind, category)?;
9136 // An item read by issue reference carries only what this write needs, so what it
9137 // becomes is never remembered for a later read to be answered from.
9138 let held = self.take_held(id)?;
9139 let by_reference = held.is_some();
9140 let bound = match held {
9141 Some(item) => Some(item),
9142 None => self.bound_item(id).await?,
9143 };
9144 let Some(mut item) = bound.filter(|item| item.kind == BoardKind::Work(kind)) else {
9145 return Ok(None);
9146 };
9147 let board = self.status_board(&item).await?;
9148 let (field, option, name) = self
9149 .column_for(&board.fields, kind, category, &target)?
9150 .ok_or_else(|| SourceError::Malformed {
9151 message: format!(
9152 "status {} of source {} names no board Status option",
9153 category_name(category),
9154 self.name
9155 ),
9156 })?;
9157 // The card already shows the target's option. That alone is not the status: an open
9158 // issue under a terminal card reads that card's category while GitHub, its
9159 // notifications and a search of open issues all say the work is not finished, and a
9160 // closed issue under an open column's card reads as its closure. So the write is no
9161 // write only where the issue's open or closed state is also what the target needs —
9162 // closed, for a reason reading this category, for a terminal one; open for a column.
9163 let at_option = item
9164 .option
9165 .as_deref()
9166 .is_some_and(|held| held.eq_ignore_ascii_case(&name));
9167 let issue = item.content_kind == ContentKind::Issue;
9168 let state_holds = match &target {
9169 StatusTarget::Terminal(_, _) => {
9170 !issue || (item.closed && closed_category(item.reason.as_deref()) == category)
9171 }
9172 _ => !issue || !item.closed,
9173 };
9174 if item.status.category == category && at_option && state_holds {
9175 return Ok(Some(item.status));
9176 }
9177 match &target {
9178 StatusTarget::Terminal(_, reason) => {
9179 if item.content_kind == ContentKind::DraftIssue {
9180 return Err(self.closes_a_draft(category));
9181 }
9182 // The option first, so a refused selection leaves an open issue open rather
9183 // than closed behind a card that still reads open. A card already showing it
9184 // is sent nothing: only the issue's state is out of line.
9185 if !at_option {
9186 self.set_item_field(
9187 board.id.as_str(),
9188 &item.item_id,
9189 &field,
9190 json!({"singleSelectOptionId": option}),
9191 )
9192 .await?;
9193 }
9194 // An issue already closed in a way that reads as this category keeps its state
9195 // and its reason: only its card was out of line, and closing it again would
9196 // overwrite a reason — a duplicate's — that says more than this write does.
9197 let already = item.closed && item.status.category == category;
9198 if !already {
9199 self.update_content(
9200 ContentKind::Issue,
9201 &item.id,
9202 json!({"stateInput": state_input(Some(&target))}),
9203 )
9204 .await?;
9205 }
9206 let reason = if already {
9207 item.reason.clone()
9208 } else {
9209 Some(reason.reason().to_owned())
9210 };
9211 item.closed = true;
9212 item.status = self
9213 .statuses
9214 .status(kind, Some(&name), true, reason.as_deref());
9215 item.option = Some(name);
9216 item.reason = reason;
9217 }
9218 StatusTarget::Column(_) => {
9219 // An option is what an open item's status is, so a closed issue is reopened
9220 // first — sitting closed in the column, it would read back as closed. A draft has
9221 // no state to reopen.
9222 if item.content_kind == ContentKind::Issue && item.closed {
9223 self.update_content(
9224 ContentKind::Issue,
9225 &item.id,
9226 json!({"stateInput": state_input(Some(&target))}),
9227 )
9228 .await?;
9229 item.closed = false;
9230 }
9231 if !at_option {
9232 self.set_item_field(
9233 board.id.as_str(),
9234 &item.item_id,
9235 &field,
9236 json!({"singleSelectOptionId": option}),
9237 )
9238 .await?;
9239 }
9240 item.status = self.statuses.status(kind, Some(&name), false, None);
9241 item.option = Some(name);
9242 }
9243 StatusTarget::Disabled(_) => {
9244 unreachable!("resolved_target refused a disabled status")
9245 }
9246 }
9247 let status = item.status.clone();
9248 if !by_reference {
9249 self.remember_written(item, false)?;
9250 }
9251 Ok(Some(status))
9252 }
9253
9254 /// Replace one task's `delivered_by` and nothing else; see
9255 /// [`TaskSource::set_delivered_by`].
9256 ///
9257 /// One update of the body, which differs from the body GitHub holds only inside the
9258 /// metadata slot — see [`with_slot`]. A body that would not change is not sent at all.
9259 async fn replace_delivered_by(
9260 &self,
9261 id: &NativeId,
9262 delivered_by: &[TaskRef],
9263 ) -> Result<Option<()>, SourceError> {
9264 let entries = TaskRef::listed(
9265 TaskRef::DELIVERED_BY_KEY,
9266 id,
9267 Some(&self.name),
9268 delivered_by.to_vec(),
9269 )
9270 .map_err(|message| SourceError::Refused { message })?;
9271 let Some(mut item) = self
9272 .bound_item(id)
9273 .await?
9274 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9275 else {
9276 return Ok(None);
9277 };
9278 let mut slot = item.slot.clone();
9279 set_task_list(&mut slot, TaskRef::DELIVERED_BY_KEY, &entries);
9280 self.write_slot(&mut item, &slot).await?;
9281 item.delivered_by = entries;
9282 self.remember_written(item, false)?;
9283 Ok(Some(()))
9284 }
9285
9286 /// Set one caller key of the metadata slot of one issue of `kind`, and nothing else;
9287 /// see [`TaskSource::set_task_metadata`].
9288 ///
9289 /// `None` when this board holds no item by that id, or holds one of another kind. The
9290 /// answer is the item as this source now reads it, so what a caller is told the key
9291 /// holds is what the slot holds.
9292 ///
9293 /// A key already holding the value is answered without a write, compared as JSON rather
9294 /// than as the body's bytes: a slot a person spelled with other whitespace would
9295 /// otherwise be re-encoded, which is a write that changes nothing the caller asked for.
9296 async fn set_slot_key(
9297 &self,
9298 id: &NativeId,
9299 kind: BoardKind,
9300 key: &MetadataKey,
9301 value: &Value,
9302 ) -> Result<Option<Resolved>, SourceError> {
9303 let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
9304 return Ok(None);
9305 };
9306 if item.slot.get(key.as_str()) == Some(value) {
9307 return Ok(Some(item));
9308 }
9309 let mut slot = item.slot.clone();
9310 slot.insert(key.as_str().to_owned(), value.clone());
9311 // A key a board text field projects moves that field first, so the body — the value's
9312 // one authoritative home — is written last, as every write of an existing item is.
9313 if self
9314 .metadata_fields
9315 .iter()
9316 .any(|projection| &*projection.key == key.as_str())
9317 {
9318 let board = self.projection_board(&item).await?;
9319 let (writes, projected) = self.projection_writes(
9320 &board.fields,
9321 Some(&item.projected),
9322 &slot,
9323 Some(&[key.as_str()]),
9324 )?;
9325 let (mut values, mut clears) = (Vec::new(), Vec::new());
9326 for write in &writes {
9327 write.join(&mut values, &mut clears);
9328 }
9329 self.set_item_fields(board.id.as_str(), &item.item_id, &values, &clears)
9330 .await?;
9331 item.projected = projected;
9332 }
9333 self.write_slot(&mut item, &slot).await?;
9334 self.remember_written(item.clone(), false)?;
9335 Ok(Some(item))
9336 }
9337
9338 /// What a projection write to `item` needs of the board, read off the item when it says
9339 /// enough, as [`Self::fields_for`] reads it.
9340 async fn projection_board(&self, item: &Resolved) -> Result<BoardFields, SourceError> {
9341 if let Some(board) = item.carried_board() {
9342 return Ok(board);
9343 }
9344 if let Some(board_id) = item.named_board()
9345 && self
9346 .metadata_fields
9347 .iter()
9348 .all(|projection| item.defines(&projection.field))
9349 {
9350 return Ok(BoardFields {
9351 id: board_id,
9352 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9353 });
9354 }
9355 self.board_fields().await
9356 }
9357
9358 /// Put `slot` in one item's metadata slot with a single update of its body, and bring
9359 /// `item` up to what that write left.
9360 ///
9361 /// The body sent differs from the body GitHub holds only inside the slot — see
9362 /// [`with_slot`] — and a body that would not change is not sent at all. It goes through
9363 /// the mutation the item's content takes, so a board draft's body is written with
9364 /// `updateProjectV2DraftIssue` exactly as an issue's is with `updateIssue`.
9365 async fn write_slot(
9366 &self,
9367 item: &mut Resolved,
9368 slot: &BTreeMap<String, Value>,
9369 ) -> Result<(), SourceError> {
9370 let held = item.raw_body.clone().unwrap_or_default();
9371 let body = with_slot(&held, slot)?;
9372 if body != held {
9373 self.update_content(item.content_kind, &item.id, json!({"body": body}))
9374 .await?;
9375 }
9376 let (visible, slot) = self.visible(Some(body.clone()))?;
9377 item.body = visible.filter(|value| !value.is_empty());
9378 item.raw_body = Some(body);
9379 item.slot = slot;
9380 Ok(())
9381 }
9382
9383 /// This instance's target for a category written to an item of `kind`, refusing one
9384 /// that kind has no option for — before anything is read or written.
9385 ///
9386 /// Nothing here mutates the board's option set to make room for a status. GitHub
9387 /// documents `UpdateProjectV2FieldInput.singleSelectOptions` as *"provided values
9388 /// overwrite existing options"*, so no addition is additive and a mistake destroys the
9389 /// field and every item's status.
9390 fn resolved_target(
9391 &self,
9392 kind: ItemKind,
9393 category: StatusCategory,
9394 ) -> Result<StatusTarget, SourceError> {
9395 let target = self.statuses.target(kind, category).clone();
9396 let StatusTarget::Disabled(why) = target else {
9397 return Ok(target);
9398 };
9399 let refusal = why.refusal(&self.name, category, kind);
9400 // Why there is no shipped default, which is the question a person meeting this
9401 // refusal on a source that never mentioned the category asks.
9402 let shipped_none = match category {
9403 StatusCategory::Draft => Some(
9404 "draft has no shipped default because GitHub draft issues cannot have \
9405 sub-issues, and this source stores a project's tasks as its issue's sub-issues",
9406 ),
9407 StatusCategory::Unknown => Some(
9408 "unknown has no shipped default because this board keeps no open-ended status \
9409 word: every word classified unknown is written to the one board Status option \
9410 status_mapping.unknown names",
9411 ),
9412 _ => None,
9413 };
9414 Err(match (refusal, shipped_none, why) {
9415 (SourceError::Refused { message }, Some(note), UnmappedStatus::Unconfigured) => {
9416 SourceError::Refused {
9417 message: format!("{message}; {note}"),
9418 }
9419 }
9420 (refusal, _, _) => refusal,
9421 })
9422 }
9423
9424 /// What writing `priority` does to one item's `Priority` field on this board, or the
9425 /// refusal naming what the board lacks.
9426 ///
9427 /// `none` is no value, so it clears the field — and asks nothing of an item that holds
9428 /// none already, or of an item not created yet. Every other priority selects the option
9429 /// the mapping names, matched case-insensitively; a board with no `Priority` field, or
9430 /// without that option, is refused rather than given one: reads and writes never create
9431 /// a field or an option.
9432 fn priority_write(
9433 &self,
9434 fields: &Value,
9435 existing: Option<&Resolved>,
9436 priority: Priority,
9437 ) -> Result<Option<PriorityWrite>, SourceError> {
9438 let Some(mapping) = &self.priorities else {
9439 return Err(self.holds_no_priority());
9440 };
9441 let Some(wanted) = mapping.option(priority) else {
9442 if !existing.is_some_and(Resolved::holds_priority) {
9443 return Ok(None);
9444 }
9445 let field =
9446 Board::field(fields, PRIORITY_FIELD)?.ok_or_else(|| SourceError::Malformed {
9447 message: format!(
9448 "an item holding a {PRIORITY_FIELD} value was read without that field"
9449 ),
9450 })?;
9451 return Ok(Some(PriorityWrite::Clear {
9452 field: required_str(field, "id")?.to_owned(),
9453 }));
9454 };
9455 let missing = |detail: &str| SourceError::Refused {
9456 message: format!(
9457 "priority {priority} of source {} needs the board {PRIORITY_FIELD} option \
9458 {wanted:?}, and {detail}; run `onetaskgraph sources fields {} --apply` to add \
9459 it, or point priority_mapping.{priority} of this source at an option the board \
9460 has",
9461 self.name, self.name
9462 ),
9463 };
9464 let Some(field) = Board::field(fields, PRIORITY_FIELD)? else {
9465 return Err(missing(&format!(
9466 "this board has no {PRIORITY_FIELD} field"
9467 )));
9468 };
9469 if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
9470 return Err(missing(&format!(
9471 "this board's {PRIORITY_FIELD} field is not a single-select field"
9472 )));
9473 }
9474 // An options list that is absent or not a list is an answer this source cannot read,
9475 // not a board lacking the option: `sources fields --apply` is no remedy for it.
9476 let option = field
9477 .get("options")
9478 .and_then(Value::as_array)
9479 .ok_or_else(|| SourceError::Malformed {
9480 message: format!("GitHub {PRIORITY_FIELD} field options is not an array"),
9481 })?
9482 .iter()
9483 .find(|option| {
9484 option
9485 .get("name")
9486 .and_then(Value::as_str)
9487 .is_some_and(|name| name.eq_ignore_ascii_case(wanted))
9488 })
9489 .ok_or_else(|| missing("this board does not have it"))?;
9490 Ok(Some(PriorityWrite::Select {
9491 field: required_str(field, "id")?.to_owned(),
9492 option: required_str(option, "id")?.to_owned(),
9493 }))
9494 }
9495
9496 /// What writing `metadata` does to each projected text field of one item, and what those
9497 /// fields hold after it — or the refusal, before anything is sent.
9498 ///
9499 /// `held` is what the item's fields hold now, `None` for an item not created yet. `keys`
9500 /// narrows the work to the entries projecting one of those metadata keys, for a write that
9501 /// touches only them; `None` is every entry. A string the field already holds, and nothing
9502 /// for a field holding nothing, sends nothing. A value no text field can hold is refused,
9503 /// and so is a board without the field, or with a field of that name that is not a text
9504 /// field: reads and writes never create a field.
9505 fn projection_writes(
9506 &self,
9507 fields: &Value,
9508 held: Option<&BTreeMap<String, String>>,
9509 metadata: &BTreeMap<String, Value>,
9510 keys: Option<&[&str]>,
9511 ) -> Result<(Vec<ProjectionWrite>, BTreeMap<String, String>), SourceError> {
9512 let mut projected = held.cloned().unwrap_or_default();
9513 let mut writes = Vec::new();
9514 for projection in self
9515 .metadata_fields
9516 .iter()
9517 .filter(|projection| keys.is_none_or(|keys| keys.contains(&&*projection.key)))
9518 {
9519 let wanted = projection.projected(metadata, &self.name)?;
9520 let field = self.projection_field(fields, projection)?;
9521 let holding = projected.get(&*projection.field);
9522 match wanted {
9523 Projected::Text(text) if holding != Some(&text) => {
9524 writes.push(ProjectionWrite::Set {
9525 field,
9526 text: text.clone(),
9527 });
9528 projected.insert(projection.field.to_string(), text);
9529 }
9530 Projected::Nothing if holding.is_some() => {
9531 writes.push(ProjectionWrite::Clear { field });
9532 projected.remove(&*projection.field);
9533 }
9534 Projected::Text(_) | Projected::Nothing => {}
9535 }
9536 }
9537 Ok((writes, projected))
9538 }
9539
9540 /// The id of the board text field one projection writes, or the refusal naming what the
9541 /// board has instead.
9542 fn projection_field(
9543 &self,
9544 fields: &Value,
9545 projection: &MetadataField,
9546 ) -> Result<String, SourceError> {
9547 let refuse = |detail: String| SourceError::Refused {
9548 message: format!(
9549 "source {} projects metadata key {:?} onto the board text field {:?}, and \
9550 {detail}; next: run `onetaskgraph sources fields {} --apply` to create it as a \
9551 text field, or name another field in metadata_fields",
9552 self.name, &*projection.key, &*projection.field, self.name
9553 ),
9554 };
9555 let Some(field) = Board::field(fields, &projection.field)? else {
9556 return Err(refuse("this board has no field of that name".to_owned()));
9557 };
9558 let typename = optional_str(field, "__typename")?.unwrap_or("field of another type");
9559 let data_type = optional_str(field, "dataType")?;
9560 if typename != "ProjectV2Field" || data_type != Some("TEXT") {
9561 return Err(refuse(format!(
9562 "this board's field of that name is not a text field (it is a {}), so it is \
9563 left as it is; rename or remove that field first",
9564 data_type.unwrap_or(typename)
9565 )));
9566 }
9567 Ok(required_str(field, "id")?.to_owned())
9568 }
9569
9570 /// Apply one priority write to one board item.
9571 async fn write_priority(
9572 &self,
9573 board_id: &str,
9574 item_id: &str,
9575 write: &PriorityWrite,
9576 ) -> Result<(), SourceError> {
9577 match write {
9578 PriorityWrite::Select { field, option } => {
9579 self.set_item_field(
9580 board_id,
9581 item_id,
9582 field,
9583 json!({"singleSelectOptionId": option}),
9584 )
9585 .await
9586 }
9587 PriorityWrite::Clear { field } => {
9588 let data = self
9589 .graphql(
9590 graphql::CLEAR_FIELD,
9591 json!({"input":{"projectId":board_id,"itemId":item_id,"fieldId":field},
9592 "readPriority":false,"priorityName":PRIORITY_FIELD}),
9593 )
9594 .await?;
9595 let returned = data
9596 .pointer("/clearProjectV2ItemFieldValue/projectV2Item")
9597 .ok_or_else(|| SourceError::Malformed {
9598 message: "GitHub field clear returned no project item".into(),
9599 })?;
9600 if required_str(returned, "id")? != item_id {
9601 return Err(SourceError::Malformed {
9602 message: "GitHub field clear returned the wrong project item".into(),
9603 });
9604 }
9605 Ok(())
9606 }
9607 }
9608 }
9609
9610 /// The refusal a priority is answered with by an instance configured with no
9611 /// `priority_mapping`, which holds none.
9612 fn holds_no_priority(&self) -> SourceError {
9613 SourceError::Refused {
9614 message: format!(
9615 "source {} holds no task priority: its configuration sets no priority_mapping; \
9616 next: set priority_mapping on this source, then run `onetaskgraph sources \
9617 fields {} --apply` to set its board up",
9618 self.name, self.name
9619 ),
9620 }
9621 }
9622
9623 /// Set one task's priority and nothing else; see [`TaskSource::set_task_priority`].
9624 ///
9625 /// One field write — a select, or a clear for `none` — and no title, body, label, state
9626 /// or `Status` request. Clearing a priority an item does not hold sends nothing.
9627 async fn set_priority(
9628 &self,
9629 id: &NativeId,
9630 priority: Priority,
9631 ) -> Result<Option<Priority>, SourceError> {
9632 if self.priorities.is_none() {
9633 return Err(self.holds_no_priority());
9634 }
9635 let Some(mut item) = self
9636 .bound_item(id)
9637 .await?
9638 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9639 else {
9640 return Ok(None);
9641 };
9642 if priority == Priority::None && !item.holds_priority() {
9643 return Ok(Some(priority));
9644 }
9645 // The item's own read carries the field's definition whenever it holds a value of
9646 // it, which a clear always does; a select onto an item holding none reads the board.
9647 let board = match (item.carried_board(), item.named_board()) {
9648 (Some(board), _) => board,
9649 (None, Some(id)) if item.defines(PRIORITY_FIELD) => BoardFields {
9650 id,
9651 fields: json!({"nodes": item.fields.clone(), "pageInfo": {"hasNextPage": false}}),
9652 },
9653 _ => self.board_fields().await?,
9654 };
9655 let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? else {
9656 return Ok(Some(priority));
9657 };
9658 let (document, root, input) = match write {
9659 PriorityWrite::Select { field, option } => (
9660 graphql::UPDATE_FIELD,
9661 "updateProjectV2ItemFieldValue",
9662 json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field,"value":{"singleSelectOptionId":option}}),
9663 ),
9664 PriorityWrite::Clear { field } => (
9665 graphql::CLEAR_FIELD,
9666 "clearProjectV2ItemFieldValue",
9667 json!({"projectId":board.id.as_str(),"itemId":item.item_id,"fieldId":field}),
9668 ),
9669 };
9670 let data = self
9671 .graphql(
9672 document,
9673 json!({"input":input,"readPriority":true,"priorityName":PRIORITY_FIELD}),
9674 )
9675 .await?;
9676 let returned = data
9677 .get(root)
9678 .and_then(|value| value.get("projectV2Item"))
9679 .ok_or_else(|| SourceError::Malformed {
9680 message: "GitHub priority write returned no project item".into(),
9681 })?;
9682 if required_str(returned, "id")? != item.item_id {
9683 return Err(SourceError::Malformed {
9684 message: "GitHub priority write returned the wrong project item".into(),
9685 });
9686 }
9687 let value = returned
9688 .get("fieldValueByName")
9689 .ok_or_else(|| SourceError::Malformed {
9690 message: "GitHub priority write returned no priority read-back".into(),
9691 })?;
9692 if !value.is_null()
9693 && value.pointer("/field/name").and_then(Value::as_str) != Some(PRIORITY_FIELD)
9694 {
9695 return Err(SourceError::Malformed {
9696 message: "GitHub priority read-back is not a Priority field value".into(),
9697 });
9698 }
9699 let values = if value.is_null() {
9700 Vec::new()
9701 } else {
9702 vec![value.clone()]
9703 };
9704 item.priority = self.held_priority(&values)?;
9705 let answer = item.task()?.priority;
9706 self.remember_written(item, false)?;
9707 Ok(Some(answer))
9708 }
9709
9710 /// Replace one task's visible body and nothing else; see
9711 /// [`TaskSource::set_task_content`].
9712 ///
9713 /// One update of the body, which differs from the body GitHub holds only outside the
9714 /// metadata slot — the slot is kept byte for byte, so every caller key and every list
9715 /// this source keeps there reads back as it was. A body that would not change is not
9716 /// sent at all.
9717 async fn replace_content(
9718 &self,
9719 id: &NativeId,
9720 content: &str,
9721 ) -> Result<Option<()>, SourceError> {
9722 let Some(mut item) = self
9723 .bound_item(id)
9724 .await?
9725 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9726 else {
9727 return Ok(None);
9728 };
9729 let held = item.raw_body.clone().unwrap_or_default();
9730 // The task's `## Links` section, re-rendered from the links it holds, stays with it.
9731 let content = &onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &item.slot);
9732 let body = with_content(&held, &self.marked(content))?;
9733 // Checked before anything is sent: content ending in what this source reads as its own
9734 // metadata slot would read back as metadata rather than as the content it was.
9735 let (visible, slot) = self.visible(Some(body.clone()))?;
9736 if visible.as_deref().unwrap_or_default() != content || slot != item.slot {
9737 return Err(SourceError::Refused {
9738 message: format!(
9739 "this content ends in what source {} reads as its own metadata slot \
9740 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
9741 as content; next: remove that trailing block from the content",
9742 self.name
9743 ),
9744 });
9745 }
9746 if body != held {
9747 self.update_content(item.content_kind, &item.id, json!({"body": body}))
9748 .await?;
9749 }
9750 item.body = visible.filter(|value| !value.is_empty());
9751 item.raw_body = Some(body);
9752 item.slot = slot;
9753 self.remember_written(item, false)?;
9754 Ok(Some(()))
9755 }
9756
9757 /// Apply one targeted update to one task; see [`TaskSource::update_task`].
9758 ///
9759 /// One read of the item — which carries the board's field definitions and the issue's
9760 /// `blockedBy`, so neither is read again — and then only what differs from it: the
9761 /// `Status` option and the `Priority` field together in one request, the `blockedBy`
9762 /// additions and removals the named edges differ by, and last one `updateIssue` carrying
9763 /// the title, the body — visible content and metadata slot together — and a state change.
9764 /// So an update naming any of title, body, metadata, status and priority is one read and
9765 /// at most two writes. The body goes last so that a write refused part-way leaves it, and
9766 /// the metadata in it, as it stood. A terminal status selects its option and then closes,
9767 /// as a whole write does; an open one selects its option and then reopens. The origin
9768 /// field is never written: an update is of an item that already exists, whose origin is
9769 /// what it is.
9770 ///
9771 /// The task answered is the item as those writes left it, built from the read and what was
9772 /// sent rather than read again — the same record a later read in this run answers from.
9773 ///
9774 /// Its `version` is the one the task holds after the writes: the change token the last
9775 /// mutation's own response spells — each sent as the twin selecting the whole issue, at
9776 /// the price of the plain document — or, where that mutation shows no whole issue (several
9777 /// board fields written together, or `blockedBy` alone), the token one read right after
9778 /// the writes spells. Never the token the item was read at before them. Against GitHub
9779 /// itself that token has not settled yet (`change_token::SETTLED`), so a read gives none
9780 /// until it has, and a write held to it before then is refused rather than let through;
9781 /// once settled, a read gives exactly this token unless the task changed again.
9782 async fn targeted_update(
9783 &self,
9784 id: &NativeId,
9785 update: &TaskUpdate,
9786 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9787 Box::pin(SPELLING.scope(
9788 std::ptr::from_ref(self) as usize,
9789 self.composed_update(id, update),
9790 ))
9791 .await
9792 }
9793
9794 /// [`Self::targeted_update`], inside the scope that has its mutations answer whole.
9795 async fn composed_update(
9796 &self,
9797 id: &NativeId,
9798 update: &TaskUpdate,
9799 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
9800 // Everything this source can refuse without reading the item is refused first, in the
9801 // words a whole write of the same fields is refused with.
9802 update.consistent()?;
9803 // A duplicate close is the `cancelled` it implies where it names no status.
9804 let closing = update.duplicate_of.as_ref().map(|_| TaskUpdate {
9805 status: update.effective_status(),
9806 ..update.clone()
9807 });
9808 let update = closing.as_ref().unwrap_or(update);
9809 if update.assignees.is_some() && !self.assignees {
9810 return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
9811 }
9812 if update
9813 .title
9814 .as_deref()
9815 .is_some_and(|title| title.starts_with(DESIGN_TITLE_PREFIX))
9816 {
9817 return Err(SourceError::Refused {
9818 message: format!(
9819 "the title of this task begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
9820 spells a document, so it would read back as one rather than as a task; \
9821 retitle it",
9822 self.name
9823 ),
9824 });
9825 }
9826 if let Some(delivers) = &update.delivers {
9827 TaskRef::listed(
9828 TaskRef::DELIVERS_KEY,
9829 id,
9830 Some(&self.name),
9831 delivers.clone(),
9832 )
9833 .map_err(|message| SourceError::Refused { message })?;
9834 }
9835 if self.priorities.is_none()
9836 && update
9837 .priority
9838 .is_some_and(|priority| priority != Priority::None)
9839 {
9840 return Err(self.holds_no_priority());
9841 }
9842 let target = update
9843 .status
9844 .as_ref()
9845 .map(|status| self.resolved_target(ItemKind::Task, status.category))
9846 .transpose()?;
9847 let Some(mut item) = self
9848 .bound_item(id)
9849 .await?
9850 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
9851 else {
9852 return Ok(None);
9853 };
9854 let before = item.task()?;
9855 // The issue a duplicate close names as its survivor, refused naming both before anything
9856 // is written when it is not an issue of this board's own.
9857 let survivor = match &update.duplicate_of {
9858 Some(survivor) => Some(self.duplicate_survivor(id, &item, survivor).await?),
9859 None => None,
9860 };
9861 // The people it is to be assigned to, by node id, when they are not exactly whom it
9862 // holds: looked up — unless this process already has — and refused for a login GitHub
9863 // does not know, before anything is sent.
9864 let assignee_ids = match &update.assignees {
9865 Some(people)
9866 if item
9867 .assignees
9868 .as_deref()
9869 .is_none_or(|held| !assignees::same_people(held, people)) =>
9870 {
9871 if item.content_kind == ContentKind::DraftIssue {
9872 return Err(self.assigns_a_draft());
9873 }
9874 self.resolve_people(people).await?;
9875 Some(self.people_ids(people, &item.written_name())?)
9876 }
9877 _ => None,
9878 };
9879
9880 let mut status_move = None;
9881 if let (Some(status), Some(target)) = (&update.status, target) {
9882 let board = self.status_board(&item).await?;
9883 let (field, option, name) = self
9884 .column_for(&board.fields, ItemKind::Task, status.category, &target)?
9885 .ok_or_else(|| SourceError::Malformed {
9886 message: format!(
9887 "status {} of source {} names no board Status option",
9888 category_name(status.category),
9889 self.name
9890 ),
9891 })?;
9892 let terminal = matches!(target, StatusTarget::Terminal(_, _));
9893 if terminal && item.content_kind == ContentKind::DraftIssue {
9894 return Err(self.closes_a_draft(status.category));
9895 }
9896 // A duplicate close lands closed as `DUPLICATE`, which reads `cancelled` as not
9897 // planned does; an issue already closed as one is not closed again.
9898 let reason = match (&target, &survivor) {
9899 (StatusTarget::Terminal(_, _), Some(_)) => Some(DUPLICATE_REASON),
9900 (StatusTarget::Terminal(_, reason), None) => Some(reason.reason()),
9901 _ => None,
9902 };
9903 let landed = self
9904 .statuses
9905 .status(ItemKind::Task, Some(&name), terminal, reason);
9906 let option_moves = item
9907 .option
9908 .as_deref()
9909 .is_none_or(|held| !held.eq_ignore_ascii_case(&name));
9910 let state_moves = item.content_kind == ContentKind::Issue
9911 && (item.closed != terminal
9912 || (terminal && item.status != landed)
9913 || (survivor.is_some() && item.reason.as_deref() != Some(DUPLICATE_REASON)));
9914 if let Some(moves) = Moves::of(option_moves, state_moves) {
9915 status_move = Some(StatusMove {
9916 board: board.id,
9917 field,
9918 option,
9919 name,
9920 target,
9921 landed,
9922 moves,
9923 });
9924 }
9925 }
9926
9927 let mut priority_move = None;
9928 if let Some(priority) = update.priority
9929 && self.priorities.is_some()
9930 && item.priority != HeldPriority::Read(priority)
9931 {
9932 let board = match (item.carried_board(), item.named_board()) {
9933 (Some(board), _) => board,
9934 (None, Some(board)) if item.defines(PRIORITY_FIELD) => BoardFields {
9935 id: board,
9936 fields: json!({"nodes": item.fields, "pageInfo": {"hasNextPage": false}}),
9937 },
9938 _ => self.board_fields().await?,
9939 };
9940 if let Some(write) = self.priority_write(&board.fields, Some(&item), priority)? {
9941 priority_move = Some((board.id, write, priority));
9942 }
9943 }
9944
9945 // The metadata keys this update names that a board text field projects, and what
9946 // that does to those fields — refused, as a whole write refuses it, before anything
9947 // is sent.
9948 let touched: Vec<&str> = update
9949 .metadata_set
9950 .keys()
9951 .chain(update.metadata_remove.iter())
9952 .map(MetadataKey::as_str)
9953 .collect();
9954 let mut projection_move = None;
9955 if self
9956 .metadata_fields
9957 .iter()
9958 .any(|projection| touched.contains(&&*projection.key))
9959 {
9960 let mut metadata = item.slot.clone();
9961 for (key, value) in &update.metadata_set {
9962 metadata.insert(key.as_str().to_owned(), value.clone());
9963 }
9964 for key in &update.metadata_remove {
9965 metadata.remove(key.as_str());
9966 }
9967 let board = self.projection_board(&item).await?;
9968 let (writes, projected) = self.projection_writes(
9969 &board.fields,
9970 Some(&item.projected),
9971 &metadata,
9972 Some(&touched),
9973 )?;
9974 projection_move = Some((board.id, writes, projected));
9975 }
9976
9977 // Resolved before the body is composed, because a far end `blockedBy` cannot name is
9978 // recorded in the slot, and the slot travels in the one body update below.
9979 let edges = match &update.depends_on {
9980 Some(edges) => Some(
9981 self.partition_edges(
9982 BoardKind::Work(ItemKind::Task),
9983 item.content_kind,
9984 item.blocked_by.as_deref(),
9985 edges,
9986 )
9987 .await?,
9988 ),
9989 None => None,
9990 };
9991
9992 // A record primed from what a producer wrote holds no body anybody read, so an update
9993 // changing the body reads it first: by the `Status` write's own answer when the update
9994 // moves the option — the mutation answering with the issue whole — and otherwise by
9995 // reading the issue. The body is then composed against what GitHub holds now.
9996 let mut option_selected = false;
9997 // The mark stays until a read lands, so an update that writes no body, or one whose
9998 // read fails, leaves the next update of it to read the body too.
9999 if (update.content.is_some()
10000 || !update.metadata_set.is_empty()
10001 || !update.metadata_remove.is_empty()
10002 || update.delivers.is_some()
10003 || update.repositories.is_some()
10004 || edges.is_some())
10005 && self.is_unread(id)
10006 {
10007 let live = match status_move.as_ref().filter(|moving| moving.moves.option()) {
10008 Some(moving) => {
10009 option_selected = true;
10010 Some(
10011 self.select_reading_body(
10012 moving.board.as_str(),
10013 &item.item_id,
10014 &moving.field,
10015 &moving.option,
10016 )
10017 .await?,
10018 )
10019 }
10020 None => {
10021 self.forget(id)?;
10022 let Some(read) = self.item_by_id(id).await? else {
10023 return Ok(None);
10024 };
10025 read.raw_body
10026 }
10027 };
10028 let (visible, read_slot) = self.visible(live.clone())?;
10029 self.mark_read(id);
10030 item.raw_body = live;
10031 item.body = visible;
10032 item.slot = read_slot;
10033 }
10034
10035 let mut slot = item.slot.clone();
10036 for (key, value) in &update.metadata_set {
10037 slot.insert(key.as_str().to_owned(), value.clone());
10038 }
10039 for key in &update.metadata_remove {
10040 slot.remove(key.as_str());
10041 }
10042 if let Some(delivers) = &update.delivers {
10043 set_task_list(&mut slot, TaskRef::DELIVERS_KEY, delivers);
10044 }
10045 // The list a whole write records, by the same rule: none when it is exactly the issue's
10046 // own repository, or empty with no issue repository to derive, and otherwise the list.
10047 if let Some(repositories) = &update.repositories {
10048 let derivable = item
10049 .own_repository
10050 .as_ref()
10051 .map_or(repositories.is_empty(), |own| {
10052 repositories.as_slice() == std::slice::from_ref(own)
10053 });
10054 if derivable {
10055 slot.remove(Repository::METADATA_KEY);
10056 } else {
10057 slot.insert(
10058 Repository::METADATA_KEY.to_owned(),
10059 Value::Array(
10060 repositories
10061 .iter()
10062 .map(|repository| Value::String(repository.as_str().to_owned()))
10063 .collect(),
10064 ),
10065 );
10066 }
10067 }
10068 if let Some((_, recorded)) = &edges {
10069 record_edges(&mut slot, recorded);
10070 }
10071 let held = item.raw_body.clone().unwrap_or_default();
10072 // A content write keeps the task's `## Links` section, re-rendered from the links the
10073 // slot holds once written.
10074 let relinked = update
10075 .content
10076 .as_deref()
10077 .map(|content| onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot));
10078 let content = match &relinked {
10079 Some(content) => with_content(&held, &self.marked(content))?,
10080 None => held.clone(),
10081 };
10082 // A slot holding what it held is kept byte for byte, compared as JSON rather than as
10083 // the body's bytes, as a metadata write compares it: a slot a person spelled with
10084 // other whitespace would otherwise be re-encoded, which is a write nobody asked for.
10085 let body = if slot == item.slot {
10086 content
10087 } else {
10088 with_slot(&content, &slot)?
10089 };
10090 // Checked before anything is sent, as a content write checks it: content ending in
10091 // what this source reads as its own slot would read back as metadata.
10092 let (visible, read) = self.visible(Some(body.clone()))?;
10093 let wanted = relinked.as_deref().or(item.body.as_deref());
10094 if visible.as_deref().unwrap_or_default() != wanted.unwrap_or_default() || read != slot {
10095 return Err(SourceError::Refused {
10096 message: format!(
10097 "this content ends in what source {} reads as its own metadata slot \
10098 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10099 as content; next: remove that trailing block from the content",
10100 self.name
10101 ),
10102 });
10103 }
10104 let recorded_moves =
10105 slot.get(DependencyEdge::RECORDED_KEY) != item.slot.get(DependencyEdge::RECORDED_KEY);
10106
10107 // One `updateIssue` carries all three, because every mutation spends the secondary
10108 // limiter and the title, body and state are one mutation's inputs.
10109 let mut fields = serde_json::Map::new();
10110 if let Some(title) = update.title.as_ref().filter(|title| **title != item.title) {
10111 fields.insert("title".to_owned(), json!(title));
10112 }
10113 if body != held {
10114 fields.insert("body".to_owned(), json!(body));
10115 }
10116 // A duplicate's closure is `closeIssue`'s, sent after this update: `stateInput` names
10117 // no survivor.
10118 if let Some(moving) = status_move
10119 .as_ref()
10120 .filter(|moving| moving.moves.state() && survivor.is_none())
10121 {
10122 fields.insert("stateInput".to_owned(), state_input(Some(&moving.target)));
10123 }
10124 let closes_as_duplicate = status_move
10125 .as_ref()
10126 .is_some_and(|moving| moving.moves.state())
10127 && survivor.is_some();
10128 // The assignees ride the same mutation: replacing whoever the issue holds, in the one
10129 // `updateIssue` this update already ends with — or as the one it sends for them alone.
10130 if let Some(ids) = &assignee_ids {
10131 fields.insert("assigneeIds".to_owned(), json!(ids));
10132 }
10133 // **The body is written last, and that is the guarantee a refusal part-way keeps.**
10134 // GitHub runs no two requests as one, and runs one document's mutation fields in order
10135 // without undoing an earlier field when a later one fails — so a body written before a
10136 // board field the board then refused would be left changed. Written after every other
10137 // write has landed, a refusal anywhere leaves the item's body, and every metadata key
10138 // it carries, exactly as they stood. So the `Status` option and the `Priority` field go
10139 // first, together in one request — a terminal option selected before the issue
10140 // closes, as a whole write does — then the `blockedBy` difference, then the body.
10141 let mut board_writes: Vec<(&BoardId, (String, Value))> = Vec::new();
10142 let mut clears: Vec<(&BoardId, &str)> = Vec::new();
10143 if let Some(moving) = status_move
10144 .as_ref()
10145 .filter(|moving| moving.moves.option() && !option_selected)
10146 {
10147 board_writes.push((
10148 &moving.board,
10149 (
10150 moving.field.clone(),
10151 json!({"singleSelectOptionId": moving.option}),
10152 ),
10153 ));
10154 }
10155 match &priority_move {
10156 Some((board, PriorityWrite::Select { field, option }, _)) => board_writes.push((
10157 board,
10158 (field.clone(), json!({"singleSelectOptionId": option})),
10159 )),
10160 Some((board, PriorityWrite::Clear { field }, _)) => clears.push((board, field)),
10161 None => {}
10162 }
10163 if let Some((board, writes, _)) = &projection_move {
10164 for write in writes {
10165 let (mut values, mut cleared) = (Vec::new(), Vec::new());
10166 write.join(&mut values, &mut cleared);
10167 board_writes.extend(values.into_iter().map(|value| (board, value)));
10168 clears.extend(cleared.into_iter().map(|field| (board, field)));
10169 }
10170 }
10171 let mut boards: Vec<&BoardId> = board_writes.iter().map(|(board, _)| *board).collect();
10172 boards.extend(clears.iter().map(|(board, _)| *board));
10173 boards.dedup_by(|one, other| one.as_str() == other.as_str());
10174 for board in boards {
10175 let writes = board_writes
10176 .iter()
10177 .filter(|(on, _)| on.as_str() == board.as_str())
10178 .map(|(_, write)| write.clone())
10179 .collect::<Vec<_>>();
10180 let cleared = clears
10181 .iter()
10182 .filter(|(on, _)| on.as_str() == board.as_str())
10183 .map(|(_, field)| *field)
10184 .collect::<Vec<_>>();
10185 self.set_item_fields(board.as_str(), &item.item_id, &writes, &cleared)
10186 .await?;
10187 }
10188 // Whether anything is sent: what the version answered has to come after.
10189 let sends = option_selected
10190 || !board_writes.is_empty()
10191 || !clears.is_empty()
10192 || !fields.is_empty()
10193 || closes_as_duplicate;
10194 let mut blocked_by_moved = false;
10195 if let Some((native, _)) = &edges
10196 && item.content_kind == ContentKind::Issue
10197 {
10198 blocked_by_moved = self
10199 .reconcile_blocked_by(
10200 &item.id,
10201 native,
10202 Issue::Existing(item.blocked_by.as_deref()),
10203 )
10204 .await?;
10205 }
10206 if !fields.is_empty() {
10207 self.update_content(item.content_kind, &item.id, Value::Object(fields))
10208 .await?;
10209 }
10210 // Last, the duplicate's closure, with the survivor GitHub links it to: the card already
10211 // shows the `cancelled` option, so a refusal here leaves an open issue at a terminal
10212 // card, which the next write of the same status closes.
10213 if let (true, Some(survivor)) = (closes_as_duplicate, &survivor) {
10214 self.graphql(
10215 graphql::CLOSE_ISSUE,
10216 json!({"input":{"issueId":item.id.0,"stateReason":DUPLICATE_REASON,
10217 "duplicateIssueId":survivor.0}}),
10218 )
10219 .await?;
10220 }
10221
10222 // The `blockedBy` this item was read with is what the write just changed, so it is no
10223 // answer any more: a later write in this command would reconcile against it — re-adding
10224 // what it kept and never removing what it dropped — and a forward-edge read would
10225 // answer with it. Left unknown, each asks GitHub instead.
10226 if blocked_by_moved {
10227 item.blocked_by = None;
10228 }
10229 if let Some(title) = &update.title {
10230 item.title.clone_from(title);
10231 }
10232 item.body = visible.filter(|value| !value.is_empty());
10233 item.raw_body = (!body.is_empty() || item.raw_body.is_some()).then_some(body);
10234 item.slot = slot;
10235 if let Some(delivers) = &update.delivers {
10236 item.delivers.clone_from(delivers);
10237 }
10238 if let Some(repositories) = &update.repositories {
10239 item.repositories.clone_from(repositories);
10240 }
10241 if let Some(moving) = status_move {
10242 item.closed = matches!(moving.target, StatusTarget::Terminal(_, _))
10243 && item.content_kind == ContentKind::Issue;
10244 if moving.moves.state() {
10245 item.reason = match &moving.target {
10246 StatusTarget::Terminal(_, _) if survivor.is_some() => {
10247 Some(DUPLICATE_REASON.to_owned())
10248 }
10249 StatusTarget::Terminal(_, reason) => Some(reason.reason().to_owned()),
10250 _ => None,
10251 };
10252 }
10253 item.status = moving.landed;
10254 item.option = Some(moving.name);
10255 }
10256 if let Some((_, _, priority)) = priority_move {
10257 item.priority = HeldPriority::Read(priority);
10258 }
10259 if let Some((_, _, projected)) = projection_move {
10260 item.projected = projected;
10261 }
10262 // Only a write that assigned anyone moves whom the item holds, and they are who GitHub
10263 // says they are; one naming the people it already holds leaves its read as it was.
10264 if let (Some(people), Some(_)) = (&update.assignees, &assignee_ids) {
10265 item.assignees = Some(self.spelled(people));
10266 }
10267 let mut task = item.task()?;
10268 let mut written = update.changed(&before, &task);
10269 if blocked_by_moved || recorded_moves {
10270 written.insert(UpdatedField::DependsOn);
10271 }
10272 if closes_as_duplicate {
10273 written.insert(UpdatedField::DuplicateOf);
10274 }
10275 if sends || blocked_by_moved {
10276 // The token the item was read at is not the one it holds now. A batch of updates
10277 // holding this one's writes back reads every task it wrote once they are sent.
10278 task.version = if self.holding_writes_of(id) {
10279 None
10280 } else {
10281 self.version_after_write(id).await
10282 };
10283 }
10284 self.remember_written(item, false)?;
10285 Ok(Some(TaskUpdateOutcome {
10286 task,
10287 written,
10288 delivers_before: before.delivers,
10289 }))
10290 }
10291
10292 /// The issue `survivor` names, the one a duplicate close of `id` links GitHub's closure to:
10293 /// refused, naming both, when it is not an issue of this board's own source — a task of
10294 /// another source, a board draft, an item this board does not hold — or is `id` itself.
10295 async fn duplicate_survivor(
10296 &self,
10297 id: &NativeId,
10298 item: &Resolved,
10299 survivor: &TaskRef,
10300 ) -> Result<NativeId, SourceError> {
10301 let refused = |why: String| SourceError::Refused {
10302 message: format!(
10303 "{} cannot be closed as a duplicate of {survivor}: {why}; next: name an issue of \
10304 source {} as the survivor",
10305 TaskRef::qualified(&self.name, id),
10306 self.name
10307 ),
10308 };
10309 let (source, native) = survivor.parts(self.name.as_str());
10310 if source != self.name.as_str() {
10311 return Err(refused(format!(
10312 "it is not a GitHub issue of source {}, which GitHub links a duplicate to",
10313 self.name
10314 )));
10315 }
10316 let native = NativeId(native.to_owned());
10317 if native == *id || native == item.id {
10318 return Err(refused("a task cannot be a duplicate of itself".to_owned()));
10319 }
10320 match self.bound_item(&native).await? {
10321 Some(held) if held.content_kind == ContentKind::Issue => Ok(held.id),
10322 Some(_) => Err(refused(
10323 "it is a board draft, which is no issue GitHub can link a duplicate to".to_owned(),
10324 )),
10325 None => Err(refused(format!("source {} holds no such issue", self.name))),
10326 }
10327 }
10328
10329 /// The change token the task `id` holds after the writes a targeted update just sent: the
10330 /// one the last mutation's own response showed, or, where none showed the whole issue, the
10331 /// one a read made now spells. `None` when that read cannot say — never the token the
10332 /// task was read at before the writes.
10333 async fn version_after_write(&self, id: &NativeId) -> Option<String> {
10334 // A response that showed the issue whole answers, a token or none: a read made now
10335 // would read the same parts.
10336 if let Some(answered) = self.written_answer(id) {
10337 return answered;
10338 }
10339 // An item this command created is answered from its own record, not read.
10340 if self.created().ok()?.iter().any(|own| own.id == *id) {
10341 return None;
10342 }
10343 let read = self.item_by_id(id).await.ok()??;
10344 let token = read.written_version()?;
10345 self.remember_written_token(&read, token.clone());
10346 Some(token)
10347 }
10348
10349 /// Replace one issue's visible body and its [`MetadataKey::TEMPLATE_KEY`] slot entry
10350 /// together, and nothing else; see [`TaskSource::set_task_rendering`].
10351 ///
10352 /// One update of the body: the content outside the slot, and inside it that one entry,
10353 /// every other entry kept as it was. This source keeps no template answers — an issue has
10354 /// no room beside itself that is not its body, and answers written there would duplicate
10355 /// what the content already says and count against GitHub's body limit — so `answers`
10356 /// reaches nothing here. A body that would not change is not sent at all.
10357 async fn replace_rendering(
10358 &self,
10359 id: &NativeId,
10360 kind: BoardKind,
10361 content: &str,
10362 provenance: &Value,
10363 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
10364 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
10365 let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
10366 return Ok(None);
10367 };
10368 let held = item.raw_body.clone().unwrap_or_default();
10369 let mut slot = item.slot.clone();
10370 slot.insert(MetadataKey::TEMPLATE_KEY.to_owned(), provenance.clone());
10371 let rewritten;
10372 let content = if let Some(assets) = assets {
10373 let uploads = self
10374 .upload_assets(item.own_repository.as_ref(), assets)
10375 .await?;
10376 rewritten =
10377 onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads);
10378 rewritten.as_str()
10379 } else {
10380 content
10381 };
10382 let relinked = onetaskgraph_plugin_api::relinked(content, item.body.as_deref(), &slot);
10383 let content = relinked.as_str();
10384 let body = with_slot(&with_content(&held, &self.marked(content))?, &slot)?;
10385 // Checked before anything is sent, as a content write checks it.
10386 let (visible, read) = self.visible(Some(body.clone()))?;
10387 if visible.as_deref().unwrap_or_default() != content || read != slot {
10388 return Err(SourceError::Refused {
10389 message: format!(
10390 "this content ends in what source {} reads as its own metadata slot \
10391 ({METADATA_OPEN:?}), so part of it would read back as metadata rather than \
10392 as content; next: remove that trailing block from the template",
10393 self.name
10394 ),
10395 });
10396 }
10397 if body != held {
10398 self.update_content(item.content_kind, &item.id, json!({"body": body}))
10399 .await?;
10400 }
10401 item.body = visible.filter(|value| !value.is_empty());
10402 item.raw_body = Some(body);
10403 // The content as a read answers it: without the `## Links` section of a linked task.
10404 let answered = onetaskgraph_plugin_api::read_content(Some(content.to_owned()), &read);
10405 item.slot = read;
10406 self.remember_written(item, false)?;
10407 Ok(Some(onetaskgraph_plugin_api::AssetsWritten {
10408 id: id.clone(),
10409 content: answered,
10410 }))
10411 }
10412
10413 async fn set_item_field(
10414 &self,
10415 board_id: &str,
10416 item_id: &str,
10417 field_id: &str,
10418 value: Value,
10419 ) -> Result<(), SourceError> {
10420 let data = self
10421 .graphql(
10422 graphql::UPDATE_FIELD,
10423 json!({"input":{
10424 "projectId":board_id,"itemId":item_id,"fieldId":field_id,"value":value
10425 },"readPriority":false,"priorityName":PRIORITY_FIELD}),
10426 )
10427 .await?;
10428 field_update_item(&data, item_id).map(|_| ())
10429 }
10430
10431 /// GitHub accepts one value per field mutation; aliases combine those mutations in
10432 /// one request — writes in the order given, then clears. A lone write is
10433 /// [`graphql::UPDATE_FIELD`] and a lone clear [`graphql::CLEAR_FIELD`]; more than one
10434 /// request's slots hold go in further requests of the same document, in order. Every
10435 /// returned item id is checked, including optional aliases.
10436 async fn set_item_fields(
10437 &self,
10438 board: &str,
10439 item: &str,
10440 fields: &[(String, Value)],
10441 clears: &[&str],
10442 ) -> Result<(), SourceError> {
10443 if !(fields.is_empty() && clears.is_empty())
10444 && self.hold_fields(board, item, fields, clears)?
10445 {
10446 return Ok(());
10447 }
10448 match (fields, clears) {
10449 ([], []) => return Ok(()),
10450 ([(field, value)], []) => {
10451 return self.set_item_field(board, item, field, value.clone()).await;
10452 }
10453 ([], [field]) => {
10454 return self
10455 .write_priority(
10456 board,
10457 item,
10458 &PriorityWrite::Clear {
10459 field: (*field).to_owned(),
10460 },
10461 )
10462 .await;
10463 }
10464 _ => {}
10465 }
10466 // Any field of the request stands in for an input a slot leaves out, which GitHub
10467 // still requires to be well formed although it never runs it.
10468 let filler = fields
10469 .first()
10470 .map_or_else(|| clears[0], |(field, _)| field.as_str());
10471 let mut writes = fields.iter();
10472 let mut cleared = clears.iter();
10473 loop {
10474 let batch: Vec<&(String, Value)> =
10475 writes.by_ref().take(FIELD_WRITE_SLOTS.len()).collect();
10476 let batch_clears: Vec<&&str> = cleared.by_ref().take(FIELD_CLEAR_SLOTS.len()).collect();
10477 if batch.is_empty() && batch_clears.is_empty() {
10478 return Ok(());
10479 }
10480 let mut variables = serde_json::Map::new();
10481 for (index, slot) in FIELD_WRITE_SLOTS.iter().enumerate() {
10482 let input = match batch.get(index) {
10483 Some((field, value)) => {
10484 json!({"projectId":board,"itemId":item,"fieldId":field,"value":value})
10485 }
10486 None => json!({"projectId":board,"itemId":item,"fieldId":filler,
10487 "value":{"text":""}}),
10488 };
10489 variables.insert(slot.variable.to_owned(), input);
10490 variables.insert(slot.include.to_owned(), json!(index < batch.len()));
10491 }
10492 for (index, slot) in FIELD_CLEAR_SLOTS.iter().enumerate() {
10493 let field = batch_clears.get(index).map_or(filler, |field| **field);
10494 variables.insert(
10495 slot.variable.to_owned(),
10496 json!({"projectId":board,"itemId":item,"fieldId":field}),
10497 );
10498 variables.insert(slot.include.to_owned(), json!(index < batch_clears.len()));
10499 }
10500 let data = self
10501 .graphql(graphql::UPDATE_FIELDS, Value::Object(variables))
10502 .await?;
10503 let sent = FIELD_WRITE_SLOTS[..batch.len()]
10504 .iter()
10505 .chain(&FIELD_CLEAR_SLOTS[..batch_clears.len()]);
10506 for slot in sent {
10507 let alias = slot.alias;
10508 let returned = data
10509 .get(alias)
10510 .and_then(|value| value.get("projectV2Item"))
10511 .ok_or_else(|| SourceError::Malformed {
10512 message: format!("GitHub field update {alias} returned no project item"),
10513 })?;
10514 if required_str(returned, "id")? != item {
10515 return Err(SourceError::Malformed {
10516 message: format!(
10517 "GitHub field update {alias} returned the wrong project item"
10518 ),
10519 });
10520 }
10521 }
10522 }
10523 }
10524
10525 async fn native_dependency_ids(&self, id: &NativeId) -> Result<Vec<String>, SourceError> {
10526 let mut after: Option<String> = None;
10527 let mut ids = Vec::new();
10528 loop {
10529 let data = self
10530 .graphql(
10531 graphql::ISSUE_DEPENDENCIES,
10532 json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after}),
10533 )
10534 .await?;
10535 let connection =
10536 data.pointer("/node/blockedBy")
10537 .ok_or_else(|| SourceError::Malformed {
10538 message: "GitHub dependency response has no blockedBy connection".into(),
10539 })?;
10540 ids.extend(
10541 connection
10542 .get("nodes")
10543 .and_then(Value::as_array)
10544 .ok_or_else(|| SourceError::Malformed {
10545 message: "GitHub dependency response nodes is not an array".into(),
10546 })?
10547 .iter()
10548 .map(|value| required_str(value, "id").map(str::to_owned))
10549 .collect::<Result<Vec<_>, _>>()?,
10550 );
10551 let next = next_cursor(connection)?;
10552 if let Some(next) = &next {
10553 validate_cursor_progress(after.as_deref(), &next.0)?;
10554 }
10555 after = next.map(|cursor| cursor.0);
10556 if after.is_none() {
10557 return Ok(ids);
10558 }
10559 }
10560 }
10561
10562 async fn dependencies(
10563 &self,
10564 id: &NativeId,
10565 near_kind: ItemKind,
10566 direction: Direction,
10567 page: &PageRequest,
10568 ) -> Result<Page<DependencyEdge>, SourceError> {
10569 validate_page(page)?;
10570 let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
10571 let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
10572 let recorded = recorded_offset(cursor, direction)?;
10573 // What this issue is blocked by, when a read of it by its own id in this command
10574 // already carried the whole connection — a copy reads the item it writes before it
10575 // reads its edges — and the page asked for is the whole of it, or the recorded tail
10576 // after it. Answered from that read, in the shape the dependency read answers in;
10577 // anything else is asked of GitHub.
10578 let carried = match direction {
10579 Direction::DependsOn => self
10580 .resolved_cache()?
10581 .get(id)
10582 .filter(|item| item.content_kind == ContentKind::Issue)
10583 .and_then(|item| Some((item.blocked_by.clone()?, item.raw_body.clone()))),
10584 Direction::DependedOnBy => None,
10585 }
10586 .filter(|(nodes, _)| recorded.is_some() || (cursor.is_none() && nodes.len() <= limit));
10587 // Asked for even in the recorded phase, whose page reads nothing from the
10588 // connection: `__typename` is what says whether this item has a native
10589 // relationship at all, and that is what decides which far ends the reserved key is
10590 // allowed to hold.
10591 let data = match carried {
10592 Some((nodes, body)) => json!({"node":{"__typename":"Issue","body":body,
10593 "blockedBy":{"nodes":nodes,"pageInfo":{"hasNextPage":false,"endCursor":null}}}}),
10594 None => {
10595 let after = if recorded.is_some() { None } else { cursor };
10596 let first = page.limit.min(MAX_PAGE_SIZE);
10597 match direction {
10598 Direction::DependsOn => {
10599 self.graphql(
10600 graphql::ISSUE_DEPENDS_ON,
10601 json!({"id":id.0,"first":first,"after":after,"owner":self.owner,
10602 "number":self.project_number,
10603 "boardItems":BOARD_ITEMS_PAGE_SIZE}),
10604 )
10605 .await?
10606 }
10607 Direction::DependedOnBy => {
10608 self.graphql(
10609 graphql::ISSUE_DEPENDED_ON_BY,
10610 json!({"id":id.0,"first":first,"after":after}),
10611 )
10612 .await?
10613 }
10614 }
10615 }
10616 };
10617 let draft_slot = draft_slot(&data, id, self.project_number)?;
10618 let node =
10619 data.get("node")
10620 .filter(|v| !v.is_null())
10621 .ok_or_else(|| SourceError::Refused {
10622 message: format!(
10623 "GitHub item {} was not found or does not support dependencies",
10624 id.0
10625 ),
10626 })?;
10627 let connection_name = match direction {
10628 Direction::DependsOn => "blockedBy",
10629 Direction::DependedOnBy => "blocking",
10630 };
10631 // A draft has neither `blockedBy` nor `blocking`, so nothing it depends on can be
10632 // named natively and the reserved key may hold any far end. An issue's connections
10633 // hold issues, and this source reads them at the near item's own level.
10634 let natively_names = (required_str(node, "__typename")? == "Issue").then_some(near_kind);
10635 if let Some(offset) = recorded {
10636 return Ok(recorded_page(
10637 self.recorded_edges(
10638 id,
10639 near_kind,
10640 direction,
10641 natively_names,
10642 node,
10643 draft_slot.as_ref(),
10644 )
10645 .await?,
10646 offset,
10647 limit,
10648 ));
10649 }
10650 if natively_names.is_none() {
10651 return Ok(recorded_page(
10652 self.recorded_edges(
10653 id,
10654 near_kind,
10655 direction,
10656 natively_names,
10657 node,
10658 draft_slot.as_ref(),
10659 )
10660 .await?,
10661 0,
10662 limit,
10663 ));
10664 }
10665 let connection = node
10666 .get(connection_name)
10667 .ok_or_else(|| SourceError::Malformed {
10668 message: "GitHub dependency response is missing its connection".into(),
10669 })?;
10670 let nodes = connection
10671 .get("nodes")
10672 .and_then(Value::as_array)
10673 .ok_or_else(|| SourceError::Malformed {
10674 message: "GitHub dependency response nodes is not an array".into(),
10675 })?;
10676 // `from` depends on `to`, always. GitHub spells the same relationship from either
10677 // end — `blockedBy` lists what this item waits on, `blocking` lists what waits on
10678 // it — so the near item is `from` in one direction and `to` in the other.
10679 let items = nodes
10680 .iter()
10681 .map(|value| {
10682 let related = NativeId(required_str(value, "id")?.into());
10683 let related_kind = related_kind(value, self.sub_issues)?;
10684 let (from, to) = match direction {
10685 Direction::DependsOn => (
10686 DependencyEndpoint::from_native(id.clone(), near_kind),
10687 DependencyEndpoint::from_native(related, related_kind),
10688 ),
10689 Direction::DependedOnBy => (
10690 DependencyEndpoint::from_native(related, related_kind),
10691 DependencyEndpoint::from_native(id.clone(), near_kind),
10692 ),
10693 };
10694 Ok(DependencyEdge {
10695 from,
10696 to,
10697 kind: DependencyKind::Blocks,
10698 })
10699 })
10700 .collect::<Result<Vec<_>, SourceError>>()?;
10701 let mut next = next_cursor(connection)?;
10702 if let Some(next) = &next {
10703 validate_cursor_progress(cursor, &next.0)?;
10704 }
10705 // The recorded far ends ride on the last page of `blockedBy`, whose answer carried the
10706 // body they are recorded in, as far as the page has room — so they cost no request of
10707 // their own — and only what does not fit is resumed by a cursor.
10708 let mut items = items;
10709 if next.is_none() {
10710 let recorded = self
10711 .recorded_edges(
10712 id,
10713 near_kind,
10714 direction,
10715 natively_names,
10716 node,
10717 draft_slot.as_ref(),
10718 )
10719 .await?;
10720 let room = limit.saturating_sub(items.len());
10721 let total = recorded.len();
10722 items.extend(recorded.into_iter().take(room));
10723 if total > room {
10724 next = Some(Cursor(format!("{RECORDED_CURSOR}{room}")));
10725 }
10726 }
10727 Ok(Page { items, next })
10728 }
10729
10730 /// The edges this item records under [`DependencyEdge::RECORDED_KEY`], which is where
10731 /// a far end in another source has to live: no GitHub issue relationship can name one.
10732 ///
10733 /// Only forwards. The reverse of a recorded edge is derived from the far end, and this
10734 /// source never writes one down.
10735 ///
10736 /// The metadata lives in the item's own body slot, and `node` is the dependency read's
10737 /// own answer, which carries an issue's body — so an issue's recorded edges cost no
10738 /// request beyond the read already made, and reading the board for them would be a
10739 /// walk of every item for one field of one. A draft has no body in that answer, because
10740 /// a draft is not an issue, so a draft's are read off its own read by id — never off a
10741 /// listing of the board, which can be behind on the very item asked about.
10742 async fn recorded_edges(
10743 &self,
10744 id: &NativeId,
10745 near_kind: ItemKind,
10746 direction: Direction,
10747 natively_names: Option<ItemKind>,
10748 node: &Value,
10749 draft_slot: Option<&Option<BTreeMap<String, Value>>>,
10750 ) -> Result<Vec<DependencyEdge>, SourceError> {
10751 if direction != Direction::DependsOn {
10752 return Ok(Vec::new());
10753 }
10754 let slot = match (node.get("body"), draft_slot) {
10755 (Some(body), _) if natively_names.is_some() => {
10756 metadata_body(body.as_str().map(str::to_owned))?.1
10757 }
10758 // A draft the dependency read itself answered: this board's, or none of its.
10759 (_, Some(Some(slot))) => slot.clone(),
10760 (_, Some(None)) => return Ok(Vec::new()),
10761 _ => {
10762 let Some(item) = self.bound_item(id).await? else {
10763 return Ok(Vec::new());
10764 };
10765 item.slot
10766 }
10767 };
10768 DependencyEdge::recorded(&slot, id, near_kind, &self.name, natively_names)
10769 .map_err(|message| SourceError::Malformed { message })
10770 }
10771
10772 /// Why `creation_owners` refuses a create filed in `target`, or `None` when it allows it —
10773 /// every create when the list is empty.
10774 fn owner_refusal(&self, target: &RepositoryTarget) -> Option<String> {
10775 if self.creation_owners.is_empty()
10776 || self
10777 .creation_owners
10778 .iter()
10779 .any(|owner| owner.eq_ignore_ascii_case(&target.owner))
10780 {
10781 return None;
10782 }
10783 Some(format!(
10784 "source {} would create the issue in repository {}, owned by {}, and its \
10785 creation_owners allows only repositories of {}",
10786 self.name,
10787 target.slug(),
10788 target.owner,
10789 self.creation_owners.join(", ")
10790 ))
10791 }
10792
10793 fn configured_repository(&self) -> Result<&RepositoryTarget, SourceError> {
10794 self.repository
10795 .as_ref()
10796 .ok_or_else(|| SourceError::Refused {
10797 message: format!(
10798 "source {} has no repository configured, and a GitHub Projects board has no \
10799 repository of its own to create an issue in; set repository: owner/name on \
10800 this source",
10801 self.name
10802 ),
10803 })
10804 }
10805
10806 /// The repository one new issue is created in, under the rule [`RepositoryTarget`]
10807 /// states.
10808 ///
10809 /// The fallback is demanded first, whichever arm answers: a write without a configured
10810 /// repository is refused naming the field exactly as it was before the rule existed,
10811 /// so a source that could not write before cannot write now, rather than writing for
10812 /// the one item whose own field happens to decide it.
10813 ///
10814 /// Everything this refuses is refused before `createIssue`, so a refusal leaves no
10815 /// issue behind: an entry that is not a repository on [`RepositoryTarget::HOST`], an
10816 /// entry owned by someone other than the owner of the parent issue's repository —
10817 /// GitHub accepts a sub-issue from another repository of the same owner and from no
10818 /// other, so `addSubIssue` would refuse it after the issue existed — a parent the
10819 /// board does not hold, and a parent that is a draft, which GitHub gives no sub-issues,
10820 /// both of which `addSubIssue` would likewise refuse too late. Whether the entry exists
10821 /// and is visible to the token is checked where its node id is resolved, still before
10822 /// `createIssue`. The parent is read by its own id through [`Self::item_by_id`] — never
10823 /// looked up in a listing of the board, which can be minutes behind an issue its own
10824 /// `projectItems` already places on it — and that read answers first from this process's
10825 /// own record, so a project created moments ago in this command answers though GitHub
10826 /// has not caught up.
10827 async fn creation_target(
10828 &self,
10829 incoming: &Incoming<'_>,
10830 ) -> Result<RepositoryTarget, SourceError> {
10831 let what = format!(
10832 "{} {:?}",
10833 incoming.written.kind().describes(),
10834 incoming.title
10835 );
10836 let target = self
10837 .creation_rule(incoming.repositories, incoming.parent, &what)
10838 .await?;
10839 // The engine asks `creation_refusal` before anything of a copy is written; this holds
10840 // every other create to the same restriction, before `createIssue`.
10841 match self.owner_refusal(&target) {
10842 Some(message) => Err(SourceError::Refused { message }),
10843 None => Ok(target),
10844 }
10845 }
10846
10847 /// [`Self::creation_target`]'s rule over what it reads of the item — its `repositories`
10848 /// and the project issue it is filed under — with `what` naming the item in a refusal: the
10849 /// one place the rule is, so the create, [`TaskSource::creation_repository`] and the
10850 /// write-time read of who can read the issue ([`TaskSource::visibility`]) cannot answer
10851 /// differently.
10852 ///
10853 /// On a source declared private, an item's one named repository is read for its
10854 /// visibility first — once per engine hold, see the `visibility` module — and one that
10855 /// does not read private decides nothing: the issue is created in the parent's
10856 /// repository, else the configured one. A read that cannot be answered refuses.
10857 async fn creation_rule(
10858 &self,
10859 repositories: &[Repository],
10860 parent: Option<&NativeId>,
10861 what: &str,
10862 ) -> Result<RepositoryTarget, SourceError> {
10863 let parent = match parent {
10864 Some(parent) => Some(self.bound_item(parent).await?.ok_or_else(|| {
10865 SourceError::Refused {
10866 message: format!(
10867 "GitHub project issue {} was not found on the board of source {}, so {} \
10868 cannot be filed under it",
10869 parent.0, self.name, what
10870 ),
10871 }
10872 })?),
10873 None => None,
10874 };
10875 let parents_repository = parent
10876 .as_ref()
10877 .map(|parent| {
10878 // A draft is on the board and so is found, but it has no repository to
10879 // place a task in and GitHub gives it no sub-issues, so `addSubIssue`
10880 // would refuse the task only once `createIssue` had made it.
10881 if parent.content_kind == ContentKind::DraftIssue {
10882 return Err(SourceError::Refused {
10883 message: format!(
10884 "GitHub project item {} on the board of source {} is a draft, \
10885 which cannot have sub-issues, so {} cannot be filed under it",
10886 parent.id.0, self.name, what
10887 ),
10888 });
10889 }
10890 // An issue's repository is where a sub-issue is placed and whose owner it
10891 // is compared against, so a parent whose repository this source cannot
10892 // spell as `owner/name` — GitHub's login grammar is wider than this
10893 // source's floor — is one nothing can be filed under.
10894 parent
10895 .own_repository
10896 .as_ref()
10897 .and_then(|origin| RepositoryTarget::from_origin(origin).ok())
10898 .ok_or_else(|| SourceError::Malformed {
10899 message: format!(
10900 "GitHub project issue {} on the board of source {} is in {}, which \
10901 is not a {}/owner/name repository this source can place {} in",
10902 parent.id.0,
10903 self.name,
10904 parent
10905 .own_repository
10906 .as_ref()
10907 .map_or("no repository", Repository::as_str),
10908 RepositoryTarget::HOST,
10909 what
10910 ),
10911 })
10912 })
10913 .transpose()?;
10914 self.creation_rule_in_repository(repositories, parents_repository, what)
10915 .await
10916 }
10917
10918 async fn creation_rule_in_repository(
10919 &self,
10920 repositories: &[Repository],
10921 parents_repository: Option<RepositoryTarget>,
10922 what: &str,
10923 ) -> Result<RepositoryTarget, SourceError> {
10924 let fallback = self.configured_repository()?;
10925 match repositories {
10926 [named] => {
10927 let target =
10928 RepositoryTarget::from_origin(named).map_err(|_| SourceError::Refused {
10929 message: format!(
10930 "{} names repository {}, which is not a {}/owner/name repository \
10931 source {} can create an issue in; name one that is, or name none",
10932 what,
10933 named.as_str(),
10934 RepositoryTarget::HOST,
10935 self.name
10936 ),
10937 })?;
10938 // On a source declared private, an issue whose one named repository does not
10939 // read private is created where an item naming none is: the item still names
10940 // that repository in its metadata slot, and its issue stays private.
10941 if self.is_declared_private()
10942 && self.repository_visibility(&target).await?
10943 != onetaskgraph_plugin_api::Visibility::Private
10944 {
10945 return Ok(parents_repository.unwrap_or_else(|| fallback.clone()));
10946 }
10947 if let Some(parents) = &parents_repository
10948 && parents.owner != target.owner
10949 {
10950 return Err(SourceError::Refused {
10951 message: format!(
10952 "{} names repository {}, owned by {}, but its project's issue is in \
10953 {}, owned by {}, and GitHub files a sub-issue only in a repository \
10954 of the same owner as its parent issue; name a repository of {}, or \
10955 name none",
10956 what,
10957 target.slug(),
10958 target.owner,
10959 parents.slug(),
10960 parents.owner,
10961 parents.owner
10962 ),
10963 });
10964 }
10965 Ok(target)
10966 }
10967 _ => Ok(parents_repository.unwrap_or_else(|| fallback.clone())),
10968 }
10969 }
10970
10971 /// The node id of the repository `incoming` is being created in, or the refusal naming
10972 /// the item and the repository the token cannot see.
10973 ///
10974 /// Resolved once per command per repository; see [`Self::repository_cache`].
10975 async fn repository_id(
10976 &self,
10977 repository: &RepositoryTarget,
10978 incoming: &Incoming<'_>,
10979 ) -> Result<String, SourceError> {
10980 if let Some(id) = self.repository_cache()?.get(repository).cloned() {
10981 return Ok(id);
10982 }
10983 let data = self
10984 .graphql(
10985 graphql::REPOSITORY,
10986 json!({"owner":repository.owner,"name":repository.name}),
10987 )
10988 .await?;
10989 self.repository_read(&data, repository, incoming)
10990 }
10991
10992 /// The repository's node id out of an answer carrying the `repository` root, held for
10993 /// the rest of this command, or the refusal naming the item that cannot be created in it.
10994 fn repository_read(
10995 &self,
10996 data: &Value,
10997 repository: &RepositoryTarget,
10998 incoming: &Incoming<'_>,
10999 ) -> Result<String, SourceError> {
11000 let node = data
11001 .get("repository")
11002 .filter(|value| !value.is_null())
11003 .ok_or_else(|| SourceError::Refused {
11004 message: format!(
11005 "GitHub repository {} was not found or is not visible to the token, so {} \
11006 {:?} cannot be created in it",
11007 repository.slug(),
11008 incoming.written.kind().describes(),
11009 incoming.title
11010 ),
11011 })?;
11012 let id = required_str(node, "id")?.to_owned();
11013 self.repository_cache()?
11014 .insert(repository.clone(), id.clone());
11015 Ok(id)
11016 }
11017
11018 fn repository_cache(
11019 &self,
11020 ) -> Result<std::sync::MutexGuard<'_, BTreeMap<RepositoryTarget, String>>, SourceError> {
11021 self.repository_cache
11022 .lock()
11023 .map_err(|_| SourceError::Unavailable {
11024 message: "this source's record of the destination repository was left \
11025 inconsistent by an earlier failure; next: run the command again"
11026 .into(),
11027 })
11028 }
11029
11030 /// Create or update one board item, whichever kind it is.
11031 async fn write_item(
11032 &self,
11033 incoming: &Incoming<'_>,
11034 target: Option<&NativeId>,
11035 depends_on: &[DependencyEdge],
11036 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11037 let prepared = self.prepare_write(incoming, target, depends_on).await?;
11038 let landed = match &prepared.destination {
11039 // Its content is written last, by `complete_write`, once everything else has landed.
11040 WriteDestination::Existing(item) => Landed {
11041 content_id: item.id.clone(),
11042 item_id: Some(item.item_id.clone()),
11043 url: item.url.clone(),
11044 number: item.number,
11045 },
11046 WriteDestination::New(target) => {
11047 if self.deferring()? {
11048 self.create_filed_issue(
11049 prepared.board.id.as_str(),
11050 target,
11051 incoming,
11052 &prepared.body,
11053 )
11054 .await?
11055 } else {
11056 self.create_and_file_issue(
11057 prepared.board.id.as_str(),
11058 target,
11059 incoming,
11060 &prepared.body,
11061 )
11062 .await?
11063 }
11064 }
11065 };
11066 self.complete_write(incoming, prepared, landed).await
11067 }
11068
11069 /// Everything one write of `incoming` reads and decides before it sends anything: what is
11070 /// there now, where a new item is created, the board's fields, and every value refused while
11071 /// nothing has been written — the item's body included.
11072 async fn prepare_write(
11073 &self,
11074 incoming: &Incoming<'_>,
11075 target: Option<&NativeId>,
11076 depends_on: &[DependencyEdge],
11077 ) -> Result<Prepared, SourceError> {
11078 // Refused before anything is read or written: a task or a project titled the way
11079 // this board spells a document would land as an issue this same source reads back
11080 // as a document, so the field this destination cannot carry is named rather than
11081 // written and silently reclassified.
11082 if let Written::Work(kind, _) = incoming.written
11083 && incoming.title.starts_with(DESIGN_TITLE_PREFIX)
11084 {
11085 return Err(SourceError::Refused {
11086 message: format!(
11087 "the title of this {} begins {DESIGN_TITLE_PREFIX:?}, which is how source {} \
11088 spells a document, so it would read back as one rather than as a {}; \
11089 retitle it, or copy it as a document",
11090 kind.marker(),
11091 self.name,
11092 kind.marker()
11093 ),
11094 });
11095 }
11096 // The destination is read by its own id, and whether this board holds it is decided
11097 // by that read — its own `projectItems` — rather than by whether a listing of the
11098 // board happens to include it yet. See the module documentation.
11099 // An existing issue is never moved; a new one is created where the rule says — and
11100 // knowing where is what lets the board's fields and that repository's id be read
11101 // together, before anything below needs either.
11102 let destination = match target {
11103 Some(target) => {
11104 WriteDestination::Existing(Box::new(self.bound_item(target).await?.ok_or_else(
11105 || SourceError::Refused {
11106 message: format!("GitHub destination item {} was not found", target.0),
11107 },
11108 )?))
11109 }
11110 None => {
11111 let target = self.creation_target(incoming).await?;
11112 self.creation_context(&target, incoming).await?;
11113 WriteDestination::New(target)
11114 }
11115 };
11116 let existing = destination.existing();
11117 let board = self
11118 .fields_for(
11119 existing,
11120 incoming.metadata.contains_key(ORIGIN_KEY),
11121 incoming.written.status().is_some(),
11122 incoming
11123 .priority
11124 .is_some_and(|priority| priority != Priority::None),
11125 )
11126 .await?;
11127 let status_target = incoming
11128 .written
11129 .work_status()
11130 .map(|(kind, status)| self.resolved_target(kind, status.category))
11131 .transpose()?;
11132 let column = match (incoming.written.work_status(), status_target.as_ref()) {
11133 (Some((kind, status)), Some(target)) => {
11134 self.column_for(&board.fields, kind, status.category, target)?
11135 }
11136 _ => None,
11137 };
11138 // Resolved before anything is created, for the reason the column above is: a
11139 // priority this board has no option for is refused while nothing has been written.
11140 let priority_write = match incoming.priority {
11141 Some(priority) => self.priority_write(&board.fields, existing, priority)?,
11142 None => None,
11143 };
11144 // And for the reason the priority is: a value no projected field can hold, or a board
11145 // that cannot hold the field, is refused while nothing has been written.
11146 let (projections, projected) = self.projection_writes(
11147 &board.fields,
11148 existing.map(|item| &item.projected),
11149 incoming.metadata,
11150 None,
11151 )?;
11152 let content_kind = existing.map_or(ContentKind::Issue, |item| item.content_kind);
11153 if content_kind == ContentKind::DraftIssue {
11154 if let (Some(StatusTarget::Terminal(_, _)), Some(status)) =
11155 (status_target.as_ref(), incoming.written.status())
11156 {
11157 return Err(self.closes_a_draft(status.category));
11158 }
11159 if incoming.parent.is_some() {
11160 return Err(SourceError::Refused {
11161 message: "GitHub draft items cannot be a project's sub-issue".into(),
11162 });
11163 }
11164 }
11165 // The people it is to be assigned to are looked up — unless this process already has —
11166 // and a login GitHub does not know refused, while nothing has been written.
11167 if let Some(people) = incoming.assignees
11168 && existing.is_none_or(|item| {
11169 item.assignees
11170 .as_deref()
11171 .is_none_or(|held| !assignees::same_people(held, people))
11172 })
11173 {
11174 if content_kind == ContentKind::DraftIssue {
11175 return Err(self.assigns_a_draft());
11176 }
11177 self.resolve_people(people).await?;
11178 self.people_ids(
11179 people,
11180 &existing.map_or_else(
11181 || format!("the new {}", incoming.title),
11182 Resolved::written_name,
11183 ),
11184 )?;
11185 }
11186 match existing {
11187 Some(item) if content_kind == ContentKind::Issue => {
11188 if item.labels != incoming.labels {
11189 return Err(SourceError::Refused {
11190 message: "GitHub issue labels differ from the labels being written".into(),
11191 });
11192 }
11193 }
11194 _ => {
11195 if !incoming.labels.is_empty() {
11196 return Err(SourceError::Refused {
11197 message: "GitHub items created by this destination carry no labels".into(),
11198 });
11199 }
11200 }
11201 }
11202
11203 // The repository the issue really lives in is what the slot below is written against,
11204 // so a single entry that is where the issue is created travels as no key at all, and
11205 // the read side derives it back from the issue.
11206 let own_repository = match &destination {
11207 WriteDestination::Existing(item) => item.own_repository.clone(),
11208 WriteDestination::New(target) => Some(
11209 Repository::try_from(target.origin())
11210 .map_err(|message| SourceError::Config { message })?,
11211 ),
11212 };
11213 let (native, fallback) = self
11214 .partition_edges(
11215 incoming.written.kind(),
11216 content_kind,
11217 existing.and_then(|item| item.blocked_by.as_deref()),
11218 depends_on,
11219 )
11220 .await?;
11221 let mut slot = slot_metadata(incoming, own_repository.as_ref(), &fallback);
11222 let content = match incoming.assets {
11223 Some(assets) => {
11224 let uploads = self.upload_assets(own_repository.as_ref(), assets).await?;
11225 let rewritten = onetaskgraph_plugin_api::serve_asset_references(
11226 incoming.content.unwrap_or_default(),
11227 &mut slot,
11228 &uploads,
11229 );
11230 incoming.content.map(|_| rewritten)
11231 }
11232 None => incoming.content.map(str::to_owned),
11233 };
11234 // A write over an existing item keeps its `## Links` section, re-rendered from the
11235 // links it holds.
11236 let content = content.map(|content| {
11237 onetaskgraph_plugin_api::relinked(
11238 &content,
11239 existing.and_then(|item| item.body.as_deref()),
11240 incoming.metadata,
11241 )
11242 });
11243 let marked = content.as_deref().map(|content| self.marked(content));
11244 let body = compose_body(marked.as_deref(), &slot)?;
11245 // Read before anything is created, for the reason the field below is: a value
11246 // this destination cannot store has to refuse, and refusing after `createIssue`
11247 // would leave an issue behind that nothing asked for. The engine writes a
11248 // qualified id here; a caller handing this key anything else is told so rather
11249 // than having it silently stored as no origin at all.
11250 // 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.
11251 let origin = match incoming.metadata.get(ORIGIN_KEY) {
11252 None => "",
11253 Some(Value::String(origin)) => origin.as_str(),
11254 Some(other) => {
11255 return Err(SourceError::Refused {
11256 message: format!(
11257 "{ORIGIN_KEY} holds a qualified id spelled as a string, and this item's \
11258 is {other}"
11259 ),
11260 });
11261 }
11262 };
11263 // Resolved before anything is created: a board that cannot carry the copy origin
11264 // has to refuse the write, and refusing it after `createIssue` would leave an
11265 // issue behind that nothing asked for.
11266 let origin_field = match Board::field(&board.fields, ORIGIN_FIELD)? {
11267 Some(field) => {
11268 if required_str(field, "__typename")? != "ProjectV2Field" {
11269 return Err(SourceError::Refused {
11270 message: format!(
11271 "GitHub board source-owned {ORIGIN_FIELD} field is not a text field"
11272 ),
11273 });
11274 }
11275 Some(required_str(field, "id")?.to_owned())
11276 }
11277 None if incoming.metadata.contains_key(ORIGIN_KEY) => {
11278 return Err(SourceError::Refused {
11279 message: format!(
11280 "GitHub board has no source-owned {ORIGIN_FIELD} text field, and the \
11281 item carries {ORIGIN_KEY}; add a text field named {ORIGIN_FIELD} to \
11282 the board"
11283 ),
11284 });
11285 }
11286 None => None,
11287 };
11288
11289 Ok(Prepared {
11290 origin: origin.to_owned(),
11291 destination,
11292 board,
11293 status_target,
11294 column,
11295 priority_write,
11296 projections,
11297 projected,
11298 content_kind,
11299 own_repository,
11300 native,
11301 slot,
11302 content,
11303 body,
11304 origin_field,
11305 })
11306 }
11307
11308 /// Everything one write does once the item it writes exists: its board fields, its
11309 /// relationships and — for an item that was already there — its content last, then what this
11310 /// process remembers of it.
11311 ///
11312 /// While this source is holding writes back — see [`TaskSource::begin_deferred_writes`] — an
11313 /// item this command created has its fields, its closing and its edges held for
11314 /// [`TaskSource::finish_writes`] rather than sent here.
11315 async fn complete_write(
11316 &self,
11317 incoming: &Incoming<'_>,
11318 prepared: Prepared,
11319 landed: Landed,
11320 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
11321 let Prepared {
11322 destination,
11323 board,
11324 status_target,
11325 column,
11326 priority_write,
11327 projections,
11328 projected,
11329 content_kind,
11330 own_repository,
11331 native,
11332 slot,
11333 content,
11334 body,
11335 origin,
11336 origin_field,
11337 } = prepared;
11338 let existing = destination.existing();
11339 let origin = origin.as_str();
11340 let Landed {
11341 content_id,
11342 item_id,
11343 url,
11344 number,
11345 } = landed;
11346
11347 // Only what differs from the item as this write read it is sent: a priority the item
11348 // already holds is not, so an unchanged re-copy writes no field and a person's edit of
11349 // it since that read is left alone.
11350 let priority_write = priority_write.filter(|_| {
11351 !existing.is_some_and(|item| {
11352 incoming.priority.map(HeldPriority::Read) == Some(item.priority.clone())
11353 })
11354 });
11355 let written_option = column.as_ref().map(|(_, _, name)| name.clone());
11356 let column = column
11357 .filter(|(_, _, name)| existing.is_none_or(|item| item.option.as_ref() != Some(name)))
11358 .map(|(field, option, _)| (field, option));
11359 // Creating an item here is several calls — `createIssue`, which files it on the
11360 // board, then its board fields, the parent and the dependencies — and GitHub can fail
11361 // at any of them. Everything this source can refuse *before* the first of those is
11362 // already checked above, so what is left is GitHub itself failing part way. When it
11363 // does over an item this call created, the issue is taken back: a write that
11364 // refused must not leave an item behind that nobody asked for, and one that does
11365 // makes the retry create a second.
11366 // Whether the board-field write carrying a moved origin was answered as landing whole.
11367 // When it was refused, GitHub does not say which of its fields ran before the one that
11368 // failed, so the origin may or may not have moved.
11369 let mut origin_landed = false;
11370 // An item this command created while writes are held back has every part that can land
11371 // later held for `finish_writes` — its own create filed it on the board and under its
11372 // project already — and so does a later write of it in the same command.
11373 let holding = (existing.is_none() && self.deferring()?) || self.holds_back(&content_id)?;
11374 let landed = if holding {
11375 self.hold_back(
11376 &board.id,
11377 &content_id,
11378 existing,
11379 origin_field.as_deref(),
11380 origin,
11381 column,
11382 status_target.as_ref(),
11383 priority_write.as_ref(),
11384 &projections,
11385 &native,
11386 )
11387 } else if let Some(item_id) = item_id.as_deref() {
11388 self.finish_write(
11389 board.id.as_str(),
11390 incoming,
11391 &content_id,
11392 item_id,
11393 content_kind,
11394 existing,
11395 origin_field.as_deref(),
11396 origin,
11397 column,
11398 status_target.as_ref(),
11399 priority_write.as_ref(),
11400 &projections,
11401 &native,
11402 &mut origin_landed,
11403 )
11404 .await
11405 } else {
11406 // An issue a create filed on the board itself has no board item this process
11407 // knows until `finish_writes` reads it, so nothing but a held-back write may land
11408 // on it before then.
11409 Err(SourceError::Malformed {
11410 message: format!(
11411 "issue {} was written before the board item GitHub filed it as was read",
11412 content_id.0
11413 ),
11414 })
11415 };
11416 // An existing item's title, body and state go last, in one `updateIssue`, once its board
11417 // fields and its relationships have landed: a refusal of any of those then leaves its
11418 // body — and the metadata slot inside it — exactly as it stood.
11419 let landed = match (landed, existing) {
11420 (Ok(()), Some(item)) => {
11421 self.update_existing(item, incoming, &body, status_target.as_ref())
11422 .await
11423 }
11424 (landed, _) => landed,
11425 };
11426 if let Err(error) = landed {
11427 match existing {
11428 // Best effort, and the write's own failure is what the caller is told: a
11429 // refusal naming the tidy-up would hide why the write failed at all.
11430 None => {
11431 let _ = self.delete_issue(&content_id).await;
11432 }
11433 // The origin field is the one piece of an existing item's metadata written
11434 // before its body, so a write refused after it puts it back as it was. When
11435 // that is refused too, the write's own failure is still what the caller is
11436 // told — with what it left behind added, because the item's metadata is then
11437 // not as it stood and a caller retrying has to know which key moved.
11438 Some(item) => {
11439 let before = item.origin.as_deref().unwrap_or("");
11440 if let Some(field) = origin_field.as_deref()
11441 && before != origin
11442 && let Err(restore) = self
11443 .set_item_field(
11444 board.id.as_str(),
11445 &item.item_id,
11446 field,
11447 json!({"text": before}),
11448 )
11449 .await
11450 {
11451 let left = if origin_landed {
11452 format!(
11453 "its {ORIGIN_KEY} was moved to {origin:?} before that and could \
11454 not be put back to {before:?} ({restore}), so item {} still \
11455 holds {origin:?} there",
11456 item.id.0
11457 )
11458 } else {
11459 format!(
11460 "the refused write carried its {ORIGIN_KEY} from {before:?} to \
11461 {origin:?}, GitHub does not say whether that part of it ran, \
11462 and putting it back to {before:?} was refused ({restore}), so \
11463 item {} holds {origin:?} or {before:?} there",
11464 item.id.0
11465 )
11466 };
11467 return Err(noting(
11468 error,
11469 &format!(
11470 "; {left}; next: set {ORIGIN_KEY} on it back to {before:?}, or \
11471 run the write again"
11472 ),
11473 ));
11474 }
11475 }
11476 }
11477 return Err(error);
11478 }
11479
11480 let written_status = match (incoming.written.work_status(), status_target.as_ref()) {
11481 (Some((kind, _)), Some(StatusTarget::Terminal(_, reason))) => {
11482 self.statuses
11483 .status(kind, written_option.as_deref(), true, Some(reason.reason()))
11484 }
11485 (Some((kind, _)), Some(StatusTarget::Column(_))) => {
11486 self.statuses
11487 .status(kind, written_option.as_deref(), false, None)
11488 }
11489 (Some((_, status)), _) => status.clone(),
11490 (None, _) => Status {
11491 category: StatusCategory::Unknown,
11492 name: "Open".to_owned(),
11493 },
11494 };
11495
11496 // So the rest of this command reads what it just did rather than what the board
11497 // said before it. See `remember_written` for which half takes it.
11498 let remembered = Resolved {
11499 // Empty for an issue whose board item is not read yet: `finish_writes` reads it
11500 // and `learn_item` puts it here.
11501 // 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.
11502 item_id: item_id.unwrap_or_default(),
11503 id: content_id.clone(),
11504 content_kind,
11505 kind: incoming.written.kind(),
11506 title: incoming.title.to_owned(),
11507 // The visible half of the body this write composed, split back off it the
11508 // way a read splits it — so what this record reports is what a read of the
11509 // same issue reports, rather than the person's text with the metadata slot
11510 // still on the end of it.
11511 body: self.visible(body.clone())?.0,
11512 raw_body: body.clone(),
11513 // A document has no status of its own; what it reads back as is whatever
11514 // the issue's own state says, which is what a re-read reports.
11515 status: written_status,
11516 option: written_option.or_else(|| existing.and_then(|item| item.option.clone())),
11517 priority: match incoming.priority {
11518 Some(priority) => HeldPriority::Read(priority),
11519 None => existing.map_or(HeldPriority::Read(Priority::None), |item| {
11520 item.priority.clone()
11521 }),
11522 },
11523 // What `state_input` asked for: closed for a terminal target, open for any other
11524 // status, and the issue's own state left as it was by a document write.
11525 closed: content_kind == ContentKind::Issue
11526 && match status_target.as_ref() {
11527 Some(StatusTarget::Terminal(_, _)) => true,
11528 Some(_) => false,
11529 None => existing.is_some_and(|item| item.closed),
11530 },
11531 reason: match status_target.as_ref() {
11532 Some(StatusTarget::Terminal(_, reason)) if content_kind == ContentKind::Issue => {
11533 Some(reason.reason().to_owned())
11534 }
11535 Some(_) => None,
11536 None => existing.and_then(|item| item.reason.clone()),
11537 },
11538 delivers: incoming.delivers.to_vec(),
11539 delivered_by: incoming.delivered_by.to_vec(),
11540 labels: incoming.labels.to_vec(),
11541 parent: incoming.parent.cloned(),
11542 issue_parent: None,
11543 origin: (!origin.is_empty()).then(|| origin.to_owned()),
11544 projected,
11545 number,
11546 // In the update path this is the item's own url, read off `existing` where the
11547 // record above was bound, so one expression serves both halves.
11548 url,
11549 created_at: existing.and_then(|item| item.created_at),
11550 updated_at: existing.and_then(|item| item.updated_at),
11551 // What this write moved is GitHub's to say, so a record of it gives no token until
11552 // it is read again.
11553 item_updated_at: None,
11554 comment_count: None,
11555 relationship_events: None,
11556 served_at: None,
11557 facets: None,
11558 own_repository,
11559 repositories: incoming.repositories.to_vec(),
11560 classification: incoming.classification,
11561 slot,
11562 board_id: Some(board.id.as_str().to_owned()),
11563 fields: board
11564 .fields
11565 .get("nodes")
11566 .and_then(Value::as_array)
11567 .cloned()
11568 .unwrap_or_default(),
11569 board_fields: Some(board.fields.clone()),
11570 // What this write left the relationship holding is known by id alone, and a
11571 // later read of its edges needs each far end's kind, so it reads them again.
11572 blocked_by: None,
11573 // The people it named, which its own answer was held to; none named keeps the
11574 // item's, and creates a task of an opted-in source unassigned.
11575 assignees: match incoming.assignees {
11576 Some(people) => Some(people.to_vec()),
11577 None => match existing {
11578 Some(item) => item.assignees.clone(),
11579 None => (self.assignees
11580 && matches!(incoming.written, Written::Work(ItemKind::Task, _)))
11581 .then(Vec::new),
11582 },
11583 },
11584 };
11585 self.remember_written(remembered, existing.is_none())?;
11586 Ok(onetaskgraph_plugin_api::AssetsWritten {
11587 id: content_id,
11588 content,
11589 })
11590 }
11591
11592 /// Everything a write does after the item exists: its board fields, its parent, and
11593 /// its dependencies.
11594 ///
11595 /// Split out of `write_item` so there is one place a failure past the point of no
11596 /// return is caught, rather than a tidy-up repeated at each `?` above.
11597 // llmlint: ignore[suppressions_justified] This is the tail of `write_item` lifted out
11598 // so there is one place a failure past the point of no return is caught, and its
11599 // arguments are exactly the values that tail already had in scope. Bundling them into a
11600 // struct would describe no concept — it would be "the arguments of this function" — and
11601 // would put the whole of `write_item`'s locals behind one more indirection.
11602 #[allow(clippy::too_many_arguments)]
11603 async fn finish_write(
11604 &self,
11605 board_id: &str,
11606 incoming: &Incoming<'_>,
11607 content_id: &NativeId,
11608 item_id: &str,
11609 content_kind: ContentKind,
11610 existing: Option<&Resolved>,
11611 origin_field: Option<&str>,
11612 origin: &str,
11613 column: Option<(String, String)>,
11614 status_target: Option<&StatusTarget>,
11615 priority: Option<&PriorityWrite>,
11616 projections: &[ProjectionWrite],
11617 native: &[String],
11618 origin_landed: &mut bool,
11619 ) -> Result<(), SourceError> {
11620 let (fields, clears) = field_writes(
11621 existing,
11622 origin_field,
11623 origin,
11624 column,
11625 priority,
11626 projections,
11627 );
11628 self.set_item_fields(board_id, item_id, &fields, &clears)
11629 .await?;
11630 *origin_landed = true;
11631
11632 // An existing issue closes in the `updateIssue` its write ends with; one created just
11633 // now closes here, once its option is selected.
11634 if existing.is_none()
11635 && content_kind == ContentKind::Issue
11636 && matches!(status_target, Some(StatusTarget::Terminal(_, _)))
11637 {
11638 self.update_content(
11639 ContentKind::Issue,
11640 content_id,
11641 json!({"stateInput":state_input(status_target)}),
11642 )
11643 .await?;
11644 }
11645
11646 if content_kind == ContentKind::Issue {
11647 self.reparent(
11648 existing.and_then(|item| item.parent.clone()),
11649 content_id,
11650 incoming.parent,
11651 )
11652 .await?;
11653 // A document takes part in no dependency graph, so writing one neither reads
11654 // nor changes the issue's own `blockedBy` relationships. Reconciling them
11655 // against the empty list a document write carries would *delete* whatever
11656 // relationships a person had made on that issue, which is a write nobody
11657 // asked for.
11658 if incoming.written.kind() != BoardKind::Document {
11659 let issue = match existing {
11660 Some(item) => Issue::Existing(item.blocked_by.as_deref()),
11661 None => Issue::Created,
11662 };
11663 self.reconcile_blocked_by(content_id, native, issue).await?;
11664 }
11665 }
11666 Ok(())
11667 }
11668
11669 /// Whether this source is holding writes back — see [`TaskSource::begin_deferred_writes`].
11670 fn deferring(&self) -> Result<bool, SourceError> {
11671 Ok(self.deferred()?.is_some())
11672 }
11673
11674 /// Whether `content` is an item this command created whose parts are held back.
11675 fn holds_back(&self, content: &NativeId) -> Result<bool, SourceError> {
11676 Ok(self
11677 .deferred()?
11678 .as_ref()
11679 .is_some_and(|deferred| deferred.holds(content)))
11680 }
11681
11682 fn deferred(&self) -> Result<std::sync::MutexGuard<'_, Option<Deferred>>, SourceError> {
11683 self.deferred.lock().map_err(|_| SourceError::Unavailable {
11684 message: "this source's record of the writes it is holding back was left \
11685 inconsistent by an earlier failure; next: run the command again"
11686 .into(),
11687 })
11688 }
11689
11690 /// Creates one issue filed on the board and under its project by the `createIssue` itself —
11691 /// `projectV2Ids` naming the board and `parentIssueId` the project — which is what a copy
11692 /// creates with: one request where adding it to the board and filing it under its project
11693 /// were two more. GitHub adds the board item after answering, so its id is not known here;
11694 /// [`TaskSource::finish_writes`] reads it.
11695 async fn create_filed_issue(
11696 &self,
11697 board_id: &str,
11698 repository: &RepositoryTarget,
11699 incoming: &Incoming<'_>,
11700 body: &Option<String>,
11701 ) -> Result<Landed, SourceError> {
11702 let repository_id = self.repository_id(repository, incoming).await?;
11703 let mut input = filed_input(&repository_id, board_id, incoming, body);
11704 self.assigning(&mut input, incoming)?;
11705 let data = match self
11706 .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
11707 .await
11708 {
11709 Ok(data) => data,
11710 Err(error) => return Err(self.refusing_people(&input, error)),
11711 };
11712 let created = data
11713 .pointer("/createIssue/issue")
11714 .filter(|value| !value.is_null())
11715 .ok_or_else(|| SourceError::Malformed {
11716 message: "GitHub issue creation returned no issue".into(),
11717 })?;
11718 let landed = self.created_landed(created).await?;
11719 // An issue GitHub created assigned otherwise than asked is refused and taken back; a
11720 // delete GitHub refuses too is answered beside the refusal, naming the issue left.
11721 if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
11722 return Err(self.taken_back(&landed.content_id, created, error).await);
11723 }
11724 Ok(landed)
11725 }
11726
11727 /// Keep the address `createIssue` answered for the issue `content`, for
11728 /// [`TaskSource::written_location`].
11729 fn note_written(&self, content: &NativeId, url: Option<&str>) {
11730 if let Some(url) = url {
11731 self.written
11732 .lock()
11733 .unwrap_or_else(std::sync::PoisonError::into_inner)
11734 .insert(content.clone(), url.to_owned());
11735 }
11736 }
11737
11738 /// What one `createIssue` answered, as the item it created — or, when its number cannot be
11739 /// read, the refusal, after taking the issue back.
11740 async fn created_landed(&self, created: &Value) -> Result<Landed, SourceError> {
11741 let content_id = NativeId(required_nonblank_str(created, "id")?.to_owned());
11742 let url = optional_str(created, "url")?.map(str::to_owned);
11743 let number = match created_issue_number(created) {
11744 Ok(number) => number,
11745 Err(error) => {
11746 let _ = self.delete_issue(&content_id).await;
11747 return Err(error);
11748 }
11749 };
11750 self.note_written(&content_id, url.as_deref());
11751 Ok(Landed {
11752 content_id,
11753 item_id: None,
11754 url,
11755 number,
11756 })
11757 }
11758
11759 /// Hold back everything a write of the created item `content` would send after creating it,
11760 /// for [`TaskSource::finish_writes`]: the same field values, closing and edges
11761 /// `finish_write` sends, the parent excepted, which its create already named. A later write
11762 /// of the same item replaces what it changes.
11763 // 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.
11764 #[allow(clippy::too_many_arguments)]
11765 fn hold_back(
11766 &self,
11767 board_id: &BoardId,
11768 content: &NativeId,
11769 existing: Option<&Resolved>,
11770 origin_field: Option<&str>,
11771 origin: &str,
11772 column: Option<(String, String)>,
11773 status_target: Option<&StatusTarget>,
11774 priority: Option<&PriorityWrite>,
11775 projections: &[ProjectionWrite],
11776 native: &[String],
11777 ) -> Result<(), SourceError> {
11778 let status = column.map(|(field, option)| {
11779 let name = self
11780 .fields_cache()
11781 .ok()
11782 .and_then(|fields| {
11783 fields.as_ref().and_then(|board| {
11784 option_name(&board.fields, &field, &option).map(str::to_owned)
11785 })
11786 })
11787 .unwrap_or_default();
11788 (field, option, name)
11789 });
11790 let (fields, clears) =
11791 field_writes(existing, origin_field, origin, None, priority, projections);
11792 let close = match status_target {
11793 Some(StatusTarget::Terminal(_, reason)) => Some(*reason),
11794 _ => None,
11795 };
11796 let mut deferred = self.deferred()?;
11797 let deferred = deferred.get_or_insert_with(Deferred::default);
11798 if let Deferred::Nothing = deferred {
11799 *deferred = Deferred::Held {
11800 board: board_id.clone(),
11801 created: Vec::new(),
11802 };
11803 }
11804 let Deferred::Held { created, .. } = deferred else {
11805 unreachable!("held back on the line above");
11806 };
11807 let held = match created.iter().position(|held| held.content == *content) {
11808 Some(at) => &mut created[at],
11809 None => {
11810 created.push(HeldBack {
11811 content: content.clone(),
11812 fields: Vec::new(),
11813 status: None,
11814 clears: Vec::new(),
11815 close: None,
11816 edges: Vec::new(),
11817 });
11818 created.last_mut().expect("just held")
11819 }
11820 };
11821 for (field, value) in fields {
11822 held.fields.retain(|(held, _)| *held != field);
11823 held.clears.retain(|held| *held != field);
11824 held.fields.push((field, value));
11825 }
11826 for field in clears {
11827 held.fields.retain(|(held, _)| held != field);
11828 if !held.clears.iter().any(|held| held == field) {
11829 held.clears.push(field.to_owned());
11830 }
11831 }
11832 if status.is_some() {
11833 held.status = status;
11834 }
11835 if close.is_some() {
11836 held.close = close;
11837 }
11838 // Nothing of an item created in this command has been sent but its create, so the edges
11839 // it is to have are exactly the ones its latest write names.
11840 held.edges = native.iter().map(|far| NativeId(far.clone())).collect();
11841 Ok(())
11842 }
11843
11844 /// Create every task of `writes`, together, filed on the board and under each one's
11845 /// project: [`graphql::CREATE_ISSUES`], [`MUTATION_BATCH`] to a request.
11846 ///
11847 /// Each is prepared as [`Self::write_item`] prepares one — every refusal a write owes made
11848 /// before the first request — then created, then completed with its parts held back. A
11849 /// request refused part way leaves the issues it did create, which are taken back, with the
11850 /// rest of this call's, before the refusal is answered.
11851 async fn create_together(
11852 &self,
11853 writes: &[ItemWrite<Task>],
11854 ) -> Result<Vec<NativeId>, SourceError> {
11855 let incomings: Vec<Incoming<'_>> = writes
11856 .iter()
11857 .map(|write| self.task_incoming(write, None))
11858 .collect::<Result<_, _>>()?;
11859 // Every person these creates assign, looked up together rather than one write at a time.
11860 let people: Vec<String> = writes
11861 .iter()
11862 .filter_map(|write| write.item.assignees.clone())
11863 .flatten()
11864 .collect();
11865 self.resolve_people(&people).await?;
11866 let mut prepared = Vec::with_capacity(writes.len());
11867 for (incoming, write) in incomings.iter().zip(writes) {
11868 if write.target.is_some() {
11869 return Err(SourceError::Malformed {
11870 message: "a write naming its target was handed to a batch of creates".into(),
11871 });
11872 }
11873 prepared.push(
11874 self.prepare_write(incoming, None, &write.depends_on)
11875 .await?,
11876 );
11877 }
11878 let mut inputs = Vec::with_capacity(prepared.len());
11879 for (incoming, prepared) in incomings.iter().zip(&prepared) {
11880 let WriteDestination::New(target) = &prepared.destination else {
11881 return Err(SourceError::Malformed {
11882 message: "an update was decided for a write handed to a batch of creates"
11883 .into(),
11884 });
11885 };
11886 let repository_id = self.repository_id(target, incoming).await?;
11887 let mut input = filed_input(
11888 &repository_id,
11889 prepared.board.id.as_str(),
11890 incoming,
11891 &prepared.body,
11892 );
11893 self.assigning(&mut input, incoming)?;
11894 inputs.push(input);
11895 }
11896 let mut landed: Vec<Landed> = Vec::with_capacity(inputs.len());
11897 let refused = 'create: {
11898 for chunk in inputs.chunks(MUTATION_BATCH) {
11899 let mut variables = serde_json::Map::new();
11900 for slot in 0..MUTATION_BATCH {
11901 variables.insert(
11902 format!("create{slot}"),
11903 chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
11904 );
11905 variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
11906 }
11907 let data = match self
11908 .graphql(graphql::CREATE_ISSUES, Value::Object(variables))
11909 .await
11910 {
11911 Ok(data) => data,
11912 Err(error) => break 'create Some(error),
11913 };
11914 let mut refusal = data.get(ANSWER_ERRORS).map(|errors| {
11915 let said: Vec<&str> = errors
11916 .as_array()
11917 .into_iter()
11918 .flatten()
11919 .filter_map(|error| error.get("message").and_then(Value::as_str))
11920 .collect();
11921 SourceError::Refused {
11922 message: if said.is_empty() {
11923 "GitHub returned GraphQL errors".to_owned()
11924 } else {
11925 said.join("; ")
11926 },
11927 }
11928 });
11929 for (slot, input) in chunk.iter().enumerate() {
11930 match data
11931 .pointer(&format!("/create{slot}/issue"))
11932 .filter(|value| !value.is_null())
11933 {
11934 Some(created) => match self.created_landed(created).await {
11935 Ok(landed_one) => {
11936 landed.push(landed_one);
11937 // Taken back with the rest, as any refusal here is.
11938 if let Err(error) = self.assigned_as_asked(input, Some(created)) {
11939 refusal.get_or_insert(error);
11940 }
11941 }
11942 Err(error) => {
11943 refusal.get_or_insert(error);
11944 }
11945 },
11946 // An alias GitHub refused answers nothing, and the refusal says why.
11947 None => {
11948 refusal.get_or_insert(SourceError::Malformed {
11949 message: "GitHub issue creation returned no issue".into(),
11950 });
11951 }
11952 }
11953 }
11954 if let Some(error) = refusal {
11955 break 'create Some(error);
11956 }
11957 }
11958 None
11959 };
11960 if let Some(error) = refused {
11961 // None of these ids reaches the caller, so an issue GitHub will not take back is
11962 // named here or by nobody.
11963 let ids: Vec<&NativeId> = landed.iter().map(|created| &created.content_id).collect();
11964 let left = self.delete_issues(&ids).await;
11965 let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
11966 return Err(left_behind(error, &left));
11967 }
11968 let created: Vec<NativeId> = landed
11969 .iter()
11970 .map(|landed| landed.content_id.clone())
11971 .collect();
11972 let mut ids = Vec::with_capacity(landed.len());
11973 for ((incoming, prepared), landed) in incomings.iter().zip(prepared).zip(landed) {
11974 match self.complete_write(incoming, prepared, landed).await {
11975 Ok(written) => ids.push(written.id),
11976 // 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.
11977 Err(error) => {
11978 let ids: Vec<&NativeId> = created.iter().collect();
11979 let left = self.delete_issues(&ids).await;
11980 let left: Vec<&str> = left.iter().map(|id| id.0.as_str()).collect();
11981 return Err(left_behind(error, &left));
11982 }
11983 }
11984 }
11985 Ok(ids)
11986 }
11987
11988 /// Hold back the update of the existing issue `issue` — `members`, what its own
11989 /// [`graphql::UPDATE_ISSUE`] would send beside its id — while writes are being held back — so the updates a copy makes one after
11990 /// another go to GitHub as one request. Whatever this source held of the issue is dropped
11991 /// as the mutation itself would drop it. Answers whether it was held: never while a write
11992 /// the store's cache expects runs, which records each mutation's own answer, and never for
11993 /// an issue an update is already held for, which that one is sent ahead of.
11994 fn hold_update(&self, issue: &NativeId, members: &Value) -> Result<bool, SourceError> {
11995 if self.expected.journaling() || self.deferred()?.is_none() {
11996 return Ok(false);
11997 }
11998 let mut held = self
11999 .held_updates
12000 .lock()
12001 .map_err(|_| SourceError::Unavailable {
12002 message: "issue updates held back were left inconsistent; run the command again"
12003 .into(),
12004 })?;
12005 if held.iter().any(|earlier| earlier.issue == *issue) {
12006 return Ok(false);
12007 }
12008 let named = |value: &str| issue.0 == value;
12009 self.resolved_cache()?
12010 .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12011 self.read_ahead()?.retain(|id, item| {
12012 !named(&id.0) && !item.as_ref().is_some_and(|item| named(&item.item_id))
12013 });
12014 self.carried()?
12015 .retain(|id, item| !named(&id.0) && !named(&item.item_id));
12016 held.push(HeldUpdate::new(issue, members));
12017 Ok(true)
12018 }
12019
12020 /// Send every update [`Self::hold_update`] held back: one alone as [`graphql::UPDATE_ISSUE`]
12021 /// sends it, several as aliased `updateIssue`s of [`graphql::UPDATE_ISSUES`],
12022 /// [`MUTATION_BATCH`] to a request. Each counts one write, as it would alone.
12023 async fn send_held_updates(&self) -> Result<(), SourceError> {
12024 let held = std::mem::take(&mut *self.held_updates.lock().map_err(|_| {
12025 SourceError::Unavailable {
12026 message: "issue updates held back were left inconsistent; run the command again"
12027 .into(),
12028 }
12029 })?);
12030 if let [one] = held.as_slice() {
12031 return self
12032 .send_update(
12033 graphql::UPDATE_ISSUE,
12034 "/updateIssue/issue",
12035 &one.issue,
12036 one.input.clone(),
12037 )
12038 .await;
12039 }
12040 for chunk in held.chunks(MUTATION_BATCH) {
12041 let mut variables = serde_json::Map::new();
12042 for slot in 0..MUTATION_BATCH {
12043 variables.insert(
12044 format!("update{slot}"),
12045 chunk.get(slot).unwrap_or(&chunk[0]).input.clone(),
12046 );
12047 variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12048 }
12049 let data = match self
12050 .graphql(graphql::UPDATE_ISSUES, Value::Object(variables))
12051 .await
12052 {
12053 Ok(data) => data,
12054 Err(error) => {
12055 for held in chunk {
12056 self.forget_people(&held.input);
12057 }
12058 return Err(error);
12059 }
12060 };
12061 let inputs: Vec<&Value> = chunk.iter().map(|held| &held.input).collect();
12062 check_aliased_answers(
12063 graphql::UPDATE_ISSUES,
12064 &data,
12065 "update",
12066 &inputs,
12067 &[("issue", "id")],
12068 )?;
12069 for (slot, held) in chunk.iter().enumerate() {
12070 self.assigned_as_asked(&held.input, data.pointer(&format!("/update{slot}/issue")))?;
12071 }
12072 }
12073 Ok(())
12074 }
12075
12076 /// Send everything held back since [`TaskSource::begin_deferred_writes`]: one read of the
12077 /// created items' board items, then their field values and edges together in requests of
12078 /// [`WRITE_BATCH`], then their closes in requests of [`MUTATION_BATCH`]. Anything refused
12079 /// takes back every issue held, [`DELETE_BATCH`] to a request, and answers the refusal.
12080 async fn send_held_back(&self) -> Result<(), SourceError> {
12081 let Some(Deferred::Held { board, created }) = self.deferred()?.take() else {
12082 return Ok(());
12083 };
12084 if created.is_empty() {
12085 return Ok(());
12086 }
12087 let sent = self.send_deferred(board.as_str(), &created).await;
12088 if let Err(error) = sent {
12089 // Best effort, and the failure is what the caller is told, as a write of one item
12090 // that fails part way takes back what it created: the copy that held these back
12091 // journalled every one, so one this cannot take back its undo tries again, and says
12092 // so when it cannot either.
12093 let ids: Vec<&NativeId> = created.iter().map(|held| &held.content).collect();
12094 let _ = self.delete_issues(&ids).await;
12095 return Err(error);
12096 }
12097 Ok(())
12098 }
12099
12100 /// The requests [`Self::send_held_back`] makes.
12101 async fn send_deferred(&self, board: &str, created: &[HeldBack]) -> Result<(), SourceError> {
12102 let items = self.created_board_items(board, created).await?;
12103 let mut fields: Vec<Value> = Vec::new();
12104 let mut closes: Vec<Value> = Vec::new();
12105 let mut edges: Vec<Value> = Vec::new();
12106 for held in created {
12107 let (item, status) = &items[&held.content];
12108 let mut values = held.fields.clone();
12109 // A status the board already shows — set by a workflow a person turned on to file
12110 // new items at it — is not written again.
12111 if let Some((field, option, name)) = &held.status
12112 && status.as_deref() != Some(name.as_str())
12113 {
12114 values.insert(0, (field.clone(), json!({"singleSelectOptionId": option})));
12115 }
12116 for (field, value) in values {
12117 fields.push(json!({"projectId":board,"itemId":item,"fieldId":field,"value":value}));
12118 }
12119 if let Some(reason) = held.close {
12120 closes.push(json!({"id": held.content.0, "stateInput": closed_input(reason)}));
12121 }
12122 for far in &held.edges {
12123 edges.push(json!({"issueId": held.content.0, "blockingIssueId": far.0}));
12124 }
12125 if !held.clears.is_empty() {
12126 let clears: Vec<&str> = held.clears.iter().map(String::as_str).collect();
12127 self.set_item_fields(board, item, &[], &clears).await?;
12128 }
12129 }
12130 // Each alias answers with what it wrote, which is what its input named: the board item a
12131 // field value is set on, the issue closed, the issue blocked and the one blocking it.
12132 let field_answer: &[(&str, &str)] = &[("projectV2Item", "itemId")];
12133 let close_answer: &[(&str, &str)] = &[("issue", "id")];
12134 let block_answer: &[(&str, &str)] =
12135 &[("issue", "issueId"), ("blockingIssue", "blockingIssueId")];
12136 // Every field value, then every edge, as one ordered list sent `WRITE_BATCH` aliases to a
12137 // request: a request holding both kinds is the one document carrying both, so a plan's
12138 // values and edges cost one request where they fit in one.
12139 let writes: Vec<HeldWrite<'_>> = fields
12140 .iter()
12141 .map(HeldWrite::Field)
12142 .chain(edges.iter().map(HeldWrite::Edge))
12143 .collect();
12144 for chunk in writes.chunks(WRITE_BATCH) {
12145 let values: Vec<&Value> = chunk
12146 .iter()
12147 .filter_map(|write| match write {
12148 HeldWrite::Field(input) => Some(*input),
12149 HeldWrite::Edge(_) => None,
12150 })
12151 .collect();
12152 let blocks: Vec<&Value> = chunk
12153 .iter()
12154 .filter_map(|write| match write {
12155 HeldWrite::Edge(input) => Some(*input),
12156 HeldWrite::Field(_) => None,
12157 })
12158 .collect();
12159 let (document, sends) = match (values.is_empty(), blocks.is_empty()) {
12160 (false, false) => (graphql::WRITE_FIELDS_AND_EDGES, ["sendField", "sendBlock"]),
12161 (false, true) => (graphql::WRITE_FIELD_VALUES, ["send", "send"]),
12162 _ => (graphql::ADD_BLOCKED_BYS, ["send", "send"]),
12163 };
12164 let mut variables = serde_json::Map::new();
12165 let kinds = [
12166 ("field", &values, sends[0], field_answer),
12167 ("block", &blocks, sends[1], block_answer),
12168 ];
12169 for (prefix, inputs, send, _) in &kinds {
12170 if inputs.is_empty() {
12171 continue;
12172 }
12173 for slot in 0..WRITE_BATCH {
12174 variables.insert(
12175 format!("{prefix}{slot}"),
12176 (*inputs.get(slot).unwrap_or(&inputs[0])).clone(),
12177 );
12178 variables.insert(format!("{send}{slot}"), json!(slot < inputs.len()));
12179 }
12180 }
12181 let data = self.graphql(document, Value::Object(variables)).await?;
12182 for (prefix, inputs, _, answers) in kinds {
12183 check_aliased_answers(document, &data, prefix, inputs, answers)?;
12184 }
12185 }
12186 for chunk in closes.chunks(MUTATION_BATCH) {
12187 let mut variables = serde_json::Map::new();
12188 for slot in 0..MUTATION_BATCH {
12189 variables.insert(
12190 format!("close{slot}"),
12191 chunk.get(slot).cloned().unwrap_or_else(|| chunk[0].clone()),
12192 );
12193 variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12194 }
12195 let data = self
12196 .graphql(graphql::CLOSE_ISSUES, Value::Object(variables))
12197 .await?;
12198 let inputs: Vec<&Value> = chunk.iter().collect();
12199 check_aliased_answers(graphql::CLOSE_ISSUES, &data, "close", &inputs, close_answer)?;
12200 }
12201 for held in created {
12202 self.learn_item(&held.content, &items[&held.content].0)?;
12203 }
12204 Ok(())
12205 }
12206
12207 /// The board item each of `created` is on this board, with its `Status` as the board set it:
12208 /// [`graphql::CREATED_BOARD_ITEMS`], read again — after a wait of a second, then two, four,
12209 /// eight and sixteen — for only those GitHub has not filed yet.
12210 ///
12211 /// **Membership is never assumed.** `createIssue`'s `projectV2Ids` files an issue some time
12212 /// after GitHub answered the create — the feasibility spike saw 0.45 to 1.84 seconds, and no
12213 /// create answer carrying the item — so only a read says it is there. One still absent once
12214 /// those reads are spent is filed with [`graphql::ADD_TO_BOARD`], one write each; GitHub
12215 /// filing it meanwhile refuses that "Content already exists in this project", which says it
12216 /// is placed, and one more read finds the item rather than a second one being made.
12217 async fn created_board_items(
12218 &self,
12219 board: &str,
12220 created: &[HeldBack],
12221 ) -> Result<BTreeMap<NativeId, (String, Option<String>)>, SourceError> {
12222 let mut found: BTreeMap<NativeId, (String, Option<String>)> = BTreeMap::new();
12223 let unfiled = |found: &BTreeMap<NativeId, (String, Option<String>)>| -> Vec<NativeId> {
12224 created
12225 .iter()
12226 .map(|held| held.content.clone())
12227 .filter(|id| !found.contains_key(id))
12228 .collect()
12229 };
12230 let mut wait = Duration::from_secs(1);
12231 for attempt in 0..6 {
12232 let absent = unfiled(&found);
12233 if absent.is_empty() {
12234 return Ok(found);
12235 }
12236 if attempt > 0 {
12237 self.clock
12238 .sleep_because(wait, pacing::cause::BOARD_FILING)
12239 .await;
12240 wait = wait.saturating_mul(2);
12241 }
12242 self.read_created_items(board, &absent, &mut found).await?;
12243 }
12244 let mut placed_meanwhile = Vec::new();
12245 for id in unfiled(&found) {
12246 match self
12247 .graphql(
12248 graphql::ADD_TO_BOARD,
12249 json!({"input":{"projectId":board,"contentId":id.0}}),
12250 )
12251 .await
12252 {
12253 Ok(added) => {
12254 let item = added
12255 .pointer("/addProjectV2ItemById/item")
12256 .filter(|value| !value.is_null())
12257 .ok_or_else(|| SourceError::Malformed {
12258 message: "GitHub board addition returned no project item".into(),
12259 })?;
12260 found.insert(id, (required_nonblank_str(item, "id")?.to_owned(), None));
12261 }
12262 Err(error) if already_on_the_board(&error) => placed_meanwhile.push(id),
12263 Err(error) => return Err(error),
12264 }
12265 }
12266 if !placed_meanwhile.is_empty() {
12267 self.read_created_items(board, &placed_meanwhile, &mut found)
12268 .await?;
12269 }
12270 let absent = unfiled(&found);
12271 if absent.is_empty() {
12272 return Ok(found);
12273 }
12274 let absent: Vec<&str> = absent.iter().map(|id| id.0.as_str()).collect();
12275 Err(SourceError::Unavailable {
12276 message: format!(
12277 "GitHub created {} filed on board {board} and, after 31 seconds and adding {} \
12278 to it, still answers {} on no item of it: {}; next: run the copy again once \
12279 GitHub has caught up",
12280 if absent.len() == 1 {
12281 "an issue"
12282 } else {
12283 "issues"
12284 },
12285 if absent.len() == 1 { "it" } else { "them" },
12286 if absent.len() == 1 { "it" } else { "them" },
12287 absent.join(", ")
12288 ),
12289 })
12290 }
12291
12292 /// One [`graphql::CREATED_BOARD_ITEMS`] read of each of `ids`, [`COPY_DETAIL_BATCH`] to a
12293 /// request, adding to `found` the board item of every one GitHub has filed on `board`.
12294 async fn read_created_items(
12295 &self,
12296 board: &str,
12297 ids: &[NativeId],
12298 found: &mut BTreeMap<NativeId, (String, Option<String>)>,
12299 ) -> Result<(), SourceError> {
12300 for chunk in ids.chunks(COPY_DETAIL_BATCH) {
12301 let mut variables = serde_json::Map::new();
12302 for slot in 0..COPY_DETAIL_BATCH {
12303 variables.insert(
12304 format!("id{slot}"),
12305 json!(chunk.get(slot).unwrap_or(&chunk[0]).0),
12306 );
12307 variables.insert(format!("read{slot}"), json!(slot < chunk.len()));
12308 }
12309 variables.insert("boardItems".into(), json!(BOARD_ITEMS_PAGE_SIZE));
12310 variables.insert("statusName".into(), json!(STATUS_FIELD));
12311 let data = self
12312 .graphql(graphql::CREATED_BOARD_ITEMS, Value::Object(variables))
12313 .await?;
12314 for (slot, id) in chunk.iter().enumerate() {
12315 // An answer for another issue than the one asked about says nothing of
12316 // where that one is filed, and its board item is not this one's.
12317 let node = data.get(format!("i{slot}")).filter(|node| !node.is_null());
12318 let named = node.map(|node| node.get("id").and_then(Value::as_str));
12319 if let Some(named) = named
12320 && named != Some(id.0.as_str())
12321 {
12322 return Err(SourceError::Malformed {
12323 message: format!(
12324 "GitHub answered the board items of {} when asked for those of {}",
12325 named.unwrap_or("an issue it did not name"),
12326 id.0
12327 ),
12328 });
12329 }
12330 // An issue GitHub does not answer yet is not filed yet; one it answers is
12331 // read whole, its connection, each board item's board and its status, and
12332 // any of them unreadable is refused rather than read as not filed.
12333 let Some(node) = node else { continue };
12334 let malformed = |what: &str| SourceError::Malformed {
12335 message: format!("GitHub answered the board items of {} with {what}", id.0),
12336 };
12337 let nodes = node
12338 .pointer("/projectItems/nodes")
12339 .and_then(Value::as_array)
12340 .ok_or_else(|| malformed("no list of board items"))?;
12341 let mut item = None;
12342 for node in nodes {
12343 let on = node
12344 .pointer("/project/id")
12345 .and_then(Value::as_str)
12346 .ok_or_else(|| malformed("a board item naming no board"))?;
12347 if on == board {
12348 item = Some(node);
12349 }
12350 }
12351 if let Some(item) = item {
12352 let status = match item.get("status") {
12353 None | Some(Value::Null) => None,
12354 Some(status) => Some(
12355 status
12356 .get("name")
12357 .and_then(Value::as_str)
12358 .ok_or_else(|| malformed("a status that names no option"))?
12359 .to_owned(),
12360 ),
12361 };
12362 found.insert(
12363 id.clone(),
12364 (required_nonblank_str(item, "id")?.to_owned(), status),
12365 );
12366 }
12367 }
12368 }
12369 Ok(())
12370 }
12371
12372 /// The board item id of `content`, which this process created and remembered without one,
12373 /// in every half of its own view.
12374 fn learn_item(&self, content: &NativeId, item: &str) -> Result<(), SourceError> {
12375 if let Some(held) = self.resolved_cache()?.get_mut(content) {
12376 held.item_id = item.to_owned();
12377 }
12378 if let Some(held) = self.created()?.iter_mut().find(|held| held.id == *content) {
12379 held.item_id = item.to_owned();
12380 }
12381 Ok(())
12382 }
12383
12384 /// Ask together which items each of `origins` names, and what creating an item reads; see
12385 /// [`TaskSource::read_ahead_origins_for_copy`]. An origin whose answer runs past its first
12386 /// page is left to its own lookup.
12387 async fn origins_ahead(&self, origins: &[String]) -> Result<(), SourceError> {
12388 if self.repository.is_none() {
12389 return Ok(());
12390 }
12391 let unasked: Vec<&String> = {
12392 let held = self.narrowed_cache()?;
12393 let mut unasked: Vec<&String> = Vec::new();
12394 for origin in origins {
12395 if !held.contains_key(&Narrowing::Origin(origin.clone()).key())
12396 && !unasked.contains(&origin)
12397 {
12398 unasked.push(origin);
12399 }
12400 }
12401 unasked
12402 };
12403 if unasked.is_empty() {
12404 return Ok(());
12405 }
12406 // One batch is held back for the read ahead that follows, which may carry a project's
12407 // members beside it in the same request.
12408 if unasked.len() <= ORIGIN_BATCH {
12409 let mut pending =
12410 self.pending_origins
12411 .lock()
12412 .map_err(|_| SourceError::Unavailable {
12413 message:
12414 "origins held for a read ahead were left inconsistent; run the command \
12415 again"
12416 .into(),
12417 })?;
12418 for origin in unasked {
12419 if !pending.contains(origin) {
12420 pending.push(origin.clone());
12421 }
12422 }
12423 return Ok(());
12424 }
12425 let unasked: Vec<String> = unasked.into_iter().cloned().collect();
12426 self.send_origin_lookups(&unasked, None).await
12427 }
12428
12429 /// Hold, for [`TaskSource::member_classifications`] of `project`, each member's
12430 /// classification and repositories as the members page `data` carries them — when that page
12431 /// is every member, each one names `project` as its parent, and every record it holds is
12432 /// readable. Any other page holds nothing, so the members are read as they always were.
12433 fn hold_member_classes(&self, project: &NativeId, data: &Value) -> Result<(), SourceError> {
12434 let Some(page) = data
12435 .pointer("/members/subIssues")
12436 .filter(|page| !page.is_null())
12437 else {
12438 return Ok(());
12439 };
12440 if page
12441 .pointer("/pageInfo/hasNextPage")
12442 .and_then(Value::as_bool)
12443 != Some(false)
12444 {
12445 return Ok(());
12446 }
12447 let Some(nodes) = page.get("nodes").and_then(Value::as_array) else {
12448 return Ok(());
12449 };
12450 let mut members = Vec::with_capacity(nodes.len());
12451 for node in nodes {
12452 if node.pointer("/parent/id").and_then(Value::as_str) != Some(project.0.as_str()) {
12453 return Ok(());
12454 }
12455 let Some(body) = node.get("body").and_then(Value::as_str) else {
12456 return Ok(());
12457 };
12458 // Every node here is filed under `project`, which `BoardKind::of` reads as one of its
12459 // tasks whatever its marker says, so each is a member the full read would classify.
12460 let Ok((_, slot)) = metadata_body(Some(body.to_owned())) else {
12461 return Ok(());
12462 };
12463 let Ok(classification) = Classification::from_metadata(&slot) else {
12464 return Ok(());
12465 };
12466 let repositories = if slot.contains_key(Repository::METADATA_KEY) {
12467 let Ok(repositories) = Repository::from_metadata(&slot) else {
12468 return Ok(());
12469 };
12470 repositories
12471 } else {
12472 let Some(origin) = node
12473 .pointer("/repository/nameWithOwner")
12474 .and_then(Value::as_str)
12475 else {
12476 return Ok(());
12477 };
12478 let Ok(own) = Repository::try_from(format!("{}/{origin}", RepositoryTarget::HOST))
12479 else {
12480 return Ok(());
12481 };
12482 vec![own]
12483 };
12484 members.push((classification, repositories));
12485 }
12486 self.member_classes
12487 .lock()
12488 .map_err(|_| SourceError::Unavailable {
12489 message: "a project's members held for its classification were left \
12490 inconsistent; run the command again"
12491 .into(),
12492 })?
12493 .insert(project.clone(), members);
12494 Ok(())
12495 }
12496
12497 /// Send every origin held back for the read ahead, beside the members of `members` when it
12498 /// names a project — or nothing, when none is held.
12499 async fn send_pending_origins(&self, members: Option<&NativeId>) -> Result<(), SourceError> {
12500 let pending = std::mem::take(&mut *self.pending_origins.lock().map_err(|_| {
12501 SourceError::Unavailable {
12502 message: "origins held for a read ahead were left inconsistent; run the command \
12503 again"
12504 .into(),
12505 }
12506 })?);
12507 if pending.is_empty() {
12508 return Ok(());
12509 }
12510 self.send_origin_lookups(&pending, members).await
12511 }
12512
12513 /// [`graphql::ORIGIN_LOOKUPS`] of `unasked`, [`ORIGIN_BATCH`] to a request — the first one
12514 /// [`graphql::ORIGIN_LOOKUPS_WITH_MEMBERS`], carrying the members of `members`, when it names
12515 /// a project — holding each origin's answer and, from a members page that is the whole of
12516 /// them, each member's classification.
12517 async fn send_origin_lookups(
12518 &self,
12519 unasked: &[String],
12520 members: Option<&NativeId>,
12521 ) -> Result<(), SourceError> {
12522 let Some(repository) = self.repository.clone() else {
12523 return Ok(());
12524 };
12525 let mut members = members;
12526 for chunk in unasked.chunks(ORIGIN_BATCH) {
12527 let mut variables = json!({"owner":self.owner,"number":self.project_number,
12528 "type":"ISSUE","lookupFirst":ORIGIN_LOOKUPS_PAGE_SIZE,"nestedFirst":NESTED_PAGE_SIZE,
12529 "boardItems":BOARD_ITEMS_PAGE_SIZE,"duplicates":true,
12530 "repositoryOwner":repository.owner,"repositoryName":repository.name});
12531 for slot in 0..ORIGIN_BATCH {
12532 let origin = chunk.get(slot).unwrap_or(&chunk[0]);
12533 variables[format!("filter{slot}")] =
12534 json!(format!("{ORIGIN_FIELD}:{}", quoted(origin)));
12535 variables[format!("search{slot}")] = json!(
12536 self.board_search(Some(&format!("in:body {}", quoted(&as_stored(origin)))))
12537 );
12538 variables[format!("ask{slot}")] = json!(slot < chunk.len());
12539 }
12540 let project = members.take();
12541 let document = match project {
12542 Some(project) => {
12543 variables["project"] = json!(project.0);
12544 variables["memberFirst"] = json!(MEMBER_PAGE_SIZE);
12545 graphql::ORIGIN_LOOKUPS_WITH_MEMBERS
12546 }
12547 None => graphql::ORIGIN_LOOKUPS,
12548 };
12549 let data = self.graphql(document, variables).await?;
12550 self.fields_read(&data)?;
12551 if let Some(project) = project {
12552 self.hold_member_classes(project, &data)?;
12553 }
12554 if let Some(node) = data.get("repository").filter(|value| !value.is_null()) {
12555 let id = required_nonblank_str(node, "id")?.to_owned();
12556 self.repository_cache()?.insert(repository.clone(), id);
12557 if let Some(numeric) = node
12558 .get("databaseId")
12559 .and_then(Value::as_u64)
12560 .and_then(std::num::NonZeroU64::new)
12561 {
12562 self.numeric_repositories
12563 .lock()
12564 .await
12565 .insert(repository.clone(), numeric);
12566 }
12567 }
12568 for (slot, origin) in chunk.iter().enumerate() {
12569 let items = data
12570 .pointer(&format!("/o{slot}/projectV2/items"))
12571 .filter(|value| !value.is_null())
12572 .ok_or_else(|| SourceError::Refused {
12573 message: format!(
12574 "GitHub project {}/{} was not found or is not visible to the token",
12575 self.owner, self.project_number
12576 ),
12577 })?;
12578 let searched =
12579 data.get(format!("s{slot}"))
12580 .ok_or_else(|| SourceError::Malformed {
12581 message: "GitHub search response has no search connection".into(),
12582 })?;
12583 if resumed(items, None)?.has_more() || resumed(searched, None)?.has_more() {
12584 continue;
12585 }
12586 let mut found: Vec<Resolved> = Vec::new();
12587 for item in optional_nodes(Some(items), "project items")?
12588 .into_iter()
12589 .flatten()
12590 {
12591 if let Some(resolved) = self.resolve(item)?
12592 && resolved.content_kind == ContentKind::Issue
12593 && !found.iter().any(|held| held.id == resolved.id)
12594 {
12595 found.push(resolved);
12596 }
12597 }
12598 for node in optional_nodes(Some(searched), "search")?
12599 .into_iter()
12600 .flatten()
12601 {
12602 if let Some(resolved) = self.resolve_issue(node).await?
12603 && !found.iter().any(|held| held.id == resolved.id)
12604 {
12605 found.push(resolved);
12606 }
12607 }
12608 self.narrowed_cache()?
12609 .insert(Narrowing::Origin((*origin).clone()).key(), found);
12610 }
12611 }
12612 Ok(())
12613 }
12614
12615 /// Delete every issue of `ids`, [`DELETE_BATCH`] to a request with
12616 /// [`graphql::DELETE_ISSUES`], and answer those still there: each a request's answer does not
12617 /// confirm, every one of a request refused whole included.
12618 async fn delete_issues(&self, ids: &[&NativeId]) -> Vec<NativeId> {
12619 let mut left = Vec::new();
12620 for chunk in ids.chunks(DELETE_BATCH) {
12621 let mut variables = serde_json::Map::new();
12622 for slot in 0..DELETE_BATCH {
12623 let id = chunk.get(slot).unwrap_or(&chunk[0]);
12624 variables.insert(format!("delete{slot}"), json!({"issueId": id.0}));
12625 variables.insert(format!("send{slot}"), json!(slot < chunk.len()));
12626 }
12627 let data = self
12628 .graphql(graphql::DELETE_ISSUES, Value::Object(variables))
12629 .await
12630 .unwrap_or(Value::Null);
12631 for (slot, id) in chunk.iter().enumerate() {
12632 // Confirmed only by the repository the deleted issue was in, named by a
12633 // non-blank id: anything else says nothing of whether the issue is gone.
12634 let confirmed = data
12635 .pointer(&format!("/delete{slot}/repository/id"))
12636 .and_then(Value::as_str)
12637 .is_some_and(|id| !id.trim().is_empty());
12638 if !confirmed {
12639 left.push((*id).clone());
12640 }
12641 }
12642 }
12643 left
12644 }
12645
12646 /// Delete one issue, which takes its board item with it.
12647 async fn delete_issue(&self, id: &NativeId) -> Result<(), SourceError> {
12648 let data = self
12649 .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12650 .await?;
12651 data.pointer("/deleteIssue/repository")
12652 .filter(|value| !value.is_null())
12653 .ok_or_else(|| SourceError::Malformed {
12654 message: "GitHub issue deletion returned no repository".into(),
12655 })?;
12656 self.forget(id)?;
12657 Ok(())
12658 }
12659
12660 /// Remove one item this copy created, so a copy that could not finish leaves the board
12661 /// as it found it.
12662 ///
12663 /// Deleting the issue takes its board item with it, so there is no second mutation to
12664 /// keep in step. An id the board does not hold is not an error: the item is already
12665 /// gone, which is the state this asks for. Which that is, is decided by reading the item
12666 /// by its own id — a listing of the board can still be missing an item it holds, and
12667 /// reading that as *already gone* would leave behind the very item this was asked to
12668 /// take back.
12669 async fn delete_item(&self, id: &NativeId) -> Result<(), SourceError> {
12670 let Some(item) = self.bound_item(id).await? else {
12671 return Ok(());
12672 };
12673 if item.content_kind == ContentKind::DraftIssue {
12674 return Err(SourceError::Refused {
12675 message: format!(
12676 "GitHub item {} is a draft, and this source removes an item by deleting \
12677 its issue; next: remove it from the board by hand",
12678 id.0
12679 ),
12680 });
12681 }
12682 let data = self
12683 .graphql(graphql::DELETE_ISSUE, json!({"input":{"issueId":id.0}}))
12684 .await?;
12685 data.pointer("/deleteIssue/repository")
12686 .filter(|value| !value.is_null())
12687 .ok_or_else(|| SourceError::Malformed {
12688 message: "GitHub issue deletion returned no repository".into(),
12689 })?;
12690 self.forget(id)?;
12691 Ok(())
12692 }
12693
12694 /// The issue a comment call on `task` is about, or `None` when this board holds no such
12695 /// task.
12696 ///
12697 /// Resolved exactly as [`TaskSource::get_task`] resolves it, so the comment verbs and a
12698 /// read of the task cannot disagree about which ids name one: a project or a document of
12699 /// this board is not a task here either.
12700 ///
12701 /// A **draft** is a task with nowhere to keep a comment, because GitHub keeps comments on
12702 /// issues and a draft is not one. It is refused rather than answered with an empty page,
12703 /// which would read as a task nobody has commented on yet.
12704 async fn commented_issue(&self, task: &NativeId) -> Result<Option<NativeId>, SourceError> {
12705 let cached = self.resolved_cache()?.get(task).cloned();
12706 let Some(item) = (match cached {
12707 Some(item) => Some(item),
12708 None => self.item_by_id(task).await?,
12709 })
12710 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
12711 return Ok(None);
12712 };
12713 if item.content_kind == ContentKind::DraftIssue {
12714 return Err(self.draft_has_no_comments(task));
12715 }
12716 Ok(Some(item.id))
12717 }
12718
12719 /// The refusal a comment call on a board draft is answered with: GitHub keeps comments on
12720 /// issues, and a draft is not one.
12721 fn draft_has_no_comments(&self, task: &NativeId) -> SourceError {
12722 SourceError::Refused {
12723 message: format!(
12724 "task {} of source {} is a draft item on the board, and GitHub keeps \
12725 comments on issues alone, so a draft has none to read or write; next: \
12726 convert the draft to an issue on the board, then comment on the issue it \
12727 becomes",
12728 task.0, self.name
12729 ),
12730 }
12731 }
12732
12733 /// One task and a page of its comments, read with [`graphql::ISSUE_DETAIL`] in one
12734 /// request — or `None` when this board holds no task by that id.
12735 ///
12736 /// What `task show` and a comment listing read. A draft is a task with no comments, so it
12737 /// is answered with the draft and the refusal, at the price of the draft's own read.
12738 async fn issue_detail(
12739 &self,
12740 id: &NativeId,
12741 page: &PageRequest,
12742 ) -> Result<Option<TaskDetailRead>, SourceError> {
12743 let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
12744 let asked = self
12745 .graphql(
12746 graphql::ISSUE_DETAIL,
12747 json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),"after":after,
12748 "nestedFirst":NESTED_PAGE_SIZE,"boardItems":BOARD_ITEMS_PAGE_SIZE,
12749 "duplicates":true}),
12750 )
12751 .await;
12752 let data = match asked {
12753 Ok(data) => data,
12754 Err(error) if unresolvable_node(&error) => return Ok(None),
12755 Err(error) => return Err(error),
12756 };
12757 // `node` is null for an id that names nothing, and absent only from an answer this
12758 // source cannot read — never the same thing.
12759 let node = data.get("node").ok_or_else(|| SourceError::Malformed {
12760 message: format!("GitHub answered the read of {} with no node", id.0),
12761 })?;
12762 self.detail_of(id, node, true, after).await
12763 }
12764
12765 /// Several tasks, each with the first page of its comments when `comments` is set, read
12766 /// [`DETAIL_BATCH`] at a time with [`graphql::ISSUE_DETAILS`] — one answer per id, in
12767 /// order.
12768 ///
12769 /// A batch GitHub refuses because one of its ids resolves to no node at all is read again
12770 /// one item at a time, so that id is answered as missing and the others as themselves; any
12771 /// other refusal is every id of that batch's answer.
12772 async fn issue_details(
12773 &self,
12774 ids: &[NativeId],
12775 comments: Option<&PageRequest>,
12776 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
12777 let mut read = Vec::with_capacity(ids.len());
12778 for batch in ids.chunks(DETAIL_BATCH) {
12779 match self
12780 .graphql(graphql::ISSUE_DETAILS, detail_batch(batch, comments))
12781 .await
12782 {
12783 Ok(data) => {
12784 for (slot, id) in batch.iter().enumerate() {
12785 // Every alias asked for is answered, null for an id naming nothing;
12786 // one missing is an answer this source cannot read.
12787 let read_one = match data.get(format!("i{slot}")) {
12788 Some(node) => self.detail_of(id, node, comments.is_some(), None).await,
12789 None => Err(SourceError::Malformed {
12790 message: format!(
12791 "GitHub answered a batch read with no item for {}",
12792 id.0
12793 ),
12794 }),
12795 };
12796 read.push(read_one);
12797 }
12798 }
12799 Err(error) if unresolvable_node(&error) => {
12800 for id in batch {
12801 read.push(match comments {
12802 Some(page) => self.issue_detail(id, page).await,
12803 None => self.task_read(id).await,
12804 });
12805 }
12806 }
12807 Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
12808 }
12809 }
12810 read
12811 }
12812
12813 /// One task and nothing of its comments, as [`TaskSource::get_task`] reads it.
12814 async fn task_read(&self, id: &NativeId) -> Result<Option<TaskDetailRead>, SourceError> {
12815 Ok(self.get_task(id).await?.map(|task| TaskDetailRead {
12816 task,
12817 comments: None,
12818 }))
12819 }
12820
12821 /// What one node a detail read reached says: the task this board holds by `id`, with the
12822 /// page of comments the node carries when `commented` — or `None` for a node that is no
12823 /// task of this board.
12824 ///
12825 /// Resolved as [`Self::item_by_id`] resolves an item: a draft is read again as a draft,
12826 /// and an item this process created answers from this process's own record, which a node
12827 /// read taken moments after the write can still be behind.
12828 async fn detail_of(
12829 &self,
12830 id: &NativeId,
12831 node: &Value,
12832 commented: bool,
12833 after: Option<&str>,
12834 ) -> Result<Option<TaskDetailRead>, SourceError> {
12835 if node.is_null() {
12836 return Ok(None);
12837 }
12838 let draft = optional_str(node, "__typename")? == Some("DraftIssue");
12839 // An issue answered under one id is that id's, or the answer is not one this source
12840 // can report: reporting another issue's task and comments under the qualified id asked
12841 // for would be the one wrong answer here. A draft's own read checks the same.
12842 if !draft
12843 && optional_str(node, "__typename")? == Some("Issue")
12844 && required_str(node, "id")? != id.0
12845 {
12846 return Err(SourceError::Malformed {
12847 message: format!(
12848 "GitHub answered the read of {} with issue {}",
12849 id.0,
12850 required_str(node, "id")?
12851 ),
12852 });
12853 }
12854 let item = if draft {
12855 self.draft_by_id(id).await?
12856 } else {
12857 self.resolve_issue(node).await?
12858 };
12859 // A read that carried the whole of what the issue is blocked by — a copy's — is kept
12860 // for this command, so the dependency read the copy makes next is answered from it.
12861 if let Some(read) = item.as_ref().filter(|item| item.blocked_by.is_some()) {
12862 self.resolved_cache()?.insert(read.id.clone(), read.clone());
12863 }
12864 let Some(item) = item.filter(|item| item.kind == BoardKind::Work(ItemKind::Task)) else {
12865 return Ok(None);
12866 };
12867 let own = self.created()?.iter().find(|own| own.id == *id).cloned();
12868 let task = own.unwrap_or(item).task()?;
12869 let comments = match (commented, draft) {
12870 (false, _) => None,
12871 (true, true) => Some(Err(self.draft_has_no_comments(id))),
12872 (true, false) => Some(comment_page(node, &id.0, after).map(Some)),
12873 };
12874 if commented && !draft && after.is_none() {
12875 self.expected.learn_comments(id, node);
12876 }
12877 Ok(Some(TaskDetailRead { task, comments }))
12878 }
12879
12880 /// Whether the comment `comment` is one of `issue`'s own.
12881 ///
12882 /// Read before an edit or a removal is sent, because GitHub's comment mutations take the
12883 /// comment's id and nothing else: a comment id given against the wrong task would
12884 /// otherwise change a comment on some other issue entirely. An id that names nothing, or
12885 /// names something that is not an issue comment, is a comment this task does not have —
12886 /// which is what GitHub refusing to resolve it means too.
12887 async fn comment_is_on(
12888 &self,
12889 issue: &NativeId,
12890 comment: &NativeId,
12891 ) -> Result<bool, SourceError> {
12892 Ok(self.comment_on(issue, comment).await?.is_some())
12893 }
12894
12895 /// The body the comment `comment` holds, exactly as GitHub holds it, when it is one of
12896 /// `issue`'s own — the read [`Self::comment_is_on`] makes, answering with what it selected.
12897 async fn comment_on(
12898 &self,
12899 issue: &NativeId,
12900 comment: &NativeId,
12901 ) -> Result<Option<String>, SourceError> {
12902 // A write the store's cache expects knows which comments its issue held, and their
12903 // bodies, at the version it expects: what this read would answer.
12904 if let Some(primed) = self.expected.primed_comment(issue, comment) {
12905 return Ok(primed);
12906 }
12907 let asked = self
12908 .graphql(graphql::COMMENT_ISSUE, json!({"id":comment.0}))
12909 .await;
12910 let data = match asked {
12911 Ok(data) => data,
12912 Err(error) if unresolvable_node(&error) => return Ok(None),
12913 Err(error) => return Err(error),
12914 };
12915 let Some(node) = data.get("node").filter(|value| !value.is_null()) else {
12916 return Ok(None);
12917 };
12918 if optional_str(node, "__typename")? != Some("IssueComment") {
12919 return Ok(None);
12920 }
12921 let on = node.get("issue").ok_or_else(|| SourceError::Malformed {
12922 message: format!("GitHub issue comment {} names no issue", comment.0),
12923 })?;
12924 if required_str(on, "id")? != issue.0 {
12925 return Ok(None);
12926 }
12927 Ok(Some(required_str(node, "body")?.to_owned()))
12928 }
12929
12930 /// Which far ends this item's own `blockedBy` relationship holds, and which it cannot.
12931 async fn partition_edges(
12932 &self,
12933 near_kind: BoardKind,
12934 near_content: ContentKind,
12935 carried: Option<&[Value]>,
12936 depends_on: &[DependencyEdge],
12937 ) -> Result<(Vec<String>, Vec<DependencyEdge>), SourceError> {
12938 let mut native = Vec::new();
12939 let mut fallback = Vec::new();
12940 let far_ends: Vec<(&DependencyEdge, &str, bool, Option<&Value>)> = depends_on
12941 .iter()
12942 .map(|edge| {
12943 // An opaque far end names another tracker, so it is never this board's own.
12944 let same_source = edge.to.designator().is_none()
12945 && edge
12946 .to
12947 .source()
12948 .is_none_or(|source| source == self.name.as_str());
12949 // A qualified id's source segment runs to its *first* colon — `GlobalId` and
12950 // `DependencyEndpoint::source` both read it that way — and a native id may hold
12951 // colons of its own, so the far end is everything after that one separator.
12952 // Splitting at the last would truncate `work:urn:task:7` to `7`.
12953 let far_id = if edge.to.is_qualified() {
12954 edge.to
12955 .id()
12956 .split_once(':')
12957 .map_or(edge.to.id(), |(_, native)| native)
12958 } else {
12959 edge.to.id()
12960 };
12961 // One that already blocks the near issue was answered by that issue's own
12962 // read, which carried each of its blockers' kinds — an issue every one — so it
12963 // is not read again.
12964 let blocking = carried.and_then(|nodes| {
12965 nodes
12966 .iter()
12967 .find(|node| node.get("id").and_then(Value::as_str) == Some(far_id))
12968 });
12969 (edge, far_id, same_source, blocking)
12970 })
12971 .collect();
12972 // Every other same-source far end is read by its own id, exactly as the item it is a
12973 // far end of is: whether this board holds it is that read's answer, never a listing's.
12974 // They are read together, [`DETAIL_BATCH`] to a request, rather than one each.
12975 let mut unread: Vec<NativeId> = Vec::new();
12976 for (_, far_id, same_source, blocking) in &far_ends {
12977 let id = NativeId((*far_id).to_owned());
12978 if *same_source && blocking.is_none() && !unread.contains(&id) {
12979 unread.push(id);
12980 }
12981 }
12982 let read: BTreeMap<NativeId, Option<Resolved>> = unread
12983 .iter()
12984 .cloned()
12985 .zip(self.items_by_ids(&unread).await?)
12986 .collect();
12987 for (edge, far_id, same_source, blocking) in far_ends {
12988 let far = match (same_source, blocking) {
12989 (false, _) => None,
12990 (true, Some(node)) => Some(FarEnd {
12991 kind: if required_str(node, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
12992 BoardKind::Document
12993 } else {
12994 BoardKind::Work(related_kind(node, self.sub_issues)?)
12995 },
12996 content_kind: ContentKind::Issue,
12997 }),
12998 (true, None) => {
12999 let read = read
13000 .get(&NativeId(far_id.to_owned()))
13001 .cloned()
13002 .flatten()
13003 .ok_or_else(|| SourceError::Refused {
13004 message: format!("GitHub dependency item {far_id} was not found"),
13005 })?;
13006 Some(FarEnd {
13007 kind: read.kind,
13008 content_kind: read.content_kind,
13009 })
13010 }
13011 };
13012 let far = far.as_ref();
13013 // The caller says which kind the far end is, and this board holds the far end
13014 // itself, so a disagreement is settled here rather than stored: recorded, the
13015 // wrong kind would read back as a cross-level edge that never existed; written
13016 // natively, it would name a relationship of a different level than the caller
13017 // asked for.
13018 //
13019 // A far end this board holds as a *document* fails the same comparison and is
13020 // refused by the same sentence: `ItemKind` has no document variant because
13021 // nothing may point at one, so no caller can name it correctly and the refusal
13022 // is the only honest answer.
13023 if let Some(disagreeing) = far.filter(|far| far.kind != BoardKind::Work(edge.to.kind)) {
13024 return Err(SourceError::Refused {
13025 message: format!(
13026 "GitHub dependency item {far_id} is a {} of this board, and this item \
13027 names it as a {}; record the kind it is",
13028 disagreeing.kind.describes(),
13029 edge.to.kind.marker()
13030 ),
13031 });
13032 }
13033 // A draft has neither `blockedBy` nor `blocking`, so no edge of one is native
13034 // however the far end is spelled — and one classified native here would be
13035 // written nowhere at all, because a draft's native reconciliation never runs.
13036 let native_here = near_content == ContentKind::Issue
13037 && far.is_some_and(|far| {
13038 far.content_kind == ContentKind::Issue
13039 && BoardKind::Work(edge.to.kind) == near_kind
13040 });
13041 if native_here {
13042 native.push(far_id.to_owned());
13043 } else {
13044 fallback.push(edge.clone());
13045 }
13046 }
13047 Ok((native, fallback))
13048 }
13049
13050 async fn update_existing(
13051 &self,
13052 item: &Resolved,
13053 incoming: &Incoming<'_>,
13054 body: &Option<String>,
13055 status_target: Option<&StatusTarget>,
13056 ) -> Result<(), SourceError> {
13057 let title = incoming.written_title();
13058 // A terminal status closes the issue here, in the same mutation as its body: its board
13059 // option was selected before this, so a close never lands on an item whose board cannot
13060 // show it.
13061 let mut fields = match item.content_kind {
13062 ContentKind::DraftIssue => json!({"title":title,"body":body}),
13063 ContentKind::Issue => json!({"title":title,"body":body,
13064 "stateInput":state_input(status_target)}),
13065 };
13066 // The people it is to be assigned to, replacing whoever it holds — sent only when they
13067 // are not exactly those, and looked up before anything of this write was sent.
13068 if let Some(people) = incoming.assignees
13069 && item
13070 .assignees
13071 .as_deref()
13072 .is_none_or(|held| !assignees::same_people(held, people))
13073 {
13074 if item.content_kind == ContentKind::DraftIssue {
13075 return Err(self.assigns_a_draft());
13076 }
13077 fields["assigneeIds"] = json!(self.people_ids(people, &item.written_name())?);
13078 }
13079 // Only the members whose value differs from the item as this write read it are sent,
13080 // and nothing at all when none does — whether or not the store's cache expects a
13081 // version of it. A member left out is one GitHub leaves as it is, so a person's edit
13082 // of it since that read is kept rather than overwritten with what it already held,
13083 // and a re-copy of an unchanged item costs no mutation.
13084 if let Some(members) = fields.as_object_mut() {
13085 if members.get("title").and_then(Value::as_str) == Some(item.title.as_str()) {
13086 members.remove("title");
13087 }
13088 let body_unchanged = match (members.get("body"), item.raw_body.as_deref()) {
13089 (Some(Value::String(sent)), Some(held)) => sent == held,
13090 (Some(Value::Null), held) => held.is_none_or(str::is_empty),
13091 _ => false,
13092 };
13093 if body_unchanged {
13094 members.remove("body");
13095 }
13096 // An issue already in the state the target asks for keeps it: an open one stays
13097 // open, and a closed one whose closure reads as the target's category keeps its
13098 // reason — a duplicate's says more than this write would.
13099 let unchanged_state = match status_target {
13100 Some(StatusTarget::Terminal(_, reason)) => {
13101 item.closed
13102 && closed_category(item.reason.as_deref())
13103 == closed_category(Some(reason.reason()))
13104 }
13105 Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => !item.closed,
13106 None => true,
13107 };
13108 if unchanged_state {
13109 members.remove("stateInput");
13110 }
13111 if members.is_empty() {
13112 return Ok(());
13113 }
13114 }
13115 self.update_content(item.content_kind, &item.id, fields)
13116 .await
13117 }
13118
13119 /// Update one board item's content with exactly `fields` beside its id, through the
13120 /// mutation its kind takes: `updateIssue` for an issue, `updateProjectV2DraftIssue` for
13121 /// a draft.
13122 ///
13123 /// Every input field either mutation leaves out is a field GitHub leaves as it is, which
13124 /// is what lets a narrow write carry the one thing it changes and nothing else.
13125 async fn update_content(
13126 &self,
13127 kind: ContentKind,
13128 id: &NativeId,
13129 fields: Value,
13130 ) -> Result<(), SourceError> {
13131 let (operation, id_key, pointer) = match kind {
13132 ContentKind::DraftIssue => (
13133 graphql::UPDATE_DRAFT,
13134 "draftIssueId",
13135 "/updateProjectV2DraftIssue/draftIssue",
13136 ),
13137 ContentKind::Issue => (graphql::UPDATE_ISSUE, "id", "/updateIssue/issue"),
13138 };
13139 if kind == ContentKind::Issue && self.hold_issue(&fields)? {
13140 return Ok(());
13141 }
13142 if kind == ContentKind::Issue && self.hold_update(id, &fields)? {
13143 return Ok(());
13144 }
13145 let mut input = fields;
13146 input[id_key] = json!(id.0);
13147 self.send_update(operation, pointer, id, input).await
13148 }
13149
13150 /// Send one item's update, `input`, as `operation`, and hold GitHub's answer at `pointer`
13151 /// to naming that item, `id`.
13152 async fn send_update(
13153 &self,
13154 operation: &str,
13155 pointer: &str,
13156 id: &NativeId,
13157 input: Value,
13158 ) -> Result<(), SourceError> {
13159 let data = match self.graphql(operation, json!({"input":&input})).await {
13160 Ok(data) => data,
13161 Err(error) => return Err(self.refusing_people(&input, error)),
13162 };
13163 let returned = data
13164 .pointer(pointer)
13165 .ok_or_else(|| SourceError::Malformed {
13166 message: "GitHub item update returned no item".into(),
13167 })?;
13168 if required_str(returned, "id")? != id.0 {
13169 return Err(SourceError::Malformed {
13170 message: "GitHub item update returned the wrong item".into(),
13171 });
13172 }
13173 self.assigned_as_asked(&input, Some(returned))
13174 }
13175
13176 /// Creates one issue, files it on the board, and reports what a read of it would say:
13177 /// its content id, its board item id, and the web address GitHub gave it.
13178 ///
13179 /// Two calls rather than one: `createIssue` answers with an issue that is on no board,
13180 /// and `addProjectV2ItemById` is what puts it there. Filing it at creation through
13181 /// `CreateIssueInput.projectV2Ids` was tried and is not done: GitHub answered with no
13182 /// board item, and the `addProjectV2ItemById` that then had to follow was refused
13183 /// "Content already exists in this project". A terminal status is not written here:
13184 /// `finish_write` selects its option first and closes the issue after, so a close never
13185 /// lands on an item whose board cannot show it.
13186 ///
13187 /// The address and the number come back here because this is the only place either is
13188 /// known before GitHub's own board read catches up — an item this run created answers
13189 /// the reads that follow it out of the record below, and one remembered without them
13190 /// would report no location and no key for the rest of the run.
13191 async fn create_and_file_issue(
13192 &self,
13193 board_id: &str,
13194 repository: &RepositoryTarget,
13195 incoming: &Incoming<'_>,
13196 body: &Option<String>,
13197 ) -> Result<Landed, SourceError> {
13198 let repository_id = self.repository_id(repository, incoming).await?;
13199 let mut input = json!({
13200 "repositoryId":repository_id,"title":incoming.written_title(),"body":body
13201 });
13202 self.assigning(&mut input, incoming)?;
13203 let data = match self
13204 .graphql(graphql::CREATE_ISSUE, json!({"input": &input}))
13205 .await
13206 {
13207 Ok(data) => data,
13208 Err(error) => return Err(self.refusing_people(&input, error)),
13209 };
13210 let created = data
13211 .pointer("/createIssue/issue")
13212 .filter(|value| !value.is_null())
13213 .ok_or_else(|| SourceError::Malformed {
13214 message: "GitHub issue creation returned no issue".into(),
13215 })?;
13216 let content_id = NativeId(required_str(created, "id")?.to_owned());
13217 // Assigned otherwise than asked, the issue is refused and taken back as the filed
13218 // create's is, a refused delete answered beside the refusal.
13219 if let Err(error) = self.assigned_as_asked(&input, Some(created)) {
13220 return Err(self.taken_back(&content_id, created, error).await);
13221 }
13222 // Optional although GitHub's schema makes it non-null: the issue exists by now, so
13223 // a response without it is not worth failing a landed write over — the item simply
13224 // reports no location until the board read catches up, which is what it did before.
13225 let url = optional_str(created, "url")?.map(str::to_owned);
13226 // The issue exists from here on, so an unreadable number and a refused board
13227 // filing below each try, best effort, to take it back: an issue in the repository
13228 // that is on no board is an item nobody asked for and nothing here would find again.
13229 //
13230 // Its number is optional on the same terms its address is — a landed write is not
13231 // worth failing over a member that came back missing, and such an item reports no
13232 // handle until a board read catches up. A number that is *present* and is not an
13233 // unsigned integer is still a response this source cannot read.
13234 let number = match created_issue_number(created) {
13235 Ok(number) => number,
13236 Err(error) => {
13237 let _ = self.delete_issue(&content_id).await;
13238 return Err(error);
13239 }
13240 };
13241 let added = match self
13242 .graphql(
13243 graphql::ADD_TO_BOARD,
13244 json!({"input":{"projectId":board_id,"contentId":content_id.0}}),
13245 )
13246 .await
13247 {
13248 Ok(added) => added,
13249 Err(error) => {
13250 let _ = self.delete_issue(&content_id).await;
13251 return Err(error);
13252 }
13253 };
13254 let item = added
13255 .pointer("/addProjectV2ItemById/item")
13256 .filter(|value| !value.is_null())
13257 .ok_or_else(|| SourceError::Malformed {
13258 message: "GitHub board addition returned no project item".into(),
13259 })?;
13260 self.note_written(&content_id, url.as_deref());
13261 Ok(Landed {
13262 content_id,
13263 item_id: Some(required_str(item, "id")?.to_owned()),
13264 url,
13265 number,
13266 })
13267 }
13268
13269 /// Move one issue under the project it now belongs to, or out of the one it left.
13270 async fn reparent(
13271 &self,
13272 held: Option<NativeId>,
13273 child: &NativeId,
13274 wanted: Option<&NativeId>,
13275 ) -> Result<(), SourceError> {
13276 if held.as_ref() == wanted {
13277 return Ok(());
13278 }
13279 if let Some(held) = &held {
13280 self.sub_issue(graphql::REMOVE_SUB_ISSUE, held, child, "removeSubIssue")
13281 .await?;
13282 }
13283 if let Some(wanted) = wanted {
13284 self.sub_issue(graphql::ADD_SUB_ISSUE, wanted, child, "addSubIssue")
13285 .await?;
13286 }
13287 Ok(())
13288 }
13289
13290 async fn sub_issue(
13291 &self,
13292 operation: &str,
13293 parent: &NativeId,
13294 child: &NativeId,
13295 root: &str,
13296 ) -> Result<(), SourceError> {
13297 let data = self
13298 .graphql(
13299 operation,
13300 json!({"input":{"issueId":parent.0,"subIssueId":child.0}}),
13301 )
13302 .await?;
13303 let issue =
13304 data.pointer(&format!("/{root}/issue"))
13305 .ok_or_else(|| SourceError::Malformed {
13306 message: "GitHub sub-issue update returned no issue".into(),
13307 })?;
13308 let sub =
13309 data.pointer(&format!("/{root}/subIssue"))
13310 .ok_or_else(|| SourceError::Malformed {
13311 message: "GitHub sub-issue update returned no sub-issue".into(),
13312 })?;
13313 if required_str(issue, "id")? != parent.0 || required_str(sub, "id")? != child.0 {
13314 return Err(SourceError::Malformed {
13315 message: "GitHub sub-issue update returned the wrong issues".into(),
13316 });
13317 }
13318 Ok(())
13319 }
13320
13321 /// Bring one issue's `blockedBy` to exactly `native`, sending only the difference, and say
13322 /// whether there was one.
13323 ///
13324 /// An issue [`Issue::Created`] by this very write is blocked by nothing yet, so its
13325 /// relationships are not read: there is nothing a read of them could find.
13326 async fn reconcile_blocked_by(
13327 &self,
13328 content_id: &NativeId,
13329 native: &[String],
13330 issue: Issue<'_>,
13331 ) -> Result<bool, SourceError> {
13332 let current = match issue {
13333 Issue::Created => Vec::new(),
13334 Issue::Existing(Some(held)) => held
13335 .iter()
13336 .map(|far| required_str(far, "id").map(str::to_owned))
13337 .collect::<Result<Vec<_>, _>>()?,
13338 Issue::Existing(None) => self.native_dependency_ids(content_id).await?,
13339 };
13340 let mut changed = false;
13341 for (operation, far_id) in current
13342 .iter()
13343 .filter(|id| !native.contains(id))
13344 .map(|id| (graphql::REMOVE_BLOCKED_BY, id))
13345 .chain(
13346 native
13347 .iter()
13348 .filter(|id| !current.contains(id))
13349 .map(|id| (graphql::ADD_BLOCKED_BY, id)),
13350 )
13351 {
13352 let data = self
13353 .graphql(
13354 operation,
13355 json!({"input":{"issueId":content_id.0,"blockingIssueId":far_id}}),
13356 )
13357 .await?;
13358 let root = if operation == graphql::ADD_BLOCKED_BY {
13359 "addBlockedBy"
13360 } else {
13361 "removeBlockedBy"
13362 };
13363 let issue =
13364 data.pointer(&format!("/{root}/issue"))
13365 .ok_or_else(|| SourceError::Malformed {
13366 message: "GitHub dependency update returned no issue".into(),
13367 })?;
13368 let blocker = data
13369 .pointer(&format!("/{root}/blockingIssue"))
13370 .ok_or_else(|| SourceError::Malformed {
13371 message: "GitHub dependency update returned no blocking issue".into(),
13372 })?;
13373 if required_str(issue, "id")? != content_id.0 || required_str(blocker, "id")? != far_id
13374 {
13375 return Err(SourceError::Malformed {
13376 message: "GitHub dependency update returned the wrong issues".into(),
13377 });
13378 }
13379 changed = true;
13380 }
13381 Ok(changed)
13382 }
13383}
13384
13385/// The board field values one write sends, in the order GitHub runs them, and the fields it
13386/// clears after them: the origin field when it moves, the `Status` option `column` names, the
13387/// priority, then each projected field.
13388fn field_writes<'a>(
13389 existing: Option<&Resolved>,
13390 origin_field: Option<&str>,
13391 origin: &str,
13392 column: Option<(String, String)>,
13393 priority: Option<&'a PriorityWrite>,
13394 projections: &'a [ProjectionWrite],
13395) -> (Vec<(String, Value)>, Vec<&'a str>) {
13396 let mut fields = Vec::new();
13397 if let Some(field_id) = origin_field
13398 && existing.map_or(!origin.is_empty(), |item| {
13399 item.origin.as_deref().unwrap_or("") != origin
13400 })
13401 {
13402 fields.push((field_id.to_owned(), json!({"text":origin})));
13403 }
13404 if let Some((field_id, option_id)) = column {
13405 fields.push((field_id, json!({"singleSelectOptionId":option_id})));
13406 }
13407 let mut clears = Vec::new();
13408 match priority {
13409 Some(PriorityWrite::Select { field, option }) => {
13410 fields.push((field.clone(), json!({"singleSelectOptionId":option})));
13411 }
13412 Some(PriorityWrite::Clear { field }) => clears.push(field.as_str()),
13413 None => {}
13414 }
13415 for projection in projections {
13416 projection.join(&mut fields, &mut clears);
13417 }
13418 (fields, clears)
13419}
13420
13421/// Everything one write decided before sending anything: see
13422/// [`GitHubProjectsSource::prepare_write`].
13423struct Prepared {
13424 /// What the write lands on.
13425 destination: WriteDestination,
13426 board: BoardFields,
13427 status_target: Option<StatusTarget>,
13428 /// The `Status` field, the option and the option's name the status lands on.
13429 // 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.
13430 column: Option<(String, String, String)>,
13431 priority_write: Option<PriorityWrite>,
13432 projections: Vec<ProjectionWrite>,
13433 projected: BTreeMap<String, String>,
13434 content_kind: ContentKind,
13435 own_repository: Option<Repository>,
13436 /// The far ends of the item's native blocked-by relationships.
13437 // 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.
13438 native: Vec<String>,
13439 slot: BTreeMap<String, Value>,
13440 content: Option<String>,
13441 body: Option<String>,
13442 /// The copy origin the item records, empty for none.
13443 // 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.
13444 origin: String,
13445 origin_field: Option<String>,
13446}
13447
13448/// One write a copy held back of the kinds sent together: a board field value, or a blocked-by
13449/// edge, each its input.
13450enum HeldWrite<'a> {
13451 Field(&'a Value),
13452 Edge(&'a Value),
13453}
13454
13455/// Whether `error` is GitHub refusing to file an issue on a board because it is filed there
13456/// already — what `addProjectV2ItemById` answers once `createIssue`'s `projectV2Ids` has placed
13457/// it, rather than answering with the item it holds.
13458fn already_on_the_board(error: &SourceError) -> bool {
13459 error
13460 .to_string()
13461 .contains("Content already exists in this project")
13462}
13463
13464/// Hold every alias `inputs` sent under `prefix` in `data` to answering with what its input
13465/// named — each `(root, named)` of `answers` — and refuse one that answered nothing or another
13466/// item.
13467fn check_aliased_answers(
13468 document: &str,
13469 data: &Value,
13470 prefix: &str,
13471 inputs: &[&Value],
13472 answers: &[(&str, &str)],
13473) -> Result<(), SourceError> {
13474 for (slot, input) in inputs.iter().enumerate() {
13475 for (root, named) in answers {
13476 let answered = data
13477 .pointer(&format!("/{prefix}{slot}/{root}/id"))
13478 .and_then(Value::as_str)
13479 .ok_or_else(|| SourceError::Malformed {
13480 message: format!(
13481 "GitHub answered {} with nothing at {prefix}{slot}",
13482 operation_description(document)
13483 ),
13484 })?;
13485 let asked = input.get(named).and_then(Value::as_str).unwrap_or_default();
13486 if answered != asked {
13487 return Err(SourceError::Malformed {
13488 message: format!(
13489 "GitHub answered {} at {prefix}{slot} with {answered}, which is not \
13490 {asked}, the item it was asked to write",
13491 operation_description(document)
13492 ),
13493 });
13494 }
13495 }
13496 }
13497 Ok(())
13498}
13499
13500/// `error`, which stopped a batch of creates, and — when GitHub refused to take any of them
13501/// back — each issue of `left` it created that is still in the repository, which its caller,
13502/// never handed their ids, could not name.
13503fn left_behind(error: SourceError, left: &[&str]) -> SourceError {
13504 if left.is_empty() {
13505 return error;
13506 }
13507 SourceError::Refused {
13508 message: format!(
13509 "{error}; GitHub then refused to take back {}, which this write created and which \
13510 are still in the repository; next: delete {} before writing again",
13511 left.join(", "),
13512 if left.len() == 1 { "it" } else { "them" }
13513 ),
13514 }
13515}
13516
13517/// What one write lands on: the item it updates, as it stood, or where it creates a new one.
13518enum WriteDestination {
13519 /// The item as it stood, for an update.
13520 Existing(Box<Resolved>),
13521 /// Where a new item is created.
13522 New(RepositoryTarget),
13523}
13524
13525impl WriteDestination {
13526 /// The item an update writes over, as it stood; `None` for a create.
13527 fn existing(&self) -> Option<&Resolved> {
13528 match self {
13529 Self::Existing(item) => Some(item),
13530 Self::New(_) => None,
13531 }
13532 }
13533}
13534
13535/// One existing issue's update held back by [`GitHubProjectsSource::hold_update`]: the issue,
13536/// and the `UpdateIssueInput` its own [`graphql::UPDATE_ISSUE`] would have sent — the members
13537/// it writes beside that issue's id, which only [`Self::new`] sets.
13538struct HeldUpdate {
13539 issue: NativeId,
13540 // llmlint: ignore[invalid_states_unrepresentable] The members are exactly what `update_content` would have sent at once, which every one of its callers builds as GraphQL variables; holding them back changes when they are sent, not what they may be, and only `new` builds one, fixing the issue's id. Typing `UpdateIssueInput` would retype every caller of `update_content`, a change of its own.
13541 input: Value,
13542}
13543
13544impl HeldUpdate {
13545 /// The update writing `members` — an `UpdateIssueInput` without its id — to `issue`.
13546 fn new(issue: &NativeId, members: &Value) -> Self {
13547 let mut input = members.clone();
13548 input["id"] = json!(issue.0);
13549 Self {
13550 issue: issue.clone(),
13551 input,
13552 }
13553 }
13554}
13555
13556/// What a copy has held back of the items it created; see
13557/// [`GitHubProjectsSource::hold_back`].
13558#[derive(Debug, Default)]
13559enum Deferred {
13560 /// Writes are being held back, and nothing has been held yet.
13561 #[default]
13562 Nothing,
13563 /// The items held back, every one of them on `board`.
13564 Held {
13565 /// The board every one of them is on.
13566 board: BoardId,
13567 /// Each created item, in the order it was created.
13568 created: Vec<HeldBack>,
13569 },
13570}
13571
13572impl Deferred {
13573 /// Whether `content` is one of the items held back.
13574 fn holds(&self, content: &NativeId) -> bool {
13575 match self {
13576 Self::Nothing => false,
13577 Self::Held { created, .. } => created.iter().any(|held| held.content == *content),
13578 }
13579 }
13580}
13581
13582/// One created item's parts that land once [`TaskSource::finish_writes`] is called.
13583#[derive(Debug)]
13584struct HeldBack {
13585 /// The issue.
13586 content: NativeId,
13587 /// Its board field values other than its `Status`, in the order they are written.
13588 fields: Vec<(String, Value)>,
13589 /// The `Status` field, and the option and its name that the item's status lands on.
13590 // llmlint: ignore[invalid_states_unrepresentable] The same triple `column_for` returns and `Prepared::column` carries, held back unchanged until it is sent.
13591 status: Option<(String, String, String)>,
13592 /// The fields it clears after those are written.
13593 clears: Vec<String>,
13594 /// The reason it is closed for, once its option is selected; `None` leaves it open.
13595 close: Option<ClosedState>,
13596 /// The issues it is blocked by.
13597 edges: Vec<NativeId>,
13598}
13599
13600/// The member [`answer_with_errors`] carries a response's GraphQL errors under, beside its data:
13601/// no GitHub type has a field of this name.
13602const ANSWER_ERRORS: &str = "onetaskgraphErrors";
13603
13604/// A response's `data` with its GraphQL errors beside it under [`ANSWER_ERRORS`], when it has
13605/// both — or `None`, for an answer [`GitHubProjectsSource::answer`] reads as it always has.
13606///
13607/// What [`graphql::CREATE_ISSUES`] is answered with: GitHub runs a document's mutation fields in
13608/// order and answers each one that ran, so a refusal of one alias leaves the issues the others
13609/// created named in the data beside it — the ids a copy needs to take them back.
13610fn answer_with_errors(body: &str) -> Option<Value> {
13611 let parsed: Value = serde_json::from_str(body).ok()?;
13612 let errors = parsed
13613 .get("errors")?
13614 .as_array()
13615 .filter(|errors| !errors.is_empty())?;
13616 let mut data = parsed.get("data").filter(|data| data.is_object())?.clone();
13617 data[ANSWER_ERRORS] = Value::Array(errors.clone());
13618 Some(data)
13619}
13620
13621/// The `createIssue` input that files the new issue on `board` and, when `incoming` names one,
13622/// under its project — see [`GitHubProjectsSource::create_filed_issue`].
13623fn filed_input(
13624 repository: &str,
13625 board: &str,
13626 incoming: &Incoming<'_>,
13627 body: &Option<String>,
13628) -> Value {
13629 let mut input = json!({"repositoryId":repository,"title":incoming.written_title(),
13630 "body":body,"projectV2Ids":[board]});
13631 if let Some(parent) = incoming.parent {
13632 input["parentIssueId"] = json!(parent.0);
13633 }
13634 input
13635}
13636
13637/// The name of option `option` of field `field` among a board's `fields`.
13638fn option_name<'a>(fields: &'a Value, field: &str, option: &str) -> Option<&'a str> {
13639 fields
13640 .get("nodes")?
13641 .as_array()?
13642 .iter()
13643 .find(|node| node.get("id").and_then(Value::as_str) == Some(field))?
13644 .get("options")?
13645 .as_array()?
13646 .iter()
13647 .find(|candidate| candidate.get("id").and_then(Value::as_str) == Some(option))?
13648 .get("name")?
13649 .as_str()
13650}
13651
13652/// What a write needs to know of one far end it names: which kind of item it is, and whether
13653/// it is an issue a native relationship can name.
13654struct FarEnd {
13655 kind: BoardKind,
13656 content_kind: ContentKind,
13657}
13658
13659/// Whether the issue one write reconciles was created by that write or was already there.
13660#[derive(Clone, Copy, PartialEq, Eq)]
13661enum Issue<'a> {
13662 /// Created by this write, so it holds no relationships yet.
13663 Created,
13664 /// On the board before this write, holding whatever relationships it holds — the far
13665 /// ends of its whole `blockedBy`, when the read that reached it carried them.
13666 Existing(Option<&'a [Value]>),
13667}
13668
13669/// What resolving one node id reached; see [`GitHubProjectsSource::reach`].
13670enum Reached {
13671 /// An issue this board holds, resolved into everything this source reports about it.
13672 Held(Box<Resolved>),
13673 /// Nothing this board holds: no such node, or a node on some other board.
13674 Nothing,
13675 /// A board draft, which [`graphql::ISSUE`] reaches and reads nothing of, so it is read
13676 /// again by [`GitHubProjectsSource::draft_by_id`].
13677 Draft,
13678}
13679
13680/// What GitHub says when a string is not a node id it can resolve.
13681///
13682/// Matched because it is the ordinary answer to a project selector naming a project by its
13683/// *name*, and reporting that as a failure would make naming one impossible. It is read
13684/// off the refusal GitHub sent, never guessed from the shape of the string: this source
13685/// does not define the syntax of a GitHub node id and would be wrong about it.
13686const UNRESOLVABLE_NODE: &str = "could not resolve to a node";
13687
13688/// `error` with `note` added to the end of what it says, its kind and every other member
13689/// unchanged — so a caller still branches on the failure that happened, and reads beside it
13690/// what that failure left behind.
13691fn noting(error: SourceError, note: &str) -> SourceError {
13692 match error {
13693 SourceError::Config { message } => SourceError::Config {
13694 message: message + note,
13695 },
13696 SourceError::Auth { message } => SourceError::Auth {
13697 message: message + note,
13698 },
13699 SourceError::Refused { message } => SourceError::Refused {
13700 message: message + note,
13701 },
13702 SourceError::RateLimited {
13703 retry_after_seconds,
13704 message,
13705 } => SourceError::RateLimited {
13706 retry_after_seconds,
13707 message: Some(message.unwrap_or_default() + note),
13708 },
13709 SourceError::Unavailable { message } => SourceError::Unavailable {
13710 message: message + note,
13711 },
13712 SourceError::Malformed { message } => SourceError::Malformed {
13713 message: message + note,
13714 },
13715 }
13716}
13717
13718/// The variables of one [`graphql::ISSUE_COPY_DETAILS`] request, as [`detail_batch`] binds its
13719/// own: a slot `batch` has no id for is bound to its last id, read again at no added price.
13720fn copy_detail_batch(batch: &[NativeId], comments: &PageRequest, children: bool) -> Value {
13721 let mut variables = serde_json::Map::new();
13722 for slot in 0..COPY_DETAIL_BATCH {
13723 let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13724 variables.insert(format!("id{slot}"), json!(id));
13725 }
13726 variables.insert("project".to_owned(), json!(batch.first().map(|id| &id.0)));
13727 variables.insert("children".to_owned(), json!(children));
13728 variables.insert("first".to_owned(), json!(comments.limit.min(MAX_PAGE_SIZE)));
13729 variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13730 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13731 variables.insert("duplicates".to_owned(), json!(true));
13732 Value::Object(variables)
13733}
13734
13735/// The variables of one [`graphql::ISSUE_DETAILS`] request over `batch` — at most
13736/// [`DETAIL_BATCH`] ids — each item with the first page of its comments when `comments` asks
13737/// for them.
13738///
13739/// The document is fixed-size, so a slot `batch` has no id for is bound to its last id, which
13740/// is read again at no added price.
13741fn detail_batch(batch: &[NativeId], comments: Option<&PageRequest>) -> Value {
13742 let mut variables = serde_json::Map::new();
13743 for slot in 0..DETAIL_BATCH {
13744 let id = batch.get(slot).or(batch.last()).map(|id| id.0.clone());
13745 variables.insert(format!("id{slot}"), json!(id));
13746 }
13747 variables.insert(
13748 "first".to_owned(),
13749 json!(comments.map_or(MAX_PAGE_SIZE, |page| page.limit.min(MAX_PAGE_SIZE))),
13750 );
13751 variables.insert("comments".to_owned(), json!(comments.is_some()));
13752 variables.insert("nestedFirst".to_owned(), json!(NESTED_PAGE_SIZE));
13753 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
13754 variables.insert("duplicates".to_owned(), json!(true));
13755 Value::Object(variables)
13756}
13757
13758/// Whether this refusal is GitHub saying the id names no node at all.
13759fn unresolvable_node(error: &SourceError) -> bool {
13760 matches!(error, SourceError::Refused { message }
13761 if message.to_ascii_lowercase().contains(UNRESOLVABLE_NODE))
13762}
13763
13764/// One project name, as a search qualifier which filters on it at the server.
13765///
13766/// Quoted so the whole title is one phrase rather than a bag of words, with the two
13767/// characters GitHub's own quoting grammar gives a meaning inside a quoted phrase escaped
13768/// the way it documents. A title matched here is still compared for equality afterwards:
13769/// the qualifier narrows what the server sends, and this source decides what it names.
13770fn title_qualifier(name: &str) -> String {
13771 format!("in:title {}", quoted(name))
13772}
13773
13774/// `value` as one quoted phrase of a GitHub search or a board filter, with the two
13775/// characters GitHub's quoting grammar gives a meaning inside a quoted phrase escaped the way
13776/// it documents — so a value holding a qualifier's spelling is searched for rather than
13777/// obeyed.
13778fn quoted(value: &str) -> String {
13779 let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
13780 format!("\"{escaped}\"")
13781}
13782
13783/// The search qualifier for the issues updated at or after `since`.
13784///
13785/// Written to the second, rounded down, which can only widen what the search returns.
13786fn updated_qualifier(since: DateTime<Utc>) -> String {
13787 format!("updated:>={}", since.format("%Y-%m-%dT%H:%M:%S+00:00"))
13788}
13789
13790/// The search terms that narrow a board-scoped issue search to a task query's text and
13791/// metadata predicates, or `None` when it carries neither.
13792///
13793/// The text is one quoted phrase, searched `in:title`, `in:body` or both as its fields say,
13794/// and each metadata value is one more quoted phrase, which GitHub finds in the body because
13795/// its index covers the metadata comment the value is stored in. GitHub ANDs the phrases and
13796/// matches each in any field the `in:` qualifier names, so a query naming a title search and
13797/// a metadata value searches both fields for both — wider than asked, never narrower, and
13798/// every candidate is confirmed in process afterwards.
13799///
13800/// **This narrows a text search, and that is this source's declared semantics.** GitHub
13801/// matches whole tokens where a substring rule would match inside a word, so an item holding
13802/// the text only inside a longer word is not returned. A text of nothing but whitespace
13803/// matches every item, so it narrows nothing and is not sent.
13804fn narrowing_qualifiers(query: &TaskQuery) -> Option<String> {
13805 let text = query
13806 .text
13807 .as_ref()
13808 .filter(|text| !text.terms.trim().is_empty());
13809 if text.is_none() && query.metadata.is_empty() {
13810 return None;
13811 }
13812 let (title, body) = match text.map(|text| text.fields) {
13813 None => (false, true),
13814 Some(TextFields::Title) => (true, !query.metadata.is_empty()),
13815 Some(TextFields::Content) => (false, true),
13816 Some(TextFields::TitleOrContent) => (true, true),
13817 };
13818 let fields = match (title, body) {
13819 (true, true) => "in:title,body",
13820 (true, false) => "in:title",
13821 _ => "in:body",
13822 };
13823 let phrases = text
13824 .map(|text| text.terms.clone())
13825 .into_iter()
13826 .chain(
13827 query
13828 .metadata
13829 .iter()
13830 .map(|wanted| as_stored(wanted.value())),
13831 )
13832 .map(|phrase| quoted(&phrase))
13833 .collect::<Vec<_>>();
13834 Some(format!("{fields} {}", phrases.join(" ")))
13835}
13836
13837/// Whether every status category `query` keeps reads only off an open issue or a draft: a
13838/// closed issue reads `done`, `cancelled` or — closed for a reason that implies no category —
13839/// `unknown`, so a status filter naming none of those three can ask every issue search it sends
13840/// for open issues alone; each candidate's category is still confirmed from its own item.
13841fn open_only(query: &TaskQuery) -> bool {
13842 !query.statuses.is_empty()
13843 && query.statuses.iter().all(|category| {
13844 !matches!(
13845 category,
13846 StatusCategory::Done | StatusCategory::Cancelled | StatusCategory::Unknown
13847 )
13848 })
13849}
13850
13851/// Whether every status category `query` keeps is one only an open item reads as — `draft`,
13852/// `backlog`, `todo`, `queued`, `in-progress` and `unknown` — so a listing of it can read the
13853/// board's open items alone.
13854///
13855/// `unknown` is among them here though [`open_only`] leaves it out: a closed issue reads
13856/// `unknown` only for a closure reason GitHub never records on a closed issue (see
13857/// [`closed_category`]), so an open-only read of the board loses nothing a whole one keeps,
13858/// while an issue search, which [`open_only`] narrows, keeps its own rule.
13859fn open_items_only(query: &TaskQuery) -> bool {
13860 !query.statuses.is_empty()
13861 && query
13862 .statuses
13863 .iter()
13864 .all(|category| !matches!(category, StatusCategory::Done | StatusCategory::Cancelled))
13865}
13866
13867/// What a task query is narrowed by beside a board-scoped issue search's scope — its comment
13868/// activity and its text and metadata, with `is:open` when [`open_only`] — or `None` for a query
13869/// carrying none of those, which no narrowed search answers.
13870///
13871/// A narrowed search never answers a draft, which is no issue, so narrowing it to open issues
13872/// too leaves out nothing such a search could have answered.
13873fn search_qualifiers(query: &TaskQuery) -> Option<String> {
13874 let mut qualifiers: Vec<String> = [
13875 query.commented_since.map(updated_qualifier),
13876 narrowing_qualifiers(query),
13877 ]
13878 .into_iter()
13879 .flatten()
13880 .collect();
13881 if qualifiers.is_empty() {
13882 return None;
13883 }
13884 if open_only(query) {
13885 qualifiers.push(OPEN_QUALIFIER.to_owned());
13886 }
13887 Some(qualifiers.join(" "))
13888}
13889
13890/// The search terms that narrow a board-scoped issue search to a project or document query's
13891/// text, or `None` when it has none or a blank one: the phrase, in the fields, a task query
13892/// carrying that text alone is sent as by [`narrowing_qualifiers`].
13893fn text_qualifiers(text: Option<&TextQuery>) -> Option<String> {
13894 narrowing_qualifiers(&TaskQuery {
13895 text: text.cloned(),
13896 ..TaskQuery::default()
13897 })
13898}
13899
13900/// Refuses a project or document query's text GitHub's issue search cannot find, before
13901/// anything is asked of GitHub, on exactly the terms [`refuse_unsearchable`] refuses a task
13902/// query's.
13903fn refuse_unsearchable_text(text: Option<&TextQuery>) -> Result<(), SourceError> {
13904 refuse_unsearchable(&TaskQuery {
13905 text: text.cloned(),
13906 ..TaskQuery::default()
13907 })
13908}
13909
13910/// Refuses a task query naming a text or a metadata value GitHub's issue search cannot find,
13911/// before anything is asked of GitHub.
13912///
13913/// GitHub's index holds words, so a phrase with no letter or digit names none to find, and no
13914/// bounded query answers it: sent, GitHub's answer to it is nothing this source may rely on;
13915/// left out, the search is every issue of the board. So this source says it cannot answer
13916/// rather than reading the board or answering nothing. A blank text is not refused: it narrows
13917/// nothing GitHub could search for, and keeps the board read it always had.
13918fn refuse_unsearchable(query: &TaskQuery) -> Result<(), SourceError> {
13919 const WHY: &str = "GitHub's issue search indexes words, so it cannot answer a value with no \
13920 letter or digit with a bounded query";
13921 if let Some(text) = &query.text
13922 && !text.terms.trim().is_empty()
13923 && !has_words(&text.terms)
13924 {
13925 return Err(SourceError::Refused {
13926 message: format!(
13927 "cannot search for the text {:?}: {WHY}; search for a text holding a letter or a digit",
13928 text.terms
13929 ),
13930 });
13931 }
13932 if let Some(wanted) = query
13933 .metadata
13934 .iter()
13935 .find(|wanted| !has_words(wanted.value()))
13936 {
13937 return Err(SourceError::Refused {
13938 message: format!(
13939 "cannot filter by the metadata value {:?} at {:?}: {WHY}; filter by a value holding a letter or a digit",
13940 wanted.value(),
13941 std::iter::once(wanted.key())
13942 .chain(wanted.path().iter().map(String::as_str))
13943 .collect::<Vec<_>>()
13944 .join("/"),
13945 ),
13946 });
13947 }
13948 Ok(())
13949}
13950
13951/// Whether GitHub's index could hold a word of `phrase`: whether it has a letter or a digit.
13952fn has_words(phrase: &str) -> bool {
13953 phrase.chars().any(char::is_alphanumeric)
13954}
13955
13956/// `value` spelled the way the metadata slot stores it: as the inside of its JSON string.
13957///
13958/// What GitHub indexes is the slot's JSON text, so a value holding a character JSON escapes —
13959/// a newline, a tab, a quote — is found by the escape the body holds and not by the character,
13960/// which GitHub's word match would read as different words.
13961fn as_stored(value: &str) -> String {
13962 let encoded = Value::String(value.to_owned()).to_string();
13963 encoded[1..encoded.len() - 1].to_owned()
13964}
13965
13966/// The one narrower question a task query carrying a text, metadata or origin predicate is
13967/// sent as.
13968enum Narrowing {
13969 /// Every carrier of this origin: [`graphql::ORIGIN_LOOKUP`].
13970 Origin(String),
13971 /// The board-scoped issue search narrowed by these qualifiers.
13972 Search(String),
13973}
13974
13975impl Narrowing {
13976 /// What this question is remembered under for the length of one command.
13977 fn key(&self) -> String {
13978 match self {
13979 Self::Origin(origin) => format!("origin {origin}"),
13980 Self::Search(also) => format!("search {also}"),
13981 }
13982 }
13983}
13984
13985/// Where one connection of [`graphql::ORIGIN_LOOKUP`] resumes.
13986enum Resumed {
13987 /// It reported another page, which starts after this cursor.
13988 More(String),
13989 /// It has ended. Sending this cursor again — the page's own end when it had one, and
13990 /// otherwise the cursor it was reached from — answers an empty page, so the one document
13991 /// can go on walking the other connection.
13992 Ended(Option<String>),
13993}
13994
13995impl Resumed {
13996 /// Whether the connection has another page.
13997 const fn has_more(&self) -> bool {
13998 matches!(self, Self::More(_))
13999 }
14000
14001 /// The cursor to send this connection next.
14002 fn cursor(self) -> Option<String> {
14003 match self {
14004 Self::More(next) => Some(next),
14005 Self::Ended(last) => last,
14006 }
14007 }
14008}
14009
14010/// Where `connection`, reached from `after`, resumes — refused when it reports another page
14011/// with no cursor to it, or from a cursor that does not advance.
14012fn resumed(connection: &Value, after: Option<&str>) -> Result<Resumed, SourceError> {
14013 let info = connection
14014 .get("pageInfo")
14015 .ok_or_else(|| SourceError::Malformed {
14016 message: "GitHub connection has no pageInfo".into(),
14017 })?;
14018 let end = optional_str(info, "endCursor")?;
14019 if required_bool(info, "hasNextPage")? {
14020 let next = end.ok_or_else(|| SourceError::Malformed {
14021 message: "GitHub connection reports another page and no endCursor".into(),
14022 })?;
14023 validate_cursor_progress(after, next)?;
14024 return Ok(Resumed::More(next.to_owned()));
14025 }
14026 Ok(Resumed::Ended(
14027 end.map(str::to_owned).or_else(|| after.map(str::to_owned)),
14028 ))
14029}
14030
14031/// The board, and every item on it this source reports.
14032#[derive(Clone)]
14033struct Board {
14034 id: String,
14035 fields: Value,
14036 items: Vec<Resolved>,
14037}
14038
14039/// What a write needs of the board and nothing more: its node id and its field
14040/// definitions, in the shape a read of the board's own `fields` gives them.
14041///
14042/// Deliberately no items. A write decides which item it writes, which parent it files
14043/// under and which far ends it names by reading each of them by its own id; this is the
14044/// half of the board those reads cannot carry, and holding no item is what keeps it from
14045/// ever being asked whether an item is there.
14046#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14047struct BoardFields {
14048 id: BoardId,
14049 fields: Value,
14050}
14051
14052/// A board's node id: what a field write and `addProjectV2ItemById` address.
14053///
14054/// Never blank, because a blank one addresses no board — so an id GitHub answers blank is
14055/// refused where it is read, and one an item names blank is read as not named at all.
14056#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
14057#[serde(try_from = "String")]
14058struct BoardId(String);
14059
14060impl TryFrom<String> for BoardId {
14061 type Error = String;
14062
14063 /// The same refusal [`BoardId::parse`] makes, for an id read back from a kept context.
14064 fn try_from(id: String) -> Result<Self, Self::Error> {
14065 Self::parse(&id).map_err(|error| error.to_string())
14066 }
14067}
14068
14069/// Where one write left its item, for the record the rest of the command reads it out of.
14070///
14071/// A named record rather than a tuple because the update arm and the create arm each fill
14072/// all four, and two `Option`s of different meaning side by side in a tuple are two
14073/// positions a reader has to count.
14074struct Landed {
14075 /// The issue's own node id, which is the [`NativeId`] this source reports.
14076 content_id: NativeId,
14077 /// The board item's id, which is what a field write addresses — `None` for an issue its
14078 /// create filed on the board itself, whose board item GitHub adds after answering and
14079 /// [`TaskSource::finish_writes`] reads.
14080 // 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.
14081 item_id: Option<String>,
14082 /// The web address GitHub gave the issue, when it gave one.
14083 // 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.
14084 url: Option<String>,
14085 /// The issue's number on its repository, when GitHub reported one.
14086 number: Option<u64>,
14087}
14088
14089impl BoardId {
14090 fn parse(id: &str) -> Result<Self, SourceError> {
14091 if id.trim().is_empty() {
14092 return Err(SourceError::Malformed {
14093 message: "GitHub named a board with a blank node id".into(),
14094 });
14095 }
14096 Ok(Self(id.to_owned()))
14097 }
14098
14099 fn as_str(&self) -> &str {
14100 &self.0
14101 }
14102}
14103
14104impl Board {
14105 fn field<'a>(fields: &'a Value, name: &str) -> Result<Option<&'a Value>, SourceError> {
14106 complete_connection(fields, "project fields", NESTED_PAGE_SIZE)?;
14107 let nodes = fields
14108 .get("nodes")
14109 .and_then(Value::as_array)
14110 .ok_or_else(|| SourceError::Malformed {
14111 message: "GitHub project fields.nodes is not an array".into(),
14112 })?;
14113 Ok(nodes
14114 .iter()
14115 .find(|field| field.get("name").and_then(Value::as_str) == Some(name)))
14116 }
14117}
14118
14119/// One board item, resolved into everything this source reports about it.
14120///
14121/// Serializable because it is what [`TaskSource::write_context`] hands the store's cache and
14122/// [`TaskSource::prime_write`] takes back — see [`expected`].
14123#[derive(Clone, Serialize, Deserialize, schemars::JsonSchema)]
14124struct Resolved {
14125 item_id: String,
14126 id: NativeId,
14127 content_kind: ContentKind,
14128 kind: BoardKind,
14129 title: String,
14130 body: Option<String>,
14131 /// The body exactly as GitHub holds it, metadata slot and all, which is what a write
14132 /// that changes the slot alone has to keep byte for byte outside it.
14133 raw_body: Option<String>,
14134 status: Status,
14135 /// The name of the board `Status` option this item sits in, as the board spells it.
14136 option: Option<String>,
14137 /// What its `Priority` field says, read through this instance's mapping.
14138 priority: HeldPriority,
14139 /// Whether this item's issue is closed. A draft has no such state and is never closed.
14140 closed: bool,
14141 /// GitHub's reason for a closed issue's closure, as it spells it — `None` for an open
14142 /// issue, a draft, and an issue closed before GitHub recorded reasons.
14143 #[serde(default)]
14144 reason: Option<String>,
14145 /// The tasks this one delivers, read out of its slot. Empty for anything not a task.
14146 delivers: Vec<TaskRef>,
14147 /// Every task that delivers this one, read out of its slot. Empty for anything not a
14148 /// task.
14149 delivered_by: Vec<TaskRef>,
14150 labels: Vec<Label>,
14151 parent: Option<NativeId>,
14152 /// The issue's GitHub parent on a source reading sub-issues as children (`sub_issues:
14153 /// parent`), where [`Self::parent`] — the project it is filed under — is always `None`.
14154 #[serde(default)]
14155 issue_parent: Option<NativeId>,
14156 // 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.
14157 origin: Option<String>,
14158 /// What each board text field this instance projects metadata onto holds for this item,
14159 /// by field name — only the fields holding a value, an empty text included. What a write compares the
14160 /// item's metadata against, so a field already holding its value is not written again;
14161 /// never read back as metadata, which the slot alone reports.
14162 projected: BTreeMap<String, String>,
14163 /// The issue's own number on its repository, as GitHub reports it.
14164 ///
14165 /// `None` in exactly two cases: a draft, which has no number at all — `DraftIssue`
14166 /// declares none, and a draft is not filed in a repository to be numbered by one — and
14167 /// an issue this run created whose creating mutation answered without one, which is a
14168 /// response GitHub's own schema says cannot happen and which a landed write is not
14169 /// worth failing over. An `Issue` read off the board always has one.
14170 number: Option<u64>,
14171 url: Option<String>,
14172 created_at: Option<DateTime<Utc>>,
14173 updated_at: Option<DateTime<Utc>>,
14174 /// When the board item itself last changed — what a board field write moves — when the
14175 /// read that reached it said.
14176 item_updated_at: Option<DateTime<Utc>>,
14177 /// How many comments the issue holds, when the read that reached it said.
14178 comment_count: Option<u64>,
14179 /// How many relationship events the issue's timeline holds — every dependency, as
14180 /// `blockedBy` or `blocking`, and every project membership, as its parent, added or
14181 /// removed — when the read that reached it said.
14182 relationship_events: Option<u64>,
14183 /// The server's clock on the response that read it — its `Date` header — when the
14184 /// response carried one.
14185 served_at: Option<DateTime<Utc>>,
14186 /// The digest of its [`change_token::Facets`] — its own kind, its board field values and
14187 /// its labels — when the read that reached it carried all three whole.
14188 #[serde(default)]
14189 facets: Option<change_token::FacetsDigest>,
14190 own_repository: Option<Repository>,
14191 repositories: Vec<Repository>,
14192 classification: Classification,
14193 slot: BTreeMap<String, Value>,
14194 /// The node id of the board this item sits on, when the read that reached it said.
14195 board_id: Option<String>,
14196 /// The definition of every board field this item holds a value of, in the shape a read
14197 /// of the board's own `fields` gives one.
14198 ///
14199 /// Only the fields this item has a value in: a field it holds nothing of is not here,
14200 /// which says nothing about whether the board has it.
14201 fields: Vec<Value>,
14202 /// Every field the board this item sits on defines, as its own read of the board's
14203 /// `fields` gives them — when the read that reached the item carried them, which a read
14204 /// of it by its own id does. What a write of it needs of the board, then, needs no read
14205 /// of the board.
14206 board_fields: Option<Value>,
14207 /// The far ends of this issue's whole `blockedBy` connection, each as a dependency read
14208 /// selects one — when the read that reached it carried the connection to its end, which a
14209 /// read of it by its own id does for any issue blocked by no more than a page. What a
14210 /// write reconciles that relationship against, and what a read of its forward edges in
14211 /// the same command answers with.
14212 blocked_by: Option<Vec<Value>>,
14213 /// Every person the item is assigned to, by login in the order GitHub answered them — read
14214 /// only by a source opted in to assignees, and `None` for any other, and for a record no
14215 /// read or write of this process showed them on.
14216 #[serde(default)]
14217 assignees: Option<Vec<String>>,
14218}
14219
14220impl Resolved {
14221 /// The board this item's own read names it on, when that read named one this source can
14222 /// address.
14223 fn named_board(&self) -> Option<BoardId> {
14224 self.board_id
14225 .as_deref()
14226 .and_then(|id| BoardId::parse(id).ok())
14227 }
14228
14229 /// The board's id and every field it defines, when the read that reached this item
14230 /// carried both — which a read of it by its own id does.
14231 fn carried_board(&self) -> Option<BoardFields> {
14232 Some(BoardFields {
14233 id: self.named_board()?,
14234 fields: self.board_fields.clone()?,
14235 })
14236 }
14237
14238 /// Whether this item holds a value of the board field called `name`, and so carries
14239 /// that field's definition. `false` says nothing about whether the board has the field.
14240 fn defines(&self, name: &str) -> bool {
14241 self.fields
14242 .iter()
14243 .any(|field| field.get("name").and_then(Value::as_str) == Some(name))
14244 }
14245
14246 /// The metadata a caller sees: their own keys, plus the copy origin this source keeps
14247 /// in a field of its own, and none of the five keys that are only an encoding.
14248 ///
14249 /// The two delivery keys are left out for every kind, not only for a task: they are
14250 /// the encoding of [`Task::delivers`] and [`Task::delivered_by`], and a project or a
14251 /// document carrying one holds nothing a caller's own metadata could mean by it.
14252 fn metadata(&self) -> BTreeMap<String, Value> {
14253 let mut metadata = self.slot.clone();
14254 metadata.remove(Repository::METADATA_KEY);
14255 metadata.remove(DependencyEdge::RECORDED_KEY);
14256 metadata.remove(ItemKind::METADATA_KEY);
14257 metadata.remove(TaskRef::DELIVERS_KEY);
14258 metadata.remove(TaskRef::DELIVERED_BY_KEY);
14259 metadata.remove(Classification::METADATA_KEY);
14260 // The board field is the origin, and the body's copy of it is only a mirror for the
14261 // issue search to find: an item whose field holds none has none, whatever its body
14262 // says, so no reader ever sees two answers.
14263 metadata.remove(ORIGIN_KEY);
14264 if let Some(origin) = &self.origin {
14265 metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin.clone()));
14266 }
14267 metadata
14268 }
14269
14270 /// Where this item is, as a link a reader can open.
14271 ///
14272 /// A board is a hosted place and every issue on it has a web address, so that address
14273 /// is what "where is this?" means here — and [`Location::Url`] is what says which kind
14274 /// of place it is, so a reader knows to open it rather than to read a file out. It
14275 /// does not replace or derive from `url`: the field goes on reporting exactly what it
14276 /// reported before, and this says what that address *is*.
14277 ///
14278 /// An item GitHub gave no `url` for — a draft has none — reports no location at all
14279 /// rather than a third variant, which is the contract's "the source did not say". An
14280 /// issue this run created is not one of those: its address comes back from the
14281 /// creating mutation, so it is somewhere a reader can open from the moment it exists
14282 /// rather than from whenever the board read catches up.
14283 fn location(&self) -> Option<Location> {
14284 self.url.clone().map(Location::Url)
14285 }
14286
14287 /// The short handle this board's backend shows people for a task: the issue's number
14288 /// alone, as a decimal string.
14289 ///
14290 /// The number alone rather than `owner/repo#1043`, because that is the contract's
14291 /// value for this backend. A draft has no number and so no handle, which is the
14292 /// contract's *absent* rather than a handle of some other shape — and the native
14293 /// [`Task::id`] here is the issue's GraphQL node id, which this neither replaces nor
14294 /// derives from.
14295 fn key(&self) -> Option<String> {
14296 self.number.map(|number| number.to_string())
14297 }
14298
14299 /// This item's change token — see [`change_token`] — or `None` when the read that
14300 /// reached it did not carry all six of its parts, which a draft never does, did not say
14301 /// when GitHub served it, or found it changed too recently to have settled.
14302 fn version(&self) -> Option<String> {
14303 let parts = self.token_parts()?;
14304 change_token::settled(parts.issue, parts.item, self.served_at?)
14305 .then(|| change_token::spell(&parts))
14306 }
14307
14308 /// The change token this item, read just after a write of it, holds now — whether or not it
14309 /// has settled: what a written task's `version` answers (see
14310 /// [`GitHubProjectsSource::written_tokens`]), spelled from the parts a later read spells its
14311 /// token from.
14312 fn written_version(&self) -> Option<String> {
14313 self.token_parts().map(|parts| change_token::spell(&parts))
14314 }
14315
14316 /// Every part of this item's change token, or `None` when the read that reached it did not
14317 /// carry them all — a draft never does.
14318 fn token_parts(&self) -> Option<change_token::Parts> {
14319 match self.content_kind {
14320 ContentKind::Issue => Some(change_token::Parts {
14321 issue: self.updated_at?,
14322 item: self.item_updated_at?,
14323 comments: self.comment_count?,
14324 relationships: self.relationship_events?,
14325 facets: self.facets.clone()?,
14326 repository: self.own_repository.clone()?,
14327 }),
14328 ContentKind::DraftIssue => None,
14329 }
14330 }
14331
14332 /// Whether its `Priority` field holds a value at all, mapped or not.
14333 fn holds_priority(&self) -> bool {
14334 self.priority != HeldPriority::Read(Priority::None)
14335 }
14336
14337 /// The task this item is.
14338 ///
14339 /// Fails for an item whose `Priority` field holds an option the mapping does not name:
14340 /// reading that as a level would be a guess, and reading it as `none` would let the next
14341 /// copy clear a priority a person set.
14342 fn task(&self) -> Result<Task, SourceError> {
14343 let priority = match &self.priority {
14344 HeldPriority::Read(priority) => *priority,
14345 HeldPriority::Unmapped(option) => {
14346 return Err(SourceError::Malformed {
14347 message: format!(
14348 "task {}{} sits in the board {PRIORITY_FIELD} option {option:?}, which \
14349 this source's priority_mapping does not name, so its priority cannot be \
14350 read; next: name {option:?} under priority_mapping, or move the item to \
14351 a mapped option",
14352 self.id,
14353 self.number
14354 .map(|number| format!(" (#{number})"))
14355 .unwrap_or_default()
14356 ),
14357 });
14358 }
14359 };
14360 let metadata = self.metadata();
14361 Ok(Task {
14362 version: self.version(),
14363 id: self.id.clone(),
14364 key: self.key(),
14365 title: self.title.clone(),
14366 // The `## Links` section the engine rendered is stripped, so content round-trips.
14367 content: onetaskgraph_plugin_api::read_content(self.body.clone(), &metadata),
14368 status: self.status.clone(),
14369 priority,
14370 labels: self.labels.clone(),
14371 project: self.parent.clone(),
14372 url: self.url.clone(),
14373 location: self.location(),
14374 created_at: self.created_at,
14375 updated_at: self.updated_at,
14376 metadata,
14377 repositories: self.repositories.clone(),
14378 delivers: self.delivers.clone(),
14379 delivered_by: self.delivered_by.clone(),
14380 classification: self.classification,
14381 assignees: self.assignees.clone(),
14382 })
14383 }
14384
14385 fn project(&self) -> Project {
14386 Project {
14387 version: self.version(),
14388 id: self.id.clone(),
14389 title: self.title.clone(),
14390 content: self.body.clone(),
14391 status: self.status.clone(),
14392 labels: self.labels.clone(),
14393 url: self.url.clone(),
14394 location: self.location(),
14395 created_at: self.created_at,
14396 updated_at: self.updated_at,
14397 metadata: self.metadata(),
14398 repositories: self.repositories.clone(),
14399 classification: self.classification,
14400 }
14401 }
14402
14403 /// The same issue as a document: the project it is filed under, and no status and no
14404 /// dependencies, because a document is not work.
14405 fn document(&self) -> Document {
14406 Document {
14407 version: self.version(),
14408 id: self.id.clone(),
14409 title: self.title.clone(),
14410 content: self.body.clone(),
14411 project: self.parent.clone(),
14412 labels: self.labels.clone(),
14413 url: self.url.clone(),
14414 location: self.location(),
14415 created_at: self.created_at,
14416 updated_at: self.updated_at,
14417 metadata: self.metadata(),
14418 repositories: self.repositories.clone(),
14419 classification: self.classification,
14420 }
14421 }
14422}
14423
14424/// Where one targeted update moves an item's status, and which of its two halves move.
14425struct StatusMove {
14426 /// The board the item's `Status` field is on.
14427 board: BoardId,
14428 /// The `Status` field's id.
14429 field: String,
14430 /// The option's id.
14431 option: String,
14432 /// The option's name, as the board spells it.
14433 name: String,
14434 /// What the status asks of the issue's state.
14435 target: StatusTarget,
14436 /// The status the item reads as once it is there.
14437 landed: Status,
14438 /// Which of the status's two halves differ from what the item holds.
14439 moves: Moves,
14440}
14441
14442/// Which halves of an item's status one targeted update moves: its `Status` option, the open or
14443/// closed state of its issue, or both. A status neither half of which differs is no move at all,
14444/// and is not a value of this type.
14445#[derive(Clone, Copy, PartialEq, Eq)]
14446enum Moves {
14447 /// The option alone.
14448 Option,
14449 /// The issue's state alone: open, closed, or closed with another reason.
14450 State,
14451 /// Both.
14452 Both,
14453}
14454
14455impl Moves {
14456 /// What differs, or `None` when nothing does.
14457 const fn of(option: bool, state: bool) -> Option<Self> {
14458 match (option, state) {
14459 (true, true) => Some(Self::Both),
14460 (true, false) => Some(Self::Option),
14461 (false, true) => Some(Self::State),
14462 (false, false) => None,
14463 }
14464 }
14465
14466 /// Whether the option moves.
14467 const fn option(self) -> bool {
14468 matches!(self, Self::Option | Self::Both)
14469 }
14470
14471 /// Whether the issue's state moves.
14472 const fn state(self) -> bool {
14473 matches!(self, Self::State | Self::Both)
14474 }
14475}
14476
14477/// What one write is, and the status that comes with being it.
14478///
14479/// One value rather than a [`BoardKind`] beside an `Option<Status>`: a document has no
14480/// status and a task or a project always has one, so "a document carrying a status" and
14481/// "a task carrying none" are states a write cannot be in rather than states every use
14482/// site below has to defend against.
14483enum Written<'a> {
14484 /// A document, which is not work and so has no status at all.
14485 Document,
14486 /// A task or a project, and the status it is being written with.
14487 Work(ItemKind, &'a Status),
14488}
14489
14490impl Written<'_> {
14491 /// Which of the board's three kinds this write is.
14492 const fn kind(&self) -> BoardKind {
14493 match self {
14494 Self::Document => BoardKind::Document,
14495 Self::Work(kind, _) => BoardKind::Work(*kind),
14496 }
14497 }
14498
14499 /// The status this write carries. A document carries none, so a write of one says
14500 /// nothing about the issue's open or closed state and selects no board `Status`
14501 /// option.
14502 const fn status(&self) -> Option<&Status> {
14503 match self {
14504 Self::Document => None,
14505 Self::Work(_, status) => Some(status),
14506 }
14507 }
14508
14509 /// The status this write carries with the kind whose half of `status_mapping` it is
14510 /// written through.
14511 const fn work_status(&self) -> Option<(ItemKind, &Status)> {
14512 match self {
14513 Self::Document => None,
14514 Self::Work(kind, status) => Some((*kind, status)),
14515 }
14516 }
14517}
14518
14519/// The item being written, in the one shape all three write methods reach.
14520struct Incoming<'a> {
14521 written: Written<'a>,
14522 /// The title a person wrote. A document's goes onto the issue with
14523 /// [`DESIGN_TITLE_PREFIX`] put back, so a round trip returns the title that went in.
14524 title: &'a str,
14525 content: Option<&'a str>,
14526 assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
14527 labels: &'a [Label],
14528 metadata: &'a BTreeMap<String, Value>,
14529 repositories: &'a [Repository],
14530 /// Recorded in the slot while private, and nowhere while public.
14531 classification: Classification,
14532 parent: Option<&'a NativeId>,
14533 /// [`Task::delivers`], already checked. Empty for a project or a document, which is
14534 /// what keeps either key out of their slot.
14535 delivers: &'a [TaskRef],
14536 /// [`Task::delivered_by`], already checked. Empty for a project or a document.
14537 delivered_by: &'a [TaskRef],
14538 /// [`Task::priority`], for a task written to an instance that holds one; `None` for a
14539 /// project, a document, and every write to an instance with no `priority_mapping` —
14540 /// which is what keeps such a write's requests exactly what they were before.
14541 priority: Option<Priority>,
14542 /// [`Task::assignees`] of a task written to a source opted in to them — the people it is
14543 /// to be assigned to, replacing whoever it holds — and `None` for everything else, which
14544 /// leaves an existing item's as they are and creates one unassigned.
14545 assignees: Option<&'a [String]>,
14546}
14547
14548/// What one write does to one projected metadata text field, by the field's id.
14549#[derive(Debug, Clone)]
14550enum ProjectionWrite {
14551 /// Write this text.
14552 Set {
14553 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.
14554 text: String,
14555 },
14556 /// Clear the field's value.
14557 Clear { field: String }, // llmlint: ignore[invalid_states_unrepresentable] As above.
14558}
14559
14560impl ProjectionWrite {
14561 /// Add this write to a field write's list of values and list of clears.
14562 fn join<'a>(&'a self, values: &mut Vec<(String, Value)>, clears: &mut Vec<&'a str>) {
14563 match self {
14564 Self::Set { field, text } => values.push((field.clone(), json!({"text": text}))),
14565 Self::Clear { field } => clears.push(field),
14566 }
14567 }
14568}
14569
14570/// What one write does to an item's `Priority` field.
14571enum PriorityWrite {
14572 /// Select this option of this field.
14573 Select {
14574 /// The `Priority` field's id.
14575 field: String,
14576 /// The mapped option's id.
14577 option: String,
14578 },
14579 /// Clear the field's value, which is what `none` is.
14580 Clear {
14581 /// The `Priority` field's id.
14582 field: String,
14583 },
14584}
14585
14586impl Incoming<'_> {
14587 /// The title this write puts on the issue.
14588 fn written_title(&self) -> String {
14589 match self.written {
14590 Written::Document => format!("{DESIGN_TITLE_PREFIX}{}", self.title),
14591 Written::Work(..) => self.title.to_owned(),
14592 }
14593 }
14594}
14595
14596#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14597enum ContentKind {
14598 DraftIssue,
14599 Issue,
14600}
14601
14602/// What one board issue is: a document, or the work an [`ItemKind`] names.
14603///
14604/// A type of this source's own rather than an `ItemKind` with a third variant, because
14605/// `ItemKind` names what a dependency endpoint points at and nothing may point at a
14606/// document — the contract keeps a document out of that enum deliberately. Holding the
14607/// board's three answers in one value is what makes every place that asks "which is this?"
14608/// answer all three, rather than a `document: bool` beside a `kind` that means nothing for
14609/// two thirds of the board.
14610#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
14611enum BoardKind {
14612 /// An issue whose title begins [`DESIGN_TITLE_PREFIX`].
14613 Document,
14614 /// Every other issue, and every draft.
14615 Work(ItemKind),
14616}
14617
14618impl BoardKind {
14619 /// The kind of an item titled `title`, filed under a project or not, holding `sub_issues`
14620 /// sub-issues and carrying the kind marker `marked` in its slot.
14621 ///
14622 /// The design prefix is read *first*, before either of the two rules that separate a
14623 /// project from a task. A document is not work whatever sub-issues it has and whatever
14624 /// marker it carries, and reading the prefix later would make a design issue with none of
14625 /// either an empty project. Being a sub-issue wins outright over the rest, and no marker
14626 /// overrides it: an issue filed under a project is that project's task even when it has
14627 /// sub-issues of its own.
14628 fn of(title: &str, filed: bool, sub_issues: u64, marked: Option<ItemKind>) -> Self {
14629 if title.starts_with(DESIGN_TITLE_PREFIX) {
14630 Self::Document
14631 } else if filed {
14632 Self::Work(ItemKind::Task)
14633 } else if sub_issues > 0 || marked == Some(ItemKind::Project) {
14634 Self::Work(ItemKind::Project)
14635 } else {
14636 Self::Work(ItemKind::Task)
14637 }
14638 }
14639
14640 /// What the change token's facets call this kind.
14641 const fn facet(self) -> change_token::FacetKind {
14642 match self {
14643 Self::Document => change_token::FacetKind::Document,
14644 Self::Work(ItemKind::Project) => change_token::FacetKind::Project,
14645 Self::Work(ItemKind::Task) => change_token::FacetKind::Task,
14646 }
14647 }
14648
14649 /// Whose half of `status_mapping` an item of this kind reads its status through. A
14650 /// document has no status of its own, so the task half stands in for whatever the issue
14651 /// holds; nothing reports it.
14652 const fn status_kind(self) -> ItemKind {
14653 match self {
14654 Self::Document => ItemKind::Task,
14655 Self::Work(kind) => kind,
14656 }
14657 }
14658
14659 /// How a refusal names this kind to the person reading it.
14660 const fn describes(self) -> &'static str {
14661 match self {
14662 Self::Document => "document",
14663 Self::Work(kind) => kind.marker(),
14664 }
14665 }
14666}
14667
14668/// Whether `labels` satisfies `filter`, matching by name, case-insensitively.
14669///
14670/// This is the local Markdown source's `labels_match`, spelled the same way on purpose:
14671/// the shared cross-source journeys assert one answer to one question, so two sources
14672/// that disagree about what "carries the label bug" means fail them.
14673fn labels_match(labels: &[Label], filter: &LabelFilter) -> bool {
14674 let holds = |name: &String| {
14675 labels
14676 .iter()
14677 .any(|label| label.name.eq_ignore_ascii_case(name))
14678 };
14679 (filter.any_of.is_empty() || filter.any_of.iter().any(holds))
14680 && filter.all_of.iter().all(holds)
14681 && !filter.none_of.iter().any(holds)
14682}
14683
14684/// Whether `category` is one of `statuses`. An empty list is unfiltered rather than
14685/// "keeps nothing", which is what lets a `Vec<StatusCategory>` spell no filter at all.
14686fn status_matches(category: StatusCategory, statuses: &[StatusCategory]) -> bool {
14687 statuses.is_empty() || statuses.contains(&category)
14688}
14689
14690/// Whether `title`/`content` satisfies `query`, matching case-insensitively.
14691///
14692/// `content` is the item's own prose — the body with this source's trailing metadata
14693/// comment already taken off — so a search never matches an encoding the author of the
14694/// issue never wrote.
14695fn text_matches(title: &str, content: Option<&str>, query: &TextQuery) -> bool {
14696 let terms = query.terms.to_lowercase();
14697 let in_title = title.to_lowercase().contains(&terms);
14698 let in_content = content.is_some_and(|body| body.to_lowercase().contains(&terms));
14699 match query.fields {
14700 TextFields::Title => in_title,
14701 TextFields::Content => in_content,
14702 TextFields::TitleOrContent => in_title || in_content,
14703 }
14704}
14705
14706/// Whether `task` satisfies `query`, with `project` deciding the project predicate.
14707///
14708/// The project predicate is passed separately because a read narrowed to one project has
14709/// already answered it by asking *that project* for its own items — and re-applying it
14710/// there would compare the caller's selector, which may be a project's **name**, against
14711/// the id of the project that name resolved to, and keep nothing. Every other read passes
14712/// `query.project` and applies it here, which is what keeps `projects` a predicate this
14713/// source really does apply.
14714fn task_matches(task: &Task, query: &TaskQuery, project: &ProjectFilter) -> bool {
14715 labels_match(&task.labels, &query.labels)
14716 && status_matches(task.status.category, &query.statuses)
14717 && (query.priorities.is_empty() || query.priorities.contains(&task.priority))
14718 && match project {
14719 ProjectFilter::Any => true,
14720 ProjectFilter::Orphans => task.project.is_none(),
14721 ProjectFilter::Is(id) => task.project.as_ref() == Some(id),
14722 }
14723 && query
14724 .text
14725 .as_ref()
14726 .is_none_or(|text| text_matches(&task.title, task.content.as_deref(), text))
14727 // Against the parsed metadata slot, and against the origin field, which is where
14728 // `Resolved::metadata` reads each of them from.
14729 && query.metadata_matches(&task.metadata)
14730 && query.origin_matches(&task.metadata)
14731}
14732
14733fn project_matches(project: &Project, query: &ProjectQuery) -> bool {
14734 labels_match(&project.labels, &query.labels)
14735 && status_matches(project.status.category, &query.statuses)
14736 && query
14737 .text
14738 .as_ref()
14739 .is_none_or(|text| text_matches(&project.title, project.content.as_deref(), text))
14740}
14741
14742/// The same three predicates a task query carries, minus the status filter.
14743///
14744/// A document is not work, so it has no status for one to compare against and the query
14745/// type carries none. The project predicate is the same one — a design issue filed under a
14746/// project issue is in that project, and one filed under nothing is in none — so it is
14747/// spelled the same way here rather than answered differently.
14748fn document_matches(document: &Document, query: &DocumentQuery, project: &ProjectFilter) -> bool {
14749 labels_match(&document.labels, &query.labels)
14750 && match project {
14751 ProjectFilter::Any => true,
14752 ProjectFilter::Orphans => document.project.is_none(),
14753 ProjectFilter::Is(id) => document.project.as_ref() == Some(id),
14754 }
14755 && query
14756 .text
14757 .as_ref()
14758 .is_none_or(|text| text_matches(&document.title, document.content.as_deref(), text))
14759}
14760
14761/// Why a GitHub item's change token does not vouch for its forward edges.
14762///
14763/// A forward edge names its far end and that far end's kind, and the near item's token moves
14764/// with the edges it holds but says nothing of the far ends themselves: a far end turning from a
14765/// task into a project when it gains a sub-issue, retitled into a document, or deleted moves
14766/// nothing the near token reads, so an edge kept at the near version could name a far end that
14767/// is no longer what it said.
14768const FAR_ENDS_UNCOVERED: &str = "a github item's change token does not attest a far end's kind, \
14769 whether it became a document, or its deletion, so its forward edges are always read from \
14770 github";
14771
14772/// The issue-search qualifier that keeps open issues alone, which a status filter naming only
14773/// categories an open issue reads as narrows a board-scoped search with.
14774const OPEN_QUALIFIER: &str = "is:open";
14775
14776/// What the board's open items are held under among the narrowed answers of one command — a
14777/// key no [`Narrowing`], each `origin …` or `search …`, can spell.
14778const OPEN_ITEMS_KEY: &str = "items is:open";
14779
14780/// The board filter `task status reconcile` reads the board through: closed items alone.
14781const CLOSED_FILTER: &str = "is:closed";
14782
14783/// The variables of one [`graphql::ISSUES_BY_REFERENCE`] request for `batch`: each slot names
14784/// one reference, and a slot the batch has none for names its last one again.
14785fn reference_batch(batch: &[IssueRef]) -> Value {
14786 let mut variables = serde_json::Map::new();
14787 for slot in 0..REFERENCE_BATCH {
14788 let issue = batch.get(slot).or(batch.last());
14789 variables.insert(format!("owner{slot}"), json!(issue.map(|i| &i.owner)));
14790 variables.insert(format!("name{slot}"), json!(issue.map(|i| &i.name)));
14791 variables.insert(format!("number{slot}"), json!(issue.map(|i| i.number)));
14792 }
14793 variables.insert("boardItems".to_owned(), json!(BOARD_ITEMS_PAGE_SIZE));
14794 variables.insert("statusField".to_owned(), json!(STATUS_FIELD));
14795 variables.insert("duplicates".to_owned(), json!(true));
14796 Value::Object(variables)
14797}
14798
14799/// One issue an issue read by reference answered, in the shape every other read of an issue
14800/// hands its resolver: each board membership's `Status` value, read by name, as the one field
14801/// value that membership carries.
14802///
14803/// A membership's `status` is `null` when its card sits at no option — or on a board with no
14804/// field of that name — and otherwise an option value naming its option; anything else is not
14805/// an answer to this read, and is refused rather than read as a card at no option.
14806fn held_issue(issue: &Value) -> Result<Value, SourceError> {
14807 let malformed = |what: &str| SourceError::Malformed {
14808 message: format!("GitHub answered an issue read by reference with {what}"),
14809 };
14810 let mut issue = issue.clone();
14811 let nodes = issue
14812 .pointer_mut("/projectItems/nodes")
14813 .and_then(Value::as_array_mut)
14814 .ok_or_else(|| malformed("no list of board memberships"))?;
14815 for node in nodes {
14816 let node = node
14817 .as_object_mut()
14818 .ok_or_else(|| malformed("a board membership that is not an object"))?;
14819 let status = match node.get("status") {
14820 None => return Err(malformed("a board membership with no status member")),
14821 Some(Value::Null) => None,
14822 Some(status) if status.get("name").is_some_and(Value::is_string) => {
14823 Some(status.clone())
14824 }
14825 // A single-select value of another field type answers `{}`; only an option value
14826 // carries a name.
14827 Some(status) if status.as_object().is_some_and(serde_json::Map::is_empty) => None,
14828 Some(_) => return Err(malformed("a membership status that names no option")),
14829 };
14830 node.insert(
14831 "fieldValues".to_owned(),
14832 json!({"nodes": status.into_iter().collect::<Vec<_>>(),
14833 "pageInfo": {"hasNextPage": false}}),
14834 );
14835 }
14836 Ok(issue)
14837}
14838
14839/// The issue one slot of a read by reference answered, `None` when GitHub answered that
14840/// slot's repository or issue `null` — which [`GitHubProjectsSource::answer_unresolved`]
14841/// admitted only beside a `NOT_FOUND` naming that very slot — and a refusal when the answer
14842/// leaves the slot, or its `issue` member, out: an answer missing a member is malformed rather
14843/// than a reference nothing holds.
14844fn referenced_issue(data: &Value, slot: usize) -> Result<Option<&Value>, SourceError> {
14845 let alias = format!("r{slot}");
14846 let repository = data.get(&alias).ok_or_else(|| SourceError::Malformed {
14847 message: format!("GitHub answered a read by reference with no {alias}"),
14848 })?;
14849 if repository.is_null() {
14850 return Ok(None);
14851 }
14852 let issue = repository
14853 .get("issue")
14854 .ok_or_else(|| SourceError::Malformed {
14855 message: format!("GitHub answered {alias} of a read by reference with no issue"),
14856 })?;
14857 if issue.is_null() {
14858 return Ok(None);
14859 }
14860 // `Repository.issue` is typed `Issue`, so anything else is not an answer to this read.
14861 if optional_str(issue, "__typename")? != Some("Issue") {
14862 return Err(SourceError::Malformed {
14863 message: format!(
14864 "GitHub answered {alias} of a read by reference with an issue whose __typename \
14865 is not Issue"
14866 ),
14867 });
14868 }
14869 Ok(Some(issue))
14870}
14871
14872/// A closure reason as a person reads it: `NOT_PLANNED` as `not planned`.
14873fn spoken_reason(reason: &str) -> String {
14874 reason.to_ascii_lowercase().replace('_', " ")
14875}
14876
14877impl GitHubProjectsSource {
14878 /// Every task and project of this board whose card contradicts its issue's closure, each
14879 /// judged against its own kind's half of `status_mapping`, read through the board's own
14880 /// `is:closed` filter, page by page — never the board's unfiltered `items`.
14881 ///
14882 /// Each item the filter answers is confirmed from its own node: an open one, one whose
14883 /// closure reads `unknown`, and one whose card is already in line are left out whatever
14884 /// the filter let through. The board's fields ride along and are held for the option
14885 /// writes that follow, so those need no read of the board.
14886 async fn contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
14887 let mut after: Option<String> = None;
14888 let mut found = Vec::new();
14889 loop {
14890 let data = self
14891 .graphql(
14892 graphql::CLOSED_ITEMS,
14893 json!({"owner":self.owner,"number":self.project_number,
14894 "first":MAX_PAGE_SIZE,"after":after,"filter":CLOSED_FILTER,
14895 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true}),
14896 )
14897 .await?;
14898 let board = data
14899 .pointer("/closedItems/projectV2")
14900 .filter(|value| !value.is_null())
14901 .ok_or_else(|| SourceError::Refused {
14902 message: format!(
14903 "GitHub project {}/{} was not found or is not visible to the token",
14904 self.owner, self.project_number
14905 ),
14906 })?;
14907 *self.fields_cache()? = Some(BoardFields {
14908 id: BoardId::parse(required_str(board, "id")?)?,
14909 fields: board.get("fields").cloned().unwrap_or(Value::Null),
14910 });
14911 let items = board.get("items").ok_or_else(|| SourceError::Malformed {
14912 message: "GitHub project closed items are missing".into(),
14913 })?;
14914 for item in items
14915 .get("nodes")
14916 .and_then(Value::as_array)
14917 .ok_or_else(|| SourceError::Malformed {
14918 message: "GitHub project items.nodes is not an array".into(),
14919 })?
14920 {
14921 let Some(resolved) = self.resolve(item)? else {
14922 continue;
14923 };
14924 let BoardKind::Work(kind) = resolved.kind else {
14925 continue;
14926 };
14927 let Some((closed_as, name)) = self.statuses.contradicted(
14928 kind,
14929 resolved.option.as_deref(),
14930 resolved.closed,
14931 resolved.reason.as_deref(),
14932 ) else {
14933 continue;
14934 };
14935 found.push(StatusContradiction {
14936 closed_as,
14937 to: name.to_owned(),
14938 option: resolved.option.clone(),
14939 item: match kind {
14940 ItemKind::Task => ContradictedItem::Task(resolved.task()?),
14941 ItemKind::Project => ContradictedItem::Project(resolved.project()),
14942 },
14943 });
14944 }
14945 let info = items
14946 .get("pageInfo")
14947 .ok_or_else(|| SourceError::Malformed {
14948 message: "GitHub project items have no pageInfo".into(),
14949 })?;
14950 if !required_bool(info, "hasNextPage")? {
14951 return Ok(found);
14952 }
14953 let next = required_str(info, "endCursor")?;
14954 validate_cursor_progress(after.as_deref(), next)?;
14955 after = Some(next.to_owned());
14956 }
14957 }
14958
14959 /// What this board holds for each issue in `issues`, once each in the order given, read
14960 /// [`REFERENCE_BATCH`] references at a time — and nothing else of the board.
14961 ///
14962 /// An issue GitHub cannot find for this source's credential, and one with no item on this
14963 /// board, are both absent. A closure that already says the work will not be done here —
14964 /// not planned, duplicate — is skipped: a landing does not overrule it. An item closed as
14965 /// completed whose card sits at its kind's `done` option is unchanged, and every other item
14966 /// is due a `done` write. A project item — a plan's home card, its issue holding the plan's
14967 /// tasks as sub-issues — is held under exactly these rules, judged against the project
14968 /// kind's half of `status_mapping`.
14969 async fn holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
14970 let mut distinct: Vec<IssueRef> = Vec::with_capacity(issues.len());
14971 for issue in issues {
14972 if !distinct.contains(issue) {
14973 distinct.push(issue.clone());
14974 }
14975 }
14976 let done = |kind: ItemKind| {
14977 self.statuses
14978 .target(kind, StatusCategory::Done)
14979 .option()
14980 .unwrap_or("Done")
14981 .to_owned()
14982 };
14983 // GitHub numbers an issue with a GraphQL `Int`, a signed 32-bit value, so a reference past
14984 // its range names no issue any repository can hold: it is answered absent and never sent,
14985 // where binding it would have GitHub refuse the whole batch.
14986 let readable: Vec<IssueRef> = distinct
14987 .iter()
14988 .filter(|issue| i32::try_from(issue.number).is_ok())
14989 .cloned()
14990 .collect();
14991 let mut holdings = Vec::with_capacity(readable.len());
14992 for batch in readable.chunks(REFERENCE_BATCH) {
14993 let data = self
14994 .graphql(graphql::ISSUES_BY_REFERENCE, reference_batch(batch))
14995 .await?;
14996 for (slot, issue) in batch.iter().enumerate() {
14997 let node = referenced_issue(&data, slot)?;
14998 let resolved = match node {
14999 Some(node) => self.resolve_issue_as(&held_issue(node)?, false).await?,
15000 None => None,
15001 };
15002 // A task and a project are both held; a document is not work, so nothing is.
15003 let Some((item, kind)) = resolved.and_then(|item| match item.kind {
15004 BoardKind::Work(kind) => Some((item, kind)),
15005 BoardKind::Document => None,
15006 }) else {
15007 holdings.push(IssueHolding {
15008 issue: issue.clone(),
15009 completion: Completion::Absent,
15010 });
15011 continue;
15012 };
15013 let task = match kind {
15014 ItemKind::Task => {
15015 let held = item.task()?;
15016 HeldTask {
15017 id: held.id,
15018 kind,
15019 option: item.option.clone(),
15020 classification: held.classification,
15021 repositories: held.repositories,
15022 delivers: held.delivers,
15023 }
15024 }
15025 // A project delivers no task, so what its write keeps in step is nothing.
15026 ItemKind::Project => {
15027 let held = item.project();
15028 HeldTask {
15029 id: held.id,
15030 kind,
15031 option: item.option.clone(),
15032 classification: held.classification,
15033 repositories: held.repositories,
15034 delivers: Vec::new(),
15035 }
15036 }
15037 };
15038 let done = done(kind);
15039 let completion = match (item.closed, item.reason.as_deref()) {
15040 (true, Some(reason @ ("NOT_PLANNED" | "DUPLICATE"))) => Completion::Skipped {
15041 task,
15042 reason: format!("closed as {}", spoken_reason(reason)),
15043 },
15044 (true, None | Some("COMPLETED"))
15045 if item
15046 .option
15047 .as_deref()
15048 .is_some_and(|option| option.eq_ignore_ascii_case(&done)) =>
15049 {
15050 Completion::Unchanged { task }
15051 }
15052 _ => {
15053 let kept = item.clone();
15054 self.held_cache
15055 .lock()
15056 .map_err(|_| SourceError::Unavailable {
15057 message: "items read by issue reference were left \
15058 inconsistent; run the command again"
15059 .into(),
15060 })?
15061 .insert(kept.id.clone(), kept);
15062 Completion::Due {
15063 task,
15064 to: done.clone(),
15065 }
15066 }
15067 };
15068 holdings.push(IssueHolding {
15069 issue: issue.clone(),
15070 completion,
15071 });
15072 }
15073 }
15074 let mut read = holdings.into_iter();
15075 let mut answered = Vec::with_capacity(distinct.len());
15076 for issue in distinct {
15077 if i32::try_from(issue.number).is_ok() {
15078 answered.push(read.next().ok_or_else(|| SourceError::Malformed {
15079 message: format!("no holding was read for {issue}"),
15080 })?);
15081 } else {
15082 answered.push(IssueHolding {
15083 issue,
15084 completion: Completion::Absent,
15085 });
15086 }
15087 }
15088 Ok(answered)
15089 }
15090}
15091
15092#[async_trait::async_trait]
15093impl TaskSource for GitHubProjectsSource {
15094 fn kind(&self) -> &'static str {
15095 KIND
15096 }
15097 /// GitHub's issue search, which narrows a read of the comments made since an instant, is
15098 /// an index behind the writes it indexes — the credentialed lane has watched it miss a newly
15099 /// commented issue for thirty seconds — so a watermark is set back by
15100 /// [`COMMENT_SEARCH_LAG`], four times that.
15101 fn comment_consistency_window(&self) -> std::time::Duration {
15102 COMMENT_SEARCH_LAG
15103 }
15104 /// The `Date` of the last answer GitHub gave this source.
15105 fn served_at(&self) -> Option<DateTime<Utc>> {
15106 *self
15107 .last_served
15108 .lock()
15109 .unwrap_or_else(std::sync::PoisonError::into_inner)
15110 }
15111 fn attach_body_markup(&self, markup: onetaskgraph_plugin_api::SharedBodyMarkup) {
15112 let _ = self.body_markup.set(markup);
15113 }
15114 fn order_versions(&self, a: &str, b: &str) -> Option<std::cmp::Ordering> {
15115 change_token::order(a, b)
15116 }
15117 /// A task's fields and comments: §4.13d of `docs/plugin-protocol.md` states, member by
15118 /// member, the change each part of the token moves for. Not its forward edges — see
15119 /// [`FAR_ENDS_UNCOVERED`].
15120 fn version_coverage(&self) -> VersionCoverage {
15121 VersionCoverage {
15122 forward_edges: Coverage::Uncovered {
15123 reason: FAR_ENDS_UNCOVERED.to_owned(),
15124 },
15125 ..VersionCoverage::whole()
15126 }
15127 }
15128 /// Every part, for a copy's skip: the relationship count moves for an edge added or removed
15129 /// and for a far end deleted, so the token sees every change to a task's edges but one — a
15130 /// far end's own kind flipping, by gaining a sub-issue or being retitled into a document,
15131 /// which `spike-coverage` measured stale 1 of 1. A skipping recopy does not carry that, and
15132 /// the next copy that reads the task does (`docs/plugin-protocol.md` §4.13d).
15133 // 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.
15134 fn copy_version_coverage(&self) -> VersionCoverage {
15135 VersionCoverage::whole()
15136 }
15137 /// A project's fields, and not its forward edges, for the same reason a task's are not.
15138 fn project_version_coverage(&self) -> ProjectVersionCoverage {
15139 ProjectVersionCoverage {
15140 fields: Coverage::Covered,
15141 forward_edges: Coverage::Uncovered {
15142 reason: FAR_ENDS_UNCOVERED.to_owned(),
15143 },
15144 }
15145 }
15146 /// A document's fields and the manifest of its image assets, which its metadata slot
15147 /// records: both are the issue's body, whose every edit moves the token's issue time.
15148 fn document_version_coverage(&self) -> DocumentVersionCoverage {
15149 DocumentVersionCoverage::whole()
15150 }
15151 fn write_context(&self, id: &NativeId) -> Option<Value> {
15152 self.context_of(id)
15153 }
15154 fn board_context(&self) -> Option<Value> {
15155 self.board_context_held()
15156 }
15157 fn prime_write(&self, id: &NativeId, context: &Value, board: Option<&Value>) -> bool {
15158 self.prime(id, context, board)
15159 }
15160 fn unprime(&self, id: &NativeId) {
15161 self.unprime_held(id);
15162 }
15163 fn placement_context(&self) -> Option<Value> {
15164 self.placement_held()
15165 }
15166 fn prime_placement(&self, context: &Value) -> bool {
15167 self.prime_placement_held(context)
15168 }
15169 fn written_context(&self, id: &NativeId) -> Option<Value> {
15170 self.written_held(id)
15171 }
15172 fn prime_written(&self, id: &NativeId, context: &Value, task: &Task) -> bool {
15173 self.prime_written_held(id, context, task)
15174 }
15175 fn begin_journal(&self) {
15176 self.expected.begin();
15177 }
15178 fn end_journal(&self) -> Option<WriteJournal> {
15179 Some(self.expected.end())
15180 }
15181 fn capabilities(&self) -> Capabilities {
15182 Capabilities {
15183 projects: Support::Native,
15184 documents: Support::Native,
15185 comments: Support::Native,
15186 assets: Support::Native,
15187 priority: if self.priorities.is_some() {
15188 Support::Native
15189 } else {
15190 Support::Unsupported
15191 },
15192 filter_by_priority: Support::Native,
15193 filter_by_comment_activity: Support::Native,
15194 filter_by_metadata: Support::Native,
15195 filter_by_origin: Support::Native,
15196 reconcile_status: Support::Native,
15197 complete_by_issue: Support::Native,
15198 orphan_tasks: Support::Native,
15199 filter_by_label: Support::Native,
15200 filter_by_status: Support::Native,
15201 search_title: Support::Native,
15202 search_content: Support::Native,
15203 task_dependencies: DependencySupport::BothDirections,
15204 project_dependencies: DependencySupport::BothDirections,
15205 max_page_size: MAX_PAGE_SIZE,
15206 assignees: if self.assignees {
15207 Support::Native
15208 } else {
15209 Support::Unsupported
15210 },
15211 }
15212 }
15213 async fn visibility(
15214 &self,
15215 target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15216 ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15217 self.write_visibility(target).await
15218 }
15219 async fn visibility_with_project(
15220 &self,
15221 target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15222 project: &onetaskgraph_plugin_api::WriteTarget<'_>,
15223 ) -> Result<onetaskgraph_plugin_api::Visibility, SourceError> {
15224 self.write_visibility_with_project(target, project).await
15225 }
15226 fn declare_visibility(&self, declared: onetaskgraph_plugin_api::Visibility) {
15227 self.declared_private.store(
15228 declared == onetaskgraph_plugin_api::Visibility::Private,
15229 std::sync::atomic::Ordering::SeqCst,
15230 );
15231 }
15232 fn scope_visibility<'a>(
15233 &'a self,
15234 operation: std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>>,
15235 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + 'a>> {
15236 self.scope_visibility_reads(operation)
15237 }
15238
15239 /// Where a create of `target` would file its issue, by [`Self::creation_rule`] — the rule
15240 /// the create applies — reading the parent project's issue only when `target` names one.
15241 async fn creation_repository(
15242 &self,
15243 target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15244 ) -> Result<Option<Repository>, SourceError> {
15245 let onetaskgraph_plugin_api::WriteTarget::New {
15246 repositories,
15247 project,
15248 } = target
15249 else {
15250 return Ok(None);
15251 };
15252 let target = self
15253 .creation_rule(repositories, *project, "a new item")
15254 .await?;
15255 Repository::try_from(target.origin())
15256 .map(Some)
15257 .map_err(|message| SourceError::Malformed { message })
15258 }
15259 /// Every issue of the repository a create of `target` files in whose body carries `key` in
15260 /// its metadata slot, read off that repository's issues newest first back to `since` —
15261 /// never through search, whose index lags a fresh issue by seconds.
15262 async fn created_with_key(
15263 &self,
15264 record: onetaskgraph_plugin_api::MetadataRecord,
15265 key: &str,
15266 since: Option<DateTime<Utc>>,
15267 target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15268 ) -> Result<Vec<NativeId>, SourceError> {
15269 let _ = record;
15270 let onetaskgraph_plugin_api::WriteTarget::New {
15271 repositories,
15272 project,
15273 } = target
15274 else {
15275 return Ok(Vec::new());
15276 };
15277 let repository = self
15278 .creation_rule(repositories, *project, "a new item")
15279 .await?;
15280 let wanted = Value::String(key.to_owned());
15281 let mut found = Vec::new();
15282 let mut after: Option<String> = None;
15283 let mut followed = std::collections::HashSet::new();
15284 loop {
15285 let data = self
15286 .graphql(
15287 graphql::ISSUES_BY_CREATION,
15288 json!({"owner": repository.owner, "name": repository.name,
15289 "first": MAX_PAGE_SIZE, "after": after}),
15290 )
15291 .await?;
15292 let issues =
15293 data.pointer("/repository/issues")
15294 .ok_or_else(|| SourceError::Malformed {
15295 message: format!(
15296 "GitHub answered no issues for repository {}",
15297 repository.slug()
15298 ),
15299 })?;
15300 let malformed = |what: &str| SourceError::Malformed {
15301 message: format!(
15302 "GitHub answered a page of repository {}'s issues {what}",
15303 repository.slug()
15304 ),
15305 };
15306 let nodes = issues
15307 .get("nodes")
15308 .and_then(Value::as_array)
15309 .ok_or_else(|| malformed("with no list of issues"))?;
15310 let mut older = false;
15311 for node in nodes {
15312 let id = node
15313 .get("id")
15314 .and_then(Value::as_str)
15315 .filter(|id| !id.is_empty())
15316 .ok_or_else(|| malformed("holding an issue with no id"))?;
15317 let created = optional_time(node, "createdAt")?
15318 .ok_or_else(|| malformed("holding an issue with no creation time"))?;
15319 if since.is_some_and(|since| created < since) {
15320 older = true;
15321 break;
15322 }
15323 let body = match node.get("body") {
15324 Some(Value::String(body)) => Some(body.clone()),
15325 Some(Value::Null) => None,
15326 _ => return Err(malformed("holding an issue with no body member")),
15327 };
15328 let (_, metadata) = metadata_body(body)?;
15329 if metadata.get(MetadataKey::CREATE_KEY) == Some(&wanted) {
15330 found.push(NativeId(id.to_owned()));
15331 }
15332 }
15333 let next = issues
15334 .pointer("/pageInfo/hasNextPage")
15335 .and_then(Value::as_bool)
15336 .ok_or_else(|| malformed("that does not say whether another follows"))?;
15337 if older || !next {
15338 return Ok(found);
15339 }
15340 // A page that says another follows names where it starts, and never a page already
15341 // read: anything else would ask for the same pages again for ever.
15342 let cursor = issues
15343 .pointer("/pageInfo/endCursor")
15344 .and_then(Value::as_str)
15345 .filter(|cursor| !cursor.is_empty())
15346 .map(str::to_owned);
15347 if cursor
15348 .as_ref()
15349 .is_none_or(|cursor| !followed.insert(cursor.clone()))
15350 {
15351 return Err(SourceError::Malformed {
15352 message: format!(
15353 "GitHub answered a page of repository {}'s issues that says another \
15354 follows without a new cursor to it",
15355 repository.slug()
15356 ),
15357 });
15358 }
15359 after = cursor;
15360 }
15361 }
15362
15363 /// `Repository.issues` lists an issue GitHub committed only once its listing catches up.
15364 fn create_key_lags(&self) -> bool {
15365 true
15366 }
15367
15368 /// The task as this process's own latest write of it left it, from the item it recorded
15369 /// that write as — never a request. Its `version` is always `None`: a board's change token
15370 /// is given only once an item has gone unchanged for [`change_token::SETTLED`], which an
15371 /// item this command has just written has not, so no write's own answer can vouch for one.
15372 async fn written_task(&self, id: &NativeId) -> Option<Task> {
15373 let held = self
15374 .created()
15375 .ok()?
15376 .iter()
15377 .find(|held| held.id == *id)
15378 .cloned()
15379 .or_else(|| {
15380 self.updated()
15381 .ok()?
15382 .iter()
15383 .find(|held| held.id == *id)
15384 .cloned()
15385 })?;
15386 let mut task = held.task().ok()?;
15387 task.version = self.written_token(id);
15388 Some(task)
15389 }
15390
15391 /// Why `creation_owners` refuses a create of `target`, by [`Self::creation_rule`] — read
15392 /// only when the list is not empty, so a source restricting nothing reads nothing.
15393 async fn creation_refusal(
15394 &self,
15395 target: &onetaskgraph_plugin_api::WriteTarget<'_>,
15396 ) -> Result<Option<String>, SourceError> {
15397 let onetaskgraph_plugin_api::WriteTarget::New {
15398 repositories,
15399 project,
15400 } = target
15401 else {
15402 return Ok(None);
15403 };
15404 if self.creation_owners.is_empty() {
15405 return Ok(None);
15406 }
15407 let target = self
15408 .creation_rule(repositories, *project, "a new item")
15409 .await?;
15410 Ok(self.owner_refusal(&target))
15411 }
15412
15413 async fn health(&self) -> Result<Health, SourceError> {
15414 let board = self.board_page(None, 1).await?;
15415 Ok(Health {
15416 reachable: true,
15417 detail: Some(format!(
15418 "reading GitHub project {}/{} ({})",
15419 self.owner,
15420 self.project_number,
15421 required_str(&board, "title")?
15422 )),
15423 })
15424 }
15425 /// The board's own node id, digested: the one request reading its fields, or none when
15426 /// this command has read them already.
15427 async fn designator(&self) -> Result<Option<Designator>, SourceError> {
15428 let board = self.board_fields().await?;
15429 Designator::of_backend(KIND, board.id.as_str())
15430 .map(Some)
15431 .map_err(|message| SourceError::Malformed { message })
15432 }
15433 async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
15434 self.item_by_id(id)
15435 .await?
15436 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15437 .map(|item| item.task())
15438 .transpose()
15439 }
15440 async fn task_assets(
15441 &self,
15442 id: &NativeId,
15443 ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15444 self.held_assets(id, BoardKind::Work(ItemKind::Task)).await
15445 }
15446 async fn task_asset(
15447 &self,
15448 id: &NativeId,
15449 name: &onetaskgraph_plugin_api::AssetName,
15450 ) -> Result<Option<Vec<u8>>, SourceError> {
15451 self.held_asset(id, BoardKind::Work(ItemKind::Task), name)
15452 .await
15453 }
15454 async fn set_task_rendering_with_assets(
15455 &self,
15456 id: &NativeId,
15457 content: &str,
15458 provenance: &Value,
15459 _answers: &BTreeMap<String, Value>,
15460 assets: &onetaskgraph_plugin_api::AssetWrite,
15461 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15462 self.replace_rendering(
15463 id,
15464 BoardKind::Work(ItemKind::Task),
15465 content,
15466 provenance,
15467 Some(assets),
15468 )
15469 .await
15470 }
15471 async fn document_assets(
15472 &self,
15473 id: &NativeId,
15474 ) -> Result<Vec<onetaskgraph_plugin_api::Asset>, SourceError> {
15475 self.held_assets(id, BoardKind::Document).await
15476 }
15477 async fn document_asset(
15478 &self,
15479 id: &NativeId,
15480 name: &onetaskgraph_plugin_api::AssetName,
15481 ) -> Result<Option<Vec<u8>>, SourceError> {
15482 self.held_asset(id, BoardKind::Document, name).await
15483 }
15484 async fn set_document_rendering_with_assets(
15485 &self,
15486 id: &NativeId,
15487 content: &str,
15488 provenance: &Value,
15489 _answers: &BTreeMap<String, Value>,
15490 assets: &onetaskgraph_plugin_api::AssetWrite,
15491 ) -> Result<Option<onetaskgraph_plugin_api::AssetsWritten>, SourceError> {
15492 self.replace_rendering(id, BoardKind::Document, content, provenance, Some(assets))
15493 .await
15494 }
15495 async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
15496 Ok(self
15497 .item_by_id(id)
15498 .await?
15499 .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15500 .map(|item| item.project()))
15501 }
15502 /// Every narrowed search and origin lookup asked, a page at a time, as aliased fields of one
15503 /// [`graphql::SEARCH_BATCH`] request a round — a search's issue search in an `s<n>` field,
15504 /// an origin's board filter in an `o<n>` field beside its issue search — and every other
15505 /// query by [`Self::query_tasks`] on its own: one narrowed by a project or by comment
15506 /// activity, one carrying no narrowing, one resumed from a cursor that read handed out, and
15507 /// every query of a process that has written this board, whose own writes complete a
15508 /// narrowed answer. A lone search is its own read too, which costs a batch's point at a
15509 /// page of its own size.
15510 ///
15511 /// Each search's first page asks [`SEARCH_BATCH_FIRST_PAGE`] rows and each later page
15512 /// [`SEARCH_PAGE_SIZE`]. GitHub answers an error about one aliased field at that field's
15513 /// path, beside the others' answers, so a refused page fails that query's answer alone; a
15514 /// request it refuses whole is every query of that request's answer.
15515 async fn query_tasks_batch(
15516 &self,
15517 asks: &[(TaskQuery, PageRequest)],
15518 ) -> Vec<Result<Page<Task>, SourceError>> {
15519 self.search_batched(asks).await
15520 }
15521 async fn query_tasks(
15522 &self,
15523 query: &TaskQuery,
15524 page: &PageRequest,
15525 ) -> Result<Page<Task>, SourceError> {
15526 validate_page(page)?;
15527 refuse_unsearchable(query)?;
15528 // A closed issue reads `done`, `cancelled` or — closed for a reason that implies no
15529 // category — `unknown`; every other category reads only off an open issue or a draft. So
15530 // a status filter naming none of those three asks every issue search it sends for open
15531 // issues alone; each candidate's category is still confirmed from its own item below.
15532 let open_only = open_only(query);
15533 if query.origin.is_none()
15534 && !matches!(query.project, ProjectFilter::Is(_))
15535 && let Some(also) = search_qualifiers(query)
15536 {
15537 return self.search_tasks(query, page, &also).await;
15538 }
15539
15540 // A read narrowed to one project asks that project for its own tasks, so nothing
15541 // about it costs what the rest of the board holds. A read carrying a text, metadata
15542 // or origin predicate asks GitHub the narrower question those predicates are, and a
15543 // read narrowed to comment activity alone asks the board's own issue search for the
15544 // issues updated since, which is every issue a comment could have been written or
15545 // edited on since. Every other task read is a question about the whole board and is
15546 // answered by reading it.
15547 let (held, membership) = match (&query.project, query.commented_since) {
15548 (ProjectFilter::Is(project), _) => (
15549 match self.held_task_children(project)? {
15550 // Taken as `project_children` takes the project's own sub-issue read: with
15551 // every item this process wrote under it since, and none it moved away.
15552 Some(held) => self.completed_with_written(
15553 held.into_iter()
15554 .filter(|child| child.parent.as_ref() == Some(project))
15555 .collect(),
15556 |own| own.parent.as_ref() == Some(project),
15557 )?,
15558 None => self.project_children(project).await?,
15559 },
15560 // Answered by where these items came from; see `task_matches`.
15561 &ProjectFilter::Any,
15562 ),
15563 (ProjectFilter::Any | ProjectFilter::Orphans, since) => {
15564 match (self.narrowed(query).await?, since) {
15565 (Some(narrowed), _) => (narrowed, &query.project),
15566 (None, Some(since)) => (self.updated_since(since).await?, &query.project),
15567 // The board's own items list every draft; only the search half, which
15568 // completes them with issues they lag behind on, is narrowed — a closed
15569 // issue that half leaves out is at no category the filter keeps.
15570 // Every category it keeps reads only off an open item, so it reads the
15571 // board's open items alone, through the board's own filter.
15572 (None, None) if open_items_only(query) => {
15573 (self.open_items().await?, &query.project)
15574 }
15575 (None, None) if open_only => (
15576 self.board_completed_by(Some(OPEN_QUALIFIER)).await?.items,
15577 &query.project,
15578 ),
15579 (None, None) => (self.board().await?.items, &query.project),
15580 }
15581 }
15582 };
15583 // Every candidate this read confirms by its comments is read together.
15584 let candidates = self.comment_candidates(held.iter(), query, membership)?;
15585 self.hold_comment_pages(&candidates).await?;
15586 // Filtered before paged: a page of a filtered result is a page of the survivors,
15587 // never the survivors of a page.
15588 let mut tasks = Vec::new();
15589 for item in held
15590 .iter()
15591 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
15592 {
15593 let task = item.task()?;
15594 if task_matches(&task, query, membership)
15595 && self.commented_since(item, query.commented_since).await?
15596 {
15597 tasks.push(task);
15598 }
15599 }
15600 Ok(offset_page(
15601 tasks,
15602 numeric_cursor(page.cursor.as_ref())?,
15603 page.limit.min(MAX_PAGE_SIZE) as usize,
15604 ))
15605 }
15606 /// Read board pages directly, at the board connection's consistency. Unlike
15607 /// `query_tasks`, this does not complete a lagging board with issue search: a complete
15608 /// sweep needs one request per listing page, including the first comments.
15609 async fn query_task_details(
15610 &self,
15611 query: &TaskQuery,
15612 page: &PageRequest,
15613 comments: Option<&PageRequest>,
15614 ) -> Result<Page<TaskDetailRead>, SourceError> {
15615 let Some(comments) = comments else {
15616 let tasks = self.query_tasks(query, page).await?;
15617 return Ok(Page {
15618 items: tasks
15619 .items
15620 .into_iter()
15621 .map(|task| TaskDetailRead {
15622 task,
15623 comments: None,
15624 })
15625 .collect(),
15626 next: tasks.next,
15627 });
15628 };
15629 validate_page(page)?;
15630 validate_page(comments)?;
15631 refuse_unsearchable(query)?;
15632 if comments.cursor.is_some() || query.commented_since.is_some() {
15633 return Err(SourceError::Refused {
15634 message: "a board listing with comments requires a first comment page and cannot filter by comment activity".into(),
15635 });
15636 }
15637 let after = page.cursor.as_ref().map(|cursor| cursor.0.as_str());
15638 let data = self
15639 .graphql(
15640 graphql::BOARD_WITH_COMMENTS,
15641 json!({
15642 "owner":self.owner,"number":self.project_number,
15643 "first":page.limit.min(MAX_PAGE_SIZE),"after":after,
15644 "commentFirst":comments.limit.min(MAX_PAGE_SIZE),
15645 "nestedFirst":NESTED_PAGE_SIZE,"duplicates":true,
15646 }),
15647 )
15648 .await?;
15649 let connection = data
15650 .pointer("/owner/projectV2/items")
15651 .filter(|value| !value.is_null())
15652 .ok_or_else(|| SourceError::Refused {
15653 message: "GitHub project was not found or is not visible to the token".into(),
15654 })?;
15655 let mut items = Vec::new();
15656 for node in optional_nodes(Some(connection), "board items")?
15657 .into_iter()
15658 .flatten()
15659 {
15660 let Some(item) = self.resolve(node)? else {
15661 continue;
15662 };
15663 if item.kind != BoardKind::Work(ItemKind::Task) {
15664 continue;
15665 }
15666 let task = item.task()?;
15667 if !task_matches(&task, query, &query.project) {
15668 continue;
15669 }
15670 let read = if item.content_kind == ContentKind::DraftIssue {
15671 Err(self.draft_has_no_comments(&task.id))
15672 } else {
15673 self.expected.learn_comments(&task.id, &node["content"]);
15674 comment_page(&node["content"], &task.id.0, None).map(Some)
15675 };
15676 items.push(TaskDetailRead {
15677 task,
15678 comments: Some(read),
15679 });
15680 }
15681 let next = next_cursor(connection)?;
15682 if let Some(next) = &next {
15683 validate_cursor_progress(after, &next.0)?;
15684 }
15685 Ok(Page { items, next })
15686 }
15687
15688 async fn query_projects(
15689 &self,
15690 query: &ProjectQuery,
15691 page: &PageRequest,
15692 ) -> Result<Page<Project>, SourceError> {
15693 validate_page(page)?;
15694 refuse_unsearchable_text(query.text.as_ref())?;
15695 // The projects a board holds are found by an issue search scoped to that board,
15696 // never by walking the board's own item connection: what tells a project from a
15697 // task is the `parent` each issue carries, which costs nothing to read. A query
15698 // carrying a text asks that search for the text too, so it reads the issues that
15699 // hold it rather than every issue of the board.
15700 let held = match self.text_searched(query.text.as_ref()).await? {
15701 Some(searched) => searched,
15702 None => self.board_issues().await?,
15703 };
15704 let projects = held
15705 .iter()
15706 .filter(|item| item.kind == BoardKind::Work(ItemKind::Project))
15707 .map(Resolved::project)
15708 .filter(|project| project_matches(project, query))
15709 .collect();
15710 Ok(offset_page(
15711 projects,
15712 numeric_cursor(page.cursor.as_ref())?,
15713 page.limit.min(MAX_PAGE_SIZE) as usize,
15714 ))
15715 }
15716 async fn query_projects_by_origin(
15717 &self,
15718 origin: &str,
15719 page: &PageRequest,
15720 ) -> Result<Page<Project>, SourceError> {
15721 validate_page(page)?;
15722 let projects = self
15723 .copied_from(origin, BoardKind::Work(ItemKind::Project))
15724 .await?
15725 .iter()
15726 .map(Resolved::project)
15727 .collect();
15728 Ok(offset_page(
15729 projects,
15730 numeric_cursor(page.cursor.as_ref())?,
15731 page.limit.min(MAX_PAGE_SIZE) as usize,
15732 ))
15733 }
15734 async fn get_document(&self, id: &NativeId) -> Result<Option<Document>, SourceError> {
15735 let Some(item) = self
15736 .document_by_id(id)
15737 .await?
15738 .filter(|item| item.kind == BoardKind::Document)
15739 else {
15740 return Ok(None);
15741 };
15742 self.expected.read_document(&item);
15743 Ok(Some(item.document()))
15744 }
15745 async fn query_documents_by_origin(
15746 &self,
15747 origin: &str,
15748 page: &PageRequest,
15749 ) -> Result<Page<Document>, SourceError> {
15750 validate_page(page)?;
15751 let documents = self
15752 .copied_from(origin, BoardKind::Document)
15753 .await?
15754 .iter()
15755 .map(Resolved::document)
15756 .collect();
15757 Ok(offset_page(
15758 documents,
15759 numeric_cursor(page.cursor.as_ref())?,
15760 page.limit.min(MAX_PAGE_SIZE) as usize,
15761 ))
15762 }
15763 async fn query_documents(
15764 &self,
15765 query: &DocumentQuery,
15766 page: &PageRequest,
15767 ) -> Result<Page<Document>, SourceError> {
15768 validate_page(page)?;
15769 // Narrowed to one project, this is the same sub-issue read a task list scoped to
15770 // that project makes — a document filed under a project is a sub-issue of it too,
15771 // and which of them come back is the kind this caller asked for. Unscoped, a query
15772 // carrying a text asks the board-scoped issue search for it, as a task query does,
15773 // and only one carrying none reads the board.
15774 let (held, membership) = match &query.project {
15775 ProjectFilter::Is(project) => (
15776 self.project_children(project).await?,
15777 // Answered by where these items came from; see `task_matches`.
15778 &ProjectFilter::Any,
15779 ),
15780 ProjectFilter::Any | ProjectFilter::Orphans => {
15781 refuse_unsearchable_text(query.text.as_ref())?;
15782 match self.text_searched(query.text.as_ref()).await? {
15783 Some(searched) => (searched, &query.project),
15784 None => (self.board().await?.items, &query.project),
15785 }
15786 }
15787 };
15788 // Filtered before paged, exactly as a task read is: a page of a filtered result is
15789 // a page of the survivors, never the survivors of a page.
15790 let documents = held
15791 .iter()
15792 .filter(|item| item.kind == BoardKind::Document)
15793 .map(Resolved::document)
15794 .filter(|document| document_matches(document, query, membership))
15795 .collect();
15796 Ok(offset_page(
15797 documents,
15798 numeric_cursor(page.cursor.as_ref())?,
15799 page.limit.min(MAX_PAGE_SIZE) as usize,
15800 ))
15801 }
15802 async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
15803 validate_page(page)?;
15804 let offset = numeric_cursor(page.cursor.as_ref())?;
15805 let mut labels = self
15806 .board()
15807 .await?
15808 .items
15809 .into_iter()
15810 .flat_map(|item| item.labels)
15811 .fold(Vec::new(), |mut all, label| {
15812 if !all.iter().any(|x: &Label| x.id == label.id) {
15813 all.push(label);
15814 }
15815 all
15816 });
15817 labels.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.0.cmp(&b.id.0)));
15818 Ok(offset_page(
15819 labels,
15820 offset,
15821 page.limit.min(MAX_PAGE_SIZE) as usize,
15822 ))
15823 }
15824 async fn task_dependencies(
15825 &self,
15826 id: &NativeId,
15827 direction: Direction,
15828 page: &PageRequest,
15829 ) -> Result<Page<DependencyEdge>, SourceError> {
15830 self.dependencies(id, ItemKind::Task, direction, page).await
15831 }
15832 async fn project_dependencies(
15833 &self,
15834 id: &NativeId,
15835 direction: Direction,
15836 page: &PageRequest,
15837 ) -> Result<Page<DependencyEdge>, SourceError> {
15838 self.dependencies(id, ItemKind::Project, direction, page)
15839 .await
15840 }
15841
15842 fn writes(&self) -> WriteSupport {
15843 WriteSupport::Supported
15844 }
15845
15846 /// Create or update one task.
15847 ///
15848 /// Its `delivers` and `delivered_by` are checked before anything is read or written —
15849 /// neither may name the task itself or name one task twice — and land in the body's
15850 /// metadata slot under their reserved keys, in place of any caller metadata of those
15851 /// names.
15852 async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
15853 if write.item.project.is_some() {
15854 self.projectless()?;
15855 }
15856 self.write_task_assets(write, None)
15857 .await
15858 .map(|written| written.id)
15859 }
15860
15861 async fn read_ahead_origins_for_copy(&self, origins: &[String]) -> Result<(), SourceError> {
15862 self.origins_ahead(origins).await
15863 }
15864
15865 async fn member_classifications(
15866 &self,
15867 project: &NativeId,
15868 ) -> Result<Option<Vec<(Classification, Vec<Repository>)>>, SourceError> {
15869 Ok(self
15870 .member_classes
15871 .lock()
15872 .map_err(|_| SourceError::Unavailable {
15873 message: "a project's members held for its classification were left \
15874 inconsistent; run the command again"
15875 .into(),
15876 })?
15877 .remove(project))
15878 }
15879
15880 /// The issue's own web address, as the `createIssue` that made it in this command answered
15881 /// it: a task, a project and a document are each an issue here.
15882 fn written_location(
15883 &self,
15884 _record: onetaskgraph_plugin_api::MetadataRecord,
15885 id: &NativeId,
15886 ) -> Option<Location> {
15887 self.written
15888 .lock()
15889 .unwrap_or_else(std::sync::PoisonError::into_inner)
15890 .get(id)
15891 .cloned()
15892 .map(Location::Url)
15893 }
15894
15895 /// [`MUTATION_BATCH`], while writes are held back: [`graphql::CREATE_ISSUES`] creates that many
15896 /// in one request, and a copy's tasks are created together only then, since their fields
15897 /// and edges are what is held back.
15898 fn create_batch_limit(&self) -> usize {
15899 if self.deferring().unwrap_or(false) {
15900 MUTATION_BATCH
15901 } else {
15902 1
15903 }
15904 }
15905
15906 // 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.
15907 async fn write_tasks(&self, writes: &[ItemWrite<Task>]) -> Result<Vec<NativeId>, SourceError> {
15908 if writes.iter().any(|write| write.item.project.is_some()) {
15909 self.projectless()?;
15910 }
15911 if let Some(write) = writes.iter().find(|write| write.target.is_some()) {
15912 return Err(SourceError::Refused {
15913 message: format!(
15914 "write_tasks creates tasks, and the write of {} names the existing task {}; \
15915 next: update it with write_task",
15916 write.item.id,
15917 write.target.as_ref().map_or("", |target| target.0.as_str())
15918 ),
15919 });
15920 }
15921 if !self.deferring()? {
15922 let mut created = Vec::with_capacity(writes.len());
15923 for write in writes {
15924 match self.write_task(write).await {
15925 Ok(id) => created.push(id),
15926 Err(error) => {
15927 let mut left: Vec<&str> = Vec::new();
15928 for id in &created {
15929 if self.delete_issue(id).await.is_err() {
15930 left.push(id.0.as_str());
15931 }
15932 }
15933 return Err(left_behind(error, &left));
15934 }
15935 }
15936 }
15937 return Ok(created);
15938 }
15939 self.create_together(writes).await
15940 }
15941
15942 fn begin_deferred_writes(&self) {
15943 if let Ok(mut deferred) = self.deferred.lock() {
15944 deferred.get_or_insert_with(Deferred::default);
15945 }
15946 }
15947
15948 async fn finish_writes(&self) -> Result<(), SourceError> {
15949 self.send_held_updates().await?;
15950 self.send_held_back().await
15951 }
15952
15953 async fn write_task_with_assets(
15954 &self,
15955 write: &ItemWrite<Task>,
15956 _answers: Option<&BTreeMap<String, Value>>,
15957 assets: &onetaskgraph_plugin_api::AssetWrite,
15958 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
15959 self.write_task_assets(write, Some(assets)).await
15960 }
15961
15962 async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
15963 self.projectless()?;
15964 self.write_item(
15965 &Incoming {
15966 written: Written::Work(ItemKind::Project, &write.item.status),
15967 title: &write.item.title,
15968 content: write.item.content.as_deref(),
15969 assets: None,
15970 labels: &write.item.labels,
15971 metadata: &write.item.metadata,
15972 repositories: &write.item.repositories,
15973 classification: write.item.classification,
15974 parent: None,
15975 delivers: &[],
15976 delivered_by: &[],
15977 priority: None,
15978 assignees: None,
15979 },
15980 write.target.as_ref(),
15981 &write.depends_on,
15982 )
15983 .await
15984 .map(|written| written.id)
15985 }
15986
15987 fn task_body_size(
15988 &self,
15989 write: &ItemWrite<Task>,
15990 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
15991 ) -> Option<onetaskgraph_plugin_api::BodySize> {
15992 Some(self.body_size(&self.task_incoming(write, assets).ok()?))
15993 }
15994
15995 fn project_body_size(
15996 &self,
15997 write: &ItemWrite<Project>,
15998 ) -> Option<onetaskgraph_plugin_api::BodySize> {
15999 Some(self.body_size(&Incoming {
16000 written: Written::Work(ItemKind::Project, &write.item.status),
16001 title: &write.item.title,
16002 content: write.item.content.as_deref(),
16003 assets: None,
16004 labels: &write.item.labels,
16005 metadata: &write.item.metadata,
16006 repositories: &write.item.repositories,
16007 classification: write.item.classification,
16008 parent: None,
16009 delivers: &[],
16010 delivered_by: &[],
16011 priority: None,
16012 assignees: None,
16013 }))
16014 }
16015
16016 fn document_body_size(
16017 &self,
16018 write: &ItemWrite<Document>,
16019 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
16020 ) -> Option<onetaskgraph_plugin_api::BodySize> {
16021 Some(self.body_size(&Incoming {
16022 written: Written::Document,
16023 title: &write.item.title,
16024 content: write.item.content.as_deref(),
16025 assets,
16026 labels: &write.item.labels,
16027 metadata: &write.item.metadata,
16028 repositories: &write.item.repositories,
16029 classification: write.item.classification,
16030 parent: write.item.project.as_ref(),
16031 delivers: &[],
16032 delivered_by: &[],
16033 priority: None,
16034 assignees: None,
16035 }))
16036 }
16037
16038 /// Create or update one document, which is one issue titled the way this board spells
16039 /// a document.
16040 ///
16041 /// Everything else is exactly a task write: caller metadata goes to the same canonical
16042 /// JSON slot at the end of the body and comes back with its JSON types intact, a key
16043 /// or a field this board cannot carry is refused by name rather than dropped, a target
16044 /// naming an issue this board does not hold is refused rather than created, and an
16045 /// issue this call created is taken back when the rest of the write fails.
16046 async fn write_document(&self, write: &ItemWrite<Document>) -> Result<NativeId, SourceError> {
16047 self.write_document_assets(write, None)
16048 .await
16049 .map(|written| written.id)
16050 }
16051
16052 async fn write_document_with_assets(
16053 &self,
16054 write: &ItemWrite<Document>,
16055 _answers: Option<&BTreeMap<String, Value>>,
16056 assets: &onetaskgraph_plugin_api::AssetWrite,
16057 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
16058 self.write_document_assets(write, Some(assets)).await
16059 }
16060
16061 /// Refused exactly as the write refuses it, from what the write reads: the mapping first,
16062 /// which reads nothing; then the board's `Status` option. Over an existing item that is
16063 /// read off the item, as the write reads it, and the item is held among this command's
16064 /// resolved records so the write that follows reuses that read rather than repeating it;
16065 /// an item that does not carry the field takes the board's fields, which are held once
16066 /// read. A create is checked against the board's fields only when this command already
16067 /// holds them, because a create reads them together with its repository, in one request,
16068 /// and refuses a missing option before it writes anything.
16069 async fn check_status_write(
16070 &self,
16071 kind: ItemKind,
16072 category: StatusCategory,
16073 target: Option<&NativeId>,
16074 ) -> Result<(), SourceError> {
16075 let status = self.resolved_target(kind, category)?;
16076 if status.option().is_none() {
16077 return Ok(());
16078 }
16079 let fields = match target {
16080 Some(target) => {
16081 // A target this board does not hold is the write's own refusal to make.
16082 let Some(item) = self.bound_item(target).await? else {
16083 return Ok(());
16084 };
16085 self.resolved_cache()?.insert(target.clone(), item.clone());
16086 // Only the `Status` field decides whether the write can land.
16087 self.fields_for(Some(&item), false, true, false)
16088 .await?
16089 .fields
16090 }
16091 None => {
16092 let held = self
16093 .board_cache()?
16094 .as_ref()
16095 .map(|board| board.fields.clone());
16096 match held.or_else(|| {
16097 self.fields_cache()
16098 .ok()
16099 .and_then(|cache| cache.as_ref().map(|board| board.fields.clone()))
16100 }) {
16101 Some(fields) => fields,
16102 None => return Ok(()),
16103 }
16104 }
16105 };
16106 self.column_for(&fields, kind, category, &status)
16107 .map(|_| ())
16108 }
16109
16110 /// Whether this instance's resolved mapping — its `status_mapping` over the shipped
16111 /// defaults — gives `category` an option for `kind`. The board's `Status` field is not
16112 /// read: an option the field lacks is the write's own refusal.
16113 fn maps_status(&self, kind: ItemKind, category: StatusCategory) -> bool {
16114 !matches!(
16115 self.statuses.target(kind, category),
16116 StatusTarget::Disabled(_)
16117 )
16118 }
16119
16120 /// What a write of `status` reads back as: the `Status` option its category maps to for
16121 /// `kind`, and for a closing category the closure that option and its fixed reason read
16122 /// as — exactly what [`BoardStatuses::status`] reports of the item once written. A category
16123 /// this instance has no option for is answered as given, since writing it is refused.
16124 fn status_as_written(&self, kind: ItemKind, status: &Status) -> Status {
16125 match self.statuses.target(kind, status.category) {
16126 StatusTarget::Column(name) => {
16127 self.statuses.status(kind, Some(name.as_str()), false, None)
16128 }
16129 StatusTarget::Terminal(name, reason) => {
16130 self.statuses
16131 .status(kind, Some(name.as_str()), true, Some(reason.reason()))
16132 }
16133 StatusTarget::Disabled(_) => status.clone(),
16134 }
16135 }
16136
16137 /// Set one task's status alone.
16138 ///
16139 /// An open target reopens a closed issue with an `updateIssue` carrying only its
16140 /// `stateInput`, then selects the board option with `updateProjectV2ItemFieldValue`; a
16141 /// terminal target selects its mapped option, then closes with its fixed reason. No
16142 /// request carries a title, a body or a label. The status
16143 /// answered is what [`BoardStatuses::status`] reads off the state just written, which is
16144 /// what a re-read reports.
16145 async fn set_task_status(
16146 &self,
16147 id: &NativeId,
16148 category: StatusCategory,
16149 ) -> Result<Option<Status>, SourceError> {
16150 self.set_status(id, ItemKind::Task, category).await
16151 }
16152
16153 /// Set one task's status and answer the task with it, reading the item once: the read the
16154 /// task is answered from is handed to the status write, which would otherwise read the
16155 /// same issue again — two requests on a fresh process, the read and the field write,
16156 /// where the default's `get_task` before `set_task_status` sent three.
16157 async fn set_task_status_reading(
16158 &self,
16159 id: &NativeId,
16160 category: StatusCategory,
16161 ) -> Result<Option<Task>, SourceError> {
16162 // Refused before anything is read, in the words the write itself refuses it.
16163 self.resolved_target(ItemKind::Task, category)?;
16164 let Some(item) = self
16165 .bound_item(id)
16166 .await?
16167 .filter(|item| item.kind == BoardKind::Work(ItemKind::Task))
16168 else {
16169 return Ok(None);
16170 };
16171 let mut task = item.task()?;
16172 self.held_cache
16173 .lock()
16174 .map_err(|_| SourceError::Unavailable {
16175 message: "items read by issue reference were left inconsistent; run the \
16176 command again"
16177 .into(),
16178 })?
16179 .insert(id.clone(), item);
16180 let Some(status) = self.set_status(id, ItemKind::Task, category).await? else {
16181 return Ok(None);
16182 };
16183 task.status = status;
16184 Ok(Some(task))
16185 }
16186
16187 /// Set one project's status alone, by exactly the paired write a task's status takes, for
16188 /// the project kind: a terminal category selects the project kind's mapped option and then
16189 /// closes the issue with the category's fixed reason — an issue already closed with a
16190 /// reason that reads that category is left as it is — and an open category reopens a closed
16191 /// issue and then selects its option. A board draft is refused a terminal category as a
16192 /// task's is.
16193 async fn set_project_status(
16194 &self,
16195 id: &NativeId,
16196 category: StatusCategory,
16197 ) -> Result<Option<Status>, SourceError> {
16198 self.projectless()?;
16199 self.set_status(id, ItemKind::Project, category).await
16200 }
16201
16202 /// Every task and project whose card contradicts its issue's closure, read through the
16203 /// board's own `is:closed` filter; see [`TaskSource::status_contradictions`].
16204 async fn status_contradictions(&self) -> Result<Vec<StatusContradiction>, SourceError> {
16205 self.contradictions().await
16206 }
16207
16208 /// What this board holds for each issue reference, one request per fifty of them; see
16209 /// [`TaskSource::issue_holdings`].
16210 async fn issue_holdings(&self, issues: &[IssueRef]) -> Result<Vec<IssueHolding>, SourceError> {
16211 self.holdings(issues).await
16212 }
16213
16214 /// Set one task's priority alone: one `updateProjectV2ItemFieldValue` selecting the
16215 /// mapped option of the board's `Priority` field, or one `clearProjectV2ItemFieldValue`
16216 /// for `none`. Refused by an instance with no `priority_mapping`.
16217 async fn set_task_priority(
16218 &self,
16219 id: &NativeId,
16220 priority: Priority,
16221 ) -> Result<Option<Priority>, SourceError> {
16222 self.set_priority(id, priority).await
16223 }
16224
16225 /// Replace one task's content with a single body update that keeps the metadata slot
16226 /// byte for byte.
16227 async fn set_task_content(
16228 &self,
16229 id: &NativeId,
16230 content: &str,
16231 ) -> Result<Option<()>, SourceError> {
16232 self.replace_content(id, content).await
16233 }
16234
16235 /// Replace one task issue's content and its provenance slot entry with a single body
16236 /// update. The answers are not kept: see `replace_rendering`.
16237 async fn set_task_rendering(
16238 &self,
16239 id: &NativeId,
16240 content: &str,
16241 provenance: &Value,
16242 _answers: &BTreeMap<String, Value>,
16243 ) -> Result<Option<()>, SourceError> {
16244 self.replace_rendering(
16245 id,
16246 BoardKind::Work(ItemKind::Task),
16247 content,
16248 provenance,
16249 None,
16250 )
16251 .await
16252 .map(|written| written.map(|_| ()))
16253 }
16254
16255 /// Replace one design-document issue's content and its provenance slot entry, on exactly
16256 /// the terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16257 async fn set_document_rendering(
16258 &self,
16259 id: &NativeId,
16260 content: &str,
16261 provenance: &Value,
16262 _answers: &BTreeMap<String, Value>,
16263 ) -> Result<Option<()>, SourceError> {
16264 self.replace_rendering(id, BoardKind::Document, content, provenance, None)
16265 .await
16266 .map(|written| written.map(|_| ()))
16267 }
16268
16269 /// Replace one project issue's content and its provenance slot entry, on exactly the
16270 /// terms of [`set_task_rendering`](TaskSource::set_task_rendering).
16271 async fn set_project_rendering(
16272 &self,
16273 id: &NativeId,
16274 content: &str,
16275 provenance: &Value,
16276 _answers: &BTreeMap<String, Value>,
16277 ) -> Result<Option<()>, SourceError> {
16278 self.projectless()?;
16279 self.replace_rendering(
16280 id,
16281 BoardKind::Work(ItemKind::Project),
16282 content,
16283 provenance,
16284 None,
16285 )
16286 .await
16287 .map(|written| written.map(|_| ()))
16288 }
16289
16290 /// Apply a targeted update with one read of the item and a write only for what differs:
16291 /// the `Status` and `Priority` field writes in one request, the `blockedBy` difference,
16292 /// and last one `updateIssue` for title, body and state. See `targeted_update`.
16293 async fn update_task(
16294 &self,
16295 id: &NativeId,
16296 update: &TaskUpdate,
16297 ) -> Result<Option<TaskUpdateOutcome>, SourceError> {
16298 self.targeted_update(id, update).await
16299 }
16300
16301 /// Each issue's sub-issue parent and children and its links, read in batches.
16302 async fn read_relations(
16303 &self,
16304 ids: &[NativeId],
16305 ) -> Vec<Result<Option<onetaskgraph_plugin_api::Relations>, SourceError>> {
16306 self.relations_of(ids).await
16307 }
16308
16309 async fn set_parents(
16310 &self,
16311 writes: &[onetaskgraph_plugin_api::ParentWrite],
16312 ) -> Vec<Result<onetaskgraph_plugin_api::ParentAnswer, SourceError>> {
16313 self.parents_set(writes).await
16314 }
16315
16316 fn link_types(&self) -> onetaskgraph_plugin_api::LinkTypes {
16317 self.link_types.clone()
16318 }
16319
16320 async fn add_native_links(
16321 &self,
16322 links: &[onetaskgraph_plugin_api::NativeLink],
16323 ) -> Vec<Result<(), SourceError>> {
16324 self.native_links(links, relations::NativeWrite::Add).await
16325 }
16326
16327 async fn remove_native_links(
16328 &self,
16329 links: &[onetaskgraph_plugin_api::NativeLink],
16330 ) -> Vec<Result<(), SourceError>> {
16331 self.native_links(links, relations::NativeWrite::Remove)
16332 .await
16333 }
16334
16335 /// Every task read together — [`DETAIL_BATCH`] to a [`graphql::ISSUE_DETAILS`] request —
16336 /// and each update's hold and guard decided on that read; then each update the read lets
16337 /// through composed exactly as [`Self::update_task`] composes one, its board field writes
16338 /// and its issue update held back and sent in [`graphql::WRITE_TASKS`] requests: every
16339 /// field write first, then the issue update of every task whose field writes all landed.
16340 ///
16341 /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16342 /// batched node read naming an id that resolves to nothing is refused whole, so each id of
16343 /// that batch is read by itself, the missing one answered missing and the rest as
16344 /// themselves. A batch of one, an update of a board draft, one naming dependencies and one
16345 /// of an item whose body this process has not read are each made on their own, as
16346 /// [`Self::update_task`] makes them, because each sends writes of its own in an order the
16347 /// batch does not hold. A field write GitHub refuses fails that task's update alone and
16348 /// sends nothing of its body.
16349 async fn update_tasks(
16350 &self,
16351 updates: &[onetaskgraph_plugin_api::BatchUpdate],
16352 ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<TaskUpdateOutcome>, SourceError>> {
16353 self.updates_batched(updates).await
16354 }
16355
16356 /// Replace one task's `delivered_by` with a single body update that changes the
16357 /// metadata slot and nothing outside it.
16358 async fn set_delivered_by(
16359 &self,
16360 id: &NativeId,
16361 delivered_by: &[TaskRef],
16362 ) -> Result<Option<()>, SourceError> {
16363 self.replace_delivered_by(id, delivered_by).await
16364 }
16365
16366 /// Set one key of one task issue's metadata with a single body update that changes the
16367 /// metadata slot and nothing outside it — no title, label, state or board field request —
16368 /// and sends nothing when the task already holds that value under the key.
16369 async fn set_task_metadata(
16370 &self,
16371 id: &NativeId,
16372 key: &MetadataKey,
16373 value: &Value,
16374 ) -> Result<Option<Task>, SourceError> {
16375 Ok(self
16376 .set_slot_key(id, BoardKind::Work(ItemKind::Task), key, value)
16377 .await?
16378 .map(|item| item.task())
16379 .transpose()?)
16380 }
16381
16382 /// Set one key of one project issue's metadata, on exactly the terms of
16383 /// [`set_task_metadata`](TaskSource::set_task_metadata).
16384 async fn set_project_metadata(
16385 &self,
16386 id: &NativeId,
16387 key: &MetadataKey,
16388 value: &Value,
16389 ) -> Result<Option<Project>, SourceError> {
16390 self.projectless()?;
16391 Ok(self
16392 .set_slot_key(id, BoardKind::Work(ItemKind::Project), key, value)
16393 .await?
16394 .map(|item| item.project()))
16395 }
16396
16397 /// Set one key of one design-document issue's metadata, on exactly the terms of
16398 /// [`set_task_metadata`](TaskSource::set_task_metadata).
16399 async fn set_document_metadata(
16400 &self,
16401 id: &NativeId,
16402 key: &MetadataKey,
16403 value: &Value,
16404 ) -> Result<Option<Document>, SourceError> {
16405 Ok(self
16406 .set_slot_key(id, BoardKind::Document, key, value)
16407 .await?
16408 .map(|item| item.document()))
16409 }
16410
16411 /// Take one key out of one issue's metadata slot with a single body update that changes the
16412 /// slot and nothing outside it, sending nothing when the slot does not hold the key.
16413 async fn remove_record_metadata(
16414 &self,
16415 record: onetaskgraph_plugin_api::MetadataRecord,
16416 id: &NativeId,
16417 key: &MetadataKey,
16418 ) -> Result<Option<Option<String>>, SourceError> {
16419 let kind = match record {
16420 onetaskgraph_plugin_api::MetadataRecord::Task => BoardKind::Work(ItemKind::Task),
16421 onetaskgraph_plugin_api::MetadataRecord::Project => BoardKind::Work(ItemKind::Project),
16422 onetaskgraph_plugin_api::MetadataRecord::Document => BoardKind::Document,
16423 };
16424 let Some(mut item) = self.bound_item(id).await?.filter(|item| item.kind == kind) else {
16425 return Ok(None);
16426 };
16427 if item.slot.contains_key(key.as_str()) {
16428 let mut slot = item.slot.clone();
16429 slot.remove(key.as_str());
16430 self.write_slot(&mut item, &slot).await?;
16431 self.remember_written(item.clone(), false)?;
16432 }
16433 Ok(Some(match record {
16434 onetaskgraph_plugin_api::MetadataRecord::Task => item.task()?.version,
16435 onetaskgraph_plugin_api::MetadataRecord::Project => item.project().version,
16436 onetaskgraph_plugin_api::MetadataRecord::Document => item.document().version,
16437 }))
16438 }
16439
16440 async fn delete_task(&self, id: &NativeId) -> Result<(), SourceError> {
16441 self.delete_item(id).await
16442 }
16443
16444 async fn delete_project(&self, id: &NativeId) -> Result<(), SourceError> {
16445 self.projectless()?;
16446 self.delete_item(id).await
16447 }
16448
16449 async fn delete_document(&self, id: &NativeId) -> Result<(), SourceError> {
16450 self.delete_item(id).await
16451 }
16452
16453 /// One page of the task issue's own comments, walked by GitHub's own cursor.
16454 ///
16455 /// Nothing here filters, so nothing has to be read ahead of the page: the caller's limit is
16456 /// the page GitHub is asked for and GitHub's `endCursor` is the cursor handed back.
16457 ///
16458 /// One request, [`graphql::ISSUE_DETAIL`]: the read that says the id names a task of this
16459 /// board is the read of its comments. A draft this process already resolved is refused
16460 /// without one.
16461 async fn task_comments(
16462 &self,
16463 task: &NativeId,
16464 page: &PageRequest,
16465 ) -> Result<Option<Page<Comment>>, SourceError> {
16466 validate_page(page)?;
16467 let cached = self.resolved_cache()?.get(task).cloned();
16468 if let Some(item) = cached {
16469 if item.kind != BoardKind::Work(ItemKind::Task) {
16470 return Ok(None);
16471 }
16472 if item.content_kind == ContentKind::DraftIssue {
16473 return Err(self.draft_has_no_comments(task));
16474 }
16475 }
16476 // The first page a comment-activity read just read of this task, at the size asked, is
16477 // that read's answer: taken, so it answers once.
16478 if page.cursor.is_none()
16479 && page.limit >= MAX_PAGE_SIZE
16480 && let Some(held) = self.held_comments()?.remove(task)
16481 {
16482 return Ok(Some(held));
16483 }
16484 match self.issue_detail(task, page).await? {
16485 Some(TaskDetailRead {
16486 comments: Some(comments),
16487 ..
16488 }) => comments,
16489 _ => Ok(None),
16490 }
16491 }
16492
16493 /// Every id's task, with the first page of its comments when `comments` names it:
16494 /// [`DETAIL_BATCH`] items per [`graphql::ISSUE_DETAILS`] request, and one item with its
16495 /// comments in one [`graphql::ISSUE_DETAIL`] request.
16496 async fn get_task_details(
16497 &self,
16498 ids: &[NativeId],
16499 comments: Option<&PageRequest>,
16500 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16501 if let Some(page) = comments
16502 && let Err(error) = validate_page(page)
16503 {
16504 return ids.iter().map(|_| Err(error.clone())).collect();
16505 }
16506 match (ids, comments) {
16507 ([id], Some(page)) => vec![self.issue_detail(id, page).await],
16508 ([id], None) => vec![self.task_read(id).await],
16509 _ => self.issue_details(ids, comments).await,
16510 }
16511 }
16512
16513 /// Every id's task with the first page of its comments and its `blockedBy`, as a copy reads
16514 /// the tasks it carries: [`COPY_DETAIL_BATCH`] items per [`graphql::ISSUE_COPY_DETAILS`]
16515 /// request, so the dependency read a copy makes of each next is answered from this one.
16516 async fn get_task_details_for_copy(
16517 &self,
16518 ids: &[NativeId],
16519 comments: &PageRequest,
16520 ) -> Vec<Result<Option<TaskDetailRead>, SourceError>> {
16521 // A page past the first is a page of one task's comments, which the detail read of it
16522 // alone answers.
16523 if comments.cursor.is_some() {
16524 return self.get_task_details(ids, Some(comments)).await;
16525 }
16526 if let Err(error) = validate_page(comments) {
16527 return ids.iter().map(|_| Err(error.clone())).collect();
16528 }
16529 let mut read = Vec::with_capacity(ids.len());
16530 for batch in ids.chunks(COPY_DETAIL_BATCH) {
16531 match self
16532 .graphql(
16533 graphql::ISSUE_COPY_DETAILS,
16534 copy_detail_batch(batch, comments, false),
16535 )
16536 .await
16537 {
16538 Ok(data) => {
16539 for (slot, id) in batch.iter().enumerate() {
16540 let read_one = match data.get(format!("i{slot}")) {
16541 Some(node) => self.detail_of(id, node, true, None).await,
16542 None => Err(SourceError::Malformed {
16543 message: format!(
16544 "GitHub answered a batch read with no item for {}",
16545 id.0
16546 ),
16547 }),
16548 };
16549 read.push(read_one);
16550 }
16551 }
16552 Err(error) if unresolvable_node(&error) => {
16553 for id in batch {
16554 read.push(self.issue_detail(id, comments).await);
16555 }
16556 }
16557 Err(error) => read.extend(batch.iter().map(|_| Err(error.clone()))),
16558 }
16559 }
16560 read
16561 }
16562
16563 /// Every id's item, whatever kind it is, read [`COPY_DETAIL_BATCH`] at a time with
16564 /// [`graphql::ISSUE_COPY_DETAILS`] — the document a copy reads the tasks it carries with —
16565 /// and held for the next read of each by id; see `read_ahead`.
16566 ///
16567 /// What this run wrote is never read: its own record answers, as it does for a read by id.
16568 /// Nor is an item a listing of its project carried whole earlier in this command — see
16569 /// `carried` — which is held in place of reading it.
16570 /// A batch GitHub refuses because one of its ids resolves to no node at all holds nothing,
16571 /// so each of its ids is read on its own and answered as that read answers; a draft, and an
16572 /// answer naming another issue than the one asked for, are left to their own reads too.
16573 async fn read_ahead_for_copy(&self, ids: &[NativeId]) -> Result<(), SourceError> {
16574 // The origins asked just before go out now, beside the members of the one project this
16575 // names when it names one; a project those origins answered whole is held for its next
16576 // read by id rather than read again here.
16577 let hinted = match ids {
16578 [one] => Some(one),
16579 _ => None,
16580 };
16581 self.send_pending_origins(hinted).await?;
16582 if let Some(project) = hinted {
16583 let answered = self.resolved_cache()?.get(project).cloned();
16584 if let Some(answered) = answered
16585 && answered.kind == BoardKind::Work(ItemKind::Project)
16586 {
16587 self.read_ahead()?.insert(project.clone(), Some(answered));
16588 return Ok(());
16589 }
16590 }
16591 let mut unread: Vec<NativeId> = Vec::new();
16592 // Read whole by a listing of its project in this command, which a mutation naming it
16593 // would have dropped: held as a batch would have held it, once every batch is answered.
16594 let mut listed: Vec<NativeId> = Vec::new();
16595 {
16596 let created = self.created()?;
16597 let held = self.read_ahead()?;
16598 let carried = self.carried()?;
16599 for id in ids {
16600 if unread.contains(id)
16601 || listed.contains(id)
16602 || held.contains_key(id)
16603 || created.iter().any(|own| own.id == *id)
16604 {
16605 continue;
16606 }
16607 // An issue a listing carried without the whole of what blocks it is read in a
16608 // batch too, which carries that, rather than having its dependency read sent
16609 // on its own once the copy reconciles its edges.
16610 let whole = carried.get(id).is_some_and(|item| {
16611 item.content_kind != ContentKind::Issue || item.blocked_by.is_some()
16612 });
16613 if whole {
16614 listed.push(id.clone());
16615 } else {
16616 unread.push(id.clone());
16617 }
16618 }
16619 }
16620 // Nothing of an item's comments is wanted here: the smallest page keeps the read to
16621 // what the item itself costs.
16622 let comments = PageRequest {
16623 cursor: None,
16624 limit: 1,
16625 };
16626 // Held only once every batch has been answered, so a read-ahead that fails part way
16627 // holds nothing — what a listing carried included, which stays carried — and every
16628 // item is read on its own, as the method promises.
16629 let mut read: Vec<(NativeId, Option<Resolved>)> = Vec::new();
16630 // The issues the first id names as sub-issues, as `ISSUE_COPY_DETAILS`'s `children`
16631 // answered them: what a project copy's orphan check asks, when that first id is its
16632 // project.
16633 let mut children: Option<(NativeId, Vec<(String, String)>)> = None;
16634 for (index, batch) in unread.chunks(COPY_DETAIL_BATCH).enumerate() {
16635 let data = match self
16636 .graphql(
16637 graphql::ISSUE_COPY_DETAILS,
16638 copy_detail_batch(batch, &comments, index == 0),
16639 )
16640 .await
16641 {
16642 Ok(data) => data,
16643 Err(error) if unresolvable_node(&error) => continue,
16644 Err(error) => return Err(error),
16645 };
16646 for (slot, id) in batch.iter().enumerate() {
16647 let Some(node) = data.get(format!("i{slot}")) else {
16648 continue;
16649 };
16650 let held = if node.is_null() {
16651 None
16652 } else {
16653 match optional_str(node, "__typename")? {
16654 Some("DraftIssue") => continue,
16655 Some("Issue") if required_str(node, "id")? != id.0 => continue,
16656 _ => {}
16657 }
16658 // Remembered below with the rest, so a later batch refused leaves no
16659 // dependency read answered from this one either.
16660 self.resolve_issue_as(node, false).await?
16661 };
16662 read.push((id.clone(), held));
16663 }
16664 if index == 0
16665 && let Some(node) = data.get("children").filter(|node| !node.is_null())
16666 && node.get("id").and_then(Value::as_str) == batch.first().map(|id| id.0.as_str())
16667 && node.pointer("/subIssues/pageInfo/hasNextPage") == Some(&Value::Bool(false))
16668 {
16669 // A list GitHub did not answer is not an empty one: it would answer the project's
16670 // task listing with nothing, and the orphan check with no orphans.
16671 let listed = node
16672 .pointer("/subIssues/nodes")
16673 .and_then(Value::as_array)
16674 .ok_or_else(|| SourceError::Malformed {
16675 message: format!(
16676 "GitHub answered the sub-issues of project {} with no list of them",
16677 batch[0].0
16678 ),
16679 })?
16680 .iter()
16681 .map(|child| {
16682 Ok((
16683 required_str(child, "id")?.to_owned(),
16684 required_str(child, "title")?.to_owned(),
16685 ))
16686 })
16687 .collect::<Result<Vec<_>, SourceError>>()?;
16688 children = Some((batch[0].clone(), listed));
16689 }
16690 }
16691 // The project's tasks are known from this read alone when every child it named is held
16692 // from it, but for a document, which its title says is one and which a task listing
16693 // never answers: then a listing of the project's tasks is answered from them.
16694 if let Some((project, listed)) = children
16695 && read.iter().any(|(id, held)| {
16696 *id == project
16697 && held
16698 .as_ref()
16699 .is_some_and(|held| held.kind == BoardKind::Work(ItemKind::Project))
16700 })
16701 {
16702 let mut tasks = Vec::new();
16703 let mut whole = true;
16704 for (child, title) in &listed {
16705 match read.iter().find(|(id, _)| id.0 == *child) {
16706 Some((_, Some(held))) if held.parent.as_ref() == Some(&project) => {
16707 if held.kind == BoardKind::Work(ItemKind::Task) {
16708 tasks.push(held.clone());
16709 }
16710 }
16711 _ if title.starts_with(DESIGN_TITLE_PREFIX) => {}
16712 _ => whole = false,
16713 }
16714 }
16715 if whole {
16716 self.task_children()?.insert(project, tasks);
16717 }
16718 }
16719 let mut resolved = self.resolved_cache()?;
16720 let mut ahead = self.read_ahead()?;
16721 let mut carried = self.carried()?;
16722 for item in read.iter().filter_map(|(_, held)| held.as_ref()) {
16723 resolved.insert(item.id.clone(), item.clone());
16724 }
16725 // Taken only if still carried: a mutation naming it while the batches ran dropped it,
16726 // and its next read is then its own.
16727 for id in &listed {
16728 let Some(item) = carried.remove(id) else {
16729 continue;
16730 };
16731 // The whole of what it is blocked by came with it, so the dependency read a copy
16732 // makes next is answered from this one, as a copy's detail read is.
16733 if item.blocked_by.is_some() {
16734 resolved.insert(item.id.clone(), item.clone());
16735 }
16736 read.push((id.clone(), Some(item)));
16737 }
16738 for (id, held) in read {
16739 ahead.insert(id, held);
16740 }
16741 Ok(())
16742 }
16743
16744 /// Add one comment to the task's issue, as the account the token belongs to.
16745 ///
16746 /// The author is refused before anything is sent — not even the task is read — because
16747 /// no answer GitHub could give would make posting under another name than the one asked
16748 /// for the right outcome.
16749 async fn add_comment(
16750 &self,
16751 task: &NativeId,
16752 comment: &NewComment,
16753 ) -> Result<Option<Comment>, SourceError> {
16754 if let Some(author) = &comment.author {
16755 return Err(SourceError::Refused {
16756 message: format!(
16757 "source {} cannot post a comment as {author:?}: GitHub records the account \
16758 the token signs in as the author of every comment; next: leave --author \
16759 out, and the comment is posted as that account",
16760 self.name
16761 ),
16762 });
16763 }
16764 let Some(issue) = self.commented_issue(task).await? else {
16765 return Ok(None);
16766 };
16767 let data = self
16768 .graphql(
16769 graphql::ADD_COMMENT,
16770 json!({"input":{"subjectId":issue.0,"body":comment.body.as_str()}}),
16771 )
16772 .await?;
16773 let subject = data
16774 .pointer("/addComment/subject")
16775 .filter(|value| !value.is_null())
16776 .ok_or_else(|| SourceError::Malformed {
16777 message: "GitHub comment addition returned no subject".into(),
16778 })?;
16779 if required_str(subject, "id")? != issue.0 {
16780 return Err(SourceError::Malformed {
16781 message: "GitHub comment addition answered about another issue".into(),
16782 });
16783 }
16784 let added = data
16785 .pointer("/addComment/commentEdge/node")
16786 .filter(|value| !value.is_null())
16787 .ok_or_else(|| SourceError::Malformed {
16788 message: "GitHub comment addition returned no comment".into(),
16789 })?;
16790 let added = comment_from(added)?;
16791 self.remember_commented(&issue)?;
16792 Ok(Some(added))
16793 }
16794
16795 /// Every task commented on read together — [`DETAIL_BATCH`] to a
16796 /// [`graphql::ISSUE_DETAILS`] request — and each comment's hold decided on that read; then
16797 /// every comment it lets through added by aliased `addComment`s of one
16798 /// [`graphql::ADD_COMMENTS`] request per [`COMMENT_BATCH`]. GitHub answers a refusal of one
16799 /// alias at that alias's path, so it fails that comment alone.
16800 ///
16801 /// **Where GitHub would refuse the batch as a whole, each item is read on its own:** a
16802 /// batched node read naming an id that resolves to nothing is refused whole, so each id of
16803 /// that batch is read by itself, the missing one answered missing. A batch of one is the
16804 /// comment alone, as [`Self::add_comment`] adds it.
16805 async fn add_comments(
16806 &self,
16807 comments: &[onetaskgraph_plugin_api::BatchComment],
16808 ) -> Vec<Result<onetaskgraph_plugin_api::BatchAnswer<Comment>, SourceError>> {
16809 self.comments_batched(comments).await
16810 }
16811
16812 async fn edit_comment(
16813 &self,
16814 task: &NativeId,
16815 comment: &NativeId,
16816 body: &CommentBody,
16817 ) -> Result<Option<Comment>, SourceError> {
16818 let Some(issue) = self.commented_issue(task).await? else {
16819 return Ok(None);
16820 };
16821 let Some(held) = self.comment_on(&issue, comment).await? else {
16822 return Ok(None);
16823 };
16824 // A comment a copy wrote keeps its origin through an edit: its marker is carried over.
16825 let body = CommentOrigin::kept(&held, body)?;
16826 let data = self
16827 .graphql(
16828 graphql::UPDATE_COMMENT,
16829 json!({"input":{"id":comment.0,"body":body.as_str()}}),
16830 )
16831 .await?;
16832 let edited = data
16833 .pointer("/updateIssueComment/issueComment")
16834 .filter(|value| !value.is_null())
16835 .ok_or_else(|| SourceError::Malformed {
16836 message: "GitHub comment update returned no comment".into(),
16837 })?;
16838 let edited = comment_from(edited)?;
16839 if edited.id != *comment {
16840 return Err(SourceError::Malformed {
16841 message: "GitHub comment update returned the wrong comment".into(),
16842 });
16843 }
16844 self.remember_commented(&issue)?;
16845 Ok(Some(edited))
16846 }
16847
16848 async fn delete_comment(
16849 &self,
16850 task: &NativeId,
16851 comment: &NativeId,
16852 ) -> Result<Option<NativeId>, SourceError> {
16853 let Some(issue) = self.commented_issue(task).await? else {
16854 return Ok(None);
16855 };
16856 if !self.comment_is_on(&issue, comment).await? {
16857 return Ok(None);
16858 }
16859 self.held_comments()?.remove(&issue);
16860 let data = self
16861 .graphql(graphql::DELETE_COMMENT, json!({"input":{"id":comment.0}}))
16862 .await?;
16863 // The payload says nothing about the comment it removed, so what is checked is that
16864 // GitHub answered the mutation at all rather than leaving it unanswered.
16865 data.get("deleteIssueComment")
16866 .filter(|value| !value.is_null())
16867 .ok_or_else(|| SourceError::Malformed {
16868 message: "GitHub comment deletion returned no payload".into(),
16869 })?;
16870 Ok(Some(comment.clone()))
16871 }
16872
16873 /// Every request this source has recorded, and what each of GitHub's two budgets was
16874 /// attributed — read off the same accounting the session report is rendered from, so
16875 /// the two cannot count one request two ways.
16876 async fn metering(&self) -> Result<Option<Metering>, SourceError> {
16877 Ok(Some(self.ledger.snapshot().metering()))
16878 }
16879
16880 /// One `GET /rate_limit` at this source's endpoint, every resource it reports, asked
16881 /// afresh each time and counted in nothing [`metering`](TaskSource::metering) reports:
16882 /// GitHub documents the endpoint as free. See [`quota`].
16883 async fn quota(&self) -> Result<Vec<onetaskgraph_plugin_api::QuotaReading>, SourceError> {
16884 self.rate_limits().await
16885 }
16886
16887 /// Drop every item, search answer and board read this source holds, so the next command
16888 /// reads the board as a person has since left it.
16889 ///
16890 /// Every one of those is held on the assumption that nothing but this source writes the
16891 /// board while a command runs, which stops being true the moment the command is over: a
16892 /// body a person edited would be overwritten from the record held here, and a card they
16893 /// moved would be read as still where this source left it. The board's own field
16894 /// definitions go too, because a person can add or delete a `Status` option and a write
16895 /// resolved against the held list would not re-read on a miss. What stays is what stays
16896 /// valid in normal use: each repository's node id, which a miss re-reads, the pacing of
16897 /// mutations, which is about GitHub's limiter rather than anybody's work, and the running
16898 /// accounting [`metering`](TaskSource::metering) answers from.
16899 ///
16900 /// Infallible in practice: a lock an earlier failure poisoned is cleared rather than
16901 /// refused, because clearing it is what puts it right.
16902 async fn end_command(&self) -> Result<(), SourceError> {
16903 fn clear<T: Default>(held: &Mutex<T>) {
16904 *held
16905 .lock()
16906 .unwrap_or_else(std::sync::PoisonError::into_inner) = T::default();
16907 held.clear_poison();
16908 }
16909 clear(&self.created);
16910 clear(&self.updated);
16911 clear(&self.commented);
16912 clear(&self.board_cache);
16913 clear(&self.search_cache);
16914 clear(&self.narrowed_cache);
16915 clear(&self.search_next);
16916 clear(&self.resolved_cache);
16917 clear(&self.read_ahead);
16918 clear(&self.pending_origins);
16919 clear(&self.member_classes);
16920 clear(&self.carried);
16921 clear(&self.held_cache);
16922 clear(&self.children_cache);
16923 clear(&self.task_children);
16924 clear(&self.written);
16925 clear(&self.fields_cache);
16926 clear(&self.held_comments);
16927 clear(&self.task_writes);
16928 clear(&self.written_tokens);
16929 self.forget_at_end_of_call();
16930 self.expected.end_command();
16931 Ok(())
16932 }
16933}
16934
16935/// One member of a project as a classification-only read answers it: its classification and
16936/// the repositories its work changes.
16937type MemberClass = (Classification, Vec<Repository>);
16938
16939/// Each project's sub-issues as one command read them, keyed by the selector they were asked
16940/// for under, beside the project that selector named; see `children_cache`.
16941type ProjectChildren = BTreeMap<NativeId, (NativeId, Vec<Resolved>)>;
16942
16943/// One issue comment as the contract carries it.
16944///
16945/// `author` is absent both when GitHub answers `null` for an account that no longer exists
16946/// and when it answers an actor with no login, because either way the source did not say who
16947/// wrote it — which is what an absent author means, rather than an author called nothing.
16948///
16949/// A comment a copy wrote here carries its origin as the hidden marker at the end of its body
16950/// — GitHub sets every comment's author and times itself, so there is nowhere else to keep it —
16951/// and is read back with the marker taken out and reported as its origin.
16952fn comment_from(value: &Value) -> Result<Comment, SourceError> {
16953 let actor = value.get("author").unwrap_or(&Value::Null);
16954 // A bot's login is spelled as GitHub's own pages spell it, `<login>[bot]`, so a reader —
16955 // and every copy of the comment — can tell it from a person's.
16956 let bot = actor.get("__typename").and_then(Value::as_str) == Some("Bot");
16957 Ok(Comment {
16958 origin: None,
16959 id: NativeId(required_str(value, "id")?.to_owned()),
16960 author: optional_str(actor, "login")?.map(|login| {
16961 if bot && !login.ends_with("[bot]") {
16962 format!("{login}[bot]")
16963 } else {
16964 login.to_owned()
16965 }
16966 }),
16967 created_at: optional_time(value, "createdAt")?,
16968 updated_at: optional_time(value, "updatedAt")?,
16969 body: required_str(value, "body")?.to_owned(),
16970 url: optional_str(value, "url")?.map(str::to_owned),
16971 }
16972 .unmarked())
16973}
16974
16975/// The page of comments one issue node carries, resumed from `after`.
16976fn comment_page(
16977 node: &Value,
16978 issue: &str,
16979 after: Option<&str>,
16980) -> Result<Page<Comment>, SourceError> {
16981 let connection = node
16982 .get("comments")
16983 .filter(|value| !value.is_null())
16984 .ok_or_else(|| SourceError::Malformed {
16985 message: format!("GitHub issue {issue} answered with no comments connection"),
16986 })?;
16987 let items = optional_nodes(Some(connection), "issue comments")?
16988 .into_iter()
16989 .flatten()
16990 .map(comment_from)
16991 .collect::<Result<Vec<_>, _>>()?;
16992 let next = next_cursor(connection)?;
16993 if let Some(next) = &next {
16994 validate_cursor_progress(after, &next.0)?;
16995 }
16996 Ok(Page { items, next })
16997}
16998
16999/// The far ends of an issue's whole `blockedBy` connection, when the read carried it to its
17000/// end — `None` when it carried none, or a page with more past it.
17001fn carried_blocked_by(content: &Value) -> Result<Option<Vec<Value>>, SourceError> {
17002 let Some(connection) = content.get("blockedBy").filter(|value| !value.is_null()) else {
17003 return Ok(None);
17004 };
17005 if next_cursor(connection)?.is_some() {
17006 return Ok(None);
17007 }
17008 Ok(Some(
17009 optional_nodes(Some(connection), "blocked-by issues")?
17010 .into_iter()
17011 .flatten()
17012 .cloned()
17013 .collect(),
17014 ))
17015}
17016
17017/// Where the recorded tail of a dependency walk resumes; see
17018/// [`GitHubProjectsSource::recorded_edges`].
17019const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";
17020
17021/// The board text field this source keeps a copy's origin in.
17022///
17023/// Named after the key it holds, and held to that name by the guard below rather than by
17024/// a reader noticing.
17025const ORIGIN_FIELD: &str = "onetaskgraph.origin";
17026
17027/// The metadata key that field holds.
17028///
17029/// The engine owns this key and spells it once as `GlobalId::ORIGIN_KEY`; a plugin never
17030/// constructs or interprets the qualified id it carries. This source names it only to
17031/// route it — a short, typed value belongs in a typed field rather than in the body slot
17032/// a caller's own prose shares.
17033///
17034/// Restated rather than imported, because no plugin crate may depend on the engine. What
17035/// keeps the two spellings one contract is `scripts/check-origin-key-spelling.sh`, a
17036/// target in `check`: it reads the engine's own literal and fails naming the file and the
17037/// line when a plugin's parts from it either way. Drift here has one symptom — a copy
17038/// that creates a second item every run instead of finding the one it wrote — and that is
17039/// too late to learn it.
17040const ORIGIN_KEY: &str = "onetaskgraph.origin";
17041
17042/// Where a recorded tail resumes, refusing a cursor no walk in `direction` reported.
17043///
17044/// The reserved key holds forward edges and nothing else — the reverse of a recorded edge
17045/// is derived from the far end, never written down on the near item — so only a forward
17046/// walk ever reports one of these cursors. A reverse read carrying one is resuming a walk
17047/// it did not come from, and it is told so rather than answered with an empty page that
17048/// reads as a walk which ended.
17049fn recorded_offset(
17050 cursor: Option<&str>,
17051 direction: Direction,
17052) -> Result<Option<usize>, SourceError> {
17053 cursor
17054 .and_then(|cursor| cursor.strip_prefix(RECORDED_CURSOR))
17055 .map(|offset| {
17056 if direction != Direction::DependsOn {
17057 return Err(SourceError::Config {
17058 message: format!(
17059 "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a \
17060 reverse dependency read never issues; resume it in the direction \
17061 that reported it"
17062 ),
17063 });
17064 }
17065 offset.parse().map_err(|_| SourceError::Config {
17066 message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
17067 })
17068 })
17069 .transpose()
17070}
17071
17072/// What a dependency read's own answer says of a board draft: `None` when the item is not a
17073/// draft, or the answer did not carry its board item; `Some(None)` for a draft whose one board
17074/// item is not on this board, which this source does not hold; and `Some(Some(slot))`, the
17075/// draft's metadata, for one it does — its board item naming this board by its number and by
17076/// the id the same answer read of the board, as [`GitHubProjectsSource::draft_by_id`] decides.
17077fn draft_slot(
17078 data: &Value,
17079 id: &NativeId,
17080 project_number: u32,
17081) -> Result<Option<Option<BTreeMap<String, Value>>>, SourceError> {
17082 let Some(draft) = data
17083 .get("node")
17084 .filter(|node| node.get("__typename").and_then(Value::as_str) == Some("DraftIssue"))
17085 else {
17086 return Ok(None);
17087 };
17088 let Some(items) = data.pointer("/draft/projectV2Items") else {
17089 return Ok(None);
17090 };
17091 if required_str(draft, "id")? != id.0 {
17092 return Err(SourceError::Malformed {
17093 message: format!("GitHub answered a different draft for {}", id.0),
17094 });
17095 }
17096 let nodes = items
17097 .get("nodes")
17098 .and_then(Value::as_array)
17099 .ok_or_else(|| SourceError::Malformed {
17100 message: format!("GitHub draft {} projectV2Items.nodes is not an array", id.0),
17101 })?;
17102 let info = items
17103 .get("pageInfo")
17104 .ok_or_else(|| SourceError::Malformed {
17105 message: format!("GitHub draft {} projectV2Items has no pageInfo", id.0),
17106 })?;
17107 if required_bool(info, "hasNextPage")? || nodes.len() > 1 {
17108 return Err(SourceError::Malformed {
17109 message: format!(
17110 "GitHub draft {} reports more board items than the one GitHub links a draft to",
17111 id.0
17112 ),
17113 });
17114 }
17115 let board = data
17116 .pointer("/board/projectV2/id")
17117 .and_then(Value::as_str)
17118 .ok_or_else(|| SourceError::Malformed {
17119 message: format!(
17120 "GitHub answered draft {} without this board's own id beside it",
17121 id.0
17122 ),
17123 })?;
17124 let mut held = false;
17125 for node in nodes {
17126 let project = node.get("project").ok_or_else(|| SourceError::Malformed {
17127 message: format!("GitHub draft {} board item has no project", id.0),
17128 })?;
17129 let number = project
17130 .get("number")
17131 .and_then(Value::as_u64)
17132 .ok_or_else(|| SourceError::Malformed {
17133 message: format!(
17134 "GitHub draft {} board item has no numeric project number",
17135 id.0
17136 ),
17137 })?;
17138 let project_id = required_str(project, "id")?;
17139 held |= number == u64::from(project_number) && project_id == board;
17140 }
17141 if !held {
17142 return Ok(Some(None));
17143 }
17144 Ok(Some(Some(
17145 metadata_body(optional_str(draft, "body")?.map(str::to_owned))?.1,
17146 )))
17147}
17148
17149fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
17150 let mut page = offset_page(edges, offset, limit.max(1));
17151 page.next = page
17152 .next
17153 .map(|cursor| Cursor(format!("{RECORDED_CURSOR}{}", cursor.0)));
17154 page
17155}
17156
17157/// The kind of one issue reached through a dependency connection.
17158///
17159/// The same questions the board scan asks, over the fields the dependency document
17160/// selects, and in the same order: the design prefix first, then a sub-issue is a task,
17161/// then anything with sub-issues or the marker is a project.
17162///
17163/// # Errors
17164///
17165/// A far end this board holds as a document is refused rather than reported. The two
17166/// answers that are not refusals would both be wrong: reporting it as a task names an id
17167/// no task read of this source can find, and reporting it as a project names one no
17168/// project read can. There is no third value to return — `ItemKind` has no document
17169/// variant, because nothing may point at a document — so the relationship itself is what
17170/// the person is told about.
17171fn related_kind(value: &Value, meaning: SubIssues) -> Result<ItemKind, SourceError> {
17172 let id = required_str(value, "id")?;
17173 if required_str(value, "title")?.starts_with(DESIGN_TITLE_PREFIX) {
17174 return Err(SourceError::Refused {
17175 message: format!(
17176 "GitHub issue {id} is a document of this board — its title begins \
17177 {DESIGN_TITLE_PREFIX:?} — and nothing may depend on a document or be depended \
17178 on by one; next: remove that issue's blocking relationship on this board"
17179 ),
17180 });
17181 }
17182 let parent = optional_str(value.get("parent").unwrap_or(&Value::Null), "id")?;
17183 if parent.is_some() || meaning == SubIssues::Parent {
17184 return Ok(ItemKind::Task);
17185 }
17186 let (_, slot) = metadata_body(optional_str(value, "body")?.map(str::to_owned))?;
17187 let marked = ItemKind::from_metadata(&slot).map_err(|message| SourceError::Malformed {
17188 message: format!("GitHub issue {id}: {message}"),
17189 })?;
17190 let sub_issues = sub_issue_total(value)?;
17191 Ok(if sub_issues > 0 || marked == Some(ItemKind::Project) {
17192 ItemKind::Project
17193 } else {
17194 ItemKind::Task
17195 })
17196}
17197
17198/// The reason GitHub records an issue closed as a duplicate of another under.
17199const DUPLICATE_REASON: &str = "DUPLICATE";
17200
17201/// The `stateInput` that closes an issue for `reason`.
17202fn closed_input(reason: ClosedState) -> Value {
17203 json!({"value":"CLOSED","stateReason":reason.reason()})
17204}
17205
17206/// The `IssueStateUpdateInput` one status target asks for.
17207///
17208/// `stateInput` and `state` are mutually exclusive on `UpdateIssueInput`, and only this
17209/// one is ever sent. A non-terminal status always asks for `OPEN`, which is what reopens
17210/// a currently-closed issue: without that the item would read back `Unknown` and a copy
17211/// would report a change forever. A document has no status at all, and asks for neither.
17212fn state_input(target: Option<&StatusTarget>) -> Value {
17213 match target {
17214 Some(StatusTarget::Terminal(_, reason)) => closed_input(*reason),
17215 Some(StatusTarget::Column(_) | StatusTarget::Disabled(_)) => json!({"value":"OPEN"}),
17216 // A document has no status, so a write of one says nothing about the issue's open
17217 // or closed state rather than forcing it open: `stateInput` is what carries that
17218 // instruction, and an explicit null asks for no change to it.
17219 None => Value::Null,
17220 }
17221}
17222
17223/// The metadata one write stores in the item's body slot.
17224///
17225/// The typed fields travel as themselves, so the three reserved keys are rebuilt here
17226/// rather than carried: the kind marker so an empty project stays readable, the
17227/// repository list only when it is not exactly the issue's own repository, and the far
17228/// ends no relationship here can name.
17229///
17230/// The copy origin is the one typed field that is also mirrored here, and only as a
17231/// mirror: it lands in the board's origin field as well, which stays the one every reader
17232/// takes it from, and it is here so that GitHub's issue search — which indexes this comment
17233/// and catches up with a write in seconds rather than minutes — can find the item by it.
17234/// A reader of the release before this one drops the slot's copy and reads the field, so an
17235/// item written here still reads with exactly one origin there.
17236fn slot_metadata(
17237 incoming: &Incoming<'_>,
17238 own_repository: Option<&Repository>,
17239 fallback: &[DependencyEdge],
17240) -> BTreeMap<String, Value> {
17241 let mut metadata = incoming.metadata.clone();
17242 match metadata.remove(ORIGIN_KEY) {
17243 Some(Value::String(origin)) if !origin.is_empty() => {
17244 metadata.insert(ORIGIN_KEY.to_owned(), Value::String(origin));
17245 }
17246 _ => {}
17247 }
17248 match incoming.written.kind() {
17249 BoardKind::Work(kind) => metadata.insert(
17250 ItemKind::METADATA_KEY.to_owned(),
17251 Value::String(kind.marker().to_owned()),
17252 ),
17253 // A document is told by its title, so it carries no kind marker: that key names
17254 // what a dependency endpoint points at, and nothing may point at a document.
17255 BoardKind::Document => metadata.remove(ItemKind::METADATA_KEY),
17256 };
17257 incoming.classification.record(&mut metadata);
17258 let derivable = own_repository
17259 .map(|own| incoming.repositories == [own.clone()])
17260 .unwrap_or(incoming.repositories.is_empty());
17261 if derivable {
17262 metadata.remove(Repository::METADATA_KEY);
17263 } else {
17264 metadata.insert(
17265 Repository::METADATA_KEY.to_owned(),
17266 Value::Array(
17267 incoming
17268 .repositories
17269 .iter()
17270 .map(|repository| Value::String(repository.as_str().to_owned()))
17271 .collect(),
17272 ),
17273 );
17274 }
17275 // The typed lists are what land, whatever the caller's own metadata held under their
17276 // keys: a key of either name travelling beside the field would otherwise be a second
17277 // answer to the same question, and the field is the one the contract names.
17278 for (key, entries) in [
17279 (TaskRef::DELIVERS_KEY, incoming.delivers),
17280 (TaskRef::DELIVERED_BY_KEY, incoming.delivered_by),
17281 ] {
17282 set_task_list(&mut metadata, key, entries);
17283 }
17284 record_edges(&mut metadata, fallback);
17285 metadata
17286}
17287
17288/// Hold the far ends no relationship here can name under [`DependencyEdge::RECORDED_KEY`] in
17289/// one slot's metadata, or no such key when there are none.
17290fn record_edges(metadata: &mut BTreeMap<String, Value>, fallback: &[DependencyEdge]) {
17291 if fallback.is_empty() {
17292 metadata.remove(DependencyEdge::RECORDED_KEY);
17293 } else {
17294 metadata.insert(
17295 DependencyEdge::RECORDED_KEY.to_owned(),
17296 Value::Array(
17297 fallback
17298 .iter()
17299 .map(|edge| {
17300 serde_json::to_value(&edge.to).expect("an endpoint renders as JSON")
17301 })
17302 .collect(),
17303 ),
17304 );
17305 }
17306}
17307
17308/// Every label one item carries, from its content's own connection and nowhere else.
17309///
17310/// There is no second place to read one from: no document this source sends selects the
17311/// board's built-in `Labels` field, because GitHub derives it from the content and a draft
17312/// cannot carry one at all. The module documentation records the three schema facts that
17313/// settle it.
17314fn labels(content: &Value) -> Result<Vec<Label>, SourceError> {
17315 optional_nodes(content.get("labels"), "content labels")?
17316 .into_iter()
17317 .flatten()
17318 .map(|v| {
17319 Ok(Label {
17320 id: NativeId(required_str(v, "id")?.to_owned()),
17321 name: required_str(v, "name")?.to_owned(),
17322 color: optional_str(v, "color")?.map(str::to_owned),
17323 })
17324 })
17325 .collect()
17326}
17327
17328/// Each board field value one item holds, as the change token's facets name it: the field's
17329/// name, with the single-select option's name or the text. A value of a type no read here
17330/// selects, and one naming no field, says nothing a person can rename and is left out.
17331fn facet_fields(field_values: &[Value]) -> Vec<(String, String)> {
17332 field_values
17333 .iter()
17334 .filter_map(|value| {
17335 let field = value.pointer("/field/name")?.as_str()?;
17336 let held = value.get("name").or_else(|| value.get("text"))?.as_str()?;
17337 Some((field.to_owned(), held.to_owned()))
17338 })
17339 .collect()
17340}
17341
17342/// The digest of the facets of the issue `content`, whose board item's values are
17343/// `field_values` — or `None` when the response did not carry, whole, every member they are read
17344/// from: the title, the parent, the sub-issue summary and the body its kind is read from, every
17345/// label, and every field value.
17346///
17347/// What a write's own response spells its token from, by exactly the rules a read takes them by.
17348fn facets_of(content: &Value, field_values: &Value) -> Option<change_token::FacetsDigest> {
17349 let ended = |connection: &Value| {
17350 connection.pointer("/pageInfo/hasNextPage") == Some(&Value::Bool(false))
17351 };
17352 let labels = content.get("labels").filter(|labels| ended(labels))?;
17353 if !ended(field_values) {
17354 return None;
17355 }
17356 let parent = content.get("parent")?;
17357 let (_, slot) = metadata_body(content.get("body")?.as_str().map(str::to_owned)).ok()?;
17358 let kind = BoardKind::of(
17359 content.get("title")?.as_str()?,
17360 !parent.is_null(),
17361 sub_issue_total(content).ok()?,
17362 ItemKind::from_metadata(&slot).ok()?,
17363 );
17364 let labels = self::labels(&json!({"labels": labels})).ok()?;
17365 let nodes = field_values.get("nodes")?.as_array()?;
17366 Some(change_token::Facets::new(kind.facet(), facet_fields(nodes), &labels).digest())
17367}
17368
17369/// The definition of each board field one item's values are values of, in the shape a read
17370/// of the board's own `fields` gives one.
17371///
17372/// A value names its field through a fragment on that field's own type, so the type is
17373/// known from which kind of value it is: a single-select value's field is a
17374/// `ProjectV2SingleSelectField`, options and all, and a text value's is a `ProjectV2Field`.
17375/// A value whose field carried no id, or an empty one, says nothing usable and is left out.
17376fn field_definitions(field_values: &[Value]) -> Vec<Value> {
17377 field_values
17378 .iter()
17379 .filter_map(|value| {
17380 let field = value.get("field")?.as_object()?;
17381 field.get("id")?.as_str().filter(|id| !id.is_empty())?;
17382 let typename = if value.get("text").is_some() {
17383 "ProjectV2Field"
17384 } else if value.get("name").is_some() {
17385 "ProjectV2SingleSelectField"
17386 } else {
17387 return None;
17388 };
17389 let mut defined = field.clone();
17390 defined.insert("__typename".to_owned(), json!(typename));
17391 // Only a text field holds a text value, so the value says the field's type too.
17392 if typename == "ProjectV2Field" {
17393 defined.insert("dataType".to_owned(), json!("TEXT"));
17394 }
17395 Some(Value::Object(defined))
17396 })
17397 .collect()
17398}
17399
17400fn text_field(field_values: &[Value], name: &str) -> Result<Option<String>, SourceError> {
17401 let Some(node) = field_values
17402 .iter()
17403 .find(|node| node.pointer("/field/name").and_then(Value::as_str) == Some(name))
17404 else {
17405 return Ok(None);
17406 };
17407 Ok(optional_str(node, "text")?.map(str::to_owned))
17408}
17409
17410fn valid_github_owner(owner: &str) -> bool {
17411 !owner.is_empty()
17412 && owner.len() <= 39
17413 && !owner.starts_with('-')
17414 && !owner.ends_with('-')
17415 && !owner.contains("--")
17416 && owner
17417 .bytes()
17418 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
17419}
17420
17421/// GitHub's repository-name grammar: 1-100 ASCII letters, digits, `-`, `_` or `.`, and
17422/// neither of the two names a path segment already means.
17423fn valid_github_repository_name(name: &str) -> bool {
17424 !name.is_empty()
17425 && name.len() <= 100
17426 && name != "."
17427 && name != ".."
17428 && name
17429 .bytes()
17430 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
17431}
17432
17433fn valid_environment_name(name: &str) -> bool {
17434 let mut bytes = name.bytes();
17435 bytes
17436 .next()
17437 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
17438 && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
17439}
17440
17441/// How many sub-issues one issue has.
17442///
17443/// `Issue.subIssuesSummary` is `SubIssuesSummary!` and its `total` is `Int!`, so an
17444/// absent or non-integer one is a response this source cannot read — and reading it as
17445/// zero would classify a project as a task, which is exactly the mistake the marker
17446/// exists to keep from happening quietly.
17447fn sub_issue_total(issue: &Value) -> Result<u64, SourceError> {
17448 let summary = issue
17449 .get("subIssuesSummary")
17450 .ok_or_else(|| SourceError::Malformed {
17451 message: "GitHub issue is missing subIssuesSummary".into(),
17452 })?;
17453 summary
17454 .get("total")
17455 .and_then(Value::as_u64)
17456 .ok_or_else(|| SourceError::Malformed {
17457 message: "GitHub issue subIssuesSummary.total is not an unsigned integer".into(),
17458 })
17459}
17460
17461/// One issue's own `number`.
17462///
17463/// An issue always has one: GitHub declares `Issue.number` as `Int!` and every selection of
17464/// an issue in this module asks for it. So a read of one that comes back without it, or
17465/// with something that is not an unsigned integer, is a response this source cannot read —
17466/// absence here is **not** "this issue has no number". A draft is the content that has
17467/// none, and a draft never reaches this: the caller decides on `__typename` first, the way
17468/// it does for `subIssuesSummary`, which `DraftIssue` equally declares nothing for.
17469fn issue_number(issue: &Value) -> Result<u64, SourceError> {
17470 issue
17471 .get("number")
17472 .and_then(Value::as_u64)
17473 .ok_or_else(|| SourceError::Malformed {
17474 message: "GitHub issue number is missing or is not an unsigned integer".into(),
17475 })
17476}
17477
17478/// The `number` a creating mutation answered with, and `None` when it answered without one;
17479/// why a missing one is tolerated is at the call in `create_and_file_issue`.
17480fn created_issue_number(created: &Value) -> Result<Option<u64>, SourceError> {
17481 match created.get("number") {
17482 None | Some(Value::Null) => Ok(None),
17483 Some(value) => value
17484 .as_u64()
17485 .map(Some)
17486 .ok_or_else(|| SourceError::Malformed {
17487 message: "GitHub created issue number is not an unsigned integer".into(),
17488 }),
17489 }
17490}
17491
17492fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17493 value
17494 .get(field)
17495 .and_then(Value::as_str)
17496 .ok_or_else(|| SourceError::Malformed {
17497 message: format!("GitHub response is missing string field {field}"),
17498 })
17499}
17500
17501fn required_nonblank_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
17502 let found = required_str(value, field)?;
17503 if found.trim().is_empty() {
17504 return Err(SourceError::Malformed {
17505 message: format!("GitHub response has blank string field {field}"),
17506 });
17507 }
17508 Ok(found)
17509}
17510
17511/// The slot's delimiters, which `docs/metadata.md` settles once for every source that
17512/// needs one — Linear spells them too, in its own description field.
17513///
17514/// Restated rather than shared, because a plugin crate depends on the contract crate and
17515/// nothing else of this workspace. `scripts/check-metadata-slot-encoding.sh`, a target in
17516/// `check`, is what keeps the two one encoding: drift is otherwise quiet, since each
17517/// source round-trips its own writes perfectly well under its own spelling.
17518const METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
17519const METADATA_CLOSE: &str = "\n-->";
17520
17521/// What the composer puts between a non-empty visible body and the slot, and the one thing
17522/// the parser takes off the visible body when it takes the slot off — exactly once, so every
17523/// other trailing byte of the body comes back as it was written.
17524// 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.
17525const METADATA_SEPARATOR: &str = "\n\n";
17526
17527/// The visible body and the metadata slot at the end of it.
17528///
17529/// The encoding is the one `docs/metadata.md` settles for Linear, which is where its
17530/// reasons are. Only a comment at the very end is a slot; one in the middle is a person's
17531/// own content and is left alone. The visible body is everything before the slot less the
17532/// one [`METADATA_SEPARATOR`] the composer put there, byte for byte.
17533fn metadata_body(
17534 body: Option<String>,
17535) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
17536 let Some(body) = body else {
17537 return Ok((None, BTreeMap::new()));
17538 };
17539 let Some(slot) = slot_span(&body)? else {
17540 return Ok((Some(body), BTreeMap::new()));
17541 };
17542 let metadata =
17543 serde_json::from_str(&body[slot.encoded_start..slot.encoded_end]).map_err(|error| {
17544 SourceError::Malformed {
17545 message: format!(
17546 "invalid canonical JSON in GitHub issue onetaskgraph metadata slot: {error}"
17547 ),
17548 }
17549 })?;
17550 let before = &body[..slot.start];
17551 let visible = before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before);
17552 Ok(((!visible.is_empty()).then(|| visible.to_owned()), metadata))
17553}
17554
17555/// Where the metadata slot sits in one body, as byte offsets into it.
17556struct SlotSpan {
17557 /// Where [`METADATA_OPEN`] begins.
17558 start: usize,
17559 /// Where the encoded JSON begins, just past [`METADATA_OPEN`].
17560 encoded_start: usize,
17561 /// Where the encoded JSON ends, at the start of [`METADATA_CLOSE`].
17562 encoded_end: usize,
17563 /// Just past [`METADATA_CLOSE`].
17564 end: usize,
17565}
17566
17567/// The slot at the very end of `body`, or `None` when it has none.
17568///
17569/// The one reading of *where the slot is*, shared by [`metadata_body`], which reads it, and
17570/// [`with_slot`], which rewrites it — so the two cannot disagree about which comment is the
17571/// slot.
17572fn slot_span(body: &str) -> Result<Option<SlotSpan>, SourceError> {
17573 let Some(start) = body.rfind(METADATA_OPEN) else {
17574 return Ok(None);
17575 };
17576 let encoded_start = start + METADATA_OPEN.len();
17577 let Some(relative_end) = body[encoded_start..].find(METADATA_CLOSE) else {
17578 return Err(SourceError::Malformed {
17579 message: "unterminated onetaskgraph metadata slot in GitHub issue body".into(),
17580 });
17581 };
17582 let encoded_end = encoded_start + relative_end;
17583 let end = encoded_end + METADATA_CLOSE.len();
17584 if !body[end..].trim().is_empty() {
17585 return Ok(None);
17586 }
17587 Ok(Some(SlotSpan {
17588 start,
17589 encoded_start,
17590 encoded_end,
17591 end,
17592 }))
17593}
17594
17595/// `body` with its metadata slot holding exactly `metadata`, and every byte outside the
17596/// slot as it was.
17597///
17598/// A slot that is there has its JSON replaced in place; one that becomes empty is removed
17599/// together with the one [`METADATA_SEPARATOR`] separating it from the prose before it. A
17600/// body with no slot gains one the way [`compose_body`] writes it — after that separator,
17601/// or alone in an empty body — and a body with no slot that is given no metadata is
17602/// returned as it is.
17603fn with_slot(body: &str, metadata: &BTreeMap<String, Value>) -> Result<String, SourceError> {
17604 let encoded = if metadata.is_empty() {
17605 None
17606 } else {
17607 Some(
17608 serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17609 message: error.to_string(),
17610 })?,
17611 )
17612 };
17613 Ok(match (slot_span(body)?, encoded) {
17614 (Some(slot), Some(encoded)) => format!(
17615 "{}{encoded}{}",
17616 &body[..slot.encoded_start],
17617 &body[slot.encoded_end..]
17618 ),
17619 (Some(slot), None) => {
17620 let before = &body[..slot.start];
17621 format!(
17622 "{}{}",
17623 before.strip_suffix(METADATA_SEPARATOR).unwrap_or(before),
17624 &body[slot.end..]
17625 )
17626 }
17627 (None, None) => body.to_owned(),
17628 (None, Some(encoded)) if body.is_empty() => {
17629 format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17630 }
17631 (None, Some(encoded)) => {
17632 format!("{body}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17633 }
17634 })
17635}
17636
17637/// `body` with everything before its metadata slot replaced by `content`, and the slot
17638/// itself kept byte for byte.
17639///
17640/// The inverse of how [`metadata_body`] splits a body: the slot, when there is one, follows
17641/// `content` after the one [`METADATA_SEPARATOR`] the composer puts there — or alone, when
17642/// `content` is empty — so a read of the result reports `content` as the visible body and
17643/// the slot's metadata exactly as it was.
17644fn with_content(body: &str, content: &str) -> Result<String, SourceError> {
17645 let Some(slot) = slot_span(body)? else {
17646 return Ok(content.to_owned());
17647 };
17648 let kept = &body[slot.start..];
17649 Ok(if content.is_empty() {
17650 kept.to_owned()
17651 } else {
17652 format!("{content}{METADATA_SEPARATOR}{kept}")
17653 })
17654}
17655
17656/// Hold `entries` under `key` in one slot's metadata, or no such key when there are none.
17657fn set_task_list(metadata: &mut BTreeMap<String, Value>, key: &str, entries: &[TaskRef]) {
17658 if entries.is_empty() {
17659 metadata.remove(key);
17660 } else {
17661 metadata.insert(
17662 key.to_owned(),
17663 Value::Array(
17664 entries
17665 .iter()
17666 .map(|entry| Value::String(entry.as_str().to_owned()))
17667 .collect(),
17668 ),
17669 );
17670 }
17671}
17672
17673fn compose_body(
17674 content: Option<&str>,
17675 metadata: &BTreeMap<String, Value>,
17676) -> Result<Option<String>, SourceError> {
17677 let visible = content.unwrap_or_default();
17678 if metadata.is_empty() {
17679 return Ok((!visible.is_empty()).then(|| visible.to_owned()));
17680 }
17681 let encoded = serde_json::to_string(metadata).map_err(|error| SourceError::Malformed {
17682 message: error.to_string(),
17683 })?;
17684 Ok(Some(if visible.is_empty() {
17685 format!("{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17686 } else {
17687 format!("{visible}{METADATA_SEPARATOR}{METADATA_OPEN}{encoded}{METADATA_CLOSE}")
17688 }))
17689}
17690
17691fn required_bool(value: &Value, field: &str) -> Result<bool, SourceError> {
17692 value
17693 .get(field)
17694 .and_then(Value::as_bool)
17695 .ok_or_else(|| SourceError::Malformed {
17696 message: format!("GitHub response is missing boolean field {field}"),
17697 })
17698}
17699fn optional_str<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, SourceError> {
17700 match value.get(field) {
17701 None | Some(Value::Null) => Ok(None),
17702 Some(value) => value
17703 .as_str()
17704 .map(Some)
17705 .ok_or_else(|| SourceError::Malformed {
17706 message: format!("GitHub response field {field} is not a string or null"),
17707 }),
17708 }
17709}
17710fn optional_nodes<'a>(
17711 connection: Option<&'a Value>,
17712 name: &str,
17713) -> Result<Option<&'a Vec<Value>>, SourceError> {
17714 match connection {
17715 None | Some(Value::Null) => Ok(None),
17716 Some(value) => value
17717 .get("nodes")
17718 .and_then(Value::as_array)
17719 .map(Some)
17720 .ok_or_else(|| SourceError::Malformed {
17721 message: format!("GitHub {name}.nodes is not an array"),
17722 }),
17723 }
17724}
17725fn complete_connection(connection: &Value, name: &str, size: u32) -> Result<(), SourceError> {
17726 let page_info = connection
17727 .get("pageInfo")
17728 .ok_or_else(|| SourceError::Malformed {
17729 message: format!("GitHub {name} has no pageInfo"),
17730 })?;
17731 if required_bool(page_info, "hasNextPage")? {
17732 return Err(SourceError::Malformed {
17733 message: format!(
17734 "GitHub {name} exceeds the supported nested connection size of {size}"
17735 ),
17736 });
17737 }
17738 Ok(())
17739}
17740fn optional_time(value: &Value, field: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
17741 optional_str(value, field)?
17742 .map(|timestamp| {
17743 timestamp.parse().map_err(|error| SourceError::Malformed {
17744 message: format!("GitHub response field {field} is not a timestamp: {error}"),
17745 })
17746 })
17747 .transpose()
17748}
17749fn validate_page(page: &PageRequest) -> Result<(), SourceError> {
17750 if page.limit == 0 {
17751 Err(SourceError::Config {
17752 message: "page limit must be at least 1".into(),
17753 })
17754 } else {
17755 Ok(())
17756 }
17757}
17758fn next_cursor(connection: &Value) -> Result<Option<Cursor>, SourceError> {
17759 let page = connection
17760 .get("pageInfo")
17761 .filter(|value| value.is_object())
17762 .ok_or_else(|| SourceError::Malformed {
17763 message: "GitHub connection is missing pageInfo".into(),
17764 })?;
17765 if required_bool(page, "hasNextPage")? {
17766 let cursor = required_str(page, "endCursor")?;
17767 validate_cursor_progress(None, cursor)?;
17768 Ok(Some(Cursor(cursor.into())))
17769 } else {
17770 Ok(None)
17771 }
17772}
17773fn validate_cursor_progress(previous: Option<&str>, next: &str) -> Result<(), SourceError> {
17774 if next.is_empty() || previous == Some(next) {
17775 Err(SourceError::Malformed {
17776 message: "GitHub pagination cursor is empty or did not advance".into(),
17777 })
17778 } else {
17779 Ok(())
17780 }
17781}
17782/// The version of this plugin's opaque narrowing-search cursor.
17783pub const SEARCH_CURSOR_VERSION: u32 = 4;
17784
17785#[derive(Serialize, Deserialize)]
17786#[serde(tag = "state", rename_all = "snake_case", deny_unknown_fields)]
17787enum SearchConnection {
17788 Initial {},
17789 Continuing { after: Cursor },
17790 Exhausted {},
17791}
17792impl SearchConnection {
17793 fn after(&self) -> Option<&str> {
17794 match self {
17795 Self::Continuing { after } => Some(&after.0),
17796 _ => None,
17797 }
17798 }
17799 fn exhausted(&self) -> bool {
17800 matches!(self, Self::Exhausted { .. })
17801 }
17802 /// Whether a cursor naming this position, `offset` rows into its page, is one this
17803 /// plugin could have handed out: a page is resumed only part of the way through it — an
17804 /// offset of a whole page or more would skip rows nobody was given — an initial page
17805 /// only once some of it was handed out, and an exhausted connection has no page to be
17806 /// part of the way through.
17807 fn valid_resume(&self, offset: usize) -> bool {
17808 let within = offset < SEARCH_PAGE_SIZE as usize;
17809 match self {
17810 Self::Initial { .. } => offset > 0 && within,
17811 Self::Continuing { after } => !after.0.is_empty() && within,
17812 Self::Exhausted { .. } => offset == 0,
17813 }
17814 }
17815}
17816
17817/// Versioned source cursor. A zero offset and empty own-write ids are omitted.
17818#[derive(Serialize, Deserialize)]
17819#[serde(deny_unknown_fields)]
17820struct SearchPosition {
17821 version: u32,
17822 connection: SearchConnection,
17823 /// How many rows of the page `connection` starts were already handed out.
17824 #[serde(default, skip_serializing_if = "is_zero")]
17825 offset: usize,
17826 #[serde(default, skip_serializing_if = "Vec::is_empty")]
17827 seen: Vec<NativeId>,
17828 #[serde(default, skip_serializing_if = "Vec::is_empty")]
17829 own: Vec<NativeId>,
17830}
17831impl Default for SearchPosition {
17832 fn default() -> Self {
17833 Self {
17834 version: SEARCH_CURSOR_VERSION,
17835 connection: SearchConnection::Initial {},
17836 offset: 0,
17837 seen: Vec::new(),
17838 own: Vec::new(),
17839 }
17840 }
17841}
17842
17843fn is_zero(offset: &usize) -> bool {
17844 *offset == 0
17845}
17846
17847fn numeric_cursor(cursor: Option<&Cursor>) -> Result<usize, SourceError> {
17848 cursor.map_or(Ok(0), |c| {
17849 c.0.parse().map_err(|_| SourceError::Config {
17850 message: "page cursor is invalid".into(),
17851 })
17852 })
17853}
17854fn offset_page<T>(mut items: Vec<T>, offset: usize, limit: usize) -> Page<T> {
17855 if offset > items.len() {
17856 return Page::last(vec![]);
17857 }
17858 let tail = items.split_off(offset);
17859 let mut selected = tail;
17860 let next = (selected.len() > limit).then(|| Cursor((offset + limit).to_string()));
17861 selected.truncate(limit);
17862 Page {
17863 items: selected,
17864 next,
17865 }
17866}
17867
17868impl GitHubProjectsSource {
17869 /// The body [`Self::write_item`] would compose for `incoming`, sized in the characters
17870 /// [`BODY_LIMIT`] counts, without a request: its slot as `slot_metadata` writes it, every
17871 /// asset reference rewritten to its recorded URL or — for one not uploaded yet — to an
17872 /// address as long as GitHub's, and the heading markup this board's bodies carry.
17873 ///
17874 /// What the write reads rather than knows is taken as it most often lands: the issue in
17875 /// the one repository the item names, else the configured one, and every edge on the
17876 /// board's own relationships rather than in the slot.
17877 fn body_size(&self, incoming: &Incoming<'_>) -> onetaskgraph_plugin_api::BodySize {
17878 let own = match incoming.repositories {
17879 [named] => Some(named.clone()),
17880 _ => self
17881 .repository
17882 .as_ref()
17883 .and_then(|target| Repository::try_from(target.origin()).ok()),
17884 };
17885 let mut slot = slot_metadata(incoming, own.as_ref(), &[]);
17886 let content = match incoming.assets {
17887 Some(assets) => {
17888 let mut uploads = onetaskgraph_plugin_api::AssetUploads::default();
17889 for asset in &assets.assets {
17890 let url = assets
17891 .recorded_assets
17892 .as_ref()
17893 .and_then(|recorded| recorded.reusable(&asset.name, &asset.sha256))
17894 .unwrap_or(PREDICTED_ATTACHMENT_URL)
17895 .to_owned();
17896 uploads.0.insert(
17897 asset.name.clone(),
17898 onetaskgraph_plugin_api::AssetUpload {
17899 sha256: asset.sha256.clone(),
17900 url,
17901 },
17902 );
17903 }
17904 incoming.content.map(|content| {
17905 onetaskgraph_plugin_api::serve_asset_references(content, &mut slot, &uploads)
17906 })
17907 }
17908 None => incoming.content.map(str::to_owned),
17909 };
17910 let marked = content.as_deref().map(|content| self.marked(content));
17911 let size = compose_body(marked.as_deref(), &slot)
17912 .ok()
17913 .flatten()
17914 .map_or(0, |body| body.chars().count());
17915 onetaskgraph_plugin_api::BodySize {
17916 size: u64::try_from(size).unwrap_or(u64::MAX),
17917 limit: Some(BODY_LIMIT),
17918 }
17919 }
17920
17921 async fn write_task_assets(
17922 &self,
17923 write: &ItemWrite<Task>,
17924 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
17925 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
17926 self.write_item(
17927 &self.task_incoming(write, assets)?,
17928 write.target.as_ref(),
17929 &write.depends_on,
17930 )
17931 .await
17932 }
17933
17934 /// One task write as [`Self::write_item`] takes it, once what it delivers and its priority
17935 /// are known to be ones this source can write.
17936 fn task_incoming<'a>(
17937 &self,
17938 write: &'a ItemWrite<Task>,
17939 assets: Option<&'a onetaskgraph_plugin_api::AssetWrite>,
17940 ) -> Result<Incoming<'a>, SourceError> {
17941 let near = write.target.as_ref().unwrap_or(&write.item.id);
17942 for (key, entries) in [
17943 (TaskRef::DELIVERS_KEY, &write.item.delivers),
17944 (TaskRef::DELIVERED_BY_KEY, &write.item.delivered_by),
17945 ] {
17946 TaskRef::listed(key, near, Some(&self.name), entries.clone())
17947 .map_err(|message| SourceError::Refused { message })?;
17948 }
17949 if self.priorities.is_none() && write.item.priority != Priority::None {
17950 return Err(self.holds_no_priority());
17951 }
17952 if write.item.assignees.is_some() && !self.assignees {
17953 return Err(onetaskgraph_plugin_api::unwritable_field(KIND, "assignees"));
17954 }
17955 Ok(Incoming {
17956 written: Written::Work(ItemKind::Task, &write.item.status),
17957 title: &write.item.title,
17958 content: write.item.content.as_deref(),
17959 assets,
17960 labels: &write.item.labels,
17961 metadata: &write.item.metadata,
17962 repositories: &write.item.repositories,
17963 classification: write.item.classification,
17964 parent: write.item.project.as_ref(),
17965 delivers: &write.item.delivers,
17966 delivered_by: &write.item.delivered_by,
17967 priority: self.priorities.as_ref().map(|_| write.item.priority),
17968 assignees: write.item.assignees.as_deref(),
17969 })
17970 }
17971 async fn write_document_assets(
17972 &self,
17973 write: &ItemWrite<Document>,
17974 assets: Option<&onetaskgraph_plugin_api::AssetWrite>,
17975 ) -> Result<onetaskgraph_plugin_api::AssetsWritten, SourceError> {
17976 // A document takes part in no dependency graph, so there is no far end to write
17977 // natively and none to record: a caller naming one is told so rather than having it
17978 // stored under the reserved key, where a later read would report an edge the
17979 // contract says cannot exist.
17980 if !write.depends_on.is_empty() {
17981 return Err(SourceError::Refused {
17982 message: format!(
17983 "this write names {} dependencies for a document, and a document takes \
17984 part in no dependency graph; next: put the dependency on the task or \
17985 project the document is about",
17986 write.depends_on.len()
17987 ),
17988 });
17989 }
17990 self.write_item(
17991 &Incoming {
17992 written: Written::Document,
17993 title: &write.item.title,
17994 content: write.item.content.as_deref(),
17995 assets,
17996 labels: &write.item.labels,
17997 metadata: &write.item.metadata,
17998 repositories: &write.item.repositories,
17999 classification: write.item.classification,
18000 parent: write.item.project.as_ref(),
18001 delivers: &[],
18002 delivered_by: &[],
18003 priority: None,
18004 assignees: None,
18005 },
18006 write.target.as_ref(),
18007 &[],
18008 )
18009 .await
18010 }
18011}
18012
18013/// What [`TaskSource::end_command`] leaves of this source's held state, asserted on the state
18014/// itself, for the two things no journey can observe.
18015///
18016/// The journeys in `crates/onetaskgraph-e2e/tests/e2e/end_command.rs` prove through the engine,
18017/// with and without the call, that a settlement, a board listing and a metadata search each
18018/// read afresh after it — the resolved records, the written-item overlay, the board and its
18019/// search, and the narrowed searches. What they cannot reach is the held field definitions,
18020/// because a status write naming an option a person deleted is refused the same whether or
18021/// not the list is held, and a poisoned lock, because nothing outside the source can panic
18022/// while one of its locks is held. So these assert those directly, and every other holder
18023/// beside them so a holder added later without a clear in the call fails here.
18024#[cfg(test)]
18025mod end_command_tests {
18026 use super::*;
18027
18028 struct Token;
18029
18030 impl SecretResolver for Token {
18031 fn get(&self, var: &str) -> Option<SecretString> {
18032 (var == "GH_PROJECTS_TOKEN").then(|| "test-token".into())
18033 }
18034 }
18035
18036 fn source() -> GitHubProjectsSource {
18037 let config = serde_json::from_value(json!({
18038 "owner": "octo-org", "project_number": 7, "repository": "acme/work",
18039 // Nothing here is sent: the source is only built and its state inspected.
18040 "endpoint": "http://127.0.0.1:9/graphql",
18041 }))
18042 .expect("a usable configuration");
18043 GitHubProjectsSource::new(&SourceName::new("work").unwrap(), config, &Token)
18044 .expect("the source builds")
18045 }
18046
18047 /// One issue as a board read answers it.
18048 fn resolved(source: &GitHubProjectsSource) -> Resolved {
18049 source
18050 .resolve(&json!({
18051 "id": "ITEM-1",
18052 "content": {"__typename": "Issue", "id": "I_1", "title": "Held",
18053 "body": "what a person may since have edited", "state": "OPEN",
18054 "stateReason": null, "url": null, "number": 1,
18055 "subIssuesSummary": {"total": 0},
18056 "labels": {"nodes": [], "pageInfo": {"hasNextPage": false}}},
18057 "fieldValues": {"nodes": [], "pageInfo": {"hasNextPage": false}},
18058 }))
18059 .expect("the item reads")
18060 .expect("an issue")
18061 }
18062
18063 /// Hold something in every holder the call clears, and the repository id it keeps.
18064 fn fill(source: &GitHubProjectsSource) {
18065 let item = resolved(source);
18066 source.created.lock().unwrap().push(item.clone());
18067 source.updated.lock().unwrap().push(item.clone());
18068 *source.board_cache.lock().unwrap() = Some(Board {
18069 id: "PVT-board".into(),
18070 fields: json!({"nodes": []}),
18071 items: vec![item.clone()],
18072 });
18073 *source.search_cache.lock().unwrap() = Some(vec![item.clone()]);
18074 source
18075 .narrowed_cache
18076 .lock()
18077 .unwrap()
18078 .insert("status:todo".into(), vec![item.clone()]);
18079 source.children_cache.lock().unwrap().insert(
18080 NativeId("P-1".into()),
18081 (NativeId("P-1".into()), vec![item.clone()]),
18082 );
18083 source
18084 .search_next
18085 .lock()
18086 .unwrap()
18087 .insert("status:todo".into(), Some("cursor".into()));
18088 source
18089 .resolved_cache
18090 .lock()
18091 .unwrap()
18092 .insert(item.id.clone(), item);
18093 *source.fields_cache.lock().unwrap() = Some(BoardFields {
18094 id: BoardId::parse("PVT-board").unwrap(),
18095 fields: json!({"nodes": []}),
18096 });
18097 source
18098 .repository_cache
18099 .lock()
18100 .unwrap()
18101 .insert(RepositoryTarget::parse("acme/work").unwrap(), "R_1".into());
18102 }
18103
18104 fn assert_dropped(source: &GitHubProjectsSource) {
18105 assert!(source.created().unwrap().is_empty(), "created");
18106 assert!(source.updated().unwrap().is_empty(), "updated");
18107 assert!(source.board_cache().unwrap().is_none(), "board");
18108 assert!(source.search_cache.lock().unwrap().is_none(), "search");
18109 assert!(source.narrowed_cache.lock().unwrap().is_empty(), "narrowed");
18110 assert!(
18111 source.children_cache.lock().unwrap().is_empty(),
18112 "project children"
18113 );
18114 assert!(
18115 source.search_next.lock().unwrap().is_empty(),
18116 "search paging"
18117 );
18118 assert!(
18119 source.resolved_cache().unwrap().is_empty(),
18120 "resolved records"
18121 );
18122 assert!(source.fields_cache().unwrap().is_none(), "board fields");
18123 assert_eq!(
18124 source.repository_cache().unwrap().len(),
18125 1,
18126 "a repository's node id stays valid and is kept"
18127 );
18128 }
18129
18130 fn end(source: &GitHubProjectsSource) {
18131 tokio::runtime::Builder::new_current_thread()
18132 .build()
18133 .unwrap()
18134 .block_on(source.end_command())
18135 .expect("the command ends");
18136 }
18137
18138 #[test]
18139 fn the_call_drops_every_item_search_and_board_read_and_keeps_repository_ids() {
18140 let source = source();
18141 fill(&source);
18142 end(&source);
18143 assert_dropped(&source);
18144 }
18145
18146 #[test]
18147 fn the_call_clears_a_lock_an_earlier_failure_poisoned() {
18148 fn poison<T: Send>(held: &Mutex<T>) {
18149 std::thread::scope(|scope| {
18150 let _ = scope
18151 .spawn(|| {
18152 let _guard = held.lock().unwrap();
18153 panic!("a failure while the lock is held");
18154 })
18155 .join();
18156 });
18157 assert!(held.is_poisoned());
18158 }
18159 let source = source();
18160 fill(&source);
18161 poison(&source.created);
18162 poison(&source.updated);
18163 poison(&source.board_cache);
18164 poison(&source.search_cache);
18165 poison(&source.narrowed_cache);
18166 poison(&source.search_next);
18167 poison(&source.resolved_cache);
18168 poison(&source.fields_cache);
18169 assert!(
18170 source.resolved_cache().is_err(),
18171 "a poisoned lock is refused before the call"
18172 );
18173 end(&source);
18174 assert_dropped(&source);
18175 }
18176}
18177
18178#[cfg(test)]
18179mod unprojectable_fields_tests {
18180 use super::*;
18181
18182 /// The field names `docs/metadata.md` says a `metadata_fields` entry may not name.
18183 fn documented() -> std::collections::BTreeSet<String> {
18184 let document = std::fs::read_to_string(
18185 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18186 )
18187 .expect("docs/metadata.md is readable");
18188 let document = document.split_whitespace().collect::<Vec<_>>().join(" ");
18189 let lead = "a `field` equal, ignoring case, to ";
18190 let start = document.find(lead).expect("the refused-field sentence") + lead.len();
18191 let sentence = &document[start..];
18192 let sentence = &sentence[..sentence
18193 .find("; and two entries naming one field")
18194 .expect("the refused-field sentence ends at the duplicate rule")];
18195 let (own, github) = sentence
18196 .split_once(" or a field GitHub owns on every board (")
18197 .expect("the sentence names GitHub's own fields");
18198 own.split('`')
18199 .skip(1)
18200 .step_by(2)
18201 .chain(
18202 github
18203 .strip_suffix(')')
18204 .expect("GitHub's own fields close the sentence")
18205 .split(", "),
18206 )
18207 .map(str::to_owned)
18208 .collect()
18209 }
18210
18211 /// `docs/metadata.md` states the text field's limit a caller is held to; it is this source's
18212 /// own constant, so the two cannot part.
18213 #[test]
18214 fn the_documented_text_field_limit_is_the_one_the_source_shortens_at() {
18215 let document = std::fs::read_to_string(
18216 std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/metadata.md"),
18217 )
18218 .expect("docs/metadata.md is readable");
18219 let lead = "**A text field holds at most ";
18220 let start = document.find(lead).expect("the limit sentence") + lead.len();
18221 let stated = &document[start..start + document[start..].find(',').unwrap() + 4];
18222 assert_eq!(
18223 stated.replace(',', "").parse::<usize>().ok(),
18224 Some(TEXT_FIELD_LIMIT),
18225 "docs/metadata.md states {stated:?}"
18226 );
18227 assert!(document[start..].starts_with(&format!("{stated}, counted here in UTF-8 bytes.")));
18228 }
18229
18230 #[test]
18231 fn the_documented_refused_fields_are_exactly_the_ones_the_configuration_refuses() {
18232 let refused: std::collections::BTreeSet<String> = UNPROJECTABLE_FIELDS
18233 .iter()
18234 .map(|&name| name.to_owned())
18235 .collect();
18236 assert_eq!(documented(), refused, "the fields docs/metadata.md lists");
18237 let instance = SourceName::new("work").unwrap();
18238 for name in UNPROJECTABLE_FIELDS {
18239 for spelled in [name.to_owned(), name.to_uppercase()] {
18240 let entry = MetadataFieldConfig {
18241 field: spelled.clone(),
18242 key: "team.machine".to_owned(),
18243 path: Vec::new(),
18244 };
18245 let refused = MetadataField::resolve(vec![entry], &instance)
18246 .expect_err("an unprojectable field is refused");
18247 assert!(
18248 refused.to_string().contains(&format!("{name:?}")),
18249 "{spelled}: {refused}"
18250 );
18251 }
18252 }
18253 }
18254}