1use std::collections::BTreeMap;
5use std::ops::{Deref, DerefMut};
6use std::sync::{Arc, Mutex};
7
8use super::{AsyncEngineContext, AsyncEngineContextProvider, Data};
9use crate::engine::{AsyncEngineController, EngineContextGuard};
10use async_trait::async_trait;
11
12use super::registry::Registry;
13
14pub struct Context<T: Data> {
15 current: T,
16 controller: Arc<Controller>,
17 registry: Registry,
18 stages: Vec<String>,
19 metadata: BTreeMap<String, String>,
20}
21
22impl<T: Send + Sync + 'static> Context<T> {
23 pub fn new(current: T) -> Self {
25 Context {
26 current,
27 controller: Arc::new(Controller::default()),
28 registry: Registry::new(),
29 stages: Vec::new(),
30 metadata: BTreeMap::new(),
31 }
32 }
33
34 pub fn rejoin<U: Send + Sync + 'static>(current: T, context: Context<U>) -> Self {
35 Context {
36 current,
37 controller: context.controller,
38 registry: context.registry,
39 stages: context.stages,
40 metadata: context.metadata,
41 }
42 }
43
44 pub fn with_controller(current: T, controller: Controller) -> Self {
45 Context {
46 current,
47 controller: Arc::new(controller),
48 registry: Registry::new(),
49 stages: Vec::new(),
50 metadata: BTreeMap::new(),
51 }
52 }
53
54 pub fn with_id_and_metadata(
55 current: T,
56 id: String,
57 metadata: BTreeMap<String, String>,
58 ) -> Self {
59 Context {
60 current,
61 controller: Arc::new(Controller::new(id)),
62 registry: Registry::new(),
63 stages: Vec::new(),
64 metadata,
65 }
66 }
67
68 pub fn id(&self) -> &str {
70 self.controller.id()
71 }
72
73 pub fn content(&self) -> &T {
75 &self.current
76 }
77
78 pub fn controller(&self) -> &Controller {
79 &self.controller
80 }
81
82 pub fn metadata(&self) -> &BTreeMap<String, String> {
83 &self.metadata
84 }
85
86 pub fn metadata_mut(&mut self) -> &mut BTreeMap<String, String> {
87 &mut self.metadata
88 }
89
90 pub fn set_metadata(&mut self, metadata: BTreeMap<String, String>) {
91 self.metadata = metadata;
92 }
93
94 pub fn insert_metadata<K: Into<String>, V: Into<String>>(&mut self, key: K, value: V) {
95 self.metadata.insert(key.into(), value.into());
96 }
97
98 pub fn insert<K: ToString, U: Send + Sync + 'static>(&mut self, key: K, value: U) {
100 self.registry.insert_shared(key, value);
101 }
102
103 pub fn insert_arc<K: ToString, U: Send + Sync + 'static>(&mut self, key: K, value: Arc<U>) {
105 self.registry.insert_arc(key, value);
106 }
107
108 pub fn insert_unique<K: ToString, U: Send + Sync + 'static>(&mut self, key: K, value: U) {
110 self.registry.insert_unique(key, value);
111 }
112
113 pub fn get<V: Send + Sync + 'static>(&self, key: &str) -> Result<Arc<V>, String> {
115 self.registry.get_shared(key)
116 }
117
118 pub fn get_optional<V: Send + Sync + 'static>(
120 &self,
121 key: &str,
122 ) -> Result<Option<Arc<V>>, String> {
123 self.registry.get_shared_optional(key)
124 }
125
126 pub fn clone_unique<V: Clone + Send + Sync + 'static>(&self, key: &str) -> Result<V, String> {
128 self.registry.clone_unique(key)
129 }
130
131 pub fn take_unique<V: Send + Sync + 'static>(&mut self, key: &str) -> Result<V, String> {
133 self.registry.take_unique(key)
134 }
135
136 pub fn transfer<U: Send + Sync + 'static>(self, new_current: U) -> (T, Context<U>) {
139 (
140 self.current,
141 Context {
142 current: new_current,
143 controller: self.controller,
144 registry: self.registry,
145 stages: self.stages,
146 metadata: self.metadata,
147 },
148 )
149 }
150
151 pub fn into_parts(self) -> (T, Context<()>) {
153 self.transfer(())
154 }
155
156 pub fn stages(&self) -> &Vec<String> {
157 &self.stages
158 }
159
160 pub fn add_stage(&mut self, stage: &str) {
161 self.stages.push(stage.to_string());
162 }
163
164 pub fn map<U: Send + Sync + 'static, F>(self, f: F) -> Context<U>
166 where
167 F: FnOnce(T) -> U,
168 {
169 let (current, temp_context) = self.transfer(());
171
172 let new_current = f(current);
174
175 temp_context.transfer(new_current).1
177 }
178
179 pub fn try_map<U, F, E>(self, f: F) -> Result<Context<U>, E>
180 where
181 F: FnOnce(T) -> Result<U, E>,
182 U: Send + Sync + 'static,
183 {
184 let (current, temp_context) = self.transfer(());
186
187 let new_current = f(current)?;
189
190 Ok(temp_context.transfer(new_current).1)
192 }
193}
194
195impl<T: Data> std::fmt::Debug for Context<T> {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 f.debug_struct("Context")
198 .field("id", &self.controller.id())
199 .finish()
200 }
201}
202
203impl<T: Data> Deref for Context<T> {
205 type Target = T;
206
207 fn deref(&self) -> &Self::Target {
208 &self.current
209 }
210}
211
212impl<T: Data> DerefMut for Context<T> {
214 fn deref_mut(&mut self) -> &mut Self::Target {
215 &mut self.current
216 }
217}
218
219impl<T> From<T> for Context<T>
221where
222 T: Send + Sync + 'static,
223{
224 fn from(current: T) -> Self {
225 Context::new(current)
226 }
227}
228
229pub trait IntoContext<U: Data> {
231 fn into_context(self) -> Context<U>;
232}
233
234impl<T, U> IntoContext<U> for Context<T>
236where
237 T: Send + Sync + 'static + Into<U>,
238 U: Send + Sync + 'static,
239{
240 fn into_context(self) -> Context<U> {
241 self.map(|current| current.into())
242 }
243}
244
245impl<T: Data> AsyncEngineContextProvider for Context<T> {
246 fn context(&self) -> Arc<dyn AsyncEngineContext> {
247 self.controller.clone()
248 }
249}
250
251#[derive(Debug, Clone)]
252pub struct StreamContext {
253 controller: Arc<Controller>,
254 registry: Arc<Registry>,
255 stages: Vec<String>,
256 metadata: BTreeMap<String, String>,
257}
258
259impl StreamContext {
260 fn new(
261 controller: Arc<Controller>,
262 registry: Registry,
263 metadata: BTreeMap<String, String>,
264 ) -> Self {
265 StreamContext {
266 controller,
267 registry: Arc::new(registry),
268 stages: Vec::new(),
269 metadata,
270 }
271 }
272
273 pub fn get<V: Send + Sync + 'static>(&self, key: &str) -> Result<Arc<V>, String> {
275 self.registry.get_shared(key)
276 }
277
278 pub fn clone_unique<V: Clone + Send + Sync + 'static>(&self, key: &str) -> Result<V, String> {
280 self.registry.clone_unique(key)
281 }
282
283 pub fn registry(&self) -> Arc<Registry> {
284 self.registry.clone()
285 }
286
287 pub fn stages(&self) -> &Vec<String> {
288 &self.stages
289 }
290
291 pub fn add_stage(&mut self, stage: &str) {
292 self.stages.push(stage.to_string());
293 }
294
295 pub fn metadata(&self) -> &BTreeMap<String, String> {
296 &self.metadata
297 }
298}
299
300#[async_trait]
301impl AsyncEngineContext for StreamContext {
302 fn id(&self) -> &str {
303 self.controller.id()
304 }
305
306 fn stop(&self) {
307 self.controller.stop();
308 }
309
310 fn kill(&self) {
311 self.controller.kill();
312 }
313
314 fn stop_generating(&self) {
315 self.controller.stop_generating();
316 }
317
318 fn is_stopped(&self) -> bool {
319 self.controller.is_stopped()
320 }
321
322 fn is_killed(&self) -> bool {
323 self.controller.is_killed()
324 }
325
326 async fn stopped(&self) {
327 self.controller.stopped().await
328 }
329
330 async fn killed(&self) {
331 self.controller.killed().await
332 }
333
334 fn link_child(&self, child: Arc<dyn AsyncEngineContext>) {
335 self.controller.link_child(child);
336 }
337
338 fn retain(&self, guard: EngineContextGuard) {
339 self.controller.retain(guard);
340 }
341}
342
343impl AsyncEngineContextProvider for StreamContext {
344 fn context(&self) -> Arc<dyn AsyncEngineContext> {
345 self.controller.clone()
346 }
347}
348
349impl<T: Send + Sync + 'static> From<Context<T>> for StreamContext {
350 fn from(value: Context<T>) -> Self {
351 StreamContext::new(value.controller, value.registry, value.metadata)
352 }
353}
354
355use tokio::sync::watch::{Receiver, Sender, channel};
358
359#[derive(Debug, Eq, PartialEq)]
360enum State {
361 Live,
362 Stopped,
363 Killed,
364}
365
366#[derive(Debug)]
368pub struct Controller {
369 id: String,
370 tx: Sender<State>,
371 rx: Receiver<State>,
372 child_context: Mutex<Vec<Arc<dyn AsyncEngineContext>>>,
373 retained: Mutex<Vec<RetainedGuard>>,
374}
375
376struct RetainedGuard {
377 _guard: EngineContextGuard,
378}
379
380impl std::fmt::Debug for RetainedGuard {
381 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382 f.write_str("RetainedGuard")
383 }
384}
385
386impl Controller {
387 pub fn new(id: String) -> Self {
388 let (tx, rx) = channel(State::Live);
389 Self {
390 id,
391 tx,
392 rx,
393 child_context: Mutex::new(Vec::new()),
394 retained: Mutex::new(Vec::new()),
395 }
396 }
397
398 pub fn id(&self) -> &str {
399 &self.id
400 }
401
402 fn transition_to_stopped(&self) {
403 self.tx.send_if_modified(|state| {
404 if *state != State::Live {
405 return false;
406 }
407 *state = State::Stopped;
408 true
409 });
410 }
411}
412
413impl Default for Controller {
414 fn default() -> Self {
415 Self::new(uuid::Uuid::new_v4().to_string())
416 }
417}
418
419impl AsyncEngineController for Controller {}
420
421#[async_trait]
422impl AsyncEngineContext for Controller {
423 fn id(&self) -> &str {
424 &self.id
425 }
426
427 fn is_stopped(&self) -> bool {
428 *self.rx.borrow() != State::Live
429 }
430
431 fn is_killed(&self) -> bool {
432 *self.rx.borrow() == State::Killed
433 }
434
435 async fn stopped(&self) {
436 let mut rx = self.rx.clone();
437 loop {
438 if *rx.borrow_and_update() != State::Live || rx.changed().await.is_err() {
439 return;
440 }
441 }
442 }
443
444 async fn killed(&self) {
445 let mut rx = self.rx.clone();
446 loop {
447 if *rx.borrow_and_update() == State::Killed || rx.changed().await.is_err() {
448 return;
449 }
450 }
451 }
452
453 fn stop_generating(&self) {
454 let children = self
456 .child_context
457 .lock()
458 .expect("Failed to lock child context")
459 .iter()
460 .cloned()
461 .collect::<Vec<_>>();
462 for child in children {
463 child.stop_generating();
464 }
465
466 self.transition_to_stopped();
467 }
468
469 fn stop(&self) {
470 let children = self
472 .child_context
473 .lock()
474 .expect("Failed to lock child context")
475 .iter()
476 .cloned()
477 .collect::<Vec<_>>();
478 for child in children {
479 child.stop();
480 }
481
482 self.transition_to_stopped();
483 }
484
485 fn kill(&self) {
486 let children = self
488 .child_context
489 .lock()
490 .expect("Failed to lock child context")
491 .iter()
492 .cloned()
493 .collect::<Vec<_>>();
494 for child in children {
495 child.kill();
496 }
497
498 let _ = self.tx.send(State::Killed);
499 }
500
501 fn link_child(&self, child: Arc<dyn AsyncEngineContext>) {
502 self.child_context
503 .lock()
504 .expect("Failed to lock child context")
505 .push(child);
506 }
507
508 fn retain(&self, guard: EngineContextGuard) {
509 self.retained
510 .lock()
511 .expect("Failed to lock retained engine state")
512 .push(RetainedGuard { _guard: guard });
513 }
514}
515
516#[cfg(test)]
517mod tests {
518 use super::*;
519
520 #[derive(Debug, Clone)]
521 struct Input {
522 value: String,
523 }
524
525 #[derive(Debug, Clone)]
526 struct Processed {
527 length: usize,
528 }
529
530 #[derive(Debug, Clone)]
531 struct Final {
532 message: String,
533 }
534
535 impl From<Input> for Processed {
536 fn from(input: Input) -> Self {
537 Processed {
538 length: input.value.len(),
539 }
540 }
541 }
542
543 impl From<Processed> for Final {
544 fn from(processed: Processed) -> Self {
545 Final {
546 message: format!("Processed length: {}", processed.length),
547 }
548 }
549 }
550
551 #[tokio::test]
552 async fn parent_stop_does_not_downgrade_killed_child() {
553 let parent = Controller::default();
554 let child = Arc::new(Controller::default());
555 parent.link_child(child.clone());
556
557 child.kill();
558 parent.stop();
559
560 assert!(child.is_killed());
561 tokio::time::timeout(std::time::Duration::from_secs(1), child.killed())
562 .await
563 .expect("killed child no longer reported its terminal state");
564
565 child.stop_generating();
566 assert!(child.is_killed());
567 }
568
569 #[test]
570 fn test_insert_and_get() {
571 let mut ctx = Context::new(Input {
572 value: "Hello".to_string(),
573 });
574
575 ctx.insert("key1", 42);
576 ctx.insert("key2", "some data".to_string());
577
578 assert_eq!(*ctx.get::<i32>("key1").unwrap(), 42);
579 assert_eq!(*ctx.get::<String>("key2").unwrap(), "some data");
580 assert!(ctx.get::<f64>("key1").is_err()); }
582
583 #[test]
584 fn test_metadata_preserved_across_transfers() {
585 let mut ctx = Context::new(Input {
586 value: "Hello".to_string(),
587 });
588 ctx.insert_metadata("tenant", "alpha");
589
590 let (_, transferred) = ctx.transfer(Processed { length: 5 });
591 assert_eq!(
592 transferred.metadata().get("tenant").map(String::as_str),
593 Some("alpha")
594 );
595 }
596
597 #[test]
598 fn test_with_id_and_metadata_constructor() {
599 let metadata = BTreeMap::from([("tenant".to_string(), "alpha".to_string())]);
600 let ctx = Context::with_id_and_metadata(
601 Input {
602 value: "Hello".to_string(),
603 },
604 "request-123".to_string(),
605 metadata,
606 );
607
608 assert_eq!(ctx.id(), "request-123");
609 assert_eq!(
610 ctx.metadata().get("tenant").map(String::as_str),
611 Some("alpha")
612 );
613 }
614
615 #[test]
616 fn test_metadata_preserved_across_rejoin() {
617 let mut ctx = Context::new(Input {
618 value: "Hello".to_string(),
619 });
620 ctx.insert_metadata("tenant", "alpha");
621
622 let (input, empty_ctx) = ctx.into_parts();
623 let rejoined = Context::rejoin(input, empty_ctx);
624 assert_eq!(
625 rejoined.metadata().get("tenant").map(String::as_str),
626 Some("alpha")
627 );
628 }
629
630 #[test]
631 fn test_metadata_preserved_in_stream_context() {
632 let mut ctx = Context::new(Input {
633 value: "Hello".to_string(),
634 });
635 ctx.insert_metadata("tenant", "alpha");
636
637 let stream_ctx = StreamContext::from(ctx);
638 assert_eq!(
639 stream_ctx.metadata().get("tenant").map(String::as_str),
640 Some("alpha")
641 );
642 }
643
644 #[test]
645 fn test_transfer() {
646 let ctx = Context::new(Input {
647 value: "Hello".to_string(),
648 });
649
650 let (input, ctx) = ctx.transfer(Processed { length: 5 });
651
652 assert_eq!(input.value, "Hello");
653 assert_eq!(ctx.length, 5);
654 }
655
656 #[test]
657 fn test_map() {
658 let ctx = Context::new(Input {
659 value: "Hello".to_string(),
660 });
661
662 let ctx: Context<Processed> = ctx.map(|input| input.into());
663 let ctx: Context<Final> = ctx.map(|processed| processed.into());
664
665 assert_eq!(ctx.current.message, "Processed length: 5");
666 }
667
668 #[test]
669 fn test_into_context() {
670 let ctx = Context::new(Input {
671 value: "Hello".to_string(),
672 });
673
674 let ctx: Context<Processed> = ctx.into_context();
675 let ctx: Context<Final> = ctx.into_context();
676
677 assert_eq!(ctx.current.message, "Processed length: 5");
678 }
679}