pkg/service/process_pool.go

package service

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"log/slog"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"reflect"
	"strings"
	"sync"
	"time"

	"git.cafe/ezterry/ez-agent/pkg/ezagentapi"
	"git.cafe/ezterry/ez-agent/pkg/service/config"
)

const (
	processOutputDrainTimeout = 250 * time.Millisecond
	processRetireTimeout      = 2 * time.Second
	processRetryDelay         = 250 * time.Millisecond
)

type ProcessPool struct {
	mu                 sync.Mutex
	procs              map[string]*childRecord
	spawning           map[string]*spawnFlight
	closed             bool
	outputDrainTimeout time.Duration
}

type childRecord struct {
	name          string
	serviceConfig config.ServiceConfig
	conn          *Connection
	cmd           *exec.Cmd
	published     bool
	retiring      bool
	done          chan struct{}
	finished      chan struct{}
	finishOnce    sync.Once
	stdoutR       *os.File
	stderrR       *os.File
	once          sync.Once
}

type spawnFlight struct {
	done          chan struct{}
	serviceConfig config.ServiceConfig
	conn          *Connection
	err           error
	waiters       int
	retryAfter    time.Time
}

func NewProcessPool() *ProcessPool {
	return &ProcessPool{
		procs:              make(map[string]*childRecord),
		spawning:           make(map[string]*spawnFlight),
		outputDrainTimeout: processOutputDrainTimeout,
	}
}

type SpawnCallbacks struct {
	connectionID   func() string
	RegisterConn   func(*Connection)
	CleanupConn    func(*Connection)
	ServiceOptions func(*Connection) ezagentapi.ServiceOptions
	// CredentialEnvironmentNames returns auth-configured environment variable
	// names whose values must not be inherited by a spawned service.
	CredentialEnvironmentNames func() []string
}

func newProcessConnection(name string, process *os.Process, service config.ServiceConfig, allocateID func() string) *Connection {
	if allocateID == nil {
		allocateID = freshConnectionID
	}
	return &Connection{
		ID: allocateID(), Name: name, process: process,
		helloCh: make(chan struct{}), announceCh: make(chan struct{}), infoCh: make(chan struct{}),
		launchedServiceName: name, launchedService: &service,
	}
}

func (p *ProcessPool) GetOrSpawn(serviceName string, cfg *config.ServiceConfig, cb SpawnCallbacks) (*Connection, error) {
	if cfg == nil || !cfg.Direct {
		return nil, fmt.Errorf("service %s is not configured for direct JSONL", serviceName)
	}
	return p.getOrSpawn(serviceName, cfg, cb)
}

// RecoverDirectConn retires stale only if it still owns the configured service,
// then shares one replacement startup with other pool callers. A healthy matching
// replacement is reused. The caller must authorize recovery before dispatch;
// this method never replays a request. Cancellation stops this caller's wait, not
// the shared startup. Failed starts are briefly shared to limit restart churn.
func (p *ProcessPool) RecoverDirectConn(ctx context.Context, serviceName string, cfg *config.ServiceConfig, stale *Connection, cb SpawnCallbacks) (*Connection, error) {
	if cfg == nil || !cfg.Direct {
		return nil, fmt.Errorf("service %s is not configured for direct JSONL", serviceName)
	}
	if stale == nil || stale.launchedServiceName != serviceName || stale.launchedService == nil || !reflect.DeepEqual(*stale.launchedService, cloneServiceConfig(*cfg)) {
		return nil, fmt.Errorf("service %s recovery configuration does not match stale connection", serviceName)
	}
	startupTimeout, err := cfg.ParsedStartupTimeout()
	if err != nil {
		return nil, fmt.Errorf("service %s: %w", serviceName, err)
	}
	// Include the existing optional announce wait and the bounded retirement.
	ctx, cancel := context.WithTimeout(ctx, startupTimeout+5*time.Second+processRetireTimeout)
	defer cancel()
	return p.getOrSpawnContext(ctx, serviceName, cfg, stale, cb)
}

