package process import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "errors" "fmt" "io/fs" "os" "path/filepath" "runtime" "sort" "strconv" "strings" "sync" "time" "github.com/luciochen233/luphoto/internal/config" "github.com/luciochen233/luphoto/internal/fsutil" ) const processorVersion = "luphoto-pyramid-2" type Level struct { Width int `json:"width"` Height int `json:"height"` TileSize int `json:"tile_size"` Overlap int `json:"overlap,omitempty"` Cols int `json:"cols"` Rows int `json:"rows"` Quality int `json:"quality"` Tiles []string `json:"tiles"` Bytes []int64 `json:"bytes"` } type Pyramid struct { Hash string `json:"hash"` Width int `json:"width"` Height int `json:"height"` Levels []Level `json:"levels"` Seed string `json:"seed"` Scramble string `json:"scramble,omitempty"` } type Record struct { Pyramid Kind string `json:"kind"` Format string `json:"format"` TileSize int `json:"tile_size"` Overlap int `json:"overlap"` Crop []int `json:"crop,omitempty"` EXIF *EXIF `json:"exif,omitempty"` Processed time.Time `json:"processed"` } func (r *Record) TileBytes() int64 { var total int64 for _, level := range r.Levels { for _, b := range level.Bytes { total += b } } return total } func (r *Record) TileCount() int { n := 0 for _, level := range r.Levels { n += len(level.Tiles) } return n } type Processor struct { images config.Images vips *Vips key []byte fingerprint string TilesDir string OGDir string StateDir string recordsDir string workDir string Threads int } func New(ctx context.Context, cfg *config.Config) (*Processor, error) { tiles := filepath.Join(cfg.Paths.Output, "t") og := filepath.Join(cfg.Paths.Output, "og") records := filepath.Join(cfg.State, "pyramids") work := filepath.Join(cfg.Paths.Cache, "work") for _, dir := range []string{cfg.Paths.Output, tiles, og, cfg.State, records, cfg.Paths.Cache, work} { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, err } } key, err := SiteKey(cfg.State) if err != nil { return nil, err } threads := runtime.NumCPU() / cfg.Build.Workers if threads < 1 { threads = 1 } env := os.Environ() if os.Getenv("VIPS_CONCURRENCY") == "" { env = append(env, "VIPS_CONCURRENCY="+strconv.Itoa(threads)) } env = append(env, "TMPDIR="+work) v, err := DetectVips(ctx, env) if err != nil { return nil, err } img := cfg.Images keySum := sha256.Sum256(key) format := img.Format if format == "webp" { format += "+smart_subsample" } fingerprint := strings.Join([]string{ processorVersion, "tile=" + strconv.Itoa(img.TileSize), "overlap=" + strconv.Itoa(img.Overlap), "format=" + format, fmt.Sprintf("q=%d,%d,%d", img.Quality.Top, img.Quality.Mid, img.Quality.Low), "min_levels=" + strconv.Itoa(img.MinLevels), "min_grid=" + strconv.Itoa(img.MinGrid), "seed=" + strconv.Itoa(img.SeedPx), "names=" + img.TileNames, "scramble=" + strconv.FormatBool(img.ScrambleCells), "key=" + hex.EncodeToString(keySum[:4]), }, "|") return &Processor{ images: img, vips: v, key: key, fingerprint: fingerprint, TilesDir: tiles, OGDir: og, StateDir: cfg.State, recordsDir: records, workDir: work, Threads: threads, }, nil } func (p *Processor) VipsVersion() string { return p.vips.Version } func SiteKey(state string) ([]byte, error) { path := filepath.Join(state, "site.key") if err := os.MkdirAll(state, 0o755); err != nil { return nil, err } key, err := os.ReadFile(path) if err == nil { if len(key) != 32 { return nil, fmt.Errorf("site key %s: expected 32 bytes, found %d", path, len(key)) } return key, nil } if !errors.Is(err, fs.ErrNotExist) { return nil, err } key = make([]byte, 32) if _, err := rand.Read(key); err != nil { return nil, err } if err := fsutil.WriteFileAtomic(path, key, 0o600); err != nil { return nil, err } return key, nil } func (p *Processor) recordPath(hash string) string { return filepath.Join(p.recordsDir, hash+".json") } func (p *Processor) Lookup(hash string) (*Record, bool) { var rec Record if err := fsutil.ReadJSON(p.recordPath(hash), &rec); err != nil || rec.Hash != hash { return nil, false } info, err := os.Stat(filepath.Join(p.TilesDir, hash)) if err != nil || !info.IsDir() { return nil, false } return &rec, true } type Job struct { Hash string Kind string Label string Source *Source Crop *[4]int } func (j *Job) pixels() int { if j.Kind == "og" { return 0 } if j.Crop != nil { return j.Crop[2] * j.Crop[3] } return j.Source.Width * j.Source.Height } type Result struct { Job *Job Record *Record Err error Duration time.Duration } func (p *Processor) Run(ctx context.Context, jobs []*Job, workers int, done func(Result)) { ordered := append([]*Job(nil), jobs...) sort.SliceStable(ordered, func(i, j int) bool { return ordered[i].pixels() > ordered[j].pixels() }) queue := make(chan *Job) var wg sync.WaitGroup var mu sync.Mutex for w := 0; w < min(workers, len(ordered)); w++ { wg.Add(1) go func() { defer wg.Done() for job := range queue { start := time.Now() rec, err := p.process(ctx, job) res := Result{Job: job, Record: rec, Err: err, Duration: time.Since(start)} mu.Lock() done(res) mu.Unlock() } }() } for _, job := range ordered { queue <- job } close(queue) wg.Wait() } func (p *Processor) ForgetUnreferenced(keep map[string]bool) (int, error) { entries, err := os.ReadDir(p.TilesDir) if err != nil { return 0, err } removed := 0 var firstErr error for _, entry := range entries { name := entry.Name() if strings.HasPrefix(name, ".") { if strings.Contains(name, fsutil.TempMarker) { _ = os.RemoveAll(filepath.Join(p.TilesDir, name)) } continue } if keep[name] { continue } if err := os.Remove(p.recordPath(name)); err != nil && !errors.Is(err, fs.ErrNotExist) && firstErr == nil { firstErr = err } if err := os.RemoveAll(filepath.Join(p.TilesDir, name)); err != nil { if firstErr == nil { firstErr = err } continue } removed++ } records, err := os.ReadDir(p.recordsDir) if err == nil { for _, entry := range records { hash := strings.TrimSuffix(entry.Name(), ".json") if !keep[hash] { _ = os.Remove(filepath.Join(p.recordsDir, entry.Name())) } } } return removed, firstErr } func (p *Processor) OGHash(src *Source, region [4]int) string { return p.hashWith(src.digest, fmt.Sprintf("og:%d,%d,%d,%d:%dx%d:q%d", region[0], region[1], region[2], region[3], OGWidth, OGHeight, OGQuality)) } func (p *Processor) HasOG(hash string) bool { info, err := os.Stat(filepath.Join(p.OGDir, hash+".jpg")) return err == nil && info.Mode().IsRegular() && info.Size() > 0 } func (p *Processor) ForgetOG(keep map[string]bool) (int, error) { entries, err := os.ReadDir(p.OGDir) if err != nil { return 0, err } removed := 0 var firstErr error for _, entry := range entries { name := entry.Name() if keep[strings.TrimSuffix(name, ".jpg")] { continue } if err := os.Remove(filepath.Join(p.OGDir, name)); err != nil { if firstErr == nil { firstErr = err } continue } removed++ } return removed, firstErr } func (p *Processor) CleanWork() { entries, err := os.ReadDir(p.workDir) if err != nil { return } for _, entry := range entries { _ = os.RemoveAll(filepath.Join(p.workDir, entry.Name())) } }