1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//! 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)"
);
}
}