github.com/ledgerwatch/erigon-lib@v1.0.0/common/background/progress.go (about) 1 /* 2 Copyright 2021 Erigon contributors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package background 18 19 import ( 20 "fmt" 21 "strings" 22 "sync" 23 "sync/atomic" 24 25 btree2 "github.com/tidwall/btree" 26 ) 27 28 // Progress - tracks background job progress 29 type Progress struct { 30 Name atomic.Pointer[string] 31 Processed, Total atomic.Uint64 32 i int 33 } 34 35 func (p *Progress) percent() int { 36 return int( 37 (float64(p.Processed.Load()) / float64(p.Total.Load())) * 100, 38 ) 39 } 40 41 // ProgressSet - tracks multiple background job progress 42 type ProgressSet struct { 43 list *btree2.Map[int, *Progress] 44 i int 45 lock sync.RWMutex 46 } 47 48 func NewProgressSet() *ProgressSet { 49 return &ProgressSet{list: btree2.NewMap[int, *Progress](128)} 50 } 51 func (s *ProgressSet) AddNew(fName string, total uint64) *Progress { 52 p := &Progress{} 53 p.Name.Store(&fName) 54 p.Total.Store(total) 55 s.Add(p) 56 return p 57 } 58 func (s *ProgressSet) Add(p *Progress) { 59 s.lock.Lock() 60 defer s.lock.Unlock() 61 s.i++ 62 p.i = s.i 63 s.list.Set(p.i, p) 64 } 65 66 func (s *ProgressSet) Delete(p *Progress) { 67 s.lock.Lock() 68 defer s.lock.Unlock() 69 s.list.Delete(p.i) 70 } 71 func (s *ProgressSet) Has() bool { 72 s.lock.Lock() 73 defer s.lock.Unlock() 74 return s.list.Len() > 0 75 } 76 77 func (s *ProgressSet) String() string { 78 s.lock.RLock() 79 defer s.lock.RUnlock() 80 var sb strings.Builder 81 var i int 82 s.list.Scan(func(_ int, p *Progress) bool { 83 if p == nil { 84 return true 85 } 86 namePtr := p.Name.Load() 87 if namePtr == nil { 88 return true 89 } 90 sb.WriteString(fmt.Sprintf("%s=%d%%", *namePtr, p.percent())) 91 i++ 92 if i != s.list.Len() { 93 sb.WriteString(", ") 94 } 95 return true 96 }) 97 return sb.String() 98 }