2021-12-11 22:43:41 -05:00
|
|
|
//! Server process
|
2021-12-05 21:28:02 -05:00
|
|
|
use futures::SinkExt;
|
2021-12-05 17:53:26 -05:00
|
|
|
use futures::StreamExt;
|
2022-01-03 18:42:24 -05:00
|
|
|
use hyper::header::ACCEPT;
|
2022-01-01 09:08:54 -05:00
|
|
|
use hyper::service::{make_service_fn, service_fn};
|
|
|
|
use hyper::upgrade::Upgraded;
|
|
|
|
use hyper::{
|
|
|
|
header, server::conn::AddrStream, upgrade, Body, Request, Response, Server, StatusCode,
|
|
|
|
};
|
2021-12-05 17:53:26 -05:00
|
|
|
use log::*;
|
2021-12-05 19:14:14 -05:00
|
|
|
use nostr_rs_relay::close::Close;
|
2022-02-12 17:19:10 -05:00
|
|
|
use nostr_rs_relay::close::CloseCmd;
|
2021-12-29 23:13:02 -05:00
|
|
|
use nostr_rs_relay::config;
|
2021-12-05 17:53:26 -05:00
|
|
|
use nostr_rs_relay::conn;
|
2021-12-11 16:48:59 -05:00
|
|
|
use nostr_rs_relay::db;
|
2022-02-13 10:35:54 -05:00
|
|
|
use nostr_rs_relay::db::SubmittedEvent;
|
2021-12-05 17:53:26 -05:00
|
|
|
use nostr_rs_relay::error::{Error, Result};
|
|
|
|
use nostr_rs_relay::event::Event;
|
2022-02-12 17:19:10 -05:00
|
|
|
use nostr_rs_relay::event::EventCmd;
|
2022-01-05 10:10:44 -05:00
|
|
|
use nostr_rs_relay::info::RelayInfo;
|
2022-02-12 10:29:25 -05:00
|
|
|
use nostr_rs_relay::nip05;
|
2022-02-12 17:19:10 -05:00
|
|
|
use nostr_rs_relay::subscription::Subscription;
|
|
|
|
use serde::{Deserialize, Serialize};
|
2022-02-26 18:34:58 -05:00
|
|
|
use serde_json::json;
|
2021-12-11 16:48:59 -05:00
|
|
|
use std::collections::HashMap;
|
2022-01-01 09:08:54 -05:00
|
|
|
use std::convert::Infallible;
|
2021-12-31 12:51:57 -05:00
|
|
|
use std::env;
|
2022-01-01 09:08:54 -05:00
|
|
|
use std::net::SocketAddr;
|
2021-12-31 12:51:57 -05:00
|
|
|
use std::path::Path;
|
2022-02-12 17:57:26 -05:00
|
|
|
use std::time::Duration;
|
|
|
|
use std::time::Instant;
|
2021-12-05 17:53:26 -05:00
|
|
|
use tokio::runtime::Builder;
|
2022-02-12 10:29:25 -05:00
|
|
|
use tokio::sync::broadcast::{self, Receiver, Sender};
|
2021-12-05 17:53:26 -05:00
|
|
|
use tokio::sync::mpsc;
|
2021-12-11 16:48:59 -05:00
|
|
|
use tokio::sync::oneshot;
|
2022-01-01 09:08:54 -05:00
|
|
|
use tokio_tungstenite::WebSocketStream;
|
2022-02-12 17:19:10 -05:00
|
|
|
use tungstenite::error::Error as WsError;
|
2022-01-01 09:08:54 -05:00
|
|
|
use tungstenite::handshake;
|
2022-02-12 17:19:10 -05:00
|
|
|
use tungstenite::protocol::Message;
|
2021-12-19 17:26:32 -05:00
|
|
|
use tungstenite::protocol::WebSocketConfig;
|
2021-12-05 17:53:26 -05:00
|
|
|
|
2022-01-05 17:41:12 -05:00
|
|
|
/// Return a requested DB name from command line arguments.
|
2021-12-31 12:51:57 -05:00
|
|
|
fn db_from_args(args: Vec<String>) -> Option<String> {
|
2021-12-31 16:19:35 -05:00
|
|
|
if args.len() == 3 && args.get(1) == Some(&"--db".to_owned()) {
|
|
|
|
return args.get(2).map(|x| x.to_owned());
|
2021-12-31 12:51:57 -05:00
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
2022-01-05 17:41:12 -05:00
|
|
|
|
|
|
|
/// Handle arbitrary HTTP requests, including for WebSocket upgrades.
|
2022-01-01 09:08:54 -05:00
|
|
|
async fn handle_web_request(
|
|
|
|
mut request: Request<Body>,
|
2022-01-25 21:39:24 -05:00
|
|
|
pool: db::SqlitePool,
|
2022-01-01 09:08:54 -05:00
|
|
|
remote_addr: SocketAddr,
|
|
|
|
broadcast: Sender<Event>,
|
2022-02-13 10:35:54 -05:00
|
|
|
event_tx: tokio::sync::mpsc::Sender<SubmittedEvent>,
|
2022-01-01 09:08:54 -05:00
|
|
|
shutdown: Receiver<()>,
|
|
|
|
) -> Result<Response<Body>, Infallible> {
|
|
|
|
match (
|
|
|
|
request.uri().path(),
|
|
|
|
request.headers().contains_key(header::UPGRADE),
|
|
|
|
) {
|
2022-01-03 18:42:24 -05:00
|
|
|
// Request for / as websocket
|
2022-01-01 09:08:54 -05:00
|
|
|
("/", true) => {
|
2022-02-26 18:34:58 -05:00
|
|
|
trace!("websocket with upgrade request");
|
2022-01-01 09:08:54 -05:00
|
|
|
//assume request is a handshake, so create the handshake response
|
|
|
|
let response = match handshake::server::create_response_with_body(&request, || {
|
|
|
|
Body::empty()
|
|
|
|
}) {
|
|
|
|
Ok(response) => {
|
|
|
|
//in case the handshake response creation succeeds,
|
|
|
|
//spawn a task to handle the websocket connection
|
|
|
|
tokio::spawn(async move {
|
|
|
|
//using the hyper feature of upgrading a connection
|
|
|
|
match upgrade::on(&mut request).await {
|
|
|
|
//if successfully upgraded
|
|
|
|
Ok(upgraded) => {
|
2022-01-05 17:41:12 -05:00
|
|
|
// set WebSocket configuration options
|
|
|
|
let mut config = WebSocketConfig::default();
|
|
|
|
{
|
|
|
|
let settings = config::SETTINGS.read().unwrap();
|
|
|
|
config.max_message_size = settings.limits.max_ws_message_bytes;
|
|
|
|
config.max_frame_size = settings.limits.max_ws_frame_bytes;
|
|
|
|
}
|
2022-01-01 09:08:54 -05:00
|
|
|
//create a websocket stream from the upgraded object
|
|
|
|
let ws_stream = WebSocketStream::from_raw_socket(
|
|
|
|
//pass the upgraded object
|
|
|
|
//as the base layer stream of the Websocket
|
|
|
|
upgraded,
|
|
|
|
tokio_tungstenite::tungstenite::protocol::Role::Server,
|
2022-01-05 17:41:12 -05:00
|
|
|
Some(config),
|
2022-01-01 09:08:54 -05:00
|
|
|
)
|
|
|
|
.await;
|
2022-01-25 21:39:24 -05:00
|
|
|
|
2022-01-01 09:08:54 -05:00
|
|
|
tokio::spawn(nostr_server(
|
2022-01-25 21:39:24 -05:00
|
|
|
pool, ws_stream, broadcast, event_tx, shutdown,
|
2022-01-01 09:08:54 -05:00
|
|
|
));
|
|
|
|
}
|
|
|
|
Err(e) => println!(
|
|
|
|
"error when trying to upgrade connection \
|
|
|
|
from address {} to websocket connection. \
|
|
|
|
Error is: {}",
|
|
|
|
remote_addr, e
|
|
|
|
),
|
|
|
|
}
|
|
|
|
});
|
|
|
|
//return the response to the handshake request
|
|
|
|
response
|
|
|
|
}
|
|
|
|
Err(error) => {
|
|
|
|
warn!("websocket response failed");
|
|
|
|
let mut res =
|
|
|
|
Response::new(Body::from(format!("Failed to create websocket: {}", error)));
|
|
|
|
*res.status_mut() = StatusCode::BAD_REQUEST;
|
|
|
|
return Ok(res);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
Ok::<_, Infallible>(response)
|
|
|
|
}
|
2022-01-03 18:42:24 -05:00
|
|
|
// Request for Relay info
|
2022-01-01 09:08:54 -05:00
|
|
|
("/", false) => {
|
|
|
|
// handle request at root with no upgrade header
|
2022-01-03 18:42:24 -05:00
|
|
|
// Check if this is a nostr server info request
|
|
|
|
let accept_header = &request.headers().get(ACCEPT);
|
|
|
|
// check if application/nostr+json is included
|
|
|
|
if let Some(media_types) = accept_header {
|
|
|
|
if let Ok(mt_str) = media_types.to_str() {
|
|
|
|
if mt_str.contains("application/nostr+json") {
|
|
|
|
let config = config::SETTINGS.read().unwrap();
|
|
|
|
// build a relay info response
|
|
|
|
debug!("Responding to server info request");
|
2022-01-05 10:10:44 -05:00
|
|
|
let rinfo = RelayInfo::from(config.info.clone());
|
|
|
|
let b = Body::from(serde_json::to_string_pretty(&rinfo).unwrap());
|
2022-01-03 18:42:24 -05:00
|
|
|
return Ok(Response::builder()
|
|
|
|
.status(200)
|
|
|
|
.header("Content-Type", "application/nostr+json")
|
|
|
|
.body(b)
|
|
|
|
.unwrap());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-01-03 22:03:30 -05:00
|
|
|
Ok(Response::new(Body::from(
|
2022-01-03 18:42:24 -05:00
|
|
|
"Please use a Nostr client to connect.",
|
2022-01-03 22:03:30 -05:00
|
|
|
)))
|
2022-01-01 09:08:54 -05:00
|
|
|
}
|
|
|
|
(_, _) => {
|
|
|
|
//handle any other url
|
|
|
|
Ok(Response::builder()
|
|
|
|
.status(StatusCode::NOT_FOUND)
|
|
|
|
.body(Body::from("Nothing here."))
|
|
|
|
.unwrap())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn shutdown_signal() {
|
|
|
|
// Wait for the CTRL+C signal
|
|
|
|
tokio::signal::ctrl_c()
|
|
|
|
.await
|
|
|
|
.expect("failed to install CTRL+C signal handler");
|
|
|
|
}
|
2021-12-31 12:51:57 -05:00
|
|
|
|
2021-12-05 17:53:26 -05:00
|
|
|
/// Start running a Nostr relay server.
|
|
|
|
fn main() -> Result<(), Error> {
|
2021-12-29 23:13:02 -05:00
|
|
|
// setup logger
|
2021-12-05 17:53:26 -05:00
|
|
|
let _ = env_logger::try_init();
|
2021-12-31 12:51:57 -05:00
|
|
|
// get database directory from args
|
|
|
|
let args: Vec<String> = env::args().collect();
|
|
|
|
let db_dir: Option<String> = db_from_args(args);
|
2021-12-29 23:13:02 -05:00
|
|
|
{
|
2021-12-29 23:47:31 -05:00
|
|
|
let mut settings = config::SETTINGS.write().unwrap();
|
2021-12-29 23:13:02 -05:00
|
|
|
// replace default settings with those read from config.toml
|
2021-12-31 12:51:57 -05:00
|
|
|
let mut c = config::Settings::new();
|
|
|
|
// update with database location
|
|
|
|
if let Some(db) = db_dir {
|
2021-12-31 16:19:35 -05:00
|
|
|
c.database.data_directory = db;
|
2021-12-31 12:51:57 -05:00
|
|
|
}
|
2021-12-29 23:13:02 -05:00
|
|
|
*settings = c;
|
|
|
|
}
|
2022-01-01 09:08:54 -05:00
|
|
|
|
2022-02-12 10:29:25 -05:00
|
|
|
let settings = config::SETTINGS.read().unwrap();
|
|
|
|
trace!("Config: {:?}", settings);
|
2021-12-31 12:51:57 -05:00
|
|
|
// do some config validation.
|
2022-02-12 10:29:25 -05:00
|
|
|
if !Path::new(&settings.database.data_directory).is_dir() {
|
2021-12-31 12:51:57 -05:00
|
|
|
error!("Database directory does not exist");
|
|
|
|
return Err(Error::DatabaseDirError);
|
|
|
|
}
|
2022-02-12 10:29:25 -05:00
|
|
|
let addr = format!(
|
|
|
|
"{}:{}",
|
|
|
|
settings.network.address.trim(),
|
|
|
|
settings.network.port
|
|
|
|
);
|
2022-01-01 09:08:54 -05:00
|
|
|
let socket_addr = addr.parse().expect("listening address not valid");
|
2022-02-12 10:29:25 -05:00
|
|
|
// address whitelisting settings
|
|
|
|
if let Some(addr_whitelist) = &settings.authorization.pubkey_whitelist {
|
2022-01-26 22:39:03 -05:00
|
|
|
info!(
|
|
|
|
"Event publishing restricted to {} pubkey(s)",
|
|
|
|
addr_whitelist.len()
|
|
|
|
);
|
|
|
|
}
|
2022-02-12 10:29:25 -05:00
|
|
|
// check if NIP-05 enforced user verification is on
|
|
|
|
if settings.verified_users.is_active() {
|
|
|
|
info!(
|
|
|
|
"NIP-05 user verification mode:{:?}",
|
|
|
|
settings.verified_users.mode
|
|
|
|
);
|
|
|
|
if let Some(d) = settings.verified_users.verify_update_duration() {
|
|
|
|
info!("NIP-05 check user verification every: {:?}", d);
|
|
|
|
}
|
|
|
|
if let Some(d) = settings.verified_users.verify_expiration_duration() {
|
|
|
|
info!("NIP-05 user verification expires after: {:?}", d);
|
|
|
|
}
|
|
|
|
if let Some(wl) = &settings.verified_users.domain_whitelist {
|
|
|
|
info!("NIP-05 domain whitelist: {:?}", wl);
|
|
|
|
}
|
|
|
|
if let Some(bl) = &settings.verified_users.domain_blacklist {
|
|
|
|
info!("NIP-05 domain blacklist: {:?}", bl);
|
|
|
|
}
|
|
|
|
}
|
2021-12-05 17:53:26 -05:00
|
|
|
// configure tokio runtime
|
|
|
|
let rt = Builder::new_multi_thread()
|
|
|
|
.enable_all()
|
|
|
|
.thread_name("tokio-ws")
|
|
|
|
.build()
|
|
|
|
.unwrap();
|
|
|
|
// start tokio
|
|
|
|
rt.block_on(async {
|
2021-12-29 23:47:31 -05:00
|
|
|
let settings = config::SETTINGS.read().unwrap();
|
2022-01-01 09:08:54 -05:00
|
|
|
info!("listening on: {}", socket_addr);
|
2021-12-11 22:43:41 -05:00
|
|
|
// all client-submitted valid events are broadcast to every
|
|
|
|
// other client on this channel. This should be large enough
|
|
|
|
// to accomodate slower readers (messages are dropped if
|
|
|
|
// clients can not keep up).
|
2021-12-29 23:13:02 -05:00
|
|
|
let (bcast_tx, _) = broadcast::channel::<Event>(settings.limits.broadcast_buffer);
|
2021-12-11 22:43:41 -05:00
|
|
|
// validated events that need to be persisted are sent to the
|
|
|
|
// database on via this channel.
|
2022-02-13 10:35:54 -05:00
|
|
|
let (event_tx, event_rx) =
|
|
|
|
mpsc::channel::<SubmittedEvent>(settings.limits.event_persist_buffer);
|
2021-12-11 22:43:41 -05:00
|
|
|
// establish a channel for letting all threads now about a
|
|
|
|
// requested server shutdown.
|
2022-02-12 10:29:25 -05:00
|
|
|
let (invoke_shutdown, shutdown_listen) = broadcast::channel::<()>(1);
|
|
|
|
// create a channel for sending any new metadata event. These
|
|
|
|
// will get processed relatively slowly (a potentially
|
|
|
|
// multi-second blocking HTTP call) on a single thread, so we
|
|
|
|
// buffer requests on the channel. No harm in dropping events
|
|
|
|
// here, since we are protecting against DoS. This can make
|
|
|
|
// it difficult to setup initial metadata in bulk, since
|
|
|
|
// overwhelming this will drop events and won't register
|
|
|
|
// metadata events.
|
|
|
|
let (metadata_tx, metadata_rx) = broadcast::channel::<Event>(4096);
|
2022-01-26 22:39:03 -05:00
|
|
|
// start the database writer thread. Give it a channel for
|
|
|
|
// writing events, and for publishing events that have been
|
|
|
|
// written (to all connected clients).
|
2022-02-12 10:29:25 -05:00
|
|
|
db::db_writer(
|
|
|
|
event_rx,
|
|
|
|
bcast_tx.clone(),
|
|
|
|
metadata_tx.clone(),
|
|
|
|
shutdown_listen,
|
|
|
|
)
|
|
|
|
.await;
|
2022-01-26 22:39:03 -05:00
|
|
|
info!("db writer created");
|
2022-02-12 10:29:25 -05:00
|
|
|
|
|
|
|
// create a nip-05 verifier thread
|
|
|
|
let verifier_opt = nip05::Verifier::new(metadata_rx, bcast_tx.clone());
|
|
|
|
if let Ok(mut v) = verifier_opt {
|
|
|
|
if settings.verified_users.is_active() {
|
|
|
|
tokio::task::spawn(async move {
|
|
|
|
info!("starting up NIP-05 verifier...");
|
|
|
|
v.run().await;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2022-01-01 09:08:54 -05:00
|
|
|
// // listen for ctrl-c interruupts
|
2022-01-26 22:39:03 -05:00
|
|
|
let ctrl_c_shutdown = invoke_shutdown.clone();
|
2021-12-11 16:48:59 -05:00
|
|
|
tokio::spawn(async move {
|
|
|
|
tokio::signal::ctrl_c().await.unwrap();
|
2021-12-12 11:03:28 -05:00
|
|
|
info!("shutting down due to SIGINT");
|
2021-12-11 22:43:41 -05:00
|
|
|
ctrl_c_shutdown.send(()).ok();
|
2021-12-11 16:48:59 -05:00
|
|
|
});
|
2022-01-26 22:39:03 -05:00
|
|
|
// build a connection pool for sqlite connections
|
2022-02-12 10:29:25 -05:00
|
|
|
let pool = db::build_pool(
|
|
|
|
"client query",
|
|
|
|
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY
|
|
|
|
| rusqlite::OpenFlags::SQLITE_OPEN_SHARED_CACHE,
|
|
|
|
settings.database.min_conn,
|
|
|
|
settings.database.max_conn,
|
|
|
|
true,
|
|
|
|
);
|
2022-01-01 09:08:54 -05:00
|
|
|
// A `Service` is needed for every connection, so this
|
|
|
|
// creates one from our `handle_request` function.
|
|
|
|
let make_svc = make_service_fn(|conn: &AddrStream| {
|
2022-01-25 21:39:24 -05:00
|
|
|
let svc_pool = pool.clone();
|
2022-01-01 09:08:54 -05:00
|
|
|
let remote_addr = conn.remote_addr();
|
|
|
|
let bcast = bcast_tx.clone();
|
|
|
|
let event = event_tx.clone();
|
|
|
|
let stop = invoke_shutdown.clone();
|
|
|
|
async move {
|
|
|
|
// service_fn converts our function into a `Service`
|
|
|
|
Ok::<_, Infallible>(service_fn(move |request: Request<Body>| {
|
|
|
|
handle_web_request(
|
|
|
|
request,
|
2022-01-25 21:39:24 -05:00
|
|
|
svc_pool.clone(),
|
2022-01-01 09:08:54 -05:00
|
|
|
remote_addr,
|
|
|
|
bcast.clone(),
|
|
|
|
event.clone(),
|
|
|
|
stop.subscribe(),
|
|
|
|
)
|
|
|
|
}))
|
2021-12-11 16:48:59 -05:00
|
|
|
}
|
2022-01-01 09:08:54 -05:00
|
|
|
});
|
|
|
|
let server = Server::bind(&socket_addr)
|
|
|
|
.serve(make_svc)
|
|
|
|
.with_graceful_shutdown(shutdown_signal());
|
|
|
|
// run hyper
|
|
|
|
if let Err(e) = server.await {
|
|
|
|
eprintln!("server error: {}", e);
|
2021-12-05 17:53:26 -05:00
|
|
|
}
|
2022-01-01 09:08:54 -05:00
|
|
|
// our code
|
2021-12-05 17:53:26 -05:00
|
|
|
});
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-02-12 17:19:10 -05:00
|
|
|
/// Nostr protocol messages from a client
|
|
|
|
#[derive(Deserialize, Serialize, Clone, PartialEq, Debug)]
|
|
|
|
#[serde(untagged)]
|
|
|
|
pub enum NostrMessage {
|
|
|
|
/// An `EVENT` message
|
|
|
|
EventMsg(EventCmd),
|
|
|
|
/// A `REQ` message
|
|
|
|
SubMsg(Subscription),
|
|
|
|
/// A `CLOSE` message
|
|
|
|
CloseMsg(CloseCmd),
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Convert Message to NostrMessage
|
|
|
|
fn convert_to_msg(msg: String) -> Result<NostrMessage> {
|
|
|
|
let config = config::SETTINGS.read().unwrap();
|
|
|
|
let parsed_res: Result<NostrMessage> = serde_json::from_str(&msg).map_err(|e| e.into());
|
|
|
|
match parsed_res {
|
|
|
|
Ok(m) => {
|
|
|
|
if let NostrMessage::EventMsg(_) = m {
|
|
|
|
if let Some(max_size) = config.limits.max_event_bytes {
|
|
|
|
// check length, ensure that some max size is set.
|
|
|
|
if msg.len() > max_size && max_size > 0 {
|
|
|
|
return Err(Error::EventMaxLengthError(msg.len()));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(m)
|
|
|
|
}
|
|
|
|
Err(e) => {
|
|
|
|
debug!("proto parse error: {:?}", e);
|
|
|
|
debug!("parse error on message: {}", msg.trim());
|
|
|
|
Err(Error::ProtoParseError)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-26 18:34:58 -05:00
|
|
|
/// Turn a string into a NOTICE message ready to send over a WebSocket
|
|
|
|
fn make_notice_message(msg: &str) -> Message {
|
|
|
|
Message::text(json!(["NOTICE", msg]).to_string())
|
|
|
|
}
|
|
|
|
|
2021-12-11 22:43:41 -05:00
|
|
|
/// Handle new client connections. This runs through an event loop
|
|
|
|
/// for all client communication.
|
2021-12-05 17:53:26 -05:00
|
|
|
async fn nostr_server(
|
2022-01-25 21:39:24 -05:00
|
|
|
pool: db::SqlitePool,
|
2022-02-12 17:19:10 -05:00
|
|
|
mut ws_stream: WebSocketStream<Upgraded>,
|
2021-12-05 17:53:26 -05:00
|
|
|
broadcast: Sender<Event>,
|
2022-02-13 10:35:54 -05:00
|
|
|
event_tx: mpsc::Sender<SubmittedEvent>,
|
2021-12-11 16:48:59 -05:00
|
|
|
mut shutdown: Receiver<()>,
|
2021-12-05 17:53:26 -05:00
|
|
|
) {
|
|
|
|
// get a broadcast channel for clients to communicate on
|
2021-12-05 21:28:02 -05:00
|
|
|
let mut bcast_rx = broadcast.subscribe();
|
2021-12-05 17:53:26 -05:00
|
|
|
// Track internal client state
|
2021-12-05 19:14:14 -05:00
|
|
|
let mut conn = conn::ClientConn::new();
|
2021-12-11 16:48:59 -05:00
|
|
|
let cid = conn.get_client_prefix();
|
|
|
|
// Create a channel for receiving query results from the database.
|
|
|
|
// we will send out the tx handle to any query we generate.
|
|
|
|
let (query_tx, mut query_rx) = mpsc::channel::<db::QueryResult>(256);
|
2022-02-13 10:35:54 -05:00
|
|
|
// Create channel for receiving NOTICEs
|
|
|
|
let (notice_tx, mut notice_rx) = mpsc::channel::<String>(32);
|
|
|
|
|
2022-02-21 09:46:01 -05:00
|
|
|
// last time this client sent data (message, ping, etc.)
|
2022-02-12 17:57:26 -05:00
|
|
|
let mut last_message_time = Instant::now();
|
|
|
|
|
|
|
|
// ping interval (every 5 minutes)
|
|
|
|
let default_ping_dur = Duration::from_secs(300);
|
|
|
|
|
|
|
|
// disconnect after 20 minutes without a ping response or event.
|
|
|
|
let max_quiet_time = Duration::from_secs(60 * 20);
|
|
|
|
|
|
|
|
let start = tokio::time::Instant::now() + default_ping_dur;
|
|
|
|
let mut ping_interval = tokio::time::interval_at(start, default_ping_dur);
|
|
|
|
|
2022-02-17 17:18:05 -05:00
|
|
|
// maintain a hashmap of a oneshot channel for active subscriptions.
|
|
|
|
// when these subscriptions are cancelled, make a message
|
|
|
|
// available to the executing query so it knows to stop.
|
2021-12-11 16:48:59 -05:00
|
|
|
let mut running_queries: HashMap<String, oneshot::Sender<()>> = HashMap::new();
|
2022-02-17 17:18:05 -05:00
|
|
|
|
2021-12-12 11:03:28 -05:00
|
|
|
// for stats, keep track of how many events the client published,
|
|
|
|
// and how many it received from queries.
|
|
|
|
let mut client_published_event_count: usize = 0;
|
|
|
|
let mut client_received_event_count: usize = 0;
|
2022-02-12 10:29:25 -05:00
|
|
|
info!("new connection for client: {:?}", cid);
|
2021-12-05 17:53:26 -05:00
|
|
|
loop {
|
|
|
|
tokio::select! {
|
2021-12-11 16:48:59 -05:00
|
|
|
_ = shutdown.recv() => {
|
|
|
|
// server shutting down, exit loop
|
|
|
|
break;
|
|
|
|
},
|
2022-02-12 17:57:26 -05:00
|
|
|
_ = ping_interval.tick() => {
|
|
|
|
// check how long since we talked to client
|
|
|
|
// if it has been too long, disconnect
|
|
|
|
if last_message_time.elapsed() > max_quiet_time {
|
|
|
|
debug!("ending connection due to lack of client ping response");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
// Send a ping
|
|
|
|
ws_stream.send(Message::Ping(Vec::new())).await.ok();
|
|
|
|
},
|
2022-02-13 10:35:54 -05:00
|
|
|
Some(notice_msg) = notice_rx.recv() => {
|
2022-02-26 18:34:58 -05:00
|
|
|
ws_stream.send(make_notice_message(¬ice_msg)).await.ok();
|
2022-02-13 10:35:54 -05:00
|
|
|
},
|
2021-12-11 16:48:59 -05:00
|
|
|
Some(query_result) = query_rx.recv() => {
|
2021-12-12 11:03:28 -05:00
|
|
|
// database informed us of a query result we asked for
|
2022-02-12 17:19:10 -05:00
|
|
|
let subesc = query_result.sub_id.replace("\"", "");
|
2022-05-30 18:02:59 -04:00
|
|
|
if query_result.event == "EOSE" {
|
|
|
|
let send_str = format!("[\"EOSE\",\"{}\"]", subesc);
|
|
|
|
ws_stream.send(Message::Text(send_str)).await.ok();
|
|
|
|
} else {
|
|
|
|
client_received_event_count += 1;
|
|
|
|
// send a result
|
|
|
|
let send_str = format!("[\"EVENT\",\"{}\",{}]", subesc, &query_result.event);
|
|
|
|
ws_stream.send(Message::Text(send_str)).await.ok();
|
|
|
|
}
|
2021-12-11 16:48:59 -05:00
|
|
|
},
|
2022-02-12 10:29:25 -05:00
|
|
|
// TODO: consider logging the LaggedRecv error
|
2021-12-05 21:28:02 -05:00
|
|
|
Ok(global_event) = bcast_rx.recv() => {
|
2021-12-12 11:03:28 -05:00
|
|
|
// an event has been broadcast to all clients
|
|
|
|
// first check if there is a subscription for this event.
|
2021-12-14 22:38:26 -05:00
|
|
|
let matching_subs = conn.get_matching_subscriptions(&global_event);
|
|
|
|
for s in matching_subs {
|
2021-12-12 11:03:28 -05:00
|
|
|
// TODO: serialize at broadcast time, instead of
|
|
|
|
// once for each consumer.
|
|
|
|
if let Ok(event_str) = serde_json::to_string(&global_event) {
|
2022-02-12 10:29:25 -05:00
|
|
|
debug!("sub match: client: {:?}, sub: {:?}, event: {:?}",
|
2021-12-14 22:38:26 -05:00
|
|
|
cid, s,
|
2021-12-12 11:03:28 -05:00
|
|
|
global_event.get_event_id_prefix());
|
2021-12-05 21:28:02 -05:00
|
|
|
// create an event response and send it
|
2022-02-12 17:19:10 -05:00
|
|
|
let subesc = s.replace("\"", "");
|
|
|
|
ws_stream.send(Message::Text(format!("[\"EVENT\",\"{}\",{}]", subesc, event_str))).await.ok();
|
|
|
|
//nostr_stream.send(res).await.ok();
|
2021-12-11 16:48:59 -05:00
|
|
|
} else {
|
2022-02-12 10:29:25 -05:00
|
|
|
warn!("could not serialize event {:?}", global_event.get_event_id_prefix());
|
2021-12-05 21:28:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
2022-02-12 17:19:10 -05:00
|
|
|
ws_next = ws_stream.next() => {
|
2022-02-12 17:57:26 -05:00
|
|
|
// update most recent message time for client
|
|
|
|
last_message_time = Instant::now();
|
2022-02-12 17:26:55 -05:00
|
|
|
// Consume text messages from the client, parse into Nostr messages.
|
|
|
|
let nostr_msg = match ws_next {
|
2022-02-12 17:19:10 -05:00
|
|
|
Some(Ok(Message::Text(m))) => {
|
2022-02-12 17:57:26 -05:00
|
|
|
convert_to_msg(m)
|
2022-02-12 17:19:10 -05:00
|
|
|
},
|
2022-02-12 17:26:55 -05:00
|
|
|
Some(Ok(Message::Binary(_))) => {
|
2022-02-26 18:34:58 -05:00
|
|
|
ws_stream.send(make_notice_message("binary messages are not accepted")).await.ok();
|
2022-02-12 17:26:55 -05:00
|
|
|
continue;
|
|
|
|
},
|
2022-02-12 17:57:26 -05:00
|
|
|
Some(Ok(Message::Ping(_))) | Some(Ok(Message::Pong(_))) => {
|
2022-02-21 09:57:07 -05:00
|
|
|
// get a ping/pong, ignore. tungstenite will
|
|
|
|
// send responses automatically.
|
2022-02-12 17:57:26 -05:00
|
|
|
continue;
|
|
|
|
},
|
2022-02-21 09:57:07 -05:00
|
|
|
None |
|
|
|
|
Some(Ok(Message::Close(_))) |
|
|
|
|
Some(Err(WsError::AlreadyClosed)) |
|
|
|
|
Some(Err(WsError::ConnectionClosed)) |
|
|
|
|
Some(Err(WsError::Protocol(tungstenite::error::ProtocolError::ResetWithoutClosingHandshake)))
|
|
|
|
=> {
|
|
|
|
debug!("websocket close from client: {:?}",cid);
|
2022-02-12 17:29:27 -05:00
|
|
|
break;
|
2022-02-12 17:19:10 -05:00
|
|
|
},
|
2022-02-21 09:46:01 -05:00
|
|
|
Some(Err(WsError::Io(e))) => {
|
|
|
|
// IO errors are considered fatal
|
|
|
|
warn!("IO error (client: {:?}): {:?}", cid, e);
|
|
|
|
break;
|
|
|
|
}
|
2022-02-12 17:19:10 -05:00
|
|
|
x => {
|
2022-02-21 09:46:01 -05:00
|
|
|
// default condition on error is to close the client connection
|
|
|
|
info!("unknown error (client: {:?}): {:?} (closing conn)", cid, x);
|
|
|
|
break;
|
2022-02-12 17:19:10 -05:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// convert ws_next into proto_next
|
2022-02-12 17:26:55 -05:00
|
|
|
match nostr_msg {
|
2022-02-12 17:29:27 -05:00
|
|
|
Ok(NostrMessage::EventMsg(ec)) => {
|
2021-12-05 18:15:50 -05:00
|
|
|
// An EventCmd needs to be validated to be converted into an Event
|
2021-12-05 17:53:26 -05:00
|
|
|
// handle each type of message
|
2021-12-05 18:15:50 -05:00
|
|
|
let parsed : Result<Event> = Result::<Event>::from(ec);
|
|
|
|
match parsed {
|
2021-12-05 19:14:14 -05:00
|
|
|
Ok(e) => {
|
|
|
|
let id_prefix:String = e.id.chars().take(8).collect();
|
2022-02-12 10:29:25 -05:00
|
|
|
debug!("successfully parsed/validated event: {:?} from client: {:?}", id_prefix, cid);
|
2022-02-13 10:35:54 -05:00
|
|
|
// Write this to the database.
|
|
|
|
let submit_event = SubmittedEvent { event: e.clone(), notice_tx: notice_tx.clone() };
|
|
|
|
event_tx.send(submit_event).await.ok();
|
2021-12-12 11:03:28 -05:00
|
|
|
client_published_event_count += 1;
|
2021-12-05 21:28:02 -05:00
|
|
|
},
|
2021-12-12 11:50:16 -05:00
|
|
|
Err(_) => {
|
2022-02-12 10:29:25 -05:00
|
|
|
info!("client {:?} sent an invalid event", cid);
|
2022-02-26 18:34:58 -05:00
|
|
|
ws_stream.send(make_notice_message("event was invalid")).await.ok();
|
2021-12-12 11:50:16 -05:00
|
|
|
}
|
2021-12-05 18:15:50 -05:00
|
|
|
}
|
|
|
|
},
|
2022-02-12 17:29:27 -05:00
|
|
|
Ok(NostrMessage::SubMsg(s)) => {
|
2021-12-12 11:03:28 -05:00
|
|
|
debug!("client {} requesting a subscription", cid);
|
2021-12-05 19:14:14 -05:00
|
|
|
// subscription handling consists of:
|
2021-12-11 16:48:59 -05:00
|
|
|
// * registering the subscription so future events can be matched
|
|
|
|
// * making a channel to cancel to request later
|
|
|
|
// * sending a request for a SQL query
|
|
|
|
let (abandon_query_tx, abandon_query_rx) = oneshot::channel::<()>();
|
2021-12-12 11:50:16 -05:00
|
|
|
match conn.subscribe(s.clone()) {
|
|
|
|
Ok(()) => {
|
2022-01-30 16:14:02 -05:00
|
|
|
// when we insert, if there was a previous query running with the same name, cancel it.
|
|
|
|
if let Some(previous_query) = running_queries.insert(s.id.to_owned(), abandon_query_tx) {
|
|
|
|
previous_query.send(()).ok();
|
|
|
|
}
|
2021-12-12 11:50:16 -05:00
|
|
|
// start a database query
|
2022-02-23 17:38:16 -05:00
|
|
|
db::db_query(s, pool.clone(), query_tx.clone(), abandon_query_rx).await;
|
2021-12-12 11:50:16 -05:00
|
|
|
},
|
|
|
|
Err(e) => {
|
|
|
|
info!("Subscription error: {}", e);
|
2022-02-26 18:34:58 -05:00
|
|
|
ws_stream.send(make_notice_message(&e.to_string())).await.ok();
|
2021-12-12 11:50:16 -05:00
|
|
|
}
|
|
|
|
}
|
2021-12-05 18:33:40 -05:00
|
|
|
},
|
2022-02-12 17:29:27 -05:00
|
|
|
Ok(NostrMessage::CloseMsg(cc)) => {
|
2021-12-05 19:14:14 -05:00
|
|
|
// closing a request simply removes the subscription.
|
|
|
|
let parsed : Result<Close> = Result::<Close>::from(cc);
|
|
|
|
match parsed {
|
2021-12-11 16:48:59 -05:00
|
|
|
Ok(c) => {
|
2021-12-12 11:03:28 -05:00
|
|
|
// check if a query is currently
|
|
|
|
// running, and remove it if so.
|
2021-12-11 16:48:59 -05:00
|
|
|
let stop_tx = running_queries.remove(&c.id);
|
2021-12-11 22:56:52 -05:00
|
|
|
if let Some(tx) = stop_tx {
|
|
|
|
tx.send(()).ok();
|
2021-12-11 16:48:59 -05:00
|
|
|
}
|
2021-12-12 11:03:28 -05:00
|
|
|
// stop checking new events against
|
|
|
|
// the subscription
|
2021-12-11 16:48:59 -05:00
|
|
|
conn.unsubscribe(c);
|
|
|
|
},
|
2021-12-12 11:50:16 -05:00
|
|
|
Err(_) => {
|
|
|
|
info!("invalid command ignored");
|
2022-02-26 18:34:58 -05:00
|
|
|
ws_stream.send(make_notice_message("could not parse command")).await.ok();
|
2021-12-12 11:50:16 -05:00
|
|
|
}
|
2021-12-05 19:14:14 -05:00
|
|
|
}
|
2021-12-05 17:53:26 -05:00
|
|
|
},
|
2022-02-12 17:29:27 -05:00
|
|
|
Err(Error::ConnError) => {
|
2022-02-12 10:29:25 -05:00
|
|
|
debug!("got connection close/error, disconnecting client: {:?}",cid);
|
2021-12-11 16:48:59 -05:00
|
|
|
break;
|
2021-12-05 17:53:26 -05:00
|
|
|
}
|
2022-02-12 17:29:27 -05:00
|
|
|
Err(Error::EventMaxLengthError(s)) => {
|
2022-02-12 10:29:25 -05:00
|
|
|
info!("client {:?} sent event larger ({} bytes) than max size", cid, s);
|
2022-02-26 18:34:58 -05:00
|
|
|
ws_stream.send(make_notice_message("event exceeded max size")).await.ok();
|
2021-12-31 16:19:35 -05:00
|
|
|
},
|
2022-02-12 17:33:29 -05:00
|
|
|
Err(Error::ProtoParseError) => {
|
|
|
|
info!("client {:?} sent event that could not be parsed", cid);
|
2022-02-26 18:34:58 -05:00
|
|
|
ws_stream.send(make_notice_message("could not parse command")).await.ok();
|
2022-02-12 17:33:29 -05:00
|
|
|
},
|
2022-02-12 17:29:27 -05:00
|
|
|
Err(e) => {
|
2022-02-12 10:29:25 -05:00
|
|
|
info!("got non-fatal error from client: {:?}, error: {:?}", cid, e);
|
2021-12-05 17:53:26 -05:00
|
|
|
},
|
|
|
|
}
|
2021-12-11 16:48:59 -05:00
|
|
|
},
|
2021-12-05 17:53:26 -05:00
|
|
|
}
|
|
|
|
}
|
2021-12-11 16:48:59 -05:00
|
|
|
// connection cleanup - ensure any still running queries are terminated.
|
|
|
|
for (_, stop_tx) in running_queries.into_iter() {
|
|
|
|
stop_tx.send(()).ok();
|
|
|
|
}
|
2021-12-12 11:03:28 -05:00
|
|
|
info!(
|
2022-02-12 10:29:25 -05:00
|
|
|
"stopping connection for client: {:?} (client sent {} event(s), received {})",
|
2021-12-12 11:03:28 -05:00
|
|
|
cid, client_published_event_count, client_received_event_count
|
|
|
|
);
|
2021-12-05 09:42:28 -05:00
|
|
|
}
|