Rework ad serving: signed impression tokens, per-campaign daily caps, stats
Follows the usual ad-server flow (serve -> impression -> click):
- GET /api/ads/next returns an impressionToken: HMAC-signed (ads.tracking.secret,
defaults to jwt.secret) ad id, campaign id, subject and nonce, valid 1 hour.
/impression and /click accept it, verify the signature, count each nonce once
(Redis SET NX) and take the user/session from the token, so impressions
cannot be forged or replayed. Requests without a token keep working until
ads.tracking.require-token is switched on after the frontend update.
- The frequency cap is per campaign and calendar day (ads.timezone) and grows
on real impressions, not on serving: ad:cap:<subject>:<campaign>:<yyyyMMdd>.
- Selection reads a 30-second in-memory snapshot of eligible ads (projection,
invalidated locally on admin changes), filters capped campaigns with one
MGET, picks by weight and then sets the cooldown atomically. The weighted
sort drew random numbers inside the comparator, breaking its contract.
- Campaigns past endDate are finished every 10 minutes (ShedLock).
- GET /api/v1/admin/campaigns/{id}/stats: impressions, clicks and CTR per ad
for a date range; composite indexes on impression/click (changelog 021).
- Removed unused cascade collections on Campaign/Advertising, the unused
FullscreenAdActivateRequestDto and the /api/ads/impression/beacon rule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,7 @@ import com.krylov.refound.ai.config.AiRetryProperties;
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.ratelimit.RateLimitProperties;
|
||||
import com.krylov.refound.search.SearchProperties;
|
||||
import com.krylov.refound.service.advertising.AdsProperties;
|
||||
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -18,7 +19,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
|
||||
)@EnableScheduling
|
||||
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
|
||||
SearchProperties.class, RateLimitProperties.class})
|
||||
SearchProperties.class, RateLimitProperties.class, AdsProperties.class})
|
||||
@EnableRetry
|
||||
public class ReFoundApplication {
|
||||
|
||||
|
||||
@@ -6,10 +6,9 @@ import com.krylov.refound.dto.advertising.AdvertisingResponseDto;
|
||||
import com.krylov.refound.dto.advertising.ClickRequestDto;
|
||||
import com.krylov.refound.dto.advertising.ImpressionRequestDto;
|
||||
import com.krylov.refound.dto.advertising.SelectedAdvertisingDto;
|
||||
import com.krylov.refound.service.advertising.AdvertisingClickService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingImpressionService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingSelectionService;
|
||||
import com.krylov.refound.service.advertising.AdvertisingTrackingService;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -30,8 +29,7 @@ public class AdvertisingController {
|
||||
|
||||
private final AdvertisingSelectionService advertisingSelectionService;
|
||||
private final AdvertisingMediaService advertisingMediaService;
|
||||
private final AdvertisingImpressionService advertisingImpressionService;
|
||||
private final AdvertisingClickService advertisingClickService;
|
||||
private final AdvertisingTrackingService advertisingTrackingService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@GetMapping("/api/ads/next")
|
||||
@@ -47,21 +45,24 @@ public class AdvertisingController {
|
||||
SelectedAdvertisingDto advertising = selected.get();
|
||||
String mediaUrl = advertisingMediaService.getMediaUrl(advertising.mediaKey());
|
||||
|
||||
return ResponseEntity.ok(new AdvertisingResponseDto(advertising.advertisingId(), advertising.type(), mediaUrl, advertising.targetUrl()));
|
||||
return ResponseEntity.ok(new AdvertisingResponseDto(advertising.advertisingId(), advertising.type(), mediaUrl,
|
||||
advertising.targetUrl(), advertising.impressionToken()));
|
||||
}
|
||||
|
||||
@PostMapping("/api/ads/impression")
|
||||
public ResponseEntity<Void> registerImpression(@RequestBody String body, Authentication authentication) throws JsonProcessingException {
|
||||
log.debug("registerImpression for body {}", body);
|
||||
ImpressionRequestDto request = objectMapper.readValue(body, ImpressionRequestDto.class);
|
||||
advertisingImpressionService.recordImpression(request.advertisingId(), authentication, request.sessionId());
|
||||
advertisingTrackingService.recordImpression(request.advertisingId(), authentication, request.sessionId(),
|
||||
request.token());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
@PostMapping("/api/ads/click")
|
||||
public ResponseEntity<Void> registerClick(@RequestBody ClickRequestDto request, Authentication authentication) {
|
||||
log.debug("registerClick");
|
||||
advertisingClickService.recordClick(request.advertisingId(), authentication, request.sessionId());
|
||||
advertisingTrackingService.recordClick(request.advertisingId(), authentication, request.sessionId(),
|
||||
request.token());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,16 @@ import com.krylov.refound.dto.advertising.CampaignCreateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignResponseDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignStatusUpdateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignUpdateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignStatsDto;
|
||||
import com.krylov.refound.service.advertising.CampaignService;
|
||||
import com.krylov.refound.service.advertising.CampaignStatsService;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.validation.Valid;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
@@ -21,6 +25,7 @@ import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Slf4j
|
||||
@@ -30,6 +35,19 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class CampaignAdminController {
|
||||
|
||||
private final CampaignService campaignService;
|
||||
private final CampaignStatsService campaignStatsService;
|
||||
|
||||
/**
|
||||
* Показы, клики и CTR кампании по объявлениям. from/to — дни (yyyy-MM-dd)
|
||||
* включительно в часовом поясе рекламы; по умолчанию последние 30 дней.
|
||||
*/
|
||||
@GetMapping("/{campaignId}/stats")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<CampaignStatsDto> getStats(@PathVariable Long campaignId,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to) {
|
||||
return ResponseEntity.ok(campaignStatsService.getStats(campaignId, from, to));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
|
||||
@@ -4,7 +4,9 @@ public record AdvertisingResponseDto(
|
||||
Long advertisingId,
|
||||
String type,
|
||||
String mediaUrl,
|
||||
String targetUrl
|
||||
String targetUrl,
|
||||
/** Подписанный токен показа: вернуть в /api/ads/impression и /api/ads/click. */
|
||||
String impressionToken
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
/** Показы, клики и CTR (в процентах) одного объявления за период отчёта. */
|
||||
public record AdvertisingStatsDto(
|
||||
Long advertisingId,
|
||||
long impressions,
|
||||
long clicks,
|
||||
double ctr
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/** Отчёт по кампании за период [from, to] (оба дня включительно). CTR — в процентах. */
|
||||
public record CampaignStatsDto(
|
||||
Long campaignId,
|
||||
LocalDate from,
|
||||
LocalDate to,
|
||||
long impressions,
|
||||
long clicks,
|
||||
double ctr,
|
||||
List<AdvertisingStatsDto> advertisings
|
||||
) {
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package com.krylov.refound.dto.advertising;
|
||||
|
||||
public record ClickRequestDto(
|
||||
Long advertisingId,
|
||||
String sessionId
|
||||
String sessionId,
|
||||
/** Тот же токен показа, что и для /api/ads/impression. */
|
||||
String token
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||
|
||||
/**
|
||||
* Объявление, которое сейчас можно показывать, вместе с нужными для выбора
|
||||
* полями кампании. Неизменяемый снимок — его можно держать в кэше без сессии JPA.
|
||||
*/
|
||||
public record EligibleAdvertising(
|
||||
Long advertisingId,
|
||||
Long campaignId,
|
||||
AdvertisingType type,
|
||||
String mediaKey,
|
||||
String targetUrl,
|
||||
Integer weight,
|
||||
Integer dailyImpressionCap
|
||||
) {
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
public record FullscreenAdActivateRequestDto(boolean active) {
|
||||
|
||||
}
|
||||
@@ -2,6 +2,8 @@ package com.krylov.refound.dto.advertising;
|
||||
|
||||
public record ImpressionRequestDto(
|
||||
Long advertisingId,
|
||||
String sessionId
|
||||
String sessionId,
|
||||
/** Токен показа из GET /api/ads/next; без него — устаревший путь без защиты от повторов. */
|
||||
String token
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@ public record SelectedAdvertisingDto(
|
||||
Long advertisingId,
|
||||
String type,
|
||||
String mediaKey,
|
||||
String targetUrl
|
||||
String targetUrl,
|
||||
String impressionToken
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@ import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Table(name = "advertising")
|
||||
@@ -45,20 +43,6 @@ public class Advertising {
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "advertising",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true
|
||||
)
|
||||
private List<Impression> impressions = new ArrayList<>();
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "advertising",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true
|
||||
)
|
||||
private List<Click> clicks = new ArrayList<>();
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) {
|
||||
|
||||
@@ -7,8 +7,6 @@ import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Entity
|
||||
@Table(name = "campaign")
|
||||
@@ -39,13 +37,6 @@ public class Campaign {
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "campaign",
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true
|
||||
)
|
||||
private List<Advertising> ads = new ArrayList<>();
|
||||
|
||||
@PrePersist
|
||||
protected void onCreate() {
|
||||
if (createdAt == null) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.dto.advertising.EligibleAdvertising;
|
||||
import com.krylov.refound.entity.advertising.Advertising;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
@@ -9,16 +10,24 @@ import org.springframework.data.repository.query.Param;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface AdvertisingRepository extends JpaRepository<Advertising, Long> {
|
||||
|
||||
/** Объявления, которые можно показывать сейчас: активная кампания в окне дат и готовое медиа. */
|
||||
@Query("""
|
||||
SELECT a FROM Advertising a JOIN FETCH a.campaign c
|
||||
SELECT new com.krylov.refound.dto.advertising.EligibleAdvertising(
|
||||
a.id, c.id, a.type, a.mediaKey, a.targetUrl, a.weight, c.dailyImpressionCap)
|
||||
FROM Advertising a JOIN a.campaign c
|
||||
WHERE c.status = 'ACTIVE'
|
||||
AND a.transcodingStatus = 'READY'
|
||||
AND a.mediaKey IS NOT NULL
|
||||
AND :now BETWEEN c.startDate AND c.endDate
|
||||
""")
|
||||
List<Advertising> findEligibleAds(@Param("now") LocalDateTime now);
|
||||
List<EligibleAdvertising> findEligible(@Param("now") LocalDateTime now);
|
||||
|
||||
@Query("SELECT a.campaign.id FROM Advertising a WHERE a.id = :id")
|
||||
Optional<Long> findCampaignIdById(@Param("id") Long id);
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
|
||||
@@ -1,11 +1,23 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Campaign;
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface CampaignRepository extends JpaRepository<Campaign, Long> {
|
||||
|
||||
List<Campaign> findAllByOrderByCreatedAtDesc();
|
||||
|
||||
/** Завершает кампании, у которых закончилось окно показа. */
|
||||
@Modifying
|
||||
@Query("UPDATE Campaign c SET c.status = :finished WHERE c.status IN :running AND c.endDate < :now")
|
||||
int finishExpired(@Param("now") LocalDateTime now, @Param("running") Collection<CampaignStatus> running,
|
||||
@Param("finished") CampaignStatus finished);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Click;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface ClickRepository extends JpaRepository<Click, Long> {
|
||||
|
||||
/** Число событий по объявлениям кампании за период [from, to): строки (advertisingId, count). */
|
||||
@Query("""
|
||||
SELECT e.advertising.id, COUNT(e) FROM Click e
|
||||
WHERE e.advertising.campaign.id = :campaignId AND e.clickedAt >= :from AND e.clickedAt < :to
|
||||
GROUP BY e.advertising.id
|
||||
""")
|
||||
List<Object[]> countByAdvertising(@Param("campaignId") Long campaignId, @Param("from") LocalDateTime from,
|
||||
@Param("to") LocalDateTime to);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,20 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Impression;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface ImpressionRepository extends JpaRepository<Impression, Long> {
|
||||
|
||||
/** Число событий по объявлениям кампании за период [from, to): строки (advertisingId, count). */
|
||||
@Query("""
|
||||
SELECT e.advertising.id, COUNT(e) FROM Impression e
|
||||
WHERE e.advertising.campaign.id = :campaignId AND e.shownAt >= :from AND e.shownAt < :to
|
||||
GROUP BY e.advertising.id
|
||||
""")
|
||||
List<Object[]> countByAdvertising(@Param("campaignId") Long campaignId, @Param("from") LocalDateTime from,
|
||||
@Param("to") LocalDateTime to);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Clock;
|
||||
import java.util.Base64;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Токен показа — подписанная квитанция о выдаче рекламы, как impression URL в
|
||||
* рекламных серверах. Его получает клиент в ответе {@code GET /api/ads/next} и
|
||||
* возвращает в {@code /api/ads/impression} и {@code /api/ads/click}.
|
||||
*
|
||||
* <p>Токен фиксирует, какое объявление какой кампании выдано какому субъекту
|
||||
* (пользователю или сессии) и когда. По подписи нельзя засчитать показ рекламы,
|
||||
* которая не выдавалась, или приписать его другому пользователю; по nonce
|
||||
* каждый токен засчитывается один раз.
|
||||
*
|
||||
* <p>Формат: {@code base64url(v1|adId|campaignId|subject|issuedAtSec|nonce).base64url(HMAC-SHA256)}.
|
||||
*/
|
||||
@Service
|
||||
public class AdTrackingTokenService {
|
||||
|
||||
private static final String VERSION = "v1";
|
||||
private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding();
|
||||
private static final Base64.Decoder DECODER = Base64.getUrlDecoder();
|
||||
|
||||
private final byte[] secret;
|
||||
private final AdsProperties properties;
|
||||
private final Clock clock;
|
||||
|
||||
@Autowired
|
||||
public AdTrackingTokenService(AdsProperties properties, @Value("${jwt.secret}") String jwtSecret) {
|
||||
this(properties, jwtSecret, Clock.systemUTC());
|
||||
}
|
||||
|
||||
AdTrackingTokenService(AdsProperties properties, String jwtSecret, Clock clock) {
|
||||
String configured = properties.getTracking().getSecret();
|
||||
this.secret = (configured == null || configured.isBlank() ? jwtSecret : configured).getBytes(StandardCharsets.UTF_8);
|
||||
this.properties = properties;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/** Что подтверждает токен. */
|
||||
public record Claims(long advertisingId, long campaignId, String subject, long issuedAt, String nonce) {
|
||||
}
|
||||
|
||||
public String issue(long advertisingId, long campaignId, String subject) {
|
||||
String payload = String.join("|", VERSION, Long.toString(advertisingId), Long.toString(campaignId),
|
||||
subject, Long.toString(clock.instant().getEpochSecond()), UUID.randomUUID().toString());
|
||||
byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8);
|
||||
return ENCODER.encodeToString(payloadBytes) + "." + ENCODER.encodeToString(sign(payloadBytes));
|
||||
}
|
||||
|
||||
/** Данные токена, если подпись верна и срок не истёк; иначе пусто. */
|
||||
public Optional<Claims> verify(String token) {
|
||||
if (token == null || token.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
int dot = token.indexOf('.');
|
||||
if (dot <= 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
byte[] payloadBytes = DECODER.decode(token.substring(0, dot));
|
||||
byte[] signature = DECODER.decode(token.substring(dot + 1));
|
||||
if (!MessageDigest.isEqual(sign(payloadBytes), signature)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// subject — "u<id>" или "s<sessionId>" без '|' (AdSessionId его не пропускает)
|
||||
String[] parts = new String(payloadBytes, StandardCharsets.UTF_8).split("\\|", -1);
|
||||
if (parts.length != 6 || !VERSION.equals(parts[0])) {
|
||||
return Optional.empty();
|
||||
}
|
||||
long issuedAt = Long.parseLong(parts[4]);
|
||||
long age = clock.instant().getEpochSecond() - issuedAt;
|
||||
if (age < -60 || age > properties.getTracking().getTokenTtl().toSeconds()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new Claims(Long.parseLong(parts[1]), Long.parseLong(parts[2]), parts[3], issuedAt, parts[5]));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] sign(byte[] payload) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
|
||||
return mac.doFinal(payload);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw new IllegalStateException("HmacSHA256 недоступен", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.ZoneId;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/** Настройки рекламы ({@code ads.*} в application.yaml). */
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "ads")
|
||||
public class AdsProperties {
|
||||
|
||||
/**
|
||||
* Часовой пояс рекламы: в нём считаются даты кампаний (startDate/endDate)
|
||||
* и календарные сутки дневного лимита показов.
|
||||
*/
|
||||
private ZoneId timezone = ZoneId.of("Europe/Moscow");
|
||||
|
||||
/** Минимальная пауза между показами любой рекламы одному пользователю/сессии. */
|
||||
private Duration sessionCooldown = Duration.ofSeconds(30);
|
||||
|
||||
/** Сколько экземпляр держит в памяти список объявлений, доступных к показу. */
|
||||
private Duration eligibleCacheTtl = Duration.ofSeconds(30);
|
||||
|
||||
private Tracking tracking = new Tracking();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Tracking {
|
||||
/** Ключ HMAC для токенов показа. По умолчанию — jwt.secret. */
|
||||
private String secret;
|
||||
/** Сколько после выдачи принимается показ/клик по токену. */
|
||||
private Duration tokenTtl = Duration.ofHours(1);
|
||||
/**
|
||||
* Принимать показы и клики только с токеном. Пока фронт не присылает токен,
|
||||
* false: запросы без токена учитываются по-старому (без защиты от повторов).
|
||||
*/
|
||||
private boolean requireToken = false;
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import org.springframework.stereotype.Service;
|
||||
public class AdvertisingAdminService {
|
||||
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
private final AdvertisingSelectionService selectionService;
|
||||
|
||||
public Advertising createAdvertising(Campaign campaign, AdvertisingCreateRequestDto request){
|
||||
Advertising advertising = new Advertising();
|
||||
@@ -82,6 +83,7 @@ public class AdvertisingAdminService {
|
||||
|
||||
public AdvertisingAdminResponseDto toAdminDto(Advertising advertising) {
|
||||
Advertising saved = advertisingRepository.save(advertising);
|
||||
selectionService.invalidateCache();
|
||||
return mapToAdminDto(saved);
|
||||
}
|
||||
|
||||
@@ -99,6 +101,7 @@ public class AdvertisingAdminService {
|
||||
advertising.setWeight(request.weight());
|
||||
Advertising saved = advertisingRepository.save(advertising);
|
||||
log.info("Advertising {} updated", saved.getId());
|
||||
selectionService.invalidateCache();
|
||||
return mapToAdminDto(saved);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
|
||||
import com.krylov.refound.entity.advertising.Advertising;
|
||||
import com.krylov.refound.entity.advertising.Click;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.repository.advertising.ClickRepository;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import com.krylov.refound.util.AdSessionId;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdvertisingClickService {
|
||||
|
||||
private final UserService userService;
|
||||
private final ClickRepository clickRepository;
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
|
||||
@Transactional
|
||||
public void recordClick(Long advertisingId, Authentication authentication, String sessionId) {
|
||||
Long userId = extractUserId(authentication);
|
||||
// getReferenceById не проверяет существование: несуществующий id падал
|
||||
// на внешнем ключе при коммите (500), а catch EntityNotFoundException не срабатывал
|
||||
if (advertisingId == null || !advertisingRepository.existsById(advertisingId)) {
|
||||
log.debug("Click skipped: advertisingId={} does not exist", advertisingId);
|
||||
return;
|
||||
}
|
||||
Advertising advertising = advertisingRepository.getReferenceById(advertisingId);
|
||||
|
||||
Click click = new Click();
|
||||
click.setAdvertising(advertising);
|
||||
click.setUserId(userId);
|
||||
click.setSessionId(AdSessionId.normalize(sessionId));
|
||||
|
||||
Click save = clickRepository.save(click);
|
||||
log.debug("click {} saved", save.getId());
|
||||
}
|
||||
|
||||
private Long extractUserId(Authentication authentication) {
|
||||
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
return userService.getUserIdByLogin(login);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,69 +1,100 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.core.script.DefaultRedisScript;
|
||||
import org.springframework.data.redis.core.script.RedisScript;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Частотные ограничения рекламы в Redis (общие для всех экземпляров).
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Дневной лимит кампании</b> — сколько показов кампании видел субъект
|
||||
* (пользователь {@code u<id>} или сессия {@code s<id>}) за календарные сутки
|
||||
* в часовом поясе рекламы: {@code ad:cap:<субъект>:<кампания>:<yyyyMMdd>}.
|
||||
* Растёт по факту показа (а не выдачи), ключ живёт 48 часов.</li>
|
||||
* <li><b>Пауза между показами</b> — {@code ad:cooldown:<субъект>}, SET NX с TTL.</li>
|
||||
* <li><b>Однократный учёт</b> показа и клика по токену — {@code ad:imp:<nonce>},
|
||||
* {@code ad:clk:<nonce>}, SET NX на срок жизни токена.</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Ошибки Redis пробрасываются: решение (показать или нет) принимает вызывающий код.
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdvertisingFrequencyService {
|
||||
|
||||
private static final Duration FREQ_TTL = Duration.ofHours(24);
|
||||
private static final Duration SESSION_COOLDOWN = Duration.ofSeconds(30);
|
||||
private static final Duration CAP_KEY_TTL = Duration.ofHours(48);
|
||||
private static final DateTimeFormatter DAY = DateTimeFormatter.BASIC_ISO_DATE;
|
||||
|
||||
private static final RedisScript<Long> INCREMENT_WITH_TTL = new DefaultRedisScript<>("""
|
||||
local count = redis.call('INCR', KEYS[1])
|
||||
if count == 1 then
|
||||
redis.call('PEXPIRE', KEYS[1], ARGV[1])
|
||||
end
|
||||
return count
|
||||
""", Long.class);
|
||||
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final AdsProperties properties;
|
||||
|
||||
/**
|
||||
* Проверяет и атомарно увеличивает счётчик показов объявления пользователю
|
||||
* (или анонимной сессии, если userId отсутствует).
|
||||
* Возвращает true, если показ укладывается в dailyCap.
|
||||
*/
|
||||
public boolean tryRegisterImpression(Long userId, String sessionId, Long adId, int dailyCap) {
|
||||
String key = freqKey(userId, sessionId, adId);
|
||||
// При недоступном Redis increment бросает DataAccessException — её обрабатывает
|
||||
// AdvertisingSelectionService. null возможен только внутри pipeline/транзакции Redis.
|
||||
Long count = redisTemplate.opsForValue().increment(key);
|
||||
if (count == null) {
|
||||
return true;
|
||||
}
|
||||
if (count == 1L) {
|
||||
redisTemplate.expire(key, FREQ_TTL);
|
||||
}
|
||||
return count <= dailyCap;
|
||||
/** Субъект частоты: авторизованный пользователь или сессия/устройство гостя. */
|
||||
public static String subject(Long userId, String sessionId) {
|
||||
return userId != null ? "u" + userId : "s" + sessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Откатывает счётчик, если после инкремента показ всё же не состоялся
|
||||
* (например, объявление не прошло другие проверки в AdSelectionService).
|
||||
* Ставит паузу между показами для субъекта. false — пауза ещё идёт
|
||||
* (реклама показывалась недавно), показывать нельзя.
|
||||
*/
|
||||
public void rollback(Long userId, String sessionId, Long adId) {
|
||||
String key = freqKey(userId, sessionId, adId);
|
||||
Long count = redisTemplate.opsForValue().decrement(key);
|
||||
if (count != null && count <= 0) {
|
||||
redisTemplate.delete(key);
|
||||
public boolean tryStartCooldown(String subject) {
|
||||
Boolean started = redisTemplate.opsForValue()
|
||||
.setIfAbsent("ad:cooldown:" + subject, "1", properties.getSessionCooldown());
|
||||
return Boolean.TRUE.equals(started);
|
||||
}
|
||||
|
||||
/** Сегодняшние показы субъекту по каждой кампании (одним MGET). */
|
||||
public Map<Long, Long> todayImpressions(String subject, Collection<Long> campaignIds) {
|
||||
List<Long> ids = new ArrayList<>(campaignIds);
|
||||
Map<Long, Long> result = new HashMap<>();
|
||||
if (ids.isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
String day = today();
|
||||
List<String> values = redisTemplate.opsForValue().multiGet(ids.stream().map(id -> capKey(subject, id, day)).toList());
|
||||
for (int i = 0; i < ids.size(); i++) {
|
||||
String value = values == null ? null : values.get(i);
|
||||
result.put(ids.get(i), value == null ? 0L : Long.parseLong(value));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Минимальный интервал между показами любой рекламы в рамках одной сессии,
|
||||
* независимо от дневного капа конкретного объявления.
|
||||
*/
|
||||
public boolean isSessionCooldownPassed(String sessionId) {
|
||||
String key = sessionCooldownKey(sessionId);
|
||||
Boolean wasAbsent = redisTemplate.opsForValue()
|
||||
.setIfAbsent(key, Instant.now().toString(), SESSION_COOLDOWN);
|
||||
return Boolean.TRUE.equals(wasAbsent);
|
||||
/** Засчитывает показ кампании субъекту за сегодня. */
|
||||
public void registerImpression(String subject, long campaignId) {
|
||||
redisTemplate.execute(INCREMENT_WITH_TTL, List.of(capKey(subject, campaignId, today())),
|
||||
Long.toString(CAP_KEY_TTL.toMillis()));
|
||||
}
|
||||
|
||||
private String freqKey(Long userId, String sessionId, Long adId) {
|
||||
String subject = userId != null ? "u" + userId : "s" + sessionId;
|
||||
return "ad:freq:%s:%d".formatted(subject, adId);
|
||||
/** true, если событие с этим nonce ещё не учитывалось (и теперь отмечено). */
|
||||
public boolean markOnce(String kind, String nonce, Duration ttl) {
|
||||
Boolean first = redisTemplate.opsForValue().setIfAbsent("ad:" + kind + ":" + nonce, "1", ttl);
|
||||
return Boolean.TRUE.equals(first);
|
||||
}
|
||||
|
||||
private String sessionCooldownKey(String sessionId) {
|
||||
return "ad:session:%s:cooldown".formatted(sessionId);
|
||||
private String today() {
|
||||
return LocalDate.now(properties.getTimezone()).format(DAY);
|
||||
}
|
||||
|
||||
private static String capKey(String subject, long campaignId, String day) {
|
||||
return "ad:cap:" + subject + ":" + campaignId + ":" + day;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Advertising;
|
||||
import com.krylov.refound.entity.advertising.Impression;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.repository.advertising.ImpressionRepository;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import com.krylov.refound.util.AdSessionId;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdvertisingImpressionService {
|
||||
private final UserService userService;
|
||||
private final ImpressionRepository impressionRepository;
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
|
||||
@Transactional
|
||||
public void recordImpression(Long advertisingId, Authentication authentication, String sessionId) {
|
||||
Long userId = extractUserId(authentication);
|
||||
// getReferenceById не проверяет существование: несуществующий id падал
|
||||
// на внешнем ключе при коммите (500), а catch EntityNotFoundException не срабатывал
|
||||
if (advertisingId == null || !advertisingRepository.existsById(advertisingId)) {
|
||||
log.debug("Impression skipped: advertisingId={} does not exist", advertisingId);
|
||||
return;
|
||||
}
|
||||
Advertising advertising = advertisingRepository.getReferenceById(advertisingId);
|
||||
|
||||
Impression impression = new Impression();
|
||||
impression.setAdvertising(advertising);
|
||||
impression.setUserId(userId);
|
||||
impression.setSessionId(AdSessionId.normalize(sessionId));
|
||||
|
||||
Impression save = impressionRepository.save(impression);
|
||||
log.debug("impression {} saved", save.getId());
|
||||
}
|
||||
|
||||
private Long extractUserId(Authentication authentication) {
|
||||
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
return userService.getUserIdByLogin(login);
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,36 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import com.krylov.refound.dto.advertising.EligibleAdvertising;
|
||||
import com.krylov.refound.dto.advertising.SelectedAdvertisingDto;
|
||||
import com.krylov.refound.entity.advertising.Advertising;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import com.krylov.refound.util.AdSessionId;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
/**
|
||||
* Выбор рекламы для показа (ad decisioning):
|
||||
* <ol>
|
||||
* <li>кандидаты — объявления активных кампаний в их окне дат с готовым медиа
|
||||
* (снимок кэшируется в памяти на {@code ads.eligible-cache-ttl});</li>
|
||||
* <li>кампании, исчерпавшие дневной лимит показов этому пользователю/сессии,
|
||||
* отсекаются (лимит считается по фактическим показам за календарные сутки);</li>
|
||||
* <li>среди оставшихся — взвешенная случайная выборка по weight;</li>
|
||||
* <li>пауза между показами одному субъекту ({@code ads.session-cooldown});</li>
|
||||
* <li>к выбранному объявлению выдаётся подписанный токен показа
|
||||
* ({@link AdTrackingTokenService}), по которому клиент сообщит о показе и клике.</li>
|
||||
* </ol>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -26,88 +39,107 @@ public class AdvertisingSelectionService {
|
||||
private final UserService userService;
|
||||
private final AdvertisingRepository adRepository;
|
||||
private final AdvertisingFrequencyService frequencyService;
|
||||
private final AdTrackingTokenService trackingTokenService;
|
||||
private final AdsProperties properties;
|
||||
|
||||
private volatile Snapshot snapshot;
|
||||
|
||||
private record Snapshot(Instant loadedAt, List<EligibleAdvertising> ads) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбирает одно объявление для показа пользователю/сессии с учётом
|
||||
* частотного капа и весов кампаний. Перебирает кандидатов в случайном
|
||||
* порядке, взвешенном по weight, пока не найдёт первое разрешённое.
|
||||
*/
|
||||
public Optional<SelectedAdvertisingDto> selectAdvertising(Authentication authentication, String sessionId, HttpServletRequest request) {
|
||||
|
||||
Long userId = extractUserId(authentication);
|
||||
// Приложение stateless: request.getSession(true) заводил HTTP-сессию в памяти Tomcat
|
||||
// на каждый запрос без X-Session-Id. Без заголовка частоту считаем по IP клиента.
|
||||
// Приложение stateless: HTTP-сессию не заводим. Без X-Session-Id гость
|
||||
// учитывается по IP клиента.
|
||||
String resolvedSessionId = sessionId != null && !sessionId.isBlank()
|
||||
? AdSessionId.normalize(sessionId)
|
||||
: AdSessionId.normalize("ip:" + request.getRemoteAddr());
|
||||
String subject = AdvertisingFrequencyService.subject(userId, resolvedSessionId);
|
||||
|
||||
try {
|
||||
return select(userId, resolvedSessionId);
|
||||
return select(subject);
|
||||
} catch (DataAccessException e) {
|
||||
// Капы и кулдаун живут в Redis. Без него не показываем рекламу (204),
|
||||
// а не роняем запрос с 500 и не показываем её без ограничений.
|
||||
// Лимиты живут в Redis. Без него рекламу не показываем (204), а не роняем
|
||||
// запрос с 500 и не показываем её без ограничений.
|
||||
log.warn("Redis недоступен, реклама не выбрана: {}", e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<SelectedAdvertisingDto> select(Long userId, String resolvedSessionId) {
|
||||
if (!frequencyService.isSessionCooldownPassed(resolvedSessionId)) {
|
||||
log.debug("Session cooldown not passed for sessionId={}", resolvedSessionId);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
List<Advertising> eligible = adRepository.findEligibleAds(LocalDateTime.now());
|
||||
private Optional<SelectedAdvertisingDto> select(String subject) {
|
||||
List<EligibleAdvertising> eligible = eligibleAds();
|
||||
if (eligible.isEmpty()) {
|
||||
log.debug("No eligible ads to show");
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
for (Advertising candidate : weightedOrder(eligible)) {
|
||||
int dailyCap = candidate.getCampaign().getDailyImpressionCap();
|
||||
boolean allowed = frequencyService.tryRegisterImpression(userId, resolvedSessionId, candidate.getId(), dailyCap);
|
||||
|
||||
if (allowed) {
|
||||
log.debug("advertising candidate {}", candidate.getId());
|
||||
return Optional.of(toDto(candidate));
|
||||
}
|
||||
log.debug("rollback dailyCap for candidate {}", candidate.getId());
|
||||
frequencyService.rollback(userId, resolvedSessionId, candidate.getId());
|
||||
Map<Long, Long> shownToday = frequencyService.todayImpressions(subject,
|
||||
eligible.stream().map(EligibleAdvertising::campaignId).distinct().toList());
|
||||
List<EligibleAdvertising> underCap = eligible.stream()
|
||||
.filter(ad -> shownToday.getOrDefault(ad.campaignId(), 0L) < capOf(ad))
|
||||
.toList();
|
||||
if (underCap.isEmpty()) {
|
||||
log.debug("All campaigns reached the daily cap for subject={}", subject);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
log.debug("No ad passed frequency cap for userId={}, sessionId={}", userId, resolvedSessionId);
|
||||
return Optional.empty();
|
||||
EligibleAdvertising chosen = pickWeighted(underCap);
|
||||
// Пауза ставится атомарно в момент выдачи: параллельные запросы одного
|
||||
// клиента не получат две рекламы подряд
|
||||
if (!frequencyService.tryStartCooldown(subject)) {
|
||||
log.debug("Cooldown not passed for subject={}", subject);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
String token = trackingTokenService.issue(chosen.advertisingId(), chosen.campaignId(), subject);
|
||||
return Optional.of(new SelectedAdvertisingDto(chosen.advertisingId(), chosen.type().name(), chosen.mediaKey(),
|
||||
chosen.targetUrl(), token));
|
||||
}
|
||||
|
||||
/** Сбрасывает кэш кандидатов этого экземпляра (после правок в админке). */
|
||||
public void invalidateCache() {
|
||||
snapshot = null;
|
||||
}
|
||||
|
||||
List<EligibleAdvertising> eligibleAds() {
|
||||
Snapshot current = snapshot;
|
||||
Instant now = Instant.now();
|
||||
if (current == null || current.loadedAt().plus(properties.getEligibleCacheTtl()).isBefore(now)) {
|
||||
current = new Snapshot(now, adRepository.findEligible(LocalDateTime.now(properties.getTimezone())));
|
||||
snapshot = current;
|
||||
}
|
||||
return current.ads();
|
||||
}
|
||||
|
||||
private static long capOf(EligibleAdvertising ad) {
|
||||
return ad.dailyImpressionCap() == null ? Long.MAX_VALUE : ad.dailyImpressionCap();
|
||||
}
|
||||
|
||||
private Long extractUserId(Authentication authentication) {
|
||||
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
return userService.getUserIdByLogin(login);
|
||||
return userService.getUserIdByLogin(authentication.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Взвешенная выборка без повторов (алгоритм Ефраимидиса-Спиракиса):
|
||||
* каждому объявлению присваивается ключ u^(1/weight), сортировка по
|
||||
* убыванию ключа даёт порядок, эквивалентный последовательному
|
||||
* взвешенному семплированию без возврата.
|
||||
* Взвешенный случайный выбор (алгоритм Ефраимидиса-Спиракиса): каждому объявлению
|
||||
* ключ u^(1/weight), побеждает максимальный — вероятность пропорциональна весу.
|
||||
* Ключ считается один раз на объявление: прежняя версия генерировала случайное
|
||||
* число внутри компаратора сортировки, что нарушало контракт Comparator.
|
||||
*/
|
||||
private List<Advertising> weightedOrder(List<Advertising> ads) {
|
||||
static EligibleAdvertising pickWeighted(List<EligibleAdvertising> ads) {
|
||||
ThreadLocalRandom random = ThreadLocalRandom.current();
|
||||
return ads.stream()
|
||||
.sorted(Comparator.comparingDouble(
|
||||
(Advertising ad) -> Math.pow(random.nextDouble(), 1.0 / Math.max(ad.getWeight(), 1)))
|
||||
.reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private SelectedAdvertisingDto toDto(Advertising ad) {
|
||||
return new SelectedAdvertisingDto(
|
||||
ad.getId(),
|
||||
ad.getType().name(),
|
||||
ad.getMediaKey(),
|
||||
ad.getTargetUrl());
|
||||
EligibleAdvertising best = null;
|
||||
double bestKey = -1;
|
||||
for (EligibleAdvertising ad : ads) {
|
||||
int weight = Math.max(ad.weight() == null ? 1 : ad.weight(), 1);
|
||||
double key = Math.pow(random.nextDouble(), 1.0 / weight);
|
||||
if (key > bestKey) {
|
||||
bestKey = key;
|
||||
best = ad;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class AdvertisingStatusService {
|
||||
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
private final AdvertisingSelectionService selectionService;
|
||||
// Транскодинг идёт в любом экземпляре, а админ может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
|
||||
@@ -22,6 +23,7 @@ public class AdvertisingStatusService {
|
||||
ad.setMediaKey(mediaKey);
|
||||
ad.setTranscodingStatus(TranscodingStatus.READY);
|
||||
});
|
||||
selectionService.invalidateCache();
|
||||
notifyStatusChange(advertisingId, TranscodingStatus.READY);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Click;
|
||||
import com.krylov.refound.entity.advertising.Impression;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.repository.advertising.ClickRepository;
|
||||
import com.krylov.refound.repository.advertising.ImpressionRepository;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import com.krylov.refound.util.AdSessionId;
|
||||
import java.util.Optional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* Учёт показов и кликов рекламы.
|
||||
*
|
||||
* <p>Основной путь — по токену показа из {@code GET /api/ads/next}: подпись
|
||||
* подтверждает, что реклама действительно выдавалась этому субъекту, nonce —
|
||||
* что событие учитывается один раз. Показ по токену увеличивает дневной
|
||||
* счётчик кампании (частотный лимит считается по фактическим показам).
|
||||
*
|
||||
* <p>Запросы без токена (старые клиенты) принимаются, пока
|
||||
* {@code ads.tracking.require-token=false}: учитываются как раньше, но без
|
||||
* защиты от повторов. После обновления фронта флаг нужно включить.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AdvertisingTrackingService {
|
||||
|
||||
private final UserService userService;
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
private final ImpressionRepository impressionRepository;
|
||||
private final ClickRepository clickRepository;
|
||||
private final AdTrackingTokenService tokenService;
|
||||
private final AdvertisingFrequencyService frequencyService;
|
||||
private final AdsProperties properties;
|
||||
|
||||
private enum Kind { IMPRESSION, CLICK }
|
||||
|
||||
/** Источник события после проверки: какое объявление, чьё и с какой сессией. */
|
||||
private record Event(long advertisingId, long campaignId, String subject, Long userId, String sessionId) {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void recordImpression(Long advertisingId, Authentication authentication, String sessionId, String token) {
|
||||
resolve(Kind.IMPRESSION, advertisingId, authentication, sessionId, token).ifPresent(event -> {
|
||||
try {
|
||||
frequencyService.registerImpression(event.subject(), event.campaignId());
|
||||
} catch (DataAccessException e) {
|
||||
// Показ всё равно сохраняем в БД; лимит за этот показ не вырастет
|
||||
log.warn("Не удалось учесть показ в дневном лимите: {}", e.getMessage());
|
||||
}
|
||||
Impression impression = new Impression();
|
||||
impression.setAdvertising(advertisingRepository.getReferenceById(event.advertisingId()));
|
||||
impression.setUserId(event.userId());
|
||||
impression.setSessionId(event.sessionId());
|
||||
impressionRepository.save(impression);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void recordClick(Long advertisingId, Authentication authentication, String sessionId, String token) {
|
||||
resolve(Kind.CLICK, advertisingId, authentication, sessionId, token).ifPresent(event -> {
|
||||
Click click = new Click();
|
||||
click.setAdvertising(advertisingRepository.getReferenceById(event.advertisingId()));
|
||||
click.setUserId(event.userId());
|
||||
click.setSessionId(event.sessionId());
|
||||
clickRepository.save(click);
|
||||
});
|
||||
}
|
||||
|
||||
private Optional<Event> resolve(Kind kind, Long advertisingId, Authentication authentication, String sessionId,
|
||||
String token) {
|
||||
String normalizedSession = AdSessionId.normalize(sessionId);
|
||||
if (token != null && !token.isBlank()) {
|
||||
return fromToken(kind, advertisingId, normalizedSession, token);
|
||||
}
|
||||
if (properties.getTracking().isRequireToken()) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Нужен токен показа", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return legacy(advertisingId, authentication, normalizedSession);
|
||||
}
|
||||
|
||||
private Optional<Event> fromToken(Kind kind, Long advertisingId, String sessionId, String token) {
|
||||
AdTrackingTokenService.Claims claims = tokenService.verify(token).orElse(null);
|
||||
if (claims == null) {
|
||||
log.debug("{} skipped: invalid or expired tracking token", kind);
|
||||
return Optional.empty();
|
||||
}
|
||||
if (advertisingId != null && advertisingId != claims.advertisingId()) {
|
||||
log.debug("{} skipped: advertisingId {} does not match token", kind, advertisingId);
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!markOnce(kind, claims.nonce())) {
|
||||
log.debug("{} skipped: token already used", kind);
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!advertisingRepository.existsById(claims.advertisingId())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Long userId = claims.subject().startsWith("u") ? Long.valueOf(claims.subject().substring(1)) : null;
|
||||
String session = !AdSessionId.UNKNOWN.equals(sessionId) ? sessionId
|
||||
: AdSessionId.normalize(claims.subject().substring(1));
|
||||
return Optional.of(new Event(claims.advertisingId(), claims.campaignId(), claims.subject(), userId, session));
|
||||
}
|
||||
|
||||
private Optional<Event> legacy(Long advertisingId, Authentication authentication, String sessionId) {
|
||||
if (advertisingId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<Long> campaignId = advertisingRepository.findCampaignIdById(advertisingId);
|
||||
if (campaignId.isEmpty()) {
|
||||
log.debug("Tracking skipped: advertisingId={} does not exist", advertisingId);
|
||||
return Optional.empty();
|
||||
}
|
||||
Long userId = extractUserId(authentication);
|
||||
String subject = AdvertisingFrequencyService.subject(userId, sessionId);
|
||||
return Optional.of(new Event(advertisingId, campaignId.get(), subject, userId, sessionId));
|
||||
}
|
||||
|
||||
private boolean markOnce(Kind kind, String nonce) {
|
||||
try {
|
||||
return frequencyService.markOnce(kind == Kind.IMPRESSION ? "imp" : "clk", nonce,
|
||||
properties.getTracking().getTokenTtl());
|
||||
} catch (DataAccessException e) {
|
||||
// Без Redis повтор не отличить — засчитываем, чтобы не терять статистику
|
||||
log.warn("Не удалось проверить повтор события рекламы: {}", e.getMessage());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private Long extractUserId(Authentication authentication) {
|
||||
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
|
||||
return null;
|
||||
}
|
||||
return userService.getUserIdByLogin(authentication.getName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import com.krylov.refound.repository.advertising.CampaignRepository;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.EnumSet;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* Автоматическое завершение кампаний: ACTIVE и PAUSED с прошедшим endDate
|
||||
* переводятся в FINISHED. Без этого статус в админке оставался ACTIVE, хотя
|
||||
* реклама уже не показывалась.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CampaignLifecycleService {
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final AdvertisingSelectionService selectionService;
|
||||
private final AdsProperties properties;
|
||||
|
||||
@Scheduled(cron = "${ads.finish-expired-cron:0 */10 * * * *}")
|
||||
@SchedulerLock(name = "finishExpiredCampaigns", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S")
|
||||
@Transactional
|
||||
public void finishExpiredCampaigns() {
|
||||
int finished = campaignRepository.finishExpired(LocalDateTime.now(properties.getTimezone()),
|
||||
EnumSet.of(CampaignStatus.ACTIVE, CampaignStatus.PAUSED), CampaignStatus.FINISHED);
|
||||
if (finished > 0) {
|
||||
log.info("Завершено кампаний по дате окончания: {}", finished);
|
||||
selectionService.invalidateCache();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class CampaignService {
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final AdvertisingSelectionService selectionService;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CampaignResponseDto> getCampaign() {
|
||||
@@ -66,6 +67,7 @@ public class CampaignService {
|
||||
campaign.setDailyImpressionCap(request.dailyImpressionCap());
|
||||
|
||||
log.info("campaign {} updated", campaignId);
|
||||
selectionService.invalidateCache();
|
||||
return toDto(campaign);
|
||||
}
|
||||
|
||||
@@ -86,6 +88,7 @@ public class CampaignService {
|
||||
// Раньше статус менялся bulk-UPDATE'ом, а ответ собирался из сущности
|
||||
// со старым статусом — фронт видел прежнее значение
|
||||
campaign.setStatus(request.status());
|
||||
selectionService.invalidateCache();
|
||||
return toDto(campaign);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import com.krylov.refound.dto.advertising.AdvertisingStatsDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignStatsDto;
|
||||
import com.krylov.refound.entity.advertising.Advertising;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.repository.advertising.CampaignRepository;
|
||||
import com.krylov.refound.repository.advertising.ClickRepository;
|
||||
import com.krylov.refound.repository.advertising.ImpressionRepository;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/** Отчёт по кампании: показы, клики и CTR по каждому объявлению за период. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CampaignStatsService {
|
||||
|
||||
/** Период по умолчанию и максимальная длина периода отчёта. */
|
||||
static final int DEFAULT_DAYS = 30;
|
||||
static final int MAX_DAYS = 366;
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
private final ImpressionRepository impressionRepository;
|
||||
private final ClickRepository clickRepository;
|
||||
private final AdsProperties properties;
|
||||
|
||||
/**
|
||||
* @param from первый день периода (включительно), по умолчанию 30 дней назад
|
||||
* @param to последний день периода (включительно), по умолчанию сегодня
|
||||
*/
|
||||
@Transactional(readOnly = true)
|
||||
public CampaignStatsDto getStats(Long campaignId, LocalDate from, LocalDate to) {
|
||||
if (!campaignRepository.existsById(campaignId)) {
|
||||
throw new EntityNotFoundException("Campaign not found: " + campaignId);
|
||||
}
|
||||
LocalDate end = to != null ? to : LocalDate.now(properties.getTimezone());
|
||||
LocalDate start = from != null ? from : end.minusDays(DEFAULT_DAYS - 1L);
|
||||
if (start.isAfter(end) || start.plusDays(MAX_DAYS).isBefore(end)) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||
"Период: from не позже to и не длиннее " + MAX_DAYS + " дней", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
Map<Long, Long> impressions = toMap(impressionRepository.countByAdvertising(campaignId,
|
||||
start.atStartOfDay(), end.plusDays(1).atStartOfDay()));
|
||||
Map<Long, Long> clicks = toMap(clickRepository.countByAdvertising(campaignId,
|
||||
start.atStartOfDay(), end.plusDays(1).atStartOfDay()));
|
||||
|
||||
List<AdvertisingStatsDto> ads = advertisingRepository.findAllByCampaignIdOrderByCreatedAtDesc(campaignId).stream()
|
||||
.map(Advertising::getId)
|
||||
.map(id -> {
|
||||
long shown = impressions.getOrDefault(id, 0L);
|
||||
long clicked = clicks.getOrDefault(id, 0L);
|
||||
return new AdvertisingStatsDto(id, shown, clicked, ctr(shown, clicked));
|
||||
})
|
||||
.toList();
|
||||
|
||||
long totalImpressions = impressions.values().stream().mapToLong(Long::longValue).sum();
|
||||
long totalClicks = clicks.values().stream().mapToLong(Long::longValue).sum();
|
||||
return new CampaignStatsDto(campaignId, start, end, totalImpressions, totalClicks,
|
||||
ctr(totalImpressions, totalClicks), ads);
|
||||
}
|
||||
|
||||
private static Map<Long, Long> toMap(List<Object[]> rows) {
|
||||
Map<Long, Long> result = new HashMap<>();
|
||||
for (Object[] row : rows) {
|
||||
result.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** CTR в процентах с двумя знаками; 0 при отсутствии показов. */
|
||||
static double ctr(long impressions, long clicks) {
|
||||
if (impressions == 0) {
|
||||
return 0;
|
||||
}
|
||||
return Math.round(clicks * 10_000.0 / impressions) / 100.0;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.krylov.refound.util;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Идентификатор рекламной сессии от клиента (X-Session-Id или поле sessionId).
|
||||
* Он попадает в ключи Redis и в колонки session_id VARCHAR(64), поэтому длина
|
||||
@@ -10,6 +12,7 @@ public final class AdSessionId {
|
||||
public static final int MAX_LENGTH = 64;
|
||||
/** impression.session_id — NOT NULL; клиент без идентификатора всё равно учитывается. */
|
||||
public static final String UNKNOWN = "unknown";
|
||||
private static final Pattern SAFE = Pattern.compile("[^A-Za-z0-9._:-]");
|
||||
|
||||
private AdSessionId() {
|
||||
}
|
||||
@@ -18,7 +21,9 @@ public final class AdSessionId {
|
||||
if (sessionId == null || sessionId.isBlank()) {
|
||||
return UNKNOWN;
|
||||
}
|
||||
String trimmed = sessionId.trim();
|
||||
return trimmed.length() > MAX_LENGTH ? trimmed.substring(0, MAX_LENGTH) : trimmed;
|
||||
// Идентификатор попадает в ключи Redis и в токен показа (разделитель '|'):
|
||||
// оставляем только безопасные символы
|
||||
String cleaned = SAFE.matcher(sessionId.trim()).replaceAll("_");
|
||||
return cleaned.length() > MAX_LENGTH ? cleaned.substring(0, MAX_LENGTH) : cleaned;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,3 +176,17 @@ rate-limit:
|
||||
paths: [/api/ads/impression, /api/ads/click]
|
||||
limit: 120
|
||||
window: PT1M
|
||||
|
||||
# Реклама (docs/advertising.md)
|
||||
ads:
|
||||
# Пояс дат кампаний и календарных суток дневного лимита
|
||||
timezone: ${ADS_TIMEZONE:Europe/Moscow}
|
||||
session-cooldown: PT30S # пауза между показами одному пользователю/сессии
|
||||
eligible-cache-ttl: PT30S # кэш кандидатов в памяти экземпляра
|
||||
finish-expired-cron: "0 */10 * * * *"
|
||||
tracking:
|
||||
# HMAC-ключ токенов показа; пусто — используется jwt.secret
|
||||
secret: ${ADS_TRACKING_SECRET:}
|
||||
token-ttl: PT1H
|
||||
# true — показы/клики без токена отклоняются (включить после обновления фронта)
|
||||
require-token: ${ADS_REQUIRE_TRACKING_TOKEN:false}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 021-impression-advertising-shown-at
|
||||
author: krylov
|
||||
comment: >
|
||||
Отчёт по кампании (CampaignStatsService) считает показы по объявлению за период.
|
||||
Составной индекс (advertising_id, shown_at); одиночный idx_impression_advertising_id им покрывается.
|
||||
preConditions:
|
||||
onFail: MARK_RAN
|
||||
not:
|
||||
indexExists:
|
||||
tableName: impression
|
||||
indexName: idx_impression_advertising_shown_at
|
||||
changes:
|
||||
- createIndex:
|
||||
tableName: impression
|
||||
indexName: idx_impression_advertising_shown_at
|
||||
columns:
|
||||
- column: { name: advertising_id }
|
||||
- column: { name: shown_at }
|
||||
- changeSet:
|
||||
id: 021-click-advertising-clicked-at
|
||||
author: krylov
|
||||
preConditions:
|
||||
onFail: MARK_RAN
|
||||
not:
|
||||
indexExists:
|
||||
tableName: click
|
||||
indexName: idx_click_advertising_clicked_at
|
||||
changes:
|
||||
- createIndex:
|
||||
tableName: click
|
||||
indexName: idx_click_advertising_clicked_at
|
||||
columns:
|
||||
- column: { name: advertising_id }
|
||||
- column: { name: clicked_at }
|
||||
@@ -33,3 +33,4 @@ databaseChangeLog:
|
||||
- include: { file: db/changelog/add/018-add-address-posts.yaml }
|
||||
- include: { file: db/changelog/search/019-posts-full-text-search.yaml }
|
||||
- include: { file: db/changelog/search/020-search-words.yaml }
|
||||
- include: { file: db/changelog/add/021-ad-stats-indexes.yaml }
|
||||
|
||||
@@ -3,8 +3,7 @@ package com.krylov.refound.service.advertising;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyCollection;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
@@ -14,24 +13,44 @@ import static org.mockito.Mockito.when;
|
||||
import com.krylov.refound.dto.advertising.AdvertisingCreateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignResponseDto;
|
||||
import com.krylov.refound.dto.advertising.CampaignStatusUpdateRequestDto;
|
||||
import com.krylov.refound.dto.advertising.EligibleAdvertising;
|
||||
import com.krylov.refound.dto.advertising.SelectedAdvertisingDto;
|
||||
import com.krylov.refound.entity.advertising.Campaign;
|
||||
import com.krylov.refound.entity.advertising.Impression;
|
||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.repository.advertising.CampaignRepository;
|
||||
import com.krylov.refound.repository.advertising.ImpressionRepository;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import com.krylov.refound.util.AdTargetUrl;
|
||||
import java.time.Clock;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.data.redis.RedisConnectionFailureException;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
|
||||
class AdvertisingServicesTest {
|
||||
|
||||
private AdvertisingRepository advertisingRepository;
|
||||
private AdvertisingFrequencyService frequency;
|
||||
private AdTrackingTokenService tokenService;
|
||||
private AdvertisingSelectionService selection;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
advertisingRepository = mock(AdvertisingRepository.class);
|
||||
frequency = mock(AdvertisingFrequencyService.class);
|
||||
AdsProperties properties = new AdsProperties();
|
||||
tokenService = new AdTrackingTokenService(properties, "test-secret-test-secret-test-secret-0123456789",
|
||||
Clock.systemUTC());
|
||||
selection = new AdvertisingSelectionService(mock(UserService.class), advertisingRepository, frequency,
|
||||
tokenService, properties);
|
||||
}
|
||||
|
||||
@Test
|
||||
void campaignStatusChangeReturnsNewStatus() {
|
||||
CampaignRepository repository = mock(CampaignRepository.class);
|
||||
@@ -40,7 +59,7 @@ class AdvertisingServicesTest {
|
||||
campaign.setStatus(CampaignStatus.DRAFT);
|
||||
when(repository.findById(1L)).thenReturn(Optional.of(campaign));
|
||||
|
||||
CampaignResponseDto dto = new CampaignService(repository)
|
||||
CampaignResponseDto dto = new CampaignService(repository, selection)
|
||||
.updateCampaignStatus(1L, new CampaignStatusUpdateRequestDto(CampaignStatus.ACTIVE));
|
||||
|
||||
assertThat(dto.status()).isEqualTo(CampaignStatus.ACTIVE);
|
||||
@@ -48,49 +67,88 @@ class AdvertisingServicesTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void selectionWithoutSessionHeaderDoesNotCreateHttpSession() {
|
||||
AdvertisingFrequencyService frequency = mock(AdvertisingFrequencyService.class);
|
||||
when(frequency.isSessionCooldownPassed(anyString())).thenReturn(false);
|
||||
AdvertisingSelectionService service = new AdvertisingSelectionService(mock(UserService.class),
|
||||
mock(AdvertisingRepository.class), frequency);
|
||||
void selectedAdCarriesVerifiableImpressionToken() {
|
||||
when(advertisingRepository.findEligible(any())).thenReturn(List.of(ad(10L, 1L, 5)));
|
||||
when(frequency.todayImpressions(anyString(), anyCollection())).thenReturn(Map.of(1L, 0L));
|
||||
when(frequency.tryStartCooldown("s-session-1")).thenReturn(true);
|
||||
|
||||
SelectedAdvertisingDto selected = selection.selectAdvertising(null, "-session-1", new MockHttpServletRequest())
|
||||
.orElseThrow();
|
||||
|
||||
AdTrackingTokenService.Claims claims = tokenService.verify(selected.impressionToken()).orElseThrow();
|
||||
assertThat(claims.advertisingId()).isEqualTo(10L);
|
||||
assertThat(claims.campaignId()).isEqualTo(1L);
|
||||
assertThat(claims.subject()).isEqualTo("s-session-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void campaignThatReachedDailyCapIsSkipped() {
|
||||
when(advertisingRepository.findEligible(any())).thenReturn(List.of(ad(10L, 1L, 3), ad(20L, 2L, 3)));
|
||||
Map<Long, Long> shown = new HashMap<>();
|
||||
shown.put(1L, 3L);
|
||||
shown.put(2L, 0L);
|
||||
when(frequency.todayImpressions(anyString(), anyCollection())).thenReturn(shown);
|
||||
when(frequency.tryStartCooldown(anyString())).thenReturn(true);
|
||||
|
||||
for (int i = 0; i < 20; i++) {
|
||||
selection.invalidateCache();
|
||||
assertThat(selection.selectAdvertising(null, "s", new MockHttpServletRequest()).orElseThrow().advertisingId())
|
||||
.isEqualTo(20L);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void nothingIsServedDuringCooldown() {
|
||||
when(advertisingRepository.findEligible(any())).thenReturn(List.of(ad(10L, 1L, 5)));
|
||||
when(frequency.todayImpressions(anyString(), anyCollection())).thenReturn(Map.of(1L, 0L));
|
||||
when(frequency.tryStartCooldown(anyString())).thenReturn(false);
|
||||
|
||||
assertThat(selection.selectAdvertising(null, "s", new MockHttpServletRequest())).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void eligibleAdsAreCachedBetweenRequests() {
|
||||
when(advertisingRepository.findEligible(any())).thenReturn(List.of());
|
||||
|
||||
selection.selectAdvertising(null, "s", new MockHttpServletRequest());
|
||||
selection.selectAdvertising(null, "s", new MockHttpServletRequest());
|
||||
|
||||
verify(advertisingRepository, org.mockito.Mockito.times(1)).findEligible(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void selectionWithoutSessionHeaderUsesClientIpAndNoHttpSession() {
|
||||
when(advertisingRepository.findEligible(any())).thenReturn(List.of(ad(10L, 1L, 5)));
|
||||
when(frequency.todayImpressions(anyString(), anyCollection())).thenReturn(Map.of(1L, 0L));
|
||||
MockHttpServletRequest request = new MockHttpServletRequest();
|
||||
request.setRemoteAddr("10.0.0.7");
|
||||
|
||||
assertThat(service.selectAdvertising(null, null, request)).isEmpty();
|
||||
selection.selectAdvertising(null, null, request);
|
||||
|
||||
assertThat(request.getSession(false)).isNull();
|
||||
verify(frequency).isSessionCooldownPassed("ip:10.0.0.7");
|
||||
verify(frequency).tryStartCooldown("sip:10.0.0.7");
|
||||
}
|
||||
|
||||
@Test
|
||||
void selectionReturnsNothingWhenRedisIsDown() {
|
||||
AdvertisingFrequencyService frequency = mock(AdvertisingFrequencyService.class);
|
||||
when(frequency.isSessionCooldownPassed(anyString())).thenThrow(new RedisConnectionFailureException("down"));
|
||||
AdvertisingRepository repository = mock(AdvertisingRepository.class);
|
||||
AdvertisingSelectionService service = new AdvertisingSelectionService(mock(UserService.class), repository,
|
||||
frequency);
|
||||
when(advertisingRepository.findEligible(any())).thenReturn(List.of(ad(10L, 1L, 5)));
|
||||
when(frequency.todayImpressions(anyString(), anyCollection())).thenThrow(new RedisConnectionFailureException("down"));
|
||||
|
||||
assertThat(service.selectAdvertising(null, "session-1", new MockHttpServletRequest())).isEmpty();
|
||||
verify(frequency, never()).tryRegisterImpression(any(), anyString(), anyLong(), anyInt());
|
||||
assertThat(selection.selectAdvertising(null, "session-1", new MockHttpServletRequest())).isEmpty();
|
||||
verify(frequency, never()).tryStartCooldown(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void impressionForUnknownAdIsSkippedAndSessionIdIsTrimmed() {
|
||||
AdvertisingRepository advertisingRepository = mock(AdvertisingRepository.class);
|
||||
ImpressionRepository impressionRepository = mock(ImpressionRepository.class);
|
||||
AdvertisingImpressionService service = new AdvertisingImpressionService(mock(UserService.class),
|
||||
impressionRepository, advertisingRepository);
|
||||
|
||||
service.recordImpression(404L, null, "s");
|
||||
verify(impressionRepository, never()).save(any());
|
||||
|
||||
when(advertisingRepository.existsById(1L)).thenReturn(true);
|
||||
when(impressionRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
service.recordImpression(1L, null, "x".repeat(500));
|
||||
|
||||
ArgumentCaptor<Impression> saved = ArgumentCaptor.forClass(Impression.class);
|
||||
verify(impressionRepository).save(saved.capture());
|
||||
assertThat(saved.getValue().getSessionId()).hasSize(64);
|
||||
void weightedPickFollowsWeights() {
|
||||
List<EligibleAdvertising> ads = List.of(ad(1L, 1L, 10, 1), ad(2L, 1L, 10, 9));
|
||||
int heavy = 0;
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
if (AdvertisingSelectionService.pickWeighted(ads).advertisingId() == 2L) {
|
||||
heavy++;
|
||||
}
|
||||
}
|
||||
// ожидается ~90%
|
||||
assertThat(heavy).isBetween(1650, 1950);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -103,7 +161,7 @@ class AdvertisingServicesTest {
|
||||
|
||||
@Test
|
||||
void advertisingWithUnsafeTargetUrlIsNotCreated() {
|
||||
AdvertisingAdminService service = new AdvertisingAdminService(mock(AdvertisingRepository.class));
|
||||
AdvertisingAdminService service = new AdvertisingAdminService(advertisingRepository, selection);
|
||||
AdvertisingCreateRequestDto request = new AdvertisingCreateRequestDto(1L, AdvertisingType.IMAGE,
|
||||
"images/a.png", "javascript:alert(1)", 1);
|
||||
|
||||
@@ -112,7 +170,7 @@ class AdvertisingServicesTest {
|
||||
|
||||
@Test
|
||||
void confirmUploadAcceptsOnlyOwnSourceKeys() {
|
||||
AdvertisingAdminService service = new AdvertisingAdminService(mock(AdvertisingRepository.class));
|
||||
AdvertisingAdminService service = new AdvertisingAdminService(advertisingRepository, selection);
|
||||
|
||||
assertThat(service.isOwnSourceKey(5L, "sources/5/abc.mp4")).isTrue();
|
||||
assertThat(service.isOwnSourceKey(5L, "videos/other.mp4")).isFalse();
|
||||
@@ -121,4 +179,19 @@ class AdvertisingServicesTest {
|
||||
assertThat(service.isOwnSourceKey(5L, null)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ctrIsPercentWithTwoDecimals() {
|
||||
assertThat(CampaignStatsService.ctr(0, 0)).isZero();
|
||||
assertThat(CampaignStatsService.ctr(3, 1)).isEqualTo(33.33);
|
||||
assertThat(CampaignStatsService.ctr(200, 3)).isEqualTo(1.5);
|
||||
}
|
||||
|
||||
private static EligibleAdvertising ad(Long id, Long campaignId, int cap) {
|
||||
return ad(id, campaignId, cap, 1);
|
||||
}
|
||||
|
||||
private static EligibleAdvertising ad(Long id, Long campaignId, int cap, int weight) {
|
||||
return new EligibleAdvertising(id, campaignId, AdvertisingType.IMAGE, "images/" + id + ".png",
|
||||
"https://example.com", weight, cap);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.krylov.refound.service.advertising;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Advertising;
|
||||
import com.krylov.refound.entity.advertising.Impression;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.repository.advertising.ClickRepository;
|
||||
import com.krylov.refound.repository.advertising.ImpressionRepository;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
class AdvertisingTrackingServiceTest {
|
||||
|
||||
private static final String SECRET = "test-secret-test-secret-test-secret-0123456789";
|
||||
|
||||
private AdvertisingRepository advertisingRepository;
|
||||
private ImpressionRepository impressionRepository;
|
||||
private ClickRepository clickRepository;
|
||||
private AdvertisingFrequencyService frequency;
|
||||
private AdsProperties properties;
|
||||
private AdTrackingTokenService tokenService;
|
||||
private AdvertisingTrackingService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
advertisingRepository = mock(AdvertisingRepository.class);
|
||||
impressionRepository = mock(ImpressionRepository.class);
|
||||
clickRepository = mock(ClickRepository.class);
|
||||
frequency = mock(AdvertisingFrequencyService.class);
|
||||
properties = new AdsProperties();
|
||||
tokenService = new AdTrackingTokenService(properties, SECRET, Clock.systemUTC());
|
||||
service = new AdvertisingTrackingService(mock(UserService.class), advertisingRepository, impressionRepository,
|
||||
clickRepository, tokenService, frequency, properties);
|
||||
|
||||
when(advertisingRepository.existsById(10L)).thenReturn(true);
|
||||
when(advertisingRepository.getReferenceById(10L)).thenReturn(new Advertising());
|
||||
when(frequency.markOnce(anyString(), anyString(), any())).thenReturn(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void impressionByTokenCountsTowardsCampaignCap() {
|
||||
String token = tokenService.issue(10L, 1L, "u42");
|
||||
|
||||
service.recordImpression(10L, null, "device-1", token);
|
||||
|
||||
verify(frequency).registerImpression("u42", 1L);
|
||||
ArgumentCaptor<Impression> saved = ArgumentCaptor.forClass(Impression.class);
|
||||
verify(impressionRepository).save(saved.capture());
|
||||
assertThat(saved.getValue().getUserId()).isEqualTo(42L);
|
||||
assertThat(saved.getValue().getSessionId()).isEqualTo("device-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatedTokenIsCountedOnce() {
|
||||
String token = tokenService.issue(10L, 1L, "sdevice-1");
|
||||
when(frequency.markOnce(eq("imp"), anyString(), any())).thenReturn(true, false);
|
||||
|
||||
service.recordImpression(10L, null, "device-1", token);
|
||||
service.recordImpression(10L, null, "device-1", token);
|
||||
|
||||
verify(impressionRepository, org.mockito.Mockito.times(1)).save(any());
|
||||
verify(frequency, org.mockito.Mockito.times(1)).registerImpression("sdevice-1", 1L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void forgedOrMismatchedTokensAreIgnored() {
|
||||
String foreign = new AdTrackingTokenService(properties, "another-secret-another-secret-0123456789",
|
||||
Clock.systemUTC()).issue(10L, 1L, "u42");
|
||||
String valid = tokenService.issue(10L, 1L, "u42");
|
||||
|
||||
service.recordImpression(10L, null, "s", foreign);
|
||||
service.recordImpression(99L, null, "s", valid);
|
||||
service.recordClick(null, null, "s", "garbage");
|
||||
|
||||
verify(impressionRepository, never()).save(any());
|
||||
verify(clickRepository, never()).save(any());
|
||||
verify(frequency, never()).registerImpression(anyString(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredTokenIsIgnored() {
|
||||
Clock past = Clock.fixed(Instant.now().minus(Duration.ofHours(2)), ZoneOffset.UTC);
|
||||
String old = new AdTrackingTokenService(properties, SECRET, past).issue(10L, 1L, "u42");
|
||||
|
||||
service.recordImpression(10L, null, "s", old);
|
||||
|
||||
verify(impressionRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clickByTokenIsSaved() {
|
||||
service.recordClick(10L, null, "device-1", tokenService.issue(10L, 1L, "sdevice-1"));
|
||||
|
||||
verify(clickRepository).save(any());
|
||||
verify(frequency).markOnce(eq("clk"), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyRequestWithoutTokenIsAcceptedUntilRequired() {
|
||||
when(advertisingRepository.findCampaignIdById(10L)).thenReturn(Optional.of(1L));
|
||||
|
||||
service.recordImpression(10L, null, "device-1", null);
|
||||
|
||||
verify(frequency).registerImpression("sdevice-1", 1L);
|
||||
verify(impressionRepository).save(any());
|
||||
|
||||
properties.getTracking().setRequireToken(true);
|
||||
assertThatThrownBy(() -> service.recordImpression(10L, null, "device-1", null)).isInstanceOf(ApiException.class);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user