Fix the billing model for a bounded downstream call

Review the AI's codeEasy12 minAmazon style

Your task

Your API Gateway Lambda calls a flaky downstream service. The first version had no timeout on that call, so a slow downstream kept every invocation running, and billed, until Lambda stopped it. The fix bounds the call with an abort timer and sends a fast fallback response. Your team wants a model of what each request is billed under the fix.

An assistant wrote billed_ms_per_request(downstream_ms, call_timeout_ms, function_timeout_ms, fallback_ms). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • downstream_ms: for each request, how long the downstream would take to answer, in milliseconds (ms).
  • call_timeout_ms: when the abort timer on the call fires.
  • function_timeout_ms: the Lambda's own timeout. Lambda stops the invocation at this point, and nothing is billed past it.
  • fallback_ms: how long the fallback response takes after an abort.
  • Return the billed ms for each request, in request order. All values are whole numbers, 0 or more.

Rules the tests check, for a request whose downstream time is d:

  1. If d is at most call_timeout_ms and at most function_timeout_ms, the call answers. Bill d.
  2. Otherwise, if call_timeout_ms is less than function_timeout_ms, the abort fires. Bill call_timeout_ms + fallback_ms, but never more than function_timeout_ms.
  3. Otherwise the abort never fires before Lambda stops the invocation. Bill function_timeout_ms.

Examples

billed_ms_per_request(downstream_ms: list[int], call_timeout_ms: int, function_timeout_ms: int, fallback_ms: int) -> list[int]
Example 1
Inputbilled_ms_per_request([120, 8000, 45], 2000, 30000, 50)
Output[120, 2050, 45]
Example 2
Inputbilled_ms_per_request([50000], 60000, 30000, 50)
Output[30000]