ryuk-cli 0.1.0

The `ryuk` command: scaffold a Ryuk app (axum, SeaORM, Inertia/Svelte), generate controllers, models, jobs and mails, run migrations and the dev server.
use ryuk::{
    push::{Notification, Push},
    queue::{Job, JobContext, JobError, Queue},
};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use tokio::sync::OnceCell;

/// Push a notification to every device of a user. Enqueue it with [`notify`].
/// The provider keys are read once per worker process (`Push::from_env`).
#[derive(Serialize, Deserialize)]
pub struct SendPush {
    pub user_id: i64,
    pub title: Option<String>,
    pub body: Option<String>,
    #[serde(default)]
    pub data: BTreeMap<String, String>,
    pub badge: Option<u32>,
    pub collapse_key: Option<String>,
}

static PUSH: OnceCell<Push> = OnceCell::const_new();

impl Job for SendPush {
    const NAME: &'static str = "send_push";

    async fn handle(self, ctx: &JobContext) -> Result<(), JobError> {
        let push = PUSH.get_or_try_init(|| Push::from_env(ctx.db.clone())).await.map_err(|e| JobError(e.to_string()))?;
        let mut n = Notification::new();
        if let Some(t) = self.title {
            n = n.title(t);
        }
        if let Some(b) = self.body {
            n = n.body(b);
        }
        for (k, v) in self.data {
            n = n.data(k, v);
        }
        if let Some(b) = self.badge {
            n = n.badge(b);
        }
        if let Some(c) = self.collapse_key {
            n = n.collapse_key(c);
        }
        // Per-device failures are retried inside the library and reported, never fatal; a registry error retries the job.
        let r = push.send_to_user(self.user_id, &n).await.map_err(|e| JobError(e.to_string()))?;
        tracing::info!(user_id = self.user_id, sent = r.sent, failed = r.failed, invalidated = r.invalidated, "push job");
        Ok(())
    }
}

/// Queue a push for `user_id` (sent by `ryuk queue:work`). `data` values must be strings.
///
/// ```ignore
/// notify(&queue, user.id, "New comment", "Ann replied to your post", [("post", "42")]).await?;
/// ```
pub async fn notify<'a>(
    queue: &Queue,
    user_id: i64,
    title: &str,
    body: &str,
    data: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Result<(), sea_orm::DbErr> {
    queue
        .dispatch(SendPush {
            user_id,
            title: Some(title.into()),
            body: Some(body.into()),
            data: data.into_iter().map(|(k, v)| (k.into(), v.into())).collect(),
            badge: None,
            collapse_key: None,
        })
        .await
}