cranpose-core 0.9.9

Composition runtime and reactive state for Cranpose
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
//! Composition-scoped structured concurrency.
//!
//! `LaunchedEffect` covers work that starts because a key changed. This covers
//! the rest: work started from an event handler, timed work, work that feeds a
//! piece of state, and blocking work that must not run on the UI thread.
//! Everything here is owned by the composition — a scope cancels its tasks when
//! it leaves, and a timer stops when nothing is waiting on it — so an
//! application never keeps its own task list or its own "is this still alive"
//! flag.

#[cfg(not(any(target_arch = "wasm32", target_vendor = "apple")))]
use std::sync::{Condvar, Mutex, PoisonError};
use std::{
    cell::{Cell, RefCell},
    future::Future,
    pin::Pin,
    rc::Rc,
    sync::{
        Arc, OnceLock,
        atomic::{AtomicBool, Ordering},
    },
    task::{Context, Poll, Waker},
    time::Duration,
};

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast;
use web_time::Instant;

use crate::{
    hooks::{mutableStateOfNeverEqual, remember},
    runtime::{RuntimeHandle, TaskHandle, current_runtime_handle},
    state::{MutableState, State},
};

/// Spawns `future` on the current runtime's UI task queue.
///
/// Framework-internal: application code launches through a
/// [`CoroutineScope`] so the work is cancelled with its
/// composition. Returns `None` when there is no runtime on this thread.
pub fn spawn_ui_task(future: impl Future<Output = ()> + 'static) -> Option<TaskHandle> {
    current_runtime_handle().and_then(|runtime| runtime.spawn_ui(future))
}

/// A cancellation scope for work launched outside the composition pass.
///
/// Tasks launched through a scope are cancelled when the scope leaves the
/// composition, so a click handler can start an asynchronous job without the
/// job outliving the screen that started it.
#[derive(Clone)]
pub struct CoroutineScope {
    inner: Rc<ScopeInner>,
}

struct ScopeInner {
    runtime: Option<RuntimeHandle>,
    tasks: RefCell<Vec<TaskHandle>>,
    closed: Cell<bool>,
}

impl Drop for ScopeInner {
    fn drop(&mut self) {
        for task in self.tasks.get_mut().drain(..) {
            task.cancel();
        }
    }
}

struct CompositionScopeOwner(CoroutineScope);

impl Drop for CompositionScopeOwner {
    fn drop(&mut self) {
        self.0.inner.closed.set(true);
        self.0.cancel();
    }
}

impl CoroutineScope {
    /// Launches `future`, keeping it alive until it finishes or the scope is
    /// cancelled.
    pub fn launch(&self, future: impl Future<Output = ()> + 'static) {
        if self.inner.closed.get() {
            return;
        }
        let Some(runtime) = self.inner.runtime.clone() else {
            log::warn!("cranpose: a coroutine scope with no runtime dropped its work");
            return;
        };
        self.inner
            .tasks
            .borrow_mut()
            .retain(|task| !task.is_finished());
        if let Some(handle) = runtime.spawn_ui(future) {
            self.inner.tasks.borrow_mut().push(handle);
        }
    }

    /// Cancels every task this scope launched.
    pub fn cancel(&self) {
        let tasks = std::mem::take(&mut *self.inner.tasks.borrow_mut());
        for task in tasks {
            task.cancel();
        }
    }

    #[cfg(test)]
    pub(crate) fn probe_identity(&self) -> usize {
        Rc::as_ptr(&self.inner) as *const () as usize
    }
}

/// Remembers a [`CoroutineScope`] bound to this position in the composition.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberCoroutineScope() -> CoroutineScope {
    remember(|| {
        CompositionScopeOwner(CoroutineScope {
            inner: Rc::new(ScopeInner {
                runtime: current_runtime_handle(),
                tasks: RefCell::new(Vec::new()),
                closed: Cell::new(false),
            }),
        })
    })
    .with(|owner| owner.0.clone())
}

