//! Наблюдения и composition-часть приватного ATDD-стенда Story 3.6. //! //! Подмодуль того же приватного `#[cfg(test)]` фикстура //! `crate::app::resource_test_support` (регистрация в `app.rs` не меняется): физическое //! разделение выполнено только потому, что health-правило репозитория ограничивает файл //! 1000 строками (`scripts/check-rust-code-health.sh`), а базовая часть модуля уже //! содержит HTTP-стенд guard-проверок. Здесь находятся: //! //! * редактирование чувствительных заголовков рукописной диагностики (F5, TL run105); //! * composition-стенд сервисных проверок чтения Resource (F3/F4, TL run105); //! * SQL-наблюдение итогов строк V16 и файловые наблюдения содержимого. //! //! Границы те же, что у корневого файла: `cfg(test)`-only, никакого production API. use std::{path::PathBuf, sync::Arc}; use crank_artifacts::ArtifactStore; use crank_core::resource::ResourceLimits; use crank_registry::PostgresRegistry; use crate::service::resources::ResourcesService; // --------------------------------------------------------------------------- // F5: диагностика не несёт значения чувствительных заголовков // --------------------------------------------------------------------------- /// Значения этих заголовков не попадают в диагностику даже синтетического стенда. const SENSITIVE_HEADERS: [&str; 4] = ["cookie", "set-cookie", "x-csrf-token", "authorization"]; /// Редактирует значения чувствительных заголовков (AGENTS: credentials не в журналах). /// /// Редактирование выполняется **до** сохранения головы, а не при печати (TL run105 F5); /// метод, путь, структура заголовков и статус сохраняются, иначе отказ не отличить от /// ошибки харнесса. pub(crate) fn redact_sensitive_headers(head: &str) -> String { head.split("\r\n") .map(|line| match line.split_once(':') { Some((name, _value)) if SENSITIVE_HEADERS.contains(&name.trim().to_ascii_lowercase().as_str()) => { format!("{name}: ") } _ => line.to_owned(), }) .collect::>() .join("\r\n") } // --------------------------------------------------------------------------- // F3/F4: composition-стенд сервисных проверок чтения Resource // --------------------------------------------------------------------------- /// Изолированная PG-схема вместе с соединением к ней. /// /// Конкретный драйвер допускается только в composition root (`cfg(test)`-фикстура /// вне `service/**`): сервисные тест-модули получают готовые registry/service и /// не называют адаптер хранилища сами (TL run105 F3, FINAL-DISPOSITION run99:47). pub(crate) async fn resource_schema(prefix: &str) -> (String, sqlx::PgPool) { let url = crank_test_support::postgres_schema_url(prefix).await; let pool = sqlx::postgres::PgPoolOptions::new() .max_connections(2) .connect(&url) .await .expect("the isolated test schema must accept connections"); (url, pool) } /// Приватный стенд сервисных проверок чтения Resource: изолированная PG-схема V16, /// приватный artifact root и **готовый** `ResourcesService`. /// /// Драйвер, миграция и сборка store/service живут в composition root, а не в сервисном /// тест-модуле (TL run105 F3; FINAL-DISPOSITION run99:47). pub(crate) struct ResourceServiceHarness { pub service: ResourcesService, pub registry: PostgresRegistry, /// Приватный root содержимого: по нему наблюдаются физические отказы чтения. pub root: PathBuf, } impl ResourceServiceHarness { pub(crate) async fn spawn(name: &str, limit: usize) -> Self { let (database_url, pool) = resource_schema(&format!("story36_integrity_{name}")).await; crank_registry::MigrationAuthority::apply(&pool) .await .expect("V16 must be applicable"); drop(pool); let registry = PostgresRegistry::connect(&database_url) .await .expect("fixture registry must connect"); let root = super::private_storage_root(&format!("integrity_{name}")); let store = ArtifactStore::open(&root).expect("private artifact store must open"); let limits = ResourceLimits::uniform(limit) .expect("the configured test limit must stay inside the storage ceiling"); Self { service: ResourcesService::new(registry.clone(), Arc::new(store), limits), registry, root, } } } // --------------------------------------------------------------------------- // SQL/файловые наблюдения состояния (только composition root) // --------------------------------------------------------------------------- /// Итоги строк V16 `(resources, resource_versions, artifact_sources, artifact_blobs)` — /// наблюдение «отказ без побочных эффектов» (SQL только в composition root). pub(crate) async fn resource_row_counts(pool: &sqlx::PgPool) -> (i64, i64, i64, i64) { sqlx::query_as( "select (select count(*) from resources), (select count(*) from resource_versions), (select count(*) from artifact_sources), (select count(*) from artifact_blobs)", ) .fetch_one(pool) .await .expect("V16 relations must be countable") } /// Физические файлы содержимого под приватным artifact root. pub(crate) fn artifact_files(root: &std::path::Path) -> Vec { let mut files = Vec::new(); let mut pending = vec![root.to_path_buf()]; while let Some(dir) = pending.pop() { let entries = std::fs::read_dir(&dir).expect("the private artifact root must be readable"); for entry in entries { let entry = entry.expect("an artifact entry must be readable"); let path = entry.path(); if path.is_dir() { pending.push(path); } else { files.push(path); } } } files.sort(); files }