feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.
Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
resources/list admission fix for bound template publications.
Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
`just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
a real MCP Inspector 2.12.0 client smoke.
Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
runs only on main), story events run the changed packages, the full workspace suite
stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
release entry of the tag instead of dying with the runner workspace.
Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.
Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
This commit is contained in:
1 parent
1b6db09bd1
commit
54ce770682
357 files changed
+117394
-5115
No files matched your search
@@ -0,0 +1,297 @@
|
||||
//! Story 3.9: bounded portability envelope — экспорт текущего Draft / точной
|
||||
//! Published Version и импорт как **нового** Draft текущего владельца.
|
||||
//!
|
||||
//! Транспортный контракт (allowlist ключей, base64, digest) живёт здесь, в admin-api:
|
||||
//! домен (`crank-core`) отвечает только за стабильный код отказа
|
||||
//! `resource_portability_envelope_invalid`. Импорт не восстанавливает идентичность:
|
||||
//! `source` — только provenance, новый Resource всегда получает новый `resource_id`,
|
||||
//! `current_draft_version = 1` и не публикуется. Владелец и target workspace берутся
|
||||
//! из authenticated session и URL, никогда из envelope.
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::ids::ResourceId;
|
||||
use crank_core::resource::{ResourceError, ResourceKind};
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use super::{DraftMetadata, NewDraft, ResourcesService};
|
||||
|
||||
/// Единственный поддерживаемый формат переносимого документа.
|
||||
pub(crate) const ENVELOPE_FORMAT: &str = "crank-resource-portability";
|
||||
pub(crate) const ENVELOPE_VERSION: u64 = 1;
|
||||
|
||||
/// Предел тела импорта: base64-накладные расходы (`MAX_ARTIFACT_BYTES / 3 * 4`) плюс
|
||||
/// 64 KiB на metadata оболочки. Равен 415 060 байт; лимит содержимого не меняется.
|
||||
pub(crate) const MAX_IMPORT_BODY_BYTES: usize =
|
||||
crank_artifacts::MAX_ARTIFACT_BYTES / 3 * 4 + 64 * 1024;
|
||||
|
||||
const ROOT_KEYS: [&str; 5] = ["format", "version", "resource", "source", "content"];
|
||||
const RESOURCE_KEYS: [&str; 6] = [
|
||||
"uri",
|
||||
"name",
|
||||
"description",
|
||||
"kind",
|
||||
"mime_type",
|
||||
"sensitivity",
|
||||
];
|
||||
const SOURCE_KEYS: [&str; 2] = ["kind", "version"];
|
||||
const CONTENT_KEYS: [&str; 3] = ["size_bytes", "digest", "base64"];
|
||||
|
||||
/// Переносимый документ в wire-форме (экспорт и разобранный импорт).
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct PortableEnvelope {
|
||||
pub format: &'static str,
|
||||
pub version: u64,
|
||||
pub resource: PortableResourceBlock,
|
||||
pub source: PortableSourceBlock,
|
||||
pub content: PortableContentBlock,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct PortableResourceBlock {
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: String,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: String,
|
||||
}
|
||||
|
||||
/// `source` — только provenance: `draft` с ревизией содержимого либо `published`
|
||||
/// с номером точной версии. Импорт по нему ничего не восстанавливает.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct PortableSourceBlock {
|
||||
pub kind: String,
|
||||
pub version: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct PortableContentBlock {
|
||||
pub size_bytes: i64,
|
||||
pub digest: String,
|
||||
pub base64: String,
|
||||
}
|
||||
|
||||
/// Разобранный envelope импорта: metadata + уже декодированные bytes.
|
||||
pub(crate) struct PortableImport {
|
||||
pub resource: PortableResourceBlock,
|
||||
pub bytes: Vec<u8>,
|
||||
pub size_bytes: i64,
|
||||
pub digest: String,
|
||||
}
|
||||
|
||||
impl ResourcesService {
|
||||
/// Экспорт текущего содержимого Draft: metadata и bytes берутся из **одного**
|
||||
/// pinned-разрешения версии, второй путь чтения не открывается.
|
||||
pub(crate) async fn export_draft_envelope(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<PortableEnvelope, ResourceError> {
|
||||
// Story 3.10: definition-only Resource не переносим (нет content envelope).
|
||||
if self.is_template_draft(workspace_id, resource_id).await? {
|
||||
return Err(ResourceError::SourceNotPortable);
|
||||
}
|
||||
let (bytes, resolved) = self.load_content(workspace_id, resource_id).await?;
|
||||
let snapshot = resolved.snapshot;
|
||||
Ok(PortableEnvelope {
|
||||
format: ENVELOPE_FORMAT,
|
||||
version: ENVELOPE_VERSION,
|
||||
resource: PortableResourceBlock {
|
||||
uri: snapshot.resource.uri,
|
||||
name: snapshot.resource.name,
|
||||
description: snapshot.resource.description,
|
||||
kind: snapshot.resource.kind,
|
||||
mime_type: snapshot.version.mime_type,
|
||||
sensitivity: snapshot.version.sensitivity,
|
||||
},
|
||||
source: PortableSourceBlock {
|
||||
kind: "draft".to_owned(),
|
||||
version: snapshot.version.version,
|
||||
},
|
||||
content: content_block(&bytes),
|
||||
})
|
||||
}
|
||||
|
||||
/// Экспорт **точной** Published Version: immutable snapshot и его bytes из одного
|
||||
/// разрешения; существующие revoke/read/integrity semantics сохраняются, второго
|
||||
/// пути чтения `ArtifactStore` не открывается.
|
||||
pub(crate) async fn export_published_envelope(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
) -> Result<PortableEnvelope, ResourceError> {
|
||||
// Story 3.10: опубликованное определение шаблона не экспортируется как content.
|
||||
if self
|
||||
.publication_is_template(workspace_id, resource_id, version)
|
||||
.await?
|
||||
{
|
||||
return Err(ResourceError::SourceNotPortable);
|
||||
}
|
||||
let (bytes, publication) = self
|
||||
.load_published_content(workspace_id, resource_id, version)
|
||||
.await?;
|
||||
Ok(PortableEnvelope {
|
||||
format: ENVELOPE_FORMAT,
|
||||
version: ENVELOPE_VERSION,
|
||||
resource: PortableResourceBlock {
|
||||
uri: publication.uri,
|
||||
name: publication.name,
|
||||
description: publication.description,
|
||||
kind: publication.kind,
|
||||
mime_type: publication.mime_type,
|
||||
sensitivity: publication.sensitivity,
|
||||
},
|
||||
source: PortableSourceBlock {
|
||||
kind: "published".to_owned(),
|
||||
version: publication.version,
|
||||
},
|
||||
content: content_block(&bytes),
|
||||
})
|
||||
}
|
||||
|
||||
/// Импорт envelope: integrity/bounded-проверки → существующий `create_draft`.
|
||||
///
|
||||
/// Никакого upsert/update: при занятых uri/name реестр отвечает существующими
|
||||
/// `resource_uri_duplicate` / `resource_name_duplicate` (409). Публикации нет.
|
||||
pub(crate) async fn import_envelope(
|
||||
&self,
|
||||
workspace_id: WorkspaceId,
|
||||
import: PortableImport,
|
||||
) -> Result<super::ResourceCardResponse, ResourceError> {
|
||||
let PortableImport {
|
||||
resource,
|
||||
bytes,
|
||||
size_bytes,
|
||||
digest,
|
||||
} = import;
|
||||
if i64::try_from(bytes.len()).unwrap_or(i64::MAX) != size_bytes
|
||||
|| super::sha256_hex(&bytes) != digest
|
||||
{
|
||||
return Err(ResourceError::ArtifactIntegrity);
|
||||
}
|
||||
let kind = ResourceKind::parse(&resource.kind).ok_or(ResourceError::KindMismatch)?;
|
||||
if bytes.len() > self.limits.effective_limit(kind) {
|
||||
return Err(ResourceError::ContentTooLarge);
|
||||
}
|
||||
let created = self
|
||||
.create_draft(NewDraft {
|
||||
workspace_id: workspace_id.clone(),
|
||||
metadata: DraftMetadata {
|
||||
uri: resource.uri,
|
||||
name: resource.name,
|
||||
description: resource.description,
|
||||
kind: resource.kind,
|
||||
mime_type: resource.mime_type,
|
||||
sensitivity: resource.sensitivity,
|
||||
},
|
||||
bytes,
|
||||
})
|
||||
.await?;
|
||||
self.card(&workspace_id, &created.resource_id).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Разбор envelope со **строгим** allowlist: любой неизвестный ключ (в том числе
|
||||
/// `artifact`, `owner`, `workspace_id`, `resource_id`, `status`, `path`) — отказ формы.
|
||||
pub(crate) fn parse_portable_envelope(value: &Value) -> Result<PortableImport, ResourceError> {
|
||||
let root = block(value, &ROOT_KEYS)?;
|
||||
if root["format"].as_str() != Some(ENVELOPE_FORMAT) {
|
||||
return Err(envelope_invalid());
|
||||
}
|
||||
if root["version"].as_u64() != Some(ENVELOPE_VERSION) {
|
||||
return Err(envelope_invalid());
|
||||
}
|
||||
|
||||
let resource = block(&root["resource"], &RESOURCE_KEYS)?;
|
||||
let resource = PortableResourceBlock {
|
||||
uri: text(resource, "uri")?,
|
||||
name: text(resource, "name")?,
|
||||
description: text(resource, "description")?,
|
||||
kind: text(resource, "kind")?,
|
||||
mime_type: text(resource, "mime_type")?,
|
||||
sensitivity: text(resource, "sensitivity")?,
|
||||
};
|
||||
|
||||
let source = block(&root["source"], &SOURCE_KEYS)?;
|
||||
match source["kind"].as_str() {
|
||||
Some("draft") | Some("published") => {}
|
||||
_ => return Err(envelope_invalid()),
|
||||
}
|
||||
// `source.version` — только provenance: проверяется по форме (целое ≥ 1) и не
|
||||
// восстанавливает ни ревизию, ни идентичность импортируемого Draft.
|
||||
source["version"]
|
||||
.as_u64()
|
||||
.filter(|value| (1..=u32::MAX as u64).contains(value))
|
||||
.ok_or_else(envelope_invalid)?;
|
||||
|
||||
let content = block(&root["content"], &CONTENT_KEYS)?;
|
||||
let size_bytes = content["size_bytes"]
|
||||
.as_i64()
|
||||
.filter(|value| *value >= 0)
|
||||
.ok_or_else(envelope_invalid)?;
|
||||
let digest = text(content, "digest")?;
|
||||
let digest_is_lowercase_hex = digest.len() == 64
|
||||
&& digest
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase());
|
||||
if !digest_is_lowercase_hex {
|
||||
return Err(envelope_invalid());
|
||||
}
|
||||
let encoded = text(content, "base64")?;
|
||||
let bytes = BASE64
|
||||
.decode(encoded.as_bytes())
|
||||
.map_err(|_| envelope_invalid())?;
|
||||
|
||||
Ok(PortableImport {
|
||||
resource,
|
||||
bytes,
|
||||
size_bytes,
|
||||
digest,
|
||||
})
|
||||
}
|
||||
|
||||
/// `<sanitized name>.crank-resource.json` — только ASCII, без CR/LF и traversal.
|
||||
pub(crate) fn export_filename(name: &str) -> String {
|
||||
let stem: String = name
|
||||
.chars()
|
||||
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
|
||||
.take(64)
|
||||
.collect();
|
||||
let stem = if stem.is_empty() {
|
||||
"resource"
|
||||
} else {
|
||||
stem.as_str()
|
||||
};
|
||||
format!("{stem}.crank-resource.json")
|
||||
}
|
||||
|
||||
fn content_block(bytes: &[u8]) -> PortableContentBlock {
|
||||
PortableContentBlock {
|
||||
size_bytes: i64::try_from(bytes.len()).unwrap_or(i64::MAX),
|
||||
digest: super::sha256_hex(bytes),
|
||||
base64: BASE64.encode(bytes),
|
||||
}
|
||||
}
|
||||
|
||||
/// Ровно объявленный набор ключей: объект, ни одного лишнего, ни одного недостающего.
|
||||
fn block<'a>(value: &'a Value, keys: &[&str]) -> Result<&'a Map<String, Value>, ResourceError> {
|
||||
let object = value.as_object().ok_or_else(envelope_invalid)?;
|
||||
if object.len() != keys.len() || object.keys().any(|key| !keys.contains(&key.as_str())) {
|
||||
return Err(envelope_invalid());
|
||||
}
|
||||
Ok(object)
|
||||
}
|
||||
|
||||
fn text(object: &Map<String, Value>, key: &str) -> Result<String, ResourceError> {
|
||||
object[key]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(envelope_invalid)
|
||||
}
|
||||
|
||||
fn envelope_invalid() -> ResourceError {
|
||||
ResourceError::PortabilityEnvelopeInvalid
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Preview-снимок Resource: metadata, безопасные findings и инертный `text` (D-6, AC01).
|
||||
//!
|
||||
//! Вынесено из `service/resources.rs` ради health-лимита 1000 строк: preview —
|
||||
//! единственный второй читатель pinned-снимка, и его findings обязаны считаться теми
|
||||
//! же validators/scanner, что и публикация.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl ResourcesService {
|
||||
/// Preview: метаданные + findings + инертный `text` только для text/json (D-6).
|
||||
///
|
||||
/// Metadata и bytes относятся к **одному** разрешению версии: второй запрос за
|
||||
/// card-строкой смешал бы metadata версии N с bytes версии N+1 при одновременном
|
||||
/// обновлении (P3, TL F05).
|
||||
pub(crate) async fn preview(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
) -> Result<ResourcePreviewResponse, ResourceError> {
|
||||
// Story 3.10: template Draft не имеет bytes — preview отдаёт findings и text=null,
|
||||
// не обращаясь ни к artifact store, ни к REST.
|
||||
let record = self
|
||||
.registry
|
||||
.get_resource_draft(workspace_id.as_str(), resource_id)
|
||||
.await?;
|
||||
if record.version.source_kind == "template" {
|
||||
let (source, findings) = self
|
||||
.template_card(workspace_id, resource_id, record.version.version)
|
||||
.await?;
|
||||
let card = ResourceCardResponse::from_record(&record);
|
||||
return Ok(ResourcePreviewResponse {
|
||||
resource: card.resource,
|
||||
version: card.version,
|
||||
findings,
|
||||
preview: ResourcePreviewView { text: None },
|
||||
source: Some(source),
|
||||
});
|
||||
}
|
||||
let (bytes, resolved) = self.load_content(workspace_id, resource_id).await?;
|
||||
let card = ResourceCardResponse::from_record(&resolved.snapshot);
|
||||
let kind = card.kind()?;
|
||||
let text = match kind {
|
||||
ResourceKind::Text | ResourceKind::Json => Some(
|
||||
String::from_utf8(bytes.clone()).map_err(|_| ResourceError::ContentInvalidUtf8)?,
|
||||
),
|
||||
// Для binary bytes не возвращаются вообще.
|
||||
ResourceKind::Binary => None,
|
||||
};
|
||||
let findings = self
|
||||
.preview_findings(workspace_id, &card, kind, &bytes)
|
||||
.await?;
|
||||
Ok(ResourcePreviewResponse {
|
||||
resource: card.resource,
|
||||
version: card.version,
|
||||
findings,
|
||||
preview: ResourcePreviewView { text },
|
||||
source: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Findings preview (AC01): те же validators/scanner, что и у публикации, на тех же
|
||||
/// pinned bytes. Наружу уходят только стабильные `code`/`field`; bytes содержимого,
|
||||
/// совпавший фрагмент и цель `include:` никогда не попадают в ответ.
|
||||
async fn preview_findings(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
card: &ResourceCardResponse,
|
||||
kind: ResourceKind,
|
||||
bytes: &[u8],
|
||||
) -> Result<Vec<PreviewFinding>, ResourceError> {
|
||||
let mut findings = Vec::new();
|
||||
let metadata = ResourceMetadata {
|
||||
uri: card.resource.uri.clone(),
|
||||
name: card.resource.name.clone(),
|
||||
description: card.resource.description.clone(),
|
||||
kind,
|
||||
mime_type: card.version.mime_type.clone(),
|
||||
sensitivity: parse_sensitivity(&card.version.sensitivity)?,
|
||||
};
|
||||
if let Err(error) =
|
||||
ResourceMetadata::validate_content(kind, &metadata.mime_type, bytes, &self.limits)
|
||||
{
|
||||
findings.push(PreviewFinding::from_error(&error));
|
||||
}
|
||||
for error in self
|
||||
.publication_findings(workspace_id, &metadata, bytes)
|
||||
.await?
|
||||
{
|
||||
findings.push(PreviewFinding::from_error(&error));
|
||||
}
|
||||
Ok(findings)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Отзыв Resource (Story 3.8): отдельная security-команда, не lifecycle-переход.
|
||||
//!
|
||||
//! Слой Admin не решает, что значит отзыв: он передаёт actor/корреляцию из
|
||||
//! серверной сессии и `RequestContext`, а единственную транзакцию и tombstone
|
||||
//! создаёт реестр. Archive, immutable bytes и защищённое административное чтение
|
||||
//! этой командой не меняются.
|
||||
|
||||
use crank_core::resource::ResourceError;
|
||||
use crank_registry::model::resource::RevokeResourceRequest;
|
||||
|
||||
use super::ResourcesService;
|
||||
|
||||
impl ResourcesService {
|
||||
pub(crate) async fn revoke(&self, request: RevokeResourceRequest) -> Result<(), ResourceError> {
|
||||
self.registry.revoke_resource(request).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
//! 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)),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
use super::*;
|
||||
use base64::Engine as _;
|
||||
|
||||
impl ResourcesService {
|
||||
async fn test_resource_read(
|
||||
&self,
|
||||
admin: &super::super::AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
body: Value,
|
||||
correlation: &crank_core::CorrelationContext,
|
||||
) -> Result<Value, ApiError> {
|
||||
let object = body
|
||||
.as_object()
|
||||
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
|
||||
if object.len() != 4
|
||||
|| !["version", "digest", "updated_at", "parameters"]
|
||||
.iter()
|
||||
.all(|key| object.contains_key(*key))
|
||||
{
|
||||
return Err(ApiError::validation("invalid resource test request"));
|
||||
}
|
||||
let version = object
|
||||
.get("version")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|v| u32::try_from(v).ok())
|
||||
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
|
||||
let digest = object
|
||||
.get("digest")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
|
||||
let updated_at = object
|
||||
.get("updated_at")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
|
||||
let values = object
|
||||
.get("parameters")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or_else(|| ApiError::validation("invalid resource test request"))?;
|
||||
|
||||
let current = admin.resources.card(workspace_id, resource_id).await?;
|
||||
if current.resource.updated_at != updated_at
|
||||
|| current.version.version != version
|
||||
|| current.version.digest != digest
|
||||
{
|
||||
return Err(ApiError::conflict_with_context(
|
||||
"Resource changed; reload before testing",
|
||||
json!({"error_code":"resource_stale","recovery":"reload"}),
|
||||
));
|
||||
}
|
||||
if current.resource.status == crank_core::resource::ResourceStatus::Archived {
|
||||
return Err(
|
||||
crank_core::resource::ResourceError::InvalidLifecycleTransition {
|
||||
from: current.resource.status,
|
||||
to: crank_core::resource::ResourceStatus::Draft,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
let stored = admin
|
||||
.registry
|
||||
.get_resource_template_source(workspace_id.as_str(), resource_id, version)
|
||||
.await?;
|
||||
let definition = template::TemplateDefinition::from_stored(&stored)?;
|
||||
let source = &definition.source;
|
||||
let operation_id: crank_core::OperationId = source.operation_id.as_str().into();
|
||||
let operation = admin
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await?
|
||||
.ok_or(crank_core::resource::ResourceError::SourceNotFound)?;
|
||||
if operation.status != crank_core::operation::OperationStatus::Published {
|
||||
return Err(crank_core::resource::ResourceError::SourceNotPublished.into());
|
||||
}
|
||||
let operation_detail = admin.get_operation(workspace_id, &operation_id).await?;
|
||||
if operation_detail.status == crank_core::operation::OperationStatus::Archived {
|
||||
return Err(crank_core::resource::ResourceError::SourceNotPublished.into());
|
||||
}
|
||||
let findings = template::template_findings(&definition, &operation);
|
||||
if !findings.is_empty() {
|
||||
return Err(crank_core::resource::ResourceError::SourceBlocked { findings }.into());
|
||||
}
|
||||
if values.keys().any(|name| {
|
||||
!source
|
||||
.parameters
|
||||
.iter()
|
||||
.any(|parameter| ¶meter.name == name)
|
||||
}) {
|
||||
return Err(ApiError::validation(
|
||||
"resource parameters do not match the saved definition",
|
||||
));
|
||||
}
|
||||
let mut input = serde_json::Map::new();
|
||||
for (parameter, schema) in source.parameters.iter().zip(&definition.schemas) {
|
||||
let value = values
|
||||
.get(¶meter.name)
|
||||
.or(schema.default_value.as_ref())
|
||||
.ok_or_else(|| {
|
||||
ApiError::validation("resource parameters do not match the saved definition")
|
||||
})?;
|
||||
let parameter_schema: crank_schema::Schema =
|
||||
serde_json::from_value(parameter.schema.clone()).map_err(|_| {
|
||||
ApiError::validation("saved resource parameter schema is invalid")
|
||||
})?;
|
||||
crank_runtime::validate_resource_template_parameter(¶meter_schema, value).map_err(
|
||||
|_| ApiError::validation("resource parameter does not match the saved definition"),
|
||||
)?;
|
||||
// Validate the narrower Resource contract before assembling input; the runtime
|
||||
// separately validates the pinned Operation contract before outbound dispatch.
|
||||
if !set_resource_input_path(&mut input, ¶meter.input_path, value.clone()) {
|
||||
return Err(ApiError::validation(
|
||||
"saved resource parameter mapping is invalid",
|
||||
));
|
||||
}
|
||||
}
|
||||
let runtime = crank_runtime::RuntimeOperation::from(operation.snapshot.clone());
|
||||
let context = crank_runtime::RuntimeRequestContext::from_correlation(correlation)
|
||||
.with_metering_context(
|
||||
workspace_id.clone(),
|
||||
None,
|
||||
crank_core::InvocationSource::AdminTestRun,
|
||||
);
|
||||
let request_id = context.request_id.as_str().to_owned();
|
||||
let trace_id = context.trace_context.trace_id().to_string();
|
||||
let auth = admin
|
||||
.resolve_operation_auth(workspace_id, &runtime.execution_config, None)
|
||||
.await
|
||||
.map_err(|_| {
|
||||
ApiError::unprocessable_with_context(
|
||||
"operation authorization is unavailable",
|
||||
json!({"error_code":"resource_test_authorization_failed"}),
|
||||
)
|
||||
})?;
|
||||
let deadline = std::time::Instant::now()
|
||||
+ std::time::Duration::from_millis(runtime.execution_config.timeout_ms.max(1));
|
||||
let input = Value::Object(input);
|
||||
let resource_guard = admin
|
||||
.registry
|
||||
.begin_authorized_resource_test_read(
|
||||
workspace_id.as_str(),
|
||||
resource_id,
|
||||
version,
|
||||
digest,
|
||||
)
|
||||
.await?;
|
||||
let execution = crank_runtime::RuntimeExecutionRequest::try_new(
|
||||
workspace_id,
|
||||
crank_core::ExecutionOrigin::AdminDraft,
|
||||
None,
|
||||
&runtime,
|
||||
&input,
|
||||
crank_runtime::ExecutionAuthorization::Authorized,
|
||||
auth.as_ref(),
|
||||
&context,
|
||||
deadline,
|
||||
)
|
||||
.map_err(|_| ApiError::validation("resource test request is invalid"))?;
|
||||
let started_at = std::time::Instant::now();
|
||||
let execution_result = admin.runtime.execute_outcome(execution).await;
|
||||
resource_guard.commit().await?;
|
||||
let duration_ms = u64::try_from(started_at.elapsed().as_millis()).unwrap_or(u64::MAX);
|
||||
match execution_result {
|
||||
Ok(success) => {
|
||||
let kind = crank_core::resource::ResourceKind::parse(¤t.resource.kind)
|
||||
.ok_or_else(|| ApiError::unprocessable_with_context("saved Resource kind is invalid", json!({"error_code":"resource_test_output_invalid","request_id":request_id,"trace_id":trace_id})))?;
|
||||
if !kind.allows_mime_type(¤t.version.mime_type) {
|
||||
return Err(ApiError::unprocessable_with_context(
|
||||
"saved Resource representation is invalid",
|
||||
json!({"error_code":"resource_test_output_invalid","request_id":request_id,"trace_id":trace_id}),
|
||||
));
|
||||
}
|
||||
let representation = match kind {
|
||||
crank_core::resource::ResourceKind::Text => success.output.as_str().map(str::as_bytes).map(Vec::from),
|
||||
crank_core::resource::ResourceKind::Json if !success.output.is_null() => serde_json::to_vec(&success.output).ok(),
|
||||
crank_core::resource::ResourceKind::Binary => success
|
||||
.output
|
||||
.as_object()
|
||||
.filter(|object| object.len() == 1 && object.contains_key("data_base64"))
|
||||
.and_then(|object| object.get("data_base64"))
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|encoded| base64::engine::general_purpose::STANDARD.decode(encoded).ok()),
|
||||
_ => None,
|
||||
}.filter(|bytes| !bytes.is_empty() && bytes.len() as u64 <= source.cache.max_bytes)
|
||||
.ok_or_else(|| ApiError::unprocessable_with_context(
|
||||
"test read output does not match the saved Resource contract",
|
||||
json!({"error_code":"resource_test_output_invalid","request_id":request_id,"trace_id":trace_id}),
|
||||
))?;
|
||||
let _representation = representation;
|
||||
let response_preview = crank_core::sanitize_invocation_preview(&success.output);
|
||||
admin
|
||||
.record_invocation(super::super::InvocationRecordRequest {
|
||||
workspace_id,
|
||||
agent_id: None,
|
||||
operation: &operation.snapshot,
|
||||
request_id: Some(&request_id),
|
||||
trace_id: Some(&trace_id),
|
||||
source: crank_core::InvocationSource::AdminTestRun,
|
||||
level: crank_core::InvocationLevel::Info,
|
||||
status: crank_core::InvocationStatus::Ok,
|
||||
message: "administrative Resource test read completed".to_owned(),
|
||||
status_code: None,
|
||||
error_kind: None,
|
||||
execution_stage: Some(crank_core::ExecutionStage::Runtime),
|
||||
execution_error_code: None,
|
||||
retryability: Some(crank_core::Retryability::Never),
|
||||
outcome_certainty: Some(crank_core::OutcomeCertainty::Certain),
|
||||
duration_ms,
|
||||
request_preview: success.request_preview.clone(),
|
||||
response_preview: response_preview.clone(),
|
||||
})
|
||||
.await;
|
||||
Ok(
|
||||
json!({"ok":true,"request_id":request_id,"trace_id":trace_id,"output":response_preview}),
|
||||
)
|
||||
}
|
||||
Err(failure) => {
|
||||
admin
|
||||
.record_invocation(super::super::InvocationRecordRequest {
|
||||
workspace_id,
|
||||
agent_id: None,
|
||||
operation: &operation.snapshot,
|
||||
request_id: Some(&request_id),
|
||||
trace_id: Some(&trace_id),
|
||||
source: crank_core::InvocationSource::AdminTestRun,
|
||||
level: crank_core::InvocationLevel::Error,
|
||||
status: crank_core::InvocationStatus::Error,
|
||||
message: "administrative Resource test read failed".to_owned(),
|
||||
status_code: failure.upstream_status(),
|
||||
error_kind: Some(failure.error_code().as_str().to_owned()),
|
||||
execution_stage: Some(failure.stage()),
|
||||
execution_error_code: Some(failure.error_code()),
|
||||
retryability: Some(failure.retryability()),
|
||||
outcome_certainty: Some(failure.outcome_certainty()),
|
||||
duration_ms,
|
||||
request_preview: Value::Null,
|
||||
response_preview: Value::Null,
|
||||
})
|
||||
.await;
|
||||
Ok(
|
||||
json!({"ok":false,"request_id":request_id,"trace_id":trace_id,"error":crate::error::execution_test_failure_localized(&failure, crank_core::ExecutionLocale::En)}),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn execute_template_test(
|
||||
&self,
|
||||
admin: &super::super::AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
body: Value,
|
||||
correlation: &crank_core::CorrelationContext,
|
||||
) -> Result<Value, ApiError> {
|
||||
self.test_resource_read(admin, workspace_id, resource_id, body, correlation)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Story 3.16 §4: pinned content of a dynamic (template) dependency.
|
||||
///
|
||||
/// The Prompt dependency names only the exact `(resource_id, version)` of the template, so the
|
||||
/// declared read Operation is executed through the same 3.11 runtime (authorization, outbound,
|
||||
/// size and live revocation gate) with the template's own parameter defaults. A parameter
|
||||
/// without a default cannot be supplied by a Prompt, and every failure stays `None` — the
|
||||
/// caller turns that into `prompt_dependency_unavailable` instead of substituting definition
|
||||
/// text or stale content.
|
||||
pub(crate) async fn read_pinned_template_content(
|
||||
&self,
|
||||
admin: &super::super::AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
resource_id: &ResourceId,
|
||||
version: u32,
|
||||
correlation: &crank_core::CorrelationContext,
|
||||
) -> Option<Vec<u8>> {
|
||||
let (publication, stored) = admin
|
||||
.registry
|
||||
.resolve_resource_template_publication(workspace_id.as_str(), resource_id, version)
|
||||
.await
|
||||
.ok()?;
|
||||
let kind = crank_core::resource::ResourceKind::parse(&publication.kind)?;
|
||||
if !kind.allows_mime_type(&publication.mime_type) {
|
||||
return None;
|
||||
}
|
||||
let definition = template::TemplateDefinition::from_stored(&stored).ok()?;
|
||||
let source = &definition.source;
|
||||
let operation_id: crank_core::OperationId = source.operation_id.as_str().into();
|
||||
let operation = admin
|
||||
.registry
|
||||
.get_operation_version(workspace_id, &operation_id, source.operation_version)
|
||||
.await
|
||||
.ok()??;
|
||||
if operation.status != crank_core::operation::OperationStatus::Published {
|
||||
return None;
|
||||
}
|
||||
let detail = admin
|
||||
.get_operation(workspace_id, &operation_id)
|
||||
.await
|
||||
.ok()?;
|
||||
if detail.status == crank_core::operation::OperationStatus::Archived {
|
||||
return None;
|
||||
}
|
||||
if !template::template_findings(&definition, &operation).is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut input = serde_json::Map::new();
|
||||
for (parameter, schema) in source.parameters.iter().zip(&definition.schemas) {
|
||||
let value = schema.default_value.as_ref()?;
|
||||
let parameter_schema: crank_schema::Schema =
|
||||
serde_json::from_value(parameter.schema.clone()).ok()?;
|
||||
crank_runtime::validate_resource_template_parameter(¶meter_schema, value).ok()?;
|
||||
if !set_resource_input_path(&mut input, ¶meter.input_path, value.clone()) {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let runtime = crank_runtime::RuntimeOperation::from(operation.snapshot.clone());
|
||||
let context = crank_runtime::RuntimeRequestContext::from_correlation(correlation)
|
||||
.with_metering_context(
|
||||
workspace_id.clone(),
|
||||
None,
|
||||
crank_core::InvocationSource::AdminTestRun,
|
||||
);
|
||||
let auth = admin
|
||||
.resolve_operation_auth(workspace_id, &runtime.execution_config, None)
|
||||
.await
|
||||
.ok()?;
|
||||
let deadline = std::time::Instant::now()
|
||||
+ std::time::Duration::from_millis(runtime.execution_config.timeout_ms.max(1));
|
||||
let input = Value::Object(input);
|
||||
let guard = admin
|
||||
.registry
|
||||
.begin_authorized_resource_template_read(
|
||||
workspace_id.as_str(),
|
||||
resource_id,
|
||||
publication.version,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
let request = crank_runtime::RuntimeExecutionRequest::try_new(
|
||||
workspace_id,
|
||||
crank_core::ExecutionOrigin::AdminDraft,
|
||||
None,
|
||||
&runtime,
|
||||
&input,
|
||||
crank_runtime::ExecutionAuthorization::Authorized,
|
||||
auth.as_ref(),
|
||||
&context,
|
||||
deadline,
|
||||
)
|
||||
.ok()?;
|
||||
let success = admin.runtime.execute_outcome(request).await.ok()?;
|
||||
guard.commit().await.ok()?;
|
||||
let max_bytes = usize::try_from(source.cache.max_bytes).unwrap_or(usize::MAX);
|
||||
match kind {
|
||||
crank_core::resource::ResourceKind::Text => {
|
||||
success.output.as_str().map(str::as_bytes).map(Vec::from)
|
||||
}
|
||||
crank_core::resource::ResourceKind::Json if !success.output.is_null() => {
|
||||
serde_json::to_vec(&success.output).ok()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
.filter(|bytes| !bytes.is_empty() && bytes.len() <= max_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fn set_resource_input_path(
|
||||
root: &mut serde_json::Map<String, Value>,
|
||||
path: &str,
|
||||
value: Value,
|
||||
) -> bool {
|
||||
let Some((prefix, tail)) = path.split_once('.') else {
|
||||
return false;
|
||||
};
|
||||
if prefix != "input" {
|
||||
return false;
|
||||
}
|
||||
let mut current = root;
|
||||
let mut parts = tail.split('.').peekable();
|
||||
while let Some(part) = parts.next() {
|
||||
if parts.peek().is_none() {
|
||||
return current.insert(part.to_owned(), value).is_none();
|
||||
}
|
||||
let entry = current.entry(part.to_owned()).or_insert_with(|| json!({}));
|
||||
let Some(object) = entry.as_object_mut() else {
|
||||
return false;
|
||||
};
|
||||
current = object;
|
||||
}
|
||||
false
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
//! BUILD-ONLY: in-crate counter harness Story 3.6 (D-19, пять именованных проверок).
|
||||
//!
|
||||
//! Статус на стадии Dev ATDD: **не зарегистрирован**. Файл лежит по пути, который BUILD
|
||||
//! объявит из production-модуля:
|
||||
//! ```text
|
||||
//! // apps/admin-api/src/service/resources.rs
|
||||
//! #[cfg(test)] pub(crate) mod counters { /* inline: note_artifact_put/read, artifact_puts/reads, reset */ }
|
||||
//! #[cfg(test)] #[path = "resources/tests.rs"] mod tests;
|
||||
//! ```
|
||||
//! Сегодня `apps/admin-api/src/service/resources.rs` не существует, поэтому файл не компилируется
|
||||
//! и не исполняется (нулевая коллекция — не PASS). Ранняя регистрация запрещена: счётчики живут
|
||||
//! внутри production-модуля, а production-код на стадии ATDD не пишется.
|
||||
//!
|
||||
//! Минимальный будущий интерфейс, на который опираются тесты (объявляется в
|
||||
//! `service/resources.rs`, отдельного production `tests_support`-модуля не требуется):
|
||||
//! ```text
|
||||
//! pub(crate) struct DraftMetadata { pub uri: String, pub name: String, pub description: String,
|
||||
//! pub kind: String, pub mime_type: String, pub sensitivity: String }
|
||||
//! pub(crate) struct NewDraft { pub workspace_id: WorkspaceId, pub metadata: DraftMetadata,
|
||||
//! pub bytes: Vec<u8> }
|
||||
//! pub(crate) struct CreatedDraft { pub resource_id: ResourceId }
|
||||
//! impl ResourcesService {
|
||||
//! pub(crate) fn for_tests(registry: PostgresRegistry, limit: usize) -> Self;
|
||||
//! pub(crate) async fn create_draft(&self, draft: NewDraft) -> Result<CreatedDraft, ResourceError>;
|
||||
//! pub(crate) async fn read_content(&self, workspace_id: &WorkspaceId, resource_id: &ResourceId)
|
||||
//! -> Result<Vec<u8>, ResourceError>;
|
||||
//! }
|
||||
//! ```
|
||||
//! Фикстуры собираются локально в этом файле (`text_draft`/`text_draft_in`), поэтому production
|
||||
//! обязан остаться без тестового `tests_support`-модуля и без публичного API ради тестов.
|
||||
//!
|
||||
//! Что именно должен доказать harness (D-19): счётчики стоят на реальных точках —
|
||||
//! `ArtifactStore::put_registered` (перед регистрацией bytes) и физического чтения байт в
|
||||
//! приватном `read_resource_content()`. «0» доказывается только вместе с положительным
|
||||
//! контролем, а duplicate/DB-rollback проверяются по отсутствию принятых строк, а не по put.
|
||||
//! Запуск после BUILD (фильтр обязан содержать сегмент `tests::`):
|
||||
//! `cargo test -p admin-api --lib service::resources::tests::story36_ -- --list`
|
||||
//! и затем `... -- --test-threads=1` (каждый тест предваряется `counters::reset()`).
|
||||
|
||||
use super::ResourcesService;
|
||||
use super::counters;
|
||||
use crate::app::resource_test_support::ResourceServiceHarness;
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::model::resource::ResourceDraftRecord;
|
||||
use crank_registry::{ArtifactSourceLifecycle, ListArtifactSourcesQuery, PostgresRegistry};
|
||||
use serial_test::serial;
|
||||
|
||||
const LIMIT: usize = 256 * 1024;
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
const FOREIGN_WORKSPACE_ID: &str = "ws_story36_counters_other";
|
||||
|
||||
struct Harness {
|
||||
service: ResourcesService,
|
||||
registry: PostgresRegistry,
|
||||
}
|
||||
|
||||
/// Изолированный стенд: своя PG-схема на каждый тест (иначе счётчики делят строки между тестами).
|
||||
///
|
||||
/// Драйвер, миграция и сборка store/service выполняются composition-фикстурой
|
||||
/// `crate::app::resource_test_support::ResourceServiceHarness`: сервисный тест-модуль
|
||||
/// получает готовый сервис и реестр, а не сырой pool (TL run105 F3, Q1).
|
||||
async fn harness(name: &str) -> Harness {
|
||||
let ResourceServiceHarness {
|
||||
service, registry, ..
|
||||
} = ResourceServiceHarness::spawn(name, LIMIT).await;
|
||||
Harness { service, registry }
|
||||
}
|
||||
|
||||
/// Принятые черновики workspace через продуктовое чтение: raw SQL в
|
||||
/// `apps/admin-api/src/service/**` запрещён execution-boundary правилом, поэтому
|
||||
/// «0 принятых строк» наблюдается на том же публичном чтении, что и UI.
|
||||
async fn accepted_drafts(harness: &Harness) -> Vec<ResourceDraftRecord> {
|
||||
harness
|
||||
.registry
|
||||
.list_resource_drafts(WORKSPACE_ID, 100)
|
||||
.await
|
||||
.expect("accepted resource drafts must be readable")
|
||||
}
|
||||
|
||||
/// Активные owning-ссылки workspace (учёт владения bytes, AD-10).
|
||||
async fn active_owning_refs(harness: &Harness) -> usize {
|
||||
let workspace_id = WorkspaceId::new(WORKSPACE_ID);
|
||||
let page = harness
|
||||
.registry
|
||||
.list_artifact_sources(ListArtifactSourcesQuery {
|
||||
workspace_id: &workspace_id,
|
||||
cursor: None,
|
||||
limit: 100,
|
||||
})
|
||||
.await
|
||||
.expect("artifact sources must be readable");
|
||||
page.items
|
||||
.iter()
|
||||
.filter(|source| source.lifecycle == ArtifactSourceLifecycle::Active)
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Локальная фикстура: Draft в `ws_default` (никакого production `tests_support`).
|
||||
fn text_draft(uri: &str, name: &str, bytes: &[u8]) -> NewDraftFixture {
|
||||
text_draft_in(&WorkspaceId::new(WORKSPACE_ID), uri, name, bytes)
|
||||
}
|
||||
|
||||
/// Та же фикстура с явным workspace (нужна для «чужого» Resource).
|
||||
fn text_draft_in(
|
||||
workspace_id: &WorkspaceId,
|
||||
uri: &str,
|
||||
name: &str,
|
||||
bytes: &[u8],
|
||||
) -> NewDraftFixture {
|
||||
super::NewDraft {
|
||||
workspace_id: workspace_id.clone(),
|
||||
metadata: super::DraftMetadata {
|
||||
uri: uri.to_owned(),
|
||||
name: name.to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
},
|
||||
bytes: bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
type NewDraftFixture = super::NewDraft;
|
||||
|
||||
/// Второй workspace (никаких прав/членства у него нет: здесь проверяется только адресация).
|
||||
async fn create_other_workspace(registry: &PostgresRegistry) -> WorkspaceId {
|
||||
use crank_core::{Workspace, WorkspaceStatus};
|
||||
use crank_registry::CreateWorkspaceRequest;
|
||||
use serde_json::json;
|
||||
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let workspace_id = WorkspaceId::new(FOREIGN_WORKSPACE_ID);
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: workspace_id.clone(),
|
||||
slug: "story36-counters-other".to_owned(),
|
||||
display_name: "Story 3.6 Counters Other".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.expect("the second workspace must be created");
|
||||
workspace_id
|
||||
}
|
||||
|
||||
// Детерминизм счётчиков: счётчики D-19 — процессные статики, поэтому все проверки,
|
||||
// которые их наблюдают (включая guard-пути), сериализуются атрибутом планировщика.
|
||||
// Сами ассерты и тела тестов не изменены.
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_counter_authorized_create_puts_once() {
|
||||
let harness = harness("create_puts").await;
|
||||
counters::reset();
|
||||
|
||||
let created = harness
|
||||
.service
|
||||
.create_draft(text_draft("crank://counter/put", "counter_put", b"payload"))
|
||||
.await
|
||||
.expect("authorized create must succeed");
|
||||
|
||||
assert_eq!(
|
||||
counters::artifact_puts(),
|
||||
1,
|
||||
"an authorized create must hit the real byte-registration point exactly once"
|
||||
);
|
||||
assert_eq!(counters::artifact_reads(), 0);
|
||||
// Положительный контроль: счётчик отражает настоящую запись, а не переменную теста.
|
||||
let stored = harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
|
||||
.await
|
||||
.expect("stored content must be readable");
|
||||
assert_eq!(stored.as_slice(), b"payload");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_counter_authorized_read_reads_once() {
|
||||
let harness = harness("read_reads").await;
|
||||
let created = harness
|
||||
.service
|
||||
.create_draft(text_draft(
|
||||
"crank://counter/read",
|
||||
"counter_read",
|
||||
b"payload",
|
||||
))
|
||||
.await
|
||||
.expect("authorized create must succeed");
|
||||
|
||||
counters::reset();
|
||||
let stored = harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
|
||||
.await
|
||||
.expect("authorized read must succeed");
|
||||
assert_eq!(stored.as_slice(), b"payload");
|
||||
assert_eq!(
|
||||
counters::artifact_reads(),
|
||||
1,
|
||||
"an authorized read must hit the real byte-read point exactly once"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_counter_denied_create_puts_zero() {
|
||||
let harness = harness("denied_create").await;
|
||||
counters::reset();
|
||||
|
||||
// Конкретный доменный отказ до регистрации bytes: kind=text + text/plain + C3 28.
|
||||
let draft = text_draft("crank://counter/denied", "counter_denied", &[0xC3, 0x28]);
|
||||
let error = harness
|
||||
.service
|
||||
.create_draft(draft)
|
||||
.await
|
||||
.expect_err("invalid UTF-8 must be rejected before bytes are registered");
|
||||
assert_eq!(error.code(), "resource_content_invalid_utf8");
|
||||
assert_eq!(counters::artifact_puts(), 0);
|
||||
assert_eq!(counters::artifact_reads(), 0);
|
||||
assert!(
|
||||
accepted_drafts(&harness).await.is_empty(),
|
||||
"a refused create must not accept any resource row"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_counter_denied_foreign_resource_reads_zero() {
|
||||
let harness = harness("foreign_read").await;
|
||||
let foreign_workspace = create_other_workspace(&harness.registry).await;
|
||||
|
||||
// Реальный Resource в другом workspace: он существует, но не в ws_default.
|
||||
let created = harness
|
||||
.service
|
||||
.create_draft(text_draft_in(
|
||||
&foreign_workspace,
|
||||
"crank://counter/foreign",
|
||||
"counter_foreign",
|
||||
b"foreign payload",
|
||||
))
|
||||
.await
|
||||
.expect("create in the owning workspace must succeed");
|
||||
|
||||
counters::reset();
|
||||
let error = harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
|
||||
.await
|
||||
.expect_err("a Resource of another workspace must not be readable here");
|
||||
assert_eq!(error.code(), "resource_not_found");
|
||||
assert_eq!(counters::artifact_reads(), 0);
|
||||
assert_eq!(counters::artifact_puts(), 0);
|
||||
|
||||
// Положительный контроль: тот же существующий Resource читается в своём workspace,
|
||||
// поэтому «0» выше — наблюдение, а не отсутствие реализации.
|
||||
let stored = harness
|
||||
.service
|
||||
.read_content(&foreign_workspace, &created.resource_id)
|
||||
.await
|
||||
.expect("the owning workspace must read its own Resource");
|
||||
assert_eq!(stored.as_slice(), b"foreign payload");
|
||||
assert_eq!(counters::artifact_reads(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_counter_duplicate_conflict_accepted_rows_zero() {
|
||||
let harness = harness("duplicate").await;
|
||||
counters::reset();
|
||||
|
||||
harness
|
||||
.service
|
||||
.create_draft(text_draft("crank://counter/dup", "counter_dup", b"payload"))
|
||||
.await
|
||||
.expect("first create must succeed");
|
||||
let duplicate = text_draft("crank://counter/dup", "counter_other", b"payload");
|
||||
let error = harness
|
||||
.service
|
||||
.create_draft(duplicate)
|
||||
.await
|
||||
.expect_err("duplicate uri must be rejected");
|
||||
assert_eq!(error.code(), "resource_uri_duplicate");
|
||||
|
||||
// Значение put здесь НЕ утверждается: bytes регистрируются до конфликта, осиротевшие
|
||||
// bytes допустимы (AD-10). Доказывается отсутствие принятых строк: у принятого
|
||||
// черновика ровно одна текущая версия, а живая owning-ссылка ровно одна.
|
||||
let accepted = accepted_drafts(&harness).await;
|
||||
assert_eq!(accepted.len(), 1, "only the first create is accepted");
|
||||
assert_eq!(
|
||||
accepted[0].version.version, 1,
|
||||
"the accepted draft keeps exactly one current version"
|
||||
);
|
||||
harness
|
||||
.registry
|
||||
.resolve_current_resource_version(WORKSPACE_ID, &accepted[0].resource.resource_id)
|
||||
.await
|
||||
.expect("the accepted draft must expose its current version");
|
||||
assert_eq!(
|
||||
active_owning_refs(&harness).await,
|
||||
1,
|
||||
"only the accepted draft keeps an active owning reference"
|
||||
);
|
||||
}
|
||||
|
||||
// Регистрация подмодулей guard-путей (TL review run101, R-A): тот же in-crate набор,
|
||||
// отдельные файлы, потому что inline-модуль такого объёма запрещён health-правилом.
|
||||
//
|
||||
// Три HTTP-модуля лежат в тестовом пути `tests/integration/resources/in_crate/`
|
||||
// (TL run111): их содержимое использует прямой HTTP-клиент, а `apps/admin-api/src/service/**`
|
||||
// по execution-boundary правилу не может содержать такую зависимость даже в тестах.
|
||||
// Модули остаются in-crate тестами библиотеки — import-путь `service::resources::tests::<модуль>`
|
||||
// и все test IDs сохраняются, внешний integration-бинарь их не регистрирует.
|
||||
#[path = "../../../tests/integration/resources/in_crate/guard_path.rs"]
|
||||
mod guard_path;
|
||||
#[path = "../../../tests/integration/resources/in_crate/guard_telemetry.rs"]
|
||||
mod guard_telemetry;
|
||||
#[path = "../../../tests/integration/resources/in_crate/limits.rs"]
|
||||
mod limits;
|
||||
#[path = "tests/read_integrity.rs"]
|
||||
mod read_integrity;
|
||||
// P3 (TL F05): детерминированная проверка единого снимка версии и bytes.
|
||||
#[path = "tests/snapshot.rs"]
|
||||
mod snapshot;
|
||||
#[path = "tests/snapshot_after_resolve.rs"]
|
||||
mod snapshot_after_resolve;
|
||||
// F5 (TL run105): контроль редактирования чувствительных заголовков в диагностике
|
||||
// рукописного запроса — отдельный файл по тому же health-правилу.
|
||||
#[path = "tests/diagnostics.rs"]
|
||||
mod diagnostics;
|
||||
// Story 3.7 / AC03 (TL CODE-REVIEW): детерминированный race «публикация vs Draft
|
||||
// update» через уже принятый BUILD-only шов `interleave`.
|
||||
#[path = "tests/publication_race.rs"]
|
||||
mod publication_race;
|
||||
|
||||
// BUILD obligations, которые этот harness НЕ подтверждает:
|
||||
// - session/Owner/CSRF/origin guard-ы (это HTTP-уровень, таргет A);
|
||||
// - DB-rollback при update после шага пометки (таргет P, `story36_at03_update_rollback_*`);
|
||||
// - захват logs/spans/metrics (см. `apps/admin-api/tests/integration/resources/telemetry.rs`).
|
||||
// Измерение принятых строк идёт через публичное чтение реестра (`list_resource_drafts`,
|
||||
// `list_artifact_sources`), а не через прямой SQL-драйвер: execution-boundary запрещает
|
||||
// зависимость от драйвера хранилища в `apps/admin-api/src/service/**`. Поведенческое
|
||||
// ожидание сохранено: на отказе не появляется ни принятый черновик, ни его текущая версия,
|
||||
// ни активная owning-ссылка.
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Story 3.7 / AC02: configure lower limit демонстрирует 413-путь публикации,
|
||||
// недостижимый через persisted state (DB CHECK = storage ceiling).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[tokio::test]
|
||||
async fn story37_at02_configured_lower_limit_refuses_publication_before_writes() {
|
||||
use std::sync::Arc;
|
||||
|
||||
use crank_artifacts::ArtifactStore;
|
||||
use crank_core::resource::{ResourceError, ResourceLimits};
|
||||
|
||||
let wide = ResourceServiceHarness::spawn("story37_publish_limit", LIMIT).await;
|
||||
let bytes = b"0123456789abcdef0123456789abcdef";
|
||||
let created = wide
|
||||
.service
|
||||
.create_draft(text_draft("crank://story37/limit", "limit_doc", bytes))
|
||||
.await
|
||||
.expect("draft must be created under the default limit");
|
||||
let card = wide
|
||||
.service
|
||||
.card(&WorkspaceId::new(WORKSPACE_ID), &created.resource_id)
|
||||
.await
|
||||
.expect("draft card must be readable");
|
||||
|
||||
// Тот же registry/store, но сконфигурированный ниже сохранённого размера: публикация
|
||||
// обязана отказать до любых записей (413-путь).
|
||||
let store = Arc::new(ArtifactStore::open(&wide.root).expect("shared store must open"));
|
||||
let narrow = ResourcesService::new(
|
||||
wide.registry.clone(),
|
||||
store,
|
||||
ResourceLimits::uniform(8).expect("lower limit must stay inside the ceiling"),
|
||||
);
|
||||
let error = narrow
|
||||
.publish(super::PublishResource {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
resource_id: created.resource_id.clone(),
|
||||
expected_updated_at: Some(card.resource.updated_at),
|
||||
})
|
||||
.await
|
||||
.expect_err("a stored content above the configured limit must be refused");
|
||||
assert_eq!(error, ResourceError::ContentTooLarge);
|
||||
|
||||
let drafts = accepted_drafts(&Harness {
|
||||
service: wide.service,
|
||||
registry: wide.registry,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(drafts.len(), 1, "a refused publication must keep the Draft");
|
||||
assert_eq!(
|
||||
drafts[0].resource.status,
|
||||
crank_core::resource::ResourceStatus::Draft
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! F5 (TL run105): диагностика рукописного фрагментированного запроса не несёт
|
||||
//! session/CSRF-значения.
|
||||
//!
|
||||
//! Контроль **положительный и синтетический**: маркерные значения заведомо отправляются
|
||||
//! реальным сокетным запросом, поэтому их отсутствие в подписи — результат редактирования,
|
||||
//! а не пустая строка. Одновременно проверяется, что подпись сохраняет метод, путь,
|
||||
//! `Transfer-Encoding` и статус: иначе отказ не отличить от ошибки харнесса.
|
||||
//!
|
||||
//! Размещение: in-crate сервисные тесты (`tests/**`) — корневой фикстур-файл ограничен
|
||||
//! health-правилом 1000 строк, а сам контроль проверяет публичные (crate-private) шлюзы
|
||||
//! composition-стенда.
|
||||
//!
|
||||
//! Канонический прогон: `cargo test -p admin-api --lib
|
||||
//! service::resources::tests::diagnostics -- --test-threads=1`.
|
||||
|
||||
use serial_test::serial;
|
||||
|
||||
use crate::app::resource_test_support::{
|
||||
GuardHarness, RawHttpResponse, RawSession, redact_sensitive_headers, send_chunked_multipart,
|
||||
};
|
||||
|
||||
const MARKER_COOKIE: &str = "crank_session=C36-F5-MARKER-cookie";
|
||||
const MARKER_CSRF: &str = "C36-F5-MARKER-csrf";
|
||||
const MARKER_REPLY_COOKIE: &str = "C36-F5-MARKER-reply";
|
||||
|
||||
/// Прямой контроль шлюза: значения заменяются маркером, структура головы сохраняется.
|
||||
#[test]
|
||||
fn story36_at06_header_redaction_drops_sensitive_values_and_keeps_context() {
|
||||
let request_head = format!(
|
||||
"POST /api/admin/workspaces/ws_default/resources HTTP/1.1\r\n\
|
||||
Host: 127.0.0.1:1234\r\n\
|
||||
Cookie: {MARKER_COOKIE}\r\n\
|
||||
X-CSRF-Token: {MARKER_CSRF}\r\n\
|
||||
Content-Type: multipart/form-data; boundary=story36\r\n\
|
||||
Transfer-Encoding: chunked\r\n\
|
||||
Connection: close\r\n\r\n"
|
||||
);
|
||||
let response_head = format!(
|
||||
"HTTP/1.1 400 Bad Request\r\n\
|
||||
content-type: application/json\r\n\
|
||||
set-cookie: {MARKER_REPLY_COOKIE}; Path=/\r\n\r\n"
|
||||
);
|
||||
let response = RawHttpResponse {
|
||||
status: 400,
|
||||
head: redact_sensitive_headers(&response_head),
|
||||
body: "{\"error\":{\"code\":\"validation_error\"}}".to_owned(),
|
||||
request_head: redact_sensitive_headers(&request_head),
|
||||
write_error: None,
|
||||
read_error: None,
|
||||
};
|
||||
let signature = response.signature();
|
||||
|
||||
for marker in [MARKER_COOKIE, MARKER_CSRF, MARKER_REPLY_COOKIE] {
|
||||
assert!(
|
||||
!signature.contains(marker),
|
||||
"raw session/CSRF values must never reach the diagnostics: marker `{marker}` \
|
||||
present in `{signature}`"
|
||||
);
|
||||
}
|
||||
for kept in [
|
||||
"POST /api/admin/workspaces/ws_default/resources HTTP/1.1",
|
||||
"Cookie: <redacted-sensitive-header>",
|
||||
"X-CSRF-Token: <redacted-sensitive-header>",
|
||||
"Transfer-Encoding: chunked",
|
||||
"status=400",
|
||||
"400 Bad Request",
|
||||
] {
|
||||
assert!(
|
||||
signature.contains(kept),
|
||||
"redaction must keep the diagnostic context `{kept}`: {signature}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Тот же контроль на **реальном** сокетном пути: маркерная сессия действительно
|
||||
/// отправляется настоящим chunked-запросом, а сохранённая диагностика обязана быть
|
||||
/// отредактированной (значения живут только в момент отправки).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn story36_at06_real_chunked_diagnostics_carry_no_session_or_csrf_values() {
|
||||
let harness = GuardHarness::spawn("redaction").await;
|
||||
let session = RawSession {
|
||||
cookie: MARKER_COOKIE.to_owned(),
|
||||
csrf: MARKER_CSRF.to_owned(),
|
||||
};
|
||||
let boundary = "story36f5marker";
|
||||
let body = format!(
|
||||
"--{boundary}\r\nContent-Disposition: form-data; name=\"metadata\"\r\n\r\n{{}}\r\n\
|
||||
--{boundary}\r\nContent-Disposition: form-data; name=\"content\"; filename=\"d.txt\"\r\n\r\n\
|
||||
marker payload without a closing boundary"
|
||||
);
|
||||
let chunks = vec![body.into_bytes()];
|
||||
let response = send_chunked_multipart(
|
||||
harness.addr,
|
||||
"/api/admin/workspaces/ws_default/resources",
|
||||
&session,
|
||||
boundary,
|
||||
&chunks,
|
||||
)
|
||||
.await;
|
||||
let signature = response.signature();
|
||||
|
||||
for marker in [MARKER_COOKIE, MARKER_CSRF] {
|
||||
assert!(
|
||||
!signature.contains(marker),
|
||||
"a real chunked request must not store raw credentials: marker `{marker}` present \
|
||||
in `{signature}`"
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
!signature.contains("crank_session="),
|
||||
"no stored head may carry a session value: {signature}"
|
||||
);
|
||||
for kept in [
|
||||
"POST /api/admin/workspaces/ws_default/resources HTTP/1.1",
|
||||
"Cookie: <redacted-sensitive-header>",
|
||||
"X-CSRF-Token: <redacted-sensitive-header>",
|
||||
"Transfer-Encoding: chunked",
|
||||
] {
|
||||
assert!(
|
||||
signature.contains(kept),
|
||||
"the refused request must stay distinguishable from a harness error: `{kept}` \
|
||||
missing in `{signature}`"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! Story 3.7 / AC03: детерминированный race «публикация vs Draft update».
|
||||
//!
|
||||
//! TL CODE-REVIEW (F4/race): существующие registry-тесты доказывают последовательный
|
||||
//! mismatch и stale-replay, но не само чередование. Здесь используется уже принятый
|
||||
//! BUILD-only шов `interleave::fire_after_resolve`: обновление того же Resource
|
||||
//! исполняется ровно один раз **после** разрешения версии/байт и **до** commit
|
||||
//! публикации. Ожидание: публикация отвергается как stale (HTTP 428 по существующему
|
||||
//! mapping), строк публикации/owning-ссылки не появляется, CAS не сдвигается, а
|
||||
//! обновлённый Draft остаётся сохранённым. Новый harness не создаётся.
|
||||
|
||||
use super::super::{DraftMetadata, NewDraft, PublishResource, UpdateDraft, interleave};
|
||||
use crate::app::resource_test_support::ResourceServiceHarness;
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_core::resource::{ResourceError, ResourceStatus};
|
||||
use crank_registry::{ArtifactSourceLifecycle, ListArtifactSourcesQuery};
|
||||
use serial_test::serial;
|
||||
|
||||
const LIMIT: usize = 256 * 1024;
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
const PUBLISHED_CANDIDATE: &[u8] = b"{\"publication_race\":\"v1-candidate\"}";
|
||||
const LATER_EDIT: &[u8] = b"{\"publication_race\":\"v2-after-update\"}";
|
||||
|
||||
fn text_draft(bytes: &[u8]) -> NewDraft {
|
||||
NewDraft {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
metadata: DraftMetadata {
|
||||
uri: "crank://story37/publication-race".to_owned(),
|
||||
name: "publication_race".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
},
|
||||
bytes: bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story37_at03_concurrent_draft_update_refuses_publication_without_writes() {
|
||||
let harness = ResourceServiceHarness::spawn("story37_publication_race", LIMIT).await;
|
||||
let service = harness.service.clone();
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
|
||||
let created = service
|
||||
.create_draft(text_draft(PUBLISHED_CANDIDATE))
|
||||
.await
|
||||
.expect("the seed draft must be created");
|
||||
let resource_id = created.resource_id;
|
||||
let card = service
|
||||
.card(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("the seed card must be readable");
|
||||
assert_eq!(card.version.version, 1);
|
||||
let precondition = card.resource.updated_at.clone();
|
||||
|
||||
// Настоящее обновление того же Resource, исполняемое ровно один раз в окне
|
||||
// «после разрешения версии/байт, до commit публикации».
|
||||
let updating = service.clone();
|
||||
let updated_id = resource_id.clone();
|
||||
let updated_workspace = workspace.clone();
|
||||
let update_precondition = precondition.clone();
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<(u32, String), String>>();
|
||||
interleave::install_after_resolve(Box::new(move || {
|
||||
Box::pin(async move {
|
||||
let outcome = updating
|
||||
.update_draft(UpdateDraft {
|
||||
workspace_id: updated_workspace,
|
||||
resource_id: updated_id,
|
||||
description: "edited during publication".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: Some(update_precondition),
|
||||
immutable_fields: Vec::new(),
|
||||
bytes: LATER_EDIT.to_vec(),
|
||||
})
|
||||
.await
|
||||
.map(|card| (card.version.version, card.resource.updated_at))
|
||||
.map_err(|error| error.to_string());
|
||||
let _ = sender.send(outcome);
|
||||
})
|
||||
}));
|
||||
|
||||
let error = service
|
||||
.publish(PublishResource {
|
||||
workspace_id: workspace.clone(),
|
||||
resource_id: resource_id.clone(),
|
||||
expected_updated_at: Some(precondition.clone()),
|
||||
})
|
||||
.await
|
||||
.expect_err("a publication interleaved with a Draft update must be refused");
|
||||
assert_eq!(
|
||||
error,
|
||||
ResourceError::Stale,
|
||||
"the interleaved update must surface as the accepted stale taxonomy (428 at HTTP)"
|
||||
);
|
||||
|
||||
let concurrent = receiver
|
||||
.await
|
||||
.expect("the interleaved update must report its outcome");
|
||||
let (updated_version, updated_at) =
|
||||
concurrent.expect("the interleaved Draft update must really be accepted");
|
||||
assert_eq!(
|
||||
updated_version, 2,
|
||||
"the concurrent update must have produced a new Draft version"
|
||||
);
|
||||
|
||||
// Отказ публикации не сдвинул CAS: карточка осталась той, которую записал update.
|
||||
let after = service
|
||||
.card(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("the card must be readable after the refused publication");
|
||||
assert_eq!(
|
||||
after.resource.updated_at, updated_at,
|
||||
"the refused publication must not advance the card revision"
|
||||
);
|
||||
assert_eq!(
|
||||
after.version.version, 2,
|
||||
"the updated Draft must stay the current version"
|
||||
);
|
||||
assert_eq!(
|
||||
after.resource.status,
|
||||
ResourceStatus::Draft,
|
||||
"the card must stay a Draft after the refused publication"
|
||||
);
|
||||
assert_eq!(
|
||||
service
|
||||
.read_content(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("the updated Draft must stay readable"),
|
||||
LATER_EDIT.to_vec(),
|
||||
"the updated Draft bytes must survive the refused publication"
|
||||
);
|
||||
|
||||
// Ни одной Published Version не появилось (ни для прежней, ни для новой версии).
|
||||
for version in [1, 2] {
|
||||
let resolution = harness
|
||||
.registry
|
||||
.resolve_resource_publication(WORKSPACE_ID, &resource_id, version)
|
||||
.await
|
||||
.expect_err("a refused publication must not create a Published Version");
|
||||
assert_eq!(
|
||||
resolution,
|
||||
ResourceError::NotFound,
|
||||
"no publication row/owning source must exist for version {version}"
|
||||
);
|
||||
}
|
||||
|
||||
// Владение: единственная активная owning-ссылка — новая Draft-версия; publication
|
||||
// source не вставлен отказом.
|
||||
let page = harness
|
||||
.registry
|
||||
.list_artifact_sources(ListArtifactSourcesQuery {
|
||||
workspace_id: &workspace,
|
||||
cursor: None,
|
||||
limit: 100,
|
||||
})
|
||||
.await
|
||||
.expect("artifact sources must be readable");
|
||||
let active: Vec<_> = page
|
||||
.items
|
||||
.iter()
|
||||
.filter(|source| source.lifecycle == ArtifactSourceLifecycle::Active)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
active.len(),
|
||||
1,
|
||||
"only the current Draft keeps an active owning reference: {active:?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! R-D (P5): где именно срабатывает защита чтения Resource и как это наблюдается
|
||||
//! счётчиками физических точек (AT-3.6-03/05).
|
||||
//!
|
||||
//! Источник: FINAL-DISPOSITION run99 (P5), TL review run103:35 (R-D): «однофакторная
|
||||
//! integrity-матрица на durable seed-ах, metadata-denial до чтения против физического
|
||||
//! отказа, который чтение уже выполнил».
|
||||
//!
|
||||
//! Наблюдения: `counters::artifact_reads` (реальная точка физического чтения) и точные
|
||||
//! bytes/идентичность артефакта. SQL-мутации и файловые наблюдения живут в composition
|
||||
//! fixture `crate::app::resource_test_support`, а не в сервисном коде.
|
||||
//!
|
||||
//! Канонический прогон: `cargo test -p admin-api --lib
|
||||
//! service::resources::tests::read_integrity -- --test-threads=1`.
|
||||
|
||||
use std::{fs, os::unix::fs::PermissionsExt, path::PathBuf};
|
||||
|
||||
use crank_core::WorkspaceId;
|
||||
use crank_registry::PostgresRegistry;
|
||||
use serial_test::serial;
|
||||
|
||||
use super::super::{DraftMetadata, NewDraft, ResourcesService};
|
||||
use super::counters;
|
||||
use crate::app::resource_test_support::{
|
||||
ArtifactIdentity, ArtifactMutation, ResourceServiceHarness, apply_artifact_mutation,
|
||||
artifact_files, observe_artifact_identity, restore_artifact_identity,
|
||||
};
|
||||
|
||||
const LIMIT: usize = 256 * 1024;
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
const CONTENT: &[u8] = b"integrity payload";
|
||||
|
||||
struct Harness {
|
||||
service: ResourcesService,
|
||||
registry: PostgresRegistry,
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
/// Стенд с **известным** приватным artifact root: физический отказ можно наблюдать
|
||||
/// только там, где тест владеет корнем хранилища (production-конструктор его скрывает).
|
||||
///
|
||||
/// Драйвер, миграция и сборка store/service выполняются в composition fixture
|
||||
/// `crate::app::resource_test_support::ResourceServiceHarness` — сервисный тест-модуль
|
||||
/// не создаёт SQL-адаптер и не держит raw pool (TL review run105 F3).
|
||||
async fn harness(name: &str) -> Harness {
|
||||
let ResourceServiceHarness {
|
||||
service,
|
||||
registry,
|
||||
root,
|
||||
} = ResourceServiceHarness::spawn(name, LIMIT).await;
|
||||
Harness {
|
||||
service,
|
||||
registry,
|
||||
root,
|
||||
}
|
||||
}
|
||||
|
||||
async fn seed(harness: &Harness, suffix: &str) -> crank_core::ids::ResourceId {
|
||||
harness
|
||||
.service
|
||||
.create_draft(NewDraft {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
metadata: DraftMetadata {
|
||||
uri: format!("crank://integrity/{suffix}"),
|
||||
name: format!("integrity_{suffix}"),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
},
|
||||
bytes: CONTENT.to_vec(),
|
||||
})
|
||||
.await
|
||||
.expect("the durable seed draft must be created")
|
||||
.resource_id
|
||||
}
|
||||
|
||||
/// Физические файлы содержимого (один blob на seed).
|
||||
fn blob_files(harness: &Harness) -> Vec<PathBuf> {
|
||||
let files = artifact_files(&harness.root);
|
||||
assert_eq!(
|
||||
files.len(),
|
||||
1,
|
||||
"exactly one durable blob is expected under the private root: {files:?}"
|
||||
);
|
||||
files
|
||||
}
|
||||
|
||||
/// Запись файла содержимого в форме, которую принимает store (регулярный файл
|
||||
/// владельца, одна ссылка, без прав записи) — создаёт файл заново при необходимости.
|
||||
fn install_blob(path: &PathBuf, bytes: &[u8]) {
|
||||
if path.exists() {
|
||||
fs::remove_file(path).expect("the durable blob must be removable for the fault case");
|
||||
}
|
||||
fs::write(path, bytes).expect("the replacement blob must be writable");
|
||||
fs::set_permissions(path, fs::Permissions::from_mode(0o444))
|
||||
.expect("the replacement blob must lose its write bits");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_at03_metadata_denial_refuses_before_any_physical_read() {
|
||||
let harness = harness("metadata_denial").await;
|
||||
let resource_id = seed(&harness, "metadata").await;
|
||||
|
||||
// Позитивный контроль: durable seed действительно читается точными bytes.
|
||||
counters::reset();
|
||||
assert_eq!(
|
||||
harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
|
||||
.await
|
||||
.expect("the durable seed must be readable"),
|
||||
CONTENT.to_vec()
|
||||
);
|
||||
assert_eq!(counters::artifact_reads(), 1);
|
||||
let identity: ArtifactIdentity =
|
||||
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await;
|
||||
|
||||
let mut observations: Vec<String> = Vec::new();
|
||||
let mut mismatches: Vec<String> = Vec::new();
|
||||
for mutation in ArtifactMutation::ALL {
|
||||
let label = mutation.label();
|
||||
apply_artifact_mutation(harness.registry.pool(), mutation)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("mutation `{label}` must apply: {error}"));
|
||||
assert_ne!(
|
||||
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await,
|
||||
identity,
|
||||
"mutation `{label}` must really change the observed identity"
|
||||
);
|
||||
|
||||
counters::reset();
|
||||
let refusal = harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
|
||||
.await;
|
||||
let reads = counters::artifact_reads();
|
||||
let observed = match &refusal {
|
||||
Err(error) => error.code().to_owned(),
|
||||
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
|
||||
};
|
||||
// Metadata-сверка обязана отсечь рассинхронизацию ДО физического чтения.
|
||||
if refusal.is_err() && observed == "resource_artifact_integrity" && reads == 0 {
|
||||
observations.push(format!("{label}: {observed}, physical reads={reads}"));
|
||||
} else {
|
||||
mismatches.push(format!(
|
||||
"{label}: expected resource_artifact_integrity with reads=0, observed \
|
||||
{observed} with reads={reads}"
|
||||
));
|
||||
observations.push(format!("{label}: {observed}, physical reads={reads}"));
|
||||
}
|
||||
|
||||
restore_artifact_identity(harness.registry.pool(), WORKSPACE_ID, &identity)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("restoration after `{label}` must apply: {error}"));
|
||||
assert_eq!(
|
||||
observe_artifact_identity(harness.registry.pool(), WORKSPACE_ID).await,
|
||||
identity,
|
||||
"mutation `{label}` must be restored byte-exactly"
|
||||
);
|
||||
counters::reset();
|
||||
assert_eq!(
|
||||
harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("restore after `{label}` must resolve: {error:?}")),
|
||||
CONTENT.to_vec()
|
||||
);
|
||||
assert_eq!(counters::artifact_reads(), 1);
|
||||
}
|
||||
|
||||
assert!(
|
||||
mismatches.is_empty(),
|
||||
"every metadata mismatch must be refused before the physical read point; observations: \
|
||||
{observations:?}; mismatches: {mismatches:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_at03_physical_failure_reads_once_and_returns_no_bytes() {
|
||||
let harness = harness("physical_failure").await;
|
||||
let resource_id = seed(&harness, "physical").await;
|
||||
let mut files = blob_files(&harness);
|
||||
let blob = files.remove(0);
|
||||
|
||||
// (1) Содержимое физически отсутствует: metadata-сверка проходит, чтение выполняется
|
||||
// и падает — счётчик чтения равен 1, bytes не возвращаются.
|
||||
fs::remove_file(&blob).expect("the durable blob must be removable");
|
||||
counters::reset();
|
||||
let missing = harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
|
||||
.await;
|
||||
let missing_reads = counters::artifact_reads();
|
||||
let missing_code = match &missing {
|
||||
Err(error) => error.code().to_owned(),
|
||||
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
|
||||
};
|
||||
|
||||
// (2) Содержимое подменено на другую строку той же длины: чтение тоже выполняется,
|
||||
// но расхождение digest обязано быть отказом без bytes.
|
||||
install_blob(&blob, b"integrity payloaX");
|
||||
counters::reset();
|
||||
let corrupted = harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
|
||||
.await;
|
||||
let corrupted_reads = counters::artifact_reads();
|
||||
let corrupted_code = match &corrupted {
|
||||
Err(error) => error.code().to_owned(),
|
||||
Ok(bytes) => format!("accepted with {} bytes", bytes.len()),
|
||||
};
|
||||
|
||||
// (3) Положительный контроль: возврат точных bytes восстанавливает чтение.
|
||||
install_blob(&blob, CONTENT);
|
||||
counters::reset();
|
||||
assert_eq!(
|
||||
harness
|
||||
.service
|
||||
.read_content(&WorkspaceId::new(WORKSPACE_ID), &resource_id)
|
||||
.await
|
||||
.expect("the restored blob must be readable again"),
|
||||
CONTENT.to_vec()
|
||||
);
|
||||
assert_eq!(counters::artifact_reads(), 1);
|
||||
|
||||
assert!(
|
||||
missing.is_err() && missing_code == "resource_artifact_integrity" && missing_reads == 1,
|
||||
"a physically missing blob must fail after the read point with no bytes; observed \
|
||||
{missing_code} with reads={missing_reads}"
|
||||
);
|
||||
assert!(
|
||||
corrupted.is_err()
|
||||
&& corrupted_code == "resource_artifact_integrity"
|
||||
&& corrupted_reads == 1,
|
||||
"a physically corrupted blob must fail closed after the read point with no bytes; \
|
||||
observed {corrupted_code} with reads={corrupted_reads}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! P3 (AT-3.6-03/04): preview отдаёт metadata и bytes **одного** разрешения версии.
|
||||
//!
|
||||
//! Источник: CORRECTION-PACKAGE P3 (TL F05), SPEC v4 §3 D-6/D-19. Проверка
|
||||
//! детерминированная: приватная точка `interleave` внутри `load_content` исполняет
|
||||
//! настоящий concurrent update того же Resource в той же PG-схеме, поэтому окно
|
||||
//! «между источником metadata и физическим чтением bytes» наблюдаемо без гонки.
|
||||
//!
|
||||
//! Ожидание одного снимка: версия/размер/MIME/digest/text в ответе относятся к
|
||||
//! одной и той же версии, а не к metadata версии N и bytes версии N+1 (TL F05).
|
||||
|
||||
use super::super::{DraftMetadata, NewDraft, UpdateDraft, interleave};
|
||||
use crate::app::resource_test_support::ResourceServiceHarness;
|
||||
use crank_core::WorkspaceId;
|
||||
use serde_json::Value;
|
||||
use serial_test::serial;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const LIMIT: usize = 256 * 1024;
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
const FIRST: &[u8] = b"{\"snapshot\":\"first\"}";
|
||||
const SECOND: &[u8] = b"{\"snapshot\":\"second\",\"n\":2}";
|
||||
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
fn text_draft(bytes: &[u8]) -> NewDraft {
|
||||
NewDraft {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
metadata: DraftMetadata {
|
||||
uri: "crank://snapshot/draft".to_owned(),
|
||||
name: "snapshot_draft".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
},
|
||||
bytes: bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_at04_preview_serves_one_pinned_resolution_snapshot() {
|
||||
let harness = ResourceServiceHarness::spawn("snapshot", LIMIT).await;
|
||||
let service = harness.service.clone();
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
|
||||
let created = service
|
||||
.create_draft(text_draft(FIRST))
|
||||
.await
|
||||
.expect("the seed draft must be created");
|
||||
let resource_id = created.resource_id;
|
||||
|
||||
let card = service
|
||||
.card(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("the seed card must be readable");
|
||||
let precondition = card.resource.updated_at.clone();
|
||||
|
||||
// Controlled concurrent update того же Resource и той же схемы: шаг исполняется
|
||||
// ровно один раз на приватной точке чередования.
|
||||
let updating = service.clone();
|
||||
let updated_id = resource_id.clone();
|
||||
let updated_workspace = workspace.clone();
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<u32, String>>();
|
||||
interleave::install(Box::new(move || {
|
||||
Box::pin(async move {
|
||||
let outcome = updating
|
||||
.update_draft(UpdateDraft {
|
||||
workspace_id: updated_workspace,
|
||||
resource_id: updated_id,
|
||||
description: "updated during interleave".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: Some(precondition),
|
||||
immutable_fields: Vec::new(),
|
||||
bytes: SECOND.to_vec(),
|
||||
})
|
||||
.await
|
||||
.map(|card| card.version.version)
|
||||
.map_err(|error| error.to_string());
|
||||
let _ = sender.send(outcome);
|
||||
})
|
||||
}));
|
||||
|
||||
let preview = service
|
||||
.preview(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("preview must succeed");
|
||||
let concurrent = receiver
|
||||
.await
|
||||
.expect("the interleave step must report its outcome");
|
||||
|
||||
// Положительный контроль чередования: одновременный update действительно принят,
|
||||
// поэтому «один снимок» ниже — наблюдение, а не следствие того, что ничего не менялось.
|
||||
assert_eq!(
|
||||
concurrent,
|
||||
Ok(2),
|
||||
"the interleaved update must be accepted before the bytes of this response are read"
|
||||
);
|
||||
|
||||
let digest_first = sha256_hex(FIRST);
|
||||
let digest_second = sha256_hex(SECOND);
|
||||
let expected_text = std::str::from_utf8(SECOND)
|
||||
.expect("the fixture content must be UTF-8")
|
||||
.to_owned();
|
||||
let observed = format!(
|
||||
"version={} digest={} size={} mime={} text={:?}",
|
||||
preview.version.version,
|
||||
preview.version.digest,
|
||||
preview.version.size_bytes,
|
||||
preview.version.mime_type,
|
||||
preview.preview.text
|
||||
);
|
||||
|
||||
// Все поля относятся к одному снимку: той версии, которую разрешил этот ответ.
|
||||
assert_eq!(preview.version.version, 2, "single snapshot: {observed}");
|
||||
assert_eq!(
|
||||
preview.version.digest, digest_second,
|
||||
"single snapshot: {observed}"
|
||||
);
|
||||
assert_eq!(
|
||||
preview.version.size_bytes,
|
||||
i64::try_from(SECOND.len()).expect("fixture size must fit i64"),
|
||||
"single snapshot: {observed}"
|
||||
);
|
||||
assert_eq!(
|
||||
preview.version.mime_type, "text/plain",
|
||||
"single snapshot: {observed}"
|
||||
);
|
||||
assert_eq!(
|
||||
preview.preview.text.as_deref(),
|
||||
Some(expected_text.as_str()),
|
||||
"single snapshot: the preview text must be the bytes of the same version: {observed}"
|
||||
);
|
||||
// Расхождение с metadata предыдущей версии — то, что было дефектом (материализация).
|
||||
assert_ne!(
|
||||
preview.version.digest, digest_first,
|
||||
"the snapshot must not fall back to the pre-interleave version: {observed}"
|
||||
);
|
||||
assert!(
|
||||
!preview.version.digest.is_empty() && preview.version.digest.len() == 64,
|
||||
"the digest must be the pinned version digest, not a placeholder: {observed}"
|
||||
);
|
||||
assert_eq!(preview.resource.name, "snapshot_draft");
|
||||
assert_eq!(preview.resource.uri, "crank://snapshot/draft");
|
||||
assert_eq!(preview.resource.current_draft_version, 2);
|
||||
let _: Value = serde_json::to_value(&preview).expect("the preview must serialize");
|
||||
|
||||
// Тот же Resource после ответа отдаёт содержимое новой версии: update настоящий,
|
||||
// а не «виртуальный» только внутри тестового шага.
|
||||
let served = service
|
||||
.read_content(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("content must be readable after the interleave");
|
||||
assert_eq!(served, SECOND.to_vec());
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! F6 (TL run109 CODE-REVIEW): сохранность pinned-версии, когда обновление того же
|
||||
//! Resource приходит **после** разрешения версии.
|
||||
//!
|
||||
//! Источник: CODE-REVIEW run109 F6. Существующая проверка `snapshot.rs` исполняет
|
||||
//! чередование **до** `resolve_current_resource_version`, поэтому оба повторных
|
||||
//! разрешения увидели бы уже новую версию и регресс «два разрешения в одном
|
||||
//! ответе» такой тест не поймал бы. Здесь шаг стоит после разрешения и до
|
||||
//! физического чтения байт: он либо ничего не меняет в наблюдаемом ответе
|
||||
//! (honest existing GREEN для корректного кода), либо доказывает, что metadata и
|
||||
//! bytes взяты из разных разрешений.
|
||||
//!
|
||||
//! Тест намеренно не требует RED: production-ветка уже обслуживает ответ одним
|
||||
//! pinned-разрешением, а новое наблюдение — это preservation-проверка.
|
||||
|
||||
use super::super::{DraftMetadata, NewDraft, UpdateDraft, interleave};
|
||||
use crate::app::resource_test_support::ResourceServiceHarness;
|
||||
use crank_core::WorkspaceId;
|
||||
use serial_test::serial;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const LIMIT: usize = 256 * 1024;
|
||||
const WORKSPACE_ID: &str = "ws_default";
|
||||
const FIRST: &[u8] = b"{\"after_resolve\":\"pinned\",\"v\":1}";
|
||||
const SECOND: &[u8] = b"{\"after_resolve\":\"pinned\",\"v\":2,\"late\":true}";
|
||||
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
fn text_draft(bytes: &[u8]) -> NewDraft {
|
||||
NewDraft {
|
||||
workspace_id: WorkspaceId::new(WORKSPACE_ID),
|
||||
metadata: DraftMetadata {
|
||||
uri: "crank://snapshot/after-resolve".to_owned(),
|
||||
name: "snapshot_after_resolve".to_owned(),
|
||||
description: String::new(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "text/plain".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
},
|
||||
bytes: bytes.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn story36_at04_preview_stays_pinned_when_the_update_lands_after_resolution() {
|
||||
let harness = ResourceServiceHarness::spawn("snapshot_after_resolve", LIMIT).await;
|
||||
let service = harness.service.clone();
|
||||
let workspace = WorkspaceId::new(WORKSPACE_ID);
|
||||
|
||||
let created = service
|
||||
.create_draft(text_draft(FIRST))
|
||||
.await
|
||||
.expect("the seed draft must be created");
|
||||
let resource_id = created.resource_id;
|
||||
let precondition = service
|
||||
.card(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("the seed card must be readable")
|
||||
.resource
|
||||
.updated_at
|
||||
.clone();
|
||||
|
||||
// Настоящее обновление того же Resource и той же PG-схемы, исполняемое ровно
|
||||
// один раз в окне «после разрешения версии, до физического чтения байт».
|
||||
let updating = service.clone();
|
||||
let updated_id = resource_id.clone();
|
||||
let updated_workspace = workspace.clone();
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel::<Result<u32, String>>();
|
||||
interleave::install_after_resolve(Box::new(move || {
|
||||
Box::pin(async move {
|
||||
let outcome = updating
|
||||
.update_draft(UpdateDraft {
|
||||
workspace_id: updated_workspace,
|
||||
resource_id: updated_id,
|
||||
description: "updated after resolution".to_owned(),
|
||||
// MIME тоже меняется в рамках того же kind, поэтому ответ обязан
|
||||
// остаться на MIME разрешённой версии, а не поздней (F6).
|
||||
mime_type: "text/markdown".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
expected_updated_at: Some(precondition),
|
||||
immutable_fields: Vec::new(),
|
||||
bytes: SECOND.to_vec(),
|
||||
})
|
||||
.await
|
||||
.map(|card| card.version.version)
|
||||
.map_err(|error| error.to_string());
|
||||
let _ = sender.send(outcome);
|
||||
})
|
||||
}));
|
||||
|
||||
let preview = service
|
||||
.preview(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("preview must succeed");
|
||||
let concurrent = receiver
|
||||
.await
|
||||
.expect("the after-resolution step must report its outcome");
|
||||
|
||||
// Положительный контроль: позднее обновление действительно принято, поэтому
|
||||
// «версия 1 в ответе» — наблюдение, а не следствие неудавшегося шага.
|
||||
assert_eq!(
|
||||
concurrent,
|
||||
Ok(2),
|
||||
"the update that landed after the resolution must really be accepted"
|
||||
);
|
||||
|
||||
let digest_first = sha256_hex(FIRST);
|
||||
let digest_second = sha256_hex(SECOND);
|
||||
let expected_text = std::str::from_utf8(FIRST)
|
||||
.expect("the fixture content must be UTF-8")
|
||||
.to_owned();
|
||||
let observed = format!(
|
||||
"version={} digest={} size={} mime={} text={:?}",
|
||||
preview.version.version,
|
||||
preview.version.digest,
|
||||
preview.version.size_bytes,
|
||||
preview.version.mime_type,
|
||||
preview.preview.text
|
||||
);
|
||||
|
||||
// Весь ответ относится к версии, разрешённой до позднего обновления.
|
||||
assert_eq!(
|
||||
preview.version.version, 1,
|
||||
"the answer must stay pinned to the version resolved before the late update: {observed}"
|
||||
);
|
||||
assert_eq!(
|
||||
preview.version.digest, digest_first,
|
||||
"the digest must belong to the resolved version: {observed}"
|
||||
);
|
||||
assert_eq!(
|
||||
preview.version.size_bytes,
|
||||
i64::try_from(FIRST.len()).expect("fixture size must fit i64"),
|
||||
"the size must belong to the resolved version: {observed}"
|
||||
);
|
||||
assert_eq!(
|
||||
preview.preview.text.as_deref(),
|
||||
Some(expected_text.as_str()),
|
||||
"the preview text must be the bytes of the resolved version: {observed}"
|
||||
);
|
||||
// Явный MIME-оракул: поздняя правка меняет именно MIME, поэтому ответ обязан
|
||||
// показывать MIME разрешённой версии (F6).
|
||||
assert_eq!(
|
||||
preview.version.mime_type, "text/plain",
|
||||
"the MIME must belong to the resolved version, not to the late update: {observed}"
|
||||
);
|
||||
assert_ne!(
|
||||
preview.version.digest, digest_second,
|
||||
"the response must not mix in bytes of the later version: {observed}"
|
||||
);
|
||||
assert_eq!(
|
||||
preview.resource.current_draft_version, 1,
|
||||
"the card metadata of this answer must not be re-read after the late update: {observed}"
|
||||
);
|
||||
|
||||
// И валидный последующий запрос уже отдаёт версию 2 целиком: обновление настоящее.
|
||||
let after = service
|
||||
.card(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("the card must be readable after the late update");
|
||||
assert_eq!(after.version.version, 2, "the late update must be durable");
|
||||
assert_eq!(after.version.digest, digest_second);
|
||||
assert_eq!(
|
||||
after.version.mime_type, "text/markdown",
|
||||
"the late update's own MIME must be durable as well"
|
||||
);
|
||||
assert_eq!(
|
||||
service
|
||||
.read_content(&workspace, &resource_id)
|
||||
.await
|
||||
.expect("content must be readable after the late update"),
|
||||
SECOND.to_vec()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Wire-view Resource (Story 3.6–3.10), вынесены из `service/resources.rs` под
|
||||
//! лимит rust-code-health. Здесь только сериализация и снимок уже прочитанной
|
||||
//! строки; второго чтения Resource или bytes не появляется.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Ответ публикации: существующая карточка Resource + immutable Published Version.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct PublishedVersionResponse {
|
||||
pub resource: ResourceCardResponse,
|
||||
pub published_version: PublishedVersionView,
|
||||
}
|
||||
|
||||
/// Публичные metadata точной Published Version (TL decision 2/3): ровно девять полей,
|
||||
/// без owning-ссылки, хранилища, path и raw upload filename.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct PublishedVersionView {
|
||||
pub version: u32,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: String,
|
||||
pub mime_type: String,
|
||||
pub size_bytes: i64,
|
||||
pub digest: String,
|
||||
pub sensitivity: String,
|
||||
/// Story 3.10: снимок определения шаблона; у static версии отсутствует.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<template::TemplateSourceView>,
|
||||
}
|
||||
|
||||
impl PublishedVersionView {
|
||||
pub(super) fn from_record(record: &ResourcePublicationRecord) -> Self {
|
||||
Self {
|
||||
version: record.version,
|
||||
uri: record.uri.clone(),
|
||||
name: record.name.clone(),
|
||||
description: record.description.clone(),
|
||||
kind: record.kind.clone(),
|
||||
mime_type: record.mime_type.clone(),
|
||||
size_bytes: record.size_bytes,
|
||||
digest: record.digest.clone(),
|
||||
sensitivity: record.sensitivity.clone(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct ResourceListResponse {
|
||||
pub items: Vec<ResourceCardResponse>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct ResourceCardResponse {
|
||||
pub resource: ResourceView,
|
||||
pub version: ResourceVersionView,
|
||||
pub findings: Vec<PreviewFinding>,
|
||||
/// Story 3.10: additive source-блок; у static Resource поле отсутствует.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<template::TemplateSourceView>,
|
||||
}
|
||||
|
||||
impl ResourceCardResponse {
|
||||
pub(super) fn from_record(record: &ResourceDraftRecord) -> Self {
|
||||
Self {
|
||||
resource: ResourceView::from_record(record),
|
||||
version: ResourceVersionView::from_record(&record.version),
|
||||
findings: Vec::new(),
|
||||
source: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn kind(&self) -> Result<ResourceKind, ResourceError> {
|
||||
parse_kind(&self.resource.kind)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct ResourcePreviewResponse {
|
||||
pub resource: ResourceView,
|
||||
pub version: ResourceVersionView,
|
||||
pub findings: Vec<PreviewFinding>,
|
||||
pub preview: ResourcePreviewView,
|
||||
/// Story 3.10: template source view того же снимка; у static Resource отсутствует.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<template::TemplateSourceView>,
|
||||
}
|
||||
|
||||
/// Безопасный finding preview: только стабильный код и поле, без bytes содержимого,
|
||||
/// совпавшего фрагмента и цели `include:`.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct PreviewFinding {
|
||||
pub code: &'static str,
|
||||
pub field: &'static str,
|
||||
}
|
||||
|
||||
impl PreviewFinding {
|
||||
pub(super) fn from_error(error: &ResourceError) -> Self {
|
||||
Self {
|
||||
code: error.code(),
|
||||
field: error.field().unwrap_or("content"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct ResourcePreviewView {
|
||||
/// Ровно сохранённые bytes как строка; `null` для kind=binary (D-6).
|
||||
pub text: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct ResourceView {
|
||||
pub resource_id: String,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Wire-значение kind (`text`|`json`|`binary`).
|
||||
pub kind: String,
|
||||
pub status: crank_core::resource::ResourceStatus,
|
||||
pub current_draft_version: u32,
|
||||
/// Точная последняя Published версия (discovery-указатель), `null` если публикаций нет.
|
||||
pub latest_published_version: Option<u32>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
}
|
||||
|
||||
impl ResourceView {
|
||||
pub(super) fn from_record(record: &ResourceDraftRecord) -> Self {
|
||||
Self {
|
||||
resource_id: record.resource.resource_id.as_str().to_owned(),
|
||||
uri: record.resource.uri.clone(),
|
||||
name: record.resource.name.clone(),
|
||||
description: record.resource.description.clone(),
|
||||
kind: record.resource.kind.clone(),
|
||||
status: record.resource.status,
|
||||
current_draft_version: record.resource.current_draft_version,
|
||||
latest_published_version: record.resource.latest_published_version,
|
||||
created_at: format_timestamp(record.resource.created_at),
|
||||
updated_at: format_timestamp(record.resource.updated_at),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub(crate) struct ResourceVersionView {
|
||||
pub version: u32,
|
||||
/// Wire-значение kind версии (`text`|`json`|`binary`).
|
||||
pub kind: String,
|
||||
pub mime_type: String,
|
||||
pub size_bytes: i64,
|
||||
pub digest: String,
|
||||
/// Wire-значение sensitivity (`public`|`internal`|`secret`).
|
||||
pub sensitivity: String,
|
||||
pub created_at: String,
|
||||
pub superseded_at: Option<String>,
|
||||
}
|
||||
|
||||
impl ResourceVersionView {
|
||||
pub(super) fn from_record(record: &ResourceVersionRecord) -> Self {
|
||||
Self {
|
||||
version: record.version,
|
||||
kind: record.kind.clone(),
|
||||
mime_type: record.mime_type.clone(),
|
||||
size_bytes: record.size_bytes,
|
||||
digest: record.digest.clone(),
|
||||
sensitivity: record.sensitivity.clone(),
|
||||
created_at: format_timestamp(record.created_at),
|
||||
superseded_at: record.superseded_at.map(format_timestamp),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user