diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 430f699..c9c00ed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,9 +42,9 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - # Go 1.26.10 fixes GO-2026-6809 in crypto/x509. + # Go 1.26.11 fixes GO-2026-6809 in crypto/x509 and GO-2026-6859 in net/http. # go.mod retains the downstream-consumer language floor. - go-version: "1.26.10" + go-version: "1.26.11" cache: true - name: Verify modules @@ -106,7 +106,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: "1.26.10" + go-version: "1.26.11" cache: true - name: Download suite @@ -131,7 +131,7 @@ jobs: # checked AGAINST, separate from the toolchain version. uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: "1.26.10" + go-version: "1.26.11" cache: true - name: golangci-lint @@ -287,15 +287,15 @@ jobs: runs-on: ubuntu-latest permissions: contents: read - # Block on reachable vulnerabilities. Go 1.26.10 fixes the crypto/x509 - # finding GO-2026-6809. Keep this toolchain + # Block on reachable vulnerabilities. Go 1.26.11 fixes the crypto/x509 + # finding GO-2026-6809 and the net/http finding GO-2026-6859. Keep this toolchain # aligned with the test jobs and Docker builder when patching Go. # Do not bypass this gate with continue-on-error. steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: "1.26.10" + go-version: "1.26.11" cache: true - name: Install govulncheck # Pin govulncheck so a future major release (e.g. new finding @@ -421,7 +421,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: "1.26.10" + go-version: "1.26.11" cache: true # Build llm-init image first so the compose file's @@ -683,7 +683,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: "1.26.10" + go-version: "1.26.11" cache: true - name: Build static binary for release artifact diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index f4b45cc..b51f457 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -64,7 +64,7 @@ jobs: - name: Set up Go uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: - go-version: "1.26.10" + go-version: "1.26.11" cache: true - name: Initialize CodeQL diff --git a/CHANGELOG.md b/CHANGELOG.md index ffe34ba..fdc66de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,23 @@ and the project adheres to [Semantic Versioning 2.0](https://semver.org/spec/v2. ## [Unreleased] +### Added + +- `llm-init comfyui` runs the Model Console of a single-workflow ComfyUI + app. It reads a JSON app config (`COMFY_APP_CONFIG`) listing the models the + workflow needs, downloads them into `COMFY_MODELS_DIR` with resume and + sha256 verification (a marker under `.llm-init-verified/` skips re-hashing + on restart), re-fetches a model that disappears, probes ComfyUI's + `GET /system_stats`, and serves `GET /api/status` (ready only when every + model is verified and ComfyUI answers) plus a progress page at `/`. Models + of 64 MiB or more are fetched over `COMFY_DOWNLOAD_CONNECTIONS` (default 8) + byte ranges, checkpointed to `.part.json`, since Hugging Face's CDN + throttles each connection. The LLM mode is untouched. +- `llm-init comfyui` honours `HF_ENDPOINT`: huggingface.co model URLs are + fetched from that mirror instead (same `//resolve//`), so + an Olares with an internal mirror (`OLARES_SYSTEM_HUGGINGFACE_SERVICE`) + downloads from it and warms it for other machines. + ### Changed - A chat card whose `max_output_tokens` is unset, or as large as its diff --git a/Dockerfile b/Dockerfile index 9ece32e..7256aa7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,15 +2,15 @@ # Stage 1: build a static Linux binary with version metadata injected. # -# Builder is pinned to golang:1.26.10-alpine to match the CI test/lint/vulncheck -# floor pinned in .github/workflows/ci.yml (`go-version: "1.26.10"`). The +# Builder is pinned to golang:1.26.11-alpine to match the CI test/lint/vulncheck +# floor pinned in .github/workflows/ci.yml (`go-version: "1.26.11"`). The # downstream-consumer floor in go.mod (`go 1.23.0`) is intentionally # separate — see CHANGELOG entry for v1.0.3. # # Pinned by digest for reproducible builds (the tag is kept inline so # Dependabot's docker ecosystem can resolve + bump both in lockstep). # Digest is the multi-arch image index (covers amd64 + arm64). -FROM --platform=$BUILDPLATFORM golang:1.26.10-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba AS builder +FROM --platform=$BUILDPLATFORM golang:1.26.11-alpine@sha256:ae52b5bc6ed045a9ed26ab03dc19327a802a9cc9aa8b27ed57f5c6b60579b0bb AS builder ARG TARGETOS ARG TARGETARCH diff --git a/cmd/llm-init/comfyui.go b/cmd/llm-init/comfyui.go new file mode 100644 index 0000000..b817fb5 --- /dev/null +++ b/cmd/llm-init/comfyui.go @@ -0,0 +1,120 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + "time" + + "github.com/llm-init/llm-init/internal/comfyconsole" + "github.com/llm-init/llm-init/internal/config" + "github.com/llm-init/llm-init/internal/version" +) + +// runComfyUI is `llm-init comfyui`: the Model Console of a single-workflow +// ComfyUI app (see internal/comfyconsole). It reads its own small env set +// and never loads the LLM config. +// +// COMFY_APP_CONFIG app config JSON (default /etc/comfy-app/app-config.json) +// COMFY_MODELS_DIR ComfyUI models root (required) +// COMFYUI_URL ComfyUI base URL (default http://127.0.0.1:8188) +// PORT listen port (default 8090) +// HF_TOKEN optional bearer token for huggingface.co downloads +// HF_ENDPOINT optional Hugging Face mirror; huggingface.co model URLs are fetched from it +// COMFY_DOWNLOAD_CONNECTIONS concurrent byte ranges per large model (default 8) +// COMFY_GROUPS model groups to install first: ids separated by commas, "all", or empty for the first +// COMFY_SELECTION_FILE where the installed groups are kept across restarts (on persistent storage) +// LOG_LEVEL / LOG_FORMAT as in the LLM mode +func runComfyUI(getenv config.Getenv, stderr *os.File) int { + env := func(k, def string) string { + if v := strings.TrimSpace(getenv(k)); v != "" { + return v + } + return def + } + logger := newLogger(env("LOG_LEVEL", "info"), env("LOG_FORMAT", config.LogFormatJSON), stderr) + slog.SetDefault(logger) + + cfgFile := env("COMFY_APP_CONFIG", "/etc/comfy-app/app-config.json") + cfg, err := comfyconsole.LoadConfig(cfgFile) + if err != nil { + fmt.Fprintf(stderr, "config error: %v\n", err) + return exitConfig + } + mirrored, err := cfg.UseMirror(env("HF_ENDPOINT", "")) + if err != nil { + fmt.Fprintf(stderr, "config error: %v\n", err) + return exitConfig + } + modelsDir := env("COMFY_MODELS_DIR", "") + if modelsDir == "" { + fmt.Fprintln(stderr, "config error: COMFY_MODELS_DIR is required") + return exitConfig + } + var headers http.Header + if tok := env("HF_TOKEN", ""); tok != "" { + headers = http.Header{"Authorization": {"Bearer " + tok}} + } + + conns := 0 + if v := env("COMFY_DOWNLOAD_CONNECTIONS", ""); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 { + fmt.Fprintf(stderr, "config error: COMFY_DOWNLOAD_CONNECTIONS must be a positive integer, got %q\n", v) + return exitConfig + } + conns = n + } + + selFile := env("COMFY_SELECTION_FILE", "") + selected, err := comfyconsole.LoadSelection(cfg, selFile, env("COMFY_GROUPS", "")) + if err != nil { + fmt.Fprintf(stderr, "config error: %v\n", err) + return exitConfig + } + + console := comfyconsole.New(comfyconsole.Options{ + Config: cfg, + ModelsDir: modelsDir, + ComfyURL: strings.TrimRight(env("COMFYUI_URL", "http://127.0.0.1:8188"), "/"), + Headers: headers, + Connections: conns, + Selected: selected, + SelectionFile: selFile, + Logger: logger, + }) + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + addr := net.JoinHostPort("", env("PORT", "8090")) + ln, err := net.Listen("tcp", addr) + if err != nil { + fmt.Fprintf(stderr, "listen %s: %v\n", addr, err) + return exitControlPlane + } + srv := &http.Server{Handler: console.Handler(), ReadHeaderTimeout: 10 * time.Second} + go func() { + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { + logger.Error("console server", "err", err) + stop() + } + }() + logger.Info("comfyui console started", "version", version.Version, "addr", addr, + "config", cfgFile, "models_dir", modelsDir, "models", len(cfg.Models), "groups", selected, "hf_mirrored", mirrored) + + console.Run(ctx) + + shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownGracePeriod) + defer cancel() + _ = srv.Shutdown(shutdownCtx) + return exitOK +} diff --git a/cmd/llm-init/main.go b/cmd/llm-init/main.go index 529edb9..f3da2b3 100644 --- a/cmd/llm-init/main.go +++ b/cmd/llm-init/main.go @@ -71,6 +71,9 @@ func run(args []string, stdout, stderr *os.File, getenv config.Getenv) int { if getenv == nil { getenv = os.Getenv } + if len(args) > 0 && args[0] == "comfyui" { + return runComfyUI(getenv, stderr) + } fs := flag.NewFlagSet("llm-init", flag.ContinueOnError) fs.SetOutput(stderr) diff --git a/internal/comfyconsole/config.go b/internal/comfyconsole/config.go new file mode 100644 index 0000000..8199271 --- /dev/null +++ b/internal/comfyconsole/config.go @@ -0,0 +1,184 @@ +// Package comfyconsole is llm-init's comfyui mode: the Model Console of a +// single-workflow ComfyUI app. +// +// It reads one app config shared with the Easy UI, downloads the models the +// workflow needs into ComfyUI's model tree (resumable, sha256-verified), +// probes ComfyUI's GET /system_stats, and reports both through +// GET /api/status. The app is ready only when every model is verified and +// ComfyUI answers. Nothing here touches the LLM lifecycle: the mode is +// entered through `llm-init comfyui` and shares only internal/fetch. +package comfyconsole + +import ( + "encoding/json" + "errors" + "fmt" + "net/url" + "os" + "path" + "regexp" + "strings" +) + +// AppConfig is the single source of truth for the app: the workflow the +// Easy UI submits and the models it needs. The console reads only Models +// and Groups; Workflow is kept raw so the Easy UI owns its schema. +type AppConfig struct { + Workflow json.RawMessage `json:"workflow"` + // Models are always installed. + Models []Model `json:"models"` + // Groups are optional model sets on top of Models, e.g. one per + // precision; the selection (see LoadSelection) says which are kept. + Groups []Group `json:"groups,omitempty"` +} + +// Group is one installable model set. A file may belong to several groups +// but not to a group and Models. +type Group struct { + ID string `json:"id"` + Label string `json:"label"` + Models []Model `json:"models"` +} + +var groupIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,31}$`) + +// Model is one weight file. Dir is the ComfyUI model category directory +// (checkpoints, vae, clip, diffusion_models, ...) relative to the models +// root. +type Model struct { + Name string `json:"name"` + Dir string `json:"dir"` + URL string `json:"url"` + SHA256 string `json:"sha256"` + Size int64 `json:"size"` +} + +// RelPath is the model's path under the models root. +func (m Model) RelPath() string { return path.Join(m.Dir, m.Name) } + +// LoadConfig reads and validates the app config. The file is JSON so the +// Easy UI can fetch the same bytes without a YAML parser. +func LoadConfig(file string) (*AppConfig, error) { + raw, err := os.ReadFile(file) + if err != nil { + return nil, fmt.Errorf("read app config: %w", err) + } + var cfg AppConfig + if err := json.Unmarshal(raw, &cfg); err != nil { + return nil, fmt.Errorf("parse app config %s: %w", file, err) + } + if err := cfg.validate(); err != nil { + return nil, fmt.Errorf("app config %s: %w", file, err) + } + return &cfg, nil +} + +func (c *AppConfig) validate() error { + if len(c.Models) == 0 && len(c.Groups) == 0 { + return errors.New("models is empty") + } + shared := make(map[string]bool, len(c.Models)) + for i, m := range c.Models { + if err := m.validate(); err != nil { + return fmt.Errorf("models[%d]: %w", i, err) + } + if shared[m.RelPath()] { + return fmt.Errorf("models[%d]: duplicate path %s", i, m.RelPath()) + } + shared[m.RelPath()] = true + } + ids := map[string]bool{} + inGroups := map[string]Model{} + for i, g := range c.Groups { + if !groupIDRe.MatchString(g.ID) || ids[g.ID] { + return fmt.Errorf("groups[%d]: id %q must be unique and match %s", i, g.ID, groupIDRe) + } + ids[g.ID] = true + if len(g.Models) == 0 { + return fmt.Errorf("groups[%d] %s: models is empty", i, g.ID) + } + own := map[string]bool{} + for j, m := range g.Models { + if err := m.validate(); err != nil { + return fmt.Errorf("groups[%d] %s models[%d]: %w", i, g.ID, j, err) + } + p := m.RelPath() + switch prev, ok := inGroups[p]; { + case shared[p]: + return fmt.Errorf("groups[%d] %s: %s is also in models", i, g.ID, p) + case own[p]: + return fmt.Errorf("groups[%d] %s: duplicate path %s", i, g.ID, p) + case ok && (prev.SHA256 != m.SHA256 || prev.Size != m.Size): + return fmt.Errorf("groups[%d] %s: %s differs from another group's file of that path", i, g.ID, p) + } + own[p] = true + inGroups[p] = m + } + } + return nil +} + +func (m Model) validate() error { + if m.Name == "" || strings.ContainsAny(m.Name, `/\`) || m.Name == "." || m.Name == ".." { + return fmt.Errorf("invalid name %q", m.Name) + } + if m.Dir == "" || path.IsAbs(m.Dir) || path.Clean(m.Dir) != m.Dir || strings.HasPrefix(m.Dir, "..") { + return fmt.Errorf("%s: dir must be a clean relative path, got %q", m.Name, m.Dir) + } + u, err := url.Parse(m.URL) + if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" { + return fmt.Errorf("%s: invalid url %q", m.Name, m.URL) + } + if len(m.SHA256) != 64 { + return fmt.Errorf("%s: sha256 must be 64 hex chars", m.Name) + } + if m.Size <= 0 { + return fmt.Errorf("%s: size must be positive", m.Name) + } + return nil +} + +func (c *AppConfig) group(id string) *Group { + for i := range c.Groups { + if c.Groups[i].ID == id { + return &c.Groups[i] + } + } + return nil +} + +// UseMirror points every huggingface.co model URL at a Hugging Face mirror +// (HF_ENDPOINT, e.g. Olares' OLARES_SYSTEM_HUGGINGFACE_SERVICE), keeping the +// //resolve// part. It returns how many URLs changed. An +// empty endpoint, or huggingface.co itself, changes nothing. +func (c *AppConfig) UseMirror(endpoint string) (int, error) { + endpoint = strings.TrimSpace(endpoint) + if endpoint == "" { + return 0, nil + } + base, err := url.Parse(endpoint) + if err != nil || (base.Scheme != "http" && base.Scheme != "https") || base.Host == "" { + return 0, fmt.Errorf("HF_ENDPOINT %q is not an http(s) URL", endpoint) + } + if base.Host == "huggingface.co" { + return 0, nil + } + n := 0 + lists := [][]Model{c.Models} + for _, g := range c.Groups { + lists = append(lists, g.Models) + } + for _, ms := range lists { + for i, m := range ms { + u, err := url.Parse(m.URL) + if err != nil || u.Host != "huggingface.co" { + continue + } + u.Scheme, u.Host = base.Scheme, base.Host + u.Path = strings.TrimRight(base.Path, "/") + u.Path + ms[i].URL = u.String() + n++ + } + } + return n, nil +} diff --git a/internal/comfyconsole/console.go b/internal/comfyconsole/console.go new file mode 100644 index 0000000..579e393 --- /dev/null +++ b/internal/comfyconsole/console.go @@ -0,0 +1,387 @@ +package comfyconsole + +import ( + "context" + "crypto/tls" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net" + "net/http" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" + + "github.com/llm-init/llm-init/internal/fetch" + "github.com/llm-init/llm-init/internal/progress" +) + +// Model states reported by /api/status. +const ( + StatePending = "pending" + StateDownloading = "downloading" + StateVerifying = "verifying" + StateDone = "done" + StateError = "error" +) + +// Backend states reported by /api/status. +const ( + BackendDown = "down" + BackendUp = "up" +) + +// markerDir holds one file per verified model under the models root, so a +// restart does not re-hash tens of GB. A marker only counts while the +// model's size and mtime still match what was hashed. +const markerDir = ".llm-init-verified" + +// Options wires a Console. Zero intervals take the defaults below. +type Options struct { + Config *AppConfig + ModelsDir string + ComfyURL string // e.g. http://127.0.0.1:8188 + Headers http.Header + Downloader fetch.RangeDownloader + Client *http.Client // for the /system_stats probe + + // Selected are the groups to keep (LoadSelection); SelectionFile is + // rewritten when they change. + Selected []string + SelectionFile string + + // Models of at least ParallelMin bytes are fetched over Connections + // concurrent byte ranges through DownloadClient; smaller ones, or an + // upstream without range support, use Downloader. + Connections int + ParallelMin int64 + SegmentRetries int + DownloadClient *http.Client + + ProbeInterval time.Duration + RecheckEvery time.Duration // how often finished models are re-stat'ed + RetryBackoff time.Duration + RetryBackoffMx time.Duration + Logger *slog.Logger +} + +// Console tracks the models and the ComfyUI backend. +type Console struct { + opts Options + mu sync.Mutex + items []*itemState + selected map[string]bool + passCancel context.CancelFunc + // passMu is held while a pass over the models runs, so RemoveGroup can + // delete files only once no download writes them. + passMu sync.Mutex + kick chan struct{} + backend atomic.Bool +} + +type itemState struct { + model Model + groups []string // empty: shared + state string + downloaded int64 + err string +} + +// New returns a Console with defaults applied. +func New(opts Options) *Console { + if opts.Downloader == nil { + opts.Downloader = fetch.New(nil) + } + if opts.Client == nil { + opts.Client = &http.Client{Timeout: 3 * time.Second} + } + if opts.Connections <= 0 { + opts.Connections = 8 + } + if opts.ParallelMin <= 0 { + opts.ParallelMin = 64 << 20 + } + if opts.SegmentRetries <= 0 { + opts.SegmentRetries = 30 + } + if opts.DownloadClient == nil { + // No overall timeout: a range of a 20 GB file streams for minutes. + // HTTP/1.1 only: over HTTP/2 every range shares one TCP connection, + // which the CDN throttles as a single stream. + opts.DownloadClient = &http.Client{Transport: &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext, + TLSHandshakeTimeout: 15 * time.Second, + ResponseHeaderTimeout: 60 * time.Second, + IdleConnTimeout: 90 * time.Second, + MaxIdleConnsPerHost: 32, + TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, + }} + } + if opts.ProbeInterval <= 0 { + opts.ProbeInterval = 2 * time.Second + } + if opts.RecheckEvery <= 0 { + opts.RecheckEvery = time.Minute + } + if opts.RetryBackoff <= 0 { + opts.RetryBackoff = 10 * time.Second + } + if opts.RetryBackoffMx <= 0 { + opts.RetryBackoffMx = 5 * time.Minute + } + if opts.Logger == nil { + opts.Logger = slog.Default() + } + c := &Console{opts: opts, selected: map[string]bool{}, kick: make(chan struct{}, 1)} + for _, m := range opts.Config.Models { + c.items = append(c.items, &itemState{model: m, state: StatePending}) + } + byPath := map[string]*itemState{} + for _, g := range opts.Config.Groups { + for _, m := range g.Models { + it := byPath[m.RelPath()] + if it == nil { + it = &itemState{model: m, state: StatePending} + byPath[m.RelPath()] = it + c.items = append(c.items, it) + } + it.groups = append(it.groups, g.ID) + } + } + for _, id := range opts.Selected { + c.selected[id] = true + } + return c +} + +// Run drives downloads and the backend probe until ctx ends. +func (c *Console) Run(ctx context.Context) { + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); c.probeLoop(ctx) }() + go func() { defer wg.Done(); c.modelLoop(ctx) }() + wg.Wait() +} + +func (c *Console) probeLoop(ctx context.Context) { + t := time.NewTicker(c.opts.ProbeInterval) + defer t.Stop() + for { + up := c.probe(ctx) + if prev := c.backend.Swap(up); prev != up { + c.opts.Logger.Info("comfyui backend state changed", "up", up) + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} + +func (c *Console) probe(ctx context.Context) bool { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.opts.ComfyURL+"/system_stats", nil) + if err != nil { + return false + } + resp, err := c.opts.Client.Do(req) + if err != nil { + return false + } + resp.Body.Close() + return resp.StatusCode == http.StatusOK +} + +// modelLoop ensures every wanted model in order, then keeps re-checking so +// a model deleted or moved from the ComfyUI side is fetched again. A group +// change cancels the pass and starts the next one at once. +func (c *Console) modelLoop(ctx context.Context) { + failures := 0 + for { + failed := c.pass(ctx) + if ctx.Err() != nil { + return + } + wait := c.opts.RecheckEvery + if failed { + wait = min(c.opts.RetryBackoff< 1 && m.Size >= c.opts.ParallelMin { + c.set(it, StateDownloading, 0, "") + err := c.downloadParallel(ctx, m, dest, func(n int64) { c.set(it, StateDownloading, n, "") }) + if !errors.Is(err, errNoRanges) { + return err + } + c.opts.Logger.Warn("upstream ignored Range, downloading in one stream", "model", m.RelPath()) + _ = os.Remove(dest + ".part.json") + _ = os.Remove(dest + ".part") + } + var have int64 + if info, err := os.Stat(dest + ".part"); err == nil { + have = info.Size() + } + c.set(it, StateDownloading, have, "") + return c.opts.Downloader.Download(ctx, fetch.RangeOptions{ + URL: m.URL, + DestPath: dest, + ExpectedSize: m.Size, + Headers: c.opts.Headers, + }, &bytesSink{c: c, it: it}) +} + +func (c *Console) verify(ctx context.Context, it *itemState, dest, marker string) error { + m := it.model + c.set(it, StateVerifying, m.Size, "") + if err := c.opts.Downloader.Verify(ctx, dest, m.Size, m.SHA256); err != nil { + return fmt.Errorf("verify: %w", err) + } + info, err := os.Stat(dest) + if err != nil { + return fmt.Errorf("verify: %w", err) + } + if err := writeMarker(marker, m, info); err != nil { + // Only costs a re-hash on the next start. + c.opts.Logger.Warn("write verify marker", "model", m.RelPath(), "err", err) + } + c.set(it, StateDone, m.Size, "") + c.opts.Logger.Info("model ready", "model", m.RelPath()) + return nil +} + +// set updates an item. downloaded < 0 keeps the current byte count. +func (c *Console) set(it *itemState, state string, downloaded int64, errMsg string) { + c.mu.Lock() + defer c.mu.Unlock() + it.state = state + if downloaded >= 0 { + it.downloaded = downloaded + } + it.err = errMsg +} + +type bytesSink struct { + progress.NopSink + c *Console + it *itemState +} + +func (s *bytesSink) OnBytes(delta int64) { + s.c.mu.Lock() + s.it.downloaded += delta + s.c.mu.Unlock() +} + +type markerFile struct { + SHA256 string `json:"sha256"` + Size int64 `json:"size"` + ModTime int64 `json:"mtime_unix_nano"` +} + +func markerMatches(file string, m Model, info os.FileInfo) bool { + raw, err := os.ReadFile(file) + if err != nil { + return false + } + var mk markerFile + if json.Unmarshal(raw, &mk) != nil { + return false + } + return mk.SHA256 == m.SHA256 && mk.Size == info.Size() && mk.ModTime == info.ModTime().UnixNano() +} + +func writeMarker(file string, m Model, info os.FileInfo) error { + if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + return err + } + raw, err := json.Marshal(markerFile{SHA256: m.SHA256, Size: info.Size(), ModTime: info.ModTime().UnixNano()}) + if err != nil { + return err + } + tmp := file + ".tmp" + if err := os.WriteFile(tmp, raw, 0o644); err != nil { + return err + } + return os.Rename(tmp, file) +} diff --git a/internal/comfyconsole/console_test.go b/internal/comfyconsole/console_test.go new file mode 100644 index 0000000..ba7e8d7 --- /dev/null +++ b/internal/comfyconsole/console_test.go @@ -0,0 +1,352 @@ +package comfyconsole + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +func sum(b []byte) string { h := sha256.Sum256(b); return hex.EncodeToString(h[:]) } + +// fixture serves one model file (Range + HEAD via ServeContent) and a +// ComfyUI /system_stats whose answer the test controls. +type fixture struct { + srv *httptest.Server + payload []byte + gets atomic.Int32 + ranged atomic.Int64 // bytes served to Range requests + up atomic.Bool +} + +func newFixture(t *testing.T) *fixture { + t.Helper() + f := &fixture{payload: bytes.Repeat([]byte("comfy-weights-"), 4096)} + f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/model.safetensors": + if r.Method == http.MethodGet { + f.gets.Add(1) + } + cw := &countingWriter{ResponseWriter: w} + http.ServeContent(cw, r, "model.safetensors", time.Unix(0, 0), bytes.NewReader(f.payload)) + if r.Header.Get("Range") != "" { + f.ranged.Add(cw.n) + } + case "/norange.safetensors": + f.gets.Add(1) + _, _ = w.Write(f.payload) + case "/system_stats": + if !f.up.Load() { + http.Error(w, "starting", http.StatusServiceUnavailable) + return + } + _, _ = w.Write([]byte(`{}`)) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(f.srv.Close) + return f +} + +func (f *fixture) config(sha string) *AppConfig { + return &AppConfig{Models: []Model{{ + Name: "model.safetensors", Dir: "diffusion_models", + URL: f.srv.URL + "/model.safetensors", SHA256: sha, Size: int64(len(f.payload)), + }}} +} + +func (f *fixture) console(cfg *AppConfig, dir string) *Console { + return New(Options{ + Config: cfg, ModelsDir: dir, ComfyURL: f.srv.URL, + ProbeInterval: 10 * time.Millisecond, RecheckEvery: 20 * time.Millisecond, + RetryBackoff: 20 * time.Millisecond, RetryBackoffMx: 20 * time.Millisecond, + }) +} + +func waitFor(t *testing.T, c *Console, what string, ok func(Status) bool) Status { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + st := c.Status() + if ok(st) { + return st + } + if time.Now().After(deadline) { + raw, _ := json.Marshal(st) + t.Fatalf("timed out waiting for %s; last status %s", what, raw) + } + time.Sleep(10 * time.Millisecond) + } +} + +func run(t *testing.T, c *Console) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { c.Run(ctx); close(done) }() + t.Cleanup(func() { cancel(); <-done }) +} + +func TestConsole_DownloadsVerifiesAndBecomesReady(t *testing.T) { + t.Parallel() + f := newFixture(t) + dir := t.TempDir() + c := f.console(f.config(sum(f.payload)), dir) + run(t, c) + + st := waitFor(t, c, "models done", func(s Status) bool { return s.Models.State == StateDone }) + if st.Ready { + t.Fatal("ready with ComfyUI down") + } + if st.Models.Progress != 1 || st.Models.Items[0].Downloaded != int64(len(f.payload)) { + t.Fatalf("progress = %v downloaded = %d", st.Models.Progress, st.Models.Items[0].Downloaded) + } + got, err := os.ReadFile(filepath.Join(dir, "diffusion_models", "model.safetensors")) + if err != nil || !bytes.Equal(got, f.payload) { + t.Fatalf("model file not written correctly: %v", err) + } + + f.up.Store(true) + waitFor(t, c, "ready", func(s Status) bool { return s.Ready && s.Backend.State == BackendUp }) + f.up.Store(false) + waitFor(t, c, "not ready after backend loss", func(s Status) bool { return !s.Ready }) +} + +func TestConsole_VerifiedModelIsNotFetchedAgain(t *testing.T) { + t.Parallel() + f := newFixture(t) + dir := t.TempDir() + cfg := f.config(sum(f.payload)) + + first := f.console(cfg, dir) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { first.Run(ctx); close(done) }() + waitFor(t, first, "first pass done", func(s Status) bool { return s.Models.State == StateDone }) + cancel() + <-done + gets := f.gets.Load() + + second := f.console(cfg, dir) + run(t, second) + waitFor(t, second, "second pass done", func(s Status) bool { return s.Models.State == StateDone }) + if f.gets.Load() != gets { + t.Fatalf("restart re-downloaded a verified model: GETs %d -> %d", gets, f.gets.Load()) + } +} + +func TestConsole_RedownloadsDeletedModel(t *testing.T) { + t.Parallel() + f := newFixture(t) + dir := t.TempDir() + c := f.console(f.config(sum(f.payload)), dir) + run(t, c) + waitFor(t, c, "done", func(s Status) bool { return s.Models.State == StateDone }) + + dest := filepath.Join(dir, "diffusion_models", "model.safetensors") + if err := os.Remove(dest); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(5 * time.Second) + for { + if _, err := os.Stat(dest); err == nil && f.gets.Load() >= 2 { + break + } + if time.Now().After(deadline) { + t.Fatal("deleted model was not downloaded again") + } + time.Sleep(10 * time.Millisecond) + } + waitFor(t, c, "done again", func(s Status) bool { return s.Models.State == StateDone }) +} + +func TestConsole_ShaMismatchReportsError(t *testing.T) { + t.Parallel() + f := newFixture(t) + dir := t.TempDir() + c := f.console(f.config(strings.Repeat("0", 64)), dir) + run(t, c) + + st := waitFor(t, c, "error", func(s Status) bool { return s.Models.State == StateError }) + if !strings.Contains(st.Models.Items[0].Error, "sha256") || st.Ready { + t.Fatalf("unexpected status: %+v", st.Models.Items[0]) + } + if _, err := os.Stat(filepath.Join(dir, "diffusion_models", "model.safetensors")); !os.IsNotExist(err) { + t.Fatalf("corrupt file kept on disk: %v", err) + } +} + +func TestHandler_StatusShape(t *testing.T) { + t.Parallel() + f := newFixture(t) + c := f.console(f.config(sum(f.payload)), t.TempDir()) + rec := httptest.NewRecorder() + c.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/status", nil)) + if rec.Code != http.StatusOK { + t.Fatalf("status code %d", rec.Code) + } + var body map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + for _, k := range []string{"ready", "models", "backend"} { + if _, ok := body[k]; !ok { + t.Errorf("missing key %q in %s", k, rec.Body.String()) + } + } + rec = httptest.NewRecorder() + c.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/readyz", nil)) + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("readyz before ready = %d", rec.Code) + } + rec = httptest.NewRecorder() + c.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil)) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Model Console") { + t.Fatalf("console page = %d", rec.Code) + } +} + +func TestLoadConfig_Validation(t *testing.T) { + t.Parallel() + good := `{"workflow":{"file":"w.json"},"models":[{"name":"a.safetensors","dir":"vae","url":"https://x/a","sha256":"` + strings.Repeat("a", 64) + `","size":1}]}` + cases := map[string]string{ + "ok": good, + "empty": `{"models":[]}`, + "traversal": strings.Replace(good, `"dir":"vae"`, `"dir":"../etc"`, 1), + "slash name": strings.Replace(good, `"a.safetensors"`, `"x/a.safetensors"`, 1), + "short sha": strings.Replace(good, strings.Repeat("a", 64), "abc", 1), + "no size": strings.Replace(good, `"size":1`, `"size":0`, 1), + "bad url": strings.Replace(good, `https://x/a`, `ftp://x/a`, 1), + } + for name, body := range cases { + file := filepath.Join(t.TempDir(), "c.json") + if err := os.WriteFile(file, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + _, err := LoadConfig(file) + if (err == nil) != (name == "ok") { + t.Errorf("%s: err = %v", name, err) + } + } +} + +type countingWriter struct { + http.ResponseWriter + n int64 +} + +func (w *countingWriter) Write(b []byte) (int, error) { + n, err := w.ResponseWriter.Write(b) + w.n += int64(n) + return n, err +} + +func (f *fixture) parallelConsole(cfg *AppConfig, dir string) *Console { + c := f.console(cfg, dir) + c.opts.Connections = 4 + c.opts.ParallelMin = 1 + return c +} + +func TestConsole_ParallelRangesAssembleTheFile(t *testing.T) { + t.Parallel() + f := newFixture(t) + dir := t.TempDir() + c := f.parallelConsole(f.config(sum(f.payload)), dir) + run(t, c) + waitFor(t, c, "done", func(s Status) bool { return s.Models.State == StateDone }) + + if got := f.gets.Load(); got < 4 { + t.Fatalf("GETs = %d, want one per range", got) + } + dest := filepath.Join(dir, "diffusion_models", "model.safetensors") + for _, leftover := range []string{dest + ".part", dest + ".part.json"} { + if _, err := os.Stat(leftover); !os.IsNotExist(err) { + t.Errorf("%s left behind: %v", leftover, err) + } + } +} + +func TestConsole_ParallelResumesFromCheckpoint(t *testing.T) { + t.Parallel() + f := newFixture(t) + dir := t.TempDir() + cfg := f.config(sum(f.payload)) + dest := filepath.Join(dir, "diffusion_models", "model.safetensors") + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + t.Fatal(err) + } + + // Two of four ranges already on disk. + size := int64(len(f.payload)) + st := newPartState(size, 4) + part := make([]byte, size) + for _, s := range st.Segments[:2] { + copy(part[s.Start:s.End+1], f.payload[s.Start:s.End+1]) + s.Next = s.End + 1 + } + if err := os.WriteFile(dest+".part", part, 0o644); err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(st) + if err := os.WriteFile(dest+".part.json", raw, 0o644); err != nil { + t.Fatal(err) + } + + c := f.parallelConsole(cfg, dir) + run(t, c) + waitFor(t, c, "done", func(s Status) bool { return s.Models.State == StateDone }) + remaining := size - (st.Segments[1].End + 1) + if got := f.ranged.Load(); got != remaining { + t.Fatalf("served %d bytes on resume, want %d", got, remaining) + } +} + +func TestConsole_ParallelFallsBackWithoutRanges(t *testing.T) { + t.Parallel() + f := newFixture(t) + dir := t.TempDir() + cfg := f.config(sum(f.payload)) + cfg.Models[0].URL = f.srv.URL + "/norange.safetensors" + c := f.parallelConsole(cfg, dir) + run(t, c) + waitFor(t, c, "done", func(s Status) bool { return s.Models.State == StateDone }) + got, err := os.ReadFile(filepath.Join(dir, "diffusion_models", "model.safetensors")) + if err != nil || !bytes.Equal(got, f.payload) { + t.Fatalf("fallback produced a bad file: %v", err) + } +} + +func TestUseMirror(t *testing.T) { + cfg := &AppConfig{Models: []Model{ + {Name: "a.safetensors", URL: "https://huggingface.co/Comfy-Org/MiniMax-H3/resolve/main/vae/a.safetensors"}, + {Name: "b.safetensors", URL: "https://example.com/b.safetensors"}, + }} + n, err := cfg.UseMirror("https://hf-mirrors-internal.joinolares.cn/") + if err != nil || n != 1 { + t.Fatalf("n=%d err=%v", n, err) + } + if got := cfg.Models[0].URL; got != "https://hf-mirrors-internal.joinolares.cn/Comfy-Org/MiniMax-H3/resolve/main/vae/a.safetensors" { + t.Errorf("mirrored URL = %s", got) + } + if cfg.Models[1].URL != "https://example.com/b.safetensors" { + t.Errorf("non-HF URL changed: %s", cfg.Models[1].URL) + } + if n, _ := cfg.UseMirror("https://huggingface.co"); n != 0 { + t.Errorf("huggingface.co endpoint rewrote %d URLs", n) + } + if _, err := cfg.UseMirror("ftp://x"); err == nil { + t.Error("ftp endpoint accepted") + } +} diff --git a/internal/comfyconsole/groups.go b/internal/comfyconsole/groups.go new file mode 100644 index 0000000..99ed485 --- /dev/null +++ b/internal/comfyconsole/groups.go @@ -0,0 +1,197 @@ +package comfyconsole + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" +) + +// Errors from AddGroup and RemoveGroup; the HTTP handler maps them to 404 and 409. +var ( + ErrNoGroups = errors.New("this app has no model groups") + ErrUnknownGroup = errors.New("unknown model group") + ErrLastGroup = errors.New("at least one model group must stay installed") +) + +type selectionFile struct { + Groups []string `json:"groups"` +} + +// LoadSelection returns the groups to keep installed. The selection file +// (on persistent storage) wins; without one, initial is used: a comma list +// of group ids, "all", or empty for the first group. The result is written +// back so later starts keep what the user changed. +func LoadSelection(cfg *AppConfig, file, initial string) ([]string, error) { + if len(cfg.Groups) == 0 { + return nil, nil + } + var ids []string + if file != "" { + if raw, err := os.ReadFile(file); err == nil { + var sf selectionFile + if err := json.Unmarshal(raw, &sf); err != nil { + return nil, fmt.Errorf("selection file %s: %w", file, err) + } + for _, id := range sf.Groups { + if cfg.group(id) != nil { + ids = append(ids, id) + } + } + } else if !errors.Is(err, os.ErrNotExist) { + return nil, err + } + } + if len(ids) == 0 { + switch initial = strings.TrimSpace(initial); initial { + case "": + ids = []string{cfg.Groups[0].ID} + case "all": + for _, g := range cfg.Groups { + ids = append(ids, g.ID) + } + default: + for _, id := range strings.Split(initial, ",") { + id = strings.TrimSpace(id) + if cfg.group(id) == nil { + return nil, fmt.Errorf("COMFY_GROUPS: %w %q", ErrUnknownGroup, id) + } + ids = append(ids, id) + } + } + } + return ids, saveSelection(file, ids) +} + +func saveSelection(file string, ids []string) error { + if file == "" { + return nil + } + ids = append([]string(nil), ids...) + sort.Strings(ids) + raw, err := json.Marshal(selectionFile{Groups: ids}) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil { + return err + } + tmp := file + ".tmp" + if err := os.WriteFile(tmp, raw, 0o644); err != nil { + return err + } + return os.Rename(tmp, file) +} + +// wanted reports whether an item is kept: shared, or in a selected group. +// Callers hold c.mu. +func (c *Console) wanted(it *itemState) bool { + if len(it.groups) == 0 { + return true + } + for _, g := range it.groups { + if c.selected[g] { + return true + } + } + return false +} + +func (c *Console) selectedIDs() []string { + var ids []string + for _, g := range c.opts.Config.Groups { + if c.selected[g.ID] { + ids = append(ids, g.ID) + } + } + return ids +} + +// AddGroup selects a group; its models download in the next pass. +func (c *Console) AddGroup(id string) error { + if len(c.opts.Config.Groups) == 0 { + return ErrNoGroups + } + if c.opts.Config.group(id) == nil { + return ErrUnknownGroup + } + c.mu.Lock() + if c.selected[id] { + c.mu.Unlock() + return nil + } + c.selected[id] = true + err := saveSelection(c.opts.SelectionFile, c.selectedIDs()) + c.mu.Unlock() + c.opts.Logger.Info("model group added", "group", id) + c.wake() + return err +} + +// RemoveGroup unselects a group and deletes its files that no other +// selected group uses (shared models stay). A download in progress is +// stopped first. +func (c *Console) RemoveGroup(id string) error { + if len(c.opts.Config.Groups) == 0 { + return ErrNoGroups + } + if c.opts.Config.group(id) == nil { + return ErrUnknownGroup + } + c.mu.Lock() + if !c.selected[id] { + c.mu.Unlock() + return nil + } + if len(c.selectedIDs()) == 1 { + c.mu.Unlock() + return ErrLastGroup + } + delete(c.selected, id) + err := saveSelection(c.opts.SelectionFile, c.selectedIDs()) + if c.passCancel != nil { + c.passCancel() + } + c.mu.Unlock() + + c.passMu.Lock() + for _, it := range c.items { + c.mu.Lock() + drop := !c.wanted(it) && contains(it.groups, id) + c.mu.Unlock() + if !drop { + continue + } + dest := filepath.Join(c.opts.ModelsDir, filepath.FromSlash(it.model.RelPath())) + for _, p := range []string{dest, dest + ".part", dest + ".part.json", + filepath.Join(c.opts.ModelsDir, markerDir, filepath.FromSlash(it.model.RelPath())+".json")} { + if rerr := os.Remove(p); rerr != nil && !errors.Is(rerr, os.ErrNotExist) { + c.opts.Logger.Warn("remove model file", "path", p, "err", rerr) + } + } + c.set(it, StatePending, 0, "") + } + c.passMu.Unlock() + c.opts.Logger.Info("model group removed", "group", id) + c.wake() + return err +} + +func (c *Console) wake() { + select { + case c.kick <- struct{}{}: + default: + } +} + +func contains(xs []string, x string) bool { + for _, y := range xs { + if y == x { + return true + } + } + return false +} diff --git a/internal/comfyconsole/groups_test.go b/internal/comfyconsole/groups_test.go new file mode 100644 index 0000000..29ad70f --- /dev/null +++ b/internal/comfyconsole/groups_test.go @@ -0,0 +1,228 @@ +package comfyconsole + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" +) + +// groupFixture serves /f/ from payloads; /f/slow writes half of its +// payload and then hangs until the client goes away. +type groupFixture struct { + srv *httptest.Server + payloads map[string][]byte +} + +func newGroupFixture(t *testing.T) *groupFixture { + t.Helper() + g := &groupFixture{payloads: map[string][]byte{}} + for _, n := range []string{"shared", "a", "b", "both", "slow"} { + g.payloads[n] = bytes.Repeat([]byte(n+"-weights-"), 2048) + } + g.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/system_stats" { + _, _ = w.Write([]byte(`{}`)) + return + } + name := strings.TrimPrefix(r.URL.Path, "/f/") + p, ok := g.payloads[name] + if !ok { + http.NotFound(w, r) + return + } + if name == "slow" { + w.Header().Set("Content-Length", strconv.Itoa(len(p))) + if r.Method == http.MethodHead { + return + } + _, _ = w.Write(p[:len(p)/2]) + w.(http.Flusher).Flush() + <-r.Context().Done() + return + } + http.ServeContent(w, r, name, time.Unix(0, 0), bytes.NewReader(p)) + })) + t.Cleanup(g.srv.Close) + return g +} + +func (g *groupFixture) model(name string) Model { + p := g.payloads[name] + return Model{Name: name + ".safetensors", Dir: "diffusion_models", URL: g.srv.URL + "/f/" + name, SHA256: sum(p), Size: int64(len(p))} +} + +func (g *groupFixture) config() *AppConfig { + return &AppConfig{ + Models: []Model{g.model("shared")}, + Groups: []Group{ + {ID: "a", Label: "A", Models: []Model{g.model("a"), g.model("both")}}, + {ID: "b", Label: "B", Models: []Model{g.model("b"), g.model("both")}}, + {ID: "slow", Label: "Slow", Models: []Model{g.model("slow")}}, + }, + } +} + +func groupState(st Status, id string) GroupStatus { + for _, g := range st.Groups { + if g.ID == id { + return g + } + } + return GroupStatus{} +} + +func exists(dir, name string) bool { + _, err := os.Stat(filepath.Join(dir, "diffusion_models", name+".safetensors")) + return err == nil +} + +func TestLoadSelection(t *testing.T) { + t.Parallel() + cfg := newGroupFixture(t).config() + dir := t.TempDir() + for initial, want := range map[string]string{"": "a", "all": "a,b,slow", "b, a": "b,a"} { + got, err := LoadSelection(cfg, "", initial) + if err != nil || strings.Join(got, ",") != want { + t.Errorf("LoadSelection(%q) = %v, %v; want %s", initial, got, err, want) + } + } + if _, err := LoadSelection(cfg, "", "fp8"); err == nil { + t.Error("unknown COMFY_GROUPS accepted") + } + + file := filepath.Join(dir, "sel", "groups.json") + if got, _ := LoadSelection(cfg, file, "b"); strings.Join(got, ",") != "b" { + t.Fatalf("first start = %v", got) + } + if got, _ := LoadSelection(cfg, file, "a"); strings.Join(got, ",") != "b" { + t.Fatalf("the selection file must win over COMFY_GROUPS, got %v", got) + } + _ = os.WriteFile(file, []byte(`{"groups":["gone"]}`), 0o644) + if got, _ := LoadSelection(cfg, file, "a"); strings.Join(got, ",") != "a" { + t.Fatalf("stale selection should fall back to COMFY_GROUPS, got %v", got) + } + if got, _ := LoadSelection(&AppConfig{Models: cfg.Models}, file, "a"); got != nil { + t.Fatalf("no groups: %v", got) + } +} + +func TestGroupsValidation(t *testing.T) { + t.Parallel() + g := newGroupFixture(t) + bad := g.config() + bad.Groups[0].Models = append(bad.Groups[0].Models, g.model("shared")) + if err := bad.validate(); err == nil || !strings.Contains(err.Error(), "also in models") { + t.Errorf("shared file in a group: %v", err) + } + bad = g.config() + bad.Groups[1].Models[1].SHA256 = sum([]byte("other")) + if err := bad.validate(); err == nil || !strings.Contains(err.Error(), "differs") { + t.Errorf("same path, other file: %v", err) + } + bad = g.config() + bad.Groups[1].ID = "a" + if err := bad.validate(); err == nil { + t.Error("duplicate group id accepted") + } + ok := g.config() + ok.Models = nil + if err := ok.validate(); err != nil { + t.Errorf("groups without shared models: %v", err) + } +} + +func TestGroups_AddAndRemove(t *testing.T) { + t.Parallel() + g := newGroupFixture(t) + dir := t.TempDir() + selFile := filepath.Join(dir, "groups.json") + cfg := g.config() + sel, err := LoadSelection(cfg, selFile, "a") + if err != nil { + t.Fatal(err) + } + c := New(Options{Config: cfg, ModelsDir: dir, ComfyURL: g.srv.URL, Selected: sel, SelectionFile: selFile, + ProbeInterval: 10 * time.Millisecond, RecheckEvery: time.Hour, RetryBackoff: 20 * time.Millisecond, RetryBackoffMx: 20 * time.Millisecond}) + run(t, c) + h := c.Handler() + call := func(method, id string) int { + rr := httptest.NewRecorder() + h.ServeHTTP(rr, httptest.NewRequest(method, "/api/groups/"+id, nil)) + return rr.Code + } + + st := waitFor(t, c, "ready with group a", func(s Status) bool { return s.Ready }) + if a, b := groupState(st, "a"), groupState(st, "b"); a.State != StateDone || !a.Selected || b.State != StateAbsent || b.Selected { + t.Fatalf("groups a=%+v b=%+v", a, b) + } + if len(st.Models.Items) != 3 || !exists(dir, "shared") || !exists(dir, "both") || exists(dir, "b") { + t.Fatalf("only shared and group a should be on disk; items %+v", st.Models.Items) + } + + if code := call(http.MethodPut, "b"); code != http.StatusOK { + t.Fatalf("PUT b = %d", code) + } + waitFor(t, c, "group b installed", func(s Status) bool { return groupState(s, "b").State == StateDone }) + if code := call(http.MethodDelete, "a"); code != http.StatusOK { + t.Fatalf("DELETE a = %d", code) + } + if exists(dir, "a") || !exists(dir, "both") || !exists(dir, "shared") { + t.Fatal("deleting a must remove a.safetensors and keep files group b or every group uses") + } + st = waitFor(t, c, "a absent, still ready", func(s Status) bool { return groupState(s, "a").State == StateAbsent && s.Ready }) + if len(st.Models.Items) != 3 { + t.Fatalf("items after delete: %+v", st.Models.Items) + } + if code := call(http.MethodDelete, "b"); code != http.StatusConflict { + t.Fatalf("deleting the last group = %d, want 409", code) + } + if code := call(http.MethodPut, "fp8"); code != http.StatusNotFound { + t.Fatalf("PUT unknown = %d, want 404", code) + } + var saved selectionFile + raw, _ := os.ReadFile(selFile) + if json.Unmarshal(raw, &saved) != nil || strings.Join(saved.Groups, ",") != "b" { + t.Fatalf("selection file = %s", raw) + } +} + +func TestGroups_RemoveStopsDownload(t *testing.T) { + t.Parallel() + g := newGroupFixture(t) + dir := t.TempDir() + c := New(Options{Config: g.config(), ModelsDir: dir, ComfyURL: g.srv.URL, Selected: []string{"a"}, + ProbeInterval: 10 * time.Millisecond, RecheckEvery: time.Hour, RetryBackoff: 20 * time.Millisecond, RetryBackoffMx: 20 * time.Millisecond}) + run(t, c) + waitFor(t, c, "group a", func(s Status) bool { return groupState(s, "a").State == StateDone }) + if err := c.AddGroup("slow"); err != nil { + t.Fatal(err) + } + waitFor(t, c, "slow downloading", func(s Status) bool { + gs := groupState(s, "slow") + return gs.State == StateDownloading && gs.Downloaded > 0 + }) + done := make(chan error, 1) + go func() { done <- c.RemoveGroup("slow") }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("RemoveGroup did not stop the download") + } + matches, _ := filepath.Glob(filepath.Join(dir, "diffusion_models", "slow.safetensors*")) + if len(matches) != 0 { + t.Fatalf("left behind: %v", matches) + } + if st := c.Status(); groupState(st, "slow").State != StateAbsent || !st.Ready { + t.Fatalf("after removing slow: %+v ready=%v", groupState(st, "slow"), st.Ready) + } +} diff --git a/internal/comfyconsole/parallel.go b/internal/comfyconsole/parallel.go new file mode 100644 index 0000000..07033a1 --- /dev/null +++ b/internal/comfyconsole/parallel.go @@ -0,0 +1,228 @@ +package comfyconsole + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "sync" + "sync/atomic" + "time" +) + +// Hugging Face's CDN throttles each connection (about 1.6 MiB/s measured +// on a home line) while several connections add up, so large models are +// fetched as N byte ranges written in place into .part. Progress is +// checkpointed to .part.json so a restart resumes every range. + +// errNoRanges means the upstream ignored Range; the caller falls back to +// the single-stream downloader. +var errNoRanges = errors.New("upstream does not serve byte ranges") + +type segment struct { + Start int64 `json:"start"` + End int64 `json:"end"` // inclusive + Next int64 `json:"next"` +} + +type partState struct { + Size int64 `json:"size"` + Segments []*segment `json:"segments"` +} + +func newPartState(size int64, conns int) *partState { + st := &partState{Size: size} + step := (size + int64(conns) - 1) / int64(conns) + for start := int64(0); start < size; start += step { + end := min(start+step, size) - 1 + st.Segments = append(st.Segments, &segment{Start: start, End: end, Next: start}) + } + return st +} + +func loadPartState(file string, size int64, conns int) *partState { + raw, err := os.ReadFile(file) + if err == nil { + var st partState + if json.Unmarshal(raw, &st) == nil && st.Size == size && len(st.Segments) > 0 { + return &st + } + } + return newPartState(size, conns) +} + +// downloadParallel fetches m into dest with conns concurrent range requests. +// onBytes receives the absolute byte count so far. +func (c *Console) downloadParallel(ctx context.Context, m Model, dest string, onBytes func(int64)) error { + part := dest + ".part" + stateFile := part + ".json" + conns := c.opts.Connections + + st := loadPartState(stateFile, m.Size, conns) + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + return err + } + f, err := os.OpenFile(part, os.O_RDWR|os.O_CREATE, 0o644) + if err != nil { + return err + } + defer f.Close() + if info, err := f.Stat(); err != nil { + return err + } else if info.Size() != m.Size { + if err := f.Truncate(m.Size); err != nil { + return fmt.Errorf("preallocate: %w", err) + } + } + + var mu sync.Mutex // guards segment Next values while checkpointing + var have atomic.Int64 + for _, s := range st.Segments { + have.Add(s.Next - s.Start) + } + onBytes(have.Load()) + + save := func() { + mu.Lock() + raw, _ := json.Marshal(st) + mu.Unlock() + tmp := stateFile + ".tmp" + if os.WriteFile(tmp, raw, 0o644) == nil { + _ = os.Rename(tmp, stateFile) + } + } + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + errs := make(chan error, len(st.Segments)) + var wg sync.WaitGroup + for _, s := range st.Segments { + if s.Next > s.End { + continue + } + wg.Add(1) + go func(s *segment) { + defer wg.Done() + if err := c.fetchSegment(ctx, m, f, s, &mu, func(n int64) { onBytes(have.Add(n)) }); err != nil { + errs <- err + cancel() + } + }(s) + } + + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + tick := time.NewTicker(5 * time.Second) + defer tick.Stop() +loop: + for { + select { + case <-done: + break loop + case <-tick.C: + save() + } + } + save() + close(errs) + if err := <-errs; err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + if err := f.Sync(); err != nil { + return err + } + if err := f.Close(); err != nil { + return err + } + if err := os.Rename(part, dest); err != nil { + return err + } + _ = os.Remove(stateFile) + return nil +} + +// fetchSegment streams one range, retrying from where it stopped. +func (c *Console) fetchSegment(ctx context.Context, m Model, f *os.File, s *segment, mu *sync.Mutex, onBytes func(int64)) error { + buf := make([]byte, 1<<20) + failures := 0 + for { + mu.Lock() + next := s.Next + mu.Unlock() + if next > s.End { + return nil + } + err := c.fetchRange(ctx, m, f, next, s, mu, buf, onBytes) + if err == nil || errors.Is(err, errNoRanges) || ctx.Err() != nil { + if ctx.Err() != nil { + return ctx.Err() + } + return err + } + failures++ + if failures > c.opts.SegmentRetries { + return fmt.Errorf("range %d-%d: %w", s.Start, s.End, err) + } + wait := min(time.Second< 0 { + if _, werr := f.WriteAt(buf[:n], off); werr != nil { + return werr + } + off += int64(n) + mu.Lock() + s.Next = off + mu.Unlock() + onBytes(int64(n)) + } + if rerr == io.EOF { + break + } + if rerr != nil { + return rerr + } + } + if off <= s.End { + return io.ErrUnexpectedEOF + } + return nil +} diff --git a/internal/comfyconsole/static/index.html b/internal/comfyconsole/static/index.html new file mode 100644 index 0000000..99a9a74 --- /dev/null +++ b/internal/comfyconsole/static/index.html @@ -0,0 +1,112 @@ + + + + + +Model Console + + + +
+

