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 has_open_issue_with_title(&self, title: &str, label: &str) -> anyhow::Result<bool> {
487 self.inner.has_open_issue_with_title(title, label).await
488 }
489}
490
491#[async_trait]
492impl TaskWriter for Outboxed {
493 async fn create_task(
496 &self,
497 title: &str,
498 body: &str,
499 labels: &[String],
500 ) -> anyhow::Result<ExternalId> {
501 self.fence().await?;
502 self.inner.create_task(title, body, labels).await
503 }
504
505 async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
506 if !is_issue(id) {
507 return self.inner.update_status(id, status).await;
508 }
509
510 let op = Op::Status {
511 issue: id.0.clone(),
512 status,
513 };
514 let run = self.inner.update_status(id, status);
515 send(&self.store, &new_key(), entry(&self.repo, op), run).await
516 }
517
518 async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
519 if !is_issue(id) {
520 return self.inner.set_labels(id, labels).await;
521 }
522
523 let op = Op::AddLabels {
524 issue: id.0.clone(),
525 labels: labels.to_vec(),
526 };
527 let run = self.inner.set_labels(id, labels);
528 send(&self.store, &new_key(), entry(&self.repo, op), run).await
529 }
530
531 async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()> {
532 if !is_issue(id) {
533 return self.inner.remove_label(id, label).await;
534 }
535
536 let op = Op::RemoveLabel {
537 issue: id.0.clone(),
538 label: label.to_string(),
539 };
540 let run = self.inner.remove_label(id, label);
541 send(&self.store, &new_key(), entry(&self.repo, op), run).await
542 }
543
544 async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
545 self.inner.get_sub_issues(id).await
546 }
547
548 async fn create_sub_task(
549 &self,
550 parent_id: &ExternalId,
551 title: &str,
552 body: &str,
553 labels: &[String],
554 ) -> anyhow::Result<ExternalId> {
555 self.fence().await?;
556 self.inner
557 .create_sub_task(parent_id, title, body, labels)
558 .await
559 }
560
561 async fn ensure_status_label(&self, label: &str) -> anyhow::Result<()> {
562 self.fence().await?;
563 self.inner.ensure_status_label(label).await
564 }
565}
566
567#[async_trait]
568impl Conversation for Outboxed {
569 async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
570 self.comment(&self.repo, id, body).await
571 }
572
573 async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
574 self.inner.get_authenticated_user().await
575 }
576
577 async fn get_mentions(&self, since: &str) -> anyhow::Result<Vec<Mention>> {
578 self.inner.get_mentions(since).await
579 }
580
581 async fn list_issue_comments(&self, id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
582 self.inner.list_issue_comments(id).await
583 }
584
585 async fn acknowledge_issue(&self, id: &ExternalId) -> anyhow::Result<()> {
586 self.fence().await?;
587 self.inner.acknowledge_issue(id).await
588 }
589
590 async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
591 self.fence().await?;
592 self.inner.acknowledge_mention(comment_id).await
593 }
594
595 async fn post_comment_in_repo(
596 &self,
597 repo: &str,
598 id: &ExternalId,
599 body: &str,
600 ) -> anyhow::Result<()> {
601 self.comment(repo, id, body).await
602 }
603}
604
605#[async_trait]
606impl MergeState for Outboxed {
607 async fn is_pr_merged(&self, branch: &str) -> anyhow::Result<bool> {
608 self.inner.is_pr_merged(branch).await
609 }
610
611 async fn batch_is_pr_merged(
612 &self,
613 branches: &[String],
614 ) -> anyhow::Result<HashMap<String, bool>> {
615 self.inner.batch_is_pr_merged(branches).await
616 }
617
618 async fn blocked_by(&self, repo: &str, issue_number: i64) -> anyhow::Result<BlockedByFetch> {
619 self.inner.blocked_by(repo, issue_number).await
620 }
621
622 async fn issue_close_state(
623 &self,
624 repo: &str,
625 issue_number: i64,
626 ) -> anyhow::Result<Option<(String, Option<String>)>> {
627 self.inner.issue_close_state(repo, issue_number).await
628 }
629
630 async fn pull_request_completion(
631 &self,
632 repo: &str,
633 pr_number: i64,
634 ) -> anyhow::Result<Option<PullRequestCompletion>> {
635 self.inner.pull_request_completion(repo, pr_number).await
636 }
637
638 async fn add_dependency(
639 &self,
640 issue_number: i64,
641 blocking_repo: &str,
642 blocking_number: i64,
643 ) -> anyhow::Result<()> {
644 self.fence().await?;
645 self.inner
646 .add_dependency(issue_number, blocking_repo, blocking_number)
647 .await
648 }
649}
650
651#[async_trait]
652impl Tracker for Outboxed {
653 fn name(&self) -> &str {
654 self.inner.name()
655 }
656
657 async fn sync_to_project(
658 &self,
659 id: &ExternalId,
660 status: Status,
661 ) -> anyhow::Result<Option<String>> {
662 self.fence().await?;
663 self.inner.sync_to_project(id, status).await
664 }
665
666 async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
667 self.fence().await?;
668 self.inner.reconcile_project_statuses().await
669 }
670
671 async fn sync_estimate_to_project(&self, id: &ExternalId, estimate: u8) -> anyhow::Result<()> {
672 self.fence().await?;
673 self.inner.sync_estimate_to_project(id, estimate).await
674 }
675
676 async fn get_project_item_estimates(
677 &self,
678 issue_node_ids: &[String],
679 ) -> anyhow::Result<HashMap<String, u8>> {
680 self.inner.get_project_item_estimates(issue_node_ids).await
681 }
682
683 async fn health_check(&self) -> anyhow::Result<()> {
684 self.inner.health_check().await
685 }
686}
687
688#[cfg(test)]
689mod tests;