2026-02-14 19:30:49 +01:00
|
|
|
|
//! Content-Addressable Storage with Deduplication (PostgreSQL-backed)
|
2026-02-14 01:29:34 +01:00
|
|
|
|
//!
|
|
|
|
|
|
//! Implements hash-based deduplication to eliminate redundant file storage.
|
2026-03-01 21:47:39 +01:00
|
|
|
|
//! Files are stored by their BLAKE3 hash, and multiple references can point
|
2026-02-14 01:29:34 +01:00
|
|
|
|
//! to the same physical blob.
|
|
|
|
|
|
//!
|
|
|
|
|
|
//! Architecture:
|
|
|
|
|
|
//! ```text
|
|
|
|
|
|
//! ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
2026-02-14 19:30:49 +01:00
|
|
|
|
//! │ storage.files │────▶│ storage.blobs │────▶│ Blob Store │
|
|
|
|
|
|
//! │ (references) │ │ (PG dedup index)│ │ (.blobs/ on FS) │
|
2026-02-14 01:29:34 +01:00
|
|
|
|
//! └─────────────────┘ └─────────────────┘ └─────────────────┘
|
|
|
|
|
|
//! ```
|
|
|
|
|
|
//!
|
2026-02-14 19:30:49 +01:00
|
|
|
|
//! The dedup index lives in PostgreSQL (`storage.blobs`) — no in-memory
|
2026-02-25 23:31:51 +01:00
|
|
|
|
//! HashMap, no JSON file, no WAL.
|
|
|
|
|
|
//!
|
|
|
|
|
|
//! **Write-first strategy** (store_bytes / store_from_file):
|
|
|
|
|
|
//! 1. Write/move the blob file to disk *before* touching PostgreSQL.
|
|
|
|
|
|
//! 2. Single `INSERT … ON CONFLICT … RETURNING ref_count` upsert
|
|
|
|
|
|
//! (~2-4 ms) — no explicit transaction, no `SELECT FOR UPDATE`.
|
|
|
|
|
|
//! 3. PG connection is never held during disk I/O.
|
|
|
|
|
|
//!
|
|
|
|
|
|
//! `remove_reference` retains `SELECT … FOR UPDATE` inside a short
|
|
|
|
|
|
//! transaction because it must atomically decide whether to delete the
|
|
|
|
|
|
//! row *and* the blob file.
|
2026-02-14 19:30:49 +01:00
|
|
|
|
//!
|
2026-02-14 01:29:34 +01:00
|
|
|
|
//! Benefits:
|
2026-02-14 19:30:49 +01:00
|
|
|
|
//! - ACID durability — crash-safe, zero orphaned index entries
|
2026-02-25 23:31:51 +01:00
|
|
|
|
//! - PG connections never blocked by disk I/O (write-first)
|
2026-02-14 01:29:34 +01:00
|
|
|
|
//! - 30-50% storage reduction typical
|
|
|
|
|
|
//! - Faster uploads for existing content (instant dedup)
|
|
|
|
|
|
|
|
|
|
|
|
use async_trait::async_trait;
|
|
|
|
|
|
use bytes::Bytes;
|
2026-02-23 23:43:59 +01:00
|
|
|
|
use futures::stream::{self, StreamExt};
|
2026-02-24 10:45:38 +01:00
|
|
|
|
use futures::{Stream, TryStreamExt};
|
2026-03-01 21:47:39 +01:00
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
use sqlx::PgPool;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
use std::path::{Path, PathBuf};
|
2026-02-15 17:53:25 +01:00
|
|
|
|
use std::pin::Pin;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
use tokio::fs::{self, File};
|
2026-02-23 00:51:46 +01:00
|
|
|
|
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
2026-02-15 17:53:25 +01:00
|
|
|
|
use tokio_util::io::ReaderStream;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
|
|
|
|
|
use crate::application::ports::dedup_ports::{
|
|
|
|
|
|
BlobMetadataDto, DedupPort, DedupResultDto, DedupStatsDto,
|
|
|
|
|
|
};
|
|
|
|
|
|
use crate::domain::errors::{DomainError, ErrorKind};
|
|
|
|
|
|
|
2026-03-01 21:47:39 +01:00
|
|
|
|
/// Block size for BLAKE3 file hashing (1MB — optimal syscall/throughput ratio).
|
2026-02-23 00:51:46 +01:00
|
|
|
|
const HASH_BLOCK_SIZE: usize = 1024 * 1024;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-23 00:51:46 +01:00
|
|
|
|
/// Chunk size for streaming file reads (256 KB)
|
2026-02-15 17:53:25 +01:00
|
|
|
|
const STREAM_CHUNK_SIZE: usize = 256 * 1024;
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Content-Addressable Storage Service (PostgreSQL-backed)
|
2026-02-14 01:29:34 +01:00
|
|
|
|
pub struct DedupService {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Root directory for blob storage on the filesystem
|
2026-02-14 01:29:34 +01:00
|
|
|
|
blob_root: PathBuf,
|
|
|
|
|
|
/// Root directory for temporary files during upload
|
|
|
|
|
|
temp_root: PathBuf,
|
2026-02-24 19:28:00 +01:00
|
|
|
|
/// PostgreSQL connection pool (dedup index in `storage.blobs`) — primary,
|
|
|
|
|
|
/// used by request-path operations (store_bytes, store_from_file, etc.).
|
2026-02-14 19:30:49 +01:00
|
|
|
|
pool: Arc<PgPool>,
|
2026-02-24 19:28:00 +01:00
|
|
|
|
/// Isolated maintenance pool for long-running operations
|
|
|
|
|
|
/// (verify_integrity, garbage_collect) that must never starve the primary.
|
|
|
|
|
|
maintenance_pool: Arc<PgPool>,
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl DedupService {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Create a new dedup service backed by PostgreSQL.
|
2026-02-24 19:28:00 +01:00
|
|
|
|
///
|
|
|
|
|
|
/// * `pool` — primary pool for request-path operations.
|
|
|
|
|
|
/// * `maintenance_pool` — isolated pool for verify_integrity / garbage_collect.
|
|
|
|
|
|
pub fn new(storage_root: &Path, pool: Arc<PgPool>, maintenance_pool: Arc<PgPool>) -> Self {
|
2026-02-14 01:29:34 +01:00
|
|
|
|
let blob_root = storage_root.join(".blobs");
|
|
|
|
|
|
let temp_root = storage_root.join(".dedup_temp");
|
|
|
|
|
|
|
|
|
|
|
|
Self {
|
|
|
|
|
|
blob_root,
|
|
|
|
|
|
temp_root,
|
2026-02-14 19:30:49 +01:00
|
|
|
|
pool,
|
2026-02-24 19:28:00 +01:00
|
|
|
|
maintenance_pool,
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Initialize the service (create blob directories on the filesystem).
|
|
|
|
|
|
pub async fn initialize(&self) -> Result<(), DomainError> {
|
2026-02-14 01:29:34 +01:00
|
|
|
|
// Create directories
|
2026-02-14 19:30:49 +01:00
|
|
|
|
fs::create_dir_all(&self.blob_root)
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(DomainError::from)?;
|
|
|
|
|
|
fs::create_dir_all(&self.temp_root)
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(DomainError::from)?;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
|
|
|
|
|
// Create hash prefix directories (00-ff)
|
|
|
|
|
|
for i in 0..=255u8 {
|
|
|
|
|
|
let prefix = format!("{:02x}", i);
|
2026-02-14 19:30:49 +01:00
|
|
|
|
fs::create_dir_all(self.blob_root.join(&prefix))
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(DomainError::from)?;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// Log existing blob stats from PG
|
|
|
|
|
|
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM storage.blobs")
|
|
|
|
|
|
.fetch_one(self.pool.as_ref())
|
|
|
|
|
|
.await
|
|
|
|
|
|
.unwrap_or(0);
|
|
|
|
|
|
|
|
|
|
|
|
let total_bytes: i64 =
|
|
|
|
|
|
sqlx::query_scalar("SELECT COALESCE(SUM(size), 0) FROM storage.blobs")
|
|
|
|
|
|
.fetch_one(self.pool.as_ref())
|
|
|
|
|
|
.await
|
|
|
|
|
|
.unwrap_or(0);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
|
|
|
|
|
tracing::info!(
|
2026-02-14 19:30:49 +01:00
|
|
|
|
"Dedup service initialized (PostgreSQL-backed): {} blobs, {} bytes stored",
|
|
|
|
|
|
count,
|
|
|
|
|
|
total_bytes
|
2026-02-14 01:29:34 +01:00
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// ── Path helpers ─────────────────────────────────────────────
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Get the blob path for a given hash.
|
2026-02-14 01:29:34 +01:00
|
|
|
|
pub fn blob_path(&self, hash: &str) -> PathBuf {
|
|
|
|
|
|
let prefix = &hash[0..2];
|
|
|
|
|
|
self.blob_root.join(prefix).join(format!("{}.blob", hash))
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// ── Hash helpers ─────────────────────────────────────────────
|
|
|
|
|
|
|
2026-03-01 21:47:39 +01:00
|
|
|
|
/// Calculate BLAKE3 hash of content (~5× faster than SHA-256).
|
2026-02-14 01:29:34 +01:00
|
|
|
|
pub fn hash_bytes(content: &[u8]) -> String {
|
2026-03-01 21:47:39 +01:00
|
|
|
|
blake3::hash(content).to_hex().to_string()
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-01 21:47:39 +01:00
|
|
|
|
/// Calculate BLAKE3 hash of a file (~5× faster than SHA-256).
|
2026-02-23 00:51:46 +01:00
|
|
|
|
///
|
|
|
|
|
|
/// Runs entirely on `spawn_blocking` with synchronous I/O so the Tokio
|
|
|
|
|
|
/// worker threads are never blocked by CPU-bound hashing. Uses 1 MB
|
2026-03-01 21:47:39 +01:00
|
|
|
|
/// reads for optimal syscall-to-throughput ratio.
|
2026-02-14 01:29:34 +01:00
|
|
|
|
pub async fn hash_file(path: &Path) -> std::io::Result<String> {
|
2026-02-23 00:51:46 +01:00
|
|
|
|
let path = path.to_path_buf();
|
|
|
|
|
|
tokio::task::spawn_blocking(move || {
|
|
|
|
|
|
use std::io::Read;
|
|
|
|
|
|
|
|
|
|
|
|
let mut file = std::fs::File::open(&path)?;
|
2026-03-01 21:47:39 +01:00
|
|
|
|
let mut hasher = blake3::Hasher::new();
|
2026-02-23 00:51:46 +01:00
|
|
|
|
let mut buffer = vec![0u8; HASH_BLOCK_SIZE];
|
|
|
|
|
|
|
|
|
|
|
|
loop {
|
|
|
|
|
|
let n = file.read(&mut buffer)?;
|
|
|
|
|
|
if n == 0 {
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
hasher.update(&buffer[..n]);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-01 21:47:39 +01:00
|
|
|
|
Ok(hasher.finalize().to_hex().to_string())
|
2026-02-23 00:51:46 +01:00
|
|
|
|
})
|
|
|
|
|
|
.await
|
|
|
|
|
|
.expect("hash_file: spawn_blocking task panicked")
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// ── Core store operations ────────────────────────────────────
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-24 16:11:52 +01:00
|
|
|
|
/// Maximum payload accepted by `store_bytes`. Anything larger
|
|
|
|
|
|
/// should use `store_from_file` (streaming — constant RAM).
|
|
|
|
|
|
const MAX_STORE_BYTES: usize = 10 * 1024 * 1024; // 10 MB
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Store content with deduplication (from bytes).
|
|
|
|
|
|
///
|
2026-02-25 23:31:51 +01:00
|
|
|
|
/// **Write-first strategy**: the blob file is written to disk *before*
|
|
|
|
|
|
/// touching PostgreSQL, so the PG connection is never held during I/O.
|
|
|
|
|
|
/// The database operation is a single `INSERT … ON CONFLICT` upsert
|
|
|
|
|
|
/// (~2-4 ms) instead of `SELECT FOR UPDATE` + write + commit.
|
2026-02-24 16:11:52 +01:00
|
|
|
|
///
|
|
|
|
|
|
/// **Guard**: rejects payloads >10 MB. Large content must go through
|
|
|
|
|
|
/// `store_from_file` which streams from disk with constant RAM.
|
2026-02-14 01:29:34 +01:00
|
|
|
|
pub async fn store_bytes(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
content: &[u8],
|
|
|
|
|
|
content_type: Option<String>,
|
2026-02-14 19:30:49 +01:00
|
|
|
|
) -> Result<DedupResultDto, DomainError> {
|
2026-02-24 16:11:52 +01:00
|
|
|
|
if content.len() > Self::MAX_STORE_BYTES {
|
|
|
|
|
|
return Err(DomainError::internal_error(
|
|
|
|
|
|
"Dedup",
|
|
|
|
|
|
format!(
|
|
|
|
|
|
"store_bytes called with {} bytes (max {}). Use store_from_file for large content.",
|
|
|
|
|
|
content.len(),
|
|
|
|
|
|
Self::MAX_STORE_BYTES
|
|
|
|
|
|
),
|
|
|
|
|
|
));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 01:29:34 +01:00
|
|
|
|
let size = content.len() as u64;
|
|
|
|
|
|
let hash = Self::hash_bytes(content);
|
2026-02-25 23:31:51 +01:00
|
|
|
|
let blob_path = self.blob_path(&hash);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
// ── Phase 1: Write blob to disk (NO PG connection held) ─────
|
|
|
|
|
|
//
|
|
|
|
|
|
// Content-addressable: if two writers race for the same hash,
|
|
|
|
|
|
// both produce identical files. The rename is atomic on the
|
|
|
|
|
|
// same filesystem; if it fails because the other writer won,
|
|
|
|
|
|
// we just discard our temp file — the blob is already there.
|
|
|
|
|
|
if !blob_path.exists() {
|
2026-03-02 00:12:33 +01:00
|
|
|
|
// Parent directory (xx/) guaranteed to exist — created by initialize()
|
2026-02-25 23:31:51 +01:00
|
|
|
|
let temp_path = self.temp_root.join(format!("{}.tmp", uuid::Uuid::new_v4()));
|
|
|
|
|
|
fs::write(&temp_path, content).await.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to write temp blob: {}", e))
|
2026-02-14 19:30:49 +01:00
|
|
|
|
})?;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
if let Err(e) = fs::rename(&temp_path, &blob_path).await {
|
|
|
|
|
|
// Another writer already placed the blob — discard ours
|
|
|
|
|
|
let _ = fs::remove_file(&temp_path).await;
|
|
|
|
|
|
tracing::debug!("Blob file already placed by concurrent writer: {}", e);
|
|
|
|
|
|
}
|
2026-02-24 13:06:40 +01:00
|
|
|
|
}
|
2026-02-14 19:30:49 +01:00
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
// ── Phase 2: Single atomic upsert (~2-4 ms, no explicit TX) ─
|
|
|
|
|
|
//
|
|
|
|
|
|
// `INSERT … ON CONFLICT` is executed as a single implicit
|
|
|
|
|
|
// transaction by PostgreSQL. RETURNING ref_count tells us
|
|
|
|
|
|
// whether this was a new blob (ref_count = 1) or a dedup hit.
|
|
|
|
|
|
let ref_count: i32 = sqlx::query_scalar(
|
2026-02-14 19:30:49 +01:00
|
|
|
|
"INSERT INTO storage.blobs (hash, size, ref_count, content_type)
|
|
|
|
|
|
VALUES ($1, $2, 1, $3)
|
2026-02-25 23:31:51 +01:00
|
|
|
|
ON CONFLICT (hash) DO UPDATE SET ref_count = storage.blobs.ref_count + 1
|
|
|
|
|
|
RETURNING ref_count",
|
2026-02-14 19:30:49 +01:00
|
|
|
|
)
|
|
|
|
|
|
.bind(&hash)
|
|
|
|
|
|
.bind(size as i64)
|
|
|
|
|
|
.bind(&content_type)
|
2026-02-25 23:31:51 +01:00
|
|
|
|
.fetch_one(self.pool.as_ref())
|
2026-02-14 19:30:49 +01:00
|
|
|
|
.await
|
|
|
|
|
|
.map_err(|e| {
|
2026-02-25 23:31:51 +01:00
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to upsert blob: {}", e))
|
2026-02-14 19:30:49 +01:00
|
|
|
|
})?;
|
|
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
if ref_count > 1 {
|
|
|
|
|
|
tracing::info!("DEDUP HIT: {} ({} bytes saved)", &hash[..12], size);
|
|
|
|
|
|
Ok(DedupResultDto::ExistingBlob {
|
|
|
|
|
|
hash,
|
|
|
|
|
|
size,
|
|
|
|
|
|
blob_path,
|
|
|
|
|
|
saved_bytes: size,
|
|
|
|
|
|
})
|
|
|
|
|
|
} else {
|
|
|
|
|
|
tracing::info!("NEW BLOB: {} ({} bytes)", &hash[..12], size);
|
|
|
|
|
|
Ok(DedupResultDto::NewBlob {
|
|
|
|
|
|
hash,
|
|
|
|
|
|
size,
|
|
|
|
|
|
blob_path,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Store content with deduplication (streaming from file).
|
2026-02-25 23:31:51 +01:00
|
|
|
|
///
|
|
|
|
|
|
/// **Write-first strategy**: the source file is moved/copied to the
|
|
|
|
|
|
/// blob store *before* touching PostgreSQL, so the PG connection is
|
|
|
|
|
|
/// never held during disk I/O.
|
2026-02-15 17:53:25 +01:00
|
|
|
|
///
|
|
|
|
|
|
/// If `pre_computed_hash` is `Some`, the file will NOT be re-read for
|
2026-03-02 02:13:08 +01:00
|
|
|
|
/// BLAKE3 — saving one full sequential read (the biggest I/O win).
|
2026-02-14 01:29:34 +01:00
|
|
|
|
pub async fn store_from_file(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
source_path: &Path,
|
|
|
|
|
|
content_type: Option<String>,
|
2026-02-15 17:53:25 +01:00
|
|
|
|
pre_computed_hash: Option<String>,
|
2026-02-14 19:30:49 +01:00
|
|
|
|
) -> Result<DedupResultDto, DomainError> {
|
2026-02-14 01:29:34 +01:00
|
|
|
|
let file_size = fs::metadata(source_path)
|
|
|
|
|
|
.await
|
2026-02-14 19:30:49 +01:00
|
|
|
|
.map_err(|e| {
|
2026-02-15 18:04:32 +01:00
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to get file metadata: {}", e))
|
2026-02-14 19:30:49 +01:00
|
|
|
|
})?
|
2026-02-14 01:29:34 +01:00
|
|
|
|
.len();
|
|
|
|
|
|
|
2026-02-15 17:53:25 +01:00
|
|
|
|
// Use pre-computed hash if available, otherwise calculate (streaming)
|
|
|
|
|
|
let hash = match pre_computed_hash {
|
|
|
|
|
|
Some(h) => h,
|
|
|
|
|
|
None => Self::hash_file(source_path)
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(DomainError::from)?,
|
|
|
|
|
|
};
|
2026-02-14 19:30:49 +01:00
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
let blob_path = self.blob_path(&hash);
|
2026-02-14 19:30:49 +01:00
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
// ── Phase 1: Move/place blob on disk (NO PG connection held) ─
|
|
|
|
|
|
//
|
|
|
|
|
|
// If the blob file already exists on disk, the source is simply
|
|
|
|
|
|
// deleted — the file content is identical by definition.
|
|
|
|
|
|
if blob_path.exists() {
|
|
|
|
|
|
// Blob already on disk — discard the source file
|
|
|
|
|
|
let _ = fs::remove_file(source_path).await;
|
|
|
|
|
|
} else {
|
2026-03-02 00:12:33 +01:00
|
|
|
|
// Parent directory (xx/) guaranteed to exist — created by initialize()
|
2026-02-14 19:30:49 +01:00
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
// rename is atomic on the same filesystem. If source and blob
|
|
|
|
|
|
// dirs live on different filesystems (rare), this falls back to
|
|
|
|
|
|
// copy+delete which is slower but still correct.
|
|
|
|
|
|
if let Err(e) = fs::rename(source_path, &blob_path).await {
|
|
|
|
|
|
// Another writer may have placed the blob concurrently
|
|
|
|
|
|
if blob_path.exists() {
|
|
|
|
|
|
let _ = fs::remove_file(source_path).await;
|
|
|
|
|
|
tracing::debug!("Blob file placed by concurrent writer: {}", e);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return Err(DomainError::internal_error(
|
|
|
|
|
|
"Dedup",
|
|
|
|
|
|
format!("Failed to move file to blob store: {}", e),
|
|
|
|
|
|
));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
// ── Phase 2: Single atomic upsert (~2-4 ms, no explicit TX) ─
|
|
|
|
|
|
let ref_count: i32 = sqlx::query_scalar(
|
2026-02-14 19:30:49 +01:00
|
|
|
|
"INSERT INTO storage.blobs (hash, size, ref_count, content_type)
|
|
|
|
|
|
VALUES ($1, $2, 1, $3)
|
2026-02-25 23:31:51 +01:00
|
|
|
|
ON CONFLICT (hash) DO UPDATE SET ref_count = storage.blobs.ref_count + 1
|
|
|
|
|
|
RETURNING ref_count",
|
2026-02-14 19:30:49 +01:00
|
|
|
|
)
|
|
|
|
|
|
.bind(&hash)
|
|
|
|
|
|
.bind(file_size as i64)
|
|
|
|
|
|
.bind(&content_type)
|
2026-02-25 23:31:51 +01:00
|
|
|
|
.fetch_one(self.pool.as_ref())
|
2026-02-14 19:30:49 +01:00
|
|
|
|
.await
|
|
|
|
|
|
.map_err(|e| {
|
2026-02-25 23:31:51 +01:00
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to upsert blob: {}", e))
|
2026-02-14 19:30:49 +01:00
|
|
|
|
})?;
|
|
|
|
|
|
|
2026-02-25 23:31:51 +01:00
|
|
|
|
if ref_count > 1 {
|
|
|
|
|
|
tracing::info!(
|
|
|
|
|
|
"DEDUP HIT (file): {} ({} bytes saved)",
|
|
|
|
|
|
&hash[..12],
|
|
|
|
|
|
file_size
|
|
|
|
|
|
);
|
|
|
|
|
|
Ok(DedupResultDto::ExistingBlob {
|
|
|
|
|
|
hash,
|
|
|
|
|
|
size: file_size,
|
|
|
|
|
|
blob_path,
|
|
|
|
|
|
saved_bytes: file_size,
|
|
|
|
|
|
})
|
|
|
|
|
|
} else {
|
|
|
|
|
|
tracing::info!("NEW BLOB (file): {} ({} bytes)", &hash[..12], file_size);
|
|
|
|
|
|
Ok(DedupResultDto::NewBlob {
|
|
|
|
|
|
hash,
|
|
|
|
|
|
size: file_size,
|
|
|
|
|
|
blob_path,
|
|
|
|
|
|
})
|
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// ── Reference counting ───────────────────────────────────────
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Check if a blob with the given hash exists in the PG index.
|
|
|
|
|
|
pub async fn blob_exists(&self, hash: &str) -> bool {
|
|
|
|
|
|
sqlx::query_scalar::<_, bool>("SELECT EXISTS(SELECT 1 FROM storage.blobs WHERE hash = $1)")
|
|
|
|
|
|
.bind(hash)
|
|
|
|
|
|
.fetch_one(self.pool.as_ref())
|
|
|
|
|
|
.await
|
|
|
|
|
|
.unwrap_or(false)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Get metadata for a blob from PostgreSQL.
|
|
|
|
|
|
pub async fn get_blob_metadata(&self, hash: &str) -> Option<BlobMetadataDto> {
|
|
|
|
|
|
let row = sqlx::query_as::<_, (String, i64, i32, Option<String>)>(
|
|
|
|
|
|
"SELECT hash, size, ref_count, content_type FROM storage.blobs WHERE hash = $1",
|
|
|
|
|
|
)
|
|
|
|
|
|
.bind(hash)
|
|
|
|
|
|
.fetch_optional(self.pool.as_ref())
|
|
|
|
|
|
.await
|
|
|
|
|
|
.ok()
|
|
|
|
|
|
.flatten()?;
|
|
|
|
|
|
|
|
|
|
|
|
Some(BlobMetadataDto {
|
|
|
|
|
|
hash: row.0,
|
|
|
|
|
|
size: row.1 as u64,
|
|
|
|
|
|
ref_count: row.2 as u32,
|
|
|
|
|
|
content_type: row.3,
|
|
|
|
|
|
})
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Add a reference to a blob (increment ref_count).
|
|
|
|
|
|
pub async fn add_reference(&self, hash: &str) -> Result<(), DomainError> {
|
|
|
|
|
|
let rows_affected =
|
|
|
|
|
|
sqlx::query("UPDATE storage.blobs SET ref_count = ref_count + 1 WHERE hash = $1")
|
|
|
|
|
|
.bind(hash)
|
|
|
|
|
|
.execute(self.pool.as_ref())
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error(
|
|
|
|
|
|
"Dedup",
|
|
|
|
|
|
format!("Failed to increment ref_count: {}", e),
|
|
|
|
|
|
)
|
|
|
|
|
|
})?
|
|
|
|
|
|
.rows_affected();
|
|
|
|
|
|
|
|
|
|
|
|
if rows_affected == 0 {
|
|
|
|
|
|
return Err(DomainError::new(
|
|
|
|
|
|
ErrorKind::NotFound,
|
|
|
|
|
|
"Blob",
|
|
|
|
|
|
format!("Blob not found: {}", hash),
|
|
|
|
|
|
));
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Remove a reference from a blob.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Uses a single transaction with `SELECT … FOR UPDATE` to atomically
|
|
|
|
|
|
/// decrement ref_count and delete the row + blob file if it reaches 0.
|
|
|
|
|
|
/// Returns `true` if the blob was deleted.
|
|
|
|
|
|
pub async fn remove_reference(&self, hash: &str) -> Result<bool, DomainError> {
|
|
|
|
|
|
let mut tx = self.pool.begin().await.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to begin transaction: {}", e))
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
// Lock the row exclusively — prevents concurrent store_bytes from
|
|
|
|
|
|
// incrementing ref_count while we might be deleting
|
|
|
|
|
|
let row = sqlx::query_as::<_, (i32, i64)>(
|
|
|
|
|
|
"SELECT ref_count, size FROM storage.blobs WHERE hash = $1 FOR UPDATE",
|
|
|
|
|
|
)
|
|
|
|
|
|
.bind(hash)
|
|
|
|
|
|
.fetch_optional(&mut *tx)
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to lock blob row: {}", e))
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
let Some((ref_count, _size)) = row else {
|
|
|
|
|
|
// Blob doesn't exist — nothing to do
|
|
|
|
|
|
tx.rollback().await.ok();
|
|
|
|
|
|
return Ok(false);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
};
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
let new_ref_count = (ref_count - 1).max(0);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
if new_ref_count == 0 {
|
|
|
|
|
|
// Last reference — delete row from PG
|
|
|
|
|
|
sqlx::query("DELETE FROM storage.blobs WHERE hash = $1")
|
|
|
|
|
|
.bind(hash)
|
|
|
|
|
|
.execute(&mut *tx)
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error(
|
|
|
|
|
|
"Dedup",
|
|
|
|
|
|
format!("Failed to delete blob row: {}", e),
|
|
|
|
|
|
)
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
tx.commit().await.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to commit: {}", e))
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
// Delete blob file AFTER committing PG — the row is gone, so no
|
|
|
|
|
|
// concurrent store_bytes can resurrect a reference to this hash.
|
|
|
|
|
|
let blob_path = self.blob_path(hash);
|
|
|
|
|
|
if let Err(e) = fs::remove_file(&blob_path).await {
|
|
|
|
|
|
tracing::warn!("Failed to delete blob file {}: {}", hash, e);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
tracing::info!("BLOB DELETED: {} (no more references)", &hash[..12]);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
Ok(true)
|
|
|
|
|
|
} else {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// Still has references — just decrement
|
|
|
|
|
|
sqlx::query("UPDATE storage.blobs SET ref_count = $1 WHERE hash = $2")
|
|
|
|
|
|
.bind(new_ref_count)
|
|
|
|
|
|
.bind(hash)
|
|
|
|
|
|
.execute(&mut *tx)
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error(
|
|
|
|
|
|
"Dedup",
|
|
|
|
|
|
format!("Failed to decrement ref_count: {}", e),
|
|
|
|
|
|
)
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
tx.commit().await.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to commit: {}", e))
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
tracing::debug!("Reference removed from blob {}", &hash[..12]);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
Ok(false)
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// ── Read operations ──────────────────────────────────────────
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-15 17:53:25 +01:00
|
|
|
|
/// Stream blob content in 64 KB chunks — constant memory (~64 KB per stream).
|
|
|
|
|
|
///
|
|
|
|
|
|
/// A 1 GB file uses the same ~64 KB as a 1 KB file.
|
|
|
|
|
|
pub async fn read_blob_stream(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
hash: &str,
|
|
|
|
|
|
) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>, DomainError>
|
|
|
|
|
|
{
|
|
|
|
|
|
let blob_path = self.blob_path(hash);
|
|
|
|
|
|
let file = File::open(&blob_path).await.map_err(|e| {
|
|
|
|
|
|
DomainError::new(
|
|
|
|
|
|
ErrorKind::NotFound,
|
|
|
|
|
|
"Blob",
|
|
|
|
|
|
format!("Failed to open blob {}: {}", hash, e),
|
|
|
|
|
|
)
|
|
|
|
|
|
})?;
|
2026-02-15 18:04:32 +01:00
|
|
|
|
Ok(Box::pin(ReaderStream::with_capacity(
|
|
|
|
|
|
file,
|
|
|
|
|
|
STREAM_CHUNK_SIZE,
|
|
|
|
|
|
)))
|
2026-02-15 17:53:25 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Stream a byte range of a blob — only reads the requested portion.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Uses seek + take so a 1 MB range request on a 1 GB file only reads 1 MB.
|
|
|
|
|
|
pub async fn read_blob_range_stream(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
hash: &str,
|
|
|
|
|
|
start: u64,
|
|
|
|
|
|
end: Option<u64>,
|
|
|
|
|
|
) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>, DomainError>
|
|
|
|
|
|
{
|
|
|
|
|
|
let blob_path = self.blob_path(hash);
|
|
|
|
|
|
let mut file = File::open(&blob_path).await.map_err(|e| {
|
|
|
|
|
|
DomainError::new(
|
|
|
|
|
|
ErrorKind::NotFound,
|
|
|
|
|
|
"Blob",
|
|
|
|
|
|
format!("Failed to open blob {}: {}", hash, e),
|
|
|
|
|
|
)
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
// Seek to the start position
|
|
|
|
|
|
file.seek(std::io::SeekFrom::Start(start))
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error("Blob", format!("Failed to seek in blob: {}", e))
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
// If an end is specified, limit the read with take()
|
|
|
|
|
|
if let Some(end_pos) = end {
|
|
|
|
|
|
let limit = end_pos.saturating_sub(start);
|
|
|
|
|
|
let limited = file.take(limit);
|
2026-02-15 18:04:32 +01:00
|
|
|
|
Ok(Box::pin(ReaderStream::with_capacity(
|
|
|
|
|
|
limited,
|
|
|
|
|
|
STREAM_CHUNK_SIZE,
|
|
|
|
|
|
)))
|
2026-02-15 17:53:25 +01:00
|
|
|
|
} else {
|
2026-02-15 18:04:32 +01:00
|
|
|
|
Ok(Box::pin(ReaderStream::with_capacity(
|
|
|
|
|
|
file,
|
|
|
|
|
|
STREAM_CHUNK_SIZE,
|
|
|
|
|
|
)))
|
2026-02-15 17:53:25 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// Get the size of a blob without reading its content.
|
|
|
|
|
|
pub async fn blob_size(&self, hash: &str) -> Result<u64, DomainError> {
|
|
|
|
|
|
let blob_path = self.blob_path(hash);
|
|
|
|
|
|
let meta = fs::metadata(&blob_path).await.map_err(|e| {
|
|
|
|
|
|
DomainError::new(
|
|
|
|
|
|
ErrorKind::NotFound,
|
|
|
|
|
|
"Blob",
|
|
|
|
|
|
format!("Failed to stat blob {}: {}", hash, e),
|
|
|
|
|
|
)
|
|
|
|
|
|
})?;
|
|
|
|
|
|
Ok(meta.len())
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// ── Statistics (computed from PG) ────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
/// Get deduplication statistics by querying PostgreSQL.
|
|
|
|
|
|
pub async fn get_stats(&self) -> DedupStatsDto {
|
|
|
|
|
|
let row = sqlx::query_as::<_, (i64, i64, i64)>(
|
|
|
|
|
|
"SELECT
|
|
|
|
|
|
COUNT(*) AS total_blobs,
|
|
|
|
|
|
COALESCE(SUM(size), 0) AS total_bytes_stored,
|
|
|
|
|
|
COALESCE(SUM(size::BIGINT * ref_count), 0) AS total_bytes_referenced
|
|
|
|
|
|
FROM storage.blobs",
|
|
|
|
|
|
)
|
|
|
|
|
|
.fetch_one(self.pool.as_ref())
|
|
|
|
|
|
.await
|
|
|
|
|
|
.unwrap_or((0, 0, 0));
|
|
|
|
|
|
|
|
|
|
|
|
let total_blobs = row.0 as u64;
|
|
|
|
|
|
let total_bytes_stored = row.1 as u64;
|
|
|
|
|
|
let total_bytes_referenced = row.2 as u64;
|
|
|
|
|
|
let bytes_saved = total_bytes_referenced.saturating_sub(total_bytes_stored);
|
|
|
|
|
|
let dedup_ratio = if total_bytes_stored > 0 {
|
|
|
|
|
|
total_bytes_referenced as f64 / total_bytes_stored as f64
|
|
|
|
|
|
} else {
|
|
|
|
|
|
1.0
|
|
|
|
|
|
};
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
DedupStatsDto {
|
|
|
|
|
|
total_blobs,
|
|
|
|
|
|
total_bytes_stored,
|
|
|
|
|
|
total_bytes_referenced,
|
|
|
|
|
|
bytes_saved,
|
|
|
|
|
|
dedup_hits: 0, // Not tracked per-session — derive from SUM(ref_count - 1)
|
|
|
|
|
|
dedup_ratio,
|
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// ── Maintenance ──────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
/// Verify integrity of all blobs (PG index vs filesystem).
|
2026-02-23 23:43:59 +01:00
|
|
|
|
///
|
2026-02-24 10:45:38 +01:00
|
|
|
|
/// Uses a **streaming cursor** (`fetch()`) so memory stays O(batch)
|
|
|
|
|
|
/// instead of O(total_blobs). Blobs are verified in micro-batches
|
|
|
|
|
|
/// of `VERIFY_CONCURRENCY` using `buffer_unordered`.
|
2026-02-14 19:30:49 +01:00
|
|
|
|
pub async fn verify_integrity(&self) -> Result<Vec<String>, DomainError> {
|
2026-02-23 23:43:59 +01:00
|
|
|
|
/// Max blobs verified concurrently. Each spawns a blocking
|
2026-03-02 02:13:08 +01:00
|
|
|
|
/// thread for BLAKE3 so this also caps blocking-pool pressure.
|
2026-02-23 23:43:59 +01:00
|
|
|
|
const VERIFY_CONCURRENCY: usize = 16;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-24 10:45:38 +01:00
|
|
|
|
let mut row_stream = sqlx::query_as::<_, (String, i64)>(
|
2026-02-14 19:30:49 +01:00
|
|
|
|
"SELECT hash, size FROM storage.blobs ORDER BY hash",
|
|
|
|
|
|
)
|
2026-02-24 19:28:00 +01:00
|
|
|
|
.fetch(self.maintenance_pool.as_ref());
|
2026-02-24 10:45:38 +01:00
|
|
|
|
|
|
|
|
|
|
let mut total = 0usize;
|
|
|
|
|
|
let mut corrupted = Vec::<String>::new();
|
|
|
|
|
|
let mut batch = Vec::with_capacity(VERIFY_CONCURRENCY);
|
|
|
|
|
|
|
|
|
|
|
|
loop {
|
|
|
|
|
|
let maybe_row = row_stream.try_next().await.map_err(|e| {
|
|
|
|
|
|
DomainError::internal_error("Dedup", format!("Failed to list blobs: {}", e))
|
|
|
|
|
|
})?;
|
|
|
|
|
|
|
|
|
|
|
|
let is_done = maybe_row.is_none();
|
2026-02-14 19:30:49 +01:00
|
|
|
|
|
2026-02-24 10:45:38 +01:00
|
|
|
|
if let Some(row) = maybe_row {
|
|
|
|
|
|
total += 1;
|
|
|
|
|
|
batch.push(row);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Flush when batch is full or we've exhausted the cursor
|
|
|
|
|
|
if batch.len() >= VERIFY_CONCURRENCY || (is_done && !batch.is_empty()) {
|
|
|
|
|
|
let blob_root = self.blob_root.clone();
|
|
|
|
|
|
let current_batch =
|
|
|
|
|
|
std::mem::replace(&mut batch, Vec::with_capacity(VERIFY_CONCURRENCY));
|
|
|
|
|
|
|
|
|
|
|
|
let issues: Vec<String> = stream::iter(current_batch)
|
|
|
|
|
|
.map(move |(hash, expected_size)| {
|
|
|
|
|
|
let blob_root = blob_root.clone();
|
|
|
|
|
|
async move {
|
|
|
|
|
|
let prefix = &hash[0..2];
|
2026-02-25 10:28:34 +01:00
|
|
|
|
let blob_path = blob_root.join(prefix).join(format!("{}.blob", hash));
|
2026-02-24 10:45:38 +01:00
|
|
|
|
|
|
|
|
|
|
let mut issues = Vec::new();
|
|
|
|
|
|
|
2026-02-24 13:06:40 +01:00
|
|
|
|
// Single async metadata() replaces the previous
|
|
|
|
|
|
// blocking .exists() + separate metadata() — one
|
|
|
|
|
|
// stat() syscall instead of two, and non-blocking.
|
|
|
|
|
|
let file_meta = match fs::metadata(&blob_path).await {
|
|
|
|
|
|
Ok(m) => m,
|
|
|
|
|
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
|
|
|
|
|
issues.push(format!("{}: file missing on disk", hash));
|
|
|
|
|
|
return issues;
|
|
|
|
|
|
}
|
|
|
|
|
|
Err(e) => {
|
|
|
|
|
|
issues.push(format!("{}: metadata error ({})", hash, e));
|
|
|
|
|
|
return issues;
|
|
|
|
|
|
}
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
// Check size
|
|
|
|
|
|
if file_meta.len() != expected_size as u64 {
|
|
|
|
|
|
issues.push(format!(
|
|
|
|
|
|
"{}: size mismatch (expected: {}, actual: {})",
|
|
|
|
|
|
hash,
|
|
|
|
|
|
expected_size,
|
|
|
|
|
|
file_meta.len(),
|
|
|
|
|
|
));
|
2026-02-24 10:45:38 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Verify hash
|
|
|
|
|
|
match Self::hash_file(&blob_path).await {
|
|
|
|
|
|
Ok(actual_hash) => {
|
|
|
|
|
|
if actual_hash != hash {
|
|
|
|
|
|
issues.push(format!(
|
|
|
|
|
|
"{}: hash mismatch (actual: {})",
|
|
|
|
|
|
hash, actual_hash,
|
|
|
|
|
|
));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
Err(e) => {
|
|
|
|
|
|
issues.push(format!("{}: read error ({})", hash, e));
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
issues
|
2026-02-23 23:43:59 +01:00
|
|
|
|
}
|
2026-02-24 10:45:38 +01:00
|
|
|
|
})
|
|
|
|
|
|
.buffer_unordered(VERIFY_CONCURRENCY)
|
|
|
|
|
|
.flat_map(stream::iter)
|
|
|
|
|
|
.collect()
|
|
|
|
|
|
.await;
|
|
|
|
|
|
|
|
|
|
|
|
corrupted.extend(issues);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if is_done {
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
|
|
|
|
|
if corrupted.is_empty() {
|
2026-02-23 23:43:59 +01:00
|
|
|
|
tracing::info!("Integrity check passed for {} blobs", total);
|
2026-02-14 01:29:34 +01:00
|
|
|
|
} else {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
tracing::warn!("Integrity check found {} issues", corrupted.len());
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
Ok(corrupted)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 19:30:49 +01:00
|
|
|
|
/// Garbage collect orphaned blobs (ref_count = 0).
|
|
|
|
|
|
///
|
2026-02-25 23:54:09 +01:00
|
|
|
|
/// Deletes in small batches (BATCH_SIZE rows per TX) so that each
|
|
|
|
|
|
/// transaction lasts only a few milliseconds. This avoids:
|
|
|
|
|
|
/// - massive row-lock accumulation in PostgreSQL,
|
|
|
|
|
|
/// - WAL bloat from a single giant DELETE,
|
|
|
|
|
|
/// - blocking concurrent uploads that touch `storage.blobs`.
|
|
|
|
|
|
///
|
|
|
|
|
|
/// Blob files are removed **after** each batch commits, so a crash
|
|
|
|
|
|
/// mid-GC only leaves a few orphan files on disk (reclaimed next run).
|
2026-02-14 19:30:49 +01:00
|
|
|
|
pub async fn garbage_collect(&self) -> Result<(u64, u64), DomainError> {
|
2026-02-25 23:54:09 +01:00
|
|
|
|
/// Max rows deleted per mini-transaction.
|
|
|
|
|
|
const BATCH_SIZE: i64 = 500;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-25 23:54:09 +01:00
|
|
|
|
let mut total_deleted = 0u64;
|
|
|
|
|
|
let mut total_bytes = 0u64;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
|
2026-02-25 23:54:09 +01:00
|
|
|
|
loop {
|
|
|
|
|
|
// Each DELETE is its own implicit TX — short and bounded.
|
|
|
|
|
|
// The `ctid` sub-select is the canonical way to do
|
|
|
|
|
|
// `DELETE … LIMIT` in PostgreSQL.
|
|
|
|
|
|
let batch: Vec<(String, i64)> = sqlx::query_as(
|
|
|
|
|
|
"DELETE FROM storage.blobs
|
|
|
|
|
|
WHERE ctid = ANY(
|
|
|
|
|
|
SELECT ctid FROM storage.blobs
|
|
|
|
|
|
WHERE ref_count = 0
|
|
|
|
|
|
LIMIT $1
|
|
|
|
|
|
)
|
|
|
|
|
|
RETURNING hash, size",
|
|
|
|
|
|
)
|
|
|
|
|
|
.bind(BATCH_SIZE)
|
|
|
|
|
|
.fetch_all(self.maintenance_pool.as_ref())
|
|
|
|
|
|
.await
|
2026-02-26 00:47:32 +01:00
|
|
|
|
.map_err(|e| DomainError::internal_error("Dedup", format!("GC batch failed: {e}")))?;
|
2026-02-25 23:54:09 +01:00
|
|
|
|
|
|
|
|
|
|
if batch.is_empty() {
|
|
|
|
|
|
break;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Delete blob files OUTSIDE the TX (already committed).
|
|
|
|
|
|
for (hash, size) in &batch {
|
|
|
|
|
|
let blob_path = self.blob_path(hash);
|
|
|
|
|
|
if let Err(e) = fs::remove_file(&blob_path).await {
|
|
|
|
|
|
tracing::warn!("Failed to delete orphan blob file {hash}: {e}");
|
|
|
|
|
|
}
|
|
|
|
|
|
total_bytes += *size as u64;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
2026-02-25 23:54:09 +01:00
|
|
|
|
total_deleted += batch.len() as u64;
|
|
|
|
|
|
|
|
|
|
|
|
// Yield so uploads / other tasks are not starved.
|
|
|
|
|
|
tokio::task::yield_now().await;
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-25 23:54:09 +01:00
|
|
|
|
if total_deleted > 0 {
|
|
|
|
|
|
tracing::info!("GC: removed {total_deleted} blobs ({total_bytes} bytes)");
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-25 23:54:09 +01:00
|
|
|
|
Ok((total_deleted, total_bytes))
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ─── Port implementation ─────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
|
|
#[async_trait]
|
|
|
|
|
|
impl DedupPort for DedupService {
|
|
|
|
|
|
async fn store_bytes(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
content: &[u8],
|
|
|
|
|
|
content_type: Option<String>,
|
|
|
|
|
|
) -> Result<DedupResultDto, DomainError> {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
self.store_bytes(content, content_type).await
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn store_from_file(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
source_path: &Path,
|
|
|
|
|
|
content_type: Option<String>,
|
2026-02-15 17:53:25 +01:00
|
|
|
|
pre_computed_hash: Option<String>,
|
2026-02-14 01:29:34 +01:00
|
|
|
|
) -> Result<DedupResultDto, DomainError> {
|
2026-02-15 18:04:32 +01:00
|
|
|
|
self.store_from_file(source_path, content_type, pre_computed_hash)
|
|
|
|
|
|
.await
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn blob_exists(&self, hash: &str) -> bool {
|
|
|
|
|
|
self.blob_exists(hash).await
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn get_blob_metadata(&self, hash: &str) -> Option<BlobMetadataDto> {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
self.get_blob_metadata(hash).await
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-15 17:53:25 +01:00
|
|
|
|
async fn read_blob_stream(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
hash: &str,
|
|
|
|
|
|
) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>, DomainError>
|
|
|
|
|
|
{
|
|
|
|
|
|
self.read_blob_stream(hash).await
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn read_blob_range_stream(
|
|
|
|
|
|
&self,
|
|
|
|
|
|
hash: &str,
|
|
|
|
|
|
start: u64,
|
|
|
|
|
|
end: Option<u64>,
|
|
|
|
|
|
) -> Result<Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>, DomainError>
|
|
|
|
|
|
{
|
|
|
|
|
|
self.read_blob_range_stream(hash, start, end).await
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn blob_size(&self, hash: &str) -> Result<u64, DomainError> {
|
|
|
|
|
|
self.blob_size(hash).await
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-14 01:29:34 +01:00
|
|
|
|
async fn add_reference(&self, hash: &str) -> Result<(), DomainError> {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
self.add_reference(hash).await
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn remove_reference(&self, hash: &str) -> Result<bool, DomainError> {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
self.remove_reference(hash).await
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn hash_file(&self, path: &Path) -> Result<String, DomainError> {
|
|
|
|
|
|
DedupService::hash_file(path)
|
|
|
|
|
|
.await
|
|
|
|
|
|
.map_err(DomainError::from)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn get_stats(&self) -> DedupStatsDto {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
self.get_stats().await
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn flush(&self) -> Result<(), DomainError> {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
// No-op: PostgreSQL handles persistence automatically via WAL/commit
|
|
|
|
|
|
Ok(())
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
async fn verify_integrity(&self) -> Result<Vec<String>, DomainError> {
|
2026-02-14 19:30:49 +01:00
|
|
|
|
self.verify_integrity().await
|
2026-02-14 01:29:34 +01:00
|
|
|
|
}
|
|
|
|
|
|
}
|