Skip to content
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
1 change: 1 addition & 0 deletions modules/.submodules.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
"mediafilterRtdProvider",
"medianetRtdProvider",
"mgidRtdProvider",
"mileRtdProvider",
"mobianRtdProvider",
"neuwoRtdProvider",
"nodalsAiRtdProvider",
Expand Down
67 changes: 67 additions & 0 deletions modules/mileRtdProvider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Mile RTD Provider

## Overview

The `mile` RTD provider computes per-slot targeting values through a runtime engine and sets GPT slot targeting used by GAM unified Pricing rules.

It sets a single targeting key:

- `mile_rtd`

The value is provider-specific and is returned by `window[params.runtimeGlobalName].getMileTargetingByAdUnit(...)`

## When targeting is applied

Targeting is applied during:

- `onAuctionInitEvent`
- `onBidResponseEvent`


## Key-value mapping

The runtime engine returns a map keyed by ad unit identifier (slot element ID or ad unit path), and each resolved slot gets:

- key: `mile_rtd`
- value: `targetingByAdUnit[slotElementId]` or `targetingByAdUnit[adUnitPath]`

Example runtime response:

```js
{
"div-gpt-ad-123": "segA_floorHigh",
"/1234567/homepage/top": "segB_floorMid"
}
```

Resulting GPT slot targeting:

```js
slot.setTargeting("mile_rtd", "segA_floorHigh");
```

## Configuration

Use the RTD module with provider name `mile`:

```js
pbjs.setConfig({
realTimeData: {
dataProviders: [
{
name: "mile",
waitForIt: false,
params: {
runtimeScriptUrl: "https://cdn.example.com/mile-rtd-runtime.js",
runtimeGlobalName: "mileRtdRuntime", // optional, default shown
},
},
],
},
});
```

### Params

- `runtimeScriptUrl` (optional): URL of runtime script to load.
- `runtimeGlobalName` (optional): global object name exposing `getMileTargetingByAdUnit`; defaults to `mileRtdRuntime`.
264 changes: 264 additions & 0 deletions modules/mileRtdProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
/**
* Thin Mile RTD client.
* Pulls pre-hashed targeting values from runtime global and merges them into
* ad unit adserver targeting.
*/
import { submodule } from '../src/hook.js';
import { loadExternalScript } from '../src/adloader.js';
import { MODULE_TYPE_RTD } from '../src/activities/modules.js';
import { auctionManager } from '../src/auctionManager.js';
import { logError, logInfo } from '../src/utils.js';
import type { Bid } from '../src/bidfactory.ts';
import type { AllConsentData } from '../src/consentHandler.ts';
import type { RTDProviderConfig, RtdProviderSpec } from './rtdModule/spec.ts';

type ModuleParams = {
runtimeScriptUrl?: string;
runtimeGlobalName?: string;
};

declare module './rtdModule/spec' {
interface ProviderConfig {
mile: {
params?: ModuleParams;
};
}
}

type TargetingValue = string | number | boolean | Array<string | number | boolean>;
type TargetingByAdUnit = Record<string, TargetingValue>;
type RuntimeContext = {
mode: 'auctionInit' | 'bidResponse';
bidResponse?: Bid;
};

type AuctionSnapshot = {
adUnitCodes: string[];
[key: string]: unknown;
};

type AuctionDetails = AuctionSnapshot & {
adUnits: unknown[];
bidderRequests: unknown[];
bidsReceived: unknown[];
};

type AuctionLike = {
getAdUnitCodes?: () => string[];
getAdUnits?: () => unknown[];
getBidRequests?: () => unknown[];
getBidsReceived?: () => unknown[];
};

type AdUnitLike = {
code?: string;
ortb2Imp?: {
ext?: {
gpid?: string;
data?: {
pbadslot?: string;
};
};
};
adserverTargeting?: Record<string, TargetingValue>;
};

type MileRuntimeEngine = {
getMileTargetingByAdUnit: (
auctionSnapshot: AuctionSnapshot,
context: RuntimeContext
) => TargetingByAdUnit | null | Promise<TargetingByAdUnit | null>;
};

type ExtractAuctionSnapshot = (auctionDetails: AuctionDetails) => AuctionSnapshot;

