Resilient Fake API Client
Learn this problemProblem statement
A fake API provides one response per attempt through parallel arrays statuses and bodies. Process at most maxAttempts responses in order.
- A status from
200through299is successful. Parse its body using the closed JSON grammar below. ReturnSUCCESS:followed by the object with keys sorted lexicographically, orJSON_ERRORwhen parsing fails. - Status
429and every status from500through599are retryable while attempts remain. - Every other status is terminal; return
HTTP_n, wherenis the status. - If every permitted attempt is retryable, return
EXHAUSTED.
An accepted body is exactly {} or a whitespace-free object such as {"b":"two","a":"1"}. Keys are unique, nonempty strings. Values may be empty. Key and value characters are limited to ASCII letters, digits, underscores, and hyphens. Escapes, nesting, arrays, numbers, booleans, null, and whitespace are invalid.
Function
handleResponses(statuses: int[], bodies: String[], maxAttempts: int) → StringExamples
Example 1
statuses = [429,503,200]bodies = ["ignored","ignored","{\"b\":\"two\",\"a\":\"1\"}"]maxAttempts = 3return = "SUCCESS:{\"a\":\"1\",\"b\":\"two\"}"The client retries the rate limit and server failure. The successful body is valid and its keys are canonicalized.
Example 2
statuses = [500,429,503,200]bodies = ["","","","{}"]maxAttempts = 3return = "EXHAUSTED"Only three attempts are permitted, and all three observed statuses are retryable. The later success is not consumed.
Example 3
statuses = [200]bodies = ["{\"a\": \"b\"}"]maxAttempts = 1return = "JSON_ERROR"Whitespace is outside the accepted grammar, so a successful HTTP status still produces a parse error.
Constraints
1 <= statuses.length == bodies.length <= 100000.1 <= maxAttempts <= statuses.length.100 <= statuses[i] <= 599.0 <= bodies[i].length <= 1000.- A body is parsed only for the first successful status.
- Accepted object keys are unique and the total output fits in memory.