dabla commented on code in PR #72398:
URL: https://github.com/apache/airflow/pull/72398#discussion_r4756920251
##########
providers/http/src/airflow/providers/http/hooks/http.py:
##########
@@ -687,6 +729,39 @@ async def request_func() -> ClientResponse:
raise NotImplementedError # should not reach this, but makes mypy
happy
+ async def _send(
+ self,
+ url: str,
+ *,
+ data: dict[str, Any] | str | None,
+ json: dict[str, Any] | str | None,
+ headers: dict[str, Any],
+ extra_options: dict[str, Any],
+ connection_header_names: set[str] | None = None,
+ ) -> ClientResponse:
+ extra_options = dict(extra_options)
+ if connection_header_names is None:
Review Comment:
**[nit]** The `None` fallback brings back the behaviour the last round
removed, and nothing reaches it.
`run()` is the only caller of `_run_with_retries`, which is the only caller
of `_send`, and it always passes `connection_header_names`. The fallback to
`self.config.connection_headers` here is the full Extra set, without the
caller's names taken out, so a future caller that leaves the argument out would
again drop a caller header on a cross-origin hop. Making the parameter required
in both signatures (`connection_header_names: set[str]`) removes the branch and
the risk.
##########
providers/http/src/airflow/providers/http/hooks/http.py:
##########
@@ -687,6 +729,39 @@ async def request_func() -> ClientResponse:
raise NotImplementedError # should not reach this, but makes mypy
happy
+ async def _send(
+ self,
+ url: str,
+ *,
+ data: dict[str, Any] | str | None,
+ json: dict[str, Any] | str | None,
+ headers: dict[str, Any],
+ extra_options: dict[str, Any],
+ connection_header_names: set[str] | None = None,
+ ) -> ClientResponse:
+ extra_options = dict(extra_options)
+ if connection_header_names is None:
+ connection_header_names = set(self.config.connection_headers)
+ if connection_header_names:
+ # A per-request middlewares= replaces the session's,
middlewares=() included; keep that.
+ if "middlewares" in extra_options:
Review Comment:
**[nit]** `extra_options={"middlewares": None}` drops the session's
middlewares, where aiohttp keeps them.
aiohttp falls back to the session's middlewares when the per-request value
is `None` and replaces them for anything else, `()` included
([client.py](https://github.com/aio-libs/aiohttp/blob/v3.14.5/aiohttp/client.py#L887-L890):
`self._middlewares if middlewares is None else middlewares`). The key test
here sends an explicit `None` into the first branch, where `tuple(None or ())`
is empty. Testing the value keeps the two in step:
```python
request_middlewares = extra_options.get("middlewares")
if request_middlewares is None:
other_middlewares = self._session._middlewares if self._session is not
None else ()
else:
other_middlewares = tuple(request_middlewares)
```
A fourth case `pytest.param(None, ...)` passed as an explicit key in
`test_async_extra_headers_compose_middlewares` would cover it.
##########
providers/http/tests/unit/http/hooks/test_http.py:
##########
@@ -1224,6 +1230,403 @@ async def
test_build_request_url_from_endpoint_param(self):
await hook.run(session=session,
endpoint="test.com:8080/v1/test")
assert mocked_function.call_args.args[0] ==
"http://test.com:8080/v1/test"
+ @pytest.mark.asyncio
+ @mock.patch("aiohttp.ClientSession.get", new_callable=mock.AsyncMock)
+ async def
test_async_request_without_extra_headers_uses_native_redirects(self,
mocked_get):
+ hook = HttpAsyncHook(method="GET", http_conn_id="http_empty_conn")
+ mocked_get.return_value = MockAiohttpClientResponse(
+ status=200, method="GET", url="http://example.com/v1"
+ )
+ async with aiohttp.ClientSession() as session:
+ await hook.run(session=session, endpoint="http://example.com/v1")
+ assert mocked_get.call_count == 1
+ assert mocked_get.call_args.kwargs.get("allow_redirects") is None
+ assert mocked_get.call_args.kwargs.get("middlewares") is None
+
+ @pytest.mark.asyncio
+ async def test_async_config_records_extra_header_names(self,
create_connection_without_db):
+ create_connection_without_db(
+ Connection(
+ conn_id="http_redirect_conn",
+ conn_type="http",
+ host="api.example.com",
+ extra=json.dumps({"X-API-Key": "secret", "max_redirects": 3}),
+ )
+ )
+ hook = HttpAsyncHook(http_conn_id="http_redirect_conn")
+ config = await hook.config()
+ assert config.connection_headers == {"X-API-Key"}
+ assert config.extra_options.get("max_redirects") == 3
+
+ @pytest.mark.asyncio
+ @mock.patch("aiohttp.ClientSession.get", new_callable=mock.AsyncMock)
+ async def
test_async_extra_headers_pass_middleware_without_forcing_redirects(
+ self, mocked_get, create_connection_without_db
+ ):
+ create_connection_without_db(
+ Connection(
+ conn_id="http_redirect_conn",
+ conn_type="http",
+ host="api.example.com",
+ schema="https",
+ extra=json.dumps({"X-API-Key": "secret"}),
+ )
+ )
+ hook = HttpAsyncHook(method="GET", http_conn_id="http_redirect_conn")
+ mocked_get.return_value = MockAiohttpClientResponse(
+ status=200, method="GET", url="https://api.example.com/v1"
+ )
+
+ async with aiohttp.ClientSession() as session:
+ await hook.run(session=session, endpoint="v1")
+
+ assert mocked_get.call_count == 1
+ kwargs = mocked_get.call_args.kwargs
+ assert kwargs.get("allow_redirects") is not False
+ middlewares = kwargs.get("middlewares")
+ assert middlewares
+ assert callable(middlewares[0])
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("request_middlewares", "expected_after_ours"),
+ [
+ pytest.param(None, ("session",), id="session-middlewares-kept"),
+ pytest.param(("extra",), ("extra",),
id="per-request-replaces-session"),
+ pytest.param((), (), id="empty-per-request-disables-session"),
+ ],
+ )
+ @mock.patch("aiohttp.ClientSession.get", new_callable=mock.AsyncMock)
+ async def test_async_extra_headers_compose_middlewares(
+ self, mocked_get, create_connection_without_db, request_middlewares,
expected_after_ours
+ ):
+ create_connection_without_db(
+ Connection(
+ conn_id="http_redirect_conn",
+ conn_type="http",
+ host="api.example.com",
+ schema="https",
+ extra=json.dumps({"X-API-Key": "secret"}),
+ )
+ )
+ hook = HttpAsyncHook(method="GET", http_conn_id="http_redirect_conn")
+ mocked_get.return_value = MockAiohttpClientResponse(
+ status=200, method="GET", url="https://api.example.com/v1"
+ )
+
+ async def session_mw(req, handler):
+ return await handler(req)
+
+ async def extra_mw(req, handler):
+ return await handler(req)
+
+ by_name = {"session": session_mw, "extra": extra_mw}
+ extra_options = (
+ {}
+ if request_middlewares is None
+ else {"middlewares": tuple(by_name[name] for name in
request_middlewares)}
+ )
+
+ async with aiohttp.ClientSession(middlewares=(session_mw,)) as session:
+ await hook.run(session=session, endpoint="v1",
extra_options=extra_options)
+
+ middlewares = mocked_get.call_args.kwargs["middlewares"]
+ assert middlewares[0] not in (session_mw, extra_mw)
+ assert middlewares[1:] == tuple(by_name[name] for name in
expected_after_ours)
+
+ @pytest.mark.asyncio
+ @mock.patch("aiohttp.ClientSession.get", new_callable=mock.AsyncMock)
+ async def test_async_allow_redirects_false_is_a_single_call(
+ self, mocked_get, create_connection_without_db
+ ):
+ create_connection_without_db(
+ Connection(
+ conn_id="http_redirect_conn",
+ conn_type="http",
+ host="api.example.com",
+ schema="https",
+ extra=json.dumps({"X-API-Key": "secret"}),
+ )
+ )
+ hook = HttpAsyncHook(method="GET", http_conn_id="http_redirect_conn")
+ mocked_get.return_value = MockAiohttpClientResponse(
+ status=302,
+ method="GET",
+ url="https://api.example.com/v1",
+ headers={"Location": "https://cdn.example.com/file"},
+ )
+
+ async with aiohttp.ClientSession() as session:
+ resp = await hook.run(
+ session=session,
+ endpoint="v1",
+ extra_options={"allow_redirects": False},
+ )
+
+ assert resp.status == 302
+ assert mocked_get.call_count == 1
+ assert mocked_get.call_args.kwargs["headers"]["X-API-Key"] == "secret"
+ assert mocked_get.call_args.kwargs.get("allow_redirects") is False
+
+ @pytest.mark.asyncio
+ @mock.patch("aiohttp.ClientSession.head", new_callable=mock.AsyncMock)
+ async def test_async_head_with_extra_does_not_force_allow_redirects(
+ self, mocked_head, create_connection_without_db
+ ):
+ create_connection_without_db(
+ Connection(
+ conn_id="http_redirect_conn",
+ conn_type="http",
+ host="api.example.com",
+ schema="https",
+ extra=json.dumps({"X-API-Key": "secret"}),
+ )
+ )
+ hook = HttpAsyncHook(method="HEAD", http_conn_id="http_redirect_conn")
+ mocked_head.return_value = MockAiohttpClientResponse(
+ status=200, method="HEAD", url="https://api.example.com/v1"
+ )
+
+ async with aiohttp.ClientSession() as session:
+ await hook.run(session=session, endpoint="v1")
+
+ assert mocked_head.call_count == 1
+ kwargs = mocked_head.call_args.kwargs
+ assert kwargs.get("allow_redirects") is not True
+ assert kwargs.get("middlewares")
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("same_origin", [True, False])
+ async def
test_async_connection_header_is_only_forwarded_on_a_same_origin_redirect(
+ self, same_origin, create_connection_without_db
+ ):
+ seen: dict[str, CIMultiDict] = {}
+
+ async def dest(request: web.Request) -> web.Response:
+ seen["dest"] = CIMultiDict(request.headers)
+ return web.Response(text="ok")
+
+ def start_handler(location: str):
+ async def start(request: web.Request) -> web.StreamResponse:
+ seen["start"] = CIMultiDict(request.headers)
+ raise web.HTTPFound(location)
+
+ return start
+
+ async def run_hook(origin_server: TestServer) -> None:
+ create_connection_without_db(
+ Connection(
+ conn_id="http_redirect_live",
+ conn_type="http",
+ host=origin_server.host,
+ port=origin_server.port,
+ schema="http",
+ extra=json.dumps({"X-API-Key": "secret"}),
+ )
+ )
+ hook = HttpAsyncHook(method="GET",
http_conn_id="http_redirect_live")
+ resp = await hook.run(endpoint="start")
+ try:
+ assert resp.status == 200
+ assert await resp.text() == "ok"
+ assert len(resp.history) == 1
+ assert seen["start"]["X-API-Key"] == "secret"
+ if same_origin:
+ assert seen["dest"]["X-API-Key"] == "secret"
+ else:
+ assert "X-API-Key" not in seen["dest"]
+ finally:
+ resp.release()
+
+ if same_origin:
+ app = web.Application()
+ app.router.add_get("/dest", dest)
+ app.router.add_get("/start", start_handler("/dest"))
+ async with TestServer(app) as origin_server:
+ await run_hook(origin_server)
+ return
+
+ dest_app = web.Application()
+ dest_app.router.add_get("/dest", dest)
+ async with TestServer(dest_app) as dest_server:
+ origin_app = web.Application()
+ origin_app.router.add_get("/start",
start_handler(str(dest_server.make_url("/dest"))))
+ async with TestServer(origin_app) as origin_server:
+ await run_hook(origin_server)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("caller_header_name", ["Accept", "accept",
"ACCEPT"])
+ async def test_caller_header_overriding_connection_header_is_kept(
+ self, create_connection_without_db, caller_header_name
+ ):
+ from aiohttp import web
Review Comment:
**[warning]** This test repeats the two-server redirect set-up of the test
above it, and re-imports what the module already imports.
`dest`, `start_handler`, the two `TestServer`s and the connection are
written out a second time here (the first copy is in
`test_async_connection_header_is_only_forwarded_on_a_same_origin_redirect`).
The copies already differ: `CIMultiDict(request.headers)` there,
`dict(request.headers)` here, which is why this one needs `.get("Accept")` on
an exact-case key. One fixture that starts the origin and destination servers
and yields the origin server plus the recorded headers would leave each test
with its connection, its call and its assertions.
`from aiohttp import web` and `from aiohttp.test_utils import TestServer`
are at the top of the module since this PR (lines 35-36), so the two local
imports can go; the project keeps imports at module level
([AGENTS.md](https://github.com/apache/airflow/blob/main/AGENTS.md)).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]