/
message_receiver.go
209 lines (179 loc) · 7.18 KB
/
message_receiver.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
/*
Copyright 2020 The Knative Authors
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 channel
import (
"context"
"errors"
"fmt"
nethttp "net/http"
"time"
"github.com/cloudevents/sdk-go/v2/binding"
"github.com/cloudevents/sdk-go/v2/protocol/http"
"go.uber.org/zap"
"knative.dev/pkg/network"
"knative.dev/eventing/pkg/kncloudevents"
"knative.dev/eventing/pkg/utils"
)
// UnknownChannelError represents the error when an event is received by a channel dispatcher for a
// channel that does not exist.
type UnknownChannelError struct {
Channel ChannelReference
}
func (e *UnknownChannelError) Error() string {
return fmt.Sprint("unknown channel: ", e.Channel)
}
// UnknownHostError represents the error when a ResolveMessageChannelFromHostHeader func cannot resolve an host
type UnknownHostError string
func (e UnknownHostError) Error() string {
return "cannot map host to channel: " + string(e)
}
// MessageReceiver starts a server to receive new events for the channel dispatcher. The new
// event is emitted via the receiver function.
type MessageReceiver struct {
httpBindingsReceiver *kncloudevents.HTTPMessageReceiver
receiverFunc UnbufferedMessageReceiverFunc
logger *zap.Logger
hostToChannelFunc ResolveChannelFromHostFunc
reporter StatsReporter
}
// UnbufferedMessageReceiverFunc is the function to be called for handling the message.
// The provided message is not buffered, so it can't be safely read more times.
// When you perform the write (or the buffering) of the Message, you must use the transformers provided as parameters.
// This function is responsible for invoking Message.Finish().
type UnbufferedMessageReceiverFunc func(context.Context, ChannelReference, binding.Message, []binding.Transformer, nethttp.Header) error
// ReceiverOptions provides functional options to MessageReceiver function.
type MessageReceiverOptions func(*MessageReceiver) error
// ResolveChannelFromHostFunc function enables EventReceiver to get the Channel Reference from incoming request HostHeader
// before calling receiverFunc.
// Returns UnknownHostError if the channel is not found, otherwise returns a generic error.
type ResolveChannelFromHostFunc func(string) (ChannelReference, error)
// ResolveMessageChannelFromHostHeader is a ReceiverOption for NewMessageReceiver which enables the caller to overwrite the
// default behaviour defined by ParseChannel function.
func ResolveMessageChannelFromHostHeader(hostToChannelFunc ResolveChannelFromHostFunc) MessageReceiverOptions {
return func(r *MessageReceiver) error {
r.hostToChannelFunc = hostToChannelFunc
return nil
}
}
// NewMessageReceiver creates an event receiver passing new events to the
// receiverFunc.
func NewMessageReceiver(receiverFunc UnbufferedMessageReceiverFunc, logger *zap.Logger, reporter StatsReporter, opts ...MessageReceiverOptions) (*MessageReceiver, error) {
bindingsReceiver := kncloudevents.NewHTTPMessageReceiver(8080)
receiver := &MessageReceiver{
httpBindingsReceiver: bindingsReceiver,
receiverFunc: receiverFunc,
hostToChannelFunc: ResolveChannelFromHostFunc(ParseChannel),
logger: logger,
reporter: reporter,
}
for _, opt := range opts {
if err := opt(receiver); err != nil {
return nil, err
}
}
return receiver, nil
}
// Start begins to receive events for the receiver.
//
// Only HTTP POST requests to the root path (/) are accepted. If other paths or
// methods are needed, use the HandleRequest method directly with another HTTP
// server.
func (r *MessageReceiver) Start(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
errCh := make(chan error, 1)
go func() {
errCh <- r.httpBindingsReceiver.StartListen(ctx, r)
}()
// Stop either if the receiver stops (sending to errCh) or if the context Done channel is closed.
select {
case err := <-errCh:
return err
case <-ctx.Done():
break
}
// Done channel has been closed, we need to gracefully shutdown r.ceClient. The cancel() method will start its
// shutdown, if it hasn't finished in a reasonable amount of Time, just return an error.
cancel()
select {
case err := <-errCh:
return err
case <-time.After(network.DefaultDrainTimeout):
return errors.New("timeout shutting down http bindings receiver")
}
}
func (r *MessageReceiver) ServeHTTP(response nethttp.ResponseWriter, request *nethttp.Request) {
response.Header().Set("Allow", "POST, OPTIONS")
if request.Method == nethttp.MethodOptions {
response.Header().Set("WebHook-Allowed-Origin", "*") // Accept from any Origin:
response.Header().Set("WebHook-Allowed-Rate", "*") // Unlimited requests/minute
response.WriteHeader(nethttp.StatusOK)
return
}
if request.Method != nethttp.MethodPost {
response.WriteHeader(nethttp.StatusMethodNotAllowed)
return
}
// tctx.URI is actually the path...
if request.URL.Path != "/" {
response.WriteHeader(nethttp.StatusNotFound)
return
}
args := ReportArgs{}
// The response status codes:
// 202 - the event was sent to subscribers
// 404 - the request was for an unknown channel
// 500 - an error occurred processing the request
host := request.Host
r.logger.Debug("Received request", zap.String("host", host))
channel, err := r.hostToChannelFunc(host)
if err != nil {
if _, ok := err.(UnknownHostError); ok {
response.WriteHeader(nethttp.StatusNotFound)
r.logger.Info(err.Error())
} else {
r.logger.Info("Could not extract channel", zap.Error(err))
response.WriteHeader(nethttp.StatusInternalServerError)
}
ReportEventCountMetricsForDispatchError(err, r.reporter, &args)
return
}
r.logger.Debug("Request mapped to channel", zap.String("channel", channel.String()))
args.Ns = channel.Namespace
message := http.NewMessageFromHttpRequest(request)
if message.ReadEncoding() == binding.EncodingUnknown {
r.logger.Info("Cannot determine the cloudevent message encoding")
response.WriteHeader(nethttp.StatusBadRequest)
r.reporter.ReportEventCount(&args, nethttp.StatusBadRequest)
return
}
err = r.receiverFunc(request.Context(), channel, message, []binding.Transformer{}, utils.PassThroughHeaders(request.Header))
if err != nil {
if _, ok := err.(*UnknownChannelError); ok {
response.WriteHeader(nethttp.StatusNotFound)
} else {
r.logger.Info("Error in receiver", zap.Error(err))
response.WriteHeader(nethttp.StatusInternalServerError)
}
return
}
response.WriteHeader(nethttp.StatusAccepted)
}
func ReportEventCountMetricsForDispatchError(err error, reporter StatsReporter, args *ReportArgs) {
if _, ok := err.(*UnknownChannelError); ok {
_ = reporter.ReportEventCount(args, nethttp.StatusNotFound)
} else {
_ = reporter.ReportEventCount(args, nethttp.StatusInternalServerError)
}
}
var _ nethttp.Handler = (*MessageReceiver)(nil)