rivet-envoy-client 2.3.15

Envoy client transport for Rivet actor hosts
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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
use rivet_envoy_protocol as protocol;
use std::collections::HashMap;
use std::time::Duration;

use crate::connection::ws_send;
use crate::envoy::{BufferedActorMessage, EnvoyContext, HttpRequestRoute, WebSocketRoute};

const HTTP_REQUEST_CANCELLATION_TTL: Duration = Duration::from_secs(60);

#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct HttpRequestCancellationKey {
	gateway_id: protocol::GatewayId,
	request_id: protocol::RequestId,
	actor_id: String,
	actor_generation: u32,
}

fn request_cancellation_key(
	message_id: &protocol::MessageId,
	actor_id: &str,
	actor_generation: u32,
) -> HttpRequestCancellationKey {
	HttpRequestCancellationKey {
		gateway_id: message_id.gateway_id,
		request_id: message_id.request_id,
		actor_id: actor_id.to_owned(),
		actor_generation,
	}
}

fn request_abort_cancellation_key(
	message_id: &protocol::MessageId,
	abort: &protocol::ToEnvoyRequestAbort,
) -> Result<Option<HttpRequestCancellationKey>, &'static str> {
	match (&abort.actor_id, abort.actor_generation) {
		(Some(actor_id), Some(actor_generation)) => Ok(Some(request_cancellation_key(
			message_id,
			actor_id,
			actor_generation,
		))),
		(None, None) => Ok(None),
		_ => Err("HTTP request abort must include both actor id and generation"),
	}
}

fn prune_http_request_cancellations(ctx: &mut EnvoyContext) {
	let now = crate::time::Instant::now();
	ctx.http_request_cancellations.retain(|_, cancelled_at| {
		now.duration_since(*cancelled_at) < HTTP_REQUEST_CANCELLATION_TTL
	});
}

pub(crate) fn make_ws_key(
	gateway_id: &protocol::GatewayId,
	request_id: &protocol::RequestId,
) -> [u8; 8] {
	let mut key = [0u8; 8];
	key[..4].copy_from_slice(gateway_id);
	key[4..].copy_from_slice(request_id);
	key
}

fn advance_http_message_index(ctx: &mut EnvoyContext, message_id: &protocol::MessageId) -> bool {
	let key: [&[u8]; 2] = [&message_id.gateway_id, &message_id.request_id];
	let Some(expected) = ctx.http_message_indices.get_mut(&key) else {
		tracing::warn!(
			message_index = message_id.message_index,
			"received HTTP tunnel message without request start"
		);
		return false;
	};
	if message_id.message_index != *expected {
		tracing::warn!(
			expected_message_index = *expected,
			actual_message_index = message_id.message_index,
			"received reordered HTTP tunnel message"
		);
		return false;
	}
	*expected = expected.wrapping_add(1);
	true
}

pub struct HibernatingWebSocketMetadata {
	pub gateway_id: protocol::GatewayId,
	pub request_id: protocol::RequestId,
	pub envoy_message_index: u16,
	pub rivet_message_index: u16,
	pub path: String,
	pub headers: std::collections::HashMap<String, String>,
}

pub async fn handle_tunnel_message(
	ctx: &mut EnvoyContext,
	connection_session: u64,
	msg: protocol::ToEnvoyTunnelMessage,
) {
	let message_id = msg.message_id;
	let is_http_continuation = matches!(
		&msg.message_kind,
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyRequestChunk(_)
			| protocol::ToEnvoyTunnelMessageKind::ToEnvoyRequestAbort(_)
			| protocol::ToEnvoyTunnelMessageKind::ToEnvoyRequestBodyCancel
			| protocol::ToEnvoyTunnelMessageKind::ToEnvoyResponseBodyWindowUpdate(_)
	);
	if is_http_continuation
		&& let Some(route) = ctx
			.http_request_routes
			.get(&[&message_id.gateway_id, &message_id.request_id])
		&& route.session != connection_session
	{
		handle_http_protocol_violation(
			ctx,
			connection_session,
			message_id,
			"HTTP request identifier belongs to another connection",
		)
		.await;
		return;
	}
	match msg.message_kind {
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyRequestStart(req) => {
			handle_request_start(ctx, connection_session, message_id, req).await;
		}
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyRequestChunk(chunk) => {
			if advance_http_message_index(ctx, &message_id) {
				handle_request_chunk(ctx, message_id, chunk).await;
			} else {
				handle_http_protocol_violation(
					ctx,
					connection_session,
					message_id,
					"invalid HTTP tunnel message sequence",
				)
				.await;
			}
		}
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyRequestAbort(abort) => {
			let cancellation_key = match request_abort_cancellation_key(&message_id, &abort) {
				Ok(key) => key,
				Err(detail) => {
					handle_http_protocol_violation(ctx, connection_session, message_id, detail)
						.await;
					return;
				}
			};
			if let Some(cancellation_key) = cancellation_key {
				let route = ctx
					.http_request_routes
					.get(&[&message_id.gateway_id, &message_id.request_id])
					.map(|route| (route.actor_id.clone(), route.actor_generation));
				if let Some((route_actor_id, route_actor_generation)) = route
					&& (cancellation_key.actor_id != route_actor_id
						|| Some(cancellation_key.actor_generation) != route_actor_generation)
				{
					handle_http_protocol_violation(
						ctx,
						connection_session,
						message_id,
						"HTTP request abort actor identity does not match request start",
					)
					.await;
				} else {
					// Exact-generation cancellation is intentionally out of band from the
					// ordered body stream. It must work after an ambiguous message handoff,
					// when Gateway cannot know which message index Envoy accepted.
					handle_request_abort(ctx, message_id, abort, Some(cancellation_key));
				}
			} else if advance_http_message_index(ctx, &message_id) {
				// V6 cancellation has no actor identity, so preserve its ordered behavior.
				handle_request_abort(ctx, message_id, abort, None);
			} else {
				handle_http_protocol_violation(
					ctx,
					connection_session,
					message_id,
					"invalid HTTP request-abort sequence",
				)
				.await;
			}
		}
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyRequestBodyCancel => {
			if advance_http_message_index(ctx, &message_id) {
				handle_request_body_cancel(ctx, message_id);
			} else {
				handle_http_protocol_violation(
					ctx,
					connection_session,
					message_id,
					"invalid HTTP request-body-cancel sequence",
				)
				.await;
			}
		}
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyResponseBodyWindowUpdate(update) => {
			if advance_http_message_index(ctx, &message_id) {
				handle_response_body_window_update(ctx, message_id, update.consumed_bytes);
			} else {
				handle_http_protocol_violation(
					ctx,
					connection_session,
					message_id,
					"invalid HTTP response-window sequence",
				)
				.await;
			}
		}
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyWebSocketOpen(open) => {
			handle_ws_open(ctx, message_id, open).await;
		}
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyWebSocketMessage(msg) => {
			handle_ws_message(ctx, message_id, msg);
		}
		protocol::ToEnvoyTunnelMessageKind::ToEnvoyWebSocketClose(close) => {
			handle_ws_close(ctx, message_id, close);
		}
	}
}

async fn handle_http_protocol_violation(
	ctx: &mut EnvoyContext,
	connection_session: u64,
	message_id: protocol::MessageId,
	detail: &'static str,
) {
	let key: [&[u8]; 2] = [&message_id.gateway_id, &message_id.request_id];
	if let Some(route) = ctx.http_request_routes.get(&key) {
		if route.session != connection_session {
			send_response_abort_for_session(ctx, connection_session, message_id, detail).await;
			return;
		}
		let actor_id = route.actor_id.clone();
		let actor_generation = route.actor_generation;
		if route.actor_admitted
			&& let Some(actor) = ctx.get_actor(&actor_id, actor_generation)
		{
			let _ = actor
				.handle
				.send(crate::actor::ToActor::ReqProtocolViolation {
					message_id: message_id.clone(),
					detail: detail.to_owned(),
				});
		}
		ctx.http_request_routes.remove(&key);
		ctx.http_message_indices.remove(&key);
		return;
	}

	send_response_abort_for_session(ctx, connection_session, message_id, detail).await;
}

async fn send_response_abort_for_session(
	ctx: &EnvoyContext,
	connection_session: u64,
	mut message_id: protocol::MessageId,
	detail: &'static str,
) {
	message_id.message_index = 0;
	let _ = crate::connection::ws_send_http_for_session(
		&ctx.shared,
		protocol::ToRivet::ToRivetTunnelMessage(protocol::ToRivetTunnelMessage {
			message_id,
			message_kind: protocol::ToRivetTunnelMessageKind::ToRivetResponseAbort(
				protocol::ToRivetResponseAbort {
					reason: protocol::HttpStreamAbortReason {
						kind: protocol::HttpStreamAbortReasonKind::InternalError,
						detail: Some(detail.to_owned()),
					},
				},
			),
		}),
		connection_session,
	)
	.await;
}

fn handle_request_body_cancel(ctx: &mut EnvoyContext, message_id: protocol::MessageId) {
	let route = ctx
		.http_request_routes
		.get(&[&message_id.gateway_id, &message_id.request_id])
		.map(|route| {
			(
				route.actor_id.clone(),
				route.actor_generation,
				route.actor_admitted,
			)
		});
	if let Some((actor_id, actor_generation, true)) = &route
		&& let Some(actor) = ctx.get_actor(actor_id, *actor_generation)
	{
		let _ = actor.handle.send(crate::actor::ToActor::ReqBodyCancel {
			message_id: message_id.clone(),
		});
	}
	if matches!(route, Some((_, _, false))) {
		ctx.http_request_routes
			.remove(&[&message_id.gateway_id, &message_id.request_id]);
		ctx.http_message_indices
			.remove(&[&message_id.gateway_id, &message_id.request_id]);
	}
}

fn handle_response_body_window_update(
	ctx: &mut EnvoyContext,
	message_id: protocol::MessageId,
	consumed_bytes: u64,
) {
	let route = ctx
		.http_request_routes
		.get(&[&message_id.gateway_id, &message_id.request_id])
		.map(|route| {
			(
				route.actor_id.clone(),
				route.actor_generation,
				route.actor_admitted,
			)
		});
	if let Some((actor_id, actor_generation, true)) = &route
		&& let Some(actor) = ctx.get_actor(actor_id, *actor_generation)
	{
		let _ = actor
			.handle
			.send(crate::actor::ToActor::ResponseBodyWindowUpdate {
				message_id,
				consumed_bytes,
			});
	}
}

async fn handle_request_start(
	ctx: &mut EnvoyContext,
	connection_session: u64,
	message_id: protocol::MessageId,
	req: protocol::ToEnvoyRequestStart,
) {
	let key: [&[u8]; 2] = [&message_id.gateway_id, &message_id.request_id];
	let actor_id = req.actor_id.clone();
	let actor_generation = req.actor_generation;
	let response_stream = req.response_stream;
	let request_stream = req.stream;
	if message_id.message_index != 0 {
		tracing::warn!(
			message_index = message_id.message_index,
			"received invalid HTTP request start sequence"
		);
		send_response_abort_for_session(
			ctx,
			connection_session,
			message_id,
			"HTTP request start must use message index zero",
		)
		.await;
		return;
	}
	prune_http_request_cancellations(ctx);
	if let Some(actor_generation) = actor_generation {
		let cancellation_key = request_cancellation_key(&message_id, &actor_id, actor_generation);
		if ctx
			.http_request_cancellations
			.contains_key(&cancellation_key)
		{
			tracing::debug!(
				%actor_id,
				actor_generation,
				gateway_id = ?message_id.gateway_id,
				request_id = ?message_id.request_id,
				"discarding HTTP request start cancelled before delivery"
			);
			return;
		}
	}
	if let Some(existing) = ctx.http_request_routes.get(&key) {
		let same_session = existing.session == connection_session;
		handle_http_protocol_violation(
			ctx,
			connection_session,
			message_id,
			if same_session {
				"duplicate HTTP request start"
			} else {
				"HTTP request identifier belongs to another connection"
			},
		)
		.await;
		return;
	}
	let actor_handle = ctx
		.get_actor_for_admission(&actor_id, actor_generation)
		.map(|actor| actor.handle.clone());

	let Some(actor_handle) = actor_handle else {
		let generation_mismatch =
			actor_generation.is_some() && ctx.get_actor(&actor_id, None).is_some();
		let (error_code, message) = if generation_mismatch {
			tracing::warn!(
				actor_id = %actor_id,
				?actor_generation,
				"received request for stale actor generation"
			);
			(
				"envoy.actor_generation_mismatch",
				"Actor generation does not match",
			)
		} else {
			tracing::warn!(actor_id = %actor_id, ?actor_generation, "received request for unknown actor");
			("envoy.actor_not_found", "Actor not found")
		};
		// RequestStart is deliberately not application-acknowledged, so body frames may already be
		// in flight when this rejection reaches Gateway. Keep a short-lived drain route only for a
		// streamed upload; its finish, cancellation, abort, or connection close removes the state.
		if request_stream {
			ctx.http_message_indices.insert(&key, 1);
			ctx.http_request_routes.insert(
				&key,
				HttpRequestRoute {
					actor_id: actor_id.clone(),
					actor_generation,
					actor_admitted: false,
					session: connection_session,
					gateway_id: message_id.gateway_id,
					request_id: message_id.request_id,
				},
			);
		}
		send_error_response(
			ctx,
			response_stream.then_some(connection_session),
			message_id.gateway_id,
			message_id.request_id,
			error_code,
			message,
			actor_generation.map(|generation| (actor_id.as_str(), generation)),
		)
		.await;
		return;
	};
	ctx.http_message_indices
		.insert(&[&message_id.gateway_id, &message_id.request_id], 1);

	ctx.http_request_routes.insert(
		&[&message_id.gateway_id, &message_id.request_id],
		HttpRequestRoute {
			actor_id: actor_id.clone(),
			actor_generation,
			actor_admitted: true,
			session: connection_session,
			gateway_id: message_id.gateway_id,
			request_id: message_id.request_id,
		},
	);

	if actor_handle
		.send(crate::actor::ToActor::ReqStart {
			message_id: message_id.clone(),
			req,
			connection_session,
		})
		.is_err()
	{
		ctx.http_request_routes
			.remove(&[&message_id.gateway_id, &message_id.request_id]);
		ctx.http_message_indices
			.remove(&[&message_id.gateway_id, &message_id.request_id]);
		send_error_response(
			ctx,
			response_stream.then_some(connection_session),
			message_id.gateway_id,
			message_id.request_id,
			"envoy.actor_not_found",
			"Actor stopped before accepting request",
			actor_generation.map(|generation| (actor_id.as_str(), generation)),
		)
		.await;
	}
}

