Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close dependent http responses before closing api context #1109

Merged
merged 2 commits into from
Apr 8, 2024
Merged
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
40 changes: 37 additions & 3 deletions kopf/_cogs/clients/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import ssl
import tempfile
from contextvars import ContextVar
from typing import Any, Callable, Dict, Iterator, Mapping, Optional, TypeVar, cast
from typing import Any, Callable, Dict, Iterator, List, Mapping, Optional, TypeVar, cast

import aiohttp

Expand Down Expand Up @@ -36,13 +36,22 @@ async def wrapper(*args: Any, **kwargs: Any) -> Any:
# If a context is explicitly passed, make it a simple call without re-auth.
# Exceptions are escalated to a caller, which is probably wrapped itself.
if 'context' in kwargs:
return await fn(*args, **kwargs)
context = kwargs['context']
response = await fn(*args, **kwargs)
if isinstance(response, aiohttp.ClientResponse):
# Keep track of responses which are using this context.
context.add_response(response)
return response

# Otherwise, attempt the execution with the vault credentials and re-authenticate on 401s.
vault: credentials.Vault = vault_var.get()
async for key, info, context in vault.extended(APIContext, 'contexts'):
try:
return await fn(*args, **kwargs, context=context)
response = await fn(*args, **kwargs, context=context)
if isinstance(response, aiohttp.ClientResponse):
# Keep track of responses which are using this context.
context.add_response(response)
return response
except errors.APIUnauthorizedError as e:
await vault.invalidate(key, exc=e)

Expand Down Expand Up @@ -74,6 +83,9 @@ class APIContext:
server: str
default_namespace: Optional[str]

# List of open responses.
responses: List[aiohttp.ClientResponse]

# Temporary caches of the information retrieved for and from the environment.
_tempfiles: "_TempFiles"

Expand Down Expand Up @@ -166,10 +178,32 @@ def __init__(
self.server = info.server
self.default_namespace = info.default_namespace

self.responses = []

# For purging on garbage collection.
self._tempfiles = tempfiles

def flush_closed_responses(self) -> None:
# There's no point keeping references to already closed responses.
self.responses[:] = [_response for _response in self.responses if not _response.closed]

def add_response(self, response: aiohttp.ClientResponse) -> None:
# Keep track of responses so they can be closed later when the session
# is closed.
self.flush_closed_responses()
if not response.closed:
self.responses.append(response)

def close_open_responses(self) -> None:
# Close all responses that are still open and are using this session.
for response in self.responses:
if not response.closed:
response.close()
self.responses.clear()

async def close(self) -> None:
# Close all open responses that use this session before closing the session itself.
self.close_open_responses()

# Closing is triggered by `Vault._flush_caches()` -- forward it to the actual session.
await self.session.close()
Expand Down
Loading