Skip to content

Commit

Permalink
Fix spam endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
dcadenas committed Sep 18, 2024
1 parent 1336e16 commit 06ebde5
Show file tree
Hide file tree
Showing 5 changed files with 145 additions and 21 deletions.
93 changes: 93 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ gcloud-sdk = { version = "0.25.6", features = ["google-pubsub-v1"] }
log = "0.4.22"
metrics = "0.23.0"
metrics-exporter-prometheus = "0.15.3"
moka = { version = "0.12.8", features = ["future"] }
neo4rs = "0.8.0"
nonzero_ext = "0.3.0"
nostr-sdk = "0.33.0"
Expand Down
32 changes: 29 additions & 3 deletions src/http_server.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
mod router;
use crate::repo::Repo;
use crate::repo::RepoTrait;
use crate::repo::{Recommendation, Repo, RepoTrait};
use anyhow::{Context, Result};
use axum::Router;
use moka::future::Cache;
use router::create_router;
use std::net::SocketAddr;
use std::sync::Arc;
Expand All @@ -16,6 +16,32 @@ where
T: RepoTrait,
{
pub repo: Arc<T>,
pub recommendation_cache: Cache<String, Vec<Recommendation>>,
pub spammer_cache: Cache<String, bool>,
}

// Initialize AppState with caches
impl<T> AppState<T>
where
T: RepoTrait + 'static,
{
pub fn new(repo: Arc<T>) -> Self {
let recommendation_cache = Cache::builder()
.time_to_live(Duration::from_secs(86400)) // 1 day
.max_capacity(4000)
.build();

let spammer_cache = Cache::builder()
.time_to_live(Duration::from_secs(86400)) // 1 day
.max_capacity(4000)
.build();

Self {
repo,
recommendation_cache,
spammer_cache,
}
}
}

pub struct HttpServer;
Expand All @@ -26,7 +52,7 @@ impl HttpServer {
repo: Arc<Repo>,
cancellation_token: CancellationToken,
) -> Result<()> {
let state = Arc::new(AppState { repo }); // Create the shared state
let state = Arc::new(AppState::new(repo)); // Create the shared state
let router = create_router(state)?; // Pass the state to the router

start_http_server(task_tracker, http_port, router, cancellation_token);
Expand Down
34 changes: 19 additions & 15 deletions src/http_server/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,33 +52,37 @@ where
T: RepoTrait,
{
let public_key = PublicKey::from_hex(&pubkey).map_err(|_| ApiError::InvalidPublicKey)?;
cached_get_recommendations(state.repo.clone(), public_key)
let recommendations = state
.repo
.get_recommendations(&public_key)
.await
.map_err(ApiError::from)
}
.map_err(ApiError::from)?;

async fn cached_get_recommendations<T>(
repo: Arc<T>,
public_key: PublicKey,
) -> Result<Json<Vec<Recommendation>>, RepoError>
where
T: RepoTrait,
{
let recommendations = repo.get_recommendations(&public_key).await?;
Ok(Json(recommendations))
}

async fn maybe_spammer<T>(
State(state): State<Arc<AppState<T>>>, // Extract shared state with generic RepoTrait
axum::extract::Path(pubkey): axum::extract::Path<String>, // Extract pubkey from the path
) -> Result<Json<bool>, ApiError>
) -> Json<bool>
where
T: RepoTrait,
{
let public_key = PublicKey::from_hex(&pubkey).map_err(|_| ApiError::InvalidPublicKey)?;
let pagerank = state.repo.get_pagerank(&public_key).await?;
let Ok(public_key) = PublicKey::from_hex(&pubkey).map_err(|_| ApiError::InvalidPublicKey)
else {
return Json(false);
};

let Ok(pagerank) = state
.repo
.get_pagerank(&public_key)
.await
.map_err(ApiError::from)
else {
return Json(false);
};

Ok(Json(pagerank < 0.2))
Json(pagerank > 0.5)
}

async fn serve_root_page(_headers: HeaderMap) -> impl IntoResponse {
Expand Down
6 changes: 3 additions & 3 deletions src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ impl RepoTrait for Repo {
// Step 1: Get valid target nodes
MATCH (source:User {pubkey: $pubkey_val})
MATCH (target:User)
WHERE target.pagerank >= 0.2
WHERE target.pagerank >= 0.1
AND NOT EXISTS {
MATCH (source)-[:FOLLOWS]->(target)
}
Expand All @@ -473,7 +473,7 @@ impl RepoTrait for Repo {
sourceNodeFilter: [id(source)],
targetNodeFilter: targetNodeIds,
topK: 10, // Top 10 similar users
similarityCutoff: 0.1 // Only include nodes with similarity >= 0.1
similarityCutoff: 0.05 // Only include nodes with similarity >= 0.1
})
YIELD node1, node2, similarity
WITH gds.util.asNode(node2) AS targetUser, similarity
Expand Down Expand Up @@ -629,7 +629,7 @@ impl RepoError {
}
}

#[derive(Debug, Serialize)]
#[derive(Debug, Serialize, Clone)]
pub struct Recommendation {
pubkey: PublicKey,
friendly_id: String,
Expand Down

0 comments on commit 06ebde5

Please sign in to comment.