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

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:
bsodfather committed 2026-10-25 09:08:22 +00:00
1 parent 1b6db09bd1
commit 54ce770682
357 files changed
+117394 -5115

No files matched your search

+32 -770
View File
@@ -1,772 +1,34 @@
use std::collections::BTreeSet;
//! Реестр метрик: корень модуля (wiring + ре-экспорты подмодулей).
//!
//! Разбиение чисто механическое: имена и сигнатуры всех items не изменились,
//! поэтому и пути `crate::schema::<Item>` внутри крейта, и список
//! `pub use schema::{...}` в `lib.rs` остаются валидными без правок.
use crate::labels::{
CacheOutcome, ConfirmationOutcome, DbPoolState, Exporter, HttpMethod, HttpStatusClass,
IdempotencyOutcome, InvocationSource, LimitStage, McpMethod, McpOutcome, McpResponseMode,
SignalType, ToolErrorKind, ToolOutcome, UpstreamOperationKind, UpstreamOutcome,
mod budget;
#[cfg(test)]
mod checked_arithmetic_tests;
mod descriptor;
mod projection;
mod rendering;
mod routes;
pub(crate) use budget::checked_exemplar_capacity;
pub use budget::{
MetricBindingError, SchemaBudget, SchemaError, validate_all_projections, validate_budget,
validate_exemplar_budget, validate_schema,
};
pub use descriptor::{
DURATION_BUCKETS_SECONDS, LabelClass, LabelDomain, MAX_EXEMPLAR_SLOTS_PER_PROCESS,
MAX_EXPOSITION_BYTES, MAX_LOGICAL_SERIES_PER_PROCESS, MAX_METRIC_FAMILIES,
MAX_PRODUCT_LABELS_PER_FAMILY, MAX_RENDERED_SERIES_PER_PROCESS, METRIC_SCHEMA_VERSION,
MetricDefinition, MetricKind, MetricProcess, MetricService, MetricUnit,
PROCESS_CONSTANT_LABELS, metric_schema,
};
pub use projection::{
max_exemplar_slots, metric_schema_for_service, schema_budget, service_projection,
};
pub use rendering::render_metric_schema_json;
pub use routes::{
ADMIN_HTTP_ROUTE_DOMAIN, HTTP_ROUTE_DOMAIN, HTTP_ROUTES, HttpRouteDefinition,
MCP_HTTP_ROUTE_DOMAIN, http_route_processes, validate_http_routes,
};
pub const METRIC_SCHEMA_VERSION: u32 = 1;
pub const MAX_METRIC_FAMILIES: usize = 128;
pub const MAX_PRODUCT_LABELS_PER_FAMILY: usize = 4;
pub const MAX_LOGICAL_SERIES_PER_PROCESS: usize = 5_563;
pub const MAX_RENDERED_SERIES_PER_PROCESS: usize = 17_638;
pub const MAX_EXPOSITION_BYTES: usize = 8 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricKind {
Counter,
Gauge,
Histogram,
}
impl MetricKind {
pub const fn as_str(self) -> &'static str {
match self {
Self::Counter => "counter",
Self::Gauge => "gauge",
Self::Histogram => "histogram",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricUnit {
Count,
Seconds,
}
impl MetricUnit {
pub const fn as_str(self) -> &'static str {
match self {
Self::Count => "count",
Self::Seconds => "seconds",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricProcess {
AdminApi,
McpServer,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MetricService {
AdminApi,
McpServer,
}
impl MetricService {
pub fn parse(value: &str) -> Option<Self> {
match value {
"admin-api" => Some(Self::AdminApi),
"mcp-server" => Some(Self::McpServer),
_ => None,
}
}
pub const fn process(self) -> MetricProcess {
match self {
Self::AdminApi => MetricProcess::AdminApi,
Self::McpServer => MetricProcess::McpServer,
}
}
}
impl MetricProcess {
pub const fn as_str(self) -> &'static str {
match self {
Self::AdminApi => "admin_api",
Self::McpServer => "mcp_server",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LabelClass {
ProductClosed,
ProcessConstant,
}
impl LabelClass {
pub const fn as_str(self) -> &'static str {
match self {
Self::ProductClosed => "product_closed",
Self::ProcessConstant => "process_constant",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LabelDomain {
pub name: &'static str,
pub class: LabelClass,
pub values: &'static [&'static str],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MetricDefinition {
pub name: &'static str,
pub kind: MetricKind,
pub unit: MetricUnit,
pub labels: &'static [&'static str],
pub label_domains: &'static [LabelDomain],
pub buckets: &'static [f64],
pub processes: &'static [MetricProcess],
pub max_logical_series: usize,
pub max_rendered_series: usize,
pub description: &'static str,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SchemaBudget {
pub logical_series: usize,
pub rendered_series: usize,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SchemaError {
TooManyFamilies,
DuplicateMetric,
InvalidMetric,
DuplicateLabel,
InvalidDomain,
InvalidBuckets,
InvalidCeiling,
BudgetExceeded,
}
pub const DURATION_BUCKETS_SECONDS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0,
];
pub const PROCESS_CONSTANT_LABELS: &[LabelDomain] = &[
LabelDomain {
name: "service",
class: LabelClass::ProcessConstant,
values: &["admin-api", "mcp-server"],
},
LabelDomain {
name: "version",
class: LabelClass::ProcessConstant,
values: &["validated_release_identity"],
},
LabelDomain {
name: "environment",
class: LabelClass::ProcessConstant,
values: &["validated_startup_value"],
},
];
const BOTH: &[MetricProcess] = &[MetricProcess::AdminApi, MetricProcess::McpServer];
const MCP: &[MetricProcess] = &[MetricProcess::McpServer];
pub const HTTP_ROUTE_DOMAIN: &[&str] = &[
"unmatched",
"/health",
"/ready",
"/api/auth/login",
"/api/auth/bootstrap/status",
"/api/auth/bootstrap/complete",
"/api/auth/logout",
"/api/auth/session",
"/api/auth/session/csrf",
"/api/auth/profile",
"/api/auth/password",
"/api/admin/capabilities",
"/api/admin/workspaces",
"/api/admin/workspaces/{workspace_id}",
"/api/admin/workspaces/{workspace_id}/onboarding",
"/api/admin/workspaces/{workspace_id}/onboarding/events",
"/api/admin/workspaces/{workspace_id}/onboarding/reset-selection",
"/api/admin/workspaces/{workspace_id}/onboarding/import-context",
"/api/admin/workspaces/{workspace_id}/onboarding/select-draft",
"/api/admin/workspaces/{workspace_id}/operations",
"/api/admin/workspaces/{workspace_id}/imports/openapi/preview",
"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/create",
"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/plans",
"/api/admin/workspaces/{workspace_id}/imports/openapi/plans/{plan_id}",
"/api/admin/workspaces/{workspace_id}/imports/openapi/{plan_id}/apply",
"/api/admin/workspaces/{workspace_id}/operations/analyze-quality",
"/api/admin/workspaces/{workspace_id}/operations/import",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/versions/{version}",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/publish",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/archive",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/test-runs",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/input-json",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/output-json",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/drafts/generate",
"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/export",
"/api/admin/workspaces/{workspace_id}/agents",
"/api/admin/workspaces/{workspace_id}/agents/tool-search/preview",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/versions/{version}",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/bindings",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/publish",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/unpublish",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/archive",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}/revoke",
"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}",
"/api/admin/workspaces/{workspace_id}/auth-profiles",
"/api/admin/workspaces/{workspace_id}/auth-profiles/{auth_profile_id}",
"/api/admin/workspaces/{workspace_id}/upstreams",
"/api/admin/workspaces/{workspace_id}/upstreams/{upstream_id}",
"/api/admin/workspaces/{workspace_id}/secrets",
"/api/admin/workspaces/{workspace_id}/secrets/{secret_id}",
"/api/admin/workspaces/{workspace_id}/secrets/{secret_id}/rotate",
"/api/admin/workspaces/{workspace_id}/export",
"/api/admin/workspaces/{workspace_id}/logs",
"/api/admin/workspaces/{workspace_id}/logs/export.csv",
"/api/admin/workspaces/{workspace_id}/logs/{log_id}",
"/api/admin/workspaces/{workspace_id}/approvals",
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}",
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/approve",
"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/deny",
"/api/admin/workspaces/{workspace_id}/usage",
"/api/admin/workspaces/{workspace_id}/usage/export.csv",
"/api/admin/workspaces/{workspace_id}/usage/operations/{operation_id}",
"/api/admin/workspaces/{workspace_id}/usage/agents/{agent_id}",
"/v1/{workspace_slug}/{agent_slug}",
"/v1/{workspace_slug}/{agent_slug}/approvals",
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/approve",
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}",
"/v1/{workspace_slug}/{agent_slug}/approvals/{approval_id}/deny",
];
const METHODS: &[&str] = HttpMethod::VALUES;
const STATUS: &[&str] = HttpStatusClass::VALUES;
const MCP_METHODS: &[&str] = McpMethod::VALUES;
const RESPONSE_MODES: &[&str] = McpResponseMode::VALUES;
const MCP_OUTCOMES: &[&str] = McpOutcome::VALUES;
const SOURCES: &[&str] = InvocationSource::VALUES;
const TOOL_OUTCOMES: &[&str] = ToolOutcome::VALUES;
const TOOL_ERRORS: &[&str] = ToolErrorKind::VALUES;
const OPERATION_KINDS: &[&str] = UpstreamOperationKind::VALUES;
const UPSTREAM_OUTCOMES: &[&str] = UpstreamOutcome::VALUES;
const LIMIT_STAGES: &[&str] = LimitStage::VALUES;
const CACHE_OUTCOMES: &[&str] = CacheOutcome::VALUES;
const IDEMPOTENCY_OUTCOMES: &[&str] = IdempotencyOutcome::VALUES;
const CONFIRMATION_OUTCOMES: &[&str] = ConfirmationOutcome::VALUES;
const DB_STATES: &[&str] = DbPoolState::VALUES;
const SIGNAL_TYPES: &[&str] = SignalType::VALUES;
const EXPORTERS: &[&str] = Exporter::VALUES;
const fn domain(name: &'static str, values: &'static [&'static str]) -> LabelDomain {
LabelDomain {
name,
class: LabelClass::ProductClosed,
values,
}
}
#[allow(
clippy::too_many_arguments,
reason = "the canonical descriptor keeps every metric contract dimension explicit"
)]
const fn metric(
name: &'static str,
kind: MetricKind,
unit: MetricUnit,
labels: &'static [&'static str],
label_domains: &'static [LabelDomain],
buckets: &'static [f64],
processes: &'static [MetricProcess],
logical: usize,
description: &'static str,
) -> MetricDefinition {
let rendered = if matches!(kind, MetricKind::Histogram) {
logical * (buckets.len() + 3)
} else {
logical
};
MetricDefinition {
name,
kind,
unit,
labels,
label_domains,
buckets,
processes,
max_logical_series: logical,
max_rendered_series: rendered,
description,
}
}
const METRIC_SCHEMA: &[MetricDefinition] = &[
metric(
"crank_http_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["route", "method", "status_class"],
&[
domain("route", HTTP_ROUTE_DOMAIN),
domain("method", METHODS),
domain("status_class", STATUS),
],
&[],
BOTH,
HTTP_ROUTE_DOMAIN.len() * 10 * 6,
"Total HTTP requests.",
),
metric(
"crank_http_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["route", "method"],
&[
domain("route", HTTP_ROUTE_DOMAIN),
domain("method", METHODS),
],
DURATION_BUCKETS_SECONDS,
BOTH,
HTTP_ROUTE_DOMAIN.len() * 10,
"HTTP request duration in seconds.",
),
metric(
"crank_http_inflight",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"HTTP requests currently being processed.",
),
metric(
"crank_mcp_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["method", "response_mode", "outcome"],
&[
domain("method", MCP_METHODS),
domain("response_mode", RESPONSE_MODES),
domain("outcome", MCP_OUTCOMES),
],
&[],
MCP,
9 * 3 * 7,
"Total MCP JSON-RPC requests.",
),
metric(
"crank_mcp_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["method", "outcome"],
&[
domain("method", MCP_METHODS),
domain("outcome", MCP_OUTCOMES),
],
DURATION_BUCKETS_SECONDS,
MCP,
9 * 7,
"MCP JSON-RPC request duration in seconds.",
),
metric(
"crank_mcp_active_sessions",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Active persisted MCP transport sessions.",
),
metric(
"crank_mcp_session_metrics_fresh",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Whether the active-session gauge was refreshed successfully.",
),
metric(
"crank_mcp_active_streams",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"MCP event streams currently being served.",
),
metric(
"crank_tool_invocations_total",
MetricKind::Counter,
MetricUnit::Count,
&["source", "outcome", "error_kind"],
&[
domain("source", SOURCES),
domain("outcome", TOOL_OUTCOMES),
domain("error_kind", TOOL_ERRORS),
],
&[],
BOTH,
3 * 3 * 22,
"Total tool invocations.",
),
metric(
"crank_tool_invocation_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["source", "outcome"],
&[domain("source", SOURCES), domain("outcome", TOOL_OUTCOMES)],
DURATION_BUCKETS_SECONDS,
BOTH,
3 * 3,
"Tool invocation duration in seconds.",
),
metric(
"crank_upstream_requests_total",
MetricKind::Counter,
MetricUnit::Count,
&["operation_kind", "outcome"],
&[
domain("operation_kind", OPERATION_KINDS),
domain("outcome", UPSTREAM_OUTCOMES),
],
&[],
BOTH,
13,
"Total upstream requests.",
),
metric(
"crank_upstream_request_duration_seconds",
MetricKind::Histogram,
MetricUnit::Seconds,
&["operation_kind", "outcome"],
&[
domain("operation_kind", OPERATION_KINDS),
domain("outcome", UPSTREAM_OUTCOMES),
],
DURATION_BUCKETS_SECONDS,
BOTH,
13,
"Upstream request duration in seconds.",
),
metric(
"crank_runtime_inflight",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"Runtime executions currently in progress.",
),
metric(
"crank_runtime_limit_rejections_total",
MetricKind::Counter,
MetricUnit::Count,
&["stage"],
&[domain("stage", LIMIT_STAGES)],
&[],
BOTH,
3,
"Runtime executions rejected by a bounded limit.",
),
metric(
"crank_runtime_cache_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", CACHE_OUTCOMES)],
&[],
BOTH,
7,
"Runtime response cache outcomes.",
),
metric(
"crank_idempotency_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", IDEMPOTENCY_OUTCOMES)],
&[],
BOTH,
8,
"Runtime idempotency outcomes.",
),
metric(
"crank_confirmation_total",
MetricKind::Counter,
MetricUnit::Count,
&["outcome"],
&[domain("outcome", CONFIRMATION_OUTCOMES)],
&[],
BOTH,
5,
"Runtime confirmation outcomes.",
),
metric(
"crank_db_pool_connections",
MetricKind::Gauge,
MetricUnit::Count,
&["state"],
&[domain("state", DB_STATES)],
&[],
BOTH,
2,
"PostgreSQL pool connections by state.",
),
metric(
"crank_catalog_tools",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Tools in the current published catalog.",
),
metric(
"crank_catalog_estimated_context_tokens",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Estimated context tokens in the current published catalog.",
),
metric(
"crank_catalog_warnings",
MetricKind::Gauge,
MetricUnit::Count,
&[],
&[],
&[],
MCP,
1,
"Warnings in the current published catalog.",
),
metric(
"crank_invocation_history_lost_total",
MetricKind::Counter,
MetricUnit::Count,
&[],
&[],
&[],
BOTH,
1,
"Invocation history records lost after an action completed.",
),
metric(
"crank_telemetry_export_failures_total",
MetricKind::Counter,
MetricUnit::Count,
&["signal_type", "exporter"],
&[
domain("signal_type", SIGNAL_TYPES),
domain("exporter", EXPORTERS),
],
&[],
BOTH,
4,
"Telemetry export failures.",
),
];
pub const fn metric_schema() -> &'static [MetricDefinition] {
METRIC_SCHEMA
}
pub fn metric_schema_for_service(
service: MetricService,
) -> impl Iterator<Item = &'static MetricDefinition> {
METRIC_SCHEMA
.iter()
.filter(move |definition| definition.processes.contains(&service.process()))
}
pub fn schema_budget() -> Result<SchemaBudget, SchemaError> {
validate_schema(METRIC_SCHEMA)
}
pub fn validate_budget(logical: usize, rendered: usize) -> Result<(), SchemaError> {
if logical > MAX_LOGICAL_SERIES_PER_PROCESS || rendered > MAX_RENDERED_SERIES_PER_PROCESS {
Err(SchemaError::BudgetExceeded)
} else {
Ok(())
}
}
pub fn max_exemplar_slots() -> usize {
METRIC_SCHEMA
.iter()
.filter(|definition| definition.kind == MetricKind::Histogram)
.map(|definition| definition.max_logical_series * (definition.buckets.len() + 1))
.sum()
}
pub fn validate_schema(schema: &[MetricDefinition]) -> Result<SchemaBudget, SchemaError> {
if schema.len() > MAX_METRIC_FAMILIES {
return Err(SchemaError::TooManyFamilies);
}
let mut names = BTreeSet::new();
let mut logical = 0usize;
let mut rendered = 0usize;
for item in schema {
if !names.insert(item.name) {
return Err(SchemaError::DuplicateMetric);
}
if !valid_metric_name(item.name)
|| !valid_static_text(item.description)
|| item.processes.is_empty()
|| item.labels.len() > MAX_PRODUCT_LABELS_PER_FAMILY
|| item.labels.len() != item.label_domains.len()
{
return Err(SchemaError::InvalidMetric);
}
let mut labels = BTreeSet::new();
let mut computed = 1usize;
for (label, domain) in item.labels.iter().zip(item.label_domains) {
if *label != domain.name || !valid_label_name(label) || !labels.insert(*label) {
return Err(SchemaError::DuplicateLabel);
}
if domain.class != LabelClass::ProductClosed
|| domain.values.is_empty()
|| domain.values.iter().any(|value| !valid_domain_value(value))
|| domain.values.iter().copied().collect::<BTreeSet<_>>().len()
!= domain.values.len()
{
return Err(SchemaError::InvalidDomain);
}
computed = computed
.checked_mul(domain.values.len())
.ok_or(SchemaError::BudgetExceeded)?;
}
if item.kind == MetricKind::Histogram {
if item.buckets.is_empty()
|| item.buckets.iter().any(|v| !v.is_finite() || *v <= 0.0)
|| item.buckets.windows(2).any(|pair| pair[0] >= pair[1])
{
return Err(SchemaError::InvalidBuckets);
}
} else if !item.buckets.is_empty() {
return Err(SchemaError::InvalidBuckets);
}
let expected_rendered = if item.kind == MetricKind::Histogram {
computed
.checked_mul(item.buckets.len() + 3)
.ok_or(SchemaError::BudgetExceeded)?
} else {
computed
};
if computed != item.max_logical_series || expected_rendered != item.max_rendered_series {
return Err(SchemaError::InvalidCeiling);
}
logical = logical
.checked_add(computed)
.ok_or(SchemaError::BudgetExceeded)?;
rendered = rendered
.checked_add(expected_rendered)
.ok_or(SchemaError::BudgetExceeded)?;
}
validate_budget(logical, rendered)?;
Ok(SchemaBudget {
logical_series: logical,
rendered_series: rendered,
})
}
fn valid_static_text(value: &str) -> bool {
!value.trim().is_empty()
&& value.len() <= 512
&& !value
.bytes()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
}
fn valid_metric_name(name: &str) -> bool {
!name.is_empty()
&& name
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
&& name.starts_with("crank_")
}
fn valid_label_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with("__")
&& name
.bytes()
.next()
.is_some_and(|byte| byte.is_ascii_lowercase() || byte == b'_')
&& name
.bytes()
.skip(1)
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}
fn valid_domain_value(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 256
&& !value
.bytes()
.any(|byte| byte.is_ascii_control() || matches!(byte, b'"' | b'\\'))
}
pub fn render_metric_schema_json() -> Result<String, SchemaError> {
let budget = schema_budget()?;
let mut out = format!(
"{{\n \"schema_version\": {METRIC_SCHEMA_VERSION},\n \"budget\": {{\"logical_series\": {}, \"rendered_series\": {}, \"max_logical_series\": {MAX_LOGICAL_SERIES_PER_PROCESS}, \"max_rendered_series\": {MAX_RENDERED_SERIES_PER_PROCESS}}},\n \"global_labels\": [\n",
budget.logical_series, budget.rendered_series
);
for (index, label) in PROCESS_CONSTANT_LABELS.iter().enumerate() {
out.push_str(&format!(
" {{\"name\": \"{}\", \"class\": \"{}\", \"domain\": [{}]}}{}\n",
label.name,
label.class.as_str(),
json_strings(label.values),
comma(index, PROCESS_CONSTANT_LABELS.len())
));
}
out.push_str(" ],\n \"metrics\": [\n");
for (index, item) in METRIC_SCHEMA.iter().enumerate() {
out.push_str(&format!(" {{\"name\": \"{}\", \"kind\": \"{}\", \"unit\": \"{}\", \"help\": \"{}\", \"processes\": [{}], \"labels\": [", item.name, item.kind.as_str(), item.unit.as_str(), item.description, json_processes(item.processes)));
for (label_index, domain) in item.label_domains.iter().enumerate() {
out.push_str(&format!(
"{{\"name\": \"{}\", \"class\": \"{}\", \"domain\": [{}]}}{}",
domain.name,
domain.class.as_str(),
json_strings(domain.values),
comma(label_index, item.label_domains.len())
));
}
out.push_str(&format!("], \"buckets_seconds\": [{}], \"max_logical_series\": {}, \"max_rendered_series\": {}}}{}\n", item.buckets.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "), item.max_logical_series, item.max_rendered_series, comma(index, METRIC_SCHEMA.len())));
}
out.push_str(" ]\n}\n");
Ok(out)
}
fn json_strings(values: &[&str]) -> String {
values
.iter()
.map(|value| format!("\"{value}\""))
.collect::<Vec<_>>()
.join(", ")
}
fn json_processes(values: &[MetricProcess]) -> String {
values
.iter()
.map(|value| format!("\"{}\"", value.as_str()))
.collect::<Vec<_>>()
.join(", ")
}
const fn comma(index: usize, len: usize) -> &'static str {
if index + 1 == len { "" } else { "," }
}