Files
lincodex/backend/internal/usecase/files/stream.go
T

173 lines
4.6 KiB
Go

package files
import (
"crypto/sha256"
"errors"
"fmt"
"hash"
"io"
)
// maxEmptyReads bounds reads that return neither data nor an error.
const maxEmptyReads = 100
// uploadReader gives storage exactly the declared number of bytes and hashes
// them on the way. It withholds the last chunk until the source has ended, so
// a longer source never lets storage receive a complete request body. A short
// source ends the stream early with an error. Storage errors are sanitized,
// so the first violation is kept in err for the caller.
type uploadReader struct {
source io.Reader
limited *io.LimitedReader
hash hash.Hash
ended bool
err error
}
func newUploadReader(source io.Reader, size int64) *uploadReader {
return &uploadReader{source: source, limited: &io.LimitedReader{R: source, N: size}, hash: sha256.New()}
}
func (reader *uploadReader) Read(buffer []byte) (int, error) {
if reader.err != nil {
return 0, reader.err
}
if reader.ended {
return 0, io.EOF
}
if reader.limited.N == 0 {
if err := reader.confirmEnd(); err != nil {
return 0, err
}
return 0, io.EOF
}
n, err := reader.limited.Read(buffer)
if err != nil && !errors.Is(err, io.EOF) {
reader.err = fmt.Errorf("files.uploadReader - read source: %w", err)
return n, reader.err
}
if reader.limited.N > 0 {
if errors.Is(err, io.EOF) {
reader.err = fmt.Errorf("files.uploadReader - source ended early: %w", ErrSizeMismatch)
return n, reader.err
}
reader.hash.Write(buffer[:n])
return n, nil
}
// The declared size is reached. Release the final chunk only when the
// source has nothing more.
if !errors.Is(err, io.EOF) {
if endErr := reader.confirmEnd(); endErr != nil {
return 0, endErr
}
}
reader.ended = true
reader.hash.Write(buffer[:n])
return n, nil
}
// confirmEnd reads one byte past the declared size from the source.
func (reader *uploadReader) confirmEnd() error {
var probe [1]byte
for range maxEmptyReads {
n, err := reader.source.Read(probe[:])
switch {
case n > 0:
reader.err = fmt.Errorf("files.uploadReader - source exceeds declared size: %w", ErrTooLarge)
return reader.err
case errors.Is(err, io.EOF):
reader.ended = true
return nil
case err != nil:
reader.err = fmt.Errorf("files.uploadReader - read source: %w", err)
return reader.err
}
}
reader.err = fmt.Errorf("files.uploadReader - read source: %w", io.ErrNoProgress)
return reader.err
}
// finish verifies the whole source after storage reported success. Storage
// may skip reading an empty body, so the end is confirmed here when needed.
func (reader *uploadReader) finish() error {
if reader.err != nil {
return reader.err
}
if reader.limited.N != 0 {
return fmt.Errorf("files.uploadReader - storage did not consume the body: %w", ErrSizeMismatch)
}
if reader.ended {
return nil
}
return reader.confirmEnd()
}
func (reader *uploadReader) sum() []byte { return reader.hash.Sum(nil) }
// File is an open stored file. The caller must close it, including after a
// read error. The context passed to Open is the only time bound on reading:
// storage limits connection setup and the wait for response headers, not the
// body, so the caller sets a deadline that fits the file size and its client,
// and canceling that context aborts reading. Read fails when the stored body
// is shorter or longer than Size.
type File struct {
Size int64
ContentType string
body io.ReadCloser
remaining int64
ended bool
closed bool
}
func (file *File) Read(buffer []byte) (int, error) {
if file.closed {
return 0, fmt.Errorf("File.Read - read closed file: %w", io.ErrClosedPipe)
}
if file.ended {
return 0, io.EOF
}
if file.remaining == 0 {
return 0, file.confirmEnd()
}
if int64(len(buffer)) > file.remaining {
buffer = buffer[:file.remaining]
}
n, err := file.body.Read(buffer)
file.remaining -= int64(n)
if errors.Is(err, io.EOF) {
if file.remaining > 0 {
return n, fmt.Errorf("File.Read - stored body ended early: %w", io.ErrUnexpectedEOF)
}
file.ended = true
return n, nil
}
return n, err
}
func (file *File) confirmEnd() error {
var probe [1]byte
for range maxEmptyReads {
n, err := file.body.Read(probe[:])
switch {
case n > 0:
return fmt.Errorf("File.Read - stored body exceeds its size: %w", ErrSizeMismatch)
case errors.Is(err, io.EOF):
file.ended = true
return io.EOF
case err != nil:
return err
}
}
return fmt.Errorf("File.Read - read stored body: %w", io.ErrNoProgress)
}
// Close releases the storage response. Repeated calls return nil.
func (file *File) Close() error {
if file.closed {
return nil
}
file.closed = true
return file.body.Close()
}