github.com/iotexproject/iotex-core@v1.14.1-rc1/pkg/lifecycle/ready.go (about)

     1  // Copyright (c) 2021 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package lifecycle
     7  
     8  import (
     9  	"sync/atomic"
    10  
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  const (
    15  	_notReady = 0
    16  	_ready    = 1
    17  )
    18  
    19  // vars
    20  var (
    21  	ErrWrongState = errors.New("service is in wrong state")
    22  )
    23  
    24  // Readiness is a thread-safe struct to indicate a service's status
    25  type Readiness struct {
    26  	ready int32
    27  }
    28  
    29  // TurnOn sets the service to ready (can accept service request)
    30  func (r *Readiness) TurnOn() error {
    31  	if atomic.CompareAndSwapInt32(&r.ready, _notReady, _ready) {
    32  		return nil
    33  	}
    34  	return ErrWrongState
    35  }
    36  
    37  // TurnOff sets the service to not ready (initial state)
    38  func (r *Readiness) TurnOff() error {
    39  	if atomic.CompareAndSwapInt32(&r.ready, _ready, _notReady) {
    40  		return nil
    41  	}
    42  	return ErrWrongState
    43  }
    44  
    45  // IsReady returns whether the service is ready (can accept service request)
    46  func (r *Readiness) IsReady() bool {
    47  	return atomic.LoadInt32(&r.ready) == _ready
    48  }