pkg/service/daemon.go

package service

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log/slog"
	"net"
	"os"
	"os/exec"
	"os/signal"
	"path/filepath"
	"sync"
	"syscall"
	"time"

	"git.cafe/ezterry/ez-agent/internal/incident"

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

const (
	probeDialTimeout      = time.Second
	probeHandshakeTimeout = 2 * time.Second
	// Owned renewal is bounded to 65 seconds plus a 10-second credential save.
	// Allow that drain and a small margin without lengthening startup probes.
	shutdownDrainTimeout  = 80 * time.Second
	bootstrapAcceptPoll   = 100 * time.Millisecond
	bootstrapHelloTimeout = 2 * time.Second
	serviceLogFilename    = "ez-agent-service.log"
)

func socketPath() (string, error) {
	dir, err := config.RuntimeDir()
	if err != nil {
		return "", err
	}
	return filepath.Join(dir, "ez-agent.sock"), nil
}

func dbPath() string {
	return filepath.Join(config.StateDir(), "ez-agent.db")
}

// DaemonState is the result class of a live daemon probe.
type DaemonState string

const (
	DaemonUnavailable DaemonState = "unavailable"
	DaemonStarting    DaemonState = "starting"
	DaemonReady       DaemonState = "ready"
)

// DaemonStatus is a short-lived socket probe result. Message is populated for
// a starting daemon and is intentionally suitable for display to a user.
type DaemonStatus struct {
	State   DaemonState
	Message string
}

func unavailableStatus() DaemonStatus { return DaemonStatus{State: DaemonUnavailable} }

// ProbeDaemonContext performs one bounded hello exchange, honoring ctx while
// dialing and while a live peer is mid-handshake. A cancellation is returned to
// the caller rather than being misclassified as daemon unavailability.
func ProbeDaemonContext(ctx context.Context) (DaemonStatus, error) {
	if ctx == nil {
		ctx = context.Background()
	}
	path, err := socketPath()
	if err != nil {
		return unavailableStatus(), nil
	}

	rw, err := ipcsocket.Dial(ctx, ipcsocket.Unix(path), probeDialTimeout)
	if err != nil {
		if ctx.Err() != nil {
			return unavailableStatus(), ctx.Err()
		}
		return unavailableStatus(), nil
	}
	defer rw.Close()
	if err := rw.SetDeadline(time.Now().Add(probeHandshakeTimeout)); err != nil {
		return unavailableStatus(), nil
	}
	conn := ezagentapi.ConnectClientRW(rw, rw.Close, ezagentapi.ClientOptions{})
	started := make(chan error, 1)
	go func() { started <- conn.Start() }()
	select {
	case err := <-started:
		if err != nil {
			_ = conn.Close()
			if isTimeout(err) {
				return DaemonStatus{State: DaemonStarting, Message: "waiting for daemon response"}, nil
			}
			// A malformed frame, protocol error, EOF, and any other startup
			// failure do not prove an in-progress daemon and must not block a
			// legitimate launch attempt.
			return unavailableStatus(), nil
		}
	case <-ctx.Done():
		_ = conn.Close()
		return unavailableStatus(), ctx.Err()
	}
	ack, ok := conn.HelloAck()
	_ = conn.Close()
	if !ok {
		return unavailableStatus(), nil
	}
	if !ack.Ready {
		message := ack.Message
		if message == "" {
			message = "starting daemon"
		}
		return DaemonStatus{State: DaemonStarting, Message: message}, nil
	}
	return DaemonStatus{State: DaemonReady, Message: ack.Message}, nil
}

func isTimeout(err error) bool {
	var netErr net.Error
	return errors.As(err, &netErr) && netErr.Timeout()
}

// ProbeDaemon is the background-context compatibility wrapper.
func ProbeDaemon() DaemonStatus {
	status, _ := ProbeDaemonContext(context.Background())
	return status
}

// IsDaemonRunning remains for callers that only need the historical boolean
// question. New lifecycle code should use ProbeDaemon to preserve startup.
func IsDaemonRunning() bool { return ProbeDaemon().State == DaemonReady }

