glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! One Postgres `NOTIFY` channel for everything Glacier tells other
//! processes, each message a small JSON envelope: `{"topic": "jobs",
//! "event": "queued", "id": 42}`. Job wake-ups use it now; PubSub (0.6)
//! will send its topics through it too.
//!
//! An envelope carries ids, never records: Postgres caps a payload at
//! 8,000 bytes, and a listener reads what changed from the database.

use serde::{Deserialize, Serialize};

/// The channel every envelope goes on.
pub const CHANNEL: &str = "glacier";

/// One message: what it's about (`jobs`), what happened (`queued`), and
/// the id of the row it's about.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Envelope {
    pub topic: String,
    pub event: String,
    #[serde(default)]
    pub id: serde_json::Value,
}

impl Envelope {
    /// The envelope a payload holds, if it's one.
    pub fn parse(payload: &str) -> Option<Envelope> {
        serde_json::from_str(payload).ok()
    }
}

/// SQL that sends an envelope from inside a statement, for the row it's
/// about: `pg_notify('glacier', json_build_object(…)::text)`, delivered
/// when the transaction commits. `topic` and `event` are trusted
/// identifiers from Glacier's own code; `id` is an SQL expression.
pub(crate) fn pg_notify_sql(topic: &str, event: &str, id: &str) -> String {
    format!(
        "pg_notify('{CHANNEL}', json_build_object('topic', '{topic}', 'event', '{event}', 'id', {id})::text)"
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn envelopes_round_trip() {
        let envelope = Envelope::parse(r#"{"topic":"jobs","event":"queued","id":42}"#).unwrap();
        assert_eq!(envelope.topic, "jobs");
        assert_eq!(envelope.event, "queued");
        assert_eq!(envelope.id, 42);
        assert!(
            Envelope::parse("default").is_none(),
            "an old job queue name"
        );
        assert_eq!(
            pg_notify_sql("jobs", "queued", "id"),
            "pg_notify('glacier', json_build_object('topic', 'jobs', 'event', 'queued', 'id', id)::text)"
        );
    }
}