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
//! Builders for [Uni], responsible for creating the executor and creating the producers.\
//! For more, see [super]

use super::{
    super::{
        instruments::Instruments,
        stream_executor::StreamExecutor,
        mutiny_stream::MutinyStream,
        types::{FullDuplexUniChannel},
    },
    uni::Uni,
};
use std::{
    fmt::Debug,
    future::Future,
    marker::PhantomData,
    sync::{
        Arc,
        atomic::Ordering::Relaxed,
    },
    time::Duration,
};
use futures::Stream;


pub struct UniBuilder<InType:              'static + Debug + Sync + Send,
                      UniChannelType:      FullDuplexUniChannel<'static, InType, DerivedItemType> + Sync + Send + 'static,
                      const INSTRUMENTS:   usize,
                      DerivedItemType:     'static + Debug + Sync + Send> {

    pub concurrency_limit:        u32,
    /// if Some, will cause the pipeline to be wrapped with [tokio::time::timeout] so that an Err will be produced whenever the pipeline takes too much time to process
    pub futures_timeout:          Duration,
    /// Instrumentation this instance gathers / produces
    pub instruments:              Instruments,
    // phantoms
    _phantom:                     PhantomData<(InType, UniChannelType, DerivedItemType)>,

}
impl<InType:              'static + Sync + Send + Debug,
     UniChannelType:      FullDuplexUniChannel<'static, InType, DerivedItemType> + Sync + Send + 'static,
     const INSTRUMENTS:   usize,
     DerivedItemType:     'static + Debug + Sync + Send>