func FindServiceBinary() (string, error) {
	exe, err := os.Executable()
	if err != nil {
		return "", fmt.Errorf("getting executable path: %w", err)
	}
	dir := filepath.Dir(exe)
	svcPath := filepath.Join(dir, "ez-agent-service")
	if _, err := os.Stat(svcPath); err == nil {
		return svcPath, nil
	}
	svcPath, err = exec.LookPath("ez-agent-service")
	if err != nil {
		return "", fmt.Errorf("ez-agent-service not found next to client or on PATH: %w", err)
	}
	return svcPath, nil
}

var findServiceBinaryForDaemon = FindServiceBinary

// LaunchHandle owns a daemon process started by this client. It is nil when a
// caller joined an existing daemon startup. Done delivers the child Wait result
// exactly once and then closes.
type LaunchHandle struct {
	done    chan error
	logPath string
}

func (h *LaunchHandle) Done() <-chan error { return h.done }

// FailureError decorates a child exit observed before readiness with the tail
// of its captured output. Frontends call this after their required re-probe.
func (h *LaunchHandle) FailureError(waitErr error) error {
	if waitErr == nil {
		waitErr = errors.New("daemon exited before becoming ready")
	}
	const maxTail = 8 << 10
	data, err := os.ReadFile(h.logPath)
	if err != nil || len(data) == 0 {
		return fmt.Errorf("daemon launch failed: %w", waitErr)
	}
	if len(data) > maxTail {
		data = data[len(data)-maxTail:]
	}
	return fmt.Errorf("daemon launch failed: %w\n--- daemon output (%s) ---\n%s", waitErr, h.logPath, data)
}

// StartDaemonContext probes first. It starts a child only when no daemon
// endpoint is reachable; callers receiving starting or ready join that daemon.
// Cancellation before spawning returns promptly and never creates a child.
func StartDaemonContext(ctx context.Context) (DaemonStatus, *LaunchHandle, error) {
	if ctx == nil {
		ctx = context.Background()
	}
	status, err := ProbeDaemonContext(ctx)
	if err != nil {
		return status, nil, err
	}
	if status.State != DaemonUnavailable {
		return status, nil, nil
	}
	if err := ctx.Err(); err != nil {
		return status, nil, err
	}

	svcPath, err := findServiceBinaryForDaemon()
	if err != nil {
		return status, nil, err
	}
	if err := config.EnsureStateDir(); err != nil {
		return status, nil, fmt.Errorf("creating state dir for daemon log: %w", err)
	}
	logPath := filepath.Join(config.StateDir(), serviceLogFilename)
	logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
	if err != nil {
		return status, nil, fmt.Errorf("opening daemon log: %w", err)
	}

	if err := ctx.Err(); err != nil {
		_ = logFile.Close()
		return status, nil, err
	}
	cmd := exec.Command(svcPath)
	cmd.Stdin = nil
	cmd.Stdout = logFile
	cmd.Stderr = logFile
	cmd.Env = os.Environ()
	if err := cmd.Start(); err != nil {
		_ = logFile.Close()
		return status, nil, fmt.Errorf("starting daemon: %w", err)
	}
	_ = logFile.Close()

	handle := &LaunchHandle{done: make(chan error, 1), logPath: logPath}
	go func() {
		handle.done <- cmd.Wait()
		close(handle.done)
	}()
	return status, handle, nil
}

// StartDaemon is the background-context compatibility wrapper.
func StartDaemon() (DaemonStatus, *LaunchHandle, error) {
	return StartDaemonContext(context.Background())
}

