Skip to content

Commit

Permalink
Add caching to API Resources (#254)
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobtomlinson authored Dec 15, 2023
1 parent 1a79d2c commit 134647a
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 9 deletions.
5 changes: 5 additions & 0 deletions kr8s/_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

import aiohttp
import httpx
from asyncache import cached
from cachetools import TTLCache
from cryptography import x509

from ._auth import KubeAuth
Expand Down Expand Up @@ -443,6 +445,9 @@ async def api_resources(self) -> dict:
"""Get the Kubernetes API resources."""
return await self._api_resources()

# Cache for 10 minutes because kubectl does
# https://github.com/kubernetes/kubernetes/blob/0fb71846df9babb6012a7fce22e2533e9d795baa/staging/src/k8s.io/cli-runtime/pkg/genericclioptions/config_flags.go#L253
@cached(TTLCache(1, 600))
async def _api_resources(self) -> dict:
"""Get the Kubernetes API resources."""
resources = []
Expand Down
18 changes: 9 additions & 9 deletions kr8s/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,15 +236,6 @@ def test_sync_api_returns_sync_objects():
assert pods[0]._asyncio is False


def test_api_client_reuse_between_event_loops():
async def get_api():
await kr8s.asyncio.get("pods", namespace=kr8s.ALL)

asyncio.run(get_api())
asyncio.set_event_loop(asyncio.new_event_loop())
asyncio.run(get_api())


async def test_api_names(example_pod_spec, ns):
pod = await Pod(example_pod_spec)
await pod.create()
Expand All @@ -269,3 +260,12 @@ async def test_whoami():
async def test_whoami_sync():
api = kr8s.api()
assert kr8s.whoami() == api.whoami()


async def test_api_resources_cache(caplog):
caplog.set_level("INFO")
api = await kr8s.asyncio.api()
await api.api_resources()
assert caplog.text.count('/apis/ "HTTP/1.1 200 OK"') == 1
await api.api_resources()
assert caplog.text.count('/apis/ "HTTP/1.1 200 OK"') == 1
2 changes: 2 additions & 0 deletions kr8s/tests/test_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ async def main():
api = await kr8s.asyncio.api()
version = await api.version()
assert "major" in version
api_resources = await api.api_resources()
assert api_resources

trio.run(main)

Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ requires-python = ">=3.8"
dynamic = ["version"]
dependencies = [
"aiohttp>=3.8.4",
"asyncache>=0.3.1",
"cryptography>=35",
"pyyaml>=6.0",
"python-jsonpath>=0.7.1",
Expand Down

0 comments on commit 134647a

Please sign in to comment.