UniBuilder<InType, UniChannelType, INSTRUMENTS, DerivedItemType> {

    pub fn new() -> Self {
        Self {
            concurrency_limit:        1,
            futures_timeout:          Duration::ZERO,
            instruments:              Instruments::from(INSTRUMENTS),
            _phantom:                 Default::default(),
        }
    }

    pub fn concurrency_limit(mut self, concurrency_limit: u32) -> Self {
        self.concurrency_limit = concurrency_limit;
        self
    }

    pub fn futures_timeout(mut self, futures_timeout: Duration) -> Self {
        self.futures_timeout = futures_timeout;
        self
    }

    #[must_use]
    pub fn spawn_executor<IntoString:             Into<String>,
                          OutItemType:            Send + Debug,
                          OutStreamType:          Stream<Item=OutType> + Send + 'static,
                          OutType:                Future<Output=Result<OutItemType, Box<dyn std::error::Error + Send + Sync>>> + Send,
                          ErrVoidAsyncType:       Future<Output=()> + Send + 'static,
                          CloseVoidAsyncType:     Future<Output=()> + Send + 'static>

                         (self,
                          stream_name:               IntoString,
                          pipeline_builder:          impl FnOnce(MutinyStream<'static, InType, UniChannelType, DerivedItemType>) -> OutStreamType,
                          on_err_callback:           impl Fn(Box<dyn std::error::Error + Send + Sync>)                           -> ErrVoidAsyncType   + Send + Sync + 'static,
                          on_close_callback:         impl Fn(Arc<StreamExecutor<INSTRUMENTS>>)                                   -> CloseVoidAsyncType + Send + Sync + 'static)

                         -> Arc<Uni<'static, InType, UniChannelType, INSTRUMENTS, DerivedItemType>> {

        let stream_name = stream_name.into();
        let executor = StreamExecutor::with_futures_timeout(stream_name.to_string(), self.futures_timeout);
        let handle = Arc::new(Uni::new(stream_name, Arc::clone(&executor)));
        let in_stream = handle.consumer_stream();
        let returned_handle = Arc::clone(&handle);
        let out_stream = pipeline_builder(in_stream);
        let on_close_callback = Arc::new(on_close_callback);
        executor
            .spawn_executor(
                self.concurrency_limit,
                on_err_callback,
                move |executor| {
                    let on_close_callback = Arc::clone(&on_close_callback);
                    let handle = Arc::clone(&handle);
                        async move {
                        handle.finished_executors_count.fetch_add(1, Relaxed);
                        on_close_callback(executor).await;
                    }
                },
                out_stream
            );
        returned_handle
    }

    #[must_use]
    pub fn spawn_fallibles_executor<IntoString:             Into<String>,
                                    OutItemType:            Send + Debug,
                                    OutStreamType:          Stream<Item=Result<OutItemType, Box<dyn std::error::Error + Send + Sync>>> + Send + 'static,
                                    CloseVoidAsyncType:     Future<Output=()> + Send + 'static>

                                   (self,
                                    stream_name:               IntoString,
                                    pipeline_builder:          impl FnOnce(MutinyStream<'static, InType, UniChannelType, DerivedItemType>) -> OutStreamType,
                                    on_err_callback:           impl Fn(Box<dyn std::error::Error + Send + Sync>)                                                 + Send + Sync + 'static,
                                    on_close_callback:         impl Fn(Arc<StreamExecutor<INSTRUMENTS>>)                                   -> CloseVoidAsyncType + Send + Sync + 'static)

                                   -> Arc<Uni<'static, InType, UniChannelType, INSTRUMENTS, DerivedItemType>> {

        let stream_name = stream_name.into();
        let executor = StreamExecutor::with_futures_timeout(stream_name.to_string(), self.futures_timeout);
        let handle = Arc::new(Uni::new(stream_name, Arc::clone(&executor)));
        let in_stream = handle.consumer_stream();
        let returned_handle = Arc::clone(&handle);
        let out_stream = pipeline_builder(in_stream);
        let on_close_callback = Arc::new(on_close_callback);
        executor
            .spawn_fallibles_executor(
                self.concurrency_limit,
                on_err_callback,
                move |executor| {
                    let on_close_callback = Arc::clone(&on_close_callback);
                    let handle = Arc::clone(&handle);
                        async move {
                        handle.finished_executors_count.fetch_add(1, Relaxed);
                        on_close_callback(executor).await;
                    }
                },
                out_stream
            );
        returned_handle
    }

    #[must_use]
    pub fn spawn_futures_executor<IntoString:             Into<String>,
                                  OutItemType:            Send + Debug,
                                  OutStreamType:          Stream<Item=OutType> + Send + 'static,
                                  OutType:                Future<Output=OutItemType> + Send,
                                  CloseVoidAsyncType:     Future<Output=()> + Send + 'static>

                                 (self,
                                  stream_name:               IntoString,
                                  pipeline_builder:          impl FnOnce(MutinyStream<'static, InType, UniChannelType, DerivedItemType>) -> OutStreamType,
                                  on_close_callback:         impl Fn(Arc<StreamExecutor<INSTRUMENTS>>)                                   -> CloseVoidAsyncType + Send + Sync + 'static)

                                 -> Arc<Uni<'static, InType, UniChannelType, INSTRUMENTS, DerivedItemType>> {

        let stream_name = stream_name.into();
        let executor = StreamExecutor::with_futures_timeout(stream_name.to_string(), self.futures_timeout);
        let handle = Arc::new(Uni::new(stream_name, Arc::clone(&executor)));
        let in_stream = handle.consumer_stream();
        let returned_handle = Arc::clone(&handle);
        let out_stream = pipeline_builder(in_stream);
        let on_close_callback = Arc::new(on_close_callback);
        executor
            .spawn_futures_executor(
                self.concurrency_limit,
                move |executor| {
                    let on_close_callback = Arc::clone(&on_close_callback);
                    let handle = Arc::clone(&handle);
                        async move {
                        handle.finished_executors_count.fetch_add(1, Relaxed);
                        on_close_callback(executor).await;
                    }
                },
                out_stream
            );
        returned_handle
    }

    #[must_use]
    pub fn spawn_non_futures_non_fallibles_executor<IntoString:             Into<String>,
                                                   OutItemType:            Send + Debug,
                                                   OutStreamType:          Stream<Item=OutItemType> + Send + 'static,
                                                   CloseVoidAsyncType:     Future<Output=()> + Send + 'static>

                                                  (self,
                                                   stream_name:              IntoString,
                                                   pipeline_builder:         impl FnOnce(MutinyStream<'static, InType, UniChannelType, DerivedItemType>) -> OutStreamType,
                                                   on_close_callback:        impl FnOnce(Arc<StreamExecutor<INSTRUMENTS>>)                               -> CloseVoidAsyncType + Send + Sync + 'static)

                                                  -> Arc<Uni<'static, InType, UniChannelType, INSTRUMENTS, DerivedItemType>> {

        let stream_name = stream_name.into();
        let executor = StreamExecutor::new(stream_name.to_string());
        let handle = Arc::new(Uni::new(stream_name, Arc::clone(&executor)));
        let in_stream = handle.consumer_stream();
        let returned_handle = Arc::clone(&handle);
        let out_stream = pipeline_builder(in_stream);
        executor
            .spawn_non_futures_non_fallibles_executor(
                self.concurrency_limit,
                move |executor| {
                    let handle = Arc::clone(&handle);
                    async move {
                        handle.finished_executors_count.fetch_add(1, Relaxed);
                        on_close_callback(executor).await;
                    }
                },
                out_stream
            );
        returned_handle
    }

}