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
use clonelet::clone;
use futures::{Future, FutureExt, StreamExt};
use futures_signals::{
    signal::{Mutable, ReadOnlyMutable, Signal, SignalExt},
    signal_vec::{MutableVec, MutableVecLockMut, SignalVec, SignalVecExt, VecDiff},
};
use silkenweb_macros::cfg_browser;

#[cfg_browser(false)]
/// Server only task tools.
pub mod server {
    use std::{
        pin::pin,
        sync::Arc,
        task::{Context, Poll, Wake},
    };

    use crossbeam::sync::{Parker, Unparker};
    use futures::Future;

    /// Synchronous version of [`run_tasks`][super::run_tasks].
    ///
    /// This is only available on the server.
    pub fn run_tasks_sync() {
        super::arch::run_tasks_sync()
    }

    struct ThreadWaker(Unparker);

    impl Wake for ThreadWaker {
        fn wake(self: Arc<Self>) {
            self.0.unpark();
        }
    }

    /// Run a future to completion on the current thread.
    ///
    /// This doesn't use the microtask executor, so it's safe to call
    /// [run_tasks] from within the future. It's also safe to call `block_on`
    /// recursively.
    ///
    /// [run_tasks]: super::run_tasks
    pub fn block_on<T>(fut: impl Future<Output = T>) -> T {
        let mut fut = pin!(fut);

        // Use a `Parker` instance rather than global `thread::park/unpark`, so no one
        // else can steal our `unpark`s and they don't get confused with recursive
        // `block_on` `unpark`s.
        let parker = Parker::new();
        // Make sure we create a new waker each call, rather than using a global, so
        // recursive `block_on`s don't use the same waker.
        let waker = Arc::new(ThreadWaker(parker.unparker().clone())).into();
        let mut cx = Context::from_waker(&waker);

        // Run the future to completion.
        loop {
            match fut.as_mut().poll(&mut cx) {
                Poll::Ready(res) => return res,
                Poll::Pending => parker.park(),
            }
        }
    }
}

#[cfg_browser(false)]
mod arch {
    use std::{cell::RefCell, future::Future};

    use futures::{
        executor::{LocalPool, LocalSpawner},
        task::LocalSpawnExt,
    };
    use tokio::task_local;

    pub struct Runtime {
        executor: RefCell<LocalPool>,
        spawner: LocalSpawner,
    }

    impl Default for Runtime {
        fn default() -> Self {
            let executor = RefCell::new(LocalPool::new());
            let spawner = executor.borrow().spawner();

            Self { executor, spawner }
        }
    }

    task_local! {
        pub static RUNTIME: Runtime;
    }

    fn with_runtime<R>(f: impl FnOnce(&Runtime) -> R) -> R {
        match RUNTIME.try_with(f) {
            Ok(r) => r,
            Err(_) => panic!("Must be run from within `silkenweb_task::task::scope`"),
        }
    }

    pub fn scope<Fut>(f: Fut) -> impl Future<Output = Fut::Output>
    where
        Fut: Future,
    {
        RUNTIME.scope(Runtime::default(), f)
    }

    pub fn sync_scope<F, R>(f: F) -> R
    where
        F: FnOnce() -> R,
    {
        RUNTIME.sync_scope(Runtime::default(), f)
    }

    pub async fn run_tasks() {
        run_tasks_sync()
    }

    pub fn run_tasks_sync() {
        with_runtime(|runtime| runtime.executor.borrow_mut().run_until_stalled())
    }

    pub fn spawn_local<F>(future: F)
    where
        F: Future<Output = ()> + 'static,
    {
        with_runtime(|runtime| runtime.spawner.spawn_local(future).unwrap())
    }
}

#[cfg_browser(true)]
mod arch {
    use std::future::Future;

    use js_sys::Promise;
    use wasm_bindgen::{JsValue, UnwrapThrowExt};
    use wasm_bindgen_futures::JsFuture;

    pub fn scope<Fut>(f: Fut) -> impl Future<Output = Fut::Output>
    where
        Fut: Future,
    {
        f
    }

    pub fn sync_scope<F, R>(f: F) -> R
    where
        F: FnOnce() -> R,
    {
        f()
    }

    // Microtasks are run in the order they were queued in Javascript, so we just
    // put a task on the queue and `await` it.
    pub async fn run_tasks() {
        let wait_for_microtasks = Promise::resolve(&JsValue::NULL);
        JsFuture::from(wait_for_microtasks).await.unwrap_throw();
    }

    pub fn spawn_local<F>(future: F)
    where
        F: Future<Output = ()> + 'static,
    {
        wasm_bindgen_futures::spawn_local(future)
    }
}

/// Run futures on the microtask queue, until no more progress can be
/// made.
///
/// Don't call this from a future already on the microtask queue.
pub async fn run_tasks() {
    arch::run_tasks().await
}

