-
Notifications
You must be signed in to change notification settings - Fork 59
/
framework.go
274 lines (231 loc) · 9.11 KB
/
framework.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
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package funcframework is a Functions Framework implementation for Go. It allows you to register
// HTTP and event functions, then start an HTTP server serving those functions.
package funcframework
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"reflect"
"runtime/debug"
"strings"
"github.com/GoogleCloudPlatform/functions-framework-go/internal/registry"
cloudevents "github.com/cloudevents/sdk-go/v2"
)
const (
functionStatusHeader = "X-Google-Status"
crashStatus = "crash"
errorStatus = "error"
)
var (
handler = http.DefaultServeMux
)
func recoverPanic(msg string) {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n\n%s", msg, r, debug.Stack())
}
}
func recoverPanicHTTP(w http.ResponseWriter, msg string) {
if r := recover(); r != nil {
writeHTTPErrorResponse(w, http.StatusInternalServerError, crashStatus, fmt.Sprintf("%s: %v\n\n%s", msg, r, debug.Stack()))
}
}
// RegisterHTTPFunction registers fn as an HTTP function.
// Maintained for backward compatibility. Please use RegisterHTTPFunctionContext instead.
func RegisterHTTPFunction(path string, fn interface{}) {
defer recoverPanic("Registration panic")
fnHTTP, ok := fn.(func(http.ResponseWriter, *http.Request))
if !ok {
panic("expected function to have signature func(http.ResponseWriter, *http.Request)")
}
ctx := context.Background()
if err := RegisterHTTPFunctionContext(ctx, path, fnHTTP); err != nil {
panic(fmt.Sprintf("unexpected error in RegisterEventFunctionContext: %v", err))
}
}
// RegisterEventFunction registers fn as an event function.
// Maintained for backward compatibility. Please use RegisterEventFunctionContext instead.
func RegisterEventFunction(path string, fn interface{}) {
defer recoverPanic("Registration panic")
ctx := context.Background()
if err := RegisterEventFunctionContext(ctx, path, fn); err != nil {
panic(fmt.Sprintf("unexpected error in RegisterEventFunctionContext: %v", err))
}
}
// RegisterHTTPFunctionContext registers fn as an HTTP function.
func RegisterHTTPFunctionContext(ctx context.Context, path string, fn func(http.ResponseWriter, *http.Request)) error {
return registerHTTPFunction(path, fn, handler)
}
// RegisterEventFunctionContext registers fn as an event function. The function must have two arguments, a
// context.Context and a struct type depending on the event, and return an error. If fn has the
// wrong signature, RegisterEventFunction returns an error.
func RegisterEventFunctionContext(ctx context.Context, path string, fn interface{}) error {
return registerEventFunction(path, fn, handler)
}
// RegisterCloudEventFunctionContext registers fn as an cloudevent function.
func RegisterCloudEventFunctionContext(ctx context.Context, path string, fn func(context.Context, cloudevents.Event) error) error {
return registerCloudEventFunction(ctx, path, fn, handler)
}
// Declaratively registers a HTTP function.
func HTTP(name string, fn func(http.ResponseWriter, *http.Request)) {
defer recoverPanic("Registration panic")
// Register the function.
registry.RegisterHTTP(name, fn)
}
// Declaratively registers a CloudEvent function.
func CloudEvent(name string, fn func(context.Context, cloudevents.Event) error) {
defer recoverPanic("Registration panic")
// Register the function.
registry.RegisterCloudEvent(name, fn)
}
// Start serves an HTTP server with registered function(s).
func Start(port string) error {
// If FUNCTION_TARGET, try to start with that registered function
// If not set, assume non-declarative functions.
target := os.Getenv("FUNCTION_TARGET")
if target == "" {
// Default function target
target = "function"
}
// Check if we have a function resource set, and if so, log progress.
if os.Getenv("K_SERVICE") == "" {
fmt.Printf("Serving function: %s\n", target)
}
// Check if there's a registered function, and use if possible
fn, hasRegisteredFn := registry.GetRegisteredFunction(target)
if hasRegisteredFn {
ctx := context.Background()
if fn.HTTPFn != nil {
if err := registerHTTPFunction("/", fn.HTTPFn, handler); err != nil {
panic(fmt.Sprintf("unexpected error in registerHTTPFunction: %v", err))
}
} else if fn.CloudEventFn != nil {
if err := registerCloudEventFunction(ctx, "/", fn.CloudEventFn, handler); err != nil {
panic(fmt.Sprintf("unexpected error in registerCloudEventFunction: %v", err))
}
}
}
return http.ListenAndServe(":"+port, handler)
}
func registerHTTPFunction(path string, fn func(http.ResponseWriter, *http.Request), h *http.ServeMux) error {
h.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
// TODO(b/111823046): Remove following once Cloud Functions does not need flushing the logs anymore.
if os.Getenv("K_SERVICE") != "" {
// Force flush of logs after every function trigger when running on GCF.
defer fmt.Println()
defer fmt.Fprintln(os.Stderr)
}
defer recoverPanicHTTP(w, "Function panic")
fn(w, r)
})
return nil
}
func registerEventFunction(path string, fn interface{}, h *http.ServeMux) error {
err := validateEventFunction(fn)
if err != nil {
return err
}
h.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if os.Getenv("K_SERVICE") != "" {
// Force flush of logs after every function trigger when running on GCF.
defer fmt.Println()
defer fmt.Fprintln(os.Stderr)
}
defer recoverPanicHTTP(w, "Function panic")
if shouldConvertCloudEventToBackgroundRequest(r) {
if err := convertCloudEventToBackgroundRequest(r); err != nil {
writeHTTPErrorResponse(w, http.StatusBadRequest, crashStatus, fmt.Sprintf("error converting CloudEvent to Background Event: %v", err))
}
}
handleEventFunction(w, r, fn)
})
return nil
}
func registerCloudEventFunction(ctx context.Context, path string, fn func(context.Context, cloudevents.Event) error, h *http.ServeMux) error {
p, err := cloudevents.NewHTTP()
if err != nil {
return fmt.Errorf("failed to create protocol: %v", err)
}
handleFn, err := cloudevents.NewHTTPReceiveHandler(ctx, p, fn)
if err != nil {
return fmt.Errorf("failed to create handler: %v", err)
}
h.Handle(path, convertBackgroundToCloudEvent(handleFn))
return nil
}
func handleEventFunction(w http.ResponseWriter, r *http.Request, fn interface{}) {
body, err := readHTTPRequestBody(r)
if err != nil {
writeHTTPErrorResponse(w, http.StatusBadRequest, crashStatus, fmt.Sprintf("%v", err))
return
}
// Background events have data and an associated metadata, so parse those and run if present.
if metadata, data, err := getBackgroundEvent(body, r.URL.Path); err != nil {
writeHTTPErrorResponse(w, http.StatusBadRequest, crashStatus, fmt.Sprintf("Error: %s, parsing background event: %s", err.Error(), string(body)))
return
} else if data != nil && metadata != nil {
runBackgroundEvent(w, r, metadata, data, fn)
return
}
// Otherwise, we assume the body is a JSON blob containing the user-specified data structure.
runUserFunction(w, r, body, fn)
}
func readHTTPRequestBody(r *http.Request) ([]byte, error) {
if r.Body == nil {
return nil, fmt.Errorf("request body not found")
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, fmt.Errorf("could not read request body %s: %v", r.Body, err)
}
return body, nil
}
func runUserFunction(w http.ResponseWriter, r *http.Request, data []byte, fn interface{}) {
runUserFunctionWithContext(r.Context(), w, r, data, fn)
}
func runUserFunctionWithContext(ctx context.Context, w http.ResponseWriter, r *http.Request, data []byte, fn interface{}) {
argVal := reflect.New(reflect.TypeOf(fn).In(1))
if err := json.Unmarshal(data, argVal.Interface()); err != nil {
writeHTTPErrorResponse(w, http.StatusBadRequest, crashStatus, fmt.Sprintf("Error: %s, while converting event data: %s", err.Error(), string(data)))
return
}
userFunErr := reflect.ValueOf(fn).Call([]reflect.Value{
reflect.ValueOf(ctx),
argVal.Elem(),
})
if userFunErr[0].Interface() != nil {
writeHTTPErrorResponse(w, http.StatusInternalServerError, errorStatus, fmt.Sprintf("Function error: %v", userFunErr[0]))
return
}
}
func writeHTTPErrorResponse(w http.ResponseWriter, statusCode int, status, msg string) {
// Ensure logs end with a newline otherwise they are grouped incorrectly in SD.
if !strings.HasSuffix(msg, "\n") {
msg += "\n"
}
fmt.Fprint(os.Stderr, msg)
// Flush stdout and stderr when running on GCF. This must be done before writing
// the HTTP response in order for all logs to appear in Stackdriver.
if os.Getenv("K_SERVICE") != "" {
fmt.Println()
fmt.Fprintln(os.Stderr)
}
w.Header().Set(functionStatusHeader, status)
w.WriteHeader(statusCode)
fmt.Fprint(w, msg)
}