/// Resolves after `duration` has elapsed.
///
/// The wait is served by the framework's timer, which posts the wake-up onto
/// the runtime's UI queue. Nothing spins and no frames are requested while a
/// delay is pending, so a one-minute timer costs nothing for a minute.
pub fn delay(duration: Duration) -> Delay {
    Delay {
        deadline: Instant::now() + duration,
        armed: false,
        fired: Arc::new(AtomicBool::new(false)),
    }
}

/// The future returned by [`delay`].
pub struct Delay {
    deadline: Instant,
    armed: bool,
    fired: Arc<AtomicBool>,
}

impl Future for Delay {
    type Output = ();

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<()> {
        if self.fired.load(Ordering::Acquire) || Instant::now() >= self.deadline {
            return Poll::Ready(());
        }
        let this = self.get_mut();
        if !this.armed {
            this.armed = true;
            timer().arm(
                this.deadline,
                context.waker().clone(),
                Arc::clone(&this.fired),
            );
        }
        Poll::Pending
    }
}

/// Runs `tick` every `period` until the returned future is dropped.
///
/// The first tick happens after one full period, matching a repeating timer
/// rather than a leading-edge one.
pub async fn interval(period: Duration, mut tick: impl FnMut()) {
    loop {
        delay(period).await;
        tick();
    }
}

#[cfg(not(any(target_arch = "wasm32", target_vendor = "apple")))]
struct Alarm {
    deadline: Instant,
    waker: Waker,
    fired: Arc<AtomicBool>,
}

struct Timer {
    #[cfg(not(any(target_arch = "wasm32", target_vendor = "apple")))]
    alarms: Mutex<Vec<Alarm>>,
    #[cfg(not(any(target_arch = "wasm32", target_vendor = "apple")))]
    wake: Condvar,
}

fn timer() -> &'static Timer {
    static TIMER: OnceLock<&'static Timer> = OnceLock::new();
    TIMER.get_or_init(|| {
        let timer: &'static Timer = Box::leak(Box::new(Timer::new()));
        timer.start();
        timer
    })
}

#[cfg(not(any(target_arch = "wasm32", target_vendor = "apple")))]
impl Timer {
    fn new() -> Self {
        Self {
            alarms: Mutex::new(Vec::new()),
            wake: Condvar::new(),
        }
    }

    fn start(&'static self) {
        std::thread::Builder::new()
            .name("cranpose-timer".to_string())
            .spawn(move || self.run())
            .expect("the timer thread starts");
    }

    fn run(&self) {
        let mut alarms = self.alarms.lock().unwrap_or_else(PoisonError::into_inner);
        loop {
            let now = Instant::now();
            let mut due = Vec::new();
            let mut next: Option<Duration> = None;
            alarms.retain(|alarm| {
                if alarm.deadline <= now {
                    due.push((alarm.waker.clone(), Arc::clone(&alarm.fired)));
                    false
                } else {
                    let remaining = alarm.deadline - now;
                    next = Some(next.map_or(remaining, |current| current.min(remaining)));
                    true
                }
            });

            if !due.is_empty() {
                drop(alarms);
                for (waker, fired) in due {
                    fired.store(true, Ordering::Release);
                    waker.wake();
                }
                alarms = self.alarms.lock().unwrap_or_else(PoisonError::into_inner);
                continue;
            }

            alarms = match next {
                Some(timeout) => {
                    self.wake
                        .wait_timeout(alarms, timeout)
                        .unwrap_or_else(PoisonError::into_inner)
                        .0
                }
                None => self
                    .wake
                    .wait(alarms)
                    .unwrap_or_else(PoisonError::into_inner),
            };
        }
    }

    fn arm(&self, deadline: Instant, waker: Waker, fired: Arc<AtomicBool>) {
        let mut alarms = self.alarms.lock().unwrap_or_else(PoisonError::into_inner);
        alarms.push(Alarm {
            deadline,
            waker,
            fired,
        });
        self.wake.notify_one();
    }
}

/// Apple platforms hand each deadline to Grand Central Dispatch on the
/// user-interactive queue. A thread sleeping on a condition variable at the
/// default quality of service wakes about 8 ms late there, as macOS coalesces
/// its timers, so a one-frame `delay` often missed its frame; GCD at
/// user-interactive quality of service wakes within a millisecond.
#[cfg(target_vendor = "apple")]
impl Timer {
    fn new() -> Self {
        Self {}
    }

