feat(epic4): подтверждать durable Task после атомарного PG-commit (Story 4.2)
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 19m34s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
CI / UI Checks (pull_request) Successful in 8s
CI / Rust Checks (pull_request) Successful in 19m34s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
Application entry выдаёт Task ID только после атомарного PostgreSQL commit Task+intent+capacity; replay/conflict, owner scope, bounded envelope, terminal CAS и fail-closed readiness проверены на реальном PG. Также включён принятый план перехода на rmcp (только документ, миграция не запускается).
This commit is contained in:
1 parent
cc612516a2
commit
2219a7217d
37 files changed
+4028
-136
No files matched your search
@@ -0,0 +1,295 @@
|
||||
//! Application entry of durable background Tasks (Story 4.2, FR-22/FR-23).
|
||||
//!
|
||||
//! The entry takes an already authenticated principal (a verified machine credential, or an
|
||||
//! administrator identity verified by the calling admin surface), resolves the exact published Tool,
|
||||
//! repeats the caller's authorization, pins the Published Version/policy/deadline and delegates the
|
||||
//! durable acceptance to the runtime Task service. The repository owns the transaction, so the
|
||||
//! returned Task ID exists only after Task + dispatch intent + queue slot committed.
|
||||
//!
|
||||
//! Deliberately not wired: the public MCP `tools/call`/Tasks wire (Story 4.7) and the worker/leases
|
||||
//! (Story 4.3). The existing synchronous/unsupported `tools/call` path is unchanged, and this entry
|
||||
//! never spawns an ephemeral execution future.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crank_core::{
|
||||
CorrelationContext, TaskAcceptance, TaskAccess, TaskError, TaskId, TaskOwnerKind, TaskRecord,
|
||||
ToolExecutionMode,
|
||||
};
|
||||
use crank_registry::{PostgresRegistry, PublishedAgentTool};
|
||||
use crank_runtime::{TaskAcceptDraft, TaskOutcome, TaskService};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::access::credential_allows_security_level;
|
||||
use crate::catalog::PublishedToolCatalog;
|
||||
|
||||
/// Authenticated principal of one Task operation. The authorization scope identity is derived here
|
||||
/// from the verified credential/admin identity, never from a caller-supplied request string.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum TaskPrincipal {
|
||||
Agent {
|
||||
workspace_slug: String,
|
||||
agent_slug: String,
|
||||
credential: crank_core::VerifiedMachineCredential,
|
||||
},
|
||||
/// Administrator identity that the admin surface already authenticated. It is never a wildcard:
|
||||
/// owner, workspace and authorization scope all participate in the stored predicate.
|
||||
Admin {
|
||||
workspace_slug: String,
|
||||
agent_slug: String,
|
||||
user_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl TaskPrincipal {
|
||||
fn workspace_slug(&self) -> &str {
|
||||
match self {
|
||||
Self::Agent { workspace_slug, .. } | Self::Admin { workspace_slug, .. } => {
|
||||
workspace_slug
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn agent_slug(&self) -> &str {
|
||||
match self {
|
||||
Self::Agent { agent_slug, .. } | Self::Admin { agent_slug, .. } => agent_slug,
|
||||
}
|
||||
}
|
||||
|
||||
fn owner(&self, tool: &PublishedAgentTool) -> (TaskOwnerKind, String) {
|
||||
match self {
|
||||
Self::Agent { .. } => (TaskOwnerKind::Agent, tool.agent_id.as_str().to_owned()),
|
||||
Self::Admin { user_id, .. } => (TaskOwnerKind::Admin, user_id.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bounded server-derived authorization scope identity of this principal.
|
||||
fn authorization_scope(&self) -> String {
|
||||
let identity = match self {
|
||||
Self::Agent { credential, .. } => {
|
||||
let mut scopes = credential
|
||||
.scopes
|
||||
.iter()
|
||||
.map(|scope| format!("{scope:?}"))
|
||||
.collect::<Vec<_>>();
|
||||
scopes.sort();
|
||||
format!(
|
||||
"key:{}|mode:{:?}|level:{:?}|scopes:{}",
|
||||
credential
|
||||
.platform_api_key_id
|
||||
.as_ref()
|
||||
.map(|id| id.as_str().to_owned())
|
||||
.unwrap_or_else(|| "-".to_owned()),
|
||||
credential.machine_access_mode,
|
||||
credential.max_security_level,
|
||||
scopes.join(",")
|
||||
)
|
||||
}
|
||||
Self::Admin { user_id, .. } => format!("admin:{user_id}"),
|
||||
};
|
||||
identity.chars().take(160).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed refusal of the application entry. `NotFound`/`Denied` never reveal whether a foreign Task
|
||||
/// exists, and no variant carries Task payload or fingerprint.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum TaskApplicationError {
|
||||
#[error("task request was not found")]
|
||||
NotFound,
|
||||
#[error("task request is not authorized")]
|
||||
Denied,
|
||||
#[error("the published Tool policy does not accept durable background work")]
|
||||
NotBackground,
|
||||
#[error("the requested published Tool version is not available")]
|
||||
VersionUnavailable,
|
||||
#[error("this Tool requires a verified approval before acceptance")]
|
||||
ApprovalRequired,
|
||||
#[error(transparent)]
|
||||
Task(#[from] TaskError),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TaskApplication {
|
||||
catalog: PublishedToolCatalog,
|
||||
service: TaskService,
|
||||
}
|
||||
|
||||
impl TaskApplication {
|
||||
/// Production construction of the application entry over the process registry, the published
|
||||
/// catalog and the durable Task service.
|
||||
pub fn new(
|
||||
registry: PostgresRegistry,
|
||||
refresh_interval: Duration,
|
||||
coordination_store: Arc<dyn crank_core::CoordinationStateStore>,
|
||||
service: TaskService,
|
||||
) -> Self {
|
||||
Self {
|
||||
catalog: PublishedToolCatalog::new(registry, refresh_interval, coordination_store),
|
||||
service,
|
||||
}
|
||||
}
|
||||
|
||||
/// Readiness of the durable Task store this entry depends on.
|
||||
pub async fn health(&self) -> Result<(), TaskError> {
|
||||
self.service.health().await
|
||||
}
|
||||
|
||||
/// Accepts one background request for an already authenticated principal.
|
||||
///
|
||||
/// `expected_version` is the caller's explicit Published Version pin. Without it the current
|
||||
/// publication is pinned for new work and a retry of the same scoped key returns the stored Task
|
||||
/// even after a newer publication. An explicit pin may only retry the Task accepted with that
|
||||
/// exact version: a different pin is a typed conflict, never a rebind.
|
||||
pub async fn accept_background(
|
||||
&self,
|
||||
principal: &TaskPrincipal,
|
||||
tool_name: &str,
|
||||
expected_version: Option<u32>,
|
||||
scoped_key: &str,
|
||||
input: &Value,
|
||||
correlation: &CorrelationContext,
|
||||
) -> Result<TaskAcceptance, TaskApplicationError> {
|
||||
let tool = self.resolve_authorized_tool(principal, tool_name).await?;
|
||||
let current_version = tool.operation.version;
|
||||
let Some(policy) = tool.operation.execution_config.execution_policy else {
|
||||
return Err(TaskApplicationError::NotBackground);
|
||||
};
|
||||
if policy.mode == ToolExecutionMode::Synchronous {
|
||||
return Err(TaskApplicationError::NotBackground);
|
||||
}
|
||||
if tool
|
||||
.operation
|
||||
.execution_config
|
||||
.approval_policy
|
||||
.as_ref()
|
||||
.is_some_and(|approval| approval.required)
|
||||
{
|
||||
// Without a verified, non-consuming approval reference this entry fails closed instead
|
||||
// of accepting work a worker could never safely execute.
|
||||
return Err(TaskApplicationError::ApprovalRequired);
|
||||
}
|
||||
let draft = |operation_version: u32| {
|
||||
let (owner_kind, owner_id) = principal.owner(&tool);
|
||||
TaskAcceptDraft {
|
||||
workspace_id: tool.workspace_id.as_str().to_owned(),
|
||||
owner_kind,
|
||||
owner_id,
|
||||
authorization_scope: principal.authorization_scope(),
|
||||
operation_id: tool.operation.id.as_str().to_owned(),
|
||||
operation_version,
|
||||
policy_mode: policy.mode,
|
||||
scoped_key: scoped_key.to_owned(),
|
||||
input: input.clone(),
|
||||
correlation: correlation.clone(),
|
||||
deadline: Instant::now() + Duration::from_millis(policy.deadline_ms.max(1)),
|
||||
retention_ms: TaskService::default_retention_ms(),
|
||||
approval_reference: None,
|
||||
}
|
||||
};
|
||||
|
||||
let Some(requested) = expected_version else {
|
||||
return Ok(self.service.accept(draft(current_version)).await?);
|
||||
};
|
||||
let draft = draft(requested);
|
||||
match self.service.lookup(&draft).await? {
|
||||
Some(record) => {
|
||||
if record.input_fingerprint != TaskService::input_fingerprint(input)? {
|
||||
return Err(TaskApplicationError::Task(TaskError::FingerprintConflict));
|
||||
}
|
||||
if record.pins.operation_version != requested {
|
||||
return Err(TaskApplicationError::VersionUnavailable);
|
||||
}
|
||||
Ok(TaskAcceptance {
|
||||
task_id: record.task_id,
|
||||
state: record.state,
|
||||
operation_version: record.pins.operation_version,
|
||||
support: record.support,
|
||||
created_at_unix_ms: record.created_at_unix_ms,
|
||||
retain_until_unix_ms: record.pins.retain_until_unix_ms,
|
||||
replayed: true,
|
||||
})
|
||||
}
|
||||
None if requested == current_version => Ok(self.service.accept(draft).await?),
|
||||
// A new Task can only be accepted against the currently published version.
|
||||
None => Err(TaskApplicationError::VersionUnavailable),
|
||||
}
|
||||
}
|
||||
|
||||
/// Owner-scoped status read of one Task of the addressed published Tool.
|
||||
pub async fn status(
|
||||
&self,
|
||||
principal: &TaskPrincipal,
|
||||
tool_name: &str,
|
||||
task_id: TaskId,
|
||||
) -> Result<TaskRecord, TaskApplicationError> {
|
||||
let access = self.task_access(principal, tool_name).await?;
|
||||
match self.service.status(&access, task_id).await {
|
||||
Ok(record) => Ok(record),
|
||||
Err(TaskError::NotFound) => Err(TaskApplicationError::NotFound),
|
||||
Err(error) => Err(TaskApplicationError::Task(error)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Owner-scoped result projection of one Task of the addressed published Tool.
|
||||
pub async fn result(
|
||||
&self,
|
||||
principal: &TaskPrincipal,
|
||||
tool_name: &str,
|
||||
task_id: TaskId,
|
||||
) -> Result<TaskOutcome, TaskApplicationError> {
|
||||
let access = self.task_access(principal, tool_name).await?;
|
||||
match self.service.result(&access, task_id).await {
|
||||
Ok(outcome) => Ok(outcome),
|
||||
Err(TaskError::NotFound) => Err(TaskApplicationError::NotFound),
|
||||
Err(error) => Err(TaskApplicationError::Task(error)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn task_access(
|
||||
&self,
|
||||
principal: &TaskPrincipal,
|
||||
tool_name: &str,
|
||||
) -> Result<TaskAccess, TaskApplicationError> {
|
||||
let tool = self.resolve_authorized_tool(principal, tool_name).await?;
|
||||
let (owner_kind, owner_id) = principal.owner(&tool);
|
||||
Ok(TaskAccess {
|
||||
workspace_id: tool.workspace_id.as_str().to_owned(),
|
||||
owner_kind,
|
||||
owner_id,
|
||||
authorization_scope: principal.authorization_scope(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves the addressed Tool of the principal's published catalog and repeats its authorization
|
||||
/// check. A foreign workspace, an unknown Tool and an insufficient security level are typed
|
||||
/// refusals without metadata.
|
||||
async fn resolve_authorized_tool(
|
||||
&self,
|
||||
principal: &TaskPrincipal,
|
||||
tool_name: &str,
|
||||
) -> Result<PublishedAgentTool, TaskApplicationError> {
|
||||
let catalog = self
|
||||
.catalog
|
||||
.get_catalog(principal.workspace_slug(), principal.agent_slug())
|
||||
.await
|
||||
.map_err(|_| TaskApplicationError::NotFound)?;
|
||||
let tool = catalog
|
||||
.tools
|
||||
.into_iter()
|
||||
.find(|tool| tool.tool_name == tool_name)
|
||||
.ok_or(TaskApplicationError::NotFound)?;
|
||||
if let TaskPrincipal::Admin { workspace_slug, .. } = principal
|
||||
&& tool.workspace_slug != *workspace_slug
|
||||
{
|
||||
return Err(TaskApplicationError::Denied);
|
||||
}
|
||||
if let TaskPrincipal::Agent { credential, .. } = principal
|
||||
&& !credential_allows_security_level(credential, tool.operation.security_level)
|
||||
{
|
||||
return Err(TaskApplicationError::Denied);
|
||||
}
|
||||
Ok(tool)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user