1use anyhow::Result;
6use async_nats::HeaderMap;
7use async_trait::async_trait;
8use greentic_types::{
9 DispatchError, DispatchMode, RuntimeDispatchRequest, RuntimeDispatchResponse, request_topic,
10 response_topic,
11};
12use serde_json::Value;
13
14type WatchdogMap = std::collections::HashMap<String, (u64, tokio::task::JoinHandle<()>)>;
24
25static WATCHDOGS: std::sync::LazyLock<parking_lot::Mutex<WatchdogMap>> =
26 std::sync::LazyLock::new(|| parking_lot::Mutex::new(std::collections::HashMap::new()));
27
28static WATCHDOG_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
29
30fn next_watchdog_generation() -> u64 {
31 WATCHDOG_GENERATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
32}
33
34#[cfg(test)]
37fn register_watchdog(correlation_id: String, generation: u64, handle: tokio::task::JoinHandle<()>) {
38 if let Some((_, previous)) = WATCHDOGS
39 .lock()
40 .insert(correlation_id, (generation, handle))
41 {
42 previous.abort();
43 }
44}
45
46fn deregister_watchdog(correlation_id: &str, generation: u64) {
48 let mut watchdogs = WATCHDOGS.lock();
49 if watchdogs
50 .get(correlation_id)
51 .is_some_and(|(current, _)| *current == generation)
52 {
53 watchdogs.remove(correlation_id);
54 }
55}
56
57fn arm_watchdog<F>(correlation_id: String, deadline_ms: u64, on_timeout: F) -> u64
62where
63 F: std::future::Future<Output = ()> + Send + 'static,
64{
65 let generation = next_watchdog_generation();
66 let key = correlation_id.clone();
67 let mut watchdogs = WATCHDOGS.lock();
72 let handle = tokio::spawn(async move {
73 tokio::time::sleep(tokio::time::Duration::from_millis(deadline_ms)).await;
74 deregister_watchdog(&key, generation);
75 on_timeout.await;
76 });
77 if let Some((_, previous)) = watchdogs.insert(correlation_id, (generation, handle)) {
78 previous.abort();
79 }
80 generation
81}
82
83fn disarm_watchdog(correlation_id: &str, generation: u64) {
85 let mut watchdogs = WATCHDOGS.lock();
86 if watchdogs
87 .get(correlation_id)
88 .is_some_and(|(current, _)| *current == generation)
89 && let Some((_, handle)) = watchdogs.remove(correlation_id)
90 {
91 handle.abort();
92 }
93}
94
95#[cfg(test)]
96pub(crate) fn register_watchdog_for_test(
97 correlation_id: &str,
98 handle: tokio::task::JoinHandle<()>,
99) -> u64 {
100 let generation = next_watchdog_generation();
101 register_watchdog(correlation_id.to_string(), generation, handle);
102 generation
103}
104
105#[cfg(test)]
106pub(crate) fn deregister_watchdog_for_test(correlation_id: &str, generation: u64) {
107 deregister_watchdog(correlation_id, generation);
108}
109
110#[cfg(test)]
111pub(crate) fn watchdog_pending(correlation_id: &str) -> bool {
112 WATCHDOGS.lock().contains_key(correlation_id)
113}
114
115pub fn cancel_watchdog(correlation_id: &str) -> bool {
118 match WATCHDOGS.lock().remove(correlation_id) {
119 Some((_, handle)) => {
120 handle.abort();
121 true
122 }
123 None => false,
124 }
125}
126
127pub struct RemoteDispatch {
129 pub tenant: String,
130 pub env: String,
131 pub runtime: String,
132 pub target: String,
133 pub operation: String,
134 pub mode: DispatchMode,
135 pub correlation_id: String,
137 pub input: Value,
138 pub deadline_ms: Option<u64>,
139 pub decision_token: Option<String>,
147}
148
149#[derive(Debug)]
151pub enum RemoteDispatchAction {
152 AwaitingResponse { correlation_id: String },
153 Dispatched,
154}
155
156fn new_dispatch_id() -> String {
158 use rand::RngExt as _;
159 let mut bytes = [0u8; 16];
160 rand::rng().fill(&mut bytes);
161 hex::encode(bytes)
162}
163
164pub struct BuiltRequest {
166 pub subject: String,
167 pub headers: HeaderMap,
168 pub body: Vec<u8>,
169 pub action: RemoteDispatchAction,
170}
171
172pub fn build_request(req: &RemoteDispatch) -> Result<BuiltRequest> {
175 let body_struct = RuntimeDispatchRequest {
176 target: req.target.clone(),
177 operation: req.operation.clone(),
178 mode: req.mode,
179 input: req.input.clone(),
180 deadline_ms: req.deadline_ms,
181 };
182 let body = match req.decision_token.as_deref() {
183 None => serde_json::to_vec(&body_struct)?,
184 Some(token) => {
185 let mut value = serde_json::to_value(&body_struct)?;
189 if let Value::Object(map) = &mut value {
190 map.insert(
191 "routing".to_string(),
192 serde_json::json!({ "decision_token": token }),
193 );
194 }
195 serde_json::to_vec(&value)?
196 }
197 };
198
199 let mut headers = HeaderMap::new();
200 headers.insert("Greentic-Correlation-Id", req.correlation_id.as_str());
201 headers.insert("Greentic-Tenant", req.tenant.as_str());
202 headers.insert("Greentic-Env", req.env.as_str());
203 headers.insert("Greentic-Idempotency-Key", req.correlation_id.as_str());
204 headers.insert("Greentic-Dispatch-Id", new_dispatch_id().as_str());
209
210 let action = match req.mode {
211 DispatchMode::Await => RemoteDispatchAction::AwaitingResponse {
212 correlation_id: req.correlation_id.clone(),
213 },
214 DispatchMode::FireAndForget => RemoteDispatchAction::Dispatched,
215 };
216
217 Ok(BuiltRequest {
218 subject: request_topic(&req.runtime),
219 headers,
220 body,
221 action,
222 })
223}
224
225pub fn build_timeout_response_message(
242 runtime: &str,
243 correlation_id: &str,
244 tenant: &str,
245 env: &str,
246 deadline_ms: u64,
247) -> (String, HeaderMap, Vec<u8>) {
248 build_timeout_response_message_with_token(
249 runtime,
250 correlation_id,
251 tenant,
252 env,
253 deadline_ms,
254 None,
255 )
256}
257
258pub fn build_timeout_response_message_with_token(
263 runtime: &str,
264 correlation_id: &str,
265 tenant: &str,
266 env: &str,
267 deadline_ms: u64,
268 decision_token: Option<&str>,
269) -> (String, HeaderMap, Vec<u8>) {
270 let subject = response_topic(runtime);
271
272 let mut headers = HeaderMap::new();
273 headers.insert("Greentic-Correlation-Id", correlation_id);
274 headers.insert("Greentic-Tenant", tenant);
275 headers.insert("Greentic-Env", env);
276
277 let output = match decision_token {
278 Some(token) => serde_json::json!({ "decision_token": token }),
279 None => Value::Null,
280 };
281 let response = RuntimeDispatchResponse {
282 ok: false,
283 output,
284 events: vec![],
285 error: Some(DispatchError {
286 code: "timeout".into(),
287 message: format!("no response within {deadline_ms}ms"),
288 }),
289 };
290 let body = serde_json::to_vec(&response).unwrap_or_default();
292
293 (subject, headers, body)
294}
295
296#[async_trait]
300pub trait RemoteDispatchHandler: Send + Sync {
301 async fn dispatch(&self, request: RemoteDispatch) -> Result<RemoteDispatchAction>;
302}
303
304pub struct NatsDispatcher {
306 client: async_nats::Client,
307}
308
309impl NatsDispatcher {
310 pub fn new(client: async_nats::Client) -> Self {
311 Self { client }
312 }
313}
314
315fn pre_effect_failure(error: impl Into<anyhow::Error>) -> anyhow::Error {
318 crate::runner::engine::pre_effect(error)
319}
320
321#[async_trait]
322impl RemoteDispatchHandler for NatsDispatcher {
323 async fn dispatch(&self, request: RemoteDispatch) -> Result<RemoteDispatchAction> {
324 let maybe_timeout = match (request.mode, request.deadline_ms) {
327 (DispatchMode::Await, Some(deadline_ms)) => Some((
328 deadline_ms,
329 request.runtime.clone(),
330 request.correlation_id.clone(),
331 request.tenant.clone(),
332 request.env.clone(),
333 request.decision_token.clone(),
334 )),
335 _ => None,
336 };
337
338 let built = build_request(&request).map_err(pre_effect_failure)?;
342
343 let armed = maybe_timeout.map(
348 |(deadline_ms, runtime, correlation_id, tenant, env, decision_token)| {
349 let timeout_client = self.client.clone();
350 let watchdog_key = correlation_id.clone();
351 let generation = arm_watchdog(watchdog_key.clone(), deadline_ms, async move {
352 let (subject, headers, body) = build_timeout_response_message_with_token(
353 &runtime,
354 &correlation_id,
355 &tenant,
356 &env,
357 deadline_ms,
358 decision_token.as_deref(),
359 );
360 if let Err(publish_error) = timeout_client
361 .publish_with_headers(subject, headers, body.into())
362 .await
363 {
364 tracing::warn!(
365 %publish_error,
366 correlation_id = %crate::log_safe::log_safe(&correlation_id),
367 deadline_ms,
368 "failed to publish timeout response for awaited dispatch"
369 );
370 }
371 });
372 (watchdog_key, generation)
373 },
374 );
375
376 if let Err(error) = self
377 .client
378 .publish_with_headers(built.subject, built.headers, built.body.into())
379 .await
380 {
381 if let Some((key, generation)) = armed {
383 disarm_watchdog(&key, generation);
384 }
385 return Err(pre_effect_failure(error));
386 }
387
388 Ok(built.action)
389 }
390}
391
392#[cfg(test)]
393mod tests {
394 use super::*;
395 use greentic_types::{DispatchMode, RuntimeDispatchRequest, RuntimeDispatchResponse};
396 use serde_json::json;
397
398 fn sample(mode: DispatchMode) -> RemoteDispatch {
399 RemoteDispatch {
400 tenant: "t1".into(),
401 env: "default".into(),
402 runtime: "sorla".into(),
403 target: "dep-1".into(),
404 operation: "create".into(),
405 mode,
406 correlation_id: "t1:web:chan:conv:user::pack=p".into(), input: json!({"a": 1}),
408 deadline_ms: Some(1000),
409 decision_token: None,
410 }
411 }
412
413 #[test]
414 fn pre_effect_failure_marks_without_changing_the_message() {
415 let err = pre_effect_failure(anyhow::anyhow!("publish refused"));
416 assert!(crate::runner::engine::is_pre_effect_error(&err));
417 assert_eq!(err.to_string(), "publish refused");
418 }
419
420 async fn fake_nats_server() -> String {
422 use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
423 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
424 let addr = listener.local_addr().unwrap();
425 tokio::spawn(async move {
426 let Ok((stream, _)) = listener.accept().await else {
427 return;
428 };
429 let (read, mut write) = stream.into_split();
430 let info = r#"INFO {"server_id":"fake","server_name":"fake","version":"2.10.0","proto":1,"max_payload":1024,"headers":true,"host":"127.0.0.1","port":0}"#;
431 if write
432 .write_all(format!("{info}\r\n").as_bytes())
433 .await
434 .is_err()
435 {
436 return;
437 }
438 let mut lines = BufReader::new(read).lines();
439 while let Ok(Some(line)) = lines.next_line().await {
440 if line.starts_with("PING") && write.write_all(b"PONG\r\n").await.is_err() {
441 return;
442 }
443 }
444 });
445 format!("nats://{addr}")
446 }
447
448 #[tokio::test]
451 async fn a_refused_publish_is_pre_effect_and_disarms_the_watchdog() {
452 let url = fake_nats_server().await;
453 let client = async_nats::connect(url).await.expect("fake server connect");
454 let dispatcher = NatsDispatcher::new(client);
455 let mut request = sample(DispatchMode::Await);
456 request.correlation_id = "corr-refused-publish".into();
457 request.runtime = "bad runtime".into();
460 let err = dispatcher
461 .dispatch(request)
462 .await
463 .expect_err("a publish to an invalid subject is refused");
464 assert!(crate::runner::engine::is_pre_effect_error(&err), "{err:#}");
465 assert!(
466 !watchdog_pending("corr-refused-publish"),
467 "the watchdog armed before the publish is disarmed"
468 );
469 }
470
471 #[tokio::test]
472 async fn an_expiring_watchdog_never_removes_a_newer_one() {
473 let old =
474 register_watchdog_for_test("corr-gen", tokio::spawn(std::future::pending::<()>()));
475 let newer =
476 register_watchdog_for_test("corr-gen", tokio::spawn(std::future::pending::<()>()));
477 assert_ne!(old, newer);
478 deregister_watchdog_for_test("corr-gen", old);
479 assert!(watchdog_pending("corr-gen"), "stale generation is a no-op");
480 deregister_watchdog_for_test("corr-gen", newer);
481 assert!(!watchdog_pending("corr-gen"));
482 }
483
484 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
485 async fn a_watchdog_that_expires_at_once_leaves_no_entry_behind() {
486 for i in 0..200 {
487 arm_watchdog(format!("corr-instant-{i}"), 0, async {});
488 }
489 tokio::time::sleep(std::time::Duration::from_millis(200)).await;
490 for i in 0..200 {
491 assert!(
492 !watchdog_pending(&format!("corr-instant-{i}")),
493 "a finished watchdog must deregister itself (iteration {i})"
494 );
495 }
496 }
497
498 #[tokio::test]
499 async fn a_response_admitted_right_after_arming_prevents_the_timeout() {
500 let fired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
501 let flag = std::sync::Arc::clone(&fired);
502 arm_watchdog("corr-early".to_string(), 30, async move {
504 flag.store(true, std::sync::atomic::Ordering::SeqCst);
505 });
506 assert!(
507 cancel_watchdog("corr-early"),
508 "cancel must find the armed watchdog"
509 );
510 tokio::time::sleep(std::time::Duration::from_millis(80)).await;
511 assert!(!fired.load(std::sync::atomic::Ordering::SeqCst));
512 }
513
514 #[tokio::test]
515 async fn a_failed_publish_disarms_only_its_own_watchdog() {
516 let fired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
517 let flag = std::sync::Arc::clone(&fired);
518 let old = arm_watchdog("corr-disarm".to_string(), 30, async move {
519 flag.store(true, std::sync::atomic::Ordering::SeqCst);
520 });
521 let newer = arm_watchdog("corr-disarm".to_string(), 10_000, async {});
522 disarm_watchdog("corr-disarm", old);
523 assert!(
524 watchdog_pending("corr-disarm"),
525 "stale generation is a no-op"
526 );
527 disarm_watchdog("corr-disarm", newer);
528 assert!(!watchdog_pending("corr-disarm"));
529 tokio::time::sleep(std::time::Duration::from_millis(80)).await;
530 assert!(!fired.load(std::sync::atomic::Ordering::SeqCst));
531 }
532
533 #[tokio::test]
534 async fn a_response_cancels_the_pending_watchdog() {
535 let fired = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
536 let flag = std::sync::Arc::clone(&fired);
537 let handle = tokio::spawn(async move {
538 tokio::time::sleep(std::time::Duration::from_millis(50)).await;
539 flag.store(true, std::sync::atomic::Ordering::SeqCst);
540 });
541 register_watchdog_for_test("corr-cancel", handle);
542 assert!(cancel_watchdog("corr-cancel"));
543 assert!(!cancel_watchdog("corr-cancel"), "second cancel is a no-op");
544 tokio::time::sleep(std::time::Duration::from_millis(120)).await;
545 assert!(
546 !fired.load(std::sync::atomic::Ordering::SeqCst),
547 "cancelled watchdog must never fire"
548 );
549 }
550
551 #[test]
552 fn each_publish_gets_its_own_dispatch_id_but_the_same_correlation() {
553 let first = build_request(&sample(DispatchMode::Await)).unwrap();
554 let second = build_request(&sample(DispatchMode::Await)).unwrap();
555 let id = |built: &BuiltRequest| {
556 built
557 .headers
558 .get("Greentic-Dispatch-Id")
559 .map(|v| v.as_str().to_string())
560 };
561 let (a, b) = (id(&first), id(&second));
562 assert!(a.is_some() && b.is_some());
563 assert_ne!(a, b, "two turns must not share a dispatch id");
564 let key = |built: &BuiltRequest| {
565 built
566 .headers
567 .get("Greentic-Idempotency-Key")
568 .map(|v| v.as_str().to_string())
569 };
570 assert_eq!(key(&first), key(&second), "the session hint is unchanged");
571 }
572
573 #[test]
574 fn a_request_without_a_token_has_no_routing_block() {
575 let built = build_request(&sample(DispatchMode::Await)).unwrap();
576 let body: Value = serde_json::from_slice(&built.body).unwrap();
577 assert!(body.get("routing").is_none());
578 }
579
580 #[test]
581 fn an_approval_token_rides_at_routing_decision_token() {
582 let mut dispatch = sample(DispatchMode::Await);
583 dispatch.runtime = "approval".into();
584 dispatch.decision_token = Some("tok-abc".into());
585 let built = build_request(&dispatch).unwrap();
586 let body: Value = serde_json::from_slice(&built.body).unwrap();
587 assert_eq!(body["routing"]["decision_token"], "tok-abc");
588 let decoded: RuntimeDispatchRequest = serde_json::from_slice(&built.body).unwrap();
590 assert_eq!(decoded.target, "dep-1");
591 assert_eq!(decoded.input, json!({"a": 1}));
592 }
593
594 #[test]
595 fn the_watchdog_timeout_carries_the_token_at_output() {
596 let (_s, _h, body) = build_timeout_response_message_with_token(
597 "approval",
598 "corr-1",
599 "t1",
600 "default",
601 200,
602 Some("tok-abc"),
603 );
604 let response: RuntimeDispatchResponse = serde_json::from_slice(&body).unwrap();
605 assert!(!response.ok);
606 assert_eq!(response.output["decision_token"], "tok-abc");
607 assert_eq!(response.error.expect("error").code, "timeout");
608 }
609
610 #[test]
611 fn build_request_targets_request_topic_with_headers_and_body() {
612 let built = build_request(&sample(DispatchMode::Await)).unwrap();
613 assert_eq!(built.subject, "greentic.sorla.request.v1");
614 assert_eq!(
615 built
616 .headers
617 .get("Greentic-Correlation-Id")
618 .map(|v| v.as_str()),
619 Some("t1:web:chan:conv:user::pack=p")
620 );
621 assert_eq!(
622 built.headers.get("Greentic-Tenant").map(|v| v.as_str()),
623 Some("t1")
624 );
625 let body: RuntimeDispatchRequest = serde_json::from_slice(&built.body).unwrap();
626 assert_eq!(body.operation, "create");
627 assert_eq!(body.mode, DispatchMode::Await);
628 assert!(matches!(
629 built.action,
630 RemoteDispatchAction::AwaitingResponse { .. }
631 ));
632 }
633
634 #[test]
635 fn fire_and_forget_action_is_dispatched() {
636 let built = build_request(&sample(DispatchMode::FireAndForget)).unwrap();
637 assert!(matches!(built.action, RemoteDispatchAction::Dispatched));
638 }
639
640 #[test]
641 fn build_request_targets_telco_x_request_topic() {
642 let mut dispatch = sample(DispatchMode::Await);
646 dispatch.runtime = "telco-x".into();
647 let built = build_request(&dispatch).unwrap();
648 assert_eq!(built.subject, "greentic.telco-x.request.v1");
649 }
650
651 #[test]
652 fn build_timeout_response_message_telco_x_response_topic() {
653 let (subject, _headers, _body) =
654 build_timeout_response_message("telco-x", "corr-1", "t1", "default", 500);
655 assert_eq!(subject, "greentic.telco-x.response.v1");
656 }
657
658 #[test]
659 fn build_timeout_response_message_uses_response_topic() {
660 let (subject, _headers, _body) =
661 build_timeout_response_message("sorla", "corr-1", "t1", "default", 500);
662 assert_eq!(subject, "greentic.sorla.response.v1");
663 }
664
665 #[test]
666 fn build_timeout_response_message_echoes_correlation_header() {
667 let (_subject, headers, _body) =
668 build_timeout_response_message("sorla", "my-corr-id", "t1", "default", 1000);
669 assert_eq!(
670 headers.get("Greentic-Correlation-Id").map(|v| v.as_str()),
671 Some("my-corr-id")
672 );
673 }
674
675 #[test]
676 fn build_timeout_response_message_body_deserializes_to_timeout_error() {
677 let (_subject, _headers, body) =
678 build_timeout_response_message("sorla", "corr-1", "t1", "default", 200);
679 let response: RuntimeDispatchResponse = serde_json::from_slice(&body).unwrap();
680 assert!(!response.ok, "ok must be false");
681 assert_eq!(response.output, serde_json::Value::Null);
682 let error = response.error.expect("error must be present");
683 assert_eq!(error.code, "timeout");
684 assert!(
685 error.message.contains("200ms"),
686 "message must mention deadline: {:?}",
687 error.message
688 );
689 }
690}