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