use serde_json::{Value, json};
use crate::model::SessionId;
const ENVELOPE_KEY: &str = "kian";
const CONTROL_TYPE: &str = "control";
const INTERRUPT_ACTION: &str = "interrupt";
const CONFIRM_ACTION: &str = "confirm";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterruptIntent {
pub reason: Option<String>,
pub requested_by: Option<String>,
pub requested_at_ms: u64,
pub target_epoch: Option<u64>,
}
impl InterruptIntent {
#[must_use]
pub fn is_control_envelope(payload: &Value) -> bool {
Self::parse(payload).is_some()
}
#[must_use]
pub fn parse(payload: &Value) -> Option<Self> {
let obj = payload.as_object()?;
if obj.len() != 1 {
return None;
}
let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
|| inner.get("action").and_then(Value::as_str) != Some(INTERRUPT_ACTION)
{
return None;
}
Some(Self {
reason: inner
.get("reason")
.and_then(Value::as_str)
.map(str::to_owned),
requested_by: inner
.get("requested_by")
.and_then(Value::as_str)
.map(str::to_owned),
requested_at_ms: inner
.get("requested_at_ms")
.and_then(Value::as_u64)
.unwrap_or(0),
target_epoch: inner.get("target_epoch").and_then(Value::as_u64),
})
}
#[must_use]
pub fn envelope(&self) -> Value {
let mut inner = json!({
"type": CONTROL_TYPE,
"action": INTERRUPT_ACTION,
"requested_at_ms": self.requested_at_ms,
});
let map = inner.as_object_mut().expect("literal object");
match &self.reason {
Some(r) => map.insert("reason".into(), json!(r)),
None => map.insert("reason".into(), Value::Null),
};
match &self.requested_by {
Some(r) => map.insert("requested_by".into(), json!(r)),
None => map.insert("requested_by".into(), Value::Null),
};
map.insert(
"target_epoch".into(),
self.target_epoch.map_or(Value::Null, |e| json!(e)),
);
json!({ ENVELOPE_KEY: inner })
}
#[must_use]
pub fn event_payload(&self, stale: bool) -> Value {
let mut payload = json!({
"action": INTERRUPT_ACTION,
"requested_at_ms": self.requested_at_ms,
});
let map = payload.as_object_mut().expect("literal object");
match &self.reason {
Some(r) => map.insert("reason".into(), json!(r)),
None => map.insert("reason".into(), Value::Null),
};
match &self.requested_by {
Some(r) => map.insert("requested_by".into(), json!(r)),
None => map.insert("requested_by".into(), Value::Null),
};
map.insert(
"target_epoch".into(),
self.target_epoch.map_or(Value::Null, |e| json!(e)),
);
if stale {
map.insert("stale".into(), json!(true));
}
payload
}
#[must_use]
pub fn idempotency_key(session: &SessionId, target_epoch: Option<u64>) -> String {
match target_epoch {
Some(e) => format!("interrupt:{}:{}", session.0, e),
None => format!("interrupt:{}:null", session.0),
}
}
}
#[must_use]
pub fn is_reserved_control_shape(payload: &Value) -> bool {
let Some(obj) = payload.as_object() else {
return false;
};
if obj.len() != 1 {
return false;
}
let Some(inner) = obj.get(ENVELOPE_KEY).and_then(Value::as_object) else {
return false;
};
inner.get("type").and_then(Value::as_str) == Some(CONTROL_TYPE)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConfirmIntent {
pub call_id: String,
pub decision: ConfirmDecision,
pub reason: Option<String>,
pub requested_by: Option<String>,
pub answered_at_ms: u64,
pub expired: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfirmDecision {
Approve,
Reject,
}
impl ConfirmDecision {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Approve => "approve",
Self::Reject => "reject",
}
}
#[must_use]
pub fn parse(s: &str) -> Option<Self> {
match s {
"approve" => Some(Self::Approve),
"reject" => Some(Self::Reject),
_ => None,
}
}
}
impl ConfirmIntent {
#[must_use]
pub fn is_control_envelope(payload: &Value) -> bool {
Self::parse(payload).is_some()
}
#[must_use]
pub fn is_reserved_shape(payload: &Value) -> bool {
is_reserved_control_shape(payload)
}
#[must_use]
pub fn parse(payload: &Value) -> Option<Self> {
let obj = payload.as_object()?;
if obj.len() != 1 {
return None;
}
let inner = obj.get(ENVELOPE_KEY)?.as_object()?;
if inner.get("type").and_then(Value::as_str) != Some(CONTROL_TYPE)
|| inner.get("action").and_then(Value::as_str) != Some(CONFIRM_ACTION)
{
return None;
}
let call_id = inner
.get("call_id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())?
.to_owned();
let decision = inner
.get("decision")
.and_then(Value::as_str)
.and_then(ConfirmDecision::parse)?;
Some(Self {
call_id,
decision,
reason: inner
.get("reason")
.and_then(Value::as_str)
.map(str::to_owned),
requested_by: inner
.get("requested_by")
.and_then(Value::as_str)
.map(str::to_owned),
answered_at_ms: inner
.get("answered_at_ms")
.and_then(Value::as_u64)
.unwrap_or(0),
expired: inner.get("expired").and_then(Value::as_bool) == Some(true),
})
}
#[must_use]
pub fn from_event_payload(payload: &Value) -> Option<Self> {
let inner = payload.as_object()?;
if inner.get("action").and_then(Value::as_str) != Some(CONFIRM_ACTION) {
return None;
}
let call_id = inner
.get("call_id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())?
.to_owned();
let decision = inner
.get("decision")
.and_then(Value::as_str)
.and_then(ConfirmDecision::parse)?;
Some(Self {
call_id,
decision,
reason: inner
.get("reason")
.and_then(Value::as_str)
.map(str::to_owned),
requested_by: inner
.get("requested_by")
.and_then(Value::as_str)
.map(str::to_owned),
answered_at_ms: inner
.get("answered_at_ms")
.and_then(Value::as_u64)
.unwrap_or(0),
expired: inner.get("expired").and_then(Value::as_bool) == Some(true),
})
}
#[must_use]
pub fn envelope(&self) -> Value {
let mut inner = json!({
"type": CONTROL_TYPE,
"action": CONFIRM_ACTION,
"call_id": self.call_id,
"decision": self.decision.as_str(),
"reason": self.reason,
"requested_by": self.requested_by,
"answered_at_ms": self.answered_at_ms,
});
if self.expired {
inner["expired"] = json!(true);
}
json!({ ENVELOPE_KEY: inner })
}
#[must_use]
pub fn event_payload(&self) -> Value {
let mut payload = json!({
"action": CONFIRM_ACTION,
"call_id": self.call_id,
"decision": self.decision.as_str(),
"reason": self.reason,
"requested_by": self.requested_by,
"answered_at_ms": self.answered_at_ms,
});
if self.expired {
payload["expired"] = json!(true);
}
payload
}
#[must_use]
pub fn idempotency_key(session: &SessionId, call_id: &str) -> String {
format!("confirm:{}:{}", session.0, call_id)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use uuid::Uuid;
use super::{ConfirmDecision, ConfirmIntent, InterruptIntent};
use crate::model::SessionId;
fn intent() -> InterruptIntent {
InterruptIntent {
reason: Some("stop the deploy".into()),
requested_by: Some("replica-a".into()),
requested_at_ms: 1_762_000_000_000,
target_epoch: Some(3),
}
}
#[test]
fn envelope_round_trips_through_parse() {
let i = intent();
let envelope = i.envelope();
assert_eq!(
envelope,
json!({
"kian": {
"type": "control",
"action": "interrupt",
"reason": "stop the deploy",
"requested_by": "replica-a",
"requested_at_ms": 1_762_000_000_000_u64,
"target_epoch": 3
}
})
);
assert_eq!(InterruptIntent::parse(&envelope), Some(i));
assert!(InterruptIntent::is_control_envelope(&envelope));
}
#[test]
fn null_fields_round_trip() {
let i = InterruptIntent {
reason: None,
requested_by: None,
requested_at_ms: 7,
target_epoch: None,
};
assert_eq!(InterruptIntent::parse(&i.envelope()), Some(i));
}
#[test]
fn minimal_envelope_parses_with_defaults() {
let minimal = json!({"kian": {"type": "control", "action": "interrupt"}});
assert_eq!(
InterruptIntent::parse(&minimal),
Some(InterruptIntent {
reason: None,
requested_by: None,
requested_at_ms: 0,
target_epoch: None,
})
);
}
#[test]
fn only_the_exact_reserved_shape_is_an_envelope() {
for payload in [
json!({"kian": {"type": "control", "action": "interrupt"}, "extra": 1}),
json!({"kian": {"type": "user", "action": "interrupt"}}),
json!({"kian": {"type": "control", "action": "cancel"}}),
json!({"kian": "not an object"}),
json!({"synthetic": true, "content": "steer"}),
json!({"content": "x", "spill": "y"}),
json!("plain string"),
json!({"role": "user", "content": "hi"}),
] {
assert!(
!InterruptIntent::is_control_envelope(&payload),
"{payload} must be plain content"
);
}
}
#[test]
fn event_payload_shape_and_stale_marker() {
let live = intent().event_payload(false);
assert_eq!(
live,
json!({
"action": "interrupt",
"reason": "stop the deploy",
"requested_by": "replica-a",
"requested_at_ms": 1_762_000_000_000_u64,
"target_epoch": 3
})
);
assert!(live.get("stale").is_none());
let stale = intent().event_payload(true);
assert_eq!(stale.get("stale"), Some(&json!(true)));
let mut without = stale.clone();
without.as_object_mut().unwrap().remove("stale");
assert_eq!(without, live);
}
#[test]
fn idempotency_key_is_deterministic() {
let sid = SessionId(Uuid::nil());
assert_eq!(
InterruptIntent::idempotency_key(&sid, Some(3)),
format!("interrupt:{}:3", sid.0)
);
assert_eq!(
InterruptIntent::idempotency_key(&sid, None),
format!("interrupt:{}:null", sid.0)
);
}
#[test]
fn confirm_envelope_round_trips_and_reserved_shape_covers_both_actions() {
let i = ConfirmIntent {
call_id: "call-1".into(),
decision: ConfirmDecision::Approve,
reason: Some("looks right".into()),
requested_by: Some("alice".into()),
answered_at_ms: 1_762_000_000_000,
expired: false,
};
let envelope = i.envelope();
assert_eq!(
envelope,
json!({"kian": {"type": "control", "action": "confirm", "call_id": "call-1",
"decision": "approve", "reason": "looks right",
"requested_by": "alice", "answered_at_ms": 1_762_000_000_000_u64}})
);
assert_eq!(ConfirmIntent::parse(&envelope), Some(i));
assert!(ConfirmIntent::is_control_envelope(&envelope));
assert!(ConfirmIntent::is_reserved_shape(&envelope));
let expired = ConfirmIntent {
expired: true,
decision: ConfirmDecision::Reject,
reason: None,
requested_by: None,
answered_at_ms: 5,
call_id: "call-2".into(),
};
assert_eq!(
ConfirmIntent::parse(&expired.envelope()),
Some(expired.clone())
);
assert_eq!(expired.event_payload()["expired"], json!(true));
assert_eq!(expired.event_payload()["decision"], json!("reject"));
let interrupt = InterruptIntent {
reason: None,
requested_by: None,
requested_at_ms: 1,
target_epoch: None,
}
.envelope();
assert!(ConfirmIntent::is_reserved_shape(&interrupt));
assert!(!ConfirmIntent::is_control_envelope(&interrupt));
for plain in [
json!({"kian": {"type": "control", "action": "confirm"}}),
json!({"kian": {"type": "control", "action": "confirm", "call_id": "c",
"decision": "maybe"}}),
json!({"kian": {"type": "async_result", "job_id": "j"}}),
json!({"kian": {"type": "control", "action": "confirm"}, "extra": 1}),
json!({"kian": "string"}),
] {
assert!(!ConfirmIntent::is_control_envelope(&plain), "{plain}");
}
assert!(!ConfirmIntent::is_reserved_shape(
&json!({"kian": {"type": "async_result"}})
));
assert!(!ConfirmIntent::is_reserved_shape(&json!("plain")));
}
#[test]
fn confirm_idempotency_key_is_deterministic() {
let sid = SessionId(Uuid::nil());
assert_eq!(
ConfirmIntent::idempotency_key(&sid, "call-1"),
format!("confirm:{}:call-1", sid.0)
);
}
}