Skip to content

Latest commit

 

History

History

Inventory API

README.md

Stockroom: repair a MongoDB inventory API

What you should know

Mode: Debugging.

Python 3.11, PyMongo 4.11.3, and MongoDB 8.0.


Scenario

Stockroom is a private inventory API. Operators see successful creates disappear, stale update responses and cross-account access. Repair the Python service while retaining the real MongoDB persistence layer.


Files

Edit service.py and REFLECTION.essay. Keep the public names, signatures and fixed files unchanged. You may add helper modules and your own regression tests. The fixed model.py, HTTP adapter and application can be inspected.


Public API

InventoryService(collection)
InventoryService.handle(method, path, user, body=None) -> Response

collection is an initialized PyMongo collection. handle accepts a parsed body: a dictionary for valid create/update requests. Invalid shapes return the documented error. Response.status is an integer; Response.body is an item dictionary, a list of item dictionaries, an error dictionary, or None for deletion. Returned quantity and version values are Python integers.

Numeric inputs may be int, finite integral float, or exact integral decimal.Decimal, within their bounds. Strings, booleans and None are never numbers. The fixed HTTP parser preserves fractional JSON numbers as Decimal, so a value such as 3.0000000000000001 cannot silently round into a valid integer. The supplied helpers implement ECMAScript whitespace and UTF-16 length rules.


Requirements

1. Runtime and database

  • Use the pinned driver and an actual MongoDB server. Do not replace persistence with an in-memory collection.
  • initialize_items creates the collection's validation rules and unique index before returning it. Pass that initialized collection into the service.
  • Set MONGODB_URI if the server is not at mongodb://127.0.0.1:27017.
  • Tests create unique stockroom_test_* databases and drop only those databases, even if the URI contains a database name.
  • The demo application uses stockroom_local by default. MONGODB_DATABASE changes the demo database; PORT changes its default port, 8080. No credentials or .env are supplied.

2. Identity and routing

  • First require a nonblank string user, otherwise return 401 unauthorized. Preserve the user's value exactly, including surrounding spaces.
  • Routes are /items and /items/{id}. Unknown paths return 404 not_found.
  • An item ID must be exactly 24 hexadecimal characters, otherwise return 400 invalid_id. Accept either letter case; returned IDs are lowercase.
  • Unsupported methods on valid paths return 405 method_not_allowed. Validate identity, route and ID in that order before dispatching a method.
  • Every error body is a dictionary containing exactly {"error": code}.

3. Create an item

  • POST /items requires exactly {sku, name, quantity}.
  • sku is a case-sensitive string consisting of 1 to 24 uppercase ASCII letters, digits or hyphens.
  • name is a string with trimmed length 1 to 80 UTF-16 code units. Use the supplied trim rules for names and blank-identity checks. Store the trimmed name.
  • quantity is an integer number from 0 through 1000000. Reject invalid values with 400 invalid_input.
  • Persist before returning 201 with exactly {id, owner, sku, name, quantity, version}. Generate the ObjectId, preserve the authenticated owner and set version to 1. Do not accept caller-supplied owner, id or version.

4. Read and delete items

  • GET /items returns 200 and this user's documents sorted by sku ascending, then id ascending. An empty list is valid.
  • GET /items/{id} returns 200 and one document.
  • Missing items and items owned by another user both return 404 item_not_found.
  • DELETE /items/{id} deletes only the owned item and returns Response(204, None). Repeating the deletion returns 404.

5. Update an item

  • PATCH /items/{id} requires an integer version from 1 through 9223372036854775806 and at least one of name or quantity. No other fields are allowed. The upper bound leaves room for the increment.
  • Validate the entire payload, including quantity bounds and trimmed name length, before looking up the owned item. Invalid input returns 400 invalid_input; a missing or foreign item returns 404 item_not_found; a version mismatch returns 409 version_conflict.
  • Atomically update the matching owner, ID and version. Return 200 and the updated document, with version incremented by one even when the supplied values are unchanged.
  • Never change owner, sku or id. Every failed update leaves all fields and the version unchanged.
  • Concurrent valid patches using one version allow exactly one success, including requests handled by separate service instances. Concurrent deletion during a patch is outside the exercise's workload.

6. Uniqueness and storage errors

  • The fixed compound unique index enforces (owner, sku). A duplicate creation returns 409 sku_conflict without adding a document, including concurrent calls. Another owner may use the same sku.
  • Database duplicate-key errors use code 11000. Schema validation errors use code 121 and map to 400 invalid_input. Unexpected storage errors map to 503 storage_unavailable.
  • Return JSON-serializable values and do not expose exception details.

7. HTTP adapter and fixed files

  • The supplied server reads X-User-ID, parses JSON and delegates to handle. Malformed JSON returns 400 invalid_json; query strings do not affect routing.
  • A 204 response has an empty body. The server binds to the container interfaces so the IDE can forward its port.
  • The model, server transport, public tests, Python dependency configuration and setup scripts are fixed. Implement the repair in the service and any helpers you add.

Implementation checklist

  1. Authenticate requests and validate payloads.
  2. Persist new documents and return database query results.
  3. Scope reads, updates and deletes to the owner.
  4. Apply version checks and increments in the same database operation.
  5. Map storage errors and verify the HTTP responses.

Estimated completion time

75 minutes, including investigation, implementation, regression testing and the reflection answers.


Running locally

Click Run in the IDE to run the public tests. The starter imports successfully but some public tests fail intentionally. After changes, check the test results as well as whether the server starts. Public tests cover part of the contract; implement every requirement above. Tests use temporary databases and time limits.

MongoDB 8.0 runs in the environment at mongodb://127.0.0.1:27017. Fill in each question's answer field in REFLECTION.essay; discuss the proposed extensions without implementing them.

Optional: run the server yourself

Run does not start the demo server, and the tests do not need it.

# Start the demo server:
bash .theia/run_app.sh

Example

With a correctly implemented service and an initialized collection:

created = service.handle(
    "POST", "/items", "alice", {"sku": "BOOK-1", "name": "Book", "quantity": 3}
)
assert created.status == 201
item = created.body
assert item["owner"] == "alice"
assert item["quantity"] == 3
assert item["version"] == 1
assert service.handle("GET", "/items/" + item["id"], "alice").body == item