    fn start(&'static self) {}

    fn arm(&self, deadline: Instant, waker: Waker, fired: Arc<AtomicBool>) {
        use dispatch2::{DispatchQoS, DispatchQueue, DispatchTime, GlobalQueueIdentifier};

        let nanos = deadline
            .saturating_duration_since(Instant::now())
            .as_nanos()
            .min(i64::MAX as u128) as i64;
        let queue = DispatchQueue::global_queue(GlobalQueueIdentifier::QualityOfService(
            DispatchQoS::UserInteractive,
        ));
        let fire = move || {
            fired.store(true, Ordering::Release);
            waker.wake();
        };
        if queue.after(DispatchTime::NOW.time(nanos), fire).is_err() {
            log::error!("cranpose: GCD refused a timer; the delay never resolves");
        }
    }
}

#[cfg(target_arch = "wasm32")]
impl Timer {
    fn new() -> Self {
        Self {}
    }

    fn start(&'static self) {}

    fn arm(&self, deadline: Instant, waker: Waker, fired: Arc<AtomicBool>) {
        let millis = deadline
            .saturating_duration_since(Instant::now())
            .as_millis()
            .min(i32::MAX as u128) as i32;
        let callback = wasm_bindgen::closure::Closure::once_into_js(move || {
            fired.store(true, Ordering::Release);
            waker.wake();
        });
        let scheduled = web_sys::window().and_then(|window| {
            window
                .set_timeout_with_callback_and_timeout_and_arguments_0(
                    callback.unchecked_ref(),
                    millis,
                )
                .ok()
        });
        if scheduled.is_none() {
            log::warn!("cranpose: no window timer is available; the delay resolves immediately");
        }
    }
}

/// The producing half of an [`EventStream`].
///
/// A service that receives events from outside the composition — a platform
/// callback, a worker thread, a socket — publishes through a channel, and every
/// pending collector is woken. This is the shape that replaces
/// "register an observer, then drain a queue" everywhere in the framework.
pub struct EventChannel<T: 'static> {
    shared: Rc<ChannelShared<T>>,
}

struct ChannelShared<T: 'static> {
    ready: RefCell<std::collections::VecDeque<T>>,
    closed: std::cell::Cell<bool>,
    delivered: std::cell::Cell<usize>,
    wakers: RefCell<Vec<Waker>>,
}

impl<T: 'static> ChannelShared<T> {
    fn wake_all(&self) {
        for waker in self.wakers.borrow_mut().drain(..) {
            waker.wake();
        }
    }
}

impl<T: 'static> Default for EventChannel<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: 'static> EventChannel<T> {
    /// Creates an open channel.
    pub fn new() -> Self {
        Self {
            shared: Rc::new(ChannelShared {
                ready: RefCell::new(std::collections::VecDeque::new()),
                closed: std::cell::Cell::new(false),
                delivered: std::cell::Cell::new(0),
                wakers: RefCell::new(Vec::new()),
            }),
        }
    }

    /// The consuming half, handed to collectors.
    pub fn stream(&self) -> EventStream<T> {
        EventStream {
            shared: Rc::clone(&self.shared),
        }
    }

    /// Publishes one event and wakes every pending collector.
    pub fn send(&self, event: T) {
        if self.shared.closed.get() {
            return;
        }
        self.shared.ready.borrow_mut().push_back(event);
        self.shared.wake_all();
    }

    /// Ends the stream. Collectors drain what is queued and then finish.
    pub fn close(&self) {
        if self.shared.closed.get() {
            return;
        }
        self.shared.closed.set(true);
        self.shared.wake_all();
    }

    /// Whether the channel has been closed.
    pub fn is_closed(&self) -> bool {
        self.shared.closed.get()
    }

    /// How many events are queued but not yet taken.
    pub fn pending(&self) -> usize {
        self.shared.ready.borrow().len()
    }
}

/// The consuming half of an [`EventChannel`].
///
/// Collectors take events one at a time; an event goes to exactly one
/// collector, so two collectors share the stream rather than each seeing every
/// event.
pub struct EventStream<T: 'static> {
    shared: Rc<ChannelShared<T>>,
}

