Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
83 changes: 48 additions & 35 deletions src/typesense/async_/api_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,18 +211,18 @@ 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
if max_concurrent_requests is None or max_connections is None:
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."""
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/typesense/async_/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 7 additions & 7 deletions src/typesense/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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.
Expand Down
83 changes: 48 additions & 35 deletions src/typesense/sync/api_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,18 +211,18 @@ 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
if max_concurrent_requests is None or max_connections is None:
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."""
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/typesense/sync/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading