-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathclient.go
More file actions
366 lines (317 loc) · 10.6 KB
/
Copy pathclient.go
File metadata and controls
366 lines (317 loc) · 10.6 KB
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
/****************************************************************************
* Copyright 2025, Optimizely, Inc. and contributors *
* *
* 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 cmab provides CMAB client implementation
package cmab
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"time"
"github.com/optimizely/go-sdk/v2/pkg/config"
"github.com/optimizely/go-sdk/v2/pkg/entities"
"github.com/optimizely/go-sdk/v2/pkg/event"
"github.com/optimizely/go-sdk/v2/pkg/logging"
)
// CMABPredictionEndpoint is the endpoint for CMAB predictions
var CMABPredictionEndpoint = "https://prediction.cmab.optimizely.com/predict/%s"
const (
// DefaultMaxRetries is the default number of retries for CMAB requests
DefaultMaxRetries = 3
// DefaultInitialBackoff is the default initial backoff duration
DefaultInitialBackoff = 100 * time.Millisecond
// DefaultMaxBackoff is the default maximum backoff duration
DefaultMaxBackoff = 10 * time.Second
// DefaultBackoffMultiplier is the default multiplier for exponential backoff
DefaultBackoffMultiplier = 2.0
)
// Attribute represents an attribute in a CMAB request
type Attribute struct {
ID string `json:"id"`
Value interface{} `json:"value"`
Type string `json:"type"`
}
// Instance represents an instance in a CMAB request
type Instance struct {
VisitorID string `json:"visitorId"`
ExperimentID string `json:"experimentId"`
Attributes []Attribute `json:"attributes"`
CmabUUID string `json:"cmabUUID"`
}
// Request represents a request to the CMAB API
type Request struct {
Instances []Instance `json:"instances"`
}
// Prediction represents a prediction in a CMAB response
type Prediction struct {
VariationID string `json:"variation_id"`
}
// Response represents a response from the CMAB API
type Response struct {
Predictions []Prediction `json:"predictions"`
}
// RetryConfig defines configuration for retry behavior
type RetryConfig struct {
// MaxRetries is the maximum number of retry attempts
MaxRetries int
// InitialBackoff is the initial backoff duration
InitialBackoff time.Duration
// MaxBackoff is the maximum backoff duration
MaxBackoff time.Duration
// BackoffMultiplier is the multiplier for exponential backoff
BackoffMultiplier float64
}
// DefaultCmabClient implements the CmabClient interface
type DefaultCmabClient struct {
httpClient *http.Client
retryConfig *RetryConfig
logger logging.OptimizelyLogProducer
eventProcessor event.Processor
projectConfig config.ProjectConfig
}
// ClientOptions defines options for creating a CMAB client
type ClientOptions struct {
HTTPClient *http.Client
RetryConfig *RetryConfig
Logger logging.OptimizelyLogProducer
EventProcessor event.Processor
ProjectConfig config.ProjectConfig
}
// NewDefaultCmabClient creates a new instance of DefaultCmabClient
func NewDefaultCmabClient(options ClientOptions) *DefaultCmabClient {
httpClient := options.HTTPClient
if httpClient == nil {
httpClient = &http.Client{
Timeout: 10 * time.Second,
}
}
// retry is optional:
// retryConfig can be nil - in that case, no retries will be performed
retryConfig := options.RetryConfig
logger := options.Logger
if logger == nil {
logger = logging.GetLogger("", "DefaultCmabClient")
}
return &DefaultCmabClient{
httpClient: httpClient,
retryConfig: retryConfig,
logger: logger,
eventProcessor: options.EventProcessor,
projectConfig: options.ProjectConfig,
}
}
// FetchDecision fetches a decision from the CMAB API
func (c *DefaultCmabClient) FetchDecision(
ctx context.Context,
ruleID string,
userID string,
attributes map[string]interface{},
cmabUUID string,
) (string, error) {
// If no context is provided, create a background context
if ctx == nil {
ctx = context.Background()
}
// Create the URL
url := fmt.Sprintf(CMABPredictionEndpoint, ruleID)
// Convert attributes to CMAB format
cmabAttributes := make([]Attribute, 0, len(attributes))
for key, value := range attributes {
cmabAttributes = append(cmabAttributes, Attribute{
ID: key,
Value: value,
Type: "custom_attribute",
})
}
// Create the request body
requestBody := Request{
Instances: []Instance{
{
VisitorID: userID,
ExperimentID: ruleID,
Attributes: cmabAttributes,
CmabUUID: cmabUUID,
},
},
}
// Serialize the request body
bodyBytes, err := json.Marshal(requestBody)
if err != nil {
return "", fmt.Errorf("failed to marshal CMAB request: %w", err)
}
// If no retry config, just do a single fetch
if c.retryConfig == nil {
return c.doFetch(ctx, url, bodyBytes)
}
// Retry sending request with exponential backoff
for i := 0; i <= c.retryConfig.MaxRetries; i++ {
// Check if context is done
if ctx.Err() != nil {
return "", fmt.Errorf("context canceled or timed out: %w", ctx.Err())
}
// Make the request
result, err := c.doFetch(ctx, url, bodyBytes)
if err == nil {
return result, nil
}
// If this is the last retry, return the error
if i == c.retryConfig.MaxRetries {
return "", fmt.Errorf("failed to fetch CMAB decision after %d attempts: %w",
c.retryConfig.MaxRetries, err)
}
// Calculate backoff duration
backoffDuration := c.retryConfig.InitialBackoff * time.Duration(math.Pow(c.retryConfig.BackoffMultiplier, float64(i)))
if backoffDuration > c.retryConfig.MaxBackoff {
backoffDuration = c.retryConfig.MaxBackoff
}
c.logger.Debug(fmt.Sprintf("CMAB request retry %d/%d, backing off for %v",
i+1, c.retryConfig.MaxRetries, backoffDuration))
// Wait for backoff duration with context awareness
select {
case <-ctx.Done():
return "", fmt.Errorf("context canceled or timed out during backoff: %w", ctx.Err())
case <-time.After(backoffDuration):
// Continue with retry
}
c.logger.Warning(fmt.Sprintf("CMAB API request failed (attempt %d/%d): %v",
i+1, c.retryConfig.MaxRetries, err))
}
// This should never be reached due to the return in the loop above
return "", fmt.Errorf("unexpected error in retry loop")
}
// doFetch performs a single fetch operation to the CMAB API
func (c *DefaultCmabClient) doFetch(ctx context.Context, url string, bodyBytes []byte) (string, error) {
// Create the request
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(bodyBytes))
if err != nil {
return "", fmt.Errorf("failed to create CMAB request: %w", err)
}
// Set headers
req.Header.Set("Content-Type", "application/json")
// Execute the request
resp, err := c.httpClient.Do(req)
if err != nil {
return "", fmt.Errorf("CMAB request failed: %w", err)
}
defer resp.Body.Close()
// Check status code
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return "", fmt.Errorf("CMAB API returned non-success status code: %d", resp.StatusCode)
}
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read CMAB response body: %w", err)
}
// Parse response
var cmabResponse Response
if err := json.Unmarshal(respBody, &cmabResponse); err != nil {
return "", fmt.Errorf("failed to unmarshal CMAB response: %w", err)
}
// Validate response
if !c.validateResponse(cmabResponse) {
return "", fmt.Errorf("invalid CMAB response: missing predictions or variation_id")
}
// Return the variation ID
return cmabResponse.Predictions[0].VariationID, nil
}
// validateResponse validates the CMAB response
func (c *DefaultCmabClient) validateResponse(response Response) bool {
return len(response.Predictions) > 0 && response.Predictions[0].VariationID != ""
}
// EventProcessor is an interface for processing events
type EventProcessor interface {
Process(userEvent interface{}) bool
}
// LogImpression logs a CMAB impression event
func (c *DefaultCmabClient) LogImpression(
ctx context.Context,
eventProcessor EventProcessor,
projectConfig config.ProjectConfig,
ruleID string,
userID string,
variationKey string,
variationID string,
attributes map[string]interface{},
cmabUUID string,
) error {
// Instead of directly creating an event, we'll delegate this to the client
// that has access to the event package
return fmt.Errorf("CMAB impression logging not implemented")
}
// TrackCMABDecision tracks a CMAB decision event
func (c *DefaultCmabClient) TrackCMABDecision(
ruleID string,
userID string,
variationID string,
variationKey string,
attributes map[string]interface{},
cmabUUID string,
) {
if c.eventProcessor == nil || c.projectConfig == nil {
c.logger.Debug("Event processor or project config not available, not tracking impression")
return
}
// Get experiment from project config
experiment, err := c.projectConfig.GetExperimentByID(ruleID)
if err != nil {
c.logger.Error("Error getting experiment", err)
return
}
// Create variation object
variation := entities.Variation{
ID: variationID,
Key: variationKey,
}
// Create user context
userContext := entities.UserContext{
ID: userID,
Attributes: attributes,
}
// Look for associated feature flag (if any)
flagKey := ""
featureList := c.projectConfig.GetFeatureList()
for _, feature := range featureList {
for _, featureExperiment := range feature.FeatureExperiments {
if featureExperiment.ID == ruleID {
flagKey = feature.Key
break
}
}
if flagKey != "" {
break
}
}
// Create user event with CMAB impression
userEvent, shouldDispatch := event.CreateCMABImpressionUserEvent(
c.projectConfig,
experiment,
&variation,
userContext,
flagKey,
experiment.Key, // ruleKey
"experiment", // ruleType
true,
cmabUUID,
)
// Process the event if it should be dispatched
if shouldDispatch {
c.eventProcessor.ProcessEvent(userEvent)
}
}