async fn handle_request_chunk(
	ctx: &mut EnvoyContext,
	message_id: protocol::MessageId,
	chunk: protocol::ToEnvoyRequestChunk,
) {
	let route = ctx
		.http_request_routes
		.get(&[&message_id.gateway_id, &message_id.request_id])
		.map(|route| {
			(
				route.actor_id.clone(),
				route.actor_generation,
				route.actor_admitted,
			)
		});

	if let Some((actor_id, actor_generation, actor_admitted)) = &route {
		if !actor_admitted {
			if chunk.finish {
				ctx.http_request_routes
					.remove(&[&message_id.gateway_id, &message_id.request_id]);
				ctx.http_message_indices
					.remove(&[&message_id.gateway_id, &message_id.request_id]);
			}
			return;
		}
		if let Some(actor) = ctx.get_actor(actor_id, *actor_generation) {
			let _ = actor.handle.send(crate::actor::ToActor::ReqChunk {
				message_id: message_id.clone(),
				chunk,
			});
		} else {
			tracing::warn!(actor_id = %actor_id, "received request chunk for unknown actor");
		}
	} else {
		tracing::warn!(
			gateway_id = ?message_id.gateway_id,
			request_id = ?message_id.request_id,
			message_index = message_id.message_index,
			"received request chunk without request start"
		);
		send_error_response(
			ctx,
			None,
			message_id.gateway_id,
			message_id.request_id,
			"envoy.request_not_found",
			"Request start was not delivered",
			None,
		)
		.await;
	}
}

fn handle_request_abort(
	ctx: &mut EnvoyContext,
	message_id: protocol::MessageId,
	abort: protocol::ToEnvoyRequestAbort,
	cancellation_key: Option<HttpRequestCancellationKey>,
) {
	let route = ctx
		.http_request_routes
		.get(&[&message_id.gateway_id, &message_id.request_id])
		.map(|route| {
			(
				route.actor_id.clone(),
				route.actor_generation,
				route.actor_admitted,
			)
		});
	if let Some((actor_id, actor_generation, true)) = &route {
		if let Some(actor) = ctx.get_actor(actor_id, *actor_generation) {
			let _ = actor.handle.send(crate::actor::ToActor::ReqAbort {
				message_id: message_id.clone(),
				reason: abort.reason,
			});
		}
	}
	if let Some(cancellation_key) = cancellation_key {
		prune_http_request_cancellations(ctx);
		ctx.http_request_cancellations
			.insert(cancellation_key, crate::time::Instant::now());
		tracing::debug!(
			gateway_id = ?message_id.gateway_id,
			request_id = ?message_id.request_id,
			"recorded exact HTTP request cancellation"
		);
	}

	ctx.http_request_routes
		.remove(&[&message_id.gateway_id, &message_id.request_id]);
	ctx.http_message_indices
		.remove(&[&message_id.gateway_id, &message_id.request_id]);
}

