-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
http_channel.go
226 lines (184 loc) · 6.61 KB
/
http_channel.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
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation and Dapr Contributors.
// Licensed under the MIT License.
// ------------------------------------------------------------
package http
import (
"context"
"crypto/tls"
"fmt"
"strconv"
"time"
nethttp "net/http"
jsoniter "github.com/json-iterator/go"
"github.com/valyala/fasthttp"
"go.opencensus.io/plugin/ochttp/propagation/tracecontext"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/dapr/dapr/pkg/channel"
"github.com/dapr/dapr/pkg/config"
diag "github.com/dapr/dapr/pkg/diagnostics"
diag_utils "github.com/dapr/dapr/pkg/diagnostics/utils"
invokev1 "github.com/dapr/dapr/pkg/messaging/v1"
commonv1pb "github.com/dapr/dapr/pkg/proto/common/v1"
internalv1pb "github.com/dapr/dapr/pkg/proto/internals/v1"
auth "github.com/dapr/dapr/pkg/runtime/security"
)
const (
// HTTPStatusCode is an dapr http channel status code.
HTTPStatusCode = "http.status_code"
httpScheme = "http"
httpsScheme = "https"
appConfigEndpoint = "dapr/config"
)
// Channel is an HTTP implementation of an AppChannel.
type Channel struct {
client *fasthttp.Client
baseAddress string
ch chan int
tracingSpec config.TracingSpec
appHeaderToken string
json jsoniter.API
maxResponseBodySize int
}
// CreateLocalChannel creates an HTTP AppChannel
// nolint:gosec
func CreateLocalChannel(port, maxConcurrency int, spec config.TracingSpec, sslEnabled bool, maxRequestBodySize int) (channel.AppChannel, error) {
scheme := httpScheme
if sslEnabled {
scheme = httpsScheme
}
c := &Channel{
client: &fasthttp.Client{
MaxConnsPerHost: 1000000,
MaxIdemponentCallAttempts: 0,
},
baseAddress: fmt.Sprintf("%s://%s:%d", scheme, channel.DefaultChannelAddress, port),
tracingSpec: spec,
appHeaderToken: auth.GetAppToken(),
json: jsoniter.ConfigFastest,
maxResponseBodySize: maxRequestBodySize,
}
if sslEnabled {
c.client.TLSConfig = &tls.Config{InsecureSkipVerify: true}
}
if maxConcurrency > 0 {
c.ch = make(chan int, maxConcurrency)
}
return c, nil
}
// GetBaseAddress returns the application base address.
func (h *Channel) GetBaseAddress() string {
return h.baseAddress
}
// GetAppConfig gets application config from user application
// GET http://localhost:<app_port>/dapr/config
func (h *Channel) GetAppConfig() (*config.ApplicationConfig, error) {
req := invokev1.NewInvokeMethodRequest(appConfigEndpoint)
req.WithHTTPExtension(nethttp.MethodGet, "")
req.WithRawData(nil, invokev1.JSONContentType)
// TODO Propagate context
ctx := context.Background()
resp, err := h.InvokeMethod(ctx, req)
if err != nil {
return nil, err
}
var config config.ApplicationConfig
if resp.Status().Code != nethttp.StatusOK {
return &config, nil
}
_, body := resp.RawData()
if err = h.json.Unmarshal(body, &config); err != nil {
return nil, err
}
return &config, nil
}
// InvokeMethod invokes user code via HTTP.
func (h *Channel) InvokeMethod(ctx context.Context, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
// Check if HTTP Extension is given. Otherwise, it will return error.
httpExt := req.Message().GetHttpExtension()
if httpExt == nil {
return nil, status.Error(codes.InvalidArgument, "missing HTTP extension field")
}
if httpExt.GetVerb() == commonv1pb.HTTPExtension_NONE {
return nil, status.Error(codes.InvalidArgument, "invalid HTTP verb")
}
var rsp *invokev1.InvokeMethodResponse
var err error
switch req.APIVersion() {
case internalv1pb.APIVersion_V1:
rsp, err = h.invokeMethodV1(ctx, req)
default:
// Reject unsupported version
err = status.Error(codes.Unimplemented, fmt.Sprintf("Unsupported spec version: %d", req.APIVersion()))
}
return rsp, err
}
func (h *Channel) invokeMethodV1(ctx context.Context, req *invokev1.InvokeMethodRequest) (*invokev1.InvokeMethodResponse, error) {
channelReq := h.constructRequest(ctx, req)
if h.ch != nil {
h.ch <- 1
}
// Emit metric when request is sent
verb := string(channelReq.Header.Method())
diag.DefaultHTTPMonitoring.ClientRequestStarted(ctx, verb, req.Message().Method, int64(len(req.Message().Data.GetValue())))
startRequest := time.Now()
// Send request to user application
resp := fasthttp.AcquireResponse()
err := h.client.Do(channelReq, resp)
defer func() {
fasthttp.ReleaseRequest(channelReq)
fasthttp.ReleaseResponse(resp)
}()
elapsedMs := float64(time.Since(startRequest) / time.Millisecond)
if h.ch != nil {
<-h.ch
}
rsp := h.parseChannelResponse(req, resp, err)
diag.DefaultHTTPMonitoring.ClientRequestCompleted(ctx, verb, req.Message().GetMethod(), strconv.Itoa(int(rsp.Status().Code)), int64(resp.Header.ContentLength()), elapsedMs)
return rsp, nil
}
func (h *Channel) constructRequest(ctx context.Context, req *invokev1.InvokeMethodRequest) *fasthttp.Request {
channelReq := fasthttp.AcquireRequest()
// Construct app channel URI: VERB http://localhost:3000/method?query1=value1
uri := fmt.Sprintf("%s/%s", h.baseAddress, req.Message().GetMethod())
channelReq.SetRequestURI(uri)
channelReq.URI().SetQueryString(req.EncodeHTTPQueryString())
channelReq.Header.SetMethod(req.Message().HttpExtension.Verb.String())
// Recover headers
invokev1.InternalMetadataToHTTPHeader(ctx, req.Metadata(), channelReq.Header.Set)
// HTTP client needs to inject traceparent header for proper tracing stack.
span := diag_utils.SpanFromContext(ctx)
httpFormat := &tracecontext.HTTPFormat{}
tp, ts := httpFormat.SpanContextToHeaders(span.SpanContext())
channelReq.Header.Set("traceparent", tp)
if ts != "" {
channelReq.Header.Set("tracestate", ts)
}
if h.appHeaderToken != "" {
channelReq.Header.Set(auth.APITokenHeader, h.appHeaderToken)
}
// Set Content body and types
contentType, body := req.RawData()
channelReq.Header.SetContentType(contentType)
channelReq.SetBody(body)
return channelReq
}
func (h *Channel) parseChannelResponse(req *invokev1.InvokeMethodRequest, resp *fasthttp.Response, respErr error) *invokev1.InvokeMethodResponse {
var statusCode int
var contentType string
var body []byte
if respErr != nil {
statusCode = fasthttp.StatusInternalServerError
contentType = string(invokev1.JSONContentType)
body = []byte(fmt.Sprintf("{\"error\": \"client error: %s\"}", respErr))
} else {
statusCode = resp.StatusCode()
contentType = (string)(resp.Header.ContentType())
body = resp.Body()
}
// Convert status code
rsp := invokev1.NewInvokeMethodResponse(int32(statusCode), "", nil)
rsp.WithFastHTTPHeaders(&resp.Header).WithRawData(body, contentType)
return rsp
}