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    #[tracing::instrument(
490        name = "interprex.provider.code_reviews.publish_review",
491        skip_all,
492        fields(interprex.provider.name = "github")
493    )]
494    async fn publish_review(
495        &self,
496        repository: &Repository,
497        number: ChangeRequestNumber,
498        reviewer: &ReviewerApplication,
499        submission: &ReviewSubmission,
500    ) -> Result<ReviewId> {
501        let app = self.reviewer_app(reviewer)?;
502        validate_submission_summary(submission.summary())?;
503        let digest = submission_digest(submission)?;
504        let scope = PublicationScope {
505            app,
506            repository,
507            number,
508            reviewer,
509            key: submission.publication_key(),
510            digest: Some(&digest),
511            submission: Some(submission),
512        };
513        if let Some(publication) = self.read_matching_publication(scope).await? {
514            if publication.is_submitted() {
515                return Ok(publication.review_id);
516            }
517            self.require_review_revision(app, repository, number, &submission.revision().head_sha)
518                .await?;
519            return self.finish_publication(scope, publication).await;
520        }
521
522        self.require_review_revision(app, repository, number, &submission.revision().head_sha)
523            .await?;
524
525        let record = PublicationRecord {
526            version: PUBLICATION_VERSION,
527            key: submission.publication_key().as_str().to_owned(),
528            digest: digest.clone(),
529            disposition: submission.disposition(),
530        };
531        let body = publication_body(submission.summary(), &record)?;
532        let comments = submission
533            .findings()
534            .iter()
535            .map(|finding| {
536                json!({
537                    "path": finding.path(),
538                    "line": finding.line().get(),
539                    "side": match finding.side() {
540                        ReviewDiffSide::Left => "LEFT",
541                        ReviewDiffSide::Right => "RIGHT",
542                    },
543                    "body": finding.body(),
544                })
545            })
546            .collect::<Vec<_>>();
547        let draft = PublicationDraft {
548            submission,
549            digest: &digest,
550            body,
551            comments,
552        };
553
554        let created = match self.create_publication(scope, &draft).await {
555            Ok(publication) => publication,
556            Err(create_error) => {
557                match self
558                    .reconcile_or_replace_create(scope, &draft, create_error)
559                    .await?
560                {
561                    CreateOutcome::Published(review_id) => return Ok(review_id),
562                    CreateOutcome::Draft(publication) => publication,
563                }
564            }
565        };
566
567        if !created.is_pending() {
568            return Err(reconciliation_error(
569                "GitHub create-review response was not pending",
570            ));
571        }
572        self.submit_publication(scope, &created).await
573    }
574
575    #[tracing::instrument(
576        name = "interprex.provider.code_reviews.resume_review_publication",
577        skip_all,
578        fields(interprex.provider.name = "github")
579    )]
580    async fn resume_review_publication(
581        &self,
582        repository: &Repository,
583        number: ChangeRequestNumber,
584        reviewer: &ReviewerApplication,
585        key: &ReviewPublicationKey,
586    ) -> Result<Option<ReviewId>> {
587        let app = self.reviewer_app(reviewer)?;
588        let scope = PublicationScope {
589            app,
590            repository,
591            number,
592            reviewer,
593            key,
594            digest: None,
595            submission: None,
596        };
597        let Some(publication) = self.read_matching_publication(scope).await? else {
598            return Ok(None);
599        };
600        self.finish_publication(scope, publication).await.map(Some)
601    }
602
603    #[tracing::instrument(
604        name = "interprex.provider.code_reviews.dismiss_review",
605        skip_all,
606        fields(interprex.provider.name = "github")
607    )]
608    async fn dismiss_review(
609        &self,
610        repository: &Repository,
611        number: ChangeRequestNumber,
612        reviewer: &ReviewerApplication,
613        review_id: &ReviewId,
614        message: &ReviewDismissalMessage,
615    ) -> Result<()> {
616        let app = self.reviewer_app(reviewer)?;
617        let Some(numeric_id) = self
618            .dismissable_review(app, repository, number, reviewer, review_id)
619            .await?
620        else {
621            return Ok(());
622        };
623
624        // This client does not retry writes. A dismissal GitHub already
625        // applied is indistinguishable from one it refused once the response
626        // is lost, so the reread below decides which happened.
627        let path = format!(
628            "/repos/{repository}/pulls/{}/reviews/{numeric_id}/dismissals",
629            number.get()
630        );
631        let write = tokio::time::timeout(
632            WRITE_TIMEOUT,
633            app.write.put::<serde_json::Value, _, _>(
634                path,
635                Some(&json!({ "message": message.as_str() })),
636            ),
637        )
638        .await;
639        let write_error = match write {
640            Ok(Ok(_)) => None,
641            Ok(Err(error)) => Some(authenticated_external("dismiss review", &error)),
642            Err(_) => Some(dismissal_error("the dismissal request timed out")),
643        };
644
645        match self
646            .observed_review(app, repository, number, review_id)
647            .await?
648        {
649            Some(review) if review.state == DISMISSED_STATE => Ok(()),
650            Some(_) => Err(write_error.unwrap_or_else(|| {
651                dismissal_error("GitHub accepted the dismissal but reread the review undismissed")
652            })),
653            None => Err(write_error.unwrap_or_else(|| {
654                dismissal_error("GitHub accepted the dismissal but reread found no review")
655            })),
656        }
657    }
658}
659
660fn validate_submission_summary(summary: &str) -> Result<()> {
661    if summary.contains(PUBLICATION_IDENTIFIER) {
662        return Err(ProviderError::InvalidInput {
663            provider: "github",
664            fact: "review summary contains the reserved interprex:review-publication identifier"
665                .to_owned(),
666        });
667    }
668    Ok(())
669}
670
671#[derive(Clone)]
672struct OwnedPublication {
673    numeric_id: u64,
674    review_id: ReviewId,
675    state: String,
676    record: PublicationRecord,
677}
678
679impl OwnedPublication {
680    fn is_pending(&self) -> bool {
681        self.state == "PENDING"
682    }
683
684    fn is_submitted(&self) -> bool {
685        !self.is_pending()
686    }
687}
688
689impl From<Publication<'_>> for OwnedPublication {
690    fn from(publication: Publication<'_>) -> Self {
691        Self {
692            numeric_id: publication.review.id,
693            review_id: ReviewId::new(publication.review.node_id.clone())
694                .expect("validated review identifier"),
695            state: publication.review.state.clone(),
696            record: publication.record,
697        }
698    }
699}
700
701fn owned_publication(
702    review: GithubReview,
703    reviewer: &ReviewerApplication,
704    key: &ReviewPublicationKey,
705    digest: &str,
706    submission: &ReviewSubmission,
707) -> Result<OwnedPublication> {
708    if !same_reviewer(&review, reviewer) {
709        return Err(reconciliation_error(
710            "GitHub create-review response has a different reviewer identity",
711        ));
712    }
713    let mut records = publication_records(&review.body)?;
714    if records.len() != 1 || records[0].key != key.as_str() {
715        return Err(reconciliation_error(format!(
716            "GitHub create-review response contains {} matching publication records",
717            records
718                .iter()
719                .filter(|record| record.key == key.as_str())
720                .count()
721        )));
722    }
723    let record = records.pop().expect("one matching publication record");
724    validate_review_record(&review, &record)?;
725    if record.digest != digest
726        || record.disposition != submission.disposition()
727        || review.commit_id != submission.revision().head_sha
728    {
729        return Err(reconciliation_error(
730            "GitHub create-review response contradicts the requested digest, revision, or disposition",
731        ));
732    }
733    let review_id = ReviewId::new(review.node_id.clone())
734        .map_err(|error| reconciliation_error(error.to_string()))?;
735    Ok(OwnedPublication {
736        numeric_id: review.id,
737        review_id,
738        state: review.state,
739        record,
740    })
741}
742
743fn same_reviewer(review: &GithubReview, reviewer: &ReviewerApplication) -> bool {
744    // GitHub omits `performed_via_github_app` on pending reviews, so the bot
745    // user is what identifies the application's actor; the app id is checked
746    // only on the responses that carry it.
747    review
748        .user
749        .as_ref()
750        .is_some_and(|user| user.node_id == reviewer.bot().id.as_str())
751        && review
752            .performed_via_github_app
753            .as_ref()
754            .is_none_or(|app| app.id.to_string() == reviewer.app().id.as_str())
755}
756
757fn publication_records(body: &str) -> Result<Vec<PublicationRecord>> {
758    let carrier_count = body.match_indices(PUBLICATION_CARRIER).count();
759    let records = super::text_records::extract_records(body)
760        .into_iter()
761        .filter(|record| {
762            record.namespace() == PUBLICATION_NAMESPACE && record.name() == PUBLICATION_NAME
763        })
764        .map(|record| {
765            serde_json::from_value::<PublicationRecord>(record.value().clone()).map_err(|error| {
766                reconciliation_error(format!("malformed publication record: {error}"))
767            })
768        })
769        .collect::<Result<Vec<_>>>()?;
770    if records.len() != carrier_count {
771        return Err(reconciliation_error(
772            "malformed publication record carrier in exact-identity review",
773        ));
774    }
775    for record in &records {
776        validate_record(record)?;
777    }
778    Ok(records)
779}
780
781fn validate_record(record: &PublicationRecord) -> Result<()> {
782    let digest = record.digest.strip_prefix("sha256:");
783    if record.version != PUBLICATION_VERSION
784        || record.key.trim().is_empty()
785        || digest.is_none_or(|value| {
786            value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit())
787        })
788    {
789        return Err(reconciliation_error(
790            "publication record has an unsupported version, blank key, or invalid digest",
791        ));
792    }
793    Ok(())
794}
795
796fn validate_review_record(review: &GithubReview, record: &PublicationRecord) -> Result<()> {
797    if review.id == 0 || review.node_id.is_empty() || review.commit_id.trim().is_empty() {
798        return Err(reconciliation_error(
799            "publication review has an invalid identifier or revision",
800        ));
801    }
802    match review.state.as_str() {
803        "PENDING" if review.submitted_at.is_none() => Ok(()),
804        "PENDING" => Err(reconciliation_error(
805            "pending publication review has a submission time",
806        )),
807        state if state == github_state(record.disposition) && review.submitted_at.is_some() => {
808            Ok(())
809        }
810        state if state == github_state(record.disposition) => Err(reconciliation_error(
811            "submitted publication review has no submission time",
812        )),
813        state => Err(reconciliation_error(format!(
814            "publication record intends {} but GitHub reports {state}",
815            github_state(record.disposition)
816        ))),
817    }
818}
819
820fn publication_body(summary: &str, record: &PublicationRecord) -> Result<String> {
821    let record = ProviderTextRecord::new(
822        PUBLICATION_NAMESPACE,
823        PUBLICATION_NAME,
824        serde_json::to_value(record).map_err(|error| reconciliation_error(error.to_string()))?,
825    )
826    .map_err(|error| reconciliation_error(error.to_string()))?;
827    Ok(super::text_records::embed_record(summary, &record))
828}
829
830fn submission_digest(submission: &ReviewSubmission) -> Result<String> {
831    let bytes = serde_json::to_vec(submission)
832        .map_err(|error| reconciliation_error(format!("serialize review submission: {error}")))?;
833    Ok(format!("sha256:{:x}", Sha256::digest(bytes)))
834}
835
836fn create_review_error(error: &octocrab::Error) -> ProviderError {
837    if let octocrab::Error::GitHub { source, .. } = error
838        && source.status_code.as_u16() == 422
839        && let Some(errors) = source.errors.as_deref()
840        && !errors.is_empty()
841        && let Some(mut fields) = errors
842            .iter()
843            .map(review_validation_field)
844            .collect::<Option<Vec<_>>>()
845    {
846        fields.sort_unstable();
847        fields.dedup();
848        return ProviderError::InvalidInput {
849            provider: "github",
850            fact: format!("GitHub rejected these review fields: {}", fields.join(", ")),
851        };
852    }
853    authenticated_external("create review", error)
854}
855
856fn review_validation_field(error: &serde_json::Value) -> Option<&'static str> {
857    let resource = error.get("resource")?.as_str()?;
858    let field = error.get("field")?.as_str()?;
859    let code = error.get("code")?.as_str()?;
860    if !matches!(
861        code,
862        "custom" | "invalid" | "missing" | "missing_field" | "unprocessable"
863    ) {
864        return None;
865    }
866    match (resource, field) {
867        ("PullRequestReview", "body") => Some("body"),
868        ("PullRequestReview", "comments") => Some("comments"),
869        ("PullRequestReview", "commit_id") => Some("commit_id"),
870        ("PullRequestReview", "event") => Some("event"),
871        ("PullRequestReviewComment", "body") => Some("comments.body"),
872        ("PullRequestReviewComment", "line") => Some("comments.line"),
873        ("PullRequestReviewComment", "path") => Some("comments.path"),
874        ("PullRequestReviewComment", "position") => Some("comments.position"),
875        ("PullRequestReviewComment", "side") => Some("comments.side"),
876        ("PullRequestReviewComment", "start_line") => Some("comments.start_line"),
877        ("PullRequestReviewComment", "start_side") => Some("comments.start_side"),
878        _ => None,
879    }
880}
881
882fn github_event(disposition: ReviewSubmissionDisposition) -> &'static str {
883    match disposition {
884        ReviewSubmissionDisposition::Approved => "APPROVE",
885        ReviewSubmissionDisposition::ChangesRequested => "REQUEST_CHANGES",
886        ReviewSubmissionDisposition::Commented => "COMMENT",
887    }
888}
889
890fn github_state(disposition: ReviewSubmissionDisposition) -> &'static str {
891    match disposition {
892        ReviewSubmissionDisposition::Approved => "APPROVED",
893        ReviewSubmissionDisposition::ChangesRequested => "CHANGES_REQUESTED",
894        ReviewSubmissionDisposition::Commented => "COMMENTED",
895    }
896}
897
898fn reconciliation_error(message: impl Into<String>) -> ProviderError {
899    ProviderError::External {
900        provider: "github",
901        operation: "reconcile review publication",
902        message: message.into(),
903    }
904}
905
906fn dismissal_error(message: impl Into<String>) -> ProviderError {
907    ProviderError::External {
908        provider: "github",
909        operation: "dismiss review",
910        message: message.into(),
911    }
912}