feat: v2 rewrite — hexagonal arch, ActivityPub federation, NATS, deployment-ready (#1)
This commit was merged in pull request #1.
This commit is contained in:
23
crates/domain/Cargo.toml
Normal file
23
crates/domain/Cargo.toml
Normal file
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "domain"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[features]
|
||||
test-helpers = ["dep:sha2", "dep:hex"]
|
||||
|
||||
[dependencies]
|
||||
async-trait = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
uuid = { workspace = true }
|
||||
chrono = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
url = { workspace = true }
|
||||
sha2 = { version = "0.10", optional = true }
|
||||
hex = { version = "0.4", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
sha2 = "0.10"
|
||||
hex = "0.4"
|
||||
21
crates/domain/src/errors.rs
Normal file
21
crates/domain/src/errors.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error, Clone)]
|
||||
pub enum DomainError {
|
||||
#[error("not found")]
|
||||
NotFound,
|
||||
#[error("unauthorized")]
|
||||
Unauthorized,
|
||||
#[error("forbidden")]
|
||||
Forbidden,
|
||||
#[error("conflict: {0}")]
|
||||
Conflict(String),
|
||||
#[error("unique violation on field: {field}")]
|
||||
UniqueViolation { field: &'static str },
|
||||
#[error("invalid input: {0}")]
|
||||
InvalidInput(String),
|
||||
#[error("external service error: {0}")]
|
||||
ExternalService(String),
|
||||
#[error("internal error: {0}")]
|
||||
Internal(String),
|
||||
}
|
||||
86
crates/domain/src/events.rs
Normal file
86
crates/domain/src/events.rs
Normal file
@@ -0,0 +1,86 @@
|
||||
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,
|
||||
},
|
||||
ProfileUpdated {
|
||||
user_id: UserId,
|
||||
},
|
||||
MentionReceived {
|
||||
thought_id: ThoughtId,
|
||||
mentioned_user_id: UserId,
|
||||
author_user_id: UserId,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct EventEnvelope {
|
||||
pub event: DomainEvent,
|
||||
pub delivery_count: u64,
|
||||
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)
|
||||
.field("delivery_count", &self.delivery_count)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
139
crates/domain/src/hashtag.rs
Normal file
139
crates/domain/src/hashtag.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// A hashtag extracted from content.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct Hashtag {
|
||||
/// Original casing, e.g. "Rust"
|
||||
pub raw: String,
|
||||
/// Lowercased, e.g. "rust" — used for DB lookups
|
||||
pub normalized: String,
|
||||
/// "tags/rust" — callers prepend base_url
|
||||
pub url_slug: String,
|
||||
/// "#rust" — used directly in AP tag array
|
||||
pub ap_name: String,
|
||||
}
|
||||
|
||||
/// Extract hashtags from content using a char-by-char scan.
|
||||
///
|
||||
/// Rules:
|
||||
/// - Tag starts after a bare `#` followed immediately by an alphanumeric char.
|
||||
/// - Tag chars: `[A-Za-z0-9_]`.
|
||||
/// - Deduplicated case-insensitively; first occurrence wins.
|
||||
/// - Returned in order of first appearance.
|
||||
pub fn extract(content: &str) -> Vec<Hashtag> {
|
||||
let mut seen: HashSet<String> = HashSet::new();
|
||||
let mut tags: Vec<Hashtag> = Vec::new();
|
||||
let mut chars = content.char_indices().peekable();
|
||||
|
||||
while let Some((_, c)) = chars.next() {
|
||||
if c == '#'
|
||||
&& chars
|
||||
.peek()
|
||||
.map(|(_, nc)| nc.is_alphanumeric())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let raw: String = chars
|
||||
.by_ref()
|
||||
.take_while(|(_, nc)| nc.is_alphanumeric() || *nc == '_')
|
||||
.map(|(_, nc)| nc)
|
||||
.collect();
|
||||
|
||||
if raw.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalized = raw.to_lowercase();
|
||||
if seen.insert(normalized.clone()) {
|
||||
tags.push(Hashtag {
|
||||
url_slug: format!("tags/{}", normalized),
|
||||
ap_name: format!("#{}", normalized),
|
||||
raw,
|
||||
normalized,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tags
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn names(tags: &[Hashtag]) -> Vec<&str> {
|
||||
tags.iter().map(|h| h.normalized.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn basic() {
|
||||
let tags = extract("Hello #world and #Rust!");
|
||||
assert_eq!(names(&tags), ["world", "rust"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fields() {
|
||||
let tags = extract("#Rust");
|
||||
assert_eq!(tags.len(), 1);
|
||||
let h = &tags[0];
|
||||
assert_eq!(h.raw, "Rust");
|
||||
assert_eq!(h.normalized, "rust");
|
||||
assert_eq!(h.url_slug, "tags/rust");
|
||||
assert_eq!(h.ap_name, "#rust");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedup_case_insensitive() {
|
||||
let tags = extract("#rust #Rust #RUST");
|
||||
assert_eq!(names(&tags), ["rust"]);
|
||||
assert_eq!(tags[0].raw, "rust"); // first occurrence wins
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deduplicates_non_adjacent() {
|
||||
// The old algorithm used Vec::dedup() which only removes adjacent duplicates.
|
||||
// Using HashSet silently fixed this bug. This test documents the fix.
|
||||
let tags = extract("#a #b #a");
|
||||
assert_eq!(tags.len(), 2);
|
||||
assert_eq!(tags[0].normalized, "a");
|
||||
assert_eq!(tags[1].normalized, "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mid_word_extracted() {
|
||||
// `text#tag` — `#` not preceded by whitespace is still matched by the
|
||||
// char-by-char scan (the old algorithm didn't require whitespace before `#`).
|
||||
// This test documents the authoritative behaviour: mid-word tags ARE extracted.
|
||||
let tags = extract("text#tag");
|
||||
assert_eq!(names(&tags), ["tag"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_only_ignored() {
|
||||
assert!(extract("# lone hash").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_punctuation_excluded() {
|
||||
// punctuation after tag terminates the tag, not included
|
||||
let tags = extract("#rust.");
|
||||
assert_eq!(names(&tags), ["rust"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underscore_allowed() {
|
||||
let tags = extract("#hello_world");
|
||||
assert_eq!(names(&tags), ["hello_world"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_content() {
|
||||
assert!(extract("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn order_of_appearance() {
|
||||
let tags = extract("#b #a #c");
|
||||
assert_eq!(names(&tags), ["b", "a", "c"]);
|
||||
}
|
||||
}
|
||||
9
crates/domain/src/lib.rs
Normal file
9
crates/domain/src/lib.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
pub mod errors;
|
||||
pub mod events;
|
||||
pub mod hashtag;
|
||||
pub mod models;
|
||||
pub mod ports;
|
||||
pub mod value_objects;
|
||||
|
||||
#[cfg(any(test, feature = "test-helpers"))]
|
||||
pub mod testing;
|
||||
7
crates/domain/src/models/actor_connection_summary.rs
Normal file
7
crates/domain/src/models/actor_connection_summary.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ActorConnectionSummary {
|
||||
pub url: String,
|
||||
pub handle: String,
|
||||
pub display_name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
}
|
||||
11
crates/domain/src/models/api_key.rs
Normal file
11
crates/domain/src/models/api_key.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use crate::value_objects::{ApiKeyId, UserId};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ApiKey {
|
||||
pub id: ApiKeyId,
|
||||
pub user_id: UserId,
|
||||
pub key_hash: String,
|
||||
pub name: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
14
crates/domain/src/models/connection_type.rs
Normal file
14
crates/domain/src/models/connection_type.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ConnectionType {
|
||||
Followers,
|
||||
Following,
|
||||
}
|
||||
|
||||
impl ConnectionType {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Followers => "followers",
|
||||
Self::Following => "following",
|
||||
}
|
||||
}
|
||||
}
|
||||
60
crates/domain/src/models/feed.rs
Normal file
60
crates/domain/src/models/feed.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use crate::models::{thought::Thought, user::User};
|
||||
use crate::value_objects::UserId;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct EngagementStats {
|
||||
pub like_count: i64,
|
||||
pub boost_count: i64,
|
||||
pub reply_count: i64,
|
||||
}
|
||||
|
||||
/// Present only when an authenticated viewer made the request.
|
||||
/// `liked`/`boosted` are the viewer's interaction state with this thought.
|
||||
/// `None` means anonymous request or viewer context unavailable.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ViewerContext {
|
||||
pub liked: bool,
|
||||
pub boosted: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FeedEntry {
|
||||
pub thought: Thought,
|
||||
pub author: User,
|
||||
pub stats: EngagementStats,
|
||||
pub viewer: Option<ViewerContext>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct UserSummary {
|
||||
pub id: UserId,
|
||||
pub username: String,
|
||||
pub display_name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub thought_count: i64,
|
||||
pub follower_count: i64,
|
||||
pub following_count: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Paginated<T> {
|
||||
pub items: Vec<T>,
|
||||
pub total: i64,
|
||||
pub page: u64,
|
||||
pub per_page: u64,
|
||||
}
|
||||
12
crates/domain/src/models/mod.rs
Normal file
12
crates/domain/src/models/mod.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
pub mod actor_connection_summary;
|
||||
pub mod api_key;
|
||||
pub mod connection_type;
|
||||
pub mod feed;
|
||||
pub mod notification;
|
||||
pub mod remote_actor;
|
||||
pub mod remote_note;
|
||||
pub mod social;
|
||||
pub mod tag;
|
||||
pub mod thought;
|
||||
pub mod top_friend;
|
||||
pub mod user;
|
||||
66
crates/domain/src/models/notification.rs
Normal file
66
crates/domain/src/models/notification.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
use crate::value_objects::{NotificationId, ThoughtId, UserId};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum NotificationKind {
|
||||
Like {
|
||||
thought_id: ThoughtId,
|
||||
from_user_id: UserId,
|
||||
},
|
||||
Boost {
|
||||
thought_id: ThoughtId,
|
||||
from_user_id: UserId,
|
||||
},
|
||||
Reply {
|
||||
thought_id: ThoughtId,
|
||||
from_user_id: UserId,
|
||||
},
|
||||
Mention {
|
||||
thought_id: ThoughtId,
|
||||
from_user_id: UserId,
|
||||
},
|
||||
Follow {
|
||||
from_user_id: UserId,
|
||||
},
|
||||
}
|
||||
|
||||
impl NotificationKind {
|
||||
pub fn from_user_id(&self) -> &UserId {
|
||||
match self {
|
||||
Self::Like { from_user_id, .. } => from_user_id,
|
||||
Self::Boost { from_user_id, .. } => from_user_id,
|
||||
Self::Reply { from_user_id, .. } => from_user_id,
|
||||
Self::Mention { from_user_id, .. } => from_user_id,
|
||||
Self::Follow { from_user_id } => from_user_id,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn thought_id(&self) -> Option<&ThoughtId> {
|
||||
match self {
|
||||
Self::Like { thought_id, .. } => Some(thought_id),
|
||||
Self::Boost { thought_id, .. } => Some(thought_id),
|
||||
Self::Reply { thought_id, .. } => Some(thought_id),
|
||||
Self::Mention { thought_id, .. } => Some(thought_id),
|
||||
Self::Follow { .. } => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Like { .. } => "like",
|
||||
Self::Boost { .. } => "boost",
|
||||
Self::Reply { .. } => "reply",
|
||||
Self::Mention { .. } => "mention",
|
||||
Self::Follow { .. } => "follow",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Notification {
|
||||
pub id: NotificationId,
|
||||
pub user_id: UserId,
|
||||
pub kind: NotificationKind,
|
||||
pub read: bool,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
17
crates/domain/src/models/remote_actor.rs
Normal file
17
crates/domain/src/models/remote_actor.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RemoteActor {
|
||||
pub url: String,
|
||||
pub handle: String,
|
||||
pub display_name: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub banner_url: Option<String>,
|
||||
pub also_known_as: Option<String>,
|
||||
pub outbox_url: Option<String>,
|
||||
pub followers_url: Option<String>,
|
||||
pub following_url: Option<String>,
|
||||
pub attachment: Vec<(String, String)>,
|
||||
pub last_fetched_at: DateTime<Utc>,
|
||||
}
|
||||
10
crates/domain/src/models/remote_note.rs
Normal file
10
crates/domain/src/models/remote_note.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RemoteNote {
|
||||
pub ap_id: String,
|
||||
pub content: String,
|
||||
pub published: DateTime<Utc>,
|
||||
pub sensitive: bool,
|
||||
pub content_warning: Option<String>,
|
||||
}
|
||||
64
crates/domain/src/models/social.rs
Normal file
64
crates/domain/src/models/social.rs
Normal file
@@ -0,0 +1,64 @@
|
||||
use crate::value_objects::{BoostId, LikeId, ThoughtId, UserId};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Like {
|
||||
pub id: LikeId,
|
||||
pub user_id: UserId,
|
||||
pub thought_id: ThoughtId,
|
||||
pub ap_id: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Boost {
|
||||
pub id: BoostId,
|
||||
pub user_id: UserId,
|
||||
pub thought_id: ThoughtId,
|
||||
pub ap_id: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum FollowState {
|
||||
Pending,
|
||||
Accepted,
|
||||
Rejected,
|
||||
}
|
||||
|
||||
impl FollowState {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Pending => "pending",
|
||||
Self::Accepted => "accepted",
|
||||
Self::Rejected => "rejected",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_db_str(s: &str) -> Result<Self, crate::errors::DomainError> {
|
||||
match s {
|
||||
"pending" => Ok(Self::Pending),
|
||||
"accepted" => Ok(Self::Accepted),
|
||||
"rejected" => Ok(Self::Rejected),
|
||||
other => Err(crate::errors::DomainError::Internal(format!(
|
||||
"unknown follow_state: '{other}'"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Follow {
|
||||
pub follower_id: UserId,
|
||||
pub following_id: UserId,
|
||||
pub state: FollowState,
|
||||
pub ap_id: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Block {
|
||||
pub blocker_id: UserId,
|
||||
pub blocked_id: UserId,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
5
crates/domain/src/models/tag.rs
Normal file
5
crates/domain/src/models/tag.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Tag {
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
}
|
||||
72
crates/domain/src/models/thought.rs
Normal file
72
crates/domain/src/models/thought.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
use crate::value_objects::{Content, ThoughtId, UserId};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Visibility {
|
||||
Public,
|
||||
Followers,
|
||||
Unlisted,
|
||||
Direct,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Thought {
|
||||
pub id: ThoughtId,
|
||||
pub user_id: UserId,
|
||||
pub content: Content,
|
||||
pub in_reply_to_id: Option<ThoughtId>,
|
||||
pub visibility: Visibility,
|
||||
pub content_warning: Option<String>,
|
||||
pub sensitive: bool,
|
||||
pub local: bool,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl Visibility {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Visibility::Public => "public",
|
||||
Visibility::Followers => "followers",
|
||||
Visibility::Unlisted => "unlisted",
|
||||
Visibility::Direct => "direct",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_db_str(s: &str) -> Result<Self, crate::errors::DomainError> {
|
||||
match s {
|
||||
"public" => Ok(Self::Public),
|
||||
"followers" => Ok(Self::Followers),
|
||||
"unlisted" => Ok(Self::Unlisted),
|
||||
"direct" => Ok(Self::Direct),
|
||||
other => Err(crate::errors::DomainError::Internal(format!(
|
||||
"unknown visibility: '{other}'"
|
||||
))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
user_id,
|
||||
content,
|
||||
in_reply_to_id,
|
||||
visibility,
|
||||
content_warning,
|
||||
sensitive,
|
||||
local: true,
|
||||
created_at: Utc::now(),
|
||||
updated_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
8
crates/domain/src/models/top_friend.rs
Normal file
8
crates/domain/src/models/top_friend.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use crate::value_objects::UserId;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TopFriend {
|
||||
pub user_id: UserId,
|
||||
pub friend_id: UserId,
|
||||
pub position: i16,
|
||||
}
|
||||
43
crates/domain/src/models/user.rs
Normal file
43
crates/domain/src/models/user.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
use crate::value_objects::{Email, PasswordHash, UserId, Username};
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct User {
|
||||
pub id: UserId,
|
||||
pub username: Username,
|
||||
pub email: Email,
|
||||
pub password_hash: PasswordHash,
|
||||
pub display_name: Option<String>,
|
||||
pub bio: Option<String>,
|
||||
pub avatar_url: Option<String>,
|
||||
pub header_url: Option<String>,
|
||||
pub custom_css: Option<String>,
|
||||
pub local: bool,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
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,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
}
|
||||
}
|
||||
}
|
||||
411
crates/domain/src/ports.rs
Normal file
411
crates/domain/src/ports.rs
Normal file
@@ -0,0 +1,411 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{
|
||||
errors::DomainError,
|
||||
events::{DomainEvent, EventEnvelope},
|
||||
models::{
|
||||
api_key::ApiKey,
|
||||
feed::{EngagementStats, FeedEntry, PageParams, Paginated, UserSummary, ViewerContext},
|
||||
notification::Notification,
|
||||
remote_actor::RemoteActor,
|
||||
social::{Block, Boost, Follow, FollowState, Like},
|
||||
tag::Tag,
|
||||
thought::Thought,
|
||||
top_friend::TopFriend,
|
||||
user::User,
|
||||
},
|
||||
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,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait AuthService: Send + Sync {
|
||||
fn generate_token(&self, user_id: &UserId) -> Result<GeneratedToken, DomainError>;
|
||||
fn validate_token(&self, token: &str) -> Result<UserId, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait PasswordHasher: Send + Sync {
|
||||
async fn hash(&self, plain: &str) -> Result<PasswordHash, DomainError>;
|
||||
async fn verify(&self, plain: &str, hash: &PasswordHash) -> Result<bool, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait EventPublisher: Send + Sync {
|
||||
async fn publish(&self, event: &DomainEvent) -> Result<(), DomainError>;
|
||||
}
|
||||
|
||||
pub trait EventConsumer: Send + Sync {
|
||||
fn consume(&self) -> futures::stream::BoxStream<'_, Result<EventEnvelope, DomainError>>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait OutboxWriter: Send + Sync {
|
||||
async fn append(&self, event: &DomainEvent) -> Result<(), DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserReader: Send + Sync {
|
||||
async fn find_by_id(&self, id: &UserId) -> Result<Option<User>, DomainError>;
|
||||
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 list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError>;
|
||||
async fn count(&self) -> Result<i64, DomainError>;
|
||||
async fn list_paginated(&self, page: PageParams) -> Result<Paginated<UserSummary>, DomainError>;
|
||||
async fn find_by_ids(&self, ids: &[UserId]) -> Result<HashMap<UserId, User>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UserWriter: Send + Sync {
|
||||
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>;
|
||||
}
|
||||
|
||||
/// Combined supertrait — `AppState.users` stays `Arc<dyn UserRepository>`.
|
||||
/// Blanket impl: any type implementing both sub-traits gets `UserRepository` for free.
|
||||
pub trait UserRepository: UserReader + UserWriter {}
|
||||
impl<T: UserReader + UserWriter> UserRepository for T {}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ThoughtRepository: Send + Sync {
|
||||
async fn save(&self, thought: &Thought) -> Result<(), DomainError>;
|
||||
async fn find_by_id(&self, id: &ThoughtId) -> Result<Option<Thought>, DomainError>;
|
||||
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_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 count_for_thought(&self, thought_id: &ThoughtId) -> Result<i64, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
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 count_for_thought(&self, thought_id: &ThoughtId) -> Result<i64, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait EngagementRepository: Send + Sync {
|
||||
async fn get_for_thoughts(
|
||||
&self,
|
||||
thought_ids: &[ThoughtId],
|
||||
viewer_id: Option<&UserId>,
|
||||
) -> Result<HashMap<ThoughtId, (EngagementStats, Option<ViewerContext>)>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
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_trait]
|
||||
pub trait BlockRepository: Send + Sync {
|
||||
async fn save(&self, block: &Block) -> Result<(), DomainError>;
|
||||
async fn delete(&self, blocker_id: &UserId, blocked_id: &UserId) -> Result<(), DomainError>;
|
||||
async fn exists(&self, blocker_id: &UserId, blocked_id: &UserId) -> Result<bool, DomainError>;
|
||||
}
|
||||
|
||||
#[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 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>;
|
||||
/// Returns (tag_name, thought_count) pairs ordered by usage, most popular first.
|
||||
async fn popular_tags(&self, limit: usize) -> Result<Vec<(String, i64)>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ApiKeyRepository: Send + Sync {
|
||||
async fn save(&self, key: &ApiKey) -> Result<(), DomainError>;
|
||||
async fn find_by_hash(&self, key_hash: &str) -> Result<Option<ApiKey>, DomainError>;
|
||||
async fn list_for_user(&self, user_id: &UserId) -> Result<Vec<ApiKey>, DomainError>;
|
||||
async fn delete(&self, id: &ApiKeyId, user_id: &UserId) -> Result<(), DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ApiKeyService: Send + Sync {
|
||||
async fn validate_key(&self, raw_key: &str) -> Result<Option<UserId>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait TopFriendRepository: Send + Sync {
|
||||
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 count_unread(&self, user_id: &UserId) -> Result<u64, DomainError>;
|
||||
async fn mark_read(&self, id: &NotificationId, user_id: &UserId) -> Result<(), DomainError>;
|
||||
async fn mark_all_read(&self, user_id: &UserId) -> Result<(), DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait RemoteActorRepository: Send + Sync {
|
||||
async fn upsert(&self, actor: &RemoteActor) -> Result<(), DomainError>;
|
||||
async fn find_by_url(&self, url: &str) -> Result<Option<RemoteActor>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait RemoteActorConnectionRepository: Send + Sync {
|
||||
async fn upsert_connections(
|
||||
&self,
|
||||
actor_url: &str,
|
||||
connection_type: &str,
|
||||
page: u32,
|
||||
actors: &[crate::models::actor_connection_summary::ActorConnectionSummary],
|
||||
) -> Result<(), DomainError>;
|
||||
|
||||
async fn list_connections(
|
||||
&self,
|
||||
actor_url: &str,
|
||||
connection_type: &str,
|
||||
page: u32,
|
||||
) -> Result<Vec<crate::models::actor_connection_summary::ActorConnectionSummary>, DomainError>;
|
||||
|
||||
async fn connection_page_age(
|
||||
&self,
|
||||
actor_url: &str,
|
||||
connection_type: &str,
|
||||
page: u32,
|
||||
) -> Result<Option<chrono::DateTime<chrono::Utc>>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait FederationLookupPort: Send + Sync {
|
||||
async fn lookup_actor(&self, handle: &str) -> Result<RemoteActor, DomainError>;
|
||||
async fn actor_json(&self, user_id: &UserId) -> Result<String, DomainError>;
|
||||
async fn followers_collection_json(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
page: Option<u32>,
|
||||
) -> Result<String, DomainError>;
|
||||
async fn following_collection_json(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
page: Option<u32>,
|
||||
) -> Result<String, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait FederationFollowPort: Send + Sync {
|
||||
async fn follow_remote(&self, local_user_id: &UserId, handle: &str) -> Result<(), DomainError>;
|
||||
async fn unfollow_remote(
|
||||
&self,
|
||||
local_user_id: &UserId,
|
||||
handle: &str,
|
||||
) -> Result<(), DomainError>;
|
||||
async fn get_remote_following(&self, user_id: &UserId)
|
||||
-> Result<Vec<RemoteActor>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait FederationFollowRequestPort: Send + Sync {
|
||||
async fn get_pending_followers(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
) -> Result<Vec<RemoteActor>, DomainError>;
|
||||
async fn accept_follow_request(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
actor_url: &str,
|
||||
) -> Result<(), DomainError>;
|
||||
async fn reject_follow_request(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
actor_url: &str,
|
||||
) -> Result<(), DomainError>;
|
||||
async fn get_remote_followers(&self, user_id: &UserId)
|
||||
-> Result<Vec<RemoteActor>, DomainError>;
|
||||
async fn remove_remote_follower(
|
||||
&self,
|
||||
user_id: &UserId,
|
||||
actor_url: &str,
|
||||
) -> Result<(), DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait FederationFetchPort: Send + Sync {
|
||||
async fn fetch_outbox_page(
|
||||
&self,
|
||||
outbox_url: &str,
|
||||
page: u32,
|
||||
) -> Result<Vec<crate::models::remote_note::RemoteNote>, DomainError>;
|
||||
async fn fetch_actor_urls_from_collection(
|
||||
&self,
|
||||
collection_url: &str,
|
||||
) -> Result<Vec<String>, DomainError>;
|
||||
async fn resolve_actor_profiles(
|
||||
&self,
|
||||
urls: Vec<String>,
|
||||
) -> Vec<crate::models::actor_connection_summary::ActorConnectionSummary>;
|
||||
}
|
||||
|
||||
pub trait FederationActionPort:
|
||||
FederationLookupPort + FederationFollowPort + FederationFollowRequestPort + FederationFetchPort
|
||||
{
|
||||
}
|
||||
impl<
|
||||
T: FederationLookupPort
|
||||
+ FederationFollowPort
|
||||
+ FederationFollowRequestPort
|
||||
+ FederationFetchPort,
|
||||
> FederationActionPort for T
|
||||
{
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum FeedScope {
|
||||
Home { following_ids: Vec<UserId> },
|
||||
Public,
|
||||
Tag { tag_name: String },
|
||||
User { user_id: UserId },
|
||||
Search { query: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FeedQuery {
|
||||
pub scope: FeedScope,
|
||||
pub page: PageParams,
|
||||
pub viewer_id: Option<UserId>,
|
||||
}
|
||||
|
||||
impl FeedQuery {
|
||||
pub fn home(viewer_id: UserId, following_ids: Vec<UserId>, page: PageParams) -> Self {
|
||||
Self { scope: FeedScope::Home { following_ids }, page, viewer_id: Some(viewer_id) }
|
||||
}
|
||||
pub fn public(page: PageParams, viewer_id: Option<UserId>) -> Self {
|
||||
Self { scope: FeedScope::Public, page, viewer_id }
|
||||
}
|
||||
pub fn tag(tag_name: impl Into<String>, page: PageParams, viewer_id: Option<UserId>) -> Self {
|
||||
Self { scope: FeedScope::Tag { tag_name: tag_name.into() }, page, viewer_id }
|
||||
}
|
||||
pub fn user(user_id: UserId, page: PageParams, viewer_id: Option<UserId>) -> Self {
|
||||
Self { scope: FeedScope::User { user_id }, page, viewer_id }
|
||||
}
|
||||
pub fn search(query: impl Into<String>, page: PageParams, viewer_id: Option<UserId>) -> Self {
|
||||
Self { scope: FeedScope::Search { query: query.into() }, page, viewer_id }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait FeedRepository: Send + Sync {
|
||||
async fn query(&self, q: &FeedQuery) -> Result<Paginated<FeedEntry>, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait SearchPort: Send + Sync {
|
||||
/// Full-text search over public thoughts, ranked by trigram similarity.
|
||||
async fn search_thoughts(
|
||||
&self,
|
||||
query: &str,
|
||||
page: &PageParams,
|
||||
viewer_id: Option<&UserId>,
|
||||
) -> Result<Paginated<FeedEntry>, DomainError>;
|
||||
|
||||
/// Search users by username or display_name, ranked by trigram similarity.
|
||||
async fn search_users(
|
||||
&self,
|
||||
query: &str,
|
||||
page: &PageParams,
|
||||
) -> Result<Paginated<User>, DomainError>;
|
||||
}
|
||||
|
||||
|
||||
#[async_trait]
|
||||
pub trait FederationSchedulerPort: Send + Sync {
|
||||
async fn schedule_actor_posts_fetch(
|
||||
&self,
|
||||
actor_ap_url: &str,
|
||||
outbox_url: &str,
|
||||
) -> Result<(), DomainError>;
|
||||
|
||||
async fn schedule_connections_fetch(
|
||||
&self,
|
||||
actor_ap_url: &str,
|
||||
collection_url: &str,
|
||||
connection_type: &str,
|
||||
page: u32,
|
||||
) -> Result<(), DomainError>;
|
||||
}
|
||||
964
crates/domain/src/testing.rs
Normal file
964
crates/domain/src/testing.rs
Normal file
@@ -0,0 +1,964 @@
|
||||
use crate::{
|
||||
errors::DomainError,
|
||||
events::DomainEvent,
|
||||
models::{
|
||||
api_key::ApiKey,
|
||||
feed::{FeedEntry, PageParams, Paginated, UserSummary},
|
||||
notification::Notification,
|
||||
remote_actor::RemoteActor,
|
||||
social::{Block, Boost, Follow, FollowState, Like},
|
||||
tag::Tag,
|
||||
thought::Thought,
|
||||
top_friend::TopFriend,
|
||||
user::User,
|
||||
},
|
||||
ports::*,
|
||||
value_objects::{
|
||||
ApiKeyId, Content, Email, NotificationId, PasswordHash, ThoughtId, UserId, Username,
|
||||
},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use chrono::Utc;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[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 notifications: Arc<Mutex<Vec<Notification>>>,
|
||||
pub events: Arc<Mutex<Vec<DomainEvent>>>,
|
||||
/// AP URL → UserId for remote actors (used by find_remote_actor_id / intern_remote_actor)
|
||||
pub actor_ap_ids: Arc<Mutex<HashMap<String, UserId>>>,
|
||||
/// ThoughtId → AP object URL (used by get_thought_ap_id)
|
||||
pub thought_ap_ids: Arc<Mutex<HashMap<ThoughtId, String>>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UserReader 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())
|
||||
}
|
||||
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())
|
||||
}
|
||||
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())
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
async fn list_paginated(&self, page: PageParams) -> Result<Paginated<UserSummary>, DomainError> {
|
||||
let all = self.list_with_stats().await?;
|
||||
let total = all.len() as i64;
|
||||
let start = page.offset() as usize;
|
||||
let items: Vec<UserSummary> = all.into_iter().skip(start).take(page.limit() as usize).collect();
|
||||
Ok(Paginated { items, total, page: page.page, per_page: page.per_page })
|
||||
}
|
||||
|
||||
async fn find_by_ids(&self, ids: &[UserId]) -> Result<HashMap<UserId, User>, DomainError> {
|
||||
let g = self.users.lock().unwrap();
|
||||
let map = g.iter()
|
||||
.filter(|u| ids.contains(&u.id))
|
||||
.map(|u| (u.id.clone(), u.clone()))
|
||||
.collect();
|
||||
Ok(map)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UserWriter for TestStore {
|
||||
async fn save(&self, user: &User) -> Result<(), DomainError> {
|
||||
let mut g = self.users.lock().unwrap();
|
||||
g.retain(|u| u.id != user.id);
|
||||
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)
|
||||
{
|
||||
u.display_name = display_name;
|
||||
u.bio = bio;
|
||||
u.avatar_url = avatar_url;
|
||||
u.header_url = header_url;
|
||||
u.custom_css = custom_css;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
g.push(t.clone());
|
||||
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())
|
||||
}
|
||||
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);
|
||||
}
|
||||
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)
|
||||
{
|
||||
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()
|
||||
.filter(|t| t.in_reply_to_id.as_ref() == Some(id) || &t.id == id)
|
||||
.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_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)
|
||||
{
|
||||
return Err(DomainError::Conflict("already liked".into()));
|
||||
}
|
||||
g.push(like.clone());
|
||||
Ok(())
|
||||
}
|
||||
async fn delete(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<(), DomainError> {
|
||||
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);
|
||||
}
|
||||
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 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)
|
||||
}
|
||||
}
|
||||
|
||||
#[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)
|
||||
{
|
||||
return Err(DomainError::Conflict("already boosted".into()));
|
||||
}
|
||||
g.push(boost.clone());
|
||||
Ok(())
|
||||
}
|
||||
async fn delete(&self, user_id: &UserId, thought_id: &ThoughtId) -> Result<(), DomainError> {
|
||||
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);
|
||||
}
|
||||
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 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)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EngagementRepository for TestStore {
|
||||
async fn get_for_thoughts(
|
||||
&self,
|
||||
thought_ids: &[ThoughtId],
|
||||
viewer_id: Option<&UserId>,
|
||||
) -> Result<HashMap<ThoughtId, (crate::models::feed::EngagementStats, Option<crate::models::feed::ViewerContext>)>, DomainError> {
|
||||
use crate::models::feed::{EngagementStats, ViewerContext};
|
||||
let likes = self.likes.lock().unwrap();
|
||||
let boosts = self.boosts.lock().unwrap();
|
||||
let thoughts = self.thoughts.lock().unwrap();
|
||||
|
||||
let mut result = HashMap::new();
|
||||
for tid in thought_ids {
|
||||
let like_count = likes.iter().filter(|l| &l.thought_id == tid).count() as i64;
|
||||
let boost_count = boosts.iter().filter(|b| &b.thought_id == tid).count() as i64;
|
||||
let reply_count = thoughts.iter().filter(|t| t.in_reply_to_id.as_ref() == Some(tid)).count() as i64;
|
||||
let viewer = viewer_id.map(|vid| ViewerContext {
|
||||
liked: likes.iter().any(|l| &l.thought_id == tid && &l.user_id == vid),
|
||||
boosted: boosts.iter().any(|b| &b.thought_id == tid && &b.user_id == vid),
|
||||
});
|
||||
result.insert(tid.clone(), (EngagementStats { like_count, boost_count, reply_count }, viewer));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
#[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.push(follow.clone());
|
||||
Ok(())
|
||||
}
|
||||
async fn delete(&self, follower_id: &UserId, following_id: &UserId) -> Result<(), DomainError> {
|
||||
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);
|
||||
}
|
||||
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 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_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()
|
||||
.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 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));
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
#[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(),
|
||||
};
|
||||
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 popular_tags(&self, _limit: usize) -> Result<Vec<(String, i64)>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
#[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())
|
||||
}
|
||||
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())
|
||||
}
|
||||
async fn delete(&self, id: &ApiKeyId, uid: &UserId) -> Result<(), DomainError> {
|
||||
self.api_keys
|
||||
.lock()
|
||||
.unwrap()
|
||||
.retain(|k| !(&k.id == id && &k.user_id == uid));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ApiKeyService for TestStore {
|
||||
async fn validate_key(&self, raw_key: &str) -> Result<Option<UserId>, DomainError> {
|
||||
use sha2::{Digest, Sha256};
|
||||
let hash = hex::encode(Sha256::digest(raw_key.as_bytes()));
|
||||
Ok(self
|
||||
.api_keys
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|k| k.key_hash == hash)
|
||||
.map(|k| k.user_id.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
async fn list_for_user(&self, _uid: &UserId) -> Result<Vec<(TopFriend, User)>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
#[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();
|
||||
let total = items.len() as i64;
|
||||
Ok(Paginated {
|
||||
items,
|
||||
total,
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
})
|
||||
}
|
||||
async fn count_unread(&self, uid: &UserId) -> Result<u64, DomainError> {
|
||||
Ok(self
|
||||
.notifications
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|n| &n.user_id == uid && !n.read)
|
||||
.count() as u64)
|
||||
}
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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 FederationLookupPort for TestStore {
|
||||
async fn lookup_actor(&self, _handle: &str) -> Result<RemoteActor, DomainError> {
|
||||
Err(DomainError::NotFound)
|
||||
}
|
||||
|
||||
async fn actor_json(&self, _user_id: &UserId) -> Result<String, DomainError> {
|
||||
Err(DomainError::NotFound)
|
||||
}
|
||||
|
||||
async fn followers_collection_json(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
_page: Option<u32>,
|
||||
) -> Result<String, DomainError> {
|
||||
Err(DomainError::NotFound)
|
||||
}
|
||||
|
||||
async fn following_collection_json(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
_page: Option<u32>,
|
||||
) -> Result<String, DomainError> {
|
||||
Err(DomainError::NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FederationFollowPort for TestStore {
|
||||
async fn follow_remote(
|
||||
&self,
|
||||
_local_user_id: &UserId,
|
||||
_handle: &str,
|
||||
) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn unfollow_remote(
|
||||
&self,
|
||||
_local_user_id: &UserId,
|
||||
_handle: &str,
|
||||
) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_remote_following(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
) -> Result<Vec<RemoteActor>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FederationFollowRequestPort for TestStore {
|
||||
async fn get_pending_followers(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
) -> Result<Vec<RemoteActor>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn accept_follow_request(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
_actor_url: &str,
|
||||
) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn reject_follow_request(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
_actor_url: &str,
|
||||
) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn get_remote_followers(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
) -> Result<Vec<RemoteActor>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn remove_remote_follower(
|
||||
&self,
|
||||
_user_id: &UserId,
|
||||
_actor_url: &str,
|
||||
) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FederationFetchPort for TestStore {
|
||||
async fn fetch_outbox_page(
|
||||
&self,
|
||||
_outbox_url: &str,
|
||||
_page: u32,
|
||||
) -> Result<Vec<crate::models::remote_note::RemoteNote>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn fetch_actor_urls_from_collection(
|
||||
&self,
|
||||
_collection_url: &str,
|
||||
) -> Result<Vec<String>, DomainError> {
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn resolve_actor_profiles(
|
||||
&self,
|
||||
_urls: Vec<String>,
|
||||
) -> Vec<crate::models::actor_connection_summary::ActorConnectionSummary> {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RemoteActorConnectionRepository for TestStore {
|
||||
async fn upsert_connections(
|
||||
&self,
|
||||
_actor_url: &str,
|
||||
_connection_type: &str,
|
||||
_page: u32,
|
||||
_actors: &[crate::models::actor_connection_summary::ActorConnectionSummary],
|
||||
) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn list_connections(
|
||||
&self,
|
||||
_actor_url: &str,
|
||||
_connection_type: &str,
|
||||
_page: u32,
|
||||
) -> Result<Vec<crate::models::actor_connection_summary::ActorConnectionSummary>, DomainError>
|
||||
{
|
||||
Ok(vec![])
|
||||
}
|
||||
|
||||
async fn connection_page_age(
|
||||
&self,
|
||||
_actor_url: &str,
|
||||
_connection_type: &str,
|
||||
_page: u32,
|
||||
) -> Result<Option<chrono::DateTime<chrono::Utc>>, DomainError> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl FeedRepository for TestStore {
|
||||
async fn query(&self, _q: &crate::ports::FeedQuery) -> Result<Paginated<FeedEntry>, DomainError> {
|
||||
Ok(Paginated {
|
||||
items: vec![],
|
||||
total: 0,
|
||||
page: 1,
|
||||
per_page: 20,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[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 FederationSchedulerPort for TestStore {
|
||||
async fn schedule_actor_posts_fetch(&self, _: &str, _: &str) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
async fn schedule_connections_fetch(
|
||||
&self,
|
||||
_: &str,
|
||||
_: &str,
|
||||
_: &str,
|
||||
_: u32,
|
||||
) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl EventPublisher for TestStore {
|
||||
async fn publish(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||
self.events.lock().unwrap().push(event.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoOpEventPublisher;
|
||||
#[async_trait]
|
||||
impl EventPublisher for NoOpEventPublisher {
|
||||
async fn publish(&self, _e: &DomainEvent) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct TestOutbox {
|
||||
pub entries: Arc<Mutex<Vec<DomainEvent>>>,
|
||||
}
|
||||
|
||||
impl TestOutbox {
|
||||
pub fn staged(&self) -> Vec<DomainEvent> {
|
||||
self.entries.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl OutboxWriter for TestOutbox {
|
||||
async fn append(&self, event: &DomainEvent) -> Result<(), DomainError> {
|
||||
self.entries.lock().unwrap().push(event.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NoOpOutboxWriter;
|
||||
#[async_trait]
|
||||
impl OutboxWriter for NoOpOutboxWriter {
|
||||
async fn append(&self, _e: &DomainEvent) -> Result<(), DomainError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod federation_port_tests {
|
||||
use super::*;
|
||||
use crate::value_objects::UserId;
|
||||
|
||||
fn uid() -> UserId {
|
||||
UserId::new()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_lookup_returns_not_found() {
|
||||
let store = TestStore::default();
|
||||
let err = store.lookup_actor("@alice@example.com").await.unwrap_err();
|
||||
assert!(matches!(err, DomainError::NotFound));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_follow_remote_is_noop_ok() {
|
||||
let store = TestStore::default();
|
||||
store
|
||||
.follow_remote(&uid(), "@alice@example.com")
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_actor_json_returns_not_found() {
|
||||
let store = TestStore::default();
|
||||
let err = store.actor_json(&UserId::new()).await.unwrap_err();
|
||||
assert!(matches!(err, DomainError::NotFound));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_fetch_outbox_returns_empty() {
|
||||
let store = TestStore::default();
|
||||
let notes = store
|
||||
.fetch_outbox_page("https://example.com/outbox", 1)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(notes.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_resolve_actor_profiles_returns_empty() {
|
||||
let store = TestStore::default();
|
||||
let result = store
|
||||
.resolve_actor_profiles(vec!["https://example.com/users/alice".into()])
|
||||
.await;
|
||||
assert!(result.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_store_fetch_collection_urls_returns_empty() {
|
||||
let store = TestStore::default();
|
||||
let urls = store
|
||||
.fetch_actor_urls_from_collection("https://example.com/users/alice/followers")
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(urls.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod search_tests {
|
||||
use super::*;
|
||||
use crate::models::feed::PageParams;
|
||||
|
||||
#[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();
|
||||
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();
|
||||
assert_eq!(result.total, 0);
|
||||
}
|
||||
}
|
||||
150
crates/domain/src/value_objects.rs
Normal file
150
crates/domain/src/value_objects.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
use crate::errors::DomainError;
|
||||
use uuid::Uuid;
|
||||
|
||||
const MAX_USERNAME_LENGTH: usize = 32;
|
||||
const MAX_EMAIL_LENGTH: usize = 255;
|
||||
const MAX_CONTENT_LENGTH: usize = 128;
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
impl Default for $name {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for $name {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
uuid_id!(UserId);
|
||||
uuid_id!(ThoughtId);
|
||||
uuid_id!(LikeId);
|
||||
uuid_id!(BoostId);
|
||||
uuid_id!(ApiKeyId);
|
||||
uuid_id!(NotificationId);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Username(String);
|
||||
impl Username {
|
||||
pub fn new(s: impl Into<String>) -> Result<Self, DomainError> {
|
||||
let s = s.into();
|
||||
if s.is_empty() || s.len() > MAX_USERNAME_LENGTH {
|
||||
return Err(DomainError::InvalidInput("username: 1-32 chars".into()));
|
||||
}
|
||||
if !s
|
||||
.chars()
|
||||
.all(|c| c.is_alphanumeric() || c == '_' || c == '.')
|
||||
{
|
||||
return Err(DomainError::InvalidInput(
|
||||
"username: alphanumeric, underscore, or dot only".into(),
|
||||
));
|
||||
}
|
||||
Ok(Self(s))
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Email(String);
|
||||
impl Email {
|
||||
pub fn new(s: impl Into<String>) -> Result<Self, DomainError> {
|
||||
let s = s.into().to_lowercase();
|
||||
if !s.contains('@') || s.len() > MAX_EMAIL_LENGTH {
|
||||
return Err(DomainError::InvalidInput("invalid email".into()));
|
||||
}
|
||||
Ok(Self(s))
|
||||
}
|
||||
pub fn from_trusted(s: String) -> Self {
|
||||
Self(s)
|
||||
}
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PasswordHash(pub String);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Content(String);
|
||||
impl Content {
|
||||
pub fn new_local(s: impl Into<String>) -> Result<Self, DomainError> {
|
||||
let s = s.into();
|
||||
if s.is_empty() || s.len() > MAX_CONTENT_LENGTH {
|
||||
return Err(DomainError::InvalidInput("content: 1-128 chars".into()));
|
||||
}
|
||||
Ok(Self(s))
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn username_rejects_empty() {
|
||||
assert!(Username::new("").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn username_rejects_too_long() {
|
||||
assert!(Username::new("a".repeat(33)).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn username_rejects_invalid_chars() {
|
||||
assert!(Username::new("hello world").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn username_accepts_valid() {
|
||||
assert!(Username::new("hello_123").is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn content_local_rejects_over_128() {
|
||||
assert!(Content::new_local("a".repeat(129)).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn content_local_accepts_128() {
|
||||
assert!(Content::new_local("a".repeat(128)).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn email_rejects_no_at() {
|
||||
assert!(Email::new("notanemail").is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user