github.com/braveheart12/insolar-09-08-19@v0.8.7/ledger/storage/pulsestorage.go (about)

     1  /*
     2   *    Copyright 2019 Insolar Technologies
     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 storage
    18  
    19  import (
    20  	"context"
    21  	"sync"
    22  
    23  	"github.com/insolar/insolar/core"
    24  )
    25  
    26  // PulseStorage implements core.PulseStorage
    27  type PulseStorage struct {
    28  	PulseTracker PulseTracker `inject:""`
    29  	rwLock       sync.RWMutex
    30  	currentPulse *core.Pulse
    31  }
    32  
    33  // NewPulseStorage creates new pulse storage
    34  func NewPulseStorage() *PulseStorage {
    35  	return &PulseStorage{}
    36  }
    37  
    38  // Current returns current pulse of the system
    39  func (ps *PulseStorage) Current(ctx context.Context) (*core.Pulse, error) {
    40  	ps.rwLock.RLock()
    41  
    42  	if ps.currentPulse == nil {
    43  		ps.rwLock.RUnlock()
    44  
    45  		ps.rwLock.Lock()
    46  		defer ps.rwLock.Unlock()
    47  
    48  		if ps.currentPulse == nil {
    49  			currentPulse, err := ps.PulseTracker.GetLatestPulse(ctx)
    50  			if err != nil {
    51  				return nil, err
    52  			}
    53  			ps.currentPulse = &currentPulse.Pulse
    54  		}
    55  
    56  		return ps.currentPulse, nil
    57  	}
    58  
    59  	defer ps.rwLock.RUnlock()
    60  	return ps.currentPulse, nil
    61  }
    62  
    63  func (ps *PulseStorage) Set(pulse *core.Pulse) {
    64  	ps.currentPulse = pulse
    65  }
    66  
    67  // Lock takes lock on parent's pulse storage
    68  func (ps *PulseStorage) Lock() {
    69  	ps.rwLock.Lock()
    70  }
    71  
    72  // Unlock takes unlock on parent's pulse storage
    73  func (ps *PulseStorage) Unlock() {
    74  	ps.rwLock.Unlock()
    75  }