jobflow 0.3.0

Executes jobs in order
Documentation
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
//! A task within the backend

use crate::actions::{Action, BoxAction, Runnable, action};
use crate::backend::disjointed::Disjointed;
use crate::backend::flow_backend::{FlowBackendError, FlowBackendInput};
use crate::backend::funnel::BackendFunnel;
use crate::backend::recv_promise::RecvPromise;
use crate::backend::reusable;
use crate::backend::reusable::Reusable;
use crate::private::Sealed;
use crate::sync::promise::{BoxPromise, PollPromise, Promise, PromiseExt, PromiseSet};
use crate::sync::promise::{IntoPromise, MapPromise};
use crossbeam::channel::{Receiver, RecvError, SendError, Sender, bounded};
use fortuples::fortuples;
use std::any::{Any, TypeId, type_name};
use std::collections::HashSet;
use std::fmt::{Debug, Display, Formatter};
use std::marker::PhantomData;
use std::num::NonZero;
use std::sync::atomic::{AtomicUsize, Ordering};
use thiserror::Error;
use tracing::trace;

static JOB_ID_COUNTER: AtomicUsize = AtomicUsize::new(1);

/// A task id
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct JobId(NonZero<usize>);

impl Display for JobId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "T#{}", self.0)
    }
}

impl JobId {
    /// Creates a new task id
    pub(crate) fn new() -> Self {
        let id = JOB_ID_COUNTER.fetch_add(1, Ordering::SeqCst);
        if id == 0 {
            panic!("task ID overflowed");
        }
        let non_zero = NonZero::new(id).expect("Should never be zero");
        JobId(non_zero)
    }
}

/// This is the data that is used
pub type Data = Box<dyn Any + Send>;

/// A backend task
pub struct BackendJob {
    id: JobId,
    nickname: String,
    input: Input,
    output: Output,
    action_input_sender: Sender<Data>,
    action_output_receiver: Receiver<Data>,

    action: BoxAction<'static, (), ()>,
}

impl Debug for BackendJob {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BackendTask")
            .field("id", &self.id)
            .field("nickname", &self.nickname)
            .finish()
    }
}

impl BackendJob {
    pub fn new<A, I, O>(
        name: impl AsRef<str>,
        output: impl AsOutputFlavor<Data = O>,
        action: A,
    ) -> BackendJob
    where
        I: Send + 'static,
        O: Send + 'static,
        A: Action<Input = I, Output = O> + 'static,
    {
        let id = JobId::new();
        let input = action.input_flavor();
        let nickname = name.as_ref().to_owned();
        let (input_sender, input_receiver) = bounded::<Data>(1);
        let (output_sender, output_receiver) = bounded::<Data>(1);

        let erased_action: BoxAction<(), ()> = match input {
            InputFlavor::None => {
                assert_eq!(
                    TypeId::of::<I>(),
                    TypeId::of::<()>(),
                    "illegal input type for flavor {:?}",
                    input
                );
                let mut action = action;
                let safe_action = crate::actions::action(move |_: ()| -> O {
                    let fake = unsafe {
                        assert_eq!(size_of::<I>(), 0, "input must have zero size");
                        let fake: I = std::mem::zeroed();
                        fake
                    };
                    action.apply(fake)
                });
                Box::new(safe_action.chain(SendOutputAction::new(output_sender)))
            }
            InputFlavor::Single => Box::new(
                ReceiveInputAction::new(input_receiver)
                    .chain(action)
                    .chain(SendOutputAction::new(output_sender)),
            ),
            InputFlavor::Funnel => {
                todo!("Directly creating funnel input not supported")
            }
        };
        let output = output.to_output(id);

        Self {
            id,
            nickname,
            input: Input::new::<I>(input),
            output,
            action_input_sender: input_sender,
            action_output_receiver: output_receiver,
            action: erased_action,
        }
    }

    /// Gets the id of this task
    pub fn id(&self) -> JobId {
        self.id
    }

    /// Gets the dependencies for this task
    pub fn dependencies(&self) -> &HashSet<JobId> {
        self.input.dependencies()
    }

    /// Runs this task
    pub fn run(&mut self) -> Result<(), JobError> {
        if self.input.input_required() {
            match std::mem::replace(&mut self.input.kind, InputKind::None) {
                InputKind::None => return Err(JobError::NoInput),
                InputKind::Single(s) => {
                    let data = s.try_get().map_err(|_| JobError::InputNotReady)?;
                    self.action_input_sender.send(data)?;
                }
                InputKind::Funnel(m) => {
                    let promise = m.into_promise();
                    let data = promise.try_get().map_err(|_| JobError::InputNotReady)?;
                    self.action_input_sender.send(Box::new(data) as Data)?;
                }
            }
        } else if !matches!(self.input.kind, InputKind::None) {
            return Err(JobError::UnexpectedInput);
        }

        self.action.run();

        let output_receiver = self.action_output_receiver.recv()?;

        self.output
            .set_output_fn
            .take()
            .expect("can not set output multiple times")
            .accept(output_receiver)?;

        Ok(())
    }