type MileRuntimeUtils = {
extractAuctionSnapshot?: ExtractAuctionSnapshot;
};
type MileRtdProviderSpec = RtdProviderSpec<'mile'> & {
onAuctionInitEvent?: (auctionDetails: Partial<AuctionDetails>) => void;
onBidResponseEvent?: (
bidResponse: Partial<Bid>,
config: RTDProviderConfig<'mile'>,
userConsent: AllConsentData
) => void;
};

const MODULE_NAME = 'realTimeData';
const SUBMODULE_NAME = 'mile';
const TARGETING_KEY = 'mile_rtd';
const LOG_PREFIX = '[mileRtdProvider]';
const DEFAULT_ENGINE_GLOBAL = 'mileRtdRuntime';

let moduleParams: ModuleParams = {};
let engineLoadPromise: Promise<boolean> | null = null;

function isRuntimeEngine(value: unknown): value is MileRuntimeEngine {
return !!value && typeof (value as MileRuntimeEngine).getMileTargetingByAdUnit === 'function';
}

function getRuntimeEngine(): MileRuntimeEngine | null {
const globalName = moduleParams.runtimeGlobalName || DEFAULT_ENGINE_GLOBAL;
const runtimeEngine = (window as unknown as Record<string, unknown>)?.[globalName];
return isRuntimeEngine(runtimeEngine) ? runtimeEngine : null;
}

export function loadRuntimeScript(): Promise<boolean> {
if (engineLoadPromise) return engineLoadPromise;
const runtimeScriptUrl = moduleParams.runtimeScriptUrl;
if (!runtimeScriptUrl) return Promise.resolve(false);

engineLoadPromise = new Promise<boolean>((resolve) => {
loadExternalScript(runtimeScriptUrl, MODULE_TYPE_RTD, SUBMODULE_NAME, () => {
Comment thread
patmmccann marked this conversation as resolved.
logInfo(LOG_PREFIX, 'runtime script loaded', runtimeScriptUrl);
resolve(true);
}, undefined, undefined);
}).catch((error: unknown) => {
logError(LOG_PREFIX, 'unable to load runtime script', error);
engineLoadPromise = null;
return false;
});
return engineLoadPromise;
}

export function getTargetingFromRuntime(
auctionSnapshot: AuctionSnapshot,
context: RuntimeContext = { mode: 'auctionInit' }
): Promise<TargetingByAdUnit | null> {
const runtimeEngine = getRuntimeEngine();
if (!runtimeEngine) {
logInfo(LOG_PREFIX, 'runtime engine missing getMileTargetingByAdUnit()');
return Promise.resolve(null);
}
try {
return Promise.resolve(runtimeEngine.getMileTargetingByAdUnit(auctionSnapshot, context));
} catch (error: unknown) {
logError(LOG_PREFIX, 'runtime engine failed while computing targeting', error);
return Promise.resolve(null);
}
}

function getAdUnitTargetingValue(adUnit: AdUnitLike, targetingByAdUnit: TargetingByAdUnit): TargetingValue | null {
const targetingIdentifiers = [
adUnit.code,
adUnit.ortb2Imp?.ext?.gpid,
adUnit.ortb2Imp?.ext?.data?.pbadslot,
];

for (const identifier of targetingIdentifiers) {
if (identifier != null && targetingByAdUnit[identifier] != null) {
return targetingByAdUnit[identifier];
}
}

return null;
}

export function setAdUnitTargeting(
targetingByAdUnit: TargetingByAdUnit,
adUnits: AdUnitLike[] = []
): boolean {
if (!adUnits.length) {
logInfo(LOG_PREFIX, 'auction ad units are unavailable, skipping adserver targeting');
return false;
}

let appliedTargeting = false;
adUnits.forEach((adUnit) => {
const targetingValue = getAdUnitTargetingValue(adUnit, targetingByAdUnit);
if (targetingValue == null) return;

adUnit.adserverTargeting = Object.assign(adUnit.adserverTargeting || {}, {
[TARGETING_KEY]: targetingValue,
});
appliedTargeting = true;
});

return appliedTargeting;
}

