Skip to main content

day_part_background/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Background work registered independently of the UI. Register tasks at link time so an
5//! Android Worker or an iOS background launch can find them before any page is mounted.
6//! Schedules are requests: the OS decides when work runs and may stop it before completion.
7//! Use [`in_process`] for jobs that only need to run while this process stays alive.
8
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::sync::{
12    Arc, Mutex, OnceLock,
13    atomic::{AtomicBool, Ordering},
14};
15
16pub mod in_process;
17mod native;
18pub use day_process::linkme;
19
20#[derive(Clone, Debug, PartialEq, Eq)]
21pub enum Error {
22    Unsupported,
23    InvalidRequest(String),
24    Platform(String),
25}
26impl std::fmt::Display for Error {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        write!(f, "{self:?}")
29    }
30}
31impl std::error::Error for Error {}
32
33#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
34#[serde(rename_all = "snake_case")]
35pub enum Outcome {
36    Success,
37    Retry,
38    Failed,
39}
40
41/// The handler must check cancellation between bounded units of work and return promptly.
42pub struct Context {
43    pub payload: String,
44    cancelled: Arc<AtomicBool>,
45}
46impl Context {
47    pub fn is_cancelled(&self) -> bool {
48        self.cancelled.load(Ordering::Acquire)
49    }
50}
51
52pub struct TaskDefinition {
53    pub identifier: &'static str,
54    pub run: fn(Context) -> Outcome,
55}
56
57#[cfg(not(target_arch = "wasm32"))]
58#[linkme::distributed_slice]
59#[linkme(crate = day_process::linkme)]
60pub static TASKS: [TaskDefinition];
61
62/// Register a stable identifier and a function that does not require UI state.
63#[macro_export]
64macro_rules! register_task {
65    ($id:literal, $handler:path) => {
66        #[cfg(not(target_arch = "wasm32"))]
67        const _: () = {
68            #[$crate::linkme::distributed_slice($crate::TASKS)]
69            #[linkme(crate = $crate::linkme)]
70            static TASK: $crate::TaskDefinition = $crate::TaskDefinition {
71                identifier: $id,
72                run: $handler,
73            };
74        };
75    };
76}
77
78#[derive(Clone, Debug, Serialize, Deserialize)]
79pub struct Schedule {
80    pub identifier: String,
81    pub payload: String,
82    pub delay_secs: u64,
83    /// Best-effort repeat interval, at least 15 minutes. Never an exact timer.
84    pub interval_secs: Option<u64>,
85    pub requires_network: bool,
86    pub requires_charging: bool,
87}
88impl Schedule {
89    pub fn new(identifier: impl Into<String>) -> Self {
90        Self {
91            identifier: identifier.into(),
92            payload: String::new(),
93            delay_secs: 0,
94            interval_secs: None,
95            requires_network: false,
96            requires_charging: false,
97        }
98    }
99    fn validate(&self) -> Result<(), Error> {
100        if self.identifier.is_empty() || self.identifier.len() > 200 || self.payload.len() > 4096 {
101            return Err(Error::InvalidRequest(
102                "invalid identifier or payload larger than 4096 bytes".into(),
103            ));
104        }
105        if self.delay_secs > 31_536_000
106            || self
107                .interval_secs
108                .is_some_and(|n| !(900..=31_536_000).contains(&n))
109        {
110            return Err(Error::InvalidRequest(
111                "repeat intervals must be 15 minutes to one year; delay cannot exceed one year"
112                    .into(),
113            ));
114        }
115        if !definitions()
116            .iter()
117            .any(|task| task.identifier == self.identifier)
118        {
119            return Err(Error::InvalidRequest(
120                "task is not registered in this executable".into(),
121            ));
122        }
123        Ok(())
124    }
125}
126
127fn definitions() -> &'static [TaskDefinition] {
128    #[cfg(not(target_arch = "wasm32"))]
129    {
130        &TASKS
131    }
132    #[cfg(target_arch = "wasm32")]
133    {
134        &[]
135    }
136}
137
138/// Scheduler availability. Persistent scheduling may also require app manifest setup.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub struct Capabilities {
141    /// Jobs can run while the app process is alive and the OS permits it to execute.
142    pub in_process: bool,
143    /// The OS can retain jobs and launch the app's services after its process exits.
144    pub persistent: bool,
145}
146
147pub const fn capabilities() -> Capabilities {
148    Capabilities {
149        in_process: cfg!(any(
150            target_os = "macos",
151            target_os = "windows",
152            all(target_os = "linux", not(target_env = "ohos")),
153            target_os = "ios",
154            target_os = "android",
155        )),
156        persistent: cfg!(any(target_os = "ios", target_os = "android")),
157    }
158}
159
160/// Whether persistent OS scheduling is available. See [`capabilities`] for in-process work.
161pub const fn supported() -> bool {
162    capabilities().persistent
163}
164
165/// Persist an OS schedule; never falls back to in-process scheduling.
166/// Replace a pending schedule for this identifier. An already executing handler receives
167/// cancellation on Android; callers must make writes idempotent across retries and restarts.
168///
169/// # Errors
170///
171/// Returns [`Error::InvalidRequest`] for a malformed request or an unregistered task,
172/// [`Error::Unsupported`] where the OS has no persistent scheduling, and
173/// [`Error::Platform`] when the OS rejects the schedule.
174pub async fn schedule(request: &Schedule) -> Result<(), Error> {
175    request.validate()?;
176    if !supported() {
177        return Err(Error::Unsupported);
178    }
179    start()?;
180    let text = serde_json::to_string(request).map_err(|e| Error::InvalidRequest(e.to_string()))?;
181    native::schedule_native_future(&text)
182        .await
183        .map_err(bridge_error)
184        .and_then(answer)
185}
186/// Cancel the persistent OS schedule for `identifier`.
187///
188/// # Errors
189///
190/// Returns [`Error::Unsupported`] where the OS has no persistent scheduling, and
191/// [`Error::Platform`] when the OS reports a failure.
192pub async fn cancel(identifier: &str) -> Result<(), Error> {
193    if !supported() {
194        return Err(Error::Unsupported);
195    }
196    native::cancel_native_future(identifier)
197        .await
198        .map_err(bridge_error)
199        .and_then(answer)
200}
201
202/// Run a registered handler now, for foreground diagnostics. This does not exercise OS scheduling.
203///
204/// # Errors
205///
206/// Returns [`Error::InvalidRequest`] when no handler is registered for `identifier`.
207pub fn run_now(identifier: &str, payload: String) -> Result<Outcome, Error> {
208    let task = definitions()
209        .iter()
210        .find(|task| task.identifier == identifier)
211        .ok_or_else(|| Error::InvalidRequest("unknown task".into()))?;
212    Ok((task.run)(Context {
213        payload,
214        cancelled: Arc::new(AtomicBool::new(false)),
215    }))
216}
217
218type Runs = Mutex<HashMap<i64, Arc<AtomicBool>>>;
219static RUNS: OnceLock<Runs> = OnceLock::new();
220fn runs() -> &'static Runs {
221    RUNS.get_or_init(Mutex::default)
222}
223
224#[derive(Deserialize)]
225#[serde(tag = "event", rename_all = "snake_case")]
226enum Delivery {
227    Run {
228        run: i64,
229        identifier: String,
230        payload: String,
231    },
232    Cancel {
233        run: i64,
234    },
235}
236
237fn start() -> Result<(), Error> {
238    static STARTED: OnceLock<Result<(), Error>> = OnceLock::new();
239    STARTED
240        .get_or_init(|| {
241            let mut ids = std::collections::HashSet::new();
242            for definition in definitions() {
243                if !ids.insert(definition.identifier) {
244                    return Err(Error::InvalidRequest(
245                        "duplicate background task identifier".into(),
246                    ));
247                }
248            }
249            native::events_native_stream(|item| {
250                if let day_bridge::Item::Value(json) = item {
251                    match serde_json::from_str::<Delivery>(&json) {
252                        Ok(Delivery::Cancel { run }) => {
253                            if let Some(cancelled) = runs()
254                                .lock()
255                                .unwrap_or_else(std::sync::PoisonError::into_inner)
256                                .get(&run)
257                            {
258                                cancelled.store(true, Ordering::Release);
259                            }
260                        }
261                        Ok(Delivery::Run {
262                            run,
263                            identifier,
264                            payload,
265                        }) => dispatch(run, &identifier, payload),
266                        Err(_) => {}
267                    }
268                }
269            })
270            .map_err(bridge_error)?;
271            let mut identifiers: Vec<_> = ids.into_iter().collect();
272            identifiers.sort_unstable();
273            native::initialize(
274                &serde_json::to_string(&identifiers)
275                    .map_err(|e| Error::InvalidRequest(e.to_string()))?,
276            )
277            .map_err(bridge_error)
278        })
279        .clone()
280}
281
282fn dispatch(run: i64, identifier: &str, payload: String) {
283    let Some(task) = definitions()
284        .iter()
285        .find(|task| task.identifier == identifier)
286    else {
287        let _ = native::finish(run, "failed");
288        return;
289    };
290    let cancelled = Arc::new(AtomicBool::new(false));
291    {
292        let mut active = runs()
293            .lock()
294            .unwrap_or_else(std::sync::PoisonError::into_inner);
295        if active.contains_key(&run) {
296            return;
297        }
298        active.insert(run, cancelled.clone());
299    }
300    let handler = task.run;
301    #[cfg(not(target_arch = "wasm32"))]
302    {
303        let spawned = std::thread::Builder::new()
304            .name("day-background".into())
305            .spawn(move || {
306                let result = std::panic::catch_unwind(|| handler(Context { payload, cancelled }))
307                    .unwrap_or(Outcome::Failed);
308                runs()
309                    .lock()
310                    .unwrap_or_else(std::sync::PoisonError::into_inner)
311                    .remove(&run);
312                let value = match result {
313                    Outcome::Success => "success",
314                    Outcome::Retry => "retry",
315                    Outcome::Failed => "failed",
316                };
317                let _ = native::finish(run, value);
318            });
319        if spawned.is_err() {
320            runs()
321                .lock()
322                .unwrap_or_else(std::sync::PoisonError::into_inner)
323                .remove(&run);
324            let _ = native::finish(run, "failed");
325        }
326    }
327    #[cfg(target_arch = "wasm32")]
328    {
329        let _ = (handler, payload, cancelled);
330    }
331}
332
333#[cfg(any(target_os = "ios", target_os = "android"))]
334#[day_process::linkme::distributed_slice(day_process::services::SERVICES)]
335#[linkme(crate = day_process::linkme)]
336static SERVICE: day_process::services::Service = day_process::services::Service {
337    name: "background",
338    initialize: || {
339        let _ = start();
340    },
341};
342
343#[expect(
344    clippy::needless_pass_by_value,
345    reason = "passed to `map_err`, which hands the error over by value"
346)]
347fn bridge_error(e: day_bridge::Error) -> Error {
348    if matches!(e, day_bridge::Error::Unsupported) {
349        Error::Unsupported
350    } else {
351        Error::Platform(e.to_string())
352    }
353}
354fn answer(value: String) -> Result<(), Error> {
355    if value.is_empty() {
356        Ok(())
357    } else {
358        Err(Error::Platform(value))
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365    register_task!("dev.daybrite.fixture", fixture);
366    #[expect(
367        clippy::needless_pass_by_value,
368        reason = "`TaskDefinition::run` fixes the handler signature"
369    )]
370    fn fixture(context: Context) -> Outcome {
371        if context.is_cancelled() {
372            Outcome::Retry
373        } else {
374            Outcome::Success
375        }
376    }
377    #[test]
378    fn schedules_require_registered_handlers_and_bounded_payloads() {
379        assert!(Schedule::new("unknown").validate().is_err());
380        let mut request = Schedule::new("dev.daybrite.fixture");
381        assert!(request.validate().is_ok());
382        request.interval_secs = Some(30);
383        assert!(request.validate().is_err());
384        request.interval_secs = Some(900);
385        request.payload = "x".repeat(4097);
386        assert!(request.validate().is_err());
387    }
388    #[test]
389    fn cancellation_reaches_a_running_handler() {
390        let cancelled = Arc::new(AtomicBool::new(true));
391        assert_eq!(
392            fixture(Context {
393                payload: String::new(),
394                cancelled
395            }),
396            Outcome::Retry
397        );
398        assert_eq!(
399            run_now("dev.daybrite.fixture", String::new()),
400            Ok(Outcome::Success)
401        );
402    }
403
404    #[test]
405    fn in_process_constraints_are_rejected_instead_of_ignored() {
406        let mut request = Schedule::new("dev.daybrite.fixture");
407        request.requires_network = true;
408        assert_eq!(in_process::schedule(&request), Err(Error::Unsupported));
409        request.requires_network = false;
410        request.requires_charging = true;
411        assert_eq!(in_process::schedule(&request), Err(Error::Unsupported));
412    }
413}