    /// Turns this into a funnel input
    pub fn make_funnel<
        T: Send + 'static,
        I: FromIterator<T> + IntoIterator<Item = T, IntoIter: Send> + Send + 'static,
    >(
        &mut self,
    ) -> Result<(), JobError> {
        if !matches!(self.input.flavor, InputFlavor::Single) {
            return Err(JobError::UnexpectedInput);
        }
        if TypeId::of::<I>() != self.input.input_ty {
            return Err(JobError::UnexpectedType {
                expected: self.input.input_ty_str,
                received: type_name::<T>(),
                comment: None,
            });
        }
        self.input.flavor = InputFlavor::Funnel;
        let mut funnel = BackendFunnel::new();
        match std::mem::replace(&mut self.input.kind, InputKind::None) {
            InputKind::None => {}
            InputKind::Single(input) => {
                funnel.insert_iter(input.map(|data| {
                    // this is actually I
                    let d = *data.downcast::<I>().unwrap_or_else(|b| {
                        panic!("failed to downcast {b:?} to `{}`", type_name::<I>())
                    });
                    d.into_iter().map(|i| Box::new(i) as Data)
                }));
            }
            InputKind::Funnel(_) => {
                unreachable!()
            }
        }
        let action = std::mem::replace(&mut self.action, Box::new(action(|_| {})));
        let (new_sender, new_receiver) = bounded::<Data>(1);
        let old_sender = std::mem::replace(&mut self.action_input_sender, new_sender);

        self.action =
            Box::new(ReceiveFunnelInputAction::<T, I>::new(new_receiver, old_sender).chain(action));
        self.input.kind = InputKind::Funnel(funnel);
        Ok(())
    }

    /// Turns this into a disjointed output
    pub fn make_disjointed<T: Send + 'static>(&mut self) -> Result<(), JobError> {
        if TypeId::of::<Vec<T>>() != self.output.output_ty {
            return Err(JobError::UnexpectedType {
                expected: self.output.output_ty_str,
                received: type_name::<T>(),
                comment: None,
            });
        }
        self.output.make_disjointed::<T>()?;

        // let action = std::mem::replace(&mut self.action, Box::new(action(|_| {})));
        // let (new_sender, new_receiver) = bounded::<Data>(1);
        // let old_receiver = std::mem::replace(&mut self.action_output_receiver, new_receiver);
        //
        // self.action =
        //     Box::new(action.chain(SendDisjointedOutputAction::<T>::new(old_receiver, new_sender)));

        Ok(())
    }

    /// Gets the input for this task
    #[must_use]
    pub fn input_mut(&mut self) -> &mut Input {
        &mut self.input
    }

    /// Gets the input for this task
    #[must_use]
    pub fn input(&self) -> &Input {
        &self.input
    }

    /// Gets the output of this task
    #[must_use]
    pub fn output_mut(&mut self) -> &mut Output {
        &mut self.output
    }

    /// Gets the output of this task
    #[must_use]
    pub fn output(&self) -> &Output {
        &self.output
    }

    pub fn nickname(&self) -> &str {
        &self.nickname
    }
}

struct ReceiveInputAction<T> {
    receiver: Receiver<Data>,
    _marker: PhantomData<T>,
}

impl<T> ReceiveInputAction<T> {
    fn new(receiver: Receiver<Data>) -> Self {
        Self {
            receiver,
            _marker: PhantomData,
        }
    }
}

impl<T: Send + 'static> Action for ReceiveInputAction<T> {
    type Input = ();
    type Output = T;

    fn apply(&mut self, _: Self::Input) -> Self::Output {
        let i = self
            .receiver
            .recv()
            .expect("failed to receive input")
            .downcast::<T>()
            .unwrap_or_else(|e| {
                if let Some(s) = e.downcast_ref::<Vec<Data>>() {
                    panic!(
                        "failed to downcast vector of data {:?} ({:?}) to `{}` while receiving input. Perhaps you need to downcast it's elements",
                        s,
                        (*s).type_id(),
                        type_name::<T>()
                    )
                }  else {
                    panic!(
                        "failed to downcast {:?} ({:?}) to `{}` while receiving input",
                        e,
                        (*e).type_id(),
                        type_name::<T>()
                    )
                }
            });

        *i
    }

    fn input_flavor(&self) -> InputFlavor {
        InputFlavor::None
    }
}

