clickhouse_native_rs/pool/
mod.rs1use std::{
2 fmt, mem,
3 pin::Pin,
4 sync::atomic::{self, Ordering},
5 sync::Arc,
6 task::{Context, Poll, Waker},
7};
8
9use futures_util::future::BoxFuture;
10use log::{error, warn};
11
12use crate::{
13 errors::Result,
14 types::{IntoOptions, OptionsSource},
15 Client, ClientHandle,
16};
17
18pub use self::futures::GetHandle;
19use futures_util::FutureExt;
20use url::Url;
21
22mod futures;
23
24pub(crate) struct Inner {
25 new: crossbeam::queue::ArrayQueue<BoxFuture<'static, Result<ClientHandle>>>,
26 idle: crossbeam::queue::ArrayQueue<ClientHandle>,
27 tasks: crossbeam::queue::SegQueue<Waker>,
28 ongoing: atomic::AtomicUsize,
29 hosts: Vec<Url>,
30 connections_num: atomic::AtomicUsize,
31}
32
33impl Inner {
34 pub(crate) fn release_conn(&self) {
35 self.ongoing.fetch_sub(1, Ordering::AcqRel);
36 while let Some(task) = self.tasks.pop() {
37 task.wake()
38 }
39 }
40
41 fn conn_count(&self) -> usize {
42 let is_new_some = self.new.len();
43 let ongoing = self.ongoing.load(Ordering::Acquire);
44 let idle_count = self.idle.len();
45 is_new_some + idle_count + ongoing
46 }
47}
48
49#[derive(Clone)]
50pub(crate) enum PoolBinding {
51 None,
52 Attached(Pool),
53 Detached(Pool),
54}
55
56impl From<PoolBinding> for Option<Pool> {
57 fn from(binding: PoolBinding) -> Self {
58 match binding {
59 PoolBinding::None => None,
60 PoolBinding::Attached(pool) | PoolBinding::Detached(pool) => Some(pool),
61 }
62 }
63}
64
65impl PoolBinding {
66 pub(crate) fn take(&mut self) -> Self {
67 mem::replace(self, PoolBinding::None)
68 }
69
70 fn return_conn(self, client: ClientHandle) {
71 if let Some(mut pool) = self.into() {
72 Pool::return_conn(&mut pool, client);
73 }
74 }
75
76 pub(crate) fn is_attached(&self) -> bool {
77 matches!(self, PoolBinding::Attached(_))
78 }
79
80 pub(crate) fn is_some(&self) -> bool {
81 !matches!(self, PoolBinding::None)
82 }
83
84 pub(crate) fn attach(&mut self) {
85 match self.take() {
86 PoolBinding::Detached(pool) => *self = PoolBinding::Attached(pool),
87 _ => unreachable!(),
88 }
89 }
90
91 pub(crate) fn detach(&mut self) {
92 match self.take() {
93 PoolBinding::Attached(pool) => *self = PoolBinding::Detached(pool),
94 _ => unreachable!(),
95 }
96 }
97}
98
99#[derive(Clone)]
101pub struct Pool {
102 options: OptionsSource,
103 pub(crate) inner: Arc<Inner>,
104 min: usize,
105 max: usize,
106}
107
108#[derive(Debug)]
109struct PoolInfo {
110 new_len: usize,
111 idle_len: usize,
112 tasks_len: usize,
113 ongoing: usize,
114}
115
116impl fmt::Debug for Pool {
117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
118 let info = self.info();
119 f.debug_struct("Pool")
120 .field("min", &self.min)
121 .field("max", &self.max)
122 .field("new connections count", &info.new_len)
123 .field("idle connections count", &info.idle_len)
124 .field("tasks count", &info.tasks_len)
125 .field("ongoing connections count", &info.ongoing)
126 .finish()
127 }
128}
129
130impl Pool {
131 pub fn new<O>(options: O) -> Self
133 where
134 O: IntoOptions,
135 {
136 let options_src = options.into_options_src();
137
138 let mut min = 5;
139 let mut max = 10;
140 let mut hosts = vec![];
141
142 match options_src.get() {
143 Ok(opt) => {
144 min = opt.pool_min;
145 max = opt.pool_max;
146 hosts.push(opt.addr.clone());
147 hosts.extend(opt.alt_hosts.iter().cloned());
148 }
149 Err(err) => error!("{}", err),
150 }
151
152 for host in &hosts {
153 if host.port() == Some(8123) {
154 warn!(
155 "Port 8123 is the HTTP interface; this client speaks the native TCP protocol (port 9000 by default)."
156 );
157 break;
158 }
159 }
160
161 let inner = Arc::new(Inner {
162 new: crossbeam::queue::ArrayQueue::new(1),
163 idle: crossbeam::queue::ArrayQueue::new(max),
164 tasks: crossbeam::queue::SegQueue::new(),
165 ongoing: atomic::AtomicUsize::new(0),
166 connections_num: atomic::AtomicUsize::new(0),
167 hosts,
168 });
169
170 Self {
171 options: options_src,
172 inner,
173 min,
174 max,
175 }
176 }
177
178 fn info(&self) -> PoolInfo {
179 PoolInfo {
180 new_len: self.inner.new.len(),
181 idle_len: self.inner.idle.len(),
182 tasks_len: self.inner.tasks.len(),
183 ongoing: self.inner.ongoing.load(Ordering::Acquire),
184 }
185 }
186
187 pub fn get_handle(&self) -> GetHandle {
189 GetHandle::new(self)
190 }
191
192 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<ClientHandle>> {
193 self.handle_futures(cx)?;
194
195 match self.take_conn() {
196 Some(client) => Poll::Ready(Ok(client)),
197 None => {
198 let new_conn_created = {
199 let conn_count = self.inner.conn_count();
200
201 if conn_count < self.max && self.inner.new.push(self.new_connection()).is_ok() {
202 true
203 } else {
204 self.inner.tasks.push(cx.waker().clone());
205 false
206 }
207 };
208 if new_conn_created {
209 self.poll(cx)
210 } else {
211 Poll::Pending
212 }
213 }
214 }
215 }
216
217 fn new_connection(&self) -> BoxFuture<'static, Result<ClientHandle>> {
218 let source = self.options.clone();
219 let pool = Some(self.clone());
220 Box::pin(async move { Client::open(source, pool).await })
221 }
222
223 fn handle_futures(&mut self, cx: &mut Context<'_>) -> Result<()> {
224 if let Some(mut new) = self.inner.new.pop() {
225 match new.poll_unpin(cx) {
226 Poll::Ready(Ok(client)) => {
227 self.inner.idle.push(client).unwrap();
228 }
229 Poll::Pending => {
230 let _ = self.inner.new.push(new);
234 }
235 Poll::Ready(Err(err)) => {
236 return Err(err);
237 }
238 }
239 }
240
241 Ok(())
242 }
243
244 fn take_conn(&mut self) -> Option<ClientHandle> {
245 if let Some(mut client) = self.inner.idle.pop() {
246 client.pool = PoolBinding::Attached(self.clone());
247 client.set_inside(false);
248 self.inner.ongoing.fetch_add(1, Ordering::AcqRel);
249 Some(client)
250 } else {
251 None
252 }
253 }
254
255 fn return_conn(&mut self, mut client: ClientHandle) {
256 let min = self.min;
257
258 let is_attached = client.pool.is_attached();
259 client.pool = PoolBinding::None;
260 client.set_inside(true);
261
262 if self.inner.idle.len() < min && is_attached && client.inner.is_some() {
263 let _ = self.inner.idle.push(client);
264 }
265 self.inner.ongoing.fetch_sub(1, Ordering::AcqRel);
266
267 while let Some(task) = self.inner.tasks.pop() {
268 task.wake()
269 }
270 }
271
272 pub(crate) fn get_addr(&self) -> &Url {
273 let n = self.inner.hosts.len();
274 let index = self.inner.connections_num.fetch_add(1, Ordering::SeqCst);
275 &self.inner.hosts[index % n]
276 }
277}
278
279impl Drop for ClientHandle {
280 fn drop(&mut self) {
281 if let (pool, Some(mut inner)) = (self.pool.take(), self.inner.take()) {
282 if !pool.is_some() {
283 return;
284 }
285 inner.release_buffers();
287
288 let context = self.context.clone();
289 let client = Self {
290 inner: Some(inner),
291 pool: pool.clone(),
292 context,
293 };
294 pool.return_conn(client);
295 }
296 }
297}
298
299#[cfg(feature = "tokio_io")]
300#[cfg(test)]
301mod test {
302 use std::{
303 str::FromStr,
304 time::{Duration, Instant},
305 };
306
307 use futures_util::future;
308
309 use crate::{errors::Result, test_misc::DATABASE_URL, Block, Options};
310
311 use super::Pool;
312 use url::Url;
313
314 #[tokio::test]
315 async fn test_connect() -> Result<()> {
316 let options = Options::from_str(DATABASE_URL.as_str()).unwrap();
317 let pool = Pool::new(options);
318 {
319 let mut c = pool.get_handle().await?;
320 c.ping().await?;
321 }
322
323 let info = pool.info();
324 assert_eq!(info.ongoing, 0);
325 assert_eq!(info.idle_len, 1);
326 Ok(())
327 }
328
329 #[tokio::test]
330 async fn test_detach() -> Result<()> {
331 async fn done(pool: Pool) -> Result<()> {
332 let p = pool.clone();
333 let mut c = p.get_handle().await?;
334 c.ping().await?;
335 c.pool.detach();
336 Ok(())
337 }
338
339 let pool = Pool::new(DATABASE_URL.as_str());
340 done(pool.clone()).await?;
341 assert_eq!(pool.info().idle_len, 0);
342
343 Ok(())
344 }
345
346 #[tokio::test]
347 async fn test_many_connection() -> Result<()> {
348 let options = Options::from_str(DATABASE_URL.as_str())
349 .unwrap()
350 .pool_min(6)
351 .pool_max(12);
352 let pool = Pool::new(options);
353
354 async fn exec_query(pool: &Pool) -> Result<u32> {
355 let mut c = pool.get_handle().await?;
356 let block = c.query("SELECT toUInt32(1), sleep(1)").fetch_all().await?;
357
358 let value: u32 = block.get(0, 0)?;
359 Ok(value)
360 }
361
362 let expected = 22_u32;
363
364 let start = Instant::now();
365
366 let mut requests = Vec::new();
367 for _ in 0..expected as usize {
368 requests.push(exec_query(&pool))
369 }
370
371 let xs = future::join_all(requests).await;
372 let mut actual: u32 = 0;
373
374 for x in xs {
375 actual += x?;
376 }
377 assert_eq!(actual, expected);
378
379 let spent = start.elapsed();
380
381 assert!(spent >= Duration::from_millis(2000));
382 #[cfg(feature = "_tls")]
383 assert!(spent < Duration::from_millis(5000)); #[cfg(not(feature = "_tls"))]
385 assert!(spent < Duration::from_millis(2500));
386
387 assert_eq!(pool.info().idle_len, 6);
388 Ok(())
389 }
390
391 #[tokio::test]
392 async fn test_wrong_insert() -> Result<()> {
393 let pool = Pool::new(DATABASE_URL.as_str());
394 {
395 let block = Block::new();
396 let mut c = pool.get_handle().await?;
397 c.insert("unexisting", block).await.unwrap_err();
398 }
399 let info = pool.info();
400 assert_eq!(info.ongoing, 0);
401 assert_eq!(info.tasks_len, 0);
402 assert_eq!(info.idle_len, 0);
403 Ok(())
404 }
405
406 #[tokio::test]
407 async fn test_wrong_execute() -> Result<()> {
408 let pool = Pool::new(DATABASE_URL.as_str());
409 {
410 let mut c = pool.get_handle().await?;
411 c.execute("DROP TABLE unexisting").await.unwrap_err();
412 }
413 let info = pool.info();
414 assert_eq!(info.ongoing, 0);
415 assert_eq!(info.tasks_len, 0);
416 assert_eq!(info.idle_len, 0);
417 Ok(())
418 }
419
420 #[test]
421 fn test_get_addr() {
422 let options =
423 Options::from_str("tcp://host1:9000?alt_hosts=host2:9000,host3:9000").unwrap();
424 let pool = Pool::new(options);
425
426 assert_eq!(pool.get_addr(), &Url::from_str("tcp://host1:9000").unwrap());
427 assert_eq!(pool.get_addr(), &Url::from_str("tcp://host2:9000").unwrap());
428 assert_eq!(pool.get_addr(), &Url::from_str("tcp://host3:9000").unwrap());
429 assert_eq!(pool.get_addr(), &Url::from_str("tcp://host1:9000").unwrap())
430 }
431}