Skip to main content

sisa_caching_hybrid/backplane/
node_id.rs

1use std::{
2    collections::hash_map::RandomState,
3    fmt,
4    hash::{BuildHasher, Hasher},
5    sync::Arc,
6};
7
8use serde::{Deserialize, Serialize};
9
10/// Names one node, so a node can skip the invalidations that it sent itself.
11#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(from = "String", into = "String")]
13pub struct NodeId(Arc<str>);
14
15impl NodeId {
16    /// An id from any string. It must be unique to the process: a node skips every message that
17    /// carries its own id.
18    pub(crate) fn new(id: impl Into<Arc<str>>) -> Self {
19        Self(id.into())
20    }
21
22    /// A fresh id from the process id and a per-call random number.
23    pub(crate) fn generate() -> Self {
24        let random = RandomState::new().build_hasher().finish();
25
26        Self::new(format!("{}-{random:016x}", std::process::id()))
27    }
28}
29
30// Writes the id as given, as messages and logs carry it.
31impl fmt::Display for NodeId {
32    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33        formatter.write_str(&self.0)
34    }
35}
36
37// Lets serde read an id from a message.
38impl From<String> for NodeId {
39    fn from(id: String) -> Self {
40        Self::new(id)
41    }
42}
43
44// Lets serde write the id as a plain string.
45impl From<NodeId> for String {
46    fn from(id: NodeId) -> Self {
47        id.to_string()
48    }
49}