diff --git a/src/main/java/org/prebid/server/bidder/insticator/InsticatorBidder.java b/src/main/java/org/prebid/server/bidder/insticator/InsticatorBidder.java new file mode 100644 index 00000000000..562dd763473 --- /dev/null +++ b/src/main/java/org/prebid/server/bidder/insticator/InsticatorBidder.java @@ -0,0 +1,266 @@ +package org.prebid.server.bidder.insticator; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.iab.openrtb.request.App; +import com.iab.openrtb.request.BidRequest; +import com.iab.openrtb.request.Device; +import com.iab.openrtb.request.Imp; +import com.iab.openrtb.request.Publisher; +import com.iab.openrtb.request.Site; +import com.iab.openrtb.request.Video; +import com.iab.openrtb.response.Bid; +import com.iab.openrtb.response.BidResponse; +import com.iab.openrtb.response.SeatBid; +import io.vertx.core.MultiMap; +import org.apache.commons.collections4.CollectionUtils; +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.Price; +import org.prebid.server.bidder.model.Result; +import org.prebid.server.currency.CurrencyConversionService; +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.insticator.ExtImpInsticator; +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.util.ObjectUtil; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public class InsticatorBidder implements Bidder { + + private static final TypeReference> TYPE_REFERENCE = new TypeReference<>() { + }; + + private static final String DEFAULT_BIDDER_CURRENCY = "USD"; + private static final String INSTICATOR_FIELD = "insticator"; + private static final InsticatorExtRequestCaller DEFAULT_INSTICATOR_CALLER = + InsticatorExtRequestCaller.of("Prebid-Server", "n/a"); + + private final CurrencyConversionService currencyConversionService; + private final String endpointUrl; + private final JacksonMapper mapper; + + public InsticatorBidder(CurrencyConversionService currencyConversionService, + String endpointUrl, + JacksonMapper mapper) { + + this.currencyConversionService = Objects.requireNonNull(currencyConversionService); + this.endpointUrl = HttpUtil.validateUrl(Objects.requireNonNull(endpointUrl)); + this.mapper = Objects.requireNonNull(mapper); + } + + @Override + public Result>> makeHttpRequests(BidRequest request) { + final Map> groupedImps = new HashMap<>(); + final List errors = new ArrayList<>(); + + String publisherId = null; + + for (Imp imp : request.getImp()) { + try { + validateImp(imp); + final ExtImpInsticator extImp = parseImpExt(imp); + + if (publisherId == null) { + publisherId = extImp.getPublisherId(); + } + + final Imp modifiedImp = modifyImp(request, imp, extImp); + groupedImps.computeIfAbsent(extImp.getAdUnitId(), key -> new ArrayList<>()).add(modifiedImp); + } catch (PreBidException e) { + errors.add(BidderError.badInput(e.getMessage())); + } + } + + final BidRequest modifiedRequest = modifyRequest(request, publisherId, errors); + final List> requests = groupedImps.values().stream() + .map(imps -> modifiedRequest.toBuilder().imp(imps).build()) + .map(finalRequest -> BidderUtil.defaultRequest( + finalRequest, + makeHeaders(finalRequest.getDevice()), + endpointUrl, + mapper)) + .toList(); + + return Result.of(requests, errors); + } + + private void validateImp(Imp imp) { + final Video video = imp.getVideo(); + if (video == null) { + return; + } + + if (isInvalidDimension(video.getH()) + || isInvalidDimension(video.getW()) + || CollectionUtils.isNotEmpty(video.getMimes())) { + + throw new PreBidException("One or more invalid or missing video field(s) w, h, mimes"); + } + } + + private static boolean isInvalidDimension(Integer dimension) { + return dimension == null || dimension == 0; + } + + private ExtImpInsticator parseImpExt(Imp imp) { + try { + return mapper.mapper().convertValue(imp.getExt(), TYPE_REFERENCE).getBidder(); + } catch (IllegalArgumentException e) { + throw new PreBidException(e.getMessage()); + } + } + + private Imp modifyImp(BidRequest request, Imp imp, ExtImpInsticator extImp) { + final Price bidFloorPrice = resolveBidFloor(request, imp); + return imp.toBuilder() + .ext(mapper.mapper().createObjectNode().set(INSTICATOR_FIELD, mapper.mapper().valueToTree(extImp))) + .bidfloorcur(bidFloorPrice.getCurrency()) + .bidfloor(bidFloorPrice.getValue()) + .build(); + } + + private Price resolveBidFloor(BidRequest bidRequest, Imp imp) { + final Price initialBidFloorPrice = Price.of(imp.getBidfloorcur(), imp.getBidfloor()); + return BidderUtil.isValidPrice(initialBidFloorPrice) + ? convertBidFloor(initialBidFloorPrice, bidRequest) + : initialBidFloorPrice; + } + + private Price convertBidFloor(Price bidFloorPrice, BidRequest bidRequest) { + final BigDecimal convertedPrice = currencyConversionService.convertCurrency( + bidFloorPrice.getValue(), + bidRequest, + bidFloorPrice.getCurrency(), + DEFAULT_BIDDER_CURRENCY); + + return Price.of(DEFAULT_BIDDER_CURRENCY, BidderUtil.roundFloor(convertedPrice)); + } + + private BidRequest modifyRequest(BidRequest request, String publisherId, List errors) { + return request.toBuilder() + .site(modifySite(request.getSite(), publisherId)) + .app(modifyApp(request.getApp(), publisherId)) + .ext(modifyExtRequest(request.getExt(), errors)) + .build(); + } + + private static Site modifySite(Site site, String id) { + return Optional.ofNullable(site) + .map(Site::toBuilder) + .map(builder -> builder.publisher(modifyPublisher(site.getPublisher(), id))) + .map(Site.SiteBuilder::build) + .orElse(null); + } + + private static App modifyApp(App app, String id) { + return Optional.ofNullable(app) + .map(App::toBuilder) + .map(builder -> builder.publisher(modifyPublisher(app.getPublisher(), id))) + .map(App.AppBuilder::build) + .orElse(null); + } + + private static Publisher modifyPublisher(Publisher publisher, String id) { + return Optional.ofNullable(publisher) + .map(Publisher::toBuilder) + .orElseGet(Publisher::builder) + .id(id) + .build(); + } + + private ExtRequest modifyExtRequest(ExtRequest extRequest, List errors) { + final ExtRequest modifiedExtRequest = extRequest == null ? ExtRequest.empty() : extRequest; + final InsticatorExtRequest existingInsticator = getInsticatorExtRequest(modifiedExtRequest, errors); + + modifiedExtRequest.addProperty( + INSTICATOR_FIELD, + mapper.mapper().valueToTree(buildInsticator(existingInsticator))); + + return modifiedExtRequest; + } + + private InsticatorExtRequest getInsticatorExtRequest(ExtRequest modifiedExtRequest, List errors) { + try { + return mapper.mapper().convertValue( + modifiedExtRequest.getProperty(INSTICATOR_FIELD), + InsticatorExtRequest.class); + } catch (IllegalArgumentException e) { + errors.add(BidderError.badInput(e.getMessage())); + return null; + } + } + + private static InsticatorExtRequest buildInsticator(InsticatorExtRequest existingInsticator) { + if (existingInsticator == null || CollectionUtils.isEmpty(existingInsticator.getCaller())) { + return InsticatorExtRequest.of(Collections.singletonList(DEFAULT_INSTICATOR_CALLER)); + } + + final List callers = new ArrayList<>(existingInsticator.getCaller()); + callers.add(DEFAULT_INSTICATOR_CALLER); + return InsticatorExtRequest.of(Collections.unmodifiableList(callers)); + } + + private static MultiMap makeHeaders(Device device) { + final MultiMap headers = HttpUtil.headers(); + HttpUtil.addHeaderIfValueIsNotEmpty(headers, HttpUtil.USER_AGENT_HEADER, + ObjectUtil.getIfNotNull(device, Device::getUa)); + HttpUtil.addHeaderIfValueIsNotEmpty(headers, HttpUtil.X_FORWARDED_FOR_HEADER, + ObjectUtil.getIfNotNull(device, Device::getIp)); + HttpUtil.addHeaderIfValueIsNotEmpty(headers, "IP", + ObjectUtil.getIfNotNull(device, Device::getIp)); + HttpUtil.addHeaderIfValueIsNotEmpty(headers, HttpUtil.X_FORWARDED_FOR_HEADER, + ObjectUtil.getIfNotNull(device, Device::getIpv6)); + + return headers; + } + + @Override + public Result> makeBids(BidderCall httpCall, BidRequest bidRequest) { + try { + final BidResponse bidResponse = mapper.decodeValue(httpCall.getResponse().getBody(), BidResponse.class); + return Result.withValues(extractBids(bidResponse)); + } catch (DecodeException | PreBidException e) { + return Result.withError(BidderError.badServerResponse(e.getMessage())); + } + } + + private static List extractBids(BidResponse bidResponse) { + if (bidResponse == null || CollectionUtils.isEmpty(bidResponse.getSeatbid())) { + return Collections.emptyList(); + } + + return bidResponse.getSeatbid().stream() + .filter(Objects::nonNull) + .map(SeatBid::getBid) + .filter(Objects::nonNull) + .flatMap(Collection::stream) + .filter(Objects::nonNull) + .map(bid -> BidderBid.of(bid, getBidType(bid), bidResponse.getCur())) + .filter(Objects::nonNull) + .toList(); + } + + private static BidType getBidType(Bid bid) { + return switch (bid.getMtype()) { + case 2 -> BidType.video; + case null, default -> BidType.banner; + }; + } +} diff --git a/src/main/java/org/prebid/server/bidder/insticator/InsticatorExtRequest.java b/src/main/java/org/prebid/server/bidder/insticator/InsticatorExtRequest.java new file mode 100644 index 00000000000..079c7270ea5 --- /dev/null +++ b/src/main/java/org/prebid/server/bidder/insticator/InsticatorExtRequest.java @@ -0,0 +1,12 @@ +package org.prebid.server.bidder.insticator; + +import lombok.Value; + +import java.util.List; + +@Value(staticConstructor = "of") +public class InsticatorExtRequest { + + List caller; + +} diff --git a/src/main/java/org/prebid/server/bidder/insticator/InsticatorExtRequestCaller.java b/src/main/java/org/prebid/server/bidder/insticator/InsticatorExtRequestCaller.java new file mode 100644 index 00000000000..9b7ec994558 --- /dev/null +++ b/src/main/java/org/prebid/server/bidder/insticator/InsticatorExtRequestCaller.java @@ -0,0 +1,12 @@ +package org.prebid.server.bidder.insticator; + +import lombok.Value; + +@Value(staticConstructor = "of") +public class InsticatorExtRequestCaller { + + String name; + + String version; + +} diff --git a/src/main/java/org/prebid/server/proto/openrtb/ext/request/insticator/ExtImpInsticator.java b/src/main/java/org/prebid/server/proto/openrtb/ext/request/insticator/ExtImpInsticator.java new file mode 100644 index 00000000000..067680eb0df --- /dev/null +++ b/src/main/java/org/prebid/server/proto/openrtb/ext/request/insticator/ExtImpInsticator.java @@ -0,0 +1,14 @@ +package org.prebid.server.proto.openrtb.ext.request.insticator; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Value; + +@Value(staticConstructor = "of") +public class ExtImpInsticator { + + @JsonProperty("adUnitId") + String adUnitId; + + @JsonProperty("publisherId") + String publisherId; +} diff --git a/src/main/java/org/prebid/server/spring/config/bidder/InsticatorConfiguration.java b/src/main/java/org/prebid/server/spring/config/bidder/InsticatorConfiguration.java new file mode 100644 index 00000000000..7ae0e1a3432 --- /dev/null +++ b/src/main/java/org/prebid/server/spring/config/bidder/InsticatorConfiguration.java @@ -0,0 +1,43 @@ +package org.prebid.server.spring.config.bidder; + +import org.prebid.server.bidder.BidderDeps; +import org.prebid.server.bidder.insticator.InsticatorBidder; +import org.prebid.server.currency.CurrencyConversionService; +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.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/insticator.yaml", factory = YamlPropertySourceFactory.class) +public class InsticatorConfiguration { + + private static final String BIDDER_NAME = "insticator"; + + @Bean("insticatorConfigurationProperties") + @ConfigurationProperties("adapters.insticator") + BidderConfigurationProperties configurationProperties() { + return new BidderConfigurationProperties(); + } + + @Bean + BidderDeps insticatorBidderDeps(BidderConfigurationProperties insticatorConfigurationProperties, + @NotBlank @Value("${external-url}") String externalUrl, + CurrencyConversionService currencyConversionService, + JacksonMapper mapper) { + + return BidderDepsAssembler.forBidder(BIDDER_NAME) + .withConfig(insticatorConfigurationProperties) + .usersyncerCreator(UsersyncerCreator.create(externalUrl)) + .bidderCreator(config -> new InsticatorBidder(currencyConversionService, config.getEndpoint(), mapper)) + .assemble(); + } +} diff --git a/src/main/resources/bidder-config/insticator.yaml b/src/main/resources/bidder-config/insticator.yaml new file mode 100644 index 00000000000..7fcf60b877c --- /dev/null +++ b/src/main/resources/bidder-config/insticator.yaml @@ -0,0 +1,19 @@ +adapters: + insticator: + endpoint: https://ex.ingage.tech/v1/prebidserver + meta-info: + maintainer-email: prebid@insticator.com + app-media-types: + - banner + - video + site-media-types: + - banner + - video + supported-vendors: + vendor-id: 910 + usersync: + cookie-family-name: insticator + iframe: + url: https://usync.ingage.tech?gdpr={{gdpr}}&gdpr_consent={{gdpr_consent}}&us_privacy={{us_privacy}}&redirect={{redirect_url}} + support-cors: false + uid-macro: '$UID' diff --git a/src/main/resources/static/bidder-params/insticator.json b/src/main/resources/static/bidder-params/insticator.json new file mode 100644 index 00000000000..645ca8e0ebe --- /dev/null +++ b/src/main/resources/static/bidder-params/insticator.json @@ -0,0 +1,22 @@ +{ + "$schema": "http://json-schema.org/draft-04/schema#", + "title": "Insticator Adapter Params", + "description": "A schema which validates params accepted by Insticator", + "type": "object", + "properties": { + "adUnitId": { + "type": "string", + "description": "Ad Unit Id", + "minLength": 1 + }, + "publisherId": { + "type": "string", + "description": "Publisher Id", + "minLength": 1 + } + }, + "required": [ + "adUnitId", + "publisherId" + ] +} diff --git a/src/test/java/org/prebid/server/bidder/insticator/InsticatorBidderTest.java b/src/test/java/org/prebid/server/bidder/insticator/InsticatorBidderTest.java new file mode 100644 index 00000000000..9a6326327a0 --- /dev/null +++ b/src/test/java/org/prebid/server/bidder/insticator/InsticatorBidderTest.java @@ -0,0 +1,596 @@ +package org.prebid.server.bidder.insticator; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.fasterxml.jackson.databind.node.TextNode; +import com.iab.openrtb.request.App; +import com.iab.openrtb.request.BidRequest; +import com.iab.openrtb.request.Device; +import com.iab.openrtb.request.Imp; +import com.iab.openrtb.request.Publisher; +import com.iab.openrtb.request.Site; +import com.iab.openrtb.request.Video; +import com.iab.openrtb.response.Bid; +import com.iab.openrtb.response.BidResponse; +import com.iab.openrtb.response.SeatBid; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.prebid.server.VertxTest; +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.HttpResponse; +import org.prebid.server.bidder.model.Result; +import org.prebid.server.currency.CurrencyConversionService; +import org.prebid.server.exception.PreBidException; +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.insticator.ExtImpInsticator; + +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; + +import static java.util.Collections.singletonList; +import static java.util.function.UnaryOperator.identity; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mock.Strictness.LENIENT; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.prebid.server.proto.openrtb.ext.response.BidType.banner; +import static org.prebid.server.proto.openrtb.ext.response.BidType.video; +import static org.prebid.server.util.HttpUtil.ACCEPT_HEADER; +import static org.prebid.server.util.HttpUtil.APPLICATION_JSON_CONTENT_TYPE; +import static org.prebid.server.util.HttpUtil.CONTENT_TYPE_HEADER; +import static org.prebid.server.util.HttpUtil.USER_AGENT_HEADER; +import static org.prebid.server.util.HttpUtil.X_FORWARDED_FOR_HEADER; +import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE; + +@ExtendWith(MockitoExtension.class) +public class InsticatorBidderTest extends VertxTest { + + private static final String ENDPOINT_URL = "https://test.endpoint.com"; + + @Mock(strictness = LENIENT) + private CurrencyConversionService currencyConversionService; + + private InsticatorBidder target; + + @BeforeEach + public void before() { + target = new InsticatorBidder(currencyConversionService, ENDPOINT_URL, jacksonMapper); + } + + @Test + public void creationShouldFailOnInvalidEndpointUrl() { + assertThatIllegalArgumentException().isThrownBy(() -> new InsticatorBidder( + currencyConversionService, "invalid_url", jacksonMapper)); + } + + @Test + public void makeHttpRequestsShouldReturnErrorIfImpExtCouldNotBeParsed() { + // given + final BidRequest bidRequest = givenBidRequest( + imp -> imp.ext(mapper.valueToTree(ExtPrebid.of(null, mapper.createArrayNode())))); + + // when + final Result>> result = target.makeHttpRequests(bidRequest); + + // then + assertThat(result.getValue()).isEmpty(); + assertThat(result.getErrors()).hasSize(1).allSatisfy(bidderError -> { + assertThat(bidderError.getType()).isEqualTo(BidderError.Type.bad_input); + assertThat(bidderError.getMessage()).startsWith("Cannot deserialize value"); + }); + } + + @Test + public void makeHttpRequestsShouldMakeOneRequestPerAdUnitId() { + // given + final BidRequest bidRequest = givenBidRequest( + imp -> imp.id("givenImp1").ext(givenImpExt("1")), + imp -> imp.id("givenImp2").ext(givenImpExt("1")), + imp -> imp.id("givenImp3").ext(givenImpExt("2"))); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()).hasSize(2) + .extracting(HttpRequest::getPayload) + .extracting(payload -> payload.getImp().stream().map(Imp::getId).collect(Collectors.toList())) + .containsExactlyInAnyOrder(List.of("givenImp1", "givenImp2"), List.of("givenImp3")); + + assertThat(result.getValue()).hasSize(2) + .extracting(HttpRequest::getImpIds) + .containsExactlyInAnyOrder(Set.of("givenImp1", "givenImp2"), Set.of("givenImp3")); + } + + @Test + public void makeHttpRequestsShouldHaveCorrectUri() { + // given + final BidRequest bidRequest = givenBidRequest(imp -> imp.id("givenImp")); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()).hasSize(1) + .extracting(HttpRequest::getUri) + .containsExactlyInAnyOrder(ENDPOINT_URL); + } + + @Test + public void makeHttpRequestsShouldReturnExpectedHeadersWithIpWhenDeviceHasIp() { + // given + final BidRequest bidRequest = givenBidRequest(identity()).toBuilder() + .device(Device.builder().ip("ip").ua("ua").ipv6("ipv6").build()) + .build(); + + // when + final Result>> result = target.makeHttpRequests(bidRequest); + + // then + assertThat(result.getValue()).hasSize(1).first() + .extracting(HttpRequest::getHeaders) + .satisfies(headers -> assertThat(headers.get(CONTENT_TYPE_HEADER)) + .isEqualTo(APPLICATION_JSON_CONTENT_TYPE)) + .satisfies(headers -> assertThat(headers.get(ACCEPT_HEADER)) + .isEqualTo(APPLICATION_JSON_VALUE)) + .satisfies(headers -> assertThat(headers.get(USER_AGENT_HEADER)) + .isEqualTo("ua")) + .satisfies(headers -> assertThat(headers.get("IP")) + .isEqualTo("ip")) + .satisfies(headers -> assertThat(headers.get(X_FORWARDED_FOR_HEADER)) + .isEqualTo("ip")); + assertThat(result.getErrors()).isEmpty(); + } + + @Test + public void makeHttpRequestsShouldReturnExpectedHeadersWithIpv6WhenDeviceHasIpv6AndDoesNotHaveIp() { + // given + final BidRequest bidRequest = givenBidRequest(identity()).toBuilder() + .device(Device.builder().ip(null).ua("ua").ipv6("ipv6").build()) + .build(); + + // when + final Result>> result = target.makeHttpRequests(bidRequest); + + // then + assertThat(result.getValue()).hasSize(1).first() + .extracting(HttpRequest::getHeaders) + .satisfies(headers -> assertThat(headers.get(CONTENT_TYPE_HEADER)) + .isEqualTo(APPLICATION_JSON_CONTENT_TYPE)) + .satisfies(headers -> assertThat(headers.get(ACCEPT_HEADER)) + .isEqualTo(APPLICATION_JSON_VALUE)) + .satisfies(headers -> assertThat(headers.get(USER_AGENT_HEADER)) + .isEqualTo("ua")) + .satisfies(headers -> assertThat(headers.get("IP")) + .isNull()) + .satisfies(headers -> assertThat(headers.get(X_FORWARDED_FOR_HEADER)) + .isEqualTo("ipv6")); + assertThat(result.getErrors()).isEmpty(); + } + + @Test + public void makeHttpRequestsShouldReturnExpectedHeadersWhenDeviceIsAbsent() { + // given + final BidRequest bidRequest = givenBidRequest(identity()); + + // when + final Result>> result = target.makeHttpRequests(bidRequest); + + // then + assertThat(result.getValue()).hasSize(1).first() + .extracting(HttpRequest::getHeaders) + .satisfies(headers -> assertThat(headers.get(CONTENT_TYPE_HEADER)) + .isEqualTo(APPLICATION_JSON_CONTENT_TYPE)) + .satisfies(headers -> assertThat(headers.get(ACCEPT_HEADER)) + .isEqualTo(APPLICATION_JSON_VALUE)) + .satisfies(headers -> assertThat(headers.get(USER_AGENT_HEADER)).isNull()) + .satisfies(headers -> assertThat(headers.get("IP")).isNull()) + .satisfies(headers -> assertThat(headers.get(X_FORWARDED_FOR_HEADER)).isNull()); + assertThat(result.getErrors()).isEmpty(); + } + + @Test + public void makeHttpRequestsShouldConvertAndReturnProperBidFloorCur() { + // given + given(currencyConversionService.convertCurrency(any(), any(), anyString(), anyString())) + .willReturn(BigDecimal.ONE); + + final BidRequest bidRequest = givenBidRequest(impBuilder -> impBuilder + .bidfloorcur("EUR") + .bidfloor(BigDecimal.TEN)); + + // when + final Result>> result = target.makeHttpRequests(bidRequest); + + // then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()) + .extracting(HttpRequest::getPayload) + .flatExtracting(BidRequest::getImp) + .first() + .satisfies(imps -> { + assertThat(imps.getBidfloorcur()).isEqualTo("USD"); + assertThat(imps.getBidfloor()).isEqualTo(BigDecimal.ONE); + }); + } + + @Test + public void makeHttpRequestsShouldNotConvertAndReturnUSDBidFloorCurWhenBidFloorNotPositiveNumber() { + // given + given(currencyConversionService.convertCurrency(any(), any(), anyString(), anyString())) + .willReturn(BigDecimal.ONE); + + final BidRequest bidRequest = givenBidRequest(impBuilder -> impBuilder + .bidfloorcur("EUR") + .bidfloor(BigDecimal.ZERO)); + + // when + final Result>> result = target.makeHttpRequests(bidRequest); + + // then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()) + .extracting(HttpRequest::getPayload) + .flatExtracting(BidRequest::getImp) + .first() + .satisfies(imp -> { + assertThat(imp.getBidfloorcur()).isEqualTo("EUR"); + assertThat(imp.getBidfloor()).isEqualTo(BigDecimal.ZERO); + }); + + verifyNoInteractions(currencyConversionService); + } + + @Test + public void makeHttpRequestsShouldThrowErrorWhenCurrencyConvertCannotConvertInAnotherCurrency() { + // given + when(currencyConversionService.convertCurrency(any(), any(), any(), any())).thenThrow( + new PreBidException("Unable to convert from currency UAH to desired ad server currency USD")); + + final BidRequest bidRequest = givenBidRequest(impBuilder -> impBuilder + .bidfloorcur("UAH") + .bidfloor(BigDecimal.TEN)); + + // when + final Result>> result = target.makeHttpRequests(bidRequest); + + // then + assertThat(result.getValue()).isEmpty(); + assertThat(result.getErrors()) + .extracting(BidderError::getMessage) + .containsExactly("Unable to convert from currency UAH to desired ad server currency USD"); + } + + @Test + public void makeHttpRequestsShouldReturnImpWithUpdatedExt() { + // given + final BidRequest bidRequest = givenBidRequest( + imp -> imp.id("givenImp").ext(givenImpExt("adUnitId", "publisherId"))); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getErrors()).isEmpty(); + + final ObjectNode expectedNode = mapper.createObjectNode(); + expectedNode.set("adUnitId", TextNode.valueOf("adUnitId")); + expectedNode.set("publisherId", TextNode.valueOf("publisherId")); + final ObjectNode expectedImpExt = mapper.createObjectNode().set("insticator", expectedNode); + + assertThat(result.getValue()).hasSize(1) + .extracting(HttpRequest::getPayload) + .flatExtracting(BidRequest::getImp) + .extracting(Imp::getExt) + .containsExactly(expectedImpExt); + } + + @Test + public void makeHttpRequestsShouldReturnExtRequestInsticatorWithDefaultCallerWhenInsticatorIsAbsent() { + // given + final ExtRequest givenExtRequest = ExtRequest.empty(); + givenExtRequest.addProperty("insticator", + mapper.createObjectNode().set("caller", + mapper.createArrayNode().add(mapper.createObjectNode() + .put("name", "something") + .put("version", "1.0")))); + final BidRequest bidRequest = givenBidRequest(imp -> imp.id("givenImp")) + .toBuilder() + .ext(givenExtRequest) + .build(); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getErrors()).isEmpty(); + + final ExtRequest expectedExtRequest = ExtRequest.empty(); + expectedExtRequest.addProperty("insticator", + mapper.createObjectNode().set("caller", + mapper.createArrayNode() + .add(mapper.createObjectNode() + .put("name", "something") + .put("version", "1.0")) + .add(mapper.createObjectNode() + .put("name", "Prebid-Server") + .put("version", "n/a")))); + + assertThat(result.getValue()).hasSize(1) + .extracting(HttpRequest::getPayload) + .flatExtracting(BidRequest::getExt) + .containsExactly(expectedExtRequest); + } + + @Test + public void makeHttpRequestsShouldAddsToExtRequestInsticatorDefaultCaller() { + // given + final BidRequest bidRequest = givenBidRequest(imp -> imp.id("givenImp")) + .toBuilder() + .ext(ExtRequest.empty()) + .build(); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getErrors()).isEmpty(); + + final ExtRequest expectedExtRequest = ExtRequest.empty(); + expectedExtRequest.addProperty("insticator", + mapper.createObjectNode().set("caller", + mapper.createArrayNode().add(mapper.createObjectNode() + .put("name", "Prebid-Server") + .put("version", "n/a")))); + + assertThat(result.getValue()).hasSize(1) + .extracting(HttpRequest::getPayload) + .flatExtracting(BidRequest::getExt) + .containsExactly(expectedExtRequest); + } + + @Test + public void makeHttpRequestsShouldAddsToExtRequestInsticatorDefaultCallerWhenExistingInsticatorCanNotBeParsed() { + // given + final ExtRequest givenExtRequest = ExtRequest.empty(); + givenExtRequest.addProperty("insticator", mapper.createArrayNode()); + final BidRequest bidRequest = givenBidRequest(imp -> imp.id("givenImp")) + .toBuilder() + .ext(givenExtRequest) + .build(); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getErrors()).hasSize(1).allSatisfy(bidderError -> { + assertThat(bidderError.getType()).isEqualTo(BidderError.Type.bad_input); + assertThat(bidderError.getMessage()).startsWith("Cannot deserialize value of type " + + "`org.prebid.server.bidder.insticator.InsticatorExtRequest`"); + }); + + final ExtRequest expectedExtRequest = ExtRequest.empty(); + expectedExtRequest.addProperty("insticator", + mapper.createObjectNode().set("caller", + mapper.createArrayNode().add(mapper.createObjectNode() + .put("name", "Prebid-Server") + .put("version", "n/a")))); + + assertThat(result.getValue()).hasSize(1) + .extracting(HttpRequest::getPayload) + .flatExtracting(BidRequest::getExt) + .containsExactly(expectedExtRequest); + } + + @Test + public void makeHttpRequestsShouldModifyAppWithPublisherIdOfTheFirstImp() { + // given + final BidRequest bidRequest = givenBidRequest( + imp -> imp.id("givenImpId1").ext(givenImpExt("adUnitId1", "publisherId1")), + imp -> imp.id("givenImpId2").ext(givenImpExt("adUnitId2", "publisherId2"))) + .toBuilder() + .app(App.builder().publisher(Publisher.builder().id("id").build()).build()) + .build(); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getValue()).hasSize(2) + .extracting(HttpRequest::getPayload) + .extracting(BidRequest::getApp) + .extracting(App::getPublisher) + .extracting(Publisher::getId) + .containsExactly("publisherId1", "publisherId1"); + } + + @Test + public void makeHttpRequestsShouldModifySiteWithPublisherIdOfTheFirstImp() { + // given + final BidRequest bidRequest = givenBidRequest( + imp -> imp.id("givenImpId1").ext(givenImpExt("adUnitId1", "publisherId1")), + imp -> imp.id("givenImpId2").ext(givenImpExt("adUnitId2", "publisherId2"))) + .toBuilder() + .site(Site.builder().publisher(Publisher.builder().id("id").build()).build()) + .build(); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getValue()).hasSize(2) + .extracting(HttpRequest::getPayload) + .extracting(BidRequest::getSite) + .extracting(Site::getPublisher) + .extracting(Publisher::getId) + .containsExactly("publisherId1", "publisherId1"); + } + + @Test + public void makeHttpRequestsShouldMakeOneRequestWhenOneImpIsValidAndAnotherAreInvalid() { + // given + final BidRequest bidRequest = givenBidRequest( + imp -> imp.id("givenImpId1").ext(mapper.valueToTree(ExtPrebid.of(null, mapper.createArrayNode()))), + imp -> imp.id("givenImpId2"), + imp -> imp.id("givenImpId3").video(Video.builder().mimes(null).build()), + imp -> imp.id("givenImpId4").video(Video.builder().h(null).build()), + imp -> imp.id("givenImpId5").video(Video.builder().h(0).build()), + imp -> imp.id("givenImpId6").video(Video.builder().w(null).build()), + imp -> imp.id("givenImpId7").video(Video.builder().w(0).build())); + + //when + final Result>> result = target.makeHttpRequests(bidRequest); + + //then + assertThat(result.getValue()).hasSize(1) + .extracting(HttpRequest::getPayload) + .flatExtracting(BidRequest::getImp) + .extracting(Imp::getId) + .containsExactly("givenImpId2"); + } + + @Test + public void makeBidsShouldReturnErrorWhenResponseCanNotBeParsed() { + // given + final BidderCall httpCall = givenHttpCall("invalid"); + + // when + final Result> actual = target.makeBids(httpCall, null); + + // then + assertThat(actual.getValue()).isEmpty(); + assertThat(actual.getErrors()).hasSize(1) + .allSatisfy(error -> { + assertThat(error.getMessage()).startsWith("Failed to decode: Unrecognized token 'invalid':"); + assertThat(error.getType()).isEqualTo(BidderError.Type.bad_server_response); + }); + } + + @Test + public void makeBidsShouldReturnEmptyBidsWhenResponseDoesNotHaveSeatBid() throws JsonProcessingException { + // given + final BidderCall httpCall = givenHttpCall(mapper.writeValueAsString(BidResponse.builder().build())); + + // when + final Result> actual = target.makeBids(httpCall, null); + + // then + assertThat(actual.getValue()).isEmpty(); + assertThat(actual.getErrors()).isEmpty(); + } + + @Test + public void makeBidsShouldReturnBannerBidSuccessfully() throws JsonProcessingException { + // given + final BidderCall httpCall = givenHttpCall(givenBidResponse(bid -> bid.impid("1").mtype(1))); + + // when + final Result> result = target.makeBids(httpCall, null); + + // then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()) + .containsExactly(BidderBid.of(Bid.builder().mtype(1).impid("1").build(), banner, "USD")); + } + + @Test + public void makeBidsShouldReturnVideoBidSuccessfully() throws JsonProcessingException { + // given + final BidderCall httpCall = givenHttpCall(givenBidResponse(bid -> bid.impid("2").mtype(2))); + + // when + final Result> result = target.makeBids(httpCall, null); + + // then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()) + .containsExactly(BidderBid.of(Bid.builder().mtype(2).impid("2").build(), video, "USD")); + } + + @Test + public void makeBidsShouldReturnBannerBidWhenMtypeIsUnknown() throws JsonProcessingException { + // given + final BidderCall httpCall = givenHttpCall(givenBidResponse(bid -> bid.impid("3").mtype(3))); + + // when + final Result> result = target.makeBids(httpCall, null); + + // then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()) + .containsExactly(BidderBid.of(Bid.builder().mtype(3).impid("3").build(), banner, "USD")); + } + + @Test + public void makeBidsShouldReturnBannerBidWhenMtypeIsNull() throws JsonProcessingException { + // given + final BidderCall httpCall = givenHttpCall(givenBidResponse(bid -> bid.impid("3").mtype(null))); + + // when + final Result> result = target.makeBids(httpCall, null); + + // then + assertThat(result.getErrors()).isEmpty(); + assertThat(result.getValue()) + .containsExactly(BidderBid.of(Bid.builder().mtype(null).impid("3").build(), banner, "USD")); + } + + private static BidRequest givenBidRequest(UnaryOperator... impCustomizers) { + return BidRequest.builder() + .imp(Arrays.stream(impCustomizers).map(InsticatorBidderTest::givenImp).toList()) + .build(); + } + + private static Imp givenImp(UnaryOperator impCustomizer) { + return impCustomizer.apply(Imp.builder() + .id("impId") + .bidfloor(BigDecimal.TEN) + .bidfloorcur("USD") + .ext(mapper.valueToTree(ExtPrebid.of( + null, + ExtImpInsticator.of("adUnitId", "publisherId"))))) + .build(); + } + + private static ObjectNode givenImpExt(String adUnitId) { + return givenImpExt(adUnitId, "publisherId"); + } + + private static ObjectNode givenImpExt(String adUnitId, String publisherId) { + return mapper.valueToTree(ExtPrebid.of(null, ExtImpInsticator.of(adUnitId, publisherId))); + } + + private static BidderCall givenHttpCall(String body) { + return BidderCall.succeededHttp( + HttpRequest.builder().payload(null).build(), + HttpResponse.of(200, null, body), + null); + } + + private String givenBidResponse(UnaryOperator bidCustomizer) throws JsonProcessingException { + return mapper.writeValueAsString(BidResponse.builder() + .cur("USD") + .seatbid(singletonList(SeatBid.builder() + .bid(singletonList(bidCustomizer.apply(Bid.builder()).build())) + .build())) + .build()); + } + +} diff --git a/src/test/java/org/prebid/server/it/InsticatorTest.java b/src/test/java/org/prebid/server/it/InsticatorTest.java new file mode 100644 index 00000000000..4a96954e5c5 --- /dev/null +++ b/src/test/java/org/prebid/server/it/InsticatorTest.java @@ -0,0 +1,36 @@ +package org.prebid.server.it; + +import io.restassured.response.Response; +import org.json.JSONException; +import org.junit.jupiter.api.Test; +import org.prebid.server.model.Endpoint; + +import java.io.IOException; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static java.util.Collections.singletonList; + +public class InsticatorTest extends IntegrationTest { + + @Test + public void openrtb2AuctionShouldRespondWithBidsFromInsticator() throws IOException, JSONException { + // given + WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/insticator-exchange")) + .withRequestBody(equalToJson(jsonFrom("openrtb2/insticator/test-insticator-bid-request.json"))) + .willReturn(aResponse().withBody(jsonFrom("openrtb2/insticator/test-insticator-bid-response.json")))); + + // when + final Response response = responseFor("openrtb2/insticator/test-auction-insticator-request.json", + Endpoint.openrtb2_auction); + + // then + assertJsonEquals( + "openrtb2/insticator/test-auction-insticator-response.json", + response, + singletonList("insticator")); + } + +} diff --git a/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-auction-insticator-request.json b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-auction-insticator-request.json new file mode 100644 index 00000000000..2ae15855dcd --- /dev/null +++ b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-auction-insticator-request.json @@ -0,0 +1,24 @@ +{ + "id": "request_id", + "imp": [ + { + "id": "imp_id", + "banner": { + "w": 300, + "h": 250 + }, + "ext": { + "insticator": { + "adUnitId": "adUnitId", + "publisherId": "adUnitId" + } + } + } + ], + "tmax": 5000, + "regs": { + "ext": { + "gdpr": 0 + } + } +} diff --git a/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-auction-insticator-response.json b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-auction-insticator-response.json new file mode 100644 index 00000000000..fa2b0a4accd --- /dev/null +++ b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-auction-insticator-response.json @@ -0,0 +1,40 @@ +{ + "id": "request_id", + "seatbid": [ + { + "bid": [ + { + "id": "bid_id", + "impid": "imp_id", + "exp": 300, + "price": 3.33, + "adm": "adm001", + "adid": "adid001", + "cid": "cid001", + "crid": "crid001", + "mtype": 1, + "w": 300, + "h": 250, + "ext": { + "prebid": { + "type": "banner" + }, + "origbidcpm": 3.33 + } + } + ], + "seat": "insticator", + "group": 0 + } + ], + "cur": "USD", + "ext": { + "responsetimemillis": { + "insticator": "{{ insticator.response_time_ms }}" + }, + "prebid": { + "auctiontimestamp": 0 + }, + "tmaxrequest": 5000 + } +} diff --git a/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-insticator-bid-request.json b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-insticator-bid-request.json new file mode 100644 index 00000000000..5baeef4526a --- /dev/null +++ b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-insticator-bid-request.json @@ -0,0 +1,65 @@ +{ + "id": "request_id", + "imp": [ + { + "id": "imp_id", + "secure": 1, + "banner": { + "w": 300, + "h": 250 + }, + "ext": { + "insticator": { + "adUnitId": "adUnitId", + "publisherId": "adUnitId" + } + } + } + ], + "source": { + "tid": "${json-unit.any-string}" + }, + "site": { + "domain": "www.example.com", + "page": "http://www.example.com", + "publisher": { + "domain": "example.com", + "id" : "adUnitId" + }, + "ext": { + "amp": 0 + } + }, + "device": { + "ua": "userAgent", + "ip": "193.168.244.1" + }, + "at": 1, + "tmax": "${json-unit.any-number}", + "cur": [ + "USD" + ], + "regs": { + "ext": { + "gdpr": 0 + } + }, + "ext": { + "insticator": { + "caller": [ + { + "name": "Prebid-Server", + "version": "n/a" + } + ] + }, + "prebid": { + "server": { + "externalurl": "http://localhost:8080", + "gvlid": 1, + "datacenter": "local", + "endpoint": "/openrtb2/auction" + } + } + } +} diff --git a/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-insticator-bid-response.json b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-insticator-bid-response.json new file mode 100644 index 00000000000..2769168e6ed --- /dev/null +++ b/src/test/resources/org/prebid/server/it/openrtb2/insticator/test-insticator-bid-response.json @@ -0,0 +1,21 @@ +{ + "id": "request_id", + "seatbid": [ + { + "bid": [ + { + "id": "bid_id", + "impid": "imp_id", + "price": 3.33, + "adid": "adid001", + "crid": "crid001", + "cid": "cid001", + "adm": "adm001", + "mtype": 1, + "h": 250, + "w": 300 + } + ] + } + ] +} diff --git a/src/test/resources/org/prebid/server/it/test-application.properties b/src/test/resources/org/prebid/server/it/test-application.properties index 485e32c5092..2e115d00348 100644 --- a/src/test/resources/org/prebid/server/it/test-application.properties +++ b/src/test/resources/org/prebid/server/it/test-application.properties @@ -514,6 +514,8 @@ adapters.vox.enabled=true adapters.vox.endpoint=http://localhost:8090/vox-exchange adapters.inmobi.enabled=true adapters.inmobi.endpoint=http://localhost:8090/inmobi-exchange +adapters.insticator.enabled=true +adapters.insticator.endpoint=http://localhost:8090/insticator-exchange adapters.interactiveoffers.enabled=true adapters.interactiveoffers.endpoint=http://localhost:8090/interactiveoffers-exchange adapters.invibes.enabled=true