|
| 1 | +use crate::uniffi::{error::Result, model::packet::Packet}; |
| 2 | +use async_trait; |
| 3 | +use itertools::Itertools as _; |
| 4 | +use std::{clone::Clone, collections::HashMap, iter::IntoIterator, sync::Arc}; |
| 5 | +use tokio::sync::Mutex; |
| 6 | + |
| 7 | +#[async_trait::async_trait] |
| 8 | +pub trait Operator { |
| 9 | + async fn next(&self, stream_name: String, packet: Packet) -> Result<Vec<Packet>>; |
| 10 | +} |
| 11 | + |
| 12 | +pub struct JoinOperator { |
| 13 | + parent_count: usize, |
| 14 | + received_packets: Arc<Mutex<HashMap<String, Vec<Packet>>>>, |
| 15 | +} |
| 16 | + |
| 17 | +impl JoinOperator { |
| 18 | + pub fn new(parent_count: usize) -> Self { |
| 19 | + Self { |
| 20 | + parent_count, |
| 21 | + received_packets: Arc::new(Mutex::new(HashMap::new())), |
| 22 | + } |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +#[async_trait::async_trait] |
| 27 | +impl Operator for JoinOperator { |
| 28 | + async fn next(&self, stream_name: String, packet: Packet) -> Result<Vec<Packet>> { |
| 29 | + let mut received_packets = self.received_packets.lock().await; |
| 30 | + received_packets |
| 31 | + .entry(stream_name.clone()) |
| 32 | + .or_default() |
| 33 | + .push(packet.clone()); |
| 34 | + Ok( |
| 35 | + if self.parent_count - usize::from(!received_packets.contains_key(&stream_name)) |
| 36 | + == received_packets.len() |
| 37 | + { |
| 38 | + let packets_to_multiplex = received_packets |
| 39 | + .iter() |
| 40 | + .filter_map(|(parent_stream, parent_packets)| { |
| 41 | + (parent_stream != &stream_name).then_some(parent_packets.clone()) |
| 42 | + }) |
| 43 | + .chain(vec![vec![packet.clone()]].into_iter()) |
| 44 | + .collect::<Vec<_>>(); |
| 45 | + drop(received_packets); |
| 46 | + |
| 47 | + packets_to_multiplex |
| 48 | + .into_iter() |
| 49 | + .multi_cartesian_product() |
| 50 | + .map(|packet_combinations_to_merge| { |
| 51 | + packet_combinations_to_merge |
| 52 | + .into_iter() |
| 53 | + .flat_map(IntoIterator::into_iter) |
| 54 | + .collect::<HashMap<_, _>>() |
| 55 | + }) |
| 56 | + .collect() |
| 57 | + } else { |
| 58 | + vec![] |
| 59 | + }, |
| 60 | + ) |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +pub struct MapOperator { |
| 65 | + map: HashMap<String, String>, |
| 66 | +} |
| 67 | + |
| 68 | +impl MapOperator { |
| 69 | + pub fn new(map: &HashMap<String, String>) -> Self { |
| 70 | + Self { map: map.clone() } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +#[async_trait::async_trait] |
| 75 | +impl Operator for MapOperator { |
| 76 | + async fn next(&self, _: String, packet: Packet) -> Result<Vec<Packet>> { |
| 77 | + Ok(vec![ |
| 78 | + packet |
| 79 | + .iter() |
| 80 | + .map(|(packet_key, path_set)| { |
| 81 | + ( |
| 82 | + self.map |
| 83 | + .get(packet_key) |
| 84 | + .map_or_else(|| packet_key.clone(), Clone::clone), |
| 85 | + path_set.clone(), |
| 86 | + ) |
| 87 | + }) |
| 88 | + .collect(), |
| 89 | + ]) |
| 90 | + } |
| 91 | +} |
0 commit comments