github.com/ethersphere/bee/v2@v2.2.0/pkg/pusher/inflight.go (about)

     1  // Copyright 2021 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package pusher
     6  
     7  import (
     8  	"sync"
     9  
    10  	"github.com/ethersphere/bee/v2/pkg/swarm"
    11  )
    12  
    13  type inflight struct {
    14  	mtx      sync.Mutex
    15  	inflight map[string]struct{}
    16  }
    17  
    18  func newInflight() *inflight {
    19  	return &inflight{
    20  		inflight: make(map[string]struct{}),
    21  	}
    22  }
    23  
    24  func (i *inflight) delete(ch swarm.Chunk) {
    25  	key := ch.Address().ByteString() + string(ch.Stamp().BatchID())
    26  	i.mtx.Lock()
    27  	delete(i.inflight, key)
    28  	i.mtx.Unlock()
    29  }
    30  
    31  func (i *inflight) set(ch swarm.Chunk) bool {
    32  
    33  	i.mtx.Lock()
    34  	defer i.mtx.Unlock()
    35  
    36  	key := ch.Address().ByteString() + string(ch.Stamp().BatchID())
    37  	if _, ok := i.inflight[key]; ok {
    38  		return true
    39  	}
    40  
    41  	i.inflight[key] = struct{}{}
    42  	return false
    43  }
    44  
    45  type attempts struct {
    46  	mtx        sync.Mutex
    47  	retryCount int
    48  	attempts   map[string]int
    49  }
    50  
    51  // try to log a chunk sync attempt. returns false when
    52  // maximum amount of attempts have been reached.
    53  func (a *attempts) try(ch swarm.Address) bool {
    54  	a.mtx.Lock()
    55  	defer a.mtx.Unlock()
    56  	key := ch.ByteString()
    57  	a.attempts[key]++
    58  	return a.attempts[key] < a.retryCount
    59  }
    60  
    61  func (a *attempts) delete(ch swarm.Address) {
    62  	a.mtx.Lock()
    63  	delete(a.attempts, ch.ByteString())
    64  	a.mtx.Unlock()
    65  }