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
use crate::{
    computed::{ArcMemo, Memo},
    diagnostics::is_suppressing_resource_load,
    owner::{FromLocal, LocalStorage, Storage, StoredValue, SyncStorage},
    signal::{ArcRwSignal, RwSignal},
    traits::{DefinedAt, Dispose, Get, GetUntracked, Update},
    unwrap_signal,
};
use any_spawner::Executor;
use futures::{channel::oneshot, select, FutureExt};
use send_wrapper::SendWrapper;
use std::{future::Future, panic::Location, pin::Pin, sync::Arc};

/// An action runs some asynchronous code when you dispatch a new value to it, and gives you
/// reactive access to the result.
///
/// Actions are intended for mutating or updating data, not for loading data. If you find yourself
/// creating an action and immediately dispatching a value to it, this is probably the wrong
/// primitive.
///
/// The arena-allocated, `Copy` version of an `ArcAction` is an [`Action`].
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # use reactive_graph::prelude::*;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio();
/// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
/// async fn send_new_todo_to_api(task: String) -> usize {
///     // do something...
///     // return a task id
///     42
/// }
/// let save_data = ArcAction::new(|task: &String| {
///   // `task` is given as `&String` because its value is available in `input`
///   send_new_todo_to_api(task.clone())
/// });
///
/// // the argument currently running
/// let input = save_data.input();
/// // the most recent returned result
/// let result_of_call = save_data.value();
/// // whether the call is pending
/// let pending = save_data.pending();
/// // how many times the action has run
/// // useful for reactively updating something else in response to a `dispatch` and response
/// let version = save_data.version();
///
/// // before we do anything
/// assert_eq!(input.get(), None); // no argument yet
/// assert_eq!(pending.get(), false); // isn't pending a response
/// assert_eq!(result_of_call.get(), None); // there's no "last value"
/// assert_eq!(version.get(), 0);
///
/// // dispatch the action
/// save_data.dispatch("My todo".to_string());
///
/// // when we're making the call
/// assert_eq!(input.get(), Some("My todo".to_string()));
/// assert_eq!(pending.get(), true); // is pending
/// assert_eq!(result_of_call.get(), None); // has not yet gotten a response
///
/// # any_spawner::Executor::tick().await;
///
/// // after call has resolved
/// assert_eq!(input.get(), None); // input clears out after resolved
/// assert_eq!(pending.get(), false); // no longer pending
/// assert_eq!(result_of_call.get(), Some(42));
/// assert_eq!(version.get(), 1);
/// # });
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Action::input] as well.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// // if there's a single argument, just use that
/// let action1 = ArcAction::new(|input: &String| {
///     let input = input.clone();
///     async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = ArcAction::new(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 = ArcAction::new(|input: &(usize, String)| async { todo!() });
/// ```
pub struct ArcAction<I, O> {
    in_flight: ArcRwSignal<usize>,
    input: ArcRwSignal<Option<I>>,
    value: ArcRwSignal<Option<O>>,
    version: ArcRwSignal<usize>,
    #[allow(clippy::complexity)]
    action_fn: Arc<
        dyn Fn(&I) -> Pin<Box<dyn Future<Output = O> + Send>> + Send + Sync,
    >,
    #[cfg(debug_assertions)]
    defined_at: &'static Location<'static>,
}

impl<I, O> Clone for ArcAction<I, O> {
    fn clone(&self) -> Self {
        Self {
            in_flight: self.in_flight.clone(),
            input: self.input.clone(),
            value: self.value.clone(),
            version: self.version.clone(),
            action_fn: self.action_fn.clone(),
            #[cfg(debug_assertions)]
            defined_at: self.defined_at,
        }
    }
}

