1package server
  2
  3import (
  4	"context"
  5	"fmt"
  6	"log/slog"
  7	"net"
  8	"net/http"
  9	"net/url"
 10	"os/user"
 11	"runtime"
 12	"strings"
 13
 14	"github.com/charmbracelet/crush/internal/app"
 15	"github.com/charmbracelet/crush/internal/config"
 16	"github.com/charmbracelet/crush/internal/csync"
 17)
 18
 19// ErrServerClosed is returned when the server is closed.
 20var ErrServerClosed = http.ErrServerClosed
 21
 22// InstanceState represents the state of a running [app.App] instance.
 23type InstanceState uint8
 24
 25const (
 26	// InstanceStateCreated indicates that the instance has been created but not yet started.
 27	InstanceStateCreated InstanceState = iota
 28	// InstanceStateStarted indicates that the instance is currently running.
 29	InstanceStateStarted
 30	// InstanceStateStopped indicates that the instance has been stopped.
 31	InstanceStateStopped
 32)
 33
 34// Instance represents a running [app.App] instance with its associated
 35// resources and state.
 36type Instance struct {
 37	*app.App
 38	State InstanceState
 39	ln    net.Listener
 40	cfg   *config.Config
 41	id    string
 42	path  string
 43}
 44
 45// ParseHostURL parses a host URL into a [url.URL].
 46func ParseHostURL(host string) (*url.URL, error) {
 47	proto, addr, ok := strings.Cut(host, "://")
 48	if !ok {
 49		return nil, fmt.Errorf("invalid host format: %s", host)
 50	}
 51
 52	var basePath string
 53	if proto == "tcp" {
 54		parsed, err := url.Parse("tcp://" + addr)
 55		if err != nil {
 56			return nil, fmt.Errorf("invalid tcp address: %v", err)
 57		}
 58		addr = parsed.Host
 59		basePath = parsed.Path
 60	}
 61	return &url.URL{
 62		Scheme: proto,
 63		Host:   addr,
 64		Path:   basePath,
 65	}, nil
 66}
 67
 68// DefaultHost returns the default server host.
 69func DefaultHost() string {
 70	sock := "crush.sock"
 71	usr, err := user.Current()
 72	if err == nil && usr.Uid != "" {
 73		sock = fmt.Sprintf("crush-%s.sock", usr.Uid)
 74	}
 75	if runtime.GOOS == "windows" {
 76		return fmt.Sprintf("npipe:////./pipe/%s", sock)
 77	}
 78	return fmt.Sprintf("unix:///tmp/%s", sock)
 79}
 80
 81// Server represents a Crush server instance bound to a specific address.
 82type Server struct {
 83	// Addr can be a TCP address, a Unix socket path, or a Windows named pipe.
 84	Addr    string
 85	network string
 86
 87	h   *http.Server
 88	ln  net.Listener
 89	ctx context.Context
 90
 91	// instances is a map of running applications managed by the server.
 92	instances *csync.Map[string, *Instance]
 93	cfg       *config.Config
 94	logger    *slog.Logger
 95}
 96
 97// SetLogger sets the logger for the server.
 98func (s *Server) SetLogger(logger *slog.Logger) {
 99	s.logger = logger
100}
101
102// DefaultServer returns a new [Server] instance with the default address.
103func DefaultServer(cfg *config.Config) *Server {
104	hostURL, err := ParseHostURL(DefaultHost())
105	if err != nil {
106		panic("invalid default host")
107	}
108	return NewServer(cfg, hostURL.Scheme, hostURL.Host)
109}
110
111// NewServer is a helper to create a new [Server] instance with the given
112// address. On Windows, if the address is not a "tcp" address, it will be
113// converted to a named pipe format.
114func NewServer(cfg *config.Config, network, address string) *Server {
115	s := new(Server)
116	s.Addr = address
117	s.network = network
118	s.cfg = cfg
119	s.instances = csync.NewMap[string, *Instance]()
120	s.ctx = context.Background()
121
122	var p http.Protocols
123	p.SetHTTP1(true)
124	p.SetUnencryptedHTTP2(true)
125	c := &controllerV1{Server: s}
126	mux := http.NewServeMux()
127	mux.HandleFunc("GET /v1/health", c.handleGetHealth)
128	mux.HandleFunc("GET /v1/version", c.handleGetVersion)
129	mux.HandleFunc("GET /v1/config", c.handleGetConfig)
130	mux.HandleFunc("POST /v1/control", c.handlePostControl)
131	mux.HandleFunc("GET /v1/instances", c.handleGetInstances)
132	mux.HandleFunc("POST /v1/instances", c.handlePostInstances)
133	mux.HandleFunc("DELETE /v1/instances/{id}", c.handleDeleteInstances)
134	mux.HandleFunc("GET /v1/instances/{id}", c.handleGetInstance)
135	mux.HandleFunc("GET /v1/instances/{id}/config", c.handleGetInstanceConfig)
136	mux.HandleFunc("GET /v1/instances/{id}/events", c.handleGetInstanceEvents)
137	mux.HandleFunc("GET /v1/instances/{id}/sessions", c.handleGetInstanceSessions)
138	mux.HandleFunc("POST /v1/instances/{id}/sessions", c.handlePostInstanceSessions)
139	mux.HandleFunc("GET /v1/instances/{id}/sessions/{sid}", c.handleGetInstanceSession)
140	mux.HandleFunc("GET /v1/instances/{id}/sessions/{sid}/history", c.handleGetInstanceSessionHistory)
141	mux.HandleFunc("GET /v1/instances/{id}/sessions/{sid}/messages", c.handleGetInstanceSessionMessages)
142	mux.HandleFunc("GET /v1/instances/{id}/lsps", c.handleGetInstanceLSPs)
143	mux.HandleFunc("GET /v1/instances/{id}/lsps/{lsp}/diagnostics", c.handleGetInstanceLSPDiagnostics)
144	mux.HandleFunc("GET /v1/instances/{id}/permissions/skip", c.handleGetInstancePermissionsSkip)
145	mux.HandleFunc("POST /v1/instances/{id}/permissions/skip", c.handlePostInstancePermissionsSkip)
146	mux.HandleFunc("POST /v1/instances/{id}/permissions/grant", c.handlePostInstancePermissionsGrant)
147	mux.HandleFunc("GET /v1/instances/{id}/agent", c.handleGetInstanceAgent)
148	mux.HandleFunc("POST /v1/instances/{id}/agent", c.handlePostInstanceAgent)
149	mux.HandleFunc("POST /v1/instances/{id}/agent/init", c.handlePostInstanceAgentInit)
150	mux.HandleFunc("POST /v1/instances/{id}/agent/update", c.handlePostInstanceAgentUpdate)
151	mux.HandleFunc("GET /v1/instances/{id}/agent/sessions/{sid}", c.handleGetInstanceAgentSession)
152	mux.HandleFunc("POST /v1/instances/{id}/agent/sessions/{sid}/cancel", c.handlePostInstanceAgentSessionCancel)
153	mux.HandleFunc("GET /v1/instances/{id}/agent/sessions/{sid}/prompts/queued", c.handleGetInstanceAgentSessionPromptQueued)
154	mux.HandleFunc("POST /v1/instances/{id}/agent/sessions/{sid}/prompts/clear", c.handlePostInstanceAgentSessionPromptClear)
155	mux.HandleFunc("POST /v1/instances/{id}/agent/sessions/{sid}/summarize", c.handleGetInstanceAgentSessionSummarize)
156	s.h = &http.Server{
157		Protocols: &p,
158		Handler:   s.loggingHandler(mux),
159	}
160	if network == "tcp" {
161		s.h.Addr = address
162	}
163	return s
164}
165
166// Serve accepts incoming connections on the listener.
167func (s *Server) Serve(ln net.Listener) error {
168	return s.h.Serve(ln)
169}
170
171// ListenAndServe starts the server and begins accepting connections.
172func (s *Server) ListenAndServe() error {
173	if s.ln != nil {
174		return fmt.Errorf("server already started")
175	}
176	ln, err := listen(s.network, s.Addr)
177	if err != nil {
178		return fmt.Errorf("failed to listen on %s: %w", s.Addr, err)
179	}
180	return s.Serve(ln)
181}
182
183func (s *Server) closeListener() {
184	if s.ln != nil {
185		s.ln.Close()
186		s.ln = nil
187	}
188}
189
190// Close force close all listeners and connections.
191func (s *Server) Close() error {
192	defer func() { s.closeListener() }()
193	return s.h.Close()
194}
195
196// Shutdown gracefully shuts down the server without interrupting active
197// connections. It stops accepting new connections and waits for existing
198// connections to finish.
199func (s *Server) Shutdown(ctx context.Context) error {
200	defer func() { s.closeListener() }()
201	return s.h.Shutdown(ctx)
202}
203
204func (s *Server) logDebug(r *http.Request, msg string, args ...any) {
205	if s.logger != nil {
206		s.logger.With(
207			slog.String("method", r.Method),
208			slog.String("url", r.URL.String()),
209			slog.String("remote_addr", r.RemoteAddr),
210		).Debug(msg, args...)
211	}
212}
213
214func (s *Server) logError(r *http.Request, msg string, args ...any) {
215	if s.logger != nil {
216		s.logger.With(
217			slog.String("method", r.Method),
218			slog.String("url", r.URL.String()),
219			slog.String("remote_addr", r.RemoteAddr),
220		).Error(msg, args...)
221	}
222}