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:
SlimusMinus
2026-10-20 01:37:32 +03:00
parent 477737c161
commit 2f52e6df70
35 changed files with 1018 additions and 290 deletions

View File

@@ -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}