forked from
rocksky.app/rocksky
A decentralized music tracking and discovery platform built on AT Protocol 馃幍
1use std::env;
2
3use actix_web::{
4 get, post,
5 web::{self, Data},
6 App, HttpRequest, HttpResponse, HttpServer, Responder,
7};
8use anyhow::Error;
9use duckdb::Connection;
10use owo_colors::OwoColorize;
11use serde_json::json;
12use std::sync::{Arc, Mutex};
13
14use crate::{handlers::handle, subscriber::subscribe};
15
16// return json response
17#[get("/")]
18async fn index(_req: HttpRequest) -> HttpResponse {
19 HttpResponse::Ok().json(json!({
20 "server": "Rocksky Analytics Server",
21 "version": "0.1.0",
22 }))
23}
24
25#[post("/{method}")]
26async fn call_method(
27 data: web::Data<Arc<Mutex<Connection>>>,
28 mut payload: web::Payload,
29 req: HttpRequest,
30) -> Result<impl Responder, actix_web::Error> {
31 let method = req.match_info().get("method").unwrap_or("unknown");
32 tracing::info!(method = %method.bright_green(), "API call");
33
34 let conn = data.get_ref().clone();
35 handle(method, &mut payload, &req, conn)
36 .await
37 .map_err(actix_web::error::ErrorInternalServerError)
38}
39
40pub async fn serve(conn: Arc<Mutex<Connection>>) -> Result<(), Error> {
41 subscribe(conn.clone()).await?;
42
43 let host = env::var("ANALYTICS_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
44 let port = env::var("ANALYTICS_PORT").unwrap_or_else(|_| "7879".to_string());
45 let addr = format!("{}:{}", host, port);
46
47 let url = format!("http://{}", addr);
48 tracing::info!(url = %url.bright_green(), "Listening on");
49
50 let conn = conn.clone();
51 HttpServer::new(move || {
52 App::new()
53 .app_data(Data::new(conn.clone()))
54 .service(index)
55 .service(call_method)
56 })
57 .bind(&addr)?
58 .run()
59 .await
60 .map_err(Error::new)?;
61
62 Ok(())
63}