// StopDaemonContext refuses to shut down a bootstrap daemon and sends shutdown
// only over a separately verified ready connection. The second hello exchange
// has the same bounded deadline and cancellation behavior as a normal probe.
func StopDaemonContext(ctx context.Context) error {
	if ctx == nil {
		ctx = context.Background()
	}
	status, err := ProbeDaemonContext(ctx)
	if err != nil {
		return err
	}
	if status.State == DaemonStarting {
		return fmt.Errorf("daemon is still starting; retry once ready")
	}
	if status.State == DaemonUnavailable {
		return fmt.Errorf("daemon is not running")
	}

	path, err := socketPath()
	if err != nil {
		return fmt.Errorf("runtime directory not available: %w", err)
	}
	rw, err := ipcsocket.Dial(ctx, ipcsocket.Unix(path), time.Second*2)
	if err != nil {
		if ctx.Err() != nil {
			return ctx.Err()
		}
		return fmt.Errorf("connecting to daemon: %w", err)
	}
	conn := ezagentapi.ConnectClientRW(rw, rw.Close, ezagentapi.ClientOptions{})
	if err := rw.SetDeadline(time.Now().Add(probeHandshakeTimeout)); err != nil {
		_ = rw.Close()
		return fmt.Errorf("setting shutdown startup deadline: %w", err)
	}
	started := make(chan error, 1)
	go func() { started <- conn.Start() }()
	select {
	case err := <-started:
		if err != nil {
			_ = conn.Close()
			return fmt.Errorf("connecting to daemon: %w", err)
		}
	case <-ctx.Done():
		_ = conn.Close()
		return ctx.Err()
	}
	ack, ok := conn.HelloAck()
	if !ok || !ack.Ready {
		_ = conn.Close()
		return fmt.Errorf("daemon is still starting; retry once ready")
	}
	if err := rw.SetDeadline(time.Time{}); err != nil {
		_ = conn.Close()
		return fmt.Errorf("clearing shutdown startup deadline: %w", err)
	}
	defer conn.Close()

	if err := conn.SendShutdown(ctx, ""); err != nil {
		return fmt.Errorf("sending shutdown: %w", err)
	}
	_ = rw.SetReadDeadline(time.Now().Add(shutdownDrainTimeout))
	waited := make(chan error, 1)
	go func() { waited <- conn.Wait() }()
	select {
	case err := <-waited:
		if err != nil && !errors.Is(err, io.EOF) {
			return fmt.Errorf("waiting for shutdown: %w", err)
		}
		return nil
	case <-ctx.Done():
		_ = conn.Close()
		return ctx.Err()
	}
}

// StopDaemon is the background-context compatibility wrapper.
func StopDaemon() error { return StopDaemonContext(context.Background()) }

func autoVacuumAge(days int) (time.Duration, error) {
	if days < 0 {
		return 0, fmt.Errorf("auto vacuum days must be non-negative")
	}
	const day = 24 * time.Hour
	if int64(days) > int64((time.Duration(1<<63-1))/day) {
		return 0, fmt.Errorf("auto vacuum days is too large")
	}
	return time.Duration(days) * day, nil
}

// Hooks keep startup phase tests deterministic without changing session's
// public API or production maintenance semantics.
var (
	newAuditForDaemon    = newServiceAudit
	sessionOpenForDaemon = session.Open
	newServerForDaemon   = NewServer
	cleanupEmptyLeaves   = func(s *session.Storage) (int, error) { return s.CleanupEmptyLeaves() }
	repairStreamingTurns = func(s *session.Storage) (int, error) { return s.MarkStreamingTurnsInterrupted() }
	reconcileContent     = func(s *session.Storage) (session.MaintenanceResult, error) { return s.ReconcileStartupContent() }
)

type startupPhase struct {
	mu      sync.RWMutex
	message string
}

func (p *startupPhase) Set(message string) {
	p.mu.Lock()
	p.message = message
	p.mu.Unlock()
}

func (p *startupPhase) Get() string {
	p.mu.RLock()
	defer p.mu.RUnlock()
	return p.message
}

// bootstrapServer owns the listener until durable startup maintenance has
// completed. It intentionally has no Server connection registration or command
// handlers: each accepted peer receives only a not-ready hello_ack and closes.
type bootstrapServer struct {
	listener *net.UnixListener
	phase    *startupPhase
	stop     chan struct{}
	once     sync.Once
	wg       sync.WaitGroup
}

