cranpose-services 0.1.163

Multiplatform system services for Cranpose (HTTP, URI, and OS integrations)
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
//! Framework-owned application-host state and controls.

use std::{
    path::{Path, PathBuf},
    sync::{
        Arc, Mutex, OnceLock,
        atomic::{AtomicU8, AtomicU64, Ordering},
    },
};

/// Platform directory roots for application-owned files.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PlatformDirectories {
    pub data: PathBuf,
    pub config: PathBuf,
    pub cache: PathBuf,
    pub documents: Option<PathBuf>,
    pub temporary: PathBuf,
    pub shared: Option<PathBuf>,
}

impl PlatformDirectories {
    fn scoped(&self, application_id: &str) -> Self {
        Self {
            data: self.data.join(application_id),
            config: self.config.join(application_id),
            cache: self.cache.join(application_id),
            documents: self
                .documents
                .as_ref()
                .map(|path| path.join(application_id)),
            temporary: self.temporary.join(application_id),
            shared: self.shared.as_ref().map(|path| path.join(application_id)),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
pub enum PlatformDirectoryError {
    #[error("application id must be one non-empty path component")]
    InvalidApplicationId,
    #[error("no application id has been registered")]
    NoApplicationId,
    #[error("platform directories are unavailable")]
    Unavailable,
}

/// Android-style lifecycle state exposed to composition observers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LifecycleState {
    Created,
    Started,
    Resumed,
    Paused,
    Stopped,
    Destroyed,
}

/// A lifecycle transition delivered by the platform host.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct LifecycleEvent {
    pub from: LifecycleState,
    pub to: LifecycleState,
}

/// Host operations supplied by the framework platform backend.
pub trait HostController: Send + Sync {
    /// Keeps the host window awake while enabled.
    fn set_keep_screen_on(&self, enabled: bool);
    /// Returns platform directory roots inside the application's host sandbox.
    fn platform_directories(&self) -> Option<PlatformDirectories>;
    /// Finishes/backgrounds the host.
    fn exit(&self);
    /// Requests that the app move to the background.
    fn background(&self);
    /// How long this host will wait for durable saves before it suspends the
    /// app. Android's `onPause` and iOS's background transition each allow a
    /// short, platform-defined budget; work that overruns it keeps running
    /// under a background-work lease.
    fn durable_save_deadline(&self) -> std::time::Duration {
        DEFAULT_DURABLE_SAVE_DEADLINE
    }
}

/// The budget used when a host does not state one of its own.
pub const DEFAULT_DURABLE_SAVE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2);

/// How long the installed host will wait for durable saves.
pub fn durable_save_deadline() -> std::time::Duration {
    host_controller().map_or(DEFAULT_DURABLE_SAVE_DEADLINE, |host| {
        host.durable_save_deadline()
    })
}

pub type HostControllerRef = Arc<dyn HostController>;

fn controller() -> &'static Mutex<Option<HostControllerRef>> {
    static SLOT: OnceLock<Mutex<Option<HostControllerRef>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(None))
}

/// Installs the framework host controller.
pub fn set_host_controller(value: HostControllerRef) {
    if let Ok(mut slot) = controller().lock() {
        *slot = Some(value);
    }
    KEEP_SCREEN_ON.store(0, Ordering::Release);
}
/// Removes the installed host controller.
pub fn clear_host_controller() {
    if let Ok(mut slot) = controller().lock() {
        *slot = None;
    }
    KEEP_SCREEN_ON.store(0, Ordering::Release);
}
/// Returns the installed framework host controller.
pub fn host_controller() -> Option<HostControllerRef> {
    controller().lock().ok().and_then(|slot| slot.clone())
}
/// Enables or disables the host's keep-screen-on flag.
pub fn set_keep_screen_on(enabled: bool) {
    let value = if enabled { 2 } else { 1 };
    if KEEP_SCREEN_ON.swap(value, Ordering::AcqRel) == value {
        return;
    }
    if let Some(host) = host_controller() {
        host.set_keep_screen_on(enabled);
    }
}
fn valid_application_id(application_id: &str) -> bool {
    !application_id.is_empty()
        && Path::new(application_id).components().count() == 1
        && application_id != "."
        && application_id != ".."
}

