taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

worker.rs (8018B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use std::time::Duration;
     18 
     19 use jiff::Timestamp;
     20 use sqlx::PgPool;
     21 use taler_common::{ExpoBackoffDecorr, config::Config};
     22 use tracing::{error, info, trace, warn};
     23 
     24 use crate::{
     25     apns::{ApnsError, Client, Reason},
     26     config::WorkerCfg,
     27     constants::DEVICE_PAGE_SIZE,
     28     db,
     29 };
     30 
     31 #[derive(Debug, thiserror::Error)]
     32 pub enum WorkerError {
     33     #[error(transparent)]
     34     Db(#[from] sqlx::Error),
     35     #[error(transparent)]
     36     Apns(#[from] ApnsError),
     37 }
     38 
     39 const NB_RETRY: usize = 5;
     40 
     41 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
     42 enum FailureAction {
     43     Fatal,
     44     Config,
     45     ExpiredProviderToken,
     46     Unregister,
     47     Defer,
     48     Retry,
     49 }
     50 
     51 fn classify_reason(reason: Reason) -> FailureAction {
     52     match reason {
     53         // Request construction bugs independent of the client-supplied token.
     54         Reason::BadCollapseId
     55         | Reason::BadExpirationDate
     56         | Reason::BadMessageId
     57         | Reason::BadPriority
     58         | Reason::BadTopic
     59         | Reason::DuplicateHeaders
     60         | Reason::InvalidPushType
     61         | Reason::MissingTopic
     62         | Reason::PayloadEmpty
     63         | Reason::MethodNotAllowed => FailureAction::Fatal,
     64         // Provider credentials / topic configuration errors.
     65         Reason::TopicDisallowed
     66         | Reason::BadCertificate
     67         | Reason::BadCertificateEnvironment
     68         | Reason::Forbidden
     69         | Reason::InvalidProviderToken
     70         | Reason::MissingProviderToken
     71         | Reason::UnrelatedKeyIdInToken
     72         | Reason::BadEnvironmentKeyIdInToken
     73         | Reason::PayloadTooLarge => FailureAction::Config,
     74         // The client already retried once with a fresh provider token.
     75         Reason::ExpiredProviderToken => FailureAction::ExpiredProviderToken,
     76         // Invalid, inactive, or path-rejected client token: unregister
     77         Reason::BadPath
     78         | Reason::MissingDeviceToken
     79         | Reason::BadDeviceToken
     80         | Reason::DeviceTokenNotForTopic
     81         | Reason::ExpiredToken
     82         | Reason::Unregistered => FailureAction::Unregister,
     83         // Retry this device on the next scheduled pass.
     84         Reason::TooManyRequests => FailureAction::Defer,
     85         // Wait before retry.
     86         Reason::IdleTimeout
     87         | Reason::TooManyProviderTokenUpdates
     88         | Reason::InternalServerError
     89         | Reason::ServiceUnavailable
     90         | Reason::Shutdown => FailureAction::Retry,
     91     }
     92 }
     93 
     94 async fn wakeup(pool: &PgPool, client: &mut Client) -> Result<(), WorkerError> {
     95     // Wait at least 15 minutes before retrying API calls as per: https://developer.apple.com/documentation/usernotifications/sending-notification-requests-to-apns#Follow-best-practices-while-sending-push-notifications-with-APNs
     96     // After 15 minutes, you can retry JSON payloads that receive response status codes that begin with 5XX.
     97     // While retrying, you may employ a back-off technique. Most notifications with the status code 4XX can
     98     // be retried after you fix the error noted in the reason field. Don’t retry notification responses with
     99     // the error code BadDeviceToken, DeviceTokenNotForTopic, Forbidden, ExpiredToken, Unregistered, or PayloadTooLarge.
    100     // You can retry with a delay, if you get the error code TooManyRequests.
    101     let mut jitter = ExpoBackoffDecorr::new(Duration::from_mins(15), Duration::from_hours(1), 2.5);
    102 
    103     // TODO send in batches
    104     let mut after_id = 0i64;
    105     let mut processed = 0usize;
    106 
    107     loop {
    108         let page = db::registration_page(pool, after_id, DEVICE_PAGE_SIZE).await?;
    109         if page.is_empty() {
    110             break;
    111         }
    112         processed += page.len();
    113 
    114         'devices: for (device_id, token) in page {
    115             after_id = device_id;
    116             trace!(target: "worker", "send background notification to {token}");
    117             let mut attempt = 0;
    118             while let Err(e) = client.send(&token).await {
    119                 trace!(target: "worker", "notification to {token} failed {e}");
    120                 if let ApnsError::Err { reason, timestamp } = e {
    121                     match classify_reason(reason) {
    122                         FailureAction::Fatal => {
    123                             error!(target: "worker", "fatal error the service is broken: {e}");
    124                             std::process::exit(9);
    125                         }
    126                         FailureAction::Config => {
    127                             error!(target: "worker", "config error, check the configuration: {e}");
    128                             std::process::exit(6);
    129                         }
    130                         FailureAction::ExpiredProviderToken => return Err(e.into()),
    131                         FailureAction::Unregister => {
    132                             db::unregister(
    133                                 pool,
    134                                 &token,
    135                                 &timestamp
    136                                     .and_then(|s| i64::try_from(s).ok())
    137                                     .and_then(|s| Timestamp::from_millisecond(s).ok())
    138                                     .unwrap_or_else(Timestamp::now),
    139                             )
    140                             .await?;
    141                             continue 'devices;
    142                         }
    143                         FailureAction::Defer => {
    144                             warn!(target: "worker", "notification to {token} rate-limited, deferring to the next pass");
    145                             continue 'devices;
    146                         }
    147                         FailureAction::Retry => {}
    148                     }
    149                 }
    150 
    151                 attempt += 1;
    152 
    153                 if attempt >= NB_RETRY {
    154                     error!(target: "worker", "notification to {token} failed more than {NB_RETRY} times, stopping worker after back-off");
    155                     tokio::time::sleep(jitter.backoff()).await;
    156                     return Err(WorkerError::Apns(e));
    157                 } else {
    158                     warn!(target: "worker", "notification to {token} failed {e}, retrying after back-off");
    159                     tokio::time::sleep(jitter.backoff()).await;
    160                 }
    161             }
    162             info!(target: "trace", "notification to {token} succeeded");
    163         }
    164     }
    165 
    166     info!(target: "worker", "processed notifications for {processed} devices");
    167     Ok(())
    168 }
    169 
    170 pub async fn run(cfg: &Config, pool: &PgPool, transient: bool) -> anyhow::Result<()> {
    171     let cfg = WorkerCfg::parse(cfg)?;
    172     let mut client = Client::new(&cfg.apns)?;
    173 
    174     if transient {
    175         wakeup(pool, &mut client).await?;
    176         return Ok(());
    177     }
    178 
    179     info!(target: "worker", "running at initialisation");
    180     let mut jitter = ExpoBackoffDecorr::default();
    181     loop {
    182         match wakeup(pool, &mut client).await {
    183             Ok(()) => jitter.reset(),
    184             Err(WorkerError::Db(err)) if !matches!(err, sqlx::Error::PoolClosed) => {
    185                 let delay = jitter.backoff();
    186                 error!(target: "worker", ?delay, "database operation failed: {err}");
    187                 tokio::time::sleep(delay).await;
    188                 continue;
    189             }
    190             // APNs errors reach here only after their bounded operation retries.
    191             Err(err) => return Err(err.into()),
    192         }
    193 
    194         // TODO take sending time into account
    195         tokio::time::sleep(cfg.frequency).await;
    196         info!(target: "worker", "running at frequency");
    197     }
    198 }