feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.
Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
resources/list admission fix for bound template publications.
Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
`just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
a real MCP Inspector 2.12.0 client smoke.
Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
runs only on main), story events run the changed packages, the full workspace suite
stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
release entry of the tag instead of dying with the runner workspace.
Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.
Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
1 parent
1b6db09bd1
commit
54ce770682
357 files changed
+117394
-5115
No files matched your search
@@ -196,6 +196,11 @@ pub enum MetricsServeError {
|
||||
pub(crate) fn install_prometheus_recorder(
|
||||
identity: &ServiceIdentity,
|
||||
) -> Result<PrometheusHandle, MetricsSurfaceError> {
|
||||
let service = MetricService::parse(identity.service())
|
||||
.ok_or(MetricsSurfaceError::RecorderConfiguration)?;
|
||||
if crank_metrics::bound_metric_service() != Some(service) {
|
||||
return Err(MetricsSurfaceError::RecorderConfiguration);
|
||||
}
|
||||
prometheus_builder(identity)?
|
||||
.install_recorder()
|
||||
.map_err(|_| MetricsSurfaceError::RecorderConfiguration)
|
||||
@@ -220,6 +225,10 @@ async fn render_metrics(State(state): State<MetricsState>, headers: HeaderMap) -
|
||||
let Some(_permit) = ScrapePermit::try_acquire(&state.active_scrapes) else {
|
||||
return (StatusCode::SERVICE_UNAVAILABLE, TOO_MANY_SCRAPES).into_response();
|
||||
};
|
||||
// cfg(test)-only точка синхронизации у permit seam'а: в production-сборке
|
||||
// строки нет, поэтому поведение не меняется.
|
||||
#[cfg(test)]
|
||||
crate::prometheus::scrape_barrier::hold().await;
|
||||
let legacy = state.handle.render();
|
||||
let openmetrics = headers
|
||||
.get(header::ACCEPT)
|
||||
@@ -387,89 +396,161 @@ fn token_digest(token: &[u8]) -> [u8; 32] {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod rendering_tests {
|
||||
use std::{
|
||||
sync::{Arc, atomic::AtomicUsize},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
mod rendering_tests;
|
||||
|
||||
use crank_metrics::{ExemplarObservation, ExemplarTraceId};
|
||||
/// cfg(test)-only барьер у scrape-permit seam'а: позволяет детерминированно
|
||||
/// доказать, что допускаются ровно два одновременных scrape, третий
|
||||
/// отвергается, а после release permit освобождается. В production-сборке
|
||||
/// (и в интеграционных тест-бинар��х, где crate компилируется как dependency)
|
||||
/// модуля нет, поэтому семантика не меняется.
|
||||
#[cfg(test)]
|
||||
pub(crate) mod scrape_barrier {
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock};
|
||||
|
||||
use super::{
|
||||
MAX_CONCURRENT_SCRAPES, ScrapePermit, exposition_response, prefers_openmetrics,
|
||||
render_openmetrics,
|
||||
};
|
||||
static STATE: OnceLock<Mutex<State>> = OnceLock::new();
|
||||
|
||||
#[test]
|
||||
fn openmetrics_adds_bounded_exemplar_without_changing_aggregate() {
|
||||
let legacy = "# TYPE crank_http_request_duration_seconds histogram\ncrank_http_request_duration_seconds_bucket{method=\"GET\",route=\"/health\",le=\"0.01\"} 1\ncrank_http_request_duration_seconds_sum{method=\"GET\",route=\"/health\"} 0.007\n";
|
||||
let exemplar = ExemplarObservation {
|
||||
metric: "crank_http_request_duration_seconds",
|
||||
labels: vec![("route", "/health"), ("method", "GET")],
|
||||
bucket_upper_bound: Some(0.01),
|
||||
value: 0.007,
|
||||
trace_id: ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").unwrap(),
|
||||
};
|
||||
let rendered = render_openmetrics(legacy, &[Arc::new(exemplar)]);
|
||||
assert!(rendered.contains("# {trace_id=\"0123456789abcdef0123456789abcdef\"} 0.007"));
|
||||
assert!(rendered.ends_with("# EOF\n"));
|
||||
assert_eq!(rendered.matches(" 1").count(), legacy.matches(" 1").count());
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
enabled: bool,
|
||||
release: bool,
|
||||
parked: usize,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accept_negotiation_is_exact_and_honors_quality_and_version() {
|
||||
assert!(prefers_openmetrics(
|
||||
"application/openmetrics-text; version=1.0.0"
|
||||
));
|
||||
assert!(prefers_openmetrics("application/openmetrics-text"));
|
||||
assert!(!prefers_openmetrics("application/openmetrics-text; q=0"));
|
||||
assert!(!prefers_openmetrics("application/openmetrics-textual"));
|
||||
assert!(!prefers_openmetrics(
|
||||
"application/openmetrics-text; version=0.0.1"
|
||||
));
|
||||
assert!(!prefers_openmetrics(
|
||||
"application/openmetrics-text;q=0.2,text/plain;q=0.8"
|
||||
));
|
||||
fn lock() -> MutexGuard<'static, State> {
|
||||
STATE
|
||||
.get_or_init(|| Mutex::new(State::default()))
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_and_concurrent_scrapes_fail_closed_at_their_bounds() {
|
||||
assert_eq!(
|
||||
exposition_response("x".repeat(crank_metrics::MAX_EXPOSITION_BYTES + 1), false)
|
||||
.status(),
|
||||
axum::http::StatusCode::SERVICE_UNAVAILABLE
|
||||
);
|
||||
let active = Arc::new(AtomicUsize::new(0));
|
||||
let permits = (0..MAX_CONCURRENT_SCRAPES)
|
||||
.map(|_| ScrapePermit::try_acquire(&active).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(ScrapePermit::try_acquire(&active).is_none());
|
||||
drop(permits);
|
||||
assert!(ScrapePermit::try_acquire(&active).is_some());
|
||||
/// Включает барьер для одного детерминированного кейса.
|
||||
pub(crate) fn enable() {
|
||||
let mut state = lock();
|
||||
state.enabled = true;
|
||||
state.release = false;
|
||||
state.parked = 0;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_fixture_renders_in_linear_bounded_time() {
|
||||
let trace = ExemplarTraceId::parse("0123456789abcdef0123456789abcdef").unwrap();
|
||||
let mut legacy = String::new();
|
||||
let mut exemplars = Vec::new();
|
||||
for index in 0..5_000 {
|
||||
let value: &'static str = Box::leak(format!("route-{index}").into_boxed_str());
|
||||
legacy.push_str(&format!(
|
||||
"crank_http_request_duration_seconds_bucket{{route=\"{value}\",method=\"GET\",le=\"0.01\"}} 1\n"
|
||||
));
|
||||
exemplars.push(Arc::new(ExemplarObservation {
|
||||
metric: "crank_http_request_duration_seconds",
|
||||
labels: vec![("route", value), ("method", "GET")],
|
||||
bucket_upper_bound: Some(0.01),
|
||||
value: 0.007,
|
||||
trace_id: trace,
|
||||
}));
|
||||
/// Парковка после успешного acquire permit'а. Если барьер выключен —
|
||||
/// немедленный возврат, поэтому прочие unit-тесты не затрагиваются.
|
||||
/// Ожидание асинхронное (yield), поэтому worker'ы runtime'а не блокируются и
|
||||
/// обслуживание следующих соединений остаётся детерминированным.
|
||||
pub(crate) async fn hold() {
|
||||
{
|
||||
let mut state = lock();
|
||||
if !state.enabled {
|
||||
return;
|
||||
}
|
||||
state.parked += 1;
|
||||
}
|
||||
let started = Instant::now();
|
||||
let rendered = render_openmetrics(&legacy, &exemplars);
|
||||
assert_eq!(rendered.matches("# {trace_id=").count(), 5_000);
|
||||
assert!(started.elapsed() < Duration::from_secs(3));
|
||||
assert!(rendered.len() < crank_metrics::MAX_EXPOSITION_BYTES);
|
||||
while !lock().release {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Ожидание `count` припаркованных scrape'ов; `false` — истёк deadline.
|
||||
/// Вызывается из blocking-пула, поэтому не расходует worker'ы runtime'а.
|
||||
pub(crate) fn wait_for_parked(count: usize, timeout: std::time::Duration) -> bool {
|
||||
let deadline = std::time::Instant::now() + timeout;
|
||||
while std::time::Instant::now() < deadline {
|
||||
if lock().parked >= count {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
lock().parked >= count
|
||||
}
|
||||
|
||||
pub(crate) fn parked() -> usize {
|
||||
lock().parked
|
||||
}
|
||||
|
||||
/// Освобождает все припаркованные scrape'ы.
|
||||
pub(crate) fn release() {
|
||||
lock().release = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod recorder_guard_tests {
|
||||
use std::process::Command;
|
||||
|
||||
use super::{MetricsSurfaceError, install_prometheus_recorder};
|
||||
use crate::ServiceIdentity;
|
||||
|
||||
const GUARD_ROLE_PREFIX: &str = "crank-observability-guard-role-";
|
||||
|
||||
fn current_role() -> Option<String> {
|
||||
std::env::current_dir()
|
||||
.ok()?
|
||||
.file_name()?
|
||||
.to_str()?
|
||||
.strip_prefix(GUARD_ROLE_PREFIX)
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// F7 — приватный `install_prometheus_recorder` обязан отвергать identity,
|
||||
/// не совпадающую с опубликованным binding'ом, **до** любой установки
|
||||
/// recorder'а; ошибка типизированная, а positive control доказывает, что
|
||||
/// отклонённый вызов ничего не установил.
|
||||
///
|
||||
/// Свежий процесс обязателен: outer lifecycle-тест падает раньше (уже
|
||||
/// занятый global recorder/binding), поэтому приватный guard он не
|
||||
/// доказывает.
|
||||
#[test]
|
||||
fn private_recorder_guard_rejects_identity_mismatch_before_installing() {
|
||||
if current_role().is_none() {
|
||||
let role = "guard";
|
||||
let directory = std::env::temp_dir().join(format!("{GUARD_ROLE_PREFIX}{role}"));
|
||||
std::fs::create_dir_all(&directory).expect("guard role dir");
|
||||
let output = Command::new(std::env::current_exe().expect("current test binary"))
|
||||
.args([
|
||||
"prometheus::recorder_guard_tests::private_recorder_guard_rejects_identity_mismatch_before_installing",
|
||||
"--exact",
|
||||
"--nocapture",
|
||||
])
|
||||
.current_dir(&directory)
|
||||
.output()
|
||||
.expect("re-executed guard child");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"guard child failed:\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Свежий процесс: ни recorder, ни binding ещё не установлены.
|
||||
assert_eq!(crank_metrics::bound_metric_service(), None);
|
||||
crank_metrics::bind_metric_service(crank_metrics::MetricService::AdminApi)
|
||||
.expect("admin binding");
|
||||
|
||||
let mismatched = ServiceIdentity::try_new("mcp-server", "0.3.1", "test")
|
||||
.expect("valid mismatched identity");
|
||||
match install_prometheus_recorder(&mismatched) {
|
||||
Err(MetricsSurfaceError::RecorderConfiguration) => {}
|
||||
other => panic!(
|
||||
"identity другого сервиса обязана быть отвергнута приватным guard'ом: {other:?}"
|
||||
),
|
||||
}
|
||||
|
||||
// Positive control: matching identity проходит, значит предыдущий отказ
|
||||
// пришёл из guard'а, а не из заранее установленного recorder'а.
|
||||
let matching = ServiceIdentity::try_new("admin-api", "0.3.1", "test")
|
||||
.expect("valid matching identity");
|
||||
let handle = install_prometheus_recorder(&matching)
|
||||
.expect("matching identity обязан установить recorder");
|
||||
crank_metrics::record_http_request(
|
||||
crank_metrics::HttpRoute::from_matched_path("/health"),
|
||||
crank_metrics::HttpMethod::Get,
|
||||
crank_metrics::HttpStatusClass::Success,
|
||||
std::time::Duration::from_millis(1),
|
||||
);
|
||||
let exposition = handle.render();
|
||||
assert!(
|
||||
exposition.contains("crank_http_requests_total"),
|
||||
"установленный recorder обязан отдавать записанные series: {exposition}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user