fn desktop_platform_directories() -> Option<PlatformDirectories> {
    let base = directories::BaseDirs::new()?;
    let documents = directories::UserDirs::new()
        .and_then(|directories| directories.document_dir().map(Path::to_path_buf));
    Some(PlatformDirectories {
        data: base.data_dir().to_path_buf(),
        config: base.config_dir().to_path_buf(),
        cache: base.cache_dir().to_path_buf(),
        documents,
        temporary: std::env::temp_dir(),
        shared: None,
    })
}

fn application_id_slot() -> &'static Mutex<Option<String>> {
    static SLOT: OnceLock<Mutex<Option<String>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(None))
}

/// Registers the id every framework-owned storage path is scoped by.
///
/// Platform backends call this at startup with what the platform packaged —
/// the Android package name, the iOS bundle identifier, the desktop
/// application name — so applications never assemble a storage path
/// themselves.
pub fn set_application_id(application_id: &str) -> Result<(), PlatformDirectoryError> {
    if !valid_application_id(application_id) {
        return Err(PlatformDirectoryError::InvalidApplicationId);
    }
    if let Ok(mut slot) = application_id_slot().lock() {
        *slot = Some(application_id.to_string());
    }
    Ok(())
}

/// Removes the registered application id (tests and teardown).
pub fn clear_application_id() {
    if let Ok(mut slot) = application_id_slot().lock() {
        *slot = None;
    }
}

/// The registered application id, if a host has published one.
pub fn application_id() -> Option<String> {
    application_id_slot()
        .lock()
        .ok()
        .and_then(|slot| slot.clone())
}

/// Returns typed directories for the registered application.
pub fn application_directories() -> Result<PlatformDirectories, PlatformDirectoryError> {
    let application_id = application_id().ok_or(PlatformDirectoryError::NoApplicationId)?;
    let roots = host_controller()
        .and_then(|host| host.platform_directories())
        .or_else(desktop_platform_directories)
        .ok_or(PlatformDirectoryError::Unavailable)?;
    Ok(roots.scoped(&application_id))
}
/// Requests that the host finish the app.
pub fn exit_app() {
    if let Some(host) = host_controller() {
        host.exit();
    }
}
/// Requests that the host move the app to the background.
pub fn background_app() {
    if let Some(host) = host_controller() {
        host.background();
    }
}

#[cfg(not(target_arch = "wasm32"))]
type Observer = Arc<dyn Fn(LifecycleEvent) + Send + Sync>;
#[cfg(target_arch = "wasm32")]
type Observer = std::rc::Rc<dyn Fn(LifecycleEvent)>;

#[cfg(not(target_arch = "wasm32"))]
fn observers() -> &'static Mutex<Vec<(u64, Observer)>> {
    static SLOT: OnceLock<Mutex<Vec<(u64, Observer)>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Vec::new()))
}
#[cfg(target_arch = "wasm32")]
thread_local! {
    static OBSERVERS: std::cell::RefCell<Vec<(u64, Observer)>> = const { std::cell::RefCell::new(Vec::new()) };
}
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
static LIFECYCLE_STATE: AtomicU8 = AtomicU8::new(LifecycleState::Created as u8);
static KEEP_SCREEN_ON: AtomicU8 = AtomicU8::new(0);

