-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
recorder.go
510 lines (450 loc) · 16 KB
/
recorder.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// Copyright (c) 2015-2022 Marin Atanasov Nikolov <dnaeon@gmail.com>
// Copyright (c) 2016 David Jack <davars@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer
// in this position and unchanged.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package recorder
import (
"bufio"
"bytes"
"errors"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"os"
"time"
"gopkg.in/dnaeon/go-vcr.v3/cassette"
)
// Mode represents the mode of operation of the recorder
type Mode int
// Recorder states
const (
// ModeRecordOnly specifies that VCR will run in recording
// mode only. HTTP interactions will be recorded for each
// interaction. If the cassette file is present, it will be
// overwritten.
ModeRecordOnly Mode = iota
// ModeReplayOnly specifies that VCR will only replay
// interactions from previously recorded cassette. If an
// interaction is missing from the cassette it will return
// ErrInteractionNotFound error. If the cassette file is
// missing it will return ErrCassetteNotFound error.
ModeReplayOnly
// ModeReplayWithNewEpisodes starts the recorder in replay
// mode, where existing interactions are returned from the
// cassette, and missing ones will be recorded and added to
// the cassette. This mode is useful in cases where you need
// to update an existing cassette with new interactions, but
// don't want to wipe out previously recorded interactions.
// If the cassette file is missing it will create a new one.
ModeReplayWithNewEpisodes
// ModeRecordOnce will record new HTTP interactions once only.
// This mode is useful in cases where you need to record a set
// of interactions once only and replay only the known
// interactions. Unknown/missing interactions will cause the
// recorder to return an ErrInteractionNotFound error. If the
// cassette file is missing, it will be created.
ModeRecordOnce
// ModePassthrough specifies that VCR will not record any
// interactions at all. In this mode all HTTP requests will be
// forwarded to the endpoints using the real HTTP transport.
// In this mode no cassette will be created.
ModePassthrough
)
// ErrInvalidMode is returned when attempting to start the recorder
// with invalid mode
var ErrInvalidMode = errors.New("invalid recorder mode")
// FilterFunc represents a function, which allows modification of an
// interaction before being added to the cassette
type FilterFunc func(i *cassette.Interaction) error
// PassthroughFunc is handler which determines whether a specific HTTP
// request is to be forwarded to the original endpoint. It should
// return true when a request needs to be passed through, and false
// otherwise.
type PassthroughFunc func(req *http.Request) bool
// Option represents the Recorder options
type Options struct {
// CassetteName is the name of the cassette
CassetteName string
// Mode is the operating mode of the Recorder
Mode Mode
// RealTransport is the underlying http.RoundTripper to make
// the real requests
RealTransport http.RoundTripper
// SkipRequestLatency, if set to true will not simulate the
// latency of the recorded interaction. When set to false
// (default) it will block for the period of time taken by the
// original request to simulate the latency between our
// recorder and the remote endpoints.
SkipRequestLatency bool
}
// Recorder represents a type used to record and replay
// client and server interactions
type Recorder struct {
// Cassette used by the recorder
cassette *cassette.Cassette
// Recorder options
options *Options
// Passthrough handlers
passthroughs []PassthroughFunc
// filters is a set of FilterFunc handlers, which are invoked
// before the interaction is added to the cassette. The
// interaction is still in-memory and not persisted on
// disk. These filters are different than the PreSaveFilters,
// which are invoked right before persisting the cassette on
// disk.
filters []FilterFunc
// preSaveFilters are applied to interactions just before they
// are saved on disk. These are different than the Filters,
// which are usually applied to the interactions before they
// are added to the cassette, which is still in-memory.
preSaveFilters []FilterFunc
}
// New creates a new recorder
func New(cassetteName string) (*Recorder, error) {
opts := &Options{
CassetteName: cassetteName,
Mode: ModeRecordOnce,
SkipRequestLatency: false,
RealTransport: http.DefaultTransport,
}
return NewWithOptions(opts)
}
// NewWithOptions creates a new recorder based on the provided options
func NewWithOptions(opts *Options) (*Recorder, error) {
if opts.RealTransport == nil {
opts.RealTransport = http.DefaultTransport
}
rec := &Recorder{
options: opts,
passthroughs: make([]PassthroughFunc, 0),
filters: make([]FilterFunc, 0),
preSaveFilters: make([]FilterFunc, 0),
}
cassetteFile := cassette.New(opts.CassetteName).File
_, err := os.Stat(cassetteFile)
cassetteExists := !os.IsNotExist(err)
switch {
case opts.Mode == ModeRecordOnly:
c := cassette.New(opts.CassetteName)
rec.cassette = c
return rec, nil
case opts.Mode == ModeReplayOnly && !cassetteExists:
return nil, cassette.ErrCassetteNotFound
case opts.Mode == ModeReplayOnly && cassetteExists:
c, err := cassette.Load(opts.CassetteName)
if err != nil {
return nil, err
}
rec.cassette = c
return rec, nil
case opts.Mode == ModeReplayWithNewEpisodes && !cassetteExists:
c := cassette.New(opts.CassetteName)
rec.cassette = c
return rec, nil
case opts.Mode == ModeReplayWithNewEpisodes && cassetteExists:
c, err := cassette.Load(opts.CassetteName)
if err != nil {
return nil, err
}
rec.cassette = c
return rec, nil
case opts.Mode == ModeRecordOnce && !cassetteExists:
c := cassette.New(opts.CassetteName)
rec.cassette = c
return rec, nil
case opts.Mode == ModeRecordOnce && cassetteExists:
c, err := cassette.Load(opts.CassetteName)
if err != nil {
return nil, err
}
rec.cassette = c
return rec, nil
case opts.Mode == ModePassthrough:
c := cassette.New(opts.CassetteName)
rec.cassette = c
return rec, nil
default:
return nil, ErrInvalidMode
}
}
// Proxies client requests to their original destination
func (rec *Recorder) requestHandler(r *http.Request) (*cassette.Interaction, error) {
if err := r.Context().Err(); err != nil {
return nil, err
}
switch {
case rec.options.Mode == ModeReplayOnly:
return rec.cassette.GetInteraction(r)
case rec.options.Mode == ModeReplayWithNewEpisodes:
interaction, err := rec.cassette.GetInteraction(r)
if err == nil {
// Interaction found, return it
return interaction, nil
} else if err == cassette.ErrInteractionNotFound {
// Interaction not found, we have a new episode
break
} else {
// Any other error is an error
return nil, err
}
case rec.options.Mode == ModeRecordOnce && !rec.cassette.IsNew:
// We've got an existing cassette, return what we've got
return rec.cassette.GetInteraction(r)
case rec.options.Mode == ModePassthrough:
// Passthrough requests always hit the original endpoint
break
case (rec.options.Mode == ModeRecordOnly || rec.options.Mode == ModeRecordOnce) && rec.cassette.ReplayableInteractions:
// When running with replayable interactions look for
// existing interaction first, so we avoid hitting
// multiple times the same endpoint.
interaction, err := rec.cassette.GetInteraction(r)
if err == nil {
// Interaction found, return it
return interaction, nil
} else if err == cassette.ErrInteractionNotFound {
// Interaction not found, we have to record it
break
} else {
// Any other error is an error
return nil, err
}
default:
// Anything else hits the original endpoint
break
}
// Copy the original request, so we can read the form values
reqBytes, err := httputil.DumpRequestOut(r, true)
if err != nil {
return nil, err
}
reqBuffer := bytes.NewBuffer(reqBytes)
copiedReq, err := http.ReadRequest(bufio.NewReader(reqBuffer))
if err != nil {
return nil, err
}
err = copiedReq.ParseForm()
if err != nil {
return nil, err
}
reqBody := &bytes.Buffer{}
if r.Body != nil && r.Body != http.NoBody {
// Record the request body so we can add it to the cassette
r.Body = io.NopCloser(io.TeeReader(r.Body, reqBody))
}
// Perform request to it's original destination and record the interactions
var start time.Time
start = time.Now()
resp, err := rec.options.RealTransport.RoundTrip(r)
if err != nil {
return nil, err
}
requestDuration := time.Since(start)
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Add interaction to the cassette
interaction := &cassette.Interaction{
Request: cassette.Request{
Proto: r.Proto,
ProtoMajor: r.ProtoMajor,
ProtoMinor: r.ProtoMinor,
ContentLength: r.ContentLength,
TransferEncoding: r.TransferEncoding,
Trailer: r.Trailer,
Host: r.Host,
RemoteAddr: r.RemoteAddr,
RequestURI: r.RequestURI,
Body: reqBody.String(),
Form: copiedReq.PostForm,
Headers: r.Header,
URL: r.URL.String(),
Method: r.Method,
},
Response: cassette.Response{
Status: resp.Status,
Code: resp.StatusCode,
Proto: resp.Proto,
ProtoMajor: resp.ProtoMajor,
ProtoMinor: resp.ProtoMinor,
TransferEncoding: resp.TransferEncoding,
Trailer: resp.Trailer,
ContentLength: resp.ContentLength,
Uncompressed: resp.Uncompressed,
Body: string(respBody),
Headers: resp.Header,
Duration: requestDuration,
},
}
// Apply filters before adding them to the in-memory cassette
for _, filter := range rec.filters {
err = filter(interaction)
if err != nil {
return nil, err
}
}
rec.cassette.AddInteraction(interaction)
return interaction, nil
}
// Stop is used to stop the recorder and save any recorded
// interactions if running in one of the recording modes. When
// running in ModePassthrough no cassette will be saved on disk.
func (rec *Recorder) Stop() error {
cassetteFile := rec.cassette.File
_, err := os.Stat(cassetteFile)
cassetteExists := !os.IsNotExist(err)
switch {
case rec.options.Mode == ModeRecordOnly || rec.options.Mode == ModeReplayWithNewEpisodes:
return rec.persistCassette()
case rec.options.Mode == ModeReplayOnly || rec.options.Mode == ModePassthrough:
return nil
case rec.options.Mode == ModeRecordOnce && !cassetteExists:
return rec.persistCassette()
default:
return nil
}
}
// persisteCassette persists the cassette on disk for future re-use
func (rec *Recorder) persistCassette() error {
// Apply any pre-save filters
for _, interaction := range rec.cassette.Interactions {
for _, filter := range rec.preSaveFilters {
if err := filter(interaction); err != nil {
return err
}
}
}
return rec.cassette.Save()
}
// SetRealTransport can be used to configure the real HTTP transport
// of the recorder.
func (rec *Recorder) SetRealTransport(t http.RoundTripper) {
rec.options.RealTransport = t
}
// RoundTrip implements the http.RoundTripper interface
func (rec *Recorder) RoundTrip(req *http.Request) (*http.Response, error) {
// Passthrough mode, use real transport
if rec.options.Mode == ModePassthrough {
return rec.options.RealTransport.RoundTrip(req)
}
// Apply passthrough handler functions
for _, passthroughFunc := range rec.passthroughs {
if passthroughFunc(req) {
return rec.options.RealTransport.RoundTrip(req)
}
}
interaction, err := rec.requestHandler(req)
if err != nil {
return nil, err
}
select {
case <-req.Context().Done():
return nil, req.Context().Err()
default:
// Apply the duration defined in the interaction
if !rec.options.SkipRequestLatency {
<-time.After(interaction.Response.Duration)
}
return interaction.GetHTTPResponse()
}
}
// CancelRequest implements the
// github.com/coreos/etcd/client.CancelableTransport interface
func (rec *Recorder) CancelRequest(req *http.Request) {
type cancelableTransport interface {
CancelRequest(req *http.Request)
}
if ct, ok := rec.options.RealTransport.(cancelableTransport); ok {
ct.CancelRequest(req)
}
}
// SetMatcher sets a function to match requests against recorded HTTP
// interactions.
func (rec *Recorder) SetMatcher(matcher cassette.MatcherFunc) {
rec.cassette.Matcher = matcher
}
// SetReplayableInteractions defines whether to allow interactions to
// be replayed or not. This is useful in cases when you need to hit
// the same endpoint multiple times and want to replay the interaction
// from the cassette, instead of hiting the endpoint.
func (rec *Recorder) SetReplayableInteractions(replayable bool) {
rec.cassette.ReplayableInteractions = replayable
}
// AddPassthrough appends a hook to determine if a request should be
// ignored by the recorder.
func (rec *Recorder) AddPassthrough(pass PassthroughFunc) {
rec.passthroughs = append(rec.passthroughs, pass)
}
// AddFilter appends a hook to modify an interaction before it is
// added to the cassette. Note, that the cassette is not yet saved on
// disk, but the interaction is only added to the in-memory cassette.
func (rec *Recorder) AddFilter(filter FilterFunc) {
rec.filters = append(rec.filters, filter)
}
// AddPreSaveFilter appends a hook to modify an interaction just
// before the cassette is saved on disk.
func (rec *Recorder) AddPreSaveFilter(filter FilterFunc) {
rec.preSaveFilters = append(rec.preSaveFilters, filter)
}
// Mode returns recorder state
func (rec *Recorder) Mode() Mode {
return rec.options.Mode
}
// GetDefaultClient returns an HTTP client with a pre-configured
// transport
func (rec *Recorder) GetDefaultClient() *http.Client {
client := &http.Client{
Transport: rec,
}
return client
}
// IsNewCassette returns true, if the recorder was started with a
// new/empty cassette. Returns false, if it was started using an
// existing cassette, which was loaded.
func (rec *Recorder) IsNewCassette() bool {
return rec.cassette.IsNew
}
// IsRecording returns true, if the recorder is recording
// interactions, returns false otherwise. Note, that in some modes
// (e.g. ModeReplayWithNewEpisodes and ModeRecordOnce) the recorder
// might be recording new interactions. For example in ModeRecordOnce,
// we are replaying interactions only if there was an existing
// cassette, and we are recording it, if the cassette is a new one.
// ModeReplayWithNewEpisodes would replay interactions, if they are
// present in the cassette, but will also record new ones, if they are
// not part of the cassette already. In these cases the recorder is
// considered to be recording for these modes.
func (rec *Recorder) IsRecording() bool {
switch {
case rec.options.Mode == ModeRecordOnly || rec.options.Mode == ModeReplayWithNewEpisodes:
return true
case rec.options.Mode == ModeReplayOnly || rec.options.Mode == ModePassthrough:
return false
case rec.options.Mode == ModeRecordOnce && rec.IsNewCassette():
return true
default:
return false
}
}