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