tstor/pkg/ioutils/disk.go

73 lines
1.4 KiB
Go
Raw Permalink Normal View History

2024-06-02 19:53:33 +00:00
package ioutils
2024-04-17 08:36:14 +00:00
import (
"context"
"io"
"os"
"sync"
2024-06-02 19:53:33 +00:00
"github.com/royalcat/ctxio"
2024-04-17 08:36:14 +00:00
)
type DiskCacheReader struct {
m sync.Mutex
fo int64
fr *os.File
to int64
2024-06-02 19:53:33 +00:00
tr ctxio.Reader
2024-04-17 08:36:14 +00:00
}
2024-06-02 19:53:33 +00:00
var _ ctxio.ReaderAt = (*DiskCacheReader)(nil)
var _ ctxio.Reader = (*DiskCacheReader)(nil)
var _ ctxio.Closer = (*DiskCacheReader)(nil)
2024-04-17 08:36:14 +00:00
2024-06-02 19:53:33 +00:00
func NewDiskCacheReader(r ctxio.Reader) (*DiskCacheReader, error) {
2024-04-17 08:36:14 +00:00
tempDir, err := os.MkdirTemp("/tmp", "tstor")
if err != nil {
return nil, err
}
fr, err := os.CreateTemp(tempDir, "dtb_tmp")
if err != nil {
return nil, err
}
2024-06-02 19:53:33 +00:00
tr := ctxio.TeeReader(r, ctxio.WrapIoWriter(fr))
2024-04-17 08:36:14 +00:00
return &DiskCacheReader{fr: fr, tr: tr}, nil
}
func (dtr *DiskCacheReader) ReadAt(ctx context.Context, p []byte, off int64) (int, error) {
dtr.m.Lock()
defer dtr.m.Unlock()
tb := off + int64(len(p))
if tb > dtr.fo {
2024-06-02 19:53:33 +00:00
w, err := ctxio.CopyN(ctx, ctxio.Discard, dtr.tr, tb-dtr.fo)
2024-04-17 08:36:14 +00:00
dtr.to += w
if err != nil && err != io.EOF {
return 0, err
}
}
n, err := dtr.fr.ReadAt(p, off)
dtr.fo += int64(n)
return n, err
}
func (dtr *DiskCacheReader) Read(ctx context.Context, p []byte) (n int, err error) {
dtr.m.Lock()
defer dtr.m.Unlock()
// use directly tee reader here
n, err = dtr.tr.Read(ctx, p)
dtr.to += int64(n)
return
}
func (dtr *DiskCacheReader) Close(ctx context.Context) error {
if err := dtr.fr.Close(); err != nil {
return err
}
return os.Remove(dtr.fr.Name())
}