forked from lavina/lavina
1
0
Fork 0

Compare commits

...

11 Commits

24 changed files with 913 additions and 161 deletions

451
Cargo.lock generated
View File

@ -132,6 +132,39 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b34d609dfbaf33d6889b2b7106d3ca345eacad44200913df5ba02bfd31d2ba9"
[[package]]
name = "async-stream"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51"
dependencies = [
"async-stream-impl",
"futures-core",
"pin-project-lite",
]
[[package]]
name = "async-stream-impl"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.60",
]
[[package]]
name = "async-trait"
version = "0.1.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.60",
]
[[package]]
name = "atoi"
version = "2.0.0"
@ -156,6 +189,51 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
[[package]]
name = "axum"
version = "0.6.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf"
dependencies = [
"async-trait",
"axum-core",
"bitflags 1.3.2",
"bytes",
"futures-util",
"http 0.2.12",
"http-body 0.4.6",
"hyper 0.14.28",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"rustversion",
"serde",
"sync_wrapper",
"tower",
"tower-layer",
"tower-service",
]
[[package]]
name = "axum-core"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c"
dependencies = [
"async-trait",
"bytes",
"futures-util",
"http 0.2.12",
"http-body 0.4.6",
"mime",
"rustversion",
"tower-layer",
"tower-service",
]
[[package]]
name = "backtrace"
version = "0.3.71"
@ -360,6 +438,15 @@ version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
[[package]]
name = "crossbeam-channel"
version = "0.5.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab3db02a9c5b5121e1e42fbdb1aeb65f5e02624cc58c43f2884c6ccac0b82f95"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-queue"
version = "0.3.11"
@ -632,6 +719,37 @@ version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
[[package]]
name = "glob"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
[[package]]
name = "h2"
version = "0.3.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8"
dependencies = [
"bytes",
"fnv",
"futures-core",
"futures-sink",
"futures-util",
"http 0.2.12",
"indexmap 2.2.6",
"slab",
"tokio",
"tokio-util",
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
[[package]]
name = "hashbrown"
version = "0.14.3"
@ -648,7 +766,7 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8094feaf31ff591f651a2664fb9cfd92bba7a60ce3197265e9482ebe753c8f7"
dependencies = [
"hashbrown",
"hashbrown 0.14.3",
]
[[package]]
@ -705,6 +823,17 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "http"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
dependencies = [
"bytes",
"fnv",
"itoa",
]
[[package]]
name = "http"
version = "1.1.0"
@ -716,6 +845,17 @@ dependencies = [
"itoa",
]
[[package]]
name = "http-body"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2"
dependencies = [
"bytes",
"http 0.2.12",
"pin-project-lite",
]
[[package]]
name = "http-body"
version = "1.0.0"
@ -723,7 +863,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643"
dependencies = [
"bytes",
"http",
"http 1.1.0",
]
[[package]]
@ -734,8 +874,8 @@ checksum = "0475f8b2ac86659c21b64320d5d653f9efe42acd2a4e560073ec61a155a34f1d"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http 1.1.0",
"http-body 1.0.0",
"pin-project-lite",
]
@ -751,6 +891,30 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "0.14.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf96e135eb83a2a8ddf766e426a841d8ddd7449d5f00d34ea02b41d2f19eef80"
dependencies = [
"bytes",
"futures-channel",
"futures-core",
"futures-util",
"h2",
"http 0.2.12",
"http-body 0.4.6",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"socket2",
"tokio",
"tower-service",
"tracing",
"want",
]
[[package]]
name = "hyper"
version = "1.3.1"
@ -760,8 +924,8 @@ dependencies = [
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"http 1.1.0",
"http-body 1.0.0",
"httparse",
"httpdate",
"itoa",
@ -771,6 +935,18 @@ dependencies = [
"want",
]
[[package]]
name = "hyper-timeout"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbb958482e8c7be4bc3cf272a766a2b0bf1a6755e7a6ae777f017a31d11b13b1"
dependencies = [
"hyper 0.14.28",
"pin-project-lite",
"tokio",
"tokio-io-timeout",
]
[[package]]
name = "hyper-util"
version = "0.1.3"
@ -780,9 +956,9 @@ dependencies = [
"bytes",
"futures-channel",
"futures-util",
"http",
"http-body",
"hyper",
"http 1.1.0",
"http-body 1.0.0",
"hyper 1.3.1",
"pin-project-lite",
"socket2",
"tokio",
@ -824,6 +1000,16 @@ dependencies = [
"unicode-normalization",
]
[[package]]
name = "indexmap"
version = "1.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
dependencies = [
"autocfg",
"hashbrown 0.12.3",
]
[[package]]
name = "indexmap"
version = "2.2.6"
@ -831,7 +1017,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26"
dependencies = [
"equivalent",
"hashbrown",
"hashbrown 0.14.3",
]
[[package]]
@ -872,7 +1058,7 @@ dependencies = [
[[package]]
name = "lavina"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"anyhow",
"assert_matches",
@ -881,11 +1067,15 @@ dependencies = [
"figment",
"futures-util",
"http-body-util",
"hyper",
"hyper 1.3.1",
"hyper-util",
"lavina-core",
"mgmt-api",
"nonempty",
"opentelemetry",
"opentelemetry-otlp",
"opentelemetry-semantic-conventions",
"opentelemetry_sdk",
"projection-irc",
"projection-xmpp",
"prometheus",
@ -895,12 +1085,13 @@ dependencies = [
"serde_json",
"tokio",
"tracing",
"tracing-opentelemetry",
"tracing-subscriber",
]
[[package]]
name = "lavina-core"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"anyhow",
"argon2",
@ -967,6 +1158,12 @@ version = "0.4.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
[[package]]
name = "matchit"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"
[[package]]
name = "md-5"
version = "0.10.6"
@ -985,7 +1182,7 @@ checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
[[package]]
name = "mgmt-api"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"serde",
]
@ -1120,6 +1317,89 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "opentelemetry"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "900d57987be3f2aeb70d385fff9b27fb74c5723cc9a52d904d4f9c807a0667bf"
dependencies = [
"futures-core",
"futures-sink",
"js-sys",
"once_cell",
"pin-project-lite",
"thiserror",
"urlencoding",
]
[[package]]
name = "opentelemetry-otlp"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a016b8d9495c639af2145ac22387dcb88e44118e45320d9238fbf4e7889abcb"
dependencies = [
"async-trait",
"futures-core",
"http 0.2.12",
"opentelemetry",
"opentelemetry-proto",
"opentelemetry-semantic-conventions",
"opentelemetry_sdk",
"prost",
"thiserror",
"tokio",
"tonic",
]
[[package]]
name = "opentelemetry-proto"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a8fddc9b68f5b80dae9d6f510b88e02396f006ad48cac349411fbecc80caae4"
dependencies = [
"opentelemetry",
"opentelemetry_sdk",
"prost",
"tonic",
]
[[package]]
name = "opentelemetry-semantic-conventions"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9ab5bd6c42fb9349dcf28af2ba9a0667f697f9bdcca045d39f2cec5543e2910"
[[package]]
name = "opentelemetry_sdk"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e90c7113be649e31e9a0f8b5ee24ed7a16923b322c3c5ab6367469c049d6b7e"
dependencies = [
"async-trait",
"crossbeam-channel",
"futures-channel",
"futures-executor",
"futures-util",
"glob",
"once_cell",
"opentelemetry",
"ordered-float",
"percent-encoding",
"rand",
"thiserror",
"tokio",
"tokio-stream",
]
[[package]]
name = "ordered-float"
version = "4.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a76df7075c7d4d01fdcb46c912dd17fba5b60c78ea480b475f2b6ab6f666584e"
dependencies = [
"num-traits",
]
[[package]]
name = "overload"
version = "0.1.1"
@ -1293,7 +1573,7 @@ dependencies = [
[[package]]
name = "projection-irc"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"anyhow",
"bitflags 2.5.0",
@ -1312,7 +1592,7 @@ dependencies = [
[[package]]
name = "projection-xmpp"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"anyhow",
"assert_matches",
@ -1346,9 +1626,32 @@ dependencies = [
"thiserror",
]
[[package]]
name = "prost"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0f5d036824e4761737860779c906171497f6d55681139d8312388f8fe398922"
dependencies = [
"bytes",
"prost-derive",
]
[[package]]
name = "prost-derive"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19de2de2a00075bf566bee3bd4db014b11587e84184d3f7a791bc17f1a8e9e48"
dependencies = [
"anyhow",
"itertools",
"proc-macro2",
"quote",
"syn 2.0.60",
]
[[package]]
name = "proto-irc"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"anyhow",
"assert_matches",
@ -1360,7 +1663,7 @@ dependencies = [
[[package]]
name = "proto-xmpp"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"anyhow",
"assert_matches",
@ -1468,10 +1771,10 @@ dependencies = [
"bytes",
"futures-core",
"futures-util",
"http",
"http-body",
"http 1.1.0",
"http-body 1.0.0",
"http-body-util",
"hyper",
"hyper 1.3.1",
"hyper-util",
"ipnet",
"js-sys",
@ -1587,6 +1890,12 @@ dependencies = [
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80af6f9131f277a45a3fba6ce8e2258037bb0477a67e610d3c1fe046ab31de47"
[[package]]
name = "ryu"
version = "1.0.17"
@ -1595,7 +1904,7 @@ checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
[[package]]
name = "sasl"
version = "0.0.2-dev"
version = "0.0.3-dev"
dependencies = [
"anyhow",
"base64 0.22.0",
@ -1821,7 +2130,7 @@ dependencies = [
"futures-util",
"hashlink",
"hex",
"indexmap",
"indexmap 2.2.6",
"log",
"memchr",
"once_cell",
@ -2108,6 +2417,16 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "tokio-io-timeout"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "30b74022ada614a1b4834de765f9bb43877f910cc8ce4be40e89042c9223a8bf"
dependencies = [
"pin-project-lite",
"tokio",
]
[[package]]
name = "tokio-macros"
version = "2.2.0"
@ -2129,6 +2448,31 @@ dependencies = [
"tokio",
]
[[package]]
name = "tokio-stream"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "267ac89e0bec6e691e5813911606935d77c476ff49024f98abcea3e7b15e37af"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5419f34732d9eb6ee4c3578b7989078579b7f039cbbb9ca2c4da015749371e15"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
"tracing",
]
[[package]]
name = "toml"
version = "0.8.12"
@ -2156,13 +2500,40 @@ version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb686a972ccef8537b39eead3968b0e8616cb5040dbb9bba93007c8e07c9215f"
dependencies = [
"indexmap",
"indexmap 2.2.6",
"serde",
"serde_spanned",
"toml_datetime",
"winnow",
]
[[package]]
name = "tonic"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76c4eb7a4e9ef9d4763600161f12f5070b92a578e1b634db88a6887844c91a13"
dependencies = [
"async-stream",
"async-trait",
"axum",
"base64 0.21.7",
"bytes",
"h2",
"http 0.2.12",
"http-body 0.4.6",
"hyper 0.14.28",
"hyper-timeout",
"percent-encoding",
"pin-project",
"prost",
"tokio",
"tokio-stream",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower"
version = "0.4.13"
@ -2171,9 +2542,13 @@ checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"
dependencies = [
"futures-core",
"futures-util",
"indexmap 1.9.3",
"pin-project",
"pin-project-lite",
"rand",
"slab",
"tokio",
"tokio-util",
"tower-layer",
"tower-service",
"tracing",
@ -2235,6 +2610,24 @@ dependencies = [
"tracing-core",
]
[[package]]
name = "tracing-opentelemetry"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9be14ba1bbe4ab79e9229f7f89fab8d120b865859f10527f31c033e599d2284"
dependencies = [
"js-sys",
"once_cell",
"opentelemetry",
"opentelemetry_sdk",
"smallvec",
"tracing",
"tracing-core",
"tracing-log",
"tracing-subscriber",
"web-time",
]
[[package]]
name = "tracing-subscriber"
version = "0.3.18"
@ -2456,6 +2849,16 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "web-time"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "whoami"
version = "1.5.1"

View File

@ -10,7 +10,7 @@ members = [
]
[workspace.package]
version = "0.0.2-dev"
version = "0.0.3-dev"
[workspace.dependencies]
nom = "7.1.3"
@ -59,6 +59,11 @@ projection-irc = { path = "crates/projection-irc" }
projection-xmpp = { path = "crates/projection-xmpp" }
mgmt-api = { path = "crates/mgmt-api" }
clap.workspace = true
opentelemetry = "0.22.0"
opentelemetry-semantic-conventions = "0.14.0"
opentelemetry_sdk = { version = "0.22.1", features = ["rt-tokio"] }
opentelemetry-otlp = "0.15.0"
tracing-opentelemetry = "0.23.0"
[dev-dependencies]
assert_matches.workspace = true

View File

@ -25,6 +25,7 @@ impl<'a> Authenticator<'a> {
Self { storage }
}
#[tracing::instrument(skip(self, provided_password), name = "Authenticator::authenticate")]
pub async fn authenticate(&self, login: &str, provided_password: &str) -> Result<Verdict> {
let Some(stored_user) = self.storage.retrieve_user_by_name(login).await? else {
return Ok(Verdict::UserNotFound);
@ -46,6 +47,7 @@ impl<'a> Authenticator<'a> {
Ok(Verdict::InvalidPassword)
}
#[tracing::instrument(skip(self, provided_password), name = "Authenticator::set_password")]
pub async fn set_password(&self, login: &str, provided_password: &str) -> Result<UpdatePasswordResult> {
let Some(u) = self.storage.retrieve_user_by_name(login).await? else {
return Ok(UpdatePasswordResult::UserNotFound);

View File

@ -65,7 +65,10 @@ impl DialogRegistry {
let dialog = guard.dialogs.get(&id);
if let Some(d) = dialog {
let mut d = d.write().await;
guard.storage.increment_dialog_message_count(d.storage_id).await?;
guard
.storage
.insert_dialog_message(d.storage_id, d.message_count, from.as_inner(), &body, created_at)
.await?;
d.message_count += 1;
} else {
drop(guard);
@ -73,7 +76,10 @@ impl DialogRegistry {
// double check in case concurrent access has loaded this dialog
if let Some(d) = guard2.dialogs.get(&id) {
let mut d = d.write().await;
guard2.storage.increment_dialog_message_count(d.storage_id).await?;
guard2
.storage
.insert_dialog_message(d.storage_id, d.message_count, from.as_inner(), &body, created_at)
.await?;
d.message_count += 1;
} else {
let (p1, p2) = id.as_inner();
@ -86,7 +92,16 @@ impl DialogRegistry {
}
};
tracing::info!("Dialog {id:?} loaded");
guard2.storage.increment_dialog_message_count(stored_dialog.id).await?;
guard2
.storage
.insert_dialog_message(
stored_dialog.id,
stored_dialog.message_count,
from.as_inner(),
&body,
created_at,
)
.await?;
let dialog = Dialog {
storage_id: stored_dialog.id,
player_storage_id_1: stored_dialog.participant_1,

View File

@ -15,6 +15,7 @@ use prometheus::{IntGauge, Registry as MetricsRegistry};
use serde::Serialize;
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::sync::RwLock;
use tracing::{Instrument, Span};
use crate::dialog::DialogRegistry;
use crate::prelude::*;
@ -54,11 +55,12 @@ pub struct ConnectionId(pub AnonKey);
/// The connection is used to send commands to the player actor and to receive updates that might be sent to the client.
pub struct PlayerConnection {
pub connection_id: ConnectionId,
pub receiver: Receiver<Updates>,
pub receiver: Receiver<ConnectionMessage>,
player_handle: PlayerHandle,
}
impl PlayerConnection {
/// Handled in [Player::send_message].
#[tracing::instrument(skip(self, body), name = "PlayerConnection::send_message")]
pub async fn send_message(&mut self, room_id: RoomId, body: Str) -> Result<SendMessageResult> {
let (promise, deferred) = oneshot();
let cmd = ClientCommand::SendMessage { room_id, body, promise };
@ -67,6 +69,7 @@ impl PlayerConnection {
}
/// Handled in [Player::join_room].
#[tracing::instrument(skip(self), name = "PlayerConnection::join_room")]
pub async fn join_room(&mut self, room_id: RoomId) -> Result<JoinResult> {
let (promise, deferred) = oneshot();
let cmd = ClientCommand::JoinRoom { room_id, promise };
@ -75,6 +78,7 @@ impl PlayerConnection {
}
/// Handled in [Player::change_topic].
#[tracing::instrument(skip(self, new_topic), name = "PlayerConnection::change_topic")]
pub async fn change_topic(&mut self, room_id: RoomId, new_topic: Str) -> Result<()> {
let (promise, deferred) = oneshot();
let cmd = ClientCommand::ChangeTopic {
@ -87,6 +91,7 @@ impl PlayerConnection {
}
/// Handled in [Player::leave_room].
#[tracing::instrument(skip(self), name = "PlayerConnection::leave_room")]
pub async fn leave_room(&mut self, room_id: RoomId) -> Result<()> {
let (promise, deferred) = oneshot();
let cmd = ClientCommand::LeaveRoom { room_id, promise };
@ -99,6 +104,7 @@ impl PlayerConnection {
}
/// Handled in [Player::get_rooms].
#[tracing::instrument(skip(self), name = "PlayerConnection::get_rooms")]
pub async fn get_rooms(&self) -> Result<Vec<RoomInfo>> {
let (promise, deferred) = oneshot();
let cmd = ClientCommand::GetRooms { promise };
@ -107,6 +113,7 @@ impl PlayerConnection {
}
/// Handler in [Player::send_dialog_message].
#[tracing::instrument(skip(self, body), name = "PlayerConnection::send_dialog_message")]
pub async fn send_dialog_message(&self, recipient: PlayerId, body: Str) -> Result<()> {
let (promise, deferred) = oneshot();
let cmd = ClientCommand::SendDialogMessage {
@ -122,14 +129,14 @@ impl PlayerConnection {
/// Handle to a player actor.
#[derive(Clone)]
pub struct PlayerHandle {
tx: Sender<ActorCommand>,
tx: Sender<(ActorCommand, Span)>,
}
impl PlayerHandle {
pub async fn subscribe(&self) -> PlayerConnection {
let (sender, receiver) = channel(32);
let (promise, deferred) = oneshot();
let cmd = ActorCommand::AddConnection { sender, promise };
let _ = self.tx.send(cmd).await;
self.send(cmd).await;
let connection_id = deferred.await.unwrap();
PlayerConnection {
connection_id,
@ -139,8 +146,9 @@ impl PlayerHandle {
}
async fn send(&self, command: ActorCommand) {
let span = tracing::span!(tracing::Level::INFO, "PlayerHandle::send");
// TODO either handle the error or doc why it is safe to ignore
let _ = self.tx.send(command).await;
let _ = self.tx.send((command, span)).await;
}
pub async fn update(&self, update: Updates) {
@ -152,7 +160,7 @@ impl PlayerHandle {
enum ActorCommand {
/// Establish a new connection.
AddConnection {
sender: Sender<Updates>,
sender: Sender<ConnectionMessage>,
promise: Promise<ConnectionId>,
},
/// Terminate an existing connection.
@ -329,10 +337,10 @@ struct PlayerRegistryInner {
struct Player {
player_id: PlayerId,
storage_id: u32,
connections: AnonTable<Sender<Updates>>,
connections: AnonTable<Sender<ConnectionMessage>>,
my_rooms: HashMap<RoomId, RoomHandle>,
banned_from: HashSet<RoomId>,
rx: Receiver<ActorCommand>,
rx: Receiver<(ActorCommand, Span)>,
handle: PlayerHandle,
rooms: RoomRegistry,
dialogs: DialogRegistry,
@ -379,20 +387,36 @@ impl Player {
}
}
while let Some(cmd) = self.rx.recv().await {
match cmd {
ActorCommand::AddConnection { sender, promise } => {
let connection_id = self.connections.insert(sender);
if let Err(connection_id) = promise.send(ConnectionId(connection_id)) {
log::warn!("Connection {connection_id:?} terminated before finalization");
self.terminate_connection(connection_id);
let (cmd, span) = cmd;
let should_stop = async {
match cmd {
ActorCommand::AddConnection { sender, promise } => {
let connection_id = self.connections.insert(sender);
if let Err(connection_id) = promise.send(ConnectionId(connection_id)) {
log::warn!("Connection {connection_id:?} terminated before finalization");
self.terminate_connection(connection_id);
}
false
}
ActorCommand::TerminateConnection(connection_id) => {
self.terminate_connection(connection_id);
false
}
ActorCommand::Update(update) => {
self.handle_update(update).await;
false
}
ActorCommand::ClientCommand(cmd, connection_id) => {
self.handle_cmd(cmd, connection_id).await;
false
}
ActorCommand::Stop => true,
}
ActorCommand::TerminateConnection(connection_id) => {
self.terminate_connection(connection_id);
}
ActorCommand::Update(update) => self.handle_update(update).await,
ActorCommand::ClientCommand(cmd, connection_id) => self.handle_cmd(cmd, connection_id).await,
ActorCommand::Stop => break,
}
.instrument(span)
.await;
if should_stop {
break;
}
}
log::debug!("Shutting down player actor #{:?}", self.player_id);
@ -400,6 +424,7 @@ impl Player {
}
/// Handle an incoming update by changing the internal state and broadcasting it to all connections if necessary.
#[tracing::instrument(skip(self, update), name = "Player::handle_update")]
async fn handle_update(&mut self, update: Updates) {
log::debug!(
"Player received an update, broadcasting to {} connections",
@ -413,7 +438,7 @@ impl Player {
_ => {}
}
for (_, connection) in &self.connections {
let _ = connection.send(update.clone()).await;
let _ = connection.send(ConnectionMessage::Update(update.clone())).await;
}
}
@ -461,6 +486,7 @@ impl Player {
}
}
#[tracing::instrument(skip(self), name = "Player::join_room")]
async fn join_room(&mut self, connection_id: ConnectionId, room_id: RoomId) -> JoinResult {
if self.banned_from.contains(&room_id) {
return JoinResult::Banned;
@ -488,6 +514,7 @@ impl Player {
JoinResult::Success(room_info)
}
#[tracing::instrument(skip(self), name = "Player::leave_room")]
async fn leave_room(&mut self, connection_id: ConnectionId, room_id: RoomId) {
let room = self.my_rooms.remove(&room_id);
if let Some(room) = room {
@ -501,6 +528,7 @@ impl Player {
self.broadcast_update(update, connection_id).await;
}
#[tracing::instrument(skip(self, body), name = "Player::send_message")]
async fn send_message(&mut self, connection_id: ConnectionId, room_id: RoomId, body: Str) -> SendMessageResult {
let Some(room) = self.my_rooms.get(&room_id) else {
tracing::info!("no room found");
@ -518,6 +546,7 @@ impl Player {
SendMessageResult::Success(created_at)
}
#[tracing::instrument(skip(self, new_topic), name = "Player::change_topic")]
async fn change_topic(&mut self, connection_id: ConnectionId, room_id: RoomId, new_topic: Str) {
let Some(room) = self.my_rooms.get(&room_id) else {
tracing::info!("no room found");
@ -528,6 +557,7 @@ impl Player {
self.broadcast_update(update, connection_id).await;
}
#[tracing::instrument(skip(self), name = "Player::get_rooms")]
async fn get_rooms(&self) -> Vec<RoomInfo> {
let mut response = vec![];
for (_, handle) in &self.my_rooms {
@ -536,6 +566,7 @@ impl Player {
response
}
#[tracing::instrument(skip(self, body), name = "Player::send_dialog_message")]
async fn send_dialog_message(&self, connection_id: ConnectionId, recipient: PlayerId, body: Str) {
let created_at = chrono::Utc::now();
self.dialogs.send_message(self.player_id.clone(), recipient.clone(), body.clone(), &created_at).await.unwrap();
@ -552,12 +583,23 @@ impl Player {
///
/// This is called after handling a client command.
/// Sending the update to the connection which sent the command is handled by the connection itself.
#[tracing::instrument(skip(self, update), name = "Player::broadcast_update")]
async fn broadcast_update(&self, update: Updates, except: ConnectionId) {
for (a, b) in &self.connections {
if ConnectionId(a) == except {
continue;
}
let _ = b.send(update.clone()).await;
let _ = b.send(ConnectionMessage::Update(update.clone())).await;
}
}
}
pub enum ConnectionMessage {
Update(Updates),
Stop(StopReason),
}
pub enum StopReason {
ServerShutdown,
InternalError,
}

View File

@ -3,6 +3,7 @@ use anyhow::Result;
use crate::repo::Storage;
impl Storage {
#[tracing::instrument(skip(self), name = "Storage::set_argon2_challenge")]
pub async fn set_argon2_challenge(&self, user_id: u32, hash: &str) -> Result<()> {
let mut executor = self.conn.lock().await;
sqlx::query(

View File

@ -1,10 +1,11 @@
use anyhow::Result;
use anyhow::{anyhow, Result};
use chrono::{DateTime, Utc};
use sqlx::FromRow;
use crate::repo::Storage;
impl Storage {
#[tracing::instrument(skip(self), name = "Storage::retrieve_dialog")]
pub async fn retrieve_dialog(&self, participant_1: &str, participant_2: &str) -> Result<Option<StoredDialog>> {
let mut executor = self.conn.lock().await;
let res = sqlx::query_as(
@ -20,19 +21,41 @@ impl Storage {
Ok(res)
}
pub async fn increment_dialog_message_count(&self, storage_id: u32) -> Result<()> {
#[tracing::instrument(skip(self, content, created_at), name = "Storage::insert_dialog_message")]
pub async fn insert_dialog_message(
&self,
dialog_id: u32,
id: u32,
author_id: &str,
content: &str,
created_at: &DateTime<Utc>,
) -> Result<()> {
let mut executor = self.conn.lock().await;
let res: Option<(u32,)> = sqlx::query_as("select id from users where name = ?;")
.bind(author_id)
.fetch_optional(&mut *executor)
.await?;
let Some((author_id,)) = res else {
return Err(anyhow!("No such user"));
};
sqlx::query(
"update rooms set message_count = message_count + 1
where id = ?;",
"insert into dialog_messages(dialog_id, id, author_id, content, created_at)
values (?, ?, ?, ?, ?);
update dialogs set message_count = message_count + 1 where id = ?;",
)
.bind(storage_id)
.bind(dialog_id)
.bind(id)
.bind(author_id)
.bind(content)
.bind(created_at)
.bind(dialog_id)
.execute(&mut *executor)
.await?;
Ok(())
}
#[tracing::instrument(skip(self, created_at), name = "Storage::initialize_dialog")]
pub async fn initialize_dialog(
&self,
participant_1: &str,

View File

@ -40,6 +40,7 @@ impl Storage {
Ok(Storage { conn })
}
#[tracing::instrument(skip(self), name = "Storage::retrieve_user_by_name")]
pub async fn retrieve_user_by_name(&self, name: &str) -> Result<Option<StoredUser>> {
let mut executor = self.conn.lock().await;
let res = sqlx::query_as(
@ -55,6 +56,7 @@ impl Storage {
Ok(res)
}
#[tracing::instrument(skip(self), name = "Storage::retrieve_room_by_name")]
pub async fn retrieve_room_by_name(&self, name: &str) -> Result<Option<StoredRoom>> {
let mut executor = self.conn.lock().await;
let res = sqlx::query_as(
@ -69,6 +71,7 @@ impl Storage {
Ok(res)
}
#[tracing::instrument(skip(self, topic), name = "Storage::create_new_room")]
pub async fn create_new_room(&mut self, name: &str, topic: &str) -> Result<u32> {
let mut executor = self.conn.lock().await;
let (id,): (u32,) = sqlx::query_as(
@ -84,6 +87,7 @@ impl Storage {
Ok(id)
}
#[tracing::instrument(skip(self, content, created_at), name = "Storage::insert_message")]
pub async fn insert_message(
&mut self,
room_id: u32,
@ -127,6 +131,7 @@ impl Storage {
Ok(())
}
#[tracing::instrument(skip(self), name = "Storage::create_user")]
pub async fn create_user(&mut self, name: &str) -> Result<()> {
let query = sqlx::query(
"insert into users(name)
@ -139,6 +144,7 @@ impl Storage {
Ok(())
}
#[tracing::instrument(skip(self, pwd), name = "Storage::set_password")]
pub async fn set_password<'a>(&'a self, name: &'a str, pwd: &'a str) -> Result<Option<()>> {
async fn inner(txn: &mut Transaction<'_, Sqlite>, name: &str, pwd: &str) -> Result<Option<()>> {
let id: Option<(u32,)> = sqlx::query_as("select * from users where name = ? limit 1;")

View File

@ -3,6 +3,7 @@ use anyhow::Result;
use crate::repo::Storage;
impl Storage {
#[tracing::instrument(skip(self), name = "Storage::add_room_member")]
pub async fn add_room_member(&self, room_id: u32, player_id: u32) -> Result<()> {
let mut executor = self.conn.lock().await;
sqlx::query(
@ -17,6 +18,7 @@ impl Storage {
Ok(())
}
#[tracing::instrument(skip(self), name = "Storage::remove_room_member")]
pub async fn remove_room_member(&self, room_id: u32, player_id: u32) -> Result<()> {
let mut executor = self.conn.lock().await;
sqlx::query(
@ -31,6 +33,7 @@ impl Storage {
Ok(())
}
#[tracing::instrument(skip(self, topic), name = "Storage::set_room_topic")]
pub async fn set_room_topic(&mut self, id: u32, topic: &str) -> Result<()> {
let mut executor = self.conn.lock().await;
sqlx::query(

View File

@ -59,6 +59,7 @@ impl RoomRegistry {
Ok(())
}
#[tracing::instrument(skip(self), name = "RoomRegistry::get_or_create_room")]
pub async fn get_or_create_room(&mut self, room_id: RoomId) -> Result<RoomHandle> {
let mut inner = self.0.write().await;
if let Some(room_handle) = inner.get_or_load_room(&room_id).await? {
@ -83,11 +84,13 @@ impl RoomRegistry {
}
}
#[tracing::instrument(skip(self), name = "RoomRegistry::get_room")]
pub async fn get_room(&self, room_id: &RoomId) -> Option<RoomHandle> {
let mut inner = self.0.write().await;
inner.get_or_load_room(room_id).await.unwrap()
}
#[tracing::instrument(skip(self), name = "RoomRegistry::get_all_rooms")]
pub async fn get_all_rooms(&self) -> Vec<RoomInfo> {
let handles = {
let inner = self.0.read().await;
@ -109,6 +112,7 @@ struct RoomRegistryInner {
}
impl RoomRegistryInner {
#[tracing::instrument(skip(self), name = "RoomRegistryInner::get_or_load_room")]
async fn get_or_load_room(&mut self, room_id: &RoomId) -> Result<Option<RoomHandle>> {
if let Some(room_handle) = self.rooms.get(room_id) {
log::debug!("Room {} was loaded already", &room_id.0);
@ -138,12 +142,14 @@ impl RoomRegistryInner {
#[derive(Clone)]
pub struct RoomHandle(Arc<AsyncRwLock<Room>>);
impl RoomHandle {
#[tracing::instrument(skip(self, player_handle), name = "RoomHandle::subscribe")]
pub async fn subscribe(&self, player_id: &PlayerId, player_handle: PlayerHandle) {
let mut lock = self.0.write().await;
tracing::info!("Adding a subscriber to a room");
lock.subscriptions.insert(player_id.clone(), player_handle);
}
#[tracing::instrument(skip(self), name = "RoomHandle::add_member")]
pub async fn add_member(&self, player_id: &PlayerId, player_storage_id: u32) {
let mut lock = self.0.write().await;
tracing::info!("Adding a new member to a room");
@ -157,11 +163,13 @@ impl RoomHandle {
lock.broadcast_update(update, player_id).await;
}
#[tracing::instrument(skip(self), name = "RoomHandle::unsubscribe")]
pub async fn unsubscribe(&self, player_id: &PlayerId) {
let mut lock = self.0.write().await;
lock.subscriptions.remove(player_id);
}
#[tracing::instrument(skip(self), name = "RoomHandle::remove_member")]
pub async fn remove_member(&self, player_id: &PlayerId, player_storage_id: u32) {
let mut lock = self.0.write().await;
tracing::info!("Removing a member from a room");
@ -175,6 +183,7 @@ impl RoomHandle {
lock.broadcast_update(update, player_id).await;
}
#[tracing::instrument(skip(self, body, created_at), name = "RoomHandle::send_message")]
pub async fn send_message(&self, player_id: &PlayerId, body: Str, created_at: DateTime<Utc>) {
let mut lock = self.0.write().await;
let res = lock.send_message(player_id, body, created_at).await;
@ -183,6 +192,7 @@ impl RoomHandle {
}
}
#[tracing::instrument(skip(self), name = "RoomHandle::get_room_info")]
pub async fn get_room_info(&self) -> RoomInfo {
let lock = self.0.read().await;
RoomInfo {
@ -192,6 +202,7 @@ impl RoomHandle {
}
}
#[tracing::instrument(skip(self, new_topic), name = "RoomHandle::set_topic")]
pub async fn set_topic(&self, changer_id: &PlayerId, new_topic: Str) {
let mut lock = self.0.write().await;
let storage_id = lock.storage_id;
@ -220,6 +231,7 @@ struct Room {
storage: Storage,
}
impl Room {
#[tracing::instrument(skip(self, body, created_at), name = "Room::send_message")]
async fn send_message(&mut self, author_id: &PlayerId, body: Str, created_at: DateTime<Utc>) -> Result<()> {
tracing::info!("Adding a message to room");
self.storage
@ -246,6 +258,7 @@ impl Room {
///
/// This is called after handling a client command.
/// Sending the update to the player who sent the command is handled by the player actor.
#[tracing::instrument(skip(self, update), name = "Room::broadcast_update")]
async fn broadcast_update(&self, update: Updates, except: &PlayerId) {
tracing::debug!("Broadcasting an update to {} subs", self.subscriptions.len());
for (player_id, sub) in &self.subscriptions {

View File

@ -507,11 +507,18 @@ async fn handle_registered_socket<'a>(
buffer.clear();
},
update = connection.receiver.recv() => {
if let Some(update) = update {
handle_update(&config, &user, &player_id, writer, &rooms, update).await?;
} else {
log::warn!("Player is terminated, must terminate the connection");
break;
match update {
Some(ConnectionMessage::Update(update)) => {
handle_update(&config, &user, &player_id, writer, &rooms, update).await?;
}
Some(ConnectionMessage::Stop(_)) => {
tracing::debug!("Connection is being terminated");
break;
}
None => {
log::warn!("Player is terminated, must terminate the connection");
break;
}
}
}
}
@ -678,6 +685,7 @@ enum HandleResult {
Leave,
}
#[tracing::instrument(skip_all, name = "handle_incoming_message")]
async fn handle_incoming_message(
buffer: &str,
config: &ServerConfig,

View File

@ -23,7 +23,7 @@ use tokio_rustls::rustls::{Certificate, PrivateKey};
use tokio_rustls::TlsAcceptor;
use lavina_core::auth::{Authenticator, Verdict};
use lavina_core::player::{PlayerConnection, PlayerId, PlayerRegistry};
use lavina_core::player::{ConnectionMessage, PlayerConnection, PlayerId, PlayerRegistry};
use lavina_core::prelude::*;
use lavina_core::repo::Storage;
use lavina_core::room::RoomRegistry;
@ -296,20 +296,19 @@ async fn socket_auth(
xml_writer.get_mut().flush().await?;
let auth: proto_xmpp::sasl::Auth = proto_xmpp::sasl::Auth::parse(xml_reader, reader_buf).await?;
proto_xmpp::sasl::Success.write_xml(xml_writer).await?;
xml_writer.get_mut().flush().await?;
match AuthBody::from_str(&auth.body) {
Ok(logopass) => {
let name = &logopass.login;
let verdict = Authenticator::new(storage).authenticate(name, &logopass.password).await?;
// TODO return proper XML errors to the client
match verdict {
Verdict::Authenticated => {}
Verdict::UserNotFound => {
return Err(anyhow!("no user found"));
Verdict::Authenticated => {
proto_xmpp::sasl::Success.write_xml(xml_writer).await?;
xml_writer.get_mut().flush().await?;
}
Verdict::InvalidPassword => {
Verdict::UserNotFound | Verdict::InvalidPassword => {
proto_xmpp::sasl::Failure.write_xml(xml_writer).await?;
xml_writer.get_mut().flush().await?;
return Err(anyhow!("incorrect credentials"));
}
}
@ -396,16 +395,23 @@ async fn socket_final(
true
},
update = conn.user_handle.receiver.recv() => {
if let Some(update) = update {
conn.handle_update(&mut events, update).await?;
for i in &events {
xml_writer.write_event_async(i).await?;
match update {
Some(ConnectionMessage::Update(update)) => {
conn.handle_update(&mut events, update).await?;
for i in &events {
xml_writer.write_event_async(i).await?;
}
events.clear();
xml_writer.get_mut().flush().await?;
}
Some(ConnectionMessage::Stop(_)) => {
tracing::debug!("Connection is being terminated");
break;
}
None => {
log::warn!("Player is terminated, must terminate the connection");
break;
}
events.clear();
xml_writer.get_mut().flush().await?;
} else {
log::warn!("Player is terminated, must terminate the connection");
break;
}
false
}
@ -428,6 +434,7 @@ struct XmppConnection<'a> {
}
impl<'a> XmppConnection<'a> {
#[tracing::instrument(skip(self, output, packet), name = "XmppConnection::handle_packet")]
async fn handle_packet(&mut self, output: &mut Vec<Event<'static>>, packet: ClientPacket) -> Result<bool> {
let res = match packet {
ClientPacket::Iq(iq) => {
@ -446,6 +453,7 @@ impl<'a> XmppConnection<'a> {
ServerStreamEnd.serialize(output);
true
}
ClientPacket::Eos => true,
};
Ok(res)
}

View File

@ -14,7 +14,7 @@ impl<'a> XmppConnection<'a> {
pub async fn handle_presence(&mut self, output: &mut Vec<Event<'static>>, p: Presence<Ignore>) -> Result<()> {
match p.to {
None => {
self.self_presence(output).await;
self.self_presence(output, p.r#type.as_deref()).await;
}
Some(Jid {
name: Some(name),
@ -33,21 +33,29 @@ impl<'a> XmppConnection<'a> {
Ok(())
}
async fn self_presence(&mut self, output: &mut Vec<Event<'static>>) {
let response = Presence::<()> {
to: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()),
}),
..Default::default()
};
response.serialize(output);
async fn self_presence(&mut self, output: &mut Vec<Event<'static>>, r#type: Option<&str>) {
match r#type {
Some("unavailable") => {
// do not print anything
}
None => {
let response = Presence::<()> {
to: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()),
}),
..Default::default()
};
response.serialize(output);
}
_ => todo!(),
}
}
async fn muc_presence(&mut self, name: Name, output: &mut Vec<Event<'static>>) -> Result<()> {

View File

@ -25,7 +25,7 @@ impl FromXml for IqClientBody {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let bytes = match event {
Event::Start(bytes) => bytes,
Event::Empty(bytes) => bytes,
@ -52,13 +52,14 @@ pub enum ClientPacket {
Message(Message<Ignore>),
Presence(Presence<Ignore>),
StreamEnd,
Eos,
}
impl FromXml for ClientPacket {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
match event {
Event::Start(bytes) | Event::Empty(bytes) => {
let name = bytes.name();
@ -83,6 +84,7 @@ impl FromXml for ClientPacket {
return Err(anyhow!("Unexpected XML event: {event:?}"));
}
}
Event::Eof => Ok(ClientPacket::Eos),
_ => {
return Err(anyhow!("Unexpected XML event: {event:?}"));
}

View File

@ -82,7 +82,7 @@ impl<'a> TestScopeTls<'a> {
fn new(stream: &'a mut TlsStream<TcpStream>, buffer: Vec<u8>) -> TestScopeTls<'a> {
let (reader, writer) = tokio::io::split(stream);
let reader = NsReader::from_reader(BufReader::new(reader));
let timeout = Duration::from_millis(100);
let timeout = Duration::from_millis(500);
TestScopeTls {
reader,
@ -203,6 +203,102 @@ async fn scenario_basic() -> Result<()> {
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"mechanisms"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"mechanism"));
assert_matches!(s.next_xml_event().await?, Event::Text(b) => assert_eq!(&*b, b"PLAIN"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"mechanism"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"mechanisms"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
// base64-encoded b"\x00tester\x00password"
s.send(r#"<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="PLAIN">AHRlc3RlcgBwYXNzd29yZA==</auth>"#)
.await?;
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"success"));
s.send(r#"<?xml version="1.0"?>"#).await?;
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"bind"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
s.send(r#"<iq id="bind_1" type="set"><bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>kek</resource></bind></iq>"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"iq"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"bind"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"jid"));
assert_matches!(s.next_xml_event().await?, Event::Text(b) => assert_eq!(&*b, b"tester@localhost/tester"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"jid"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"bind"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"iq"));
s.send(r#"<presence xmlns="jabber:client" type="unavailable"><status>Logged out</status></presence>"#).await?;
stream.shutdown().await?;
// wrap up
server.shutdown().await?;
Ok(())
}
#[tokio::test]
async fn scenario_wrong_password() -> Result<()> {
let mut server = TestServer::start().await?;
// test scenario
server.storage.create_user("tester").await?;
Authenticator::new(&server.storage).set_password("tester", "password").await?;
let mut stream = TcpStream::connect(server.server.addr).await?;
let mut s = TestScope::new(&mut stream);
tracing::info!("TCP connection established");
s.send(r#"<?xml version="1.0"?>"#).await?;
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"required"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
s.send(r#"<starttls/>"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed"));
let buffer = s.buffer;
tracing::info!("TLS feature negotiation complete");
let connector = TlsConnector::from(Arc::new(
ClientConfig::builder()
.with_safe_defaults()
.with_custom_certificate_verifier(Arc::new(IgnoreCertVerification))
.with_no_client_auth(),
));
tracing::info!("Initiating TLS connection...");
let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
tracing::info!("TLS connection established");
let mut s = TestScopeTls::new(&mut stream, buffer);
s.send(r#"<?xml version="1.0"?>"#).await?;
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"mechanisms"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"mechanism"));
assert_matches!(s.next_xml_event().await?, Event::Text(b) => assert_eq!(&*b, b"PLAIN"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"mechanism"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"mechanisms"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
// base64-encoded b"\x00tester\x00password2"
s.send(r#"<auth xmlns="urn:ietf:params:xml:ns:xmpp-sasl" mechanism="PLAIN">AHRlc3RlcgBwYXNzd29yZDI=</auth>"#)
.await?;
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"failure"));
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"not-authorized"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"failure"));
stream.shutdown().await?;
// wrap up

View File

@ -82,7 +82,7 @@ impl FromXml for BindRequest {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut resource: Option<Str> = None;
let Event::Start(bytes) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
@ -97,15 +97,15 @@ impl FromXml for BindRequest {
return Err(anyhow!("Incorrect namespace"));
}
loop {
let (namespace, event) = yield;
(namespace, event) = yield;
match event {
Event::Start(bytes) if bytes.name().0 == b"resource" => {
let (namespace, event) = yield;
(namespace, event) = yield;
let Event::Text(text) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
};
resource = Some(std::str::from_utf8(&*text)?.into());
let (namespace, event) = yield;
(namespace, event) = yield;
let Event::End(bytes) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
};

View File

@ -378,7 +378,7 @@ impl<T: FromXml> Parser for IqParser<T> {
}
},
IqParserInner::Final(state) => {
if let Event::End(ref bytes) = event {
if let Event::End(_) = event {
let id = fail_fast!(state.id.ok_or_else(|| ffail!("No id provided")));
let r#type = fail_fast!(state.r#type.ok_or_else(|| ffail!("No type provided")));
let body = fail_fast!(state.body.ok_or_else(|| ffail!("No body provided")));
@ -528,7 +528,7 @@ impl<T: FromXml> FromXml for Presence<T> {
type P = impl Parser<Output = Result<Presence<T>>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let (bytes, end) = match event {
Event::Start(bytes) => (bytes, false),
Event::Empty(bytes) => (bytes, true),
@ -557,37 +557,37 @@ impl<T: FromXml> FromXml for Presence<T> {
return Ok(p);
}
loop {
let (namespace, event) = yield;
(namespace, event) = yield;
match event {
Event::Start(bytes) => match bytes.name().0 {
b"show" => {
let (_, event) = yield;
(namespace, event) = yield;
let Event::Text(bytes) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
let i = PresenceShow::from_str(bytes)?;
p.show = Some(i);
let (_, event) = yield;
(namespace, event) = yield;
let Event::End(_) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
}
b"status" => {
let (_, event) = yield;
(namespace, event) = yield;
let Event::Text(bytes) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
let s = std::str::from_utf8(bytes)?;
p.status.push(s.to_string());
let (_, event) = yield;
(namespace, event) = yield;
let Event::End(_) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
}
b"priority" => {
let (_, event) = yield;
(namespace, event) = yield;
let Event::Text(bytes) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
@ -595,7 +595,7 @@ impl<T: FromXml> FromXml for Presence<T> {
let i = s.parse()?;
p.priority = Some(PresencePriority(i));
let (_, event) = yield;
(namespace, event) = yield;
let Event::End(_) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};

View File

@ -21,7 +21,7 @@ impl FromXml for InfoQuery {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut node = None;
let mut identity = vec![];
let mut feature = vec![];
@ -48,7 +48,7 @@ impl FromXml for InfoQuery {
});
}
loop {
let (namespace, event) = yield;
(namespace, event) = yield;
let bytes = match event {
Event::Start(bytes) => bytes,
Event::Empty(bytes) => bytes,
@ -141,7 +141,7 @@ impl FromXml for Identity {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut category = None;
let mut name = None;
let mut r#type = None;
@ -179,8 +179,8 @@ impl FromXml for Identity {
return Ok(item);
}
let (namespace, event) = yield;
let Event::End(bytes) = event else {
(namespace, event) = yield;
let Event::End(_) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
Ok(item)
@ -209,7 +209,7 @@ impl FromXml for Feature {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut var = None;
let (bytes, end) = match event {
Event::Start(bytes) => (bytes, false),
@ -234,8 +234,8 @@ impl FromXml for Feature {
return Ok(item);
}
let (namespace, event) = yield;
let Event::End(bytes) = event else {
(namespace, event) = yield;
let Event::End(_) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
Ok(item)
@ -258,9 +258,9 @@ impl FromXml for ItemQuery {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut item = vec![];
let (bytes, end) = match event {
let (_, end) = match event {
Event::Start(bytes) => (bytes, false),
Event::Empty(bytes) => (bytes, true),
_ => return Err(ffail!("Unexpected XML event: {event:?}")),
@ -269,7 +269,7 @@ impl FromXml for ItemQuery {
return Ok(ItemQuery { item });
}
loop {
let (namespace, event) = yield;
(namespace, event) = yield;
let bytes = match event {
Event::Start(bytes) => bytes,
Event::Empty(bytes) => bytes,
@ -296,7 +296,7 @@ impl FromXmlTag for ItemQuery {
impl ToXml for ItemQuery {
fn serialize(&self, events: &mut Vec<Event<'static>>) {
let mut bytes = BytesStart::new(format!(r#"query xmlns="{}""#, XMLNS_ITEM));
let bytes = BytesStart::new(format!(r#"query xmlns="{}""#, XMLNS_ITEM));
let empty = self.item.is_empty();
if empty {
events.push(Event::Empty(bytes));
@ -342,7 +342,7 @@ impl FromXml for Item {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(_, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut jid = None;
let mut name = None;
let mut node = None;
@ -378,8 +378,8 @@ impl FromXml for Item {
return Ok(item);
}
let (namespace, event) = yield;
let Event::End(bytes) = event else {
(_, event) = yield;
let Event::End(_) = event else {
return Err(ffail!("Unexpected XML event: {event:?}"));
};
Ok(item)

View File

@ -19,7 +19,7 @@ impl FromXml for History {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut history = History::default();
let (bytes, end) = match event {
Event::Start(bytes) if bytes.name().0 == Self::NAME.as_bytes() => (bytes, false),
@ -51,7 +51,7 @@ impl FromXml for History {
return Ok(history);
}
let (namespace, event) = yield;
(namespace, event) = yield;
let Event::End(bytes) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
};
@ -73,17 +73,17 @@ impl FromXml for Password {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let bytes = match event {
Event::Start(bytes) if bytes.name().0 == Self::NAME.as_bytes() => bytes,
_ => return Err(anyhow!("Unexpected XML event: {event:?}")),
};
let (namespace, event) = yield;
(namespace, event) = yield;
let Event::Text(bytes) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
};
let s = std::str::from_utf8(bytes)?.to_string();
let (namespace, event) = yield;
(namespace, event) = yield;
let Event::End(bytes) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
};
@ -108,7 +108,7 @@ impl FromXml for X {
type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let mut res = X::default();
let (_, end) = match event {
Event::Start(bytes) => (bytes, false),
@ -120,7 +120,7 @@ impl FromXml for X {
}
loop {
let (namespace, event) = yield;
(namespace, event) = yield;
let bytes = match event {
Event::Start(bytes) => bytes,
Event::Empty(bytes) => bytes,

View File

@ -1,7 +1,7 @@
use std::borrow::Borrow;
use anyhow::{anyhow, Result};
use quick_xml::events::{BytesStart, Event};
use quick_xml::events::{BytesEnd, BytesStart, Event};
use quick_xml::{NsReader, Writer};
use tokio::io::{AsyncBufRead, AsyncWrite};
@ -74,3 +74,16 @@ impl Success {
Ok(())
}
}
pub struct Failure;
impl Failure {
pub async fn write_xml(&self, writer: &mut Writer<impl AsyncWrite + Unpin>) -> Result<()> {
let event = BytesStart::new(r#"failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl""#);
writer.write_event_async(Event::Start(event)).await?;
let event = BytesStart::new(r#"not-authorized"#);
writer.write_event_async(Event::Empty(event)).await?;
let event = BytesEnd::new(r#"failure"#);
writer.write_event_async(Event::End(event)).await?;
Ok(())
}
}

View File

@ -10,9 +10,38 @@ use anyhow::Result;
mod ignore;
pub use ignore::Ignore;
/// Types which can be parsed from an XML input stream.
///
/// Example:
/// ```
/// #![feature(type_alias_impl_trait)]
/// #![feature(impl_trait_in_assoc_type)]
/// #![feature(coroutines)]
/// # use proto_xmpp::xml::FromXml;
/// # use quick_xml::events::Event;
/// # use quick_xml::name::ResolveResult;
/// # use proto_xmpp::xml::Parser;
/// # use anyhow::Result;
///
/// struct MyStruct;
/// impl FromXml for MyStruct {
/// type P = impl Parser<Output = Result<Self>>;
///
/// fn parse() -> Self::P {
/// |(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
/// (namespace, event) = yield;
/// Ok(MyStruct)
/// }
/// }
/// }
/// ```
pub trait FromXml: Sized {
/// The type of parser instances.
///
/// If the result type of the [parse] is anonymous, this type member can be defined by using `impl Trait`.
type P: Parser<Output = Result<Self>>;
/// Creates a new instance of a parser with an initial state.
fn parse() -> Self::P;
}
@ -25,9 +54,18 @@ pub trait FromXmlTag: FromXml {
const NS: &'static str;
}
/// A stateful parser instance which consumes XML events until the parsing is complete.
///
/// Usually implemented with the experimental coroutine syntax, which yields to consume the next XML event,
/// and returns the final result when the parsing is done.
pub trait Parser: Sized {
type Output;
/// Advance the parsing by one XML event.
///
/// This method consumes `self`, but if the parsing is incomplete,
/// it will return the next state of the parser in the returned result.
/// Otherwise, it will return the final result of parsing.
fn consume<'a>(self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output>;
}
@ -50,8 +88,11 @@ where
}
}
/// The result of a single parser iteration.
pub enum Continuation<Parser, Res> {
/// The parsing is complete and the final result is available.
Final(Res),
/// The parsing is not complete and more XML events are required.
Continue(Parser),
}
@ -89,8 +130,8 @@ macro_rules! delegate_parsing {
Continuation::Final(Ok(res)) => break Ok(res.into()),
Continuation::Final(Err(err)) => break Err(err),
Continuation::Continue(p) => {
let (namespace, event) = yield;
parser = p.consume(namespace, event);
($namespace, $event) = yield;
parser = p.consume($namespace, $event);
}
}
}

View File

@ -23,6 +23,11 @@ hostname = "localhost"
[storage]
db_path = "db.sqlite"
[tracing]
# otlp grpc endpoint
endpoint = "http://jaeger:4317"
service_name = "lavina"
```
## With Docker Compose
@ -41,6 +46,15 @@ services:
- '5222:5222' # xmpp
- '6667:6667' # irc non-tls
- '127.0.0.1:1380:8080' # management http (private)
# if you want to observe traces
jaeger:
image: "jaegertracing/all-in-one:1.56"
ports:
- "16686:16686" # web ui
- "4317:4317" # grpc ingest endpoint
environment:
- COLLECTOR_OTLP_ENABLED=true
- SPAN_STORAGE_TYPE=memory
```
## With Cargo

View File

@ -111,14 +111,7 @@ async fn endpoint_create_player(
) -> Result<Response<Full<Bytes>>> {
let str = request.collect().await?.to_bytes();
let Ok(res) = serde_json::from_slice::<CreatePlayerRequest>(&str[..]) else {
let payload = ErrorResponse {
code: errors::MALFORMED_REQUEST,
message: "The request payload contains incorrect JSON value",
}
.to_body();
let mut response = Response::new(payload);
*response.status_mut() = StatusCode::BAD_REQUEST;
return Ok(response);
return Ok(malformed_request());
};
storage.create_user(&res.name).await?;
log::info!("Player {} created", res.name);
@ -129,18 +122,11 @@ async fn endpoint_create_player(
async fn endpoint_set_password(
request: Request<hyper::body::Incoming>,
mut storage: Storage,
storage: Storage,
) -> Result<Response<Full<Bytes>>> {
let str = request.collect().await?.to_bytes();
let Ok(res) = serde_json::from_slice::<ChangePasswordRequest>(&str[..]) else {
let payload = ErrorResponse {
code: errors::MALFORMED_REQUEST,
message: "The request payload contains incorrect JSON value",
}
.to_body();
let mut response = Response::new(payload);
*response.status_mut() = StatusCode::BAD_REQUEST;
return Ok(response);
return Ok(malformed_request());
};
let verdict = Authenticator::new(&storage).set_password(&res.player_name, &res.password).await?;
match verdict {
@ -173,19 +159,28 @@ pub fn not_found() -> Response<Full<Bytes>> {
response
}
fn malformed_request() -> Response<Full<Bytes>> {
let payload = ErrorResponse {
code: errors::MALFORMED_REQUEST,
message: "The request payload contains incorrect JSON value",
}
.to_body();
let mut response = Response::new(payload);
*response.status_mut() = StatusCode::BAD_REQUEST;
return response;
}
trait Or5xx {
fn or5xx(self) -> Response<Full<Bytes>>;
}
impl Or5xx for Result<Response<Full<Bytes>>> {
fn or5xx(self) -> Response<Full<Bytes>> {
match self {
Ok(e) => e,
Err(e) => {
let mut response = Response::new(Full::new(e.to_string().into()));
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
response
}
}
self.unwrap_or_else(|e| {
let mut response = Response::new(Full::new(e.to_string().into()));
*response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
response
})
}
}

View File

@ -6,8 +6,17 @@ use std::path::Path;
use clap::Parser;
use figment::providers::Format;
use figment::{providers::Toml, Figment};
use opentelemetry::KeyValue;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::trace::{BatchConfig, RandomIdGenerator, Sampler};
use opentelemetry_sdk::{runtime, Resource};
use opentelemetry_semantic_conventions::resource::SERVICE_NAME;
use opentelemetry_semantic_conventions::SCHEMA_URL;
use prometheus::Registry as MetricsRegistry;
use serde::Deserialize;
use tracing_opentelemetry::OpenTelemetryLayer;
use tracing_subscriber::fmt::Subscriber;
use tracing_subscriber::prelude::*;
use lavina_core::prelude::*;
use lavina_core::repo::Storage;
@ -19,6 +28,13 @@ struct ServerConfig {
irc: projection_irc::ServerConfig,
xmpp: projection_xmpp::ServerConfig,
storage: lavina_core::repo::StorageConfig,
tracing: Option<TracingConfig>,
}
#[derive(Deserialize, Debug)]
struct TracingConfig {
endpoint: String,
service_name: String,
}
#[derive(Parser)]
@ -36,9 +52,9 @@ fn load_config() -> Result<ServerConfig> {
#[tokio::main]
async fn main() -> Result<()> {
set_up_logging()?;
let sleep = ctrl_c()?;
let config = load_config()?;
set_up_logging(&config.tracing)?;
tracing::info!("Booting up");
tracing::info!("Loaded config: {config:?}");
@ -47,6 +63,7 @@ async fn main() -> Result<()> {
irc: irc_config,
xmpp: xmpp_config,
storage: storage_config,
tracing: _,
} = config;
let metrics = MetricsRegistry::new();
let storage = Storage::open(storage_config).await?;
@ -87,7 +104,44 @@ fn ctrl_c() -> Result<impl Future<Output = ()>> {
Ok(recv(chan))
}
fn set_up_logging() -> Result<()> {
tracing_subscriber::fmt::init();
fn set_up_logging(tracing_config: &Option<TracingConfig>) -> Result<()> {
let subscriber = tracing_subscriber::registry().with(tracing_subscriber::fmt::layer());
let targets = {
use std::{env, str::FromStr};
use tracing_subscriber::filter::Targets;
match env::var("RUST_LOG") {
Ok(var) => Targets::from_str(&var)
.map_err(|e| {
eprintln!("Ignoring `RUST_LOG={:?}`: {}", var, e);
})
.unwrap_or_default(),
Err(env::VarError::NotPresent) => Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL),
Err(e) => {
eprintln!("Ignoring `RUST_LOG`: {}", e);
Targets::new().with_default(Subscriber::DEFAULT_MAX_LEVEL)
}
}
};
if let Some(config) = tracing_config {
let trace_config = opentelemetry_sdk::trace::Config::default()
.with_sampler(Sampler::ParentBased(Box::new(Sampler::TraceIdRatioBased(1.0))))
.with_id_generator(RandomIdGenerator::default())
.with_resource(Resource::from_schema_url(
[KeyValue::new(SERVICE_NAME, config.service_name.to_string())],
SCHEMA_URL,
));
let trace_exporter = opentelemetry_otlp::new_exporter().tonic().with_endpoint(&config.endpoint);
let tracer = opentelemetry_otlp::new_pipeline()
.tracing()
.with_trace_config(trace_config)
.with_batch_config(BatchConfig::default())
.with_exporter(trace_exporter)
.install_batch(runtime::Tokio)?;
let subscriber = subscriber.with(OpenTelemetryLayer::new(tracer));
targets.with_subscriber(subscriber).try_init()?;
} else {
targets.with_subscriber(subscriber).try_init()?;
}
Ok(())
}