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
use std::fmt::Debug;
use std::hash::Hash;
use std::pin::Pin;
use std::task::{Context, Poll};

use futures::{Future, Sink, SinkExt};
use futures::channel::oneshot;
use futures_lite::FutureExt;

use crate::TaskType;

use super::{assert_future, Error, ErrorType, TaskExecQueue};

pub struct GroupSpawner<'a, Item, Tx, G> {
    inner: Spawner<'a, Item, Tx, G, ()>,
    name: Option<G>,
}

impl<Item, Tx, G> Unpin for GroupSpawner<'_, Item, Tx, G> {}

impl<'a, Item, Tx, G> GroupSpawner<'a, Item, Tx, G>
    where
        Tx: Clone + Unpin + Sink<((), TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    #[inline]
    pub(crate) fn new(inner: Spawner<'a, Item, Tx, G, ()>, name: G) -> Self {
        Self {
            inner,
            name: Some(name),
        }
    }

    #[inline]
    pub async fn result(mut self) -> Result<Item::Output, Error<Item>>
        where
            Item: Future + Send + 'static,
            Item::Output: Send + 'static,
    {
        let task = match self.inner.item.take() {
            Some(task) => task,
            None => {
                log::error!("polled Feed after completion, task is None!");
                return Err(Error::SendError(ErrorType::Closed(None)));
            }
        };

        let name = match self.name.take() {
            Some(name) => name,
            None => {
                log::error!("polled Feed after completion, name is None!");
                return Err(Error::SendError(ErrorType::Closed(None)));
            }
        };

        if self.inner.sink.is_closed() {
            return Err(Error::SendError(ErrorType::Closed(Some(task))));
        }

        let (res_tx, res_rx) = oneshot::channel();
        let waiting_count = self.inner.sink.waiting_count.clone();
        let task = async move {
            waiting_count.dec();
            let output = task.await;
            if let Err(_e) = res_tx.send(output) {
                log::warn!("send result failed");
            }
        };
        self.inner.sink.waiting_count.inc();

        if let Err(_e) = self
            .inner
            .sink
            .group_send(name, Box::new(Box::pin(task)))
            .await
        {
            self.inner.sink.waiting_count.dec();
            Err(Error::SendError(ErrorType::Closed(None)))
        } else {
            res_rx.await.map_err(|_| {
                self.inner.sink.waiting_count.dec();
                Error::RecvResultError
            })
        }
    }
}

impl<Item, Tx, G> Future for GroupSpawner<'_, Item, Tx, G>
    where
        Item: Future + Send + 'static,
        Item::Output: Send + 'static,
        Tx: Clone + Unpin + Sink<((), TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    type Output = Result<(), Error<Item>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        let task = match this.inner.item.take() {
            Some(task) => task,
            None => {
                log::error!("polled Feed after completion, task is None!");
                return Poll::Ready(Ok(()));
            }
        };

        let name = match this.name.take() {
            Some(name) => name,
            None => {
                log::error!("polled Feed after completion, name is None!");
                return Poll::Ready(Ok(()));
            }
        };

        if this.inner.sink.is_closed() {
            return Poll::Ready(Err(Error::SendError(ErrorType::Closed(Some(task)))));
        }
        let waiting_count = this.inner.sink.waiting_count.clone();
        let task = async move {
            waiting_count.dec();
            let _ = task.await;
        };
        this.inner.sink.waiting_count.inc();
        let mut group_send = this
            .inner
            .sink
            .group_send(name, Box::new(Box::pin(task)))
            .boxed();

        if (futures::ready!(group_send.poll(cx))).is_err() {
            this.inner.sink.waiting_count.dec();
            Poll::Ready(Err(Error::SendError(ErrorType::Closed(None))))
        } else {
            Poll::Ready(Ok(()))
        }
    }
}

pub struct TryGroupSpawner<'a, Item, Tx, G> {
    inner: GroupSpawner<'a, Item, Tx, G>,
}

impl<Item, Tx, G> Unpin for TryGroupSpawner<'_, Item, Tx, G> {}

impl<'a, Item, Tx, G> TryGroupSpawner<'a, Item, Tx, G>
    where
        Tx: Clone + Unpin + Sink<((), TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    #[inline]
    pub(crate) fn new(inner: Spawner<'a, Item, Tx, G, ()>, name: G) -> Self {
        Self {
            inner: GroupSpawner {
                inner,
                name: Some(name),
            },
        }
    }

    #[inline]
    pub async fn result(mut self) -> Result<Item::Output, Error<Item>>
        where
            Item: Future + Send + 'static,
            Item::Output: Send + 'static,
    {
        if self.inner.inner.sink.is_full() {
            return Err(Error::TrySendError(ErrorType::Full(
                self.inner.inner.item.take(),
            )));
        }
        self.inner.result().await
    }
}

impl<Item, Tx, G> Future for TryGroupSpawner<'_, Item, Tx, G>
    where
        Item: Future + Send + 'static,
        Item::Output: Send + 'static,
        Tx: Clone + Unpin + Sink<((), TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    type Output = Result<(), Error<Item>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();

        if this.inner.inner.sink.is_full() {
            return Poll::Ready(Err(Error::TrySendError(ErrorType::Full(
                this.inner.inner.item.take(),
            ))));
        }

        this.inner.poll(cx)
    }
}

pub struct Spawner<'a, Item, Tx, G, D> {
    sink: &'a TaskExecQueue<Tx, G, D>,
    item: Option<Item>,
    d: Option<D>,
}

impl<'a, Item, Tx, G, D> Unpin for Spawner<'a, Item, Tx, G, D> {}

