util.py
Overview
The util.py file provides a collection of utility functions primarily focused on configuration parsing and validation related to environment settings, memory limits, and time durations. These utilities help standardize and simplify common operations such as interpreting boolean flags from strings, validating memory limit formats (especially Docker-style memory specifications), and parsing or formatting timeout durations expressed as strings.
This file is typically used in broader system components that require interpreting user or environment input for configuration purposes, ensuring that inputs conform to expected formats before use.
Functions
1. is_enabled(value: str) -> bool
Purpose:
Determines whether a given string value represents an enabled (or "true") flag.
Parameters:
value(str): The input string to evaluate.
Returns:
bool:Trueif the input string (case-insensitive) is one of{"1", "true", "yes", "on"}, otherwiseFalse.
Usage Example:
is_enabled("Yes") # Returns: True
is_enabled("no") # Returns: False
is_enabled("1") # Returns: True
Details:
Trims whitespace and converts the input to lowercase before checking membership in a set of accepted "enabled" values.
2. env_setting_enabled(env_key: str, default: str = "false") -> bool
Purpose:
Checks if a given environment variable key corresponds to an enabled flag, using the is_enabled interpretation.
Parameters:
env_key(str): The name of the environment variable to check.default(str, optional): Default value to use if the environment variable is not set. Defaults to"false".
Returns:
bool:Trueif the environment variable's value is enabled, elseFalse.
Usage Example:
# Assuming environment variable DEBUG="true"
env_setting_enabled("DEBUG") # Returns: True
# If environment variable not set
env_setting_enabled("FEATURE_X", default="yes") # Returns: True
Details:
Fetches the environment variable value using os.getenv(), then delegates evaluation to is_enabled().
3. is_valid_memory_limit(mem: str | None) -> bool
Purpose:
Validates whether a given string is a valid Docker-style memory limit specification.
Parameters:
mem(strorNone): The memory limit string to validate (e.g.,"256m","1g").
Returns:
bool:Trueifmemis a non-empty string matching the required pattern, otherwiseFalse.
Usage Example:
is_valid_memory_limit("512m") # Returns: True
is_valid_memory_limit("0g") # Returns: False (zero disallowed)
is_valid_memory_limit("10x") # Returns: False (invalid unit)
Details:
Acceptable units:
b,k,m,g(case-insensitive).The numeric part must be a positive integer (no zero or negative values).
Uses a regular expression to validate the format:
^[1-9]\d*(b|k|m|g)$Trims and lowers the input string before validation.
4. parse_timeout_duration(timeout: str | None, default_seconds: int = 10) -> int
Purpose:
Parses a timeout duration string into an integer number of seconds.
Parameters:
timeout(strorNone): Timeout string to parse (e.g.,"90s","2m","1m30s").default_seconds(int, optional): Default number of seconds to return if parsing fails. Default is10.
Returns:
int: Total timeout duration in seconds.
Usage Example:
parse_timeout_duration("1m30s") # Returns: 90
parse_timeout_duration("45s") # Returns: 45
parse_timeout_duration(None) # Returns: 10 (default)
parse_timeout_duration("abc") # Returns: 10 (default)
Details:
Supports optional minutes and seconds parts, both optional but at least one must be present.
Valid formats include
"Xm","Ys", or"XmYs"where X and Y are integers.Regex pattern used:
^(?:(\d+)m)?(?:(\d+)s)?$If total calculated seconds is zero or invalid format, returns the default.
5. format_timeout_duration(seconds: int) -> str
Purpose:
Formats an integer number of seconds into a string representation with minutes and seconds.
Parameters:
seconds(int): Number of seconds to format.
Returns:
str: Formatted timeout string, e.g.,"1m30s".
Usage Example:
format_timeout_duration(90) # Returns: "1m30s"
format_timeout_duration(45) # Returns: "45s"
format_timeout_duration(120) # Returns: "2m"
Details:
If less than 60 seconds, returns only seconds with suffix
"s".Otherwise, splits into minutes and remaining seconds.
Omits seconds if zero.
Implementation Details
Boolean evaluation: Uses a fixed set of string matches representing "true" values for consistency in configuration parsing.
Environment variables: Relies on standard Python
os.getenvwith defaults to safely access environment-based flags.Regex usage: For memory limit validation and timeout parsing, regex ensures strict adherence to expected formats, reducing errors from malformed inputs.
Timeout parsing: Supports flexible combinations of minutes and seconds allowing for granular timeout specifications.
Timeout formatting: Provides a human-readable conversion from integer seconds to a common minute-second notation.
Interactions with Other System Parts
This utility file is designed to be imported by various components that need to parse environment variables and configuration values related to resource limits and timeouts.
The functions here can be used in configuration loaders, resource managers, or anywhere environment-driven flags and time/duration values need normalization or validation.
Since the file is independent and does not maintain state, it acts as a pure utility module, typically called by higher-level configuration or runtime code.
Visual Diagram
flowchart TD
A[is_enabled(value: str) -> bool]
B[env_setting_enabled(env_key: str, default: str) -> bool]
C[is_valid_memory_limit(mem: str | None) -> bool]
D[parse_timeout_duration(timeout: str | None, default_seconds: int) -> int]
E[format_timeout_duration(seconds: int) -> str]
B --> A
Diagram Explanation:
env_setting_enableddepends onis_enabledto determine boolean flags from environment variables.Other functions operate independently.
The diagram highlights the main function relationships and independence within the utility module.
Summary
The util.py file is a straightforward utility module providing helper functions for:
Converting strings to boolean flags (
is_enabledandenv_setting_enabled).Validating Docker-like memory limit strings (
is_valid_memory_limit).Parsing and formatting timeout durations (
parse_timeout_durationandformat_timeout_duration).
Its simplicity and independence make it a reusable component for configuration and environment parsing throughout the InfiniFlow project or similar applications.