-
Notifications
You must be signed in to change notification settings - Fork 3
/
package.go
318 lines (288 loc) · 9.53 KB
/
package.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
// Copyright 2023 Cisco Systems, Inc. and its affiliates
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
package opensearchtest
import (
"context"
"github.com/cisco-open/go-lanai/pkg/opensearch"
"github.com/cisco-open/go-lanai/pkg/utils/order"
"github.com/cisco-open/go-lanai/test"
"github.com/cisco-open/go-lanai/test/apptest"
"github.com/cockroachdb/copyist"
opensearchgo "github.com/opensearch-project/opensearch-go"
"github.com/opensearch-project/opensearch-go/opensearchapi"
"github.com/opensearch-project/opensearch-go/opensearchutil"
"go.uber.org/fx"
"gopkg.in/dnaeon/go-vcr.v3/recorder"
"net/http"
"testing"
"time"
)
// IndexSuffix is the suffix we append to the index name when running opensearch tests, so that we don't
// corrupt the application's indices.
const IndexSuffix = "_test"
// IsRecording returns true if copyist is currently in recording mode.
// We wrap the copyist.IsRecording because we re-use the same commandline flag
// as the copyist library, and flag.Bool doesn't like it when you have two places
// that listen to the same flag
func IsRecording() bool {
return copyist.IsRecording()
}
type Options func(opt *Option)
type Option struct {
Name string
SavePath string
Mode Mode
RealTransport http.RoundTripper
SkipRequestLatency bool
FuzzyJsonPaths []string
RecordDelay time.Duration
}
// SetRecordDelay add delay between each request.
// Note: original request latency is applied by default. This is the additional delay between each requests
func SetRecordDelay(delay time.Duration) Options {
return func(opt *Option) {
SkipRequestLatency(false)(opt)
opt.RecordDelay = delay
}
}
func SetRecordMode(mode Mode) Options {
return func(o *Option) {
o.Mode = mode
}
}
// SkipRequestLatency disable mimic request latency in playback mode. Has no effect during recording
// By default, original request latency during recording is applied in playback mode.
func SkipRequestLatency(skip bool) Options {
return func(o *Option) {
o.SkipRequestLatency = skip
}
}
// ReplayMode override recording/playback mode. Default is ModeCommandline
func ReplayMode(mode Mode) Options {
return func(o *Option) {
o.Mode = mode
}
}
// FuzzyJsonPaths ignore part of JSON body with JSONPath notation during playback mode.
// Useful for search queries with time-sensitive fields
// e.g. FuzzyJsonPaths("$.query.*.Time")
// JSONPath Syntax: https://goessner.net/articles/JsonPath/
func FuzzyJsonPaths(jsonPaths...string) Options {
return func(o *Option) {
o.FuzzyJsonPaths = append(o.FuzzyJsonPaths, jsonPaths...)
}
}
// WithOpenSearchPlayback will setup the recorder, similar to crdb's copyist functionality
// where actual interactions with opensearch will be recorded, and then when the mode is set to
// ModeReplaying, the recorder will respond with its recorded responses.
// the parameter recordDelay defines how long of a delay is needed between a write to
// opensearch, and a read. opensearch does not immediately have writes available, so the only
// solution right now is to delay and reads that happen immediately after a write.
// For some reason, the refresh options on the index to opensearch are not working.
//
// To control what is being matched in the http vcr, this function will provide a
// *MatcherBodyModifiers to uber.FX.
func WithOpenSearchPlayback(options ...Options) test.Options {
openSearchOption := Option {
Mode: ModeCommandline,
}
for _, fn := range options {
fn(&openSearchOption)
}
//var modifiers MatcherBodyModifiers
//openSearchOption.RecordOptions = append(
// openSearchOption.RecordOptions,
// func(c *RecordOption) {
// c.Modifiers = &modifiers
// },
//)
var rec *recorder.Recorder
testOpts := []test.Options{
test.Setup(
startRecording(&rec, options...),
),
apptest.WithFxOptions(
fx.Decorate(func(c opensearchgo.Config) opensearchgo.Config {
c.Transport = rec
return c
}),
fx.Provide(
IndexEditHookProvider(opensearch.FxGroup),
//func() *MatcherBodyModifiers { return &MatcherBodyModifiers{} },
),
),
test.Teardown(stopRecording()),
}
if openSearchOption.Mode == ModeRecording || openSearchOption.Mode == ModeCommandline && IsRecording(){
testOpts = append(testOpts, apptest.WithFxOptions(
fx.Provide(SearchDelayerHookProvider(opensearch.FxGroup, openSearchOption.RecordDelay)),
))
}
return test.WithOptions(testOpts...)
}
func startRecording(recRef **recorder.Recorder, options ...Options) test.SetupFunc {
return func(ctx context.Context, t *testing.T) (context.Context, error) {
initial := func(c *Option) {
c.Mode = ModeCommandline
c.Name = t.Name()
c.SavePath = "testdata"
}
opts := append([]Options{initial}, options...)
var err error
*recRef, err = NewRecorder(opts...)
return contextWithRecorder(ctx, *recRef), err
}
}
func stopRecording() test.TeardownFunc {
return func(ctx context.Context, t *testing.T) error {
if rec, ok := ctx.Value(ckRecorder{}).(*recorder.Recorder); ok {
return rec.Stop()
}
return nil
}
}
// SearchDelayer will ensure that all searches that happen after inserting a document
// will have a delay so that the search can find all the documents.
type SearchDelayer struct {
Delay time.Duration
lastEvent opensearch.CommandType
}
func (s *SearchDelayer) Before(ctx context.Context, beforeContext opensearch.BeforeContext) context.Context {
if beforeContext.CommandType() == opensearch.CmdSearch && s.lastEvent == opensearch.CmdIndex {
time.Sleep(s.Delay)
}
return ctx
}
func (s *SearchDelayer) After(ctx context.Context, afterContext opensearch.AfterContext) context.Context {
s.lastEvent = afterContext.CommandType()
return ctx
}
func SearchDelayerHook(delay time.Duration) *SearchDelayer {
return &SearchDelayer{Delay: delay}
}
func SearchDelayerHookProvider(group string, delay time.Duration) (fx.Annotated, fx.Annotated) {
searchDelayer := SearchDelayerHook(delay)
return fx.Annotated{
Group: group, Target: func() opensearch.BeforeHook { return searchDelayer },
},
fx.Annotated{
Group: group, Target: func() opensearch.AfterHook { return searchDelayer },
}
}
type EditIndexForTestingHook struct {
Suffix string
}
func (e *EditIndexForTestingHook) Order() int {
return order.Highest
}
func NewEditingIndexForTestingHook() opensearch.BeforeHook {
return &EditIndexForTestingHook{
Suffix: IndexSuffix,
}
}
func (e *EditIndexForTestingHook) Before(ctx context.Context, before opensearch.BeforeContext) context.Context {
switch opt := before.Options.(type) {
case *[]func(request *opensearchapi.SearchRequest):
f := func(request *opensearchapi.SearchRequest) {
var indices []string
for _, index := range request.Index {
indices = append(indices, index+e.Suffix)
}
request.Index = indices
}
*opt = append(*opt, f)
case *[]func(request *opensearchapi.IndicesCreateRequest):
f := func(request *opensearchapi.IndicesCreateRequest) {
request.Index = request.Index + e.Suffix
}
*opt = append(*opt, f)
case *[]func(request *opensearchapi.IndexRequest):
f := func(request *opensearchapi.IndexRequest) {
request.Index = request.Index + e.Suffix
}
*opt = append(*opt, f)
case *[]func(request *opensearchapi.IndicesPutAliasRequest):
f := func(request *opensearchapi.IndicesPutAliasRequest) {
var indices []string
for _, index := range request.Index {
indices = append(indices, index+e.Suffix)
}
request.Index = indices
}
*opt = append(*opt, f)
case *[]func(request *opensearchapi.IndicesDeleteAliasRequest):
f := func(request *opensearchapi.IndicesDeleteAliasRequest) {
var indices []string
for _, index := range request.Index {
indices = append(indices, index+e.Suffix)
}
request.Index = indices
}
*opt = append(*opt, f)
case *[]func(request *opensearchapi.IndicesDeleteRequest):
f := func(request *opensearchapi.IndicesDeleteRequest) {
var indices []string
for _, index := range request.Index {
indices = append(indices, index+e.Suffix)
}
request.Index = indices
}
*opt = append(*opt, f)
case *[]func(cfg *opensearchutil.BulkIndexerConfig):
f := func(cfg *opensearchutil.BulkIndexerConfig) {
cfg.Index = cfg.Index + e.Suffix
}
*opt = append(*opt, f)
case *[]func(request *opensearchapi.SearchTemplateRequest):
f := func(request *opensearchapi.SearchTemplateRequest) {
var indices []string
for _, index := range request.Index {
indices = append(indices, index+e.Suffix)
}
request.Index = indices
}
*opt = append(*opt, f)
}
return ctx
}
func IndexEditHookProvider(group string) fx.Annotated {
return fx.Annotated{
Group: group,
Target: NewEditingIndexForTestingHook,
}
}
/******************
Context
******************/
type ckRecorder struct{}
type recorderContext struct {
context.Context
rec *recorder.Recorder
}
func (c recorderContext) Value(k interface{}) interface{} {
switch k {
case ckRecorder{}:
return c.rec
default:
return c.Context.Value(k)
}
}
func contextWithRecorder(parent context.Context, rec *recorder.Recorder) context.Context {
return recorderContext{
Context: parent,
rec: rec,
}
}