struct ReceiveFunnelInputAction<T, I: FromIterator<T>> {
    receiver: Receiver<Data>,
    sender: Sender<Data>,
    _marker: PhantomData<(T, I)>,
}

impl<T, I: FromIterator<T>> ReceiveFunnelInputAction<T, I> {
    fn new(receiver: Receiver<Data>, sender: Sender<Data>) -> Self {
        Self {
            receiver,
            sender,
            _marker: PhantomData,
        }
    }
}

impl<T: Send + 'static, I: 'static + FromIterator<T> + Send> Action
    for ReceiveFunnelInputAction<T, I>
{
    type Input = ();
    type Output = ();

    fn apply(&mut self, _: Self::Input) -> Self::Output {
        let i = *self
            .receiver
            .recv()
            .expect("failed to receive input")
            .downcast::<Vec<Data>>()
            .unwrap_or_else(|e| panic!("failed to downcast {:?} to `{}`", e, type_name::<T>()));

        let rebuilt = i
            .into_iter()
            .map(|data| {
                *data.downcast::<T>().unwrap_or_else(|e| {
                    panic!("failed to downcast {e:?} to `{}`", type_name::<T>())
                })
            })
            .collect::<I>();
        self.sender.send(Box::new(rebuilt) as Data).unwrap();
    }

    fn input_flavor(&self) -> InputFlavor {
        InputFlavor::None
    }
}

struct SendOutputAction<T> {
    sender: Sender<Data>,
    _marker: PhantomData<T>,
}

impl<T> SendOutputAction<T> {
    fn new(sender: Sender<Data>) -> Self {
        Self {
            sender,
            _marker: PhantomData,
        }
    }
}

impl<T: Send + 'static> Action for SendOutputAction<T> {
    type Input = T;
    type Output = ();

    fn apply(&mut self, input: Self::Input) -> Self::Output {
        let data = Box::new(input) as Data;
        self.sender.send(data).expect("failed to send data");
    }

    fn input_flavor(&self) -> InputFlavor {
        InputFlavor::Single
    }
}

/// Input flavor for this task
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum InputFlavor {
    None,
    Single,
    Funnel,
}

/// An input source
pub trait InputSource<T> {
    type Data;

    fn use_as_input_source(&mut self, other: T) -> Result<(), JobError>;
}

/// Task input data
#[derive(Debug)]
pub struct Input {
    input_ty: TypeId,
    input_ty_str: &'static str,
    task_dependencies: HashSet<JobId>,
    pub(super) flavor: InputFlavor,
    pub(super) kind: InputKind,
}

impl Input {
    fn new<T: 'static>(input_flavor: InputFlavor) -> Self {
        let ty = TypeId::of::<T>();
        Self {
            input_ty: ty,
            input_ty_str: type_name::<T>(),
            task_dependencies: HashSet::new(),
            flavor: input_flavor,
            kind: match input_flavor {
                InputFlavor::Funnel => InputKind::Funnel(BackendFunnel::new()),
                _ => InputKind::None,
            },
        }
    }

    fn input_required(&self) -> bool {
        match self.flavor {
            InputFlavor::None => false,
            InputFlavor::Single | InputFlavor::Funnel => true,
        }
    }

    #[cfg(test)]
    pub(super) fn check_type<T: 'static>(&self) -> Result<(), JobError> {
        if TypeId::of::<T>() != self.input_ty {
            Err(JobError::UnexpectedType {
                expected: self.input_ty_str,
                received: type_name::<T>(),
                comment: None,
            })
        } else {
            Ok(())
        }
    }

    /// Gets the list of task id dependencies for this task
    pub fn dependencies(&self) -> &HashSet<JobId> {
        &self.task_dependencies
    }

    /// Sets an explicit task ordering
    pub fn depends_on(&mut self, task_id: JobId) {
        self.task_dependencies.insert(task_id);
    }

    /// Sets an explicit task ordering
    #[inline]
    pub fn depends_on_all<I: IntoIterator<Item = JobId>>(&mut self, task_ids: I) {
        task_ids.into_iter().for_each(|task_id| {
            self.depends_on(task_id);
        })
    }

    pub fn set_source<T: 'static + Send, S>(&mut self, source: S) -> Result<(), JobError>
    where
        Self: InputSource<S, Data = T>,
    {
        self.use_as_input_source(source)
    }

    pub fn input_ty(&self) -> TypeId {
        self.input_ty
    }
}

pub trait AsOutputFlavor: Sealed {
    type Data: 'static;

    fn to_output(self, id: JobId) -> Output;
}

pub struct SingleOutput<T: 'static + Send>(PhantomData<T>);

impl<T: 'static + Send> SingleOutput<T> {
    /// Create a new single output
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

impl<T: 'static + Send> Sealed for SingleOutput<T> {}

