2016-06-27 20:52:48 +00:00
|
|
|
package kcp
|
|
|
|
|
|
|
|
import (
|
2016-06-29 08:34:34 +00:00
|
|
|
"io"
|
2016-06-27 20:52:48 +00:00
|
|
|
"sync"
|
|
|
|
|
2017-09-19 21:27:49 +00:00
|
|
|
"v2ray.com/core/common/retry"
|
|
|
|
|
|
|
|
"v2ray.com/core/common"
|
2016-12-09 10:35:27 +00:00
|
|
|
"v2ray.com/core/common/buf"
|
2016-06-27 20:52:48 +00:00
|
|
|
)
|
|
|
|
|
2016-07-02 19:26:50 +00:00
|
|
|
type SegmentWriter interface {
|
2016-12-20 21:53:58 +00:00
|
|
|
Write(seg Segment) error
|
2016-07-02 19:26:50 +00:00
|
|
|
}
|
|
|
|
|
2016-12-20 21:53:58 +00:00
|
|
|
type SimpleSegmentWriter struct {
|
2016-06-27 20:52:48 +00:00
|
|
|
sync.Mutex
|
2016-12-09 10:35:27 +00:00
|
|
|
buffer *buf.Buffer
|
2016-12-08 15:27:41 +00:00
|
|
|
writer io.Writer
|
2016-06-27 20:52:48 +00:00
|
|
|
}
|
|
|
|
|
2016-12-20 21:53:58 +00:00
|
|
|
func NewSegmentWriter(writer io.Writer) SegmentWriter {
|
|
|
|
return &SimpleSegmentWriter{
|
2016-06-27 20:52:48 +00:00
|
|
|
writer: writer,
|
2017-04-15 19:19:21 +00:00
|
|
|
buffer: buf.New(),
|
2016-06-27 20:52:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-19 21:27:49 +00:00
|
|
|
func (w *SimpleSegmentWriter) Write(seg Segment) error {
|
|
|
|
w.Lock()
|
|
|
|
defer w.Unlock()
|
2016-06-27 20:52:48 +00:00
|
|
|
|
2017-09-19 21:27:49 +00:00
|
|
|
common.Must(w.buffer.Reset(seg.Bytes()))
|
|
|
|
_, err := w.writer.Write(w.buffer.Bytes())
|
2016-12-20 21:53:58 +00:00
|
|
|
return err
|
2016-06-27 20:52:48 +00:00
|
|
|
}
|
2017-09-19 21:27:49 +00:00
|
|
|
|
|
|
|
type RetryableWriter struct {
|
|
|
|
writer SegmentWriter
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewRetryableWriter(writer SegmentWriter) SegmentWriter {
|
|
|
|
return &RetryableWriter{
|
|
|
|
writer: writer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *RetryableWriter) Write(seg Segment) error {
|
|
|
|
return retry.Timed(5, 100).On(func() error {
|
|
|
|
return w.writer.Write(seg)
|
|
|
|
})
|
|
|
|
}
|