picodata-driver 4.0.0

A native asyncronous cluster-aware Picodata client
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
use std::sync::Arc;

use tokio::{
    sync::oneshot::{Receiver, channel},
    task::JoinHandle,
};
use tokio_util::sync::CancellationToken;

use crate::{Error, accessor::Accessor, config::Config, topology::Topology};

/// Receiver to recv topology init result.
pub(crate) type TopologyInitReceiver = Receiver<Result<(), Error>>;

/// Discovers cluster with provided interval to check if
/// there are new instances added or some instances removed.
pub(crate) struct Discovery {
    /// Accessor to a pool.
    accessor: Arc<Accessor>,
    /// Config to create new pools.
    config: Config,
    /// Token which is checked to stop underlying discovery task.
    token: CancellationToken,
}

impl Discovery {
    /// SQL query to fetch cluster topology from picodata system tables, one row per address.
    const TOPOLOGY_QUERY: &str = r"
    SELECT ppa.address, pi.current_state, pt.name AS tier, pi.name AS instance_name,
           pi.replicaset_name, pt.bucket_count,
           pr.uuid AS replicaset_uuid, pr.current_master_name,
           pi.raft_id, pi.uuid AS instance_uuid, ppa.connection_type
    FROM _pico_tier AS pt
    LEFT JOIN _pico_instance AS pi ON pi.tier = pt.name
    LEFT JOIN _pico_peer_address AS ppa ON ppa.raft_id = pi.raft_id
    LEFT JOIN _pico_replicaset AS pr ON pr.name = pi.replicaset_name
    ";

    /// Creates a new instance of `Manager`.
    ///
    /// # Parameters
    ///
    /// - `accessor`: An accessor to pool of connections.
    /// - `config`: A config to create new pools.
    /// - `token`: A token to cancel task.
    ///
    /// # Returns
    ///
    /// An instance of `Discovery`.
    pub(crate) fn new(accessor: Arc<Accessor>, config: Config, token: CancellationToken) -> Self {
        Self {
            accessor,
            config,
            token,
        }
    }

    /// Scans cluster instances.
    ///
    /// This function does check following conditions:
    ///
    /// - Instances were added. In this case new connection pools will be added.
    /// - Instances changed their state. If instance state is online - new pool will be added. If state is offline - instance pool will be removed.
    ///
    /// # Errors
    ///
    /// - Any [`Error`] returned by inner driver.
    ///
    /// # Returns
    ///
    /// A unit on success.
    /// Fetches topology and bucket ranges, merges into current, synchronizes pools.
    async fn refresh(&self, client: &pg::Client) -> Result<(), Error> {
        let excluded_tiers = self.config.excluded_tiers.clone().unwrap_or_default();
        let (query, params): (String, Vec<&(dyn pg::types::ToSql + Sync)>) =
            if excluded_tiers.is_empty() {
                (Self::TOPOLOGY_QUERY.to_string(), Vec::new())
            } else {
                let placeholders = (1..=excluded_tiers.len())
                    .map(|i| format!("${i}"))
                    .collect::<Vec<String>>()
                    .join(", ");
                (
                    format!(
                        "{} WHERE pt.name NOT IN ({placeholders})",
                        Self::TOPOLOGY_QUERY
                    ),
                    excluded_tiers
                        .iter()
                        .map(|tier| tier as &(dyn pg::types::ToSql + Sync))
                        .collect(),
                )
            };
        let topology_rows = client.query(&query, &params).await.inspect_err(|e| {
            log::error!("failed to query topology: {e}");
        })?;

        let tiers: std::collections::HashSet<&str> =
            topology_rows.iter().map(|row| row.get("tier")).collect();
        let mut bucket_rows = Vec::new();
        for tier in tiers {
            match client.query_one("SELECT _pico_bucket($1)", &[&tier]).await {
                Ok(row) => bucket_rows.push(row),
                Err(e) => log::error!("failed to query buckets of tier {tier}: {e}"),
            }
        }

        let incoming = Topology::from((topology_rows, bucket_rows));
        let config = self.config.clone();
        let mut guard = self.accessor.write().await;
        guard.apply_topology(incoming);
        guard.synchronize(|inst| Arc::new(build_pool(&config.clone_for(inst))));
        Ok(())
    }

