Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core & fledgeForGpt: backport customSlotMatching #11957

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 18 additions & 14 deletions modules/fledgeForGpt.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
*/
import {getHook, submodule} from '../src/hook.js';
import {deepAccess, logInfo, logWarn, sizeTupleToSizeString} from '../src/utils.js';
import {getGptSlotForAdUnitCode} from '../libraries/gptUtils/gptUtils.js';
import {config} from '../src/config.js';
import {getGlobal} from '../src/prebidGlobal.js';

Expand All @@ -13,6 +12,8 @@ import {getGlobal} from '../src/prebidGlobal.js';
// eslint-disable-next-line prebid/validate-imports
import './paapi.js';
import {keyCompare} from '../src/utils/reducers.js';
import {getGPTSlotsForAdUnits} from '../src/targeting.js';
import {getGptSlotForAdUnitCode} from '../libraries/gptUtils/gptUtils.js';
const MODULE = 'fledgeForGpt';

let getPAAPIConfig;
Expand All @@ -34,9 +35,8 @@ Object.entries({

export function slotConfigurator() {
const PREVIOUSLY_SET = {};
return function setComponentAuction(adUnitCode, auctionConfigs, reset = true) {
const gptSlot = getGptSlotForAdUnitCode(adUnitCode);
if (gptSlot && gptSlot.setConfig) {
return function setComponentAuction(adUnitCode, gptSlots, auctionConfigs, reset = true) {
if (gptSlots.length > 0) {
let previous = PREVIOUSLY_SET[adUnitCode] ?? {};
let configsBySeller = Object.fromEntries(auctionConfigs.map(cfg => [cfg.seller, cfg]));
const sellers = Object.keys(configsBySeller);
Expand All @@ -52,8 +52,10 @@ export function slotConfigurator() {
const componentAuction = Object.entries(configsBySeller)
.map(([configKey, auctionConfig]) => ({configKey, auctionConfig}));
if (componentAuction.length > 0) {
gptSlot.setConfig({componentAuction});
logInfo(MODULE, `register component auction configs for: ${adUnitCode}: ${gptSlot.getAdUnitPath()}`, auctionConfigs);
gptSlots.forEach(gptSlot => {
gptSlot.setConfig({componentAuction});
logInfo(MODULE, `register component auction configs for: ${adUnitCode}: ${gptSlot.getAdUnitPath()}`, auctionConfigs);
});
}
} else if (auctionConfigs.length > 0) {
logWarn(MODULE, `unable to register component auction config for ${adUnitCode}`, auctionConfigs);
Expand All @@ -63,11 +65,11 @@ export function slotConfigurator() {

const setComponentAuction = slotConfigurator();

export function onAuctionConfigFactory(setGptConfig = setComponentAuction) {
export function onAuctionConfigFactory(setGptConfig = setComponentAuction, getSlot = getGptSlotForAdUnitCode) {
return function onAuctionConfig(auctionId, configsByAdUnit, markAsUsed) {
if (autoconfig) {
Object.entries(configsByAdUnit).forEach(([adUnitCode, cfg]) => {
setGptConfig(adUnitCode, cfg?.componentAuctions ?? []);
setGptConfig(adUnitCode, [getSlot(adUnitCode)], cfg?.componentAuctions ?? []);
markAsUsed(adUnitCode);
});
}
Expand Down Expand Up @@ -138,20 +140,22 @@ export const getPAAPISizeHook = (() => {

export function setPAAPIConfigFactory(
getConfig = (filters) => getPAAPIConfig(filters, true),
setGptConfig = setComponentAuction) {
setGptConfig = setComponentAuction,
getSlots = getGPTSlotsForAdUnits) {
/**
* Configure GPT slots with PAAPI auction configs.
* `filters` are the same filters accepted by `pbjs.getPAAPIConfig`;
*/
return function(filters = {}) {
return function(filters = {}, customSlotMatching) {
let some = false;
Object.entries(
getConfig(filters) || {}
).forEach(([au, config]) => {
const cfg = getConfig(filters) || {};
const auToSlots = getSlots(Object.keys(cfg), customSlotMatching);

Object.entries(cfg).forEach(([au, config]) => {
if (config != null) {
some = true;
}
setGptConfig(au, config?.componentAuctions || [], true);
setGptConfig(au, auToSlots[au], config?.componentAuctions || [], true);
})
if (!some) {
logInfo(`${MODULE}: No component auctions available to set`);
Expand Down
60 changes: 33 additions & 27 deletions src/targeting.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {ADPOD} from './mediaTypes.js';
import {hook} from './hook.js';
import {bidderSettings} from './bidderSettings.js';
import {find, includes} from './polyfill.js';
import { BID_STATUS, JSON_MAPPING, DEFAULT_TARGETING_KEYS, TARGETING_KEYS, NATIVE_KEYS, STATUS } from './constants.js';
import {BID_STATUS, DEFAULT_TARGETING_KEYS, JSON_MAPPING, NATIVE_KEYS, STATUS, TARGETING_KEYS} from './constants.js';
import {getHighestCpm, getOldestHighestCpmBid} from './utils/reducers.js';
import {getTTL} from './bidTTL.js';

Expand Down Expand Up @@ -124,6 +124,22 @@ export function sortByDealAndPriceBucketOrCpm(useCpm = false) {
}
}

/**
* Return a map where each code in `adUnitCodes` maps to a list of GPT slots that match it.
*
* @param {Array<String>} adUnitCodes
* @param customSlotMatching
* @param getSlots
* @return {{[p: string]: any}}
*/
export function getGPTSlotsForAdUnits(adUnitCodes, customSlotMatching, getSlots = () => window.googletag.pubads().getSlots()) {
return getSlots().reduce((auToSlots, slot) => {
const customMatch = isFn(customSlotMatching) && customSlotMatching(slot);
Object.keys(auToSlots).filter(isFn(customMatch) ? customMatch : isAdUnitCodeMatchingSlot(slot)).forEach(au => auToSlots[au].push(slot));
return auToSlots;
}, Object.fromEntries(adUnitCodes.map(au => [au, []])));
}

/**
* @typedef {Object.<string,string>} targeting
* @property {string} targeting_key
Expand All @@ -144,22 +160,13 @@ export function newTargeting(auctionManager) {
targeting.resetPresetTargeting = function(adUnitCode, customSlotMatching) {
if (isGptPubadsDefined()) {
const adUnitCodes = getAdUnitCodes(adUnitCode);
const adUnits = auctionManager.getAdUnits().filter(adUnit => includes(adUnitCodes, adUnit.code));
let unsetKeys = pbTargetingKeys.reduce((reducer, key) => {
reducer[key] = null;
return reducer;
}, {});
window.googletag.pubads().getSlots().forEach(slot => {
let customSlotMatchingFunc = isFn(customSlotMatching) && customSlotMatching(slot);
// reset only registered adunits
adUnits.forEach(unit => {
if (unit.code === slot.getAdUnitPath() ||
unit.code === slot.getSlotElementId() ||
(isFn(customSlotMatchingFunc) && customSlotMatchingFunc(unit.code))) {
slot.updateTargetingFromMap(unsetKeys);
}
});
});
Object.values(getGPTSlotsForAdUnits(adUnitCodes, customSlotMatching)).forEach((slots) => {
slots.forEach(slot => slot.updateTargetingFromMap(unsetKeys))
})
}
};

Expand Down Expand Up @@ -420,20 +427,19 @@ export function newTargeting(auctionManager) {
* @param {Object.<string,Object.<string,string>>} targetingConfig
*/
targeting.setTargetingForGPT = function(targetingConfig, customSlotMatching) {
window.googletag.pubads().getSlots().forEach(slot => {
Object.keys(targetingConfig).filter(customSlotMatching ? customSlotMatching(slot) : isAdUnitCodeMatchingSlot(slot))
.forEach(targetId => {
Object.keys(targetingConfig[targetId]).forEach(key => {
let value = targetingConfig[targetId][key];
if (typeof value === 'string' && value.indexOf(',') !== -1) {
// due to the check the array will be formed only if string has ',' else plain string will be assigned as value
value = value.split(',');
}
targetingConfig[targetId][key] = value;
});
logMessage(`Attempting to set targeting-map for slot: ${slot.getSlotElementId()} with targeting-map:`, targetingConfig[targetId]);
slot.updateTargetingFromMap(targetingConfig[targetId])
})
Object.entries(getGPTSlotsForAdUnits(Object.keys(targetingConfig), customSlotMatching)).forEach(([targetId, slots]) => {
slots.forEach(slot => {
Object.keys(targetingConfig[targetId]).forEach(key => {
let value = targetingConfig[targetId][key];
if (typeof value === 'string' && value.indexOf(',') !== -1) {
// due to the check the array will be formed only if string has ',' else plain string will be assigned as value
value = value.split(',');
}
targetingConfig[targetId][key] = value;
});
logMessage(`Attempting to set targeting-map for slot: ${slot.getSlotElementId()} with targeting-map:`, targetingConfig[targetId]);
slot.updateTargetingFromMap(targetingConfig[targetId])
})
})
};

Expand Down
165 changes: 93 additions & 72 deletions test/spec/modules/fledgeForGpt_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import {
setPAAPIConfigFactory,
slotConfigurator
} from 'modules/fledgeForGpt.js';
import * as gptUtils from '../../../libraries/gptUtils/gptUtils.js';
import 'modules/appnexusBidAdapter.js';
import 'modules/rubiconBidAdapter.js';
import {deepSetValue} from '../../../src/utils.js';
Expand All @@ -25,81 +24,94 @@ describe('fledgeForGpt module', () => {
});

describe('slotConfigurator', () => {
let mockGptSlot, setGptConfig;
beforeEach(() => {
mockGptSlot = {
let setGptConfig;
function mockGptSlot(auPath) {
return {
setConfig: sinon.stub(),
getAdUnitPath: () => 'mock/gpt/au'
};
sandbox.stub(gptUtils, 'getGptSlotForAdUnitCode').callsFake(() => mockGptSlot);
getAdUnitPath: () => auPath
}
}
beforeEach(() => {
setGptConfig = slotConfigurator();
});
it('should set GPT slot config', () => {
setGptConfig('au', [fledgeAuctionConfig]);
sinon.assert.calledWith(gptUtils.getGptSlotForAdUnitCode, 'au');
sinon.assert.calledWith(mockGptSlot.setConfig, {
componentAuction: [{
configKey: 'bidder',
auctionConfig: fledgeAuctionConfig,
}]
});
});

describe('when reset = true', () => {
it('should reset GPT slot config', () => {
setGptConfig('au', [fledgeAuctionConfig]);
mockGptSlot.setConfig.resetHistory();
gptUtils.getGptSlotForAdUnitCode.resetHistory();
setGptConfig('au', [], true);
sinon.assert.calledWith(gptUtils.getGptSlotForAdUnitCode, 'au');
sinon.assert.calledWith(mockGptSlot.setConfig, {
componentAuction: [{
configKey: 'bidder',
auctionConfig: null
}]
Object.entries({
'single slot': [mockGptSlot('mock/gpt/au')],
'multiple slots': [mockGptSlot('mock/gpt/au'), mockGptSlot('mock/gpt/au2')]
}).forEach(([t, gptSlots]) => {
describe(`when ad unit code matches ${t}`, () => {
it('should set GPT slot config', () => {
setGptConfig('au', gptSlots, [fledgeAuctionConfig]);
gptSlots.forEach(slot => {
sinon.assert.calledWith(slot.setConfig, {
componentAuction: [{
configKey: 'bidder',
auctionConfig: fledgeAuctionConfig,
}]
});
})
});
});
describe('when reset = true', () => {
it('should reset GPT slot config', () => {
setGptConfig('au', gptSlots, [fledgeAuctionConfig]);
gptSlots.forEach(slot => slot.setConfig.resetHistory());
setGptConfig('au', gptSlots, [], true);
gptSlots.forEach(slot => {
sinon.assert.calledWith(slot.setConfig, {
componentAuction: [{
configKey: 'bidder',
auctionConfig: null
}]
});
})
});

it('should reset only sellers with no fresh config', () => {
setGptConfig('au', [{seller: 's1'}, {seller: 's2'}]);
mockGptSlot.setConfig.resetHistory();
setGptConfig('au', [{seller: 's1'}], true);
sinon.assert.calledWith(mockGptSlot.setConfig, {
componentAuction: [{
configKey: 's1',
auctionConfig: {seller: 's1'}
}, {
configKey: 's2',
auctionConfig: null
}]
})
});
it('should reset only sellers with no fresh config', () => {
setGptConfig('au', gptSlots, [{seller: 's1'}, {seller: 's2'}]);
gptSlots.forEach(slot => slot.setConfig.resetHistory());
setGptConfig('au', gptSlots, [{seller: 's1'}], true);
gptSlots.forEach(slot => {
sinon.assert.calledWith(slot.setConfig, {
componentAuction: [{
configKey: 's1',
auctionConfig: {seller: 's1'}
}, {
configKey: 's2',
auctionConfig: null
}]
})
})
});

it('should not reset sellers that were already reset', () => {
setGptConfig('au', [{seller: 's1'}]);
setGptConfig('au', [], true);
mockGptSlot.setConfig.resetHistory();
setGptConfig('au', [], true);
sinon.assert.notCalled(mockGptSlot.setConfig);
})
it('should not reset sellers that were already reset', () => {
setGptConfig('au', gptSlots, [{seller: 's1'}]);
setGptConfig('au', gptSlots, [], true);
gptSlots.forEach(slot => slot.setConfig.resetHistory());
setGptConfig('au', gptSlots, [], true);
gptSlots.forEach(slot => sinon.assert.notCalled(slot.setConfig));
})

it('should keep track of configuration history by slot', () => {
setGptConfig('au1', [{seller: 's1'}]);
setGptConfig('au1', [{seller: 's2'}], false);
setGptConfig('au2', [{seller: 's3'}]);
mockGptSlot.setConfig.resetHistory();
setGptConfig('au1', [], true);
sinon.assert.calledWith(mockGptSlot.setConfig, {
componentAuction: [{
configKey: 's1',
auctionConfig: null
}, {
configKey: 's2',
auctionConfig: null
}]
it('should keep track of configuration history by ad unit', () => {
setGptConfig('au1', gptSlots, [{seller: 's1'}]);
setGptConfig('au1', gptSlots, [{seller: 's2'}], false);
setGptConfig('au2', gptSlots, [{seller: 's3'}]);
gptSlots.forEach(slot => slot.setConfig.resetHistory());
setGptConfig('au1', gptSlots, [], true);
gptSlots.forEach(slot => {
sinon.assert.calledWith(slot.setConfig, {
componentAuction: [{
configKey: 's1',
auctionConfig: null
}, {
configKey: 's2',
auctionConfig: null
}]
});
})
})
});
})
});
})
});
describe('onAuctionConfig', () => {
[
Expand All @@ -124,12 +136,14 @@ describe('fledgeForGpt module', () => {

it(`should ${shouldSetConfig ? '' : 'NOT'} set GPT slot configuration`, () => {
const auctionConfig = {componentAuctions: [{seller: 'mock1'}, {seller: 'mock2'}]};
const mockSlot = {};
const getSlot = sinon.stub().returns({});
const setGptConfig = sinon.stub();
const markAsUsed = sinon.stub();
onAuctionConfigFactory(setGptConfig)('aid', {au1: auctionConfig, au2: null}, markAsUsed);
onAuctionConfigFactory(setGptConfig, getSlot)('aid', {au1: auctionConfig, au2: null}, markAsUsed);
if (shouldSetConfig) {
sinon.assert.calledWith(setGptConfig, 'au1', auctionConfig.componentAuctions);
sinon.assert.calledWith(setGptConfig, 'au2', []);
sinon.assert.calledWith(setGptConfig, 'au1', [mockSlot], auctionConfig.componentAuctions);
sinon.assert.calledWith(setGptConfig, 'au2', [mockSlot], []);
sinon.assert.calledWith(markAsUsed, 'au1');
} else {
sinon.assert.notCalled(setGptConfig);
Expand All @@ -142,11 +156,12 @@ describe('fledgeForGpt module', () => {
})
});
describe('setPAAPIConfigForGpt', () => {
let getPAAPIConfig, setGptConfig, setPAAPIConfigForGPT;
let getPAAPIConfig, setGptConfig, getSlots, setPAAPIConfigForGPT;
beforeEach(() => {
getPAAPIConfig = sinon.stub();
setGptConfig = sinon.stub();
setPAAPIConfigForGPT = setPAAPIConfigFactory(getPAAPIConfig, setGptConfig);
getSlots = sinon.stub().callsFake((codes) => Object.fromEntries(codes.map(code => [code, ['mock-slot']])))
setPAAPIConfigForGPT = setPAAPIConfigFactory(getPAAPIConfig, setGptConfig, getSlots);
});

Object.entries({
Expand All @@ -161,6 +176,12 @@ describe('fledgeForGpt module', () => {
})
});

it('passes customSlotMatching to getSlots', () => {
getPAAPIConfig.returns({au1: {}});
setPAAPIConfigForGPT('mock-filters', 'mock-custom-matching');
sinon.assert.calledWith(getSlots, ['au1'], 'mock-custom-matching');
})

it('sets GPT slot config for each ad unit that has PAAPI config, and resets the rest', () => {
const cfg = {
au1: {
Expand All @@ -175,7 +196,7 @@ describe('fledgeForGpt module', () => {
setPAAPIConfigForGPT('mock-filters');
sinon.assert.calledWith(getPAAPIConfig, 'mock-filters');
Object.entries(cfg).forEach(([au, config]) => {
sinon.assert.calledWith(setGptConfig, au, config?.componentAuctions ?? [], true);
sinon.assert.calledWith(setGptConfig, au, ['mock-slot'], config?.componentAuctions ?? [], true);
})
});
});
Expand Down
Loading