resultstore.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package downloader
  17. import (
  18. "fmt"
  19. "sync"
  20. "sync/atomic"
  21. "github.com/ethereum/go-ethereum/core/types"
  22. )
  23. // resultStore implements a structure for maintaining fetchResults, tracking their
  24. // download-progress and delivering (finished) results.
  25. type resultStore struct {
  26. items []*fetchResult // Downloaded but not yet delivered fetch results
  27. resultOffset uint64 // Offset of the first cached fetch result in the block chain
  28. // Internal index of first non-completed entry, updated atomically when needed.
  29. // If all items are complete, this will equal length(items), so
  30. // *important* : is not safe to use for indexing without checking against length
  31. indexIncomplete int32 // atomic access
  32. // throttleThreshold is the limit up to which we _want_ to fill the
  33. // results. If blocks are large, we want to limit the results to less
  34. // than the number of available slots, and maybe only fill 1024 out of
  35. // 8192 possible places. The queue will, at certain times, recalibrate
  36. // this index.
  37. throttleThreshold uint64
  38. lock sync.RWMutex
  39. }
  40. func newResultStore(size int) *resultStore {
  41. return &resultStore{
  42. resultOffset: 0,
  43. items: make([]*fetchResult, size),
  44. throttleThreshold: uint64(size),
  45. }
  46. }
  47. // SetThrottleThreshold updates the throttling threshold based on the requested
  48. // limit and the total queue capacity. It returns the (possibly capped) threshold
  49. func (r *resultStore) SetThrottleThreshold(threshold uint64) uint64 {
  50. r.lock.Lock()
  51. defer r.lock.Unlock()
  52. limit := uint64(len(r.items))
  53. if threshold >= limit {
  54. threshold = limit
  55. }
  56. r.throttleThreshold = threshold
  57. return r.throttleThreshold
  58. }
  59. // AddFetch adds a header for body/receipt fetching. This is used when the queue
  60. // wants to reserve headers for fetching.
  61. //
  62. // It returns the following:
  63. // stale - if true, this item is already passed, and should not be requested again
  64. // throttled - if true, the store is at capacity, this particular header is not prio now
  65. // item - the result to store data into
  66. // err - any error that occurred
  67. func (r *resultStore) AddFetch(header *types.Header, fastSync bool) (stale, throttled bool, item *fetchResult, err error) {
  68. r.lock.Lock()
  69. defer r.lock.Unlock()
  70. var index int
  71. item, index, stale, throttled, err = r.getFetchResult(header.Number.Uint64())
  72. if err != nil || stale || throttled {
  73. return stale, throttled, item, err
  74. }
  75. if item == nil {
  76. item = newFetchResult(header, fastSync)
  77. r.items[index] = item
  78. }
  79. return stale, throttled, item, err
  80. }
  81. // GetDeliverySlot returns the fetchResult for the given header. If the 'stale' flag
  82. // is true, that means the header has already been delivered 'upstream'. This method
  83. // does not bubble up the 'throttle' flag, since it's moot at the point in time when
  84. // the item is downloaded and ready for delivery
  85. func (r *resultStore) GetDeliverySlot(headerNumber uint64) (*fetchResult, bool, error) {
  86. r.lock.RLock()
  87. defer r.lock.RUnlock()
  88. res, _, stale, _, err := r.getFetchResult(headerNumber)
  89. return res, stale, err
  90. }
  91. // getFetchResult returns the fetchResult corresponding to the given item, and
  92. // the index where the result is stored.
  93. func (r *resultStore) getFetchResult(headerNumber uint64) (item *fetchResult, index int, stale, throttle bool, err error) {
  94. index = int(int64(headerNumber) - int64(r.resultOffset))
  95. throttle = index >= int(r.throttleThreshold)
  96. stale = index < 0
  97. if index >= len(r.items) {
  98. err = fmt.Errorf("%w: index allocation went beyond available resultStore space "+
  99. "(index [%d] = header [%d] - resultOffset [%d], len(resultStore) = %d", errInvalidChain,
  100. index, headerNumber, r.resultOffset, len(r.items))
  101. return nil, index, stale, throttle, err
  102. }
  103. if stale {
  104. return nil, index, stale, throttle, nil
  105. }
  106. item = r.items[index]
  107. return item, index, stale, throttle, nil
  108. }
  109. // hasCompletedItems returns true if there are processable items available
  110. // this method is cheaper than countCompleted
  111. func (r *resultStore) HasCompletedItems() bool {
  112. r.lock.RLock()
  113. defer r.lock.RUnlock()
  114. if len(r.items) == 0 {
  115. return false
  116. }
  117. if item := r.items[0]; item != nil && item.AllDone() {
  118. return true
  119. }
  120. return false
  121. }
  122. // countCompleted returns the number of items ready for delivery, stopping at
  123. // the first non-complete item.
  124. //
  125. // The mthod assumes (at least) rlock is held.
  126. func (r *resultStore) countCompleted() int {
  127. // We iterate from the already known complete point, and see
  128. // if any more has completed since last count
  129. index := atomic.LoadInt32(&r.indexIncomplete)
  130. for ; ; index++ {
  131. if index >= int32(len(r.items)) {
  132. break
  133. }
  134. result := r.items[index]
  135. if result == nil || !result.AllDone() {
  136. break
  137. }
  138. }
  139. atomic.StoreInt32(&r.indexIncomplete, index)
  140. return int(index)
  141. }
  142. // GetCompleted returns the next batch of completed fetchResults
  143. func (r *resultStore) GetCompleted(limit int) []*fetchResult {
  144. r.lock.Lock()
  145. defer r.lock.Unlock()
  146. completed := r.countCompleted()
  147. if limit > completed {
  148. limit = completed
  149. }
  150. results := make([]*fetchResult, limit)
  151. copy(results, r.items[:limit])
  152. // Delete the results from the cache and clear the tail.
  153. copy(r.items, r.items[limit:])
  154. for i := len(r.items) - limit; i < len(r.items); i++ {
  155. r.items[i] = nil
  156. }
  157. // Advance the expected block number of the first cache entry
  158. r.resultOffset += uint64(limit)
  159. atomic.AddInt32(&r.indexIncomplete, int32(-limit))
  160. return results
  161. }
  162. // Prepare initialises the offset with the given block number
  163. func (r *resultStore) Prepare(offset uint64) {
  164. r.lock.Lock()
  165. defer r.lock.Unlock()
  166. if r.resultOffset < offset {
  167. r.resultOffset = offset
  168. }
  169. }