-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
testing.go
268 lines (224 loc) · 5.75 KB
/
testing.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
//go:build go1.15
// +build go1.15
package eventstreamtest
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/awstesting/unit"
"github.com/aws/aws-sdk-go/private/protocol"
"github.com/aws/aws-sdk-go/private/protocol/eventstream"
"golang.org/x/net/http2"
)
const (
errClientDisconnected = "client disconnected"
errStreamClosed = "http2: stream closed"
)
// ServeEventStream provides serving EventStream messages from a HTTP server to
// the client. The events are sent sequentially to the client without delay.
type ServeEventStream struct {
T *testing.T
BiDirectional bool
Events []eventstream.Message
ClientEvents []eventstream.Message
ForceCloseAfter time.Duration
requestsIdx int
}
func (s ServeEventStream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush()
if s.BiDirectional {
s.serveBiDirectionalStream(w, r)
} else {
s.serveReadOnlyStream(w, r)
}
}
func (s *ServeEventStream) serveReadOnlyStream(w http.ResponseWriter, r *http.Request) {
encoder := eventstream.NewEncoder(flushWriter{w})
for _, event := range s.Events {
encoder.Encode(event)
}
}
func (s *ServeEventStream) serveBiDirectionalStream(w http.ResponseWriter, r *http.Request) {
var wg sync.WaitGroup
ctx := context.Background()
if s.ForceCloseAfter > 0 {
var cancelFunc func()
ctx, cancelFunc = context.WithTimeout(context.Background(), s.ForceCloseAfter)
defer cancelFunc()
}
var (
err error
m sync.Mutex
)
wg.Add(1)
go func() {
defer wg.Done()
readErr := s.readEvents(ctx, r)
if readErr != nil {
m.Lock()
if err == nil {
err = readErr
}
m.Unlock()
}
}()
writeErr := s.writeEvents(ctx, w)
if writeErr != nil {
m.Lock()
if err != nil {
err = writeErr
}
m.Unlock()
}
wg.Wait()
if err != nil && isError(err) {
s.T.Error(err.Error())
}
}
func isError(err error) bool {
switch err.(type) {
case http2.StreamError:
return false
}
for _, s := range []string{errClientDisconnected, errStreamClosed} {
if strings.Contains(err.Error(), s) {
return false
}
}
return true
}
func (s ServeEventStream) readEvents(ctx context.Context, r *http.Request) error {
signBuffer := make([]byte, 1024)
messageBuffer := make([]byte, 1024)
decoder := eventstream.NewDecoder(r.Body)
for {
select {
case <-ctx.Done():
return nil
default:
}
// unwrap signing envelope
signedMessage, err := decoder.Decode(signBuffer)
if err != nil {
if err == io.EOF {
break
}
return err
}
// empty payload is expected for the last signing message
if len(signedMessage.Payload) == 0 {
break
}
// get service event message from payload
msg, err := eventstream.Decode(bytes.NewReader(signedMessage.Payload), messageBuffer)
if err != nil {
if err == io.EOF {
break
}
return err
}
if len(s.ClientEvents) > 0 {
i := s.requestsIdx
s.requestsIdx++
if e, a := s.ClientEvents[i], msg; !reflect.DeepEqual(e, a) {
return fmt.Errorf("expected %v, got %v", e, a)
}
}
}
return nil
}
func (s *ServeEventStream) writeEvents(ctx context.Context, w http.ResponseWriter) error {
encoder := eventstream.NewEncoder(flushWriter{w})
var event eventstream.Message
pendingEvents := s.Events
for len(pendingEvents) > 0 {
event, pendingEvents = pendingEvents[0], pendingEvents[1:]
select {
case <-ctx.Done():
return nil
default:
err := encoder.Encode(event)
if err != nil {
if err == io.EOF {
return nil
}
return fmt.Errorf("expected no error encoding event, got %v", err)
}
}
}
return nil
}
// SetupEventStreamSession creates a HTTP server SDK session for communicating
// with that server to be used for EventStream APIs. If HTTP/2 is enabled the
// server/client will only attempt to use HTTP/2.
func SetupEventStreamSession(
t *testing.T, handler http.Handler, h2 bool,
) (sess *session.Session, cleanupFn func(), err error) {
server := httptest.NewUnstartedServer(handler)
client := setupServer(server, h2)
cleanupFn = func() {
server.Close()
}
sess, err = session.NewSession(unit.Session.Config, &aws.Config{
Endpoint: &server.URL,
DisableParamValidation: aws.Bool(true),
HTTPClient: client,
// LogLevel: aws.LogLevel(aws.LogDebugWithEventStreamBody),
})
if err != nil {
return nil, nil, err
}
return sess, cleanupFn, nil
}
type flushWriter struct {
w io.Writer
}
func (fw flushWriter) Write(p []byte) (n int, err error) {
n, err = fw.w.Write(p)
if f, ok := fw.w.(http.Flusher); ok {
f.Flush()
}
return
}
// MarshalEventPayload marshals a SDK API shape into its associated wire
// protocol payload.
func MarshalEventPayload(
payloadMarshaler protocol.PayloadMarshaler,
v interface{},
) []byte {
var w bytes.Buffer
err := payloadMarshaler.MarshalPayload(&w, v)
if err != nil {
panic(fmt.Sprintf("failed to marshal event %T, %v, %v", v, v, err))
}
return w.Bytes()
}
// Prevent circular dependencies on eventstreamapi redefine these here.
const (
messageTypeHeader = `:message-type` // Identifies type of message.
eventMessageType = `event`
exceptionMessageType = `exception`
)
// EventMessageTypeHeader is an event message type header for specifying an
// event is an message type.
var EventMessageTypeHeader = eventstream.Header{
Name: messageTypeHeader,
Value: eventstream.StringValue(eventMessageType),
}
// EventExceptionTypeHeader is an event exception type header for specifying an
// event is an exception type.
var EventExceptionTypeHeader = eventstream.Header{
Name: messageTypeHeader,
Value: eventstream.StringValue(exceptionMessageType),
}