// StartService starts one configured service generation if it is not already
// running or starting. Direct and background services share singleton and
// startup-flight ownership.
func (p *ProcessPool) StartService(serviceName string, cfg *config.ServiceConfig, cb SpawnCallbacks) error {
	if cfg == nil {
		return fmt.Errorf("service %s has no configuration", serviceName)
	}
	_, err := p.getOrSpawn(serviceName, cfg, cb)
	return err
}

func cloneServiceConfig(cfg config.ServiceConfig) config.ServiceConfig {
	cfg.Args = append([]string(nil), cfg.Args...)
	cfg.Tools = append([]string(nil), cfg.Tools...)
	cfg.Plugins = append([]string(nil), cfg.Plugins...)
	cfg.Macros = append([]string(nil), cfg.Macros...)
	return cfg
}

func (p *ProcessPool) getOrSpawn(connName string, cfg *config.ServiceConfig, cb SpawnCallbacks) (*Connection, error) {
	return p.getOrSpawnContext(context.Background(), connName, cfg, nil, cb)
}

// recordHealthy is called under p.mu. Transport closure is terminal even when
// the OS process is still alive or callback cleanup has not finished yet.
func recordHealthy(rec *childRecord) bool {
	if rec.retiring {
		return false
	}
	select {
	case <-rec.done:
		return false
	default:
	}
	if rec.serviceConfig.Direct {
		if rec.conn == nil || rec.conn.apiConn == nil {
			return false
		}
		select {
		case <-rec.conn.apiConn.Closed():
			return false
		default:
		}
	}
	return true
}

func (p *ProcessPool) getOrSpawnContext(ctx context.Context, connName string, cfg *config.ServiceConfig, stale *Connection, cb SpawnCallbacks) (*Connection, error) {
	if err := ctx.Err(); err != nil {
		return nil, err
	}
	snapshot := cloneServiceConfig(*cfg)
	p.mu.Lock()
	if p.closed {
		p.mu.Unlock()
		return nil, fmt.Errorf("process pool is shut down")
	}
	rec := p.procs[connName]
	flight := p.spawning[connName]
	if flight != nil {
		select {
		case <-flight.done:
			if flight.err == nil || (flight.waiters == 0 && !time.Now().Before(flight.retryAfter)) {
				delete(p.spawning, connName)
				flight = nil
			}
		default:
		}
	}
	if stale != nil && ((rec != nil && !reflect.DeepEqual(rec.serviceConfig, snapshot)) || (flight != nil && !reflect.DeepEqual(flight.serviceConfig, snapshot))) {
		p.mu.Unlock()
		return nil, fmt.Errorf("service %s is already managed with a different configuration", connName)
	}
	if rec != nil && rec.published && recordHealthy(rec) && (stale == nil || rec.conn != stale) {
		if cfg.Direct && rec.conn == nil {
			p.mu.Unlock()
			return nil, fmt.Errorf("service %s is already running without direct JSONL", connName)
		}
		p.mu.Unlock()
		return rec.conn, nil
	}
	if flight == nil {
		if rec != nil && stale == nil {
			// Ordinary callers follow the first owner, including while it is
			// retiring. Keep its configuration and await cleanup rather than
			// letting an incidental caller change the managed service.
			if cfg.Direct && !rec.serviceConfig.Direct {
				p.mu.Unlock()
				return nil, fmt.Errorf("service %s is retiring without direct JSONL", connName)
			}
			snapshot = rec.serviceConfig
		}
		flight = &spawnFlight{done: make(chan struct{}), serviceConfig: snapshot}
		p.spawning[connName] = flight
		if rec != nil {
			rec.retiring = true
		} else {
			rec = newChildRecord(connName, snapshot)
			p.procs[connName] = rec
		}
		go p.runSpawnFlight(rec, flight, cb)
	}
	flight.waiters++
	p.mu.Unlock()
	select {
	case <-ctx.Done():
	case <-flight.done:
	}
	p.mu.Lock()
	c, err := flight.conn, flight.err
	if ctx.Err() != nil {
		c, err = nil, ctx.Err()
	} else if err == nil && (p.closed || p.procs[connName] == nil || p.procs[connName].conn != c || !recordHealthy(p.procs[connName])) {
		c, err = nil, fmt.Errorf("service %s exited during startup or pool shut down", connName)
	}
	flight.waiters--
	p.releaseFlightLocked(connName, flight)
	p.mu.Unlock()
	return c, err
}

