buzzrelay/src/db.rs

89 lines
2.8 KiB
Rust
Raw Normal View History

2022-12-20 02:40:51 +00:00
use std::{sync::Arc, time::Instant};
use metrics::histogram;
2022-12-19 20:20:13 +00:00
use tokio_postgres::{Client, Error, NoTls, Statement};
2022-12-19 23:15:00 +00:00
2022-12-19 20:20:13 +00:00
const CREATE_SCHEMA_COMMANDS: &[&str] = &[
2022-12-20 02:48:14 +00:00
"CREATE TABLE IF NOT EXISTS follows (id TEXT NOT NULL, inbox TEXT NOT NULL, actor TEXT NOT NULL, UNIQUE (inbox, actor))",
2022-12-20 00:16:53 +00:00
"CREATE INDEX IF NOT EXISTS follows_actor ON follows (actor) INCLUDE (inbox)",
2022-12-19 20:20:13 +00:00
];
#[derive(Clone)]
pub struct Database {
inner: Arc<DatabaseInner>,
}
struct DatabaseInner {
client: Client,
add_follow: Statement,
del_follow: Statement,
get_following_inboxes: Statement,
}
impl Database {
pub async fn connect(conn_str: &str) -> Self {
let (client, connection) = tokio_postgres::connect(conn_str, NoTls)
.await
.unwrap();
tokio::spawn(async move {
if let Err(e) = connection.await {
tracing::error!("postgresql: {}", e);
}
});
for command in CREATE_SCHEMA_COMMANDS {
client.execute(*command, &[])
.await
.unwrap();
}
let add_follow = client.prepare("INSERT INTO follows (id, inbox, actor) VALUES ($1, $2, $3)")
.await
.unwrap();
let del_follow = client.prepare("DELETE FROM follows WHERE id=$1 AND actor=$2")
.await
.unwrap();
let get_following_inboxes = client.prepare("SELECT DISTINCT inbox FROM follows WHERE actor=$1")
.await
.unwrap();
Database {
inner: Arc::new(DatabaseInner {
client,
add_follow,
del_follow,
get_following_inboxes,
}),
}
}
pub async fn add_follow(&self, id: &str, inbox: &str, actor: &str) -> Result<(), Error> {
2022-12-20 02:40:51 +00:00
let t1 = Instant::now();
2022-12-19 20:20:13 +00:00
self.inner.client.execute(&self.inner.add_follow, &[&id, &inbox, &actor])
.await?;
2022-12-20 02:40:51 +00:00
let t2 = Instant::now();
histogram!("sql", t2 - t1, "query" => "add_follow");
2022-12-19 20:20:13 +00:00
Ok(())
}
pub async fn del_follow(&self, id: &str, actor: &str) -> Result<(), Error> {
2022-12-20 02:40:51 +00:00
let t1 = Instant::now();
2022-12-19 20:20:13 +00:00
self.inner.client.execute(&self.inner.del_follow, &[&id, &actor])
.await?;
2022-12-20 02:40:51 +00:00
let t2 = Instant::now();
histogram!("sql", t2 - t1, "query" => "del_follow");
2022-12-19 20:20:13 +00:00
Ok(())
}
pub async fn get_following_inboxes(&self, actor: &str) -> Result<impl Iterator<Item = String>, Error> {
2022-12-20 02:40:51 +00:00
let t1 = Instant::now();
2022-12-19 20:20:13 +00:00
let rows = self.inner.client.query(&self.inner.get_following_inboxes, &[&actor])
.await?;
2022-12-20 02:40:51 +00:00
let t2 = Instant::now();
histogram!("sql", t2 - t1, "query" => "get_following_inboxes");
2022-12-19 20:20:13 +00:00
Ok(rows.into_iter()
.map(|row| row.get(0))
)
}
}