Merge pull request #56 from SlimusMinus/claude/backend-review-80c5df
Claude/backend review 80c5df
This commit is contained in:
24
.env.example
24
.env.example
@@ -18,10 +18,8 @@ MINIO_SECRET_KEY=
|
||||
# docker-compose падает с понятной ошибкой, если переменная пустая.
|
||||
REDIS_PASSWORD=
|
||||
|
||||
# --- Рекомендуется задать ---
|
||||
|
||||
# Секрет подписи JWT. Без переменной берётся захардкоженное значение
|
||||
# из application.yaml — подделать такой токен может кто угодно.
|
||||
# Секрет подписи JWT (HMAC-SHA): строка не короче 32 байт. Значения
|
||||
# по умолчанию нет — без переменной приложение не стартует.
|
||||
# Сгенерировать, например, так:
|
||||
# openssl rand -base64 48
|
||||
JWT_SECRET=
|
||||
@@ -34,6 +32,24 @@ JWT_SECRET=
|
||||
# MINIO_ADS_BUCKET=ads-media
|
||||
# MINIO_REGION=us-east-1
|
||||
# AI_SERVICE_URL=http://localhost:8000
|
||||
# AI_IMAGE_TIMEOUT=30
|
||||
# AI_TEXT_MAX_LENGTH=5000
|
||||
# FFMPEG_PATH=ffmpeg
|
||||
# DB_URL=jdbc:postgresql://localhost:5432/nahodka
|
||||
# DB_USER=user
|
||||
# DB_PASSWORD=pass
|
||||
# CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
|
||||
# FORWARD_HEADERS_STRATEGY=native
|
||||
# RATE_LIMIT_ENABLED=true
|
||||
# WS_CLUSTER_BROADCAST=true
|
||||
# GEOCODING_URL=https://nominatim.openstreetmap.org
|
||||
# GEOCODING_USER_AGENT=ReFound/1.0 (admin@example.com)
|
||||
# GEOCODING_MIN_INTERVAL=PT1S
|
||||
# STORAGE_ORPHAN_CLEANUP_ENABLED=true
|
||||
# ADS_TIMEZONE=Europe/Moscow
|
||||
# ADS_TRACKING_SECRET=
|
||||
# ADS_REQUIRE_TRACKING_TOKEN=false
|
||||
# JWT_ACCESS_EXPIRATION=900000
|
||||
# JWT_REFRESH_EXPIRATION=604800000
|
||||
# JPA_DDL_AUTO=validate
|
||||
# JPA_SHOW_SQL=false
|
||||
|
||||
@@ -65,6 +65,11 @@ dependencies {
|
||||
//WebClient
|
||||
implementation 'org.springframework.boot:spring-boot-starter-webflux'
|
||||
|
||||
// Фоновые задачи (@Scheduled) при нескольких экземплярах выполняет только один —
|
||||
// блокировка в Redis
|
||||
implementation 'net.javacrumbs.shedlock:shedlock-spring:6.10.0'
|
||||
implementation 'net.javacrumbs.shedlock:shedlock-provider-redis-spring:6.10.0'
|
||||
|
||||
implementation 'org.springframework.retry:spring-retry'
|
||||
implementation 'org.springframework:spring-aspects'
|
||||
|
||||
|
||||
389
docs/advertising.md
Normal file
389
docs/advertising.md
Normal file
@@ -0,0 +1,389 @@
|
||||
# Реклама в ReFound
|
||||
|
||||
В приложении два вида рекламы:
|
||||
|
||||
- **ротируемая реклама** (`Campaign` → `Advertising`) — баннеры-картинки и
|
||||
ролики, которые клиент запрашивает через `GET /api/ads/next`; выбор
|
||||
учитывает веса, дневной лимит показов кампании одному пользователю и паузу
|
||||
между показами, а показы и клики подтверждаются подписанным токеном;
|
||||
- **полноэкранная реклама** (`FullscreenAdvertising`) — один ролик на всё
|
||||
приложение (обычно показывается при запуске), активным может быть только один.
|
||||
|
||||
Пакеты: `controller/advertising`, `service/advertising`,
|
||||
`entity/advertising`, `repository/advertising`, `dto/advertising`,
|
||||
`enums/advertising`. Таблицы — changelog `create/010-add-advertising.yaml`,
|
||||
`create/011-create-fullscreen-ads.yaml` и правки `alter/012`, `alter/013`, `add/016`.
|
||||
|
||||
## Сущности
|
||||
|
||||
```
|
||||
campaign 1 ──── * advertising 1 ──── * impression
|
||||
1 ──── * click
|
||||
fullscreen_advertising (отдельно)
|
||||
```
|
||||
|
||||
### `Campaign` — рекламная кампания
|
||||
|
||||
| Поле | Смысл |
|
||||
|---|---|
|
||||
| `name` | название (обязательно, ≤ 255) |
|
||||
| `status` | `DRAFT`, `ACTIVE`, `PAUSED`, `FINISHED` |
|
||||
| `startDate`, `endDate` | окно показа; реклама выдаётся, только если сейчас между ними |
|
||||
| `dailyImpressionCap` | сколько показов кампании (всех её объявлений вместе) один пользователь/сессия может увидеть за календарные сутки (`ads.timezone`) |
|
||||
| `createdAt` | время создания |
|
||||
|
||||
### `Advertising` — объявление (креатив) кампании
|
||||
|
||||
| Поле | Смысл |
|
||||
|---|---|
|
||||
| `campaign` | кампания (обязательно) |
|
||||
| `type` | `IMAGE` или `VIDEO` |
|
||||
| `mediaKey` | ключ файла в бакете `ads-media`; у видео пуст до конца транскодинга |
|
||||
| `targetUrl` | куда ведёт клик; только абсолютный `http(s)`, ≤ 1024 |
|
||||
| `weight` | вес в ротации, > 0 |
|
||||
| `transcodingStatus` | `PENDING`, `PROCESSING`, `READY`, `FAILED`; у картинки сразу `READY` |
|
||||
|
||||
### `Impression` и `Click` — учёт показов и кликов
|
||||
|
||||
`advertising`, `userId` (если пользователь авторизован), `sessionId`
|
||||
(≤ 64 символов, только `[A-Za-z0-9._:-]`; без идентификатора — `unknown`),
|
||||
время `shownAt`/`clickedAt`. Отчёт по ним — `GET /api/v1/admin/campaigns/{id}/stats`.
|
||||
|
||||
### `FullscreenAdvertising` — полноэкранный ролик
|
||||
|
||||
`mediaKey`, `targetUrl` (необязательна; если задана — `http(s)`), `status`
|
||||
(`DRAFT`, `ACTIVE`, `INACTIVE`), `transcodingStatus`, `createdAt`.
|
||||
Частичный уникальный индекс `uq_fullscreen_ad_single_active` гарантирует в БД
|
||||
не больше одной строки со статусом `ACTIVE`.
|
||||
|
||||
## Жизненный цикл кампании
|
||||
|
||||
```
|
||||
PATCH status=ACTIVE PATCH status=PAUSED
|
||||
DRAFT ─────────────────────► ACTIVE ◄──────────────────────► PAUSED
|
||||
│ PATCH status=ACTIVE │
|
||||
│ FINISHED │ FINISHED
|
||||
▼ ▼
|
||||
FINISHED (конечный, вернуть нельзя)
|
||||
```
|
||||
|
||||
- Новая кампания всегда создаётся в `DRAFT` (`CampaignService.createCampaign`).
|
||||
- Разрешённые переходы — `CampaignService.isValidTransition`; переход в тот
|
||||
же статус или недопустимый → **422** `INVALID_STATUS_TRANSITION`.
|
||||
- Кампании `ACTIVE` и `PAUSED` с прошедшим `endDate` раз в 10 минут
|
||||
переводятся в `FINISHED` (`CampaignLifecycleService.finishExpiredCampaigns`,
|
||||
ShedLock — выполняет один экземпляр). Даты кампании трактуются в поясе
|
||||
`ads.timezone` (по умолчанию `Europe/Moscow`).
|
||||
- Удаления кампаний и объявлений в API нет.
|
||||
|
||||
Объявление участвует в ротации, когда одновременно:
|
||||
`campaign.status = ACTIVE`, `startDate ≤ now ≤ endDate`,
|
||||
`advertising.transcodingStatus = READY`, `mediaKey` задан
|
||||
(`AdvertisingRepository.findEligible`).
|
||||
|
||||
## Загрузка медиа
|
||||
|
||||
### Картинка (`IMAGE`)
|
||||
|
||||
1. `POST /api/v1/admin/ads/image` (multipart, поле `file`) →
|
||||
`AdvertisingMediaService.uploadImage`:
|
||||
- файл не пустой, есть имя, ≤ 10 МБ, `Content-Type` jpeg/png/webp;
|
||||
- формат подтверждается сигнатурой файла (`util/ImageFormat`), расширение
|
||||
и `Content-Type` объекта берутся из неё;
|
||||
- ключ `images/<uuid>.<ext>` в бакете `ads-media`. Сжатия нет (в отличие
|
||||
от фото объявлений).
|
||||
- Ответ: `{"mediaKey": "images/....png"}`.
|
||||
2. `POST /api/v1/admin/ads` с `type=IMAGE` и этим `mediaKey` — объявление
|
||||
создаётся сразу в `READY`.
|
||||
|
||||
### Видео (`VIDEO`) — прямая загрузка в MinIO и транскодинг
|
||||
|
||||
```
|
||||
админка бэкенд MinIO (ads-media)
|
||||
│ POST /api/v1/admin/ads (type=VIDEO) ──► Advertising(PENDING, mediaKey=null)
|
||||
│ POST /{id}/video/presign-upload {contentType}
|
||||
│ ──► sourceKey = sources/{id}/<uuid>.mp4|.mov|.webm
|
||||
│ ◄── {uploadUrl, sourceKey, expiryMinutes: 30}
|
||||
│ PUT uploadUrl (файл, тот же Content-Type) ─────────────────────────────► sources/{id}/...
|
||||
│ POST /{id}/video/confirm-upload {sourceKey}
|
||||
│ ──► проверка: sourceKey начинается с sources/{id}/
|
||||
│ ──► transcodingStatus = PROCESSING, событие VideoUploadConfirmedEvent
|
||||
│ ◄── 202 Accepted
|
||||
│ после коммита: VideoUploadEventListener (@TransactionalEventListener AFTER_COMMIT)
|
||||
│ → AdvertisingTranscodingService (@Async "ffmpegExecutor")
|
||||
│ → VideoTranscoderService.transcode:
|
||||
│ скачать исходник во временный файл ◄──────────── sources/{id}/...
|
||||
│ ffmpeg → H.264 720p, AAC 128k, faststart
|
||||
│ залить videos/<uuid>.mp4 ─────────────────────► videos/...
|
||||
│ удалить исходник (и при ошибке тоже) ─────────► ✕ sources/{id}/...
|
||||
│ → AdvertisingStatusService.markReady / markFailed
|
||||
│ ◄── STOMP /topic/ads/{id}/status {advertisingId, transcodingStatus}
|
||||
│ GET /{id}/status — то же самое опросом
|
||||
```
|
||||
|
||||
Детали:
|
||||
|
||||
- Допустимые типы — `video/mp4`, `video/quicktime`, `video/webm`; иначе 400.
|
||||
- Presigned PUT подписан на 30 минут и на конкретный `Content-Type`
|
||||
(`AdvertisingMediaService.getPresignedUploadUrl`).
|
||||
- Браузер грузит файл в MinIO напрямую, поэтому бакету `ads-media` нужен
|
||||
CORS (`minio/cors.json`, накладывает `mc-init`). Сейчас там только
|
||||
`localhost:5173` и `localhost:3000` — для боевого домена правило нужно дополнить.
|
||||
- `confirm-upload` принимает только ключ из `sources/{id}/` этого объявления:
|
||||
транскодер удаляет исходник после работы, и чужой ключ (например, готовый
|
||||
ролик другого объявления) был бы удалён.
|
||||
- ffmpeg: `ffmpeg -nostdin -y -i <src> -vf scale=-2:720 -c:v libx264 -preset medium
|
||||
-b:v 1500k -maxrate 2000k -bufsize 3000k -c:a aac -b:a 128k -movflags +faststart <out>`.
|
||||
Путь — `ffmpeg.binary-path` (`FFMPEG_PATH`); в Docker-образе ffmpeg
|
||||
ставится из apt. Вывод пишется во временный лог, при ошибке или таймауте
|
||||
(5 минут — процесс убивается) в лог приложения попадает хвост вывода.
|
||||
- Пул `ffmpegExecutor` (`config/AsyncConfig`): 2 потока, очередь 20. При
|
||||
переполнении очереди `@Async` бросит `TaskRejectedException` уже после
|
||||
коммита — статус останется `PROCESSING`.
|
||||
- Статус транскодинга шлётся в `/topic/ads/{id}/status` через Redis во все
|
||||
экземпляры (`config/ClusterMessaging`), так что админ получит его, к какому
|
||||
бы экземпляру ни был подключён. Подписаться на
|
||||
`/topic/ads/**` и `/topic/fullscreen-ads/**` может только `ADMIN`
|
||||
(`util/WsStompInterceptor`).
|
||||
|
||||
Полноэкранный ролик загружается так же, но через
|
||||
`/api/v1/admin/fullscreen-ads/{id}/video/...`: ключи `fullscreen-sources/{id}/...`,
|
||||
результат `fullscreen/<uuid>.mp4`, сервисы `FullscreenAdTranscodingService`,
|
||||
`FullscreenAdStatusService`, топик `/topic/fullscreen-ads/{id}/status`.
|
||||
|
||||
## Как это устроено: выдача → показ → клик
|
||||
|
||||
Схема та же, что у рекламных серверов: **выдача** (ad decision) ещё не показ.
|
||||
Клиент получает рекламу вместе с подписанным **токеном показа**, отрисовывает
|
||||
её и сообщает о показе, возвращая токен; клик сообщается с тем же токеном.
|
||||
|
||||
```
|
||||
клиент бэкенд Redis
|
||||
│ GET /api/ads/next ───────► кандидаты (кэш 30 с) ──────────────────────────
|
||||
│ дневные показы кампаний субъекту ── MGET ──► ad:cap:<субъект>:<кампания>:<день>
|
||||
│ взвешенный выбор
|
||||
│ пауза между показами ── SET NX EX 30 ──────► ad:cooldown:<субъект>
|
||||
│ ◄── {advertisingId, type, mediaUrl, targetUrl, impressionToken}
|
||||
│ (реклама отрисована)
|
||||
│ POST /api/ads/impression {advertisingId, sessionId, token}
|
||||
│ подпись и срок токена (HMAC, 1 ч)
|
||||
│ токен ещё не засчитан ── SET NX ───────────► ad:imp:<nonce>
|
||||
│ +1 к дневному счётчику кампании ── INCR ──► ad:cap:...
|
||||
│ строка impression в БД
|
||||
│ (клик)
|
||||
│ POST /api/ads/click {advertisingId, sessionId, token}
|
||||
│ подпись, однократность ── SET NX ─────────► ad:clk:<nonce>
|
||||
│ строка click в БД
|
||||
```
|
||||
|
||||
### Выдача — `GET /api/ads/next` (публично)
|
||||
|
||||
Заголовок `X-Session-Id` — стабильный идентификатор устройства/браузера.
|
||||
Токен авторизации необязателен: если он есть, лимиты считаются по пользователю.
|
||||
|
||||
`AdvertisingSelectionService.selectAdvertising`:
|
||||
|
||||
1. **Субъект** — `u{userId}` для авторизованного пользователя, иначе
|
||||
`s{sessionId}`. Сессия — `X-Session-Id` (недопустимые символы заменяются
|
||||
`_`, обрезается до 64), без заголовка — `ip:{адрес клиента}`. HTTP-сессия
|
||||
на сервере не создаётся.
|
||||
2. **Кандидаты** — `findEligible(now)`: объявления активных кампаний в окне дат с
|
||||
готовым медиа. Список держится в памяти экземпляра `ads.eligible-cache-ttl`
|
||||
(30 с) и сбрасывается сразу после правок в админке этого экземпляра;
|
||||
остальные экземпляры увидят правку в пределах 30 секунд.
|
||||
3. **Дневной лимит** — одним `MGET` читаются показы кампаний субъекту за
|
||||
сегодня (`ad:cap:<субъект>:<кампания>:<yyyyMMdd>`, сутки в `ads.timezone`).
|
||||
Кампании, достигшие `dailyImpressionCap`, отбрасываются.
|
||||
4. **Взвешенный выбор** среди оставшихся: ключ `u^(1/weight)`, побеждает
|
||||
максимальный (Efraimidis–Spirakis) — вероятность пропорциональна весу.
|
||||
5. **Пауза между показами** — `SET ad:cooldown:<субъект> NX EX 30`
|
||||
(`ads.session-cooldown`). Если ключ уже есть — 204. Ставится в момент выдачи,
|
||||
поэтому параллельные запросы одного клиента не получат две рекламы.
|
||||
6. **Токен показа** — `AdTrackingTokenService.issue(adId, campaignId, subject)`.
|
||||
|
||||
Нет кандидатов, все кампании исчерпали лимит, идёт пауза или недоступен
|
||||
Redis → **204** (реклама не показывается, запрос не падает).
|
||||
|
||||
Ответ 200:
|
||||
|
||||
```json
|
||||
{
|
||||
"advertisingId": 12,
|
||||
"type": "VIDEO",
|
||||
"mediaUrl": "/api/v1/ads-media/videos/3f0c....mp4",
|
||||
"targetUrl": "https://example.com/promo",
|
||||
"impressionToken": "djF8MTJ8M3x1NDJ8MTc2MDk1...Q.4mK1f..."
|
||||
}
|
||||
```
|
||||
|
||||
`mediaUrl` — относительный путь на прокси бэкенда, а не presigned URL:
|
||||
presigned-ссылка подписана под адрес MinIO, который снаружи может быть
|
||||
недоступен.
|
||||
|
||||
### Токен показа
|
||||
|
||||
`AdTrackingTokenService`: `base64url(v1|adId|campaignId|subject|issuedAt|nonce)`
|
||||
`.` `base64url(HMAC-SHA256)`. Ключ — `ads.tracking.secret`
|
||||
(`ADS_TRACKING_SECRET`), если не задан — `jwt.secret`. Срок —
|
||||
`ads.tracking.token-ttl` (1 час).
|
||||
|
||||
Что даёт токен:
|
||||
|
||||
- **нельзя засчитать показ рекламы, которая не выдавалась**, или приписать его
|
||||
другому пользователю — субъект и кампания берутся из подписанного токена, а
|
||||
не из тела запроса;
|
||||
- **повтор не учитывается** — каждый nonce засчитывается один раз
|
||||
(`ad:imp:<nonce>`, `ad:clk:<nonce>` на срок жизни токена);
|
||||
- **лимит считается по факту показа**: дневной счётчик растёт на `/impression`,
|
||||
а не при выдаче. Выданная, но не показанная реклама лимит не тратит
|
||||
(от частых запросов защищает пауза между показами).
|
||||
|
||||
### Показы и клики
|
||||
|
||||
| Запрос | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `POST /api/ads/impression` (публично) | `{"advertisingId": 12, "sessionId": "...", "token": "..."}` | 202 |
|
||||
| `POST /api/ads/click` (публично) | `{"advertisingId": 12, "sessionId": "...", "token": "..."}` | 202 |
|
||||
|
||||
`AdvertisingTrackingService`:
|
||||
|
||||
- с токеном: неверная подпись, истёкший срок, `advertisingId` не из токена,
|
||||
повтор → событие молча пропускается (202, без записи);
|
||||
- без токена (старые клиенты): пока `ads.tracking.require-token=false`,
|
||||
событие учитывается по-старому — по `advertisingId` и субъекту из
|
||||
запроса, без защиты от повторов. После обновления фронта включите
|
||||
`ADS_REQUIRE_TRACKING_TOKEN=true` — запросы без токена получат 400;
|
||||
- `/impression` читает тело строкой и разбирает JSON сам — так его можно слать
|
||||
через `navigator.sendBeacon` с `Content-Type: text/plain`;
|
||||
- оба эндпоинта ограничены по IP (`rate-limit.rules`, 120 запросов в минуту).
|
||||
|
||||
Если Redis недоступен при показе: проверить повтор нельзя — событие
|
||||
засчитывается; дневной счётчик не вырастет, строка в БД сохраняется.
|
||||
|
||||
### Медиа — `GET /api/v1/ads-media/{*key}` (публично)
|
||||
|
||||
`AdvertisingMediaService.downloadMedia` отдаёт файл из `ads-media` потоком,
|
||||
с поддержкой `Range` (206/416) и `Cache-Control: public, max-age=2592000`.
|
||||
Подробно — в [images-storage.md](images-storage.md#медиа-рекламы--get-apiv1ads-mediakey-публично).
|
||||
|
||||
### Полноэкранная реклама — `GET /api/fullscreen-ad` (публично)
|
||||
|
||||
`FullscreenAdController`: берёт запись со статусом `ACTIVE`. Нет активной или
|
||||
у неё пустой `mediaKey` → 204. Иначе:
|
||||
|
||||
```json
|
||||
{ "mediaUrl": "/api/v1/ads-media/fullscreen/....mp4", "targetUrl": "https://..." }
|
||||
```
|
||||
|
||||
Лимитов и паузы у полноэкранной рекламы нет — частоту показа решает клиент;
|
||||
показы полноэкранного ролика не учитываются.
|
||||
|
||||
## Статистика
|
||||
|
||||
`GET /api/v1/admin/campaigns/{id}/stats?from=2026-10-01&to=2026-10-20`
|
||||
(`CampaignStatsService`) — показы, клики и CTR (в процентах) по кампании и
|
||||
каждому её объявлению за дни `from..to` включительно (по умолчанию последние
|
||||
30 дней, не больше 366):
|
||||
|
||||
```json
|
||||
{
|
||||
"campaignId": 3, "from": "2026-10-01", "to": "2026-10-20",
|
||||
"impressions": 1200, "clicks": 18, "ctr": 1.5,
|
||||
"advertisings": [ {"advertisingId": 12, "impressions": 800, "clicks": 14, "ctr": 1.75} ]
|
||||
}
|
||||
```
|
||||
|
||||
Для запросов есть индексы `impression(advertising_id, shown_at)` и
|
||||
`click(advertising_id, clicked_at)` (changelog `add/021`).
|
||||
|
||||
## Эндпоинты
|
||||
|
||||
### Публичные
|
||||
|
||||
| Метод и путь | Что делает |
|
||||
|---|---|
|
||||
| `GET /api/ads/next` | выбрать объявление (200 или 204) |
|
||||
| `POST /api/ads/impression` | записать показ |
|
||||
| `POST /api/ads/click` | записать клик |
|
||||
| `GET /api/fullscreen-ad` | активный полноэкранный ролик (200 или 204) |
|
||||
| `GET /api/v1/ads-media/{*key}` | файл медиа (поток, Range) |
|
||||
|
||||
### Админка (роль `ADMIN`: `/api/v1/admin/**` + `@PreAuthorize`)
|
||||
|
||||
Кампании — `CampaignAdminController`, `/api/v1/admin/campaigns`:
|
||||
|
||||
| Метод и путь | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `GET /` | — | список `CampaignResponseDto` (новые сверху) |
|
||||
| `GET /{campaignId}` | — | `CampaignResponseDto`; нет → 404 |
|
||||
| `POST /` | `{name, startDate, endDate, dailyImpressionCap}` | 201; `startDate ≥ endDate` или кап ≤ 0 → 400 |
|
||||
| `PUT /{campaignId}` | то же | 200; те же проверки → 400 |
|
||||
| `PATCH /{campaignId}/status` | `{status}` | 200 с новым статусом; недопустимый переход → 422 |
|
||||
| `GET /{campaignId}/stats?from=&to=` | — | `CampaignStatsDto` (раздел «Статистика») |
|
||||
|
||||
`CampaignResponseDto`: `{id, name, status, startDate, endDate, dailyImpressionCap}`.
|
||||
|
||||
Объявления — `AdvertisingAdminController`, `/api/v1/admin/ads`:
|
||||
|
||||
| Метод и путь | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `GET /?campaignId=` | — | список `AdvertisingAdminResponseDto` |
|
||||
| `POST /` | `{campaignId, type, mediaKey, targetUrl, weight}` | 201; кампании нет → 404; `weight ≤ 0`, `IMAGE` без `mediaKey`, плохой `targetUrl` → 400 |
|
||||
| `PUT /{advertisingId}` | `{targetUrl, weight}` | 200 |
|
||||
| `POST /image` | multipart `file` | `{mediaKey}` |
|
||||
| `POST /{advertisingId}/video/presign-upload` | `{contentType}` | `{uploadUrl, sourceKey, expiryMinutes}` |
|
||||
| `POST /{advertisingId}/video/confirm-upload` | `{sourceKey}` | 202; чужой ключ → 400 |
|
||||
| `GET /{advertisingId}/status` | — | `{advertisingId, transcodingStatus}` |
|
||||
|
||||
`AdvertisingAdminResponseDto`: `{id, campaignId, type, targetUrl, weight, transcodingStatus}`.
|
||||
|
||||
Полноэкранная реклама — `FullscreenAdAdminController`, `/api/v1/admin/fullscreen-ads`:
|
||||
|
||||
| Метод и путь | Тело | Ответ |
|
||||
|---|---|---|
|
||||
| `GET /` | — | список `FullscreenAdAdminResponseDto` |
|
||||
| `POST /` | `{targetUrl}` | 201, статус `DRAFT` |
|
||||
| `POST /{id}/video/presign-upload` | `{contentType}` | как у объявлений |
|
||||
| `POST /{id}/video/confirm-upload` | `{sourceKey}` | 202; ключ не из `fullscreen-sources/{id}/` → 400 |
|
||||
| `GET /{id}/status` | — | `{advertisingId, transcodingStatus}` |
|
||||
| `PATCH /{id}/activate` | — | делает ролик единственным `ACTIVE` (прежний → `INACTIVE`); ролик не `READY` → 422 |
|
||||
| `PATCH /{id}/deactivate` | — | `INACTIVE` |
|
||||
|
||||
`FullscreenAdAdminResponseDto`: `{id, targetUrl, status, transcodingStatus}`.
|
||||
При активации прежний активный ролик сохраняется в БД первым (`saveAndFlush`),
|
||||
иначе порядок UPDATE мог нарушить уникальный индекс.
|
||||
|
||||
## Ошибки
|
||||
|
||||
| Ситуация | Ответ |
|
||||
|---|---|
|
||||
| нет кампании/объявления/ролика (`EntityNotFoundException`) | 404 `NOT_FOUND` |
|
||||
| невалидное тело (`@Valid`), плохая ссылка, неверный тип файла | 400 `VALIDATION_ERROR` (или пустой 400 из контроллера) |
|
||||
| недопустимый переход статуса кампании | 422 `INVALID_STATUS_TRANSITION` |
|
||||
| нет роли `ADMIN` | 403 |
|
||||
|
||||
## Настройки (`ads.*`, `AdsProperties`)
|
||||
|
||||
| Свойство | Переменная | По умолчанию | Смысл |
|
||||
|---|---|---|---|
|
||||
| `ads.timezone` | `ADS_TIMEZONE` | `Europe/Moscow` | пояс дат кампаний и суток дневного лимита |
|
||||
| `ads.session-cooldown` | — | `PT30S` | пауза между показами одному субъекту |
|
||||
| `ads.eligible-cache-ttl` | — | `PT30S` | кэш кандидатов в памяти экземпляра |
|
||||
| `ads.finish-expired-cron` | — | каждые 10 минут | завершение кампаний по `endDate` |
|
||||
| `ads.tracking.secret` | `ADS_TRACKING_SECRET` | `jwt.secret` | ключ подписи токенов показа |
|
||||
| `ads.tracking.token-ttl` | — | `PT1H` | сколько после выдачи принимается показ/клик |
|
||||
| `ads.tracking.require-token` | `ADS_REQUIRE_TRACKING_TOKEN` | `false` | отклонять показы/клики без токена |
|
||||
|
||||
## Что можно улучшить
|
||||
|
||||
- Включить `ads.tracking.require-token` после того, как фронт начнёт
|
||||
присылать `impressionToken`.
|
||||
- Viewability (засчитывать показ, когда ≥ 50% баннера видно ≥ 1 с, по стандарту
|
||||
IAB/MRC) — решается на клиенте: отправлять `/impression` по
|
||||
IntersectionObserver.
|
||||
- Бюджеты и общий лимит показов кампании (не на пользователя), темп
|
||||
расходования (pacing).
|
||||
- Удаление кампаний/объявлений с чисткой медиа в MinIO (сейчас их архивирует
|
||||
статус `FINISHED`).
|
||||
- Восстановление транскодинга: если экземпляр упал во время ffmpeg, объявление
|
||||
останется в `PROCESSING` — нужен повторный `confirm-upload`.
|
||||
281
docs/images-storage.md
Normal file
281
docs/images-storage.md
Normal file
@@ -0,0 +1,281 @@
|
||||
# Картинки и файловое хранилище
|
||||
|
||||
Как ReFound принимает, хранит, отдаёт и удаляет картинки: фото объявлений,
|
||||
аватары и медиа рекламы. Всё описано по коду; имена классов — от пакета
|
||||
`com.krylov.refound`.
|
||||
|
||||
## Коротко
|
||||
|
||||
```
|
||||
клиент ──multipart──► контроллер ──► FileStorageService.uploadFile
|
||||
│ 1. validateFile: не пустой, есть имя, ≤ 10 МБ, Content-Type jpeg/png/webp
|
||||
│ 2. ImageFormat.detect: сигнатура файла = JPEG/PNG/WebP
|
||||
│ 3. ImageOptimizer.optimize: > 300 КБ → до 1600px, JPEG 0.82
|
||||
│ 4. PutObject в бакет minio.bucket, ключ <папка/>UUID.<ext>
|
||||
│ 5. Redis files:owner:<ключ> = логин (180 дней)
|
||||
▼
|
||||
ключ объекта (строка) ──► хранится в БД (images.url, users.avatar_url)
|
||||
|
||||
показ: GET /api/v1/files/<ключ> → прокси через бэкенд (байты + Cache-Control)
|
||||
GET /api/v1/files/<ключ>?presigned=true → 302 на presigned URL MinIO (ссылка кэшируется в Redis)
|
||||
GET /api/v1/files/url/<ключ> → {"url": presigned URL}
|
||||
модерация: PostModerationExecutorService скачивает файлы из MinIO и шлёт их в AI-сервис
|
||||
удаление: сервисы после коммита транзакции; DELETE /api/v1/files/<ключ> — владелец или админ
|
||||
```
|
||||
|
||||
## Где что лежит
|
||||
|
||||
| Что | Бакет | Ключ | Кто пишет |
|
||||
|---|---|---|---|
|
||||
| Фото объявлений | `minio.bucket` (`refound-images`) | `<uuid>.<ext>` (в корне) | `PostService.attachImages`, `AdminPostService.syncImages`, `POST /api/v1/files` |
|
||||
| Аватары | `minio.bucket` | `avatars/<uuid>.<ext>` | `UserService.updateUser` |
|
||||
| Картинки рекламы | `minio.ads-bucket` (`ads-media`) | `images/<uuid>.<ext>` | `AdvertisingMediaService.uploadImage` |
|
||||
| Исходники видео рекламы | `minio.ads-bucket` | `sources/<adId>/<uuid>.<ext>`, `fullscreen-sources/<id>/<uuid>.<ext>` | браузер админа по presigned PUT |
|
||||
| Готовые ролики | `minio.ads-bucket` | `videos/<uuid>.mp4`, `fullscreen/<uuid>.mp4` | `VideoTranscoderService` |
|
||||
|
||||
В БД хранится только **ключ** объекта (`images.url`, `users.avatar_url`,
|
||||
`advertising.media_key`, `fullscreen_advertising.media_key`), а не URL: адрес
|
||||
MinIO и срок ссылок могут меняться.
|
||||
|
||||
## Подключение к MinIO
|
||||
|
||||
- `config/MinioProperties` — типизированные `minio.*` (`endpoint`, `bucket`,
|
||||
`access-key`, `secret-key`, `region`), все обязательны (`@Validated`).
|
||||
`minio.ads-bucket` читается через `@Value` в рекламных сервисах.
|
||||
- `config/S3ClientConfig` создаёт `S3Client` и `S3Presigner` (AWS SDK v2) с
|
||||
`endpointOverride` и path-style адресами — так работает MinIO.
|
||||
- Автоконфигурация Spring Cloud AWS S3 отключена в `ReFoundApplication`
|
||||
(`exclude = S3AutoConfiguration.class`), клиенты свои.
|
||||
- Зависимость `io.minio:minio` в `build.gradle` есть, но в коде не используется.
|
||||
|
||||
### Что происходит при старте
|
||||
|
||||
`health/StorageStructureService` по `ContextRefreshedEvent`:
|
||||
|
||||
1. создаёт бакет `minio.bucket`, если его нет;
|
||||
2. включает версионирование;
|
||||
3. ставит правило жизненного цикла: **неактуальные версии** (то, что осталось
|
||||
после удаления/перезаписи) удаляются через 30 дней, «пустые» delete-маркеры
|
||||
убираются. Текущие версии файлов не истекают никогда.
|
||||
|
||||
Ошибки на любом шаге только логируются — приложение стартует и без MinIO.
|
||||
|
||||
> Раньше правило удаляло **все** объекты старше 180 дней, включая аватары и
|
||||
> картинки живых объявлений. Теперь файлы удаляет само приложение (см.
|
||||
> «Удаление»), а правило подчищает только старые версии.
|
||||
|
||||
Бакет `ads-media` и его CORS (`minio/cors.json`) создаёт контейнер `mc-init`
|
||||
из `docker-compose.yaml`. CORS там разрешает только `localhost:5173` и
|
||||
`localhost:3000` — для боевого домена админки правило нужно дополнить, иначе
|
||||
браузер не сможет загрузить видео по presigned PUT.
|
||||
|
||||
## Загрузка
|
||||
|
||||
### Валидация — `FileStorageService.validateFile` + `util/ImageFormat`
|
||||
|
||||
По порядку:
|
||||
|
||||
| Проверка | Ответ при нарушении |
|
||||
|---|---|
|
||||
| файл не пустой | 400 `VALIDATION_ERROR` «Файл не может быть пустым.» |
|
||||
| у файла есть оригинальное имя | 400 «Имя файла отсутствует.» |
|
||||
| размер ≤ 10 МБ (`MAX_FILE_SIZE`) | 400 «Файл слишком большой (максимум 10 МБ).» |
|
||||
| заявленный `Content-Type` ∈ `image/jpeg`, `image/png`, `image/webp` | 400 «Недопустимый тип файла.» |
|
||||
| **сигнатура файла** — JPEG (`FF D8 FF`), PNG (`89 50 4E 47 0D 0A 1A 0A`) или WebP (`RIFF....WEBP`) | 400 «Недопустимый тип файла.» |
|
||||
|
||||
Расширение ключа и `Content-Type` объекта берутся **из распознанного
|
||||
формата**, а не из имени файла и заголовка клиента. Иначе HTML/SVG с
|
||||
`Content-Type: image/png` сохранялся бы под ключом `<uuid>.html`.
|
||||
|
||||
Кроме того, Spring ограничивает multipart (`application.yaml`):
|
||||
`max-file-size: 10MB`, `max-request-size: 20MB`. Превышение даёт 413
|
||||
(`MaxUploadSizeExceededException` в `GlobalExceptionHandler`).
|
||||
|
||||
Картинки рекламы (`AdvertisingMediaService.uploadImage`) проверяются так же,
|
||||
но без оптимизации.
|
||||
|
||||
### Сжатие — `service/ImageOptimizer`
|
||||
|
||||
Фото с телефона весят 3–10 МБ при 12–24 Мп; лента с такими оригиналами
|
||||
открывается медленно. `optimize(byte[] source, String contentType)`:
|
||||
|
||||
1. Файлы **≤ 300 КБ** (`SKIP_BELOW_BYTES`) не трогает — они и так лёгкие.
|
||||
2. Размер читает из заголовка без декодирования пикселей (`maxSide`).
|
||||
Если большая сторона > **1600 px** (`MAX_DIMENSION`) — уменьшает до 1600
|
||||
по большей стороне с сохранением пропорций (Thumbnailator); меньшие
|
||||
картинки не увеличивает, только пережимает.
|
||||
3. Thumbnailator поворачивает картинку по EXIF-ориентации; сами EXIF
|
||||
(включая геометку) в результат не попадают.
|
||||
4. Картинку с прозрачностью (PNG/WebP с альфой) сохраняет в **PNG**; всё
|
||||
остальное — в **progressive JPEG** с качеством **0.82** (прозрачные места
|
||||
заливаются белым).
|
||||
5. Если результат не меньше оригинала или файл не читается — возвращает
|
||||
`Optional.empty()`, и сохраняется оригинал.
|
||||
|
||||
Плагины TwelveMonkeys (`imageio-jpeg`, `imageio-webp`) дают чтение WebP и
|
||||
CMYK-JPEG; `ImageIO.scanForPlugins()` в `@PostConstruct` регистрирует их в fat jar.
|
||||
Запись WebP не поддерживается, поэтому WebP после сжатия становится JPEG/PNG.
|
||||
|
||||
### Сохранение
|
||||
|
||||
`FileStorageService.uploadFile(file, folder)`:
|
||||
|
||||
- ключ: `<folder>/` + `UUID` + расширение (`.jpg`/`.png`/`.webp`);
|
||||
- метаданные объекта: `original-filename` (URL-encoded исходное имя) — нужно
|
||||
для `Content-Disposition` при скачивании;
|
||||
- после `PutObject` — `registerOwner`: в Redis `files:owner:<ключ>` = логин
|
||||
текущего пользователя на 180 дней (только если запрос авторизован);
|
||||
- ошибки S3 → 500 `INTERNAL_ERROR` «Ошибка при загрузке файла.».
|
||||
|
||||
Кто вызывает:
|
||||
|
||||
| Вызов | Папка |
|
||||
|---|---|
|
||||
| `POST /api/v1/posts` (multipart `images`) → `PostService.create` → `attachImages` | корень |
|
||||
| `PUT /api/v1/posts/{id}` → `PostService.update` | корень |
|
||||
| `PUT /api/v1/admin/posts/{id}` → `AdminPostService.updatePost` | корень |
|
||||
| `PUT /api/v1/users/{id}` (multipart `avatar`) → `UserService.updateUser` | `avatars` |
|
||||
| `POST /api/v1/files` (поле `file`) → возвращает ключ строкой | корень |
|
||||
|
||||
При создании и правке объявления (`PostService.create`/`update`) фото
|
||||
загружаются **до** транзакции БД — соединение с базой не держится, пока идёт
|
||||
загрузка в MinIO и запрос к геокодеру. Если загрузка одного из фото или
|
||||
транзакция упали, уже загруженные файлы удаляются. То, что всё же осталось
|
||||
без ссылки (например, `POST /api/v1/files` без последующего сохранения
|
||||
формы), убирает ночная чистка (см. ниже). Админская правка
|
||||
(`AdminPostService`) по-прежнему загружает файлы внутри транзакции.
|
||||
|
||||
## Отдача
|
||||
|
||||
### Прокси через бэкенд — `GET /api/v1/files/{*key}` (публично)
|
||||
|
||||
`FileStorageService.downloadFile`: `HeadObject` (тип, исходное имя) +
|
||||
`GetObjectAsBytes`. Ответ:
|
||||
|
||||
- `Content-Type` — как сохранён;
|
||||
- `Content-Disposition: inline` для картинок, `attachment` для остального,
|
||||
с исходным именем (`filename*=UTF-8''...`);
|
||||
- для картинок `Cache-Control: private, max-age=31536000, immutable` — ключи
|
||||
уникальны (UUID) и не меняются, так что браузер может хранить картинку год.
|
||||
Без явного заголовка Spring Security ставил бы `no-store`, и лента
|
||||
перекачивала бы все картинки при каждом открытии.
|
||||
|
||||
Файл целиком читается в память (до 10 МБ на картинку). Отсутствующий ключ → 404.
|
||||
|
||||
### Presigned URL
|
||||
|
||||
- `GET /api/v1/files/{*key}?presigned=true` → **302** на presigned GET URL
|
||||
MinIO. `FileStorageService.getCachedPresignedDownloadUrl` кэширует ссылку
|
||||
в Redis (`files:presigned:<ключ>`, TTL 12 ч), сама ссылка живёт 24 ч, а
|
||||
редирект браузер кэширует 6 ч (`Cache-Control: private, max-age=21600`).
|
||||
Пока URL одинаковый, браузер берёт картинку из своего кэша. В ссылку
|
||||
зашит `response-cache-control`, поэтому MinIO отдаёт тот же
|
||||
`immutable`-заголовок. Если Redis недоступен — генерируется новая ссылка.
|
||||
- `GET /api/v1/files/url/{*key}?ttlHours=24` → `{"url": "..."}`. `ttlHours`
|
||||
ограничен 168 часами (7 дней — максимум подписи SigV4); ≤ 0 → 24 ч.
|
||||
|
||||
Presigned URL подписан под `minio.endpoint`. Если это внутренний адрес
|
||||
(`http://minio:9010`), снаружи ссылка не откроется — тогда используйте
|
||||
прокси-вариант или задайте публичный `MINIO_ENDPOINT`.
|
||||
|
||||
### Медиа рекламы — `GET /api/v1/ads-media/{*key}` (публично)
|
||||
|
||||
`AdvertisingMediaService.downloadMedia` отдаёт объект из `ads-media`
|
||||
**потоком** (`InputStreamResource`), не загружая его в память, и понимает
|
||||
`Range`:
|
||||
|
||||
- без `Range` — 200, `Content-Length`, `Accept-Ranges: bytes`;
|
||||
- `Range: bytes=a-b` (а также `a-` и `-n`) — 206 и `Content-Range`, из MinIO
|
||||
читается только нужный кусок;
|
||||
- диапазон за пределами файла — 416 с `Content-Range: bytes */<длина>`;
|
||||
- `Cache-Control: public, max-age=2592000` (30 дней): ключи медиа неизменяемы.
|
||||
|
||||
Range нужен видеоплееру: Safari на iOS без 206 видео не воспроизводит, а
|
||||
перемотка в остальных браузерах иначе качает файл с начала.
|
||||
|
||||
## Удаление
|
||||
|
||||
| Сценарий | Что удаляется | Когда |
|
||||
|---|---|---|
|
||||
| Владелец удаляет объявление (`DELETE /api/v1/posts/{id}`) | все картинки поста | после коммита (`PostDeletionService`) |
|
||||
| Админ удаляет объявление (`DELETE /api/v1/admin/posts/{id}`) | все картинки поста | после коммита |
|
||||
| Ночная чистка (`SchedulerService.deleteExpiredPosts`, 00:01) — CLOSED и старше 6 мес. | все картинки постов | после коммита |
|
||||
| Правка объявления — картинки, которых нет в `existingImages` | убранные картинки | после коммита (`PostDeletionService.deleteFilesAfterCommit`) |
|
||||
| Новый аватар или `removeAvatar=true` | старый аватар | после сохранения профиля |
|
||||
| Ночная чистка сирот (`OrphanFileCleanupService`, 03:30) | файлы старше суток без ссылок из `images.url` и `users.avatar_url` | сразу, не больше 5000 за прогон |
|
||||
| `DELETE /api/v1/files/{*key}` | один файл | сразу; только владелец (по `files:owner:<ключ>`) или `ADMIN` |
|
||||
| Транскодинг видео рекламы | исходник `sources/...` | после транскодинга, в т.ч. неудачного |
|
||||
|
||||
`FileStorageService.deleteFile` удаляет объект и записи Redis
|
||||
`files:owner:<ключ>` и `files:presigned:<ключ>`. Ошибки хранилища при
|
||||
удалении постов только логируются (`warn`) — объявление удаляется в любом случае.
|
||||
|
||||
Почему «после коммита»: если транзакция удаления/правки откатится, пост
|
||||
останется с целыми картинками, а не со ссылками на удалённые файлы.
|
||||
|
||||
Через `DELETE /api/v1/files` удалить можно только файл, у которого есть
|
||||
отметка о владельце (загружен через API, не старше 180 дней). Файлы без
|
||||
отметки удаляет только администратор.
|
||||
|
||||
Бакет версионируемый: после удаления объект становится неактуальной
|
||||
версией и физически исчезает через 30 дней (правило жизненного цикла).
|
||||
|
||||
### Чистка файлов-сирот
|
||||
|
||||
`service/OrphanFileCleanupService` (cron `storage.orphan-cleanup.cron`,
|
||||
по умолчанию 03:30, ShedLock — один экземпляр):
|
||||
|
||||
1. собирает все значения `images.url` и `users.avatar_url` и приводит их к
|
||||
ключу (полные URL и пути `/bucket/key` в старых записях тоже распознаются);
|
||||
2. листает бакет `minio.bucket` постранично;
|
||||
3. удаляет объекты старше `min-age` (24 ч), на которые нет ссылок, — не
|
||||
больше `max-deletes` (5000) за прогон.
|
||||
|
||||
Выключается `STORAGE_ORPHAN_CLEANUP_ENABLED=false`. Ошибочно удалённое можно
|
||||
восстановить из неактуальной версии в течение 30 дней.
|
||||
|
||||
## Отправка на AI-модерацию
|
||||
|
||||
Картинки модерируются не при загрузке, а фоновой задачей:
|
||||
|
||||
1. `PostService.create`/`update` ставит посту статус `MODERATION`.
|
||||
2. `SchedulerService.moderatePendingPosts` раз в 60 секунд (одним экземпляром — ShedLock) берёт id постов
|
||||
на модерации и для каждого вызывает `PostModerationExecutorService.moderateOne`.
|
||||
3. Короткая транзакция читает снимок поста: заголовок, описание, ключи картинок.
|
||||
4. Без транзакции каждая картинка скачивается из MinIO
|
||||
(`FileStorageService.downloadFileRaw` — уже сжатая версия) и
|
||||
оборачивается в `util/ByteArrayMultipartFile`.
|
||||
5. `ContentModerationFacade` → `ContentModerationPipeline`:
|
||||
`TextModerationProcessor` (order 10), затем `ImageModerationProcessor`
|
||||
(order 20). Каждая картинка уходит в `ImageModerationClient` →
|
||||
`AiMultipartHttpClient`: `POST {ai.url}/api/v1/moderation/image`,
|
||||
multipart-поле `file`, таймаут ответа `ai.image-timeout` (30 с),
|
||||
ретраи по `ai.retry.*` на 5xx/503/таймаут/недоступность.
|
||||
6. Ответ `approved=false` → `ContentBlockedException` → пост `REJECTED`.
|
||||
7. Новая транзакция ставит `ACTIVE`/`REJECTED`, только если пост всё ещё в
|
||||
`MODERATION` и не менялся с момента снимка (заголовок, описание, набор
|
||||
картинок). Иначе вердикт отбрасывается и новая версия проверяется в
|
||||
следующий запуск.
|
||||
|
||||
| Ситуация | Статус поста |
|
||||
|---|---|
|
||||
| AI одобрил текст и все картинки | `ACTIVE` (+ сброс кэша ленты/карты) |
|
||||
| AI отклонил текст или картинку | `REJECTED` |
|
||||
| AI вернул 4xx (не принимает файл) | `REJECTED` |
|
||||
| Картинки нет в MinIO (404) | `REJECTED` |
|
||||
| AI недоступен после ретраев, MinIO недоступен, иная ошибка | остаётся `MODERATION`, повтор через минуту |
|
||||
|
||||
## Связанные классы
|
||||
|
||||
| Класс | Роль |
|
||||
|---|---|
|
||||
| `controller/FileStorageController` | `/api/v1/files`: загрузка, прокси, presigned, удаление |
|
||||
| `service/FileStorageService` | работа с бакетом картинок, владельцы, кэш ссылок |
|
||||
| `service/ImageOptimizer` | ресайз и пережатие |
|
||||
| `util/ImageFormat` | распознавание формата по сигнатуре |
|
||||
| `service/PostDeletionService` | удаление постов и файлов после коммита |
|
||||
| `service/OrphanFileCleanupService` | ночная чистка файлов без ссылок |
|
||||
| `service/PostModerationExecutorService` | модерация одного поста |
|
||||
| `health/StorageStructureService` | бакет, версионирование, lifecycle |
|
||||
| `config/S3ClientConfig`, `config/MinioProperties` | клиенты S3 |
|
||||
| `controller/advertising/AdvertisingMediaController`, `service/advertising/AdvertisingMediaService` | медиа рекламы |
|
||||
231
docs/redis.md
Normal file
231
docs/redis.md
Normal file
@@ -0,0 +1,231 @@
|
||||
# Redis в ReFound
|
||||
|
||||
Redis — общий для всех экземпляров приложения слой: кэш, refresh-токены,
|
||||
лимиты запросов и рекламы, распределённые блокировки фоновых задач и шина
|
||||
WebSocket-событий. Источник правды везде — PostgreSQL или MinIO, кроме
|
||||
refresh-токенов и счётчиков: они живут только в Redis.
|
||||
|
||||
## Подключение
|
||||
|
||||
`application.yaml`:
|
||||
|
||||
```yaml
|
||||
spring:
|
||||
data:
|
||||
redis:
|
||||
host: ${REDIS_HOST:localhost}
|
||||
port: 6379
|
||||
password: ${REDIS_PASSWORD} # обязателен, значения по умолчанию нет
|
||||
timeout: 500ms # таймаут команды
|
||||
connect-timeout: 500ms
|
||||
```
|
||||
|
||||
Клиент — Lettuce (по умолчанию в `spring-boot-starter-data-redis`).
|
||||
Шаблоны (`config/RedisConfig`):
|
||||
|
||||
| Бин | Значение | Сериализация |
|
||||
|---|---|---|
|
||||
| `StringRedisTemplate` (автоконфигурация) | строки | ключ и значение — строки |
|
||||
| `postCacheRedisTemplate` | `dto/CachedPostPage` — страница ленты | ключ — строка, значение — JSON (Jackson) |
|
||||
| `mapRedisTemplate` | `List<dto/MapMarkerDto>` — метки карты | ключ — строка, значение — JSON |
|
||||
|
||||
Для JSON-шаблонов берётся копия `ObjectMapper` приложения с
|
||||
`FAIL_ON_UNKNOWN_PROPERTIES=false`: новые поля DTO не ломают чтение старых
|
||||
записей кэша.
|
||||
|
||||
### Redis в docker-compose
|
||||
|
||||
```
|
||||
redis-server --requirepass $REDIS_PASSWORD --maxmemory 256mb
|
||||
--maxmemory-policy volatile-lru --save "" --appendonly no
|
||||
```
|
||||
|
||||
- `volatile-lru` — при нехватке памяти вытесняются только ключи **с TTL**.
|
||||
Ключ версии кэша (`posts:version`) живёт без TTL и поэтому не вытесняется.
|
||||
Обратная сторона: refresh-токены тоже с TTL и при нехватке памяти могут
|
||||
быть вытеснены — пользователю придётся войти заново.
|
||||
- Персистентность выключена: после перезапуска Redis пропадают все
|
||||
refresh-токены (пользователи перелогиниваются, когда истечёт access-токен)
|
||||
и счётчики лимитов. Кэши восстанавливаются сами. Для production включите
|
||||
AOF (`--appendonly yes`) или используйте управляемый Redis с репликой, а
|
||||
для refresh-токенов — политику `noeviction` или отдельный экземпляр.
|
||||
- Порт открыт только на `127.0.0.1`.
|
||||
|
||||
## Все ключи
|
||||
|
||||
| Ключ | Тип | TTL | Что хранит | Класс |
|
||||
|---|---|---|---|---|
|
||||
| `posts:version` | string (INCR) | нет | версия всех данных объявлений | `service/redis/PostCacheService` |
|
||||
| `posts:feed:v{версия}:filter={sha256}:page={n}:size={n}:sort={поле:направление,...}` | JSON | 2 мин | страница публичной ленты | `PostService.getFeed`, `PostCacheKeyGenerator.feedKey` |
|
||||
| `posts:map:v{версия}:bbox={minLat},{maxLat},{minLng},{maxLng}:type={тип}:category={категория}` | JSON | 5 мин | метки карты | `MapService.findMarkers`, `PostCacheKeyGenerator.mapKey` |
|
||||
| `refresh_token:{uuid}` | string | `jwt.refresh-expiration` (7 дней) | логин владельца refresh-токена | `service/RefreshTokenService` |
|
||||
| `files:owner:{ключ файла}` | string | 180 дней | логин того, кто загрузил файл | `FileStorageService.registerOwner` |
|
||||
| `files:presigned:{ключ файла}` | string | 12 ч | presigned URL картинки | `FileStorageService.getCachedPresignedDownloadUrl` |
|
||||
| `geo:{lat}:{lon}` | JSON | 30 дней | город/район по координатам (округлены до 4 знаков) | `service/GeocodingService` |
|
||||
| `geo:throttle` | string | 1 с | слот общего лимита 1 запрос/с к Nominatim | `GeocodingService.acquireSlot` |
|
||||
| `ad:cap:{субъект}:{кампания}:{yyyyMMdd}` | string (INCR) | 48 ч | показы кампании субъекту за календарные сутки | `service/advertising/AdvertisingFrequencyService` |
|
||||
| `ad:cooldown:{субъект}` | string | 30 с | пауза между показами рекламы | `AdvertisingFrequencyService.tryStartCooldown` |
|
||||
| `ad:imp:{nonce}`, `ad:clk:{nonce}` | string | 1 ч (срок токена) | токен показа уже засчитан как показ/клик | `AdvertisingFrequencyService.markOnce` |
|
||||
| `rl:{правило}:{ip}:{номер окна}` | string (INCR) | длина окна | счётчик лимита запросов | `ratelimit/RedisRateLimiter` |
|
||||
| `rl:login-failures:{логин}:{номер окна}` | string (INCR) | 15 мин | неудачные входы в аккаунт | `AuthService.loginUser` |
|
||||
| `job-lock:refound:{задача}` | string | `lockAtMostFor` задачи | блокировка фоновой задачи (ShedLock) | `config/SchedulerLockConfig` |
|
||||
| канал `ws:broadcast` | pub/sub | — | STOMP-события для всех экземпляров | `config/ClusterMessaging` |
|
||||
|
||||
Субъект рекламы — `u{userId}` для авторизованного пользователя или
|
||||
`s{sessionId}` для гостя.
|
||||
|
||||
В старых базах могут остаться ключи прежних версий: `maps:markers:version`,
|
||||
`ad:freq:*`, `ad:session:*:cooldown`. Их никто не читает — удалите или
|
||||
дождитесь TTL.
|
||||
|
||||
## Кэш ленты и карты
|
||||
|
||||
### Что кэшируется
|
||||
|
||||
- **Лента без поиска** — `GET /api/v1/posts` без параметра `search`
|
||||
(`PostService.getFeed`). Ключ учитывает фильтры (`PostFeedFilter.cacheKeyPart()`
|
||||
→ SHA-256: тип, категории, города), номер и размер страницы и сортировку.
|
||||
К сортировке всегда добавляется `id DESC`, чтобы страницы были стабильными.
|
||||
TTL 2 минуты.
|
||||
- **Метки карты** — `GET /api/v1/posts/map` (`MapService.findMarkers`). Углы
|
||||
прямоугольника округляются до сетки 0,01° (≈1 км), чтобы соседние положения
|
||||
карты попадали в один ключ. TTL 5 минут.
|
||||
|
||||
Не кэшируются: поиск по тексту (запросы почти всегда уникальны, отвечает
|
||||
GIN-индекс), объявления пользователя, карточка объявления, избранное, чаты,
|
||||
админская лента.
|
||||
|
||||
### Инвалидация через версию
|
||||
|
||||
Удалять ключи по шаблону (`KEYS`/`SCAN`) дорого, поэтому версия — часть ключа:
|
||||
|
||||
1. Перед запросом в БД читается `posts:version` (нет ключа или Redis недоступен
|
||||
→ `"0"`), из неё строится ключ.
|
||||
2. Любое изменение объявлений вызывает `PostCacheService.invalidatePosts()`,
|
||||
который делает `INCR posts:version` **после коммита** транзакции
|
||||
(`TransactionSynchronization.afterCommit`; вне транзакции — сразу).
|
||||
3. Следующие запросы строят ключи с новой версией и идут в БД; старые записи
|
||||
никто не читает, они умирают по TTL.
|
||||
|
||||
Версия читается **до** запроса в БД: если пост изменится между чтением
|
||||
версии и сохранением кэша, устаревшая страница ляжет под старую версию и
|
||||
читаться не будет.
|
||||
|
||||
Кто сбрасывает кэш:
|
||||
|
||||
| Событие | Где |
|
||||
|---|---|
|
||||
| создание, правка, смена статуса объявления владельцем | `PostService.create`, `update`, `updateStatus` |
|
||||
| удаление владельцем, админом, ночной чисткой | `PostDeletionService.delete` |
|
||||
| правка и смена статуса админом | `AdminPostService.updatePost`, `updateStatus` |
|
||||
| пост прошёл AI-модерацию (стал виден) | `PostModerationExecutorService.moderateOne` |
|
||||
|
||||
Одна версия на ленту и карту: изменение поста сбрасывает оба представления.
|
||||
Смена имени, логина или аватара пользователя кэш не сбрасывает — в ленте
|
||||
старые данные видны до истечения TTL (до 2 минут).
|
||||
|
||||
## Refresh-токены
|
||||
|
||||
`RefreshTokenService`:
|
||||
|
||||
- **выдача** (`/auth/register`, `/auth/login`, `/auth/refresh`): клиент
|
||||
получает строку `{uuid}.{jwt}`; в Redis пишется `refresh_token:{uuid}` =
|
||||
логин с TTL, равным сроку жизни refresh-JWT;
|
||||
- **обмен** (`POST /api/v1/auth/refresh`): JWT проверяется по подписи и типу
|
||||
(`typ=refresh`), затем запись забирается атомарно `GETDEL`. Повторный или
|
||||
параллельный обмен того же токена получает 401 — токен одноразовый.
|
||||
Логин из Redis должен совпадать с логином в JWT;
|
||||
- **выход** (`POST /api/v1/auth/logout`): запись удаляется.
|
||||
|
||||
Если Redis недоступен, вход, регистрация и обмен токена отвечают ошибкой —
|
||||
без Redis новые сессии не создаются. Уже выданные access-токены (15 минут)
|
||||
продолжают работать: они проверяются только по подписи.
|
||||
|
||||
## Файлы
|
||||
|
||||
- `files:owner:{ключ}` — кто загрузил файл. Нужен только для
|
||||
`DELETE /api/v1/files/{ключ}`: удалить может владелец или админ. Без
|
||||
записи (старый файл, Redis очищен) удалить файл через API может только админ.
|
||||
- `files:presigned:{ключ}` — одна и та же presigned-ссылка на 12 часов, чтобы
|
||||
браузер кэшировал картинку (сама ссылка живёт 24 ч).
|
||||
|
||||
Обе записи удаляются вместе с файлом (`FileStorageService.deleteFile`).
|
||||
Ошибки Redis здесь не роняют запрос: владелец не сохранится, ссылка
|
||||
сгенерируется заново.
|
||||
|
||||
Подробнее — в [images-storage.md](images-storage.md).
|
||||
|
||||
## Реклама
|
||||
|
||||
`AdvertisingFrequencyService` (подробно — в [advertising.md](advertising.md)):
|
||||
|
||||
- **дневной лимит кампании**: при выдаче одним `MGET` читаются
|
||||
`ad:cap:{субъект}:{кампания}:{день}` всех кампаний-кандидатов; на
|
||||
подтверждённом показе счётчик растёт Lua-скриптом `INCR` + `PEXPIRE 48h`.
|
||||
Сутки — календарные в `ads.timezone`;
|
||||
- **пауза между показами**: `SET ad:cooldown:{субъект} NX EX 30` в момент выдачи;
|
||||
- **однократный учёт**: `SET ad:imp:{nonce} NX EX 3600` (и `ad:clk:`) — токен
|
||||
показа засчитывается один раз.
|
||||
|
||||
Если Redis недоступен, `GET /api/ads/next` отвечает 204 (реклама не
|
||||
показывается); показ по токену сохраняется в БД без проверки повтора.
|
||||
|
||||
## Лимиты запросов
|
||||
|
||||
`ratelimit/RateLimitFilter` + `RedisRateLimiter`: фиксированное окно,
|
||||
ключ `rl:{правило}:{ip}:{номер окна}`, `INCR` и `PEXPIRE` одним Lua-скриптом
|
||||
(атомарно, ключ без TTL не появится). Правила — `rate-limit.rules` в
|
||||
`application.yaml` (вход, регистрация, refresh, check-login, создание
|
||||
объявлений, загрузка файлов, начало чата, реклама). Превышение — 429 с
|
||||
`Retry-After`.
|
||||
|
||||
Отдельно `AuthService` считает неудачные входы в аккаунт
|
||||
(`rl:login-failures:{логин}:...`): после 10 за 15 минут вход в этот аккаунт
|
||||
блокируется до конца окна (429), успешный вход сбрасывает счётчик.
|
||||
|
||||
Лимиты — защитный слой: при недоступном Redis запросы пропускаются
|
||||
(fail-open), чтобы сбой Redis не остановил API. IP клиента за прокси берётся
|
||||
из `X-Forwarded-For` (`server.forward-headers-strategy=native`).
|
||||
|
||||
## Несколько экземпляров приложения
|
||||
|
||||
- **Фоновые задачи** — ShedLock (`RedisLockProvider`, ключ
|
||||
`job-lock:refound:{задача}`): ночная чистка постов, модерация, словарь
|
||||
подсказок, завершение кампаний, чистка файлов-сирот выполняются одним
|
||||
экземпляром. Нет Redis — задача пропускает запуск.
|
||||
- **WebSocket** — брокер STOMP встроенный (в памяти экземпляра), поэтому
|
||||
события (новые сообщения чата, счётчики непрочитанных, статусы
|
||||
транскодинга) публикуются в канал `ws:broadcast`; каждый экземпляр
|
||||
подписан на канал (`RedisMessageListenerContainer`) и отдаёт событие своим
|
||||
подписчикам. Выключается `app.websocket.cluster-broadcast=false`. Без Redis
|
||||
событие доставляется только локально.
|
||||
- Кэши, лимиты, токены и блокировки в Redis — общие; в памяти экземпляра
|
||||
остаются только список кандидатов рекламы (30 с) и буфер статистики
|
||||
поисков (сбрасывается в БД раз в минуту).
|
||||
|
||||
## Чего в Redis нет
|
||||
|
||||
- **HTTP-сессий** — приложение stateless (`SessionCreationPolicy.STATELESS`),
|
||||
Spring Session не подключён.
|
||||
- **Spring Cache (`@Cacheable`)** — не используется, кэш собран вручную.
|
||||
- **Подсказки поиска** — `SearchSuggestService` копит статистику поисков в
|
||||
памяти процесса и раз в минуту пишет её в PostgreSQL (`search_words`).
|
||||
|
||||
## Поведение при недоступности Redis
|
||||
|
||||
| Функция | Что происходит |
|
||||
|---|---|
|
||||
| Лента, карта | кэш пропускается (warn в лог), данные из БД |
|
||||
| Presigned-ссылки | генерируется новая ссылка на каждый запрос |
|
||||
| Владельцы файлов | не сохраняются; удалить файл через API сможет только админ |
|
||||
| Вход, регистрация, refresh, logout | ошибка 500 |
|
||||
| Лимиты запросов и блокировка перебора | не применяются (fail-open) |
|
||||
| Геокодер | без кэша и общего лимита |
|
||||
| Реклама `/api/ads/next` | 204, реклама не показывается |
|
||||
| Показы/клики | сохраняются, без проверки повторов и без роста дневного лимита |
|
||||
| Фоновые задачи | пропускают запуск (блокировку не взять) |
|
||||
| WebSocket между экземплярами | события доставляются только подписчикам своего экземпляра |
|
||||
| Проверка access-токенов, чаты по REST, остальное API | работает |
|
||||
|
||||
Команды ограничены таймаутом 500 мс, так что недоступный Redis не вешает
|
||||
запросы надолго.
|
||||
@@ -3,7 +3,9 @@ package com.krylov.refound;
|
||||
import com.krylov.refound.ai.config.AiProperties;
|
||||
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;
|
||||
@@ -17,7 +19,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
|
||||
)@EnableScheduling
|
||||
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
|
||||
SearchProperties.class})
|
||||
SearchProperties.class, RateLimitProperties.class, AdsProperties.class})
|
||||
@EnableRetry
|
||||
public class ReFoundApplication {
|
||||
|
||||
|
||||
@@ -20,8 +20,10 @@ public class ImageModerationClient {
|
||||
|
||||
@Retryable(
|
||||
retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
|
||||
maxAttempts = 3,
|
||||
backoff = @Backoff(delay = 500, multiplier = 2)
|
||||
// Параметры из ai.retry.* (AiRetryProperties); раньше они были захардкожены
|
||||
maxAttemptsExpression = "${ai.retry.max-attempts:3}",
|
||||
backoff = @Backoff(delayExpression = "${ai.retry.delay:500}",
|
||||
multiplierExpression = "${ai.retry.multiplier:2}")
|
||||
)
|
||||
public ImageModerationResponse moderate(MultipartFile file) {
|
||||
log.info("Calling AI ImageModeration service");
|
||||
|
||||
@@ -21,8 +21,10 @@ public class TextModerationClient {
|
||||
|
||||
@Retryable(
|
||||
retryFor = {AiUnavailableException.class, AiServerException.class, AiTimeoutException.class},
|
||||
maxAttempts = 3,
|
||||
backoff = @Backoff(delay = 500, multiplier = 2)
|
||||
// Параметры из ai.retry.* (AiRetryProperties); раньше они были захардкожены
|
||||
maxAttemptsExpression = "${ai.retry.max-attempts:3}",
|
||||
backoff = @Backoff(delayExpression = "${ai.retry.delay:500}",
|
||||
multiplierExpression = "${ai.retry.multiplier:2}")
|
||||
)
|
||||
public ModerationResponse moderate(String text) {
|
||||
log.info("Calling AI TextModeration service");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.ai.config;
|
||||
|
||||
import io.netty.channel.ChannelOption;
|
||||
import java.time.Duration;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import reactor.netty.http.client.HttpClient;
|
||||
@@ -14,11 +15,15 @@ import org.springframework.web.reactive.function.client.WebClient;
|
||||
@EnableConfigurationProperties(AiProperties.class)
|
||||
public class WebClientConfig {
|
||||
|
||||
private static final int CONNECT_TIMEOUT_MILLIS = 3_000;
|
||||
|
||||
@Bean
|
||||
public WebClient aiWebClient(AiProperties properties) {
|
||||
log.info("aiWebClient get for properties {}", properties);
|
||||
HttpClient httpClient =
|
||||
HttpClient.create()
|
||||
// Без явного таймаута соединения недоступный хост держал поток модерации ~30 с на попытку
|
||||
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT_MILLIS)
|
||||
.responseTimeout(
|
||||
Duration.ofSeconds(properties.getTimeout())
|
||||
);
|
||||
|
||||
@@ -27,7 +27,8 @@ public class TextModerationProcessor implements ModerationProcessor {
|
||||
|
||||
@Override
|
||||
public Boolean process(ModerationContext context) {
|
||||
log.info("process TextModerationProcessor for context {}", context);
|
||||
// Весь контекст (текст поста, файлы) в лог не пишем — только размер
|
||||
log.debug("process TextModerationProcessor: images={}", context.getImages() == null ? 0 : context.getImages().size());
|
||||
String text = buildText(
|
||||
context.getTitle(),
|
||||
context.getDescription()
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.krylov.refound.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.connection.Message;
|
||||
import org.springframework.data.redis.connection.MessageListener;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Рассылка STOMP-сообщений во все экземпляры приложения.
|
||||
*
|
||||
* <p>WebSocket-брокер (simple broker) живёт в памяти процесса: подписчики,
|
||||
* подключённые к другому экземпляру, сообщение не получили бы. Поэтому событие
|
||||
* публикуется в канал Redis {@value #CHANNEL}, каждый экземпляр (включая
|
||||
* отправителя) получает его и отдаёт своему локальному брокеру — а тот своим
|
||||
* подписчикам. Права на подписку по-прежнему проверяет WsStompInterceptor в
|
||||
* том экземпляре, где подключён клиент.
|
||||
*
|
||||
* <p>Если Redis недоступен, сообщение доставляется хотя бы локально.
|
||||
* Включается свойством {@code app.websocket.cluster-broadcast} (по умолчанию да).
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ClusterMessaging implements MessageListener {
|
||||
|
||||
public static final String CHANNEL = "ws:broadcast";
|
||||
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final boolean clusterBroadcast;
|
||||
|
||||
public ClusterMessaging(SimpMessagingTemplate messagingTemplate, StringRedisTemplate redisTemplate,
|
||||
ObjectMapper objectMapper, @Value("${app.websocket.cluster-broadcast:true}") boolean clusterBroadcast) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.objectMapper = objectMapper;
|
||||
this.clusterBroadcast = clusterBroadcast;
|
||||
}
|
||||
|
||||
record Envelope(String destination, JsonNode payload) {
|
||||
}
|
||||
|
||||
/** Отправляет сообщение подписчикам destination во всех экземплярах. */
|
||||
public void convertAndSend(String destination, Object payload) {
|
||||
if (!clusterBroadcast) {
|
||||
messagingTemplate.convertAndSend(destination, payload);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String json = objectMapper.writeValueAsString(new Envelope(destination, objectMapper.valueToTree(payload)));
|
||||
redisTemplate.convertAndSend(CHANNEL, json);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось опубликовать WS-сообщение в Redis ({}), доставляем локально: {}",
|
||||
destination, e.getMessage());
|
||||
messagingTemplate.convertAndSend(destination, payload);
|
||||
}
|
||||
}
|
||||
|
||||
/** Сообщение из канала Redis — от этого или другого экземпляра. */
|
||||
@Override
|
||||
public void onMessage(Message message, byte[] pattern) {
|
||||
try {
|
||||
Envelope envelope = objectMapper.readValue(new String(message.getBody(), StandardCharsets.UTF_8), Envelope.class);
|
||||
if (envelope.destination() == null) {
|
||||
return;
|
||||
}
|
||||
messagingTemplate.convertAndSend(envelope.destination(), envelope.payload());
|
||||
} catch (Exception e) {
|
||||
log.warn("Некорректное WS-сообщение из Redis: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isClusterBroadcast() {
|
||||
return clusterBroadcast;
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,16 @@ package com.krylov.refound.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.krylov.refound.dto.CachedMapMarkers;
|
||||
import com.krylov.refound.dto.CachedPostPage;
|
||||
import com.krylov.refound.dto.MapMarkerDto;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.listener.ChannelTopic;
|
||||
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@@ -21,11 +23,6 @@ public class RedisConfig {
|
||||
return buildTemplate(connectionFactory, objectMapper, CachedPostPage.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, CachedMapMarkers> feedRedisTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper) {
|
||||
return buildTemplate(connectionFactory, objectMapper, CachedMapMarkers.class);
|
||||
}
|
||||
|
||||
private static <T> RedisTemplate<String, T> buildTemplate(RedisConnectionFactory connectionFactory, ObjectMapper objectMapper, Class<T> type) {
|
||||
// Своя копия: изменения веб-настроек ObjectMapper не должны ломать формат кэша,
|
||||
// а неизвестные поля в старых записях не должны валить десериализацию
|
||||
@@ -60,4 +57,15 @@ public class RedisConfig {
|
||||
template.setValueSerializer(valueSerializer);
|
||||
return template;
|
||||
}
|
||||
}
|
||||
|
||||
/** Подписка на канал рассылки WebSocket-сообщений между экземплярами (см. ClusterMessaging). */
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "app.websocket.cluster-broadcast", havingValue = "true", matchIfMissing = true)
|
||||
public RedisMessageListenerContainer wsBroadcastListenerContainer(RedisConnectionFactory connectionFactory,
|
||||
ClusterMessaging clusterMessaging) {
|
||||
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
|
||||
container.setConnectionFactory(connectionFactory);
|
||||
container.addMessageListener(clusterMessaging, new ChannelTopic(ClusterMessaging.CHANNEL));
|
||||
return container;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.krylov.refound.config;
|
||||
|
||||
import net.javacrumbs.shedlock.core.LockProvider;
|
||||
import net.javacrumbs.shedlock.provider.redis.spring.RedisLockProvider;
|
||||
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
|
||||
/**
|
||||
* Распределённая блокировка фоновых задач (ShedLock). Приложение может работать
|
||||
* в нескольких экземплярах: без блокировки ночная чистка и модерация запускались
|
||||
* бы в каждом из них одновременно. Задача с {@code @SchedulerLock} выполняется
|
||||
* тем экземпляром, который первым взял блокировку в Redis
|
||||
* ({@code job-lock:refound:<имя задачи>}); остальные пропускают запуск.
|
||||
*
|
||||
* <p>Если Redis недоступен, блокировку взять нельзя и задача пропускается до
|
||||
* следующего запуска — это безопаснее, чем выполнить её во всех экземплярах.
|
||||
*/
|
||||
@Configuration
|
||||
@EnableSchedulerLock(defaultLockAtMostFor = "PT10M")
|
||||
public class SchedulerLockConfig {
|
||||
|
||||
static final String LOCK_ENVIRONMENT = "refound";
|
||||
|
||||
@Bean
|
||||
public LockProvider lockProvider(RedisConnectionFactory connectionFactory) {
|
||||
return new RedisLockProvider(connectionFactory, LOCK_ENVIRONMENT);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ public class FileStorageController {
|
||||
* Вместе с кэшем ссылки (12ч) укладывается в её срок жизни (24ч).
|
||||
*/
|
||||
private static final Duration REDIRECT_CACHE_MAX_AGE = Duration.ofHours(6);
|
||||
private static final long MAX_PRESIGNED_TTL_HOURS = 7 * 24;
|
||||
|
||||
private final FileStorageService fileStorageService;
|
||||
|
||||
@@ -68,7 +69,8 @@ public class FileStorageController {
|
||||
@GetMapping("/url/{*objectName}")
|
||||
public ResponseEntity<Map<String, String>> getPresignedUrl(@PathVariable String objectName, @RequestParam(value = "ttlHours", required = false, defaultValue = "24") long ttlHours) {
|
||||
String key = objectName.startsWith("/") ? objectName.substring(1) : objectName;
|
||||
Duration ttl = ttlHours > 0 ? Duration.ofHours(ttlHours) : Duration.ofHours(24);
|
||||
// SigV4 не подписывает ссылки дольше 7 дней: больший ttlHours ронял presigner с 500
|
||||
Duration ttl = ttlHours > 0 ? Duration.ofHours(Math.min(ttlHours, MAX_PRESIGNED_TTL_HOURS)) : Duration.ofHours(24);
|
||||
String url = fileStorageService.generatePresignedDownloadUrl(key, ttl);
|
||||
return ResponseEntity.ok(Map.of("url", url));
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.search.PostFeedFilter;
|
||||
import com.krylov.refound.search.SearchSuggestService;
|
||||
import com.krylov.refound.service.PostService;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -40,8 +41,8 @@ public class PostController {
|
||||
private final SearchSuggestService searchSuggestService;
|
||||
|
||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
||||
log.info("create post {}", request.toString());
|
||||
public PostRequest create(@Valid @ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
||||
log.info("create post type={}, title='{}'", request.getType(), request.getTitle());
|
||||
return service.create(request, images);
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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,13 +29,12 @@ 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")
|
||||
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()) {
|
||||
// Нормальная ситуация (нет активных реклам / кулдаун / кап) — не ошибка
|
||||
@@ -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.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());
|
||||
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.info("registerClick");
|
||||
advertisingClickService.recordClick(request.advertisingId(), authentication, request.sessionId());
|
||||
log.debug("registerClick");
|
||||
advertisingTrackingService.recordClick(request.advertisingId(), authentication, request.sessionId(),
|
||||
request.token());
|
||||
return ResponseEntity.accepted().build();
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,12 @@ package com.krylov.refound.controller.advertising;
|
||||
import com.krylov.refound.service.advertising.AdvertisingMediaService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@@ -23,9 +26,10 @@ public class AdvertisingMediaController {
|
||||
private final AdvertisingMediaService mediaService;
|
||||
|
||||
@GetMapping("/{*key}")
|
||||
public ResponseEntity<byte[]> getMedia(@PathVariable String key) {
|
||||
public ResponseEntity<Resource> getMedia(@PathVariable String key,
|
||||
@RequestHeader(value = HttpHeaders.RANGE, required = false) String range) {
|
||||
String mediaKey = key.startsWith("/") ? key.substring(1) : key;
|
||||
log.info("GET ads-media: key={} -> mediaKey={}", key, mediaKey);
|
||||
return mediaService.downloadMedia(mediaKey);
|
||||
log.debug("GET ads-media: key={} -> mediaKey={}, range={}", key, mediaKey, range);
|
||||
return mediaService.downloadMedia(mediaKey, range);
|
||||
}
|
||||
}
|
||||
@@ -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')")
|
||||
|
||||
@@ -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,14 +0,0 @@
|
||||
package com.krylov.refound.dto;
|
||||
|
||||
import java.util.List;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CachedMapMarkers {
|
||||
|
||||
private List<MapMarkerDto> content;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
) {
|
||||
}
|
||||
@@ -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
|
||||
) {
|
||||
|
||||
|
||||
@@ -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
|
||||
) {
|
||||
}
|
||||
@@ -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
|
||||
) {
|
||||
}
|
||||
@@ -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
|
||||
) {
|
||||
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.dto.user;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.krylov.refound.enums.Role;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
@@ -15,4 +16,13 @@ public class UserResponseDto {
|
||||
private String email;
|
||||
private String avatar;
|
||||
private Role role;
|
||||
|
||||
/**
|
||||
* Новая пара токенов — только в ответе PUT /api/v1/users/{id}, когда пользователь
|
||||
* сменил свой логин (логин — subject JWT, прежние токены больше не подходят).
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private String token;
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private String refreshToken;
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
@@ -28,7 +26,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)
|
||||
@@ -44,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) {
|
||||
|
||||
@@ -8,5 +8,6 @@ public enum ErrorCode {
|
||||
UNAUTHORIZED,
|
||||
FORBIDDEN,
|
||||
CONTENT_BLOCKED,
|
||||
INVALID_STATUS_TRANSITION
|
||||
INVALID_STATUS_TRANSITION,
|
||||
TOO_MANY_REQUESTS
|
||||
}
|
||||
|
||||
@@ -3,15 +3,23 @@ package com.krylov.refound.exception;
|
||||
import com.krylov.refound.ai.exception.ContentBlockedException;
|
||||
import com.krylov.refound.dto.ModerationErrorDetails;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
|
||||
@RestControllerAdvice
|
||||
@Slf4j
|
||||
@@ -44,8 +52,74 @@ public class GlobalExceptionHandler {
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ошибки привязки параметров (@Valid на @ModelAttribute, неверный тип в query/path).
|
||||
* MethodArgumentNotValidException обрабатывается выше и сюда не попадает.
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBind(BindException ex, HttpServletRequest request) {
|
||||
String message = ex.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.findFirst()
|
||||
.map(e -> e.getField() + " " + e.getDefaultMessage())
|
||||
.orElse("Validation error");
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
@ExceptionHandler({MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
|
||||
public ResponseEntity<ErrorResponse> handleBadInput(Exception ex, HttpServletRequest request) {
|
||||
log.debug("Bad request {}: {}", request.getRequestURI(), ex.getMessage());
|
||||
String message = ex instanceof MethodArgumentTypeMismatchException mismatch
|
||||
? "Некорректное значение параметра " + mismatch.getName()
|
||||
: "Некорректное тело запроса";
|
||||
return buildResponse(HttpStatus.BAD_REQUEST, ErrorCode.VALIDATION_ERROR, message, request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MaxUploadSizeExceededException.class)
|
||||
public ResponseEntity<ErrorResponse> handleMaxUploadSize(MaxUploadSizeExceededException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.PAYLOAD_TOO_LARGE, ErrorCode.VALIDATION_ERROR,
|
||||
"Файл или запрос слишком большой", request);
|
||||
}
|
||||
|
||||
/**
|
||||
* @PreAuthorize бросает AccessDeniedException внутри контроллера — без этого
|
||||
* обработчика её перехватывал handleUnknown и отвечал 500 вместо 403.
|
||||
*/
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAccessDenied(AccessDeniedException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.FORBIDDEN, ErrorCode.FORBIDDEN, "Forbidden", request);
|
||||
}
|
||||
|
||||
/** BadCredentialsException из /auth/refresh и т.п. — это 401, а не 500. */
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleAuthentication(AuthenticationException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.UNAUTHORIZED, ErrorCode.UNAUTHORIZED, ex.getMessage(), request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(EntityNotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleEntityNotFound(EntityNotFoundException ex, HttpServletRequest request) {
|
||||
return buildResponse(HttpStatus.NOT_FOUND, ErrorCode.NOT_FOUND, ex.getMessage(), request);
|
||||
}
|
||||
|
||||
/** Гонка на уникальных ключах (повторная регистрация, двойной клик «в избранное»). */
|
||||
@ExceptionHandler(DataIntegrityViolationException.class)
|
||||
public ResponseEntity<ErrorResponse> handleDataIntegrity(DataIntegrityViolationException ex, HttpServletRequest request) {
|
||||
log.warn("Data integrity violation on {}: {}", request.getRequestURI(), ex.getMostSpecificCause().getMessage());
|
||||
return buildResponse(HttpStatus.CONFLICT, ErrorCode.BAD_REQUEST, "Конфликт данных, повторите запрос", request);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleUnknown(Exception ex, HttpServletRequest request) {
|
||||
// Исключения Spring MVC (404 без маршрута, 405, 415, пропущенный параметр и т.п.)
|
||||
// сами знают свой HTTP-статус — без этой ветки они превращались в 500
|
||||
if (ex instanceof org.springframework.web.ErrorResponse springError) {
|
||||
HttpStatus status = HttpStatus.resolve(springError.getStatusCode().value());
|
||||
if (status != null && !status.is5xxServerError()) {
|
||||
return buildResponse(status, status == HttpStatus.NOT_FOUND ? ErrorCode.NOT_FOUND : ErrorCode.BAD_REQUEST,
|
||||
springError.getBody().getDetail(), request);
|
||||
}
|
||||
}
|
||||
log.error("Unexpected error", ex);
|
||||
|
||||
return buildResponse(
|
||||
|
||||
@@ -29,6 +29,9 @@ import java.util.List;
|
||||
@RequiredArgsConstructor
|
||||
public class StorageStructureService {
|
||||
|
||||
/** Сколько хранится удалённый (неактуальный) вариант файла — шанс восстановить ошибочно удалённое. */
|
||||
private static final int NONCURRENT_VERSION_DAYS = 30;
|
||||
|
||||
private final S3Client s3Client;
|
||||
private final MinioProperties properties;
|
||||
|
||||
@@ -70,12 +73,17 @@ public class StorageStructureService {
|
||||
try {
|
||||
log.info("Установка политики жизненного цикла для бакета '{}'...", mainBucket);
|
||||
|
||||
// Текущие версии файлов не истекают: правило "удалять всё старше 180 дней"
|
||||
// стирало аватары и картинки живых объявлений. Файлы удаляет само приложение
|
||||
// (удаление поста/аватара, ночная чистка постов); при версионировании от них
|
||||
// остаются неактуальные версии — их и убирает это правило. Id прежний, чтобы
|
||||
// конфигурация бакета перезаписалась при старте.
|
||||
LifecycleRule rule = LifecycleRule.builder()
|
||||
.id("delete-after-180-days-rule")
|
||||
.status(ExpirationStatus.ENABLED)
|
||||
.filter(f -> f.prefix(""))
|
||||
.expiration(exp -> exp.days(180))
|
||||
.noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(180))
|
||||
.noncurrentVersionExpiration(ncv -> ncv.noncurrentDays(NONCURRENT_VERSION_DAYS))
|
||||
.expiration(exp -> exp.expiredObjectDeleteMarker(true))
|
||||
.build();
|
||||
|
||||
BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder()
|
||||
|
||||
@@ -21,7 +21,8 @@ public interface PostMapper {
|
||||
@Mapping(source = "user.id", target = "userId")
|
||||
@Mapping(source = "user.login", target = "userEmail")
|
||||
@Mapping(source = "images", target = "images", qualifiedByName = "imagesToUrls")
|
||||
@Mapping(target = "category", expression = "java(post.getCategory().getDisplayName())")
|
||||
// Категория необязательна: без проверки на null пост без категории ронял ленту с 500
|
||||
@Mapping(target = "category", expression = "java(post.getCategory() == null ? null : post.getCategory().getDisplayName())")
|
||||
@Mapping(source = "isReward", target = "reward")
|
||||
@Mapping(source = "reward", target = "rewardText")
|
||||
@Mapping(source = "rulesAccepted", target = "rulesAccepted", qualifiedByName = "booleanToString")
|
||||
|
||||
105
src/main/java/com/krylov/refound/ratelimit/RateLimitFilter.java
Normal file
105
src/main/java/com/krylov/refound/ratelimit/RateLimitFilter.java
Normal file
@@ -0,0 +1,105 @@
|
||||
package com.krylov.refound.ratelimit;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.server.PathContainer;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.web.util.pattern.PathPattern;
|
||||
import org.springframework.web.util.pattern.PathPatternParser;
|
||||
|
||||
/**
|
||||
* Ограничение частоты запросов по IP для уязвимых маршрутов: вход и регистрация
|
||||
* (перебор паролей, спам аккаунтами), публичный трекинг рекламы (накрутка),
|
||||
* загрузка файлов и создание объявлений. Правила — {@code rate-limit.rules}.
|
||||
*
|
||||
* <p>IP берётся из {@code request.getRemoteAddr()}; за обратным прокси он
|
||||
* восстанавливается из X-Forwarded-For (server.forward-headers-strategy=native).
|
||||
* При превышении — 429 с заголовком Retry-After в формате ErrorResponse.
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RateLimitFilter extends OncePerRequestFilter {
|
||||
|
||||
private final RedisRateLimiter rateLimiter;
|
||||
private final RateLimitProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final List<CompiledRule> rules;
|
||||
|
||||
record CompiledRule(RateLimitProperties.Rule rule, List<PathPattern> patterns) {
|
||||
|
||||
boolean matches(HttpServletRequest request, PathContainer path) {
|
||||
String method = rule.getMethod();
|
||||
if (method != null && !method.isBlank() && !method.equalsIgnoreCase(request.getMethod())) {
|
||||
return false;
|
||||
}
|
||||
return patterns.stream().anyMatch(pattern -> pattern.matches(path));
|
||||
}
|
||||
}
|
||||
|
||||
public RateLimitFilter(RedisRateLimiter rateLimiter, RateLimitProperties properties, ObjectMapper objectMapper) {
|
||||
this.rateLimiter = rateLimiter;
|
||||
this.properties = properties;
|
||||
this.objectMapper = objectMapper;
|
||||
PathPatternParser parser = new PathPatternParser();
|
||||
this.rules = properties.getRules().stream()
|
||||
.map(rule -> new CompiledRule(rule, rule.getPaths().stream().map(parser::parse).toList()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !properties.isEnabled() || rules.isEmpty();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
PathContainer path = PathContainer.parsePath(request.getRequestURI().substring(request.getContextPath().length()));
|
||||
String clientIp = request.getRemoteAddr();
|
||||
|
||||
for (CompiledRule compiled : rules) {
|
||||
if (!compiled.matches(request, path)) {
|
||||
continue;
|
||||
}
|
||||
RateLimitProperties.Rule rule = compiled.rule();
|
||||
RedisRateLimiter.Decision decision = rateLimiter.hit(rule.getName(), clientIp, rule.getLimit(), rule.getWindow());
|
||||
if (!decision.allowed()) {
|
||||
log.warn("Rate limit '{}' превышен: ip={}, {} {}", rule.getName(), clientIp, request.getMethod(),
|
||||
request.getRequestURI());
|
||||
writeTooManyRequests(request, response, decision.retryAfterSeconds());
|
||||
return;
|
||||
}
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private void writeTooManyRequests(HttpServletRequest request, HttpServletResponse response, long retryAfter)
|
||||
throws IOException {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("timestamp", LocalDateTime.now());
|
||||
body.put("status", HttpStatus.TOO_MANY_REQUESTS.value());
|
||||
body.put("error", ErrorCode.TOO_MANY_REQUESTS.name());
|
||||
body.put("message", "Слишком много запросов, повторите позже");
|
||||
body.put("path", request.getRequestURI());
|
||||
|
||||
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
|
||||
response.setHeader(HttpHeaders.RETRY_AFTER, Long.toString(retryAfter));
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
objectMapper.writeValue(response.getWriter(), body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.krylov.refound.ratelimit;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* Лимиты запросов ({@code rate-limit.*} в application.yaml). Счётчики лежат в
|
||||
* Redis, поэтому лимит общий для всех экземпляров приложения.
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@ConfigurationProperties(prefix = "rate-limit")
|
||||
public class RateLimitProperties {
|
||||
|
||||
/** Выключатель всех лимитов (например, для нагрузочных тестов). */
|
||||
private boolean enabled = true;
|
||||
|
||||
/** Правила по маршрутам; ключ лимита — IP клиента. */
|
||||
private List<Rule> rules = new ArrayList<>();
|
||||
|
||||
/** Защита конкретного аккаунта от перебора пароля с разных IP. */
|
||||
private Login login = new Login();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Rule {
|
||||
/** Имя правила — часть ключа в Redis. */
|
||||
private String name;
|
||||
/** HTTP-метод; пусто — любой. */
|
||||
private String method;
|
||||
/** Шаблоны путей в стиле Spring MVC ({@code /api/v1/auth/login}, {@code /api/ads/**}). */
|
||||
private List<String> paths = new ArrayList<>();
|
||||
/** Сколько запросов разрешено за окно. */
|
||||
private int limit;
|
||||
private Duration window = Duration.ofMinutes(1);
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class Login {
|
||||
/** Сколько неудачных входов в один аккаунт допускается за окно. */
|
||||
private int maxFailures = 10;
|
||||
private Duration window = Duration.ofMinutes(15);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.krylov.refound.ratelimit;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
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.Component;
|
||||
|
||||
/**
|
||||
* Счётчик с фиксированным окном в Redis: ключ {@code rl:<правило>:<субъект>:<номер окна>},
|
||||
* INCR и EXPIRE выполняются одним Lua-скриптом (атомарно, без «вечных» ключей).
|
||||
*
|
||||
* <p>Лимиты — защитный слой, а не бизнес-логика: при недоступном Redis запрос
|
||||
* пропускается (fail-open), чтобы сбой кэша не положил весь API.
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class RedisRateLimiter {
|
||||
|
||||
private static final RedisScript<Long> INCREMENT = 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;
|
||||
|
||||
public RedisRateLimiter(StringRedisTemplate redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
/** Результат проверки: разрешён ли запрос и через сколько секунд откроется окно. */
|
||||
public record Decision(boolean allowed, long count, long retryAfterSeconds) {
|
||||
|
||||
static Decision allow() {
|
||||
return new Decision(true, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Учитывает запрос и решает, укладывается ли он в лимит. */
|
||||
public Decision hit(String rule, String subject, int limit, Duration window) {
|
||||
long windowMillis = window.toMillis();
|
||||
long now = System.currentTimeMillis();
|
||||
long windowIndex = now / windowMillis;
|
||||
String key = "rl:" + rule + ":" + subject + ":" + windowIndex;
|
||||
try {
|
||||
Long count = redisTemplate.execute(INCREMENT, List.of(key), Long.toString(windowMillis));
|
||||
if (count == null) {
|
||||
return Decision.allow();
|
||||
}
|
||||
long retryAfter = Math.max(1, ((windowIndex + 1) * windowMillis - now + 999) / 1000);
|
||||
return new Decision(count <= limit, count, retryAfter);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Rate limit '{}' не проверен, Redis недоступен: {}", rule, e.getMessage());
|
||||
return Decision.allow();
|
||||
}
|
||||
}
|
||||
|
||||
/** Сбрасывает текущее окно (например, после успешного входа). */
|
||||
public void reset(String rule, String subject, Duration window) {
|
||||
long windowIndex = System.currentTimeMillis() / window.toMillis();
|
||||
try {
|
||||
redisTemplate.delete("rl:" + rule + ":" + subject + ":" + windowIndex);
|
||||
} catch (RuntimeException e) {
|
||||
log.debug("Rate limit '{}' не сброшен: {}", rule, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Текущее значение счётчика без увеличения (0, если ключа нет или Redis недоступен). */
|
||||
public long current(String rule, String subject, Duration window) {
|
||||
long windowIndex = System.currentTimeMillis() / window.toMillis();
|
||||
try {
|
||||
String value = redisTemplate.opsForValue().get("rl:" + rule + ":" + subject + ":" + windowIndex);
|
||||
return value == null ? 0 : Long.parseLong(value);
|
||||
} catch (RuntimeException e) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.Chat;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
@@ -30,6 +31,6 @@ public interface ChatRepository extends JpaRepository<Chat, Long> {
|
||||
* У posts нет ON DELETE CASCADE, поэтому без этого удаление падало бы с 500.
|
||||
*/
|
||||
@Modifying
|
||||
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId = :postId")
|
||||
int clearPostReference(@Param("postId") Long postId);
|
||||
@Query("UPDATE Chat c SET c.postId = NULL WHERE c.postId IN :postIds")
|
||||
int clearPostReferences(@Param("postIds") Collection<Long> postIds);
|
||||
}
|
||||
|
||||
@@ -15,4 +15,8 @@ public interface ImageRepository extends JpaRepository<Image, Long> {
|
||||
/** Один запрос вместо N+1 при сборке админской страницы объявлений. */
|
||||
@Query("select i from Image i where i.post.id in :postIds order by i.id asc")
|
||||
List<Image> findByPostIdIn(@Param("postIds") Collection<Long> postIds);
|
||||
|
||||
/** Все ключи картинок объявлений — для чистки файлов-сирот. */
|
||||
@Query("select i.url from Image i where i.url is not null")
|
||||
List<String> findAllUrls();
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.Message;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.domain.Page;
|
||||
@@ -14,7 +15,18 @@ public interface MessageRepository extends JpaRepository<Message, Long> {
|
||||
|
||||
Page<Message> findByChatIdOrderByCreatedAtDesc(Long chatId, Pageable pageable);
|
||||
|
||||
Optional<Message> findFirstByChatIdOrderByCreatedAtDesc(Long chatId);
|
||||
/**
|
||||
* Последнее сообщение каждого чата. «Последнее» — по id: createdAt пишется в
|
||||
* часовом поясе отправителя, и у собеседников из разных поясов не монотонен.
|
||||
*/
|
||||
@Query("SELECT m FROM Message m WHERE m.id IN "
|
||||
+ "(SELECT MAX(m2.id) FROM Message m2 WHERE m2.chatId IN :chatIds GROUP BY m2.chatId)")
|
||||
List<Message> findLastMessages(@Param("chatIds") Collection<Long> chatIds);
|
||||
|
||||
/** Непрочитанные сообщения от собеседника по каждому чату: строки (chatId, count). */
|
||||
@Query("SELECT m.chatId, COUNT(m) FROM Message m WHERE m.chatId IN :chatIds "
|
||||
+ "AND m.isRead = false AND m.senderId <> :userId GROUP BY m.chatId")
|
||||
List<Object[]> countUnreadByChat(@Param("chatIds") Collection<Long> chatIds, @Param("userId") Long userId);
|
||||
|
||||
long countByChatIdAndIsReadFalseAndSenderIdNot(Long chatId, Long userId);
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -2,7 +2,18 @@ package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.Statistics;
|
||||
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 StatisticsRepository extends JpaRepository<Statistics, Long> {
|
||||
|
||||
/** Атомарный инкремент: read-modify-write в Java терял обновления при параллельных запросах. */
|
||||
@Modifying
|
||||
@Query("update Statistics s set s.postsCreated = s.postsCreated + 1 where s.id = :id")
|
||||
int incrementCreated(@Param("id") Long id);
|
||||
|
||||
@Modifying
|
||||
@Query("update Statistics s set s.postsFound = s.postsFound + 1 where s.id = :id")
|
||||
int incrementFound(@Param("id") Long id);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.krylov.refound.repository;
|
||||
|
||||
import com.krylov.refound.entity.User;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
@@ -13,4 +14,8 @@ public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
@Query("SELECT u.id FROM User u WHERE u.login = :login")
|
||||
Optional<Long> findUserByLogin(@Param("login") String login);
|
||||
|
||||
/** Все ключи аватаров — для чистки файлов-сирот. */
|
||||
@Query("SELECT u.avatarUrl FROM User u WHERE u.avatarUrl IS NOT NULL")
|
||||
List<String> findAllAvatarUrls();
|
||||
}
|
||||
|
||||
@@ -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("""
|
||||
|
||||
@@ -2,22 +2,22 @@ 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.JpaRepository;
|
||||
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> {
|
||||
|
||||
@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();
|
||||
|
||||
/** Завершает кампании, у которых закончилось окно показа. */
|
||||
@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);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.util.concurrent.atomic.LongAdder;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
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;
|
||||
@@ -97,6 +98,8 @@ public class SearchSuggestService {
|
||||
|
||||
@Scheduled(initialDelayString = "${search.suggest.initial-delay:PT10S}",
|
||||
fixedDelayString = "${search.suggest.refresh-interval:PT10M}")
|
||||
// Словарь общий (таблица search_words) — пересобирает один экземпляр
|
||||
@SchedulerLock(name = "rebuildSearchDictionary", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S")
|
||||
@Transactional
|
||||
public void rebuildDictionary() {
|
||||
long start = System.currentTimeMillis();
|
||||
|
||||
@@ -5,7 +5,6 @@ import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -37,7 +36,7 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
final String token = authHeader.substring(7);
|
||||
|
||||
try {
|
||||
if (jwtService.isTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
if (jwtService.isAccessTokenValid(token) && SecurityContextHolder.getContext().getAuthentication() == null) {
|
||||
String login = jwtService.extractLogin(token);
|
||||
String role = jwtService.extractRole(token);
|
||||
|
||||
|
||||
@@ -16,6 +16,13 @@ import org.springframework.stereotype.Service;
|
||||
public class JwtService {
|
||||
|
||||
private static final String ROLE_CLAIM = "role";
|
||||
/**
|
||||
* Тип токена. Access- и refresh-токены подписаны одним ключом, поэтому без
|
||||
* этого claim долгоживущий refresh-токен принимался бы как access-токен.
|
||||
*/
|
||||
private static final String TYPE_CLAIM = "typ";
|
||||
private static final String ACCESS_TYPE = "access";
|
||||
private static final String REFRESH_TYPE = "refresh";
|
||||
|
||||
@Value("${jwt.secret}")
|
||||
private String secret;
|
||||
@@ -29,6 +36,7 @@ public class JwtService {
|
||||
public String generateAccessToken(String login, String role) {
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(ROLE_CLAIM, role);
|
||||
claims.put(TYPE_CLAIM, ACCESS_TYPE);
|
||||
return buildToken(claims, login, accessExpiration);
|
||||
}
|
||||
|
||||
@@ -37,7 +45,9 @@ public class JwtService {
|
||||
* чтобы получить новый access-токен, а не для прямого доступа к API.
|
||||
*/
|
||||
public String generateRefreshToken(String login) {
|
||||
return buildToken(new HashMap<>(), login, refreshExpiration);
|
||||
Map<String, Object> claims = new HashMap<>();
|
||||
claims.put(TYPE_CLAIM, REFRESH_TYPE);
|
||||
return buildToken(claims, login, refreshExpiration);
|
||||
}
|
||||
|
||||
public long getRefreshExpirationMillis() {
|
||||
@@ -62,21 +72,35 @@ public class JwtService {
|
||||
return extractClaim(token, claims -> claims.get(ROLE_CLAIM, String.class));
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token) {
|
||||
/**
|
||||
* Токен годится для доступа к API (HTTP и WebSocket). Токены, выданные до
|
||||
* появления claim "typ", различаем по роли: она есть только у access-токена.
|
||||
*/
|
||||
public boolean isAccessTokenValid(String token) {
|
||||
try {
|
||||
String login = extractLogin(token);
|
||||
return login != null && !isTokenExpired(token);
|
||||
Claims claims = extractAllClaims(token);
|
||||
if (claims.getSubject() == null || claims.getExpiration().before(new Date())) {
|
||||
return false;
|
||||
}
|
||||
String type = claims.get(TYPE_CLAIM, String.class);
|
||||
return type == null ? claims.get(ROLE_CLAIM) != null : ACCESS_TYPE.equals(type);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
private Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
/** Токен годится только для обмена на новую пару в /auth/refresh. */
|
||||
public boolean isRefreshTokenValid(String token) {
|
||||
try {
|
||||
Claims claims = extractAllClaims(token);
|
||||
if (claims.getSubject() == null || claims.getExpiration().before(new Date())) {
|
||||
return false;
|
||||
}
|
||||
String type = claims.get(TYPE_CLAIM, String.class);
|
||||
return type == null ? claims.get(ROLE_CLAIM) == null : REFRESH_TYPE.equals(type);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
|
||||
@@ -49,11 +49,12 @@ public class SecurityConfig {
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
// публичные эндпоинты
|
||||
.requestMatchers("/api/v1/auth/**").permitAll()
|
||||
// health-пробы балансировщика/оркестратора (без деталей состояния)
|
||||
.requestMatchers(HttpMethod.GET, "/actuator/health", "/actuator/health/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/files/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/ads-media/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/posts/**").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/v1/reviews/**").permitAll()
|
||||
.requestMatchers("/files/**", "/uploads/**").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll() // авторизация чата — на уровне STOMP CONNECT interceptor, см. заметку ниже
|
||||
|
||||
// изменяющие операции — только для авторизованных
|
||||
@@ -69,7 +70,6 @@ public class SecurityConfig {
|
||||
// реклама
|
||||
.requestMatchers(HttpMethod.GET, "/api/ads/next").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/ads/impression").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/ads/impression/beacon").permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/ads/click").permitAll()
|
||||
.requestMatchers(HttpMethod.GET, "/api/fullscreen-ad").permitAll()
|
||||
|
||||
|
||||
@@ -8,27 +8,43 @@ import com.krylov.refound.dto.RegisterRequest;
|
||||
import com.krylov.refound.dto.user.UserDto;
|
||||
import com.krylov.refound.dto.user.UserRegisterDto;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.exception.InvalidCredentialsException;
|
||||
import com.krylov.refound.exception.LoginAlreadyExistsException;
|
||||
import com.krylov.refound.ratelimit.RateLimitProperties;
|
||||
import com.krylov.refound.ratelimit.RedisRateLimiter;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import com.krylov.refound.security.JwtService;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthService {
|
||||
|
||||
private static final int MAX_LOGIN_LENGTH = 255;
|
||||
/** Минимум по рекомендациям NIST SP 800-63B для паролей, выбранных пользователем. */
|
||||
private static final int MIN_PASSWORD_LENGTH = 8;
|
||||
private static final String LOGIN_FAILURES_RULE = "login-failures";
|
||||
private static final int MAX_PASSWORD_BYTES = 72;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtService jwtService;
|
||||
private final RefreshTokenService refreshTokenService;
|
||||
private final RedisRateLimiter rateLimiter;
|
||||
private final RateLimitProperties rateLimitProperties;
|
||||
|
||||
public UserRegisterDto registerUser(RegisterRequest request) {
|
||||
validateRegistration(request);
|
||||
if (userRepository.findByLogin(request.getLogin()).isPresent()) {
|
||||
log.warn("registration failed: login {} already taken", request.getLogin());
|
||||
throw new LoginAlreadyExistsException("Логин уже занят");
|
||||
@@ -42,23 +58,35 @@ public class AuthService {
|
||||
|
||||
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String refreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", refreshToken);
|
||||
UserDto userDto = getUserDto(user);
|
||||
|
||||
return new UserRegisterDto(userDto, accessToken, refreshToken);
|
||||
}
|
||||
|
||||
public UserRegisterDto loginUser(AuthRequest request) {
|
||||
User user = userRepository.findByLogin(request.getLogin()).orElse(null);
|
||||
String login = request.getLogin();
|
||||
// Перебор пароля одного аккаунта с разных IP: лимит по IP (RateLimitFilter) тут не спасает
|
||||
RateLimitProperties.Login loginLimit = rateLimitProperties.getLogin();
|
||||
if (login != null && rateLimitProperties.isEnabled()
|
||||
&& rateLimiter.current(LOGIN_FAILURES_RULE, login, loginLimit.getWindow()) >= loginLimit.getMaxFailures()) {
|
||||
log.warn("login blocked: too many failed attempts for {}", login);
|
||||
throw new ApiException(ErrorCode.TOO_MANY_REQUESTS,
|
||||
"Слишком много неудачных попыток входа, повторите позже", HttpStatus.TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
if (user == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
log.warn("login failed: login or password incorrect for {}", request.getLogin());
|
||||
User user = login == null ? null : userRepository.findByLogin(login).orElse(null);
|
||||
|
||||
if (user == null || request.getPassword() == null || !passwordEncoder.matches(request.getPassword(), user.getPassword())) {
|
||||
log.warn("login failed: login or password incorrect for {}", login);
|
||||
if (login != null) {
|
||||
rateLimiter.hit(LOGIN_FAILURES_RULE, login, loginLimit.getMaxFailures(), loginLimit.getWindow());
|
||||
}
|
||||
throw new InvalidCredentialsException("Неверный логин или пароль");
|
||||
}
|
||||
rateLimiter.reset(LOGIN_FAILURES_RULE, login, loginLimit.getWindow());
|
||||
|
||||
String accessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String refreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", refreshToken);
|
||||
UserDto userDto = getUserDto(user);
|
||||
|
||||
return new UserRegisterDto(userDto, accessToken, refreshToken);
|
||||
@@ -69,18 +97,15 @@ public class AuthService {
|
||||
}
|
||||
|
||||
public AuthResponse refresh(RefreshRequest request) {
|
||||
String login = refreshTokenService.validateAndGetLogin(request.getRefreshToken())
|
||||
// ротация: consume отзывает старый refresh-токен, выдаём новую пару
|
||||
String login = refreshTokenService.consume(request.getRefreshToken())
|
||||
.orElseThrow(() -> new BadCredentialsException("Invalid or expired refresh token"));
|
||||
|
||||
User user = userRepository.findByLogin(login)
|
||||
.orElseThrow(() -> new BadCredentialsException("User not found"));
|
||||
|
||||
// ротация: старый refresh-токен отзываем, выдаём новую пару
|
||||
refreshTokenService.revoke(request.getRefreshToken());
|
||||
|
||||
String newAccessToken = jwtService.generateAccessToken(user.getLogin(), user.getRole().name());
|
||||
String newRefreshToken = refreshTokenService.issue(user.getLogin());
|
||||
log.info("Refresh token returned = {}", newRefreshToken);
|
||||
return new AuthResponse(newAccessToken, newRefreshToken, getUserDto(user));
|
||||
}
|
||||
|
||||
@@ -88,6 +113,23 @@ public class AuthService {
|
||||
refreshTokenService.revoke(request.getRefreshToken());
|
||||
}
|
||||
|
||||
/**
|
||||
* Без проверки пустой логин сохранялся в БД, а null-пароль ронял BCrypt с 500.
|
||||
* Ответ при ошибке — тот же формат {"message"}, что и у занятого логина.
|
||||
*/
|
||||
private static void validateRegistration(RegisterRequest request) {
|
||||
if (!StringUtils.hasText(request.getLogin()) || request.getLogin().length() > MAX_LOGIN_LENGTH) {
|
||||
throw new InvalidCredentialsException("Логин не может быть пустым или длиннее " + MAX_LOGIN_LENGTH + " символов");
|
||||
}
|
||||
String password = request.getPassword();
|
||||
// BCrypt учитывает только первые 72 байта пароля
|
||||
if (password == null || password.length() < MIN_PASSWORD_LENGTH
|
||||
|| password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) {
|
||||
throw new InvalidCredentialsException("Пароль должен быть не короче " + MIN_PASSWORD_LENGTH
|
||||
+ " символов и не длиннее " + MAX_PASSWORD_BYTES + " байт");
|
||||
}
|
||||
}
|
||||
|
||||
private static UserDto getUserDto(User user) {
|
||||
return new UserDto(
|
||||
user.getId(),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import com.krylov.refound.dto.ChatDto;
|
||||
import com.krylov.refound.dto.ChatPostDto;
|
||||
import com.krylov.refound.dto.MessageDto;
|
||||
@@ -7,6 +8,7 @@ import com.krylov.refound.entity.Chat;
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Message;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
@@ -17,14 +19,16 @@ import java.time.LocalDateTime;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
@@ -40,7 +44,8 @@ public class ChatService {
|
||||
|
||||
private final ChatRepository chatRepository;
|
||||
private final MessageRepository messageRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
// Рассылка через Redis во все экземпляры: получатель может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
private final UserRepository userRepository;
|
||||
private final PostRepository postRepository;
|
||||
|
||||
@@ -103,10 +108,12 @@ public class ChatService {
|
||||
record ChatWithActivity(ChatDto dto, LocalDateTime lastActivity) {
|
||||
}
|
||||
|
||||
return chatRepository.findAllByUserId(userId).stream()
|
||||
.map(c -> {
|
||||
ChatDto dto = toDto(c, userId);
|
||||
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : c.getCreatedAt());
|
||||
List<Chat> chats = chatRepository.findAllByUserId(userId);
|
||||
Map<Long, Chat> byId = chats.stream().collect(Collectors.toMap(Chat::getId, Function.identity()));
|
||||
return toDtos(chats, userId).stream()
|
||||
.map(dto -> {
|
||||
LocalDateTime created = byId.get(dto.getId()).getCreatedAt();
|
||||
return new ChatWithActivity(dto, dto.getLastMessageAt() != null ? dto.getLastMessageAt() : created);
|
||||
})
|
||||
.sorted(Comparator.comparing(ChatWithActivity::lastActivity, Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.map(ChatWithActivity::dto)
|
||||
@@ -163,8 +170,8 @@ public class ChatService {
|
||||
// Рассылаем только после коммита: иначе клиент, получив событие и перезапросив
|
||||
// историю, мог не увидеть ещё не закоммиченное сообщение
|
||||
afterCommit(() -> {
|
||||
messagingTemplate.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
messagingTemplate.convertAndSend(
|
||||
messaging.convertAndSend("/topic/chat/" + chatId, dto);
|
||||
messaging.convertAndSend(
|
||||
"/topic/user/" + recipientId + "/unread",
|
||||
Map.of("chatId", chatId, "unreadCount", unreadCount)
|
||||
);
|
||||
@@ -223,40 +230,65 @@ public class ChatService {
|
||||
}
|
||||
|
||||
private ChatDto toDto(Chat chat, Long currentUserId) {
|
||||
Long otherUserId = chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||||
return toDtos(List.of(chat), currentUserId).get(0);
|
||||
}
|
||||
|
||||
ChatDto dto = new ChatDto();
|
||||
dto.setId(chat.getId());
|
||||
dto.setOtherUserId(otherUserId);
|
||||
dto.setPostId(chat.getPostId());
|
||||
/**
|
||||
* Собирает ChatDto для списка чатов фиксированным числом запросов (собеседники,
|
||||
* объявления, последние сообщения, непрочитанные), а не пятью запросами на чат.
|
||||
*/
|
||||
private List<ChatDto> toDtos(List<Chat> chats, Long currentUserId) {
|
||||
if (chats.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> chatIds = chats.stream().map(Chat::getId).toList();
|
||||
Map<Long, User> users = userRepository.findAllById(chats.stream()
|
||||
.map(chat -> otherUserId(chat, currentUserId)).distinct().toList()).stream()
|
||||
.collect(Collectors.toMap(User::getId, Function.identity()));
|
||||
Map<Long, Post> posts = postRepository.findAllById(chats.stream()
|
||||
.map(Chat::getPostId).filter(Objects::nonNull).distinct().toList()).stream()
|
||||
.collect(Collectors.toMap(Post::getId, Function.identity()));
|
||||
Map<Long, Message> lastMessages = messageRepository.findLastMessages(chatIds).stream()
|
||||
.collect(Collectors.toMap(Message::getChatId, Function.identity()));
|
||||
Map<Long, Long> unread = new HashMap<>();
|
||||
for (Object[] row : messageRepository.countUnreadByChat(chatIds, currentUserId)) {
|
||||
unread.put(((Number) row[0]).longValue(), ((Number) row[1]).longValue());
|
||||
}
|
||||
|
||||
userRepository.findById(otherUserId).ifPresent(user -> {
|
||||
dto.setOtherUserName(user.getName() + " " + user.getLastName());
|
||||
dto.setOtherUserAvatar(user.getAvatarUrl());
|
||||
});
|
||||
return chats.stream().map(chat -> {
|
||||
Long otherUserId = otherUserId(chat, currentUserId);
|
||||
ChatDto dto = new ChatDto();
|
||||
dto.setId(chat.getId());
|
||||
dto.setOtherUserId(otherUserId);
|
||||
dto.setPostId(chat.getPostId());
|
||||
|
||||
if (chat.getPostId() != null) {
|
||||
postRepository.findById(chat.getPostId()).ifPresent(post -> {
|
||||
User other = users.get(otherUserId);
|
||||
if (other != null) {
|
||||
dto.setOtherUserName(other.getName() + " " + other.getLastName());
|
||||
dto.setOtherUserAvatar(other.getAvatarUrl());
|
||||
}
|
||||
|
||||
Post post = chat.getPostId() == null ? null : posts.get(chat.getPostId());
|
||||
if (post != null) {
|
||||
ChatPostDto postDto = new ChatPostDto();
|
||||
postDto.setId(post.getId());
|
||||
postDto.setTitle(post.getTitle());
|
||||
postDto.setImages(post.getImages().stream().map(Image::getUrl).toList());
|
||||
dto.setPost(postDto);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// без N+1: берём только последнее сообщение, а не всю историю
|
||||
messageRepository.findFirstByChatIdOrderByCreatedAtDesc(chat.getId())
|
||||
.ifPresent(last -> {
|
||||
dto.setLastMessage(last.getContent());
|
||||
dto.setLastMessageAt(last.getCreatedAt());
|
||||
});
|
||||
Message last = lastMessages.get(chat.getId());
|
||||
if (last != null) {
|
||||
dto.setLastMessage(last.getContent());
|
||||
dto.setLastMessageAt(last.getCreatedAt());
|
||||
}
|
||||
dto.setUnreadCount(unread.getOrDefault(chat.getId(), 0L));
|
||||
return dto;
|
||||
}).toList();
|
||||
}
|
||||
|
||||
dto.setUnreadCount(
|
||||
messageRepository.countByChatIdAndIsReadFalseAndSenderIdNot(chat.getId(), currentUserId)
|
||||
);
|
||||
|
||||
return dto;
|
||||
private static Long otherUserId(Chat chat, Long currentUserId) {
|
||||
return chat.getUserOneId().equals(currentUserId) ? chat.getUserTwoId() : chat.getUserOneId();
|
||||
}
|
||||
|
||||
private MessageDto toMessageDto(Message m) {
|
||||
|
||||
@@ -9,8 +9,8 @@ import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.mapper.PostMapper;
|
||||
import com.krylov.refound.repository.FavoriteRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.util.PostVisibility;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -53,30 +53,32 @@ public class FavoriteService {
|
||||
return repository.findByUser(user)
|
||||
.stream()
|
||||
.map(Favorite::getPost)
|
||||
.filter(post -> isVisibleTo(post, user))
|
||||
.map(mapper::toResponse)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<PostResponse> getAllFavoritesPosts() {
|
||||
User user = userService.getCurrentUser();
|
||||
if (user == null) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Long> favoritePostIds = repository.findPostIdsByUserId(user.getId());
|
||||
if (favoritePostIds.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<Post> posts = postRepository.findAllById(favoritePostIds);
|
||||
|
||||
List<Long> postIds = posts.stream()
|
||||
.map(Post::getId)
|
||||
.toList();
|
||||
|
||||
|
||||
return posts.stream()
|
||||
return postRepository.findAllById(favoritePostIds).stream()
|
||||
.filter(post -> isVisibleTo(post, user))
|
||||
.map(post -> postService.toResponse(post, true))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Пост из избранного мог уйти на повторную модерацию (после правки) или быть
|
||||
* отклонён — такой виден только владельцу, как и в ленте.
|
||||
*/
|
||||
private static boolean isVisibleTo(Post post, User user) {
|
||||
return PostVisibility.FEED_VISIBLE_STATUSES.contains(post.getStatus())
|
||||
|| post.getUser().getId().equals(user.getId());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ package com.krylov.refound.service;
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.dto.DownloadedFile;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.enums.Role;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.util.ImageFormat;
|
||||
import java.io.IOException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
@@ -57,9 +57,9 @@ public class FileStorageService {
|
||||
private static final String ORIGINAL_FILENAME_METADATA_KEY = "original-filename";
|
||||
|
||||
/**
|
||||
* Сколько живёт запись о владельце файла. Совпадает с правилом жизненного цикла бакета
|
||||
* (180 дней), который ставит StorageStructureService: раньше файл исчезнет из MinIO,
|
||||
* чем протухнет отметка о нём.
|
||||
* Сколько живёт запись о владельце файла. Она нужна только для DELETE /api/v1/files
|
||||
* (удалить свежезагруженную, но не прикреплённую картинку); файлы постов и аватаров
|
||||
* удаляются сервисами без этой проверки. Позже удалить файл через API может только админ.
|
||||
*/
|
||||
private static final Duration OWNER_TTL = Duration.ofDays(180);
|
||||
private static final String OWNER_KEY_PREFIX = "files:owner:";
|
||||
@@ -100,8 +100,13 @@ public class FileStorageService {
|
||||
|
||||
try {
|
||||
byte[] content = file.getBytes();
|
||||
String contentType = file.getContentType();
|
||||
String extension = extractExtension(originalFilename);
|
||||
// Тип и расширение берём из содержимого файла, а не из запроса клиента
|
||||
ImageFormat format = ImageFormat.detect(content).orElseThrow(() -> {
|
||||
log.warn("Содержимое файла '{}' не похоже на JPEG/PNG/WebP (заявлен {}).", originalFilename, file.getContentType());
|
||||
return new ApiException(ErrorCode.VALIDATION_ERROR, "Недопустимый тип файла.", HttpStatus.BAD_REQUEST);
|
||||
});
|
||||
String contentType = format.contentType();
|
||||
String extension = format.extension();
|
||||
|
||||
Optional<ImageOptimizer.OptimizedImage> optimized = imageOptimizer.optimize(content, contentType);
|
||||
if (optimized.isPresent()) {
|
||||
@@ -269,7 +274,7 @@ public class FileStorageService {
|
||||
}
|
||||
|
||||
boolean isAdmin = authentication.getAuthorities().stream()
|
||||
.anyMatch(authority -> Role.ADMIN.name().equals(authority.getAuthority()));
|
||||
.anyMatch(authority -> UserService.ADMIN_AUTHORITY.equals(authority.getAuthority()));
|
||||
if (isAdmin) {
|
||||
return;
|
||||
}
|
||||
@@ -400,10 +405,4 @@ public class FileStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
private String extractExtension(String originalFilename) {
|
||||
if (originalFilename != null && originalFilename.contains(".")) {
|
||||
return originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -14,31 +14,74 @@ import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Город и район по координатам (обратное геокодирование, Nominatim/OSM).
|
||||
*
|
||||
* <ul>
|
||||
* <li>Адрес сервиса и User-Agent настраиваются ({@code geocoding.*}): политика
|
||||
* публичного Nominatim требует узнаваемый User-Agent с контактом и не больше
|
||||
* 1 запроса в секунду; для нагрузки лучше свой экземпляр Nominatim.</li>
|
||||
* <li>Результат кэшируется в Redis ({@code geo:<lat>:<lon>}, координаты округлены
|
||||
* до 4 знаков ≈ 11 м) — повторные объявления из того же места не ходят наружу.</li>
|
||||
* <li>Лимит 1 запрос/с общий для всех экземпляров: метка {@code geo:throttle} в Redis.
|
||||
* Если слот за ~1 с не освободился — ApiException 503, и объявление
|
||||
* сохраняется с городом из адреса формы.</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class GeocodingService {
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
// Поля address-объекта Nominatim, которые в сумме считаем "городом" (в порядке приоритета)
|
||||
private static final List<String> CITY_FIELDS = List.of("city", "town", "village", "municipality");
|
||||
private static final Duration CACHE_TTL = Duration.ofDays(30);
|
||||
private static final String THROTTLE_KEY = "geo:throttle";
|
||||
private static final int THROTTLE_ATTEMPTS = 5;
|
||||
private static final long THROTTLE_WAIT_MILLIS = 250;
|
||||
/** Колонки posts.city и posts.district. */
|
||||
private static final int CITY_MAX = 100;
|
||||
private static final int DISTRICT_MAX = 500;
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final String baseUrl;
|
||||
private final String userAgent;
|
||||
private final Duration minInterval;
|
||||
|
||||
// HttpClient потокобезопасен и предназначен для переиспользования — не создаём его на каждый запрос
|
||||
private final HttpClient httpClient = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5))
|
||||
.build();
|
||||
|
||||
public GeocodingService(ObjectMapper mapper, StringRedisTemplate redisTemplate,
|
||||
@Value("${geocoding.url:https://nominatim.openstreetmap.org}") String baseUrl,
|
||||
@Value("${geocoding.user-agent:ReFound-backend/1.0}") String userAgent,
|
||||
@Value("${geocoding.min-interval:PT1S}") Duration minInterval) {
|
||||
this.mapper = mapper;
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
|
||||
this.userAgent = userAgent;
|
||||
this.minInterval = minInterval;
|
||||
}
|
||||
|
||||
/**
|
||||
* Определяет город и остальную часть адреса по координатам через Nominatim reverse geocoding.
|
||||
*/
|
||||
public AddressInfo getAddress(String lat, String lon) {
|
||||
String url = "https://nominatim.openstreetmap.org/reverse"
|
||||
String cacheKey = cacheKey(lat, lon);
|
||||
AddressInfo cached = readCache(cacheKey);
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
acquireSlot();
|
||||
String url = baseUrl + "/reverse"
|
||||
+ "?lat=" + encode(lat)
|
||||
+ "&lon=" + encode(lon)
|
||||
+ "&format=jsonv2"
|
||||
@@ -47,7 +90,8 @@ public class GeocodingService {
|
||||
HttpRequest request = HttpRequest.newBuilder()
|
||||
.uri(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(5))
|
||||
.header("User-Agent", "MyApp/1.0")
|
||||
.header("User-Agent", userAgent)
|
||||
.header("Accept-Language", "ru")
|
||||
.GET()
|
||||
.build();
|
||||
|
||||
@@ -67,7 +111,65 @@ public class GeocodingService {
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Запрос к сервису геокодирования прерван.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
|
||||
return toAddressInfo(root);
|
||||
AddressInfo result = toAddressInfo(root);
|
||||
writeCache(cacheKey, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Ждёт свободный слот общего лимита запросов к геокодеру. */
|
||||
private void acquireSlot() {
|
||||
for (int attempt = 0; attempt < THROTTLE_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
Boolean acquired = redisTemplate.opsForValue().setIfAbsent(THROTTLE_KEY, "1", minInterval);
|
||||
if (Boolean.TRUE.equals(acquired)) {
|
||||
return;
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
// Без Redis общий лимит не соблюсти — идём без него, это редкий случай
|
||||
log.debug("Лимит геокодера не проверен: {}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(THROTTLE_WAIT_MILLIS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Сервис геокодирования перегружен.", HttpStatus.SERVICE_UNAVAILABLE);
|
||||
}
|
||||
|
||||
static String cacheKey(String lat, String lon) {
|
||||
return "geo:" + round(lat) + ":" + round(lon);
|
||||
}
|
||||
|
||||
private static String round(String coordinate) {
|
||||
try {
|
||||
return String.format(java.util.Locale.ROOT, "%.4f", Double.parseDouble(coordinate));
|
||||
} catch (NumberFormatException e) {
|
||||
return coordinate;
|
||||
}
|
||||
}
|
||||
|
||||
private AddressInfo readCache(String key) {
|
||||
try {
|
||||
String json = redisTemplate.opsForValue().get(key);
|
||||
return json == null ? null : mapper.readValue(json, AddressInfo.class);
|
||||
} catch (Exception e) {
|
||||
log.debug("Кэш геокодера недоступен: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeCache(String key, AddressInfo info) {
|
||||
if (info.city() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
redisTemplate.opsForValue().set(key, mapper.writeValueAsString(info), CACHE_TTL);
|
||||
} catch (Exception e) {
|
||||
log.debug("Не удалось сохранить результат геокодера: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private AddressInfo toAddressInfo(JsonNode root) {
|
||||
@@ -82,7 +184,11 @@ public class GeocodingService {
|
||||
|
||||
String district = buildDistrict(displayName, city);
|
||||
|
||||
return new AddressInfo(city, district);
|
||||
return new AddressInfo(truncate(city, CITY_MAX), truncate(district, DISTRICT_MAX));
|
||||
}
|
||||
|
||||
private static String truncate(String value, int max) {
|
||||
return value == null || value.length() <= max ? value : value.substring(0, max);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.repository.ImageRepository;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
|
||||
/**
|
||||
* Ночная чистка «сирот» в бакете картинок: файлов, на которые не ссылаются ни
|
||||
* images.url, ни users.avatar_url. Они появляются, когда фото загружено через
|
||||
* POST /api/v1/files и не прикреплено к объявлению, или когда запрос упал между
|
||||
* загрузкой и сохранением.
|
||||
*
|
||||
* <p>Удаляются только файлы старше {@code storage.orphan-cleanup.min-age}
|
||||
* (по умолчанию сутки) — свежая загрузка может ещё ждать сохранения формы. За
|
||||
* прогон удаляется не больше {@code max-deletes} файлов. Бакет версионируемый:
|
||||
* удалённое ещё 30 дней можно восстановить (StorageStructureService).
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class OrphanFileCleanupService {
|
||||
|
||||
private final S3Client s3Client;
|
||||
private final MinioProperties properties;
|
||||
private final ImageRepository imageRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final FileStorageService fileStorageService;
|
||||
private final boolean enabled;
|
||||
private final Duration minAge;
|
||||
private final int maxDeletes;
|
||||
|
||||
public OrphanFileCleanupService(S3Client s3Client, MinioProperties properties, ImageRepository imageRepository,
|
||||
UserRepository userRepository, FileStorageService fileStorageService,
|
||||
@Value("${storage.orphan-cleanup.enabled:true}") boolean enabled,
|
||||
@Value("${storage.orphan-cleanup.min-age:PT24H}") Duration minAge,
|
||||
@Value("${storage.orphan-cleanup.max-deletes:5000}") int maxDeletes) {
|
||||
this.s3Client = s3Client;
|
||||
this.properties = properties;
|
||||
this.imageRepository = imageRepository;
|
||||
this.userRepository = userRepository;
|
||||
this.fileStorageService = fileStorageService;
|
||||
this.enabled = enabled;
|
||||
this.minAge = minAge;
|
||||
this.maxDeletes = maxDeletes;
|
||||
}
|
||||
|
||||
@Scheduled(cron = "${storage.orphan-cleanup.cron:0 30 3 * * *}")
|
||||
@SchedulerLock(name = "cleanupOrphanFiles", lockAtMostFor = "PT1H", lockAtLeastFor = "PT1M")
|
||||
public void cleanupOrphanFiles() {
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
// Ссылки читаются до листинга: файл, прикреплённый во время прогона, моложе minAge
|
||||
Set<String> referenced = referencedKeys();
|
||||
Instant olderThan = Instant.now().minus(minAge);
|
||||
|
||||
int deleted = 0;
|
||||
int scanned = 0;
|
||||
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket(properties.bucket()).build();
|
||||
for (S3Object object : s3Client.listObjectsV2Paginator(request).contents()) {
|
||||
scanned++;
|
||||
if (object.lastModified() == null || object.lastModified().isAfter(olderThan)
|
||||
|| referenced.contains(object.key())) {
|
||||
continue;
|
||||
}
|
||||
if (deleted >= maxDeletes) {
|
||||
log.warn("Чистка файлов: достигнут предел {} удалений за прогон, остальное — в следующий раз", maxDeletes);
|
||||
break;
|
||||
}
|
||||
try {
|
||||
fileStorageService.deleteFile(object.key());
|
||||
deleted++;
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Чистка файлов: не удалось удалить {}: {}", object.key(), e.getMessage());
|
||||
}
|
||||
}
|
||||
log.info("Чистка файлов-сирот: просмотрено {}, удалено {}", scanned, deleted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ключи, на которые ссылается БД. Значения приводятся к ключу объекта: в старых
|
||||
* записях может лежать полный URL или путь вида /bucket/key — такие файлы тоже
|
||||
* считаются используемыми.
|
||||
*/
|
||||
Set<String> referencedKeys() {
|
||||
Set<String> keys = new HashSet<>();
|
||||
Stream.concat(imageRepository.findAllUrls().stream(), userRepository.findAllAvatarUrls().stream())
|
||||
.map(this::toKey)
|
||||
.forEach(keys::add);
|
||||
return keys;
|
||||
}
|
||||
|
||||
String toKey(String value) {
|
||||
String key = value;
|
||||
int query = key.indexOf('?');
|
||||
if (query >= 0) {
|
||||
key = key.substring(0, query);
|
||||
}
|
||||
String bucketPart = "/" + properties.bucket() + "/";
|
||||
int bucketIndex = key.indexOf(bucketPart);
|
||||
if (bucketIndex >= 0) {
|
||||
key = key.substring(bucketIndex + bucketPart.length());
|
||||
} else if (key.startsWith("/api/v1/files/")) {
|
||||
key = key.substring("/api/v1/files/".length());
|
||||
}
|
||||
return key.startsWith("/") ? key.substring(1) : key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.FavoriteRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.service.redis.PostCacheService;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
/**
|
||||
* Удаление объявлений — одно для владельца, администратора и ночной чистки.
|
||||
*
|
||||
* <p>На posts ссылаются favorites (внешний ключ без ON DELETE CASCADE) и chats.post_id
|
||||
* (без внешнего ключа). Раньше пользовательское удаление не чистило избранное и падало
|
||||
* с 500, если пост кто-то добавил в избранное.
|
||||
*
|
||||
* <p>Файлы в MinIO удаляются только после коммита: если транзакция откатится,
|
||||
* объявление останется с целыми картинками, а не со ссылками на удалённые файлы.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class PostDeletionService {
|
||||
|
||||
private final PostRepository postRepository;
|
||||
private final FavoriteRepository favoriteRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final FileStorageService fileStorageService;
|
||||
private final PostCacheService postCacheService;
|
||||
|
||||
@Transactional
|
||||
public void delete(List<Post> posts) {
|
||||
if (posts.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> fileKeys = posts.stream()
|
||||
.flatMap(post -> post.getImages().stream())
|
||||
.map(Image::getUrl)
|
||||
.toList();
|
||||
List<Long> postIds = posts.stream().map(Post::getId).toList();
|
||||
|
||||
favoriteRepository.deleteByPostIn(posts);
|
||||
// Переписка остаётся, просто без ссылки на объявление
|
||||
chatRepository.clearPostReferences(postIds);
|
||||
postRepository.deleteAll(posts);
|
||||
|
||||
deleteFilesAfterCommit(fileKeys);
|
||||
postCacheService.invalidatePosts();
|
||||
log.info("Удалено объявлений: {}, файлов к удалению: {}", posts.size(), fileKeys.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Удаляет файлы из хранилища после коммита текущей транзакции (или сразу, если её нет).
|
||||
* Ошибки хранилища не роняют операцию: файл останется мусором, это лишь warn в логе.
|
||||
*/
|
||||
public void deleteFilesAfterCommit(Collection<String> fileKeys) {
|
||||
if (fileKeys.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<String> keys = List.copyOf(fileKeys);
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
keys.forEach(PostDeletionService.this::deleteFileQuietly);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
keys.forEach(this::deleteFileQuietly);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteFileQuietly(String objectKey) {
|
||||
try {
|
||||
fileStorageService.deleteFile(objectKey);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,82 +1,162 @@
|
||||
package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.ai.exception.AiBadRequestException;
|
||||
import com.krylov.refound.ai.exception.ContentBlockedException;
|
||||
import com.krylov.refound.ai.facade.ContentModerationFacade;
|
||||
import com.krylov.refound.dto.DownloadedFile;
|
||||
import com.krylov.refound.entity.Image;
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.service.redis.MapCacheService;
|
||||
import com.krylov.refound.service.redis.PostCacheService;
|
||||
import com.krylov.refound.util.ByteArrayMultipartFile;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import java.util.Objects;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
/**
|
||||
* Вынесено из SchedulerService отдельным бином специально: вызов moderateOne(post)
|
||||
* из цикла в том же классе был бы self-invocation и обходил бы Spring-прокси,
|
||||
* из-за чего @Transactional на методе не действовал бы во время выполнения
|
||||
* (post.getImages() как раз требует активной транзакции — это ленивая коллекция).
|
||||
* Модерация одного поста. Вынесено из SchedulerService отдельным бином, чтобы
|
||||
* транзакции работали через Spring-прокси.
|
||||
*
|
||||
* <p>Пост проверяется в три шага: короткая транзакция читает снимок поста
|
||||
* (текст и ключи картинок), затем без транзакции скачиваются картинки и идёт
|
||||
* вызов AI (с ретраями это десятки секунд — держать всё это время соединение
|
||||
* с БД незачем), и в конце новая транзакция ставит статус. Статус ставится,
|
||||
* только если пост всё ещё на модерации и не менялся с момента снимка: иначе
|
||||
* правка, сделанная во время проверки, стала бы ACTIVE без модерации.
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class PostModerationExecutorService {
|
||||
|
||||
private final PostRepository postRepository;
|
||||
private final ContentModerationFacade contentModerationFacade;
|
||||
private final FileStorageService fileStorageService;
|
||||
private final PostCacheService postCacheService;
|
||||
private final MapCacheService mapCacheService;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
|
||||
public PostModerationExecutorService(PostRepository postRepository,
|
||||
ContentModerationFacade contentModerationFacade, FileStorageService fileStorageService,
|
||||
PostCacheService postCacheService, PlatformTransactionManager transactionManager) {
|
||||
this.postRepository = postRepository;
|
||||
this.contentModerationFacade = contentModerationFacade;
|
||||
this.fileStorageService = fileStorageService;
|
||||
this.postCacheService = postCacheService;
|
||||
this.transactionTemplate = new TransactionTemplate(transactionManager);
|
||||
}
|
||||
|
||||
/** Что именно проверяла модерация. */
|
||||
record Snapshot(Long postId, String title, String description, List<String> imageKeys) {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void moderateOne(Long postId) {
|
||||
Post post = postRepository.findById(postId).orElse(null);
|
||||
if (post == null) {
|
||||
log.warn("Пост {} не найден на момент модерации, пропускаем", postId);
|
||||
Snapshot snapshot = transactionTemplate.execute(status -> loadSnapshot(postId));
|
||||
if (snapshot == null) {
|
||||
log.debug("Пост {} уже не на модерации или удалён, пропускаем", postId);
|
||||
return;
|
||||
}
|
||||
|
||||
PostStatus verdict = moderate(snapshot);
|
||||
if (verdict == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Boolean applied = transactionTemplate.execute(status -> applyVerdict(snapshot, verdict));
|
||||
if (Boolean.TRUE.equals(applied) && verdict == PostStatus.ACTIVE) {
|
||||
// Пост впервые становится виден публике — и в ленте, и на карте
|
||||
postCacheService.invalidatePosts();
|
||||
}
|
||||
}
|
||||
|
||||
private Snapshot loadSnapshot(Long postId) {
|
||||
Post post = postRepository.findById(postId).orElse(null);
|
||||
if (post == null || post.getStatus() != PostStatus.MODERATION) {
|
||||
return null;
|
||||
}
|
||||
return new Snapshot(post.getId(), post.getTitle(), post.getDescription(), imageKeys(post));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ACTIVE или REJECTED; null — решения нет (AI или хранилище недоступны),
|
||||
* пост остаётся на модерации и проверяется при следующем запуске
|
||||
*/
|
||||
PostStatus moderate(Snapshot snapshot) {
|
||||
Long postId = snapshot.postId();
|
||||
try {
|
||||
List<MultipartFile> images = post.getImages().stream()
|
||||
.map(Image::getUrl)
|
||||
List<MultipartFile> images = snapshot.imageKeys().stream()
|
||||
.map(fileStorageService::downloadFileRaw)
|
||||
.map(this::toMultipartFile)
|
||||
.toList();
|
||||
|
||||
Boolean approved = contentModerationFacade.moderate(post.getTitle(), post.getDescription(), images);
|
||||
|
||||
Boolean approved = contentModerationFacade.moderate(snapshot.title(), snapshot.description(), images);
|
||||
if (approved == null) {
|
||||
log.warn("Пост {} не отмодерирован из-за недоступности AI, статус не меняем", post.getId());
|
||||
return;
|
||||
log.warn("Пост {} не отмодерирован из-за недоступности AI, статус не меняем", postId);
|
||||
return null;
|
||||
}
|
||||
return approved ? PostStatus.ACTIVE : PostStatus.REJECTED;
|
||||
|
||||
if (!approved) {
|
||||
postRepository.updateStatus(postId, PostStatus.REJECTED);
|
||||
log.info("Пост {} отклонён модерацией.", post.getId());
|
||||
return;
|
||||
} catch (ContentBlockedException e) {
|
||||
log.info("Пост {} отклонён модерацией: {} {}", postId, e.getReason(), e.getDetectedLabels());
|
||||
return PostStatus.REJECTED;
|
||||
} catch (ApiException e) {
|
||||
if (e.getStatus() == HttpStatus.NOT_FOUND) {
|
||||
// Картинки поста нет в хранилище — проверить его целиком уже не получится
|
||||
log.warn("Пост {}: файл не найден в хранилище, отклоняем: {}", postId, e.getMessage());
|
||||
return PostStatus.REJECTED;
|
||||
}
|
||||
|
||||
postRepository.updateStatus(postId, PostStatus.ACTIVE);
|
||||
log.info("Пост {} прошёл модерацию.", post.getId());
|
||||
|
||||
// Пост впервые становится виден публике — и в ленте, и на карте.
|
||||
// Инвалидируем оба кэша, иначе одобренный пост висит до TTL (2 минуты)
|
||||
postCacheService.invalidatePosts();
|
||||
mapCacheService.clearMapMarkersCache();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.warn("Пост {} не прошёл модерацию: {}", post.getId(), e.getMessage());
|
||||
postRepository.updateStatus(postId, PostStatus.REJECTED);
|
||||
log.warn("Пост {}: хранилище недоступно, повторим позже: {}", postId, e.getMessage());
|
||||
return null;
|
||||
} catch (RuntimeException e) {
|
||||
if (hasCause(e, AiBadRequestException.class)) {
|
||||
// 4xx от AI-сервиса: контент он не принимает (формат, размер) — повтор не поможет
|
||||
log.warn("Пост {}: AI-сервис отверг запрос, отклоняем: {}", postId, e.getMessage());
|
||||
return PostStatus.REJECTED;
|
||||
}
|
||||
log.warn("Пост {} не отмодерирован, повторим позже: {}", postId, e.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Boolean applyVerdict(Snapshot snapshot, PostStatus verdict) {
|
||||
Post post = postRepository.findById(snapshot.postId()).orElse(null);
|
||||
if (post == null || post.getStatus() != PostStatus.MODERATION) {
|
||||
log.info("Пост {} удалён или сменил статус во время модерации, вердикт {} не применяем",
|
||||
snapshot.postId(), verdict);
|
||||
return false;
|
||||
}
|
||||
if (!Objects.equals(post.getTitle(), snapshot.title())
|
||||
|| !Objects.equals(post.getDescription(), snapshot.description())
|
||||
|| !new HashSet<>(imageKeys(post)).equals(new HashSet<>(snapshot.imageKeys()))) {
|
||||
log.info("Пост {} изменён во время модерации, проверим новую версию при следующем запуске",
|
||||
snapshot.postId());
|
||||
return false;
|
||||
}
|
||||
post.setStatus(verdict);
|
||||
log.info("Пост {} {}", snapshot.postId(), verdict == PostStatus.ACTIVE ? "прошёл модерацию" : "отклонён модерацией");
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<String> imageKeys(Post post) {
|
||||
return post.getImages().stream().map(Image::getUrl).toList();
|
||||
}
|
||||
|
||||
private static boolean hasCause(Throwable e, Class<? extends Throwable> type) {
|
||||
for (Throwable t = e; t != null; t = t.getCause()) {
|
||||
if (type.isInstance(t)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private MultipartFile toMultipartFile(DownloadedFile file) {
|
||||
return new ByteArrayMultipartFile("images", file.originalFilename(), file.contentType(), file.content());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,9 +20,9 @@ import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.search.PostFeedFilter;
|
||||
import com.krylov.refound.search.PostSearchService;
|
||||
import com.krylov.refound.search.SearchSuggestService;
|
||||
import com.krylov.refound.service.redis.MapCacheService;
|
||||
import com.krylov.refound.service.redis.PostCacheKeyGenerator;
|
||||
import com.krylov.refound.service.redis.PostCacheService;
|
||||
import com.krylov.refound.util.PostFieldLimits;
|
||||
import com.krylov.refound.util.PostSpecification;
|
||||
import com.krylov.refound.util.PostVisibility;
|
||||
import com.krylov.refound.util.TimeZoneContext;
|
||||
@@ -37,10 +37,12 @@ import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -67,39 +69,46 @@ public class PostService {
|
||||
private final ObjectMapper objectMapper;
|
||||
private final PostCacheService postCacheService;
|
||||
private final PostCacheKeyGenerator postCacheKeyGenerator;
|
||||
private final MapCacheService mapCacheService;
|
||||
private final PostDeletionService postDeletionService;
|
||||
private final TransactionTemplate transactionTemplate;
|
||||
private final PostSearchService postSearchService;
|
||||
private final SearchSuggestService searchSuggestService;
|
||||
|
||||
@Transactional
|
||||
/**
|
||||
* Создание объявления. Сетевые вызовы — геокодер и загрузка фото в MinIO — идут
|
||||
* до транзакции: соединение с БД не держится, пока ждём внешние сервисы.
|
||||
* Если транзакция не прошла, загруженные файлы удаляются.
|
||||
*/
|
||||
public PostRequest create(PostRequest request, List<MultipartFile> images) {
|
||||
|
||||
User currentUser = userService.getCurrentUser();
|
||||
PostFieldLimits.validate(request.getTitle(), request.getAddress(), request.getPhone(), request.getRewardText());
|
||||
|
||||
Post post = mapper.toEntity(request);
|
||||
post.setCreatedAt(TimeZoneContext.now());
|
||||
post.setStatus(PostStatus.MODERATION);
|
||||
post.setUser(currentUser);
|
||||
post.setIsReward(request.getReward());
|
||||
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
|
||||
post.setAddress(normalizeAddress(request.getAddress()));
|
||||
if (request.getLatitude() == null || request.getLongitude() == null) {
|
||||
post.setCity(request.getAddress());
|
||||
} else {
|
||||
AddressInfo address = geocodingService.getAddress(request.getLatitude().toString(), request.getLongitude().toString());
|
||||
post.setCity(address.city());
|
||||
post.setDistrict(address.district());
|
||||
AddressInfo location = geocode(request.getLatitude(), request.getLongitude());
|
||||
List<String> imageKeys = uploadImages(images);
|
||||
|
||||
try {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
Post post = mapper.toEntity(request);
|
||||
post.setCreatedAt(TimeZoneContext.now());
|
||||
post.setStatus(PostStatus.MODERATION);
|
||||
post.setUser(currentUser);
|
||||
post.setIsReward(request.getReward());
|
||||
// Адрес из формы сохраняем как есть; геокодер заполняет только city/district
|
||||
post.setAddress(normalizeAddress(request.getAddress()));
|
||||
applyLocation(post, location, request.getAddress());
|
||||
|
||||
postRepository.save(post);
|
||||
attachImages(post, imageKeys);
|
||||
log.info("Создан пост id={} пользователем userId={}, изображений={}", post.getId(), currentUser.getId(),
|
||||
imageKeys.size());
|
||||
|
||||
statisticsService.incrementCreated();
|
||||
postCacheService.invalidatePosts();
|
||||
});
|
||||
} catch (RuntimeException e) {
|
||||
postDeletionService.deleteFilesAfterCommit(imageKeys);
|
||||
throw e;
|
||||
}
|
||||
|
||||
postRepository.save(post);
|
||||
log.info("Создан пост id={} пользователем userId={}, статус={}", post.getId(), currentUser.getId(), post.getStatus());
|
||||
|
||||
int uploaded = attachImages(post, images);
|
||||
log.info("К посту id={} прикреплено {} изображений", post.getId(), uploaded);
|
||||
|
||||
statisticsService.incrementCreated();
|
||||
postCacheService.invalidatePosts();
|
||||
mapCacheService.clearMapMarkersCache();
|
||||
return request;
|
||||
}
|
||||
|
||||
@@ -202,12 +211,9 @@ public class PostService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Удобный overload для контроллера, принимающего multipart-поля по отдельности.
|
||||
* @Transactional стоит и здесь, и на основном update() — раньше этот метод вызывал
|
||||
* update(id, request, images, existingUrls) через this, что было self-invocation
|
||||
* и обходило Spring-прокси: @Transactional на вызываемом методе не срабатывал.
|
||||
* Правка объявления владельцем; multipart-поля приходят по отдельности.
|
||||
* Как и при создании, геокодер и загрузка фото выполняются до транзакции.
|
||||
*/
|
||||
@Transactional
|
||||
public PostResponse update(Long id, String type, String title, String address, Double latitude,
|
||||
Double longitude, String description, String category, String phone, Boolean reward,
|
||||
String rewardText, List<MultipartFile> images, String existingImagesJson) {
|
||||
@@ -223,14 +229,25 @@ public class PostService {
|
||||
request.setAddress(address);
|
||||
request.setReward(reward);
|
||||
request.setRewardText(rewardText);
|
||||
PostFieldLimits.validate(title, address, phone, rewardText);
|
||||
|
||||
List<String> existingUrls = parseExistingImages(existingImagesJson);
|
||||
|
||||
return doUpdate(id, request, images, existingUrls);
|
||||
// Проверка владельца — до обращения к внешним сервисам и загрузки файлов
|
||||
findOwnedPost(id);
|
||||
AddressInfo location = geocode(latitude, longitude);
|
||||
List<String> imageKeys = uploadImages(images);
|
||||
|
||||
try {
|
||||
return transactionTemplate.execute(status -> doUpdate(id, request, imageKeys, existingUrls, location));
|
||||
} catch (RuntimeException e) {
|
||||
postDeletionService.deleteFilesAfterCommit(imageKeys);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private PostResponse doUpdate(Long id, PostRequest request, List<MultipartFile> images, List<String> existingUrls) {
|
||||
// Проверка владельца выполняется до любых изменений и загрузки файлов
|
||||
private PostResponse doUpdate(Long id, PostRequest request, List<String> imageKeys, List<String> existingUrls,
|
||||
AddressInfo location) {
|
||||
Post post = findOwnedPost(id);
|
||||
|
||||
post.setStatus(PostStatus.MODERATION);
|
||||
@@ -248,14 +265,8 @@ public class PostService {
|
||||
if (request.getLatitude() != null && request.getLongitude() != null) {
|
||||
post.setLatitude(request.getLatitude());
|
||||
post.setLongitude(request.getLongitude());
|
||||
AddressInfo address = geocodingService.getAddress(
|
||||
request.getLatitude().toString(), request.getLongitude().toString());
|
||||
|
||||
post.setCity(address.city());
|
||||
post.setDistrict(address.district());
|
||||
} else {
|
||||
post.setCity(request.getAddress());
|
||||
}
|
||||
applyLocation(post, location, request.getAddress());
|
||||
|
||||
List<String> keepUrls = existingUrls != null ? existingUrls : List.of();
|
||||
|
||||
@@ -265,28 +276,20 @@ public class PostService {
|
||||
|
||||
removeImages(post, toRemove);
|
||||
|
||||
int uploaded = attachImages(post, images);
|
||||
int uploaded = attachImages(post, imageKeys);
|
||||
|
||||
Post updated = postRepository.save(post);
|
||||
log.info("Обновлён пост id={}: удалено изображений={}, добавлено={}, статус={}", id, toRemove.size(), uploaded, updated.getStatus());
|
||||
postCacheService.invalidatePosts();
|
||||
mapCacheService.clearMapMarkersCache();
|
||||
log.info("redis cache invalidated in update");
|
||||
return mapper.toResponse(updated);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void delete(Long id) {
|
||||
Post post = findOwnedPost(id);
|
||||
|
||||
// Без этого файлы останутся в MinIO мусором после удаления объявления
|
||||
post.getImages().forEach(img -> deleteFileQuietly(img.getUrl()));
|
||||
|
||||
postRepository.delete(post);
|
||||
// Вместе с постом чистит избранное, ссылки из чатов и файлы в MinIO
|
||||
postDeletionService.delete(List.of(post));
|
||||
log.info("Удалён пост id={}, изображений={}", id, post.getImages().size());
|
||||
postCacheService.invalidatePosts();
|
||||
mapCacheService.clearMapMarkersCache();
|
||||
log.info("redis cache invalidated in delete");
|
||||
}
|
||||
|
||||
@Transactional
|
||||
@@ -311,8 +314,6 @@ public class PostService {
|
||||
Post updated = postRepository.save(post);
|
||||
log.info("Статус поста id={} изменён: {} -> {}", id, previousStatus, newStatus);
|
||||
postCacheService.invalidatePosts();
|
||||
mapCacheService.clearMapMarkersCache();
|
||||
log.info("redis cache invalidated in update status");
|
||||
return mapper.toResponse(updated);
|
||||
}
|
||||
|
||||
@@ -383,44 +384,68 @@ public class PostService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Загружает файлы в MinIO и привязывает их к посту. Возвращает количество загруженных файлов.
|
||||
* Загружает фото в MinIO (вне транзакции). Если какое-то не загрузилось,
|
||||
* уже загруженные удаляются, и ошибка пробрасывается.
|
||||
*/
|
||||
private int attachImages(Post post, List<MultipartFile> images) {
|
||||
private List<String> uploadImages(List<MultipartFile> images) {
|
||||
if (images == null || images.isEmpty()) {
|
||||
return 0;
|
||||
return List.of();
|
||||
}
|
||||
|
||||
int count = 0;
|
||||
for (MultipartFile image : images) {
|
||||
if (image == null || image.isEmpty()) {
|
||||
continue;
|
||||
List<String> keys = new ArrayList<>();
|
||||
try {
|
||||
for (MultipartFile image : images) {
|
||||
if (image != null && !image.isEmpty()) {
|
||||
keys.add(fileStorageService.uploadFile(image));
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
postDeletionService.deleteFilesAfterCommit(keys);
|
||||
throw e;
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
String objectKey = fileStorageService.uploadFile(image);
|
||||
|
||||
/** Привязывает загруженные файлы к посту. Возвращает их количество. */
|
||||
private int attachImages(Post post, List<String> imageKeys) {
|
||||
for (String objectKey : imageKeys) {
|
||||
Image img = new Image();
|
||||
img.setUrl(objectKey); // храним ключ MinIO, а не путь на диске
|
||||
img.setPost(post);
|
||||
imageRepository.save(img);
|
||||
post.getImages().add(img);
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
return imageKeys.size();
|
||||
}
|
||||
|
||||
private void removeImages(Post post, List<Image> toRemove) {
|
||||
toRemove.forEach(img -> deleteFileQuietly(img.getUrl()));
|
||||
post.getImages().removeAll(toRemove);
|
||||
postDeletionService.deleteFilesAfterCommit(toRemove.stream().map(Image::getUrl).toList());
|
||||
}
|
||||
|
||||
private void deleteFileQuietly(String objectKey) {
|
||||
try {
|
||||
fileStorageService.deleteFile(objectKey);
|
||||
} catch (Exception e) {
|
||||
// Не блокируем основную операцию из-за мусора в хранилище — это некритично,
|
||||
// но стоит завести алерт на такие warn-логи, если их станет много.
|
||||
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
|
||||
/**
|
||||
* Город и район по координатам. Геокодер (Nominatim) — внешний сервис: если он
|
||||
* недоступен, объявление всё равно сохраняется, а городом становится адрес из
|
||||
* формы (applyLocation). Раньше недоступность Nominatim не давала создать объявление.
|
||||
*/
|
||||
private AddressInfo geocode(Double latitude, Double longitude) {
|
||||
if (latitude == null || longitude == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return geocodingService.getAddress(latitude.toString(), longitude.toString());
|
||||
} catch (ApiException e) {
|
||||
log.warn("Геокодинг недоступен, город берём из адреса: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void applyLocation(Post post, AddressInfo location, String address) {
|
||||
if (location != null && StringUtils.hasText(location.city())) {
|
||||
post.setCity(location.city());
|
||||
post.setDistrict(location.district());
|
||||
return;
|
||||
}
|
||||
post.setCity(PostFieldLimits.cityFromAddress(address));
|
||||
}
|
||||
|
||||
public PostResponse toResponse(Post post, boolean includeUserRole) {
|
||||
|
||||
@@ -9,6 +9,14 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* Refresh-токены. Клиент получает строку вида {@code <tokenId>.<jwt>}: JWT
|
||||
* проверяется по подписи, а tokenId — ключ записи {@code refresh_token:<tokenId>}
|
||||
* в Redis со значением login и TTL, равным сроку жизни токена. Запись в Redis
|
||||
* делает токен отзываемым (logout, ротация при refresh).
|
||||
*
|
||||
* <p>Сами токены в лог не пишем: по ним можно войти от имени пользователя.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@@ -18,80 +26,60 @@ public class RefreshTokenService {
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final JwtService jwtService;
|
||||
|
||||
/**
|
||||
* Создаёт refresh-токен, сохраняет его в Redis с TTL и привязкой к логину.
|
||||
* В качестве ключа используем не сам JWT, а отдельный UUID —
|
||||
* так тело токена не обязано быть валидным JWT для проверки существования в Redis,
|
||||
* упрощает revoke без необходимости парсить токен.
|
||||
*/
|
||||
/** Создаёт refresh-токен и сохраняет его в Redis с TTL и привязкой к логину. */
|
||||
public String issue(String login) {
|
||||
String tokenId = UUID.randomUUID().toString();
|
||||
String refreshJwt = jwtService.generateRefreshToken(login);
|
||||
log.info("Saving refresh token: key={}, login={}",
|
||||
KEY_PREFIX + tokenId,
|
||||
login);
|
||||
redisTemplate.opsForValue().set(
|
||||
KEY_PREFIX + tokenId,
|
||||
login,
|
||||
Duration.ofMillis(jwtService.getRefreshExpirationMillis())
|
||||
);
|
||||
|
||||
// Кодируем tokenId в сам JWT через отдельный claim, чтобы при refresh
|
||||
// можно было найти запись в Redis по этому id, а не по всему телу токена
|
||||
log.debug("Refresh token issued for login={}", login);
|
||||
return tokenId + "." + refreshJwt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет refresh-токен: валиден ли JWT и существует ли запись в Redis.
|
||||
* Возвращает login, если всё ок, иначе — пусто.
|
||||
* Проверяет refresh-токен и сразу отзывает его (одноразовый токен для ротации).
|
||||
* Запись в Redis удаляется атомарно (GETDEL), поэтому два параллельных
|
||||
* /auth/refresh с одним токеном не получат две новые пары.
|
||||
*
|
||||
* @return login владельца или пусто, если токен невалиден, отозван или истёк
|
||||
*/
|
||||
public java.util.Optional<String> validateAndGetLogin(String rawToken) {
|
||||
log.info("Incoming refresh token = {}", rawToken);
|
||||
|
||||
String[] parts = rawToken.split("\\.", 2);
|
||||
|
||||
log.info("parts.length = {}", parts.length);
|
||||
|
||||
|
||||
if (parts.length == 2) {
|
||||
log.info("tokenId={}", parts[0]);
|
||||
log.info("jwt={}", parts[1]);
|
||||
}
|
||||
|
||||
if (parts.length != 2) {
|
||||
public Optional<String> consume(String rawToken) {
|
||||
TokenParts parts = TokenParts.parse(rawToken);
|
||||
if (parts == null || !jwtService.isRefreshTokenValid(parts.jwt())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
boolean valid = jwtService.isTokenValid(parts[1]);
|
||||
log.info("jwt valid={}", valid);
|
||||
|
||||
if (!valid) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
|
||||
String tokenId = parts[0];
|
||||
String jwt = parts[1];
|
||||
|
||||
if (!jwtService.isTokenValid(jwt)) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
|
||||
String storedLogin = redisTemplate.opsForValue().get(KEY_PREFIX + tokenId);
|
||||
String jwtLogin = jwtService.extractLogin(jwt);
|
||||
String storedLogin = redisTemplate.opsForValue().getAndDelete(KEY_PREFIX + parts.tokenId());
|
||||
String jwtLogin = jwtService.extractLogin(parts.jwt());
|
||||
|
||||
if (storedLogin == null || !storedLogin.equals(jwtLogin)) {
|
||||
return java.util.Optional.empty();
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return java.util.Optional.of(jwtLogin);
|
||||
return Optional.of(jwtLogin);
|
||||
}
|
||||
|
||||
/** Ротация: старый токен удаляется, выпускается новый. */
|
||||
/** Отзыв токена при logout. Невалидный или пустой токен просто игнорируется. */
|
||||
public void revoke(String rawToken) {
|
||||
String[] parts = rawToken.split("\\.", 2);
|
||||
if (parts.length == 2) {
|
||||
redisTemplate.delete(KEY_PREFIX + parts[0]);
|
||||
TokenParts parts = TokenParts.parse(rawToken);
|
||||
if (parts != null) {
|
||||
redisTemplate.delete(KEY_PREFIX + parts.tokenId());
|
||||
}
|
||||
}
|
||||
|
||||
private record TokenParts(String tokenId, String jwt) {
|
||||
|
||||
static TokenParts parse(String rawToken) {
|
||||
if (rawToken == null || rawToken.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String[] parts = rawToken.split("\\.", 2);
|
||||
if (parts.length != 2 || parts[0].isBlank() || parts[1].isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return new TokenParts(parts[0], parts[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,19 @@ package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.repository.FavoriteRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.service.redis.MapCacheService;
|
||||
import com.krylov.refound.service.redis.PostCacheService;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
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;
|
||||
@@ -19,69 +24,57 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
@RequiredArgsConstructor
|
||||
public class SchedulerService {
|
||||
|
||||
/** Меньше lockAtMostFor задачи модерации (10 минут). */
|
||||
private static final Duration MODERATION_RUN_BUDGET = Duration.ofMinutes(8);
|
||||
|
||||
private final PostRepository postRepository;
|
||||
private final FavoriteRepository favoriteRepository;
|
||||
private final PostModerationExecutorService postModerationExecutorService;
|
||||
private final PostCacheService postCacheService;
|
||||
private final MapCacheService mapCacheService;
|
||||
private final PostDeletionService postDeletionService;
|
||||
|
||||
/**
|
||||
* Runs every day at 00:01 to delete:
|
||||
* 1. Posts with CLOSED status
|
||||
* 2. Posts older than 6 months
|
||||
*
|
||||
* Удаление идёт через PostDeletionService: вместе с постами чистятся избранное,
|
||||
* ссылки из чатов и файлы в MinIO (раньше файлы оставались мусором в бакете).
|
||||
*/
|
||||
@Scheduled(cron = "0 1 0 * * ?")
|
||||
@SchedulerLock(name = "deleteExpiredPosts", lockAtMostFor = "PT30M", lockAtLeastFor = "PT1M")
|
||||
@Transactional
|
||||
public void deleteExpiredPosts() {
|
||||
log.info("Starting scheduled cleanup of expired posts...");
|
||||
|
||||
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
|
||||
|
||||
// Find and delete posts with CLOSED status
|
||||
List<Post> closedPosts = postRepository.findByStatus(PostStatus.CLOSED);
|
||||
if (!closedPosts.isEmpty()) {
|
||||
// Delete favorites first to avoid foreign key constraint violation
|
||||
favoriteRepository.deleteByPostIn(closedPosts);
|
||||
log.info("Deleted {} favorites for CLOSED posts", closedPosts.size());
|
||||
|
||||
postRepository.deleteAll(closedPosts);
|
||||
log.info("Deleted {} posts with CLOSED status", closedPosts.size());
|
||||
}
|
||||
|
||||
// Find and delete posts older than 6 months
|
||||
List<Post> oldPosts = postRepository.findByCreatedAtBefore(sixMonthsAgo);
|
||||
if (!oldPosts.isEmpty()) {
|
||||
// Delete favorites first to avoid foreign key constraint violation
|
||||
favoriteRepository.deleteByPostIn(oldPosts);
|
||||
log.info("Deleted {} favorites for old posts", oldPosts.size());
|
||||
|
||||
postRepository.deleteAll(oldPosts);
|
||||
log.info("Deleted {} posts older than 6 months", oldPosts.size());
|
||||
}
|
||||
|
||||
if (!closedPosts.isEmpty() || !oldPosts.isEmpty()) {
|
||||
// Иначе удалённые посты висят в ленте и на карте до TTL кэша
|
||||
postCacheService.invalidatePosts();
|
||||
mapCacheService.clearMapMarkersCache();
|
||||
}
|
||||
|
||||
log.info("Scheduled cleanup completed successfully");
|
||||
LocalDateTime sixMonthsAgo = LocalDateTime.now().minusMonths(6);
|
||||
|
||||
List<Post> closedPosts = postRepository.findByStatus(PostStatus.CLOSED);
|
||||
List<Post> oldPosts = postRepository.findByCreatedAtBefore(sixMonthsAgo);
|
||||
|
||||
// Закрытый пост бывает и старым — удаляем каждый один раз
|
||||
Map<Long, Post> expired = Stream.concat(closedPosts.stream(), oldPosts.stream())
|
||||
.collect(Collectors.toMap(Post::getId, Function.identity(), (a, b) -> a, LinkedHashMap::new));
|
||||
|
||||
postDeletionService.delete(new ArrayList<>(expired.values()));
|
||||
log.info("Scheduled cleanup completed: closed={}, older than 6 months={}, deleted={}",
|
||||
closedPosts.size(), oldPosts.size(), expired.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* Каждые 60 секунд забирает посты, ожидающие модерации, и прогоняет их через
|
||||
* ContentModerationFacade. Изображения к этому моменту уже лежат в MinIO
|
||||
* (залиты синхронно в PostService.create/update) — оригинальные MultipartFile
|
||||
* из запроса уже недоступны (Tomcat удаляет temp-файл сразу после завершения
|
||||
* запроса), поэтому скачиваем их заново и оборачиваем в ByteArrayMultipartFile,
|
||||
* чтобы не менять сигнатуру ContentModerationFacade.
|
||||
* из запроса уже недоступны, поэтому PostModerationExecutorService скачивает их заново.
|
||||
*
|
||||
* Сама обработка одного поста вынесена в отдельный бин PostModerationExecutor —
|
||||
* вызов через него идёт через Spring-прокси, поэтому @Transactional на
|
||||
* moderateOne реально применяется (self-invocation внутри этого класса привёл бы
|
||||
* к тому, что транзакция не открывалась бы вовсе).
|
||||
* При нескольких экземплярах прогон выполняет один (ShedLock), а результат
|
||||
* поста применяется условно (см. PostModerationExecutorService), так что
|
||||
* даже параллельная проверка не испортит статус.
|
||||
*
|
||||
* Сама обработка одного поста вынесена в отдельный бин: ему нужны собственные
|
||||
* короткие транзакции до и после вызова AI, а self-invocation внутри этого
|
||||
* класса обошёл бы Spring-прокси.
|
||||
*/
|
||||
@Scheduled(fixedDelay = 60_000)
|
||||
@SchedulerLock(name = "moderatePendingPosts", lockAtMostFor = "PT10M", lockAtLeastFor = "PT10S")
|
||||
public void moderatePendingPosts() {
|
||||
List<Long> pending = postRepository.findIdsByStatus(PostStatus.MODERATION);
|
||||
if (pending.isEmpty()) {
|
||||
@@ -89,10 +82,19 @@ public class SchedulerService {
|
||||
}
|
||||
|
||||
log.info("На модерации {} постов.", pending.size());
|
||||
long deadline = System.nanoTime() + MODERATION_RUN_BUDGET.toNanos();
|
||||
for (Long postId : pending) {
|
||||
postModerationExecutorService.moderateOne(postId);
|
||||
// Не дольше, чем держится блокировка: иначе другой экземпляр начнёт тот же прогон
|
||||
if (System.nanoTime() > deadline) {
|
||||
log.info("Прогон модерации прерван по времени, остальные посты — в следующем запуске");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
postModerationExecutorService.moderateOne(postId);
|
||||
} catch (RuntimeException e) {
|
||||
// Один сломанный пост не должен останавливать модерацию остальных
|
||||
log.error("Ошибка модерации поста {}", postId, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -2,27 +2,39 @@ package com.krylov.refound.service;
|
||||
|
||||
import com.krylov.refound.entity.Statistics;
|
||||
import com.krylov.refound.repository.StatisticsRepository;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Transactional
|
||||
public class StatisticsService {
|
||||
/** Единственная строка статистики, её создаёт changelog 009. */
|
||||
private static final Long STATISTICS_ID = 1L;
|
||||
|
||||
private final StatisticsRepository repository;
|
||||
|
||||
public void incrementCreated() {
|
||||
Statistics statistics = repository.findById(1L).orElseThrow();
|
||||
statistics.setPostsCreated(statistics.getPostsCreated() + 1);
|
||||
if (repository.incrementCreated(STATISTICS_ID) == 0) {
|
||||
log.warn("Строка statistics id={} не найдена, счётчик созданных не увеличен", STATISTICS_ID);
|
||||
}
|
||||
}
|
||||
|
||||
public void incrementFound() {
|
||||
Statistics statistics = repository.findById(1L).orElseThrow();
|
||||
statistics.setPostsFound(statistics.getPostsFound() + 1);
|
||||
if (repository.incrementFound(STATISTICS_ID) == 0) {
|
||||
log.warn("Строка statistics id={} не найдена, счётчик найденных не увеличен", STATISTICS_ID);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Statistics getStatistics() {
|
||||
return repository.findById(1L).orElseThrow();
|
||||
return repository.findById(STATISTICS_ID)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "Statistics not found", HttpStatus.NOT_FOUND));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,30 +7,40 @@ import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.enums.Role;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.UserRepository;
|
||||
import com.krylov.refound.security.JwtService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class UserService {
|
||||
public static final String ADMIN_AUTHORITY = "ROLE_" + Role.ADMIN.name();
|
||||
|
||||
private final UserRepository repository;
|
||||
private static final int MAX_LOGIN_LENGTH = 255;
|
||||
|
||||
private final FileStorageService fileStorageService;
|
||||
private final JwtService jwtService;
|
||||
private final RefreshTokenService refreshTokenService;
|
||||
|
||||
public User getCurrentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (authentication == null || authentication.getPrincipal() == null) {
|
||||
// Анонимный запрос тоже несёт Authentication (principal "anonymousUser") —
|
||||
// раньше он искался в БД как логин и давал 404 вместо 401
|
||||
if (authentication == null || authentication instanceof AnonymousAuthenticationToken
|
||||
|| !(authentication.getPrincipal() instanceof String login)) {
|
||||
throw new ApiException(ErrorCode.UNAUTHORIZED, "Пользователь не авторизован", HttpStatus.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
String login = (String) authentication.getPrincipal();
|
||||
|
||||
return repository.findByLogin(login)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
|
||||
}
|
||||
@@ -41,8 +51,10 @@ public class UserService {
|
||||
if (authentication == null) {
|
||||
return false;
|
||||
}
|
||||
// JwtAuthenticationFilter кладёт роль с префиксом: "ROLE_ADMIN". Сравнение
|
||||
// с "ADMIN" никогда не срабатывало, и администратор не мог править чужой профиль
|
||||
return authentication.getAuthorities().stream()
|
||||
.anyMatch(authority -> Role.ADMIN.name().equals(authority.getAuthority()));
|
||||
.anyMatch(authority -> ADMIN_AUTHORITY.equals(authority.getAuthority()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,10 +73,31 @@ public class UserService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Профиль пользователя. Email и телефон — личные данные: их видит сам
|
||||
* пользователь и администратор, остальным они не отдаются (контакт для
|
||||
* объявления — телефон в самом объявлении или чат).
|
||||
*/
|
||||
public UserResponseDto getUserById(Long id) {
|
||||
User user = repository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
|
||||
return getUserResponseDto(user);
|
||||
UserResponseDto dto = getUserResponseDto(user);
|
||||
if (!canSeePrivateData(user.getId())) {
|
||||
dto.setEmail(null);
|
||||
dto.setPhone(null);
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
|
||||
private boolean canSeePrivateData(Long userId) {
|
||||
if (isCurrentUserAdmin()) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
return getCurrentUser().getId().equals(userId);
|
||||
} catch (ApiException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public UserResponseDto updateUser(Long id, UserUpdateDto dto, Boolean removeAvatar) {
|
||||
@@ -73,51 +106,66 @@ public class UserService {
|
||||
User user = repository.findById(id)
|
||||
.orElseThrow(() -> new ApiException(ErrorCode.NOT_FOUND, "User not found", HttpStatus.NOT_FOUND));
|
||||
|
||||
if (dto.getLogin() != null && !dto.getLogin().equals(user.getLogin())
|
||||
&& repository.existsByLogin(dto.getLogin())) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Логин уже занят", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
// Правит ли пользователь сам себя (а не админ чужой профиль) — до смены логина
|
||||
boolean selfUpdate = isCurrentUser(user);
|
||||
|
||||
user.setLogin(dto.getLogin());
|
||||
// Логин не прислали — оставляем прежний: null в login ломал вход в аккаунт
|
||||
boolean loginChanged = false;
|
||||
if (StringUtils.hasText(dto.getLogin()) && !dto.getLogin().equals(user.getLogin())) {
|
||||
if (dto.getLogin().length() > MAX_LOGIN_LENGTH) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||
"Логин длиннее " + MAX_LOGIN_LENGTH + " символов", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
if (repository.existsByLogin(dto.getLogin())) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Логин уже занят", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
user.setLogin(dto.getLogin());
|
||||
loginChanged = true;
|
||||
}
|
||||
user.setName(dto.getFirstName());
|
||||
user.setLastName(dto.getLastName());
|
||||
user.setPhone(dto.getPhone());
|
||||
user.setEmail(dto.getEmail());
|
||||
|
||||
MultipartFile avatar = dto.getAvatar();
|
||||
String replacedAvatarKey = null;
|
||||
if (avatar != null && !avatar.isEmpty()) {
|
||||
String oldAvatarKey = user.getAvatarUrl();
|
||||
|
||||
String newAvatarKey = fileStorageService.uploadFile(avatar, "avatars");
|
||||
user.setAvatarUrl(newAvatarKey);
|
||||
|
||||
// подчищаем старый файл, если он был и это реально ключ MinIO
|
||||
if (oldAvatarKey != null && !oldAvatarKey.isBlank() && isMinioKey(oldAvatarKey)) {
|
||||
try {
|
||||
fileStorageService.deleteFile(oldAvatarKey);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить старый аватар из хранилища: {}", oldAvatarKey, e);
|
||||
}
|
||||
}
|
||||
replacedAvatarKey = user.getAvatarUrl();
|
||||
user.setAvatarUrl(fileStorageService.uploadFile(avatar, "avatars"));
|
||||
} else if (Boolean.TRUE.equals(removeAvatar)) {
|
||||
String oldAvatarKey = user.getAvatarUrl();
|
||||
if (oldAvatarKey != null && !oldAvatarKey.isBlank() && isMinioKey(oldAvatarKey)) {
|
||||
try {
|
||||
fileStorageService.deleteFile(oldAvatarKey);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить старый аватар из хранилища: {}", oldAvatarKey, e);
|
||||
}
|
||||
}
|
||||
replacedAvatarKey = user.getAvatarUrl();
|
||||
user.setAvatarUrl(null);
|
||||
}
|
||||
|
||||
repository.save(user);
|
||||
|
||||
// Старый аватар удаляем после сохранения профиля: если сохранение упадёт,
|
||||
// у пользователя не останется ссылки на удалённый файл
|
||||
if (replacedAvatarKey != null && !replacedAvatarKey.isBlank() && isMinioKey(replacedAvatarKey)) {
|
||||
try {
|
||||
fileStorageService.deleteFile(replacedAvatarKey);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить старый аватар из хранилища: {}", replacedAvatarKey, e);
|
||||
}
|
||||
}
|
||||
|
||||
UserResponseDto userResponseDto = getUserResponseDto(user);
|
||||
if (loginChanged && selfUpdate) {
|
||||
// В JWT логин — subject: старые токены после смены логина не находят пользователя.
|
||||
// Отдаём новую пару; старые refresh-токены перестают работать сами (логин в них не совпадёт).
|
||||
userResponseDto.setToken(jwtService.generateAccessToken(user.getLogin(), user.getRole().name()));
|
||||
userResponseDto.setRefreshToken(refreshTokenService.issue(user.getLogin()));
|
||||
}
|
||||
log.info("User updated: {}", userResponseDto.getLogin());
|
||||
return userResponseDto;
|
||||
}
|
||||
|
||||
private boolean isCurrentUser(User user) {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken)
|
||||
&& user.getLogin().equals(authentication.getName());
|
||||
}
|
||||
|
||||
/** Ключ MinIO — относительный (без хоста и без ведущего слеша). */
|
||||
private static boolean isMinioKey(String key) {
|
||||
return !key.startsWith("http://") && !key.startsWith("https://") && !key.startsWith("/") && !key.contains("\\");
|
||||
|
||||
@@ -12,15 +12,14 @@ import com.krylov.refound.enums.PostCategory;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.repository.ChatRepository;
|
||||
import com.krylov.refound.repository.FavoriteRepository;
|
||||
import com.krylov.refound.repository.ImageRepository;
|
||||
import com.krylov.refound.repository.PostRepository;
|
||||
import com.krylov.refound.service.FileStorageService;
|
||||
import com.krylov.refound.service.GeocodingService;
|
||||
import com.krylov.refound.service.PostDeletionService;
|
||||
import com.krylov.refound.service.StatisticsService;
|
||||
import com.krylov.refound.service.redis.MapCacheService;
|
||||
import com.krylov.refound.service.redis.PostCacheService;
|
||||
import com.krylov.refound.util.PostFieldLimits;
|
||||
import com.krylov.refound.util.PostSpecification;
|
||||
import java.util.Arrays;
|
||||
import java.util.EnumSet;
|
||||
@@ -48,7 +47,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
* <li>нет проверки владельца — операции доступны любому ADMIN;</li>
|
||||
* <li>редактирование не меняет статус: перевод в MODERATION убрал бы объявление из ленты до
|
||||
* прохождения AI-модерации, а в REJECTED — скрыл бы навсегда;</li>
|
||||
* <li>удаление чистит ссылки из favorites и chats, потому что каскада в БД нет;</li>
|
||||
* <li>удаление идёт через {@link PostDeletionService}, как и у владельца;</li>
|
||||
* <li>геокодинг при правке best-effort: недоступность Nominatim не должна блокировать
|
||||
* исправление текста объявления.</li>
|
||||
* </ul>
|
||||
@@ -68,12 +67,10 @@ public class AdminPostService {
|
||||
|
||||
private final PostRepository postRepository;
|
||||
private final ImageRepository imageRepository;
|
||||
private final FavoriteRepository favoriteRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final FileStorageService fileStorageService;
|
||||
private final GeocodingService geocodingService;
|
||||
private final PostCacheService postCacheService;
|
||||
private final MapCacheService mapCacheService;
|
||||
private final PostDeletionService postDeletionService;
|
||||
private final StatisticsService statisticsService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@@ -128,6 +125,7 @@ public class AdminPostService {
|
||||
|
||||
Post post = findPost(postId);
|
||||
PostStatus statusBeforeEdit = post.getStatus();
|
||||
PostFieldLimits.validate(title, address, phone, rewardText);
|
||||
|
||||
post.setType(parseTypeOrThrow(type));
|
||||
post.setTitle(title);
|
||||
@@ -147,7 +145,7 @@ public class AdminPostService {
|
||||
post.setLongitude(longitude);
|
||||
resolveLocation(post, latitude, longitude, address);
|
||||
} else if (StringUtils.hasText(address)) {
|
||||
post.setCity(address.trim());
|
||||
post.setCity(PostFieldLimits.cityFromAddress(address));
|
||||
}
|
||||
|
||||
syncImages(post, existingImagesJson, images);
|
||||
@@ -161,17 +159,8 @@ public class AdminPostService {
|
||||
@Transactional
|
||||
public void deletePost(Long postId) {
|
||||
Post post = findPost(postId);
|
||||
|
||||
for (Image image : post.getImages()) {
|
||||
deleteFileQuietly(image.getUrl());
|
||||
}
|
||||
// На posts ссылаются favorites и chats, ON DELETE CASCADE в БД нет:
|
||||
// без явной чистки удаление падало бы на внешнем ключе.
|
||||
favoriteRepository.deleteByPostIn(List.of(post));
|
||||
chatRepository.clearPostReference(postId);
|
||||
|
||||
postRepository.delete(post);
|
||||
invalidateCaches();
|
||||
// Чистит favorites и ссылки из chats (каскада в БД нет), файлы — после коммита
|
||||
postDeletionService.delete(List.of(post));
|
||||
|
||||
log.info("Post {} deleted by admin", postId);
|
||||
}
|
||||
@@ -219,7 +208,7 @@ public class AdminPostService {
|
||||
log.warn("Геокодинг недоступен, город берём из address: postId={}, {}", post.getId(), e.getMessage());
|
||||
}
|
||||
if (StringUtils.hasText(address)) {
|
||||
post.setCity(address.trim());
|
||||
post.setCity(PostFieldLimits.cityFromAddress(address));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,10 +218,8 @@ public class AdminPostService {
|
||||
List<Image> toRemove = post.getImages().stream()
|
||||
.filter(image -> !keepUrls.contains(image.getUrl()))
|
||||
.toList();
|
||||
for (Image image : toRemove) {
|
||||
deleteFileQuietly(image.getUrl());
|
||||
}
|
||||
post.getImages().removeAll(toRemove);
|
||||
postDeletionService.deleteFilesAfterCommit(toRemove.stream().map(Image::getUrl).toList());
|
||||
|
||||
if (newImages == null) {
|
||||
return;
|
||||
@@ -263,15 +250,6 @@ public class AdminPostService {
|
||||
|
||||
private void invalidateCaches() {
|
||||
postCacheService.invalidatePosts();
|
||||
mapCacheService.clearMapMarkersCache();
|
||||
}
|
||||
|
||||
private void deleteFileQuietly(String objectKey) {
|
||||
try {
|
||||
fileStorageService.deleteFile(objectKey);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось удалить файл из хранилища: {}", objectKey, e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Один запрос вместо N+1 при сборке страницы объявлений. */
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -22,12 +23,13 @@ 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();
|
||||
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 +49,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) {
|
||||
@@ -68,6 +83,7 @@ public class AdvertisingAdminService {
|
||||
|
||||
public AdvertisingAdminResponseDto toAdminDto(Advertising advertising) {
|
||||
Advertising saved = advertisingRepository.save(advertising);
|
||||
selectionService.invalidateCache();
|
||||
return mapToAdminDto(saved);
|
||||
}
|
||||
|
||||
@@ -81,10 +97,11 @@ 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());
|
||||
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 jakarta.persistence.EntityNotFoundException;
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private Long extractUserId(Authentication authentication) {
|
||||
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
log.info("extractUserId by login {}", login);
|
||||
return userService.getUserIdByLogin(login);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,68 +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);
|
||||
Long count = redisTemplate.opsForValue().increment(key);
|
||||
if (count == null) {
|
||||
// Redis недоступен — не блокируем показ, решение остаётся за вызывающим кодом
|
||||
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,52 +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 jakarta.persistence.EntityNotFoundException;
|
||||
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);
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private Long extractUserId(Authentication authentication) {
|
||||
if (authentication == null || !authentication.isAuthenticated() || "anonymousUser".equals(authentication.getPrincipal())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String login = authentication.getName();
|
||||
log.info("extractUserId by login {}", login);
|
||||
return userService.getUserIdByLogin(login);
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,21 @@ package com.krylov.refound.service.advertising;
|
||||
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.util.ImageFormat;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.InputStreamResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.CacheControl;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpRange;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
@@ -41,26 +47,31 @@ public class AdvertisingMediaService {
|
||||
|
||||
private static final long MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10 MB
|
||||
private static final Set<String> ALLOWED_IMAGE_TYPES = Set.of("image/jpeg", "image/png", "image/webp");
|
||||
/** Медиа лежат под UUID-ключами и не меняются — браузер может хранить их долго. */
|
||||
private static final CacheControl MEDIA_CACHE_CONTROL = CacheControl.maxAge(Duration.ofDays(30)).cachePublic();
|
||||
|
||||
/**
|
||||
* Загружает изображение рекламного объявления в ads-media.
|
||||
* Валидация полностью повторяет FileStorageService (10MB, jpeg/png/webp) —
|
||||
* Валидация повторяет FileStorageService (10MB, jpeg/png/webp по сигнатуре файла) —
|
||||
* но целевой бакет другой, поэтому логика не переиспользуется напрямую.
|
||||
*/
|
||||
public String uploadImage(MultipartFile file) {
|
||||
validateImage(file);
|
||||
|
||||
String extension = extractExtension(file.getOriginalFilename());
|
||||
String mediaKey = "images/%s%s".formatted(UUID.randomUUID(), extension);
|
||||
|
||||
try {
|
||||
byte[] content = file.getBytes();
|
||||
// Тип и расширение — по содержимому, а не по имени и Content-Type от клиента
|
||||
ImageFormat format = ImageFormat.detect(content).orElseThrow(() ->
|
||||
new ApiException(ErrorCode.VALIDATION_ERROR, "Недопустимый тип файла.", HttpStatus.BAD_REQUEST));
|
||||
String mediaKey = "images/%s%s".formatted(UUID.randomUUID(), format.extension());
|
||||
|
||||
PutObjectRequest request = PutObjectRequest.builder()
|
||||
.bucket(adsBucket)
|
||||
.key(mediaKey)
|
||||
.contentType(file.getContentType())
|
||||
.contentType(format.contentType())
|
||||
.build();
|
||||
|
||||
s3Client.putObject(request, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
|
||||
s3Client.putObject(request, RequestBody.fromBytes(content));
|
||||
log.info("Ad image uploaded: {}", mediaKey);
|
||||
return mediaKey;
|
||||
|
||||
@@ -93,13 +104,6 @@ public class AdvertisingMediaService {
|
||||
}
|
||||
}
|
||||
|
||||
private String extractExtension(String originalFilename) {
|
||||
if (originalFilename != null && originalFilename.contains(".")) {
|
||||
return originalFilename.substring(originalFilename.lastIndexOf("."));
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* URL, по которому фронтенд сможет получить медиа на любом устройстве.
|
||||
* Presigned URL непригоден: он подписан под host MinIO (localhost:9010),
|
||||
@@ -112,35 +116,84 @@ public class AdvertisingMediaService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Отдаёт медиа рекламы из ads-media потоком/байтами через бэкенд —
|
||||
* без presigned URL, доступно с любого устройства.
|
||||
* Отдаёт медиа рекламы из ads-media потоком через бэкенд — без presigned URL,
|
||||
* доступно с любого устройства.
|
||||
*
|
||||
* <p>Файл не читается в память целиком (ролик в десятки мегабайт на каждый
|
||||
* запрос быстро съедал heap) и поддерживается заголовок Range: без ответа 206
|
||||
* Safari на iOS не воспроизводит видео, а перемотка в остальных браузерах
|
||||
* перекачивает файл с начала. Ключи медиа неизменяемы (UUID), поэтому ответ
|
||||
* можно кэшировать.
|
||||
*/
|
||||
public ResponseEntity<byte[]> downloadMedia(String mediaKey) {
|
||||
public ResponseEntity<Resource> downloadMedia(String mediaKey, String rangeHeader) {
|
||||
try {
|
||||
HeadObjectResponse head = s3Client.headObject(
|
||||
HeadObjectRequest.builder().bucket(adsBucket).key(mediaKey).build());
|
||||
|
||||
String contentType = head.contentType() != null
|
||||
? head.contentType()
|
||||
: MediaType.APPLICATION_OCTET_STREAM_VALUE;
|
||||
|
||||
byte[] content = s3Client.getObjectAsBytes(
|
||||
GetObjectRequest.builder().bucket(adsBucket).key(mediaKey).build()).asByteArray();
|
||||
|
||||
long length = head.contentLength();
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline");
|
||||
headers.add(HttpHeaders.ACCEPT_RANGES, "bytes");
|
||||
headers.setCacheControl(MEDIA_CACHE_CONTROL);
|
||||
headers.setContentType(head.contentType() != null
|
||||
? MediaType.parseMediaType(head.contentType())
|
||||
: MediaType.APPLICATION_OCTET_STREAM);
|
||||
|
||||
log.info("downloadMedia: served mediaKey={}, contentType={}, {} bytes", mediaKey, contentType, content.length);
|
||||
return ResponseEntity.ok()
|
||||
.headers(headers)
|
||||
.contentType(MediaType.parseMediaType(contentType))
|
||||
.body(content);
|
||||
GetObjectRequest.Builder get = GetObjectRequest.builder().bucket(adsBucket).key(mediaKey);
|
||||
HttpStatus status = HttpStatus.OK;
|
||||
long bodyLength = length;
|
||||
|
||||
if (rangeHeader != null && !rangeHeader.isBlank()) {
|
||||
long[] range = resolveRange(rangeHeader, length);
|
||||
if (range == null) {
|
||||
headers.set(HttpHeaders.CONTENT_RANGE, "bytes */" + length);
|
||||
return ResponseEntity.status(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE).headers(headers).build();
|
||||
}
|
||||
get.range("bytes=" + range[0] + "-" + range[1]);
|
||||
headers.set(HttpHeaders.CONTENT_RANGE, "bytes " + range[0] + "-" + range[1] + "/" + length);
|
||||
status = HttpStatus.PARTIAL_CONTENT;
|
||||
bodyLength = range[1] - range[0] + 1;
|
||||
}
|
||||
|
||||
headers.setContentLength(bodyLength);
|
||||
InputStream body = s3Client.getObject(get.build());
|
||||
log.debug("downloadMedia: mediaKey={}, status={}, {} bytes", mediaKey, status.value(), bodyLength);
|
||||
return ResponseEntity.status(status).headers(headers).body(new InputStreamResource(body));
|
||||
} catch (NoSuchKeyException e) {
|
||||
log.warn("Ad media not found: {}", mediaKey);
|
||||
throw new ApiException(ErrorCode.NOT_FOUND, "Медиа не найдено.", HttpStatus.NOT_FOUND);
|
||||
} catch (S3Exception | SdkClientException e) {
|
||||
} catch (S3Exception e) {
|
||||
if (e.statusCode() == HttpStatus.NOT_FOUND.value()) {
|
||||
// HEAD отсутствующего ключа приходит как S3Exception 404, а не NoSuchKeyException
|
||||
log.warn("Ad media not found: {}", mediaKey);
|
||||
throw new ApiException(ErrorCode.NOT_FOUND, "Медиа не найдено.", HttpStatus.NOT_FOUND);
|
||||
}
|
||||
log.error("Failed to download ad media mediaKey={}", mediaKey, e);
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при скачивании медиа.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
} catch (SdkClientException e) {
|
||||
log.error("Failed to download ad media mediaKey={}", mediaKey, e);
|
||||
throw new ApiException(ErrorCode.INTERNAL_ERROR, "Ошибка при скачивании медиа.", HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Первый диапазон из заголовка Range как [start, end] включительно или null,
|
||||
* если диапазон некорректен или вне файла. Несколько диапазонов сразу
|
||||
* (multipart/byteranges) плееры не запрашивают.
|
||||
*/
|
||||
static long[] resolveRange(String rangeHeader, long length) {
|
||||
try {
|
||||
List<HttpRange> ranges = HttpRange.parseRanges(rangeHeader);
|
||||
if (ranges.isEmpty() || length <= 0) {
|
||||
return null;
|
||||
}
|
||||
HttpRange range = ranges.get(0);
|
||||
long start = range.getRangeStart(length);
|
||||
long end = range.getRangeEnd(length);
|
||||
// HttpRange не проверяет, что начало диапазона внутри файла
|
||||
return start < length && start <= end ? new long[] {start, end} : null;
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +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
|
||||
@@ -24,74 +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);
|
||||
String resolvedSessionId = sessionId != null ? sessionId : request.getSession(true).getId();
|
||||
// Приложение 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);
|
||||
|
||||
if (!frequencyService.isSessionCooldownPassed(resolvedSessionId)) {
|
||||
log.debug("Session cooldown not passed for sessionId={}", resolvedSessionId);
|
||||
try {
|
||||
return select(subject);
|
||||
} catch (DataAccessException e) {
|
||||
// Лимиты живут в Redis. Без него рекламу не показываем (204), а не роняем
|
||||
// запрос с 500 и не показываем её без ограничений.
|
||||
log.warn("Redis недоступен, реклама не выбрана: {}", e.getMessage());
|
||||
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.info("advertising candidate {}", candidate);
|
||||
return Optional.of(toDto(candidate));
|
||||
}
|
||||
log.info("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.info("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();
|
||||
log.info("extractUserId by login {}", login);
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import com.krylov.refound.dto.advertising.TranscodingStatusDto;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.AdvertisingRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -13,7 +13,9 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class AdvertisingStatusService {
|
||||
|
||||
private final AdvertisingRepository advertisingRepository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
private final AdvertisingSelectionService selectionService;
|
||||
// Транскодинг идёт в любом экземпляре, а админ может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
|
||||
@Transactional
|
||||
public void markReady(Long advertisingId, String mediaKey) {
|
||||
@@ -21,6 +23,7 @@ public class AdvertisingStatusService {
|
||||
ad.setMediaKey(mediaKey);
|
||||
ad.setTranscodingStatus(TranscodingStatus.READY);
|
||||
});
|
||||
selectionService.invalidateCache();
|
||||
notifyStatusChange(advertisingId, TranscodingStatus.READY);
|
||||
}
|
||||
|
||||
@@ -32,7 +35,7 @@ public class AdvertisingStatusService {
|
||||
}
|
||||
|
||||
private void notifyStatusChange(Long advertisingId, TranscodingStatus status) {
|
||||
messagingTemplate.convertAndSend(
|
||||
messaging.convertAndSend(
|
||||
"/topic/ads/%d/status".formatted(advertisingId),
|
||||
new TranscodingStatusDto(advertisingId, status));
|
||||
}
|
||||
|
||||
@@ -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,7 +22,9 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class CampaignService {
|
||||
|
||||
private final CampaignRepository campaignRepository;
|
||||
private final AdvertisingSelectionService selectionService;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public List<CampaignResponseDto> getCampaign() {
|
||||
return campaignRepository.findAllByOrderByCreatedAtDesc()
|
||||
.stream()
|
||||
@@ -34,6 +36,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());
|
||||
@@ -64,6 +67,7 @@ public class CampaignService {
|
||||
campaign.setDailyImpressionCap(request.dailyImpressionCap());
|
||||
|
||||
log.info("campaign {} updated", campaignId);
|
||||
selectionService.invalidateCache();
|
||||
return toDto(campaign);
|
||||
}
|
||||
|
||||
@@ -81,7 +85,10 @@ public class CampaignService {
|
||||
);
|
||||
}
|
||||
|
||||
campaignRepository.updateStatus(campaignId, request.status());
|
||||
// Раньше статус менялся 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;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package com.krylov.refound.service.advertising;
|
||||
import com.krylov.refound.enums.advertising.TranscodingStatus;
|
||||
import com.krylov.refound.repository.advertising.FullscreenAdvertisingRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import com.krylov.refound.config.ClusterMessaging;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -12,7 +12,8 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public class FullscreenAdStatusService {
|
||||
|
||||
private final FullscreenAdvertisingRepository repository;
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
// Транскодинг идёт в любом экземпляре, а админ может быть подключён к другому
|
||||
private final ClusterMessaging messaging;
|
||||
|
||||
@Transactional
|
||||
public void markReady(Long id, String mediaKey) {
|
||||
@@ -30,7 +31,7 @@ public class FullscreenAdStatusService {
|
||||
}
|
||||
|
||||
private void notifyStatusChange(Long id, TranscodingStatus status) {
|
||||
messagingTemplate.convertAndSend(
|
||||
messaging.convertAndSend(
|
||||
"/topic/fullscreen-ads/%d/status".formatted(id),
|
||||
new com.krylov.refound.dto.advertising.TranscodingStatusDto(id, status));
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package com.krylov.refound.service.redis;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class MapCacheKeyGenerator {
|
||||
|
||||
private static final String PREFIX = "maps:markers:v";
|
||||
|
||||
private final MapCacheService mapCacheService;
|
||||
|
||||
public String markersKey(String type, String category) {
|
||||
// Версия читается здесь, то есть в самом начале getMapMarkers, до запроса в БД
|
||||
String version = mapCacheService.currentMapVersion();
|
||||
|
||||
return PREFIX + version
|
||||
+ ":type=" + RedisCacheKeyUtil.sha256(RedisCacheKeyUtil.normalize(type))
|
||||
+ ":category=" + RedisCacheKeyUtil.sha256(RedisCacheKeyUtil.normalize(category));
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package com.krylov.refound.service.redis;
|
||||
|
||||
import com.krylov.refound.dto.CachedMapMarkers;
|
||||
import java.time.Duration;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MapCacheService {
|
||||
|
||||
// Ключ версии без TTL. Redis должен работать с maxmemory-policy volatile-lru,
|
||||
// чтобы этот ключ не вытеснялся
|
||||
private static final String VERSION_KEY = "maps:markers:version";
|
||||
|
||||
private final RedisTemplate<String, CachedMapMarkers> redisTemplate;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
|
||||
public CachedMapMarkers getMarkers(String key) {
|
||||
try {
|
||||
return redisTemplate.opsForValue().get(key);
|
||||
} catch (Exception e) {
|
||||
// Кэш best-effort: любая проблема (Redis недоступен, битый JSON) = miss
|
||||
log.warn("Не удалось прочитать метки карты из Redis, key={}: {}", key, e.toString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void saveMarkers(String key, CachedMapMarkers value, Duration ttl) {
|
||||
try {
|
||||
redisTemplate.opsForValue().set(key, value, ttl);
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось сохранить метки карты в Redis, key={}: {}", key, e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/** Текущая версия меток карты. Должна читаться ДО запроса в БД. */
|
||||
public String currentMapVersion() {
|
||||
try {
|
||||
String version = stringRedisTemplate.opsForValue().get(VERSION_KEY);
|
||||
return version == null ? "0" : version;
|
||||
} catch (Exception e) {
|
||||
log.warn("Не удалось прочитать версию map cache: {}", e.toString());
|
||||
return "0";
|
||||
}
|
||||
}
|
||||
|
||||
/** Инвалидирует метки карты после коммита текущей транзакции (или сразу, если транзакции нет). */
|
||||
public void clearMapMarkersCache() {
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
bumpMapVersion();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
bumpMapVersion();
|
||||
}
|
||||
}
|
||||
|
||||
private void bumpMapVersion() {
|
||||
try {
|
||||
Long version = stringRedisTemplate.opsForValue().increment(VERSION_KEY);
|
||||
log.info("Map cache инвалидирован, версия={}", version);
|
||||
} catch (Exception e) {
|
||||
// Устаревшие записи доживут до TTL (2 минуты)
|
||||
log.warn("Не удалось инвалидировать map cache: {}", e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
29
src/main/java/com/krylov/refound/util/AdSessionId.java
Normal file
29
src/main/java/com/krylov/refound/util/AdSessionId.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package com.krylov.refound.util;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Идентификатор рекламной сессии от клиента (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 static final Pattern SAFE = Pattern.compile("[^A-Za-z0-9._:-]");
|
||||
|
||||
private AdSessionId() {
|
||||
}
|
||||
|
||||
public static String normalize(String sessionId) {
|
||||
if (sessionId == null || sessionId.isBlank()) {
|
||||
return UNKNOWN;
|
||||
}
|
||||
// Идентификатор попадает в ключи Redis и в токен показа (разделитель '|'):
|
||||
// оставляем только безопасные символы
|
||||
String cleaned = SAFE.matcher(sessionId.trim()).replaceAll("_");
|
||||
return cleaned.length() > MAX_LENGTH ? cleaned.substring(0, MAX_LENGTH) : cleaned;
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
61
src/main/java/com/krylov/refound/util/ImageFormat.java
Normal file
61
src/main/java/com/krylov/refound/util/ImageFormat.java
Normal file
@@ -0,0 +1,61 @@
|
||||
package com.krylov.refound.util;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Форматы картинок, которые принимает сервис. Формат определяется по первым
|
||||
* байтам файла (сигнатуре), а не по Content-Type и имени файла от клиента:
|
||||
* иначе под видом image/png можно загрузить HTML или SVG с расширением .html,
|
||||
* и он отдавался бы из хранилища с этим ключом.
|
||||
*/
|
||||
public enum ImageFormat {
|
||||
JPEG("image/jpeg", ".jpg"),
|
||||
PNG("image/png", ".png"),
|
||||
WEBP("image/webp", ".webp");
|
||||
|
||||
private final String contentType;
|
||||
private final String extension;
|
||||
|
||||
ImageFormat(String contentType, String extension) {
|
||||
this.contentType = contentType;
|
||||
this.extension = extension;
|
||||
}
|
||||
|
||||
public String contentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
/** Расширение для ключа объекта в хранилище (с точкой). */
|
||||
public String extension() {
|
||||
return extension;
|
||||
}
|
||||
|
||||
/** Формат по сигнатуре файла или пусто, если это не JPEG/PNG/WebP. */
|
||||
public static Optional<ImageFormat> detect(byte[] content) {
|
||||
if (content == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (startsWith(content, 0, 0xFF, 0xD8, 0xFF)) {
|
||||
return Optional.of(JPEG);
|
||||
}
|
||||
if (startsWith(content, 0, 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A)) {
|
||||
return Optional.of(PNG);
|
||||
}
|
||||
if (startsWith(content, 0, 'R', 'I', 'F', 'F') && startsWith(content, 8, 'W', 'E', 'B', 'P')) {
|
||||
return Optional.of(WEBP);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private static boolean startsWith(byte[] content, int offset, int... signature) {
|
||||
if (content.length < offset + signature.length) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < signature.length; i++) {
|
||||
if ((content[offset + i] & 0xFF) != signature[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
52
src/main/java/com/krylov/refound/util/PostFieldLimits.java
Normal file
52
src/main/java/com/krylov/refound/util/PostFieldLimits.java
Normal file
@@ -0,0 +1,52 @@
|
||||
package com.krylov.refound.util;
|
||||
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Длины текстовых полей объявления по схеме БД (changelog 002, 003, 015, 018).
|
||||
* Без проверки слишком длинное значение доходило до INSERT и давало 500.
|
||||
*/
|
||||
public final class PostFieldLimits {
|
||||
|
||||
public static final int TITLE = 255;
|
||||
public static final int PHONE = 255;
|
||||
public static final int REWARD_TEXT = 255;
|
||||
public static final int ADDRESS = 500;
|
||||
public static final int CITY = 100;
|
||||
|
||||
private PostFieldLimits() {
|
||||
}
|
||||
|
||||
/** Проверяет поля формы объявления; 400 VALIDATION_ERROR при нарушении. */
|
||||
public static void validate(String title, String address, String phone, String rewardText) {
|
||||
if (!StringUtils.hasText(title)) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Заголовок обязателен", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
checkLength("Заголовок", title, TITLE);
|
||||
checkLength("Адрес", address, ADDRESS);
|
||||
checkLength("Телефон", phone, PHONE);
|
||||
checkLength("Текст вознаграждения", rewardText, REWARD_TEXT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Город, когда геокодер его не дал: берётся адрес из формы, обрезанный под
|
||||
* колонку city (адрес допускает 500 символов, город — 100).
|
||||
*/
|
||||
public static String cityFromAddress(String address) {
|
||||
if (!StringUtils.hasText(address)) {
|
||||
return null;
|
||||
}
|
||||
String city = address.trim();
|
||||
return city.length() > CITY ? city.substring(0, CITY) : city;
|
||||
}
|
||||
|
||||
private static void checkLength(String field, String value, int max) {
|
||||
if (value != null && value.length() > max) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR,
|
||||
field + " длиннее " + max + " символов", HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.krylov.refound.util;
|
||||
import com.krylov.refound.security.JwtService;
|
||||
import com.krylov.refound.service.ChatService;
|
||||
import com.krylov.refound.service.UserService;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -13,6 +14,9 @@ import org.springframework.messaging.MessagingException;
|
||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
import org.springframework.messaging.support.ChannelInterceptor;
|
||||
import org.springframework.messaging.support.MessageHeaderAccessor;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@@ -28,6 +32,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
private static final Pattern UNREAD_TOPIC = Pattern.compile("^/topic/user/(\\d+)/unread$");
|
||||
/** /user/{userId}/queue/** — личная очередь одного пользователя */
|
||||
private static final Pattern USER_QUEUE = Pattern.compile("^/user/[^/]+/queue/.+$");
|
||||
/**
|
||||
* /user/queue/** — личная очередь текущей сессии. Spring сам подставляет в неё
|
||||
* Principal сессии, поэтому чужую очередь так получить нельзя. Именно сюда
|
||||
* доходят сообщения convertAndSendToUser (например, /user/queue/errors).
|
||||
*/
|
||||
private static final Pattern OWN_USER_QUEUE = Pattern.compile("^/user/queue/.+$");
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final UserService userService;
|
||||
@@ -45,7 +55,12 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
@Override
|
||||
public Message<?> preSend(Message<?> message, MessageChannel channel) {
|
||||
|
||||
StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
|
||||
// Изменяемый accessor самого сообщения: setUser на копии из wrap() не доходил бы
|
||||
// до STOMP-сессии
|
||||
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
|
||||
if (accessor == null) {
|
||||
accessor = StompHeaderAccessor.wrap(message);
|
||||
}
|
||||
|
||||
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
|
||||
handleConnect(accessor);
|
||||
@@ -65,7 +80,7 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
|
||||
String token = authorization.substring(7);
|
||||
|
||||
if (!jwtService.isTokenValid(token)) {
|
||||
if (!jwtService.isAccessTokenValid(token)) {
|
||||
throw new IllegalArgumentException("Invalid JWT token");
|
||||
}
|
||||
|
||||
@@ -81,6 +96,10 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
|
||||
accessor.getSessionAttributes().put(USER_ID_ATTR, userId);
|
||||
accessor.getSessionAttributes().put(ROLE_ATTR, role);
|
||||
// Principal с именем = userId: без него convertAndSendToUser(userId, ...) никого
|
||||
// не находил, и ошибки отправки сообщений (/queue/errors) терялись
|
||||
accessor.setUser(new UsernamePasswordAuthenticationToken(userId.toString(), null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_" + role))));
|
||||
|
||||
// Таймзону присылает клиент на CONNECT; применяется при сохранении Message
|
||||
String timezone = accessor.getFirstNativeHeader(TimeZoneContext.WS_HEADER);
|
||||
@@ -123,6 +142,10 @@ public class WsStompInterceptor implements ChannelInterceptor {
|
||||
return;
|
||||
}
|
||||
|
||||
if (OWN_USER_QUEUE.matcher(destination).matches()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (USER_QUEUE.matcher(destination).matches()) {
|
||||
String[] parts = destination.split("/");
|
||||
if (parts.length < 3 || !userId.toString().equals(parts[2])) {
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
ffmpeg:
|
||||
binary-path: ${FFMPEG_PATH:C:\ffmpeg\ffmpeg-9.0.2-essentials_build\bin\ffmpeg.exe}
|
||||
|
||||
server:
|
||||
# За обратным прокси (nginx, балансировщик) IP клиента и схема берутся из
|
||||
# X-Forwarded-*: без этого лимиты считали бы все запросы с адреса прокси.
|
||||
# Tomcat доверяет заголовкам только от внутренних адресов (10/8, 172.16/12, 192.168/16, 127/8).
|
||||
forward-headers-strategy: ${FORWARD_HEADERS_STRATEGY:native}
|
||||
shutdown: graceful
|
||||
|
||||
spring:
|
||||
lifecycle:
|
||||
timeout-per-shutdown-phase: 20s
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 10MB
|
||||
@@ -19,10 +28,17 @@ spring:
|
||||
# из-за чего базы расходились. Для разработки можно переопределить
|
||||
# переменной окружения JPA_DDL_AUTO=update.
|
||||
ddl-auto: ${JPA_DDL_AUTO:validate}
|
||||
show-sql: ${JPA_SHOW_SQL:true}
|
||||
show-sql: ${JPA_SHOW_SQL:false}
|
||||
# Ленту и избранное собирают вне транзакции (PostResponse читает images и user лениво),
|
||||
# поэтому сессия Hibernate должна жить до конца запроса. Значение по умолчанию,
|
||||
# указано явно, чтобы убрать предупреждение при старте.
|
||||
open-in-view: true
|
||||
properties:
|
||||
hibernate:
|
||||
format_sql: true
|
||||
# Ленивые коллекции (images) и связи (user) грузятся пачками по id,
|
||||
# а не по одному запросу на пост — убирает N+1 в ленте, избранном и чистке
|
||||
default_batch_fetch_size: 50
|
||||
|
||||
data:
|
||||
redis:
|
||||
@@ -57,6 +73,21 @@ ai:
|
||||
delay: 500
|
||||
multiplier: 2
|
||||
|
||||
# Ночная чистка файлов без ссылок в бакете картинок (OrphanFileCleanupService)
|
||||
storage:
|
||||
orphan-cleanup:
|
||||
enabled: ${STORAGE_ORPHAN_CLEANUP_ENABLED:true}
|
||||
cron: "0 30 3 * * *"
|
||||
min-age: PT24H # моложе — не трогаем: загрузка может ещё ждать сохранения формы
|
||||
max-deletes: 5000 # предел удалений за прогон
|
||||
|
||||
# Обратное геокодирование (GeocodingService): публичный Nominatim требует
|
||||
# User-Agent с контактом и не больше 1 запроса/с; для нагрузки — свой экземпляр
|
||||
geocoding:
|
||||
url: ${GEOCODING_URL:https://nominatim.openstreetmap.org}
|
||||
user-agent: ${GEOCODING_USER_AGENT:ReFound-backend/1.0}
|
||||
min-interval: ${GEOCODING_MIN_INTERVAL:PT1S}
|
||||
|
||||
# Поиск по объявлениям (PostSearchService)
|
||||
search:
|
||||
typo-threshold: 0.3
|
||||
@@ -89,4 +120,88 @@ jwt:
|
||||
|
||||
app:
|
||||
cors:
|
||||
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000}
|
||||
allowed-origins: ${CORS_ALLOWED_ORIGINS:http://localhost:5173,http://localhost:3000,http://192.168.1.76:3000}
|
||||
|
||||
websocket:
|
||||
# Рассылка STOMP-сообщений во все экземпляры через Redis pub/sub (ClusterMessaging)
|
||||
cluster-broadcast: ${WS_CLUSTER_BROADCAST:true}
|
||||
|
||||
# Health-пробы для оркестратора/балансировщика: /actuator/health/liveness и /readiness
|
||||
# открыты без токена (SecurityConfig), подробности состояния наружу не отдаются
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: health
|
||||
endpoint:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
show-details: never
|
||||
|
||||
# Лимиты запросов по IP (RateLimitFilter), счётчики в Redis — общие для всех экземпляров
|
||||
rate-limit:
|
||||
enabled: ${RATE_LIMIT_ENABLED:true}
|
||||
login:
|
||||
max-failures: 10 # неудачных входов в один аккаунт
|
||||
window: PT15M
|
||||
rules:
|
||||
- name: auth-login
|
||||
method: POST
|
||||
paths: [/api/v1/auth/login]
|
||||
limit: 20
|
||||
window: PT1M
|
||||
- name: auth-register
|
||||
method: POST
|
||||
paths: [/api/v1/auth/register]
|
||||
limit: 10
|
||||
window: PT1H
|
||||
- name: auth-refresh
|
||||
method: POST
|
||||
paths: [/api/v1/auth/refresh]
|
||||
limit: 60
|
||||
window: PT1M
|
||||
- name: auth-check-login
|
||||
method: GET
|
||||
paths: [/api/v1/auth/check-login]
|
||||
limit: 60
|
||||
window: PT1M
|
||||
- name: post-create
|
||||
method: POST
|
||||
paths: [/api/v1/posts]
|
||||
limit: 20
|
||||
window: PT1H
|
||||
- name: file-upload
|
||||
method: POST
|
||||
paths: [/api/v1/files]
|
||||
limit: 60
|
||||
window: PT1H
|
||||
- name: chat-start
|
||||
method: POST
|
||||
paths: [/api/v1/chats/with/**]
|
||||
limit: 30
|
||||
window: PT1M
|
||||
- name: ads-next
|
||||
method: GET
|
||||
paths: [/api/ads/next, /api/fullscreen-ad]
|
||||
limit: 120
|
||||
window: PT1M
|
||||
- name: ads-tracking
|
||||
method: POST
|
||||
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 }
|
||||
|
||||
@@ -2,10 +2,26 @@ package com.krylov.refound;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
/**
|
||||
* Поднимает весь контекст на настоящем PostgreSQL (Testcontainers, нужен Docker):
|
||||
* проверяет, что Liquibase-миграции применяются, а сущности совпадают со схемой
|
||||
* (ddl-auto: validate). Секреты — в профиле test (application-test.yaml).
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
@Testcontainers
|
||||
class ReFoundApplicationTests {
|
||||
|
||||
@Container
|
||||
@ServiceConnection
|
||||
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15");
|
||||
|
||||
@Test
|
||||
void contextLoads() {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package com.krylov.refound.config;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
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.data.redis.connection.DefaultMessage;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
|
||||
class ClusterMessagingTest {
|
||||
|
||||
private SimpMessagingTemplate messagingTemplate;
|
||||
private StringRedisTemplate redis;
|
||||
private ObjectMapper objectMapper;
|
||||
private ClusterMessaging messaging;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
messagingTemplate = mock(SimpMessagingTemplate.class);
|
||||
redis = mock(StringRedisTemplate.class);
|
||||
objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
messaging = new ClusterMessaging(messagingTemplate, redis, objectMapper, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void publishesToRedisInsteadOfLocalBroker() {
|
||||
messaging.convertAndSend("/topic/chat/7", Map.of("content", "привет"));
|
||||
|
||||
ArgumentCaptor<String> json = ArgumentCaptor.forClass(String.class);
|
||||
verify(redis).convertAndSend(eq(ClusterMessaging.CHANNEL), json.capture());
|
||||
assertThat(json.getValue()).contains("/topic/chat/7").contains("привет");
|
||||
verify(messagingTemplate, never()).convertAndSend(anyString(), any(Object.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageFromRedisGoesToLocalBroker() throws Exception {
|
||||
String json = objectMapper.writeValueAsString(Map.of("destination", "/topic/chat/7",
|
||||
"payload", Map.of("content", "привет")));
|
||||
|
||||
messaging.onMessage(new DefaultMessage(ClusterMessaging.CHANNEL.getBytes(), json.getBytes(StandardCharsets.UTF_8)),
|
||||
null);
|
||||
|
||||
ArgumentCaptor<Object> payload = ArgumentCaptor.forClass(Object.class);
|
||||
verify(messagingTemplate).convertAndSend(eq("/topic/chat/7"), payload.capture());
|
||||
assertThat(((JsonNode) payload.getValue()).get("content").asText()).isEqualTo("привет");
|
||||
}
|
||||
|
||||
@Test
|
||||
void redisOutageFallsBackToLocalDelivery() {
|
||||
doThrow(new RedisConnectionFailureException("down")).when(redis).convertAndSend(anyString(), anyString());
|
||||
Map<String, String> payload = Map.of("content", "привет");
|
||||
|
||||
messaging.convertAndSend("/topic/chat/7", payload);
|
||||
|
||||
verify(messagingTemplate).convertAndSend("/topic/chat/7", (Object) payload);
|
||||
}
|
||||
|
||||
@Test
|
||||
void garbageFromRedisIsIgnored() {
|
||||
messaging.onMessage(new DefaultMessage(new byte[0], "not json".getBytes(StandardCharsets.UTF_8)), null);
|
||||
|
||||
verify(messagingTemplate, never()).convertAndSend(anyString(), any(Object.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.krylov.refound.exception;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import jakarta.persistence.EntityNotFoundException;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** Раньше все эти исключения перехватывал handleUnknown и отвечал 500. */
|
||||
class GlobalExceptionHandlerTest {
|
||||
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(new ThrowingController())
|
||||
.setControllerAdvice(new GlobalExceptionHandler())
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void accessDeniedFromPreAuthorizeIs403() throws Exception {
|
||||
mvc.perform(get("/denied")).andExpect(status().isForbidden())
|
||||
.andExpect(jsonPath("$.error").value("FORBIDDEN"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void badCredentialsIs401() throws Exception {
|
||||
mvc.perform(get("/bad-credentials")).andExpect(status().isUnauthorized());
|
||||
}
|
||||
|
||||
@Test
|
||||
void entityNotFoundIs404() throws Exception {
|
||||
mvc.perform(get("/missing")).andExpect(status().isNotFound())
|
||||
.andExpect(jsonPath("$.error").value("NOT_FOUND"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingParameterAndWrongTypeAre400() throws Exception {
|
||||
mvc.perform(get("/number")).andExpect(status().isBadRequest());
|
||||
mvc.perform(get("/number").param("value", "abc")).andExpect(status().isBadRequest())
|
||||
.andExpect(jsonPath("$.error").value("VALIDATION_ERROR"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableBodyIs400() throws Exception {
|
||||
mvc.perform(post("/body").contentType(MediaType.APPLICATION_JSON).content("{broken"))
|
||||
.andExpect(status().isBadRequest());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unexpectedErrorIsStill500() throws Exception {
|
||||
mvc.perform(get("/boom")).andExpect(status().isInternalServerError())
|
||||
.andExpect(jsonPath("$.message").value("Internal server error"));
|
||||
}
|
||||
|
||||
@RestController
|
||||
static class ThrowingController {
|
||||
|
||||
@GetMapping("/denied")
|
||||
void denied() {
|
||||
throw new AccessDeniedException("Access Denied");
|
||||
}
|
||||
|
||||
@GetMapping("/bad-credentials")
|
||||
void badCredentials() {
|
||||
throw new BadCredentialsException("Invalid or expired refresh token");
|
||||
}
|
||||
|
||||
@GetMapping("/missing")
|
||||
void missing() {
|
||||
throw new EntityNotFoundException("Campaign not found: 1");
|
||||
}
|
||||
|
||||
@GetMapping("/number")
|
||||
long number(@RequestParam long value) {
|
||||
return value;
|
||||
}
|
||||
|
||||
@PostMapping("/body")
|
||||
void body(@RequestBody Payload payload) {
|
||||
}
|
||||
|
||||
@GetMapping("/boom")
|
||||
void boom() {
|
||||
throw new IllegalStateException("boom");
|
||||
}
|
||||
}
|
||||
|
||||
record Payload(String value) {
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user