func newBootstrapServer(listener *net.UnixListener, phase *startupPhase) *bootstrapServer {
	return &bootstrapServer{listener: listener, phase: phase, stop: make(chan struct{})}
}

func (b *bootstrapServer) Start() {
	b.wg.Add(1)
	go func() {
		defer b.wg.Done()
		for {
			select {
			case <-b.stop:
				return
			default:
			}
			if err := b.listener.SetDeadline(time.Now().Add(bootstrapAcceptPoll)); err != nil {
				slog.Error("set bootstrap listener deadline", "error", err)
				return
			}
			conn, err := b.listener.AcceptUnix()
			if err != nil {
				if ne, ok := err.(net.Error); ok && ne.Timeout() {
					select {
					case <-b.stop:
						return
					default:
						continue
					}
				}
				select {
				case <-b.stop:
					return
				default:
					slog.Error("bootstrap accept error", "error", err)
					return
				}
			}
			if conn == nil {
				// AcceptUnix must not return a nil connection without an error,
				// but never hand a nil connection to a reply goroutine if an
				// externally closed listener violates that expectation.
				slog.Error("bootstrap accept returned nil connection")
				return
			}
			select {
			case <-b.stop:
				_ = conn.Close()
				return
			default:
			}
			go b.replyNotReady(conn)
		}
	}()
}

func (b *bootstrapServer) replyNotReady(conn *net.UnixConn) {
	defer conn.Close()
	_ = conn.SetDeadline(time.Now().Add(bootstrapHelloTimeout))
	apiConn := ezagentapi.AcceptServiceConnRW(conn, conn.Close, ezagentapi.ServiceOptions{
		ServerID: "ez1",
		StateDir: config.StateDir(),
		BuildAck: func(ezagentapi.ClientHello) (ezagentapi.HelloAck, error) {
			return ezagentapi.HelloAck{ServerID: "ez1", StateDir: config.StateDir(), Ready: false, Message: b.phase.Get()}, nil
		},
	})
	if err := apiConn.Start(); err != nil {
		slog.Debug("bootstrap client connection ended during startup", "error", err)
		return
	}
	// Start flushes the acknowledgement before returning. Close immediately so
	// bootstrap peers cannot issue commands or delay the listener handoff.
	_ = apiConn.Close()
}

// Stop joins only the accept loop; it leaves the listener open for the normal
// Server to take over. New connections remain queued in the kernel backlog.
func (b *bootstrapServer) Stop() {
	b.once.Do(func() {
		close(b.stop)
		b.wg.Wait()
		if err := b.listener.SetDeadline(time.Time{}); err != nil {
			slog.Warn("clear bootstrap listener deadline", "error", err)
		}
	})
}

// bindDaemonSocket retains the daemon's stale-socket behavior while making the
// listener available before opening SQLite or running maintenance.
func bindDaemonSocket() (*net.UnixListener, string, error) {
	runtimeDir, err := config.EnsureRuntimeDir()
	if err != nil {
		return nil, "", fmt.Errorf("runtime directory: %w", err)
	}
	socketPath := filepath.Join(runtimeDir, "ez-agent.sock")
	if _, err := os.Lstat(socketPath); err == nil {
		conn, dialErr := net.DialTimeout("unix", socketPath, time.Second)
		if dialErr == nil {
			_ = conn.Close()
			return nil, "", fmt.Errorf("socket already in use: %s", socketPath)
		}
		if err := os.Remove(socketPath); err != nil {
			return nil, "", fmt.Errorf("removing stale socket: %w", err)
		}
	} else if !os.IsNotExist(err) {
		return nil, "", fmt.Errorf("stat socket: %w", err)
	}
	listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: socketPath, Net: "unix"})
	if err != nil {
		return nil, "", fmt.Errorf("listening on socket: %w", err)
	}
	return listener, socketPath, nil
}

