Compare commits
5 Commits
cf94b0ba6c
...
38b4774a63
| Author | SHA1 | Date | |
|---|---|---|---|
| 38b4774a63 | |||
| 9b47779e63 | |||
| eb7dbb0aee | |||
| a2cc4fba21 | |||
| 6eba91e699 |
@@ -10,6 +10,13 @@ BASE_URL=http://localhost:3000
|
||||
# Optional
|
||||
HOST=0.0.0.0
|
||||
PORT=3000
|
||||
|
||||
# CORS — comma-separated allowed origins, or * for permissive (default: *)
|
||||
CORS_ORIGINS=*
|
||||
# CORS_ORIGINS=https://your-nextjs-app.example.com
|
||||
|
||||
# Rate limiting — max requests per minute per IP (disabled by default)
|
||||
# RATE_LIMIT=60
|
||||
ALLOW_REGISTRATION=true # set to false to disable new sign-ups
|
||||
RUST_ENV=development # set to "production" to disable AP debug mode
|
||||
|
||||
|
||||
@@ -51,6 +51,21 @@ impl TagRepository for PgTagRepository {
|
||||
|
||||
Ok(Paginated { items: rows.into_iter().map(Thought::from).collect(), total, page: page.page, per_page: page.per_page })
|
||||
}
|
||||
|
||||
async fn popular_tags(&self, limit: usize) -> Result<Vec<(String, i64)>, DomainError> {
|
||||
sqlx::query_as::<_, (String, i64)>(
|
||||
"SELECT t.name, COUNT(tt.thought_id) AS thought_count
|
||||
FROM tags t
|
||||
JOIN thought_tags tt ON t.id = tt.tag_id
|
||||
GROUP BY t.id, t.name
|
||||
ORDER BY thought_count DESC
|
||||
LIMIT $1"
|
||||
)
|
||||
.bind(limit as i64)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -176,6 +176,13 @@ impl UserRepository for PgUserRepository {
|
||||
following_count: r.following_count,
|
||||
}).collect())
|
||||
}
|
||||
|
||||
async fn count(&self) -> Result<i64, DomainError> {
|
||||
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM users WHERE local = true")
|
||||
.fetch_one(&self.pool)
|
||||
.await
|
||||
.map_err(|e| DomainError::Internal(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -27,3 +27,5 @@ tower-http = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
tracing-subscriber = { workspace = true }
|
||||
dotenvy = { workspace = true }
|
||||
tower_governor = "0.8"
|
||||
http = "1"
|
||||
|
||||
@@ -8,6 +8,9 @@ pub struct Config {
|
||||
pub allow_registration: bool,
|
||||
/// true when RUST_ENV != "production" — enables AP debug mode
|
||||
pub debug: bool,
|
||||
pub host: String,
|
||||
pub cors_origins: String,
|
||||
pub rate_limit: Option<u32>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@@ -31,6 +34,9 @@ impl Config {
|
||||
debug: std::env::var("RUST_ENV")
|
||||
.map(|v| v != "production")
|
||||
.unwrap_or(true),
|
||||
host: std::env::var("HOST").unwrap_or_else(|_| "0.0.0.0".into()),
|
||||
cors_origins: std::env::var("CORS_ORIGINS").unwrap_or_else(|_| "*".into()),
|
||||
rate_limit: std::env::var("RATE_LIMIT").ok().and_then(|v| v.parse().ok()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
mod config;
|
||||
mod factory;
|
||||
|
||||
use tower_http::cors::CorsLayer;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use tower_http::cors::{AllowOrigin, CorsLayer};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
@@ -14,12 +16,63 @@ async fn main() {
|
||||
|
||||
let infra = factory::build(&cfg).await;
|
||||
|
||||
let app = presentation::routes::router(&infra.fed_config)
|
||||
.with_state(infra.state)
|
||||
.layer(CorsLayer::permissive());
|
||||
// CORS
|
||||
let cors = if cfg.cors_origins.trim() == "*" {
|
||||
CorsLayer::permissive()
|
||||
} else {
|
||||
let origins: Vec<http::HeaderValue> = cfg
|
||||
.cors_origins
|
||||
.split(',')
|
||||
.map(|o| o.trim())
|
||||
.filter_map(|o| o.parse().ok())
|
||||
.collect();
|
||||
CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::list(origins))
|
||||
.allow_methods(tower_http::cors::Any)
|
||||
.allow_headers(tower_http::cors::Any)
|
||||
};
|
||||
|
||||
let addr = format!("0.0.0.0:{}", cfg.port);
|
||||
let base = presentation::routes::router(&infra.fed_config)
|
||||
.with_state(infra.state)
|
||||
.layer(cors);
|
||||
|
||||
let addr = format!("{}:{}", cfg.host, cfg.port);
|
||||
tracing::info!("Listening on {addr}");
|
||||
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
|
||||
if let Some(rate_limit) = cfg.rate_limit {
|
||||
use tower_governor::{governor::GovernorConfigBuilder, GovernorLayer}; // crate: tower_governor
|
||||
|
||||
// per_millisecond sets the token replenishment interval.
|
||||
// rate_limit = max requests/minute => replenish every (60000 / rate_limit) ms.
|
||||
let ms = (60_000u64).saturating_div(rate_limit as u64).max(1);
|
||||
let governor_conf = Arc::new(
|
||||
GovernorConfigBuilder::default()
|
||||
.per_millisecond(ms)
|
||||
.burst_size(rate_limit)
|
||||
.use_headers()
|
||||
.finish()
|
||||
.expect("valid rate limit config"),
|
||||
);
|
||||
|
||||
let limiter = governor_conf.limiter().clone();
|
||||
tokio::spawn(async move {
|
||||
let mut interval =
|
||||
tokio::time::interval(std::time::Duration::from_secs(60));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
limiter.retain_recent();
|
||||
}
|
||||
});
|
||||
|
||||
let app = base.layer(GovernorLayer::new(governor_conf));
|
||||
axum::serve(
|
||||
listener,
|
||||
app.into_make_service_with_connect_info::<SocketAddr>(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
} else {
|
||||
axum::serve(listener, base).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,6 +47,7 @@ pub trait UserRepository: 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>;
|
||||
async fn list_with_stats(&self) -> Result<Vec<UserSummary>, DomainError>;
|
||||
async fn count(&self) -> Result<i64, DomainError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -100,6 +101,8 @@ pub trait TagRepository: Send + Sync {
|
||||
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]
|
||||
|
||||
@@ -62,6 +62,9 @@ pub struct TestStore {
|
||||
Ok(())
|
||||
}
|
||||
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_trait] impl ThoughtRepository for TestStore {
|
||||
@@ -211,6 +214,9 @@ pub struct TestStore {
|
||||
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 {
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
use axum::{extract::{Path, Query, State}, Json};
|
||||
use api_types::requests::{PaginationQuery, SearchQuery};
|
||||
use api_types::responses::ThoughtResponse;
|
||||
use application::use_cases::feed::{get_home_feed, get_public_feed, get_followers, get_following, get_user_feed, get_by_tag};
|
||||
use domain::models::feed::PageParams;
|
||||
use crate::{errors::ApiError, extractors::{AuthUser, OptionalAuthUser}, handlers::auth::to_user_response, state::AppState};
|
||||
use application::use_cases::profile::get_user_by_username;
|
||||
|
||||
fn to_thought_response(e: &domain::models::feed::FeedEntry) -> ThoughtResponse {
|
||||
ThoughtResponse {
|
||||
id: e.thought.id.as_uuid(),
|
||||
content: e.thought.content.as_str().to_string(),
|
||||
author: to_user_response(&e.author),
|
||||
in_reply_to_id: e.thought.in_reply_to_id.as_ref().map(|id| id.as_uuid()),
|
||||
visibility: e.thought.visibility.as_str().to_string(),
|
||||
content_warning: e.thought.content_warning.clone(),
|
||||
sensitive: e.thought.sensitive,
|
||||
like_count: e.like_count,
|
||||
boost_count: e.boost_count,
|
||||
reply_count: e.reply_count,
|
||||
liked_by_viewer: e.liked_by_viewer,
|
||||
boosted_by_viewer: e.boosted_by_viewer,
|
||||
created_at: e.thought.created_at,
|
||||
updated_at: e.thought.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get, path = "/feed",
|
||||
params(PaginationQuery),
|
||||
@@ -14,7 +34,12 @@ use application::use_cases::profile::get_user_by_username;
|
||||
pub async fn home_feed(State(s): State<AppState>, AuthUser(uid): AuthUser, Query(q): Query<PaginationQuery>) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let page = PageParams { page: q.page(), per_page: q.per_page() };
|
||||
let result = get_home_feed(&*s.feed, &*s.follows, &uid, page).await?;
|
||||
Ok(Json(serde_json::json!({ "items": result.items.iter().map(|e| e.thought.id.as_uuid()).collect::<Vec<_>>(), "total": result.total, "page": result.page })))
|
||||
Ok(Json(serde_json::json!({
|
||||
"items": result.items.iter().map(to_thought_response).collect::<Vec<_>>(),
|
||||
"total": result.total,
|
||||
"page": result.page,
|
||||
"per_page": result.per_page,
|
||||
})))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -25,7 +50,12 @@ pub async fn home_feed(State(s): State<AppState>, AuthUser(uid): AuthUser, Query
|
||||
pub async fn public_feed(State(s): State<AppState>, OptionalAuthUser(viewer): OptionalAuthUser, Query(q): Query<PaginationQuery>) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let page = PageParams { page: q.page(), per_page: q.per_page() };
|
||||
let result = get_public_feed(&*s.feed, viewer.as_ref(), page).await?;
|
||||
Ok(Json(serde_json::json!({ "items": result.items.iter().map(|e| e.thought.id.as_uuid()).collect::<Vec<_>>(), "total": result.total, "page": result.page })))
|
||||
Ok(Json(serde_json::json!({
|
||||
"items": result.items.iter().map(to_thought_response).collect::<Vec<_>>(),
|
||||
"total": result.total,
|
||||
"page": result.page,
|
||||
"per_page": result.per_page,
|
||||
})))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
@@ -99,15 +129,20 @@ pub async fn user_thoughts_handler(
|
||||
"total": result.total,
|
||||
"page": result.page,
|
||||
"per_page": result.per_page,
|
||||
"items": result.items.iter().map(|e| serde_json::json!({
|
||||
"id": e.thought.id.as_uuid(),
|
||||
"content": e.thought.content.as_str(),
|
||||
"visibility": e.thought.visibility.as_str(),
|
||||
"like_count": e.like_count,
|
||||
"boost_count": e.boost_count,
|
||||
"reply_count": e.reply_count,
|
||||
"created_at": e.thought.created_at,
|
||||
"updated_at": e.thought.updated_at,
|
||||
"items": result.items.iter().map(to_thought_response).collect::<Vec<_>>()
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn get_popular_tags(
|
||||
State(s): State<AppState>,
|
||||
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let limit: usize = params.get("limit").and_then(|v| v.parse().ok()).unwrap_or(20);
|
||||
let tags = s.tags.popular_tags(limit.min(100)).await?;
|
||||
Ok(Json(serde_json::json!({
|
||||
"tags": tags.iter().map(|(name, count)| serde_json::json!({
|
||||
"name": name,
|
||||
"thought_count": count,
|
||||
})).collect::<Vec<_>>()
|
||||
})))
|
||||
}
|
||||
@@ -135,8 +170,12 @@ pub async fn tag_thoughts_handler(
|
||||
"items": result.items.iter().map(|t| serde_json::json!({
|
||||
"id": t.id.as_uuid(),
|
||||
"content": t.content.as_str(),
|
||||
"in_reply_to_id": t.in_reply_to_id.as_ref().map(|id| id.as_uuid()),
|
||||
"visibility": t.visibility.as_str(),
|
||||
"content_warning": t.content_warning,
|
||||
"sensitive": t.sensitive,
|
||||
"created_at": t.created_at,
|
||||
"updated_at": t.updated_at,
|
||||
})).collect::<Vec<_>>()
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use axum::{extract::{Path, State}, Json};
|
||||
use axum::{extract::{Path, Query, State}, Json};
|
||||
use api_types::{requests::UpdateProfileRequest, responses::{ErrorResponse, UserResponse}};
|
||||
use application::use_cases::profile::{get_user_by_username, update_profile};
|
||||
use crate::{errors::ApiError, extractors::AuthUser, handlers::auth::to_user_response, state::AppState};
|
||||
@@ -43,3 +43,48 @@ pub async fn get_me(State(s): State<AppState>, AuthUser(uid): AuthUser) -> Resul
|
||||
let user = s.users.find_by_id(&uid).await?.ok_or(domain::errors::DomainError::NotFound)?;
|
||||
Ok(Json(to_user_response(&user)))
|
||||
}
|
||||
|
||||
pub async fn get_users(
|
||||
State(s): State<AppState>,
|
||||
Query(params): Query<std::collections::HashMap<String, String>>,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
use domain::models::feed::PageParams;
|
||||
let page = params.get("page").and_then(|v| v.parse::<u64>().ok()).unwrap_or(1);
|
||||
let per_page = params.get("per_page").and_then(|v| v.parse::<u64>().ok()).unwrap_or(20);
|
||||
let page_params = PageParams { page, per_page };
|
||||
|
||||
if let Some(q) = params.get("q").filter(|q| !q.trim().is_empty()) {
|
||||
let result = s.search.search_users(q, &page_params).await?;
|
||||
let users: Vec<_> = result.items.iter().map(|u| crate::handlers::auth::to_user_response(u)).collect();
|
||||
return Ok(Json(serde_json::json!({
|
||||
"items": users, "total": result.total, "page": result.page, "per_page": result.per_page
|
||||
})));
|
||||
}
|
||||
|
||||
let all = s.users.list_with_stats().await?;
|
||||
let total = all.len() as i64;
|
||||
let start = ((page - 1) * per_page) as usize;
|
||||
let items: Vec<_> = all.into_iter()
|
||||
.skip(start).take(per_page as usize)
|
||||
.map(|u| serde_json::json!({
|
||||
"id": u.id.as_uuid(),
|
||||
"username": u.username,
|
||||
"display_name": u.display_name,
|
||||
"avatar_url": u.avatar_url,
|
||||
"bio": u.bio,
|
||||
"thought_count": u.thought_count,
|
||||
"follower_count": u.follower_count,
|
||||
"following_count": u.following_count,
|
||||
}))
|
||||
.collect();
|
||||
Ok(Json(serde_json::json!({
|
||||
"items": items, "total": total, "page": page, "per_page": per_page
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn get_user_count(
|
||||
State(s): State<AppState>,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let count = s.users.count().await?;
|
||||
Ok(Json(serde_json::json!({ "count": count })))
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ pub fn router(fed_config: &ApFederationConfig) -> Router<AppState> {
|
||||
.route("/auth/register", post(auth::post_register))
|
||||
.route("/auth/login", post(auth::post_login))
|
||||
// users — static paths before parameterised
|
||||
.route("/users", get(users::get_users))
|
||||
.route("/users/count", get(users::get_user_count))
|
||||
.route("/users/me", get(users::get_me).patch(users::patch_profile))
|
||||
.route("/users/me/top-friends", put(social::put_top_friends))
|
||||
.route("/users/{username}/top-friends", get(social::get_top_friends_handler))
|
||||
@@ -56,7 +58,10 @@ pub fn router(fed_config: &ApFederationConfig) -> Router<AppState> {
|
||||
.route("/feed", get(feed::home_feed))
|
||||
.route("/feed/public", get(feed::public_feed))
|
||||
.route("/search", get(feed::search_handler))
|
||||
.route("/users/{username}/follower-list", get(feed::get_followers_handler))
|
||||
.route("/users/{username}/following-list", get(feed::get_following_handler))
|
||||
.route("/users/{username}/thoughts", get(feed::user_thoughts_handler))
|
||||
.route("/tags/popular", get(feed::get_popular_tags))
|
||||
.route("/tags/{name}", get(feed::tag_thoughts_handler))
|
||||
// notifications
|
||||
.route("/notifications", get(notifications::list_notifications))
|
||||
|
||||
Reference in New Issue
Block a user