function buildAuctionDetailsFromAuction(auction: AuctionLike | undefined): AuctionDetails {
return {
adUnitCodes: auction?.getAdUnitCodes?.() || [],
adUnits: auction?.getAdUnits?.() || [],
bidderRequests: auction?.getBidRequests?.() || [],
bidsReceived: auction?.getBidsReceived?.() || [],
};
}

function extractAuctionSnapshot(auctionDetails: AuctionDetails): AuctionSnapshot {
const extractSnapshot = ((window as unknown as { mileRtdRuntimeUtils?: MileRuntimeUtils }).mileRtdRuntimeUtils)?.extractAuctionSnapshot;
if (typeof extractSnapshot === 'function') {
return extractSnapshot(auctionDetails);
}
return { adUnitCodes: auctionDetails.adUnitCodes || [] };
}

function applyRuntimeTargeting(
auctionSnapshot: AuctionSnapshot,
context: RuntimeContext,
adUnits: AdUnitLike[] = []
): Promise<void> {
return getTargetingFromRuntime(auctionSnapshot, context).then((targetingByAdUnit) => {
if (targetingByAdUnit && Object.keys(targetingByAdUnit).length > 0) {
setAdUnitTargeting(targetingByAdUnit, adUnits);
}
});
}

export function onAuctionInitEvent(auctionDetails: Partial<AuctionDetails> = {}): void {
const snapshotDetails = auctionDetails.adUnitCodes?.length
? (auctionDetails as AuctionDetails)
: buildAuctionDetailsFromAuction(
auctionManager.index.getAuction({ auctionId: auctionManager.getLastAuctionId() }) as AuctionLike
);
if (!snapshotDetails.adUnitCodes?.length) return;
const auctionSnapshot = extractAuctionSnapshot(snapshotDetails);
applyRuntimeTargeting(auctionSnapshot, { mode: 'auctionInit' }, snapshotDetails.adUnits as AdUnitLike[]);
}

export function onBidResponseEvent(
bidResponse: Partial<Bid>,
_config: RTDProviderConfig<'mile'>,
_userConsent: AllConsentData,
auctionDetailsOverride?: Partial<AuctionDetails>
): void {
const adUnitCode = bidResponse?.adUnitCode;
if (!adUnitCode) return;
const auctionDetails = auctionDetailsOverride || buildAuctionDetailsFromAuction(auctionManager.index.getAuction(bidResponse) as AuctionLike);
const auctionSnapshot = extractAuctionSnapshot(auctionDetails as AuctionDetails);
if (!auctionSnapshot.adUnitCodes?.includes(adUnitCode)) {
auctionSnapshot.adUnitCodes = [...(auctionSnapshot.adUnitCodes || []), adUnitCode];
}
applyRuntimeTargeting(
auctionSnapshot,
{ mode: 'bidResponse', bidResponse: bidResponse as Bid },
auctionDetails.adUnits as AdUnitLike[]
);
}

export function init(moduleConfig: RTDProviderConfig<'mile'>): boolean {
moduleParams = moduleConfig?.params || {};
if (moduleParams.runtimeScriptUrl) {
loadRuntimeScript();
} else {
logInfo(LOG_PREFIX, 'runtimeScriptUrl not provided; runtime script will not load');
}
return true;
}

export const mileRtdSubmodule: MileRtdProviderSpec = {
name: SUBMODULE_NAME,
init,
onAuctionInitEvent,
onBidResponseEvent: (bidResponse, config, userConsent) => onBidResponseEvent(bidResponse, config, userConsent),
};

export const __testing__ = {
setModuleParams(params?: ModuleParams): void {
moduleParams = params || {};
engineLoadPromise = null;
},
};

submodule(MODULE_NAME, mileRtdSubmodule);
1 change: 1 addition & 0 deletions plugins/eslint/approvedLoadExternalScriptPaths.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ const APPROVED_LOAD_EXTERNAL_SCRIPT_PATHS = [
'modules/optableRtdProvider.js',
'modules/oftmediaRtdProvider.js',
'modules/panxoRtdProvider.js',
'modules/mileRtdProvider.ts',
// UserId Submodules
'modules/justIdSystem.js',
'modules/tncIdSystem.js',
Expand Down
Loading
Loading