impl<I, O> ArcAction<I, O>
where
    I: 'static,
    O: 'static,
{
    /// Creates a new action. This is lazy: it does not run the action function until some value
    /// is dispatched.
    ///
    /// The constructor takes a function which will create a new `Future` from some input data.
    /// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
    /// be spawned.
    ///
    /// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
    /// `Future` must be `Send` so that it can be moved across threads by the async executor as
    /// needed.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = ArcAction::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// act.dispatch(3);
    /// assert_eq!(act.input().get(), Some(3));
    ///
    /// // Remember that async functions already return a future if they are
    /// // not `await`ed. You can save keystrokes by leaving out the `async move`
    ///
    /// let act2 = Action::new(|n: &String| yell(n.to_owned()));
    /// act2.dispatch(String::from("i'm in a doctest"));
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    ///
    /// // after it resolves
    /// assert_eq!(act2.value().get(), Some("I'M IN A DOCTEST".to_string()));
    ///
    /// async fn yell(n: String) -> String {
    ///     n.to_uppercase()
    /// }
    /// # });
    /// ```
    #[track_caller]
    pub fn new<F, Fu>(action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + Send + Sync + 'static,
        Fu: Future<Output = O> + Send + 'static,
    {
        Self::new_with_value(None, action_fn)
    }

    /// Creates a new action, initializing it with the given value.
    ///
    /// This is lazy: it does not run the action function until some value is dispatched.
    ///
    /// The constructor takes a function which will create a new `Future` from some input data.
    /// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
    /// be spawned.
    ///
    /// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
    /// `Future` must be `Send` so that it can be moved across threads by the async executor as
    /// needed.
    #[track_caller]
    pub fn new_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + Send + Sync + 'static,
        Fu: Future<Output = O> + Send + 'static,
    {
        ArcAction {
            in_flight: ArcRwSignal::new(0),
            input: Default::default(),
            value: ArcRwSignal::new(value),
            version: Default::default(),
            action_fn: Arc::new(move |input| Box::pin(action_fn(input))),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }
}

/// A handle that allows aborting an in-flight action. It is returned from [`Action::dispatch`] or
/// [`ArcAction::dispatch`].
#[derive(Debug)]
pub struct ActionAbortHandle(oneshot::Sender<()>);

impl ActionAbortHandle {
    /// Aborts the action.
    ///
    /// This will cause the dispatched task to complete, without updating the action's value. The
    /// dispatched action's `Future` will no longer be polled. This does not guarantee that side
    /// effects created by that `Future` no longer run: for example, if the action dispatches an
    /// HTTP request, whether that request is actually canceled or not depends on whether the
    /// request library actually cancels a request when its `Future` is dropped.
    pub fn abort(self) {
        let _ = self.0.send(());
    }
}

impl<I, O> ArcAction<I, O>
where
    I: Send + Sync + 'static,
    O: Send + Sync + 'static,
{
    /// Calls the `async` function with a reference to the input type as its argument.
    #[track_caller]
    pub fn dispatch(&self, input: I) -> ActionAbortHandle {
        let (abort_tx, mut abort_rx) = oneshot::channel();
        if !is_suppressing_resource_load() {
            let mut fut = (self.action_fn)(&input).fuse();

            // Update the state before loading
            self.in_flight.update(|n| *n += 1);
            let current_version =
                self.version.try_get_untracked().unwrap_or_default();
            self.input.try_update(|inp| *inp = Some(input));

            // Spawn the task
            Executor::spawn({
                let input = self.input.clone();
                let version = self.version.clone();
                let value = self.value.clone();
                let in_flight = self.in_flight.clone();
                async move {
                    select! {
                        // if the abort message has been sent, bail and do nothing
                        _ = abort_rx => {
                            in_flight.update(|n| *n = n.saturating_sub(1));
                        },
                        // otherwise, update the value
                        result = fut => {
                            in_flight.update(|n| *n = n.saturating_sub(1));
                            let is_latest = version.get_untracked() <= current_version;
                            if is_latest {
                                version.update(|n| *n += 1);
                                value.update(|n| *n = Some(result));
                            }
                        }
                    }
                    if in_flight.get_untracked() == 0 {
                        input.update(|inp| *inp = None);
                    }
                }
            });
        }

        ActionAbortHandle(abort_tx)
    }
}

impl<I, O> ArcAction<I, O>
where
    I: 'static,
    O: 'static,
{
    /// Calls the `async` function with a reference to the input type as its argument,
    /// ensuring that it is spawned on the current thread.
    #[track_caller]
    pub fn dispatch_local(&self, input: I) -> ActionAbortHandle {
        let (abort_tx, mut abort_rx) = oneshot::channel();
        if !is_suppressing_resource_load() {
            let mut fut = (self.action_fn)(&input).fuse();

            // Update the state before loading
            self.in_flight.update(|n| *n += 1);
            let current_version =
                self.version.try_get_untracked().unwrap_or_default();
            self.input.try_update(|inp| *inp = Some(input));

            // Spawn the task
            Executor::spawn_local({
                let input = self.input.clone();
                let version = self.version.clone();
                let value = self.value.clone();
                let in_flight = self.in_flight.clone();
                async move {
                    select! {
                        // if the abort message has been sent, bail and do nothing
                        _ = abort_rx => {
                            in_flight.update(|n| *n = n.saturating_sub(1));
                        },
                        // otherwise, update the value
                        result = fut => {
                            in_flight.update(|n| *n = n.saturating_sub(1));
                            let is_latest = version.get_untracked() <= current_version;
                            if is_latest {
                                version.update(|n| *n += 1);
                                value.update(|n| *n = Some(result));
                            }
                        }
                    }
                    if in_flight.get_untracked() == 0 {
                        input.update(|inp| *inp = None);
                    }
                }
            });
        }
        ActionAbortHandle(abort_tx)
    }
}

impl<I, O> ArcAction<I, O>
where
    I: 'static,
    O: 'static,
{
    /// Creates a new action, which will only be run on the thread in which it is created.
    ///
    /// In all other ways, this is identical to [`ArcAction::new`].
    #[track_caller]
    pub fn new_unsync<F, Fu>(action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + 'static,
        Fu: Future<Output = O> + 'static,
    {
        let action_fn = move |inp: &I| SendWrapper::new(action_fn(inp));
        Self::new_unsync_with_value(None, action_fn)
    }

    /// Creates a new action that will only run on the current thread, initializing it with the given value.
    ///
    /// In all other ways, this is identical to [`ArcAction::new_with_value`].
    #[track_caller]
    pub fn new_unsync_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + 'static,
        Fu: Future<Output = O> + 'static,
    {
        let action_fn = SendWrapper::new(action_fn);
        ArcAction {
            in_flight: ArcRwSignal::new(0),
            input: Default::default(),
            value: ArcRwSignal::new(value),
            version: Default::default(),
            action_fn: Arc::new(move |input| {
                Box::pin(SendWrapper::new(action_fn(input)))
            }),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }
}

impl<I, O> ArcAction<I, O> {
    /// The number of times the action has successfully completed.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = ArcAction::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let version = act.version();
    /// act.dispatch(3);
    /// assert_eq!(version.get(), 0);
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(version.get(), 1);
    /// # });
    /// ```
    #[track_caller]
    pub fn version(&self) -> ArcRwSignal<usize> {
        self.version.clone()
    }

    /// The current argument that was dispatched to the async function. This value will
    /// be `Some` while we are waiting for it to resolve, and `None` after it has resolved.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = ArcAction::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let input = act.input();
    /// assert_eq!(input.get(), None);
    /// act.dispatch(3);
    /// assert_eq!(input.get(), Some(3));
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(input.get(), None);
    /// # });
    /// ```
    #[track_caller]
    pub fn input(&self) -> ArcRwSignal<Option<I>> {
        self.input.clone()
    }

    /// The most recent return value of the `async` function. This will be `None` before
    /// the action has ever run successfully, and subsequently will always be `Some(_)`,
    /// holding the old value until a new value has been received.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = ArcAction::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let value = act.value();
    /// assert_eq!(value.get(), None);
    /// act.dispatch(3);
    /// assert_eq!(value.get(), None);
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(value.get(), Some(6));
    /// // dispatch another value, and it still holds the old value
    /// act.dispatch(3);
    /// assert_eq!(value.get(), Some(6));
    /// # });
    /// ```
    #[track_caller]
    pub fn value(&self) -> ArcRwSignal<Option<O>> {
        self.value.clone()
    }

    /// Whether the action has been dispatched and is currently waiting to resolve.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = ArcAction::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let pending = act.pending();
    /// assert_eq!(pending.get(), false);
    /// act.dispatch(3);
    /// assert_eq!(pending.get(), true);
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(pending.get(), false);
    /// # });
    /// ```
    #[track_caller]
    pub fn pending(&self) -> ArcMemo<bool> {
        let in_flight = self.in_flight.clone();
        ArcMemo::new(move |_| in_flight.get() > 0)
    }
}

impl<I, O> DefinedAt for ArcAction<I, O>
where
    I: 'static,
    O: 'static,
{
    fn defined_at(&self) -> Option<&'static Location<'static>> {
        #[cfg(debug_assertions)]
        {
            Some(self.defined_at)
        }
        #[cfg(not(debug_assertions))]
        {
            None
        }
    }
}

/// An action runs some asynchronous code when you dispatch a new value to it, and gives you
/// reactive access to the result.
///
/// Actions are intended for mutating or updating data, not for loading data. If you find yourself
/// creating an action and immediately dispatching a value to it, this is probably the wrong
/// primitive.
///
/// The reference-counted, `Clone` (but not `Copy` version of an `Action` is an [`ArcAction`].
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # use reactive_graph::prelude::*;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio();
/// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
/// async fn send_new_todo_to_api(task: String) -> usize {
///     // do something...
///     // return a task id
///     42
/// }
/// let save_data = Action::new(|task: &String| {
///   // `task` is given as `&String` because its value is available in `input`
///   send_new_todo_to_api(task.clone())
/// });
///
/// // the argument currently running
/// let input = save_data.input();
/// // the most recent returned result
/// let result_of_call = save_data.value();
/// // whether the call is pending
/// let pending = save_data.pending();
/// // how many times the action has run
/// // useful for reactively updating something else in response to a `dispatch` and response
/// let version = save_data.version();
///
/// // before we do anything
/// assert_eq!(input.get(), None); // no argument yet
/// assert_eq!(pending.get(), false); // isn't pending a response
/// assert_eq!(result_of_call.get(), None); // there's no "last value"
/// assert_eq!(version.get(), 0);
///
/// // dispatch the action
/// save_data.dispatch("My todo".to_string());
///
/// // when we're making the call
/// assert_eq!(input.get(), Some("My todo".to_string()));
/// assert_eq!(pending.get(), true); // is pending
/// assert_eq!(result_of_call.get(), None); // has not yet gotten a response
///
/// # any_spawner::Executor::tick().await;
///
/// // after call has resolved
/// assert_eq!(input.get(), None); // input clears out after resolved
/// assert_eq!(pending.get(), false); // no longer pending
/// assert_eq!(result_of_call.get(), Some(42));
/// assert_eq!(version.get(), 1);
/// # });
/// ```
///
/// The input to the `async` function should always be a single value,
/// but it can be of any type. The argument is always passed by reference to the
/// function, because it is stored in [Action::input] as well.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// // if there's a single argument, just use that
/// let action1 = Action::new(|input: &String| {
///     let input = input.clone();
///     async move { todo!() }
/// });
///
/// // if there are no arguments, use the unit type `()`
/// let action2 = Action::new(|input: &()| async { todo!() });
///
/// // if there are multiple arguments, use a tuple
/// let action3 = Action::new(|input: &(usize, String)| async { todo!() });
/// ```
pub struct Action<I, O, S = SyncStorage> {
    inner: StoredValue<ArcAction<I, O>, S>,
    #[cfg(debug_assertions)]
    defined_at: &'static Location<'static>,
}

impl<I, O, S> Dispose for Action<I, O, S> {
    fn dispose(self) {
        self.inner.dispose()
    }
}

impl<I, O> Action<I, O>
where
    I: Send + Sync + 'static,
    O: Send + Sync + 'static,
{
    /// Creates a new action. This is lazy: it does not run the action function until some value
    /// is dispatched.
    ///
    /// The constructor takes a function which will create a new `Future` from some input data.
    /// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
    /// be spawned.
    ///
    /// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
    /// `Future` must be `Send` so that it can be moved across threads by the async executor as
    /// needed. In order to be stored in the `Copy` arena, the input and output types should also
    /// be `Send + Sync`.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = Action::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// act.dispatch(3);
    /// assert_eq!(act.input().get(), Some(3));
    ///
    /// // Remember that async functions already return a future if they are
    /// // not `await`ed. You can save keystrokes by leaving out the `async move`
    ///
    /// let act2 = Action::new(|n: &String| yell(n.to_owned()));
    /// act2.dispatch(String::from("i'm in a doctest"));
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    ///
    /// // after it resolves
    /// assert_eq!(act2.value().get(), Some("I'M IN A DOCTEST".to_string()));
    ///
    /// async fn yell(n: String) -> String {
    ///     n.to_uppercase()
    /// }
    /// # });
    /// ```
    #[track_caller]
    pub fn new<F, Fu>(action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + Send + Sync + 'static,
        Fu: Future<Output = O> + Send + 'static,
    {
        Self {
            inner: StoredValue::new(ArcAction::new(action_fn)),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }

    /// Creates a new action, initializing it with the given value.
    ///
    /// This is lazy: it does not run the action function until some value is dispatched.
    ///
    /// The constructor takes a function which will create a new `Future` from some input data.
    /// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
    /// be spawned.
    ///
    /// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
    /// `Future` must be `Send` so that it can be moved across threads by the async executor as
    /// needed. In order to be stored in the `Copy` arena, the input and output types should also
    /// be `Send + Sync`.
    #[track_caller]
    pub fn new_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + Send + Sync + 'static,
        Fu: Future<Output = O> + Send + 'static,
    {
        Self {
            inner: StoredValue::new(ArcAction::new_with_value(
                value, action_fn,
            )),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }
}

impl<I, O> Action<I, O, LocalStorage>
where
    I: 'static,
    O: 'static,
{
    /// Creates a new action, which does not require its inputs or outputs to be `Send`. In all other
    /// ways, this is the same as [`Action::new`]. If this action is accessed from outside the
    /// thread on which it was created, it panics.
    #[track_caller]
    pub fn new_local<F, Fu>(action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + 'static,
        Fu: Future<Output = O> + Send + 'static,
    {
        Self {
            inner: StoredValue::new_local(ArcAction::new_unsync(action_fn)),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }

    /// Creates a new action with the initial value, which does not require its inputs or outputs to be `Send`. In all other
    /// ways, this is the same as [`Action::new_with_value`]. If this action is accessed from outside the
    /// thread on which it was created, it panics.
    #[track_caller]
    pub fn new_local_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + 'static,
        Fu: Future<Output = O> + Send + 'static,
    {
        Self {
            inner: StoredValue::new_local(ArcAction::new_unsync_with_value(
                value, action_fn,
            )),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }
}

impl<I, O, S> Action<I, O, S>
where
    S: Storage<ArcAction<I, O>>,
{
    /// The number of times the action has successfully completed.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = Action::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let version = act.version();
    /// act.dispatch(3);
    /// assert_eq!(version.get(), 0);
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(version.get(), 1);
    /// # });
    /// ```
    #[track_caller]
    pub fn version(&self) -> RwSignal<usize> {
        let inner = self
            .inner
            .try_with_value(|inner| inner.version())
            .unwrap_or_else(unwrap_signal!(self));
        inner.into()
    }

    /// Whether the action has been dispatched and is currently waiting to resolve.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = Action::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let pending = act.pending();
    /// assert_eq!(pending.get(), false);
    /// act.dispatch(3);
    /// assert_eq!(pending.get(), true);
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(pending.get(), false);
    /// # });
    /// ```
    #[track_caller]
    pub fn pending(&self) -> Memo<bool> {
        let inner = self
            .inner
            .try_with_value(|inner| inner.pending())
            .unwrap_or_else(unwrap_signal!(self));
        inner.into()
    }
}

impl<I, O, S> Action<I, O, S>
where
    I: 'static,
    S: Storage<ArcAction<I, O>>,
{
    /// The current argument that was dispatched to the async function. This value will
    /// be `Some` while we are waiting for it to resolve, and `None` after it has resolved.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = ArcAction::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let input = act.input();
    /// assert_eq!(input.get(), None);
    /// act.dispatch(3);
    /// assert_eq!(input.get(), Some(3));
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(input.get(), None);
    /// # });
    /// ```
    #[track_caller]
    pub fn input(&self) -> RwSignal<Option<I>>
    where
        I: Send + Sync,
    {
        let inner = self
            .inner
            .try_with_value(|inner| inner.input())
            .unwrap_or_else(unwrap_signal!(self));
        inner.into()
    }

    /// The current argument that was dispatched to the async function. This value will
    /// be `Some` while we are waiting for it to resolve, and `None` after it has resolved.
    ///
    /// Returns a thread-local signal using [`LocalStorage`].
    #[track_caller]
    pub fn input_local(&self) -> RwSignal<Option<I>, LocalStorage> {
        let inner = self
            .inner
            .try_with_value(|inner| inner.input())
            .unwrap_or_else(unwrap_signal!(self));
        RwSignal::from_local(inner)
    }
}

impl<I, O, S> Action<I, O, S>
where
    O: 'static,
    S: Storage<ArcAction<I, O>>,
{
    /// The most recent return value of the `async` function. This will be `None` before
    /// the action has ever run successfully, and subsequently will always be `Some(_)`,
    /// holding the old value until a new value has been received.
    ///
    /// ```rust
    /// # use reactive_graph::actions::*;
    /// # use reactive_graph::prelude::*;
    /// # tokio_test::block_on(async move {
    /// # any_spawner::Executor::init_tokio();
    /// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
    /// let act = Action::new(|n: &u8| {
    ///     let n = n.to_owned();
    ///     async move { n * 2 }
    /// });
    ///
    /// let value = act.value();
    /// assert_eq!(value.get(), None);
    /// act.dispatch(3);
    /// assert_eq!(value.get(), None);
    ///
    /// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    /// // after it resolves
    /// assert_eq!(value.get(), Some(6));
    /// // dispatch another value, and it still holds the old value
    /// act.dispatch(3);
    /// assert_eq!(value.get(), Some(6));
    /// # });
    /// ```
    #[track_caller]
    pub fn value(&self) -> RwSignal<Option<O>>
    where
        O: Send + Sync,
    {
        let inner = self
            .inner
            .try_with_value(|inner| inner.value())
            .unwrap_or_else(unwrap_signal!(self));
        inner.into()
    }

    /// The most recent return value of the `async` function. This will be `None` before
    /// the action has ever run successfully, and subsequently will always be `Some(_)`,
    /// holding the old value until a new value has been received.
    ///
    /// Returns a thread-local signal using [`LocalStorage`].
    #[track_caller]
    pub fn value_local(&self) -> RwSignal<Option<O>, LocalStorage>
    where
        O: Send + Sync,
    {
        let inner = self
            .inner
            .try_with_value(|inner| inner.value())
            .unwrap_or_else(unwrap_signal!(self));
        RwSignal::from_local(inner)
    }
}

impl<I, O, S> Action<I, O, S>
where
    I: Send + Sync + 'static,
    O: Send + Sync + 'static,
    S: Storage<ArcAction<I, O>>,
{
    /// Calls the `async` function with a reference to the input type as its argument.
    #[track_caller]
    pub fn dispatch(&self, input: I) -> ActionAbortHandle {
        self.inner.with_value(|inner| inner.dispatch(input))
    }
}

impl<I, O, S> Action<I, O, S>
where
    I: 'static,
    O: 'static,
    S: Storage<ArcAction<I, O>>,
{
    /// Calls the `async` function with a reference to the input type as its argument.
    #[track_caller]
    pub fn dispatch_local(&self, input: I) -> ActionAbortHandle {
        self.inner.with_value(|inner| inner.dispatch_local(input))
    }
}

impl<I, O, S> Action<I, O, S>
where
    I: Send + Sync + 'static,
    O: Send + Sync + 'static,
    S: Storage<ArcAction<I, O>>,
{
    /// Creates a new action, which does not require the action itself to be `Send`, but will run
    /// it on the same thread it was created on.
    ///
    /// In all other ways, this is identical to [`Action::new`].
    #[track_caller]
    pub fn new_unsync<F, Fu>(action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + 'static,
        Fu: Future<Output = O> + 'static,
    {
        Self {
            inner: StoredValue::new_with_storage(ArcAction::new_unsync(
                action_fn,
            )),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }

    /// Creates a new action, which does not require the action itself to be `Send`, but will run
    /// it on the same thread it was created on, and gives an initial value.
    ///
    /// In all other ways, this is identical to [`Action::new`].
    #[track_caller]
    pub fn new_unsync_with_value<F, Fu>(value: Option<O>, action_fn: F) -> Self
    where
        F: Fn(&I) -> Fu + 'static,
        Fu: Future<Output = O> + 'static,
    {
        Self {
            inner: StoredValue::new_with_storage(
                ArcAction::new_unsync_with_value(value, action_fn),
            ),
            #[cfg(debug_assertions)]
            defined_at: Location::caller(),
        }
    }
}

impl<I, O, S> DefinedAt for Action<I, O, S> {
    fn defined_at(&self) -> Option<&'static Location<'static>> {
        #[cfg(debug_assertions)]
        {
            Some(self.defined_at)
        }
        #[cfg(not(debug_assertions))]
        {
            None
        }
    }
}

impl<I, O, S> Clone for Action<I, O, S> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<I, O, S> Copy for Action<I, O, S> {}

/// Creates a new action. This is lazy: it does not run the action function until some value
/// is dispatched.
///
/// The constructor takes a function which will create a new `Future` from some input data.
/// When the action is dispatched, this `action_fn` will run, and the `Future` it returns will
/// be spawned.
///
/// The `action_fn` must be `Send + Sync` so that the `ArcAction` is `Send + Sync`. The
/// `Future` must be `Send` so that it can be moved across threads by the async executor as
/// needed. In order to be stored in the `Copy` arena, the input and output types should also
/// be `Send + Sync`.
///
/// ```rust
/// # use reactive_graph::actions::*;
/// # use reactive_graph::prelude::*;
/// # tokio_test::block_on(async move {
/// # any_spawner::Executor::init_tokio();
/// # let _guard = reactive_graph::diagnostics::SpecialNonReactiveZone::enter();
/// let act = create_action(|n: &u8| {
///     let n = n.to_owned();
///     async move { n * 2 }
/// });
///
/// act.dispatch(3);
/// assert_eq!(act.input().get(), Some(3));
///
/// // Remember that async functions already return a future if they are
/// // not `await`ed. You can save keystrokes by leaving out the `async move`
///
/// let act2 = Action::new(|n: &String| yell(n.to_owned()));
/// act2.dispatch(String::from("i'm in a doctest"));
/// # tokio::time::sleep(std::time::Duration::from_millis(10)).await;
///
/// // after it resolves
/// assert_eq!(act2.value().get(), Some("I'M IN A DOCTEST".to_string()));
///
/// async fn yell(n: String) -> String {
///     n.to_uppercase()
/// }
/// # });
/// ```
#[inline(always)]
#[track_caller]
#[deprecated = "This function is being removed to conform to Rust idioms. \
                Please use `Action::new()` instead."]
pub fn create_action<I, O, F, Fu>(action_fn: F) -> Action<I, O>
where
    I: Send + Sync + 'static,
    O: Send + Sync + 'static,
    F: Fn(&I) -> Fu + Send + Sync + 'static,
    Fu: Future<Output = O> + Send + 'static,
{
    Action::new(action_fn)
}