reifydb-core 0.10.1

Core database interfaces and data structures for ReifyDB
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB

use std::{
	any::{Any, TypeId, type_name},
	collections::HashMap,
	sync,
	sync::Arc,
};

use reifydb_runtime::actor::{
	context::Context,
	mailbox::ActorRef,
	system::ActorSpawner,
	traits::{Actor, Directive},
};
use sync::mpsc::Sender;

pub mod lifecycle;
pub mod operator;
#[macro_use]
pub mod r#macro;
pub mod metric;
pub mod procedure;
pub mod row;
pub mod store;
pub mod transaction;

type EventListenerInstaller = Box<dyn FnOnce(&mut HashMap<TypeId, Box<dyn EventListenerList>>) + Send>;

pub trait Event: Any + Send + Sync + Clone + 'static {
	fn as_any(&self) -> &dyn Any;
	fn into_any(self) -> Box<dyn Any + Send>;
}

pub trait EventListener<E>: Send + Sync + 'static
where
	E: Event,
{
	fn on(&self, event: &E);
}

trait EventListenerList: Any + Send + Sync {
	fn on_any(&self, event: Box<dyn Any + Send>);
	fn as_any_mut(&mut self) -> &mut dyn Any;
}

struct EventListenerListImpl<E> {
	listeners: Vec<Arc<dyn EventListener<E>>>,
}

impl<E> EventListenerListImpl<E>
where
	E: Event,
{
	fn new() -> Self {
		Self {
			listeners: Vec::new(),
		}
	}

	fn add(&mut self, listener: Arc<dyn EventListener<E>>) {
		self.listeners.push(listener);
	}
}

impl<E> EventListenerList for EventListenerListImpl<E>
where
	E: Event,
{
	fn on_any(&self, event: Box<dyn Any + Send>) {
		if let Ok(event) = event.downcast::<E>() {
			for listener in &self.listeners {
				listener.on(&*event);
			}
		}
	}

	fn as_any_mut(&mut self) -> &mut dyn Any {
		self
	}
}

struct EventEnvelope {
	type_id: TypeId,
	event: Box<dyn Any + Send>,
}

enum EventBusMessage {
	Emit(EventEnvelope),
	Register {
		installer: EventListenerInstaller,
	},
	WaitForCompletion(Sender<()>),
}

struct EventBusActor;

impl Actor for EventBusActor {
	type State = HashMap<TypeId, Box<dyn EventListenerList>>;
	type Message = EventBusMessage;

	fn init(&self, _ctx: &Context<Self::Message>) -> Self::State {
		HashMap::new()
	}

	fn handle(&self, state: &mut Self::State, msg: Self::Message, _ctx: &Context<Self::Message>) -> Directive {
		match msg {
			EventBusMessage::Emit(envelope) => {
				if let Some(list) = state.get(&envelope.type_id) {
					list.on_any(envelope.event);
				}
			}
			EventBusMessage::Register {
				installer,
			} => {
				installer(state);
			}
			EventBusMessage::WaitForCompletion(tx) => {
				let _ = tx.send(());
			}
		}
		Directive::Continue
	}
}

#[derive(Clone)]
pub struct EventBus {
	actor_ref: ActorRef<EventBusMessage>,
	spawner: ActorSpawner,
}

impl EventBus {
	pub fn new(spawner: &ActorSpawner) -> Self {
		let handle = spawner.spawn_coordination("event-bus", EventBusActor);
		Self {
			actor_ref: handle.actor_ref().clone(),
			spawner: spawner.clone(),
		}
	}

	pub fn register<E, L>(&self, listener: L)
	where
		E: Event,
		L: EventListener<E>,
	{
		let type_id = TypeId::of::<E>();
		let listener = Arc::new(listener);

		let installer: EventListenerInstaller = Box::new(move |map| {
			let list = map.entry(type_id).or_insert_with(|| Box::new(EventListenerListImpl::<E>::new()));
			list.as_any_mut().downcast_mut::<EventListenerListImpl<E>>().unwrap().add(listener);
		});

		if self.actor_ref
			.send(EventBusMessage::Register {
				installer,
			})
			.is_err()
		{
			let shutting_down = self.spawner.cancellation_token().is_none_or(|token| token.is_cancelled());
			assert!(
				shutting_down,
				"the event bus rejected a listener for {} while the system was running; the \
				 listener would never install and every later event of this type is lost silently",
				type_name::<E>()
			);
		}
	}

