feat: complete Epic 1 production foundation

This commit is contained in:
bsodfather committed 2026-08-25 01:24:11 +03:00
1 parent 767428436d
commit 182bde8ac0
298 files changed
+35711 -5291

No files matched your search

+144 -18
View File
@@ -1,4 +1,7 @@
use std::time::{Duration, Instant};
use std::{
collections::BTreeMap,
time::{Duration, Instant},
};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use crank_core::{
@@ -38,7 +41,7 @@ pub fn prepare_idempotency(
return Ok(None);
};
let key = key_from_policy(policy, input, prepared_request);
let key = key_from_policy(policy, input);
let Some(key) = key else {
if policy.mode == IdempotencyMode::Required {
return Err(RuntimeError::InvalidPreparedRequest {
@@ -54,10 +57,13 @@ pub fn prepare_idempotency(
.as_deref()
.filter(|value| !value.is_empty())
{
remove_header_case_insensitive(&mut prepared_request.headers, header_name);
prepared_request
.headers
.entry(header_name.to_owned())
.or_insert_with(|| key.clone());
.insert(header_name.to_owned(), key.clone());
prepared_request
.trusted_header_names
.insert(header_name.to_ascii_lowercase());
}
Ok(Some(key))
@@ -186,6 +192,19 @@ pub(crate) async fn mark_outcome_unknown(
}
}
pub(crate) async fn release(
store: &dyn CoordinationStateStore,
operation: &RuntimeOperation,
reservation: &IdempotencyReservation,
) -> Result<(), RuntimeError> {
store
.delete_value(CacheScope::Coordination, &reservation.key)
.await
.map_err(|_| RuntimeError::IdempotencyStoreUnavailable {
operation_id: operation.operation_id.as_str().to_owned(),
})
}
async fn resolve_existing(
store: &dyn CoordinationStateStore,
operation: &RuntimeOperation,
@@ -315,20 +334,7 @@ fn in_progress_value(fingerprint: &str) -> CoordinationStateValue {
}
}
fn key_from_policy(
policy: &IdempotencyPolicy,
input: &Value,
prepared_request: &PreparedRequest,
) -> Option<String> {
if let Some(header_name) = policy
.header_name
.as_deref()
.filter(|value| !value.is_empty())
&& let Some(value) = prepared_request.headers.get(header_name)
{
return Some(value.clone());
}
fn key_from_policy(policy: &IdempotencyPolicy, input: &Value) -> Option<String> {
let field_name = policy.input_field.as_deref()?.trim();
if field_name.is_empty() {
return None;
@@ -340,3 +346,123 @@ fn key_from_policy(
_ => None,
})
}
pub(crate) fn verified_retry_key(
operation: &RuntimeOperation,
idempotency_key: Option<&str>,
) -> bool {
let Some(policy) = policy(operation) else {
return false;
};
idempotency_key.is_some()
&& policy
.input_field
.as_deref()
.is_some_and(|field| !field.trim().is_empty())
}
fn remove_header_case_insensitive(headers: &mut BTreeMap<String, String>, header_name: &str) {
let Some(existing) = headers
.keys()
.find(|candidate| candidate.eq_ignore_ascii_case(header_name))
.cloned()
else {
return;
};
headers.remove(&existing);
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crank_core::{
ExecutionConfig, HttpMethod, IdempotencyMode, IdempotencyPolicy, OperationId, Protocol,
RestTarget, Target, ToolDescription,
};
use crank_mapping::MappingSet;
use crank_schema::{Schema, SchemaKind};
use serde_json::json;
use crate::{PreparedRequest, RuntimeOperation};
#[test]
fn idempotency_header_is_derived_from_input_not_user_mapped_header() {
let operation = RuntimeOperation {
operation_id: OperationId::new("op_idempotent"),
operation_version: 1,
tool_name: "idempotent_write".to_owned(),
protocol: Protocol::Rest,
target: Target::Rest(RestTarget {
base_url: "https://api.example.invalid".to_owned(),
method: HttpMethod::Post,
path_template: "/orders".to_owned(),
static_headers: BTreeMap::new(),
}),
input_schema: Schema {
kind: SchemaKind::Object,
description: None,
required: true,
nullable: false,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
output_schema: Schema {
kind: SchemaKind::Object,
description: None,
required: true,
nullable: false,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
input_mapping: MappingSet { rules: Vec::new() },
output_mapping: MappingSet { rules: Vec::new() },
execution_config: ExecutionConfig {
timeout_ms: 1_000,
retry_policy: None,
response_cache: None,
idempotency: Some(IdempotencyPolicy {
mode: IdempotencyMode::Required,
ttl_ms: 60_000,
input_field: Some("request_id".to_owned()),
header_name: Some("Idempotency-Key".to_owned()),
}),
safety: None,
approval_policy: None,
auth_profile_ref: None,
headers: BTreeMap::new(),
},
tool_description: ToolDescription {
title: "Idempotent write".to_owned(),
description: "Test operation".to_owned(),
tags: Vec::new(),
examples: Vec::new(),
},
};
let mut prepared = PreparedRequest {
headers: BTreeMap::from([("idempotency-key".to_owned(), "attacker".to_owned())]),
..PreparedRequest::default()
};
let key = super::prepare_idempotency(
&operation,
&json!({"request_id": "trusted-key"}),
&mut prepared,
)
.unwrap();
assert_eq!(key.as_deref(), Some("trusted-key"));
assert_eq!(
prepared.headers.get("Idempotency-Key").map(String::as_str),
Some("trusted-key")
);
assert!(!prepared.headers.contains_key("idempotency-key"));
assert!(prepared.trusted_header_names.contains("idempotency-key"));
}
}