rivetkit-core 2.3.0-rc.12

Core runtime primitives for RivetKit actor hosts
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
mod moved_tests {
	use std::sync::Arc;
	use std::sync::atomic::{AtomicUsize, Ordering};

	use crate::actor::context::ActorContext;
	use crate::actor::work_registry::ActorWorkKind;
	use parking_lot::Mutex as DropMutex;
	use rivet_envoy_client::async_counter::AsyncCounter;
	use std::time::{Duration, Instant};
	use tokio::sync::oneshot;
	use tokio::task::yield_now;

	use tokio::time::advance;
	use tracing::field::{Field, Visit};
	use tracing::{Event, Subscriber};
	use tracing_subscriber::layer::{Context as LayerContext, Layer};
	use tracing_subscriber::prelude::*;
	use tracing_subscriber::registry::Registry;

	#[derive(Default)]
	struct MessageVisitor {
		message: Option<String>,
		actor_id: Option<String>,
		kind: Option<String>,
		reason: Option<String>,
	}

	impl Visit for MessageVisitor {
		fn record_str(&mut self, field: &Field, value: &str) {
			match field.name() {
				"message" => self.message = Some(value.to_owned()),
				"actor_id" => self.actor_id = Some(value.to_owned()),
				"kind" => self.kind = Some(value.to_owned()),
				"reason" => self.reason = Some(value.to_owned()),
				_ => {}
			}
		}

		fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
			let value = format!("{value:?}").trim_matches('"').to_owned();
			match field.name() {
				"message" => self.message = Some(value),
				"actor_id" => self.actor_id = Some(value),
				"kind" => self.kind = Some(value),
				"reason" => self.reason = Some(value),
				_ => {}
			}
		}
	}

	#[derive(Clone)]
	struct ShutdownTaskRefusedLayer {
		count: Arc<AtomicUsize>,
	}

	#[derive(Clone)]
	struct RegisteredTaskDeadlineLayer {
		count: Arc<AtomicUsize>,
	}

	impl<S> Layer<S> for ShutdownTaskRefusedLayer
	where
		S: Subscriber,
	{
		fn on_event(&self, event: &Event<'_>, _ctx: LayerContext<'_, S>) {
			if *event.metadata().level() != tracing::Level::WARN {
				return;
			}

			let mut visitor = MessageVisitor::default();
			event.record(&mut visitor);
			if visitor.message.as_deref()
				== Some("shutdown task spawned after teardown; aborting immediately")
			{
				self.count.fetch_add(1, Ordering::SeqCst);
			}
		}
	}

	impl<S> Layer<S> for RegisteredTaskDeadlineLayer
	where
		S: Subscriber,
	{
		fn on_event(&self, event: &Event<'_>, _ctx: LayerContext<'_, S>) {
			if *event.metadata().level() != tracing::Level::WARN {
				return;
			}

			let mut visitor = MessageVisitor::default();
			event.record(&mut visitor);
			if visitor.message.as_deref() == Some("actor work cancelled by shutdown deadline")
				&& visitor.actor_id.as_deref() == Some("actor-register-task-deadline")
				&& visitor.kind.as_deref() == Some("registered_task")
				&& visitor.reason.as_deref() == Some("shutdown_deadline_elapsed")
			{
				self.count.fetch_add(1, Ordering::SeqCst);
			}
		}
	}

	struct NotifyOnDrop(DropMutex<Option<oneshot::Sender<()>>>);

	impl NotifyOnDrop {
		fn new(sender: oneshot::Sender<()>) -> Self {
			Self(DropMutex::new(Some(sender)))
		}
	}

	impl Drop for NotifyOnDrop {
		fn drop(&mut self) {
			if let Some(sender) = self.0.lock().take() {
				let _ = sender.send(());
			}
		}
	}

	#[tokio::test(start_paused = true)]
	async fn shutdown_task_counter_reaches_zero_after_completion() {
		let ctx = ActorContext::new_for_sleep_tests("actor-shutdown-complete");
		let (done_tx, done_rx) = oneshot::channel();

		ctx.track_shutdown_task(async move {
			let _ = done_tx.send(());
		});

		done_rx.await.expect("shutdown task should complete");
		yield_now().await;

		assert_eq!(ctx.shutdown_task_count(), 0);
		assert!(
			ctx.0
				.sleep
				.work
				.shutdown_counter
				.wait_zero(Instant::now() + Duration::from_millis(1))
				.await
		);
	}

	#[tokio::test(start_paused = true)]
	async fn shutdown_task_counter_reaches_zero_after_panic() {
		let ctx = ActorContext::new_for_sleep_tests("actor-shutdown-panic");

		ctx.track_shutdown_task(async move {
			panic!("boom");
		});

		yield_now().await;
		yield_now().await;

		assert_eq!(ctx.shutdown_task_count(), 0);
		assert!(
			ctx.0
				.sleep
				.work
				.shutdown_counter
				.wait_zero(Instant::now() + Duration::from_millis(1))
				.await
		);
	}

	#[tokio::test(start_paused = true)]
	async fn teardown_aborts_tracked_shutdown_tasks() {
		let ctx = ActorContext::new_for_sleep_tests("actor-shutdown-teardown");
		let (drop_tx, drop_rx) = oneshot::channel();
		let (_never_tx, never_rx) = oneshot::channel::<()>();
		let notify = NotifyOnDrop::new(drop_tx);

		ctx.track_shutdown_task(async move {
			let _notify = notify;
			let _ = never_rx.await;
		});

		assert_eq!(ctx.shutdown_task_count(), 1);

		ctx.teardown_sleep_state().await;
		advance(Duration::from_millis(1)).await;

		drop_rx
			.await
			.expect("teardown should abort the tracked task");
		assert_eq!(ctx.shutdown_task_count(), 0);
	}

	#[tokio::test(start_paused = true)]
	async fn track_shutdown_task_refuses_spawns_after_teardown() {
		let ctx = ActorContext::new_for_sleep_tests("actor-shutdown-refuse");
		let warning_count = Arc::new(AtomicUsize::new(0));
		let subscriber = Registry::default().with(ShutdownTaskRefusedLayer {
			count: warning_count.clone(),
		});
		let _guard = tracing::subscriber::set_default(subscriber);

		ctx.teardown_sleep_state().await;
		ctx.track_shutdown_task(async move {
			panic!("post-teardown shutdown task should never spawn");
		});
		yield_now().await;

		assert_eq!(ctx.shutdown_task_count(), 0);
		assert_eq!(warning_count.load(Ordering::SeqCst), 1);
	}

	#[tokio::test(start_paused = true)]
	async fn register_task_exits_when_shutdown_deadline_cancels() {
		let ctx = ActorContext::new_for_sleep_tests("actor-register-task-deadline");
		let warning_count = Arc::new(AtomicUsize::new(0));
		let subscriber = Registry::default().with(RegisteredTaskDeadlineLayer {
			count: warning_count.clone(),
		});
		let _guard = tracing::subscriber::set_default(subscriber);

		ctx.register_task(futures::future::pending::<()>());
		assert_eq!(ctx.shutdown_task_count(), 1);

		ctx.cancel_shutdown_deadline();

		assert!(
			ctx.0
				.sleep
				.work
				.shutdown_counter
				.wait_zero(Instant::now() + Duration::from_millis(1))
				.await,
			"registered task should stop waiting after the shutdown deadline"
		);
		assert_eq!(ctx.shutdown_task_count(), 0);
		assert_eq!(warning_count.load(Ordering::SeqCst), 1);
	}

	#[tokio::test(start_paused = true)]
	async fn tracked_shutdown_work_drain_wakes_on_shutdown_counter_zero() {
		let ctx = ActorContext::new_for_sleep_tests("actor-shutdown-drain-counter");
		ctx.notify_activity_dirty();
		let (release_tx, release_rx) = oneshot::channel();

		ctx.track_shutdown_task(async move {
			let _ = release_rx.await;
		});
		let waiter = tokio::spawn({
			let ctx = ctx.clone();
			async move { ctx.wait_for_tracked_shutdown_work().await }
		});

		yield_now().await;
		assert!(
			!waiter.is_finished(),
			"shutdown drain should wait while the counter is non-zero"
		);

		release_tx
			.send(())
			.expect("release signal should send to tracked shutdown task");
		yield_now().await;
		yield_now().await;

		assert!(
			waiter.is_finished(),
			"shutdown drain should wake from the counter zero notification"
		);
		assert!(waiter.await.expect("shutdown drain waiter should join"));
	}

	#[tokio::test(start_paused = true)]
	async fn tracked_shutdown_work_drain_wakes_on_websocket_callback_zero() {
		let ctx = ActorContext::new_for_sleep_tests("actor-shutdown-drain-websocket");
		ctx.notify_activity_dirty();
		let guard = ctx.websocket_callback_region();
		let waiter = tokio::spawn({
			let ctx = ctx.clone();
			async move { ctx.wait_for_tracked_shutdown_work().await }
		});

		yield_now().await;
		assert!(
			!waiter.is_finished(),
			"shutdown drain should wait while the websocket callback is active"
		);

		drop(guard);
		yield_now().await;

		assert!(
			waiter.is_finished(),
			"shutdown drain should wake from the websocket zero notification"
		);
		assert!(waiter.await.expect("shutdown drain waiter should join"));
	}

	#[tokio::test(start_paused = true)]
	async fn keep_awake_spawned_work_exits_when_shutdown_deadline_cancels() {
		let ctx = ActorContext::new_for_sleep_tests("actor-keep-awake-deadline");

		ctx.spawn_work(ActorWorkKind::KeepAwake, futures::future::pending::<()>());
		assert_eq!(ctx.shutdown_task_count(), 1);
		assert_eq!(ctx.sleep_keep_awake_count(), 1);

		ctx.cancel_shutdown_deadline();

		assert!(
			ctx.0
				.sleep
				.work
				.shutdown_counter
				.wait_zero(Instant::now() + Duration::from_millis(1))
				.await,
			"keepAwake work should stop waiting after the shutdown deadline"
		);
		assert_eq!(ctx.shutdown_task_count(), 0);
		assert_eq!(ctx.sleep_keep_awake_count(), 0);
	}

	#[tokio::test(start_paused = true)]
	async fn sleep_then_destroy_signal_tasks_do_not_leak_after_teardown() {
		let ctx = ActorContext::new_for_sleep_tests("actor-sleep-destroy");
		ctx.set_started(true);

		ctx.sleep()
			.expect("sleep should succeed after started is set");
		ctx.destroy()
			.expect("destroy should succeed after started is set");

		assert_eq!(
			ctx.shutdown_task_count(),
			2,
			"sleep and destroy bridge work should be tracked before it runs"
		);

		ctx.teardown_sleep_state().await;
		advance(Duration::from_millis(1)).await;

		assert_eq!(ctx.shutdown_task_count(), 0);
	}

	#[tokio::test(start_paused = true)]
	async fn sleep_idle_window_without_work_returns_next_tick() {
		let ctx = ActorContext::new_for_sleep_tests("actor-sleep-idle");

		let waiter = tokio::spawn({
			let ctx = ctx.clone();
			async move {
				ctx.wait_for_sleep_idle_window(Instant::now() + Duration::from_secs(1))
					.await
			}
		});

		yield_now().await;

		assert!(
			waiter.is_finished(),
			"idle wait should not poll in 10ms slices"
		);
		assert!(waiter.await.expect("idle waiter should join"));
	}

	#[tokio::test(start_paused = true)]
	async fn sleep_idle_window_waits_for_http_counter_zero_transition() {
		let ctx = ActorContext::new_for_sleep_tests("actor-http-idle");
		let counter = Arc::new(AsyncCounter::new());
		counter.register_zero_notify(&ctx.0.sleep.work.idle_notify);
		counter.register_change_notify(&ctx.sleep_activity_notify());
		*ctx.0.sleep.http_request_counter.lock() = Some(counter.clone());

		counter.increment();
		let waiter = tokio::spawn({
			let ctx = ctx.clone();
			async move {
				ctx.wait_for_sleep_idle_window(Instant::now() + Duration::from_secs(1))
					.await
			}
		});

		yield_now().await;
		assert!(
			!waiter.is_finished(),
			"http request drain should stay blocked while the counter is non-zero"
		);

		counter.decrement();
		advance(Duration::from_millis(1)).await;
		yield_now().await;
		assert!(waiter.await.expect("http idle waiter should join"));
	}

	#[tokio::test(start_paused = true)]
	async fn http_request_idle_wait_uses_zero_notify() {
		let ctx = ActorContext::new_for_sleep_tests("actor-http-zero-notify");
		let counter = Arc::new(AsyncCounter::new());
		counter.register_zero_notify(&ctx.0.sleep.work.idle_notify);
		*ctx.0.sleep.http_request_counter.lock() = Some(counter.clone());

		counter.increment();
		let waiter = tokio::spawn({
			let ctx = ctx.clone();
			async move {
				ctx.wait_for_http_requests_idle().await;
			}
		});

		yield_now().await;
		assert!(
			!waiter.is_finished(),
			"http request idle wait should block while the counter is non-zero"
		);

		counter.decrement();
		yield_now().await;

		assert!(
			waiter.is_finished(),
			"http request idle wait should wake on the zero notification"
		);
		waiter.await.expect("http idle waiter should join");
	}

	#[tokio::test(start_paused = true)]
	async fn sleep_idle_window_waits_for_websocket_callback_zero_transition() {
		let ctx = ActorContext::new_for_sleep_tests("actor-websocket-idle");
		let guard = ctx.websocket_callback_region();

		let waiter = tokio::spawn({
			let ctx = ctx.clone();
			async move {
				ctx.wait_for_sleep_idle_window(Instant::now() + Duration::from_secs(1))
					.await
			}
		});

		yield_now().await;
		assert!(
			!waiter.is_finished(),
			"websocket callback drain should stay blocked while the counter is non-zero"
		);

		drop(guard);
		advance(Duration::from_millis(1)).await;
		yield_now().await;
		assert!(waiter.await.expect("websocket idle waiter should join"));
	}

	#[tokio::test(start_paused = true)]
	async fn sleep_before_started_errors_with_actor_starting() {
		let ctx = ActorContext::new_for_sleep_tests("actor-sleep-before-started");

		let err = ctx
			.sleep()
			.expect_err("sleep should fail before started is set");
		let rivet_err = rivet_error::RivetError::extract(&err);
		assert_eq!(rivet_err.group(), "actor");
		assert_eq!(rivet_err.code(), "starting");
	}

	#[tokio::test(start_paused = true)]
	async fn destroy_before_started_errors_with_actor_starting() {
		let ctx = ActorContext::new_for_sleep_tests("actor-destroy-before-started");

		let err = ctx
			.destroy()
			.expect_err("destroy should fail before started is set");
		let rivet_err = rivet_error::RivetError::extract(&err);
		assert_eq!(rivet_err.group(), "actor");
		assert_eq!(rivet_err.code(), "starting");
	}

	#[tokio::test(start_paused = true)]
	async fn double_sleep_errors_with_actor_stopping() {
		let ctx = ActorContext::new_for_sleep_tests("actor-double-sleep");
		ctx.set_started(true);

		ctx.sleep()
			.expect("first sleep call should be accepted after startup");

		let err = ctx
			.sleep()
			.expect_err("second sleep call should fail as already requested");
		let rivet_err = rivet_error::RivetError::extract(&err);
		assert_eq!(rivet_err.group(), "actor");
		assert_eq!(rivet_err.code(), "stopping");
	}

	#[tokio::test(start_paused = true)]
	async fn double_destroy_errors_with_actor_stopping() {
		let ctx = ActorContext::new_for_sleep_tests("actor-double-destroy");
		ctx.set_started(true);

		ctx.destroy()
			.expect("first destroy call should be accepted after startup");

		let err = ctx
			.destroy()
			.expect_err("second destroy call should fail as already requested");
		let rivet_err = rivet_error::RivetError::extract(&err);
		assert_eq!(rivet_err.group(), "actor");
		assert_eq!(rivet_err.code(), "stopping");
	}

	// `set_prevent_sleep` is a deprecated no-op kept for NAPI bridge
	// compatibility. The exhaustive `CanSleep` match below is a build-time
	// guard against reintroducing a `PreventSleep` enum variant.
	#[tokio::test(start_paused = true)]
	#[allow(deprecated)]
	async fn set_prevent_sleep_is_a_deprecated_noop() {
		use crate::actor::sleep::CanSleep;

		let ctx = ActorContext::new_for_sleep_tests("actor-prevent-sleep-noop");
		ctx.set_started(true);

		ctx.set_prevent_sleep(true);
		match ctx.can_sleep().await {
			CanSleep::Yes
			| CanSleep::NotReady
			| CanSleep::NoSleep
			| CanSleep::ActiveHttpRequests
			| CanSleep::ActiveKeepAwake
			| CanSleep::ActiveInternalKeepAwake
			| CanSleep::ActiveRunHandler
			| CanSleep::ActiveDisconnectCallbacks
			| CanSleep::ActiveConnections
			| CanSleep::ActiveWebSocketCallbacks => {}
		}

		ctx.set_prevent_sleep(false);
	}

	#[tokio::test(start_paused = true)]
	async fn shutdown_deadline_token_aborts_select_awaiting_task() {
		// Mirrors the NAPI `RunGracefulCleanup` pattern: a task awaits user
		// work and the shutdown_deadline cancellation in a `tokio::select!`.
		// If `cancel_shutdown_deadline()` does not propagate to clones of the
		// token, the spawned task would hang and the test would time out.
		let ctx = ActorContext::new_for_sleep_tests("actor-shutdown-deadline");
		let token = ctx.shutdown_deadline_token();
		assert!(!token.is_cancelled());

		let aborted = Arc::new(std::sync::atomic::AtomicBool::new(false));
		let aborted_clone = aborted.clone();
		let task = tokio::spawn(async move {
			tokio::select! {
				_ = token.cancelled() => {
					aborted_clone.store(true, Ordering::SeqCst);
				}
				_ = futures::future::pending::<()>() => {}
			}
		});

		yield_now().await;
		assert!(!aborted.load(Ordering::SeqCst));

		ctx.cancel_shutdown_deadline();
		task.await.expect("select task should join after cancel");
		assert!(
			aborted.load(Ordering::SeqCst),
			"select-awaiting task must observe cancel via the cloned token"
		);
	}

	#[tokio::test(start_paused = true)]
	async fn sleep_after_grace_clears_started_returns_stopping_not_starting() {
		// Simulate the lifecycle state machine clearing `started` when it
		// transitions into SleepGrace. Calls into `sleep()` after that point
		// must surface `Stopping`, not `Starting`.
		let ctx = ActorContext::new_for_sleep_tests("actor-sleep-after-grace");
		ctx.set_started(true);

		ctx.sleep().expect("first sleep call should be accepted");

		// Lifecycle machine clears `started` on transition into SleepGrace.
		ctx.set_started(false);

		let err = ctx.sleep().expect_err("second sleep should fail");
		let rivet_err = rivet_error::RivetError::extract(&err);
		assert_eq!(rivet_err.group(), "actor");
		assert_eq!(
			rivet_err.code(),
			"stopping",
			"started=false during shutdown must surface stopping, not starting"
		);
	}
}