pipeless-ai 1.11.0

An open-source computer vision framework to build and deploy applications in minutes
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::fmt;
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
use std::str::FromStr;
use log::{error, warn};
use serde_derive::{Serialize, Deserialize};
use uuid;
use tabled::Tabled;

// The reconciler takes care of moving streams to the target state
#[derive(Debug,Copy,Clone,Serialize,Deserialize,PartialEq)]
pub enum StreamEntryState {
    Running,
    Completed,
    Error,
}
impl fmt::Display for StreamEntryState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StreamEntryState::Running => write!(f, "Running"),
            StreamEntryState::Completed => write!(f, "Completed"),
            StreamEntryState::Error => write!(f, "Error"),
        }
    }
}

#[derive(Debug,Clone,Serialize,Deserialize,PartialEq)]
pub struct RestartPolicyError;
impl fmt::Display for RestartPolicyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Unknown restart policy")
    }
}

#[derive(Debug,Copy,Clone,Serialize,PartialEq)]
pub enum RestartPolicy {
    Never, // Never restart
    Always, // Restart when there is an error or the stream reaches the end
    OnError, // Restart when there is an error
    OnEos, // Restart when the stream reaches the end
}
impl FromStr for RestartPolicy {
    type Err = RestartPolicyError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "never" | "Never" => Ok(Self::Never),
            "always" | "Always" => Ok(Self::Always),
            "onerror" | "OnError" | "onError" | "Onerror" | "on_error" | "On_Error" => Ok(Self::OnError),
            "oneos" | "OnEos" | "onEos" | "Oneos" | "on_eos" | "On_Eos" => Ok(Self::OnEos),
            _ => Err(RestartPolicyError),
        }
    }
}
impl<'de> serde::Deserialize<'de> for RestartPolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s: String = serde::Deserialize::deserialize(deserializer)?;

        match s.parse::<RestartPolicy>() {
            Ok(restart_policy) => Ok(restart_policy),
            Err(err) => Err(serde::de::Error::custom(format!("Error parsing restart policy: {}", err))),
        }
    }
}
impl fmt::Display for RestartPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RestartPolicy::Never => write!(f, "never"),
            RestartPolicy::Always => write!(f, "always"),
            RestartPolicy::OnError => write!(f, "on_error"),
            RestartPolicy::OnEos => write!(f, "on_eos"),
        }
    }
}

fn calculate_hash<T: Hash>(data: &T) -> u64 {
    let mut hasher = DefaultHasher::new();
    data.hash(&mut hasher);
    hasher.finish()
}

fn calculate_entry_hash(
    input_uri: &str,
    output_uri: Option<&str>,
    frame_path: &Vec<String>,
    restart_policy: &RestartPolicy
) -> u64 {
    let mut hash = calculate_hash(&input_uri);
    if let Some(out_uri) = output_uri {
        // Combine hashs with XOR to avoid overflows
        hash = hash ^ calculate_hash(&out_uri);
    }
    hash = hash ^ calculate_hash(&frame_path.join("/"));
    hash = hash ^ calculate_hash(&restart_policy.to_string());
    hash
}

#[derive(
    Clone,
    Debug,
    PartialEq,
    Serialize,
    Deserialize,
)]
pub struct StreamsTableEntry {
    /// Id of the dynamic coniguration entry
    id: uuid::Uuid,
    input_uri: String,
    /// There can be no output
    output_uri: Option<String>,
    frame_path: Vec<String>, // The ordered list of stages
    /// The id of the associated processing pipeline.
    /// Optional because it will be added an removed when streams reach their end
    /// to allow processing several consecutive streams from the same source
    pipeline_id: Option<uuid::Uuid>,
    // To know when the entry (only the URIs) has changed.
    // An entry that does not match the hash will be re-created since it has been updated.
    hash: u64,
    target_state: StreamEntryState,
    restart_policy: RestartPolicy,
}
impl StreamsTableEntry {
    pub fn new(
        input_uri: String,
        output_uri: Option<String>,
        frame_path: Vec<String>,
        restart_policy: RestartPolicy,
    ) -> Self {
        // We have to use underscores when providing the stage names as modules to some laguages like Python.
        let sanitized_frame_path: Vec<String> = frame_path.iter().map(|s| s.replace("-", "_")).collect();

        let entry_hash = calculate_entry_hash(&input_uri, output_uri.as_deref(), &sanitized_frame_path, &restart_policy);

        let mut restart_policy = restart_policy;
        let using_input_file = input_uri.starts_with("file://");
        let using_output_file = match output_uri.clone() {
            Some(uri) => uri.starts_with("file://"),
            None => false
        };
        if using_input_file || using_output_file {
            if restart_policy != RestartPolicy::Never {
                warn!("Overriding restart policy with 'never' because the stream uses files");
                restart_policy = RestartPolicy::Never;
            }
        }

        Self {
            id: uuid::Uuid::new_v4(),
            input_uri: input_uri.to_string(),
            output_uri: output_uri.map(|x| x.to_string()),
            frame_path: sanitized_frame_path,
            pipeline_id: None, // No pipeline id assigned when created
            hash: entry_hash,
            target_state: StreamEntryState::Running,
            restart_policy,
        }
    }

