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 record(store, key, &entry).await?;
220 supersede(store, key, &entry).await;
221 return Ok(());
222 }
223
224 let _claim = Claim::take(key);
225 if let Err(e) = record(store, key, &entry).await {
226 return Err(Fenced(format!("{e:#}")).into());
227 }
228
229 supersede(store, key, &entry).await;
230
231 if let Err(e) = node.ensure_majority().await {
232 tracing::warn!(key, err = %e, "outbox: leaving the write for the next leader");
233 return Err(Fenced(format!("{e:#}")).into());
234 }
235
236 let result = run.await;
237 remove(store, key).await;
238 result
239}
240
241pub async fn merge(
243 store: &TaskStore,
244 gh: &GhHttp,
245 repo: &str,
246 pr: u64,
247 delete_branch: bool,
248 head_sha: &str,
249) -> anyhow::Result<()> {
250 let entry = Entry {
251 repo: repo.to_string(),
252 op: Op::Merge {
253 pr,
254 head_sha: head_sha.to_string(),
255 delete_branch,
256 },
257 };
258 send(
259 store,
260 &new_key(),
261 entry,
262 Box::pin(gh.merge_pr(repo, pr, delete_branch, head_sha)),
263 )
264 .await
265}
266
267pub async fn retry_pending(store: &TaskStore, targets: &dyn Targets) -> anyhow::Result<usize> {
270 let Some(node) = store.node() else {
271 return Ok(0);
272 };
273 if !node.is_leader() {
274 return Ok(0);
275 }
276
277 let mut rows: Vec<(String, Entry)> = Vec::new();
278 for (key, value) in store.kv_list_prefix(PREFIX).await? {
279 match serde_json::from_str(&value) {
280 Ok(entry) => rows.push((key, entry)),
281 Err(e) => {
282 tracing::warn!(key, err = %e, "outbox: dropping a row this version cannot read");
283 remove(store, &key).await;
284 }
285 }
286 }
287 if rows.is_empty() {
288 return Ok(0);
289 }
290
291 rows.sort_by(|a, b| a.0.cmp(&b.0));
292 node.ensure_majority()
293 .await
294 .map_err(|e| Fenced(format!("{e:#}")))?;
295 let latest_status: HashMap<(&str, &str), &str> = rows
296 .iter()
297 .filter_map(|(key, e)| match &e.op {
298 Op::Status { issue, .. } => Some(((e.repo.as_str(), issue.as_str()), key.as_str())),
299 _ => None,
300 })
301 .collect();
302 let mut sent = 0;
303 for (key, entry) in &rows {
304 let Some(_claim) = Claim::take(key) else {
305 continue;
306 };
307 if store.kv_get(key).await?.is_none() {
309 continue;
310 }
311
312 let superseded = match &entry.op {
313 Op::Status { issue, .. } => {
314 latest_status.get(&(entry.repo.as_str(), issue.as_str())) != Some(&key.as_str())
315 }
316 _ => false,
317 };
318 if !superseded {
319 match retry(entry, targets).await {
320 Ok(()) => sent += 1,
321 Err(e) => {
322 tracing::warn!(key, repo = %entry.repo, err = %e, "outbox: retry failed, dropping it");
323 }
324 }
325 }
326
327 remove(store, key).await;
328 }
329
330 Ok(sent)
331}
332
333async fn retry(entry: &Entry, targets: &dyn Targets) -> anyhow::Result<()> {
336 let id = |issue: &str| ExternalId(issue.to_string());
337 match &entry.op {
338 Op::Status { issue, status } => {
339 targets
340 .backend(&entry.repo)?
341 .update_status(&id(issue), *status)
342 .await
343 }
344 Op::AddLabels { issue, labels } => {
345 targets
346 .backend(&entry.repo)?
347 .set_labels(&id(issue), labels)
348 .await
349 }
350 Op::RemoveLabel { issue, label } => {
351 targets
352 .backend(&entry.repo)?
353 .remove_label(&id(issue), label)
354 .await
355 }
356 Op::Comment {
357 issue,
358 body,
359 marker,
360 } => {
361 let number: u64 = issue.parse()?;
362 let posted = targets.comment_bodies(&entry.repo, number).await?;
363 if posted.iter().any(|b| b.contains(marker.as_str())) {
364 return Ok(());
365 }
366
367 targets
368 .backend(&entry.repo)?
369 .post_comment(&id(issue), body)
370 .await
371 }
372 Op::Merge {
373 pr,
374 head_sha,
375 delete_branch,
376 } => {
377 targets
378 .merge(&entry.repo, *pr, *delete_branch, head_sha)
379 .await
380 }
381 }
382}
383
384pub fn wrap(
386 backend: Arc<dyn ExternalBackend>,
387 store: &TaskStore,
388 repo: &str,
389) -> Arc<dyn ExternalBackend> {
390 if store.node().is_none() {
391 return backend;
392 }
393
394 Arc::new(Outboxed {
395 inner: backend,
396 store: store.clone(),
397 repo: repo.to_string(),
398 })
399}
400
401struct Outboxed {
404 inner: Arc<dyn ExternalBackend>,
405 store: TaskStore,
406 repo: String,
407}
408
409fn entry(repo: &str, op: Op) -> Entry {
410 Entry {
411 repo: repo.to_string(),
412 op,
413 }
414}
415
416fn is_issue(id: &ExternalId) -> bool {
418 id.0.parse::<u64>().is_ok()
419}
420
421impl Outboxed {
422 async fn fence(&self) -> anyhow::Result<()> {
423 match self.store.node() {
424 Some(node) if node.is_leader() => node
425 .ensure_majority()
426 .await
427 .map_err(|e| Fenced(format!("{e:#}")).into()),
428 Some(node) if !node.has_leader() => {
429 Err(Fenced("this node knows no leader".into()).into())
430 }
431 _ => Ok(()),
432 }
433 }
434
435 async fn comment(&self, repo: &str, id: &ExternalId, body: &str) -> anyhow::Result<()> {
436 if !is_issue(id) {
437 return self.inner.post_comment_in_repo(repo, id, body).await;
438 }
439
440 let key = new_key();
441 let marker = marker(&key);
442 let body = format!("{}\n\n{marker}", security::redact_posted_body(body));
444 let op = Op::Comment {
445 issue: id.0.clone(),
446 body: body.clone(),
447 marker,
448 };
449 let run = async {
450 if repo == self.repo {
451 self.inner.post_comment(id, &body).await
452 } else {
453 self.inner.post_comment_in_repo(repo, id, &body).await
454 }
455 };
456 send(&self.store, &key, entry(repo, op), run).await
457 }
458}
459
460#[async_trait]
461impl TaskReader for Outboxed {
462 async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
463 self.inner.get_task(id).await
464 }
465
466 async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
467 self.inner.list_by_status(status).await
468 }
469
470 async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
471 self.inner.list_all_tasks().await
472 }
473
474 async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
475 self.inner.list_reconciliation_candidates().await
476 }
477
478 async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
479 self.inner.list_routable().await
480 }
481
482 async fn list_active_open_issues(&self) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
483 self.inner.list_active_open_issues().await
484 }
485
486 async fn get_active_open_issue(
487 &self,
488 id: &ExternalId,
489 ) -> anyhow::Result<Option<(ExternalTask, Option<Status>)>> {
490 self.inner.get_active_open_issue(id).await
491 }
492
493 async fn has_open_issue_with_title(&self, title: &str, label: &str) -> anyhow::Result<bool> {
494 self.inner.has_open_issue_with_title(title, label).await
495 }
496}
497
498#[async_trait]
499impl TaskWriter for Outboxed {
500 async fn create_task(
503 &self,
504 title: &str,
505 body: &str,
506 labels: &[String],
507 ) -> anyhow::Result<ExternalId> {
508 self.fence().await?;
509 self.inner.create_task(title, body, labels).await
510 }
511
512 async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
513 if !is_issue(id) {
514 return self.inner.update_status(id, status).await;
515 }
516
517 let op = Op::Status {
518 issue: id.0.clone(),
519 status,
520 };
521 let run = self.inner.update_status(id, status);
522 send(&self.store, &new_key(), entry(&self.repo, op), run).await
523 }
524
525 async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
526 if !is_issue(id) {
527 return self.inner.set_labels(id, labels).await;
528 }
529
530 let op = Op::AddLabels {
531 issue: id.0.clone(),
532 labels: labels.to_vec(),
533 };
534 let run = self.inner.set_labels(id, labels);
535 send(&self.store, &new_key(), entry(&self.repo, op), run).await
536 }
537
538 async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()> {
539 if !is_issue(id) {
540 return self.inner.remove_label(id, label).await;
541 }
542
543 let op = Op::RemoveLabel {
544 issue: id.0.clone(),
545 label: label.to_string(),
546 };
547 let run = self.inner.remove_label(id, label);
548 send(&self.store, &new_key(), entry(&self.repo, op), run).await
549 }
550
551 async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
552 self.inner.get_sub_issues(id).await
553 }
554
555 async fn create_sub_task(
556 &self,
557 parent_id: &ExternalId,
558 title: &str,
559 body: &str,
560 labels: &[String],
561 ) -> anyhow::Result<ExternalId> {
562 self.fence().await?;
563 self.inner
564 .create_sub_task(parent_id, title, body, labels)
565 .await
566 }
567
568 async fn ensure_status_label(&self, label: &str) -> anyhow::Result<()> {
569 self.fence().await?;
570 self.inner.ensure_status_label(label).await
571 }
572}
573
574#[async_trait]
575impl Conversation for Outboxed {
576 async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
577 self.comment(&self.repo, id, body).await
578 }
579
580 async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
581 self.inner.get_authenticated_user().await
582 }
583
584 async fn get_mentions(&self, since: &str) -> anyhow::Result<Vec<Mention>> {
585 self.inner.get_mentions(since).await
586 }
587
588 async fn list_issue_comments(&self, id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
589 self.inner.list_issue_comments(id).await
590 }
591
592 async fn acknowledge_issue(&self, id: &ExternalId) -> anyhow::Result<()> {
593 self.fence().await?;
594 self.inner.acknowledge_issue(id).await
595 }
596
597 async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
598 self.fence().await?;
599 self.inner.acknowledge_mention(comment_id).await
600 }
601
602 async fn post_comment_in_repo(
603 &self,
604 repo: &str,
605 id: &ExternalId,
606 body: &str,
607 ) -> anyhow::Result<()> {
608 self.comment(repo, id, body).await
609 }
610}
611
612#[async_trait]
613impl MergeState for Outboxed {
614 async fn is_pr_merged(&self, branch: &str) -> anyhow::Result<bool> {
615 self.inner.is_pr_merged(branch).await
616 }
617
618 async fn batch_is_pr_merged(
619 &self,
620 branches: &[String],
621 ) -> anyhow::Result<HashMap<String, bool>> {
622 self.inner.batch_is_pr_merged(branches).await
623 }
624
625 async fn blocked_by(&self, repo: &str, issue_number: i64) -> anyhow::Result<BlockedByFetch> {
626 self.inner.blocked_by(repo, issue_number).await
627 }
628
629 async fn issue_close_state(
630 &self,
631 repo: &str,
632 issue_number: i64,
633 ) -> anyhow::Result<Option<(String, Option<String>)>> {
634 self.inner.issue_close_state(repo, issue_number).await
635 }
636
637 async fn pull_request_completion(
638 &self,
639 repo: &str,
640 pr_number: i64,
641 ) -> anyhow::Result<Option<PullRequestCompletion>> {
642 self.inner.pull_request_completion(repo, pr_number).await
643 }
644
645 async fn add_dependency(
646 &self,
647 issue_number: i64,
648 blocking_repo: &str,
649 blocking_number: i64,
650 ) -> anyhow::Result<()> {
651 self.fence().await?;
652 self.inner
653 .add_dependency(issue_number, blocking_repo, blocking_number)
654 .await
655 }
656}
657
658#[async_trait]
659impl Tracker for Outboxed {
660 fn name(&self) -> &str {
661 self.inner.name()
662 }
663
664 async fn sync_to_project(
665 &self,
666 id: &ExternalId,
667 status: Status,
668 ) -> anyhow::Result<Option<String>> {
669 self.fence().await?;
670 self.inner.sync_to_project(id, status).await
671 }
672
673 async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
674 self.fence().await?;
675 self.inner.reconcile_project_statuses().await
676 }
677
678 async fn sync_estimate_to_project(&self, id: &ExternalId, estimate: u8) -> anyhow::Result<()> {
679 self.fence().await?;
680 self.inner.sync_estimate_to_project(id, estimate).await
681 }
682
683 async fn get_project_item_estimates(
684 &self,
685 issue_node_ids: &[String],
686 ) -> anyhow::Result<HashMap<String, u8>> {
687 self.inner.get_project_item_estimates(issue_node_ids).await
688 }
689
690 async fn health_check(&self) -> anyhow::Result<()> {
691 self.inner.health_check().await
692 }
693}
694
695#[cfg(test)]
696mod tests;