package build import ( "context" "crypto/rand" "encoding/hex" "errors" "fmt" "io" "io/fs" "log" "math" "os" "path/filepath" "runtime" "sort" "strconv" "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/protect" "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 DecoysLinked int DecoysRemoved 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 records []*process.Record 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 := b.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, recs := b.carryOver(previous, plan.album.Slug, id); m != nil { plan.manifest = m plan.records = recs 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 published []*albumPlan for _, plan := range plans { if plan.manifest != nil { published = append(published, plan) } } sort.SliceStable(published, func(i, j int) bool { mi, mj := published[i].manifest, published[j].manifest return album.Before( album.SortKey{Order: mi.Order, Date: mi.Date, Slug: mi.Slug}, album.SortKey{Order: mj.Order, Date: mj.Date, Slug: mj.Slug}) }) manifests := make([]*site.Manifest, len(published)) var lives []*live seenLive := map[string]bool{} for i, plan := range published { manifests[i] = plan.manifest if plan.manifest.Hidden { sum.Hidden++ } for _, rec := range plan.records { if !seenLive[rec.Hash] { seenLive[rec.Hash] = true lives = append(lives, &live{rec: rec, album: i}) } } } sum.Albums = len(manifests) secret, err := protect.NewSecret() if err != nil { return nil, err } keyer := protect.NewKeyer(secret) coverKey := keyer.Cover() covers := make(map[string]bool, len(manifests)) for _, m := range manifests { covers[m.Cover.Hash] = true } keys := make(map[string][32]byte, len(lives)) for _, l := range lives { if covers[l.rec.Hash] { keys[l.rec.Hash] = coverKey } else { keys[l.rec.Hash] = keyer.Photo(l.rec.Hash) } } poolStart := time.Now() pools, linked, err := b.pools(lives, keys) if err != nil { return nil, fmt.Errorf("decoys: %w", err) } sum.DecoysLinked = linked b.log.Printf("protect: %d pools sealed, %d decoys linked in %s", len(pools), linked, round(time.Since(poolStart))) if err := b.writeBuild(id, manifests, secret, keys, coverKey, lives, pools); 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, removedDecoys, err := b.cleanup(id) sum.BuildsRemoved = removedBuilds sum.TilesRemoved = removedTiles sum.DecoysRemoved = removedDecoys 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) tiles() site.Tiles { tiles := site.Tiles{ Format: b.cfg.Images.Format, 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 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: site.Layout(&records[plan.coverHash].Pyramid), OG: plan.ogHash, Photos: make([]site.Photo, len(a.Photos)), } plan.records = make([]*process.Record, 0, len(a.Photos)+1) for i, photo := range a.Photos { rec := records[plan.hashes[i]] plan.records = append(plan.records, rec) p := site.Photo{ Pyramid: *site.Layout(&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 } plan.records = append(plan.records, records[plan.coverHash]) 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, []*process.Record) { if previous == "" { return nil, 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() || m.Cover == nil { return nil, nil } hashes := make([]string, 0, len(m.Photos)+1) for _, p := range m.Photos { hashes = append(hashes, p.Hash) } hashes = append(hashes, m.Cover.Hash) records := make([]*process.Record, len(hashes)) for i, hash := range hashes { rec, ok := b.proc.Lookup(hash) if !ok || len(rec.Levels) == 0 { return nil, nil } for _, level := range rec.Levels { if level.TileSize <= 0 || len(level.Tiles) != level.Cols*level.Rows { return nil, nil } } records[i] = rec } m.Build = id return &m, records } func buildStamp(t time.Time) string { return t.Format("20060102-150405") + fmt.Sprintf("-%06d", t.Nanosecond()/1000) } func (b *builder) newBuildID() (string, error) { var suffix [3]byte if _, err := rand.Read(suffix[:]); err != nil { return "", err } t := time.Now().UTC().Truncate(time.Microsecond) if entries, err := os.ReadDir(b.builds); err == nil { for _, entry := range entries { if last, ok := parseStamp(entry.Name()); ok && !t.After(last) { t = last.Add(time.Microsecond) } } } return buildStamp(t) + "-" + hex.EncodeToString(suffix[:]), nil } func parseStamp(name string) (time.Time, bool) { if len(name) < 15 { return time.Time{}, false } t, err := time.Parse("20060102-150405", name[:15]) if err != nil { return time.Time{}, false } if len(name) >= 23 && name[15] == '-' && name[22] == '-' { if micro, err := strconv.Atoi(name[16:22]); err == nil { return t.Add(time.Duration(micro) * time.Microsecond), true } } return t.Add(time.Second - time.Microsecond), true } func (b *builder) writeBuild(id string, manifests []*site.Manifest, secret []byte, keys map[string][32]byte, coverKey [32]byte, lives []*live, pools map[string]*pool) 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, Gate: string(b.cfg.Protection.Gate), MinEntropy: b.cfg.Protection.MinEntropy, BaseURL: strings.TrimRight(b.cfg.Server.BaseURL, "/"), } public := &site.Gate{Build: id, Mode: page.Gate, Cover: hex.EncodeToString(coverKey[:]), MinEntropy: page.MinEntropy} if err := fsutil.WriteFileAtomic(filepath.Join(stage, protect.SecretName), secret, 0o600); err != nil { return err } if err := fsutil.WriteFileAtomic(filepath.Join(stage, "robots.txt"), []byte(site.Robots), 0o644); err != nil { return err } if err := writeRefs(filepath.Join(stage, refsName), lives, pools); err != nil { return err } index := &site.Index{Build: id, Tiles: b.tiles(), Gate: public, Albums: []site.IndexAlbum{}} for _, m := range manifests { m.Gate = public if public.Mode == site.GateOff { open := *public open.Keys = make(map[string]string, len(m.Photos)) for _, p := range m.Photos { k := keys[p.Hash] open.Keys[p.Hash] = hex.EncodeToString(k[:]) } m.Gate = &open } 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) poolDir := filepath.Join(dir, site.PoolDir) if err := os.MkdirAll(poolDir, 0o755); err != nil { errs[i] = err return } hashes := make([]string, 0, len(m.Photos)+1) for _, p := range m.Photos { hashes = append(hashes, p.Hash) } hashes = append(hashes, m.Cover.Hash) for _, hash := range hashes { if err := fsutil.WritePublic(filepath.Join(poolDir, site.PoolName(id, hash)), pools[hash].data); 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, int, error) { entries, err := os.ReadDir(b.builds) if err != nil { return 0, 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, 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) } pooled := map[uint64][]uint64{} for _, name := range kept { if err := readRefs(filepath.Join(b.builds, name, refsName), pooled); err != nil { if !errors.Is(err, fs.ErrNotExist) { errs = append(errs, fmt.Errorf("build %s pool list unreadable, keeping all decoys: %w", name, err)) } return removed, tilesRemoved, 0, errors.Join(errs...) } } decoysRemoved, err := b.sweepDecoys(pooled) if err != nil { errs = append(errs, err) } return removed, tilesRemoved, decoysRemoved, 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, %d decoys linked; removed %d old builds, %d tile folders and %d stale decoys; %s total", s.ID, s.Albums, s.Hidden, s.Skipped, s.Carried, s.Processed, s.TilesWritten, megabytes(s.BytesWritten), s.Cached, s.Failed, s.DecoysLinked, s.BuildsRemoved, s.TilesRemoved, s.DecoysRemoved, round(s.Duration)) }