cli/pkg/php/services.go
Snider 96d394435a feat(php): implement Laravel development environment support
Add pkg/php for Laravel/PHP development:
- Auto-detect Laravel project and required services
- FrankenPHP/Octane, Vite, Horizon, Reverb, Redis orchestration
- mkcert SSL integration for local HTTPS
- Unified log streaming with colored service prefixes
- Graceful shutdown handling

CLI commands:
- core php dev - start all services
- core php logs - unified/per-service logs
- core php stop - stop all services
- core php status - show service status
- core php ssl - setup SSL certificates

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-28 19:14:06 +00:00

473 lines
9.4 KiB
Go

// Package php provides Laravel/PHP development environment management.
package php
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
)
// Service represents a managed development service.
type Service interface {
// Name returns the service name.
Name() string
// Start starts the service.
Start(ctx context.Context) error
// Stop stops the service gracefully.
Stop() error
// Logs returns a reader for the service logs.
Logs(follow bool) (io.ReadCloser, error)
// Status returns the current service status.
Status() ServiceStatus
}
// ServiceStatus represents the status of a service.
type ServiceStatus struct {
Name string
Running bool
PID int
Port int
Error error
}
// baseService provides common functionality for all services.
type baseService struct {
name string
port int
dir string
cmd *exec.Cmd
logFile *os.File
logPath string
mu sync.RWMutex
running bool
lastError error
}
func (s *baseService) Name() string {
return s.name
}
func (s *baseService) Status() ServiceStatus {
s.mu.RLock()
defer s.mu.RUnlock()
status := ServiceStatus{
Name: s.name,
Running: s.running,
Port: s.port,
Error: s.lastError,
}
if s.cmd != nil && s.cmd.Process != nil {
status.PID = s.cmd.Process.Pid
}
return status
}
func (s *baseService) Logs(follow bool) (io.ReadCloser, error) {
if s.logPath == "" {
return nil, fmt.Errorf("no log file available for %s", s.name)
}
file, err := os.Open(s.logPath)
if err != nil {
return nil, fmt.Errorf("failed to open log file: %w", err)
}
if !follow {
return file, nil
}
// For follow mode, return a tailing reader
return newTailReader(file), nil
}
func (s *baseService) startProcess(ctx context.Context, cmdName string, args []string, env []string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.running {
return fmt.Errorf("%s is already running", s.name)
}
// Create log file
logDir := filepath.Join(s.dir, ".core", "logs")
if err := os.MkdirAll(logDir, 0755); err != nil {
return fmt.Errorf("failed to create log directory: %w", err)
}
s.logPath = filepath.Join(logDir, fmt.Sprintf("%s.log", strings.ToLower(s.name)))
logFile, err := os.OpenFile(s.logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return fmt.Errorf("failed to create log file: %w", err)
}
s.logFile = logFile
// Create command
s.cmd = exec.CommandContext(ctx, cmdName, args...)
s.cmd.Dir = s.dir
s.cmd.Stdout = logFile
s.cmd.Stderr = logFile
s.cmd.Env = append(os.Environ(), env...)
// Set process group for clean shutdown
s.cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
if err := s.cmd.Start(); err != nil {
logFile.Close()
s.lastError = err
return fmt.Errorf("failed to start %s: %w", s.name, err)
}
s.running = true
s.lastError = nil
// Monitor process in background
go func() {
err := s.cmd.Wait()
s.mu.Lock()
s.running = false
if err != nil {
s.lastError = err
}
if s.logFile != nil {
s.logFile.Close()
}
s.mu.Unlock()
}()
return nil
}
func (s *baseService) stopProcess() error {
s.mu.Lock()
defer s.mu.Unlock()
if !s.running || s.cmd == nil || s.cmd.Process == nil {
return nil
}
// Send SIGTERM to process group
pgid, err := syscall.Getpgid(s.cmd.Process.Pid)
if err == nil {
syscall.Kill(-pgid, syscall.SIGTERM)
} else {
s.cmd.Process.Signal(syscall.SIGTERM)
}
// Wait for graceful shutdown with timeout
done := make(chan struct{})
go func() {
s.cmd.Wait()
close(done)
}()
select {
case <-done:
// Process exited gracefully
case <-time.After(5 * time.Second):
// Force kill
if pgid, err := syscall.Getpgid(s.cmd.Process.Pid); err == nil {
syscall.Kill(-pgid, syscall.SIGKILL)
} else {
s.cmd.Process.Kill()
}
}
s.running = false
return nil
}
// FrankenPHPService manages the FrankenPHP/Octane server.
type FrankenPHPService struct {
baseService
https bool
httpsPort int
certFile string
keyFile string
}
// NewFrankenPHPService creates a new FrankenPHP service.
func NewFrankenPHPService(dir string, opts FrankenPHPOptions) *FrankenPHPService {
port := opts.Port
if port == 0 {
port = 8000
}
httpsPort := opts.HTTPSPort
if httpsPort == 0 {
httpsPort = 443
}
return &FrankenPHPService{
baseService: baseService{
name: "FrankenPHP",
port: port,
dir: dir,
},
https: opts.HTTPS,
httpsPort: httpsPort,
certFile: opts.CertFile,
keyFile: opts.KeyFile,
}
}
// FrankenPHPOptions configures the FrankenPHP service.
type FrankenPHPOptions struct {
Port int
HTTPSPort int
HTTPS bool
CertFile string
KeyFile string
}
func (s *FrankenPHPService) Start(ctx context.Context) error {
args := []string{
"artisan", "octane:start",
"--server=frankenphp",
fmt.Sprintf("--port=%d", s.port),
"--no-interaction",
}
if s.https && s.certFile != "" && s.keyFile != "" {
args = append(args,
fmt.Sprintf("--https-port=%d", s.httpsPort),
fmt.Sprintf("--https-certificate=%s", s.certFile),
fmt.Sprintf("--https-certificate-key=%s", s.keyFile),
)
}
return s.startProcess(ctx, "php", args, nil)
}
func (s *FrankenPHPService) Stop() error {
return s.stopProcess()
}
// ViteService manages the Vite development server.
type ViteService struct {
baseService
packageManager string
}
// NewViteService creates a new Vite service.
func NewViteService(dir string, opts ViteOptions) *ViteService {
port := opts.Port
if port == 0 {
port = 5173
}
pm := opts.PackageManager
if pm == "" {
pm = DetectPackageManager(dir)
}
return &ViteService{
baseService: baseService{
name: "Vite",
port: port,
dir: dir,
},
packageManager: pm,
}
}
// ViteOptions configures the Vite service.
type ViteOptions struct {
Port int
PackageManager string
}
func (s *ViteService) Start(ctx context.Context) error {
var cmdName string
var args []string
switch s.packageManager {
case "bun":
cmdName = "bun"
args = []string{"run", "dev"}
case "pnpm":
cmdName = "pnpm"
args = []string{"run", "dev"}
case "yarn":
cmdName = "yarn"
args = []string{"dev"}
default:
cmdName = "npm"
args = []string{"run", "dev"}
}
return s.startProcess(ctx, cmdName, args, nil)
}
func (s *ViteService) Stop() error {
return s.stopProcess()
}
// HorizonService manages Laravel Horizon.
type HorizonService struct {
baseService
}
// NewHorizonService creates a new Horizon service.
func NewHorizonService(dir string) *HorizonService {
return &HorizonService{
baseService: baseService{
name: "Horizon",
port: 0, // Horizon doesn't expose a port directly
dir: dir,
},
}
}
func (s *HorizonService) Start(ctx context.Context) error {
return s.startProcess(ctx, "php", []string{"artisan", "horizon"}, nil)
}
func (s *HorizonService) Stop() error {
// Horizon has its own terminate command
cmd := exec.Command("php", "artisan", "horizon:terminate")
cmd.Dir = s.dir
cmd.Run() // Ignore errors, will also kill via signal
return s.stopProcess()
}
// ReverbService manages Laravel Reverb WebSocket server.
type ReverbService struct {
baseService
}
// NewReverbService creates a new Reverb service.
func NewReverbService(dir string, opts ReverbOptions) *ReverbService {
port := opts.Port
if port == 0 {
port = 8080
}
return &ReverbService{
baseService: baseService{
name: "Reverb",
port: port,
dir: dir,
},
}
}
// ReverbOptions configures the Reverb service.
type ReverbOptions struct {
Port int
}
func (s *ReverbService) Start(ctx context.Context) error {
args := []string{
"artisan", "reverb:start",
fmt.Sprintf("--port=%d", s.port),
}
return s.startProcess(ctx, "php", args, nil)
}
func (s *ReverbService) Stop() error {
return s.stopProcess()
}
// RedisService manages a local Redis server.
type RedisService struct {
baseService
configFile string
}
// NewRedisService creates a new Redis service.
func NewRedisService(dir string, opts RedisOptions) *RedisService {
port := opts.Port
if port == 0 {
port = 6379
}
return &RedisService{
baseService: baseService{
name: "Redis",
port: port,
dir: dir,
},
configFile: opts.ConfigFile,
}
}
// RedisOptions configures the Redis service.
type RedisOptions struct {
Port int
ConfigFile string
}
func (s *RedisService) Start(ctx context.Context) error {
args := []string{
"--port", fmt.Sprintf("%d", s.port),
"--daemonize", "no",
}
if s.configFile != "" {
args = []string{s.configFile}
args = append(args, "--port", fmt.Sprintf("%d", s.port), "--daemonize", "no")
}
return s.startProcess(ctx, "redis-server", args, nil)
}
func (s *RedisService) Stop() error {
// Try graceful shutdown via redis-cli
cmd := exec.Command("redis-cli", "-p", fmt.Sprintf("%d", s.port), "shutdown", "nosave")
cmd.Run() // Ignore errors
return s.stopProcess()
}
// tailReader wraps a file and provides tailing functionality.
type tailReader struct {
file *os.File
reader *bufio.Reader
closed bool
mu sync.RWMutex
}
func newTailReader(file *os.File) *tailReader {
return &tailReader{
file: file,
reader: bufio.NewReader(file),
}
}
func (t *tailReader) Read(p []byte) (n int, err error) {
t.mu.RLock()
if t.closed {
t.mu.RUnlock()
return 0, io.EOF
}
t.mu.RUnlock()
n, err = t.reader.Read(p)
if err == io.EOF {
// Wait a bit and try again (tailing behavior)
time.Sleep(100 * time.Millisecond)
return 0, nil
}
return n, err
}
func (t *tailReader) Close() error {
t.mu.Lock()
t.closed = true
t.mu.Unlock()
return t.file.Close()
}