subscription_push.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. "sync"
  20. "time"
  21. "github.com/ethereum/go-ethereum/log"
  22. "github.com/ethereum/go-ethereum/metrics"
  23. "github.com/ethereum/go-ethereum/swarm/chunk"
  24. "github.com/ethereum/go-ethereum/swarm/shed"
  25. "github.com/ethereum/go-ethereum/swarm/spancontext"
  26. "github.com/opentracing/opentracing-go"
  27. olog "github.com/opentracing/opentracing-go/log"
  28. )
  29. // SubscribePush returns a channel that provides storage chunks with ordering from push syncing index.
  30. // Returned stop function will terminate current and further iterations, and also it will close
  31. // the returned channel without any errors. Make sure that you check the second returned parameter
  32. // from the channel to stop iteration when its value is false.
  33. func (db *DB) SubscribePush(ctx context.Context) (c <-chan chunk.Chunk, stop func()) {
  34. metricName := "localstore.SubscribePush"
  35. metrics.GetOrRegisterCounter(metricName, nil).Inc(1)
  36. chunks := make(chan chunk.Chunk)
  37. trigger := make(chan struct{}, 1)
  38. db.pushTriggersMu.Lock()
  39. db.pushTriggers = append(db.pushTriggers, trigger)
  40. db.pushTriggersMu.Unlock()
  41. // send signal for the initial iteration
  42. trigger <- struct{}{}
  43. stopChan := make(chan struct{})
  44. var stopChanOnce sync.Once
  45. go func() {
  46. defer metrics.GetOrRegisterCounter(metricName+".done", nil).Inc(1)
  47. // close the returned chunkInfo channel at the end to
  48. // signal that the subscription is done
  49. defer close(chunks)
  50. // sinceItem is the Item from which the next iteration
  51. // should start. The first iteration starts from the first Item.
  52. var sinceItem *shed.Item
  53. for {
  54. select {
  55. case <-trigger:
  56. // iterate until:
  57. // - last index Item is reached
  58. // - subscription stop is called
  59. // - context is done
  60. metrics.GetOrRegisterCounter(metricName+".iter", nil).Inc(1)
  61. ctx, sp := spancontext.StartSpan(ctx, metricName+".iter")
  62. iterStart := time.Now()
  63. var count int
  64. err := db.pushIndex.Iterate(func(item shed.Item) (stop bool, err error) {
  65. // get chunk data
  66. dataItem, err := db.retrievalDataIndex.Get(item)
  67. if err != nil {
  68. return true, err
  69. }
  70. select {
  71. case chunks <- chunk.NewChunk(dataItem.Address, dataItem.Data):
  72. count++
  73. // set next iteration start item
  74. // when its chunk is successfully sent to channel
  75. sinceItem = &item
  76. return false, nil
  77. case <-stopChan:
  78. // gracefully stop the iteration
  79. // on stop
  80. return true, nil
  81. case <-db.close:
  82. // gracefully stop the iteration
  83. // on database close
  84. return true, nil
  85. case <-ctx.Done():
  86. return true, ctx.Err()
  87. }
  88. }, &shed.IterateOptions{
  89. StartFrom: sinceItem,
  90. // sinceItem was sent as the last Address in the previous
  91. // iterator call, skip it in this one
  92. SkipStartFromItem: true,
  93. })
  94. totalTimeMetric(metricName+".iter", iterStart)
  95. sp.FinishWithOptions(opentracing.FinishOptions{
  96. LogRecords: []opentracing.LogRecord{
  97. {
  98. Timestamp: time.Now(),
  99. Fields: []olog.Field{olog.Int("count", count)},
  100. },
  101. },
  102. })
  103. if err != nil {
  104. metrics.GetOrRegisterCounter(metricName+".iter.error", nil).Inc(1)
  105. log.Error("localstore push subscription iteration", "err", err)
  106. return
  107. }
  108. case <-stopChan:
  109. // terminate the subscription
  110. // on stop
  111. return
  112. case <-db.close:
  113. // terminate the subscription
  114. // on database close
  115. return
  116. case <-ctx.Done():
  117. err := ctx.Err()
  118. if err != nil {
  119. log.Error("localstore push subscription", "err", err)
  120. }
  121. return
  122. }
  123. }
  124. }()
  125. stop = func() {
  126. stopChanOnce.Do(func() {
  127. close(stopChan)
  128. })
  129. db.pushTriggersMu.Lock()
  130. defer db.pushTriggersMu.Unlock()
  131. for i, t := range db.pushTriggers {
  132. if t == trigger {
  133. db.pushTriggers = append(db.pushTriggers[:i], db.pushTriggers[i+1:]...)
  134. break
  135. }
  136. }
  137. }
  138. return chunks, stop
  139. }
  140. // triggerPushSubscriptions is used internally for starting iterations
  141. // on Push subscriptions. Whenever new item is added to the push index,
  142. // this function should be called.
  143. func (db *DB) triggerPushSubscriptions() {
  144. db.pushTriggersMu.RLock()
  145. triggers := db.pushTriggers
  146. db.pushTriggersMu.RUnlock()
  147. for _, t := range triggers {
  148. select {
  149. case t <- struct{}{}:
  150. default:
  151. }
  152. }
  153. }