Skip to content
Open
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
6 changes: 6 additions & 0 deletions kubernetes/aio/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,9 @@
FailToCreateError, create_from_dict, create_from_yaml,
create_from_yaml_single_item,
)
from .retry import (Backoff, DEFAULT_BACKOFF, DEFAULT_RETRY,
DEFAULT_RETRY_AFTER_BACKOFF, async_on_error,
async_on_retry_after_error, async_retry_on_conflict,
is_conflict, is_retry_after_response,
is_too_many_requests, retry_after_backoff,
retry_after_max_retries, retry_after_seconds)
1 change: 1 addition & 0 deletions kubernetes/aio/utils/_retry_base.py
113 changes: 113 additions & 0 deletions kubernetes/aio/utils/retry.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Copyright 2026 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import random
from typing import Awaitable, Callable, TypeVar

from ._retry_base import (
Backoff,
DEFAULT_BACKOFF,
DEFAULT_RETRY,
DEFAULT_RETRY_AFTER_BACKOFF,
_delay,
is_conflict,
is_retry_after_response,
is_too_many_requests,
retry_after_backoff,
retry_after_max_retries,
retry_after_seconds,
)


T = TypeVar("T")


# The retry helpers in this module are async 1:1 Python implementations of the
# Kubernetes Go retry algorithms used by client-go:
# - https://github.com/kubernetes/client-go/blob/master/util/retry/util.go
# - https://github.com/kubernetes/client-go/blob/master/rest/with_retry.go
async def async_on_error(
backoff: Backoff,
retriable: Callable[[Exception], bool],
fn: Callable[[], Awaitable[T]],
sleep_func: Callable[[float], Awaitable[None]] = asyncio.sleep,
random_func: Callable[[], float] = random.random,
) -> T:
"""Async 1:1 implementation of client-go ``retry.OnError``."""

steps = backoff.steps
duration = backoff.duration
last_error = None
while steps > 0:
try:
return await fn()
except Exception as error:
if not retriable(error):
raise
last_error = error

if steps == 1:
break

delay, duration, steps = _delay(
steps, duration, backoff, random_func)
await sleep_func(delay)

raise last_error


async def async_retry_on_conflict(
fn: Callable[[], Awaitable[T]],
backoff: Backoff = DEFAULT_RETRY,
sleep_func: Callable[[float], Awaitable[None]] = asyncio.sleep,
random_func: Callable[[], float] = random.random,
) -> T:
"""Async 1:1 implementation of client-go ``retry.RetryOnConflict``."""

return await async_on_error(
backoff, is_conflict, fn, sleep_func, random_func)


async def async_on_retry_after_error(
backoff: Backoff,
retriable: Callable[[Exception], bool],
fn: Callable[[], Awaitable[T]],
sleep_func: Callable[[float], Awaitable[None]] = asyncio.sleep,
random_func: Callable[[], float] = random.random,
) -> T:
"""Async implementation of client-go REST Retry-After sleep semantics."""

steps = backoff.steps
duration = backoff.duration
last_error = None
while steps > 0:
try:
return await fn()
except Exception as error:
if not retriable(error):
raise
last_error = error

if steps == 1:
break

delay, duration, steps = _delay(
steps, duration, backoff, random_func)
retry_after = retry_after_seconds(error)
if retry_after is not None and retry_after > delay:
delay = retry_after
await sleep_func(delay)

raise last_error
124 changes: 124 additions & 0 deletions kubernetes/aio/utils/retry_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Copyright 2026 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

from kubernetes.aio.utils.retry import (
Backoff,
DEFAULT_RETRY,
async_on_error,
async_on_retry_after_error,
async_retry_on_conflict,
is_too_many_requests,
retry_after_seconds,
)


class FakeError(Exception):

def __init__(self, status, headers=None):
super().__init__("status {0}".format(status))
self.status = status
self.headers = headers or {}


class AioRetryTest(unittest.IsolatedAsyncioTestCase):

def test_default_retry_matches_client_go(self):
self.assertEqual(
DEFAULT_RETRY,
Backoff(steps=5, duration=0.01, factor=1.0, jitter=0.1),
)

def test_retry_after_seconds_parses_delay_seconds(self):
error = FakeError(429, {"Retry-After": "7"})

self.assertEqual(retry_after_seconds(error), 7.0)

async def test_async_on_error_retries_retriable_errors(self):
attempts = []
sleeps = []

async def fn():
attempts.append(1)
if len(attempts) < 3:
raise FakeError(500)
return "ok"

async def sleep(delay):
sleeps.append(delay)

result = await async_on_error(
Backoff(steps=4, duration=1.0, factor=2.0),
lambda e: getattr(e, "status", None) == 500,
fn,
sleep_func=sleep,
random_func=lambda: 0.0,
)

self.assertEqual(result, "ok")
self.assertEqual(len(attempts), 3)
self.assertEqual(sleeps, [1.0, 2.0])

async def test_async_on_retry_after_error_honors_retry_after_for_429(self):
attempts = []
sleeps = []

async def fn():
attempts.append(1)
if len(attempts) < 2:
raise FakeError(429, {"Retry-After": "3"})
return "ok"

async def sleep(delay):
sleeps.append(delay)

result = await async_on_retry_after_error(
Backoff(steps=3, duration=1.0, factor=2.0),
is_too_many_requests,
fn,
sleep_func=sleep,
random_func=lambda: 0.0,
)

self.assertEqual(result, "ok")
self.assertEqual(sleeps, [3.0])

async def test_async_retry_on_conflict_retries(self):
attempts = []
sleeps = []

async def fn():
attempts.append(1)
if len(attempts) < 3:
raise FakeError(409)
return "updated"

async def sleep(delay):
sleeps.append(delay)

result = await async_retry_on_conflict(
fn,
backoff=Backoff(steps=3, duration=1.0, factor=1.0),
sleep_func=sleep,
random_func=lambda: 0.0,
)

self.assertEqual(result, "updated")
self.assertEqual(len(attempts), 3)
self.assertEqual(sleeps, [1.0, 1.0])


if __name__ == "__main__":
unittest.main()
Loading