centralize HTTP request handling

This commit is contained in:
Steven Tischer
2026-07-26 09:34:02 +02:00
parent 1810918e43
commit b0e4ad639e
@@ -129,6 +129,51 @@ def _wrap_exception(e: Exception) -> Exception:
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
async def _request(
method: str,
cluster: ESCluster,
path: str,
*,
json_body: Optional[Any] = None,
params: Optional[Dict[str, Any]] = None,
content: Optional[bytes] = None,
content_type: str = "application/json",
) -> httpx.Response:
"""Sends an authenticated request to cluster and returns the raw response.
Args:
method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE").
cluster: The Elasticsearch cluster to send the request to.
path: The path appended to the cluster URL (without leading slash).
json_body: Optional JSON-serialisable request body.
params: Optional query parameters.
content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body.
content_type: The Content-Type header value.
Returns:
httpx.Response: The successful response (status already checked).
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
client = get_client()
try:
response = await client.request(
method,
f"{elasticsearch_url}/{path}",
json=json_body,
params=params,
content=content,
headers=_headers(api_key, content_type=content_type),
)
response.raise_for_status()
return response
except Exception as exc:
raise _wrap_exception(exc) from exc
async def search(
index: ESIndex | List[ESIndex] | str | List[str],
query: Optional[Dict] = None,
@@ -179,8 +224,6 @@ async def search(
elif len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
payload: Dict[str, Any] = {}
if body is not None:
@@ -212,59 +255,33 @@ async def search(
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
)
client = get_client()
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}"
)
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=_headers(api_key)
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload)
return response.json()
async def open_point_in_time(
index: str, keep_alive: str = "1m", cluster: str = "nes"
) -> str:
"""Opens a point-in-time on the given index and returns its id."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive})
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_pit",
params={"keep_alive": keep_alive},
headers=_headers(api_key),
)
response.raise_for_status()
return response.json()["id"]
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()["id"]
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
"""Closes a previously opened point-in-time."""
elasticsearch_url, api_key = _cluster_credentials(cluster)
client = get_client()
try:
response = await client.request(
"DELETE",
f"{elasticsearch_url}/_pit",
json={"id": pit_id},
headers=_headers(api_key),
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
await _request("DELETE", cluster, "_pit", json_body={"id": pit_id})
async def scan(
@@ -280,12 +297,9 @@ async def scan(
Unlike ``from``/``size`` pagination, this is not bounded by
``index.max_result_window``, so it can stream result sets larger than 10k.
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
search_after: Optional[List] = None
try:
client = get_client()
while True:
payload: Dict[str, Any] = {
"size": page_size,
@@ -298,14 +312,7 @@ async def scan(
if search_after is not None:
payload["search_after"] = search_after
try:
response = await client.post(
f"{elasticsearch_url}/_search", json=payload, headers=_headers(api_key)
)
response.raise_for_status()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, "_search", json_body=payload)
result = response.json()
hits = result.get("hits", {}).get("hits", [])
@@ -337,22 +344,13 @@ async def get(
if isinstance(index, ESIndex):
cluster = _index_to_cluster(index) or cluster
elasticsearch_url, api_key = _cluster_credentials(cluster)
params = {}
if source is not None:
params["_source_includes"] = ",".join(source)
client = get_client()
try:
response = await client.get(
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=_headers(api_key)
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params)
return response.json()
async def update(
@@ -361,19 +359,11 @@ async def update(
doc: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
response = await _request(
"POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc}
)
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index}/_update/{doc_id}",
json={"doc": doc},
headers=_headers(api_key),
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def index_doc(
@@ -382,19 +372,11 @@ async def index_doc(
document: Dict[str, Any],
cluster: ESCluster = ESCluster.NES,
) -> Dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
response = await _request(
"PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document
)
client = get_client()
try:
response = await client.put(
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
json=document,
headers=_headers(api_key),
)
response.raise_for_status()
return response.json()
except Exception as exc:
raise _wrap_exception(exc) from exc
return response.json()
async def count(
@@ -427,23 +409,15 @@ async def count(
if len(clusters) == 1:
cluster = clusters.pop()
elasticsearch_url, api_key = _cluster_credentials(cluster)
if isinstance(index, list):
index_str = ",".join(str(idx) for idx in index)
else:
index_str = str(index)
payload = {"query": query} if query else {}
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=_headers(api_key)
)
response.raise_for_status()
return response.json().get("count", 0)
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload)
return response.json().get("count", 0)
async def msearch(
@@ -468,9 +442,6 @@ async def msearch(
if c is not None:
cluster = c
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = _headers(api_key, content_type="application/x-ndjson")
lines = []
for idx, body in searches:
if isinstance(idx, list):
@@ -483,16 +454,13 @@ async def msearch(
ndjson_payload = "\n".join(lines) + "\n"
client = get_client()
try:
response = await client.post(
f"{elasticsearch_url}/_msearch",
content=ndjson_payload.encode("utf-8"),
headers=_headers(api_key),
)
response.raise_for_status()
res_json = response.json()
return res_json.get("responses", [])
except Exception as exc:
raise _wrap_exception(exc) from exc
response = await _request(
"POST",
cluster,
"_msearch",
content=ndjson_payload.encode("utf-8"),
content_type="application/x-ndjson",
)
return response.json().get("responses", [])