async fn handle_ws_open(
	ctx: &mut EnvoyContext,
	message_id: protocol::MessageId,
	open: protocol::ToEnvoyWebSocketOpen,
) {
	let actor_id = open.actor_id.clone();
	let actor_generation = open.actor_generation;
	let actor_handle = ctx
		.get_actor_for_admission(&actor_id, actor_generation)
		.map(|actor| actor.handle.clone());

	let Some(actor_handle) = actor_handle else {
		let generation_mismatch =
			actor_generation.is_some() && ctx.get_actor(&actor_id, None).is_some();
		let reason = if generation_mismatch {
			tracing::warn!(
				actor_id = %actor_id,
				?actor_generation,
				"received ws open for stale actor generation"
			);
			"envoy.actor_generation_mismatch"
		} else {
			tracing::warn!(actor_id = %actor_id, ?actor_generation, "received ws open for unknown actor");
			"envoy.actor_not_found"
		};

		ws_send(
			&ctx.shared,
			protocol::ToRivet::ToRivetTunnelMessage(protocol::ToRivetTunnelMessage {
				message_id,
				message_kind: protocol::ToRivetTunnelMessageKind::ToRivetWebSocketClose(
					protocol::ToRivetWebSocketClose {
						code: Some(1011),
						reason: Some(reason.to_string()),
						hibernate: false,
					},
				),
			}),
		)
		.await;
		return;
	};

	ctx.request_to_actor.insert(
		&[&message_id.gateway_id, &message_id.request_id],
		WebSocketRoute {
			actor_id: actor_id.clone(),
			actor_generation,
		},
	);
	ctx.shared
		.live_tunnel_requests
		.lock()
		.expect("shared live tunnel request registry poisoned")
		.insert(
			make_ws_key(&message_id.gateway_id, &message_id.request_id),
			actor_id.clone(),
		);

	// Convert HashMap headers to BTreeMap for the actor message
	let headers = open
		.headers
		.iter()
		.map(|(k, v)| (k.clone(), v.clone()))
		.collect();

	if actor_handle
		.send(crate::actor::ToActor::WsOpen {
			message_id: message_id.clone(),
			path: open.path,
			headers,
		})
		.is_err()
	{
		ctx.request_to_actor
			.remove(&[&message_id.gateway_id, &message_id.request_id]);
		ctx.shared
			.live_tunnel_requests
			.lock()
			.expect("shared live tunnel request registry poisoned")
			.remove(&make_ws_key(&message_id.gateway_id, &message_id.request_id));
		ws_send(
			&ctx.shared,
			protocol::ToRivet::ToRivetTunnelMessage(protocol::ToRivetTunnelMessage {
				message_id,
				message_kind: protocol::ToRivetTunnelMessageKind::ToRivetWebSocketClose(
					protocol::ToRivetWebSocketClose {
						code: Some(1011),
						reason: Some("envoy.actor_not_found".to_string()),
						hibernate: false,
					},
				),
			}),
		)
		.await;
	}
}

fn handle_ws_message(
	ctx: &mut EnvoyContext,
	message_id: protocol::MessageId,
	msg: protocol::ToEnvoyWebSocketMessage,
) {
	let route = ctx
		.request_to_actor
		.get(&[&message_id.gateway_id, &message_id.request_id])
		.cloned();
	if let Some(route) = &route {
		if let Some(actor) = ctx.get_actor(&route.actor_id, route.actor_generation) {
			let _ = actor
				.handle
				.send(crate::actor::ToActor::WsMsg { message_id, msg });
		} else if route.actor_generation.is_none() {
			ctx.buffered_actor_messages
				.entry(route.actor_id.clone())
				.or_default()
				.push(BufferedActorMessage::WsMsg { message_id, msg });
		}
	}
}

