refactor(treewide): get rid of compile time build environment introspection

It's cursed and not very useful. Still a few uses of ctor left, but oh well.
This commit is contained in:
K900 2026-01-16 13:49:46 +03:00
parent ebc8df1c4d
commit cb79a3b9d7
29 changed files with 8 additions and 366 deletions

6
Cargo.lock generated
View file

@ -993,7 +993,6 @@ dependencies = [
"conduwuit_service",
"console-subscriber",
"const-str",
"ctor",
"hardened_malloc-rs",
"log",
"opentelemetry",
@ -1022,7 +1021,6 @@ dependencies = [
"conduwuit_macros",
"conduwuit_service",
"const-str",
"ctor",
"futures",
"log",
"ruma",
@ -1046,7 +1044,6 @@ dependencies = [
"conduwuit_core",
"conduwuit_service",
"const-str",
"ctor",
"futures",
"hmac",
"http",
@ -1141,7 +1138,6 @@ dependencies = [
"async-channel",
"conduwuit_core",
"const-str",
"ctor",
"futures",
"log",
"minicbor",
@ -1178,7 +1174,6 @@ dependencies = [
"conduwuit_service",
"conduwuit_web",
"const-str",
"ctor",
"futures",
"http",
"http-body-util",
@ -1209,7 +1204,6 @@ dependencies = [
"conduwuit_core",
"conduwuit_database",
"const-str",
"ctor",
"either",
"futures",
"hickory-resolver",

View file

@ -118,10 +118,6 @@ Print detailed tokio runtime metrics accumulated since last command invocation
Print the current time
## `!admin debug list-dependencies`
List dependencies
## `!admin debug database-stats`
Get database statistics

View file

@ -16,10 +16,6 @@ Show configuration values
Reload configuration values
## `!admin server list-features`
List the features built into the server
## `!admin server memory-usage`
Print database memory usage statistics

View file

@ -87,7 +87,6 @@ serde-saphyr.workspace = true
tokio.workspace = true
tracing-subscriber.workspace = true
tracing.workspace = true
ctor.workspace = true
[lints]
workspace = true

View file

@ -819,32 +819,6 @@ pub(super) async fn time(&self) -> Result {
self.write_str(&now).await
}
#[admin_command]
pub(super) async fn list_dependencies(&self, names: bool) -> Result {
if names {
let out = info::cargo::dependencies_names().join(" ");
return self.write_str(&out).await;
}
let mut out = String::new();
let deps = info::cargo::dependencies();
writeln!(out, "| name | version | features |")?;
writeln!(out, "| ---- | ------- | -------- |")?;
for (name, dep) in deps {
let version = dep.try_req().unwrap_or("*");
let feats = dep.req_features();
let feats = if !feats.is_empty() {
feats.join(" ")
} else {
String::new()
};
writeln!(out, "| {name} | {version} | {feats} |")?;
}
self.write_str(&out).await
}
#[admin_command]
pub(super) async fn database_stats(
&self,

View file

@ -206,12 +206,6 @@ pub enum DebugCommand {
/// Print the current time
Time,
/// List dependencies
ListDependencies {
#[arg(short, long)]
names: bool,
},
/// Get database statistics
DatabaseStats {
property: Option<String>,

View file

@ -30,11 +30,8 @@ pub(crate) use crate::{context::Context, utils::get_room_info};
pub(crate) const PAGE_SIZE: usize = 100;
use ctor::{ctor, dtor};
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
conduwuit::rustc_flags_capture! {}
pub use crate::admin::AdminCommand;

View file

@ -1,7 +1,7 @@
use std::{fmt::Write, path::PathBuf, sync::Arc};
use std::{path::PathBuf, sync::Arc};
use conduwuit::{
Err, Result, info,
Err, Result,
utils::{stream::IterStream, time},
warn,
};
@ -59,34 +59,6 @@ pub(super) async fn reload_config(&self, path: Option<PathBuf>) -> Result {
.await
}
#[admin_command]
pub(super) async fn list_features(&self, available: bool, enabled: bool, comma: bool) -> Result {
let delim = if comma { "," } else { " " };
if enabled && !available {
let features = info::rustc::features().join(delim);
let out = format!("`\n{features}\n`");
return self.write_str(&out).await;
}
if available && !enabled {
let features = info::cargo::features().join(delim);
let out = format!("`\n{features}\n`");
return self.write_str(&out).await;
}
let mut features = String::new();
let enabled = info::rustc::features();
let available = info::cargo::features();
for feature in available {
let active = enabled.contains(&feature.as_str());
let emoji = if active { "" } else { "" };
let remark = if active { "[enabled]" } else { "" };
writeln!(features, "{emoji} {feature} {remark}")?;
}
self.write_str(&features).await
}
#[admin_command]
pub(super) async fn memory_usage(&self) -> Result {
let services_usage = self.services.memory_usage().await?;

View file

@ -21,18 +21,6 @@ pub enum ServerCommand {
path: Option<PathBuf>,
},
/// List the features built into the server
ListFeatures {
#[arg(short, long)]
available: bool,
#[arg(short, long)]
enabled: bool,
#[arg(short, long)]
comma: bool,
},
/// Print database memory usage statistics
MemoryUsage,

View file

@ -91,7 +91,6 @@ serde.workspace = true
sha1.workspace = true
tokio.workspace = true
tracing.workspace = true
ctor.workspace = true
[lints]
workspace = true

View file

@ -371,11 +371,3 @@ pub(crate) async fn is_ignored_invite(
.invite_filter_level(&sender_user, recipient_user)
.await == FilterLevel::Ignore
}
#[cfg_attr(debug_assertions, ctor::ctor)]
fn _is_sorted() {
debug_assert!(
IGNORED_MESSAGE_TYPES.is_sorted(),
"IGNORED_MESSAGE_TYPES must be sorted by the developer"
);
}

View file

@ -47,7 +47,7 @@ type Key = ArrayVec<usize, KEY_SEGS>;
const NAME_MAX: usize = 128;
const KEY_SEGS: usize = 8;
#[crate::ctor]
#[ctor::ctor]
fn _static_initialization() {
acq_epoch().expect("pre-initialization of jemalloc failed");
acq_epoch().expect("pre-initialization of jemalloc failed");

View file

@ -62,7 +62,7 @@ pub const INFO_SPAN_LEVEL: Level = if cfg!(debug_assertions) {
pub static DEBUGGER: LazyLock<bool> =
LazyLock::new(|| env::var("_").unwrap_or_default().ends_with("gdb"));
#[cfg_attr(debug_assertions, crate::ctor)]
#[cfg_attr(debug_assertions, ctor::ctor)]
#[cfg_attr(not(debug_assertions), allow(dead_code))]
fn set_panic_trap() {
if !*DEBUGGER {

View file

@ -1,95 +0,0 @@
//! Information about the build related to Cargo. This is a frontend interface
//! informed by proc-macros that capture raw information at build time which is
//! further processed at runtime either during static initialization or as
//! necessary.
use std::sync::OnceLock;
use cargo_toml::{DepsSet, Manifest};
use conduwuit_macros::cargo_manifest;
use crate::Result;
// Raw captures of the cargo manifest for each crate. This is provided by a
// proc-macro at build time since the source directory and the cargo toml's may
// not be present during execution.
#[cargo_manifest]
const WORKSPACE_MANIFEST: &'static str = ();
#[cargo_manifest(crate = "macros")]
const MACROS_MANIFEST: &'static str = ();
#[cargo_manifest(crate = "core")]
const CORE_MANIFEST: &'static str = ();
#[cargo_manifest(crate = "database")]
const DATABASE_MANIFEST: &'static str = ();
#[cargo_manifest(crate = "service")]
const SERVICE_MANIFEST: &'static str = ();
#[cargo_manifest(crate = "admin")]
const ADMIN_MANIFEST: &'static str = ();
#[cargo_manifest(crate = "router")]
const ROUTER_MANIFEST: &'static str = ();
#[cargo_manifest(crate = "main")]
const MAIN_MANIFEST: &'static str = ();
/// Processed list of features across all project crates. This is generated from
/// the data in the MANIFEST strings and contains all possible project features.
/// For *enabled* features see the info::rustc module instead.
static FEATURES: OnceLock<Vec<String>> = OnceLock::new();
/// Processed list of dependencies. This is generated from the data captured in
/// the MANIFEST.
static DEPENDENCIES: OnceLock<DepsSet> = OnceLock::new();
#[must_use]
pub fn dependencies_names() -> Vec<&'static str> {
dependencies().keys().map(String::as_str).collect()
}
pub fn dependencies() -> &'static DepsSet {
DEPENDENCIES.get_or_init(|| {
init_dependencies().unwrap_or_else(|e| panic!("Failed to initialize dependencies: {e}"))
})
}
/// List of all possible features for the project. For *enabled* features in
/// this build see the companion function in info::rustc.
pub fn features() -> &'static Vec<String> {
FEATURES.get_or_init(|| {
init_features().unwrap_or_else(|e| panic!("Failed initialize features: {e}"))
})
}
fn init_features() -> Result<Vec<String>> {
let mut features = Vec::new();
append_features(&mut features, WORKSPACE_MANIFEST)?;
append_features(&mut features, MACROS_MANIFEST)?;
append_features(&mut features, CORE_MANIFEST)?;
append_features(&mut features, DATABASE_MANIFEST)?;
append_features(&mut features, SERVICE_MANIFEST)?;
append_features(&mut features, ADMIN_MANIFEST)?;
append_features(&mut features, ROUTER_MANIFEST)?;
append_features(&mut features, MAIN_MANIFEST)?;
features.sort();
features.dedup();
Ok(features)
}
fn append_features(features: &mut Vec<String>, manifest: &str) -> Result<()> {
let manifest = Manifest::from_str(manifest)?;
features.extend(manifest.features.keys().cloned());
Ok(())
}
fn init_dependencies() -> Result<DepsSet> {
let manifest = Manifest::from_str(WORKSPACE_MANIFEST)?;
let deps_set = manifest
.workspace
.as_ref()
.expect("manifest has workspace section")
.dependencies
.clone();
Ok(deps_set)
}

View file

@ -1,12 +1,5 @@
//! Information about the project. This module contains version, build, system,
//! etc information which can be queried by admins or used by developers.
pub mod cargo;
pub mod room_version;
pub mod rustc;
pub mod version;
pub use conduwuit_macros::rustc_flags_capture;
pub const MODULE_ROOT: &str = const_str::split!(std::module_path!(), "::")[0];
pub const CRATE_PREFIX: &str = const_str::split!(MODULE_ROOT, '_')[0];

View file

@ -1,54 +0,0 @@
//! Information about the build related to rustc. This is a frontend interface
//! informed by proc-macros at build time. Since the project is split into
//! several crates, lower-level information is supplied from each crate during
//! static initialization.
use std::{collections::BTreeMap, sync::OnceLock};
use crate::utils::exchange;
/// Raw capture of rustc flags used to build each crate in the project. Informed
/// by rustc_flags_capture macro (one in each crate's mod.rs). This is
/// done during static initialization which is why it's mutex-protected and pub.
/// Should not be written to by anything other than our macro.
///
/// We specifically use a std mutex here because parking_lot cannot be used
/// after thread local storage is destroyed on MacOS.
pub static FLAGS: std::sync::Mutex<BTreeMap<&str, &[&str]>> =
std::sync::Mutex::new(BTreeMap::new());
/// Processed list of enabled features across all project crates. This is
/// generated from the data in FLAGS.
static FEATURES: OnceLock<Vec<&'static str>> = OnceLock::new();
/// List of features enabled for the project.
pub fn features() -> &'static Vec<&'static str> { FEATURES.get_or_init(init_features) }
fn init_features() -> Vec<&'static str> {
let mut features = Vec::new();
FLAGS
.lock()
.expect("locked")
.iter()
.for_each(|(_, flags)| append_features(&mut features, flags));
features.sort_unstable();
features.dedup();
features
}
fn append_features(features: &mut Vec<&'static str>, flags: &[&'static str]) {
let mut next_is_cfg = false;
for flag in flags {
let is_cfg = *flag == "--cfg";
let is_feature = flag.starts_with("feature=");
if exchange(&mut next_is_cfg, is_cfg) && is_feature {
if let Some(feature) = flag
.split_once('=')
.map(|(_, feature)| feature.trim_matches('"'))
{
features.push(feature);
}
}
}
}

View file

@ -22,7 +22,7 @@ pub use ::tracing;
pub use config::Config;
pub use error::Error;
pub use info::{
rustc_flags_capture, version,
version,
version::{name, version},
};
pub use matrix::{
@ -30,12 +30,10 @@ pub use matrix::{
};
pub use parking_lot::{Mutex as SyncMutex, RwLock as SyncRwLock};
pub use server::Server;
pub use utils::{ctor, dtor, implement, result, result::Result};
pub use utils::{implement, result, result::Result};
pub use crate as conduwuit_core;
rustc_flags_capture! {}
#[cfg(any(not(conduwuit_mods), not(feature = "conduwuit_mods")))]
pub mod mods {
#[macro_export]

View file

@ -22,7 +22,6 @@ pub mod time;
pub mod with_lock;
pub use ::conduwuit_macros::implement;
pub use ::ctor::{ctor, dtor};
pub use self::{
arrayvec::ArrayVecExt,

View file

@ -64,7 +64,6 @@ serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
tracing.workspace = true
ctor.workspace = true
[lints]
workspace = true

View file

@ -3,11 +3,8 @@
extern crate conduwuit_core as conduwuit;
extern crate rust_rocksdb as rocksdb;
use ctor::{ctor, dtor};
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
conduwuit::rustc_flags_capture! {}
#[cfg(test)]
mod benches;

View file

@ -1,47 +0,0 @@
use std::{fs::read_to_string, path::PathBuf};
use proc_macro::{Span, TokenStream};
use quote::quote;
use syn::{Error, ItemConst, Meta};
use crate::{Result, utils};
pub(super) fn manifest(item: ItemConst, args: &[Meta]) -> Result<TokenStream> {
let member = utils::get_named_string(args, "crate");
let path = manifest_path(member.as_deref())?;
let manifest = read_to_string(&path).unwrap_or_default();
let val = manifest.as_str();
let name = item.ident;
let ret = quote! {
const #name: &'static str = #val;
};
Ok(ret.into())
}
#[allow(clippy::option_env_unwrap)]
fn manifest_path(member: Option<&str>) -> Result<PathBuf> {
let Some(path) = option_env!("CARGO_MANIFEST_DIR") else {
return Err(Error::new(
Span::call_site().into(),
"missing CARGO_MANIFEST_DIR in environment",
));
};
let mut path: PathBuf = path.into();
// conduwuit/src/macros/ -> conduwuit/src/
path.pop();
if let Some(member) = member {
// conduwuit/$member/Cargo.toml
path.push(member);
} else {
// conduwuit/src/ -> conduwuit/
path.pop();
}
path.push("Cargo.toml");
Ok(path)
}

View file

@ -1,15 +1,13 @@
mod admin;
mod cargo;
mod config;
mod debug;
mod implement;
mod refutable;
mod rustc;
mod utils;
use proc_macro::TokenStream;
use syn::{
Error, Item, ItemConst, ItemEnum, ItemFn, ItemStruct, Meta,
Error, Item, ItemEnum, ItemFn, ItemStruct, Meta,
parse::{Parse, Parser},
parse_macro_input,
};
@ -26,19 +24,11 @@ pub fn admin_command_dispatch(args: TokenStream, input: TokenStream) -> TokenStr
attribute_macro::<ItemEnum, _>(args, input, admin::command_dispatch)
}
#[proc_macro_attribute]
pub fn cargo_manifest(args: TokenStream, input: TokenStream) -> TokenStream {
attribute_macro::<ItemConst, _>(args, input, cargo::manifest)
}
#[proc_macro_attribute]
pub fn recursion_depth(args: TokenStream, input: TokenStream) -> TokenStream {
attribute_macro::<Item, _>(args, input, debug::recursion_depth)
}
#[proc_macro]
pub fn rustc_flags_capture(args: TokenStream) -> TokenStream { rustc::flags_capture(args) }
#[proc_macro_attribute]
pub fn refutable(args: TokenStream, input: TokenStream) -> TokenStream {
attribute_macro::<ItemFn, _>(args, input, refutable::refutable)

View file

@ -1,29 +0,0 @@
use proc_macro::TokenStream;
use quote::quote;
pub(super) fn flags_capture(args: TokenStream) -> TokenStream {
let cargo_crate_name = std::env::var("CARGO_CRATE_NAME");
let crate_name = match cargo_crate_name.as_ref() {
| Err(_) => return args,
| Ok(crate_name) => crate_name.trim_start_matches("conduwuit_"),
};
let flag = std::env::args().collect::<Vec<_>>();
let flag_len = flag.len();
let ret = quote! {
pub static RUSTC_FLAGS: [&str; #flag_len] = [#( #flag ),*];
#[ctor]
fn _set_rustc_flags() {
conduwuit_core::info::rustc::FLAGS.lock().expect("locked").insert(#crate_name, &RUSTC_FLAGS);
}
// static strings have to be yanked on module unload
#[dtor]
fn _unset_rustc_flags() {
conduwuit_core::info::rustc::FLAGS.lock().expect("locked").remove(#crate_name);
}
};
ret.into()
}

View file

@ -207,7 +207,6 @@ clap.workspace = true
console-subscriber.optional = true
console-subscriber.workspace = true
const-str.workspace = true
ctor.workspace = true
log.workspace = true
opentelemetry.optional = true
opentelemetry.workspace = true

View file

@ -2,7 +2,7 @@
use std::sync::{Arc, atomic::Ordering};
use conduwuit_core::{debug_info, error, rustc_flags_capture};
use conduwuit_core::{debug_info, error};
mod clap;
mod logging;
@ -13,11 +13,8 @@ mod sentry;
mod server;
mod signal;
use ctor::{ctor, dtor};
use server::Server;
rustc_flags_capture! {}
pub use conduwuit_core::{Error, Result};
pub use crate::clap::Args;

View file

@ -122,7 +122,6 @@ tokio.workspace = true
tower.workspace = true
tower-http.workspace = true
tracing.workspace = true
ctor.workspace = true
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
sd-notify.workspace = true

View file

@ -12,12 +12,10 @@ use std::{panic::AssertUnwindSafe, pin::Pin, sync::Arc};
use conduwuit::{Error, Result, Server};
use conduwuit_service::Services;
use ctor::{ctor, dtor};
use futures::{Future, FutureExt, TryFutureExt};
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
conduwuit::rustc_flags_capture! {}
#[unsafe(no_mangle)]
pub extern "Rust" fn start(

View file

@ -118,7 +118,6 @@ webpage.optional = true
blurhash.workspace = true
blurhash.optional = true
recaptcha-verify = { version = "0.1.5", default-features = false }
ctor.workspace = true
[target.'cfg(all(unix, target_os = "linux"))'.dependencies]
sd-notify.workspace = true

View file

@ -34,11 +34,9 @@ pub mod transaction_ids;
pub mod uiaa;
pub mod users;
use ctor::{ctor, dtor};
pub(crate) use service::{Args, Dep, Service};
pub use crate::services::Services;
conduwuit::mod_ctor! {}
conduwuit::mod_dtor! {}
conduwuit::rustc_flags_capture! {}