reifydb-runtime 0.10.2

Runtime infrastructure 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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB

#![cfg_attr(not(debug_assertions), deny(clippy::disallowed_methods))]
#![cfg_attr(debug_assertions, warn(clippy::disallowed_methods))]
#![allow(clippy::tabs_in_doc_comments)]

pub mod cache;

pub mod context;

pub mod fatal;

pub mod io;

pub mod pool;

pub mod shutdown;

pub mod sync;

pub mod actor;

pub mod version_epoch;

#[cfg(reifydb_dst)]
pub mod testing;

#[cfg(not(reifydb_dst))]
use std::future::Future;
use std::thread;

use reifydb_value::Result as ValueResult;

use crate::{
	actor::system::ActorSystem,
	context::clock::{Clock, MockClock},
	pool::{PoolConfig, Pools},
	shutdown::{Shutdown, ShutdownErrors},
};

#[derive(Clone)]
pub struct RuntimeConfig {
	pub clock: Clock,
	pub rng: context::rng::Rng,
	pub fatal: fatal::FatalConfig,
}

impl Default for RuntimeConfig {
	fn default() -> Self {
		Self {
			clock: Clock::Real,
			rng: context::rng::Rng::default(),
			fatal: fatal::FatalConfig::default(),
		}
	}
}

impl RuntimeConfig {
	pub fn seeded(mut self, seed: u64) -> Self {
		self.clock = Clock::Mock(MockClock::from_millis(seed));
		self.rng = context::rng::Rng::seeded(seed);
		self
	}

	pub fn fatal(mut self, config: fatal::FatalConfig) -> Self {
		self.fatal = config;
		self
	}

	pub fn clock(mut self, clock: Clock) -> Self {
		self.clock = clock;
		self
	}
}

use std::fmt;
#[cfg(target_arch = "wasm32")]
use std::{
	pin::Pin,
	task::{Context, Poll},
};

#[cfg(target_arch = "wasm32")]
use futures_util::future::LocalBoxFuture;
#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
use tokio::runtime as tokio_runtime;
#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
use tokio::task::JoinHandle;

#[cfg(target_arch = "wasm32")]
#[derive(Clone, Copy, Debug)]
pub struct WasmHandle;

#[cfg(target_arch = "wasm32")]
pub struct WasmJoinHandle<T> {
	future: LocalBoxFuture<'static, T>,
}

#[cfg(target_arch = "wasm32")]
impl<T> Future for WasmJoinHandle<T> {
	type Output = Result<T, WasmJoinError>;

	fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
		match self.future.as_mut().poll(cx) {
			Poll::Ready(v) => Poll::Ready(Ok(v)),
			Poll::Pending => Poll::Pending,
		}
	}
}

#[cfg(target_arch = "wasm32")]
#[derive(Debug)]
pub struct WasmJoinError;

#[cfg(target_arch = "wasm32")]
impl fmt::Display for WasmJoinError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "WASM task failed")
	}
}

#[cfg(target_arch = "wasm32")]
use std::error::Error;

#[cfg(target_arch = "wasm32")]
impl Error for WasmJoinError {}

use crate::actor::system::ActorSpawner;

pub struct Runtime {
	system: ActorSystem,
	pools: Pools,
	clock: Clock,
	rng: context::rng::Rng,
}

impl Runtime {
	pub fn from_config(config: RuntimeConfig, pools: PoolConfig) -> Self {
		let pools = Pools::new(pools);
		let system = ActorSystem::new(pools.clone(), config.clock.clone());

		Self {
			system,
			pools,
			clock: config.clock,
			rng: config.rng,
		}
	}

	pub fn handle(&self) -> RuntimeHandle {
		RuntimeHandle {
			system: self.system.clone(),
			pools: self.pools.clone(),
			clock: self.clock.clone(),
			rng: self.rng.clone(),
		}
	}

	pub fn actor_system(&self) -> ActorSystem {
		self.system.clone()
	}

	pub fn spawner(&self) -> ActorSpawner {
		self.system.spawner()
	}

	pub fn clock(&self) -> &Clock {
		&self.clock
	}