/// RAII lifecycle observer registration.
pub struct LifecycleObserver {
    id: u64,
}
impl Drop for LifecycleObserver {
    fn drop(&mut self) {
        #[cfg(not(target_arch = "wasm32"))]
        if let Ok(mut list) = observers().lock() {
            list.retain(|(id, _)| *id != self.id);
        }
        #[cfg(target_arch = "wasm32")]
        OBSERVERS.with(|list| list.borrow_mut().retain(|(id, _)| *id != self.id));
    }
}
/// Observes host lifecycle transitions until the returned handle is dropped.
#[cfg(not(target_arch = "wasm32"))]
pub fn observe_lifecycle(
    observer: impl Fn(LifecycleEvent) + Send + Sync + 'static,
) -> LifecycleObserver {
    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    if let Ok(mut list) = observers().lock() {
        list.push((id, Arc::new(observer)));
    }
    LifecycleObserver { id }
}
/// Observes host lifecycle transitions until the returned handle is dropped.
#[cfg(target_arch = "wasm32")]
pub fn observe_lifecycle(observer: impl Fn(LifecycleEvent) + 'static) -> LifecycleObserver {
    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    OBSERVERS.with(|list| list.borrow_mut().push((id, std::rc::Rc::new(observer))));
    LifecycleObserver { id }
}
/// Publishes a lifecycle transition from the platform host.
pub fn dispatch_lifecycle(event: LifecycleEvent) {
    LIFECYCLE_STATE.store(event.to as u8, Ordering::Release);
    crate::media::on_lifecycle(event);
    #[cfg(not(target_arch = "wasm32"))]
    let callbacks = observers()
        .lock()
        .map(|list| {
            list.iter()
                .map(|(_, cb)| Arc::clone(cb))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    #[cfg(target_arch = "wasm32")]
    let callbacks = OBSERVERS.with(|list| {
        list.borrow()
            .iter()
            .map(|(_, callback)| std::rc::Rc::clone(callback))
            .collect::<Vec<_>>()
    });
    for callback in callbacks {
        callback(event);
    }
}

/// Returns the latest lifecycle state published by the platform host.
pub fn current_lifecycle_state() -> LifecycleState {
    match LIFECYCLE_STATE.load(Ordering::Acquire) {
        0 => LifecycleState::Created,
        1 => LifecycleState::Started,
        2 => LifecycleState::Resumed,
        3 => LifecycleState::Paused,
        4 => LifecycleState::Stopped,
        _ => LifecycleState::Destroyed,
    }
}

/// Publishes a platform lifecycle state and derives the transition source from
/// the framework's previous state.
///
/// Leaving the foreground runs every registered durable save first, inside the
/// budget the host allows, so an application never has to hook the transition
/// itself to persist its data.
pub fn dispatch_lifecycle_state(to: LifecycleState) {
    let from = current_lifecycle_state();
    if from == to {
        return;
    }
    #[cfg(not(target_arch = "wasm32"))]
    if matches!(to, LifecycleState::Paused) {
        let outcome = run_durable_saves(durable_save_deadline());
        if outcome == DurableSaveOutcome::TimedOut {
            log::warn!("cranpose: durable saves overran the host deadline; they keep running");
        }
    }
    dispatch_lifecycle(LifecycleEvent { from, to });
}

/// The lifecycle state of a window or browser page that is `visible` and
/// has keyboard `focused`, mapped the way Compose Multiplatform maps desktop
/// windows: resumed while focused, paused while only visible, and stopped
/// while minimized, hidden or in a background tab.
pub fn window_lifecycle_state(visible: bool, focused: bool) -> LifecycleState {
    match (visible, focused) {
        (false, _) => LifecycleState::Stopped,
        (true, true) => LifecycleState::Resumed,
        (true, false) => LifecycleState::Paused,
    }
}

impl LifecycleState {
    /// Whether this state is at least as active as `other`, counting paused
    /// as started and stopped as created — Android's `isAtLeast`.
    pub fn is_at_least(self, other: LifecycleState) -> bool {
        lifecycle_level(self) >= lifecycle_level(other)
    }
}

fn lifecycle_level(state: LifecycleState) -> u8 {
    match state {
        LifecycleState::Destroyed => 0,
        LifecycleState::Created | LifecycleState::Stopped => 1,
        LifecycleState::Started | LifecycleState::Paused => 2,
        LifecycleState::Resumed => 3,
    }
}

fn next_lifecycle_step(from: LifecycleState, to: LifecycleState) -> Option<LifecycleState> {
    let rising = match lifecycle_level(from).cmp(&lifecycle_level(to)) {
        std::cmp::Ordering::Equal => return None,
        std::cmp::Ordering::Less => true,
        std::cmp::Ordering::Greater => false,
    };
    match (from, rising) {
        (LifecycleState::Destroyed, _) => None,
        (LifecycleState::Created | LifecycleState::Stopped, true) => Some(LifecycleState::Started),
        (LifecycleState::Started | LifecycleState::Paused, true) => Some(LifecycleState::Resumed),
        (LifecycleState::Resumed, _) => Some(LifecycleState::Paused),
        (LifecycleState::Started | LifecycleState::Paused, false) => Some(LifecycleState::Stopped),
        (LifecycleState::Created | LifecycleState::Stopped, false) => {
            Some(LifecycleState::Destroyed)
        }
    }
}

/// Moves the host lifecycle to `target` through every state in between, in
/// Android's order: a stopped app starts before it resumes, and a resumed one
/// pauses before it stops, so leaving the foreground always runs the durable
/// saves. Paused and started count as the same place, as do created and
/// stopped. Hosts whose platform reports only visibility and focus use this
/// instead of dispatching each transition themselves.
pub fn advance_lifecycle(target: LifecycleState) {
    while let Some(next) = next_lifecycle_step(current_lifecycle_state(), target) {
        dispatch_lifecycle_state(next);
    }
}

/// The `CompositionLocal` carrying the host's current lifecycle state.
///
/// [`ProvideLifecycle`] installs it; descendants read it and recompose on every
/// transition, so a screen can pause its own work without registering an
/// observer of its own.
pub fn local_lifecycle_state() -> cranpose_core::CompositionLocal<LifecycleState> {
    thread_local! {
        static LOCAL: std::cell::RefCell<Option<cranpose_core::CompositionLocal<LifecycleState>>> =
            const { std::cell::RefCell::new(None) };
    }
    LOCAL.with(|cell| {
        cell.borrow_mut()
            .get_or_insert_with(|| cranpose_core::compositionLocalOf(current_lifecycle_state))
            .clone()
    })
}

/// The host's lifecycle state as observable state.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberLifecycleState() -> cranpose_core::State<LifecycleState> {
    let transitions = rememberLifecycleEvents();
    let state = cranpose_core::collectAsState(
        transitions,
        (),
        LifecycleEvent {
            from: current_lifecycle_state(),
            to: current_lifecycle_state(),
        },
    );
    cranpose_core::derivedStateOf(move || state.get().to)
}

/// Host lifecycle transitions as a composition-scoped stream.
#[expect(non_snake_case)]
#[track_caller]
pub fn rememberLifecycleEvents() -> cranpose_core::EventStream<LifecycleEvent> {
    cranpose_core::rememberEventStream((), |sender| {
        observe_lifecycle(move |event| sender.send(event))
    })
}

/// Provides the host's lifecycle state to descendant composables.
///
/// The application shell wraps its content in this once; screens then read
/// [`local_lifecycle_state`].
#[cranpose_macros::composable]
pub fn ProvideLifecycle(content: impl FnOnce()) {
    let state = rememberLifecycleState();
    let local = local_lifecycle_state();
    cranpose_core::CompositionLocalProvider(vec![local.provides(state.get())], move || {
        content();
    });
}

/// What became of the durable saves the host asked for.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DurableSaveOutcome {
    /// Nothing was registered.
    Nothing,
    /// Every registered save finished inside the deadline.
    Completed,
    /// The deadline expired with saves still running. They keep running under
    /// a background-work lease, but the host is free to suspend.
    TimedOut,
}