    pub fn get_id(&self) -> uuid::Uuid {
        self.id
    }

    pub fn get_input_uri(&self) -> &str {
        &self.input_uri
    }
    pub fn set_input_uri(&mut self, new_uri: &str) {
        self.input_uri = new_uri.to_owned()
    }

    pub fn get_output_uri(&self) -> Option<&str> {
        self.output_uri.as_deref()
    }
    pub fn set_output_uri(&mut self, new_uri: Option<String>) {
        self.output_uri = new_uri
    }

    pub fn get_frame_path(&self) -> &Vec<String> {
        &self.frame_path
    }
    pub fn set_frame_path(&mut self, new_path: Vec<String>) {
        self.frame_path = new_path
    }

    pub fn assign_pipeline(&mut self, pipeline_id: uuid::Uuid) {
        self.pipeline_id = Some(pipeline_id);
    }

    pub fn unassign_pipeline(&mut self) {
        self.pipeline_id = None;
    }

    pub fn get_pipeline(&self) -> Option<uuid::Uuid> {
        self.pipeline_id
    }

    /// Returns the hash that the entry has from its creation
    pub fn get_stored_hash(&self) -> u64 {
        self.hash
    }

    /// Calculates the hash that the entry should have according to the current values
    pub fn hash(&self) -> u64 {
        calculate_entry_hash(
            self.get_input_uri(),
            self.get_output_uri(),
            self.get_frame_path(),
            &self.get_restart_policy()
        )
    }

    pub fn get_target_state(&self) -> StreamEntryState {
        self.target_state
    }

    pub fn set_target_state(&mut self, state: StreamEntryState) {
        self.target_state = state;
    }

    pub fn set_restart_policy(&mut self, restart_policy: RestartPolicy) {
        self.restart_policy = restart_policy;
    }

    pub fn get_restart_policy(&self) -> RestartPolicy {
        self.restart_policy
    }
}
impl Tabled for StreamsTableEntry {
    const LENGTH: usize = 6;

    fn fields(&self) -> Vec<std::borrow::Cow<'_, str>> {
        vec![
            self.id.to_string().into(),
            self.input_uri.clone().into(),
            self.output_uri.clone().unwrap_or_else(|| "".into()).into(),
            self.frame_path.join(" -> ").into(),
            self.target_state.to_string().into(),
            self.restart_policy.to_string().into(),
        ]
    }

    fn headers() -> Vec<std::borrow::Cow<'static, str>> {
        vec![
            "ID".into(),
            "Input URI".into(),
            "Output URI".into(),
            "Frame Path".into(),
            "State".into(),
            "Restart Policy".into()
        ]
    }
}

/// Represents the Pipeless dynamic streams configuration
/// which is modified by the user ahdn automatically handled
pub struct StreamsTable {
    table: Vec<StreamsTableEntry>,
}
impl StreamsTable {
    pub fn new() -> Self {
        Self {
            table: Vec::new(),
        }
    }

    /// Get a copy of the streams table
    pub fn get_table(&self) -> Vec<StreamsTableEntry> {
        self.table.clone()
    }

    pub fn add(&mut self, entry: StreamsTableEntry) -> Result<(), String> {
        self.table.push(entry);
        Ok(())
    }

    pub fn get_entry_by_id(&self, entry_id: uuid::Uuid) -> Option<&StreamsTableEntry> {
        self.table.iter().find(|entry| entry.get_id() == entry_id)
    }

    pub fn remove(&mut self, stream_id: uuid::Uuid) -> Option<StreamsTableEntry> {
        if let Some(index) = self.table.iter().position(|entry| entry.id == stream_id) {
            let removed_entry = self.table.remove(index);
            Some(removed_entry)
        } else {
            None
        }
    }

    pub fn set_stream_pipeline(&mut self, stream_id: uuid::Uuid, pipeline_id: uuid::Uuid) -> Result<(), String> {
        if self.table.iter().any(|entry| entry.pipeline_id == Some(pipeline_id)) {
            return Err("Pipeline ID already assigned to another entry".to_string());
        }

        if let Some(entry) = self.table.iter_mut().find(|entry| entry.id == stream_id) {
            entry.assign_pipeline(pipeline_id);
            Ok(())
        } else {
            Err("Entry not found".to_string())
        }
    }

