buffer.go 11 KB

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