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