Changesets · Branches · Tags · Compare
| Changeset | c259084282255f2259ca5df3acb8cc0e56b1eceade5e22b9b4e23ffbe9362ffb |
|---|---|
| Author | Will Jones <willjones127@gmail.com> · 2024-10-08 21:21 -07:00 |
| Committer | GitHub <noreply@github.com> · 2024-10-08 22:21 -06:00 |
| Parents | e6c3bef0cf81 |
9 files changed
modified python/python/lancedb/remote/client.py +14 −4
| @@ -103,19 +103,29 @@ | ||
| 103 | 103 | |
| 104 | 104 | @staticmethod |
| 105 | 105 | def _check_status(resp: requests.Response): |
| 106 | + # Leaving request id empty for now, as we'll be replacing this impl | |
| 107 | + # with the Rust one shortly. | |
| 106 | 108 | if resp.status_code == 404: |
| 107 | - raise LanceDBClientError(f"Not found: {resp.text}") | |
| 109 | + raise LanceDBClientError( | |
| 110 | + f"Not found: {resp.text}", request_id="", status_code=404 | |
| 111 | + ) | |
| 108 | 112 | elif 400 <= resp.status_code < 500: |
| 109 | 113 | raise LanceDBClientError( |
| 110 | - f"Bad Request: {resp.status_code}, error: {resp.text}" | |
| 114 | + f"Bad Request: {resp.status_code}, error: {resp.text}", | |
| 115 | + request_id="", | |
| 116 | + status_code=resp.status_code, | |
| 111 | 117 | ) |
| 112 | 118 | elif 500 <= resp.status_code < 600: |
| 113 | 119 | raise LanceDBClientError( |
| 114 | - f"Internal Server Error: {resp.status_code}, error: {resp.text}" | |
| 120 | + f"Internal Server Error: {resp.status_code}, error: {resp.text}", | |
| 121 | + request_id="", | |
| 122 | + status_code=resp.status_code, | |
| 115 | 123 | ) |
| 116 | 124 | elif resp.status_code != 200: |
| 117 | 125 | raise LanceDBClientError( |
| 118 | - f"Unknown Error: {resp.status_code}, error: {resp.text}" | |
| 126 | + f"Unknown Error: {resp.status_code}, error: {resp.text}", | |
| 127 | + request_id="", | |
| 128 | + status_code=resp.status_code, | |
| 119 | 129 | ) |
| 120 | 130 | |
| 121 | 131 | @_check_not_closed |
modified python/python/lancedb/remote/errors.py +97 −0
| @@ -12,5 +12,102 @@ | ||
| 12 | 12 | # limitations under the License. |
| 13 | 13 | |
| 14 | 14 | |
| 15 | +from typing import Optional | |
| 16 | + | |
| 17 | + | |
| 15 | 18 | class LanceDBClientError(RuntimeError): |
| 19 | + """An error that occurred in the LanceDB client. | |
| 20 | + | |
| 21 | + Attributes | |
| 22 | + ---------- | |
| 23 | + message: str | |
| 24 | + The error message. | |
| 25 | + request_id: str | |
| 26 | + The id of the request that failed. This can be provided in error reports | |
| 27 | + to help diagnose the issue. | |
| 28 | + status_code: int | |
| 29 | + The HTTP status code of the response. May be None if the request | |
| 30 | + failed before the response was received. | |
| 31 | + """ | |
| 32 | + | |
| 33 | + def __init__( | |
| 34 | + self, message: str, request_id: str, status_code: Optional[int] = None | |
| 35 | + ): | |
| 36 | + super().__init__(message) | |
| 37 | + self.request_id = request_id | |
| 38 | + self.status_code = status_code | |
| 39 | + | |
| 40 | + | |
| 41 | +class HttpError(LanceDBClientError): | |
| 42 | + """An error that occurred during an HTTP request. | |
| 43 | + | |
| 44 | + Attributes | |
| 45 | + ---------- | |
| 46 | + message: str | |
| 47 | + The error message. | |
| 48 | + request_id: str | |
| 49 | + The id of the request that failed. This can be provided in error reports | |
| 50 | + to help diagnose the issue. | |
| 51 | + status_code: int | |
| 52 | + The HTTP status code of the response. May be None if the request | |
| 53 | + failed before the response was received. | |
| 54 | + """ | |
| 55 | + | |
| 16 | 56 | pass |
| 57 | + | |
| 58 | + | |
| 59 | +class RetryError(LanceDBClientError): | |
| 60 | + """An error that occurs when the client has exceeded the maximum number of retries. | |
| 61 | + | |
| 62 | + The retry strategy can be adjusted by setting the | |
| 63 | + [retry_config](lancedb.remote.ClientConfig.retry_config) in the client | |
| 64 | + configuration. This is passed in the `client_config` argument of | |
| 65 | + [connect](lancedb.connect) and [connect_async](lancedb.connect_async). | |
| 66 | + | |
| 67 | + The __cause__ attribute of this exception will be the last exception that | |
| 68 | + caused the retry to fail. It will be an | |
| 69 | + [HttpError][lancedb.remote.errors.HttpError] instance. | |
| 70 | + | |
| 71 | + Attributes | |
| 72 | + ---------- | |
| 73 | + message: str | |
| 74 | + The retry error message, which will describe which retry limit was hit. | |
| 75 | + request_id: str | |
| 76 | + The id of the request that failed. This can be provided in error reports | |
| 77 | + to help diagnose the issue. | |
| 78 | + request_failures: int | |
| 79 | + The number of request failures. | |
| 80 | + connect_failures: int | |
| 81 | + The number of connect failures. | |
| 82 | + read_failures: int | |
| 83 | + The number of read failures. | |
| 84 | + max_request_failures: int | |
| 85 | + The maximum number of request failures. | |
| 86 | + max_connect_failures: int | |
| 87 | + The maximum number of connect failures. | |
| 88 | + max_read_failures: int | |
| 89 | + The maximum number of read failures. | |
| 90 | + status_code: int | |
| 91 | + The HTTP status code of the last response. May be None if the request | |
| 92 | + failed before the response was received. | |
| 93 | + """ | |
| 94 | + | |
| 95 | + def __init__( | |
| 96 | + self, | |
| 97 | + message: str, | |
| 98 | + request_id: str, | |
| 99 | + request_failures: int, | |
| 100 | + connect_failures: int, | |
| 101 | + read_failures: int, | |
| 102 | + max_request_failures: int, | |
| 103 | + max_connect_failures: int, | |
| 104 | + max_read_failures: int, | |
| 105 | + status_code: Optional[int], | |
| 106 | + ): | |
| 107 | + super().__init__(message, request_id, status_code) | |
| 108 | + self.request_failures = request_failures | |
| 109 | + self.connect_failures = connect_failures | |
| 110 | + self.read_failures = read_failures | |
| 111 | + self.max_request_failures = max_request_failures | |
| 112 | + self.max_connect_failures = max_connect_failures | |
| 113 | + self.max_read_failures = max_read_failures |
modified python/python/tests/test_db.py +2 −2
| @@ -354,7 +354,7 @@ | ||
| 354 | 354 | ) |
| 355 | 355 | await db.create_table("test", data=data) |
| 356 | 356 | |
| 357 | - with pytest.raises(RuntimeError): | |
| 357 | + with pytest.raises(ValueError, match="already exists"): | |
| 358 | 358 | await db.create_table("test", data=data) |
| 359 | 359 | |
| 360 | 360 | new_data = pd.DataFrame( |
| @@ -382,7 +382,7 @@ | ||
| 382 | 382 | ) |
| 383 | 383 | tbl = await db.create_table("test", data=data) |
| 384 | 384 | |
| 385 | - with pytest.raises(RuntimeError): | |
| 385 | + with pytest.raises(ValueError, match="already exists"): | |
| 386 | 386 | await db.create_table("test", data=data) |
| 387 | 387 | |
| 388 | 388 | # open the table but don't add more rows |
modified python/python/tests/test_remote_db.py +76 −25
| @@ -1,12 +1,14 @@ | ||
| 1 | 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | 2 | # SPDX-FileCopyrightText: Copyright The LanceDB Authors |
| 3 | 3 | |
| 4 | +import contextlib | |
| 4 | 5 | import http.server |
| 5 | 6 | import threading |
| 6 | 7 | from unittest.mock import MagicMock |
| 7 | 8 | import uuid |
| 8 | 9 | |
| 9 | 10 | import lancedb |
| 11 | +from lancedb.remote.errors import HttpError, RetryError | |
| 10 | 12 | import pyarrow as pa |
| 11 | 13 | from lancedb.remote.client import VectorQuery, VectorQueryResult |
| 12 | 14 | import pytest |
| @@ -98,6 +100,33 @@ | ||
| 98 | 100 | return MockLanceDBHandler |
| 99 | 101 | |
| 100 | 102 | |
| 103 | +@contextlib.asynccontextmanager | |
| 104 | +async def mock_lancedb_connection(handler): | |
| 105 | + with http.server.HTTPServer( | |
| 106 | + ("localhost", 8080), make_mock_http_handler(handler) | |
| 107 | + ) as server: | |
| 108 | + handle = threading.Thread(target=server.serve_forever) | |
| 109 | + handle.start() | |
| 110 | + | |
| 111 | + db = await lancedb.connect_async( | |
| 112 | + "db://dev", | |
| 113 | + api_key="fake", | |
| 114 | + host_override="http://localhost:8080", | |
| 115 | + client_config={ | |
| 116 | + "retry_config": {"retries": 2}, | |
| 117 | + "timeout_config": { | |
| 118 | + "connect_timeout": 1, | |
| 119 | + }, | |
| 120 | + }, | |
| 121 | + ) | |
| 122 | + | |
| 123 | + try: | |
| 124 | + yield db | |
| 125 | + finally: | |
| 126 | + server.shutdown() | |
| 127 | + handle.join() | |
| 128 | + | |
| 129 | + | |
| 101 | 130 | @pytest.mark.asyncio |
| 102 | 131 | async def test_async_remote_db(): |
| 103 | 132 | def handler(request): |
| @@ -114,28 +143,50 @@ | ||
| 114 | 143 | request.end_headers() |
| 115 | 144 | request.wfile.write(b'{"tables": []}') |
| 116 | 145 | |
| 117 | - def run_server(): | |
| 118 | - with http.server.HTTPServer( | |
| 119 | - ("localhost", 8080), make_mock_http_handler(handler) | |
| 120 | - ) as server: | |
| 121 | - # we will only make one request | |
| 122 | - server.handle_request() | |
| 123 | - | |
| 124 | - handle = threading.Thread(target=run_server) | |
| 125 | - handle.start() | |
| 126 | - | |
| 127 | - db = await lancedb.connect_async( | |
| 128 | - "db://dev", | |
| 129 | - api_key="fake", | |
| 130 | - host_override="http://localhost:8080", | |
| 131 | - client_config={ | |
| 132 | - "retry_config": {"retries": 2}, | |
| 133 | - "timeout_config": { | |
| 134 | - "connect_timeout": 1, | |
| 135 | - }, | |
| 136 | - }, | |
| 137 | - ) | |
| 138 | - table_names = await db.table_names() | |
| 139 | - assert table_names == [] | |
| 140 | - | |
| 141 | - handle.join() | |
| 146 | + async with mock_lancedb_connection(handler) as db: | |
| 147 | + table_names = await db.table_names() | |
| 148 | + assert table_names == [] | |
| 149 | + | |
| 150 | + | |
| 151 | +@pytest.mark.asyncio | |
| 152 | +async def test_http_error(): | |
| 153 | + request_id_holder = {"request_id": None} | |
| 154 | + | |
| 155 | + def handler(request): | |
| 156 | + request_id_holder["request_id"] = request.headers["x-request-id"] | |
| 157 | + | |
| 158 | + request.send_response(507) | |
| 159 | + request.end_headers() | |
| 160 | + request.wfile.write(b"Internal Server Error") | |
| 161 | + | |
| 162 | + async with mock_lancedb_connection(handler) as db: | |
| 163 | + with pytest.raises(HttpError, match="Internal Server Error") as exc_info: | |
| 164 | + await db.table_names() | |
| 165 | + | |
| 166 | + assert exc_info.value.request_id == request_id_holder["request_id"] | |
| 167 | + assert exc_info.value.status_code == 507 | |
| 168 | + | |
| 169 | + | |
| 170 | +@pytest.mark.asyncio | |
| 171 | +async def test_retry_error(): | |
| 172 | + request_id_holder = {"request_id": None} | |
| 173 | + | |
| 174 | + def handler(request): | |
| 175 | + request_id_holder["request_id"] = request.headers["x-request-id"] | |
| 176 | + | |
| 177 | + request.send_response(429) | |
| 178 | + request.end_headers() | |
| 179 | + request.wfile.write(b"Try again later") | |
| 180 | + | |
| 181 | + async with mock_lancedb_connection(handler) as db: | |
| 182 | + with pytest.raises(RetryError, match="Hit retry limit") as exc_info: | |
| 183 | + await db.table_names() | |
| 184 | + | |
| 185 | + assert exc_info.value.request_id == request_id_holder["request_id"] | |
| 186 | + assert exc_info.value.status_code == 429 | |
| 187 | + | |
| 188 | + cause = exc_info.value.__cause__ | |
| 189 | + assert isinstance(cause, HttpError) | |
| 190 | + assert "Try again later" in str(cause) | |
| 191 | + assert cause.request_id == request_id_holder["request_id"] | |
| 192 | + assert cause.status_code == 429 |
modified python/src/error.rs +92 −2
| @@ -14,7 +14,9 @@ | ||
| 14 | 14 | |
| 15 | 15 | use pyo3::{ |
| 16 | 16 | exceptions::{PyIOError, PyNotImplementedError, PyOSError, PyRuntimeError, PyValueError}, |
| 17 | - PyResult, | |
| 17 | + intern, | |
| 18 | + types::{PyAnyMethods, PyNone}, | |
| 19 | + PyErr, PyResult, Python, | |
| 18 | 20 | }; |
| 19 | 21 | |
| 20 | 22 | use lancedb::error::Error as LanceError; |
| @@ -38,12 +40,79 @@ | ||
| 38 | 40 | LanceError::InvalidInput { .. } |
| 39 | 41 | | LanceError::InvalidTableName { .. } |
| 40 | 42 | | LanceError::TableNotFound { .. } |
| 41 | - | LanceError::Schema { .. } => self.value_error(), | |
| 43 | + | LanceError::Schema { .. } | |
| 44 | + | LanceError::TableAlreadyExists { .. } => self.value_error(), | |
| 42 | 45 | LanceError::CreateDir { .. } => self.os_error(), |
| 43 | 46 | LanceError::ObjectStore { .. } => Err(PyIOError::new_err(err.to_string())), |
| 44 | 47 | LanceError::NotSupported { .. } => { |
| 45 | 48 | Err(PyNotImplementedError::new_err(err.to_string())) |
| 46 | 49 | } |
| 50 | + LanceError::Http { | |
| 51 | + request_id, | |
| 52 | + source, | |
| 53 | + status_code, | |
| 54 | + } => Python::with_gil(|py| { | |
| 55 | + let message = err.to_string(); | |
| 56 | + let http_err_cls = py | |
| 57 | + .import_bound(intern!(py, "lancedb.remote.errors"))? | |
| 58 | + .getattr(intern!(py, "HttpError"))?; | |
| 59 | + let err = http_err_cls.call1(( | |
| 60 | + message, | |
| 61 | + request_id, | |
| 62 | + status_code.map(|s| s.as_u16()), | |
| 63 | + ))?; | |
| 64 | + | |
| 65 | + if let Some(cause) = source.source() { | |
| 66 | + // The HTTP error already includes the first cause. But | |
| 67 | + // we can add the rest of the chain if there is any more. | |
| 68 | + let cause_err = http_from_rust_error( | |
| 69 | + py, | |
| 70 | + cause, | |
| 71 | + request_id, | |
| 72 | + status_code.map(|s| s.as_u16()), | |
| 73 | + )?; | |
| 74 | + err.setattr(intern!(py, "__cause__"), cause_err)?; | |
| 75 | + } | |
| 76 | + | |
| 77 | + Err(PyErr::from_value_bound(err)) | |
| 78 | + }), | |
| 79 | + LanceError::Retry { | |
| 80 | + request_id, | |
| 81 | + request_failures, | |
| 82 | + max_request_failures, | |
| 83 | + connect_failures, | |
| 84 | + max_connect_failures, | |
| 85 | + read_failures, | |
| 86 | + max_read_failures, | |
| 87 | + source, | |
| 88 | + status_code, | |
| 89 | + } => Python::with_gil(|py| { | |
| 90 | + let cause_err = http_from_rust_error( | |
| 91 | + py, | |
| 92 | + source.as_ref(), | |
| 93 | + request_id, | |
| 94 | + status_code.map(|s| s.as_u16()), | |
| 95 | + )?; | |
| 96 | + | |
| 97 | + let message = err.to_string(); | |
| 98 | + let retry_error_cls = py | |
| 99 | + .import_bound(intern!(py, "lancedb.remote.errors"))? | |
| 100 | + .getattr("RetryError")?; | |
| 101 | + let err = retry_error_cls.call1(( | |
| 102 | + message, | |
| 103 | + request_id, | |
| 104 | + *request_failures, | |
| 105 | + *connect_failures, | |
| 106 | + *read_failures, | |
| 107 | + *max_request_failures, | |
| 108 | + *max_connect_failures, | |
| 109 | + *max_read_failures, | |
| 110 | + status_code.map(|s| s.as_u16()), | |
| 111 | + ))?; | |
| 112 | + | |
| 113 | + err.setattr(intern!(py, "__cause__"), cause_err)?; | |
| 114 | + Err(PyErr::from_value_bound(err)) | |
| 115 | + }), | |
| 47 | 116 | _ => self.runtime_error(), |
| 48 | 117 | }, |
| 49 | 118 | } |
| @@ -61,3 +130,24 @@ | ||
| 61 | 130 | self.map_err(|err| PyValueError::new_err(err.to_string())) |
| 62 | 131 | } |
| 63 | 132 | } |
| 133 | + | |
| 134 | +fn http_from_rust_error( | |
| 135 | + py: Python<'_>, | |
| 136 | + err: &dyn std::error::Error, | |
| 137 | + request_id: &str, | |
| 138 | + status_code: Option<u16>, | |
| 139 | +) -> PyResult<PyErr> { | |
| 140 | + let message = err.to_string(); | |
| 141 | + let http_err_cls = py.import("lancedb.remote.errors")?.getattr("HttpError")?; | |
| 142 | + let py_err = http_err_cls.call1((message, request_id, status_code))?; | |
| 143 | + | |
| 144 | + // Reset the traceback since it doesn't provide additional information. | |
| 145 | + let py_err = py_err.call_method1(intern!(py, "with_traceback"), (PyNone::get_bound(py),))?; | |
| 146 | + | |
| 147 | + if let Some(cause) = err.source() { | |
| 148 | + let cause_err = http_from_rust_error(py, cause, request_id, status_code)?; | |
| 149 | + py_err.setattr(intern!(py, "__cause__"), cause_err)?; | |
| 150 | + } | |
| 151 | + | |
| 152 | + Ok(PyErr::from_value(py_err)) | |
| 153 | +} |
modified rust/lancedb/src/error.rs +31 −20
| @@ -46,8 +46,37 @@ | ||
| 46 | 46 | ObjectStore { source: object_store::Error }, |
| 47 | 47 | #[snafu(display("lance error: {source}"))] |
| 48 | 48 | Lance { source: lance::Error }, |
| 49 | - #[snafu(display("Http error: {message}"))] | |
| 50 | - Http { message: String }, | |
| 49 | + #[cfg(feature = "remote")] | |
| 50 | + #[snafu(display("Http error: (request_id={request_id}) {source}"))] | |
| 51 | + Http { | |
| 52 | + #[snafu(source(from(reqwest::Error, Box::new)))] | |
| 53 | + source: Box<dyn std::error::Error + Send + Sync>, | |
| 54 | + request_id: String, | |
| 55 | + /// Status code associated with the error, if available. | |
| 56 | + /// This is not always available, for example when the error is due to a | |
| 57 | + /// connection failure. It may also be missing if the request was | |
| 58 | + /// successful but there was an error decoding the response. | |
| 59 | + status_code: Option<reqwest::StatusCode>, | |
| 60 | + }, | |
| 61 | + #[cfg(feature = "remote")] | |
| 62 | + #[snafu(display( | |
| 63 | + "Hit retry limit for request_id={request_id} (\ | |
| 64 | + request_failures={request_failures}/{max_request_failures}, \ | |
| 65 | + connect_failures={connect_failures}/{max_connect_failures}, \ | |
| 66 | + read_failures={read_failures}/{max_read_failures})" | |
| 67 | + ))] | |
| 68 | + Retry { | |
| 69 | + request_id: String, | |
| 70 | + request_failures: u8, | |
| 71 | + max_request_failures: u8, | |
| 72 | + connect_failures: u8, | |
| 73 | + max_connect_failures: u8, | |
| 74 | + read_failures: u8, | |
| 75 | + max_read_failures: u8, | |
| 76 | + #[snafu(source(from(reqwest::Error, Box::new)))] | |
| 77 | + source: Box<dyn std::error::Error + Send + Sync>, | |
| 78 | + status_code: Option<reqwest::StatusCode>, | |
| 79 | + }, | |
| 51 | 80 | #[snafu(display("Arrow error: {source}"))] |
| 52 | 81 | Arrow { source: ArrowError }, |
| 53 | 82 | #[snafu(display("LanceDBError: not supported: {message}"))] |
| @@ -98,24 +127,6 @@ | ||
| 98 | 127 | } |
| 99 | 128 | } |
| 100 | 129 | |
| 101 | -#[cfg(feature = "remote")] | |
| 102 | -impl From<reqwest::Error> for Error { | |
| 103 | - fn from(e: reqwest::Error) -> Self { | |
| 104 | - Self::Http { | |
| 105 | - message: e.to_string(), | |
| 106 | - } | |
| 107 | - } | |
| 108 | -} | |
| 109 | - | |
| 110 | -#[cfg(feature = "remote")] | |
| 111 | -impl From<url::ParseError> for Error { | |
| 112 | - fn from(e: url::ParseError) -> Self { | |
| 113 | - Self::Http { | |
| 114 | - message: e.to_string(), | |
| 115 | - } | |
| 116 | - } | |
| 117 | -} | |
| 118 | - | |
| 119 | 130 | #[cfg(feature = "polars")] |
| 120 | 131 | impl From<polars::prelude::PolarsError> for Error { |
| 121 | 132 | fn from(source: polars::prelude::PolarsError) -> Self { |
modified rust/lancedb/src/remote/client.rs +175 −81
| @@ -216,10 +216,12 @@ | ||
| 216 | 216 | host_override: Option<String>, |
| 217 | 217 | client_config: ClientConfig, |
| 218 | 218 | ) -> Result<Self> { |
| 219 | - let parsed_url = url::Url::parse(db_url)?; | |
| 219 | + let parsed_url = url::Url::parse(db_url).map_err(|err| Error::InvalidInput { | |
| 220 | + message: format!("db_url is not a valid URL. '{db_url}'. Error: {err}"), | |
| 221 | + })?; | |
| 220 | 222 | debug_assert_eq!(parsed_url.scheme(), "db"); |
| 221 | 223 | if !parsed_url.has_host() { |
| 222 | - return Err(Error::Http { | |
| 224 | + return Err(Error::InvalidInput { | |
| 223 | 225 | message: format!("Invalid database URL (missing host) '{}'", db_url), |
| 224 | 226 | }); |
| 225 | 227 | } |
| @@ -255,7 +257,11 @@ | ||
| 255 | 257 | host_override.is_some(), |
| 256 | 258 | )?) |
| 257 | 259 | .user_agent(client_config.user_agent) |
| 258 | - .build()?; | |
| 260 | + .build() | |
| 261 | + .map_err(|err| Error::Other { | |
| 262 | + message: "Failed to build HTTP client".into(), | |
| 263 | + source: Some(Box::new(err)), | |
| 264 | + })?; | |
| 259 | 265 | let host = match host_override { |
| 260 | 266 | Some(host_override) => host_override, |
| 261 | 267 | None => format!("https://{}.{}.api.lancedb.com", db_name, region), |
| @@ -284,7 +290,7 @@ | ||
| 284 | 290 | let mut headers = HeaderMap::new(); |
| 285 | 291 | headers.insert( |
| 286 | 292 | "x-api-key", |
| 287 | - HeaderValue::from_str(api_key).map_err(|_| Error::Http { | |
| 293 | + HeaderValue::from_str(api_key).map_err(|_| Error::InvalidInput { | |
| 288 | 294 | message: "non-ascii api key provided".to_string(), |
| 289 | 295 | })?, |
| 290 | 296 | ); |
| @@ -292,7 +298,7 @@ | ||
| 292 | 298 | let host = format!("{}.local.api.lancedb.com", db_name); |
| 293 | 299 | headers.insert( |
| 294 | 300 | "Host", |
| 295 | - HeaderValue::from_str(&host).map_err(|_| Error::Http { | |
| 301 | + HeaderValue::from_str(&host).map_err(|_| Error::InvalidInput { | |
| 296 | 302 | message: format!("non-ascii database name '{}' provided", db_name), |
| 297 | 303 | })?, |
| 298 | 304 | ); |
| @@ -300,7 +306,7 @@ | ||
| 300 | 306 | if has_host_override { |
| 301 | 307 | headers.insert( |
| 302 | 308 | "x-lancedb-database", |
| 303 | - HeaderValue::from_str(db_name).map_err(|_| Error::Http { | |
| 309 | + HeaderValue::from_str(db_name).map_err(|_| Error::InvalidInput { | |
| 304 | 310 | message: format!("non-ascii database name '{}' provided", db_name), |
| 305 | 311 | })?, |
| 306 | 312 | ); |
| @@ -319,22 +325,30 @@ | ||
| 319 | 325 | self.client.post(full_uri) |
| 320 | 326 | } |
| 321 | 327 | |
| 322 | - pub async fn send(&self, req: RequestBuilder, with_retry: bool) -> Result<Response> { | |
| 328 | + pub async fn send(&self, req: RequestBuilder, with_retry: bool) -> Result<(String, Response)> { | |
| 323 | 329 | let (client, request) = req.build_split(); |
| 324 | 330 | let mut request = request.unwrap(); |
| 325 | 331 | |
| 326 | 332 | // Set a request id. |
| 327 | 333 | // 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 | - } | |
| 334 | + let request_id = if let Some(request_id) = request.headers().get(REQUEST_ID_HEADER) { | |
| 335 | + request_id.to_str().unwrap().to_string() | |
| 336 | + } else { | |
| 337 | + let request_id = uuid::Uuid::new_v4().to_string(); | |
| 338 | + let header = HeaderValue::from_str(&request_id).unwrap(); | |
| 339 | + request.headers_mut().insert(REQUEST_ID_HEADER, header); | |
| 340 | + request_id | |
| 341 | + }; | |
| 333 | 342 | |
| 334 | 343 | if with_retry { |
| 335 | - self.send_with_retry_impl(client, request).await | |
| 344 | + self.send_with_retry_impl(client, request, request_id).await | |
| 336 | 345 | } else { |
| 337 | - Ok(self.sender.send(&client, request).await?) | |
| 346 | + let response = self | |
| 347 | + .sender | |
| 348 | + .send(&client, request) | |
| 349 | + .await | |
| 350 | + .err_to_http(request_id.clone())?; | |
| 351 | + Ok((request_id, response)) | |
| 338 | 352 | } |
| 339 | 353 | } |
| 340 | 354 | |
| @@ -342,98 +356,178 @@ | ||
| 342 | 356 | &self, |
| 343 | 357 | client: reqwest::Client, |
| 344 | 358 | req: Request, |
| 345 | - ) -> Result<Response> { | |
| 346 | - let mut request_failures = 0; | |
| 347 | - let mut connect_failures = 0; | |
| 348 | - let mut read_failures = 0; | |
| 359 | + request_id: String, | |
| 360 | + ) -> Result<(String, Response)> { | |
| 361 | + let mut retry_counter = RetryCounter::new(&self.retry_config, request_id); | |
| 349 | 362 | |
| 350 | 363 | loop { |
| 351 | 364 | // This only works if the request body is not a stream. If it is |
| 352 | 365 | // a stream, we can't use the retry path. We would need to implement |
| 353 | 366 | // an outer retry. |
| 354 | - let request = req.try_clone().ok_or_else(|| Error::Http { | |
| 367 | + let request = req.try_clone().ok_or_else(|| Error::Runtime { | |
| 355 | 368 | message: "Attempted to retry a request that cannot be cloned".to_string(), |
| 356 | 369 | })?; |
| 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 | - } | |
| 370 | + let response = self | |
| 371 | + .sender | |
| 372 | + .send(&client, request) | |
| 373 | + .await | |
| 374 | + .map(|r| (r.status(), r)); | |
| 375 | + match response { | |
| 376 | + Ok((status, response)) if status.is_success() => { | |
| 377 | + return Ok((retry_counter.request_id, response)) | |
| 378 | + } | |
| 379 | + Ok((status, response)) if self.retry_config.statuses.contains(&status) => { | |
| 380 | + let source = self | |
| 381 | + .check_response(&retry_counter.request_id, response) | |
| 382 | + .await | |
| 383 | + .unwrap_err(); | |
| 384 | + retry_counter.increment_request_failures(source)?; | |
| 372 | 385 | } |
| 373 | 386 | 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 | - } | |
| 387 | + retry_counter.increment_connect_failures(err)?; | |
| 383 | 388 | } |
| 384 | 389 | 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 | - } | |
| 390 | + retry_counter.increment_read_failures(err)?; | |
| 391 | + } | |
| 392 | + Err(err) => { | |
| 393 | + let status_code = err.status(); | |
| 394 | + return Err(Error::Http { | |
| 395 | + source: Box::new(err), | |
| 396 | + request_id: retry_counter.request_id, | |
| 397 | + status_code, | |
| 398 | + }); | |
| 394 | 399 | } |
| 395 | - Ok(_) | Err(_) => return Ok(response?), | |
| 400 | + Ok((_, response)) => return Ok((retry_counter.request_id, response)), | |
| 396 | 401 | } |
| 397 | 402 | |
| 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 | - ); | |
| 403 | + let sleep_time = retry_counter.next_sleep_time(); | |
| 414 | 404 | tokio::time::sleep(sleep_time).await; |
| 415 | 405 | } |
| 416 | 406 | } |
| 417 | 407 | |
| 418 | - async fn rsp_to_str(response: Response) -> String { | |
| 408 | + pub async fn check_response(&self, request_id: &str, response: Response) -> Result<Response> { | |
| 409 | + // Try to get the response text, but if that fails, just return the status code | |
| 419 | 410 | let status = response.status(); |
| 420 | - response.text().await.unwrap_or_else(|_| status.to_string()) | |
| 411 | + if status.is_success() { | |
| 412 | + Ok(response) | |
| 413 | + } else { | |
| 414 | + let response_text = response.text().await.ok(); | |
| 415 | + let message = if let Some(response_text) = response_text { | |
| 416 | + format!("{}: {}", status, response_text) | |
| 417 | + } else { | |
| 418 | + status.to_string() | |
| 419 | + }; | |
| 420 | + Err(Error::Http { | |
| 421 | + source: message.into(), | |
| 422 | + request_id: request_id.into(), | |
| 423 | + status_code: Some(status), | |
| 424 | + }) | |
| 425 | + } | |
| 421 | 426 | } |
| 427 | +} | |
| 422 | 428 | |
| 423 | - pub async fn check_response(&self, response: Response) -> Result<Response> { | |
| 424 | - let status_int: u16 = u16::from(response.status()); | |
| 425 | - if (400..500).contains(&status_int) { | |
| 426 | - Err(Error::InvalidInput { | |
| 427 | - message: Self::rsp_to_str(response).await, | |
| 428 | - }) | |
| 429 | - } else if status_int != 200 { | |
| 430 | - Err(Error::Runtime { | |
| 431 | - message: Self::rsp_to_str(response).await, | |
| 429 | +struct RetryCounter<'a> { | |
| 430 | + request_failures: u8, | |
| 431 | + connect_failures: u8, | |
| 432 | + read_failures: u8, | |
| 433 | + config: &'a ResolvedRetryConfig, | |
| 434 | + request_id: String, | |
| 435 | +} | |
| 436 | + | |
| 437 | +impl<'a> RetryCounter<'a> { | |
| 438 | + fn new(config: &'a ResolvedRetryConfig, request_id: String) -> Self { | |
| 439 | + Self { | |
| 440 | + request_failures: 0, | |
| 441 | + connect_failures: 0, | |
| 442 | + read_failures: 0, | |
| 443 | + config, | |
| 444 | + request_id, | |
| 445 | + } | |
| 446 | + } | |
| 447 | + | |
| 448 | + fn check_out_of_retries( | |
| 449 | + &self, | |
| 450 | + source: Box<dyn std::error::Error + Send + Sync>, | |
| 451 | + status_code: Option<reqwest::StatusCode>, | |
| 452 | + ) -> Result<()> { | |
| 453 | + if self.request_failures >= self.config.retries | |
| 454 | + || self.connect_failures >= self.config.connect_retries | |
| 455 | + || self.read_failures >= self.config.read_retries | |
| 456 | + { | |
| 457 | + Err(Error::Retry { | |
| 458 | + request_id: self.request_id.clone(), | |
| 459 | + request_failures: self.request_failures, | |
| 460 | + max_request_failures: self.config.retries, | |
| 461 | + connect_failures: self.connect_failures, | |
| 462 | + max_connect_failures: self.config.connect_retries, | |
| 463 | + read_failures: self.read_failures, | |
| 464 | + max_read_failures: self.config.read_retries, | |
| 465 | + source, | |
| 466 | + status_code, | |
| 432 | 467 | }) |
| 433 | 468 | } else { |
| 434 | - Ok(response) | |
| 469 | + Ok(()) | |
| 435 | 470 | } |
| 436 | 471 | } |
| 472 | + | |
| 473 | + fn increment_request_failures(&mut self, source: crate::Error) -> Result<()> { | |
| 474 | + self.request_failures += 1; | |
| 475 | + let status_code = if let crate::Error::Http { status_code, .. } = &source { | |
| 476 | + *status_code | |
| 477 | + } else { | |
| 478 | + None | |
| 479 | + }; | |
| 480 | + self.check_out_of_retries(Box::new(source), status_code) | |
| 481 | + } | |
| 482 | + | |
| 483 | + fn increment_connect_failures(&mut self, source: reqwest::Error) -> Result<()> { | |
| 484 | + self.connect_failures += 1; | |
| 485 | + let status_code = source.status(); | |
| 486 | + self.check_out_of_retries(Box::new(source), status_code) | |
| 487 | + } | |
| 488 | + | |
| 489 | + fn increment_read_failures(&mut self, source: reqwest::Error) -> Result<()> { | |
| 490 | + self.read_failures += 1; | |
| 491 | + let status_code = source.status(); | |
| 492 | + self.check_out_of_retries(Box::new(source), status_code) | |
| 493 | + } | |
| 494 | + | |
| 495 | + fn next_sleep_time(&self) -> Duration { | |
| 496 | + let backoff = self.config.backoff_factor * (2.0f32.powi(self.request_failures as i32)); | |
| 497 | + let jitter = rand::random::<f32>() * self.config.backoff_jitter; | |
| 498 | + let sleep_time = Duration::from_secs_f32(backoff + jitter); | |
| 499 | + debug!( | |
| 500 | + "Retrying request {:?} ({}/{} connect, {}/{} read, {}/{} read) in {:?}", | |
| 501 | + self.request_id, | |
| 502 | + self.connect_failures, | |
| 503 | + self.config.connect_retries, | |
| 504 | + self.request_failures, | |
| 505 | + self.config.retries, | |
| 506 | + self.read_failures, | |
| 507 | + self.config.read_retries, | |
| 508 | + sleep_time | |
| 509 | + ); | |
| 510 | + sleep_time | |
| 511 | + } | |
| 512 | +} | |
| 513 | + | |
| 514 | +pub trait RequestResultExt { | |
| 515 | + type Output; | |
| 516 | + fn err_to_http(self, request_id: String) -> Result<Self::Output>; | |
| 517 | +} | |
| 518 | + | |
| 519 | +impl<T> RequestResultExt for reqwest::Result<T> { | |
| 520 | + type Output = T; | |
| 521 | + fn err_to_http(self, request_id: String) -> Result<T> { | |
| 522 | + self.map_err(|err| { | |
| 523 | + let status_code = err.status(); | |
| 524 | + Error::Http { | |
| 525 | + source: Box::new(err), | |
| 526 | + request_id, | |
| 527 | + status_code, | |
| 528 | + } | |
| 529 | + }) | |
| 530 | + } | |
| 437 | 531 | } |
| 438 | 532 | |
| 439 | 533 | #[cfg(test)] |
modified rust/lancedb/src/remote/db.rs +61 −18
| @@ -29,7 +29,7 @@ | ||
| 29 | 29 | use crate::error::Result; |
| 30 | 30 | use crate::Table; |
| 31 | 31 | |
| 32 | -use super::client::{ClientConfig, HttpSend, RestfulLanceDbClient, Sender}; | |
| 32 | +use super::client::{ClientConfig, HttpSend, RequestResultExt, RestfulLanceDbClient, Sender}; | |
| 33 | 33 | use super::table::RemoteTable; |
| 34 | 34 | use super::util::batches_to_ipc_bytes; |
| 35 | 35 | use super::ARROW_STREAM_CONTENT_TYPE; |
| @@ -105,9 +105,13 @@ | ||
| 105 | 105 | if let Some(start_after) = options.start_after { |
| 106 | 106 | req = req.query(&[("page_token", start_after)]); |
| 107 | 107 | } |
| 108 | - let rsp = self.client.send(req, true).await?; | |
| 109 | - let rsp = self.client.check_response(rsp).await?; | |
| 110 | - let tables = rsp.json::<ListTablesResponse>().await?.tables; | |
| 108 | + let (request_id, rsp) = self.client.send(req, true).await?; | |
| 109 | + let rsp = self.client.check_response(&request_id, rsp).await?; | |
| 110 | + let tables = rsp | |
| 111 | + .json::<ListTablesResponse>() | |
| 112 | + .await | |
| 113 | + .err_to_http(request_id)? | |
| 114 | + .tables; | |
| 111 | 115 | for table in &tables { |
| 112 | 116 | self.table_cache.insert(table.clone(), ()).await; |
| 113 | 117 | } |
| @@ -130,13 +134,11 @@ | ||
| 130 | 134 | .client |
| 131 | 135 | .post(&format!("/v1/table/{}/create/", options.name)) |
| 132 | 136 | .body(data_buffer) |
| 133 | - .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) | |
| 134 | - // This is currently expected by LanceDb cloud but will be removed soon. | |
| 135 | - .header("x-request-id", "na"); | |
| 136 | - let rsp = self.client.send(req, false).await?; | |
| 137 | + .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE); | |
| 138 | + let (request_id, rsp) = self.client.send(req, false).await?; | |
| 137 | 139 | |
| 138 | 140 | if rsp.status() == StatusCode::BAD_REQUEST { |
| 139 | - let body = rsp.text().await?; | |
| 141 | + let body = rsp.text().await.err_to_http(request_id.clone())?; | |
| 140 | 142 | if body.contains("already exists") { |
| 141 | 143 | return Err(crate::Error::TableAlreadyExists { name: options.name }); |
| 142 | 144 | } else { |
| @@ -144,7 +146,7 @@ | ||
| 144 | 146 | } |
| 145 | 147 | } |
| 146 | 148 | |
| 147 | - self.client.check_response(rsp).await?; | |
| 149 | + self.client.check_response(&request_id, rsp).await?; | |
| 148 | 150 | |
| 149 | 151 | self.table_cache.insert(options.name.clone(), ()).await; |
| 150 | 152 | |
| @@ -160,11 +162,11 @@ | ||
| 160 | 162 | let req = self |
| 161 | 163 | .client |
| 162 | 164 | .get(&format!("/v1/table/{}/describe/", options.name)); |
| 163 | - let resp = self.client.send(req, true).await?; | |
| 165 | + let (request_id, resp) = self.client.send(req, true).await?; | |
| 164 | 166 | if resp.status() == StatusCode::NOT_FOUND { |
| 165 | 167 | return Err(crate::Error::TableNotFound { name: options.name }); |
| 166 | 168 | } |
| 167 | - self.client.check_response(resp).await?; | |
| 169 | + self.client.check_response(&request_id, resp).await?; | |
| 168 | 170 | } |
| 169 | 171 | |
| 170 | 172 | Ok(Table::new(Arc::new(RemoteTable::new( |
| @@ -178,8 +180,8 @@ | ||
| 178 | 180 | .client |
| 179 | 181 | .post(&format!("/v1/table/{}/rename/", current_name)); |
| 180 | 182 | let req = req.json(&serde_json::json!({ "new_table_name": new_name })); |
| 181 | - let resp = self.client.send(req, false).await?; | |
| 182 | - self.client.check_response(resp).await?; | |
| 183 | + let (request_id, resp) = self.client.send(req, false).await?; | |
| 184 | + self.client.check_response(&request_id, resp).await?; | |
| 183 | 185 | self.table_cache.remove(current_name).await; |
| 184 | 186 | self.table_cache.insert(new_name.into(), ()).await; |
| 185 | 187 | Ok(()) |
| @@ -187,8 +189,8 @@ | ||
| 187 | 189 | |
| 188 | 190 | async fn drop_table(&self, name: &str) -> Result<()> { |
| 189 | 191 | let req = self.client.post(&format!("/v1/table/{}/drop/", name)); |
| 190 | - let resp = self.client.send(req, true).await?; | |
| 191 | - self.client.check_response(resp).await?; | |
| 192 | + let (request_id, resp) = self.client.send(req, true).await?; | |
| 193 | + self.client.check_response(&request_id, resp).await?; | |
| 192 | 194 | self.table_cache.remove(name).await; |
| 193 | 195 | Ok(()) |
| 194 | 196 | } |
| @@ -206,16 +208,57 @@ | ||
| 206 | 208 | |
| 207 | 209 | #[cfg(test)] |
| 208 | 210 | mod tests { |
| 209 | - use std::sync::Arc; | |
| 211 | + use std::sync::{Arc, OnceLock}; | |
| 210 | 212 | |
| 211 | 213 | use arrow_array::{Int32Array, RecordBatch, RecordBatchIterator}; |
| 212 | 214 | use arrow_schema::{DataType, Field, Schema}; |
| 213 | 215 | |
| 214 | 216 | use crate::{ |
| 215 | 217 | remote::{ARROW_STREAM_CONTENT_TYPE, JSON_CONTENT_TYPE}, |
| 216 | - Connection, | |
| 218 | + Connection, Error, | |
| 217 | 219 | }; |
| 218 | 220 | |
| 221 | + #[tokio::test] | |
| 222 | + async fn test_retries() { | |
| 223 | + // We'll record the request_id here, to check it matches the one in the error. | |
| 224 | + let seen_request_id = Arc::new(OnceLock::new()); | |
| 225 | + let seen_request_id_ref = seen_request_id.clone(); | |
| 226 | + let conn = Connection::new_with_handler(move |request| { | |
| 227 | + // Request id should be the same on each retry. | |
| 228 | + let request_id = request.headers()["x-request-id"] | |
| 229 | + .to_str() | |
| 230 | + .unwrap() | |
| 231 | + .to_string(); | |
| 232 | + let seen_id = seen_request_id_ref.get_or_init(|| request_id.clone()); | |
| 233 | + assert_eq!(&request_id, seen_id); | |
| 234 | + | |
| 235 | + http::Response::builder() | |
| 236 | + .status(500) | |
| 237 | + .body("internal server error") | |
| 238 | + .unwrap() | |
| 239 | + }); | |
| 240 | + let result = conn.table_names().execute().await; | |
| 241 | + if let Err(Error::Retry { | |
| 242 | + request_id, | |
| 243 | + request_failures, | |
| 244 | + max_request_failures, | |
| 245 | + source, | |
| 246 | + .. | |
| 247 | + }) = result | |
| 248 | + { | |
| 249 | + let expected_id = seen_request_id.get().unwrap(); | |
| 250 | + assert_eq!(&request_id, expected_id); | |
| 251 | + assert_eq!(request_failures, max_request_failures); | |
| 252 | + assert!( | |
| 253 | + source.to_string().contains("internal server error"), | |
| 254 | + "source: {:?}", | |
| 255 | + source | |
| 256 | + ); | |
| 257 | + } else { | |
| 258 | + panic!("unexpected result: {:?}", result); | |
| 259 | + }; | |
| 260 | + } | |
| 261 | + | |
| 219 | 262 | #[tokio::test] |
| 220 | 263 | async fn test_table_names() { |
| 221 | 264 | let conn = Connection::new_with_handler(|request| { |
modified rust/lancedb/src/remote/table.rs +79 −46
| @@ -34,6 +34,7 @@ | ||
| 34 | 34 | }, |
| 35 | 35 | }; |
| 36 | 36 | |
| 37 | +use super::client::RequestResultExt; | |
| 37 | 38 | use super::client::{HttpSend, RestfulLanceDbClient, Sender}; |
| 38 | 39 | use super::{ARROW_STREAM_CONTENT_TYPE, JSON_CONTENT_TYPE}; |
| 39 | 40 | |
| @@ -53,15 +54,25 @@ | ||
| 53 | 54 | let request = self |
| 54 | 55 | .client |
| 55 | 56 | .post(&format!("/v1/table/{}/describe/", self.name)); |
| 56 | - let response = self.client.send(request, true).await?; | |
| 57 | - | |
| 58 | - let response = self.check_table_response(response).await?; | |
| 59 | - | |
| 60 | - let body = response.text().await?; | |
| 61 | - | |
| 62 | - serde_json::from_str(&body).map_err(|e| Error::Http { | |
| 63 | - message: format!("Failed to parse table description: {}", e), | |
| 64 | - }) | |
| 57 | + let (request_id, response) = self.client.send(request, true).await?; | |
| 58 | + | |
| 59 | + let response = self.check_table_response(&request_id, response).await?; | |
| 60 | + | |
| 61 | + match response.text().await { | |
| 62 | + Ok(body) => serde_json::from_str(&body).map_err(|e| Error::Http { | |
| 63 | + source: format!("Failed to parse table description: {}", e).into(), | |
| 64 | + request_id, | |
| 65 | + status_code: None, | |
| 66 | + }), | |
| 67 | + Err(err) => { | |
| 68 | + let status_code = err.status(); | |
| 69 | + Err(Error::Http { | |
| 70 | + source: Box::new(err), | |
| 71 | + request_id, | |
| 72 | + status_code, | |
| 73 | + }) | |
| 74 | + } | |
| 75 | + } | |
| 65 | 76 | } |
| 66 | 77 | |
| 67 | 78 | fn reader_as_body(data: Box<dyn RecordBatchReader + Send>) -> Result<reqwest::Body> { |
| @@ -87,18 +98,23 @@ | ||
| 87 | 98 | Ok(reqwest::Body::wrap_stream(body_stream)) |
| 88 | 99 | } |
| 89 | 100 | |
| 90 | - async fn check_table_response(&self, response: reqwest::Response) -> Result<reqwest::Response> { | |
| 101 | + async fn check_table_response( | |
| 102 | + &self, | |
| 103 | + request_id: &str, | |
| 104 | + response: reqwest::Response, | |
| 105 | + ) -> Result<reqwest::Response> { | |
| 91 | 106 | if response.status() == StatusCode::NOT_FOUND { |
| 92 | 107 | return Err(Error::TableNotFound { |
| 93 | 108 | name: self.name.clone(), |
| 94 | 109 | }); |
| 95 | 110 | } |
| 96 | 111 | |
| 97 | - self.client.check_response(response).await | |
| 112 | + self.client.check_response(request_id, response).await | |
| 98 | 113 | } |
| 99 | 114 | |
| 100 | 115 | async fn read_arrow_stream( |
| 101 | 116 | &self, |
| 117 | + request_id: &str, | |
| 102 | 118 | body: reqwest::Response, |
| 103 | 119 | ) -> Result<SendableRecordBatchStream> { |
| 104 | 120 | // Assert that the content type is correct |
| @@ -106,24 +122,31 @@ | ||
| 106 | 122 | .headers() |
| 107 | 123 | .get(CONTENT_TYPE) |
| 108 | 124 | .ok_or_else(|| Error::Http { |
| 109 | - message: "Missing content type".into(), | |
| 125 | + source: "Missing content type".into(), | |
| 126 | + request_id: request_id.to_string(), | |
| 127 | + status_code: None, | |
| 110 | 128 | })? |
| 111 | 129 | .to_str() |
| 112 | 130 | .map_err(|e| Error::Http { |
| 113 | - message: format!("Failed to parse content type: {}", e), | |
| 131 | + source: format!("Failed to parse content type: {}", e).into(), | |
| 132 | + request_id: request_id.to_string(), | |
| 133 | + status_code: None, | |
| 114 | 134 | })?; |
| 115 | 135 | if content_type != ARROW_STREAM_CONTENT_TYPE { |
| 116 | 136 | return Err(Error::Http { |
| 117 | - message: format!( | |
| 137 | + source: format!( | |
| 118 | 138 | "Expected content type {}, got {}", |
| 119 | 139 | ARROW_STREAM_CONTENT_TYPE, content_type |
| 120 | - ), | |
| 140 | + ) | |
| 141 | + .into(), | |
| 142 | + request_id: request_id.to_string(), | |
| 143 | + status_code: None, | |
| 121 | 144 | }); |
| 122 | 145 | } |
| 123 | 146 | |
| 124 | 147 | // There isn't a way to actually stream this data yet. I have an upstream issue: |
| 125 | 148 | // https://github.com/apache/arrow-rs/issues/6420 |
| 126 | - let body = body.bytes().await?; | |
| 149 | + let body = body.bytes().await.err_to_http(request_id.into())?; | |
| 127 | 150 | let reader = StreamReader::try_new(body.reader(), None)?; |
| 128 | 151 | let schema = reader.schema(); |
| 129 | 152 | let stream = futures::stream::iter(reader).map_err(DataFusionError::from); |
| @@ -259,14 +282,16 @@ | ||
| 259 | 282 | request = request.json(&serde_json::json!({})); |
| 260 | 283 | } |
| 261 | 284 | |
| 262 | - let response = self.client.send(request, true).await?; | |
| 285 | + let (request_id, response) = self.client.send(request, true).await?; | |
| 263 | 286 | |
| 264 | - let response = self.check_table_response(response).await?; | |
| 287 | + let response = self.check_table_response(&request_id, response).await?; | |
| 265 | 288 | |
| 266 | - let body = response.text().await?; | |
| 289 | + let body = response.text().await.err_to_http(request_id.clone())?; | |
| 267 | 290 | |
| 268 | 291 | serde_json::from_str(&body).map_err(|e| Error::Http { |
| 269 | - message: format!("Failed to parse row count: {}", e), | |
| 292 | + source: format!("Failed to parse row count: {}", e).into(), | |
| 293 | + request_id, | |
| 294 | + status_code: None, | |
| 270 | 295 | }) |
| 271 | 296 | } |
| 272 | 297 | async fn add( |
| @@ -288,9 +313,9 @@ | ||
| 288 | 313 | } |
| 289 | 314 | } |
| 290 | 315 | |
| 291 | - let response = self.client.send(request, false).await?; | |
| 316 | + let (request_id, response) = self.client.send(request, false).await?; | |
| 292 | 317 | |
| 293 | - self.check_table_response(response).await?; | |
| 318 | + self.check_table_response(&request_id, response).await?; | |
| 294 | 319 | |
| 295 | 320 | Ok(()) |
| 296 | 321 | } |
| @@ -339,9 +364,9 @@ | ||
| 339 | 364 | |
| 340 | 365 | let request = request.json(&body); |
| 341 | 366 | |
| 342 | - let response = self.client.send(request, true).await?; | |
| 367 | + let (request_id, response) = self.client.send(request, true).await?; | |
| 343 | 368 | |
| 344 | - let stream = self.read_arrow_stream(response).await?; | |
| 369 | + let stream = self.read_arrow_stream(&request_id, response).await?; | |
| 345 | 370 | |
| 346 | 371 | Ok(Arc::new(OneShotExec::new(stream))) |
| 347 | 372 | } |
| @@ -361,9 +386,9 @@ | ||
| 361 | 386 | |
| 362 | 387 | let request = request.json(&body); |
| 363 | 388 | |
| 364 | - let response = self.client.send(request, true).await?; | |
| 389 | + let (request_id, response) = self.client.send(request, true).await?; | |
| 365 | 390 | |
| 366 | - let stream = self.read_arrow_stream(response).await?; | |
| 391 | + let stream = self.read_arrow_stream(&request_id, response).await?; | |
| 367 | 392 | |
| 368 | 393 | Ok(DatasetRecordBatchStream::new(stream)) |
| 369 | 394 | } |
| @@ -383,17 +408,20 @@ | ||
| 383 | 408 | "only_if": update.filter, |
| 384 | 409 | })); |
| 385 | 410 | |
| 386 | - let response = self.client.send(request, false).await?; | |
| 411 | + let (request_id, response) = self.client.send(request, false).await?; | |
| 387 | 412 | |
| 388 | - let response = self.check_table_response(response).await?; | |
| 413 | + let response = self.check_table_response(&request_id, response).await?; | |
| 389 | 414 | |
| 390 | - let body = response.text().await?; | |
| 415 | + let body = response.text().await.err_to_http(request_id.clone())?; | |
| 391 | 416 | |
| 392 | 417 | serde_json::from_str(&body).map_err(|e| Error::Http { |
| 393 | - message: format!( | |
| 418 | + source: format!( | |
| 394 | 419 | "Failed to parse updated rows result from response {}: {}", |
| 395 | 420 | body, e |
| 396 | - ), | |
| 421 | + ) | |
| 422 | + .into(), | |
| 423 | + request_id, | |
| 424 | + status_code: None, | |
| 397 | 425 | }) |
| 398 | 426 | } |
| 399 | 427 | async fn delete(&self, predicate: &str) -> Result<()> { |
| @@ -402,8 +430,8 @@ | ||
| 402 | 430 | .client |
| 403 | 431 | .post(&format!("/v1/table/{}/delete/", self.name)) |
| 404 | 432 | .json(&body); |
| 405 | - let response = self.client.send(request, false).await?; | |
| 406 | - self.check_table_response(response).await?; | |
| 433 | + let (request_id, response) = self.client.send(request, false).await?; | |
| 434 | + self.check_table_response(&request_id, response).await?; | |
| 407 | 435 | Ok(()) |
| 408 | 436 | } |
| 409 | 437 | |
| @@ -474,9 +502,9 @@ | ||
| 474 | 502 | |
| 475 | 503 | let request = request.json(&body); |
| 476 | 504 | |
| 477 | - let response = self.client.send(request, false).await?; | |
| 505 | + let (request_id, response) = self.client.send(request, false).await?; | |
| 478 | 506 | |
| 479 | - self.check_table_response(response).await?; | |
| 507 | + self.check_table_response(&request_id, response).await?; | |
| 480 | 508 | |
| 481 | 509 | Ok(()) |
| 482 | 510 | } |
| @@ -495,9 +523,9 @@ | ||
| 495 | 523 | .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE) |
| 496 | 524 | .body(body); |
| 497 | 525 | |
| 498 | - let response = self.client.send(request, false).await?; | |
| 526 | + let (request_id, response) = self.client.send(request, false).await?; | |
| 499 | 527 | |
| 500 | - self.check_table_response(response).await?; | |
| 528 | + self.check_table_response(&request_id, response).await?; | |
| 501 | 529 | |
| 502 | 530 | Ok(()) |
| 503 | 531 | } |
| @@ -531,8 +559,8 @@ | ||
| 531 | 559 | let request = self |
| 532 | 560 | .client |
| 533 | 561 | .post(&format!("/v1/table/{}/index/list/", self.name)); |
| 534 | - let response = self.client.send(request, true).await?; | |
| 535 | - let response = self.check_table_response(response).await?; | |
| 562 | + let (request_id, response) = self.client.send(request, true).await?; | |
| 563 | + let response = self.check_table_response(&request_id, response).await?; | |
| 536 | 564 | |
| 537 | 565 | #[derive(Deserialize)] |
| 538 | 566 | struct ListIndicesResponse { |
| @@ -545,12 +573,15 @@ | ||
| 545 | 573 | columns: Vec<String>, |
| 546 | 574 | } |
| 547 | 575 | |
| 548 | - let body = response.text().await?; | |
| 576 | + let body = response.text().await.err_to_http(request_id.clone())?; | |
| 549 | 577 | let body: ListIndicesResponse = serde_json::from_str(&body).map_err(|err| Error::Http { |
| 550 | - message: format!( | |
| 578 | + source: format!( | |
| 551 | 579 | "Failed to parse list_indices response: {}, body: {}", |
| 552 | 580 | err, body |
| 553 | - ), | |
| 581 | + ) | |
| 582 | + .into(), | |
| 583 | + request_id, | |
| 584 | + status_code: None, | |
| 554 | 585 | })?; |
| 555 | 586 | |
| 556 | 587 | // Make request to get stats for each index, so we get the index type. |
| @@ -581,18 +612,20 @@ | ||
| 581 | 612 | "/v1/table/{}/index/{}/stats/", |
| 582 | 613 | self.name, index_name |
| 583 | 614 | )); |
| 584 | - let response = self.client.send(request, true).await?; | |
| 615 | + let (request_id, response) = self.client.send(request, true).await?; | |
| 585 | 616 | |
| 586 | 617 | if response.status() == StatusCode::NOT_FOUND { |
| 587 | 618 | return Ok(None); |
| 588 | 619 | } |
| 589 | 620 | |
| 590 | - let response = self.check_table_response(response).await?; | |
| 621 | + let response = self.check_table_response(&request_id, response).await?; | |
| 591 | 622 | |
| 592 | - let body = response.text().await?; | |
| 623 | + let body = response.text().await.err_to_http(request_id.clone())?; | |
| 593 | 624 | |
| 594 | 625 | let stats = serde_json::from_str(&body).map_err(|e| Error::Http { |
| 595 | - message: format!("Failed to parse index statistics: {}", e), | |
| 626 | + source: format!("Failed to parse index statistics: {}", e).into(), | |
| 627 | + request_id, | |
| 628 | + status_code: None, | |
| 596 | 629 | })?; |
| 597 | 630 | |
| 598 | 631 | Ok(Some(stats)) |