Skip to main content

ag_forge/
client.rs

1//! Public review-request trait boundary and production client wiring.
2
3use std::sync::Arc;
4
5use super::{
6    CreateReviewRequestInput, ForgeCommandRunner, ForgeFuture, ForgeKind, ForgeRemote,
7    GitHubReviewRequestAdapter, GitLabReviewRequestAdapter, RealForgeCommandRunner,
8    ReviewCommentSnapshot, ReviewRequestAttention, ReviewRequestError, ReviewRequestMetadata,
9    ReviewRequestSummary, UpdateReviewRequestInput, detect_remote,
10};
11
12/// Async boundary used by app orchestration for forge review requests.
13///
14/// The app layer depends on this narrow contract so provider-specific request
15/// formats remain isolated inside concrete adapters.
16#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
17pub trait ReviewRequestClient: Send + Sync {
18    /// Detects whether `repo_url` belongs to one supported forge.
19    ///
20    /// # Errors
21    /// Returns [`ReviewRequestError::UnsupportedRemote`] when the remote does
22    /// not map to a supported forge.
23    fn detect_remote(&self, repo_url: String) -> Result<ForgeRemote, ReviewRequestError>;
24
25    /// Finds an existing review request for `source_branch`.
26    ///
27    /// # Errors
28    /// Returns a provider-specific review-request error when the forge lookup
29    /// cannot be completed.
30    fn find_by_source_branch(
31        &self,
32        remote: ForgeRemote,
33        source_branch: String,
34    ) -> ForgeFuture<Result<Option<ReviewRequestSummary>, ReviewRequestError>>;
35
36    /// Creates a new review request from `input`.
37    ///
38    /// # Errors
39    /// Returns a provider-specific review-request error when creation fails.
40    fn create_review_request(
41        &self,
42        remote: ForgeRemote,
43        input: CreateReviewRequestInput,
44    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
45
46    /// Refreshes one existing review request by provider display id.
47    ///
48    /// # Errors
49    /// Returns a provider-specific review-request error when refresh fails.
50    fn refresh_review_request(
51        &self,
52        remote: ForgeRemote,
53        display_id: String,
54    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
55
56    /// Loads the current title and body of one existing review request.
57    ///
58    /// # Errors
59    /// Returns a provider-specific review-request error when metadata lookup
60    /// fails.
61    fn review_request_metadata(
62        &self,
63        remote: ForgeRemote,
64        display_id: String,
65    ) -> ForgeFuture<Result<ReviewRequestMetadata, ReviewRequestError>>;
66
67    /// Best-effort syncs reconciled metadata after rechecking that the remote
68    /// fields match the values used during evaluation.
69    ///
70    /// The provider CLI update is not atomic with the recheck, so a later
71    /// concurrent manual edit can still be overwritten.
72    ///
73    /// # Errors
74    /// Returns a provider-specific review-request error when metadata lookup,
75    /// update, or refresh fails.
76    fn sync_review_request_metadata(
77        &self,
78        remote: ForgeRemote,
79        display_id: String,
80        input: UpdateReviewRequestInput,
81    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
82
83    /// Returns the browser-openable URL for one review request.
84    ///
85    /// # Errors
86    /// Returns [`ReviewRequestError::OperationFailed`] when the summary does
87    /// not carry a web URL.
88    fn review_request_web_url(
89        &self,
90        review_request: &ReviewRequestSummary,
91    ) -> Result<String, ReviewRequestError>;
92
93    /// Fetches the review-comment snapshot for one open review request.
94    ///
95    /// Returns both inline threads and review-request-wide comments. Threads
96    /// are grouped by `path` and sorted by `(path, line)` by callers; adapters
97    /// return what the forge reports without enforcing an ordering.
98    ///
99    /// # Errors
100    /// Returns a provider-specific review-request error when the snapshot fetch
101    /// cannot be completed (including authentication and host failures).
102    fn fetch_review_comment_snapshot(
103        &self,
104        remote: ForgeRemote,
105        display_id: String,
106    ) -> ForgeFuture<Result<ReviewCommentSnapshot, ReviewRequestError>>;
107
108    /// Fetches the conditions on one open review request that may need
109    /// follow-up work: failed and pending checks for its head commit, merge
110    /// conflicts with its target branch, and unresolved review threads
111    /// awaiting a response from trusted authors.
112    ///
113    /// `trusted_bots` lists review-bot logins whose comments count as
114    /// trusted and whose own failed checks are left to their review threads.
115    /// GitHub matches bot accounts by login, never users with the same name;
116    /// GitLab matches note author usernames.
117    ///
118    /// # Errors
119    /// Returns a provider-specific review-request error when any forge lookup
120    /// cannot be completed, including the author-trust lookups, so callers
121    /// never act on partial facts.
122    fn fetch_review_request_attention(
123        &self,
124        remote: ForgeRemote,
125        display_id: String,
126        trusted_bots: Vec<String>,
127    ) -> ForgeFuture<Result<ReviewRequestAttention, ReviewRequestError>>;
128
129    /// Reruns the failed jobs of each workflow run or pipeline named by
130    /// `rerun_ids`, taken from
131    /// [`ReviewCheckFailure::rerun_id`](crate::ReviewCheckFailure::rerun_id).
132    ///
133    /// Each distinct id is rerun once, in order, so several failed checks
134    /// from one workflow run or pipeline request one rerun.
135    ///
136    /// # Errors
137    /// Returns a provider-specific review-request error when an id is
138    /// malformed or the forge rejects a rerun. Reruns requested before the
139    /// failing one are not reverted.
140    fn rerun_failed_checks(
141        &self,
142        remote: ForgeRemote,
143        rerun_ids: Vec<String>,
144    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
145
146    /// Adds one reply to an existing review thread.
147    ///
148    /// # Errors
149    /// Returns a provider-specific review-request error when the reply cannot
150    /// be posted.
151    fn reply_to_thread(
152        &self,
153        remote: ForgeRemote,
154        display_id: String,
155        thread_id: String,
156        body: String,
157    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
158
159    /// Marks one existing review thread resolved.
160    ///
161    /// # Errors
162    /// Returns a provider-specific review-request error when the thread cannot
163    /// be resolved.
164    fn resolve_thread(
165        &self,
166        remote: ForgeRemote,
167        display_id: String,
168        thread_id: String,
169    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
170}
171
172/// Production [`ReviewRequestClient`] that routes to forge-specific adapters.
173pub struct RealReviewRequestClient {
174    command_runner: Arc<dyn ForgeCommandRunner>,
175}
176
177impl RealReviewRequestClient {
178    /// Builds one review-request client from a forge command runner.
179    pub(crate) fn new(command_runner: Arc<dyn ForgeCommandRunner>) -> Self {
180        Self { command_runner }
181    }
182
183    /// Runs `call` on an authenticated adapter selected for `remote`.
184    fn call_with_authenticated_adapter<T>(
185        &self,
186        remote: ForgeRemote,
187        call: impl FnOnce(
188            Arc<dyn ReviewRequestAdapter>,
189            ForgeRemote,
190        ) -> ForgeFuture<Result<T, ReviewRequestError>>
191        + Send
192        + 'static,
193    ) -> ForgeFuture<Result<T, ReviewRequestError>>
194    where
195        T: Send + 'static,
196    {
197        let adapter = self.adapter_for(remote.forge_kind);
198
199        Box::pin(async move {
200            adapter.ensure_authenticated(&remote).await?;
201
202            call(adapter, remote).await
203        })
204    }
205
206    /// Returns one adapter implementation for `forge_kind`.
207    fn adapter_for(&self, forge_kind: ForgeKind) -> Arc<dyn ReviewRequestAdapter> {
208        match forge_kind {
209            ForgeKind::GitHub => Arc::new(GitHubReviewRequestAdapter::new(Arc::clone(
210                &self.command_runner,
211            ))),
212            ForgeKind::GitLab => Arc::new(GitLabReviewRequestAdapter::new(Arc::clone(
213                &self.command_runner,
214            ))),
215        }
216    }
217}
218
219impl Default for RealReviewRequestClient {
220    fn default() -> Self {
221        Self::new(Arc::new(RealForgeCommandRunner))
222    }
223}
224
225impl ReviewRequestClient for RealReviewRequestClient {
226    fn detect_remote(&self, repo_url: String) -> Result<ForgeRemote, ReviewRequestError> {
227        detect_remote(&repo_url)
228    }
229
230    fn find_by_source_branch(
231        &self,
232        remote: ForgeRemote,
233        source_branch: String,
234    ) -> ForgeFuture<Result<Option<ReviewRequestSummary>, ReviewRequestError>> {
235        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
236            adapter.find_authenticated_by_source_branch(remote, source_branch)
237        })
238    }
239
240    fn create_review_request(
241        &self,
242        remote: ForgeRemote,
243        input: CreateReviewRequestInput,
244    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>> {
245        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
246            adapter.create_authenticated_review_request(remote, input)
247        })
248    }
249
250    fn refresh_review_request(
251        &self,
252        remote: ForgeRemote,
253        display_id: String,
254    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>> {
255        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
256            adapter.refresh_authenticated_review_request(remote, display_id)
257        })
258    }
259
260    fn review_request_metadata(
261        &self,
262        remote: ForgeRemote,
263        display_id: String,
264    ) -> ForgeFuture<Result<ReviewRequestMetadata, ReviewRequestError>> {
265        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
266            adapter.authenticated_review_request_metadata(remote, display_id)
267        })
268    }
269
270    fn sync_review_request_metadata(
271        &self,
272        remote: ForgeRemote,
273        display_id: String,
274        input: UpdateReviewRequestInput,
275    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>> {
276        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
277            adapter.sync_authenticated_review_request_metadata(remote, display_id, input)
278        })
279    }
280
281    fn review_request_web_url(
282        &self,
283        review_request: &ReviewRequestSummary,
284    ) -> Result<String, ReviewRequestError> {
285        if review_request.web_url.trim().is_empty() {
286            return Err(ReviewRequestError::OperationFailed {
287                forge_kind: review_request.forge_kind,
288                message: "review request summary is missing a web URL".to_string(),
289            });
290        }
291
292        Ok(review_request.web_url.clone())
293    }
294
295    fn fetch_review_comment_snapshot(
296        &self,
297        remote: ForgeRemote,
298        display_id: String,
299    ) -> ForgeFuture<Result<ReviewCommentSnapshot, ReviewRequestError>> {
300        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
301            adapter.fetch_authenticated_review_comment_snapshot(remote, display_id)
302        })
303    }
304
305    fn fetch_review_request_attention(
306        &self,
307        remote: ForgeRemote,
308        display_id: String,
309        trusted_bots: Vec<String>,
310    ) -> ForgeFuture<Result<ReviewRequestAttention, ReviewRequestError>> {
311        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
312            adapter.fetch_authenticated_review_request_attention(remote, display_id, trusted_bots)
313        })
314    }
315
316    fn rerun_failed_checks(
317        &self,
318        remote: ForgeRemote,
319        rerun_ids: Vec<String>,
320    ) -> ForgeFuture<Result<(), ReviewRequestError>> {
321        let mut distinct_rerun_ids = Vec::with_capacity(rerun_ids.len());
322        for rerun_id in rerun_ids {
323            if !distinct_rerun_ids.contains(&rerun_id) {
324                distinct_rerun_ids.push(rerun_id);
325            }
326        }
327
328        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
329            adapter.rerun_authenticated_failed_checks(remote, distinct_rerun_ids)
330        })
331    }
332
333    fn reply_to_thread(
334        &self,
335        remote: ForgeRemote,
336        display_id: String,
337        thread_id: String,
338        body: String,
339    ) -> ForgeFuture<Result<(), ReviewRequestError>> {
340        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
341            adapter.reply_to_authenticated_thread(remote, display_id, thread_id, body)
342        })
343    }
344
345    fn resolve_thread(
346        &self,
347        remote: ForgeRemote,
348        display_id: String,
349        thread_id: String,
350    ) -> ForgeFuture<Result<(), ReviewRequestError>> {
351        self.call_with_authenticated_adapter(remote, move |adapter, remote| {
352            adapter.resolve_authenticated_thread(remote, display_id, thread_id)
353        })
354    }
355}
356
357/// Provider-specific operation boundary used after client-level authentication.
358///
359/// The production client selects one implementation, calls
360/// [`ReviewRequestAdapter::ensure_authenticated`] once, and then invokes the
361/// requested operation without provider-specific dispatch in each public
362/// method.
363pub(crate) trait ReviewRequestAdapter: Send + Sync {
364    /// Verifies that CLI authentication succeeds for `remote`.
365    ///
366    /// # Errors
367    /// Returns a provider-specific review-request error when the forge CLI is
368    /// unavailable, unauthenticated, or cannot resolve the target host.
369    fn ensure_authenticated(
370        &self,
371        remote: &ForgeRemote,
372    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
373
374    /// Finds one review request after the production client has authenticated.
375    fn find_authenticated_by_source_branch(
376        &self,
377        remote: ForgeRemote,
378        source_branch: String,
379    ) -> ForgeFuture<Result<Option<ReviewRequestSummary>, ReviewRequestError>>;
380
381    /// Creates one review request after the production client has
382    /// authenticated.
383    fn create_authenticated_review_request(
384        &self,
385        remote: ForgeRemote,
386        input: CreateReviewRequestInput,
387    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
388
389    /// Refreshes one existing review request after authentication.
390    fn refresh_authenticated_review_request(
391        &self,
392        remote: ForgeRemote,
393        display_id: String,
394    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
395
396    /// Loads current review-request metadata after authentication.
397    fn authenticated_review_request_metadata(
398        &self,
399        remote: ForgeRemote,
400        display_id: String,
401    ) -> ForgeFuture<Result<ReviewRequestMetadata, ReviewRequestError>>;
402
403    /// Synchronizes review-request metadata after authentication.
404    fn sync_authenticated_review_request_metadata(
405        &self,
406        remote: ForgeRemote,
407        display_id: String,
408        input: UpdateReviewRequestInput,
409    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
410
411    /// Fetches a review-comment snapshot after authentication.
412    fn fetch_authenticated_review_comment_snapshot(
413        &self,
414        remote: ForgeRemote,
415        display_id: String,
416    ) -> ForgeFuture<Result<ReviewCommentSnapshot, ReviewRequestError>>;
417
418    /// Fetches review-request attention facts after authentication, trusting
419    /// the review bots named by `trusted_bots`.
420    fn fetch_authenticated_review_request_attention(
421        &self,
422        remote: ForgeRemote,
423        display_id: String,
424        trusted_bots: Vec<String>,
425    ) -> ForgeFuture<Result<ReviewRequestAttention, ReviewRequestError>>;
426
427    /// Reruns the failed jobs of each distinct workflow run or pipeline in
428    /// `rerun_ids` after authentication.
429    fn rerun_authenticated_failed_checks(
430        &self,
431        remote: ForgeRemote,
432        rerun_ids: Vec<String>,
433    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
434
435    /// Adds one reply after authentication.
436    fn reply_to_authenticated_thread(
437        &self,
438        remote: ForgeRemote,
439        display_id: String,
440        thread_id: String,
441        body: String,
442    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
443
444    /// Resolves one review thread after authentication.
445    fn resolve_authenticated_thread(
446        &self,
447        remote: ForgeRemote,
448        display_id: String,
449        thread_id: String,
450    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
451}
452
453#[cfg(test)]
454#[path = "client_test.rs"]
455mod tests;