type SaveWork = Arc<dyn Fn() + Send + Sync>;

fn durable_saves() -> &'static Mutex<Vec<(u64, SaveWork)>> {
    static SLOT: OnceLock<Mutex<Vec<(u64, SaveWork)>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(Vec::new()))
}

/// Keeps a durable save registered until it is dropped.
pub struct DurableSaveRegistration {
    id: u64,
}

impl Drop for DurableSaveRegistration {
    fn drop(&mut self) {
        if let Ok(mut saves) = durable_saves().lock() {
            saves.retain(|(id, _)| *id != self.id);
        }
    }
}

/// Registers work that must reach durable storage before the host suspends.
///
/// Applications use [`DurableSaveEffect`] so the registration is scoped to the
/// composition that owns the data.
pub fn register_durable_save(save: impl Fn() + Send + Sync + 'static) -> DurableSaveRegistration {
    let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
    if let Ok(mut saves) = durable_saves().lock() {
        saves.push((id, Arc::new(save)));
    }
    DurableSaveRegistration { id }
}

/// Registers `save` for as long as this call stays in the composition.
///
/// The host runs it when the app is about to be suspended, off the UI thread
/// and under a background-work lease, so a slow write does not stall the
/// lifecycle callback the platform is waiting on.
#[expect(non_snake_case)]
#[track_caller]
pub fn DurableSaveEffect<K: PartialEq + 'static>(keys: K, save: impl Fn() + Send + Sync + 'static) {
    cranpose_core::__disposable_effect_impl(
        cranpose_core::caller_location_key()
            ^ cranpose_core::location_key(file!(), line!(), column!()),
        keys,
        move |scope| {
            let registration = register_durable_save(save);
            scope.on_dispose(move || drop(registration))
        },
    );
}

