From 5ad36c0914e4d714b341f824a7233560cd03f325 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 21 Nov 2026 17:59:19 +0000 Subject: [PATCH] refactor(core): Drop hot reload support This was unused and a hotbed of potential issues --- Cargo.lock | 15 +-- Cargo.toml | 54 --------- docs/development/_meta.json | 5 - docs/development/hot_reload.mdx | 200 -------------------------------- docs/development/index.mdx | 7 -- docs/reference/admin/server.md | 4 - src/admin/mod.rs | 3 - src/admin/server/commands.rs | 8 -- src/admin/server/mod.rs | 4 - src/api/mod.rs | 3 - src/core/Cargo.toml | 5 - src/core/mod.rs | 13 --- src/core/mods/canary.rs | 28 ----- src/core/mods/macros.rs | 70 ----------- src/core/mods/mod.rs | 11 -- src/core/mods/module.rs | 93 --------------- src/core/mods/new.rs | 31 ----- src/core/mods/path.rs | 41 ------- src/core/server.rs | 27 ----- src/database/mod.rs | 3 - src/main/Cargo.toml | 3 - src/main/mod.rs | 40 +------ src/main/mods.rs | 174 --------------------------- src/main/server.rs | 7 -- src/main/signal.rs | 5 +- src/router/mod.rs | 16 +-- src/service/mod.rs | 12 +- 27 files changed, 11 insertions(+), 871 deletions(-) delete mode 100644 docs/development/hot_reload.mdx delete mode 100644 src/core/mods/canary.rs delete mode 100644 src/core/mods/macros.rs delete mode 100644 src/core/mods/mod.rs delete mode 100644 src/core/mods/module.rs delete mode 100644 src/core/mods/new.rs delete mode 100644 src/core/mods/path.rs delete mode 100644 src/main/mods.rs diff --git a/Cargo.lock b/Cargo.lock index 50af5a466..9a40fe2fb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -759,7 +759,7 @@ checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" dependencies = [ "glob", "libc", - "libloading 0.8.9", + "libloading", ] [[package]] @@ -997,7 +997,6 @@ dependencies = [ "ipaddress", "lettre", "libc", - "libloading 0.9.1", "libmimalloc-sys", "lock_api 0.5.0", "maplit", @@ -3241,16 +3240,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "libloading" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1832accd5a4ca2795ace4d05d15c4039be15b62d3b950eff99746a990e3cc10" -dependencies = [ - "cfg-if", - "windows-link", -] - [[package]] name = "libm" version = "0.2.16" @@ -5652,7 +5641,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "969cde0349344dbbf58b5f9badbfb8f806db13969364eb8007c057ef687007d9" dependencies = [ "annotate-snippets", - "base64 0.22.1", + "base64 0.23.1", "encoding_rs_io", "granit-parser", "nohash-hasher", diff --git a/Cargo.toml b/Cargo.toml index 18558e4db..dfd81c967 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -269,9 +269,6 @@ features = [ [workspace.dependencies.tokio-metrics] version = "0.5.2" -[workspace.dependencies.libloading] -version = "0.9.0" - [workspace.dependencies.wildmatch] version = "2.7.0" @@ -753,74 +750,23 @@ inherits = "release" # Developer profile # -# To enable hot-reloading: -# 1. Uncomment all of the rustflags here. -# 2. Uncomment crate-type=dylib in src/*/Cargo.toml -# -# opt-level, mir-opt-level, validate-mir are not known to interfere with reloading -# and can be raised if build times are tolerable. - [profile.dev] debug = "full" opt-level = 0 panic = "unwind" debug-assertions = true incremental = true -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztime-passes', -# '-Zmir-opt-level=0', -# '-Zvalidate-mir=false', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zstaticlib-prefer-dynamic=true', -# '-Zstaticlib-allow-rdylib-deps=true', -# '-Zpacked-bundled-libs=false', -# '-Zplt=true', -# '-Crpath=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,--allow-shlib-undefined', -# '-Clink-arg=-Wl,-z,keep-text-section-prefix', -# '-Clink-arg=-Wl,-z,lazy', -#] [profile.dev.package.conduwuit_core] inherits = "dev" [profile.dev.package.conduwuit] inherits = "dev" -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztime-passes', -# '-Zmir-opt-level=0', -# '-Zvalidate-mir=false', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zexport-executable-symbols=true', -# '-Zplt=true', -# '-Crpath=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,--allow-shlib-undefined', -# '-Clink-arg=-Wl,--export-dynamic', -# '-Clink-arg=-Wl,-z,lazy', -#] [profile.dev.package.'*'] inherits = "dev" debug = 'limited' codegen-units = 1 opt-level = 'z' -#rustflags = [ -# '--cfg', 'conduwuit_mods', -# '-Ztls-model=global-dynamic', -# '-Cprefer-dynamic=true', -# '-Zstaticlib-prefer-dynamic=true', -# '-Zstaticlib-allow-rdylib-deps=true', -# '-Zpacked-bundled-libs=true', -# '-Zplt=true', -# '-Clink-arg=-Wl,--as-needed', -# '-Clink-arg=-Wl,-z,lazy', -# '-Clink-arg=-Wl,-z,nodelete', -#] # primarily used for CI [profile.test] diff --git a/docs/development/_meta.json b/docs/development/_meta.json index c89720f5b..82db72db5 100644 --- a/docs/development/_meta.json +++ b/docs/development/_meta.json @@ -18,10 +18,5 @@ "type": "file", "name": "testing", "label": "Testing" - }, - { - "type": "file", - "name": "hot_reload", - "label": "Hot Reloading" } ] diff --git a/docs/development/hot_reload.mdx b/docs/development/hot_reload.mdx deleted file mode 100644 index 11cb4253f..000000000 --- a/docs/development/hot_reload.mdx +++ /dev/null @@ -1,200 +0,0 @@ -# Hot Reloading ("Live" Development) - -Note that hot reloading has not been refactored in quite a while and is not -guaranteed to work at this time. - -### Summary - -When developing in debug-builds with the nightly toolchain, Continuwuity is modular -using dynamic libraries and various parts of the application are hot-reloadable -while the server is running: http api handlers, admin commands, services, -database, etc. These are all split up into individual workspace crates as seen -in the `src/` directory. Changes to sourcecode in a crate rebuild that crate and -subsequent crates depending on it. Reloading then occurs for the changed crates. - -Release builds still produce static binaries which are unaffected. Rust's -soundness guarantees are in full force. Thus you cannot hot-reload release -binaries. - -### Requirements - -Currently, this development setup only works on x86_64 and aarch64 Linux glibc. -[musl explicitly does not support hot reloadable libraries, and does not -implement `dlclose`][2]. macOS does not fully support our usage of `RTLD_GLOBAL` -possibly due to some thread-local issues. [This Rust issue][3] may be of -relevance, specifically [this comment][4]. It may be possible to get it working -on only very modern macOS versions such as at least Sonoma, as currently loading -dylibs is supported, but not unloading them in our setup, and the cited comment -mentions an Apple WWDC confirming there have been TLS changes to somewhat make -this possible. - -As mentioned above this requires the nightly toolchain. This is due to reliance -on various Cargo.toml features that are only available on nightly, most -specifically `RUSTFLAGS` in Cargo.toml. Some of the implementation could also be -simpler based on other various nightly features. We hope lots of nightly -features start making it out of nightly sooner as there have been dozens of very -helpful features that have been stuck in nightly ("unstable") for at least 5+ -years that would make this simpler. We encourage greater community consensus to -move these features into stability. - -This currently only works on x86_64/aarch64 Linux with a glibc C library. musl C -library, macOS, and likely other host architectures are not supported (if other -architectures work, feel free to let us know and/or make a PR updating this). -This should work on GNU ld and lld (rust-lld) and gcc/clang, however if you -happen to have linker issues it's recommended to try using `mold` or `gold` -linkers, and please let us know in the [Continuwuity Matrix room][7] the linker -error and what linker solved this issue so we can figure out a solution. Ideally -there should be minimal friction to using this, and in the future a build script -(`build.rs`) may be suitable to making this easier to use if the capabilities -allow us. - -### Usage - -As of 19 May 2024, the instructions for using this are: - -0. Have patience. Don't hesitate to join the [Continuwuity Matrix room][7] to - receive help using this. As indicated by the various rustflags used and some -of the interesting issues linked at the bottom, this is definitely not something -the Rust ecosystem or toolchain is used to doing. - -1. Install the nightly toolchain using rustup. You may need to use `rustup - override set nightly` in your local Continuwuity directory, or use `cargo -+nightly` for all actions. - -2. Uncomment `cargo-features` at the top level / root Cargo.toml - -3. Scroll down to the `# Developer profile` section and uncomment ALL the - rustflags for each dev profile and their respective packages. - -4. In each workspace crate's Cargo.toml (everything under `src/*` AND - `deps/rust-rocksdb/Cargo.toml`), uncomment the `dylib` crate type under -`[lib]`. - -5. Due to [this rpath issue][5], you must export the `LD_LIBRARY_PATH` - environment variable to your nightly Rust toolchain library directory. If -using rustup (hopefully), use this: `export -LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/` - -6. Start the server. You can use `cargo +nightly run` for this along with the - standard. - -7. Make some changes where you need to. - -8. In a separate terminal window in the same directory (or using a terminal - multiplexer like tmux), run the *build* Cargo command `cargo +nightly build`. - Cargo should only rebuild what was changed / what's necessary, so it should - not be rebuilding all the crates. - -9. In your Continuwuity server terminal, hit/send `CTRL+C` signal. This will tell - Continuwuity to find which libraries need to be reloaded, and reloads them as - necessary. - -10. If there were no errors, it will tell you it successfully reloaded `#` - modules, and your changes should now be visible. Repeat 7 - 9 as needed. - -To shutdown Continuwuity in this setup, hit/send `CTRL+\`. Normal builds still -shutdown with `CTRL+C` as usual. - -Steps 1 - 5 are the initial first-time steps for using this. To remove the hot -reload setup, revert/comment all the Cargo.toml changes. - -As mentioned in the requirements section, if you happen to have some linker -issues, try using the `-fuse-ld=` rustflag and specify mold or gold in all the -`rustflags` definitions in the top level Cargo.toml, and please let us know in -the [Continuwuity Matrix room][7] the problem. mold can be installed typically -through your distro, and gold is provided by the binutils package. - -It's possible a helper script can be made to do all of this, or most preferably -a specially made build script (build.rs). `cargo watch` support will be -implemented soon which will eliminate the need to manually run `cargo build` all -together. - -### Addendum - -Conduit was inherited as a single crate without modularity or reloading in its -design. Reasonable partitioning and abstraction allowed a split into several -crates, though many circular dependencies had to be corrected. The resulting -crates now form a directed graph as depicted in figures below. The interfacing -between these crates is still extremely broad which is not mitigable. - -Initially [hot_lib_reload][6] was investigated but found appropriate for a -project designed with modularity through limited interfaces, not a large and -complex existing codebase. Instead a bespoke solution built directly on -[libloading][8] satisfied our constraints. This required relatively minimal -modifications and zero maintenance burden compared to what would be required -otherwise. The technical difference lies with relocation processing: we leverage -global bindings (`RTLD_GLOBAL`) in a very intentional way. Most libraries and -off-the-shelf module systems (such as [hot_lib_reload][6]) restrict themselves -to local bindings (`RTLD_LOCAL`). This allows them to release software to -multiple platforms with much greater consistency, but at the cost of burdening -applications to explicitly manage these bindings. In our case with an optional -feature for developers, we shrug any such requirement to enjoy the cost/benefit -on platforms where global relocations are properly cooperative. - -To make use of `RTLD_GLOBAL` the application has to be oriented as a directed -acyclic graph. The primary rule is simple and illustrated in the figure below: -**no crate is allowed to call a function or use a variable from a crate below -it.** - -![Continuwuity's dynamic library setup diagram - created by Jason -Volk](./assets/libraries.png) - -When a symbol is referenced between crates they become bound: **crates cannot be -unloaded until their calling crates are first unloaded.** Thus we start the -reloading process from the crate which has no callers. There is a small problem -though: the first crate is called by the base executable itself! This is solved -by using an `RTLD_LOCAL` binding for just one link between the main executable -and the first crate, freeing the executable from all modules as no global -binding ever occurs between them. - -![Continuwuity's reload and load order diagram - created by Jason -Volk](./assets/reload_order.png) - -Proper resource management is essential for reliable reloading to occur. This is -a very basic ask in RAII-idiomatic Rust and the exposure to reloading hazards is -remarkably low, generally stemming from poor patterns and practices. -Unfortunately static analysis doesn't enforce reload-safety programmatically -(though it could one day), for now hazards can be avoided by knowing a few basic -do's and dont's: - -1. Understand that code is memory. Just like one is forbidden from referencing - free'd memory, one must not transfer control to free'd code. Exposure to this -is primarily from two things: - - - Callbacks, which this project makes very little use of. - - Async tasks, which are addressed below. - -2. Tie all resources to a scope or object lifetime with greatest possible -symmetry (locality). For our purposes this applies to code resources, which -means async blocks and tokio tasks. - - - **Never spawn a task without receiving and storing its JoinHandle**. - - **Always wait on join handles** before leaving a scope or in another cleanup - function called by an owning scope. - -3. Know any minor specific quirks documented in code or here: - - - Don't use `tokio::spawn`, instead use our `Handle` in `core/server.rs`, which - is reachable in most of the codebase via `services()` or other state. This is - due to some bugs or assumptions made in tokio, as it happens in `unsafe {}` - blocks, which are mitigated by circumventing some thread-local variables. Using - runtime handles is good practice in any case. - -The initial implementation PR is available [here][1]. - -### Interesting related issues/bugs - -- [DT_RUNPATH produced in binary with rpath = true is wrong (cargo)][5] -- [Disabling MIR Optimization in Rust Compilation -(cargo)](https://internals.rust-lang.org/t/disabling-mir-optimization-in-rust-compilation/19066/5) -- [Workspace-level metadata -(cargo-deb)](https://github.com/kornelski/cargo-deb/issues/68) - -[1]: https://forgejo.ellis.link/continuwuation/continuwuity/pulls/387 -[2]: https://wiki.musl-libc.org/functional-differences-from-glibc.html#Unloading-libraries -[3]: https://github.com/rust-lang/rust/issues/28794 -[4]: https://github.com/rust-lang/rust/issues/28794#issuecomment-368693049 -[5]: https://github.com/rust-lang/cargo/issues/12746 -[6]: https://crates.io/crates/hot-lib-reloader/ -[7]: https://matrix.to/#/#continuwuity:continuwuity.org?via=continuwuity.org&via=ellis.link&via=explodie.org&via=matrix.org -[8]: https://crates.io/crates/libloading diff --git a/docs/development/index.mdx b/docs/development/index.mdx index 280c25c64..d9aef98b3 100644 --- a/docs/development/index.mdx +++ b/docs/development/index.mdx @@ -37,13 +37,6 @@ It is highly unlikely you will ever need to add a new workspace member, but if you truly find yourself needing to, we recommend reaching out to us in the Matrix room for discussions about it beforehand. -The primary inspiration for this design was apart of hot reloadable development, -to support "Continuwuity as a library" where specific parts can simply be -swapped out. There is evidence Conduit wanted to go this route too as `axum` is -technically an optional feature in Conduit, and can be compiled without the -binary or axum library for handling inbound web requests; but it was never -completed or worked. - See the Rust documentation on [Workspaces][workspaces] for general questions and information on Cargo workspaces. diff --git a/docs/reference/admin/server.md b/docs/reference/admin/server.md index 95a0af91d..0a56394fe 100644 --- a/docs/reference/admin/server.md +++ b/docs/reference/admin/server.md @@ -36,10 +36,6 @@ List database backups Send a message to the admin room -## `!admin server reload` - -Hot-reload the server - ## `!admin server restart` Restart the server diff --git a/src/admin/mod.rs b/src/admin/mod.rs index 079aa0185..eab68e4d0 100644 --- a/src/admin/mod.rs +++ b/src/admin/mod.rs @@ -34,9 +34,6 @@ pub(crate) use crate::{context::Context, utils::get_room_info}; pub(crate) const PAGE_SIZE: usize = 100; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - pub use crate::admin::AdminCommand; /// Install the admin command processor diff --git a/src/admin/server/commands.rs b/src/admin/server/commands.rs index 1173c5457..51042f89b 100644 --- a/src/admin/server/commands.rs +++ b/src/admin/server/commands.rs @@ -110,14 +110,6 @@ impl crate::Context<'_> { self.write_str("Notice was sent to #admins").await } - pub(super) async fn reload_mods(&self) -> Result { - self.bail_restricted()?; - - self.services.server.reload()?; - - self.write_str("Reloading server...").await - } - #[cfg(unix)] pub(super) async fn restart(&self, force: bool) -> Result { use conduwuit::utils::sys::current_exe_deleted; diff --git a/src/admin/server/mod.rs b/src/admin/server/mod.rs index ff6933ef9..c9fb6d299 100644 --- a/src/admin/server/mod.rs +++ b/src/admin/server/mod.rs @@ -39,10 +39,6 @@ pub enum ServerCommand { message: Vec, }, - /// Hot-reload the server - #[command(name = "reload", alias = "reload-mods")] - ReloadMods, - #[cfg(unix)] /// Restart the server Restart { diff --git a/src/api/mod.rs b/src/api/mod.rs index c2e71ba8c..df050e7be 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -16,6 +16,3 @@ pub mod client_ip; pub mod admin; pub(crate) use self::router::{Ruma, RumaResponse, State}; - -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 48a0f2e9e..72aae4312 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -20,9 +20,6 @@ crate-type = [ brotli_compression = [ "reqwest/brotli", ] -conduwuit_mods = [ - "dep:libloading" -] gzip_compression = [ "reqwest/gzip", ] @@ -85,8 +82,6 @@ http-body-util.workspace = true http.workspace = true ipaddress.workspace = true libc.workspace = true -libloading.workspace = true -libloading.optional = true lettre.workspace = true num-traits.workspace = true rand.workspace = true diff --git a/src/core/mod.rs b/src/core/mod.rs index d815bc545..f0388be62 100644 --- a/src/core/mod.rs +++ b/src/core/mod.rs @@ -8,19 +8,6 @@ pub mod info; pub mod log; pub mod matrix; pub mod metrics; -pub mod mods; - -#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))] -pub mod mods { - #[macro_export] - macro_rules! mod_ctor { - () => {}; - } - #[macro_export] - macro_rules! mod_dtor { - () => {}; - } -} pub mod server; pub mod utils; diff --git a/src/core/mods/canary.rs b/src/core/mods/canary.rs deleted file mode 100644 index 6095608c6..000000000 --- a/src/core/mods/canary.rs +++ /dev/null @@ -1,28 +0,0 @@ -use std::sync::atomic::{AtomicI32, Ordering}; - -const ORDERING: Ordering = Ordering::Relaxed; -static STATIC_DTORS: AtomicI32 = AtomicI32::new(0); - -/// Called by Module::unload() to indicate module is about to be unloaded and -/// static destruction is intended. This will allow verifying it actually took -/// place. -pub(crate) fn prepare() { - let count = STATIC_DTORS.fetch_sub(1, ORDERING); - debug_assert!(count <= 0, "STATIC_DTORS should not be greater than zero."); -} - -/// Called by static destructor of a module. This call should only be found -/// inside a mod_fini! macro. Do not call from anywhere else. -#[inline(always)] -pub fn report() { let _count = STATIC_DTORS.fetch_add(1, ORDERING); } - -/// Called by Module::unload() (see check()) with action in case a check() -/// failed. This can allow a stuck module to be noted while allowing for other -/// independent modules to be diagnosed. -pub(crate) fn check_and_reset() -> bool { STATIC_DTORS.swap(0, ORDERING) == 0 } - -/// Called by Module::unload() after unload to verify static destruction took -/// place. A call to prepare() must be made prior to Module::unload() and making -/// this call. -#[allow(dead_code)] -pub(crate) fn check() -> bool { STATIC_DTORS.load(ORDERING) == 0 } diff --git a/src/core/mods/macros.rs b/src/core/mods/macros.rs deleted file mode 100644 index fe434ec94..000000000 --- a/src/core/mods/macros.rs +++ /dev/null @@ -1,70 +0,0 @@ -#[macro_export] -macro_rules! mod_ctor { - ( $($body:block)? ) => { - $crate::mod_init! {{ - $crate::debug_info!("Module loaded"); - $($body)? - }} - } -} - -#[macro_export] -macro_rules! mod_dtor { - ( $($body:block)? ) => { - $crate::mod_fini! {{ - $crate::debug_info!("Module unloading"); - $($body)? - $crate::mods::canary::report(); - }} - } -} - -#[macro_export] -macro_rules! mod_init { - ($body:block) => { - #[cfg(not(all(target_family = "unix", not(target_vendor = "apple"))))] - compile_error!("conduwuit_mods (mod_init!) requires an ELF Unix target"); - - #[used] - // SAFETY: `.init_array` is the standard ELF constructor pointer table; - // the dynamic loader invokes `_mod_init` before `main()` or on `dlopen`. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".init_array") - )] - static MOD_INIT: unsafe extern "C" fn() = { _mod_init }; - - // SAFETY: `.text.startup` is the standard ELF text subsection for - // initialization functions. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".text.startup") - )] - unsafe extern "C" fn _mod_init() -> () $body - }; -} - -#[macro_export] -macro_rules! mod_fini { - ($body:block) => { - #[cfg(not(all(target_family = "unix", not(target_vendor = "apple"))))] - compile_error!("conduwuit_mods (mod_fini!) requires an ELF Unix target"); - - #[used] - // SAFETY: `.fini_array` is the standard ELF destructor pointer table; - // the dynamic loader invokes `_mod_fini` on `dlclose` or process teardown. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".fini_array") - )] - static MOD_FINI: unsafe extern "C" fn() = { _mod_fini }; - - // SAFETY: `.text.exit` / `.text.startup` is a standard ELF text - // subsection for teardown/initialization functions. - #[cfg_attr( - all(target_family = "unix", not(target_vendor = "apple")), - unsafe(link_section = ".text.startup") - )] - unsafe extern "C" fn _mod_fini() -> () $body - }; -} diff --git a/src/core/mods/mod.rs b/src/core/mods/mod.rs deleted file mode 100644 index b8f06f29f..000000000 --- a/src/core/mods/mod.rs +++ /dev/null @@ -1,11 +0,0 @@ -#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - -pub(crate) use libloading::os::unix::{Library, Symbol}; - -pub mod canary; -pub mod macros; -pub mod module; -pub mod new; -pub mod path; - -pub use module::Module; diff --git a/src/core/mods/module.rs b/src/core/mods/module.rs deleted file mode 100644 index 0cd49cb28..000000000 --- a/src/core/mods/module.rs +++ /dev/null @@ -1,93 +0,0 @@ -use std::{ - ffi::{CString, OsString}, - time::SystemTime, -}; - -use super::{Library, Symbol, canary, new, path}; -use crate::{Result, error}; - -pub struct Module { - handle: Option, - loaded: SystemTime, - path: OsString, -} - -impl Module { - /// # Safety - /// See [`new::from_name`]: loads a shared library via `dlopen(3)` and runs - /// its initialization routines. - pub unsafe fn from_name(name: &str) -> Result { - // SAFETY: Upheld by caller. - unsafe { Self::from_path(path::from_name(name)?) } - } - - /// # Safety - /// See [`new::from_path`]: loads a shared library via `dlopen(3)` and runs - /// its initialization routines. - pub unsafe fn from_path(path: OsString) -> Result { - Ok(Self { - // SAFETY: Upheld by caller. - handle: Some(unsafe { new::from_path(&path)? }), - loaded: SystemTime::now(), - path, - }) - } - - pub fn unload(&mut self) { - canary::prepare(); - self.close(); - if !canary::check_and_reset() { - let name = self.name().expect("Module is named"); - error!("Module {name:?} is stuck and failed to unload."); - } - } - - pub(crate) fn close(&mut self) { - if let Some(handle) = self.handle.take() { - handle.close().expect("Module handle closed"); - } - } - - /// Look up a symbol in this module via `dlsym(3)`. - /// - /// # Safety - /// `Prototype` is not checked against the symbol's actual type or ABI in - /// the loaded shared library. The caller must ensure `name` refers to a - /// symbol whose type, calling convention, and ABI exactly match - /// `Prototype`. - pub unsafe fn get(&self, name: &str) -> Result> { - let cname = CString::new(name.to_owned()).expect("terminated string from provided name"); - let handle = self - .handle - .as_ref() - .expect("backing library loaded by this instance"); - - // SAFETY: Caller guarantees `Prototype` matches the symbol's actual - // type and ABI. Passing `as_bytes_with_nul()` avoids a redundant copy - // inside `libloading`. - let sym = unsafe { handle.get::(cname.as_bytes_with_nul()) }; - let sym = sym.expect("symbol found; binding successful"); - - Ok(sym) - } - - pub fn deleted(&self) -> Result { - let mtime = path::mtime(self.path())?; - let res = mtime > self.loaded; - - Ok(res) - } - - pub fn name(&self) -> Result { path::to_name(self.path()) } - - #[must_use] - pub fn path(&self) -> &OsString { &self.path } -} - -impl Drop for Module { - fn drop(&mut self) { - if self.handle.is_some() { - self.unload(); - } - } -} diff --git a/src/core/mods/new.rs b/src/core/mods/new.rs deleted file mode 100644 index e138b2046..000000000 --- a/src/core/mods/new.rs +++ /dev/null @@ -1,31 +0,0 @@ -use std::ffi::OsStr; - -use super::{Library, path}; -use crate::{Err, Result}; - -const OPEN_FLAGS: i32 = libloading::os::unix::RTLD_LAZY | libloading::os::unix::RTLD_GLOBAL; - -/// # Safety -/// Loads a shared library via `dlopen(3)`, which executes the library's -/// initialization routines (`.init_array` / constructors). The caller must -/// ensure the resolved module is trusted and ABI-compatible with this binary. -pub unsafe fn from_name(name: &str) -> Result { - let path = path::from_name(name)?; - // SAFETY: Upheld by caller. - unsafe { from_path(&path) } -} - -/// # Safety -/// Loads a shared library via `dlopen(3)`, which executes the library's -/// initialization routines (`.init_array` / constructors). The caller must -/// ensure `path` points to a trusted, ABI-compatible shared library. -pub unsafe fn from_path(path: &OsStr) -> Result { - // SAFETY: Caller guarantees `path` is a trusted, ABI-compatible library. - let lib = unsafe { Library::open(Some(path), OPEN_FLAGS) }; - if let Err(e) = lib { - let name = path::to_name(path)?; - return Err!("Loading module {name:?} failed: {e}"); - } - - Ok(lib.expect("module loaded")) -} diff --git a/src/core/mods/path.rs b/src/core/mods/path.rs deleted file mode 100644 index b792890b9..000000000 --- a/src/core/mods/path.rs +++ /dev/null @@ -1,41 +0,0 @@ -use std::{ - env::current_exe, - ffi::{OsStr, OsString}, - path::{Path, PathBuf}, - time::SystemTime, -}; - -use libloading::library_filename; - -use crate::Result; - -pub fn from_name(name: &str) -> Result { - let root = PathBuf::new(); - let exe_path = current_exe()?; - let exe_dir = exe_path.parent().unwrap_or(&root); - let mut mod_path = exe_dir.to_path_buf(); - let mod_file = library_filename(name); - mod_path.push(mod_file); - - Ok(mod_path.into_os_string()) -} - -pub fn to_name(path: &OsStr) -> Result { - let path = Path::new(path); - let name = path - .file_stem() - .expect("path file stem") - .to_str() - .expect("name string"); - - let name = name.strip_prefix("lib").unwrap_or(name).to_owned(); - - Ok(name) -} - -pub fn mtime(path: &OsStr) -> Result { - let meta = std::fs::metadata(path)?; - let mtime = meta.modified()?; - - Ok(mtime) -} diff --git a/src/core/server.rs b/src/core/server.rs index c84936478..328eb50ae 100644 --- a/src/core/server.rs +++ b/src/core/server.rs @@ -27,10 +27,6 @@ pub struct Server { /// observable used on shutdown and should not be modified. pub stopping: AtomicBool, - /// Reload/shutdown desired indicator; when false, shutdown is desired. This - /// is an observable used on shutdown and modifying is not recommended. - pub reloading: AtomicBool, - /// Restart desired; when true, restart it desired after shutdown. pub restarting: AtomicBool, @@ -60,7 +56,6 @@ impl Server { config: config::Manager::new(config), started: SystemTime::now(), stopping: AtomicBool::new(false), - reloading: AtomicBool::new(false), restarting: AtomicBool::new(false), runtime, signal: broadcast::channel::<&'static str>(1).0, @@ -69,25 +64,6 @@ impl Server { } } - pub fn reload(&self) -> Result<()> { - if cfg!(any(not(conduwuit_mods), not(feature = "conduwuit_mods"))) { - return Err!("Reloading not enabled"); - } - - if self.reloading.swap(true, Ordering::AcqRel) { - return Err!("Reloading already in progress"); - } - - if self.stopping.swap(true, Ordering::AcqRel) { - return Err!("Shutdown already in progress"); - } - - self.signal("SIGINT").inspect_err(|_| { - self.stopping.store(false, Ordering::Release); - self.reloading.store(false, Ordering::Release); - }) - } - pub fn restart(&self) -> Result { if self.restarting.swap(true, Ordering::AcqRel) { return Err!("Restart already in progress"); @@ -146,9 +122,6 @@ impl Server { #[inline] pub fn is_stopping(&self) -> bool { self.stopping.load(Ordering::Relaxed) } - #[inline] - pub fn is_reloading(&self) -> bool { self.reloading.load(Ordering::Relaxed) } - #[inline] pub fn is_restarting(&self) -> bool { self.restarting.load(Ordering::Relaxed) } diff --git a/src/database/mod.rs b/src/database/mod.rs index fcc4f4df7..020530219 100644 --- a/src/database/mod.rs +++ b/src/database/mod.rs @@ -5,9 +5,6 @@ extern crate rust_rocksdb as rocksdb; conduwuit_macros::introspect_crate! {} -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - #[cfg(test)] mod benches; mod cork; diff --git a/src/main/Cargo.toml b/src/main/Cargo.toml index c4477721f..40162bd5c 100644 --- a/src/main/Cargo.toml +++ b/src/main/Cargo.toml @@ -175,9 +175,6 @@ zstd_compression = [ "conduwuit-router/zstd_compression", "conduwuit-service/zstd_compression", ] -conduwuit_mods = [ - "conduwuit-core/conduwuit_mods", -] bindgen-static = [ # "bindgen/static" # "clang-sys/static" diff --git a/src/main/mod.rs b/src/main/mod.rs index cdc8e27ce..7c5bbe200 100644 --- a/src/main/mod.rs +++ b/src/main/mod.rs @@ -10,7 +10,6 @@ mod clap; mod deadlock; mod logging; mod metrics; -mod mods; mod panic; mod restart; mod runtime; @@ -63,9 +62,8 @@ pub fn run_with_args(args: &Args) -> Result<()> { Ok(()) } -/// Operate the server normally in release-mode static builds. This will start, -/// run and stop the server within the asynchronous runtime. -#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))] +/// Operate the server. This will start, run and stop the server within the +/// asynchronous runtime. #[tracing::instrument( name = "main", parent = None, @@ -114,37 +112,3 @@ async fn async_main(server: &Arc) -> Result<(), Error> { debug_info!("Exit runtime"); Ok(()) } - -/// Operate the server in developer-mode dynamic builds. This will start, run, -/// and hot-reload portions of the server as-needed before returning for an -/// actual shutdown. This is not available in release-mode or static builds. -#[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] -async fn async_main(server: &Arc) -> Result<(), Error> { - let mut starts = true; - let mut reloads = true; - while reloads { - if let Err(error) = mods::open(server).await { - error!("Loading router: {error}"); - return Err(error); - } - - let result = mods::run(server, starts).await; - if let Ok(result) = result { - (starts, reloads) = result; - } - - let force = !reloads || result.is_err(); - if let Err(error) = mods::close(server, force).await { - error!("Unloading router: {error}"); - return Err(error); - } - - if let Err(error) = result { - error!("{error}"); - return Err(error); - } - } - - debug_info!("Exit runtime"); - Ok(()) -} diff --git a/src/main/mods.rs b/src/main/mods.rs deleted file mode 100644 index c00c30f70..000000000 --- a/src/main/mods.rs +++ /dev/null @@ -1,174 +0,0 @@ -#![cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - -#[unsafe(no_link)] -extern crate conduwuit_service; - -use std::{ - future::Future, - pin::Pin, - sync::{Arc, atomic::Ordering}, -}; - -use conduwuit_core::{Error, Result, debug, error, mods}; -use conduwuit_service::Services; - -use crate::Server; - -type StartFuncResult = Pin>> + Send>>; -type StartFuncProto = fn(&Arc) -> StartFuncResult; - -type RunFuncResult = Pin> + Send>>; -type RunFuncProto = fn(&Arc) -> RunFuncResult; - -type StopFuncResult = Pin> + Send>>; -type StopFuncProto = fn(Arc) -> StopFuncResult; - -const RESTART_THRESH: &str = "conduwuit_service"; -const MODULE_NAMES: &[&str] = &[ - //"conduwuit_core", - "conduwuit_database", - "conduwuit_service", - "conduwuit_api", - "conduwuit_admin", - "conduwuit_router", -]; - -#[cfg(panic_trap)] -conduwuit_core::mod_init! {{ - conduwuit_core::debug::set_panic_trap(); -}} - -pub(crate) async fn run(server: &Arc, starts: bool) -> Result<(bool, bool), Error> { - let main_lock = server.mods.read().await; - let main_mod = (*main_lock).last().expect("main module loaded"); - if starts { - // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern - // "Rust" fn start` with signature matching `StartFuncProto`, compiled - // with the same toolchain and flags. - let start = unsafe { main_mod.get::("start")? }; - match start(&server.server).await { - | Ok(services) => server.services.lock().await.insert(services), - | Err(error) => { - error!("Starting server: {error}"); - return Err(error); - }, - }; - } - - server.server.stopping.store(false, Ordering::Release); - - // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern - // "Rust" fn run` with signature matching `RunFuncProto`, compiled with the - // same toolchain and flags. - let run = unsafe { main_mod.get::("run")? }; - if let Err(error) = run(server - .services - .lock() - .await - .as_ref() - .expect("services initialized")) - .await - { - error!("Running server: {error}"); - return Err(error); - } - - let reloads = server.server.reloading.swap(false, Ordering::AcqRel); - - let stops = !reloads || stale_from_mods(&main_lock)? <= restart_thresh(); - let starts = reloads && stops; - if stops { - // SAFETY: `conduwuit_router` exports `#[unsafe(no_mangle)] pub extern - // "Rust" fn stop` with signature matching `StopFuncProto`, compiled - // with the same toolchain and flags. - let stop = unsafe { main_mod.get::("stop")? }; - if let Err(error) = stop( - server - .services - .lock() - .await - .take() - .expect("services initialized"), - ) - .await - { - error!("Stopping server: {error}"); - return Err(error); - } - } - - Ok((starts, reloads)) -} - -pub(crate) async fn open(server: &Arc) -> Result { - let mut mods_lock = server.mods.write().await; - let mods: &mut Vec = &mut mods_lock; - debug!( - available = %available(), - loaded = %mods.len(), - "Loading modules", - ); - - for (i, name) in MODULE_NAMES.iter().enumerate() { - if mods.get(i).is_none() { - // SAFETY: `MODULE_NAMES` are this workspace's own hot-reloadable - // shared libraries built with the same compiler/ABI. - mods.push(unsafe { mods::Module::from_name(name)? }); - } - } - - Ok(mods.len()) -} - -pub(crate) async fn close(server: &Arc, force: bool) -> Result { - let stale = stale_count(server).await; - let mut mods_lock = server.mods.write().await; - let mods: &mut Vec = &mut mods_lock; - debug!( - available = %available(), - loaded = %mods.len(), - stale = %stale, - force, - "Unloading modules", - ); - - while mods.last().is_some() { - let module = &mods.last().expect("module"); - if force || module.deleted()? { - mods.pop(); - } else { - break; - } - } - - Ok(mods.len()) -} - -async fn stale_count(server: &Arc) -> usize { - let watermark = stale(server).await.unwrap_or(available()); - available().saturating_sub(watermark) -} - -async fn stale(server: &Arc) -> Result { - let mods_lock = server.mods.read().await; - stale_from_mods(&mods_lock) -} - -fn stale_from_mods(mods: &[mods::Module]) -> Result { - for (i, module) in mods.iter().enumerate() { - if module.deleted()? { - return Ok(i); - } - } - - Ok(mods.len()) -} - -fn restart_thresh() -> usize { - MODULE_NAMES - .iter() - .position(|&name| name.ends_with(RESTART_THRESH)) - .unwrap_or(MODULE_NAMES.len()) -} - -const fn available() -> usize { MODULE_NAMES.len() } diff --git a/src/main/server.rs b/src/main/server.rs index 28b9039ef..e75c9777b 100644 --- a/src/main/server.rs +++ b/src/main/server.rs @@ -27,10 +27,6 @@ pub(crate) struct Server { #[cfg(feature = "sentry_telemetry")] _sentry_guard: Option<::sentry::ClientInitGuard>, - - #[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - // Module instances; TODO: move to mods::loaded mgmt vector - pub(crate) mods: tokio::sync::RwLock>, } impl Server { @@ -87,9 +83,6 @@ impl Server { #[cfg(feature = "sentry_telemetry")] _sentry_guard: sentry_guard, - - #[cfg(all(conduwuit_mods, feature = "conduwuit_mods"))] - mods: tokio::sync::RwLock::new(Vec::new()), })) } diff --git a/src/main/signal.rs b/src/main/signal.rs index 42cade135..5cd9914fe 100644 --- a/src/main/signal.rs +++ b/src/main/signal.rs @@ -12,7 +12,6 @@ pub(super) async fn signal(server: Arc) { use unix::SignalKind; const CONSOLE: bool = cfg!(feature = "console"); - const RELOADING: bool = cfg!(all(conduwuit_mods, feature = "conduwuit_mods", not(CONSOLE))); let mut quit = unix::signal(SignalKind::quit()).expect("SIGQUIT handler"); let mut term = unix::signal(SignalKind::terminate()).expect("SIGTERM handler"); @@ -30,9 +29,7 @@ pub(super) async fn signal(server: Arc) { } warn!("Received {sig}"); - let result = if RELOADING && sig == "SIGINT" { - server.server.reload() - } else if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") { + let result = if matches!(sig, "SIGQUIT" | "SIGTERM") || (!CONSOLE && sig == "SIGINT") { server.server.shutdown() } else { server.server.signal(sig) diff --git a/src/router/mod.rs b/src/router/mod.rs index c6f909d36..d907de7be 100644 --- a/src/router/mod.rs +++ b/src/router/mod.rs @@ -16,11 +16,7 @@ use conduwuit::{Error, Result, Server}; use conduwuit_service::Services; use futures::{Future, FutureExt, TryFutureExt}; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - -#[unsafe(no_mangle)] -pub extern "Rust" fn start( +pub fn start( server: &Arc, ) -> Pin>> + Send>> { AssertUnwindSafe(run::start(server.clone())) @@ -30,10 +26,7 @@ pub extern "Rust" fn start( .boxed() } -#[unsafe(no_mangle)] -pub extern "Rust" fn stop( - services: Arc, -) -> Pin> + Send>> { +pub fn stop(services: Arc) -> Pin> + Send>> { AssertUnwindSafe(run::stop(services)) .catch_unwind() .map_err(Error::from_panic) @@ -41,10 +34,7 @@ pub extern "Rust" fn stop( .boxed() } -#[unsafe(no_mangle)] -pub extern "Rust" fn run( - services: &Arc, -) -> Pin> + Send>> { +pub fn run(services: &Arc) -> Pin> + Send>> { AssertUnwindSafe(run::run(services.clone())) .catch_unwind() .map_err(Error::from_panic) diff --git a/src/service/mod.rs b/src/service/mod.rs index 0cb476cb0..93738ecad 100644 --- a/src/service/mod.rs +++ b/src/service/mod.rs @@ -44,19 +44,13 @@ pub mod transactions; pub mod uiaa; pub mod users; -use std::collections::BTreeMap; +use std::{collections::BTreeMap, sync::LazyLock}; +use conduwuit::matrix::versions::versions; +use ruma::api::SupportedVersions; pub(crate) use service::{Args, Dep, Service}; pub use crate::services::Services; -conduwuit::mod_ctor! {} -conduwuit::mod_dtor! {} - -use std::sync::LazyLock; - -use conduwuit::matrix::versions::versions; -use ruma::api::SupportedVersions; - pub static SUPPORTED_VERSIONS: LazyLock = LazyLock::new(|| SupportedVersions::from_parts(&versions(), &BTreeMap::new()));