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