diff --git a/README.md b/README.md index b76edd1..e9b97fc 100644 --- a/README.md +++ b/README.md @@ -66,13 +66,13 @@ async with await client.collections["books"].documents.export_stream() as stream A stream can be read once, either as lines or as bytes. Keep these in mind: -- **Always close the stream**, ideally with a context manager. With `max_concurrent_requests` set, a stream that is abandoned before its end permanently uses up one of the open export places below. +- **Always close the stream**, ideally with a context manager. With `max_concurrent_requests` set, a stream that is abandoned before its end permanently uses up one of the open export places below. With the sync client, closing a stream from another thread does not interrupt a read in progress there: that read raises once `stream_read_timeout_seconds` runs out. - **A failed export has to be restarted.** Nodes are only retried until the response headers arrive. After that, errors such as `httpx.RemoteProtocolError` or `httpx.ReadTimeout` are raised as they are, and exports cannot resume from where they stopped. - **Keep reading.** If your code stops reading for about 60 seconds, the server drops the connection. `stream_read_timeout_seconds` (default 60) separately limits how long the client waits for the server's next chunk. - **Lines are raw.** They are not parsed, and the server could write an error message into the body after a successful status, so a line is not guaranteed to be a document. - **Exports are uncompressed by default.** The server compresses on the thread that handles all other requests, which delays them, especially with a large `batch_size`. Pass `compress=True` if bandwidth matters more. An `Accept-Encoding` in `additional_headers` is always respected. -With `max_concurrent_requests`, an export only takes a slot while it opens, so requests made while reading an export do not wait for it. To keep connections free for those requests, at most `max_connections - max_concurrent_requests` exports can be open at once. If that is not positive, one export is still allowed, and it can leave a request short of a connection, so keep `max_concurrent_requests` below `max_connections`. Further exports wait for a place, so opening an export inside another one can wait forever when no place is free. The limit does not apply to an `http_client` you pass in, because its pool size is unknown. +With `max_concurrent_requests`, an export only takes a slot while it opens, so requests made while reading an export do not wait for it. To keep connections free for those requests, at most `max_connections - max_concurrent_requests` exports can be open at once. Further exports wait for one to close, with no timeout, so an export opened inside another needs a second free place or it waits forever. If `max_concurrent_requests` is not below `max_connections`, no connection can be kept free, so exports are not limited. The limit does not apply to an `http_client` you pass in, because its pool size is unknown. If your application cancels many requests, prefer [httpx2](#using-httpx2), which fixes a connection pool leak that cancellation can trigger in httpx. diff --git a/src/typesense/async_/api_call.py b/src/typesense/async_/api_call.py index 43c9e94..6feb426 100644 --- a/src/typesense/async_/api_call.py +++ b/src/typesense/async_/api_call.py @@ -211,10 +211,9 @@ def _max_open_exports(self, config: Configuration) -> typing.Optional[int]: An open export keeps a connection but not a concurrency slot, so exports get the connections the slots cannot use. There is no limit without - ``max_concurrent_requests``, or when the pool is unlimited or belongs to a - client passed in by the caller. When the slots alone can fill the pool, one - export at a time is still allowed, which can leave a request short of a - connection. + ``max_concurrent_requests``, when the pool is unlimited or belongs to a + client passed in by the caller, or when the slots alone can fill the pool, + which leaves no connection to keep free. """ max_concurrent_requests = config.max_concurrent_requests max_connections = config.max_connections @@ -222,7 +221,8 @@ def _max_open_exports(self, config: Configuration) -> typing.Optional[int]: return None if not self._owns_client: return None - return max(max_connections - max_concurrent_requests, 1) + spare_connections = max_connections - max_concurrent_requests + return spare_connections if spare_connections > 0 else None async def __aenter__(self) -> "AsyncApiCall": """Async context manager entry.""" @@ -631,9 +631,11 @@ async def export_stream( """ Open a document export as a stream. - Failing nodes are retried like any other request until the response - headers arrive. Errors after that are raised while reading the stream and - are not retried, since part of the export has already been read. + The export takes its place among the open exports before a node is chosen, + and keeps it until the stream is closed or its body ends or fails. Failing + nodes are retried like any other request until the response headers + arrive. Errors after that are raised while reading the stream and are not + retried, since part of the export has already been read. Args: endpoint (str): The export endpoint to call. @@ -643,16 +645,31 @@ async def export_stream( Returns: AsyncExportStream: The open stream. """ - return await self._execute_stream_request( - endpoint, - lambda node, url, request_kwargs: self._open_export_stream( - node, - url, - compress, - **request_kwargs, - ), - params=params, - ) + # Closes the response, then gives back the export's place. + export = AsyncExitStack() + await self._export_limit.acquire() + export.callback(self._export_limit.release) + try: + response = await self._execute_stream_request( + endpoint, + lambda node, url, request_kwargs: self._open_export_stream( + export, + node, + url, + compress, + **request_kwargs, + ), + params=params, + ) + except BaseException: + await export.aclose() + raise + + # A single entry, so that a second close cannot give back the place while + # the first is still closing the response. + exit_stack = AsyncExitStack() + await exit_stack.enter_async_context(export) + return AsyncExportStream(response, exit_stack) async def _execute_stream_request( self, @@ -723,17 +740,18 @@ async def _open_search_stream( async def _open_export_stream( self, + export: AsyncExitStack, node: Node, url: str, compress: bool, **kwargs: typing.Unpack[SessionFunctionKwargs[TParams, TBody]], - ) -> AsyncExportStream: + ) -> ResponseType: """ - Send an export request to `node` and return the stream once headers arrive. + Send an export request to `node` and return the response once headers arrive. - The concurrency slot is held only while opening, so that a request made - while reading the export does not have to wait for the export to finish. - The stream keeps its place among the open exports until it is closed. + The response is added to ``export``, which holds the export's place. The + concurrency slot is held only while opening, so that a request made while + reading the export does not have to wait for the export to finish. Unless ``compress`` is set the export is requested uncompressed, because the server compresses on the thread that handles every other request. An @@ -745,24 +763,19 @@ async def _open_export_stream( headers["Accept-Encoding"] = "identity" response_context = self._stream_context("GET", url, request_kwargs) - # Closes the response, then gives back the export's place. - export = AsyncExitStack() - await self._export_limit.acquire() - export.callback(self._export_limit.release) + # Kept apart from ``export`` until the request succeeds, so that a failed + # attempt closes its response without giving back the place. + response_stack = AsyncExitStack() try: async with self._concurrency_limit: - response = await self._enter_stream(export, response_context) + response = await self._enter_stream(response_stack, response_context) except BaseException: - await export.aclose() + await response_stack.aclose() raise - - # A single entry, so that a second close cannot give back the place while - # the first is still closing the response. - exit_stack = AsyncExitStack() - await exit_stack.enter_async_context(export) + await export.enter_async_context(response_stack) self.node_manager.set_node_health(node, is_healthy=True) - return AsyncExportStream(response, exit_stack) + return response def _stream_context( self, diff --git a/src/typesense/async_/stream.py b/src/typesense/async_/stream.py index 7c6f2f5..30e0a33 100644 --- a/src/typesense/async_/stream.py +++ b/src/typesense/async_/stream.py @@ -267,7 +267,7 @@ def __init__( response (httpx.Response | httpx2.Response): A successful response opened with ``stream=True``. exit_stack (AsyncExitStack): Closes the response and gives up the - export's place when the stream is closed. + export's place when the stream is closed or its body ends or fails. """ self.response = response self._exit_stack = exit_stack diff --git a/src/typesense/configuration.py b/src/typesense/configuration.py index 8735877..56c8f5c 100644 --- a/src/typesense/configuration.py +++ b/src/typesense/configuration.py @@ -92,11 +92,11 @@ class ConfigDict(typing.TypedDict): ``connection_timeout_seconds`` makes the httpcore connection leak (encode/httpcore#1093) more likely under load. - max_connections (int): The maximum number of connections in the pool. With - ``max_concurrent_requests``, it also limits open streaming exports to - ``max_connections - max_concurrent_requests``, or one if that is not - positive, when an open export can leave a request short of a connection. - Further exports wait for one to close. Defaults to 100. + max_connections (int | None): The maximum number of connections in the + pool, or ``None`` for no limit. With a lower ``max_concurrent_requests``, + it also limits open streaming exports to ``max_connections - + max_concurrent_requests``, so that exports cannot take the connections + requests need. Further exports wait for one to close. Defaults to 100. max_keepalive_connections (int): The maximum number of idle connections kept alive in the pool. Defaults to 20. @@ -133,7 +133,7 @@ class ConfigDict(typing.TypedDict): connection_timeout_seconds: typing.NotRequired[float] suppress_deprecation_warnings: typing.NotRequired[bool] pool_timeout_seconds: typing.NotRequired[float] - max_connections: typing.NotRequired[int] + max_connections: typing.NotRequired[typing.Optional[int]] max_keepalive_connections: typing.NotRequired[int] max_concurrent_requests: typing.NotRequired[int] stream_read_timeout_seconds: typing.NotRequired[float] @@ -230,7 +230,7 @@ class Configuration: healthcheck_interval_seconds (int): The interval in seconds between health checks. verify (bool | str | ssl.SSLContext): Whether to verify the SSL certificate. pool_timeout_seconds (float): How long to wait for a free pooled connection. - max_connections (int): The maximum number of connections in the pool. + max_connections (int | None): The maximum number of pooled connections. max_keepalive_connections (int): The maximum number of idle pooled connections. max_concurrent_requests (int | None): The maximum number of requests in flight. stream_read_timeout_seconds (float): How long a stream waits for its next chunk. diff --git a/src/typesense/sync/api_call.py b/src/typesense/sync/api_call.py index 80fb468..aebc9cc 100644 --- a/src/typesense/sync/api_call.py +++ b/src/typesense/sync/api_call.py @@ -211,10 +211,9 @@ def _max_open_exports(self, config: Configuration) -> typing.Optional[int]: An open export keeps a connection but not a concurrency slot, so exports get the connections the slots cannot use. There is no limit without - ``max_concurrent_requests``, or when the pool is unlimited or belongs to a - client passed in by the caller. When the slots alone can fill the pool, one - export at a time is still allowed, which can leave a request short of a - connection. + ``max_concurrent_requests``, when the pool is unlimited or belongs to a + client passed in by the caller, or when the slots alone can fill the pool, + which leaves no connection to keep free. """ max_concurrent_requests = config.max_concurrent_requests max_connections = config.max_connections @@ -222,7 +221,8 @@ def _max_open_exports(self, config: Configuration) -> typing.Optional[int]: return None if not self._owns_client: return None - return max(max_connections - max_concurrent_requests, 1) + spare_connections = max_connections - max_concurrent_requests + return spare_connections if spare_connections > 0 else None def __enter__(self) -> "ApiCall": """Async context manager entry.""" @@ -631,9 +631,11 @@ def export_stream( """ Open a document export as a stream. - Failing nodes are retried like any other request until the response - headers arrive. Errors after that are raised while reading the stream and - are not retried, since part of the export has already been read. + The export takes its place among the open exports before a node is chosen, + and keeps it until the stream is closed or its body ends or fails. Failing + nodes are retried like any other request until the response headers + arrive. Errors after that are raised while reading the stream and are not + retried, since part of the export has already been read. Args: endpoint (str): The export endpoint to call. @@ -643,16 +645,31 @@ def export_stream( Returns: ExportStream: The open stream. """ - return self._execute_stream_request( - endpoint, - lambda node, url, request_kwargs: self._open_export_stream( - node, - url, - compress, - **request_kwargs, - ), - params=params, - ) + # Closes the response, then gives back the export's place. + export = ExitStack() + self._export_limit.acquire() + export.callback(self._export_limit.release) + try: + response = self._execute_stream_request( + endpoint, + lambda node, url, request_kwargs: self._open_export_stream( + export, + node, + url, + compress, + **request_kwargs, + ), + params=params, + ) + except BaseException: + export.close() + raise + + # A single entry, so that a second close cannot give back the place while + # the first is still closing the response. + exit_stack = ExitStack() + exit_stack.enter_context(export) + return ExportStream(response, exit_stack) def _execute_stream_request( self, @@ -723,17 +740,18 @@ def _open_search_stream( def _open_export_stream( self, + export: ExitStack, node: Node, url: str, compress: bool, **kwargs: typing.Unpack[SessionFunctionKwargs[TParams, TBody]], - ) -> ExportStream: + ) -> ResponseType: """ - Send an export request to `node` and return the stream once headers arrive. + Send an export request to `node` and return the response once headers arrive. - The concurrency slot is held only while opening, so that a request made - while reading the export does not have to wait for the export to finish. - The stream keeps its place among the open exports until it is closed. + The response is added to ``export``, which holds the export's place. The + concurrency slot is held only while opening, so that a request made while + reading the export does not have to wait for the export to finish. Unless ``compress`` is set the export is requested uncompressed, because the server compresses on the thread that handles every other request. An @@ -745,24 +763,19 @@ def _open_export_stream( headers["Accept-Encoding"] = "identity" response_context = self._stream_context("GET", url, request_kwargs) - # Closes the response, then gives back the export's place. - export = ExitStack() - self._export_limit.acquire() - export.callback(self._export_limit.release) + # Kept apart from ``export`` until the request succeeds, so that a failed + # attempt closes its response without giving back the place. + response_stack = ExitStack() try: with self._concurrency_limit: - response = self._enter_stream(export, response_context) + response = self._enter_stream(response_stack, response_context) except BaseException: - export.close() + response_stack.close() raise - - # A single entry, so that a second close cannot give back the place while - # the first is still closing the response. - exit_stack = ExitStack() - exit_stack.enter_context(export) + export.enter_context(response_stack) self.node_manager.set_node_health(node, is_healthy=True) - return ExportStream(response, exit_stack) + return response def _stream_context( self, diff --git a/src/typesense/sync/stream.py b/src/typesense/sync/stream.py index bdf5da4..94fd92b 100644 --- a/src/typesense/sync/stream.py +++ b/src/typesense/sync/stream.py @@ -267,7 +267,7 @@ def __init__( response (httpx.Response | httpx2.Response): A successful response opened with ``stream=True``. exit_stack (ExitStack): Closes the response and gives up the - export's place when the stream is closed. + export's place when the stream is closed or its body ends or fails. """ self.response = response self._exit_stack = exit_stack diff --git a/tests/export_stream_async_test.py b/tests/export_stream_async_test.py index 361d4e8..b95ddd6 100644 --- a/tests/export_stream_async_test.py +++ b/tests/export_stream_async_test.py @@ -742,7 +742,7 @@ async def handler(request: RequestType) -> ResponseType: @pytest.mark.parametrize( ("max_connections", "max_concurrent_requests", "places"), - [(3, 2, 1), (5, 2, 3), (2, 2, 1), (1, 5, 1)], + [(3, 2, 1), (5, 2, 3)], ) async def test_open_exports_are_limited( fake_config: Configuration, @@ -750,7 +750,7 @@ async def test_open_exports_are_limited( max_concurrent_requests: int, places: int, ) -> None: - """Test the limit, including when the slots leave no room in the pool.""" + """Test that open exports are limited to the connections the slots leave.""" documents = limited_documents(fake_config, max_connections, max_concurrent_requests) with respx.mock: @@ -836,6 +836,25 @@ async def test_exports_are_not_limited_without_a_concurrency_limit( await stream.aclose() +@pytest.mark.parametrize( + ("max_connections", "max_concurrent_requests"), + [(2, 2), (1, 5)], +) +async def test_exports_are_not_limited_when_the_slots_fill_the_pool( + fake_config: Configuration, + max_connections: int, + max_concurrent_requests: int, +) -> None: + """Test that a limit that could keep no connection free is not applied.""" + documents = limited_documents(fake_config, max_connections, max_concurrent_requests) + + with respx.mock: + mock_export() + streams = [await open_export(documents) for _ in range(3)] + for stream in streams: + await stream.aclose() + + async def test_exports_are_not_limited_with_an_unlimited_pool( fake_config: Configuration, ) -> None: @@ -920,6 +939,44 @@ async def test_a_failed_open_gives_back_its_slot_and_place( await (await open_export(documents)).aclose() +async def test_a_failed_attempt_closes_its_response( + fake_config: Configuration, +) -> None: + """Test that a response which broke off while opening is not kept by the export.""" + bodies: typing.List["BrokenBody"] = [] + + class BrokenBody(httpx.AsyncByteStream): + """An error body that breaks off while it is being read.""" + + def __init__(self) -> None: + """Start open.""" + self.closed = False + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + """Send part of the body, then fail.""" + yield b"Do" + raise httpx.ReadError("connection reset") + + async def aclose(self) -> None: + """Remember that the response was closed.""" + self.closed = True + + def respond(request: httpx.Request) -> httpx.Response: + if bodies: + return httpx.Response(200, content=BODY) + bodies.append(BrokenBody()) + return httpx.Response(503, stream=bodies[0]) + + documents = limited_documents(fake_config, 2, 1) + + with respx.mock: + respx.get(path=EXPORT_PATH).mock(side_effect=respond) + stream = await open_export(documents) + + assert bodies[0].closed + await stream.aclose() + + async def test_cancelling_while_waiting_for_a_place( fake_config: Configuration, ) -> None: @@ -964,6 +1021,57 @@ async def test_an_export_waiting_for_a_place_holds_no_slot( await (await asyncio.wait_for(waiting, WAIT_SECONDS)).aclose() +async def test_an_export_picks_its_node_after_waiting_for_a_place( + fake_config: Configuration, +) -> None: + """Test that a node marked unhealthy during the wait is not used.""" + hosts: typing.List[str] = [] + + def respond(request: httpx.Request) -> httpx.Response: + hosts.append(request.url.host) + return httpx.Response(200, content=BODY) + + documents = limited_documents(fake_config, 2, 1) + assert fake_config.nearest_node is not None + + with respx.mock: + respx.get(path=EXPORT_PATH).mock(side_effect=respond) + first = await open_export(documents) + waiting = asyncio.ensure_future(documents.export_stream()) + await assert_waiting(waiting) + + documents.api_call.node_manager.set_node_health( + fake_config.nearest_node, + is_healthy=False, + ) + await first.aclose() + await (await asyncio.wait_for(waiting, WAIT_SECONDS)).aclose() + + assert hosts == ["nearest", "node0"] + + +async def test_failing_over_keeps_the_place( + fake_config: Configuration, +) -> None: + """Test that an export retrying another node is not overtaken by a later one.""" + documents = limited_documents(fake_config, 2, 1) + later: typing.List["asyncio.Future[AsyncExportStream]"] = [] + + def respond(request: httpx.Request) -> httpx.Response: + if not later: + later.append(asyncio.ensure_future(documents.export_stream())) + return httpx.Response(503, text="Down") + return httpx.Response(200, content=BODY) + + with respx.mock: + respx.get(path=EXPORT_PATH).mock(side_effect=respond) + stream = await open_export(documents) + await assert_waiting(later[0]) + + await stream.aclose() + await (await asyncio.wait_for(later[0], WAIT_SECONDS)).aclose() + + async def test_cancelling_while_waiting_for_a_slot_gives_back_the_place( fake_config: Configuration, ) -> None: diff --git a/tests/export_stream_test.py b/tests/export_stream_test.py index 0059323..9404f8f 100644 --- a/tests/export_stream_test.py +++ b/tests/export_stream_test.py @@ -692,7 +692,7 @@ def handler(request: RequestType) -> ResponseType: @pytest.mark.parametrize( ("max_connections", "max_concurrent_requests", "places"), - [(3, 2, 1), (5, 2, 3), (2, 2, 1), (1, 5, 1)], + [(3, 2, 1), (5, 2, 3)], ) def test_open_exports_are_limited( fake_config: Configuration, @@ -700,7 +700,7 @@ def test_open_exports_are_limited( max_concurrent_requests: int, places: int, ) -> None: - """Test the limit, including when the slots leave no room in the pool.""" + """Test that open exports are limited to the connections the slots leave.""" documents = limited_documents(fake_config, max_connections, max_concurrent_requests) with respx.mock: @@ -735,6 +735,55 @@ def test_an_export_waiting_for_a_place_holds_no_slot( waiting.result().close() +def test_an_export_picks_its_node_after_waiting_for_a_place( + fake_config: Configuration, +) -> None: + """Test that a node marked unhealthy during the wait is not used.""" + hosts: typing.List[str] = [] + + def respond(request: httpx.Request) -> httpx.Response: + hosts.append(request.url.host) + return httpx.Response(200, content=BODY) + + documents = limited_documents(fake_config, 2, 1) + assert fake_config.nearest_node is not None + + with respx.mock: + respx.get(path=EXPORT_PATH).mock(side_effect=respond) + first = open_export(documents) + waiting = Background(documents.export_stream) + waiting.assert_waiting() + + documents.api_call.node_manager.set_node_health( + fake_config.nearest_node, + is_healthy=False, + ) + first.close() + waiting.result().close() + + assert hosts == ["nearest", "node0"] + + +def test_failing_over_keeps_the_place(fake_config: Configuration) -> None: + """Test that an export retrying another node is not overtaken by a later one.""" + documents = limited_documents(fake_config, 2, 1) + later: typing.List[Background[ExportStream]] = [] + + def respond(request: httpx.Request) -> httpx.Response: + if not later: + later.append(Background(documents.export_stream)) + return httpx.Response(503, text="Down") + return httpx.Response(200, content=BODY) + + with respx.mock: + respx.get(path=EXPORT_PATH).mock(side_effect=respond) + stream = open_export(documents) + later[0].assert_waiting() + + stream.close() + later[0].result().close() + + def test_closing_twice_gives_back_one_place(fake_config: Configuration) -> None: """Test that a second close cannot raise the limit.""" documents = limited_documents(fake_config, 3, 2) @@ -803,6 +852,25 @@ def test_exports_are_not_limited_without_a_concurrency_limit( stream.close() +@pytest.mark.parametrize( + ("max_connections", "max_concurrent_requests"), + [(2, 2), (1, 5)], +) +def test_exports_are_not_limited_when_the_slots_fill_the_pool( + fake_config: Configuration, + max_connections: int, + max_concurrent_requests: int, +) -> None: + """Test that a limit that could keep no connection free is not applied.""" + documents = limited_documents(fake_config, max_connections, max_concurrent_requests) + + with respx.mock: + mock_export() + streams = [open_export(documents) for _ in range(3)] + for stream in streams: + stream.close() + + def test_exports_are_not_limited_with_an_unlimited_pool( fake_config: Configuration, ) -> None: @@ -884,6 +952,42 @@ def test_a_failed_open_gives_back_its_slot_and_place( open_export(documents).close() +def test_a_failed_attempt_closes_its_response(fake_config: Configuration) -> None: + """Test that a response which broke off while opening is not kept by the export.""" + bodies: typing.List["BrokenBody"] = [] + + class BrokenBody(httpx.SyncByteStream): + """An error body that breaks off while it is being read.""" + + def __init__(self) -> None: + """Start open.""" + self.closed = False + + def __iter__(self) -> typing.Iterator[bytes]: + """Send part of the body, then fail.""" + yield b"Do" + raise httpx.ReadError("connection reset") + + def close(self) -> None: + """Remember that the response was closed.""" + self.closed = True + + def respond(request: httpx.Request) -> httpx.Response: + if bodies: + return httpx.Response(200, content=BODY) + bodies.append(BrokenBody()) + return httpx.Response(503, stream=bodies[0]) + + documents = limited_documents(fake_config, 2, 1) + + with respx.mock: + respx.get(path=EXPORT_PATH).mock(side_effect=respond) + stream = open_export(documents) + + assert bodies[0].closed + stream.close() + + def test_export_stream_through_the_default_client( fake_config: Configuration, ) -> None: