Skip to content

Commit 36f845e

Browse files
authored
Merge pull request #159 from tharropoulos/fix/export-stream-places
fix(documents): choose an export's node after it gets a place
2 parents 9ee6b37 + 038ef8d commit 36f845e

8 files changed

Lines changed: 323 additions & 85 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,13 +66,13 @@ async with await client.collections["books"].documents.export_stream() as stream
6666

6767
A stream can be read once, either as lines or as bytes. Keep these in mind:
6868

69-
- **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.
69+
- **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.
7070
- **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.
7171
- **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.
7272
- **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.
7373
- **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.
7474

75-
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.
75+
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.
7676

7777
If your application cancels many requests, prefer [httpx2](#using-httpx2), which fixes a connection pool leak that cancellation can trigger in httpx.
7878

‎src/typesense/async_/api_call.py‎

Lines changed: 48 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -211,18 +211,18 @@ def _max_open_exports(self, config: Configuration) -> typing.Optional[int]:
211211
212212
An open export keeps a connection but not a concurrency slot, so exports
213213
get the connections the slots cannot use. There is no limit without
214-
``max_concurrent_requests``, or when the pool is unlimited or belongs to a
215-
client passed in by the caller. When the slots alone can fill the pool, one
216-
export at a time is still allowed, which can leave a request short of a
217-
connection.
214+
``max_concurrent_requests``, when the pool is unlimited or belongs to a
215+
client passed in by the caller, or when the slots alone can fill the pool,
216+
which leaves no connection to keep free.
218217
"""
219218
max_concurrent_requests = config.max_concurrent_requests
220219
max_connections = config.max_connections
221220
if max_concurrent_requests is None or max_connections is None:
222221
return None
223222
if not self._owns_client:
224223
return None
225-
return max(max_connections - max_concurrent_requests, 1)
224+
spare_connections = max_connections - max_concurrent_requests
225+
return spare_connections if spare_connections > 0 else None
226226

227227
async def __aenter__(self) -> "AsyncApiCall":
228228
"""Async context manager entry."""
@@ -631,9 +631,11 @@ async def export_stream(
631631
"""
632632
Open a document export as a stream.
633633
634-
Failing nodes are retried like any other request until the response
635-
headers arrive. Errors after that are raised while reading the stream and
636-
are not retried, since part of the export has already been read.
634+
The export takes its place among the open exports before a node is chosen,
635+
and keeps it until the stream is closed or its body ends or fails. Failing
636+
nodes are retried like any other request until the response headers
637+
arrive. Errors after that are raised while reading the stream and are not
638+
retried, since part of the export has already been read.
637639
638640
Args:
639641
endpoint (str): The export endpoint to call.
@@ -643,16 +645,31 @@ async def export_stream(
643645
Returns:
644646
AsyncExportStream: The open stream.
645647
"""
646-
return await self._execute_stream_request(
647-
endpoint,
648-
lambda node, url, request_kwargs: self._open_export_stream(
649-
node,
650-
url,
651-
compress,
652-
**request_kwargs,
653-
),
654-
params=params,
655-
)
648+
# Closes the response, then gives back the export's place.
649+
export = AsyncExitStack()
650+
await self._export_limit.acquire()
651+
export.callback(self._export_limit.release)
652+
try:
653+
response = await self._execute_stream_request(
654+
endpoint,
655+
lambda node, url, request_kwargs: self._open_export_stream(
656+
export,
657+
node,
658+
url,
659+
compress,
660+
**request_kwargs,
661+
),
662+
params=params,
663+
)
664+
except BaseException:
665+
await export.aclose()
666+
raise
667+
668+
# A single entry, so that a second close cannot give back the place while
669+
# the first is still closing the response.
670+
exit_stack = AsyncExitStack()
671+
await exit_stack.enter_async_context(export)
672+
return AsyncExportStream(response, exit_stack)
656673

657674
async def _execute_stream_request(
658675
self,
@@ -723,17 +740,18 @@ async def _open_search_stream(
723740

724741
async def _open_export_stream(
725742
self,
743+
export: AsyncExitStack,
726744
node: Node,
727745
url: str,
728746
compress: bool,
729747
**kwargs: typing.Unpack[SessionFunctionKwargs[TParams, TBody]],
730-
) -> AsyncExportStream:
748+
) -> ResponseType:
731749
"""
732-
Send an export request to `node` and return the stream once headers arrive.
750+
Send an export request to `node` and return the response once headers arrive.
733751
734-
The concurrency slot is held only while opening, so that a request made
735-
while reading the export does not have to wait for the export to finish.
736-
The stream keeps its place among the open exports until it is closed.
752+
The response is added to ``export``, which holds the export's place. The
753+
concurrency slot is held only while opening, so that a request made while
754+
reading the export does not have to wait for the export to finish.
737755
738756
Unless ``compress`` is set the export is requested uncompressed, because
739757
the server compresses on the thread that handles every other request. An
@@ -745,24 +763,19 @@ async def _open_export_stream(
745763
headers["Accept-Encoding"] = "identity"
746764
response_context = self._stream_context("GET", url, request_kwargs)
747765

748-
# Closes the response, then gives back the export's place.
749-
export = AsyncExitStack()
750-
await self._export_limit.acquire()
751-
export.callback(self._export_limit.release)
766+
# Kept apart from ``export`` until the request succeeds, so that a failed
767+
# attempt closes its response without giving back the place.
768+
response_stack = AsyncExitStack()
752769
try:
753770
async with self._concurrency_limit:
754-
response = await self._enter_stream(export, response_context)
771+
response = await self._enter_stream(response_stack, response_context)
755772
except BaseException:
756-
await export.aclose()
773+
await response_stack.aclose()
757774
raise
758-
759-
# A single entry, so that a second close cannot give back the place while
760-
# the first is still closing the response.
761-
exit_stack = AsyncExitStack()
762-
await exit_stack.enter_async_context(export)
775+
await export.enter_async_context(response_stack)
763776

764777
self.node_manager.set_node_health(node, is_healthy=True)
765-
return AsyncExportStream(response, exit_stack)
778+
return response
766779

767780
def _stream_context(
768781
self,

‎src/typesense/async_/stream.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def __init__(
267267
response (httpx.Response | httpx2.Response): A successful response
268268
opened with ``stream=True``.
269269
exit_stack (AsyncExitStack): Closes the response and gives up the
270-
export's place when the stream is closed.
270+
export's place when the stream is closed or its body ends or fails.
271271
"""
272272
self.response = response
273273
self._exit_stack = exit_stack

‎src/typesense/configuration.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -92,11 +92,11 @@ class ConfigDict(typing.TypedDict):
9292
``connection_timeout_seconds`` makes the httpcore connection leak
9393
(encode/httpcore#1093) more likely under load.
9494
95-
max_connections (int): The maximum number of connections in the pool. With
96-
``max_concurrent_requests``, it also limits open streaming exports to
97-
``max_connections - max_concurrent_requests``, or one if that is not
98-
positive, when an open export can leave a request short of a connection.
99-
Further exports wait for one to close. Defaults to 100.
95+
max_connections (int | None): The maximum number of connections in the
96+
pool, or ``None`` for no limit. With a lower ``max_concurrent_requests``,
97+
it also limits open streaming exports to ``max_connections -
98+
max_concurrent_requests``, so that exports cannot take the connections
99+
requests need. Further exports wait for one to close. Defaults to 100.
100100
101101
max_keepalive_connections (int): The maximum number of idle connections
102102
kept alive in the pool. Defaults to 20.
@@ -133,7 +133,7 @@ class ConfigDict(typing.TypedDict):
133133
connection_timeout_seconds: typing.NotRequired[float]
134134
suppress_deprecation_warnings: typing.NotRequired[bool]
135135
pool_timeout_seconds: typing.NotRequired[float]
136-
max_connections: typing.NotRequired[int]
136+
max_connections: typing.NotRequired[typing.Optional[int]]
137137
max_keepalive_connections: typing.NotRequired[int]
138138
max_concurrent_requests: typing.NotRequired[int]
139139
stream_read_timeout_seconds: typing.NotRequired[float]
@@ -230,7 +230,7 @@ class Configuration:
230230
healthcheck_interval_seconds (int): The interval in seconds between health checks.
231231
verify (bool | str | ssl.SSLContext): Whether to verify the SSL certificate.
232232
pool_timeout_seconds (float): How long to wait for a free pooled connection.
233-
max_connections (int): The maximum number of connections in the pool.
233+
max_connections (int | None): The maximum number of pooled connections.
234234
max_keepalive_connections (int): The maximum number of idle pooled connections.
235235
max_concurrent_requests (int | None): The maximum number of requests in flight.
236236
stream_read_timeout_seconds (float): How long a stream waits for its next chunk.

‎src/typesense/sync/api_call.py‎

Lines changed: 48 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -211,18 +211,18 @@ def _max_open_exports(self, config: Configuration) -> typing.Optional[int]:
211211
212212
An open export keeps a connection but not a concurrency slot, so exports
213213
get the connections the slots cannot use. There is no limit without
214-
``max_concurrent_requests``, or when the pool is unlimited or belongs to a
215-
client passed in by the caller. When the slots alone can fill the pool, one
216-
export at a time is still allowed, which can leave a request short of a
217-
connection.
214+
``max_concurrent_requests``, when the pool is unlimited or belongs to a
215+
client passed in by the caller, or when the slots alone can fill the pool,
216+
which leaves no connection to keep free.
218217
"""
219218
max_concurrent_requests = config.max_concurrent_requests
220219
max_connections = config.max_connections
221220
if max_concurrent_requests is None or max_connections is None:
222221
return None
223222
if not self._owns_client:
224223
return None
225-
return max(max_connections - max_concurrent_requests, 1)
224+
spare_connections = max_connections - max_concurrent_requests
225+
return spare_connections if spare_connections > 0 else None
226226

227227
def __enter__(self) -> "ApiCall":
228228
"""Async context manager entry."""
@@ -631,9 +631,11 @@ def export_stream(
631631
"""
632632
Open a document export as a stream.
633633
634-
Failing nodes are retried like any other request until the response
635-
headers arrive. Errors after that are raised while reading the stream and
636-
are not retried, since part of the export has already been read.
634+
The export takes its place among the open exports before a node is chosen,
635+
and keeps it until the stream is closed or its body ends or fails. Failing
636+
nodes are retried like any other request until the response headers
637+
arrive. Errors after that are raised while reading the stream and are not
638+
retried, since part of the export has already been read.
637639
638640
Args:
639641
endpoint (str): The export endpoint to call.
@@ -643,16 +645,31 @@ def export_stream(
643645
Returns:
644646
ExportStream: The open stream.
645647
"""
646-
return self._execute_stream_request(
647-
endpoint,
648-
lambda node, url, request_kwargs: self._open_export_stream(
649-
node,
650-
url,
651-
compress,
652-
**request_kwargs,
653-
),
654-
params=params,
655-
)
648+
# Closes the response, then gives back the export's place.
649+
export = ExitStack()
650+
self._export_limit.acquire()
651+
export.callback(self._export_limit.release)
652+
try:
653+
response = self._execute_stream_request(
654+
endpoint,
655+
lambda node, url, request_kwargs: self._open_export_stream(
656+
export,
657+
node,
658+
url,
659+
compress,
660+
**request_kwargs,
661+
),
662+
params=params,
663+
)
664+
except BaseException:
665+
export.close()
666+
raise
667+
668+
# A single entry, so that a second close cannot give back the place while
669+
# the first is still closing the response.
670+
exit_stack = ExitStack()
671+
exit_stack.enter_context(export)
672+
return ExportStream(response, exit_stack)
656673

657674
def _execute_stream_request(
658675
self,
@@ -723,17 +740,18 @@ def _open_search_stream(
723740

724741
def _open_export_stream(
725742
self,
743+
export: ExitStack,
726744
node: Node,
727745
url: str,
728746
compress: bool,
729747
**kwargs: typing.Unpack[SessionFunctionKwargs[TParams, TBody]],
730-
) -> ExportStream:
748+
) -> ResponseType:
731749
"""
732-
Send an export request to `node` and return the stream once headers arrive.
750+
Send an export request to `node` and return the response once headers arrive.
733751
734-
The concurrency slot is held only while opening, so that a request made
735-
while reading the export does not have to wait for the export to finish.
736-
The stream keeps its place among the open exports until it is closed.
752+
The response is added to ``export``, which holds the export's place. The
753+
concurrency slot is held only while opening, so that a request made while
754+
reading the export does not have to wait for the export to finish.
737755
738756
Unless ``compress`` is set the export is requested uncompressed, because
739757
the server compresses on the thread that handles every other request. An
@@ -745,24 +763,19 @@ def _open_export_stream(
745763
headers["Accept-Encoding"] = "identity"
746764
response_context = self._stream_context("GET", url, request_kwargs)
747765

748-
# Closes the response, then gives back the export's place.
749-
export = ExitStack()
750-
self._export_limit.acquire()
751-
export.callback(self._export_limit.release)
766+
# Kept apart from ``export`` until the request succeeds, so that a failed
767+
# attempt closes its response without giving back the place.
768+
response_stack = ExitStack()
752769
try:
753770
with self._concurrency_limit:
754-
response = self._enter_stream(export, response_context)
771+
response = self._enter_stream(response_stack, response_context)
755772
except BaseException:
756-
export.close()
773+
response_stack.close()
757774
raise
758-
759-
# A single entry, so that a second close cannot give back the place while
760-
# the first is still closing the response.
761-
exit_stack = ExitStack()
762-
exit_stack.enter_context(export)
775+
export.enter_context(response_stack)
763776

764777
self.node_manager.set_node_health(node, is_healthy=True)
765-
return ExportStream(response, exit_stack)
778+
return response
766779

767780
def _stream_context(
768781
self,

‎src/typesense/sync/stream.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -267,7 +267,7 @@ def __init__(
267267
response (httpx.Response | httpx2.Response): A successful response
268268
opened with ``stream=True``.
269269
exit_stack (ExitStack): Closes the response and gives up the
270-
export's place when the stream is closed.
270+
export's place when the stream is closed or its body ends or fails.
271271
"""
272272
self.response = response
273273
self._exit_stack = exit_stack

0 commit comments

Comments
 (0)