Refactor handlers and OpenAPI documentation for improved readability and consistency
Some checks failed
lint / lint (push) Has been cancelled
test / unit (push) Has been cancelled
test / integration (push) Has been cancelled
lint / lint (pull_request) Failing after 6m49s
test / unit (pull_request) Successful in 16m24s
test / integration (pull_request) Failing after 17m7s

- Reorganized imports in health, notifications, social, thoughts, and users handlers for clarity.
- Updated function signatures in handlers to improve readability by aligning parameters.
- Enhanced JSON response formatting in notifications and thoughts handlers.
- Improved error handling in user-related functions.
- Refactored OpenAPI documentation to maintain consistent formatting and structure.
- Cleaned up unnecessary code and comments across various files.
- Ensured consistent use of `Arc` for shared state in AppState and WorkerHandlers.
This commit is contained in:
2026-05-14 16:28:57 +02:00
parent 004bfb427b
commit 10c4a66de5
47 changed files with 2406 additions and 723 deletions

View File

@@ -1,30 +1,76 @@
use crate::value_objects::{UserId, ThoughtId, LikeId, BoostId};
use crate::value_objects::{BoostId, LikeId, ThoughtId, UserId};
#[derive(Debug, Clone)]
pub enum DomainEvent {
ThoughtCreated { thought_id: ThoughtId, user_id: UserId, in_reply_to_id: Option<ThoughtId> },
ThoughtDeleted { thought_id: ThoughtId, user_id: UserId },
ThoughtUpdated { thought_id: ThoughtId, user_id: UserId },
LikeAdded { like_id: LikeId, user_id: UserId, thought_id: ThoughtId },
LikeRemoved { user_id: UserId, thought_id: ThoughtId },
BoostAdded { boost_id: BoostId, user_id: UserId, thought_id: ThoughtId },
BoostRemoved { user_id: UserId, thought_id: ThoughtId },
FollowRequested { follower_id: UserId, following_id: UserId },
FollowAccepted { follower_id: UserId, following_id: UserId },
FollowRejected { follower_id: UserId, following_id: UserId },
Unfollowed { follower_id: UserId, following_id: UserId },
UserBlocked { blocker_id: UserId, blocked_id: UserId },
UserUnblocked { blocker_id: UserId, blocked_id: UserId },
UserRegistered { user_id: UserId },
ThoughtCreated {
thought_id: ThoughtId,
user_id: UserId,
in_reply_to_id: Option<ThoughtId>,
},
ThoughtDeleted {
thought_id: ThoughtId,
user_id: UserId,
},
ThoughtUpdated {
thought_id: ThoughtId,
user_id: UserId,
},
LikeAdded {
like_id: LikeId,
user_id: UserId,
thought_id: ThoughtId,
},
LikeRemoved {
user_id: UserId,
thought_id: ThoughtId,
},
BoostAdded {
boost_id: BoostId,
user_id: UserId,
thought_id: ThoughtId,
},
BoostRemoved {
user_id: UserId,
thought_id: ThoughtId,
},
FollowRequested {
follower_id: UserId,
following_id: UserId,
},
FollowAccepted {
follower_id: UserId,
following_id: UserId,
},
FollowRejected {
follower_id: UserId,
following_id: UserId,
},
Unfollowed {
follower_id: UserId,
following_id: UserId,
},
UserBlocked {
blocker_id: UserId,
blocked_id: UserId,
},
UserUnblocked {
blocker_id: UserId,
blocked_id: UserId,
},
UserRegistered {
user_id: UserId,
},
}
pub struct EventEnvelope {
pub event: DomainEvent,
pub ack: Box<dyn Fn() + Send + Sync>,
pub ack: Box<dyn Fn() + Send + Sync>,
pub nack: Box<dyn Fn() + Send + Sync>,
}
impl std::fmt::Debug for EventEnvelope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EventEnvelope").field("event", &self.event).finish()
f.debug_struct("EventEnvelope")
.field("event", &self.event)
.finish()
}
}

View File

