navidrome/core/artwork/tee_reader.go
Deluan 7307fd716b fix(artwork): close the underlying stream from the tee; rename to tee_reader
The tee was built around io.NopCloser(r) and teeCachedStream.Close only closed the
tee, so the underlying CachedStream (an open cache-file fd, or the raw source stream
when the image cache is disabled) was never closed — one fd leaked per teed serve,
enough to exhaust the process limit during a client's initial cover sync. The tee now
wraps the stream directly and its Close propagates; teeCachedStream is gone (all
artwork handlers io.Copy, none Seek). The file is renamed to tee_reader.go since the
wrapper is generic, not blurhash-specific.
2026-07-17 21:13:03 -04:00

48 lines
1.1 KiB
Go

package artwork
import (
"bytes"
"io"
)
// teeReader mirrors bytes read from src into buf, and on Close invokes onComplete with the captured
// bytes only if the stream was fully consumed (EOF) and stayed within maxBytes. Partial reads and
// oversized streams are skipped, so the callback only ever receives a complete, bounded payload.
type teeReader struct {
src io.ReadCloser
buf bytes.Buffer
maxBytes int
onComplete func(data []byte)
eof bool
over bool
done bool
}
func newTeeReader(src io.ReadCloser, maxBytes int, onComplete func(data []byte)) *teeReader {
return &teeReader{src: src, maxBytes: maxBytes, onComplete: onComplete}
}
func (t *teeReader) Read(p []byte) (int, error) {
n, err := t.src.Read(p)
if n > 0 && !t.over {
if t.buf.Len()+n > t.maxBytes {
t.over = true
t.buf.Reset()
} else {
t.buf.Write(p[:n])
}
}
if err == io.EOF {
t.eof = true
}
return n, err
}
func (t *teeReader) Close() error {
err := t.src.Close()
if !t.done && t.eof && !t.over && t.onComplete != nil {
t.done = true
t.onComplete(t.buf.Bytes())
}
return err
}