forked from prebid/Prebid.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgreenbidsAnalyticsAdapter.js
291 lines (262 loc) · 9.9 KB
/
greenbidsAnalyticsAdapter.js
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
import {ajax} from '../src/ajax.js';
import adapter from '../libraries/analyticsAdapter/AnalyticsAdapter.js';
import { EVENTS } from '../src/constants.js';
import adapterManager from '../src/adapterManager.js';
import {deepClone, generateUUID, logError, logInfo, logWarn, getParameterByName} from '../src/utils.js';
/**
* @typedef {import('../src/adapters/bidderFactory.js').Bid} Bid
*/
/**
* @typedef {object} Message Payload message sent to the Greenbids API
*/
const analyticsType = 'endpoint';
export const ANALYTICS_VERSION = '2.3.2';
const ANALYTICS_SERVER = 'https://a.greenbids.ai';
const {
AUCTION_INIT,
AUCTION_END,
BID_TIMEOUT,
BILLABLE_EVENT,
} = EVENTS;
export const BIDDER_STATUS = {
BID: 'bid',
NO_BID: 'noBid',
TIMEOUT: 'timeout'
};
const analyticsOptions = {};
export const isSampled = function(greenbidsId, samplingRate, exploratorySamplingSplit) {
const isSamplingForced = getParameterByName('greenbids_force_sampling');
if (isSamplingForced) {
logInfo('Greenbids Analytics: sampling flag detected, forcing analytics');
return true;
}
if (samplingRate < 0 || samplingRate > 1) {
logWarn('Sampling rate must be between 0 and 1');
return true;
}
const exploratorySamplingRate = samplingRate * exploratorySamplingSplit;
const throttledSamplingRate = samplingRate * (1.0 - exploratorySamplingSplit);
const hashInt = parseInt(greenbidsId.slice(-4), 16);
const isPrimarySampled = hashInt < exploratorySamplingRate * (0xFFFF + 1);
if (isPrimarySampled) return true;
const isExtraSampled = hashInt >= (1 - throttledSamplingRate) * (0xFFFF + 1);
return isExtraSampled;
}
export const greenbidsAnalyticsAdapter = Object.assign(adapter({ANALYTICS_SERVER, analyticsType}), {
cachedAuctions: {},
exploratorySamplingSplit: 0.9,
initConfig(config) {
analyticsOptions.options = deepClone(config.options);
/**
* Required option: pbuid
* @type {boolean}
*/
if (typeof analyticsOptions.options.pbuid !== 'string' || analyticsOptions.options.pbuid.length < 1) {
logError('"options.pbuid" is required.');
return false;
}
/**
* Deprecate use of integerated 'sampling' config
* replace by greenbidsSampling
*/
if (typeof analyticsOptions.options.sampling === 'number') {
logWarn('"options.sampling" is deprecated, please use "greenbidsSampling" instead.');
analyticsOptions.options.greenbidsSampling = analyticsOptions.options.sampling;
}
/**
* Discourage unsampled analytics
*/
if (typeof analyticsOptions.options.greenbidsSampling !== 'number' || analyticsOptions.options.greenbidsSampling >= 1) {
logWarn('"options.greenbidsSampling" is not set or >=1, using this analytics module unsampled is discouraged.');
analyticsOptions.options.greenbidsSampling = 1;
}
/**
* Add optional debug parameter to override exploratorySamplingSplit
*/
if (typeof analyticsOptions.options.exploratorySamplingSplit === 'number') {
logInfo('Greenbids Analytics: Overriding "exploratorySamplingSplit".');
this.exploratorySamplingSplit = analyticsOptions.options.exploratorySamplingSplit;
}
analyticsOptions.pbuid = config.options.pbuid
analyticsOptions.server = ANALYTICS_SERVER;
return true;
},
sendEventMessage(endPoint, data) {
logInfo(`AJAX: ${endPoint}: ` + JSON.stringify(data));
ajax(`${analyticsOptions.server}${endPoint}`, null, JSON.stringify(data), {
contentType: 'application/json'
});
},
/**
*
* @param {string} auctionId
* @returns {Message}
*/
createCommonMessage(auctionId) {
const cachedAuction = this.getCachedAuction(auctionId);
return {
version: ANALYTICS_VERSION,
auctionId: auctionId,
referrer: window.location.href,
sampling: analyticsOptions.options.greenbidsSampling,
prebid: '$prebid.version$',
greenbidsId: cachedAuction.greenbidsId,
pbuid: analyticsOptions.pbuid,
billingId: cachedAuction.billingId,
adUnits: [],
};
},
/**
* @param {Bid} bid
* @param {BIDDER_STATUS} status
*/
serializeBidResponse(bid, status) {
return {
bidder: bid.bidder,
isTimeout: (status === BIDDER_STATUS.TIMEOUT),
hasBid: (status === BIDDER_STATUS.BID),
params: (bid.params && Object.keys(bid.params).length > 0) ? bid.params : {},
...(status === BIDDER_STATUS.BID ? {
cpm: bid.cpm,
currency: bid.currency
} : {}),
};
},
/**
* @param {*} message Greenbids API payload
* @param {Bid} bid Bid to add to the payload
* @param {BIDDER_STATUS} status Bidding status
*/
addBidResponseToMessage(message, bid, status) {
const adUnitCode = bid.adUnitCode.toLowerCase();
const adUnitIndex = message.adUnits.findIndex((adUnit) => {
return adUnit.code === adUnitCode;
});
if (adUnitIndex === -1) {
logError('Trying to add to non registered adunit');
return;
}
const bidderIndex = message.adUnits[adUnitIndex].bidders.findIndex((bidder) => {
return bidder.bidder === bid.bidder;
});
if (bidderIndex === -1) {
message.adUnits[adUnitIndex].bidders.push(this.serializeBidResponse(bid, status));
} else {
message.adUnits[adUnitIndex].bidders[bidderIndex].params = (bid.params && Object.keys(bid.params).length > 0) ? bid.params : {};
if (status === BIDDER_STATUS.BID) {
message.adUnits[adUnitIndex].bidders[bidderIndex].hasBid = true;
message.adUnits[adUnitIndex].bidders[bidderIndex].cpm = bid.cpm;
message.adUnits[adUnitIndex].bidders[bidderIndex].currency = bid.currency;
} else if (status === BIDDER_STATUS.TIMEOUT) {
message.adUnits[adUnitIndex].bidders[bidderIndex].isTimeout = true;
}
}
},
createBidMessage(auctionEndArgs) {
const {auctionId, timestamp, auctionEnd, adUnits, bidsReceived, noBids} = auctionEndArgs;
const cachedAuction = this.getCachedAuction(auctionId);
const message = this.createCommonMessage(auctionId);
const timeoutBids = cachedAuction.timeoutBids || [];
message.auctionElapsed = (auctionEnd - timestamp);
adUnits.forEach((adUnit) => {
const adUnitCode = adUnit.code?.toLowerCase() || 'unknown_adunit_code';
message.adUnits.push({
code: adUnitCode,
mediaTypes: {
...(adUnit.mediaTypes?.banner !== undefined) && {banner: adUnit.mediaTypes.banner},
...(adUnit.mediaTypes?.video !== undefined) && {video: adUnit.mediaTypes.video},
...(adUnit.mediaTypes?.native !== undefined) && {native: adUnit.mediaTypes.native}
},
ortb2Imp: adUnit.ortb2Imp || {},
bidders: [],
});
});
// We enrich noBid then bids, then timeouts, because in case of a timeout, one response from a bidder
// Can be in the 3 arrays, and we want that case reflected in the call
noBids.forEach(bid => this.addBidResponseToMessage(message, bid, BIDDER_STATUS.NO_BID));
bidsReceived.forEach(bid => this.addBidResponseToMessage(message, bid, BIDDER_STATUS.BID));
timeoutBids.forEach(bid => this.addBidResponseToMessage(message, bid, BIDDER_STATUS.TIMEOUT));
return message;
},
getCachedAuction(auctionId) {
this.cachedAuctions[auctionId] = this.cachedAuctions[auctionId] || {
timeoutBids: [],
greenbidsId: null,
billingId: null,
isSampled: true,
};
return this.cachedAuctions[auctionId];
},
handleAuctionInit(auctionInitArgs) {
const cachedAuction = this.getCachedAuction(auctionInitArgs.auctionId);
try {
cachedAuction.greenbidsId = auctionInitArgs.adUnits[0].ortb2Imp.ext.greenbids.greenbidsId;
} catch (e) {
logInfo("Couldn't find Greenbids RTD info, assuming analytics only");
cachedAuction.greenbidsId = generateUUID();
}
cachedAuction.isSampled = isSampled(cachedAuction.greenbidsId, analyticsOptions.options.greenbidsSampling, this.exploratorySamplingSplit);
},
handleAuctionEnd(auctionEndArgs) {
const cachedAuction = this.getCachedAuction(auctionEndArgs.auctionId);
const isFilteringForced = getParameterByName('greenbids_force_filtering');
if (!isFilteringForced) {
this.sendEventMessage('/',
this.createBidMessage(auctionEndArgs, cachedAuction)
)
};
},
handleBidTimeout(timeoutBids) {
timeoutBids.forEach((bid) => {
const cachedAuction = this.getCachedAuction(bid.auctionId);
cachedAuction.timeoutBids.push(bid);
});
},
handleBillable(billableArgs) {
const cachedAuction = this.getCachedAuction(billableArgs.auctionId);
/* Filter Greenbids Billable Events only */
if (billableArgs.vendor === 'greenbidsRtdProvider') {
cachedAuction.billingId = billableArgs.billingId || 'unknown_billing_id';
}
},
track({eventType, args}) {
try {
if (eventType === AUCTION_INIT) {
this.handleAuctionInit(args);
}
if (this.getCachedAuction(args?.auctionId)?.isSampled ?? true) {
switch (eventType) {
case BID_TIMEOUT:
this.handleBidTimeout(args);
break;
case AUCTION_END:
this.handleAuctionEnd(args);
break;
case BILLABLE_EVENT:
this.handleBillable(args);
break;
}
}
} catch (e) {
logWarn('There was an error handling event ' + eventType);
}
},
getAnalyticsOptions() {
return analyticsOptions;
},
});
greenbidsAnalyticsAdapter.originEnableAnalytics = greenbidsAnalyticsAdapter.enableAnalytics;
greenbidsAnalyticsAdapter.enableAnalytics = function(config) {
this.initConfig(config);
if (typeof config.options.sampling === 'number') {
// Set sampling to 1 to prevent prebid analytics integrated sampling to happen
config.options.sampling = 1;
}
logInfo('loading greenbids analytics');
greenbidsAnalyticsAdapter.originEnableAnalytics(config);
};
adapterManager.registerAnalyticsAdapter({
adapter: greenbidsAnalyticsAdapter,
code: 'greenbids'
});
export default greenbidsAnalyticsAdapter;