Elffuss BraidHub

kikocis/lancedb public

feat(rust): client configuration for remote client (#1696)

This PR ports over advanced client configuration present in the Python
`RestfulLanceDBClient` to the Rust one. The goal is to have feature
parity so we can replace the implementation.

* [x] Request timeout
* [x] Retries with backoff
* [x] Request id generation
* [x] User agent (with default tied to library version ✨ )
* [x] Table existence cache
* [ ] Deferred: ~Request id customization (should this just pick up OTEL
trace ids?)~

Fixes #1684
Changesetd3aaefc5a7c9ab816f80a9ea24ffc042358f375bcd246b04f6eeeabae1a6f893
AuthorWill Jones <willjones127@gmail.com> · 2024-10-01 10:22 -07:00
CommitterGitHub <noreply@github.com> · 2024-10-01 10:22 -07:00
Parents003c3ff7b96f

Browse the files at this changeset

8 files changed

modified Cargo.toml +2 −0
@@ -45,10 +45,12 @@
4545 ] }
4646 futures = "0"
4747 log = "0.4"
48+moka = { version = "0.11", features = ["future"] }
4849 object_store = "0.10.2"
4950 pin-project = "1.0.7"
5051 snafu = "0.7.4"
5152 url = "2"
5253 num-traits = "0.2"
54+rand = "0.8"
5355 regex = "1.10"
5456 lazy_static = "1"
modified rust/lancedb/Cargo.toml +5 −2
@@ -32,6 +32,7 @@
3232 lance-linalg = { workspace = true }
3333 lance-testing = { workspace = true }
3434 lance-encoding = { workspace = true }
35+moka = { workspace = true}
3536 pin-project = { workspace = true }
3637 tokio = { version = "1.23", features = ["rt-multi-thread"] }
3738 log.workspace = true
@@ -47,7 +48,9 @@
4748 serde_with = { version = "3.8.1" }
4849 # For remote feature
4950 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 }
5154 polars-arrow = { version = ">=0.37,<0.40.0", optional = true }
5255 polars = { version = ">=0.37,<0.40.0", optional = true }
5356 hf-hub = { version = "0.3.2", optional = true }
@@ -71,7 +74,7 @@
7174
7275 [features]
7376 default = []
74-remote = ["dep:reqwest", "dep:http"]
77+remote = ["dep:reqwest", "dep:http", "dep:rand", "dep:uuid"]
7578 fp16kernels = ["lance-linalg/fp16kernels"]
7679 s3-test = []
7780 openai = ["dep:async-openai", "dep:reqwest"]
modified rust/lancedb/src/connection.rs +32 −0
@@ -32,6 +32,8 @@
3232 };
3333 use crate::error::{CreateDirSnafu, Error, InvalidTableNameSnafu, Result};
3434 use crate::io::object_store::MirroringObjectStoreWrapper;
35+#[cfg(feature = "remote")]
36+use crate::remote::client::ClientConfig;
3537 use crate::table::{NativeTable, TableDefinition, WriteOptions};
3638 use crate::utils::validate_table_name;
3739 use crate::Table;
@@ -567,6 +569,8 @@
567569 region: Option<String>,
568570 /// LanceDB Cloud host override, only required if using an on-premises Lance Cloud instance
569571 host_override: Option<String>,
572+ #[cfg(feature = "remote")]
573+ client_config: ClientConfig,
570574
571575 storage_options: HashMap<String, String>,
572576
@@ -592,6 +596,8 @@
592596 api_key: None,
593597 region: None,
594598 host_override: None,
599+ #[cfg(feature = "remote")]
600+ client_config: Default::default(),
595601 read_consistency_interval: None,
596602 storage_options: HashMap::new(),
597603 embedding_registry: None,
@@ -613,6 +619,30 @@
613619 self
614620 }
615621
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+
616646 /// Provide a custom [`EmbeddingRegistry`] to use for this connection.
617647 pub fn embedding_registry(mut self, registry: Arc<dyn EmbeddingRegistry>) -> Self {
618648 self.embedding_registry = Some(registry);
@@ -685,12 +715,14 @@
685715 let api_key = self.api_key.ok_or_else(|| Error::InvalidInput {
686716 message: "An api_key is required when connecting to LanceDb Cloud".to_string(),
687717 })?;
718+ // TODO: remove this warning when the remote client is ready
688719 warn!("The rust implementation of the remote client is not yet ready for use.");
689720 let internal = Arc::new(crate::remote::db::RemoteDatabase::try_new(
690721 &self.uri,
691722 &api_key,
692723 &region,
693724 self.host_override,
725+ self.client_config,
694726 )?);
695727 Ok(Connection {
696728 internal,
modified rust/lancedb/src/lib.rs +1 −1
@@ -213,7 +213,7 @@
213213 mod polars_arrow_convertors;
214214 pub mod query;
215215 #[cfg(feature = "remote")]
216-pub(crate) mod remote;
216+pub mod remote;
217217 pub mod table;
218218 pub mod utils;
219219
modified rust/lancedb/src/remote.rs +6 −4
@@ -17,10 +17,12 @@
1717 //! building client/server applications with LanceDB or as a client for some
1818 //! other custom LanceDB service.
1919
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;
2424
2525 const ARROW_STREAM_CONTENT_TYPE: &str = "application/vnd.apache.arrow.stream";
2626 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 @@
1414
1515 use std::{future::Future, time::Duration};
1616
17+use log::debug;
1718 use reqwest::{
1819 header::{HeaderMap, HeaderValue},
19- RequestBuilder, Response,
20+ Request, RequestBuilder, Response,
2021 };
2122
2223 use crate::error::{Error, Result};
2324
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+
24163 // We use the `HttpSend` trait to abstract over the `reqwest::Client` so that
25164 // we can mock responses in tests. Based on the patterns from this blog post:
26165 // https://write.as/balrogboogie/testing-reqwest-based-clients
@@ -28,28 +167,54 @@
28167 pub struct RestfulLanceDbClient<S: HttpSend = Sender> {
29168 client: reqwest::Client,
30169 host: String,
170+ retry_config: ResolvedRetryConfig,
31171 sender: S,
32172 }
33173
34174 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;
36180 }
37181
38182 // Default implementation of HttpSend which sends the request normally with reqwest
39183 #[derive(Clone, Debug)]
40184 pub struct Sender;
41185 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
44192 }
45193 }
46194
47195 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+
48212 pub fn try_new(
49213 db_url: &str,
50214 api_key: &str,
51215 region: &str,
52216 host_override: Option<String>,
217+ client_config: ClientConfig,
53218 ) -> Result<Self> {
54219 let parsed_url = url::Url::parse(db_url)?;
55220 debug_assert_eq!(parsed_url.scheme(), "db");
@@ -59,22 +224,47 @@
59224 });
60225 }
61226 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+
62247 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)
64251 .default_headers(Self::default_headers(
65252 api_key,
66253 region,
67254 db_name,
68255 host_override.is_some(),
69256 )?)
257+ .user_agent(client_config.user_agent)
70258 .build()?;
71259 let host = match host_override {
72260 Some(host_override) => host_override,
73261 None => format!("https://{}.{}.api.lancedb.com", db_name, region),
74262 };
263+ let retry_config = client_config.retry_config.try_into()?;
75264 Ok(Self {
76265 client,
77266 host,
267+ retry_config,
78268 sender: Sender,
79269 })
80270 }
@@ -129,8 +319,100 @@
129319 self.client.post(full_uri)
130320 }
131321
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+ }
134416 }
135417
136418 async fn rsp_to_str(response: Response) -> String {
@@ -172,8 +454,11 @@
172454 }
173455
174456 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> {
177462 let response = (self.f)(request);
178463 Ok(response)
179464 }
@@ -193,6 +478,7 @@
193478 RestfulLanceDbClient {
194479 client: reqwest::Client::new(),
195480 host: "http://localhost".to_string(),
481+ retry_config: RetryConfig::default().try_into().unwrap(),
196482 sender: MockSender {
197483 f: Arc::new(wrapper),
198484 },
modified rust/lancedb/src/remote/db.rs +44 −17
@@ -17,6 +17,7 @@
1717 use arrow_array::RecordBatchReader;
1818 use async_trait::async_trait;
1919 use http::StatusCode;
20+use moka::future::Cache;
2021 use reqwest::header::CONTENT_TYPE;
2122 use serde::Deserialize;
2223 use tokio::task::spawn_blocking;
@@ -28,7 +29,7 @@
2829 use crate::error::Result;
2930 use crate::Table;
3031
31-use super::client::{HttpSend, RestfulLanceDbClient, Sender};
32+use super::client::{ClientConfig, HttpSend, RestfulLanceDbClient, Sender};
3233 use super::table::RemoteTable;
3334 use super::util::batches_to_ipc_bytes;
3435 use super::ARROW_STREAM_CONTENT_TYPE;
@@ -41,6 +42,7 @@
4142 #[derive(Debug)]
4243 pub struct RemoteDatabase<S: HttpSend = Sender> {
4344 client: RestfulLanceDbClient<S>,
45+ table_cache: Cache<String, ()>,
4446 }
4547
4648 impl RemoteDatabase {
@@ -49,9 +51,20 @@
4951 api_key: &str,
5052 region: &str,
5153 host_override: Option<String>,
54+ client_config: ClientConfig,
5255 ) -> 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+ })
5568 }
5669 }
5770
@@ -68,7 +81,10 @@
6881 T: Into<reqwest::Body>,
6982 {
7083 let client = client_with_handler(handler);
71- Self { client }
84+ Self {
85+ client,
86+ table_cache: Cache::new(0),
87+ }
7288 }
7389 }
7490 }
@@ -89,9 +105,13 @@
89105 if let Some(start_after) = options.start_after {
90106 req = req.query(&[("page_token", start_after)]);
91107 }
92- let rsp = self.client.send(req).await?;
108+ let rsp = self.client.send(req, true).await?;
93109 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)
95115 }
96116
97117 async fn do_create_table(
@@ -113,7 +133,7 @@
113133 .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE)
114134 // This is currently expected by LanceDb cloud but will be removed soon.
115135 .header("x-request-id", "na");
116- let rsp = self.client.send(req).await?;
136+ let rsp = self.client.send(req, false).await?;
117137
118138 if rsp.status() == StatusCode::BAD_REQUEST {
119139 let body = rsp.text().await?;
@@ -126,6 +146,8 @@
126146
127147 self.client.check_response(rsp).await?;
128148
149+ self.table_cache.insert(options.name.clone(), ()).await;
150+
129151 Ok(Table::new(Arc::new(RemoteTable::new(
130152 self.client.clone(),
131153 options.name,
@@ -134,15 +156,17 @@
134156
135157 async fn do_open_table(&self, options: OpenTableBuilder) -> Result<Table> {
136158 // 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?;
144168 }
145- self.client.check_response(resp).await?;
169+
146170 Ok(Table::new(Arc::new(RemoteTable::new(
147171 self.client.clone(),
148172 options.name,
@@ -154,15 +178,18 @@
154178 .client
155179 .post(&format!("/v1/table/{}/rename/", current_name));
156180 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?;
158182 self.client.check_response(resp).await?;
183+ self.table_cache.remove(current_name).await;
184+ self.table_cache.insert(new_name.into(), ()).await;
159185 Ok(())
160186 }
161187
162188 async fn drop_table(&self, name: &str) -> Result<()> {
163189 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?;
165191 self.client.check_response(resp).await?;
192+ self.table_cache.remove(name).await;
166193 Ok(())
167194 }
168195
modified rust/lancedb/src/remote/table.rs +10 −10
@@ -51,7 +51,7 @@
5151
5252 async fn describe(&self) -> Result<TableDescription> {
5353 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?;
5555
5656 let response = self.check_table_response(response).await?;
5757
@@ -257,7 +257,7 @@
257257 request = request.json(&serde_json::json!({}));
258258 }
259259
260- let response = self.client.send(request).await?;
260+ let response = self.client.send(request, true).await?;
261261
262262 let response = self.check_table_response(response).await?;
263263
@@ -286,7 +286,7 @@
286286 }
287287 }
288288
289- let response = self.client.send(request).await?;
289+ let response = self.client.send(request, false).await?;
290290
291291 self.check_table_response(response).await?;
292292
@@ -337,7 +337,7 @@
337337
338338 let request = request.json(&body);
339339
340- let response = self.client.send(request).await?;
340+ let response = self.client.send(request, true).await?;
341341
342342 let stream = self.read_arrow_stream(response).await?;
343343
@@ -359,7 +359,7 @@
359359
360360 let request = request.json(&body);
361361
362- let response = self.client.send(request).await?;
362+ let response = self.client.send(request, true).await?;
363363
364364 let stream = self.read_arrow_stream(response).await?;
365365
@@ -379,7 +379,7 @@
379379 "only_if": update.filter,
380380 }));
381381
382- let response = self.client.send(request).await?;
382+ let response = self.client.send(request, false).await?;
383383
384384 let response = self.check_table_response(response).await?;
385385
@@ -398,7 +398,7 @@
398398 .client
399399 .post(&format!("/table/{}/delete/", self.name))
400400 .json(&body);
401- let response = self.client.send(request).await?;
401+ let response = self.client.send(request, false).await?;
402402 self.check_table_response(response).await?;
403403 Ok(())
404404 }
@@ -468,7 +468,7 @@
468468
469469 let request = request.json(&body);
470470
471- let response = self.client.send(request).await?;
471+ let response = self.client.send(request, false).await?;
472472
473473 self.check_table_response(response).await?;
474474
@@ -489,7 +489,7 @@
489489 .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE)
490490 .body(body);
491491
492- let response = self.client.send(request).await?;
492+ let response = self.client.send(request, false).await?;
493493
494494 self.check_table_response(response).await?;
495495
@@ -528,7 +528,7 @@
528528 let request = self
529529 .client
530530 .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?;
532532
533533 if response.status() == StatusCode::NOT_FOUND {
534534 return Ok(None);