Skip to main content

interprex_github/code_reviews/
review_publications.rs

1use std::time::Duration;
2
3use async_trait::async_trait;
4use interprex::{
5    ChangeRequestNumber, ProviderError, ProviderTextRecord, Repository, Result, ReviewDiffSide,
6    ReviewDismissalMessage, ReviewId, ReviewPublicationKey, ReviewPublishingProvider,
7    ReviewSubmission, ReviewSubmissionDisposition, ReviewerApplication,
8};
9use octocrab::Page;
10use serde::{Deserialize, Serialize};
11use serde_json::json;
12use sha2::{Digest, Sha256};
13
14use crate::{
15    GithubProvider,
16    client::{ConfiguredApp, authenticated_external, is_not_found},
17};
18
19use super::change_requests::GithubReview;
20
21const PUBLICATION_NAMESPACE: &str = "interprex";
22const PUBLICATION_NAME: &str = "review-publication";
23const PUBLICATION_VERSION: u64 = 1;
24const PUBLICATION_IDENTIFIER: &str = "interprex:review-publication";
25const PUBLICATION_CARRIER: &str = "<!-- interprex:review-publication";
26const MAX_OBSERVED_PULL_REQUEST_COMMITS: usize = 250;
27const DISMISSED_STATE: &str = "DISMISSED";
28const WRITE_TIMEOUT: Duration = Duration::from_secs(30);
29
30#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
31#[serde(deny_unknown_fields)]
32struct PublicationRecord {
33    version: u64,
34    key: String,
35    digest: String,
36    disposition: ReviewSubmissionDisposition,
37}
38
39#[derive(Deserialize)]
40struct PullRequestCommit {
41    sha: String,
42}
43
44struct Publication<'a> {
45    review: &'a GithubReview,
46    record: PublicationRecord,
47}
48
49/// What one read of a change request's reviews says about a publication: the
50/// review carrying its key, and any other pending draft the same reviewer app
51/// owns. GitHub allows one pending review per author per change request, so
52/// while such a draft stands GitHub refuses every create that follows.
53struct PublicationReadout {
54    publication: Option<OwnedPublication>,
55    orphaned_draft: Option<u64>,
56}
57
58/// The review a create request writes, kept whole so the request can be made
59/// again after an orphaned draft is deleted.
60struct PublicationDraft<'a> {
61    submission: &'a ReviewSubmission,
62    digest: &'a str,
63    body: String,
64    comments: Vec<serde_json::Value>,
65}
66
67/// How a failed create ended once the provider had re-read the change request.
68enum CreateOutcome {
69    /// The re-read found the publication, and it needs nothing further.
70    Published(ReviewId),
71    /// A second create, after an orphaned draft was deleted, produced this
72    /// draft; the caller still submits it.
73    Draft(OwnedPublication),
74}
75
76#[derive(Clone, Copy)]
77struct PublicationScope<'a> {
78    app: &'a ConfiguredApp,
79    repository: &'a Repository,
80    number: ChangeRequestNumber,
81    reviewer: &'a ReviewerApplication,
82    key: &'a ReviewPublicationKey,
83    digest: Option<&'a str>,
84    submission: Option<&'a ReviewSubmission>,
85}
86
87impl GithubProvider {
88    fn reviewer_app(&self, reviewer: &ReviewerApplication) -> Result<&ConfiguredApp> {
89        let configured = self.configured_app(&reviewer.app().slug)?;
90        if configured.app_id.to_string() != reviewer.app().id.as_str() {
91            return Err(ProviderError::Configuration {
92                origin: configured.source.clone(),
93                reason: format!(
94                    "named app {} has APP_ID {}, but the resolved reviewer has provider app ID {}",
95                    reviewer.app().slug,
96                    configured.app_id,
97                    reviewer.app().id.as_str()
98                ),
99            });
100        }
101        Ok(configured)
102    }
103
104    fn matching_publication<'a>(
105        &self,
106        reviews: &'a [GithubReview],
107        reviewer: &ReviewerApplication,
108        key: &ReviewPublicationKey,
109        expected_digest: Option<&str>,
110        expected_submission: Option<&ReviewSubmission>,
111    ) -> Result<Option<Publication<'a>>> {
112        let mut matches = Vec::new();
113        for review in reviews {
114            if !same_reviewer(review, reviewer) {
115                continue;
116            }
117            if review.user.as_ref().and_then(|user| user.kind.as_deref()) != Some("Bot") {
118                return Err(reconciliation_error(
119                    "exact-identity publication review author is not a bot",
120                ));
121            }
122            let records = publication_records(&review.body)?;
123            if records.is_empty() {
124                if review.state == "PENDING"
125                    && expected_submission.is_some_and(|submission| {
126                        review.commit_id == submission.revision().head_sha
127                            && review.body.starts_with(submission.summary())
128                    })
129                {
130                    return Err(reconciliation_error(
131                        "an exact-identity pending review matches the submission but has no publication record",
132                    ));
133                }
134                continue;
135            }
136            if records.len() != 1 {
137                return Err(reconciliation_error(format!(
138                    "exact-identity review {} contains {} publication records",
139                    review.node_id,
140                    records.len()
141                )));
142            }
143            for record in records {
144                if record.key == key.as_str() {
145                    matches.push(Publication { review, record });
146                }
147            }
148        }
149
150        let publication = match matches.len() {
151            0 => return Ok(None),
152            1 => matches.pop().expect("one publication"),
153            count => {
154                return Err(reconciliation_error(format!(
155                    "found {count} exact-identity reviews carrying publication key {}",
156                    key.as_str()
157                )));
158            }
159        };
160        validate_review_record(publication.review, &publication.record)?;
161        if let Some(expected_digest) = expected_digest
162            && publication.record.digest != expected_digest
163        {
164            return Err(ProviderError::InvalidInput {
165                provider: "github",
166                fact: format!(
167                    "review publication key {} already identifies a different submission",
168                    key.as_str()
169                ),
170            });
171        }
172        if let Some(submission) = expected_submission
173            && (publication.review.commit_id != submission.revision().head_sha
174                || publication.record.disposition != submission.disposition())
175        {
176            return Err(reconciliation_error(
177                "matching publication record contradicts the submitted revision or disposition",
178            ));
179        }
180        Ok(Some(publication))
181    }
182
183    async fn read_matching_publication(
184        &self,
185        scope: PublicationScope<'_>,
186    ) -> Result<Option<OwnedPublication>> {
187        self.read_publication(scope)
188            .await
189            .map(|readout| readout.publication)
190    }
191
192    async fn read_publication(&self, scope: PublicationScope<'_>) -> Result<PublicationReadout> {
193        let reviews = self
194            .github_reviews_with(&scope.app.read, scope.repository, scope.number)
195            .await?;
196        let publication = self
197            .matching_publication(
198                &reviews,
199                scope.reviewer,
200                scope.key,
201                scope.digest,
202                scope.submission,
203            )?
204            .map(OwnedPublication::from);
205        let matched = publication
206            .as_ref()
207            .map(|publication| publication.numeric_id);
208        let orphaned_draft = reviews
209            .iter()
210            .find(|review| {
211                review.state == "PENDING"
212                    && same_reviewer(review, scope.reviewer)
213                    && Some(review.id) != matched
214            })
215            .map(|review| review.id);
216        Ok(PublicationReadout {
217            publication,
218            orphaned_draft,
219        })
220    }
221
222    async fn require_review_revision(
223        &self,
224        app: &ConfiguredApp,
225        repository: &Repository,
226        number: ChangeRequestNumber,
227        revision: &str,
228    ) -> Result<()> {
229        let page: Page<PullRequestCommit> = app
230            .read
231            .get(
232                format!("/repos/{repository}/pulls/{}/commits", number.get()),
233                Some(&[("per_page", 100)]),
234            )
235            .await
236            .map_err(|error| {
237                if is_not_found(&error) {
238                    ProviderError::NotFound {
239                        entity: format!("change request {} in {repository}", number.get()),
240                    }
241                } else {
242                    authenticated_external("read change request revisions", &error)
243                }
244            })?;
245        let commits = app
246            .read
247            .all_pages(page)
248            .await
249            .map_err(|error| authenticated_external("read change request revisions", &error))?;
250        if commits.iter().any(|commit| commit.sha == revision) {
251            return Ok(());
252        }
253        if commits.len() >= MAX_OBSERVED_PULL_REQUEST_COMMITS {
254            return Err(reconciliation_error(
255                "GitHub capped the change request revision observation before the requested revision was found",
256            ));
257        }
258        Err(ProviderError::NotFound {
259            entity: format!(
260                "revision {revision} on change request {} in {repository}",
261                number.get()
262            ),
263        })
264    }
265
266    async fn submit_publication(
267        &self,
268        scope: PublicationScope<'_>,
269        pending: &OwnedPublication,
270    ) -> Result<ReviewId> {
271        let event = github_event(pending.record.disposition);
272        let path = format!(
273            "/repos/{}/pulls/{}/reviews/{}/events",
274            scope.repository,
275            scope.number.get(),
276            pending.numeric_id
277        );
278        let write = tokio::time::timeout(
279            WRITE_TIMEOUT,
280            scope
281                .app
282                .write
283                .post::<_, serde_json::Value>(path, Some(&json!({ "event": event }))),
284        )
285        .await;
286        let write_error = match write {
287            Ok(Ok(_)) => None,
288            Ok(Err(error)) => Some(authenticated_external("submit review", &error)),
289            Err(_) => Some(reconciliation_error("submit review timed out")),
290        };
291
292        match self.read_matching_publication(scope).await? {
293            Some(publication) if publication.review_id != pending.review_id => Err(
294                reconciliation_error("GitHub reread a different review after submission"),
295            ),
296            Some(publication) if publication.is_submitted() => Ok(publication.review_id),
297            Some(_) => Err(write_error.unwrap_or_else(|| {
298                reconciliation_error("GitHub accepted review submission but reread it as pending")
299            })),
300            None => Err(write_error.unwrap_or_else(|| {
301                reconciliation_error("GitHub accepted review submission but reread found no review")
302            })),
303        }
304    }
305
306    async fn finish_publication(
307        &self,
308        scope: PublicationScope<'_>,
309        publication: OwnedPublication,
310    ) -> Result<ReviewId> {
311        if publication.is_submitted() {
312            return Ok(publication.review_id);
313        }
314        self.submit_publication(scope, &publication).await
315    }
316
317    async fn observed_review(
318        &self,
319        app: &ConfiguredApp,
320        repository: &Repository,
321        number: ChangeRequestNumber,
322        review_id: &ReviewId,
323    ) -> Result<Option<GithubReview>> {
324        Ok(self
325            .github_reviews_with(&app.read, repository, number)
326            .await?
327            .into_iter()
328            .find(|review| review.node_id == review_id.as_str()))
329    }
330
331    /// Reads the numeric identifier a dismissal request needs, or nothing when
332    /// the review already stands dismissed.
333    ///
334    /// The dismissal endpoint addresses a review by that identifier while
335    /// callers hold the review's node ID, so the review is read before it is
336    /// written whatever the read decides.
337    async fn dismissable_review(
338        &self,
339        app: &ConfiguredApp,
340        repository: &Repository,
341        number: ChangeRequestNumber,
342        reviewer: &ReviewerApplication,
343        review_id: &ReviewId,
344    ) -> Result<Option<u64>> {
345        let review = self
346            .observed_review(app, repository, number, review_id)
347            .await?
348            .ok_or_else(|| ProviderError::NotFound {
349                entity: format!(
350                    "review {} on change request {} in {repository}",
351                    review_id.as_str(),
352                    number.get()
353                ),
354            })?;
355        if !same_reviewer(&review, reviewer) {
356            return Err(ProviderError::InvalidInput {
357                provider: "github",
358                fact: format!(
359                    "review {} was published by another reviewer identity",
360                    review_id.as_str()
361                ),
362            });
363        }
364        match review.state.as_str() {
365            DISMISSED_STATE => Ok(None),
366            "APPROVED" | "CHANGES_REQUESTED" if review.id != 0 => Ok(Some(review.id)),
367            "APPROVED" | "CHANGES_REQUESTED" => Err(dismissal_error(format!(
368                "review {} has no GitHub identifier to dismiss",
369                review_id.as_str()
370            ))),
371            state => Err(ProviderError::InvalidInput {
372                provider: "github",
373                fact: format!("GitHub does not dismiss a {state} review"),
374            }),
375        }
376    }
377
378    async fn reconcile_create(
379        &self,
380        scope: PublicationScope<'_>,
381        create_error: ProviderError,
382    ) -> Result<ReviewId> {
383        match self.read_matching_publication(scope).await? {
384            Some(publication) => self.finish_publication(scope, publication).await,
385            None => Err(create_error),
386        }
387    }
388
389    async fn create_publication(
390        &self,
391        scope: PublicationScope<'_>,
392        draft: &PublicationDraft<'_>,
393    ) -> Result<OwnedPublication> {
394        let path = format!(
395            "/repos/{}/pulls/{}/reviews",
396            scope.repository,
397            scope.number.get()
398        );
399        let create = tokio::time::timeout(
400            WRITE_TIMEOUT,
401            scope.app.write.post::<_, GithubReview>(
402                path,
403                Some(&json!({
404                    "commit_id": draft.submission.revision().head_sha,
405                    "body": draft.body,
406                    "comments": draft.comments,
407                })),
408            ),
409        )
410        .await;
411        match create {
412            Ok(Ok(review)) => owned_publication(
413                review,
414                scope.reviewer,
415                scope.key,
416                draft.digest,
417                draft.submission,
418            ),
419            Ok(Err(error)) => Err(create_review_error(&error)),
420            Err(_) => Err(reconciliation_error("create review timed out")),
421        }
422    }
423
424    /// Re-reads the change request after a create failed, and clears the one
425    /// condition a retry can resolve.
426    ///
427    /// A create that produced no publication under this key may still have
428    /// been rejected because this reviewer app owns a pending draft from an
429    /// earlier round: GitHub allows one pending review per author per change
430    /// request, and a round that failed to reconcile leaves a draft whose key
431    /// no later submission matches. Deleting that draft is what lets the
432    /// publication proceed without a person removing it by hand. Only a
433    /// PENDING review authored by this same reviewer app is ever deleted, and
434    /// the create is retried exactly once.
435    async fn reconcile_or_replace_create(
436        &self,
437        scope: PublicationScope<'_>,
438        draft: &PublicationDraft<'_>,
439        create_error: ProviderError,
440    ) -> Result<CreateOutcome> {
441        let readout = self.read_publication(scope).await?;
442        if let Some(publication) = readout.publication {
443            return self
444                .finish_publication(scope, publication)
445                .await
446                .map(CreateOutcome::Published);
447        }
448        let Some(orphan) = readout.orphaned_draft else {
449            return Err(create_error);
450        };
451        self.delete_pending_draft(scope, orphan).await?;
452        match self.create_publication(scope, draft).await {
453            Ok(publication) => Ok(CreateOutcome::Draft(publication)),
454            Err(retry_error) => self
455                .reconcile_create(scope, retry_error)
456                .await
457                .map(CreateOutcome::Published),
458        }
459    }
460
461    async fn delete_pending_draft(
462        &self,
463        scope: PublicationScope<'_>,
464        review_id: u64,
465    ) -> Result<()> {
466        let path = format!(
467            "/repos/{}/pulls/{}/reviews/{review_id}",
468            scope.repository,
469            scope.number.get()
470        );
471        let delete = tokio::time::timeout(
472            WRITE_TIMEOUT,
473            scope
474                .app
475                .write
476                .delete::<serde_json::Value, _, ()>(path, None),
477        )
478        .await;
479        match delete {
480            Ok(Ok(_)) => Ok(()),
481            Ok(Err(error)) => Err(authenticated_external("delete pending review", &error)),
482            Err(_) => Err(reconciliation_error("delete pending review timed out")),
483        }
484    }
485}
486
487#[async_trait]
488impl ReviewPublishingProvider for GithubProvider {
489    async fn publish_review(
490        &self,
491        repository: &Repository,
492        number: ChangeRequestNumber,
493        reviewer: &ReviewerApplication,
494        submission: &ReviewSubmission,
495    ) -> Result<ReviewId> {
496        let app = self.reviewer_app(reviewer)?;
497        validate_submission_summary(submission.summary())?;
498        let digest = submission_digest(submission)?;
499        let scope = PublicationScope {
500            app,
501            repository,
502            number,
503            reviewer,
504            key: submission.publication_key(),
505            digest: Some(&digest),
506            submission: Some(submission),
507        };
508        if let Some(publication) = self.read_matching_publication(scope).await? {
509            if publication.is_submitted() {
510                return Ok(publication.review_id);
511            }
512            self.require_review_revision(app, repository, number, &submission.revision().head_sha)
513                .await?;
514            return self.finish_publication(scope, publication).await;
515        }
516
517        self.require_review_revision(app, repository, number, &submission.revision().head_sha)
518            .await?;
519
520        let record = PublicationRecord {
521            version: PUBLICATION_VERSION,
522            key: submission.publication_key().as_str().to_owned(),
523            digest: digest.clone(),
524            disposition: submission.disposition(),
525        };
526        let body = publication_body(submission.summary(), &record)?;
527        let comments = submission
528            .findings()
529            .iter()
530            .map(|finding| {
531                json!({
532                    "path": finding.path(),
533                    "line": finding.line().get(),
534                    "side": match finding.side() {
535                        ReviewDiffSide::Left => "LEFT",
536                        ReviewDiffSide::Right => "RIGHT",
537                    },
538                    "body": finding.body(),
539                })
540            })
541            .collect::<Vec<_>>();
542        let draft = PublicationDraft {
543            submission,
544            digest: &digest,
545            body,
546            comments,
547        };
548
549        let created = match self.create_publication(scope, &draft).await {
550            Ok(publication) => publication,
551            Err(create_error) => {
552                match self
553                    .reconcile_or_replace_create(scope, &draft, create_error)
554                    .await?
555                {
556                    CreateOutcome::Published(review_id) => return Ok(review_id),
557                    CreateOutcome::Draft(publication) => publication,
558                }
559            }
560        };
561
562        if !created.is_pending() {
563            return Err(reconciliation_error(
564                "GitHub create-review response was not pending",
565            ));
566        }
567        self.submit_publication(scope, &created).await
568    }
569
570    async fn resume_review_publication(
571        &self,
572        repository: &Repository,
573        number: ChangeRequestNumber,
574        reviewer: &ReviewerApplication,
575        key: &ReviewPublicationKey,
576    ) -> Result<Option<ReviewId>> {
577        let app = self.reviewer_app(reviewer)?;
578        let scope = PublicationScope {
579            app,
580            repository,
581            number,
582            reviewer,
583            key,
584            digest: None,
585            submission: None,
586        };
587        let Some(publication) = self.read_matching_publication(scope).await? else {
588            return Ok(None);
589        };
590        self.finish_publication(scope, publication).await.map(Some)
591    }
592
593    async fn dismiss_review(
594        &self,
595        repository: &Repository,
596        number: ChangeRequestNumber,
597        reviewer: &ReviewerApplication,
598        review_id: &ReviewId,
599        message: &ReviewDismissalMessage,
600    ) -> Result<()> {
601        let app = self.reviewer_app(reviewer)?;
602        let Some(numeric_id) = self
603            .dismissable_review(app, repository, number, reviewer, review_id)
604            .await?
605        else {
606            return Ok(());
607        };
608
609        // This client does not retry writes. A dismissal GitHub already
610        // applied is indistinguishable from one it refused once the response
611        // is lost, so the reread below decides which happened.
612        let path = format!(
613            "/repos/{repository}/pulls/{}/reviews/{numeric_id}/dismissals",
614            number.get()
615        );
616        let write = tokio::time::timeout(
617            WRITE_TIMEOUT,
618            app.write.put::<serde_json::Value, _, _>(
619                path,
620                Some(&json!({ "message": message.as_str() })),
621            ),
622        )
623        .await;
624        let write_error = match write {
625            Ok(Ok(_)) => None,
626            Ok(Err(error)) => Some(authenticated_external("dismiss review", &error)),
627            Err(_) => Some(dismissal_error("the dismissal request timed out")),
628        };
629
630        match self
631            .observed_review(app, repository, number, review_id)
632            .await?
633        {
634            Some(review) if review.state == DISMISSED_STATE => Ok(()),
635            Some(_) => Err(write_error.unwrap_or_else(|| {
636                dismissal_error("GitHub accepted the dismissal but reread the review undismissed")
637            })),
638            None => Err(write_error.unwrap_or_else(|| {
639                dismissal_error("GitHub accepted the dismissal but reread found no review")
640            })),
641        }
642    }
643}
644
645fn validate_submission_summary(summary: &str) -> Result<()> {
646    if summary.contains(PUBLICATION_IDENTIFIER) {
647        return Err(ProviderError::InvalidInput {
648            provider: "github",
649            fact: "review summary contains the reserved interprex:review-publication identifier"
650                .to_owned(),
651        });
652    }
653    Ok(())
654}
655
656#[derive(Clone)]
657struct OwnedPublication {
658    numeric_id: u64,
659    review_id: ReviewId,
660    state: String,
661    record: PublicationRecord,
662}
663
664impl OwnedPublication {
665    fn is_pending(&self) -> bool {
666        self.state == "PENDING"
667    }
668
669    fn is_submitted(&self) -> bool {
670        !self.is_pending()
671    }
672}
673
674impl From<Publication<'_>> for OwnedPublication {
675    fn from(publication: Publication<'_>) -> Self {
676        Self {
677            numeric_id: publication.review.id,
678            review_id: ReviewId::new(publication.review.node_id.clone())
679                .expect("validated review identifier"),
680            state: publication.review.state.clone(),
681            record: publication.record,
682        }
683    }
684}
685
686fn owned_publication(
687    review: GithubReview,
688    reviewer: &ReviewerApplication,
689    key: &ReviewPublicationKey,
690    digest: &str,
691    submission: &ReviewSubmission,
692) -> Result<OwnedPublication> {
693    if !same_reviewer(&review, reviewer) {
694        return Err(reconciliation_error(
695            "GitHub create-review response has a different reviewer identity",
696        ));
697    }
698    let mut records = publication_records(&review.body)?;
699    if records.len() != 1 || records[0].key != key.as_str() {
700        return Err(reconciliation_error(format!(
701            "GitHub create-review response contains {} matching publication records",
702            records
703                .iter()
704                .filter(|record| record.key == key.as_str())
705                .count()
706        )));
707    }
708    let record = records.pop().expect("one matching publication record");
709    validate_review_record(&review, &record)?;
710    if record.digest != digest
711        || record.disposition != submission.disposition()
712        || review.commit_id != submission.revision().head_sha
713    {
714        return Err(reconciliation_error(
715            "GitHub create-review response contradicts the requested digest, revision, or disposition",
716        ));
717    }
718    let review_id = ReviewId::new(review.node_id.clone())
719        .map_err(|error| reconciliation_error(error.to_string()))?;
720    Ok(OwnedPublication {
721        numeric_id: review.id,
722        review_id,
723        state: review.state,
724        record,
725    })
726}
727
728fn same_reviewer(review: &GithubReview, reviewer: &ReviewerApplication) -> bool {
729    // GitHub omits `performed_via_github_app` on pending reviews, so the bot
730    // user is what identifies the application's actor; the app id is checked
731    // only on the responses that carry it.
732    review
733        .user
734        .as_ref()
735        .is_some_and(|user| user.node_id == reviewer.bot().id.as_str())
736        && review
737            .performed_via_github_app
738            .as_ref()
739            .is_none_or(|app| app.id.to_string() == reviewer.app().id.as_str())
740}
741
742fn publication_records(body: &str) -> Result<Vec<PublicationRecord>> {
743    let carrier_count = body.match_indices(PUBLICATION_CARRIER).count();
744    let records = super::text_records::extract_records(body)
745        .into_iter()
746        .filter(|record| {
747            record.namespace() == PUBLICATION_NAMESPACE && record.name() == PUBLICATION_NAME
748        })
749        .map(|record| {
750            serde_json::from_value::<PublicationRecord>(record.value().clone()).map_err(|error| {
751                reconciliation_error(format!("malformed publication record: {error}"))
752            })
753        })
754        .collect::<Result<Vec<_>>>()?;
755    if records.len() != carrier_count {
756        return Err(reconciliation_error(
757            "malformed publication record carrier in exact-identity review",
758        ));
759    }
760    for record in &records {
761        validate_record(record)?;
762    }
763    Ok(records)
764}
765
766fn validate_record(record: &PublicationRecord) -> Result<()> {
767    let digest = record.digest.strip_prefix("sha256:");
768    if record.version != PUBLICATION_VERSION
769        || record.key.trim().is_empty()
770        || digest.is_none_or(|value| {
771            value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit())
772        })
773    {
774        return Err(reconciliation_error(
775            "publication record has an unsupported version, blank key, or invalid digest",
776        ));
777    }
778    Ok(())
779}
780
781fn validate_review_record(review: &GithubReview, record: &PublicationRecord) -> Result<()> {
782    if review.id == 0 || review.node_id.is_empty() || review.commit_id.trim().is_empty() {
783        return Err(reconciliation_error(
784            "publication review has an invalid identifier or revision",
785        ));
786    }
787    match review.state.as_str() {
788        "PENDING" if review.submitted_at.is_none() => Ok(()),
789        "PENDING" => Err(reconciliation_error(
790            "pending publication review has a submission time",
791        )),
792        state if state == github_state(record.disposition) && review.submitted_at.is_some() => {
793            Ok(())
794        }
795        state if state == github_state(record.disposition) => Err(reconciliation_error(
796            "submitted publication review has no submission time",
797        )),
798        state => Err(reconciliation_error(format!(
799            "publication record intends {} but GitHub reports {state}",
800            github_state(record.disposition)
801        ))),
802    }
803}
804
805fn publication_body(summary: &str, record: &PublicationRecord) -> Result<String> {
806    let record = ProviderTextRecord::new(
807        PUBLICATION_NAMESPACE,
808        PUBLICATION_NAME,
809        serde_json::to_value(record).map_err(|error| reconciliation_error(error.to_string()))?,
810    )
811    .map_err(|error| reconciliation_error(error.to_string()))?;
812    Ok(super::text_records::embed_record(summary, &record))
813}
814
815fn submission_digest(submission: &ReviewSubmission) -> Result<String> {
816    let bytes = serde_json::to_vec(submission)
817        .map_err(|error| reconciliation_error(format!("serialize review submission: {error}")))?;
818    Ok(format!("sha256:{:x}", Sha256::digest(bytes)))
819}
820
821fn create_review_error(error: &octocrab::Error) -> ProviderError {
822    if let octocrab::Error::GitHub { source, .. } = error
823        && source.status_code.as_u16() == 422
824        && let Some(errors) = source.errors.as_deref()
825        && !errors.is_empty()
826        && let Some(mut fields) = errors
827            .iter()
828            .map(review_validation_field)
829            .collect::<Option<Vec<_>>>()
830    {
831        fields.sort_unstable();
832        fields.dedup();
833        return ProviderError::InvalidInput {
834            provider: "github",
835            fact: format!("GitHub rejected these review fields: {}", fields.join(", ")),
836        };
837    }
838    authenticated_external("create review", error)
839}
840
841fn review_validation_field(error: &serde_json::Value) -> Option<&'static str> {
842    let resource = error.get("resource")?.as_str()?;
843    let field = error.get("field")?.as_str()?;
844    let code = error.get("code")?.as_str()?;
845    if !matches!(
846        code,
847        "custom" | "invalid" | "missing" | "missing_field" | "unprocessable"
848    ) {
849        return None;
850    }
851    match (resource, field) {
852        ("PullRequestReview", "body") => Some("body"),
853        ("PullRequestReview", "comments") => Some("comments"),
854        ("PullRequestReview", "commit_id") => Some("commit_id"),
855        ("PullRequestReview", "event") => Some("event"),
856        ("PullRequestReviewComment", "body") => Some("comments.body"),
857        ("PullRequestReviewComment", "line") => Some("comments.line"),
858        ("PullRequestReviewComment", "path") => Some("comments.path"),
859        ("PullRequestReviewComment", "position") => Some("comments.position"),
860        ("PullRequestReviewComment", "side") => Some("comments.side"),
861        ("PullRequestReviewComment", "start_line") => Some("comments.start_line"),
862        ("PullRequestReviewComment", "start_side") => Some("comments.start_side"),
863        _ => None,
864    }
865}
866
867fn github_event(disposition: ReviewSubmissionDisposition) -> &'static str {
868    match disposition {
869        ReviewSubmissionDisposition::Approved => "APPROVE",
870        ReviewSubmissionDisposition::ChangesRequested => "REQUEST_CHANGES",
871        ReviewSubmissionDisposition::Commented => "COMMENT",
872    }
873}
874
875fn github_state(disposition: ReviewSubmissionDisposition) -> &'static str {
876    match disposition {
877        ReviewSubmissionDisposition::Approved => "APPROVED",
878        ReviewSubmissionDisposition::ChangesRequested => "CHANGES_REQUESTED",
879        ReviewSubmissionDisposition::Commented => "COMMENTED",
880    }
881}
882
883fn reconciliation_error(message: impl Into<String>) -> ProviderError {
884    ProviderError::External {
885        provider: "github",
886        operation: "reconcile review publication",
887        message: message.into(),
888    }
889}
890
891fn dismissal_error(message: impl Into<String>) -> ProviderError {
892    ProviderError::External {
893        provider: "github",
894        operation: "dismiss review",
895        message: message.into(),
896    }
897}