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