	pub fn emit<E>(&self, event: E)
	where
		E: Event,
	{
		let type_id = TypeId::of::<E>();
		if self.actor_ref
			.send(EventBusMessage::Emit(EventEnvelope {
				type_id,
				event: event.into_any(),
			}))
			.is_err()
		{
			let shutting_down = self.spawner.cancellation_token().is_none_or(|token| token.is_cancelled());
			assert!(
				shutting_down,
				"the event bus rejected a {} while the system was running; dropping it silently \
				 loses a post-commit update no subscriber will ever see",
				type_name::<E>()
			);
		}
	}

	/// Waits until the bus has drained everything queued ahead of this call.
	///
	/// Under dst the caller's thread is also the thread that steps the actor system, so it drives
	/// the system to quiescence itself and then picks the reply up without blocking. A blocking
	/// receive here would park the only thread that can run the bus actor, so the reply it waits
	/// for could never be sent; that deadlocks subsystem start-up before any test can run.
	#[cfg(reifydb_dst)]
	pub fn wait_for_completion(&self) {
		let (tx, rx) = sync::mpsc::channel();
		if self.actor_ref.send(EventBusMessage::WaitForCompletion(tx)).is_err() {
			return;
		}
		if self.spawner.is_alive() {
			self.spawner.system().run_until_idle();
		}
		let _ = rx.try_recv();
	}

	/// Waits until the bus has drained everything queued ahead of this call.
	///
	/// Off dst the bus actor runs on its own thread (host) or inline on `send` (wasm), so a
	/// blocking receive is both correct and the cheapest way to wait.
	#[cfg(not(reifydb_dst))]
	pub fn wait_for_completion(&self) {
		let (tx, rx) = sync::mpsc::channel();
		let _ = self.actor_ref.send(EventBusMessage::WaitForCompletion(tx));
		let _ = rx.recv();
	}
}

#[cfg(test)]
pub mod tests {
	use std::{sync::Arc, thread};

	use reifydb_runtime::{
		actor::system::ActorSystem,
		context::clock::Clock,
		pool::{PoolConfig, Pools},
		sync::mutex::Mutex,
	};

	use crate::event::{Event, EventBus, EventListener};

	fn test_actor_system() -> ActorSystem {
		let pools = Pools::new(PoolConfig::default());
		ActorSystem::new(pools, Clock::Real)
	}

	define_event! {
		pub struct TestEvent{}
	}

	define_event! {
		pub struct AnotherEvent{}
	}

	#[derive(Default, Debug, Clone)]
	pub struct TestEventListener(Arc<TestHandlerInner>);

	#[derive(Default, Debug)]
	pub struct TestHandlerInner {
		pub counter: Arc<Mutex<i32>>,
	}

	impl EventListener<TestEvent> for TestEventListener {
		fn on(&self, _event: &TestEvent) {
			let mut x = self.0.counter.lock();
			*x += 1;
		}
	}

	impl EventListener<AnotherEvent> for TestEventListener {
		fn on(&self, _event: &AnotherEvent) {
			let mut x = self.0.counter.lock();
			*x *= 2;
		}
	}

	#[test]
	fn test_event_bus_new() {
		let actor_system = test_actor_system();
		let event_bus = EventBus::new(&actor_system.spawner());
		event_bus.emit(TestEvent::new());
		event_bus.wait_for_completion();
	}

	#[test]
	fn test_register_single_listener() {
		let actor_system = test_actor_system();
		let event_bus = EventBus::new(&actor_system.spawner());
		let listener = TestEventListener::default();

		event_bus.register::<TestEvent, TestEventListener>(listener.clone());
		event_bus.emit(TestEvent::new());
		event_bus.wait_for_completion();
		assert_eq!(*listener.0.counter.lock(), 1);
	}

