Workspace/Coding labs
Loading progress

Implement a scoped idempotent inventory operation

Intermediate60 min

Implement reserve_inventory(stock, ledger, principal, key, sku, quantity). It mutates in-memory stock once per tenant-scoped key and returns a copied result for identical replays.

Your task

  1. Require a nonempty string tenant and inventory:reserve in principal scopes on every call, including replays; otherwise raise PermissionError.
  2. Require nonempty string key and SKU and an exact integer quantity from 1 through 20; reject invalid input with ValueError before changing state.
  3. Use (tenant, key) for the ledger identity and (sku, quantity) as the payload fingerprint. Return a copy for an identical replay and raise ValueError for a conflicting replay.
  4. For a fresh operation, reject unknown or insufficient stock with ValueError; otherwise decrement stock and store the result. The initial stock mapping contains nonnegative integer counts.
  5. Keep this a sequential simulation. Document the transaction and unique constraint required in production.

Examples

EXAMPLE 1

Inputstock={'A':10}, tenant='north', key='K', sku='A', quantity=3

Output{'sku':'A','reserved':3,'remaining':7}

Repeating the identical authorized operation leaves stock at seven.
solution.pyPython 3.12