8000 Clean up range checking in format_duration. · kubernetes-client/python@862f48a · GitHub
[go: up one dir, main page]

Skip to content

Commit 862f48a

Browse files
committed
Clean up range checking in format_duration.
Signed-off-by: Flynn <emissary@flynn.kodachi.com>
1 parent 90d4fef commit 862f48a

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

kubernetes/utils/duration.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
# really be a big deal.
2222
reDuration = re.compile(r'^([0-9]{1,5}(h|m|s|ms)){1,4}$')
2323

24+
# maxDuration_ms is the maximum duration that GEP-2257 can support, in milliseconds.
25+
maxDuration_ms = (((99999 * 3600) + (59 * 60) + 59) * 1_000) + 999
26+
2427
def parse_duration(duration) -> datetime.timedelta:
2528
"""
2629
Parse GEP-2257 Duration format to a datetime.timedelta object.
@@ -65,6 +68,13 @@ def format_duration(delta: datetime.timedelta) -> str:
6568
if delta == datetime.timedelta(0):
6669
return "0s"
6770

71+
# Check range early.
72+
if delta < datetime.timedelta(0):
73+
raise ValueError("Cannot express negative durations in GEP-2257: {}".format(delta))
74+
75+
if delta > datetime.timedelta(milliseconds=maxDuration_ms):
76+
raise ValueError("Cannot express durations longer than 99999h59m59s999ms in GEP-2257: {}".format(delta))
77+
6878
# durationpy.to_str() is happy to use floating-point seconds, which
6979
# GEP-2257 is _not_ happy with. So start by peeling off any microseconds
7080
# from our delta.
@@ -90,8 +100,5 @@ def format_duration(delta: datetime.timedelta) -> str:
90100

91101
delta_str += f"{delta_ms}ms"
92102

93-
if not reDuration.match(delta_str):
94-
raise ValueError("Invalid duration format: {}".format(durationpy.to_str(delta)))
95-
96103
return delta_str
97104

0 commit comments

Comments
 (0)
0