Add ASGI apps to the HTTP frontend
:robot: Summary
Add ASGI apps as a new kind of web app in the HTTP frontend. Keep Tornado as the outer server in Mopidy 4.x, and mount ASGI apps through a bridge that Mopidy owns. Move Mopidy's own endpoints to an ASGI app behind the same bridge.
Background:
- Research:
docs/research/http-asgi-migration.mdin mopidy/workspace - Decision: ADR 0001 in mopidy/workspace
- Glossary:
CONTEXT.mdin mopidy/workspace - Docs PR: mopidy/workspace#3
- Prototype:
prototype/asgi-bridge
Problem Statement
Extension authors who want to add endpoints to Mopidy's HTTP frontend must write Tornado request handlers. Tornado is part of Mopidy's public extension API through http:app, so authors cannot use the ASGI tools that most Python web code uses today, such as Starlette, FastAPI or Litestar. It also ties Mopidy to Tornado: 63 known extensions register Tornado apps, and 16 of them use Tornado WebSockets. Tornado has no released ASGI support.
Extension authors also have no public way to apply Mopidy's origin and CSRF checks to their own endpoints. Some extensions imported mopidy.http.handlers for this, and that module was removed in Mopidy 4.0.0 (mopidy/mopidy#1966).
Solution
A new registry key, http:asgi, lets an extension register an ASGI app. The HTTP frontend mounts the app at /<name>/ on the same port as everything else. The app sees a normal ASGI environment with HTTP, WebSockets and lifespan events. It does not know that Tornado is the outer server.
Mopidy's own endpoints (JSON-RPC over HTTP, the /mopidy/ws WebSocket and the web client list) become an ASGI app behind the same bridge. Their wire protocol does not change.
Tornado apps (http:app) and static apps (http:static) keep working without change. The docs mark http:app as deprecated. A runtime warning comes in a later 4.x release, and Tornado apps can be removed in Mopidy 5.
Mopidy ships public ASGI middleware for the origin and CSRF checks, configured from the http config section.
User Stories
- As an extension author, I want to register an ASGI app with
http:asgi, so that I can write my web app with Starlette, FastAPI or another ASGI framework. - As an extension author, I want my ASGI app to get
configandcorethrough its factory, so that it has the same access as a Tornado app. - As an extension author, I want my ASGI app mounted at
/<name>/, so that its URLs follow the same pattern as Tornado apps and static apps. - As an extension author, I want
root_pathset to/<name>in the scope, so that my framework builds correct URLs withurl_for. - As an extension author, I want a request to
/<name>to redirect to/<name>/, so that my ASGI app behaves like other web apps. - As an extension author, I want my ASGI app to serve WebSockets, so that I can push live updates to my web client.
- As an extension author, I want to choose a WebSocket subprotocol and add headers when I accept a connection, so that the ASGI WebSocket API works in full.
- As an extension author, I want to reject a WebSocket connection before the handshake, so that the client gets HTTP 403.
- As an extension author, I want WebSocket close codes and reasons to go both ways, so that my client and server can tell why a connection closed.
- As an extension author, I want
send()to wait while a slow client does not read, so that my app does not buffer without limit. - As an extension author, I want large request bodies to arrive in parts, so that uploads do not have to fit in memory.
- As an extension author, I want streamed responses to reach the client in parts, so that I can send long responses.
- As an extension author, I want my app to know when the client disconnects, so that it stops work nobody will read.
- As an extension author, I want lifespan startup and shutdown events, so that I can open and close resources like HTTP clients and background tasks in the usual way.
- As an extension author, I want Mopidy to log the error and skip my app when its lifespan startup fails, so that one broken extension does not stop the HTTP frontend.
- As an extension author, I want Mopidy to log the error and skip my app when its factory fails, so that the behavior matches Tornado apps.
- As an extension author, I want my responses sent exactly as my app wrote them, without extra headers or ETags from Tornado, so that my app behaves the same as under any other ASGI server.
- As an extension author, I want public ASGI middleware for Mopidy's origin and CSRF checks, so that I can protect my endpoints without copying Mopidy code.
- As an extension author, I want that middleware to read
allowed_originsandcsrf_protectionfrom thehttpconfig, so that users configure it in one place. - As an extension author, I want the public
http:asgitype to be a plain ASGI callable, so that I am not tied to Starlette or any other framework. - As an extension author with a Tornado app, I want it to keep working without change in 4.x, so that I can migrate when I am ready.
- As an extension author with a Tornado app, I want the docs to mark
http:appas deprecated and to point to a migration guide, so that I know what to do before Mopidy 5. - As an extension author with a static app, I want
http:staticto keep working without change, now and in Mopidy 5, so that shipping a web client stays simple. - As an extension author, I want a documented example of an ASGI app with an HTTP endpoint, a WebSocket and the Mopidy middleware, so that I can start from working code.
- As a web client author, I want
/mopidy/rpcto accept and return exactly the same JSON-RPC as before, so that my client keeps working. - As a web client author, I want
/mopidy/wsto send the same events and accept the same JSON-RPC messages as before, so that my client keeps working. - As a web client author, I want the same origin, CORS and CSRF rules on Mopidy's own endpoints, so that my client's requests are accepted or rejected as before.
- As a Mopidy user, I want all web apps on the one configured port, so that I do not need to change my firewall or URLs.
- As a Mopidy user, I want
default_appto accept the name of an ASGI app, so that I can make any web client my start page. - As a Mopidy user, I want the web client list page to show ASGI apps next to Tornado apps and static apps, so that I can find all installed web clients.
- As a Mopidy user, I want the HTTP frontend to start and stop as before, so that the change is not visible to me.
- As a Mopidy maintainer, I want Mopidy's own endpoints to use the same bridge as extensions, so that the bridge is tested by the most-used traffic in the ecosystem.
- As a Mopidy maintainer, I want the bridge to be the only code that knows about both Tornado and ASGI, so that replacing the outer server in Mopidy 5 touches only the bridge.
- As a Debian packager, I want the new dependencies to be in Debian stable, so that Mopidy stays packageable.
Implementation Decisions
- Registry key. Add
http:asgiwith the fieldsnameandfactory. The factory takes(config, core)and returns an ASGI app. The public type is a plain ASGI 3 callable. Do not use Starlette types in the public API.http:appkeeps its current Tornado-only type. - Outer server. Tornado stays the outer server in 4.x (ADR 0001). The bridge mounts each ASGI app into the Tornado application at
/<name>, next to the existing rules for Tornado apps and static apps. - Routing. Each mounted ASGI app gets two Tornado rules with a custom matcher on the path prefix. One rule matches WebSocket upgrade requests (the
Upgrade: websocketheader) and goes to the WebSocket bridge handler. The other rule matches all other requests and goes to the HTTP bridge handler. - Scope. Use the current ASGI convention:
pathis the full, percent-decoded path including the prefix,raw_pathis the raw path, androot_pathis/<name>. Setasgi.spec_versionto2.4. The prototype confirmed that current Starlette routing andurl_forwork with this. - HTTP bridge. A Tornado request handler with streamed request bodies. Rules that the prototype showed are necessary:
- Start the ASGI app in
prepare(). Feed body chunks intoreceive()fromdata_received(), and send the last empty chunk withmore_body: Falsefrom the handler method. - Finish the Tornado response only from the handler method, after the app sends its last body part. If the bridge finishes it from
send(), Tornado cancels its body future and resets the keep-alive connection. The app task can run on after the response is finished, for example for Starlette background tasks. - On
http.response.start, clear Tornado's defaultContent-Type,ServerandDateheaders, and turn off Tornado's ETag computation. - For
more_body: True, flush and wait, for backpressure. - On client disconnect, send
http.disconnectto the app. Do not log an error when the app fails because the client is gone, for example with Starlette'sClientDisconnect.
- Start the ASGI app in
- WebSocket bridge. A Tornado WebSocket handler. Rules that the prototype showed are necessary:
- Allow every origin in Tornado. The ASGI app decides, for example with the Mopidy middleware.
- Start the ASGI app before the handshake, send
websocket.connect, and wait for the app's first message. Onwebsocket.accept, use its subprotocol and headers, then let Tornado do the handshake. Onwebsocket.closebefore accept, respond with HTTP 403. - Hold every later
send()until Tornado callsopen(), because Tornado drops frames and close requests before its handshake is done. - Await
write_message()for backpressure. - Map Tornado's close code and reason to
websocket.disconnect. Use 1005 if the client sent no code. - If the app returns without closing, close the connection with code 1000.
- Lifespan. When the HTTP frontend starts, send
lifespan.startupto each ASGI app and wait for the reply before the server accepts connections. Onlifespan.startup.failedor an exception, log the error and do not mount that app. When the HTTP frontend stops, sendlifespan.shutdownand wait for the reply. Accept apps that do not support lifespan, as the ASGI spec says. - Mopidy's own endpoints. Rewrite the JSON-RPC HTTP endpoint, the
/mopidy/wsWebSocket, the web client list page and the redirects as one Starlette app, registered internally the same way as anhttp:asgiapp namedmopidy. The wire protocol, status codes, headers (includingX-Mopidy-VersionandCache-Control), CORS behavior and CSRF behavior do not change. - Event broadcast. Core events reach
/mopidy/wsclients from the actor thread. Schedule the broadcast on the HTTP frontend's event loop in a thread-safe way, as today. - Web client list. The list includes ASGI apps, Tornado apps and static apps. Replace the Tornado template with an equivalent that does not need Tornado.
- Default app.
default_appaccepts the name of any web app, including ASGI apps. - Middleware. Add public ASGI middleware that applies the origin check and CSRF protection from the
httpconfig. Mopidy's own endpoints use it. Its behavior matches the current checks exactly, including the special cases for empty,nullandfile://origins and for same-host origins. - Dependencies. Add Starlette as a dependency of Mopidy. It is in Debian trixie. Tornado stays a dependency in 4.x. Do not add an ASGI server in 4.x.
- Static apps.
http:staticdoes not change. Its served behavior, includingindex.htmlfor directory URLs, cache headers and the redirect from/<name>to/<name>/, does not change. Moving static apps to Starlette'sStaticFilesis allowed but not required in this work. - Deprecation. The docs mark
http:appas deprecated and link to a migration guide. There is no runtime warning in this work. - Docs. Update the HTTP server reference to describe
http:asgifirst, with an example app, the middleware and lifespan. Remove the WSGI example, which does not run.
Testing Decisions
- Test only external behavior through one seam: the HTTP frontend's server, built from config, a core mock and registry entries (
http:app,http:static,http:asgi), served on an unused port with the existingtornado_serverfixture, and tested with real HTTP and WebSocket clients. Do not test the bridge handler classes directly. - The existing HTTP frontend tests are the wire-compatibility guarantee for Mopidy's own endpoints. That includes the server, handler and JSON-RPC tests. Their assertions must not change. Only their fixture setup may change, for example to build the server through the new code.
- New tests use small ASGI test apps, registered with
http:asgi, that cover:- routing,
root_path,url_forand percent-decoded paths - the redirect from
/<name>to/<name>/ - no Tornado default headers and no ETag
- request bodies in parts, including chunked uploads
- streamed responses and client disconnect
- WebSocket accept with subprotocol and headers, reject with 403, close codes in both directions, text and binary messages, and backpressure
- lifespan startup and shutdown, and a failed startup that skips only that app
- a failing factory that skips only that app
default_appset to an ASGI app, and ASGI apps on the web client list- the public middleware, for allowed and blocked origins and for the CSRF content-type rule
- Tornado apps and ASGI apps on the same port at the same time
- routing,
- Prior art: the
tornado_serverfixture, the static and WebSocket tests in the handler tests, the origin tests, and the checks in the prototype branch.
Out of Scope
- Removing Tornado or
http:app. That is for Mopidy 5. - A runtime deprecation warning for
http:app. That comes in a later 4.x release. - Choosing or adding the Mopidy 5 outer server. uvicorn is the most likely choice.
- Using
awaiton core calls. Pykka's planned async support changesawaiton a future into a real non-blocking await, intended only for callers on an event loop. It is no longer another way to call.get(). Until that Pykka release, Mopidy's own endpoints, the docs and the example app use sync endpoints, or run.get()in a thread. A follow-up, blocked by the Pykka release, requires the new Pykka version and moves Mopidy's JSON-RPC,/mopidy/ws, the docs and the example app toawait. - A public replacement for the removed
mopidy.http.handlersbeyond the origin and CSRF middleware. - Migrating any third-party extension.
- Running Mopidy's HTTP API under an external ASGI server.
- WSGI support.
Further Notes
- The prototype on the
prototype/asgi-bridgebranch passes 17 checks with Tornado 6.5 and current Starlette, and is the best reference for the bridge's edge cases. It is throwaway code. Do not copy it without tests. - Not tested in the prototype: HEAD requests, HTTPS, apps that respond before the whole request body has arrived, and load.
Source: mopidy/mopidy