forked from lavina/lavina
1
0
Fork 0

Compare commits

...

10 Commits

40 changed files with 791 additions and 420 deletions

View File

@ -0,0 +1,19 @@
name: check-and-test
on: [push, pull_request]
jobs:
check-and-test:
runs-on: ubuntu-latest
steps:
- name: git checkout repository
uses: actions/checkout@v4
- name: setup rust
uses: https://github.com/actions-rs/toolchain@v1
- name: cargo check
uses: https://github.com/actions-rs/cargo@v1
with:
command: check
- name: test
uses: https://github.com/actions-rs/cargo@v1
with:
command: test
args: --workspace -- --skip projections::irc

363
Cargo.lock generated
View File

@ -44,6 +44,54 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
[[package]]
name = "anstream"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f58811cfac344940f1a400b6e6231ce35171f614f26439e80f8c1465c5cc0c"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b84bf0a05bbb2a83e5eb6fa36bb6e87baa08193c35ff52bbf6b38d8af2890e46"
[[package]]
name = "anstyle-parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "938874ff5980b03a87c5524b3ae5b59cf99b1d6bc836848df7bc5ada9643c333"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58f54d10c6dfa51283a066ceab3ec1ab78d13fae00aa49243a45e4571fb79dfd"
dependencies = [
"anstyle",
"windows-sys",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.75" version = "1.0.75"
@ -161,6 +209,52 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "4.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1d7b8d5ec32af0fadc644bf1fd509a688c2103b185644bb1e29d164e0703136"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5179bb514e4d7c2051749d8fcefa2ed6d06a9f4e6d69faf3805f5d80b8cf8d56"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0862016ff20d69b84ef8247369fabf5c008a7417002411897d40ee1f4532b873"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.29",
]
[[package]]
name = "clap_lex"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961"
[[package]]
name = "colorchoice"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
[[package]] [[package]]
name = "const-oid" name = "const-oid"
version = "0.9.5" version = "0.9.5"
@ -277,15 +371,6 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "encoding_rs"
version = "0.8.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7268b386296a025e474d5140678f75d6de9493ae55a5d709eeb9dd08149945e1"
dependencies = [
"cfg-if",
]
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.1" version = "1.0.1"
@ -488,31 +573,6 @@ version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0" checksum = "6fb8d784f27acf97159b40fc4db5ecd8aa23b9ad5ef69cdd136d3bc80665f0c0"
[[package]]
name = "h2"
version = "0.3.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91fc23aa11be92976ef4729127f1a74adf36d8436f7816b185d18df956790833"
dependencies = [
"bytes",
"fnv",
"futures-core",
"futures-sink",
"futures-util",
"http",
"indexmap 1.9.3",
"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]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.14.0" version = "0.14.0"
@ -529,7 +589,7 @@ version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "312f66718a2d7789ffef4f4b7b213138ed9f1eb3aa1d0d82fc99f88fb3ffd26f" checksum = "312f66718a2d7789ffef4f4b7b213138ed9f1eb3aa1d0d82fc99f88fb3ffd26f"
dependencies = [ dependencies = [
"hashbrown 0.14.0", "hashbrown",
] ]
[[package]] [[package]]
@ -591,17 +651,6 @@ dependencies = [
"itoa", "itoa",
] ]
[[package]]
name = "http-body"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1"
dependencies = [
"bytes",
"http",
"pin-project-lite",
]
[[package]] [[package]]
name = "http-body" name = "http-body"
version = "1.0.0-rc.2" version = "1.0.0-rc.2"
@ -621,7 +670,7 @@ dependencies = [
"bytes", "bytes",
"futures-util", "futures-util",
"http", "http",
"http-body 1.0.0-rc.2", "http-body",
"pin-project-lite", "pin-project-lite",
] ]
@ -637,30 +686,6 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "0.14.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468"
dependencies = [
"bytes",
"futures-channel",
"futures-core",
"futures-util",
"h2",
"http",
"http-body 0.4.5",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"socket2 0.4.9",
"tokio",
"tower-service",
"tracing",
"want",
]
[[package]] [[package]]
name = "hyper" name = "hyper"
version = "1.0.0-rc.3" version = "1.0.0-rc.3"
@ -672,7 +697,7 @@ dependencies = [
"futures-core", "futures-core",
"futures-util", "futures-util",
"http", "http",
"http-body 1.0.0-rc.2", "http-body",
"httparse", "httparse",
"httpdate", "httpdate",
"itoa", "itoa",
@ -692,16 +717,6 @@ dependencies = [
"unicode-normalization", "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]] [[package]]
name = "indexmap" name = "indexmap"
version = "2.0.0" version = "2.0.0"
@ -709,7 +724,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown 0.14.0", "hashbrown",
] ]
[[package]] [[package]]
@ -718,12 +733,6 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb"
[[package]]
name = "ipnet"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6"
[[package]] [[package]]
name = "itertools" name = "itertools"
version = "0.10.5" version = "0.10.5"
@ -754,18 +763,19 @@ version = "0.0.1-dev"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"assert_matches", "assert_matches",
"clap",
"derive_more", "derive_more",
"figment", "figment",
"futures-util", "futures-util",
"http-body-util", "http-body-util",
"hyper 1.0.0-rc.3", "hyper",
"lazy_static", "mgmt-api",
"nom",
"nonempty", "nonempty",
"prometheus", "prometheus",
"proto-irc",
"proto-xmpp",
"quick-xml", "quick-xml",
"regex", "regex",
"reqwest",
"rustls-pemfile", "rustls-pemfile",
"serde", "serde",
"serde_json", "serde_json",
@ -847,10 +857,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]] [[package]]
name = "mime" name = "mgmt-api"
version = "0.3.17" version = "0.0.1-dev"
source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" "serde",
]
[[package]] [[package]]
name = "minimal-lexical" name = "minimal-lexical"
@ -1151,6 +1162,30 @@ dependencies = [
"thiserror", "thiserror",
] ]
[[package]]
name = "proto-irc"
version = "0.0.1-dev"
dependencies = [
"anyhow",
"assert_matches",
"futures-util",
"nom",
"nonempty",
"tokio",
]
[[package]]
name = "proto-xmpp"
version = "0.0.1-dev"
dependencies = [
"anyhow",
"derive_more",
"lazy_static",
"quick-xml",
"regex",
"tokio",
]
[[package]] [[package]]
name = "quick-xml" name = "quick-xml"
version = "0.30.0" version = "0.30.0"
@ -1238,40 +1273,6 @@ version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da" checksum = "dbb5fb1acd8a1a18b3dd5be62d25485eb770e05afb408a9627d14d451bae12da"
[[package]]
name = "reqwest"
version = "0.11.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1"
dependencies = [
"base64",
"bytes",
"encoding_rs",
"futures-core",
"futures-util",
"h2",
"http",
"http-body 0.4.5",
"hyper 0.14.27",
"ipnet",
"js-sys",
"log",
"mime",
"once_cell",
"percent-encoding",
"pin-project-lite",
"serde",
"serde_json",
"serde_urlencoded",
"tokio",
"tower-service",
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"winreg",
]
[[package]] [[package]]
name = "ring" name = "ring"
version = "0.16.20" version = "0.16.20"
@ -1436,18 +1437,6 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]] [[package]]
name = "sha1" name = "sha1"
version = "0.10.5" version = "0.10.5"
@ -1498,6 +1487,24 @@ dependencies = [
"rand_core", "rand_core",
] ]
[[package]]
name = "sim-irc"
version = "0.0.1-dev"
dependencies = [
"anyhow",
"clap",
"http-body-util",
"hyper",
"mgmt-api",
"proto-irc",
"rand",
"serde",
"serde_json",
"tokio",
"tracing",
"tracing-subscriber",
]
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.9" version = "0.4.9"
@ -1513,16 +1520,6 @@ version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9"
[[package]]
name = "socket2"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64a4a911eed85daf18834cfaa86a79b7d266ff93ff5ba14005426219480ed662"
dependencies = [
"libc",
"winapi",
]
[[package]] [[package]]
name = "socket2" name = "socket2"
version = "0.5.3" version = "0.5.3"
@ -1604,7 +1601,7 @@ dependencies = [
"futures-util", "futures-util",
"hashlink", "hashlink",
"hex", "hex",
"indexmap 2.0.0", "indexmap",
"log", "log",
"memchr", "memchr",
"once_cell", "once_cell",
@ -1770,6 +1767,12 @@ dependencies = [
"unicode-normalization", "unicode-normalization",
] ]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]] [[package]]
name = "subtle" name = "subtle"
version = "2.5.0" version = "2.5.0"
@ -1870,7 +1873,7 @@ dependencies = [
"parking_lot", "parking_lot",
"pin-project-lite", "pin-project-lite",
"signal-hook-registry", "signal-hook-registry",
"socket2 0.5.3", "socket2",
"tokio-macros", "tokio-macros",
"windows-sys", "windows-sys",
] ]
@ -1896,20 +1899,6 @@ dependencies = [
"tokio", "tokio",
] ]
[[package]]
name = "tokio-util"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "806fe8c2c87eccc8b3267cbae29ed3ab2d0bd37fca70ab622e46aaa9375ddb7d"
dependencies = [
"bytes",
"futures-core",
"futures-sink",
"pin-project-lite",
"tokio",
"tracing",
]
[[package]] [[package]]
name = "toml" name = "toml"
version = "0.7.6" version = "0.7.6"
@ -1937,19 +1926,13 @@ version = "0.19.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a" checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a"
dependencies = [ dependencies = [
"indexmap 2.0.0", "indexmap",
"serde", "serde",
"serde_spanned", "serde_spanned",
"toml_datetime", "toml_datetime",
"winnow", "winnow",
] ]
[[package]]
name = "tower-service"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.37" version = "0.1.37"
@ -2080,6 +2063,12 @@ dependencies = [
"percent-encoding", "percent-encoding",
] ]
[[package]]
name = "utf8parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.4.1" version = "1.4.1"
@ -2147,18 +2136,6 @@ dependencies = [
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.87" version = "0.2.87"
@ -2301,16 +2278,6 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "winreg"
version = "0.50.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
dependencies = [
"cfg-if",
"windows-sys",
]
[[package]] [[package]]
name = "yansi" name = "yansi"
version = "1.0.0-rc.1" version = "1.0.0-rc.1"

View File

@ -1,33 +1,63 @@
[workspace]
members = [
".",
"crates/proto-irc",
"crates/sim-irc",
"crates/proto-xmpp",
"crates/mgmt-api",
]
[workspace.package]
version = "0.0.1-dev"
[workspace.dependencies]
nom = "7.1.3"
assert_matches = "1.5.0"
tokio = { version = "1.24.1", features = ["full"] } # async runtime
futures-util = "0.3.25"
anyhow = "1.0.68" # error utils
nonempty = "0.8.1"
quick-xml = { version = "0.30.0", features = ["async-tokio"] }
lazy_static = "1.4.0"
regex = "1.7.1"
derive_more = "0.99.17"
clap = { version = "4.4.4", features = ["derive"] }
serde = { version = "1.0.152", features = ["rc", "serde_derive"] }
tracing = "0.1.37" # logging & tracing api
tracing-subscriber = "0.3.16"
http-body-util = "0.1.0-rc.3"
serde_json = "1.0.93"
[package] [package]
name = "lavina" name = "lavina"
version = "0.0.1-dev" version.workspace = true
edition = "2021" edition = "2021"
publish = false publish = false
[dependencies] [dependencies]
anyhow = "1.0.68" # error utils anyhow.workspace = true
figment = { version = "0.10.8", features = ["env", "toml"] } # configuration files figment = { version = "0.10.8", features = ["env", "toml"] } # configuration files
hyper = { version = "1.0.0-rc.3,<1.0.0-rc.4", features = ["server", "http1"] } # http server hyper = { version = "1.0.0-rc.3,<1.0.0-rc.4", features = ["server", "http1"] } # http server
http-body-util = "0.1.0-rc.3" http-body-util.workspace = true
serde = { version = "1.0.152", features = ["rc", "serde_derive"] } serde.workspace = true
serde_json = "1.0.93" serde_json.workspace = true
tokio = { version = "1.24.1", features = ["full"] } # async runtime tokio.workspace = true
tracing = "0.1.37" # logging & tracing api tracing.workspace = true
tracing-subscriber = "0.3.16" tracing-subscriber.workspace = true
futures-util = "0.3.25" futures-util.workspace = true
prometheus = { version = "0.13.3", default-features = false } prometheus = { version = "0.13.3", default-features = false }
regex = "1.7.1" nonempty.workspace = true
lazy_static = "1.4.0"
nom = "7.1.3"
nonempty = "0.8.1"
tokio-rustls = "0.24.1" tokio-rustls = "0.24.1"
rustls-pemfile = "1.0.2" rustls-pemfile = "1.0.2"
quick-xml = { version = "0.30.0", features = ["async-tokio"] } quick-xml.workspace = true
derive_more = "0.99.17" derive_more.workspace = true
uuid = { version = "1.3.0", features = ["v4"] } uuid = { version = "1.3.0", features = ["v4"] }
sqlx = { version = "0.7.0-alpha.2", features = ["sqlite", "migrate"] } sqlx = { version = "0.7.0-alpha.2", features = ["sqlite", "migrate"] }
proto-irc = { path = "crates/proto-irc" }
proto-xmpp = { path = "crates/proto-xmpp" }
mgmt-api = { path = "crates/mgmt-api" }
clap.workspace = true
[dev-dependencies] [dev-dependencies]
assert_matches = "1.5.0" assert_matches.workspace = true
regex = "1.7.1" regex = "1.7.1"
reqwest = { version = "0.11", default-features = false }

View File

@ -0,0 +1,8 @@
[package]
name = "mgmt-api"
edition = "2021"
version.workspace = true
publish = false
[dependencies]
serde.workspace = true

View File

@ -0,0 +1,29 @@
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct ErrorResponse<'a> {
pub code: &'a str,
pub message: &'a str,
}
#[derive(Serialize, Deserialize)]
pub struct CreatePlayerRequest<'a> {
pub name: &'a str,
}
#[derive(Serialize, Deserialize)]
pub struct ChangePasswordRequest<'a> {
pub player_name: &'a str,
pub password: &'a str,
}
pub mod paths {
pub const CREATE_PLAYER: &'static str = "/mgmt/create_player";
pub const SET_PASSWORD: &'static str = "/mgmt/set_password";
}
pub mod errors {
pub const INVALID_PATH: &'static str = "invalid_path";
pub const MALFORMED_REQUEST: &'static str = "malformed_request";
pub const PLAYER_NOT_FOUND: &'static str = "player_not_found";
}