func newChildRecord(name string, cfg config.ServiceConfig) *childRecord {
	return &childRecord{
		name:          name,
		serviceConfig: cfg,
		done:          make(chan struct{}),
		finished:      make(chan struct{}),
	}
}

func (p *ProcessPool) releaseFlightLocked(name string, flight *spawnFlight) {
	select {
	case <-flight.done:
		if flight.waiters == 0 && flight.err == nil && p.spawning[name] == flight {
			delete(p.spawning, name)
		}
	default:
	}
}

func (p *ProcessPool) runSpawnFlight(rec *childRecord, flight *spawnFlight, cb SpawnCallbacks) {
	connName := rec.name
	cfg := &flight.serviceConfig
	var c *Connection
	var err error
	p.mu.Lock()
	retiring := rec.retiring
	p.mu.Unlock()
	if retiring {
		p.stopRecord(rec)
		timer := time.NewTimer(processRetireTimeout)
		select {
		case <-rec.finished:
		case <-timer.C:
			err = fmt.Errorf("service %s retirement timed out", connName)
		}
		timer.Stop()
		if err == nil {
			p.mu.Lock()
			if p.closed {
				err = fmt.Errorf("process pool is shut down")
			} else {
				rec = newChildRecord(connName, *cfg)
				p.procs[connName] = rec
			}
			p.mu.Unlock()
		}
	}
	if err == nil {
		if cfg.Direct {
			c, err = p.spawnDirectProcess(rec, cfg, cb)
		} else {
			err = p.spawnBackgroundProcess(rec, cfg, cb)
		}
	}
	p.mu.Lock()
	if err == nil && (p.closed || !recordHealthy(rec) || p.procs[connName] != rec) {
		err = fmt.Errorf("service %s exited during startup or pool shut down", connName)
	}
	if err == nil {
		rec.published = true
	} else {
		rec.retiring = true
		p.mu.Unlock()
		p.stopRecord(rec)
		p.mu.Lock()
		started := rec.cmd != nil
		p.mu.Unlock()
		if !started {
			p.cleanupRecord(rec, cb)
		}
		p.mu.Lock()
	}
	flight.conn, flight.err = c, err
	if err != nil {
		flight.conn = nil
		flight.retryAfter = time.Now().Add(processRetryDelay)
	}
	close(flight.done)
	p.releaseFlightLocked(connName, flight)
	p.mu.Unlock()
}