impl<T: 'static + Send> AsOutputFlavor for SingleOutput<T> {
    type Data = T;

    fn to_output(self, id: JobId) -> Output {
        let (send, receive) = bounded::<Data>(1);
        let promise = RecvPromise::new(receive);

        let f = move |data: Data| -> Result<(), JobError> {
            send.send(data)?;
            Ok(())
        };

        Output {
            task_id: id,
            output_ty: TypeId::of::<T>(),
            output_ty_str: type_name::<T>(),
            flavor: OutputFlavor::Single,
            kind: OutputKind::Once(Some(Box::new(promise))),
            set_output_fn: Some(SetOutputFn::new(f)),
        }
    }
}

pub struct NoOutput;

impl Sealed for NoOutput {}
impl AsOutputFlavor for NoOutput {
    type Data = ();

    fn to_output(self, id: JobId) -> Output {
        Output {
            task_id: id,
            output_ty: TypeId::of::<()>(),
            output_ty_str: type_name::<()>(),
            flavor: OutputFlavor::None,
            kind: OutputKind::None,
            set_output_fn: None,
        }
    }
}

pub struct ReusableOutput<T: 'static + Send + Clone>(PhantomData<T>);

impl<T: 'static + Send + Clone> Sealed for ReusableOutput<T> {}

impl<T: 'static + Send + Clone> AsOutputFlavor for ReusableOutput<T> {
    type Data = T;

    fn to_output(self, id: JobId) -> Output {
        let (promise, f) = create_reusable::<T>();

        Output {
            task_id: id,
            output_ty: TypeId::of::<T>(),
            output_ty_str: type_name::<T>(),
            flavor: OutputFlavor::Reusable,
            kind: OutputKind::Reusable(promise),
            set_output_fn: Some(SetOutputFn::new(f)),
        }
    }
}

impl<T: 'static + Send + Clone> ReusableOutput<T> {
    /// Create a new reusable output
    #[allow(unused)]
    pub const fn new() -> Self {
        Self(PhantomData)
    }
}

#[derive(Debug)]
pub(super) enum InputKind {
    None,
    Single(BoxPromise<'static, Data>),
    Funnel(BackendFunnel),
}

#[derive(Debug, Copy, Clone)]
pub enum OutputFlavor {
    None,
    Single,
    Reusable,
    Disjointed,
}

pub struct Output {
    task_id: JobId,
    output_ty: TypeId,
    output_ty_str: &'static str,
    pub(crate) flavor: OutputFlavor,
    pub(crate) kind: OutputKind,
    set_output_fn: Option<SetOutputFn>,
}

impl Output {
    pub fn make_reusable<T: Send + Clone + 'static>(&mut self) -> Result<(), JobError> {
        if TypeId::of::<T>() != self.output_ty {
            return Err(JobError::UnexpectedType {
                expected: self.output_ty_str,
                received: type_name::<T>(),
                comment: None,
            });
        } else if matches!(self.kind, OutputKind::Once(None)) {
            return Err(JobError::OutputAlreadyUsed);
        }

        self.flavor = OutputFlavor::Reusable;

        let (promise, f) = create_reusable::<T>();

        self.set_output_fn = Some(SetOutputFn::new(f));
        self.kind = OutputKind::Reusable(promise);
        Ok(())
    }

    pub fn make_disjointed<T: Send + 'static>(&mut self) -> Result<(), JobError> {
        if TypeId::of::<Vec<T>>() != self.output_ty {
            return Err(JobError::UnexpectedType {
                expected: self.output_ty_str,
                received: type_name::<T>(),
                comment: format!(
                    "To make disjointed, the output must have been declared as type `Vec<{}>`",
                    type_name::<T>()
                )
                .into(),
            });
        } else if matches!(self.kind, OutputKind::Once(None)) {
            return Err(JobError::OutputAlreadyUsed);
        }

        self.flavor = OutputFlavor::Disjointed;

        let (disjointed, f) = create_disjointed::<T>();
        self.set_output_fn = Some(SetOutputFn::new(f));
        self.kind = OutputKind::Disjointed(disjointed);

        Ok(())
    }

    pub fn output_ty(&self) -> TypeId {
        self.output_ty
    }
}

/// This creates a reusable that appears a
fn create_reusable<T: Send + Clone + 'static>() -> (
    Reusable<'static, Data>,
    impl FnOnce(Data) -> Result<(), JobError> + Send + 'static,
) {
    let (send, receive) = bounded::<T>(1);
    let promise: Reusable<T> = Reusable::new(Box::new(RecvPromise::new(receive)));

    let f = move |data: Data| -> Result<(), JobError> {
        let as_t = *data.downcast::<T>().expect("failed to downcast to");
        send.send(as_t)
            .map_err(|SendError(e)| SendError(Box::new(e) as Data))?;
        Ok(())
    };
    (promise.into_data(), f)
}

