MediumPro challengePython

Middleware Pipeline (compose)

PythonAsyncDesign

Implement compose(middlewares) that chains async middleware functions
(like Koa.js or Starlette). Each middleware receives (req, next) where
next() (a coroutine) calls the following middleware.

solve builds middlewares from a declarative ops list and runs them:

  • {'op': 'set', 'key': ..., 'val': ...} — adds key to req then awaits next().
  • {'op': 'stop'} — marks req['stopped'] = True, does not await next().

Return the final req state after compose(middlewares)(req) resolves.

Sample tests

Test #1Two middlewares both run
Input: [[{"op":"set","key":"auth","val":true},{"op":"set","key":"log","val":1}],{}]
Output: {"log":1,"auth":true}
Test #2stop prevents further middlewares
Input: [[{"op":"set","key":"auth","val":true},{"op":"stop"},{"op":"set","key":"never","val":true}],{}]
Output: {"auth":true,"stopped":true}
Test #3Empty middleware list returns req unchanged
Input: [[],{}]
Output: {}
Test #4Preserves existing req properties
Input: [[{"op":"set","key":"x","val":1}],{"existing":true}]
Output: {"x":1,"existing":true}
Test #5Pass-through middleware defers to next
Input: [[{"op":"pass"},{"op":"set","key":"a","val":42}],{}]
Output: {"a":42}