	pub fn rng(&self) -> &context::rng::Rng {
		&self.rng
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn task_spawner(&self) -> context::spawner::Spawner {
		context::spawner::Spawner::host(self.pools.handle())
	}

	#[cfg(not(all(reifydb_target = "host", not(reifydb_dst))))]
	pub fn task_spawner(&self) -> context::spawner::Spawner {
		context::spawner::Spawner::inline()
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn tokio(&self) -> tokio_runtime::Handle {
		self.pools.handle()
	}

	#[cfg(target_arch = "wasm32")]
	pub fn tokio(&self) -> WasmHandle {
		WasmHandle
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
	where
		F: Future + Send + 'static,
		F::Output: Send + 'static,
	{
		self.pools.spawn(future)
	}

	#[cfg(target_arch = "wasm32")]
	pub fn spawn<F>(&self, future: F) -> WasmJoinHandle<F::Output>
	where
		F: Future + 'static,
		F::Output: 'static,
	{
		WasmJoinHandle {
			future: Box::pin(future),
		}
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn block_on<F>(&self, future: F) -> F::Output
	where
		F: Future,
	{
		self.pools.block_on(future)
	}

	#[cfg(target_arch = "wasm32")]
	pub fn block_on<F>(&self, _future: F) -> F::Output
	where
		F: Future,
	{
		unimplemented!("block_on not supported in WASM - use async execution instead")
	}
}

impl Shutdown for Runtime {
	fn shutdown(&self) -> ValueResult<()> {
		let mut errors = ShutdownErrors::new("runtime");
		self.system.shutdown();
		if let Err(err) = self.system.join() {
			errors.fail("actor system", err);
		}
		self.pools.shutdown();
		errors.finish()
	}
}

impl Drop for Runtime {
	fn drop(&mut self) {
		if let Err(err) = self.shutdown() {
			if thread::panicking() {
				eprintln!("runtime shutdown failed during unwind: {err}");
			} else {
				panic!("runtime shutdown failed: {err}");
			}
		}
	}
}

impl fmt::Debug for Runtime {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("Runtime").finish_non_exhaustive()
	}
}

#[derive(Clone)]
pub struct RuntimeHandle {
	system: ActorSystem,
	pools: Pools,
	clock: Clock,
	rng: context::rng::Rng,
}

impl RuntimeHandle {
	pub fn actor_system(&self) -> ActorSystem {
		self.system.clone()
	}

	pub fn spawner(&self) -> ActorSpawner {
		self.system.spawner()
	}

	pub fn pools(&self) -> Pools {
		self.pools.clone()
	}

	pub fn clock(&self) -> &Clock {
		&self.clock
	}

	pub fn rng(&self) -> &context::rng::Rng {
		&self.rng
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn task_spawner(&self) -> context::spawner::Spawner {
		context::spawner::Spawner::host(self.pools.handle())
	}

	#[cfg(not(all(reifydb_target = "host", not(reifydb_dst))))]
	pub fn task_spawner(&self) -> context::spawner::Spawner {
		context::spawner::Spawner::inline()
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn tokio(&self) -> tokio_runtime::Handle {
		self.pools.handle()
	}

	#[cfg(target_arch = "wasm32")]
	pub fn tokio(&self) -> WasmHandle {
		WasmHandle
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
	where
		F: Future + Send + 'static,
		F::Output: Send + 'static,
	{
		self.pools.spawn(future)
	}

	#[cfg(target_arch = "wasm32")]
	pub fn spawn<F>(&self, future: F) -> WasmJoinHandle<F::Output>
	where
		F: Future + 'static,
		F::Output: 'static,
	{
		WasmJoinHandle {
			future: Box::pin(future),
		}
	}

	#[cfg(all(reifydb_target = "host", not(reifydb_dst)))]
	pub fn block_on<F>(&self, future: F) -> F::Output
	where
		F: Future,
	{
		self.pools.block_on(future)
	}

	#[cfg(target_arch = "wasm32")]
	pub fn block_on<F>(&self, _future: F) -> F::Output
	where
		F: Future,
	{
		unimplemented!("block_on not supported in WASM - use async execution instead")
	}
}

impl fmt::Debug for RuntimeHandle {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("RuntimeHandle").finish_non_exhaustive()
	}
}

#[cfg(all(test, not(reifydb_single_threaded)))]
mod tests {
	use super::*;

	fn test_config() -> RuntimeConfig {
		RuntimeConfig::default()
	}

	fn test_pools() -> PoolConfig {
		PoolConfig {
			coordination_threads: 2,
			flow_threads: 2,
			maintenance_threads: 1,
			task_threads: 2,
			compute_threads: 2,
			async_threads: 2,
		}
	}

	#[test]
	fn test_runtime_creation() {
		let runtime = Runtime::from_config(test_config(), test_pools());
		let result = runtime.block_on(async { 42 });
		assert_eq!(result, 42);
	}

	#[test]
	fn test_spawn() {
		let runtime = Runtime::from_config(test_config(), test_pools());
		let handle = runtime.spawn(async { 123 });
		let result = runtime.block_on(handle).unwrap();
		assert_eq!(result, 123);
	}

	#[test]
	fn test_actor_system_accessible() {
		let runtime = Runtime::from_config(test_config(), test_pools());
		let _system = runtime.actor_system();
	}

	#[test]
	fn test_shutdown_drops_runtime() {
		let runtime = Runtime::from_config(test_config(), test_pools());
		let spawner = runtime.spawner();
		assert!(spawner.is_alive());
		drop(runtime);
		assert!(!spawner.is_alive());
	}
}