-
Notifications
You must be signed in to change notification settings - Fork 453
/
invariant.go
116 lines (98 loc) · 4.51 KB
/
invariant.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package instrument
import (
"fmt"
"os"
"strconv"
"strings"
"go.uber.org/zap"
)
const (
// InvariantViolatedMetricName is the name of the metric emitted upon
// invocation of `EmitInvariantViolation`.
InvariantViolatedMetricName = "invariant_violated"
// InvariantViolatedLogFieldName is the name of the log field to be
// used when generating errors/log statements pertaining to the violation
// of an invariant.
InvariantViolatedLogFieldName = "violation"
// InvariantViolatedLogFieldValue is the value of the log field to be
// used when generating errors/log statements pertaining to the violation
// of an invariant.
InvariantViolatedLogFieldValue = InvariantViolatedMetricName
// ShouldPanicEnvironmentVariableName is the name of the environment variable
// that must be set to "true" in order for the invariant violated functions
// to panic after logging / emitting metrics. Should only be set in test
// environments.
ShouldPanicEnvironmentVariableName = "PANIC_ON_INVARIANT_VIOLATED"
)
// EmitInvariantViolation emits a metric to indicate a system invariant has
// been violated. Users of this method are expected to monitor/alert off this
// metric to ensure they're notified when such an event occurs. Further, they
// should log further information to aid diagnostics of the system invariant
// violated at the callsite of the violation. Optionally panics if the
// ShouldPanicEnvironmentVariableName is set to "true".
func EmitInvariantViolation(opts Options) {
// NB(prateek): there's no need to cache this metric. It should be never
// be called in production systems unless something is seriously messed
// up. At which point, the extra map alloc should be of no concern.
opts.MetricsScope().Counter(InvariantViolatedMetricName).Inc(1)
panicIfEnvSet()
}
// EmitAndLogInvariantViolation calls EmitInvariantViolation and then calls the provided function
// with a supplied logger that is pre-configured with an invariant violated field. Optionally panics
// if the ShouldPanicEnvironmentVariableName is set to "true".
func EmitAndLogInvariantViolation(opts Options, f func(l *zap.Logger)) {
logger := opts.Logger().With(
zap.String(InvariantViolatedLogFieldName, InvariantViolatedLogFieldValue))
f(logger)
EmitInvariantViolation(opts)
}
// InvariantErrorf constructs a new error, prefixed with a string indicating that an invariant
// violation occurred. Optionally panics if the ShouldPanicEnvironmentVariableName is set to "true".
func InvariantErrorf(format string, a ...interface{}) error {
var (
invariantFormat = InvariantViolatedMetricName + ": " + format
err = fmt.Errorf(invariantFormat, a...)
)
panicIfEnvSetWithMessage(err.Error())
return err
}
// SetShouldPanicEnvironmentVariable sets the env variable and returns a func to reset to the previous value.
// Useful for tests to use a defer statement when they need to test a specific value.
func SetShouldPanicEnvironmentVariable(value bool) func() {
restoreValue := os.Getenv(ShouldPanicEnvironmentVariableName)
_ = os.Setenv(ShouldPanicEnvironmentVariableName, strconv.FormatBool(value))
return func() {
_ = os.Setenv(ShouldPanicEnvironmentVariableName, restoreValue)
}
}
func panicIfEnvSet() {
panicIfEnvSetWithMessage("")
}
func panicIfEnvSetWithMessage(s string) {
envIsSet := strings.ToLower(os.Getenv(ShouldPanicEnvironmentVariableName)) == "true"
if envIsSet {
if s == "" {
s = "invariant violation detected"
}
panic(s)
}
}