-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.go
More file actions
294 lines (257 loc) · 8.99 KB
/
Copy pathdriver.go
File metadata and controls
294 lines (257 loc) · 8.99 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
// Package openrtb facilitates the interaction with the OpenRTB (Real-Time Bidding) protocol,
// enabling real-time bidding requests and responses following OpenRTB standards.
//
// Features:
// - Request and Response Handling: Manages bid requests and responses for OpenRTB 2.x and 3.x.
// - Metrics and Logging: Integrates comprehensive metrics and logging using zap and prometheuswrapper.
// - Error Handling: Implements robust error handling and retry mechanisms.
// - Customizable Headers: Allows customization of HTTP request headers.
// - Rate Limiting: Supports RPS (Requests Per Second) limits to control request rates.
//
// The main component of the package is the `driver` struct which handles the lifecycle of a bid request,
// including preparation, execution, and response processing. It utilizes various supporting packages for
// logging, metrics, and HTTP client functionalities.
//
// Usage:
//
// Initialization:
// ctx := context.Background()
// source := &admodels.RTBSource{ /* initialize with source details */ }
// netClient := httpclient.New() // Or your custom HTTP client
//
// driver, err := newDriver(ctx, source, netClient)
// if err != nil {
// // handle error
// }
//
// Sending a Bid Request:
// request := &bidrequest.BidRequest{ /* initialize bid request */ }
// if err := driver.Test(request); err == nil {
// response := driver.Bid(request)
// // process response
// }
//
// Handling Metrics:
// metrics := driver.Metrics()
// // log or process metrics
//
// Functions:
// - newDriver: Initializes a new driver instance.
// - ID: Returns the ID of the source.
// - Protocol: Returns the protocol version.
// - Test: Tests if the request meets the criteria for processing.
// - PriceCorrectionReduceFactor: Returns the price correction reduce factor.
// - RequestStrategy: Returns the request strategy.
// - Bid: Processes a bid request and returns a response.
// - ProcessResponseItem: Processes individual response items.
// - RevenueShareReduceFactor: Returns the revenue share reduce factor.
// - Metrics: Returns platform
package adsourceopenrtb
import (
"context"
"sync/atomic"
"time"
"github.com/demdxx/gocast/v2"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/geniusrabbit/adcorelib/admodels"
"github.com/geniusrabbit/adcorelib/adquery/bidresponse"
"github.com/geniusrabbit/adcorelib/adtype"
"github.com/geniusrabbit/adcorelib/context/ctxlogger"
counter "github.com/geniusrabbit/adcorelib/errorcounter"
"github.com/geniusrabbit/adcorelib/errtype"
"github.com/geniusrabbit/adcorelib/eventtraking/events"
"github.com/geniusrabbit/adcorelib/eventtraking/eventstream"
"github.com/geniusrabbit/adcorelib/fasttime"
"github.com/geniusrabbit/adcorelib/openlatency"
"github.com/geniusrabbit/adcorelib/openlatency/prometheuswrapper"
"github.com/geniusrabbit/adsource-openrtb/response/requester"
"github.com/geniusrabbit/adsource-openrtb/sources"
)
const (
defaultMinWeight = 0.001
)
// RTBRequester wraps the execution of a single RTB server round-trip.
// It is re-exported from response/requester for convenience.
type RTBRequester = requester.RTBRequester
type driver struct {
lastRequestTime uint64
// Requests RPS counter
rpsCurrent counter.Counter
errorCounter counter.ErrorCounter
latencyMetrics *prometheuswrapper.Wrapper
// Original source model
source *admodels.RTBSource
sourceInfo *adtype.SourceInfo
// RTB source requester (performs actual HTTP call)
rtbRequester RTBRequester
}
func newDriver(_ context.Context, source *admodels.RTBSource, rtbRequester RTBRequester, _ ...any) (*driver, error) {
if source == nil {
return nil, ErrNilSource
}
if rtbRequester == nil {
return nil, ErrNilHTTPClient
}
source.MinimalWeight = max(source.MinimalWeight, defaultMinWeight)
sourceInfo := sources.Sources.SourceInfoByDSPDomain(source.Domain())
if sourceInfo != nil {
sourceInfo.ID = gocast.Str(source.ID)
sourceInfo.Protocol = source.Protocol
} else {
sourceInfo = &adtype.SourceInfo{
ID: gocast.Str(source.ID),
Protocol: source.Protocol,
}
}
return &driver{
source: source,
rtbRequester: rtbRequester,
sourceInfo: sourceInfo,
latencyMetrics: prometheuswrapper.NewWrapperDefault("adsource_",
[]string{"id", "protocol", "driver"},
[]string{gocast.Str(source.ID), source.Protocol, "openrtb"},
),
}, nil
}
// ID of source
func (d *driver) ID() uint64 { return d.source.ID }
// ObjectKey of source
func (d *driver) ObjectKey() uint64 { return d.source.ID }
// Protocol of source
func (d *driver) Protocol() string { return d.source.Protocol }
// Info returns information about the source platform and the source protocol
func (d *driver) Info() *adtype.SourceInfo {
return d.sourceInfo
}
// AccountID of source
func (d *driver) AccountID() uint64 {
if d.source.Account == nil {
return 0
}
return d.source.Account.ID()
}
var (
ErrNilRequest = errtype.Error("nil bid request")
ErrErrorCircuitOpen = errtype.Error("error circuit open")
ErrRPSLimitExceeded = errtype.Error("rps limit exceeded")
ErrTargetFilterRejected = errtype.Error("target filter rejected")
)
// Test request before processing.
// Returns a typed cause on rejection, or nil when the request may proceed.
func (d *driver) Test(request adtype.BidRequester) error {
if request == nil {
return ErrNilRequest
}
if d.source.RPS > 0 {
if d.source.Options.ErrorsIgnore == 0 && !d.errorCounter.Next() {
d.latencyMetrics.IncSkip()
return ErrErrorCircuitOpen
}
now := fasttime.UnixTimestampNano()
if now-atomic.LoadUint64(&d.lastRequestTime) >= uint64(time.Second) {
atomic.StoreUint64(&d.lastRequestTime, now)
d.rpsCurrent.Set(0)
} else if d.rpsCurrent.Get() >= int64(d.source.RPS) {
d.latencyMetrics.IncSkip()
return ErrRPSLimitExceeded
}
}
pointers := request.TargetPointers()
if len(pointers) == 0 {
return nil
}
var lastErr error
for _, pointer := range pointers {
err := d.source.Test(pointer)
if err == nil {
return nil
}
lastErr = err
}
d.latencyMetrics.IncSkip()
if lastErr != nil {
return lastErr
}
return ErrTargetFilterRejected
}
// PriceCorrectionReduceFactor which is a potential
// Returns percent from 0 to 1 for reducing of the value
// If there is 10% of price correction, it means that 10% of the final price must be ignored
func (d *driver) PriceCorrectionReduceFactor() float64 {
return d.source.PriceCorrectionReduceFactor()
}
// RequestStrategy description
func (d *driver) RequestStrategy() adtype.RequestStrategy {
return adtype.AsynchronousRequestStrategy
}
// Bid request for standart system filter
func (d *driver) Bid(request adtype.BidRequester) adtype.Response {
beginTime := fasttime.UnixTimestampNano()
d.rpsCurrent.Inc(1)
d.latencyMetrics.BeginQuery()
// Send request to source and get response
response, err := d.rtbRequester.Request(request, beginTime)
if err != nil {
if errors.Is(err, ErrResponseNoBid) {
// No bid is not an error, so we just return empty response
response = bidresponse.NewEmptyResponse(request, d, err)
} else {
response = adtype.NewErrorResponse(request, err)
ctxlogger.Get(request.Context()).Error("bid", zap.Error(err))
}
}
// Update metrics based on response
// Success if there are ads in the response and no error; NoBid if no ads but also no error; otherwise, it's an error case
if response != nil && response.Error() == nil {
if len(response.Ads()) > 0 {
d.latencyMetrics.IncSuccess()
} else {
d.latencyMetrics.IncNobid()
}
}
if response == nil {
response = bidresponse.NewEmptyResponse(request, d, err)
}
return response
}
// ProcessResponseItem result or error
func (d *driver) ProcessResponseItem(response adtype.Response, item adtype.ResponseItem) {
if response == nil || response.Error() != nil {
return
}
ctxl := response.Context()
// Send win notification if NotifyWinURL is set in the bid content and the bid is a winner.
if nurl := item.ContentItemString(adtype.ContentItemNotifyWinURL); nurl != "" {
if prep := adtype.ContentMappingPreparer(response, item); prep != nil {
nurl = prep.Replace(nurl)
}
ctxlogger.Get(ctxl).Info("ping", zap.String("url", nurl))
err := eventstream.WinsFromContext(ctxl).Send(ctxl, nurl)
if err != nil {
ctxlogger.Get(ctxl).Error("ping error", zap.Error(err))
}
}
// Send win event to event stream for tracking
err := eventstream.StreamFromContext(ctxl).
Send(events.SourceWin, events.StatusUndefined, response, item)
if err != nil {
ctxlogger.Get(ctxl).Error("send win event", zap.Error(err))
}
}
// Weight of the source
func (d *driver) Weight() float64 {
return d.source.MinimalWeight
}
///////////////////////////////////////////////////////////////////////////////
/// Implementation of platform.Metrics interface
///////////////////////////////////////////////////////////////////////////////
// Metrics information of the platform
func (d *driver) Metrics() *openlatency.MetricsInfo {
var info openlatency.MetricsInfo
d.latencyMetrics.FillMetrics(&info)
info.ID = d.ID()
info.Protocol = d.source.Protocol
info.QPSLimit = d.source.RPS
return &info
}