package server import ( "errors" "fmt" "io" "io/fs" "os" "path" "path/filepath" "sort" "strings" "syscall" ) // Bounds on the partial work a retried visit inherits from the failed one. const ( carryMaxFiles = 200 carryMaxFileBytes = 1 << 20 carryMaxTotal = 8 << 20 carryDir = "previous-attempt" ) // carryPartialWork copies a failed visit's output.md and private/ files // (bounded) into the retried visit's turn directory under previous-attempt/ // and returns the markdown that tells the stage about them, or "" when there // was nothing to carry. Symlinks and special files are skipped; the source is // read through os.Root so nothing outside the failed turn is reachable. func carryPartialWork(sourceTurn, targetTurn string) string { source, err := os.OpenRoot(sourceTurn) if err != nil { return "" } defer source.Close() var names []string if info, err := source.Lstat("output.md"); err == nil && info.Mode().IsRegular() { names = append(names, "output.md") } skipped := 0 _ = fs.WalkDir(source.FS(), "private", func(name string, entry fs.DirEntry, walkErr error) error { if walkErr != nil { return nil } if entry.Type().IsRegular() { names = append(names, name) } return nil }) sort.Strings(names[min(1, len(names)):]) target := filepath.Join(targetTurn, carryDir) var copied []string total := int64(0) for _, name := range names { if len(copied) >= carryMaxFiles { skipped++ continue } info, err := source.Lstat(name) if err != nil || !info.Mode().IsRegular() || info.Size() > carryMaxFileBytes || total+info.Size() > carryMaxTotal { skipped++ continue } if err := copyCarried(source, name, filepath.Join(target, filepath.FromSlash(name))); err != nil { skipped++ continue } total += info.Size() copied = append(copied, fmt.Sprintf("%s (%d bytes)", name, info.Size())) } if len(copied) == 0 { return "" } var b strings.Builder b.WriteString("\n## Partial work from the failed attempt\n\n") fmt.Fprintf(&b, "The failed visit's output.md and private/ files are copied, read-only, into %s:\n\n", target) for _, line := range copied { b.WriteString("- " + line + "\n") } if skipped > 0 { fmt.Fprintf(&b, "- … %d more not copied (over the size or count bound)\n", skipped) } b.WriteString("\nReuse what is still valid instead of redoing it.\n") return b.String() } func copyCarried(source *os.Root, name, destination string) error { if path.Clean(name) != name || strings.HasPrefix(name, "../") { return errors.New("invalid name") } src, err := source.OpenFile(name, os.O_RDONLY|syscall.O_NOFOLLOW, 0) if err != nil { return err } defer src.Close() if err := os.MkdirAll(filepath.Dir(destination), 0o700); err != nil { return err } dst, err := os.OpenFile(destination, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) if err != nil { return err } _, copyErr := io.Copy(dst, io.LimitReader(src, carryMaxFileBytes)) if closeErr := dst.Close(); copyErr == nil { copyErr = closeErr } return copyErr }