View File

@ -0,0 +1,15 @@
[package]
name = "proto-irc"
edition = "2021"
version.workspace = true
publish = false
[dependencies]
nom.workspace = true
nonempty.workspace = true
tokio.workspace = true
futures-util.workspace = true
anyhow.workspace = true
[dev-dependencies]
assert_matches.workspace = true

View File

@ -1,10 +1,13 @@
//! Client-to-Server IRC protocol. //! Client-to-Server IRC protocol.
pub mod client; pub mod client;
mod prelude;
pub mod server; pub mod server;
#[cfg(test)]
mod testkit;
pub mod user; pub mod user;
use std::io::Result;
use crate::prelude::Str; use crate::prelude::Str;
use std::io::Result;
use nom::{ use nom::{
branch::alt, branch::alt,
@ -101,7 +104,7 @@ mod test {
use assert_matches::*; use assert_matches::*;
use super::*; use super::*;
use crate::util::testkit::*; use crate::testkit::*;
#[test] #[test]
fn test_chan_global() { fn test_chan_global() {

View File

@ -0,0 +1,3 @@
use std::sync::Arc;
pub type Str = Arc<str>;

View File

@ -3,7 +3,7 @@ use tokio::io::AsyncWrite;
use tokio::io::AsyncWriteExt; use tokio::io::AsyncWriteExt;
use super::*; use super::*;
use crate::protos::irc::user::PrefixedNick; use crate::user::PrefixedNick;
/// Server-to-client message. /// Server-to-client message.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
@ -287,7 +287,9 @@ impl ServerMessageBody {
chan.write_async(writer).await?; chan.write_async(writer).await?;
writer.write_all(b" :").await?; writer.write_all(b" :").await?;
for member in members { for member in members {
writer.write_all(member.prefix.to_string().as_bytes()).await?; writer
.write_all(member.prefix.to_string().as_bytes())
.await?;
writer.write_all(member.nick.as_bytes()).await?; writer.write_all(member.nick.as_bytes()).await?;
writer.write_all(b" ").await?; writer.write_all(b" ").await?;
} }
@ -387,7 +389,7 @@ mod test {
use assert_matches::*; use assert_matches::*;
use super::*; use super::*;
use crate::util::testkit::*; use crate::testkit::*;
#[test] #[test]
fn test_server_message_notice() { fn test_server_message_notice() {

View File

@ -0,0 +1,16 @@
use std::future::Future;
use std::task::{Context, Poll};
use futures_util::task::noop_waker_ref;
use tokio::pin;
pub fn sync_future<T>(future: impl Future<Output = T>) -> anyhow::Result<T> {
let waker = noop_waker_ref();
let mut context = Context::from_waker(waker);
pin!(future);
if let Poll::Ready(a) = future.poll(&mut context) {
Ok(a)
} else {
Err(anyhow::Error::msg("Future has suspended"))
}
}

View File

@ -1,6 +1,5 @@
use super::*; use super::*;
use std::fmt; use std::fmt;
use crate::core::player::PlayerId;
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
pub enum Prefix { pub enum Prefix {
@ -23,10 +22,9 @@ pub struct PrefixedNick {
impl PrefixedNick { impl PrefixedNick {
pub fn from_str(nick: Str) -> PrefixedNick { pub fn from_str(nick: Str) -> PrefixedNick {
PrefixedNick { prefix: Prefix::Empty, nick } PrefixedNick {
prefix: Prefix::Empty,
nick,
}
} }
}
pub fn from_player_id(id: PlayerId) -> PrefixedNick {
PrefixedNick { prefix: Prefix::Empty, nick: id.into_inner() }
}
}

View File

@ -0,0 +1,12 @@
[package]
name = "proto-xmpp"
edition = "2021"
version.workspace = true
[dependencies]
quick-xml.workspace = true
lazy_static.workspace = true
regex.workspace = true
anyhow.workspace = true
tokio.workspace = true
derive_more.workspace = true

View File

@ -1,11 +1,11 @@
use std::fmt::Display; use std::fmt::Display;
use nom::AsBytes; use anyhow::{anyhow, Result};
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event}; use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::name::{Namespace, ResolveResult}; use quick_xml::name::{Namespace, ResolveResult};
use crate::prelude::*; use crate::prelude::*;
use crate::util::xml::*; use crate::xml::*;
pub const XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-bind"; pub const XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-bind";
@ -49,7 +49,7 @@ impl Jid {
} }
let m = RE let m = RE
.captures(i) .captures(i)
.ok_or(ffail!("Incorrectly format jid: {i}"))?; .ok_or(anyhow!("Incorrectly format jid: {i}"))?;
let name = m.get(2).map(|name| Name(name.as_str().into())); let name = m.get(2).map(|name| Name(name.as_str().into()));
let server = m.get(3).unwrap(); let server = m.get(3).unwrap();
@ -78,89 +78,56 @@ impl Jid {
#[derive(PartialEq, Eq, Debug)] #[derive(PartialEq, Eq, Debug)]
pub struct BindRequest(pub Resource); pub struct BindRequest(pub Resource);
pub struct BindRequestParser(BindRequestParserInner);
enum BindRequestParserInner {
Initial,
/// Consumed <bind> start and expects <resource>
InBind(Option<String>),
/// Consumed <resource> start
InBindResourceInitial,
/// Consumer <resource> start and inner text
InBindResourceEnd(String),
}
impl FromXmlTag for BindRequest { impl FromXmlTag for BindRequest {
const NS: &'static str = XMLNS; const NS: &'static str = XMLNS;
const NAME: &'static str = "bind"; const NAME: &'static str = "bind";
} }
impl FromXml for BindRequest { impl FromXml for BindRequest {
type P = BindRequestParser; type P = impl Parser<Output = Result<Self>>;
fn parse() -> Self::P { fn parse() -> Self::P {
BindRequestParser(BindRequestParserInner::Initial) |(namespace, 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:?}"));
// TODO rewrite as a generator };
impl Parser for BindRequestParser { if bytes.name().0 != BindRequest::NAME.as_bytes() {
type Output = Result<BindRequest>; return Err(anyhow!("Unexpected XML tag: {:?}", bytes.name()));
fn consume<'a>(
self: Self,
namespace: ResolveResult,
event: &Event<'a>,
) -> Continuation<Self, Self::Output> {
// TODO validate tag names and namespaces
use BindRequestParserInner::*;
match self.0 {
Initial => {
let Event::Start(bytes) = event else {
return Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}")));
};
if bytes.name().0 != BindRequest::NAME.as_bytes() {
return Continuation::Final(Err(ffail!(
"Unexpected XML tag: {:?}",
bytes.name()
)));
}
let ResolveResult::Bound(Namespace(ns)) = namespace else {
return Continuation::Final(Err(ffail!("No namespace provided")));
};
if ns != XMLNS.as_bytes() {
return Continuation::Final(Err(ffail!("Incorrect namespace")));
}
Continuation::Continue(BindRequestParser(InBind(None)))
} }
InBind(resource) => match event { let ResolveResult::Bound(Namespace(ns)) = namespace else {
Event::Start(bytes) => { return Err(anyhow!("No namespace provided"));
Continuation::Continue(BindRequestParser(InBindResourceInitial)) };
} if ns != XMLNS.as_bytes() {
Event::End(bytes) => { return Err(anyhow!("Incorrect namespace"));
let Some(resource) = resource else { }
return Continuation::Final(Err(ffail!("No resource was provided"))); loop {
let (namespace, event) = yield;
match event {
Event::Start(bytes) if bytes.name().0 == b"resource" => {
let (namespace, event) = yield;
let Event::Text(text) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
}; };
Continuation::Final(Ok(BindRequest(Resource(resource.into())))) resource = Some(std::str::from_utf8(&*text)?.into());
let (namespace, event) = yield;
let Event::End(bytes) = event else {
return Err(anyhow!("Unexpected XML event: {event:?}"));
};
if bytes.name().0 != b"resource" {
return Err(anyhow!("Unexpected XML tag: {:?}", bytes.name()));
}
}
Event::End(bytes) if bytes.name().0 == BindRequest::NAME.as_bytes() => {
break;
}
_ => return Err(anyhow!("Unexpected XML event: {event:?}")),
} }
_ => Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}"))),
},
InBindResourceInitial => {
let Event::Text(text) = event else {
return Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}")));
};
let resource = match std::str::from_utf8(text.as_bytes()) {
Ok(e) => e.to_string(),
Err(err) => return Continuation::Final(Err(err.into())),
};
Continuation::Continue(BindRequestParser(InBindResourceEnd(resource)))
}
InBindResourceEnd(resource) => {
let Event::End(bytes) = event else {
return Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}")));
};
Continuation::Continue(BindRequestParser(InBind(Some(resource))))
} }
let Some(resource) = resource else {
return Err(anyhow!("No resource was provided"));
};
Ok(BindRequest(Resource(resource)))
} }
} }
} }

View File

@ -3,8 +3,11 @@ use quick_xml::events::attributes::Attribute;
use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event}; use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event};
use quick_xml::name::{QName, ResolveResult}; use quick_xml::name::{QName, ResolveResult};
use anyhow::{Result, anyhow as ffail};
use crate::prelude::*; use crate::prelude::*;
use crate::util::xml::*; use crate::xml::*;
use super::bind::Jid; use super::bind::Jid;
@ -308,9 +311,9 @@ impl<T: FromXml> Parser for IqParser<T> {
} }
IqParserInner::Final(state) => { IqParserInner::Final(state) => {
if let Event::End(ref bytes) = event { if let Event::End(ref bytes) = event {
let id = fail_fast!(state.id.ok_or_else(|| fail("No id provided"))); let id = fail_fast!(state.id.ok_or_else(|| ffail!("No id provided")));
let r#type = fail_fast!(state.r#type.ok_or_else(|| fail("No type 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(|| fail("No body provided"))); let body = fail_fast!(state.body.ok_or_else(|| ffail!("No body provided")));
Continuation::Final(Ok(Iq { Continuation::Final(Ok(Iq {
from: state.from, from: state.from,
id, id,
@ -579,7 +582,7 @@ impl<T: ToXml> ToXml for Presence<T> {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::protos::xmpp::bind::{BindRequest, Name, Resource, Server}; use crate::bind::{BindRequest, Name, Resource, Server};
use super::*; use super::*;
use quick_xml::NsReader; use quick_xml::NsReader;

View File

@ -2,8 +2,8 @@ use quick_xml::events::attributes::Attribute;
use quick_xml::events::{BytesEnd, BytesStart, Event}; use quick_xml::events::{BytesEnd, BytesStart, Event};
use quick_xml::name::{QName, ResolveResult}; use quick_xml::name::{QName, ResolveResult};
use crate::prelude::*; use anyhow::{Result, anyhow as ffail};
use crate::util::xml::*; use crate::xml::*;
use super::bind::Jid; use super::bind::Jid;

View File

@ -1,3 +1,10 @@
#![feature(
generators,
generator_trait,
type_alias_impl_trait,
impl_trait_in_assoc_type
)]
pub mod bind; pub mod bind;
pub mod client; pub mod client;
pub mod disco; pub mod disco;
@ -8,6 +15,8 @@ pub mod session;
pub mod stanzaerror; pub mod stanzaerror;
pub mod stream; pub mod stream;
pub mod tls; pub mod tls;
mod prelude;
pub mod xml;
// Implemented as a macro instead of a fn due to borrowck limitations // Implemented as a macro instead of a fn due to borrowck limitations
macro_rules! skip_text { macro_rules! skip_text {
@ -25,4 +34,4 @@ macro_rules! skip_text {
}; };
} }
pub(super) use skip_text; pub(crate) use skip_text;

View File

@ -1,8 +1,8 @@
use quick_xml::events::Event; use quick_xml::events::Event;
use quick_xml::name::ResolveResult; use quick_xml::name::ResolveResult;
use crate::prelude::*; use anyhow::{anyhow, Result};
use crate::util::xml::*; use crate::xml::*;
pub const XMLNS: &'static str = "http://jabber.org/protocol/muc"; pub const XMLNS: &'static str = "http://jabber.org/protocol/muc";
@ -22,7 +22,7 @@ impl FromXml for History {
let (bytes, end) = match event { let (bytes, end) = match event {
Event::Start(bytes) => (bytes, false), Event::Start(bytes) => (bytes, false),
Event::Empty(bytes) => (bytes, true), Event::Empty(bytes) => (bytes, true),
_ => return Err(ffail!("Unexpected XML event: {event:?}")), _ => return Err(anyhow!("Unexpected XML event: {event:?}")),
}; };
for attr in bytes.attributes() { for attr in bytes.attributes() {
let attr = attr?; let attr = attr?;
@ -51,7 +51,7 @@ impl FromXml for History {
let (namespace, event) = yield; let (namespace, event) = yield;
let Event::End(bytes) = event else { let Event::End(bytes) = event else {
return Err(ffail!("Unexpected XML event: {event:?}")); return Err(anyhow!("Unexpected XML event: {event:?}"));
}; };
Ok(history) Ok(history)
} }
@ -73,15 +73,15 @@ impl FromXml for Password {
fn parse() -> Self::P { fn parse() -> Self::P {
|(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> { |(namespace, event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
let Event::Start(bytes) = event else { let Event::Start(bytes) = event else {
return Err(ffail!("Unexpected XML event: {event:?}")); return Err(anyhow!("Unexpected XML event: {event:?}"));
}; };
let (namespace, event) = yield; let (namespace, event) = yield;
let Event::Text(bytes) = event else { let Event::Text(bytes) = event else {
return Err(ffail!("Unexpected XML event: {event:?}")); return Err(anyhow!("Unexpected XML event: {event:?}"));
}; };
let s = std::str::from_utf8(bytes)?.to_string(); let s = std::str::from_utf8(bytes)?.to_string();
let Event::End(bytes) = event else { let Event::End(bytes) = event else {
return Err(ffail!("Unexpected XML event: {event:?}")); return Err(anyhow!("Unexpected XML event: {event:?}"));
}; };
Ok(Password(s)) Ok(Password(s))
} }
@ -109,7 +109,7 @@ impl FromXml for X {
let (bytes, end) = match event { let (bytes, end) = match event {
Event::Start(bytes) => (bytes, false), Event::Start(bytes) => (bytes, false),
Event::Empty(bytes) => (bytes, true), Event::Empty(bytes) => (bytes, true),
_ => return Err(ffail!("Unexpected XML event: {event:?}")), _ => return Err(anyhow!("Unexpected XML event: {event:?}")),
}; };
if end { if end {
return Ok(res); return Ok(res);
@ -121,7 +121,7 @@ impl FromXml for X {
Event::Start(bytes) => bytes, Event::Start(bytes) => bytes,
Event::Empty(bytes) => bytes, Event::Empty(bytes) => bytes,
Event::End(_) => break, Event::End(_) => break,
_ => return Err(ffail!("Unexpected XML event: {event:?}")), _ => return Err(anyhow!("Unexpected XML event: {event:?}")),
}; };
if bytes.name().0 == Password::NAME.as_bytes() { if bytes.name().0 == Password::NAME.as_bytes() {
let password = delegate_parsing!(Password, namespace, event)?; let password = delegate_parsing!(Password, namespace, event)?;
@ -130,7 +130,7 @@ impl FromXml for X {
let history = delegate_parsing!(History, namespace, event)?; let history = delegate_parsing!(History, namespace, event)?;
res.history = Some(history); res.history = Some(history);
} else { } else {
return Err(ffail!("Unexpected XML event: {event:?}")); return Err(anyhow!("Unexpected XML event: {event:?}"));
} }
} }

View File

@ -0,0 +1,3 @@
use std::sync::Arc;
pub type Str = Arc<str>;

View File

@ -1,7 +1,7 @@
use quick_xml::events::{BytesStart, Event}; use quick_xml::events::{BytesStart, Event};
use crate::prelude::*; use crate::xml::*;
use crate::util::xml::*; use anyhow::{anyhow as ffail, Result};
pub const XMLNS: &'static str = "jabber:iq:roster"; pub const XMLNS: &'static str = "jabber:iq:roster";

View File

@ -7,7 +7,7 @@ use quick_xml::{
use tokio::io::{AsyncBufRead, AsyncWrite}; use tokio::io::{AsyncBufRead, AsyncWrite};
use super::skip_text; use super::skip_text;
use crate::prelude::*; use anyhow::{anyhow, Result};
pub enum Mechanism { pub enum Mechanism {
Plain, Plain,
@ -22,7 +22,7 @@ impl Mechanism {
pub fn from_str(input: &[u8]) -> Result<Mechanism> { pub fn from_str(input: &[u8]) -> Result<Mechanism> {
match input { match input {
b"PLAIN" => Ok(Mechanism::Plain), b"PLAIN" => Ok(Mechanism::Plain),
_ => Err(fail(format!("unknown auth mechanism: {input:?}").as_str())), _ => Err(anyhow!("unknown auth mechanism: {input:?}")),
} }
} }
} }
@ -48,20 +48,20 @@ impl Auth {
if let Some(mechanism) = mechanism { if let Some(mechanism) = mechanism {
Mechanism::from_str(mechanism.borrow())? Mechanism::from_str(mechanism.borrow())?
} else { } else {
return Err(fail("expected mechanism attribute in <auth>")); return Err(anyhow!("expected mechanism attribute in <auth>"));
} }
} else { } else {
return Err(fail("expected start of <auth>")); return Err(anyhow!("expected start of <auth>"));
}; };
let body = if let Event::Text(text) = reader.read_event_into_async(buf).await? { let body = if let Event::Text(text) = reader.read_event_into_async(buf).await? {
text.into_inner().into_owned() text.into_inner().into_owned()
} else { } else {
return Err(fail("expected text body in <auth>")); return Err(anyhow!("expected text body in <auth>"));
}; };
if let Event::End(_) = reader.read_event_into_async(buf).await? { if let Event::End(_) = reader.read_event_into_async(buf).await? {
//TODO //TODO
} else { } else {
return Err(fail("expected end of <auth>")); return Err(anyhow!("expected end of <auth>"));
}; };
Ok(Auth { mechanism, body }) Ok(Auth { mechanism, body })

View File

@ -1,7 +1,7 @@
use quick_xml::events::{BytesStart, Event}; use quick_xml::events::{BytesStart, Event};
use crate::prelude::*; use crate::xml::*;
use crate::util::xml::*; use anyhow::{anyhow, Result};
pub const XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-session"; pub const XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-session";
@ -29,11 +29,11 @@ impl Parser for SessionParser {
Continuation::Continue(SessionParser(SessionParserInner::InSession)) Continuation::Continue(SessionParser(SessionParserInner::InSession))
} }
Event::Empty(_) => Continuation::Final(Ok(Session)), Event::Empty(_) => Continuation::Final(Ok(Session)),
_ => Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}"))), _ => Continuation::Final(Err(anyhow!("Unexpected XML event: {event:?}"))),
}, },
SessionParserInner::InSession => match event { SessionParserInner::InSession => match event {
Event::End(_) => Continuation::Final(Ok(Session)), Event::End(_) => Continuation::Final(Ok(Session)),
_ => Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}"))), _ => Continuation::Final(Err(anyhow!("Unexpected XML event: {event:?}"))),
}, },
} }
} }

View File

@ -5,8 +5,9 @@ use quick_xml::{NsReader, Writer};
use tokio::io::{AsyncBufRead, AsyncWrite}; use tokio::io::{AsyncBufRead, AsyncWrite};
use super::skip_text; use super::skip_text;
use crate::prelude::*;
use crate::util::xml::ToXml; use anyhow::{anyhow, Result};
use crate::xml::ToXml;
pub static XMLNS: &'static str = "http://etherx.jabber.org/streams"; pub static XMLNS: &'static str = "http://etherx.jabber.org/streams";
pub static PREFIX: &'static str = "stream"; pub static PREFIX: &'static str = "stream";
@ -63,7 +64,6 @@ impl ClientStreamStart {
version: version.unwrap(), version: version.unwrap(),
}) })
} else { } else {
log::error!("WAT: {incoming:?}");
Err(panic!()) Err(panic!())
} }
} }

View File

@ -5,7 +5,8 @@ use quick_xml::{NsReader, Writer};
use tokio::io::{AsyncBufRead, AsyncWrite}; use tokio::io::{AsyncBufRead, AsyncWrite};
use super::skip_text; use super::skip_text;
use crate::prelude::*;
use anyhow::{anyhow, Result};
pub static XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-tls"; pub static XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-tls";
@ -21,7 +22,7 @@ impl StartTLS {
return Ok(StartTLS); return Ok(StartTLS);
} }
} }
Err(ffail!("XML tag starttls expected, received: {incoming:?}")) Err(anyhow!("XML tag starttls expected, received: {incoming:?}"))
} }
} }

View File

@ -4,7 +4,7 @@ use std::pin::Pin;
use quick_xml::events::Event; use quick_xml::events::Event;
use quick_xml::name::ResolveResult; use quick_xml::name::ResolveResult;
use crate::prelude::Result; use anyhow::{anyhow, Result};
mod ignore; mod ignore;
pub use ignore::Ignore; pub use ignore::Ignore;
@ -72,6 +72,7 @@ macro_rules! fail_fast {
}; };
} }
#[macro_export]
macro_rules! delegate_parsing { macro_rules! delegate_parsing {
($parser: ty, $namespace: expr, $event: expr) => {{ ($parser: ty, $namespace: expr, $event: expr) => {{
let mut parser = <$parser as FromXml>::parse().consume($namespace, $event); let mut parser = <$parser as FromXml>::parse().consume($namespace, $event);
@ -88,6 +89,7 @@ macro_rules! delegate_parsing {
}}; }};
} }
#[macro_export]
macro_rules! match_parser { macro_rules! match_parser {
($name: expr, $ns: expr, $event: expr; $subtype: ty, $fin: block) => { ($name: expr, $ns: expr, $event: expr; $subtype: ty, $fin: block) => {
if $name.0 == <$subtype as FromXmlTag>::NAME.as_bytes() && $ns == ResolveResult::Bound(Namespace(<$subtype as FromXmlTag>::NS.as_bytes())) { if $name.0 == <$subtype as FromXmlTag>::NAME.as_bytes() && $ns == ResolveResult::Bound(Namespace(<$subtype as FromXmlTag>::NS.as_bytes())) {
@ -105,6 +107,6 @@ macro_rules! match_parser {
}; };
} }
pub(crate) use delegate_parsing; pub use delegate_parsing;
pub(crate) use fail_fast; pub(crate) use fail_fast;
pub(crate) use match_parser; pub use match_parser;

18
crates/sim-irc/Cargo.toml Normal file
View File

@ -0,0 +1,18 @@
[package]
name = "sim-irc"
edition = "2021"
version.workspace = true
[dependencies]
proto-irc = { path = "../proto-irc" }
mgmt-api = { path = "../mgmt-api" }
clap.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
rand = "0.8.5"
tokio.workspace = true
anyhow.workspace = true
hyper = { version = "1.0.0-rc.3,<1.0.0-rc.4", features = ["client", "http1"] }
http-body-util.workspace = true
serde.workspace = true
serde_json = "1.0.93"

126
crates/sim-irc/src/main.rs Normal file
View File

@ -0,0 +1,126 @@
use anyhow::Result;
use clap::Parser;
use http_body_util::Full;
use hyper::body::{Bytes, Incoming};
use hyper::client::conn::http1::SendRequest;
use hyper::{Request, Response};
use rand::prelude::Distribution;
use rand::{distributions::Uniform, Rng};
use serde::Serialize;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::io::{AsyncWriteExt, BufReader};
use tokio::net::tcp::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
#[derive(Parser)]
struct CliArgs {
/// Management API address
#[arg(long)]
mgmt: SocketAddr,
/// IRC server address
#[arg(long)]
irc: SocketAddr,
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = CliArgs::parse();
let mut gen = rand::thread_rng();
tracing::info!("Starting");
let stream = TcpStream::connect(args.mgmt).await?;
let (mut request_sender, connection) = hyper::client::conn::http1::handshake(stream).await?;
tracing::info!("Mgmt connected");
let fiber = tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("Error in connection: {}", e);
}
});
let name = generate_player_name(&mut gen);
let pass = generate_password(&mut gen);
{
let v = mgmt_api::CreatePlayerRequest { name: &*name };
let response = http_send(&mut request_sender, mgmt_api::paths::CREATE_PLAYER, &v).await?;
assert!(response.status().is_success());
tracing::info!("Player {} created", name);
}
{
let v = mgmt_api::ChangePasswordRequest {
player_name: &*name,
password: &*pass,
};
let response = http_send(&mut request_sender, mgmt_api::paths::SET_PASSWORD, &v).await?;
assert!(response.status().is_success());
tracing::info!("Password set for {}", name);
}
drop(request_sender);
fiber.await?;
let mut stream = TcpStream::connect(args.irc).await?;
tracing::info!("IRC connected");
let (reader, writer) = stream.split();
let reader = BufReader::new(reader);
let test_scope = TestScope { reader, writer, buffer: vec![] };
test_scope.send(&format!("PASS {pass}")).await?;
test_scope.send(&format!("NICK {name}")).await?;
test_scope.send(&format!("USER UserName 0 * :Real Name")).await?;
stream.shutdown().await?;
Ok(())
}
struct TestScope<'a> {
reader: BufReader<ReadHalf<'a>>,
writer: WriteHalf<'a>,
buffer: Vec<u8>,
}
impl<'a> TestScope<'a> {
async fn send(&mut self, str: &(impl AsRef<str> + ?Sized)) -> Result<()> {
self.writer.write_all(str.as_ref().as_bytes()).await?;
self.writer.write_all(b"\r\n").await?;
self.writer.flush().await?;
Ok(())
}
async fn assert(&mut self, f: impl FnOnce(&str) -> Result<()>) -> Result<()> {
let len = self.reader.read_until(b'\n', &mut self.buffer).await?;
let res = f(std::str::from_utf8(&self.buffer[0..len])?);
self.buffer.clear();
res
}
}
async fn http_send(
client: &mut SendRequest<Full<Bytes>>,
path: &str,
payload: &impl Serialize,
) -> Result<Response<Incoming>> {
let mut buffer = vec![];
serde_json::to_writer(&mut buffer, payload).expect("unexpected fail when writing to vec");
let body = Full::new(Bytes::from(buffer));
let request = Request::builder().method("POST").uri(path).body(body)?;
let response = client.send_request(request).await?;
Ok(response)
}
fn generate_player_name(gen: &mut impl Rng) -> Arc<str> {
let len = Uniform::from(7..14).sample(gen);
gen.sample_iter(Uniform::from('a'..'z'))
.take(len)
.collect::<String>()
.into()
}
fn generate_password(gen: &mut impl Rng) -> Arc<str> {
let len = Uniform::from(8..32).sample(gen);
gen.sample_iter(Uniform::from('0'..'z'))
.take(len)
.collect::<String>()
.into()
}

View File

@ -8,4 +8,4 @@ FROM alpine:3.18@sha256:7144f7bab3d4c2648d7e59409f15ec52a18006a128c733fcff20d3a4
COPY --from=bld target/release/lavina /usr/bin/lavina COPY --from=bld target/release/lavina /usr/bin/lavina
VOLUME ["/etc/lavina/", "/var/lib/lavina/"] VOLUME ["/etc/lavina/", "/var/lib/lavina/"]
ENTRYPOINT ["lavina"] ENTRYPOINT ["lavina", "--config", "/etc/lavina/config.toml"]

1
rustfmt.toml Normal file
View File

@ -0,0 +1 @@
max_width = 120

View File

@ -5,7 +5,7 @@ use std::sync::Arc;
use serde::Deserialize; use serde::Deserialize;
use sqlx::sqlite::SqliteConnectOptions; use sqlx::sqlite::SqliteConnectOptions;
use sqlx::{ConnectOptions, Connection, FromRow, SqliteConnection}; use sqlx::{ConnectOptions, Connection, FromRow, Sqlite, SqliteConnection, Transaction};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use crate::prelude::*; use crate::prelude::*;
@ -102,6 +102,50 @@ impl Storage {
res.close().await?; res.close().await?;
Ok(()) Ok(())
} }
pub async fn create_user(&mut self, name: &str) -> Result<()> {
let query = sqlx::query(
"insert into users(name)
values (?);",
)
.bind(name);
let mut executor = self.conn.lock().await;
query.execute(&mut *executor).await?;
Ok(())
}
pub async fn set_password<'a>(&'a mut 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;")
.bind(name)
.fetch_optional(&mut **txn)
.await?;
let Some((id,)) = id else {
return Ok(None);
};
sqlx::query("insert or replace into challenges_plain_password(user_id, password) values (?, ?);")
.bind(id)
.bind(pwd)
.execute(&mut **txn)
.await?;
Ok(Some(()))
}
let mut executor = self.conn.lock().await;
let mut tx = executor.begin().await?;
let res = inner(&mut tx, name, pwd).await;
match res {
Ok(e) => {
tx.commit().await?;
Ok(e)
}
Err(e) => {
tx.rollback().await?;
Err(e)
}
}
}
} }
#[derive(FromRow)] #[derive(FromRow)]

