Skip to main content

rivetkit_core/actor/
config.rs

1use std::fmt;
2use std::sync::Arc;
3use std::time::Duration;
4
5use rivet_envoy_client::config::HttpRequest;
6
7use crate::inspector::InspectorTabEntry;
8
9const DEFAULT_STATE_SAVE_INTERVAL: Duration = Duration::from_secs(1);
10const DEFAULT_CREATE_VARS_TIMEOUT: Duration = Duration::from_secs(5);
11const DEFAULT_CREATE_CONN_STATE_TIMEOUT: Duration = Duration::from_secs(5);
12const DEFAULT_ON_BEFORE_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
13const DEFAULT_ON_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
14const DEFAULT_ON_MIGRATE_TIMEOUT: Duration = Duration::from_secs(30);
15const DEFAULT_ACTION_TIMEOUT: Duration = Duration::from_secs(60);
16const DEFAULT_SLEEP_TIMEOUT: Duration = Duration::from_secs(30);
17const DEFAULT_SLEEP_GRACE_PERIOD: Duration = Duration::from_secs(15);
18const DEFAULT_CONNECTION_LIVENESS_TIMEOUT: Duration = Duration::from_millis(2500);
19const DEFAULT_CONNECTION_LIVENESS_INTERVAL: Duration = Duration::from_secs(5);
20const DEFAULT_MAX_QUEUE_SIZE: u32 = 1000;
21pub const DEFAULT_MAX_SCHEDULES: u32 = 1_000;
22const DEFAULT_MAX_QUEUE_MESSAGE_SIZE: u32 = 65_536;
23const DEFAULT_MAX_INCOMING_MESSAGE_SIZE: u32 = 65_536;
24const DEFAULT_MAX_OUTGOING_MESSAGE_SIZE: u32 = 1_048_576;
25
26#[derive(Clone)]
27pub enum CanHibernateWebSocket {
28	Bool(bool),
29	Callback(Arc<dyn Fn(&HttpRequest) -> bool + Send + Sync>),
30}
31
32impl fmt::Debug for CanHibernateWebSocket {
33	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34		match self {
35			Self::Bool(value) => f.debug_tuple("Bool").field(value).finish(),
36			Self::Callback(_) => f.write_str("Callback(..)"),
37		}
38	}
39}
40
41impl Default for CanHibernateWebSocket {
42	fn default() -> Self {
43		Self::Bool(false)
44	}
45}
46
47#[derive(Clone, Debug, Default)]
48pub struct ActorConfigOverrides {
49	pub sleep_grace_period: Option<Duration>,
50}
51
52#[derive(Clone, Debug)]
53pub struct ActionDefinition {
54	pub name: String,
55}
56
57#[derive(Clone, Debug)]
58pub struct ActorConfig {
59	pub name: Option<String>,
60	pub icon: Option<String>,
61	/// Whether the user declared a SQLite database for this actor (`db({...})`
62	/// on the TS side). Gates the inspector database tab.
63	pub has_database: bool,
64	pub remote_sqlite: bool,
65	/// Enables the experimental Actor Runtime Socket.
66	pub enable_actor_runtime_socket: bool,
67	/// Whether the user declared actor state (`state: ...` or `createState`).
68	/// Gates the inspector state tab and state-subscription messages.
69	pub has_state: bool,
70	pub can_hibernate_websocket: CanHibernateWebSocket,
71	pub state_save_interval: Duration,
72	pub create_vars_timeout: Duration,
73	pub create_conn_state_timeout: Duration,
74	pub on_before_connect_timeout: Duration,
75	pub on_connect_timeout: Duration,
76	pub on_migrate_timeout: Duration,
77	pub action_timeout: Duration,
78	pub sleep_timeout: Duration,
79	pub no_sleep: bool,
80	pub sleep_grace_period: Duration,
81	pub sleep_grace_period_overridden: bool,
82	pub connection_liveness_timeout: Duration,
83	pub connection_liveness_interval: Duration,
84	pub max_queue_size: u32,
85	pub max_schedules: u32,
86	pub max_queue_message_size: u32,
87	pub max_incoming_message_size: u32,
88	pub max_outgoing_message_size: u32,
89	pub overrides: Option<ActorConfigOverrides>,
90	pub actions: Vec<ActionDefinition>,
91	/// Author-declared inspector tab entries (custom tabs + built-in
92	/// hides). Validated upstream (Zod / builder).
93	pub inspector_tabs: Vec<InspectorTabEntry>,
94}
95
96/// Sparse, serialization-friendly actor configuration. All fields are optional with millisecond integers instead of Duration. Used at runtime boundaries (NAPI, config files). Convert to ActorConfig via ActorConfig::from_input().
97#[derive(Clone, Debug, Default)]
98pub struct ActorConfigInput {
99	pub name: Option<String>,
100	pub icon: Option<String>,
101	pub has_database: Option<bool>,
102	pub remote_sqlite: Option<bool>,
103	pub enable_actor_runtime_socket: Option<bool>,
104	pub has_state: Option<bool>,
105	pub can_hibernate_websocket: Option<bool>,
106	pub state_save_interval_ms: Option<u32>,
107	pub create_vars_timeout_ms: Option<u32>,
108	pub create_conn_state_timeout_ms: Option<u32>,
109	pub on_before_connect_timeout_ms: Option<u32>,
110	pub on_connect_timeout_ms: Option<u32>,
111	pub on_migrate_timeout_ms: Option<u32>,
112	pub action_timeout_ms: Option<u32>,
113	pub sleep_timeout_ms: Option<u32>,
114	pub no_sleep: Option<bool>,
115	pub sleep_grace_period_ms: Option<u32>,
116	pub connection_liveness_timeout_ms: Option<u32>,
117	pub connection_liveness_interval_ms: Option<u32>,
118	pub max_queue_size: Option<u32>,
119	pub max_schedules: Option<u32>,
120	pub max_queue_message_size: Option<u32>,
121	pub max_incoming_message_size: Option<u32>,
122	pub max_outgoing_message_size: Option<u32>,
123	pub actions: Option<Vec<ActionDefinition>>,
124	pub inspector_tabs: Option<Vec<InspectorTabEntry>>,
125}
126
127impl ActorConfig {
128	pub fn from_input(config: ActorConfigInput) -> Self {
129		let mut actor_config = Self {
130			name: config.name,
131			icon: config.icon,
132			has_database: config.has_database.unwrap_or(false),
133			remote_sqlite: config.remote_sqlite.unwrap_or(false),
134			enable_actor_runtime_socket: config.enable_actor_runtime_socket.unwrap_or(false),
135			has_state: config.has_state.unwrap_or(false),
136			..Self::default()
137		};
138		if let Some(can_hibernate_websocket) = config.can_hibernate_websocket {
139			actor_config.can_hibernate_websocket =
140				CanHibernateWebSocket::Bool(can_hibernate_websocket);
141		}
142		if let Some(value) = config.state_save_interval_ms {
143			actor_config.state_save_interval = duration_ms(value);
144		}
145		if let Some(value) = config.create_vars_timeout_ms {
146			actor_config.create_vars_timeout = duration_ms(value);
147		}
148		if let Some(value) = config.create_conn_state_timeout_ms {
149			actor_config.create_conn_state_timeout = duration_ms(value);
150		}
151		if let Some(value) = config.on_before_connect_timeout_ms {
152			actor_config.on_before_connect_timeout = duration_ms(value);
153		}
154		if let Some(value) = config.on_connect_timeout_ms {
155			actor_config.on_connect_timeout = duration_ms(value);
156		}
157		if let Some(value) = config.on_migrate_timeout_ms {
158			actor_config.on_migrate_timeout = duration_ms(value);
159		}
160		if let Some(value) = config.action_timeout_ms {
161			actor_config.action_timeout = duration_ms(value);
162		}
163		if let Some(value) = config.sleep_timeout_ms {
164			actor_config.sleep_timeout = duration_ms(value);
165		}
166		if let Some(value) = config.no_sleep {
167			actor_config.no_sleep = value;
168		}
169		if let Some(value) = config.sleep_grace_period_ms {
170			actor_config.sleep_grace_period = duration_ms(value);
171			actor_config.sleep_grace_period_overridden = true;
172		}
173		if let Some(value) = config.connection_liveness_timeout_ms {
174			actor_config.connection_liveness_timeout = duration_ms(value);
175		}
176		if let Some(value) = config.connection_liveness_interval_ms {
177			actor_config.connection_liveness_interval = duration_ms(value);
178		}
179		if let Some(value) = config.max_queue_size {
180			actor_config.max_queue_size = value;
181		}
182		if let Some(value) = config.max_schedules {
183			actor_config.max_schedules = value;
184		}
185		if let Some(value) = config.max_queue_message_size {
186			actor_config.max_queue_message_size = value;
187		}
188		if let Some(value) = config.max_incoming_message_size {
189			actor_config.max_incoming_message_size = value;
190		}
191		if let Some(value) = config.max_outgoing_message_size {
192			actor_config.max_outgoing_message_size = value;
193		}
194		if let Some(actions) = config.actions {
195			actor_config.actions = actions;
196		}
197		if let Some(tabs) = config.inspector_tabs {
198			actor_config.inspector_tabs = tabs;
199		}
200
201		actor_config
202	}
203
204	pub fn effective_sleep_grace_period(&self) -> Duration {
205		cap_duration(
206			self.sleep_grace_period,
207			self.overrides
208				.as_ref()
209				.and_then(|overrides| overrides.sleep_grace_period),
210		)
211	}
212
213	/// Runtime authority for rejecting malformed config that bypassed the
214	/// TypeScript Zod layer (direct Rust builders, NAPI shim corruption,
215	/// etc.). Call this before constructing an `ActorFactory` from this
216	/// config so the actor never starts with garbage state.
217	pub fn validate(&self) -> anyhow::Result<()> {
218		crate::inspector::validate_inspector_tabs(&self.inspector_tabs)?;
219		Ok(())
220	}
221}
222
223impl Default for ActorConfig {
224	fn default() -> Self {
225		Self {
226			name: None,
227			icon: None,
228			has_database: false,
229			remote_sqlite: false,
230			enable_actor_runtime_socket: false,
231			has_state: false,
232			can_hibernate_websocket: CanHibernateWebSocket::default(),
233			state_save_interval: DEFAULT_STATE_SAVE_INTERVAL,
234			create_vars_timeout: DEFAULT_CREATE_VARS_TIMEOUT,
235			create_conn_state_timeout: DEFAULT_CREATE_CONN_STATE_TIMEOUT,
236			on_before_connect_timeout: DEFAULT_ON_BEFORE_CONNECT_TIMEOUT,
237			on_connect_timeout: DEFAULT_ON_CONNECT_TIMEOUT,
238			on_migrate_timeout: DEFAULT_ON_MIGRATE_TIMEOUT,
239			action_timeout: DEFAULT_ACTION_TIMEOUT,
240			sleep_timeout: DEFAULT_SLEEP_TIMEOUT,
241			no_sleep: false,
242			sleep_grace_period: DEFAULT_SLEEP_GRACE_PERIOD,
243			sleep_grace_period_overridden: false,
244			connection_liveness_timeout: DEFAULT_CONNECTION_LIVENESS_TIMEOUT,
245			connection_liveness_interval: DEFAULT_CONNECTION_LIVENESS_INTERVAL,
246			max_queue_size: DEFAULT_MAX_QUEUE_SIZE,
247			max_schedules: DEFAULT_MAX_SCHEDULES,
248			max_queue_message_size: DEFAULT_MAX_QUEUE_MESSAGE_SIZE,
249			max_incoming_message_size: DEFAULT_MAX_INCOMING_MESSAGE_SIZE,
250			max_outgoing_message_size: DEFAULT_MAX_OUTGOING_MESSAGE_SIZE,
251			overrides: None,
252			actions: Vec::new(),
253			inspector_tabs: Vec::new(),
254		}
255	}
256}
257
258fn cap_duration(duration: Duration, override_duration: Option<Duration>) -> Duration {
259	if let Some(override_duration) = override_duration {
260		duration.min(override_duration)
261	} else {
262		duration
263	}
264}
265
266fn duration_ms(value: u32) -> Duration {
267	Duration::from_millis(u64::from(value))
268}
269
270// Test shim keeps moved tests in crate-root tests/ with private-module access.
271#[cfg(test)]
272#[path = "../../tests/config.rs"]
273mod tests;