| 1 |
// Package registry provides a registry for managing multiple language server |
| 2 |
// instances. |
| 3 |
package registry |
| 4 |
|
| 5 |
import ( |
| 6 |
"context" |
| 7 |
"fmt" |
| 8 |
"log/slog" |
| 9 |
"maps" |
| 10 |
"os" |
| 11 |
"path/filepath" |
| 12 |
"strings" |
| 13 |
"sync" |
| 14 |
|
| 15 |
"github.com/charmbracelet/x/powernap/pkg/config" |
| 16 |
"github.com/charmbracelet/x/powernap/pkg/lsp" |
| 17 |
"github.com/charmbracelet/x/powernap/pkg/lsp/protocol" |
| 18 |
) |
| 19 |
|
| 20 |
// Registry manages multiple language server instances. |
| 21 |
type Registry struct { |
| 22 |
mu sync.RWMutex |
| 23 |
clients map[string]*lsp.Client |
| 24 |
configs map[string]*config.ServerConfig |
| 25 |
logger *slog.Logger |
| 26 |
} |
| 27 |
|
| 28 |
// New creates a new registry. |
| 29 |
func New() *Registry { |
| 30 |
return &Registry{ |
| 31 |
clients: make(map[string]*lsp.Client), |
| 32 |
configs: make(map[string]*config.ServerConfig), |
| 33 |
logger: slog.Default(), |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
// NewWithLogger creates a new registry with a custom logger. |
| 38 |
func NewWithLogger(logger *slog.Logger) *Registry { |
| 39 |
return &Registry{ |
| 40 |
clients: make(map[string]*lsp.Client), |
| 41 |
configs: make(map[string]*config.ServerConfig), |
| 42 |
logger: logger, |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
// LoadConfig loads server configurations from a config manager. |
| 47 |
func (r *Registry) LoadConfig(cfg *config.Manager) error { |
| 48 |
r.mu.Lock() |
| 49 |
defer r.mu.Unlock() |
| 50 |
servers := cfg.GetServers() |
| 51 |
maps.Copy(r.configs, servers) |
| 52 |
return nil |
| 53 |
} |
| 54 |
|
| 55 |
// StartServer starts a language server for the given name and project path. |
| 56 |
func (r *Registry) StartServer(ctx context.Context, name string, projectPath string) (*lsp.Client, error) { |
| 57 |
r.mu.Lock() |
| 58 |
defer r.mu.Unlock() |
| 59 |
|
| 60 |
// Check if server is already running |
| 61 |
if client, exists := r.clients[name]; exists { |
| 62 |
return client, nil |
| 63 |
} |
| 64 |
|
| 65 |
// Get server configuration |
| 66 |
serverCfg, exists := r.configs[name] |
| 67 |
if !exists { |
| 68 |
return nil, fmt.Errorf("no configuration found for server: %s", name) |
| 69 |
} |
| 70 |
|
| 71 |
// Find project root |
| 72 |
rootPath := r.findProjectRoot(projectPath, serverCfg.RootMarkers) |
| 73 |
if rootPath == "" { |
| 74 |
// Check if server supports single file mode |
| 75 |
if !serverCfg.SingleFileSupport { |
| 76 |
return nil, fmt.Errorf("language server %s requires a project root with one of: %v", name, serverCfg.RootMarkers) |
| 77 |
} |
| 78 |
rootPath = projectPath |
| 79 |
} |
| 80 |
|
| 81 |
// Create workspace folders |
| 82 |
workspaceFolders := []protocol.WorkspaceFolder{ |
| 83 |
{ |
| 84 |
URI: "file://" + rootPath, |
| 85 |
Name: filepath.Base(rootPath), |
| 86 |
}, |
| 87 |
} |
| 88 |
|
| 89 |
// Create client configuration |
| 90 |
clientCfg := lsp.ClientConfig{ |
| 91 |
Command: serverCfg.Command, |
| 92 |
Args: serverCfg.Args, |
| 93 |
RootURI: "file://" + rootPath, |
| 94 |
WorkspaceFolders: workspaceFolders, |
| 95 |
InitOptions: serverCfg.InitOptions, |
| 96 |
Settings: serverCfg.Settings, |
| 97 |
Environment: serverCfg.Environment, |
| 98 |
} |
| 99 |
|
| 100 |
// Create and initialize client |
| 101 |
client, err := lsp.NewClient(clientCfg) |
| 102 |
if err != nil { |
| 103 |
return nil, fmt.Errorf("failed to create client: %w", err) |
| 104 |
} |
| 105 |
|
| 106 |
// Initialize the client |
| 107 |
if err := client.Initialize(ctx, serverCfg.EnableSnippets); err != nil { |
| 108 |
return nil, fmt.Errorf("failed to initialize client: %w", err) |
| 109 |
} |
| 110 |
|
| 111 |
// Store the client |
| 112 |
r.clients[name] = client |
| 113 |
|
| 114 |
r.logger.Info("Started language server", "name", name, "root", rootPath) |
| 115 |
return client, nil |
| 116 |
} |
| 117 |
|
| 118 |
// StopServer stops a running language server. |
| 119 |
func (r *Registry) StopServer(ctx context.Context, name string) error { |
| 120 |
r.mu.Lock() |
| 121 |
defer r.mu.Unlock() |
| 122 |
|
| 123 |
client, exists := r.clients[name] |
| 124 |
if !exists { |
| 125 |
return fmt.Errorf("server not running: %s", name) |
| 126 |
} |
| 127 |
|
| 128 |
// Shutdown the client |
| 129 |
if err := client.Shutdown(ctx); err != nil { |
| 130 |
r.logger.Error("Failed to shutdown server", "name", name, "error", err) |
| 131 |
} |
| 132 |
|
| 133 |
// Send exit notification |
| 134 |
if err := client.Exit(); err != nil { |
| 135 |
r.logger.Error("Failed to exit server", "name", name, "error", err) |
| 136 |
} |
| 137 |
|
| 138 |
// Remove from registry |
| 139 |
delete(r.clients, name) |
| 140 |
|
| 141 |
r.logger.Info("Stopped language server", "name", name) |
| 142 |
return nil |
| 143 |
} |
| 144 |
|
| 145 |
// RestartServer restarts a language server. |
| 146 |
func (r *Registry) RestartServer(ctx context.Context, name string, projectPath string) (*lsp.Client, error) { |
| 147 |
// Stop the server if it's running |
| 148 |
if err := r.StopServer(ctx, name); err != nil { |
| 149 |
// Ignore error if server wasn't running |
| 150 |
r.logger.Debug("Server was not running", "name", name) |
| 151 |
} |
| 152 |
|
| 153 |
// Start the server |
| 154 |
return r.StartServer(ctx, name, projectPath) |
| 155 |
} |
| 156 |
|
| 157 |
// GetClient returns a running client by name. |
| 158 |
func (r *Registry) GetClient(name string) (*lsp.Client, bool) { |
| 159 |
r.mu.RLock() |
| 160 |
defer r.mu.RUnlock() |
| 161 |
|
| 162 |
client, exists := r.clients[name] |
| 163 |
return client, exists |
| 164 |
} |
| 165 |
|
| 166 |
// GetClientsForFile returns all appropriate clients for the given file. |
| 167 |
// This allows multiple language servers to handle the same file type (e.g., gopls and golangci-lint for Go files). |
| 168 |
func (r *Registry) GetClientsForFile(ctx context.Context, filePath string) ([]*lsp.Client, error) { |
| 169 |
// Convert to absolute path |
| 170 |
absPath, err := filepath.Abs(filePath) |
| 171 |
if err != nil { |
| 172 |
return nil, fmt.Errorf("failed to get absolute path: %w", err) |
| 173 |
} |
| 174 |
|
| 175 |
// Detect language from file |
| 176 |
language := string(lsp.DetectLanguage(absPath)) |
| 177 |
if language == "" { |
| 178 |
return nil, fmt.Errorf("unsupported file type: %s", filepath.Ext(absPath)) |
| 179 |
} |
| 180 |
|
| 181 |
r.mu.RLock() |
| 182 |
|
| 183 |
// Find all servers that support this language |
| 184 |
var serverNames []string |
| 185 |
for name, cfg := range r.configs { |
| 186 |
for _, ft := range cfg.FileTypes { |
| 187 |
// Match by extension or language ID |
| 188 |
ext := filepath.Ext(absPath) |
| 189 |
if ft == language || ft == strings.TrimPrefix(ext, ".") || "."+ft == ext { |
| 190 |
serverNames = append(serverNames, name) |
| 191 |
break |
| 192 |
} |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
r.mu.RUnlock() |
| 197 |
|
| 198 |
if len(serverNames) == 0 { |
| 199 |
return nil, fmt.Errorf("no language servers found for language: %s", language) |
| 200 |
} |
| 201 |
|
| 202 |
var clients []*lsp.Client |
| 203 |
projectDir := filepath.Dir(absPath) |
| 204 |
|
| 205 |
// Start or get each server |
| 206 |
for _, serverName := range serverNames { |
| 207 |
// Check if server is already running |
| 208 |
if client, exists := r.GetClient(serverName); exists { |
| 209 |
clients = append(clients, client) |
| 210 |
} else { |
| 211 |
// Start the server |
| 212 |
client, err := r.StartServer(ctx, serverName, projectDir) |
| 213 |
if err != nil { |
| 214 |
r.logger.Warn("Failed to start server", "name", serverName, "error", err) |
| 215 |
continue |
| 216 |
} |
| 217 |
clients = append(clients, client) |
| 218 |
} |
| 219 |
} |
| 220 |
|
| 221 |
if len(clients) == 0 { |
| 222 |
return nil, fmt.Errorf("failed to start any language servers for language: %s", language) |
| 223 |
} |
| 224 |
|
| 225 |
return clients, nil |
| 226 |
} |
| 227 |
|
| 228 |
// GetClientForFile returns a single appropriate client for the given file. |
| 229 |
// This is a convenience method that returns the first available client. |
| 230 |
// For multiple servers support, use GetClientsForFile instead. |
| 231 |
func (r *Registry) GetClientForFile(ctx context.Context, filePath string) (*lsp.Client, error) { |
| 232 |
clients, err := r.GetClientsForFile(ctx, filePath) |
| 233 |
if err != nil { |
| 234 |
return nil, err |
| 235 |
} |
| 236 |
|
| 237 |
if len(clients) == 0 { |
| 238 |
return nil, fmt.Errorf("no clients available") |
| 239 |
} |
| 240 |
|
| 241 |
return clients[0], nil |
| 242 |
} |
| 243 |
|
| 244 |
// ListClients returns a list of running clients. |
| 245 |
func (r *Registry) ListClients() []string { |
| 246 |
r.mu.RLock() |
| 247 |
defer r.mu.RUnlock() |
| 248 |
|
| 249 |
names := make([]string, 0, len(r.clients)) |
| 250 |
for name := range r.clients { |
| 251 |
names = append(names, name) |
| 252 |
} |
| 253 |
|
| 254 |
return names |
| 255 |
} |
| 256 |
|
| 257 |
// StopAll stops all running language servers. |
| 258 |
func (r *Registry) StopAll(ctx context.Context) error { |
| 259 |
r.mu.Lock() |
| 260 |
defer r.mu.Unlock() |
| 261 |
|
| 262 |
var errs []error |
| 263 |
|
| 264 |
for name, client := range r.clients { |
| 265 |
if err := client.Shutdown(ctx); err != nil { |
| 266 |
errs = append(errs, fmt.Errorf("failed to shutdown %s: %w", name, err)) |
| 267 |
} |
| 268 |
|
| 269 |
if err := client.Exit(); err != nil { |
| 270 |
errs = append(errs, fmt.Errorf("failed to exit %s: %w", name, err)) |
| 271 |
} |
| 272 |
} |
| 273 |
|
| 274 |
// Clear all clients |
| 275 |
r.clients = make(map[string]*lsp.Client) |
| 276 |
|
| 277 |
if len(errs) > 0 { |
| 278 |
return fmt.Errorf("errors stopping servers: %v", errs) |
| 279 |
} |
| 280 |
|
| 281 |
return nil |
| 282 |
} |
| 283 |
|
| 284 |
// findProjectRoot finds the project root based on root markers. |
| 285 |
func (r *Registry) findProjectRoot(startPath string, rootMarkers []string) string { |
| 286 |
currentPath := startPath |
| 287 |
|
| 288 |
for { |
| 289 |
// Check for root markers |
| 290 |
for _, marker := range rootMarkers { |
| 291 |
markerPath := filepath.Join(currentPath, marker) |
| 292 |
if fileExists(markerPath) { |
| 293 |
return currentPath |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
// Move up one directory |
| 298 |
parentPath := filepath.Dir(currentPath) |
| 299 |
if parentPath == currentPath { |
| 300 |
// Reached filesystem root |
| 301 |
break |
| 302 |
} |
| 303 |
|
| 304 |
currentPath = parentPath |
| 305 |
} |
| 306 |
|
| 307 |
return "" |
| 308 |
} |
| 309 |
|
| 310 |
// fileExists checks if a file exists. |
| 311 |
func fileExists(path string) bool { |
| 312 |
// Use os.Stat to check if the file/directory exists |
| 313 |
if _, err := os.Stat(path); err != nil { |
| 314 |
return false |
| 315 |
} |
| 316 |
return true |
| 317 |
} |