Fix advertising admin flows, tracking endpoints and ffmpeg timeout
- createAdvertising saved an IMAGE ad without mediaKey and only then answered 400; validation now happens first. Target URLs must be absolute http(s) (they end up in href on the client), DTOs get @NotNull/@NotBlank. - confirm-upload accepted any sourceKey; the transcoder deletes the source afterwards, so another ad's finished video could be deleted. Keys must now belong to the ad's own sources/ prefix. - Activating a fullscreen ad could hit uq_fullscreen_ad_single_active because Hibernate may flush the new ACTIVE row first; the old one is flushed first. - Campaign status change answered with the previous status (bulk UPDATE vs stale entity). - Impression/click used getReferenceById, so unknown ids failed with 500 on the FK at commit; session ids are trimmed to the 64-char column. - /api/ads/next created a Tomcat HttpSession for every client without X-Session-Id and failed with 500 when Redis was down; it now falls back to the client IP and returns 204 on Redis errors. - ffmpeg output was read before waitFor, so the 5-minute timeout never fired; output goes to a temp log and its tail is logged on failure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -86,6 +86,10 @@ public class AdvertisingAdminController {
|
||||
log.info("confirmUpload for advertisingId {}", advertisingId);
|
||||
Advertising advertising = advertisingRepository.findById(advertisingId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Advertising not found: " + advertisingId));
|
||||
if (!advertisingAdminService.isOwnSourceKey(advertisingId, request.sourceKey())) {
|
||||
log.warn("confirmUpload: foreign sourceKey {} for advertisingId {}", request.sourceKey(), advertisingId);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
advertisingAdminService.updateTranscodingStatus(advertising.getId());
|
||||
eventPublisher.publishEvent(new VideoUploadConfirmedEvent(advertisingId, request.sourceKey()));
|
||||
@@ -139,13 +143,14 @@ public class AdvertisingAdminController {
|
||||
log.warn("weight AdvertisingCreateRequestDto {} <= 0", request);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
|
||||
// Проверка до создания: раньше объявление создавалось и только потом отвечали 400
|
||||
if (request.type() == AdvertisingType.IMAGE && (request.mediaKey() == null || request.mediaKey().isBlank())) {
|
||||
log.warn("advertising image has bad mediaKey() or mediaKey isBlank");
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
Advertising advertising = advertisingAdminService.createAdvertising(campaign, request);
|
||||
|
||||
AdvertisingAdminResponseDto adminDto = advertisingAdminService.toAdminDto(advertising);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(adminDto);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ public class AdvertisingController {
|
||||
|
||||
@GetMapping("/api/ads/next")
|
||||
public ResponseEntity<AdvertisingResponseDto> getNextAdvertising(Authentication authentication, @RequestHeader(value = "X-Session-Id", required = false) String sessionId, HttpServletRequest request) {
|
||||
log.info("getNextAdvertising");
|
||||
log.debug("getNextAdvertising");
|
||||
Optional<SelectedAdvertisingDto> selected = advertisingSelectionService.selectAdvertising(authentication, sessionId, request);
|
||||
if (selected.isEmpty()) {
|
||||
// Нормальная ситуация (нет активных реклам / кулдаун / кап) — не ошибка
|
||||
@@ -52,7 +52,7 @@ public class AdvertisingController {
|
||||
|
||||
@PostMapping("/api/ads/impression")
|
||||
public ResponseEntity<Void> registerImpression(@RequestBody String body, Authentication authentication) throws JsonProcessingException {
|
||||
log.info("registerImpression for body {}", body);
|
||||
log.debug("registerImpression for body {}", body);
|
||||
ImpressionRequestDto request = objectMapper.readValue(body, ImpressionRequestDto.class);
|
||||
advertisingImpressionService.recordImpression(request.advertisingId(), authentication, request.sessionId());
|
||||
return ResponseEntity.accepted().build();
|
||||
@@ -60,7 +60,7 @@ public class AdvertisingController {
|
||||
|
||||
@PostMapping("/api/ads/click")
|
||||
public ResponseEntity<Void> registerClick(@RequestBody ClickRequestDto request, Authentication authentication) {
|
||||
log.info("registerClick");
|
||||
log.debug("registerClick");
|
||||
advertisingClickService.recordClick(request.advertisingId(), authentication, request.sessionId());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.krylov.refound.enums.advertising.FullscreenAdStatus;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import com.krylov.refound.util.AdTargetUrl;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -43,7 +44,9 @@ public class FullscreenAdAdminController {
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public ResponseEntity<FullscreenAdAdminResponseDto> create(@RequestBody FullscreenAdCreateRequestDto request) {
|
||||
FullscreenAdvertising ad = new FullscreenAdvertising();
|
||||
ad.setTargetUrl(request.targetUrl());
|
||||
// Ссылка у полноэкранного ролика необязательна, но если есть — только http(s)
|
||||
ad.setTargetUrl(request.targetUrl() == null || request.targetUrl().isBlank()
|
||||
? null : AdTargetUrl.requireValid(request.targetUrl()));
|
||||
FullscreenAdvertising saved = repository.save(ad);
|
||||
return ResponseEntity.status(HttpStatus.CREATED).body(toDto(saved));
|
||||
}
|
||||
@@ -60,8 +63,7 @@ public class FullscreenAdAdminController {
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
String sourceKey = "fullscreen-sources/%d/%s%s".formatted(
|
||||
id, UUID.randomUUID(), extensionFor(request.contentType()));
|
||||
String sourceKey = sourcePrefix(id) + UUID.randomUUID() + extensionFor(request.contentType());
|
||||
String uploadUrl = mediaService.getPresignedUploadUrl(sourceKey, request.contentType());
|
||||
|
||||
return ResponseEntity.ok(new PresignUploadResponseDto(uploadUrl, sourceKey, PRESIGN_URL_EXPIRY_MINUTES));
|
||||
@@ -75,6 +77,12 @@ public class FullscreenAdAdminController {
|
||||
|
||||
FullscreenAdvertising ad = repository.findById(id)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Fullscreen ad not found: " + id));
|
||||
// Транскодер удаляет исходник после работы — чужой ключ сюда подставлять нельзя
|
||||
String sourceKey = request.sourceKey();
|
||||
if (sourceKey == null || !sourceKey.startsWith(sourcePrefix(id)) || sourceKey.contains("..")) {
|
||||
log.warn("confirmUpload: foreign sourceKey {} for fullscreen ad {}", sourceKey, id);
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
ad.setTranscodingStatus(TranscodingStatus.PROCESSING);
|
||||
repository.save(ad);
|
||||
@@ -108,7 +116,13 @@ public class FullscreenAdAdminController {
|
||||
}
|
||||
|
||||
repository.findByStatus(FullscreenAdStatus.ACTIVE)
|
||||
.ifPresent(current -> current.setStatus(FullscreenAdStatus.INACTIVE));
|
||||
.filter(current -> !current.getId().equals(target.getId()))
|
||||
.ifPresent(current -> {
|
||||
current.setStatus(FullscreenAdStatus.INACTIVE);
|
||||
// Hibernate не гарантирует порядок UPDATE при flush: если target обновится
|
||||
// первым, две строки ACTIVE нарушат uq_fullscreen_ad_single_active
|
||||
repository.saveAndFlush(current);
|
||||
});
|
||||
|
||||
target.setStatus(FullscreenAdStatus.ACTIVE);
|
||||
return ResponseEntity.ok(toDto(target));
|
||||
@@ -124,6 +138,10 @@ public class FullscreenAdAdminController {
|
||||
return ResponseEntity.ok(toDto(ad));
|
||||
}
|
||||
|
||||
private static String sourcePrefix(Long id) {
|
||||
return "fullscreen-sources/%d/".formatted(id);
|
||||
}
|
||||
|
||||
private boolean isAllowedContentType(String contentType) {
|
||||
return contentType != null && (contentType.equals("video/mp4")
|
||||
|| contentType.equals("video/quicktime") || contentType.equals("video/webm"));
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record AdvertisingCreateRequestDto(
|
||||
Long campaignId,
|
||||
AdvertisingType type,
|
||||
@NotNull Long campaignId,
|
||||
@NotNull AdvertisingType type,
|
||||
String mediaKey, // обязателен только для IMAGE, для VIDEO — null
|
||||
String targetUrl,
|
||||
int weight
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record CampaignCreateRequestDto(
|
||||
String name,
|
||||
LocalDateTime startDate,
|
||||
LocalDateTime endDate,
|
||||
@NotBlank @Size(max = 255) String name,
|
||||
@NotNull LocalDateTime startDate,
|
||||
@NotNull LocalDateTime endDate,
|
||||
int dailyImpressionCap
|
||||
) {
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public record CampaignStatusUpdateRequestDto(
|
||||
CampaignStatus status
|
||||
@NotNull CampaignStatus status
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
package com.krylov.refound.dto.advertising;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public record CampaignUpdateRequestDto(
|
||||
String name,
|
||||
LocalDateTime startDate,
|
||||
LocalDateTime endDate,
|
||||
@NotBlank @Size(max = 255) String name,
|
||||
@NotNull LocalDateTime startDate,
|
||||
@NotNull LocalDateTime endDate,
|
||||
int dailyImpressionCap
|
||||
) {
|
||||
}
|
||||
@@ -28,7 +28,8 @@ public class Advertising {
|
||||
@Column(name = "type", nullable = false, length = 10)
|
||||
private AdvertisingType type;
|
||||
|
||||
@Column(name = "media_key", nullable = false, length = 512)
|
||||
// У видео ключ появляется только после транскодинга (changelog 012 снял NOT NULL)
|
||||
@Column(name = "media_key", length = 512)
|
||||
private String mediaKey;
|
||||
|
||||
@Column(name = "target_url", nullable = false, length = 1024)
|
||||
|
||||
@@ -10,10 +10,8 @@ import java.util.Collection;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificationExecutor<Post> {
|
||||
|
||||
@@ -26,11 +24,6 @@ public interface PostRepository extends JpaRepository<Post, Long>, JpaSpecificat
|
||||
@Query("select p.id from Post p where p.status = :status")
|
||||
List<Long> findIdsByStatus(@Param("status") PostStatus status);
|
||||
|
||||
@Modifying
|
||||
@Transactional
|
||||
@Query("update Post p set p.status = :status where p.id = :id")
|
||||
void updateStatus(@Param("id") Long id, @Param("status") PostStatus status);
|
||||
|
||||
@Query("select distinct p.city from Post p where p.city is not null and p.status in :statuses order by p.city")
|
||||
List<String> findDistinctCities(@Param("statuses") Collection<PostStatus> statuses);
|
||||
|
||||
|
||||
@@ -1,23 +1,11 @@
|
||||
package com.krylov.refound.repository.advertising;
|
||||
|
||||
import com.krylov.refound.entity.advertising.Campaign;
|
||||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||||
import java.util.List;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
public interface CampaignRepository extends JpaRepository<Campaign, Long> {
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
UPDATE Campaign c
|
||||
SET c.status = :status
|
||||
WHERE c.id = :campaignId
|
||||
""")
|
||||
void updateStatus(@Param("campaignId") Long campaignId, @Param("status") CampaignStatus status);
|
||||
|
||||
List<Campaign> findAllByOrderByCreatedAtDesc();
|
||||
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import com.krylov.refound.entity.advertising.Campaign;
|
||||
import com.krylov.refound.enums.advertising.AdvertisingType;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import com.krylov.refound.util.AdTargetUrl;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
@@ -27,7 +28,7 @@ public class AdvertisingAdminService {
|
||||
Advertising advertising = new Advertising();
|
||||
advertising.setCampaign(campaign);
|
||||
advertising.setType(request.type());
|
||||
advertising.setTargetUrl(request.targetUrl());
|
||||
advertising.setTargetUrl(AdTargetUrl.requireValid(request.targetUrl()));
|
||||
advertising.setWeight(request.weight());
|
||||
if (request.type() == AdvertisingType.IMAGE) {
|
||||
advertising.setMediaKey(request.mediaKey());
|
||||
@@ -47,7 +48,20 @@ public class AdvertisingAdminService {
|
||||
|
||||
public String getSourceKey(Long advertisingId,PresignUploadRequestDto request){
|
||||
String extensionFor = extensionFor(request.contentType());
|
||||
return "sources/%d/%s%s".formatted(advertisingId, UUID.randomUUID(), extensionFor);
|
||||
return sourcePrefix(advertisingId) + UUID.randomUUID() + extensionFor;
|
||||
}
|
||||
|
||||
/**
|
||||
* sourceKey в confirm-upload приходит от клиента, а транскодер после работы
|
||||
* удаляет исходник. Без проверки можно было подставить ключ готового ролика
|
||||
* другого объявления — и он бы удалился.
|
||||
*/
|
||||
public boolean isOwnSourceKey(Long advertisingId, String sourceKey) {
|
||||
return sourceKey != null && sourceKey.startsWith(sourcePrefix(advertisingId)) && !sourceKey.contains("..");
|
||||
}
|
||||
|
||||
private static String sourcePrefix(Long advertisingId) {
|
||||
return "sources/%d/".formatted(advertisingId);
|
||||
}
|
||||
|
||||
public String extensionFor(String contentType) {
|
||||
@@ -81,7 +95,7 @@ public class AdvertisingAdminService {
|
||||
public AdvertisingAdminResponseDto updateAdvertising(Long advertisingId, AdvertisingUpdateRequestDto request) {
|
||||
Advertising advertising = advertisingRepository.findById(advertisingId)
|
||||
.orElseThrow(() -> new EntityNotFoundException("Advertising not found: " + advertisingId));
|
||||
advertising.setTargetUrl(request.targetUrl());
|
||||
advertising.setTargetUrl(AdTargetUrl.requireValid(request.targetUrl()));
|
||||
advertising.setWeight(request.weight());
|
||||
Advertising saved = advertisingRepository.save(advertising);
|
||||
log.info("Advertising {} updated", saved.getId());
|
||||
|
||||
@@ -6,7 +6,7 @@ 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 jakarta.persistence.EntityNotFoundException;
|
||||
import com.krylov.refound.util.AdSessionId;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -25,20 +25,21 @@ public class AdvertisingClickService {
|
||||
@Transactional
|
||||
public void recordClick(Long advertisingId, Authentication authentication, String sessionId) {
|
||||
Long userId = extractUserId(authentication);
|
||||
try {
|
||||
Advertising advertising = advertisingRepository.getReferenceById(advertisingId);
|
||||
|
||||
Click click = new Click();
|
||||
click.setAdvertising(advertising);
|
||||
click.setUserId(userId);
|
||||
click.setSessionId(sessionId);
|
||||
click.setAdvertising(advertising);
|
||||
|
||||
Click save = clickRepository.save(click);
|
||||
log.info("click by advertising {}", save.getId());
|
||||
} catch (EntityNotFoundException e) {
|
||||
log.warn("Click skipped: advertisingId={} no longer exists", advertisingId);
|
||||
// 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) {
|
||||
@@ -47,7 +48,6 @@ public class AdvertisingClickService {
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
log.info("extractUserId by login {}", login);
|
||||
return userService.getUserIdByLogin(login);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,9 +23,10 @@ public class AdvertisingFrequencyService {
|
||||
*/
|
||||
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) {
|
||||
// Redis недоступен — не блокируем показ, решение остаётся за вызывающим кодом
|
||||
return true;
|
||||
}
|
||||
if (count == 1L) {
|
||||
|
||||
@@ -5,7 +5,7 @@ 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 jakarta.persistence.EntityNotFoundException;
|
||||
import com.krylov.refound.util.AdSessionId;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.core.Authentication;
|
||||
@@ -23,21 +23,21 @@ public class AdvertisingImpressionService {
|
||||
@Transactional
|
||||
public void recordImpression(Long advertisingId, Authentication authentication, String sessionId) {
|
||||
Long userId = extractUserId(authentication);
|
||||
try {
|
||||
Advertising advertising = advertisingRepository.getReferenceById(advertisingId);
|
||||
|
||||
Impression impression = new Impression();
|
||||
impression.setAdvertising(advertising);
|
||||
impression.setUserId(userId);
|
||||
impression.setSessionId(sessionId);
|
||||
|
||||
Impression save = impressionRepository.save(impression);
|
||||
log.info("impression is {}", save);
|
||||
} catch (EntityNotFoundException e) {
|
||||
// advertisingId мог устареть (кампания удалена между показом и трекингом) —
|
||||
// не роняем запрос трекинга из-за гонки данных
|
||||
log.warn("Impression skipped: advertisingId={} no longer exists", advertisingId);
|
||||
// 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) {
|
||||
@@ -46,7 +46,6 @@ public class AdvertisingImpressionService {
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
log.info("extractUserId by login {}", login);
|
||||
return userService.getUserIdByLogin(login);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ 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 lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -33,8 +35,23 @@ public class AdvertisingSelectionService {
|
||||
public Optional<SelectedAdvertisingDto> selectAdvertising(Authentication authentication, String sessionId, HttpServletRequest request) {
|
||||
|
||||
Long userId = extractUserId(authentication);
|
||||
String resolvedSessionId = sessionId != null ? sessionId : request.getSession(true).getId();
|
||||
// Приложение stateless: request.getSession(true) заводил HTTP-сессию в памяти Tomcat
|
||||
// на каждый запрос без X-Session-Id. Без заголовка частоту считаем по IP клиента.
|
||||
String resolvedSessionId = sessionId != null && !sessionId.isBlank()
|
||||
? AdSessionId.normalize(sessionId)
|
||||
: AdSessionId.normalize("ip:" + request.getRemoteAddr());
|
||||
|
||||
try {
|
||||
return select(userId, resolvedSessionId);
|
||||
} catch (DataAccessException e) {
|
||||
// Капы и кулдаун живут в 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();
|
||||
@@ -51,14 +68,14 @@ public class AdvertisingSelectionService {
|
||||
boolean allowed = frequencyService.tryRegisterImpression(userId, resolvedSessionId, candidate.getId(), dailyCap);
|
||||
|
||||
if (allowed) {
|
||||
log.info("advertising candidate {}", candidate);
|
||||
log.debug("advertising candidate {}", candidate.getId());
|
||||
return Optional.of(toDto(candidate));
|
||||
}
|
||||
log.info("rollback dailyCap for candidate {}", candidate.getId());
|
||||
log.debug("rollback dailyCap for candidate {}", candidate.getId());
|
||||
frequencyService.rollback(userId, resolvedSessionId, candidate.getId());
|
||||
}
|
||||
|
||||
log.info("No ad passed frequency cap for userId={}, sessionId={}", userId, resolvedSessionId);
|
||||
log.debug("No ad passed frequency cap for userId={}, sessionId={}", userId, resolvedSessionId);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@@ -68,7 +85,6 @@ public class AdvertisingSelectionService {
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
log.info("extractUserId by login {}", login);
|
||||
return userService.getUserIdByLogin(login);
|
||||
}
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ public class CampaignService {
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CampaignResponseDto> getCampaign() {
|
||||
return campaignRepository.findAllByOrderByCreatedAtDesc()
|
||||
.stream()
|
||||
@@ -34,6 +35,7 @@ public class CampaignService {
|
||||
return campaignRepository.findById(campaignId).map(this::toDto);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CampaignResponseDto createCampaign(CampaignCreateRequestDto request){
|
||||
Campaign campaign = new Campaign();
|
||||
campaign.setName(request.name());
|
||||
@@ -81,7 +83,9 @@ public class CampaignService {
|
||||
);
|
||||
}
|
||||
|
||||
campaignRepository.updateStatus(campaignId, request.status());
|
||||
// Раньше статус менялся bulk-UPDATE'ом, а ответ собирался из сущности
|
||||
// со старым статусом — фронт видел прежнее значение
|
||||
campaign.setStatus(request.status());
|
||||
return toDto(campaign);
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ import java.util.concurrent.TimeUnit;
|
||||
@RequiredArgsConstructor
|
||||
public class VideoTranscoderService {
|
||||
|
||||
private static final long FFMPEG_TIMEOUT_MINUTES = 5;
|
||||
private static final int LOG_TAIL_LINES = 20;
|
||||
|
||||
private final AdvertisingMediaService mediaService;
|
||||
private final S3Client s3Client;
|
||||
|
||||
@@ -76,8 +79,9 @@ public class VideoTranscoderService {
|
||||
}
|
||||
|
||||
private boolean runFfmpeg(Path input, Path output) throws IOException, InterruptedException {
|
||||
// -nostdin: ffmpeg не ждёт ввода с консоли, которой у фонового процесса нет
|
||||
List<String> command = List.of(
|
||||
ffmpegPath, "-y", "-i", input.toString(),
|
||||
ffmpegPath, "-nostdin", "-y", "-i", input.toString(),
|
||||
"-vf", "scale=-2:720",
|
||||
"-c:v", "libx264", "-preset", "medium",
|
||||
"-b:v", "1500k", "-maxrate", "2000k", "-bufsize", "3000k",
|
||||
@@ -86,21 +90,39 @@ public class VideoTranscoderService {
|
||||
output.toString()
|
||||
);
|
||||
|
||||
ProcessBuilder builder = new ProcessBuilder(command);
|
||||
builder.redirectErrorStream(true);
|
||||
Process process = builder.start();
|
||||
// Вывод ffmpeg пишется в файл, а не читается в этом потоке: раньше чтение
|
||||
// stdout до waitFor блокировалось до конца процесса, и таймаут не срабатывал —
|
||||
// зависший ffmpeg навсегда занимал поток ffmpegExecutor
|
||||
Path logPath = Files.createTempFile("ffmpeg-", ".log");
|
||||
try {
|
||||
ProcessBuilder builder = new ProcessBuilder(command);
|
||||
builder.redirectErrorStream(true);
|
||||
builder.redirectOutput(logPath.toFile());
|
||||
Process process = builder.start();
|
||||
|
||||
try (var reader = process.inputReader()) {
|
||||
reader.lines().forEach(line -> log.debug("[ffmpeg] {}", line));
|
||||
boolean finished = process.waitFor(FFMPEG_TIMEOUT_MINUTES, TimeUnit.MINUTES);
|
||||
if (!finished) {
|
||||
process.destroyForcibly();
|
||||
log.error("FFmpeg timed out after {} min, killed process. Output tail:\n{}", FFMPEG_TIMEOUT_MINUTES, tail(logPath));
|
||||
return false;
|
||||
}
|
||||
if (process.exitValue() != 0) {
|
||||
log.error("FFmpeg exited with {}. Output tail:\n{}", process.exitValue(), tail(logPath));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
cleanup(logPath);
|
||||
}
|
||||
}
|
||||
|
||||
boolean finished = process.waitFor(5, TimeUnit.MINUTES);
|
||||
if (!finished) {
|
||||
process.destroyForcibly();
|
||||
log.error("FFmpeg timed out, killed process");
|
||||
return false;
|
||||
private static String tail(Path logPath) {
|
||||
try {
|
||||
List<String> lines = Files.readAllLines(logPath);
|
||||
return String.join("\n", lines.subList(Math.max(0, lines.size() - LOG_TAIL_LINES), lines.size()));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
return "<лог ffmpeg недоступен: " + e.getMessage() + ">";
|
||||
}
|
||||
return process.exitValue() == 0;
|
||||
}
|
||||
|
||||
private void uploadToStorage(Path filePath, String mediaKey) throws IOException {
|
||||
|
||||
24
src/main/java/com/krylov/refound/util/AdSessionId.java
Normal file
24
src/main/java/com/krylov/refound/util/AdSessionId.java
Normal file
@@ -0,0 +1,24 @@
|
||||
package com.krylov.refound.util;
|
||||
|
||||
/**
|
||||
* Идентификатор рекламной сессии от клиента (X-Session-Id или поле sessionId).
|
||||
* Он попадает в ключи Redis и в колонки session_id VARCHAR(64), поэтому длина
|
||||
* ограничивается: без этого длинная строка давала 500 при сохранении показа.
|
||||
*/
|
||||
public final class AdSessionId {
|
||||
|
||||
public static final int MAX_LENGTH = 64;
|
||||
/** impression.session_id — NOT NULL; клиент без идентификатора всё равно учитывается. */
|
||||
public static final String UNKNOWN = "unknown";
|
||||
|
||||
private AdSessionId() {
|
||||
}
|
||||
|
||||
public static String normalize(String sessionId) {
|
||||
if (sessionId == null || sessionId.isBlank()) {
|
||||
return UNKNOWN;
|
||||
}
|
||||
String trimmed = sessionId.trim();
|
||||
return trimmed.length() > MAX_LENGTH ? trimmed.substring(0, MAX_LENGTH) : trimmed;
|
||||
}
|
||||
}
|
||||
47
src/main/java/com/krylov/refound/util/AdTargetUrl.java
Normal file
47
src/main/java/com/krylov/refound/util/AdTargetUrl.java
Normal file
@@ -0,0 +1,47 @@
|
||||
package com.krylov.refound.util;
|
||||
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* Ссылка, куда ведёт клик по рекламе. Фронт вставляет её в href, поэтому
|
||||
* разрешены только абсолютные http(s)-адреса: "javascript:..." или "data:..."
|
||||
* выполнились бы в браузере пользователя.
|
||||
*/
|
||||
public final class AdTargetUrl {
|
||||
|
||||
/** Колонка advertising.target_url — VARCHAR(1024). */
|
||||
public static final int MAX_LENGTH = 1024;
|
||||
|
||||
private AdTargetUrl() {
|
||||
}
|
||||
|
||||
/** Проверяет ссылку и возвращает её без пробелов по краям; 400 при ошибке. */
|
||||
public static String requireValid(String url) {
|
||||
if (url == null || url.isBlank()) {
|
||||
throw invalid("Ссылка рекламы обязательна");
|
||||
}
|
||||
String trimmed = url.trim();
|
||||
if (trimmed.length() > MAX_LENGTH) {
|
||||
throw invalid("Ссылка рекламы длиннее " + MAX_LENGTH + " символов");
|
||||
}
|
||||
try {
|
||||
URI uri = new URI(trimmed);
|
||||
String scheme = uri.getScheme();
|
||||
if (scheme == null || !(scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))
|
||||
|| uri.getHost() == null) {
|
||||
throw invalid("Ссылка рекламы должна быть абсолютным http(s)-адресом");
|
||||
}
|
||||
} catch (URISyntaxException e) {
|
||||
throw invalid("Некорректная ссылка рекламы");
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
private static ApiException invalid(String message) {
|
||||
return new ApiException(ErrorCode.VALIDATION_ERROR, message, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user