	#[test]
	fn test_emit_unregistered_event() {
		let actor_system = test_actor_system();
		let event_bus = EventBus::new(&actor_system.spawner());
		event_bus.emit(TestEvent::new());
		event_bus.wait_for_completion();
	}

	#[test]
	fn test_multiple_listeners_same_event() {
		let actor_system = test_actor_system();
		let event_bus = EventBus::new(&actor_system.spawner());
		let listener1 = TestEventListener::default();
		let listener2 = TestEventListener::default();

		event_bus.register::<TestEvent, TestEventListener>(listener1.clone());
		event_bus.register::<TestEvent, TestEventListener>(listener2.clone());

		event_bus.emit(TestEvent::new());
		event_bus.wait_for_completion();
		assert_eq!(*listener1.0.counter.lock(), 1);
		assert_eq!(*listener2.0.counter.lock(), 1);
	}

	#[test]
	fn test_event_bus_clone() {
		let actor_system = test_actor_system();
		let event_bus1 = EventBus::new(&actor_system.spawner());
		let listener = TestEventListener::default();
		event_bus1.register::<TestEvent, TestEventListener>(listener.clone());

		let event_bus2 = event_bus1.clone();
		event_bus2.emit(TestEvent::new());
		event_bus2.wait_for_completion();
		assert_eq!(*listener.0.counter.lock(), 1);
	}

	#[test]
	fn test_concurrent_registration() {
		let actor_system = test_actor_system();
		let event_bus = Arc::new(EventBus::new(&actor_system.spawner()));
		let mut handles = Vec::new();

		for _ in 0..10 {
			let event_bus = event_bus.clone();
			handles.push(thread::spawn(move || {
				let listener = TestEventListener::default();
				event_bus.register::<TestEvent, TestEventListener>(listener);
			}));
		}

		for handle in handles {
			handle.join().unwrap();
		}

		event_bus.emit(TestEvent::new());
		event_bus.wait_for_completion();
	}

	#[test]
	fn test_concurrent_emitting() {
		let actor_system = test_actor_system();
		let event_bus = Arc::new(EventBus::new(&actor_system.spawner()));
		let listener = TestEventListener::default();
		event_bus.register::<TestEvent, TestEventListener>(listener.clone());
		event_bus.wait_for_completion();

		let mut handles = Vec::new();

		for _ in 0..10 {
			let event_bus = event_bus.clone();
			handles.push(thread::spawn(move || {
				event_bus.emit(TestEvent::new());
			}));
		}

		for handle in handles {
			handle.join().unwrap();
		}

		event_bus.wait_for_completion();
		assert_eq!(*listener.0.counter.lock(), 10);
	}

	define_event! {
		pub struct MacroTestEvent {
			pub value: i32,
		}
	}

	#[test]
	fn testine_event_macro() {
		let event = MacroTestEvent::new(42);
		let any_ref = event.as_any();
		assert!(any_ref.downcast_ref::<MacroTestEvent>().is_some());
		assert_eq!(any_ref.downcast_ref::<MacroTestEvent>().unwrap().value(), &42);
	}

	#[test]
	fn test_multi_event_listener() {
		let actor_system = test_actor_system();
		let event_bus = EventBus::new(&actor_system.spawner());
		let listener = TestEventListener::default();

		event_bus.register::<TestEvent, TestEventListener>(listener.clone());
		event_bus.register::<AnotherEvent, TestEventListener>(listener.clone());

		// Each event type triggers only its own listeners
		event_bus.emit(TestEvent::new());
		event_bus.wait_for_completion();
		assert_eq!(*listener.0.counter.lock(), 1);

		event_bus.emit(TestEvent::new());
		event_bus.wait_for_completion();
		assert_eq!(*listener.0.counter.lock(), 2);

		event_bus.emit(AnotherEvent::new());
		event_bus.wait_for_completion();
		assert_eq!(*listener.0.counter.lock(), 4); // 2 * 2
	}
}