fn handle_ws_close(
	ctx: &mut EnvoyContext,
	message_id: protocol::MessageId,
	close: protocol::ToEnvoyWebSocketClose,
) {
	let route = ctx
		.request_to_actor
		.get(&[&message_id.gateway_id, &message_id.request_id])
		.cloned();
	if let Some(route) = &route {
		if let Some(actor) = ctx.get_actor(&route.actor_id, route.actor_generation) {
			let _ = actor.handle.send(crate::actor::ToActor::WsClose {
				message_id: message_id.clone(),
				close,
			});
		} else if route.actor_generation.is_none() {
			ctx.buffered_actor_messages
				.entry(route.actor_id.clone())
				.or_default()
				.push(BufferedActorMessage::WsClose {
					message_id: message_id.clone(),
					close,
				});
		}
	}

	ctx.request_to_actor
		.remove(&[&message_id.gateway_id, &message_id.request_id]);
	ctx.shared
		.live_tunnel_requests
		.lock()
		.expect("shared live tunnel request registry poisoned")
		.remove(&make_ws_key(&message_id.gateway_id, &message_id.request_id));
}

pub fn send_hibernatable_ws_message_ack(
	ctx: &mut EnvoyContext,
	gateway_id: protocol::GatewayId,
	request_id: protocol::RequestId,
	envoy_message_index: u16,
) {
	let route = ctx
		.request_to_actor
		.get(&[&gateway_id, &request_id])
		.cloned();
	if let Some(route) = &route {
		if let Some(actor) = ctx.get_actor(&route.actor_id, route.actor_generation) {
			let _ = actor.handle.send(crate::actor::ToActor::HwsAck {
				gateway_id,
				request_id,
				envoy_message_index,
			});
		}
	}
}

pub async fn resend_buffered_tunnel_messages(ctx: &mut EnvoyContext) {
	if ctx.buffered_messages.is_empty() {
		return;
	}

	tracing::info!(
		count = ctx.buffered_messages.len(),
		"resending buffered tunnel messages"
	);

	let messages = std::mem::take(&mut ctx.buffered_messages);
	let mut messages = messages.into_iter();
	while let Some(msg) = messages.next() {
		let failed = ws_send(
			&ctx.shared,
			protocol::ToRivet::ToRivetTunnelMessage(msg.clone()),
		)
		.await;
		if failed {
			ctx.buffered_messages.push(msg);
			ctx.buffered_messages.extend(messages);
			break;
		}
	}
}

pub async fn send_or_buffer_tunnel_message(
	ctx: &mut EnvoyContext,
	msg: protocol::ToRivetTunnelMessage,
) {
	let failed = ws_send(
		&ctx.shared,
		protocol::ToRivet::ToRivetTunnelMessage(msg.clone()),
	)
	.await;
	if failed {
		ctx.buffered_messages.push(msg);
	}
}

async fn send_error_response(
	ctx: &EnvoyContext,
	connection_session: Option<u64>,
	gateway_id: protocol::GatewayId,
	request_id: protocol::RequestId,
	error_code: &str,
	message: &str,
	actor: Option<(&str, u32)>,
) {
	let code = error_code.strip_prefix("envoy.").unwrap_or(error_code);
	let mut error = serde_json::json!({
		"group": "envoy",
		"code": code,
		"message": message,
	});
	if let Some((actor_id, generation)) = actor {
		error["actor"] = serde_json::json!({
			"actorId": actor_id,
			"generation": generation,
		});
	}
	let body = serde_json::to_vec(&error).expect("serialize canonical HTTP error response");
	let mut headers = HashMap::new();
	headers.insert("x-rivet-error".to_string(), error_code.to_owned());
	headers.insert("content-type".to_string(), "application/json".to_owned());
	headers.insert("content-length".to_string(), body.len().to_string());

	let response = protocol::ToRivet::ToRivetTunnelMessage(protocol::ToRivetTunnelMessage {
		message_id: protocol::MessageId {
			gateway_id,
			request_id,
			message_index: 0,
		},
		message_kind: protocol::ToRivetTunnelMessageKind::ToRivetResponseStart(
			protocol::ToRivetResponseStart {
				status: 503,
				headers,
				body: Some(body),
				stream: false,
			},
		),
	});
	match connection_session {
		Some(session) => {
			let _ =
				crate::connection::ws_send_http_for_session(&ctx.shared, response, session).await;
		}
		None => {
			ws_send(&ctx.shared, response).await;
		}
	}
}