наблюдаемость: завершить базовый контур Community
CI / Rust Checks (push) Failing after 4m28s
CI / UI Checks (push) Has been skipped
CI / Frontend E2E (push) Has been skipped
CI / Community Image Smoke (push) Has been skipped
CI / Deploy (push) Has been skipped

Добавить структурированные журналы, метрики, трассировку и безопасный канал критических ошибок. Усилить границы рантайма, тесты, проверку зависимостей и сценарии развёртывания.
This commit is contained in:
bsodfather committed 2026-07-31 01:01:14 +03:00
1 parent 99bd05c145
commit 0e8f1ca03a
160 files changed
+13506 -1499

No files matched your search

+23 -4
View File
@@ -296,7 +296,12 @@ impl AdminService {
bindings: &[],
})
.await?;
info!(agent_id = %agent_id.as_str(), version = 1, "agent created");
info!(
name: "admin.agent.created",
agent_id = %agent_id.as_str(),
version = 1,
"agent created"
);
Ok(CreatedAgentResponse {
agent_id: agent_id.as_str().to_owned(),
@@ -417,6 +422,7 @@ impl AdminService {
})
.await?;
info!(
name: "admin.agent.bindings_saved",
agent_id = %agent_id.as_str(),
version = current_version.version,
binding_count = bindings.len(),
@@ -531,7 +537,12 @@ impl AdminService {
published_by: None,
})
.await?;
info!(agent_id = %agent_id.as_str(), version, "agent published");
info!(
name: "admin.agent.published",
agent_id = %agent_id.as_str(),
version,
"agent published"
);
Ok(PublishAgentResponse {
agent_id: agent_id.as_str().to_owned(),
@@ -589,7 +600,11 @@ impl AdminService {
self.registry
.unpublish_agent(workspace_id, agent_id, &updated_at)
.await?;
info!(agent_id = %agent_id.as_str(), "agent moved to draft");
info!(
name: "admin.agent.unpublished",
agent_id = %agent_id.as_str(),
"agent moved to draft"
);
Ok(AgentMutationResult {
agent_id: agent_id.as_str().to_owned(),
@@ -609,7 +624,11 @@ impl AdminService {
self.registry
.archive_agent(workspace_id, agent_id, &updated_at)
.await?;
info!(agent_id = %agent_id.as_str(), "agent archived");
info!(
name: "admin.agent.archived",
agent_id = %agent_id.as_str(),
"agent archived"
);
Ok(AgentMutationResult {
agent_id: agent_id.as_str().to_owned(),
+7 -2
View File
@@ -22,7 +22,7 @@ impl AdminService {
)?;
let user_id = self
.registry
.upsert_bootstrap_user(
.ensure_bootstrap_user(
&self.auth_settings.bootstrap_admin.email,
&self.auth_settings.bootstrap_admin.display_name,
&password_hash,
@@ -227,6 +227,7 @@ impl AdminService {
pub async fn change_password(
&self,
user_id: &crank_core::UserId,
current_session_id: &UserSessionId,
payload: ChangePasswordPayload,
) -> Result<(), ApiError> {
if payload.new_password.len() < 12 {
@@ -257,7 +258,11 @@ impl AdminService {
let password_hash =
hash_password(&payload.new_password, &self.auth_settings.password_pepper)?;
self.registry
.update_user_password(user_id, &password_hash)
.update_user_password_and_revoke_other_sessions(
user_id,
current_session_id,
&password_hash,
)
.await?;
Ok(())
+2 -1
View File
@@ -131,6 +131,7 @@ impl AdminService {
Ok(()) => Ok(()),
Err(RegistryError::OperationHasPublishedAgentBindings { .. }) => {
tracing::warn!(
name: "admin.demo_operation.cleanup_skipped",
operation_id = %operation_id.as_str(),
"legacy demo operation is still bound to a published agent; leaving it in place"
);
@@ -335,7 +336,7 @@ impl AdminService {
}),
response_preview: demo_rest_response_sample(),
})
.await?;
.await;
Ok(())
}
}
@@ -110,6 +110,7 @@ impl AdminService {
warnings,
};
info!(
name: "admin.operation.imported",
operation_id = %response.operation_id,
version = response.version,
"operation imported by upsert"
@@ -125,6 +126,7 @@ impl AdminService {
warnings,
};
info!(
name: "admin.operation.imported",
operation_id = %response.operation_id,
version = response.version,
"operation imported by upsert"
+86 -76
View File
@@ -8,9 +8,11 @@ use crank_import::rest::{
ImportFinding, ImportFindingSeverity, ImportOperationCandidate, operation_draft_from_candidate,
};
use crank_registry::{
CreateImportJobRequest, FinishImportJobRequest, ImportJobId, ImportJobKind, ImportJobStatus,
ApplyImportJobRequest, CreateImportJobRequest, ImportConflictMode, ImportJobId, ImportJobKind,
ImportJobStatus, ImportOperationDraft,
};
use serde_json::json;
use sha2::{Digest, Sha256};
use time::{Duration, OffsetDateTime, format_description::well_known::Rfc3339};
use tracing::{info, instrument};
@@ -50,7 +52,7 @@ impl AdminService {
kind: ImportJobKind::OpenApi,
source_format: &preview.source.format,
source_version: preview.source.version.as_deref(),
status: ImportJobStatus::Completed,
status: ImportJobStatus::Pending,
preview_payload: &preview_payload,
created_at: &now,
expires_at: &expires_at,
@@ -99,9 +101,13 @@ impl AdminService {
return Err(ApiError::validation("import job kind is not openapi"));
}
let preview: crank_import::rest::ImportPreview =
serde_json::from_value(job.preview_payload.clone())
.map_err(|error| ApiError::internal(error.to_string()))?;
let stored_preview = job
.preview_payload
.get("preview")
.cloned()
.unwrap_or_else(|| job.preview_payload.clone());
let preview: crank_import::rest::ImportPreview = serde_json::from_value(stored_preview)
.map_err(|error| ApiError::internal(error.to_string()))?;
let selected = payload
.selected_operation_keys
.iter()
@@ -120,10 +126,8 @@ impl AdminService {
}
}
let mut created = Vec::new();
let mut skipped = Vec::new();
let mut findings = Vec::new();
let mut created_ids = Vec::new();
let mut operations = Vec::new();
for operation_key in selected {
let Some(candidate) = candidates.get(&operation_key) else {
@@ -137,44 +141,7 @@ impl AdminService {
let mut draft =
operation_draft_from_candidate(candidate, payload.server_url.as_deref());
attach_import_findings(&mut draft, candidate);
if let Some(existing_name) = self
.find_operation_by_name(workspace_id, &draft.name)
.await?
.map(|operation| operation.name)
{
if payload.conflict_mode == "skip" {
skipped.push(OpenApiImportSkippedOperation {
operation_key: candidate.key.clone(),
name: draft.name.clone(),
reason: "operation with this name already exists".to_owned(),
});
findings.push(ImportFinding {
code: "operation_name_conflict".to_owned(),
severity: ImportFindingSeverity::Warning,
message: format!(
"Операция {} уже существует и была пропущена.",
draft.name
),
operation_key: Some(candidate.key.clone()),
});
continue;
}
let renamed = self
.next_available_operation_name(workspace_id, &draft.name)
.await?;
findings.push(ImportFinding {
code: "operation_name_renamed".to_owned(),
severity: ImportFindingSeverity::Info,
message: format!(
"Операция {existing_name} уже существует, новый черновик создан как {renamed}."
),
operation_key: Some(candidate.key.clone()),
});
draft.name = renamed;
}
let payload = OperationPayload {
let operation = self.new_operation_snapshot(OperationPayload {
name: draft.name.clone(),
display_name: draft.display_name.clone(),
category: draft.category,
@@ -197,27 +164,74 @@ impl AdminService {
},
tool_description: draft.tool_description,
wizard_state: draft.wizard_state,
};
let result = self.create_operation(workspace_id, payload).await?;
created_ids.push(result.operation_id.clone());
created.push(OpenApiImportCreatedOperation {
operation_id: result.operation_id,
name: draft.name,
version: result.version,
})?;
operations.push(ImportOperationDraft {
operation_key: candidate.key.clone(),
operation,
});
}
let finished_at = OffsetDateTime::now_utc();
self.registry
.finish_import_job(FinishImportJobRequest {
let application_key = openapi_application_key(&payload)?;
let conflict_mode = if payload.conflict_mode == "skip" {
ImportConflictMode::Skip
} else {
ImportConflictMode::Rename
};
let applied = self
.registry
.apply_import_job(ApplyImportJobRequest {
id: job_id,
status: ImportJobStatus::Completed,
created_operation_ids: &json!(created_ids),
error_text: None,
workspace_id,
application_key: &application_key,
conflict_mode,
operations: &operations,
finished_at: &finished_at,
})
.await?;
let created = applied
.created
.iter()
.map(|operation| OpenApiImportCreatedOperation {
operation_id: operation.operation_id.as_str().to_owned(),
name: operation.name.clone(),
version: operation.version,
})
.collect::<Vec<_>>();
let mut findings = applied
.created
.iter()
.filter_map(|operation| {
operation.renamed_from.as_ref().map(|previous_name| ImportFinding {
code: "operation_name_renamed".to_owned(),
severity: ImportFindingSeverity::Info,
message: format!(
"Операция {previous_name} уже существует, новый черновик создан как {}.",
operation.name
),
operation_key: Some(operation.operation_key.clone()),
})
})
.collect::<Vec<_>>();
for operation in applied.skipped {
skipped.push(OpenApiImportSkippedOperation {
operation_key: operation.operation_key.clone(),
name: operation.name.clone(),
reason: "operation with this name already exists".to_owned(),
});
findings.push(ImportFinding {
code: operation.reason,
severity: ImportFindingSeverity::Warning,
message: format!(
"Операция {} уже существует и была пропущена.",
operation.name
),
operation_key: Some(operation.operation_key),
});
}
info!(
name: "admin.openapi_import.completed",
created = created.len(),
skipped = skipped.len(),
"openapi import created drafts"
@@ -229,25 +243,21 @@ impl AdminService {
findings,
})
}
}
async fn next_available_operation_name(
&self,
workspace_id: &WorkspaceId,
base_name: &str,
) -> Result<String, ApiError> {
for index in 2.. {
let candidate = format!("{base_name}_{index}");
if self
.find_operation_by_name(workspace_id, &candidate)
.await?
.is_none()
{
return Ok(candidate);
}
}
unreachable!()
}
fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result<String, ApiError> {
let selected_operation_keys = payload
.selected_operation_keys
.iter()
.cloned()
.collect::<BTreeSet<_>>();
let canonical = serde_json::to_vec(&json!({
"selected_operation_keys": selected_operation_keys,
"server_url": payload.server_url.as_deref(),
"conflict_mode": payload.conflict_mode.as_str(),
}))
.map_err(|error| ApiError::internal(error.to_string()))?;
Ok(format!("{:x}", Sha256::digest(canonical)))
}
fn attach_import_findings(
@@ -19,6 +19,16 @@ use crate::{
};
impl AdminService {
pub async fn cleanup_invocation_logs_before(
&self,
cutoff: OffsetDateTime,
) -> Result<u64, ApiError> {
self.registry
.delete_invocation_logs_before(cutoff)
.await
.map_err(ApiError::from)
}
#[instrument(skip(self))]
pub async fn list_logs(
&self,
+81 -52
View File
@@ -141,7 +141,6 @@ impl AdminService {
workspace_id: &WorkspaceId,
payload: OperationPayload,
) -> Result<CreatedOperationResponse, ApiError> {
self.validate_operation_payload(&payload)?;
self.ensure_workspace_exists(workspace_id).await?;
if self
@@ -155,10 +154,36 @@ impl AdminService {
));
}
let snapshot = self.new_operation_snapshot(payload)?;
let operation_id = snapshot.id.clone();
self.registry
.create_operation(workspace_id, &snapshot, None)
.await?;
info!(
name: "admin.operation.created",
operation_id = %operation_id.as_str(),
version = 1,
"operation created"
);
Ok(CreatedOperationResponse {
operation_id: operation_id.as_str().to_owned(),
workspace_id: workspace_id.as_str().to_owned(),
version: 1,
status: OperationStatus::Draft,
updated_at: format_timestamp(snapshot.updated_at),
})
}
pub(super) fn new_operation_snapshot(
&self,
payload: OperationPayload,
) -> Result<RegistryOperation, ApiError> {
self.validate_operation_payload(&payload)?;
let now = OffsetDateTime::now_utc();
let operation_id = OperationId::new(new_prefixed_id("op"));
let snapshot = RegistryOperation {
id: operation_id.clone(),
Ok(RegistryOperation {
id: OperationId::new(new_prefixed_id("op")),
name: payload.name,
display_name: payload.display_name,
category: payload.category,
@@ -183,19 +208,6 @@ impl AdminService {
created_at: now,
updated_at: now,
published_at: None,
};
self.registry
.create_operation(workspace_id, &snapshot, None)
.await?;
info!(operation_id = %operation_id.as_str(), version = 1, "operation created");
Ok(CreatedOperationResponse {
operation_id: operation_id.as_str().to_owned(),
workspace_id: workspace_id.as_str().to_owned(),
version: 1,
status: OperationStatus::Draft,
updated_at: format_timestamp(snapshot.updated_at),
})
}
@@ -279,7 +291,12 @@ impl AdminService {
created_by: None,
})
.await?;
info!(operation_id = %operation_id.as_str(), version, "operation version created");
info!(
name: "admin.operation.version_created",
operation_id = %operation_id.as_str(),
version,
"operation version created"
);
Ok(CreatedOperationResponse {
operation_id: operation_id.as_str().to_owned(),
@@ -364,7 +381,12 @@ impl AdminService {
published_by: None,
})
.await?;
info!(operation_id = %operation_id.as_str(), version, "operation published");
info!(
name: "admin.operation.published",
operation_id = %operation_id.as_str(),
version,
"operation published"
);
Ok(PublishResponse {
operation_id: operation_id.as_str().to_owned(),
@@ -431,37 +453,44 @@ impl AdminService {
.await?;
let runtime = RuntimeOperation::from(record.snapshot.clone());
let mode = ExecutionMode::Unary;
let request_preview =
match build_request_preview(&record.snapshot.input_mapping, &payload.input) {
Ok(preview) => preview,
Err(error) => {
self.record_invocation(InvocationRecordRequest {
workspace_id,
agent_id: None,
operation: &record.snapshot,
request_id: Some(request_id),
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Error,
status: InvocationStatus::Error,
message: "mapping preview failed".to_owned(),
status_code: None,
error_kind: Some("mapping".to_owned()),
duration_ms: 0,
request_preview: Value::Null,
response_preview: Value::Null,
})
.await?;
return Ok(TestRunResult {
ok: false,
mode,
request_preview: Value::Null,
response_preview: Value::Null,
errors: vec![crate::error::runtime_test_failure(&RuntimeError::Mapping(
error,
))],
});
}
};
let preview_span = crank_trace::Stage::RuntimeArgumentsMap.span();
let preview_result = preview_span
.in_scope(|| build_request_preview(&record.snapshot.input_mapping, &payload.input));
let request_preview = match preview_result {
Ok(preview) => preview,
Err(error) => {
crank_trace::StageOutcome::Error.record(&preview_span);
crank_trace::ErrorCategory::Mapping.record(&preview_span);
drop(preview_span);
self.record_invocation(InvocationRecordRequest {
workspace_id,
agent_id: None,
operation: &record.snapshot,
request_id: Some(request_id),
source: InvocationSource::AdminTestRun,
level: InvocationLevel::Error,
status: InvocationStatus::Error,
message: "mapping preview failed".to_owned(),
status_code: None,
error_kind: Some("mapping".to_owned()),
duration_ms: 0,
request_preview: Value::Null,
response_preview: Value::Null,
})
.await;
return Ok(TestRunResult {
ok: false,
mode,
request_preview: Value::Null,
response_preview: Value::Null,
errors: vec![crate::error::runtime_test_failure(&RuntimeError::Mapping(
error,
))],
});
}
};
crank_trace::StageOutcome::Success.record(&preview_span);
drop(preview_span);
let resolved_auth = self
.resolve_operation_auth(workspace_id, &runtime.execution_config)
@@ -497,7 +526,7 @@ impl AdminService {
request_preview: request_preview.clone(),
response_preview: response_preview.clone(),
})
.await?;
.await;
Ok(TestRunResult {
ok: true,
mode,
@@ -524,7 +553,7 @@ impl AdminService {
request_preview: request_preview.clone(),
response_preview: Value::Null,
})
.await?;
.await;
Ok(TestRunResult {
ok: false,
mode,
+6 -1
View File
@@ -50,6 +50,7 @@ impl AdminService {
.save_sample_metadata(SaveSampleMetadataRequest { sample: &metadata })
.await?;
info!(
name: "admin.sample.saved",
operation_id = %operation_id.as_str(),
sample_id = %metadata.id.as_str(),
version,
@@ -119,7 +120,11 @@ impl AdminService {
input_mapping,
output_mapping,
};
info!(operation_id = %operation_id.as_str(), "draft generated from samples");
info!(
name: "admin.operation_draft.generated",
operation_id = %operation_id.as_str(),
"draft generated from samples"
);
Ok(result)
}
+20 -4
View File
@@ -92,7 +92,11 @@ impl AdminService {
created_by,
})
.await?;
info!(secret_id = %secret.id.as_str(), "secret created");
info!(
name: "admin.secret.created",
secret_id = %secret.id.as_str(),
"secret created"
);
Ok(secret)
}
@@ -126,7 +130,11 @@ impl AdminService {
created_by,
})
.await?;
info!(secret_id = %secret_id.as_str(), "secret rotated");
info!(
name: "admin.secret.rotated",
secret_id = %secret_id.as_str(),
"secret rotated"
);
self.get_secret(workspace_id, secret_id).await
}
@@ -152,7 +160,11 @@ impl AdminService {
.into());
}
self.registry.delete_secret(workspace_id, secret_id).await?;
info!(secret_id = %secret_id.as_str(), "secret deleted");
info!(
name: "admin.secret.deleted",
secret_id = %secret_id.as_str(),
"secret deleted"
);
Ok(())
}
@@ -201,7 +213,11 @@ impl AdminService {
profile: &profile,
})
.await?;
info!(auth_profile_id = %profile.id.as_str(), "auth profile created");
info!(
name: "admin.auth_profile.created",
auth_profile_id = %profile.id.as_str(),
"auth profile created"
);
Ok(profile)
}
+5 -1
View File
@@ -75,7 +75,11 @@ impl AdminService {
upstream: &upstream,
})
.await?;
info!(upstream_id = %upstream.id.as_str(), "workspace upstream saved");
info!(
name: "admin.upstream.saved",
upstream_id = %upstream.id.as_str(),
"workspace upstream saved"
);
Ok(upstream)
}