package library import ( "context" "errors" "time" ) // filesGate keeps a library scan and a duplicate-resolver pass from running // at once. A full scan holds it for its whole length and the watcher for each // batch; a resolver pass runs only while no one else holds it. The scan // rewrites tracks from the files it reads, and the pass decides from those // tracks which copies are one song: run together, the pass would decide from // a library half-read. // // A scan that starts during a resolver pass waits for the pass to finish, // up to filesWaitLimit. A resolver pass that finds the gate taken is put off // and tried again (DuplicateResolveWorker). var filesGate = make(gate, 1) // filesWaitLimit is how long a scan waits for a resolver pass to let go of // the files. A pass takes minutes; one still holding them after this long is // stuck, and the scan gives up rather than wait forever. const filesWaitLimit = 30 * time.Minute // errFilesBusy is a scan giving up on a resolver pass that held the files // past filesWaitLimit. var errFilesBusy = errors.New("library files held by a duplicate-resolver pass past the wait limit") // gate is a lock that a waiter can give up on. type gate chan struct{} // acquire takes the gate, or returns ctx's error when ctx ends first and // errFilesBusy once limit has passed. func (g gate) acquire(ctx context.Context, limit time.Duration) error { t := time.NewTimer(limit) defer t.Stop() select { case g <- struct{}{}: return nil case <-ctx.Done(): return ctx.Err() case <-t.C: return errFilesBusy } } // tryAcquire takes the gate if no one holds it, and reports whether it did. func (g gate) tryAcquire() bool { select { case g <- struct{}{}: return true default: return false } } // release lets go of a gate acquire or tryAcquire took. func (g gate) release() { <-g }