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.
702 lines
27 KiB
Rust
702 lines
27 KiB
Rust
//! Story 3.10 (FR-16): admin-api контракт REST-backed Resource template.
|
|
//!
|
|
//! Здесь живёт всё, что требует pinned Operation Version: structural-разбор
|
|
//! `metadata.source`, типизация параметров через shared `crank_schema`, blocker
|
|
//! findings (read-safety/parameters/cache) и view публикации. Домен (`crank-core`)
|
|
//! отвечает за типы/грамматику/пределы, persistence (`crank-registry`) — за
|
|
//! byte-less version-keyed хранение; сетевых вызовов здесь нет.
|
|
//!
|
|
//! Порядок create: metadata (форма) → source (структура/грамматика) → pinned
|
|
//! Published версия того же workspace → запись. Preview/publish пересчитывают
|
|
//! findings по **сохранённому** определению и заново разрешают pinned версию, поэтому
|
|
//! правка сохранённой ссылки не публикует небезопасную операцию.
|
|
|
|
use std::collections::BTreeSet;
|
|
|
|
use crank_core::WorkspaceId;
|
|
use crank_core::ids::{OperationId, ResourceId};
|
|
use crank_core::operation::{
|
|
OperationApprovalPolicy, OperationSafetyClass, OperationSafetyPolicy, OperationStatus, Target,
|
|
};
|
|
use crank_core::protocol::HttpMethod;
|
|
use crank_core::resource::template::{
|
|
TEMPLATE_CACHE_SCOPE, TemplateFinding, TemplateFindingCode, TemplateSource,
|
|
cache_policy_findings, parse_uri_template,
|
|
};
|
|
use crank_core::resource::{ResourceError, ResourceKind, ResourceMetadata};
|
|
use crank_registry::OperationVersionRecord;
|
|
use crank_registry::model::resource::{
|
|
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
|
|
ResourcePublicationRecord, ResourceTemplateSourceRecord, UpdateResourceTemplateDraftRequest,
|
|
};
|
|
use crank_schema::{Schema, SchemaKind};
|
|
use serde::Serialize;
|
|
use serde_json::Value;
|
|
use time::OffsetDateTime;
|
|
|
|
const MAX_TEMPLATE_DEFINITION_BYTES: usize = 65_536;
|
|
|
|
use super::{
|
|
CreatedDraft, DraftMetadata, PreviewFinding, PublishedVersionResponse, PublishedVersionView,
|
|
ResourceCardResponse, ResourcesService, generate_resource_id, parse_kind, parse_metadata,
|
|
parse_sensitivity, parse_timestamp, sha256_hex, truncate_to_micros,
|
|
};
|
|
|
|
/// Новый template Draft: `metadata` без части `content` + source-объект.
|
|
pub(crate) struct NewTemplateDraft {
|
|
pub workspace_id: WorkspaceId,
|
|
pub metadata: DraftMetadata,
|
|
pub source: Value,
|
|
}
|
|
|
|
/// Обновление template Draft: изменяемые metadata + новое определение.
|
|
pub(crate) struct UpdateTemplateDraft {
|
|
pub workspace_id: WorkspaceId,
|
|
pub resource_id: ResourceId,
|
|
pub description: String,
|
|
pub mime_type: String,
|
|
pub sensitivity: String,
|
|
pub expected_updated_at: Option<String>,
|
|
pub identity: TemplateIdentity,
|
|
pub source: Option<Value>,
|
|
}
|
|
|
|
/// Identity-поля template Draft: неизменяемы, но могут быть повторены в PUT-форме
|
|
/// (значение обязано совпадать с сохранённым).
|
|
#[derive(Clone, Debug, Default)]
|
|
pub(crate) struct TemplateIdentity {
|
|
pub uri: Option<String>,
|
|
pub name: Option<String>,
|
|
pub kind: Option<String>,
|
|
}
|
|
|
|
/// Каноническое определение + типизированные схемы параметров.
|
|
pub(crate) struct TemplateDefinition {
|
|
pub source: TemplateSource,
|
|
pub schemas: Vec<Schema>,
|
|
pub json: String,
|
|
pub digest: String,
|
|
}
|
|
|
|
impl TemplateDefinition {
|
|
pub(crate) fn parse(value: &Value) -> Result<Self, ResourceError> {
|
|
let source =
|
|
TemplateSource::parse(value).map_err(|error| ResourceError::SourceInvalid {
|
|
field: error.field(),
|
|
})?;
|
|
let mut schemas = Vec::with_capacity(source.parameters.len());
|
|
for parameter in &source.parameters {
|
|
let schema: Schema =
|
|
serde_json::from_value(parameter.schema.clone()).map_err(|_| {
|
|
ResourceError::SourceInvalid {
|
|
field: "source.parameters",
|
|
}
|
|
})?;
|
|
schemas.push(schema);
|
|
}
|
|
let json = serde_json::to_string(&source)
|
|
.map_err(|_| ResourceError::SourceInvalid { field: "source" })?;
|
|
if json.len() > MAX_TEMPLATE_DEFINITION_BYTES {
|
|
return Err(ResourceError::SourceInvalid { field: "source" });
|
|
}
|
|
let digest = sha256_hex(json.as_bytes());
|
|
Ok(Self {
|
|
source,
|
|
schemas,
|
|
json,
|
|
digest,
|
|
})
|
|
}
|
|
|
|
/// Сохранённое определение: parse + сверка digest (повреждение = integrity).
|
|
pub(crate) fn from_stored(
|
|
stored: &ResourceTemplateSourceRecord,
|
|
) -> Result<Self, ResourceError> {
|
|
let value: Value = serde_json::from_str(&stored.definition_json)
|
|
.map_err(|_| ResourceError::ArtifactIntegrity)?;
|
|
let definition = Self::parse(&value)?;
|
|
if definition.digest != stored.definition_digest {
|
|
return Err(ResourceError::ArtifactIntegrity);
|
|
}
|
|
Ok(definition)
|
|
}
|
|
}
|
|
|
|
/// `source` в карточке/публикации: факты без потерь + read-safety/access pinned версии.
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct TemplateSourceView {
|
|
pub operation_id: String,
|
|
pub operation_version: u32,
|
|
pub uri_template: String,
|
|
pub parameters: Vec<Value>,
|
|
pub cache: TemplateCacheView,
|
|
pub failure: TemplateFailureView,
|
|
pub read_safety: TemplateReadSafetyView,
|
|
pub access: TemplateAccessView,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct TemplateCacheView {
|
|
pub ttl_ms: u64,
|
|
pub vary: Vec<String>,
|
|
pub max_bytes: u64,
|
|
/// Нормализованная серверная policy (клиент не может её задать).
|
|
pub scope: &'static str,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct TemplateFailureView {
|
|
pub outcome: &'static str,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct TemplateReadSafetyView {
|
|
pub method: HttpMethod,
|
|
pub safety_class: Option<OperationSafetyClass>,
|
|
pub read_safe: bool,
|
|
pub approval_required: bool,
|
|
}
|
|
|
|
#[derive(Clone, Debug, Serialize)]
|
|
pub(crate) struct TemplateAccessView {
|
|
pub security_level: Value,
|
|
pub auth_profile_ref: Option<String>,
|
|
}
|
|
|
|
impl ResourcesService {
|
|
/// Story 3.10: текущий Draft является template-определением (без bytes).
|
|
pub(crate) async fn is_template_draft(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
resource_id: &ResourceId,
|
|
) -> Result<bool, ResourceError> {
|
|
match self
|
|
.registry
|
|
.get_resource_draft(workspace_id.as_str(), resource_id)
|
|
.await
|
|
{
|
|
Ok(record) => Ok(record.version.source_kind == "template"),
|
|
Err(ResourceError::NotFound) => Ok(false),
|
|
Err(error) => Err(error),
|
|
}
|
|
}
|
|
|
|
/// Создание template Draft: source обязан ссылаться на exact same-workspace
|
|
/// Published версию; блocker findings на этом шаге не запрещают сохранение.
|
|
pub(crate) async fn create_template_draft(
|
|
&self,
|
|
draft: NewTemplateDraft,
|
|
) -> Result<CreatedDraft, ResourceError> {
|
|
let metadata = parse_metadata(&draft.metadata)?;
|
|
let definition = TemplateDefinition::parse(&draft.source)?;
|
|
self.pinned_version(&draft.workspace_id, &definition.source)
|
|
.await?;
|
|
let resource_id = generate_resource_id();
|
|
let now = truncate_to_micros(OffsetDateTime::now_utc());
|
|
let record = self
|
|
.registry
|
|
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
|
workspace_id: draft.workspace_id,
|
|
resource_id: resource_id.clone(),
|
|
uri: metadata.uri,
|
|
name: metadata.name,
|
|
description: metadata.description,
|
|
kind: metadata.kind.as_str().to_owned(),
|
|
mime_type: metadata.mime_type,
|
|
sensitivity: metadata.sensitivity.as_str().to_owned(),
|
|
definition_json: definition.json,
|
|
definition_digest: definition.digest,
|
|
created_at: now,
|
|
})
|
|
.await?;
|
|
Ok(CreatedDraft {
|
|
resource_id: record.snapshot.resource.resource_id,
|
|
})
|
|
}
|
|
|
|
/// Обновление template Draft: те же immutable-поля/precondition, новое определение.
|
|
pub(crate) async fn update_template_draft(
|
|
&self,
|
|
update: UpdateTemplateDraft,
|
|
) -> Result<ResourceCardResponse, ResourceError> {
|
|
let current = self
|
|
.registry
|
|
.get_resource_draft(update.workspace_id.as_str(), &update.resource_id)
|
|
.await?;
|
|
if current.version.source_kind != "template" {
|
|
return Err(ResourceError::SourceInvalid { field: "source" });
|
|
}
|
|
if update
|
|
.identity
|
|
.uri
|
|
.as_deref()
|
|
.is_some_and(|uri| uri != current.resource.uri)
|
|
{
|
|
return Err(ResourceError::FieldImmutable { field: "uri" });
|
|
}
|
|
if update
|
|
.identity
|
|
.name
|
|
.as_deref()
|
|
.is_some_and(|name| name != current.resource.name)
|
|
{
|
|
return Err(ResourceError::FieldImmutable { field: "name" });
|
|
}
|
|
if update
|
|
.identity
|
|
.kind
|
|
.as_deref()
|
|
.is_some_and(|kind| kind != current.resource.kind)
|
|
{
|
|
return Err(ResourceError::FieldImmutable { field: "kind" });
|
|
}
|
|
let current_kind = parse_kind(¤t.resource.kind)?;
|
|
if !ResourceMetadata::description_is_valid(&update.description) {
|
|
return Err(ResourceError::DescriptionInvalid);
|
|
}
|
|
if !ResourceMetadata::mime_syntax_is_valid(&update.mime_type) {
|
|
return Err(ResourceError::MimeSyntaxInvalid);
|
|
}
|
|
match ResourceKind::for_mime(&update.mime_type) {
|
|
None => return Err(ResourceError::MimeNotAllowed),
|
|
Some(owner) if owner != current_kind => return Err(ResourceError::KindMismatch),
|
|
Some(_) => {}
|
|
}
|
|
let sensitivity = parse_sensitivity(&update.sensitivity)?;
|
|
let expected_updated_at = update
|
|
.expected_updated_at
|
|
.as_deref()
|
|
.map(parse_timestamp)
|
|
.transpose()?
|
|
.ok_or(ResourceError::Stale)?;
|
|
if expected_updated_at != current.resource.updated_at {
|
|
return Err(ResourceError::Stale);
|
|
}
|
|
if current.resource.status == crank_core::resource::ResourceStatus::Archived {
|
|
return Err(ResourceError::InvalidLifecycleTransition {
|
|
from: current.resource.status,
|
|
to: crank_core::resource::ResourceStatus::Draft,
|
|
});
|
|
}
|
|
let source = update
|
|
.source
|
|
.ok_or(ResourceError::SourceInvalid { field: "source" })?;
|
|
let definition = TemplateDefinition::parse(&source)?;
|
|
self.pinned_version(&update.workspace_id, &definition.source)
|
|
.await?;
|
|
self.registry
|
|
.update_resource_template_draft(UpdateResourceTemplateDraftRequest {
|
|
workspace_id: update.workspace_id.clone(),
|
|
resource_id: update.resource_id.clone(),
|
|
description: update.description,
|
|
mime_type: update.mime_type,
|
|
sensitivity: sensitivity.as_str().to_owned(),
|
|
expected_updated_at,
|
|
definition_json: definition.json,
|
|
definition_digest: definition.digest,
|
|
})
|
|
.await?;
|
|
self.card(&update.workspace_id, &update.resource_id).await
|
|
}
|
|
|
|
/// Публикация template Draft: сохранённое определение перепроверяется целиком,
|
|
/// затем reference разрешается заново (tampering не проходит), и только после
|
|
/// этого создаётся immutable publication snapshot.
|
|
pub(crate) async fn publish_template(
|
|
&self,
|
|
request: super::PublishResource,
|
|
current: crank_registry::model::resource::ResourceDraftRecord,
|
|
) -> Result<PublishedVersionResponse, ResourceError> {
|
|
let expected_updated_at = request
|
|
.expected_updated_at
|
|
.as_deref()
|
|
.map(parse_timestamp)
|
|
.transpose()?
|
|
.ok_or(ResourceError::Stale)?;
|
|
if expected_updated_at != current.resource.updated_at {
|
|
return Err(ResourceError::Stale);
|
|
}
|
|
if current.resource.status == crank_core::resource::ResourceStatus::Archived {
|
|
return Err(ResourceError::InvalidLifecycleTransition {
|
|
from: current.resource.status,
|
|
to: crank_core::resource::ResourceStatus::Published,
|
|
});
|
|
}
|
|
let stored = self
|
|
.registry
|
|
.get_resource_template_source(
|
|
request.workspace_id.as_str(),
|
|
&request.resource_id,
|
|
current.version.version,
|
|
)
|
|
.await?;
|
|
let definition = TemplateDefinition::from_stored(&stored)?;
|
|
let pinned = self
|
|
.pinned_version(&request.workspace_id, &definition.source)
|
|
.await?;
|
|
let findings = template_findings(&definition, &pinned);
|
|
if !findings.is_empty() {
|
|
return Err(ResourceError::SourceBlocked { findings });
|
|
}
|
|
let (publication, source) = self
|
|
.registry
|
|
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
|
|
workspace_id: request.workspace_id.clone(),
|
|
resource_id: request.resource_id.clone(),
|
|
expected_updated_at,
|
|
expected_version: current.version.version,
|
|
expected_digest: definition.digest,
|
|
published_at: truncate_to_micros(OffsetDateTime::now_utc()),
|
|
})
|
|
.await?;
|
|
let card = self
|
|
.card(&request.workspace_id, &request.resource_id)
|
|
.await?;
|
|
Ok(PublishedVersionResponse {
|
|
resource: card,
|
|
published_version: published_template_view(&publication, &source, &pinned)?,
|
|
})
|
|
}
|
|
|
|
/// Карточка template Draft: source view + blocker findings сохранённого определения.
|
|
pub(crate) async fn template_card(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
resource_id: &ResourceId,
|
|
version: u32,
|
|
) -> Result<(TemplateSourceView, Vec<PreviewFinding>), ResourceError> {
|
|
let stored = self
|
|
.registry
|
|
.get_resource_template_source(workspace_id.as_str(), resource_id, version)
|
|
.await?;
|
|
let definition = TemplateDefinition::from_stored(&stored)?;
|
|
let pinned = self
|
|
.pinned_version(workspace_id, &definition.source)
|
|
.await?;
|
|
let findings = template_findings(&definition, &pinned)
|
|
.into_iter()
|
|
.map(|finding| PreviewFinding {
|
|
code: finding.code(),
|
|
field: finding.field,
|
|
})
|
|
.collect();
|
|
Ok((source_view(&definition, &pinned), findings))
|
|
}
|
|
|
|
/// Exact Published Version шаблона (definition-only, без artifact-чтения).
|
|
pub(crate) async fn published_template_view(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
resource_id: &ResourceId,
|
|
version: u32,
|
|
) -> Result<PublishedVersionView, ResourceError> {
|
|
let (publication, source) = self
|
|
.registry
|
|
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
|
|
.await?;
|
|
let definition = TemplateDefinition::from_stored(&source)?;
|
|
let pinned = self
|
|
.pinned_version(workspace_id, &definition.source)
|
|
.await?;
|
|
published_template_view(&publication, &source, &pinned)
|
|
}
|
|
|
|
/// Точная Published версия является template-определением (без bytes).
|
|
pub(crate) async fn publication_is_template(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
resource_id: &ResourceId,
|
|
version: u32,
|
|
) -> Result<bool, ResourceError> {
|
|
match self
|
|
.registry
|
|
.resolve_resource_publication(workspace_id.as_str(), resource_id, version)
|
|
.await
|
|
{
|
|
Ok(_) => Ok(false),
|
|
Err(ResourceError::NotFound) => match self
|
|
.registry
|
|
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
|
|
.await
|
|
{
|
|
Ok(_) => Ok(true),
|
|
Err(ResourceError::NotFound) => Err(ResourceError::NotFound),
|
|
Err(error) => Err(error),
|
|
},
|
|
Err(error) => Err(error),
|
|
}
|
|
}
|
|
|
|
async fn pinned_version(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
source: &TemplateSource,
|
|
) -> Result<OperationVersionRecord, ResourceError> {
|
|
let operation_id: OperationId = source.operation_id.as_str().into();
|
|
let record = self
|
|
.registry
|
|
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
|
.await
|
|
.map_err(|_| ResourceError::StorageUnavailable)?
|
|
.ok_or(ResourceError::SourceNotFound)?;
|
|
if record.status != OperationStatus::Published {
|
|
return Err(ResourceError::SourceNotPublished);
|
|
}
|
|
Ok(record)
|
|
}
|
|
}
|
|
|
|
/// Blockers шаблона на pinned версии: read-safety, mapping параметров, cache policy.
|
|
pub(crate) fn template_findings(
|
|
definition: &TemplateDefinition,
|
|
pinned: &OperationVersionRecord,
|
|
) -> Vec<TemplateFinding> {
|
|
let source = &definition.source;
|
|
let snapshot = &pinned.snapshot;
|
|
let Target::Rest(target) = &snapshot.target;
|
|
let safety: Option<&OperationSafetyPolicy> = snapshot.execution_config.safety.as_ref();
|
|
let approval: Option<&OperationApprovalPolicy> =
|
|
snapshot.execution_config.approval_policy.as_ref();
|
|
let approval_required = approval.is_some_and(|policy| policy.required);
|
|
let read_safe = matches!(target.method, HttpMethod::Get | HttpMethod::Head)
|
|
&& safety.is_some_and(|policy| policy.class == OperationSafetyClass::Read)
|
|
&& !approval_required;
|
|
|
|
let mut findings = Vec::new();
|
|
if !read_safe {
|
|
findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::NotReadSafe,
|
|
"source.operation_id",
|
|
));
|
|
}
|
|
|
|
let placeholders = parse_uri_template(&source.uri_template).unwrap_or_default();
|
|
let placeholder_set: BTreeSet<&str> = placeholders.iter().map(String::as_str).collect();
|
|
let names: BTreeSet<&str> = source
|
|
.parameters
|
|
.iter()
|
|
.map(|parameter| parameter.name.as_str())
|
|
.collect();
|
|
if names.len() != source.parameters.len() || placeholder_set.len() != placeholders.len() {
|
|
findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterDuplicate,
|
|
"source.parameters",
|
|
));
|
|
}
|
|
let mut input_paths = BTreeSet::new();
|
|
if source
|
|
.parameters
|
|
.iter()
|
|
.any(|parameter| !input_paths.insert(parameter.input_path.as_str()))
|
|
{
|
|
findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterDuplicate,
|
|
"source.parameters",
|
|
));
|
|
}
|
|
for parameter in &source.parameters {
|
|
if !placeholder_set.contains(parameter.name.as_str()) {
|
|
findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterUnknown,
|
|
"source.parameters",
|
|
));
|
|
}
|
|
}
|
|
for placeholder in &placeholders {
|
|
if !names.contains(placeholder.as_str()) {
|
|
findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterUnmapped,
|
|
"source.uri_template",
|
|
));
|
|
}
|
|
}
|
|
for (parameter, schema) in source.parameters.iter().zip(&definition.schemas) {
|
|
match resolve_input_field(&snapshot.input_schema, ¶meter.input_path) {
|
|
Some(pinned_field) => {
|
|
findings.extend(parameter_mismatches(schema, pinned_field));
|
|
findings.extend(parameter_default_findings(schema, pinned_field));
|
|
}
|
|
None => findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterUnmapped,
|
|
"source.parameters",
|
|
)),
|
|
}
|
|
}
|
|
findings.extend(cache_policy_findings(&source.cache, &names));
|
|
findings
|
|
}
|
|
|
|
fn parameter_mismatches(schema: &Schema, pinned: &Schema) -> Vec<TemplateFinding> {
|
|
let mut findings = Vec::new();
|
|
let incompatible = matches!(
|
|
schema.kind,
|
|
SchemaKind::Object | SchemaKind::Array | SchemaKind::Oneof
|
|
) || schema.kind != pinned.kind
|
|
|| schema
|
|
.format
|
|
.as_ref()
|
|
.is_some_and(|format| pinned.format.as_ref() != Some(format))
|
|
|| (!schema.enum_values.is_empty()
|
|
&& schema
|
|
.enum_values
|
|
.iter()
|
|
.any(|value| !pinned.enum_values.contains(value)));
|
|
if incompatible {
|
|
findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterTypeMismatch,
|
|
"source.parameters",
|
|
));
|
|
}
|
|
findings
|
|
}
|
|
|
|
fn parameter_default_findings(schema: &Schema, pinned: &Schema) -> Vec<TemplateFinding> {
|
|
let mut findings = Vec::new();
|
|
match &schema.default_value {
|
|
Some(default) => {
|
|
let enum_violation =
|
|
[&schema.enum_values, &pinned.enum_values]
|
|
.into_iter()
|
|
.any(|values| {
|
|
!values.is_empty()
|
|
&& default
|
|
.as_str()
|
|
.is_none_or(|value| !values.iter().any(|item| item == value))
|
|
});
|
|
if enum_violation
|
|
|| !default_matches_schema(schema, default)
|
|
|| !default_matches_schema(pinned, default)
|
|
{
|
|
findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterDefaultInvalid,
|
|
"source.parameters",
|
|
));
|
|
}
|
|
}
|
|
None if !schema.required => findings.push(TemplateFinding::new(
|
|
TemplateFindingCode::ParameterOptionalWithoutDefault,
|
|
"source.parameters",
|
|
)),
|
|
None => {}
|
|
}
|
|
findings
|
|
}
|
|
|
|
/// Соответствие default объявленному `crank_schema::Schema` (definition-time).
|
|
///
|
|
/// Runtime schema-shape validation намеренно не вызывается: admin-api находится
|
|
/// за execution boundary (никаких runtime execute/mapping/validation вызовов в
|
|
/// этом слое). Здесь используются только типовые факты уже разобранной схемы;
|
|
/// новых языков схем не вводится.
|
|
fn default_matches_schema(schema: &Schema, default: &Value) -> bool {
|
|
if default.is_null() {
|
|
return schema.nullable || schema.kind == SchemaKind::Null;
|
|
}
|
|
match schema.kind {
|
|
SchemaKind::Object => default.is_object(),
|
|
SchemaKind::Array => default.is_array(),
|
|
SchemaKind::String => default.is_string(),
|
|
SchemaKind::Integer => default.is_i64() || default.is_u64(),
|
|
SchemaKind::Number => default.is_number(),
|
|
SchemaKind::Boolean => default.is_boolean(),
|
|
SchemaKind::Enum => default
|
|
.as_str()
|
|
.is_some_and(|value| schema.enum_values.iter().any(|item| item == value)),
|
|
SchemaKind::Null => false,
|
|
SchemaKind::Oneof => schema
|
|
.variants
|
|
.iter()
|
|
.any(|variant| default_matches_schema(variant, default)),
|
|
}
|
|
}
|
|
|
|
/// `input.order_id` → поле pinned `input_schema` (не `request.path`).
|
|
fn resolve_input_field<'a>(input_schema: &'a Schema, input_path: &str) -> Option<&'a Schema> {
|
|
let mut segments = input_path.split('.');
|
|
if segments.next()? != "input" {
|
|
return None;
|
|
}
|
|
let mut current = input_schema;
|
|
let mut matched = false;
|
|
for segment in segments {
|
|
current = current.field(segment)?;
|
|
matched = true;
|
|
}
|
|
matched.then_some(current)
|
|
}
|
|
|
|
fn source_view(
|
|
definition: &TemplateDefinition,
|
|
pinned: &OperationVersionRecord,
|
|
) -> TemplateSourceView {
|
|
let source = &definition.source;
|
|
let snapshot = &pinned.snapshot;
|
|
let Target::Rest(target) = &snapshot.target;
|
|
let safety = snapshot.execution_config.safety.as_ref();
|
|
let approval_required = snapshot
|
|
.execution_config
|
|
.approval_policy
|
|
.as_ref()
|
|
.is_some_and(|policy| policy.required);
|
|
let read_safe = matches!(target.method, HttpMethod::Get | HttpMethod::Head)
|
|
&& safety.is_some_and(|policy| policy.class == OperationSafetyClass::Read)
|
|
&& !approval_required;
|
|
TemplateSourceView {
|
|
operation_id: source.operation_id.clone(),
|
|
operation_version: source.operation_version,
|
|
uri_template: source.uri_template.clone(),
|
|
parameters: source
|
|
.parameters
|
|
.iter()
|
|
.map(|parameter| {
|
|
serde_json::json!({
|
|
"name": parameter.name,
|
|
"input_path": parameter.input_path,
|
|
"schema": parameter.schema,
|
|
})
|
|
})
|
|
.collect(),
|
|
cache: TemplateCacheView {
|
|
ttl_ms: source.cache.ttl_ms,
|
|
vary: source.cache.vary.clone(),
|
|
max_bytes: source.cache.max_bytes,
|
|
scope: TEMPLATE_CACHE_SCOPE,
|
|
},
|
|
failure: TemplateFailureView { outcome: "error" },
|
|
read_safety: TemplateReadSafetyView {
|
|
method: target.method,
|
|
safety_class: safety.map(|policy| policy.class),
|
|
read_safe,
|
|
approval_required,
|
|
},
|
|
access: TemplateAccessView {
|
|
security_level: serde_json::to_value(snapshot.security_level).unwrap_or(Value::Null),
|
|
auth_profile_ref: snapshot
|
|
.execution_config
|
|
.auth_profile_ref
|
|
.as_ref()
|
|
.map(|profile| profile.as_str().to_owned()),
|
|
},
|
|
}
|
|
}
|
|
|
|
fn published_template_view(
|
|
publication: &ResourcePublicationRecord,
|
|
source: &ResourceTemplateSourceRecord,
|
|
pinned: &OperationVersionRecord,
|
|
) -> Result<PublishedVersionView, ResourceError> {
|
|
let definition = TemplateDefinition::from_stored(source)?;
|
|
Ok(PublishedVersionView {
|
|
version: publication.version,
|
|
uri: publication.uri.clone(),
|
|
name: publication.name.clone(),
|
|
description: publication.description.clone(),
|
|
kind: publication.kind.clone(),
|
|
mime_type: publication.mime_type.clone(),
|
|
size_bytes: publication.size_bytes,
|
|
digest: publication.digest.clone(),
|
|
sensitivity: publication.sensitivity.clone(),
|
|
source: Some(source_view(&definition, pinned)),
|
|
})
|
|
}
|