Skip to content
Open
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
241 changes: 241 additions & 0 deletions src/main/java/org/prebid/server/bidder/hypelab/HypeLabBidder.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
package org.prebid.server.bidder.hypelab;

import com.fasterxml.jackson.databind.JsonNode;
import com.iab.openrtb.request.BidRequest;
import com.iab.openrtb.request.Imp;
import com.iab.openrtb.response.Bid;
import com.iab.openrtb.response.BidResponse;
import com.iab.openrtb.response.SeatBid;
import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpMethod;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.prebid.server.bidder.Bidder;
import org.prebid.server.bidder.model.BidderBid;
import org.prebid.server.bidder.model.BidderCall;
import org.prebid.server.bidder.model.BidderError;
import org.prebid.server.bidder.model.HttpRequest;
import org.prebid.server.bidder.model.Result;
import org.prebid.server.exception.PreBidException;
import org.prebid.server.json.DecodeException;
import org.prebid.server.json.JacksonMapper;
import org.prebid.server.proto.openrtb.ext.ExtPrebid;
import org.prebid.server.proto.openrtb.ext.request.ExtRequest;
import org.prebid.server.proto.openrtb.ext.request.hypelab.ExtImpHypeLab;
import org.prebid.server.proto.openrtb.ext.response.BidType;
import org.prebid.server.util.BidderUtil;
import org.prebid.server.util.HttpUtil;
import org.prebid.server.version.PrebidVersionProvider;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class HypeLabBidder implements Bidder<BidRequest> {

private static final String DISPLAY_MANAGER = "HypeLab Prebid Server";
private static final String SOURCE = "prebid-server";
private static final String UNKNOWN_VERSION = "unknown";

private final String endpointUrl;
private final JacksonMapper mapper;
private final PrebidVersionProvider prebidVersionProvider;

public HypeLabBidder(String endpointUrl, JacksonMapper mapper, PrebidVersionProvider prebidVersionProvider) {
this.endpointUrl = HttpUtil.validateUrl(Objects.requireNonNull(endpointUrl));
this.mapper = Objects.requireNonNull(mapper);
this.prebidVersionProvider = Objects.requireNonNull(prebidVersionProvider);
}

@Override
public Result<List<HttpRequest<BidRequest>>> makeHttpRequests(BidRequest request) {
final List<BidderError> errors = new ArrayList<>();
final List<Imp> validImps = new ArrayList<>();

for (Imp imp : request.getImp()) {
try {
validImps.add(makeOutgoingImp(imp));
} catch (PreBidException e) {
errors.add(BidderError.badInput(e.getMessage()));
}
}

if (validImps.isEmpty()) {
return Result.of(Collections.emptyList(), errors);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Result.withErrors

}

final BidRequest outgoingRequest = request.toBuilder()
.imp(validImps)
.ext(makeOutgoingRequestExt(request.getExt()))
.build();

return Result.of(Collections.singletonList(
HttpRequest.<BidRequest>builder()
.method(HttpMethod.POST)
.uri(endpointUrl)
.headers(headers())
.impIds(BidderUtil.impIds(outgoingRequest))
.body(mapper.encodeToBytes(outgoingRequest))
.payload(outgoingRequest)
.build()),
errors);
Comment on lines +76 to +85
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use BidderUtil.defaultRequest

}

private Imp makeOutgoingImp(Imp imp) {
final ExtImpHypeLab extImp = parseImpExt(imp);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move parsing out of this method

final String pbsVersion = pbsVersion();

return imp.toBuilder()
.tagid(extImp.getPlacementSlug())
.displaymanager(DISPLAY_MANAGER)
.displaymanagerver(pbsVersion)
.ext(mapper.mapper().valueToTree(ExtPrebid.of(null, extImp)))
.build();
}

private ExtImpHypeLab parseImpExt(Imp imp) {
if (imp.getExt() == null) {
throw new PreBidException("imp %s: unable to unmarshal ext".formatted(imp.getId()));
}

final JsonNode bidderNode = imp.getExt().get("bidder");
if (bidderNode == null || bidderNode.isNull()) {
throw new PreBidException("imp %s: unable to unmarshal ext.bidder".formatted(imp.getId()));
}
Comment on lines +101 to +108
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for this checks


final ExtImpHypeLab extImp;
try {
extImp = mapper.mapper().convertValue(bidderNode, ExtImpHypeLab.class);
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use TypeReference<ExtPrebid<?, ExtImpHypeLab>> instead

} catch (IllegalArgumentException e) {
throw new PreBidException("imp %s: unable to unmarshal ext.bidder".formatted(imp.getId()), e);
}

if (StringUtils.isBlank(extImp.getPropertySlug()) || StringUtils.isBlank(extImp.getPlacementSlug())) {
throw new PreBidException("imp %s: property_slug and placement_slug are required".formatted(imp.getId()));
}

return extImp;
}

private ExtRequest makeOutgoingRequestExt(ExtRequest ext) {
final ExtRequest outgoingExt = ext != null ? ExtRequest.of(ext.getPrebid()) : ExtRequest.empty();
if (ext != null) {
outgoingExt.addProperties(ext.getProperties());
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use mapper.fillExtension instead

}

outgoingExt.addProperty("source", mapper.mapper().valueToTree(SOURCE));
outgoingExt.addProperty("provider_version", mapper.mapper().valueToTree(pbsVersion()));
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see the difference with GO version. You didn't append prebid-server@ prefix


return outgoingExt;
}

private static MultiMap headers() {
return HttpUtil.headers()
.add(HttpUtil.X_OPENRTB_VERSION_HEADER, "2.6");
}

@Override
public Result<List<BidderBid>> makeBids(BidderCall<BidRequest> httpCall, BidRequest bidRequest) {
final BidResponse bidResponse;
try {
bidResponse = mapper.decodeValue(httpCall.getResponse().getBody(), BidResponse.class);
} catch (DecodeException e) {
return Result.withError(BidderError.badServerResponse(e.getMessage()));
}

final List<BidderError> errors = new ArrayList<>();
return Result.of(extractBids(httpCall.getRequest().getPayload(), bidResponse, errors), errors);
}

private static List<BidderBid> extractBids(BidRequest request, BidResponse response, List<BidderError> errors) {
if (response == null || CollectionUtils.isEmpty(response.getSeatbid())) {
return Collections.emptyList();
}

final Map<String, Imp> impIdToImp = request.getImp().stream()
.collect(Collectors.toMap(Imp::getId, imp -> imp));

return response.getSeatbid().stream()
.filter(Objects::nonNull)
.map(seatBid -> bidsFromSeatBid(seatBid, impIdToImp, response.getCur(), errors))
.flatMap(Collection::stream)
.toList();
}

private static List<BidderBid> bidsFromSeatBid(SeatBid seatBid, Map<String, Imp> impIdToImp, String currency,
List<BidderError> errors) {

final List<Bid> bids = seatBid.getBid();
if (CollectionUtils.isEmpty(bids)) {
return Collections.emptyList();
}

return bids.stream()
.filter(Objects::nonNull)
.map(bid -> makeBidderBid(bid, seatBid.getSeat(), impIdToImp, currency, errors))
.filter(Objects::nonNull)
.toList();
}

Comment on lines +154 to +183
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

    private static List<BidderBid> extractBids(BidRequest request, BidResponse response, List<BidderError> errors) {
        if (response == null || CollectionUtils.isEmpty(response.getSeatbid())) {
            return Collections.emptyList();
        }

        final Map<String, Imp> impIdToImp = request.getImp().stream()
                .collect(Collectors.toMap(Imp::getId, imp -> imp));

        return response.getSeatbid().stream()
                .filter(Objects::nonNull)
                .flatMap(seatBid -> CollectionUtils.emptyIfNull(seatBid.getBid()).stream()
                        .filter(Objects::nonNull)
                        .map(bid -> makeBidderBid(bid, seatBid.getSeat(), impIdToImp, response.getCur(), errors))
                        .filter(Objects::nonNull))
                .toList();
    }

    private static BidderBid makeBidderBid(Bid bid,
                                           String seat,
                                           Map<String, Imp> impIdToImp, String currency,
                                           List<BidderError> errors) {

        try {
            return BidderBid.of(bid, resolveBidType(bid, impIdToImp), seat, currency);
        } catch (PreBidException e) {
            errors.add(BidderError.badServerResponse(e.getMessage()));
            return null;
        }
    }

    private static BidType resolveBidType(Bid bid, Map<String, Imp> impIdToImp) {
        return bidTypeFromMtype(bid.getMtype())
                .or(() -> bidTypeFromExt(bid))
                .or(() -> bidTypeFromAdm(bid.getAdm()))
                .or(() -> bidTypeFromImp(bid, impIdToImp))
                .orElseThrow(() -> new PreBidException("unable to determine media type for bid %s on imp %s"
                        .formatted(bid.getId(), bid.getImpid())));
    }

    private static Optional<BidType> bidTypeFromMtype(Integer mtype) {
        return Optional.ofNullable(switch (mtype) {
            case 1 -> BidType.banner;
            case 2 -> BidType.video;
            case 4 -> BidType.xNative;
            case null, default -> null;
        });
    }

    private static Optional<BidType> bidTypeFromExt(Bid bid) {
        return Optional.ofNullable(bid.getExt())
                .map(ext -> ext.get("hypelab"))
                .map(hypelab -> hypelab.get("creative_type"))
                .filter(JsonNode::isTextual)
                .map(JsonNode::asText)
                .map(creativeType -> switch (creativeType) {
                    case "display" -> BidType.banner;
                    case "video" -> BidType.video;
                    default -> null;
                });
    }

    private static Optional<BidType> bidTypeFromAdm(String adm) {
        return StringUtils.startsWith(StringUtils.trimToEmpty(adm), "<VAST")
                ? Optional.of(BidType.video)
                : Optional.empty();
    }

    private static Optional<BidType> bidTypeFromImp(Bid bid, Map<String, Imp> impIdToImp) {
        return impIdToImp.containsKey(bid.getImpid())
                ? Optional.of(BidderUtil.getBidType(bid, impIdToImp))
                : Optional.empty();
    }

private static BidderBid makeBidderBid(Bid bid, String seat, Map<String, Imp> impIdToImp, String currency,
List<BidderError> errors) {

try {
return BidderBid.of(bid, resolveBidType(bid, impIdToImp), seat, currency);
} catch (PreBidException e) {
errors.add(BidderError.badServerResponse(e.getMessage()));
return null;
}
}

private static BidType resolveBidType(Bid bid, Map<String, Imp> impIdToImp) {
final BidType bidTypeFromMtype = bidTypeFromMtype(bid.getMtype());
if (bidTypeFromMtype != null) {
return bidTypeFromMtype;
}

final BidType bidTypeFromExt = bidTypeFromExt(bid);
if (bidTypeFromExt != null) {
return bidTypeFromExt;
}

if (StringUtils.startsWith(StringUtils.trimToEmpty(bid.getAdm()), "<VAST")) {
return BidType.video;
}

if (impIdToImp.containsKey(bid.getImpid())) {
return BidderUtil.getBidType(bid, impIdToImp);
}
Comment on lines +210 to +212
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GO doesn't support multi-media imps: mediaTypeCount == 1


throw new PreBidException("unable to determine media type for bid %s on imp %s"
.formatted(bid.getId(), bid.getImpid()));
}

private static BidType bidTypeFromMtype(Integer mtype) {
return switch (Objects.requireNonNullElse(mtype, 0)) {
case 1 -> BidType.banner;
case 2 -> BidType.video;
case 4 -> BidType.xNative;
default -> null;
};
}

private static BidType bidTypeFromExt(Bid bid) {
final JsonNode hypelabExt = bid.getExt() != null ? bid.getExt().get("hypelab") : null;
final String creativeType = hypelabExt != null ? hypelabExt.path("creative_type").asText() : null;

return switch (StringUtils.defaultString(creativeType)) {
case "display" -> BidType.banner;
case "video" -> BidType.video;
default -> null;
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GO version have native case:

	case "native":
		return openrtb_ext.BidTypeNative, true, nil

};
}

private String pbsVersion() {
return StringUtils.defaultIfBlank(prebidVersionProvider.getNameVersionRecord(), UNKNOWN_VERSION);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package org.prebid.server.proto.openrtb.ext.request.hypelab;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Value;

@Value(staticConstructor = "of")
public class ExtImpHypeLab {

@JsonProperty("property_slug")
String propertySlug;

@JsonProperty("placement_slug")
String placementSlug;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package org.prebid.server.spring.config.bidder;

import org.prebid.server.bidder.BidderDeps;
import org.prebid.server.bidder.hypelab.HypeLabBidder;
import org.prebid.server.json.JacksonMapper;
import org.prebid.server.spring.config.bidder.model.BidderConfigurationProperties;
import org.prebid.server.spring.config.bidder.util.BidderDepsAssembler;
import org.prebid.server.spring.config.bidder.util.UsersyncerCreator;
import org.prebid.server.spring.env.YamlPropertySourceFactory;
import org.prebid.server.version.PrebidVersionProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import jakarta.validation.constraints.NotBlank;

@Configuration
@PropertySource(value = "classpath:/bidder-config/hypelab.yaml", factory = YamlPropertySourceFactory.class)
public class HypeLabConfiguration {

private static final String BIDDER_NAME = "hypelab";

@Bean("hypelabConfigurationProperties")
@ConfigurationProperties("adapters.hypelab")
BidderConfigurationProperties configurationProperties() {
return new BidderConfigurationProperties();
}

@Bean
BidderDeps hypelabBidderDeps(BidderConfigurationProperties hypelabConfigurationProperties,
@NotBlank @Value("${external-url}") String externalUrl,
PrebidVersionProvider prebidVersionProvider,
JacksonMapper mapper) {

return BidderDepsAssembler.forBidder(BIDDER_NAME)
.withConfig(hypelabConfigurationProperties)
.usersyncerCreator(UsersyncerCreator.create(externalUrl))
.bidderCreator(config -> new HypeLabBidder(
config.getEndpoint(),
mapper,
prebidVersionProvider))
.assemble();
}
}
21 changes: 21 additions & 0 deletions src/main/resources/bidder-config/hypelab.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
adapters:
hypelab:
endpoint: https://api.hypelab.com/v1/rtb_requests
ortb-version: "2.6"
aliases:
hype: ~
meta-info:
maintainer-email: sdk@hypelab.com
app-media-types: []
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to declare empty app-media-types

site-media-types:
- banner
- native
- video
supported-vendors:
vendor-id: 0
usersync:
cookie-family-name: hypelab
redirect:
url: https://api.hypelab.com/v1/i?redirect_url={{redirect_url}}&gdpr={{gdpr}}&gdpr_consent={{gdpr_consent}}&us_privacy={{us_privacy}}&gpp={{gpp}}&gpp_sid={{gpp_sid}}
support-cors: false
uid-macro: '$UID'
19 changes: 19 additions & 0 deletions src/main/resources/static/bidder-params/hypelab.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "HypeLab Adapter Params",
"description": "A schema which validates params accepted by the HypeLab adapter",
"type": "object",
"properties": {
"property_slug": {
"type": "string",
"minLength": 1,
"description": "HypeLab property slug"
},
"placement_slug": {
"type": "string",
"minLength": 1,
"description": "HypeLab placement slug"
}
},
"required": ["property_slug", "placement_slug"]
}
Loading