notification.rs

  1use crate::proto;
  2use serde::{Deserialize, Serialize};
  3use serde_json::{map, Value};
  4use strum::{EnumVariantNames, VariantNames as _};
  5
  6const KIND: &'static str = "kind";
  7const ENTITY_ID: &'static str = "entity_id";
  8
  9/// A notification that can be stored, associated with a given recipient.
 10///
 11/// This struct is stored in the collab database as JSON, so it shouldn't be
 12/// changed in a backward-incompatible way. For example, when renaming a
 13/// variant, add a serde alias for the old name.
 14///
 15/// Most notification types have a special field which is aliased to
 16/// `entity_id`. This field is stored in its own database column, and can
 17/// be used to query the notification.
 18#[derive(Debug, Clone, PartialEq, Eq, EnumVariantNames, Serialize, Deserialize)]
 19#[serde(tag = "kind")]
 20pub enum Notification {
 21    ContactRequest {
 22        #[serde(rename = "entity_id")]
 23        sender_id: u64,
 24    },
 25    ContactRequestAccepted {
 26        #[serde(rename = "entity_id")]
 27        responder_id: u64,
 28    },
 29    ChannelInvitation {
 30        #[serde(rename = "entity_id")]
 31        channel_id: u64,
 32        channel_name: String,
 33    },
 34    ChannelMessageMention {
 35        sender_id: u64,
 36        channel_id: u64,
 37        #[serde(rename = "entity_id")]
 38        message_id: u64,
 39    },
 40}
 41
 42impl Notification {
 43    pub fn to_proto(&self) -> proto::Notification {
 44        let mut value = serde_json::to_value(self).unwrap();
 45        let mut entity_id = None;
 46        let value = value.as_object_mut().unwrap();
 47        let Some(Value::String(kind)) = value.remove(KIND) else {
 48            unreachable!("kind is the enum tag")
 49        };
 50        if let map::Entry::Occupied(e) = value.entry(ENTITY_ID) {
 51            if e.get().is_u64() {
 52                entity_id = e.remove().as_u64();
 53            }
 54        }
 55        proto::Notification {
 56            kind,
 57            entity_id,
 58            content: serde_json::to_string(&value).unwrap(),
 59            ..Default::default()
 60        }
 61    }
 62
 63    pub fn from_proto(notification: &proto::Notification) -> Option<Self> {
 64        let mut value = serde_json::from_str::<Value>(&notification.content).ok()?;
 65        let object = value.as_object_mut()?;
 66        object.insert(KIND.into(), notification.kind.to_string().into());
 67        if let Some(entity_id) = notification.entity_id {
 68            object.insert(ENTITY_ID.into(), entity_id.into());
 69        }
 70        serde_json::from_value(value).ok()
 71    }
 72
 73    pub fn all_variant_names() -> &'static [&'static str] {
 74        Self::VARIANTS
 75    }
 76}
 77
 78#[test]
 79fn test_notification() {
 80    // Notifications can be serialized and deserialized.
 81    for notification in [
 82        Notification::ContactRequest { sender_id: 1 },
 83        Notification::ContactRequestAccepted { responder_id: 2 },
 84        Notification::ChannelInvitation {
 85            channel_id: 100,
 86            channel_name: "the-channel".into(),
 87        },
 88        Notification::ChannelMessageMention {
 89            sender_id: 200,
 90            channel_id: 30,
 91            message_id: 1,
 92        },
 93    ] {
 94        let message = notification.to_proto();
 95        let deserialized = Notification::from_proto(&message).unwrap();
 96        assert_eq!(deserialized, notification);
 97    }
 98
 99    // When notifications are serialized, the `kind` and `actor_id` fields are
100    // stored separately, and do not appear redundantly in the JSON.
101    let notification = Notification::ContactRequest { sender_id: 1 };
102    assert_eq!(notification.to_proto().content, "{}");
103}