subscription_pull.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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 localstore
  17. import (
  18. "context"
  19. "errors"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/log"
  23. "github.com/ethereum/go-ethereum/metrics"
  24. "github.com/ethereum/go-ethereum/swarm/chunk"
  25. "github.com/ethereum/go-ethereum/swarm/shed"
  26. "github.com/syndtr/goleveldb/leveldb"
  27. )
  28. // SubscribePull returns a channel that provides chunk addresses and stored times from pull syncing index.
  29. // Pull syncing index can be only subscribed to a particular proximity order bin. If since
  30. // is not 0, the iteration will start from the since item (the item with binID == since). If until is not 0,
  31. // only chunks stored up to this id will be sent to the channel, and the returned channel will be
  32. // closed. The since-until interval is closed on since side, and closed on until side: [since,until]. Returned stop
  33. // function will terminate current and further iterations without errors, and also close the returned channel.
  34. // Make sure that you check the second returned parameter from the channel to stop iteration when its value
  35. // is false.
  36. func (db *DB) SubscribePull(ctx context.Context, bin uint8, since, until uint64) (c <-chan chunk.Descriptor, stop func()) {
  37. metricName := "localstore.SubscribePull"
  38. metrics.GetOrRegisterCounter(metricName, nil).Inc(1)
  39. chunkDescriptors := make(chan chunk.Descriptor)
  40. trigger := make(chan struct{}, 1)
  41. db.pullTriggersMu.Lock()
  42. if _, ok := db.pullTriggers[bin]; !ok {
  43. db.pullTriggers[bin] = make([]chan struct{}, 0)
  44. }
  45. db.pullTriggers[bin] = append(db.pullTriggers[bin], trigger)
  46. db.pullTriggersMu.Unlock()
  47. // send signal for the initial iteration
  48. trigger <- struct{}{}
  49. stopChan := make(chan struct{})
  50. var stopChanOnce sync.Once
  51. // used to provide information from the iterator to
  52. // stop subscription when until chunk descriptor is reached
  53. var errStopSubscription = errors.New("stop subscription")
  54. go func() {
  55. defer metrics.GetOrRegisterCounter(metricName+".stop", nil).Inc(1)
  56. // close the returned chunk.Descriptor channel at the end to
  57. // signal that the subscription is done
  58. defer close(chunkDescriptors)
  59. // sinceItem is the Item from which the next iteration
  60. // should start. The first iteration starts from the first Item.
  61. var sinceItem *shed.Item
  62. if since > 0 {
  63. sinceItem = &shed.Item{
  64. Address: db.addressInBin(bin),
  65. BinID: since,
  66. }
  67. }
  68. first := true // first iteration flag for SkipStartFromItem
  69. for {
  70. select {
  71. case <-trigger:
  72. // iterate until:
  73. // - last index Item is reached
  74. // - subscription stop is called
  75. // - context is done
  76. metrics.GetOrRegisterCounter(metricName+".iter", nil).Inc(1)
  77. iterStart := time.Now()
  78. var count int
  79. err := db.pullIndex.Iterate(func(item shed.Item) (stop bool, err error) {
  80. select {
  81. case chunkDescriptors <- chunk.Descriptor{
  82. Address: item.Address,
  83. BinID: item.BinID,
  84. }:
  85. count++
  86. // until chunk descriptor is sent
  87. // break the iteration
  88. if until > 0 && item.BinID >= until {
  89. return true, errStopSubscription
  90. }
  91. // set next iteration start item
  92. // when its chunk is successfully sent to channel
  93. sinceItem = &item
  94. return false, nil
  95. case <-stopChan:
  96. // gracefully stop the iteration
  97. // on stop
  98. return true, nil
  99. case <-db.close:
  100. // gracefully stop the iteration
  101. // on database close
  102. return true, nil
  103. case <-ctx.Done():
  104. return true, ctx.Err()
  105. }
  106. }, &shed.IterateOptions{
  107. StartFrom: sinceItem,
  108. // sinceItem was sent as the last Address in the previous
  109. // iterator call, skip it in this one, but not the item with
  110. // the provided since bin id as it should be sent to a channel
  111. SkipStartFromItem: !first,
  112. Prefix: []byte{bin},
  113. })
  114. totalTimeMetric(metricName+".iter", iterStart)
  115. if err != nil {
  116. if err == errStopSubscription {
  117. // stop subscription without any errors
  118. // if until is reached
  119. return
  120. }
  121. metrics.GetOrRegisterCounter(metricName+".iter.error", nil).Inc(1)
  122. log.Error("localstore pull subscription iteration", "bin", bin, "since", since, "until", until, "err", err)
  123. return
  124. }
  125. if count > 0 {
  126. first = false
  127. }
  128. case <-stopChan:
  129. // terminate the subscription
  130. // on stop
  131. return
  132. case <-db.close:
  133. // terminate the subscription
  134. // on database close
  135. return
  136. case <-ctx.Done():
  137. err := ctx.Err()
  138. if err != nil {
  139. log.Error("localstore pull subscription", "bin", bin, "since", since, "until", until, "err", err)
  140. }
  141. return
  142. }
  143. }
  144. }()
  145. stop = func() {
  146. stopChanOnce.Do(func() {
  147. close(stopChan)
  148. })
  149. db.pullTriggersMu.Lock()
  150. defer db.pullTriggersMu.Unlock()
  151. for i, t := range db.pullTriggers[bin] {
  152. if t == trigger {
  153. db.pullTriggers[bin] = append(db.pullTriggers[bin][:i], db.pullTriggers[bin][i+1:]...)
  154. break
  155. }
  156. }
  157. }
  158. return chunkDescriptors, stop
  159. }
  160. // LastPullSubscriptionBinID returns chunk bin id of the latest Chunk
  161. // in pull syncing index for a provided bin. If there are no chunks in
  162. // that bin, 0 value is returned.
  163. func (db *DB) LastPullSubscriptionBinID(bin uint8) (id uint64, err error) {
  164. metrics.GetOrRegisterCounter("localstore.LastPullSubscriptionBinID", nil).Inc(1)
  165. item, err := db.pullIndex.Last([]byte{bin})
  166. if err != nil {
  167. if err == leveldb.ErrNotFound {
  168. return 0, nil
  169. }
  170. return 0, err
  171. }
  172. return item.BinID, nil
  173. }
  174. // triggerPullSubscriptions is used internally for starting iterations
  175. // on Pull subscriptions for a particular bin. When new item with address
  176. // that is in particular bin for DB's baseKey is added to pull index
  177. // this function should be called.
  178. func (db *DB) triggerPullSubscriptions(bin uint8) {
  179. db.pullTriggersMu.RLock()
  180. triggers, ok := db.pullTriggers[bin]
  181. db.pullTriggersMu.RUnlock()
  182. if !ok {
  183. return
  184. }
  185. for _, t := range triggers {
  186. select {
  187. case t <- struct{}{}:
  188. default:
  189. }
  190. }
  191. }
  192. // addressInBin returns an address that is in a specific
  193. // proximity order bin from database base key.
  194. func (db *DB) addressInBin(bin uint8) (addr chunk.Address) {
  195. addr = append([]byte(nil), db.baseKey...)
  196. b := bin / 8
  197. addr[b] = addr[b] ^ (1 << (7 - bin%8))
  198. return addr
  199. }