1use std::collections::HashMap;
5use std::collections::HashSet;
6use std::error;
7use std::fmt;
8use std::fmt::Display;
9use std::fmt::Formatter;
10use std::future::Future;
11use std::sync::Arc;
12use std::sync::LazyLock;
13use std::sync::Mutex;
14use std::sync::PoisonError;
15
16use async_trait::async_trait;
17use serde::{Deserialize, Serialize};
18use tokio::time;
19
20use super::github::GitHubBackend;
21use super::{
22 BlockedByFetch, Conversation, ExternalBackend, ExternalId, ExternalTask, Mention, MergeState,
23 PullRequestCompletion, Status, TaskReader, TaskWriter, Tracker,
24};
25use crate::github::http::GhHttp;
26use crate::security;
27use crate::store::TaskStore;
28use crate::store::cluster::MAJORITY_TIMEOUT;
29
30pub const PREFIX: &str = "outbox:";
32
33static IN_FLIGHT: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);
35
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
38pub struct Entry {
39 pub repo: String,
40 #[serde(flatten)]
41 pub op: Op,
42}
43
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45#[serde(tag = "op", rename_all = "snake_case")]
46pub enum Op {
47 Status {
48 issue: String,
49 status: Status,
50 },
51 AddLabels {
52 issue: String,
53 labels: Vec<String>,
54 },
55 RemoveLabel {
56 issue: String,
57 label: String,
58 },
59 Comment {
61 issue: String,
62 body: String,
63 marker: String,
64 },
65 Merge {
67 pr: u64,
68 head_sha: String,
69 delete_branch: bool,
70 },
71}
72
73#[derive(Debug)]
76pub struct Fenced(pub String);
77
78impl Display for Fenced {
79 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
80 write!(f, "not sent to GitHub: {}", self.0)
81 }
82}
83
84impl error::Error for Fenced {}
85
86#[async_trait]
88pub trait Targets: Send + Sync {
89 fn backend(&self, repo: &str) -> anyhow::Result<Arc<dyn ExternalBackend>>;
90
91 async fn merge(
92 &self,
93 repo: &str,
94 pr: u64,
95 delete_branch: bool,
96 head_sha: &str,
97 ) -> anyhow::Result<()>;
98
99 async fn comment_bodies(&self, repo: &str, issue: u64) -> anyhow::Result<Vec<String>>;
101}
102
103#[derive(Debug)]
104pub struct GitHub;
105
106#[async_trait]
107impl Targets for GitHub {
108 fn backend(&self, repo: &str) -> anyhow::Result<Arc<dyn ExternalBackend>> {
109 Ok(Arc::new(GitHubBackend::new(repo.to_string())?))
110 }
111
112 async fn merge(
113 &self,
114 repo: &str,
115 pr: u64,
116 delete_branch: bool,
117 head_sha: &str,
118 ) -> anyhow::Result<()> {
119 GhHttp::new()?
120 .merge_pr(repo, pr, delete_branch, head_sha)
121 .await
122 }
123
124 async fn comment_bodies(&self, repo: &str, issue: u64) -> anyhow::Result<Vec<String>> {
125 let comments = GhHttp::new()?.get_issue_comments(repo, issue).await?;
126 Ok(comments.into_iter().map(|c| c.body).collect())
127 }
128}
129
130struct Claim(String);
132
133impl Claim {
134 fn take(key: &str) -> Option<Self> {
135 let mut keys = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
136 keys.insert(key.to_string()).then(|| Claim(key.to_string()))
137 }
138}
139
140impl Drop for Claim {
141 fn drop(&mut self) {
142 IN_FLIGHT
143 .lock()
144 .unwrap_or_else(PoisonError::into_inner)
145 .remove(&self.0);
146 }
147}
148
149fn new_key() -> String {
151 let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
152 let id = uuid::Uuid::new_v4().simple().to_string();
153 format!("{PREFIX}{nanos:020}-{}", &id[..8])
154}
155
156fn marker(key: &str) -> String {
157 format!("<!-- orch-outbox:{} -->", key.trim_start_matches(PREFIX))
158}
159
160async fn record(store: &TaskStore, key: &str, entry: &Entry) -> anyhow::Result<()> {
161 let value = serde_json::to_string(entry)?;
162 time::timeout(MAJORITY_TIMEOUT, store.kv_set(key, &value))
164 .await
165 .map_err(|_| anyhow::anyhow!("no majority committed the outbox row"))?
166}
167
168async fn supersede(store: &TaskStore, key: &str, entry: &Entry) {
171 let Op::Status { issue, .. } = &entry.op else {
172 return;
173 };
174 let rows = match store.kv_list_prefix(PREFIX).await {
175 Ok(rows) => rows,
176 Err(e) => {
177 tracing::warn!(key, err = %e, "outbox: failed to list older status rows");
178 return;
179 }
180 };
181 for (older, value) in rows {
182 if older.as_str() >= key {
183 continue;
184 }
185
186 let Ok(row) = serde_json::from_str::<Entry>(&value) else {
187 continue;
188 };
189 if row.repo == entry.repo && matches!(&row.op, Op::Status { issue: i, .. } if i == issue) {
190 remove(store, &older).await;
191 }
192 }
193}
194
195async fn remove(store: &TaskStore, key: &str) {
196 match time::timeout(MAJORITY_TIMEOUT, store.kv_delete(key)).await {
197 Ok(Ok(())) => {}
198 Ok(Err(e)) => tracing::warn!(key, err = %e, "outbox: failed to remove a sent row"),
199 Err(_) => tracing::warn!(key, "outbox: no majority to remove a sent row"),
200 }
201}
202
203pub async fn send(
206 store: &TaskStore,
207 key: &str,
208 entry: Entry,
209 run: impl Future<Output = anyhow::Result<()>>,
210) -> anyhow::Result<()> {
211 let Some(node) = store.node() else {
212 return run.await;
213 };
214 if !node.is_leader() {
215 if matches!(entry.op, Op::Merge { .. }) {
216 return Err(Fenced("only the leader merges".into()).into());
217 }
218
219 if let Err(e) = record(store, key, &entry).await {
221 return Err(Fenced(format!("{e:#}")).into());
222 }
223
224 supersede(store, key, &entry).await;
225 return Ok(());
226 }
227
228 let _claim = Claim::take(key);
229 if let Err(e) = record(store, key, &entry).await {
230 return Err(Fenced(format!("{e:#}")).into());
231 }
232
233 supersede(store, key, &entry).await;
234
235 if let Err(e) = node.ensure_majority().await {
236 tracing::warn!(key, err = %e, "outbox: leaving the write for the next leader");
237 return Err(Fenced(format!("{e:#}")).into());
238 }
239
240 let result = run.await;
241 remove(store, key).await;
242 result
243}
244
245pub async fn merge(
247 store: &TaskStore,
248 gh: &GhHttp,
249 repo: &str,
250 pr: u64,
251 delete_branch: bool,
252 head_sha: &str,
253) -> anyhow::Result<()> {
254 let entry = Entry {
255 repo: repo.to_string(),
256 op: Op::Merge {
257 pr,
258 head_sha: head_sha.to_string(),
259 delete_branch,
260 },
261 };
262 send(
263 store,
264 &new_key(),
265 entry,
266 Box::pin(gh.merge_pr(repo, pr, delete_branch, head_sha)),
267 )
268 .await
269}
270
271pub async fn retry_pending(store: &TaskStore, targets: &dyn Targets) -> anyhow::Result<usize> {
274 let Some(node) = store.node() else {
275 return Ok(0);
276 };
277 if !node.is_leader() {
278 return Ok(0);
279 }
280
281 let mut rows: Vec<(String, Entry)> = Vec::new();
282 for (key, value) in store.kv_list_prefix(PREFIX).await? {
283 match serde_json::from_str(&value) {
284 Ok(entry) => rows.push((key, entry)),
285 Err(e) => {
286 tracing::warn!(key, err = %e, "outbox: dropping a row this version cannot read");
287 remove(store, &key).await;
288 }
289 }
290 }
291 if rows.is_empty() {
292 return Ok(0);
293 }
294
295 rows.sort_by(|a, b| a.0.cmp(&b.0));
296 node.ensure_majority()
297 .await
298 .map_err(|e| Fenced(format!("{e:#}")))?;
299 let latest_status: HashMap<(&str, &str), &str> = rows
300 .iter()
301 .filter_map(|(key, e)| match &e.op {
302 Op::Status { issue, .. } => Some(((e.repo.as_str(), issue.as_str()), key.as_str())),
303 _ => None,
304 })
305 .collect();
306 let mut sent = 0;
307 for (key, entry) in &rows {
308 let Some(_claim) = Claim::take(key) else {
309 continue;
310 };
311 if store.kv_get(key).await?.is_none() {
313 continue;
314 }
315
316 let superseded = match &entry.op {
317 Op::Status { issue, .. } => {
318 latest_status.get(&(entry.repo.as_str(), issue.as_str())) != Some(&key.as_str())
319 }
320 _ => false,
321 };
322 if !superseded {
323 match retry(entry, targets).await {
324 Ok(()) => sent += 1,
325 Err(e) => {
326 tracing::warn!(key, repo = %entry.repo, err = %e, "outbox: retry failed, dropping it");
327 }
328 }
329 }
330
331 remove(store, key).await;
332 }
333
334 Ok(sent)
335}
336
337async fn retry(entry: &Entry, targets: &dyn Targets) -> anyhow::Result<()> {
340 let id = |issue: &str| ExternalId(issue.to_string());
341 match &entry.op {
342 Op::Status { issue, status } => {
343 targets
344 .backend(&entry.repo)?
345 .update_status(&id(issue), *status)
346 .await
347 }
348 Op::AddLabels { issue, labels } => {
349 targets
350 .backend(&entry.repo)?
351 .set_labels(&id(issue), labels)
352 .await
353 }
354 Op::RemoveLabel { issue, label } => {
355 targets
356 .backend(&entry.repo)?
357 .remove_label(&id(issue), label)
358 .await
359 }
360 Op::Comment {
361 issue,
362 body,
363 marker,
364 } => {
365 let number: u64 = issue.parse()?;
366 let posted = targets.comment_bodies(&entry.repo, number).await?;
367 if posted.iter().any(|b| b.contains(marker.as_str())) {
368 return Ok(());
369 }
370
371 targets
372 .backend(&entry.repo)?
373 .post_comment(&id(issue), body)
374 .await
375 }
376 Op::Merge {
377 pr,
378 head_sha,
379 delete_branch,
380 } => {
381 targets
382 .merge(&entry.repo, *pr, *delete_branch, head_sha)
383 .await
384 }
385 }
386}
387
388pub fn wrap(
390 backend: Arc<dyn ExternalBackend>,
391 store: &TaskStore,
392 repo: &str,
393) -> Arc<dyn ExternalBackend> {
394 if store.node().is_none() {
395 return backend;
396 }
397
398 Arc::new(Outboxed {
399 inner: backend,
400 store: store.clone(),
401 repo: repo.to_string(),
402 })
403}
404
405struct Outboxed {
408 inner: Arc<dyn ExternalBackend>,
409 store: TaskStore,
410 repo: String,
411}
412
413fn entry(repo: &str, op: Op) -> Entry {
414 Entry {
415 repo: repo.to_string(),
416 op,
417 }
418}
419
420fn is_issue(id: &ExternalId) -> bool {
422 id.0.parse::<u64>().is_ok()
423}
424
425impl Outboxed {
426 async fn fence(&self) -> anyhow::Result<()> {
427 match self.store.node() {
428 Some(node) if node.is_leader() => node
429 .ensure_majority()
430 .await
431 .map_err(|e| Fenced(format!("{e:#}")).into()),
432 Some(node) if !node.has_leader() => {
433 Err(Fenced("this node knows no leader".into()).into())
434 }
435 _ => Ok(()),
436 }
437 }
438
439 async fn comment(&self, repo: &str, id: &ExternalId, body: &str) -> anyhow::Result<()> {
440 if !is_issue(id) {
441 return self.inner.post_comment_in_repo(repo, id, body).await;
442 }
443
444 let key = new_key();
445 let marker = marker(&key);
446 let body = format!("{}\n\n{marker}", security::redact_posted_body(body));
448 let op = Op::Comment {
449 issue: id.0.clone(),
450 body: body.clone(),
451 marker,
452 };
453 let run = async {
454 if repo == self.repo {
455 self.inner.post_comment(id, &body).await
456 } else {
457 self.inner.post_comment_in_repo(repo, id, &body).await
458 }
459 };
460 send(&self.store, &key, entry(repo, op), run).await
461 }
462}
463
464#[async_trait]
465impl TaskReader for Outboxed {
466 async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
467 self.inner.get_task(id).await
468 }
469
470 async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
471 self.inner.list_by_status(status).await
472 }
473
474 async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
475 self.inner.list_all_tasks().await
476 }
477
478 async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
479 self.inner.list_reconciliation_candidates().await
480 }
481
482 async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
483 self.inner.list_routable().await
484 }
485
486 async fn list_active_open_issues(&self) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
487 self.inner.list_active_open_issues().await
488 }
489
490 async fn get_active_open_issue(
491 &self,
492 id: &ExternalId,
493 ) -> anyhow::Result<Option<(ExternalTask, Option<Status>)>> {
494 self.inner.get_active_open_issue(id).await
495 }
496
497 async fn has_open_issue_with_title(&self, title: &str, label: &str) -> anyhow::Result<bool> {
498 self.inner.has_open_issue_with_title(title, label).await
499 }
500}
501
502#[async_trait]
503impl TaskWriter for Outboxed {
504 async fn create_task(
507 &self,
508 title: &str,
509 body: &str,
510 labels: &[String],
511 ) -> anyhow::Result<ExternalId> {
512 self.fence().await?;
513 self.inner.create_task(title, body, labels).await
514 }
515
516 async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
517 if !is_issue(id) {
518 return self.inner.update_status(id, status).await;
519 }
520
521 let op = Op::Status {
522 issue: id.0.clone(),
523 status,
524 };
525 let run = self.inner.update_status(id, status);
526 send(&self.store, &new_key(), entry(&self.repo, op), run).await
527 }
528
529 async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
530 if !is_issue(id) {
531 return self.inner.set_labels(id, labels).await;
532 }
533
534 let op = Op::AddLabels {
535 issue: id.0.clone(),
536 labels: labels.to_vec(),
537 };
538 let run = self.inner.set_labels(id, labels);
539 send(&self.store, &new_key(), entry(&self.repo, op), run).await
540 }
541
542 async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()> {
543 if !is_issue(id) {
544 return self.inner.remove_label(id, label).await;
545 }
546
547 let op = Op::RemoveLabel {
548 issue: id.0.clone(),
549 label: label.to_string(),
550 };
551 let run = self.inner.remove_label(id, label);
552 send(&self.store, &new_key(), entry(&self.repo, op), run).await
553 }
554
555 async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
556 self.inner.get_sub_issues(id).await
557 }
558
559 async fn create_sub_task(
560 &self,
561 parent_id: &ExternalId,
562 title: &str,
563 body: &str,
564 labels: &[String],
565 ) -> anyhow::Result<ExternalId> {
566 self.fence().await?;
567 self.inner
568 .create_sub_task(parent_id, title, body, labels)
569 .await
570 }
571
572 async fn ensure_status_label(&self, label: &str) -> anyhow::Result<()> {
573 self.fence().await?;
574 self.inner.ensure_status_label(label).await
575 }
576}
577
578#[async_trait]
579impl Conversation for Outboxed {
580 async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
581 self.comment(&self.repo, id, body).await
582 }
583
584 async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
585 self.inner.get_authenticated_user().await
586 }
587
588 async fn get_mentions(&self, since: &str) -> anyhow::Result<Vec<Mention>> {
589 self.inner.get_mentions(since).await
590 }
591
592 async fn list_issue_comments(&self, id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
593 self.inner.list_issue_comments(id).await
594 }
595
596 async fn acknowledge_issue(&self, id: &ExternalId) -> anyhow::Result<()> {
597 self.fence().await?;
598 self.inner.acknowledge_issue(id).await
599 }
600
601 async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
602 self.fence().await?;
603 self.inner.acknowledge_mention(comment_id).await
604 }
605
606 async fn post_comment_in_repo(
607 &self,
608 repo: &str,
609 id: &ExternalId,
610 body: &str,
611 ) -> anyhow::Result<()> {
612 self.comment(repo, id, body).await
613 }
614}
615
616#[async_trait]
617impl MergeState for Outboxed {
618 async fn is_pr_merged(&self, branch: &str) -> anyhow::Result<bool> {
619 self.inner.is_pr_merged(branch).await
620 }
621
622 async fn batch_is_pr_merged(
623 &self,
624 branches: &[String],
625 ) -> anyhow::Result<HashMap<String, bool>> {
626 self.inner.batch_is_pr_merged(branches).await
627 }
628
629 async fn blocked_by(&self, repo: &str, issue_number: i64) -> anyhow::Result<BlockedByFetch> {
630 self.inner.blocked_by(repo, issue_number).await
631 }
632
633 async fn issue_close_state(
634 &self,
635 repo: &str,
636 issue_number: i64,
637 ) -> anyhow::Result<Option<(String, Option<String>)>> {
638 self.inner.issue_close_state(repo, issue_number).await
639 }
640
641 async fn pull_request_completion(
642 &self,
643 repo: &str,
644 pr_number: i64,
645 ) -> anyhow::Result<Option<PullRequestCompletion>> {
646 self.inner.pull_request_completion(repo, pr_number).await
647 }
648
649 async fn add_dependency(
650 &self,
651 issue_number: i64,
652 blocking_repo: &str,
653 blocking_number: i64,
654 ) -> anyhow::Result<()> {
655 self.fence().await?;
656 self.inner
657 .add_dependency(issue_number, blocking_repo, blocking_number)
658 .await
659 }
660}
661
662#[async_trait]
663impl Tracker for Outboxed {
664 fn name(&self) -> &str {
665 self.inner.name()
666 }
667
668 async fn sync_to_project(
669 &self,
670 id: &ExternalId,
671 status: Status,
672 ) -> anyhow::Result<Option<String>> {
673 self.fence().await?;
674 self.inner.sync_to_project(id, status).await
675 }
676
677 async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
678 self.fence().await?;
679 self.inner.reconcile_project_statuses().await
680 }
681
682 async fn sync_estimate_to_project(&self, id: &ExternalId, estimate: u8) -> anyhow::Result<()> {
683 self.fence().await?;
684 self.inner.sync_estimate_to_project(id, estimate).await
685 }
686
687 async fn get_project_item_estimates(
688 &self,
689 issue_node_ids: &[String],
690 ) -> anyhow::Result<HashMap<String, u8>> {
691 self.inner.get_project_item_estimates(issue_node_ids).await
692 }
693
694 async fn health_check(&self) -> anyhow::Result<()> {
695 self.inner.health_check().await
696 }
697}
698
699#[cfg(test)]
700mod tests;