Fix the parser for a Retry-After header

Review the AI's codeMedium15 min

Your task

Your HTTP client waits before retrying when a server sends a Retry-After header. The header holds either a number of seconds or an HTTP date. An AI wrote the parser, and your team checks it against the header's rules before it controls retry timing in production.

An assistant wrote parse_retry_after_ms(header, now_epoch_seconds). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • header: the header's value as text.
  • now_epoch_seconds: the current time in epoch seconds (seconds since 1 January 1970, UTC).
  • Return how long to wait in milliseconds, or -1 when the header is not valid.

Rules the tests check:

  • Trim whitespace from both ends of header. If nothing is left, return -1.
  • If the trimmed header is one or more digits 0 to 9 and nothing else, it is a delay in seconds: return it times 1000.
  • Otherwise it must be an HTTP date in exactly this 29 character form: Wdy, DD Mon YYYY HH:MM:SS GMT. Anything else returns -1.
    • Wdy is any 3 characters. The weekday is not checked.
    • DD, YYYY, HH, MM and SS are digits 0 to 9, with exactly that many digits each.
    • Mon is one of Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec, with that exact case.
    • The punctuation and spaces are exactly as shown.
  • The day must be 1 to 31, the year at least 1, the hour 0 to 23, the minute 0 to 59 and the second 0 to 60. Otherwise return -1. The day is not checked against the month's length: a day past the month's end counts on into the next month, so 31 Feb 2015 is 3 Mar 2015.
  • Read the date as UTC on the Gregorian calendar and convert it to epoch seconds. A second of 60 is just 60 seconds past the minute. The delay is that minus now_epoch_seconds. If it is below 0, the delay is 0. Return the delay times 1000.

Examples

parse_retry_after_ms(header: str, now_epoch_seconds: int) -> int
Example 1
Inputparse_retry_after_ms("120", 1445412480)
Output120000
Example 2
Inputparse_retry_after_ms("Wed, 21 Oct 2015 07:30:00 GMT", 1445412480)
Output120000
Example 3
Inputparse_retry_after_ms("Wed, 21 Oct 2015 07:00:00 GMT", 1445412480)
Output0