buffer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Package asyncbuffer provides an asynchronous buffer that reads data from an
  2. // io.Reader in the background.
  3. //
  4. // When created, AsyncBuffer starts reading from the upstream reader in the
  5. // background. If a read error occurs, it is stored and can be checked with
  6. // AsyncBuffer.Error().
  7. //
  8. // When reading through AsyncBuffer.Reader().Read(), the error is only returned
  9. // once the reader reaches the point where the error occurred. In other words,
  10. // errors are delayed until encountered by the reader.
  11. //
  12. // However, AsyncBuffer.Close() and AsyncBuffer.Error() will immediately return
  13. // any stored error, even if the reader has not yet reached the error point.
  14. package asyncbuffer
  15. import (
  16. "context"
  17. "errors"
  18. "io"
  19. "sync"
  20. "sync/atomic"
  21. "github.com/sirupsen/logrus"
  22. )
  23. const (
  24. // chunkSize is the size of each chunk in bytes
  25. chunkSize = 4096
  26. // pauseThreshold is the size of the file which is always read to memory. Data beyond the
  27. // threshold is read only if accessed. If not a multiple of chunkSize, the last chunk it points
  28. // to is read in full.
  29. pauseThreshold = 32768 // 32 KiB
  30. )
  31. // byteChunk is a struct that holds a buffer and the data read from the upstream reader
  32. // data slice is required since the chunk read may be smaller than ChunkSize
  33. type byteChunk struct {
  34. buf []byte
  35. data []byte
  36. }
  37. // chunkPool is a global sync.Pool that holds byteChunk objects for
  38. // all readers
  39. var chunkPool = sync.Pool{
  40. New: func() any {
  41. buf := make([]byte, chunkSize)
  42. return &byteChunk{
  43. buf: buf,
  44. data: buf[:0],
  45. }
  46. },
  47. }
  48. // AsyncBuffer is a wrapper around io.Reader that reads data in chunks
  49. // in background and allows reading from synchronously.
  50. type AsyncBuffer struct {
  51. r io.ReadCloser // Upstream reader
  52. chunks []*byteChunk // References to the chunks read from the upstream reader
  53. mu sync.RWMutex // Mutex on chunks slice
  54. err atomic.Value // Error that occurred during reading
  55. len atomic.Int64 // Total length of the data read
  56. finished atomic.Bool // Indicates that the buffer has finished reading
  57. closed atomic.Bool // Indicates that the buffer was closed
  58. paused *Latch // Paused buffer does not read data beyond threshold
  59. chunkCond *Cond // Ticker that signals when a new chunk is ready
  60. finishOnce sync.Once
  61. finishFn []context.CancelFunc
  62. }
  63. // New creates a new AsyncBuffer that reads from the given io.ReadCloser in background
  64. // and closes it when finished.
  65. func New(r io.ReadCloser, finishFn ...context.CancelFunc) *AsyncBuffer {
  66. ab := &AsyncBuffer{
  67. r: r,
  68. paused: NewLatch(),
  69. chunkCond: NewCond(),
  70. finishFn: finishFn,
  71. }
  72. go ab.readChunks()
  73. return ab
  74. }
  75. // addChunk adds a new chunk to the AsyncBuffer, increments len and signals that a chunk is ready
  76. func (ab *AsyncBuffer) addChunk(chunk *byteChunk) {
  77. ab.mu.Lock()
  78. defer ab.mu.Unlock()
  79. if ab.closed.Load() {
  80. // If the reader is closed, we return the chunk to the pool
  81. chunkPool.Put(chunk)
  82. return
  83. }
  84. // Store the chunk, increase chunk size, increase length of the data read
  85. ab.chunks = append(ab.chunks, chunk)
  86. ab.len.Add(int64(len(chunk.data)))
  87. ab.chunkCond.Tick()
  88. }
  89. // readChunks reads data from the upstream reader in background and stores them in the pool
  90. func (ab *AsyncBuffer) readChunks() {
  91. defer func() {
  92. // Indicate that the reader has finished reading
  93. ab.finished.Store(true)
  94. ab.chunkCond.Close()
  95. // Close the upstream reader
  96. if err := ab.r.Close(); err != nil {
  97. logrus.WithField("source", "asyncbuffer.AsyncBuffer.readChunks").Warningf("error closing upstream reader: %s", err)
  98. }
  99. ab.finishOnce.Do(func() {
  100. for _, fn := range ab.finishFn {
  101. fn()
  102. }
  103. })
  104. }()
  105. // Stop reading if the reader is closed
  106. for !ab.closed.Load() {
  107. // In case we are trying to read data beyond threshold and we are paused,
  108. // wait for pause to be released.
  109. if ab.len.Load() >= pauseThreshold {
  110. ab.paused.Wait()
  111. // If the reader has been closed while waiting, we can stop reading
  112. if ab.closed.Load() {
  113. return // No more data to read
  114. }
  115. }
  116. // Get a chunk from the pool
  117. // If the pool is empty, it will create a new byteChunk with ChunkSize
  118. chunk, ok := chunkPool.Get().(*byteChunk)
  119. if !ok {
  120. ab.err.Store(errors.New("asyncbuffer.AsyncBuffer.readChunks: failed to get chunk from pool"))
  121. return
  122. }
  123. // Read data into the chunk's buffer
  124. // There is no way to guarantee that ReadFull will abort on context cancellation,
  125. // unfortunately, this is how golang works.
  126. n, err := io.ReadFull(ab.r, chunk.buf)
  127. // If it's not the EOF, we need to store the error
  128. if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
  129. ab.err.Store(err)
  130. chunkPool.Put(chunk)
  131. return
  132. }
  133. // No bytes were read (n == 0), we can return the chunk to the pool
  134. if err == io.EOF || n == 0 {
  135. chunkPool.Put(chunk)
  136. return
  137. }
  138. // Resize the chunk's data slice to the number of bytes read
  139. chunk.data = chunk.buf[:n]
  140. // Store the reference to the chunk in the AsyncBuffer
  141. ab.addChunk(chunk)
  142. // We got ErrUnexpectedEOF meaning that some bytes were read, but this is the
  143. // end of the stream, so we can stop reading
  144. if err == io.ErrUnexpectedEOF {
  145. return
  146. }
  147. }
  148. }
  149. // closedError returns an error if the attempt to read on a closed reader was made.
  150. // If the reader had an error, it returns that error instead.
  151. func (ab *AsyncBuffer) closedError() error {
  152. // If the reader is closed, we return the error or nil
  153. if !ab.closed.Load() {
  154. return nil
  155. }
  156. err := ab.Error()
  157. if err == nil {
  158. err = errors.New("asyncbuffer.AsyncBuffer.ReadAt: attempt to read on closed reader")
  159. }
  160. return err
  161. }
  162. // offsetAvailable checks if the data at the given offset is available for reading.
  163. // It may return io.EOF if the reader is finished reading and the offset is beyond the end of the stream.
  164. func (ab *AsyncBuffer) offsetAvailable(off int64) (bool, error) {
  165. // We can not read data from the closed reader, none
  166. if err := ab.closedError(); err != nil {
  167. return false, err
  168. }
  169. // In case the offset falls within the already read chunks, we can return immediately,
  170. // even if error has occurred in the future
  171. if off < ab.len.Load() {
  172. return true, nil
  173. }
  174. // In case the reader is finished reading, and we have not read enough
  175. // data yet, return either error or EOF
  176. if ab.finished.Load() {
  177. // In case, error has occurred, we need to return it
  178. if err := ab.Error(); err != nil {
  179. return false, err
  180. }
  181. // Otherwise, it's EOF if the offset is beyond the end of the stream
  182. return false, io.EOF
  183. }
  184. // No available data
  185. return false, nil
  186. }
  187. // WaitFor waits for the data to be ready at the given offset. nil means ok.
  188. // It guarantees that the chunk at the given offset is ready to be read.
  189. func (ab *AsyncBuffer) WaitFor(off int64) error {
  190. // In case we are trying to read data which would potentially hit the pause threshold,
  191. // we need to unpause the reader ASAP.
  192. if off >= pauseThreshold {
  193. ab.paused.Release()
  194. }
  195. for {
  196. ok, err := ab.offsetAvailable(off)
  197. if ok || err != nil {
  198. return err
  199. }
  200. ab.chunkCond.Wait()
  201. }
  202. }
  203. // Wait waits for the reader to finish reading all data and returns
  204. // the total length of the data read.
  205. func (ab *AsyncBuffer) Wait() (int, error) {
  206. // Wait ends till the end of the stream: unpause the reader
  207. ab.paused.Release()
  208. for {
  209. // We can not read data from the closed reader
  210. if err := ab.closedError(); err != nil {
  211. return 0, err
  212. }
  213. // In case the reader is finished reading, we can return immediately
  214. if ab.finished.Load() {
  215. return int(ab.len.Load()), ab.Error()
  216. }
  217. // Lock until the next chunk is ready
  218. ab.chunkCond.Wait()
  219. }
  220. }
  221. // Error returns the error that occurred during reading data in background.
  222. func (ab *AsyncBuffer) Error() error {
  223. err := ab.err.Load()
  224. if err == nil {
  225. return nil
  226. }
  227. errCast, ok := err.(error)
  228. if !ok {
  229. return errors.New("asyncbuffer.AsyncBuffer.Error: failed to get error")
  230. }
  231. return errCast
  232. }
  233. // readChunkAt copies data from the chunk at the given absolute offset to the provided slice.
  234. // Chunk must be available when this method is called.
  235. // Returns the number of bytes copied to the slice or 0 if chunk has no data
  236. // (eg. offset is beyond the end of the stream).
  237. func (ab *AsyncBuffer) readChunkAt(p []byte, off int64) int {
  238. // If the chunk is not available, we return 0
  239. if off >= ab.len.Load() {
  240. return 0
  241. }
  242. ind := off / chunkSize // chunk index
  243. chunk := ab.chunks[ind]
  244. startOffset := off % chunkSize // starting offset in the chunk
  245. // If the offset in current chunk is greater than the data
  246. // it has, we return 0
  247. if startOffset >= int64(len(chunk.data)) {
  248. return 0
  249. }
  250. // Copy data to the target slice. The number of bytes to copy is limited by the
  251. // size of the target slice and the size of the data in the chunk.
  252. return copy(p, chunk.data[startOffset:])
  253. }
  254. // readAt reads data from the AsyncBuffer at the given offset.
  255. //
  256. // Please note that if pause threshold is hit in the middle of the reading,
  257. // the data beyond the threshold may not be available.
  258. //
  259. // If the reader is paused and we try to read data beyond the pause threshold,
  260. // it will wait till something could be returned.
  261. func (ab *AsyncBuffer) readAt(p []byte, off int64) (int, error) {
  262. size := int64(len(p)) // total size of the data to read
  263. if off < 0 {
  264. return 0, errors.New("asyncbuffer.AsyncBuffer.readAt: negative offset")
  265. }
  266. // If we plan to hit threshold while reading, release the paused reader
  267. if int64(len(p))+off > pauseThreshold {
  268. ab.paused.Release()
  269. }
  270. // Wait for the offset to be available.
  271. // It may return io.EOF if the offset is beyond the end of the stream.
  272. err := ab.WaitFor(off)
  273. if err != nil {
  274. return 0, err
  275. }
  276. // We lock the mutex until current buffer is read
  277. ab.mu.RLock()
  278. defer ab.mu.RUnlock()
  279. // If the reader is closed, we return an error
  280. if err := ab.closedError(); err != nil {
  281. return 0, err
  282. }
  283. // Read data from the first chunk
  284. n := ab.readChunkAt(p, off)
  285. if n == 0 {
  286. return 0, io.EOF // Failed to read any data: means we tried to read beyond the end of the stream
  287. }
  288. size -= int64(n)
  289. off += int64(n) // Here and beyond off always points to the last read byte + 1
  290. // Now, let's try to read the rest of the data from next chunks while they are available
  291. for size > 0 {
  292. // If data is not available at the given offset, we can return data read so far.
  293. ok, err := ab.offsetAvailable(off)
  294. if !ok {
  295. if err == io.EOF {
  296. return n, nil
  297. }
  298. return n, err
  299. }
  300. // Read data from the next chunk
  301. nX := ab.readChunkAt(p[n:], off)
  302. n += nX
  303. size -= int64(nX)
  304. off += int64(nX)
  305. // If we read data shorter than ChunkSize or, in case that was the last chunk, less than
  306. // the size of the tail, return kind of EOF
  307. if int64(nX) < min(size, int64(chunkSize)) {
  308. return n, nil
  309. }
  310. }
  311. return n, nil
  312. }
  313. // Close closes the AsyncBuffer and releases all resources.
  314. // It returns an error if the reader was already closed or if there was
  315. // an error during reading data in background even if none of the subsequent
  316. // readers have reached the position where the error occurred.
  317. func (ab *AsyncBuffer) Close() error {
  318. ab.mu.Lock()
  319. defer ab.mu.Unlock()
  320. // If the reader is already closed, we return immediately error or nil
  321. if ab.closed.Load() {
  322. return ab.Error()
  323. }
  324. ab.closed.Store(true)
  325. // Return all chunks to the pool
  326. for _, chunk := range ab.chunks {
  327. chunkPool.Put(chunk)
  328. }
  329. // Release the paused latch so that no goroutines are waiting for it
  330. ab.paused.Release()
  331. // Finish downloading
  332. ab.finishOnce.Do(func() {
  333. for _, fn := range ab.finishFn {
  334. fn()
  335. }
  336. })
  337. return nil
  338. }
  339. // Reader returns an io.ReadSeeker+io.ReaderAt that can be used to read actual data from the AsyncBuffer
  340. func (ab *AsyncBuffer) Reader() *Reader {
  341. return &Reader{ab: ab, pos: 0}
  342. }