From 6d28e069a78b367035fced0405c9124969b290a8 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 02:24:23 -0600 Subject: [PATCH 01/37] feat(api): create internal/api package structure Set up the foundation package structure for the HTTP API server that will serve the management CLI and web dashboard. Files created: - doc.go: Package documentation with endpoint overview - config.go: Config struct with DefaultConfig(), Validate(), and builder methods - errors.go: Package-specific error definitions - types.go: JSON request/response type definitions - routes.go: Route registration with /health endpoint - server.go: Server struct with Start/Stop lifecycle - server_test.go: Comprehensive unit tests (11 tests) The API server follows existing GoClusterFS patterns: - Config pattern from internal/cache - Manager lifecycle pattern from internal/journal - Dependency injection (no global singletons) All tests pass (11/11). Task: #5588 --- internal/api/config.go | 139 ++++++++++++++++ internal/api/doc.go | 46 ++++++ internal/api/errors.go | 24 +++ internal/api/routes.go | 25 +++ internal/api/server.go | 154 +++++++++++++++++ internal/api/server_test.go | 319 ++++++++++++++++++++++++++++++++++++ internal/api/types.go | 45 +++++ 7 files changed, 752 insertions(+) create mode 100644 internal/api/config.go create mode 100644 internal/api/doc.go create mode 100644 internal/api/errors.go create mode 100644 internal/api/routes.go create mode 100644 internal/api/server.go create mode 100644 internal/api/server_test.go create mode 100644 internal/api/types.go diff --git a/internal/api/config.go b/internal/api/config.go new file mode 100644 index 00000000..c1859b96 --- /dev/null +++ b/internal/api/config.go @@ -0,0 +1,139 @@ +package api + +import ( + "fmt" + "net" + "net/url" + "strings" + "time" +) + +// Config holds the configuration for the API server. +type Config struct { + // ListenAddr is the address to listen on (e.g., ":8080" or "127.0.0.1:8080"). + // Default: ":8080" + ListenAddr string + + // AuthToken is the Bearer token for API authentication. + // If empty, authentication is disabled. + // Default: "" (disabled) + AuthToken string + + // CORSOrigins is the list of allowed CORS origins. + // If empty, CORS is disabled. + // Use "*" to allow all origins (not recommended for production). + // Default: nil (disabled) + CORSOrigins []string + + // ReadTimeout is the maximum duration for reading the entire request. + // Default: 30s + ReadTimeout time.Duration + + // WriteTimeout is the maximum duration for writing the response. + // Default: 30s + WriteTimeout time.Duration + + // IdleTimeout is the maximum duration to wait for the next request. + // Default: 60s + IdleTimeout time.Duration + + // ShutdownTimeout is the maximum duration to wait for graceful shutdown. + // Default: 10s + ShutdownTimeout time.Duration +} + +// DefaultConfig returns a Config with sensible defaults. +func DefaultConfig() Config { + return Config{ + ListenAddr: ":8080", + AuthToken: "", + CORSOrigins: nil, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 60 * time.Second, + ShutdownTimeout: 10 * time.Second, + } +} + +// Validate checks the configuration for errors. +func (c *Config) Validate() error { + // Validate listen address + if c.ListenAddr == "" { + return fmt.Errorf("%w: listen address cannot be empty", ErrInvalidListenAddr) + } + + // Check if it's a valid host:port format + host, port, err := net.SplitHostPort(c.ListenAddr) + if err != nil { + return fmt.Errorf("%w: %v", ErrInvalidListenAddr, err) + } + + // If host is specified, validate it + if host != "" { + ip := net.ParseIP(host) + if ip == nil { + // Not an IP, check if it could be a hostname + if strings.ContainsAny(host, " \t\n\r") { + return fmt.Errorf("%w: invalid host %q", ErrInvalidListenAddr, host) + } + } + } + + // Port should be a number or empty (for dynamic allocation) + if port != "" && port != "0" { + // net.SplitHostPort already validated it's a valid port string + _ = port + } + + // Validate timeouts + if c.ReadTimeout < 0 { + return fmt.Errorf("%w: read timeout must be >= 0", ErrInvalidTimeout) + } + if c.WriteTimeout < 0 { + return fmt.Errorf("%w: write timeout must be >= 0", ErrInvalidTimeout) + } + if c.IdleTimeout < 0 { + return fmt.Errorf("%w: idle timeout must be >= 0", ErrInvalidTimeout) + } + if c.ShutdownTimeout < 0 { + return fmt.Errorf("%w: shutdown timeout must be >= 0", ErrInvalidTimeout) + } + + // Validate CORS origins + for _, origin := range c.CORSOrigins { + if origin == "*" { + continue // Wildcard is allowed + } + if origin == "" { + return fmt.Errorf("%w: empty origin", ErrInvalidCORSOrigin) + } + // Parse as URL to validate format + u, err := url.Parse(origin) + if err != nil { + return fmt.Errorf("%w: %v", ErrInvalidCORSOrigin, err) + } + if u.Scheme == "" || u.Host == "" { + return fmt.Errorf("%w: origin must have scheme and host: %q", ErrInvalidCORSOrigin, origin) + } + } + + return nil +} + +// WithListenAddr returns a copy of the config with a new listen address. +func (c Config) WithListenAddr(addr string) Config { + c.ListenAddr = addr + return c +} + +// WithAuthToken returns a copy of the config with a new auth token. +func (c Config) WithAuthToken(token string) Config { + c.AuthToken = token + return c +} + +// WithCORSOrigins returns a copy of the config with new CORS origins. +func (c Config) WithCORSOrigins(origins ...string) Config { + c.CORSOrigins = origins + return c +} diff --git a/internal/api/doc.go b/internal/api/doc.go new file mode 100644 index 00000000..d73d2bd9 --- /dev/null +++ b/internal/api/doc.go @@ -0,0 +1,46 @@ +// Package api provides the HTTP JSON API server for GoClusterFS. +// +// The API server runs embedded within the mount process and exposes +// endpoints for health checks, status queries, statistics, and +// administrative operations. It is consumed by the gfsctl CLI tool +// and the web dashboard. +// +// # Endpoints +// +// The following endpoints are available: +// +// - GET /health - Health check (always returns 200) +// - GET /api/v1/status - Filesystem status overview +// - GET /api/v1/stats/* - Detailed component statistics +// - GET /metrics - Prometheus metrics export +// +// # Authentication +// +// Authentication is via Bearer token when configured. Set the AuthToken +// in Config to enable authentication. When enabled, all endpoints except +// /health require a valid Authorization header: +// +// Authorization: Bearer +// +// # Configuration +// +// Use DefaultConfig() to get sensible defaults, then customize as needed: +// +// cfg := api.DefaultConfig() +// cfg.ListenAddr = ":9090" +// cfg.AuthToken = "secret-token" +// server, err := api.NewServer(cfg) +// +// # Lifecycle +// +// The server follows the standard Start/Stop pattern: +// +// server, err := api.NewServer(cfg) +// if err != nil { +// log.Fatal(err) +// } +// if err := server.Start(ctx); err != nil { +// log.Fatal(err) +// } +// defer server.Stop() +package api diff --git a/internal/api/errors.go b/internal/api/errors.go new file mode 100644 index 00000000..ea2afdfb --- /dev/null +++ b/internal/api/errors.go @@ -0,0 +1,24 @@ +package api + +import "errors" + +// Package-level errors for the API server. +var ( + // ErrServerAlreadyStarted is returned when Start is called on an already running server. + ErrServerAlreadyStarted = errors.New("api: server already started") + + // ErrServerNotStarted is returned when operations require a running server. + ErrServerNotStarted = errors.New("api: server not started") + + // ErrInvalidListenAddr is returned when the listen address is malformed. + ErrInvalidListenAddr = errors.New("api: invalid listen address") + + // ErrInvalidTimeout is returned when a timeout value is invalid. + ErrInvalidTimeout = errors.New("api: invalid timeout value (must be positive)") + + // ErrInvalidCORSOrigin is returned when a CORS origin is malformed. + ErrInvalidCORSOrigin = errors.New("api: invalid CORS origin") + + // ErrShutdownTimeout is returned when graceful shutdown times out. + ErrShutdownTimeout = errors.New("api: shutdown timed out") +) diff --git a/internal/api/routes.go b/internal/api/routes.go new file mode 100644 index 00000000..e6f52ed1 --- /dev/null +++ b/internal/api/routes.go @@ -0,0 +1,25 @@ +package api + +import ( + "net/http" +) + +// registerRoutes registers all API routes with the server's router. +func (s *Server) registerRoutes() { + // Health check endpoint - always accessible, no auth required + s.router.HandleFunc("/health", s.handleHealth) + + // API v1 routes will be added in subsequent tasks: + // - Task 5595: GET /api/v1/status + // - Task 5602-5611: GET /api/v1/stats/* + // - Task 5609: GET /metrics +} + +// handleHealth handles GET /health requests. +// This endpoint always returns 200 OK and is used for load balancer +// health checks and basic connectivity verification. +func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, HealthResponse{ + Status: "ok", + }) +} diff --git a/internal/api/server.go b/internal/api/server.go new file mode 100644 index 00000000..f7b75d50 --- /dev/null +++ b/internal/api/server.go @@ -0,0 +1,154 @@ +package api + +import ( + "context" + "fmt" + "log" + "net" + "net/http" + "sync" + "time" +) + +// Server is the HTTP API server for GoClusterFS. +type Server struct { + mu sync.RWMutex + config Config + + // HTTP server components + server *http.Server + router *http.ServeMux + listener net.Listener + + // Lifecycle state + started bool + startTime time.Time + stopOnce sync.Once + stopErr error +} + +// NewServer creates a new API server with the given configuration. +// The server is not started until Start is called. +func NewServer(cfg Config) (*Server, error) { + if err := cfg.Validate(); err != nil { + return nil, fmt.Errorf("invalid config: %w", err) + } + + s := &Server{ + config: cfg, + router: http.NewServeMux(), + } + + // Register routes + s.registerRoutes() + + // Create HTTP server + s.server = &http.Server{ + Handler: s.router, + ReadTimeout: cfg.ReadTimeout, + WriteTimeout: cfg.WriteTimeout, + IdleTimeout: cfg.IdleTimeout, + } + + return s, nil +} + +// Start starts the API server and begins accepting connections. +// The server runs in a background goroutine and returns immediately. +// Use Stop to shut down the server gracefully. +func (s *Server) Start(ctx context.Context) error { + s.mu.Lock() + defer s.mu.Unlock() + + if s.started { + return ErrServerAlreadyStarted + } + + // Create listener + ln, err := net.Listen("tcp", s.config.ListenAddr) + if err != nil { + return fmt.Errorf("failed to listen on %s: %w", s.config.ListenAddr, err) + } + s.listener = ln + + // Mark as started + s.started = true + s.startTime = time.Now() + + // Start serving in background + go func() { + log.Printf("api: server listening on %s", ln.Addr()) + if err := s.server.Serve(ln); err != nil && err != http.ErrServerClosed { + log.Printf("api: server error: %v", err) + } + }() + + return nil +} + +// Stop gracefully shuts down the API server. +// It waits for active connections to complete up to the configured +// ShutdownTimeout before forcefully closing them. +func (s *Server) Stop() error { + s.stopOnce.Do(func() { + s.mu.Lock() + if !s.started { + s.mu.Unlock() + s.stopErr = ErrServerNotStarted + return + } + timeout := s.config.ShutdownTimeout + s.mu.Unlock() + + log.Printf("api: shutting down server...") + + // Create shutdown context with timeout + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + // Attempt graceful shutdown + if err := s.server.Shutdown(ctx); err != nil { + if ctx.Err() == context.DeadlineExceeded { + s.stopErr = ErrShutdownTimeout + } else { + s.stopErr = fmt.Errorf("shutdown error: %w", err) + } + return + } + + log.Printf("api: server stopped") + }) + + return s.stopErr +} + +// Addr returns the address the server is listening on. +// Returns an empty string if the server has not been started. +func (s *Server) Addr() string { + s.mu.RLock() + defer s.mu.RUnlock() + + if s.listener == nil { + return "" + } + return s.listener.Addr().String() +} + +// Started returns true if the server has been started. +func (s *Server) Started() bool { + s.mu.RLock() + defer s.mu.RUnlock() + return s.started +} + +// Uptime returns the duration since the server was started. +// Returns 0 if the server has not been started. +func (s *Server) Uptime() time.Duration { + s.mu.RLock() + defer s.mu.RUnlock() + + if !s.started { + return 0 + } + return time.Since(s.startTime) +} diff --git a/internal/api/server_test.go b/internal/api/server_test.go new file mode 100644 index 00000000..1b131a79 --- /dev/null +++ b/internal/api/server_test.go @@ -0,0 +1,319 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "testing" + "time" +) + +func TestDefaultConfig(t *testing.T) { + cfg := DefaultConfig() + + if cfg.ListenAddr != ":8080" { + t.Errorf("expected ListenAddr :8080, got %s", cfg.ListenAddr) + } + if cfg.AuthToken != "" { + t.Errorf("expected empty AuthToken, got %s", cfg.AuthToken) + } + if cfg.CORSOrigins != nil { + t.Errorf("expected nil CORSOrigins, got %v", cfg.CORSOrigins) + } + if cfg.ReadTimeout != 30*time.Second { + t.Errorf("expected ReadTimeout 30s, got %s", cfg.ReadTimeout) + } + if cfg.WriteTimeout != 30*time.Second { + t.Errorf("expected WriteTimeout 30s, got %s", cfg.WriteTimeout) + } + if cfg.IdleTimeout != 60*time.Second { + t.Errorf("expected IdleTimeout 60s, got %s", cfg.IdleTimeout) + } + if cfg.ShutdownTimeout != 10*time.Second { + t.Errorf("expected ShutdownTimeout 10s, got %s", cfg.ShutdownTimeout) + } +} + +func TestConfig_Validate_Valid(t *testing.T) { + tests := []struct { + name string + cfg Config + }{ + { + name: "default config", + cfg: DefaultConfig(), + }, + { + name: "with auth token", + cfg: DefaultConfig().WithAuthToken("secret"), + }, + { + name: "with CORS origins", + cfg: DefaultConfig().WithCORSOrigins("http://localhost:3000", "https://example.com"), + }, + { + name: "with wildcard CORS", + cfg: DefaultConfig().WithCORSOrigins("*"), + }, + { + name: "localhost address", + cfg: DefaultConfig().WithListenAddr("127.0.0.1:9090"), + }, + { + name: "dynamic port", + cfg: DefaultConfig().WithListenAddr(":0"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := tt.cfg.Validate(); err != nil { + t.Errorf("expected valid config, got error: %v", err) + } + }) + } +} + +func TestConfig_Validate_Invalid(t *testing.T) { + tests := []struct { + name string + cfg Config + wantError error + }{ + { + name: "empty listen addr", + cfg: func() Config { + cfg := DefaultConfig() + cfg.ListenAddr = "" + return cfg + }(), + wantError: ErrInvalidListenAddr, + }, + { + name: "invalid listen addr format", + cfg: func() Config { + cfg := DefaultConfig() + cfg.ListenAddr = "not-a-valid-addr" + return cfg + }(), + wantError: ErrInvalidListenAddr, + }, + { + name: "negative read timeout", + cfg: func() Config { + cfg := DefaultConfig() + cfg.ReadTimeout = -1 * time.Second + return cfg + }(), + wantError: ErrInvalidTimeout, + }, + { + name: "negative write timeout", + cfg: func() Config { + cfg := DefaultConfig() + cfg.WriteTimeout = -1 * time.Second + return cfg + }(), + wantError: ErrInvalidTimeout, + }, + { + name: "empty CORS origin", + cfg: func() Config { + cfg := DefaultConfig() + cfg.CORSOrigins = []string{""} + return cfg + }(), + wantError: ErrInvalidCORSOrigin, + }, + { + name: "invalid CORS origin - no scheme", + cfg: func() Config { + cfg := DefaultConfig() + cfg.CORSOrigins = []string{"localhost:3000"} + return cfg + }(), + wantError: ErrInvalidCORSOrigin, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.cfg.Validate() + if err == nil { + t.Errorf("expected error, got nil") + return + } + if !errors.Is(err, tt.wantError) { + t.Errorf("expected error %v, got %v", tt.wantError, err) + } + }) + } +} + +func TestNewServer_ValidConfig(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") // Use dynamic port + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("expected no error, got: %v", err) + } + if server == nil { + t.Fatal("expected server, got nil") + } +} + +func TestNewServer_InvalidConfig(t *testing.T) { + cfg := DefaultConfig() + cfg.ListenAddr = "" + + server, err := NewServer(cfg) + if err == nil { + t.Error("expected error for invalid config, got nil") + } + if server != nil { + t.Error("expected nil server for invalid config") + } +} + +func TestServer_StartStop(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Start server + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + + // Verify server is running + if !server.Started() { + t.Error("expected server to be started") + } + + addr := server.Addr() + if addr == "" { + t.Error("expected non-empty address") + } + + // Give it a moment to start listening + time.Sleep(10 * time.Millisecond) + + // Stop server + if err := server.Stop(); err != nil { + t.Errorf("Stop error: %v", err) + } +} + +func TestServer_HealthEndpoint(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + // Give it a moment to start listening + time.Sleep(10 * time.Millisecond) + + // Make health check request + resp, err := http.Get("http://" + server.Addr() + "/health") + if err != nil { + t.Fatalf("health check request error: %v", err) + } + defer resp.Body.Close() + + // Check status code + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + // Check response body + var health HealthResponse + if err := json.NewDecoder(resp.Body).Decode(&health); err != nil { + t.Fatalf("decode error: %v", err) + } + + if health.Status != "ok" { + t.Errorf("expected status 'ok', got %q", health.Status) + } +} + +func TestServer_DoubleStart(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("first Start error: %v", err) + } + defer server.Stop() + + // Second start should return error + if err := server.Start(ctx); !errors.Is(err, ErrServerAlreadyStarted) { + t.Errorf("expected ErrServerAlreadyStarted, got: %v", err) + } +} + +func TestServer_StopWithoutStart(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Stop without start should return error + if err := server.Stop(); !errors.Is(err, ErrServerNotStarted) { + t.Errorf("expected ErrServerNotStarted, got: %v", err) + } +} + +func TestServer_Uptime(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Uptime before start should be 0 + if uptime := server.Uptime(); uptime != 0 { + t.Errorf("expected 0 uptime before start, got %v", uptime) + } + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + // Wait a bit + time.Sleep(50 * time.Millisecond) + + // Uptime should be > 0 + if uptime := server.Uptime(); uptime <= 0 { + t.Errorf("expected positive uptime after start, got %v", uptime) + } +} + +func TestServer_AddrBeforeStart(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Addr before start should be empty + if addr := server.Addr(); addr != "" { + t.Errorf("expected empty addr before start, got %q", addr) + } +} diff --git a/internal/api/types.go b/internal/api/types.go new file mode 100644 index 00000000..a07c59da --- /dev/null +++ b/internal/api/types.go @@ -0,0 +1,45 @@ +package api + +import ( + "encoding/json" + "net/http" +) + +// HealthResponse is returned by GET /health. +type HealthResponse struct { + Status string `json:"status"` +} + +// ErrorResponse is returned for API errors. +type ErrorResponse struct { + Error string `json:"error"` + Code int `json:"code"` + Details string `json:"details,omitempty"` +} + +// StatusResponse is returned by GET /api/v1/status. +// This is a placeholder that will be expanded in Task 5595. +type StatusResponse struct { + Status string `json:"status"` + Version string `json:"version"` + Uptime int64 `json:"uptime_seconds"` + MountPath string `json:"mount_path,omitempty"` +} + +// writeJSON writes a JSON response with the given status code. +func writeJSON(w http.ResponseWriter, status int, v interface{}) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + if v != nil { + json.NewEncoder(w).Encode(v) + } +} + +// writeError writes an error response with the given status code. +func writeError(w http.ResponseWriter, status int, err string, details string) { + writeJSON(w, status, ErrorResponse{ + Error: err, + Code: status, + Details: details, + }) +} From 7daedbe08641220721c7154f69d3a6c3ea53b259 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 02:32:07 -0600 Subject: [PATCH 02/37] feat(api): implement route registration with groups - Add /api/v1/ catch-all handler for versioned endpoints - Add /metrics endpoint for Prometheus scraping - Add /api/v1/status endpoint returning server status - Add /api/v1/stats/* placeholder for component stats - Add method validation (405 Method Not Allowed) - Add route tests for all endpoint groups Task: #5591 --- internal/api/routes.go | 69 +++++++++++++- internal/api/routes_test.go | 175 ++++++++++++++++++++++++++++++++++++ 2 files changed, 240 insertions(+), 4 deletions(-) create mode 100644 internal/api/routes_test.go diff --git a/internal/api/routes.go b/internal/api/routes.go index e6f52ed1..524ee9ce 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -2,24 +2,85 @@ package api import ( "net/http" + "strings" ) // registerRoutes registers all API routes with the server's router. +// Routes are organized into logical groups: +// - /health - Health check (no auth required) +// - /api/v1/* - Versioned API endpoints (auth required when configured) +// - /metrics - Prometheus metrics (no auth required) func (s *Server) registerRoutes() { // Health check endpoint - always accessible, no auth required s.router.HandleFunc("/health", s.handleHealth) - // API v1 routes will be added in subsequent tasks: - // - Task 5595: GET /api/v1/status - // - Task 5602-5611: GET /api/v1/stats/* - // - Task 5609: GET /metrics + // API v1 route group - catch-all handler for versioned endpoints + s.router.HandleFunc("/api/v1/", s.handleAPIv1) + + // Metrics endpoint for Prometheus scraping + s.router.HandleFunc("/metrics", s.handleMetrics) } // handleHealth handles GET /health requests. // This endpoint always returns 200 OK and is used for load balancer // health checks and basic connectivity verification. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet && r.Method != http.MethodHead { + writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET or HEAD") + return + } writeJSON(w, http.StatusOK, HealthResponse{ Status: "ok", }) } + +// handleAPIv1 is the catch-all handler for /api/v1/* routes. +func (s *Server) handleAPIv1(w http.ResponseWriter, r *http.Request) { + path := strings.TrimPrefix(r.URL.Path, "/api/v1") + + switch { + case path == "/status" || path == "/status/": + s.handleStatus(w, r) + case strings.HasPrefix(path, "/stats"): + s.handleStats(w, r) + default: + writeError(w, http.StatusNotFound, "endpoint not found", "") + } +} + +// handleStatus handles GET /api/v1/status requests. +func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET") + return + } + + writeJSON(w, http.StatusOK, StatusResponse{ + Status: "ok", + Version: "dev", + Uptime: int64(s.Uptime().Seconds()), + }) +} + +// handleStats handles GET /api/v1/stats/* requests. +func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET") + return + } + writeError(w, http.StatusNotImplemented, "stats endpoint not yet implemented", "") +} + +// handleMetrics handles GET /metrics requests for Prometheus scraping. +func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET") + return + } + + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.WriteHeader(http.StatusOK) + w.Write([]byte("# HELP goclusterfs_up Indicates if GoClusterFS is up\n")) + w.Write([]byte("# TYPE goclusterfs_up gauge\n")) + w.Write([]byte("goclusterfs_up 1\n")) +} diff --git a/internal/api/routes_test.go b/internal/api/routes_test.go new file mode 100644 index 00000000..632be3b2 --- /dev/null +++ b/internal/api/routes_test.go @@ -0,0 +1,175 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "strings" + "testing" + "time" +) + +// startTestServer creates and starts a test server, returning it for cleanup. +func startTestServer(t *testing.T) *Server { + t.Helper() + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + + time.Sleep(10 * time.Millisecond) + return server +} + +func TestRoutes_Status(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/status") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + var status StatusResponse + if err := json.NewDecoder(resp.Body).Decode(&status); err != nil { + t.Fatalf("decode error: %v", err) + } + + if status.Status != "ok" { + t.Errorf("expected status 'ok', got %q", status.Status) + } + if status.Version != "dev" { + t.Errorf("expected version 'dev', got %q", status.Version) + } +} + +func TestRoutes_StatusWithTrailingSlash(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/status/") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } +} + +func TestRoutes_Metrics(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/metrics") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + contentType := resp.Header.Get("Content-Type") + if !strings.HasPrefix(contentType, "text/plain") { + t.Errorf("expected text/plain content-type, got %q", contentType) + } +} + +func TestRoutes_Stats_NotImplemented(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/cache") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNotImplemented { + t.Errorf("expected status 501, got %d", resp.StatusCode) + } +} + +func TestRoutes_APIv1_NotFound(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/unknown") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNotFound { + t.Errorf("expected status 404, got %d", resp.StatusCode) + } +} + +func TestRoutes_MethodNotAllowed(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + tests := []struct { + name string + path string + method string + }{ + {"health POST", "/health", http.MethodPost}, + {"status POST", "/api/v1/status", http.MethodPost}, + {"metrics POST", "/metrics", http.MethodPost}, + } + + client := &http.Client{} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req, err := http.NewRequest(tt.method, "http://"+server.Addr()+tt.path, nil) + if err != nil { + t.Fatalf("create request error: %v", err) + } + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Errorf("expected status 405, got %d", resp.StatusCode) + } + }) + } +} + +func TestRoutes_HealthHEAD(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + client := &http.Client{} + req, err := http.NewRequest(http.MethodHead, "http://"+server.Addr()+"/health", nil) + if err != nil { + t.Fatalf("create request error: %v", err) + } + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } +} From 8d7ecaec4a816caa1e1c3dd903782bc2b678a49f Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 02:52:27 -0600 Subject: [PATCH 03/37] feat(api): implement middleware (auth, CORS, logging) - Add LoggingMiddleware that logs method, path, status, duration - Add AuthMiddleware with Bearer token validation and skip paths - Add CORSMiddleware with configurable origins and preflight support - Integrate middleware chain into server (logging -> CORS -> auth) - Add comprehensive middleware tests (11 new tests) Task: #5592 --- internal/api/middleware.go | 142 ++++++++++++++ internal/api/middleware_test.go | 324 ++++++++++++++++++++++++++++++++ internal/api/server.go | 10 +- 3 files changed, 475 insertions(+), 1 deletion(-) create mode 100644 internal/api/middleware.go create mode 100644 internal/api/middleware_test.go diff --git a/internal/api/middleware.go b/internal/api/middleware.go new file mode 100644 index 00000000..3d267d19 --- /dev/null +++ b/internal/api/middleware.go @@ -0,0 +1,142 @@ +package api + +import ( + "crypto/subtle" + "log" + "net/http" + "strings" + "time" +) + +// Middleware is a function that wraps an http.Handler. +type Middleware func(http.Handler) http.Handler + +// Chain applies middlewares in order (first middleware is outermost). +func Chain(h http.Handler, middlewares ...Middleware) http.Handler { + for i := len(middlewares) - 1; i >= 0; i-- { + h = middlewares[i](h) + } + return h +} + +// responseWriter wraps http.ResponseWriter to capture status code. +type responseWriter struct { + http.ResponseWriter + status int +} + +func (rw *responseWriter) WriteHeader(code int) { + rw.status = code + rw.ResponseWriter.WriteHeader(code) +} + +// LoggingMiddleware logs HTTP requests with method, path, status, and duration. +func LoggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + rw := &responseWriter{ResponseWriter: w, status: http.StatusOK} + next.ServeHTTP(rw, r) + + log.Printf("api: %s %s %d %s", + r.Method, + r.URL.Path, + rw.status, + time.Since(start).Round(time.Microsecond), + ) + }) +} + +// AuthMiddleware returns a middleware that validates Bearer tokens. +// If token is empty, authentication is disabled. +// Paths in skipPaths are not authenticated (e.g., /health, /metrics). +func AuthMiddleware(token string, skipPaths ...string) Middleware { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // If no token configured, skip auth + if token == "" { + next.ServeHTTP(w, r) + return + } + + // Check if path should skip auth + for _, path := range skipPaths { + if r.URL.Path == path || strings.HasPrefix(r.URL.Path, path+"/") { + next.ServeHTTP(w, r) + return + } + } + + // Extract Bearer token from Authorization header + auth := r.Header.Get("Authorization") + if auth == "" { + writeError(w, http.StatusUnauthorized, "missing authorization header", "") + return + } + + if !strings.HasPrefix(auth, "Bearer ") { + writeError(w, http.StatusUnauthorized, "invalid authorization format", "use Bearer token") + return + } + + providedToken := strings.TrimPrefix(auth, "Bearer ") + + // Constant-time comparison to prevent timing attacks + if subtle.ConstantTimeCompare([]byte(providedToken), []byte(token)) != 1 { + writeError(w, http.StatusUnauthorized, "invalid token", "") + return + } + + next.ServeHTTP(w, r) + }) + } +} + +// CORSMiddleware returns a middleware that handles CORS headers. +// If origins is empty, CORS is disabled. +// Use "*" to allow all origins (not recommended for production). +func CORSMiddleware(origins []string) Middleware { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // If no origins configured, skip CORS + if len(origins) == 0 { + next.ServeHTTP(w, r) + return + } + + origin := r.Header.Get("Origin") + if origin == "" { + next.ServeHTTP(w, r) + return + } + + // Check if origin is allowed + allowed := false + for _, o := range origins { + if o == "*" || o == origin { + allowed = true + break + } + } + + if !allowed { + next.ServeHTTP(w, r) + return + } + + // Set CORS headers + w.Header().Set("Access-Control-Allow-Origin", origin) + w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") + w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type") + w.Header().Set("Access-Control-Max-Age", "86400") + + // Handle preflight requests + if r.Method == http.MethodOptions { + w.WriteHeader(http.StatusNoContent) + return + } + + next.ServeHTTP(w, r) + }) + } +} diff --git a/internal/api/middleware_test.go b/internal/api/middleware_test.go new file mode 100644 index 00000000..b43e6a72 --- /dev/null +++ b/internal/api/middleware_test.go @@ -0,0 +1,324 @@ +package api + +import ( + "context" + "net/http" + "testing" + "time" +) + +func TestAuthMiddleware_NoTokenConfigured(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + // Request without auth should succeed when no token configured + resp, err := http.Get("http://" + server.Addr() + "/api/v1/status") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected 200, got %d", resp.StatusCode) + } +} + +func TestAuthMiddleware_ValidToken(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithAuthToken("secret-token") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("GET", "http://"+server.Addr()+"/api/v1/status", nil) + req.Header.Set("Authorization", "Bearer secret-token") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected 200, got %d", resp.StatusCode) + } +} + +func TestAuthMiddleware_MissingHeader(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithAuthToken("secret-token") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/status") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusUnauthorized { + t.Errorf("expected 401, got %d", resp.StatusCode) + } +} + +func TestAuthMiddleware_InvalidFormat(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithAuthToken("secret-token") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("GET", "http://"+server.Addr()+"/api/v1/status", nil) + req.Header.Set("Authorization", "Basic secret-token") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusUnauthorized { + t.Errorf("expected 401, got %d", resp.StatusCode) + } +} + +func TestAuthMiddleware_WrongToken(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithAuthToken("secret-token") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("GET", "http://"+server.Addr()+"/api/v1/status", nil) + req.Header.Set("Authorization", "Bearer wrong-token") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusUnauthorized { + t.Errorf("expected 401, got %d", resp.StatusCode) + } +} + +func TestAuthMiddleware_SkipPaths(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithAuthToken("secret-token") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + // /health and /metrics should be accessible without auth + paths := []string{"/health", "/metrics"} + for _, path := range paths { + t.Run(path, func(t *testing.T) { + resp, err := http.Get("http://" + server.Addr() + path) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected 200 for %s, got %d", path, resp.StatusCode) + } + }) + } +} + +func TestCORSMiddleware_NoOrigins(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("GET", "http://"+server.Addr()+"/health", nil) + req.Header.Set("Origin", "http://example.com") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + // No CORS headers should be set + if cors := resp.Header.Get("Access-Control-Allow-Origin"); cors != "" { + t.Errorf("expected no CORS header, got %q", cors) + } +} + +func TestCORSMiddleware_AllowedOrigin(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithCORSOrigins("http://example.com") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("GET", "http://"+server.Addr()+"/health", nil) + req.Header.Set("Origin", "http://example.com") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + cors := resp.Header.Get("Access-Control-Allow-Origin") + if cors != "http://example.com" { + t.Errorf("expected CORS header 'http://example.com', got %q", cors) + } +} + +func TestCORSMiddleware_DisallowedOrigin(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithCORSOrigins("http://example.com") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("GET", "http://"+server.Addr()+"/health", nil) + req.Header.Set("Origin", "http://evil.com") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + // No CORS headers for disallowed origin + if cors := resp.Header.Get("Access-Control-Allow-Origin"); cors != "" { + t.Errorf("expected no CORS header for disallowed origin, got %q", cors) + } +} + +func TestCORSMiddleware_Wildcard(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithCORSOrigins("*") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("GET", "http://"+server.Addr()+"/health", nil) + req.Header.Set("Origin", "http://any-origin.com") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + cors := resp.Header.Get("Access-Control-Allow-Origin") + if cors != "http://any-origin.com" { + t.Errorf("expected CORS header 'http://any-origin.com', got %q", cors) + } +} + +func TestCORSMiddleware_Preflight(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0").WithCORSOrigins("http://example.com") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + client := &http.Client{} + req, _ := http.NewRequest("OPTIONS", "http://"+server.Addr()+"/api/v1/status", nil) + req.Header.Set("Origin", "http://example.com") + req.Header.Set("Access-Control-Request-Method", "GET") + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNoContent { + t.Errorf("expected 204 for preflight, got %d", resp.StatusCode) + } + + if cors := resp.Header.Get("Access-Control-Allow-Origin"); cors != "http://example.com" { + t.Errorf("expected CORS header, got %q", cors) + } + + if methods := resp.Header.Get("Access-Control-Allow-Methods"); methods == "" { + t.Error("expected Access-Control-Allow-Methods header") + } +} diff --git a/internal/api/server.go b/internal/api/server.go index f7b75d50..96ce90e4 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -42,9 +42,17 @@ func NewServer(cfg Config) (*Server, error) { // Register routes s.registerRoutes() + // Build middleware chain (order: logging -> CORS -> auth) + handler := Chain( + s.router, + LoggingMiddleware, + CORSMiddleware(cfg.CORSOrigins), + AuthMiddleware(cfg.AuthToken, "/health", "/metrics"), + ) + // Create HTTP server s.server = &http.Server{ - Handler: s.router, + Handler: handler, ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, IdleTimeout: cfg.IdleTimeout, From 3b24cce79e5c696f42d0229732564d9a919f91d6 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 02:55:15 -0600 Subject: [PATCH 04/37] feat(api): define comprehensive JSON request/response types - Add HealthStatus constants (ok, degraded, unhealthy) - Add ComponentHealth for individual health checks - Enhance StatusResponse with capacity, cluster, mount state - Add CacheStatsResponse matching internal/cache.Stats - Add JournalStatsResponse matching internal/journal.JournalStats - Add IOStatsResponse and StatsOverviewResponse - Add comprehensive type marshaling tests Task: #5593 --- internal/api/routes.go | 8 +- internal/api/types.go | 126 +++++++++++++++++++++-- internal/api/types_test.go | 205 +++++++++++++++++++++++++++++++++++++ 3 files changed, 329 insertions(+), 10 deletions(-) create mode 100644 internal/api/types_test.go diff --git a/internal/api/routes.go b/internal/api/routes.go index 524ee9ce..2ea1ff57 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -30,7 +30,7 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { return } writeJSON(w, http.StatusOK, HealthResponse{ - Status: "ok", + Status: HealthStatusOK, }) } @@ -56,9 +56,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { } writeJSON(w, http.StatusOK, StatusResponse{ - Status: "ok", - Version: "dev", - Uptime: int64(s.Uptime().Seconds()), + Status: "ok", + Version: "dev", + UptimeSeconds: int64(s.Uptime().Seconds()), }) } diff --git a/internal/api/types.go b/internal/api/types.go index a07c59da..afc09eb7 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -5,9 +5,26 @@ import ( "net/http" ) +// HealthStatus represents the overall health state. +type HealthStatus string + +const ( + HealthStatusOK HealthStatus = "ok" + HealthStatusDegraded HealthStatus = "degraded" + HealthStatusUnhealthy HealthStatus = "unhealthy" +) + +// ComponentHealth represents the health of a single component. +type ComponentHealth struct { + Status HealthStatus `json:"status"` + Message string `json:"message,omitempty"` +} + // HealthResponse is returned by GET /health. +// Provides overall system health and individual component checks. type HealthResponse struct { - Status string `json:"status"` + Status HealthStatus `json:"status"` + Checks map[string]ComponentHealth `json:"checks,omitempty"` } // ErrorResponse is returned for API errors. @@ -17,13 +34,110 @@ type ErrorResponse struct { Details string `json:"details,omitempty"` } +// CapacityInfo provides storage capacity information. +type CapacityInfo struct { + TotalBytes uint64 `json:"total_bytes"` + UsedBytes uint64 `json:"used_bytes"` + FreeBytes uint64 `json:"free_bytes"` + UsedPercent float64 `json:"used_percent"` + TotalBlocks uint64 `json:"total_blocks"` + UsedBlocks uint64 `json:"used_blocks"` + FreeBlocks uint64 `json:"free_blocks"` + BlockSizeBytes uint64 `json:"block_size_bytes"` +} + +// ClusterInfo provides cluster membership information. +type ClusterInfo struct { + NodeID string `json:"node_id,omitempty"` + PeerCount int `json:"peer_count"` + Peers []string `json:"peers,omitempty"` + IsLeader bool `json:"is_leader,omitempty"` + LeaderID string `json:"leader_id,omitempty"` + ClusterState string `json:"cluster_state,omitempty"` +} + +// MountState represents the current mount state. +type MountState string + +const ( + MountStateUnmounted MountState = "unmounted" + MountStateMounting MountState = "mounting" + MountStateMounted MountState = "mounted" + MountStateUnmounting MountState = "unmounting" + MountStateError MountState = "error" +) + // StatusResponse is returned by GET /api/v1/status. -// This is a placeholder that will be expanded in Task 5595. +// Provides comprehensive system status information. type StatusResponse struct { - Status string `json:"status"` - Version string `json:"version"` - Uptime int64 `json:"uptime_seconds"` - MountPath string `json:"mount_path,omitempty"` + Status string `json:"status"` + Version string `json:"version"` + GitCommit string `json:"git_commit,omitempty"` + BuildTime string `json:"build_time,omitempty"` + GoVersion string `json:"go_version,omitempty"` + UptimeSeconds int64 `json:"uptime_seconds"` + MountPath string `json:"mount_path,omitempty"` + DevicePath string `json:"device_path,omitempty"` + MountState MountState `json:"mount_state,omitempty"` + ReadOnly bool `json:"read_only,omitempty"` + Capacity *CapacityInfo `json:"capacity,omitempty"` + Cluster *ClusterInfo `json:"cluster,omitempty"` +} + +// CacheHitRateInfo contains hit rate metrics for a cache type. +type CacheHitRateInfo struct { + Size int `json:"size"` + Hits uint64 `json:"hits"` + Misses uint64 `json:"misses"` + HitRate float64 `json:"hit_rate"` +} + +// CacheStatsResponse is returned by GET /api/v1/stats/cache. +// Matches internal/cache.Stats structure. +type CacheStatsResponse struct { + InodeCache CacheHitRateInfo `json:"inode_cache"` + ExtentCache CacheHitRateInfo `json:"extent_cache"` + NegativeCache CacheHitRateInfo `json:"negative_cache"` + LockHintCache CacheHitRateInfo `json:"lock_hint_cache,omitempty"` +} + +// JournalStatsResponse is returned by GET /api/v1/stats/journal. +// Matches internal/journal.JournalStats structure. +type JournalStatsResponse struct { + State string `json:"state"` + HeadOffset uint32 `json:"head_offset"` + TailOffset uint32 `json:"tail_offset"` + AvailableSpace uint32 `json:"available_space"` + ActiveTxnCount int `json:"active_txn_count"` + CommitCount uint64 `json:"commit_count"` + BytesWritten uint64 `json:"bytes_written"` + LastCheckpointSeq uint64 `json:"last_checkpoint_seq"` + BatchSyncCount uint64 `json:"batch_sync_count"` +} + +// IOStatsResponse contains I/O operation statistics. +type IOStatsResponse struct { + ReadOps uint64 `json:"read_ops"` + WriteOps uint64 `json:"write_ops"` + BytesRead uint64 `json:"bytes_read"` + BytesWritten uint64 `json:"bytes_written"` + AvgReadLatUs float64 `json:"avg_read_latency_us"` + AvgWriteLatUs float64 `json:"avg_write_latency_us"` +} + +// MetricsStatsResponse is returned by GET /api/v1/stats/metrics. +type MetricsStatsResponse struct { + IO *IOStatsResponse `json:"io,omitempty"` + StartTime int64 `json:"start_time_unix"` + Uptime int64 `json:"uptime_seconds"` +} + +// StatsOverviewResponse is returned by GET /api/v1/stats. +// Provides a summary of all component stats. +type StatsOverviewResponse struct { + Cache *CacheStatsResponse `json:"cache,omitempty"` + Journal *JournalStatsResponse `json:"journal,omitempty"` + IO *IOStatsResponse `json:"io,omitempty"` } // writeJSON writes a JSON response with the given status code. diff --git a/internal/api/types_test.go b/internal/api/types_test.go new file mode 100644 index 00000000..942eb82f --- /dev/null +++ b/internal/api/types_test.go @@ -0,0 +1,205 @@ +package api + +import ( + "encoding/json" + "testing" +) + +func TestHealthResponse_JSONMarshaling(t *testing.T) { + tests := []struct { + name string + resp HealthResponse + wantJSON string + }{ + { + name: "simple ok", + resp: HealthResponse{ + Status: HealthStatusOK, + }, + wantJSON: `{"status":"ok"}`, + }, + { + name: "with checks", + resp: HealthResponse{ + Status: HealthStatusDegraded, + Checks: map[string]ComponentHealth{ + "cache": {Status: HealthStatusOK}, + "journal": {Status: HealthStatusDegraded, Message: "low disk space"}, + }, + }, + wantJSON: "", // Complex; just verify round-trip + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + data, err := json.Marshal(tt.resp) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + + if tt.wantJSON != "" { + if string(data) != tt.wantJSON { + t.Errorf("got %s, want %s", string(data), tt.wantJSON) + } + } + + // Verify round-trip + var got HealthResponse + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal error: %v", err) + } + if got.Status != tt.resp.Status { + t.Errorf("Status: got %s, want %s", got.Status, tt.resp.Status) + } + }) + } +} + +func TestStatusResponse_JSONMarshaling(t *testing.T) { + resp := StatusResponse{ + Status: "ok", + Version: "1.0.0", + UptimeSeconds: 3600, + MountPath: "/mnt/test", + Capacity: &CapacityInfo{ + TotalBytes: 1073741824, // 1GB + UsedBytes: 536870912, // 512MB + FreeBytes: 536870912, + UsedPercent: 50.0, + }, + } + + data, err := json.Marshal(resp) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + + var got StatusResponse + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal error: %v", err) + } + + if got.Status != resp.Status { + t.Errorf("Status: got %s, want %s", got.Status, resp.Status) + } + if got.UptimeSeconds != resp.UptimeSeconds { + t.Errorf("UptimeSeconds: got %d, want %d", got.UptimeSeconds, resp.UptimeSeconds) + } + if got.Capacity == nil { + t.Error("Capacity should not be nil") + } else if got.Capacity.UsedPercent != resp.Capacity.UsedPercent { + t.Errorf("UsedPercent: got %f, want %f", got.Capacity.UsedPercent, resp.Capacity.UsedPercent) + } +} + +func TestCacheStatsResponse_JSONMarshaling(t *testing.T) { + resp := CacheStatsResponse{ + InodeCache: CacheHitRateInfo{ + Size: 1000, + Hits: 9500, + Misses: 500, + HitRate: 0.95, + }, + ExtentCache: CacheHitRateInfo{ + Size: 500, + Hits: 4800, + Misses: 200, + HitRate: 0.96, + }, + } + + data, err := json.Marshal(resp) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + + var got CacheStatsResponse + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal error: %v", err) + } + + if got.InodeCache.HitRate != resp.InodeCache.HitRate { + t.Errorf("InodeCache.HitRate: got %f, want %f", got.InodeCache.HitRate, resp.InodeCache.HitRate) + } +} + +func TestJournalStatsResponse_JSONMarshaling(t *testing.T) { + resp := JournalStatsResponse{ + State: "active", + HeadOffset: 1024, + TailOffset: 512, + AvailableSpace: 65536, + CommitCount: 12345, + BytesWritten: 1048576, + } + + data, err := json.Marshal(resp) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + + var got JournalStatsResponse + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal error: %v", err) + } + + if got.CommitCount != resp.CommitCount { + t.Errorf("CommitCount: got %d, want %d", got.CommitCount, resp.CommitCount) + } +} + +func TestErrorResponse_JSONMarshaling(t *testing.T) { + resp := ErrorResponse{ + Error: "not found", + Code: 404, + Details: "resource does not exist", + } + + data, err := json.Marshal(resp) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + + expected := `{"error":"not found","code":404,"details":"resource does not exist"}` + if string(data) != expected { + t.Errorf("got %s, want %s", string(data), expected) + } +} + +func TestOmitEmpty(t *testing.T) { + // Verify omitempty works correctly + resp := StatusResponse{ + Status: "ok", + Version: "dev", + UptimeSeconds: 0, + // MountPath intentionally empty + } + + data, err := json.Marshal(resp) + if err != nil { + t.Fatalf("Marshal error: %v", err) + } + + // Should not contain mount_path since it's empty and has omitempty + str := string(data) + if contains(str, "mount_path") { + t.Errorf("empty mount_path should be omitted: %s", str) + } + if contains(str, "capacity") { + t.Errorf("nil capacity should be omitted: %s", str) + } +} + +func contains(s, substr string) bool { + return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsAt(s, substr)) +} + +func containsAt(s, substr string) bool { + for i := 0; i <= len(s)-len(substr); i++ { + if s[i:i+len(substr)] == substr { + return true + } + } + return false +} From 215587b5c0f63e04bc0a5e48364f91f004a5687c Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 02:57:48 -0600 Subject: [PATCH 05/37] feat(api): implement /health endpoint with component health checks - Add HealthChecker interface for component health reporting - Add AggregateHealth to combine multiple health check results - Implement priority: unhealthy > degraded > ok - Return 503 for unhealthy status, 200 for ok/degraded - Add RegisterHealthChecker to Server for dependency injection - Add comprehensive health endpoint tests Task: #5594 --- internal/api/health.go | 69 ++++++++++++ internal/api/health_test.go | 214 ++++++++++++++++++++++++++++++++++++ internal/api/routes.go | 26 ++++- internal/api/server.go | 20 ++++ 4 files changed, 324 insertions(+), 5 deletions(-) create mode 100644 internal/api/health.go create mode 100644 internal/api/health_test.go diff --git a/internal/api/health.go b/internal/api/health.go new file mode 100644 index 00000000..a89b291b --- /dev/null +++ b/internal/api/health.go @@ -0,0 +1,69 @@ +package api + +import "context" + +// HealthChecker is the interface that components implement to report health. +type HealthChecker interface { + // Name returns the component name for health reporting. + Name() string + + // CheckHealth returns the health status of the component. + // The context allows for timeout on health checks. + CheckHealth(ctx context.Context) ComponentHealth +} + +// HealthCheckFunc allows a function to implement HealthChecker. +type HealthCheckFunc struct { + name string + fn func(ctx context.Context) ComponentHealth +} + +// NewHealthCheckFunc creates a HealthChecker from a function. +func NewHealthCheckFunc(name string, fn func(ctx context.Context) ComponentHealth) HealthChecker { + return &HealthCheckFunc{name: name, fn: fn} +} + +func (h *HealthCheckFunc) Name() string { + return h.name +} + +func (h *HealthCheckFunc) CheckHealth(ctx context.Context) ComponentHealth { + return h.fn(ctx) +} + +// AggregateHealth runs all health checks and returns aggregate status. +// Returns HealthStatusOK if all checks pass. +// Returns HealthStatusDegraded if any check is degraded (but none unhealthy). +// Returns HealthStatusUnhealthy if any check is unhealthy. +func AggregateHealth(ctx context.Context, checkers ...HealthChecker) HealthResponse { + checks := make(map[string]ComponentHealth) + overall := HealthStatusOK + + for _, checker := range checkers { + health := checker.CheckHealth(ctx) + checks[checker.Name()] = health + + // Determine overall status (unhealthy > degraded > ok) + switch health.Status { + case HealthStatusUnhealthy: + overall = HealthStatusUnhealthy + case HealthStatusDegraded: + if overall != HealthStatusUnhealthy { + overall = HealthStatusDegraded + } + } + } + + return HealthResponse{ + Status: overall, + Checks: checks, + } +} + +// DefaultHealthChecker returns a checker that always reports healthy. +// This is used as a placeholder until real components are injected. +func DefaultHealthChecker() HealthChecker { + return NewHealthCheckFunc("api", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusOK} + }) +} diff --git a/internal/api/health_test.go b/internal/api/health_test.go new file mode 100644 index 00000000..b0e9f2ac --- /dev/null +++ b/internal/api/health_test.go @@ -0,0 +1,214 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "testing" + "time" +) + +func TestAggregateHealth_AllOK(t *testing.T) { + checkers := []HealthChecker{ + NewHealthCheckFunc("cache", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusOK} + }), + NewHealthCheckFunc("journal", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusOK} + }), + } + + resp := AggregateHealth(context.Background(), checkers...) + + if resp.Status != HealthStatusOK { + t.Errorf("expected OK, got %s", resp.Status) + } + if len(resp.Checks) != 2 { + t.Errorf("expected 2 checks, got %d", len(resp.Checks)) + } +} + +func TestAggregateHealth_OneDegraded(t *testing.T) { + checkers := []HealthChecker{ + NewHealthCheckFunc("cache", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusOK} + }), + NewHealthCheckFunc("journal", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusDegraded, Message: "low disk space"} + }), + } + + resp := AggregateHealth(context.Background(), checkers...) + + if resp.Status != HealthStatusDegraded { + t.Errorf("expected Degraded, got %s", resp.Status) + } + if resp.Checks["journal"].Message != "low disk space" { + t.Errorf("expected message, got %q", resp.Checks["journal"].Message) + } +} + +func TestAggregateHealth_OneUnhealthy(t *testing.T) { + checkers := []HealthChecker{ + NewHealthCheckFunc("cache", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusDegraded} + }), + NewHealthCheckFunc("journal", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusUnhealthy, Message: "write failure"} + }), + } + + resp := AggregateHealth(context.Background(), checkers...) + + if resp.Status != HealthStatusUnhealthy { + t.Errorf("expected Unhealthy, got %s", resp.Status) + } +} + +func TestAggregateHealth_Empty(t *testing.T) { + resp := AggregateHealth(context.Background()) + + if resp.Status != HealthStatusOK { + t.Errorf("expected OK for empty checkers, got %s", resp.Status) + } + if len(resp.Checks) != 0 { + t.Errorf("expected no checks, got %d", len(resp.Checks)) + } +} + +func TestHealthEndpoint_WithCheckers(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Register a degraded checker + server.RegisterHealthChecker(NewHealthCheckFunc("test", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusDegraded, Message: "test warning"} + })) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/health") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + // Degraded returns 200 (only unhealthy returns 503) + if resp.StatusCode != http.StatusOK { + t.Errorf("expected 200, got %d", resp.StatusCode) + } + + var health HealthResponse + if err := json.NewDecoder(resp.Body).Decode(&health); err != nil { + t.Fatalf("decode error: %v", err) + } + + if health.Status != HealthStatusDegraded { + t.Errorf("expected degraded status, got %s", health.Status) + } + if health.Checks["test"].Message != "test warning" { + t.Errorf("expected message, got %q", health.Checks["test"].Message) + } +} + +func TestHealthEndpoint_Unhealthy_Returns503(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Register an unhealthy checker + server.RegisterHealthChecker(NewHealthCheckFunc("critical", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusUnhealthy, Message: "critical failure"} + })) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/health") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + // Unhealthy returns 503 + if resp.StatusCode != http.StatusServiceUnavailable { + t.Errorf("expected 503, got %d", resp.StatusCode) + } + + var health HealthResponse + if err := json.NewDecoder(resp.Body).Decode(&health); err != nil { + t.Fatalf("decode error: %v", err) + } + + if health.Status != HealthStatusUnhealthy { + t.Errorf("expected unhealthy status, got %s", health.Status) + } +} + +func TestHealthEndpoint_MultipleCheckers(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Register multiple checkers + server.RegisterHealthChecker(NewHealthCheckFunc("cache", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusOK} + })) + server.RegisterHealthChecker(NewHealthCheckFunc("journal", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusOK} + })) + server.RegisterHealthChecker(NewHealthCheckFunc("device", func(ctx context.Context) ComponentHealth { + return ComponentHealth{Status: HealthStatusOK} + })) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/health") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected 200, got %d", resp.StatusCode) + } + + var health HealthResponse + if err := json.NewDecoder(resp.Body).Decode(&health); err != nil { + t.Fatalf("decode error: %v", err) + } + + if len(health.Checks) != 3 { + t.Errorf("expected 3 checks, got %d", len(health.Checks)) + } +} + +func TestDefaultHealthChecker(t *testing.T) { + checker := DefaultHealthChecker() + if checker.Name() != "api" { + t.Errorf("expected name 'api', got %q", checker.Name()) + } + + health := checker.CheckHealth(context.Background()) + if health.Status != HealthStatusOK { + t.Errorf("expected OK, got %s", health.Status) + } +} diff --git a/internal/api/routes.go b/internal/api/routes.go index 2ea1ff57..acaca5d8 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -22,16 +22,32 @@ func (s *Server) registerRoutes() { } // handleHealth handles GET /health requests. -// This endpoint always returns 200 OK and is used for load balancer -// health checks and basic connectivity verification. +// Returns aggregate health status from all registered health checkers. +// Status codes: 200 OK, 503 Service Unavailable (if unhealthy). func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET or HEAD") return } - writeJSON(w, http.StatusOK, HealthResponse{ - Status: HealthStatusOK, - }) + + checkers := s.GetHealthCheckers() + if len(checkers) == 0 { + // No checkers registered - just report API is OK + writeJSON(w, http.StatusOK, HealthResponse{ + Status: HealthStatusOK, + }) + return + } + + // Aggregate health from all checkers + resp := AggregateHealth(r.Context(), checkers...) + + // Return 503 if unhealthy, otherwise 200 + status := http.StatusOK + if resp.Status == HealthStatusUnhealthy { + status = http.StatusServiceUnavailable + } + writeJSON(w, status, resp) } // handleAPIv1 is the catch-all handler for /api/v1/* routes. diff --git a/internal/api/server.go b/internal/api/server.go index 96ce90e4..1c0da532 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -20,6 +20,9 @@ type Server struct { router *http.ServeMux listener net.Listener + // Health checkers for component health reporting + healthCheckers []HealthChecker + // Lifecycle state started bool startTime time.Time @@ -160,3 +163,20 @@ func (s *Server) Uptime() time.Duration { } return time.Since(s.startTime) } + +// RegisterHealthChecker adds a health checker to the server. +// Health checkers are called when the /health endpoint is accessed. +func (s *Server) RegisterHealthChecker(checker HealthChecker) { + s.mu.Lock() + defer s.mu.Unlock() + s.healthCheckers = append(s.healthCheckers, checker) +} + +// GetHealthCheckers returns a copy of the registered health checkers. +func (s *Server) GetHealthCheckers() []HealthChecker { + s.mu.RLock() + defer s.mu.RUnlock() + checkers := make([]HealthChecker, len(s.healthCheckers)) + copy(checkers, s.healthCheckers) + return checkers +} From 098f467dcf705702d3196dc47957e867af7072df Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:01:13 -0600 Subject: [PATCH 06/37] feat(api): implement /api/v1/status endpoint with version and capacity info - Add version.go with build-time ldflags support (Version, GitCommit, BuildTime) - Add StatusProvider interface for filesystem status injection - Enhance handleStatus with build info and optional capacity - Add status endpoint tests with mock provider Task: #5595 --- internal/api/routes.go | 21 ++++++-- internal/api/routes_test.go | 99 +++++++++++++++++++++++++++++++++++++ internal/api/server.go | 32 ++++++++++++ internal/api/version.go | 36 ++++++++++++++ 4 files changed, 185 insertions(+), 3 deletions(-) create mode 100644 internal/api/version.go diff --git a/internal/api/routes.go b/internal/api/routes.go index acaca5d8..7e8b7136 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -65,17 +65,32 @@ func (s *Server) handleAPIv1(w http.ResponseWriter, r *http.Request) { } // handleStatus handles GET /api/v1/status requests. +// Returns comprehensive filesystem status including version, uptime, and capacity. func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET") return } - writeJSON(w, http.StatusOK, StatusResponse{ + build := GetBuildInfo() + resp := StatusResponse{ Status: "ok", - Version: "dev", + Version: build.Version, + GitCommit: build.GitCommit, + BuildTime: build.BuildTime, + GoVersion: build.GoVersion, UptimeSeconds: int64(s.Uptime().Seconds()), - }) + } + + // Add filesystem status if provider is available + if provider := s.GetStatusProvider(); provider != nil { + resp.MountPath = provider.MountPath() + resp.DevicePath = provider.DevicePath() + resp.MountState = provider.MountState() + resp.Capacity = provider.Capacity() + } + + writeJSON(w, http.StatusOK, resp) } // handleStats handles GET /api/v1/stats/* requests. diff --git a/internal/api/routes_test.go b/internal/api/routes_test.go index 632be3b2..9b7dd713 100644 --- a/internal/api/routes_test.go +++ b/internal/api/routes_test.go @@ -173,3 +173,102 @@ func TestRoutes_HealthHEAD(t *testing.T) { t.Errorf("expected status 200, got %d", resp.StatusCode) } } + +func TestRoutes_Status_WithBuildInfo(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/status") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + var status StatusResponse + if err := json.NewDecoder(resp.Body).Decode(&status); err != nil { + t.Fatalf("decode error: %v", err) + } + + // Should have Go version + if status.GoVersion == "" { + t.Error("expected go_version to be set") + } + if !strings.HasPrefix(status.GoVersion, "go") { + t.Errorf("expected go_version to start with 'go', got %q", status.GoVersion) + } + + // Uptime should be positive (since server was started) + if status.UptimeSeconds < 0 { + t.Errorf("expected positive uptime, got %d", status.UptimeSeconds) + } +} + +// mockStatusProvider implements StatusProvider for testing. +type mockStatusProvider struct { + mountPath string + devicePath string + mountState MountState + capacity *CapacityInfo +} + +func (m *mockStatusProvider) MountPath() string { return m.mountPath } +func (m *mockStatusProvider) DevicePath() string { return m.devicePath } +func (m *mockStatusProvider) MountState() MountState { return m.mountState } +func (m *mockStatusProvider) Capacity() *CapacityInfo { return m.capacity } + +func TestRoutes_Status_WithStatusProvider(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Set up mock status provider + server.SetStatusProvider(&mockStatusProvider{ + mountPath: "/mnt/test", + devicePath: "/dev/sda1", + mountState: MountStateMounted, + capacity: &CapacityInfo{ + TotalBytes: 1073741824, // 1GB + UsedBytes: 536870912, // 512MB + FreeBytes: 536870912, + UsedPercent: 50.0, + TotalBlocks: 1024, + UsedBlocks: 512, + FreeBlocks: 512, + }, + }) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/status") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + var status StatusResponse + if err := json.NewDecoder(resp.Body).Decode(&status); err != nil { + t.Fatalf("decode error: %v", err) + } + + if status.MountPath != "/mnt/test" { + t.Errorf("expected mount_path '/mnt/test', got %q", status.MountPath) + } + if status.DevicePath != "/dev/sda1" { + t.Errorf("expected device_path '/dev/sda1', got %q", status.DevicePath) + } + if status.MountState != MountStateMounted { + t.Errorf("expected mount_state 'mounted', got %q", status.MountState) + } + if status.Capacity == nil { + t.Fatal("expected capacity to be set") + } + if status.Capacity.UsedPercent != 50.0 { + t.Errorf("expected used_percent 50.0, got %f", status.Capacity.UsedPercent) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index 1c0da532..6550d1dc 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -23,6 +23,9 @@ type Server struct { // Health checkers for component health reporting healthCheckers []HealthChecker + // Status provider for filesystem status (optional) + statusProvider StatusProvider + // Lifecycle state started bool startTime time.Time @@ -180,3 +183,32 @@ func (s *Server) GetHealthCheckers() []HealthChecker { copy(checkers, s.healthCheckers) return checkers } + +// StatusProvider provides filesystem status information. +type StatusProvider interface { + // MountPath returns the current mount path. + MountPath() string + + // DevicePath returns the underlying device path. + DevicePath() string + + // MountState returns the current mount state. + MountState() MountState + + // Capacity returns storage capacity information. + Capacity() *CapacityInfo +} + +// SetStatusProvider sets the status provider for filesystem status. +func (s *Server) SetStatusProvider(provider StatusProvider) { + s.mu.Lock() + defer s.mu.Unlock() + s.statusProvider = provider +} + +// GetStatusProvider returns the current status provider. +func (s *Server) GetStatusProvider() StatusProvider { + s.mu.RLock() + defer s.mu.RUnlock() + return s.statusProvider +} diff --git a/internal/api/version.go b/internal/api/version.go new file mode 100644 index 00000000..d9e6a50f --- /dev/null +++ b/internal/api/version.go @@ -0,0 +1,36 @@ +package api + +import "runtime" + +// Build-time variables set via ldflags: +// -ldflags "-X github.com/supporttools/GoClusterFS/internal/api.Version=1.0.0 +// -X github.com/supporttools/GoClusterFS/internal/api.GitCommit=abc123 +// -X github.com/supporttools/GoClusterFS/internal/api.BuildTime=2024-01-01T00:00:00Z" +var ( + // Version is the semantic version of the build. + Version = "dev" + + // GitCommit is the git commit hash of the build. + GitCommit = "" + + // BuildTime is the time the build was created. + BuildTime = "" +) + +// BuildInfo contains build version information. +type BuildInfo struct { + Version string `json:"version"` + GitCommit string `json:"git_commit,omitempty"` + BuildTime string `json:"build_time,omitempty"` + GoVersion string `json:"go_version"` +} + +// GetBuildInfo returns the current build information. +func GetBuildInfo() BuildInfo { + return BuildInfo{ + Version: Version, + GitCommit: GitCommit, + BuildTime: BuildTime, + GoVersion: runtime.Version(), + } +} From a247e98ff629d15e1f7308c6ddfb05d431cd208d Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:05:57 -0600 Subject: [PATCH 07/37] feat(api): integrate API server into mount command - Add fsStatusProvider to expose filesystem status via API - Start API server on :8080 after FUSE mount succeeds - Register health checker and status provider - Add graceful shutdown in signal handler and exit cleanup Task: #5596 --- cmd/mount/main.go | 78 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/cmd/mount/main.go b/cmd/mount/main.go index ed28fc91..9fcd1aea 100644 --- a/cmd/mount/main.go +++ b/cmd/mount/main.go @@ -18,6 +18,7 @@ import ( "github.com/supporttools/GoClusterFS/internal/cache" "github.com/supporttools/GoClusterFS/internal/cache/broadcast" "github.com/supporttools/GoClusterFS/internal/dir" + "github.com/supporttools/GoClusterFS/internal/api" "github.com/supporttools/GoClusterFS/internal/extent" "github.com/supporttools/GoClusterFS/internal/goclusterfs" "github.com/supporttools/GoClusterFS/internal/inode" @@ -31,6 +32,49 @@ import ( "github.com/supporttools/GoClusterFS/internal/trim" ) +// fsStatusProvider implements api.StatusProvider by wrapping the filesystem. +type fsStatusProvider struct { + mountPath string + devicePath string + dev *storage.Device + bitmapMgr *bitmap.Region +} + +func (p *fsStatusProvider) MountPath() string { return p.mountPath } +func (p *fsStatusProvider) DevicePath() string { return p.devicePath } + +func (p *fsStatusProvider) MountState() api.MountState { + // If we get here, the filesystem is mounted and running + return api.MountStateMounted +} + +func (p *fsStatusProvider) Capacity() *api.CapacityInfo { + totalBlocks := p.bitmapMgr.TotalBlocks() + freeBlocks := p.bitmapMgr.FreeCount() + usedBlocks := totalBlocks - freeBlocks + + const blockSize uint64 = 1024 * 1024 // 1MB blocks + totalBytes := totalBlocks * blockSize + usedBytes := usedBlocks * blockSize + freeBytes := freeBlocks * blockSize + + var usedPercent float64 + if totalBlocks > 0 { + usedPercent = float64(usedBlocks) / float64(totalBlocks) * 100 + } + + return &api.CapacityInfo{ + TotalBytes: totalBytes, + UsedBytes: usedBytes, + FreeBytes: freeBytes, + UsedPercent: usedPercent, + TotalBlocks: totalBlocks, + UsedBlocks: usedBlocks, + FreeBlocks: freeBlocks, + BlockSizeBytes: blockSize, + } +} + func main() { var ( devicePath = flag.String("device", "", "Path to block device or image file") @@ -353,6 +397,26 @@ func main() { log.Fatalf("Failed to mount: %v", err) } + // Start API server for management and monitoring + apiCfg := api.DefaultConfig().WithListenAddr(":8080") + apiServer, err := api.NewServer(apiCfg) + if err != nil { + log.Printf("Warning: Failed to create API server: %v", err) + } else { + apiServer.SetStatusProvider(&fsStatusProvider{ + mountPath: *mountPoint, + devicePath: *devicePath, + dev: dev, + bitmapMgr: bm, + }) + apiServer.RegisterHealthChecker(api.DefaultHealthChecker()) + if err := apiServer.Start(ctx); err != nil { + log.Printf("Warning: Failed to start API server: %v", err) + } else { + log.Printf("API server listening on %s", apiServer.Addr()) + } + } + // Handle signals for clean unmount sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) @@ -360,6 +424,13 @@ func main() { <-sigChan log.Println("Received signal, unmounting...") + // Stop API server first + if apiServer != nil { + if err := apiServer.Stop(); err != nil { + log.Printf("Warning: Failed to stop API server: %v", err) + } + } + // Close filesystem (stops snapshot worker, TRIM, journal, etc.) nodeReg.Stop() if err := gfs.Close(); err != nil { @@ -380,6 +451,13 @@ func main() { // Wait for filesystem to be unmounted - this blocks until unmount server.Wait() + // Stop API server + if apiServer != nil { + if err := apiServer.Stop(); err != nil { + log.Printf("Warning: Failed to stop API server on exit: %v", err) + } + } + // Clean shutdown - close filesystem (handles snapshot worker, TRIM, journal) nodeReg.Stop() if err := gfs.Close(); err != nil { From dd68b189d5afd243c9be18203a91cadebcc99fc8 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:08:13 -0600 Subject: [PATCH 08/37] feat(api): add CLI flags for API server configuration - Add -api flag to enable/disable API server (default: enabled) - Add -api-addr for listen address (default: :8080) - Add -api-token for Bearer token authentication - Add -api-cors for comma-separated CORS allowed origins - Wire flags to API server configuration via fluent API Task: #5597 --- cmd/mount/main.go | 59 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 15 deletions(-) diff --git a/cmd/mount/main.go b/cmd/mount/main.go index 9fcd1aea..98857a7e 100644 --- a/cmd/mount/main.go +++ b/cmd/mount/main.go @@ -8,6 +8,7 @@ import ( "log" "os" "os/signal" + "strings" "syscall" "time" @@ -108,6 +109,12 @@ func main() { // Snapshot configuration snapshotsEnabled = flag.Bool("snapshots", true, "Enable O(1) file snapshots via xattr") + + // API server configuration + apiEnabled = flag.Bool("api", true, "Enable HTTP API server for management") + apiAddr = flag.String("api-addr", ":8080", "API server listen address") + apiToken = flag.String("api-token", "", "Bearer token for API authentication (empty=disabled)") + apiCORS = flag.String("api-cors", "", "Comma-separated CORS allowed origins (empty=disabled)") ) flag.Parse() @@ -398,23 +405,45 @@ func main() { } // Start API server for management and monitoring - apiCfg := api.DefaultConfig().WithListenAddr(":8080") - apiServer, err := api.NewServer(apiCfg) - if err != nil { - log.Printf("Warning: Failed to create API server: %v", err) - } else { - apiServer.SetStatusProvider(&fsStatusProvider{ - mountPath: *mountPoint, - devicePath: *devicePath, - dev: dev, - bitmapMgr: bm, - }) - apiServer.RegisterHealthChecker(api.DefaultHealthChecker()) - if err := apiServer.Start(ctx); err != nil { - log.Printf("Warning: Failed to start API server: %v", err) + var apiServer *api.Server + if *apiEnabled { + // Parse CORS origins from comma-separated string + var corsOrigins []string + if *apiCORS != "" { + for _, origin := range strings.Split(*apiCORS, ",") { + origin = strings.TrimSpace(origin) + if origin != "" { + corsOrigins = append(corsOrigins, origin) + } + } + } + + apiCfg := api.DefaultConfig(). + WithListenAddr(*apiAddr). + WithAuthToken(*apiToken). + WithCORSOrigins(corsOrigins...) + + var err error + apiServer, err = api.NewServer(apiCfg) + if err != nil { + log.Printf("Warning: Failed to create API server: %v", err) } else { - log.Printf("API server listening on %s", apiServer.Addr()) + apiServer.SetStatusProvider(&fsStatusProvider{ + mountPath: *mountPoint, + devicePath: *devicePath, + dev: dev, + bitmapMgr: bm, + }) + apiServer.RegisterHealthChecker(api.DefaultHealthChecker()) + if err := apiServer.Start(ctx); err != nil { + log.Printf("Warning: Failed to start API server: %v", err) + } else { + log.Printf("API server listening on %s (auth=%v, cors=%v)", + apiServer.Addr(), *apiToken != "", len(corsOrigins) > 0) + } } + } else { + log.Println("API server: disabled") } // Handle signals for clean unmount From 68450f4337b00daff140f0bd5de18e2784c84c43 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:12:17 -0600 Subject: [PATCH 09/37] feat(fs): add SnapshotRegistry() accessor for API endpoints Add thread-safe accessor method to expose snapshot registry for API endpoints. Uses RLock since we're only reading the pointer and the Registry itself manages its own concurrent access with internal mutex. Task: #5598 --- internal/goclusterfs/fs.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/internal/goclusterfs/fs.go b/internal/goclusterfs/fs.go index 2ef2478a..01c23e29 100644 --- a/internal/goclusterfs/fs.go +++ b/internal/goclusterfs/fs.go @@ -435,6 +435,15 @@ func (f *FS) RootDir() *Dir { } } +// SnapshotRegistry returns the snapshot registry for API endpoints. +// Returns nil if snapshots are not enabled. +// Thread-safe: the returned Registry has its own internal mutex. +func (f *FS) SnapshotRegistry() *snapshot.Registry { + f.mu.RLock() + defer f.mu.RUnlock() + return f.snapshotReg +} + // hashString returns a 64-bit FNV-1a hash of the string. // Used for journal verification of filenames. func hashString(s string) uint64 { From 760ffe584e9f12820af1eff41f2a794aeae75be2 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:19:24 -0600 Subject: [PATCH 10/37] feat(stats): create internal/stats package structure Add unified statistics collection and aggregation package: - stats.go: Core types (Snapshot, CacheStats, JournalStats, etc.) and provider interfaces for component decoupling - collector.go: Collector with TTL-based caching to aggregate statistics from multiple providers - cache.go: Cache state utilities (CacheInfo, CachedSnapshot) - errors.go: Package-specific error definitions - doc.go: Package documentation - stats_test.go: Comprehensive unit tests (16 tests) The collector uses a pull model where providers are queried on demand, with configurable cache TTL to avoid expensive repeated queries. Preset configs available for different use cases: DefaultConfig (1s TTL), HighFrequencyConfig (100ms), LowOverheadConfig (10s). Task: #5599 --- internal/stats/cache.go | 91 ++++++++ internal/stats/collector.go | 214 +++++++++++++++++ internal/stats/doc.go | 48 ++++ internal/stats/errors.go | 12 + internal/stats/stats.go | 207 +++++++++++++++++ internal/stats/stats_test.go | 436 +++++++++++++++++++++++++++++++++++ 6 files changed, 1008 insertions(+) create mode 100644 internal/stats/cache.go create mode 100644 internal/stats/collector.go create mode 100644 internal/stats/doc.go create mode 100644 internal/stats/errors.go create mode 100644 internal/stats/stats.go create mode 100644 internal/stats/stats_test.go diff --git a/internal/stats/cache.go b/internal/stats/cache.go new file mode 100644 index 00000000..10f25979 --- /dev/null +++ b/internal/stats/cache.go @@ -0,0 +1,91 @@ +package stats + +import "time" + +// CacheInfo contains metadata about the statistics cache state. +type CacheInfo struct { + // Valid indicates if the cache contains valid data. + Valid bool `json:"valid"` + + // Age is how long since the cached data was collected. + Age time.Duration `json:"age"` + + // TTL is the configured cache time-to-live. + TTL time.Duration `json:"ttl"` + + // Stale indicates if the cache is past its TTL (needs refresh). + Stale bool `json:"stale"` + + // LastCollected is when the cached snapshot was collected. + LastCollected time.Time `json:"last_collected,omitempty"` +} + +// CacheInfo returns information about the current cache state. +func (c *Collector) CacheInfo() CacheInfo { + c.mu.RLock() + defer c.mu.RUnlock() + + info := CacheInfo{ + Valid: c.cacheValid, + TTL: c.config.CacheTTL, + } + + if c.cacheValid { + info.Age = time.Since(c.cacheTime) + info.LastCollected = c.cacheTime + info.Stale = info.Age >= c.config.CacheTTL + } + + return info +} + +// IsCacheValid returns true if the cache contains valid, non-stale data. +func (c *Collector) IsCacheValid() bool { + c.mu.RLock() + defer c.mu.RUnlock() + + return c.cacheValid && time.Since(c.cacheTime) < c.config.CacheTTL +} + +// CacheAge returns how long since the cache was last refreshed. +// Returns 0 if the cache is not valid. +func (c *Collector) CacheAge() time.Duration { + c.mu.RLock() + defer c.mu.RUnlock() + + if !c.cacheValid { + return 0 + } + return time.Since(c.cacheTime) +} + +// CachedSnapshot wraps a Snapshot with cache metadata. +// This is useful for API responses that need to indicate cache freshness. +type CachedSnapshot struct { + // Snapshot contains the actual statistics. + *Snapshot + + // FromCache indicates if this snapshot was served from cache. + FromCache bool `json:"from_cache"` + + // CacheAge is how old the cached data is. + CacheAge time.Duration `json:"cache_age,omitempty"` +} + +// CollectWithMeta returns a snapshot along with cache metadata. +func (c *Collector) CollectWithMeta() CachedSnapshot { + c.mu.RLock() + wasValid := c.cacheValid && time.Since(c.cacheTime) < c.config.CacheTTL + c.mu.RUnlock() + + snapshot := c.Collect() + + c.mu.RLock() + defer c.mu.RUnlock() + + return CachedSnapshot{ + Snapshot: snapshot, + FromCache: wasValid, + CacheAge: time.Since(c.cacheTime), + } +} diff --git a/internal/stats/collector.go b/internal/stats/collector.go new file mode 100644 index 00000000..f395081e --- /dev/null +++ b/internal/stats/collector.go @@ -0,0 +1,214 @@ +package stats + +import ( + "sync" + "time" +) + +// Collector aggregates statistics from multiple components. +// It caches collected statistics for a configurable TTL to avoid +// expensive repeated queries. +type Collector struct { + mu sync.RWMutex + config Config + + // Providers + cacheProvider CacheStatsProvider + journalProvider JournalStatsProvider + filesystemProvider FilesystemStatsProvider + lockProvider LockStatsProvider + + // Cached snapshot + cache *Snapshot + cacheTime time.Time + cacheValid bool +} + +// NewCollector creates a new statistics collector with the given configuration. +func NewCollector(cfg Config) *Collector { + return &Collector{ + config: cfg, + } +} + +// SetCacheProvider sets the cache statistics provider. +func (c *Collector) SetCacheProvider(provider CacheStatsProvider) { + c.mu.Lock() + defer c.mu.Unlock() + c.cacheProvider = provider + c.invalidateCache() +} + +// SetJournalProvider sets the journal statistics provider. +func (c *Collector) SetJournalProvider(provider JournalStatsProvider) { + c.mu.Lock() + defer c.mu.Unlock() + c.journalProvider = provider + c.invalidateCache() +} + +// SetFilesystemProvider sets the filesystem statistics provider. +func (c *Collector) SetFilesystemProvider(provider FilesystemStatsProvider) { + c.mu.Lock() + defer c.mu.Unlock() + c.filesystemProvider = provider + c.invalidateCache() +} + +// SetLockProvider sets the lock statistics provider. +func (c *Collector) SetLockProvider(provider LockStatsProvider) { + c.mu.Lock() + defer c.mu.Unlock() + c.lockProvider = provider + c.invalidateCache() +} + +// Collect returns a snapshot of all current statistics. +// The snapshot may be cached if within the TTL period. +func (c *Collector) Collect() *Snapshot { + c.mu.RLock() + if c.cacheValid && time.Since(c.cacheTime) < c.config.CacheTTL { + snapshot := c.cache + c.mu.RUnlock() + return snapshot + } + c.mu.RUnlock() + + // Need to collect fresh stats + c.mu.Lock() + defer c.mu.Unlock() + + // Double-check after acquiring write lock + if c.cacheValid && time.Since(c.cacheTime) < c.config.CacheTTL { + return c.cache + } + + // Collect fresh statistics + snapshot := c.collectLocked() + c.cache = snapshot + c.cacheTime = time.Now() + c.cacheValid = true + + return snapshot +} + +// CollectFresh forces collection of fresh statistics, bypassing the cache. +func (c *Collector) CollectFresh() *Snapshot { + c.mu.Lock() + defer c.mu.Unlock() + + snapshot := c.collectLocked() + c.cache = snapshot + c.cacheTime = time.Now() + c.cacheValid = true + + return snapshot +} + +// InvalidateCache forces the next Collect call to fetch fresh data. +func (c *Collector) InvalidateCache() { + c.mu.Lock() + defer c.mu.Unlock() + c.invalidateCache() +} + +// invalidateCache marks the cache as invalid (caller must hold mu). +func (c *Collector) invalidateCache() { + c.cacheValid = false +} + +// collectLocked performs the actual statistics collection. +// Caller must hold c.mu. +func (c *Collector) collectLocked() *Snapshot { + snapshot := &Snapshot{ + CollectedAt: time.Now(), + } + + // Collect from each provider if available + if c.config.EnableComponentStats { + if c.cacheProvider != nil { + snapshot.Cache = c.cacheProvider.CacheStats() + } + + if c.journalProvider != nil { + snapshot.Journal = c.journalProvider.JournalStats() + } + + if c.filesystemProvider != nil { + snapshot.Filesystem = c.filesystemProvider.FilesystemStats() + } + + if c.lockProvider != nil { + snapshot.Lock = c.lockProvider.LockStats() + } + } + + return snapshot +} + +// CacheStats returns just the cache statistics. +// Returns nil if no cache provider is set. +func (c *Collector) CacheStats() *CacheStats { + c.mu.RLock() + provider := c.cacheProvider + c.mu.RUnlock() + + if provider == nil { + return nil + } + return provider.CacheStats() +} + +// JournalStats returns just the journal statistics. +// Returns nil if no journal provider is set. +func (c *Collector) JournalStats() *JournalStats { + c.mu.RLock() + provider := c.journalProvider + c.mu.RUnlock() + + if provider == nil { + return nil + } + return provider.JournalStats() +} + +// FilesystemStats returns just the filesystem statistics. +// Returns nil if no filesystem provider is set. +func (c *Collector) FilesystemStats() *FilesystemStats { + c.mu.RLock() + provider := c.filesystemProvider + c.mu.RUnlock() + + if provider == nil { + return nil + } + return provider.FilesystemStats() +} + +// LockStats returns just the lock statistics. +// Returns nil if no lock provider is set. +func (c *Collector) LockStats() *LockStats { + c.mu.RLock() + provider := c.lockProvider + c.mu.RUnlock() + + if provider == nil { + return nil + } + return provider.LockStats() +} + +// Config returns the collector's configuration. +func (c *Collector) Config() Config { + c.mu.RLock() + defer c.mu.RUnlock() + return c.config +} + +// SetConfig updates the collector's configuration. +func (c *Collector) SetConfig(cfg Config) { + c.mu.Lock() + defer c.mu.Unlock() + c.config = cfg + c.invalidateCache() +} diff --git a/internal/stats/doc.go b/internal/stats/doc.go new file mode 100644 index 00000000..cea2e452 --- /dev/null +++ b/internal/stats/doc.go @@ -0,0 +1,48 @@ +// Package stats provides unified statistics collection and aggregation for GoClusterFS. +// +// The stats package serves as an aggregation layer that collects statistics from +// multiple internal components (cache, journal, filesystem, etc.) and presents +// them through a unified interface for API endpoints and monitoring. +// +// # Architecture +// +// Unlike the metrics package which provides raw counters/gauges/histograms, +// the stats package provides high-level system status aggregation: +// +// - Cache stats: hit rates, sizes, broadcast status +// - Journal stats: transaction counts, space utilization +// - Filesystem stats: file counts, capacity, mount state +// - Lock stats: contention metrics, hint cache performance +// +// # Collection Model +// +// Statistics are collected on-demand using a "pull" model. The [Collector] queries +// registered providers when [Collector.Collect] is called. Results are cached +// with a configurable TTL to avoid expensive repeated queries. +// +// # Provider Interfaces +// +// Components implement provider interfaces to expose their statistics: +// +// - [CacheStatsProvider]: cache hit/miss rates and sizes +// - [JournalStatsProvider]: journal state and transaction stats +// - [FilesystemStatsProvider]: file counts and capacity +// - [LockStatsProvider]: lock contention metrics +// +// This interface-based approach keeps the stats package decoupled from +// internal implementation details. +// +// # Usage +// +// // Create collector with 1-second cache TTL +// cfg := stats.DefaultConfig() +// collector := stats.NewCollector(cfg) +// +// // Register providers +// collector.SetCacheProvider(cacheManager) +// collector.SetJournalProvider(journal) +// +// // Collect statistics (cached for TTL) +// snapshot := collector.Collect() +// fmt.Printf("Cache hit rate: %.2f%%\n", snapshot.Cache.InodeHitRate*100) +package stats diff --git a/internal/stats/errors.go b/internal/stats/errors.go new file mode 100644 index 00000000..6e7268b3 --- /dev/null +++ b/internal/stats/errors.go @@ -0,0 +1,12 @@ +package stats + +import "errors" + +// Package-level errors for stats collection. +var ( + // ErrInvalidTTL is returned when the cache TTL is invalid. + ErrInvalidTTL = errors.New("stats: invalid cache TTL") + + // ErrCollectorStopped is returned when operations are attempted on a stopped collector. + ErrCollectorStopped = errors.New("stats: collector is stopped") +) diff --git a/internal/stats/stats.go b/internal/stats/stats.go new file mode 100644 index 00000000..fea0e18d --- /dev/null +++ b/internal/stats/stats.go @@ -0,0 +1,207 @@ +package stats + +import "time" + +// Config holds configuration for the statistics collector. +type Config struct { + // CacheTTL is how long collected statistics are cached before re-collection. + // Shorter values provide fresher data but may impact performance. + // Default: 1 second + CacheTTL time.Duration + + // EnableComponentStats controls whether per-component stats are collected. + // Disable for minimal overhead in production. + // Default: true + EnableComponentStats bool +} + +// DefaultConfig returns a Config with sensible defaults. +func DefaultConfig() Config { + return Config{ + CacheTTL: 1 * time.Second, + EnableComponentStats: true, + } +} + +// HighFrequencyConfig returns a Config optimized for frequent collection. +// Use when stats need to be very fresh (e.g., real-time dashboards). +func HighFrequencyConfig() Config { + return Config{ + CacheTTL: 100 * time.Millisecond, + EnableComponentStats: true, + } +} + +// LowOverheadConfig returns a Config optimized for minimal overhead. +// Use in production when stats are infrequently accessed. +func LowOverheadConfig() Config { + return Config{ + CacheTTL: 10 * time.Second, + EnableComponentStats: false, + } +} + +// Validate checks that the configuration is valid. +func (c *Config) Validate() error { + if c.CacheTTL < 0 { + return ErrInvalidTTL + } + return nil +} + +// Snapshot contains a point-in-time snapshot of all system statistics. +// All fields are optional and may be nil if the corresponding component +// is not available or statistics collection is disabled. +type Snapshot struct { + // CollectedAt is when this snapshot was collected. + CollectedAt time.Time `json:"collected_at"` + + // Cache contains cache hit/miss statistics. + Cache *CacheStats `json:"cache,omitempty"` + + // Journal contains journal transaction statistics. + Journal *JournalStats `json:"journal,omitempty"` + + // Filesystem contains filesystem capacity and file count statistics. + Filesystem *FilesystemStats `json:"filesystem,omitempty"` + + // Lock contains lock contention statistics. + Lock *LockStats `json:"lock,omitempty"` +} + +// CacheStats contains aggregated cache statistics. +type CacheStats struct { + // Inode cache + InodeCacheSize int `json:"inode_cache_size"` + InodeCacheHits uint64 `json:"inode_cache_hits"` + InodeCacheMisses uint64 `json:"inode_cache_misses"` + InodeHitRate float64 `json:"inode_hit_rate"` + + // Extent cache + ExtentCacheSize int `json:"extent_cache_size"` + ExtentCacheHits uint64 `json:"extent_cache_hits"` + ExtentCacheMisses uint64 `json:"extent_cache_misses"` + ExtentHitRate float64 `json:"extent_hit_rate"` + + // Negative cache (caches "not found" results) + NegativeCacheSize int `json:"negative_cache_size"` + NegativeHits uint64 `json:"negative_hits"` + NegativeMisses uint64 `json:"negative_misses"` + + // Broadcast/network invalidation stats + BroadcastEnabled bool `json:"broadcast_enabled"` + InvalidationsSent uint64 `json:"invalidations_sent,omitempty"` + InvalidationsReceived uint64 `json:"invalidations_received,omitempty"` + BroadcastDuplicates uint64 `json:"broadcast_duplicates,omitempty"` + MulticastEnabled bool `json:"multicast_enabled,omitempty"` + PeerCount int `json:"peer_count,omitempty"` +} + +// JournalStats contains journal transaction statistics. +type JournalStats struct { + // State is the current journal state (clean, dirty, recovering). + State string `json:"state"` + + // HeadOffset is the current write position in the journal. + HeadOffset uint32 `json:"head_offset"` + + // TailOffset is the oldest valid entry position. + TailOffset uint32 `json:"tail_offset"` + + // AvailableSpace is bytes available for new entries. + AvailableSpace uint32 `json:"available_space"` + + // ActiveTxnCount is the number of in-flight transactions. + ActiveTxnCount int `json:"active_txn_count"` + + // CommitCount is the total number of committed transactions. + CommitCount uint64 `json:"commit_count"` + + // BytesWritten is the total bytes written to the journal. + BytesWritten uint64 `json:"bytes_written"` + + // LastCheckpointSeq is the sequence number of the last checkpoint. + LastCheckpointSeq uint64 `json:"last_checkpoint_seq"` + + // BatchSyncCount is the number of batch syncs (for CommitBatch mode). + BatchSyncCount uint64 `json:"batch_sync_count,omitempty"` +} + +// FilesystemStats contains filesystem capacity and usage statistics. +type FilesystemStats struct { + // TotalBytes is the total filesystem capacity in bytes. + TotalBytes uint64 `json:"total_bytes"` + + // UsedBytes is the bytes currently in use. + UsedBytes uint64 `json:"used_bytes"` + + // FreeBytes is the bytes available for new data. + FreeBytes uint64 `json:"free_bytes"` + + // UsedPercent is the percentage of capacity in use. + UsedPercent float64 `json:"used_percent"` + + // TotalBlocks is the total number of blocks. + TotalBlocks uint64 `json:"total_blocks"` + + // UsedBlocks is the number of blocks in use. + UsedBlocks uint64 `json:"used_blocks"` + + // FreeBlocks is the number of free blocks. + FreeBlocks uint64 `json:"free_blocks"` + + // FileCount is the total number of files. + FileCount uint64 `json:"file_count,omitempty"` + + // DirectoryCount is the total number of directories. + DirectoryCount uint64 `json:"directory_count,omitempty"` + + // SnapshotCount is the number of active snapshots. + SnapshotCount int `json:"snapshot_count,omitempty"` +} + +// LockStats contains lock contention and hint cache statistics. +type LockStats struct { + // HintCacheHits is the number of lock hint cache hits. + HintCacheHits uint64 `json:"hint_cache_hits"` + + // HintCacheMisses is the number of lock hint cache misses. + HintCacheMisses uint64 `json:"hint_cache_misses"` + + // HintCacheHitRate is the hit rate as a ratio (0.0-1.0). + HintCacheHitRate float64 `json:"hint_cache_hit_rate"` + + // ActiveLocks is the number of currently held locks. + ActiveLocks int `json:"active_locks,omitempty"` + + // PendingLocks is the number of locks waiting to be acquired. + PendingLocks int `json:"pending_locks,omitempty"` +} + +// CacheStatsProvider is implemented by components that provide cache statistics. +type CacheStatsProvider interface { + // CacheStats returns current cache statistics. + // Returns nil if cache statistics are not available. + CacheStats() *CacheStats +} + +// JournalStatsProvider is implemented by components that provide journal statistics. +type JournalStatsProvider interface { + // JournalStats returns current journal statistics. + // Returns nil if journal statistics are not available. + JournalStats() *JournalStats +} + +// FilesystemStatsProvider is implemented by components that provide filesystem statistics. +type FilesystemStatsProvider interface { + // FilesystemStats returns current filesystem statistics. + // Returns nil if filesystem statistics are not available. + FilesystemStats() *FilesystemStats +} + +// LockStatsProvider is implemented by components that provide lock statistics. +type LockStatsProvider interface { + // LockStats returns current lock statistics. + // Returns nil if lock statistics are not available. + LockStats() *LockStats +} diff --git a/internal/stats/stats_test.go b/internal/stats/stats_test.go new file mode 100644 index 00000000..ab8f5ed8 --- /dev/null +++ b/internal/stats/stats_test.go @@ -0,0 +1,436 @@ +package stats + +import ( + "testing" + "time" +) + +// mockCacheProvider implements CacheStatsProvider for testing. +type mockCacheProvider struct { + stats *CacheStats +} + +func (m *mockCacheProvider) CacheStats() *CacheStats { + return m.stats +} + +// mockJournalProvider implements JournalStatsProvider for testing. +type mockJournalProvider struct { + stats *JournalStats +} + +func (m *mockJournalProvider) JournalStats() *JournalStats { + return m.stats +} + +// mockFilesystemProvider implements FilesystemStatsProvider for testing. +type mockFilesystemProvider struct { + stats *FilesystemStats +} + +func (m *mockFilesystemProvider) FilesystemStats() *FilesystemStats { + return m.stats +} + +// mockLockProvider implements LockStatsProvider for testing. +type mockLockProvider struct { + stats *LockStats +} + +func (m *mockLockProvider) LockStats() *LockStats { + return m.stats +} + +func TestDefaultConfig(t *testing.T) { + cfg := DefaultConfig() + + if cfg.CacheTTL != 1*time.Second { + t.Errorf("expected CacheTTL 1s, got %v", cfg.CacheTTL) + } + if !cfg.EnableComponentStats { + t.Error("expected EnableComponentStats true") + } +} + +func TestConfig_Validate(t *testing.T) { + tests := []struct { + name string + config Config + wantErr error + }{ + { + name: "valid default", + config: DefaultConfig(), + wantErr: nil, + }, + { + name: "valid zero TTL", + config: Config{CacheTTL: 0}, + wantErr: nil, + }, + { + name: "invalid negative TTL", + config: Config{CacheTTL: -1 * time.Second}, + wantErr: ErrInvalidTTL, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.config.Validate() + if err != tt.wantErr { + t.Errorf("Validate() = %v, want %v", err, tt.wantErr) + } + }) + } +} + +func TestNewCollector(t *testing.T) { + cfg := DefaultConfig() + collector := NewCollector(cfg) + + if collector == nil { + t.Fatal("NewCollector returned nil") + } +} + +func TestCollector_Collect_Empty(t *testing.T) { + cfg := DefaultConfig() + collector := NewCollector(cfg) + + snapshot := collector.Collect() + + if snapshot == nil { + t.Fatal("Collect returned nil") + } + if snapshot.CollectedAt.IsZero() { + t.Error("CollectedAt should not be zero") + } + if snapshot.Cache != nil { + t.Error("expected Cache to be nil with no provider") + } + if snapshot.Journal != nil { + t.Error("expected Journal to be nil with no provider") + } +} + +func TestCollector_SetProviders(t *testing.T) { + cfg := DefaultConfig() + collector := NewCollector(cfg) + + // Set cache provider + cacheStats := &CacheStats{ + InodeCacheSize: 100, + InodeHitRate: 0.95, + } + collector.SetCacheProvider(&mockCacheProvider{stats: cacheStats}) + + // Set journal provider + journalStats := &JournalStats{ + State: "clean", + CommitCount: 500, + } + collector.SetJournalProvider(&mockJournalProvider{stats: journalStats}) + + // Collect and verify + snapshot := collector.Collect() + + if snapshot.Cache == nil { + t.Fatal("expected Cache to be set") + } + if snapshot.Cache.InodeCacheSize != 100 { + t.Errorf("expected InodeCacheSize 100, got %d", snapshot.Cache.InodeCacheSize) + } + if snapshot.Cache.InodeHitRate != 0.95 { + t.Errorf("expected InodeHitRate 0.95, got %f", snapshot.Cache.InodeHitRate) + } + + if snapshot.Journal == nil { + t.Fatal("expected Journal to be set") + } + if snapshot.Journal.State != "clean" { + t.Errorf("expected State 'clean', got %q", snapshot.Journal.State) + } + if snapshot.Journal.CommitCount != 500 { + t.Errorf("expected CommitCount 500, got %d", snapshot.Journal.CommitCount) + } +} + +func TestCollector_CacheTTL(t *testing.T) { + cfg := Config{ + CacheTTL: 50 * time.Millisecond, + EnableComponentStats: true, + } + collector := NewCollector(cfg) + + // Track how many times provider is called + callCount := 0 + provider := &countingProvider{count: &callCount} + collector.SetCacheProvider(provider) + + // First collect + snapshot1 := collector.Collect() + if callCount != 1 { + t.Errorf("expected 1 call, got %d", callCount) + } + + // Second collect within TTL - should use cache + snapshot2 := collector.Collect() + if callCount != 1 { + t.Errorf("expected still 1 call (cached), got %d", callCount) + } + + // Verify same snapshot returned (via CollectedAt) + if !snapshot1.CollectedAt.Equal(snapshot2.CollectedAt) { + t.Error("expected cached snapshot to have same CollectedAt") + } + + // Wait for TTL to expire + time.Sleep(60 * time.Millisecond) + + // Third collect after TTL - should refresh + snapshot3 := collector.Collect() + if callCount != 2 { + t.Errorf("expected 2 calls after TTL, got %d", callCount) + } + if snapshot3.CollectedAt.Equal(snapshot1.CollectedAt) { + t.Error("expected fresh snapshot after TTL") + } +} + +// countingProvider tracks how many times CacheStats is called. +type countingProvider struct { + count *int +} + +func (p *countingProvider) CacheStats() *CacheStats { + *p.count++ + return &CacheStats{InodeCacheSize: *p.count} +} + +func TestCollector_CollectFresh(t *testing.T) { + cfg := Config{ + CacheTTL: 1 * time.Hour, // Long TTL + EnableComponentStats: true, + } + collector := NewCollector(cfg) + + callCount := 0 + provider := &countingProvider{count: &callCount} + collector.SetCacheProvider(provider) + + // First collect + collector.Collect() + if callCount != 1 { + t.Errorf("expected 1 call, got %d", callCount) + } + + // CollectFresh should bypass cache + collector.CollectFresh() + if callCount != 2 { + t.Errorf("expected 2 calls with CollectFresh, got %d", callCount) + } +} + +func TestCollector_InvalidateCache(t *testing.T) { + cfg := Config{ + CacheTTL: 1 * time.Hour, // Long TTL + EnableComponentStats: true, + } + collector := NewCollector(cfg) + + callCount := 0 + provider := &countingProvider{count: &callCount} + collector.SetCacheProvider(provider) + + // First collect + collector.Collect() + if callCount != 1 { + t.Errorf("expected 1 call, got %d", callCount) + } + + // Invalidate cache + collector.InvalidateCache() + + // Next collect should refresh + collector.Collect() + if callCount != 2 { + t.Errorf("expected 2 calls after InvalidateCache, got %d", callCount) + } +} + +func TestCollector_DisabledComponentStats(t *testing.T) { + cfg := Config{ + CacheTTL: 1 * time.Second, + EnableComponentStats: false, // Disabled + } + collector := NewCollector(cfg) + + // Set provider + collector.SetCacheProvider(&mockCacheProvider{ + stats: &CacheStats{InodeCacheSize: 100}, + }) + + // Collect - should not include stats + snapshot := collector.Collect() + + if snapshot.Cache != nil { + t.Error("expected Cache to be nil when component stats disabled") + } +} + +func TestCollector_DirectStats(t *testing.T) { + cfg := DefaultConfig() + collector := NewCollector(cfg) + + // No providers - should return nil + if collector.CacheStats() != nil { + t.Error("expected nil CacheStats with no provider") + } + if collector.JournalStats() != nil { + t.Error("expected nil JournalStats with no provider") + } + if collector.FilesystemStats() != nil { + t.Error("expected nil FilesystemStats with no provider") + } + if collector.LockStats() != nil { + t.Error("expected nil LockStats with no provider") + } + + // Set providers and verify direct access + collector.SetCacheProvider(&mockCacheProvider{ + stats: &CacheStats{InodeCacheSize: 42}, + }) + collector.SetLockProvider(&mockLockProvider{ + stats: &LockStats{HintCacheHits: 999}, + }) + + if stats := collector.CacheStats(); stats == nil || stats.InodeCacheSize != 42 { + t.Error("expected CacheStats with InodeCacheSize 42") + } + if stats := collector.LockStats(); stats == nil || stats.HintCacheHits != 999 { + t.Error("expected LockStats with HintCacheHits 999") + } +} + +func TestCacheInfo(t *testing.T) { + cfg := Config{ + CacheTTL: 100 * time.Millisecond, + EnableComponentStats: true, + } + collector := NewCollector(cfg) + + // Before any collection + info := collector.CacheInfo() + if info.Valid { + t.Error("expected cache to be invalid before collection") + } + + // After collection + collector.Collect() + info = collector.CacheInfo() + if !info.Valid { + t.Error("expected cache to be valid after collection") + } + if info.Stale { + t.Error("expected cache to not be stale immediately after collection") + } + if info.TTL != 100*time.Millisecond { + t.Errorf("expected TTL 100ms, got %v", info.TTL) + } + + // Wait for TTL to expire + time.Sleep(110 * time.Millisecond) + info = collector.CacheInfo() + if !info.Stale { + t.Error("expected cache to be stale after TTL") + } +} + +func TestIsCacheValid(t *testing.T) { + cfg := Config{ + CacheTTL: 50 * time.Millisecond, + EnableComponentStats: true, + } + collector := NewCollector(cfg) + + // Before collection + if collector.IsCacheValid() { + t.Error("expected cache invalid before collection") + } + + // After collection + collector.Collect() + if !collector.IsCacheValid() { + t.Error("expected cache valid after collection") + } + + // After TTL expires + time.Sleep(60 * time.Millisecond) + if collector.IsCacheValid() { + t.Error("expected cache invalid after TTL") + } +} + +func TestCollectWithMeta(t *testing.T) { + cfg := Config{ + CacheTTL: 100 * time.Millisecond, + EnableComponentStats: true, + } + collector := NewCollector(cfg) + + // First collection - not from cache + result1 := collector.CollectWithMeta() + if result1.FromCache { + t.Error("expected FromCache=false on first collection") + } + + // Second collection - from cache + result2 := collector.CollectWithMeta() + if !result2.FromCache { + t.Error("expected FromCache=true on second collection") + } + if result2.CacheAge < 0 { + t.Error("expected positive CacheAge") + } +} + +func TestPresetConfigs(t *testing.T) { + // Test HighFrequencyConfig + high := HighFrequencyConfig() + if high.CacheTTL != 100*time.Millisecond { + t.Errorf("HighFrequencyConfig TTL = %v, want 100ms", high.CacheTTL) + } + if err := high.Validate(); err != nil { + t.Errorf("HighFrequencyConfig validation failed: %v", err) + } + + // Test LowOverheadConfig + low := LowOverheadConfig() + if low.CacheTTL != 10*time.Second { + t.Errorf("LowOverheadConfig TTL = %v, want 10s", low.CacheTTL) + } + if low.EnableComponentStats { + t.Error("LowOverheadConfig should have EnableComponentStats=false") + } + if err := low.Validate(); err != nil { + t.Errorf("LowOverheadConfig validation failed: %v", err) + } +} + +func TestCollector_SetConfig(t *testing.T) { + collector := NewCollector(DefaultConfig()) + + // Verify initial config + if collector.Config().CacheTTL != 1*time.Second { + t.Error("expected default TTL") + } + + // Update config + newCfg := Config{CacheTTL: 5 * time.Second, EnableComponentStats: true} + collector.SetConfig(newCfg) + + if collector.Config().CacheTTL != 5*time.Second { + t.Errorf("expected new TTL 5s, got %v", collector.Config().CacheTTL) + } +} From 3e619d73025557e74fa0b8f31a571df0c07b72ea Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:27:13 -0600 Subject: [PATCH 11/37] feat(stats): add TrimStats, SFBStats, and ClusterInfo types Add comprehensive statistics types for TRIM operations, Sparse File Bitmap allocation, and cluster node information: - TrimStats: TRIM/discard operation metrics - SFBStats: block allocation and fragmentation stats - ClusterInfo: node role, state, and peer information - PeerInfo: individual peer node details Also add provider interfaces and Collector support for all new types. Task: #5600 --- internal/stats/collector.go | 78 ++++++++++++++++ internal/stats/stats.go | 138 +++++++++++++++++++++++++++++ internal/stats/stats_test.go | 166 +++++++++++++++++++++++++++++++++++ 3 files changed, 382 insertions(+) diff --git a/internal/stats/collector.go b/internal/stats/collector.go index f395081e..f84984a6 100644 --- a/internal/stats/collector.go +++ b/internal/stats/collector.go @@ -17,6 +17,9 @@ type Collector struct { journalProvider JournalStatsProvider filesystemProvider FilesystemStatsProvider lockProvider LockStatsProvider + trimProvider TrimStatsProvider + sfbProvider SFBStatsProvider + clusterProvider ClusterInfoProvider // Cached snapshot cache *Snapshot @@ -63,6 +66,30 @@ func (c *Collector) SetLockProvider(provider LockStatsProvider) { c.invalidateCache() } +// SetTrimProvider sets the TRIM statistics provider. +func (c *Collector) SetTrimProvider(provider TrimStatsProvider) { + c.mu.Lock() + defer c.mu.Unlock() + c.trimProvider = provider + c.invalidateCache() +} + +// SetSFBProvider sets the Sparse File Bitmap statistics provider. +func (c *Collector) SetSFBProvider(provider SFBStatsProvider) { + c.mu.Lock() + defer c.mu.Unlock() + c.sfbProvider = provider + c.invalidateCache() +} + +// SetClusterProvider sets the cluster information provider. +func (c *Collector) SetClusterProvider(provider ClusterInfoProvider) { + c.mu.Lock() + defer c.mu.Unlock() + c.clusterProvider = provider + c.invalidateCache() +} + // Collect returns a snapshot of all current statistics. // The snapshot may be cached if within the TTL period. func (c *Collector) Collect() *Snapshot { @@ -141,6 +168,18 @@ func (c *Collector) collectLocked() *Snapshot { if c.lockProvider != nil { snapshot.Lock = c.lockProvider.LockStats() } + + if c.trimProvider != nil { + snapshot.Trim = c.trimProvider.TrimStats() + } + + if c.sfbProvider != nil { + snapshot.SFB = c.sfbProvider.SFBStats() + } + + if c.clusterProvider != nil { + snapshot.Cluster = c.clusterProvider.ClusterInfo() + } } return snapshot @@ -198,6 +237,45 @@ func (c *Collector) LockStats() *LockStats { return provider.LockStats() } +// TrimStats returns just the TRIM statistics. +// Returns nil if no trim provider is set. +func (c *Collector) TrimStats() *TrimStats { + c.mu.RLock() + provider := c.trimProvider + c.mu.RUnlock() + + if provider == nil { + return nil + } + return provider.TrimStats() +} + +// SFBStats returns just the Sparse File Bitmap statistics. +// Returns nil if no SFB provider is set. +func (c *Collector) SFBStats() *SFBStats { + c.mu.RLock() + provider := c.sfbProvider + c.mu.RUnlock() + + if provider == nil { + return nil + } + return provider.SFBStats() +} + +// ClusterInfo returns just the cluster information. +// Returns nil if no cluster provider is set. +func (c *Collector) ClusterInfo() *ClusterInfo { + c.mu.RLock() + provider := c.clusterProvider + c.mu.RUnlock() + + if provider == nil { + return nil + } + return provider.ClusterInfo() +} + // Config returns the collector's configuration. func (c *Collector) Config() Config { c.mu.RLock() diff --git a/internal/stats/stats.go b/internal/stats/stats.go index fea0e18d..922ce176 100644 --- a/internal/stats/stats.go +++ b/internal/stats/stats.go @@ -67,6 +67,15 @@ type Snapshot struct { // Lock contains lock contention statistics. Lock *LockStats `json:"lock,omitempty"` + + // Trim contains TRIM/discard operation statistics. + Trim *TrimStats `json:"trim,omitempty"` + + // SFB contains Sparse File Bitmap (block allocation) statistics. + SFB *SFBStats `json:"sfb,omitempty"` + + // Cluster contains cluster membership and node information. + Cluster *ClusterInfo `json:"cluster,omitempty"` } // CacheStats contains aggregated cache statistics. @@ -178,6 +187,114 @@ type LockStats struct { PendingLocks int `json:"pending_locks,omitempty"` } +// TrimStats contains TRIM/discard operation statistics. +type TrimStats struct { + // TrimOperations is the total number of TRIM operations performed. + TrimOperations uint64 `json:"trim_operations"` + + // TrimBytes is the total bytes trimmed. + TrimBytes uint64 `json:"trim_bytes"` + + // TrimBlocks is the total blocks trimmed. + TrimBlocks uint64 `json:"trim_blocks"` + + // PendingTrimBlocks is blocks queued for TRIM. + PendingTrimBlocks uint64 `json:"pending_trim_blocks,omitempty"` + + // LastTrimAt is when the last TRIM operation occurred. + LastTrimAt time.Time `json:"last_trim_at,omitempty"` + + // TrimErrors is the count of failed TRIM operations. + TrimErrors uint64 `json:"trim_errors,omitempty"` + + // TrimEnabled indicates if TRIM is enabled. + TrimEnabled bool `json:"trim_enabled"` + + // BatchSize is the current batch size for TRIM operations. + BatchSize int `json:"batch_size,omitempty"` +} + +// SFBStats contains Sparse File Bitmap (block allocation) statistics. +type SFBStats struct { + // TotalBlocks is the total number of blocks in the bitmap. + TotalBlocks uint64 `json:"total_blocks"` + + // AllocatedBlocks is the number of blocks currently allocated. + AllocatedBlocks uint64 `json:"allocated_blocks"` + + // FreeBlocks is the number of blocks available for allocation. + FreeBlocks uint64 `json:"free_blocks"` + + // AllocationPercent is the percentage of blocks allocated (0.0-100.0). + AllocationPercent float64 `json:"allocation_percent"` + + // FragmentationRatio estimates fragmentation (0.0-1.0, higher = more fragmented). + FragmentationRatio float64 `json:"fragmentation_ratio,omitempty"` + + // LargestFreeExtent is the size of the largest contiguous free region in blocks. + LargestFreeExtent uint64 `json:"largest_free_extent,omitempty"` + + // AllocationsTotal is the total number of allocation operations. + AllocationsTotal uint64 `json:"allocations_total"` + + // DeallocationsTotal is the total number of deallocation operations. + DeallocationsTotal uint64 `json:"deallocations_total"` + + // AllocationFailures is the count of failed allocations (e.g., no space). + AllocationFailures uint64 `json:"allocation_failures,omitempty"` +} + +// ClusterInfo contains cluster node and membership information. +type ClusterInfo struct { + // NodeID is this node's unique identifier. + NodeID string `json:"node_id"` + + // NodeAddress is this node's network address. + NodeAddress string `json:"node_address,omitempty"` + + // Role is this node's role (e.g., "primary", "replica", "standalone"). + Role string `json:"role"` + + // State is this node's current state (e.g., "active", "syncing", "offline"). + State string `json:"state"` + + // ClusterSize is the total number of nodes in the cluster. + ClusterSize int `json:"cluster_size"` + + // HealthyNodes is the number of nodes currently healthy. + HealthyNodes int `json:"healthy_nodes"` + + // LeaderID is the current cluster leader's ID (if applicable). + LeaderID string `json:"leader_id,omitempty"` + + // LastHeartbeatAt is when the last heartbeat was received/sent. + LastHeartbeatAt time.Time `json:"last_heartbeat_at,omitempty"` + + // JoinedAt is when this node joined the cluster. + JoinedAt time.Time `json:"joined_at,omitempty"` + + // Peers contains information about peer nodes. + Peers []PeerInfo `json:"peers,omitempty"` +} + +// PeerInfo contains information about a cluster peer node. +type PeerInfo struct { + // NodeID is the peer's unique identifier. + NodeID string `json:"node_id"` + + // Address is the peer's network address. + Address string `json:"address"` + + // State is the peer's current state. + State string `json:"state"` + + // LastSeen is when the peer was last seen. + LastSeen time.Time `json:"last_seen,omitempty"` + + // Latency is the round-trip latency to this peer in milliseconds. + Latency float64 `json:"latency_ms,omitempty"` +} + // CacheStatsProvider is implemented by components that provide cache statistics. type CacheStatsProvider interface { // CacheStats returns current cache statistics. @@ -205,3 +322,24 @@ type LockStatsProvider interface { // Returns nil if lock statistics are not available. LockStats() *LockStats } + +// TrimStatsProvider is implemented by components that provide TRIM statistics. +type TrimStatsProvider interface { + // TrimStats returns current TRIM/discard statistics. + // Returns nil if TRIM statistics are not available. + TrimStats() *TrimStats +} + +// SFBStatsProvider is implemented by components that provide block allocation statistics. +type SFBStatsProvider interface { + // SFBStats returns current Sparse File Bitmap statistics. + // Returns nil if SFB statistics are not available. + SFBStats() *SFBStats +} + +// ClusterInfoProvider is implemented by components that provide cluster information. +type ClusterInfoProvider interface { + // ClusterInfo returns current cluster membership and node information. + // Returns nil if cluster information is not available. + ClusterInfo() *ClusterInfo +} diff --git a/internal/stats/stats_test.go b/internal/stats/stats_test.go index ab8f5ed8..c7b60004 100644 --- a/internal/stats/stats_test.go +++ b/internal/stats/stats_test.go @@ -41,6 +41,33 @@ func (m *mockLockProvider) LockStats() *LockStats { return m.stats } +// mockTrimProvider implements TrimStatsProvider for testing. +type mockTrimProvider struct { + stats *TrimStats +} + +func (m *mockTrimProvider) TrimStats() *TrimStats { + return m.stats +} + +// mockSFBProvider implements SFBStatsProvider for testing. +type mockSFBProvider struct { + stats *SFBStats +} + +func (m *mockSFBProvider) SFBStats() *SFBStats { + return m.stats +} + +// mockClusterProvider implements ClusterInfoProvider for testing. +type mockClusterProvider struct { + info *ClusterInfo +} + +func (m *mockClusterProvider) ClusterInfo() *ClusterInfo { + return m.info +} + func TestDefaultConfig(t *testing.T) { cfg := DefaultConfig() @@ -434,3 +461,142 @@ func TestCollector_SetConfig(t *testing.T) { t.Errorf("expected new TTL 5s, got %v", collector.Config().CacheTTL) } } + +func TestCollector_NewProviders(t *testing.T) { + cfg := DefaultConfig() + collector := NewCollector(cfg) + + // Set all new providers + trimStats := &TrimStats{ + TrimOperations: 100, + TrimBytes: 1024 * 1024, + TrimBlocks: 256, + TrimEnabled: true, + } + collector.SetTrimProvider(&mockTrimProvider{stats: trimStats}) + + sfbStats := &SFBStats{ + TotalBlocks: 10000, + AllocatedBlocks: 7500, + FreeBlocks: 2500, + AllocationPercent: 75.0, + } + collector.SetSFBProvider(&mockSFBProvider{stats: sfbStats}) + + clusterInfo := &ClusterInfo{ + NodeID: "node-1", + Role: "primary", + State: "active", + ClusterSize: 3, + HealthyNodes: 3, + } + collector.SetClusterProvider(&mockClusterProvider{info: clusterInfo}) + + // Collect and verify + snapshot := collector.Collect() + + // Verify TrimStats + if snapshot.Trim == nil { + t.Fatal("expected Trim to be set") + } + if snapshot.Trim.TrimOperations != 100 { + t.Errorf("expected TrimOperations 100, got %d", snapshot.Trim.TrimOperations) + } + if !snapshot.Trim.TrimEnabled { + t.Error("expected TrimEnabled true") + } + + // Verify SFBStats + if snapshot.SFB == nil { + t.Fatal("expected SFB to be set") + } + if snapshot.SFB.TotalBlocks != 10000 { + t.Errorf("expected TotalBlocks 10000, got %d", snapshot.SFB.TotalBlocks) + } + if snapshot.SFB.AllocationPercent != 75.0 { + t.Errorf("expected AllocationPercent 75.0, got %f", snapshot.SFB.AllocationPercent) + } + + // Verify ClusterInfo + if snapshot.Cluster == nil { + t.Fatal("expected Cluster to be set") + } + if snapshot.Cluster.NodeID != "node-1" { + t.Errorf("expected NodeID 'node-1', got %q", snapshot.Cluster.NodeID) + } + if snapshot.Cluster.ClusterSize != 3 { + t.Errorf("expected ClusterSize 3, got %d", snapshot.Cluster.ClusterSize) + } +} + +func TestCollector_DirectStatsNewProviders(t *testing.T) { + cfg := DefaultConfig() + collector := NewCollector(cfg) + + // No providers - should return nil + if collector.TrimStats() != nil { + t.Error("expected nil TrimStats with no provider") + } + if collector.SFBStats() != nil { + t.Error("expected nil SFBStats with no provider") + } + if collector.ClusterInfo() != nil { + t.Error("expected nil ClusterInfo with no provider") + } + + // Set providers and verify direct access + collector.SetTrimProvider(&mockTrimProvider{ + stats: &TrimStats{TrimOperations: 42, TrimEnabled: true}, + }) + collector.SetSFBProvider(&mockSFBProvider{ + stats: &SFBStats{TotalBlocks: 999}, + }) + collector.SetClusterProvider(&mockClusterProvider{ + info: &ClusterInfo{NodeID: "test-node", State: "active"}, + }) + + if stats := collector.TrimStats(); stats == nil || stats.TrimOperations != 42 { + t.Error("expected TrimStats with TrimOperations 42") + } + if stats := collector.SFBStats(); stats == nil || stats.TotalBlocks != 999 { + t.Error("expected SFBStats with TotalBlocks 999") + } + if info := collector.ClusterInfo(); info == nil || info.NodeID != "test-node" { + t.Error("expected ClusterInfo with NodeID 'test-node'") + } +} + +func TestClusterInfo_WithPeers(t *testing.T) { + cfg := DefaultConfig() + collector := NewCollector(cfg) + + clusterInfo := &ClusterInfo{ + NodeID: "node-1", + NodeAddress: "192.168.1.10:8080", + Role: "primary", + State: "active", + ClusterSize: 3, + HealthyNodes: 3, + LeaderID: "node-1", + Peers: []PeerInfo{ + {NodeID: "node-2", Address: "192.168.1.11:8080", State: "active", Latency: 1.5}, + {NodeID: "node-3", Address: "192.168.1.12:8080", State: "active", Latency: 2.1}, + }, + } + collector.SetClusterProvider(&mockClusterProvider{info: clusterInfo}) + + snapshot := collector.Collect() + + if snapshot.Cluster == nil { + t.Fatal("expected Cluster to be set") + } + if len(snapshot.Cluster.Peers) != 2 { + t.Errorf("expected 2 peers, got %d", len(snapshot.Cluster.Peers)) + } + if snapshot.Cluster.Peers[0].NodeID != "node-2" { + t.Errorf("expected first peer NodeID 'node-2', got %q", snapshot.Cluster.Peers[0].NodeID) + } + if snapshot.Cluster.Peers[1].Latency != 2.1 { + t.Errorf("expected second peer Latency 2.1, got %f", snapshot.Cluster.Peers[1].Latency) + } +} From 707e96f4e73d548d2ccbe2cb46a56c56904686c5 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:34:28 -0600 Subject: [PATCH 12/37] feat(api): implement stats endpoints for cache, journal, trim, lock, sfb, cluster - Add StatsProvider interface for statistics collection - Implement /api/v1/stats endpoints: - /stats (overview with cache and journal) - /stats/cache (inode, extent, negative cache hit rates) - /stats/journal (transactions, space, checkpoints) - /stats/trim (TRIM operations and bytes) - /stats/lock (lock hint cache statistics) - /stats/sfb (block allocation statistics) - /stats/cluster (node membership and peers) - /stats/all (combined snapshot of all stats) - Add response types for all stats endpoints - Add comprehensive tests for stats handlers Task: #5602, #5603, #5604, #5605, #5606, #5607 --- internal/api/routes.go | 169 ++++++++++- internal/api/routes_test.go | 7 +- internal/api/server.go | 41 +++ internal/api/server_test.go | 561 ++++++++++++++++++++++++++++++++++++ internal/api/types.go | 69 +++++ 5 files changed, 843 insertions(+), 4 deletions(-) diff --git a/internal/api/routes.go b/internal/api/routes.go index 7e8b7136..690e1b4e 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -94,12 +94,179 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { } // handleStats handles GET /api/v1/stats/* requests. +// Routes to specific stats handlers based on the path suffix. func (s *Server) handleStats(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET") return } - writeError(w, http.StatusNotImplemented, "stats endpoint not yet implemented", "") + + // Extract the stats sub-path + path := strings.TrimPrefix(r.URL.Path, "/api/v1/stats") + path = strings.TrimSuffix(path, "/") + + switch path { + case "", "/overview": + s.handleStatsOverview(w, r) + case "/cache": + s.handleStatsCache(w, r) + case "/journal": + s.handleStatsJournal(w, r) + case "/trim": + s.handleStatsTrim(w, r) + case "/lock": + s.handleStatsLock(w, r) + case "/sfb": + s.handleStatsSFB(w, r) + case "/cluster": + s.handleStatsCluster(w, r) + case "/all": + s.handleStatsAll(w, r) + default: + writeError(w, http.StatusNotFound, "stats endpoint not found", "valid endpoints: cache, journal, trim, lock, sfb, cluster, all") + } +} + +// handleStatsOverview handles GET /api/v1/stats requests. +// Returns a summary of key statistics from all components. +func (s *Server) handleStatsOverview(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + resp := StatsOverviewResponse{ + Cache: provider.CacheStats(), + Journal: provider.JournalStats(), + } + writeJSON(w, http.StatusOK, resp) +} + +// handleStatsCache handles GET /api/v1/stats/cache requests. +// Returns detailed cache hit/miss statistics. +func (s *Server) handleStatsCache(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + stats := provider.CacheStats() + if stats == nil { + writeError(w, http.StatusNotFound, "cache stats not available", "cache component not initialized") + return + } + + writeJSON(w, http.StatusOK, stats) +} + +// handleStatsJournal handles GET /api/v1/stats/journal requests. +// Returns journal transaction and space statistics. +func (s *Server) handleStatsJournal(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + stats := provider.JournalStats() + if stats == nil { + writeError(w, http.StatusNotFound, "journal stats not available", "journal component not initialized") + return + } + + writeJSON(w, http.StatusOK, stats) +} + +// handleStatsTrim handles GET /api/v1/stats/trim requests. +// Returns TRIM/discard operation statistics. +func (s *Server) handleStatsTrim(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + stats := provider.TrimStats() + if stats == nil { + writeError(w, http.StatusNotFound, "trim stats not available", "trim component not initialized") + return + } + + writeJSON(w, http.StatusOK, stats) +} + +// handleStatsLock handles GET /api/v1/stats/lock requests. +// Returns lock contention and hint cache statistics. +func (s *Server) handleStatsLock(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + stats := provider.LockStats() + if stats == nil { + writeError(w, http.StatusNotFound, "lock stats not available", "lock component not initialized") + return + } + + writeJSON(w, http.StatusOK, stats) +} + +// handleStatsSFB handles GET /api/v1/stats/sfb requests. +// Returns Sparse File Bitmap (block allocation) statistics. +func (s *Server) handleStatsSFB(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + stats := provider.SFBStats() + if stats == nil { + writeError(w, http.StatusNotFound, "sfb stats not available", "block allocator not initialized") + return + } + + writeJSON(w, http.StatusOK, stats) +} + +// handleStatsCluster handles GET /api/v1/stats/cluster requests. +// Returns cluster membership and node information. +func (s *Server) handleStatsCluster(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + stats := provider.ClusterInfo() + if stats == nil { + writeError(w, http.StatusNotFound, "cluster info not available", "running in standalone mode") + return + } + + writeJSON(w, http.StatusOK, stats) +} + +// handleStatsAll handles GET /api/v1/stats/all requests. +// Returns a combined snapshot of all available statistics. +func (s *Server) handleStatsAll(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "stats not available", "no stats provider configured") + return + } + + stats := provider.AllStats() + if stats == nil { + writeError(w, http.StatusServiceUnavailable, "failed to collect stats", "") + return + } + + writeJSON(w, http.StatusOK, stats) } // handleMetrics handles GET /metrics requests for Prometheus scraping. diff --git a/internal/api/routes_test.go b/internal/api/routes_test.go index 9b7dd713..6fc96887 100644 --- a/internal/api/routes_test.go +++ b/internal/api/routes_test.go @@ -88,18 +88,19 @@ func TestRoutes_Metrics(t *testing.T) { } } -func TestRoutes_Stats_NotImplemented(t *testing.T) { +func TestRoutes_Stats_NoProvider(t *testing.T) { server := startTestServer(t) defer server.Stop() + // Without a StatsProvider configured, stats endpoints return 503 resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/cache") if err != nil { t.Fatalf("request error: %v", err) } defer resp.Body.Close() - if resp.StatusCode != http.StatusNotImplemented { - t.Errorf("expected status 501, got %d", resp.StatusCode) + if resp.StatusCode != http.StatusServiceUnavailable { + t.Errorf("expected status 503, got %d", resp.StatusCode) } } diff --git a/internal/api/server.go b/internal/api/server.go index 6550d1dc..c31d1cc8 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -26,6 +26,9 @@ type Server struct { // Status provider for filesystem status (optional) statusProvider StatusProvider + // Stats provider for statistics collection (optional) + statsProvider StatsProvider + // Lifecycle state started bool startTime time.Time @@ -212,3 +215,41 @@ func (s *Server) GetStatusProvider() StatusProvider { defer s.mu.RUnlock() return s.statusProvider } + +// StatsProvider provides statistics from the filesystem components. +type StatsProvider interface { + // CacheStats returns cache statistics, or nil if not available. + CacheStats() *CacheStatsResponse + + // JournalStats returns journal statistics, or nil if not available. + JournalStats() *JournalStatsResponse + + // TrimStats returns TRIM/discard statistics, or nil if not available. + TrimStats() *TrimStatsResponse + + // LockStats returns lock statistics, or nil if not available. + LockStats() *LockStatsResponse + + // SFBStats returns Sparse File Bitmap statistics, or nil if not available. + SFBStats() *SFBStatsResponse + + // ClusterInfo returns cluster information, or nil if not available. + ClusterInfo() *ClusterInfoResponse + + // AllStats returns a combined snapshot of all statistics. + AllStats() *AllStatsResponse +} + +// SetStatsProvider sets the stats provider for statistics collection. +func (s *Server) SetStatsProvider(provider StatsProvider) { + s.mu.Lock() + defer s.mu.Unlock() + s.statsProvider = provider +} + +// GetStatsProvider returns the current stats provider. +func (s *Server) GetStatsProvider() StatsProvider { + s.mu.RLock() + defer s.mu.RUnlock() + return s.statsProvider +} diff --git a/internal/api/server_test.go b/internal/api/server_test.go index 1b131a79..a99e6df6 100644 --- a/internal/api/server_test.go +++ b/internal/api/server_test.go @@ -317,3 +317,564 @@ func TestServer_AddrBeforeStart(t *testing.T) { t.Errorf("expected empty addr before start, got %q", addr) } } + +// mockStatsProvider implements StatsProvider for testing. +type mockStatsProvider struct { + cache *CacheStatsResponse + journal *JournalStatsResponse + trim *TrimStatsResponse + lock *LockStatsResponse + sfb *SFBStatsResponse + cluster *ClusterInfoResponse + all *AllStatsResponse +} + +func (m *mockStatsProvider) CacheStats() *CacheStatsResponse { return m.cache } +func (m *mockStatsProvider) JournalStats() *JournalStatsResponse { return m.journal } +func (m *mockStatsProvider) TrimStats() *TrimStatsResponse { return m.trim } +func (m *mockStatsProvider) LockStats() *LockStatsResponse { return m.lock } +func (m *mockStatsProvider) SFBStats() *SFBStatsResponse { return m.sfb } +func (m *mockStatsProvider) ClusterInfo() *ClusterInfoResponse { return m.cluster } +func (m *mockStatsProvider) AllStats() *AllStatsResponse { return m.all } + +func TestServer_StatsEndpoints_NoProvider(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + endpoints := []string{ + "/api/v1/stats", + "/api/v1/stats/cache", + "/api/v1/stats/journal", + "/api/v1/stats/trim", + "/api/v1/stats/lock", + "/api/v1/stats/sfb", + "/api/v1/stats/cluster", + "/api/v1/stats/all", + } + + for _, endpoint := range endpoints { + t.Run(endpoint, func(t *testing.T) { + resp, err := http.Get("http://" + server.Addr() + endpoint) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + // Should return 503 when no provider is configured + if resp.StatusCode != http.StatusServiceUnavailable { + t.Errorf("expected status 503, got %d", resp.StatusCode) + } + }) + } +} + +func TestServer_StatsCache_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Set up mock provider with cache stats + mockProvider := &mockStatsProvider{ + cache: &CacheStatsResponse{ + InodeCache: CacheHitRateInfo{ + Size: 1000, + Hits: 800, + Misses: 200, + HitRate: 0.8, + }, + ExtentCache: CacheHitRateInfo{ + Size: 500, + Hits: 400, + Misses: 100, + HitRate: 0.8, + }, + NegativeCache: CacheHitRateInfo{ + Size: 100, + Hits: 50, + Misses: 50, + HitRate: 0.5, + }, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/cache") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats CacheStatsResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.InodeCache.Size != 1000 { + t.Errorf("expected inode cache size 1000, got %d", stats.InodeCache.Size) + } + if stats.InodeCache.HitRate != 0.8 { + t.Errorf("expected inode hit rate 0.8, got %f", stats.InodeCache.HitRate) + } +} + +func TestServer_StatsCache_NotAvailable(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Provider with nil cache stats + mockProvider := &mockStatsProvider{} + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/cache") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + // Should return 404 when cache stats are nil + if resp.StatusCode != http.StatusNotFound { + t.Errorf("expected status 404, got %d", resp.StatusCode) + } +} + +func TestServer_StatsJournal_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + journal: &JournalStatsResponse{ + State: "clean", + HeadOffset: 1024, + TailOffset: 512, + AvailableSpace: 4096, + ActiveTxnCount: 5, + CommitCount: 100, + BytesWritten: 1024 * 1024, + LastCheckpointSeq: 50, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/journal") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats JournalStatsResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.State != "clean" { + t.Errorf("expected state 'clean', got %q", stats.State) + } + if stats.CommitCount != 100 { + t.Errorf("expected commit count 100, got %d", stats.CommitCount) + } +} + +func TestServer_StatsTrim_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + trim: &TrimStatsResponse{ + TrimOperations: 50, + TrimBytes: 1024 * 1024 * 10, + TrimBlocks: 2560, + TrimEnabled: true, + BatchSize: 64, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/trim") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats TrimStatsResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.TrimOperations != 50 { + t.Errorf("expected 50 trim operations, got %d", stats.TrimOperations) + } + if !stats.TrimEnabled { + t.Error("expected trim enabled") + } +} + +func TestServer_StatsLock_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + lock: &LockStatsResponse{ + HintCacheHits: 900, + HintCacheMisses: 100, + HintCacheHitRate: 0.9, + ActiveLocks: 5, + PendingLocks: 2, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/lock") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats LockStatsResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.HintCacheHitRate != 0.9 { + t.Errorf("expected hit rate 0.9, got %f", stats.HintCacheHitRate) + } +} + +func TestServer_StatsSFB_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + sfb: &SFBStatsResponse{ + TotalBlocks: 10000, + AllocatedBlocks: 7500, + FreeBlocks: 2500, + AllocationPercent: 75.0, + AllocationsTotal: 5000, + DeallocationsTotal: 2500, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/sfb") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats SFBStatsResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.AllocationPercent != 75.0 { + t.Errorf("expected allocation 75%%, got %f%%", stats.AllocationPercent) + } +} + +func TestServer_StatsCluster_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + cluster: &ClusterInfoResponse{ + NodeID: "node-1", + Role: "primary", + State: "active", + ClusterSize: 3, + HealthyNodes: 3, + LeaderID: "node-1", + Peers: []ClusterPeerInfo{ + {NodeID: "node-2", Address: "192.168.1.2:7946", State: "active"}, + {NodeID: "node-3", Address: "192.168.1.3:7946", State: "active"}, + }, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/cluster") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats ClusterInfoResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.NodeID != "node-1" { + t.Errorf("expected node-1, got %q", stats.NodeID) + } + if len(stats.Peers) != 2 { + t.Errorf("expected 2 peers, got %d", len(stats.Peers)) + } +} + +func TestServer_StatsAll_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + all: &AllStatsResponse{ + CollectedAt: "2025-01-01T00:00:00Z", + Cache: &CacheStatsResponse{ + InodeCache: CacheHitRateInfo{Size: 100}, + }, + Journal: &JournalStatsResponse{ + State: "clean", + }, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/all") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats AllStatsResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.CollectedAt != "2025-01-01T00:00:00Z" { + t.Errorf("expected collected_at, got %q", stats.CollectedAt) + } + if stats.Cache == nil { + t.Error("expected cache stats") + } + if stats.Journal == nil { + t.Error("expected journal stats") + } +} + +func TestServer_StatsOverview_Success(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + cache: &CacheStatsResponse{ + InodeCache: CacheHitRateInfo{Size: 100}, + }, + journal: &JournalStatsResponse{ + State: "clean", + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected status 200, got %d", resp.StatusCode) + } + + var stats StatsOverviewResponse + if err := json.NewDecoder(resp.Body).Decode(&stats); err != nil { + t.Fatalf("decode error: %v", err) + } + + if stats.Cache == nil { + t.Error("expected cache stats in overview") + } + if stats.Journal == nil { + t.Error("expected journal stats in overview") + } +} + +func TestServer_StatsUnknownEndpoint(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{} + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/stats/unknown") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNotFound { + t.Errorf("expected status 404, got %d", resp.StatusCode) + } +} + +func TestServer_StatsMethodNotAllowed(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + // POST should not be allowed + resp, err := http.Post("http://"+server.Addr()+"/api/v1/stats/cache", "application/json", nil) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Errorf("expected status 405, got %d", resp.StatusCode) + } +} diff --git a/internal/api/types.go b/internal/api/types.go index afc09eb7..7bf2b714 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -132,6 +132,75 @@ type MetricsStatsResponse struct { Uptime int64 `json:"uptime_seconds"` } +// TrimStatsResponse is returned by GET /api/v1/stats/trim. +type TrimStatsResponse struct { + TrimOperations uint64 `json:"trim_operations"` + TrimBytes uint64 `json:"trim_bytes"` + TrimBlocks uint64 `json:"trim_blocks"` + PendingTrimBlocks uint64 `json:"pending_trim_blocks,omitempty"` + LastTrimAt string `json:"last_trim_at,omitempty"` + TrimErrors uint64 `json:"trim_errors,omitempty"` + TrimEnabled bool `json:"trim_enabled"` + BatchSize int `json:"batch_size,omitempty"` +} + +// LockStatsResponse is returned by GET /api/v1/stats/lock. +type LockStatsResponse struct { + HintCacheHits uint64 `json:"hint_cache_hits"` + HintCacheMisses uint64 `json:"hint_cache_misses"` + HintCacheHitRate float64 `json:"hint_cache_hit_rate"` + ActiveLocks int `json:"active_locks,omitempty"` + PendingLocks int `json:"pending_locks,omitempty"` +} + +// SFBStatsResponse is returned by GET /api/v1/stats/sfb. +type SFBStatsResponse struct { + TotalBlocks uint64 `json:"total_blocks"` + AllocatedBlocks uint64 `json:"allocated_blocks"` + FreeBlocks uint64 `json:"free_blocks"` + AllocationPercent float64 `json:"allocation_percent"` + FragmentationRatio float64 `json:"fragmentation_ratio,omitempty"` + LargestFreeExtent uint64 `json:"largest_free_extent,omitempty"` + AllocationsTotal uint64 `json:"allocations_total"` + DeallocationsTotal uint64 `json:"deallocations_total"` + AllocationFailures uint64 `json:"allocation_failures,omitempty"` +} + +// ClusterPeerInfo contains information about a cluster peer node. +type ClusterPeerInfo struct { + NodeID string `json:"node_id"` + Address string `json:"address"` + State string `json:"state"` + LastSeen string `json:"last_seen,omitempty"` + Latency float64 `json:"latency_ms,omitempty"` +} + +// ClusterInfoResponse is returned by GET /api/v1/stats/cluster. +type ClusterInfoResponse struct { + NodeID string `json:"node_id"` + NodeAddress string `json:"node_address,omitempty"` + Role string `json:"role"` + State string `json:"state"` + ClusterSize int `json:"cluster_size"` + HealthyNodes int `json:"healthy_nodes"` + LeaderID string `json:"leader_id,omitempty"` + LastHeartbeatAt string `json:"last_heartbeat_at,omitempty"` + JoinedAt string `json:"joined_at,omitempty"` + Peers []ClusterPeerInfo `json:"peers,omitempty"` +} + +// AllStatsResponse is returned by GET /api/v1/stats/all. +// Provides a combined snapshot of all statistics. +type AllStatsResponse struct { + CollectedAt string `json:"collected_at"` + Cache *CacheStatsResponse `json:"cache,omitempty"` + Journal *JournalStatsResponse `json:"journal,omitempty"` + Trim *TrimStatsResponse `json:"trim,omitempty"` + Lock *LockStatsResponse `json:"lock,omitempty"` + SFB *SFBStatsResponse `json:"sfb,omitempty"` + Cluster *ClusterInfoResponse `json:"cluster,omitempty"` +} + // StatsOverviewResponse is returned by GET /api/v1/stats. // Provides a summary of all component stats. type StatsOverviewResponse struct { From f5beb8c28066f47be25397ae2491d47bdc3564c7 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Tue, 10 Nov 2026 12:39:23 -0600 Subject: [PATCH 13/37] style(api): gofmt the API and stats code CI fails on unformatted files. Whitespace and import order only. Co-Authored-By: Claude Opus 5.5 --- cmd/mount/main.go | 2 +- internal/api/routes_test.go | 6 +++--- internal/api/server_test.go | 12 ++++++------ internal/api/types.go | 36 ++++++++++++++++++------------------ internal/api/types_test.go | 2 +- internal/api/version.go | 7 ++++--- 6 files changed, 33 insertions(+), 32 deletions(-) diff --git a/cmd/mount/main.go b/cmd/mount/main.go index 98857a7e..aea5a605 100644 --- a/cmd/mount/main.go +++ b/cmd/mount/main.go @@ -15,11 +15,11 @@ import ( "github.com/hanwen/go-fuse/v2/fs" "github.com/hanwen/go-fuse/v2/fuse" + "github.com/supporttools/GoClusterFS/internal/api" "github.com/supporttools/GoClusterFS/internal/bitmap" "github.com/supporttools/GoClusterFS/internal/cache" "github.com/supporttools/GoClusterFS/internal/cache/broadcast" "github.com/supporttools/GoClusterFS/internal/dir" - "github.com/supporttools/GoClusterFS/internal/api" "github.com/supporttools/GoClusterFS/internal/extent" "github.com/supporttools/GoClusterFS/internal/goclusterfs" "github.com/supporttools/GoClusterFS/internal/inode" diff --git a/internal/api/routes_test.go b/internal/api/routes_test.go index 6fc96887..66cc5364 100644 --- a/internal/api/routes_test.go +++ b/internal/api/routes_test.go @@ -212,9 +212,9 @@ type mockStatusProvider struct { capacity *CapacityInfo } -func (m *mockStatusProvider) MountPath() string { return m.mountPath } -func (m *mockStatusProvider) DevicePath() string { return m.devicePath } -func (m *mockStatusProvider) MountState() MountState { return m.mountState } +func (m *mockStatusProvider) MountPath() string { return m.mountPath } +func (m *mockStatusProvider) DevicePath() string { return m.devicePath } +func (m *mockStatusProvider) MountState() MountState { return m.mountState } func (m *mockStatusProvider) Capacity() *CapacityInfo { return m.capacity } func TestRoutes_Status_WithStatusProvider(t *testing.T) { diff --git a/internal/api/server_test.go b/internal/api/server_test.go index a99e6df6..7657b4bb 100644 --- a/internal/api/server_test.go +++ b/internal/api/server_test.go @@ -329,7 +329,7 @@ type mockStatsProvider struct { all *AllStatsResponse } -func (m *mockStatsProvider) CacheStats() *CacheStatsResponse { return m.cache } +func (m *mockStatsProvider) CacheStats() *CacheStatsResponse { return m.cache } func (m *mockStatsProvider) JournalStats() *JournalStatsResponse { return m.journal } func (m *mockStatsProvider) TrimStats() *TrimStatsResponse { return m.trim } func (m *mockStatsProvider) LockStats() *LockStatsResponse { return m.lock } @@ -629,11 +629,11 @@ func TestServer_StatsSFB_Success(t *testing.T) { mockProvider := &mockStatsProvider{ sfb: &SFBStatsResponse{ - TotalBlocks: 10000, - AllocatedBlocks: 7500, - FreeBlocks: 2500, - AllocationPercent: 75.0, - AllocationsTotal: 5000, + TotalBlocks: 10000, + AllocatedBlocks: 7500, + FreeBlocks: 2500, + AllocationPercent: 75.0, + AllocationsTotal: 5000, DeallocationsTotal: 2500, }, } diff --git a/internal/api/types.go b/internal/api/types.go index 7bf2b714..06e9cab2 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -9,8 +9,8 @@ import ( type HealthStatus string const ( - HealthStatusOK HealthStatus = "ok" - HealthStatusDegraded HealthStatus = "degraded" + HealthStatusOK HealthStatus = "ok" + HealthStatusDegraded HealthStatus = "degraded" HealthStatusUnhealthy HealthStatus = "unhealthy" ) @@ -70,26 +70,26 @@ const ( // StatusResponse is returned by GET /api/v1/status. // Provides comprehensive system status information. type StatusResponse struct { - Status string `json:"status"` - Version string `json:"version"` - GitCommit string `json:"git_commit,omitempty"` - BuildTime string `json:"build_time,omitempty"` - GoVersion string `json:"go_version,omitempty"` - UptimeSeconds int64 `json:"uptime_seconds"` - MountPath string `json:"mount_path,omitempty"` - DevicePath string `json:"device_path,omitempty"` - MountState MountState `json:"mount_state,omitempty"` - ReadOnly bool `json:"read_only,omitempty"` - Capacity *CapacityInfo `json:"capacity,omitempty"` - Cluster *ClusterInfo `json:"cluster,omitempty"` + Status string `json:"status"` + Version string `json:"version"` + GitCommit string `json:"git_commit,omitempty"` + BuildTime string `json:"build_time,omitempty"` + GoVersion string `json:"go_version,omitempty"` + UptimeSeconds int64 `json:"uptime_seconds"` + MountPath string `json:"mount_path,omitempty"` + DevicePath string `json:"device_path,omitempty"` + MountState MountState `json:"mount_state,omitempty"` + ReadOnly bool `json:"read_only,omitempty"` + Capacity *CapacityInfo `json:"capacity,omitempty"` + Cluster *ClusterInfo `json:"cluster,omitempty"` } // CacheHitRateInfo contains hit rate metrics for a cache type. type CacheHitRateInfo struct { - Size int `json:"size"` - Hits uint64 `json:"hits"` - Misses uint64 `json:"misses"` - HitRate float64 `json:"hit_rate"` + Size int `json:"size"` + Hits uint64 `json:"hits"` + Misses uint64 `json:"misses"` + HitRate float64 `json:"hit_rate"` } // CacheStatsResponse is returned by GET /api/v1/stats/cache. diff --git a/internal/api/types_test.go b/internal/api/types_test.go index 942eb82f..6a265d98 100644 --- a/internal/api/types_test.go +++ b/internal/api/types_test.go @@ -23,7 +23,7 @@ func TestHealthResponse_JSONMarshaling(t *testing.T) { resp: HealthResponse{ Status: HealthStatusDegraded, Checks: map[string]ComponentHealth{ - "cache": {Status: HealthStatusOK}, + "cache": {Status: HealthStatusOK}, "journal": {Status: HealthStatusDegraded, Message: "low disk space"}, }, }, diff --git a/internal/api/version.go b/internal/api/version.go index d9e6a50f..afa3a0cf 100644 --- a/internal/api/version.go +++ b/internal/api/version.go @@ -3,9 +3,10 @@ package api import "runtime" // Build-time variables set via ldflags: -// -ldflags "-X github.com/supporttools/GoClusterFS/internal/api.Version=1.0.0 -// -X github.com/supporttools/GoClusterFS/internal/api.GitCommit=abc123 -// -X github.com/supporttools/GoClusterFS/internal/api.BuildTime=2024-01-01T00:00:00Z" +// +// -ldflags "-X github.com/supporttools/GoClusterFS/internal/api.Version=1.0.0 +// -X github.com/supporttools/GoClusterFS/internal/api.GitCommit=abc123 +// -X github.com/supporttools/GoClusterFS/internal/api.BuildTime=2024-01-01T00:00:00Z" var ( // Version is the semantic version of the build. Version = "dev" From a8146bf7e5e75c7adb067de2cb5c06e48a52bf5f Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Tue, 10 Nov 2026 12:40:18 -0600 Subject: [PATCH 14/37] fix(api): bind to loopback by default and refuse remote access without a token The API listened on :8080 on every interface with no auth, so any host that could reach the node could read cluster state. -api-addr now defaults to 127.0.0.1:8080. Mount exits before touching the device when -api-addr can be reached from other hosts and -api-token is empty. Co-Authored-By: Claude Opus 5.5 --- cmd/mount/main.go | 42 ++++++++------- internal/api/config.go | 27 ++++++++-- internal/api/errors.go | 3 ++ internal/api/exposure_test.go | 40 +++++++++++++++ internal/api/server_test.go | 4 +- tests/integration/api_test.go | 97 +++++++++++++++++++++++++++++++++++ tests/test-manifest.yaml | 18 +++++++ 7 files changed, 207 insertions(+), 24 deletions(-) create mode 100644 internal/api/exposure_test.go create mode 100644 tests/integration/api_test.go diff --git a/cmd/mount/main.go b/cmd/mount/main.go index aea5a605..08bf0891 100644 --- a/cmd/mount/main.go +++ b/cmd/mount/main.go @@ -76,6 +76,19 @@ func (p *fsStatusProvider) Capacity() *api.CapacityInfo { } } +func apiConfig(addr, token, corsList string) api.Config { + var origins []string + for _, origin := range strings.Split(corsList, ",") { + if origin = strings.TrimSpace(origin); origin != "" { + origins = append(origins, origin) + } + } + return api.DefaultConfig(). + WithListenAddr(addr). + WithAuthToken(token). + WithCORSOrigins(origins...) +} + func main() { var ( devicePath = flag.String("device", "", "Path to block device or image file") @@ -112,8 +125,8 @@ func main() { // API server configuration apiEnabled = flag.Bool("api", true, "Enable HTTP API server for management") - apiAddr = flag.String("api-addr", ":8080", "API server listen address") - apiToken = flag.String("api-token", "", "Bearer token for API authentication (empty=disabled)") + apiAddr = flag.String("api-addr", "127.0.0.1:8080", "API server listen address; any non-loopback address needs -api-token") + apiToken = flag.String("api-token", "", "Bearer token for API authentication (empty=disabled, loopback only)") apiCORS = flag.String("api-cors", "", "Comma-separated CORS allowed origins (empty=disabled)") ) flag.Parse() @@ -124,6 +137,13 @@ func main() { os.Exit(1) } + apiCfg := apiConfig(*apiAddr, *apiToken, *apiCORS) + if *apiEnabled { + if err := apiCfg.CheckExposure(); err != nil { + log.Fatalf("Refusing to start the API: %v. Set -api-token, set -api-addr to a loopback address such as 127.0.0.1:8080, or pass -api=false", err) + } + } + // Check mount point exists if _, err := os.Stat(*mountPoint); os.IsNotExist(err) { log.Fatalf("Mount point does not exist: %s", *mountPoint) @@ -407,22 +427,6 @@ func main() { // Start API server for management and monitoring var apiServer *api.Server if *apiEnabled { - // Parse CORS origins from comma-separated string - var corsOrigins []string - if *apiCORS != "" { - for _, origin := range strings.Split(*apiCORS, ",") { - origin = strings.TrimSpace(origin) - if origin != "" { - corsOrigins = append(corsOrigins, origin) - } - } - } - - apiCfg := api.DefaultConfig(). - WithListenAddr(*apiAddr). - WithAuthToken(*apiToken). - WithCORSOrigins(corsOrigins...) - var err error apiServer, err = api.NewServer(apiCfg) if err != nil { @@ -439,7 +443,7 @@ func main() { log.Printf("Warning: Failed to start API server: %v", err) } else { log.Printf("API server listening on %s (auth=%v, cors=%v)", - apiServer.Addr(), *apiToken != "", len(corsOrigins) > 0) + apiServer.Addr(), apiCfg.AuthToken != "", len(apiCfg.CORSOrigins) > 0) } } } else { diff --git a/internal/api/config.go b/internal/api/config.go index c1859b96..ef4e4ca5 100644 --- a/internal/api/config.go +++ b/internal/api/config.go @@ -10,8 +10,8 @@ import ( // Config holds the configuration for the API server. type Config struct { - // ListenAddr is the address to listen on (e.g., ":8080" or "127.0.0.1:8080"). - // Default: ":8080" + // ListenAddr is the address to listen on (e.g., "127.0.0.1:8080" or ":8080"). + // Default: "127.0.0.1:8080" ListenAddr string // AuthToken is the Bearer token for API authentication. @@ -45,7 +45,7 @@ type Config struct { // DefaultConfig returns a Config with sensible defaults. func DefaultConfig() Config { return Config{ - ListenAddr: ":8080", + ListenAddr: "127.0.0.1:8080", AuthToken: "", CORSOrigins: nil, ReadTimeout: 30 * time.Second, @@ -120,6 +120,27 @@ func (c *Config) Validate() error { return nil } +// LoopbackOnly reports whether ListenAddr accepts connections only from this host. +func (c *Config) LoopbackOnly() bool { + host, _, err := net.SplitHostPort(c.ListenAddr) + if err != nil { + return false + } + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +// CheckExposure refuses a config that serves other hosts without an auth token. +func (c *Config) CheckExposure() error { + if c.AuthToken == "" && !c.LoopbackOnly() { + return fmt.Errorf("%w: %s", ErrUnauthenticatedRemote, c.ListenAddr) + } + return nil +} + // WithListenAddr returns a copy of the config with a new listen address. func (c Config) WithListenAddr(addr string) Config { c.ListenAddr = addr diff --git a/internal/api/errors.go b/internal/api/errors.go index ea2afdfb..ee229a5b 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -19,6 +19,9 @@ var ( // ErrInvalidCORSOrigin is returned when a CORS origin is malformed. ErrInvalidCORSOrigin = errors.New("api: invalid CORS origin") + // ErrUnauthenticatedRemote is returned when other hosts could reach the API without a token. + ErrUnauthenticatedRemote = errors.New("api: no auth token set for an address other hosts can reach") + // ErrShutdownTimeout is returned when graceful shutdown times out. ErrShutdownTimeout = errors.New("api: shutdown timed out") ) diff --git a/internal/api/exposure_test.go b/internal/api/exposure_test.go new file mode 100644 index 00000000..b59c4ef6 --- /dev/null +++ b/internal/api/exposure_test.go @@ -0,0 +1,40 @@ +package api + +import ( + "errors" + "testing" +) + +func TestCheckExposure(t *testing.T) { + tests := []struct { + addr string + token string + refused bool + }{ + {"127.0.0.1:8080", "", false}, + {"127.1.2.3:8080", "", false}, + {"localhost:8080", "", false}, + {"[::1]:8080", "", false}, + {":8080", "", true}, + {"0.0.0.0:8080", "", true}, + {"[::]:8080", "", true}, + {"10.0.0.5:8080", "", true}, + {"node1.example.com:8080", "", true}, + {":8080", "secret", false}, + {"10.0.0.5:8080", "secret", false}, + } + for _, tt := range tests { + cfg := DefaultConfig().WithListenAddr(tt.addr).WithAuthToken(tt.token) + err := cfg.CheckExposure() + if tt.refused != errors.Is(err, ErrUnauthenticatedRemote) { + t.Errorf("CheckExposure(%q, token=%q) = %v, want refused=%v", tt.addr, tt.token, err, tt.refused) + } + } +} + +func TestDefaultConfigPassesExposureCheck(t *testing.T) { + cfg := DefaultConfig() + if err := cfg.CheckExposure(); err != nil { + t.Fatalf("default config refused: %v", err) + } +} diff --git a/internal/api/server_test.go b/internal/api/server_test.go index 7657b4bb..32e3e5ac 100644 --- a/internal/api/server_test.go +++ b/internal/api/server_test.go @@ -12,8 +12,8 @@ import ( func TestDefaultConfig(t *testing.T) { cfg := DefaultConfig() - if cfg.ListenAddr != ":8080" { - t.Errorf("expected ListenAddr :8080, got %s", cfg.ListenAddr) + if cfg.ListenAddr != "127.0.0.1:8080" { + t.Errorf("expected ListenAddr 127.0.0.1:8080, got %s", cfg.ListenAddr) } if cfg.AuthToken != "" { t.Errorf("expected empty AuthToken, got %s", cfg.AuthToken) diff --git a/tests/integration/api_test.go b/tests/integration/api_test.go new file mode 100644 index 00000000..6589d64b --- /dev/null +++ b/tests/integration/api_test.go @@ -0,0 +1,97 @@ +package integration + +import ( + "bytes" + "context" + "io" + "net" + "net/http" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +func freeLoopbackAddr(t *testing.T) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("Failed to find a free port: %v", err) + } + addr := ln.Addr().String() + ln.Close() + return addr +} + +func TestAPIServesHealthOnLoopback(t *testing.T) { + mfs := NewMountedFS(t, 20) + if err := mfs.Format(); err != nil { + t.Fatalf("Format failed: %v", err) + } + addr := freeLoopbackAddr(t) + mfs.ExtraArgs = []string{"-api-addr", addr} + if err := mfs.Mount(false); err != nil { + t.Fatalf("Mount failed: %v", err) + } + + client := &http.Client{Timeout: 2 * time.Second} + deadline := time.Now().Add(10 * time.Second) + for { + resp, err := client.Get("http://" + addr + "/health") + if err == nil { + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("GET /health returned %d, want 200", resp.StatusCode) + } + return + } + if time.Now().After(deadline) { + t.Fatalf("API never answered on %s: %v", addr, err) + } + time.Sleep(100 * time.Millisecond) + } +} + +func TestMountRefusesUnauthenticatedRemoteAPI(t *testing.T) { + binary, err := findBinary() + if err != nil { + t.Fatalf("Failed to find binary: %v", err) + } + mountPoint := t.TempDir() + image := mountPoint + ".img" + if err := allocateImage(image, 20); err != nil { + t.Fatalf("Failed to allocate image: %v", err) + } + t.Cleanup(func() { os.Remove(image) }) + + for _, addr := range []string{":8080", "0.0.0.0:8080"} { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + out, err := exec.CommandContext(ctx, binary, "-device", image, "-mount", mountPoint, "-format", "-api-addr", addr).CombinedOutput() + timedOut := ctx.Err() != nil + cancel() + if timedOut { + exec.Command("fusermount", "-u", mountPoint).Run() + t.Fatalf("-api-addr %s without -api-token: mount kept running", addr) + } + if err == nil { + t.Fatalf("-api-addr %s without -api-token: mount exited 0", addr) + } + if !strings.Contains(string(out), "-api-token") { + t.Errorf("-api-addr %s: error does not mention -api-token:\n%s", addr, out) + } + } + + f, err := os.Open(image) + if err != nil { + t.Fatalf("Failed to open image: %v", err) + } + defer f.Close() + head := make([]byte, 4096) + if _, err := io.ReadFull(f, head); err != nil { + t.Fatalf("Failed to read image: %v", err) + } + if !bytes.Equal(head, make([]byte, len(head))) { + t.Error("refused mount still wrote a superblock") + } +} diff --git a/tests/test-manifest.yaml b/tests/test-manifest.yaml index 4470242f..5b6d0ed9 100644 --- a/tests/test-manifest.yaml +++ b/tests/test-manifest.yaml @@ -2225,3 +2225,21 @@ scenarios: priority: go_only environments: go: internal/lock/safety_test.go::TestLockRegionStaysBoundedAcrossCycles + + # =========================================================================== + # HTTP API (one process on one host; Docker and VM would test nothing more) + # =========================================================================== + + - id: api-health-loopback + name: API answers /health on loopback + description: A mount started with -api-addr on 127.0.0.1 serves GET /health with 200 + priority: go_only + environments: + go: api_test.go::TestAPIServesHealthOnLoopback + + - id: api-refuses-remote-without-token + name: Mount refuses an unauthenticated remote API + description: With -api-addr on all interfaces and no -api-token, mount exits non-zero naming -api-token and never writes the device + priority: go_only + environments: + go: api_test.go::TestMountRefusesUnauthenticatedRemoteAPI From 33b0bdc69f483cea647556f74377f1b0cfb32aa7 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Tue, 10 Nov 2026 12:40:25 -0600 Subject: [PATCH 15/37] fix(mount): warn at startup when broadcast runs without a secret Broadcast is on by default and its secret is empty by default, so most clusters accept unauthenticated invalidation and peer messages without knowing it. Mount now logs a WARNING line before it opens the device. Co-Authored-By: Claude Opus 5.5 --- cmd/mount/main.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cmd/mount/main.go b/cmd/mount/main.go index 08bf0891..1d914848 100644 --- a/cmd/mount/main.go +++ b/cmd/mount/main.go @@ -143,6 +143,9 @@ func main() { log.Fatalf("Refusing to start the API: %v. Set -api-token, set -api-addr to a loopback address such as 127.0.0.1:8080, or pass -api=false", err) } } + if *broadcastEnabled && *broadcastSecret == "" { + log.Printf("WARNING: -broadcast is on without -broadcast-secret. Broadcast messages are not authenticated: any host that can send UDP to port %d can make this node drop its caches and add itself as a peer. Set the same -broadcast-secret on every node, or pass -broadcast=false.", *multicastPort) + } // Check mount point exists if _, err := os.Stat(*mountPoint); os.IsNotExist(err) { From 4c94506f9c1f80ef5cbef18c0a4e98420449825b Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Tue, 10 Nov 2026 12:40:55 -0600 Subject: [PATCH 16/37] fix(api): read the build version from internal/version internal/api kept its own Version, GitCommit and BuildTime, which scripts/dist.sh never set, so /api/v1/status always said "dev". GetBuildInfo now reads internal/version, and goclusterfs-mount -version prints the same string as goclusterfs-fsck -version. Co-Authored-By: Claude Opus 5.5 --- cmd/mount/main.go | 7 +++++++ internal/api/version.go | 26 +++++++------------------- internal/api/version_test.go | 17 +++++++++++++++++ 3 files changed, 31 insertions(+), 19 deletions(-) create mode 100644 internal/api/version_test.go diff --git a/cmd/mount/main.go b/cmd/mount/main.go index 1d914848..2279b89d 100644 --- a/cmd/mount/main.go +++ b/cmd/mount/main.go @@ -31,6 +31,7 @@ import ( "github.com/supporttools/GoClusterFS/internal/storage" "github.com/supporttools/GoClusterFS/internal/superblock" "github.com/supporttools/GoClusterFS/internal/trim" + "github.com/supporttools/GoClusterFS/internal/version" ) // fsStatusProvider implements api.StatusProvider by wrapping the filesystem. @@ -95,6 +96,7 @@ func main() { mountPoint = flag.String("mount", "", "Mount point directory") format = flag.Bool("format", false, "Format the device (WARNING: destroys data)") debug = flag.Bool("debug", false, "Enable FUSE debug output") + showVer = flag.Bool("version", false, "Print version and exit") // Cache configuration cacheStrict = flag.Bool("cache-strict", false, "Enable strict cache mode (always validate)") @@ -131,6 +133,11 @@ func main() { ) flag.Parse() + if *showVer { + fmt.Println("goclusterfs-mount", version.String()) + os.Exit(0) + } + if *devicePath == "" || *mountPoint == "" { fmt.Fprintf(os.Stderr, "Usage: %s -device -mount [-format] [-debug]\n", os.Args[0]) flag.PrintDefaults() diff --git a/internal/api/version.go b/internal/api/version.go index afa3a0cf..df0c0ac8 100644 --- a/internal/api/version.go +++ b/internal/api/version.go @@ -1,21 +1,9 @@ package api -import "runtime" +import ( + "runtime" -// Build-time variables set via ldflags: -// -// -ldflags "-X github.com/supporttools/GoClusterFS/internal/api.Version=1.0.0 -// -X github.com/supporttools/GoClusterFS/internal/api.GitCommit=abc123 -// -X github.com/supporttools/GoClusterFS/internal/api.BuildTime=2024-01-01T00:00:00Z" -var ( - // Version is the semantic version of the build. - Version = "dev" - - // GitCommit is the git commit hash of the build. - GitCommit = "" - - // BuildTime is the time the build was created. - BuildTime = "" + "github.com/supporttools/GoClusterFS/internal/version" ) // BuildInfo contains build version information. @@ -26,12 +14,12 @@ type BuildInfo struct { GoVersion string `json:"go_version"` } -// GetBuildInfo returns the current build information. +// GetBuildInfo returns the build metadata from internal/version. func GetBuildInfo() BuildInfo { return BuildInfo{ - Version: Version, - GitCommit: GitCommit, - BuildTime: BuildTime, + Version: version.Version, + GitCommit: version.Commit, + BuildTime: version.Date, GoVersion: runtime.Version(), } } diff --git a/internal/api/version_test.go b/internal/api/version_test.go new file mode 100644 index 00000000..142b4168 --- /dev/null +++ b/internal/api/version_test.go @@ -0,0 +1,17 @@ +package api + +import ( + "testing" + + "github.com/supporttools/GoClusterFS/internal/version" +) + +func TestBuildInfoUsesVersionPackage(t *testing.T) { + saved := version.Version + t.Cleanup(func() { version.Version = saved }) + version.Version = "1.2.3" + + if got := GetBuildInfo().Version; got != "1.2.3" { + t.Fatalf("GetBuildInfo().Version = %q, want internal/version's 1.2.3", got) + } +} From f1bbcf179017fadc9c131668c4dfbc685021eac3 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Tue, 10 Nov 2026 12:41:55 -0600 Subject: [PATCH 17/37] docs: document the HTTP API flags, loopback default and new warnings Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ CLAUDE.md | 3 +++ README.md | 14 ++++++++++++++ docs/API-CONFIG.md | 18 +++++++++++++++++- docs/DEPLOYMENT.md | 16 ++++++++++++++-- docs/OPERATIONS.md | 11 +++++++++-- docs/TROUBLESHOOTING.md | 4 ++-- 7 files changed, 62 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f53777a1..55f09c14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - CI gates: unit tests with the race detector and coverage, golangci-lint (`make lint`), govulncheck (`make vuln`), and a `go mod tidy` check. - Release workflow: pushing a `v*` tag publishes a GitHub Release with `linux/amd64` and `linux/arm64` archives, checksums, and the matching `CHANGELOG.md` section. `scripts/dist.sh` builds the same archives locally. - `goclusterfs-fsck -version` prints the release version, commit, and commit date. +- HTTP API in `goclusterfs-mount` (`-api`, on by default): `/health`, `/metrics`, `/api/v1/status` and `/api/v1/stats/...`. It listens on `127.0.0.1:8080` (`-api-addr`). Mount refuses a non-loopback `-api-addr` without `-api-token`. +- `goclusterfs-mount -version`, which prints the same version string as `goclusterfs-fsck -version`. `/api/v1/status` reports it too. +- Mount logs a `WARNING` line at startup when `-broadcast` is on without `-broadcast-secret`. - Design, deployment, operations, and troubleshooting docs in `docs/`. - Apache License 2.0. diff --git a/CLAUDE.md b/CLAUDE.md index 3b220083..5609a8e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,6 +53,9 @@ fusermount3 -u mnt # or Ctrl+C the mo | `internal/trim` | Batched `BLKDISCARD` for freed blocks | | `internal/fsck` | The fsck phases | | `internal/metrics` | Atomic counters, not used by `cmd/mount` yet | +| `internal/api` | HTTP API served by `cmd/mount`: `/health`, `/metrics`, `/api/v1/status`, `/api/v1/stats/...`; loopback only unless `-api-token` is set | +| `internal/stats` | Stats types and collector behind `/api/v1/stats` | +| `internal/version` | Build version, set with `-ldflags -X` by `scripts/dist.sh` | ## On-Disk Layout diff --git a/README.md b/README.md index 9eb0782a..c3f66560 100644 --- a/README.md +++ b/README.md @@ -86,6 +86,7 @@ These are the `goclusterfs-mount` flags. Run `./goclusterfs-mount -h` for the fu | `-mount` | (required) | Mount point directory (must exist) | | `-format` | `false` | Format the device, then mount it (destroys data) | | `-debug` | `false` | Log every FUSE request | +| `-version` | `false` | Print the version and exit | ### Cache Options @@ -111,6 +112,8 @@ These are the `goclusterfs-mount` flags. Run `./goclusterfs-mount -h` for the fu | `-broadcast-secret` | (empty) | HMAC secret for message authentication | | `-broadcast-iface` | (auto) | Network interface for multicast | +With `-broadcast` on and no `-broadcast-secret`, mount logs a `WARNING` line at startup: any host that can send to the port can make nodes drop their caches. Set the same secret on every node. + ### TRIM Options | Flag | Default | Description | @@ -126,6 +129,17 @@ These are the `goclusterfs-mount` flags. Run `./goclusterfs-mount -h` for the fu | `-sfb` | `true` | Ignored. SFB containers are disabled and every file uses full blocks | | `-snapshots` | `true` | Enable O(1) file snapshots | +### HTTP API Options + +| Flag | Default | Description | +|------|---------|-------------| +| `-api` | `true` | Serve the HTTP API (`/health`, `/metrics`, `/api/v1/...`) | +| `-api-addr` | `127.0.0.1:8080` | API listen address | +| `-api-token` | (empty) | Bearer token required on `/api/v1/...` | +| `-api-cors` | (empty) | Comma-separated CORS allowed origins | + +The API only listens on this host by default. Mount refuses to start when `-api-addr` can be reached from other hosts and `-api-token` is empty. See [HTTP API Flags](docs/API-CONFIG.md#http-api-flags). + ## Multi-Node Setup For clustered deployments: diff --git a/docs/API-CONFIG.md b/docs/API-CONFIG.md index d1558c95..a7c29079 100644 --- a/docs/API-CONFIG.md +++ b/docs/API-CONFIG.md @@ -35,6 +35,7 @@ These flags are passed when starting `goclusterfs`: |------|------|---------|-------------| | `-format` | bool | `false` | Format the device (destroys all data) | | `-debug` | bool | `false` | Enable verbose debug logging | +| `-version` | bool | `false` | Print the version, commit and commit date, then exit | ### Cache Flags @@ -80,6 +81,21 @@ The kernel caches file attributes and directory entries for `-attr-timeout`. For | `-sfb` | bool | `true` | Ignored. SFB containers are disabled | | `-snapshots` | bool | `true` | Enable O(1) file snapshots | +### HTTP API Flags + +| Flag | Type | Default | Description | +|------|------|---------|-------------| +| `-api` | bool | `true` | Serve the HTTP API | +| `-api-addr` | string | `127.0.0.1:8080` | Listen address | +| `-api-token` | string | (empty) | Bearer token for `/api/v1/...` requests | +| `-api-cors` | string | (empty) | Comma-separated CORS allowed origins, or `*` | + +The API serves `GET /health`, `GET /metrics`, `GET /api/v1/status` and `GET /api/v1/stats/...`. Mount does not feed statistics to the API yet, so `/api/v1/stats/...` answers 503, `/health` only checks the API itself, and `/metrics` only reports `goclusterfs_up`. With `-api-token` set, `/api/v1/...` requests need `Authorization: Bearer `. `/health` and `/metrics` never need the token. + +By default the API only accepts connections from this host. To serve other hosts, set `-api-addr` (for example `:8080` or `10.0.0.5:8080`) and `-api-token`. Mount exits before it opens the device when the address is not loopback (`127.0.0.0/8`, `::1` or `localhost`) and the token is empty. The token is a command-line flag, so local users can read it with `ps`. + +Each mount on a host needs its own `-api-addr`. When the port is taken, mount logs a warning and runs without the API. + --- ## Cache Configuration @@ -412,7 +428,7 @@ Interval between heartbeat messages to detect node failures. |----------|-------| | Default | (empty) | -HMAC secret for message authentication. All nodes must use the same secret. +HMAC secret for message authentication. All nodes must use the same secret. With broadcast on and no secret, mount logs a `WARNING` line at startup. **Generating a secret**: ```bash diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index ac77360a..4e3db66e 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -63,7 +63,7 @@ newgrp fuse |-------------|---------| | Connectivity | All nodes on same L2 network segment | | Multicast | UDP multicast between all nodes. Unicast is only a fallback to peers learned over multicast. | -| Ports | UDP 31337 (configurable) | +| Ports | UDP 31337 (configurable). TCP 8080 on loopback for the HTTP API; open it only if you expose the API | | Latency | < 10ms between nodes recommended | --- @@ -87,7 +87,7 @@ sudo cp goclusterfs-mount goclusterfs-fsck /usr/local/bin/ ### Verify Build ```bash -./goclusterfs-mount -h +./goclusterfs-mount -version ./goclusterfs-fsck -version ``` @@ -417,6 +417,18 @@ openssl rand -hex 32 See the [Security Model](OPERATIONS.md#security-model) for what this does and does not protect. +Mount logs a `WARNING` line at startup when broadcast is on without a secret. + +### HTTP API Access + +The API listens on `127.0.0.1:8080` by default. To scrape `/metrics` or call the API from another host, set a token and a reachable address: + +```bash +./goclusterfs-mount ... -api-addr :8080 -api-token "$(openssl rand -hex 32)" +``` + +Mount refuses a non-loopback `-api-addr` without `-api-token`. See [HTTP API Flags](API-CONFIG.md#http-api-flags). + ### Firewall Rules ```bash diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 6b8e9ba2..42cbd03a 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -522,13 +522,20 @@ GoClusterFS assumes every node, and everything that can reach the shared device **Broadcast cache invalidation.** Nodes send UDP messages (multicast group `239.192.74.75`, port `31337` by default) that tell peers to drop cached inodes and extents. Heartbeat and announce messages add unicast peers, which a node uses when multicast sends fail. Messages carry inode numbers but no file data. Losing them only delays cache updates until `-cache-ttl`. -- With an empty `-broadcast-secret` (the default), messages are not authenticated. Any host that can send to the port can make nodes drop their caches, and can add any address as a unicast peer. +- With an empty `-broadcast-secret` (the default), messages are not authenticated. Any host that can send to the port can make nodes drop their caches, and can add any address as a unicast peer. Mount logs a `WARNING` line at startup in this case. - With `-broadcast-secret`, every message carries an HMAC-SHA256 tag. Nodes drop messages with a missing or wrong tag, so all nodes need the same secret. - The only replay protection is a sequence number check that forgets messages after 5 minutes, so a recorded message can be sent again later, even with a secret. - Messages are never encrypted. Any host that joins the multicast group can see which inodes change. - The secret is a command-line flag, so local users on a node can read it with `ps`. -**Network listeners.** GoClusterFS has no HTTP API. Its only listener is UDP port 31337 on all interfaces, plus the multicast group. Limit that port to the cluster nodes with a firewall. +**HTTP API.** Each mount serves an HTTP API on `127.0.0.1:8080` (`-api-addr`), so only local users can reach it. It only answers `GET` requests and changes nothing. + +- To expose it, set `-api-addr` and `-api-token`. Mount refuses a non-loopback address without a token. +- `/health` and `/metrics` never need the token, so anyone who can reach the port can read them. +- The API uses plain HTTP. Put a TLS proxy in front of it if the token crosses an untrusted network. +- The token is a command-line flag, so local users can read it with `ps`. + +**Network listeners.** Each node listens on UDP port 31337 on all interfaces, plus the multicast group, and on TCP `-api-addr`. Limit the UDP port, and the API port if you expose it, to the cluster nodes and your monitoring hosts with a firewall. --- diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 2ab44126..4025f2d4 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -535,8 +535,8 @@ If this guide doesn't resolve your issue: uname -a cat /etc/os-release - # GoClusterFS version (goclusterfs-mount has no -version flag yet) - ./goclusterfs-fsck -version + # GoClusterFS version + ./goclusterfs-mount -version # Recent mount log tail -1000 /var/log/goclusterfs.log > mount.log From 79c2ee5d23f52e8f0e1637592f91b25496df72e4 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Tue, 10 Nov 2026 12:51:51 -0600 Subject: [PATCH 18/37] test(stats): cover the filesystem provider golangci-lint flagged mockFilesystemProvider as unused. Use it in a test of SetFilesystemProvider instead of deleting it. Co-Authored-By: Claude Opus 5.5 --- internal/stats/stats_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/internal/stats/stats_test.go b/internal/stats/stats_test.go index c7b60004..c57a250f 100644 --- a/internal/stats/stats_test.go +++ b/internal/stats/stats_test.go @@ -600,3 +600,16 @@ func TestClusterInfo_WithPeers(t *testing.T) { t.Errorf("expected second peer Latency 2.1, got %f", snapshot.Cluster.Peers[1].Latency) } } + +func TestCollector_FilesystemProvider(t *testing.T) { + collector := NewCollector(DefaultConfig()) + collector.SetFilesystemProvider(&mockFilesystemProvider{stats: &FilesystemStats{TotalBytes: 1 << 30, UsedBytes: 1 << 20}}) + + snapshot := collector.Collect() + if snapshot.Filesystem == nil || snapshot.Filesystem.TotalBytes != 1<<30 || snapshot.Filesystem.UsedBytes != 1<<20 { + t.Fatalf("Collect().Filesystem = %+v, want the provider's stats", snapshot.Filesystem) + } + if got := collector.FilesystemStats(); got == nil || got.TotalBytes != 1<<30 { + t.Fatalf("FilesystemStats() = %+v, want the provider's stats", got) + } +} From e33a2845bef58e8f5ee5c6cfec4001699ebad3fd Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:43:04 -0600 Subject: [PATCH 19/37] feat(api): add per-client rate limiting Token bucket per client IP, off by default (Config.RateLimitEnabled). Requests over the limit get 429 with Retry-After: 1. Recovered from uncommitted work in the user's checkout. Co-Authored-By: Claude Opus 5.5 --- internal/api/config.go | 47 ++++++++-- internal/api/errors.go | 3 + internal/api/middleware.go | 131 ++++++++++++++++++++++++++ internal/api/middleware_test.go | 161 ++++++++++++++++++++++++++++++++ internal/api/server.go | 11 ++- 5 files changed, 345 insertions(+), 8 deletions(-) diff --git a/internal/api/config.go b/internal/api/config.go index ef4e4ca5..af9324a3 100644 --- a/internal/api/config.go +++ b/internal/api/config.go @@ -40,18 +40,33 @@ type Config struct { // ShutdownTimeout is the maximum duration to wait for graceful shutdown. // Default: 10s ShutdownTimeout time.Duration + + // RateLimitEnabled enables rate limiting middleware. + // Default: false + RateLimitEnabled bool + + // RateLimitRequestsPerSecond is the sustained rate limit per client. + // Default: 100 + RateLimitRequestsPerSecond float64 + + // RateLimitBurst is the maximum burst size (token bucket capacity). + // Default: 200 + RateLimitBurst int } // DefaultConfig returns a Config with sensible defaults. func DefaultConfig() Config { return Config{ - ListenAddr: "127.0.0.1:8080", - AuthToken: "", - CORSOrigins: nil, - ReadTimeout: 30 * time.Second, - WriteTimeout: 30 * time.Second, - IdleTimeout: 60 * time.Second, - ShutdownTimeout: 10 * time.Second, + ListenAddr: "127.0.0.1:8080", + AuthToken: "", + CORSOrigins: nil, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 60 * time.Second, + ShutdownTimeout: 10 * time.Second, + RateLimitEnabled: false, + RateLimitRequestsPerSecond: 100, + RateLimitBurst: 200, } } @@ -117,6 +132,16 @@ func (c *Config) Validate() error { } } + // Validate rate limit configuration + if c.RateLimitEnabled { + if c.RateLimitRequestsPerSecond <= 0 { + return fmt.Errorf("%w: requests per second must be > 0", ErrInvalidRateLimit) + } + if c.RateLimitBurst <= 0 { + return fmt.Errorf("%w: burst must be > 0", ErrInvalidRateLimit) + } + } + return nil } @@ -158,3 +183,11 @@ func (c Config) WithCORSOrigins(origins ...string) Config { c.CORSOrigins = origins return c } + +// WithRateLimit returns a copy of the config with rate limiting enabled. +func (c Config) WithRateLimit(requestsPerSecond float64, burst int) Config { + c.RateLimitEnabled = true + c.RateLimitRequestsPerSecond = requestsPerSecond + c.RateLimitBurst = burst + return c +} diff --git a/internal/api/errors.go b/internal/api/errors.go index ee229a5b..9c695986 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -24,4 +24,7 @@ var ( // ErrShutdownTimeout is returned when graceful shutdown times out. ErrShutdownTimeout = errors.New("api: shutdown timed out") + + // ErrInvalidRateLimit is returned when rate limit configuration is invalid. + ErrInvalidRateLimit = errors.New("api: invalid rate limit configuration") ) diff --git a/internal/api/middleware.go b/internal/api/middleware.go index 3d267d19..e6acd03e 100644 --- a/internal/api/middleware.go +++ b/internal/api/middleware.go @@ -3,8 +3,10 @@ package api import ( "crypto/subtle" "log" + "net" "net/http" "strings" + "sync" "time" ) @@ -140,3 +142,132 @@ func CORSMiddleware(origins []string) Middleware { }) } } + +// RateLimiter implements a token bucket rate limiter per client IP. +type RateLimiter struct { + mu sync.Mutex + clients map[string]*tokenBucket + rate float64 // tokens per second + burst int // max tokens (bucket capacity) +} + +// tokenBucket tracks rate limit state for a single client. +type tokenBucket struct { + tokens float64 + lastSeen time.Time +} + +// NewRateLimiter creates a new rate limiter with the specified rate and burst. +func NewRateLimiter(requestsPerSecond float64, burst int) *RateLimiter { + rl := &RateLimiter{ + clients: make(map[string]*tokenBucket), + rate: requestsPerSecond, + burst: burst, + } + // Start cleanup goroutine to prevent memory leaks + go rl.cleanup() + return rl +} + +// Allow checks if a request from the given IP should be allowed. +func (rl *RateLimiter) Allow(ip string) bool { + rl.mu.Lock() + defer rl.mu.Unlock() + + now := time.Now() + bucket, exists := rl.clients[ip] + + if !exists { + // New client starts with a full bucket + rl.clients[ip] = &tokenBucket{ + tokens: float64(rl.burst) - 1, // Consume one token for this request + lastSeen: now, + } + return true + } + + // Calculate tokens to add based on time elapsed + elapsed := now.Sub(bucket.lastSeen).Seconds() + bucket.tokens += elapsed * rl.rate + if bucket.tokens > float64(rl.burst) { + bucket.tokens = float64(rl.burst) + } + bucket.lastSeen = now + + // Check if we have tokens available + if bucket.tokens < 1 { + return false + } + + bucket.tokens-- + return true +} + +// cleanup removes stale entries to prevent memory leaks. +func (rl *RateLimiter) cleanup() { + ticker := time.NewTicker(5 * time.Minute) + defer ticker.Stop() + + for range ticker.C { + rl.mu.Lock() + cutoff := time.Now().Add(-10 * time.Minute) + for ip, bucket := range rl.clients { + if bucket.lastSeen.Before(cutoff) { + delete(rl.clients, ip) + } + } + rl.mu.Unlock() + } +} + +// RateLimitMiddleware returns a middleware that enforces rate limiting per client IP. +// If limiter is nil, no rate limiting is applied. +func RateLimitMiddleware(limiter *RateLimiter) Middleware { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // If no limiter configured, skip rate limiting + if limiter == nil { + next.ServeHTTP(w, r) + return + } + + // Extract client IP + ip := getClientIP(r) + + // Check rate limit + if !limiter.Allow(ip) { + w.Header().Set("Retry-After", "1") + writeError(w, http.StatusTooManyRequests, "rate limit exceeded", "please slow down") + return + } + + next.ServeHTTP(w, r) + }) + } +} + +// getClientIP extracts the client IP from the request. +// It checks X-Forwarded-For and X-Real-IP headers first (for proxied requests), +// then falls back to RemoteAddr. +func getClientIP(r *http.Request) string { + // Check X-Forwarded-For header (may contain multiple IPs) + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + // Take the first IP (original client) + if idx := strings.Index(xff, ","); idx != -1 { + return strings.TrimSpace(xff[:idx]) + } + return strings.TrimSpace(xff) + } + + // Check X-Real-IP header + if xri := r.Header.Get("X-Real-IP"); xri != "" { + return strings.TrimSpace(xri) + } + + // Fall back to RemoteAddr (strip port) + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return ip +} diff --git a/internal/api/middleware_test.go b/internal/api/middleware_test.go index b43e6a72..d352b38b 100644 --- a/internal/api/middleware_test.go +++ b/internal/api/middleware_test.go @@ -322,3 +322,164 @@ func TestCORSMiddleware_Preflight(t *testing.T) { t.Error("expected Access-Control-Allow-Methods header") } } + +// Rate Limiting Tests + +func TestRateLimiter_Allow(t *testing.T) { + // Create a rate limiter with 10 req/s and burst of 5 + rl := NewRateLimiter(10, 5) + + // First 5 requests should be allowed (burst) + for i := 0; i < 5; i++ { + if !rl.Allow("192.168.1.1") { + t.Errorf("request %d should be allowed", i+1) + } + } + + // 6th request should be denied (burst exhausted) + if rl.Allow("192.168.1.1") { + t.Error("6th request should be denied") + } + + // Different IP should be allowed (separate bucket) + if !rl.Allow("192.168.1.2") { + t.Error("request from different IP should be allowed") + } +} + +func TestRateLimiter_TokenRefill(t *testing.T) { + // Create a rate limiter with 1000 req/s (fast refill for testing) + rl := NewRateLimiter(1000, 2) + + // Exhaust the bucket + rl.Allow("192.168.1.1") + rl.Allow("192.168.1.1") + if rl.Allow("192.168.1.1") { + t.Error("should be rate limited after exhausting burst") + } + + // Wait for refill (at 1000/s, 1ms = 1 token) + time.Sleep(2 * time.Millisecond) + + // Should be allowed again after refill + if !rl.Allow("192.168.1.1") { + t.Error("should be allowed after token refill") + } +} + +func TestRateLimitMiddleware_Disabled(t *testing.T) { + // No rate limiting when not configured + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + // Make many requests - all should succeed + for i := 0; i < 50; i++ { + resp, err := http.Get("http://" + server.Addr() + "/health") + if err != nil { + t.Fatalf("request error: %v", err) + } + resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("request %d: expected 200, got %d", i, resp.StatusCode) + } + } +} + +func TestRateLimitMiddleware_Enabled(t *testing.T) { + // Enable rate limiting with small burst for easy testing + cfg := DefaultConfig().WithListenAddr(":0").WithRateLimit(100, 3) + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + // First 3 requests should succeed (burst) + for i := 0; i < 3; i++ { + resp, err := http.Get("http://" + server.Addr() + "/health") + if err != nil { + t.Fatalf("request error: %v", err) + } + resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("request %d: expected 200, got %d", i+1, resp.StatusCode) + } + } + + // 4th request should be rate limited + resp, err := http.Get("http://" + server.Addr() + "/health") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusTooManyRequests { + t.Errorf("4th request: expected 429, got %d", resp.StatusCode) + } + + // Check Retry-After header + if retry := resp.Header.Get("Retry-After"); retry != "1" { + t.Errorf("expected Retry-After header '1', got %q", retry) + } +} + +func TestGetClientIP_RemoteAddr(t *testing.T) { + req, _ := http.NewRequest("GET", "/", nil) + req.RemoteAddr = "192.168.1.100:12345" + + ip := getClientIP(req) + if ip != "192.168.1.100" { + t.Errorf("expected '192.168.1.100', got %q", ip) + } +} + +func TestGetClientIP_XForwardedFor(t *testing.T) { + req, _ := http.NewRequest("GET", "/", nil) + req.RemoteAddr = "10.0.0.1:12345" + req.Header.Set("X-Forwarded-For", "203.0.113.50, 70.41.3.18, 150.172.238.178") + + ip := getClientIP(req) + if ip != "203.0.113.50" { + t.Errorf("expected '203.0.113.50' (first IP), got %q", ip) + } +} + +func TestGetClientIP_XRealIP(t *testing.T) { + req, _ := http.NewRequest("GET", "/", nil) + req.RemoteAddr = "10.0.0.1:12345" + req.Header.Set("X-Real-IP", "198.51.100.78") + + ip := getClientIP(req) + if ip != "198.51.100.78" { + t.Errorf("expected '198.51.100.78', got %q", ip) + } +} + +func TestGetClientIP_XForwardedForPrecedence(t *testing.T) { + req, _ := http.NewRequest("GET", "/", nil) + req.RemoteAddr = "10.0.0.1:12345" + req.Header.Set("X-Forwarded-For", "203.0.113.50") + req.Header.Set("X-Real-IP", "198.51.100.78") + + // X-Forwarded-For should take precedence + ip := getClientIP(req) + if ip != "203.0.113.50" { + t.Errorf("expected '203.0.113.50' (X-Forwarded-For takes precedence), got %q", ip) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index c31d1cc8..33dae285 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -29,6 +29,9 @@ type Server struct { // Stats provider for statistics collection (optional) statsProvider StatsProvider + // Rate limiter (optional) + rateLimiter *RateLimiter + // Lifecycle state started bool startTime time.Time @@ -48,12 +51,18 @@ func NewServer(cfg Config) (*Server, error) { router: http.NewServeMux(), } + // Create rate limiter if enabled + if cfg.RateLimitEnabled { + s.rateLimiter = NewRateLimiter(cfg.RateLimitRequestsPerSecond, cfg.RateLimitBurst) + } + // Register routes s.registerRoutes() - // Build middleware chain (order: logging -> CORS -> auth) + // Build middleware chain (order: rate limit -> logging -> CORS -> auth) handler := Chain( s.router, + RateLimitMiddleware(s.rateLimiter), LoggingMiddleware, CORSMiddleware(cfg.CORSOrigins), AuthMiddleware(cfg.AuthToken, "/health", "/metrics"), From 9688629e1e262ec01b35a725da64e9306a786c8c Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:51:14 -0600 Subject: [PATCH 20/37] feat(api): serve Prometheus metrics on /metrics A custom collector reads the StatsProvider on each scrape and exports cache, journal, TRIM, lock, SFB and cluster metrics plus Go runtime metrics. Adds github.com/prometheus/client_golang v1.23.2, which raises golang.org/x/sys from v0.28.0 to v0.35.0. Recovered from uncommitted work in the user's checkout; prometheus.go was gofmt'd. Co-Authored-By: Claude Opus 5.5 --- go.mod | 17 +- go.sum | 46 ++- internal/api/prometheus.go | 566 ++++++++++++++++++++++++++++++++ internal/api/prometheus_test.go | 447 +++++++++++++++++++++++++ internal/api/routes.go | 8 +- internal/api/server.go | 14 + 6 files changed, 1090 insertions(+), 8 deletions(-) create mode 100644 internal/api/prometheus.go create mode 100644 internal/api/prometheus_test.go diff --git a/go.mod b/go.mod index 27b26549..2d556f6f 100644 --- a/go.mod +++ b/go.mod @@ -4,4 +4,19 @@ go 1.26.0 require github.com/hanwen/go-fuse/v2 v2.9.0 -require golang.org/x/sys v0.28.0 +require ( + github.com/prometheus/client_golang v1.23.2 + golang.org/x/sys v0.35.0 +) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/prometheus/client_model v0.6.2 // indirect + github.com/prometheus/common v0.66.1 // indirect + github.com/prometheus/procfs v0.16.1 // indirect + go.yaml.in/yaml/v2 v2.4.2 // indirect + google.golang.org/protobuf v1.36.8 // indirect +) diff --git a/go.sum b/go.sum index 5185160b..63cc61ba 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,50 @@ +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/hanwen/go-fuse/v2 v2.9.0 h1:0AOGUkHtbOVeyGLr0tXupiid1Vg7QB7M6YUcdmVdC58= github.com/hanwen/go-fuse/v2 v2.9.0/go.mod h1:yE6D2PqWwm3CbYRxFXV9xUd8Md5d6NG0WBs5spCswmI= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/moby/sys/mountinfo v0.7.2 h1:1shs6aH5s4o5H2zQLn796ADW1wMrIwHsyJ2v9KouLrg= github.com/moby/sys/mountinfo v0.7.2/go.mod h1:1YOa8w8Ih7uW0wALDUgT1dTTSBrZ+HiBLGws92L2RU4= -golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= -golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= +github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs= +github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= +github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= +github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= +go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= +golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc= +google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/api/prometheus.go b/internal/api/prometheus.go new file mode 100644 index 00000000..214dc4ab --- /dev/null +++ b/internal/api/prometheus.go @@ -0,0 +1,566 @@ +package api + +import ( + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "net/http" +) + +const ( + namespace = "goclusterfs" +) + +// MetricsHandler returns an HTTP handler for Prometheus metrics scraping. +// It uses a custom collector that pulls fresh stats from the StatsProvider. +func (s *Server) MetricsHandler() http.Handler { + // Create a custom registry to avoid default Go metrics + registry := prometheus.NewRegistry() + + // Register the filesystem collector + collector := newFSCollector(s) + registry.MustRegister(collector) + + // Also register standard process and Go metrics if desired + registry.MustRegister(prometheus.NewProcessCollector(prometheus.ProcessCollectorOpts{})) + registry.MustRegister(prometheus.NewGoCollector()) + + return promhttp.HandlerFor(registry, promhttp.HandlerOpts{ + EnableOpenMetrics: true, + }) +} + +// fsCollector implements prometheus.Collector interface to expose filesystem stats. +type fsCollector struct { + server *Server + + // Descriptors for all metrics + upDesc *prometheus.Desc + + // Cache metrics + cacheInodeSizeDesc *prometheus.Desc + cacheInodeHitsDesc *prometheus.Desc + cacheInodeMissesDesc *prometheus.Desc + cacheInodeHitRateDesc *prometheus.Desc + cacheExtentSizeDesc *prometheus.Desc + cacheExtentHitsDesc *prometheus.Desc + cacheExtentMissesDesc *prometheus.Desc + cacheExtentHitRateDesc *prometheus.Desc + cacheNegativeSizeDesc *prometheus.Desc + cacheNegativeHitsDesc *prometheus.Desc + cacheNegativeMissesDesc *prometheus.Desc + cacheNegativeHitRateDesc *prometheus.Desc + cacheLockHintSizeDesc *prometheus.Desc + cacheLockHintHitsDesc *prometheus.Desc + cacheLockHintMissesDesc *prometheus.Desc + cacheLockHintHitRateDesc *prometheus.Desc + + // Journal metrics + journalStateDesc *prometheus.Desc + journalHeadOffsetDesc *prometheus.Desc + journalTailOffsetDesc *prometheus.Desc + journalAvailableSpaceDesc *prometheus.Desc + journalActiveTxnCountDesc *prometheus.Desc + journalCommitCountDesc *prometheus.Desc + journalBytesWrittenDesc *prometheus.Desc + journalLastCheckpointDesc *prometheus.Desc + journalBatchSyncCountDesc *prometheus.Desc + + // Trim metrics + trimOperationsDesc *prometheus.Desc + trimBytesDesc *prometheus.Desc + trimBlocksDesc *prometheus.Desc + trimPendingBlocksDesc *prometheus.Desc + trimErrorsDesc *prometheus.Desc + trimEnabledDesc *prometheus.Desc + + // Lock metrics + lockHintCacheHitsDesc *prometheus.Desc + lockHintCacheMissesDesc *prometheus.Desc + lockHintCacheHitRateDesc *prometheus.Desc + lockActiveLocksDesc *prometheus.Desc + lockPendingLocksDesc *prometheus.Desc + + // SFB (Sparse File Bitmap) metrics + sfbTotalBlocksDesc *prometheus.Desc + sfbAllocatedBlocksDesc *prometheus.Desc + sfbFreeBlocksDesc *prometheus.Desc + sfbAllocationPercentDesc *prometheus.Desc + sfbFragmentationDesc *prometheus.Desc + sfbLargestFreeExtentDesc *prometheus.Desc + sfbAllocationsDesc *prometheus.Desc + sfbDeallocationsDesc *prometheus.Desc + sfbAllocationFailuresDesc *prometheus.Desc + + // Cluster metrics + clusterSizeDesc *prometheus.Desc + clusterHealthyNodesDesc *prometheus.Desc + clusterIsLeaderDesc *prometheus.Desc +} + +func newFSCollector(s *Server) *fsCollector { + return &fsCollector{ + server: s, + + // Up metric + upDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "", "up"), + "Whether GoClusterFS is up and running", + nil, nil, + ), + + // Cache - Inode + cacheInodeSizeDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "inode_size"), + "Number of entries in the inode cache", + nil, nil, + ), + cacheInodeHitsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "inode_hits_total"), + "Total inode cache hits", + nil, nil, + ), + cacheInodeMissesDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "inode_misses_total"), + "Total inode cache misses", + nil, nil, + ), + cacheInodeHitRateDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "inode_hit_rate"), + "Inode cache hit rate (0.0-1.0)", + nil, nil, + ), + + // Cache - Extent + cacheExtentSizeDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "extent_size"), + "Number of entries in the extent cache", + nil, nil, + ), + cacheExtentHitsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "extent_hits_total"), + "Total extent cache hits", + nil, nil, + ), + cacheExtentMissesDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "extent_misses_total"), + "Total extent cache misses", + nil, nil, + ), + cacheExtentHitRateDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "extent_hit_rate"), + "Extent cache hit rate (0.0-1.0)", + nil, nil, + ), + + // Cache - Negative + cacheNegativeSizeDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "negative_size"), + "Number of entries in the negative cache", + nil, nil, + ), + cacheNegativeHitsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "negative_hits_total"), + "Total negative cache hits", + nil, nil, + ), + cacheNegativeMissesDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "negative_misses_total"), + "Total negative cache misses", + nil, nil, + ), + cacheNegativeHitRateDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "negative_hit_rate"), + "Negative cache hit rate (0.0-1.0)", + nil, nil, + ), + + // Cache - Lock Hint + cacheLockHintSizeDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "lock_hint_size"), + "Number of entries in the lock hint cache", + nil, nil, + ), + cacheLockHintHitsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "lock_hint_hits_total"), + "Total lock hint cache hits", + nil, nil, + ), + cacheLockHintMissesDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "lock_hint_misses_total"), + "Total lock hint cache misses", + nil, nil, + ), + cacheLockHintHitRateDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cache", "lock_hint_hit_rate"), + "Lock hint cache hit rate (0.0-1.0)", + nil, nil, + ), + + // Journal + journalStateDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "state"), + "Journal state (1=open, 0=closed)", + nil, nil, + ), + journalHeadOffsetDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "head_offset"), + "Journal head offset in bytes", + nil, nil, + ), + journalTailOffsetDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "tail_offset"), + "Journal tail offset in bytes", + nil, nil, + ), + journalAvailableSpaceDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "available_space_bytes"), + "Available space in journal in bytes", + nil, nil, + ), + journalActiveTxnCountDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "active_transactions"), + "Number of active transactions", + nil, nil, + ), + journalCommitCountDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "commits_total"), + "Total number of commits", + nil, nil, + ), + journalBytesWrittenDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "bytes_written_total"), + "Total bytes written to journal", + nil, nil, + ), + journalLastCheckpointDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "last_checkpoint_seq"), + "Last checkpoint sequence number", + nil, nil, + ), + journalBatchSyncCountDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "journal", "batch_syncs_total"), + "Total number of batch syncs", + nil, nil, + ), + + // Trim + trimOperationsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "trim", "operations_total"), + "Total TRIM operations performed", + nil, nil, + ), + trimBytesDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "trim", "bytes_total"), + "Total bytes trimmed", + nil, nil, + ), + trimBlocksDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "trim", "blocks_total"), + "Total blocks trimmed", + nil, nil, + ), + trimPendingBlocksDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "trim", "pending_blocks"), + "Number of blocks pending TRIM", + nil, nil, + ), + trimErrorsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "trim", "errors_total"), + "Total TRIM errors", + nil, nil, + ), + trimEnabledDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "trim", "enabled"), + "Whether TRIM is enabled (1) or disabled (0)", + nil, nil, + ), + + // Lock + lockHintCacheHitsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "lock", "hint_cache_hits_total"), + "Total lock hint cache hits", + nil, nil, + ), + lockHintCacheMissesDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "lock", "hint_cache_misses_total"), + "Total lock hint cache misses", + nil, nil, + ), + lockHintCacheHitRateDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "lock", "hint_cache_hit_rate"), + "Lock hint cache hit rate (0.0-1.0)", + nil, nil, + ), + lockActiveLocksDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "lock", "active_locks"), + "Number of currently active locks", + nil, nil, + ), + lockPendingLocksDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "lock", "pending_locks"), + "Number of pending lock requests", + nil, nil, + ), + + // SFB (Sparse File Bitmap) + sfbTotalBlocksDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "total_blocks"), + "Total number of blocks in the filesystem", + nil, nil, + ), + sfbAllocatedBlocksDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "allocated_blocks"), + "Number of allocated blocks", + nil, nil, + ), + sfbFreeBlocksDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "free_blocks"), + "Number of free blocks", + nil, nil, + ), + sfbAllocationPercentDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "allocation_ratio"), + "Block allocation ratio (0.0-1.0)", + nil, nil, + ), + sfbFragmentationDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "fragmentation_ratio"), + "Block fragmentation ratio (0.0-1.0)", + nil, nil, + ), + sfbLargestFreeExtentDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "largest_free_extent_blocks"), + "Largest contiguous free extent in blocks", + nil, nil, + ), + sfbAllocationsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "allocations_total"), + "Total block allocations", + nil, nil, + ), + sfbDeallocationsDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "deallocations_total"), + "Total block deallocations", + nil, nil, + ), + sfbAllocationFailuresDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "sfb", "allocation_failures_total"), + "Total block allocation failures", + nil, nil, + ), + + // Cluster + clusterSizeDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cluster", "size"), + "Total number of nodes in the cluster", + nil, nil, + ), + clusterHealthyNodesDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cluster", "healthy_nodes"), + "Number of healthy nodes in the cluster", + nil, nil, + ), + clusterIsLeaderDesc: prometheus.NewDesc( + prometheus.BuildFQName(namespace, "cluster", "is_leader"), + "Whether this node is the cluster leader (1) or not (0)", + nil, nil, + ), + } +} + +// Describe sends the super-set of all possible descriptors of metrics +// collected by this Collector to the provided channel. +func (c *fsCollector) Describe(ch chan<- *prometheus.Desc) { + ch <- c.upDesc + + // Cache + ch <- c.cacheInodeSizeDesc + ch <- c.cacheInodeHitsDesc + ch <- c.cacheInodeMissesDesc + ch <- c.cacheInodeHitRateDesc + ch <- c.cacheExtentSizeDesc + ch <- c.cacheExtentHitsDesc + ch <- c.cacheExtentMissesDesc + ch <- c.cacheExtentHitRateDesc + ch <- c.cacheNegativeSizeDesc + ch <- c.cacheNegativeHitsDesc + ch <- c.cacheNegativeMissesDesc + ch <- c.cacheNegativeHitRateDesc + ch <- c.cacheLockHintSizeDesc + ch <- c.cacheLockHintHitsDesc + ch <- c.cacheLockHintMissesDesc + ch <- c.cacheLockHintHitRateDesc + + // Journal + ch <- c.journalStateDesc + ch <- c.journalHeadOffsetDesc + ch <- c.journalTailOffsetDesc + ch <- c.journalAvailableSpaceDesc + ch <- c.journalActiveTxnCountDesc + ch <- c.journalCommitCountDesc + ch <- c.journalBytesWrittenDesc + ch <- c.journalLastCheckpointDesc + ch <- c.journalBatchSyncCountDesc + + // Trim + ch <- c.trimOperationsDesc + ch <- c.trimBytesDesc + ch <- c.trimBlocksDesc + ch <- c.trimPendingBlocksDesc + ch <- c.trimErrorsDesc + ch <- c.trimEnabledDesc + + // Lock + ch <- c.lockHintCacheHitsDesc + ch <- c.lockHintCacheMissesDesc + ch <- c.lockHintCacheHitRateDesc + ch <- c.lockActiveLocksDesc + ch <- c.lockPendingLocksDesc + + // SFB + ch <- c.sfbTotalBlocksDesc + ch <- c.sfbAllocatedBlocksDesc + ch <- c.sfbFreeBlocksDesc + ch <- c.sfbAllocationPercentDesc + ch <- c.sfbFragmentationDesc + ch <- c.sfbLargestFreeExtentDesc + ch <- c.sfbAllocationsDesc + ch <- c.sfbDeallocationsDesc + ch <- c.sfbAllocationFailuresDesc + + // Cluster + ch <- c.clusterSizeDesc + ch <- c.clusterHealthyNodesDesc + ch <- c.clusterIsLeaderDesc +} + +// Collect is called by the Prometheus registry when collecting metrics. +// It fetches fresh stats from the server's StatsProvider. +func (c *fsCollector) Collect(ch chan<- prometheus.Metric) { + // Always report up metric + ch <- prometheus.MustNewConstMetric(c.upDesc, prometheus.GaugeValue, 1) + + // Get stats provider + provider := c.server.GetStatsProvider() + if provider == nil { + return + } + + // Collect cache stats + if cache := provider.CacheStats(); cache != nil { + c.collectCacheStats(ch, cache) + } + + // Collect journal stats + if journal := provider.JournalStats(); journal != nil { + c.collectJournalStats(ch, journal) + } + + // Collect trim stats + if trim := provider.TrimStats(); trim != nil { + c.collectTrimStats(ch, trim) + } + + // Collect lock stats + if lock := provider.LockStats(); lock != nil { + c.collectLockStats(ch, lock) + } + + // Collect SFB stats + if sfb := provider.SFBStats(); sfb != nil { + c.collectSFBStats(ch, sfb) + } + + // Collect cluster stats + if cluster := provider.ClusterInfo(); cluster != nil { + c.collectClusterStats(ch, cluster) + } +} + +func (c *fsCollector) collectCacheStats(ch chan<- prometheus.Metric, stats *CacheStatsResponse) { + // Inode cache + ch <- prometheus.MustNewConstMetric(c.cacheInodeSizeDesc, prometheus.GaugeValue, float64(stats.InodeCache.Size)) + ch <- prometheus.MustNewConstMetric(c.cacheInodeHitsDesc, prometheus.CounterValue, float64(stats.InodeCache.Hits)) + ch <- prometheus.MustNewConstMetric(c.cacheInodeMissesDesc, prometheus.CounterValue, float64(stats.InodeCache.Misses)) + ch <- prometheus.MustNewConstMetric(c.cacheInodeHitRateDesc, prometheus.GaugeValue, stats.InodeCache.HitRate) + + // Extent cache + ch <- prometheus.MustNewConstMetric(c.cacheExtentSizeDesc, prometheus.GaugeValue, float64(stats.ExtentCache.Size)) + ch <- prometheus.MustNewConstMetric(c.cacheExtentHitsDesc, prometheus.CounterValue, float64(stats.ExtentCache.Hits)) + ch <- prometheus.MustNewConstMetric(c.cacheExtentMissesDesc, prometheus.CounterValue, float64(stats.ExtentCache.Misses)) + ch <- prometheus.MustNewConstMetric(c.cacheExtentHitRateDesc, prometheus.GaugeValue, stats.ExtentCache.HitRate) + + // Negative cache + ch <- prometheus.MustNewConstMetric(c.cacheNegativeSizeDesc, prometheus.GaugeValue, float64(stats.NegativeCache.Size)) + ch <- prometheus.MustNewConstMetric(c.cacheNegativeHitsDesc, prometheus.CounterValue, float64(stats.NegativeCache.Hits)) + ch <- prometheus.MustNewConstMetric(c.cacheNegativeMissesDesc, prometheus.CounterValue, float64(stats.NegativeCache.Misses)) + ch <- prometheus.MustNewConstMetric(c.cacheNegativeHitRateDesc, prometheus.GaugeValue, stats.NegativeCache.HitRate) + + // Lock hint cache + ch <- prometheus.MustNewConstMetric(c.cacheLockHintSizeDesc, prometheus.GaugeValue, float64(stats.LockHintCache.Size)) + ch <- prometheus.MustNewConstMetric(c.cacheLockHintHitsDesc, prometheus.CounterValue, float64(stats.LockHintCache.Hits)) + ch <- prometheus.MustNewConstMetric(c.cacheLockHintMissesDesc, prometheus.CounterValue, float64(stats.LockHintCache.Misses)) + ch <- prometheus.MustNewConstMetric(c.cacheLockHintHitRateDesc, prometheus.GaugeValue, stats.LockHintCache.HitRate) +} + +func (c *fsCollector) collectJournalStats(ch chan<- prometheus.Metric, stats *JournalStatsResponse) { + // Convert state to numeric (1=open, 0=other) + stateValue := 0.0 + if stats.State == "open" { + stateValue = 1.0 + } + ch <- prometheus.MustNewConstMetric(c.journalStateDesc, prometheus.GaugeValue, stateValue) + ch <- prometheus.MustNewConstMetric(c.journalHeadOffsetDesc, prometheus.GaugeValue, float64(stats.HeadOffset)) + ch <- prometheus.MustNewConstMetric(c.journalTailOffsetDesc, prometheus.GaugeValue, float64(stats.TailOffset)) + ch <- prometheus.MustNewConstMetric(c.journalAvailableSpaceDesc, prometheus.GaugeValue, float64(stats.AvailableSpace)) + ch <- prometheus.MustNewConstMetric(c.journalActiveTxnCountDesc, prometheus.GaugeValue, float64(stats.ActiveTxnCount)) + ch <- prometheus.MustNewConstMetric(c.journalCommitCountDesc, prometheus.CounterValue, float64(stats.CommitCount)) + ch <- prometheus.MustNewConstMetric(c.journalBytesWrittenDesc, prometheus.CounterValue, float64(stats.BytesWritten)) + ch <- prometheus.MustNewConstMetric(c.journalLastCheckpointDesc, prometheus.GaugeValue, float64(stats.LastCheckpointSeq)) + ch <- prometheus.MustNewConstMetric(c.journalBatchSyncCountDesc, prometheus.CounterValue, float64(stats.BatchSyncCount)) +} + +func (c *fsCollector) collectTrimStats(ch chan<- prometheus.Metric, stats *TrimStatsResponse) { + ch <- prometheus.MustNewConstMetric(c.trimOperationsDesc, prometheus.CounterValue, float64(stats.TrimOperations)) + ch <- prometheus.MustNewConstMetric(c.trimBytesDesc, prometheus.CounterValue, float64(stats.TrimBytes)) + ch <- prometheus.MustNewConstMetric(c.trimBlocksDesc, prometheus.CounterValue, float64(stats.TrimBlocks)) + ch <- prometheus.MustNewConstMetric(c.trimPendingBlocksDesc, prometheus.GaugeValue, float64(stats.PendingTrimBlocks)) + ch <- prometheus.MustNewConstMetric(c.trimErrorsDesc, prometheus.CounterValue, float64(stats.TrimErrors)) + + enabledValue := 0.0 + if stats.TrimEnabled { + enabledValue = 1.0 + } + ch <- prometheus.MustNewConstMetric(c.trimEnabledDesc, prometheus.GaugeValue, enabledValue) +} + +func (c *fsCollector) collectLockStats(ch chan<- prometheus.Metric, stats *LockStatsResponse) { + ch <- prometheus.MustNewConstMetric(c.lockHintCacheHitsDesc, prometheus.CounterValue, float64(stats.HintCacheHits)) + ch <- prometheus.MustNewConstMetric(c.lockHintCacheMissesDesc, prometheus.CounterValue, float64(stats.HintCacheMisses)) + ch <- prometheus.MustNewConstMetric(c.lockHintCacheHitRateDesc, prometheus.GaugeValue, stats.HintCacheHitRate) + ch <- prometheus.MustNewConstMetric(c.lockActiveLocksDesc, prometheus.GaugeValue, float64(stats.ActiveLocks)) + ch <- prometheus.MustNewConstMetric(c.lockPendingLocksDesc, prometheus.GaugeValue, float64(stats.PendingLocks)) +} + +func (c *fsCollector) collectSFBStats(ch chan<- prometheus.Metric, stats *SFBStatsResponse) { + ch <- prometheus.MustNewConstMetric(c.sfbTotalBlocksDesc, prometheus.GaugeValue, float64(stats.TotalBlocks)) + ch <- prometheus.MustNewConstMetric(c.sfbAllocatedBlocksDesc, prometheus.GaugeValue, float64(stats.AllocatedBlocks)) + ch <- prometheus.MustNewConstMetric(c.sfbFreeBlocksDesc, prometheus.GaugeValue, float64(stats.FreeBlocks)) + ch <- prometheus.MustNewConstMetric(c.sfbAllocationPercentDesc, prometheus.GaugeValue, stats.AllocationPercent/100.0) + ch <- prometheus.MustNewConstMetric(c.sfbFragmentationDesc, prometheus.GaugeValue, stats.FragmentationRatio) + ch <- prometheus.MustNewConstMetric(c.sfbLargestFreeExtentDesc, prometheus.GaugeValue, float64(stats.LargestFreeExtent)) + ch <- prometheus.MustNewConstMetric(c.sfbAllocationsDesc, prometheus.CounterValue, float64(stats.AllocationsTotal)) + ch <- prometheus.MustNewConstMetric(c.sfbDeallocationsDesc, prometheus.CounterValue, float64(stats.DeallocationsTotal)) + ch <- prometheus.MustNewConstMetric(c.sfbAllocationFailuresDesc, prometheus.CounterValue, float64(stats.AllocationFailures)) +} + +func (c *fsCollector) collectClusterStats(ch chan<- prometheus.Metric, stats *ClusterInfoResponse) { + ch <- prometheus.MustNewConstMetric(c.clusterSizeDesc, prometheus.GaugeValue, float64(stats.ClusterSize)) + ch <- prometheus.MustNewConstMetric(c.clusterHealthyNodesDesc, prometheus.GaugeValue, float64(stats.HealthyNodes)) + + isLeader := 0.0 + if stats.Role == "leader" { + isLeader = 1.0 + } + ch <- prometheus.MustNewConstMetric(c.clusterIsLeaderDesc, prometheus.GaugeValue, isLeader) +} diff --git a/internal/api/prometheus_test.go b/internal/api/prometheus_test.go new file mode 100644 index 00000000..01503cc5 --- /dev/null +++ b/internal/api/prometheus_test.go @@ -0,0 +1,447 @@ +package api + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus" +) + +func TestMetricsEndpoint_BasicUp(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/metrics") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body error: %v", err) + } + + content := string(body) + + // Should always have the up metric + if !strings.Contains(content, "goclusterfs_up 1") { + t.Error("expected goclusterfs_up metric") + } + + // Should have Go collector metrics + if !strings.Contains(content, "go_goroutines") { + t.Error("expected go_goroutines metric from Go collector") + } + + // Should have process metrics + if !strings.Contains(content, "process_") { + t.Error("expected process_* metrics from process collector") + } +} + +func TestMetricsEndpoint_WithStatsProvider(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Set up mock provider with all stats + server.SetStatsProvider(&mockStatsProvider{ + cache: &CacheStatsResponse{ + InodeCache: CacheHitRateInfo{ + Size: 1000, + Hits: 800, + Misses: 200, + HitRate: 0.8, + }, + ExtentCache: CacheHitRateInfo{ + Size: 500, + Hits: 400, + Misses: 100, + HitRate: 0.8, + }, + NegativeCache: CacheHitRateInfo{ + Size: 100, + Hits: 50, + Misses: 50, + HitRate: 0.5, + }, + LockHintCache: CacheHitRateInfo{ + Size: 200, + Hits: 180, + Misses: 20, + HitRate: 0.9, + }, + }, + journal: &JournalStatsResponse{ + State: "open", + HeadOffset: 4096, + TailOffset: 2048, + AvailableSpace: 1048576, + ActiveTxnCount: 5, + CommitCount: 1000, + BytesWritten: 10485760, + LastCheckpointSeq: 999, + BatchSyncCount: 100, + }, + trim: &TrimStatsResponse{ + TrimOperations: 500, + TrimBytes: 52428800, + TrimBlocks: 50, + PendingTrimBlocks: 5, + TrimErrors: 2, + TrimEnabled: true, + }, + lock: &LockStatsResponse{ + HintCacheHits: 900, + HintCacheMisses: 100, + HintCacheHitRate: 0.9, + ActiveLocks: 10, + PendingLocks: 2, + }, + sfb: &SFBStatsResponse{ + TotalBlocks: 1000, + AllocatedBlocks: 600, + FreeBlocks: 400, + AllocationPercent: 60.0, + FragmentationRatio: 0.1, + LargestFreeExtent: 100, + AllocationsTotal: 5000, + DeallocationsTotal: 4400, + AllocationFailures: 5, + }, + cluster: &ClusterInfoResponse{ + NodeID: "node-1", + Role: "leader", + State: "active", + ClusterSize: 3, + HealthyNodes: 3, + }, + }) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/metrics") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body error: %v", err) + } + + content := string(body) + + // Cache metrics + expectedMetrics := []string{ + "goclusterfs_cache_inode_size 1000", + "goclusterfs_cache_inode_hits_total 800", + "goclusterfs_cache_inode_misses_total 200", + "goclusterfs_cache_inode_hit_rate 0.8", + "goclusterfs_cache_extent_size 500", + "goclusterfs_cache_extent_hits_total 400", + "goclusterfs_cache_negative_size 100", + "goclusterfs_cache_lock_hint_size 200", + "goclusterfs_cache_lock_hint_hit_rate 0.9", + + // Journal metrics + "goclusterfs_journal_state 1", + "goclusterfs_journal_head_offset 4096", + "goclusterfs_journal_tail_offset 2048", + "goclusterfs_journal_available_space_bytes 1.048576e+06", + "goclusterfs_journal_active_transactions 5", + "goclusterfs_journal_commits_total 1000", + "goclusterfs_journal_bytes_written_total 1.048576e+07", + "goclusterfs_journal_batch_syncs_total 100", + + // Trim metrics + "goclusterfs_trim_operations_total 500", + "goclusterfs_trim_bytes_total 5.24288e+07", + "goclusterfs_trim_blocks_total 50", + "goclusterfs_trim_pending_blocks 5", + "goclusterfs_trim_errors_total 2", + "goclusterfs_trim_enabled 1", + + // Lock metrics + "goclusterfs_lock_hint_cache_hits_total 900", + "goclusterfs_lock_hint_cache_misses_total 100", + "goclusterfs_lock_hint_cache_hit_rate 0.9", + "goclusterfs_lock_active_locks 10", + "goclusterfs_lock_pending_locks 2", + + // SFB metrics + "goclusterfs_sfb_total_blocks 1000", + "goclusterfs_sfb_allocated_blocks 600", + "goclusterfs_sfb_free_blocks 400", + "goclusterfs_sfb_allocations_total 5000", + "goclusterfs_sfb_deallocations_total 4400", + "goclusterfs_sfb_allocation_failures_total 5", + + // Cluster metrics + "goclusterfs_cluster_size 3", + "goclusterfs_cluster_healthy_nodes 3", + "goclusterfs_cluster_is_leader 1", + } + + for _, metric := range expectedMetrics { + if !strings.Contains(content, metric) { + t.Errorf("expected metric %q not found in output", metric) + } + } +} + +func TestMetricsEndpoint_JournalClosedState(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Set up mock provider with closed journal + server.SetStatsProvider(&mockStatsProvider{ + journal: &JournalStatsResponse{ + State: "closed", + }, + }) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/metrics") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body error: %v", err) + } + + content := string(body) + + // Journal state should be 0 for closed + if !strings.Contains(content, "goclusterfs_journal_state 0") { + t.Error("expected journal_state to be 0 for closed state") + } +} + +func TestMetricsEndpoint_TrimDisabled(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Set up mock provider with TRIM disabled + server.SetStatsProvider(&mockStatsProvider{ + trim: &TrimStatsResponse{ + TrimEnabled: false, + }, + }) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/metrics") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body error: %v", err) + } + + content := string(body) + + // Trim enabled should be 0 + if !strings.Contains(content, "goclusterfs_trim_enabled 0") { + t.Error("expected trim_enabled to be 0") + } +} + +func TestMetricsEndpoint_ClusterFollower(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Set up mock provider with follower node + server.SetStatsProvider(&mockStatsProvider{ + cluster: &ClusterInfoResponse{ + NodeID: "node-2", + Role: "follower", + State: "active", + ClusterSize: 3, + HealthyNodes: 3, + }, + }) + + if err := server.Start(context.Background()); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/metrics") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body error: %v", err) + } + + content := string(body) + + // is_leader should be 0 for follower + if !strings.Contains(content, "goclusterfs_cluster_is_leader 0") { + t.Error("expected is_leader to be 0 for follower") + } +} + +func TestMetricsEndpoint_ContentType(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + resp, err := http.Get("http://" + server.Addr() + "/metrics") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + contentType := resp.Header.Get("Content-Type") + // Prometheus handler returns text/plain with version info + if !strings.HasPrefix(contentType, "text/plain") && + !strings.HasPrefix(contentType, "application/openmetrics-text") { + t.Errorf("unexpected content-type: %q", contentType) + } +} + +func TestMetricsEndpoint_MethodNotAllowed(t *testing.T) { + server := startTestServer(t) + defer server.Stop() + + client := &http.Client{} + req, err := http.NewRequest(http.MethodPost, "http://"+server.Addr()+"/metrics", nil) + if err != nil { + t.Fatalf("create request error: %v", err) + } + + resp, err := client.Do(req) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Errorf("expected status 405, got %d", resp.StatusCode) + } +} + +func TestMetricsHandler_LazyInit(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Get handler multiple times - should not panic and return non-nil + handler1 := server.GetMetricsHandler() + if handler1 == nil { + t.Error("expected non-nil handler on first call") + } + + handler2 := server.GetMetricsHandler() + if handler2 == nil { + t.Error("expected non-nil handler on second call") + } + + // Both calls should succeed without panic +} + +func TestFSCollector_Describe(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + collector := newFSCollector(server) + ch := make(chan *prometheus.Desc, 100) + + go func() { + collector.Describe(ch) + close(ch) + }() + + count := 0 + for range ch { + count++ + } + + // Should have descriptors for all metrics + // up (1) + cache (16) + journal (9) + trim (6) + lock (5) + sfb (9) + cluster (3) = 49 + expectedMinimum := 40 // Allow some flexibility + if count < expectedMinimum { + t.Errorf("expected at least %d descriptors, got %d", expectedMinimum, count) + } +} + +func TestFSCollector_Collect_NoProvider(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // No stats provider set + collector := newFSCollector(server) + ch := make(chan prometheus.Metric, 100) + + go func() { + collector.Collect(ch) + close(ch) + }() + + count := 0 + for range ch { + count++ + } + + // Should only have the up metric when no provider + if count != 1 { + t.Errorf("expected 1 metric (up), got %d", count) + } +} diff --git a/internal/api/routes.go b/internal/api/routes.go index 690e1b4e..5d510894 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -270,15 +270,13 @@ func (s *Server) handleStatsAll(w http.ResponseWriter, r *http.Request) { } // handleMetrics handles GET /metrics requests for Prometheus scraping. +// Delegates to the Prometheus metrics handler for proper metric exposition. func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET") return } - w.Header().Set("Content-Type", "text/plain; charset=utf-8") - w.WriteHeader(http.StatusOK) - w.Write([]byte("# HELP goclusterfs_up Indicates if GoClusterFS is up\n")) - w.Write([]byte("# TYPE goclusterfs_up gauge\n")) - w.Write([]byte("goclusterfs_up 1\n")) + // Delegate to the Prometheus handler + s.GetMetricsHandler().ServeHTTP(w, r) } diff --git a/internal/api/server.go b/internal/api/server.go index 33dae285..03ecf292 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -32,6 +32,9 @@ type Server struct { // Rate limiter (optional) rateLimiter *RateLimiter + // Prometheus metrics handler (lazily initialized) + metricsHandler http.Handler + // Lifecycle state started bool startTime time.Time @@ -262,3 +265,14 @@ func (s *Server) GetStatsProvider() StatsProvider { defer s.mu.RUnlock() return s.statsProvider } + +// GetMetricsHandler returns the Prometheus metrics HTTP handler. +// The handler is lazily initialized on first call. +func (s *Server) GetMetricsHandler() http.Handler { + s.mu.Lock() + defer s.mu.Unlock() + if s.metricsHandler == nil { + s.metricsHandler = s.MetricsHandler() + } + return s.metricsHandler +} From a8ce03c74afa1b30bc17f1de69f7a6c08f026c14 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 03:56:30 -0600 Subject: [PATCH 21/37] feat(api): add /api/v1/cluster status, nodes and locks endpoints StatsProvider gains ClusterNodes and ClusterLocks. The handlers answer 503 without a provider and 404 when the provider has no cluster data. Recovered from uncommitted work in the user's checkout. Co-Authored-By: Claude Opus 5.5 --- internal/api/routes.go | 80 ++++++++ internal/api/server.go | 6 + internal/api/server_test.go | 398 +++++++++++++++++++++++++++++++++++- internal/api/types.go | 42 ++++ 4 files changed, 519 insertions(+), 7 deletions(-) diff --git a/internal/api/routes.go b/internal/api/routes.go index 5d510894..3791ddb8 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -59,6 +59,8 @@ func (s *Server) handleAPIv1(w http.ResponseWriter, r *http.Request) { s.handleStatus(w, r) case strings.HasPrefix(path, "/stats"): s.handleStats(w, r) + case strings.HasPrefix(path, "/cluster"): + s.handleCluster(w, r) default: writeError(w, http.StatusNotFound, "endpoint not found", "") } @@ -280,3 +282,81 @@ func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) { // Delegate to the Prometheus handler s.GetMetricsHandler().ServeHTTP(w, r) } + +// handleCluster handles GET /api/v1/cluster/* requests. +// Routes to specific cluster handlers based on the path suffix. +func (s *Server) handleCluster(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + writeError(w, http.StatusMethodNotAllowed, "method not allowed", "use GET") + return + } + + // Extract the cluster sub-path + path := strings.TrimPrefix(r.URL.Path, "/api/v1/cluster") + path = strings.TrimSuffix(path, "/") + + switch path { + case "", "/status": + s.handleClusterStatus(w, r) + case "/nodes": + s.handleClusterNodes(w, r) + case "/locks": + s.handleClusterLocks(w, r) + default: + writeError(w, http.StatusNotFound, "cluster endpoint not found", "valid endpoints: status, nodes, locks") + } +} + +// handleClusterStatus handles GET /api/v1/cluster/status requests. +// Returns cluster membership and health overview. +func (s *Server) handleClusterStatus(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "cluster info not available", "no stats provider configured") + return + } + + stats := provider.ClusterInfo() + if stats == nil { + writeError(w, http.StatusNotFound, "cluster info not available", "running in standalone mode") + return + } + + writeJSON(w, http.StatusOK, stats) +} + +// handleClusterNodes handles GET /api/v1/cluster/nodes requests. +// Returns detailed information about all cluster nodes. +func (s *Server) handleClusterNodes(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "cluster nodes not available", "no stats provider configured") + return + } + + nodes := provider.ClusterNodes() + if nodes == nil { + writeError(w, http.StatusNotFound, "cluster nodes not available", "running in standalone mode") + return + } + + writeJSON(w, http.StatusOK, nodes) +} + +// handleClusterLocks handles GET /api/v1/cluster/locks requests. +// Returns active distributed locks in the cluster. +func (s *Server) handleClusterLocks(w http.ResponseWriter, r *http.Request) { + provider := s.GetStatsProvider() + if provider == nil { + writeError(w, http.StatusServiceUnavailable, "cluster locks not available", "no stats provider configured") + return + } + + locks := provider.ClusterLocks() + if locks == nil { + writeError(w, http.StatusNotFound, "cluster locks not available", "running in standalone mode") + return + } + + writeJSON(w, http.StatusOK, locks) +} diff --git a/internal/api/server.go b/internal/api/server.go index 03ecf292..869fc69b 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -248,6 +248,12 @@ type StatsProvider interface { // ClusterInfo returns cluster information, or nil if not available. ClusterInfo() *ClusterInfoResponse + // ClusterNodes returns detailed node information, or nil if not available. + ClusterNodes() *ClusterNodesResponse + + // ClusterLocks returns active distributed locks, or nil if not available. + ClusterLocks() *ClusterLocksResponse + // AllStats returns a combined snapshot of all statistics. AllStats() *AllStatsResponse } diff --git a/internal/api/server_test.go b/internal/api/server_test.go index 32e3e5ac..a7178e25 100644 --- a/internal/api/server_test.go +++ b/internal/api/server_test.go @@ -320,13 +320,15 @@ func TestServer_AddrBeforeStart(t *testing.T) { // mockStatsProvider implements StatsProvider for testing. type mockStatsProvider struct { - cache *CacheStatsResponse - journal *JournalStatsResponse - trim *TrimStatsResponse - lock *LockStatsResponse - sfb *SFBStatsResponse - cluster *ClusterInfoResponse - all *AllStatsResponse + cache *CacheStatsResponse + journal *JournalStatsResponse + trim *TrimStatsResponse + lock *LockStatsResponse + sfb *SFBStatsResponse + cluster *ClusterInfoResponse + clusterNodes *ClusterNodesResponse + clusterLocks *ClusterLocksResponse + all *AllStatsResponse } func (m *mockStatsProvider) CacheStats() *CacheStatsResponse { return m.cache } @@ -335,6 +337,8 @@ func (m *mockStatsProvider) TrimStats() *TrimStatsResponse { return m.trim func (m *mockStatsProvider) LockStats() *LockStatsResponse { return m.lock } func (m *mockStatsProvider) SFBStats() *SFBStatsResponse { return m.sfb } func (m *mockStatsProvider) ClusterInfo() *ClusterInfoResponse { return m.cluster } +func (m *mockStatsProvider) ClusterNodes() *ClusterNodesResponse { return m.clusterNodes } +func (m *mockStatsProvider) ClusterLocks() *ClusterLocksResponse { return m.clusterLocks } func (m *mockStatsProvider) AllStats() *AllStatsResponse { return m.all } func TestServer_StatsEndpoints_NoProvider(t *testing.T) { @@ -878,3 +882,383 @@ func TestServer_StatsMethodNotAllowed(t *testing.T) { t.Errorf("expected status 405, got %d", resp.StatusCode) } } + +// Cluster endpoint tests + +func TestServer_ClusterNodesEndpoint(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + clusterNodes: &ClusterNodesResponse{ + ClusterID: "test-cluster", + TotalNodes: 3, + HealthyNodes: 3, + LeaderID: "node-1", + Nodes: []ClusterNodeInfo{ + { + NodeID: "node-1", + Address: "192.168.1.1:7946", + Role: "leader", + State: "active", + LastHeartbeat: "2024-01-01T00:00:00Z", + IsSelf: true, + }, + { + NodeID: "node-2", + Address: "192.168.1.2:7946", + Role: "follower", + State: "active", + LastHeartbeat: "2024-01-01T00:00:00Z", + IsSelf: false, + LatencyMs: 1.5, + }, + { + NodeID: "node-3", + Address: "192.168.1.3:7946", + Role: "follower", + State: "active", + LastHeartbeat: "2024-01-01T00:00:00Z", + IsSelf: false, + LatencyMs: 2.1, + }, + }, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/cluster/nodes") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + var nodes ClusterNodesResponse + if err := json.NewDecoder(resp.Body).Decode(&nodes); err != nil { + t.Fatalf("decode error: %v", err) + } + + if nodes.TotalNodes != 3 { + t.Errorf("expected 3 total nodes, got %d", nodes.TotalNodes) + } + if nodes.ClusterID != "test-cluster" { + t.Errorf("expected cluster_id 'test-cluster', got %q", nodes.ClusterID) + } + if len(nodes.Nodes) != 3 { + t.Errorf("expected 3 nodes in list, got %d", len(nodes.Nodes)) + } +} + +func TestServer_ClusterLocksEndpoint(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + clusterLocks: &ClusterLocksResponse{ + ActiveLocks: 2, + PendingLocks: 1, + Locks: []DistributedLockInfo{ + { + LockID: "lock-1", + Resource: "/data/file1.txt", + OwnerNodeID: "node-1", + AcquiredAt: "2024-01-01T00:00:00Z", + LockType: "exclusive", + }, + { + LockID: "lock-2", + Resource: "/data/file2.txt", + OwnerNodeID: "node-2", + AcquiredAt: "2024-01-01T00:01:00Z", + ExpiresAt: "2024-01-01T00:11:00Z", + LockType: "shared", + }, + }, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/cluster/locks") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + var locks ClusterLocksResponse + if err := json.NewDecoder(resp.Body).Decode(&locks); err != nil { + t.Fatalf("decode error: %v", err) + } + + if locks.ActiveLocks != 2 { + t.Errorf("expected 2 active locks, got %d", locks.ActiveLocks) + } + if locks.PendingLocks != 1 { + t.Errorf("expected 1 pending lock, got %d", locks.PendingLocks) + } + if len(locks.Locks) != 2 { + t.Errorf("expected 2 locks in list, got %d", len(locks.Locks)) + } +} + +func TestServer_ClusterStatusEndpoint(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + cluster: &ClusterInfoResponse{ + NodeID: "node-1", + Role: "leader", + State: "active", + ClusterSize: 3, + HealthyNodes: 3, + LeaderID: "node-1", + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + // Test /api/v1/cluster/status + resp, err := http.Get("http://" + server.Addr() + "/api/v1/cluster/status") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + var cluster ClusterInfoResponse + if err := json.NewDecoder(resp.Body).Decode(&cluster); err != nil { + t.Fatalf("decode error: %v", err) + } + + if cluster.NodeID != "node-1" { + t.Errorf("expected node_id 'node-1', got %q", cluster.NodeID) + } + if cluster.Role != "leader" { + t.Errorf("expected role 'leader', got %q", cluster.Role) + } +} + +func TestServer_ClusterEndpoints_NoProvider(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // No stats provider set + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + endpoints := []string{ + "/api/v1/cluster/nodes", + "/api/v1/cluster/locks", + "/api/v1/cluster/status", + } + + for _, endpoint := range endpoints { + t.Run(endpoint, func(t *testing.T) { + resp, err := http.Get("http://" + server.Addr() + endpoint) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusServiceUnavailable { + t.Errorf("expected status 503, got %d", resp.StatusCode) + } + }) + } +} + +func TestServer_ClusterEndpoints_NotAvailable(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + // Set empty provider (returns nil for all cluster data) + mockProvider := &mockStatsProvider{} + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + endpoints := []string{ + "/api/v1/cluster/nodes", + "/api/v1/cluster/locks", + "/api/v1/cluster/status", + } + + for _, endpoint := range endpoints { + t.Run(endpoint, func(t *testing.T) { + resp, err := http.Get("http://" + server.Addr() + endpoint) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + // Should return 404 when running standalone (no cluster data) + if resp.StatusCode != http.StatusNotFound { + t.Errorf("expected status 404, got %d", resp.StatusCode) + } + }) + } +} + +func TestServer_ClusterUnknownEndpoint(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{} + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + resp, err := http.Get("http://" + server.Addr() + "/api/v1/cluster/unknown") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusNotFound { + t.Errorf("expected status 404, got %d", resp.StatusCode) + } +} + +func TestServer_ClusterMethodNotAllowed(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + // POST should not be allowed + resp, err := http.Post("http://"+server.Addr()+"/api/v1/cluster/nodes", "application/json", nil) + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusMethodNotAllowed { + t.Errorf("expected status 405, got %d", resp.StatusCode) + } +} + +func TestServer_ClusterDefaultRoute(t *testing.T) { + cfg := DefaultConfig().WithListenAddr(":0") + server, err := NewServer(cfg) + if err != nil { + t.Fatalf("NewServer error: %v", err) + } + + mockProvider := &mockStatsProvider{ + cluster: &ClusterInfoResponse{ + NodeID: "node-1", + Role: "leader", + State: "active", + ClusterSize: 1, + HealthyNodes: 1, + }, + } + server.SetStatsProvider(mockProvider) + + ctx := context.Background() + if err := server.Start(ctx); err != nil { + t.Fatalf("Start error: %v", err) + } + defer server.Stop() + + time.Sleep(10 * time.Millisecond) + + // /api/v1/cluster (no path) should default to status + resp, err := http.Get("http://" + server.Addr() + "/api/v1/cluster") + if err != nil { + t.Fatalf("request error: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Errorf("expected status 200, got %d", resp.StatusCode) + } + + var cluster ClusterInfoResponse + if err := json.NewDecoder(resp.Body).Decode(&cluster); err != nil { + t.Fatalf("decode error: %v", err) + } + + if cluster.NodeID != "node-1" { + t.Errorf("expected node_id 'node-1', got %q", cluster.NodeID) + } +} diff --git a/internal/api/types.go b/internal/api/types.go index 06e9cab2..9747bc62 100644 --- a/internal/api/types.go +++ b/internal/api/types.go @@ -201,6 +201,48 @@ type AllStatsResponse struct { Cluster *ClusterInfoResponse `json:"cluster,omitempty"` } +// ClusterNodeInfo provides detailed information about a cluster node. +type ClusterNodeInfo struct { + NodeID string `json:"node_id"` + Address string `json:"address"` + Role string `json:"role"` + State string `json:"state"` + LastHeartbeat string `json:"last_heartbeat,omitempty"` + JoinedAt string `json:"joined_at,omitempty"` + Version string `json:"version,omitempty"` + LatencyMs float64 `json:"latency_ms,omitempty"` + IsSelf bool `json:"is_self"` +} + +// ClusterNodesResponse is returned by GET /api/v1/cluster/nodes. +// Lists all nodes in the cluster with their current status. +type ClusterNodesResponse struct { + ClusterID string `json:"cluster_id,omitempty"` + TotalNodes int `json:"total_nodes"` + HealthyNodes int `json:"healthy_nodes"` + LeaderID string `json:"leader_id,omitempty"` + Nodes []ClusterNodeInfo `json:"nodes"` +} + +// DistributedLockInfo provides information about an active distributed lock. +type DistributedLockInfo struct { + LockID string `json:"lock_id"` + Resource string `json:"resource"` + OwnerNodeID string `json:"owner_node_id"` + OwnerProcess string `json:"owner_process,omitempty"` + AcquiredAt string `json:"acquired_at"` + ExpiresAt string `json:"expires_at,omitempty"` + LockType string `json:"lock_type"` +} + +// ClusterLocksResponse is returned by GET /api/v1/cluster/locks. +// Lists all active distributed locks in the cluster. +type ClusterLocksResponse struct { + ActiveLocks int `json:"active_locks"` + PendingLocks int `json:"pending_locks"` + Locks []DistributedLockInfo `json:"locks"` +} + // StatsOverviewResponse is returned by GET /api/v1/stats. // Provides a summary of all component stats. type StatsOverviewResponse struct { From 5eb160f72f6dab4c5d86b4bfd69d683f978aa7d0 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Wed, 31 Dec 2025 04:19:15 -0600 Subject: [PATCH 22/37] feat(gfsctl): add a CLI client for the HTTP API gfsctl wraps the API: status, health, stats, cluster, snapshot, admin, watch, config and shell completion. It reads host, port and token from flags, GFSCTL_* variables or ~/.config/gfsctl/config.yaml. Adds spf13/cobra v1.10.2 and gopkg.in/yaml.v2 v2.4.0. The snapshot and admin commands call /api/v1/snapshots and /api/v1/admin/*, which the server does not have yet. Recovered from uncommitted work in the user's checkout. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + cmd/gfsctl/client/api.go | 176 ++++++++++++++ cmd/gfsctl/client/client.go | 258 ++++++++++++++++++++ cmd/gfsctl/client/types.go | 271 +++++++++++++++++++++ cmd/gfsctl/commands/admin.go | 227 ++++++++++++++++++ cmd/gfsctl/commands/cluster.go | 202 ++++++++++++++++ cmd/gfsctl/commands/completion.go | 69 ++++++ cmd/gfsctl/commands/config.go | 131 +++++++++++ cmd/gfsctl/commands/config_cmd.go | 146 ++++++++++++ cmd/gfsctl/commands/health.go | 70 ++++++ cmd/gfsctl/commands/output.go | 209 +++++++++++++++++ cmd/gfsctl/commands/root.go | 102 ++++++++ cmd/gfsctl/commands/snapshot.go | 243 +++++++++++++++++++ cmd/gfsctl/commands/stats.go | 376 ++++++++++++++++++++++++++++++ cmd/gfsctl/commands/status.go | 145 ++++++++++++ cmd/gfsctl/commands/version.go | 59 +++++ cmd/gfsctl/commands/watch.go | 96 ++++++++ cmd/gfsctl/main.go | 36 +++ go.mod | 7 +- go.sum | 11 + 20 files changed, 2833 insertions(+), 2 deletions(-) create mode 100644 cmd/gfsctl/client/api.go create mode 100644 cmd/gfsctl/client/client.go create mode 100644 cmd/gfsctl/client/types.go create mode 100644 cmd/gfsctl/commands/admin.go create mode 100644 cmd/gfsctl/commands/cluster.go create mode 100644 cmd/gfsctl/commands/completion.go create mode 100644 cmd/gfsctl/commands/config.go create mode 100644 cmd/gfsctl/commands/config_cmd.go create mode 100644 cmd/gfsctl/commands/health.go create mode 100644 cmd/gfsctl/commands/output.go create mode 100644 cmd/gfsctl/commands/root.go create mode 100644 cmd/gfsctl/commands/snapshot.go create mode 100644 cmd/gfsctl/commands/stats.go create mode 100644 cmd/gfsctl/commands/status.go create mode 100644 cmd/gfsctl/commands/version.go create mode 100644 cmd/gfsctl/commands/watch.go create mode 100644 cmd/gfsctl/main.go diff --git a/.gitignore b/.gitignore index 2f2a6839..1aebb0ec 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ tests/vm/runtime/ tests/vm/results/ /fsck /dist/ +/gfsctl diff --git a/cmd/gfsctl/client/api.go b/cmd/gfsctl/client/api.go new file mode 100644 index 00000000..30028b0d --- /dev/null +++ b/cmd/gfsctl/client/api.go @@ -0,0 +1,176 @@ +package client + +import ( + "context" +) + +// Health fetches the health status from the API. +func (c *Client) Health(ctx context.Context) (*HealthResponse, error) { + var resp HealthResponse + if err := c.Get(ctx, "/health", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// Status fetches the filesystem status from the API. +func (c *Client) Status(ctx context.Context) (*StatusResponse, error) { + var resp StatusResponse + if err := c.Get(ctx, "/api/v1/status", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// StatsOverview fetches the stats overview from the API. +func (c *Client) StatsOverview(ctx context.Context) (*StatsOverviewResponse, error) { + var resp StatsOverviewResponse + if err := c.Get(ctx, "/api/v1/stats", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// CacheStats fetches cache statistics from the API. +func (c *Client) CacheStats(ctx context.Context) (*CacheStatsResponse, error) { + var resp CacheStatsResponse + if err := c.Get(ctx, "/api/v1/stats/cache", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// JournalStats fetches journal statistics from the API. +func (c *Client) JournalStats(ctx context.Context) (*JournalStatsResponse, error) { + var resp JournalStatsResponse + if err := c.Get(ctx, "/api/v1/stats/journal", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// TrimStats fetches TRIM statistics from the API. +func (c *Client) TrimStats(ctx context.Context) (*TrimStatsResponse, error) { + var resp TrimStatsResponse + if err := c.Get(ctx, "/api/v1/stats/trim", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// LockStats fetches lock statistics from the API. +func (c *Client) LockStats(ctx context.Context) (*LockStatsResponse, error) { + var resp LockStatsResponse + if err := c.Get(ctx, "/api/v1/stats/lock", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// SFBStats fetches SFB (Sub-File Block) statistics from the API. +func (c *Client) SFBStats(ctx context.Context) (*SFBStatsResponse, error) { + var resp SFBStatsResponse + if err := c.Get(ctx, "/api/v1/stats/sfb", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// AllStats fetches all statistics from the API. +func (c *Client) AllStats(ctx context.Context) (*AllStatsResponse, error) { + var resp AllStatsResponse + if err := c.Get(ctx, "/api/v1/stats/all", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// ClusterStatus fetches cluster status from the API. +func (c *Client) ClusterStatus(ctx context.Context) (*ClusterInfoResponse, error) { + var resp ClusterInfoResponse + if err := c.Get(ctx, "/api/v1/cluster/status", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// ClusterNodes fetches cluster node information from the API. +func (c *Client) ClusterNodes(ctx context.Context) (*ClusterNodesResponse, error) { + var resp ClusterNodesResponse + if err := c.Get(ctx, "/api/v1/cluster/nodes", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// ClusterLocks fetches distributed lock information from the API. +func (c *Client) ClusterLocks(ctx context.Context) (*ClusterLocksResponse, error) { + var resp ClusterLocksResponse + if err := c.Get(ctx, "/api/v1/cluster/locks", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// SnapshotList lists all snapshots. +func (c *Client) SnapshotList(ctx context.Context) (*SnapshotListResponse, error) { + var resp SnapshotListResponse + if err := c.Get(ctx, "/api/v1/snapshots", &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// SnapshotInfo gets information about a specific snapshot. +func (c *Client) SnapshotInfo(ctx context.Context, id string) (*SnapshotInfo, error) { + var resp SnapshotInfo + if err := c.Get(ctx, "/api/v1/snapshots/"+id, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// SnapshotCreate creates a new snapshot. +func (c *Client) SnapshotCreate(ctx context.Context, req *SnapshotCreateRequest) (*SnapshotCreateResponse, error) { + var resp SnapshotCreateResponse + if err := c.Post(ctx, "/api/v1/snapshots", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// SnapshotDelete deletes a snapshot. +func (c *Client) SnapshotDelete(ctx context.Context, id string) (*SnapshotDeleteResponse, error) { + var resp SnapshotDeleteResponse + if err := c.Delete(ctx, "/api/v1/snapshots/"+id, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// AdminFlushJournal flushes the journal to disk. +func (c *Client) AdminFlushJournal(ctx context.Context, req *FlushJournalRequest) (*AdminOperationResponse, error) { + var resp AdminOperationResponse + if err := c.Post(ctx, "/api/v1/admin/flush-journal", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// AdminClearCache clears the specified cache. +func (c *Client) AdminClearCache(ctx context.Context, req *ClearCacheRequest) (*AdminOperationResponse, error) { + var resp AdminOperationResponse + if err := c.Post(ctx, "/api/v1/admin/clear-cache", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} + +// AdminForceTrim forces a TRIM operation. +func (c *Client) AdminForceTrim(ctx context.Context, req *ForceTrimRequest) (*AdminOperationResponse, error) { + var resp AdminOperationResponse + if err := c.Post(ctx, "/api/v1/admin/force-trim", req, &resp); err != nil { + return nil, err + } + return &resp, nil +} diff --git a/cmd/gfsctl/client/client.go b/cmd/gfsctl/client/client.go new file mode 100644 index 00000000..9a1c1c65 --- /dev/null +++ b/cmd/gfsctl/client/client.go @@ -0,0 +1,258 @@ +// Package client provides an HTTP client for the GoClusterFS API. +package client + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "time" +) + +// Client is an HTTP client for the GoClusterFS API. +type Client struct { + baseURL string + token string + httpClient *http.Client +} + +// Option configures a Client. +type Option func(*Client) + +// WithHost sets the API server host. +func WithHost(host string) Option { + return func(c *Client) { + c.baseURL = fmt.Sprintf("http://%s", host) + } +} + +// WithPort sets the API server port. +func WithPort(port int) Option { + return func(c *Client) { + // Extract host from existing baseURL or default to localhost + host := "localhost" + if c.baseURL != "" { + // Parse existing host + if len(c.baseURL) > 7 { // len("http://") + host = c.baseURL[7:] + } + } + c.baseURL = fmt.Sprintf("http://%s:%d", host, port) + } +} + +// WithToken sets the Bearer token for authentication. +func WithToken(token string) Option { + return func(c *Client) { + c.token = token + } +} + +// WithTimeout sets the HTTP client timeout. +func WithTimeout(timeout time.Duration) Option { + return func(c *Client) { + c.httpClient.Timeout = timeout + } +} + +// New creates a new API client with the given options. +func New(opts ...Option) *Client { + c := &Client{ + baseURL: "http://localhost:8080", + httpClient: &http.Client{ + Timeout: 30 * time.Second, + }, + } + for _, opt := range opts { + opt(c) + } + return c +} + +// BaseURL returns the configured base URL. +func (c *Client) BaseURL() string { + return c.baseURL +} + +// doRequest performs an HTTP request and returns the response body. +func (c *Client) doRequest(ctx context.Context, method, path string) ([]byte, error) { + url := c.baseURL + path + + req, err := http.NewRequestWithContext(ctx, method, url, nil) + if err != nil { + return nil, fmt.Errorf("create request: %w", err) + } + + req.Header.Set("Accept", "application/json") + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("request failed: %w", err) + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read response: %w", err) + } + + if resp.StatusCode >= 400 { + var errResp ErrorResponse + if json.Unmarshal(body, &errResp) == nil && errResp.Error != "" { + return nil, &APIError{ + StatusCode: resp.StatusCode, + Message: errResp.Error, + Details: errResp.Details, + } + } + return nil, &APIError{ + StatusCode: resp.StatusCode, + Message: http.StatusText(resp.StatusCode), + } + } + + return body, nil +} + +// Get performs a GET request and decodes the JSON response into v. +func (c *Client) Get(ctx context.Context, path string, v interface{}) error { + body, err := c.doRequest(ctx, http.MethodGet, path) + if err != nil { + return err + } + if v != nil { + if err := json.Unmarshal(body, v); err != nil { + return fmt.Errorf("decode response: %w", err) + } + } + return nil +} + +// GetRaw performs a GET request and returns the raw response body. +func (c *Client) GetRaw(ctx context.Context, path string) ([]byte, error) { + return c.doRequest(ctx, http.MethodGet, path) +} + +// Post performs a POST request with JSON body and decodes the response into v. +func (c *Client) Post(ctx context.Context, path string, body interface{}, v interface{}) error { + respBody, err := c.doRequestWithBody(ctx, http.MethodPost, path, body) + if err != nil { + return err + } + if v != nil { + if err := json.Unmarshal(respBody, v); err != nil { + return fmt.Errorf("decode response: %w", err) + } + } + return nil +} + +// Delete performs a DELETE request and decodes the response into v. +func (c *Client) Delete(ctx context.Context, path string, v interface{}) error { + respBody, err := c.doRequest(ctx, http.MethodDelete, path) + if err != nil { + return err + } + if v != nil { + if err := json.Unmarshal(respBody, v); err != nil { + return fmt.Errorf("decode response: %w", err) + } + } + return nil +} + +// doRequestWithBody performs an HTTP request with a JSON body. +func (c *Client) doRequestWithBody(ctx context.Context, method, path string, body interface{}) ([]byte, error) { + url := c.baseURL + path + + var reqBody io.Reader + if body != nil { + data, err := json.Marshal(body) + if err != nil { + return nil, fmt.Errorf("encode request body: %w", err) + } + reqBody = bytes.NewReader(data) + } + + req, err := http.NewRequestWithContext(ctx, method, url, reqBody) + if err != nil { + return nil, fmt.Errorf("create request: %w", err) + } + + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + + resp, err := c.httpClient.Do(req) + if err != nil { + return nil, fmt.Errorf("request failed: %w", err) + } + defer resp.Body.Close() + + respData, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read response: %w", err) + } + + if resp.StatusCode >= 400 { + var errResp ErrorResponse + if json.Unmarshal(respData, &errResp) == nil && errResp.Error != "" { + return nil, &APIError{ + StatusCode: resp.StatusCode, + Message: errResp.Error, + Details: errResp.Details, + } + } + return nil, &APIError{ + StatusCode: resp.StatusCode, + Message: http.StatusText(resp.StatusCode), + } + } + + return respData, nil +} + +// ErrorResponse represents an API error response. +type ErrorResponse struct { + Error string `json:"error"` + Code int `json:"code"` + Details string `json:"details,omitempty"` +} + +// APIError represents an error returned by the API. +type APIError struct { + StatusCode int + Message string + Details string +} + +func (e *APIError) Error() string { + if e.Details != "" { + return fmt.Sprintf("%s: %s", e.Message, e.Details) + } + return e.Message +} + +// IsNotFound returns true if the error is a 404 Not Found error. +func (e *APIError) IsNotFound() bool { + return e.StatusCode == http.StatusNotFound +} + +// IsUnauthorized returns true if the error is a 401 Unauthorized error. +func (e *APIError) IsUnauthorized() bool { + return e.StatusCode == http.StatusUnauthorized +} + +// IsServerError returns true if the error is a 5xx server error. +func (e *APIError) IsServerError() bool { + return e.StatusCode >= 500 +} diff --git a/cmd/gfsctl/client/types.go b/cmd/gfsctl/client/types.go new file mode 100644 index 00000000..2948ddc6 --- /dev/null +++ b/cmd/gfsctl/client/types.go @@ -0,0 +1,271 @@ +package client + +// HealthStatus represents the overall health state. +type HealthStatus string + +const ( + HealthStatusOK HealthStatus = "ok" + HealthStatusDegraded HealthStatus = "degraded" + HealthStatusUnhealthy HealthStatus = "unhealthy" +) + +// ComponentHealth represents the health of a single component. +type ComponentHealth struct { + Status HealthStatus `json:"status"` + Message string `json:"message,omitempty"` +} + +// HealthResponse is returned by GET /health. +type HealthResponse struct { + Status HealthStatus `json:"status"` + Checks map[string]ComponentHealth `json:"checks,omitempty"` +} + +// MountState represents the current mount state. +type MountState string + +const ( + MountStateUnmounted MountState = "unmounted" + MountStateMounting MountState = "mounting" + MountStateMounted MountState = "mounted" + MountStateUnmounting MountState = "unmounting" + MountStateError MountState = "error" +) + +// CapacityInfo provides storage capacity information. +type CapacityInfo struct { + TotalBytes uint64 `json:"total_bytes"` + UsedBytes uint64 `json:"used_bytes"` + FreeBytes uint64 `json:"free_bytes"` + UsedPercent float64 `json:"used_percent"` + TotalBlocks uint64 `json:"total_blocks"` + UsedBlocks uint64 `json:"used_blocks"` + FreeBlocks uint64 `json:"free_blocks"` + BlockSizeBytes uint64 `json:"block_size_bytes"` +} + +// ClusterInfo provides cluster membership information. +type ClusterInfo struct { + NodeID string `json:"node_id,omitempty"` + PeerCount int `json:"peer_count"` + Peers []string `json:"peers,omitempty"` + IsLeader bool `json:"is_leader,omitempty"` + LeaderID string `json:"leader_id,omitempty"` + ClusterState string `json:"cluster_state,omitempty"` +} + +// StatusResponse is returned by GET /api/v1/status. +type StatusResponse struct { + Status string `json:"status"` + Version string `json:"version"` + GitCommit string `json:"git_commit,omitempty"` + BuildTime string `json:"build_time,omitempty"` + GoVersion string `json:"go_version,omitempty"` + UptimeSeconds int64 `json:"uptime_seconds"` + MountPath string `json:"mount_path,omitempty"` + DevicePath string `json:"device_path,omitempty"` + MountState MountState `json:"mount_state,omitempty"` + ReadOnly bool `json:"read_only,omitempty"` + Capacity *CapacityInfo `json:"capacity,omitempty"` + Cluster *ClusterInfo `json:"cluster,omitempty"` +} + +// CacheHitRateInfo contains hit rate metrics for a cache type. +type CacheHitRateInfo struct { + Size int `json:"size"` + Hits uint64 `json:"hits"` + Misses uint64 `json:"misses"` + HitRate float64 `json:"hit_rate"` +} + +// CacheStatsResponse is returned by GET /api/v1/stats/cache. +type CacheStatsResponse struct { + InodeCache CacheHitRateInfo `json:"inode_cache"` + ExtentCache CacheHitRateInfo `json:"extent_cache"` + NegativeCache CacheHitRateInfo `json:"negative_cache"` + LockHintCache CacheHitRateInfo `json:"lock_hint_cache,omitempty"` +} + +// JournalStatsResponse is returned by GET /api/v1/stats/journal. +type JournalStatsResponse struct { + State string `json:"state"` + HeadOffset uint32 `json:"head_offset"` + TailOffset uint32 `json:"tail_offset"` + AvailableSpace uint32 `json:"available_space"` + ActiveTxnCount int `json:"active_txn_count"` + CommitCount uint64 `json:"commit_count"` + BytesWritten uint64 `json:"bytes_written"` + LastCheckpointSeq uint64 `json:"last_checkpoint_seq"` + BatchSyncCount uint64 `json:"batch_sync_count"` +} + +// TrimStatsResponse is returned by GET /api/v1/stats/trim. +type TrimStatsResponse struct { + TrimOperations uint64 `json:"trim_operations"` + TrimBytes uint64 `json:"trim_bytes"` + TrimBlocks uint64 `json:"trim_blocks"` + PendingTrimBlocks uint64 `json:"pending_trim_blocks,omitempty"` + LastTrimAt string `json:"last_trim_at,omitempty"` + TrimErrors uint64 `json:"trim_errors,omitempty"` + TrimEnabled bool `json:"trim_enabled"` + BatchSize int `json:"batch_size,omitempty"` +} + +// LockStatsResponse is returned by GET /api/v1/stats/lock. +type LockStatsResponse struct { + HintCacheHits uint64 `json:"hint_cache_hits"` + HintCacheMisses uint64 `json:"hint_cache_misses"` + HintCacheHitRate float64 `json:"hint_cache_hit_rate"` + ActiveLocks int `json:"active_locks,omitempty"` + PendingLocks int `json:"pending_locks,omitempty"` +} + +// SFBStatsResponse is returned by GET /api/v1/stats/sfb. +type SFBStatsResponse struct { + TotalBlocks uint64 `json:"total_blocks"` + AllocatedBlocks uint64 `json:"allocated_blocks"` + FreeBlocks uint64 `json:"free_blocks"` + AllocationPercent float64 `json:"allocation_percent"` + FragmentationRatio float64 `json:"fragmentation_ratio,omitempty"` + LargestFreeExtent uint64 `json:"largest_free_extent,omitempty"` + AllocationsTotal uint64 `json:"allocations_total"` + DeallocationsTotal uint64 `json:"deallocations_total"` + AllocationFailures uint64 `json:"allocation_failures,omitempty"` +} + +// ClusterPeerInfo contains information about a cluster peer node. +type ClusterPeerInfo struct { + NodeID string `json:"node_id"` + Address string `json:"address"` + State string `json:"state"` + LastSeen string `json:"last_seen,omitempty"` + Latency float64 `json:"latency_ms,omitempty"` +} + +// ClusterInfoResponse is returned by GET /api/v1/stats/cluster. +type ClusterInfoResponse struct { + NodeID string `json:"node_id"` + NodeAddress string `json:"node_address,omitempty"` + Role string `json:"role"` + State string `json:"state"` + ClusterSize int `json:"cluster_size"` + HealthyNodes int `json:"healthy_nodes"` + LeaderID string `json:"leader_id,omitempty"` + LastHeartbeatAt string `json:"last_heartbeat_at,omitempty"` + JoinedAt string `json:"joined_at,omitempty"` + Peers []ClusterPeerInfo `json:"peers,omitempty"` +} + +// ClusterNodeInfo provides detailed information about a cluster node. +type ClusterNodeInfo struct { + NodeID string `json:"node_id"` + Address string `json:"address"` + Role string `json:"role"` + State string `json:"state"` + LastHeartbeat string `json:"last_heartbeat,omitempty"` + JoinedAt string `json:"joined_at,omitempty"` + Version string `json:"version,omitempty"` + LatencyMs float64 `json:"latency_ms,omitempty"` + IsSelf bool `json:"is_self"` +} + +// ClusterNodesResponse is returned by GET /api/v1/cluster/nodes. +type ClusterNodesResponse struct { + ClusterID string `json:"cluster_id,omitempty"` + TotalNodes int `json:"total_nodes"` + HealthyNodes int `json:"healthy_nodes"` + LeaderID string `json:"leader_id,omitempty"` + Nodes []ClusterNodeInfo `json:"nodes"` +} + +// DistributedLockInfo provides information about an active distributed lock. +type DistributedLockInfo struct { + LockID string `json:"lock_id"` + Resource string `json:"resource"` + OwnerNodeID string `json:"owner_node_id"` + OwnerProcess string `json:"owner_process,omitempty"` + AcquiredAt string `json:"acquired_at"` + ExpiresAt string `json:"expires_at,omitempty"` + LockType string `json:"lock_type"` +} + +// ClusterLocksResponse is returned by GET /api/v1/cluster/locks. +type ClusterLocksResponse struct { + ActiveLocks int `json:"active_locks"` + PendingLocks int `json:"pending_locks"` + Locks []DistributedLockInfo `json:"locks"` +} + +// AllStatsResponse is returned by GET /api/v1/stats/all. +type AllStatsResponse struct { + CollectedAt string `json:"collected_at"` + Cache *CacheStatsResponse `json:"cache,omitempty"` + Journal *JournalStatsResponse `json:"journal,omitempty"` + Trim *TrimStatsResponse `json:"trim,omitempty"` + Lock *LockStatsResponse `json:"lock,omitempty"` + SFB *SFBStatsResponse `json:"sfb,omitempty"` + Cluster *ClusterInfoResponse `json:"cluster,omitempty"` +} + +// StatsOverviewResponse is returned by GET /api/v1/stats. +type StatsOverviewResponse struct { + Cache *CacheStatsResponse `json:"cache,omitempty"` + Journal *JournalStatsResponse `json:"journal,omitempty"` +} + +// SnapshotInfo provides information about a snapshot. +type SnapshotInfo struct { + ID string `json:"id"` + Name string `json:"name"` + CreatedAt string `json:"created_at"` + SizeBytes uint64 `json:"size_bytes"` + Status string `json:"status"` + Description string `json:"description,omitempty"` +} + +// SnapshotListResponse is returned by GET /api/v1/snapshots. +type SnapshotListResponse struct { + Snapshots []SnapshotInfo `json:"snapshots"` + Total int `json:"total"` +} + +// SnapshotCreateRequest is sent to POST /api/v1/snapshots. +type SnapshotCreateRequest struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` +} + +// SnapshotCreateResponse is returned by POST /api/v1/snapshots. +type SnapshotCreateResponse struct { + Snapshot SnapshotInfo `json:"snapshot"` + Message string `json:"message"` +} + +// SnapshotDeleteResponse is returned by DELETE /api/v1/snapshots/:id. +type SnapshotDeleteResponse struct { + ID string `json:"id"` + Message string `json:"message"` +} + +// AdminOperationResponse is returned by admin operations. +type AdminOperationResponse struct { + Operation string `json:"operation"` + Status string `json:"status"` + Message string `json:"message"` + Details string `json:"details,omitempty"` +} + +// FlushJournalRequest is sent to POST /api/v1/admin/flush-journal. +type FlushJournalRequest struct { + Force bool `json:"force,omitempty"` +} + +// ClearCacheRequest is sent to POST /api/v1/admin/clear-cache. +type ClearCacheRequest struct { + CacheType string `json:"cache_type,omitempty"` // all, inode, extent, negative +} + +// ForceTrimRequest is sent to POST /api/v1/admin/force-trim. +type ForceTrimRequest struct { + Force bool `json:"force,omitempty"` +} diff --git a/cmd/gfsctl/commands/admin.go b/cmd/gfsctl/commands/admin.go new file mode 100644 index 00000000..f221d2f3 --- /dev/null +++ b/cmd/gfsctl/commands/admin.go @@ -0,0 +1,227 @@ +package commands + +import ( + "context" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/supporttools/GoClusterFS/cmd/gfsctl/client" +) + +var adminCmd = &cobra.Command{ + Use: "admin [subcommand]", + Short: "Administrative commands", + Long: `Administrative operations for filesystem maintenance. + +Available subcommands: + flush-journal - Flush pending journal transactions to disk + clear-cache - Clear filesystem caches + force-trim - Force TRIM operation on the block device + +These commands require careful consideration and may impact performance +while running. Use --force to skip confirmation prompts. + +Examples: + gfsctl admin flush-journal # Flush journal with confirmation + gfsctl admin clear-cache # Clear all caches + gfsctl admin clear-cache --type inode # Clear only inode cache + gfsctl admin force-trim # Force TRIM operation`, + Args: cobra.MaximumNArgs(1), + RunE: runAdmin, +} + +var ( + adminForce bool + adminCacheType string +) + +func init() { + adminCmd.Flags().BoolVarP(&adminForce, "force", "f", false, "Skip confirmation prompts") + adminCmd.Flags().StringVar(&adminCacheType, "type", "all", "Cache type to clear (all, inode, extent, negative)") + rootCmd.AddCommand(adminCmd) +} + +func runAdmin(cmd *cobra.Command, args []string) error { + ctx := context.Background() + apiClient := GetClient() + f := NewFormatter(cmd.OutOrStdout(), GetOutputFormat()) + + if len(args) == 0 { + return fmt.Errorf("subcommand required (valid: flush-journal, clear-cache, force-trim)") + } + + subcmd := args[0] + + switch subcmd { + case "flush-journal": + return flushJournal(ctx, apiClient, f) + case "clear-cache": + return clearCache(ctx, apiClient, f) + case "force-trim": + return forceTrim(ctx, apiClient, f) + default: + return fmt.Errorf("unknown subcommand: %s (valid: flush-journal, clear-cache, force-trim)", subcmd) + } +} + +func flushJournal(ctx context.Context, c *client.Client, f *Formatter) error { + if !adminForce && !f.IsJSON() { + f.Printf("This will flush all pending journal transactions to disk.\n") + f.Printf("The operation may cause a brief pause in I/O operations.\n\n") + + if !confirmAction("Proceed with journal flush?") { + f.Printf("Cancelled.\n") + return nil + } + } + + if !f.IsJSON() { + f.Printf("Flushing journal...") + } + + req := &client.FlushJournalRequest{ + Force: adminForce, + } + + resp, err := c.AdminFlushJournal(ctx, req) + if err != nil { + if !f.IsJSON() { + f.Printf(" failed\n") + } + printError("failed to flush journal: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(resp) + } + + f.Printf(" done\n\n") + f.Header("Journal Flush Complete") + f.KeyValue("Operation", resp.Operation) + f.KeyValueColor("Status", resp.Status, statusColor(resp.Status)) + if resp.Message != "" { + f.KeyValue("Message", resp.Message) + } + if resp.Details != "" { + f.KeyValue("Details", resp.Details) + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func clearCache(ctx context.Context, c *client.Client, f *Formatter) error { + cacheDesc := adminCacheType + if cacheDesc == "all" { + cacheDesc = "all caches" + } else { + cacheDesc = adminCacheType + " cache" + } + + if !adminForce && !f.IsJSON() { + f.Printf("This will clear %s.\n", cacheDesc) + f.Printf("Cached data will need to be re-read from disk.\n\n") + + if !confirmAction("Proceed with cache clear?") { + f.Printf("Cancelled.\n") + return nil + } + } + + if !f.IsJSON() { + f.Printf("Clearing %s...", cacheDesc) + } + + req := &client.ClearCacheRequest{ + CacheType: adminCacheType, + } + + resp, err := c.AdminClearCache(ctx, req) + if err != nil { + if !f.IsJSON() { + f.Printf(" failed\n") + } + printError("failed to clear cache: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(resp) + } + + f.Printf(" done\n\n") + f.Header("Cache Clear Complete") + f.KeyValue("Operation", resp.Operation) + f.KeyValueColor("Status", resp.Status, statusColor(resp.Status)) + if resp.Message != "" { + f.KeyValue("Message", resp.Message) + } + if resp.Details != "" { + f.KeyValue("Details", resp.Details) + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func forceTrim(ctx context.Context, c *client.Client, f *Formatter) error { + if !adminForce && !f.IsJSON() { + f.Printf("This will force a TRIM operation on the underlying block device.\n") + f.Printf("This may take some time depending on the amount of free space.\n\n") + + if !confirmAction("Proceed with TRIM operation?") { + f.Printf("Cancelled.\n") + return nil + } + } + + if !f.IsJSON() { + f.Printf("Performing TRIM operation...") + } + + req := &client.ForceTrimRequest{ + Force: adminForce, + } + + resp, err := c.AdminForceTrim(ctx, req) + if err != nil { + if !f.IsJSON() { + f.Printf(" failed\n") + } + printError("failed to perform TRIM: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(resp) + } + + f.Printf(" done\n\n") + f.Header("TRIM Operation Complete") + f.KeyValue("Operation", resp.Operation) + f.KeyValueColor("Status", resp.Status, statusColor(resp.Status)) + if resp.Message != "" { + f.KeyValue("Message", resp.Message) + } + if resp.Details != "" { + f.KeyValue("Details", resp.Details) + } + + fmt.Fprintln(os.Stdout) + return nil +} + +// statusColor returns the color indicator for an operation status. +func statusColor(status string) string { + switch status { + case "success", "complete", "ok": + return "ok" + case "failed", "error": + return "error" + default: + return "warning" + } +} diff --git a/cmd/gfsctl/commands/cluster.go b/cmd/gfsctl/commands/cluster.go new file mode 100644 index 00000000..c82e7051 --- /dev/null +++ b/cmd/gfsctl/commands/cluster.go @@ -0,0 +1,202 @@ +package commands + +import ( + "context" + "fmt" + "os" + + "github.com/spf13/cobra" + + "github.com/supporttools/GoClusterFS/cmd/gfsctl/client" +) + +var clusterCmd = &cobra.Command{ + Use: "cluster [subcommand]", + Short: "Cluster management commands", + Long: `Manage and inspect cluster state. + +Available subcommands: + status - Show cluster status + nodes - List cluster nodes + locks - Show active distributed locks + +Examples: + gfsctl cluster status # Show cluster status + gfsctl cluster nodes # List all nodes + gfsctl cluster locks # Show distributed locks`, + Args: cobra.MaximumNArgs(1), + RunE: runCluster, +} + +func init() { + rootCmd.AddCommand(clusterCmd) +} + +func runCluster(cmd *cobra.Command, args []string) error { + ctx := context.Background() + apiClient := GetClient() + f := NewFormatter(cmd.OutOrStdout(), GetOutputFormat()) + + // Determine which subcommand + subcmd := "status" + if len(args) > 0 { + subcmd = args[0] + } + + switch subcmd { + case "status": + return showClusterStatus(ctx, apiClient, f) + case "nodes": + return showClusterNodes(ctx, apiClient, f) + case "locks": + return showClusterLocks(ctx, apiClient, f) + default: + return fmt.Errorf("unknown subcommand: %s (valid: status, nodes, locks)", subcmd) + } +} + +func showClusterStatus(ctx context.Context, c *client.Client, f *Formatter) error { + status, err := c.ClusterStatus(ctx) + if err != nil { + printError("failed to get cluster status: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(status) + } + + f.Header("Cluster Status") + + f.KeyValue("Node ID", status.NodeID) + if status.NodeAddress != "" { + f.KeyValue("Address", status.NodeAddress) + } + + roleColor := "follower" + if status.Role == "leader" { + roleColor = "leader" + } + f.KeyValueColor("Role", status.Role, roleColor) + + stateColor := "ok" + if status.State != "active" { + stateColor = "warning" + } + f.KeyValueColor("State", status.State, stateColor) + + f.KeyValue("Cluster Size", fmt.Sprintf("%d", status.ClusterSize)) + + healthColor := "ok" + if status.HealthyNodes < status.ClusterSize { + healthColor = "warning" + } + f.KeyValueColor("Healthy Nodes", fmt.Sprintf("%d/%d", status.HealthyNodes, status.ClusterSize), healthColor) + + if status.LeaderID != "" { + f.KeyValue("Leader ID", status.LeaderID) + } + if status.LastHeartbeatAt != "" { + f.KeyValue("Last Heartbeat", status.LastHeartbeatAt) + } + if status.JoinedAt != "" { + f.KeyValue("Joined At", status.JoinedAt) + } + + // Show peers if present + if len(status.Peers) > 0 { + f.Header("Peers") + table := f.NewTable("Node ID", "Address", "State", "Latency") + for _, peer := range status.Peers { + latency := "-" + if peer.Latency > 0 { + latency = fmt.Sprintf("%.1fms", peer.Latency) + } + table.AddRow(peer.NodeID, peer.Address, peer.State, latency) + } + table.Render() + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func showClusterNodes(ctx context.Context, c *client.Client, f *Formatter) error { + nodes, err := c.ClusterNodes(ctx) + if err != nil { + printError("failed to get cluster nodes: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(nodes) + } + + f.Header("Cluster Nodes") + + if nodes.ClusterID != "" { + f.KeyValue("Cluster ID", nodes.ClusterID) + } + f.KeyValue("Total Nodes", fmt.Sprintf("%d", nodes.TotalNodes)) + + healthColor := "ok" + if nodes.HealthyNodes < nodes.TotalNodes { + healthColor = "warning" + } + f.KeyValueColor("Healthy Nodes", fmt.Sprintf("%d", nodes.HealthyNodes), healthColor) + + if nodes.LeaderID != "" { + f.KeyValue("Leader", nodes.LeaderID) + } + + if len(nodes.Nodes) > 0 { + f.Printf("\n") + table := f.NewTable("Node ID", "Address", "Role", "State", "Latency", "Self") + for _, node := range nodes.Nodes { + latency := "-" + if node.LatencyMs > 0 { + latency = fmt.Sprintf("%.1fms", node.LatencyMs) + } + self := "" + if node.IsSelf { + self = "*" + } + table.AddRow(node.NodeID, node.Address, node.Role, node.State, latency, self) + } + table.Render() + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func showClusterLocks(ctx context.Context, c *client.Client, f *Formatter) error { + locks, err := c.ClusterLocks(ctx) + if err != nil { + printError("failed to get cluster locks: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(locks) + } + + f.Header("Distributed Locks") + + f.KeyValue("Active Locks", fmt.Sprintf("%d", locks.ActiveLocks)) + f.KeyValue("Pending Locks", fmt.Sprintf("%d", locks.PendingLocks)) + + if len(locks.Locks) > 0 { + f.Printf("\n") + table := f.NewTable("Lock ID", "Resource", "Type", "Owner Node", "Acquired At") + for _, lock := range locks.Locks { + table.AddRow(lock.LockID, lock.Resource, lock.LockType, lock.OwnerNodeID, lock.AcquiredAt) + } + table.Render() + } else { + f.Printf("\n (no active locks)\n") + } + + fmt.Fprintln(os.Stdout) + return nil +} diff --git a/cmd/gfsctl/commands/completion.go b/cmd/gfsctl/commands/completion.go new file mode 100644 index 00000000..569b613a --- /dev/null +++ b/cmd/gfsctl/commands/completion.go @@ -0,0 +1,69 @@ +package commands + +import ( + "os" + + "github.com/spf13/cobra" +) + +var completionCmd = &cobra.Command{ + Use: "completion [shell]", + Short: "Generate shell completion scripts", + Long: `Generate shell completion scripts for gfsctl. + +Supported shells: bash, zsh, fish, powershell + +To load completions: + +Bash: + # Linux + $ gfsctl completion bash > /etc/bash_completion.d/gfsctl + + # macOS (Homebrew) + $ gfsctl completion bash > $(brew --prefix)/etc/bash_completion.d/gfsctl + + # Current session only + $ source <(gfsctl completion bash) + +Zsh: + # If shell completion is not already enabled in your environment, + # you will need to enable it. You can execute the following once: + $ echo "autoload -U compinit; compinit" >> ~/.zshrc + + # To load completions for each session, execute once: + $ gfsctl completion zsh > "${fpath[1]}/_gfsctl" + + # You will need to start a new shell for this setup to take effect. + +Fish: + $ gfsctl completion fish > ~/.config/fish/completions/gfsctl.fish + + # Or for system-wide installation: + $ gfsctl completion fish > /usr/share/fish/vendor_completions.d/gfsctl.fish + +PowerShell: + PS> gfsctl completion powershell | Out-String | Invoke-Expression + + # To load completions for every new session, add the output of the above + # command to your PowerShell profile.`, + DisableFlagsInUseLine: true, + ValidArgs: []string{"bash", "zsh", "fish", "powershell"}, + Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs), + RunE: func(cmd *cobra.Command, args []string) error { + switch args[0] { + case "bash": + return rootCmd.GenBashCompletion(os.Stdout) + case "zsh": + return rootCmd.GenZshCompletion(os.Stdout) + case "fish": + return rootCmd.GenFishCompletion(os.Stdout, true) + case "powershell": + return rootCmd.GenPowerShellCompletionWithDesc(os.Stdout) + } + return nil + }, +} + +func init() { + rootCmd.AddCommand(completionCmd) +} diff --git a/cmd/gfsctl/commands/config.go b/cmd/gfsctl/commands/config.go new file mode 100644 index 00000000..d55533d3 --- /dev/null +++ b/cmd/gfsctl/commands/config.go @@ -0,0 +1,131 @@ +package commands + +import ( + "fmt" + "os" + "path/filepath" + "time" + + "gopkg.in/yaml.v2" +) + +// AppConfig represents the configuration file structure. +type AppConfig struct { + // Host is the default API server host. + Host string `yaml:"host,omitempty"` + + // Port is the default API server port. + Port int `yaml:"port,omitempty"` + + // Token is the default Bearer token for authentication. + Token string `yaml:"token,omitempty"` + + // Output is the default output format (text, json). + Output string `yaml:"output,omitempty"` + + // Timeout is the default request timeout. + Timeout time.Duration `yaml:"timeout,omitempty"` +} + +// configDir returns the configuration directory path. +// Uses XDG_CONFIG_HOME if set, otherwise ~/.config/gfsctl +func configDir() string { + if xdg := os.Getenv("XDG_CONFIG_HOME"); xdg != "" { + return filepath.Join(xdg, "gfsctl") + } + home, err := os.UserHomeDir() + if err != nil { + return "" + } + return filepath.Join(home, ".config", "gfsctl") +} + +// configPath returns the full path to the config file. +func configPath() string { + dir := configDir() + if dir == "" { + return "" + } + return filepath.Join(dir, "config.yaml") +} + +// loadConfig loads configuration from the config file. +// Returns an empty config if the file doesn't exist. +func loadConfig() (*AppConfig, error) { + path := configPath() + if path == "" { + return &AppConfig{}, nil + } + + data, err := os.ReadFile(path) + if err != nil { + if os.IsNotExist(err) { + return &AppConfig{}, nil + } + return nil, fmt.Errorf("read config: %w", err) + } + + var cfg AppConfig + if err := yaml.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("parse config: %w", err) + } + + return &cfg, nil +} + +// initConfig loads the config file and applies values to global flags. +// Environment variables and command-line flags take precedence. +func initConfig() { + cfg, err := loadConfig() + if err != nil { + // Silently ignore config errors - CLI should still work + return + } + + // Apply config values only if not already set by env/flag + // Note: cobra doesn't easily support checking if a flag was set, + // so we check if values are at their defaults + + if cfg.Host != "" && cfgHost == "localhost" && os.Getenv("GFSCTL_HOST") == "" { + cfgHost = cfg.Host + } + + if cfg.Port != 0 && cfgPort == 8080 && os.Getenv("GFSCTL_PORT") == "" { + cfgPort = cfg.Port + } + + if cfg.Token != "" && cfgToken == "" && os.Getenv("GFSCTL_TOKEN") == "" { + cfgToken = cfg.Token + } + + if cfg.Output != "" && cfgOutput == "text" && os.Getenv("GFSCTL_OUTPUT") == "" { + cfgOutput = cfg.Output + } + + if cfg.Timeout != 0 && cfgTimeout == 30*time.Second && os.Getenv("GFSCTL_TIMEOUT") == "" { + cfgTimeout = cfg.Timeout + } +} + +// GenerateSampleConfig returns a sample configuration file content. +func GenerateSampleConfig() string { + return `# gfsctl configuration file +# Place this file at ~/.config/gfsctl/config.yaml +# or set XDG_CONFIG_HOME and use $XDG_CONFIG_HOME/gfsctl/config.yaml + +# API server host (default: localhost) +# host: localhost + +# API server port (default: 8080) +# port: 8080 + +# Bearer token for authentication (default: none) +# token: your-secret-token + +# Output format: text or json (default: text) +# output: text + +# Request timeout (default: 30s) +# timeout: 30s +` +} diff --git a/cmd/gfsctl/commands/config_cmd.go b/cmd/gfsctl/commands/config_cmd.go new file mode 100644 index 00000000..7917210a --- /dev/null +++ b/cmd/gfsctl/commands/config_cmd.go @@ -0,0 +1,146 @@ +package commands + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/spf13/cobra" +) + +var configCmd = &cobra.Command{ + Use: "config [subcommand]", + Short: "Manage gfsctl configuration", + Long: `Manage gfsctl configuration file. + +The configuration file is located at: + $XDG_CONFIG_HOME/gfsctl/config.yaml + or ~/.config/gfsctl/config.yaml + +Subcommands: + path - Show configuration file path + show - Show current configuration values + init - Create a sample configuration file + +Configuration values can be overridden by: + 1. Environment variables (GFSCTL_HOST, GFSCTL_TOKEN, etc.) + 2. Command-line flags (--host, --token, etc.) + +Examples: + gfsctl config path # Show config file location + gfsctl config show # Show current configuration + gfsctl config init # Create sample config file`, + Args: cobra.MaximumNArgs(1), + RunE: runConfig, +} + +func init() { + rootCmd.AddCommand(configCmd) +} + +func runConfig(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + return cmd.Help() + } + + subcmd := args[0] + + switch subcmd { + case "path": + return showConfigPath(cmd) + case "show": + return showCurrentConfig(cmd) + case "init": + return initConfigFile(cmd) + default: + return fmt.Errorf("unknown subcommand: %s (valid: path, show, init)", subcmd) + } +} + +func showConfigPath(cmd *cobra.Command) error { + path := configPath() + if path == "" { + fmt.Fprintln(cmd.OutOrStdout(), "Unable to determine config path") + return nil + } + + fmt.Fprintln(cmd.OutOrStdout(), path) + + // Check if file exists + if _, err := os.Stat(path); os.IsNotExist(err) { + fmt.Fprintln(cmd.OutOrStdout(), "(file does not exist)") + } + + return nil +} + +func showCurrentConfig(cmd *cobra.Command) error { + f := NewFormatter(cmd.OutOrStdout(), GetOutputFormat()) + + if f.IsJSON() { + return f.JSON(map[string]interface{}{ + "config_path": configPath(), + "host": cfgHost, + "port": cfgPort, + "token": maskToken(cfgToken), + "output": cfgOutput, + "timeout": cfgTimeout.String(), + }) + } + + f.Header("Current Configuration") + f.KeyValue("Config File", configPath()) + f.Printf("\n") + + // Show effective values with source indication + f.KeyValue("Host", cfgHost) + f.KeyValue("Port", fmt.Sprintf("%d", cfgPort)) + f.KeyValue("Token", maskToken(cfgToken)) + f.KeyValue("Output", cfgOutput) + f.KeyValue("Timeout", cfgTimeout.String()) + + fmt.Fprintln(os.Stdout) + return nil +} + +func initConfigFile(cmd *cobra.Command) error { + path := configPath() + if path == "" { + printError("unable to determine config directory") + return fmt.Errorf("unable to determine config directory") + } + + // Check if file already exists + if _, err := os.Stat(path); err == nil { + printError("config file already exists: %s", path) + return fmt.Errorf("config file already exists: %s", path) + } + + // Create directory if needed + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0755); err != nil { + printError("failed to create config directory: %v", err) + return err + } + + // Write sample config + content := GenerateSampleConfig() + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + printError("failed to write config file: %v", err) + return err + } + + fmt.Fprintf(cmd.OutOrStdout(), "Created config file: %s\n", path) + return nil +} + +// maskToken masks a token for display, showing only first/last 4 chars. +func maskToken(token string) string { + if token == "" { + return "(not set)" + } + if len(token) <= 8 { + return "****" + } + return token[:4] + "..." + token[len(token)-4:] +} diff --git a/cmd/gfsctl/commands/health.go b/cmd/gfsctl/commands/health.go new file mode 100644 index 00000000..baedf590 --- /dev/null +++ b/cmd/gfsctl/commands/health.go @@ -0,0 +1,70 @@ +package commands + +import ( + "context" + "fmt" + "os" + + "github.com/spf13/cobra" +) + +var healthCmd = &cobra.Command{ + Use: "health", + Short: "Check filesystem health", + Long: `Check the health status of the filesystem and its components. +Returns exit code 0 if healthy, 1 if unhealthy. + +Examples: + gfsctl health # Check health in text format + gfsctl health -o json # Check health in JSON format`, + RunE: runHealth, +} + +func init() { + rootCmd.AddCommand(healthCmd) +} + +func runHealth(cmd *cobra.Command, args []string) error { + ctx := context.Background() + client := GetClient() + + health, err := client.Health(ctx) + if err != nil { + printError("failed to get health: %v", err) + return err + } + + f := NewFormatter(cmd.OutOrStdout(), GetOutputFormat()) + + if f.IsJSON() { + return f.JSON(health) + } + + // Text output + f.Header("Health Status") + + statusColor := string(health.Status) + f.KeyValueColor("Overall", string(health.Status), statusColor) + + // Component checks + if len(health.Checks) > 0 { + f.Header("Component Checks") + for name, check := range health.Checks { + checkColor := string(check.Status) + msg := string(check.Status) + if check.Message != "" { + msg = fmt.Sprintf("%s - %s", check.Status, check.Message) + } + f.KeyValueColor(name, msg, checkColor) + } + } + + fmt.Fprintln(os.Stdout) + + // Return error if unhealthy (for scripting) + if health.Status == "unhealthy" { + return fmt.Errorf("filesystem is unhealthy") + } + + return nil +} diff --git a/cmd/gfsctl/commands/output.go b/cmd/gfsctl/commands/output.go new file mode 100644 index 00000000..e1e9c81c --- /dev/null +++ b/cmd/gfsctl/commands/output.go @@ -0,0 +1,209 @@ +package commands + +import ( + "encoding/json" + "fmt" + "io" + "strings" +) + +// Formatter provides output formatting utilities. +type Formatter struct { + w io.Writer + format string +} + +// NewFormatter creates a new formatter with the given writer and format. +func NewFormatter(w io.Writer, format string) *Formatter { + return &Formatter{w: w, format: format} +} + +// IsJSON returns true if the output format is JSON. +func (f *Formatter) IsJSON() bool { + return f.format == "json" +} + +// JSON outputs the value as formatted JSON. +func (f *Formatter) JSON(v interface{}) error { + enc := json.NewEncoder(f.w) + enc.SetIndent("", " ") + return enc.Encode(v) +} + +// Print prints a simple message. +func (f *Formatter) Print(format string, args ...interface{}) { + fmt.Fprintf(f.w, format, args...) +} + +// Println prints a message with a newline. +func (f *Formatter) Println(args ...interface{}) { + fmt.Fprintln(f.w, args...) +} + +// Printf prints a formatted message. +func (f *Formatter) Printf(format string, args ...interface{}) { + fmt.Fprintf(f.w, format, args...) +} + +// Header prints a section header. +func (f *Formatter) Header(title string) { + fmt.Fprintf(f.w, "\n%s\n", title) + fmt.Fprintf(f.w, "%s\n", strings.Repeat("─", len(title))) +} + +// KeyValue prints a key-value pair with proper alignment. +func (f *Formatter) KeyValue(key string, value interface{}) { + fmt.Fprintf(f.w, " %-20s %v\n", key+":", value) +} + +// KeyValueColor prints a key-value pair with color for status values. +func (f *Formatter) KeyValueColor(key string, value string, status string) { + colored := colorize(value, status) + fmt.Fprintf(f.w, " %-20s %s\n", key+":", colored) +} + +// Table prints a simple table with headers and rows. +type Table struct { + f *Formatter + headers []string + widths []int + rows [][]string +} + +// NewTable creates a new table with the given headers. +func (f *Formatter) NewTable(headers ...string) *Table { + widths := make([]int, len(headers)) + for i, h := range headers { + widths[i] = len(h) + } + return &Table{ + f: f, + headers: headers, + widths: widths, + } +} + +// AddRow adds a row to the table. +func (t *Table) AddRow(values ...string) { + // Pad values if fewer than headers + for len(values) < len(t.headers) { + values = append(values, "") + } + // Truncate if more than headers + if len(values) > len(t.headers) { + values = values[:len(t.headers)] + } + // Update widths + for i, v := range values { + if len(v) > t.widths[i] { + t.widths[i] = len(v) + } + } + t.rows = append(t.rows, values) +} + +// Render prints the table. +func (t *Table) Render() { + if len(t.rows) == 0 { + fmt.Fprintln(t.f.w, " (no data)") + return + } + + // Print headers + fmt.Fprint(t.f.w, " ") + for i, h := range t.headers { + fmt.Fprintf(t.f.w, "%-*s ", t.widths[i], h) + } + fmt.Fprintln(t.f.w) + + // Print separator + fmt.Fprint(t.f.w, " ") + for i := range t.headers { + fmt.Fprintf(t.f.w, "%s ", strings.Repeat("─", t.widths[i])) + } + fmt.Fprintln(t.f.w) + + // Print rows + for _, row := range t.rows { + fmt.Fprint(t.f.w, " ") + for i, v := range row { + fmt.Fprintf(t.f.w, "%-*s ", t.widths[i], v) + } + fmt.Fprintln(t.f.w) + } +} + +// ANSI color codes +const ( + colorReset = "\033[0m" + colorRed = "\033[31m" + colorGreen = "\033[32m" + colorYellow = "\033[33m" + colorBlue = "\033[34m" + colorCyan = "\033[36m" +) + +// colorize returns a colored string based on the status. +func colorize(value, status string) string { + switch status { + case "ok", "healthy", "active", "leader", "mounted", "open": + return colorGreen + value + colorReset + case "degraded", "warning", "follower": + return colorYellow + value + colorReset + case "unhealthy", "error", "failed", "closed": + return colorRed + value + colorReset + case "info": + return colorCyan + value + colorReset + default: + return value + } +} + +// FormatBytes formats bytes in human-readable form. +func FormatBytes(bytes uint64) string { + const ( + KB = 1024 + MB = KB * 1024 + GB = MB * 1024 + TB = GB * 1024 + ) + + switch { + case bytes >= TB: + return fmt.Sprintf("%.2f TB", float64(bytes)/TB) + case bytes >= GB: + return fmt.Sprintf("%.2f GB", float64(bytes)/GB) + case bytes >= MB: + return fmt.Sprintf("%.2f MB", float64(bytes)/MB) + case bytes >= KB: + return fmt.Sprintf("%.2f KB", float64(bytes)/KB) + default: + return fmt.Sprintf("%d B", bytes) + } +} + +// FormatDuration formats seconds in human-readable form. +func FormatDuration(seconds int64) string { + if seconds < 60 { + return fmt.Sprintf("%ds", seconds) + } + if seconds < 3600 { + return fmt.Sprintf("%dm %ds", seconds/60, seconds%60) + } + if seconds < 86400 { + hours := seconds / 3600 + mins := (seconds % 3600) / 60 + return fmt.Sprintf("%dh %dm", hours, mins) + } + days := seconds / 86400 + hours := (seconds % 86400) / 3600 + return fmt.Sprintf("%dd %dh", days, hours) +} + +// FormatPercent formats a percentage with appropriate precision. +func FormatPercent(pct float64) string { + if pct < 10 { + return fmt.Sprintf("%.2f%%", pct) + } + return fmt.Sprintf("%.1f%%", pct) +} diff --git a/cmd/gfsctl/commands/root.go b/cmd/gfsctl/commands/root.go new file mode 100644 index 00000000..ba1b14c3 --- /dev/null +++ b/cmd/gfsctl/commands/root.go @@ -0,0 +1,102 @@ +// Package commands implements the gfsctl CLI commands. +package commands + +import ( + "fmt" + "os" + "time" + + "github.com/spf13/cobra" + + "github.com/supporttools/GoClusterFS/cmd/gfsctl/client" +) + +var ( + // Global flags + cfgHost string + cfgPort int + cfgToken string + cfgTimeout time.Duration + cfgOutput string + + // API client (initialized in PersistentPreRunE) + apiClient *client.Client +) + +// rootCmd is the base command when called without subcommands. +var rootCmd = &cobra.Command{ + Use: "gfsctl", + Short: "GoClusterFS management CLI", + Long: `gfsctl is the management CLI for GoClusterFS. + +It communicates with a running GoClusterFS mount via its HTTP API +to query status, statistics, and perform administrative operations. + +Examples: + gfsctl status # Show filesystem status + gfsctl health # Check health status + gfsctl stats cache # Show cache statistics + gfsctl cluster nodes # List cluster nodes + gfsctl --host 10.0.0.1 status # Connect to remote host`, + SilenceUsage: true, + SilenceErrors: true, + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + // Skip client initialization for version command + if cmd.Name() == "version" { + return nil + } + + // Create API client with configured options + apiClient = client.New( + client.WithHost(cfgHost), + client.WithPort(cfgPort), + client.WithToken(cfgToken), + client.WithTimeout(cfgTimeout), + ) + return nil + }, +} + +// Execute runs the root command. +func Execute() error { + return rootCmd.Execute() +} + +func init() { + // Global flags available to all commands + rootCmd.PersistentFlags().StringVar(&cfgHost, "host", "localhost", "API server host") + rootCmd.PersistentFlags().IntVar(&cfgPort, "port", 8080, "API server port") + rootCmd.PersistentFlags().StringVar(&cfgToken, "token", "", "Bearer token for authentication") + rootCmd.PersistentFlags().DurationVar(&cfgTimeout, "timeout", 30*time.Second, "Request timeout") + rootCmd.PersistentFlags().StringVarP(&cfgOutput, "output", "o", "text", "Output format (text, json)") + + // Load configuration file (lowest priority) + initConfig() + + // Environment variable fallbacks (higher priority than config file) + if host := os.Getenv("GFSCTL_HOST"); host != "" { + cfgHost = host + } + if token := os.Getenv("GFSCTL_TOKEN"); token != "" { + cfgToken = token + } + if output := os.Getenv("GFSCTL_OUTPUT"); output != "" { + cfgOutput = output + } +} + +// GetClient returns the initialized API client. +// Commands should call this after PersistentPreRunE has executed. +func GetClient() *client.Client { + return apiClient +} + +// GetOutputFormat returns the configured output format. +func GetOutputFormat() string { + return cfgOutput +} + +// printError prints an error message to stderr. +func printError(format string, args ...interface{}) { + fmt.Fprintf(os.Stderr, "Error: "+format+"\n", args...) +} diff --git a/cmd/gfsctl/commands/snapshot.go b/cmd/gfsctl/commands/snapshot.go new file mode 100644 index 00000000..94d83de5 --- /dev/null +++ b/cmd/gfsctl/commands/snapshot.go @@ -0,0 +1,243 @@ +package commands + +import ( + "bufio" + "context" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/supporttools/GoClusterFS/cmd/gfsctl/client" +) + +var snapshotCmd = &cobra.Command{ + Use: "snapshot [subcommand]", + Short: "Snapshot management commands", + Long: `Manage filesystem snapshots. + +Available subcommands: + list - List all snapshots + create - Create a new snapshot + delete - Delete a snapshot + info - Show snapshot details + +Examples: + gfsctl snapshot list # List all snapshots + gfsctl snapshot create mysnap # Create snapshot named "mysnap" + gfsctl snapshot delete snap-123 # Delete snapshot by ID + gfsctl snapshot info snap-123 # Show snapshot details`, + Args: cobra.MaximumNArgs(2), + RunE: runSnapshot, +} + +var ( + snapshotDescription string + snapshotForce bool +) + +func init() { + snapshotCmd.Flags().StringVarP(&snapshotDescription, "description", "d", "", "Snapshot description (for create)") + snapshotCmd.Flags().BoolVarP(&snapshotForce, "force", "f", false, "Skip confirmation prompts") + rootCmd.AddCommand(snapshotCmd) +} + +func runSnapshot(cmd *cobra.Command, args []string) error { + ctx := context.Background() + apiClient := GetClient() + f := NewFormatter(cmd.OutOrStdout(), GetOutputFormat()) + + // Determine which subcommand + subcmd := "list" + if len(args) > 0 { + subcmd = args[0] + } + + switch subcmd { + case "list": + return listSnapshots(ctx, apiClient, f) + case "create": + if len(args) < 2 { + return fmt.Errorf("snapshot name required: gfsctl snapshot create ") + } + return createSnapshot(ctx, apiClient, f, args[1]) + case "delete": + if len(args) < 2 { + return fmt.Errorf("snapshot ID required: gfsctl snapshot delete ") + } + return deleteSnapshot(ctx, apiClient, f, args[1]) + case "info": + if len(args) < 2 { + return fmt.Errorf("snapshot ID required: gfsctl snapshot info ") + } + return showSnapshotInfo(ctx, apiClient, f, args[1]) + default: + return fmt.Errorf("unknown subcommand: %s (valid: list, create, delete, info)", subcmd) + } +} + +func listSnapshots(ctx context.Context, c *client.Client, f *Formatter) error { + resp, err := c.SnapshotList(ctx) + if err != nil { + printError("failed to list snapshots: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(resp) + } + + f.Header("Snapshots") + f.KeyValue("Total", fmt.Sprintf("%d", resp.Total)) + + if len(resp.Snapshots) > 0 { + f.Printf("\n") + table := f.NewTable("ID", "Name", "Created", "Size", "Status") + for _, snap := range resp.Snapshots { + table.AddRow(snap.ID, snap.Name, snap.CreatedAt, FormatBytes(snap.SizeBytes), snap.Status) + } + table.Render() + } else { + f.Printf("\n (no snapshots)\n") + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func createSnapshot(ctx context.Context, c *client.Client, f *Formatter, name string) error { + // Show what we're about to do + if !snapshotForce && !f.IsJSON() { + f.Printf("Creating snapshot: %s\n", name) + if snapshotDescription != "" { + f.Printf("Description: %s\n", snapshotDescription) + } + if !confirmAction("Create this snapshot?") { + f.Printf("Cancelled.\n") + return nil + } + } + + req := &client.SnapshotCreateRequest{ + Name: name, + Description: snapshotDescription, + } + + // Show progress + if !f.IsJSON() { + f.Printf("Creating snapshot...") + } + + resp, err := c.SnapshotCreate(ctx, req) + if err != nil { + if !f.IsJSON() { + f.Printf(" failed\n") + } + printError("failed to create snapshot: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(resp) + } + + f.Printf(" done\n\n") + f.Header("Snapshot Created") + f.KeyValue("ID", resp.Snapshot.ID) + f.KeyValue("Name", resp.Snapshot.Name) + f.KeyValue("Created At", resp.Snapshot.CreatedAt) + f.KeyValueColor("Status", resp.Snapshot.Status, "ok") + + fmt.Fprintln(os.Stdout) + return nil +} + +func deleteSnapshot(ctx context.Context, c *client.Client, f *Formatter, id string) error { + // Get snapshot info first for confirmation + if !snapshotForce && !f.IsJSON() { + info, err := c.SnapshotInfo(ctx, id) + if err != nil { + printError("failed to get snapshot info: %v", err) + return err + } + + f.Printf("Snapshot to delete:\n") + f.KeyValue("ID", info.ID) + f.KeyValue("Name", info.Name) + f.KeyValue("Size", FormatBytes(info.SizeBytes)) + f.Printf("\n") + + if !confirmAction("Delete this snapshot? This cannot be undone.") { + f.Printf("Cancelled.\n") + return nil + } + } + + // Show progress + if !f.IsJSON() { + f.Printf("Deleting snapshot...") + } + + resp, err := c.SnapshotDelete(ctx, id) + if err != nil { + if !f.IsJSON() { + f.Printf(" failed\n") + } + printError("failed to delete snapshot: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(resp) + } + + f.Printf(" done\n") + f.Printf("Snapshot %s deleted.\n", resp.ID) + + fmt.Fprintln(os.Stdout) + return nil +} + +func showSnapshotInfo(ctx context.Context, c *client.Client, f *Formatter, id string) error { + info, err := c.SnapshotInfo(ctx, id) + if err != nil { + printError("failed to get snapshot info: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(info) + } + + f.Header("Snapshot Details") + f.KeyValue("ID", info.ID) + f.KeyValue("Name", info.Name) + f.KeyValue("Created At", info.CreatedAt) + f.KeyValue("Size", FormatBytes(info.SizeBytes)) + + statusColor := "ok" + if info.Status != "complete" && info.Status != "ready" { + statusColor = "warning" + } + f.KeyValueColor("Status", info.Status, statusColor) + + if info.Description != "" { + f.KeyValue("Description", info.Description) + } + + fmt.Fprintln(os.Stdout) + return nil +} + +// confirmAction prompts the user for confirmation. +func confirmAction(prompt string) bool { + reader := bufio.NewReader(os.Stdin) + fmt.Printf("%s [y/N]: ", prompt) + response, err := reader.ReadString('\n') + if err != nil { + return false + } + response = strings.TrimSpace(strings.ToLower(response)) + return response == "y" || response == "yes" +} diff --git a/cmd/gfsctl/commands/stats.go b/cmd/gfsctl/commands/stats.go new file mode 100644 index 00000000..01ffd15c --- /dev/null +++ b/cmd/gfsctl/commands/stats.go @@ -0,0 +1,376 @@ +package commands + +import ( + "context" + "fmt" + "os" + "time" + + "github.com/spf13/cobra" + + "github.com/supporttools/GoClusterFS/cmd/gfsctl/client" +) + +var ( + statsWatch bool + statsInterval time.Duration +) + +var statsCmd = &cobra.Command{ + Use: "stats [component]", + Short: "Show component statistics", + Long: `Display statistics for filesystem components. + +Available components: + cache - Cache hit/miss statistics + journal - Journal transaction statistics + trim - TRIM operation statistics + lock - Lock contention statistics + sfb - Sub-File Block allocation statistics + all - All statistics combined + +If no component is specified, shows an overview of key stats. + +Examples: + gfsctl stats # Show overview + gfsctl stats cache # Show cache stats + gfsctl stats all # Show all stats + gfsctl stats -o json # Show overview in JSON + gfsctl stats cache -w # Watch cache stats with 2s refresh + gfsctl stats all -w -i 5s # Watch all stats with 5s refresh`, + Args: cobra.MaximumNArgs(1), + RunE: runStats, +} + +func init() { + statsCmd.Flags().BoolVarP(&statsWatch, "watch", "w", false, "Enable watch mode for live updates") + statsCmd.Flags().DurationVarP(&statsInterval, "interval", "i", 2*time.Second, "Refresh interval for watch mode") + rootCmd.AddCommand(statsCmd) +} + +func runStats(cmd *cobra.Command, args []string) error { + // Watch mode not compatible with JSON output + if statsWatch && GetOutputFormat() == "json" { + printError("watch mode is not compatible with JSON output") + return fmt.Errorf("watch mode is not compatible with JSON output") + } + + // Determine which stats to show + component := "" + if len(args) > 0 { + component = args[0] + } + + // Validate component name upfront + switch component { + case "", "cache", "journal", "trim", "lock", "sfb", "all": + // valid + default: + return fmt.Errorf("unknown component: %s (valid: cache, journal, trim, lock, sfb, all)", component) + } + + // Create the display function + displayFn := func(ctx context.Context) error { + return displayStats(cmd, ctx, component) + } + + // Run with or without watch + return RunWithWatch(WatchConfig{ + Enabled: statsWatch, + Interval: statsInterval, + }, displayFn) +} + +func displayStats(cmd *cobra.Command, ctx context.Context, component string) error { + apiClient := GetClient() + f := NewFormatter(cmd.OutOrStdout(), GetOutputFormat()) + + switch component { + case "": + return showStatsOverview(ctx, apiClient, f) + case "cache": + return showCacheStats(ctx, apiClient, f) + case "journal": + return showJournalStats(ctx, apiClient, f) + case "trim": + return showTrimStats(ctx, apiClient, f) + case "lock": + return showLockStats(ctx, apiClient, f) + case "sfb": + return showSFBStats(ctx, apiClient, f) + case "all": + return showAllStats(ctx, apiClient, f) + default: + return fmt.Errorf("unknown component: %s", component) + } +} + +func showStatsOverview(ctx context.Context, c *client.Client, f *Formatter) error { + stats, err := c.StatsOverview(ctx) + if err != nil { + printError("failed to get stats: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(stats) + } + + f.Header("Statistics Overview") + + if stats.Cache != nil { + f.Printf("\n Cache:\n") + f.KeyValue(" Inode Hit Rate", FormatPercent(stats.Cache.InodeCache.HitRate*100)) + f.KeyValue(" Extent Hit Rate", FormatPercent(stats.Cache.ExtentCache.HitRate*100)) + } + + if stats.Journal != nil { + f.Printf("\n Journal:\n") + f.KeyValue(" State", stats.Journal.State) + f.KeyValue(" Commits", fmt.Sprintf("%d", stats.Journal.CommitCount)) + f.KeyValue(" Bytes Written", FormatBytes(stats.Journal.BytesWritten)) + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func showCacheStats(ctx context.Context, c *client.Client, f *Formatter) error { + stats, err := c.CacheStats(ctx) + if err != nil { + printError("failed to get cache stats: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(stats) + } + + f.Header("Cache Statistics") + + table := f.NewTable("Cache", "Size", "Hits", "Misses", "Hit Rate") + table.AddRow("Inode", + fmt.Sprintf("%d", stats.InodeCache.Size), + fmt.Sprintf("%d", stats.InodeCache.Hits), + fmt.Sprintf("%d", stats.InodeCache.Misses), + FormatPercent(stats.InodeCache.HitRate*100)) + table.AddRow("Extent", + fmt.Sprintf("%d", stats.ExtentCache.Size), + fmt.Sprintf("%d", stats.ExtentCache.Hits), + fmt.Sprintf("%d", stats.ExtentCache.Misses), + FormatPercent(stats.ExtentCache.HitRate*100)) + table.AddRow("Negative", + fmt.Sprintf("%d", stats.NegativeCache.Size), + fmt.Sprintf("%d", stats.NegativeCache.Hits), + fmt.Sprintf("%d", stats.NegativeCache.Misses), + FormatPercent(stats.NegativeCache.HitRate*100)) + if stats.LockHintCache.Size > 0 { + table.AddRow("Lock Hint", + fmt.Sprintf("%d", stats.LockHintCache.Size), + fmt.Sprintf("%d", stats.LockHintCache.Hits), + fmt.Sprintf("%d", stats.LockHintCache.Misses), + FormatPercent(stats.LockHintCache.HitRate*100)) + } + table.Render() + + fmt.Fprintln(os.Stdout) + return nil +} + +func showJournalStats(ctx context.Context, c *client.Client, f *Formatter) error { + stats, err := c.JournalStats(ctx) + if err != nil { + printError("failed to get journal stats: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(stats) + } + + f.Header("Journal Statistics") + + stateColor := "ok" + if stats.State != "open" { + stateColor = "warning" + } + f.KeyValueColor("State", stats.State, stateColor) + f.KeyValue("Head Offset", fmt.Sprintf("%d", stats.HeadOffset)) + f.KeyValue("Tail Offset", fmt.Sprintf("%d", stats.TailOffset)) + f.KeyValue("Available Space", FormatBytes(uint64(stats.AvailableSpace))) + f.KeyValue("Active Transactions", fmt.Sprintf("%d", stats.ActiveTxnCount)) + f.KeyValue("Commits", fmt.Sprintf("%d", stats.CommitCount)) + f.KeyValue("Bytes Written", FormatBytes(stats.BytesWritten)) + f.KeyValue("Last Checkpoint", fmt.Sprintf("%d", stats.LastCheckpointSeq)) + f.KeyValue("Batch Syncs", fmt.Sprintf("%d", stats.BatchSyncCount)) + + fmt.Fprintln(os.Stdout) + return nil +} + +func showTrimStats(ctx context.Context, c *client.Client, f *Formatter) error { + stats, err := c.TrimStats(ctx) + if err != nil { + printError("failed to get trim stats: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(stats) + } + + f.Header("TRIM Statistics") + + enabledStr := "disabled" + enabledColor := "warning" + if stats.TrimEnabled { + enabledStr = "enabled" + enabledColor = "ok" + } + f.KeyValueColor("TRIM", enabledStr, enabledColor) + f.KeyValue("Operations", fmt.Sprintf("%d", stats.TrimOperations)) + f.KeyValue("Bytes Trimmed", FormatBytes(stats.TrimBytes)) + f.KeyValue("Blocks Trimmed", fmt.Sprintf("%d", stats.TrimBlocks)) + f.KeyValue("Pending Blocks", fmt.Sprintf("%d", stats.PendingTrimBlocks)) + if stats.TrimErrors > 0 { + f.KeyValueColor("Errors", fmt.Sprintf("%d", stats.TrimErrors), "error") + } else { + f.KeyValue("Errors", "0") + } + if stats.LastTrimAt != "" { + f.KeyValue("Last TRIM", stats.LastTrimAt) + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func showLockStats(ctx context.Context, c *client.Client, f *Formatter) error { + stats, err := c.LockStats(ctx) + if err != nil { + printError("failed to get lock stats: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(stats) + } + + f.Header("Lock Statistics") + + f.KeyValue("Hint Cache Hits", fmt.Sprintf("%d", stats.HintCacheHits)) + f.KeyValue("Hint Cache Misses", fmt.Sprintf("%d", stats.HintCacheMisses)) + f.KeyValue("Hint Cache Hit Rate", FormatPercent(stats.HintCacheHitRate*100)) + f.KeyValue("Active Locks", fmt.Sprintf("%d", stats.ActiveLocks)) + f.KeyValue("Pending Locks", fmt.Sprintf("%d", stats.PendingLocks)) + + fmt.Fprintln(os.Stdout) + return nil +} + +func showSFBStats(ctx context.Context, c *client.Client, f *Formatter) error { + stats, err := c.SFBStats(ctx) + if err != nil { + printError("failed to get sfb stats: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(stats) + } + + f.Header("SFB (Sub-File Block) Statistics") + + f.KeyValue("Total Blocks", fmt.Sprintf("%d", stats.TotalBlocks)) + f.KeyValue("Allocated Blocks", fmt.Sprintf("%d", stats.AllocatedBlocks)) + f.KeyValue("Free Blocks", fmt.Sprintf("%d", stats.FreeBlocks)) + f.KeyValue("Allocation", FormatPercent(stats.AllocationPercent)) + if stats.FragmentationRatio > 0 { + f.KeyValue("Fragmentation", FormatPercent(stats.FragmentationRatio*100)) + } + if stats.LargestFreeExtent > 0 { + f.KeyValue("Largest Free Extent", fmt.Sprintf("%d blocks", stats.LargestFreeExtent)) + } + f.KeyValue("Total Allocations", fmt.Sprintf("%d", stats.AllocationsTotal)) + f.KeyValue("Total Deallocations", fmt.Sprintf("%d", stats.DeallocationsTotal)) + if stats.AllocationFailures > 0 { + f.KeyValueColor("Allocation Failures", fmt.Sprintf("%d", stats.AllocationFailures), "error") + } + + fmt.Fprintln(os.Stdout) + return nil +} + +func showAllStats(ctx context.Context, c *client.Client, f *Formatter) error { + stats, err := c.AllStats(ctx) + if err != nil { + printError("failed to get all stats: %v", err) + return err + } + + if f.IsJSON() { + return f.JSON(stats) + } + + f.Header("All Statistics") + f.KeyValue("Collected At", stats.CollectedAt) + + // Show each component's stats inline + if stats.Cache != nil { + f.Printf("\n") + f.Header("Cache") + table := f.NewTable("Cache", "Size", "Hits", "Misses", "Hit Rate") + table.AddRow("Inode", + fmt.Sprintf("%d", stats.Cache.InodeCache.Size), + fmt.Sprintf("%d", stats.Cache.InodeCache.Hits), + fmt.Sprintf("%d", stats.Cache.InodeCache.Misses), + FormatPercent(stats.Cache.InodeCache.HitRate*100)) + table.AddRow("Extent", + fmt.Sprintf("%d", stats.Cache.ExtentCache.Size), + fmt.Sprintf("%d", stats.Cache.ExtentCache.Hits), + fmt.Sprintf("%d", stats.Cache.ExtentCache.Misses), + FormatPercent(stats.Cache.ExtentCache.HitRate*100)) + table.Render() + } + + if stats.Journal != nil { + f.Printf("\n") + f.Header("Journal") + f.KeyValue("State", stats.Journal.State) + f.KeyValue("Commits", fmt.Sprintf("%d", stats.Journal.CommitCount)) + f.KeyValue("Bytes Written", FormatBytes(stats.Journal.BytesWritten)) + } + + if stats.Trim != nil { + f.Printf("\n") + f.Header("TRIM") + f.KeyValue("Operations", fmt.Sprintf("%d", stats.Trim.TrimOperations)) + f.KeyValue("Bytes Trimmed", FormatBytes(stats.Trim.TrimBytes)) + } + + if stats.Lock != nil { + f.Printf("\n") + f.Header("Lock") + f.KeyValue("Hint Cache Hit Rate", FormatPercent(stats.Lock.HintCacheHitRate*100)) + f.KeyValue("Active Locks", fmt.Sprintf("%d", stats.Lock.ActiveLocks)) + } + + if stats.SFB != nil { + f.Printf("\n") + f.Header("SFB") + f.KeyValue("Allocation", FormatPercent(stats.SFB.AllocationPercent)) + f.KeyValue("Free Blocks", fmt.Sprintf("%d", stats.SFB.FreeBlocks)) + } + + if stats.Cluster != nil { + f.Printf("\n") + f.Header("Cluster") + f.KeyValue("Node ID", stats.Cluster.NodeID) + f.KeyValue("Role", stats.Cluster.Role) + f.KeyValue("Cluster Size", fmt.Sprintf("%d", stats.Cluster.ClusterSize)) + f.KeyValue("Healthy Nodes", fmt.Sprintf("%d", stats.Cluster.HealthyNodes)) + } + + fmt.Fprintln(os.Stdout) + return nil +} diff --git a/cmd/gfsctl/commands/status.go b/cmd/gfsctl/commands/status.go new file mode 100644 index 00000000..2f523955 --- /dev/null +++ b/cmd/gfsctl/commands/status.go @@ -0,0 +1,145 @@ +package commands + +import ( + "context" + "fmt" + "os" + "time" + + "github.com/spf13/cobra" +) + +var ( + statusWatch bool + statusInterval time.Duration +) + +var statusCmd = &cobra.Command{ + Use: "status", + Short: "Show filesystem status", + Long: `Display comprehensive filesystem status including mount state, version, +uptime, and storage capacity. + +Examples: + gfsctl status # Show status in text format + gfsctl status -o json # Show status in JSON format + gfsctl status -w # Watch mode with 2s refresh + gfsctl status -w -i 5s # Watch mode with 5s refresh`, + RunE: runStatus, +} + +func init() { + statusCmd.Flags().BoolVarP(&statusWatch, "watch", "w", false, "Enable watch mode for live updates") + statusCmd.Flags().DurationVarP(&statusInterval, "interval", "i", 2*time.Second, "Refresh interval for watch mode") + rootCmd.AddCommand(statusCmd) +} + +func runStatus(cmd *cobra.Command, args []string) error { + // Watch mode not compatible with JSON output + if statusWatch && GetOutputFormat() == "json" { + printError("watch mode is not compatible with JSON output") + return fmt.Errorf("watch mode is not compatible with JSON output") + } + + // Create the display function + displayFn := func(ctx context.Context) error { + return displayStatus(cmd, ctx) + } + + // Run with or without watch + return RunWithWatch(WatchConfig{ + Enabled: statusWatch, + Interval: statusInterval, + }, displayFn) +} + +func displayStatus(cmd *cobra.Command, ctx context.Context) error { + client := GetClient() + + status, err := client.Status(ctx) + if err != nil { + printError("failed to get status: %v", err) + return err + } + + f := NewFormatter(cmd.OutOrStdout(), GetOutputFormat()) + + if f.IsJSON() { + return f.JSON(status) + } + + // Text output with colored status + f.Header("GoClusterFS Status") + + // Status indicator + statusColor := "ok" + if status.Status != "ok" { + statusColor = "error" + } + f.KeyValueColor("Status", status.Status, statusColor) + + // Version info + f.KeyValue("Version", status.Version) + if status.GitCommit != "" { + f.KeyValue("Git Commit", status.GitCommit) + } + if status.BuildTime != "" { + f.KeyValue("Build Time", status.BuildTime) + } + if status.GoVersion != "" { + f.KeyValue("Go Version", status.GoVersion) + } + + // Uptime + f.KeyValue("Uptime", FormatDuration(status.UptimeSeconds)) + + // Mount info + if status.MountPath != "" { + f.Header("Mount") + f.KeyValue("Mount Path", status.MountPath) + f.KeyValue("Device Path", status.DevicePath) + + mountColor := "ok" + if status.MountState != "mounted" { + mountColor = "warning" + } + f.KeyValueColor("Mount State", string(status.MountState), mountColor) + + if status.ReadOnly { + f.KeyValueColor("Read Only", "yes", "warning") + } + } + + // Capacity info + if status.Capacity != nil { + c := status.Capacity + f.Header("Storage Capacity") + f.KeyValue("Total", FormatBytes(c.TotalBytes)) + f.KeyValue("Used", fmt.Sprintf("%s (%s)", FormatBytes(c.UsedBytes), FormatPercent(c.UsedPercent))) + f.KeyValue("Free", FormatBytes(c.FreeBytes)) + f.KeyValue("Block Size", FormatBytes(c.BlockSizeBytes)) + f.KeyValue("Total Blocks", fmt.Sprintf("%d", c.TotalBlocks)) + f.KeyValue("Used Blocks", fmt.Sprintf("%d", c.UsedBlocks)) + f.KeyValue("Free Blocks", fmt.Sprintf("%d", c.FreeBlocks)) + } + + // Cluster info + if status.Cluster != nil { + c := status.Cluster + f.Header("Cluster") + f.KeyValue("Node ID", c.NodeID) + f.KeyValue("Peer Count", fmt.Sprintf("%d", c.PeerCount)) + if c.LeaderID != "" { + f.KeyValue("Leader ID", c.LeaderID) + } + if c.IsLeader { + f.KeyValueColor("Role", "leader", "leader") + } + if c.ClusterState != "" { + f.KeyValue("State", c.ClusterState) + } + } + + fmt.Fprintln(os.Stdout) + return nil +} diff --git a/cmd/gfsctl/commands/version.go b/cmd/gfsctl/commands/version.go new file mode 100644 index 00000000..cf2da86f --- /dev/null +++ b/cmd/gfsctl/commands/version.go @@ -0,0 +1,59 @@ +package commands + +import ( + "encoding/json" + "fmt" + "runtime" + + "github.com/spf13/cobra" +) + +var ( + // Version information, set at build time via ldflags + Version = "dev" + GitCommit = "unknown" + BuildTime = "unknown" +) + +// VersionInfo contains version information for JSON output. +type VersionInfo struct { + Version string `json:"version"` + GitCommit string `json:"git_commit"` + BuildTime string `json:"build_time"` + GoVersion string `json:"go_version"` + OS string `json:"os"` + Arch string `json:"arch"` +} + +var versionCmd = &cobra.Command{ + Use: "version", + Short: "Show gfsctl version information", + Long: `Display version, build information, and runtime details for gfsctl.`, + RunE: func(cmd *cobra.Command, args []string) error { + info := VersionInfo{ + Version: Version, + GitCommit: GitCommit, + BuildTime: BuildTime, + GoVersion: runtime.Version(), + OS: runtime.GOOS, + Arch: runtime.GOARCH, + } + + if GetOutputFormat() == "json" { + enc := json.NewEncoder(cmd.OutOrStdout()) + enc.SetIndent("", " ") + return enc.Encode(info) + } + + fmt.Fprintf(cmd.OutOrStdout(), "gfsctl version %s\n", info.Version) + fmt.Fprintf(cmd.OutOrStdout(), " Git commit: %s\n", info.GitCommit) + fmt.Fprintf(cmd.OutOrStdout(), " Built: %s\n", info.BuildTime) + fmt.Fprintf(cmd.OutOrStdout(), " Go version: %s\n", info.GoVersion) + fmt.Fprintf(cmd.OutOrStdout(), " OS/Arch: %s/%s\n", info.OS, info.Arch) + return nil + }, +} + +func init() { + rootCmd.AddCommand(versionCmd) +} diff --git a/cmd/gfsctl/commands/watch.go b/cmd/gfsctl/commands/watch.go new file mode 100644 index 00000000..de595196 --- /dev/null +++ b/cmd/gfsctl/commands/watch.go @@ -0,0 +1,96 @@ +package commands + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + "time" +) + +// WatchConfig holds configuration for watch mode. +type WatchConfig struct { + Enabled bool + Interval time.Duration +} + +// WatchFunc is a function that can be watched (called repeatedly). +type WatchFunc func(ctx context.Context) error + +// RunWithWatch executes the given function once or repeatedly based on watch mode. +// If watch mode is enabled, it clears the screen and re-runs the function +// at the configured interval until interrupted. +func RunWithWatch(cfg WatchConfig, fn WatchFunc) error { + if !cfg.Enabled { + return fn(context.Background()) + } + + // Set up signal handling for graceful exit + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + sigCh := make(chan os.Signal, 1) + signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) + + // Channel for watch loop to signal completion + done := make(chan struct{}) + + go func() { + defer close(done) + ticker := time.NewTicker(cfg.Interval) + defer ticker.Stop() + + // Initial run + clearScreen() + printWatchHeader(cfg.Interval) + if err := fn(ctx); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + } + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + clearScreen() + printWatchHeader(cfg.Interval) + if err := fn(ctx); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + } + } + } + }() + + // Wait for signal or context cancellation + select { + case <-sigCh: + cancel() + <-done + fmt.Println("\nWatch mode terminated.") + case <-done: + } + + return nil +} + +// clearScreen clears the terminal screen using ANSI escape codes. +func clearScreen() { + // Move cursor to home position and clear screen + fmt.Print("\033[H\033[2J") +} + +// printWatchHeader prints the watch mode header with timestamp. +func printWatchHeader(interval time.Duration) { + now := time.Now().Format("2006-01-02 15:04:05") + fmt.Printf("Every %s: gfsctl (updated: %s) [Ctrl+C to exit]\n\n", + formatInterval(interval), now) +} + +// formatInterval formats a duration for display. +func formatInterval(d time.Duration) string { + if d >= time.Minute { + return fmt.Sprintf("%.0fm", d.Minutes()) + } + return fmt.Sprintf("%.0fs", d.Seconds()) +} diff --git a/cmd/gfsctl/main.go b/cmd/gfsctl/main.go new file mode 100644 index 00000000..3df45691 --- /dev/null +++ b/cmd/gfsctl/main.go @@ -0,0 +1,36 @@ +// Command gfsctl is the management CLI for GoClusterFS. +// +// gfsctl communicates with a running GoClusterFS mount via its HTTP API +// to query status, statistics, and perform administrative operations. +// +// Usage: +// +// gfsctl [global flags] [command flags] +// +// Global flags: +// +// --host API server host (default: localhost) +// --port API server port (default: 8080) +// --token Bearer token for authentication +// --timeout Request timeout (default: 30s) +// +// Commands: +// +// status Show filesystem status +// health Check filesystem health +// stats Show component statistics +// cluster Cluster management commands +// version Show version information +package main + +import ( + "os" + + "github.com/supporttools/GoClusterFS/cmd/gfsctl/commands" +) + +func main() { + if err := commands.Execute(); err != nil { + os.Exit(1) + } +} diff --git a/go.mod b/go.mod index 2d556f6f..324bf7f8 100644 --- a/go.mod +++ b/go.mod @@ -2,21 +2,24 @@ module github.com/supporttools/GoClusterFS go 1.26.0 -require github.com/hanwen/go-fuse/v2 v2.9.0 - require ( + github.com/hanwen/go-fuse/v2 v2.9.0 github.com/prometheus/client_golang v1.23.2 + github.com/spf13/cobra v1.10.2 golang.org/x/sys v0.35.0 + gopkg.in/yaml.v2 v2.4.0 ) require ( github.com/beorn7/perks v1.0.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/kr/text v0.2.0 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.66.1 // indirect github.com/prometheus/procfs v0.16.1 // indirect + github.com/spf13/pflag v1.0.9 // indirect go.yaml.in/yaml/v2 v2.4.2 // indirect google.golang.org/protobuf v1.36.8 // indirect ) diff --git a/go.sum b/go.sum index 63cc61ba..d6c1ff75 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,7 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -9,6 +10,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/hanwen/go-fuse/v2 v2.9.0 h1:0AOGUkHtbOVeyGLr0tXupiid1Vg7QB7M6YUcdmVdC58= github.com/hanwen/go-fuse/v2 v2.9.0/go.mod h1:yE6D2PqWwm3CbYRxFXV9xUd8Md5d6NG0WBs5spCswmI= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -33,12 +36,18 @@ github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzM github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI= go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc= @@ -46,5 +55,7 @@ google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXn gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From ab1feb354d3f20959a2e10c5a9f8cf1ab5766869 Mon Sep 17 00:00:00 2001 From: Matthew Mattox Date: Fri, 2 Jan 2026 00:27:13 -0600 Subject: [PATCH 23/37] feat(web): add a React dashboard for the HTTP API Vite + React 19 + Tailwind, with pages for the dashboard, cluster, statistics, snapshots and settings. `npm run dev` serves it on :5173 and proxies /api, /health and /metrics to localhost:8080. Nothing serves the built files yet. Source only: node_modules and dist stay ignored by web/dashboard/.gitignore. The lockfile is the user's from 2025-12-31. Recovered from untracked work in the user's checkout. Co-Authored-By: Claude Opus 5.5 --- web/dashboard/.gitignore | 24 + web/dashboard/README.md | 73 + web/dashboard/eslint.config.js | 23 + web/dashboard/index.html | 15 + web/dashboard/package-lock.json | 4527 +++++++++++++++++ web/dashboard/package.json | 38 + web/dashboard/postcss.config.js | 6 + web/dashboard/public/favicon.svg | 22 + web/dashboard/public/vite.svg | 1 + web/dashboard/src/App.tsx | 28 + web/dashboard/src/api/client.ts | 421 ++ web/dashboard/src/api/index.ts | 10 + web/dashboard/src/api/types.ts | 280 + web/dashboard/src/assets/react.svg | 1 + .../src/components/charts/CacheCharts.tsx | 401 ++ web/dashboard/src/components/charts/index.ts | 5 + web/dashboard/src/components/common/Modal.tsx | 148 + .../src/components/common/SlidePanel.tsx | 126 + web/dashboard/src/components/common/index.ts | 9 + .../src/components/gauges/CircularGauge.tsx | 796 +++ web/dashboard/src/components/gauges/index.ts | 5 + web/dashboard/src/components/index.ts | 9 + .../components/modals/ConfirmDeleteModal.tsx | 229 + .../components/modals/CreateSnapshotModal.tsx | 259 + web/dashboard/src/components/modals/index.ts | 9 + .../src/components/panels/NodeDetailPanel.tsx | 228 + web/dashboard/src/components/panels/index.ts | 6 + web/dashboard/src/hooks/index.ts | 5 + web/dashboard/src/hooks/useApi.ts | 314 ++ web/dashboard/src/index.css | 169 + web/dashboard/src/layouts/DashboardLayout.tsx | 226 + web/dashboard/src/layouts/index.ts | 5 + web/dashboard/src/main.tsx | 10 + web/dashboard/src/pages/ClusterPage.tsx | 476 ++ web/dashboard/src/pages/DashboardPage.tsx | 370 ++ web/dashboard/src/pages/SettingsPage.tsx | 340 ++ web/dashboard/src/pages/SnapshotsPage.tsx | 542 ++ web/dashboard/src/pages/StatisticsPage.tsx | 236 + web/dashboard/src/pages/index.ts | 9 + web/dashboard/src/stores/index.ts | 22 + web/dashboard/src/stores/settingsContext.ts | 9 + web/dashboard/src/stores/settingsHooks.ts | 29 + web/dashboard/src/stores/settingsStore.tsx | 77 + web/dashboard/src/stores/settingsTypes.ts | 55 + web/dashboard/src/utils/format.ts | 81 + web/dashboard/src/utils/index.ts | 5 + web/dashboard/tailwind.config.js | 69 + web/dashboard/tsconfig.app.json | 34 + web/dashboard/tsconfig.json | 7 + web/dashboard/tsconfig.node.json | 26 + web/dashboard/vite.config.ts | 37 + 51 files changed, 10852 insertions(+) create mode 100644 web/dashboard/.gitignore create mode 100644 web/dashboard/README.md create mode 100644 web/dashboard/eslint.config.js create mode 100644 web/dashboard/index.html create mode 100644 web/dashboard/package-lock.json create mode 100644 web/dashboard/package.json create mode 100644 web/dashboard/postcss.config.js create mode 100644 web/dashboard/public/favicon.svg create mode 100644 web/dashboard/public/vite.svg create mode 100644 web/dashboard/src/App.tsx create mode 100644 web/dashboard/src/api/client.ts create mode 100644 web/dashboard/src/api/index.ts create mode 100644 web/dashboard/src/api/types.ts create mode 100644 web/dashboard/src/assets/react.svg create mode 100644 web/dashboard/src/components/charts/CacheCharts.tsx create mode 100644 web/dashboard/src/components/charts/index.ts create mode 100644 web/dashboard/src/components/common/Modal.tsx create mode 100644 web/dashboard/src/components/common/SlidePanel.tsx create mode 100644 web/dashboard/src/components/common/index.ts create mode 100644 web/dashboard/src/components/gauges/CircularGauge.tsx create mode 100644 web/dashboard/src/components/gauges/index.ts create mode 100644 web/dashboard/src/components/index.ts create mode 100644 web/dashboard/src/components/modals/ConfirmDeleteModal.tsx create mode 100644 web/dashboard/src/components/modals/CreateSnapshotModal.tsx create mode 100644 web/dashboard/src/components/modals/index.ts create mode 100644 web/dashboard/src/components/panels/NodeDetailPanel.tsx create mode 100644 web/dashboard/src/components/panels/index.ts create mode 100644 web/dashboard/src/hooks/index.ts create mode 100644 web/dashboard/src/hooks/useApi.ts create mode 100644 web/dashboard/src/index.css create mode 100644 web/dashboard/src/layouts/DashboardLayout.tsx create mode 100644 web/dashboard/src/layouts/index.ts create mode 100644 web/dashboard/src/main.tsx create mode 100644 web/dashboard/src/pages/ClusterPage.tsx create mode 100644 web/dashboard/src/pages/DashboardPage.tsx create mode 100644 web/dashboard/src/pages/SettingsPage.tsx create mode 100644 web/dashboard/src/pages/SnapshotsPage.tsx create mode 100644 web/dashboard/src/pages/StatisticsPage.tsx create mode 100644 web/dashboard/src/pages/index.ts create mode 100644 web/dashboard/src/stores/index.ts create mode 100644 web/dashboard/src/stores/settingsContext.ts create mode 100644 web/dashboard/src/stores/settingsHooks.ts create mode 100644 web/dashboard/src/stores/settingsStore.tsx create mode 100644 web/dashboard/src/stores/settingsTypes.ts create mode 100644 web/dashboard/src/utils/format.ts create mode 100644 web/dashboard/src/utils/index.ts create mode 100644 web/dashboard/tailwind.config.js create mode 100644 web/dashboard/tsconfig.app.json create mode 100644 web/dashboard/tsconfig.json create mode 100644 web/dashboard/tsconfig.node.json create mode 100644 web/dashboard/vite.config.ts diff --git a/web/dashboard/.gitignore b/web/dashboard/.gitignore new file mode 100644 index 00000000..a547bf36 --- /dev/null +++ b/web/dashboard/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/web/dashboard/README.md b/web/dashboard/README.md new file mode 100644 index 00000000..d2e77611 --- /dev/null +++ b/web/dashboard/README.md @@ -0,0 +1,73 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh + +## React Compiler + +The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: + +```js +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + + // Remove tseslint.configs.recommended and replace with this + tseslint.configs.recommendedTypeChecked, + // Alternatively, use this for stricter rules + tseslint.configs.strictTypeChecked, + // Optionally, add this for stylistic rules + tseslint.configs.stylisticTypeChecked, + + // Other configs... + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` + +You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: + +```js +// eslint.config.js +import reactX from 'eslint-plugin-react-x' +import reactDom from 'eslint-plugin-react-dom' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + // Enable lint rules for React + reactX.configs['recommended-typescript'], + // Enable lint rules for React DOM + reactDom.configs.recommended, + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` diff --git a/web/dashboard/eslint.config.js b/web/dashboard/eslint.config.js new file mode 100644 index 00000000..5e6b472f --- /dev/null +++ b/web/dashboard/eslint.config.js @@ -0,0 +1,23 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]) diff --git a/web/dashboard/index.html b/web/dashboard/index.html new file mode 100644 index 00000000..e043e80e --- /dev/null +++ b/web/dashboard/index.html @@ -0,0 +1,15 @@ + + + + + + + + + GoClusterFS Dashboard + + +
+ + + diff --git a/web/dashboard/package-lock.json b/web/dashboard/package-lock.json new file mode 100644 index 00000000..d0200911 --- /dev/null +++ b/web/dashboard/package-lock.json @@ -0,0 +1,4527 @@ +{ + "name": "@goclusterfs/dashboard", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@goclusterfs/dashboard", + "version": "0.1.0", + "dependencies": { + "react": "^19.2.0", + "react-dom": "^19.2.0", + "react-router-dom": "^7.11.0", + "recharts": "^3.6.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.1", + "@tailwindcss/forms": "^0.5.11", + "@types/node": "^24.10.1", + "@types/react": "^19.2.5", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.1.1", + "autoprefixer": "^10.4.23", + "eslint": "^9.39.1", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.4.24", + "globals": "^16.5.0", + "postcss": "^8.5.6", + "tailwindcss": "^3.4.19", + "typescript": "~5.9.3", + "typescript-eslint": "^8.46.4", + "vite": "^7.2.4" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", + "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", + "dev": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.27.1", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.5.tgz", + "integrity": "sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz", + "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-module-transforms": "^7.28.3", + "@babel/helpers": "^7.28.4", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.5.tgz", + "integrity": "sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.27.2", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz", + "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==", + "dev": true, + "dependencies": { + "@babel/compat-data": "^7.27.2", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz", + "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==", + "dev": true, + "dependencies": { + "@babel/traverse": "^7.27.1", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.3.tgz", + "integrity": "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==", + "dev": true, + "dependencies": { + "@babel/helper-module-imports": "^7.27.1", + "@babel/helper-validator-identifier": "^7.27.1", + "@babel/traverse": "^7.28.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.27.1.tgz", + "integrity": "sha512-1gn1Up5YXka3YYAHGKpbideQ5Yjf1tDa9qYcgysz+cNCXukyLl6DjPXhD3VRwSb8c0J9tA4b2+rHEZtc6R0tlw==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.28.4", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.4.tgz", + "integrity": "sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==", + "dev": true, + "dependencies": { + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", + "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "dev": true, + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.27.1.tgz", + "integrity": "sha512-6UzkCs+ejGdZ5mFFC/OCUrv028ab2fp1znZmCZjAOBKiBK2jXD1O+BPSfX8X2qjJ75fZBMSnQn3Rq2mrBJK2mw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.27.1.tgz", + "integrity": "sha512-zbwoTsBruTeKB9hSq73ha66iFeJHuaFkUbwvqElnygoNbj/jHRsSeokowZFN3CZ64IvEqcmmkVe89OPXc7ldAw==", + "dev": true, + "dependencies": { + "@babel/helper-plugin-utils": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.27.2", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz", + "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/parser": "^7.27.2", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.5.tgz", + "integrity": "sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ==", + "dev": true, + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.5", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", + "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "dev": true, + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", + "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", + "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", + "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", + "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", + "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", + "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", + "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", + "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", + "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", + "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", + "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", + "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", + "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", + "cpu": [ + "mips64el" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", + "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", + "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", + "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", + "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", + "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", + "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", + "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", + "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", + "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", + "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", + "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", + "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", + "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", + "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", + "dev": true, + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz", + "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==", + "dev": true, + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.3.tgz", + "integrity": "sha512-Kr+LPIUVKz2qkx1HAMH8q1q6azbqBAsXJUxBl/ODDuVPX45Z9DfwB8tPjTi6nNZ8BuM3nbJxC5zCAg5elnBUTQ==", + "dev": true, + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/eslintrc/node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.2.tgz", + "integrity": "sha512-q1mjIoW1VX4IvSocvM/vbTiveKC4k9eLrajNEuSsmjymSDEbpGddtpfOoN7YGAqBK3NG+uqo8ia4PDTt8buCYA==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@reduxjs/toolkit": { + "version": "2.11.2", + "resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.11.2.tgz", + "integrity": "sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ==", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@standard-schema/utils": "^0.3.0", + "immer": "^11.0.0", + "redux": "^5.0.1", + "redux-thunk": "^3.1.0", + "reselect": "^5.1.0" + }, + "peerDependencies": { + "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", + "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-redux": { + "optional": true + } + } + }, + "node_modules/@reduxjs/toolkit/node_modules/immer": { + "version": "11.1.3", + "resolved": "https://registry.npmjs.org/immer/-/immer-11.1.3.tgz", + "integrity": "sha512-6jQTc5z0KJFtr1UgFpIL3N9XSC3saRaI9PwWtzM2pSqkNGtiNkYY2OSwkOGDK2XcTRcLb1pi/aNkKZz0nxVH4Q==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.0-beta.53", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.53.tgz", + "integrity": "sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ==", + "dev": true + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.54.0.tgz", + "integrity": "sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.54.0.tgz", + "integrity": "sha512-Skx39Uv+u7H224Af+bDgNinitlmHyQX1K/atIA32JP3JQw6hVODX5tkbi2zof/E69M1qH2UoN3Xdxgs90mmNYw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.54.0.tgz", + "integrity": "sha512-k43D4qta/+6Fq+nCDhhv9yP2HdeKeP56QrUUTW7E6PhZP1US6NDqpJj4MY0jBHlJivVJD5P8NxrjuobZBJTCRw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.54.0.tgz", + "integrity": "sha512-cOo7biqwkpawslEfox5Vs8/qj83M/aZCSSNIWpVzfU2CYHa2G3P1UN5WF01RdTHSgCkri7XOlTdtk17BezlV3A==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.54.0.tgz", + "integrity": "sha512-miSvuFkmvFbgJ1BevMa4CPCFt5MPGw094knM64W9I0giUIMMmRYcGW/JWZDriaw/k1kOBtsWh1z6nIFV1vPNtA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.54.0.tgz", + "integrity": "sha512-KGXIs55+b/ZfZsq9aR026tmr/+7tq6VG6MsnrvF4H8VhwflTIuYh+LFUlIsRdQSgrgmtM3fVATzEAj4hBQlaqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.54.0.tgz", + "integrity": "sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.54.0.tgz", + "integrity": "sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.54.0.tgz", + "integrity": "sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.54.0.tgz", + "integrity": "sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.54.0.tgz", + "integrity": "sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==", + "cpu": [ + "loong64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.54.0.tgz", + "integrity": "sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.54.0.tgz", + "integrity": "sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.54.0.tgz", + "integrity": "sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==", + "cpu": [ + "riscv64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.54.0.tgz", + "integrity": "sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==", + "cpu": [ + "s390x" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.54.0.tgz", + "integrity": "sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.54.0.tgz", + "integrity": "sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.54.0.tgz", + "integrity": "sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.54.0.tgz", + "integrity": "sha512-c2V0W1bsKIKfbLMBu/WGBz6Yci8nJ/ZJdheE0EwB73N3MvHYKiKGs3mVilX4Gs70eGeDaMqEob25Tw2Gb9Nqyw==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.54.0.tgz", + "integrity": "sha512-woEHgqQqDCkAzrDhvDipnSirm5vxUXtSKDYTVpZG3nUdW/VVB5VdCYA2iReSj/u3yCZzXID4kuKG7OynPnB3WQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.54.0.tgz", + "integrity": "sha512-dzAc53LOuFvHwbCEOS0rPbXp6SIhAf2txMP5p6mGyOXXw5mWY8NGGbPMPrs4P1WItkfApDathBj/NzMLUZ9rtQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.54.0.tgz", + "integrity": "sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==" + }, + "node_modules/@standard-schema/utils": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/@standard-schema/utils/-/utils-0.3.0.tgz", + "integrity": "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g==" + }, + "node_modules/@tailwindcss/forms": { + "version": "0.5.11", + "resolved": "https://registry.npmjs.org/@tailwindcss/forms/-/forms-0.5.11.tgz", + "integrity": "sha512-h9wegbZDPurxG22xZSoWtdzc41/OlNEUQERNqI/0fOwa2aVlWGu7C35E/x6LDyD3lgtztFSSjKZyuVM0hxhbgA==", + "dev": true, + "dependencies": { + "mini-svg-data-uri": "^1.2.3" + }, + "peerDependencies": { + "tailwindcss": ">=3.0.0 || >= 3.0.0-alpha.1 || >= 4.0.0-alpha.20 || >= 4.0.0-beta.1" + } + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/d3-array": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.2.2.tgz", + "integrity": "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw==" + }, + "node_modules/@types/d3-color": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.3.tgz", + "integrity": "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A==" + }, + "node_modules/@types/d3-ease": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-ease/-/d3-ease-3.0.2.tgz", + "integrity": "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA==" + }, + "node_modules/@types/d3-interpolate": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-interpolate/-/d3-interpolate-3.0.4.tgz", + "integrity": "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA==", + "dependencies": { + "@types/d3-color": "*" + } + }, + "node_modules/@types/d3-path": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-3.1.1.tgz", + "integrity": "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg==" + }, + "node_modules/@types/d3-scale": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz", + "integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==", + "dependencies": { + "@types/d3-time": "*" + } + }, + "node_modules/@types/d3-shape": { + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.7.tgz", + "integrity": "sha512-VLvUQ33C+3J+8p+Daf+nYSOsjB4GXp19/S/aGo60m9h1v6XaxjiT82lKVWJCfzhtuZ3yD7i/TPeC/fuKLLOSmg==", + "dependencies": { + "@types/d3-path": "*" + } + }, + "node_modules/@types/d3-time": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz", + "integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==" + }, + "node_modules/@types/d3-timer": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/d3-timer/-/d3-timer-3.0.2.tgz", + "integrity": "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw==" + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true + }, + "node_modules/@types/node": { + "version": "24.10.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz", + "integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==", + "dev": true, + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.7", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz", + "integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==", + "devOptional": true, + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@types/use-sync-external-store": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", + "integrity": "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==" + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.51.0.tgz", + "integrity": "sha512-XtssGWJvypyM2ytBnSnKtHYOGT+4ZwTnBVl36TA4nRO2f4PRNGz5/1OszHzcZCvcBMh+qb7I06uoCmLTRdR9og==", + "dev": true, + "dependencies": { + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "8.51.0", + "@typescript-eslint/type-utils": "8.51.0", + "@typescript-eslint/utils": "8.51.0", + "@typescript-eslint/visitor-keys": "8.51.0", + "ignore": "^7.0.0", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.51.0", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.51.0.tgz", + "integrity": "sha512-3xP4XzzDNQOIqBMWogftkwxhg5oMKApqY0BAflmLZiFYHqyhSOxv/cd/zPQLTcCXr4AkaKb25joocY0BD1WC6A==", + "dev": true, + "dependencies": { + "@typescript-eslint/scope-manager": "8.51.0", + "@typescript-eslint/types": "8.51.0", + "@typescript-eslint/typescript-estree": "8.51.0", + "@typescript-eslint/visitor-keys": "8.51.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.51.0.tgz", + "integrity": "sha512-Luv/GafO07Z7HpiI7qeEW5NW8HUtZI/fo/kE0YbtQEFpJRUuR0ajcWfCE5bnMvL7QQFrmT/odMe8QZww8X2nfQ==", + "dev": true, + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.51.0", + "@typescript-eslint/types": "^8.51.0", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.51.0.tgz", + "integrity": "sha512-JhhJDVwsSx4hiOEQPeajGhCWgBMBwVkxC/Pet53EpBVs7zHHtayKefw1jtPaNRXpI9RA2uocdmpdfE7T+NrizA==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.51.0", + "@typescript-eslint/visitor-keys": "8.51.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.51.0.tgz", + "integrity": "sha512-Qi5bSy/vuHeWyir2C8u/uqGMIlIDu8fuiYWv48ZGlZ/k+PRPHtaAu7erpc7p5bzw2WNNSniuxoMSO4Ar6V9OXw==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.51.0.tgz", + "integrity": "sha512-0XVtYzxnobc9K0VU7wRWg1yiUrw4oQzexCG2V2IDxxCxhqBMSMbjB+6o91A+Uc0GWtgjCa3Y8bi7hwI0Tu4n5Q==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.51.0", + "@typescript-eslint/typescript-estree": "8.51.0", + "@typescript-eslint/utils": "8.51.0", + "debug": "^4.3.4", + "ts-api-utils": "^2.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.51.0.tgz", + "integrity": "sha512-TizAvWYFM6sSscmEakjY3sPqGwxZRSywSsPEiuZF6d5GmGD9Gvlsv0f6N8FvAAA0CD06l3rIcWNbsN1e5F/9Ag==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.51.0.tgz", + "integrity": "sha512-1qNjGqFRmlq0VW5iVlcyHBbCjPB7y6SxpBkrbhNWMy/65ZoncXCEPJxkRZL8McrseNH6lFhaxCIaX+vBuFnRng==", + "dev": true, + "dependencies": { + "@typescript-eslint/project-service": "8.51.0", + "@typescript-eslint/tsconfig-utils": "8.51.0", + "@typescript-eslint/types": "8.51.0", + "@typescript-eslint/visitor-keys": "8.51.0", + "debug": "^4.3.4", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.51.0.tgz", + "integrity": "sha512-11rZYxSe0zabiKaCP2QAwRf/dnmgFgvTmeDTtZvUvXG3UuAdg/GU02NExmmIXzz3vLGgMdtrIosI84jITQOxUA==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.51.0", + "@typescript-eslint/types": "8.51.0", + "@typescript-eslint/typescript-estree": "8.51.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.51.0.tgz", + "integrity": "sha512-mM/JRQOzhVN1ykejrvwnBRV3+7yTKK8tVANVN3o1O0t0v7o+jqdVu9crPy5Y9dov15TJk/FTIgoUGHrTOVL3Zg==", + "dev": true, + "dependencies": { + "@typescript-eslint/types": "8.51.0", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.1.2.tgz", + "integrity": "sha512-EcA07pHJouywpzsoTUqNh5NwGayl2PPVEJKUSinGGSxFGYn+shYbqMGBg6FXDqgXum9Ou/ecb+411ssw8HImJQ==", + "dev": true, + "dependencies": { + "@babel/core": "^7.28.5", + "@babel/plugin-transform-react-jsx-self": "^7.27.1", + "@babel/plugin-transform-react-jsx-source": "^7.27.1", + "@rolldown/pluginutils": "1.0.0-beta.53", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.18.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" + } + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/anymatch/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "dev": true + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true + }, + "node_modules/autoprefixer": { + "version": "10.4.23", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.23.tgz", + "integrity": "sha512-YYTXSFulfwytnjAPlw8QHncHJmlvFKtczb8InXaAx9Q0LbfDnfEYDE55omerIJKihhmU61Ft+cAOSzQVaBUmeA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/autoprefixer" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "browserslist": "^4.28.1", + "caniuse-lite": "^1.0.30001760", + "fraction.js": "^5.3.4", + "picocolors": "^1.1.1", + "postcss-value-parser": "^4.2.0" + }, + "bin": { + "autoprefixer": "bin/autoprefixer" + }, + "engines": { + "node": "^10 || ^12 || >=14" + }, + "peerDependencies": { + "postcss": "^8.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true + }, + "node_modules/baseline-browser-mapping": { + "version": "2.9.11", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz", + "integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==", + "dev": true, + "bin": { + "baseline-browser-mapping": "dist/cli.js" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001762", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001762.tgz", + "integrity": "sha512-PxZwGNvH7Ak8WX5iXzoK1KPZttBXNPuaOvI2ZYU7NrlM+d9Ov+TUvlLOBNGzVXAntMSMMlJPd+jY6ovrVjSmUw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ] + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true + }, + "node_modules/cookie": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", + "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true + }, + "node_modules/d3-array": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", + "integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==", + "dependencies": { + "internmap": "1 - 2" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-color": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz", + "integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-ease": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz", + "integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-format": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz", + "integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-interpolate": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz", + "integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==", + "dependencies": { + "d3-color": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-path": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz", + "integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==", + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-scale": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz", + "integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==", + "dependencies": { + "d3-array": "2.10.0 - 3", + "d3-format": "1 - 3", + "d3-interpolate": "1.2.0 - 3", + "d3-time": "2.1.1 - 3", + "d3-time-format": "2 - 4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-shape": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz", + "integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==", + "dependencies": { + "d3-path": "^3.1.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz", + "integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==", + "dependencies": { + "d3-array": "2 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-time-format": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz", + "integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==", + "dependencies": { + "d3-time": "1 - 3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/d3-timer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz", + "integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==", + "engines": { + "node": ">=12" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decimal.js-light": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/decimal.js-light/-/decimal.js-light-2.5.1.tgz", + "integrity": "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==" + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "optional": true, + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "dev": true + }, + "node_modules/electron-to-chromium": { + "version": "1.5.267", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", + "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", + "dev": true + }, + "node_modules/es-toolkit": { + "version": "1.43.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.43.0.tgz", + "integrity": "sha512-SKCT8AsWvYzBBuUqMk4NPwFlSdqLpJwmy6AP322ERn8W2YLIB6JBXnwMI2Qsh2gfphT3q7EKAxKb23cvFHFwKA==" + }, + "node_modules/esbuild": { + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", + "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==", + "dev": true, + "hasInstallScript": true, + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.2.tgz", + "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", + "dev": true, + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.1", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.39.2", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz", + "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==", + "dev": true, + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-react-refresh": { + "version": "0.4.26", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.4.26.tgz", + "integrity": "sha512-1RETEylht2O6FM/MvgnyvT+8K21wLqDNg4qD51Zj3guhjt433XbnnkVttHMyaVyAFD03QSV4LPS5iE3VQmO7XQ==", + "dev": true, + "peerDependencies": { + "eslint": ">=8.40" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.1.tgz", + "integrity": "sha512-GWkBvjiSZK87ELrYOSESUYeVIc9mvLLf/nXalMOS5dYrgZq9o5OVkbZAVM06CVxYsCwH9BDZFPlQTlPA1j4ahA==" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true + }, + "node_modules/fastq": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "dev": true, + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true + }, + "node_modules/fraction.js": { + "version": "5.3.4", + "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-5.3.4.tgz", + "integrity": "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==", + "dev": true, + "engines": { + "node": "*" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "16.5.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.5.0.tgz", + "integrity": "sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==", + "dev": true, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "engines": { + "node": ">= 4" + } + }, + "node_modules/immer": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/immer/-/immer-10.2.0.tgz", + "integrity": "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/immer" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/internmap": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz", + "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==", + "engines": { + "node": ">=12" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "dev": true, + "optional": true, + "peer": true, + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz", + "integrity": "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==", + "dev": true, + "optional": true, + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.30.2", + "lightningcss-darwin-arm64": "1.30.2", + "lightningcss-darwin-x64": "1.30.2", + "lightningcss-freebsd-x64": "1.30.2", + "lightningcss-linux-arm-gnueabihf": "1.30.2", + "lightningcss-linux-arm64-gnu": "1.30.2", + "lightningcss-linux-arm64-musl": "1.30.2", + "lightningcss-linux-x64-gnu": "1.30.2", + "lightningcss-linux-x64-musl": "1.30.2", + "lightningcss-win32-arm64-msvc": "1.30.2", + "lightningcss-win32-x64-msvc": "1.30.2" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.30.2.tgz", + "integrity": "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.30.2.tgz", + "integrity": "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.30.2.tgz", + "integrity": "sha512-oBZgKchomuDYxr7ilwLcyms6BCyLn0z8J0+ZZmfpjwg9fRVZIR5/GMXd7r9RH94iDhld3UmSjBM6nXWM2TfZTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.30.2.tgz", + "integrity": "sha512-c2bH6xTrf4BDpK8MoGG4Bd6zAMZDAXS569UxCAGcA7IKbHNMlhGQ89eRmvpIUGfKWNVdbhSbkQaWhEoMGmGslA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.30.2.tgz", + "integrity": "sha512-eVdpxh4wYcm0PofJIZVuYuLiqBIakQ9uFZmipf6LF/HRj5Bgm0eb3qL/mr1smyXIS1twwOxNWndd8z0E374hiA==", + "cpu": [ + "arm" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.30.2.tgz", + "integrity": "sha512-UK65WJAbwIJbiBFXpxrbTNArtfuznvxAJw4Q2ZGlU8kPeDIWEX1dg3rn2veBVUylA2Ezg89ktszWbaQnxD/e3A==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.30.2.tgz", + "integrity": "sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.30.2.tgz", + "integrity": "sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.30.2.tgz", + "integrity": "sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.30.2.tgz", + "integrity": "sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.30.2.tgz", + "integrity": "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw==", + "cpu": [ + "x64" + ], + "dev": true, + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "dev": true, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/mini-svg-data-uri": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz", + "integrity": "sha512-r9deDe9p5FJUPZAk3A59wGH7Ii9YrjjWw0jmw/liSbHl2CHiyXj6FcDXDu2K3TjVAXqiJdaw3xxwlZZr9E6nHg==", + "dev": true, + "bin": { + "mini-svg-data-uri": "cli.js" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true + }, + "node_modules/node-releases": { + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "dev": true + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true + }, + "node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pify": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/pify/-/pify-2.3.0.tgz", + "integrity": "sha512-udgsAY+fTnvv7kI7aaxbqwWNb0AHiB0qBO89PZKPkoTmGOgdbrHDKD+0B2X4uTfJ/FT1R09r9gTsjUjNJotuog==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "engines": { + "node": ">= 6" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "dev": true, + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz", + "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz", + "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==", + "dev": true, + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/react": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz", + "integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.3" + } + }, + "node_modules/react-is": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.3.tgz", + "integrity": "sha512-qJNJfu81ByyabuG7hPFEbXqNcWSU3+eVus+KJs+0ncpGfMyYdvSmxiJxbWR65lYi1I+/0HBcliO029gc4F+PnA==", + "peer": true + }, + "node_modules/react-redux": { + "version": "9.2.0", + "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz", + "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==", + "dependencies": { + "@types/use-sync-external-store": "^0.0.6", + "use-sync-external-store": "^1.4.0" + }, + "peerDependencies": { + "@types/react": "^18.2.25 || ^19", + "react": "^18.0 || ^19", + "redux": "^5.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "redux": { + "optional": true + } + } + }, + "node_modules/react-refresh": { + "version": "0.18.0", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.18.0.tgz", + "integrity": "sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-router": { + "version": "7.11.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.11.0.tgz", + "integrity": "sha512-uI4JkMmjbWCZc01WVP2cH7ZfSzH91JAZUDd7/nIprDgWxBV1TkkmLToFh7EbMTcMak8URFRa2YoBL/W8GWnCTQ==", + "dependencies": { + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } + } + }, + "node_modules/react-router-dom": { + "version": "7.11.0", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.11.0.tgz", + "integrity": "sha512-e49Ir/kMGRzFOOrYQBdoitq3ULigw4lKbAyKusnvtDu2t4dBX4AGYPrzNvorXmVuOyeakai6FUPW5MmibvVG8g==", + "dependencies": { + "react-router": "7.11.0" + }, + "engines": { + "node": ">=20.0.0" + }, + "peerDependencies": { + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/read-cache": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", + "integrity": "sha512-Owdv/Ft7IjOgm/i0xvNDZ1LrRANRfew4b2prF3OWMQLxLfu3bS8FVhCsrSCMK4lR56Y9ya+AThoTpDCTxCmpRA==", + "dev": true, + "dependencies": { + "pify": "^2.3.0" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/readdirp/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/recharts": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/recharts/-/recharts-3.6.0.tgz", + "integrity": "sha512-L5bjxvQRAe26RlToBAziKUB7whaGKEwD3znoM6fz3DrTowCIC/FnJYnuq1GEzB8Zv2kdTfaxQfi5GoH0tBinyg==", + "dependencies": { + "@reduxjs/toolkit": "1.x.x || 2.x.x", + "clsx": "^2.1.1", + "decimal.js-light": "^2.5.1", + "es-toolkit": "^1.39.3", + "eventemitter3": "^5.0.1", + "immer": "^10.1.1", + "react-redux": "8.x.x || 9.x.x", + "reselect": "5.1.1", + "tiny-invariant": "^1.3.3", + "use-sync-external-store": "^1.2.2", + "victory-vendor": "^37.0.2" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/redux": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", + "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==" + }, + "node_modules/redux-thunk": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/redux-thunk/-/redux-thunk-3.1.0.tgz", + "integrity": "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw==", + "peerDependencies": { + "redux": "^5.0.0" + } + }, + "node_modules/reselect": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/reselect/-/reselect-5.1.1.tgz", + "integrity": "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==" + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.54.0", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.54.0.tgz", + "integrity": "sha512-3nk8Y3a9Ea8szgKhinMlGMhGMw89mqule3KWczxhIzqudyHdCIOHw8WJlj/r329fACjKLEh13ZSk7oE22kyeIw==", + "dev": true, + "dependencies": { + "@types/estree": "1.0.8" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.54.0", + "@rollup/rollup-android-arm64": "4.54.0", + "@rollup/rollup-darwin-arm64": "4.54.0", + "@rollup/rollup-darwin-x64": "4.54.0", + "@rollup/rollup-freebsd-arm64": "4.54.0", + "@rollup/rollup-freebsd-x64": "4.54.0", + "@rollup/rollup-linux-arm-gnueabihf": "4.54.0", + "@rollup/rollup-linux-arm-musleabihf": "4.54.0", + "@rollup/rollup-linux-arm64-gnu": "4.54.0", + "@rollup/rollup-linux-arm64-musl": "4.54.0", + "@rollup/rollup-linux-loong64-gnu": "4.54.0", + "@rollup/rollup-linux-ppc64-gnu": "4.54.0", + "@rollup/rollup-linux-riscv64-gnu": "4.54.0", + "@rollup/rollup-linux-riscv64-musl": "4.54.0", + "@rollup/rollup-linux-s390x-gnu": "4.54.0", + "@rollup/rollup-linux-x64-gnu": "4.54.0", + "@rollup/rollup-linux-x64-musl": "4.54.0", + "@rollup/rollup-openharmony-arm64": "4.54.0", + "@rollup/rollup-win32-arm64-msvc": "4.54.0", + "@rollup/rollup-win32-ia32-msvc": "4.54.0", + "@rollup/rollup-win32-x64-gnu": "4.54.0", + "@rollup/rollup-win32-x64-msvc": "4.54.0", + "fsevents": "~2.3.2" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/set-cookie-parser": { + "version": "2.7.2", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", + "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==" + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.19", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz", + "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==", + "dev": true, + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.6.0", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.2", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.7", + "lilconfig": "^3.1.3", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.47", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0", + "postcss-nested": "^6.2.0", + "postcss-selector-parser": "^6.1.2", + "resolve": "^1.22.8", + "sucrase": "^3.35.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tailwindcss/node_modules/jiti": { + "version": "1.21.7", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", + "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", + "dev": true, + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tiny-invariant": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.3.3.tgz", + "integrity": "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==" + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-api-utils": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.3.0.tgz", + "integrity": "sha512-6eg3Y9SF7SsAvGzRHQvvc1skDAhwI4YQ32ui1scxD1Ccr0G5qIIbUBT3pFTKX8kmWIQClHobtUdNuaBgwdfdWg==", + "dev": true, + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.51.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.51.0.tgz", + "integrity": "sha512-jh8ZuM5oEh2PSdyQG9YAEM1TCGuWenLSuSUhf/irbVUNW9O5FhbFVONviN2TgMTBnUmyHv7E56rYnfLZK6TkiA==", + "dev": true, + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.51.0", + "@typescript-eslint/parser": "8.51.0", + "@typescript-eslint/typescript-estree": "8.51.0", + "@typescript-eslint/utils": "8.51.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/use-sync-external-store": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz", + "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true + }, + "node_modules/victory-vendor": { + "version": "37.3.6", + "resolved": "https://registry.npmjs.org/victory-vendor/-/victory-vendor-37.3.6.tgz", + "integrity": "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ==", + "dependencies": { + "@types/d3-array": "^3.0.3", + "@types/d3-ease": "^3.0.0", + "@types/d3-interpolate": "^3.0.1", + "@types/d3-scale": "^4.0.2", + "@types/d3-shape": "^3.1.0", + "@types/d3-time": "^3.0.0", + "@types/d3-timer": "^3.0.0", + "d3-array": "^3.1.6", + "d3-ease": "^3.0.1", + "d3-interpolate": "^3.0.1", + "d3-scale": "^4.0.2", + "d3-shape": "^3.1.0", + "d3-time": "^3.0.0", + "d3-timer": "^3.0.1" + } + }, + "node_modules/vite": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.0.tgz", + "integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==", + "dev": true, + "dependencies": { + "esbuild": "^0.27.0", + "fdir": "^6.5.0", + "picomatch": "^4.0.3", + "postcss": "^8.5.6", + "rollup": "^4.43.0", + "tinyglobby": "^0.2.15" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "lightningcss": "^1.21.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.2.tgz", + "integrity": "sha512-b8L8yn4rIVfiXyHAmnr52/ZEpDumlT0bmxiq3Ws1ybrinhflGpt12Hvv54kYnEsGPRs6o/Ka3/ppA2OWY21IVg==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + } + } +} diff --git a/web/dashboard/package.json b/web/dashboard/package.json new file mode 100644 index 00000000..234ee2e5 --- /dev/null +++ b/web/dashboard/package.json @@ -0,0 +1,38 @@ +{ + "name": "@goclusterfs/dashboard", + "description": "Web dashboard for GoClusterFS monitoring and management", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "react": "^19.2.0", + "react-dom": "^19.2.0", + "react-router-dom": "^7.11.0", + "recharts": "^3.6.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.1", + "@tailwindcss/forms": "^0.5.11", + "@types/node": "^24.10.1", + "@types/react": "^19.2.5", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.1.1", + "autoprefixer": "^10.4.23", + "eslint": "^9.39.1", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.4.24", + "globals": "^16.5.0", + "postcss": "^8.5.6", + "tailwindcss": "^3.4.19", + "typescript": "~5.9.3", + "typescript-eslint": "^8.46.4", + "vite": "^7.2.4" + } +} diff --git a/web/dashboard/postcss.config.js b/web/dashboard/postcss.config.js new file mode 100644 index 00000000..2e7af2b7 --- /dev/null +++ b/web/dashboard/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/web/dashboard/public/favicon.svg b/web/dashboard/public/favicon.svg new file mode 100644 index 00000000..813815c4 --- /dev/null +++ b/web/dashboard/public/favicon.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/web/dashboard/public/vite.svg b/web/dashboard/public/vite.svg new file mode 100644 index 00000000..e7b8dfb1 --- /dev/null +++ b/web/dashboard/public/vite.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/web/dashboard/src/App.tsx b/web/dashboard/src/App.tsx new file mode 100644 index 00000000..da13028b --- /dev/null +++ b/web/dashboard/src/App.tsx @@ -0,0 +1,28 @@ +/** + * GoClusterFS Dashboard Application + */ + +import { BrowserRouter, Routes, Route } from 'react-router-dom' +import { DashboardLayout } from '@/layouts' +import { DashboardPage, ClusterPage, SnapshotsPage, StatisticsPage, SettingsPage } from '@/pages' +import { SettingsProvider } from '@/stores' + +function App() { + return ( + + + + }> + } /> + } /> + } /> + } /> + } /> + + + + + ) +} + +export default App diff --git a/web/dashboard/src/api/client.ts b/web/dashboard/src/api/client.ts new file mode 100644 index 00000000..9c8070fb --- /dev/null +++ b/web/dashboard/src/api/client.ts @@ -0,0 +1,421 @@ +/** + * GoClusterFS API Client + * + * Typed fetch-based client for communicating with the GoClusterFS HTTP API. + * Handles authentication, error handling, and request/response processing. + */ + +import type { + HealthResponse, + StatusResponse, + CacheStatsResponse, + JournalStatsResponse, + TrimStatsResponse, + LockStatsResponse, + SFBStatsResponse, + ClusterInfoResponse, + AllStatsResponse, + ClusterNodesResponse, + ClusterLocksResponse, + StatsOverviewResponse, + ErrorResponse, + SnapshotsListResponse, + SnapshotInfo, + CreateSnapshotRequest, + CreateSnapshotResponse, + DeleteSnapshotResponse, +} from './types' + +// API configuration +export interface ApiConfig { + baseUrl: string + authToken?: string + timeout?: number +} + +// Default configuration +const defaultConfig: ApiConfig = { + baseUrl: '', // Uses relative URLs by default (proxied by Vite in dev) + timeout: 30000, +} + +// Custom API error class +export class ApiError extends Error { + readonly status: number + readonly code?: number + readonly details?: string + + constructor( + message: string, + status: number, + code?: number, + details?: string + ) { + super(message) + this.name = 'ApiError' + this.status = status + this.code = code + this.details = details + } + + static fromResponse(response: ErrorResponse, status: number): ApiError { + return new ApiError(response.error, status, response.code, response.details) + } +} + +// Request options for API calls +interface RequestOptions { + signal?: AbortSignal + headers?: Record + body?: string +} + +/** + * GoClusterFS API Client + */ +export class ApiClient { + private config: ApiConfig + + constructor(config: Partial = {}) { + this.config = { ...defaultConfig, ...config } + } + + /** + * Set the authentication token + */ + setAuthToken(token: string | undefined): void { + this.config.authToken = token + } + + /** + * Make an authenticated request to the API + */ + private async request( + method: string, + path: string, + options: RequestOptions = {} + ): Promise { + const url = `${this.config.baseUrl}${path}` + + const headers: Record = { + 'Accept': 'application/json', + ...options.headers, + } + + if (this.config.authToken) { + headers['Authorization'] = `Bearer ${this.config.authToken}` + } + + // Create abort controller for timeout + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), this.config.timeout) + + try { + const response = await fetch(url, { + method, + headers, + body: options.body, + signal: options.signal ?? controller.signal, + }) + + clearTimeout(timeoutId) + + if (!response.ok) { + // Try to parse error response + try { + const errorData = await response.json() as ErrorResponse + throw ApiError.fromResponse(errorData, response.status) + } catch (e) { + if (e instanceof ApiError) throw e + throw new ApiError( + `HTTP ${response.status}: ${response.statusText}`, + response.status + ) + } + } + + // Handle empty responses + const text = await response.text() + if (!text) { + return {} as T + } + + return JSON.parse(text) as T + } catch (error) { + clearTimeout(timeoutId) + + if (error instanceof ApiError) { + throw error + } + + if (error instanceof DOMException && error.name === 'AbortError') { + throw new ApiError('Request timed out', 408) + } + + if (error instanceof TypeError) { + throw new ApiError('Network error: Unable to connect', 0) + } + + throw new ApiError( + error instanceof Error ? error.message : 'Unknown error', + 0 + ) + } + } + + /** + * GET request helper + */ + private get(path: string, options?: RequestOptions): Promise { + return this.request('GET', path, options) + } + + /** + * POST request helper + */ + private post(path: string, body?: unknown, options?: RequestOptions): Promise { + return this.request('POST', path, { + ...options, + headers: { + ...options?.headers, + 'Content-Type': 'application/json', + }, + body: body ? JSON.stringify(body) : undefined, + } as RequestOptions & { body?: string }) + } + + /** + * DELETE request helper + */ + private delete(path: string, options?: RequestOptions): Promise { + return this.request('DELETE', path, options) + } + + // ============================================================ + // Health Endpoints + // ============================================================ + + /** + * Check API health status + * GET /health + */ + async getHealth(options?: RequestOptions): Promise { + return this.get('/health', options) + } + + // ============================================================ + // Status Endpoints + // ============================================================ + + /** + * Get system status overview + * GET /api/v1/status + */ + async getStatus(options?: RequestOptions): Promise { + return this.get('/api/v1/status', options) + } + + // ============================================================ + // Statistics Endpoints + // ============================================================ + + /** + * Get stats overview + * GET /api/v1/stats + */ + async getStatsOverview(options?: RequestOptions): Promise { + return this.get('/api/v1/stats', options) + } + + /** + * Get all stats combined + * GET /api/v1/stats/all + */ + async getAllStats(options?: RequestOptions): Promise { + return this.get('/api/v1/stats/all', options) + } + + /** + * Get cache statistics + * GET /api/v1/stats/cache + */ + async getCacheStats(options?: RequestOptions): Promise { + return this.get('/api/v1/stats/cache', options) + } + + /** + * Get journal statistics + * GET /api/v1/stats/journal + */ + async getJournalStats(options?: RequestOptions): Promise { + return this.get('/api/v1/stats/journal', options) + } + + /** + * Get trim statistics + * GET /api/v1/stats/trim + */ + async getTrimStats(options?: RequestOptions): Promise { + return this.get('/api/v1/stats/trim', options) + } + + /** + * Get lock statistics + * GET /api/v1/stats/lock + */ + async getLockStats(options?: RequestOptions): Promise { + return this.get('/api/v1/stats/lock', options) + } + + /** + * Get space/free block statistics + * GET /api/v1/stats/sfb + */ + async getSFBStats(options?: RequestOptions): Promise { + return this.get('/api/v1/stats/sfb', options) + } + + /** + * Get cluster statistics + * GET /api/v1/stats/cluster + */ + async getClusterStats(options?: RequestOptions): Promise { + return this.get('/api/v1/stats/cluster', options) + } + + // ============================================================ + // Cluster Endpoints + // ============================================================ + + /** + * Get cluster nodes + * GET /api/v1/cluster/nodes + */ + async getClusterNodes(options?: RequestOptions): Promise { + return this.get('/api/v1/cluster/nodes', options) + } + + /** + * Get cluster locks + * GET /api/v1/cluster/locks + */ + async getClusterLocks(options?: RequestOptions): Promise { + return this.get('/api/v1/cluster/locks', options) + } + + // ============================================================ + // Snapshot Endpoints + // ============================================================ + + /** + * List all snapshots + * GET /api/v1/snapshots + */ + async listSnapshots(options?: RequestOptions): Promise { + return this.get('/api/v1/snapshots', options) + } + + /** + * Get a specific snapshot + * GET /api/v1/snapshots/:id + */ + async getSnapshot(snapshotId: string, options?: RequestOptions): Promise { + return this.get(`/api/v1/snapshots/${encodeURIComponent(snapshotId)}`, options) + } + + /** + * Create a new snapshot + * POST /api/v1/snapshots + */ + async createSnapshot(request: CreateSnapshotRequest, options?: RequestOptions): Promise { + return this.post('/api/v1/snapshots', request, options) + } + + /** + * Delete a snapshot + * DELETE /api/v1/snapshots/:id + */ + async deleteSnapshot(snapshotId: string, options?: RequestOptions): Promise { + return this.delete(`/api/v1/snapshots/${encodeURIComponent(snapshotId)}`, options) + } + + // ============================================================ + // Metrics Endpoint + // ============================================================ + + /** + * Get Prometheus metrics (raw text format) + * GET /metrics + */ + async getMetrics(options?: RequestOptions): Promise { + const url = `${this.config.baseUrl}/metrics` + + const headers: Record = { + 'Accept': 'text/plain', + } + + if (this.config.authToken) { + headers['Authorization'] = `Bearer ${this.config.authToken}` + } + + const controller = new AbortController() + const timeoutId = setTimeout(() => controller.abort(), this.config.timeout) + + try { + const response = await fetch(url, { + method: 'GET', + headers, + signal: options?.signal ?? controller.signal, + }) + + clearTimeout(timeoutId) + + if (!response.ok) { + throw new ApiError( + `HTTP ${response.status}: ${response.statusText}`, + response.status + ) + } + + return response.text() + } catch (error) { + clearTimeout(timeoutId) + + if (error instanceof ApiError) throw error + + if (error instanceof DOMException && error.name === 'AbortError') { + throw new ApiError('Request timed out', 408) + } + + throw new ApiError( + error instanceof Error ? error.message : 'Unknown error', + 0 + ) + } + } +} + +// Default client instance +export const apiClient = new ApiClient() + +// Export convenience functions using default client +export const api = { + getHealth: (options?: RequestOptions) => apiClient.getHealth(options), + getStatus: (options?: RequestOptions) => apiClient.getStatus(options), + getStatsOverview: (options?: RequestOptions) => apiClient.getStatsOverview(options), + getAllStats: (options?: RequestOptions) => apiClient.getAllStats(options), + getCacheStats: (options?: RequestOptions) => apiClient.getCacheStats(options), + getJournalStats: (options?: RequestOptions) => apiClient.getJournalStats(options), + getTrimStats: (options?: RequestOptions) => apiClient.getTrimStats(options), + getLockStats: (options?: RequestOptions) => apiClient.getLockStats(options), + getSFBStats: (options?: RequestOptions) => apiClient.getSFBStats(options), + getClusterStats: (options?: RequestOptions) => apiClient.getClusterStats(options), + getClusterNodes: (options?: RequestOptions) => apiClient.getClusterNodes(options), + getClusterLocks: (options?: RequestOptions) => apiClient.getClusterLocks(options), + getMetrics: (options?: RequestOptions) => apiClient.getMetrics(options), + // Snapshot endpoints + listSnapshots: (options?: RequestOptions) => apiClient.listSnapshots(options), + getSnapshot: (id: string, options?: RequestOptions) => apiClient.getSnapshot(id, options), + createSnapshot: (request: CreateSnapshotRequest, options?: RequestOptions) => apiClient.createSnapshot(request, options), + deleteSnapshot: (id: string, options?: RequestOptions) => apiClient.deleteSnapshot(id, options), +} diff --git a/web/dashboard/src/api/index.ts b/web/dashboard/src/api/index.ts new file mode 100644 index 00000000..da2da164 --- /dev/null +++ b/web/dashboard/src/api/index.ts @@ -0,0 +1,10 @@ +/** + * API module exports + */ + +// Export all types +export * from './types' + +// Export client and utilities +export { ApiClient, ApiError, apiClient, api } from './client' +export type { ApiConfig } from './client' diff --git a/web/dashboard/src/api/types.ts b/web/dashboard/src/api/types.ts new file mode 100644 index 00000000..1c4c5dbc --- /dev/null +++ b/web/dashboard/src/api/types.ts @@ -0,0 +1,280 @@ +/** + * TypeScript interfaces matching GoClusterFS API response types. + * These types mirror the Go structs in internal/api/types.go + */ + +// Health status values +export type HealthStatus = 'ok' | 'degraded' | 'unhealthy' + +// Mount state values +export type MountState = 'unmounted' | 'mounting' | 'mounted' | 'unmounting' | 'error' + +// Component health for individual system components +export interface ComponentHealth { + status: HealthStatus + message?: string +} + +// GET /health response +export interface HealthResponse { + status: HealthStatus + checks?: Record +} + +// API error response +export interface ErrorResponse { + error: string + code: number + details?: string +} + +// Storage capacity information +export interface CapacityInfo { + total_bytes: number + used_bytes: number + free_bytes: number + used_percent: number + total_blocks: number + used_blocks: number + free_blocks: number + block_size_bytes: number +} + +// Cluster membership information +export interface ClusterInfo { + node_id?: string + peer_count: number + peers?: string[] + is_leader?: boolean + leader_id?: string + cluster_state?: string +} + +// GET /api/v1/status response +export interface StatusResponse { + status: string + version: string + git_commit?: string + build_time?: string + go_version?: string + uptime_seconds: number + mount_path?: string + device_path?: string + mount_state?: MountState + read_only?: boolean + capacity?: CapacityInfo + cluster?: ClusterInfo +} + +// Cache hit rate metrics +export interface CacheHitRateInfo { + size: number + hits: number + misses: number + hit_rate: number +} + +// GET /api/v1/stats/cache response +export interface CacheStatsResponse { + inode_cache: CacheHitRateInfo + extent_cache: CacheHitRateInfo + negative_cache: CacheHitRateInfo + lock_hint_cache?: CacheHitRateInfo +} + +// GET /api/v1/stats/journal response +export interface JournalStatsResponse { + state: string + head_offset: number + tail_offset: number + available_space: number + active_txn_count: number + commit_count: number + bytes_written: number + last_checkpoint_seq: number + batch_sync_count: number +} + +// I/O operation statistics +export interface IOStatsResponse { + read_ops: number + write_ops: number + bytes_read: number + bytes_written: number + avg_read_latency_us: number + avg_write_latency_us: number +} + +// GET /api/v1/stats/metrics response +export interface MetricsStatsResponse { + io?: IOStatsResponse + start_time_unix: number + uptime_seconds: number +} + +// GET /api/v1/stats/trim response +export interface TrimStatsResponse { + trim_operations: number + trim_bytes: number + trim_blocks: number + pending_trim_blocks?: number + last_trim_at?: string + trim_errors?: number + trim_enabled: boolean + batch_size?: number +} + +// GET /api/v1/stats/lock response +export interface LockStatsResponse { + hint_cache_hits: number + hint_cache_misses: number + hint_cache_hit_rate: number + active_locks?: number + pending_locks?: number +} + +// GET /api/v1/stats/sfb response +export interface SFBStatsResponse { + total_blocks: number + allocated_blocks: number + free_blocks: number + allocation_percent: number + fragmentation_ratio?: number + largest_free_extent?: number + allocations_total: number + deallocations_total: number + allocation_failures?: number +} + +// Cluster peer node information +export interface ClusterPeerInfo { + node_id: string + address: string + state: string + last_seen?: string + latency_ms?: number +} + +// GET /api/v1/stats/cluster response +export interface ClusterInfoResponse { + node_id: string + node_address?: string + role: string + state: string + cluster_size: number + healthy_nodes: number + leader_id?: string + last_heartbeat_at?: string + joined_at?: string + peers?: ClusterPeerInfo[] +} + +// GET /api/v1/stats/all response +export interface AllStatsResponse { + collected_at: string + cache?: CacheStatsResponse + journal?: JournalStatsResponse + trim?: TrimStatsResponse + lock?: LockStatsResponse + sfb?: SFBStatsResponse + cluster?: ClusterInfoResponse +} + +// Cluster node detailed information +export interface ClusterNodeInfo { + node_id: string + address: string + role: string + state: string + last_heartbeat?: string + joined_at?: string + version?: string + latency_ms?: number + is_self: boolean +} + +// GET /api/v1/cluster/nodes response +export interface ClusterNodesResponse { + cluster_id?: string + total_nodes: number + healthy_nodes: number + leader_id?: string + nodes: ClusterNodeInfo[] +} + +// Distributed lock information +export interface DistributedLockInfo { + lock_id: string + resource: string + owner_node_id: string + owner_process?: string + acquired_at: string + expires_at?: string + lock_type: string +} + +// GET /api/v1/cluster/locks response +export interface ClusterLocksResponse { + active_locks: number + pending_locks: number + locks: DistributedLockInfo[] +} + +// GET /api/v1/stats response (overview) +export interface StatsOverviewResponse { + cache?: CacheStatsResponse + journal?: JournalStatsResponse + io?: IOStatsResponse +} + +// ============================================================ +// Snapshot Types +// ============================================================ + +// Snapshot status values +export type SnapshotStatus = 'creating' | 'active' | 'deleting' | 'error' | 'archived' + +// Individual snapshot information +export interface SnapshotInfo { + snapshot_id: string + name: string + description?: string + status: SnapshotStatus + created_at: string + created_by?: string + size_bytes: number + parent_snapshot_id?: string + metadata?: Record + // Retention info + retention_policy?: string + expires_at?: string + // Progress info (for creating/deleting states) + progress_percent?: number + error_message?: string +} + +// GET /api/v1/snapshots response +export interface SnapshotsListResponse { + snapshots: SnapshotInfo[] + total_count: number + total_size_bytes: number +} + +// POST /api/v1/snapshots request +export interface CreateSnapshotRequest { + name: string + description?: string + metadata?: Record + retention_policy?: string +} + +// POST /api/v1/snapshots response +export interface CreateSnapshotResponse { + snapshot: SnapshotInfo +} + +// DELETE /api/v1/snapshots/:id response +export interface DeleteSnapshotResponse { + success: boolean + message?: string +} diff --git a/web/dashboard/src/assets/react.svg b/web/dashboard/src/assets/react.svg new file mode 100644 index 00000000..6c87de9b --- /dev/null +++ b/web/dashboard/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/web/dashboard/src/components/charts/CacheCharts.tsx b/web/dashboard/src/components/charts/CacheCharts.tsx new file mode 100644 index 00000000..e751becb --- /dev/null +++ b/web/dashboard/src/components/charts/CacheCharts.tsx @@ -0,0 +1,401 @@ +/** + * Cache Performance Charts - visualizations for cache metrics + * + * Uses Recharts for rendering line/area/bar charts showing: + * - Cache hit rate over time + * - Cache size/memory usage + * - Per-cache breakdown (inode, extent, lock hint) + */ + +import { useMemo } from 'react' +import { + BarChart, + Bar, + LineChart, + Line, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + ResponsiveContainer, + Legend, +} from 'recharts' +import type { CacheHitRateInfo } from '@/api' +import { formatNumber, formatPercent } from '@/utils/format' + +// Chart theme colors matching GoClusterFS design system +const CHART_COLORS = { + primary: '#63b3ed', // gfs-accent-primary + secondary: '#4299e1', // gfs-accent-secondary + success: '#48bb78', // gfs-status-ok + warning: '#ed8936', // gfs-status-warning + error: '#f56565', // gfs-status-error + grid: '#2d3748', // gfs-border + text: '#a0aec0', // gfs-text-secondary +} + +// Custom tooltip styles +const tooltipStyle = { + backgroundColor: '#1a1a2e', + border: '1px solid #2d3748', + borderRadius: '0.375rem', + padding: '0.5rem 0.75rem', + color: '#e2e8f0', + fontSize: '0.875rem', +} + +/** + * Props for cache breakdown bar chart + */ +interface CacheBreakdownChartProps { + inodeCache?: CacheHitRateInfo + extentCache?: CacheHitRateInfo + lockHintCache?: CacheHitRateInfo +} + +/** + * Bar chart showing cache breakdown by type + */ +export function CacheBreakdownChart({ + inodeCache, + extentCache, + lockHintCache, +}: CacheBreakdownChartProps) { + const data = useMemo(() => [ + { + name: 'Inode', + hits: inodeCache?.hits ?? 0, + misses: inodeCache?.misses ?? 0, + size: inodeCache?.size ?? 0, + hitRate: (inodeCache?.hit_rate ?? 0) * 100, + }, + { + name: 'Extent', + hits: extentCache?.hits ?? 0, + misses: extentCache?.misses ?? 0, + size: extentCache?.size ?? 0, + hitRate: (extentCache?.hit_rate ?? 0) * 100, + }, + { + name: 'Lock Hint', + hits: lockHintCache?.hits ?? 0, + misses: lockHintCache?.misses ?? 0, + size: lockHintCache?.size ?? 0, + hitRate: (lockHintCache?.hit_rate ?? 0) * 100, + }, + ], [inodeCache, extentCache, lockHintCache]) + + return ( +
+ + + + formatNumber(value)} + /> + + [ + formatNumber(Number(value ?? 0)), + name === 'hits' ? 'Hits' : 'Misses', + ]} + /> + ( + + {value === 'hits' ? 'Hits' : 'Misses'} + + )} + /> + + + + +
+ ) +} + +/** + * Props for hit rate line chart + */ +interface HitRateChartProps { + inodeCache?: CacheHitRateInfo + extentCache?: CacheHitRateInfo + lockHintCache?: CacheHitRateInfo +} + +/** + * Line chart showing hit rates for each cache type + */ +export function HitRateChart({ + inodeCache, + extentCache, + lockHintCache, +}: HitRateChartProps) { + const data = useMemo(() => [ + { + name: 'Inode', + hitRate: (inodeCache?.hit_rate ?? 0) * 100, + }, + { + name: 'Extent', + hitRate: (extentCache?.hit_rate ?? 0) * 100, + }, + { + name: 'Lock Hint', + hitRate: (lockHintCache?.hit_rate ?? 0) * 100, + }, + ], [inodeCache, extentCache, lockHintCache]) + + return ( +
+ + + + + `${value}%`} + /> + [formatPercent(Number(value ?? 0)), 'Hit Rate']} + /> + + + +
+ ) +} + +/** + * Props for cache size chart + */ +interface CacheSizeChartProps { + inodeCache?: CacheHitRateInfo + extentCache?: CacheHitRateInfo + lockHintCache?: CacheHitRateInfo +} + +/** + * Area chart showing cache sizes + */ +export function CacheSizeChart({ + inodeCache, + extentCache, + lockHintCache, +}: CacheSizeChartProps) { + const data = useMemo(() => [ + { + name: 'Inode', + size: inodeCache?.size ?? 0, + }, + { + name: 'Extent', + size: extentCache?.size ?? 0, + }, + { + name: 'Lock Hint', + size: lockHintCache?.size ?? 0, + }, + ], [inodeCache, extentCache, lockHintCache]) + + return ( +
+ + + + + formatNumber(value)} + /> + [formatNumber(Number(value ?? 0)), 'Entries']} + /> + + + +
+ ) +} + +/** + * Props for time series data + */ +interface TimeSeriesPoint { + timestamp: string + inodeHitRate: number + extentHitRate: number + lockHintHitRate: number +} + +interface TimeSeriesChartProps { + data: TimeSeriesPoint[] +} + +/** + * Line chart for hit rate over time + * Note: This requires historical data to be collected by the API + */ +export function HitRateTimeSeriesChart({ data }: TimeSeriesChartProps) { + if (!data || data.length === 0) { + return ( +
+

No historical data available

+
+ ) + } + + return ( +
+ + + + { + const date = new Date(value) + return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) + }} + /> + `${value}%`} + /> + [ + formatPercent(Number(value ?? 0)), + String(name).replace('HitRate', ' Hit Rate'), + ]} + labelFormatter={(value) => new Date(String(value)).toLocaleString()} + /> + ( + + {value.replace('HitRate', '')} + + )} + /> + + + + + +
+ ) +} + +/** + * Props for the combined cache stats panel + */ +interface CacheStatsPanelProps { + inodeCache?: CacheHitRateInfo + extentCache?: CacheHitRateInfo + lockHintCache?: CacheHitRateInfo + timeSeries?: TimeSeriesPoint[] +} + +/** + * Combined panel showing all cache charts + */ +export function CacheStatsPanel({ + inodeCache, + extentCache, + lockHintCache, + timeSeries, +}: CacheStatsPanelProps) { + return ( +
+ {/* Hit rates by cache type */} +
+

Cache Hit Rates

+ +
+ + {/* Cache sizes */} +
+

Cache Sizes

+ +
+ + {/* Hits vs Misses breakdown */} +
+

Hits vs Misses

+ +
+ + {/* Time series (if available) */} + {timeSeries && timeSeries.length > 0 && ( +
+

Hit Rate Over Time

+ +
+ )} +
+ ) +} + +export default CacheStatsPanel diff --git a/web/dashboard/src/components/charts/index.ts b/web/dashboard/src/components/charts/index.ts new file mode 100644 index 00000000..7e5cdd57 --- /dev/null +++ b/web/dashboard/src/components/charts/index.ts @@ -0,0 +1,5 @@ +/** + * Charts module exports + */ + +export * from './CacheCharts' diff --git a/web/dashboard/src/components/common/Modal.tsx b/web/dashboard/src/components/common/Modal.tsx new file mode 100644 index 00000000..12966949 --- /dev/null +++ b/web/dashboard/src/components/common/Modal.tsx @@ -0,0 +1,148 @@ +/** + * Reusable modal component with accessibility support + */ + +import { useEffect, useRef, type ReactNode } from 'react' +import { createPortal } from 'react-dom' + +export interface ModalProps { + /** Whether the modal is open */ + isOpen: boolean + /** Callback when the modal should close */ + onClose: () => void + /** Modal title */ + title: string + /** Modal content */ + children: ReactNode + /** Optional footer content (buttons, etc.) */ + footer?: ReactNode + /** Size of the modal */ + size?: 'sm' | 'md' | 'lg' + /** Whether clicking the backdrop closes the modal */ + closeOnBackdrop?: boolean + /** Whether pressing Escape closes the modal */ + closeOnEscape?: boolean +} + +const sizeClasses = { + sm: 'max-w-md', + md: 'max-w-lg', + lg: 'max-w-2xl', +} + +export function Modal({ + isOpen, + onClose, + title, + children, + footer, + size = 'md', + closeOnBackdrop = true, + closeOnEscape = true, +}: ModalProps) { + const modalRef = useRef(null) + const previousActiveElement = useRef(null) + + // Handle escape key + useEffect(() => { + if (!isOpen || !closeOnEscape) return + + const handleKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + onClose() + } + } + + document.addEventListener('keydown', handleKeyDown) + return () => document.removeEventListener('keydown', handleKeyDown) + }, [isOpen, closeOnEscape, onClose]) + + // Focus management + useEffect(() => { + if (isOpen) { + previousActiveElement.current = document.activeElement as HTMLElement + // Focus the modal on open + modalRef.current?.focus() + } else if (previousActiveElement.current) { + // Restore focus on close + previousActiveElement.current.focus() + } + }, [isOpen]) + + // Prevent body scroll when modal is open + useEffect(() => { + if (isOpen) { + document.body.style.overflow = 'hidden' + } else { + document.body.style.overflow = '' + } + return () => { + document.body.style.overflow = '' + } + }, [isOpen]) + + if (!isOpen) return null + + const handleBackdropClick = (e: React.MouseEvent) => { + if (closeOnBackdrop && e.target === e.currentTarget) { + onClose() + } + } + + const modalContent = ( +
+ {/* Backdrop */} + + ) + + // Render modal in portal + return createPortal(modalContent, document.body) +} + +export default Modal diff --git a/web/dashboard/src/components/common/SlidePanel.tsx b/web/dashboard/src/components/common/SlidePanel.tsx new file mode 100644 index 00000000..8d162d67 --- /dev/null +++ b/web/dashboard/src/components/common/SlidePanel.tsx @@ -0,0 +1,126 @@ +/** + * Reusable slide-in panel component + * Slides in from the right side of the screen + */ + +import { useEffect, useCallback, type ReactNode } from 'react' +import { createPortal } from 'react-dom' + +export interface SlidePanelProps { + /** Whether the panel is open */ + isOpen: boolean + /** Callback when the panel should close */ + onClose: () => void + /** Panel title */ + title: string + /** Optional subtitle */ + subtitle?: string + /** Panel content */ + children: ReactNode + /** Panel width - defaults to 'md' */ + width?: 'sm' | 'md' | 'lg' | 'xl' + /** Whether to close on backdrop click */ + closeOnBackdrop?: boolean + /** Whether to close on escape key */ + closeOnEscape?: boolean +} + +const widthClasses = { + sm: 'max-w-sm', + md: 'max-w-md', + lg: 'max-w-lg', + xl: 'max-w-xl', +} + +export function SlidePanel({ + isOpen, + onClose, + title, + subtitle, + children, + width = 'md', + closeOnBackdrop = true, + closeOnEscape = true, +}: SlidePanelProps) { + // Handle escape key + const handleKeyDown = useCallback( + (e: KeyboardEvent) => { + if (closeOnEscape && e.key === 'Escape') { + onClose() + } + }, + [closeOnEscape, onClose] + ) + + useEffect(() => { + if (isOpen) { + document.addEventListener('keydown', handleKeyDown) + // Prevent body scroll when panel is open + document.body.style.overflow = 'hidden' + + return () => { + document.removeEventListener('keydown', handleKeyDown) + document.body.style.overflow = '' + } + } + }, [isOpen, handleKeyDown]) + + if (!isOpen) { + return null + } + + const panel = ( +
+ {/* Backdrop */} + + ) + + return createPortal(panel, document.body) +} + +export default SlidePanel diff --git a/web/dashboard/src/components/common/index.ts b/web/dashboard/src/components/common/index.ts new file mode 100644 index 00000000..dcedecc4 --- /dev/null +++ b/web/dashboard/src/components/common/index.ts @@ -0,0 +1,9 @@ +/** + * Common components exports + */ + +export { Modal } from './Modal' +export type { ModalProps } from './Modal' + +export { SlidePanel } from './SlidePanel' +export type { SlidePanelProps } from './SlidePanel' diff --git a/web/dashboard/src/components/gauges/CircularGauge.tsx b/web/dashboard/src/components/gauges/CircularGauge.tsx new file mode 100644 index 00000000..707c01cc --- /dev/null +++ b/web/dashboard/src/components/gauges/CircularGauge.tsx @@ -0,0 +1,796 @@ +/** + * Circular Gauge Components - SVG-based circular progress indicators + * + * These gauges display percentage values in a visually appealing circular format + * with configurable colors, sizes, and warning thresholds. + */ + +import { useMemo } from 'react' +import { formatPercent, formatBytes, formatNumber } from '@/utils/format' + +/** + * Color thresholds for gauge status indication + */ +interface ThresholdColors { + ok: string + warning: string + critical: string +} + +const DEFAULT_COLORS: ThresholdColors = { + ok: '#48bb78', // gfs-status-ok (green) + warning: '#ed8936', // gfs-status-warning (orange) + critical: '#f56565', // gfs-status-error (red) +} + +/** + * Get color based on percentage and thresholds + */ +function getColorForPercent( + percent: number, + warningThreshold: number, + criticalThreshold: number, + colors: ThresholdColors = DEFAULT_COLORS +): string { + if (percent >= criticalThreshold) return colors.critical + if (percent >= warningThreshold) return colors.warning + return colors.ok +} + +/** + * Base props for all circular gauges + */ +interface CircularGaugeBaseProps { + /** Current percentage (0-100) */ + percent: number + /** Size in pixels (default: 120) */ + size?: number + /** Stroke width (default: 8) */ + strokeWidth?: number + /** Warning threshold percentage (default: 75) */ + warningThreshold?: number + /** Critical threshold percentage (default: 90) */ + criticalThreshold?: number + /** Custom color overrides */ + colors?: Partial + /** Label text below the value */ + label?: string + /** Show percentage text (default: true) */ + showPercent?: boolean + /** Animation duration in ms (default: 500) */ + animationDuration?: number +} + +/** + * Basic circular gauge showing a percentage + */ +export function CircularGauge({ + percent, + size = 120, + strokeWidth = 8, + warningThreshold = 75, + criticalThreshold = 90, + colors, + label, + showPercent = true, + animationDuration = 500, +}: CircularGaugeBaseProps) { + const mergedColors = { ...DEFAULT_COLORS, ...colors } + + // Calculate SVG dimensions + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const center = size / 2 + + // Clamp percent to 0-100 + const clampedPercent = Math.min(100, Math.max(0, percent)) + + // Calculate stroke offset for the progress arc + const strokeDashoffset = circumference * (1 - clampedPercent / 100) + + // Get color based on thresholds + const strokeColor = getColorForPercent( + clampedPercent, + warningThreshold, + criticalThreshold, + mergedColors + ) + + return ( +
+ + {/* Background circle */} + + {/* Progress circle */} + + + {/* Center text overlay */} +
+ {showPercent && ( + + {formatPercent(clampedPercent)} + + )} +
+ {/* Label below gauge */} + {label && ( + {label} + )} +
+ ) +} + +/** + * Props for capacity gauge with byte values + */ +interface CapacityGaugeProps extends Omit { + /** Used bytes */ + usedBytes: number + /** Total bytes */ + totalBytes: number + /** Show used/total values (default: true) */ + showValues?: boolean +} + +/** + * Capacity gauge showing storage usage with byte values + */ +export function CapacityGauge({ + usedBytes, + totalBytes, + size = 140, + strokeWidth = 10, + warningThreshold = 75, + criticalThreshold = 90, + colors, + label = 'Storage', + showValues = true, + animationDuration = 500, +}: CapacityGaugeProps) { + const percent = useMemo(() => { + if (totalBytes <= 0) return 0 + return (usedBytes / totalBytes) * 100 + }, [usedBytes, totalBytes]) + + const mergedColors = { ...DEFAULT_COLORS, ...colors } + + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const center = size / 2 + const clampedPercent = Math.min(100, Math.max(0, percent)) + const strokeDashoffset = circumference * (1 - clampedPercent / 100) + + const strokeColor = getColorForPercent( + clampedPercent, + warningThreshold, + criticalThreshold, + mergedColors + ) + + return ( +
+
+ + + + + {/* Center content */} +
+ + {formatPercent(clampedPercent)} + + {showValues && ( + + {formatBytes(usedBytes)} + + )} +
+
+ {label && ( + {label} + )} + {showValues && ( + + of {formatBytes(totalBytes)} + + )} +
+ ) +} + +/** + * Props for inode gauge + */ +interface InodeGaugeProps extends Omit { + /** Used inodes */ + usedInodes: number + /** Total inodes */ + totalInodes: number + /** Show inode counts (default: true) */ + showCounts?: boolean +} + +/** + * Inode gauge showing inode usage + */ +export function InodeGauge({ + usedInodes, + totalInodes, + size = 140, + strokeWidth = 10, + warningThreshold = 80, + criticalThreshold = 95, + colors, + label = 'Inodes', + showCounts = true, + animationDuration = 500, +}: InodeGaugeProps) { + const percent = useMemo(() => { + if (totalInodes <= 0) return 0 + return (usedInodes / totalInodes) * 100 + }, [usedInodes, totalInodes]) + + const mergedColors = { ...DEFAULT_COLORS, ...colors } + + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const center = size / 2 + const clampedPercent = Math.min(100, Math.max(0, percent)) + const strokeDashoffset = circumference * (1 - clampedPercent / 100) + + const strokeColor = getColorForPercent( + clampedPercent, + warningThreshold, + criticalThreshold, + mergedColors + ) + + return ( +
+
+ + + + +
+ + {formatPercent(clampedPercent)} + + {showCounts && ( + + {formatNumber(usedInodes)} + + )} +
+
+ {label && ( + {label} + )} + {showCounts && ( + + of {formatNumber(totalInodes)} + + )} +
+ ) +} + +/** + * Props for block gauge + */ +interface BlockGaugeProps extends Omit { + /** Used blocks */ + usedBlocks: number + /** Total blocks */ + totalBlocks: number + /** Show block counts (default: true) */ + showCounts?: boolean +} + +/** + * Block gauge showing block allocation + */ +export function BlockGauge({ + usedBlocks, + totalBlocks, + size = 140, + strokeWidth = 10, + warningThreshold = 75, + criticalThreshold = 90, + colors, + label = 'Blocks', + showCounts = true, + animationDuration = 500, +}: BlockGaugeProps) { + const percent = useMemo(() => { + if (totalBlocks <= 0) return 0 + return (usedBlocks / totalBlocks) * 100 + }, [usedBlocks, totalBlocks]) + + const mergedColors = { ...DEFAULT_COLORS, ...colors } + + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const center = size / 2 + const clampedPercent = Math.min(100, Math.max(0, percent)) + const strokeDashoffset = circumference * (1 - clampedPercent / 100) + + const strokeColor = getColorForPercent( + clampedPercent, + warningThreshold, + criticalThreshold, + mergedColors + ) + + return ( +
+
+ + + + +
+ + {formatPercent(clampedPercent)} + + {showCounts && ( + + {formatNumber(usedBlocks)} + + )} +
+
+ {label && ( + {label} + )} + {showCounts && ( + + of {formatNumber(totalBlocks)} + + )} +
+ ) +} + +/** + * Mini gauge for compact displays (e.g., in cards or tables) + */ +interface MiniGaugeProps { + percent: number + size?: number + strokeWidth?: number + warningThreshold?: number + criticalThreshold?: number + colors?: Partial +} + +export function MiniGauge({ + percent, + size = 40, + strokeWidth = 4, + warningThreshold = 75, + criticalThreshold = 90, + colors, +}: MiniGaugeProps) { + const mergedColors = { ...DEFAULT_COLORS, ...colors } + + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const center = size / 2 + const clampedPercent = Math.min(100, Math.max(0, percent)) + const strokeDashoffset = circumference * (1 - clampedPercent / 100) + + const strokeColor = getColorForPercent( + clampedPercent, + warningThreshold, + criticalThreshold, + mergedColors + ) + + return ( +
+ + + + + + {Math.round(clampedPercent)} + +
+ ) +} + +/** + * Props for cache hit rate gauge + */ +interface HitRateGaugeProps { + /** Number of cache hits */ + hits: number + /** Number of cache misses */ + misses: number + /** Size in pixels (default: 140) */ + size?: number + /** Stroke width (default: 10) */ + strokeWidth?: number + /** Label text (default: 'Hit Rate') */ + label?: string + /** Show hit/miss counts (default: true) */ + showCounts?: boolean + /** Animation duration in ms (default: 500) */ + animationDuration?: number +} + +/** + * Cache hit rate gauge - shows cache performance with inverted thresholds + * (higher is better, so green >= 80%, yellow >= 50%, red < 50%) + */ +export function HitRateGauge({ + hits, + misses, + size = 140, + strokeWidth = 10, + label = 'Hit Rate', + showCounts = true, + animationDuration = 500, +}: HitRateGaugeProps) { + const percent = useMemo(() => { + const total = hits + misses + if (total <= 0) return 0 + return (hits / total) * 100 + }, [hits, misses]) + + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const center = size / 2 + const clampedPercent = Math.min(100, Math.max(0, percent)) + const strokeDashoffset = circumference * (1 - clampedPercent / 100) + + // Custom color logic for hit rate (higher = better) + const strokeColor = + clampedPercent >= 80 + ? '#48bb78' // green (good) + : clampedPercent >= 50 + ? '#ed8936' // orange (warning) + : '#f56565' // red (bad) + + return ( +
+
+ + + + +
+ + {formatPercent(clampedPercent)} + + {showCounts && ( + + {formatNumber(hits)} / {formatNumber(hits + misses)} + + )} +
+
+ {label && ( + {label} + )} +
+ ) +} + +/** + * Props for journal usage gauge + */ +interface JournalGaugeProps { + /** Bytes written to journal */ + bytesWritten?: number + /** Available space in journal */ + availableSpace?: number + /** Total journal size (bytesWritten + availableSpace if not provided) */ + totalSize?: number + /** Journal state (e.g., 'active', 'flushing', 'idle') */ + state?: string + /** Number of commits */ + commitCount?: number + /** Number of active transactions */ + activeTxnCount?: number + /** Size in pixels (default: 140) */ + size?: number + /** Stroke width (default: 10) */ + strokeWidth?: number + /** Animation duration in ms (default: 500) */ + animationDuration?: number +} + +/** + * Journal usage gauge with state indicator + */ +export function JournalGauge({ + bytesWritten = 0, + availableSpace = 0, + totalSize, + state = 'unknown', + commitCount = 0, + activeTxnCount = 0, + size = 140, + strokeWidth = 10, + animationDuration = 500, +}: JournalGaugeProps) { + // Calculate utilization + const total = totalSize ?? (bytesWritten + availableSpace) + const percent = useMemo(() => { + if (total <= 0) return 0 + return ((total - availableSpace) / total) * 100 + }, [total, availableSpace]) + + const radius = (size - strokeWidth) / 2 + const circumference = 2 * Math.PI * radius + const center = size / 2 + const clampedPercent = Math.min(100, Math.max(0, percent)) + const strokeDashoffset = circumference * (1 - clampedPercent / 100) + + // Color based on utilization (higher = worse for journal) + const strokeColor = + clampedPercent >= 90 + ? '#f56565' // red (critical) + : clampedPercent >= 75 + ? '#ed8936' // orange (warning) + : '#48bb78' // green (ok) + + // State badge color + const stateColorMap: Record = { + active: 'bg-gfs-status-ok', + flushing: 'bg-gfs-status-warning', + idle: 'bg-gfs-status-info', + error: 'bg-gfs-status-error', + unknown: 'bg-gfs-text-muted', + } + const stateBgColor = stateColorMap[state.toLowerCase()] || stateColorMap.unknown + + return ( +
+
+ + + + +
+ + {formatPercent(clampedPercent)} + + + utilized + +
+
+ + {/* State badge */} +
+ + + {state} + +
+ + {/* Stats row */} +
+ {formatNumber(commitCount)} commits + {activeTxnCount > 0 && ( + + {activeTxnCount} active + + )} +
+
+ ) +} + +export default CircularGauge diff --git a/web/dashboard/src/components/gauges/index.ts b/web/dashboard/src/components/gauges/index.ts new file mode 100644 index 00000000..7b18aa02 --- /dev/null +++ b/web/dashboard/src/components/gauges/index.ts @@ -0,0 +1,5 @@ +/** + * Gauges module exports + */ + +export * from './CircularGauge' diff --git a/web/dashboard/src/components/index.ts b/web/dashboard/src/components/index.ts new file mode 100644 index 00000000..153828c0 --- /dev/null +++ b/web/dashboard/src/components/index.ts @@ -0,0 +1,9 @@ +/** + * Components module exports + */ + +export * from './charts' +export * from './gauges' +export * from './common' +export * from './modals' +export * from './panels' diff --git a/web/dashboard/src/components/modals/ConfirmDeleteModal.tsx b/web/dashboard/src/components/modals/ConfirmDeleteModal.tsx new file mode 100644 index 00000000..81fa6ff6 --- /dev/null +++ b/web/dashboard/src/components/modals/ConfirmDeleteModal.tsx @@ -0,0 +1,229 @@ +/** + * Reusable confirmation modal for destructive actions + * Includes type-to-confirm functionality for extra safety + */ + +import { useState } from 'react' +import { Modal } from '@/components/common/Modal' + +export interface ConfirmDeleteModalProps { + /** Whether the modal is open */ + isOpen: boolean + /** Callback when the modal should close */ + onClose: () => void + /** Callback when deletion is confirmed - should return a promise */ + onConfirm: () => Promise + /** Title for the modal */ + title?: string + /** Name of the item being deleted (used for type-to-confirm) */ + itemName: string + /** Type of item being deleted (e.g., "snapshot", "node") */ + itemType?: string + /** Additional warning message */ + warning?: string + /** Whether to require typing the name to confirm */ + requireTypeToConfirm?: boolean +} + +type ModalState = 'confirm' | 'deleting' | 'success' | 'error' + +/** + * ConfirmDeleteModal - Reusable delete confirmation with type-to-confirm + * + * IMPORTANT: To ensure proper state reset between uses, pass a unique `key` + * prop based on the item being deleted (e.g., key={snapshot?.id}). + * This causes React to remount the component with fresh state. + */ +export function ConfirmDeleteModal({ + isOpen, + onClose, + onConfirm, + title = 'Confirm Delete', + itemName, + itemType = 'item', + warning, + requireTypeToConfirm = true, +}: ConfirmDeleteModalProps) { + const [state, setState] = useState('confirm') + const [confirmText, setConfirmText] = useState('') + const [errorMessage, setErrorMessage] = useState('') + + const handleClose = () => { + onClose() + } + + const isConfirmEnabled = !requireTypeToConfirm || confirmText === itemName + + const handleDelete = async () => { + if (!isConfirmEnabled) return + + setState('deleting') + setErrorMessage('') + + try { + await onConfirm() + setState('success') + + // Auto-close after success + setTimeout(() => { + handleClose() + }, 1500) + } catch (err) { + setState('error') + setErrorMessage(err instanceof Error ? err.message : 'Failed to delete') + } + } + + const renderContent = () => { + switch (state) { + case 'deleting': + return ( +
+
+

Deleting {itemType}...

+
+ ) + + case 'success': + return ( +
+
+ + + +
+

Deleted successfully

+
+ ) + + case 'error': + return ( +
+
+
+
+ + + +
+
+

Delete failed

+

{errorMessage}

+
+
+
+ +
+ ) + + default: + return ( +
+ {/* Warning icon and message */} +
+
+ + + +
+
+

+ Are you sure you want to delete{' '} + "{itemName}"? +

+

+ This action cannot be undone. +

+
+
+ + {/* Additional warning */} + {warning && ( +
+

{warning}

+
+ )} + + {/* Type to confirm */} + {requireTypeToConfirm && ( +
+ + setConfirmText(e.target.value)} + placeholder={itemName} + className="w-full px-3 py-2 bg-gfs-bg-primary border border-gfs-border rounded-md text-gfs-text-primary placeholder-gfs-text-muted focus:outline-none focus:ring-2 focus:ring-gfs-status-error focus:border-transparent" + autoComplete="off" + spellCheck={false} + /> +
+ )} +
+ ) + } + } + + const renderFooter = () => { + if (state === 'deleting' || state === 'success') { + return null + } + + if (state === 'error') { + return ( + + ) + } + + return ( + <> + + + + ) + } + + return ( + + {renderContent()} + + ) +} + +export default ConfirmDeleteModal diff --git a/web/dashboard/src/components/modals/CreateSnapshotModal.tsx b/web/dashboard/src/components/modals/CreateSnapshotModal.tsx new file mode 100644 index 00000000..10441ca4 --- /dev/null +++ b/web/dashboard/src/components/modals/CreateSnapshotModal.tsx @@ -0,0 +1,259 @@ +/** + * Modal for creating a new snapshot + */ + +import { useState, useCallback } from 'react' +import { Modal } from '@/components/common/Modal' +import { api, ApiError } from '@/api' +import type { CreateSnapshotRequest } from '@/api' + +export interface CreateSnapshotModalProps { + isOpen: boolean + onClose: () => void + onSuccess: () => void +} + +type ModalState = 'form' | 'submitting' | 'success' | 'error' + +export function CreateSnapshotModal({ + isOpen, + onClose, + onSuccess, +}: CreateSnapshotModalProps) { + const [state, setState] = useState('form') + const [name, setName] = useState('') + const [description, setDescription] = useState('') + const [retentionPolicy, setRetentionPolicy] = useState('') + const [errorMessage, setErrorMessage] = useState('') + + // Reset form when modal opens/closes + const resetForm = useCallback(() => { + setState('form') + setName('') + setDescription('') + setRetentionPolicy('') + setErrorMessage('') + }, []) + + const handleClose = () => { + resetForm() + onClose() + } + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault() + + if (!name.trim()) { + setErrorMessage('Snapshot name is required') + return + } + + setState('submitting') + setErrorMessage('') + + try { + const request: CreateSnapshotRequest = { + name: name.trim(), + } + + if (description.trim()) { + request.description = description.trim() + } + + if (retentionPolicy.trim()) { + request.retention_policy = retentionPolicy.trim() + } + + await api.createSnapshot(request) + setState('success') + + // Auto-close after success + setTimeout(() => { + handleClose() + onSuccess() + }, 1500) + } catch (err) { + setState('error') + if (err instanceof ApiError) { + setErrorMessage(err.message) + } else { + setErrorMessage('Failed to create snapshot') + } + } + } + + const renderContent = () => { + switch (state) { + case 'submitting': + return ( +
+
+

Creating snapshot...

+

This may take a moment

+
+ ) + + case 'success': + return ( +
+
+ + + +
+

Snapshot created successfully!

+

"{name}"

+
+ ) + + case 'error': + return ( +
+
+
+
+ + + +
+
+

Failed to create snapshot

+

{errorMessage}

+
+
+
+ +
+ ) + + default: + return ( +
+ {/* Name field */} +
+ + setName(e.target.value)} + placeholder="e.g., pre-upgrade-backup" + className="w-full px-3 py-2 bg-gfs-bg-primary border border-gfs-border rounded-md text-gfs-text-primary placeholder-gfs-text-muted focus:outline-none focus:ring-2 focus:ring-gfs-accent-primary focus:border-transparent" + autoFocus + required + /> +

+ A descriptive name for this snapshot +

+
+ + {/* Description field */} +
+ +