impl<T: 'static> Clone for EventStream<T> {
    fn clone(&self) -> Self {
        Self {
            shared: Rc::clone(&self.shared),
        }
    }
}

impl<T: 'static> EventStream<T> {
    /// Resolves with the next event, or `None` once the stream is closed and
    /// drained.
    pub fn next(&self) -> EventStreamNext<T> {
        EventStreamNext {
            shared: Rc::clone(&self.shared),
        }
    }

    /// How many events this stream has handed out.
    pub fn delivered(&self) -> usize {
        self.shared.delivered.get()
    }
}

/// The future returned by [`EventStream::next`].
pub struct EventStreamNext<T: 'static> {
    shared: Rc<ChannelShared<T>>,
}

impl<T: 'static> Future for EventStreamNext<T> {
    type Output = Option<T>;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<T>> {
        if let Some(event) = self.shared.ready.borrow_mut().pop_front() {
            self.shared.delivered.set(self.shared.delivered.get() + 1);
            return Poll::Ready(Some(event));
        }
        if self.shared.closed.get() {
            return Poll::Ready(None);
        }
        self.shared
            .wakers
            .borrow_mut()
            .push(context.waker().clone());
        Poll::Pending
    }
}

/// Collects `stream` for as long as this call stays in the composition,
/// handing each event to `on_event`.
///
/// `key` re-starts the collection when it changes, exactly like
/// `LaunchedEffect`.
#[expect(non_snake_case)]
#[track_caller]
pub fn CollectEvents<T, K>(stream: EventStream<T>, key: K, on_event: impl FnMut(T) + 'static)
where
    T: 'static,
    K: PartialEq + 'static,
{
    crate::__launched_effect_async_impl(
        crate::caller_location_key(),
        std::panic::Location::caller().into(),
        key,
        move |_scope| {
            let mut on_event = on_event;
            Box::pin(async move {
                while let Some(event) = stream.next().await {
                    on_event(event);
                }
            })
        },
    );
}

/// Collects `stream` into state, starting at `initial`.
///
/// The composition reads the latest value the stream produced, and recomposes
/// when a new one arrives.
#[expect(non_snake_case)]
#[track_caller]
pub fn collectAsState<T, K>(stream: EventStream<T>, key: K, initial: T) -> State<T>
where
    T: Clone + 'static,
    K: PartialEq + 'static,
{
    let state = remember(|| mutableStateOfNeverEqual(initial)).with(|state| *state);
    let sink = state;
    CollectEvents(stream, key, move |event| sink.set(event));
    state.as_state()
}

/// A `Send` publishing handle for a composition-scoped [`EventStream`].
///
/// Platform services publish events from whatever thread they run on — a JNI
/// callback, a worker, a socket reader. The sender hops each event onto the UI
/// thread through the runtime's dispatcher and pushes it into the stream the
/// composition is collecting, so no service and no application ever writes that
/// hop again.
pub struct EventSender<T: Send + 'static> {
    #[cfg(not(target_arch = "wasm32"))]
    dispatcher: crate::runtime::UiDispatcher,
    bridge: u64,
    _events: std::marker::PhantomData<fn(T)>,
}

impl<T: Send + 'static> Clone for EventSender<T> {
    fn clone(&self) -> Self {
        Self {
            #[cfg(not(target_arch = "wasm32"))]
            dispatcher: self.dispatcher.clone(),
            bridge: self.bridge,
            _events: std::marker::PhantomData,
        }
    }
}

impl<T: Send + 'static> EventSender<T> {
    /// Publishes `event` to the composition that owns this bridge.
    pub fn send(&self, event: T) {
        let bridge = self.bridge;
        #[cfg(not(target_arch = "wasm32"))]
        self.dispatcher
            .post(move || deliver_bridged::<T>(bridge, event));
        #[cfg(target_arch = "wasm32")]
        deliver_bridged::<T>(bridge, event);
    }
}

thread_local! {
    static BRIDGES: RefCell<std::collections::HashMap<u64, Rc<dyn std::any::Any>>> =
        RefCell::new(std::collections::HashMap::new());
}