func (rec *childRecord) markFinished() {
	rec.finishOnce.Do(func() { close(rec.finished) })
}
func (p *ProcessPool) spawnDirectProcess(rec *childRecord, cfg *config.ServiceConfig, cb SpawnCallbacks) (*Connection, error) {
	connName := rec.name
	startupTimeout, err := cfg.ParsedStartupTimeout()
	if err != nil {
		return nil, fmt.Errorf("service %s: %w", connName, err)
	}
	cmd, err := serviceCommand(cfg)
	if err != nil {
		return nil, fmt.Errorf("service %s: %w", connName, err)
	}

	// Own the pipe endpoints explicitly. cmd.Wait therefore never owns or
	// closes the daemon's readers and may reap the direct child independently
	// of descendants which inherited its stdout/stderr descriptors.
	stdinR, stdinW, err := os.Pipe()
	if err != nil {
		return nil, fmt.Errorf("stdin pipe: %w", err)
	}
	stdoutR, stdoutW, err := os.Pipe()
	if err != nil {
		stdinR.Close()
		stdinW.Close()
		return nil, fmt.Errorf("stdout pipe: %w", err)
	}
	stderrR, stderrW, err := os.Pipe()
	if err != nil {
		stdinR.Close()
		stdinW.Close()
		stdoutR.Close()
		stdoutW.Close()
		return nil, fmt.Errorf("stderr pipe: %w", err)
	}
	closeAll := func() {
		stdinR.Close()
		stdinW.Close()
		stdoutR.Close()
		stdoutW.Close()
		stderrR.Close()
		stderrW.Close()
	}

	cmd.Env = directChildEnvironment(spawnCredentialEnvironmentNames(cb)...)
	cmd.Stdin, cmd.Stdout, cmd.Stderr = stdinR, stdoutW, stderrW
	if err := cmd.Start(); err != nil {
		closeAll()
		return nil, fmt.Errorf("starting service process: %w", err)
	}
	// The child-side copies must not keep EOF from the daemon's readers.
	_ = stdinR.Close()
	_ = stdoutW.Close()
	_ = stderrW.Close()

	p.mu.Lock()
	rec.cmd, rec.stdoutR, rec.stderrR = cmd, stdoutR, stderrR
	closed := p.closed
	p.mu.Unlock()
	if closed {
		_ = cmd.Process.Kill()
	}

	slog.Info("service process spawned", "service", connName, "pid", cmd.Process.Pid)
	stderrDone := make(chan struct{})
	go func() { logProcessStderr(connName, cmd.Process.Pid, stderrR); close(stderrDone) }()

	launchConfig := cloneServiceConfig(rec.serviceConfig)
	c := newProcessConnection(connName, cmd.Process, launchConfig, cb.connectionID)
	helloCh, announceCh := c.helloCh, c.announceCh
	closeFn := func() error {
		_ = stdinW.Close()
		_ = stdoutR.Close()
		if cmd.Process != nil {
			return cmd.Process.Kill()
		}
		return nil
	}
	opts := ezagentapi.ServiceOptions{}
	if cb.ServiceOptions != nil {
		opts = cb.ServiceOptions(c)
	}
	ec := ezagentapi.AcceptServiceConn(bufio.NewReader(stdoutR), stdinW, closeFn, opts)
	c.apiConn = ec
	p.mu.Lock()
	rec.conn = c
	p.mu.Unlock()

	ecDone := make(chan struct{})
	registered := make(chan struct{})
	var waitErr error // Published by closing rec.done; contains OS wait status only.
	// EOF is a failed direct service even if the child keeps running. Watch the
	// transport, not Wait(), which also joins potentially blocked callbacks.
	go func() {
		<-ec.Closed()
		p.mu.Lock()
		rec.retiring = true
		p.mu.Unlock()
		_ = ec.Close()
		_ = cmd.Process.Kill()
		<-rec.done
		slog.Info("service process connection closed", "service", connName, "conn_id", c.ID, "pid", cmd.Process.Pid, "wait_error", waitErr)
	}()
	// Exactly one owner waits immediately. Reaping does not depend on pipe EOF.
	go func() {
		waitErr = cmd.Wait()
		close(rec.done)
		// Allow final buffered JSONL/stderr data to drain normally, but inherited
		// descendant descriptors may not retain this lifecycle indefinitely.
		timer := time.NewTimer(p.outputDrainTimeout)
		ecDrainDone, stderrDrainDone := ecDone, stderrDone
		for ecDrainDone != nil || stderrDrainDone != nil {
			select {
			case <-ecDrainDone:
				ecDrainDone = nil
			case <-stderrDrainDone:
				stderrDrainDone = nil
			case <-timer.C:
				if ecDrainDone != nil {
					_ = stdoutR.Close()
					_ = ec.Close()
				}
				if stderrDrainDone != nil {
					_ = stderrR.Close()
				}
				ecDrainDone, stderrDrainDone = nil, nil
			}
		}
		if !timer.Stop() {
			select {
			case <-timer.C:
			default:
			}
		}
		<-registered
		p.cleanupRecord(rec, cb)
		rec.markFinished()
	}()

	// Registration happens-before cleanup even if Wait returned immediately.
	if cb.RegisterConn != nil {
		cb.RegisterConn(c)
	}
	close(registered)
	// Publish before accepting capability claims or metadata from this instance.
	go func() {
		if err := ec.Start(); err != nil {
			slog.Warn("service process connection ended during startup", "service", connName, "pid", cmd.Process.Pid, "error", err)
		}
		_ = ec.Wait()
		close(ecDone)
	}()

	select {
	case <-helloCh:
	case <-rec.done:
		return nil, fmt.Errorf("service %s exited before hello", connName)
	case <-time.After(startupTimeout):
		_ = cmd.Process.Kill()
		return nil, fmt.Errorf("service %s failed to complete hello handshake", connName)
	}
	select {
	case <-announceCh:
	case <-rec.done:
		return nil, fmt.Errorf("service %s exited during handshake", connName)
	case <-time.After(5 * time.Second):
	}
	if !c.helloDone.Load() {
		_ = cmd.Process.Kill()
		return nil, fmt.Errorf("service %s failed to complete handshake", connName)
	}
	select {
	case <-rec.done:
		return nil, fmt.Errorf("service %s exited during handshake", connName)
	default:
	}
	return c, nil
}

