This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-python-config-open-timeout-offset-and-async-borrows in repository https://gitbox.apache.org/repos/asf/opendal.git
commit ed9fb9e60f2d9066f75eb3d65344cf44c09defad Author: Xuanwo <[email protected]> AuthorDate: Tue Nov 24 02:53:30 2026 +0100 fix(bindings/python): validate config/open kwargs, reject sub-ns timeouts, widen read ranges to u64, and drop unnecessary async mut borrows --- bindings/python/python/opendal/file.pyi | 4 +- bindings/python/python/opendal/operator.pyi | 6 + bindings/python/src/file.rs | 19 +-- bindings/python/src/layers/timeout.rs | 15 ++- bindings/python/src/lister.rs | 39 ++++-- bindings/python/src/operator.rs | 141 +++++++++++++-------- bindings/python/src/options.rs | 56 +++++++- bindings/python/tests/layers/test_timeout_layer.py | 83 ++++++++++++ bindings/python/tests/test_async_list.py | 36 ++++++ bindings/python/tests/test_from_config.py | 67 ++++++++++ bindings/python/tests/test_open_modes.py | 41 ++++++ bindings/python/tests/test_read.py | 72 ++++++++++- dev/src/generate/options.rs | 4 +- 13 files changed, 490 insertions(+), 93 deletions(-) diff --git a/bindings/python/python/opendal/file.pyi b/bindings/python/python/opendal/file.pyi index 569e8c6755..d8537a87c7 100644 --- a/bindings/python/python/opendal/file.pyi +++ b/bindings/python/python/opendal/file.pyi @@ -81,9 +81,7 @@ class AsyncFile: coroutine An awaitable that returns the bytes read from the stream. """ - def read_buffered( - self, /, size: SupportsIndex - ) -> collections.abc.Awaitable[bytes]: + def read_buffered(self, /, size: SupportsIndex) -> collections.abc.Awaitable[bytes]: """ Read up to `size` bytes by combining immediately available data. diff --git a/bindings/python/python/opendal/operator.pyi b/bindings/python/python/opendal/operator.pyi index 38918d5e28..ab515dcd87 100644 --- a/bindings/python/python/opendal/operator.pyi +++ b/bindings/python/python/opendal/operator.pyi @@ -346,6 +346,9 @@ class AsyncOperator: Raises ------ + TypeError + If `**kwargs` contains an unknown keyword argument, an option that + does not apply to `mode`, or a value with an incompatible type. ValueError If the mode is invalid or unsupported, including text (`"t"`) and update (`"+"`) modes, or if the mode conflicts with `append` or @@ -1063,6 +1066,9 @@ class Operator: Raises ------ + TypeError + If `**kwargs` contains an unknown keyword argument, an option that + does not apply to `mode`, or a value with an incompatible type. ValueError If the mode is invalid or unsupported, including text (`"t"`) and update (`"+"`) modes, or if the mode conflicts with `append` or diff --git a/bindings/python/src/file.rs b/bindings/python/src/file.rs index 38e013befb..b9497a9906 100644 --- a/bindings/python/src/file.rs +++ b/bindings/python/src/file.rs @@ -769,11 +769,7 @@ impl AsyncFile { /// coroutine /// An awaitable that returns the number of bytes written. #[pyo3(signature = (bs: "bytes") -> "collections.abc.Awaitable[int]")] - pub fn write<'p>( - &'p mut self, - py: Python<'p>, - bs: &Bound<PyBytes>, - ) -> PyResult<Bound<'p, PyAny>> { + pub fn write<'p>(&'p self, py: Python<'p>, bs: &Bound<PyBytes>) -> PyResult<Bound<'p, PyAny>> { let state = self.0.clone(); let bs = py_bytes_like_into_buffer(bs.as_any())?; @@ -827,12 +823,7 @@ impl AsyncFile { /// coroutine /// An awaitable that returns the current absolute position. #[pyo3(signature = (pos, whence = 0) -> "collections.abc.Awaitable[int]")] - pub fn seek<'p>( - &'p mut self, - py: Python<'p>, - pos: i64, - whence: u8, - ) -> PyResult<Bound<'p, PyAny>> { + pub fn seek<'p>(&'p self, py: Python<'p>, pos: i64, whence: u8) -> PyResult<Bound<'p, PyAny>> { let state = self.0.clone(); let whence = match whence { @@ -871,7 +862,7 @@ impl AsyncFile { /// ValueError /// If the file is closed. #[pyo3(signature = () -> "collections.abc.Awaitable[int]")] - pub fn tell<'p>(&'p mut self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> { + pub fn tell<'p>(&'p self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> { let state = self.0.clone(); future_into_py(py, async move { @@ -900,7 +891,7 @@ impl AsyncFile { /// ----- /// A closed file cannot be used for further I/O operations. #[pyo3(signature = () -> "collections.abc.Awaitable[None]")] - fn close<'p>(&'p mut self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> { + fn close<'p>(&'p self, py: Python<'p>) -> PyResult<Bound<'p, PyAny>> { let state = self.0.clone(); future_into_py(py, async move { let mut state = state.lock().await; @@ -924,7 +915,7 @@ impl AsyncFile { exc_value: "BaseException | None", traceback: "types.TracebackType | None") -> "collections.abc.Awaitable[None]")] fn __aexit__<'a>( - &'a mut self, + &'a self, py: Python<'a>, exc_type: &Bound<'a, PyAny>, exc_value: &Bound<'a, PyAny>, diff --git a/bindings/python/src/layers/timeout.rs b/bindings/python/src/layers/timeout.rs index 1969d66a9a..95502c4440 100644 --- a/bindings/python/src/layers/timeout.rs +++ b/bindings/python/src/layers/timeout.rs @@ -24,19 +24,26 @@ use opendal::Operator; /// Parse a timeout given in seconds into a [`Duration`]. /// -/// Rejects non-positive, non-finite, or out-of-range values. A zero timeout -/// is rejected because it would make every operation time out immediately. +/// Rejects non-positive, non-finite, sub-nanosecond values that round to zero, +/// or out-of-range values. A zero timeout is rejected because it would make +/// every operation time out immediately. fn parse_timeout_secs(name: &str, secs: f64) -> PyResult<Duration> { if !secs.is_finite() || secs <= 0.0 { return Err(ConfigInvalid::new_err(format!( "{name} must be a positive, finite number of seconds" ))); } - Duration::try_from_secs_f64(secs).map_err(|_| { + let timeout = Duration::try_from_secs_f64(secs).map_err(|_| { ConfigInvalid::new_err(format!( "{name} must be a positive, finite number of seconds" )) - }) + })?; + if timeout.is_zero() { + return Err(ConfigInvalid::new_err(format!( + "{name} must be a positive, finite number of seconds" + ))); + } + Ok(timeout) } /// A layer that adds timeouts to operations. diff --git a/bindings/python/src/lister.rs b/bindings/python/src/lister.rs index 7f5e35d4b8..ccf7b05879 100644 --- a/bindings/python/src/lister.rs +++ b/bindings/python/src/lister.rs @@ -334,20 +334,37 @@ impl AsyncLister { fn __aiter__(slf: PyRef<'_, Self>) -> PyRef<'_, Self> { slf } - fn __anext__(slf: PyRefMut<'_, Self>) -> PyResult<Option<Py<PyAny>>> { + fn __anext__(slf: PyRef<'_, Self>) -> PyResult<Option<Py<PyAny>>> { check_runtime_process()?; slf.reconcile_deliveries(slf.py())?; - if let Some(mut state) = slf.state.try_lock() { - let mut requeued = slf.requeued.lock().unwrap(); - if !requeued.is_empty() || !state.buffered.is_empty() || state.exhausted { - let py = slf.py(); - let future = pyo3_async_runtimes::get_running_loop(py)? - .call_method0(pyo3::intern!(py, "create_future"))?; - let entry = requeued - .pop_front() - .map(Ok) - .or_else(|| state.buffered.pop_front()); + let has_ready = if let Some(state) = slf.state.try_lock() { + let requeued = slf.requeued.lock().unwrap(); + !requeued.is_empty() || !state.buffered.is_empty() || state.exhausted + } else { + false + }; + + if has_ready { + let py = slf.py(); + let future = pyo3_async_runtimes::get_running_loop(py)? + .call_method0(pyo3::intern!(py, "create_future"))?; + let next_item = if let Some(mut state) = slf.state.try_lock() { + let mut requeued = slf.requeued.lock().unwrap(); + if !requeued.is_empty() || !state.buffered.is_empty() || state.exhausted { + Some( + requeued + .pop_front() + .map(Ok) + .or_else(|| state.buffered.pop_front()), + ) + } else { + None + } + } else { + None + }; + if let Some(entry) = next_item { let result = match entry { Some(Ok(entry)) => Entry::new(entry).into_py_any(py), Some(Err(err)) => Err(format_pyerr(err)), diff --git a/bindings/python/src/operator.rs b/bindings/python/src/operator.rs index 559e301f42..5ea223f34f 100644 --- a/bindings/python/src/operator.rs +++ b/bindings/python/src/operator.rs @@ -25,6 +25,7 @@ use pyo3::exceptions::PyValueError; use pyo3::types::PyBytes; use pyo3::types::PyDelta; use pyo3::types::PyDict; +use pyo3::types::PyList; use pyo3::types::PyString; use pyo3::types::PyTuple; use pyo3::types::PyType; @@ -144,16 +145,21 @@ fn extract_delete_paths(paths: &Bound<'_, PyAny>) -> PyResult<Vec<String>> { .collect() } -/// Convert a config value into the string form core's config deserializer -/// consumes. -/// -/// Accepts the native types the `opendal.config` TypedDicts declare: `str`, -/// `bool`, `int`, `datetime.timedelta`, `os.PathLike`, and `list`/`tuple` of those -/// (`,`-joined, as core parses `Vec`). A nested `dict` has no flat-map form and is rejected. -fn config_value_to_string(value: &Bound<PyAny>) -> PyResult<String> { - // `str` before the list branch (a `str` is also a sequence); `bool` before - // `int` (a Python `bool` also extracts as `int`); `dict` before the list - // branch so a map is rejected rather than read as its keys. +fn is_python_mapping(value: &Bound<PyAny>) -> PyResult<bool> { + if value.cast::<PyDict>().is_ok() { + return Ok(true); + } + let py = value.py(); + let mapping = py + .import(pyo3::intern!(py, "collections.abc"))? + .getattr(pyo3::intern!(py, "Mapping"))?; + value.is_instance(&mapping) +} + +fn config_scalar_to_string(value: &Bound<PyAny>) -> PyResult<String> { + let py = value.py(); + // `bool` must be checked before `i128` because a Python `bool` also + // extracts as an integer. if let Ok(s) = value.extract::<String>() { Ok(s) } else if let Ok(b) = value.extract::<bool>() { @@ -163,7 +169,7 @@ fn config_value_to_string(value: &Bound<PyAny>) -> PyResult<String> { } else if let Ok(delta) = value.cast::<PyDelta>() { // Use the base descriptors so the stable ABI reads the stored components // even if a timedelta subclass overrides the attributes. - let delta_type = value.py().get_type::<PyDelta>(); + let delta_type = py.get_type::<PyDelta>(); let component = |name: &str| -> PyResult<i128> { delta_type .getattr(name)? @@ -174,18 +180,22 @@ fn config_value_to_string(value: &Bound<PyAny>) -> PyResult<String> { + component("seconds")? * 1_000_000 + component("microseconds")?; Ok(format!("{micros}us")) - } else if value.cast::<PyDict>().is_ok() { + } else if is_python_mapping(value)? { Err(Unsupported::new_err( "a map-valued config field cannot be built via from_config; leave it unset", )) - } else if let Ok(items) = value.extract::<Vec<Bound<PyAny>>>() { - let parts = items - .iter() - .map(config_value_to_string) - .collect::<PyResult<Vec<_>>>()?; - Ok(parts.join(",")) - } else if let Ok(path) = value.extract::<PathBuf>() { - Ok(path.to_string_lossy().into_owned()) + } else if value.hasattr(pyo3::intern!(py, "__fspath__"))? { + let fspath = py + .import(pyo3::intern!(py, "os"))? + .getattr(pyo3::intern!(py, "fspath"))? + .call1((value,))?; + if let Ok(path) = fspath.extract::<String>() { + Ok(path) + } else { + Err(Unsupported::new_err( + "unsupported config value type; pass a str, bool, int, datetime.timedelta, os.PathLike, or list of those", + )) + } } else { Err(Unsupported::new_err( "unsupported config value type; pass a str, bool, int, datetime.timedelta, os.PathLike, or list of those", @@ -193,6 +203,31 @@ fn config_value_to_string(value: &Bound<PyAny>) -> PyResult<String> { } } +/// Convert a config value into the string form core's config deserializer +/// consumes. +/// +/// Accepts the native types the `opendal.config` TypedDicts declare: `str`, +/// `bool`, `int`, `datetime.timedelta`, `os.PathLike[str]`, and flat +/// `list`/`tuple` of those (`,`-joined, as core parses `Vec`). Nested +/// collections and mappings have no flat-map form and are rejected. +fn config_value_to_string(value: &Bound<PyAny>) -> PyResult<String> { + if let Ok(list) = value.cast::<PyList>() { + let parts = list + .iter() + .map(|item| config_scalar_to_string(&item)) + .collect::<PyResult<Vec<_>>>()?; + return Ok(parts.join(",")); + } + if let Ok(tuple) = value.cast::<PyTuple>() { + let parts = tuple + .iter() + .map(|item| config_scalar_to_string(&item)) + .collect::<PyResult<Vec<_>>>()?; + return Ok(parts.join(",")); + } + config_scalar_to_string(value) +} + /// Extract `(scheme, config_map)` from a typed service config dict. /// /// A config is a plain `dict` (an `opendal.config.ServiceConfig`, e.g. @@ -448,6 +483,9 @@ impl Operator { /// /// Raises /// ------ + /// TypeError + /// If `**kwargs` contains an unknown keyword argument, an option that + /// does not apply to `mode`, or a value with an incompatible type. /// ValueError /// If the mode is invalid or unsupported, including text (`"t"`) and /// update (`"+"`) modes, or if the mode conflicts with `append` or @@ -474,17 +512,11 @@ impl Operator { let this = self.core.clone(); let path = path.to_string_lossy().to_string(); - let reader_opts = kwargs - .map(|v| v.extract::<ReadOptions>()) - .transpose()? - .unwrap_or_default(); - - let writer_opts = kwargs - .map(|v| v.extract::<WriteOptions>()) - .transpose()? - .unwrap_or_default(); - if matches!(mode, OpenMode::Read) { + let reader_opts = kwargs + .map(|v| v.extract::<ReadOptions>()) + .transpose()? + .unwrap_or_default(); check_runtime_process()?; let range = reader_opts.make_range(); let r = py @@ -495,7 +527,10 @@ impl Operator { .map_err(format_pyerr)?; Ok(File::new_reader(r)) } else { - let mut writer_opts = writer_opts; + let mut writer_opts = kwargs + .map(|v| v.extract::<WriteOptions>()) + .transpose()? + .unwrap_or_default(); mode.apply_write_options(&mut writer_opts)?; // Keep small writes coalesced without the std::io adapter when // neither the caller nor the service supplies a nonzero chunk size. @@ -583,9 +618,9 @@ impl Operator { concurrent: Option<usize>, chunk: Option<usize>, gap: Option<usize>, - offset: Option<usize>, + offset: Option<u64>, prefetch: Option<usize>, - size: Option<usize>, + size: Option<u64>, if_match: Option<String>, if_none_match: Option<String>, if_modified_since: Option<jiff::Timestamp>, @@ -1319,6 +1354,9 @@ impl AsyncOperator { /// /// Raises /// ------ + /// TypeError + /// If `**kwargs` contains an unknown keyword argument, an option that + /// does not apply to `mode`, or a value with an incompatible type. /// ValueError /// If the mode is invalid or unsupported, including text (`"t"`) and /// update (`"+"`) modes, or if the mode conflicts with `append` or @@ -1345,18 +1383,13 @@ impl AsyncOperator { let this = self.core.clone(); let path = path.to_string_lossy().to_string(); - let reader_opts = kwargs - .map(|v| v.extract::<ReadOptions>()) - .transpose()? - .unwrap_or_default(); - - let writer_opts = kwargs - .map(|v| v.extract::<WriteOptions>()) - .transpose()? - .unwrap_or_default(); + if matches!(mode, OpenMode::Read) { + let reader_opts = kwargs + .map(|v| v.extract::<ReadOptions>()) + .transpose()? + .unwrap_or_default(); - future_into_py(py, async move { - if matches!(mode, OpenMode::Read) { + future_into_py(py, async move { let range = reader_opts.make_range(); let reader = this .reader_options(&path, reader_opts.into()) @@ -1368,9 +1401,15 @@ impl AsyncOperator { .await .map_err(format_pyerr)?; Ok(AsyncFile::new_reader(r)) - } else { - let mut writer_opts = writer_opts; - mode.apply_write_options(&mut writer_opts)?; + }) + } else { + let mut writer_opts = kwargs + .map(|v| v.extract::<WriteOptions>()) + .transpose()? + .unwrap_or_default(); + mode.apply_write_options(&mut writer_opts)?; + + future_into_py(py, async move { // Keep small writes coalesced when neither the caller nor the // service supplies a chunk size. The core treats zero as unset. if matches!(writer_opts.chunk, None | Some(0)) @@ -1383,8 +1422,8 @@ impl AsyncOperator { .await .map_err(format_pyerr)?; Ok(AsyncFile::new_writer(writer)) - } - }) + }) + } } /// Read all or a selected range of bytes from a file. @@ -1453,9 +1492,9 @@ impl AsyncOperator { concurrent: Option<usize>, chunk: Option<usize>, gap: Option<usize>, - offset: Option<usize>, + offset: Option<u64>, prefetch: Option<usize>, - size: Option<usize>, + size: Option<u64>, if_match: Option<String>, if_none_match: Option<String>, if_modified_since: Option<jiff::Timestamp>, diff --git a/bindings/python/src/options.rs b/bindings/python/src/options.rs index 15205c3147..27b7b547c0 100644 --- a/bindings/python/src/options.rs +++ b/bindings/python/src/options.rs @@ -43,11 +43,11 @@ pub struct ReadOptions { /// The gap between each chunk. pub gap: Option<usize>, /// The offset of the file. - pub offset: Option<usize>, + pub offset: Option<u64>, /// The number of completed chunks to buffer during concurrent reads. pub prefetch: Option<usize>, /// The size of the file. - pub size: Option<usize>, + pub size: Option<u64>, /// The ETag of the file. pub if_match: Option<String>, /// The ETag of the file. @@ -88,11 +88,57 @@ fn downcast_kwargs<'a, 'py>(obj: Borrowed<'a, 'py, PyAny>) -> PyResult<pyo3::Bou .map_err(|_| PyErr::new::<PyTypeError, _>("Invalid type to convert, expected dict")) } +const READ_OPTION_KEYS: &[&str] = &[ + "version", + "concurrent", + "chunk", + "gap", + "offset", + "prefetch", + "size", + "if_match", + "if_none_match", + "if_modified_since", + "if_unmodified_since", + "content_type", + "cache_control", + "content_disposition", +]; + +const WRITE_OPTION_KEYS: &[&str] = &[ + "append", + "chunk", + "concurrent", + "cache_control", + "content_type", + "content_disposition", + "content_encoding", + "if_match", + "if_none_match", + "if_not_exists", + "user_metadata", +]; + +fn reject_unknown_kwargs(dict: &pyo3::Bound<'_, PyDict>, allowed: &[&str]) -> PyResult<()> { + for key in dict.keys() { + let name = key + .extract::<String>() + .map_err(|_| PyTypeError::new_err("keyword argument names must be strings"))?; + if !allowed.contains(&name.as_str()) { + return Err(PyTypeError::new_err(format!( + "open() got an unexpected keyword argument '{name}'" + ))); + } + } + Ok(()) +} + impl<'a, 'py> FromPyObject<'a, 'py> for ReadOptions { type Error = PyErr; fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> { let dict = downcast_kwargs(obj)?; + reject_unknown_kwargs(&dict, READ_OPTION_KEYS)?; Ok(Self { version: extract_optional(&dict, "version")?, @@ -115,10 +161,9 @@ impl<'a, 'py> FromPyObject<'a, 'py> for ReadOptions { impl ReadOptions { pub fn make_range(&self) -> BytesRange { - let offset = self.offset.unwrap_or_default() as u64; - let size = self.size.map(|v| v as u64); + let offset = self.offset.unwrap_or_default(); - BytesRange::new(offset, size) + BytesRange::new(offset, self.size) } /// Validate the options before selecting the reader path for prefetching. @@ -170,6 +215,7 @@ impl<'a, 'py> FromPyObject<'a, 'py> for WriteOptions { fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> { let dict = downcast_kwargs(obj)?; + reject_unknown_kwargs(&dict, WRITE_OPTION_KEYS)?; Ok(Self { append: extract_optional(&dict, "append")?, diff --git a/bindings/python/tests/layers/test_timeout_layer.py b/bindings/python/tests/layers/test_timeout_layer.py new file mode 100644 index 0000000000..95ef37bb2c --- /dev/null +++ b/bindings/python/tests/layers/test_timeout_layer.py @@ -0,0 +1,83 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import sys + +import pytest + +import opendal +from opendal.exceptions import ConfigInvalid + + [email protected]( + "kwargs", + [ + {"timeout": 0.0}, + {"timeout": -1.0}, + {"timeout": float("nan")}, + {"timeout": float("inf")}, + {"timeout": float("-inf")}, + {"timeout": 1e30}, + {"timeout": 1e-10}, + {"timeout": 1e-300}, + {"timeout": sys.float_info.min}, + {"io_timeout": 0.0}, + {"io_timeout": -1.0}, + {"io_timeout": float("nan")}, + {"io_timeout": float("inf")}, + {"io_timeout": float("-inf")}, + {"io_timeout": 1e30}, + {"io_timeout": 1e-10}, + {"io_timeout": 1e-300}, + {"io_timeout": sys.float_info.min}, + ], +) +def test_timeout_layer_rejects_invalid_values(kwargs): + with pytest.raises(ConfigInvalid): + opendal.layers.TimeoutLayer(**kwargs) + + [email protected]( + "kwargs", + [ + {}, + {"timeout": 1e-9}, + {"io_timeout": 1e-9}, + {"timeout": 0.5, "io_timeout": 2.0}, + ], +) +def test_timeout_layer_accepts_valid_values(kwargs): + assert isinstance( + opendal.layers.TimeoutLayer(**kwargs), opendal.layers.TimeoutLayer + ) + + +def test_timeout_layer_allows_sync_operations(): + op = opendal.Operator("memory").layer( + opendal.layers.TimeoutLayer(timeout=10.0, io_timeout=5.0) + ) + op.write("test", b"hello") + assert op.read("test") == b"hello" + + [email protected] +async def test_timeout_layer_allows_async_operations(): + op = opendal.AsyncOperator("memory").layer( + opendal.layers.TimeoutLayer(timeout=10.0, io_timeout=5.0) + ) + await op.write("test", b"hello") + assert await op.read("test") == b"hello" diff --git a/bindings/python/tests/test_async_list.py b/bindings/python/tests/test_async_list.py index 5c1b66734d..52c3afe24a 100644 --- a/bindings/python/tests/test_async_list.py +++ b/bindings/python/tests/test_async_list.py @@ -86,6 +86,42 @@ async def test_async_list_cancelled_next_preserves_entry(): assert actual == expected [email protected] +async def test_async_list_reentrant_anext_does_not_raise_already_borrowed(): + op = opendal.AsyncOperator("memory") + expected = [f"items/{idx:03d}" for idx in range(5)] + await asyncio.gather(*(op.write(path, b"test") for path in expected)) + + lister = await op.list("items/", recursive=True) + # Prime the internal batch buffer so the next `anext` takes the fast path. + first = await anext(lister) + seen = [first.path] + + loop = asyncio.get_running_loop() + original_create_future = loop.create_future + nested_future: list[asyncio.Future[opendal.Entry]] = [] + triggered = False + + def reentrant_create_future() -> asyncio.Future[object]: + nonlocal triggered + if not triggered: + triggered = True + nested_future.append(asyncio.ensure_future(anext(lister))) + return original_create_future() + + loop.create_future = reentrant_create_future + try: + second = await anext(lister) + seen.append(second.path) + assert len(nested_future) == 1 + seen.append((await nested_future[0]).path) + finally: + loop.create_future = original_create_future + + seen.extend([entry.path async for entry in lister]) + assert sorted(seen) == expected + + @pytest.mark.asyncio @pytest.mark.need_capability("read", "write", "copy", "list", "list_with_start_after") async def test_async_list_with_start_after(service_name, operator, async_operator): diff --git a/bindings/python/tests/test_from_config.py b/bindings/python/tests/test_from_config.py index fedd2c8214..e9b0a497dd 100644 --- a/bindings/python/tests/test_from_config.py +++ b/bindings/python/tests/test_from_config.py @@ -16,8 +16,10 @@ # under the License. import pickle +from collections import UserDict from datetime import timedelta from pathlib import PurePosixPath +from types import MappingProxyType import pytest @@ -114,3 +116,68 @@ def test_from_config_timedelta_precision(operator_type, duration, expected): ) _, args = operator.__reduce__() assert args[1]["probe_duration"] == expected + + +def test_from_config_stringifies_flat_list_and_tuple(): + op = opendal.Operator.from_config( + { + "scheme": "memory", + "probe_list": ["a", "b"], + "probe_tuple": ( + "x", + 1, + True, + PurePosixPath("/p"), + timedelta(seconds=1), + ), + } # type: ignore[arg-type] + ) + _, args = op.__reduce__() + assert args[1]["probe_list"] == "a,b" + assert args[1]["probe_tuple"] == "x,1,true,/p,1000000us" + + +class BytesPathLike: + def __fspath__(self) -> bytes: + """Return a bytes path.""" + return b"/tmp/bytes-path" + + +def _make_cyclic_list() -> list[object]: + cyclic: list[object] = [] + cyclic.append(cyclic) + return cyclic + + [email protected]("operator_type", [opendal.Operator, opendal.AsyncOperator]) [email protected]( + "bad_value", + [ + b"/tmp/foo", + bytearray(b"/tmp/foo"), + memoryview(b"/tmp/foo"), + BytesPathLike(), + {"a": "1"}, + MappingProxyType({"a": "1", "b": "2"}), + UserDict({"a": "1"}), + {"a", "b"}, + frozenset({"a", "b"}), + [["nested"]], + (("nested",),), + _make_cyclic_list(), + [b"/tmp/foo"], + [MappingProxyType({"a": "1"})], + ], +) +def test_from_config_rejects_unsupported_values(operator_type, bad_value): + with pytest.raises(Unsupported): + operator_type.from_config( + {"scheme": "memory", "probe": bad_value} # type: ignore[arg-type] + ) + + +def test_from_config_rejects_bytes_root_for_fs(): + with pytest.raises(Unsupported): + opendal.Operator.from_config( + {"scheme": "fs", "root": b"/tmp/foo"} # type: ignore[arg-type] + ) diff --git a/bindings/python/tests/test_open_modes.py b/bindings/python/tests/test_open_modes.py index d303840c81..645843d260 100644 --- a/bindings/python/tests/test_open_modes.py +++ b/bindings/python/tests/test_open_modes.py @@ -314,3 +314,44 @@ async def test_async_open_none_options(local_operator): assert await file.read() == b"hello" with pytest.raises(TypeError): await op.open("data", "rb", offset="invalid") + + +INVALID_OPEN_KWARGS = [ + ("rb", {"if_matches": "etag"}, "if_matches"), + ("wb", {"if_not_exist": True}, "if_not_exist"), + ("rb", {"append": True}, "append"), + ("rb", {"append": None}, "append"), + ("rb", {"if_not_exists": True}, "if_not_exists"), + ("rb", {"content_encoding": "gzip"}, "content_encoding"), + ("rb", {"user_metadata": {"a": "b"}}, "user_metadata"), + ("wb", {"offset": 0}, "offset"), + ("wb", {"offset": None}, "offset"), + ("wb", {"size": 10}, "size"), + ("wb", {"gap": 4}, "gap"), + ("wb", {"prefetch": 1}, "prefetch"), + ("wb", {"version": "v1"}, "version"), + ("ab", {"offset": 0}, "offset"), + ("xb", {"size": 1}, "size"), +] + + [email protected](("mode", "kwargs", "key"), INVALID_OPEN_KWARGS) +def test_sync_open_rejects_unknown_and_cross_mode_kwargs( + local_operator, mode, kwargs, key +): + local_operator.write("data", b"original") + with pytest.raises(TypeError, match=key): + local_operator.open("data", mode, **kwargs) + assert local_operator.read("data") == b"original" + + [email protected] [email protected](("mode", "kwargs", "key"), INVALID_OPEN_KWARGS) +async def test_async_open_rejects_unknown_and_cross_mode_kwargs( + local_operator, mode, kwargs, key +): + op = local_operator.to_async_operator() + await op.write("data", b"original") + with pytest.raises(TypeError, match=key): + await op.open("data", mode, **kwargs) + assert await op.read("data") == b"original" diff --git a/bindings/python/tests/test_read.py b/bindings/python/tests/test_read.py index c7106802ad..b1f495c6de 100644 --- a/bindings/python/tests/test_read.py +++ b/bindings/python/tests/test_read.py @@ -15,9 +15,9 @@ # specific language governing permissions and limitations # under the License. +import asyncio import io import os -import sys from datetime import timedelta from pathlib import Path from random import choices, randint @@ -490,11 +490,23 @@ def test_sync_readinto_readonly_empty_buffer(operator): operator.delete(filename) [email protected](sys.maxsize < (1 << 63) - 1, reason="requires 64-bit usize") def test_sync_open_range_overflow_raises_range_not_satisfied(): op = opendal.Operator("memory") op.write("test", b"hello") + large_offset = (1 << 32) + 1024 + with op.open("test", "rb", offset=0, size=large_offset) as reader: + assert reader.read(5) == b"hello" + + with ( + op.open("test", "rb", offset=large_offset, size=1024) as reader, + pytest.raises(OSError, match="RangeNotSatisfied"), + ): + reader.read() + + with pytest.raises(RangeNotSatisfied): + op.read("test", offset=large_offset, size=1024) + with pytest.raises(RangeNotSatisfied): op.open("test", "rb", offset=(1 << 64) - 1, size=1) @@ -506,11 +518,21 @@ def test_sync_open_range_overflow_raises_range_not_satisfied(): @pytest.mark.asyncio [email protected](sys.maxsize < (1 << 63) - 1, reason="requires 64-bit usize") async def test_async_open_range_overflow_raises_range_not_satisfied(): aop = opendal.AsyncOperator("memory") await aop.write("test", b"hello") + large_offset = (1 << 32) + 1024 + async with await aop.open("test", "rb", offset=0, size=large_offset) as reader: + assert await reader.read(5) == b"hello" + + async with await aop.open("test", "rb", offset=large_offset, size=1024) as reader: + with pytest.raises(OSError, match="RangeNotSatisfied"): + await reader.read() + + with pytest.raises(RangeNotSatisfied): + await aop.read("test", offset=large_offset, size=1024) + with pytest.raises(RangeNotSatisfied): await aop.open("test", "rb", offset=(1 << 64) - 1, size=1) @@ -519,3 +541,47 @@ async def test_async_open_range_overflow_raises_range_not_satisfied(): with pytest.raises(RangeNotSatisfied): await aop.read("test", offset=(1 << 64) - 1, size=1) + + [email protected] +async def test_async_file_reentrant_calls_do_not_raise_already_borrowed(): + aop = opendal.AsyncOperator("memory") + await aop.write("test", b"abcdef") + + async with await aop.open("test", "rb") as reader: + reentrant_tasks: list[asyncio.Future[int]] = [] + + class ReentrantInt: + def __index__(self) -> int: + reentrant_tasks.append(asyncio.ensure_future(reader.tell())) + return 3 + + assert await reader.seek(ReentrantInt()) == 3 + assert await reentrant_tasks[0] in (0, 3) + assert await reader.read() == b"def" + + loop = asyncio.get_running_loop() + original_create_future = loop.create_future + writer = await aop.open("reentrant_write", "wb") + nested_calls: list[asyncio.Future[object]] = [] + entered = False + + def reentrant_create_future() -> asyncio.Future[object]: + nonlocal entered + if not entered: + entered = True + nested_calls.append(asyncio.ensure_future(writer.tell())) + nested_calls.append(asyncio.ensure_future(writer.writable())) + return original_create_future() + + loop.create_future = reentrant_create_future + try: + assert await writer.write(b"hello") == 5 + await asyncio.gather(*nested_calls) + entered = False + await writer.close() + finally: + loop.create_future = original_create_future + await asyncio.gather(*nested_calls, return_exceptions=True) + + assert await aop.read("reentrant_write") == b"hello" diff --git a/dev/src/generate/options.rs b/dev/src/generate/options.rs index c4cc40fb44..225ec32fc1 100644 --- a/dev/src/generate/options.rs +++ b/dev/src/generate/options.rs @@ -28,7 +28,7 @@ use syn::{ pub enum OptionType { /// `Option<String>` Str, - /// `Option<usize>` + /// `Option<usize>` or `Option<u64>` Int, /// `Option<bool>` Bool, @@ -149,7 +149,7 @@ fn parse_type(ty: &Type) -> Result<OptionType> { Ok(match inner_segment.ident.to_string().as_str() { "String" => OptionType::Str, - "usize" => OptionType::Int, + "usize" | "u64" => OptionType::Int, "bool" => OptionType::Bool, // jiff::Timestamp "Timestamp" => OptionType::DateTime,