static NEXT_BRIDGE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

fn deliver_bridged<T: Send + 'static>(bridge: u64, event: T) {
    let channel = BRIDGES.with(|bridges| bridges.borrow().get(&bridge).cloned());
    let Some(channel) = channel else {
        log::debug!("event bridge {bridge} is gone, one event dropped");
        return;
    };
    if let Ok(channel) = channel.downcast::<EventChannel<T>>() {
        channel.send(event);
    }
}

struct Bridge<T: Send + 'static> {
    id: u64,
    channel: Rc<EventChannel<T>>,
}

impl<T: Send + 'static> Bridge<T> {
    fn new() -> Self {
        let id = NEXT_BRIDGE.fetch_add(1, Ordering::Relaxed);
        let channel = Rc::new(EventChannel::<T>::new());
        BRIDGES.with(|bridges| {
            bridges
                .borrow_mut()
                .insert(id, Rc::clone(&channel) as Rc<dyn std::any::Any>)
        });
        Self { id, channel }
    }
}

impl<T: Send + 'static> Drop for Bridge<T> {
    fn drop(&mut self) {
        BRIDGES.with(|bridges| bridges.borrow_mut().remove(&self.id));
        self.channel.close();
    }
}

/// Turns a platform subscription into a composition-scoped [`EventStream`].
///
/// `subscribe` receives a `Send` [`EventSender`] and returns whatever
/// registration handle the service uses; that handle is dropped — unsubscribing
/// the service — when `key` changes or the composition leaves. This is the one
/// place the framework bridges "a service publishes from another thread" to
/// "a composition collects".
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberEventStream<T, K, R, S>(key: K, subscribe: S) -> EventStream<T>
where
    T: Send + 'static,
    K: PartialEq + 'static,
    R: 'static,
    S: FnOnce(EventSender<T>) -> R + 'static,
{
    let bridge = remember(Bridge::<T>::new);
    let (id, stream) = bridge.with(|bridge| (bridge.id, bridge.channel.stream()));
    #[cfg(not(target_arch = "wasm32"))]
    let dispatcher = current_runtime_handle().map(|runtime| runtime.dispatcher());

    crate::__disposable_effect_impl(crate::caller_location_key(), key, move |scope| {
        #[cfg(not(target_arch = "wasm32"))]
        let Some(dispatcher) = dispatcher else {
            log::warn!("cranpose: an event stream was remembered without a runtime");
            return scope.on_dispose(|| {});
        };
        let registration = subscribe(EventSender {
            #[cfg(not(target_arch = "wasm32"))]
            dispatcher,
            bridge: id,
            _events: std::marker::PhantomData,
        });
        scope.on_dispose(move || drop(registration))
    });

    stream
}

/// Runs `producer` when `key` changes and exposes what it publishes as state.
///
/// The Compose `produceState` contract: the producer receives a handle it uses
/// to publish values, and is cancelled when the key changes or the composition
/// leaves.
#[expect(non_snake_case)]
#[track_caller]
pub fn produceState<T, K, F>(initial: T, key: K, producer: F) -> State<T>
where
    T: Clone + 'static,
    K: PartialEq + 'static,
    F: FnOnce(ProduceScope<T>) -> Pin<Box<dyn Future<Output = ()>>> + 'static,
{
    let state = remember(|| mutableStateOfNeverEqual(initial)).with(|state| *state);
    let handle = ProduceScope { state };
    crate::__launched_effect_async_impl(
        crate::caller_location_key(),
        std::panic::Location::caller().into(),
        key,
        move |_scope| producer(handle),
    );
    state.as_state()
}

/// The publishing half handed to a [`produceState`] producer.
pub struct ProduceScope<T: Clone + 'static> {
    state: MutableState<T>,
}

impl<T: Clone + 'static> ProduceScope<T> {
    /// Publishes `value` to the produced state.
    pub fn set(&self, value: T) {
        self.state.set(value);
    }
}

#[cfg(test)]
#[path = "tests/concurrency_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "tests/concurrency_stream_tests.rs"]
mod stream_tests;

#[cfg(test)]
#[path = "tests/concurrency_timer_race_tests.rs"]
mod timer_race_tests;