feat(sidecar): Phase B-3 — SidecarPool consolida sidecars en un runtime
Antes: cada spawn(card) creaba un thread + tokio runtime propio.
Para módulos con muchas sesiones (nouser daemon con 50+ Mónadas)
eso es 50 threads + 50 runtimes. Ahora: un thread + un runtime
tokio current_thread que hostea N tasks de sidecar.
API nueva (aditiva, no rompe spawn/spawn_with_handle):
let pool = SidecarPool::new()?;
pool.spawn(card1);
pool.spawn(card2);
pool.spawn_conscious(card_with_wit, wit);
pool.spawn_with_config(custom_config);
// pool drop = todas las sesiones cierran.
run_client se hace pública para que el pool pueda enqueuar tasks
externos al runtime con handle.spawn(run_client(config)).
nouser daemon migrado al pool. Verificación con ps -L:
$ ps -L -p $(pidof nouser)
LWP CMD
28817 nouser # main thread
28819 brahman-sidecar # pool thread (todas las sesiones)
Antes serían 6+ LWP (1 main + N sesiones). Ahora 2 fijos sin
importar cuántas Mónadas se publiquen.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,7 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![warn(rust_2018_idioms)]
|
||||
|
||||
use std::sync::mpsc;
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -79,6 +80,85 @@ pub fn spawn_with_handle(config: SidecarConfig) -> std::io::Result<JoinHandle<()
|
||||
.spawn(move || run_thread(config))
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
// SidecarPool — un solo runtime tokio compartido por N sesiones
|
||||
// =====================================================================
|
||||
|
||||
/// Pool consolidado: un único thread con un runtime tokio
|
||||
/// `current_thread` que hostea N tasks de sidecar simultáneas.
|
||||
///
|
||||
/// Para módulos con muchas sesiones (p. ej. `nouser daemon` publicando
|
||||
/// 50+ Mónadas), evita el costo de tener un thread+runtime por cada
|
||||
/// sesión.
|
||||
///
|
||||
/// **API**:
|
||||
/// - `SidecarPool::new()` crea el pool (spawn del thread runtime).
|
||||
/// - `pool.spawn(card)` añade una sesión sin WIT.
|
||||
/// - `pool.spawn_conscious(card, wit)` añade una sesión con WIT.
|
||||
/// - `pool.spawn_with_config(config)` para configuración custom.
|
||||
///
|
||||
/// El pool se mantiene vivo mientras exista. Si el `SidecarPool`
|
||||
/// se dropea, el thread interno termina y todas las sesiones cierran.
|
||||
pub struct SidecarPool {
|
||||
handle: tokio::runtime::Handle,
|
||||
_thread: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl SidecarPool {
|
||||
/// Crea un pool nuevo. Bloquea hasta que el runtime esté listo.
|
||||
pub fn new() -> std::io::Result<Self> {
|
||||
let (handle_tx, handle_rx) = mpsc::sync_channel::<tokio::runtime::Handle>(0);
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("brahman-sidecar-pool".into())
|
||||
.spawn(move || {
|
||||
let rt = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
.enable_time()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
warn!(error = %e, "tokio runtime falló — pool muerto");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if handle_tx.send(rt.handle().clone()).is_err() {
|
||||
return;
|
||||
}
|
||||
// Mantenemos el runtime vivo mientras existan tasks.
|
||||
rt.block_on(std::future::pending::<()>());
|
||||
})?;
|
||||
let handle = handle_rx
|
||||
.recv()
|
||||
.map_err(|_| std::io::Error::other("pool runtime no respondió"))?;
|
||||
Ok(Self {
|
||||
handle,
|
||||
_thread: thread,
|
||||
})
|
||||
}
|
||||
|
||||
/// Añade una sesión agnóstica al pool (sin WIT).
|
||||
pub fn spawn(&self, card: Card) {
|
||||
self.spawn_with_config(SidecarConfig::new(card));
|
||||
}
|
||||
|
||||
/// Añade una sesión consciente (con WIT) al pool.
|
||||
pub fn spawn_conscious(&self, card: Card, wit: WitInterface) {
|
||||
self.spawn_with_config(SidecarConfig::new(card).with_wit(wit));
|
||||
}
|
||||
|
||||
/// Añade una sesión con configuración custom.
|
||||
pub fn spawn_with_config(&self, config: SidecarConfig) {
|
||||
self.handle.spawn(run_client(config));
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for SidecarPool {
|
||||
fn default() -> Self {
|
||||
Self::new().expect("falló SidecarPool::new")
|
||||
}
|
||||
}
|
||||
|
||||
fn run_thread(config: SidecarConfig) {
|
||||
let rt = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_io()
|
||||
@@ -94,7 +174,9 @@ fn run_thread(config: SidecarConfig) {
|
||||
rt.block_on(run_client(config));
|
||||
}
|
||||
|
||||
async fn run_client(config: SidecarConfig) {
|
||||
/// Bucle async del sidecar. Público para que `SidecarPool` lo use vía
|
||||
/// `handle.spawn(run_client(...))` desde código externo al runtime.
|
||||
pub async fn run_client(config: SidecarConfig) {
|
||||
let path = transport::default_socket_path();
|
||||
let conscious = config.wit.is_some();
|
||||
let mut client = match Client::connect_with(&path, config.card, config.wit).await {
|
||||
|
||||
Reference in New Issue
Block a user