Files
pipelines/internal/server/chat_tools_snapshot.go
T

236 lines
7.2 KiB
Go

package server
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/chattools"
"git.a-wan.net/alan/pipelines/internal/paths"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// A shown file up to chattools.MaxSnapshotBytes is copied into the chat's
// snapshot directory (<root>/<session>/<item id>-<nonce>/<name>) when it is
// shown, so the card keeps showing that version however the file changes
// later. The copy lives inside the operator's home, so the /files endpoint
// serves it like any other file. A larger file stays linked: the item records
// its size, modification time and hash, and the subscribe reply says when it
// changed or no longer exists.
// shownHashLimit bounds the live files whose content hash is recorded and
// rechecked; a larger one is compared by size and modification time alone.
const shownHashLimit = 64 << 20
// shownSnapshotGrace keeps an unreferenced snapshot directory this long, so a
// copy taken for an item that is being recorded is never swept.
const shownSnapshotGrace = time.Minute
func defaultSnapshotRoot() (string, error) {
data, err := paths.Data()
if err != nil {
return "", err
}
return filepath.Join(data, "chat-shown"), nil
}
// fileItem records file as a shown item: a snapshot copy when it is small
// enough and the copy succeeds, else the live file with what identifies it.
func (s *chatToolService) fileItem(sessionID, id string, file shownFile, kind, title string) protocol.ChatShownItem {
item := protocol.ChatShownItem{Kind: kind, Title: title, Path: file.path, Name: file.name, Size: file.size, Mime: file.mime}
if file.size <= chattools.MaxSnapshotBytes {
source, err := os.Open(file.path)
if err == nil {
path, size, copyErr := s.writeSnapshot(sessionID, id, file.name, io.LimitReader(source, chattools.MaxSnapshotBytes+1))
source.Close()
if copyErr == nil {
item.Path, item.Size, item.Snapshot, item.Source = path, size, true, file.path
return item
}
err = copyErr
}
log.Printf("chat tools session=%s: snapshot %s: %v; showing the live file", sessionID, file.path, err)
}
if info, err := os.Stat(file.path); err == nil {
item.ModTime = info.ModTime().UnixMilli()
}
if file.size <= shownHashLimit {
item.SHA256, _ = fileSHA256(file.path)
}
return item
}
// writeSnapshot stores content as a new snapshot of item id and returns its
// path and size. It refuses content over the snapshot bound and a root that
// is not inside the operator's home.
func (s *chatToolService) writeSnapshot(sessionID, id, name string, content io.Reader) (string, int64, error) {
if sessionID == "" || filepath.Base(sessionID) != sessionID || filepath.Base(id) != id || id == "" {
return "", 0, errors.New("invalid snapshot owner")
}
if s.snapshotRoot == nil {
return "", 0, errors.New("no snapshot directory")
}
root, err := s.snapshotRoot()
if err != nil {
return "", 0, err
}
var nonce [4]byte
_, _ = rand.Read(nonce[:])
dir := filepath.Join(root, sessionID, id+"-"+hex.EncodeToString(nonce[:]))
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", 0, err
}
if err := s.insideHome(dir); err != nil {
_ = os.RemoveAll(dir)
return "", 0, err
}
path := filepath.Join(dir, safeSnapshotName(name))
out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
_ = os.RemoveAll(dir)
return "", 0, err
}
size, err := io.Copy(out, content)
if err == nil && size > chattools.MaxSnapshotBytes {
err = fmt.Errorf("the file grew past %s while it was copied", humanBytes(chattools.MaxSnapshotBytes))
}
if closeErr := out.Close(); err == nil {
err = closeErr
}
if err != nil {
_ = os.RemoveAll(dir)
return "", 0, err
}
return path, size, nil
}
// insideHome refuses a directory /files would not serve.
func (s *chatToolService) insideHome(dir string) error {
home, err := s.home()
if err != nil {
return err
}
realHome, err := filepath.EvalSymlinks(filepath.Clean(home))
if err != nil {
return err
}
if _, _, err := resolveInsideHome(realHome, dir); err != nil {
return errors.New("the snapshot directory " + dir + " is not inside the operator's home")
}
return nil
}
func safeSnapshotName(name string) string {
name = strings.Map(func(r rune) rune {
if r == '/' || r == '\\' || r < 0x20 || r == 0x7f {
return '_'
}
return r
}, strings.TrimSpace(name))
if name == "" || name == "." || name == ".." {
return "file"
}
return truncateUTF8(name, 200)
}
func fileSHA256(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
digest := sha256.New()
if _, err := io.Copy(digest, io.LimitReader(file, shownHashLimit+1)); err != nil {
return "", err
}
return hex.EncodeToString(digest.Sum(nil)), nil
}
// sweepSnapshots removes a chat's snapshot directories that no retained item
// references any more (pruned by the item limit, or replaced).
func (s *chatToolService) sweepSnapshots(ctx context.Context, sessionID string) {
if s.snapshotRoot == nil || s.shown == nil || filepath.Base(sessionID) != sessionID {
return
}
root, err := s.snapshotRoot()
if err != nil {
return
}
dir := filepath.Join(root, sessionID)
entries, err := os.ReadDir(dir)
if err != nil {
return
}
items, err := s.shown.ChatShownItems(ctx, sessionID)
if err != nil {
return
}
kept := map[string]bool{}
for _, item := range items {
if item.Snapshot && item.Path != "" {
kept[filepath.Dir(item.Path)] = true
}
}
for _, entry := range entries {
path := filepath.Join(dir, entry.Name())
info, err := entry.Info()
if err != nil || kept[path] || s.now().Sub(info.ModTime()) < shownSnapshotGrace {
continue
}
if err := os.RemoveAll(path); err != nil {
log.Printf("chat tools session=%s: remove snapshot %s: %v", sessionID, path, err)
}
}
}
// shownFileState says whether a file item's file still shows what was shown:
// missing when it (or its snapshot) is gone, changed when the live file's
// size, or modification time and content, differ.
func shownFileState(item protocol.ChatShownItem) string {
if item.Path == "" || (item.Kind != protocol.ChatShownFile && item.Kind != protocol.ChatShownImage) {
return ""
}
info, err := os.Stat(item.Path)
if err != nil || !info.Mode().IsRegular() {
return protocol.ChatShownFileMissing
}
if item.Snapshot {
return ""
}
if info.Size() != item.Size {
return protocol.ChatShownFileChanged
}
if item.ModTime == 0 || info.ModTime().UnixMilli() == item.ModTime {
return ""
}
if item.SHA256 != "" && info.Size() <= shownHashLimit {
if digest, err := fileSHA256(item.Path); err == nil && digest == item.SHA256 {
return ""
}
}
return protocol.ChatShownFileChanged
}
// refreshShown brings a chat's listed items up to date for its subscribe
// reply: each file's state, and each followed run's latest summary.
func (s *chatToolService) refreshShown(ctx context.Context, sessionID string, items []protocol.ChatShownItem) []protocol.ChatShownItem {
out := make([]protocol.ChatShownItem, len(items))
for i, item := range items {
item.State = shownFileState(item)
if item.Run != nil {
item = s.refreshRunItem(ctx, sessionID, item, false)
}
out[i] = item
}
return out
}