Skip to main content

nexus_common/models/
homeserver.rs

1use crate::db::RedisOps;
2use crate::types::DynError;
3use pubky_app_specs::PubkyId;
4use serde::{Deserialize, Serialize};
5
6/// Represents a homeserver with its public key, URL, and cursor.
7#[derive(Serialize, Deserialize, Debug)]
8pub struct Homeserver {
9    pub id: PubkyId,
10    pub cursor: String,
11}
12
13impl RedisOps for Homeserver {}
14
15impl Homeserver {
16    pub async fn new(id: PubkyId) -> Result<Self, Box<dyn std::error::Error + Sync + Send>> {
17        let hs = Homeserver {
18            id,
19            cursor: "0000000000000".to_string(),
20        };
21        // Store homeserver with initial cursor in Index
22        hs.put_to_index().await?;
23        Ok(hs)
24    }
25
26    /// Retrieves the homeserver from Redis.
27    pub async fn get_from_index(id: &str) -> Result<Option<Self>, DynError> {
28        if let Some(homeserver) = Self::try_from_index_json(&[id], None).await? {
29            return Ok(Some(homeserver));
30        }
31        Ok(None)
32    }
33
34    /// Stores the homeserver in Redis.
35    pub async fn put_to_index(&self) -> Result<(), DynError> {
36        self.put_index_json(&[&self.id], None, None).await?;
37        Ok(())
38    }
39
40    pub async fn from_config(homeserver: PubkyId) -> Result<Homeserver, DynError> {
41        // Attempt to load the homeserver cursor from Redis
42        match Homeserver::get_from_index(&homeserver).await? {
43            Some(hs) => Ok(hs),
44            None => {
45                // Create a new Homeserver instance with default cursor
46                Homeserver::new(homeserver).await
47            }
48        }
49    }
50}