Model Console

+

Loading…

+
+
ComfyUI—
+
Models
+
+
+ +
+
+ + + diff --git a/internal/comfyconsole/status.go b/internal/comfyconsole/status.go new file mode 100644 index 0000000..7a68725 --- /dev/null +++ b/internal/comfyconsole/status.go @@ -0,0 +1,189 @@ +package comfyconsole + +import ( + "embed" + "encoding/json" + "errors" + "io/fs" + "net/http" +) + +// Status is the body of GET /api/status. +type Status struct { + Ready bool `json:"ready"` + Models ModelsStatus `json:"models"` + Groups []GroupStatus `json:"groups,omitempty"` + Backend BackendStatus `json:"backend"` +} + +// GroupStatus is one model group. State is StateAbsent while unselected, +// else the aggregate of its own models. +type GroupStatus struct { + ID string `json:"id"` + Label string `json:"label"` + Selected bool `json:"selected"` + State string `json:"state"` + Progress float64 `json:"progress"` + Downloaded int64 `json:"downloaded"` + Size int64 `json:"size"` +} + +// StateAbsent is an unselected group. +const StateAbsent = "absent" + +// ModelsStatus aggregates the models kept: shared and selected groups. +type ModelsStatus struct { + State string `json:"state"` + Progress float64 `json:"progress"` + Items []ItemStatus `json:"items"` +} + +// ItemStatus is one model. +type ItemStatus struct { + Name string `json:"name"` + Dir string `json:"dir"` + State string `json:"state"` + Downloaded int64 `json:"downloaded"` + Size int64 `json:"size"` + Error string `json:"error,omitempty"` +} + +// BackendStatus is the ComfyUI probe result. +type BackendStatus struct { + State string `json:"state"` +} + +// Status snapshots the console. +func (c *Console) Status() Status { + c.mu.Lock() + var st Status + var have, total int64 + counts := map[string]int{} + sharedDone := true + byGroup := map[string][]*itemState{} + for _, it := range c.items { + for _, g := range it.groups { + byGroup[g] = append(byGroup[g], it) + } + if !c.wanted(it) { + continue + } + if len(it.groups) == 0 && it.state != StateDone { + sharedDone = false + } + st.Models.Items = append(st.Models.Items, ItemStatus{ + Name: it.model.Name, + Dir: it.model.Dir, + State: it.state, + Downloaded: min(it.downloaded, it.model.Size), + Size: it.model.Size, + Error: it.err, + }) + counts[it.state]++ + have += min(it.downloaded, it.model.Size) + total += it.model.Size + } + groupDone := len(c.opts.Config.Groups) == 0 + for _, g := range c.opts.Config.Groups { + gs := GroupStatus{ID: g.ID, Label: g.Label, Selected: c.selected[g.ID], State: StateAbsent} + gc := map[string]int{} + for _, it := range byGroup[g.ID] { + gs.Size += it.model.Size + if gs.Selected { + gs.Downloaded += min(it.downloaded, it.model.Size) + gc[it.state]++ + } + } + if gs.Selected { + gs.State = aggregate(gc, len(byGroup[g.ID])) + groupDone = groupDone || gs.State == StateDone + } + if gs.Size > 0 { + gs.Progress = float64(gs.Downloaded) / float64(gs.Size) + } + st.Groups = append(st.Groups, gs) + } + c.mu.Unlock() + + st.Models.State = aggregate(counts, len(st.Models.Items)) + if total > 0 { + st.Models.Progress = float64(have) / float64(total) + } + st.Backend.State = BackendDown + if c.backend.Load() { + st.Backend.State = BackendUp + } + // With groups, one installed group is enough: another may still be + // downloading after the user added it. + st.Ready = sharedDone && groupDone && st.Backend.State == BackendUp + return st +} + +func aggregate(counts map[string]int, n int) string { + switch { + case counts[StateDone] == n: + return StateDone + case counts[StateError] > 0: + return StateError + case counts[StateDownloading] > 0: + return StateDownloading + case counts[StateVerifying] > 0: + return StateVerifying + default: + return StatePending + } +} + +//go:embed static +var staticFS embed.FS + +// Handler serves the console. Paths are relative so the app's nginx can +// mount it under any prefix (the design uses /console/). +func (c *Console) Handler() http.Handler { + m := http.NewServeMux() + m.HandleFunc("GET /api/status", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, c.Status()) + }) + m.HandleFunc("GET /livez", func(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) + }) + m.HandleFunc("GET /readyz", func(w http.ResponseWriter, _ *http.Request) { + st := c.Status() + code := http.StatusOK + if !st.Ready { + code = http.StatusServiceUnavailable + } + writeJSON(w, code, map[string]bool{"ready": st.Ready}) + }) + m.HandleFunc("PUT /api/groups/{id}", func(w http.ResponseWriter, r *http.Request) { + c.groupChange(w, c.AddGroup(r.PathValue("id"))) + }) + m.HandleFunc("DELETE /api/groups/{id}", func(w http.ResponseWriter, r *http.Request) { + c.groupChange(w, c.RemoveGroup(r.PathValue("id"))) + }) + sub, _ := fs.Sub(staticFS, "static") + m.Handle("GET /", http.FileServer(http.FS(sub))) + return m +} + +func (c *Console) groupChange(w http.ResponseWriter, err error) { + if err == nil { + writeJSON(w, http.StatusOK, c.Status()) + return + } + status := http.StatusInternalServerError + switch { + case errors.Is(err, ErrUnknownGroup), errors.Is(err, ErrNoGroups): + status = http.StatusNotFound + case errors.Is(err, ErrLastGroup): + status = http.StatusConflict + } + writeJSON(w, status, map[string]string{"error": err.Error()}) +} + +func writeJSON(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Cache-Control", "no-store") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} diff --git a/tests/integration/faultsrv/Dockerfile b/tests/integration/faultsrv/Dockerfile index f5f68a2..c270755 100644 --- a/tests/integration/faultsrv/Dockerfile +++ b/tests/integration/faultsrv/Dockerfile @@ -10,7 +10,7 @@ # The compose files pass `-addr 0.0.0.0:9000` so the server is reachable # from the llm-init container over the compose network. -FROM golang:1.26.10-alpine@sha256:27f2d3b83cfc5803c8078f8e730af0f7c431bf067afaec8f60a36fb763187cba AS build +FROM golang:1.26.11-alpine@sha256:ae52b5bc6ed045a9ed26ab03dc19327a802a9cc9aa8b27ed57f5c6b60579b0bb AS build WORKDIR /src COPY go.mod go.sum* ./ RUN go mod download