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
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter};
use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::bail;
use chrono::{DateTime, Utc};
use tokio::sync::{mpsc, oneshot, watch};
use tracing::error;
use uuid::Uuid;
use mz_build_info::BuildInfo;
use mz_ore::collections::CollectionExt;
use mz_ore::id_gen::IdAllocator;
use mz_ore::now::{to_datetime, EpochMillis, NowFn};
use mz_ore::task::{AbortOnDropHandle, JoinHandleExt};
use mz_ore::thread::JoinOnDropHandle;
use mz_repr::{GlobalId, Row, ScalarType};
use mz_sql::ast::{Raw, Statement};
use mz_sql::session::user::{User, INTROSPECTION_USER};
use crate::command::{Canceled, Command, ExecuteResponse, Response, StartupResponse};
use crate::error::AdapterError;
use crate::metrics::Metrics;
use crate::session::{EndTransactionAction, PreparedStatement, Session, TransactionId};
use crate::PeekResponseUnary;
pub type ConnectionId = u32;
pub struct Handle {
pub(crate) session_id: Uuid,
pub(crate) start_instant: Instant,
pub(crate) _thread: JoinOnDropHandle<()>,
}
impl Handle {
pub fn session_id(&self) -> Uuid {
self.session_id
}
pub fn start_instant(&self) -> Instant {
self.start_instant
}
}
#[derive(Debug, Clone)]
pub struct Client {
build_info: &'static BuildInfo,
inner_cmd_tx: mpsc::UnboundedSender<Command>,
id_alloc: Arc<IdAllocator<ConnectionId>>,
now: NowFn,
metrics: Metrics,
}
impl Client {
pub(crate) fn new(
build_info: &'static BuildInfo,
cmd_tx: mpsc::UnboundedSender<Command>,
metrics: Metrics,
now: NowFn,
) -> Client {
Client {
build_info,
inner_cmd_tx: cmd_tx,
id_alloc: Arc::new(IdAllocator::new(1, 1 << 16)),
now,
metrics,
}
}
pub fn new_conn(&self) -> Result<ConnClient, AdapterError> {
Ok(ConnClient {
build_info: self.build_info,
conn_id: self
.id_alloc
.alloc()
.ok_or(AdapterError::IdExhaustionError)?,
inner: self.clone(),
})
}
pub async fn introspection_execute_one(&self, sql: &str) -> Result<Vec<Row>, anyhow::Error> {
let conn_client = self.new_conn()?;
let session = conn_client.new_session(INTROSPECTION_USER.clone());
let (mut session_client, _) = conn_client.startup(session).await?;
let stmts = mz_sql::parse::parse(sql)?;
if stmts.len() != 1 {
bail!("must supply exactly one query");
}
let stmt = stmts.into_element();
const EMPTY_PORTAL: &str = "";
session_client.start_transaction(Some(1))?;
session_client
.declare(EMPTY_PORTAL.into(), stmt, vec![])
.await?;
match session_client.execute(EMPTY_PORTAL.into()).await? {
ExecuteResponse::SendingRows { future, span: _ } => match future.await {
PeekResponseUnary::Rows(rows) => Ok(rows),
PeekResponseUnary::Canceled => bail!("query canceled"),
PeekResponseUnary::Error(e) => bail!(e),
},
r => bail!("unsupported response type: {r:?}"),
}
}
pub fn metrics(&self) -> &Metrics {
&self.metrics
}
fn send(&self, cmd: Command) {
self.inner_cmd_tx
.send(cmd)
.expect("coordinator unexpectedly gone");
}
}
#[derive(Debug)]
pub struct ConnClient {
build_info: &'static BuildInfo,
conn_id: ConnectionId,
inner: Client,
}
impl ConnClient {
pub fn new_session(&self, user: User) -> Session {
Session::new(self.build_info, self.conn_id, user)
}
pub fn conn_id(&self) -> ConnectionId {
self.conn_id
}
#[tracing::instrument(level = "debug", skip(self))]
pub async fn startup(
self,
session: Session,
) -> Result<(SessionClient, StartupResponse), AdapterError> {
let (cancel_tx, cancel_rx) = watch::channel(Canceled::NotCanceled);
let cancel_tx = Arc::new(cancel_tx);
let mut client = SessionClient {
inner: Some(self),
session: Some(session),
cancel_tx: Arc::clone(&cancel_tx),
cancel_rx,
timeouts: Timeout::new(),
};
let response = client
.send(|tx, session| Command::Startup {
session,
cancel_tx,
tx,
})
.await;
match response {
Ok(response) => Ok((client, response)),
Err(e) => {
client.session.take();
Err(e)
}
}
}
pub fn cancel_request(&mut self, conn_id: ConnectionId, secret_key: u32) {
self.inner.send(Command::CancelRequest {
conn_id,
secret_key,
});
}
async fn send<T, F>(&mut self, f: F) -> T
where
F: FnOnce(oneshot::Sender<T>) -> Command,
{
let (tx, rx) = oneshot::channel();
self.inner.send(f(tx));
rx.await.expect("coordinator unexpectedly canceled request")
}
}
impl Drop for ConnClient {
fn drop(&mut self) {
self.inner.id_alloc.free(self.conn_id);
}
}
pub struct SessionClient {
inner: Option<ConnClient>,
session: Option<Session>,
cancel_tx: Arc<watch::Sender<Canceled>>,
cancel_rx: watch::Receiver<Canceled>,
timeouts: Timeout,
}
impl SessionClient {
pub fn canceled(&self) -> impl Future<Output = ()> + Send {
let mut cancel_rx = self.cancel_rx.clone();
async move {
loop {
let _ = cancel_rx.changed().await;
if let Canceled::Canceled = *cancel_rx.borrow() {
return;
}
}
}
}
pub fn reset_canceled(&mut self) {
let _ = self.cancel_tx.send(Canceled::NotCanceled);
}
pub async fn get_prepared_statement(
&mut self,
name: &str,
) -> Result<&PreparedStatement, AdapterError> {
self.send(|tx, session| Command::VerifyPreparedStatement {
name: name.to_string(),
session,
tx,
})
.await?;
Ok(self
.session()
.get_prepared_statement_unverified(name)
.expect("must exist"))
}
pub async fn describe(
&mut self,
name: String,
stmt: Option<Statement<Raw>>,
param_types: Vec<Option<ScalarType>>,
) -> Result<(), AdapterError> {
self.send(|tx, session| Command::Describe {
name,
stmt,
param_types,
session,
tx,
})
.await
}
pub async fn declare(
&mut self,
name: String,
stmt: Statement<Raw>,
param_types: Vec<Option<ScalarType>>,
) -> Result<(), AdapterError> {
self.send(|tx, session| Command::Declare {
name,
stmt,
param_types,
session,
tx,
})
.await
.map(|_| ())
}
#[tracing::instrument(level = "debug", skip(self))]
pub async fn execute(&mut self, portal_name: String) -> Result<ExecuteResponse, AdapterError> {
self.send(|tx, session| Command::Execute {
portal_name,
session,
tx,
span: tracing::Span::current(),
})
.await
}
fn now(&self) -> EpochMillis {
(self.inner().inner.now)()
}
fn now_datetime(&self) -> DateTime<Utc> {
to_datetime(self.now())
}
pub fn start_transaction(&mut self, implicit: Option<usize>) -> Result<(), AdapterError> {
let session = self.session.take().expect("session invariant violated");
let now = self.now_datetime();
let (session, result) = match implicit {
None => session.start_transaction(now, None, None),
Some(stmts) => (session.start_transaction_implicit(now, stmts), Ok(())),
};
self.session = Some(session);
result
}
pub fn cancel_request(&mut self, conn_id: ConnectionId, secret_key: u32) {
self.inner_mut().cancel_request(conn_id, secret_key)
}
pub async fn end_transaction(
&mut self,
action: EndTransactionAction,
) -> Result<ExecuteResponse, AdapterError> {
self.send(|tx, session| Command::Commit {
action,
session,
tx,
})
.await
}
pub fn fail_transaction(&mut self) {
let session = self.session.take().expect("session invariant violated");
let session = session.fail_transaction();
self.session = Some(session);
}
pub async fn dump_catalog(&mut self) -> Result<String, AdapterError> {
self.send(|tx, session| Command::DumpCatalog { session, tx })
.await
}
pub async fn insert_rows(
&mut self,
id: GlobalId,
columns: Vec<usize>,
rows: Vec<Row>,
) -> Result<ExecuteResponse, AdapterError> {
self.send(|tx, session| Command::CopyRows {
id,
columns,
rows,
session,
tx,
})
.await
}
pub async fn get_system_vars(&mut self) -> Result<BTreeMap<String, String>, AdapterError> {
self.send(|tx, session| Command::GetSystemVars { session, tx })
.await
}
pub async fn set_system_vars(
&mut self,
vars: BTreeMap<String, String>,
) -> Result<(), AdapterError> {
self.send(|tx, session| Command::SetSystemVars { vars, session, tx })
.await
}
pub async fn terminate(&mut self) {
let res = self
.send(|tx, session| Command::Terminate {
session,
tx: Some(tx),
})
.await;
if let Err(e) = res {
error!("Unable to terminate session: {e:?}");
}
self.inner = None;
}
pub fn session(&mut self) -> &mut Session {
self.session.as_mut().expect("session invariant violated")
}
pub fn inner(&self) -> &ConnClient {
self.inner.as_ref().expect("inner invariant violated")
}
pub fn inner_mut(&mut self) -> &mut ConnClient {
self.inner.as_mut().expect("inner invariant violated")
}
async fn send<T, F>(&mut self, f: F) -> Result<T, AdapterError>
where
F: FnOnce(oneshot::Sender<Response<T>>, Session) -> Command,
{
let session = self.session.take().expect("session invariant violated");
let mut typ = None;
let res = self
.inner_mut()
.send(|tx| {
let cmd = f(tx, session);
match cmd {
Command::Declare { .. } => typ = Some("declare"),
Command::Execute { .. } => typ = Some("execute"),
Command::Startup { .. }
| Command::Describe { .. }
| Command::VerifyPreparedStatement { .. }
| Command::Commit { .. }
| Command::CancelRequest { .. }
| Command::DumpCatalog { .. }
| Command::CopyRows { .. }
| Command::GetSystemVars { .. }
| Command::SetSystemVars { .. }
| Command::Terminate { .. } => {}
};
cmd
})
.await;
let status = if res.result.is_ok() {
"success"
} else {
"error"
};
if let Some(typ) = typ {
self.inner()
.inner
.metrics
.commands
.with_label_values(&[typ, status])
.inc();
}
self.session = Some(res.session);
res.result
}
pub fn add_idle_in_transaction_session_timeout(&mut self) {
let session = self.session();
let timeout_dur = session.vars().idle_in_transaction_session_timeout();
if !timeout_dur.is_zero() {
let timeout_dur = timeout_dur.clone();
if let Some(txn) = session.transaction().inner() {
let txn_id = txn.id.clone();
let timeout = TimeoutType::IdleInTransactionSession(txn_id);
self.timeouts.add_timeout(timeout, timeout_dur);
}
}
}
pub fn remove_idle_in_transaction_session_timeout(&mut self) {
let session = self.session();
if let Some(txn) = session.transaction().inner() {
let txn_id = txn.id.clone();
self.timeouts
.remove_timeout(&TimeoutType::IdleInTransactionSession(txn_id));
}
}
pub async fn recv_timeout(&mut self) -> Option<TimeoutType> {
self.timeouts.recv().await
}
}
impl Drop for SessionClient {
fn drop(&mut self) {
if let Some(session) = self.session.take() {
if let Some(inner) = &self.inner {
inner.inner.send(Command::Terminate { session, tx: None })
}
}
}
}
#[derive(Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
pub enum TimeoutType {
IdleInTransactionSession(TransactionId),
}
impl Display for TimeoutType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
TimeoutType::IdleInTransactionSession(txn_id) => {
writeln!(f, "Idle in transaction session for transaction '{txn_id}'")
}
}
}
}
impl From<TimeoutType> for AdapterError {
fn from(timeout: TimeoutType) -> Self {
match timeout {
TimeoutType::IdleInTransactionSession(_) => {
AdapterError::IdleInTransactionSessionTimeout
}
}
}
}
struct Timeout {
tx: mpsc::UnboundedSender<TimeoutType>,
rx: mpsc::UnboundedReceiver<TimeoutType>,
active_timeouts: BTreeMap<TimeoutType, AbortOnDropHandle<()>>,
}
impl Timeout {
fn new() -> Self {
let (tx, rx) = mpsc::unbounded_channel();
Timeout {
tx,
rx,
active_timeouts: BTreeMap::new(),
}
}
async fn recv(&mut self) -> Option<TimeoutType> {
self.rx.recv().await
}
fn add_timeout(&mut self, timeout: TimeoutType, duration: Duration) {
let tx = self.tx.clone();
let timeout_key = timeout.clone();
let handle = mz_ore::task::spawn(|| format!("{timeout_key}"), async move {
tokio::time::sleep(duration).await;
let _ = tx.send(timeout);
})
.abort_on_drop();
self.active_timeouts.insert(timeout_key, handle);
}
fn remove_timeout(&mut self, timeout: &TimeoutType) {
self.active_timeouts.remove(timeout);
let mut timeouts = Vec::new();
while let Ok(pending_timeout) = self.rx.try_recv() {
if timeout != &pending_timeout {
timeouts.push(pending_timeout);
}
}
for pending_timeout in timeouts {
self.tx.send(pending_timeout).expect("rx is in this struct");
}
}
}