1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//! Workflow steps are individual actions that can be taken on media as part of a media pipeline.

pub mod factory;
pub mod workflow_forwarder;

use super::MediaNotification;
use crate::workflows::definitions::WorkflowStepDefinition;
use downcast_rs::{impl_downcast, Downcast};
use futures::future::BoxFuture;

/// Represents the result of a future for a workflow step.  It is expected that the workflow step
/// will downcast this result into a struct that it owns.
pub trait StepFutureResult: Downcast {}
impl_downcast!(StepFutureResult);

pub type FutureList = Vec<BoxFuture<'static, Box<dyn StepFutureResult>>>;
pub type StepCreationResult = Result<
    (Box<dyn WorkflowStep + Sync + Send>, FutureList),
    Box<dyn std::error::Error + Sync + Send>,
>;
pub type CreateFactoryFnResult =
    Box<dyn Fn(&WorkflowStepDefinition) -> StepCreationResult + Send + Sync>;

/// Various statuses of an individual step
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StepStatus {
    /// The step has been created but it is not yet ready to handle media
    Created,

    /// The step is fully active and ready for handling media
    Active,

    /// The step has encountered an unrecoverable error and can no longer handle media or
    /// notifications.  It will likely have to be recreated.
    Error { message: String },

    /// The step has been shut down and is not expected to be invoked anymore. If it's wanted to be
    /// used it will have to be recreated
    Shutdown,
}

/// Inputs to be passed in for execution of a workflow step.
#[derive(Default)]
pub struct StepInputs {
    /// Media notifications that the step may be interested in
    pub media: Vec<MediaNotification>,

    /// Any resolved futures that are specific to this step
    pub notifications: Vec<Box<dyn StepFutureResult>>,
}

impl StepInputs {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn clear(&mut self) {
        self.media.clear();
        self.notifications.clear();
    }
}

/// Resulting outputs that come from executing a workflow step.
#[derive(Default)]
pub struct StepOutputs {
    /// Media notifications that the workflow step intends to pass to the next workflow step
    pub media: Vec<MediaNotification>,

    /// Any futures the workflow should track for this step
    pub futures: Vec<BoxFuture<'static, Box<dyn StepFutureResult>>>,
}

impl StepOutputs {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn clear(&mut self) {
        self.futures.clear();
        self.media.clear();
    }
}

/// Represents a workflow step that can be executed
pub trait WorkflowStep {
    /// Returns a reference to the status of the current workflow step
    fn get_status(&self) -> &StepStatus;

    /// Returns a reference to the definition this workflow step was created with
    fn get_definition(&self) -> &WorkflowStepDefinition;

    /// Executes the workflow step with the specified media and future resolution inputs.  Any outputs
    /// that are generated as a result of this execution will be placed in the `outputs` parameter,
    /// to allow vectors to be re-used.
    ///
    /// It is expected that `execute()` will not be called if the step is in an Error or Torn Down
    /// state.
    fn execute(&mut self, inputs: &mut StepInputs, outputs: &mut StepOutputs);

    /// Notifies the step that it is no longer needed and that all streams its managing should be
    /// closed.  All endpoints the step has interacted with should be proactively notified that it
    /// is being removed, as it can not be guaranteed that all channels will be automatically
    /// closed.
    ///
    /// After this is called it is expected that the workflow step is in a `TornDown` state.
    fn shutdown(&mut self);
}

#[cfg(feature = "test-utils")]
use crate::workflows::steps::factory::StepGenerator;
#[cfg(feature = "test-utils")]
use anyhow::{anyhow, Result};
#[cfg(feature = "test-utils")]
use futures::stream::FuturesUnordered;
#[cfg(feature = "test-utils")]
use futures::StreamExt;
#[cfg(feature = "test-utils")]
use std::iter::FromIterator;
#[cfg(feature = "test-utils")]
use std::time::Duration;

#[cfg(feature = "test-utils")]
pub struct StepTestContext {
    pub step: Box<dyn WorkflowStep>,
    pub futures: FuturesUnordered<BoxFuture<'static, Box<dyn StepFutureResult>>>,
    pub media_outputs: Vec<MediaNotification>,
}

#[cfg(feature = "test-utils")]
impl StepTestContext {
    pub fn new(
        generator: Box<dyn StepGenerator>,
        definition: WorkflowStepDefinition,
    ) -> Result<Self> {
        let (step, futures) = generator
            .generate(definition)
            .map_err(|error| anyhow!("Failed to generate workflow step: {:?}", error))?;

        Ok(StepTestContext {
            step,
            futures: FuturesUnordered::from_iter(futures),
            media_outputs: Vec::new(),
        })
    }

    pub fn execute_with_media(&mut self, media: MediaNotification) {
        let mut outputs = StepOutputs::new();
        let mut inputs = StepInputs::new();
        inputs.media.push(media);

        self.step.execute(&mut inputs, &mut outputs);

        self.futures.extend(outputs.futures.drain(..));
        self.media_outputs = outputs.media;
    }

    pub async fn execute_notification(&mut self, notification: Box<dyn StepFutureResult>) {
        let mut outputs = StepOutputs::new();
        let mut inputs = StepInputs::new();
        inputs.notifications.push(notification);

        self.step.execute(&mut inputs, &mut outputs);

        self.futures.extend(outputs.futures.drain(..));
        self.media_outputs = outputs.media;

        self.execute_pending_notifications().await;
    }

    pub async fn execute_pending_notifications(&mut self) {
        loop {
            let notification =
                match tokio::time::timeout(Duration::from_millis(10), self.futures.next()).await {
                    Ok(Some(notification)) => notification,
                    _ => break,
                };

            let mut outputs = StepOutputs::new();
            let mut inputs = StepInputs::new();
            inputs.notifications.push(notification);

            self.step.execute(&mut inputs, &mut outputs);

            self.futures.extend(outputs.futures.drain(..));
            self.media_outputs = outputs.media;
        }
    }

    pub fn assert_media_passed_through(&mut self, media: MediaNotification) {
        self.execute_with_media(media.clone());

        assert_eq!(
            self.media_outputs.len(),
            1,
            "Unexpected number of media outputs"
        );
        assert_eq!(self.media_outputs[0], media, "Unexpected media message");
    }

    pub fn assert_media_not_passed_through(&mut self, media: MediaNotification) {
        self.execute_with_media(media);

        assert!(self.media_outputs.is_empty(), "Expected no media outputs");
    }
}