//! Durable local link indexing: index inline, queue on failure, drain later. //! //! # Durability contract //! //! The write ordering for every local record is: //! //! ```text //! PDS write -> index links (or queue the record) -> DB commit -> advance cursor //! ``` //! //! Call [`index_or_queue`] with the same record body that was written to the //! PDS, then call [`DbHandle::commit`] before advancing the publish cursor. //! The link rows and the `link_repairs` row are written in the same SQLite //! transaction. A crash before the commit rolls both the links/queue row and //! the still-unadvanced cursor back, so the record is written and indexed //! again on the next cycle; a crash after the commit but before the cursor //! advance leaves the queue row (and any link rows) persisted, so the record is //! reindexed from local state. Reindexing is idempotent: [`super::index_record`] //! deletes every link row for the source before inserting the current ones, so //! a drained repair can never duplicate rows. //! //! [`drain_link_repairs`] makes no PDS calls and needs no record body from the //! network: the serialized record is already stored in `link_repairs`. Failures //! stay queued with exponential backoff (with jitter, capped) and are retried //! when due. The source CID is stored alongside the record, so a drained //! repair restores both the source URI and CID on its backlinks. //! //! [`repair_after_commit`] is the call-site marker for the ordering above: //! callers commit the indexed/queued rows first, then drain, then advance the //! cursor. use anyhow::{Result, anyhow, bail}; use chrono::{DateTime, TimeDelta, Utc}; use serde::Serialize; use serde_json::Value; use crate::db::DbHandle; use crate::db::model::{LinkRepairMark, LinkRepairRow}; use crate::time::{created_at, jitter}; use super::index_record; /// First retry delay after a failed index. Doubles per attempt. const BASE_RETRY_SECS: i64 = 30; /// Retry delay cap; repairs never sleep longer than this (plus jitter). const MAX_RETRY_SECS: i64 = 3_600; /// Outcome counters for one [`drain_link_repairs`] pass. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)] pub struct LinkRepairCounters { /// Rows that were due and attempted in this pass. pub attempted: usize, /// Rows reindexed and deleted. pub repaired: usize, /// Rows left queued with bumped attempts and backoff. pub failed: usize, /// Rows read but not due yet (`next_retry_at` in the future). pub deferred: usize, } /// Index a written record, queueing it when indexing fails. /// /// On index failure the record is serialized into `link_repairs` with the /// attempt count, the error, and a jittered exponential `next_retry_at`, so a /// restart can reindex it from local state (the caller still commits before /// advancing its cursor). Returns `Err` only when the record cannot be indexed /// *and* the repair row could not be stored; in that case the caller must not /// advance its cursor. pub async fn index_or_queue( db: &DbHandle, repo_did: &str, src_uri: &str, src_cid: Option<&str>, collection: &str, record: &Value, ) -> Result<()> { let result = if record.is_object() { index_record(db, repo_did, src_uri, src_cid, collection, record).await } else { // An ATProto record body is always a JSON object. Indexing anything // else would only delete the source's existing link rows, so queue it // (and retry with backoff) instead. Err(anyhow!("link record is not a JSON object")) }; match result { Ok(()) => Ok(()), Err(error) => queue(db, repo_did, src_uri, src_cid, collection, record, &error).await, } } /// Drain due repairs, reindexing from the stored record JSON. /// /// Rows are read in `next_retry_at` order (the DB query) and only due rows are /// attempted; `limit == 0` means no limit. Successful rows are deleted, /// failures are bumped with backoff, and the pass commits before returning. /// No PDS calls are made. pub async fn drain_link_repairs(db: &DbHandle, limit: usize) -> Result { let rows = db.pending_link_repairs(limit).await?; let mut counters = LinkRepairCounters::default(); let now = Utc::now(); for row in rows { if !due(row.next_retry_at.as_deref(), now) { counters.deferred += 1; continue; } counters.attempted += 1; match reindex(db, &row).await { Ok(()) => { db.delete_link_repair(&row.repo_did, &row.src_uri).await?; counters.repaired += 1; } Err(error) => { let mark = retry_mark(&row, error.to_string()); db.mark_link_repair(mark).await?; counters.failed += 1; } } } if counters.attempted > 0 { db.commit().await?; } Ok(counters) } /// Drain due repairs after the caller has committed its publish rows and /// before it advances the publish cursor (see the module contract). pub async fn repair_after_commit(db: &DbHandle, limit: usize) -> Result { drain_link_repairs(db, limit).await } async fn queue( db: &DbHandle, repo_did: &str, src_uri: &str, src_cid: Option<&str>, collection: &str, record: &Value, error: &anyhow::Error, ) -> Result<()> { let attempts = db .get_link_repair(repo_did, src_uri) .await? .map_or(1, |row| row.attempts + 1); db.mark_link_repair(LinkRepairMark { repo_did: repo_did.to_owned(), src_uri: src_uri.to_owned(), src_cid: src_cid.map(str::to_owned), collection: Some(collection.to_owned()), record_json: serde_json::to_string(record)?, attempts, last_error: Some(error.to_string()), next_retry_at: Some(retry_at(attempts)), }) .await } async fn reindex(db: &DbHandle, row: &LinkRepairRow) -> Result<()> { let Some(collection) = row.collection.as_deref() else { bail!("link repair has no collection"); }; let record: Value = serde_json::from_str(&row.record_json)?; if !record.is_object() { bail!("link repair record is not a JSON object"); } index_record( db, &row.repo_did, &row.src_uri, row.src_cid.as_deref(), collection, &record, ) .await } fn retry_mark(row: &LinkRepairRow, last_error: String) -> LinkRepairMark { let attempts = row.attempts + 1; LinkRepairMark { repo_did: row.repo_did.clone(), src_uri: row.src_uri.clone(), src_cid: row.src_cid.clone(), collection: row.collection.clone(), record_json: row.record_json.clone(), attempts, last_error: Some(last_error), next_retry_at: Some(retry_at(attempts)), } } /// `BASE_RETRY_SECS * 2^(attempts-1)`, capped, plus up to 20% jitter. fn retry_at(attempts: i64) -> String { let exponent = attempts.clamp(1, 16) as u32 - 1; let delay = BASE_RETRY_SECS .saturating_mul(1_i64 << exponent) .min(MAX_RETRY_SECS); let jitter_ms = jitter(delay as f64 * 1000.0 * 0.2) as i64; let when = Utc::now() + TimeDelta::milliseconds(delay * 1000 + jitter_ms); created_at(when) } fn due(next_retry_at: Option<&str>, now: DateTime) -> bool { let Some(raw) = next_retry_at else { return true; }; match DateTime::parse_from_rfc3339(raw) { Ok(when) => when.with_timezone(&Utc) <= now, // Unparseable retry stamps should not wedge the queue. Err(_) => true, } }