-
Notifications
You must be signed in to change notification settings - Fork 182
Expand file tree
/
Copy pathsqlite.rs
More file actions
669 lines (585 loc) · 17.2 KB
/
sqlite.rs
File metadata and controls
669 lines (585 loc) · 17.2 KB
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
use rivet_envoy_protocol as protocol;
use tokio::sync::oneshot;
use crate::connection::ws_send;
use crate::envoy::EnvoyContext;
use crate::kv::KV_EXPIRE_MS;
use crate::utils::{EnvoyShutdownError, RemoteSqliteIndeterminateResultError};
#[derive(Clone, Debug)]
pub enum SqliteRequest {
GetPages(protocol::SqliteGetPagesRequest),
Commit(protocol::SqliteCommitRequest),
}
pub enum SqliteResponse {
GetPages(protocol::SqliteGetPagesResponse),
Commit(protocol::SqliteCommitResponse),
}
#[derive(Clone, Debug)]
pub enum RemoteSqliteRequest {
Exec(protocol::SqliteExecRequest),
Execute(protocol::SqliteExecuteRequest),
}
#[derive(Debug)]
pub enum RemoteSqliteResponse {
Exec(protocol::SqliteExecResponse),
Execute(protocol::SqliteExecuteResponse),
}
impl RemoteSqliteRequest {
fn operation(&self) -> &'static str {
match self {
RemoteSqliteRequest::Exec(_) => "exec",
RemoteSqliteRequest::Execute(_) => "execute",
}
}
}
pub struct SqliteRequestEntry {
pub request: SqliteRequest,
pub response_tx: oneshot::Sender<anyhow::Result<SqliteResponse>>,
pub sent: bool,
pub timestamp: crate::time::Instant,
}
pub struct RemoteSqliteRequestEntry {
pub request: RemoteSqliteRequest,
pub response_tx: oneshot::Sender<anyhow::Result<RemoteSqliteResponse>>,
pub sent: bool,
pub timestamp: crate::time::Instant,
}
pub async fn handle_sqlite_request(
ctx: &mut EnvoyContext,
request: SqliteRequest,
response_tx: oneshot::Sender<anyhow::Result<SqliteResponse>>,
) {
let request_id = ctx.next_sqlite_request_id;
ctx.next_sqlite_request_id += 1;
let entry = SqliteRequestEntry {
request,
response_tx,
sent: false,
timestamp: crate::time::Instant::now(),
};
ctx.sqlite_requests.insert(request_id, entry);
let ws_available = {
let guard = ctx.shared.ws_tx.lock().await;
guard.is_some()
};
if ws_available {
send_single_sqlite_request(ctx, request_id).await;
}
}
pub async fn handle_remote_sqlite_request(
ctx: &mut EnvoyContext,
request: RemoteSqliteRequest,
response_tx: oneshot::Sender<anyhow::Result<RemoteSqliteResponse>>,
) {
let request_id = ctx.next_remote_sqlite_request_id;
ctx.next_remote_sqlite_request_id += 1;
let entry = RemoteSqliteRequestEntry {
request,
response_tx,
sent: false,
timestamp: crate::time::Instant::now(),
};
ctx.remote_sqlite_requests.insert(request_id, entry);
let ws_available = {
let guard = ctx.shared.ws_tx.lock().await;
guard.is_some()
};
if ws_available {
send_single_remote_sqlite_request(ctx, request_id).await;
}
}
pub async fn handle_sqlite_get_pages_response(
ctx: &mut EnvoyContext,
response: protocol::ToEnvoySqliteGetPagesResponse,
) {
handle_sqlite_response(
ctx,
response.request_id,
SqliteResponse::GetPages(response.data),
"sqlite_get_pages",
);
}
pub async fn handle_sqlite_commit_response(
ctx: &mut EnvoyContext,
response: protocol::ToEnvoySqliteCommitResponse,
) {
handle_sqlite_response(
ctx,
response.request_id,
SqliteResponse::Commit(response.data),
"sqlite_commit",
);
}
pub async fn handle_remote_sqlite_exec_response(
ctx: &mut EnvoyContext,
response: protocol::ToEnvoySqliteExecResponse,
) {
handle_remote_sqlite_response(
ctx,
response.request_id,
RemoteSqliteResponse::Exec(response.data),
"remote_sqlite_exec",
);
}
pub async fn handle_remote_sqlite_execute_response(
ctx: &mut EnvoyContext,
response: protocol::ToEnvoySqliteExecuteResponse,
) {
handle_remote_sqlite_response(
ctx,
response.request_id,
RemoteSqliteResponse::Execute(response.data),
"remote_sqlite_execute",
);
}
fn handle_sqlite_response(
ctx: &mut EnvoyContext,
request_id: u32,
response: SqliteResponse,
op: &str,
) {
let request = ctx.sqlite_requests.remove(&request_id);
if let Some(request) = request {
let _ = request.response_tx.send(Ok(response));
} else {
tracing::error!(
request_id,
op,
"received sqlite response for unknown request id"
);
}
}
fn handle_remote_sqlite_response(
ctx: &mut EnvoyContext,
request_id: u32,
response: RemoteSqliteResponse,
op: &str,
) {
let request = ctx.remote_sqlite_requests.remove(&request_id);
if let Some(request) = request {
let _ = request.response_tx.send(Ok(response));
} else {
tracing::error!(
request_id,
op,
"received remote sqlite response for unknown request id"
);
}
}
pub async fn send_single_sqlite_request(ctx: &mut EnvoyContext, request_id: u32) {
let request = ctx.sqlite_requests.get_mut(&request_id);
let Some(request) = request else { return };
if request.sent {
return;
}
let message =
match request.request.clone() {
SqliteRequest::GetPages(data) => protocol::ToRivet::ToRivetSqliteGetPagesRequest(
protocol::ToRivetSqliteGetPagesRequest { request_id, data },
),
SqliteRequest::Commit(data) => protocol::ToRivet::ToRivetSqliteCommitRequest(
protocol::ToRivetSqliteCommitRequest { request_id, data },
),
};
ws_send(&ctx.shared, message).await;
if let Some(request) = ctx.sqlite_requests.get_mut(&request_id) {
request.sent = true;
request.timestamp = crate::time::Instant::now();
}
}
pub async fn send_single_remote_sqlite_request(ctx: &mut EnvoyContext, request_id: u32) {
let request = ctx.remote_sqlite_requests.get_mut(&request_id);
let Some(request) = request else { return };
if request.sent {
return;
}
let message = remote_sqlite_request_to_message(request_id, request.request.clone());
ws_send(&ctx.shared, message).await;
if let Some(request) = ctx.remote_sqlite_requests.get_mut(&request_id) {
request.sent = true;
request.timestamp = crate::time::Instant::now();
}
}
pub fn remote_sqlite_request_to_message(
request_id: u32,
request: RemoteSqliteRequest,
) -> protocol::ToRivet {
match request {
RemoteSqliteRequest::Exec(data) => {
protocol::ToRivet::ToRivetSqliteExecRequest(protocol::ToRivetSqliteExecRequest {
request_id,
data,
})
}
RemoteSqliteRequest::Execute(data) => {
protocol::ToRivet::ToRivetSqliteExecuteRequest(protocol::ToRivetSqliteExecuteRequest {
request_id,
data,
})
}
}
}
pub async fn process_unsent_sqlite_requests(ctx: &mut EnvoyContext) {
let ws_available = {
let guard = ctx.shared.ws_tx.lock().await;
guard.is_some()
};
if !ws_available {
return;
}
let unsent: Vec<u32> = ctx
.sqlite_requests
.iter()
.filter(|(_, req)| !req.sent)
.map(|(id, _)| *id)
.collect();
for request_id in unsent {
send_single_sqlite_request(ctx, request_id).await;
}
}
pub async fn process_unsent_remote_sqlite_requests(ctx: &mut EnvoyContext) {
let ws_available = {
let guard = ctx.shared.ws_tx.lock().await;
guard.is_some()
};
if !ws_available {
return;
}
let unsent: Vec<u32> = ctx
.remote_sqlite_requests
.iter()
.filter(|(_, req)| !req.sent)
.map(|(id, _)| *id)
.collect();
for request_id in unsent {
send_single_remote_sqlite_request(ctx, request_id).await;
}
}
pub fn cleanup_old_sqlite_requests(ctx: &mut EnvoyContext) {
let now = crate::time::Instant::now();
let mut to_delete = Vec::new();
for (request_id, request) in &ctx.sqlite_requests {
if now.duration_since(request.timestamp).as_millis() > KV_EXPIRE_MS as u128 {
to_delete.push(*request_id);
}
}
for request_id in to_delete {
if let Some(request) = ctx.sqlite_requests.remove(&request_id) {
let _ = request
.response_tx
.send(Err(anyhow::anyhow!("sqlite request timed out")));
}
}
}
pub fn cleanup_old_remote_sqlite_requests(ctx: &mut EnvoyContext) {
let now = crate::time::Instant::now();
let mut to_delete = Vec::new();
for (request_id, request) in &ctx.remote_sqlite_requests {
if now.duration_since(request.timestamp).as_millis() > KV_EXPIRE_MS as u128 {
to_delete.push(*request_id);
}
}
for request_id in to_delete {
if let Some(request) = ctx.remote_sqlite_requests.remove(&request_id) {
let _ = request
.response_tx
.send(Err(anyhow::anyhow!("remote sqlite request timed out")));
}
}
}
pub fn fail_sqlite_requests_with_shutdown(ctx: &mut EnvoyContext) {
for (_id, request) in ctx.sqlite_requests.drain() {
let _ = request
.response_tx
.send(Err(anyhow::anyhow!(EnvoyShutdownError)));
}
}
pub fn fail_remote_sqlite_requests_with_shutdown(ctx: &mut EnvoyContext) {
for (_id, request) in ctx.remote_sqlite_requests.drain() {
let _ = request
.response_tx
.send(Err(anyhow::anyhow!(EnvoyShutdownError)));
}
}
pub fn fail_sent_remote_sqlite_requests_with_indeterminate_result(ctx: &mut EnvoyContext) {
let request_ids: Vec<u32> = ctx
.remote_sqlite_requests
.iter()
.filter(|(_, request)| request.sent)
.map(|(request_id, _)| *request_id)
.collect();
for request_id in request_ids {
if let Some(request) = ctx.remote_sqlite_requests.remove(&request_id) {
let operation = request.request.operation();
tracing::warn!(
request_id,
operation,
"remote sqlite response lost after websocket disconnect"
);
let _ = request.response_tx.send(Err(anyhow::anyhow!(
RemoteSqliteIndeterminateResultError { operation }
)));
}
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::Arc;
use vbare::OwnedVersionedData;
use super::*;
use crate::config::{
BoxFuture, EnvoyCallbacks, EnvoyConfig, HttpRequest, HttpResponse, WebSocketHandler,
WebSocketSender,
};
use crate::context::{SharedContext, WsTxMessage};
use crate::handle::EnvoyHandle;
use crate::utils::{BufferMap, RemoteSqliteIndeterminateResultError};
struct IdleCallbacks;
impl EnvoyCallbacks for IdleCallbacks {
fn on_actor_start(
&self,
_handle: EnvoyHandle,
_actor_id: String,
_generation: u32,
_config: protocol::ActorConfig,
_preloaded_kv: Option<protocol::PreloadedKv>,
) -> BoxFuture<anyhow::Result<()>> {
Box::pin(async { Ok(()) })
}
fn on_shutdown(&self) {}
fn fetch(
&self,
_handle: EnvoyHandle,
_actor_id: String,
_gateway_id: protocol::GatewayId,
_request_id: protocol::RequestId,
_request: HttpRequest,
) -> BoxFuture<anyhow::Result<HttpResponse>> {
Box::pin(async { anyhow::bail!("fetch should not be called in sqlite tests") })
}
fn websocket(
&self,
_handle: EnvoyHandle,
_actor_id: String,
_gateway_id: protocol::GatewayId,
_request_id: protocol::RequestId,
_request: HttpRequest,
_path: String,
_headers: HashMap<String, String>,
_is_hibernatable: bool,
_is_restoring_hibernatable: bool,
_sender: WebSocketSender,
) -> BoxFuture<anyhow::Result<WebSocketHandler>> {
Box::pin(async { anyhow::bail!("websocket should not be called in sqlite tests") })
}
fn can_hibernate(
&self,
_actor_id: &str,
_gateway_id: &protocol::GatewayId,
_request_id: &protocol::RequestId,
_request: &HttpRequest,
) -> BoxFuture<anyhow::Result<bool>> {
Box::pin(async { Ok(false) })
}
}
fn new_envoy_context() -> EnvoyContext {
let (envoy_tx, _envoy_rx) = tokio::sync::mpsc::unbounded_channel();
let shared = Arc::new(SharedContext {
config: EnvoyConfig {
version: 1,
endpoint: "http://127.0.0.1:1".to_string(),
token: None,
namespace: "test".to_string(),
pool_name: "test".to_string(),
prepopulate_actor_names: HashMap::new(),
metadata: None,
not_global: true,
debug_latency_ms: None,
callbacks: Arc::new(IdleCallbacks),
},
envoy_key: "test-envoy".to_string(),
envoy_tx,
actors: Arc::new(std::sync::Mutex::new(HashMap::new())),
actors_notify: Arc::new(tokio::sync::Notify::new()),
live_tunnel_requests: Arc::new(std::sync::Mutex::new(HashMap::new())),
pending_hibernation_restores: Arc::new(std::sync::Mutex::new(HashMap::new())),
ws_tx: Arc::new(tokio::sync::Mutex::new(
None::<tokio::sync::mpsc::UnboundedSender<WsTxMessage>>,
)),
protocol_metadata: Arc::new(tokio::sync::Mutex::new(None)),
shutting_down: std::sync::atomic::AtomicBool::new(false),
stopped_tx: tokio::sync::watch::channel(true).0,
});
EnvoyContext {
shared,
shutting_down: false,
actors: HashMap::new(),
buffered_actor_messages: HashMap::new(),
kv_requests: HashMap::new(),
next_kv_request_id: 0,
sqlite_requests: HashMap::new(),
next_sqlite_request_id: 0,
remote_sqlite_requests: HashMap::new(),
next_remote_sqlite_request_id: 0,
request_to_actor: BufferMap::new(),
buffered_messages: Vec::new(),
processed_command_idx: HashMap::new(),
}
}
fn exec_request() -> protocol::SqliteExecRequest {
protocol::SqliteExecRequest {
namespace_id: "ns".to_string(),
actor_id: "actor".to_string(),
generation: 1,
sql: "select 1".to_string(),
}
}
fn execute_request() -> protocol::SqliteExecuteRequest {
protocol::SqliteExecuteRequest {
namespace_id: "ns".to_string(),
actor_id: "actor".to_string(),
generation: 1,
sql: "select ?".to_string(),
params: Some(vec![protocol::SqliteBindParam::SqliteValueInteger(
protocol::SqliteValueInteger { value: 1 },
)]),
}
}
#[tokio::test]
async fn remote_sqlite_exec_response_matches_pending_request() {
let mut ctx = new_envoy_context();
let (tx, rx) = oneshot::channel();
handle_remote_sqlite_request(&mut ctx, RemoteSqliteRequest::Exec(exec_request()), tx).await;
assert!(ctx.remote_sqlite_requests.contains_key(&0));
handle_remote_sqlite_exec_response(
&mut ctx,
protocol::ToEnvoySqliteExecResponse {
request_id: 0,
data: protocol::SqliteExecResponse::SqliteExecOk(protocol::SqliteExecOk {
result: protocol::SqliteQueryResult {
columns: vec!["one".to_string()],
rows: vec![vec![protocol::SqliteColumnValue::SqliteValueInteger(
protocol::SqliteValueInteger { value: 1 },
)]],
},
}),
},
)
.await;
let response = rx
.await
.expect("response sender should complete")
.expect("response should succeed");
match response {
RemoteSqliteResponse::Exec(protocol::SqliteExecResponse::SqliteExecOk(ok)) => {
assert_eq!(ok.result.columns, vec!["one"]);
assert_eq!(ok.result.rows.len(), 1);
}
_ => panic!("unexpected response"),
}
assert!(ctx.remote_sqlite_requests.is_empty());
}
#[test]
fn remote_sqlite_requests_reject_protocol_v3_serialization() {
let requests = vec![
RemoteSqliteRequest::Exec(exec_request()),
RemoteSqliteRequest::Execute(execute_request()),
];
for request in requests {
let message = remote_sqlite_request_to_message(7, request);
let err = protocol::versioned::ToRivet::wrap_latest(message)
.serialize(3)
.expect_err("remote sqlite requests should require protocol v4");
let compatibility = err
.downcast_ref::<protocol::versioned::ProtocolCompatibilityError>()
.expect("error should be a protocol compatibility error");
assert_eq!(
compatibility.feature,
protocol::versioned::ProtocolCompatibilityFeature::RemoteSqliteExecution
);
assert_eq!(compatibility.required_version, 4);
assert_eq!(compatibility.target_version, 3);
}
}
#[tokio::test]
async fn remote_sqlite_shutdown_cleanup_fails_pending_requests() {
let mut ctx = new_envoy_context();
let (tx, rx) = oneshot::channel();
handle_remote_sqlite_request(
&mut ctx,
RemoteSqliteRequest::Execute(execute_request()),
tx,
)
.await;
fail_remote_sqlite_requests_with_shutdown(&mut ctx);
let err = rx
.await
.expect("response sender should complete")
.expect_err("pending request should fail during shutdown");
assert!(err.downcast_ref::<EnvoyShutdownError>().is_some());
assert!(ctx.remote_sqlite_requests.is_empty());
}
#[tokio::test]
async fn sent_remote_sqlite_request_fails_indeterminate_on_disconnect() {
let mut ctx = new_envoy_context();
let (ws_tx, mut ws_rx) = tokio::sync::mpsc::unbounded_channel();
*ctx.shared.ws_tx.lock().await = Some(ws_tx);
let (tx, rx) = oneshot::channel();
handle_remote_sqlite_request(
&mut ctx,
RemoteSqliteRequest::Execute(execute_request()),
tx,
)
.await;
assert!(matches!(ws_rx.recv().await, Some(WsTxMessage::Send(_))));
assert!(
ctx.remote_sqlite_requests
.get(&0)
.expect("request should be pending")
.sent
);
fail_sent_remote_sqlite_requests_with_indeterminate_result(&mut ctx);
let err = rx
.await
.expect("response sender should complete")
.expect_err("sent write should fail indeterminate on disconnect");
let indeterminate = err
.downcast_ref::<RemoteSqliteIndeterminateResultError>()
.expect("error should describe indeterminate remote sqlite result");
assert_eq!(indeterminate.operation, "execute");
assert!(ctx.remote_sqlite_requests.is_empty());
}
#[tokio::test]
async fn unsent_remote_sqlite_request_survives_disconnect_and_sends_on_reconnect() {
let mut ctx = new_envoy_context();
let (tx, mut rx) = oneshot::channel();
handle_remote_sqlite_request(
&mut ctx,
RemoteSqliteRequest::Execute(execute_request()),
tx,
)
.await;
assert!(
!ctx.remote_sqlite_requests
.get(&0)
.expect("request should be pending")
.sent
);
fail_sent_remote_sqlite_requests_with_indeterminate_result(&mut ctx);
assert!(matches!(
rx.try_recv(),
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
));
assert!(ctx.remote_sqlite_requests.contains_key(&0));
let (ws_tx, mut ws_rx) = tokio::sync::mpsc::unbounded_channel();
*ctx.shared.ws_tx.lock().await = Some(ws_tx);
process_unsent_remote_sqlite_requests(&mut ctx).await;
assert!(matches!(ws_rx.recv().await, Some(WsTxMessage::Send(_))));
assert!(
ctx.remote_sqlite_requests
.get(&0)
.expect("request should still be pending")
.sent
);
}
}