From 0923a6d27e76132ae1bc292a9c6a28cfbad4b768 Mon Sep 17 00:00:00 2001 From: ing-eoking Date: Tue, 3 Nov 2026 17:03:31 +0900 Subject: [PATCH] INTERNAL: Make a lane job from each item event of the engine --- src/aio.rs | 54 +++++--- src/aio/pool.rs | 98 ++++++--------- src/cmd.rs | 9 +- src/event.rs | 269 ++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 + src/memcached/server.rs | 20 ++- 6 files changed, 372 insertions(+), 80 deletions(-) create mode 100644 src/event.rs diff --git a/src/aio.rs b/src/aio.rs index 18c0d19..856fc29 100644 --- a/src/aio.rs +++ b/src/aio.rs @@ -6,23 +6,31 @@ use std::sync::{Arc, OnceLock}; use crate::error::Error; use crate::guard; -use crate::memcached::server::{Connection, ResponseHandler}; -use crate::protocol::Request; -use pool::Op; -pub use pool::start; +use crate::memcached::server::{Connection, IoWaiter, ResponseHandler}; +pub use pool::{Op, start, submit as begin}; -/// Hands `request` to a lane, to be replied to from the io callback; an error is for `execute` to -/// reply with. -pub fn begin(conn: Connection, request: Request<'_>) -> Result<(), Error> { - let op = Op::new(request)?; - let reply = Arc::new(OnceLock::new()); - // SAFETY: the only caller, `cmd::run`, runs in `execute`. - let waiter = unsafe { conn.wait_for_io() }; - let data = Arc::into_raw(Arc::clone(&reply)); - // SAFETY: as above, and `wake` takes back the count `data` holds. - unsafe { conn.on_io_complete(wake, data.cast_mut().cast()) }; - pool::submit(op, reply, waiter); - Ok(()) +/// A connection waiting for a lane to answer it from the io callback; dropped unanswered, it +/// answers an internal error. +pub struct Waiter { + reply: Arc>>, + _wait: IoWaiter, +} + +impl Waiter { + pub fn new(conn: Connection) -> Self { + let reply = Arc::new(OnceLock::new()); + // SAFETY: its callers, `cmd::run` and `event::offer`, run in `execute`. + let wait = unsafe { conn.wait_for_io() }; + let data = Arc::into_raw(Arc::clone(&reply)); + // SAFETY: as above, and `wake` takes back the count `data` holds. + unsafe { conn.on_io_complete(wake, data.cast_mut().cast()) }; + Self { reply, _wait: wait } + } + + /// Leaves `reply` for the io callback, then wakes the connection. + pub fn answer(self, reply: Cow<'static, [u8]>) { + let _ = self.reply.set(reply); + } } unsafe extern "C" fn wake( @@ -33,7 +41,7 @@ unsafe extern "C" fn wake( guard( || false, || { - // SAFETY: `data` is the count from `begin`, and the core calls this once. + // SAFETY: `data` is the count from `Waiter::new`, and the core calls this once. let reply = unsafe { Arc::from_raw(data.cast::>>()) }; let reply = reply.get().map_or(Error::Internal.reply(), AsRef::as_ref); // SAFETY: the server is running the io callback for `cookie`, with `handler`. @@ -42,6 +50,11 @@ unsafe extern "C" fn wake( ) } +#[cfg(test)] +pub fn start_once() { + pool::start_once(); +} + #[cfg(test)] mod tests { use std::sync::mpsc::channel; @@ -50,7 +63,7 @@ mod tests { use super::*; use crate::index; use crate::memcached::server::fake; - use crate::protocol::{self, Tokens}; + use crate::protocol::{self, Request, Tokens}; use crate::quant::Vector; #[test] @@ -68,7 +81,10 @@ mod tests { let tokens = Tokens::from_line("vop search aio vector 16 3"); let mut request = protocol::parse(tokens.words()).unwrap(); request.set_vector(Vector::F32(vec![0.0; 4])); - assert_eq!(begin(conn.connection(), request), Ok(())); + begin( + Op::new(request).unwrap(), + Some(Waiter::new(conn.connection())), + ); assert_eq!(rx.recv_timeout(Duration::from_secs(10)).unwrap(), 7); assert!(conn.reply().is_empty()); assert!(conn.run_callback()); diff --git a/src/aio/pool.rs b/src/aio/pool.rs index be0a9ae..6848cb3 100644 --- a/src/aio/pool.rs +++ b/src/aio/pool.rs @@ -5,33 +5,36 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::ptr; use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; -use std::sync::{Arc, Barrier, OnceLock}; +use std::sync::{Arc, Barrier}; +use super::Waiter; use crate::error::Error; -use crate::memcached::server::IoWaiter; use crate::protocol::{Request, Search, Source}; use crate::quant::Vector; const NUM_LANES: usize = 32; -/// A command for a lane, where it leaves the reply for the io callback, and the connection to wake -/// once it is done. +/// An op for a lane, and the connection it answers: none for a change from replication or replay. struct Task { op: Op, - /// Unset if its lane did not finish it. - reply: Arc>>, - _wait: IoWaiter, + waiter: Option, } #[expect(dead_code, reason = "no op runs yet")] +#[rustfmt::skip] pub enum Op { Search { index: String, vector: Vector }, - Upsert { index: String, vkey: String }, - SetMeta { index: String, vkey: String }, - Delete { index: String, vkey: String }, + Insert { index: String, key: usize }, + Replace { index: String, old: usize, new: usize }, + /// A replace from `vop setmeta`, answered as a store. + SetMeta { index: String, old: usize, new: usize }, + Delete { index: String, key: usize }, + Create { index: String, config: Vec }, + Drop { index: String }, } impl Op { + /// A command's search; a write's op comes from the element event it raises. pub fn new(request: Request<'_>) -> Result { match request { // Waits for the engine to give the vkey's vector. @@ -43,30 +46,21 @@ impl Op { index: index.into(), vector, }), - Request::Upsert(u) => Ok(Self::Upsert { - index: u.index.into(), - vkey: u.vkey.into(), - }), - Request::SetMeta(m) => Ok(Self::SetMeta { - index: m.index.into(), - vkey: m.vkey.into(), - }), - Request::Delete { index, vkey } => Ok(Self::Delete { - index: index.into(), - vkey: vkey.into(), - }), _ => Err(Error::NotSupported), } } - /// A search goes to the least busy lane; a write goes to its vkey's lane, so that writes on one - /// vkey run in the order they came. + /// A search goes to the least busy lane; a write goes to its index's lane, so that writes on + /// one index run in the order the engine made them. fn lane(&self) -> &'static Lane { match self { Self::Search { .. } => idlest(), - Self::Upsert { index, vkey } - | Self::SetMeta { index, vkey } - | Self::Delete { index, vkey } => lane_of(index, vkey), + Self::Insert { index, .. } + | Self::Replace { index, .. } + | Self::SetMeta { index, .. } + | Self::Delete { index, .. } + | Self::Create { index, .. } + | Self::Drop { index } => lane_of(index), } } } @@ -74,11 +68,17 @@ impl Op { impl Task { fn run(self) { let reply = match self.op { - Op::Search { .. } | Op::Upsert { .. } | Op::SetMeta { .. } | Op::Delete { .. } => { - Error::NotSupported.reply() - } + Op::Search { .. } + | Op::Insert { .. } + | Op::Replace { .. } + | Op::SetMeta { .. } + | Op::Delete { .. } + | Op::Create { .. } + | Op::Drop { .. } => Error::NotSupported.reply(), }; - let _ = self.reply.set(Cow::Borrowed(reply)); + if let Some(waiter) = self.waiter { + waiter.answer(Cow::Borrowed(reply)); + } } } @@ -177,22 +177,15 @@ fn idlest() -> &'static Lane { idlest } -fn lane_of(index: &str, vkey: &str) -> &'static Lane { +fn lane_of(index: &str) -> &'static Lane { let mut hasher = DefaultHasher::new(); - (index, vkey).hash(&mut hasher); + index.hash(&mut hasher); &lanes()[(hasher.finish() % NUM_LANES as u64) as usize] } -/// Runs `op` on its lane, which leaves its reply in `reply`, then wakes the connection. -pub fn submit(op: Op, reply: Arc>>, waiter: IoWaiter) { - send( - op.lane(), - Task { - op, - reply, - _wait: waiter, - }, - ); +/// Runs `op` on its lane, which then answers `waiter`. +pub fn submit(op: Op, waiter: Option) { + send(op.lane(), Task { op, waiter }); } fn send(lane: &Lane, task: Task) { @@ -228,17 +221,8 @@ mod tests { index: "idx".into(), vector: Vector::default(), }; - let reply = Arc::default(); - // SAFETY: the fake server takes a wait on a `Conn` at any time. - let waiter = unsafe { conn.connection().wait_for_io() }; - send( - &lanes()[3], - Task { - op, - reply, - _wait: waiter, - }, - ); + let waiter = Some(Waiter::new(conn.connection())); + send(&lanes()[3], Task { op, waiter }); } let got: Vec = (0..100) .map(|_| rx.recv_timeout(Duration::from_secs(10)).unwrap()) @@ -247,11 +231,11 @@ mod tests { } #[test] - fn one_vkey_always_gets_one_lane() { + fn one_index_always_gets_one_lane() { start_once(); - assert!(ptr::eq(lane_of("idx", "a"), lane_of("idx", "a"))); + assert!(ptr::eq(lane_of("idx"), lane_of("idx"))); let spread = (0..1000) - .map(|n| ptr::from_ref(lane_of("idx", &format!("v{n}")))) + .map(|n| ptr::from_ref(lane_of(&format!("idx{n}")))) .collect::>(); assert_eq!(spread.len(), NUM_LANES); } diff --git a/src/cmd.rs b/src/cmd.rs index 6e3eade..a0c5cc0 100644 --- a/src/cmd.rs +++ b/src/cmd.rs @@ -1,4 +1,4 @@ -use crate::aio; +use crate::aio::{self, Op, Waiter}; use crate::error::Error; use crate::index; use crate::memcached::server::Connection; @@ -13,8 +13,11 @@ pub fn run(conn: Connection, request: Result, Error>) -> bool { Err(e) => e.reply(), }, Ok(request) if index::dimensions(request.index()).is_none() => Error::NotFound.reply(), - Ok(request) => match aio::begin(conn, request) { - Ok(()) => return true, + Ok(request) => match Op::new(request) { + Ok(op) => { + aio::begin(op, Some(Waiter::new(conn))); + return true; + } Err(e) => e.reply(), }, Err(e) => e.reply(), diff --git a/src/event.rs b/src/event.rs new file mode 100644 index 0000000..f9a1c32 --- /dev/null +++ b/src/event.rs @@ -0,0 +1,269 @@ +use std::borrow::Cow; +use std::cell::Cell; +use std::os::raw::c_void; + +use crate::aio::{self, Op, Waiter}; +use crate::error::Error; +use crate::guard; +use crate::memcached::engine::Item; +use crate::memcached::ffi::{ + ENGINE_EVENT_TYPE, ENGINE_EVENT_TYPE_ON_EVENT_ITEM, event_data_t, + event_type_t_EVENT_ELEM_DELETE as EVENT_ELEM_DELETE, + event_type_t_EVENT_ELEM_INSERT as EVENT_ELEM_INSERT, + event_type_t_EVENT_ELEM_REPLACE as EVENT_ELEM_REPLACE, + event_type_t_EVENT_ITEM_LINK as EVENT_ITEM_LINK, + event_type_t_EVENT_ITEM_UNLINK as EVENT_ITEM_UNLINK, +}; +use crate::memcached::server::{self, Connection}; + +/// The event a command's write raises, which its lane answers the command from. +#[derive(Clone, Copy, PartialEq, Eq)] +#[expect(dead_code, reason = "the write commands are not in yet")] +pub enum Expect { + Create, + Drop, + /// An insert, or a replace of the element at the vkey. + Upsert, + /// A replace, answered as a store. + SetMeta, + Delete, +} + +/// A command waiting for the event of its write. +struct Pending { + expect: Expect, + waiter: Waiter, +} + +impl Pending { + /// Whether `op` is the event of this command's write. Another is from an eviction the write + /// made room by, which raises only unlinks and the deletes of their elements: never the event + /// of a write that allocates, while a write that does not evicts nothing. + fn awaits(&self, op: &Op) -> bool { + matches!( + (op, self.expect), + (Op::Create { .. }, Expect::Create) + | (Op::Drop { .. }, Expect::Drop) + | (Op::Insert { .. } | Op::Replace { .. }, Expect::Upsert) + | (Op::Replace { .. }, Expect::SetMeta) + | (Op::Delete { .. }, Expect::Delete) + ) + } +} + +thread_local! { + static PENDING: Cell> = const { Cell::new(None) }; +} + +/// Runs `write`, whose `expect` event hands `conn` to the lane that answers it. A write that fails, +/// or raises no such event, is answered here. +#[cfg_attr( + not(test), + expect(dead_code, reason = "the write commands are not in yet") +)] +pub fn offer(conn: Connection, expect: Expect, write: impl FnOnce() -> Result<(), Error>) { + struct Clear; + impl Drop for Clear { + fn drop(&mut self) { + drop(PENDING.take()); + } + } + let _clear = Clear; + PENDING.set(Some(Pending { + expect, + waiter: Waiter::new(conn), + })); + let written = write(); + // Unclaimed after a write that did not fail, the waiter drops, answering an internal error. + if let Some(Pending { waiter, .. }) = PENDING.take() + && let Err(e) = written + { + waiter.answer(Cow::Borrowed(e.reply())); + } +} + +/// The waiter `op` answers, if it is the event of the write on this thread. +fn claim(op: Op) -> (Op, Option) { + let Some(pending) = PENDING.take() else { + return (op, None); + }; + if !pending.awaits(&op) { + PENDING.set(Some(pending)); + return (op, None); + } + let op = match op { + Op::Replace { index, old, new } if pending.expect == Expect::SetMeta => { + Op::SetMeta { index, old, new } + } + op => op, + }; + (op, Some(pending.waiter)) +} + +fn op_of(ev: &event_data_t) -> Option { + let map = match ev.type_ { + EVENT_ITEM_LINK | EVENT_ITEM_UNLINK => ev.target, + _ => ev.coll_item, + }; + let map = Item::new(map.expose_provenance()).ok()?; + let index = owned(map.key()?)?; + let (key, old) = (ev.target.expose_provenance(), ev.source.expose_provenance()); + match ev.type_ { + EVENT_ITEM_LINK => { + let config = map.value()?.to_vec(); + Some(Op::Create { index, config }) + } + EVENT_ITEM_UNLINK => Some(Op::Drop { index }), + EVENT_ELEM_INSERT => Some(Op::Insert { index, key }), + EVENT_ELEM_REPLACE => Some(Op::Replace { + index, + old, + new: key, + }), + EVENT_ELEM_DELETE => Some(Op::Delete { index, key }), + _ => None, + } +} + +fn owned(bytes: &[u8]) -> Option { + str::from_utf8(bytes).ok().map(str::to_owned) +} + +pub fn install() { + // SAFETY: `on_item_event` takes the `event_data_t` the engine passes with `ON_EVENT_ITEM`. + unsafe { server::register_callback(ENGINE_EVENT_TYPE_ON_EVENT_ITEM, on_item_event) }; +} + +/// # Safety +/// +/// A non-null `data` must be an `event_data_t` whose item and elements live for the call. +unsafe extern "C" fn on_item_event( + _cookie: *const c_void, + _type: ENGINE_EVENT_TYPE, + data: *const c_void, + _cb_data: *const c_void, +) { + guard( + || (), + || { + // SAFETY: the caller guarantees a non-null `data` is a live `event_data_t`. + let Some(ev) = (unsafe { data.cast::().as_ref() }) else { + return; + }; + let Some(op) = op_of(ev) else { + return; + }; + // None for a change from replication or replay, or one the write did not ask for. + let (op, waiter) = claim(op); + aio::begin(op, waiter); + }, + ); +} + +#[cfg(test)] +mod tests { + use std::ptr; + use std::sync::mpsc::channel; + + use super::*; + use crate::memcached::ffi::event_type_t; + use crate::memcached::server::fake; + + fn event(type_: event_type_t, coll_item: usize, target: usize, source: usize) -> event_data_t { + event_data_t { + type_, + coll_item: ptr::without_provenance_mut(coll_item), + target: ptr::without_provenance_mut(target), + source: ptr::without_provenance_mut(source), + target_ref: 0, + source_ref: 0, + } + } + + #[test] + fn the_callback_takes_an_event_and_a_null() { + let ev = event(EVENT_ELEM_INSERT, 8, 16, 0); + for data in [(&raw const ev).cast(), ptr::null()] { + // SAFETY: `ev` outlives the call, and its item and elements are never read. + unsafe { + on_item_event( + ptr::null(), + ENGINE_EVENT_TYPE_ON_EVENT_ITEM, + data, + ptr::null(), + ); + }; + } + } + + fn raise(ev: &event_data_t) { + // SAFETY: `ev` outlives the call, and its item and elements are never read. + unsafe { + on_item_event( + ptr::null(), + ENGINE_EVENT_TYPE_ON_EVENT_ITEM, + ptr::from_ref(ev).cast(), + ptr::null(), + ); + } + } + + #[test] + fn an_event_the_engine_cannot_name_leaves_the_conn() { + fake::install(); + aio::start_once(); + let (tx, rx) = channel(); + let conn = fake::Conn::new(12, &tx); + // The tests have no engine to read the index from. + offer(conn.connection(), Expect::Upsert, || { + raise(&event(EVENT_ELEM_INSERT, 8, 16, 0)); + Ok(()) + }); + assert!(PENDING.take().is_none()); + assert_eq!(rx.try_recv(), Ok(12)); + assert!(conn.run_callback()); + assert_eq!(conn.reply(), Error::Internal.reply()); + } + + #[test] + fn a_failed_write_is_answered_its_error() { + fake::install(); + let (tx, rx) = channel(); + let conn = fake::Conn::new(13, &tx); + offer(conn.connection(), Expect::Upsert, || Err(Error::NotFound)); + assert_eq!(rx.try_recv(), Ok(13)); + assert!(conn.run_callback()); + assert_eq!(conn.reply(), Error::NotFound.reply()); + } + + #[test] + fn a_write_claims_only_its_own_event() { + fake::install(); + let (tx, _rx) = channel(); + let conn = fake::Conn::new(14, &tx); + let pending = || Pending { + expect: Expect::SetMeta, + waiter: Waiter::new(conn.connection()), + }; + let replace = Op::Replace { + index: "idx".into(), + old: 2, + new: 3, + }; + PENDING.set(Some(pending())); + assert!(matches!(claim(replace), (Op::SetMeta { .. }, Some(_)))); + let evicted = Op::Delete { + index: "other".into(), + key: 6, + }; + let insert = Op::Insert { + index: "idx".into(), + key: 5, + }; + PENDING.set(Some(pending())); + for op in [evicted, insert] { + assert!(claim(op).1.is_none()); + } + assert!(PENDING.take().is_some()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 397da2c..a5a241e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ mod ascii; mod bson; mod cmd; mod error; +mod event; mod index; mod memcached; mod nread; @@ -50,6 +51,7 @@ fn initialize(get_server_api: GET_SERVER_API) -> Result<(), &'static str> { if !aio::start() { return Err("the lane threads could not start"); } + event::install(); // SAFETY: `DESCRIPTOR` is static and only the core touches it from here on (it writes `next`). if !unsafe { memcached::server::register_ascii(&raw mut ascii::DESCRIPTOR) } { return Err("the server refused the ASCII protocol extension"); diff --git a/src/memcached/server.rs b/src/memcached/server.rs index 089cf7a..4377210 100644 --- a/src/memcached/server.rs +++ b/src/memcached/server.rs @@ -22,6 +22,13 @@ pub type IoCallback = unsafe extern "C" fn( handler: ResponseHandler, ) -> bool; +pub type EventCallback = unsafe extern "C" fn( + cookie: *const c_void, + type_: ENGINE_EVENT_TYPE, + data: *const c_void, + cb_data: *const c_void, +); + #[expect(dead_code, reason = "the commands that use the rest are not in yet")] struct Api { get_server_api: GetServerApi, @@ -141,6 +148,15 @@ pub unsafe fn register_ascii(descriptor: *mut EXTENSION_ASCII_PROTOCOL_DESCRIPTO unsafe { (api().register_extension)(kind, descriptor.cast()) } } +/// # Safety +/// +/// `cb` must take what the server passes with a `type_` event. +pub unsafe fn register_callback(type_: ENGINE_EVENT_TYPE, cb: EventCallback) { + // SAFETY: the caller guarantees `cb` takes `type_` events; the server ignores the engine and + // keeps no pointer of ours. + unsafe { (api().register_callback)(ptr::null_mut(), type_, Some(cb), ptr::null()) }; +} + /// A client connection, as the server names it to the extension. #[derive(Clone, Copy)] pub struct Connection { @@ -323,7 +339,9 @@ pub mod fake { unsafe extern "C" fn notify_io_complete(cookie: *const c_void, _: ENGINE_ERROR_CODE) { // SAFETY: the cookie is a `Conn`, alive until its notify. let conn = unsafe { conn(cookie) }; - let _ = conn.notified.send(conn.id); + // The test may drop `conn` once the id arrives, so the send must not use its sender. + let (notified, id) = (conn.notified.clone(), conn.id); + let _ = notified.send(id); } unsafe extern "C" fn on_io_complete(