    /// Since pipeline_ids are unique we can get an entry by pipeline id
    pub fn get_entry_by_pipeline_id(&mut self, pipeline_id: uuid::Uuid) -> Option<&mut StreamsTableEntry> {
        self.table.iter_mut().find(|entry| entry.pipeline_id == Some(pipeline_id))
    }

    pub fn find_by_pipeline_id(&self, pipeline_id: uuid::Uuid) -> Option<&StreamsTableEntry> {
        self.table.iter().find(|entry| entry.get_pipeline() == Some(pipeline_id))
    }
    pub fn find_by_pipeline_id_mut(&mut self, pipeline_id: uuid::Uuid) -> Option<&mut StreamsTableEntry> {
        self.table.iter_mut().find(|entry| entry.get_pipeline() == Some(pipeline_id))
    }

    pub fn update_by_entry_id(
        &mut self, entry_id: uuid::Uuid, input_uri: &str, output_uri: Option<String>,
        frame_path: Vec<String>, restart_policy: RestartPolicy
    ) {
        if let Some(entry) = self.table.iter_mut().find(|entry| entry.id == entry_id) {
            entry.unassign_pipeline();
            entry.set_input_uri(input_uri);
            entry.set_output_uri(output_uri);
            entry.set_frame_path(frame_path);
            entry.set_restart_policy(restart_policy);
        } else {
            error!("Unable to update stream entry. Stream id not found {}", entry_id);
        }
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add_entry_duplicated_input() {
        let mut table = StreamsTable::new();
        let entry1 = StreamsTableEntry::new(
            "input1".to_string(),
            None,
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        assert!(table.add(entry1).is_ok());
        assert_eq!(table.get_table().len(), 1);

        // Adding an entry with a duplicate input_uri should fail
        let entry2 = StreamsTableEntry::new(
            "input1".to_string(),
            None,
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        assert!(table.add(entry2).is_err());
    }

    #[test]
    fn test_add_entry_duplicated_output() {
        let mut table = StreamsTable::new();
        let entry1 = StreamsTableEntry::new(
            "input1".to_string(),
            Some("output1".to_string()),
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        assert!(table.add(entry1).is_ok());
        assert_eq!(table.get_table().len(), 1);

        // Adding an entry with a duplicate output_uri should fail
        let entry2 = StreamsTableEntry::new(
            "input2".to_string(),
            Some("output1".to_string()),
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        assert!(table.add(entry2).is_err());
    }

    #[test]
    fn test_remove_entry() {
        let mut table = StreamsTable::new();
        let entry1 = StreamsTableEntry::new(
            "input1".to_string(),
            None,
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        table.add(entry1.clone()).unwrap();

        let removed_entry = table.remove(entry1.get_id())
            .expect("Could not get entry");
        assert_eq!(removed_entry, entry1);
        assert_eq!(table.get_table().len(), 0);

        // Removing a non-existent entry should return None
        assert_eq!(table.remove(uuid::Uuid::new_v4()), None);
    }

    #[test]
    fn test_set_entry_pipeline() {
        let mut table = StreamsTable::new();
        let entry1 = StreamsTableEntry::new(
            "input1".to_string(),
            None,
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        table.add(entry1.clone()).unwrap();

        let pipeline_id = uuid::Uuid::new_v4();
        assert!(table.set_stream_pipeline(entry1.get_id(), pipeline_id).is_ok());
        assert_eq!(table.get_table()[0].get_pipeline(), Some(pipeline_id));

        // Setting a pipeline ID that is already assigned to another entry should fail
        let entry2 = StreamsTableEntry::new(
            "input2".to_string(),
            None,
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        table.add(entry2.clone()).unwrap();
        assert!(table.set_stream_pipeline(entry2.get_id(), pipeline_id).is_err());
    }

    #[test]
    fn test_find_by_pipeline_id() {
        let mut table = StreamsTable::new();
        let pipeline_id = uuid::Uuid::new_v4();
        let mut entry1 = StreamsTableEntry::new(
            "input1".to_string(),
            Some("output1".to_string()),
            vec!["s1".to_owned(), "s2".to_owned()],
            RestartPolicy::Never,
        );
        entry1.assign_pipeline(pipeline_id);
        table.add(entry1.clone()).unwrap();

        // Finding an entry by its pipeline ID
        let found_entry = table.find_by_pipeline_id(pipeline_id);
        assert_eq!(found_entry, Some(&entry1));

        // Finding an entry by a non-existent pipeline ID
        let non_existent_pipeline_id = uuid::Uuid::new_v4();
        let not_found_entry = table.find_by_pipeline_id(non_existent_pipeline_id);
        assert_eq!(not_found_entry, None);
    }
}