github.com/0chain/gosdk@v1.17.11/zboxcore/sdk/repairCallback.go (about)

     1  package sdk
     2  
     3  import (
     4  	"sync"
     5  
     6  	l "github.com/0chain/gosdk/zboxcore/logger"
     7  )
     8  
     9  var (
    10  	mutMap  = make(map[string]*sync.Mutex)
    11  	mapLock sync.Mutex
    12  )
    13  
    14  func (s *StatusBar) Started(allocationId, filePath string, op int, totalBytes int) {
    15  	if s.sb != nil {
    16  		s.sb.Started(allocationId, filePath, op, totalBytes)
    17  	}
    18  
    19  }
    20  func (s *StatusBar) InProgress(allocationId, filePath string, op int, completedBytes int, data []byte) {
    21  	if s.sb != nil {
    22  		s.sb.InProgress(allocationId, filePath, op, completedBytes, data)
    23  	}
    24  }
    25  
    26  func (s *StatusBar) Completed(allocationId, filePath string, filename string, mimetype string, size int, op int) {
    27  	s.success = true
    28  	if s.isRepair {
    29  		l.Logger.Info("Repair for file completed. File = ", filePath)
    30  	} else {
    31  		l.Logger.Info("Operation completed. File = ", filePath)
    32  		s.wg.Done()
    33  	}
    34  }
    35  
    36  func (s *StatusBar) Error(allocationID string, filePath string, op int, err error) {
    37  	s.success = false
    38  	s.err = err
    39  	l.Logger.Error("Error in status callback. Error = ", err.Error())
    40  	if !s.isRepair {
    41  		s.wg.Done()
    42  	}
    43  }
    44  
    45  func (s *StatusBar) RepairCompleted(filesRepaired int) {
    46  	if s.err == nil {
    47  		s.success = true
    48  	}
    49  	defer s.wg.Done()
    50  	mutUnlock(s.allocID)
    51  	l.Logger.Info("Repair completed. Files repaired = ", filesRepaired)
    52  
    53  }
    54  
    55  type StatusBar struct {
    56  	wg       *sync.WaitGroup
    57  	allocID  string
    58  	success  bool
    59  	err      error
    60  	isRepair bool
    61  	sb       StatusCallback
    62  }
    63  
    64  func NewRepairBar(allocID string) *StatusBar {
    65  	mapLock.Lock()
    66  	defer mapLock.Unlock()
    67  	if _, ok := mutMap[allocID]; !ok {
    68  		mutMap[allocID] = &sync.Mutex{}
    69  	}
    70  	if !mutMap[allocID].TryLock() {
    71  		return nil
    72  	}
    73  	wg := &sync.WaitGroup{}
    74  	wg.Add(1)
    75  	return &StatusBar{
    76  		wg:       wg,
    77  		allocID:  allocID,
    78  		isRepair: true,
    79  	}
    80  }
    81  
    82  func (s *StatusBar) Wait() {
    83  	s.wg.Wait()
    84  }
    85  
    86  func (s *StatusBar) CheckError() error {
    87  	if !s.success {
    88  		return s.err
    89  	}
    90  	return nil
    91  }
    92  
    93  func mutUnlock(allocID string) {
    94  	mapLock.Lock()
    95  	mutMap[allocID].Unlock()
    96  	mapLock.Unlock()
    97  }