-
Notifications
You must be signed in to change notification settings - Fork 749
/
exchange.go
1624 lines (1422 loc) · 59 KB
/
exchange.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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package exchange
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net/url"
"runtime/debug"
"sort"
"strconv"
"strings"
"time"
"github.com/prebid/prebid-server/v3/ortb"
"github.com/prebid/prebid-server/v3/privacy"
"github.com/prebid/prebid-server/v3/adapters"
"github.com/prebid/prebid-server/v3/adservertargeting"
"github.com/prebid/prebid-server/v3/bidadjustment"
"github.com/prebid/prebid-server/v3/config"
"github.com/prebid/prebid-server/v3/currency"
"github.com/prebid/prebid-server/v3/dsa"
"github.com/prebid/prebid-server/v3/errortypes"
"github.com/prebid/prebid-server/v3/exchange/entities"
"github.com/prebid/prebid-server/v3/experiment/adscert"
"github.com/prebid/prebid-server/v3/firstpartydata"
"github.com/prebid/prebid-server/v3/floors"
"github.com/prebid/prebid-server/v3/gdpr"
"github.com/prebid/prebid-server/v3/hooks/hookexecution"
"github.com/prebid/prebid-server/v3/macros"
"github.com/prebid/prebid-server/v3/metrics"
"github.com/prebid/prebid-server/v3/openrtb_ext"
"github.com/prebid/prebid-server/v3/prebid_cache_client"
"github.com/prebid/prebid-server/v3/stored_requests"
"github.com/prebid/prebid-server/v3/stored_responses"
"github.com/prebid/prebid-server/v3/usersync"
"github.com/prebid/prebid-server/v3/util/jsonutil"
"github.com/prebid/prebid-server/v3/util/maputil"
"github.com/buger/jsonparser"
"github.com/gofrs/uuid"
"github.com/golang/glog"
"github.com/prebid/openrtb/v20/openrtb2"
"github.com/prebid/openrtb/v20/openrtb3"
)
type extCacheInstructions struct {
cacheBids, cacheVAST, returnCreative bool
}
// Exchange runs Auctions. Implementations must be threadsafe, and will be shared across many goroutines.
type Exchange interface {
// HoldAuction executes an OpenRTB v2.5 Auction.
HoldAuction(ctx context.Context, r *AuctionRequest, debugLog *DebugLog) (*AuctionResponse, error)
}
// IdFetcher can find the user's ID for a specific Bidder.
type IdFetcher interface {
GetUID(key string) (uid string, exists bool, notExpired bool)
HasAnyLiveSyncs() bool
}
type exchange struct {
adapterMap map[openrtb_ext.BidderName]AdaptedBidder
bidderInfo config.BidderInfos
bidderToSyncerKey map[string]string
me metrics.MetricsEngine
cache prebid_cache_client.Client
cacheTime time.Duration
gdprPermsBuilder gdpr.PermissionsBuilder
currencyConverter *currency.RateConverter
externalURL string
gdprDefaultValue gdpr.Signal
privacyConfig config.Privacy
categoriesFetcher stored_requests.CategoryFetcher
bidIDGenerator BidIDGenerator
hostSChainNode *openrtb2.SupplyChainNode
adsCertSigner adscert.Signer
server config.Server
bidValidationEnforcement config.Validations
requestSplitter requestSplitter
macroReplacer macros.Replacer
priceFloorEnabled bool
priceFloorFetcher floors.FloorFetcher
}
// Container to pass out response ext data from the GetAllBids goroutines back into the main thread
type seatResponseExtra struct {
ResponseTimeMillis int
Errors []openrtb_ext.ExtBidderMessage
Warnings []openrtb_ext.ExtBidderMessage
// httpCalls is the list of debugging info. It should only be populated if the request.test == 1.
// This will become response.ext.debug.httpcalls.{bidder} on the final Response.
HttpCalls []*openrtb_ext.ExtHttpCall
// NonBid contains non bid reason information
NonBid *openrtb_ext.NonBid
}
type bidResponseWrapper struct {
adapterSeatBids []*entities.PbsOrtbSeatBid
adapterExtra *seatResponseExtra
bidder openrtb_ext.BidderName
adapter openrtb_ext.BidderName
bidderResponseStartTime time.Time
seatNonBidBuilder SeatNonBidBuilder
}
type BidIDGenerator interface {
New(bidder string) (string, error)
Enabled() bool
}
type bidIDGenerator struct {
enabled bool
}
func (big *bidIDGenerator) Enabled() bool {
return big.enabled
}
func (big *bidIDGenerator) New(bidder string) (string, error) {
rawUuid, err := uuid.NewV4()
return rawUuid.String(), err
}
type deduplicateChanceGenerator interface {
Generate() bool
}
type randomDeduplicateBidBooleanGenerator struct{}
func (randomDeduplicateBidBooleanGenerator) Generate() bool {
return rand.Intn(100) < 50
}
func NewExchange(adapters map[openrtb_ext.BidderName]AdaptedBidder, cache prebid_cache_client.Client, cfg *config.Configuration, requestValidator ortb.RequestValidator, syncersByBidder map[string]usersync.Syncer, metricsEngine metrics.MetricsEngine, infos config.BidderInfos, gdprPermsBuilder gdpr.PermissionsBuilder, currencyConverter *currency.RateConverter, categoriesFetcher stored_requests.CategoryFetcher, adsCertSigner adscert.Signer, macroReplacer macros.Replacer, priceFloorFetcher floors.FloorFetcher) Exchange {
bidderToSyncerKey := map[string]string{}
for bidder, syncer := range syncersByBidder {
bidderToSyncerKey[bidder] = syncer.Key()
}
gdprDefaultValue := gdpr.SignalYes
if cfg.GDPR.DefaultValue == "0" {
gdprDefaultValue = gdpr.SignalNo
}
privacyConfig := config.Privacy{
CCPA: cfg.CCPA,
GDPR: cfg.GDPR,
LMT: cfg.LMT,
}
requestSplitter := requestSplitter{
bidderToSyncerKey: bidderToSyncerKey,
me: metricsEngine,
privacyConfig: privacyConfig,
gdprPermsBuilder: gdprPermsBuilder,
hostSChainNode: cfg.HostSChainNode,
bidderInfo: infos,
requestValidator: requestValidator,
}
return &exchange{
adapterMap: adapters,
bidderInfo: infos,
bidderToSyncerKey: bidderToSyncerKey,
cache: cache,
cacheTime: time.Duration(cfg.CacheURL.ExpectedTimeMillis) * time.Millisecond,
categoriesFetcher: categoriesFetcher,
currencyConverter: currencyConverter,
externalURL: cfg.ExternalURL,
gdprPermsBuilder: gdprPermsBuilder,
me: metricsEngine,
gdprDefaultValue: gdprDefaultValue,
privacyConfig: privacyConfig,
bidIDGenerator: &bidIDGenerator{cfg.GenerateBidID},
hostSChainNode: cfg.HostSChainNode,
adsCertSigner: adsCertSigner,
server: config.Server{ExternalUrl: cfg.ExternalURL, GvlID: cfg.GDPR.HostVendorID, DataCenter: cfg.DataCenter},
bidValidationEnforcement: cfg.Validations,
requestSplitter: requestSplitter,
macroReplacer: macroReplacer,
priceFloorEnabled: cfg.PriceFloors.Enabled,
priceFloorFetcher: priceFloorFetcher,
}
}
type ImpExtInfo struct {
EchoVideoAttrs bool
StoredImp []byte
Passthrough json.RawMessage
}
// AuctionRequest holds the bid request for the auction
// and all other information needed to process that request
type AuctionRequest struct {
BidRequestWrapper *openrtb_ext.RequestWrapper
ResolvedBidRequest json.RawMessage
Account config.Account
UserSyncs IdFetcher
RequestType metrics.RequestType
StartTime time.Time
Warnings []error
GlobalPrivacyControlHeader string
ImpExtInfoMap map[string]ImpExtInfo
TCF2Config gdpr.TCF2ConfigReader
Activities privacy.ActivityControl
// LegacyLabels is included here for temporary compatibility with cleanOpenRTBRequests
// in HoldAuction until we get to factoring it away. Do not use for anything new.
LegacyLabels metrics.Labels
FirstPartyData map[openrtb_ext.BidderName]*firstpartydata.ResolvedFirstPartyData
// map of imp id to stored response
StoredAuctionResponses stored_responses.ImpsWithBidResponses
// map of imp id to bidder to stored response
StoredBidResponses stored_responses.ImpBidderStoredResp
BidderImpReplaceImpID stored_responses.BidderImpReplaceImpID
PubID string
HookExecutor hookexecution.StageExecutor
QueryParams url.Values
BidderResponseStartTime time.Time
TmaxAdjustments *TmaxAdjustmentsPreprocessed
}
// BidderRequest holds the bidder specific request and all other
// information needed to process that bidder request.
type BidderRequest struct {
BidRequest *openrtb2.BidRequest
BidderName openrtb_ext.BidderName
BidderCoreName openrtb_ext.BidderName
BidderLabels metrics.AdapterLabels
BidderStoredResponses map[string]json.RawMessage
IsRequestAlias bool
ImpReplaceImpId map[string]bool
}
func (e *exchange) HoldAuction(ctx context.Context, r *AuctionRequest, debugLog *DebugLog) (*AuctionResponse, error) {
if r == nil {
return nil, nil
}
err := r.HookExecutor.ExecuteProcessedAuctionStage(r.BidRequestWrapper)
if err != nil {
return nil, err
}
requestExt, err := r.BidRequestWrapper.GetRequestExt()
if err != nil {
return nil, err
}
// ensure prebid object always exists
requestExtPrebid := requestExt.GetPrebid()
if requestExtPrebid == nil {
requestExtPrebid = &openrtb_ext.ExtRequestPrebid{}
}
if !e.server.Empty() {
requestExtPrebid.Server = &openrtb_ext.ExtRequestPrebidServer{
ExternalUrl: e.server.ExternalUrl,
GvlID: e.server.GvlID,
DataCenter: e.server.DataCenter}
requestExt.SetPrebid(requestExtPrebid)
}
cacheInstructions := getExtCacheInstructions(requestExtPrebid)
targData := getExtTargetData(requestExtPrebid, cacheInstructions)
if targData != nil {
_, targData.cacheHost, targData.cachePath = e.cache.GetExtCacheData()
}
// Get currency rates conversions for the auction
conversions := currency.GetAuctionCurrencyRates(e.currencyConverter, requestExtPrebid.CurrencyConversions)
var floorErrs []error
if e.priceFloorEnabled {
floorErrs = floors.EnrichWithPriceFloors(r.BidRequestWrapper, r.Account, conversions, e.priceFloorFetcher)
}
responseDebugAllow, accountDebugAllow, debugLog := getDebugInfo(r.BidRequestWrapper.Test, requestExtPrebid, r.Account.DebugAllow, debugLog)
// save incoming request with stored requests (if applicable) to return in debug logs
if responseDebugAllow || len(requestExtPrebid.AdServerTargeting) > 0 {
if err := r.BidRequestWrapper.RebuildRequest(); err != nil {
return nil, err
}
resolvedBidReq, err := jsonutil.Marshal(r.BidRequestWrapper.BidRequest)
if err != nil {
return nil, err
}
r.ResolvedBidRequest = resolvedBidReq
}
e.me.RecordDebugRequest(responseDebugAllow || accountDebugAllow, r.PubID)
if r.RequestType == metrics.ReqTypeORTB2Web ||
r.RequestType == metrics.ReqTypeORTB2App ||
r.RequestType == metrics.ReqTypeAMP {
//Extract First party data for auction endpoint only
resolvedFPD, fpdErrors := firstpartydata.ExtractFPDForBidders(r.BidRequestWrapper)
if len(fpdErrors) > 0 {
var errMessages []string
for _, fpdError := range fpdErrors {
errMessages = append(errMessages, fpdError.Error())
}
return nil, &errortypes.BadInput{
Message: strings.Join(errMessages, ","),
}
}
r.FirstPartyData = resolvedFPD
}
bidAdjustmentFactors := getExtBidAdjustmentFactors(requestExtPrebid)
recordImpMetrics(r.BidRequestWrapper, e.me)
// Make our best guess if GDPR applies
gdprDefaultValue := e.parseGDPRDefaultValue(r.BidRequestWrapper)
gdprSignal, err := getGDPR(r.BidRequestWrapper)
if err != nil {
return nil, err
}
channelEnabled := r.TCF2Config.ChannelEnabled(channelTypeMap[r.LegacyLabels.RType])
gdprEnforced := enforceGDPR(gdprSignal, gdprDefaultValue, channelEnabled)
dsaWriter := dsa.Writer{
Config: r.Account.Privacy.DSA,
GDPRInScope: gdprEnforced,
}
if err := dsaWriter.Write(r.BidRequestWrapper); err != nil {
return nil, err
}
// rebuild/resync the request in the request wrapper.
if err := r.BidRequestWrapper.RebuildRequest(); err != nil {
return nil, err
}
// Slice of BidRequests, each a copy of the original cleaned to only contain bidder data for the named bidder
requestExtLegacy := &openrtb_ext.ExtRequest{
Prebid: *requestExtPrebid,
SChain: requestExt.GetSChain(),
}
bidderRequests, privacyLabels, errs := e.requestSplitter.cleanOpenRTBRequests(ctx, *r, requestExtLegacy, gdprSignal, gdprEnforced, bidAdjustmentFactors)
for _, err := range errs {
if errortypes.ReadCode(err) == errortypes.InvalidImpFirstPartyDataErrorCode {
return nil, err
}
}
errs = append(errs, floorErrs...)
mergedBidAdj, err := bidadjustment.Merge(r.BidRequestWrapper, r.Account.BidAdjustments)
if err != nil {
if errortypes.ContainsFatalError([]error{err}) {
return nil, err
}
errs = append(errs, err)
}
bidAdjustmentRules := bidadjustment.BuildRules(mergedBidAdj)
e.me.RecordRequestPrivacy(privacyLabels)
if len(r.StoredAuctionResponses) > 0 || len(r.StoredBidResponses) > 0 {
e.me.RecordStoredResponse(r.PubID)
}
// If we need to cache bids, then it will take some time to call prebid cache.
// We should reduce the amount of time the bidders have, to compensate.
auctionCtx, cancel := e.makeAuctionContext(ctx, cacheInstructions.cacheBids)
defer cancel()
var (
adapterBids map[openrtb_ext.BidderName]*entities.PbsOrtbSeatBid
adapterExtra map[openrtb_ext.BidderName]*seatResponseExtra
fledge *openrtb_ext.Fledge
anyBidsReturned bool
// List of bidders we have requests for.
liveAdapters []openrtb_ext.BidderName
seatNonBidBuilder SeatNonBidBuilder = SeatNonBidBuilder{}
)
if len(r.StoredAuctionResponses) > 0 {
adapterBids, fledge, liveAdapters, err = buildStoredAuctionResponse(r.StoredAuctionResponses)
if err != nil {
return nil, err
}
anyBidsReturned = true
} else {
// List of bidders we have requests for.
liveAdapters = listBiddersWithRequests(bidderRequests)
//This will be used to validate bids
var alternateBidderCodes openrtb_ext.ExtAlternateBidderCodes
if requestExtPrebid.AlternateBidderCodes != nil {
alternateBidderCodes = *requestExtPrebid.AlternateBidderCodes
} else if r.Account.AlternateBidderCodes != nil {
alternateBidderCodes = *r.Account.AlternateBidderCodes
}
var extraRespInfo extraAuctionResponseInfo
adapterBids, adapterExtra, extraRespInfo = e.getAllBids(auctionCtx, bidderRequests, bidAdjustmentFactors, conversions, accountDebugAllow, r.GlobalPrivacyControlHeader, debugLog.DebugOverride, alternateBidderCodes, requestExtLegacy.Prebid.Experiment, r.HookExecutor, r.StartTime, bidAdjustmentRules, r.TmaxAdjustments, responseDebugAllow)
fledge = extraRespInfo.fledge
anyBidsReturned = extraRespInfo.bidsFound
r.BidderResponseStartTime = extraRespInfo.bidderResponseStartTime
if extraRespInfo.seatNonBidBuilder != nil {
seatNonBidBuilder = extraRespInfo.seatNonBidBuilder
}
}
var (
auc *auction
cacheErrs []error
bidResponseExt *openrtb_ext.ExtBidResponse
)
if anyBidsReturned {
if e.priceFloorEnabled {
var rejectedBids []*entities.PbsOrtbSeatBid
var enforceErrs []error
adapterBids, enforceErrs, rejectedBids = floors.Enforce(r.BidRequestWrapper, adapterBids, r.Account, conversions)
errs = append(errs, enforceErrs...)
for _, rejectedBid := range rejectedBids {
errs = append(errs, &errortypes.Warning{
Message: fmt.Sprintf("%s bid id %s rejected - bid price %.4f %s is less than bid floor %.4f %s for imp %s", rejectedBid.Seat, rejectedBid.Bids[0].Bid.ID, rejectedBid.Bids[0].Bid.Price, rejectedBid.Currency, rejectedBid.Bids[0].BidFloors.FloorValue, rejectedBid.Bids[0].BidFloors.FloorCurrency, rejectedBid.Bids[0].Bid.ImpID),
WarningCode: errortypes.FloorBidRejectionWarningCode})
rejectionReason := ResponseRejectedBelowFloor
if rejectedBid.Bids[0].Bid.DealID != "" {
rejectionReason = ResponseRejectedBelowDealFloor
}
seatNonBidBuilder.rejectBid(rejectedBid.Bids[0], int(rejectionReason), rejectedBid.Seat)
}
}
var bidCategory map[string]string
//If includebrandcategory is present in ext then CE feature is on.
if requestExtPrebid.Targeting != nil && requestExtPrebid.Targeting.IncludeBrandCategory != nil {
var rejections []string
bidCategory, adapterBids, rejections, err = applyCategoryMapping(ctx, *requestExtPrebid.Targeting, adapterBids, e.categoriesFetcher, targData, &randomDeduplicateBidBooleanGenerator{}, &seatNonBidBuilder)
if err != nil {
return nil, fmt.Errorf("Error in category mapping : %s", err.Error())
}
for _, message := range rejections {
errs = append(errs, errors.New(message))
}
}
if e.bidIDGenerator.Enabled() {
for bidder, seatBid := range adapterBids {
for i := range seatBid.Bids {
if bidID, err := e.bidIDGenerator.New(bidder.String()); err == nil {
seatBid.Bids[i].GeneratedBidID = bidID
} else {
errs = append(errs, errors.New("Error generating bid.ext.prebid.bidid"))
}
}
}
}
evTracking := getEventTracking(requestExtPrebid, r.StartTime, &r.Account, e.bidderInfo, e.externalURL)
adapterBids = evTracking.modifyBidsForEvents(adapterBids)
r.HookExecutor.ExecuteAllProcessedBidResponsesStage(adapterBids)
if targData != nil {
multiBidMap := buildMultiBidMap(requestExtPrebid)
// A non-nil auction is only needed if targeting is active. (It is used below this block to extract cache keys)
auc = newAuction(adapterBids, len(r.BidRequestWrapper.Imp), targData.preferDeals)
auc.validateAndUpdateMultiBid(adapterBids, targData.preferDeals, r.Account.DefaultBidLimit)
auc.setRoundedPrices(*targData)
if requestExtPrebid.SupportDeals {
dealErrs := applyDealSupport(r.BidRequestWrapper.BidRequest, auc, bidCategory, multiBidMap)
errs = append(errs, dealErrs...)
}
bidResponseExt = e.makeExtBidResponse(adapterBids, adapterExtra, *r, responseDebugAllow, requestExtPrebid.Passthrough, fledge, errs)
if debugLog.DebugEnabledOrOverridden {
if bidRespExtBytes, err := jsonutil.Marshal(bidResponseExt); err == nil {
debugLog.Data.Response = string(bidRespExtBytes)
} else {
debugLog.Data.Response = "Unable to marshal response ext for debugging"
errs = append(errs, err)
}
}
cacheErrs = auc.doCache(ctx, e.cache, targData, evTracking, r.BidRequestWrapper.BidRequest, 60, &r.Account.CacheTTL, bidCategory, debugLog)
if len(cacheErrs) > 0 {
errs = append(errs, cacheErrs...)
}
if targData.includeWinners || targData.includeBidderKeys || targData.includeFormat {
targData.setTargeting(auc, r.BidRequestWrapper.BidRequest.App != nil, bidCategory, r.Account.TruncateTargetAttribute, multiBidMap)
}
}
bidResponseExt = e.makeExtBidResponse(adapterBids, adapterExtra, *r, responseDebugAllow, requestExtPrebid.Passthrough, fledge, errs)
} else {
bidResponseExt = e.makeExtBidResponse(adapterBids, adapterExtra, *r, responseDebugAllow, requestExtPrebid.Passthrough, fledge, errs)
if debugLog.DebugEnabledOrOverridden {
if bidRespExtBytes, err := jsonutil.Marshal(bidResponseExt); err == nil {
debugLog.Data.Response = string(bidRespExtBytes)
} else {
debugLog.Data.Response = "Unable to marshal response ext for debugging"
errs = append(errs, err)
}
}
}
if !accountDebugAllow && !debugLog.DebugOverride {
accountDebugDisabledWarning := openrtb_ext.ExtBidderMessage{
Code: errortypes.AccountLevelDebugDisabledWarningCode,
Message: "debug turned off for account",
}
bidResponseExt.Warnings[openrtb_ext.BidderReservedGeneral] = append(bidResponseExt.Warnings[openrtb_ext.BidderReservedGeneral], accountDebugDisabledWarning)
}
for _, warning := range r.Warnings {
if errortypes.ReadScope(warning) == errortypes.ScopeDebug && !responseDebugAllow {
continue
}
generalWarning := openrtb_ext.ExtBidderMessage{
Code: errortypes.ReadCode(warning),
Message: warning.Error(),
}
bidResponseExt.Warnings[openrtb_ext.BidderReservedGeneral] = append(bidResponseExt.Warnings[openrtb_ext.BidderReservedGeneral], generalWarning)
}
e.bidValidationEnforcement.SetBannerCreativeMaxSize(r.Account.Validations)
// Build the response
bidResponse := e.buildBidResponse(ctx, liveAdapters, adapterBids, r.BidRequestWrapper, adapterExtra, auc, bidResponseExt, cacheInstructions.returnCreative, r.ImpExtInfoMap, r.PubID, errs, &seatNonBidBuilder)
bidResponse = adservertargeting.Apply(r.BidRequestWrapper, r.ResolvedBidRequest, bidResponse, r.QueryParams, bidResponseExt, r.Account.TruncateTargetAttribute)
bidResponse.Ext, err = encodeBidResponseExt(bidResponseExt)
if err != nil {
return nil, err
}
bidResponseExt = setSeatNonBid(bidResponseExt, seatNonBidBuilder)
return &AuctionResponse{
BidResponse: bidResponse,
ExtBidResponse: bidResponseExt,
}, nil
}
func buildMultiBidMap(prebid *openrtb_ext.ExtRequestPrebid) map[string]openrtb_ext.ExtMultiBid {
if prebid == nil || prebid.MultiBid == nil {
return nil
}
// validation already done in validateRequestExt(), directly build a map here for downstream processing
multiBidMap := make(map[string]openrtb_ext.ExtMultiBid)
for _, multiBid := range prebid.MultiBid {
if multiBid.Bidder != "" {
if bidderNormalized, bidderFound := openrtb_ext.NormalizeBidderName(multiBid.Bidder); bidderFound {
multiBidMap[string(bidderNormalized)] = *multiBid
}
} else {
for _, bidder := range multiBid.Bidders {
if bidderNormalized, bidderFound := openrtb_ext.NormalizeBidderName(bidder); bidderFound {
multiBidMap[string(bidderNormalized)] = *multiBid
}
}
}
}
return multiBidMap
}
func (e *exchange) parseGDPRDefaultValue(r *openrtb_ext.RequestWrapper) gdpr.Signal {
gdprDefaultValue := e.gdprDefaultValue
var geo *openrtb2.Geo
if r.User != nil && r.User.Geo != nil {
geo = r.User.Geo
} else if r.Device != nil && r.Device.Geo != nil {
geo = r.Device.Geo
}
if geo != nil {
// If we have a country set, and it is on the list, we assume GDPR applies if not set on the request.
// Otherwise we assume it does not apply as long as it appears "valid" (is 3 characters long).
if _, found := e.privacyConfig.GDPR.EEACountriesMap[strings.ToUpper(geo.Country)]; found {
gdprDefaultValue = gdpr.SignalYes
} else if len(geo.Country) == 3 {
// The country field is formatted properly as a three character country code
gdprDefaultValue = gdpr.SignalNo
}
}
return gdprDefaultValue
}
func recordImpMetrics(r *openrtb_ext.RequestWrapper, metricsEngine metrics.MetricsEngine) {
for _, impInRequest := range r.GetImp() {
var impLabels metrics.ImpLabels = metrics.ImpLabels{
BannerImps: impInRequest.Banner != nil,
VideoImps: impInRequest.Video != nil,
AudioImps: impInRequest.Audio != nil,
NativeImps: impInRequest.Native != nil,
}
metricsEngine.RecordImps(impLabels)
}
}
// applyDealSupport updates targeting keys with deal prefixes if minimum deal tier exceeded
func applyDealSupport(bidRequest *openrtb2.BidRequest, auc *auction, bidCategory map[string]string, multiBid map[string]openrtb_ext.ExtMultiBid) []error {
errs := []error{}
impDealMap := getDealTiers(bidRequest)
for impID, topBidsPerImp := range auc.allBidsByBidder {
impDeal := impDealMap[impID]
for bidder, topBidsPerBidder := range topBidsPerImp {
bidderNormalized, bidderFound := openrtb_ext.NormalizeBidderName(bidder.String())
if !bidderFound {
bidderNormalized = bidder
}
maxBid := bidsToUpdate(multiBid, bidderNormalized.String())
for i, topBid := range topBidsPerBidder {
if i == maxBid {
break
}
if topBid.DealPriority > 0 {
if validateDealTier(impDeal[bidderNormalized]) {
updateHbPbCatDur(topBid, impDeal[bidderNormalized], bidCategory)
} else {
errs = append(errs, fmt.Errorf("dealTier configuration invalid for bidder '%s', imp ID '%s'", string(bidder), impID))
}
}
}
}
}
return errs
}
// By default, update 1 bid,
// For 2nd and the following bids, updateHbPbCatDur only if this bidder's multibid config is fully defined.
func bidsToUpdate(multiBid map[string]openrtb_ext.ExtMultiBid, bidder string) int {
if multiBid != nil {
if bidderMultiBid, ok := multiBid[bidder]; ok && bidderMultiBid.TargetBidderCodePrefix != "" {
return *bidderMultiBid.MaxBids
}
}
return openrtb_ext.DefaultBidLimit
}
// getDealTiers creates map of impression to bidder deal tier configuration
func getDealTiers(bidRequest *openrtb2.BidRequest) map[string]openrtb_ext.DealTierBidderMap {
impDealMap := make(map[string]openrtb_ext.DealTierBidderMap)
for _, imp := range bidRequest.Imp {
dealTierBidderMap, err := openrtb_ext.ReadDealTiersFromImp(imp)
if err != nil {
continue
}
impDealMap[imp.ID] = dealTierBidderMap
}
return impDealMap
}
func validateDealTier(dealTier openrtb_ext.DealTier) bool {
return len(dealTier.Prefix) > 0 && dealTier.MinDealTier > 0
}
func updateHbPbCatDur(bid *entities.PbsOrtbBid, dealTier openrtb_ext.DealTier, bidCategory map[string]string) {
if bid.DealPriority >= dealTier.MinDealTier {
prefixTier := fmt.Sprintf("%s%d_", dealTier.Prefix, bid.DealPriority)
bid.DealTierSatisfied = true
if oldCatDur, ok := bidCategory[bid.Bid.ID]; ok {
oldCatDurSplit := strings.SplitAfterN(oldCatDur, "_", 2)
oldCatDurSplit[0] = prefixTier
newCatDur := strings.Join(oldCatDurSplit, "")
bidCategory[bid.Bid.ID] = newCatDur
}
}
}
func (e *exchange) makeAuctionContext(ctx context.Context, needsCache bool) (auctionCtx context.Context, cancel context.CancelFunc) {
auctionCtx = ctx
cancel = func() {}
if needsCache {
if deadline, ok := ctx.Deadline(); ok {
auctionCtx, cancel = context.WithDeadline(ctx, deadline.Add(-e.cacheTime))
}
}
return
}
// This piece sends all the requests to the bidder adapters and gathers the results.
func (e *exchange) getAllBids(
ctx context.Context,
bidderRequests []BidderRequest,
bidAdjustments map[string]float64,
conversions currency.Conversions,
accountDebugAllowed bool,
globalPrivacyControlHeader string,
headerDebugAllowed bool,
alternateBidderCodes openrtb_ext.ExtAlternateBidderCodes,
experiment *openrtb_ext.Experiment,
hookExecutor hookexecution.StageExecutor,
pbsRequestStartTime time.Time,
bidAdjustmentRules map[string][]openrtb_ext.Adjustment,
tmaxAdjustments *TmaxAdjustmentsPreprocessed,
responseDebugAllowed bool) (
map[openrtb_ext.BidderName]*entities.PbsOrtbSeatBid,
map[openrtb_ext.BidderName]*seatResponseExtra,
extraAuctionResponseInfo) {
// Set up pointers to the bid results
adapterBids := make(map[openrtb_ext.BidderName]*entities.PbsOrtbSeatBid, len(bidderRequests))
adapterExtra := make(map[openrtb_ext.BidderName]*seatResponseExtra, len(bidderRequests))
chBids := make(chan *bidResponseWrapper, len(bidderRequests))
extraRespInfo := extraAuctionResponseInfo{seatNonBidBuilder: SeatNonBidBuilder{}}
e.me.RecordOverheadTime(metrics.MakeBidderRequests, time.Since(pbsRequestStartTime))
for _, bidder := range bidderRequests {
// Here we actually call the adapters and collect the bids.
bidderRunner := e.recoverSafely(bidderRequests, func(bidderRequest BidderRequest, conversions currency.Conversions) {
// Passing in aName so a doesn't change out from under the go routine
if bidderRequest.BidderLabels.Adapter == "" {
glog.Errorf("Exchange: bidlables for %s (%s) missing adapter string", bidderRequest.BidderName, bidderRequest.BidderCoreName)
bidderRequest.BidderLabels.Adapter = bidderRequest.BidderCoreName
}
brw := new(bidResponseWrapper)
brw.bidder = bidderRequest.BidderName
brw.adapter = bidderRequest.BidderCoreName
// Defer basic metrics to insure we capture them after all the values have been set
defer func() {
e.me.RecordAdapterRequest(bidderRequest.BidderLabels)
}()
start := time.Now()
reqInfo := adapters.NewExtraRequestInfo(conversions)
reqInfo.PbsEntryPoint = bidderRequest.BidderLabels.RType
reqInfo.GlobalPrivacyControlHeader = globalPrivacyControlHeader
bidReqOptions := bidRequestOptions{
accountDebugAllowed: accountDebugAllowed,
headerDebugAllowed: headerDebugAllowed,
addCallSignHeader: isAdsCertEnabled(experiment, e.bidderInfo[string(bidderRequest.BidderName)]),
bidAdjustments: bidAdjustments,
tmaxAdjustments: tmaxAdjustments,
bidderRequestStartTime: start,
responseDebugAllowed: responseDebugAllowed,
}
seatBids, extraBidderRespInfo, err := e.adapterMap[bidderRequest.BidderCoreName].requestBid(ctx, bidderRequest, conversions, &reqInfo, e.adsCertSigner, bidReqOptions, alternateBidderCodes, hookExecutor, bidAdjustmentRules)
brw.bidderResponseStartTime = extraBidderRespInfo.respProcessingStartTime
// Add in time reporting
elapsed := time.Since(start)
brw.adapterSeatBids = seatBids
brw.seatNonBidBuilder = extraBidderRespInfo.seatNonBidBuilder
// Structure to record extra tracking data generated during bidding
ae := new(seatResponseExtra)
ae.ResponseTimeMillis = int(elapsed / time.Millisecond)
if len(seatBids) != 0 {
ae.HttpCalls = seatBids[0].HttpCalls
}
// Timing statistics
e.me.RecordAdapterTime(bidderRequest.BidderLabels, elapsed)
bidderRequest.BidderLabels.AdapterBids = bidsToMetric(brw.adapterSeatBids)
bidderRequest.BidderLabels.AdapterErrors = errorsToMetric(err)
// Append any bid validation errors to the error list
ae.Errors = errsToBidderErrors(err)
ae.Warnings = errsToBidderWarnings(err)
brw.adapterExtra = ae
for _, seatBid := range seatBids {
if seatBid != nil {
for _, bid := range seatBid.Bids {
var cpm = float64(bid.Bid.Price * 1000)
e.me.RecordAdapterPrice(bidderRequest.BidderLabels, cpm)
e.me.RecordAdapterBidReceived(bidderRequest.BidderLabels, bid.BidType, bid.Bid.AdM != "")
}
}
}
chBids <- brw
}, chBids)
go bidderRunner(bidder, conversions)
}
// Wait for the bidders to do their thing
for i := 0; i < len(bidderRequests); i++ {
brw := <-chBids
if !brw.bidderResponseStartTime.IsZero() {
extraRespInfo.bidderResponseStartTime = brw.bidderResponseStartTime
}
//if bidder returned no bids back - remove bidder from further processing
for _, seatBid := range brw.adapterSeatBids {
if seatBid != nil {
bidderName := openrtb_ext.BidderName(seatBid.Seat)
if len(seatBid.Bids) != 0 {
if val, ok := adapterBids[bidderName]; ok {
adapterBids[bidderName].Bids = append(val.Bids, seatBid.Bids...)
} else {
adapterBids[bidderName] = seatBid
}
extraRespInfo.bidsFound = true
}
// collect fledgeAuctionConfigs separately from bids, as empty seatBids may be discarded
extraRespInfo.fledge = collectFledgeFromSeatBid(extraRespInfo.fledge, bidderName, brw.adapter, seatBid)
}
}
//but we need to add all bidders data to adapterExtra to have metrics and other metadata
adapterExtra[brw.bidder] = brw.adapterExtra
// collect adapter non bids
extraRespInfo.seatNonBidBuilder.append(brw.seatNonBidBuilder)
}
return adapterBids, adapterExtra, extraRespInfo
}
func collectFledgeFromSeatBid(fledge *openrtb_ext.Fledge, bidderName openrtb_ext.BidderName, adapterName openrtb_ext.BidderName, seatBid *entities.PbsOrtbSeatBid) *openrtb_ext.Fledge {
if seatBid.FledgeAuctionConfigs != nil {
if fledge == nil {
fledge = &openrtb_ext.Fledge{
AuctionConfigs: make([]*openrtb_ext.FledgeAuctionConfig, 0, len(seatBid.FledgeAuctionConfigs)),
}
}
for _, config := range seatBid.FledgeAuctionConfigs {
fledge.AuctionConfigs = append(fledge.AuctionConfigs, &openrtb_ext.FledgeAuctionConfig{
Bidder: bidderName.String(),
Adapter: config.Bidder,
ImpId: config.ImpId,
Config: config.Config,
})
}
}
return fledge
}
func (e *exchange) recoverSafely(bidderRequests []BidderRequest,
inner func(BidderRequest, currency.Conversions),
chBids chan *bidResponseWrapper) func(BidderRequest, currency.Conversions) {
return func(bidderRequest BidderRequest, conversions currency.Conversions) {
defer func() {
if r := recover(); r != nil {
allBidders := ""
sb := strings.Builder{}
for _, bidder := range bidderRequests {
sb.WriteString(bidder.BidderName.String())
sb.WriteString(",")
}
if sb.Len() > 0 {
allBidders = sb.String()[:sb.Len()-1]
}
glog.Errorf("OpenRTB auction recovered panic from Bidder %s: %v. "+
"Account id: %s, All Bidders: %s, Stack trace is: %v",
bidderRequest.BidderCoreName, r, bidderRequest.BidderLabels.PubID, allBidders, string(debug.Stack()))
e.me.RecordAdapterPanic(bidderRequest.BidderLabels)
// Let the master request know that there is no data here
brw := new(bidResponseWrapper)
brw.adapterExtra = new(seatResponseExtra)
chBids <- brw
}
}()
inner(bidderRequest, conversions)
}
}
func bidsToMetric(seatBids []*entities.PbsOrtbSeatBid) metrics.AdapterBid {
for _, seatBid := range seatBids {
if seatBid != nil && len(seatBid.Bids) != 0 {
return metrics.AdapterBidPresent
}
}
return metrics.AdapterBidNone
}
func errorsToMetric(errs []error) map[metrics.AdapterError]struct{} {
if len(errs) == 0 {
return nil
}
ret := make(map[metrics.AdapterError]struct{}, len(errs))
var s struct{}
for _, err := range errs {
switch errortypes.ReadCode(err) {
case errortypes.TimeoutErrorCode:
ret[metrics.AdapterErrorTimeout] = s
case errortypes.BadInputErrorCode:
ret[metrics.AdapterErrorBadInput] = s
case errortypes.BadServerResponseErrorCode:
ret[metrics.AdapterErrorBadServerResponse] = s
case errortypes.FailedToRequestBidsErrorCode:
ret[metrics.AdapterErrorFailedToRequestBids] = s
case errortypes.AlternateBidderCodeWarningCode:
ret[metrics.AdapterErrorValidation] = s
case errortypes.TmaxTimeoutErrorCode:
ret[metrics.AdapterErrorTmaxTimeout] = s
default:
ret[metrics.AdapterErrorUnknown] = s
}
}
return ret
}
func errsToBidderErrors(errs []error) []openrtb_ext.ExtBidderMessage {
sErr := make([]openrtb_ext.ExtBidderMessage, 0)
for _, err := range errortypes.FatalOnly(errs) {
newErr := openrtb_ext.ExtBidderMessage{
Code: errortypes.ReadCode(err),
Message: err.Error(),
}
sErr = append(sErr, newErr)
}
return sErr
}
func errsToBidderWarnings(errs []error) []openrtb_ext.ExtBidderMessage {
sWarn := make([]openrtb_ext.ExtBidderMessage, 0)
for _, warn := range errortypes.WarningOnly(errs) {
newErr := openrtb_ext.ExtBidderMessage{
Code: errortypes.ReadCode(warn),
Message: warn.Error(),
}
sWarn = append(sWarn, newErr)
}
return sWarn
}
// This piece takes all the bids supplied by the adapters and crafts an openRTB response to send back to the requester
func (e *exchange) buildBidResponse(ctx context.Context, liveAdapters []openrtb_ext.BidderName, adapterSeatBids map[openrtb_ext.BidderName]*entities.PbsOrtbSeatBid, bidRequest *openrtb_ext.RequestWrapper, adapterExtra map[openrtb_ext.BidderName]*seatResponseExtra, auc *auction, bidResponseExt *openrtb_ext.ExtBidResponse, returnCreative bool, impExtInfoMap map[string]ImpExtInfo, pubID string, errList []error, seatNonBidBuilder *SeatNonBidBuilder) *openrtb2.BidResponse {
bidResponse := new(openrtb2.BidResponse)
bidResponse.ID = bidRequest.ID
if len(liveAdapters) == 0 {
// signal "Invalid Request" if no valid bidders.
bidResponse.NBR = openrtb3.NoBidInvalidRequest.Ptr()
}
// Create the SeatBids. We use a zero sized slice so that we can append non-zero seat bids, and not include seatBid
// objects for seatBids without any bids. Preallocate the max possible size to avoid reallocating the array as we go.
seatBids := make([]openrtb2.SeatBid, 0, len(liveAdapters))
for a, adapterSeatBids := range adapterSeatBids {
//while processing every single bib, do we need to handle categories here?
if adapterSeatBids != nil && len(adapterSeatBids.Bids) > 0 {
sb := e.makeSeatBid(adapterSeatBids, a, adapterExtra, auc, returnCreative, impExtInfoMap, bidRequest, bidResponseExt, pubID, seatNonBidBuilder)
seatBids = append(seatBids, *sb)
bidResponse.Cur = adapterSeatBids.Currency
}
}
bidResponse.SeatBid = seatBids
return bidResponse
}
func encodeBidResponseExt(bidResponseExt *openrtb_ext.ExtBidResponse) ([]byte, error) {
buffer := &bytes.Buffer{}
enc := json.NewEncoder(buffer)
enc.SetEscapeHTML(false)
err := enc.Encode(bidResponseExt)
return buffer.Bytes(), err
}
func applyCategoryMapping(ctx context.Context, targeting openrtb_ext.ExtRequestTargeting, seatBids map[openrtb_ext.BidderName]*entities.PbsOrtbSeatBid, categoriesFetcher stored_requests.CategoryFetcher, targData *targetData, booleanGenerator deduplicateChanceGenerator, seatNonBidBuilder *SeatNonBidBuilder) (map[string]string, map[openrtb_ext.BidderName]*entities.PbsOrtbSeatBid, []string, error) {
res := make(map[string]string)
type bidDedupe struct {
bidderName openrtb_ext.BidderName
bidIndex int
bidID string
bidPrice string
}
dedupe := make(map[string]bidDedupe)
// applyCategoryMapping doesn't get called unless
brandCatExt := targeting.IncludeBrandCategory
//If ext.prebid.targeting.includebrandcategory is present in ext then competitive exclusion feature is on.
var includeBrandCategory = brandCatExt != nil //if not present - category will no be appended
appendBidderNames := targeting.AppendBidderNames
var primaryAdServer string
var publisher string
var err error
var rejections []string
var translateCategories = true
if includeBrandCategory && brandCatExt.WithCategory {
if brandCatExt.TranslateCategories != nil {
translateCategories = *brandCatExt.TranslateCategories
}
//if translateCategories is set to false, ignore checking primaryAdServer and publisher