OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Calculate a Retry-After delay using an explicit UTC clock

Python

Calculate a waiting interval from a restricted Retry-After value without sleeping, contacting a server or automatically retrying a request.

Python code excerpt: Calculate a Retry-After delay using an explicit UTC clock. Version 1.0.0. Read the full recipe for code, sources and recorded test scope.

Use this deterministic helper when testing retry configuration or inspecting an HTTP response. Supply the header value, an explicit UTC reference time and an informational cap. The result reports the delay and whether it exceeds that cap. Your caller remains responsible for retry safety, scheduling and idempotency.

Before you start

  • Python 3.12 standard library and the reviewed pinned runtime; no third-party packages.
  • One UTF-8 JSON request on stdin, at most 20000 encoded bytes. One extra byte may be read to detect overflow.
  • Use synthetic examples when sharing requests. The program does not read configuration files, environment variables or network services.

Build and check

  1. Save the downloaded source as calculate-retry-after-delay-python.py.
  2. Save the example JSON request below as request.json.
  3. Run python3 calculate-retry-after-delay-python.py < request.json.
  4. Compare stdout with the expected JSON. Exit 0 processes a valid request; invalid input exits 2 with empty stdout and a generic stderr message.

Limits to understand

  • The request must contain exactly retry_after and now strings, plus an integer cap_seconds from 0 through 86400. Booleans are rejected.
  • now must use YYYY-MM-DDTHH:MM:SSZ. HTTP dates must use exact IMF-fixdate spelling with GMT and a matching weekday; date years are restricted to 1970 through 2100.
  • ASCII delta-seconds are limited to 0 through 604800. Leading zeros are accepted. For absolute dates, the computed delay may exceed seven days; past dates return zero.
  • exceeds_cap informs the caller but does not clamp the delay. No sleep, jitter, HTTP request or automatic retry is performed.
  • This intentionally restricted parser rejects obsolete HTTP-date forms and surrounding whitespace. It is not a complete general-purpose HTTP header parser. Leap seconds are rejected.

Run it

python3 calculate-retry-after-delay-python.py < request.json

Example input

{"retry_after":"120","now":"2026-11-13T12:00:00Z","cap_seconds":60}

Expected output

{"delay_seconds":120,"exceeds_cap":true,"kind":"delta"}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Python example
import sys
import json
import re
from datetime import datetime, timezone


NOW_RE = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z')
DATE_RE = re.compile(r'(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2}) GMT')
DIGITS_RE = re.compile(r'[0-9]+')
MONTHS = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
WEEKDAYS = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')


def reject(*args):
    raise ValueError('invalid input')


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            reject()
        result[key] = value
    return result


def check_unicode(value):
    pending = [value]
    while pending:
        item = pending.pop()
        if isinstance(item, str):
            if any(0xD800 <= ord(char) <= 0xDFFF for char in item):
                reject()
        elif isinstance(item, dict):
            pending.extend(item.keys())
            pending.extend(item.values())
        elif isinstance(item, list):
            pending.extend(item)


def utc_datetime(year, month, day, hour, minute, second):
    if not 1970 <= year <= 2100:
        reject()
    return datetime(year, month, day, hour, minute, second, tzinfo=timezone.utc)


def calculate(data):
    if type(data) is not dict or set(data) != {'retry_after', 'now', 'cap_seconds'}:
        reject()
    retry_after = data['retry_after']
    now_text = data['now']
    cap = data['cap_seconds']
    if type(retry_after) is not str or type(now_text) is not str:
        reject()
    if type(cap) is not int or not 0 <= cap <= 86400:
        reject()

    match = NOW_RE.fullmatch(now_text)
    if match is None:
        reject()
    now = utc_datetime(*(int(part) for part in match.groups()))

    if DIGITS_RE.fullmatch(retry_after) is not None:
        significant = retry_after.lstrip('0') or '0'
        if len(significant) > 6:
            reject()
        delay = int(significant)
        if delay > 604800:
            reject()
        kind = 'delta'
    else:
        match = DATE_RE.fullmatch(retry_after)
        if match is None:
            reject()
        weekday, day, month, year, hour, minute, second = match.groups()
        target = utc_datetime(int(year), MONTHS.index(month) + 1, int(day),
                              int(hour), int(minute), int(second))
        if WEEKDAYS[target.weekday()] != weekday:
            reject()
        difference = target - now
        delay = max(0, difference.days * 86400 + difference.seconds)
        kind = 'date'

    return {'delay_seconds': delay, 'exceeds_cap': delay > cap, 'kind': kind}


def main():
    try:
        if len(sys.argv) != 1:
            reject()
        raw = sys.stdin.buffer.read(20001)
        if len(raw) > 20000:
            reject()
        text = raw.decode('utf-8', errors='strict')
        data = json.loads(text, object_pairs_hook=unique_object,
                          parse_constant=reject, parse_float=reject)
        check_unicode(data)
        result = calculate(data)
        output = json.dumps(result, separators=(',', ':'), ensure_ascii=True) + '\n'
    except Exception:
        sys.stderr.write('Invalid input\n')
        return 2
    sys.stdout.write(output)
    return 0


if __name__ == '__main__':
    sys.exit(main())
What to verify after running
  • Run the documented example and compare its parsed JSON output.
  • Confirm invalid input exits 2 and does not echo request contents to stdout.
  • 40 independent CLI cases passed on the exact reviewed source in the pinned Python sandbox.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 1.0.0 · Documentation reviewed 2026-11-14.

    40 independent CLI cases passed in rootless Docker on the pinned Python 3.12 image, with 512 MiB RAM, 1 CPU and no network. Includes the documented example, malformed input, Unicode and the inclusive 20000-byte boundary. Other runtimes and all possible inputs have not been verified.