r2d2-0.8.10/.cargo_vcs_info.json0000644000000001360000000000100116730ustar { "git": { "sha1": "111835f6f4c4e8a8b84b8c298369d90c252fddfc" }, "path_in_vcs": "" }r2d2-0.8.10/.circleci/config.yml000064400000000000000000000010720072674642500143360ustar 00000000000000version: 2 jobs: build: docker: - image: rust:1.49.0 steps: - checkout - restore_cache: key: registry - run: cargo generate-lockfile - save_cache: key: registry-{{ epoch }} paths: - /usr/local/cargo/registry/index - restore_cache: key: dependencies-1.49-{{ checksum "Cargo.lock" }} - run: cargo test - save_cache: key: dependencies-1.49-{{ checksum "Cargo.lock" }} paths: - target - /usr/local/cargo/registry/cache r2d2-0.8.10/.github/dependabot.yml000064400000000000000000000002210072674642500146760ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "13:00" open-pull-requests-limit: 10 r2d2-0.8.10/.gitignore000064400000000000000000000000610072674642500125000ustar 00000000000000/target Cargo.lock .cargo/ .idea/ *.iml .vscode/ r2d2-0.8.10/CHANGELOG.md000064400000000000000000000070660072674642500123350ustar 00000000000000# Change Log ## [Unreleased] ## [0.8.10] - 2022-06-21 ## Changed * Upgraded `parking_lot`. ## [0.8.9] - 2020-06-30 ## Changed * Upgraded `parking_lot`. ## [0.8.7] - 2019-11-25 ## Changed * Upgraded `parking_lot`. ## [0.8.6] - 2019-10-19 ## Added * Added the ability to associate arbitrary data with pooled connections. ## [0.8.5] - 2019-06-06 ## Changed * Upgraded `parking_lot`. ## [0.8.4] - 2019-04-01 ### Added * Added a `HandleEvent` trait used to listen for various events from the pool for monitoring purposes. ### Changed * Switched from standard library synchronization primitives to `parking_lot`. ## [0.8.3] - 2018-11-03 ### Fixed * The set of idle connections is now treated as a stack rather than a queue. The old behavior interacted poorly with configurations that allowed the pool size to shrink when mostly idle. ## [0.8.2] - 2017-12-24 ### Changed * Upgraded from log 0.3 to 0.4. ## [0.8.1] - 2017-10-28 ### Fixed * Fixed the example in the README. ## [0.8.0] - 2017-10-26 ### Changed * Pool configuration has changed. Rather than constructing a `Config` and passing it to the `Pool` constructor, you now configure a `Builder` which then directly constructs the pool: ```rust // In 0.7.x let config = Config::builder() .min_idle(3) .build(); let pool = Pool::new(config, manager)?; // In 0.8.x let pool = Pool::builder() .min_idle(3) .build(manager)?; ``` * The `Pool::new` method can be used to construct a `Pool` with default settings: ```rust // In 0.7.x let config = Config::default(); let pool = Pool::new(config, manager)?; // In 0.8.x let pool = Pool::new(manager)?; ``` * The `initialization_fail_fast` configuration option has been replaced with separate `Builder::build` and `Builder::build_unchecked` methods. The second returns a `Pool` directly without wrapping it in a `Result`, and does not check that connections are being successfully opened: ```rust // In 0.7.x let config = Config::builder() .initialization_fail_fast(false) .build(); let pool = Pool::new(config, manager).unwrap(); // In 0.8.x let pool = Pool::builder().build_unchecked(manager); ``` * The `InitializationError` and `GetTimeout` error types have been merged into a unified `Error` type. * The `Pool::config` method has been replaced with accessor methods on `Pool` to directly access configuration, such as `Pool::min_idle`. * The `scheduled_thread_pool` crate has been upgraded from 0.1 to 0.2. ### Removed * The deprecated `Builder::num_threads` method has been removed. Construct a `ScheduledThreadPool` and set it via `Builder::thread_pool` instead. ## Older Look at the [release tags] for information about older releases. [Unreleased]: https://github.com/sfackler/r2d2/compare/v0.8.10...HEAD [0.8.10]: https://github.com/sfackler/r2d2/compare/v0.8.9...v0.8.10 [0.8.9]: https://github.com/sfackler/r2d2/compare/v0.8.8...v0.8.9 [0.8.7]: https://github.com/sfackler/r2d2/compare/v0.8.6...v0.8.7 [0.8.6]: https://github.com/sfackler/r2d2/compare/v0.8.5...v0.8.6 [0.8.5]: https://github.com/sfackler/r2d2/compare/v0.8.4...v0.8.5 [0.8.4]: https://github.com/sfackler/r2d2/compare/v0.8.3...v0.8.4 [0.8.3]: https://github.com/sfackler/r2d2/compare/v0.8.2...v0.8.3 [0.8.2]: https://github.com/sfackler/r2d2/compare/v0.8.1...v0.8.2 [0.8.1]: https://github.com/sfackler/r2d2/compare/v0.8.0...v0.8.1 [0.8.0]: https://github.com/sfackler/r2d2/compare/v0.7.4...v0.8.0 [release tags]: https://github.com/sfackler/r2d2/releases r2d2-0.8.10/Cargo.toml0000644000000015750000000000100077010ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "r2d2" version = "0.8.10" authors = ["Steven Fackler "] description = "A generic connection pool" readme = "README.md" keywords = [ "database", "pool", ] license = "MIT/Apache-2.0" repository = "https://github.com/sfackler/r2d2" [dependencies.log] version = "0.4" [dependencies.parking_lot] version = "0.12" [dependencies.scheduled-thread-pool] version = "0.2" r2d2-0.8.10/Cargo.toml.orig000064400000000000000000000005470072674642500134100ustar 00000000000000[package] name = "r2d2" version = "0.8.10" authors = ["Steven Fackler "] license = "MIT/Apache-2.0" description = "A generic connection pool" repository = "https://github.com/sfackler/r2d2" readme = "README.md" keywords = ["database", "pool"] edition = "2018" [dependencies] log = "0.4" parking_lot = "0.12" scheduled-thread-pool = "0.2" r2d2-0.8.10/LICENSE-APACHE000064400000000000000000000261360072674642500124470ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. r2d2-0.8.10/LICENSE-MIT000064400000000000000000000020760072674642500121540ustar 00000000000000The MIT License (MIT) Copyright (c) 2014-2016 Steven Fackler Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. r2d2-0.8.10/README.md000064400000000000000000000100270072674642500117720ustar 00000000000000# r2d2 [![CircleCI](https://circleci.com/gh/sfackler/r2d2.svg?style=shield)](https://circleci.com/gh/sfackler/r2d2) A generic connection pool for Rust. [Documentation](https://docs.rs/r2d2) Opening a new database connection every time one is needed is both inefficient and can lead to resource exhaustion under high traffic conditions. A connection pool maintains a set of open connections to a database, handing them out for repeated use. r2d2 is agnostic to the connection type it is managing. Implementors of the `ManageConnection` trait provide the database-specific logic to create and check the health of connections. A (possibly not exhaustive) list of adaptors for different backends: Backend | Adaptor Crate ---------------------------------------------------------------------- | ------------- [rust-postgres](https://github.com/sfackler/rust-postgres) | [r2d2-postgres](https://github.com/sfackler/r2d2-postgres) [redis-rs](https://github.com/mitsuhiko/redis-rs) | use `r2d2` feature of [redis-rs](https://github.com/mitsuhiko/redis-rs) [rust-memcache](https://github.com/aisk/rust-memcache) | [r2d2-memcache](https://github.com/megumish/r2d2-memcache) [rust-mysql-simple](https://github.com/blackbeam/rust-mysql-simple) | [r2d2-mysql](https://github.com/outersky/r2d2-mysql) [rusqlite](https://github.com/jgallagher/rusqlite) | [r2d2-sqlite](https://github.com/ivanceras/r2d2-sqlite) [rsfbclient](https://github.com/fernandobatels/rsfbclient) | [r2d2-firebird](https://crates.io/crates/r2d2_firebird/) [rusted-cypher](https://github.com/livioribeiro/rusted-cypher) | [r2d2-cypher](https://github.com/flosse/r2d2-cypher) [diesel](https://github.com/sgrif/diesel) | [diesel::r2d2](https://github.com/diesel-rs/diesel/blob/master/diesel/src/r2d2.rs) ([docs](https://docs.diesel.rs/diesel/r2d2/)) [couchdb](https://github.com/chill-rs/chill) | [r2d2-couchdb](https://github.com/scorphus/r2d2-couchdb) [mongodb (archived)](https://github.com/mongodb-labs/mongo-rust-driver-prototype)
use official [mongodb](https://github.com/mongodb/mongo-rust-driver) driver instead | [r2d2-mongodb](https://gitlab.com/petoknm/r2d2-mongodb)
(deprecated: official driver handles pooling internally) [odbc](https://github.com/Koka/odbc-rs) | [r2d2-odbc](https://github.com/Koka/r2d2-odbc) [jfs](https://github.com/flosse/rust-json-file-store) | [r2d2-jfs](https://github.com/flosse/r2d2-jfs) [oracle](https://github.com/kubo/rust-oracle) | [r2d2-oracle](https://github.com/rursprung/r2d2-oracle) [ldap3](https://github.com/inejge/ldap3) | [r2d2-ldap](https://github.com/c0dearm/r2d2-ldap) [duckdb-rs](https://github.com/wangfenjin/duckdb-rs) | use `r2d2` feature of [duckdb-rs](https://github.com/wangfenjin/duckdb-rs) # Example Using an imaginary "foodb" database. ```rust use std::thread; extern crate r2d2; extern crate r2d2_foodb; fn main() { let manager = r2d2_foodb::FooConnectionManager::new("localhost:1234"); let pool = r2d2::Pool::builder() .max_size(15) .build(manager) .unwrap(); for _ in 0..20 { let pool = pool.clone(); thread::spawn(move || { let conn = pool.get().unwrap(); // use the connection // it will be returned to the pool when it falls out of scope. }) } } ``` ## License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. r2d2-0.8.10/src/config.rs000064400000000000000000000232170072674642500131220ustar 00000000000000use scheduled_thread_pool::ScheduledThreadPool; use std::fmt; use std::marker::PhantomData; use std::sync::Arc; use std::time::Duration; use crate::{ CustomizeConnection, Error, HandleError, HandleEvent, LoggingErrorHandler, ManageConnection, NopConnectionCustomizer, NopEventHandler, Pool, }; /// A builder for a connection pool. pub struct Builder where M: ManageConnection, { max_size: u32, min_idle: Option, test_on_check_out: bool, max_lifetime: Option, idle_timeout: Option, connection_timeout: Duration, error_handler: Box>, connection_customizer: Box>, event_handler: Box, thread_pool: Option>, reaper_rate: Duration, _p: PhantomData, } impl fmt::Debug for Builder where M: ManageConnection, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Builder") .field("max_size", &self.max_size) .field("min_idle", &self.min_idle) .field("test_on_check_out", &self.test_on_check_out) .field("max_lifetime", &self.max_lifetime) .field("idle_timeout", &self.idle_timeout) .field("connection_timeout", &self.connection_timeout) .field("error_handler", &self.error_handler) .field("event_handler", &self.event_handler) .field("connection_customizer", &self.connection_customizer) .finish() } } impl Default for Builder where M: ManageConnection, { fn default() -> Builder { Builder { max_size: 10, min_idle: None, test_on_check_out: true, idle_timeout: Some(Duration::from_secs(10 * 60)), max_lifetime: Some(Duration::from_secs(30 * 60)), connection_timeout: Duration::from_secs(30), error_handler: Box::new(LoggingErrorHandler), event_handler: Box::new(NopEventHandler), connection_customizer: Box::new(NopConnectionCustomizer), thread_pool: None, reaper_rate: Duration::from_secs(30), _p: PhantomData, } } } impl Builder where M: ManageConnection, { /// Constructs a new `Builder`. /// /// Parameters are initialized with their default values. pub fn new() -> Builder { Builder::default() } /// Sets the maximum number of connections managed by the pool. /// /// Defaults to 10. /// /// # Panics /// /// Panics if `max_size` is 0. pub fn max_size(mut self, max_size: u32) -> Builder { assert!(max_size > 0, "max_size must be positive"); self.max_size = max_size; self } /// Sets the minimum idle connection count maintained by the pool. /// /// If set, the pool will try to maintain at least this many idle /// connections at all times, while respecting the value of `max_size`. /// /// Defaults to `None` (equivalent to the value of `max_size`). pub fn min_idle(mut self, min_idle: Option) -> Builder { self.min_idle = min_idle; self } /// Sets the thread pool used for asynchronous operations such as connection /// creation. /// /// Defaults to a new pool with 3 threads. pub fn thread_pool(mut self, thread_pool: Arc) -> Builder { self.thread_pool = Some(thread_pool); self } /// If true, the health of a connection will be verified via a call to /// `ConnectionManager::is_valid` before it is checked out of the pool. /// /// Defaults to true. pub fn test_on_check_out(mut self, test_on_check_out: bool) -> Builder { self.test_on_check_out = test_on_check_out; self } /// Sets the maximum lifetime of connections in the pool. /// /// If set, connections will be closed after existing for at most 30 seconds /// beyond this duration. /// /// If a connection reaches its maximum lifetime while checked out it will /// be closed when it is returned to the pool. /// /// Defaults to 30 minutes. /// /// # Panics /// /// Panics if `max_lifetime` is the zero `Duration`. pub fn max_lifetime(mut self, max_lifetime: Option) -> Builder { assert_ne!(max_lifetime, Some(Duration::from_secs(0)), "max_lifetime must be positive"); self.max_lifetime = max_lifetime; self } /// Sets the idle timeout used by the pool. /// /// If set, connections will be closed after sitting idle for at most 30 /// seconds beyond this duration. /// /// Defaults to 10 minutes. /// /// # Panics /// /// Panics if `idle_timeout` is the zero `Duration`. pub fn idle_timeout(mut self, idle_timeout: Option) -> Builder { assert_ne!(idle_timeout, Some(Duration::from_secs(0)), "idle_timeout must be positive"); self.idle_timeout = idle_timeout; self } /// Sets the connection timeout used by the pool. /// /// Calls to `Pool::get` will wait this long for a connection to become /// available before returning an error. /// /// Defaults to 30 seconds. /// /// # Panics /// /// Panics if `connection_timeout` is the zero duration pub fn connection_timeout(mut self, connection_timeout: Duration) -> Builder { assert!( connection_timeout > Duration::from_secs(0), "connection_timeout must be positive" ); self.connection_timeout = connection_timeout; self } /// Sets the handler for errors reported in the pool. /// /// Defaults to the `LoggingErrorHandler`. pub fn error_handler(mut self, error_handler: Box>) -> Builder { self.error_handler = error_handler; self } /// Sets the handler for events reported by the pool. /// /// Defaults to the `NopEventHandler`. pub fn event_handler(mut self, event_handler: Box) -> Builder { self.event_handler = event_handler; self } /// Sets the connection customizer used by the pool. /// /// Defaults to the `NopConnectionCustomizer`. pub fn connection_customizer( mut self, connection_customizer: Box>, ) -> Builder { self.connection_customizer = connection_customizer; self } // used by tests #[allow(dead_code)] pub(crate) fn reaper_rate(mut self, reaper_rate: Duration) -> Builder { self.reaper_rate = reaper_rate; self } /// Consumes the builder, returning a new, initialized pool. /// /// It will block until the pool has established its configured minimum /// number of connections, or it times out. /// /// # Errors /// /// Returns an error if the pool is unable to open its minimum number of /// connections. /// /// # Panics /// /// Panics if `min_idle` is greater than `max_size`. pub fn build(self, manager: M) -> Result, Error> { let pool = self.build_unchecked(manager); pool.wait_for_initialization()?; Ok(pool) } /// Consumes the builder, returning a new pool. /// /// Unlike `build`, this method does not wait for any connections to be /// established before returning. /// /// # Panics /// /// Panics if `min_idle` is greater than `max_size`. pub fn build_unchecked(self, manager: M) -> Pool { if let Some(min_idle) = self.min_idle { assert!( self.max_size >= min_idle, "min_idle must be no larger than max_size" ); } let thread_pool = match self.thread_pool { Some(thread_pool) => thread_pool, None => Arc::new(ScheduledThreadPool::with_name("r2d2-worker-{}", 3)), }; let config = Config { max_size: self.max_size, min_idle: self.min_idle, test_on_check_out: self.test_on_check_out, max_lifetime: self.max_lifetime, idle_timeout: self.idle_timeout, connection_timeout: self.connection_timeout, error_handler: self.error_handler, event_handler: self.event_handler, connection_customizer: self.connection_customizer, thread_pool, }; Pool::new_inner(config, manager, self.reaper_rate) } } pub struct Config { pub max_size: u32, pub min_idle: Option, pub test_on_check_out: bool, pub max_lifetime: Option, pub idle_timeout: Option, pub connection_timeout: Duration, pub error_handler: Box>, pub event_handler: Box, pub connection_customizer: Box>, pub thread_pool: Arc, } // manual to avoid bounds on C and E impl fmt::Debug for Config { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Config") .field("max_size", &self.max_size) .field("min_idle", &self.min_idle) .field("test_on_check_out", &self.test_on_check_out) .field("max_lifetime", &self.max_lifetime) .field("idle_timeout", &self.idle_timeout) .field("connection_timeout", &self.connection_timeout) .field("error_handler", &self.error_handler) .field("event_handler", &self.event_handler) .field("connection_customizer", &self.connection_customizer) .finish() } } r2d2-0.8.10/src/event.rs000064400000000000000000000060150072674642500127730ustar 00000000000000//! Event subscriptions. use std::fmt; use std::time::Duration; /// A trait which is provided with information about events in a connection pool. pub trait HandleEvent: fmt::Debug + Sync + Send { /// Called when a new connection is acquired. /// /// The default implementation does nothing. #[allow(unused_variables)] fn handle_acquire(&self, event: AcquireEvent) {} /// Called when a connection is released. /// /// The default implementation does nothing. #[allow(unused_variables)] fn handle_release(&self, event: ReleaseEvent) {} /// Called when a connection is checked out from the pool. /// /// The default implementation does nothing. #[allow(unused_variables)] fn handle_checkout(&self, event: CheckoutEvent) {} /// Called when a checkout attempt times out. /// /// The default implementation does nothing. #[allow(unused_variables)] fn handle_timeout(&self, event: TimeoutEvent) {} /// Called when a connection is checked back into the pool. #[allow(unused_variables)] fn handle_checkin(&self, event: CheckinEvent) {} } /// A `HandleEvent` implementation which does nothing. #[derive(Copy, Clone, Debug)] pub struct NopEventHandler; impl HandleEvent for NopEventHandler {} /// Information about an acquire event. #[derive(Debug)] pub struct AcquireEvent { pub(crate) id: u64, } impl AcquireEvent { /// Returns the ID of the connection. #[inline] pub fn connection_id(&self) -> u64 { self.id } } /// Information about a release event. #[derive(Debug)] pub struct ReleaseEvent { pub(crate) id: u64, pub(crate) age: Duration, } impl ReleaseEvent { /// Returns the ID of the connection. #[inline] pub fn connection_id(&self) -> u64 { self.id } /// Returns the age of the connection. #[inline] pub fn age(&self) -> Duration { self.age } } /// Information about a checkout event. #[derive(Debug)] pub struct CheckoutEvent { pub(crate) id: u64, pub(crate) duration: Duration, } impl CheckoutEvent { /// Returns the ID of the connection. #[inline] pub fn connection_id(&self) -> u64 { self.id } /// Returns the time taken to check out the connection. #[inline] pub fn duration(&self) -> Duration { self.duration } } /// Information about a timeout event. #[derive(Debug)] pub struct TimeoutEvent { pub(crate) timeout: Duration, } impl TimeoutEvent { /// Returns the timeout of the failed checkout attempt. #[inline] pub fn timeout(&self) -> Duration { self.timeout } } /// Information about a checkin event. #[derive(Debug)] pub struct CheckinEvent { pub(crate) id: u64, pub(crate) duration: Duration, } impl CheckinEvent { /// Returns the ID of the connection. #[inline] pub fn connection_id(&self) -> u64 { self.id } /// Returns the amount of time the connection was checked out. #[inline] pub fn duration(&self) -> Duration { self.duration } } r2d2-0.8.10/src/extensions.rs000064400000000000000000000036200072674642500140500ustar 00000000000000use std::any::{Any, TypeId}; use std::collections::HashMap; /// A "type map" used to associate data with pooled connections. /// /// `Extensions` is a data structure mapping types to a value of that type. This /// can be used to, for example, cache prepared statements along side their /// connection. #[derive(Default)] pub struct Extensions(HashMap>); impl Extensions { /// Returns a new, empty `Extensions`. #[inline] pub fn new() -> Extensions { Extensions::default() } /// Inserts a new value into the map. /// /// Returns the previously stored value of that type, if present. pub fn insert(&mut self, value: T) -> Option where T: 'static + Sync + Send, { self.0 .insert(TypeId::of::(), Box::new(value)) .and_then(|v| Box::::downcast(v).ok()) .map(|v| *v) } /// Returns a shared reference to the stored value of the specified type. pub fn get(&self) -> Option<&T> where T: 'static + Sync + Send, { self.0 .get(&TypeId::of::()) .and_then(|v| v.downcast_ref()) } /// Returns a mutable reference to the stored value of the specified type. pub fn get_mut(&mut self) -> Option<&mut T> where T: 'static + Sync + Send, { self.0 .get_mut(&TypeId::of::()) .and_then(|v| v.downcast_mut()) } /// Removes the value of the specified type from the map, returning it. pub fn remove(&mut self) -> Option where T: 'static + Sync + Send, { self.0 .remove(&TypeId::of::()) .and_then(|v| Box::::downcast(v).ok()) .map(|v| *v) } /// Removes all values from the map. #[inline] pub fn clear(&mut self) { self.0.clear(); } } r2d2-0.8.10/src/lib.rs000064400000000000000000000461300072674642500124220ustar 00000000000000//! A generic connection pool. //! //! Opening a new database connection every time one is needed is both //! inefficient and can lead to resource exhaustion under high traffic //! conditions. A connection pool maintains a set of open connections to a //! database, handing them out for repeated use. //! //! r2d2 is agnostic to the connection type it is managing. Implementors of the //! `ManageConnection` trait provide the database-specific logic to create and //! check the health of connections. //! //! # Example //! //! Using an imaginary "foodb" database. //! //! ```rust,ignore //! use std::thread; //! //! extern crate r2d2; //! extern crate r2d2_foodb; //! //! fn main() { //! let manager = r2d2_foodb::FooConnectionManager::new("localhost:1234"); //! let pool = r2d2::Pool::builder() //! .max_size(15) //! .build(manager) //! .unwrap(); //! //! for _ in 0..20 { //! let pool = pool.clone(); //! thread::spawn(move || { //! let conn = pool.get().unwrap(); //! // use the connection //! // it will be returned to the pool when it falls out of scope. //! }) //! } //! } //! ``` #![warn(missing_docs)] #![doc(html_root_url = "https://docs.rs/r2d2/0.8")] use log::error; use parking_lot::{Condvar, Mutex, MutexGuard}; use std::cmp; use std::error; use std::fmt; use std::mem; use std::ops::{Deref, DerefMut}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Weak}; use std::time::{Duration, Instant}; pub use crate::config::Builder; use crate::config::Config; use crate::event::{AcquireEvent, CheckinEvent, CheckoutEvent, ReleaseEvent, TimeoutEvent}; pub use crate::event::{HandleEvent, NopEventHandler}; pub use crate::extensions::Extensions; mod config; pub mod event; mod extensions; #[cfg(test)] mod test; static CONNECTION_ID: AtomicUsize = AtomicUsize::new(0); /// A trait which provides connection-specific functionality. pub trait ManageConnection: Send + Sync + 'static { /// The connection type this manager deals with. type Connection: Send + 'static; /// The error type returned by `Connection`s. type Error: error::Error + 'static; /// Attempts to create a new connection. fn connect(&self) -> Result; /// Determines if the connection is still connected to the database. /// /// A standard implementation would check if a simple query like `SELECT 1` /// succeeds. fn is_valid(&self, conn: &mut Self::Connection) -> Result<(), Self::Error>; /// *Quickly* determines if the connection is no longer usable. /// /// This will be called synchronously every time a connection is returned /// to the pool, so it should *not* block. If it returns `true`, the /// connection will be discarded. /// /// For example, an implementation might check if the underlying TCP socket /// has disconnected. Implementations that do not support this kind of /// fast health check may simply return `false`. fn has_broken(&self, conn: &mut Self::Connection) -> bool; } /// A trait which handles errors reported by the `ManageConnection`. pub trait HandleError: fmt::Debug + Send + Sync + 'static { /// Handles an error. fn handle_error(&self, error: E); } /// A `HandleError` implementation which does nothing. #[derive(Copy, Clone, Debug)] pub struct NopErrorHandler; impl HandleError for NopErrorHandler { fn handle_error(&self, _: E) {} } /// A `HandleError` implementation which logs at the error level. #[derive(Copy, Clone, Debug)] pub struct LoggingErrorHandler; impl HandleError for LoggingErrorHandler where E: error::Error, { fn handle_error(&self, error: E) { error!("{}", error); } } /// A trait which allows for customization of connections. pub trait CustomizeConnection: fmt::Debug + Send + Sync + 'static { /// Called with connections immediately after they are returned from /// `ManageConnection::connect`. /// /// The default implementation simply returns `Ok(())`. /// /// # Errors /// /// If this method returns an error, the connection will be discarded. #[allow(unused_variables)] fn on_acquire(&self, conn: &mut C) -> Result<(), E> { Ok(()) } /// Called with connections when they are removed from the pool. /// /// The connections may be broken (as reported by `is_valid` or /// `has_broken`), or have simply timed out. /// /// The default implementation does nothing. #[allow(unused_variables)] fn on_release(&self, conn: C) {} } /// A `CustomizeConnection` which does nothing. #[derive(Copy, Clone, Debug)] pub struct NopConnectionCustomizer; impl CustomizeConnection for NopConnectionCustomizer {} struct Conn { conn: C, extensions: Extensions, birth: Instant, id: u64, } struct IdleConn { conn: Conn, idle_start: Instant, } struct PoolInternals { conns: Vec>, num_conns: u32, pending_conns: u32, last_error: Option, } struct SharedPool where M: ManageConnection, { config: Config, manager: M, internals: Mutex>, cond: Condvar, } fn drop_conns( shared: &Arc>, mut internals: MutexGuard>, conns: Vec>, ) where M: ManageConnection, { internals.num_conns -= conns.len() as u32; establish_idle_connections(shared, &mut internals); drop(internals); // make sure we run connection destructors without this locked for conn in conns { let event = ReleaseEvent { id: conn.id, age: conn.birth.elapsed(), }; shared.config.event_handler.handle_release(event); shared.config.connection_customizer.on_release(conn.conn); } } fn establish_idle_connections( shared: &Arc>, internals: &mut PoolInternals, ) where M: ManageConnection, { let min = shared.config.min_idle.unwrap_or(shared.config.max_size); let idle = internals.conns.len() as u32; for _ in idle..min { add_connection(shared, internals); } } fn add_connection(shared: &Arc>, internals: &mut PoolInternals) where M: ManageConnection, { if internals.num_conns + internals.pending_conns >= shared.config.max_size { return; } internals.pending_conns += 1; inner(Duration::from_secs(0), shared); fn inner(delay: Duration, shared: &Arc>) where M: ManageConnection, { let new_shared = Arc::downgrade(shared); shared.config.thread_pool.execute_after(delay, move || { let shared = match new_shared.upgrade() { Some(shared) => shared, None => return, }; let conn = shared.manager.connect().and_then(|mut conn| { shared .config .connection_customizer .on_acquire(&mut conn) .map(|_| conn) }); match conn { Ok(conn) => { let id = CONNECTION_ID.fetch_add(1, Ordering::Relaxed) as u64; let event = AcquireEvent { id }; shared.config.event_handler.handle_acquire(event); let mut internals = shared.internals.lock(); internals.last_error = None; let now = Instant::now(); let conn = IdleConn { conn: Conn { conn, extensions: Extensions::new(), birth: now, id, }, idle_start: now, }; internals.conns.push(conn); internals.pending_conns -= 1; internals.num_conns += 1; shared.cond.notify_one(); } Err(err) => { shared.internals.lock().last_error = Some(err.to_string()); shared.config.error_handler.handle_error(err); let delay = cmp::max(Duration::from_millis(200), delay); let delay = cmp::min(shared.config.connection_timeout / 2, delay * 2); inner(delay, &shared); } } }); } } fn reap_connections(shared: &Weak>) where M: ManageConnection, { let shared = match shared.upgrade() { Some(shared) => shared, None => return, }; let mut old = Vec::with_capacity(shared.config.max_size as usize); let mut to_drop = vec![]; let mut internals = shared.internals.lock(); mem::swap(&mut old, &mut internals.conns); let now = Instant::now(); for conn in old { let mut reap = false; if let Some(timeout) = shared.config.idle_timeout { reap |= now - conn.idle_start >= timeout; } if let Some(lifetime) = shared.config.max_lifetime { reap |= now - conn.conn.birth >= lifetime; } if reap { to_drop.push(conn.conn); } else { internals.conns.push(conn); } } drop_conns(&shared, internals, to_drop); } /// A generic connection pool. pub struct Pool(Arc>) where M: ManageConnection; /// Returns a new `Pool` referencing the same state as `self`. impl Clone for Pool where M: ManageConnection, { fn clone(&self) -> Pool { Pool(self.0.clone()) } } impl fmt::Debug for Pool where M: ManageConnection + fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Pool") .field("state", &self.state()) .field("config", &self.0.config) .field("manager", &self.0.manager) .finish() } } impl Pool where M: ManageConnection, { /// Creates a new connection pool with a default configuration. pub fn new(manager: M) -> Result, Error> { Pool::builder().build(manager) } /// Returns a builder type to configure a new pool. pub fn builder() -> Builder { Builder::new() } // for testing fn new_inner( config: Config, manager: M, reaper_rate: Duration, ) -> Pool { let internals = PoolInternals { conns: Vec::with_capacity(config.max_size as usize), num_conns: 0, pending_conns: 0, last_error: None, }; let shared = Arc::new(SharedPool { config, manager, internals: Mutex::new(internals), cond: Condvar::new(), }); establish_idle_connections(&shared, &mut shared.internals.lock()); if shared.config.max_lifetime.is_some() || shared.config.idle_timeout.is_some() { let s = Arc::downgrade(&shared); shared .config .thread_pool .execute_at_fixed_rate(reaper_rate, reaper_rate, move || reap_connections(&s)); } Pool(shared) } fn wait_for_initialization(&self) -> Result<(), Error> { let end = Instant::now() + self.0.config.connection_timeout; let mut internals = self.0.internals.lock(); let initial_size = self.0.config.min_idle.unwrap_or(self.0.config.max_size); while internals.num_conns != initial_size { if self.0.cond.wait_until(&mut internals, end).timed_out() { return Err(Error(internals.last_error.take())); } } Ok(()) } /// Retrieves a connection from the pool. /// /// Waits for at most the configured connection timeout before returning an /// error. pub fn get(&self) -> Result, Error> { self.get_timeout(self.0.config.connection_timeout) } /// Retrieves a connection from the pool, waiting for at most `timeout` /// /// The given timeout will be used instead of the configured connection /// timeout. pub fn get_timeout(&self, timeout: Duration) -> Result, Error> { let start = Instant::now(); let end = start + timeout; let mut internals = self.0.internals.lock(); loop { match self.try_get_inner(internals) { Ok(conn) => { let event = CheckoutEvent { id: conn.conn.as_ref().unwrap().id, duration: start.elapsed(), }; self.0.config.event_handler.handle_checkout(event); return Ok(conn); } Err(i) => internals = i, } add_connection(&self.0, &mut internals); if self.0.cond.wait_until(&mut internals, end).timed_out() { let event = TimeoutEvent { timeout }; self.0.config.event_handler.handle_timeout(event); return Err(Error(internals.last_error.take())); } } } /// Attempts to retrieve a connection from the pool if there is one /// available. /// /// Returns `None` if there are no idle connections available in the pool. /// This method will not block waiting to establish a new connection. pub fn try_get(&self) -> Option> { self.try_get_inner(self.0.internals.lock()).ok() } fn try_get_inner<'a>( &'a self, mut internals: MutexGuard<'a, PoolInternals>, ) -> Result, MutexGuard<'a, PoolInternals>> { loop { if let Some(mut conn) = internals.conns.pop() { establish_idle_connections(&self.0, &mut internals); drop(internals); if self.0.config.test_on_check_out { if let Err(e) = self.0.manager.is_valid(&mut conn.conn.conn) { let msg = e.to_string(); self.0.config.error_handler.handle_error(e); // FIXME we shouldn't have to lock, unlock, and relock here internals = self.0.internals.lock(); internals.last_error = Some(msg); drop_conns(&self.0, internals, vec![conn.conn]); internals = self.0.internals.lock(); continue; } } return Ok(PooledConnection { pool: self.clone(), checkout: Instant::now(), conn: Some(conn.conn), }); } else { return Err(internals); } } } fn put_back(&self, checkout: Instant, mut conn: Conn) { let event = CheckinEvent { id: conn.id, duration: checkout.elapsed(), }; self.0.config.event_handler.handle_checkin(event); // This is specified to be fast, but call it before locking anyways let broken = self.0.manager.has_broken(&mut conn.conn); let mut internals = self.0.internals.lock(); if broken { drop_conns(&self.0, internals, vec![conn]); } else { let conn = IdleConn { conn, idle_start: Instant::now(), }; internals.conns.push(conn); self.0.cond.notify_one(); } } /// Returns information about the current state of the pool. pub fn state(&self) -> State { let internals = self.0.internals.lock(); State { connections: internals.num_conns, idle_connections: internals.conns.len() as u32, _p: (), } } /// Returns the configured maximum pool size. pub fn max_size(&self) -> u32 { self.0.config.max_size } /// Returns the configured mimimum idle connection count. pub fn min_idle(&self) -> Option { self.0.config.min_idle } /// Returns if the pool is configured to test connections on check out. pub fn test_on_check_out(&self) -> bool { self.0.config.test_on_check_out } /// Returns the configured maximum connection lifetime. pub fn max_lifetime(&self) -> Option { self.0.config.max_lifetime } /// Returns the configured idle connection timeout. pub fn idle_timeout(&self) -> Option { self.0.config.idle_timeout } /// Returns the configured connection timeout. pub fn connection_timeout(&self) -> Duration { self.0.config.connection_timeout } } /// The error type returned by methods in this crate. #[derive(Debug)] pub struct Error(Option); impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(error::Error::description(self))?; if let Some(ref err) = self.0 { write!(fmt, ": {}", err)?; } Ok(()) } } impl error::Error for Error { fn description(&self) -> &str { "timed out waiting for connection" } } /// Information about the state of a `Pool`. pub struct State { /// The number of connections currently being managed by the pool. pub connections: u32, /// The number of idle connections. pub idle_connections: u32, _p: (), } impl fmt::Debug for State { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("State") .field("connections", &self.connections) .field("idle_connections", &self.idle_connections) .finish() } } /// A smart pointer wrapping a connection. pub struct PooledConnection where M: ManageConnection, { pool: Pool, checkout: Instant, conn: Option>, } impl fmt::Debug for PooledConnection where M: ManageConnection, M::Connection: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.conn.as_ref().unwrap().conn, fmt) } } impl Drop for PooledConnection where M: ManageConnection, { fn drop(&mut self) { self.pool.put_back(self.checkout, self.conn.take().unwrap()); } } impl Deref for PooledConnection where M: ManageConnection, { type Target = M::Connection; fn deref(&self) -> &M::Connection { &self.conn.as_ref().unwrap().conn } } impl DerefMut for PooledConnection where M: ManageConnection, { fn deref_mut(&mut self) -> &mut M::Connection { &mut self.conn.as_mut().unwrap().conn } } impl PooledConnection where M: ManageConnection, { /// Returns a shared reference to the extensions associated with this connection. pub fn extensions(this: &Self) -> &Extensions { &this.conn.as_ref().unwrap().extensions } /// Returns a mutable reference to the extensions associated with this connection. pub fn extensions_mut(this: &mut Self) -> &mut Extensions { &mut this.conn.as_mut().unwrap().extensions } } r2d2-0.8.10/src/test.rs000064400000000000000000000431720072674642500126360ustar 00000000000000use parking_lot::Mutex; use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}; use std::sync::mpsc::{self, Receiver, SyncSender}; use std::sync::Arc; use std::time::{Duration, Instant}; use std::{error, fmt, mem, thread}; use crate::event::{AcquireEvent, CheckinEvent, CheckoutEvent, ReleaseEvent, TimeoutEvent}; use crate::{CustomizeConnection, HandleEvent, ManageConnection, Pool, PooledConnection}; #[derive(Debug)] pub struct Error; impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str("blammo") } } impl error::Error for Error { fn description(&self) -> &str { "Error" } } #[derive(Debug, PartialEq)] struct FakeConnection(bool); struct OkManager; impl ManageConnection for OkManager { type Connection = FakeConnection; type Error = Error; fn connect(&self) -> Result { Ok(FakeConnection(true)) } fn is_valid(&self, _: &mut FakeConnection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut FakeConnection) -> bool { false } } struct NthConnectFailManager { n: Mutex, } impl ManageConnection for NthConnectFailManager { type Connection = FakeConnection; type Error = Error; fn connect(&self) -> Result { let mut n = self.n.lock(); if *n > 0 { *n -= 1; Ok(FakeConnection(true)) } else { Err(Error) } } fn is_valid(&self, _: &mut FakeConnection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut FakeConnection) -> bool { false } } #[test] fn test_max_size_ok() { let manager = NthConnectFailManager { n: Mutex::new(5) }; let pool = Pool::builder().max_size(5).build(manager).unwrap(); let mut conns = vec![]; for _ in 0..5 { conns.push(pool.get().ok().unwrap()); } } #[test] fn test_acquire_release() { let pool = Pool::builder().max_size(2).build(OkManager).unwrap(); let conn1 = pool.get().ok().unwrap(); let conn2 = pool.get().ok().unwrap(); drop(conn1); let conn3 = pool.get().ok().unwrap(); drop(conn2); drop(conn3); } #[test] fn try_get() { let pool = Pool::builder().max_size(2).build(OkManager).unwrap(); let conn1 = pool.try_get(); let conn2 = pool.try_get(); let conn3 = pool.try_get(); assert!(conn1.is_some()); assert!(conn2.is_some()); assert!(conn3.is_none()); drop(conn1); assert!(pool.try_get().is_some()); } #[test] fn get_timeout() { let pool = Pool::builder() .max_size(1) .connection_timeout(Duration::from_millis(500)) .build(OkManager) .unwrap(); let timeout = Duration::from_millis(100); let succeeds_immediately = pool.get_timeout(timeout); assert!(succeeds_immediately.is_ok()); thread::spawn(move || { thread::sleep(Duration::from_millis(50)); drop(succeeds_immediately); }); let succeeds_delayed = pool.get_timeout(timeout); assert!(succeeds_delayed.is_ok()); thread::spawn(move || { thread::sleep(Duration::from_millis(150)); drop(succeeds_delayed); }); let fails = pool.get_timeout(timeout); assert!(fails.is_err()); } #[test] fn test_is_send_sync() { fn is_send_sync() {} is_send_sync::>(); } #[test] fn test_issue_2_unlocked_during_is_valid() { struct BlockingChecker { first: AtomicBool, s: Mutex>, r: Mutex>, } impl ManageConnection for BlockingChecker { type Connection = FakeConnection; type Error = Error; fn connect(&self) -> Result { Ok(FakeConnection(true)) } fn is_valid(&self, _: &mut FakeConnection) -> Result<(), Error> { if self.first.compare_and_swap(true, false, Ordering::SeqCst) { self.s.lock().send(()).unwrap(); self.r.lock().recv().unwrap(); } Ok(()) } fn has_broken(&self, _: &mut FakeConnection) -> bool { false } } let (s1, r1) = mpsc::sync_channel(0); let (s2, r2) = mpsc::sync_channel(0); let manager = BlockingChecker { first: AtomicBool::new(true), s: Mutex::new(s1), r: Mutex::new(r2), }; let pool = Pool::builder() .test_on_check_out(true) .max_size(2) .build(manager) .unwrap(); let p2 = pool.clone(); let t = thread::spawn(move || { p2.get().ok().unwrap(); }); r1.recv().unwrap(); // get call by other task has triggered the health check pool.get().ok().unwrap(); s2.send(()).ok().unwrap(); t.join().ok().unwrap(); } #[test] fn test_drop_on_broken() { static DROPPED: AtomicBool = AtomicBool::new(false); DROPPED.store(false, Ordering::SeqCst); struct Connection; impl Drop for Connection { fn drop(&mut self) { DROPPED.store(true, Ordering::SeqCst); } } struct Handler; impl ManageConnection for Handler { type Connection = Connection; type Error = Error; fn connect(&self) -> Result { Ok(Connection) } fn is_valid(&self, _: &mut Connection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut Connection) -> bool { true } } let pool = Pool::new(Handler).unwrap(); drop(pool.get().ok().unwrap()); assert!(DROPPED.load(Ordering::SeqCst)); } #[test] fn test_initialization_failure() { let manager = NthConnectFailManager { n: Mutex::new(0) }; let err = Pool::builder() .connection_timeout(Duration::from_secs(1)) .build(manager) .err() .unwrap(); assert!(err.to_string().contains("blammo")); } #[test] fn test_lazy_initialization_failure() { let manager = NthConnectFailManager { n: Mutex::new(0) }; let pool = Pool::builder() .connection_timeout(Duration::from_secs(1)) .build_unchecked(manager); let err = pool.get().err().unwrap(); assert!(err.to_string().contains("blammo")); } #[test] fn test_get_global_timeout() { let pool = Pool::builder() .max_size(1) .connection_timeout(Duration::from_secs(1)) .build(OkManager) .unwrap(); let _c = pool.get().unwrap(); let started_waiting = Instant::now(); pool.get().err().unwrap(); // Elapsed time won't be *exactly* 1 second, but it will certainly be // less than 2 seconds assert_eq!(started_waiting.elapsed().as_secs(), 1); } #[test] fn test_connection_customizer() { static RELEASED: AtomicBool = AtomicBool::new(false); RELEASED.store(false, Ordering::SeqCst); static DROPPED: AtomicBool = AtomicBool::new(false); DROPPED.store(false, Ordering::SeqCst); struct Connection(i32); impl Drop for Connection { fn drop(&mut self) { DROPPED.store(true, Ordering::SeqCst); } } struct Handler; impl ManageConnection for Handler { type Connection = Connection; type Error = Error; fn connect(&self) -> Result { Ok(Connection(0)) } fn is_valid(&self, _: &mut Connection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut Connection) -> bool { true } } #[derive(Debug)] struct Customizer; impl CustomizeConnection for Customizer { fn on_acquire(&self, conn: &mut Connection) -> Result<(), Error> { if !DROPPED.load(Ordering::SeqCst) { Err(Error) } else { conn.0 = 1; Ok(()) } } fn on_release(&self, _: Connection) { RELEASED.store(true, Ordering::SeqCst); } } let pool = Pool::builder() .connection_customizer(Box::new(Customizer)) .build(Handler) .unwrap(); { let conn = pool.get().unwrap(); assert_eq!(1, conn.0); assert!(!RELEASED.load(Ordering::SeqCst)); assert!(DROPPED.load(Ordering::SeqCst)); } assert!(RELEASED.load(Ordering::SeqCst)); } #[test] fn test_idle_timeout() { static DROPPED: AtomicUsize = AtomicUsize::new(0); struct Connection; impl Drop for Connection { fn drop(&mut self) { DROPPED.fetch_add(1, Ordering::SeqCst); } } struct Handler(AtomicIsize); impl ManageConnection for Handler { type Connection = Connection; type Error = Error; fn connect(&self) -> Result { if self.0.fetch_sub(1, Ordering::SeqCst) > 0 { Ok(Connection) } else { Err(Error) } } fn is_valid(&self, _: &mut Connection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut Connection) -> bool { false } } let pool = Pool::builder() .max_size(5) .idle_timeout(Some(Duration::from_secs(1))) .reaper_rate(Duration::from_secs(1)) .build(Handler(AtomicIsize::new(5))) .unwrap(); let conn = pool.get().unwrap(); thread::sleep(Duration::from_secs(2)); assert_eq!(4, DROPPED.load(Ordering::SeqCst)); drop(conn); assert_eq!(4, DROPPED.load(Ordering::SeqCst)); } #[test] fn idle_timeout_partial_use() { static DROPPED: AtomicUsize = AtomicUsize::new(0); struct Connection; impl Drop for Connection { fn drop(&mut self) { DROPPED.fetch_add(1, Ordering::SeqCst); } } struct Handler(AtomicIsize); impl ManageConnection for Handler { type Connection = Connection; type Error = Error; fn connect(&self) -> Result { if self.0.fetch_sub(1, Ordering::SeqCst) > 0 { Ok(Connection) } else { Err(Error) } } fn is_valid(&self, _: &mut Connection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut Connection) -> bool { false } } let pool = Pool::builder() .max_size(5) .idle_timeout(Some(Duration::from_secs(1))) .reaper_rate(Duration::from_secs(1)) .build(Handler(AtomicIsize::new(5))) .unwrap(); for _ in 0..8 { thread::sleep(Duration::from_millis(250)); pool.get().unwrap(); } assert_eq!(4, DROPPED.load(Ordering::SeqCst)); assert_eq!(1, pool.state().connections); } #[test] fn test_max_lifetime() { static DROPPED: AtomicUsize = AtomicUsize::new(0); struct Connection; impl Drop for Connection { fn drop(&mut self) { DROPPED.fetch_add(1, Ordering::SeqCst); } } struct Handler(AtomicIsize); impl ManageConnection for Handler { type Connection = Connection; type Error = Error; fn connect(&self) -> Result { if self.0.fetch_sub(1, Ordering::SeqCst) > 0 { Ok(Connection) } else { Err(Error) } } fn is_valid(&self, _: &mut Connection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut Connection) -> bool { false } } let pool = Pool::builder() .max_size(5) .max_lifetime(Some(Duration::from_secs(1))) .connection_timeout(Duration::from_secs(1)) .reaper_rate(Duration::from_secs(1)) .build(Handler(AtomicIsize::new(5))) .unwrap(); let conn = pool.get().unwrap(); thread::sleep(Duration::from_secs(2)); assert_eq!(4, DROPPED.load(Ordering::SeqCst)); drop(conn); thread::sleep(Duration::from_secs(2)); assert_eq!(5, DROPPED.load(Ordering::SeqCst)); assert!(pool.get().is_err()); } #[test] fn min_idle() { struct Connection; struct Handler; impl ManageConnection for Handler { type Connection = Connection; type Error = Error; fn connect(&self) -> Result { Ok(Connection) } fn is_valid(&self, _: &mut Connection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut Connection) -> bool { false } } let pool = Pool::builder() .max_size(5) .min_idle(Some(2)) .build(Handler) .unwrap(); thread::sleep(Duration::from_secs(1)); assert_eq!(2, pool.state().idle_connections); assert_eq!(2, pool.state().connections); let conns = (0..3).map(|_| pool.get().unwrap()).collect::>(); thread::sleep(Duration::from_secs(1)); assert_eq!(2, pool.state().idle_connections); assert_eq!(5, pool.state().connections); mem::drop(conns); assert_eq!(5, pool.state().idle_connections); assert_eq!(5, pool.state().connections); } #[test] fn conns_drop_on_pool_drop() { static DROPPED: AtomicUsize = AtomicUsize::new(0); struct Connection; impl Drop for Connection { fn drop(&mut self) { DROPPED.fetch_add(1, Ordering::SeqCst); } } struct Handler; impl ManageConnection for Handler { type Connection = Connection; type Error = Error; fn connect(&self) -> Result { Ok(Connection) } fn is_valid(&self, _: &mut Connection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut Connection) -> bool { false } } let pool = Pool::builder() .max_lifetime(Some(Duration::from_secs(10))) .max_size(10) .build(Handler) .unwrap(); drop(pool); for _ in 0..10 { if DROPPED.load(Ordering::SeqCst) == 10 { return; } thread::sleep(Duration::from_secs(1)); } panic!("timed out waiting for connections to drop"); } #[test] fn events() { #[derive(Debug)] enum Event { Acquire(AcquireEvent), Release(ReleaseEvent), Checkout(CheckoutEvent), Checkin(CheckinEvent), Timeout(TimeoutEvent), } #[derive(Debug)] struct TestEventHandler(Arc>>); impl HandleEvent for TestEventHandler { fn handle_acquire(&self, event: AcquireEvent) { self.0.lock().push(Event::Acquire(event)); } fn handle_release(&self, event: ReleaseEvent) { self.0.lock().push(Event::Release(event)); } fn handle_checkout(&self, event: CheckoutEvent) { self.0.lock().push(Event::Checkout(event)); } fn handle_timeout(&self, event: TimeoutEvent) { self.0.lock().push(Event::Timeout(event)); } fn handle_checkin(&self, event: CheckinEvent) { self.0.lock().push(Event::Checkin(event)); } } struct TestConnection; struct TestConnectionManager; impl ManageConnection for TestConnectionManager { type Connection = TestConnection; type Error = Error; fn connect(&self) -> Result { Ok(TestConnection) } fn is_valid(&self, _: &mut TestConnection) -> Result<(), Error> { Ok(()) } fn has_broken(&self, _: &mut TestConnection) -> bool { true } } let events = Arc::new(Mutex::new(vec![])); let creation = Instant::now(); let pool = Pool::builder() .max_size(1) .connection_timeout(Duration::from_millis(250)) .event_handler(Box::new(TestEventHandler(events.clone()))) .build(TestConnectionManager) .unwrap(); let start = Instant::now(); let conn = pool.get().unwrap(); let checkout = start.elapsed(); pool.get_timeout(Duration::from_millis(123)).err().unwrap(); drop(conn); let checkin = start.elapsed(); let release = creation.elapsed(); let _conn2 = pool.get().unwrap(); let events = events.lock(); let id = match events[0] { Event::Acquire(ref event) => event.connection_id(), _ => unreachable!(), }; match events[1] { Event::Checkout(ref event) => { assert_eq!(event.connection_id(), id); assert!(event.duration() <= checkout); } _ => unreachable!(), } match events[2] { Event::Timeout(ref event) => assert_eq!(event.timeout(), Duration::from_millis(123)), _ => unreachable!(), } match events[3] { Event::Checkin(ref event) => { assert_eq!(event.connection_id(), id); assert!(event.duration() <= checkin); } _ => unreachable!(), } match events[4] { Event::Release(ref event) => { assert_eq!(event.connection_id(), id); assert!(event.age() <= release); } _ => unreachable!(), } let id2 = match events[5] { Event::Acquire(ref event) => event.connection_id(), _ => unreachable!(), }; assert!(id < id2); match events[6] { Event::Checkout(ref event) => assert_eq!(event.connection_id(), id2), _ => unreachable!(), } } #[test] fn extensions() { let pool = Pool::builder().max_size(2).build(OkManager).unwrap(); let mut conn1 = pool.get().unwrap(); let mut conn2 = pool.get().unwrap(); PooledConnection::extensions_mut(&mut conn1).insert(1); PooledConnection::extensions_mut(&mut conn2).insert(2); drop(conn1); let conn = pool.get().unwrap(); assert_eq!(PooledConnection::extensions(&conn).get::(), Some(&1)); }