    /// Runs refresh using any available pooled connection.
    async fn once(&self) -> Result<(), Error> {
        let guard = self.accessor.read().await;
        let pools: Vec<_> = guard.active_pools().cloned().collect();
        drop(guard);

        for pool in &pools {
            match pool.get().await {
                Ok(client) => return self.refresh(&client).await,
                Err(e) => {
                    log::debug!("discovery: pool unavailable, trying next: {e}");
                }
            }
        }

        Err(Error::IO(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "discovery: all pools unavailable",
        )))
    }

    /// Starts new tokio task which discovers cluster each time interval is reached.
    ///
    /// # Returns
    ///
    /// A `JoinHandle` for running tokio task and topology init receiver.
    pub(crate) fn start(self) -> (JoinHandle<()>, TopologyInitReceiver) {
        let (sender, receiver) = channel();
        let handle = tokio::spawn(async move {
            // First refresh using a temporary deadpool pool (it spawns Connection internally).
            let init = async {
                let pool = build_pool(&self.config);
                let client = pool.get().await.map_err(Error::PostgresPool)?;
                self.refresh(&client).await
            };
            let Some(init_result) = self.token.run_until_cancelled(init).await else {
                return;
            };

            if sender.send(init_result).is_err() {
                return;
            }
            let mut ticker = tokio::time::interval(self.config.discorery_interval);
            loop {
                let refresh = async {
                    ticker.tick().await;
                    self.once().await
                };
                if self.token.run_until_cancelled(refresh).await.is_none() {
                    return;
                }
            }
        });
        (handle, receiver)
    }
}

/// Creates a deadpool connection pool from config (handles TLS if enabled).
fn build_pool(cfg: &Config) -> pgpool::Pool {
    #[cfg(feature = "tls")]
    let mgr = match crate::tls::connector(cfg) {
        Ok(Some(tls)) => pgpool::Manager::new(cfg.postgres.clone(), tls),
        _ => pgpool::Manager::new(cfg.postgres.clone(), pg::NoTls),
    };
    #[cfg(not(feature = "tls"))]
    let mgr = pgpool::Manager::new(cfg.postgres.clone(), pg::NoTls);

    pgpool::Pool::builder(mgr)
        .max_size(cfg.pool_max_size)
        .build()
        .expect("building new deadpool should not fail")
}

#[cfg(test)]
mod tests {
    use bytes::{BufMut, BytesMut};
    use tokio::{
        io::{AsyncReadExt, AsyncWriteExt},
        net::{TcpListener, TcpStream},
        time::{Duration, timeout},
    };

    use super::*;
    use crate::{pool::Pool, strategy::RoundRobin};

    async fn read_startup(socket: &mut TcpStream) {
        let len = socket.read_u32().await.expect("startup length");
        let mut payload = vec![0; usize::try_from(len - 4).expect("startup size")];
        socket.read_exact(&mut payload).await.expect("startup body");
    }

    fn message(output: &mut Vec<u8>, tag: u8, body: &[u8]) {
        output.push(tag);
        output.extend_from_slice(
            &u32::try_from(body.len() + 4)
                .expect("message size")
                .to_be_bytes(),
        );
        output.extend_from_slice(body);
    }