@@ -1,5 +1,5 @@
use chrono::{DateTime, Utc};
use crate::value_objects::{ApiKeyId, UserId};
use chrono::{DateTime, Utc};
#[derive(Debug, Clone)]
pub struct ApiKey {

View File

@@ -1,4 +1,4 @@
use crate::models::{user::User, thought::Thought};
use crate::models::{thought::Thought, user::User};
use crate::value_objects::UserId;
#[derive(Debug, Clone)]
@@ -25,10 +25,17 @@ pub struct FeedEntry {
}
#[derive(Debug, Clone)]
pub struct PageParams { pub page: u64, pub per_page: u64 }
pub struct PageParams {
pub page: u64,
pub per_page: u64,
}
impl PageParams {
pub fn offset(&self) -> i64 { ((self.page.saturating_sub(1)) * self.per_page) as i64 }
pub fn limit(&self) -> i64 { self.per_page as i64 }
pub fn offset(&self) -> i64 {
((self.page.saturating_sub(1)) * self.per_page) as i64
}
pub fn limit(&self) -> i64 {
self.per_page as i64
}
}
#[derive(Debug, Clone)]

View File

@@ -1,14 +1,32 @@
use crate::value_objects::{NotificationId, ThoughtId, UserId};
use chrono::{DateTime, Utc};
use crate::value_objects::{NotificationId, UserId, ThoughtId};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NotificationType { Like, Boost, Follow, Mention, Reply }
pub enum NotificationType {
Like,
Boost,
Follow,
Mention,
Reply,
}
impl NotificationType {
pub fn from_str(s: &str) -> Self {
match s { "like" => Self::Like, "boost" => Self::Boost, "follow" => Self::Follow, "mention" => Self::Mention, _ => Self::Reply }
match s {
"like" => Self::Like,
"boost" => Self::Boost,
"follow" => Self::Follow,
"mention" => Self::Mention,
_ => Self::Reply,
}
}
pub fn as_str(&self) -> &str {
match self { Self::Like => "like", Self::Boost => "boost", Self::Follow => "follow", Self::Mention => "mention", Self::Reply => "reply" }
match self {
Self::Like => "like",
Self::Boost => "boost",
Self::Follow => "follow",
Self::Mention => "mention",
Self::Reply => "reply",
}
}
}

View File

@@ -1,5 +1,5 @@
use crate::value_objects::{BoostId, LikeId, ThoughtId, UserId};
use chrono::{DateTime, Utc};
use crate::value_objects::{UserId, ThoughtId, LikeId, BoostId};
#[derive(Debug, Clone)]
pub struct Like {
@@ -20,13 +20,25 @@ pub struct Boost {
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FollowState { Pending, Accepted, Rejected }
pub enum FollowState {
Pending,
Accepted,
Rejected,
}
impl FollowState {
pub fn from_str(s: &str) -> Self {
match s { "pending" => Self::Pending, "rejected" => Self::Rejected, _ => Self::Accepted }
match s {
"pending" => Self::Pending,
"rejected" => Self::Rejected,
_ => Self::Accepted,
}
}
pub fn as_str(&self) -> &str {
match self { Self::Pending => "pending", Self::Accepted => "accepted", Self::Rejected => "rejected" }
match self {
Self::Pending => "pending",
Self::Accepted => "accepted",
Self::Rejected => "rejected",
}
}
}

View File

@@ -1,2 +1,5 @@
#[derive(Debug, Clone)]
pub struct Tag { pub id: i32, pub name: String }
pub struct Tag {
pub id: i32,
pub name: String,
}

View File

@@ -1,16 +1,29 @@
use crate::value_objects::{Content, ThoughtId, UserId};
use chrono::{DateTime, Utc};
use crate::value_objects::{ThoughtId, UserId, Content};
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Visibility {
Public, Followers, Unlisted, Direct,
Public,
Followers,
Unlisted,
Direct,
}
impl Visibility {
pub fn from_str(s: &str) -> Self {
match s { "followers" => Self::Followers, "unlisted" => Self::Unlisted, "direct" => Self::Direct, _ => Self::Public }
match s {
"followers" => Self::Followers,
"unlisted" => Self::Unlisted,
"direct" => Self::Direct,
_ => Self::Public,
}
}
pub fn as_str(&self) -> &str {
match self { Self::Public => "public", Self::Followers => "followers", Self::Unlisted => "unlisted", Self::Direct => "direct" }
match self {
Self::Public => "public",
Self::Followers => "followers",
Self::Unlisted => "unlisted",
Self::Direct => "direct",
}
}
}
@@ -32,14 +45,27 @@ pub struct Thought {
impl Thought {
pub fn new_local(
id: ThoughtId, user_id: UserId, content: Content,
in_reply_to_id: Option<ThoughtId>, visibility: Visibility,
content_warning: Option<String>, sensitive: bool,
id: ThoughtId,
user_id: UserId,
content: Content,
in_reply_to_id: Option<ThoughtId>,
visibility: Visibility,
content_warning: Option<String>,
sensitive: bool,
) -> Self {
Self {
id, user_id, content, in_reply_to_id, in_reply_to_url: None, ap_id: None,
visibility, content_warning, sensitive, local: true,
created_at: Utc::now(), updated_at: None,
id,
user_id,
content,
in_reply_to_id,
in_reply_to_url: None,
ap_id: None,
visibility,
content_warning,
sensitive,
local: true,
created_at: Utc::now(),
updated_at: None,
}
}
}

View File

@@ -1,4 +1,8 @@
use crate::value_objects::UserId;
#[derive(Debug, Clone)]
pub struct TopFriend { pub user_id: UserId, pub friend_id: UserId, pub position: i16 }
pub struct TopFriend {
pub user_id: UserId,
pub friend_id: UserId,
pub position: i16,
}

View File

@@ -1,5 +1,5 @@
use crate::value_objects::{Email, PasswordHash, UserId, Username};
use chrono::{DateTime, Utc};
use crate::value_objects::{UserId, Username, Email, PasswordHash};
#[derive(Debug, Clone)]
pub struct User {
@@ -22,14 +22,30 @@ pub struct User {
}
impl User {
pub fn new_local(id: UserId, username: Username, email: Email, password_hash: PasswordHash) -> Self {
pub fn new_local(
id: UserId,
username: Username,
email: Email,
password_hash: PasswordHash,
) -> Self {
let now = Utc::now();
Self {
id, username, email, password_hash,
display_name: None, bio: None, avatar_url: None, header_url: None,
custom_css: None, local: true, ap_id: None, inbox_url: None,
public_key: None, private_key: None,
created_at: now, updated_at: now,
id,
username,
email,
password_hash,
display_name: None,
bio: None,
avatar_url: None,
header_url: None,
custom_css: None,
local: true,
ap_id: None,
inbox_url: None,
public_key: None,
private_key: None,
created_at: now,
updated_at: now,
}
}
}

View File

@@ -1,4 +1,3 @@
use async_trait::async_trait;
use crate::{
errors::DomainError,
events::{DomainEvent, EventEnvelope},
@@ -13,10 +12,16 @@ use crate::{
top_friend::TopFriend,
user::User,
},
value_objects::{ApiKeyId, Content, Email, NotificationId, PasswordHash, ThoughtId, UserId, Username},
value_objects::{
ApiKeyId, Content, Email, NotificationId, PasswordHash, ThoughtId, UserId, Username,
},
};
use async_trait::async_trait;
pub struct GeneratedToken { pub token: String, pub user_id: UserId }
pub struct GeneratedToken {
pub token: String,
pub user_id: UserId,
}
#[async_trait]
pub trait AuthService: Send + Sync {
@@ -45,7 +50,15 @@ pub trait UserRepository: Send + Sync {
async fn find_by_username(&self, username: &Username) -> Result<Option<User>, DomainError>;
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError>;
async fn save(&self, user: &User) -> Result<(), DomainError>;
async fn update_profile(&self, user_id: &UserId, display_name: Option<String>, bio: Option<String>, avatar_url: Option<String>, header_url: Option<String>, custom_css: Option<String>) -> Result<(), DomainError>;
async fn update_profile(
&self,
user_id: &UserId,
display_name: Option<String>,
bio: Option<String>,
avatar_url: Option<String>,
header_url: Option<String>,
custom_css: Option<String>,
) -> Result<(), DomainError>;
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError>;
async fn count(&self) -> Result<i64, DomainError>;
}
@@ -57,14 +70,22 @@ pub trait ThoughtRepository: Send + Sync {
async fn delete(&self, id: &ThoughtId, user_id: &UserId) -> Result<(), DomainError>;
async fn update_content(&self, id: &ThoughtId, content: &Content) -> Result<(), DomainError>;
async fn get_thread(&self, id: &ThoughtId) -> Result<Vec<Thought>, DomainError>;
async fn list_by_user(&self, user_id: &UserId, page: &PageParams) -> Result<Paginated<Thought>, DomainError>;
async fn list_by_user(
&self,
user_id: &UserId,
page: &PageParams,
) -> Result<Paginated<Thought>, DomainError>;
}
#[async_trait]
pub trait LikeRepository: Send + Sync {
async fn save(&self, like: &Like) -> Result<(), DomainError>;
async fn delete(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<(), DomainError>;
async fn find(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<Option<Like>, DomainError>;
async fn find(
&self,
user_id: &UserId,
thought_id: &ThoughtId,
) -> Result<Option<Like>, DomainError>;
async fn count_for_thought(&self, thought_id: &ThoughtId) -> Result<i64, DomainError>;
}
@@ -72,7 +93,11 @@ pub trait LikeRepository: Send + Sync {
pub trait BoostRepository: Send + Sync {
async fn save(&self, boost: &Boost) -> Result<(), DomainError>;
async fn delete(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<(), DomainError>;
async fn find(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<Option<Boost>, DomainError>;
async fn find(
&self,
user_id: &UserId,
thought_id: &ThoughtId,
) -> Result<Option<Boost>, DomainError>;
async fn count_for_thought(&self, thought_id: &ThoughtId) -> Result<i64, DomainError>;
}
@@ -80,11 +105,31 @@ pub trait BoostRepository: Send + Sync {
pub trait FollowRepository: Send + Sync {
async fn save(&self, follow: &Follow) -> Result<(), DomainError>;
async fn delete(&self, follower_id: &UserId, following_id: &UserId) -> Result<(), DomainError>;
async fn find(&self, follower_id: &UserId, following_id: &UserId) -> Result<Option<Follow>, DomainError>;
async fn update_state(&self, follower_id: &UserId, following_id: &UserId, state: &FollowState) -> Result<(), DomainError>;
async fn list_followers(&self, user_id: &UserId, page: &PageParams) -> Result<Paginated<User>, DomainError>;
async fn list_following(&self, user_id: &UserId, page: &PageParams) -> Result<Paginated<User>, DomainError>;
async fn get_accepted_following_ids(&self, user_id: &UserId) -> Result<Vec<UserId>, DomainError>;
async fn find(
&self,
follower_id: &UserId,
following_id: &UserId,
) -> Result<Option<Follow>, DomainError>;
async fn update_state(
&self,
follower_id: &UserId,
following_id: &UserId,
state: &FollowState,
) -> Result<(), DomainError>;
async fn list_followers(
&self,
user_id: &UserId,
page: &PageParams,
) -> Result<Paginated<User>, DomainError>;
async fn list_following(
&self,
user_id: &UserId,
page: &PageParams,
) -> Result<Paginated<User>, DomainError>;
async fn get_accepted_following_ids(
&self,
user_id: &UserId,
) -> Result<Vec<UserId>, DomainError>;
}
#[async_trait]
@@ -97,10 +142,18 @@ pub trait BlockRepository: Send + Sync {
#[async_trait]
pub trait TagRepository: Send + Sync {
async fn find_or_create(&self, name: &str) -> Result<Tag, DomainError>;
async fn attach_to_thought(&self, thought_id: &ThoughtId, tag_id: i32) -> Result<(), DomainError>;
async fn attach_to_thought(
&self,
thought_id: &ThoughtId,
tag_id: i32,
) -> Result<(), DomainError>;
async fn detach_from_thought(&self, thought_id: &ThoughtId) -> Result<(), DomainError>;
async fn list_for_thought(&self, thought_id: &ThoughtId) -> Result<Vec<Tag>, DomainError>;
async fn list_thoughts_by_tag(&self, tag_name: &str, page: &PageParams) -> Result<Paginated<Thought>, DomainError>;
async fn list_thoughts_by_tag(
&self,
tag_name: &str,
page: &PageParams,
) -> Result<Paginated<Thought>, DomainError>;
/// Returns (tag_name, thought_count) pairs ordered by usage, most popular first.
async fn popular_tags(&self, limit: usize) -> Result<Vec<(String, i64)>, DomainError>;
}
@@ -115,14 +168,22 @@ pub trait ApiKeyRepository: Send + Sync {
#[async_trait]
pub trait TopFriendRepository: Send + Sync {
async fn set_top_friends(&self, user_id: &UserId, friends: Vec<(UserId, i16)>) -> Result<(), DomainError>;
async fn set_top_friends(
&self,
user_id: &UserId,
friends: Vec<(UserId, i16)>,
) -> Result<(), DomainError>;
async fn list_for_user(&self, user_id: &UserId) -> Result<Vec<(TopFriend, User)>, DomainError>;
}
#[async_trait]
pub trait NotificationRepository: Send + Sync {
async fn save(&self, n: &Notification) -> Result<(), DomainError>;
async fn list_for_user(&self, user_id: &UserId, page: &PageParams) -> Result<Paginated<Notification>, DomainError>;
async fn list_for_user(
&self,
user_id: &UserId,
page: &PageParams,
) -> Result<Paginated<Notification>, DomainError>;
async fn mark_read(&self, id: &NotificationId, user_id: &UserId) -> Result<(), DomainError>;
async fn mark_all_read(&self, user_id: &UserId) -> Result<(), DomainError>;
}
@@ -135,11 +196,35 @@ pub trait RemoteActorRepository: Send + Sync {
#[async_trait]
pub trait FeedRepository: Send + Sync {
async fn home_feed(&self, following_ids: &[UserId], page: &PageParams, viewer_id: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError>;
async fn public_feed(&self, page: &PageParams, viewer_id: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError>;
async fn search(&self, query: &str, page: &PageParams, viewer_id: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError>;
async fn tag_feed(&self, tag_name: &str, page: &PageParams, viewer_id: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError>;
async fn user_feed(&self, user_id: &UserId, page: &PageParams, viewer_id: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError>;
async fn home_feed(
&self,
following_ids: &[UserId],
page: &PageParams,
viewer_id: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError>;
async fn public_feed(
&self,
page: &PageParams,
viewer_id: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError>;
async fn search(
&self,
query: &str,
page: &PageParams,
viewer_id: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError>;
async fn tag_feed(
&self,
tag_name: &str,
page: &PageParams,
viewer_id: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError>;
async fn user_feed(
&self,
user_id: &UserId,
page: &PageParams,
viewer_id: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError>;
}
#[async_trait]
@@ -198,10 +283,7 @@ pub trait ActivityPubRepository: Send + Sync {
/// Ensure a remote actor placeholder exists; create one if absent.
/// Idempotent — safe to call multiple times with the same URL.
async fn intern_remote_actor(
&self,
actor_ap_url: &url::Url,
) -> Result<UserId, DomainError>;
async fn intern_remote_actor(&self, actor_ap_url: &url::Url) -> Result<UserId, DomainError>;
// ── Inbox processing (remote → local) ───────────────────────────
@@ -228,10 +310,7 @@ pub trait ActivityPubRepository: Send + Sync {
async fn retract_note(&self, ap_id: &url::Url) -> Result<(), DomainError>;
/// Remove all Notes from a remote actor (actor-level Delete/Tombstone).
async fn retract_actor_notes(
&self,
actor_ap_url: &url::Url,
) -> Result<(), DomainError>;
async fn retract_actor_notes(&self, actor_ap_url: &url::Url) -> Result<(), DomainError>;
// ── Node-level stats ─────────────────────────────────────────────

View File

@@ -1,7 +1,3 @@
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use chrono::Utc;
use url;
use crate::{
errors::DomainError,
events::DomainEvent,
@@ -17,33 +13,58 @@ use crate::{
user::User,
},
ports::*,
value_objects::{ApiKeyId, Content, Email, NotificationId, PasswordHash, ThoughtId, UserId, Username},
value_objects::{
ApiKeyId, Content, Email, NotificationId, PasswordHash, ThoughtId, UserId, Username,
},
};
use async_trait::async_trait;
use chrono::Utc;
use std::sync::{Arc, Mutex};
use url;
#[derive(Default, Clone)]
pub struct TestStore {
pub users: Arc<Mutex<Vec<User>>>,
pub thoughts: Arc<Mutex<Vec<Thought>>>,
pub likes: Arc<Mutex<Vec<Like>>>,
pub boosts: Arc<Mutex<Vec<Boost>>>,
pub follows: Arc<Mutex<Vec<Follow>>>,
pub blocks: Arc<Mutex<Vec<Block>>>,
pub tags: Arc<Mutex<Vec<Tag>>>,
pub api_keys: Arc<Mutex<Vec<ApiKey>>>,
pub top_friends: Arc<Mutex<Vec<TopFriend>>>,
pub users: Arc<Mutex<Vec<User>>>,
pub thoughts: Arc<Mutex<Vec<Thought>>>,
pub likes: Arc<Mutex<Vec<Like>>>,
pub boosts: Arc<Mutex<Vec<Boost>>>,
pub follows: Arc<Mutex<Vec<Follow>>>,
pub blocks: Arc<Mutex<Vec<Block>>>,
pub tags: Arc<Mutex<Vec<Tag>>>,
pub api_keys: Arc<Mutex<Vec<ApiKey>>>,
pub top_friends: Arc<Mutex<Vec<TopFriend>>>,
pub notifications: Arc<Mutex<Vec<Notification>>>,
pub events: Arc<Mutex<Vec<DomainEvent>>>,
pub events: Arc<Mutex<Vec<DomainEvent>>>,
}
#[async_trait] impl UserRepository for TestStore {
#[async_trait]
impl UserRepository for TestStore {
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError> {
Ok(self.users.lock().unwrap().iter().find(|u| &u.id == id).cloned())
Ok(self
.users
.lock()
.unwrap()
.iter()
.find(|u| &u.id == id)
.cloned())
}
async fn find_by_username(&self, username: &Username) -> Result<Option<User>, DomainError> {
Ok(self.users.lock().unwrap().iter().find(|u| u.username.as_str() == username.as_str()).cloned())
Ok(self
.users
.lock()
.unwrap()
.iter()
.find(|u| u.username.as_str() == username.as_str())
.cloned())
}
async fn find_by_email(&self, email: &Email) -> Result<Option<User>, DomainError> {
Ok(self.users.lock().unwrap().iter().find(|u| u.email.as_str() == email.as_str()).cloned())
Ok(self
.users
.lock()
.unwrap()
.iter()
.find(|u| u.email.as_str() == email.as_str())
.cloned())
}
async fn save(&self, user: &User) -> Result<(), DomainError> {
let mut g = self.users.lock().unwrap();
@@ -51,8 +72,22 @@ pub struct TestStore {
g.push(user.clone());
Ok(())
}
async fn update_profile(&self, user_id: &UserId, display_name: Option<String>, bio: Option<String>, avatar_url: Option<String>, header_url: Option<String>, custom_css: Option<String>) -> Result<(), DomainError> {
if let Some(u) = self.users.lock().unwrap().iter_mut().find(|u| &u.id == user_id) {
async fn update_profile(
&self,
user_id: &UserId,
display_name: Option<String>,
bio: Option<String>,
avatar_url: Option<String>,
header_url: Option<String>,
custom_css: Option<String>,
) -> Result<(), DomainError> {
if let Some(u) = self
.users
.lock()
.unwrap()
.iter_mut()
.find(|u| &u.id == user_id)
{
u.display_name = display_name;
u.bio = bio;
u.avatar_url = avatar_url;
@@ -61,13 +96,22 @@ pub struct TestStore {
}
Ok(())
}
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError> { Ok(vec![]) }
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError> {
Ok(vec![])
}
async fn count(&self) -> Result<i64, DomainError> {
Ok(self.users.lock().unwrap().iter().filter(|u| u.local).count() as i64)
Ok(self
.users
.lock()
.unwrap()
.iter()
.filter(|u| u.local)
.count() as i64)
}
}
#[async_trait] impl ThoughtRepository for TestStore {
#[async_trait]
impl ThoughtRepository for TestStore {
async fn save(&self, t: &Thought) -> Result<(), DomainError> {
let mut g = self.thoughts.lock().unwrap();
g.retain(|x| x.id != t.id);
@@ -75,36 +119,67 @@ pub struct TestStore {
Ok(())
}
async fn find_by_id(&self, id: &ThoughtId) -> Result<Option<Thought>, DomainError> {
Ok(self.thoughts.lock().unwrap().iter().find(|t| &t.id == id).cloned())
Ok(self
.thoughts
.lock()
.unwrap()
.iter()
.find(|t| &t.id == id)
.cloned())
}
async fn delete(&self, id: &ThoughtId, user_id: &UserId) -> Result<(), DomainError> {
let mut g = self.thoughts.lock().unwrap();
let before = g.len();
g.retain(|t| !(&t.id == id && &t.user_id == user_id));
if g.len() == before { return Err(DomainError::NotFound); }
if g.len() == before {
return Err(DomainError::NotFound);
}
Ok(())
}
async fn update_content(&self, id: &ThoughtId, content: &Content) -> Result<(), DomainError> {
if let Some(t) = self.thoughts.lock().unwrap().iter_mut().find(|t| &t.id == id) {
if let Some(t) = self
.thoughts
.lock()
.unwrap()
.iter_mut()
.find(|t| &t.id == id)
{
t.content = content.clone();
t.updated_at = Some(Utc::now());
}
Ok(())
}
async fn get_thread(&self, id: &ThoughtId) -> Result<Vec<Thought>, DomainError> {
Ok(self.thoughts.lock().unwrap().iter()
Ok(self
.thoughts
.lock()
.unwrap()
.iter()
.filter(|t| t.in_reply_to_id.as_ref() == Some(id) || &t.id == id)
.cloned().collect())
.cloned()
.collect())
}
async fn list_by_user(&self, _user_id: &UserId, _page: &PageParams) -> Result<Paginated<Thought>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
async fn list_by_user(
&self,
_user_id: &UserId,
_page: &PageParams,
) -> Result<Paginated<Thought>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
}
#[async_trait] impl LikeRepository for TestStore {
#[async_trait]
impl LikeRepository for TestStore {
async fn save(&self, like: &Like) -> Result<(), DomainError> {
let mut g = self.likes.lock().unwrap();
if g.iter().any(|l| l.user_id == like.user_id && l.thought_id == like.thought_id) {
if g.iter()
.any(|l| l.user_id == like.user_id && l.thought_id == like.thought_id)
{
return Err(DomainError::Conflict("already liked".into()));
}
g.push(like.clone());
@@ -114,21 +189,42 @@ pub struct TestStore {
let mut g = self.likes.lock().unwrap();
let before = g.len();
g.retain(|l| !(&l.user_id == user_id && &l.thought_id == thought_id));
if g.len() == before { return Err(DomainError::NotFound); }
if g.len() == before {
return Err(DomainError::NotFound);
}
Ok(())
}
async fn find(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<Option<Like>, DomainError> {
Ok(self.likes.lock().unwrap().iter().find(|l| &l.user_id == user_id && &l.thought_id == thought_id).cloned())
async fn find(
&self,
user_id: &UserId,
thought_id: &ThoughtId,
) -> Result<Option<Like>, DomainError> {
Ok(self
.likes
.lock()
.unwrap()
.iter()
.find(|l| &l.user_id == user_id && &l.thought_id == thought_id)
.cloned())
}
async fn count_for_thought(&self, thought_id: &ThoughtId) -> Result<i64, DomainError> {
Ok(self.likes.lock().unwrap().iter().filter(|l| &l.thought_id == thought_id).count() as i64)
Ok(self
.likes
.lock()
.unwrap()
.iter()
.filter(|l| &l.thought_id == thought_id)
.count() as i64)
}
}
#[async_trait] impl BoostRepository for TestStore {
#[async_trait]
impl BoostRepository for TestStore {
async fn save(&self, boost: &Boost) -> Result<(), DomainError> {
let mut g = self.boosts.lock().unwrap();
if g.iter().any(|b| b.user_id == boost.user_id && b.thought_id == boost.thought_id) {
if g.iter()
.any(|b| b.user_id == boost.user_id && b.thought_id == boost.thought_id)
{
return Err(DomainError::Conflict("already boosted".into()));
}
g.push(boost.clone());
@@ -138,21 +234,42 @@ pub struct TestStore {
let mut g = self.boosts.lock().unwrap();
let before = g.len();
g.retain(|b| !(&b.user_id == user_id && &b.thought_id == thought_id));
if g.len() == before { return Err(DomainError::NotFound); }
if g.len() == before {
return Err(DomainError::NotFound);
}
Ok(())
}
async fn find(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<Option<Boost>, DomainError> {
Ok(self.boosts.lock().unwrap().iter().find(|b| &b.user_id == user_id && &b.thought_id == thought_id).cloned())
async fn find(
&self,
user_id: &UserId,
thought_id: &ThoughtId,
) -> Result<Option<Boost>, DomainError> {
Ok(self
.boosts
.lock()
.unwrap()
.iter()
.find(|b| &b.user_id == user_id && &b.thought_id == thought_id)
.cloned())
}
async fn count_for_thought(&self, thought_id: &ThoughtId) -> Result<i64, DomainError> {
Ok(self.boosts.lock().unwrap().iter().filter(|b| &b.thought_id == thought_id).count() as i64)
Ok(self
.boosts
.lock()
.unwrap()
.iter()
.filter(|b| &b.thought_id == thought_id)
.count() as i64)
}
}
#[async_trait] impl FollowRepository for TestStore {
#[async_trait]
impl FollowRepository for TestStore {
async fn save(&self, follow: &Follow) -> Result<(), DomainError> {
let mut g = self.follows.lock().unwrap();
g.retain(|f| !(f.follower_id == follow.follower_id && f.following_id == follow.following_id));
g.retain(|f| {
!(f.follower_id == follow.follower_id && f.following_id == follow.following_id)
});
g.push(follow.clone());
Ok(())
}
@@ -160,160 +277,386 @@ pub struct TestStore {
let mut g = self.follows.lock().unwrap();
let before = g.len();
g.retain(|f| !(&f.follower_id == follower_id && &f.following_id == following_id));
if g.len() == before { return Err(DomainError::NotFound); }
if g.len() == before {
return Err(DomainError::NotFound);
}
Ok(())
}
async fn find(&self, follower_id: &UserId, following_id: &UserId) -> Result<Option<Follow>, DomainError> {
Ok(self.follows.lock().unwrap().iter().find(|f| &f.follower_id == follower_id && &f.following_id == following_id).cloned())
async fn find(
&self,
follower_id: &UserId,
following_id: &UserId,
) -> Result<Option<Follow>, DomainError> {
Ok(self
.follows
.lock()
.unwrap()
.iter()
.find(|f| &f.follower_id == follower_id && &f.following_id == following_id)
.cloned())
}
async fn update_state(&self, follower_id: &UserId, following_id: &UserId, state: &FollowState) -> Result<(), DomainError> {
if let Some(f) = self.follows.lock().unwrap().iter_mut().find(|f| &f.follower_id == follower_id && &f.following_id == following_id) {
async fn update_state(
&self,
follower_id: &UserId,
following_id: &UserId,
state: &FollowState,
) -> Result<(), DomainError> {
if let Some(f) = self
.follows
.lock()
.unwrap()
.iter_mut()
.find(|f| &f.follower_id == follower_id && &f.following_id == following_id)
{
f.state = state.clone();
}
Ok(())
}
async fn list_followers(&self, _user_id: &UserId, _p: &PageParams) -> Result<Paginated<User>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
async fn list_followers(
&self,
_user_id: &UserId,
_p: &PageParams,
) -> Result<Paginated<User>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn list_following(&self, _user_id: &UserId, _p: &PageParams) -> Result<Paginated<User>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
async fn list_following(
&self,
_user_id: &UserId,
_p: &PageParams,
) -> Result<Paginated<User>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn get_accepted_following_ids(&self, user_id: &UserId) -> Result<Vec<UserId>, DomainError> {
Ok(self.follows.lock().unwrap().iter()
async fn get_accepted_following_ids(
&self,
user_id: &UserId,
) -> Result<Vec<UserId>, DomainError> {
Ok(self
.follows
.lock()
.unwrap()
.iter()
.filter(|f| &f.follower_id == user_id && f.state == FollowState::Accepted)
.map(|f| f.following_id.clone())
.collect())
}
}
#[async_trait] impl BlockRepository for TestStore {
#[async_trait]
impl BlockRepository for TestStore {
async fn save(&self, block: &Block) -> Result<(), DomainError> {
self.blocks.lock().unwrap().push(block.clone());
Ok(())
}
async fn delete(&self, blocker_id: &UserId, blocked_id: &UserId) -> Result<(), DomainError> {
self.blocks.lock().unwrap().retain(|b| !(&b.blocker_id == blocker_id && &b.blocked_id == blocked_id));
self.blocks
.lock()
.unwrap()
.retain(|b| !(&b.blocker_id == blocker_id && &b.blocked_id == blocked_id));
Ok(())
}
async fn exists(&self, blocker_id: &UserId, blocked_id: &UserId) -> Result<bool, DomainError> {
Ok(self.blocks.lock().unwrap().iter().any(|b| &b.blocker_id == blocker_id && &b.blocked_id == blocked_id))
Ok(self
.blocks
.lock()
.unwrap()
.iter()
.any(|b| &b.blocker_id == blocker_id && &b.blocked_id == blocked_id))
}
}
#[async_trait] impl TagRepository for TestStore {
#[async_trait]
impl TagRepository for TestStore {
async fn find_or_create(&self, name: &str) -> Result<Tag, DomainError> {
let mut g = self.tags.lock().unwrap();
if let Some(t) = g.iter().find(|t| t.name == name) { return Ok(t.clone()); }
let tag = Tag { id: g.len() as i32 + 1, name: name.to_string() };
if let Some(t) = g.iter().find(|t| t.name == name) {
return Ok(t.clone());
}
let tag = Tag {
id: g.len() as i32 + 1,
name: name.to_string(),
};
g.push(tag.clone());
Ok(tag)
}
async fn attach_to_thought(&self, _tid: &ThoughtId, _tag_id: i32) -> Result<(), DomainError> { Ok(()) }
async fn detach_from_thought(&self, _tid: &ThoughtId) -> Result<(), DomainError> { Ok(()) }
async fn list_for_thought(&self, _tid: &ThoughtId) -> Result<Vec<Tag>, DomainError> { Ok(vec![]) }
async fn list_thoughts_by_tag(&self, _name: &str, _p: &PageParams) -> Result<Paginated<Thought>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
async fn attach_to_thought(&self, _tid: &ThoughtId, _tag_id: i32) -> Result<(), DomainError> {
Ok(())
}
async fn detach_from_thought(&self, _tid: &ThoughtId) -> Result<(), DomainError> {
Ok(())
}
async fn list_for_thought(&self, _tid: &ThoughtId) -> Result<Vec<Tag>, DomainError> {
Ok(vec![])
}
async fn list_thoughts_by_tag(
&self,
_name: &str,
_p: &PageParams,
) -> Result<Paginated<Thought>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn popular_tags(&self, _limit: usize) -> Result<Vec<(String, i64)>, DomainError> {
Ok(vec![])
}
}
#[async_trait] impl ApiKeyRepository for TestStore {
#[async_trait]
impl ApiKeyRepository for TestStore {
async fn save(&self, key: &ApiKey) -> Result<(), DomainError> {
self.api_keys.lock().unwrap().push(key.clone());
Ok(())
}
async fn find_by_hash(&self, hash: &str) -> Result<Option<ApiKey>, DomainError> {
Ok(self.api_keys.lock().unwrap().iter().find(|k| k.key_hash == hash).cloned())
Ok(self
.api_keys
.lock()
.unwrap()
.iter()
.find(|k| k.key_hash == hash)
.cloned())
}
async fn list_for_user(&self, uid: &UserId) -> Result<Vec<ApiKey>, DomainError> {
Ok(self.api_keys.lock().unwrap().iter().filter(|k| &k.user_id == uid).cloned().collect())
Ok(self
.api_keys
.lock()
.unwrap()
.iter()
.filter(|k| &k.user_id == uid)
.cloned()
.collect())
}
async fn delete(&self, id: &ApiKeyId, uid: &UserId) -> Result<(), DomainError> {
self.api_keys.lock().unwrap().retain(|k| !(&k.id == id && &k.user_id == uid));
self.api_keys
.lock()
.unwrap()
.retain(|k| !(&k.id == id && &k.user_id == uid));
Ok(())
}
}
#[async_trait] impl TopFriendRepository for TestStore {
async fn set_top_friends(&self, user_id: &UserId, friends: Vec<(UserId, i16)>) -> Result<(), DomainError> {
#[async_trait]
impl TopFriendRepository for TestStore {
async fn set_top_friends(
&self,
user_id: &UserId,
friends: Vec<(UserId, i16)>,
) -> Result<(), DomainError> {
let mut g = self.top_friends.lock().unwrap();
g.retain(|tf| &tf.user_id != user_id);
for (fid, pos) in friends {
g.push(TopFriend { user_id: user_id.clone(), friend_id: fid, position: pos });
g.push(TopFriend {
user_id: user_id.clone(),
friend_id: fid,
position: pos,
});
}
Ok(())
}
async fn list_for_user(&self, _uid: &UserId) -> Result<Vec<(TopFriend, User)>, DomainError> { Ok(vec![]) }
async fn list_for_user(&self, _uid: &UserId) -> Result<Vec<(TopFriend, User)>, DomainError> {
Ok(vec![])
}
}
#[async_trait] impl NotificationRepository for TestStore {
#[async_trait]
impl NotificationRepository for TestStore {
async fn save(&self, n: &Notification) -> Result<(), DomainError> {
self.notifications.lock().unwrap().push(n.clone());
Ok(())
}
async fn list_for_user(&self, uid: &UserId, _p: &PageParams) -> Result<Paginated<Notification>, DomainError> {
let items: Vec<_> = self.notifications.lock().unwrap().iter().filter(|n| &n.user_id == uid).cloned().collect();
async fn list_for_user(
&self,
uid: &UserId,
_p: &PageParams,
) -> Result<Paginated<Notification>, DomainError> {
let items: Vec<_> = self
.notifications
.lock()
.unwrap()
.iter()
.filter(|n| &n.user_id == uid)
.cloned()
.collect();
let total = items.len() as i64;
Ok(Paginated { items, total, page: 1, per_page: 20 })
Ok(Paginated {
items,
total,
page: 1,
per_page: 20,
})
}
async fn mark_read(&self, id: &NotificationId, _uid: &UserId) -> Result<(), DomainError> {
if let Some(n) = self.notifications.lock().unwrap().iter_mut().find(|n| &n.id == id) {
if let Some(n) = self
.notifications
.lock()
.unwrap()
.iter_mut()
.find(|n| &n.id == id)
{
n.read = true;
}
Ok(())
}
async fn mark_all_read(&self, uid: &UserId) -> Result<(), DomainError> {
for n in self.notifications.lock().unwrap().iter_mut().filter(|n| &n.user_id == uid) {
for n in self
.notifications
.lock()
.unwrap()
.iter_mut()
.filter(|n| &n.user_id == uid)
{
n.read = true;
}
Ok(())
}
}
#[async_trait] impl RemoteActorRepository for TestStore {
async fn upsert(&self, _a: &RemoteActor) -> Result<(), DomainError> { Ok(()) }
async fn find_by_url(&self, _url: &str) -> Result<Option<RemoteActor>, DomainError> { Ok(None) }
}
#[async_trait] impl FeedRepository for TestStore {
async fn home_feed(&self, _ids: &[UserId], _p: &PageParams, _v: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
#[async_trait]
impl RemoteActorRepository for TestStore {
async fn upsert(&self, _a: &RemoteActor) -> Result<(), DomainError> {
Ok(())
}
async fn public_feed(&self, _p: &PageParams, _v: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
}
async fn search(&self, _q: &str, _p: &PageParams, _v: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
}
async fn tag_feed(&self, _tag_name: &str, _page: &PageParams, _viewer_id: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
}
async fn user_feed(&self, _user_id: &UserId, _page: &PageParams, _viewer_id: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
async fn find_by_url(&self, _url: &str) -> Result<Option<RemoteActor>, DomainError> {
Ok(None)
}
}
#[async_trait] impl SearchPort for TestStore {
async fn search_thoughts(&self, _q: &str, _p: &PageParams, _v: Option<&UserId>) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
#[async_trait]
impl FeedRepository for TestStore {
async fn home_feed(
&self,
_ids: &[UserId],
_p: &PageParams,
_v: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn search_users(&self, _q: &str, _p: &PageParams) -> Result<Paginated<User>, DomainError> {
Ok(Paginated { items: vec![], total: 0, page: 1, per_page: 20 })
async fn public_feed(
&self,
_p: &PageParams,
_v: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn search(
&self,
_q: &str,
_p: &PageParams,
_v: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn tag_feed(
&self,
_tag_name: &str,
_page: &PageParams,
_viewer_id: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn user_feed(
&self,
_user_id: &UserId,
_page: &PageParams,
_viewer_id: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
}
#[async_trait] impl ActivityPubRepository for TestStore {
async fn outbox_entries_for_actor(&self, _uid: &UserId) -> Result<Vec<crate::ports::OutboxEntry>, DomainError> {
#[async_trait]
impl SearchPort for TestStore {
async fn search_thoughts(
&self,
_q: &str,
_p: &PageParams,
_v: Option<&UserId>,
) -> Result<Paginated<FeedEntry>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
async fn search_users(
&self,
_q: &str,
_p: &PageParams,
) -> Result<Paginated<User>, DomainError> {
Ok(Paginated {
items: vec![],
total: 0,
page: 1,
per_page: 20,
})
}
}
#[async_trait]
impl ActivityPubRepository for TestStore {
async fn outbox_entries_for_actor(
&self,
_uid: &UserId,
) -> Result<Vec<crate::ports::OutboxEntry>, DomainError> {
Ok(vec![])
}
async fn outbox_page_for_actor(&self, _uid: &UserId, _before: Option<chrono::DateTime<chrono::Utc>>, _limit: usize) -> Result<Vec<crate::ports::OutboxEntry>, DomainError> {
async fn outbox_page_for_actor(
&self,
_uid: &UserId,
_before: Option<chrono::DateTime<chrono::Utc>>,
_limit: usize,
) -> Result<Vec<crate::ports::OutboxEntry>, DomainError> {
Ok(vec![])
}
async fn find_remote_actor_id(&self, actor_ap_url: &url::Url) -> Result<Option<UserId>, DomainError> {
async fn find_remote_actor_id(
&self,
actor_ap_url: &url::Url,
) -> Result<Option<UserId>, DomainError> {
let url = actor_ap_url.to_string();
Ok(self.users.lock().unwrap().iter()
Ok(self
.users
.lock()
.unwrap()
.iter()
.find(|u| u.ap_id.as_deref() == Some(&url))
.map(|u| u.id.clone()))
}
@@ -322,31 +665,68 @@ pub struct TestStore {
return Ok(uid);
}
let uid = UserId::new();
let handle = actor_ap_url.path().trim_start_matches('/').replace('/', "_");
let handle = actor_ap_url
.path()
.trim_start_matches('/')
.replace('/', "_");
let user = crate::models::user::User {
id: uid.clone(),
username: Username::from_trusted(handle.clone()),
email: Email::from_trusted(format!("{}@remote", uid)),
password_hash: PasswordHash("".into()),
display_name: None, bio: None, avatar_url: None, header_url: None,
custom_css: None, local: false,
display_name: None,
bio: None,
avatar_url: None,
header_url: None,
custom_css: None,
local: false,
ap_id: Some(actor_ap_url.to_string()),
inbox_url: None, public_key: None, private_key: None,
created_at: chrono::Utc::now(), updated_at: chrono::Utc::now(),
inbox_url: None,
public_key: None,
private_key: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
self.users.lock().unwrap().push(user);
Ok(uid)
}
async fn accept_note(&self, _ap_id: &url::Url, _author_id: &UserId, _content: &str, _published: chrono::DateTime<chrono::Utc>, _sensitive: bool, _content_warning: Option<String>) -> Result<(), DomainError> { Ok(()) }
async fn apply_note_update(&self, _ap_id: &url::Url, _new_content: &str) -> Result<(), DomainError> { Ok(()) }
async fn retract_note(&self, _ap_id: &url::Url) -> Result<(), DomainError> { Ok(()) }
async fn retract_actor_notes(&self, _actor_ap_url: &url::Url) -> Result<(), DomainError> { Ok(()) }
async fn accept_note(
&self,
_ap_id: &url::Url,
_author_id: &UserId,
_content: &str,
_published: chrono::DateTime<chrono::Utc>,
_sensitive: bool,
_content_warning: Option<String>,
) -> Result<(), DomainError> {
Ok(())
}
async fn apply_note_update(
&self,
_ap_id: &url::Url,
_new_content: &str,
) -> Result<(), DomainError> {
Ok(())
}
async fn retract_note(&self, _ap_id: &url::Url) -> Result<(), DomainError> {
Ok(())
}
async fn retract_actor_notes(&self, _actor_ap_url: &url::Url) -> Result<(), DomainError> {
Ok(())
}
async fn count_local_notes(&self) -> Result<u64, DomainError> {
Ok(self.thoughts.lock().unwrap().iter().filter(|t| t.local).count() as u64)
Ok(self
.thoughts
.lock()
.unwrap()
.iter()
.filter(|t| t.local)
.count() as u64)
}
}
#[async_trait] impl EventPublisher for TestStore {
#[async_trait]
impl EventPublisher for TestStore {
async fn publish(&self, event: &DomainEvent) -> Result<(), DomainError> {
self.events.lock().unwrap().push(event.clone());
Ok(())
@@ -354,8 +734,11 @@ pub struct TestStore {
}
pub struct NoOpEventPublisher;
#[async_trait] impl EventPublisher for NoOpEventPublisher {
async fn publish(&self, _e: &DomainEvent) -> Result<(), DomainError> { Ok(()) }
#[async_trait]
impl EventPublisher for NoOpEventPublisher {
async fn publish(&self, _e: &DomainEvent) -> Result<(), DomainError> {
Ok(())
}
}
#[cfg(test)]
@@ -366,7 +749,10 @@ mod ap_repo_tests {
#[tokio::test]
async fn test_store_outbox_returns_empty() {
let store = TestStore::default();
let result = store.outbox_entries_for_actor(&UserId::new()).await.unwrap();
let result = store
.outbox_entries_for_actor(&UserId::new())
.await
.unwrap();
assert!(result.is_empty());
}
@@ -388,14 +774,33 @@ mod search_tests {
#[tokio::test]
async fn test_store_search_thoughts_returns_empty() {
let store = TestStore::default();
let result = store.search_thoughts("hello", &PageParams { page: 1, per_page: 20 }, None).await.unwrap();
let result = store
.search_thoughts(
"hello",
&PageParams {
page: 1,
per_page: 20,
},
None,
)
.await
.unwrap();
assert_eq!(result.total, 0);
}
#[tokio::test]
async fn test_store_search_users_returns_empty() {
let store = TestStore::default();
let result = store.search_users("alice", &PageParams { page: 1, per_page: 20 }).await.unwrap();
let result = store
.search_users(
"alice",
&PageParams {
page: 1,
per_page: 20,
},
)
.await
.unwrap();
assert_eq!(result.total, 0);
}
}

View File

@@ -1,17 +1,25 @@
use uuid::Uuid;
use crate::errors::DomainError;
use uuid::Uuid;
macro_rules! uuid_id {
($name:ident) => {
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct $name(Uuid);
impl $name {
pub fn new() -> Self { Self(Uuid::new_v4()) }
pub fn from_uuid(u: Uuid) -> Self { Self(u) }
pub fn as_uuid(&self) -> Uuid { self.0 }
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn from_uuid(u: Uuid) -> Self {
Self(u)
}
pub fn as_uuid(&self) -> Uuid {
self.0
}
}
impl Default for $name {
fn default() -> Self { Self::new() }
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -37,15 +45,23 @@ impl Username {
return Err(DomainError::InvalidInput("username: 1-32 chars".into()));
}
if !s.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Err(DomainError::InvalidInput("username: alphanumeric or underscore only".into()));
return Err(DomainError::InvalidInput(
"username: alphanumeric or underscore only".into(),
));
}
Ok(Self(s))
}
pub fn from_trusted(s: String) -> Self { Self(s) }
pub fn as_str(&self) -> &str { &self.0 }
pub fn from_trusted(s: String) -> Self {
Self(s)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for Username {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) }
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
@@ -58,8 +74,12 @@ impl Email {
}
Ok(Self(s))
}
pub fn from_trusted(s: String) -> Self { Self(s) }
pub fn as_str(&self) -> &str { &self.0 }
pub fn from_trusted(s: String) -> Self {
Self(s)
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -75,11 +95,17 @@ impl Content {
}
Ok(Self(s))
}
pub fn new_remote(s: impl Into<String>) -> Self { Self(s.into()) }
pub fn as_str(&self) -> &str { &self.0 }
pub fn new_remote(s: impl Into<String>) -> Self {
Self(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for Content {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) }
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]