/// Run a future with a local task queue.
///
/// On the server, this creates a [`tokio`] task local queue. You can put
/// futures on this queue with [`spawn_local`].
///
/// On the browser, this does nothing and returns the original future.
pub use arch::scope;
/// Synchronous version of [`scope`].
pub use arch::sync_scope;

/// Spawn a future on the microtask queue.
pub fn spawn_local<F>(future: F)
where
    F: Future<Output = ()> + 'static,
{
    arch::spawn_local(future)
}

/// [`Signal`] methods that require a task queue.
pub trait TaskSignal: Signal {
    /// Convert `self` to a [`Mutable`].
    ///
    /// This uses the microtask queue to spawn a future that drives the signal.
    /// The resulting `Mutable` can be used to memoize the signal, allowing many
    /// signals to be derived from it.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use futures_signals::signal::Mutable;
    /// # use silkenweb_task::{sync_scope, server::run_tasks_sync, TaskSignal};
    /// #
    /// let source = Mutable::new(0);
    /// let signal = source.signal();
    ///
    /// // A scope isn't required on browser platforms
    /// sync_scope(|| {
    ///     let copy = signal.to_mutable();
    ///     assert_eq!(copy.get(), 0);
    ///     source.set(1);
    ///     run_tasks_sync();
    ///     assert_eq!(copy.get(), 1);
    /// });
    /// ```
    fn to_mutable(self) -> ReadOnlyMutable<Self::Item>;

    /// Run `callback` on each signal value.
    ///
    /// The future is spawned on the microtask queue. This is equivalent to
    /// `spawn_local(sig.for_each(callback))`.
    fn spawn_for_each<U, F>(self, callback: F)
    where
        U: Future<Output = ()> + 'static,
        F: FnMut(Self::Item) -> U + 'static;
}

impl<Sig> TaskSignal for Sig
where
    Sig: Signal + 'static,
{
    fn to_mutable(self) -> ReadOnlyMutable<Self::Item> {
        let mut s = Box::pin(self.to_stream());
        let first_value = s
            .next()
            .now_or_never()
            .expect("A `Signal`'s initial value must be `Ready` immediately")
            .expect("`Signal`s must have an initial value");
        let mutable = Mutable::new(first_value);

        spawn_local({
            clone!(mutable);

            async move {
                while let Some(value) = s.next().await {
                    mutable.set(value);
                }
            }
        });

        mutable.read_only()
    }

    fn spawn_for_each<U, F>(self, callback: F)
    where
        U: Future<Output = ()> + 'static,
        F: FnMut(Self::Item) -> U + 'static,
    {
        spawn_local(self.for_each(callback));
    }
}

/// [`SignalVec`] methods that require a task queue.
pub trait TaskSignalVec: SignalVec {
    /// Convert `self` to a [`MutableVec`].
    ///
    /// This uses the microtask queue to spawn a future that drives the signal.
    /// The resulting `MutableVec` can be used to memoize the signal, allowing
    /// many signals to be derived from it.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use futures_signals::signal_vec::MutableVec;
    /// # use silkenweb_task::{sync_scope, server::run_tasks_sync, TaskSignalVec};
    /// #
    /// let source = MutableVec::new();
    /// let signal = source.signal_vec();
    ///
    /// // A scope isn't required on browser platforms
    /// sync_scope(|| {
    ///     let copy = signal.to_mutable();
    ///     assert!(copy.lock_ref().is_empty());
    ///     source.lock_mut().push_cloned(1);
    ///     run_tasks_sync();
    ///     assert_eq!(*copy.lock_ref(), [1]);
    /// });
    /// ```
    fn to_mutable(self) -> MutableVec<Self::Item>;

    /// Run `callback` on each signal delta.
    ///
    /// The future is spawned on the microtask queue. This is equivalent to
    /// `spawn_local(sig.for_each(callback))`.
    fn spawn_for_each<U, F>(self, callback: F)
    where
        U: Future<Output = ()> + 'static,
        F: FnMut(VecDiff<Self::Item>) -> U + 'static;
}

impl<Sig> TaskSignalVec for Sig
where
    Self::Item: Clone + 'static,
    Sig: SignalVec + 'static,
{
    fn to_mutable(self) -> MutableVec<Self::Item> {
        let mv = MutableVec::new();

        self.spawn_for_each({
            clone!(mv);

            move |diff| {
                MutableVecLockMut::apply_vec_diff(&mut mv.lock_mut(), diff);
                async {}
            }
        });

        mv
    }

    fn spawn_for_each<U, F>(self, callback: F)
    where
        U: Future<Output = ()> + 'static,
        F: FnMut(VecDiff<Self::Item>) -> U + 'static,
    {
        spawn_local(self.for_each(callback));
    }
}