Files
LuPhoto/internal/build/build.go
T
2026-11-04 05:10:46 -08:00

664 lines
17 KiB
Go

package build
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"math"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/luciochen233/luphoto/internal/album"
"github.com/luciochen233/luphoto/internal/config"
"github.com/luciochen233/luphoto/internal/fsutil"
"github.com/luciochen233/luphoto/internal/process"
"github.com/luciochen233/luphoto/internal/site"
)
type Summary struct {
ID string
Albums int
Hidden int
Skipped int
Carried int
Processed int
Cached int
Failed int
TilesWritten int
BytesWritten int64
BuildsRemoved int
TilesRemoved int
Duration time.Duration
}
type albumPlan struct {
album *album.Album
coverHash string
ogHash string
coverCrop [4]int
hashes []string
pending int
fresh int
reused int
failed []string
problem string
manifest *site.Manifest
carriedOut bool
}
type builder struct {
cfg *config.Config
proc *process.Processor
log *log.Logger
start time.Time
builds string
current string
}
func Run(ctx context.Context, cfg *config.Config, logger *log.Logger) (*Summary, error) {
start := time.Now()
if info, err := os.Stat(cfg.Paths.Albums); err != nil || !info.IsDir() {
return nil, fmt.Errorf("albums folder %s is missing or not a folder", cfg.Paths.Albums)
}
proc, err := process.New(ctx, cfg)
if err != nil {
return nil, err
}
b := &builder{
cfg: cfg,
proc: proc,
log: logger,
start: start,
builds: filepath.Join(cfg.Paths.Output, "builds"),
current: filepath.Join(cfg.Paths.Output, "current"),
}
if err := os.MkdirAll(b.builds, 0o755); err != nil {
return nil, err
}
proc.CleanWork()
logger.Printf("luphoto: libvips %s, %d workers x %d vips threads, albums %s, output %s", proc.VipsVersion(), cfg.Build.Workers, proc.Threads, cfg.Paths.Albums, cfg.Paths.Output)
return b.run(ctx)
}
func (b *builder) run(ctx context.Context) (*Summary, error) {
sum := &Summary{}
albums, problems, err := album.Scan(b.cfg.Paths.Albums)
if err != nil {
return nil, err
}
plans := make([]*albumPlan, 0, len(albums)+len(problems))
for _, a := range albums {
plans = append(plans, &albumPlan{album: a})
}
for _, p := range problems {
plans = append(plans, &albumPlan{album: &album.Album{Slug: p.Slug}, problem: p.Reason})
}
var paths []string
seen := map[string]bool{}
for _, plan := range plans {
if plan.problem != "" {
continue
}
for _, photo := range plan.album.Photos {
if !seen[photo.Path] {
seen[photo.Path] = true
paths = append(paths, photo.Path)
}
}
}
inspectStart := time.Now()
sources, failures := b.proc.Inspect(ctx, paths)
if err := ctx.Err(); err != nil {
return nil, err
}
b.log.Printf("inspect: %d photos hashed in %s", len(paths), round(time.Since(inspectStart)))
jobs := map[string]*process.Job{}
records := map[string]*process.Record{}
users := map[string][]*albumPlan{}
var order []*process.Job
for _, plan := range plans {
if plan.problem != "" {
continue
}
a := plan.album
for _, photo := range a.Photos {
if err := failures[photo.Path]; err != nil {
plan.problem = fmt.Sprintf("%s: %v", photo.File, err)
break
}
}
if plan.problem != "" {
continue
}
coverSrc := sources[filepath.Join(a.Dir, a.Cover.Photo)]
crop, err := coverCrop(a.Cover, coverSrc.Width, coverSrc.Height)
if err != nil {
plan.problem = err.Error()
continue
}
plan.coverCrop = crop
plan.coverHash = b.proc.CoverHash(coverSrc, crop)
ogRegion := process.OGRegion(coverSrc.Width, coverSrc.Height, crop)
plan.ogHash = b.proc.OGHash(coverSrc, ogRegion)
if !b.proc.HasOG(plan.ogHash) {
if _, ok := jobs[plan.ogHash]; !ok {
job := &process.Job{Hash: plan.ogHash, Kind: "og", Label: a.Slug + "/" + a.Cover.Photo, Source: coverSrc, Crop: &ogRegion}
jobs[plan.ogHash] = job
order = append(order, job)
}
plan.pending++
users[plan.ogHash] = append(users[plan.ogHash], plan)
}
type need struct {
hash string
kind string
label string
src *process.Source
crop *[4]int
record *process.Record
}
var needs []need
for _, photo := range a.Photos {
src := sources[photo.Path]
needs = append(needs, need{hash: src.Hash, kind: "photo", label: a.Slug + "/" + photo.File, src: src, record: src.Record})
}
coverRecord, _ := b.proc.Lookup(plan.coverHash)
c := crop
needs = append(needs, need{hash: plan.coverHash, kind: "cover", label: a.Slug + "/" + a.Cover.Photo, src: coverSrc, crop: &c, record: coverRecord})
for _, n := range needs {
plan.hashes = append(plan.hashes, n.hash)
if n.record != nil {
records[n.hash] = n.record
plan.reused++
continue
}
if _, ok := records[n.hash]; ok {
plan.reused++
continue
}
plan.fresh++
plan.pending++
users[n.hash] = append(users[n.hash], plan)
if _, ok := jobs[n.hash]; !ok {
job := &process.Job{Hash: n.hash, Kind: n.kind, Label: n.label, Source: n.src, Crop: n.crop}
jobs[n.hash] = job
order = append(order, job)
}
}
}
for _, plan := range plans {
if plan.problem == "" && plan.pending == 0 {
b.logAlbum(plan)
}
}
b.proc.Run(ctx, order, b.cfg.Build.Workers, func(res process.Result) {
job := res.Job
if res.Err != nil {
sum.Failed++
if ctx.Err() == nil {
b.log.Printf("%s %s: failed after %s: %v", job.Kind, job.Label, round(res.Duration), res.Err)
}
} else if job.Kind == "og" {
b.log.Printf("og %s: %dx%d JPEG in %s", job.Label, res.Record.Width, res.Record.Height, round(res.Duration))
} else {
sum.Processed++
records[job.Hash] = res.Record
sum.TilesWritten += res.Record.TileCount()
sum.BytesWritten += res.Record.TileBytes()
b.log.Printf("%s %s: %dx%d, %d levels, %d tiles, %s in %s", job.Kind, job.Label,
res.Record.Width, res.Record.Height, len(res.Record.Levels), res.Record.TileCount(),
megabytes(res.Record.TileBytes()), round(res.Duration))
}
for _, plan := range users[job.Hash] {
if res.Err != nil {
plan.failed = append(plan.failed, fmt.Sprintf("%s: %v", job.Label, res.Err))
}
plan.pending--
if plan.pending == 0 {
if len(plan.failed) > 0 {
plan.problem = strings.Join(plan.failed, "; ")
} else {
b.logAlbum(plan)
}
}
}
})
if err := ctx.Err(); err != nil {
return nil, err
}
sum.Cached = len(records) - sum.Processed
id, err := newBuildID()
if err != nil {
return nil, err
}
sum.ID = id
previous := b.previousBuild()
for _, plan := range plans {
if plan.problem == "" {
plan.manifest = b.manifest(id, plan, records)
continue
}
sum.Skipped++
if m := b.carryOver(previous, plan.album.Slug, id); m != nil {
plan.manifest = m
plan.carriedOut = true
sum.Carried++
b.log.Printf("skip album %s: %s (previous version stays live)", plan.album.Slug, plan.problem)
} else {
b.log.Printf("skip album %s: %s", plan.album.Slug, plan.problem)
}
}
var manifests []*site.Manifest
for _, plan := range plans {
if plan.manifest != nil {
manifests = append(manifests, plan.manifest)
}
}
sort.SliceStable(manifests, func(i, j int) bool {
return album.Before(
album.SortKey{Order: manifests[i].Order, Date: manifests[i].Date, Slug: manifests[i].Slug},
album.SortKey{Order: manifests[j].Order, Date: manifests[j].Date, Slug: manifests[j].Slug})
})
for _, m := range manifests {
if m.Hidden {
sum.Hidden++
}
}
sum.Albums = len(manifests)
if err := b.writeBuild(id, manifests); err != nil {
return nil, err
}
if err := fsutil.SymlinkAtomic(filepath.Join("builds", id), b.current); err != nil {
return nil, fmt.Errorf("switch current: %w", err)
}
removedBuilds, removedTiles, err := b.cleanup(id)
sum.BuildsRemoved = removedBuilds
sum.TilesRemoved = removedTiles
if err != nil {
b.log.Printf("cleanup: %v", err)
}
sum.Duration = time.Since(b.start)
return sum, nil
}
func (b *builder) logAlbum(plan *albumPlan) {
a := plan.album
extra := ""
if a.Unlisted > 0 {
extra = fmt.Sprintf(", %d unlisted JPEG(s) ignored", a.Unlisted)
}
if a.Hidden {
extra += ", hidden"
}
b.log.Printf("album %s: %d photos + cover, %d processed, %d cached%s, ready at %s", a.Slug, len(a.Photos), plan.fresh, plan.reused, extra, round(time.Since(b.start)))
}
func coverCrop(c *album.Cover, width, height int) ([4]int, error) {
if width <= 0 || height <= 0 {
return [4]int{}, errors.New("cover photo has no size")
}
if c.Crop != nil {
x, y, w, h := c.Crop[0], c.Crop[1], c.Crop[2], c.Crop[3]
if x+w > width || y+h > height {
return [4]int{}, fmt.Errorf("cover.crop [%d, %d, %d, %d] exceeds the %dx%d photo", x, y, w, h, width, height)
}
return [4]int{x, y, w, h}, nil
}
w := width
h := int(math.Round(float64(width) * 9 / 32))
x := 0
if h > height {
h = height
w = min(width, int(math.Round(float64(height)*32/9)))
x = (width - w) / 2
}
focus := 0.5
if c.FocusY != nil {
focus = *c.FocusY
}
y := int(math.Round(focus*float64(height) - float64(h)/2))
y = max(0, min(y, height-h))
return [4]int{x, y, max(1, w), max(1, h)}, nil
}
func (b *builder) overlap() int {
if b.cfg.Images.ScrambleCells {
return 0
}
return b.cfg.Images.Overlap
}
func (b *builder) tiles() site.Tiles {
tiles := site.Tiles{
Format: b.cfg.Images.Format,
TileSize: b.cfg.Images.TileSize,
Overlap: b.overlap(),
Path: "/t/",
}
if b.cfg.Images.ScrambleCells {
tiles.Scrambled = true
tiles.Cell = process.ScrambleCell
}
return tiles
}
func (b *builder) manifest(id string, plan *albumPlan, records map[string]*process.Record) *site.Manifest {
a := plan.album
cover := records[plan.coverHash].Pyramid
m := &site.Manifest{
Build: id,
Slug: a.Slug,
Title: a.Title,
Subtitle: a.Subtitle,
Date: a.Date,
Order: a.Order,
Hidden: a.Hidden,
CollapsedFocusY: *a.CollapsedFocusY,
ShowEXIF: *a.ShowEXIF,
Tiles: b.tiles(),
Cover: &cover,
OG: plan.ogHash,
Photos: make([]site.Photo, len(a.Photos)),
}
for i, photo := range a.Photos {
rec := records[plan.hashes[i]]
p := site.Photo{
Pyramid: rec.Pyramid,
Title: photo.Title,
Caption: photo.Caption,
Alt: photo.Alt,
Slides: photo.Slides,
}
if m.ShowEXIF && rec.EXIF != nil {
exif := *rec.EXIF
exif.Exposure = process.NormalizeExposure(exif.Exposure)
p.EXIF = &exif
}
m.Photos[i] = p
}
return m
}
func (b *builder) previousBuild() string {
target, err := os.Readlink(b.current)
if err != nil {
return ""
}
id := filepath.Base(target)
if _, err := os.Stat(filepath.Join(b.builds, id)); err != nil {
return ""
}
return id
}
func (b *builder) carryOver(previous, slug, id string) *site.Manifest {
if previous == "" {
return nil
}
var m site.Manifest
path := filepath.Join(b.builds, previous, "a", slug, site.ManifestName(previous))
if err := fsutil.ReadJSON(path, &m); err != nil || m.Slug != slug || m.Tiles != b.tiles() {
return nil
}
m.Build = id
return &m
}
func newBuildID() (string, error) {
var suffix [3]byte
if _, err := rand.Read(suffix[:]); err != nil {
return "", err
}
return time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(suffix[:]), nil
}
func (b *builder) writeBuild(id string, manifests []*site.Manifest) error {
stage := fsutil.TempName(filepath.Join(b.builds, id))
if err := os.MkdirAll(filepath.Join(stage, "a"), 0o755); err != nil {
return err
}
ok := false
defer func() {
if !ok {
_ = os.RemoveAll(stage)
}
}()
for _, shared := range []string{"t", "og"} {
if err := os.Symlink(filepath.Join("..", "..", shared), filepath.Join(stage, shared)); err != nil {
return fmt.Errorf("link %s: %w", shared, err)
}
}
assets := site.StaticAssets()
if err := assets.Write(stage); err != nil {
return err
}
page := site.Page{
Assets: assets,
BudgetMS: b.cfg.Loading.BudgetMS,
MaxDPR: b.cfg.Loading.MaxDPR,
Concurrency: b.cfg.Loading.Concurrency,
BlockContextMenu: b.cfg.Protection.BlockContextMenu,
BaseURL: strings.TrimRight(b.cfg.Server.BaseURL, "/"),
}
index := &site.Index{Build: id, Tiles: b.tiles(), Albums: []site.IndexAlbum{}}
for _, m := range manifests {
if m.Hidden {
continue
}
index.Albums = append(index.Albums, site.IndexAlbum{
Slug: m.Slug,
Title: m.Title,
Subtitle: m.Subtitle,
Date: m.Date,
CollapsedFocusY: m.CollapsedFocusY,
Photos: len(m.Photos),
Manifest: site.ManifestURL(id, m.Slug),
Cover: m.Cover,
OG: m.OG,
})
}
errs := make([]error, len(manifests)+1)
var wg sync.WaitGroup
limit := make(chan struct{}, runtime.NumCPU())
for i, m := range manifests {
wg.Add(1)
go func(i int, m *site.Manifest) {
defer wg.Done()
limit <- struct{}{}
defer func() { <-limit }()
dir := filepath.Join(stage, "a", m.Slug)
if err := os.MkdirAll(dir, 0o755); err != nil {
errs[i] = err
return
}
data, err := fsutil.EncodeJSON(m)
if err == nil {
err = fsutil.WritePublicAtomic(filepath.Join(dir, site.ManifestName(id)), data)
}
if err != nil {
errs[i] = err
return
}
html, err := fsutil.Render(func(w io.Writer) error { return site.RenderAlbum(w, m, page) })
if err == nil {
err = fsutil.WritePublicAtomic(filepath.Join(dir, "index.html"), html)
}
errs[i] = err
}(i, m)
}
wg.Add(1)
go func() {
defer wg.Done()
data, err := fsutil.EncodeJSON(index)
if err == nil {
err = fsutil.WritePublicAtomic(filepath.Join(stage, site.IndexName(id)), data)
}
if err != nil {
errs[len(manifests)] = err
return
}
html, err := fsutil.Render(func(w io.Writer) error { return site.RenderIndex(w, index, page) })
if err == nil {
err = fsutil.WritePublicAtomic(filepath.Join(stage, "index.html"), html)
}
if err == nil {
html, err = fsutil.Render(func(w io.Writer) error { return site.RenderNotFound(w, id, page) })
}
if err == nil {
err = fsutil.WritePublicAtomic(filepath.Join(stage, "404.html"), html)
}
errs[len(manifests)] = err
}()
wg.Wait()
if err := errors.Join(errs...); err != nil {
return err
}
if err := os.Rename(stage, filepath.Join(b.builds, id)); err != nil {
return err
}
ok = true
return nil
}
func (b *builder) cleanup(id string) (int, int, error) {
entries, err := os.ReadDir(b.builds)
if err != nil {
return 0, 0, err
}
var names []string
for _, entry := range entries {
name := entry.Name()
if strings.HasPrefix(name, ".") {
if strings.Contains(name, fsutil.TempMarker) {
_ = os.RemoveAll(filepath.Join(b.builds, name))
}
continue
}
if entry.IsDir() {
names = append(names, name)
}
}
sort.Sort(sort.Reverse(sort.StringSlice(names)))
live := b.previousBuild()
var kept []string
removed := 0
var errs []error
for i, name := range names {
if i < b.cfg.Build.KeepBuilds || name == id || name == live {
kept = append(kept, name)
continue
}
if err := os.RemoveAll(filepath.Join(b.builds, name)); err != nil {
errs = append(errs, err)
kept = append(kept, name)
continue
}
removed++
}
refs := map[string]bool{}
ogRefs := map[string]bool{}
for _, name := range kept {
if err := collectRefs(filepath.Join(b.builds, name), name, refs, ogRefs); err != nil {
errs = append(errs, fmt.Errorf("build %s unreadable, keeping all tiles: %w", name, err))
return removed, 0, errors.Join(errs...)
}
}
tilesRemoved, err := b.proc.ForgetUnreferenced(refs)
if err != nil {
errs = append(errs, err)
}
if _, err := b.proc.ForgetOG(ogRefs); err != nil {
errs = append(errs, err)
}
return removed, tilesRemoved, errors.Join(errs...)
}
type pyramidRef struct {
Hash string `json:"hash"`
}
func collectRefs(dir, id string, refs, ogRefs map[string]bool) error {
var index struct {
Albums []struct {
Cover *pyramidRef `json:"cover"`
OG string `json:"og"`
} `json:"albums"`
}
if err := fsutil.ReadJSON(filepath.Join(dir, site.IndexName(id)), &index); err != nil {
return err
}
for _, a := range index.Albums {
if a.Cover != nil {
refs[a.Cover.Hash] = true
}
if a.OG != "" {
ogRefs[a.OG] = true
}
}
albums, err := os.ReadDir(filepath.Join(dir, "a"))
if err != nil {
return err
}
for _, entry := range albums {
if !entry.IsDir() {
continue
}
var m struct {
Cover *pyramidRef `json:"cover"`
OG string `json:"og"`
Photos []pyramidRef `json:"photos"`
}
if err := fsutil.ReadJSON(filepath.Join(dir, "a", entry.Name(), site.ManifestName(id)), &m); err != nil {
return err
}
if m.Cover != nil {
refs[m.Cover.Hash] = true
}
if m.OG != "" {
ogRefs[m.OG] = true
}
for _, p := range m.Photos {
refs[p.Hash] = true
}
}
return nil
}
func round(d time.Duration) time.Duration {
switch {
case d >= 10*time.Second:
return d.Round(100 * time.Millisecond)
case d >= time.Second:
return d.Round(10 * time.Millisecond)
default:
return d.Round(time.Millisecond)
}
}
func megabytes(n int64) string {
return fmt.Sprintf("%.1f MB", float64(n)/(1<<20))
}
func (s *Summary) String() string {
return fmt.Sprintf("build %s: %d albums (%d hidden, %d skipped, %d kept from previous build), %d pyramids processed (%d tiles, %s), %d cached, %d failed; removed %d old builds and %d tile folders; %s total",
s.ID, s.Albums, s.Hidden, s.Skipped, s.Carried, s.Processed, s.TilesWritten, megabytes(s.BytesWritten), s.Cached, s.Failed, s.BuildsRemoved, s.TilesRemoved, round(s.Duration))
}