use chrono::{DateTime, Utc};
use dashmap::DashMap;
use reqwest::Client;
use serde_json::{json, Map, Value};
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::mpsc;
use tokio::time::{sleep, Duration};
use crate::config::{Config, HookEvent, HooksConfig};
use crate::dates;
use crate::git::{FileChange, GitFiles, GitOrder};
use crate::order;
const MAX_BACKOFF_EXPONENT: u32 = 20;
const REPLAY_READ_CHUNK: usize = 64;
pub enum OrderChange {
Updated {
directory: String,
order: Vec<String>,
},
Deleted {
directory: String,
},
}
#[derive(Clone, Copy, Debug)]
pub enum ReplayKind {
Created,
Deleted,
}
pub struct ReplayJob {
pub repo_path: PathBuf,
pub kind: ReplayKind,
pub paths: Vec<String>,
pub order_directories: Vec<String>,
pub delay_ms: Option<u64>,
}
pub enum HookSource {
Commit {
file_changes: Vec<FileChange>,
order_changes: Vec<OrderChange>,
},
Replay(ReplayJob),
}
pub struct HookJob {
pub collection_id: String,
pub tenant_id: String,
pub commit_sha: String,
pub committed_at: DateTime<Utc>,
pub source: HookSource,
}
impl HookJob {
pub fn replay(
collection_id: String,
tenant_id: String,
commit_sha: String,
committed_at: DateTime<Utc>,
replay: ReplayJob,
) -> Self {
Self {
collection_id,
tenant_id,
commit_sha,
committed_at,
source: HookSource::Replay(replay),
}
}
pub fn new(
collection_id: String,
tenant_id: String,
commit_sha: String,
committed_at: DateTime<Utc>,
changes: Vec<FileChange>,
) -> Self {
let mut file_changes: Vec<FileChange> = Vec::with_capacity(changes.len());
let mut order_changes: Vec<OrderChange> = Vec::new();
for change in changes {
let on_dates_index = match &change {
FileChange::Created { path, .. }
| FileChange::Updated { path, .. }
| FileChange::Deleted { path } => dates::is_dates_file(path),
FileChange::Moved {
from_path, to_path, ..
} => dates::is_dates_file(from_path) || dates::is_dates_file(to_path),
};
if on_dates_index {
continue;
}
let touches_index = match &change {
FileChange::Created { path, .. }
| FileChange::Updated { path, .. }
| FileChange::Deleted { path } => order::is_order_file(path),
FileChange::Moved { to_path, .. } => order::is_order_file(to_path),
};
if !touches_index {
file_changes.push(change);
continue;
}
match change {
FileChange::Created { path, content } | FileChange::Updated { path, content } => {
Self::push_order_updated(&mut order_changes, &path, &content);
}
FileChange::Deleted { path } => {
if let Some(directory) = order::directory_of_order_file(&path) {
order_changes.push(OrderChange::Deleted {
directory: directory.to_string(),
});
}
}
FileChange::Moved {
from_path,
to_path,
content,
} => {
if let Some(directory) = order::directory_of_order_file(&from_path) {
order_changes.push(OrderChange::Deleted {
directory: directory.to_string(),
});
}
Self::push_order_updated(&mut order_changes, &to_path, &content);
}
}
}
Self {
collection_id,
tenant_id,
commit_sha,
committed_at,
source: HookSource::Commit {
file_changes,
order_changes,
},
}
}
fn push_order_updated(order_changes: &mut Vec<OrderChange>, path: &str, content: &str) {
let Some(directory) = order::directory_of_order_file(path) else {
return;
};
match order::parse(content) {
Some(parsed) => order_changes.push(OrderChange::Updated {
directory: directory.to_string(),
order: parsed,
}),
None => tracing::warn!(path, "order index is malformed, skipping its hook"),
}
}
}
pub struct HookQueue {
client: Client,
config: Arc<Config>,
senders: DashMap<String, mpsc::UnboundedSender<HookJob>>,
}
impl HookQueue {
pub fn new(config: Arc<Config>) -> Self {
Self {
client: Client::new(),
config,
senders: DashMap::new(),
}
}
pub fn enqueue(&self, queue_key: &str, job: HookJob) {
if self.config.hooks.is_none() {
return;
}
let sender = self
.senders
.entry(queue_key.to_string())
.or_insert_with(|| self.spawn_consumer())
.clone();
if sender.send(job).is_err() {
tracing::error!(queue_key, "hook queue consumer is gone, dropping hook job");
}
}
fn spawn_consumer(&self) -> mpsc::UnboundedSender<HookJob> {
let (sender, mut receiver) = mpsc::unbounded_channel::<HookJob>();
let client = self.client.clone();
let config = self.config.clone();
tokio::spawn(async move {
while let Some(job) = receiver.recv().await {
HookDelivery::deliver_all(&client, &config, job).await;
}
});
sender
}
}
struct HookDelivery;
impl HookDelivery {
async fn deliver_all(client: &Client, config: &Config, job: HookJob) {
let hooks = match config.hooks.as_ref() {
Some(hooks) => hooks,
None => return,
};
let attempts = hooks.retry_attempts.max(1);
let repository = format!("{}/{}", job.collection_id, job.tenant_id);
let (file_changes, order_changes) = match job.source {
HookSource::Commit {
file_changes,
order_changes,
} => (file_changes, order_changes),
HookSource::Replay(replay) => {
Self::deliver_replay(
client,
hooks,
attempts,
&job.collection_id,
&job.tenant_id,
&job.commit_sha,
&job.committed_at,
&repository,
replay,
)
.await;
return;
}
};
for file_change in file_changes {
let required_event = Self::event_for_change(&file_change);
if !hooks.events.contains(&required_event) {
continue;
}
let payload = Self::build_payload(
&job.collection_id,
&job.tenant_id,
&job.commit_sha,
&job.committed_at,
&file_change,
false,
);
let description = Self::change_description(&file_change);
Self::deliver_with_retries(
client,
hooks,
attempts,
payload,
&repository,
&job.commit_sha,
&description,
)
.await;
}
for order_change in order_changes {
let required_event = Self::event_for_order_change(&order_change);
if !hooks.events.contains(&required_event) {
continue;
}
let payload = Self::build_order_payload(
&job.collection_id,
&job.tenant_id,
&job.commit_sha,
&job.committed_at,
&order_change,
false,
);
let description = Self::order_change_description(&order_change);
Self::deliver_with_retries(
client,
hooks,
attempts,
payload,
&repository,
&job.commit_sha,
&description,
)
.await;
}
}
#[allow(clippy::too_many_arguments)]
async fn deliver_replay(
client: &Client,
hooks: &HooksConfig,
attempts: u32,
collection_id: &str,
tenant_id: &str,
commit_sha: &str,
committed_at: &DateTime<Utc>,
repository: &str,
replay: ReplayJob,
) {
let required_event = match replay.kind {
ReplayKind::Created => HookEvent::FileCreated,
ReplayKind::Deleted => HookEvent::FileDeleted,
};
let deliver_files = hooks.events.contains(&required_event);
let deliver_orders = hooks.events.contains(&HookEvent::OrderUpdated);
if !deliver_files && !replay.paths.is_empty() {
tracing::warn!(
repository,
event = ?replay.kind,
path_count = replay.paths.len(),
"replay requested but its event kind is not listed in [hooks] events, delivering no file events"
);
}
if !deliver_orders && !replay.order_directories.is_empty() {
tracing::warn!(
repository,
directory_count = replay.order_directories.len(),
"replay found order indexes but order.updated is not listed in [hooks] events, delivering no order events"
);
}
if !deliver_files && !deliver_orders {
return;
}
let total = replay.paths.len();
let delay = replay
.delay_ms
.filter(|milliseconds| *milliseconds > 0)
.map(Duration::from_millis);
tracing::info!(
repository,
event = ?replay.kind,
path_count = total,
order_directory_count = replay.order_directories.len(),
delay_ms = ?replay.delay_ms,
"replay starting"
);
let mut delivered: usize = 0;
let mut skipped: usize = 0;
let mut orders_delivered: usize = 0;
let mut orders_skipped: usize = 0;
if deliver_files {
for chunk in replay.paths.chunks(REPLAY_READ_CHUNK) {
let changes = match Self::replay_chunk_changes(
&replay.repo_path,
tenant_id,
replay.kind,
chunk,
)
.await
{
Some(changes) => changes,
None => {
tracing::error!(
repository,
delivered,
remaining = total - delivered - skipped,
"replay aborted: repository could not be read"
);
return;
}
};
for change in changes {
let Some(change) = change else {
skipped += 1;
continue;
};
if delivered > 0 {
if let Some(delay) = delay {
sleep(delay).await;
}
}
let payload = Self::build_payload(
collection_id,
tenant_id,
commit_sha,
committed_at,
&change,
true,
);
let description = Self::change_description(&change);
Self::deliver_with_retries(
client,
hooks,
attempts,
payload,
repository,
commit_sha,
&description,
)
.await;
delivered += 1;
}
}
}
if deliver_orders {
for chunk in replay.order_directories.chunks(REPLAY_READ_CHUNK) {
let orders = match Self::replay_chunk_orders(&replay.repo_path, tenant_id, chunk)
.await
{
Some(orders) => orders,
None => {
tracing::error!(
repository,
orders_delivered,
remaining =
replay.order_directories.len() - orders_delivered - orders_skipped,
"replay aborted: repository could not be read for order indexes"
);
return;
}
};
for (directory, order) in chunk.iter().zip(orders) {
let Some(order) = order else {
orders_skipped += 1;
continue;
};
if delivered + orders_delivered > 0 {
if let Some(delay) = delay {
sleep(delay).await;
}
}
let order_change = OrderChange::Updated {
directory: directory.clone(),
order,
};
let payload = Self::build_order_payload(
collection_id,
tenant_id,
commit_sha,
committed_at,
&order_change,
true,
);
let description = Self::order_change_description(&order_change);
Self::deliver_with_retries(
client,
hooks,
attempts,
payload,
repository,
commit_sha,
&description,
)
.await;
orders_delivered += 1;
}
}
}
tracing::info!(
repository,
event = ?replay.kind,
delivered,
skipped,
orders_delivered,
orders_skipped,
"replay finished"
);
}
async fn replay_chunk_changes(
repo_path: &std::path::Path,
tenant_id: &str,
kind: ReplayKind,
chunk: &[String],
) -> Option<Vec<Option<FileChange>>> {
if let ReplayKind::Deleted = kind {
return Some(
chunk
.iter()
.map(|path| Some(FileChange::Deleted { path: path.clone() }))
.collect(),
);
}
let repo_path = repo_path.to_path_buf();
let tenant_id = tenant_id.to_string();
let paths = chunk.to_vec();
let read = tokio::task::spawn_blocking(move || {
GitFiles::replay_read_files(&repo_path, &tenant_id, &paths)
})
.await;
let contents = match read {
Ok(Ok(contents)) => contents,
Ok(Err(read_err)) => {
tracing::error!("replay chunk read failed: {}", read_err);
return None;
}
Err(join_err) => {
tracing::error!("replay chunk read task failed: {}", join_err);
return None;
}
};
Some(
chunk
.iter()
.zip(contents)
.map(|(path, content)| {
content.map(|content| FileChange::Created {
path: path.clone(),
content,
})
})
.collect(),
)
}
async fn replay_chunk_orders(
repo_path: &std::path::Path,
tenant_id: &str,
chunk: &[String],
) -> Option<Vec<Option<Vec<String>>>> {
let repo_path = repo_path.to_path_buf();
let tenant_id = tenant_id.to_string();
let directories = chunk.to_vec();
let read = tokio::task::spawn_blocking(move || {
GitOrder::replay_read_orders(&repo_path, &tenant_id, &directories)
})
.await;
match read {
Ok(Ok(orders)) => Some(orders),
Ok(Err(read_err)) => {
tracing::error!("replay order chunk read failed: {}", read_err);
None
}
Err(join_err) => {
tracing::error!("replay order chunk read task failed: {}", join_err);
None
}
}
}
async fn deliver_with_retries(
client: &Client,
hooks: &HooksConfig,
attempts: u32,
payload: Value,
repository: &str,
commit_sha: &str,
change_description: &str,
) {
for attempt in 1..=attempts {
match Self::send(client, hooks, &payload).await {
Ok(()) => {
tracing::debug!(
repository,
commit_sha,
change = change_description,
"hook delivered"
);
return;
}
Err(delivery_err) => {
tracing::error!(
repository,
commit_sha,
change = change_description,
attempt,
total = attempts,
"hook delivery failed: {}",
delivery_err
);
if attempt == attempts {
tracing::error!(
repository, commit_sha, change = change_description,
"CRITICAL: hook permanently failed after {} attempts — the receiver may be out of sync",
attempts
);
return;
}
let exponent = (attempt - 1).min(MAX_BACKOFF_EXPONENT);
let backoff_ms = hooks.retry_backoff_ms.saturating_mul(1u64 << exponent);
sleep(Duration::from_millis(backoff_ms)).await;
}
}
}
}
async fn send(client: &Client, hooks: &HooksConfig, payload: &Value) -> Result<(), String> {
let mut request_builder = client.post(&hooks.url).json(payload);
if let Some(hook_auth) = &hooks.auth {
request_builder = request_builder.header(&hook_auth.header, &hook_auth.value);
}
let response = request_builder
.send()
.await
.map_err(|send_err| send_err.to_string())?;
let status = response.status();
if status.is_success() {
return Ok(());
}
let body = response
.text()
.await
.unwrap_or_else(|_| "(unreadable body)".to_string());
Err(format!(
"receiver returned HTTP {}: {}",
status.as_u16(),
body
))
}
fn event_for_change(file_change: &FileChange) -> HookEvent {
match file_change {
FileChange::Created { .. } => HookEvent::FileCreated,
FileChange::Updated { .. } => HookEvent::FileUpdated,
FileChange::Deleted { .. } => HookEvent::FileDeleted,
FileChange::Moved { .. } => HookEvent::FileMoved,
}
}
fn event_for_order_change(order_change: &OrderChange) -> HookEvent {
match order_change {
OrderChange::Updated { .. } => HookEvent::OrderUpdated,
OrderChange::Deleted { .. } => HookEvent::OrderDeleted,
}
}
fn change_description(file_change: &FileChange) -> String {
match file_change {
FileChange::Created { path, .. } => format!("created:{}", path),
FileChange::Updated { path, .. } => format!("updated:{}", path),
FileChange::Deleted { path } => format!("deleted:{}", path),
FileChange::Moved {
from_path, to_path, ..
} => {
format!("moved:{}→{}", from_path, to_path)
}
}
}
fn order_change_description(order_change: &OrderChange) -> String {
match order_change {
OrderChange::Updated { directory, order } => format!(
"order updated:{} ({} entries)",
order::display_directory(directory),
order.len()
),
OrderChange::Deleted { directory } => {
format!("order deleted:{}", order::display_directory(directory))
}
}
}
fn build_order_payload(
collection_id: &str,
tenant_id: &str,
commit_sha: &str,
committed_at: &DateTime<Utc>,
order_change: &OrderChange,
replay: bool,
) -> Value {
let mut payload = Map::with_capacity(7);
payload.insert(
"collection_id".to_string(),
Value::String(collection_id.to_string()),
);
payload.insert(
"tenant_id".to_string(),
Value::String(tenant_id.to_string()),
);
payload.insert(
"commit_sha".to_string(),
Value::String(commit_sha.to_string()),
);
payload.insert(
"committed_at".to_string(),
Value::String(committed_at.to_rfc3339()),
);
if replay {
payload.insert("replayed".to_string(), Value::Bool(true));
}
match order_change {
OrderChange::Updated { directory, order } => {
payload.insert(
"event".to_string(),
Value::String("order.updated".to_string()),
);
payload.insert("directory".to_string(), Value::String(directory.clone()));
payload.insert("order".to_string(), json!(order));
}
OrderChange::Deleted { directory } => {
payload.insert(
"event".to_string(),
Value::String("order.deleted".to_string()),
);
payload.insert("directory".to_string(), Value::String(directory.clone()));
}
}
Value::Object(payload)
}
fn build_payload(
collection_id: &str,
tenant_id: &str,
commit_sha: &str,
committed_at: &DateTime<Utc>,
file_change: &FileChange,
replay: bool,
) -> Value {
let mut payload = Map::with_capacity(7);
payload.insert(
"collection_id".to_string(),
Value::String(collection_id.to_string()),
);
payload.insert(
"tenant_id".to_string(),
Value::String(tenant_id.to_string()),
);
payload.insert(
"commit_sha".to_string(),
Value::String(commit_sha.to_string()),
);
payload.insert(
"committed_at".to_string(),
Value::String(committed_at.to_rfc3339()),
);
if replay {
payload.insert("replayed".to_string(), Value::Bool(true));
}
match file_change {
FileChange::Created { path, content } => {
payload.insert(
"event".to_string(),
Value::String("file.created".to_string()),
);
payload.insert(
"file".to_string(),
json!({ "path": path, "content": content }),
);
}
FileChange::Updated { path, content } => {
payload.insert(
"event".to_string(),
Value::String("file.updated".to_string()),
);
payload.insert(
"file".to_string(),
json!({ "path": path, "content": content }),
);
}
FileChange::Deleted { path } => {
payload.insert(
"event".to_string(),
Value::String("file.deleted".to_string()),
);
payload.insert("file".to_string(), json!({ "path": path }));
}
FileChange::Moved {
from_path,
to_path,
content,
} => {
payload.insert("event".to_string(), Value::String("file.moved".to_string()));
payload.insert("from".to_string(), json!({ "path": from_path }));
payload.insert(
"to".to_string(),
json!({ "path": to_path, "content": content }),
);
}
}
Value::Object(payload)
}
}