fn create_disjointed<T: Send + 'static>() -> (
    Disjointed<'static, Data>,
    impl FnOnce(Data) -> Result<(), JobError>,
) {
    let (send, receive) = bounded::<Vec<T>>(1);
    let inner = RecvPromise::new(receive)
        .map(|data| data.into_iter().map(|d| Box::new(d) as Data).collect());

    let disjointed: Disjointed<'static, Data, _> =
        Disjointed::new(Box::new(inner) as BoxPromise<_>);
    let f = move |data: Data| -> Result<(), JobError> {
        let as_t = *data
            .downcast::<Vec<T>>()
            .expect("failed to downcast to vector");
        send.send(as_t)
            .map_err(|SendError(e)| SendError(Box::new(e) as Data))?;
        Ok(())
    };

    (disjointed, f)
}

struct SetOutputFn(Box<dyn FnOnce(Data) -> Result<(), JobError> + Send>);

impl SetOutputFn {
    fn new<F: FnOnce(Data) -> Result<(), JobError> + Send + 'static>(f: F) -> Self {
        let boxed = Box::new(f) as Box<dyn FnOnce(Data) -> Result<(), JobError> + Send>;
        Self(boxed)
    }

    fn accept(self, data: Data) -> Result<(), JobError> {
        (self.0)(data)
    }
}

impl InputSource<&mut Output> for Input {
    type Data = Data;

    fn use_as_input_source(&mut self, other: &mut Output) -> Result<(), JobError> {
        match (self.flavor, other.flavor) {
            (InputFlavor::Single, OutputFlavor::Reusable) => {
                let OutputKind::Reusable(reusable) = &mut other.kind else {
                    panic!(
                        "flavor and kind mismatch. flavor = {:?}, kind = {:?}",
                        other.flavor, other.kind
                    );
                };

                self.kind = InputKind::Single(Box::new(reusable.clone().into_promise()));
                self.depends_on(other.task_id);
                Ok(())
            }
            (InputFlavor::Single, OutputFlavor::Single) => {
                let OutputKind::Once(once) = &mut other.kind else {
                    panic!(
                        "flavor and kind mismatch. flavor = {:?}, kind = {:?}",
                        other.flavor, other.kind
                    );
                };
                self.depends_on(other.task_id);
                match once.take() {
                    None => Err(JobError::OutputCanNotBeReused),
                    Some(some) => {
                        self.kind = InputKind::Single(some);
                        Ok(())
                    }
                }
            }
            (InputFlavor::Funnel, OutputFlavor::Single) => {
                let OutputKind::Once(once) = &mut other.kind else {
                    panic!(
                        "flavor and kind mismatch. flavor = {:?}, kind = {:?}",
                        other.flavor, other.kind
                    );
                };
                let InputKind::Funnel(funnel) = &mut self.kind else {
                    panic!(
                        "flavor and kind mismatch. flavor = {:?}, kind = {:?}",
                        self.flavor, self.kind
                    );
                };

                match once.take() {
                    None => Err(JobError::OutputCanNotBeReused),
                    Some(some) => {
                        funnel.insert(some);
                        self.depends_on(other.task_id);
                        Ok(())
                    }
                }
            }
            (InputFlavor::Funnel, OutputFlavor::Reusable) => {
                let OutputKind::Reusable(reusable) = &mut other.kind else {
                    panic!(
                        "flavor and kind mismatch. flavor = {:?}, kind = {:?}",
                        other.flavor, other.kind
                    );
                };
                let InputKind::Funnel(funnel) = &mut self.kind else {
                    panic!(
                        "flavor and kind mismatch. flavor = {:?}, kind = {:?}",
                        self.flavor, self.kind
                    );
                };

                funnel.insert(reusable.clone());
                self.depends_on(other.task_id);
                Ok(())
            }
            (i, o) => Err(JobError::OutputCanNotBeUsedAsInput {
                output_flavor: o,
                input_flavor: i,
            }),
        }
    }
}

