pkg/service/session/leaf_files.go

package session

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"log/slog"
	"os"
	"path/filepath"
	"strings"
	"time"
	"unicode/utf8"
)

// LeafFile describes a registration, not the contents or existence of its file.
// It is stored in leaf_files config and returned by the leaf_files attach operation.
type LeafFile struct {
	FileID string `json:"file_id"`
	Key    string `json:"key"`
	Path   string `json:"path"`
}

var errLeafStateBusy = errors.New("leaf_busy: Ruby state is in use")

func (s *Storage) leafFilesDir() string {
	return filepath.Join(filepath.Dir(s.blobsDir), "leaf-files")
}

func (s *Storage) leafFileName(path string) (string, error) {
	rel, err := filepath.Rel(s.leafFilesDir(), path)
	if err != nil || !filepath.IsAbs(path) || filepath.Clean(path) != path || !filepath.IsLocal(rel) || rel == "." || strings.ContainsRune(path, '\x00') {
		return "", fmt.Errorf("leaf file path is not inside the managed directory: %q", path)
	}
	return rel, nil
}

func (s *Storage) readLeafFiles(db interface {
	QueryRow(string, ...interface{}) *sql.Row
}, leafID string) ([]LeafFile, error) {
	var value string
	err := db.QueryRow(`SELECT COALESCE((SELECT value FROM leaf_config WHERE leaf_id = leaves.id AND key = ?), '')
FROM leaves WHERE id = ?`, leafFilesConfigKey, leafID).Scan(&value)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, fmt.Errorf("%w: %s", ErrLeafNotFound, leafID)
	}
	if err != nil {
		return nil, err
	}
	var files []LeafFile
	if value != "" {
		if err := json.Unmarshal([]byte(value), &files); err != nil {
			return nil, fmt.Errorf("decode leaf_files: %w", err)
		}
	}
	for _, file := range files {
		if file.FileID == "" {
			return nil, fmt.Errorf("invalid leaf_files descriptor: missing file_id")
		}
		if _, err := s.leafFileName(file.Path); err != nil {
			return nil, err
		}
	}
	return files, nil
}

// AttachLeafFile returns the existing registration for key or creates one.
// It creates only the managed directory; payload I/O belongs to the owner.
func (s *Storage) AttachLeafFile(leafID, key string) (*LeafFile, error) {
	if !utf8.ValidString(key) {
		return nil, fmt.Errorf("leaf file key must be valid UTF-8")
	}
	unlock := s.lockLeaf(leafID)
	defer unlock()
	files, err := s.readLeafFiles(s.db, leafID)
	if err != nil {
		return nil, err
	}
	for _, file := range files {
		if file.Key == key {
			return &file, nil
		}
	}
	root, err := s.openLeafFilesDir(true)
	if err != nil {
		return nil, err
	}
	root.Close()
	// Encode bytes, not path components. Keep a bounded suffix so long keys
	// cannot exceed common filesystem filename limits.
	var suffix strings.Builder
	for i := 0; i < len(key); i++ {
		b := key[i]
		if b >= 'a' && b <= 'z' || b >= 'A' && b <= 'Z' || b >= '0' && b <= '9' || b == '.' || b == '_' || b == '-' {
			suffix.WriteByte(b)
		} else {
			fmt.Fprintf(&suffix, "%%%02X", b)
		}
	}
	encoded := suffix.String()
	if len(encoded) > 120 {
		start := len(encoded) - 120
		// Do not retain a partial percent escape at the truncation boundary.
		if start > 0 && encoded[start-1] == '%' {
			start += 2
		} else if start > 1 && encoded[start-2] == '%' {
			start++
		}
		encoded = encoded[start:]
	}
	id := newID("lf_")
	file := LeafFile{FileID: id, Key: key, Path: filepath.Join(s.leafFilesDir(), id+"-"+encoded)}
	files = append(files, file)
	value, err := json.Marshal(files)
	if err != nil {
		return nil, err
	}
	_, err = s.db.Exec("INSERT OR REPLACE INTO leaf_config (leaf_id, key, value) VALUES (?, ?, ?)", leafID, leafFilesConfigKey, string(value))
	if err != nil {
		return nil, err
	}
	return &file, nil
}

// Open a handle to the managed directory, refusing a symlink at its name.
// Comparing identities also catches replacement between Lstat and OpenRoot.
// Root operations keep subsequent path resolution inside this directory.
func (s *Storage) openLeafFilesDir(create bool) (*os.Root, error) {
	path := s.leafFilesDir()
	if create {
		if err := os.Mkdir(path, 0700); err != nil && !errors.Is(err, os.ErrExist) {
			return nil, err
		}
	}
	before, err := os.Lstat(path)
	if err != nil {
		return nil, err
	}
	if !before.IsDir() {
		return nil, fmt.Errorf("managed leaf-files directory is not a directory or is a symlink: %q", path)
	}
	root, err := os.OpenRoot(path)
	if err != nil {
		return nil, err
	}
	after, err := root.Stat(".")
	if err != nil || !os.SameFile(before, after) {
		root.Close()
		if err != nil {
			return nil, err
		}
		return nil, fmt.Errorf("managed leaf-files directory changed while opening")
	}
	return root, nil
}

