buffer.go 12 KB

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