-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.go
More file actions
250 lines (215 loc) · 5.93 KB
/
middleware.go
File metadata and controls
250 lines (215 loc) · 5.93 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package cron
import (
"context"
"errors"
"fmt"
"runtime"
"sync"
"time"
"github.com/getsentry/sentry-go"
"github.com/prometheus/client_golang/prometheus"
)
const (
isDevelCtx contextKey = "isDevelKey"
)
// WithLogger logs via Printf function (e.g. log.Printf) all runs.
func WithLogger(pf LogPrintf, managerName string) MiddlewareFunc {
return func(next Func) Func {
return func(ctx context.Context) error {
start := time.Now()
err := next(ctx)
// set error msg for %q
errMsg, state := "", "finished"
if errors.Is(err, ErrSkipped) {
state = "skipped"
} else if err != nil {
errMsg = err.Error()
}
pf("cron job %s job=%s duration=%v err=%q manager=%s maintenance=%v",
state,
NameFromContext(ctx),
time.Since(start),
errMsg,
managerName,
MaintenanceFromContext(ctx),
)
return err
}
}
}
// Logger is as simple interface for slog.
type Logger interface {
Print(ctx context.Context, msg string, args ...any)
Error(ctx context.Context, msg string, args ...any)
}
// WithSLog logs all runs via slog (see Logger interface).
func WithSLog(lg Logger) MiddlewareFunc {
return func(next Func) Func {
return func(ctx context.Context) error {
start := time.Now()
err := next(ctx)
d, name := time.Since(start), NameFromContext(ctx)
switch {
case errors.Is(err, ErrSkipped):
lg.Print(ctx, "cron job skipped", "job", name, "duration", d.String(), "durationMS", d.Milliseconds())
case err != nil:
lg.Error(ctx, "cron job failed", "job", name, "duration", d.String(), "durationMS", d.Milliseconds(), "err", err)
default:
lg.Print(ctx, "cron job finished", "job", name, "duration", d.String(), "durationMS", d.Milliseconds())
}
return err
}
}
}
// WithSentry sends all errors to sentry. It's also handles panics.
func WithSentry() MiddlewareFunc {
return func(next Func) Func {
return func(ctx context.Context) (err error) {
defer func() {
var rec any
if rec = recover(); rec != nil {
switch e := rec.(type) {
case error:
err = e
default:
err = fmt.Errorf("%v", e)
}
}
if err != nil {
sentryHub := sentry.CurrentHub().Clone()
sentryHub.WithScope(func(scope *sentry.Scope) {
scope.SetTag("cron", NameFromContext(ctx))
sentryHub.CaptureException(err)
})
}
}()
return next(ctx)
}
}
}
// WithRecover use recover() func. Do not use with WithSentry middleware due to recover() call.
func WithRecover() MiddlewareFunc {
return func(next Func) Func {
return func(ctx context.Context) (err error) {
// recover
defer func() {
if rec := recover(); rec != nil {
stack := make([]byte, 64<<10)
stack = stack[:runtime.Stack(stack, false)]
err = fmt.Errorf("panic: %v: %s", rec, stack)
}
}()
return next(ctx)
}
}
}
// WithDevel sets bool flag to context for detecting development environment.
func WithDevel(isDevel bool) MiddlewareFunc {
return func(h Func) Func {
return func(ctx context.Context) error {
ctx = NewIsDevelContext(ctx, isDevel)
return h(ctx)
}
}
}
// NewIsDevelContext creates new context with isDevel flag.
func NewIsDevelContext(ctx context.Context, isDevel bool) context.Context {
return context.WithValue(ctx, isDevelCtx, isDevel)
}
// IsDevelFromContext returns isDevel flag from context.
func IsDevelFromContext(ctx context.Context) bool {
if isDevel, ok := ctx.Value(isDevelCtx).(bool); ok {
return isDevel
}
return false
}
// WithSkipActive skips funcs if they are already running.
func WithSkipActive() MiddlewareFunc {
active := map[string]struct{}{}
mu := sync.Mutex{}
return func(next Func) Func {
return func(ctx context.Context) error {
name := NameFromContext(ctx)
// check for running function
mu.Lock()
if _, ok := active[name]; ok {
mu.Unlock()
return ErrSkipped
}
// set active name
active[name] = struct{}{}
mu.Unlock()
defer func() {
mu.Lock()
delete(active, name)
mu.Unlock()
}()
// run func
return next(ctx)
}
}
}
// WithMaintenance puts cron jobs in line, got exclusive lock for maintenance job.
func WithMaintenance(p LogPrintf) MiddlewareFunc {
mutex := sync.RWMutex{}
pf := func(format string, v ...interface{}) {
if p != nil {
p(format, v...)
}
}
return func(next Func) Func {
return func(ctx context.Context) error {
name, isMaintenance := NameFromContext(ctx), MaintenanceFromContext(ctx)
if isMaintenance {
pf("cron getting maintenance lock=%v", name)
mutex.Lock()
pf("cron got maintenance lock=%v", name)
} else {
mutex.RLock()
}
err := next(ctx)
if isMaintenance {
mutex.Unlock()
} else {
mutex.RUnlock()
}
return err
}
}
}
// WithMetrics tracks total/active/duration metrics for runs.
func WithMetrics(app string) MiddlewareFunc {
statEvaluated := prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "app",
Subsystem: "cron",
Name: "evaluated_total",
Help: "Track all evaluations of cron.",
}, []string{"app", "cron", "state"})
statActive := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "app",
Subsystem: "cron",
Name: "active",
Help: "Track current status of cron.",
}, []string{"app", "cron"})
statDurations := prometheus.NewSummaryVec(prometheus.SummaryOpts{
Namespace: "app",
Subsystem: "cron",
Name: "evaluated_duration_seconds",
Help: "Response time by cron.",
}, []string{"app", "cron", "state"})
prometheus.MustRegister(statEvaluated, statActive, statDurations)
return func(next Func) Func {
return func(ctx context.Context) error {
name, start, state := NameFromContext(ctx), time.Now(), "ok"
statActive.WithLabelValues(app, name).Inc()
err := next(ctx)
if err != nil {
state = "error"
}
statActive.WithLabelValues(app, name).Dec()
statEvaluated.WithLabelValues(app, name, state).Inc()
statDurations.WithLabelValues(app, name, state).Observe(time.Since(start).Seconds())
return err
}
}
}