mirror of
https://github.com/mudler/LocalAI.git
synced 2026-10-28 09:08:54 -04:00
* feat(schema): add Conversation schema for chat history (#9432) Persist WebUI chat conversations server-side so browser refresh, private windows, or device changes preserve user history (issue #9432). This commit adds the on-disk representation: - Conversation holds id, name, model, opaque history, MCP / sampling settings, and timestamps. - ConversationsFile is the per-user list serialised to JSON. History is stored as json.RawMessage so the server stays agnostic to React message shapes (user / assistant / thinking / tool_call / tool_result mixed with text / image_url / audio_url / file attachments). Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * feat(chathistory): add file-based per-user conversation store (#9432) File-backed persister for chat history. Each user's conversations live under {baseDir}/{userID}/conversations.json (anonymous/ when auth is disabled). Design choices: - In-memory cache backed by sync.Mutex so concurrent saves don't interleave writes. - Atomic write via tmp file + os.Rename so a crash mid-save never leaves a corrupted history. - ID validation regex blocks path-traversal payloads at the store boundary, in addition to the auth context constraint. Tests cover round-trip persistence across instances, user isolation, unsafe-ID rejection, bulk replace migration, and the anonymous fallback path. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * feat(api): expose chat conversation CRUD endpoints (#9432) Wire the chathistory store into the HTTP layer. New endpoints under /api/conversations: - GET /api/conversations list - POST /api/conversations upsert (id in body) - DELETE /api/conversations delete all - PUT /api/conversations/bulk replace entire set (localStorage migration) - GET /api/conversations/:id fetch one - PUT /api/conversations/:id upsert (id in path; path id wins over body) - DELETE /api/conversations/:id delete one All endpoints scope queries to the authenticated user via getUserID(c) - callers cannot impersonate other users by passing a user_id in the body. The endpoints are gated behind the new chat_history feature permission (default ON in APIFeatures), registered through the existing RouteFeatureRegistry so the unified feature middleware picks them up automatically. Application.ChatHistoryStore() returns nil when DisableWebUI is set or no persistence path is configured, in which case route registration is skipped entirely rather than registering handlers that always 503. Also adds the chat-history instruction entry and Swagger tag so the endpoint surfaces in /api/instructions and /swagger. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * feat(react-ui): sync chat history to server with localStorage fallback (#9432) useChat now probes /api/conversations on mount. When the endpoint responds 200, the server becomes the authoritative source: the hook merges remote conversations into local state and pushes per-chat PUT updates on each debounced save. When the endpoint 404s - older LocalAI deploys or the feature disabled - the hook silently keeps the old localStorage-only behaviour, so the change is backward-compatible. Migration: when the server is reachable but empty and the browser has local conversations with history, the hook fires a single PUT /api/conversations/bulk to seed the server. The atomic bulk endpoint avoids partial-upload states where a retry would skip already-uploaded entries. Delete operations propagate to the server when it's available; failures are silently swallowed so the local UI stays responsive on transient network errors. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * test(chathistory): rewrite tests in Ginkgo/Gomega The initial test file used the stdlib testing package (t.Fatalf / t.Errorf), which is forbidden by the forbidigo linter rule in .golangci.yml — LocalAI mandates Ginkgo/Gomega for all Go tests (see .agents/coding-style.md). Restructured the same six scenarios into Describe / Context / It blocks, with a chathistory_suite_test.go bootstrap that registers the Ginkgo fail handler. Test coverage is unchanged: basic CRUD round-trip, cross- instance persistence, user isolation, unsafe ID rejection (now via DescribeTable), bulk replace overwrite, and the anonymous fallback path. Assisted-by: Claude:claude-opus-4-7 Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * refactor(chathistory): switch store to GORM-backed authDB Addresses mudler's review on #9902. Chat history was the only per-user state in LocalAI sitting in a separate filesystem store instead of the shared GORM database — AgentStore and JobStore both live there. Move it onto Application.authDB so per-user state stays in one place. * ConversationRecord (GORM model) with composite primary key (user_id, conv_id) — React mints IDs locally with no global coordination so per-user uniqueness is the natural shape. * Store.New(db *gorm.DB) replaces Store.New(baseDir string). Save / Get / List / Delete / DeleteAll / ReplaceAll keep their signatures so HTTP handlers and the React UI are untouched. * ReplaceAll runs in a transaction with an Unscoped() pre-clear so a future retention sweep cannot resurrect a stale ID on re-upload. * gorm.DeletedAt in the schema means a future retention pruner is a one-line query — addresses the second half of the review (unbounded in-memory map). The map is gone: reads go straight to the DB. Trade-off worth flagging in the PR reply: chat history persistence now requires auth.Enabled = true (that's what initialises Application.authDB). With auth disabled the React UI transparently falls back to localStorage, the same path the original PR took on 404. Consistent with AgentStore / JobStore; if a "chat history always on" mode is preferred we can pull DB init out of auth.InitDB into a shared helper. Assisted-by: Claude:claude-opus-4-7 [Read Edit Bash] Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * refactor(schema): drop now-unused ConversationsFile envelope ConversationsFile was the JSON wrapper for the old file-based chat history store — a {Conversations: [...], UpdatedAt: ...} pair serialised to disk under {baseDir}/{userID}/conversations.json. The previous commit replaced that store with a GORM-backed one that writes rows directly as ConversationRecord, leaving the envelope without a consumer. Assisted-by: Claude:claude-opus-4-7 [Read Edit Bash] Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * test(chathistory): switch tests to testutil.SetupTestDB Mirror the AgentStore test setup: spin up a PostgreSQL 16 container via testutil.SetupTestDB(), construct a Store on top of it, exercise CRUD round-trips. The previous file-based fixtures (TempDir, filepath.Join checks) are no longer meaningful now that the store talks GORM. Tests are skipped on macOS (testcontainers needs Docker) and run on CI, same as the other GORM-backed suites in the repo. Also reframed two cases: * "unsafe IDs" → "malformed IDs" — the DB-backed store doesn't care about path traversal, but idRegex still rejects whitespace / control characters so IDs stay safe in logs and HTTP responses. * "anonymous user" no longer pins a directory path (no directory exists anymore); instead it checks the round-trip plus the per-user isolation guarantee. Added a DeleteAll round-trip to cover the bulk-clear endpoint. Assisted-by: Claude:claude-opus-4-7 [Read Edit Bash] Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> * test(chathistory): cover the conversation HTTP handlers The seven /api/conversations handlers had no tests. Inject the *chathistory.Store into the handlers instead of the whole Application and move the route table into RegisterChatHistoryRoutes, so a spec can drive the real registration and middleware chain (auth.Middleware plus the chat_history feature gate) against an in-memory SQLite auth database. The new specs cover 401 without credentials on every route, 403 when an admin revoked chat_history, the CRUD round trip, path id over body id, 400 on malformed ids and bodies, per-user isolation, bulk replace and delete-all, and that a nil store registers nothing (the UI then falls back to localStorage). The handlers' nil-store branches are gone: the routes are only registered with a store, so those branches could never run. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * fix(chathistory): make deletions final with tombstones and versions A conversation deleted on one device came back as soon as a client with a stale copy wrote it again: Delete soft-deleted the row, and the next Save went through GORM's upsert, which cleared deleted_at and resurrected it for every device. The lookup that recovered CreatedAt also ran outside any transaction, so concurrent writers raced on it. The server is now authoritative over deletions: * Delete turns the row into a tombstone: content dropped, deleted_at set. It is idempotent, and deleting an id the server has not seen yet still records a tombstone, so a delete that overtakes the UI's in-flight debounced save of the same chat still wins. * Save runs in a transaction, refuses a tombstoned id with ErrDeleted (HTTP 410 Gone), and bumps the version with a single UPDATE ... SET version = version + 1 guarded by deleted_at IS NULL, so concurrent writers each count and a delete committed between the lookup and the write still wins. Two concurrent first writes of the same id retry once (ON CONFLICT DO NOTHING, then update). * Every row carries a server-assigned version (1 on the first save, +1 per write including the delete), returned to the client. A non-zero version tells the UI the server has seen a conversation, which is how it can tell a never-synced draft from a server-side deletion. * GET /api/conversations returns the tombstones under "deleted". * DeleteAll and ReplaceAll leave tombstones too. ReplaceAll no longer hard-deletes everything first; it upserts the payload, skips ids that were deleted (reported in "skipped"), and tombstones the rest. * createdAt/updatedAt are stored as the client sends them (only zero values are stamped), so clients compare updatedAt from their own clocks rather than against the server's. The store specs now run against PostgreSQL (testcontainers) and, with the auth tag, SQLite through auth.InitDB, since both back the auth database. The API specs cover a stale client reconnecting after a remote deletion. Swagger is regenerated with swag v1.16.6 (json.RawMessage fields get swaggertype), and the feature is documented, including that it needs user auth. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * fix(react-ui): let the server decide which chats were deleted mergeRemoteAndLocal kept every chat that was only in the browser and let the server copy win for every shared id. A stale browser therefore uploaded chats deleted on another device as if they were new drafts, and a message sent while the list request was still in flight was replaced by the older server copy and then lost from localStorage too. The first load now reconciles with the server's tombstones and versions: * a chat the server lists under "deleted" is dropped locally; * a chat on both sides keeps the copy with the newer updatedAt, so an edit made during the load wins and is uploaded afterwards; * a chat only in the browser is uploaded only if it was never synced (no version). With a version the server has seen it and no longer has it, so it is dropped instead of resurrected (this also keeps one account's cached chats out of another account on a shared browser); * deletes made while the list is loading are queued and sent once it arrives. Saves record the version the server returns, and a 410 on save drops the chat locally instead of retrying it forever. Chats received from the server count as already sent, so adopting a server copy no longer echoes it straight back. The bulk localStorage migration is gone: it replaced the whole server set from a possibly stale browser, and the per-chat saves already upload never-synced drafts through the tombstone check. The Playwright spec drives each case against a stubbed /api/conversations that follows the server contract. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * fix(chathistory): keep the LocalAI Assistant toggle on synced chats master's createNewChat sets localaiAssistant, but serializeChat did not send it and schema.Conversation had no field for it, so a chat with the Assistant mode on came back with it off after a reload from the server (and the local cache dropped it too). Add the field on both sides. The other fields createNewChat sets were already covered; a handler spec now round-trips all of them, and the UI spec checks the toggle on the way up and in the local cache. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * fix(react-ui): scope chat cache per account, retry unconfirmed deletes Two gaps in the client half of server-side chat history, both found in review: The browser cache was one shared localStorage key. A draft that one account could not upload (a failed first save) stayed in it, and after that account signed out and another signed in, the reconcile kept the unversioned draft and the save pass uploaded it into the second account. The cache now lives under localai_chats_data:<user id>, Chat remounts its state when the account changes, and nothing is synced without a signed-in account. The shared key is left for browser-only use without auth and is not uploaded when signed in, because nothing tells which account it belongs to. Deletes were dropped locally and their DELETE errors swallowed; only deletes made while the first list was loading were queued, and not persisted. A delete made while the server was unreachable therefore came back with the next list. Deletes (single, delete all, and deletes on the Home page) are now kept as pending deletes in the account's cache until the server confirms them, override the server list in the reconcile, and are sent again on the next change, on the online event and on the next load. While a delete-all is pending no conversation is uploaded, so a chat started after it is not caught by it. The Playwright specs replay both review scenarios (account switch after a failed first save; delete and delete-all while offline) with counter-checks that the same account keeps and uploads its own draft and that a confirmed delete is neither re-sent nor resurrected. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * fix(react-ui): persist cleared chats immediately Navigation cancels the debounced cache write and can restore unsynced chats after Clear all. Save the cleared list with its pending deletion before returning, and cover immediate navigation in the browser spec. Assisted-by: Codex:GPT-6 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * test(react-ui): make the chat history sync specs deterministic - "clear all persists before navigation" opened a single chat, and the menu offers no Clear all for one chat, so the spec timed out in every run. It now opens two unsynced chats and checks that neither survives. Reverting 03cd9c115's save in clearAllChats turns it red again. - "a delete the server confirmed is not sent again" reopened the page as soon as the server had the request, before the page had the answer; the unconfirmed delete was then rightly sent again (4 of 5 runs). It now waits until the cache holds no pending delete. Docs-Not-Needed: test-only change. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * fix(chathistory): keep the chat's reasoning effort on the server reasoningEffort (#12700, #12716) is part of the chat the UI syncs since the master merge, but schema.Conversation had no field for it, so the server dropped it and a reload from the server reset the setting. Add the field. The handler spec that round-trips every chat field now includes reasoningEffort. A schema test reads serializeChat in useChat.js and fails for any key the UI sends that schema.Conversation cannot hold, so the next such drift shows up as a failing test rather than in review (it reports reasoningEffort on the previous head). Swagger and docs updated. Assisted-by: Claude Code:claude-opus-5-5 Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> * test(chat): use Ginkgo for the schema drift guard The new drift guard uses testing methods forbidden by repository lint. Keep its field coverage and fail-fast parser checks in Ginkgo/Gomega. Assisted-by: nib:gpt-6.1-sol --------- Signed-off-by: TLoE419 <tloemizuchizu@gmail.com> Signed-off-by: Stefan Walcz <stefan.walcz@walcz.de> Co-authored-by: TLoE419 <tloemizuchizu@gmail.com> Co-authored-by: localai-org-maint-bot <306269227+localai-org-maint-bot@users.noreply.github.com> Co-authored-by: mudler-agent <mudler-bot@c3os.io>
734 lines
28 KiB
Go
734 lines
28 KiB
Go
package http
|
|
|
|
import (
|
|
"embed"
|
|
"errors"
|
|
"fmt"
|
|
"io/fs"
|
|
"math"
|
|
"mime"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/echo/v4/middleware"
|
|
|
|
"github.com/mudler/LocalAI/pkg/model"
|
|
|
|
corebackend "github.com/mudler/LocalAI/core/backend"
|
|
"github.com/mudler/LocalAI/core/http/auth"
|
|
"github.com/mudler/LocalAI/core/http/endpoints/localai"
|
|
|
|
httpMiddleware "github.com/mudler/LocalAI/core/http/middleware"
|
|
"github.com/mudler/LocalAI/core/http/routes"
|
|
|
|
"github.com/mudler/LocalAI/core/application"
|
|
"github.com/mudler/LocalAI/core/schema"
|
|
"github.com/mudler/LocalAI/core/services/distributed"
|
|
"github.com/mudler/LocalAI/core/services/finetune"
|
|
"github.com/mudler/LocalAI/core/services/galleryop"
|
|
"github.com/mudler/LocalAI/core/services/messaging"
|
|
"github.com/mudler/LocalAI/core/services/nodes"
|
|
"github.com/mudler/LocalAI/core/services/quantization"
|
|
|
|
"github.com/mudler/xlog"
|
|
)
|
|
|
|
// Embed a directory
|
|
//
|
|
//go:embed static/*
|
|
var embedDirStatic embed.FS
|
|
|
|
// Embed React UI build output
|
|
//
|
|
//go:embed react-ui/dist/*
|
|
var reactUI embed.FS
|
|
|
|
var quietPaths = []string{"/api/operations", "/api/resources", "/healthz", "/readyz"}
|
|
|
|
// immutableAssetCacheControl is the Cache-Control served for content-hashed
|
|
// build output. The filename changes whenever the content does, so a one-year
|
|
// TTL plus `immutable` is safe and removes both the re-download and the
|
|
// conditional revalidation round-trip.
|
|
const immutableAssetCacheControl = "public, max-age=31536000, immutable"
|
|
|
|
func defaultBodyLimitSkipper(c echo.Context) bool {
|
|
// Remeshing accepts generated GLBs that routinely exceed the default
|
|
// upload limit. The route has its own tighter, format-specific limit.
|
|
return c.Request().Method == http.MethodPost && c.Path() == "/3d/remesh"
|
|
}
|
|
|
|
// applyModelLoadCooldown maps a ModelLoadCooldownError anywhere in err's chain
|
|
// to HTTP 503 with a Retry-After header (whole seconds, floor 1), so a client
|
|
// polling a model whose load recently failed backs off instead of triggering a
|
|
// fresh backend start. If err is not a cooldown error, code is returned as-is.
|
|
func applyModelLoadCooldown(err error, code int, c echo.Context) int {
|
|
var coolErr *model.ModelLoadCooldownError
|
|
if !errors.As(err, &coolErr) {
|
|
return code
|
|
}
|
|
secs := int(math.Ceil(coolErr.RetryAfter.Seconds()))
|
|
if secs < 1 {
|
|
secs = 1
|
|
}
|
|
c.Response().Header().Set("Retry-After", strconv.Itoa(secs))
|
|
return http.StatusServiceUnavailable
|
|
}
|
|
|
|
func applyBackendAdmission(err error, code int, c echo.Context) int {
|
|
var capacityErr *corebackend.BackendAdmissionError
|
|
if !errors.As(err, &capacityErr) {
|
|
return code
|
|
}
|
|
c.Response().Header().Set("Retry-After", strconv.Itoa(int(capacityErr.RetryAfter.Seconds())))
|
|
return http.StatusTooManyRequests
|
|
}
|
|
|
|
// applyNoAvailableNodes maps scheduler "no available nodes" errors to 503.
|
|
// When the cluster has no healthy node to serve a model — all are full, a
|
|
// node selector excludes every candidate, or eviction could not free a slot —
|
|
// the request is retryable, not a server bug. Without this the error fell
|
|
// through to 500, which tells clients something is broken when they just
|
|
// need to wait for a node.
|
|
func applyNoAvailableNodes(err error, code int) int {
|
|
if errors.Is(err, nodes.ErrNoAvailableNodes) {
|
|
return http.StatusServiceUnavailable
|
|
}
|
|
return code
|
|
}
|
|
|
|
// respondModelLoading answers a request whose model is still cold-loading with
|
|
// 503, a Retry-After header and the live `loading` object, reporting true when
|
|
// it handled the error.
|
|
//
|
|
// The distinction from applyModelLoadCooldown matters: a cooldown means "the
|
|
// last load FAILED, back off", this means "the load is progressing, here is how
|
|
// far it got". Both used to look like the same anonymous error, so an operator
|
|
// watching a 35 GB model stage normally onto a new worker saw only failures.
|
|
func respondModelLoading(err error, c echo.Context) bool {
|
|
var loadErr *nodes.ModelLoadingError
|
|
if !errors.As(err, &loadErr) {
|
|
return false
|
|
}
|
|
setModelLoadingRetryAfter(loadErr, c)
|
|
status := loadErr.Status
|
|
if jerr := c.JSON(http.StatusServiceUnavailable, schema.ModelLoadingResponse{
|
|
Error: &schema.APIError{
|
|
Message: loadErr.Error(),
|
|
Code: "model_loading",
|
|
Type: "model_loading",
|
|
},
|
|
Loading: &status,
|
|
}); jerr != nil {
|
|
xlog.Debug("Failed to write model-loading response", "error", jerr)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// applyModelLoading is the body-less half of respondModelLoading, for the
|
|
// opaque-errors handler: status and Retry-After only.
|
|
func applyModelLoading(err error, code int, c echo.Context) int {
|
|
var loadErr *nodes.ModelLoadingError
|
|
if !errors.As(err, &loadErr) {
|
|
return code
|
|
}
|
|
setModelLoadingRetryAfter(loadErr, c)
|
|
return http.StatusServiceUnavailable
|
|
}
|
|
|
|
func setModelLoadingRetryAfter(loadErr *nodes.ModelLoadingError, c echo.Context) {
|
|
secs := int(math.Ceil(loadErr.RetryAfter.Seconds()))
|
|
if secs < 1 {
|
|
secs = 1
|
|
}
|
|
c.Response().Header().Set("Retry-After", strconv.Itoa(secs))
|
|
}
|
|
|
|
// @title LocalAI API
|
|
// @version 2.0.0
|
|
// @description The LocalAI Rest API.
|
|
// @termsOfService
|
|
// @contact.name LocalAI
|
|
// @contact.url https://localai.io
|
|
// @license.name MIT
|
|
// @license.url https://raw.githubusercontent.com/mudler/LocalAI/master/LICENSE
|
|
// @BasePath /
|
|
// @schemes http https
|
|
// @securityDefinitions.apikey BearerAuth
|
|
// @in header
|
|
// @name Authorization
|
|
// @tag.name inference
|
|
// @tag.description Chat completions, text completions, edits, and responses (OpenAI-compatible)
|
|
// @tag.name embeddings
|
|
// @tag.description Vector embeddings (OpenAI-compatible)
|
|
// @tag.name audio
|
|
// @tag.description Text-to-speech, transcription, voice activity detection, sound generation
|
|
// @tag.name images
|
|
// @tag.description Image generation and inpainting
|
|
// @tag.name video
|
|
// @tag.description Video generation from prompts
|
|
// @tag.name detection
|
|
// @tag.description Object detection in images
|
|
// @tag.name tokenize
|
|
// @tag.description Tokenization and token metrics
|
|
// @tag.name models
|
|
// @tag.description Model gallery browsing, installation, deletion, and listing
|
|
// @tag.name backends
|
|
// @tag.description Backend gallery browsing, installation, deletion, and listing
|
|
// @tag.name config
|
|
// @tag.description Model configuration metadata, autocomplete, PATCH updates, VRAM estimation
|
|
// @tag.name monitoring
|
|
// @tag.description Prometheus metrics, backend status, system information
|
|
// @tag.name mcp
|
|
// @tag.description Model Context Protocol — tool-augmented chat with MCP servers
|
|
// @tag.name agent-jobs
|
|
// @tag.description Agent task and job management
|
|
// @tag.name p2p
|
|
// @tag.description Peer-to-peer networking nodes and tokens
|
|
// @tag.name rerank
|
|
// @tag.description Document reranking
|
|
// @tag.name instructions
|
|
// @tag.description API instruction discovery — browse instruction areas and get endpoint guides
|
|
// @tag.name chat-history
|
|
// @tag.description Server-side persistence of WebUI chat conversations
|
|
|
|
func API(application *application.Application) (*echo.Echo, error) {
|
|
e := echo.New()
|
|
|
|
// Set body limit
|
|
if application.ApplicationConfig().UploadLimitMB > 0 {
|
|
e.Use(middleware.BodyLimitWithConfig(middleware.BodyLimitConfig{
|
|
Limit: fmt.Sprintf("%dM", application.ApplicationConfig().UploadLimitMB),
|
|
Skipper: defaultBodyLimitSkipper,
|
|
}))
|
|
}
|
|
|
|
// SPA fallback handler, set later when React UI is available
|
|
var spaFallback func(echo.Context) error
|
|
|
|
// Set error handler
|
|
if !application.ApplicationConfig().OpaqueErrors {
|
|
e.HTTPErrorHandler = func(err error, c echo.Context) {
|
|
if respondModelLoading(err, c) {
|
|
return
|
|
}
|
|
code := http.StatusInternalServerError
|
|
var he *echo.HTTPError
|
|
if errors.As(err, &he) {
|
|
code = he.Code
|
|
}
|
|
code = applyModelLoadCooldown(err, code, c)
|
|
code = applyBackendAdmission(err, code, c)
|
|
code = applyNoAvailableNodes(err, code)
|
|
|
|
// Handle 404 errors: serve React SPA for HTML requests, JSON otherwise
|
|
if code == http.StatusNotFound {
|
|
if spaFallback != nil {
|
|
accept := c.Request().Header.Get("Accept")
|
|
contentType := c.Request().Header.Get("Content-Type")
|
|
if strings.Contains(accept, "text/html") && !strings.Contains(contentType, "application/json") {
|
|
spaFallback(c)
|
|
return
|
|
}
|
|
}
|
|
notFoundHandler(c)
|
|
return
|
|
}
|
|
|
|
// Send custom error page
|
|
errType := ""
|
|
var capErr *corebackend.BackendAdmissionError
|
|
if errors.As(err, &capErr) {
|
|
errType = "rate_limit_error"
|
|
}
|
|
c.JSON(code, schema.ErrorResponse{
|
|
Error: &schema.APIError{Message: err.Error(), Code: code, Type: errType},
|
|
})
|
|
}
|
|
} else {
|
|
e.HTTPErrorHandler = func(err error, c echo.Context) {
|
|
code := http.StatusInternalServerError
|
|
var he *echo.HTTPError
|
|
if errors.As(err, &he) {
|
|
code = he.Code
|
|
}
|
|
code = applyModelLoadCooldown(err, code, c)
|
|
code = applyBackendAdmission(err, code, c)
|
|
// Opaque errors deliberately withhold the body, so a still-loading
|
|
// model gets the status and Retry-After but no progress detail.
|
|
code = applyModelLoading(err, code, c)
|
|
code = applyNoAvailableNodes(err, code)
|
|
c.NoContent(code)
|
|
}
|
|
}
|
|
|
|
// Set renderer
|
|
e.Renderer = renderEngine()
|
|
|
|
// Hide banner
|
|
e.HideBanner = true
|
|
e.HidePort = true
|
|
|
|
// Middleware - StripPathPrefix must be registered early as it uses Rewrite which runs before routing
|
|
e.Pre(httpMiddleware.StripPathPrefix())
|
|
|
|
// Stamp the configured external base URL into each request context so
|
|
// middleware.BaseURL can treat it as authoritative for self-referential
|
|
// links. Registered as Pre so it runs before routing and handlers.
|
|
if extBaseURL := application.ApplicationConfig().ExternalBaseURL; extBaseURL != "" {
|
|
e.Pre(func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
c.Set("_external_base_url", extBaseURL)
|
|
return next(c)
|
|
}
|
|
})
|
|
}
|
|
|
|
e.Pre(middleware.RemoveTrailingSlash())
|
|
|
|
if application.ApplicationConfig().MachineTag != "" {
|
|
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
c.Response().Header().Set("Machine-Tag", application.ApplicationConfig().MachineTag)
|
|
return next(c)
|
|
}
|
|
})
|
|
}
|
|
|
|
// Security headers (CSP, X-Content-Type-Options, X-Frame-Options,
|
|
// Referrer-Policy). Set early so every response — including 404s and
|
|
// errors — picks them up.
|
|
e.Use(httpMiddleware.SecurityHeaders())
|
|
|
|
// Gzip responses. Registered before the tracing and handler middlewares so
|
|
// the response writer it installs sits underneath them: the trace buffer
|
|
// keeps capturing plaintext while the wire carries the compressed bytes.
|
|
if !application.ApplicationConfig().DisableHTTPCompression {
|
|
e.Use(httpMiddleware.Compression(application.ApplicationConfig().HTTPCompressionMinLength))
|
|
}
|
|
|
|
// Custom logger middleware using xlog
|
|
e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
req := c.Request()
|
|
res := c.Response()
|
|
err := next(c)
|
|
|
|
// Echo's central HTTPErrorHandler runs *after* this middleware
|
|
// returns, so res.Status still reads the default 200 here when a
|
|
// handler returned an error without writing a response. Mirror
|
|
// echo.DefaultHTTPErrorHandler's status derivation so the access
|
|
// log reflects the status the client actually receives — without
|
|
// this, every silent handler error logs as 200.
|
|
status := res.Status
|
|
if err != nil && !res.Committed {
|
|
status = http.StatusInternalServerError
|
|
var he *echo.HTTPError
|
|
if errors.As(err, &he) {
|
|
status = he.Code
|
|
}
|
|
}
|
|
|
|
// Fix for #7989: Reduce log verbosity of Web UI polling, resources API, and health checks
|
|
// These paths are logged at DEBUG level (hidden by default) instead of INFO.
|
|
isQuietPath := false
|
|
for _, path := range quietPaths {
|
|
if req.URL.Path == path {
|
|
isQuietPath = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if isQuietPath && status == 200 {
|
|
xlog.Debug("HTTP request", "method", req.Method, "path", req.URL.Path, "status", status)
|
|
} else {
|
|
xlog.Info("HTTP request", "method", req.Method, "path", req.URL.Path, "status", status)
|
|
}
|
|
return err
|
|
}
|
|
})
|
|
|
|
// Recover middleware
|
|
if !application.ApplicationConfig().Debug {
|
|
e.Use(middleware.Recover())
|
|
}
|
|
|
|
// Metrics middleware. The metric service was created in
|
|
// application.start() so the OTel global provider is set before any
|
|
// counter is registered (the routing-module billing recorder relies
|
|
// on this). We reuse that instance here rather than calling
|
|
// monitoring.NewLocalAIMetricsService a second time, which would
|
|
// create a second provider, second prometheus exporter, and orphan
|
|
// whichever instance lost the SetMeterProvider race.
|
|
if metricsService := application.MetricsService(); metricsService != nil {
|
|
e.Use(localai.LocalAIMetricsAPIMiddleware(metricsService))
|
|
e.Server.RegisterOnShutdown(func() {
|
|
_ = metricsService.Shutdown()
|
|
})
|
|
}
|
|
|
|
// Health Checks should always be exempt from auth, so register these first
|
|
routes.HealthRoutes(e, application.Ready)
|
|
|
|
// Build auth middleware: use the new auth.Middleware when auth is enabled or
|
|
// as a unified replacement for the legacy key-auth middleware.
|
|
authMiddleware := auth.WithWebSocketTickets(application.WebSocketTickets(),
|
|
auth.Middleware(application.AuthDB(), application.ApplicationConfig()))
|
|
|
|
// Favicon handler
|
|
e.GET("/favicon.svg", func(c echo.Context) error {
|
|
data, err := embedDirStatic.ReadFile("static/favicon.svg")
|
|
if err != nil {
|
|
return c.NoContent(http.StatusNotFound)
|
|
}
|
|
c.Response().Header().Set("Content-Type", "image/svg+xml")
|
|
return c.Blob(http.StatusOK, "image/svg+xml", data)
|
|
})
|
|
|
|
// Static files - use fs.Sub to create a filesystem rooted at "static"
|
|
staticFS, err := fs.Sub(embedDirStatic, "static")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create static filesystem: %w", err)
|
|
}
|
|
e.StaticFS("/static", staticFS)
|
|
|
|
// Generated content directories
|
|
if application.ApplicationConfig().GeneratedContentDir != "" {
|
|
os.MkdirAll(application.ApplicationConfig().GeneratedContentDir, 0750)
|
|
audioPath := filepath.Join(application.ApplicationConfig().GeneratedContentDir, "audio")
|
|
imagePath := filepath.Join(application.ApplicationConfig().GeneratedContentDir, "images")
|
|
videoPath := filepath.Join(application.ApplicationConfig().GeneratedContentDir, "videos")
|
|
threeDPath := filepath.Join(application.ApplicationConfig().GeneratedContentDir, "3d")
|
|
|
|
os.MkdirAll(audioPath, 0750)
|
|
os.MkdirAll(imagePath, 0750)
|
|
os.MkdirAll(videoPath, 0750)
|
|
_ = os.MkdirAll(threeDPath, 0750)
|
|
|
|
// Go's built-in MIME table has no .glb entry and minimal containers
|
|
// ship no /etc/mime.types, so generated GLBs would otherwise be
|
|
// served as application/octet-stream.
|
|
_ = mime.AddExtensionType(".glb", "model/gltf-binary")
|
|
|
|
e.Static("/generated-audio", audioPath)
|
|
e.Static("/generated-images", imagePath)
|
|
e.Static("/generated-videos", videoPath)
|
|
e.Static("/generated-3d", threeDPath)
|
|
}
|
|
|
|
// Usage recording is initialised in application/startup.go and
|
|
// surfaced via application.StatsRecorder(); routes wire UsageMiddleware
|
|
// against that recorder regardless of auth state.
|
|
|
|
// Auth is applied to _all_ endpoints. Filtering out endpoints to bypass is
|
|
// the role of the exempt-path logic inside the middleware.
|
|
e.Use(authMiddleware)
|
|
|
|
// Feature and model access control (after auth middleware, before routes)
|
|
if application.AuthDB() != nil {
|
|
e.Use(auth.RequireRouteFeature(application.AuthDB()))
|
|
e.Use(auth.RequireModelAccess(application.AuthDB()))
|
|
e.Use(auth.RequireQuota(application.AuthDB()))
|
|
}
|
|
|
|
// CORS middleware. When CORS=true the operator must also specify the
|
|
// allowed origins; an empty allowlist would otherwise let Echo fall back
|
|
// to AllowOrigins=["*"], which is almost never what someone enabling
|
|
// "strict CORS" intended.
|
|
if application.ApplicationConfig().CORS {
|
|
if application.ApplicationConfig().CORSAllowOrigins == "" {
|
|
xlog.Warn("LOCALAI_CORS=true but LOCALAI_CORS_ALLOW_ORIGINS is empty; refusing to register a wildcard CORS policy. Set the allowlist or unset LOCALAI_CORS.")
|
|
} else {
|
|
corsConfig := middleware.CORSConfig{
|
|
AllowOrigins: strings.Split(application.ApplicationConfig().CORSAllowOrigins, ","),
|
|
}
|
|
e.Use(middleware.CORSWithConfig(corsConfig))
|
|
}
|
|
} else {
|
|
e.Use(middleware.CORS())
|
|
}
|
|
|
|
// CSRF middleware (enabled by default, disable with LOCALAI_DISABLE_CSRF=true)
|
|
//
|
|
// Protection relies on Echo's Sec-Fetch-Site header check (supported by all
|
|
// modern browsers). The legacy cookie+token approach is removed because
|
|
// Echo's Sec-Fetch-Site short-circuit never sets the cookie, so the frontend
|
|
// could never read a token to send back.
|
|
if !application.ApplicationConfig().DisableCSRF {
|
|
xlog.Debug("Enabling CSRF middleware (Sec-Fetch-Site mode)")
|
|
e.Use(auth.CSRFMiddleware())
|
|
}
|
|
|
|
// Admin middleware: enforces admin role when auth is enabled, no-op otherwise
|
|
var adminMiddleware echo.MiddlewareFunc
|
|
if application.AuthDB() != nil {
|
|
adminMiddleware = auth.RequireAdmin()
|
|
} else {
|
|
adminMiddleware = auth.NoopMiddleware()
|
|
}
|
|
|
|
// Feature middlewares: per-feature access control
|
|
agentsMw := auth.RequireFeature(application.AuthDB(), auth.FeatureAgents)
|
|
skillsMw := auth.RequireFeature(application.AuthDB(), auth.FeatureSkills)
|
|
collectionsMw := auth.RequireFeature(application.AuthDB(), auth.FeatureCollections)
|
|
mcpJobsMw := auth.RequireFeature(application.AuthDB(), auth.FeatureMCPJobs)
|
|
|
|
requestExtractor := httpMiddleware.NewRequestExtractor(application.ModelConfigLoader(), application.ModelLoader(), application.ApplicationConfig())
|
|
requestExtractor.SetFailoverManager(application.FailoverManager())
|
|
|
|
// Register auth routes (login, callback, API keys, user management)
|
|
routes.RegisterAuthRoutes(e, application)
|
|
|
|
// Register routing-module usage endpoints. Unlike /api/auth/usage
|
|
// these go through the StatsRecorder and work in no-auth single-user
|
|
// mode by attributing requests to the synthetic "local" user.
|
|
routes.RegisterUsageRoutes(e, application)
|
|
routes.RegisterPIIRoutes(e, application)
|
|
routes.RegisterSystemOneRoutes(e, application)
|
|
routes.RegisterMiddlewareRoutes(e, application)
|
|
|
|
routes.RegisterElevenLabsRoutes(e, requestExtractor, application.ModelConfigLoader(), application.ModelLoader(), application.ApplicationConfig(), application.AuthDB())
|
|
|
|
// Create opcache for tracking UI operations (used by both UI and LocalAI routes)
|
|
var opcache *galleryop.OpCache
|
|
if !application.ApplicationConfig().DisableWebUI {
|
|
opcache = galleryop.NewOpCache(application.GalleryService())
|
|
// In distributed mode, wire the NATS client + gallery store so this
|
|
// replica's OpCache stays in sync with peers — without this the
|
|
// /api/operations endpoint returns whatever this single replica
|
|
// happened to admit, and a load-balanced UI poll alternates between
|
|
// "operation visible" and "operation gone" between replicas.
|
|
if d := application.Distributed(); d != nil {
|
|
opcache.SetMessagingClient(d.Nats)
|
|
if d.DistStores != nil && d.DistStores.Gallery != nil {
|
|
opcache.SetGalleryStore(d.DistStores.Gallery)
|
|
}
|
|
if err := opcache.Start(application.ApplicationConfig().Context); err != nil {
|
|
xlog.Warn("OpCache distributed subscribe failed; running standalone", "error", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
mcpMw := auth.RequireFeature(application.AuthDB(), auth.FeatureMCP)
|
|
chatHistoryMw := auth.RequireFeature(application.AuthDB(), auth.FeatureChatHistory)
|
|
routes.RegisterLocalAIRoutes(e, requestExtractor, application.ModelConfigLoader(), application.ModelLoader(), application.ApplicationConfig(), application.GalleryService(), opcache, application.TemplatesEvaluator(), application, adminMiddleware, mcpJobsMw, mcpMw, chatHistoryMw)
|
|
routes.RegisterAgentPoolRoutes(e, application, agentsMw, skillsMw, collectionsMw)
|
|
// Fine-tuning routes
|
|
fineTuningMw := auth.RequireFeature(application.AuthDB(), auth.FeatureFineTuning)
|
|
// In distributed mode pass the shared NATS client + PostgreSQL store so
|
|
// fine-tune jobs stay consistent across replicas (the SyncedMap broadcasts
|
|
// mutations and hydrates from the DB); standalone passes nil for both.
|
|
var ftNats messaging.MessagingClient
|
|
var ftStore *distributed.FineTuneStore
|
|
if d := application.Distributed(); d != nil {
|
|
ftNats = d.Nats
|
|
if d.DistStores != nil && d.DistStores.FineTune != nil {
|
|
ftStore = d.DistStores.FineTune
|
|
}
|
|
}
|
|
ftService := finetune.NewFineTuneService(
|
|
application.ApplicationConfig(),
|
|
application.ModelLoader(),
|
|
application.ModelConfigLoader(),
|
|
ftNats,
|
|
ftStore,
|
|
)
|
|
routes.RegisterFineTuningRoutes(e, ftService, application.ApplicationConfig(), application, fineTuningMw)
|
|
|
|
// Quantization routes
|
|
quantizationMw := auth.RequireFeature(application.AuthDB(), auth.FeatureQuantization)
|
|
// In distributed mode pass the shared NATS client + PostgreSQL store so
|
|
// quantization jobs stay consistent across replicas (the SyncedMap broadcasts
|
|
// mutations and hydrates from the DB); standalone passes nil for both.
|
|
var quantNats messaging.MessagingClient
|
|
var quantStore *distributed.QuantStore
|
|
if d := application.Distributed(); d != nil {
|
|
quantNats = d.Nats
|
|
if d.DistStores != nil && d.DistStores.Quant != nil {
|
|
quantStore = d.DistStores.Quant
|
|
}
|
|
}
|
|
qService := quantization.NewQuantizationService(
|
|
application.ApplicationConfig(),
|
|
application.ModelLoader(),
|
|
application.ModelConfigLoader(),
|
|
quantNats,
|
|
quantStore,
|
|
)
|
|
routes.RegisterQuantizationRoutes(e, qService, application.ApplicationConfig(), application, quantizationMw)
|
|
|
|
// Node management routes (distributed mode)
|
|
distCfg := application.ApplicationConfig().Distributed
|
|
var registry *nodes.NodeRegistry
|
|
var remoteUnloader nodes.NodeCommandSender
|
|
var workerHTTPDial nodes.WorkerNetDialerFor
|
|
if d := application.Distributed(); d != nil {
|
|
registry = d.Registry
|
|
workerHTTPDial = d.WorkerHTTPDial
|
|
if d.Router != nil {
|
|
remoteUnloader = d.Router.Unloader()
|
|
}
|
|
}
|
|
natsCfg := distCfg.NatsAuthConfig()
|
|
routes.RegisterNodeSelfServiceRoutes(e, registry, distCfg.RegistrationToken, distCfg.AutoApproveNodes, application.AuthDB(), application.ApplicationConfig().Auth.APIKeyHMACSecret, natsCfg)
|
|
routes.RegisterNodeAdminRoutes(e, registry, remoteUnloader, application.GalleryService(), opcache, application.ApplicationConfig(), adminMiddleware, application.AuthDB(), application.ApplicationConfig().Auth.APIKeyHMACSecret, application.ApplicationConfig().Distributed.RegistrationToken, natsCfg, workerHTTPDial)
|
|
|
|
// Distributed SSE routes (job progress + agent events via NATS)
|
|
if d := application.Distributed(); d != nil {
|
|
if d.Dispatcher != nil {
|
|
e.GET("/api/agent/jobs/:id/progress", d.Dispatcher.SSEHandler(), mcpJobsMw)
|
|
}
|
|
if d.AgentBridge != nil {
|
|
e.GET("/api/agents/:name/sse/distributed", d.AgentBridge.SSEHandler(), agentsMw)
|
|
}
|
|
}
|
|
|
|
routes.RegisterOpenAIRoutes(e, requestExtractor, application)
|
|
routes.RegisterAnthropicRoutes(e, requestExtractor, application)
|
|
routes.RegisterOpenResponsesRoutes(e, requestExtractor, application)
|
|
routes.RegisterOllamaRoutes(e, requestExtractor, application)
|
|
if application.ApplicationConfig().OllamaAPIRootEndpoint {
|
|
routes.RegisterOllamaRootEndpoint(e)
|
|
}
|
|
if !application.ApplicationConfig().DisableWebUI {
|
|
routes.RegisterUIAPIRoutes(e, application.ModelConfigLoader(), application.ModelLoader(), application.ApplicationConfig(), application.GalleryService(), opcache, application, adminMiddleware)
|
|
routes.RegisterUIRoutes(e, application.ModelConfigLoader(), application.ApplicationConfig(), application.GalleryService(), adminMiddleware)
|
|
|
|
// Serve React SPA from / with SPA fallback via 404 handler
|
|
reactFS, fsErr := fs.Sub(reactUI, "react-ui/dist")
|
|
if fsErr != nil {
|
|
xlog.Warn("React UI not available (build with 'make core/http/react-ui/dist')", "error", fsErr)
|
|
} else {
|
|
serveIndex := func(c echo.Context) error {
|
|
indexHTML, err := reactUI.ReadFile("react-ui/dist/index.html")
|
|
if err != nil {
|
|
return c.String(http.StatusNotFound, "React UI not built")
|
|
}
|
|
// index.html names the content-hashed bundles, so it must never
|
|
// be cached: a stale copy pins the browser to the previous
|
|
// deploy's assets.
|
|
c.Response().Header().Set("Cache-Control", "no-cache")
|
|
// Inject <base href> for reverse-proxy support; baseURL comes
|
|
// from attacker-controllable Host / X-Forwarded-Host headers.
|
|
baseURL := httpMiddleware.BaseURL(c)
|
|
if baseURL != "" {
|
|
baseTag := `<base href="` + httpMiddleware.SecureBaseHref(baseURL) + `" />`
|
|
indexHTML = []byte(strings.Replace(string(indexHTML), "<head>", "<head>\n "+baseTag, 1))
|
|
}
|
|
// <base href> only changes how relative URLs resolve; path-absolute
|
|
// URLs (those starting with `/`) still resolve against the origin
|
|
// and would bypass the reverse-proxy prefix. Rewrite the internal
|
|
// path-absolute references emitted by the build so the browser
|
|
// requests them through the proxy under the prefix.
|
|
//
|
|
// HTML-escape the prefix before interpolating it into attributes:
|
|
// BasePathPrefix already gates X-Forwarded-Prefix via
|
|
// SafeForwardedPrefix, but the validator only blocks open-redirect
|
|
// shapes (// prefix, backslashes, control chars), not attribute
|
|
// breakout characters like `"`. Escaping makes this resilient
|
|
// even if the validator ever loosens.
|
|
if prefix := httpMiddleware.BasePathPrefix(c); prefix != "/" {
|
|
safePrefix := httpMiddleware.SecureBaseHref(prefix)
|
|
html := string(indexHTML)
|
|
html = strings.ReplaceAll(html, `="/assets/`, `="`+safePrefix+`assets/`)
|
|
html = strings.ReplaceAll(html, `="/favicon.svg"`, `="`+safePrefix+`favicon.svg"`)
|
|
indexHTML = []byte(html)
|
|
}
|
|
return c.HTMLBlob(http.StatusOK, indexHTML)
|
|
}
|
|
|
|
// Enable SPA fallback in the 404 handler for client-side routing
|
|
spaFallback = serveIndex
|
|
|
|
// Serve React SPA at /app
|
|
e.GET("/app", serveIndex)
|
|
e.GET("/app/*", serveIndex)
|
|
|
|
// prefixRedirect performs a redirect that preserves X-Forwarded-Prefix
|
|
// for reverse-proxy support. The prefix is forgeable on misconfigured
|
|
// proxy chains, so reject anything that isn't a same-origin path.
|
|
prefixRedirect := func(c echo.Context, target string) error {
|
|
if prefix, ok := httpMiddleware.SafeForwardedPrefix(c.Request().Header.Get("X-Forwarded-Prefix")); ok {
|
|
target = strings.TrimSuffix(prefix, "/") + target
|
|
}
|
|
return c.Redirect(http.StatusMovedPermanently, target)
|
|
}
|
|
|
|
// Redirect / to /app
|
|
e.GET("/", func(c echo.Context) error {
|
|
return prefixRedirect(c, "/app")
|
|
})
|
|
|
|
// Backward compatibility: redirect /browse/* to /app/*
|
|
e.GET("/browse", func(c echo.Context) error {
|
|
return prefixRedirect(c, "/app")
|
|
})
|
|
e.GET("/browse/*", func(c echo.Context) error {
|
|
p := c.Param("*")
|
|
return prefixRedirect(c, "/app/"+p)
|
|
})
|
|
|
|
// Serve React static assets (JS, CSS, etc.) and i18n locale JSONs
|
|
// from the embedded React build. cacheControl is stamped on every
|
|
// hit so the browser can reuse the bytes instead of re-fetching
|
|
// ~1.8 MB of bundle on each navigation.
|
|
serveReactSubdir := func(subdir, cacheControl string) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
p := subdir + "/" + c.Param("*")
|
|
f, err := reactFS.Open(p)
|
|
if err == nil {
|
|
defer f.Close()
|
|
stat, statErr := f.Stat()
|
|
if statErr == nil && !stat.IsDir() {
|
|
contentType := mime.TypeByExtension(filepath.Ext(p))
|
|
if contentType == "" {
|
|
contentType = echo.MIMEOctetStream
|
|
}
|
|
if cacheControl != "" {
|
|
c.Response().Header().Set("Cache-Control", cacheControl)
|
|
}
|
|
return c.Stream(http.StatusOK, contentType, f)
|
|
}
|
|
}
|
|
return echo.NewHTTPError(http.StatusNotFound)
|
|
}
|
|
}
|
|
// Vite content-hashes everything under /assets (Manage-DrwQK63f.js),
|
|
// so a given URL can never change content: cache it for a year and
|
|
// skip revalidation entirely. Locale JSONs keep stable names, so
|
|
// they only get a short TTL.
|
|
e.GET("/assets/*", serveReactSubdir("assets", immutableAssetCacheControl))
|
|
e.GET("/locales/*", serveReactSubdir("locales", "public, max-age=300"))
|
|
}
|
|
}
|
|
routes.RegisterJINARoutes(e, requestExtractor, application.ModelConfigLoader(), application.ModelLoader(), application.ApplicationConfig())
|
|
|
|
// Note: 404 handling is done via HTTPErrorHandler above, no need for catch-all route
|
|
|
|
// HTTP server timeouts.
|
|
//
|
|
// - ReadHeaderTimeout: bounds the slow-headers Slowloris case. 30s is
|
|
// enough for a real client on a poor connection but cuts off a
|
|
// drip-feeding attacker.
|
|
// - IdleTimeout: bounds idle keep-alive connections.
|
|
//
|
|
// We deliberately leave ReadTimeout and WriteTimeout at 0:
|
|
// - Request bodies can be multi-GB model/dataset uploads.
|
|
// - Chat-completion and SSE responses can stream for many minutes.
|
|
// Operators who need stricter limits should front the server with a
|
|
// reverse proxy that terminates slow clients per-request.
|
|
e.Server.ReadHeaderTimeout = 30 * time.Second
|
|
e.Server.IdleTimeout = 120 * time.Second
|
|
|
|
// Log startup message
|
|
e.Server.RegisterOnShutdown(func() {
|
|
xlog.Info("LocalAI API server shutting down")
|
|
})
|
|
|
|
return e, nil
|
|
}
|