// RunDaemon loads global configuration when cfg is nil. Resolved configurations
// remain supported for callers and fixtures. Audit starts before either path.
func RunDaemon(cfg *config.Config) error {
	audit := newAuditForDaemon(config.StateDir(), incident.Options{})
	defer audit.close()
	defer func() {
		if value := recover(); value != nil {
			// Preserve the panic boundary without inspecting its payload. The
			// earlier close defer gives the recorder only its bounded drain.
			audit.emit("daemon_boundary", incident.Unexpected, incident.Stop, incident.Data{}, true)
			panic(value)
		}
	}()
	if cfg == nil {
		endConfig := audit.phase("config", startupPhaseBudget, incident.Data{}, false)
		var err error
		cfg, err = config.LoadGlobal(config.ConfigPath())
		endConfig(err != nil)
		if err != nil {
			return fmt.Errorf("loading configuration: %w", err)
		}
	}
	endState := audit.phase("state", startupPhaseBudget, incident.Data{}, false)
	if err := config.EnsureStateDir(); err != nil {
		endState(true)
		return fmt.Errorf("creating state dir: %w", err)
	}

	lock, err := acquireStateDirLock(config.StateDir())
	endState(err != nil)
	if err != nil {
		return err
	}
	defer func() {
		end := audit.phase("state_close", shutdownPhaseBudget, incident.Data{}, true)
		err := lock.Close()
		end(err != nil)
		if err != nil {
			slog.Warn("release state directory lock", "error", err)
		}
	}()

	endSocket := audit.phase("socket", startupPhaseBudget, incident.Data{}, false)
	listener, socketPath, err := bindDaemonSocket()
	endSocket(err != nil)
	if err != nil {
		return err
	}
	listenerOwned := true
	var startupCleanup sync.Once
	cleanupStartupSocket := func() {
		startupCleanup.Do(func() {
			_ = listener.Close()
			if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {
				audit.emit("startup_socket_close", incident.CleanupFailed, incident.Fail, incident.Data{}, true)
				slog.Warn("remove failed startup socket", "path", socketPath, "error", err)
			}
		})
	}
	defer func() {
		if listenerOwned {
			cleanupStartupSocket()
		}
	}()

	// Signal handling starts as soon as the socket is visible. A signal during
	// synchronous maintenance must not leave a bootstrap listener or pathname
	// behind while the current maintenance call unwinds.
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
	defer signal.Stop(sigCh)
	startupWatchStop := make(chan struct{})
	startupWatchDone := make(chan struct{})
	startupInterrupted := make(chan os.Signal, 1)
	startupCancelled := make(chan struct{})
	go func() {
		defer close(startupWatchDone)
		select {
		case sig := <-sigCh:
			slog.Info("shutdown signal received during daemon startup", "signal", sig.String())
			cleanupStartupSocket()
			close(startupCancelled)
			startupInterrupted <- sig
		case <-startupWatchStop:
		}
	}()
	var startupWatchStopOnce sync.Once
	stopStartupWatch := func() {
		startupWatchStopOnce.Do(func() {
			close(startupWatchStop)
			<-startupWatchDone
		})
	}
	defer stopStartupWatch()
	startupError := func() error {
		select {
		case sig := <-startupInterrupted:
			return fmt.Errorf("daemon startup interrupted by signal %s", sig.String())
		default:
			return nil
		}
	}

	phase := &startupPhase{message: "opening session database"}
	bootstrap := newBootstrapServer(listener, phase)
	bootstrap.Start()
	bootstrapStopped := false
	defer func() {
		if !bootstrapStopped {
			bootstrap.Stop()
		}
	}()

	endDatabase := audit.phase("database", startupPhaseBudget, incident.Data{}, false)
	storage, err := sessionOpenForDaemon(dbPath())
	endDatabase(err != nil)
	if err != nil {
		if startupErr := startupError(); startupErr != nil {
			return startupErr
		}
		return fmt.Errorf("opening database: %w", err)
	}
	defer func() {
		end := audit.phase("storage_close", shutdownPhaseBudget, incident.Data{}, true)
		end(storage.Close() != nil)
	}()
	if startupErr := startupError(); startupErr != nil {
		return startupErr
	}

	phase.Set("cleaning incomplete leaves")
	endCleanup := audit.phase("cleanup", startupPhaseBudget, incident.Data{}, false)
	if !delayStartupMaintenanceForManualTesting(startupCancelled) {
		endCleanup(false)
		return startupError()
	}
	cleanupOK := true
	if n, err := cleanupEmptyLeaves(storage); err != nil {
		cleanupOK = false
		slog.Warn("cleanup empty leaves", "error", err)
	} else if n > 0 {
		slog.Info("cleaned up pending leaves on startup", "count", n)
	}
	endCleanup(!cleanupOK)
	if startupErr := startupError(); startupErr != nil {
		return startupErr
	}

	phase.Set("repairing interrupted turns")
	endRepair := audit.phase("repair", startupPhaseBudget, incident.Data{}, false)
	repairOK := true
	if n, err := storage.RecoverLeafAlerts(); err != nil {
		endRepair(true)
		return fmt.Errorf("recover leaf alerts: %w", err)
	} else if n > 0 {
		slog.Info("recovered active leaf alerts on startup", "count", n)
	}
	if n, err := repairStreamingTurns(storage); err != nil {
		repairOK = false
		slog.Warn("mark streaming turns interrupted", "error", err)
	} else if n > 0 {
		slog.Info("marked streaming turns interrupted on startup", "count", n)
	}
	endRepair(!repairOK)
	if startupErr := startupError(); startupErr != nil {
		return startupErr
	}

	if cleanupOK && repairOK && cfg.Daemon.AutoVacuumDays > 0 {
		phase.Set("vacuuming old roots")
		endVacuum := audit.phase("vacuum", startupPhaseBudget, incident.Data{}, false)
		vacuumFailed := false
		if age, err := autoVacuumAge(cfg.Daemon.AutoVacuumDays); err != nil {
			vacuumFailed = true
			slog.Error("invalid automatic vacuum age", "error", err)
		} else if result, err := storage.Vacuum(session.VacuumOpts{OlderThan: age}); err != nil {
			vacuumFailed = true
			slog.Warn("automatic startup vacuum failed", "error", err)
		} else {
			slog.Info("automatic startup vacuum complete", "roots", result.RootsPruned, "turns", result.TurnsPruned)
		}
		endVacuum(vacuumFailed)
	} else if !cleanupOK || !repairOK {
		slog.Warn("skipping automatic startup vacuum after failed cleanup or repair")
	}
	if startupErr := startupError(); startupErr != nil {
		return startupErr
	}

	phase.Set("reconciling stored content")
	endReconcile := audit.phase("reconcile", startupPhaseBudget, incident.Data{}, false)
	reconcileFailed := false
	if result, err := reconcileContent(storage); err != nil {
		reconcileFailed = true
		slog.Warn("startup content reconciliation failed", "error", err)
	} else {
		slog.Info("startup content reconciliation complete", "content_rows", result.ContentRowsPurged, "blob_files", result.BlobFilesRemoved)
	}
	endReconcile(reconcileFailed)
	if startupErr := startupError(); startupErr != nil {
		return startupErr
	}

	phase.Set("starting server")
	stopStartupWatch()
	if startupErr := startupError(); startupErr != nil {
		return startupErr
	}

	endServer := audit.phase("server", startupPhaseBudget, incident.Data{}, false)
	srv := newServerForDaemon(cfg, storage)
	srv.audit = audit
	srv.leaves.audit = audit
	srv.leaves.gates.audit = audit
	bootstrap.Stop()
	bootstrapStopped = true
	if err := srv.Start(listener); err != nil {
		endServer(true)
		srv.Stop()
		<-srv.shutdownComplete
		return fmt.Errorf("starting server: %w", err)
	}
	endServer(false)
	listenerOwned = false

	select {
	case <-srv.shutdown:
	case sig := <-sigCh:
		slog.Info("shutdown signal received", "signal", sig.String())
		srv.Stop()
	}
	<-srv.shutdownComplete
	return nil
}