use anyhow::Result;
use async_trait::async_trait;
use greentic_types::{ReplyScope, TenantCtx};
use serde_json::Value;
use std::sync::Arc;
use super::dispatch_listener::SessionResumer;
use crate::engine::runtime::{IngressEnvelope, StateMachineRuntime};
use crate::runner::engine::{ParkedApproval, response_authenticates};
const PACK_HINT_MARKER: &str = "::pack=";
const FLOW_HINT_MARKER: &str = "::flow=";
const THREAD_HINT_MARKER: &str = "::thread=";
const REPLY_HINT_MARKER: &str = "::reply=";
pub(crate) const NONCE_HINT_MARKER: &str = "::n=";
const NONCE_HEX_LEN: usize = 32;
pub(crate) fn new_dispatch_nonce() -> String {
use rand::{RngExt, rng};
let mut bytes = [0u8; NONCE_HEX_LEN / 2];
rng().fill(&mut bytes);
hex::encode(bytes)
}
pub fn split_dispatch_nonce(correlation_id: &str) -> (&str, Option<&str>) {
match correlation_id.rsplit_once(NONCE_HINT_MARKER) {
Some((prefix, nonce))
if nonce.len() == NONCE_HEX_LEN
&& nonce
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) =>
{
(prefix, Some(nonce))
}
_ => (correlation_id, None),
}
}
pub struct RuntimeSessionResumer {
runtime: Arc<StateMachineRuntime>,
mode: AdmissionMode,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum AdmissionMode {
Lenient,
Strict,
}
impl RuntimeSessionResumer {
pub fn new(runtime: Arc<StateMachineRuntime>) -> Self {
Self {
runtime,
mode: AdmissionMode::Lenient,
}
}
pub fn strict(runtime: Arc<StateMachineRuntime>) -> Self {
Self {
runtime,
mode: AdmissionMode::Strict,
}
}
pub(crate) fn build_resume_envelope(
tenant: &TenantCtx,
correlation_id: &str,
output: Value,
) -> IngressEnvelope {
let (without_nonce, _nonce) = split_dispatch_nonce(correlation_id);
let (without_reply, reply_to) = split_marker(without_nonce, REPLY_HINT_MARKER);
let (without_thread, thread) = split_marker(&without_reply, THREAD_HINT_MARKER);
let (without_flow, flow_marker) = split_marker(&without_thread, FLOW_HINT_MARKER);
let (bare_hint, pack_id) = split_pack_suffix(&without_flow);
let parts: Vec<&str> = bare_hint.splitn(5, ':').collect();
let provider = parts.get(1).map(|segment| segment.to_string());
let channel = parts.get(2).map(|segment| segment.to_string());
let conversation = parts.get(3).map(|segment| segment.to_string());
let user = parts.get(4).map(|segment| segment.to_string());
let flow_id = flow_marker
.or_else(|| pack_id.clone())
.unwrap_or_else(|| "resume.flow".to_string());
IngressEnvelope {
tenant: tenant.tenant_id.to_string(),
env: Some(tenant.env.to_string()),
pack_id,
flow_id,
flow_type: None,
action: None,
session_hint: Some(bare_hint.clone()),
provider,
channel,
conversation: conversation.clone(),
user,
entry_node: None,
activity_id: None,
timestamp: None,
messaging_endpoint_id: None,
payload: output,
metadata: None,
reply_scope: conversation.map(|conversation| ReplyScope {
conversation,
thread,
reply_to,
correlation: None,
}),
}
}
}
#[async_trait]
impl SessionResumer for RuntimeSessionResumer {
async fn resume(&self, tenant: TenantCtx, correlation_id: &str, output: Value) -> Result<()> {
let nonced = split_dispatch_nonce(correlation_id).1.is_some();
let envelope = Self::build_resume_envelope(&tenant, correlation_id, output.clone());
let parked = match self.runtime.parked_approvals(&envelope).await {
Ok(parked) => parked,
Err(error) if !nonced => {
tracing::warn!(%error, %correlation_id, "could not read the parked flow before resuming; the gate re-checks the response itself");
None
}
Err(error) => return Err(error),
};
match admit_response_with(self.mode, correlation_id, &output, parked.as_deref()) {
Admission::Resume => {}
Admission::WrongGate => {
tracing::warn!(
%correlation_id,
"dropping approval response: it does not match the approval this conversation is parked on"
);
return Ok(());
}
Admission::BadToken => {
tracing::warn!(
%correlation_id,
"dropping approval response: its decision_token is missing or does not match the one the parked approval was issued"
);
return Ok(());
}
}
self.runtime.handle(envelope).await.map(|_| ())
}
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Admission {
Resume,
WrongGate,
BadToken,
}
#[cfg(test)]
pub(crate) fn admit_response(
correlation_id: &str,
response: &Value,
parked: Option<&[ParkedApproval]>,
) -> Admission {
admit_response_with(AdmissionMode::Lenient, correlation_id, response, parked)
}
pub(crate) fn admit_response_with(
mode: AdmissionMode,
correlation_id: &str,
response: &Value,
parked: Option<&[ParkedApproval]>,
) -> Admission {
let nonced = split_dispatch_nonce(correlation_id).1.is_some();
let strict = nonced && mode == AdmissionMode::Strict;
let Some(parked) = parked else {
return if strict {
Admission::WrongGate
} else {
Admission::Resume
};
};
let candidates: Vec<&ParkedApproval> = parked
.iter()
.filter(|park| {
if !nonced {
return true;
}
match park.correlation_id.as_deref() {
Some(recorded) => recorded == correlation_id,
None => !strict,
}
})
.collect();
if candidates.is_empty() {
return if nonced {
Admission::WrongGate
} else {
Admission::Resume
};
}
if candidates
.iter()
.any(|park| response_authenticates(response, park))
{
Admission::Resume
} else {
Admission::BadToken
}
}
fn split_pack_suffix(hint: &str) -> (String, Option<String>) {
split_marker(hint, PACK_HINT_MARKER)
}
fn split_marker(value: &str, marker: &str) -> (String, Option<String>) {
match value.rsplit_once(marker) {
Some((prefix, captured)) if !captured.is_empty() => {
(prefix.to_string(), Some(captured.to_string()))
}
_ => (value.to_string(), None),
}
}
#[cfg(test)]
mod tests {
use super::*;
use greentic_types::{EnvId, TenantId};
use serde_json::json;
use std::str::FromStr;
fn tenant_ctx() -> TenantCtx {
TenantCtx::new(
EnvId::from_str("local").unwrap(),
TenantId::from_str("demo").unwrap(),
)
}
#[test]
fn build_resume_envelope_sets_session_hint_to_correlation_id() {
let envelope = RuntimeSessionResumer::build_resume_envelope(
&tenant_ctx(),
"demo:provider:chan:conv:user",
json!({ "ok": true }),
);
assert_eq!(
envelope.session_hint.as_deref(),
Some("demo:provider:chan:conv:user")
);
assert_eq!(envelope.payload, json!({ "ok": true }));
assert_eq!(envelope.tenant, "demo");
assert_eq!(envelope.env.as_deref(), Some("local"));
}
#[test]
fn build_resume_envelope_parses_conversation_into_reply_scope() {
let envelope = RuntimeSessionResumer::build_resume_envelope(
&tenant_ctx(),
"demo:provider:chan:conv:user",
json!(null),
);
let scope = envelope.reply_scope.expect("reply scope from conversation");
assert_eq!(scope.conversation, "conv");
assert!(scope.thread.is_none());
assert!(scope.correlation.is_none());
assert_eq!(envelope.conversation.as_deref(), Some("conv"));
assert_eq!(envelope.provider.as_deref(), Some("provider"));
assert_eq!(envelope.channel.as_deref(), Some("chan"));
assert_eq!(envelope.user.as_deref(), Some("user"));
}
#[test]
fn build_resume_envelope_recovers_pack_id_from_suffix() {
let envelope = RuntimeSessionResumer::build_resume_envelope(
&tenant_ctx(),
"demo:provider:chan:conv:user::pack=greentic.demo",
json!(null),
);
assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
assert_eq!(
envelope.session_hint.as_deref(),
Some("demo:provider:chan:conv:user")
);
assert_eq!(envelope.conversation.as_deref(), Some("conv"));
}
#[test]
fn build_resume_envelope_recovers_pack_and_flow_for_routing() {
let envelope = RuntimeSessionResumer::build_resume_envelope(
&tenant_ctx(),
"demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow",
json!(null),
);
assert_eq!(envelope.flow_id, "wait.flow");
assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
assert_eq!(
envelope.session_hint.as_deref(),
Some("demo:provider:chan:conv:user")
);
assert_eq!(envelope.conversation.as_deref(), Some("conv"));
}
#[test]
fn build_resume_envelope_recovers_thread_and_reply_into_scope() {
let envelope = RuntimeSessionResumer::build_resume_envelope(
&tenant_ctx(),
"demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow::thread=topic-7::reply=msg-42",
json!(null),
);
assert_eq!(envelope.flow_id, "wait.flow");
assert_eq!(envelope.pack_id.as_deref(), Some("greentic.demo"));
assert_eq!(
envelope.session_hint.as_deref(),
Some("demo:provider:chan:conv:user")
);
let scope = envelope.reply_scope.expect("reply scope with thread/reply");
assert_eq!(scope.conversation, "conv");
assert_eq!(scope.thread.as_deref(), Some("topic-7"));
assert_eq!(scope.reply_to.as_deref(), Some("msg-42"));
}
#[test]
fn build_resume_envelope_recovers_thread_without_reply() {
let envelope = RuntimeSessionResumer::build_resume_envelope(
&tenant_ctx(),
"demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow::thread=topic-7",
json!(null),
);
let scope = envelope.reply_scope.expect("reply scope with thread");
assert_eq!(scope.thread.as_deref(), Some("topic-7"));
assert!(scope.reply_to.is_none());
assert_eq!(
envelope.session_hint.as_deref(),
Some("demo:provider:chan:conv:user")
);
}
#[test]
fn build_resume_envelope_without_markers_leaves_thread_and_reply_none() {
let envelope = RuntimeSessionResumer::build_resume_envelope(
&tenant_ctx(),
"demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow",
json!(null),
);
let scope = envelope.reply_scope.expect("reply scope from conversation");
assert!(scope.thread.is_none());
assert!(scope.reply_to.is_none());
}
#[test]
fn split_pack_suffix_handles_missing_and_empty_marker() {
assert_eq!(
split_pack_suffix("a:b:c:d:e"),
("a:b:c:d:e".to_string(), None)
);
assert_eq!(
split_pack_suffix("a:b:c:d:e::pack=p"),
("a:b:c:d:e".to_string(), Some("p".to_string()))
);
assert_eq!(
split_pack_suffix("a:b:c:d:e::pack="),
("a:b:c:d:e::pack=".to_string(), None)
);
}
const NONCE: &str = "0123456789abcdef0123456789abcdef";
#[test]
fn new_dispatch_nonce_is_32_lowercase_hex_and_fresh() {
let a = new_dispatch_nonce();
let b = new_dispatch_nonce();
assert_eq!(a.len(), 32);
assert!(
a.bytes()
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
);
assert_ne!(a, b, "two dispatches must not share a nonce");
let id = format!("h::pack=p::flow=f{NONCE_HINT_MARKER}{a}");
assert_eq!(
split_dispatch_nonce(&id),
("h::pack=p::flow=f", Some(a.as_str()))
);
}
#[test]
fn split_dispatch_nonce_leaves_ids_without_a_nonce_unchanged() {
let old = "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow";
assert_eq!(split_dispatch_nonce(old), (old, None));
let reply = "a:b:c:d:e::pack=p::flow=f::reply=x::n=not-hex";
assert_eq!(split_dispatch_nonce(reply), (reply, None));
let short = "h::pack=p::n=abc";
assert_eq!(split_dispatch_nonce(short), (short, None));
let upper = format!("h::pack=p::n={}", NONCE.to_uppercase());
assert_eq!(split_dispatch_nonce(&upper), (upper.as_str(), None));
}
#[test]
fn a_nonce_does_not_change_the_resume_key() {
let base = "demo:provider:chan:conv:user::pack=greentic.demo::flow=wait.flow::thread=topic-7::reply=msg-42";
let with_nonce = format!("{base}::n={NONCE}");
let plain = RuntimeSessionResumer::build_resume_envelope(&tenant_ctx(), base, json!(1));
let nonced =
RuntimeSessionResumer::build_resume_envelope(&tenant_ctx(), &with_nonce, json!(1));
assert_eq!(nonced.session_hint, plain.session_hint);
assert_eq!(
nonced.session_hint.as_deref(),
Some("demo:provider:chan:conv:user")
);
assert_eq!(nonced.pack_id, plain.pack_id);
assert_eq!(nonced.flow_id, "wait.flow");
let (scope, plain_scope) = (nonced.reply_scope.unwrap(), plain.reply_scope.unwrap());
assert_eq!(scope.thread.as_deref(), Some("topic-7"));
assert_eq!(
scope.reply_to.as_deref(),
Some("msg-42"),
"the nonce must not leak into reply_to"
);
assert_eq!(scope.scope_hash(), plain_scope.scope_hash());
}
#[test]
fn a_nonced_response_resumes_only_its_own_parked_approval() {
let mine = format!("h::pack=p::flow=f::n={NONCE}");
let other = format!("h::pack=p::flow=f::n={}", "f".repeat(32));
let untokened = |id: Option<&str>| ParkedApproval {
correlation_id: id.map(str::to_string),
token_fingerprint: None,
};
let r = json!({"ok": true, "output": {"decision": "approved"}});
assert_eq!(admit_response(&mine, &r, None), Admission::Resume);
assert_eq!(
admit_response(&mine, &r, Some(&[untokened(Some(&mine))])),
Admission::Resume
);
assert_eq!(
admit_response(&mine, &r, Some(&[untokened(Some(&other))])),
Admission::WrongGate
);
assert_eq!(admit_response(&mine, &r, Some(&[])), Admission::WrongGate);
assert_eq!(
admit_response(&mine, &r, Some(&[untokened(None)])),
Admission::Resume
);
}
fn tokened(id: &str, fingerprint: &str) -> ParkedApproval {
ParkedApproval {
correlation_id: Some(id.to_string()),
token_fingerprint: Some(fingerprint.to_string()),
}
}
fn response(token: Option<&str>) -> Value {
match token {
Some(token) => {
json!({"ok": true, "output": {"decision": "approved", "decision_token": token}})
}
None => json!({"ok": true, "output": {"decision": "approved"}}),
}
}
#[test]
fn a_tokened_park_resumes_only_on_the_right_token() {
use crate::runner::approval_token::issue;
let mine = format!("h::pack=p::flow=f::n={NONCE}");
let issued = issue();
let parks = [tokened(&mine, &issued.fingerprint)];
assert_eq!(
admit_response(&mine, &response(Some(&issued.token)), Some(&parks)),
Admission::Resume
);
assert_eq!(
admit_response(&mine, &response(Some(&issue().token)), Some(&parks)),
Admission::BadToken,
"a wrong token is refused"
);
assert_eq!(
admit_response(&mine, &response(None), Some(&parks)),
Admission::BadToken,
"a missing token is refused"
);
}
#[test]
fn dropping_the_nonce_does_not_skip_the_token_check() {
use crate::runner::approval_token::issue;
let issued = issue();
let parks = [tokened(
&format!("h::pack=p::flow=f::n={NONCE}"),
&issued.fingerprint,
)];
let guessed = "h::pack=p::flow=f";
assert_eq!(
admit_response(guessed, &response(None), Some(&parks)),
Admission::BadToken
);
assert_eq!(
admit_response(guessed, &response(Some(&issued.token)), Some(&parks)),
Admission::Resume
);
}
#[test]
fn strict_mode_never_resumes_a_nonced_response_with_nothing_parked() {
use crate::runner::approval_token::issue;
let mine = format!("h::pack=p::flow=f::n={NONCE}");
let issued = issue();
let r = response(Some(&issued.token));
assert_eq!(
admit_response_with(AdmissionMode::Strict, &mine, &r, None),
Admission::WrongGate,
"nothing parked: a fresh run would re-execute the flow and raise a second approval"
);
assert_eq!(
admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&[])),
Admission::WrongGate
);
let legacy = ParkedApproval {
correlation_id: None,
token_fingerprint: None,
};
assert_eq!(
admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&[legacy])),
Admission::WrongGate
);
let parks = [tokened(&mine, &issued.fingerprint)];
assert_eq!(
admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&parks)),
Admission::Resume
);
let other = format!("h::pack=p::flow=f::n={}", "f".repeat(32));
let parks = [tokened(&other, &issued.fingerprint)];
assert_eq!(
admit_response_with(AdmissionMode::Strict, &mine, &r, Some(&parks)),
Admission::WrongGate
);
}
#[test]
fn strict_mode_leaves_unnonced_ids_and_lenient_mode_unchanged() {
let r = json!({"ok": true});
assert_eq!(
admit_response_with(AdmissionMode::Strict, "h::pack=p::flow=f", &r, None),
Admission::Resume
);
let mine = format!("h::pack=p::flow=f::n={NONCE}");
assert_eq!(
admit_response_with(AdmissionMode::Lenient, &mine, &r, None),
Admission::Resume
);
}
}