Skip to main content

day_part_push/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! APNs and FCM registration and delivery. Sender credentials belong on your server.
5//! Call `watch` before `register`; token changes arrive as events and must be sent to your server.
6
7#[cfg(all(target_os = "android", feature = "android-fcm"))]
8use day_part_push_android_fcm as backend;
9#[cfg(all(target_os = "ios", feature = "ios-apns"))]
10use day_part_push_ios_apns as backend;
11use serde::{Deserialize, Serialize};
12use std::collections::{BTreeMap, VecDeque};
13use std::sync::{Arc, Mutex, OnceLock};
14#[cfg(not(any(
15    all(target_os = "ios", feature = "ios-apns"),
16    all(target_os = "android", feature = "android-fcm")
17)))]
18mod backend {
19    static REQUESTS: day_bridge::Registry<String> = day_bridge::Registry::new();
20    pub fn start(_: impl Fn(String) + Send + Sync + 'static) -> Result<(), day_bridge::Error> {
21        Err(day_bridge::Error::Unsupported)
22    }
23    pub fn register() -> day_bridge::Completion<String> {
24        day_bridge::start_future(&REQUESTS, |_| Err(day_bridge::Error::Unsupported))
25    }
26    pub fn unregister() -> day_bridge::Completion<String> {
27        register()
28    }
29}
30
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub enum Error {
33    Unsupported,
34    PermissionDenied,
35    /// HTTP status from the optional relay; response bodies are not echoed.
36    RelayStatus(u16),
37    Platform(String),
38}
39impl std::fmt::Display for Error {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        write!(f, "{self:?}")
42    }
43}
44impl std::error::Error for Error {}
45
46#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
47#[serde(rename_all = "snake_case")]
48pub enum Provider {
49    Apns,
50    Fcm,
51}
52
53#[derive(Clone, Serialize, Deserialize)]
54pub struct Token {
55    pub provider: Provider,
56    pub value: String,
57}
58impl std::fmt::Debug for Token {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.debug_struct("Token")
61            .field("provider", &self.provider)
62            .finish_non_exhaustive()
63    }
64}
65
66#[derive(Clone, Debug, Serialize, Deserialize)]
67#[serde(tag = "event", rename_all = "snake_case")]
68pub enum Event {
69    Token {
70        token: Token,
71    },
72    Message {
73        payload: serde_json::Value,
74        opened: bool,
75    },
76    Error {
77        message: String,
78    },
79}
80
81type Listener = Arc<Subscriber>;
82struct Subscriber {
83    callback: Box<dyn Fn(Event) + Send + Sync>,
84    state: Mutex<DeliveryQueue>,
85}
86#[derive(Default)]
87struct DeliveryQueue {
88    pending: VecDeque<Event>,
89    running: bool,
90}
91impl Subscriber {
92    fn enqueue(&self, event: Event) {
93        self.state
94            .lock()
95            .unwrap_or_else(std::sync::PoisonError::into_inner)
96            .pending
97            .push_back(event);
98    }
99    fn drain(&self) {
100        {
101            let mut state = self
102                .state
103                .lock()
104                .unwrap_or_else(std::sync::PoisonError::into_inner);
105            if state.running {
106                return;
107            }
108            state.running = true;
109        }
110        loop {
111            let event = {
112                let mut state = self
113                    .state
114                    .lock()
115                    .unwrap_or_else(std::sync::PoisonError::into_inner);
116                let Some(event) = state.pending.pop_front() else {
117                    state.running = false;
118                    return;
119                };
120                event
121            };
122            // Callbacks can subscribe, unsubscribe, or trigger another event without holding a hub lock.
123            if let Err(panic) =
124                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.callback)(event)))
125            {
126                self.state
127                    .lock()
128                    .unwrap_or_else(std::sync::PoisonError::into_inner)
129                    .running = false;
130                std::panic::resume_unwind(panic);
131            }
132        }
133    }
134}
135#[derive(Default)]
136struct Hub {
137    next: u64,
138    listeners: BTreeMap<u64, Listener>,
139    token: Option<Token>,
140    recent: VecDeque<Event>,
141}
142static HUB: OnceLock<Mutex<Hub>> = OnceLock::new();
143fn hub() -> &'static Mutex<Hub> {
144    HUB.get_or_init(Mutex::default)
145}
146fn deliver(event: &Event) {
147    let listeners = {
148        let mut hub = hub()
149            .lock()
150            .unwrap_or_else(std::sync::PoisonError::into_inner);
151        if let Event::Token { token } = event {
152            hub.token = Some(token.clone());
153        } else {
154            if hub.recent.len() == 32 {
155                hub.recent.pop_front();
156            }
157            hub.recent.push_back(event.clone());
158        }
159        let listeners = hub.listeners.values().cloned().collect::<Vec<_>>();
160        for listener in &listeners {
161            listener.enqueue(event.clone());
162        }
163        listeners
164    };
165    for listener in listeners {
166        listener.drain();
167    }
168}
169
170pub struct Watch(u64);
171impl Drop for Watch {
172    fn drop(&mut self) {
173        hub()
174            .lock()
175            .unwrap_or_else(std::sync::PoisonError::into_inner)
176            .listeners
177            .remove(&self.0);
178    }
179}
180
181/// Subscribe to token changes and messages. Replays the last token and up to 32 recent events,
182/// including notification taps received before the UI mounted. Callbacks may run off the UI thread.
183///
184/// # Errors
185///
186/// Returns [`Error::Unsupported`] where no push transport is built in, and
187/// [`Error::Platform`] when the transport cannot start.
188pub fn watch(callback: impl Fn(Event) + Send + Sync + 'static) -> Result<Watch, Error> {
189    start()?;
190    let listener = Arc::new(Subscriber {
191        callback: Box::new(callback),
192        state: Mutex::default(),
193    });
194    let id = {
195        let mut hub = hub()
196            .lock()
197            .unwrap_or_else(std::sync::PoisonError::into_inner);
198        hub.next += 1;
199        let id = hub.next;
200        let mut replay = Vec::new();
201        if let Some(token) = &hub.token {
202            replay.push(Event::Token {
203                token: token.clone(),
204            });
205        }
206        replay.extend(hub.recent.iter().cloned());
207        for event in replay {
208            listener.enqueue(event);
209        }
210        hub.listeners.insert(id, listener.clone());
211        id
212    };
213    listener.drain();
214    Ok(Watch(id))
215}
216
217pub fn supported() -> bool {
218    cfg!(any(
219        all(target_os = "ios", feature = "ios-apns"),
220        all(target_os = "android", feature = "android-fcm")
221    ))
222}
223
224/// Ask for visible notification permission separately from transport registration.
225///
226/// # Errors
227///
228/// Returns [`Error::Unsupported`] where no push transport is built in or the platform has no
229/// notification permission, and [`Error::PermissionDenied`] when the person declines.
230pub async fn request_permission() -> Result<(), Error> {
231    use day_part_permissions::{Permission, Status};
232    if !supported() {
233        return Err(Error::Unsupported);
234    }
235    match day_part_permissions::request_future(Permission::Notifications).await {
236        Status::Granted => Ok(()),
237        Status::Unsupported => Err(Error::Unsupported),
238        _ => Err(Error::PermissionDenied),
239    }
240}
241
242/// Start native token registration. Completion means the request was accepted; `Event::Token`
243/// carries the token. Apple requires a push entitlement; Android requires Firebase app resources.
244///
245/// # Errors
246///
247/// Returns [`Error::Unsupported`] where no push transport is built in, and
248/// [`Error::Platform`] when the transport rejects the request.
249pub async fn register() -> Result<(), Error> {
250    start()?;
251    answer(backend::register().await.map_err(bridge_error)?)
252}
253/// Withdraw the native registration and forget the cached token.
254///
255/// # Errors
256///
257/// Returns [`Error::Unsupported`] where no push transport is built in, and
258/// [`Error::Platform`] when the transport rejects the request.
259pub async fn unregister() -> Result<(), Error> {
260    start()?;
261    answer(backend::unregister().await.map_err(bridge_error)?)?;
262    hub()
263        .lock()
264        .unwrap_or_else(std::sync::PoisonError::into_inner)
265        .token = None;
266    Ok(())
267}
268fn start() -> Result<(), Error> {
269    static STARTED: OnceLock<Result<(), Error>> = OnceLock::new();
270    if !supported() {
271        return Err(Error::Unsupported);
272    }
273    STARTED
274        .get_or_init(|| {
275            backend::start(|value| match serde_json::from_str(&value) {
276                Ok(event) => deliver(&event),
277                Err(error) => deliver(&Event::Error {
278                    message: error.to_string(),
279                }),
280            })
281            .map_err(bridge_error)
282        })
283        .clone()
284}
285fn answer(value: String) -> Result<(), Error> {
286    if value.is_empty() {
287        Ok(())
288    } else {
289        Err(Error::Platform(value))
290    }
291}
292#[expect(
293    clippy::needless_pass_by_value,
294    reason = "passed to `map_err`, which hands the error over by value"
295)]
296fn bridge_error(error: day_bridge::Error) -> Error {
297    if matches!(error, day_bridge::Error::Unsupported) {
298        Error::Unsupported
299    } else {
300        Error::Platform(error.to_string())
301    }
302}
303
304#[cfg(any(
305    all(target_os = "ios", feature = "ios-apns"),
306    all(target_os = "android", feature = "android-fcm")
307))]
308#[day_process::linkme::distributed_slice(day_process::services::SERVICES)]
309#[linkme(crate = day_process::linkme)]
310static SERVICE: day_process::services::Service = day_process::services::Service {
311    name: "push",
312    initialize: || {
313        if let Err(error) = start() {
314            deliver(&Event::Error {
315                message: error.to_string(),
316            });
317        }
318    },
319};
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324    #[test]
325    fn replay_precedes_concurrent_delivery_and_callbacks_are_serial() {
326        let (entered_tx, entered_rx) = std::sync::mpsc::channel();
327        let (release_tx, release_rx) = std::sync::mpsc::channel();
328        let release_rx = Mutex::new(release_rx);
329        let seen = Arc::new(Mutex::new(Vec::new()));
330        let observed = seen.clone();
331        let listener = Arc::new(Subscriber {
332            callback: Box::new(move |event| {
333                let Event::Error { message } = event else {
334                    unreachable!()
335                };
336                if message == "replay" {
337                    entered_tx.send(()).unwrap();
338                    release_rx.lock().unwrap().recv().unwrap();
339                }
340                observed.lock().unwrap().push(message);
341            }),
342            state: Mutex::default(),
343        });
344        listener.enqueue(Event::Error {
345            message: "replay".into(),
346        });
347        let first = listener.clone();
348        let thread = std::thread::spawn(move || first.drain());
349        entered_rx.recv().unwrap();
350        listener.enqueue(Event::Error {
351            message: "new".into(),
352        });
353        listener.drain();
354        assert!(seen.lock().unwrap().is_empty());
355        release_tx.send(()).unwrap();
356        thread.join().unwrap();
357        assert_eq!(*seen.lock().unwrap(), ["replay", "new"]);
358    }
359    #[test]
360    fn token_debug_does_not_disclose_device_identifier() {
361        let token = Token {
362            provider: Provider::Fcm,
363            value: "synthetic-sensitive-token".into(),
364        };
365        assert!(!format!("{token:?}").contains(&token.value));
366    }
367    #[test]
368    fn provider_and_opened_state_survive_native_delivery() {
369        let event: Event =
370            serde_json::from_str(r#"{"event":"message","opened":true,"payload":{"id":"fixture"}}"#)
371                .unwrap();
372        std::assert_matches!(event, Event::Message { opened: true, .. });
373        let event: Event = serde_json::from_str(
374            r#"{"event":"token","token":{"provider":"apns","value":"fixture"}}"#,
375        )
376        .unwrap();
377        std::assert_matches!(
378            event,
379            Event::Token {
380                token: Token {
381                    provider: Provider::Apns,
382                    ..
383                }
384            }
385        );
386    }
387}
388
389#[cfg(feature = "relay")]
390pub mod relay;