feat: harden community production foundation through story 1.5

This commit is contained in:
2026-08-14 00:21:59 +03:00
parent c30461cc92
commit f6fc2e5c9b
161 changed files with 16758 additions and 2515 deletions
+242
View File
@@ -0,0 +1,242 @@
use std::{process::ExitCode, time::Duration};
use crank_config::{ConfigSource, DatabaseSettings, parse_migrator};
use crank_registry::{
BackfillPolicy, MigrationApplyResult, MigrationAuthority, MigrationPreflight,
};
use serde_json::json;
use sqlx::{
PgPool,
postgres::{PgConnectOptions, PgPoolOptions},
};
#[tokio::main]
async fn main() -> ExitCode {
match run().await {
Ok(code) => code,
Err(error) => {
eprintln!(
"{}",
json!({
"status": "error",
"code": error.code,
"stage": error.stage,
"version": error.version,
"recovery": error.recovery,
})
);
ExitCode::FAILURE
}
}
}
#[derive(Clone, Copy)]
struct CliError {
code: &'static str,
stage: &'static str,
recovery: &'static str,
version: Option<i64>,
}
impl CliError {
const fn new(code: &'static str, stage: &'static str, recovery: &'static str) -> Self {
Self {
code,
stage,
recovery,
version: None,
}
}
fn from_migration(error: crank_registry::MigrationError) -> Self {
Self {
code: error.code(),
stage: error.stage(),
recovery: error.recovery(),
version: error.version(),
}
}
}
async fn run() -> Result<ExitCode, CliError> {
let mut arguments = std::env::args().skip(1);
let requested = arguments.next();
let option = arguments.next();
if arguments.next().is_some() {
return Err(CliError::new(
"invalid_command",
"cli.arguments",
"run_preflight",
));
}
let command = match requested.as_deref() {
None | Some("preflight") => "preflight",
Some("plan") => "plan",
Some("apply") => "apply",
Some(_) => {
return Err(CliError::new(
"invalid_command",
"cli.arguments",
"run_preflight",
));
}
};
if command == "plan" {
MigrationAuthority::validate_sequence().map_err(CliError::from_migration)?;
let sequence = MigrationAuthority::sequence()
.into_iter()
.map(|migration| {
let backfill = match migration.backfill {
BackfillPolicy::None => json!({ "kind": "none" }),
BackfillPolicy::Bounded {
max_batch_rows,
max_batch_ms,
resumable,
} => json!({
"kind": "bounded",
"max_batch_rows": max_batch_rows,
"max_batch_ms": max_batch_ms,
"resumable": resumable,
}),
};
json!({
"version": migration.version,
"name": migration.name,
"checksum": migration.checksum,
"source_digest": migration.source_digest,
"phase": migration.phase,
"compatibility": migration.compatibility,
"owner": migration.owner,
"transactional": migration.transactional,
"backfill": backfill,
"readable_schema_min": migration.readable_schema_min,
"readable_schema_max": migration.readable_schema_max,
"contract_evidence": migration.contract_evidence,
})
})
.collect::<Vec<_>>();
let plan = json!({ "schema_version": 1, "sequence": sequence });
if option.as_deref() == Some("--check") {
let bytes = std::fs::read("docs/schemas/migration-sequence.json")
.map_err(|_| CliError::new("contract_drift", "plan.read", "contact_operator"))?;
if bytes.len() > 65_536 {
return Err(CliError::new(
"contract_drift",
"plan.size",
"contact_operator",
));
}
let committed: serde_json::Value = serde_json::from_slice(&bytes)
.map_err(|_| CliError::new("contract_drift", "plan.parse", "contact_operator"))?;
if committed != plan {
return Err(CliError::new(
"contract_drift",
"plan.compare",
"contact_operator",
));
}
println!("{}", json!({ "status": "contract_current" }));
return Ok(ExitCode::SUCCESS);
}
if option.is_some() {
return Err(CliError::new(
"invalid_command",
"cli.arguments",
"run_preflight",
));
}
println!("{plan}");
return Ok(ExitCode::SUCCESS);
}
if option.is_some() {
return Err(CliError::new(
"invalid_command",
"cli.arguments",
"run_preflight",
));
}
let config = parse_migrator(
ConfigSource::from_os_for_migrator()
.map_err(|_| CliError::new("config_invalid", "config.source", "run_preflight"))?,
)
.map_err(|_| CliError::new("config_invalid", "config.validate", "run_preflight"))?;
let pool = connect(&config.database).await?;
if command == "apply" {
let result = MigrationAuthority::apply(&pool)
.await
.map_err(CliError::from_migration)?;
let (status, from, to) = match result {
MigrationApplyResult::Applied { from, to } => ("applied", from, to),
MigrationApplyResult::AlreadyCurrent { version } => {
("already_current", version, version)
}
};
println!(
"{}",
json!({ "status": status, "from_version": from, "to_version": to })
);
return Ok(ExitCode::SUCCESS);
}
match MigrationAuthority::preflight(&pool)
.await
.map_err(CliError::from_migration)?
{
MigrationPreflight::Current { version } => {
println!("{}", json!({ "status": "current", "version": version }));
Ok(ExitCode::SUCCESS)
}
MigrationPreflight::MigrationRequired { current, target } => {
println!(
"{}",
json!({
"status": "migration_required",
"current_version": current,
"target_version": target,
"recovery": "run_controlled_migration",
})
);
Ok(ExitCode::from(2))
}
}
}
async fn connect(config: &DatabaseSettings) -> Result<PgPool, CliError> {
let options = if let Some(url) = &config.url {
url.expose_secret()
.parse::<PgConnectOptions>()
.map_err(|_| CliError::new("config_invalid", "database.source", "run_preflight"))?
} else {
PgConnectOptions::new()
.host(&config.host)
.port(config.port)
.database(&config.database)
.username(&config.username)
.password(config.password.expose_secret())
};
for attempt in 1..=10 {
let result = PgPoolOptions::new()
.max_connections(config.pool.max_connections)
.min_connections(config.pool.min_connections)
.acquire_timeout(Duration::from_millis(config.pool.acquire_timeout_ms))
.idle_timeout(Duration::from_millis(config.pool.idle_timeout_ms))
.max_lifetime(Duration::from_millis(config.pool.max_lifetime_ms))
.connect_with(options.clone())
.await;
match result {
Ok(pool) => return Ok(pool),
Err(_) if attempt < 10 => {
tokio::time::sleep(Duration::from_secs(1)).await;
}
Err(_) => break,
}
}
Err(CliError::new(
"storage_unavailable",
"database.connect",
"contact_operator",
))
}
+1
View File
@@ -551,6 +551,7 @@ pub(crate) struct InvocationRecordRequest<'a> {
pub agent_id: Option<&'a AgentId>,
pub operation: &'a RegistryOperation,
pub request_id: Option<&'a str>,
pub trace_id: Option<&'a str>,
pub source: InvocationSource,
pub level: InvocationLevel,
pub status: InvocationStatus,
+44 -14
View File
@@ -74,9 +74,9 @@ impl ApiError {
}
}
pub fn internal(message: impl Into<String>) -> Self {
pub fn internal(_message: impl Into<String>) -> Self {
Self::Internal {
message: message.into(),
message: "internal server error".to_owned(),
context: None,
}
}
@@ -165,6 +165,13 @@ impl IntoResponse for ApiError {
if let Some(context) = self.context() {
error["context"] = context;
}
let (request_id, trace_id) = crank_observability::current_request_correlation();
if let Some(request_id) = request_id {
error["request_id"] = Value::String(request_id);
}
if let Some(trace_id) = trace_id {
error["trace_id"] = Value::String(trace_id);
}
let body = Json(json!({
"error": error
@@ -363,9 +370,10 @@ impl From<RegistryError> for ApiError {
format!("import job {job_id} was already applied with different parameters"),
json!({ "job_id": job_id }),
),
RegistryError::Storage(_) | RegistryError::Serialization(_) => {
Self::internal(value.to_string())
}
RegistryError::Migration(_)
| RegistryError::Storage(_)
| RegistryError::Serialization(_)
| RegistryError::InvalidCorrelationIdentity { .. } => Self::internal(value.to_string()),
}
}
}
@@ -399,7 +407,7 @@ impl From<StorageError> for ApiError {
pub fn runtime_test_failure(error: &RuntimeError) -> Value {
let mut payload = json!({
"code": runtime_test_failure_code(error),
"message": error.to_string()
"message": safe_runtime_test_failure_message(error)
});
if let Some(context) = runtime_error_context(error) {
payload["context"] = context;
@@ -407,6 +415,33 @@ pub fn runtime_test_failure(error: &RuntimeError) -> Value {
payload
}
fn safe_runtime_test_failure_message(error: &RuntimeError) -> &'static str {
match error {
RuntimeError::Schema(_) => "input schema validation failed",
RuntimeError::Mapping(_) => "input mapping failed",
RuntimeError::RestAdapter(_) | RuntimeError::ProtocolAdapter(_) => {
"upstream execution failed"
}
RuntimeError::UnsupportedProtocol { .. } => "operation protocol is unsupported",
RuntimeError::ConcurrencyLimitExceeded { .. } => "runtime concurrency limit exceeded",
RuntimeError::InvalidPreparedRequest { .. } => "prepared request is invalid",
RuntimeError::ConfirmationRequired { .. } => "operation confirmation is required",
RuntimeError::InvalidConfirmationToken { .. } => "confirmation token is invalid",
RuntimeError::ConfirmationStoreUnavailable { .. } => "confirmation store is unavailable",
RuntimeError::IdempotencyStoreUnavailable { .. } => "idempotency store is unavailable",
RuntimeError::IdempotencyInProgress { .. } => "idempotent execution is in progress",
RuntimeError::IdempotencyConflict { .. } => "idempotency key conflicts with the request",
RuntimeError::IdempotencyOutcomeUnknown { .. } => "previous execution outcome is unknown",
RuntimeError::UnsupportedExecutionMode { .. } => "execution mode is unsupported",
RuntimeError::MissingAuthProfile { .. } => "authorization profile is missing",
RuntimeError::MissingSecret { .. } | RuntimeError::MissingSecretVersion { .. } => {
"authorization secret is missing"
}
RuntimeError::InvalidAuthSecretValue { .. } => "authorization secret is invalid",
RuntimeError::SecretCrypto { .. } => "authorization secret processing failed",
}
}
fn runtime_test_failure_code(error: &RuntimeError) -> &'static str {
match error {
RuntimeError::Schema(_) => "runtime_schema_error",
@@ -435,9 +470,8 @@ fn runtime_test_failure_code(error: &RuntimeError) -> &'static str {
pub fn runtime_error_context(error: &RuntimeError) -> Option<Value> {
match error {
RuntimeError::InvalidPreparedRequest { field, reason } => Some(json!({
RuntimeError::InvalidPreparedRequest { field, .. } => Some(json!({
"field": field,
"reason": reason,
})),
RuntimeError::ConfirmationRequired {
confirmation_token,
@@ -457,14 +491,10 @@ pub fn runtime_error_context(error: &RuntimeError) -> Option<Value> {
| RuntimeError::IdempotencyOutcomeUnknown { operation_id } => Some(json!({
"operation_id": operation_id,
})),
RuntimeError::InvalidAuthSecretValue { secret_id, reason } => Some(json!({
RuntimeError::InvalidAuthSecretValue { secret_id, .. } => Some(json!({
"secret_id": secret_id,
"reason": reason,
})),
RuntimeError::SecretCrypto { operation, details } => Some(json!({
"operation": operation,
"details": details,
})),
RuntimeError::SecretCrypto { .. } => None,
RuntimeError::MissingAuthProfile { auth_profile_id } => Some(json!({
"auth_profile_id": auth_profile_id,
})),
+280 -114
View File
@@ -1,4 +1,4 @@
use std::{env, net::SocketAddr, path::PathBuf, time::Duration};
use std::{io, net::SocketAddr, process::ExitCode, time::Duration};
use admin_api::{
app::build_app,
@@ -8,9 +8,14 @@ use admin_api::{
state::AppState,
};
use crank_community_auth::PasswordIdentityProvider;
use crank_config::{
AdminProcessConfig, CacheBackend as ConfigCacheBackend, ConfigSource, DatabaseSettings,
DiagnosticCode, ObservabilitySettings, ProcessKind, parse_process,
};
use crank_core::CacheBackend;
use crank_observability::{
CriticalErrorCategory, MetricsConfig, ObservabilityConfig, ObservabilityLifecycle,
capture_critical_error,
OtlpTraceConfig, RedactionLimits, SentryConfig, ServiceIdentity, capture_critical_error,
};
use crank_registry::{PostgresPoolConfig, PostgresRegistry};
use crank_runtime::{
@@ -21,17 +26,77 @@ use sqlx::postgres::PgConnectOptions;
use tokio::net::TcpListener;
use tracing::{info, warn};
const MAX_INVOCATION_LOG_RETENTION_DAYS: i64 = 36_500;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let observability = crank_observability::init(ObservabilityConfig::from_env(
"admin-api",
env!("CARGO_PKG_VERSION"),
"admin_api=info,tower_http=info",
)?)?;
async fn main() -> ExitCode {
match main_result().await {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("{}", safe_startup_diagnostic(error.as_ref()));
ExitCode::FAILURE
}
}
}
fn safe_startup_diagnostic(error: &(dyn std::error::Error + 'static)) -> String {
let mut current = Some(error);
while let Some(cause) = current {
if let Some(config) = cause.downcast_ref::<crank_config::ConfigError>() {
return config.to_json();
}
if let Some(migration) = cause.downcast_ref::<crank_registry::MigrationError>() {
return serde_json::json!({
"status": "error",
"code": migration.code(),
"stage": migration.stage(),
"version": migration.version(),
"recovery": migration.recovery(),
})
.to_string();
}
if let Some(crank_registry::RegistryError::Migration(migration)) =
cause.downcast_ref::<crank_registry::RegistryError>()
{
return serde_json::json!({
"status": "error",
"code": migration.code(),
"stage": migration.stage(),
"version": migration.version(),
"recovery": migration.recovery(),
})
.to_string();
}
current = cause.source();
}
serde_json::json!({
"status": "error",
"code": "startup_failed",
"stage": "startup",
"version": null,
"recovery": "contact_operator",
})
.to_string()
}
async fn main_result() -> Result<(), Box<dyn std::error::Error>> {
let effective = parse_process(ProcessKind::AdminApi, ConfigSource::from_os()?)?;
let config = effective
.admin()
.cloned()
.ok_or_else(|| io::Error::other("admin configuration projection is unavailable"))?;
preflight_config(&config)?;
let observability = init_observability(&config.observability)?;
for deprecation in effective.deprecations() {
warn!(
name: "config.deprecated",
field = deprecation.field,
source_class = deprecation.source_class,
replacement = deprecation.replacement,
removal_window = deprecation.removal_window,
"deprecated configuration accepted"
);
}
let mut startup_completed = false;
let result = run(&observability, &mut startup_completed).await;
let result = run(config, &observability, &mut startup_completed).await;
if result.is_err() {
capture_critical_error(if startup_completed {
CriticalErrorCategory::Internal
@@ -43,54 +108,67 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
async fn run(
config: AdminProcessConfig,
observability: &ObservabilityLifecycle,
startup_completed: &mut bool,
) -> Result<(), Box<dyn std::error::Error>> {
let metrics_config =
MetricsConfig::from_env("CRANK_ADMIN_METRICS_BIND", "127.0.0.1:9464".parse()?)?;
let metrics_config = MetricsConfig::new(
config.observability.metrics.enabled,
config.observability.metrics.bind_addr,
config
.observability
.metrics
.bearer_token
.as_ref()
.map(|token| token.expose_secret().to_owned()),
)?;
let metrics_enabled = metrics_config.enabled();
let metrics_server = if metrics_config.enabled() {
let pool_config = postgres_pool_config(&config.database)?;
let registry = PostgresRegistry::connect_with_options_and_pool_config(
database_options(&config.database)?,
pool_config,
)
.await?;
let metrics_server = if metrics_enabled {
Some(observability.metrics_surface(metrics_config).bind().await?)
} else {
None
};
let storage_root = PathBuf::from(
env::var("CRANK_STORAGE_ROOT").unwrap_or_else(|_| "/var/lib/crank/storage".into()),
);
let bind_addr = env::var("CRANK_ADMIN_BIND").unwrap_or_else(|_| "0.0.0.0:3001".into());
let base_url = env::var("CRANK_BASE_URL").unwrap_or_else(|_| "http://localhost:3000".into());
let socket_addr: SocketAddr = bind_addr.parse()?;
let pool_config = PostgresPoolConfig::from_env()?;
let registry = PostgresRegistry::connect_with_options_and_pool_config(
database_options_from_env()?,
pool_config,
)
.await?;
if metrics_enabled {
spawn_postgres_pool_metrics(registry.pool().clone());
}
let base_url = config
.runtime
.base_url
.clone()
.unwrap_or_else(|| "http://localhost:3000".to_owned());
let auth_settings = AuthSettings {
session_secret: env::var("CRANK_SESSION_SECRET")?,
password_pepper: env::var("CRANK_PASSWORD_PEPPER")?,
session_ttl_hours: env::var("CRANK_SESSION_TTL_HOURS")
.ok()
.and_then(|value| value.parse::<i64>().ok())
.unwrap_or(24),
session_secret: config.session_secret.expose_secret().to_owned(),
password_pepper: config.password_pepper.expose_secret().to_owned(),
session_ttl_hours: config.session_ttl_hours,
cookie_secure: base_url.starts_with("https://"),
bootstrap_admin: BootstrapAdminConfig {
email: env::var("CRANK_BOOTSTRAP_ADMIN_EMAIL")?,
password: env::var("CRANK_BOOTSTRAP_ADMIN_PASSWORD")?,
display_name: env::var("CRANK_BOOTSTRAP_ADMIN_DISPLAY_NAME")
.unwrap_or_else(|_| "Crank Owner".into()),
email: config.bootstrap_email.clone(),
password: config.bootstrap_password.expose_secret().to_owned(),
display_name: config.bootstrap_display_name.clone(),
},
};
let runtime_limits = RuntimeLimits::from_env()?;
let cache_config = RuntimeCacheConfig::from_env()?;
let runtime_limits = RuntimeLimits::try_new(
config.runtime.max_concurrent_unary,
config.runtime.max_concurrent_sessions,
)?;
let cache_config = runtime_cache_config(&config)?;
let cache_stores = RuntimeCacheStores::from_config(&cache_config).await?;
let api_rate_limit = admin_api_rate_limit_config_from_env()?;
let secret_crypto = SecretCrypto::new(&env::var("CRANK_MASTER_KEY")?)?;
let outbound_http_policy = crank_runtime::OutboundHttpPolicy::from_env()?;
let api_rate_limit = RequestRateLimitConfig::new(
config.rate_limit.requests_per_second,
config.rate_limit.burst,
)?;
let secret_crypto = SecretCrypto::new(config.runtime.master_key.expose_secret())?;
let outbound_http_policy = crank_runtime::OutboundHttpPolicy::try_new(
config.runtime.outbound.allowed_hosts.clone(),
config.runtime.outbound.denied_hosts.clone(),
config.runtime.outbound.max_response_bytes,
)?;
let runtime = crank_runtime::community_with_outbound_policy(outbound_http_policy.clone())
.with_limits(runtime_limits)
.with_response_cache(cache_stores.response.clone())
@@ -100,7 +178,7 @@ async fn run(
PasswordIdentityProvider::new(registry.clone(), auth_settings.password_pepper.clone());
let service = AdminServiceBuilder::new(
registry,
storage_root,
config.storage_root.clone(),
auth_settings,
secret_crypto,
runtime,
@@ -108,12 +186,11 @@ async fn run(
.with_outbound_http_policy(outbound_http_policy)
.with_identity_provider(std::sync::Arc::new(identity_provider))
.build();
let invocation_log_retention_days = invocation_log_retention_days_from_env()?;
service.bootstrap_admin_user().await?;
if env_flag("CRANK_DEMO_SEED") {
if config.demo_seed {
service.seed_demo_assets().await?;
}
spawn_invocation_log_cleanup(service.clone(), invocation_log_retention_days);
spawn_invocation_log_cleanup(service.clone(), config.invocation_log_retention_days);
let state = AppState {
service,
api_rate_limiter: if cache_config.backend.is_external() {
@@ -121,10 +198,10 @@ async fn run(
} else {
RequestRateLimiter::new(api_rate_limit)
},
trust_forwarded_headers: env_flag("CRANK_TRUST_FORWARDED_HEADERS"),
trust_forwarded_headers: config.trust_forwarded_headers,
};
let app = build_app(state);
let listener = TcpListener::bind(socket_addr).await?;
let listener = TcpListener::bind(config.bind_addr).await?;
let make_service = app.into_make_service_with_connect_info::<SocketAddr>();
info!(
@@ -138,14 +215,10 @@ async fn run(
acquire_timeout_ms = pool_config.acquire_timeout_ms,
idle_timeout_ms = pool_config.idle_timeout_ms,
max_lifetime_ms = pool_config.max_lifetime_ms,
invocation_log_retention_days,
invocation_log_retention_days = config.invocation_log_retention_days,
"postgres pool configured"
);
info!(
name: "admin.server.listening",
bind_address = %socket_addr,
"admin-api listening"
);
info!(name: "admin.server.listening", bind_address = %config.bind_addr, "admin-api listening");
*startup_completed = true;
if let Some(metrics_server) = metrics_server {
@@ -156,23 +229,163 @@ async fn run(
} else {
axum::serve(listener, make_service).await?;
}
Ok(())
}
fn invocation_log_retention_days_from_env() -> Result<i64, Box<dyn std::error::Error>> {
const NAME: &str = "CRANK_INVOCATION_LOG_RETENTION_DAYS";
let value = match env::var(NAME) {
Ok(raw) => raw.parse::<i64>()?,
Err(env::VarError::NotPresent) => 30,
Err(error) => return Err(error.into()),
};
if !(1..=MAX_INVOCATION_LOG_RETENTION_DAYS).contains(&value) {
return Err(
format!("{NAME} must be between 1 and {MAX_INVOCATION_LOG_RETENTION_DAYS}").into(),
);
fn init_observability(
config: &ObservabilitySettings,
) -> Result<ObservabilityLifecycle, Box<dyn std::error::Error>> {
let identity = ServiceIdentity::try_new(
"admin-api",
env!("CARGO_PKG_VERSION"),
config.environment.clone(),
)?;
let base = ObservabilityConfig::try_new(
identity,
config.log_filter.clone(),
RedactionLimits::default(),
)?;
let sentry = SentryConfig::parse(
config
.sentry_dsn
.as_ref()
.map(|value| value.expose_secret()),
)?;
let otlp = otlp_config(config)?;
Ok(ObservabilityLifecycle::init_with_exporters(
base, sentry, otlp,
)?)
}
fn preflight_config(config: &AdminProcessConfig) -> Result<(), crank_config::ConfigError> {
let invalid = |field| crank_config::ConfigError::single(DiagnosticCode::InvalidType, field);
database_options(&config.database).map_err(|_| invalid("database.source"))?;
postgres_pool_config(&config.database).map_err(|_| invalid("database.pool"))?;
MetricsConfig::new(
config.observability.metrics.enabled,
config.observability.metrics.bind_addr,
config
.observability
.metrics
.bearer_token
.as_ref()
.map(|v| v.expose_secret().to_owned()),
)
.map_err(|_| invalid("observability.metrics"))?;
RuntimeLimits::try_new(
config.runtime.max_concurrent_unary,
config.runtime.max_concurrent_sessions,
)
.map_err(|_| invalid("runtime.limits"))?;
runtime_cache_config(config).map_err(|_| invalid("cache"))?;
RequestRateLimitConfig::new(
config.rate_limit.requests_per_second,
config.rate_limit.burst,
)
.map_err(|_| invalid("admin.rate_limit"))?;
SecretCrypto::new(config.runtime.master_key.expose_secret())
.map_err(|_| invalid("runtime.master_key"))?;
crank_runtime::OutboundHttpPolicy::try_new(
config.runtime.outbound.allowed_hosts.clone(),
config.runtime.outbound.denied_hosts.clone(),
config.runtime.outbound.max_response_bytes,
)
.map_err(|_| invalid("runtime.outbound"))?;
let identity = ServiceIdentity::try_new(
"admin-api",
env!("CARGO_PKG_VERSION"),
config.observability.environment.clone(),
)
.map_err(|_| invalid("observability.environment"))?;
ObservabilityConfig::try_new(
identity,
config.observability.log_filter.clone(),
RedactionLimits::default(),
)
.map_err(|_| invalid("observability.log_filter"))?;
SentryConfig::parse(
config
.observability
.sentry_dsn
.as_ref()
.map(|v| v.expose_secret()),
)
.map_err(|_| invalid("observability.sentry_dsn"))?;
otlp_config(&config.observability).map_err(|_| invalid("observability.otlp"))?;
Ok(())
}
fn otlp_config(
config: &ObservabilitySettings,
) -> Result<OtlpTraceConfig, crank_observability::OtlpTraceConfigError> {
let values = &config.otlp;
OtlpTraceConfig::from_values(
values.endpoint.clone(),
values.traces_endpoint.clone(),
values.protocol.clone(),
values.traces_protocol.clone(),
values.timeout.clone(),
values.traces_timeout.clone(),
values
.headers
.as_ref()
.map(|value| value.expose_secret().to_owned()),
values
.traces_headers
.as_ref()
.map(|value| value.expose_secret().to_owned()),
values.max_queue_size,
values.max_export_batch_size,
values.schedule_delay.clone(),
values.export_timeout.clone(),
)
}
fn postgres_pool_config(
config: &DatabaseSettings,
) -> Result<PostgresPoolConfig, crank_registry::PostgresPoolConfigError> {
PostgresPoolConfig::try_new(
config.pool.max_connections,
config.pool.min_connections,
config.pool.acquire_timeout_ms,
config.pool.idle_timeout_ms,
config.pool.max_lifetime_ms,
)
}
fn database_options(
config: &DatabaseSettings,
) -> Result<PgConnectOptions, Box<dyn std::error::Error>> {
if let Some(url) = &config.url {
return url
.expose_secret()
.parse::<PgConnectOptions>()
.map_err(|_| io::Error::other("database URL is invalid").into());
}
Ok(value)
Ok(PgConnectOptions::new()
.host(&config.host)
.port(config.port)
.database(&config.database)
.username(&config.username)
.password(config.password.expose_secret()))
}
fn runtime_cache_config(
config: &AdminProcessConfig,
) -> Result<RuntimeCacheConfig, crank_runtime::RuntimeCacheConfigError> {
RuntimeCacheConfig::try_new(
match config.runtime.cache.backend {
ConfigCacheBackend::Memory => CacheBackend::Memory,
ConfigCacheBackend::Valkey => CacheBackend::Valkey,
ConfigCacheBackend::Redis => CacheBackend::Redis,
},
config
.runtime
.cache
.url
.as_ref()
.map(|value| value.expose_secret().to_owned()),
)
}
fn spawn_invocation_log_cleanup(service: admin_api::service::AdminService, retention_days: i64) {
@@ -197,50 +410,3 @@ fn spawn_invocation_log_cleanup(service: admin_api::service::AdminService, reten
}
});
}
fn env_flag(name: &str) -> bool {
matches!(
env::var(name)
.ok()
.as_deref()
.map(str::to_ascii_lowercase)
.as_deref(),
Some("1" | "true" | "yes" | "on")
)
}
fn admin_api_rate_limit_config_from_env()
-> Result<RequestRateLimitConfig, Box<dyn std::error::Error>> {
let requests_per_second = env::var("CRANK_ADMIN_RATE_LIMIT_RPS")
.ok()
.and_then(|value| value.parse::<u32>().ok())
.unwrap_or(30);
let burst = env::var("CRANK_ADMIN_RATE_LIMIT_BURST")
.ok()
.and_then(|value| value.parse::<u32>().ok())
.unwrap_or(60);
Ok(RequestRateLimitConfig::new(requests_per_second, burst)?)
}
fn database_options_from_env() -> Result<PgConnectOptions, Box<dyn std::error::Error>> {
if let Ok(database_url) = env::var("CRANK_DATABASE_URL") {
return Ok(database_url.parse::<PgConnectOptions>()?);
}
let host = env::var("POSTGRES_HOST").unwrap_or_else(|_| "postgres".into());
let port = env::var("POSTGRES_PORT")
.ok()
.and_then(|value| value.parse::<u16>().ok())
.unwrap_or(5432);
let database = env::var("POSTGRES_DB").unwrap_or_else(|_| "crank".into());
let username = env::var("POSTGRES_USER").unwrap_or_else(|_| "crank".into());
let password = env::var("POSTGRES_PASSWORD").unwrap_or_else(|_| "crank".into());
Ok(PgConnectOptions::new()
.host(&host)
.port(port)
.database(&database)
.username(&username)
.password(&password))
}
+101 -27
View File
@@ -4,20 +4,30 @@ use axum::{
middleware::Next,
response::Response,
};
use crank_observability::{RequestId, set_remote_trace_parent, with_request_correlation};
use crank_core::{CorrelationContext, RequestId, TraceContext};
use crank_observability::{set_remote_trace_parent, with_request_correlation};
use tracing::{Instrument, info, info_span};
pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-request-id");
pub const TRACE_ID_HEADER: HeaderName = HeaderName::from_static("x-trace-id");
#[derive(Clone, Debug)]
pub struct RequestContext {
pub request_id: String,
pub correlation: CorrelationContext,
}
impl RequestContext {
pub fn request_id(&self) -> &str {
self.correlation.request_id().as_str()
}
pub fn trace_id(&self) -> &str {
self.correlation.trace_id().as_str()
}
}
pub async fn apply_request_context(mut request: Request, next: Next) -> Response {
let context = RequestContext {
request_id: RequestId::resolve_from_headers(request.headers()).into_string(),
};
let (request_id, remote_parent) = resolve_correlation(request.headers());
let method = request.method().clone();
let route = request
.extensions()
@@ -27,41 +37,105 @@ pub async fn apply_request_context(mut request: Request, next: Next) -> Response
let span = info_span!(
target: "crank::trace",
"http.request",
request_id = %context.request_id,
request_id = %request_id,
trace_id = tracing::field::Empty,
);
set_remote_trace_parent(&span, request.headers());
if let Some(remote_parent) = remote_parent.as_ref() {
set_canonical_parent(&span, remote_parent);
}
let trace_context = crank_trace::trace_context_for_span(&span).unwrap_or_else(|| {
remote_parent
.as_ref()
.map_or_else(TraceContext::generate, TraceContext::continue_local)
});
span.record("trace_id", trace_context.trace_id().as_str());
let context = RequestContext {
correlation: CorrelationContext::new(request_id, trace_context),
};
request.extensions_mut().insert(context.clone());
with_request_correlation(context.request_id.clone(), async move {
let mut response = next.run(request).instrument(span).await;
info!(
name: "admin.request.completed",
request_id = %context.request_id,
method = %method,
route,
status = response.status().as_u16(),
"admin request completed"
);
if let Ok(value) = HeaderValue::from_str(&context.request_id) {
response.headers_mut().insert(REQUEST_ID_HEADER, value);
}
response
})
with_request_correlation(
context.correlation.request_id().to_string(),
context.correlation.trace_id().to_string(),
async move {
let mut response = next.run(request).instrument(span).await;
info!(
name: "admin.request.completed",
request_id = %context.correlation.request_id(),
trace_id = %context.correlation.trace_id(),
method = %method,
route,
status = response.status().as_u16(),
"admin request completed"
);
if let Ok(value) = HeaderValue::from_str(context.correlation.request_id().as_str()) {
response.headers_mut().insert(REQUEST_ID_HEADER, value);
}
if let Ok(value) = HeaderValue::from_str(context.correlation.trace_id().as_str()) {
response.headers_mut().insert(TRACE_ID_HEADER, value);
}
response
},
)
.await
}
fn resolve_correlation(headers: &axum::http::HeaderMap) -> (RequestId, Option<TraceContext>) {
let _tracestate_accepted = one_auxiliary_header_within_budget(
headers,
"tracestate",
TraceContext::tracestate_within_budget,
);
let _baggage_accepted =
one_auxiliary_header_within_budget(headers, "baggage", TraceContext::baggage_within_budget);
let mut request_ids = headers.get_all(REQUEST_ID_HEADER).iter();
let request_id = request_ids.next().and_then(|value| value.to_str().ok());
let request_id = if request_ids.next().is_some() {
RequestId::generate()
} else {
RequestId::resolve(request_id)
};
let mut traceparents = headers.get_all("traceparent").iter();
let traceparent = traceparents.next().and_then(|value| value.to_str().ok());
let remote_parent = if traceparents.next().is_some() {
None
} else {
traceparent.and_then(|value| TraceContext::parse(value).ok())
};
(request_id, remote_parent)
}
fn one_auxiliary_header_within_budget(
headers: &axum::http::HeaderMap,
name: &'static str,
validate: fn(&str) -> bool,
) -> bool {
let mut values = headers.get_all(name).iter();
let value = values.next().and_then(|value| value.to_str().ok());
values.next().is_none() && value.is_some_and(validate)
}
fn set_canonical_parent(span: &tracing::Span, context: &TraceContext) {
let mut headers = axum::http::HeaderMap::new();
if let Ok(value) = HeaderValue::from_str(context.traceparent()) {
headers.insert("traceparent", value);
set_remote_trace_parent(span, &headers);
}
}
#[cfg(test)]
mod tests {
#[test]
fn accepts_visible_ascii_request_ids() {
assert!(crank_observability::RequestId::is_valid("req_test_123"));
assert!(crank_observability::RequestId::is_valid("trace-123/abc"));
assert!(crank_core::RequestId::is_valid("req_test_123"));
assert!(crank_core::RequestId::is_valid("trace-123/abc"));
}
#[test]
fn rejects_empty_or_control_request_ids() {
assert!(!crank_observability::RequestId::is_valid(""));
assert!(!crank_observability::RequestId::is_valid("bad value"));
assert!(!crank_observability::RequestId::is_valid("bad\nvalue"));
assert!(!crank_core::RequestId::is_valid(""));
assert!(!crank_core::RequestId::is_valid("bad value"));
assert!(!crank_core::RequestId::is_valid("bad\nvalue"));
}
}
+1 -1
View File
@@ -193,7 +193,7 @@ pub async fn run_test(
&path.workspace_id.as_str().into(),
&path.operation_id.as_str().into(),
payload,
&request_context.request_id,
&request_context.correlation,
)
.await?;
Ok(Json(json!(result)))
+5
View File
@@ -469,6 +469,7 @@ impl AdminService {
tool_name: request.operation.name.clone(),
message: request.message,
request_id: request.request_id.map(ToOwned::to_owned),
trace_id: request.trace_id.map(ToOwned::to_owned),
status_code: request.status_code,
duration_ms: request.duration_ms,
error_kind: request.error_kind,
@@ -506,6 +507,7 @@ impl AdminService {
observe_invocation_history_outcome(
outcome,
request.request_id,
request.trace_id,
request.status,
request.source,
);
@@ -516,6 +518,7 @@ impl AdminService {
fn observe_invocation_history_outcome(
outcome: InvocationHistoryWriteOutcome,
request_id: Option<&str>,
trace_id: Option<&str>,
status: crank_core::InvocationStatus,
source: InvocationSource,
) {
@@ -528,6 +531,7 @@ fn observe_invocation_history_outcome(
tracing::warn!(
name: "admin.invocation_history.lost",
request_id = request_id.unwrap_or_default(),
trace_id = trace_id.unwrap_or_default(),
source = invocation_source_label(source),
invocation_status = invocation_status_label(status),
error_category = loss.category.as_str(),
@@ -935,6 +939,7 @@ mod tests {
category: InvocationHistoryLossCategory::InvalidRecord,
}),
Some("req_admin_dc08"),
Some("0af7651916cd43dd8448eb211c80319c"),
InvocationStatus::Error,
InvocationSource::AgentToolCall,
);
+3 -1
View File
@@ -316,11 +316,13 @@ impl AdminService {
.current_draft_version,
)
.await?;
let correlation = crank_core::CorrelationContext::generate();
self.record_invocation(InvocationRecordRequest {
workspace_id,
agent_id: Some(currency_agent_id),
operation: &rest_operation.snapshot,
request_id: None,
request_id: Some(correlation.request_id().as_str()),
trace_id: Some(correlation.trace_id().as_str()),
source: InvocationSource::AgentToolCall,
level: InvocationLevel::Info,
status: InvocationStatus::Ok,
+7 -2
View File
@@ -444,9 +444,11 @@ impl AdminService {
workspace_id: &WorkspaceId,
operation_id: &OperationId,
payload: TestRunPayload,
request_id: &str,
correlation: &crank_core::CorrelationContext,
) -> Result<TestRunResult, ApiError> {
let runtime_request_context = RuntimeRequestContext::from_request_id(request_id)
let request_id = correlation.request_id().as_str();
let trace_id = correlation.trace_id().as_str();
let runtime_request_context = RuntimeRequestContext::from_correlation(correlation)
.with_metering_context(workspace_id.clone(), None, InvocationSource::AdminTestRun);
let record = self
.get_operation_version(workspace_id, operation_id, payload.version)
@@ -467,6 +469,7 @@ impl AdminService {
agent_id: None,
operation: &record.snapshot,
request_id: Some(request_id),
trace_id: Some(trace_id),
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Error,
status: InvocationStatus::Error,
@@ -516,6 +519,7 @@ impl AdminService {
agent_id: None,
operation: &record.snapshot,
request_id: Some(request_id),
trace_id: Some(trace_id),
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Info,
status: InvocationStatus::Ok,
@@ -543,6 +547,7 @@ impl AdminService {
agent_id: None,
operation: &record.snapshot,
request_id: Some(request_id),
trace_id: Some(trace_id),
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Error,
status: InvocationStatus::Error,