flo_scene 0.2.0

Entity-messaging system for composing large programs from small programs
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
//!
//! Sometimes, it's necessary to connect two programs where one produces a different kind
//! of output to the input. Filters provide a general way to map one stream of messages
//! to another.
//!
//! This isn't needed for the basic scene functionality: the same thing can be done by
//! creating a subprogram to do the conversion, but having filters built in like this makes
//! it much easier to create adapters between programs.
//!

use flo_scene::*;
use flo_scene::programs::*;

use futures::prelude::*;
use futures::future::{select};
use futures::executor;
use futures_timer::*;

use serde::*;

use std::time::{Duration};
use std::sync::*;
use std::sync::atomic::{AtomicUsize, Ordering};

#[test]
fn write_to_filter_target() {
    // List of messages that were received by the subprogram
    let recv_messages = Arc::new(Mutex::new(vec![]));

    // Create a scene with just this subprogram in it
    let scene           = Scene::empty();
    let sent_messages   = recv_messages.clone();

    // Create a filter that converts numbers to strings
    let usize_to_string = FilterHandle::for_filter(|number_stream: InputStream<usize>| number_stream.map(|num| num.to_string()));

    // Add a program that receives some strings and writes them to recv_messages
    let string_program = SubProgramId::new();
    scene.add_subprogram(
        string_program,
        move |mut strings: InputStream<String>, _| async move {
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
        },
        0,
    );

    // Add another program that outputs some numbers to the first program
    let number_program = SubProgramId::new();
    scene.add_subprogram(
        number_program, 
        move |_: InputStream<()>, context| async move {
            let mut filtered_output = context.send::<usize>(StreamTarget::Filtered(usize_to_string, string_program)).unwrap();

            filtered_output.send(1).await.unwrap();
            filtered_output.send(2).await.unwrap();
            filtered_output.send(3).await.unwrap();
            filtered_output.send(4).await.unwrap();
        }, 
        0);

    // Run the scene
    let mut has_finished = false;
    executor::block_on(select(async {
        scene.run_scene().await;
        has_finished = true;
    }.boxed(), Delay::new(Duration::from_millis(5000))));

    // Received output should match the numbers
    let recv_messages = (*recv_messages.lock().unwrap()).clone();
    assert!(recv_messages == vec![1.to_string(), 2.to_string(), 3.to_string(), 4.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(has_finished, "Scene did not finish when the programs terminated");
}

#[test]
fn write_to_conversion_filter() {
    // List of messages that were received by the subprogram
    let recv_messages = Arc::new(Mutex::new(vec![]));

    // Create a scene with just this subprogram in it
    let scene           = Scene::empty();
    let sent_messages   = recv_messages.clone();

    // Create a filter that converts u32s to u64s
    let u32_to_u64 = FilterHandle::conversion_filter::<u32, u64>();

    // Add a program that receives some u64s and writes them to recv_messages as strings
    let string_program = SubProgramId::new();
    scene.add_subprogram(
        string_program,
        move |mut numbers: InputStream<u64>, _| async move {
            let next_number = numbers.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_number.to_string());
            let next_number = numbers.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_number.to_string());
            let next_number = numbers.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_number.to_string());
            let next_number = numbers.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_number.to_string());
        },
        0,
    );

    // Add another program that outputs some u32s to the first program via the conversion filter
    let number_program = SubProgramId::new();
    scene.add_subprogram(
        number_program, 
        move |_: InputStream<()>, context| async move {
            let mut filtered_output = context.send::<u32>(StreamTarget::Filtered(u32_to_u64, string_program)).unwrap();

            filtered_output.send(1u32).await.unwrap();
            filtered_output.send(2u32).await.unwrap();
            filtered_output.send(3u32).await.unwrap();
            filtered_output.send(4u32).await.unwrap();
        }, 
        0);

    // Run the scene
    let mut has_finished = false;
    executor::block_on(select(async {
        scene.run_scene().await;
        has_finished = true;
    }.boxed(), Delay::new(Duration::from_millis(5000))));

    // Received output should match the numbers
    let recv_messages = (*recv_messages.lock().unwrap()).clone();
    assert!(recv_messages == vec![1.to_string(), 2.to_string(), 3.to_string(), 4.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(has_finished, "Scene did not finish when the programs terminated");
}

#[test]
fn apply_filter_to_direct_connection() {
    // List of messages that were received by the subprogram
    let recv_messages = Arc::new(Mutex::new(vec![]));

    // Create a scene with just this subprogram in it
    let scene           = Scene::empty();
    let sent_messages   = recv_messages.clone();

    // Create a filter that converts numbers to strings
    let usize_to_string = FilterHandle::for_filter(|number_stream: InputStream<usize>| number_stream.map(|num| num.to_string()));

    // Add a program that receives some strings and writes them to recv_messages
    let string_program = SubProgramId::new();
    scene.add_subprogram(
        string_program,
        move |mut strings: InputStream<String>, _| async move {
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
        },
        0,
    );

    // Create a filter targeting our new program that maps from usize to string
    scene.connect_programs((), StreamTarget::Filtered(usize_to_string, string_program), StreamId::with_message_type::<usize>().for_target(string_program)).unwrap();

    // Add another program that outputs some numbers as usize values to the first program
    // The connection defined above will apply the filter, even though the first program only accepts strings as an input
    let number_program = SubProgramId::new();
    scene.add_subprogram(
        number_program, 
        move |_: InputStream<()>, context| async move {
            let mut filtered_output = context.send::<usize>(string_program).unwrap();

            filtered_output.send(1).await.unwrap();
            filtered_output.send(2).await.unwrap();
            filtered_output.send(3).await.unwrap();
            filtered_output.send(4).await.unwrap();
        }, 
        0);

    // Run the scene
    let mut has_finished = false;
    executor::block_on(select(async {
        scene.run_scene().await;
        has_finished = true;
    }.boxed(), Delay::new(Duration::from_millis(5000))));

    // Received output should match the numbers
    let recv_messages = (*recv_messages.lock().unwrap()).clone();
    assert!(recv_messages == vec![1.to_string(), 2.to_string(), 3.to_string(), 4.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(has_finished, "Scene did not finish when the programs terminated");
}

#[test]
fn connect_all_to_filter_target() {
    // List of messages that were received by the subprogram
    let recv_messages = Arc::new(Mutex::new(vec![]));

    // Create a scene with just this subprogram in it
    let scene           = Scene::empty();
    let sent_messages   = recv_messages.clone();

    // Create a filter that converts numbers to strings
    let usize_to_string = FilterHandle::for_filter(|number_stream: InputStream<usize>| number_stream.map(|num| num.to_string()));

    // Add a program that receives some strings and writes them to recv_messages
    let string_program = SubProgramId::new();
    scene.add_subprogram(
        string_program,
        move |mut strings: InputStream<String>, _| async move {
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
        },
        0,
    );

    // Add another program that outputs some numbers to the first program
    let number_program = SubProgramId::new();
    scene.add_subprogram(
        number_program, 
        move |_: InputStream<()>, context| async move {
            let mut filtered_output = context.send::<usize>(StreamTarget::Any).unwrap();

            filtered_output.send(1).await.unwrap();
            filtered_output.send(2).await.unwrap();
            filtered_output.send(3).await.unwrap();
            filtered_output.send(4).await.unwrap();
        }, 
        0);

    scene.connect_programs((), StreamTarget::Filtered(usize_to_string, string_program), StreamId::with_message_type::<usize>()).unwrap();

    // Run the scene
    let mut has_finished = false;
    executor::block_on(select(async {
        scene.run_scene().await;
        has_finished = true;
    }.boxed(), Delay::new(Duration::from_millis(5000))));

    // Received output should match the numbers
    let recv_messages = (*recv_messages.lock().unwrap()).clone();
    assert!(recv_messages == vec![1.to_string(), 2.to_string(), 3.to_string(), 4.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(has_finished, "Scene did not finish when the programs terminated");
}

#[test]
fn direct_connection_via_general_filter() {
    // List of messages that were received by the subprogram
    let recv_messages = Arc::new(Mutex::new(vec![]));

    // Create a scene with just this subprogram in it
    let scene           = Scene::empty();
    let sent_messages   = recv_messages.clone();

    // Create a filter that converts numbers to strings
    let usize_to_string = FilterHandle::for_filter(|number_stream: InputStream<usize>| number_stream.map(|num| num.to_string()));

    // Add a program that receives some strings and writes them to recv_messages
    let string_program = SubProgramId::new();
    scene.add_subprogram(
        string_program,
        move |mut strings: InputStream<String>, _| async move {
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
        },
        0,
    );

    // Add another program that outputs some numbers to the first program
    // This directly connections to the first program, but the filter is applied to all connections of that message type
    let number_program = SubProgramId::new();
    scene.add_subprogram(
        number_program, 
        move |_: InputStream<()>, context| async move {
            let mut filtered_output = context.send::<usize>(string_program).unwrap();

            filtered_output.send(1).await.unwrap();
            filtered_output.send(2).await.unwrap();
            filtered_output.send(3).await.unwrap();
            filtered_output.send(4).await.unwrap();
        }, 
        0);

    // This connects all 'usize' streams to string_program via a filter
    scene.connect_programs((), StreamTarget::Filtered(usize_to_string, string_program), StreamId::with_message_type::<usize>()).unwrap();

    // Run the scene
    let mut has_finished = false;
    executor::block_on(select(async {
        scene.run_scene().await;
        has_finished = true;
    }.boxed(), Delay::new(Duration::from_millis(5000))));

    // Received output should match the numbers
    let recv_messages = (*recv_messages.lock().unwrap()).clone();
    assert!(recv_messages == vec![1.to_string(), 2.to_string(), 3.to_string(), 4.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(has_finished, "Scene did not finish when the programs terminated");
}

#[test]
fn connect_all_both_filtered_and_unfiltered() {
    // List of messages that were received by the subprogram
    let recv_messages = Arc::new(Mutex::new(vec![]));

    // Create a scene with just this subprogram in it
    let scene           = Scene::empty();
    let sent_messages   = recv_messages.clone();

    // Create a filter that converts numbers to strings
    let usize_to_string = FilterHandle::for_filter(|number_stream: InputStream<usize>| number_stream.map(|num| num.to_string()));

    // Add a program that receives some strings and writes them to recv_messages
    let string_program = SubProgramId::new();
    scene.add_subprogram(
        string_program,
        move |mut strings: InputStream<String>, _| async move {
            for _ in 0..8 {
                let next_string = strings.next().await.unwrap();
                sent_messages.lock().unwrap().push(next_string);
            }
        },
        3,
    );

    // Add another program that outputs some numbers to the first program
    let string_generator_program = SubProgramId::new();
    scene.add_subprogram(
        string_generator_program, 
        move |_: InputStream<()>, context| async move {
            let mut filtered_output = context.send::<String>(StreamTarget::Any).unwrap();

            filtered_output.send(5.to_string()).await.unwrap();
            filtered_output.send(6.to_string()).await.unwrap();
            filtered_output.send(7.to_string()).await.unwrap();
            filtered_output.send(8.to_string()).await.unwrap();
        }, 
        0);

    let number_program = SubProgramId::new();
    scene.add_subprogram(
        number_program, 
        move |_: InputStream<()>, context| async move {
            let mut filtered_output = context.send::<usize>(StreamTarget::Any).unwrap();

            filtered_output.send(1).await.unwrap();
            filtered_output.send(2).await.unwrap();
            filtered_output.send(3).await.unwrap();
            filtered_output.send(4).await.unwrap();
        }, 
        0);

    scene.connect_programs((), string_program, StreamId::with_message_type::<String>()).unwrap();
    scene.connect_programs((), StreamTarget::Filtered(usize_to_string, string_program), StreamId::with_message_type::<usize>()).unwrap();

    // Run the scene
    let mut has_finished = false;
    executor::block_on(select(async {
        scene.run_scene().await;
        has_finished = true;
    }.boxed(), Delay::new(Duration::from_millis(5000))));

    // Received output should match the numbers
    let recv_messages = (*recv_messages.lock().unwrap()).clone();
    let one_to_four     = recv_messages.iter().filter(|msg| *msg == "1" || *msg == "2" || *msg == "3" || *msg == "4").cloned().collect::<Vec<_>>();
    let five_to_eight   = recv_messages.iter().filter(|msg| *msg == "5" || *msg == "6" || *msg == "7" || *msg == "8").cloned().collect::<Vec<_>>();

    // The messages can appear interleaved from the two programs but should otherwise be in order
    assert!(recv_messages.len() == 8, "Wrong number of messages received: {:?}", recv_messages);
    assert!(one_to_four == vec![1.to_string(), 2.to_string(), 3.to_string(), 4.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(five_to_eight == vec![5.to_string(), 6.to_string(), 7.to_string(), 8.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(has_finished, "Scene did not finish when the programs terminated");
}

#[test]
fn disconnect_filter_target() {
    // List of messages that were received by the subprogram
    let recv_messages = Arc::new(Mutex::new(vec![]));

    // CountDisconnects is a struct that gets dropped when the filter stream is closed: it should get called twice here (once when we reconnect, once when the programs end)
    static NUM_DISCONNECTS: AtomicUsize = AtomicUsize::new(0);

    struct CountDisconnents {

    }

    impl CountDisconnents {
        fn convert_to_string(&self, num: usize) -> String {
            num.to_string()
        }
    }

    impl Drop for CountDisconnents {
        fn drop(&mut self) {
            println!("Disconnect");
            NUM_DISCONNECTS.fetch_add(1, Ordering::Relaxed);
        }
    }

    NUM_DISCONNECTS.store(0, Ordering::Relaxed);

    // Create a scene with just this subprogram in it
    let scene           = Arc::new(Scene::empty());
    let sent_messages   = recv_messages.clone();

    // Create a filter that converts numbers to strings
    println!("Register filter");
    let usize_to_string = FilterHandle::for_filter(|number_stream: InputStream<usize>| {
        println!("Connecting");
        let count_disconnects = CountDisconnents {};

        number_stream.map(move |num| count_disconnects.convert_to_string(num))
    });

    // Add a program that receives some strings and writes them to recv_messages
    println!("Create string program");
    let string_program = SubProgramId::new();
    scene.add_subprogram(
        string_program,
        move |mut strings: InputStream<String>, _| async move {
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
            let next_string = strings.next().await.unwrap();
            sent_messages.lock().unwrap().push(next_string);
        },
        0,
    );

    // Add another program that outputs some numbers to the first program
    println!("Create number program");
    let number_program  = SubProgramId::new();
    let scene2          = scene.clone();
    let usize_to_string2 = usize_to_string.clone();
    scene.add_subprogram(
        number_program, 
        move |_: InputStream<()>, context| async move {
            println!("Create initial stream...");
            let mut filtered_output = context.send::<usize>(StreamTarget::Any).unwrap();
            println!("  ... created");

            // Send first two messages
            filtered_output.send(1).await.unwrap();
            filtered_output.send(2).await.unwrap();

            // Disconnect the stream
            println!("Disconnecting initial stream...");
            scene2.connect_programs(number_program, StreamTarget::None, StreamId::with_message_type::<usize>()).unwrap();
            println!("   ... disconnected");

            // Send another two messages into oblivion
            filtered_output.send(3).await.unwrap();
            filtered_output.send(4).await.unwrap();

            // Reconnect the two programs
            println!("Reconnecting filter stream...");
            scene2.connect_programs(number_program, StreamTarget::Filtered(usize_to_string2, string_program), StreamId::with_message_type::<usize>()).unwrap();
            println!("   ... reconnected");

            // Final two messages
            filtered_output.send(5).await.unwrap();
            filtered_output.send(6).await.unwrap();

            // Disconnect them again
            println!("Disconnecting again...");
            scene2.connect_programs(number_program, StreamTarget::None, StreamId::with_message_type::<usize>()).unwrap();
            println!("   ... disconnected");
        }, 
        0);

    // Start the programs connected
    println!("Connect programs");
    scene.connect_programs(number_program, StreamTarget::Filtered(usize_to_string, string_program), StreamId::with_message_type::<usize>()).unwrap();

    // Run the scene
    println!("Start scene");
    let mut has_finished = false;
    executor::block_on(select(async {
        scene.run_scene().await;
        has_finished = true;
    }.boxed(), Delay::new(Duration::from_millis(5000))));

    println!("Scene finished");

    // Received output should match the numbers
    let recv_messages   = (*recv_messages.lock().unwrap()).clone();
    let num_disconnects = NUM_DISCONNECTS.load(Ordering::Relaxed);

    assert!(recv_messages == vec![1.to_string(), 2.to_string(), 5.to_string(), 6.to_string()], "Test program did not send correct numbers (sent {:?})", recv_messages);
    assert!(num_disconnects == 2, "Filtered stream was not dropped the expected number of times ({} != 2)", num_disconnects);
    assert!(has_finished, "Scene did not finish when the programs terminated");
}

#[test]
fn filter_with_send_and_target_filter() {
    // Create a standard scene
    let scene = Scene::default();

    // The test program can pick up on a filter defined before it starts
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message2 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }

    let str_to_msg1  = FilterHandle::for_filter(|string_value: InputStream<String>| string_value.map(|val| Message1::Msg(val.to_string())));
    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output via the message2_receiver program
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(StreamTarget::Filtered(str_to_msg1, message2_receiver_program)).unwrap();

        println!("Sending 1...");
        sender.send("Hello".to_string()).await.unwrap();
        println!("Sending 2...");
        sender.send("Goodbyte".to_string()).await.unwrap();
        println!("Done");
    }, 0);

    // message2_receiver_program relays all of the messages to the test program
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            test_program.send(input).await.unwrap(); 
        }
    }, 0);

    // message2_receiver_program accepts Message1 from any source as an input via a filter
    scene.connect_programs((), StreamTarget::Filtered(msg1_to_msg2, message2_receiver_program), StreamId::with_message_type::<Message1>()).unwrap();

    // Test program receives message2
    TestBuilder::new()
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Hello".to_string()) { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Goodbyte".to_string()) { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn filter_at_target() {
    // Create a standard scene
    let scene = Scene::default();

    // The test program can pick up on a filter defined before it starts
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message2 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(()).unwrap();

        println!("Sending 1...");
        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        println!("Sending 2...");
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
        println!("Done");
    }, 0);

    // message2_receiver_program relays all of the messages to the test program
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            test_program.send(input).await.unwrap(); 
        }
    }, 0);

    // message2_receiver_program accepts Message1 from any source as an input via a filter
    scene.connect_programs((), StreamTarget::Filtered(msg1_to_msg2, message2_receiver_program), StreamId::with_message_type::<Message1>()).unwrap();

    // Test program receives message2
    TestBuilder::new()
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Hello".to_string()) { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Goodbyte".to_string()) { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn filter_target_using_source_filter() {
    // Create a standard scene
    let scene = Scene::default();

    // The test program can pick up on a filter defined before it starts
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message2 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(()).unwrap();

        println!("Sending 1...");
        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        println!("Sending 2...");
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
        println!("Done");
    }, 0);

    // message2_receiver_program relays all of the messages to the test program
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            test_program.send(input).await.unwrap(); 
        }
    }, 0);

    // message2_receiver_program accepts Message1 from any source as an input via a filter
    scene.connect_programs(StreamSource::Filtered(msg1_to_msg2), message2_receiver_program, StreamId::with_message_type::<Message1>()).unwrap();

    // Test program receives message2
    TestBuilder::new()
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Hello".to_string()) { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Goodbyte".to_string()) { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn filter_at_source_with_specific_target() {
    // Create a standard scene
    let scene = Scene::default();

    // Filters can also be specified as a source for a stream. These change the input for all targets that target that source
    #[derive(Debug, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message2 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});

    // For any stream that tries to connect to a program with an input stream of type 'Message2' using 'Message1', automatically use the filter we just defined
    // Target filters will take priority
    scene.connect_programs(msg1_to_msg2, (), StreamId::with_message_type::<Message1>()).unwrap();

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(()).unwrap();

        println!("Sending 1...");
        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        println!("Sending 2...");
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
        println!("Done");
    }, 0);

    // message2_receiver_program should receive all messages of the target type. Temp subprogram here is replaced by the test later on
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            test_program.send(input).await.unwrap(); 
        }
    }, 0);
    scene.connect_programs(message1_sender_program, message2_receiver_program, StreamId::with_message_type::<Message1>()).unwrap();

    // Test program receives message2
    TestBuilder::new()
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Hello".to_string()) { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: Message2| if msg2 != Message2::Msg("Goodbyte".to_string()) { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn filter_at_source_with_any_target() {
    // Create a standard scene
    let scene = Scene::default();

    // Filters can also be specified as a source for a stream. These change the input for all targets that target that source
    #[derive(Debug, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message2 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});

    // For any stream that tries to connect to a program with an input stream of type 'Message2' using 'Message1', automatically use the filter we just defined
    // Target filters will take priority
    scene.connect_programs(msg1_to_msg2, (), StreamId::with_message_type::<Message1>()).unwrap();

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(()).unwrap();

        println!("Sending 1...");
        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        println!("Sending 2...");
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
        println!("Done");
    }, 0);

    // message2_receiver_program should receive all messages of the target type. Temp subprogram here is replaced by the test later on
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            // We resend as a string, as otherwise the connection below will be overridden by the test
            match input {
                Message2::Msg(msg) => test_program.send(msg).await.unwrap()
            }
        }
    }, 0);

    // Anything that generates 'Message2' should be connected to the message2 receiver program
    scene.connect_programs((), message2_receiver_program, StreamId::with_message_type::<Message2>()).unwrap();

    // Test program receives strings relayed by the receiver program
    TestBuilder::new()
        .expect_message(|msg2: String| if msg2 != "Hello".to_string() { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: String| if msg2 != "Goodbyte".to_string() { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn filter_at_source_with_direct_target() {
    // Create a standard scene
    let scene = Scene::default();

    // Filters can also be specified as a source for a stream. These change the input for all targets that target that source
    #[derive(Debug, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message2 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});

    // For any stream that tries to connect to a program with an input stream of type 'Message2' using 'Message1', automatically use the filter we just defined
    // Target filters will take priority
    scene.connect_programs(msg1_to_msg2, (), StreamId::with_message_type::<Message1>()).unwrap();

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that sends Message1 directly to the receiver program
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(message2_receiver_program).unwrap();

        println!("Sending 1...");
        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        println!("Sending 2...");
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
        println!("Done");
    }, 0);

    // message2_receiver_program should receive all messages of the target type. Temp subprogram here is replaced by the test later on
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            // We resend as a string, as otherwise the connection below will be overridden by the test
            match input {
                Message2::Msg(msg) => test_program.send(msg).await.unwrap()
            }
        }
    }, 0);

    // Test program receives strings relayed by the receiver program
    TestBuilder::new()
        .expect_message(|msg2: String| if msg2 != "Hello".to_string() { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: String| if msg2 != "Goodbyte".to_string() { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn chain_filters_with_target_filter() {
    // Create a standard scene
    let scene = Scene::default();

    // Filters can also be specified as a source for a stream. These change the input for all targets that target that source
    #[derive(Debug, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message2 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message3 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }
    impl SceneMessage for Message3 { }

    // Our source program outputs Message1, and we install a source filter that can convert that to Message2
    // The target program receives Message3 but has an input filter that can convert from Message2 (so if we chain the first filter to the second we should be able to receive the messages)
    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});
    let msg2_to_msg3 = FilterHandle::for_filter(|msg1: InputStream<Message2>| { msg1.map(|msg| match msg { Message2::Msg(val) => Message3::Msg(val) })});

    // For any stream that tries to connect to a program with an input stream of type 'Message2' using 'Message1', automatically use the filter we just defined
    // Target filters will take priority
    scene.connect_programs(msg1_to_msg2, (), StreamId::with_message_type::<Message1>()).unwrap();

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let message3_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(()).unwrap();

        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
    }, 0);

    // message2_receiver_program should receive all messages of the target type. Temp subprogram here is replaced by the test later on
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, _| async move {
        while let Some(_input) = input.next().await { 
            // We should connect using the msg1_to_msg3 filter
            assert!(false, "Should receive only Message3");
        }
    }, 0);

    // message3_receiver_program is as above but instead receives Message3
    scene.add_subprogram(message3_receiver_program, |mut input, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            // We resend as a string, as otherwise the connection below will be overridden by the test
            match input {
                Message3::Msg(msg) => test_program.send(msg).await.unwrap()
            }
        }
    }, 0);

    // Anything that generates 'Message2' should be connected to the initial message2 receiver program
    scene.connect_programs((), message2_receiver_program, StreamId::with_message_type::<Message2>()).unwrap();
    scene.connect_programs((), message3_receiver_program, StreamId::with_message_type::<Message3>()).unwrap();

    // Now make message3_receiver_program a receiver of Message2 messages via a filter (these can't be further filtered, so Message1 should no longer be sendable)
    scene.connect_programs((), StreamTarget::Filtered(msg2_to_msg3, message3_receiver_program), StreamId::with_message_type::<Message2>()).unwrap();

    // Test program receives strings relayed by the receiver program
    TestBuilder::new()
        .expect_message(|msg2: String| if msg2 != "Hello".to_string() { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: String| if msg2 != "Goodbyte".to_string() { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn chain_two_filters_with_target_filter_1() {
    // Create a standard scene
    let scene = Scene::default();

    // Filters can also be specified as a source for a stream. These change the input for all targets that target that source
    #[derive(Debug, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message2 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message3 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message4 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }
    impl SceneMessage for Message3 { }
    impl SceneMessage for Message4 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});
    let msg1_to_msg4 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message4::Msg(val) })});
    let msg2_to_msg3 = FilterHandle::for_filter(|msg1: InputStream<Message2>| { msg1.map(|msg| match msg { Message2::Msg(val) => Message3::Msg(val) })});

    // Add converters for both message 2 and message 4. We should be able to find the 1 -> 2 -> 3 chain
    // We can have more than one filter installed on a source filter, and we'll pick one that lets us match the target if we can
    scene.connect_programs(msg1_to_msg2, (), StreamId::with_message_type::<Message1>()).unwrap();
    scene.connect_programs(msg1_to_msg4, (), StreamId::with_message_type::<Message1>()).unwrap();

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let message3_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(()).unwrap();

        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
    }, 0);

    // message2_receiver_program should receive all messages of the target type. Temp subprogram here is replaced by the test later on
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, _| async move {
        while let Some(_input) = input.next().await { 
            // We should connect using the msg1_to_msg3 filter
            assert!(false, "Should receive only Message3");
        }
    }, 0);

    // message3_receiver_program is as above but instead receives Message3
    scene.add_subprogram(message3_receiver_program, |mut input, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            // We resend as a string, as otherwise the connection below will be overridden by the test
            match input {
                Message3::Msg(msg) => test_program.send(msg).await.unwrap()
            }
        }
    }, 0);

    // Anything that generates 'Message2' should be connected to the initial message2 receiver program
    scene.connect_programs((), message2_receiver_program, StreamId::with_message_type::<Message2>()).unwrap();
    scene.connect_programs((), message3_receiver_program, StreamId::with_message_type::<Message3>()).unwrap();

    // Now make message3_receiver_program a receiver of Message2 messages via a filter (these can't be further filtered, so Message1 should no longer be sendable)
    scene.connect_programs((), StreamTarget::Filtered(msg2_to_msg3, message3_receiver_program), StreamId::with_message_type::<Message2>()).unwrap();

    // Test program receives strings relayed by the receiver program
    TestBuilder::new()
        .expect_message(|msg2: String| if msg2 != "Hello".to_string() { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: String| if msg2 != "Goodbyte".to_string() { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn chain_two_filters_with_target_filter_2() {
    // Create a standard scene
    let scene = Scene::default();

    // Filters can also be specified as a source for a stream. These change the input for all targets that target that source
    #[derive(Debug, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message2 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message3 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message4 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }
    impl SceneMessage for Message3 { }
    impl SceneMessage for Message4 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});
    let msg1_to_msg4 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message4::Msg(val) })});
    let msg2_to_msg3 = FilterHandle::for_filter(|msg1: InputStream<Message2>| { msg1.map(|msg| match msg { Message2::Msg(val) => Message3::Msg(val) })});

    // Add converters for both message 2 and message 4. We should be able to find the 1 -> 2 -> 3 chain
    // We can have more than one filter installed on a source filter, and we'll pick one that lets us match the target if we can
    scene.connect_programs(msg1_to_msg4, (), StreamId::with_message_type::<Message1>()).unwrap();
    scene.connect_programs(msg1_to_msg2, (), StreamId::with_message_type::<Message1>()).unwrap();

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message2_receiver_program   = SubProgramId::new();
    let message3_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that generates 'message1' as an output
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        let mut sender = context.send(()).unwrap();

        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
    }, 0);

    // message2_receiver_program should receive all messages of the target type. Temp subprogram here is replaced by the test later on
    scene.add_subprogram(message2_receiver_program, |mut input: InputStream<Message2>, _| async move {
        while let Some(_input) = input.next().await { 
            // We should connect using the msg1_to_msg3 filter
            assert!(false, "Should receive only Message3");
        }
    }, 0);

    // message3_receiver_program is as above but instead receives Message3
    scene.add_subprogram(message3_receiver_program, |mut input, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            // We resend as a string, as otherwise the connection below will be overridden by the test
            match input {
                Message3::Msg(msg) => test_program.send(msg).await.unwrap()
            }
        }
    }, 0);

    // Anything that generates 'Message2' should be connected to the initial message2 receiver program
    scene.connect_programs((), message2_receiver_program, StreamId::with_message_type::<Message2>()).unwrap();
    scene.connect_programs((), message3_receiver_program, StreamId::with_message_type::<Message3>()).unwrap();

    // Now make message3_receiver_program a receiver of Message2 messages via a filter (these can't be further filtered, so Message1 should no longer be sendable)
    scene.connect_programs((), StreamTarget::Filtered(msg2_to_msg3, message3_receiver_program), StreamId::with_message_type::<Message2>()).unwrap();

    // Test program receives strings relayed by the receiver program
    TestBuilder::new()
        .expect_message(|msg2: String| if msg2 != "Hello".to_string() { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: String| if msg2 != "Goodbyte".to_string() { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}

#[test]
fn chain_with_direct_target() {
    // Create a standard scene
    let scene = Scene::default();

    // Filters can also be specified as a source for a stream. These change the input for all targets that target that source
    #[derive(Debug, Serialize, Deserialize)]
    enum Message1 { Msg(String) }
    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    enum Message2 { Msg(String) }
    #[derive(Debug, Serialize, Deserialize)]
    enum Message3 { Msg(String) }

    impl SceneMessage for Message1 { }
    impl SceneMessage for Message2 { }
    impl SceneMessage for Message3 { }

    let msg1_to_msg2 = FilterHandle::for_filter(|msg1: InputStream<Message1>| { msg1.map(|msg| match msg { Message1::Msg(val) => Message2::Msg(val) })});
    let msg2_to_msg3 = FilterHandle::for_filter(|msg1: InputStream<Message2>| { msg1.map(|msg| match msg { Message2::Msg(val) => Message3::Msg(val) })});

    // For any stream that tries to connect to a program with an input stream of type 'Message2' using 'Message1', automatically use the filter we just defined
    // Target filters will take priority
    scene.connect_programs(msg1_to_msg2, (), StreamId::with_message_type::<Message1>()).unwrap();

    // The IDs of the two programs involved
    let message1_sender_program     = SubProgramId::new();
    let message3_receiver_program   = SubProgramId::new();
    let test_program                = SubProgramId::new();

    // Create a program that sends Message1 directly to the receiver program
    scene.add_subprogram(message1_sender_program, |_: InputStream<()>, context| async move {
        // Send message1 direct to message3 receiver (should convert to message2 then message3)
        let mut sender = context.send(message3_receiver_program).unwrap();

        println!("Sending 1...");
        sender.send(Message1::Msg("Hello".to_string())).await.unwrap();
        println!("Sending 2...");
        sender.send(Message1::Msg("Goodbyte".to_string())).await.unwrap();
        println!("Done");
    }, 0);

    // message2_receiver_program should receive all messages of the target type. Temp subprogram here is replaced by the test later on
    scene.add_subprogram(message3_receiver_program, |mut input, context| async move {
        // We need an intermediate prorgam because the test program has its own set of filters. All this does is relay its message to the next program along.
        let mut test_program = context.send(()).unwrap();

        while let Some(input) = input.next().await { 
            // We resend as a string, as otherwise the connection below will be overridden by the test
            match input {
                Message3::Msg(msg) => test_program.send(msg).await.unwrap()
            }
        }
    }, 0);

    // Add an input filter to the message 3 program
    scene.connect_programs((), StreamTarget::Filtered(msg2_to_msg3, message3_receiver_program), StreamId::with_message_type::<Message2>()).unwrap();

    // Test program receives strings relayed by the receiver program
    TestBuilder::new()
        .expect_message(|msg2: String| if msg2 != "Hello".to_string() { Err(format!("Expected 'Hello'")) } else { Ok(()) })
        .expect_message(|msg2: String| if msg2 != "Goodbyte".to_string() { Err(format!("Expected 'Goodbyte'")) } else { Ok(()) })
        .run_in_scene(&scene, test_program);
}