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"));
|
||||
|
||||
Reference in New Issue
Block a user