use std::collections::HashMap;
use std::collections::HashSet;
use std::error;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::future::Future;
use std::sync::Arc;
use std::sync::LazyLock;
use std::sync::Mutex;
use std::sync::PoisonError;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::time;
use super::github::GitHubBackend;
use super::{
BlockedByFetch, Conversation, ExternalBackend, ExternalId, ExternalTask, Mention, MergeState,
PullRequestCompletion, Status, TaskReader, TaskWriter, Tracker,
};
use crate::github::http::GhHttp;
use crate::security;
use crate::store::TaskStore;
use crate::store::cluster::MAJORITY_TIMEOUT;
pub const PREFIX: &str = "outbox:";
static IN_FLIGHT: LazyLock<Mutex<HashSet<String>>> = LazyLock::new(Mutex::default);
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Entry {
pub repo: String,
#[serde(flatten)]
pub op: Op,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Op {
Status {
issue: String,
status: Status,
},
AddLabels {
issue: String,
labels: Vec<String>,
},
RemoveLabel {
issue: String,
label: String,
},
Comment {
issue: String,
body: String,
marker: String,
},
Merge {
pr: u64,
head_sha: String,
delete_branch: bool,
},
}
#[derive(Debug)]
pub struct Fenced(pub String);
impl Display for Fenced {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "not sent to GitHub: {}", self.0)
}
}
impl error::Error for Fenced {}
#[async_trait]
pub trait Targets: Send + Sync {
fn backend(&self, repo: &str) -> anyhow::Result<Arc<dyn ExternalBackend>>;
async fn merge(
&self,
repo: &str,
pr: u64,
delete_branch: bool,
head_sha: &str,
) -> anyhow::Result<()>;
async fn comment_bodies(&self, repo: &str, issue: u64) -> anyhow::Result<Vec<String>>;
}
#[derive(Debug)]
pub struct GitHub;
#[async_trait]
impl Targets for GitHub {
fn backend(&self, repo: &str) -> anyhow::Result<Arc<dyn ExternalBackend>> {
Ok(Arc::new(GitHubBackend::new(repo.to_string())?))
}
async fn merge(
&self,
repo: &str,
pr: u64,
delete_branch: bool,
head_sha: &str,
) -> anyhow::Result<()> {
GhHttp::new()?
.merge_pr(repo, pr, delete_branch, head_sha)
.await
}
async fn comment_bodies(&self, repo: &str, issue: u64) -> anyhow::Result<Vec<String>> {
let comments = GhHttp::new()?.get_issue_comments(repo, issue).await?;
Ok(comments.into_iter().map(|c| c.body).collect())
}
}
struct Claim(String);
impl Claim {
fn take(key: &str) -> Option<Self> {
let mut keys = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
keys.insert(key.to_string()).then(|| Claim(key.to_string()))
}
}
impl Drop for Claim {
fn drop(&mut self) {
IN_FLIGHT
.lock()
.unwrap_or_else(PoisonError::into_inner)
.remove(&self.0);
}
}
fn new_key() -> String {
let nanos = chrono::Utc::now().timestamp_nanos_opt().unwrap_or_default();
let id = uuid::Uuid::new_v4().simple().to_string();
format!("{PREFIX}{nanos:020}-{}", &id[..8])
}
fn marker(key: &str) -> String {
format!("<!-- orch-outbox:{} -->", key.trim_start_matches(PREFIX))
}
async fn record(store: &TaskStore, key: &str, entry: &Entry) -> anyhow::Result<()> {
let value = serde_json::to_string(entry)?;
time::timeout(MAJORITY_TIMEOUT, store.kv_set(key, &value))
.await
.map_err(|_| anyhow::anyhow!("no majority committed the outbox row"))?
}
async fn supersede(store: &TaskStore, key: &str, entry: &Entry) {
let Op::Status { issue, .. } = &entry.op else {
return;
};
let rows = match store.kv_list_prefix(PREFIX).await {
Ok(rows) => rows,
Err(e) => {
tracing::warn!(key, err = %e, "outbox: failed to list older status rows");
return;
}
};
for (older, value) in rows {
if older.as_str() >= key {
continue;
}
let Ok(row) = serde_json::from_str::<Entry>(&value) else {
continue;
};
if row.repo == entry.repo && matches!(&row.op, Op::Status { issue: i, .. } if i == issue) {
remove(store, &older).await;
}
}
}
async fn remove(store: &TaskStore, key: &str) {
match time::timeout(MAJORITY_TIMEOUT, store.kv_delete(key)).await {
Ok(Ok(())) => {}
Ok(Err(e)) => tracing::warn!(key, err = %e, "outbox: failed to remove a sent row"),
Err(_) => tracing::warn!(key, "outbox: no majority to remove a sent row"),
}
}
pub async fn send(
store: &TaskStore,
key: &str,
entry: Entry,
run: impl Future<Output = anyhow::Result<()>>,
) -> anyhow::Result<()> {
let Some(node) = store.node() else {
return run.await;
};
if !node.is_leader() {
if matches!(entry.op, Op::Merge { .. }) {
return Err(Fenced("only the leader merges".into()).into());
}
record(store, key, &entry).await?;
supersede(store, key, &entry).await;
return Ok(());
}
let _claim = Claim::take(key);
if let Err(e) = record(store, key, &entry).await {
return Err(Fenced(format!("{e:#}")).into());
}
supersede(store, key, &entry).await;
if let Err(e) = node.ensure_majority().await {
tracing::warn!(key, err = %e, "outbox: leaving the write for the next leader");
return Err(Fenced(format!("{e:#}")).into());
}
let result = run.await;
remove(store, key).await;
result
}
pub async fn merge(
store: &TaskStore,
gh: &GhHttp,
repo: &str,
pr: u64,
delete_branch: bool,
head_sha: &str,
) -> anyhow::Result<()> {
let entry = Entry {
repo: repo.to_string(),
op: Op::Merge {
pr,
head_sha: head_sha.to_string(),
delete_branch,
},
};
send(
store,
&new_key(),
entry,
Box::pin(gh.merge_pr(repo, pr, delete_branch, head_sha)),
)
.await
}
pub async fn retry_pending(store: &TaskStore, targets: &dyn Targets) -> anyhow::Result<usize> {
let Some(node) = store.node() else {
return Ok(0);
};
if !node.is_leader() {
return Ok(0);
}
let mut rows: Vec<(String, Entry)> = Vec::new();
for (key, value) in store.kv_list_prefix(PREFIX).await? {
match serde_json::from_str(&value) {
Ok(entry) => rows.push((key, entry)),
Err(e) => {
tracing::warn!(key, err = %e, "outbox: dropping a row this version cannot read");
remove(store, &key).await;
}
}
}
if rows.is_empty() {
return Ok(0);
}
rows.sort_by(|a, b| a.0.cmp(&b.0));
node.ensure_majority()
.await
.map_err(|e| Fenced(format!("{e:#}")))?;
let latest_status: HashMap<(&str, &str), &str> = rows
.iter()
.filter_map(|(key, e)| match &e.op {
Op::Status { issue, .. } => Some(((e.repo.as_str(), issue.as_str()), key.as_str())),
_ => None,
})
.collect();
let mut sent = 0;
for (key, entry) in &rows {
let Some(_claim) = Claim::take(key) else {
continue;
};
if store.kv_get(key).await?.is_none() {
continue;
}
let superseded = match &entry.op {
Op::Status { issue, .. } => {
latest_status.get(&(entry.repo.as_str(), issue.as_str())) != Some(&key.as_str())
}
_ => false,
};
if !superseded {
match retry(entry, targets).await {
Ok(()) => sent += 1,
Err(e) => {
tracing::warn!(key, repo = %entry.repo, err = %e, "outbox: retry failed, dropping it");
}
}
}
remove(store, key).await;
}
Ok(sent)
}
async fn retry(entry: &Entry, targets: &dyn Targets) -> anyhow::Result<()> {
let id = |issue: &str| ExternalId(issue.to_string());
match &entry.op {
Op::Status { issue, status } => {
targets
.backend(&entry.repo)?
.update_status(&id(issue), *status)
.await
}
Op::AddLabels { issue, labels } => {
targets
.backend(&entry.repo)?
.set_labels(&id(issue), labels)
.await
}
Op::RemoveLabel { issue, label } => {
targets
.backend(&entry.repo)?
.remove_label(&id(issue), label)
.await
}
Op::Comment {
issue,
body,
marker,
} => {
let number: u64 = issue.parse()?;
let posted = targets.comment_bodies(&entry.repo, number).await?;
if posted.iter().any(|b| b.contains(marker.as_str())) {
return Ok(());
}
targets
.backend(&entry.repo)?
.post_comment(&id(issue), body)
.await
}
Op::Merge {
pr,
head_sha,
delete_branch,
} => {
targets
.merge(&entry.repo, *pr, *delete_branch, head_sha)
.await
}
}
}
pub fn wrap(
backend: Arc<dyn ExternalBackend>,
store: &TaskStore,
repo: &str,
) -> Arc<dyn ExternalBackend> {
if store.node().is_none() {
return backend;
}
Arc::new(Outboxed {
inner: backend,
store: store.clone(),
repo: repo.to_string(),
})
}
struct Outboxed {
inner: Arc<dyn ExternalBackend>,
store: TaskStore,
repo: String,
}
fn entry(repo: &str, op: Op) -> Entry {
Entry {
repo: repo.to_string(),
op,
}
}
fn is_issue(id: &ExternalId) -> bool {
id.0.parse::<u64>().is_ok()
}
impl Outboxed {
async fn fence(&self) -> anyhow::Result<()> {
match self.store.node() {
Some(node) if node.is_leader() => node
.ensure_majority()
.await
.map_err(|e| Fenced(format!("{e:#}")).into()),
Some(node) if !node.has_leader() => {
Err(Fenced("this node knows no leader".into()).into())
}
_ => Ok(()),
}
}
async fn comment(&self, repo: &str, id: &ExternalId, body: &str) -> anyhow::Result<()> {
if !is_issue(id) {
return self.inner.post_comment_in_repo(repo, id, body).await;
}
let key = new_key();
let marker = marker(&key);
let body = format!("{}\n\n{marker}", security::redact_posted_body(body));
let op = Op::Comment {
issue: id.0.clone(),
body: body.clone(),
marker,
};
let run = async {
if repo == self.repo {
self.inner.post_comment(id, &body).await
} else {
self.inner.post_comment_in_repo(repo, id, &body).await
}
};
send(&self.store, &key, entry(repo, op), run).await
}
}
#[async_trait]
impl TaskReader for Outboxed {
async fn get_task(&self, id: &ExternalId) -> anyhow::Result<ExternalTask> {
self.inner.get_task(id).await
}
async fn list_by_status(&self, status: Status) -> anyhow::Result<Vec<ExternalTask>> {
self.inner.list_by_status(status).await
}
async fn list_all_tasks(&self) -> anyhow::Result<Vec<ExternalTask>> {
self.inner.list_all_tasks().await
}
async fn list_reconciliation_candidates(&self) -> anyhow::Result<Vec<ExternalTask>> {
self.inner.list_reconciliation_candidates().await
}
async fn list_routable(&self) -> anyhow::Result<Vec<ExternalTask>> {
self.inner.list_routable().await
}
async fn list_active_open_issues(&self) -> anyhow::Result<Vec<(ExternalTask, Option<Status>)>> {
self.inner.list_active_open_issues().await
}
async fn has_open_issue_with_title(&self, title: &str, label: &str) -> anyhow::Result<bool> {
self.inner.has_open_issue_with_title(title, label).await
}
}
#[async_trait]
impl TaskWriter for Outboxed {
async fn create_task(
&self,
title: &str,
body: &str,
labels: &[String],
) -> anyhow::Result<ExternalId> {
self.fence().await?;
self.inner.create_task(title, body, labels).await
}
async fn update_status(&self, id: &ExternalId, status: Status) -> anyhow::Result<()> {
if !is_issue(id) {
return self.inner.update_status(id, status).await;
}
let op = Op::Status {
issue: id.0.clone(),
status,
};
let run = self.inner.update_status(id, status);
send(&self.store, &new_key(), entry(&self.repo, op), run).await
}
async fn set_labels(&self, id: &ExternalId, labels: &[String]) -> anyhow::Result<()> {
if !is_issue(id) {
return self.inner.set_labels(id, labels).await;
}
let op = Op::AddLabels {
issue: id.0.clone(),
labels: labels.to_vec(),
};
let run = self.inner.set_labels(id, labels);
send(&self.store, &new_key(), entry(&self.repo, op), run).await
}
async fn remove_label(&self, id: &ExternalId, label: &str) -> anyhow::Result<()> {
if !is_issue(id) {
return self.inner.remove_label(id, label).await;
}
let op = Op::RemoveLabel {
issue: id.0.clone(),
label: label.to_string(),
};
let run = self.inner.remove_label(id, label);
send(&self.store, &new_key(), entry(&self.repo, op), run).await
}
async fn get_sub_issues(&self, id: &ExternalId) -> anyhow::Result<Vec<ExternalId>> {
self.inner.get_sub_issues(id).await
}
async fn create_sub_task(
&self,
parent_id: &ExternalId,
title: &str,
body: &str,
labels: &[String],
) -> anyhow::Result<ExternalId> {
self.fence().await?;
self.inner
.create_sub_task(parent_id, title, body, labels)
.await
}
async fn ensure_status_label(&self, label: &str) -> anyhow::Result<()> {
self.fence().await?;
self.inner.ensure_status_label(label).await
}
}
#[async_trait]
impl Conversation for Outboxed {
async fn post_comment(&self, id: &ExternalId, body: &str) -> anyhow::Result<()> {
self.comment(&self.repo, id, body).await
}
async fn get_authenticated_user(&self) -> anyhow::Result<Option<String>> {
self.inner.get_authenticated_user().await
}
async fn get_mentions(&self, since: &str) -> anyhow::Result<Vec<Mention>> {
self.inner.get_mentions(since).await
}
async fn list_issue_comments(&self, id: &ExternalId) -> anyhow::Result<Vec<Mention>> {
self.inner.list_issue_comments(id).await
}
async fn acknowledge_issue(&self, id: &ExternalId) -> anyhow::Result<()> {
self.fence().await?;
self.inner.acknowledge_issue(id).await
}
async fn acknowledge_mention(&self, comment_id: &str) -> anyhow::Result<()> {
self.fence().await?;
self.inner.acknowledge_mention(comment_id).await
}
async fn post_comment_in_repo(
&self,
repo: &str,
id: &ExternalId,
body: &str,
) -> anyhow::Result<()> {
self.comment(repo, id, body).await
}
}
#[async_trait]
impl MergeState for Outboxed {
async fn is_pr_merged(&self, branch: &str) -> anyhow::Result<bool> {
self.inner.is_pr_merged(branch).await
}
async fn batch_is_pr_merged(
&self,
branches: &[String],
) -> anyhow::Result<HashMap<String, bool>> {
self.inner.batch_is_pr_merged(branches).await
}
async fn blocked_by(&self, repo: &str, issue_number: i64) -> anyhow::Result<BlockedByFetch> {
self.inner.blocked_by(repo, issue_number).await
}
async fn issue_close_state(
&self,
repo: &str,
issue_number: i64,
) -> anyhow::Result<Option<(String, Option<String>)>> {
self.inner.issue_close_state(repo, issue_number).await
}
async fn pull_request_completion(
&self,
repo: &str,
pr_number: i64,
) -> anyhow::Result<Option<PullRequestCompletion>> {
self.inner.pull_request_completion(repo, pr_number).await
}
async fn add_dependency(
&self,
issue_number: i64,
blocking_repo: &str,
blocking_number: i64,
) -> anyhow::Result<()> {
self.fence().await?;
self.inner
.add_dependency(issue_number, blocking_repo, blocking_number)
.await
}
}
#[async_trait]
impl Tracker for Outboxed {
fn name(&self) -> &str {
self.inner.name()
}
async fn sync_to_project(
&self,
id: &ExternalId,
status: Status,
) -> anyhow::Result<Option<String>> {
self.fence().await?;
self.inner.sync_to_project(id, status).await
}
async fn reconcile_project_statuses(&self) -> anyhow::Result<()> {
self.fence().await?;
self.inner.reconcile_project_statuses().await
}
async fn sync_estimate_to_project(&self, id: &ExternalId, estimate: u8) -> anyhow::Result<()> {
self.fence().await?;
self.inner.sync_estimate_to_project(id, estimate).await
}
async fn get_project_item_estimates(
&self,
issue_node_ids: &[String],
) -> anyhow::Result<HashMap<String, u8>> {
self.inner.get_project_item_estimates(issue_node_ids).await
}
async fn health_check(&self) -> anyhow::Result<()> {
self.inner.health_check().await
}
}
#[cfg(test)]
mod tests;