Something went wrong. Try again.
Monorepo for Tangled forked from tangled.org/core
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276//! sync git repository objects (packfile)
use std::sync::Arc;use std::time::{Duration, Instant};
use bobbin_runtime::Clock;
use crate::admission::BackfillAdmission;use gitmirror_db::{Db, DbError};use gitmirror_git::layout::Layout;use gitmirror_types::{KnotPolicy, backoff_us, now_us};use jacquard_common::types::did::Did;use metrics::{gauge, histogram};use thiserror::Error;use tokio::sync::{Notify, Semaphore};use tokio_util::sync::CancellationToken;use tracing::{Instrument as _, error, info, warn};
mod admission;mod task;
/// The identity resolver, same concrete type the XRPC side uses.pub type Directory = jacquard_identity::JacquardResolver<bobbin_runtime::ReqwestHttp>;
#[derive(Debug, Error)]pub enum SyncError { #[error("database: {0}")] Db(#[from] DbError),}
/// Rows pulled per queue scan. Not a config knob: it only bounds one pass's memory, and the/// semaphore is what actually limits work in flight.const BATCH_SIZE: i64 = 64;
/// How long a repo is parked when the knot was busy rather than broken. Short, because this is/// not a backoff: it only has to be long enough to get the row out of the scan window.const DEFER_HOLD_US: i64 = 5 * 1_000_000;
/// Metric-only split between `backoff` and `error`; retries continue past it.const MAX_RETRY: i32 = 12;
const STATE_METRICS_INTERVAL: Duration = Duration::from_secs(30);
pub const DEFAULT_CONCURRENCY: usize = 8;pub const DEFAULT_PER_KNOT_CONCURRENCY: usize = 4;pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(5);
pub struct SyncConfig { pub concurrency: usize, pub per_knot_concurrency: usize, pub poll_interval: Duration,}
impl Default for SyncConfig { fn default() -> Self { Self { concurrency: DEFAULT_CONCURRENCY, per_knot_concurrency: DEFAULT_PER_KNOT_CONCURRENCY, poll_interval: DEFAULT_POLL_INTERVAL, } }}
pub struct SyncRuntime { pub db: Db, pub clock: Arc<dyn Clock>, pub cancel: CancellationToken, pub http: reqwest::Client, pub directory: Arc<Directory>, pub layout: Layout, pub knot_policy: KnotPolicy, pub index_notify: Arc<Notify>,}
// NOTE: see hydrant/src/backfill/worker.rs as reference
pub struct BackfillWorker { rt: SyncRuntime, poll_interval: Duration, semaphore: Arc<Semaphore>, admission: BackfillAdmission, in_flight: Arc<scc::HashSet<Did>>, /// Woken by a finishing task so a pass that hit the concurrency limit picks up the next repo /// immediately instead of waiting out `poll_interval`. drained: Arc<Notify>,}
impl BackfillWorker { pub fn new(rt: SyncRuntime, config: SyncConfig) -> Self { Self { rt, poll_interval: config.poll_interval, semaphore: Arc::new(Semaphore::new(config.concurrency)), admission: BackfillAdmission::new(config.concurrency, config.per_knot_concurrency), in_flight: Arc::new(scc::HashSet::new()), drained: Arc::new(Notify::new()), } }}
struct InFlightGuard { did: Did, set: Arc<scc::HashSet<Did>>,}
impl Drop for InFlightGuard { fn drop(&mut self) { let _ = self.set.remove_sync(&self.did); gauge!("gitmirror_sync_in_flight").decrement(1); }}
impl BackfillWorker { pub async fn run(self) -> Result<(), SyncError> { info!("backfill worker started");
loop { if self.rt.cancel.is_cancelled() { break; }
let mut spawned = 0; for row in self .rt .db .pending_repos(now_us(&*self.rt.clock), BATCH_SIZE) .await? { if self.in_flight.contains_sync(&row.did) { continue; }
let permit = match self.semaphore.clone().try_acquire_owned() { Ok(p) => p, Err(_) => break, };
// only mark as in flight if we can acquire a permit if self.in_flight.insert_sync(row.did.clone()).is_err() { // a task is already running, weh // so we don't need this one anymore... break; }
gauge!("gitmirror_sync_in_flight").increment(1); let guard = InFlightGuard { did: row.did.clone(), set: self.in_flight.clone(), };
let db = self.rt.db.clone(); let clock = self.rt.clock.clone(); let http = self.rt.http.clone(); let directory = self.rt.directory.clone(); let layout = self.rt.layout.clone(); let knot_policy = self.rt.knot_policy; let admission = self.admission.clone(); let drained = self.drained.clone(); let index_notify = self.rt.index_notify.clone();
let span = tracing::info_span!( "backfill", did = %row.did, knot = tracing::field::Empty ); tokio::spawn( async move { let _guard = guard; let started = Instant::now(); let res = task::did_task( &http, &directory, &layout, knot_policy, &row, &admission, permit, ) .await;
let duration = started.elapsed().as_secs_f64(); let outcome = match &res { Ok(task::TaskDisposition::Finished { .. }) => "finished", Ok(task::TaskDisposition::Deferred) => "deferred", Err(_) => "failed", }; histogram!("gitmirror_sync_task_duration_seconds", "outcome" => outcome) .record(duration); info!( outcome, duration_ms = duration * 1e3, retry_count = row.retry_count, error = res.as_ref().err().map(tracing::field::display), "sync finished" );
let write = match &res { Ok(task::TaskDisposition::Finished { default_branch_commit, }) => { let commit = default_branch_commit.map(|oid| oid.to_string()); let res = db.mark_synced(&row, commit.as_deref()).await; if res.is_ok() { index_notify.notify_one(); } res } Ok(task::TaskDisposition::Deferred) => { db.mark_deferred(&row, now_us(&*clock) + DEFER_HOLD_US) .await } Err(e) => { db.mark_sync_failed( &row, &e.to_string(), now_us(&*clock) + backoff_us(row.retry_count), ) .await } };
if let Err(e) = write { error!(error = %e, "recording sync outcome failed"); }
// wake worker to pick up more (in case we were sleeping at limit) drained.notify_one(); } .instrument(span), );
spawned += 1; }
if spawned == 0 { // wait for a task to finish, or for a `retry_after` to come due tokio::select! { () = self.rt.cancel.cancelled() => break, () = self.drained.notified() => {} () = self.rt.clock.sleep(self.poll_interval) => {} } } // loop immediately since we might have more tasks }
info!("backfill worker stopped"); Ok(()) }}
/// Publishes `gitmirror_sync_repos` from the DB until cancelled.pub async fn report_repo_states(db: Db, clock: Arc<dyn Clock>, cancel: CancellationToken) { loop { match db.repo_state_counts(now_us(&*clock), MAX_RETRY).await { Ok(rows) => { for state in ["pending", "active", "backoff", "error"] { for due in [true, false] { let count = rows .iter() .find(|(s, d, _)| s == state && *d == due) .map_or(0, |(_, _, c)| *c); gauge!("gitmirror_sync_repos", "state" => state, "due" => due.to_string()) .set(count as f64); } } } Err(e) => warn!(error = %e, "counting repo states failed"), }
tokio::select! { () = cancel.cancelled() => break, () = clock.sleep(STATE_METRICS_INTERVAL) => {} } }}