impl<'a, Item, Tx, G> Spawner<'a, Item, Tx, G, ()>
    where
        Tx: Clone + Unpin + Sink<((), TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    #[inline]
    pub fn group(self, name: G) -> GroupSpawner<'a, Item, Tx, G>
        where
            Item: Future + Send + 'static,
            Item::Output: Send + 'static,
    {
        let fut = GroupSpawner::new(self, name);
        assert_future::<Result<(), _>, _>(fut)
    }
}

impl<'a, Item, Tx, G, D> Spawner<'a, Item, Tx, G, D>
    where
        Tx: Clone + Unpin + Sink<(D, TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    #[inline]
    pub(crate) fn new(sink: &'a TaskExecQueue<Tx, G, D>, item: Item, d: D) -> Self {
        Self {
            sink,
            item: Some(item),
            d: Some(d),
        }
    }

    #[inline]
    pub async fn result(mut self) -> Result<Item::Output, Error<Item>>
        where
            Item: Future + Send + 'static,
            Item::Output: Send + 'static,
    {
        let task = self
            .item
            .take()
            .expect("polled Feed after completion, task is None!");
        let d = self
            .d
            .take()
            .expect("polled Feed after completion, d is None!");

        if self.sink.is_closed() {
            return Err(Error::SendError(ErrorType::Closed(Some(task))));
        }

        let (res_tx, res_rx) = oneshot::channel();
        let waiting_count = self.sink.waiting_count.clone();
        let task = async move {
            waiting_count.dec();
            let output = task.await;
            if let Err(_e) = res_tx.send(output) {
                log::warn!("send result failed");
            }
        };
        self.sink.waiting_count.inc();

        if self
            .sink
            .tx
            .clone()
            .send((d, Box::new(Box::pin(task))))
            .await
            .is_err()
        {
            self.sink.waiting_count.dec();
            return Err(Error::SendError(ErrorType::Closed(None)));
        }
        res_rx.await.map_err(|_| {
            self.sink.waiting_count.dec();
            Error::RecvResultError
        })
    }
}

impl<Item, Tx, G, D> Future for Spawner<'_, Item, Tx, G, D>
    where
        Item: Future + Send + 'static,
        Item::Output: Send + 'static,
        Tx: Clone + Unpin + Sink<(D, TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    type Output = Result<(), Error<Item>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        let task = match this.item.take() {
            Some(task) => task,
            None => {
                log::error!("polled Feed after completion, task is None!");
                return Poll::Ready(Ok(()));
            }
        };

        let d = match this.d.take() {
            Some(d) => d,
            None => {
                log::error!("polled Feed after completion, d is None!");
                return Poll::Ready(Ok(()));
            }
        };

        if this.sink.is_closed() {
            return Poll::Ready(Err(Error::SendError(ErrorType::Closed(Some(task)))));
        }

        let mut tx = this.sink.tx.clone();
        let mut sink = Pin::new(&mut tx);
        futures::ready!(sink.as_mut().poll_ready(cx))
            .map_err(|_| Error::SendError(ErrorType::Closed(None)))?;
        let waiting_count = this.sink.waiting_count.clone();
        let task = async move {
            waiting_count.dec();
            let _ = task.await;
        };
        this.sink.waiting_count.inc();
        sink.as_mut()
            .start_send((d, Box::new(Box::pin(task))))
            .map_err(|_e| {
                this.sink.waiting_count.dec();
                Error::SendError(ErrorType::Closed(None))
            })?;
        Poll::Ready(Ok(()))
    }
}

pub struct TrySpawner<'a, Item, Tx, G, D> {
    inner: Spawner<'a, Item, Tx, G, D>,
}

impl<'a, Item, Tx, G, D> Unpin for TrySpawner<'a, Item, Tx, G, D> {}

impl<'a, Item, Tx, G> TrySpawner<'a, Item, Tx, G, ()>
    where
        Tx: Clone + Unpin + Sink<((), TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    #[inline]
    pub fn group(self, name: G) -> TryGroupSpawner<'a, Item, Tx, G>
        where
            Item: Future + Send + 'static,
            Item::Output: Send + 'static,
    {
        let fut = TryGroupSpawner::new(self.inner, name);
        assert_future::<Result<(), _>, _>(fut)
    }
}

impl<'a, Item, Tx, G, D> TrySpawner<'a, Item, Tx, G, D>
    where
        Tx: Clone + Unpin + Sink<(D, TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    #[inline]
    pub(crate) fn new(sink: &'a TaskExecQueue<Tx, G, D>, item: Item, d: D) -> Self {
        Self {
            inner: Spawner {
                sink,
                item: Some(item),
                d: Some(d),
            },
        }
    }

    #[inline]
    pub async fn result(mut self) -> Result<Item::Output, Error<Item>>
        where
            Item: Future + Send + 'static,
            Item::Output: Send + 'static,
    {
        if self.inner.sink.is_full() {
            return Err(Error::TrySendError(ErrorType::Full(self.inner.item.take())));
        }
        self.inner.result().await
    }
}

impl<Item, Tx, G, D> Future for TrySpawner<'_, Item, Tx, G, D>
    where
        Item: Future + Send + 'static,
        Item::Output: Send + 'static,
        Tx: Clone + Unpin + Sink<(D, TaskType)> + Send + Sync + 'static,
        G: Hash + Eq + Clone + Debug + Send + Sync + 'static,
{
    type Output = Result<(), Error<Item>>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        if this.inner.sink.is_full() {
            return Poll::Ready(Err(Error::TrySendError(ErrorType::Full(
                this.inner.item.take(),
            ))));
        }
        this.inner.poll(cx)
    }
}