// The caller holds the leaf lock, but no transaction or pooled connection.
func (s *Storage) cleanupLeafFiles(leafID, preserved string) error {
	files, err := s.readLeafFiles(s.db, leafID)
	if err != nil || len(files) == 0 {
		return err
	}
	root, err := s.openLeafFilesDir(false)
	if errors.Is(err, os.ErrNotExist) {
		return nil
	}
	if err != nil {
		return err
	}
	defer root.Close()
	for _, file := range files {
		if file.Path == preserved {
			continue
		}
		name, _ := s.leafFileName(file.Path) // readLeafFiles already validated it.
		info, err := root.Lstat(name)
		if errors.Is(err, os.ErrNotExist) {
			continue
		}
		if err != nil {
			return err
		}
		// Remove a symlink itself, never its target. Do not recurse into directories.
		if !info.Mode().IsRegular() && info.Mode()&os.ModeSymlink == 0 {
			return fmt.Errorf("refusing to remove non-file leaf path: %q", file.Path)
		}
		remove := root.Remove
		if s.removeLeafFile != nil {
			remove = func(name string) error { return s.removeLeafFile(root, name) }
		}
		if err := remove(name); err != nil && !errors.Is(err, os.ErrNotExist) {
			return fmt.Errorf("remove leaf file: %w", err)
		}
	}
	return nil
}

// Registrations and alerts are intentional state even before the first turn.
// Explicitly temporary leaves still expire, regardless of that state.
const staleLeaves = `is_temp = 1 OR ((turn_id = '' OR turn_id IS NULL)
AND NOT EXISTS (
    SELECT 1 FROM leaf_config WHERE leaf_id = leaves.id
    AND (key IN ('alert_time', '_service_active') OR (key = 'alert_idle' AND lower(value) = 'true')
         OR (key = 'leaf_files' AND CASE
             WHEN trim(value) = '' THEN 0
             WHEN json_valid(value) THEN CASE
                 WHEN json_type(value) = 'null' THEN 0
                 WHEN json_type(value) = 'array' THEN json_array_length(value) > 0
                 ELSE 1 END
             ELSE 1 END))
))`

func (s *Storage) cleanupEmptyLeaf(leafID string) (string, bool, error) {
	unlock := s.lockLeaf(leafID)
	defer unlock()
	var rootID string
	err := s.db.QueryRow("SELECT root_id FROM leaves WHERE id = ? AND ("+staleLeaves+")", leafID).Scan(&rootID)
	if errors.Is(err, sql.ErrNoRows) {
		return "", false, nil
	}
	if err != nil {
		return rootID, false, err
	}
	stateLock, lockPath, err := s.lockLeafState(leafID)
	if errors.Is(err, errLeafStateBusy) {
		return rootID, false, nil
	}
	if err != nil {
		return rootID, false, err
	}
	if stateLock != nil {
		defer stateLock.Close()
	}
	if err := s.cleanupLeafFiles(leafID, lockPath); err != nil {
		return rootID, false, fmt.Errorf("clean up files for leaf %s: %w", leafID, err)
	}
	tx, err := s.db.Begin()
	if err != nil {
		return rootID, false, err
	}
	defer tx.Rollback()
	// Recheck before deletion; same-leaf mutations share the lock.
	res, err := tx.Exec("DELETE FROM leaves WHERE id = ? AND ("+staleLeaves+")", leafID)
	if err != nil {
		return rootID, false, fmt.Errorf("delete stale leaf: %w", err)
	}
	n, _ := res.RowsAffected()
	if n != 0 {
		now := time.Now().Format(time.RFC3339)
		if _, err := tx.Exec("UPDATE roots SET updated_at = ? WHERE id = ? AND NOT EXISTS (SELECT 1 FROM leaves WHERE root_id = ?)", now, rootID, rootID); err != nil {
			return rootID, false, fmt.Errorf("refresh orphan timestamp: %w", err)
		}
	}
	if err := tx.Commit(); err != nil {
		return rootID, false, err
	}
	if n != 0 {
		if err := s.removeLeafStateLock(lockPath); err != nil {
			slog.Error("post-commit state lock cleanup failed", "leaf_id", leafID, "error", err)
		}
	}
	return rootID, n != 0, nil
}

// Keep the lock name linked until registration deletion commits. Waiters on the
// old inode then either fail the identity check or observe missing registrations.
// An unlink failure is post-commit; do not pretend the leaf can be restored.
func (s *Storage) removeLeafStateLock(path string) error {
	if path == "" {
		return nil
	}
	root, err := s.openLeafFilesDir(false)
	if err != nil {
		return fmt.Errorf("post-commit state lock cleanup: %w", err)
	}
	defer root.Close()
	name, err := s.leafFileName(path)
	if err != nil {
		return err
	}
	if s.removeLeafFile != nil {
		err = s.removeLeafFile(root, name)
	} else {
		err = root.Remove(name)
	}
	if err != nil && !errors.Is(err, os.ErrNotExist) {
		return fmt.Errorf("post-commit state lock cleanup: %w", err)
	}
	return nil
}