File transfers on the web¶
This page explains how the web backend receives uploads and sends downloads. It also covers how the Open and Save actions transfer a study file. For request order and session lifetime, see Order and sessions.
Uploads and Open¶
Uploads.
widget_filereads the multipart body itself (uploads.py), not through Starlette’s form parser, whose spooled file a route can only copy. The body goes to a scratch file with no lock held, andWebSession.pick_filemoves that file. A file over the limit keeps being read, to answer in a notification, but stops going to the disk. Open still reads through Starlette: a study is small. A replaced upload stays untiljobs.is_runningis false: nothing says which file a job reads, and a job may not have opened it yet. Holding a file through the app’s code would bring the same failure back each time an app forgets.Several files at once. The receiver writes each file part to its own scratch file. It keeps what a chunk brings by part, because one chunk can end a file and start the next one.
max_upload_sizecounts the bytes of all the parts.WebSession.pick_filesgives several files only to aFileUploadViewwithmultiple; any other widget refuses them (400), as its page never sends them. Amultipleview gets one file this way too, so its names do not depend on how many files came. The files keep their own names when every system can hold them (_own_name), because a file can name another one. Two names that one folder cannot hold apart (case, or composed and decomposed accents) refuse the choice. The files go to a new folder, which the field holds only once all of them are there. A move that fails removes that folder, and the field keeps its previous files.An upload in the app’s folder. With
upload_folder,_keep_in_foldertakes the name first with an empty file opened exclusively, so two sessions never share it. A name that a table’s cell holds counts as taken, even with its file gone: the same text would reach the cell, and no edit would say that the file changed. The file is written beside the name, then replaces it. The session never tracks the file. It deletes it only when no cell holds its path at the end of the edit, since the app would never learn of it. A path withserver_rootsrefuses any upload, because its page sends none and a crafted one would write in that folder.A long upload and the order. A file’s post takes its turn (
order.py) once its whole body has arrived, so a later post runs first afterORDER_TIMEOUT. Waiting for the upload would hold every click for as long as the network takes. Sopage.jsmarks only the upload’s own button, and the docs say that a click does not wait.Open applies an upload to a scratch instance first (core’s
load_state_data), so a bad file never half-loads. Responses sendCache-Control: no-storeand controls setautocomplete="off", so a reload always shows the server’s state.Open over unsaved changes. The browser’s picker sends the file at once, so the question comes after the upload:
WebSession.load_statekeeps the file’s bytes in the dialog’s pending call (at mostMAX_STATE_SIZE) until the answer, a post of its own. A second upload replaces them. A session that asks doesn’t hibernate (an open dialog), so the bytes never need saving. A file of another type, or too large, is refused before the question.Save and download a study. The Save form sends
POST /_composeui/state/downloadwithout htmx. The response contains the study file, and the session marks the study as saved.GET /_composeui/statedownloads the study without marking it as saved. A link can request the file without an explicit Save action, and the user may never get the file.
Downloads on the web¶
Unlike the Save form, DownloadView sends its POST through htmx, which reads the response
for page updates. The POST does not return the file. Instead, the session gives the browser
a link with a ticket. The browser follows the link to receive the file.
Download steps¶
The diagram shows the default path, where content runs during the POST.
A click on a
DownloadViewsends an htmx POST.prepare, if set, runs first, during the POST. By default,contentruns during the POST too. Within_job, the POST starts a job that runscontent. In both cases,MainView.downloadpasses the result toWebMainRenderer.download. The app can also callMainView.downloaddirectly.The session keeps the file under a ticket: 128 random bits (
webcore/downloads.py).Event responses, the jobs poll, and the full page list tickets not yet fetched.
downloads_markeradds a link per ticket in#cui-downloads.page.jsfollows each ticket’s link once (startDownloads):GET /_composeui/download/{ticket}.The GET serves the bytes or file on disk. For a
StreamContent, it runswriteinstead. The GET does not callcontent.
Ticket lifetime and limits¶
State |
Request |
Expiration |
Limit exceeded |
Session ends |
|---|---|---|---|---|
Bytes or a path, not fetched |
The first GET or HEAD serves the file or its headers and marks the ticket as fetched. |
10 minutes after creation ( |
Drop the oldest ticket. |
Drop the ticket. |
Bytes or a path, fetched |
A GET or HEAD can use the ticket again until it expires. |
1 minute after the first fetch ( |
Drop the oldest ticket. |
Drop the ticket. |
Stream, not claimed |
The first GET claims the ticket and removes it. A HEAD returns headers without claiming the ticket. |
10 minutes after creation ( |
Drop the oldest ticket. |
Drop the ticket. |
Stream, claimed |
Another GET or HEAD returns 404. |
No ticket remains. |
No ticket remains. |
Cancel the writer. |
A stream’s HEAD response has no Content-Length.
The store checks expiration when it adds, looks up, or lists tickets.
Listed until fetched. A response can be lost, for example when the browser reloads the page. The next response with a download marker lists the ticket again if the browser has not fetched it.
page.jsremembers which links it already followed.Available after the first fetch. A browser’s download manager may send a second request for a file or its headers. The first fetch starts the shorter timeout. Later fetches do not extend it.
Limits. Each session keeps at most
MAX_DOWNLOADStickets, including those for aPathor aStreamContent.MAX_DOWNLOAD_BYTESlimits only the bytes kept in memory. Dropping a ticket for aPathdoes not delete the file.Missing file or session. The GET returns 404, not a redirect, so the browser does not save a page as the file. The link’s
downloadattribute keeps the current page open.
Streaming¶
The app creates a StreamContent during the POST, in a job, or in its own code. If the writer
needs data from a view, read it before passing the StreamContent to MainView.download.
The download uses a ticket, like a file on disk. During the GET, webcore/streaming.py runs
write, which uses the data the app captured.
The writer must not read views. ComposeUI does not enforce this rule. It is part of the
StreamContentcontract. A generator would not read the views when created. It would run when the GET reads its pieces, so the values in one file could come from before and after an edit.Session and ticket. A request must have both the session and its valid ticket to start the writer.
Once. The first GET takes the ticket (
Downloads.take): a writer can’t run twice, and a second fetch answers 404. AHEADdoesn’t take it.A thread of its own.
writeruns on a daemon thread. A long export would otherwise take one of the 40 threads that synchronous routes share in AnyIO’s pool. The stream does not hold the session’s lock while the writer runs.Backpressure.
DownloadSinkgathers the writes into pieces of 256 KiB (DOWNLOAD_CHUNK_SIZE), and cuts larger ones. The writer waits on athreading.Conditionwhile 1 MiB (MAX_QUEUED_BYTES) waits to be sent. The answer reads the pieces on the event loop, woken bycall_soon_threadsafe: it never blocks the loop. uvicorn waits for the socket to drain, so a slow browser slows the writer.Cancel. A browser that leaves, or the session’s end (
WebSession.close, throughstreaming), cancels the stream: the writer’s next write raisesDownloadCanceledError, and every one after. The answer then waits for the thread before it frees the session and its place, whatever cancels it meanwhile (Stream.ended): an anyio shield stops anyio’s cancels, not asyncio’stask.cancel, which uvicorn and thenasyncio.runsend as the server stops. A writer that doesn’t write for a while holds them that long.A server that stops. uvicorn’s graceful shutdown waits for the open answers before the lifespan closes the sessions, and tells the app nothing. So
rungives uvicornWebSettings.shutdown_timeoutastimeout_graceful_shutdown, which the processes of a--reloadserver get too. Past it, uvicorn cancels the answers, and theirfinallycancels the streams. A writer that doesn’t write still holds the stop until its next write.Errors. The answer waits for the first piece before it sends its headers. A writer that fails before it gets a 500, and the error is logged. One that fails after it raises
StreamFailedError, which breaks the connection: the browser shows a failed download, not a short file.Limits. At most
WebSettings.max_download_streamsstreams run at once on the server, andmax_session_download_streamsfor one session (StreamPlaces, AnyIOCapacityLimiters); the next wait. A stream takes its session’s place first: one that waits for it holds none of the server’s, so one browser that reads slowly can’t take them all. A client that opens many sessions still can, as formax_sessions. The waiting answer notices a browser that left only at its first piece.Held. The answer holds the session (
held): it isn’t saved to disk, and doesn’t expire, while the file is sent. A session is idle from its last request’s end (_Entry.is_expired). The GET takes the ticket before its answer holds the session. The lookup of the GET counts as a request, so only asession_idleshorter than that gap could save the session meanwhile; the stream would then answer 404.Not compressed.
GZipMiddlewarewould compress each piece on the event loop. The app’s downloads (/_composeui/download/) skip it, the bytes and the files too.
Why use POST and GET¶
The POST handles the click. SameOriginMiddleware checks its origin, and PostOrder waits
for earlier numbered POSTs, up to ORDER_TIMEOUT. A GET triggered by a click would not have
either check by default. A top-level GET from another site can carry the session cookie
(SameSite=Lax). It must not run a callback that changes the app, such as marking a study
as exported. An unnumbered GET could also run before a field edit that the page just sent.
The numbered Save form also waits up to ORDER_TIMEOUT for earlier POSTs. If the wait times
out, Save can continue before a missing POST arrives.
A ticket also lets a job or a direct call to MainView.download deliver a file when there is
no click response to carry it. The browser fetches all three kinds of download in the same way.
Letting a click stream directly from a GET would need separate checks and would still need tickets for jobs and direct downloads. That alternative would require:
The origin check used for POSTs (
is_same_origin).A request number in the same sequence as the page’s POSTs.
No HEAD or prefetch (
Sec-Purpose), and a<button>rather than a prefetchable link.The
takes_eventscheck.A lock on the session for each read, as in
table_csv.A connection that closes if the writer fails after sending part of the file.
This would save one round trip only for clicks without in_job. Locking each read separately
would still allow the writer to read view values from before and after an edit.
Pages opened in a new tab¶
MainView.open_url reaches the page the way a download does. A job or a callback can open a
URL when no click response carries it, and a response can be lost.
WebMainRenderer.open_urlkeeps the URL in the session’s downloads, as anOpenedUrl, under a ticket of its own. It counts inMAX_DOWNLOADS, and keeps a session in memory until the page fetches it, as a file does.downloads_markeradds a link per URL in#cui-downloads:/_composeui/open/{ticket}, hidden, withtarget="_blank"and the URL as its text.page.jsopens a blank tab once per ticket, sets itsopenertonull, then sends it to the link. The URL’s page can’t reach the app’s page throughwindow.opener.GET /_composeui/open/{ticket}marks the ticket as fetched and answers a redirect (303) to the URL. A ticket of another session, or a file’s ticket, gives 404, as a URL’s ticket does on the download route. Each route takes only its own kind (Downloads.take,Downloads.take_url): a ticket of the other kind stays as it was, still listed.
The redirect sends the tab only to a URL that the app’s code gave: a link of another site
can’t choose the URL. MainView.open_url takes only http and https URLs. Not mailto:
its new tab would stay blank once the mail app opens.
A browser can refuse a tab that no click opened, as after a job: window.open then returns
null. The page shows the ticket’s link, in a toast, for the user to click. A click opens the
tab, so page.js hides the link again. The next responses no longer list the ticket.