/// Runs every registered durable save, waiting up to `deadline`.
///
/// Platform hosts call this from the lifecycle callback the OS gives them —
/// Android's `onPause`, iOS's `applicationDidEnterBackground` — passing the
/// budget that platform allows. Saves run on worker threads under a
/// background-work lease, so work that overruns the deadline still finishes
/// while the OS keeps the process alive.
#[cfg(not(target_arch = "wasm32"))]
pub fn run_durable_saves(deadline: std::time::Duration) -> DurableSaveOutcome {
    let saves: Vec<SaveWork> = durable_saves()
        .lock()
        .map(|saves| saves.iter().map(|(_, save)| Arc::clone(save)).collect())
        .unwrap_or_default();
    if saves.is_empty() {
        return DurableSaveOutcome::Nothing;
    }

    let outstanding = Arc::new(std::sync::atomic::AtomicUsize::new(saves.len()));
    let finished = Arc::new((Mutex::new(false), std::sync::Condvar::new()));
    for save in saves {
        let worker_outstanding = Arc::clone(&outstanding);
        let worker_finished = Arc::clone(&finished);
        let lease = crate::background::acquire_background_work();
        let spawned = std::thread::Builder::new()
            .name("cranpose-durable-save".to_string())
            .spawn(move || {
                save();
                drop(lease);
                if worker_outstanding.fetch_sub(1, Ordering::AcqRel) == 1 {
                    let (done, wake) = &*worker_finished;
                    if let Ok(mut done) = done.lock() {
                        *done = true;
                    }
                    wake.notify_all();
                }
            });
        if spawned.is_err() {
            log::warn!("cranpose: a durable save could not be started");
            if outstanding.fetch_sub(1, Ordering::AcqRel) == 1 {
                let (done, wake) = &*finished;
                if let Ok(mut done) = done.lock() {
                    *done = true;
                }
                wake.notify_all();
            }
        }
    }

    let (done, wake) = &*finished;
    let Ok(mut guard) = done.lock() else {
        return DurableSaveOutcome::TimedOut;
    };
    let mut remaining = deadline;
    let started = web_time::Instant::now();
    while !*guard {
        let Ok((next, timeout)) = wake.wait_timeout(guard, remaining) else {
            return DurableSaveOutcome::TimedOut;
        };
        guard = next;
        if timeout.timed_out() {
            break;
        }
        remaining = deadline.saturating_sub(started.elapsed());
        if remaining.is_zero() {
            break;
        }
    }
    if *guard {
        DurableSaveOutcome::Completed
    } else {
        DurableSaveOutcome::TimedOut
    }
}

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