buffer.go 12 KB

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