// directChildEnvironment preserves ordinary service settings, including XDG,
// locale, and sanitized proxy-routing variables, but does not pass common
// provider credentials into every configured subprocess. This is exposure
// reduction, not a process sandbox. AGENTCLI is rebuilt from the running
// installation.
func directChildEnvironment(credentialNames ...string) []string {
	env := filterChildEnvironment(os.Environ(), credentialNames...)
	serviceExe, err := physicalServiceExecutable()
	if err != nil {
		return env
	}
	if agentCLI := agentCLIForServiceExecutable(serviceExe); agentCLI != "" {
		env = append(env, "AGENTCLI="+agentCLI)
	}
	return env
}

func spawnCredentialEnvironmentNames(cb SpawnCallbacks) []string {
	if cb.CredentialEnvironmentNames == nil {
		return nil
	}
	return cb.CredentialEnvironmentNames()
}

func filterChildEnvironment(env []string, credentialNames ...string) []string {
	configured := make(map[string]bool, len(credentialNames))
	for _, name := range credentialNames {
		configured[strings.ToUpper(name)] = true
	}
	out := make([]string, 0, len(env))
	for _, entry := range env {
		name, value, found := strings.Cut(entry, "=")
		if !found || configured[strings.ToUpper(name)] || childEnvironmentCredential(name) {
			continue
		}
		if childProxyEnvironment(name) {
			var ok bool
			value, ok = stripProxyCredentials(value)
			if !ok {
				continue
			}
			entry = name + "=" + value
		}
		out = append(out, entry)
	}
	return out
}

func childEnvironmentCredential(name string) bool {
	upper := strings.ToUpper(name)
	switch upper {
	case "AGENTCLI", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY",
		"AZURE_OPENAI_API_KEY", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN",
		"GITHUB_TOKEN", "GH_TOKEN":
		return true
	}
	for _, suffix := range []string{"_API_KEY", "_SECRET_KEY", "_ACCESS_TOKEN", "_REFRESH_TOKEN", "_AUTH_TOKEN", "_TOKEN", "_PASSWORD", "_CREDENTIALS", "_SECRET"} {
		if strings.HasSuffix(upper, suffix) {
			return true
		}
	}
	return false
}

func childProxyEnvironment(name string) bool {
	switch strings.ToUpper(name) {
	case "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY":
		return true
	default:
		return false
	}
}

func stripProxyCredentials(value string) (string, bool) {
	if value == "" || !strings.Contains(value, "@") {
		return value, true
	}
	prefix := ""
	parseValue := value
	if !strings.Contains(value, "://") {
		prefix = "http://"
		parseValue = prefix + value
	}
	parsed, err := url.Parse(parseValue)
	if err != nil || parsed.Host == "" || parsed.User == nil {
		return "", false
	}
	parsed.User = nil
	safe := parsed.String()
	if prefix != "" {
		safe = strings.TrimPrefix(safe, prefix)
	}
	return safe, true
}