View File

@ -8,11 +8,12 @@
mod core; mod core;
mod prelude; mod prelude;
mod projections; mod projections;
mod protos;
mod util; mod util;
use std::future::Future; use std::future::Future;
use std::path::Path;
use clap::Parser;
use figment::providers::Format; use figment::providers::Format;
use figment::{providers::Toml, Figment}; use figment::{providers::Toml, Figment};
use prometheus::Registry as MetricsRegistry; use prometheus::Registry as MetricsRegistry;
@ -31,11 +32,15 @@ struct ServerConfig {
storage: core::repo::StorageConfig, storage: core::repo::StorageConfig,
} }
#[derive(Parser)]
struct CliArgs {
#[arg(long)]
config: Box<Path>,
}
fn load_config() -> Result<ServerConfig> { fn load_config() -> Result<ServerConfig> {
// TODO get config path as a cmd line arg let args = CliArgs::parse();
let raw_config = Figment::new() let raw_config = Figment::from(Toml::file(args.config));
.merge(Toml::file("config.toml"))
.merge(Toml::file("/etc/lavina/config.toml"));
let config: ServerConfig = raw_config.extract()?; let config: ServerConfig = raw_config.extract()?;
Ok(config) Ok(config)
} }
@ -59,7 +64,7 @@ async fn main() -> Result<()> {
let rooms = RoomRegistry::new(&mut metrics, storage.clone())?; let rooms = RoomRegistry::new(&mut metrics, storage.clone())?;
let mut players = PlayerRegistry::empty(rooms.clone(), &mut metrics)?; let mut players = PlayerRegistry::empty(rooms.clone(), &mut metrics)?;
let telemetry_terminator = let telemetry_terminator =
util::telemetry::launch(telemetry_config, metrics.clone(), rooms.clone()).await?; util::telemetry::launch(telemetry_config, metrics.clone(), rooms.clone(), storage.clone()).await?;
let irc = projections::irc::launch(irc_config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await?; let irc = projections::irc::launch(irc_config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await?;
let xmpp = projections::xmpp::launch(xmpp_config, players.clone(), rooms.clone(), metrics.clone()).await?; let xmpp = projections::xmpp::launch(xmpp_config, players.clone(), rooms.clone(), metrics.clone()).await?;
tracing::info!("Started"); tracing::info!("Started");

View File

@ -5,6 +5,7 @@ use futures_util::future::join_all;
use nonempty::nonempty; use nonempty::nonempty;
use nonempty::NonEmpty; use nonempty::NonEmpty;
use prometheus::{IntCounter, IntGauge, Registry as MetricsRegistry}; use prometheus::{IntCounter, IntGauge, Registry as MetricsRegistry};
use serde::Deserialize; use serde::Deserialize;
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter}; use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
use tokio::net::tcp::{ReadHalf, WriteHalf}; use tokio::net::tcp::{ReadHalf, WriteHalf};
@ -15,10 +16,10 @@ use crate::core::player::*;
use crate::core::repo::Storage; use crate::core::repo::Storage;
use crate::core::room::{RoomId, RoomInfo, RoomRegistry}; use crate::core::room::{RoomId, RoomInfo, RoomRegistry};
use crate::prelude::*; use crate::prelude::*;
use crate::protos::irc::client::{client_message, ClientMessage}; use proto_irc::client::{client_message, ClientMessage};
use crate::protos::irc::server::{AwayStatus, ServerMessage, ServerMessageBody}; use proto_irc::server::{AwayStatus, ServerMessage, ServerMessageBody};
use crate::protos::irc::{Chan, Recipient}; use proto_irc::{Chan, Recipient};
use crate::protos::irc::user::PrefixedNick; use proto_irc::user::{Prefix, PrefixedNick};
use crate::util::Terminator; use crate::util::Terminator;
#[cfg(test)] #[cfg(test)]
@ -51,6 +52,7 @@ async fn handle_socket(
termination: Deferred<()>, // TODO use it to stop the connection gracefully termination: Deferred<()>, // TODO use it to stop the connection gracefully
mut storage: Storage, mut storage: Storage,
) -> Result<()> { ) -> Result<()> {
log::info!("Received an IRC connection from {socket_addr}");
let (reader, writer) = stream.split(); let (reader, writer) = stream.split();
let mut reader: BufReader<ReadHalf> = BufReader::new(reader); let mut reader: BufReader<ReadHalf> = BufReader::new(reader);
let mut writer = BufWriter::new(writer); let mut writer = BufWriter::new(writer);
@ -73,10 +75,13 @@ async fn handle_socket(
match registered_user { match registered_user {
Ok(user) => { Ok(user) => {
log::debug!("User registered");
handle_registered_socket(config, players, rooms, &mut reader, &mut writer, user) handle_registered_socket(config, players, rooms, &mut reader, &mut writer, user)
.await?; .await?;
} }
Err(_) => {} Err(_) => {
log::debug!("Registration failed");
}
} }
stream.shutdown().await?; stream.shutdown().await?;
@ -669,7 +674,7 @@ async fn produce_on_join_cmd_messages(
} }
.write_async(writer) .write_async(writer)
.await?; .await?;
let prefixed_members: Vec<PrefixedNick> = room_info.members.iter().map(|member| PrefixedNick::from_player_id(member.clone())).collect(); let prefixed_members: Vec<PrefixedNick> = room_info.members.iter().map(|member| PrefixedNick::from_str(member.clone().into_inner())).collect();
let non_empty_members: NonEmpty<PrefixedNick> = NonEmpty::from_vec(prefixed_members).unwrap_or(nonempty![PrefixedNick::from_str(user.nickname.clone())]); let non_empty_members: NonEmpty<PrefixedNick> = NonEmpty::from_vec(prefixed_members).unwrap_or(nonempty![PrefixedNick::from_str(user.nickname.clone())]);
ServerMessage { ServerMessage {

View File

@ -22,14 +22,13 @@ use tokio_rustls::TlsAcceptor;
use crate::core::player::{PlayerConnection, PlayerId, PlayerRegistry}; use crate::core::player::{PlayerConnection, PlayerId, PlayerRegistry};
use crate::core::room::{RoomId, RoomRegistry}; use crate::core::room::{RoomId, RoomRegistry};
use crate::prelude::*; use crate::prelude::*;
use crate::protos::xmpp; use proto_xmpp::bind::{BindResponse, Jid, Name, Resource, Server};
use crate::protos::xmpp::bind::{BindResponse, Jid, Name, Resource, Server}; use proto_xmpp::client::{Iq, Message, MessageType, Presence};
use crate::protos::xmpp::client::{Iq, Message, MessageType, Presence}; use proto_xmpp::disco::*;
use crate::protos::xmpp::disco::*; use proto_xmpp::roster::RosterQuery;
use crate::protos::xmpp::roster::RosterQuery; use proto_xmpp::session::Session;
use crate::protos::xmpp::session::Session; use proto_xmpp::stream::*;
use crate::protos::xmpp::stream::*; use proto_xmpp::xml::{Continuation, FromXml, Parser, ToXml};
use crate::util::xml::{Continuation, FromXml, Parser, ToXml};
use crate::util::Terminator; use crate::util::Terminator;
use self::proto::{ClientPacket, IqClientBody}; use self::proto::{ClientPacket, IqClientBody};
@ -149,7 +148,7 @@ async fn handle_socket(
rooms: RoomRegistry, rooms: RoomRegistry,
termination: Deferred<()>, // TODO use it to stop the connection gracefully termination: Deferred<()>, // TODO use it to stop the connection gracefully
) -> Result<()> { ) -> Result<()> {
log::debug!("Received an XMPP connection from {socket_addr}"); log::info!("Received an XMPP connection from {socket_addr}");
let mut reader_buf = vec![]; let mut reader_buf = vec![];
let (reader, writer) = stream.split(); let (reader, writer) = stream.split();
let mut buf_reader = BufReader::new(reader); let mut buf_reader = BufReader::new(reader);
@ -172,6 +171,7 @@ async fn handle_socket(
let mut xml_writer = Writer::new(b); let mut xml_writer = Writer::new(b);
let authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf).await?; let authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf).await?;
log::debug!("User authenticated");
let mut connection = players let mut connection = players
.connect_to_player(authenticated.player_id.clone()) .connect_to_player(authenticated.player_id.clone())
.await; .await;
@ -196,7 +196,7 @@ async fn socket_force_tls(
writer: &mut (impl AsyncWrite + Unpin), writer: &mut (impl AsyncWrite + Unpin),
reader_buf: &mut Vec<u8>, reader_buf: &mut Vec<u8>,
) -> Result<()> { ) -> Result<()> {
use crate::protos::xmpp::tls::*; use proto_xmpp::tls::*;
let xml_reader = &mut NsReader::from_reader(reader); let xml_reader = &mut NsReader::from_reader(reader);
let xml_writer = &mut Writer::new(writer); let xml_writer = &mut Writer::new(writer);
read_xml_header(xml_reader, reader_buf).await?; read_xml_header(xml_reader, reader_buf).await?;
@ -253,8 +253,8 @@ async fn socket_auth(
.await?; .await?;
xml_writer.get_mut().flush().await?; xml_writer.get_mut().flush().await?;
let _ = xmpp::sasl::Auth::parse(xml_reader, reader_buf).await?; let _ = proto_xmpp::sasl::Auth::parse(xml_reader, reader_buf).await?;
xmpp::sasl::Success.write_xml(xml_writer).await?; proto_xmpp::sasl::Success.write_xml(xml_writer).await?;
let name: Str = "darova".into(); let name: Str = "darova".into();
Ok(Authenticated { Ok(Authenticated {
@ -314,7 +314,6 @@ async fn socket_final(
match parser.consume(ns, &event) { match parser.consume(ns, &event) {
Continuation::Final(res) => { Continuation::Final(res) => {
let res = res?; let res = res?;
dbg!(&res);
let stop = handle_packet(&mut events, res, authenticated, user_handle, rooms).await?; let stop = handle_packet(&mut events, res, authenticated, user_handle, rooms).await?;
for i in &events { for i in &events {
xml_writer.write_event_async(i).await?; xml_writer.write_event_async(i).await?;
@ -346,7 +345,7 @@ async fn socket_final(
resource: Some(Resource(author_id.into_inner().into())), resource: Some(Resource(author_id.into_inner().into())),
}), }),
id: None, id: None,
r#type: xmpp::client::MessageType::Groupchat, r#type: proto_xmpp::client::MessageType::Groupchat,
lang: None, lang: None,
subject: None, subject: None,
body: body.into(), body: body.into(),
@ -414,7 +413,7 @@ async fn handle_packet(
resource: Some(user.xmpp_muc_name.clone()), resource: Some(user.xmpp_muc_name.clone()),
}), }),
id: m.id, id: m.id,
r#type: xmpp::client::MessageType::Groupchat, r#type: proto_xmpp::client::MessageType::Groupchat,
lang: None, lang: None,
subject: None, subject: None,
body: m.body.clone(), body: m.body.clone(),
@ -485,7 +484,7 @@ async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms
from: None, from: None,
id: iq.id, id: iq.id,
to: None, to: None,
r#type: xmpp::client::IqType::Result, r#type: proto_xmpp::client::IqType::Result,
body: BindResponse(Jid { body: BindResponse(Jid {
name: Some(Name("darova".into())), name: Some(Name("darova".into())),
server: Server("localhost".into()), server: Server("localhost".into()),
@ -499,7 +498,7 @@ async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms
from: None, from: None,
id: iq.id, id: iq.id,
to: None, to: None,
r#type: xmpp::client::IqType::Result, r#type: proto_xmpp::client::IqType::Result,
body: Session, body: Session,
}; };
req.serialize(output); req.serialize(output);
@ -509,7 +508,7 @@ async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms
from: None, from: None,
id: iq.id, id: iq.id,
to: None, to: None,
r#type: xmpp::client::IqType::Result, r#type: proto_xmpp::client::IqType::Result,
body: RosterQuery, body: RosterQuery,
}; };
req.serialize(output); req.serialize(output);
@ -520,7 +519,7 @@ async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms
from: iq.to, from: iq.to,
id: iq.id, id: iq.id,
to: None, to: None,
r#type: xmpp::client::IqType::Result, r#type: proto_xmpp::client::IqType::Result,
body: response, body: response,
}; };
req.serialize(output); req.serialize(output);
@ -531,7 +530,7 @@ async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms
from: iq.to, from: iq.to,
id: iq.id, id: iq.id,
to: None, to: None,
r#type: xmpp::client::IqType::Result, r#type: proto_xmpp::client::IqType::Result,
body: response, body: response,
}; };
req.serialize(output); req.serialize(output);
@ -541,7 +540,7 @@ async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms
from: None, from: None,
id: iq.id, id: iq.id,
to: None, to: None,
r#type: xmpp::client::IqType::Error, r#type: proto_xmpp::client::IqType::Error,
body: (), body: (),
}; };
req.serialize(output); req.serialize(output);

View File

@ -2,12 +2,12 @@ use derive_more::From;
use quick_xml::events::Event; use quick_xml::events::Event;
use quick_xml::name::{Namespace, ResolveResult}; use quick_xml::name::{Namespace, ResolveResult};
use crate::protos::xmpp::bind::BindRequest; use proto_xmpp::bind::BindRequest;
use crate::protos::xmpp::client::{Iq, Message, Presence}; use proto_xmpp::client::{Iq, Message, Presence};
use crate::protos::xmpp::disco::{InfoQuery, ItemQuery}; use proto_xmpp::disco::{InfoQuery, ItemQuery};
use crate::protos::xmpp::roster::RosterQuery; use proto_xmpp::roster::RosterQuery;
use crate::protos::xmpp::session::Session; use proto_xmpp::session::Session;
use crate::util::xml::*; use proto_xmpp::xml::*;
use crate::prelude::*; use crate::prelude::*;

View File

@ -1,3 +0,0 @@
//! Definitions of wire protocols to be used in implementations of projections.
pub mod irc;
pub mod xmpp;

View File

@ -1,10 +0,0 @@
use std::convert::Infallible;
use http_body_util::Full;
use hyper::{body::Bytes, Response, StatusCode};
pub fn not_found() -> std::result::Result<Response<Full<Bytes>>, Infallible> {
let mut response = Response::new(Full::new(Bytes::from("404")));
*response.status_mut() = StatusCode::NOT_FOUND;
Ok(response)
}

View File

@ -1,11 +1,9 @@
use crate::prelude::*; use crate::prelude::*;
pub mod http;
pub mod table; pub mod table;
pub mod telemetry; pub mod telemetry;
#[cfg(test)] #[cfg(test)]
pub mod testkit; pub mod testkit;
pub mod xml;
pub struct Terminator { pub struct Terminator {
signal: Promise<()>, signal: Promise<()>,

View File

@ -6,18 +6,18 @@ use http_body_util::{BodyExt, Full};
use hyper::body::Bytes; use hyper::body::Bytes;
use hyper::server::conn::http1; use hyper::server::conn::http1;
use hyper::service::service_fn; use hyper::service::service_fn;
use hyper::{Method, Request, Response}; use hyper::{Method, Request, Response, StatusCode};
use prometheus::{Encoder, Registry as MetricsRegistry, TextEncoder}; use prometheus::{Encoder, Registry as MetricsRegistry, TextEncoder};
use serde::Deserialize; use serde::{Deserialize, Serialize};
use tokio::net::TcpListener; use tokio::net::TcpListener;
use crate::core::repo::Storage;
use crate::core::room::RoomRegistry; use crate::core::room::RoomRegistry;
use crate::prelude::*; use crate::prelude::*;
use crate::util::http::*;
use crate::util::Terminator; use crate::util::Terminator;
type BoxBody = http_body_util::combinators::BoxBody<Bytes, Infallible>; use mgmt_api::*;
type HttpResult<T> = std::result::Result<T, Infallible>; type HttpResult<T> = std::result::Result<T, Infallible>;
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
@ -29,11 +29,12 @@ pub async fn launch(
config: ServerConfig, config: ServerConfig,
metrics: MetricsRegistry, metrics: MetricsRegistry,
rooms: RoomRegistry, rooms: RoomRegistry,
storage: Storage,
) -> Result<Terminator> { ) -> Result<Terminator> {
log::info!("Starting the telemetry service"); log::info!("Starting the telemetry service");
let listener = TcpListener::bind(config.listen_on).await?; let listener = TcpListener::bind(config.listen_on).await?;
log::debug!("Listener started"); log::debug!("Listener started");
let terminator = Terminator::spawn(|rx| main_loop(listener, metrics, rooms, rx.map(|_| ()))); let terminator = Terminator::spawn(|rx| main_loop(listener, metrics, rooms, storage, rx.map(|_| ())));
Ok(terminator) Ok(terminator)
} }
@ -41,6 +42,7 @@ async fn main_loop(
listener: TcpListener, listener: TcpListener,
metrics: MetricsRegistry, metrics: MetricsRegistry,
rooms: RoomRegistry, rooms: RoomRegistry,
storage: Storage,
termination: impl Future<Output = ()>, termination: impl Future<Output = ()>,
) -> Result<()> { ) -> Result<()> {
pin!(termination); pin!(termination);
@ -52,10 +54,12 @@ async fn main_loop(
let (stream, _) = result?; let (stream, _) = result?;
let metrics = metrics.clone(); let metrics = metrics.clone();
let rooms = rooms.clone(); let rooms = rooms.clone();
let storage = storage.clone();
tokio::task::spawn(async move { tokio::task::spawn(async move {
let registry = metrics.clone(); let registry = metrics.clone();
let rooms = rooms.clone(); let rooms = rooms.clone();
let server = http1::Builder::new().serve_connection(stream, service_fn(move |r| route(registry.clone(), rooms.clone(), r))); let storage = storage.clone();
let server = http1::Builder::new().serve_connection(stream, service_fn(move |r| route(registry.clone(), rooms.clone(), storage.clone(), r)));
if let Err(err) = server.await { if let Err(err) = server.await {
tracing::error!("Error serving connection: {:?}", err); tracing::error!("Error serving connection: {:?}", err);
} }
@ -70,27 +74,124 @@ async fn main_loop(
async fn route( async fn route(
registry: MetricsRegistry, registry: MetricsRegistry,
rooms: RoomRegistry, rooms: RoomRegistry,
storage: Storage,
request: Request<hyper::body::Incoming>, request: Request<hyper::body::Incoming>,
) -> std::result::Result<Response<BoxBody>, Infallible> { ) -> HttpResult<Response<Full<Bytes>>> {
match (request.method(), request.uri().path()) { let res = match (request.method(), request.uri().path()) {
(&Method::GET, "/metrics") => Ok(endpoint_metrics(registry)?.map(BodyExt::boxed)), (&Method::GET, "/metrics") => endpoint_metrics(registry),
(&Method::GET, "/rooms") => Ok(endpoint_rooms(rooms).await?.map(BodyExt::boxed)), (&Method::GET, "/rooms") => endpoint_rooms(rooms).await,
_ => Ok(not_found()?.map(BodyExt::boxed)), (&Method::POST, paths::CREATE_PLAYER) => endpoint_create_player(request, storage).await.or5xx(),
(&Method::POST, paths::SET_PASSWORD) => endpoint_set_password(request, storage).await.or5xx(),
_ => not_found(),
};
Ok(res)
}
fn endpoint_metrics(registry: MetricsRegistry) -> Response<Full<Bytes>> {
let mf = registry.gather();
let mut buffer = vec![];
TextEncoder.encode(&mf, &mut buffer).expect("write to vec cannot fail");
Response::new(Full::new(Bytes::from(buffer)))
}
async fn endpoint_rooms(rooms: RoomRegistry) -> Response<Full<Bytes>> {
// TODO introduce management API types independent from core-domain types
// TODO remove `Serialize` implementations from all core-domain types
let room_list = rooms.get_all_rooms().await.to_body();
Response::new(room_list)
}
async fn endpoint_create_player(
request: Request<hyper::body::Incoming>,
mut storage: Storage,
) -> 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);
};
storage.create_user(&res.name).await?;
log::info!("Player {} created", res.name);
let mut response = Response::new(Full::<Bytes>::default());
*response.status_mut() = StatusCode::CREATED;
Ok(response)
}
async fn endpoint_set_password(
request: Request<hyper::body::Incoming>,
mut 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);
};
let Some(_) = storage.set_password(&res.player_name, &res.password).await? else {
let payload = ErrorResponse {
code: errors::PLAYER_NOT_FOUND,
message: "No such player exists",
}
.to_body();
let mut response = Response::new(payload);
*response.status_mut() = StatusCode::UNPROCESSABLE_ENTITY;
return Ok(response);
};
log::info!("Password changed for player {}", res.player_name);
let mut response = Response::new(Full::<Bytes>::default());
*response.status_mut() = StatusCode::NO_CONTENT;
Ok(response)
}
pub fn not_found() -> Response<Full<Bytes>> {
let payload = ErrorResponse {
code: errors::INVALID_PATH,
message: "The path does not exist",
}
.to_body();
let mut response = Response::new(payload);
*response.status_mut() = StatusCode::NOT_FOUND;
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
}
}
} }
} }
fn endpoint_metrics(registry: MetricsRegistry) -> HttpResult<Response<Full<Bytes>>> { trait ToBody {
let mf = registry.gather(); fn to_body(&self) -> Full<Bytes>;
let mut buffer = vec![];
TextEncoder
.encode(&mf, &mut buffer)
.expect("write to vec cannot fail");
Ok(Response::new(Full::new(Bytes::from(buffer))))
} }
impl<T> ToBody for T
async fn endpoint_rooms(rooms: RoomRegistry) -> HttpResult<Response<Full<Bytes>>> { where
let room_list = rooms.get_all_rooms().await; T: Serialize,
let mut buffer = vec![]; {
serde_json::to_writer(&mut buffer, &room_list).expect("unexpected fail when writing to vec"); fn to_body(&self) -> Full<Bytes> {
Ok(Response::new(Full::new(Bytes::from(buffer)))) let mut buffer = vec![];
serde_json::to_writer(&mut buffer, self).expect("unexpected fail when writing to vec");
Full::new(Bytes::from(buffer))
}
} }