    async fn initialize_topology(listener: &TcpListener) -> Vec<TcpStream> {
        let (mut socket, _) = listener.accept().await.expect("initial discovery socket");
        read_startup(&mut socket).await;
        let mut output = Vec::new();
        message(&mut output, b'R', &0_u32.to_be_bytes());
        message(&mut output, b'Z', b"I");
        socket.write_all(&output).await.expect("authentication");

        let address = listener.local_addr().expect("listener address").to_string();
        let topology_columns = [
            ("address", 25, address.into_bytes()),
            ("current_state", 114, br#"["Online", 1]"#.to_vec()),
            ("tier", 25, Vec::new()),
            ("instance_name", 25, b"instance".to_vec()),
            ("replicaset_name", 25, b"replicaset".to_vec()),
            ("bucket_count", 20, 1_i64.to_be_bytes().to_vec()),
            (
                "replicaset_uuid",
                25,
                uuid::Uuid::nil().to_string().into_bytes(),
            ),
            ("current_master_name", 25, b"instance".to_vec()),
            ("raft_id", 20, 1_i64.to_be_bytes().to_vec()),
            (
                "instance_uuid",
                25,
                uuid::Uuid::nil().to_string().into_bytes(),
            ),
            ("connection_type", 25, b"pgproto".to_vec()),
        ];
        let bucket_columns = [(
            "_pico_bucket",
            114,
            br#"[{"tier_name":"","bucket_id_start":1,"bucket_id_end":1,"current_replicaset_uuid":"00000000-0000-0000-0000-000000000000"}]"#
                .to_vec(),
        )];

        for columns in [&topology_columns[..], &bucket_columns[..]] {
            let mut description = BytesMut::new();
            let mut row = BytesMut::new();
            description.put_u16(u16::try_from(columns.len()).expect("column count"));
            row.put_u16(u16::try_from(columns.len()).expect("column count"));
            for (name, oid, value) in columns {
                description.extend_from_slice(name.as_bytes());
                description.put_u8(0);
                description.put_u32(0);
                description.put_u16(0);
                description.put_u32(*oid);
                description.put_i16(-1);
                description.put_i32(-1);
                description.put_u16(1);
                row.put_u32(u32::try_from(value.len()).expect("value size"));
                row.extend_from_slice(value);
            }

            let mut placeholders = 0_usize;
            loop {
                let tag = socket.read_u8().await.expect("query message tag");
                let len = socket.read_u32().await.expect("query message length");
                let mut body = vec![0; usize::try_from(len - 4).expect("query size")];
                socket.read_exact(&mut body).await.expect("query body");
                output.clear();
                match tag {
                    b'P' => {
                        // Every placeholder of the parsed statement is a text parameter.
                        placeholders = body.iter().filter(|&&byte| byte == b'$').count();
                        message(&mut output, b'1', &[]);
                    }
                    b'D' => {
                        let mut parameter_description = BytesMut::new();
                        parameter_description
                            .put_u16(u16::try_from(placeholders).expect("placeholder count"));
                        for _ in 0..placeholders {
                            parameter_description.put_u32(25);
                        }
                        message(&mut output, b't', &parameter_description);
                        message(&mut output, b'T', &description);
                    }
                    b'B' => message(&mut output, b'2', &[]),
                    b'E' => {
                        message(&mut output, b'D', &row);
                        message(&mut output, b'C', b"SELECT 1\0");
                    }
                    b'S' => message(&mut output, b'Z', b"I"),
                    _ => panic!("unexpected query message: {tag}"),
                }
                socket.write_all(&output).await.expect("query response");
                if tag == b'E' {
                    break;
                }
            }

            let tag = socket.read_u8().await.expect("Sync tag");
            assert_eq!(tag, b'S');
            assert_eq!(socket.read_u32().await.expect("Sync length"), 4);
            output.clear();
            message(&mut output, b'Z', b"I");
            socket.write_all(&output).await.expect("query ready");
        }

        let mut sockets = vec![socket];
        for _ in 0..2 {
            let (mut socket, _) = listener.accept().await.expect("background socket");
            read_startup(&mut socket).await;
            sockets.push(socket);
        }
        sockets
    }

    #[tokio::test]
    async fn connect_cfg_timeout_closes_background_sockets() {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind listener");
        let address = listener.local_addr().expect("listener address");
        let mut postgres = pg::Config::new();
        postgres
            .host("127.0.0.1")
            .port(address.port())
            .user("test")
            .ssl_mode(pg::config::SslMode::Disable);

        let sockets = {
            let connect = crate::connect_cfg(Config::from(postgres));
            tokio::pin!(connect);
            let sockets = timeout(Duration::from_secs(5), async {
                tokio::select! {
                    result = &mut connect => panic!("connect completed before cancellation: {}", result.is_ok()),
                    sockets = initialize_topology(&listener) => sockets,
                }
            })
            .await
            .expect("discovery refresh and metadata must both reach a network wait");
            assert!(timeout(Duration::from_millis(50), connect).await.is_err());
            sockets
        };

        timeout(Duration::from_secs(2), async {
            for mut socket in sockets {
                let mut buffer = [0; 1024];
                while let Ok(n) = socket.read(&mut buffer).await {
                    if n == 0 {
                        break;
                    }
                }
            }
        })
        .await
        .expect("all background sockets must close after connect_cfg is cancelled");
    }

    #[tokio::test]
    async fn metadata_recovers_after_initial_failure() {
        use crate::{Strategy, manager::Manager};
        use std::sync::atomic::{AtomicBool, Ordering};

        const SQL: &str = "SELECT $1::int";
        struct Fallback(Arc<AtomicBool>);
        impl Strategy for Fallback {
            fn next(&self, _: usize) -> usize {
                self.0.store(true, Ordering::Relaxed);
                0
            }
        }

        let fallback = Arc::new(AtomicBool::new(false));
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let mut postgres = pg::Config::new();
        postgres
            .host("127.0.0.1")
            .port(listener.local_addr().unwrap().port())
            .user("test")
            .ssl_mode(pg::config::SslMode::Disable);
        let mut config = Config::from(postgres);
        config.discorery_interval = Duration::from_secs(3600);

        timeout(Duration::from_secs(5), async {
            let (manager, ()) = tokio::join!(Manager::new(config, Fallback(fallback.clone())), async {
                drop(initialize_topology(&listener).await);
            });
            let manager = manager.expect("initial metadata failure must allow construction");
            manager.route(SQL, &[&1_i32], true, None).await.unwrap();
            assert!(fallback.swap(false, Ordering::Relaxed));

            let (mut socket, _) = listener.accept().await.unwrap();
            read_startup(&mut socket).await;
            let mut response = Vec::new();
            message(&mut response, b'R', &0_u32.to_be_bytes());
            message(&mut response, b'Z', b"I");
            socket.write_all(&response).await.unwrap();

            // The prefetch queued during the outage must reach the server before another route call.
            assert_eq!(socket.read_u8().await.unwrap(), b'P');
            let len = socket.read_u32().await.unwrap();
            let mut body = vec![0; usize::try_from(len - 4).unwrap()];
            socket.read_exact(&mut body).await.unwrap();
            assert_eq!(body.split(|&b| b == 0).nth(1), Some(SQL.as_bytes()));
            response.clear();
            message(&mut response, b'1', &[]);
            message(&mut response, b't', &[0, 1, 0, 0, 0, 23]);
            message(&mut response, b'n', &[]);
            message(
                &mut response,
                b'N',
                b"SNOTICE\0C00000\0M{\"query\":\"SELECT $1::int\",\"tier\":\"\",\"dk_meta\":[[1,23]]}\0\0",
            );
            message(&mut response, b'Z', b"I");
            socket.write_all(&response).await.unwrap();

            loop {
                manager.route(SQL, &[&1_i32], true, None).await.unwrap();
                if !fallback.swap(false, Ordering::Relaxed) {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
            manager.close().await.unwrap();
        })
        .await
        .expect("metadata must recover on the existing manager");
    }

    #[tokio::test]
    async fn start_ends_quietly_when_init_receiver_is_dropped() {
        let mut postgres = pg::Config::new();
        postgres
            .host("127.0.0.1")
            .port(1)
            .connect_timeout(std::time::Duration::from_secs(1));
        let accessor = Arc::new(Accessor::new(Pool::new(), Box::new(RoundRobin::new())));
        let discovery = Discovery::new(accessor, Config::from(postgres), CancellationToken::new());

        let (handle, receiver) = discovery.start();
        drop(receiver);

        handle.await.expect("discovery task must not panic");
    }
}