Changesets · Branches · Tags · Compare
| Changeset | d3aaefc5a7c9ab816f80a9ea24ffc042358f375bcd246b04f6eeeabae1a6f893 |
|---|---|
| Author | Will Jones <willjones127@gmail.com> · 2024-10-01 10:22 -07:00 |
| Committer | GitHub <noreply@github.com> · 2024-10-01 10:22 -07:00 |
| Parents | 003c3ff7b96f |
8 files changed
modified Cargo.toml +2 −0
| @@ -45,10 +45,12 @@ | ||
| 45 | 45 | ] } |
| 46 | 46 | futures = "0" |
| 47 | 47 | log = "0.4" |
| 48 | +moka = { version = "0.11", features = ["future"] } | |
| 48 | 49 | object_store = "0.10.2" |
| 49 | 50 | pin-project = "1.0.7" |
| 50 | 51 | snafu = "0.7.4" |
| 51 | 52 | url = "2" |
| 52 | 53 | num-traits = "0.2" |
| 54 | +rand = "0.8" | |
| 53 | 55 | regex = "1.10" |
| 54 | 56 | lazy_static = "1" |
modified rust/lancedb/Cargo.toml +5 −2
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | lance-linalg = { workspace = true } |
| 33 | 33 | lance-testing = { workspace = true } |
| 34 | 34 | lance-encoding = { workspace = true } |
| 35 | +moka = { workspace = true} | |
| 35 | 36 | pin-project = { workspace = true } |
| 36 | 37 | tokio = { version = "1.23", features = ["rt-multi-thread"] } |
| 37 | 38 | log.workspace = true |
| @@ -47,7 +48,9 @@ | ||
| 47 | 48 | serde_with = { version = "3.8.1" } |
| 48 | 49 | # For remote feature |
| 49 | 50 | reqwest = { version = "0.12.0", features = ["gzip", "json", "stream"], optional = true } |
| 50 | -http = { version = "1", optional = true } # Matching what is in reqwest | |
| 51 | +rand = { version = "0.8.3", features = ["small_rng"], optional = true} | |
| 52 | +http = { version = "1", optional = true } # Matching what is in reqwest | |
| 53 | +uuid = { version = "1.7.0", features = ["v4"], optional = true } | |
| 51 | 54 | polars-arrow = { version = ">=0.37,<0.40.0", optional = true } |
| 52 | 55 | polars = { version = ">=0.37,<0.40.0", optional = true } |
| 53 | 56 | hf-hub = { version = "0.3.2", optional = true } |
| @@ -71,7 +74,7 @@ | ||
| 71 | 74 | |
| 72 | 75 | [features] |
| 73 | 76 | default = [] |
| 74 | -remote = ["dep:reqwest", "dep:http"] | |
| 77 | +remote = ["dep:reqwest", "dep:http", "dep:rand", "dep:uuid"] | |
| 75 | 78 | fp16kernels = ["lance-linalg/fp16kernels"] |
| 76 | 79 | s3-test = [] |
| 77 | 80 | openai = ["dep:async-openai", "dep:reqwest"] |
modified rust/lancedb/src/connection.rs +32 −0
| @@ -32,6 +32,8 @@ | ||
| 32 | 32 | }; |
| 33 | 33 | use crate::error::{CreateDirSnafu, Error, InvalidTableNameSnafu, Result}; |
| 34 | 34 | use crate::io::object_store::MirroringObjectStoreWrapper; |
| 35 | +#[cfg(feature = "remote")] | |
| 36 | +use crate::remote::client::ClientConfig; | |
| 35 | 37 | use crate::table::{NativeTable, TableDefinition, WriteOptions}; |
| 36 | 38 | use crate::utils::validate_table_name; |
| 37 | 39 | use crate::Table; |
| @@ -567,6 +569,8 @@ | ||
| 567 | 569 | region: Option<String>, |
| 568 | 570 | /// LanceDB Cloud host override, only required if using an on-premises Lance Cloud instance |
| 569 | 571 | host_override: Option<String>, |
| 572 | + #[cfg(feature = "remote")] | |
| 573 | + client_config: ClientConfig, | |
| 570 | 574 | |
| 571 | 575 | storage_options: HashMap<String, String>, |
| 572 | 576 | |
| @@ -592,6 +596,8 @@ | ||
| 592 | 596 | api_key: None, |
| 593 | 597 | region: None, |
| 594 | 598 | host_override: None, |
| 599 | + #[cfg(feature = "remote")] | |
| 600 | + client_config: Default::default(), | |
| 595 | 601 | read_consistency_interval: None, |
| 596 | 602 | storage_options: HashMap::new(), |
| 597 | 603 | embedding_registry: None, |
| @@ -613,6 +619,30 @@ | ||
| 613 | 619 | self |
| 614 | 620 | } |
| 615 | 621 | |
| 622 | + /// Set the LanceDB Cloud client configuration. | |
| 623 | + /// | |
| 624 | + /// ``` | |
| 625 | + /// # use lancedb::connect; | |
| 626 | + /// # use lancedb::remote::*; | |
| 627 | + /// connect("db://my_database") | |
| 628 | + /// .client_config(ClientConfig { | |
| 629 | + /// timeout_config: TimeoutConfig { | |
| 630 | + /// connect_timeout: Some(std::time::Duration::from_secs(5)), | |
| 631 | + /// ..Default::default() | |
| 632 | + /// }, | |
| 633 | + /// retry_config: RetryConfig { | |
| 634 | + /// retries: Some(5), | |
| 635 | + /// ..Default::default() | |
| 636 | + /// }, | |
| 637 | + /// ..Default::default() | |
| 638 | + /// }); | |
| 639 | + /// ``` | |
| 640 | + #[cfg(feature = "remote")] | |
| 641 | + pub fn client_config(mut self, config: ClientConfig) -> Self { | |
| 642 | + self.client_config = config; | |
| 643 | + self | |
| 644 | + } | |
| 645 | + | |
| 616 | 646 | /// Provide a custom [`EmbeddingRegistry`] to use for this connection. |
| 617 | 647 | pub fn embedding_registry(mut self, registry: Arc<dyn EmbeddingRegistry>) -> Self { |
| 618 | 648 | self.embedding_registry = Some(registry); |
| @@ -685,12 +715,14 @@ | ||
| 685 | 715 | let api_key = self.api_key.ok_or_else(|| Error::InvalidInput { |
| 686 | 716 | message: "An api_key is required when connecting to LanceDb Cloud".to_string(), |
| 687 | 717 | })?; |
| 718 | + // TODO: remove this warning when the remote client is ready | |
| 688 | 719 | warn!("The rust implementation of the remote client is not yet ready for use."); |
| 689 | 720 | let internal = Arc::new(crate::remote::db::RemoteDatabase::try_new( |
| 690 | 721 | &self.uri, |
| 691 | 722 | &api_key, |
| 692 | 723 | ®ion, |
| 693 | 724 | self.host_override, |
| 725 | + self.client_config, | |
| 694 | 726 | )?); |
| 695 | 727 | Ok(Connection { |
| 696 | 728 | internal, |
modified rust/lancedb/src/lib.rs +1 −1
| @@ -213,7 +213,7 @@ | ||
| 213 | 213 | mod polars_arrow_convertors; |
| 214 | 214 | pub mod query; |
| 215 | 215 | #[cfg(feature = "remote")] |
| 216 | -pub(crate) mod remote; | |
| 216 | +pub mod remote; | |
| 217 | 217 | pub mod table; |
| 218 | 218 | pub mod utils; |
| 219 | 219 |
modified rust/lancedb/src/remote.rs +6 −4
| @@ -17,10 +17,12 @@ | ||
| 17 | 17 | //! building client/server applications with LanceDB or as a client for some |
| 18 | 18 | //! other custom LanceDB service. |
| 19 | 19 | |
| 20 | -pub mod client; | |
| 21 | -pub mod db; | |
| 22 | -pub mod table; | |
| 23 | -pub mod util; | |
| 20 | +pub(crate) mod client; | |
| 21 | +pub(crate) mod db; | |
| 22 | +pub(crate) mod table; | |
| 23 | +pub(crate) mod util; | |
| 24 | 24 | |
| 25 | 25 | const ARROW_STREAM_CONTENT_TYPE: &str = "application/vnd.apache.arrow.stream"; |
| 26 | 26 | const JSON_CONTENT_TYPE: &str = "application/json"; |
| 27 | + | |
| 28 | +pub use client::{ClientConfig, RetryConfig, TimeoutConfig}; |
modified rust/lancedb/src/remote/client.rs +295 −9
| @@ -14,13 +14,152 @@ | ||
| 14 | 14 | |
| 15 | 15 | use std::{future::Future, time::Duration}; |
| 16 | 16 | |
| 17 | +use log::debug; | |
| 17 | 18 | use reqwest::{ |
| 18 | 19 | header::{HeaderMap, HeaderValue}, |
| 19 | - RequestBuilder, Response, | |
| 20 | + Request, RequestBuilder, Response, | |
| 20 | 21 | }; |
| 21 | 22 | |
| 22 | 23 | use crate::error::{Error, Result}; |
| 23 | 24 | |
| 25 | +const REQUEST_ID_HEADER: &str = "x-request-id"; | |
| 26 | + | |
| 27 | +/// Configuration for the LanceDB Cloud HTTP client. | |
| 28 | +#[derive(Debug)] | |
| 29 | +pub struct ClientConfig { | |
| 30 | + pub timeout_config: TimeoutConfig, | |
| 31 | + pub retry_config: RetryConfig, | |
| 32 | + /// User agent to use for requests. The default provides the libary | |
| 33 | + /// name and version. | |
| 34 | + pub user_agent: String, | |
| 35 | + // TODO: how to configure request ids? | |
| 36 | +} | |
| 37 | + | |
| 38 | +impl Default for ClientConfig { | |
| 39 | + fn default() -> Self { | |
| 40 | + Self { | |
| 41 | + timeout_config: TimeoutConfig::default(), | |
| 42 | + retry_config: RetryConfig::default(), | |
| 43 | + user_agent: concat!("LanceDB-Rust-Client/", env!("CARGO_PKG_VERSION")).into(), | |
| 44 | + } | |
| 45 | + } | |
| 46 | +} | |
| 47 | + | |
| 48 | +/// How to handle timeouts for HTTP requests. | |
| 49 | +#[derive(Default, Debug)] | |
| 50 | +pub struct TimeoutConfig { | |
| 51 | + /// The timeout for creating a connection to the server. | |
| 52 | + /// | |
| 53 | + /// You can also set the `LANCE_CLIENT_CONNECT_TIMEOUT` environment variable | |
| 54 | + /// to set this value. Use an integer value in seconds. | |
| 55 | + /// | |
| 56 | + /// The default is 120 seconds (2 minutes). | |
| 57 | + pub connect_timeout: Option<Duration>, | |
| 58 | + /// The timeout for reading a response from the server. | |
| 59 | + /// | |
| 60 | + /// You can also set the `LANCE_CLIENT_READ_TIMEOUT` environment variable | |
| 61 | + /// to set this value. Use an integer value in seconds. | |
| 62 | + /// | |
| 63 | + /// The default is 300 seconds (5 minutes). | |
| 64 | + pub read_timeout: Option<Duration>, | |
| 65 | + /// The timeout for keeping idle connections alive. | |
| 66 | + /// | |
| 67 | + /// You can also set the `LANCE_CLIENT_CONNECTION_TIMEOUT` environment variable | |
| 68 | + /// to set this value. Use an integer value in seconds. | |
| 69 | + /// | |
| 70 | + /// The default is 300 seconds (5 minutes). | |
| 71 | + pub pool_idle_timeout: Option<Duration>, | |
| 72 | +} | |
| 73 | + | |
| 74 | +/// How to handle retries for HTTP requests. | |
| 75 | +#[derive(Default, Debug)] | |
| 76 | +pub struct RetryConfig { | |
| 77 | + /// The number of times to retry a request if it fails. | |
| 78 | + /// | |
| 79 | + /// You can also set the `LANCE_CLIENT_MAX_RETRIES` environment variable | |
| 80 | + /// to set this value. Use an integer value. | |
| 81 | + /// | |
| 82 | + /// The default is 3 retries. | |
| 83 | + pub retries: Option<u8>, | |
| 84 | + /// The number of times to retry a request if it fails to connect. | |
| 85 | + /// | |
| 86 | + /// You can also set the `LANCE_CLIENT_CONNECT_RETRIES` environment variable | |
| 87 | + /// to set this value. Use an integer value. | |
| 88 | + /// | |
| 89 | + /// The default is 3 retries. | |
| 90 | + pub connect_retries: Option<u8>, | |
| 91 | + /// The number of times to retry a request if it fails to read. | |
| 92 | + /// | |
| 93 | + /// You can also set the `LANCE_CLIENT_READ_RETRIES` environment variable | |
| 94 | + /// to set this value. Use an integer value. | |
| 95 | + /// | |
| 96 | + /// The default is 3 retries. | |
| 97 | + pub read_retries: Option<u8>, | |
| 98 | + /// The exponential backoff factor to use when retrying requests. | |
| 99 | + /// | |
| 100 | + /// Between each retry, the client will wait for the amount of seconds: | |
| 101 | + /// | |
| 102 | + /// ```text | |
| 103 | + /// {backoff factor} * (2 ** ({number of previous retries})) | |
| 104 | + /// ``` | |
| 105 | + /// | |
| 106 | + /// You can also set the `LANCE_CLIENT_RETRY_BACKOFF_FACTOR` environment variable | |
| 107 | + /// to set this value. Use a float value. | |
| 108 | + /// | |
| 109 | + /// The default is 0.25. So the first retry will wait 0.25 seconds, the second | |
| 110 | + /// retry will wait 0.5 seconds, the third retry will wait 1 second, etc. | |
| 111 | + pub backoff_factor: Option<f32>, | |
| 112 | + /// The backoff jitter factor to use when retrying requests. | |
| 113 | + /// | |
| 114 | + /// The backoff jitter is a random value between 0 and the jitter factor in | |
| 115 | + /// seconds. | |
| 116 | + /// | |
| 117 | + /// You can also set the `LANCE_CLIENT_RETRY_BACKOFF_JITTER` environment variable | |
| 118 | + /// to set this value. Use a float value. | |
| 119 | + /// | |
| 120 | + /// The default is 0.25. So between 0 and 0.25 seconds will be added to the | |
| 121 | + /// sleep time between retries. | |
| 122 | + pub backoff_jitter: Option<f32>, | |
| 123 | + /// The set of status codes to retry on. | |
| 124 | + /// | |
| 125 | + /// You can also set the `LANCE_CLIENT_RETRY_STATUSES` environment variable | |
| 126 | + /// to set this value. Use a comma-separated list of integer values. | |
| 127 | + /// | |
| 128 | + /// The default is 429, 500, 502, 503. | |
| 129 | + pub statuses: Option<Vec<u16>>, | |
| 130 | + // TODO: should we allow customizing methods? | |
| 131 | +} | |
| 132 | + | |
| 133 | +#[derive(Debug, Clone)] | |
| 134 | +struct ResolvedRetryConfig { | |
| 135 | + retries: u8, | |
| 136 | + connect_retries: u8, | |
| 137 | + read_retries: u8, | |
| 138 | + backoff_factor: f32, | |
| 139 | + backoff_jitter: f32, | |
| 140 | + statuses: Vec<reqwest::StatusCode>, | |
| 141 | +} | |
| 142 | + | |
| 143 | +impl TryFrom<RetryConfig> for ResolvedRetryConfig { | |
| 144 | + type Error = Error; | |
| 145 | + | |
| 146 | + fn try_from(retry_config: RetryConfig) -> Result<Self> { | |
| 147 | + Ok(Self { | |
| 148 | + retries: retry_config.retries.unwrap_or(3), | |
| 149 | + connect_retries: retry_config.connect_retries.unwrap_or(3), | |
| 150 | + read_retries: retry_config.read_retries.unwrap_or(3), | |
| 151 | + backoff_factor: retry_config.backoff_factor.unwrap_or(0.25), | |
| 152 | + backoff_jitter: retry_config.backoff_jitter.unwrap_or(0.25), | |
| 153 | + statuses: retry_config | |
| 154 | + .statuses | |
| 155 | + .unwrap_or_else(|| vec![429, 500, 502, 503]) | |
| 156 | + .into_iter() | |
| 157 | + .map(|status| reqwest::StatusCode::from_u16(status).unwrap()) | |
| 158 | + .collect(), | |
| 159 | + }) | |
| 160 | + } | |
| 161 | +} | |
| 162 | + | |
| 24 | 163 | // We use the `HttpSend` trait to abstract over the `reqwest::Client` so that |
| 25 | 164 | // we can mock responses in tests. Based on the patterns from this blog post: |
| 26 | 165 | // https://write.as/balrogboogie/testing-reqwest-based-clients |
| @@ -28,28 +167,54 @@ | ||
| 28 | 167 | pub struct RestfulLanceDbClient<S: HttpSend = Sender> { |
| 29 | 168 | client: reqwest::Client, |
| 30 | 169 | host: String, |
| 170 | + retry_config: ResolvedRetryConfig, | |
| 31 | 171 | sender: S, |
| 32 | 172 | } |
| 33 | 173 | |
| 34 | 174 | pub trait HttpSend: Clone + Send + Sync + std::fmt::Debug + 'static { |
| 35 | - fn send(&self, req: RequestBuilder) -> impl Future<Output = Result<Response>> + Send; | |
| 175 | + fn send( | |
| 176 | + &self, | |
| 177 | + client: &reqwest::Client, | |
| 178 | + request: reqwest::Request, | |
| 179 | + ) -> impl Future<Output = reqwest::Result<Response>> + Send; | |
| 36 | 180 | } |
| 37 | 181 | |
| 38 | 182 | // Default implementation of HttpSend which sends the request normally with reqwest |
| 39 | 183 | #[derive(Clone, Debug)] |
| 40 | 184 | pub struct Sender; |
| 41 | 185 | impl HttpSend for Sender { |
| 42 | - async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> { | |
| 43 | - Ok(request.send().await?) | |
| 186 | + async fn send( | |
| 187 | + &self, | |
| 188 | + client: &reqwest::Client, | |
| 189 | + request: reqwest::Request, | |
| 190 | + ) -> reqwest::Result<reqwest::Response> { | |
| 191 | + client.execute(request).await | |
| 44 | 192 | } |
| 45 | 193 | } |
| 46 | 194 | |
| 47 | 195 | impl RestfulLanceDbClient<Sender> { |
| 196 | + fn get_timeout(passed: Option<Duration>, env_var: &str, default: Duration) -> Result<Duration> { | |
| 197 | + if let Some(passed) = passed { | |
| 198 | + Ok(passed) | |
| 199 | + } else if let Ok(timeout) = std::env::var(env_var) { | |
| 200 | + let timeout = timeout.parse::<u64>().map_err(|_| Error::InvalidInput { | |
| 201 | + message: format!( | |
| 202 | + "Invalid value for {} environment variable: '{}'", | |
| 203 | + env_var, timeout | |
| 204 | + ), | |
| 205 | + })?; | |
| 206 | + Ok(Duration::from_secs(timeout)) | |
| 207 | + } else { | |
| 208 | + Ok(default) | |
| 209 | + } | |
| 210 | + } | |
| 211 | + | |
| 48 | 212 | pub fn try_new( |
| 49 | 213 | db_url: &str, |
| 50 | 214 | api_key: &str, |
| 51 | 215 | region: &str, |
| 52 | 216 | host_override: Option<String>, |
| 217 | + client_config: ClientConfig, | |
| 53 | 218 | ) -> Result<Self> { |
| 54 | 219 | let parsed_url = url::Url::parse(db_url)?; |
| 55 | 220 | debug_assert_eq!(parsed_url.scheme(), "db"); |
| @@ -59,22 +224,47 @@ | ||
| 59 | 224 | }); |
| 60 | 225 | } |
| 61 | 226 | let db_name = parsed_url.host_str().unwrap(); |
| 227 | + | |
| 228 | + // Get the timeouts | |
| 229 | + let connect_timeout = Self::get_timeout( | |
| 230 | + client_config.timeout_config.connect_timeout, | |
| 231 | + "LANCE_CLIENT_CONNECT_TIMEOUT", | |
| 232 | + Duration::from_secs(120), | |
| 233 | + )?; | |
| 234 | + let read_timeout = Self::get_timeout( | |
| 235 | + client_config.timeout_config.read_timeout, | |
| 236 | + "LANCE_CLIENT_READ_TIMEOUT", | |
| 237 | + Duration::from_secs(300), | |
| 238 | + )?; | |
| 239 | + let pool_idle_timeout = Self::get_timeout( | |
| 240 | + client_config.timeout_config.pool_idle_timeout, | |
| 241 | + // Though it's confusing with the connect_timeout name, this is the | |
| 242 | + // legacy name for this in the Python sync client. So we keep as-is. | |
| 243 | + "LANCE_CLIENT_CONNECTION_TIMEOUT", | |
| 244 | + Duration::from_secs(300), | |
| 245 | + )?; | |
| 246 | + | |
| 62 | 247 | let client = reqwest::Client::builder() |
| 63 | - .timeout(Duration::from_secs(30)) | |
| 248 | + .connect_timeout(connect_timeout) | |
| 249 | + .read_timeout(read_timeout) | |
| 250 | + .pool_idle_timeout(pool_idle_timeout) | |
| 64 | 251 | .default_headers(Self::default_headers( |
| 65 | 252 | api_key, |
| 66 | 253 | region, |
| 67 | 254 | db_name, |
| 68 | 255 | host_override.is_some(), |
| 69 | 256 | )?) |
| 257 | + .user_agent(client_config.user_agent) | |
| 70 | 258 | .build()?; |
| 71 | 259 | let host = match host_override { |
| 72 | 260 | Some(host_override) => host_override, |
| 73 | 261 | None => format!("https://{}.{}.api.lancedb.com", db_name, region), |
| 74 | 262 | }; |
| 263 | + let retry_config = client_config.retry_config.try_into()?; | |
| 75 | 264 | Ok(Self { |
| 76 | 265 | client, |
| 77 | 266 | host, |
| 267 | + retry_config, | |
| 78 | 268 | sender: Sender, |
| 79 | 269 | }) |
| 80 | 270 | } |
| @@ -129,8 +319,100 @@ | ||
| 129 | 319 | self.client.post(full_uri) |
| 130 | 320 | } |
| 131 | 321 | |
| 132 | - pub async fn send(&self, req: RequestBuilder) -> Result<Response> { | |
| 133 | - self.sender.send(req).await | |
| 322 | + pub async fn send(&self, req: RequestBuilder, with_retry: bool) -> Result<Response> { | |
| 323 | + let (client, request) = req.build_split(); | |
| 324 | + let mut request = request.unwrap(); | |
| 325 | + | |
| 326 | + // Set a request id. | |
| 327 | + // TODO: allow the user to supply this, through middleware? | |
| 328 | + if request.headers().get(REQUEST_ID_HEADER).is_none() { | |
| 329 | + let request_id = uuid::Uuid::new_v4(); | |
| 330 | + let request_id = HeaderValue::from_str(&request_id.to_string()).unwrap(); | |
| 331 | + request.headers_mut().insert(REQUEST_ID_HEADER, request_id); | |
| 332 | + } | |
| 333 | + | |
| 334 | + if with_retry { | |
| 335 | + self.send_with_retry_impl(client, request).await | |
| 336 | + } else { | |
| 337 | + Ok(self.sender.send(&client, request).await?) | |
| 338 | + } | |
| 339 | + } | |
| 340 | + | |
| 341 | + async fn send_with_retry_impl( | |
| 342 | + &self, | |
| 343 | + client: reqwest::Client, | |
| 344 | + req: Request, | |
| 345 | + ) -> Result<Response> { | |
| 346 | + let mut request_failures = 0; | |
| 347 | + let mut connect_failures = 0; | |
| 348 | + let mut read_failures = 0; | |
| 349 | + | |
| 350 | + loop { | |
| 351 | + // This only works if the request body is not a stream. If it is | |
| 352 | + // a stream, we can't use the retry path. We would need to implement | |
| 353 | + // an outer retry. | |
| 354 | + let request = req.try_clone().ok_or_else(|| Error::Http { | |
| 355 | + message: "Attempted to retry a request that cannot be cloned".to_string(), | |
| 356 | + })?; | |
| 357 | + let response = self.sender.send(&client, request).await; | |
| 358 | + let status_code = response.as_ref().map(|r| r.status()); | |
| 359 | + match status_code { | |
| 360 | + Ok(status) if status.is_success() => return Ok(response?), | |
| 361 | + Ok(status) if self.retry_config.statuses.contains(&status) => { | |
| 362 | + request_failures += 1; | |
| 363 | + if request_failures >= self.retry_config.retries { | |
| 364 | + // TODO: better error | |
| 365 | + return Err(Error::Runtime { | |
| 366 | + message: format!( | |
| 367 | + "Request failed after {} retries with status code {}", | |
| 368 | + request_failures, status | |
| 369 | + ), | |
| 370 | + }); | |
| 371 | + } | |
| 372 | + } | |
| 373 | + Err(err) if err.is_connect() => { | |
| 374 | + connect_failures += 1; | |
| 375 | + if connect_failures >= self.retry_config.connect_retries { | |
| 376 | + return Err(Error::Runtime { | |
| 377 | + message: format!( | |
| 378 | + "Request failed after {} connect retries with error: {}", | |
| 379 | + connect_failures, err | |
| 380 | + ), | |
| 381 | + }); | |
| 382 | + } | |
| 383 | + } | |
| 384 | + Err(err) if err.is_timeout() || err.is_body() || err.is_decode() => { | |
| 385 | + read_failures += 1; | |
| 386 | + if read_failures >= self.retry_config.read_retries { | |
| 387 | + return Err(Error::Runtime { | |
| 388 | + message: format!( | |
| 389 | + "Request failed after {} read retries with error: {}", | |
| 390 | + read_failures, err | |
| 391 | + ), | |
| 392 | + }); | |
| 393 | + } | |
| 394 | + } | |
| 395 | + Ok(_) | Err(_) => return Ok(response?), | |
| 396 | + } | |
| 397 | + | |
| 398 | + let backoff = self.retry_config.backoff_factor * (2.0f32.powi(request_failures as i32)); | |
| 399 | + let jitter = rand::random::<f32>() * self.retry_config.backoff_jitter; | |
| 400 | + let sleep_time = Duration::from_secs_f32(backoff + jitter); | |
| 401 | + debug!( | |
| 402 | + "Retrying request {:?} ({}/{} connect, {}/{} read, {}/{} read) in {:?}", | |
| 403 | + req.headers() | |
| 404 | + .get("x-request-id") | |
| 405 | + .and_then(|v| v.to_str().ok()), | |
| 406 | + connect_failures, | |
| 407 | + self.retry_config.connect_retries, | |
| 408 | + request_failures, | |
| 409 | + self.retry_config.retries, | |
| 410 | + read_failures, | |
| 411 | + self.retry_config.read_retries, | |
| 412 | + sleep_time | |
| 413 | + ); | |
| 414 | + tokio::time::sleep(sleep_time).await; | |
| 415 | + } | |
| 134 | 416 | } |
| 135 | 417 | |
| 136 | 418 | async fn rsp_to_str(response: Response) -> String { |
| @@ -172,8 +454,11 @@ | ||
| 172 | 454 | } |
| 173 | 455 | |
| 174 | 456 | impl HttpSend for MockSender { |
| 175 | - async fn send(&self, request: reqwest::RequestBuilder) -> Result<reqwest::Response> { | |
| 176 | - let request = request.build().unwrap(); | |
| 457 | + async fn send( | |
| 458 | + &self, | |
| 459 | + _client: &reqwest::Client, | |
| 460 | + request: reqwest::Request, | |
| 461 | + ) -> reqwest::Result<reqwest::Response> { | |
| 177 | 462 | let response = (self.f)(request); |
| 178 | 463 | Ok(response) |
| 179 | 464 | } |
| @@ -193,6 +478,7 @@ | ||
| 193 | 478 | RestfulLanceDbClient { |
| 194 | 479 | client: reqwest::Client::new(), |
| 195 | 480 | host: "http://localhost".to_string(), |
| 481 | + retry_config: RetryConfig::default().try_into().unwrap(), | |
| 196 | 482 | sender: MockSender { |
| 197 | 483 | f: Arc::new(wrapper), |
| 198 | 484 | }, |
modified rust/lancedb/src/remote/db.rs +44 −17
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | use arrow_array::RecordBatchReader; |
| 18 | 18 | use async_trait::async_trait; |
| 19 | 19 | use http::StatusCode; |
| 20 | +use moka::future::Cache; | |
| 20 | 21 | use reqwest::header::CONTENT_TYPE; |
| 21 | 22 | use serde::Deserialize; |
| 22 | 23 | use tokio::task::spawn_blocking; |
| @@ -28,7 +29,7 @@ | ||
| 28 | 29 | use crate::error::Result; |
| 29 | 30 | use crate::Table; |
| 30 | 31 | |
| 31 | -use super::client::{HttpSend, RestfulLanceDbClient, Sender}; | |
| 32 | +use super::client::{ClientConfig, HttpSend, RestfulLanceDbClient, Sender}; | |
| 32 | 33 | use super::table::RemoteTable; |
| 33 | 34 | use super::util::batches_to_ipc_bytes; |
| 34 | 35 | use super::ARROW_STREAM_CONTENT_TYPE; |
| @@ -41,6 +42,7 @@ | ||
| 41 | 42 | #[derive(Debug)] |
| 42 | 43 | pub struct RemoteDatabase<S: HttpSend = Sender> { |
| 43 | 44 | client: RestfulLanceDbClient<S>, |
| 45 | + table_cache: Cache<String, ()>, | |
| 44 | 46 | } |
| 45 | 47 | |
| 46 | 48 | impl RemoteDatabase { |
| @@ -49,9 +51,20 @@ | ||
| 49 | 51 | api_key: &str, |
| 50 | 52 | region: &str, |
| 51 | 53 | host_override: Option<String>, |
| 54 | + client_config: ClientConfig, | |
| 52 | 55 | ) -> Result<Self> { |
| 53 | - let client = RestfulLanceDbClient::try_new(uri, api_key, region, host_override)?; | |
| 54 | - Ok(Self { client }) | |
| 56 | + let client = | |
| 57 | + RestfulLanceDbClient::try_new(uri, api_key, region, host_override, client_config)?; | |
| 58 | + | |
| 59 | + let table_cache = Cache::builder() | |
| 60 | + .time_to_live(std::time::Duration::from_secs(300)) | |
| 61 | + .max_capacity(10_000) | |
| 62 | + .build(); | |
| 63 | + | |
| 64 | + Ok(Self { | |
| 65 | + client, | |
| 66 | + table_cache, | |
| 67 | + }) | |
| 55 | 68 | } |
| 56 | 69 | } |
| 57 | 70 | |
| @@ -68,7 +81,10 @@ | ||
| 68 | 81 | T: Into<reqwest::Body>, |
| 69 | 82 | { |
| 70 | 83 | let client = client_with_handler(handler); |
| 71 | - Self { client } | |
| 84 | + Self { | |
| 85 | + client, | |
| 86 | + table_cache: Cache::new(0), | |
| 87 | + } | |
| 72 | 88 | } |
| 73 | 89 | } |
| 74 | 90 | } |
| @@ -89,9 +105,13 @@ | ||
| 89 | 105 | if let Some(start_after) = options.start_after { |
| 90 | 106 | req = req.query(&[("page_token", start_after)]); |
| 91 | 107 | } |
| 92 | - let rsp = self.client.send(req).await?; | |
| 108 | + let rsp = self.client.send(req, true).await?; | |
| 93 | 109 | let rsp = self.client.check_response(rsp).await?; |
| 94 | - Ok(rsp.json::<ListTablesResponse>().await?.tables) | |
| 110 | + let tables = rsp.json::<ListTablesResponse>().await?.tables; | |
| 111 | + for table in &tables { | |
| 112 | + self.table_cache.insert(table.clone(), ()).await; | |
| 113 | + } | |
| 114 | + Ok(tables) | |
| 95 | 115 | } |
| 96 | 116 | |
| 97 | 117 | async fn do_create_table( |
| @@ -113,7 +133,7 @@ | ||
| 113 | 133 | .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) |
| 114 | 134 | // This is currently expected by LanceDb cloud but will be removed soon. |
| 115 | 135 | .header("x-request-id", "na"); |
| 116 | - let rsp = self.client.send(req).await?; | |
| 136 | + let rsp = self.client.send(req, false).await?; | |
| 117 | 137 | |
| 118 | 138 | if rsp.status() == StatusCode::BAD_REQUEST { |
| 119 | 139 | let body = rsp.text().await?; |
| @@ -126,6 +146,8 @@ | ||
| 126 | 146 | |
| 127 | 147 | self.client.check_response(rsp).await?; |
| 128 | 148 | |
| 149 | + self.table_cache.insert(options.name.clone(), ()).await; | |
| 150 | + | |
| 129 | 151 | Ok(Table::new(Arc::new(RemoteTable::new( |
| 130 | 152 | self.client.clone(), |
| 131 | 153 | options.name, |
| @@ -134,15 +156,17 @@ | ||
| 134 | 156 | |
| 135 | 157 | async fn do_open_table(&self, options: OpenTableBuilder) -> Result<Table> { |
| 136 | 158 | // We describe the table to confirm it exists before moving on. |
| 137 | - // TODO: a TTL cache of table existence | |
| 138 | - let req = self | |
| 139 | - .client | |
| 140 | - .get(&format!("/v1/table/{}/describe/", options.name)); | |
| 141 | - let resp = self.client.send(req).await?; | |
| 142 | - if resp.status() == StatusCode::NOT_FOUND { | |
| 143 | - return Err(crate::Error::TableNotFound { name: options.name }); | |
| 159 | + if self.table_cache.get(&options.name).is_none() { | |
| 160 | + let req = self | |
| 161 | + .client | |
| 162 | + .get(&format!("/v1/table/{}/describe/", options.name)); | |
| 163 | + let resp = self.client.send(req, true).await?; | |
| 164 | + if resp.status() == StatusCode::NOT_FOUND { | |
| 165 | + return Err(crate::Error::TableNotFound { name: options.name }); | |
| 166 | + } | |
| 167 | + self.client.check_response(resp).await?; | |
| 144 | 168 | } |
| 145 | - self.client.check_response(resp).await?; | |
| 169 | + | |
| 146 | 170 | Ok(Table::new(Arc::new(RemoteTable::new( |
| 147 | 171 | self.client.clone(), |
| 148 | 172 | options.name, |
| @@ -154,15 +178,18 @@ | ||
| 154 | 178 | .client |
| 155 | 179 | .post(&format!("/v1/table/{}/rename/", current_name)); |
| 156 | 180 | let req = req.json(&serde_json::json!({ "new_table_name": new_name })); |
| 157 | - let resp = self.client.send(req).await?; | |
| 181 | + let resp = self.client.send(req, false).await?; | |
| 158 | 182 | self.client.check_response(resp).await?; |
| 183 | + self.table_cache.remove(current_name).await; | |
| 184 | + self.table_cache.insert(new_name.into(), ()).await; | |
| 159 | 185 | Ok(()) |
| 160 | 186 | } |
| 161 | 187 | |
| 162 | 188 | async fn drop_table(&self, name: &str) -> Result<()> { |
| 163 | 189 | let req = self.client.post(&format!("/v1/table/{}/drop/", name)); |
| 164 | - let resp = self.client.send(req).await?; | |
| 190 | + let resp = self.client.send(req, true).await?; | |
| 165 | 191 | self.client.check_response(resp).await?; |
| 192 | + self.table_cache.remove(name).await; | |
| 166 | 193 | Ok(()) |
| 167 | 194 | } |
| 168 | 195 |
modified rust/lancedb/src/remote/table.rs +10 −10
| @@ -51,7 +51,7 @@ | ||
| 51 | 51 | |
| 52 | 52 | async fn describe(&self) -> Result<TableDescription> { |
| 53 | 53 | let request = self.client.post(&format!("/table/{}/describe/", self.name)); |
| 54 | - let response = self.client.send(request).await?; | |
| 54 | + let response = self.client.send(request, true).await?; | |
| 55 | 55 | |
| 56 | 56 | let response = self.check_table_response(response).await?; |
| 57 | 57 | |
| @@ -257,7 +257,7 @@ | ||
| 257 | 257 | request = request.json(&serde_json::json!({})); |
| 258 | 258 | } |
| 259 | 259 | |
| 260 | - let response = self.client.send(request).await?; | |
| 260 | + let response = self.client.send(request, true).await?; | |
| 261 | 261 | |
| 262 | 262 | let response = self.check_table_response(response).await?; |
| 263 | 263 | |
| @@ -286,7 +286,7 @@ | ||
| 286 | 286 | } |
| 287 | 287 | } |
| 288 | 288 | |
| 289 | - let response = self.client.send(request).await?; | |
| 289 | + let response = self.client.send(request, false).await?; | |
| 290 | 290 | |
| 291 | 291 | self.check_table_response(response).await?; |
| 292 | 292 | |
| @@ -337,7 +337,7 @@ | ||
| 337 | 337 | |
| 338 | 338 | let request = request.json(&body); |
| 339 | 339 | |
| 340 | - let response = self.client.send(request).await?; | |
| 340 | + let response = self.client.send(request, true).await?; | |
| 341 | 341 | |
| 342 | 342 | let stream = self.read_arrow_stream(response).await?; |
| 343 | 343 | |
| @@ -359,7 +359,7 @@ | ||
| 359 | 359 | |
| 360 | 360 | let request = request.json(&body); |
| 361 | 361 | |
| 362 | - let response = self.client.send(request).await?; | |
| 362 | + let response = self.client.send(request, true).await?; | |
| 363 | 363 | |
| 364 | 364 | let stream = self.read_arrow_stream(response).await?; |
| 365 | 365 | |
| @@ -379,7 +379,7 @@ | ||
| 379 | 379 | "only_if": update.filter, |
| 380 | 380 | })); |
| 381 | 381 | |
| 382 | - let response = self.client.send(request).await?; | |
| 382 | + let response = self.client.send(request, false).await?; | |
| 383 | 383 | |
| 384 | 384 | let response = self.check_table_response(response).await?; |
| 385 | 385 | |
| @@ -398,7 +398,7 @@ | ||
| 398 | 398 | .client |
| 399 | 399 | .post(&format!("/table/{}/delete/", self.name)) |
| 400 | 400 | .json(&body); |
| 401 | - let response = self.client.send(request).await?; | |
| 401 | + let response = self.client.send(request, false).await?; | |
| 402 | 402 | self.check_table_response(response).await?; |
| 403 | 403 | Ok(()) |
| 404 | 404 | } |
| @@ -468,7 +468,7 @@ | ||
| 468 | 468 | |
| 469 | 469 | let request = request.json(&body); |
| 470 | 470 | |
| 471 | - let response = self.client.send(request).await?; | |
| 471 | + let response = self.client.send(request, false).await?; | |
| 472 | 472 | |
| 473 | 473 | self.check_table_response(response).await?; |
| 474 | 474 | |
| @@ -489,7 +489,7 @@ | ||
| 489 | 489 | .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) |
| 490 | 490 | .body(body); |
| 491 | 491 | |
| 492 | - let response = self.client.send(request).await?; | |
| 492 | + let response = self.client.send(request, false).await?; | |
| 493 | 493 | |
| 494 | 494 | self.check_table_response(response).await?; |
| 495 | 495 | |
| @@ -528,7 +528,7 @@ | ||
| 528 | 528 | let request = self |
| 529 | 529 | .client |
| 530 | 530 | .post(&format!("/table/{}/index/{}/stats/", self.name, index_name)); |
| 531 | - let response = self.client.send(request).await?; | |
| 531 | + let response = self.client.send(request, true).await?; | |
| 532 | 532 | |
| 533 | 533 | if response.status() == StatusCode::NOT_FOUND { |
| 534 | 534 | return Ok(None); |