-
Notifications
You must be signed in to change notification settings - Fork 5
/
handler_wrapper.go
215 lines (171 loc) · 5.04 KB
/
handler_wrapper.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
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
package iopipe
import (
"context"
"fmt"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/aws/aws-lambda-go/lambdacontext"
log "github.com/sirupsen/logrus"
)
// HandlerWrapper is the IOpipe handler wrapper
type HandlerWrapper struct {
agent *Agent
deadline time.Time
lambdaContext *lambdacontext.LambdaContext
originalHandler interface{}
report *Report
wrappedHandler lambdaHandler
Log *log.Logger
}
// NewHandlerWrapper creates a new IOpipe handler wrapper
func NewHandlerWrapper(handler interface{}, agent *Agent) *HandlerWrapper {
return &HandlerWrapper{
agent: agent,
originalHandler: handler,
wrappedHandler: newHandler(handler),
Log: agent.log,
}
}
// Invoke invokes the wrapped handler, handling panics and timeouts
func (hw *HandlerWrapper) Invoke(ctx context.Context, payload interface{}) (response interface{}, err error) {
lc, _ := lambdacontext.FromContext(ctx)
hw.lambdaContext = lc
cw := NewContextWrapper(lc, hw)
ctx = NewContext(ctx, cw)
hw.deadline, _ = ctx.Deadline()
hw.report = NewReport(hw)
hw.preInvoke(ctx, payload)
// Handle and report a panic if it occurs
defer func() {
if panicErr := recover(); panicErr != nil {
hw.Label("@iopipe/error")
hw.report.prepare(NewPanicInvocationError(panicErr))
hw.report.send()
panic(panicErr)
}
}()
// Start the timeout clock and handle timeouts
go func() {
if hw.deadline.IsZero() {
hw.Log.Debug("Deadline is zero, disabling timeout handling")
return
}
timeoutWindow := 0 * time.Millisecond
if hw.agent != nil && hw.agent.TimeoutWindow != nil {
timeoutWindow = *hw.agent.TimeoutWindow
}
timeoutDuration := hw.deadline.Add(-timeoutWindow)
// If timeout duration is in the past, disable timeout handling
if time.Now().After(timeoutDuration) {
hw.Log.Debug("Timeout deadline is in the past, disabling timeout handling")
return
}
hw.Log.Debug("Setting function to timeout in ", time.Until(timeoutDuration).String())
timeoutChannel := time.After(time.Until(timeoutDuration))
select {
// We're within the timeout window
case <-timeoutChannel:
hw.Log.Debug("Function is about to timeout, sending report")
hw.Label("@iopipe/timeout")
hw.report.prepare(fmt.Errorf("Timeout Exceeded"))
hw.report.send()
return
case <-ctx.Done():
return
}
}()
response, err = hw.wrappedHandler(ctx, payload)
if coldStart {
hw.Label("@iopipe/coldstart")
}
coldStart = false
if err != nil {
hw.Label("@iopipe/error")
}
hw.postInvoke(ctx, payload)
if hw.report != nil {
hw.report.prepare(err)
hw.report.send()
}
return response, err
}
// Error adds an error to the report
func (hw *HandlerWrapper) Error(err error) {
if hw.report == nil {
hw.Log.Warn("Attempting to add error before function decorated with IOpipe. This error will not be recorded.")
return
}
hw.Label("@iopipe/error")
hw.report.prepare(err)
hw.report.send()
}
// Label adds a label to the report
func (hw *HandlerWrapper) Label(name string) {
if hw.report == nil {
hw.Log.Warn("Attempting to add labels before function decorated with IOpipe. This metric will not be recorded.")
return
}
if utf8.RuneCountInString(name) > 128 {
hw.Log.Warn(fmt.Sprintf("Label name %s is longer than allowed limit of 128 characters. This label will not be recorded.", name))
return
}
// USing map to ensure uniqueness of labels
if _, ok := hw.report.labels[name]; !ok {
hw.report.labels[name] = struct{}{}
}
}
// Metric adds a custom metric to the report
func (hw *HandlerWrapper) Metric(name string, value interface{}) {
if hw.report == nil {
hw.Log.Warn("Attempting to add metrics before function decorated with IOpipe. This metric will not be recorded.")
return
}
if utf8.RuneCountInString(name) > 128 {
hw.Log.Warn(fmt.Sprintf("Metric of name %s is longer than allowed limit of 128 characters. This metric will not be recorded.", name))
return
}
s := coerceString(value)
if s != nil {
if !strings.HasPrefix(name, "@iopipe") {
hw.Label("@iopipe/metrics")
}
hw.report.CustomMetrics = append(hw.report.CustomMetrics, CustomMetric{Name: name, S: s})
}
n := coerceNumeric(value)
if n != nil {
if !strings.HasPrefix(name, "@iopipe") {
hw.Label("@iopipe/metrics")
}
hw.report.CustomMetrics = append(hw.report.CustomMetrics, CustomMetric{Name: name, N: n})
}
}
// preInvoke runs the PreInvoke hooks
func (hw *HandlerWrapper) preInvoke(ctx context.Context, payload interface{}) {
var wg sync.WaitGroup
wg.Add(len(hw.agent.plugins))
for _, plugin := range hw.agent.plugins {
go func(plugin Plugin) {
defer wg.Done()
if plugin != nil {
plugin.PreInvoke(ctx, payload)
}
}(plugin)
}
wg.Wait()
}
// postInvoke runs the PostInvoke hooks
func (hw *HandlerWrapper) postInvoke(ctx context.Context, payload interface{}) {
var wg sync.WaitGroup
wg.Add(len(hw.agent.plugins))
for _, plugin := range hw.agent.plugins {
go func(plugin Plugin) {
defer wg.Done()
if plugin != nil && plugin.Enabled() {
plugin.PostInvoke(ctx, payload)
}
}(plugin)
}
wg.Wait()
}