func agentCLIForServiceExecutable(serviceExe string) string {
	if serviceExe == "" {
		return ""
	}
	candidate := filepath.Join(filepath.Dir(serviceExe), "ez-agent")
	info, err := os.Stat(candidate)
	if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 {
		return ""
	}
	abs, err := filepath.Abs(candidate)
	if err != nil {
		return ""
	}
	return abs
}

func removeEnvironmentKey(env []string, key string) []string {
	prefix := key + "="
	out := make([]string, 0, len(env))
	for _, entry := range env {
		if !strings.HasPrefix(entry, prefix) {
			out = append(out, entry)
		}
	}
	return out
}

func logProcessStderr(connName string, pid int, r io.Reader) {
	scanner := bufio.NewScanner(r)
	// Child diagnostics can include structured log records and provider errors.
	// Keep the scanner from silently stopping at its small default token limit.
	scanner.Buffer(make([]byte, 64*1024), 1024*1024)
	for scanner.Scan() {
		slog.Info("service process stderr", "service", connName, "pid", pid, "message", scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		slog.Warn("service process stderr read failed", "service", connName, "pid", pid, "error", err)
	}
}

func (p *ProcessPool) Get(connName string) *Connection {
	p.mu.Lock()
	defer p.mu.Unlock()
	if rec := p.procs[connName]; rec != nil && rec.published && recordHealthy(rec) {
		return rec.conn
	}
	return nil
}

func (p *ProcessPool) Remove(c *Connection) {
	p.mu.Lock()
	for _, rec := range p.procs {
		if rec.conn == c {
			// Keep ownership until the reaper and cleanup callback finish. A
			// replacement must not overtake cleanup of this generation.
			rec.retiring = true
			p.mu.Unlock()
			p.stopRecord(rec)
			return
		}
	}
	p.mu.Unlock()
}

func (p *ProcessPool) Shutdown() {
	p.mu.Lock()
	if p.closed {
		p.mu.Unlock()
		return
	}
	p.closed = true
	slog.Info("process pool shutting down", "process_count", len(p.procs))
	recs := make([]*childRecord, 0, len(p.procs))
	for _, rec := range p.procs {
		recs = append(recs, rec)
	}
	p.mu.Unlock()
	for _, rec := range recs {
		p.stopRecord(rec)
	}
	// Every admitted record has a lifecycle completion channel, including a
	// spawn that has not reached cmd.Start yet. Waiting on all records prevents
	// daemon exit from racing the eventual kill and cmd.Wait owner.
	timer := time.NewTimer(2 * time.Second)
	defer timer.Stop()
	for _, rec := range recs {
		select {
		case <-rec.finished:
		case <-timer.C:
			return
		}
	}
}

func (p *ProcessPool) stopRecord(rec *childRecord) {
	p.mu.Lock()
	c, cmd, stdoutR, stderrR := rec.conn, rec.cmd, rec.stdoutR, rec.stderrR
	p.mu.Unlock()
	if stdoutR != nil {
		_ = stdoutR.Close()
	}
	if stderrR != nil {
		_ = stderrR.Close()
	}
	if c != nil && c.apiConn != nil {
		_ = c.apiConn.Close()
	}
	if cmd != nil && cmd.Process != nil {
		_ = cmd.Process.Kill()
	}
}

func (p *ProcessPool) cleanupRecord(rec *childRecord, cb SpawnCallbacks) {
	rec.once.Do(func() {
		p.mu.Lock()
		c := rec.conn
		rec.retiring = true
		p.mu.Unlock()
		if c != nil && cb.CleanupConn != nil {
			cb.CleanupConn(c)
		}
		p.mu.Lock()
		if rec.finished != nil {
			rec.markFinished()
		}
		if p.procs[rec.name] == rec {
			delete(p.procs, rec.name)
		}
		p.mu.Unlock()
	})
}