github.com/kchristidis/fabric@v1.0.4-0.20171028114726-837acd08cde1/gossip/state/payloads_buffer.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     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 state
    18  
    19  import (
    20  	"fmt"
    21  	"strconv"
    22  	"sync"
    23  	"sync/atomic"
    24  
    25  	"github.com/hyperledger/fabric/gossip/util"
    26  	proto "github.com/hyperledger/fabric/protos/gossip"
    27  	"github.com/op/go-logging"
    28  )
    29  
    30  // PayloadsBuffer is used to store payloads into which used to
    31  // support payloads with blocks reordering according to the
    32  // sequence numbers. It also will provide the capability
    33  // to signal whenever expected block has arrived.
    34  type PayloadsBuffer interface {
    35  	// Adds new block into the buffer
    36  	Push(payload *proto.Payload) error
    37  
    38  	// Returns next expected sequence number
    39  	Next() uint64
    40  
    41  	// Remove and return payload with given sequence number
    42  	Pop() *proto.Payload
    43  
    44  	// Get current buffer size
    45  	Size() int
    46  
    47  	// Channel to indicate event when new payload pushed with sequence
    48  	// number equal to the next expected value.
    49  	Ready() chan struct{}
    50  
    51  	Close()
    52  }
    53  
    54  // PayloadsBufferImpl structure to implement PayloadsBuffer interface
    55  // store inner state of available payloads and sequence numbers
    56  type PayloadsBufferImpl struct {
    57  	next uint64
    58  
    59  	buf map[uint64]*proto.Payload
    60  
    61  	readyChan chan struct{}
    62  
    63  	mutex sync.RWMutex
    64  
    65  	logger *logging.Logger
    66  }
    67  
    68  // NewPayloadsBuffer is factory function to create new payloads buffer
    69  func NewPayloadsBuffer(next uint64) PayloadsBuffer {
    70  	return &PayloadsBufferImpl{
    71  		buf:       make(map[uint64]*proto.Payload),
    72  		readyChan: make(chan struct{}, 0),
    73  		next:      next,
    74  		logger:    util.GetLogger(util.LoggingStateModule, ""),
    75  	}
    76  }
    77  
    78  // Ready function returns the channel which indicates whenever expected
    79  // next block has arrived and one could safely pop out
    80  // next sequence of blocks
    81  func (b *PayloadsBufferImpl) Ready() chan struct{} {
    82  	return b.readyChan
    83  }
    84  
    85  // Push new payload into the buffer structure in case new arrived payload
    86  // sequence number is below the expected next block number payload will be
    87  // thrown away and error will be returned.
    88  func (b *PayloadsBufferImpl) Push(payload *proto.Payload) error {
    89  	b.mutex.Lock()
    90  	defer b.mutex.Unlock()
    91  
    92  	seqNum := payload.SeqNum
    93  
    94  	if seqNum < b.next || b.buf[seqNum] != nil {
    95  		return fmt.Errorf("Payload with sequence number = %s has been already processed",
    96  			strconv.FormatUint(payload.SeqNum, 10))
    97  	}
    98  
    99  	b.buf[seqNum] = payload
   100  
   101  	// Send notification that next sequence has arrived
   102  	if seqNum == b.next {
   103  		// Do not block execution of current routine
   104  		go func() {
   105  			b.readyChan <- struct{}{}
   106  		}()
   107  	}
   108  	return nil
   109  }
   110  
   111  // Next function provides the number of the next expected block
   112  func (b *PayloadsBufferImpl) Next() uint64 {
   113  	// Atomically read the value of the top sequence number
   114  	return atomic.LoadUint64(&b.next)
   115  }
   116  
   117  // Pop function extracts the payload according to the next expected block
   118  // number, if no next block arrived yet, function returns nil.
   119  func (b *PayloadsBufferImpl) Pop() *proto.Payload {
   120  	b.mutex.Lock()
   121  	defer b.mutex.Unlock()
   122  
   123  	result := b.buf[b.Next()]
   124  
   125  	if result != nil {
   126  		// If there is such sequence in the buffer need to delete it
   127  		delete(b.buf, b.Next())
   128  		// Increment next expect block index
   129  		atomic.AddUint64(&b.next, 1)
   130  	}
   131  	return result
   132  }
   133  
   134  // Size returns current number of payloads stored within buffer
   135  func (b *PayloadsBufferImpl) Size() int {
   136  	b.mutex.RLock()
   137  	defer b.mutex.RUnlock()
   138  	return len(b.buf)
   139  }
   140  
   141  // Close cleanups resources and channels in maintained
   142  func (b *PayloadsBufferImpl) Close() {
   143  	close(b.readyChan)
   144  }