fortuples! {
    #[tuples::min_size(1)]
    impl InputSource<#Tuple> for Input
    where
        #(#Member: OutputWithType<T: Send + 'static>,)*
    {
        type Data = (#(#Member::T,)*);

        fn use_as_input_source(&mut self, mut other: #Tuple) -> Result<(), JobError> {
            let (#(#Member,)*) = (#(#other.as_output(),)*);
            let task_ids = [#(#Member.task_id),*];
            let promises = || -> Result<_, JobError> {
                let promise_set = [#(#Member,)*]
                    .iter_mut()
                    .map(|o| match &o.kind {
                        OutputKind::None => Err(JobError::OutputCanNotBeUsedAsInput {
                            output_flavor: OutputFlavor::None,
                            input_flavor: self.flavor,
                        }),
                        OutputKind::Once(None) => Err(JobError::OutputAlreadyUsed),
                        OutputKind::Once(_) | OutputKind::Reusable(_) => Ok(o.into_promise()),
                        OutputKind::Disjointed(_disjoints) => {
                            todo!("disjointed can be used as input if not's been partially used")
                        }
                    })
                    .collect::<Result<PromiseSet<_>, JobError >>()?;

                Ok(promise_set
                    .into_promise()
                    .map(|promised: Vec<Data>| {
                        trace!("converting {promised:?} to ({})", [#(type_name::<#Member::T>()),*].join(", "));
                        let [#(#Member,)*] = promised.try_into().expect("failed to convert to array");
                        let ret = (
                            #(
                                *#Member.downcast::<#Member::T>().unwrap(),
                            )*
                        );
                        ret
                    }))
            };


            match self.flavor {
                InputFlavor::None => Err(JobError::OutputCanNotBeUsedAsInput {
                    output_flavor: OutputFlavor::None,
                    input_flavor: self.flavor,
                }),
                InputFlavor::Single => {
                    let promise = promises()?;
                    self.depends_on_all(task_ids);
                    self.kind = InputKind::Single(Box::new(promise.map(|p: Self::Data| Box::new(p) as Data)));
                    Ok(())
                }
                InputFlavor::Funnel => {
                    let promise = promises()?;
                    self.depends_on_all(task_ids);
                    let InputKind::Funnel(funnel) = &mut self.kind else {
                        unreachable!()
                    };
                    funnel.insert(promise.map(|t| Box::new(t) as Data));
                    Ok(())
                }
            }
        }
    }


}

// fortuples! {
//     #[tuples::min_size(1)]
//     impl InputSource<(PhantomData<#Tuple>, [&mut Output; #len(Tuple)])> for Input
//     where
//         #(#Member: OutputWithType,)*
//     {
//         type Data = #Tuple;
//
//         fn use_as_input_source(&mut self, other: (PhantomData<#Tuple>, [&mut Output; #len(Tuple)])) -> Result<(), TaskError> {
//             todo!()
//         }
//     }
// }

impl InputSource<&mut FlowBackendInput> for Input {
    type Data = Data;

    fn use_as_input_source(&mut self, other: &mut FlowBackendInput) -> Result<(), JobError> {
        match self.flavor {
            InputFlavor::None => Err(JobError::UnexpectedInput),
            InputFlavor::Single => {
                self.kind = InputKind::Single(Box::new(other.take_promise()?));
                Ok(())
            }
            InputFlavor::Funnel => {
                let InputKind::Funnel(funnel) = &mut self.kind else {
                    panic!(
                        "flavor and kind mismatch. flavor = {:?}, kind = {:?}",
                        self.flavor, self.kind
                    );
                };
                funnel.insert(other.take_promise()?);
                Ok(())
            }
        }
    }
}

pub trait OutputWithType {
    type T;

    fn as_output(&mut self) -> &mut Output;
}

pub struct TypedOutput<'a, T>(&'a mut Output, PhantomData<T>);

impl<'a, T> TypedOutput<'a, T> {
    pub fn new(output: &'a mut Output) -> Self {
        TypedOutput(output, PhantomData)
    }
}

impl<T> OutputWithType for TypedOutput<'_, T> {
    type T = T;

    fn as_output(&mut self) -> &mut Output {
        self.0
    }
}

pub enum TaskOutputPromise {
    Once(BoxPromise<'static, Data>),
    Reusable(reusable::IntoPromise<'static, Data, BoxPromise<'static, Data>>),
}

impl Promise for TaskOutputPromise {
    type Output = Data;

    fn poll(&mut self) -> PollPromise<Self::Output> {
        match self {
            TaskOutputPromise::Once(o) => o.poll(),
            TaskOutputPromise::Reusable(r) => Promise::poll(r),
        }
    }
}

impl IntoPromise for &mut Output {
    type Output = Data;
    type IntoPromise = TaskOutputPromise;

    fn into_promise(self) -> Self::IntoPromise {
        match &mut self.kind {
            OutputKind::None => {
                panic!("can not be used as a promise")
            }
            OutputKind::Once(o) => {
                let o = o.take().expect("output already used");
                TaskOutputPromise::Once(o)
            }
            OutputKind::Reusable(s) => {
                let cloned = s.clone();
                TaskOutputPromise::Reusable(cloned.into_promise())
            }
            OutputKind::Disjointed(_) => {
                panic!("Can not infallibly made into a promise")
            }
        }
    }
}

#[derive(Debug)]
pub(crate) enum OutputKind {
    /// no output
    None,
    /// used when the output can only be used once
    Once(Option<BoxPromise<'static, Data>>),
    /// Used when the output can be used multiple times
    Reusable(Reusable<'static, Data>),
    /// Disjointed output
    Disjointed(Disjointed<'static, Data>),
}

#[allow(unused)]
impl OutputKind {
    fn as_reusable(&self) -> Option<&Reusable<'static, Data>> {
        if let Self::Reusable(reusable) = self {
            Some(reusable)
        } else {
            None
        }
    }
    fn as_reusable_mut(&mut self) -> Option<&mut Reusable<'static, Data>> {
        if let Self::Reusable(reusable) = self {
            Some(reusable)
        } else {
            None
        }
    }
    fn as_disjointed(&self) -> Option<&Disjointed<'static, Data>> {
        if let Self::Disjointed(d) = self {
            Some(d)
        } else {
            None
        }
    }
    fn as_disjointed_mut(&mut self) -> Option<&mut Disjointed<'static, Data>> {
        if let Self::Disjointed(d) = self {
            Some(d)
        } else {
            None
        }
    }
}

/// An error occurred while executing a job
#[derive(Debug, Error)]
pub enum JobError {
    #[error("Output can not be re-used")]
    OutputCanNotBeReused,
    #[error("The input for this task is yet ready")]
    InputNotReady,
    #[error("No input is expected for this task")]
    NoInput,
    #[error("This task did not expect an input")]
    UnexpectedInput,
    #[error("Can not set this as reusable because output was already used")]
    OutputAlreadyUsed,
    #[error(transparent)]
    SendError(#[from] SendError<Data>),
    #[error(transparent)]
    RecvError(#[from] RecvError),

    #[error("The input for this task was already set")]
    InputAlreadySet,
    #[error("Unexpected type (expected: `{expected}`, actual: `{received}`){}", comment.as_ref().map(|s| format!(": {s}")).unwrap_or(String::new()))]
    UnexpectedType {
        expected: &'static str,
        received: &'static str,
        comment: Option<String>,
    },
    #[error("{output_flavor:?} can not be used as an input for {input_flavor:?}")]
    OutputCanNotBeUsedAsInput {
        output_flavor: OutputFlavor,
        input_flavor: InputFlavor,
    },
    #[error(transparent)]
    FlowBackendError(Box<FlowBackendError>),
}

impl From<FlowBackendError> for JobError {
    fn from(value: FlowBackendError) -> Self {
        JobError::FlowBackendError(Box::new(value))
    }
}

#[cfg(test)]
pub(crate) mod test_fixtures {
    use crate::backend::job::{Data, Input, InputFlavor, InputKind, InputSource, JobError};
    use crate::sync::promise::MapPromise;
    use crate::sync::promise::{BoxPromise, Just};
    use std::any::{TypeId, type_name};

    /// Used for mocking a task input
    pub struct MockTaskInput<T>(pub T);

    impl<T> MockTaskInput<T> {
        pub fn into_inner(self) -> T {
            self.0
        }
    }

    impl<T: Send + 'static> InputSource<MockTaskInput<T>> for Input {
        type Data = T;

        fn use_as_input_source(&mut self, other: MockTaskInput<T>) -> Result<(), JobError> {
            self.check_type::<T>()?;
            let as_promise = Just::new(other.into_inner()).map(|t| Box::new(t) as Data);
            match (self.flavor, &mut self.kind) {
                (InputFlavor::None, _) => return Err(JobError::UnexpectedInput),
                (InputFlavor::Single, InputKind::None) => {
                    if TypeId::of::<T>() != self.input_ty {
                        return Err(JobError::UnexpectedType {
                            expected: self.input_ty_str,
                            received: type_name::<T>(),
                            comment: None,
                        });
                    }

                    let promise = Box::new(as_promise) as BoxPromise<'static, Data>;
                    self.kind = InputKind::Single(promise);
                }
                (InputFlavor::Single, _) => return Err(JobError::InputAlreadySet),
                (InputFlavor::Funnel, InputKind::Funnel(funnel)) => {
                    funnel.insert(as_promise);
                }
                (InputFlavor::Funnel, _) => {
                    panic!("funnel flavor has no funnel kind")
                }
            }
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::actions::action;
    use crate::backend::flow_backend::FlowBackendOutput;
    use crate::backend::job::test_fixtures::MockTaskInput;
    use crate::sync::promise::GetPromise;
    use std::thread;

    #[test]
    fn test_task_id() {
        let JobId(id) = JobId::new();
        assert!(id.get() > 0);
    }

    #[test]
    fn test_create_task() {
        let mut task = BackendJob::new(
            "task",
            SingleOutput::new(),
            action(|i: i32| {
                println!("{}", i);
                i.to_string()
            }),
        );
        task.input_mut()
            .set_source(MockTaskInput(12))
            .expect("failed to set input");
        task.run().expect("failed to run task");
    }

    #[test]
    fn test_no_input_task() {
        let (tx, rx) = bounded::<&str>(1);
        let mut task = BackendJob::new(
            "task",
            SingleOutput::new(),
            action(move || {
                tx.send("Hello, world").expect("failed to send input");
            }),
        );
        task.run().expect("failed to run task");
        let output = rx.try_recv().expect("failed to receive output");
        assert_eq!(output, "Hello, world");
    }

    #[test]
    fn test_flow_input_to_task() {
        let mut input = FlowBackendInput::default();
        let mut task = BackendJob::new(
            "task",
            SingleOutput::new(),
            action(move |i: i32| {
                assert_eq!(i, 32);
            }),
        );
        task.input_mut()
            .set_source(&mut input)
            .expect("failed to set input");
        input.send(Box::new(32_i32)).expect("failed to send input");
        task.run().expect("failed to run task");
    }

    #[test]
    fn test_flow_output_from_task() {
        let mut output = FlowBackendOutput::default();
        let mut task = BackendJob::new("task", SingleOutput::new(), action(move || 32_i32));
        output
            .set_source(task.output_mut())
            .expect("failed to set output");

        task.run().expect("failed to run task");
        let t = *output
            .get()
            .downcast::<i32>()
            .expect("failed to downcast output");
        assert_eq!(t, 32_i32);
    }

    #[test]
    fn test_make_output_disjointed() {
        let mut task = BackendJob::new("task", SingleOutput::new(), action(move || vec![1, 2, 3]));
        task.make_disjointed::<char>()
            .expect_err("should fail to make disjoint");
        task.make_disjointed::<i32>()
            .expect("failed to make disjoint");
    }

    #[test]
    fn test_disjointed_flow_output() {
        let mut task1 =
            BackendJob::new("task1", SingleOutput::new(), action(move || vec![1, 2, 3]));
        task1
            .make_disjointed::<i32>()
            .expect("failed to make disjoint");
        let disjoint = task1
            .output_mut()
            .kind
            .as_disjointed_mut()
            .expect("must be disjoint");

        let mut task2 = BackendJob::new("task2", SingleOutput::new(), action(move |i: i32| {}));
        task2
            .input_mut()
            .set_source(disjoint.get(0).unwrap())
            .expect("failed to set");

        let mut task3 = BackendJob::new(
            "task2",
            SingleOutput::new(),
            action(move |i: Vec<i32>| {
                assert_eq!(i.len(), 2);
            }),
        );
        task3
            .input_mut()
            .set_source(disjoint.get_range(1..).unwrap().downcast_elements::<i32>())
            .expect("failed to set");

        task1.run().expect("failed to run task1");
        task2.run().expect("failed to run task2");
        task3.run().expect("failed to run task3");
    }

    #[test]
    fn test_chain_task() {
        let mut task1 = BackendJob::new("task1", SingleOutput::new(), action(|i: i32| i * i));
        let mut task2 = BackendJob::new(
            "task2",
            SingleOutput::new(),
            action(|i: i32| {
                println!("{}", i);
                i.to_string()
            }),
        );
        task1
            .input_mut()
            .set_source(MockTaskInput(12))
            .expect("failed to set input");
        task2
            .input_mut()
            .set_source(task1.output_mut())
            .expect("failed to set output for task 2");
        task1.run().expect("failed to run task1");
        thread::spawn(move || {
            task2.run().expect("failed to run task2");
        })
        .join()
        .expect("failed to join thread");
    }

    #[test]
    fn test_funnel_task() {
        let mut task1 = BackendJob::new("task1", SingleOutput::new(), action(|i: i32| i * i));
        let mut task2 = BackendJob::new("task2", SingleOutput::new(), action(|i: i32| i * i * i));
        let mut task3 = BackendJob::new(
            "task3",
            SingleOutput::new(),
            action(|i: Vec<i32>| {
                assert_eq!(i, [9, 27]);
                i.iter().sum::<i32>()
            }),
        );
        task3
            .make_funnel::<i32, Vec<i32>>()
            .expect("failed to create funnel");
        task1
            .input_mut()
            .set_source(MockTaskInput(3))
            .expect("failed to set input");
        task2
            .input_mut()
            .set_source(MockTaskInput(3))
            .expect("failed to set input for task 2");
        task3
            .input_mut()
            .set_source(task1.output_mut())
            .expect("failed to set input for task 3");
        task3
            .input_mut()
            .set_source(task2.output_mut())
            .expect("failed to set input for task 3");

        task1.run().expect("failed to run task1");
        task2.run().expect("failed to run task2");
        task3.run().expect("failed to run task3");
    }
}