Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
import asyncio
import inspect
import logging
import re
from collections.abc import Awaitable, Callable
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, Request
from fastapi.exception_handlers import http_exception_handler
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_redoc_html, get_swagger_ui_html
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.security.utils import get_authorization_scheme_param
from fastapi_events.handlers.local import local_handler
from fastapi_events.middleware import EventHandlerASGIMiddleware
from starlette.concurrency import run_in_threadpool
from starlette.datastructures import Headers
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.middleware.gzip import GZipMiddleware
from starlette.types import ASGIApp, Message, Receive, Scope, Send
import invokeai.frontend.webv2 as webv2_dir
from invokeai.app.api.dependencies import ApiDependencies
from invokeai.app.api.frontend import mount_frontend
from invokeai.app.api.routers import (
app_info,
auth,
board_images,
boards,
client_state,
custom_nodes,
files,
fonts,
gallery,
gallery_maintenance,
image_map,
image_moves,
images,
intermediates,
model_manager,
model_relationships,
projects,
recall_parameters,
session_queue,
style_presets,
system_prompts,
utilities,
video_recall,
videos,
virtual_boards,
wildcards,
workflows,
working_memory,
)
from invokeai.app.api.sockets import SocketIO
from invokeai.app.services.config.config_default import get_config
from invokeai.app.services.shared.database.errors import TransientDatabaseError
from invokeai.app.util.custom_openapi import get_openapi_func
from invokeai.backend.util.logging import InvokeAILogger
from invokeai.frontend.cli.arg_parser import InvokeAIArgs
app_config = get_config()
logger = InvokeAILogger.get_logger(config=app_config)
loop = asyncio.new_event_loop()
@asynccontextmanager
async def lifespan(app: FastAPI):
# Add startup event to load dependencies
ApiDependencies.initialize(config=app_config, event_handler_id=event_handler_id, loop=loop, logger=logger)
# Log the server address when it starts - in case the network log level is not high enough to see the startup log
proto = "https" if app_config.ssl_certfile else "http"
msg = f"Invoke running on {proto}://{app_config.host}:{app_config.port} (Press CTRL+C to quit)"
# Logging this way ignores the logger's log level and _always_ logs the message
record = logger.makeRecord(
name=logger.name,
level=logging.INFO,
fn="",
lno=0,
msg=msg,
args=(),
exc_info=None,
)
logger.handle(record)
# Re-derive open sockets' authorization from the database on a timer. This is what
# catches user changes made by another process — the `invoke-usermod` / `invoke-userdel`
# CLIs — which cannot raise an in-process event. `socket_io` is created further down
# this module and is bound by the time the app is served.
socket_io.start()
try:
yield
finally:
# In a `finally` so an exception propagating into the generator cannot leave the
# sweep running against a half-torn-down process, or skip the thread shutdown.
socket_io.stop()
# Shut down threads
ApiDependencies.shutdown()
# Create the app
# TODO: create this all in a method so configuration/etc. can be passed in?
app = FastAPI(
title="Invoke - Community Edition",
docs_url=None,
redoc_url=None,
separate_input_output_schemas=False,
lifespan=lifespan,
)
@app.exception_handler(TransientDatabaseError)
async def database_busy(request: Request, error: TransientDatabaseError) -> JSONResponse:
return _database_busy(request, error)
@app.exception_handler(StarletteHTTPException)
async def http_error(request: Request, error: StarletteHTTPException) -> Response:
# Many routes answer every exception with an error of their own ("not found", "unexpected error"); one raised
# while handling a busy database still means the database is busy.
transient = _transient_cause(error)
if transient is not None:
return _database_busy(request, transient)
return await http_exception_handler(request, error)
def _database_busy(request: Request, error: TransientDatabaseError) -> JSONResponse:
# A lock held too long elsewhere, a race the call lost on every attempt, a server out of reach: the same
# request can succeed in a moment, so it is a busy server rather than a failed request.
logger.warning(f"{request.method} {request.url.path}: the database is busy: {error}")
return JSONResponse(
status_code=503, content={"detail": "The database is busy; try again"}, headers={"Retry-After": "1"}
)
def _transient_cause(error: BaseException) -> Optional[TransientDatabaseError]:
"""The busy database an exception was raised while handling, if any."""
seen: set[int] = set()
cause: Optional[BaseException] = error.__cause__ or error.__context__
while cause is not None and id(cause) not in seen:
if isinstance(cause, TransientDatabaseError):
return cause
seen.add(id(cause))
cause = cause.__cause__ or cause.__context__
return None
class SlidingWindowTokenMiddleware(BaseHTTPMiddleware):
"""Refresh the JWT token on each authenticated response.
When a request includes a valid Bearer token, the response includes a
X-Refreshed-Token header with a new token that has a fresh expiry.
This implements sliding-window session expiry: the session only expires
after a period of *inactivity*, not a fixed time after login.
"""
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
response = await call_next(request)
# Only refresh on mutating requests (POST/PUT/PATCH/DELETE) — these indicate
# genuine user activity. GET requests are often background fetches (RTK Query
# cache revalidation, refetch-on-focus, etc.) and should not reset the
# inactivity timer.
# Behind a sub-path proxy the public path carries the prefix (see SubPathASGIMiddleware),
# so strip `root_path` before matching the auth-route exclusions — otherwise a proxied
# logout would mint a replacement token/cookie right after the route deleted them.
route_path = request.url.path.removeprefix(request.scope.get("root_path", ""))
if (
response.status_code < 400
and request.method in ("POST", "PUT", "PATCH", "DELETE")
and route_path not in ("/api/v1/auth/login", "/api/v1/auth/logout", "/api/v1/auth/media-cookie")
):
auth_header = request.headers.get("authorization", "")
if auth_header.startswith("Bearer "):
token = auth_header[7:]
try:
from datetime import timedelta
from invokeai.app.api.routers.auth import (
TOKEN_EXPIRATION_NORMAL,
TOKEN_EXPIRATION_REMEMBER_ME,
)
from invokeai.app.services.auth.token_service import TokenData, create_access_token, verify_token
token_data = verify_token(token)
if token_data is not None:
# Decide through `resolve_authorized_user` rather than re-deriving
# "is this token still honored" here. This middleware used to carry
# its own copy of the exists/active/epoch checks, and a copy is how
# a rule added later — the refusal of the internal `system` id —
# reaches every other entry point but not this one, leaving a token
# nothing will accept being renewed indefinitely anyway.
#
# Never refresh a token that is no longer honored. This runs after
# the route, so an authenticated route has already rejected it — but
# an unauthenticated route returning 2xx with a stale Bearer header
# still reaches here, and minting from the current record would
# launder a revoked token into a valid one.
#
# The lookup inside is a synchronous SQLite query behind a
# process-wide lock; run it off the event loop so a contended lock
# (e.g. generation-result writes) can't stall every concurrent
# request from inside this per-mutation middleware.
from invokeai.app.api.auth_dependencies import resolve_authorized_user
user = await run_in_threadpool(resolve_authorized_user, token_data)
if user is None:
return response
# Mint the replacement from the *database* record, not the old
# token's claims: otherwise a demoted administrator's stale is_admin
# claim (and the media cookie carrying it) would be renewed
# indefinitely by their own mutations.
# Use the remember_me claim from the token to determine the
# correct refresh duration. This avoids the bug where a 7-day
# token with <24h remaining would be silently downgraded to 1 day.
if token_data.remember_me:
expires_delta = timedelta(days=TOKEN_EXPIRATION_REMEMBER_ME)
else:
expires_delta = timedelta(days=TOKEN_EXPIRATION_NORMAL)
refreshed_data = TokenData(
user_id=user.user_id,
email=user.email,
is_admin=user.is_admin,
remember_me=token_data.remember_me,
token_epoch=user.token_epoch,
)
new_token = create_access_token(refreshed_data, expires_delta)
response.headers["X-Refreshed-Token"] = new_token
except Exception:
pass # Don't fail the request if token refresh fails
return response
# Response types worth compressing. Everything else is passed through untouched.
#
# This is an allowlist rather than a blocklist of media types on purpose: a type missing from
# this list only loses compression it would barely have benefited from, whereas a binary type
# missing from a blocklist costs real CPU on the event loop. The app serves a small, known set
# of compressible things — the UI bundle, the API's JSON, SVG icons.
COMPRESSIBLE_CONTENT_TYPES = (
"text/",
"application/json",
"application/javascript",
"application/xml",
"application/xhtml+xml",
"application/manifest+json",
"image/svg+xml",
)
# `text/` would otherwise match this, and compressing an event stream defeats its purpose by
# withholding events until the compressor flushes. Starlette excludes it by default too.
UNCOMPRESSIBLE_CONTENT_TYPES = ("text/event-stream",)
def _is_compressible(content_type: str) -> bool:
if content_type.startswith(UNCOMPRESSIBLE_CONTENT_TYPES):
return False
return content_type.startswith(COMPRESSIBLE_CONTENT_TYPES)
class ContentTypeAwareGZipMiddleware:
"""GZip, but only for content types that actually compress.
Older Starlette releases compress every response type except `text/event-stream`, and even
newer ones only skip a fixed list of media types. The gallery serves PNG, WebP and MP4 bytes,
which are already compressed: a 3 MB PNG costs ~52ms of event-loop time to gzip and comes
back *larger* than it went in. With auto-switch enabled the UI fetches the full image after
every generated image, so that cost lands repeatedly during a batch — exactly when the
server can least afford to stall.
Each response is routed when it starts: compressible ones through Starlette's GZipMiddleware,
everything else straight to the server. Only the middleware's public ASGI interface is used,
because FastAPI leaves Starlette unbounded above and the responder's internals change between
releases — Starlette 1.8 began forwarding `http.response.start` for its own excluded types
inside the responder, so patching its exclusion flag afterwards dropped the start message.
Lowering `compresslevel` does not help here: on incompressible input, level 1 costs
essentially the same as level 9 because deflate still has to scan the data. It does help a
great deal on the compressible path — see `configure_gzip`.
"""
def __init__(self, app: ASGIApp, minimum_size: int, compresslevel: int) -> None:
self.app = app
self.minimum_size = minimum_size
self.compresslevel = compresslevel
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
async def route_by_content_type(scope: Scope, receive: Receive, gzip_send: Send) -> None:
target = send
async def routed_send(message: Message) -> None:
nonlocal target
if message["type"] == "http.response.start":
content_type = Headers(raw=message.get("headers", [])).get("content-type", "")
target = gzip_send if _is_compressible(content_type) else send
await target(message)
await self.app(scope, receive, routed_send)
gzip = GZipMiddleware(route_by_content_type, minimum_size=self.minimum_size, compresslevel=self.compresslevel)
await gzip(scope, receive, send)
# Responses below this are not worth a compression pass; the gzip framing alone is ~20 bytes.
GZIP_MINIMUM_SIZE = 1000
def configure_gzip(app: FastAPI, compresslevel: int) -> None:
"""Install response compression, unless it is turned off.
Body chunks under 128 KiB are compressed on the event loop (Starlette moves larger ones to a
worker thread), so the cost is not paid by the requesting client alone — it stalls every other
request and every socket.io event for its duration, and offloaded chunks still compete for CPU.
That makes the level a real trade-off rather than a free win.
Measured on the flat name list of a 200k-image library (8.48 MB of JSON): level 1 takes
16.4ms and returns 6.1% of the input, level 9 takes 90.2ms and returns 5.7%. Level 9 costs
5.5x the compression time for 0.4 percentage points of bandwidth, which is a poor deal for a
locally-served app. The default stays at 9 so behavior is unchanged for existing installs;
users who feel the stall on a large library can lower it.
A `compresslevel` of 0 means "no compression". The middleware is then left out entirely
rather than installed at level 0, so responses skip the responder altogether instead of
being buffered and re-emitted as a stored-only gzip stream. Deployments behind a proxy that
already compresses (nginx, Caddy) want this, both to avoid the duplicated work and because
the proxy can compress off the event loop.
"""
if compresslevel <= 0:
return
app.add_middleware(ContentTypeAwareGZipMiddleware, minimum_size=GZIP_MINIMUM_SIZE, compresslevel=compresslevel)
class RedirectRootWithQueryStringMiddleware(BaseHTTPMiddleware):
"""When a request is made to the root path with a query string, redirect to the root path without the query string.
For example, to force a Gradio app to use dark mode, users may append `?__theme=dark` to the URL. Their browser may
have this query string saved in history or a bookmark, so when the user navigates to `http://127.0.0.1:9090/`, the
browser takes them to `http://127.0.0.1:9090/?__theme=dark`.
This breaks the static file serving in the UI, so we redirect the user to the root path without the query string.
"""
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
# Be root_path-aware: behind a sub-path proxy, `scope["path"]` retains the public prefix
# (see SubPathASGIMiddleware), so the app root is `<root_path>/`, not just `/`.
root_path = request.scope.get("root_path", "")
if request.url.path in ("/", root_path + "/") and request.url.query:
return RedirectResponse(url=root_path + "/")
response = await call_next(request)
return response
def _identify_video_upload_user(scope: Scope) -> tuple[bool, str | None]:
"""Identify the uploader for auth and per-user slot accounting.
Returns (authenticated, per_user_key). In single-user mode there is only one
tenant, so per_user_key is None — the whole global capacity is theirs and no
per-user quota applies.
"""
if not ApiDependencies.invoker.services.configuration.multiuser:
return True, None
scheme, token = get_authorization_scheme_param(Headers(scope=scope).get("authorization"))
if scheme.lower() != "bearer":
return False, None
from invokeai.app.services.auth.token_service import verify_token
token_data = verify_token(token)
if token_data is None:
return False, None
from invokeai.app.api.auth_dependencies import resolve_authorized_user
if resolve_authorized_user(token_data) is None:
return False, None
return True, token_data.user_id
async def _identify_video_upload_user_async(scope: Scope) -> tuple[bool, str | None]:
return await run_in_threadpool(_identify_video_upload_user, scope)
class RequestBodyLimitASGIMiddleware:
"""Bound selected request bodies before framework parsing and buffering.
Rejects oversized requests from the Content-Length header, aborts chunked bodies that
exceed the cap mid-stream, and bounds concurrent requests both globally and per user
(so one tenant's slow uploads cannot starve the others into 429s).
It also asks the server to close the connection on any response sent before the request
body has been read to completion. The leases below are released as soon as the app
returns, and routes answer plenty of requests without reading the body (a forbidden
board, an unsupported filename) — FastAPI's own query-param validation answers 422
before the route body runs at all. A client that kept streaming after such a response
would hold ingress with no slot charged against it, outside the 429 bound, the idle
timeout and the duration cap; closing ends that upload along with the response.
Whether the body was read is the only thing that can be known here, so any early answer
closes — including when the client had in fact already finished sending. That costs a
fresh connection per rejected request, which is the conservative side to err on and is
what servers generally do when a response is sent without consuming the body.
Two limits worth knowing. Draining the body instead would also close the hole, but it
would pin one of the very few slots for the whole duration cap per rejection, which is a
cheaper denial of service than the hole it closes. And behind a reverse proxy that
buffers request bodies (nginx's default, per the multi-user admin guide) `Connection`
is hop-by-hop, so this only closes the proxy-to-app hop — there the proxy has already
absorbed the whole body before the app is invoked, so the hole does not arise. Responses
generated above this middleware (Starlette's ServerErrorMiddleware 500) do not pass
through it; uvicorn closes the transport on those itself.
"""
def __init__(
self,
app: ASGIApp,
matches_request: Callable[[str, str], bool],
too_large_detail: Callable[[int, int], str | dict[str, object]],
capacity_refusal_detail: Callable[[bool], str | dict[str, object]],
max_body_bytes: int,
max_concurrent: int,
max_concurrent_per_user: int | None = None,
identify_user: Callable[[Scope], tuple[bool, str | None] | Awaitable[tuple[bool, str | None]]] | None = None,
idle_timeout_seconds: float = 120.0,
max_upload_duration_seconds: float = 30 * 60,
retry_after_seconds: int = 5,
) -> None:
self.app = app
self.matches_request = matches_request
self.too_large_detail = too_large_detail
self.capacity_refusal_detail = capacity_refusal_detail
self.max_body_bytes = max_body_bytes
self.max_concurrent = max_concurrent
self.max_concurrent_per_user = max_concurrent_per_user
self.identify_user = identify_user
self.idle_timeout_seconds = idle_timeout_seconds
self.max_upload_duration_seconds = max_upload_duration_seconds
self.retry_after_seconds = retry_after_seconds
self._active = 0
self._active_by_user: dict[str, int] = {}
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
return await self.app(scope, receive, send)
# Behind a sub-path proxy the public path carries the prefix (see SubPathASGIMiddleware).
route_path: str = scope.get("path", "").removeprefix(scope.get("root_path", ""))
# Starlette matches routes with `^...$`, and `$` also matches before a final newline, so a
# request for `/upload%0A` reaches the `/upload` route. Test both spellings: the newline may
# be the route's terminator (`/upload\n`) or a path parameter's only character
# (`/projects/\n`), and either way the request must not reach the route unbounded.
method = scope.get("method", "")
if not (
self.matches_request(method, route_path) or self.matches_request(method, route_path.removesuffix("\n"))
):
return await self.app(scope, receive, send)
# `connection` is a hop-by-hop header and illegal in HTTP/2+, so every use below is
# gated on HTTP/1.
is_http1 = str(scope.get("http_version", "1.1")).startswith("1.")
close_header = {"connection": "close"} if is_http1 else {}
per_user_key: str | None = None
if self.identify_user is not None:
identity = self.identify_user(scope)
if inspect.isawaitable(identity):
identity = await identity
authenticated, per_user_key = identity
if not authenticated:
response = JSONResponse(
{"detail": "Authentication required"},
status_code=401,
headers={"WWW-Authenticate": "Bearer", **close_header},
)
return await response(scope, receive, send)
content_length = Headers(scope=scope).get("content-length")
content_length_bytes = int(content_length) if content_length is not None and content_length.isdigit() else None
if content_length_bytes is not None and content_length_bytes > self.max_body_bytes:
response = JSONResponse(
{"detail": self.too_large_detail(content_length_bytes, self.max_body_bytes)},
status_code=413,
headers=close_header,
)
return await response(scope, receive, send)
def has_capacity() -> bool:
return self._active < self.max_concurrent and (
per_user_key is None
or self.max_concurrent_per_user is None
or self._active_by_user.get(per_user_key, 0) < self.max_concurrent_per_user
)
if self._active >= self.max_concurrent:
response = JSONResponse(
{"detail": self.capacity_refusal_detail(False)},
status_code=429,
headers={"Retry-After": str(self.retry_after_seconds), **close_header},
)
return await response(scope, receive, send)
if not has_capacity():
response = JSONResponse(
{"detail": self.capacity_refusal_detail(True)},
status_code=429,
headers={"Retry-After": str(self.retry_after_seconds), **close_header},
)
return await response(scope, receive, send)
self._claim_capacity(per_user_key)
received = 0
# Only reading the body to its end proves the client has finished sending. This must
# NOT be seeded from Content-Length: h11 accepts `Content-Length: 0` alongside
# `Transfer-Encoding: chunked` (the chunked framing wins), so trusting the header let
# a client suppress the close and then stream indefinitely with no lease held and
# none of the caps below applying — they all live in limited_receive, which an app
# that answers early never calls again.
body_finished = False
upload_started_at = asyncio.get_running_loop().time()
async def limited_receive() -> Message:
# Backstop for clients that omit Content-Length (chunked transfer): count the
# streamed body and abort the request once it exceeds the cap, so the multipart
# parser stops spooling. A clean 413 isn't possible mid-parse; the aborted
# request surfaces to the client as a dropped connection.
nonlocal received, body_finished
remaining_duration = self.max_upload_duration_seconds - (
asyncio.get_running_loop().time() - upload_started_at
)
# The three aborts below synthesize a disconnect precisely because the client is
# still uploading, so they deliberately leave body_finished alone: whatever the
# app answers must still close the connection.
if remaining_duration <= 0:
return {"type": "http.disconnect"}
try:
message = await asyncio.wait_for(receive(), timeout=min(self.idle_timeout_seconds, remaining_duration))
except TimeoutError:
return {"type": "http.disconnect"}
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > self.max_body_bytes:
return {"type": "http.disconnect"}
if not message.get("more_body", False):
body_finished = True
elif message["type"] == "http.disconnect":
# The client is already gone; there is nothing left to close.
body_finished = True
return message
async def close_if_answered_early(message: Message) -> None:
# See the class docstring: answering before the body has been read to its end must
# not leave the client uploading into an already-sent response.
if message["type"] == "http.response.start" and not body_finished and is_http1:
headers = [(name, value) for name, value in message.get("headers", []) if name.lower() != b"connection"]
headers.append((b"connection", b"close"))
message = {**message, "headers": headers}
await send(message)
try:
await self.app(scope, limited_receive, close_if_answered_early)
finally:
self._release_capacity(per_user_key)
def _claim_capacity(self, per_user_key: str | None) -> None:
self._active += 1
if per_user_key is not None:
self._active_by_user[per_user_key] = self._active_by_user.get(per_user_key, 0) + 1
def _release_capacity(self, per_user_key: str | None) -> None:
self._active -= 1
if per_user_key is None:
return
remaining = self._active_by_user.get(per_user_key, 0) - 1
if remaining > 0:
self._active_by_user[per_user_key] = remaining
else:
self._active_by_user.pop(per_user_key, None)
# The video-recall routes that take an upload ingest it exactly as /videos/upload does, so they
# share its ingress cap and concurrency slots. Their name-only siblings take no body and stay
# outside the limiter, so a caller mid-upload is never refused a slot for a bodyless request.
_VIDEO_RECALL_UPLOAD_PATH = re.compile(
r"/api/v1/recall/video/[^/]+/(?:initial-video|reference-video|conditioning-video)/upload"
)
def _is_video_upload(method: str, path: str) -> bool:
return method == "POST" and (
path == "/api/v1/videos/upload" or _VIDEO_RECALL_UPLOAD_PATH.fullmatch(path) is not None
)
class VideoUploadLimitASGIMiddleware(RequestBodyLimitASGIMiddleware):
"""Bound video-upload ingress before FastAPI's multipart parser runs."""
def __init__(
self,
app: ASGIApp,
max_body_bytes: int,
max_concurrent: int,
max_concurrent_per_user: int | None = None,
identify_user: Callable[[Scope], tuple[bool, str | None] | Awaitable[tuple[bool, str | None]]] | None = None,
idle_timeout_seconds: float = 120.0,
max_upload_duration_seconds: float = 30 * 60,
) -> None:
super().__init__(
app=app,
matches_request=_is_video_upload,
too_large_detail=lambda _actual, limit: f"Video upload exceeds maximum request size ({limit} bytes)",
capacity_refusal_detail=lambda per_user: (
"Too many concurrent video uploads for this user; try again shortly"
if per_user
else "Too many concurrent video uploads; try again shortly"
),
max_body_bytes=max_body_bytes,
max_concurrent=max_concurrent,
max_concurrent_per_user=max_concurrent_per_user,
identify_user=identify_user,
idle_timeout_seconds=idle_timeout_seconds,
max_upload_duration_seconds=max_upload_duration_seconds,
)
def _is_project_write(method: str, path: str) -> bool:
if method == "POST":
return path == "/api/v1/projects/"
if method != "PUT" or not path.startswith("/api/v1/projects/"):
return False
# A project's content, or the caller's workspace in it: each is a document as large.
project_id = path.removeprefix("/api/v1/projects/").removesuffix("/workspace")
return bool(project_id) and "/" not in project_id
def _is_font_upload(method: str, path: str) -> bool:
return method == "POST" and path in ("/api/v1/fonts", "/api/v1/fonts/validate")
def _is_file_upload(method: str, path: str) -> bool:
return method == "POST" and path == "/api/v1/files/upload"
class ProjectWriteLimitASGIMiddleware(RequestBodyLimitASGIMiddleware):
"""Bound project writes before FastAPI parses their JSON documents."""
def __init__(
self,
app: ASGIApp,
max_body_bytes: int,
max_concurrent: int,
max_concurrent_per_user: int | None = None,
identify_user: Callable[[Scope], tuple[bool, str | None] | Awaitable[tuple[bool, str | None]]] | None = None,
idle_timeout_seconds: float = 30.0,
max_upload_duration_seconds: float = 120.0,
) -> None:
super().__init__(
app=app,
matches_request=_is_project_write,
too_large_detail=lambda actual, limit: {
"actual_bytes": actual,
"code": "project_request_too_large",
"max_bytes": limit,
},
capacity_refusal_detail=lambda _per_user: {
"code": "project_write_busy",
"message": "Too many project saves are in progress; retry shortly",
},
max_body_bytes=max_body_bytes,
max_concurrent=max_concurrent,
max_concurrent_per_user=max_concurrent_per_user,
identify_user=identify_user,
idle_timeout_seconds=idle_timeout_seconds,
max_upload_duration_seconds=max_upload_duration_seconds,
retry_after_seconds=1,
)
class SubPathASGIMiddleware:
"""Make the app work behind a reverse proxy that serves it under a sub-path (e.g. `/invoke`).
Handles both common proxy styles:
- The proxy STRIPS the sub-path: the incoming path is already `/api/...`. We restore the prefix
so `scope["path"]` is the public path, and advertise it via `root_path`.
- The proxy PRESERVES the sub-path: the incoming path is already `/invoke/api/...`. We leave the
path as-is and advertise the prefix via `root_path`.
Either way `scope["path"]` ends up holding the full public path (prefix included), as the ASGI
spec requires. Starlette's router strips `root_path` for route matching (via `get_route_path`)
and builds redirect/`url_for` URLs from the full path, so server-generated redirects keep the
prefix.
Note: we deliberately do NOT use uvicorn's `root_path`, because uvicorn also PREPENDS it to the
request path, which would double the prefix for the preserve-style proxy. Doing the rewrite here
covers both styles.
"""
def __init__(self, app: ASGIApp, base_path: str) -> None:
self.app = app
self.base_path = base_path
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] in ("http", "websocket"):
scope = dict(scope)
path: str = scope.get("path", "")
# Strip-style proxy: the prefix is missing, so restore it. Per the ASGI spec `scope["path"]`
# must include `root_path`; Starlette strips it again for matching and uses the full path
# for redirects/url_for, keeping the prefix on server-generated redirects.
if not (path == self.base_path or path.startswith(self.base_path + "/")):
scope["path"] = self.base_path + path
raw_path = scope.get("raw_path")
if raw_path is not None:
scope["raw_path"] = self.base_path.encode("latin-1") + raw_path
# Advertise the public prefix for both styles (openapi servers, /docs, redirects).
scope["root_path"] = self.base_path
await self.app(scope, receive, send)
# Add the middleware
app.add_middleware(RedirectRootWithQueryStringMiddleware)
app.add_middleware(SlidingWindowTokenMiddleware)
app.add_middleware(
VideoUploadLimitASGIMiddleware,
max_body_bytes=videos.MAX_UPLOAD_REQUEST_SIZE,
max_concurrent=videos.MAX_CONCURRENT_VIDEO_UPLOADS,
max_concurrent_per_user=videos.MAX_CONCURRENT_VIDEO_UPLOADS_PER_USER,
identify_user=_identify_video_upload_user_async,
)
app.add_middleware(
RequestBodyLimitASGIMiddleware,
matches_request=_is_file_upload,
too_large_detail=lambda _actual, limit: f"Managed file upload exceeds maximum request size ({limit} bytes)",
capacity_refusal_detail=lambda per_user: (
"Too many concurrent file uploads for this user; try again shortly"
if per_user
else "Too many concurrent file uploads; try again shortly"
),
max_body_bytes=app_config.max_file_upload_size_bytes + files.FILE_UPLOAD_MULTIPART_OVERHEAD,
max_concurrent=files.MAX_CONCURRENT_FILE_UPLOADS,
max_concurrent_per_user=files.MAX_CONCURRENT_FILE_UPLOADS_PER_USER,
identify_user=_identify_video_upload_user_async,
idle_timeout_seconds=files.FILE_UPLOAD_IDLE_TIMEOUT_SECONDS,
max_upload_duration_seconds=files.FILE_UPLOAD_MAX_DURATION_SECONDS,
)
app.add_middleware(
RequestBodyLimitASGIMiddleware,
matches_request=_is_font_upload,
too_large_detail=lambda _actual, limit: f"Font upload exceeds maximum request size ({limit} bytes)",
capacity_refusal_detail=lambda per_user: (
"Too many concurrent font uploads for this user; try again shortly"
if per_user
else "Too many concurrent font uploads; try again shortly"
),
max_body_bytes=app_config.max_font_upload_bytes + fonts.FONT_UPLOAD_MULTIPART_OVERHEAD,
max_concurrent=fonts.MAX_CONCURRENT_FONT_UPLOADS,
max_concurrent_per_user=fonts.MAX_CONCURRENT_FONT_UPLOADS_PER_USER,
identify_user=_identify_video_upload_user_async,
idle_timeout_seconds=fonts.FONT_UPLOAD_IDLE_TIMEOUT_SECONDS,
max_upload_duration_seconds=fonts.FONT_UPLOAD_MAX_DURATION_SECONDS,
retry_after_seconds=1,
)
app.add_middleware(
ProjectWriteLimitASGIMiddleware,
max_body_bytes=projects.PROJECT_WRITE_REQUEST_MAX_BYTES,
max_concurrent=projects.MAX_CONCURRENT_PROJECT_WRITES,
max_concurrent_per_user=projects.MAX_CONCURRENT_PROJECT_WRITES_PER_USER,
identify_user=_identify_video_upload_user_async,
idle_timeout_seconds=projects.PROJECT_WRITE_IDLE_TIMEOUT_SECONDS,
max_upload_duration_seconds=projects.PROJECT_WRITE_MAX_DURATION_SECONDS,
)
# Add event handler
event_handler_id: int = id(app)
app.add_middleware(
EventHandlerASGIMiddleware,
handlers=[local_handler], # TODO: consider doing this in services to support different configurations
middleware_id=event_handler_id,
)
socket_io = SocketIO(app)
app.add_middleware(
CORSMiddleware,
allow_origins=app_config.allow_origins,
allow_credentials=app_config.allow_credentials,
allow_methods=app_config.allow_methods,
allow_headers=app_config.allow_headers,
expose_headers=["X-Refreshed-Token"],
)
configure_gzip(app, app_config.http_compression_level)
# Include all routers
# Authentication router should be first so it's registered before protected routes
app.include_router(auth.auth_router, prefix="/api")
app.include_router(utilities.utilities_router, prefix="/api")
app.include_router(fonts.fonts_router, prefix="/api")
app.include_router(model_manager.model_manager_router, prefix="/api")
app.include_router(working_memory.working_memory_router, prefix="/api")
app.include_router(files.files_router, prefix="/api")
app.include_router(image_moves.image_moves_router, prefix="/api")
app.include_router(images.images_router, prefix="/api")
app.include_router(image_map.image_map_router, prefix="/api")
app.include_router(intermediates.intermediates_router, prefix="/api")
app.include_router(videos.videos_router, prefix="/api")
app.include_router(gallery.gallery_router, prefix="/api")
app.include_router(gallery_maintenance.gallery_maintenance_router, prefix="/api")
app.include_router(boards.boards_router, prefix="/api")
app.include_router(board_images.board_images_router, prefix="/api")
app.include_router(virtual_boards.virtual_boards_router, prefix="/api")
app.include_router(model_relationships.model_relationships_router, prefix="/api")
app.include_router(app_info.app_router, prefix="/api")
app.include_router(session_queue.session_queue_router, prefix="/api")
app.include_router(workflows.workflows_router, prefix="/api")
app.include_router(style_presets.style_presets_router, prefix="/api")
app.include_router(wildcards.wildcards_router, prefix="/api")
app.include_router(system_prompts.system_prompts_router, prefix="/api")
app.include_router(client_state.client_state_router, prefix="/api")
app.include_router(projects.projects_router, prefix="/api")
app.include_router(recall_parameters.recall_parameters_router, prefix="/api")
app.include_router(video_recall.video_recall_router, prefix="/api")
app.include_router(custom_nodes.custom_nodes_router, prefix="/api")
app.openapi = get_openapi_func(app)
@app.get("/docs", include_in_schema=False)
def overridden_swagger(request: Request) -> HTMLResponse:
# Prefix with the proxy root_path (if any) so the schema resolves under a sub-path deployment.
root_path = request.scope.get("root_path", "")
return get_swagger_ui_html(
openapi_url=f"{root_path}{app.openapi_url}", # type: ignore [arg-type] # this is always a string
title=f"{app.title} - Swagger UI",
swagger_favicon_url="static/docs/invoke-favicon-docs.svg",
)
@app.get("/redoc", include_in_schema=False)
def overridden_redoc(request: Request) -> HTMLResponse:
# Prefix with the proxy root_path (if any) so the schema resolves under a sub-path deployment.
root_path = request.scope.get("root_path", "")
return get_redoc_html(
openapi_url=f"{root_path}{app.openapi_url}", # type: ignore [arg-type] # this is always a string
title=f"{app.title} - Redoc",
redoc_favicon_url="static/docs/invoke-favicon-docs.svg",
)
web_root_path = Path(list(webv2_dir.__path__)[0])
if app_config.unsafe_disable_picklescan:
logger.warning(
"The unsafe_disable_picklescan option is enabled. This disables malware scanning while installing and"
"loading models, which may allow malicious code to be executed. Use at your own risk."
)
try:
mount_frontend(app, web_root_path, legacy=getattr(InvokeAIArgs.args, "web_legacy", False))
except RuntimeError as error:
logger.warning(f"No UI found, skipping UI mount: {error}")