openzeppelin_relayer/repositories/
notification.rs

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
//! This module defines an in-memory notification repository for managing
//! notifications. It provides functionality to create, retrieve, and list
//! notifications, while update and delete operations are not supported.
//! The repository is implemented using a `Mutex`-protected `HashMap` to
//! ensure thread safety in asynchronous contexts. Additionally, it includes
//! conversion implementations for `NotificationFileConfig` to `NotificationRepoModel`.
use crate::{
    config::{NotificationFileConfig, NotificationFileConfigType},
    models::{NotificationRepoModel, NotificationType as ModelNotificationType, RepositoryError},
    repositories::*,
};
use async_trait::async_trait;
use std::collections::HashMap;
use tokio::sync::{Mutex, MutexGuard};

#[derive(Debug)]
pub struct InMemoryNotificationRepository {
    store: Mutex<HashMap<String, NotificationRepoModel>>,
}

#[allow(dead_code)]
impl InMemoryNotificationRepository {
    pub fn new() -> Self {
        Self {
            store: Mutex::new(HashMap::new()),
        }
    }

    async fn acquire_lock<T>(lock: &Mutex<T>) -> Result<MutexGuard<T>, RepositoryError> {
        Ok(lock.lock().await)
    }
}

impl Default for InMemoryNotificationRepository {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Repository<NotificationRepoModel, String> for InMemoryNotificationRepository {
    async fn create(
        &self,
        notification: NotificationRepoModel,
    ) -> Result<NotificationRepoModel, RepositoryError> {
        let mut store = Self::acquire_lock(&self.store).await?;
        if store.contains_key(&notification.id) {
            return Err(RepositoryError::ConstraintViolation(format!(
                "Notification with ID {} already exists",
                notification.id
            )));
        }
        store.insert(notification.id.clone(), notification.clone());
        Ok(notification)
    }

    async fn get_by_id(&self, id: String) -> Result<NotificationRepoModel, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        match store.get(&id) {
            Some(entity) => Ok(entity.clone()),
            None => Err(RepositoryError::NotFound(format!(
                "Notification with ID {} not found",
                id
            ))),
        }
    }

    #[allow(clippy::map_entry)]
    async fn update(
        &self,
        _id: String,
        _relayer: NotificationRepoModel,
    ) -> Result<NotificationRepoModel, RepositoryError> {
        Err(RepositoryError::NotSupported("Not supported".to_string()))
    }

    async fn delete_by_id(&self, _id: String) -> Result<(), RepositoryError> {
        Err(RepositoryError::NotSupported("Not supported".to_string()))
    }

    async fn list_all(&self) -> Result<Vec<NotificationRepoModel>, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        let notifications: Vec<NotificationRepoModel> = store.values().cloned().collect();
        Ok(notifications)
    }

    async fn list_paginated(
        &self,
        query: PaginationQuery,
    ) -> Result<PaginatedResult<NotificationRepoModel>, RepositoryError> {
        let total = self.count().await?;
        let start = ((query.page - 1) * query.per_page) as usize;
        let items: Vec<NotificationRepoModel> = self
            .store
            .lock()
            .await
            .values()
            .skip(start)
            .take(query.per_page as usize)
            .cloned()
            .collect();

        Ok(PaginatedResult {
            items,
            total: total as u64,
            page: query.page,
            per_page: query.per_page,
        })
    }

    async fn count(&self) -> Result<usize, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        let length = store.len();
        Ok(length)
    }
}

impl TryFrom<NotificationFileConfig> for NotificationRepoModel {
    type Error = ConversionError;

    fn try_from(config: NotificationFileConfig) -> Result<Self, Self::Error> {
        Ok(NotificationRepoModel {
            id: config.id.clone(),
            url: config.url.clone(),
            notification_type: ModelNotificationType::try_from(&config.r#type)?,
            signing_key: config.get_signing_key(),
        })
    }
}

impl TryFrom<&NotificationFileConfigType> for ModelNotificationType {
    type Error = ConversionError;

    fn try_from(config: &NotificationFileConfigType) -> Result<Self, Self::Error> {
        match config {
            NotificationFileConfigType::Webhook => Ok(ModelNotificationType::Webhook),
        }
    }
}

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

    fn create_test_notification(id: String) -> NotificationRepoModel {
        NotificationRepoModel {
            id: id.clone(),
            url: "http://localhost".to_string(),
            notification_type: ModelNotificationType::Webhook,
            signing_key: None,
        }
    }

    #[actix_web::test]
    async fn test_new_repository_is_empty() {
        let repo = InMemoryNotificationRepository::new();
        assert_eq!(repo.count().await.unwrap(), 0);
    }

    #[actix_web::test]
    async fn test_add_notification() {
        let repo = InMemoryNotificationRepository::new();
        let notification = create_test_notification("test".to_string());

        repo.create(notification.clone()).await.unwrap();
        assert_eq!(repo.count().await.unwrap(), 1);

        let stored = repo.get_by_id("test".to_string()).await.unwrap();
        assert_eq!(stored.id, notification.id);
    }

    #[actix_web::test]
    async fn test_update_notification() {
        let repo = InMemoryNotificationRepository::new();
        let notification = create_test_notification("test".to_string());

        let result = repo.update("test".to_string(), notification).await;
        assert!(matches!(result, Err(RepositoryError::NotSupported(_))));
    }

    #[actix_web::test]
    async fn test_list_notifications() {
        let repo = InMemoryNotificationRepository::new();
        let notification1 = create_test_notification("test".to_string());
        let notification2 = create_test_notification("test2".to_string());

        repo.create(notification1.clone()).await.unwrap();
        repo.create(notification2).await.unwrap();

        let notifications = repo.list_all().await.unwrap();
        assert_eq!(notifications.len(), 2);
    }

    #[actix_web::test]
    async fn test_update_nonexistent_notification() {
        let repo = InMemoryNotificationRepository::new();
        let notification = create_test_notification("test".to_string());

        let result = repo.update("test2".to_string(), notification).await;
        assert!(matches!(result, Err(RepositoryError::NotSupported(_))));
    }

    #[actix_web::test]
    async fn test_get_nonexistent_notification() {
        let repo = InMemoryNotificationRepository::new();

        let result = repo.get_by_id("test".to_string()).await;
        assert!(matches!(result, Err(RepositoryError::NotFound(_))));
    }
}