buffer.go 11 KB

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