[skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
1 parent
1b6db09bd1
commit
75fe5a123c
357 files changed
+118831
-5113
No files matched your search
@@ -0,0 +1,915 @@
|
||||
//! Typed static Resource drafts (Story 3.6): domain contract for `Resource`.
|
||||
//!
|
||||
//! `Resource` — отдельный typed aggregate с собственными ID/version/lifecycle,
|
||||
//! sensitivity и неизменяемой published-моделью; он не является подтипом
|
||||
//! `Operation` и не «универсальный JSON blob» (AD-1/AD-2).
|
||||
//!
|
||||
//! Здесь же живут грамматики и валидаторы контракта:
|
||||
//! - D-3 — пределы содержимого (`ResourceLimits`, storage ceiling);
|
||||
//! - D-4 — синтаксис MIME (наследуется из существующего DB CHECK V12);
|
||||
//! - D-5 — закрытый allowlist MIME по kind (content sniffing отсутствует);
|
||||
//! - D-7 — пустое содержимое отвергается;
|
||||
//! - D-8 — JSON валидируется locked-парсером `serde_json` и хранится дословно;
|
||||
//! - D-9 — UTF-8 без replacement и без «успешного префикса»;
|
||||
//! - D-10 — грамматика URI;
|
||||
//! - D-11 — грамматика name;
|
||||
//! - D-14 — стабильные коды/поля отказов (`ResourceError`).
|
||||
//!
|
||||
//! Коды отказа — контракт wire-уровня: HTTP-статус и envelope формирует
|
||||
//! admin-api (`error.rs`), а домен отвечает только за `code`/`field`.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::ids::{OperationId, ResourceId};
|
||||
|
||||
/// Storage ceiling одного blob-а (`MAX_ARTIFACT_BYTES`) и DB CHECK
|
||||
/// `artifact_blobs_size_check`. Это не новый продуктовый порог: default
|
||||
/// `ResourceLimits` равен этому потолку (D-3).
|
||||
pub const RESOURCE_STORAGE_CEILING: usize = 256 * 1024;
|
||||
|
||||
/// Верхняя граница `description` в байтах (D-20, DB CHECK `resources_description_len`).
|
||||
pub const MAX_RESOURCE_DESCRIPTION_BYTES: usize = 1024;
|
||||
|
||||
/// Нижняя и верхняя границы URI в байтах; следуют из грамматики UR-2 (D-10).
|
||||
pub const MIN_RESOURCE_URI_BYTES: usize = 10;
|
||||
pub const MAX_RESOURCE_URI_BYTES: usize = 200;
|
||||
|
||||
/// Верхняя граница `name` в символах (ASCII-грамматика D-11).
|
||||
pub const MAX_RESOURCE_NAME_BYTES: usize = 64;
|
||||
|
||||
const URI_SCHEME: &str = "crank://";
|
||||
|
||||
const TEXT_MIME_TYPES: &[&str] = &["text/plain", "text/markdown", "text/csv"];
|
||||
const JSON_MIME_TYPES: &[&str] = &["application/json"];
|
||||
const BINARY_MIME_TYPES: &[&str] = &[
|
||||
"application/octet-stream",
|
||||
"application/pdf",
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/gif",
|
||||
"image/webp",
|
||||
"image/svg+xml",
|
||||
"text/html",
|
||||
];
|
||||
|
||||
/// Общий typed контракт capability (AD-2): Operation, Resource (и будущий Prompt).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum CapabilityKind {
|
||||
Operation,
|
||||
Resource,
|
||||
}
|
||||
|
||||
/// Typed ссылка на capability. Варианты несовместимы по типу: Operation-ref не
|
||||
/// принимается там, где нужен Resource-ref (AT-3.6-01).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase", tag = "kind", content = "id")]
|
||||
pub enum CapabilityRef {
|
||||
Operation(OperationId),
|
||||
Resource(ResourceId),
|
||||
}
|
||||
|
||||
impl fmt::Display for CapabilityKind {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(match self {
|
||||
Self::Operation => "operation",
|
||||
Self::Resource => "resource",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Ошибка несовместимости typed-ссылки на capability.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("capability reference is a {actual}, expected a {expected}")]
|
||||
pub struct CapabilityKindMismatch {
|
||||
pub expected: CapabilityKind,
|
||||
pub actual: CapabilityKind,
|
||||
}
|
||||
|
||||
impl CapabilityRef {
|
||||
pub fn kind(&self) -> CapabilityKind {
|
||||
match self {
|
||||
Self::Operation(_) => CapabilityKind::Operation,
|
||||
Self::Resource(_) => CapabilityKind::Resource,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resource-ref или типизированный отказ — «поиск слов» вместо проверки типа не используется.
|
||||
pub fn as_resource(&self) -> Result<&ResourceId, CapabilityKindMismatch> {
|
||||
match self {
|
||||
Self::Resource(resource_id) => Ok(resource_id),
|
||||
Self::Operation(_) => Err(CapabilityKindMismatch {
|
||||
expected: CapabilityKind::Resource,
|
||||
actual: CapabilityKind::Operation,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_operation(&self) -> Result<&OperationId, CapabilityKindMismatch> {
|
||||
match self {
|
||||
Self::Operation(operation_id) => Ok(operation_id),
|
||||
Self::Resource(_) => Err(CapabilityKindMismatch {
|
||||
expected: CapabilityKind::Operation,
|
||||
actual: CapabilityKind::Resource,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-значения `ResourceKind` (D-2).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceKind {
|
||||
Text,
|
||||
Json,
|
||||
Binary,
|
||||
}
|
||||
|
||||
impl ResourceKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Text => "text",
|
||||
Self::Json => "json",
|
||||
Self::Binary => "binary",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"text" => Some(Self::Text),
|
||||
"json" => Some(Self::Json),
|
||||
"binary" => Some(Self::Binary),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// kind, для которого MIME входит в закрытый allowlist D-5.
|
||||
pub fn for_mime(mime_type: &str) -> Option<Self> {
|
||||
if TEXT_MIME_TYPES.contains(&mime_type) {
|
||||
Some(Self::Text)
|
||||
} else if JSON_MIME_TYPES.contains(&mime_type) {
|
||||
Some(Self::Json)
|
||||
} else if BINARY_MIME_TYPES.contains(&mime_type) {
|
||||
Some(Self::Binary)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allows_mime_type(self, mime_type: &str) -> bool {
|
||||
Self::for_mime(mime_type) == Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-значения `ResourceStatus` (D-2); отдельный тип, форма как у `OperationStatus`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceStatus {
|
||||
Draft,
|
||||
Published,
|
||||
Archived,
|
||||
}
|
||||
|
||||
impl ResourceStatus {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Draft => "draft",
|
||||
Self::Published => "published",
|
||||
Self::Archived => "archived",
|
||||
}
|
||||
}
|
||||
|
||||
/// Допустимый lifecycle-переход. Publish/archive реализуются в 3.7, но модель
|
||||
/// обязана отвергать недопустимый переход уже в 3.6.
|
||||
pub fn can_transition_to(self, next: Self) -> bool {
|
||||
matches!(
|
||||
(self, next),
|
||||
(Self::Draft, Self::Published | Self::Archived)
|
||||
| (Self::Published, Self::Draft | Self::Archived)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ResourceKind {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ResourceStatus {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
/// Действия lifecycle Resource (описательная часть контракта).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceLifecycleAction {
|
||||
Publish,
|
||||
Revert,
|
||||
Archive,
|
||||
}
|
||||
|
||||
impl ResourceLifecycleAction {
|
||||
pub fn target(self) -> ResourceStatus {
|
||||
match self {
|
||||
Self::Publish => ResourceStatus::Published,
|
||||
Self::Revert => ResourceStatus::Draft,
|
||||
Self::Archive => ResourceStatus::Archived,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Проверенный lifecycle-переход; `ResourceLifecycle::transition` возвращает его
|
||||
/// только для допустимой пары состояний.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceLifecycle {
|
||||
pub from: ResourceStatus,
|
||||
pub action: ResourceLifecycleAction,
|
||||
}
|
||||
|
||||
impl ResourceLifecycle {
|
||||
pub fn transition(
|
||||
from: ResourceStatus,
|
||||
action: ResourceLifecycleAction,
|
||||
) -> Result<Self, ResourceError> {
|
||||
let to = action.target();
|
||||
if !from.can_transition_to(to) {
|
||||
return Err(ResourceError::InvalidLifecycleTransition { from, to });
|
||||
}
|
||||
Ok(Self { from, action })
|
||||
}
|
||||
|
||||
pub fn to(self) -> ResourceStatus {
|
||||
self.action.target()
|
||||
}
|
||||
}
|
||||
|
||||
/// Wire-значения sensitivity совпадают с существующим CHECK V12 (D-13).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ResourceSensitivity {
|
||||
Public,
|
||||
Internal,
|
||||
Secret,
|
||||
}
|
||||
|
||||
impl ResourceSensitivity {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Public => "public",
|
||||
Self::Internal => "internal",
|
||||
Self::Secret => "secret",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value {
|
||||
"public" => Some(Self::Public),
|
||||
"internal" => Some(Self::Internal),
|
||||
"secret" => Some(Self::Secret),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Задаваемые атрибуты Draft (D-16): URI/name/kind неизменяемы после создания.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceMetadata {
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: ResourceKind,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: ResourceSensitivity,
|
||||
}
|
||||
|
||||
impl ResourceMetadata {
|
||||
/// D-10 UR-1..UR-3: литерал `crank://`, ASCII charset 10..=200 байт, непустые
|
||||
/// сегменты без `.`/`..` и без trailing `/`.
|
||||
pub fn uri_is_valid(uri: &str) -> bool {
|
||||
let Some(path) = uri.strip_prefix(URI_SCHEME) else {
|
||||
return false;
|
||||
};
|
||||
if uri.len() < MIN_RESOURCE_URI_BYTES || uri.len() > MAX_RESOURCE_URI_BYTES {
|
||||
return false;
|
||||
}
|
||||
// UR-2: после литерала схемы ровно `1 + 0..190 + 1` символов, то есть
|
||||
// вся ссылка 10..=200 байт включительно.
|
||||
const MAX_PATH_BYTES: usize = MAX_RESOURCE_URI_BYTES - URI_SCHEME.len();
|
||||
if path.is_empty() || path.len() > MAX_PATH_BYTES {
|
||||
return false;
|
||||
}
|
||||
let bytes = path.as_bytes();
|
||||
let Some((first, rest)) = bytes.split_first() else {
|
||||
return false;
|
||||
};
|
||||
let Some((last, middle)) = rest.split_last() else {
|
||||
return false;
|
||||
};
|
||||
let edge = |byte: u8| byte.is_ascii_alphanumeric();
|
||||
if !edge(*first) || !edge(*last) {
|
||||
return false;
|
||||
}
|
||||
if !middle.iter().all(|byte| {
|
||||
byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'~' | b'/' | b'-')
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
if path.ends_with('/') {
|
||||
return false;
|
||||
}
|
||||
path.split('/')
|
||||
.all(|segment| !segment.is_empty() && segment != "." && segment != "..")
|
||||
}
|
||||
|
||||
/// D-11: `^[a-z][a-z0-9_-]{0,63}$`.
|
||||
pub fn name_is_valid(name: &str) -> bool {
|
||||
let bytes = name.as_bytes();
|
||||
if bytes.is_empty() || bytes.len() > MAX_RESOURCE_NAME_BYTES {
|
||||
return false;
|
||||
}
|
||||
let Some((first, rest)) = bytes.split_first() else {
|
||||
return false;
|
||||
};
|
||||
first.is_ascii_lowercase()
|
||||
&& rest.iter().all(|byte| {
|
||||
byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
|
||||
})
|
||||
}
|
||||
|
||||
/// D-4: bare `type/subtype` без параметров; грамматика наследуется из V12.
|
||||
pub fn mime_syntax_is_valid(mime_type: &str) -> bool {
|
||||
let Some((kind, subtype)) = mime_type.split_once('/') else {
|
||||
return false;
|
||||
};
|
||||
if kind.is_empty()
|
||||
|| subtype.is_empty()
|
||||
|| mime_type.len() > 255
|
||||
|| mime_type.len() < 3
|
||||
|| subtype.contains('/')
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let token_is_valid = |token: &str| {
|
||||
token.bytes().all(|byte| {
|
||||
byte.is_ascii_alphanumeric()
|
||||
|| matches!(
|
||||
byte,
|
||||
b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-'
|
||||
)
|
||||
})
|
||||
};
|
||||
token_is_valid(kind) && token_is_valid(subtype)
|
||||
}
|
||||
|
||||
pub fn description_is_valid(description: &str) -> bool {
|
||||
description.len() <= MAX_RESOURCE_DESCRIPTION_BYTES
|
||||
}
|
||||
|
||||
/// D-20 шаг E: фиксированный порядок uri → name → description → kind/mime.
|
||||
pub fn validate(&self) -> Result<(), ResourceError> {
|
||||
if !Self::uri_is_valid(&self.uri) {
|
||||
return Err(ResourceError::UriInvalid);
|
||||
}
|
||||
if !Self::name_is_valid(&self.name) {
|
||||
return Err(ResourceError::NameInvalid);
|
||||
}
|
||||
if !Self::description_is_valid(&self.description) {
|
||||
return Err(ResourceError::DescriptionInvalid);
|
||||
}
|
||||
self.validate_mime()
|
||||
}
|
||||
|
||||
/// Правило MIME в одном месте (D-20 шаг E): синтаксис → allowlist → совместимость с kind.
|
||||
pub fn validate_mime(&self) -> Result<(), ResourceError> {
|
||||
if !Self::mime_syntax_is_valid(&self.mime_type) {
|
||||
return Err(ResourceError::MimeSyntaxInvalid);
|
||||
}
|
||||
match ResourceKind::for_mime(&self.mime_type) {
|
||||
None => Err(ResourceError::MimeNotAllowed),
|
||||
Some(owner) if owner != self.kind => Err(ResourceError::KindMismatch),
|
||||
Some(_) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// D-9/D-3: text-kind; L inclusive, L+1 отвергается целиком, без U+FFFD и усечения.
|
||||
pub fn validate_text(bytes: &[u8], limit: usize) -> Result<Vec<u8>, ResourceError> {
|
||||
if bytes.len() > limit {
|
||||
return Err(ResourceError::ContentTooLarge);
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return Err(ResourceError::ContentEmpty);
|
||||
}
|
||||
if std::str::from_utf8(bytes).is_err() {
|
||||
return Err(ResourceError::ContentInvalidUtf8);
|
||||
}
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
|
||||
/// D-8: валидация locked-парсером `serde_json` без features; bytes хранятся дословно.
|
||||
pub fn validate_json(bytes: &[u8], limit: usize) -> Result<Vec<u8>, ResourceError> {
|
||||
if bytes.len() > limit {
|
||||
return Err(ResourceError::ContentTooLarge);
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return Err(ResourceError::ContentEmpty);
|
||||
}
|
||||
if serde_json::from_slice::<serde_json::Value>(bytes).is_err() {
|
||||
return Err(ResourceError::ContentInvalidJson);
|
||||
}
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
|
||||
/// Проверка содержимого по typed kind (без content sniffing).
|
||||
pub fn validate_content(
|
||||
kind: ResourceKind,
|
||||
mime_type: &str,
|
||||
bytes: &[u8],
|
||||
limits: &ResourceLimits,
|
||||
) -> Result<Vec<u8>, ResourceError> {
|
||||
let limit = limits.effective_limit(kind);
|
||||
match kind {
|
||||
ResourceKind::Text => Self::validate_text(bytes, limit),
|
||||
ResourceKind::Json => Self::validate_json(bytes, limit),
|
||||
ResourceKind::Binary => {
|
||||
if bytes.len() > limit {
|
||||
return Err(ResourceError::ContentTooLarge);
|
||||
}
|
||||
if bytes.is_empty() {
|
||||
return Err(ResourceError::ContentEmpty);
|
||||
}
|
||||
let _ = mime_type;
|
||||
Ok(bytes.to_vec())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Безопасный finding для непригодного MIME (bytes не раскрываются).
|
||||
pub fn mime_finding(
|
||||
mime_type: &str,
|
||||
kind: ResourceKind,
|
||||
limits: &ResourceLimits,
|
||||
) -> ResourceFinding {
|
||||
let _ = limits;
|
||||
if !Self::mime_syntax_is_valid(mime_type) {
|
||||
return ResourceFinding::rejected(ResourceFindingCode::MimeSyntaxInvalid, "mime_type");
|
||||
}
|
||||
match ResourceKind::for_mime(mime_type) {
|
||||
None => ResourceFinding::rejected(ResourceFindingCode::MimeNotAllowed, "mime_type"),
|
||||
Some(owner) if owner != kind => {
|
||||
ResourceFinding::rejected(ResourceFindingCode::KindMismatch, "kind")
|
||||
}
|
||||
Some(_) => ResourceFinding::accepted(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Безопасный finding для невалидного JSON-документа.
|
||||
pub fn json_finding(bytes: &[u8], limits: &ResourceLimits) -> ResourceFinding {
|
||||
match Self::validate_json(bytes, limits.effective_limit(ResourceKind::Json)) {
|
||||
Ok(_) => ResourceFinding::accepted(),
|
||||
Err(error) => {
|
||||
ResourceFinding::rejected(error.finding_code(), error.field_or("content"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Пределы содержимого по kind. Значение выше storage ceiling отвергается при
|
||||
/// конфигурации; новый env-ключ не вводится (D-3).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ResourceLimits {
|
||||
text: usize,
|
||||
json: usize,
|
||||
binary: usize,
|
||||
}
|
||||
|
||||
impl Default for ResourceLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: RESOURCE_STORAGE_CEILING,
|
||||
json: RESOURCE_STORAGE_CEILING,
|
||||
binary: RESOURCE_STORAGE_CEILING,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceLimits {
|
||||
pub const STORAGE_CEILING: usize = RESOURCE_STORAGE_CEILING;
|
||||
|
||||
/// Конфигурация пределов; значения выше потолка не принимаются (D-3).
|
||||
pub fn new(text: usize, json: usize, binary: usize) -> Result<Self, ResourceError> {
|
||||
if [text, json, binary]
|
||||
.into_iter()
|
||||
.any(|limit| limit == 0 || limit > RESOURCE_STORAGE_CEILING)
|
||||
{
|
||||
return Err(ResourceError::InvalidLimits);
|
||||
}
|
||||
Ok(Self { text, json, binary })
|
||||
}
|
||||
|
||||
/// Один предел на все три kind — форма, используемая сервисом и тестами.
|
||||
pub fn uniform(limit: usize) -> Result<Self, ResourceError> {
|
||||
Self::new(limit, limit, limit)
|
||||
}
|
||||
|
||||
pub fn effective_limit(&self, kind: ResourceKind) -> usize {
|
||||
match kind {
|
||||
ResourceKind::Text => self.text,
|
||||
ResourceKind::Json => self.json,
|
||||
ResourceKind::Binary => self.binary,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Коды findings (те же строки, что и stable `error.code`, D-14).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ResourceFindingCode {
|
||||
#[serde(rename = "resource_content_empty")]
|
||||
ContentEmpty,
|
||||
#[serde(rename = "resource_content_too_large")]
|
||||
ContentTooLarge,
|
||||
#[serde(rename = "resource_content_invalid_utf8")]
|
||||
ContentInvalidUtf8,
|
||||
#[serde(rename = "resource_content_invalid_json")]
|
||||
ContentInvalidJson,
|
||||
#[serde(rename = "resource_mime_syntax_invalid")]
|
||||
MimeSyntaxInvalid,
|
||||
#[serde(rename = "resource_mime_not_allowed")]
|
||||
MimeNotAllowed,
|
||||
#[serde(rename = "resource_kind_mismatch")]
|
||||
KindMismatch,
|
||||
/// Служебное значение «нарушений нет»; в ответах `findings` пуст на успехе,
|
||||
/// поэтому этот код на wire не попадает.
|
||||
#[serde(rename = "resource_finding_accepted")]
|
||||
Accepted,
|
||||
}
|
||||
|
||||
impl ResourceFindingCode {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ContentEmpty => "resource_content_empty",
|
||||
Self::ContentTooLarge => "resource_content_too_large",
|
||||
Self::ContentInvalidUtf8 => "resource_content_invalid_utf8",
|
||||
Self::ContentInvalidJson => "resource_content_invalid_json",
|
||||
Self::MimeSyntaxInvalid => "resource_mime_syntax_invalid",
|
||||
Self::MimeNotAllowed => "resource_mime_not_allowed",
|
||||
Self::KindMismatch => "resource_kind_mismatch",
|
||||
Self::Accepted => "resource_finding_accepted",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Finding не содержит bytes содержимого: только стабильный код и поле.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceFinding {
|
||||
code: ResourceFindingCode,
|
||||
field: &'static str,
|
||||
}
|
||||
|
||||
impl ResourceFinding {
|
||||
pub fn rejected(code: ResourceFindingCode, field: &'static str) -> Self {
|
||||
Self { code, field }
|
||||
}
|
||||
|
||||
/// «Нарушений нет» — служебное значение, не являющееся rejection.
|
||||
pub fn accepted() -> Self {
|
||||
Self {
|
||||
code: ResourceFindingCode::Accepted,
|
||||
field: "",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code(&self) -> &'static str {
|
||||
self.code.as_str()
|
||||
}
|
||||
|
||||
pub fn field(&self) -> &'static str {
|
||||
self.field
|
||||
}
|
||||
|
||||
pub fn is_rejection(&self) -> bool {
|
||||
!self.field.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Стабильные коды/поля отказов Resource (D-14) без HTTP-статусов: статус
|
||||
/// назначает admin-api по коду.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ResourceError {
|
||||
#[error("resource content must not be empty")]
|
||||
ContentEmpty,
|
||||
/// Story 3.9: форма переносимого envelope не распознана (неизвестные/недостающие
|
||||
/// ключи, неподдержанная версия, синтаксис base64/hex, `source`). Транспортный
|
||||
/// контракт envelope живёт в admin-api; здесь только стабильный wire-код.
|
||||
#[error("resource portability envelope is invalid")]
|
||||
PortabilityEnvelopeInvalid,
|
||||
#[error("resource content exceeds the configured limit")]
|
||||
ContentTooLarge,
|
||||
#[error("resource content is not valid UTF-8")]
|
||||
ContentInvalidUtf8,
|
||||
#[error("resource content is not valid JSON")]
|
||||
ContentInvalidJson,
|
||||
#[error("resource mime type syntax is invalid")]
|
||||
MimeSyntaxInvalid,
|
||||
#[error("resource mime type is not allowed for this kind")]
|
||||
MimeNotAllowed,
|
||||
#[error("resource mime type is incompatible with the declared kind")]
|
||||
KindMismatch,
|
||||
#[error("resource uri is invalid")]
|
||||
UriInvalid,
|
||||
#[error("resource name is invalid")]
|
||||
NameInvalid,
|
||||
#[error("resource description is invalid")]
|
||||
DescriptionInvalid,
|
||||
/// Значение поля метаданных вне набора (`kind`/`sensitivity`): форма запроса, а не
|
||||
/// доменный код (D-20 B/E). `code()` отдаёт принятый для этого отказа generic-код,
|
||||
/// а admin-api выводит его без Resource-специфичного контекста.
|
||||
#[error("resource metadata field `{field}` has an unknown value")]
|
||||
UnknownMetadataValue { field: &'static str },
|
||||
#[error("resource uri already exists in this workspace")]
|
||||
UriDuplicate,
|
||||
#[error("resource name already exists in this workspace")]
|
||||
NameDuplicate,
|
||||
#[error("resource field {field} is immutable")]
|
||||
FieldImmutable { field: &'static str },
|
||||
#[error("resource changed since it was read")]
|
||||
Stale,
|
||||
#[error("resource was not found in this workspace")]
|
||||
NotFound,
|
||||
/// Story 3.8: необратимый security-revoke закрыл Resource целиком. Это не
|
||||
/// lifecycle-состояние: archive/редактирование его не снимают, а новые
|
||||
/// публикации и привязки запрещены.
|
||||
#[error("resource has been revoked")]
|
||||
Revoked,
|
||||
#[error("resource artifact integrity verification failed")]
|
||||
ArtifactIntegrity,
|
||||
/// Публикация отклонена secret-policy: содержимое содержит структурный private key,
|
||||
/// raw credential assignment либо explicit access-bypassing reference. Наружу отдаётся
|
||||
/// только общая категория, никогда не совпавший текст (TL decision 4).
|
||||
#[error("resource content contains secret material or an access-bypassing reference")]
|
||||
SecretFindings,
|
||||
#[error("resource storage is unavailable")]
|
||||
StorageUnavailable,
|
||||
#[error("resource content limits are invalid")]
|
||||
InvalidLimits,
|
||||
#[error("resource lifecycle transition from {from} to {to} is not allowed")]
|
||||
InvalidLifecycleTransition {
|
||||
from: ResourceStatus,
|
||||
to: ResourceStatus,
|
||||
},
|
||||
/// Story 3.10: структурно неверное определение REST-шаблона (wire
|
||||
/// `resource_source_invalid`); `field` — конкретное поле отказа.
|
||||
#[error("resource source definition is invalid")]
|
||||
SourceInvalid { field: &'static str },
|
||||
/// Story 3.10: Operation/версия не найдена в этом workspace (чужой workspace
|
||||
/// неотличим от отсутствующего — без раскрытия).
|
||||
#[error("resource source operation was not found in this workspace")]
|
||||
SourceNotFound,
|
||||
/// Story 3.10: версия существует, но не Published.
|
||||
#[error("resource source operation version is not published")]
|
||||
SourceNotPublished,
|
||||
/// Story 3.10: публикацию блокируют findings шаблона.
|
||||
#[error("resource source definition has blocking findings")]
|
||||
SourceBlocked {
|
||||
findings: Vec<crate::resource::template::TemplateFinding>,
|
||||
},
|
||||
/// Story 3.10: определение шаблона не переносимо (export/content).
|
||||
#[error("resource source definition is not portable")]
|
||||
SourceNotPortable,
|
||||
}
|
||||
|
||||
impl ResourceError {
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
Self::ContentEmpty => "resource_content_empty",
|
||||
Self::PortabilityEnvelopeInvalid => "resource_portability_envelope_invalid",
|
||||
Self::ContentTooLarge => "resource_content_too_large",
|
||||
Self::ContentInvalidUtf8 => "resource_content_invalid_utf8",
|
||||
Self::ContentInvalidJson => "resource_content_invalid_json",
|
||||
Self::MimeSyntaxInvalid => "resource_mime_syntax_invalid",
|
||||
Self::MimeNotAllowed => "resource_mime_not_allowed",
|
||||
Self::KindMismatch => "resource_kind_mismatch",
|
||||
Self::UriInvalid => "resource_uri_invalid",
|
||||
Self::NameInvalid => "resource_name_invalid",
|
||||
Self::DescriptionInvalid => "resource_description_invalid",
|
||||
// D-20 B/E: у этого отказа нет Resource-специфичного кода.
|
||||
Self::UnknownMetadataValue { .. } => "validation_error",
|
||||
Self::UriDuplicate => "resource_uri_duplicate",
|
||||
Self::NameDuplicate => "resource_name_duplicate",
|
||||
Self::FieldImmutable { .. } => "resource_field_immutable",
|
||||
Self::Stale => "resource_stale",
|
||||
Self::NotFound => "resource_not_found",
|
||||
Self::Revoked => "resource_revoked",
|
||||
Self::ArtifactIntegrity => "resource_artifact_integrity",
|
||||
Self::SecretFindings => "resource_secret_findings",
|
||||
Self::StorageUnavailable => "resource_storage_unavailable",
|
||||
Self::InvalidLimits => "resource_limits_invalid",
|
||||
Self::InvalidLifecycleTransition { .. } => "resource_lifecycle_invalid",
|
||||
Self::SourceInvalid { .. } => "resource_source_invalid",
|
||||
Self::SourceNotFound => "resource_source_not_found",
|
||||
Self::SourceNotPublished => "resource_source_not_published",
|
||||
Self::SourceBlocked { .. } => "resource_source_blocked",
|
||||
Self::SourceNotPortable => "resource_source_not_portable",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn field(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::ContentEmpty
|
||||
| Self::ContentTooLarge
|
||||
| Self::ContentInvalidUtf8
|
||||
| Self::ContentInvalidJson
|
||||
| Self::ArtifactIntegrity
|
||||
| Self::SecretFindings => Some("content"),
|
||||
Self::PortabilityEnvelopeInvalid => Some("envelope"),
|
||||
Self::MimeSyntaxInvalid | Self::MimeNotAllowed => Some("mime_type"),
|
||||
Self::KindMismatch => Some("kind"),
|
||||
Self::UriInvalid | Self::UriDuplicate => Some("uri"),
|
||||
Self::NameInvalid | Self::NameDuplicate => Some("name"),
|
||||
Self::DescriptionInvalid => Some("description"),
|
||||
Self::FieldImmutable { field } => Some(field),
|
||||
Self::Stale => Some("expected_updated_at"),
|
||||
Self::NotFound | Self::Revoked => Some("resource_id"),
|
||||
Self::StorageUnavailable
|
||||
| Self::InvalidLimits
|
||||
| Self::UnknownMetadataValue { .. }
|
||||
| Self::InvalidLifecycleTransition { .. } => None,
|
||||
Self::SourceInvalid { field } => Some(field),
|
||||
Self::SourceNotFound => Some("source.operation_id"),
|
||||
Self::SourceNotPublished => Some("source.operation_version"),
|
||||
Self::SourceBlocked { .. } | Self::SourceNotPortable => Some("source"),
|
||||
}
|
||||
}
|
||||
|
||||
fn field_or(&self, fallback: &'static str) -> &'static str {
|
||||
self.field().unwrap_or(fallback)
|
||||
}
|
||||
|
||||
fn finding_code(&self) -> ResourceFindingCode {
|
||||
match self {
|
||||
Self::ContentEmpty => ResourceFindingCode::ContentEmpty,
|
||||
Self::ContentTooLarge => ResourceFindingCode::ContentTooLarge,
|
||||
Self::ContentInvalidUtf8 => ResourceFindingCode::ContentInvalidUtf8,
|
||||
Self::MimeSyntaxInvalid => ResourceFindingCode::MimeSyntaxInvalid,
|
||||
Self::MimeNotAllowed => ResourceFindingCode::MimeNotAllowed,
|
||||
Self::KindMismatch => ResourceFindingCode::KindMismatch,
|
||||
_ => ResourceFindingCode::ContentInvalidJson,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed Resource aggregate. Published-модель существует отдельным типом
|
||||
/// (`PublishedResourceVersion`) и не содержит внутренних ссылок (D-12).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Resource {
|
||||
pub resource_id: ResourceId,
|
||||
pub uri: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub kind: ResourceKind,
|
||||
pub mime_type: String,
|
||||
pub sensitivity: ResourceSensitivity,
|
||||
pub status: ResourceStatus,
|
||||
pub current_draft_version: u32,
|
||||
pub created_at: time::OffsetDateTime,
|
||||
pub updated_at: time::OffsetDateTime,
|
||||
}
|
||||
|
||||
impl Resource {
|
||||
/// Новый Draft: ровно одна текущая черновая версия (D-15).
|
||||
pub fn draft(resource_id: ResourceId, metadata: ResourceMetadata) -> Self {
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
Self {
|
||||
resource_id,
|
||||
uri: metadata.uri,
|
||||
name: metadata.name,
|
||||
description: metadata.description,
|
||||
kind: metadata.kind,
|
||||
mime_type: metadata.mime_type,
|
||||
sensitivity: metadata.sensitivity,
|
||||
status: ResourceStatus::Draft,
|
||||
current_draft_version: 1,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(&self) -> ResourceStatus {
|
||||
self.status
|
||||
}
|
||||
|
||||
pub fn current_draft_version(&self) -> u32 {
|
||||
self.current_draft_version
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> ResourceMetadata {
|
||||
ResourceMetadata {
|
||||
uri: self.uri.clone(),
|
||||
name: self.name.clone(),
|
||||
description: self.description.clone(),
|
||||
kind: self.kind,
|
||||
mime_type: self.mime_type.clone(),
|
||||
sensitivity: self.sensitivity,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Черновая версия Resource: exact digest и metadata, без filesystem path,
|
||||
/// filename и mutable external reference (D-12).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResourceVersion {
|
||||
pub version: u32,
|
||||
pub kind: ResourceKind,
|
||||
pub mime_type: String,
|
||||
pub size_bytes: u64,
|
||||
pub digest: String,
|
||||
pub created_at: time::OffsetDateTime,
|
||||
pub superseded_at: Option<time::OffsetDateTime>,
|
||||
}
|
||||
|
||||
impl ResourceVersion {
|
||||
pub fn draft(
|
||||
version: u32,
|
||||
kind: ResourceKind,
|
||||
mime_type: String,
|
||||
size_bytes: u64,
|
||||
digest: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
version,
|
||||
kind,
|
||||
mime_type,
|
||||
size_bytes,
|
||||
digest,
|
||||
created_at: time::OffsetDateTime::now_utc(),
|
||||
superseded_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
|
||||
pub fn digest(&self) -> &str {
|
||||
&self.digest
|
||||
}
|
||||
|
||||
pub fn size_bytes(&self) -> u64 {
|
||||
self.size_bytes
|
||||
}
|
||||
|
||||
pub fn is_current(&self) -> bool {
|
||||
self.superseded_at.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Immutable published-модель версии: конструируется только из Draft, мутирующих
|
||||
/// методов нет, внутренние ссылки не публикуются (D-12).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PublishedResourceVersion {
|
||||
version: u32,
|
||||
kind: ResourceKind,
|
||||
mime_type: String,
|
||||
size_bytes: u64,
|
||||
digest: String,
|
||||
}
|
||||
|
||||
impl PublishedResourceVersion {
|
||||
pub fn from_draft(draft: &ResourceVersion) -> Self {
|
||||
Self {
|
||||
version: draft.version,
|
||||
kind: draft.kind,
|
||||
mime_type: draft.mime_type.clone(),
|
||||
size_bytes: draft.size_bytes,
|
||||
digest: draft.digest.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u32 {
|
||||
self.version
|
||||
}
|
||||
|
||||
pub fn digest(&self) -> &str {
|
||||
&self.digest
|
||||
}
|
||||
|
||||
pub fn size_bytes(&self) -> u64 {
|
||||
self.size_bytes
|
||||
}
|
||||
}
|
||||
|
||||
pub mod publication;
|
||||
|
||||
pub mod template;
|
||||
|
||||
pub use publication::{publication_include_directives, publication_secret_findings};
|
||||
pub use template::{
|
||||
MAX_TEMPLATE_CACHE_BYTES, MAX_TEMPLATE_CACHE_TTL_MS, TEMPLATE_CACHE_SCOPE, TemplateCache,
|
||||
TemplateFailure, TemplateFailureOutcome, TemplateFinding, TemplateFindingCode,
|
||||
TemplateParameter, TemplateSource, TemplateSourceError, cache_policy_findings,
|
||||
parse_uri_template,
|
||||
};
|
||||
Reference in new issue
Block a user